text string | size int64 | token_count int64 |
|---|---|---|
/*
* File: BufferedInsert.cpp
* Author: root
*
* Created on October 3, 2012, 2:06 PM
*/
#ifdef _WIN32
#include "stdafx.h"
#endif
#include "BufferedInsert.h"
#include <memory>
namespace util {
BufferedInsert::BufferedInsert(DBase &conn, const char *preface, const char *postface) :
_conn(conn)
, _preface(preface)
, _postface(postface) {
buf_size = BUFFER_SIZE;
count = 0;
_buf.reserve(buf_size * 50);
_buf = preface;
}
BufferedInsert::BufferedInsert(const BufferedInsert& orig):
_conn(orig._conn)
, _preface(orig._preface)
, _postface(orig._postface)
, _buf(orig._buf)
, buf_size(orig.buf_size)
{
}
BufferedInsert::~BufferedInsert(void) {
}
bool BufferedInsert::insertValues(const char *values) {
if (count != 0)
_buf += ", ";
_buf += values;
count++;
if (count > buf_size)
flush();
return true;
}
bool BufferedInsert::insertValues(std::string &values) {
if (count != 0)
_buf += ", ";
_buf += values;
count++;
if (count > buf_size)
flush();
return true;
}
void BufferedInsert::flush() {
if (!_conn.isConnected())
throw DBException("BufferedInsert Flush: Database connection not established.");
if (count == 0)
return;
if (_postface.length() > 0)
_buf += _postface;
std::unique_ptr<util::Query> stmt = _conn.getQueryObj();
*stmt << _buf;
stmt->execUpdate();
_buf.clear();
_buf.reserve(buf_size * 50); // a guess on the size of each value string
_buf = _preface;
count = 0;
}
} // namespace util
| 1,842 | 601 |
#include <iostream>
#include <fstream>
#include <vector>
#include <iomanip>
#include "GostCipher.h"
enum RETURN_CODES {
SUCCESS = 0,
NOT_ENOUGH_ARGS = 1,
TOO_MANY_ARGS = 2,
WRONG_OPERATION = 3,
WRONG_KEY = 4,
FAILED_TO_READ_FILE = 5,
FAILED_TO_WRITE_FILE = 6,
};
std::vector<uint8_t> read_binary_file(const char* input) {
try {
std::ifstream file(input, std::ios::in | std::ios::binary);
file.unsetf(std::ios::skipws);
if (file.is_open()) {
file.seekg(0, std::ios::end);
const auto size = file.tellg();
file.seekg(0, std::ios::beg);
auto data = std::vector<uint8_t>();
data.reserve(size);
data.insert(
data.cbegin(),
std::istream_iterator<uint8_t>(file),
std::istream_iterator<uint8_t>()
);
file.close();
return data;
}
}
catch (const std::exception& ex) {
std::cerr << ex.what() << std::endl;
}
return {};
}
bool write_to_binary_file(const char* filename, const std::vector<uint8_t>& raw) {
std::ofstream file(filename, std::ios::out | std::ios::binary);
if (file.is_open()) {
file.write((const char*)raw.data(), raw.size());
file.flush();
file.close();
return true;
}
return false;
}
int main(int argc, char** argv)
{
switch (argc) {
case 0: case 1: case 2: case 3: case 4:
return RETURN_CODES::NOT_ENOUGH_ARGS;
case 5:
if (strcmp(argv[1], "encrypt") != 0 && strcmp(argv[1], "decrypt") != 0) {
return RETURN_CODES::WRONG_OPERATION;
}
std::cout << "Operation is valid. Loading key file..." << std::endl;
auto key = read_binary_file(argv[2]);
if (key.size() == 0) {
return RETURN_CODES::FAILED_TO_READ_FILE;
}
if (key.size() != 32) {
return RETURN_CODES::WRONG_KEY;
}
std::cout << "Key is fine. Loading input file..." << std::endl;
auto input = read_binary_file(argv[3]);
if (input.size() == 0) {
return RETURN_CODES::FAILED_TO_READ_FILE;
}
const auto block_num = input.size() / 8;
const auto to_add = input.size() % 8;
for (int i = 0; i < to_add; ++i) {
input.push_back(0);
}
std::cout << "Input is loaded. Encrypting..." << std::endl;
auto cipher = GostCipher((const char*)key.data());
if (strcmp(argv[1], "encrypt") == 0) {
for (int i = 0; i < block_num; i += 8) {
cipher.encrypt(input.data());
}
}
else {
for (int i = 0; i < block_num; i += 8) {
cipher.decrypt(input.data());
}
}
if (!write_to_binary_file(argv[4], input)) {
return RETURN_CODES::FAILED_TO_WRITE_FILE;
}
std::cout << "Done!" << std::endl;
return RETURN_CODES::SUCCESS;
}
return RETURN_CODES::TOO_MANY_ARGS;
}
| 3,254 | 1,105 |
#define YGP_DISABLE_BROOM
#define YGP_DISABLE_DEMENTOR
#define YGP_DISABLE_BROWSER
#define YGP_DISABLE_PLAYER
#include"../include/ygp.hpp"
YGP_INIT
YGP_WNDPROC
{
static window win;
YGP_BEGIN_MSG_MAP
case WM_CREATE:
{
win=hwnd;
break;
}
case WM_DESTROY:
{
PostQuitMessage(0);
break;
}
YGP_END_MSG_MAP
return 0;
}
YGP_WINMAIN
{
YGP_TRY
YGP_REGCLS("YGPWindowClass")
window win("YGPWindowClass","Caption");
messageloop();
YGP_CATCH_MSGBOX
} | 540 | 228 |
#include "Random.h"
std::mt19937 Random::s_RandomEngine;
std::uniform_int_distribution<std::mt19937::result_type> Random::s_Distribution; | 138 | 54 |
#include <memory>
#include <vector>
#include <string>
#include <any>
#include "cm/cf/func/SdeFFunction.h"
#include "cm/ControlledObject.h"
#include "Configuration.h"
#include "PrototypeManager.h"
#include "Individual.h"
namespace adef {
void SdeFFunction::setup(const Configuration & config, const PrototypeManager & pm)
{
auto rand_config = config.get_config("rand");
auto rand = make_and_setup_type<BaseFunction>(rand_config, pm);
rand->set_function_name("rand");
add_function(rand);
parameters_.resize(config.get_uint_value("number_of_parameters"));
}
SdeFFunction::Object SdeFFunction::generate()
{
Object diff = 0;
auto size = parameters_.size();
for (decltype(size) idx = 1; idx < size; idx += 2) {
diff += parameters_.at(idx) - parameters_.at(idx + 1);
}
return parameters_.at(0) + get_function("rand")->generate() * diff;
}
bool SdeFFunction::record(const std::vector<std::any>& params, const std::string & name)
{
if (params.size() == parameters_.size()) {
for (decltype(params.size()) idx = 0; idx < params.size(); ++idx) {
parameters_.at(idx) = std::any_cast<Object>(params.at(idx));
}
}
else {
throw std::logic_error("SdeFFunction accept wrong parameters.");
}
return true;
}
bool SdeFFunction::record(const std::vector<std::any>& params, std::shared_ptr<const Individual> parent, std::shared_ptr<const Individual> offspring, const std::string & name)
{
return record(params, name);
}
void SdeFFunction::update()
{
get_function("rand")->update();
}
unsigned int SdeFFunction::number_of_parameters() const
{
return parameters_.size();
}
}
| 1,675 | 547 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: main.cpp
* Author: Hiromi Jenna Koh
*
* Created on 9 May, 2016, 11:03 AM
*/
#include "global.hpp"
#include <gsl/gsl_cdf.h>
#include <cstdlib>
#include <vector>
#include <map>
#include <string>
#include <iostream>
#include <regex>
#include <ctime>
using namespace std;
/*
*
*/
int main(int argc, char** argv) {
if(argc < 2){
cerr<<"\nUSAGE: EBprotNP.exe <data.file> <parameter.file>\n";
return 0;
}
clock_t begin = clock();
string dataF = argv[1];
string paramF = argv[2];
map <string, vector<string> > PROTmap;
map <string, vector<double> > PEPmap;
map <string, Protein_t> PROTEIN;
Input_t *UserInput = new Input_t();
cerr<<"==================================================================="<<endl;
cerr<< "Beginning Nonparametric EBprot Analysis...\n\n" <<endl;
readUserInput(paramF, *UserInput);
cerr<< "Reading in the data file...\n"<<endl;
bool logtrans = UserInput->log2transform;
set<string> protList = readData(dataF, UserInput->labels, logtrans, PROTmap, PEPmap);
cerr<< "\nThere are a total of "<<protList.size()<< " proteins and "<< PEPmap.size()<< " peptides.\n"<<endl;
vector<string> labels = UserInput->labels;
double thres = UserInput->threshold;
string design = UserInput->ExpDesign;
cerr<<"Carrying out analysis for a "<<design<<" experimental design."<<endl;
// independent and replicate design //
if(design =="independent"|design == "replicate"){
for(int i=0; i<labels.size(); i++){
map<string, double> PEPmapNEW;
map<string, vector<string> >PROTmapNEW;
map<double, vector<double> >DENmap;
cerr<<"=============================================================="<<endl;
cerr<<"Starting model fitting for "<<labels.at(i)<<"...\n"<<endl;
vector<int> PepRM;
int minPep = UserInput->minpep;
set<string> protinRep = createMap(i,minPep,PROTmap,PROTmapNEW, PEPmap,PEPmapNEW);
if(UserInput->outlierRm) {
cerr<<"Filtering out outlying peptides from proteins..."<<endl;
PepRM = OutlierRm(UserInput->mink, PROTmapNEW,PEPmapNEW);
}
else{ cerr<<"No filtering of outlying peptides will be carried out.\n\n"<<endl;}
set<string> Proteins = getKey(PROTmapNEW);
vector<string> protNA = NotIn(protList,Proteins);
vector<double> ALLratio =nonparamFit(protNA,PepRM, PROTmapNEW, PEPmapNEW, *UserInput, PROTEIN, DENmap);
map<string, Protein_t>::iterator iter;
int count=1;
cerr<<"\nReporting the results for first 6 proteins:"<<endl;
cerr<<"----------------------------------------------------------------"<<endl;
for(iter = PROTEIN.begin();iter!=PROTEIN.end(); iter++){
if(iter->second.medratio.at(i)!=NA_VAL){
if(count<=5){
cerr<<"Protein: "<< iter->first<<endl;
cerr<<"Median log2ratio: "<< iter->second.medratio.at(i)<<endl;
cerr<<"Number of peptide: "<< iter->second.numPep.at(i)<<endl;
cerr<<"Number of peptide removed: "<< iter->second.numPepRM.at(i)<<endl;;
cerr<<"PPscore: "<< iter->second.PPscore.at(i)<<endl;
//cerr<<"Posterior Odds: "<< iter->second.PostOdds.at(i)<<endl;
cerr<<"----------------------------------------------------------------"<<endl;
}
count++;
}
}
computeBFDR(thres,i, PROTEIN);
}
}
if(design =="timecourse"){
map<string, double> PEPmapNEW;
map<string, vector<string> >PROTmapNEW;
map<double, vector<double> >DENmap;
map<string, Protein_t> PROTEINfit;
cerr<<"\nStarting model fitting procedure...\n"<<endl;
int minPep = UserInput->minpep;
set<string> protinRep = createMap2(labels.size(),minPep,PROTmap, PROTmapNEW,PEPmap, PEPmapNEW);
vector<int> PepRM;
//cerr<<"PROTmap size: "<<PROTmap.size()<<endl;
//cerr<<"PEPmap size: "<<PEPmap.size()<<endl;
//cerr<<"PROTmapNEW size: "<<PROTmapNEW.size()<<endl;
//cerr<<"PEPmapNEW size: "<<PEPmapNEW.size()<<endl;
if(UserInput->outlierRm){
cerr<<"\nFiltering out outlying peptides from proteins..." <<endl;
PepRM = OutlierRm(UserInput->mink, PROTmapNEW, PEPmapNEW);
}
else{ cerr<<"No filtering of outlying peptides will be carried out.\n\n"<<endl;}
set<string> Proteins = getKey(PROTmapNEW);
vector<string> protNA = NotIn(protinRep,Proteins);
vector<double> ALLratio =nonparamFit(protNA,PepRM, PROTmapNEW, PEPmapNEW, *UserInput, PROTEINfit, DENmap);
map<string, Protein_t>::iterator iter;
int count=1;
cerr<<"\nReporting the results for first 6 proteins:"<<endl;
cerr<<"----------------------------------------------------------------"<<endl;
for(iter = PROTEINfit.begin();iter!=PROTEINfit.end(); iter++){
if(iter->second.medratio.at(0)!=NA_VAL){
if(count<=5){
cerr<<"Protein: "<< iter->first<<endl;
cerr<<"Median log2ratio: "<< iter->second.medratio.at(0)<<endl;
cerr<<"Number of peptide: "<< iter->second.numPep.at(0)<<endl;
cerr<<"Number of peptide removed: "<< iter->second.numPepRM.at(0)<<endl;;
cerr<<"PPscore: "<< iter->second.PPscore.at(0)<<endl;
cerr<<"Posterior Odds: "<< iter->second.PostOdds.at(0)<<endl;
cerr<<"----------------------------------------------------------------"<<endl;
}
count++;
}
}
computeBFDR(thres,0, PROTEINfit);
UnmergeMap(labels.size(), PROTmap,PROTEINfit, PROTEIN);
}
cleanMap(PROTEIN);
outputResult(UserInput, PROTEIN);
clock_t end = clock();
double elapse_sec = double(end - begin)/(double)CLOCKS_PER_SEC;
cerr<< "\n\nEBprotNP has completed running in " << elapse_sec <<" seconds.\n" <<endl;
cerr<< "================================= Completed ===================================\n"<<endl;
return 0;
}
| 6,093 | 2,252 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/page_info_model.h"
#include <string>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/command_line.h"
#include "base/i18n/time_formatting.h"
#include "base/string16.h"
#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/page_info_model_observer.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ssl/ssl_error_info.h"
#include "content/public/browser/cert_store.h"
#include "content/public/common/ssl_status.h"
#include "content/public/common/url_constants.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "net/base/cert_status_flags.h"
#include "net/base/ssl_cipher_suite_names.h"
#include "net/base/ssl_connection_status_flags.h"
#include "net/base/x509_certificate.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
using content::SSLStatus;
PageInfoModel::PageInfoModel(Profile* profile,
const GURL& url,
const SSLStatus& ssl,
bool show_history,
PageInfoModelObserver* observer)
: observer_(observer) {
Init();
if (url.SchemeIs(chrome::kChromeUIScheme)) {
sections_.push_back(
SectionInfo(ICON_STATE_INTERNAL_PAGE,
string16(),
l10n_util::GetStringUTF16(IDS_PAGE_INFO_INTERNAL_PAGE),
SECTION_INFO_INTERNAL_PAGE));
return;
}
SectionStateIcon icon_id = ICON_STATE_OK;
string16 headline;
string16 description;
scoped_refptr<net::X509Certificate> cert;
// Identity section.
string16 subject_name(UTF8ToUTF16(url.host()));
bool empty_subject_name = false;
if (subject_name.empty()) {
subject_name.assign(
l10n_util::GetStringUTF16(IDS_PAGE_INFO_SECURITY_TAB_UNKNOWN_PARTY));
empty_subject_name = true;
}
if (ssl.cert_id &&
content::CertStore::GetInstance()->RetrieveCert(ssl.cert_id, &cert) &&
(!net::IsCertStatusError(ssl.cert_status) ||
net::IsCertStatusMinorError(ssl.cert_status))) {
// There are no major errors. Check for minor errors.
if (net::IsCertStatusMinorError(ssl.cert_status)) {
string16 issuer_name(UTF8ToUTF16(cert->issuer().GetDisplayName()));
if (issuer_name.empty()) {
issuer_name.assign(l10n_util::GetStringUTF16(
IDS_PAGE_INFO_SECURITY_TAB_UNKNOWN_PARTY));
}
description.assign(l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY, issuer_name));
description += ASCIIToUTF16("\n\n");
if (ssl.cert_status & net::CERT_STATUS_UNABLE_TO_CHECK_REVOCATION) {
description += l10n_util::GetStringUTF16(
IDS_PAGE_INFO_SECURITY_TAB_UNABLE_TO_CHECK_REVOCATION);
} else if (ssl.cert_status & net::CERT_STATUS_NO_REVOCATION_MECHANISM) {
description += l10n_util::GetStringUTF16(
IDS_PAGE_INFO_SECURITY_TAB_NO_REVOCATION_MECHANISM);
} else {
NOTREACHED() << "Need to specify string for this warning";
}
icon_id = ICON_STATE_WARNING_MINOR;
} else if (ssl.cert_status & net::CERT_STATUS_IS_EV) {
// EV HTTPS page.
DCHECK(!cert->subject().organization_names.empty());
headline =
l10n_util::GetStringFUTF16(IDS_PAGE_INFO_EV_IDENTITY_TITLE,
UTF8ToUTF16(cert->subject().organization_names[0]),
UTF8ToUTF16(url.host()));
// An EV Cert is required to have a city (localityName) and country but
// state is "if any".
DCHECK(!cert->subject().locality_name.empty());
DCHECK(!cert->subject().country_name.empty());
string16 locality;
if (!cert->subject().state_or_province_name.empty()) {
locality = l10n_util::GetStringFUTF16(
IDS_PAGEINFO_ADDRESS,
UTF8ToUTF16(cert->subject().locality_name),
UTF8ToUTF16(cert->subject().state_or_province_name),
UTF8ToUTF16(cert->subject().country_name));
} else {
locality = l10n_util::GetStringFUTF16(
IDS_PAGEINFO_PARTIAL_ADDRESS,
UTF8ToUTF16(cert->subject().locality_name),
UTF8ToUTF16(cert->subject().country_name));
}
DCHECK(!cert->subject().organization_names.empty());
description.assign(l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY_EV,
UTF8ToUTF16(cert->subject().organization_names[0]),
locality,
UTF8ToUTF16(cert->issuer().GetDisplayName())));
} else if (ssl.cert_status & net::CERT_STATUS_IS_DNSSEC) {
// DNSSEC authenticated page.
if (empty_subject_name)
headline.clear(); // Don't display any title.
else
headline.assign(subject_name);
description.assign(l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY, UTF8ToUTF16("DNSSEC")));
} else {
// Non-EV OK HTTPS page.
if (empty_subject_name)
headline.clear(); // Don't display any title.
else
headline.assign(subject_name);
string16 issuer_name(UTF8ToUTF16(cert->issuer().GetDisplayName()));
if (issuer_name.empty()) {
issuer_name.assign(l10n_util::GetStringUTF16(
IDS_PAGE_INFO_SECURITY_TAB_UNKNOWN_PARTY));
}
description.assign(l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY, issuer_name));
}
} else {
// HTTP or HTTPS with errors (not warnings).
description.assign(l10n_util::GetStringUTF16(
IDS_PAGE_INFO_SECURITY_TAB_INSECURE_IDENTITY));
icon_id = ssl.security_style == content::SECURITY_STYLE_UNAUTHENTICATED ?
ICON_STATE_WARNING_MAJOR : ICON_STATE_ERROR;
const string16 bullet = UTF8ToUTF16("\n • ");
std::vector<SSLErrorInfo> errors;
SSLErrorInfo::GetErrorsForCertStatus(ssl.cert_id, ssl.cert_status,
url, &errors);
for (size_t i = 0; i < errors.size(); ++i) {
description += bullet;
description += errors[i].short_description();
}
if (ssl.cert_status & net::CERT_STATUS_NON_UNIQUE_NAME) {
description += ASCIIToUTF16("\n\n");
description += l10n_util::GetStringUTF16(
IDS_PAGE_INFO_SECURITY_TAB_NON_UNIQUE_NAME);
}
}
sections_.push_back(SectionInfo(
icon_id,
headline,
description,
SECTION_INFO_IDENTITY));
// Connection section.
// We consider anything less than 80 bits encryption to be weak encryption.
// TODO(wtc): Bug 1198735: report mixed/unsafe content for unencrypted and
// weakly encrypted connections.
icon_id = ICON_STATE_OK;
headline.clear();
description.clear();
if (!ssl.cert_id) {
// Not HTTPS.
DCHECK_EQ(ssl.security_style, content::SECURITY_STYLE_UNAUTHENTICATED);
icon_id = ssl.security_style == content::SECURITY_STYLE_UNAUTHENTICATED ?
ICON_STATE_WARNING_MAJOR : ICON_STATE_ERROR;
description.assign(l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_NOT_ENCRYPTED_CONNECTION_TEXT,
subject_name));
} else if (ssl.security_bits < 0) {
// Security strength is unknown. Say nothing.
icon_id = ICON_STATE_ERROR;
} else if (ssl.security_bits == 0) {
DCHECK_NE(ssl.security_style, content::SECURITY_STYLE_UNAUTHENTICATED);
icon_id = ICON_STATE_ERROR;
description.assign(l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_NOT_ENCRYPTED_CONNECTION_TEXT,
subject_name));
} else if (ssl.security_bits < 80) {
icon_id = ICON_STATE_ERROR;
description.assign(l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_WEAK_ENCRYPTION_CONNECTION_TEXT,
subject_name));
} else {
description.assign(l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTED_CONNECTION_TEXT,
subject_name,
base::IntToString16(ssl.security_bits)));
if (ssl.content_status) {
bool ran_insecure_content =
!!(ssl.content_status & SSLStatus::RAN_INSECURE_CONTENT);
icon_id = ran_insecure_content ?
ICON_STATE_ERROR : ICON_STATE_WARNING_MINOR;
description.assign(l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTED_SENTENCE_LINK,
description,
l10n_util::GetStringUTF16(ran_insecure_content ?
IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTED_INSECURE_CONTENT_ERROR :
IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTED_INSECURE_CONTENT_WARNING)));
}
}
uint16 cipher_suite =
net::SSLConnectionStatusToCipherSuite(ssl.connection_status);
if (ssl.security_bits > 0 && cipher_suite) {
int ssl_version =
net::SSLConnectionStatusToVersion(ssl.connection_status);
const char* ssl_version_str;
net::SSLVersionToString(&ssl_version_str, ssl_version);
description += ASCIIToUTF16("\n\n");
description += l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_SSL_VERSION,
ASCIIToUTF16(ssl_version_str));
bool did_fallback = (ssl.connection_status &
net::SSL_CONNECTION_VERSION_FALLBACK) != 0;
bool no_renegotiation =
(ssl.connection_status &
net::SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION) != 0;
const char *key_exchange, *cipher, *mac;
net::SSLCipherSuiteToStrings(&key_exchange, &cipher, &mac, cipher_suite);
description += ASCIIToUTF16("\n\n");
description += l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTION_DETAILS,
ASCIIToUTF16(cipher), ASCIIToUTF16(mac), ASCIIToUTF16(key_exchange));
description += ASCIIToUTF16("\n\n");
uint8 compression_id =
net::SSLConnectionStatusToCompression(ssl.connection_status);
if (compression_id) {
const char* compression;
net::SSLCompressionToString(&compression, compression_id);
description += l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_COMPRESSION_DETAILS,
ASCIIToUTF16(compression));
} else {
description += l10n_util::GetStringUTF16(
IDS_PAGE_INFO_SECURITY_TAB_NO_COMPRESSION);
}
if (did_fallback) {
// For now, only SSL/TLS version fallback will trigger a warning icon.
if (icon_id < ICON_STATE_WARNING_MINOR)
icon_id = ICON_STATE_WARNING_MINOR;
description += ASCIIToUTF16("\n\n");
description += l10n_util::GetStringUTF16(
IDS_PAGE_INFO_SECURITY_TAB_FALLBACK_MESSAGE);
}
if (no_renegotiation) {
description += ASCIIToUTF16("\n\n");
description += l10n_util::GetStringUTF16(
IDS_PAGE_INFO_SECURITY_TAB_RENEGOTIATION_MESSAGE);
}
}
if (!description.empty()) {
sections_.push_back(SectionInfo(
icon_id,
headline,
description,
SECTION_INFO_CONNECTION));
}
// Request the number of visits.
HistoryService* history = profile->GetHistoryService(
Profile::EXPLICIT_ACCESS);
if (show_history && history) {
history->GetVisibleVisitCountToHost(
url,
&request_consumer_,
base::Bind(&PageInfoModel::OnGotVisitCountToHost,
base::Unretained(this)));
}
if (ssl.cert_id) {
certificate_label_ = l10n_util::GetStringUTF16(
IDS_PAGEINFO_CERT_INFO_BUTTON);
}
}
PageInfoModel::~PageInfoModel() {}
int PageInfoModel::GetSectionCount() {
return sections_.size();
}
PageInfoModel::SectionInfo PageInfoModel::GetSectionInfo(int index) {
DCHECK(index < static_cast<int>(sections_.size()));
return sections_[index];
}
gfx::Image* PageInfoModel::GetIconImage(SectionStateIcon icon_id) {
if (icon_id == ICON_NONE)
return NULL;
// The bubble uses new, various icons.
return icons_[icon_id];
}
void PageInfoModel::OnGotVisitCountToHost(HistoryService::Handle handle,
bool found_visits,
int count,
base::Time first_visit) {
if (!found_visits) {
// This indicates an error, such as the page wasn't http/https; do nothing.
return;
}
bool visited_before_today = false;
if (count) {
base::Time today = base::Time::Now().LocalMidnight();
base::Time first_visit_midnight = first_visit.LocalMidnight();
visited_before_today = (first_visit_midnight < today);
}
string16 headline = l10n_util::GetStringUTF16(IDS_PAGE_INFO_SITE_INFO_TITLE);
if (!visited_before_today) {
sections_.push_back(SectionInfo(
ICON_STATE_WARNING_MAJOR,
headline,
l10n_util::GetStringUTF16(
IDS_PAGE_INFO_SECURITY_TAB_FIRST_VISITED_TODAY),
SECTION_INFO_FIRST_VISIT));
} else {
sections_.push_back(SectionInfo(
ICON_STATE_INFO,
headline,
l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_VISITED_BEFORE_TODAY,
base::TimeFormatShortDate(first_visit)),
SECTION_INFO_FIRST_VISIT));
}
observer_->OnPageInfoModelChanged();
}
string16 PageInfoModel::GetCertificateLabel() const {
return certificate_label_;
}
PageInfoModel::PageInfoModel() : observer_(NULL) {
Init();
}
void PageInfoModel::Init() {
// Loads the icons into the vector. The order must match the SectionStateIcon
// enum.
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
icons_.push_back(&rb.GetNativeImageNamed(IDR_PAGEINFO_GOOD));
icons_.push_back(&rb.GetNativeImageNamed(IDR_PAGEINFO_WARNING_MINOR));
icons_.push_back(&rb.GetNativeImageNamed(IDR_PAGEINFO_WARNING_MAJOR));
icons_.push_back(&rb.GetNativeImageNamed(IDR_PAGEINFO_BAD));
icons_.push_back(&rb.GetNativeImageNamed(IDR_PAGEINFO_INFO));
icons_.push_back(&rb.GetNativeImageNamed(IDR_PRODUCT_LOGO_26));
}
| 13,989 | 5,002 |
// Fill out your copyright notice in the Description page of Project Settings.
#include "GravityGunCameraShake.h"
void UGravityGunCameraShake::SetRotPitch(float Amplitude, float Frequency)
{
//Setting new values for the roational pitch of the oscillation
RotPitch.Amplitude = Amplitude;
RotPitch.Frequency = Frequency;
RotOscillation.Pitch = RotPitch;
}
void UGravityGunCameraShake::SetRotYaw(float Amplitude, float Frequency)
{
//Setting new values for the roational yaw of the oscillation
RotYaw.Amplitude = Amplitude;
RotYaw.Frequency = Frequency;
RotOscillation.Pitch = RotYaw;
}
UGravityGunCameraShake::UGravityGunCameraShake()
{
//Default values being applied for both pitch and yaw rotational oscillation
RotPitch.Amplitude = 1.0f;
RotPitch.Frequency = FMath::RandRange(15.0f, 50.0f);
RotYaw.Amplitude = 1.0f;
RotYaw.Frequency = FMath::RandRange(15.0f, 50.0f);
RotOscillation.Pitch = RotPitch;
RotOscillation.Yaw = RotYaw;
//Setting the duration of the oscillation
OscillationDuration = .5f;
}
void UGravityGunCameraShake::PlayShake(APlayerCameraManager* Camera, float Scale, ECameraAnimPlaySpace::Type InPlaySpace, FRotator UserPlaySpaceRot)
{
Super::PlayShake(Camera, Scale, InPlaySpace, UserPlaySpaceRot);
}
void UGravityGunCameraShake::UpdateAndApplyCameraShake(float DeltaTime, float Alpha, FMinimalViewInfo& InOutPOV)
{
Super::UpdateAndApplyCameraShake(DeltaTime, Alpha, InOutPOV);
} | 1,428 | 539 |
#include "acmacs-base/argv.hh"
#include "acmacs-base/color-gradient.hh"
// ----------------------------------------------------------------------
using namespace acmacs::argv;
struct Options : public argv
{
Options(int a_argc, const char* const a_argv[], on_error on_err = on_error::exit) : argv() { parse(a_argc, a_argv, on_err); }
argument<str> color1{*this, arg_name{"color1"}, mandatory};
argument<str> color2{*this, arg_name{"color2"}, mandatory};
argument<str> color3{*this, arg_name{"color3"}, mandatory};
argument<size_t> output_size{*this, arg_name{"output-size"}, mandatory};
};
int main(int argc, const char* argv[])
{
int exit_code = 0;
try {
Options opt(argc, argv);
const Color c1{*opt.color1}, c2{*opt.color2}, c3{*opt.color3};
const auto result = acmacs::color::bezier_gradient(c1, c2, c3, opt.output_size);
for (const auto& color : result)
fmt::print("{:X}\n", color);
}
catch (std::exception& err) {
fmt::print(stderr, "ERROR: {}\n", err);
exit_code = 1;
}
return exit_code;
}
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
| 1,272 | 436 |
#include <aslam/cameras/distortion-fisheye.h>
namespace aslam {
std::ostream& operator<<(std::ostream& out, const FisheyeDistortion& distortion) {
distortion.printParameters(out, std::string(""));
return out;
}
FisheyeDistortion::FisheyeDistortion(const Eigen::VectorXd& dist_coeffs)
: Base(dist_coeffs, Distortion::Type::kFisheye) {
CHECK(distortionParametersValid(dist_coeffs)) << dist_coeffs.transpose();
}
void FisheyeDistortion::distortUsingExternalCoefficients(const Eigen::VectorXd* dist_coeffs,
Eigen::Vector2d* point,
Eigen::Matrix2d* out_jacobian) const {
CHECK_NOTNULL(point);
// Use internal params if dist_coeffs==nullptr
if(!dist_coeffs)
dist_coeffs = &distortion_coefficients_;
CHECK_EQ(dist_coeffs->size(), kNumOfParams) << "dist_coeffs: invalid size!";
const double& w = (*dist_coeffs)(0);
const double r_u = point->norm();
const double r_u_cubed = r_u * r_u * r_u;
const double tanwhalf = tan(w / 2.);
const double tanwhalfsq = tanwhalf * tanwhalf;
const double atan_wrd = atan(2. * tanwhalf * r_u);
double r_rd;
if (w * w < 1e-5) {
// Limit w > 0.
r_rd = 1.0;
} else {
if (r_u * r_u < 1e-5) {
// Limit r_u > 0.
r_rd = 2. * tanwhalf / w;
} else {
r_rd = atan_wrd / (r_u * w);
}
}
const double& u = (*point)(0);
const double& v = (*point)(1);
// If Jacobian calculation is requested.
if (out_jacobian) {
out_jacobian->resize(2, 2);
if (w * w < 1e-5) {
out_jacobian->setIdentity();
}
else if (r_u * r_u < 1e-5) {
out_jacobian->setIdentity();
// The coordinates get multiplied by an expression not depending on r_u.
*out_jacobian *= (2. * tanwhalf / w);
}
else {
const double duf_du = (atan_wrd) / (w * r_u)
- (u * u * atan_wrd) / (w * r_u_cubed)
+ (2 * u * u * tanwhalf)
/ (w * (u * u + v * v) * (4 * tanwhalfsq * (u * u + v * v) + 1));
const double duf_dv = (2 * u * v * tanwhalf)
/ (w * (u * u + v * v) * (4 * tanwhalfsq * (u * u + v * v) + 1))
- (u * v * atan_wrd) / (w * r_u_cubed);
const double dvf_du = (2 * u * v * tanwhalf)
/ (w * (u * u + v * v) * (4 * tanwhalfsq * (u * u + v * v) + 1))
- (u * v * atan_wrd) / (w * r_u_cubed);
const double dvf_dv = (atan_wrd) / (w * r_u)
- (v * v * atan_wrd) / (w * r_u_cubed)
+ (2 * v * v * tanwhalf)
/ (w * (u * u + v * v) * (4 * tanwhalfsq * (u * u + v * v) + 1));
*out_jacobian << duf_du, duf_dv,
dvf_du, dvf_dv;
}
}
*point *= r_rd;
}
void FisheyeDistortion::distortParameterJacobian(const Eigen::VectorXd* dist_coeffs,
const Eigen::Vector2d& point,
Eigen::Matrix<double, 2, Eigen::Dynamic>* out_jacobian) const {
CHECK_EQ(dist_coeffs->size(), kNumOfParams) << "dist_coeffs: invalid size!";
CHECK_NOTNULL(out_jacobian);
const double& w = (*dist_coeffs)(0);
const double tanwhalf = tan(w / 2.);
const double tanwhalfsq = tanwhalf * tanwhalf;
const double r_u = point.norm();
const double atan_wrd = atan(2. * tanwhalf * r_u);
const double& u = point(0);
const double& v = point(1);
out_jacobian->resize(2, kNumOfParams);
if (w * w < 1e-5) {
out_jacobian->setZero();
}
else if (r_u * r_u < 1e-5) {
out_jacobian->setOnes();
*out_jacobian *= (w - sin(w)) / (w * w * cos(w / 2) * cos(w / 2));
}
else {
const double dxd_d_w = (2 * u * (tanwhalfsq / 2 + 0.5))
/ (w * (4 * tanwhalfsq * r_u * r_u + 1))
- (u * atan_wrd) / (w * w * r_u);
const double dyd_d_w = (2 * v * (tanwhalfsq / 2 + 0.5))
/ (w * (4 * tanwhalfsq * r_u * r_u + 1))
- (v * atan_wrd) / (w * w * r_u);
*out_jacobian << dxd_d_w, dyd_d_w;
}
}
void FisheyeDistortion::undistortUsingExternalCoefficients(const Eigen::VectorXd& dist_coeffs,
Eigen::Vector2d* point) const {
CHECK_NOTNULL(point);
CHECK_EQ(dist_coeffs.size(), kNumOfParams) << "dist_coeffs: invalid size!";
const double& w = dist_coeffs(0);
double mul2tanwby2 = tan(w / 2.0) * 2.0;
// Calculate distance from point to center.
double r_d = point->norm();
if (mul2tanwby2 == 0 || r_d == 0) {
return;
}
// Calculate undistorted radius of point.
double r_u;
if (fabs(r_d * w) <= kMaxValidAngle) {
r_u = tan(r_d * w) / (r_d * mul2tanwby2);
} else {
return;
}
(*point) *= r_u;
}
bool FisheyeDistortion::areParametersValid(const Eigen::VectorXd& parameters)
{
// Check the vector size.
if (parameters.size() != kNumOfParams)
return false;
// Expect w to have sane magnitude.
double w = parameters(0);
bool valid = std::abs(w) < 1e-16 || (w >= kMinValidW && w <= kMaxValidW);
LOG_IF(INFO, !valid) << "Invalid w parameter: " << w << ", expected w in [" << kMinValidW
<< ", " << kMaxValidW << "].";
return valid;
}
bool FisheyeDistortion::distortionParametersValid(const Eigen::VectorXd& dist_coeffs) const {
return areParametersValid(dist_coeffs);
}
void FisheyeDistortion::printParameters(std::ostream& out, const std::string& text) const {
const Eigen::VectorXd& distortion_coefficients = getParameters();
CHECK_EQ(distortion_coefficients.size(), kNumOfParams) << "dist_coeffs: invalid size!";
out << text << std::endl;
out << "Distortion: (FisheyeDistortion) " << std::endl;
out << " w: " << distortion_coefficients(0) << std::endl;
}
} // namespace aslam
| 5,756 | 2,330 |
/*
* Copyright (c) The Shogun Machine Learning Toolbox
* Written (w) 2014 Parijat Mazumdar
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those
* of the authors and should not be interpreted as representing official policies,
* either expressed or implied, of the Shogun Development Team.
*/
#include <gtest/gtest.h>
#include <shogun/features/DenseFeatures.h>
#include <shogun/lib/SGMatrix.h>
#include <shogun/regression/LeastAngleRegression.h>
#include <shogun/labels/RegressionLabels.h>
#include <shogun/mathematics/eigen3.h>
#include <shogun/mathematics/linalg/LinalgNamespace.h>
#include <shogun/preprocessor/PruneVarSubMean.h>
#include <shogun/preprocessor/NormOne.h>
using namespace Eigen;
using namespace shogun;
//Generate the Data that N is greater than D
void generate_data_n_greater_d(SGMatrix<float64_t> &data, SGVector<float64_t> &lab)
{
data(0,0)=0.044550005575722;
data(1,0)=-0.433969606728583;
data(2,0)=-0.397935396933392;
data(0,1)=-0.778754072066602;
data(1,1)=-0.620105076569903;
data(2,1)=-0.542538248707627;
data(0,2)=0.334313094513960;
data(1,2)=0.421985645755003;
data(2,2)=0.263031426076997;
data(0,3)=0.516043376162584;
data(1,3)=0.159041471773470;
data(2,3)=0.691318725364356;
data(0,4)=-0.116152404185664;
data(1,4)=0.473047565770014;
data(2,4)=-0.013876505800334;
lab[0]=-0.196155100498902;
lab[1]=-5.376485285422094;
lab[2]=-1.717489351713958;
lab[3]=4.506538567065213;
lab[4]=2.783591170569741;
}
//Generate the Data that N is less than D
void generate_data_n_less_d(SGMatrix<float64_t> &data, SGVector<float64_t> &lab)
{
data(0,0)=0.217778502400306;
data(1,0)=0.660755393455389;
data(2,0)=0.492143169178889;
data(3,0)=0.668618163874328;
data(4,0)=0.806098163441828;
data(0,1)=-0.790379818206924;
data(1,1)=-0.745771163834136;
data(2,1)=-0.810293460958058;
data(3,1)=-0.740156729710306;
data(4,1)=-0.515540473266151;
data(0,2)=0.572601315806618;
data(1,2)=0.085015770378747;
data(2,2)=0.318150291779169;
data(3,2)=0.071538565835978;
data(4,2)=-0.290557690175677;
lab[0]=3.771471612608209;
lab[1]=-3.218048715328546;
lab[2]=-0.553422897279663;
}
TEST(LeastAngleRegression, lasso_n_greater_than_d)
{
SGMatrix<float64_t> data(3,5);
SGVector<float64_t> lab(5);
generate_data_n_greater_d(data, lab);
CDenseFeatures<float64_t>* features=new CDenseFeatures<float64_t>(data);
SG_REF(features);
CRegressionLabels* labels=new CRegressionLabels(lab);
SG_REF(labels);
CLeastAngleRegression* lars=new CLeastAngleRegression();
lars->set_labels((CLabels*) labels);
lars->train(features);
SGVector<float64_t> active3=SGVector<float64_t>(lars->get_w_for_var(3));
SGVector<float64_t> active2=SGVector<float64_t>(lars->get_w_for_var(2));
SGVector<float64_t> active1=SGVector<float64_t>(lars->get_w_for_var(1));
float64_t epsilon=0.000000000001;
EXPECT_NEAR(active3[0],2.911072069591,epsilon);
EXPECT_NEAR(active3[1],1.290672330338,epsilon);
EXPECT_NEAR(active3[2],2.208741384416,epsilon);
EXPECT_NEAR(active2[0],1.747958837898,epsilon);
EXPECT_NEAR(active2[1],0.000000000000,epsilon);
EXPECT_NEAR(active2[2],1.840553057519,epsilon);
EXPECT_NEAR(active1[0],0.000000000000,epsilon);
EXPECT_NEAR(active1[1],0.000000000000,epsilon);
EXPECT_NEAR(active1[2],0.092594219621,epsilon);
SG_UNREF(lars);
SG_UNREF(features);
SG_UNREF(labels);
}
TEST(LeastAngleRegression, lasso_n_less_than_d)
{
SGMatrix<float64_t> data(5,3);
SGVector<float64_t> lab(3);
generate_data_n_less_d(data,lab);
CDenseFeatures<float64_t>* features=new CDenseFeatures<float64_t>(data);
SG_REF(features);
CRegressionLabels* labels=new CRegressionLabels(lab);
SG_REF(labels);
CLeastAngleRegression* lars=new CLeastAngleRegression();
lars->set_labels(labels);
lars->train(features);
SGVector<float64_t> active2=SGVector<float64_t>(lars->get_w_for_var(2));
SGVector<float64_t> active1=SGVector<float64_t>(lars->get_w_for_var(1));
float64_t epsilon=0.000000000001;
EXPECT_NEAR(active1[0],0.000000000000,epsilon);
EXPECT_NEAR(active1[1],0.000000000000,epsilon);
EXPECT_NEAR(active1[2],0.000000000000,epsilon);
EXPECT_NEAR(active1[3],0.039226231353,epsilon);
EXPECT_NEAR(active1[4],0.000000000000,epsilon);
EXPECT_NEAR(active2[0],0.000000000000,epsilon);
EXPECT_NEAR(active2[1],0.000000000000,epsilon);
EXPECT_NEAR(active2[2],0.000000000000,epsilon);
EXPECT_NEAR(active2[3],2.578863294056,epsilon);
EXPECT_NEAR(active2[4],2.539637062702,epsilon);
SG_UNREF(lars);
SG_UNREF(features);
SG_UNREF(labels);
}
TEST(LeastAngleRegression, lars_n_greater_than_d)
{
SGMatrix<float64_t> data(3,5);
SGVector<float64_t> lab(5);
generate_data_n_greater_d(data, lab);
CDenseFeatures<float64_t>* features=new CDenseFeatures<float64_t>(data);
SG_REF(features);
CRegressionLabels* labels=new CRegressionLabels(lab);
SG_REF(labels);
CLeastAngleRegression* lars=new CLeastAngleRegression(false);
lars->set_labels((CLabels*) labels);
lars->train(features);
SGVector<float64_t> active3=SGVector<float64_t>(lars->get_w_for_var(3));
SGVector<float64_t> active2=SGVector<float64_t>(lars->get_w_for_var(2));
SGVector<float64_t> active1=SGVector<float64_t>(lars->get_w_for_var(1));
float64_t epsilon=0.000000000001;
EXPECT_NEAR(active3[0],2.911072069591,epsilon);
EXPECT_NEAR(active3[1],1.290672330338,epsilon);
EXPECT_NEAR(active3[2],2.208741384416,epsilon);
EXPECT_NEAR(active2[0],1.747958837898,epsilon);
EXPECT_NEAR(active2[1],0.000000000000,epsilon);
EXPECT_NEAR(active2[2],1.840553057519,epsilon);
EXPECT_NEAR(active1[0],0.000000000000,epsilon);
EXPECT_NEAR(active1[1],0.000000000000,epsilon);
EXPECT_NEAR(active1[2],0.092594219621,epsilon);
SG_UNREF(lars);
SG_UNREF(features);
SG_UNREF(labels);
}
TEST(LeastAngleRegression, lars_n_less_than_d)
{
SGMatrix<float64_t> data(5,3);
SGVector<float64_t> lab(3);
generate_data_n_less_d(data,lab);
CDenseFeatures<float64_t>* features=new CDenseFeatures<float64_t>(data);
SG_REF(features);
CRegressionLabels* labels=new CRegressionLabels(lab);
SG_REF(labels);
CLeastAngleRegression* lars=new CLeastAngleRegression(false);
lars->set_labels(labels);
lars->train(features);
SGVector<float64_t> active2=SGVector<float64_t>(lars->get_w_for_var(2));
SGVector<float64_t> active1=SGVector<float64_t>(lars->get_w_for_var(1));
float64_t epsilon=0.000000000001;
EXPECT_NEAR(active1[0],0.000000000000,epsilon);
EXPECT_NEAR(active1[1],0.000000000000,epsilon);
EXPECT_NEAR(active1[2],0.000000000000,epsilon);
EXPECT_NEAR(active1[3],0.039226231353,epsilon);
EXPECT_NEAR(active1[4],0.000000000000,epsilon);
EXPECT_NEAR(active2[0],0.000000000000,epsilon);
EXPECT_NEAR(active2[1],0.000000000000,epsilon);
EXPECT_NEAR(active2[2],0.000000000000,epsilon);
EXPECT_NEAR(active2[3],2.578863294056,epsilon);
EXPECT_NEAR(active2[4],2.539637062702,epsilon);
SG_UNREF(lars);
SG_UNREF(features);
SG_UNREF(labels);
}
template <typename ST>
void lars_n_less_than_d_feature_test_templated()
{
SGMatrix<float64_t> data_64(5,3);
SGVector<float64_t> lab(3);
generate_data_n_less_d(data_64,lab);
//copy data_64 into a ST SGMatrix
SGMatrix<ST> data(5,3);
for(index_t c = 0; c < data_64.num_cols; ++c)
for(index_t r = 0; r < data_64.num_rows; ++r)
data(r, c) = (ST) data_64(r, c);
CDenseFeatures<ST>* features = new CDenseFeatures<ST>(data);
SG_REF(features);
CRegressionLabels* labels=new CRegressionLabels(lab);
SG_REF(labels);
CLeastAngleRegression* lars=new CLeastAngleRegression(false);
SG_REF(lars)
lars->set_labels(labels);
//Catch exceptions thrown when training, clean up
try
{
lars->train(features);
}
catch(...)
{
SG_UNREF(lars);
SG_UNREF(features);
SG_UNREF(labels);
throw;
}
SGVector<float64_t> active2 = lars->get_w_for_var(2);
SGVector<float64_t> active1 = lars->get_w_for_var(1);
float64_t epsilon=0.0001;
EXPECT_NEAR(active1[0],0.000000000000,epsilon);
EXPECT_NEAR(active1[1],0.000000000000,epsilon);
EXPECT_NEAR(active1[2],0.000000000000,epsilon);
EXPECT_NEAR(active1[3],0.039226231353,epsilon);
EXPECT_NEAR(active1[4],0.000000000000,epsilon);
EXPECT_NEAR(active2[0],0.000000000000,epsilon);
EXPECT_NEAR(active2[1],0.000000000000,epsilon);
EXPECT_NEAR(active2[2],0.000000000000,epsilon);
EXPECT_NEAR(active2[3],2.578863294056,epsilon);
EXPECT_NEAR(active2[4],2.539637062702,epsilon);
SG_UNREF(lars);
SG_UNREF(features);
SG_UNREF(labels);
}
TEST(LeastAngleRegression, lars_template_test_bool)
{
EXPECT_ANY_THROW(lars_n_less_than_d_feature_test_templated<bool>());
}
TEST(LeastAngleRegression, lars_template_test_char)
{
EXPECT_ANY_THROW(lars_n_less_than_d_feature_test_templated<char>());
}
TEST(LeastAngleRegression, lars_template_test_int8)
{
EXPECT_ANY_THROW(lars_n_less_than_d_feature_test_templated<int8_t>());
}
TEST(LeastAngleRegression, lars_template_test_unit8)
{
EXPECT_ANY_THROW(lars_n_less_than_d_feature_test_templated<uint8_t>());
}
TEST(LeastAngleRegression, lars_template_test_int16)
{
EXPECT_ANY_THROW(lars_n_less_than_d_feature_test_templated<int16_t>());
}
TEST(LeastAngleRegression, lars_template_test_uint16)
{
EXPECT_ANY_THROW(lars_n_less_than_d_feature_test_templated<uint16_t>());
}
TEST(LeastAngleRegression, lars_template_test_int32)
{
EXPECT_ANY_THROW(lars_n_less_than_d_feature_test_templated<int32_t>());
}
TEST(LeastAngleRegression, lars_template_test_uint32)
{
EXPECT_ANY_THROW(lars_n_less_than_d_feature_test_templated<uint32_t>());
}
TEST(LeastAngleRegression, lars_template_test_int64)
{
EXPECT_ANY_THROW(lars_n_less_than_d_feature_test_templated<int64_t>());
}
TEST(LeastAngleRegression, lars_template_test_uint64)
{
EXPECT_ANY_THROW(lars_n_less_than_d_feature_test_templated<uint64_t>());
}
TEST(LeastAngleRegression, lars_template_test_float32)
{
lars_n_less_than_d_feature_test_templated<float32_t>();
}
TEST(LeastAngleRegression, lars_template_test_float64)
{
lars_n_less_than_d_feature_test_templated<float64_t>();
}
TEST(LeastAngleRegression, lars_template_test_floatmax)
{
lars_n_less_than_d_feature_test_templated<floatmax_t>();
}
#ifndef USE_VIENNACL_GLOBAL
TEST(LeastAngleRegression, cholesky_insert)
{
class lars_helper: public CLeastAngleRegression
{
public:
SGMatrix<float64_t> cholesky_insert_helper(const SGMatrix<float64_t>& X,
const SGMatrix<float64_t>& X_active, SGMatrix<float64_t>& R, int32_t i, int32_t n)
{
return CLeastAngleRegression::cholesky_insert<float64_t>(X, X_active, R, i, n);
}
};
int32_t num_feats=5, num_vec=6;
SGMatrix<float64_t> R(num_feats, num_feats);
SGMatrix<float64_t> mat(num_vec, num_feats-1);
SGMatrix<float64_t> matnew(num_vec, num_feats);
SGVector<float64_t> vec(num_vec);
vec.random(0.0,1.0);
Map<VectorXd> map_vec(vec.vector, vec.size());
for (index_t i=0; i<num_vec; i++)
{
for (index_t j=0; j<num_feats-1; j++)
{
mat(i,j)=CMath::random(0.0,1.0);
matnew(i,j)=mat(i,j);
}
}
for (index_t i=0 ; i<num_vec; i++)
matnew(i, num_feats-1)=vec[i];
Map<MatrixXd> mat_old(mat.matrix, num_vec, num_feats-1);
Map<MatrixXd> mat_new(matnew.matrix, num_vec, num_feats);
Map<MatrixXd> map_R(R.matrix, num_feats, num_feats);
MatrixXd XX=mat_old.transpose()*mat_old;
// Compute matrix R which has to be updated
SGMatrix<float64_t> R_old=linalg::cholesky_factor(SGMatrix<float64_t>(XX), false);
// Update cholesky decomposition matrix R
lars_helper lars;
SGMatrix<float64_t> R_new = lars.cholesky_insert_helper(matnew, mat, R_old, 4, 4);
Map<MatrixXd> map_R_new(R_new.matrix, R_new.num_rows, R_new.num_cols);
// Compute true cholesky decomposition
MatrixXd XX_new=mat_new.transpose()*mat_new;
SGMatrix<float64_t> R_true=linalg::cholesky_factor(SGMatrix<float64_t>(XX_new), false);
Map<MatrixXd> map_R_true(R_true.matrix, num_feats, num_feats);
EXPECT_NEAR((map_R_true - map_R_new).norm(), 0.0, 1E-12);
}
TEST(LeastAngleRegression, ols_equivalence)
{
int32_t n_feat=25, n_vec=100;
SGMatrix<float64_t> data(n_feat, n_vec);
for (index_t i=0; i<n_feat; i++)
{
for (index_t j=0; j<n_vec; j++)
data(i,j)=CMath::random(0.0,1.0);
}
SGVector<float64_t> lab=SGVector<float64_t>(n_vec);
lab.random(0.0,1.0);
float64_t mean=linalg::mean(lab);
for (index_t i=0; i<lab.size(); i++)
lab[i]-=mean;
auto features = some<CDenseFeatures<float64_t>>(data);
auto proc1 = some<CPruneVarSubMean>();
auto proc2 = some<CNormOne>();
proc1->fit(features);
features =
wrap(proc1->transform(features)->as<CDenseFeatures<float64_t>>());
proc2->fit(features);
features =
wrap(proc2->transform(features)->as<CDenseFeatures<float64_t>>());
auto labels = some<CRegressionLabels>(lab);
auto lars = some<CLeastAngleRegression>(false);
lars->set_labels((CLabels*) labels);
lars->train(features);
// Full LAR model
SGVector<float64_t> w=lars->get_w();
Map<VectorXd> map_w(w.vector, w.size());
SGMatrix<float64_t> mat=features->get_feature_matrix();
Map<MatrixXd> feat(mat.matrix, mat.num_rows, mat.num_cols);
Map<VectorXd> l(lab.vector, lab.size());
// OLS
#if EIGEN_WITH_TRANSPOSITION_BUG
MatrixXd feat_t = feat.transpose().eval();
VectorXd solve=feat_t.colPivHouseholderQr().solve(l);
#else
VectorXd solve=feat.transpose().colPivHouseholderQr().solve(l);
#endif
// Check if full LAR model is equivalent to OLS
EXPECT_EQ( w.size(), n_feat);
EXPECT_NEAR( (map_w - solve).norm(), 0.0, 1E-12);
}
#endif
TEST(LeastAngleRegression, early_stop_l1_norm)
{
SGMatrix<float64_t> data(3,5);
SGVector<float64_t> lab(5);
generate_data_n_greater_d(data, lab);
CDenseFeatures<float64_t>* features=new CDenseFeatures<float64_t>(data);
SG_REF(features);
CRegressionLabels* labels=new CRegressionLabels(lab);
SG_REF(labels);
CLeastAngleRegression* lars=new CLeastAngleRegression(false);
lars->set_labels((CLabels*) labels);
// set max l1 norm
lars->set_max_l1_norm(1);
lars->train(features);
SGVector<float64_t> active2=SGVector<float64_t>(lars->get_w_for_var(2));
SGVector<float64_t> active1=SGVector<float64_t>(lars->get_w_for_var(1));
float64_t epsilon=0.000000000001;
EXPECT_NEAR(active2[0],0.453702890189,epsilon);
EXPECT_NEAR(active2[1],0.000000000000,epsilon);
EXPECT_NEAR(active2[2],0.546297109810,epsilon);
EXPECT_NEAR(active1[0],0.000000000000,epsilon);
EXPECT_NEAR(active1[1],0.000000000000,epsilon);
EXPECT_NEAR(active1[2],0.092594219621,epsilon);
SG_UNREF(lars);
SG_UNREF(features);
SG_UNREF(labels);
}
| 15,640 | 7,940 |
#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#define GL_GLEXT_PROTOTYPES
#define EGL_EGLEXT_PROTOTYPES
#else
extern "C" {
#include "examples/libs/gl3w/GL/gl3w.c"
}
#define IMGUI_IMPL_OPENGL_LOADER_CUSTOM "examples/libs/gl3w/GL/gl3w.h"
#endif
#include "backends/imgui_impl_opengl3.cpp"
#include "backends/imgui_impl_glfw.cpp"
#include "misc/cpp/imgui_stdlib.cpp"
#include "misc/freetype/imgui_freetype.cpp"
#include "imgui.h"
#include "imgui-glfw.h"
#include <map>
namespace ImGui
{
namespace GLFW
{
int g_UnloadTextureInterval = 1;
std::map<void*, std::pair<int, ImTextureID>> g_TexturesCache;
GLuint GetNativeTexture(const GLFWimage& texture) {
auto&& found = g_TexturesCache.find(texture.pixels);
GLuint gl_texture = 0;
if (found != g_TexturesCache.end()) {
found->second.first = g_UnloadTextureInterval;
gl_texture = (GLuint)(intptr_t)found->second.second;
return gl_texture;
}
glGenTextures(1, &gl_texture);
glBindTexture(GL_TEXTURE_2D, gl_texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
#ifdef GL_UNPACK_ROW_LENGTH
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
#endif
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texture.width, texture.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, texture.pixels);
glBindTexture(GL_TEXTURE_2D, gl_texture);
g_TexturesCache[texture.pixels] = std::make_pair(g_UnloadTextureInterval, (ImTextureID)(intptr_t)gl_texture);
return gl_texture;
}
bool Init(GLFWwindow* window) {
IMGUI_CHECKVERSION();
ImGui::CreateContext();
#ifdef __EMSCRIPTEN__
const char* glsl_version = "#version 100";
#elif __APPLE__
// GL 3.2 + GLSL 150
const char* glsl_version = "#version 150";
#else
// GL 3.0 + GLSL 130
const char* glsl_version = "#version 130";
#endif
#ifdef __EMSCRIPTEN__
bool err = false;
#else
bool err = gl3wInit() != 0;
#endif
if (err)
{
fprintf(stderr, "Failed to initialize OpenGL loader!\n");
return false;
}
if (!ImGui_ImplGlfw_InitForOpenGL(window, true)) {
fprintf(stderr, "Failed to initialize imgui OpenGL!\n");
return false;
}
if (!ImGui_ImplOpenGL3_Init(glsl_version)) {
fprintf(stderr, "Failed to initialize imgui!\n");
return false;
}
return true;
}
void UpdateFontTexture() {
if (g_FontTexture) {
ImGui_ImplOpenGL3_DestroyFontsTexture();
}
ImGui_ImplOpenGL3_CreateFontsTexture();
}
void NewFrame() {
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
}
void Render(GLFWwindow* window) {
ImGui::Render();
int display_w, display_h;
glfwGetFramebufferSize(window, &display_w, &display_h);
glViewport(0, 0, display_w, display_h);
glClearColor(0, 0, 0, 0);
glClear(GL_COLOR_BUFFER_BIT);
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
auto&& texture = g_TexturesCache.begin();
while (texture != g_TexturesCache.end()) {
texture->second.first--;
if (texture->second.first < 0) {
GLuint gl_texture = (GLuint)(intptr_t)texture->second.second;
glDeleteTextures(1, &gl_texture);
texture = g_TexturesCache.erase(texture);
}
else {
++texture;
}
}
}
void Shutdown() {
ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplGlfw_Shutdown();
ImGui::DestroyContext();
}
void SetTextureUnloadInterval(int updateCount) {
g_UnloadTextureInterval = updateCount;
}
}
// Image overloads
void Image(const GLFWimage& texture,
const glm::vec4& tintColor,
const glm::vec4& borderColor) {
Image(texture, glm::vec2(texture.width, texture.height), tintColor, borderColor);
}
void Image(const GLFWimage& texture, const glm::vec2& size,
const glm::vec4& tintColor,
const glm::vec4& borderColor) {
ImTextureID textureID =
(ImTextureID)GLFW::GetNativeTexture(texture);
ImGui::Image(textureID, size, ImVec2(0, 0), ImVec2(1, 1), tintColor,
borderColor);
}
// ImageButton overloads
bool ImageButton(const GLFWimage& texture, const int framePadding,
const glm::vec4& bgColor,
const glm::vec4& tintColor) {
return ImageButton(texture, glm::vec2(texture.width, texture.height), framePadding, bgColor, tintColor);
}
bool ImageButton(const GLFWimage& texture, const glm::vec2& size, const int framePadding,
const glm::vec4& bgColor,
const glm::vec4& tintColor) {
ImTextureID textureID =
(ImTextureID)GLFW::GetNativeTexture(texture);
return ImGui::ImageButton(textureID, size, ImVec2(0, 0), ImVec2(1, 1), framePadding, bgColor,
tintColor);
}
// Draw_list overloads. All positions are in relative coordinates (relative to top-left of the current window)
void DrawLine(const glm::vec2& a, const glm::vec2& b, const glm::vec4& col, float thickness) {
ImDrawList* draw_list = ImGui::GetWindowDrawList();
glm::vec2 pos = ImGui::GetCursorScreenPos();
draw_list->AddLine(a + pos, b + pos, ColorConvertFloat4ToU32(col),
thickness);
}
}
| 5,945 | 1,967 |
#include <iostream>
using namespace std;
int main ()
{
cout << endl; //Extra space
cout << "__________________________________________________________" << endl;
cout << "Lesson 8.3 Pointer Reassignment to Another Variable" << endl;
cout << "----------------------------------------------------------" << endl;
int Age = 30;
int* pInteger = &Age;
cout << "pInteger points to Age now " << endl;
//Display the value of the Pointer
cout << "pInteger is " << hex << pInteger << endl;
int DogsAge = 9;
pInteger = &DogsAge;
cout << "pInteger points to DogsAge now " << endl;
cout << "pInteger is " << hex << pInteger << endl;
return 0;
}
| 665 | 207 |
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_RANDOMIZER_HPP
#define SFML_RANDOMIZER_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Config.hpp>
namespace sf
{
////////////////////////////////////////////////////////////
/// Randomizer is an utility class for generating pseudo-random
/// numbers
////////////////////////////////////////////////////////////
class SFML_API Randomizer
{
public :
////////////////////////////////////////////////////////////
/// Set the seed for the generator. Using a known seed
/// allows you to reproduce the same sequence of random number
///
/// \param Seed : Number to use as the seed
///
////////////////////////////////////////////////////////////
static void SetSeed(unsigned int Seed);
////////////////////////////////////////////////////////////
/// Get the seed used to generate random numbers the generator.
///
/// \return Current seed
///
////////////////////////////////////////////////////////////
static unsigned int GetSeed();
////////////////////////////////////////////////////////////
/// Get a random float number in a given range
///
/// \return Start : Start of the range
/// \return End : End of the range
///
/// \return Random number in [Begin, End]
///
////////////////////////////////////////////////////////////
static float Random(float Begin, float End);
////////////////////////////////////////////////////////////
/// Get a random integer number in a given range
///
/// \return Start : Start of the range
/// \return End : End of the range
///
/// \return Random number in [Begin, End]
///
////////////////////////////////////////////////////////////
static int Random(int Begin, int End);
private :
////////////////////////////////////////////////////////////
// Static member variables
////////////////////////////////////////////////////////////
static unsigned int ourSeed;
};
} // namespace sf
#endif // SFML_RANDOMIZER_HPP
| 3,246 | 746 |
#include <Heap.h>
#include <Memory.h>
using namespace Kernel;
Heap::Heap(void* start_addr, u64 size)
: m_start_addr(start_addr), m_size(size)
{
Header* first_header = (Header*)start_addr;
Header* last_header = (Header*)((u64)start_addr + size - sizeof(Header));
first_header->prev = nullptr;
first_header->free = true;
first_header->first = true;
first_header->last = false;
first_header->next = last_header;
last_header->prev = first_header;
last_header->free = false;
last_header->first = false;
last_header->last = true;
last_header->next = nullptr;
}
#include <TTY.h>
void* Heap::alloc(u32 bytes) {
if (!bytes)
return nullptr;
Header* c_header = (Header*)m_start_addr;
while (!c_header->last) {
if (c_header->free) {
u32 c_size = ((u64)c_header->next - (u64)c_header) - sizeof(Header);
if (c_size >= bytes && c_size <= bytes + sizeof(Header)) {
c_header->free = false;
return (void*)((u64)c_header + sizeof(Header));
}
if (c_size >= bytes + sizeof(Header)) {
Header* new_header = (Header*)((u64)c_header + bytes + sizeof(Header));
new_header->free = true;
new_header->last = false;
new_header->first = false;
new_header->prev = c_header;
new_header->next = c_header->next;
c_header->next = new_header;
c_header->free = false;
new_header->next->prev = new_header;
return (void*)((u64)c_header + sizeof(Header));
}
}
c_header = c_header->next;
}
out << "Heap is out of memory!\n";
return nullptr;
}
void* Heap::realloc(void* addr, u32 bytes) {
if (!bytes) {
free(addr);
return nullptr;
}
if (!addr)
return alloc(bytes);
Header* header = (Header*)((u64)addr - sizeof(Header));
u32 alloc_size = (u64)header->next - (u64)header - sizeof(Header);
// TODO: When the current allocated size is smaller it should create a new header instead of free()-ing and alloc()-ing.
if (bytes > alloc_size) {
void* new_addr = alloc(bytes);
FC::Memory::copy(new_addr, addr, alloc_size);
free(addr);
return new_addr;
}
if (bytes < alloc_size) {
void* new_addr = alloc(bytes);
FC::Memory::copy(new_addr, addr, bytes);
free(addr);
return new_addr;
}
return addr;
}
void Heap::free(void* addr) {
if (!addr)
return;
Header* header = (Header*)((u64)addr - sizeof(Header));
header->free = true;
if (!header->first && header->prev->free)
erase_header(header);
if (!header->next->last && header->next->free)
erase_header(header->next);
// if (check_corruption()) {
// out << "HEAP CORRUPTED!\n";
// print_headers();
// while (true) {}
// }
}
bool Heap::check_corruption() {
Header* c_header = (Header*)m_start_addr;
Header* next_header_ptr = nullptr;
Header* prev_header_ptr = nullptr;
while (!c_header->last) {
if (next_header_ptr != c_header && next_header_ptr)
return true;
if (prev_header_ptr != c_header->prev && prev_header_ptr)
return true;
next_header_ptr = c_header->next;
prev_header_ptr = c_header;
c_header = c_header->next;
}
return false;
}
void Heap::print_headers() {
Header* c_header = (Header*)m_start_addr;
Header* next_header_ptr = nullptr;
Header* prev_header_ptr = nullptr;
while (!c_header->last) {
if (next_header_ptr != c_header && next_header_ptr)
out << "HEAP CORRUPTION DETECTED!\n";
if (prev_header_ptr != c_header->prev && prev_header_ptr)
out << "HEAP CORRUPTION DETECTED!\n";
u32 c_size = (u64)c_header->next - (u64)c_header - sizeof(Header);
if (c_header->free)
out << "FREE:\t 0x" << c_header << " size=" << (u64)c_size << "B next=" << c_header->next << " prev=" << c_header->prev << "\n";
else
out << "USED:\t 0x" << c_header << " size=" << (u64)c_size << "B next=" << c_header->next << " prev=" << c_header->prev << "\n";
next_header_ptr = c_header->next;
prev_header_ptr = c_header;
c_header = c_header->next;
}
}
| 3,911 | 1,666 |
/*
* Copyright (C) 2010 Google 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 "SkFlate.h"
#include "SkPDFCatalog.h"
#include "SkPDFStream.h"
#include "SkStream.h"
SkPDFStream::SkPDFStream(SkStream* stream) {
if (SkFlate::HaveFlate())
SkAssertResult(SkFlate::Deflate(stream, &fCompressedData));
if (SkFlate::HaveFlate() &&
fCompressedData.getOffset() < stream->getLength()) {
fLength = fCompressedData.getOffset();
insert("Filter", new SkPDFName("FlateDecode"))->unref();
} else {
fCompressedData.reset();
fPlainData = stream;
fLength = fPlainData->getLength();
}
insert("Length", new SkPDFInt(fLength))->unref();
}
SkPDFStream::~SkPDFStream() {
}
void SkPDFStream::emitObject(SkWStream* stream, SkPDFCatalog* catalog,
bool indirect) {
if (indirect)
return emitIndirectObject(stream, catalog);
this->INHERITED::emitObject(stream, catalog, false);
stream->writeText(" stream\n");
if (fPlainData.get())
stream->write(fPlainData->getMemoryBase(), fLength);
else
stream->write(fCompressedData.getStream(), fLength);
stream->writeText("\nendstream");
}
size_t SkPDFStream::getOutputSize(SkPDFCatalog* catalog, bool indirect) {
if (indirect)
return getIndirectOutputSize(catalog);
return this->INHERITED::getOutputSize(catalog, false) +
strlen(" stream\n\nendstream") + fLength;
}
| 1,994 | 624 |
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.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.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2008, 2009 Wayne Meissner
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
#include <string.h>
#include <stdlib.h>
#include <jni.h>
#include "JUtil.h"
JavaVM* jruby::jvm;
JNIEnv*
jruby::getCurrentEnv()
{
JNIEnv* env;
jvm->GetEnv((void **) & env, JNI_VERSION_1_4);
if (env == NULL) {
jvm->AttachCurrentThread((void **) & env, NULL);
}
return env;
}
void
jruby::throwExceptionByName(JNIEnv* env, const char* exceptionName, const char* fmt, ...)
{
va_list ap;
char buf[1024] = { 0 };
va_start(ap, fmt);
vsnprintf(buf, sizeof(buf) - 1, fmt, ap);
env->PushLocalFrame(10);
jclass exceptionClass = env->FindClass(exceptionName);
if (exceptionClass != NULL) {
env->ThrowNew(exceptionClass, buf);
}
env->PopLocalFrame(NULL);
va_end(ap);
}
const char* jruby::IllegalArgumentException = "java/lang/IllegalArgumentException";
const char* jruby::NullPointerException = "java/lang/NullPointerException";
const char* jruby::OutOfBoundsException = "java/lang/IndexOutOfBoundsException";
const char* jruby::OutOfMemoryException = "java/lang/OutOfMemoryError";
const char* jruby::RuntimeException = "java/lang/RuntimeException";
| 2,597 | 824 |
/****************************************************************************
** Meta object code from reading C++ file 'qvalidatedtextedit.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.6.0)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../src/qt/qvalidatedtextedit.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'qvalidatedtextedit.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.6.0. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
struct qt_meta_stringdata_QValidatedTextEdit_t {
QByteArrayData data[7];
char stringdata0[68];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_QValidatedTextEdit_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_QValidatedTextEdit_t qt_meta_stringdata_QValidatedTextEdit = {
{
QT_MOC_LITERAL(0, 0, 18), // "QValidatedTextEdit"
QT_MOC_LITERAL(1, 19, 8), // "setValid"
QT_MOC_LITERAL(2, 28, 0), // ""
QT_MOC_LITERAL(3, 29, 5), // "valid"
QT_MOC_LITERAL(4, 35, 12), // "setErrorText"
QT_MOC_LITERAL(5, 48, 9), // "errorText"
QT_MOC_LITERAL(6, 58, 9) // "markValid"
},
"QValidatedTextEdit\0setValid\0\0valid\0"
"setErrorText\0errorText\0markValid"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_QValidatedTextEdit[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
3, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: name, argc, parameters, tag, flags
1, 1, 29, 2, 0x0a /* Public */,
4, 1, 32, 2, 0x0a /* Public */,
6, 0, 35, 2, 0x08 /* Private */,
// slots: parameters
QMetaType::Void, QMetaType::Bool, 3,
QMetaType::Void, QMetaType::QString, 5,
QMetaType::Void,
0 // eod
};
void QValidatedTextEdit::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
Q_ASSERT(staticMetaObject.cast(_o));
QValidatedTextEdit *_t = static_cast<QValidatedTextEdit *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->setValid((*reinterpret_cast< bool(*)>(_a[1]))); break;
case 1: _t->setErrorText((*reinterpret_cast< QString(*)>(_a[1]))); break;
case 2: _t->markValid(); break;
default: ;
}
}
}
const QMetaObject QValidatedTextEdit::staticMetaObject = {
{ &QPlainTextEdit::staticMetaObject, qt_meta_stringdata_QValidatedTextEdit.data,
qt_meta_data_QValidatedTextEdit, qt_static_metacall, Q_NULLPTR, Q_NULLPTR}
};
const QMetaObject *QValidatedTextEdit::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *QValidatedTextEdit::qt_metacast(const char *_clname)
{
if (!_clname) return Q_NULLPTR;
if (!strcmp(_clname, qt_meta_stringdata_QValidatedTextEdit.stringdata0))
return static_cast<void*>(const_cast< QValidatedTextEdit*>(this));
return QPlainTextEdit::qt_metacast(_clname);
}
int QValidatedTextEdit::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QPlainTextEdit::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 3)
qt_static_metacall(this, _c, _id, _a);
_id -= 3;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 3)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 3;
}
return _id;
}
QT_END_MOC_NAMESPACE
| 4,204 | 1,644 |
#include <functional>
#include <string>
#include <vector>
struct SuffixArray {
int N, k;
std::string S;
std::vector<int> sa, rank, tmp;
std::vector<int> lcp, rank_lcp;
SuffixArray(std::string &S)
: N(S.size()), S(S), sa(N + 1), rank(N + 1), tmp(N + 1) {
construct();
}
void construct() {
for (int i = 0; i <= N; i++) {
sa[i] = i;
rank[i] = i < N ? S[i] : -1;
}
std::function<bool(int, int)> compare = [&](int i, int j) {
if (rank[i] != rank[j]) {
return rank[i] < rank[j];
} else {
int ri = i + k <= N ? rank[i + k] : -1;
int rj = j + k <= N ? rank[j + k] : -1;
return ri < rj;
}
};
for (k = 1; k <= N; k *= 2) {
sort(sa.begin(), sa.end(), compare);
tmp[sa[0]] = 0;
for (int i = 1; i <= N; i++) {
tmp[sa[i]] = tmp[sa[i - 1]] + (compare(sa[i - 1], sa[i]) ? 1 : 0);
}
for (int i = 0; i <= N; i++) rank[i] = tmp[i];
}
}
bool contain(const std::string &T) const {
int left = 0, right = N;
while (left + 1 < right) {
int mid = (left + right) / 2;
(S.compare(sa[mid], T.length(), T) < 0 ? left : right) = mid;
}
return S.compare(sa[right], T.length(), T) == 0;
}
void construct_lcp() {
lcp.resize(N), rank_lcp.resize(N + 1);
for (int i = 0; i <= N; i++) rank_lcp[sa[i]] = i;
int h = 0;
lcp[0] = 0;
for (int i = 0; i < N; i++) {
int j = sa[rank[i] - 1];
if (h > 0) h--;
for (; j + h < N and i + h < N; h++) {
if (S[j + h] != S[i + h]) break;
}
lcp[rank[i] - 1] = h;
}
}
};
| 1,623 | 732 |
/**
* ofxMPMFluid.cpp
* The MIT License (MIT)
* Copyright (c) 2010 respective 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.
*
*****************************************
* MPM FLuid Simulation Demo
* OpenFrameworks version by Golan Levin
* http://www.flong.com
*
* ofxAddon created by James George (@obviousjm)
* http://www.jamesgeorge.org
*
* Original Java version:
* http://grantkot.com/MPM/Liquid.html
*
* Flash version:
* Copyright iunpin ( http://wonderfl.net/user/iunpin )
* MIT License ( http://www.opensource.org/licenses/mit-license.php )
* Downloaded from: http://wonderfl.net/c/6eu4
*
* Javascript version:
* Copyright Stephen Sinclair (radarsat1) ( http://www.music.mcgill.ca/~sinclair )
* MIT License ( http://www.opensource.org/licenses/mit-license.php )
* Downloaded from: http://www.music.mcgill.ca/~sinclair/blog
*/
#include "ofxMPMObstacle.h"
ofxMPMObstacle::ofxMPMObstacle ( float inx, float iny, float inr) {
cx = inx;
cy = iny;
radius = inr;
radius2 = radius * radius;
} | 2,082 | 734 |
// vi: set et ts=4 sw=2 sts=2:
#ifndef HMAT_HMATRIX_DENSE_COMPRESSOR_HPP
#define HMAT_HMATRIX_DENSE_COMPRESSOR_HPP
#include "common.hpp"
#include "hmatrix_compressor.hpp"
#include "data_accessor.hpp"
namespace hmat {
template <typename ValueType, int N>
class HMatrixDenseCompressor : public HMatrixCompressor<ValueType, N> {
public:
HMatrixDenseCompressor(const DataAccessor<ValueType, N> &dataAccessor);
void compressBlock(const BlockClusterTreeNode<N> &blockClusterTreeNode,
shared_ptr<HMatrixData<ValueType>> &hMatrixData) const
override;
private:
const DataAccessor<ValueType, N> &m_dataAccessor;
};
}
#include "hmatrix_dense_compressor_impl.hpp"
#endif
| 700 | 261 |
//
// Created by Ciaran on 05/02/2021.
//
#include <algorithm>
#include "OptItems.h"
#include "Error.h"
namespace opt {
OptItems::OptItems(std::vector<OptItem> optItems)
: optItems_(std::move(optItems)) {}
OptItems::OptItems(const std::vector<double> &startingValues, const std::vector<double> &lb,
const std::vector<double> &ub) {
int s1 = startingValues.size();
int s2 = lb.size();
int s3 = ub.size();
std::vector<int> sizes({s1, s2, s3});
bool equal = false;
if (std::adjacent_find(sizes.begin(), sizes.end(), std::not_equal_to<>()) == sizes.end()) {
equal = true;
}
if (!equal) {
LOGIC_ERROR << "Input vectors are not equal sizes. The startingValues vector is "
<< s1 << "; the lb vector is: " << s2
<< "; and the ub vector is " << s3 << std::endl;
}
for (int i = 0; i < startingValues.size(); i++) {
optItems_.emplace_back(startingValues[i], lb[i], ub[i]);
}
}
OptItems::OptItems(std::initializer_list<OptItem> optItems)
: optItems_(std::vector<OptItem>(optItems.begin(), optItems.end())) {}
int OptItems::size() {
return optItems_.size();
}
std::vector<OptItem>::iterator OptItems::begin() {
return optItems_.begin();
}
std::vector<OptItem>::iterator OptItems::end() {
return optItems_.end();
}
OptItem &OptItems::operator[](int index) {
return optItems_[index];
}
}
| 1,584 | 507 |
/* $Id: Cit_proc.cpp 272611 2011-04-08 18:57:08Z ucko $
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Author: .......
*
* File Description:
* .......
*
* Remark:
* This code was originally generated by application DATATOOL
* using specifications from the ASN data definition file
* 'biblio.asn'.
*/
// standard includes
// generated includes
#include <ncbi_pch.hpp>
#include <objects/biblio/Cit_proc.hpp>
// generated classes
BEGIN_NCBI_SCOPE
BEGIN_objects_SCOPE // namespace ncbi::objects::
// destructor
CCit_proc::~CCit_proc(void)
{
}
bool CCit_proc::GetLabelV1(string* label, TLabelFlags flags) const
{
// return GetBook().GetLabelV1(label, flags);
return GetBook().GetLabel(label, flags, eLabel_V1);
}
bool CCit_proc::GetLabelV2(string* label, TLabelFlags flags) const
{
return GetBook().GetLabel(label, flags, eLabel_V2);
}
END_objects_SCOPE // namespace ncbi::objects::
END_NCBI_SCOPE
/* Original file checksum: lines: 61, chars: 1883, CRC32: 78b997ee */
| 2,222 | 664 |
// Copyright (C) 2018-2020 Vincent Chambrin
// This file is part of the libscript library
// For conditions of distribution and use, see copyright notice in LICENSE
#include "script/templateargumentprocessor.h"
#include "script/class.h"
#include "script/classtemplate.h"
#include "script/classtemplateinstancebuilder.h"
#include "script/diagnosticmessage.h"
#include "script/private/template_p.h"
#include "script/compiler/compilererrors.h"
#include "script/compiler/literalprocessor.h"
#include "script/compiler/nameresolver.h"
#include "script/compiler/typeresolver.h"
#include "script/ast/node.h"
#include "script/compiler/compiler.h"
namespace script
{
TemplateArgument TemplateArgumentProcessor::argument(const Scope & scp, const std::shared_ptr<ast::Node> & arg)
{
if (arg->is<ast::Identifier>())
{
auto name = std::static_pointer_cast<ast::Identifier>(arg);
NameLookup lookup = NameLookup::resolve(name, scp);
if (lookup.resultType() == NameLookup::TypeName)
return TemplateArgument{ lookup.typeResult() };
else
throw compiler::CompilationFailure{ CompilerError::InvalidTemplateArgument };
}
else if (arg->is<ast::Literal>())
{
const ast::Literal & l = arg->as<ast::Literal>();
if (l.is<ast::BoolLiteral>())
return TemplateArgument{ l.token == parser::Token::True };
else if (l.is<ast::IntegerLiteral>())
return TemplateArgument{ compiler::LiteralProcessor::generate(std::static_pointer_cast<ast::IntegerLiteral>(arg)) };
else
throw compiler::CompilationFailure{ CompilerError::InvalidLiteralTemplateArgument };
}
else if (arg->is<ast::TypeNode>())
{
auto type = std::static_pointer_cast<ast::TypeNode>(arg);
compiler::TypeResolver r;
return TemplateArgument{ r.resolve(type->value, scp) };
}
throw compiler::CompilationFailure{ CompilerError::InvalidTemplateArgument };
}
std::vector<TemplateArgument> TemplateArgumentProcessor::arguments(const Scope & scp, const std::vector<std::shared_ptr<ast::Node>> & args)
{
std::vector<TemplateArgument> result;
result.reserve(args.size());
for (const auto & a : args)
result.push_back(argument(scp, a));
return result;
}
Class TemplateArgumentProcessor::instantiate(ClassTemplate & ct, const std::vector<TemplateArgument> & args)
{
ClassTemplateInstanceBuilder builder{ ct, std::vector<TemplateArgument>{ args} };
Class ret = ct.backend()->instantiate(builder);
ct.impl()->instances[args] = ret;
return ret;
}
Class TemplateArgumentProcessor::process(const Scope & scp, ClassTemplate & ct, const std::shared_ptr<ast::TemplateIdentifier> & tmplt)
{
try
{
std::vector<TemplateArgument> targs = arguments(scp, tmplt->arguments);
complete(ct, scp, targs);
Class c;
const bool result = ct.hasInstance(targs, &c);
if (result)
return c;
return instantiate(ct, targs);
}
catch (const compiler::CompilationFailure& ex)
{
// silently discard the error
(void)ex;
}
catch (const TemplateInstantiationError & error)
{
// silently discard the error
(void)error;
}
return Class{};
}
void TemplateArgumentProcessor::complete(const Template & t, const Scope &scp, std::vector<TemplateArgument> & args)
{
if (t.parameters().size() == args.size())
return;
for (size_t i(0); i < t.parameters().size(); ++i)
{
if (!t.parameters().at(i).hasDefaultValue())
throw compiler::CompilationFailure{ CompilerError::MissingNonDefaultedTemplateParameter };
TemplateArgument arg = argument(scp, t.parameters().at(i).defaultValue());
args.push_back(arg);
}
}
const std::vector<std::shared_ptr<ast::Node>> & TemplateArgumentProcessor::getTemplateArguments(const std::shared_ptr<ast::Identifier> & tname)
{
if (tname->is<ast::TemplateIdentifier>())
{
const auto & name = tname->as<ast::TemplateIdentifier>();
return name.arguments;
}
else if (tname->is<ast::ScopedIdentifier>())
{
return getTemplateArguments(tname->as<ast::ScopedIdentifier>().rhs);
}
throw std::runtime_error{ "Bad call to TemplateArgumentProcessor::getTemplateArguments()" };
}
} // namespace script
| 4,139 | 1,302 |
/*
* Copyright (c) 2018 MariaDB Corporation Ab
*
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file and at www.mariadb.com/bsl11.
*
* Change Date: 2026-01-04
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2 or later of the General
* Public License.
*/
#pragma once
#include <maxbase/ccdefs.hh>
#include <stdexcept>
#include <maxbase/log.h>
enum mxb_log_target_t
{
MXB_LOG_TARGET_DEFAULT,
MXB_LOG_TARGET_FS, // File system
MXB_LOG_TARGET_STDOUT, // Standard output
};
/**
* Prototype for function providing additional information.
*
* If the function returns a non-zero value, that amount of characters
* will be enclosed between '(' and ')', and written first to a logged
* message.
*
* @param buffer Buffer where additional context may be written.
* @param len Length of @c buffer.
*
* @return Length of data written to buffer.
*/
using mxb_log_context_provider_t = size_t (*)(char* buffer, size_t len);
using mxb_in_memory_log_t = void (*)(const std::string& buffer);
/**
* Typedef for conditional logging callback.
*
* @param priority The syslog priority under which the message is logged.
* @return True if the message should be logged, false if it should be suppressed.
*/
using mxb_should_log_t = bool (*)(int priority);
/**
* @brief Initialize the log
*
* This function must be called before any of the log function should be
* used.
*
* @param ident The syslog ident. If NULL, then the program name is used.
* @param logdir The directory for the log file. If NULL, file output is discarded.
* @param filename The name of the log-file. If NULL, the program name will be used
* if it can be deduced, otherwise the name will be "messages.log".
* @param target Logging target
* @param context_provider Optional function for providing contextual information
* at logging time.
*
* @return true if succeed, otherwise false
*/
bool mxb_log_init(const char* ident, const char* logdir, const char* filename,
mxb_log_target_t target, mxb_log_context_provider_t context_provider,
mxb_in_memory_log_t in_memory_log, mxb_should_log_t should_log);
/**
* @brief Finalize the log
*
* A successfull call to @c max_log_init() should be followed by a call
* to this function before the process exits.
*/
void mxb_log_finish();
/**
* @brief Initialize the log
*
* This function initializes the log using
* - the program name as the syslog ident,
* - the current directory as the logdir, and
* - the default log name (program name + ".log").
*
* @param target The specified target for the logging.
*
* @return True if succeeded, false otherwise.
*/
inline bool mxb_log_init(mxb_log_target_t target = MXB_LOG_TARGET_FS)
{
return mxb_log_init(nullptr, ".", nullptr, target, nullptr, nullptr, nullptr);
}
namespace maxbase
{
/**
* @class Log
*
* A simple utility RAII class where the constructor initializes the log and
* the destructor finalizes it.
*/
class Log
{
Log(const Log&) = delete;
Log& operator=(const Log&) = delete;
public:
Log(const char* ident,
const char* logdir,
const char* filename,
mxb_log_target_t target,
mxb_log_context_provider_t context_provider,
mxb_in_memory_log_t in_memory_log,
mxb_should_log_t should_log)
{
if (!mxb_log_init(ident, logdir, filename, target, context_provider, in_memory_log, should_log))
{
throw std::runtime_error("Failed to initialize the log.");
}
}
Log(mxb_log_target_t target = MXB_LOG_TARGET_FS)
: Log(nullptr, ".", nullptr, target, nullptr, nullptr, nullptr)
{
}
~Log()
{
mxb_log_finish();
}
};
// RAII class for setting and clearing the "scope" of the log messages. Adds the given object name to log
// messages as long as the object is alive.
class LogScope
{
public:
LogScope(const LogScope&) = delete;
LogScope& operator=(const LogScope&) = delete;
explicit LogScope(const char* name)
: m_prev_scope(s_current_scope)
, m_name(name)
{
s_current_scope = this;
}
~LogScope()
{
s_current_scope = m_prev_scope;
}
static const char* current_scope()
{
return s_current_scope ? s_current_scope->m_name : nullptr;
}
private:
LogScope* m_prev_scope;
const char* m_name;
static thread_local LogScope* s_current_scope;
};
// Class for redirecting the thread-local log message stream to a different handler. Only one of these should
// be constructed in the callstack.
class LogRedirect
{
public:
LogRedirect(const LogRedirect&) = delete;
LogRedirect& operator=(const LogRedirect&) = delete;
/**
* The message handler type
*
* @param level Syslog log level of the message
* @param msg The message itself
*
* @return True if the message was consumed (i.e. it should not be logged)
*/
using Func = bool (*)(int level, const std::string& msg);
explicit LogRedirect(Func func);
~LogRedirect();
static Func current_redirect();
private:
static thread_local Func s_redirect;
};
#define MXB_STREAM_LOG_HELPER(CMXBLOGLEVEL__, mxb_msg_str__) \
do { \
if (!mxb_log_is_priority_enabled(CMXBLOGLEVEL__)) \
{ \
break; \
} \
thread_local std::ostringstream os; \
os.str(std::string()); \
os << mxb_msg_str__; \
mxb_log_message(CMXBLOGLEVEL__, MXB_MODULE_NAME, __FILE__, __LINE__, \
__func__, "%s", os.str().c_str()); \
} while (false)
#define MXB_SALERT(mxb_msg_str__) MXB_STREAM_LOG_HELPER(LOG_ALERT, mxb_msg_str__)
#define MXB_SERROR(mxb_msg_str__) MXB_STREAM_LOG_HELPER(LOG_ERR, mxb_msg_str__)
#define MXB_SWARNING(mxb_msg_str__) MXB_STREAM_LOG_HELPER(LOG_WARNING, mxb_msg_str__)
#define MXB_SNOTICE(mxb_msg_str__) MXB_STREAM_LOG_HELPER(LOG_NOTICE, mxb_msg_str__)
#define MXB_SINFO(mxb_msg_str__) MXB_STREAM_LOG_HELPER(LOG_INFO, mxb_msg_str__)
#if defined (SS_DEBUG)
#define MXB_SDEBUG(mxb_msg_str__) MXB_STREAM_LOG_HELPER(LOG_DEBUG, mxb_msg_str__)
#else
#define MXB_SDEBUG(mxb_msg_str__)
#endif
}
| 6,407 | 2,169 |
//
// Created by hejia on 9/22/19.
//
#include "ai/external/hauser_parabolic_smoother/HauserUtil.h"
#include "ai/external/hauser_parabolic_smoother/DynamicPath.h"
namespace wecook {
namespace ai {
namespace external {
namespace hauser_parabolic_smoother {
//==============================================================================
ParabolicRamp::Vector toVector(const Eigen::VectorXd &_x) {
ParabolicRamp::Vector output(_x.size());
for (int i = 0; i < _x.size(); ++i)
output[i] = _x[i];
return output;
}
//==============================================================================
Eigen::VectorXd toEigen(const ParabolicRamp::Vector &_x) {
Eigen::VectorXd output(_x.size());
for (std::size_t i = 0; i < _x.size(); ++i)
output[i] = _x[i];
return output;
}
//==============================================================================
void evaluateAtTime(const ParabolicRamp::DynamicPath &_path,
double _t,
Eigen::VectorXd &_position,
Eigen::VectorXd &_velocity) {
ParabolicRamp::Vector positionVector;
_path.Evaluate(_t, positionVector);
_position = toEigen(positionVector);
ParabolicRamp::Vector velocityVector;
_path.Derivative(_t, velocityVector);
_velocity = toEigen(velocityVector);
}
}
}
}
}
| 1,310 | 434 |
/*
Copyright 2020 The OneFlow Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "oneflow/xrt/tensorrt/ops/op_context.h"
#include "oneflow/xrt/tensorrt/trt_value.h"
namespace oneflow {
namespace xrt {
namespace tensorrt {
const std::string &TrtOpContext::SoleOutputName() const {
CHECK_EQ(num_outputs(), 1);
return param_.output_names.front();
}
nvinfer1::ITensor *TrtOpContext::Input(const std::string &name) {
return Input(ArgumentFromKey(name));
}
nvinfer1::ITensor *TrtOpContext::Output(const std::string &name) {
return Output(ArgumentFromKey(name));
}
nvinfer1::ITensor *TrtOpContext::Input(const Argument &arg) {
CHECK_GT(param_.inputs.count(arg), 0);
return param_.inputs.at(arg).AsTensor(builder());
}
nvinfer1::ITensor *TrtOpContext::Output(const Argument &arg) {
CHECK_GT(outputs_.count(arg), 0);
return outputs_.at(arg).AsTensor(builder());
}
nvinfer1::ITensor *TrtOpContext::SoleInput() {
CHECK_EQ(num_inputs(), 1);
auto it = param_.inputs.begin();
return (it->second).AsTensor(builder());
}
nvinfer1::ITensor *TrtOpContext::SoleOutput() {
CHECK_EQ(outputs_.size(), 1);
auto it = outputs_.begin();
return (it->second).AsTensor(builder());
}
nvinfer1::Weights &TrtOpContext::Weight(const std::string &name) {
return Weight(ArgumentFromKey(name));
}
nvinfer1::Weights &TrtOpContext::Weight(const Argument &arg) {
CHECK_GT(param_.inputs.count(arg), 0);
return param_.inputs.at(arg).AsWeight(builder());
}
void TrtOpContext::SetOutput(const std::string &name, nvinfer1::ITensor *tensor) {
SetOutput(name, TrtValue::Tensor(builder(), tensor));
}
void TrtOpContext::SetOutput(const std::string &name, const TrtValue &value) {
Argument arg = ArgumentFromKey(name);
outputs_[arg] = value;
nvinfer1::ITensor *tensor = builder()->GetTensor(value.handle());
tensor->setName(arg.name().c_str());
}
void TrtOpContext::SetSoleOutput(nvinfer1::ITensor *tensor) {
CHECK_EQ(outputs_.size(), 0);
SetOutput(SoleOutputName(), tensor);
}
DataType TrtOpContext::InputType(const std::string &name) const {
return ArgumentFromKey(name).data_type();
}
DataType TrtOpContext::SoleInputType() const {
CHECK_EQ(num_inputs(), 1);
auto it = param_.inputs.begin();
return (it->first).data_type();
}
DataType TrtOpContext::OutputType(const std::string &name) const {
return ArgumentFromKey(name).data_type();
}
DataType TrtOpContext::SoleOutputType() const {
return ArgumentFromKey(SoleOutputName()).data_type();
}
Shape TrtOpContext::InputShape(const std::string &name) const {
return ArgumentFromKey(name).shape();
}
Shape TrtOpContext::SoleInputShape() const {
CHECK_EQ(num_inputs(), 1);
auto it = param_.inputs.begin();
return (it->first).shape();
}
Shape TrtOpContext::OutputShape(const std::string &name) const {
return ArgumentFromKey(name).shape();
}
Shape TrtOpContext::SoleOutputShape() const {
return ArgumentFromKey(SoleOutputName()).shape();
}
bool TrtOpContext::HasInput(const std::string &name) const {
return param_.arguments.count(name) > 0;
}
Argument TrtOpContext::ArgumentFromKey(const std::string &key) const {
CHECK_GT(param_.arguments.count(key), 0);
return param_.arguments.at(key);
}
} // namespace tensorrt
} // namespace xrt
} // namespace oneflow
| 3,777 | 1,295 |
//
// ImageProgressing.hpp
// Kessler Syndrome
//
// Created by Shamyl Zakariya on 11/30/17.
//
#ifndef ImageProcessing_hpp
#define ImageProcessing_hpp
#include <cinder/Channel.h>
#include <cinder/Perlin.h>
#include "core/Common.hpp"
#include "core/MathHelpers.hpp"
namespace core {
namespace util {
namespace ip {
// perform a dilation pass such that each pixel in dst image is the max of the pixels in src kernel for that pixel
void dilate(const Channel8u &src, Channel8u &dst, int radius);
// perform a dilation pass such that each pixel in dst image is the min of the pixels in src kernel for that pixel
void erode(const Channel8u &src, Channel8u &dst, int radius);
// acting on copy of `src, floodfill into `dst
void floodfill(const Channel8u &src, Channel8u &dst, ivec2 start, uint8_t targetValue, uint8_t newValue, bool copy);
// remap values in `src which are of value `targetValue to `newTargetValue; all other values are converted to `defaultValue
void remap(const Channel8u &src, Channel8u &dst, uint8_t targetValue, uint8_t newTargetValue, uint8_t defaultValue);
// perform blur of size `radius of `src into `dst
void blur(const Channel8u &src, Channel8u &dst, int radius);
// for every value in src, maxV if pixelV >= threshV else minV
void threshold(const Channel8u &src, Channel8u &dst, uint8_t threshV = 128, uint8_t maxV = 255, uint8_t minV = 0);
// apply vignette effect to src, into dst, where pixels have vignetteColor applied as pixel radius from center approaches outerRadius
void vignette(const Channel8u &src, Channel8u &dst, double innerRadius, double outerRadius, uint8_t vignetteColor = 0);
// perform a dilation pass such that each pixel in result image is the max of the pixels in the kernel
inline Channel8u dilate(const Channel8u &src, int size) {
Channel8u dst;
::core::util::ip::dilate(src, dst, size);
return dst;
}
// perform a dilation pass such that each pixel in result image is the min of the pixels in the kernel
inline Channel8u erode(const Channel8u &src, int size) {
Channel8u dst;
::core::util::ip::erode(src, dst, size);
return dst;
}
// remap values in `src which are of value `targetValue to `newTargetValue; all other values are converted to `defaultValue
inline Channel8u remap(const Channel8u &src, uint8_t targetValue, uint8_t newTargetValue, uint8_t defaultValue) {
Channel8u dst;
::core::util::ip::remap(src, dst, targetValue, newTargetValue, defaultValue);
return dst;
}
// perform blur of size `radius
inline Channel8u blur(const Channel8u &src, int radius) {
Channel8u dst;
::core::util::ip::blur(src, dst, radius);
return dst;
}
// for every value in src, maxV if pixelV >= threshV else minV
inline Channel8u threshold(const Channel8u &src, uint8_t threshV = 128, uint8_t maxV = 255, uint8_t minV = 0) {
Channel8u dst;
::core::util::ip::threshold(src, dst, threshV, maxV, minV);
return dst;
}
// apply vignette effect to src, where pixels have vignetteColor applied as pixel radius from center approaches outerRadius
inline Channel8u vignette(const Channel8u &src, double innerRadius, double outerRadius, uint8_t vignetteColor = 0) {
Channel8u dst;
::core::util::ip::vignette(src, dst, innerRadius, outerRadius, vignetteColor);
return dst;
}
namespace in_place {
// operations which can act on a single channel, in-place, safely
// fill all pixels in channel with a given value
void fill(Channel8u &channel, uint8_t value);
// fill all pixels of rect in channel with a given value
void fill(Channel8u &channel, Area rect, uint8_t value);
// fill all pixels of channel with noise at a given frequency
void perlin(Channel8u &channel, Perlin &noise, double frequency);
// add value of the perlin noise function, scaled, to each existing pixel
void perlin_add(Channel8u &channel, Perlin &noise, double frequency, double scale);
// fill all pixels of channel with noise at a given frequency, where the noise is absoluted and thresholded
void perlin_abs_thresh(Channel8u &channel, Perlin &noise, double frequency, uint8_t threshold);
// flood fill into channel starting at `start, where pixels of `targetValue are changed to `newValue - modifies `channel
inline void floodfill(Channel8u &channel, ivec2 start, uint8_t targetValue, uint8_t newValue) {
::core::util::ip::floodfill(channel, channel, start, targetValue, newValue, false);
}
// remap values in `src which are of value `targetValue to `newTargetValue; all other values are converted to `defaultValue
inline void remap(Channel8u &channel, uint8_t targetValue, uint8_t newTargetValue, uint8_t defaultValue) {
::core::util::ip::remap(channel, channel, targetValue, newTargetValue, defaultValue);
}
// for every value in src, maxV if pixelV >= threshV else minV
inline void threshold(Channel8u &channel, uint8_t threshV = 128, uint8_t maxV = 255, uint8_t minV = 0) {
::core::util::ip::threshold(channel, channel, threshV, maxV, minV);
}
// apply vignette effect to src, where pixels have vignetteColor applied as pixel radius from center approaches outerRadius
inline void vignette(Channel8u &src, double innerRadius, double outerRadius, uint8_t vignetteColor = 0) {
::core::util::ip::vignette(src, src, innerRadius, outerRadius, vignetteColor);
}
}
}
}
} // end namespace core::util::ip
#endif /* ImageProcessing_hpp */
| 6,577 | 1,765 |
#pragma once
#include "wx/dialog.h"
#include "wx/textctrl.h"
#include "wx/button.h"
class cDialogConfigureDetection : public wxDialog {
public:
cDialogConfigureDetection ( wxWindow * parent, wxWindowID id, const wxString & title,
const wxPoint & pos,
const wxSize & size,
wxString& yoloCfg, wxString& yoloWeight, wxString& yoloClasses);
~cDialogConfigureDetection();
wxTextCtrl * dialogText;
wxString GetText();
// private:
// void OnOk(wxCommandEvent & event);
};
| 510 | 200 |
/*
* Copyright 2017 Igor Maculan <n3wtron@gmail.com>
*
* 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 <importp12dialog.h>
#include <ui_importp12dialog.h>
#include <QShowEvent>
#include <QFileDialog>
#include <QMessageBox>
#include <QtConcurrent/QtConcurrent>
ImportP12Dialog::ImportP12Dialog(QWidget *parent, SmartCardReader **smartCardReader) :
QDialog(parent),
ui(new Ui::ImportP12Dialog)
{
ui->setupUi(this);
this->smartCardReader = smartCardReader;
connect(ui->browseBtn,SIGNAL(clicked()),this,SLOT(browseFile()));
connect(ui->importBtn,SIGNAL(clicked()),this,SLOT(importP12()));
connect(ui->cancelBtn,SIGNAL(clicked()),this,SLOT(close()));
}
void ImportP12Dialog::browseFile(){
QString fileName = QFileDialog::getOpenFileName(this,tr("Open PEM Private Key"));
ui->privKeyFilePathEdt->setText(fileName);
}
void ImportP12Dialog::importP12(){
this->setEnabled(false);
QApplication::setOverrideCursor(Qt::WaitCursor);
if (*(this->smartCardReader)!=nullptr){
SmartCard* smCard = (*this->smartCardReader)->getSmartCard();
if (smCard!=NULL){
if (ui->privKeyFilePathEdt->text().isEmpty()){
QMessageBox::critical(this,tr("Import Private Key"),tr("Cannot import private key without a selected file"));
this->setEnabled(true);
QApplication::restoreOverrideCursor();
return;
}
QFile privKeyFile(ui->privKeyFilePathEdt->text());
if (!privKeyFile.exists()){
QMessageBox::critical(this,tr("Import Private Key"),tr("Cannot import private key. file does not exist"));
this->setEnabled(true);
QApplication::restoreOverrideCursor();
return;
}
Either<QString, bool> result = smCard->storeP12(ui->privKeyFilePathEdt->text(),ui->passwordEdt->text(),ui->labelEdt->text(),ui->idEdt->text().toInt());
if (result.isLeft){
QMessageBox::critical(this,tr("Import Private Key"),result.leftValue);
}else{
emit(this->imported());
this->close();
}
}
}
QApplication::restoreOverrideCursor();
this->setEnabled(true);
}
ImportP12Dialog::~ImportP12Dialog()
{
delete ui;
}
| 2,847 | 864 |
// Created on 15-07-2019 18:51:46 by necronomicon
#include <bits/stdc++.h>
using namespace std;
#define MP make_pair
#define PB push_back
#define ARR_MAX (int)1e5 //Max array length
#define INF (int)1e9 //10^9
#define EPS 1e-9 //10^-9
#define MOD 1000000007 //10^9+7
#define PI 3.1415926535897932384626433832795
typedef long int int32;
typedef unsigned long int uint32;
typedef long long int int64;
typedef unsigned long long int uint64;
typedef pair<int, int> Pii;
typedef vector<int> Vi;
typedef vector<string> Vs;
typedef vector<Pii> VPii;
typedef vector<Vi> VVi;
typedef map<int,int> Mii;
typedef set<int> Si;
typedef multimap<int,int> MMii;
typedef multiset<int> MSi;
typedef unordered_map<int,int> UMii;
typedef unordered_set<int> USi;
typedef unordered_multimap<int,int> UMMii;
typedef unordered_multiset<int> UMSi;
typedef priority_queue<int> PQi;
typedef queue<int> Qi;
typedef deque<int> DQi;
/*
We need 3 vectors : visited, ids and low (explained below)
Slow Algo:
Run dfs and find number of Connected components
for each vertex, remove it and run dfs, see if number of Connected Components increase. If it does then its an articulation point.
for each edge remove it and see if number of Connected Components increase. If it does then its an bridge.
Faster algo takes O(n) check it in single dfs.
Doesnt count if CC increase
Algo:
call dfs with 2 params the node to visit and its parent.
increment the global id/time
assign this node's id and low with it
call all the children of this node
if the node has children as parent skip it
if the child is already visited and child has lower low than id of current node then this child is an ancestor.
else child isnt discovered
if its low is lesser than id of current then this is bridge
if its low is lesser than or equal to id of current then this is artPoint
Time Complexity: O(n)
Space Complexity: O(n)
below links have same implementations
https://cp-algorithms.com/graph/cutpoints.html
https://www.youtube.com/watch?v=aZXi1unBdJA
*/
int id;
vector<bool> visited;
Vi ids; // stores uniqueId or timestamp based on discovery of node during dfs
Vi low; // stores the minimum uniqueId reachable from that node
VPii bridges; //contains the list of bridge-edges which can break the graph into more sets
Vi articulationPoints; //contains the list of cut-points which can break the graph into more sets
void dfs(VVi Adj, int at, int parent){
visited[at] = true;
id++;
low[at] = ids[at] = id;
int children = 0;
for (int to: Adj[at])
{
if(to == parent) continue; // if backedge to parent we dont do anything
if(visited[to]){ // this is backedge to an ancestor and we need its id as our low
low[at] = min(low[at], ids[to]);
}
else{ // a child is discovered which is undiscovered and we need to update our low with its low (not its id)
dfs(Adj, to, at);
low[at] = min(low[at], low[to]);
if(ids[at] < low[to]){ // if child (to) is not linked to an ancestor above (at)
bridges.push_back({at, to});
}
if(ids[at] <= low[to] && parent != -1){ // if the child has lowest
articulationPoints.push_back(at);
}
children++; // only required for checking if the root can be an articulation point. When dfs starts from root and marks all nodes visited then this remains 1 hence not artPoint.
}
}
if(parent == -1 && children > 1){
articulationPoints.push_back(at);
}
}
void find(VVi Adj){
visited = vector<bool>(Adj.size(), false),
ids = Vi(Adj.size(), 0),
low = Vi(Adj.size(), 0),
id = -1;
bridges.clear();
articulationPoints.clear();
for(int i=0; i<Adj.size(); i++){
if(!visited[i]){
dfs(Adj, i, -1);
}
}
}
int main (int argc, char const *argv[]) {
VVi Adj; // Adjency list
Adj = {
{1,2},
{0,2},
{0,1,3,5},
{2,4},
{3},
{2,6,8},
{5,7},
{6,8},
{5,7}
};
// Adj = {
// {1},
// {2,3,4,5},
// {1},
// {1},
// {1, 5},
// {1, 4}
// };
// Adj = {
// {1,2},
// {0,2},
// {0,1}
// };
find(Adj);
std::for_each(std::begin(bridges), std::end(bridges), [](Pii p) {
cout << p.first << ' ' << p.second << endl;
});
cout << endl;
std::for_each(std::begin(articulationPoints), std::end(articulationPoints), [](int x) {
cout << x << ' ';
});
return EXIT_SUCCESS;
}
| 4,822 | 1,746 |
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "hdi_composer.h"
namespace OHOS {
namespace HDI {
namespace DISPLAY {
HdiComposer::HdiComposer(std::unique_ptr<HdiComposition> pre, std::unique_ptr<HdiComposition> post)
{
mPreComp = std::move(pre);
mPostComp = std::move(post);
}
int32_t HdiComposer::Prepare(std::vector<HdiLayer *> &layers, HdiLayer &clientLayer)
{
int ret = mPreComp->SetLayers(layers, clientLayer);
DISPLAY_CHK_RETURN((ret != DISPLAY_SUCCESS), DISPLAY_FAILURE, DISPLAY_LOGE("pre composition prepare failed"));
ret = mPostComp->SetLayers(layers, clientLayer);
DISPLAY_CHK_RETURN((ret != DISPLAY_SUCCESS), DISPLAY_FAILURE, DISPLAY_LOGE("post composition prepare failed"));
return DISPLAY_SUCCESS;
}
int32_t HdiComposer::Commit(bool modeSet)
{
int ret = mPreComp->Apply(modeSet);
DISPLAY_CHK_RETURN((ret != DISPLAY_SUCCESS), DISPLAY_FAILURE, DISPLAY_LOGE("pre composition apply failed"));
ret = mPostComp->Apply(modeSet);
DISPLAY_CHK_RETURN((ret != DISPLAY_SUCCESS), DISPLAY_FAILURE, DISPLAY_LOGE("post composition apply failed"));
return DISPLAY_SUCCESS;
}
} // OHOS
} // HDI
} // DISPLAY
| 1,772 | 629 |
// Copyright 2018-current Getnamo. All Rights Reserved
#include "CUBlueprintLibrary.h"
#include "IImageWrapper.h"
#include "IImageWrapperModule.h"
#include "Core/Public/Modules/ModuleManager.h"
#include "Core/Public/Async/Async.h"
#include "Engine/Classes/Engine/Texture2D.h"
#include "Core/Public/HAL/ThreadSafeBool.h"
#include "RHI/Public/RHI.h"
#include "Core/Public/Misc/FileHelper.h"
#include "Engine/Public/OpusAudioInfo.h"
#include "Launch/Resources/Version.h"
#include "Developer/TargetPlatform/Public/Interfaces/IAudioFormat.h"
#include "CoreMinimal.h"
#include "Engine/Engine.h"
#include "CULambdaRunnable.h"
#include "CUOpusCoder.h"
#include "CUMeasureTimer.h"
#include "Hash/CityHash.h"
#pragma warning( push )
#pragma warning( disable : 5046)
//Render thread wrapper struct
struct FUpdateTextureData
{
UTexture2D* Texture2D;
FUpdateTextureRegion2D Region;
uint32 Pitch;
TArray64<uint8> BufferArray;
TSharedPtr<IImageWrapper> Wrapper; //to keep the uncompressed data alive
};
FString UCUBlueprintLibrary::Conv_BytesToString(const TArray<uint8>& InArray)
{
FString ResultString;
FFileHelper::BufferToString(ResultString, InArray.GetData(), InArray.Num());
return ResultString;
}
TArray<uint8> UCUBlueprintLibrary::Conv_StringToBytes(FString InString)
{
TArray<uint8> ResultBytes;
ResultBytes.Append((uint8*)TCHAR_TO_UTF8(*InString), InString.Len());
return ResultBytes;
}
UTexture2D* UCUBlueprintLibrary::Conv_BytesToTexture(const TArray<uint8>& InBytes)
{
//Convert the UTexture2D back to an image
UTexture2D* Texture = nullptr;
IImageWrapperModule& ImageWrapperModule = FModuleManager::LoadModuleChecked<IImageWrapperModule>(FName("ImageWrapper"));
EImageFormat DetectedFormat = ImageWrapperModule.DetectImageFormat(InBytes.GetData(), InBytes.Num());
TSharedPtr<IImageWrapper> ImageWrapper = ImageWrapperModule.CreateImageWrapper(DetectedFormat);
//Set the compressed bytes - we need this information on game thread to be able to determine texture size, otherwise we'll need a complete async callback
if (ImageWrapper.IsValid() && ImageWrapper->SetCompressed(InBytes.GetData(), InBytes.Num()))
{
//Create image given sizes
Texture = UTexture2D::CreateTransient(ImageWrapper->GetWidth(), ImageWrapper->GetHeight(), PF_B8G8R8A8);
Texture->UpdateResource();
//Uncompress on a background thread pool
FCULambdaRunnable::RunLambdaOnBackGroundThreadPool([ImageWrapper, Texture] {
TArray64<uint8> UncompressedBGRA;
if (ImageWrapper->GetRaw(ERGBFormat::BGRA, 8, UncompressedBGRA))
{
FUpdateTextureData* UpdateData = new FUpdateTextureData;
UpdateData->Texture2D = Texture;
UpdateData->Region = FUpdateTextureRegion2D(0, 0, 0, 0, Texture->GetSizeX(), Texture->GetSizeY());
UpdateData->BufferArray = UncompressedBGRA;
UpdateData->Pitch = Texture->GetSizeX() * 4;
UpdateData->Wrapper = ImageWrapper;
//enqueue texture copy
ENQUEUE_RENDER_COMMAND(BytesToTextureCommand)(
[UpdateData](FRHICommandList& CommandList)
{
RHIUpdateTexture2D(
((FTextureResource*)UpdateData->Texture2D->Resource)->TextureRHI->GetTexture2D(),
0,
UpdateData->Region,
UpdateData->Pitch,
UpdateData->BufferArray.GetData()
);
delete UpdateData; //now that we've updated the texture data, we can finally release any data we're holding on to
});//End Enqueue
}
});
}
else
{
UE_LOG(LogTemp, Warning, TEXT("Invalid image format cannot decode %d"), (int32)DetectedFormat);
}
return Texture;
}
//one static coder, created based on need
TSharedPtr<FCUOpusCoder> OpusCoder;
TArray<uint8> UCUBlueprintLibrary::Conv_OpusBytesToWav(const TArray<uint8>& InBytes)
{
//FCUScopeTimer Timer(TEXT("Conv_OpusBytesToWav"));
TArray<uint8> WavBytes;
//Early exit condition
if (InBytes.Num() == 0)
{
return WavBytes;
}
if (!OpusCoder)
{
OpusCoder = MakeShareable(new FCUOpusCoder());
}
TArray<uint8> PCMBytes;
FCUOpusMinimalStream OpusStream;
OpusCoder->DeserializeMinimal(InBytes, OpusStream);
if (OpusCoder->DecodeStream(OpusStream, PCMBytes))
{
SerializeWaveFile(WavBytes, PCMBytes.GetData(), PCMBytes.Num(), OpusCoder->Channels, OpusCoder->SampleRate);
}
else
{
UE_LOG(LogTemp, Warning, TEXT("OpusMinimal to Wave Failed. DecodeStream returned false"));
}
return WavBytes;
}
TArray<uint8> UCUBlueprintLibrary::Conv_WavBytesToOpus(const TArray<uint8>& InBytes)
{
//FCUScopeTimer Timer(TEXT("Conv_WavBytesToOpus"));
TArray<uint8> OpusBytes;
FWaveModInfo WaveInfo;
if (!WaveInfo.ReadWaveInfo(InBytes.GetData(), InBytes.Num()))
{
return OpusBytes;
}
if (!OpusCoder)
{
OpusCoder = MakeShareable(new FCUOpusCoder());
}
TArray<uint8> PCMBytes = TArray<uint8>(WaveInfo.SampleDataStart, WaveInfo.SampleDataSize);
FCUOpusMinimalStream OpusStream;
OpusCoder->EncodeStream(PCMBytes, OpusStream);
TArray<uint8> SerializedBytes;
OpusCoder->SerializeMinimal(OpusStream, SerializedBytes);
return SerializedBytes;
}
USoundWave* UCUBlueprintLibrary::Conv_WavBytesToSoundWave(const TArray<uint8>& InBytes)
{
USoundWave* SoundWave;
//Allocate based on thread
if (IsInGameThread())
{
SoundWave = NewObject<USoundWaveProcedural>(USoundWaveProcedural::StaticClass());
SetSoundWaveFromWavBytes((USoundWaveProcedural*)SoundWave, InBytes);
}
else
{
//We will go to another thread, copy our bytes
TArray<uint8> CopiedBytes = InBytes;
FThreadSafeBool bAllocationComplete = false;
AsyncTask(ENamedThreads::GameThread, [&bAllocationComplete, &SoundWave]
{
SoundWave = NewObject<USoundWaveProcedural>(USoundWaveProcedural::StaticClass());
bAllocationComplete = true;
});
//block while not complete
while (!bAllocationComplete)
{
//100micros sleep, this should be very quick
FPlatformProcess::Sleep(0.0001f);
};
SetSoundWaveFromWavBytes((USoundWaveProcedural*)SoundWave, CopiedBytes);
}
return SoundWave;
}
TArray<uint8> UCUBlueprintLibrary::Conv_SoundWaveToWavBytes(USoundWave* SoundWave)
{
TArray<uint8> PCMBytes;
TArray<uint8> WavBytes;
//memcpy raw data from soundwave, hmm this won't work for procedurals...
const void* LockedData = SoundWave->RawData.LockReadOnly();
PCMBytes.SetNumUninitialized(SoundWave->RawData.GetBulkDataSize());
FMemory::Memcpy(PCMBytes.GetData(), LockedData, PCMBytes.Num());
SoundWave->RawData.Unlock();
//add wav header
SerializeWaveFile(WavBytes, PCMBytes.GetData(), PCMBytes.Num(), SoundWave->NumChannels, SoundWave->GetSampleRateForCurrentPlatform());
return WavBytes;
}
void UCUBlueprintLibrary::Conv_CompactBytesToTransforms(const TArray<uint8>& InCompactBytes, TArray<FTransform>& OutTransforms)
{
TArray<float> FloatView;
FloatView.SetNumUninitialized(InCompactBytes.Num() / 4);
FPlatformMemory::Memcpy(FloatView.GetData(), InCompactBytes.GetData(), InCompactBytes.Num());
//is our float array exactly divisible by 9?
if (FloatView.Num() % 9 != 0)
{
UE_LOG(LogTemp, Log, TEXT("Conv_CompactBytesToTransforms::float array is not divisible by 9"));
return;
}
int32 TransformNum = FloatView.Num() / 9;
OutTransforms.SetNumUninitialized(TransformNum);
for (int i = 0; i < FloatView.Num() - 8; i += 9)
{
OutTransforms[i/9] = FTransform(FRotator(FloatView[i], FloatView[i+1], FloatView[i+2]), FVector(FloatView[i+3], FloatView[i + 4], FloatView[i + 5]), FVector(FloatView[i+6], FloatView[i+7], FloatView[i+8]));
}
}
void UCUBlueprintLibrary::Conv_CompactPositionBytesToTransforms(const TArray<uint8>& InCompactBytes, TArray<FTransform>& OutTransforms)
{
TArray<float> FloatView;
FloatView.SetNumUninitialized(InCompactBytes.Num() / 4);
FPlatformMemory::Memcpy(FloatView.GetData(), InCompactBytes.GetData(), InCompactBytes.Num());
//is our float array exactly divisible by 3?
if (FloatView.Num() % 3 != 0)
{
UE_LOG(LogTemp, Log, TEXT("Conv_CompactPositionBytesToTransforms::float array is not divisible by 3"));
return;
}
int32 TransformNum = FloatView.Num() / 3;
OutTransforms.SetNumUninitialized(TransformNum);
for (int i = 0; i < FloatView.Num() - 2; i += 3)
{
OutTransforms[i / 3] = FTransform(FVector(FloatView[i], FloatView[i + 1], FloatView[i + 2]));
}
}
void UCUBlueprintLibrary::SetSoundWaveFromWavBytes(USoundWaveProcedural* InSoundWave, const TArray<uint8>& InBytes)
{
FWaveModInfo WaveInfo;
FString ErrorReason;
if (WaveInfo.ReadWaveInfo(InBytes.GetData(), InBytes.Num(), &ErrorReason))
{
//copy header info
int32 DurationDiv = *WaveInfo.pChannels * *WaveInfo.pBitsPerSample * *WaveInfo.pSamplesPerSec;
if (DurationDiv)
{
InSoundWave->Duration = *WaveInfo.pWaveDataSize * 8.0f / DurationDiv;
}
else
{
InSoundWave->Duration = 0.0f;
}
InSoundWave->SetSampleRate(*WaveInfo.pSamplesPerSec);
InSoundWave->NumChannels = *WaveInfo.pChannels;
//SoundWaveProc->RawPCMDataSize = WaveInfo.SampleDataSize;
InSoundWave->bLooping = false;
InSoundWave->SoundGroup = ESoundGroup::SOUNDGROUP_Default;
//Queue actual audio data
InSoundWave->QueueAudio(WaveInfo.SampleDataStart, WaveInfo.SampleDataSize);
}
else
{
UE_LOG(LogTemp, Log, TEXT("SetSoundWaveFromWavBytes::WaveRead error: %s"), *ErrorReason);
}
}
TFuture<UTexture2D*> UCUBlueprintLibrary::Conv_BytesToTexture_Async(const TArray<uint8>& InBytes)
{
//Running this on a background thread
#if ENGINE_MINOR_VERSION < 23
return Async<UTexture2D*>(EAsyncExecution::Thread,[InBytes]
#else
return Async(EAsyncExecution::Thread, [InBytes]
#endif
{
//Create wrapper pointer we can share easily across threads
struct FDataHolder
{
UTexture2D* Texture = nullptr;
};
TSharedPtr<FDataHolder> Holder = MakeShareable(new FDataHolder);
FThreadSafeBool bLoadModuleComplete = false;
IImageWrapperModule* ImageWrapperModule;
AsyncTask(ENamedThreads::GameThread, [&bLoadModuleComplete, Holder, &ImageWrapperModule]
{
ImageWrapperModule = &FModuleManager::LoadModuleChecked<IImageWrapperModule>(FName("ImageWrapper"));
bLoadModuleComplete = true;
});
while (!bLoadModuleComplete)
{
FPlatformProcess::Sleep(0.001f);
}
EImageFormat DetectedFormat = ImageWrapperModule->DetectImageFormat(InBytes.GetData(), InBytes.Num());
TSharedPtr<IImageWrapper> ImageWrapper = ImageWrapperModule->CreateImageWrapper(DetectedFormat);
if (!(ImageWrapper.IsValid() && ImageWrapper->SetCompressed(InBytes.GetData(), InBytes.Num())))
{
UE_LOG(LogTemp, Warning, TEXT("Invalid image format cannot decode %d"), (int32)DetectedFormat);
return (UTexture2D*)nullptr;
}
//Create image given sizes
//Creation of UTexture needs to happen on game thread
FThreadSafeBool bAllocationComplete = false;
FIntPoint Size;
Size.X = ImageWrapper->GetWidth();
Size.Y = ImageWrapper->GetHeight();
AsyncTask(ENamedThreads::GameThread, [&bAllocationComplete, Holder, Size]
{
Holder->Texture = UTexture2D::CreateTransient(Size.X, Size.Y, PF_B8G8R8A8);
Holder->Texture->UpdateResource();
bAllocationComplete = true;
});
while (!bAllocationComplete)
{
//sleep 10ms intervals
FPlatformProcess::Sleep(0.001f);
}
//Uncompress on a background thread pool
TArray64<uint8> UncompressedBGRA;
if (!ImageWrapper->GetRaw(ERGBFormat::BGRA, 8, UncompressedBGRA))
{
return (UTexture2D*)nullptr;
}
FUpdateTextureData* UpdateData = new FUpdateTextureData;
UpdateData->Texture2D = Holder->Texture;
UpdateData->Region = FUpdateTextureRegion2D(0, 0, 0, 0, Size.X, Size.Y);
UpdateData->BufferArray = UncompressedBGRA;
UpdateData->Pitch = Size.X * 4;
UpdateData->Wrapper = ImageWrapper;
//This command sends it to the render thread
ENQUEUE_RENDER_COMMAND(BytesToTextureAsyncCommand)(
[UpdateData](FRHICommandList& CommandList)
{
RHIUpdateTexture2D(
((FTextureResource*)UpdateData->Texture2D->Resource)->TextureRHI->GetTexture2D(),
0,
UpdateData->Region,
UpdateData->Pitch,
UpdateData->BufferArray.GetData()
);
delete UpdateData; //now that we've updated the texture data, we can finally release any data we're holding on to
});//End Enqueue
return Holder->Texture;
});//End async
}
bool UCUBlueprintLibrary::Conv_TextureToBytes(UTexture2D* Texture, TArray<uint8>& OutBuffer, EImageFormatBPType Format /*= EImageFormatBPType::JPEG*/)
{
if (!Texture || !Texture->IsValidLowLevel())
{
return false;
}
//Get our wrapper module
IImageWrapperModule& ImageWrapperModule = FModuleManager::LoadModuleChecked<IImageWrapperModule>(FName("ImageWrapper"));
TSharedPtr<IImageWrapper> ImageWrapper = ImageWrapperModule.CreateImageWrapper((EImageFormat)Format);
int32 Width = Texture->PlatformData->Mips[0].SizeX;
int32 Height = Texture->PlatformData->Mips[0].SizeY;
int32 DataLength = Width * Height * 4;
void* TextureDataPointer = Texture->PlatformData->Mips[0].BulkData.Lock(LOCK_READ_ONLY);
ImageWrapper->SetRaw(TextureDataPointer, DataLength, Width, Height, ERGBFormat::BGRA, 8);
//This part can take a while, has performance implications
OutBuffer = ImageWrapper->GetCompressed();
Texture->PlatformData->Mips[0].BulkData.Unlock();
return true;
}
FString UCUBlueprintLibrary::NowUTCString()
{
return FDateTime::UtcNow().ToString();
}
FString UCUBlueprintLibrary::GetLoginId()
{
return FPlatformMisc::GetLoginId();
}
int32 UCUBlueprintLibrary::ToHashCode(const FString& String)
{
return (int32)CityHash32(TCHAR_TO_ANSI(*String), String.Len());
}
void UCUBlueprintLibrary::MeasureTimerStart(const FString& Category /*= TEXT("TimeTaken")*/)
{
FCUMeasureTimer::Tick(Category);
}
float UCUBlueprintLibrary::MeasureTimerStop(const FString& Category /*= TEXT("TimeTaken")*/, bool bShouldLogResult /*= true*/)
{
return (float)FCUMeasureTimer::Tock(Category, bShouldLogResult);
}
void UCUBlueprintLibrary::CallFunctionOnThread(const FString& FunctionName, ESIOCallbackType ThreadType, UObject* WorldContextObject /*= nullptr*/)
{
UObject* Target = WorldContextObject;
if (!Target->IsValidLowLevel())
{
UE_LOG(LogTemp, Warning, TEXT("CallFunctionOnThread: Target not found for '%s'"), *FunctionName);
return;
}
UFunction* Function = Target->FindFunction(FName(*FunctionName));
if (nullptr == Function)
{
UE_LOG(LogTemp, Warning, TEXT("CallFunctionOnThread: Function not found '%s'"), *FunctionName);
return;
}
switch (ThreadType)
{
case CALLBACK_GAME_THREAD:
if (IsInGameThread())
{
Target->ProcessEvent(Function, nullptr);
}
else
{
FCULambdaRunnable::RunShortLambdaOnGameThread([Function, Target]
{
if (Target->IsValidLowLevel())
{
Target->ProcessEvent(Function, nullptr);
}
});
}
break;
case CALLBACK_BACKGROUND_THREADPOOL:
FCULambdaRunnable::RunLambdaOnBackGroundThreadPool([Function, Target]
{
if (Target->IsValidLowLevel())
{
Target->ProcessEvent(Function, nullptr);
}
});
break;
case CALLBACK_BACKGROUND_TASKGRAPH:
FCULambdaRunnable::RunShortLambdaOnBackGroundTask([Function, Target]
{
if (Target->IsValidLowLevel())
{
Target->ProcessEvent(Function, nullptr);
}
});
break;
default:
break;
}
}
void UCUBlueprintLibrary::CallFunctionOnThreadGraphReturn(const FString& FunctionName, ESIOCallbackType ThreadType, struct FLatentActionInfo LatentInfo, UObject* WorldContextObject /*= nullptr*/)
{
UObject* Target = WorldContextObject;
FCULatentAction* LatentAction = FCULatentAction::CreateLatentAction(LatentInfo, Target);
if (!Target->IsValidLowLevel())
{
UE_LOG(LogTemp, Warning, TEXT("CallFunctionOnThread: Target not found for '%s'"), *FunctionName);
LatentAction->Call();
return;
}
UFunction* Function = Target->FindFunction(FName(*FunctionName));
if (nullptr == Function)
{
UE_LOG(LogTemp, Warning, TEXT("CallFunctionOnThread: Function not found '%s'"), *FunctionName);
LatentAction->Call();
return;
}
switch (ThreadType)
{
case CALLBACK_GAME_THREAD:
if (IsInGameThread())
{
Target->ProcessEvent(Function, nullptr);
LatentAction->Call();
}
else
{
FCULambdaRunnable::RunShortLambdaOnGameThread([Function, Target, LatentAction]
{
if (Target->IsValidLowLevel())
{
Target->ProcessEvent(Function, nullptr);
LatentAction->Call();
}
});
}
break;
case CALLBACK_BACKGROUND_THREADPOOL:
FCULambdaRunnable::RunLambdaOnBackGroundThreadPool([Function, Target, LatentAction]
{
if (Target->IsValidLowLevel())
{
Target->ProcessEvent(Function, nullptr);
LatentAction->Call();
}
});
break;
case CALLBACK_BACKGROUND_TASKGRAPH:
FCULambdaRunnable::RunShortLambdaOnBackGroundTask([Function, Target, LatentAction]
{
if (Target->IsValidLowLevel())
{
Target->ProcessEvent(Function, nullptr);
LatentAction->Call();
}
});
break;
default:
break;
}
}
#pragma warning( pop )
| 16,686 | 6,327 |
#include <stdio.h>
#include <string.h>
#ifdef LINUX
#include <stdlib.h>
#include <mntent.h>
#include <libudev.h>
#else
#import <Foundation/Foundation.h>
#import <IOKit/IOKitLib.h>
#import <IOKit/usb/IOUSBLib.h>
#import <IOKit/hid/IOHIDKeys.h>
#endif
#ifdef LINUX
#include "../../PISupervisor/apple/include/KernelProtocol.h"
#else
#include "../../PISupervisor/PISupervisor/apple/include/KernelProtocol.h"
#endif
#include "KextDeviceNotify.h"
#include "PISecSmartDrv.h"
#ifndef VFS_RETURNED
#define VFS_RETURNED 0
#endif
#ifdef LINUX
int EnumMountCallback(void* pMount, void* pParam);
#else
int EnumMountCallback(mount_t pMount, void* pParam);
#endif
void FetchVolumes()
{
VolCtx_Clear();
EnumMountCallback(NULL, NULL);
}
#ifdef LINUX
int get_storage_type(struct udev* udev, char* mnt_fsname)
{
int ret = BusTypeUnknown;
struct udev_enumerate* enumerate = NULL;
if (udev == NULL || mnt_fsname == NULL)
return ret;
enumerate = udev_enumerate_new(udev);
if (enumerate == NULL)
return ret;
printf("DEVNAME = %s\n", mnt_fsname);
udev_enumerate_add_match_property(enumerate, "DEVNAME", mnt_fsname);
udev_enumerate_scan_devices(enumerate);
struct udev_list_entry *devices = udev_enumerate_get_list_entry(enumerate);
struct udev_list_entry *entry = NULL;
udev_list_entry_foreach(entry, devices)
{
const char* path = udev_list_entry_get_name(entry);
if (path == NULL)
continue;
struct udev_device* parent = udev_device_new_from_syspath(udev, path);
if (parent == NULL)
continue;
const char *id_cdrom = udev_device_get_property_value(parent, "ID_CDROM");
//printf("\tproperty [ID_CDROM][%s]\n", id_cdrom);
const char *devtype = udev_device_get_property_value(parent, "DEVTYPE");
//printf("\tproperty [DEVTYPE][%s]\n", devtype);
if (id_cdrom != NULL)
{
ret = BusTypeAtapi;
}
else if (devtype != NULL)
{
ret = BusTypeUsb;
}
break;
}
udev_enumerate_unref(enumerate);
if (ret == BusTypeUnknown)
{
#ifdef WSL
ret = BusTypeUsb;
#else
ret = BusTypeSFolder;
#endif
}
return ret;
}
int EnumMountCallback(void *pMount, void* pParam)
#else
int EnumMountCallback(mount_t pMount, void* pParam)
#endif
{
int nBusType = 0;
boolean_t bUsbStor = FALSE;
boolean_t bCDStor = FALSE;
boolean_t bSFolder = FALSE;
boolean_t bTBStor = FALSE;
#ifdef LINUX
struct mntent *ent = NULL;
FILE *aFile = NULL;
struct udev* udev = NULL;
aFile = setmntent("/proc/mounts", "r");
if (aFile == NULL)
{
printf("[DLP][%s] setmntent() failed \n", __FUNCTION__);
return -1;
}
udev = udev_new();
if (udev == NULL)
{
printf("[DLP][%s] udev_new() failed \n", __FUNCTION__);
endmntent(aFile);
return -1;
}
while (NULL != (ent = getmntent(aFile)))
{
// e.g.
// f_mntonname /media/somansa/PRIVACY-I
// f_mntfromname /dev/sdb1
//
// ent->mnt_fsname, ent->mnt_dir, ent->mnt_type, ent->mnt_opts
// /dev/sdb1 /media/somansa/PRIVACY-I vfat rw,nosuid,nodev,relatime,uid=1001,gid=1001,fmask=0022,dmask=0022,codepage=437,iocharset=ascii,shortname=mixed,showexec,utf8,flush,errors=remount-ro
// /dev/sda3 / ext4 rw,relatime,errors=remount-ro
#ifdef WSL
if (strstr(ent->mnt_dir, "/dev/") == NULL && strstr(ent->mnt_dir, "/mnt/") == NULL)
#else
if (strstr(ent->mnt_fsname, "/dev/") == NULL && strstr(ent->mnt_fsname, "/mnt/") == NULL)
#endif
{
#ifdef WSL
if (ent->mnt_fsname[0] == '/' && ent->mnt_fsname[1] == '/')
#else
if (ent->mnt_dir[0] == '/' && ent->mnt_dir[1] == '/')
#endif
{
// //192.168.181.1/tmp
}
else
{
continue;
}
}
else
{
#ifdef WSL
#else
// /dev/sda3 /
if (ent->mnt_dir[0] == '/' && ent->mnt_dir[1] == 0)
{
continue;
}
#endif
}
#ifdef WSL
if (strlen(ent->mnt_dir) <= 1)
#else
if (strlen(ent->mnt_fsname) <= 1)
#endif
{
continue;
}
//printf("%s %s %s %s \n", ent->mnt_fsname, ent->mnt_dir, ent->mnt_type, ent->mnt_opts);
//#ifdef WSL
int type = get_storage_type(udev, ent->mnt_fsname);
//#else
// int type = get_storage_type(udev, ent->mnt_dir);
//#endif
VolCtx_Update( ent->mnt_fsname, ent->mnt_dir, type );
}
endmntent(aFile);
udev_unref(udev);
return 0;
#else
// Get all mounted path
NSArray *mounted = [[NSFileManager defaultManager] mountedVolumeURLsIncludingResourceValuesForKeys:nil options:0];
// Get mounted USB information
for(NSURL *url in mounted) {
char f_mntfromname[MAX_PATH] = {0};
char f_mntonname[MAX_PATH] = {0};
char f_fstypename[] = "";
GetMountPath([url.path UTF8String], f_mntonname, sizeof(f_mntonname), f_mntfromname, sizeof(f_mntfromname));
if (f_mntfromname[0] == 0 || f_mntonname[0] == 0)
continue;
// 1. Volume Context Search.
nBusType = VolCtx_Search_BusType( f_mntonname );
if(nBusType == BusTypeUsb ||
nBusType == BusType1394 ||
nBusType == BusTypeThunderBolt ||
nBusType == BusTypeAtapi ||
nBusType == BusTypeSFolder)
{
switch(nBusType)
{
case BusType1394:
case BusTypeUsb:
bUsbStor = TRUE;
break;
case BusTypeThunderBolt:
bTBStor = TRUE;
break;
case BusTypeAtapi:
bCDStor = TRUE;
break;
case BusTypeSFolder:
bSFolder = TRUE;
break;
default: break;
}
}
else
{ // 2. First Acess Check.
bUsbStor = IsMediaPath_UsbStor( f_mntonname );
if(bUsbStor)
{
nBusType = BusTypeUsb;
VolCtx_Update( f_mntfromname, f_mntonname, BusTypeUsb );
}
bCDStor = IsMediaPath_CDStor( f_mntonname );
if(bCDStor)
{
nBusType = BusTypeAtapi;
VolCtx_Update( f_mntfromname, f_mntonname, BusTypeAtapi );
}
bSFolder = IsMediaPath_SFolder( f_mntfromname, f_mntonname, f_fstypename );
if(bSFolder)
{
nBusType = BusTypeSFolder;
VolCtx_Update( f_mntfromname, f_mntonname, BusTypeSFolder );
}
}
}
return (VFS_RETURNED); //VFS_RETURENED_DONE
#endif
}
boolean_t
IsControlDeviceType( const vnode_t pVnode, const char* pczPath )
{
boolean_t bSFolder = FALSE;
boolean_t bUsbStor = FALSE;
boolean_t bCDStor = FALSE;
boolean_t bTBStor = FALSE;
boolean_t bVoulmesDir = FALSE;
boolean_t bCups = FALSE;
//if(!pVnode) return FALSE;
if(pczPath)
{
bCups = IsCupsDirectory( pczPath );
if(TRUE == bCups) return TRUE;
}
if(pczPath)
{
bVoulmesDir = IsVolumesDirectory( pczPath );
// printf("[DLP][%s] pczPath=%s \n", __FUNCTION__, pczPath );
}
char f_mntonname[MAX_PATH] = {0};
char f_mntfromname[MAX_PATH] = {0};
char f_fstypename[] = "";
if(bVoulmesDir)
{
int nBusType = 0;
// e.g.
// f_mntonname /Volumes/새 볼륨
// f_mntfromname disk2s2
GetMountPath(pczPath, f_mntonname, sizeof(f_mntonname), f_mntfromname, sizeof(f_mntfromname));
// 1. Volume Context Search.
//nBusType = VolCtx_Search_BusType( Stat.f_mntonname );
nBusType = VolCtx_Search_BusType( f_mntonname );
if(nBusType == BusTypeUsb || nBusType == BusType1394 ||
nBusType == BusTypeThunderBolt || nBusType == BusTypeAtapi || nBusType == BusTypeSFolder)
{
return TRUE;
}
// 2. First Acess Check.
//bUsbStor = IsMediaPath_UsbStor( f_mntfromname );
bUsbStor = IsMediaPath_UsbStor( f_mntonname );
if(bUsbStor)
{
printf("[DLP][%s] UsbStor=1, fs=%s, from=%s, name=%s \n", __FUNCTION__, f_fstypename, f_mntfromname, f_mntonname );
VolCtx_Update( f_mntfromname, f_mntonname, BusTypeUsb );
return bUsbStor;
}
//bCDStor = IsMediaPath_CDStor( f_mntfromname );
bCDStor = IsMediaPath_CDStor( f_mntonname );
if(bCDStor)
{
printf("[DLP][%s] CDStor=1, fs=%s, from=%s, name=%s \n", __FUNCTION__, f_fstypename, f_mntfromname, f_mntonname );
VolCtx_Update( f_mntfromname, f_mntonname, BusTypeAtapi );
return bCDStor;
}
bSFolder = IsMediaPath_SFolder( f_mntfromname, f_mntonname, f_fstypename );
if(bSFolder)
{
// '/Volumes/shared2/.DS_Store' skip
printf("[DLP][%s] SFolder=1, fs=%s, from=%s, name=%s, pczPath=%s \n", __FUNCTION__, f_fstypename, f_mntfromname, f_mntonname, pczPath );
if(NULL == sms_strnstr( pczPath, "/.DS_Store", strlen("/.DS_Store") ))
{
VolCtx_Update( f_mntfromname, f_mntonname, BusTypeSFolder );
return bSFolder;
}
else
return FALSE;
}
}
return FALSE;
}
boolean_t
IsCupsdConfigFile( const char* pczPath )
{
boolean_t bCups = FALSE;
size_t nlen = 0;
if(!pczPath)
return FALSE;
if(pczPath)
{
nlen = strlen(FILE_CUPSD_CONFIG);
if(nlen > 0 && 0 == strncasecmp( pczPath, FILE_CUPSD_CONFIG, nlen))
{
bCups = TRUE;
}
}
return bCups;
}
boolean_t
IsCupsDirectory(const char* pczPath)
{
size_t nLength = 0;
size_t nCups = 0;
if(!pczPath) return FALSE;
nLength = strlen(pczPath);
nCups = strlen(g_czCupsSpoolPath);
if(0 == nCups || nLength < nCups) return FALSE;
if(0 == strncasecmp( pczPath, g_czCupsSpoolPath, nCups ))
{
size_t nLenght = (int)strlen(pczPath);
int nAdd = ('/' == g_czCupsSpoolPath[nCups-1])?0:1;
for(size_t i=nCups+nAdd; i<nLenght; i++)
{
// is file??
if('/' == pczPath[i])
{
printf("[DLP][%s] Detected Path is not file=%s \n", __FUNCTION__, pczPath );
return FALSE;
}
}
printf("[DLP][%s] Detect Path=%s \n", __FUNCTION__, pczPath );
return TRUE;
}
return FALSE;
}
boolean_t IsVolumesDirectory(const char* path)
{
boolean_t volumesDir = FALSE;
#ifdef LINUX
volumesDir = TRUE;
#else
if (path != NULL &&
strlen(path) >= strlen("/Volumes/") &&
*(path+0) == '/' &&
*(path+1) == 'V' &&
*(path+2) == 'o' &&
*(path+3) == 'l' &&
*(path+4) == 'u' &&
*(path+5) == 'm' &&
*(path+6) == 'e' &&
*(path+7) == 's' &&
*(path+8) == '/')
{
volumesDir = TRUE;
}
#endif
return volumesDir;
}
void SetProtectUsbMobileNotify(void)
{
}
void SetProtect_Camera_UsbDeviceNotify(void)
{
}
void SetProtect_RNDIS_UsbDeviceNotify(void)
{
}
void SetProtect_RNDIS_BthDeviceNotify(void)
{
}
boolean_t
KextNotify_Init()
{
return true;
}
boolean_t
KextNotify_Uninit()
{
return true;
}
| 11,727 | 4,469 |
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2017-2019 The WaykiChain Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "dexoperatortx.h"
#include "config/configuration.h"
#include "main.h"
#include <regex>
#include <algorithm>
////////////////////////////////////////////////////////////////////////////////
// ProcessAssetFee
static const string OPERATOR_ACTION_REGISTER = "register";
static const string OPERATOR_ACTION_UPDATE = "update";
static const uint32_t MAX_NAME_LEN = 32;
static const uint64_t MAX_MATCH_FEE_RATIO_VALUE = 50000000; // 50%
static const uint64_t ORDER_OPEN_DEXOP_LIST_SIZE_MAX = 500;
static bool ProcessDexOperatorFee(CBaseTx &tx, CTxExecuteContext& context, const string &action) {
IMPLEMENT_DEFINE_CW_STATE;
uint64_t exchangeFee = 0;
if (action == OPERATOR_ACTION_REGISTER) {
if (!cw.sysParamCache.GetParam(DEX_OPERATOR_REGISTER_FEE, exchangeFee))
return state.DoS(100, ERRORMSG("read param DEX_OPERATOR_REGISTER_FEE error"),
REJECT_INVALID, "read-sysparam-error");
} else {
assert(action == OPERATOR_ACTION_UPDATE);
if (!cw.sysParamCache.GetParam(DEX_OPERATOR_UPDATE_FEE, exchangeFee))
return state.DoS(100, ERRORMSG("read param DEX_OPERATOR_UPDATE_FEE error"),
REJECT_INVALID, "read-sysparam-error");
}
if (!tx.sp_tx_account->OperateBalance(SYMB::WICC, BalanceOpType::SUB_FREE, exchangeFee,
ReceiptType::DEX_OPERATOR_REG_UPDATE_FEE_FROM_OPERATOR, tx.receipts))
return state.DoS(100, ERRORMSG("tx account insufficient funds for operator %s fee! fee=%llu, tx_addr=%s",
action, exchangeFee, tx.sp_tx_account->keyid.ToAddress()),
UPDATE_ACCOUNT_FAIL, "insufficent-funds");
uint64_t dexOperatorRiskFeeRatio;
if(!cw.sysParamCache.GetParam(SysParamType::DEX_OPERATOR_RISK_FEE_RATIO, dexOperatorRiskFeeRatio)) {
return state.DoS(100, ERRORMSG("ProcessDexOperatorFee, get dexOperatorRiskFeeRatio error"),
READ_SYS_PARAM_FAIL, "read-db-error");
}
uint64_t riskFee = exchangeFee * dexOperatorRiskFeeRatio / RATIO_BOOST;
uint64_t minerTotalFee = exchangeFee - riskFee;
auto spFcoinAccount = tx.GetAccount(context, SysCfg().GetFcoinGenesisRegId(), "fcoin");
if (!spFcoinAccount) return false;
ReceiptType code = (action == OPERATOR_ACTION_REGISTER) ? ReceiptType::DEX_OPERATOR_REG_FEE_TO_RESERVE :
ReceiptType::DEX_OPERATOR_UPDATED_FEE_TO_RESERVE;
if (!spFcoinAccount->OperateBalance(SYMB::WICC, BalanceOpType::ADD_FREE, riskFee, code, tx.receipts)) {
return state.DoS(100, ERRORMSG("operate balance failed! add %s asset fee=%llu to risk reserve account error",
action, riskFee), UPDATE_ACCOUNT_FAIL, "update-account-failed");
}
VoteDelegateVector delegates;
if (!cw.delegateCache.GetActiveDelegates(delegates)) {
return state.DoS(100, ERRORMSG("GetActiveDelegates failed"), REJECT_INVALID, "get-delegates-failed");
}
assert(delegates.size() != 0 );
for (size_t i = 0; i < delegates.size(); i++) {
const CRegID &delegateRegid = delegates[i].regid;
auto spDelegateAccount = tx.GetAccount(context, delegateRegid, "delegate_regid");
if (!spDelegateAccount) return false;
uint64_t minerFee = minerTotalFee / delegates.size();
if (i == 0) minerFee += minerTotalFee % delegates.size(); // give the dust amount to topmost miner
ReceiptType code = (action == OPERATOR_ACTION_REGISTER) ? ReceiptType::DEX_OPERATOR_REG_FEE_TO_MINER :
ReceiptType::DEX_OPERATOR_UPDATED_FEE_TO_MINER;
if (!spDelegateAccount->OperateBalance(SYMB::WICC, BalanceOpType::ADD_FREE, minerFee, code, tx.receipts)) {
return state.DoS(100, ERRORMSG("add %s asset fee to miner failed, miner regid=%s",
action, delegateRegid.ToString()), UPDATE_ACCOUNT_FAIL, "operate-account-failed");
}
}
return true;
}
////////////////////////////////////////////////////////////////////////////////
// class CDEXOperatorRegisterTx
Object CDEXOperatorRegisterTx::ToJson(CCacheWrapper &cw) const {
Object result = CBaseTx::ToJson(cw);
result.push_back(Pair("owner_uid", data.owner_uid.ToString()));
result.push_back(Pair("fee_receiver_uid", data.fee_receiver_uid.ToString()));
result.push_back(Pair("dex_name", data.name));
result.push_back(Pair("portal_url", data.portal_url));
result.push_back(Pair("maker_fee_ratio",data.maker_fee_ratio));
result.push_back(Pair("taker_fee_ratio",data.taker_fee_ratio));
result.push_back(Pair("memo",data.memo));
return result;
}
bool CDEXOperatorRegisterTx::CheckTx(CTxExecuteContext &context) {
CValidationState &state = *context.pState;
if (!data.owner_uid.is<CRegID>())
return state.DoS(100, ERRORMSG("owner_uid must be regid"), REJECT_INVALID,
"owner-uid-type-error");
if (!data.fee_receiver_uid.is<CRegID>())
return state.DoS(100, ERRORMSG("fee_receiver_uid must be regid"), REJECT_INVALID,
"match-uid-type-error");
if (data.name.size() > MAX_NAME_LEN)
return state.DoS(100, ERRORMSG("name len=%d greater than %d",
data.name.size(), MAX_NAME_LEN), REJECT_INVALID, "invalid-name");
if(data.memo.size() > MAX_COMMON_TX_MEMO_SIZE)
return state.DoS(100, ERRORMSG("memo len=%d greater than %d",
data.memo.size(), MAX_COMMON_TX_MEMO_SIZE), REJECT_INVALID, "invalid-memo");
if (data.maker_fee_ratio > MAX_MATCH_FEE_RATIO_VALUE)
return state.DoS(100, ERRORMSG("maker_fee_ratio=%d is greater than %d",
data.maker_fee_ratio, MAX_MATCH_FEE_RATIO_VALUE), REJECT_INVALID, "invalid-match-fee-ratio-type");
if (data.taker_fee_ratio > MAX_MATCH_FEE_RATIO_VALUE)
return state.DoS(100, ERRORMSG("taker_fee_ratio=%d is greater than %d",
data.taker_fee_ratio, MAX_MATCH_FEE_RATIO_VALUE), REJECT_INVALID, "invalid-match-fee-ratio-type");
if (data.order_open_dexop_list.size() > ORDER_OPEN_DEXOP_LIST_SIZE_MAX)
return state.DoS(100, ERRORMSG("size=%u of order_open_dexop_list exceed max=%u",
data.order_open_dexop_list.size(), ORDER_OPEN_DEXOP_LIST_SIZE_MAX),
REJECT_INVALID, "invalid-shared-dexop-list-size");
return true;
}
bool CDEXOperatorRegisterTx::ExecuteTx(CTxExecuteContext &context) {
CCacheWrapper &cw = *context.pCw; CValidationState &state = *context.pState;
DexOpIdValueSet dexIdSet;
for (auto &item : data.order_open_dexop_list) {
if (!cw.dexCache.HaveDexOperator(item.get())) {
return state.DoS(100, ERRORMSG("operator item=%s not exist",
db_util::ToString(item)), REJECT_INVALID, "operator-not-exist");
}
auto ret = dexIdSet.insert(item);
if (!ret.second) {
return state.DoS(100, ERRORMSG("duplicated item=%s in order_open_dexop_list",
db_util::ToString(item)), REJECT_INVALID, "duplicated-item-of-dexop-list");
}
}
shared_ptr<CAccount> spOwnerAccount;
if (sp_tx_account->IsSelfUid(data.owner_uid)) {
spOwnerAccount = sp_tx_account;
} else {
spOwnerAccount = GetAccount(context, data.owner_uid, "owner_uid");
if (!spOwnerAccount) return false;
}
shared_ptr<CAccount> pMatchAccount;
if (!sp_tx_account->IsSelfUid(data.fee_receiver_uid) && !sp_tx_account->IsSelfUid(data.fee_receiver_uid)) {
pMatchAccount = GetAccount(context, data.fee_receiver_uid, "fee_receiver_uid");
if (!pMatchAccount) return false;
}
if (cw.dexCache.HasDexOperatorByOwner(spOwnerAccount->regid))
return state.DoS(100, ERRORMSG("the owner's operator exist! owner_regid=%s",
spOwnerAccount->regid.ToString()), REJECT_INVALID, "owner-dexoperator-exist");
if (!ProcessDexOperatorFee(*this, context, OPERATOR_ACTION_REGISTER))
return false;
uint32_t new_id;
if (!cw.dexCache.IncDexID(new_id))
return state.DoS(100, ERRORMSG("increase dex id error! txUid=%s", GetHash().ToString() ),
UPDATE_ACCOUNT_FAIL, "inc_dex_id_error");
DexOperatorDetail detail = {
data.owner_uid.get<CRegID>(),
data.fee_receiver_uid.get<CRegID>(),
data.name,
data.portal_url,
data.order_open_mode,
data.maker_fee_ratio,
data.taker_fee_ratio,
dexIdSet,
data.memo
};
if (!cw.dexCache.CreateDexOperator(new_id, detail))
return state.DoS(100, ERRORMSG("save new dex operator error! new_id=%u", new_id),
UPDATE_ACCOUNT_FAIL, "save-operator-error");
return true;
}
bool CDEXOperatorUpdateData::Check(CBaseTx &tx, CCacheWrapper &cw, string& errmsg, string& errcode,const uint32_t currentHeight){
DexOperatorDetail dex;
if(!cw.dexCache.GetDexOperator(dexId,dex)) {
errmsg = strprintf("dexoperator(id=%d) not found", dexId);
errcode = "invalid-dex-id";
return false;
}
if(field == UPDATE_NONE || field > MEMO ){
errmsg = "CDEXOperatorUpdateData::check(): update field is error";
errcode= "empty-update-data";
return false;
}
if (field == FEE_RECEIVER_UID || field == OWNER_UID){
string placeholder = (field == FEE_RECEIVER_UID)? "fee_receiver": "owner";
const auto &uid = get<CUserID>();
auto spAccount = tx.GetAccount(cw, uid);
if (!spAccount) {
errmsg = strprintf("CDEXOperatorUpdateData::check(): %s_uid (%s) is not exist! ",placeholder, ValueToString());
errcode = strprintf("%s-uid-invalid", placeholder);
return false;
}
if (!spAccount->IsRegistered() || !spAccount->regid.IsMature(currentHeight)) {
errmsg = strprintf("CDEXOperatorUpdateData::check(): %s_uid (%s) not register or regid is immature ! ",placeholder, ValueToString() );
errcode = strprintf("%s-uid-invalid", placeholder);
return false;
}
}
if (field == NAME && get<string>().size() > MAX_NAME_LEN) {
errmsg = strprintf("%s, name len=%d greater than %d", __func__,get<string>().size(), MAX_NAME_LEN);
errcode = "invalid-name";
return false;
}
if (field == MEMO && get<string>().size() > MAX_COMMON_TX_MEMO_SIZE){
errmsg = strprintf("%s, memo len=%d greater than %d", __func__,get<string>().size(), MAX_COMMON_TX_MEMO_SIZE);
errcode = "invalid-memo";
return false;
}
if (field == TAKER_FEE_RATIO || field == MAKER_FEE_RATIO ){
uint64_t v = get<uint64_t>();
if( v > MAX_MATCH_FEE_RATIO_VALUE){
errmsg = strprintf("%s, fee_ratio=%d is greater than %d", __func__,
v, MAX_MATCH_FEE_RATIO_VALUE);
errcode = "invalid-match-fee-ratio-type";
return false;
}
}
if (field == OPEN_MODE) {
dex::OpenMode om = get<dex::OpenMode>();
if (om != dex::OpenMode::PRIVATE && om != dex::OpenMode::PUBLIC) {
errmsg = strprintf("dex open mode value(%d) is error", (uint8_t)om);
errcode = "invalid-open-mode";
return false;
}
if (om == dex.order_open_mode) {
errmsg = strprintf("the new dex open mode value(%d) is as same as old open mode", (uint8_t)om);
errcode = "same-open-mode";
return false;
}
}
if (field == ORDER_OPEN_DEXOP_LIST) {
const auto &dexlist = get<DexOpIdValueList>();
if (dexlist.size() > ORDER_OPEN_DEXOP_LIST_SIZE_MAX) {
errmsg = strprintf("size=%u of order_open_dexop_list exceed max=%u",
dexlist.size(), ORDER_OPEN_DEXOP_LIST_SIZE_MAX);
errcode = "invalid-shared-dexop-list-size";
return false;
}
DexOpIdValueSet dexIdSet;
for (auto dexOpId : dexlist) {
if (dexOpId.get() == dexId) {
errmsg = strprintf("dexid=%d is self", dexOpId.get());
errcode = "self-dexid-error";
return false;
}
if (!cw.dexCache.HaveDexOperator(dexOpId.get())) {
errmsg = strprintf("dex(id=%d) not exist!!", dexOpId.get());
errcode = "dexid-not-exist";
return false;
}
}
}
return true;
}
bool CDEXOperatorUpdateData::UpdateToDexOperator(DexOperatorDetail& detail,CCacheWrapper& cw) {
switch (field) {
case FEE_RECEIVER_UID:{
if(get<CUserID>().is<CRegID>()) {
detail.fee_receiver_regid = get<CUserID>().get<CRegID>();
return true;
} else{
return false;
}
}
case OWNER_UID:{
if(get<CUserID>().is<CRegID>()){
detail.owner_regid = get<CUserID>().get<CRegID>();
return true;
} else{
return false;
}
}
case NAME:
detail.name = get<string>();
break;
case PORTAL_URL:
detail.portal_url = get<string>();
break;
case TAKER_FEE_RATIO:
detail.taker_fee_ratio = get<uint64_t>();
break;
case MAKER_FEE_RATIO:
detail.maker_fee_ratio = get<uint64_t>();
break;
case MEMO:
detail.memo = get<string>();
break;
case OPEN_MODE:
detail.order_open_mode = get<dex::OpenMode>();
break;
case ORDER_OPEN_DEXOP_LIST:{
const auto &dexIdList = get<DexOpIdValueList>();
DexOpIdValueSet dexIdSet;
for (auto dexId: dexIdList) {
dexIdSet.insert(dexId);
}
detail.order_open_dexop_set = dexIdSet;
break;
}
default:
return false;
}
return true;
}
string CDEXOperatorUpdateTx::ToString(CAccountDBCache &accountCache) {
return "";
}
Object CDEXOperatorUpdateTx::ToJson(CCacheWrapper &cw) const {
Object result = CBaseTx::ToJson(cw);
result.push_back(Pair("update_field", update_data.field));
result.push_back(Pair("update_value", update_data.ValueToString()));
result.push_back(Pair("dex_id", update_data.dexId));
return result;
}
bool CDEXOperatorUpdateTx::CheckTx(CTxExecuteContext &context) {
IMPLEMENT_DEFINE_CW_STATE;
string errmsg;
string errcode;
if(!update_data.Check(*this, cw, errmsg ,errcode, context.height )){
return state.DoS(100, ERRORMSG("%s", errmsg), REJECT_INVALID, errcode);
}
if(update_data.field == CDEXOperatorUpdateData::OWNER_UID){
if(cw.dexCache.HasDexOperatorByOwner(CRegID(update_data.ValueToString())))
return state.DoS(100, ERRORMSG("the owner already has a dex operator! owner_regid=%s",
update_data.ValueToString()), REJECT_INVALID, "owner-had-dexoperator");
}
return true;
}
bool CDEXOperatorUpdateTx::ExecuteTx(CTxExecuteContext &context) {
CCacheWrapper &cw = *context.pCw; CValidationState &state = *context.pState;
DexOperatorDetail oldDetail;
if (!cw.dexCache.GetDexOperator((DexID)update_data.dexId, oldDetail))
return state.DoS(100, ERRORMSG("the dexoperator( id= %u) is not exist!",
update_data.dexId), UPDATE_ACCOUNT_FAIL, "dexoperator-not-exist");
if (!sp_tx_account->IsSelfUid(oldDetail.owner_regid))
return state.DoS(100, ERRORMSG("only owner can update dexoperator! owner_regid=%s, txUid=%s, dexId=%u",
oldDetail.owner_regid.ToString(),txUid.ToString(), update_data.dexId),
UPDATE_ACCOUNT_FAIL, "dexoperator-update-permession-deny");
if (!ProcessDexOperatorFee(*this, context, OPERATOR_ACTION_UPDATE))
return false;
DexOperatorDetail detail = oldDetail;
if (!update_data.UpdateToDexOperator(detail, cw))
return state.DoS(100, ERRORMSG("copy updated dex operator error! dex_id=%u", update_data.dexId),
UPDATE_ACCOUNT_FAIL, "copy-updated-operator-error");
if (!cw.dexCache.UpdateDexOperator(update_data.dexId, oldDetail, detail))
return state.DoS(100, ERRORMSG("save updated dex operator error! dex_id=%u", update_data.dexId),
UPDATE_ACCOUNT_FAIL, "save-updated-operator-error");
return true;
}
| 16,923 | 5,761 |
#pragma once
#include <Render/Pipelining/Render/FrameBufferRender.hh>
#include <glm\glm.hpp>
namespace AGE
{
class Texture2D;
class Program;
class GaussianBlur : public FrameBufferRender
{
public:
GaussianBlur(glm::uvec2 const &screenSize, std::shared_ptr<PaintingManager> painterManager,
std::shared_ptr<Texture2D> src, std::shared_ptr<Texture2D> dst, bool horizontal);
virtual ~GaussianBlur() = default;
protected:
virtual void renderPass(const DRBCameraDrawableList &infos);
glm::vec2 _inverseSourceSize;
std::shared_ptr<Texture2D> _source;
Key<Vertices> _quadVertices;
std::shared_ptr<Painter> _quadPainter;
};
}
| 650 | 249 |
#include "../../BenchmarkNode.h"
#include <stdint.h>
#include <iostream>
#include <cmath>
#define ITER_COUNT 2
#define CACHE_LINE 32 // cache line in byte
/* this structure represents a point */
/* these will be passed around to avoid copying coordinates */
typedef struct {
float weight;
float *coord;
long assign; /* number of point where this one is assigned */
float cost; /* cost of that assignment, weight*distance */
} Point;
/* this is the array of points */
typedef struct {
long num; /* number of points; may not be N if this is a sample */
int dim; /* dimensionality */
Point *p; /* the array itself */
} Points;
class SW_StreamCluster : public BenchmarkNode
{
int dataSize;
int dim;
int thread;
bool* is_center; //whether a point is a center
int* center_table; //index table of centers
int* work_mem;
Points points;
int *switch_membership;
float *lower;
float cost_of_opening_x;
float *low;
float *gl_lower;
int number_of_centers_to_close;
int x;
public:
SW_StreamCluster()
{
std::cin >> dataSize;
}
virtual void Initialize(int threadID, int procID);
virtual void Run();
virtual void Shutdown();
float dist(Point p1, Point p2, int dim);
double pgain(long x, Points *points, double z, long int *numcenters, int pid);
};
BENCH_DECL(SW_StreamCluster);
void SW_StreamCluster::Initialize(int threadID, int procID)
{
thread = threadID;
uint8_t* constCluster;
//dataSize=1024;
dim = 32;
is_center = new bool[dataSize];
center_table = new int[dataSize];
work_mem = new int[dataSize];
points.dim = dim;
points.num = dataSize;
points.p = (Point *)malloc(dataSize*sizeof(Point));
for( int i = 0; i < dataSize; i++ ) {
points.p[i].coord = (float*)malloc( dim*sizeof(float) );
}
switch_membership = new int[dataSize];
lower = new float[dataSize];
low = new float[dataSize];
gl_lower = new float[dataSize];
memset(center_table, 0, dataSize*sizeof(int));
memset(work_mem, 0, dataSize*sizeof(int));
memset(switch_membership, 0, dataSize*sizeof(int));
memset(lower, 0, dataSize*sizeof(float));
memset(low, 0, dataSize*sizeof(float));
memset(gl_lower, 0, dataSize*sizeof(float));
for (int i=0;i<dataSize;i++)
{
if (i%2)
is_center[i] = false;
else
is_center[i]= true;
}
}
void SW_StreamCluster::Shutdown()
{
while(true);
}
void SW_StreamCluster::Run()
{
int k1 = 0;
int k2 = dataSize;
for(int it= 0; it< ITER_COUNT; it++)
{
int count = 0;
for( int i = k1; i < k2; i++ ) {
if( is_center[i] ) {
center_table[i] = count++;
}
}
//this section is omitted because it is only required to normalize the partial counting done in the previous step for parallel code. Since this code is sequential, this step is unnecessary. To simplify things, I removed this step in the LCA and CFU versions as well.
/* for( int i = k1; i < k2; i++ ) {
if( is_center[i] ) {
center_table[i] += (int)work_mem[thread];
}
}*/
for (int i = k1; i < k2; i++ ) {
float x_cost = dist(points.p[i], points.p[x], points.dim) * points.p[i].weight;
float current_cost = points.p[i].cost;
if ( x_cost < current_cost ) {
switch_membership[i] = 1;
cost_of_opening_x += x_cost - current_cost;
} else {
int assign = points.p[i].assign;
lower[center_table[assign]] += current_cost - x_cost;
}
}
for ( int i = k1; i < k2; i++ ) {
if( is_center[i] ) {
gl_lower[center_table[i]] = low[i];
if ( low[i] > 0 ) {
++number_of_centers_to_close;
}
}
}
for ( int i = k1; i < k2; i++ ) {
bool close_center = gl_lower[center_table[points.p[i].assign]] > 0 ;
if ( switch_membership[i] || close_center ) {
points.p[i].cost = points.p[i].weight * dist(points.p[i], points.p[x], points.dim);
points.p[i].assign = x;
}
}
for( int i = k1; i < k2; i++ ) {
if( is_center[i] && gl_lower[center_table[i]] > 0 ) {
is_center[i] = false;
}
}
}
}
/* compute Euclidean distance squared between two points */
float SW_StreamCluster::dist(Point p1, Point p2, int dim)
{
int i;
float result=0.0;
for (i=0;i<dim;i++)
result += (p1.coord[i] - p2.coord[i])*(p1.coord[i] - p2.coord[i]);
return(result);
}
| 4,332 | 1,689 |
/*=========================================================================
Program: ShapeWorks: Particle-based Shape Correspondence & Visualization
File: Optimize.cpp
Copyright (c) 2020 Scientific Computing and Imaging Institute.
See ShapeWorksLicense.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
// std
#include <sstream>
#include <string>
#include <iostream>
#include <vector>
#include <numeric>
#include <algorithm>
#ifdef _WIN32
#include <direct.h>
#define mkdir _mkdir
#else
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#endif // ifdef _WIN32
// itk
#include <itkImageFileReader.h>
#include <itkMultiThreaderBase.h>
#include <itkZeroCrossingImageFilter.h>
#include <itkImageRegionIteratorWithIndex.h>
#include <itkMacro.h>
// vtk
#include <vtkContourFilter.h>
#include <vtkSmartPointer.h>
#include <vtkImageData.h>
#include <vtkPolyData.h>
#include <vtkMassProperties.h>
// particle system
#include "TriMesh.h"
#include "itkImageToVTKImageFilter.h"
#include "itkParticleImageDomain.h"
#include "itkParticleImageDomainWithGradients.h"
#include "itkParticleImplicitSurfaceDomain.h"
#include "itkParticleImageDomainWithHessians.h"
#include "object_reader.h"
#include "object_writer.h"
#include <Optimize.h>
//---------------------------------------------------------------------------
Optimize::Optimize()
{
this->m_sampler = itk::MaximumEntropyCorrespondenceSampler<ImageType>::New();
}
//---------------------------------------------------------------------------
bool Optimize::Run()
{
// sanity check
if (this->m_domains_per_shape != this->m_number_of_particles.size()) {
std::cerr <<
"Inconsistency in parameters... m_domains_per_shape != m_number_of_particles.size()\n";
return false;
}
this->SetParameters();
int number_of_splits = static_cast<int>(
std::log2(static_cast<double>(this->m_number_of_particles[0])) + 1);
this->m_iteration_count = 0;
this->m_total_iterations = (number_of_splits * this->m_iterations_per_split) +
this->m_optimization_iterations;
if (this->m_verbosity_level > 0) {
std::cout << "Total number of iterations = " << this->m_total_iterations << "\n";
}
m_disable_procrustes = true;
m_disable_checkpointing = true;
// Initialize
if (m_processing_mode >= 0) { this->Initialize();}
// Introduce adaptivity
if (m_processing_mode >= 1 || m_processing_mode == -1) { this->AddAdaptivity();}
// Optimize
if (m_processing_mode >= 2 || m_processing_mode == -2) { this->RunOptimize();}
this->UpdateExportablePoints();
return true;
}
//---------------------------------------------------------------------------
void Optimize::RunProcrustes()
{
this->OptimizerStop();
m_procrustes->RunRegistration();
}
//---------------------------------------------------------------------------
void Optimize::SetParameters()
{
if (this->m_verbosity_level == 0) {
std::cout <<
"Verbosity 0: This will be the only output on your screen, unless there are any errors. Increase the verbosity if needed."
<< std::endl;
}
// Set up the optimization process
this->m_sampler->SetDomainsPerShape(this->m_domains_per_shape); // must be done first!
this->m_sampler->SetTimeptsPerIndividual(this->m_timepts_per_subject);
this->m_sampler->GetParticleSystem()->SetDomainsPerShape(this->m_domains_per_shape);
this->m_sampler->SetVerbosity(this->m_verbosity_level);
if (this->m_use_xyz.size() > 0) {
for (int i = 0; i < this->m_domains_per_shape; i++) {
this->m_sampler->SetXYZ(i, this->m_use_xyz[i]);
}
}
else {
for (int i = 0; i < this->m_domains_per_shape; i++) {
this->m_sampler->SetXYZ(i, false);
}
}
if (this->m_use_normals.size() > 0) {
for (int i = 0; i < this->m_domains_per_shape; i++) {
this->m_sampler->SetNormals(i, this->m_use_normals[i]);
}
}
else {
for (int i = 0; i < this->m_domains_per_shape; i++) {
this->m_sampler->SetNormals(i, false);
}
}
// Set up the procrustes registration object.
this->m_procrustes = itk::ParticleProcrustesRegistration < 3 > ::New();
this->m_procrustes->SetParticleSystem(this->m_sampler->GetParticleSystem());
this->m_procrustes->SetDomainsPerShape(this->m_domains_per_shape);
if (this->m_procrustes_scaling == 0) {
this->m_procrustes->ScalingOff();
}
else {
this->m_procrustes->ScalingOn();
}
this->SetIterationCallback();
this->PrintStartMessage("Initializing variables...");
this->InitializeSampler();
this->PrintDoneMessage();
if (m_use_normals.size() > 0) {
int numShapes = m_sampler->GetParticleSystem()->GetNumberOfDomains();
for (int i = 0; i < numShapes; i++) {
if (m_use_normals[i % m_domains_per_shape]) {
continue;
}
itk::ParticleImageDomainWithHessians<float, 3>* domainWithHess =
static_cast < itk::ParticleImageDomainWithHessians<float,
3>*> (m_sampler->GetParticleSystem()
->GetDomain(i));
domainWithHess->DeletePartialDerivativeImages();
}
}
else {
int numShapes = m_sampler->GetParticleSystem()->GetNumberOfDomains();
for (int i = 0; i < numShapes; i++) {
itk::ParticleImageDomainWithHessians<float, 3>* domainWithHess =
static_cast < itk::ParticleImageDomainWithHessians < float,
3 >
* > (m_sampler->GetParticleSystem()->GetDomain(i));
domainWithHess->DeletePartialDerivativeImages();
}
}
if (m_domain_flags.size() > 0) {
for (int i = 0; i < m_domain_flags.size(); i++) {
itk::ParticleImageDomainWithHessians<float, 3>* domainWithHess =
static_cast < itk::ParticleImageDomainWithHessians < float,
3 >
* > (m_sampler->GetParticleSystem()->GetDomain(m_domain_flags[i]));
if (m_use_normals.size() > 0) {
if (m_use_normals[i % m_domains_per_shape]) {
domainWithHess->DeletePartialDerivativeImages();
}
else {
domainWithHess->DeleteImages();
}
}
}
}
if (m_verbosity_level > 1) {
this->PrintParamInfo();
}
m_good_bad = itk::ParticleGoodBadAssessment<float, 3>::New();
m_good_bad->SetDomainsPerShape(m_domains_per_shape);
m_good_bad->SetCriterionAngle(m_normal_angle);
m_good_bad->SetPerformAssessment(m_perform_good_bad);
m_energy_a.clear();
m_energy_b.clear();
m_total_energy.clear();
// Now read the transform file if present.
if (m_transform_file != "") { this->ReadTransformFile(); }
if (m_prefix_transform_file != "") { this->ReadPrefixTransformFile(m_prefix_transform_file); }
}
//---------------------------------------------------------------------------
Optimize::~Optimize() {}
//---------------------------------------------------------------------------
void Optimize::SetVerbosity(int verbosity_level)
{
this->m_verbosity_level = verbosity_level;
}
//---------------------------------------------------------------------------
void Optimize::SetDomainsPerShape(int domains_per_shape)
{
this->m_domains_per_shape = domains_per_shape;
this->m_sampler->SetDomainsPerShape(this->m_domains_per_shape);
}
//---------------------------------------------------------------------------
int Optimize::GetDomainsPerShape()
{
return this->m_domains_per_shape;
}
//---------------------------------------------------------------------------
void Optimize::SetNumberOfParticles(std::vector<unsigned int> number_of_particles)
{
this->m_number_of_particles = number_of_particles;
}
//---------------------------------------------------------------------------
std::vector<unsigned int> Optimize::GetNumberOfParticles()
{
return this->m_number_of_particles;
}
//---------------------------------------------------------------------------
void Optimize::SetTransformFile(std::string filename)
{
this->m_transform_file = filename;
}
//---------------------------------------------------------------------------
std::string Optimize::GetTransformFile()
{
return this->m_transform_file;
}
//---------------------------------------------------------------------------
void Optimize::SetPrefixTransformFile(std::string prefix_transform_file)
{
this->m_prefix_transform_file = prefix_transform_file;
}
//---------------------------------------------------------------------------
std::string Optimize::GetPrefixTransformFile()
{
return this->m_prefix_transform_file;
}
//---------------------------------------------------------------------------
void Optimize::SetOutputDir(std::string output_dir)
{
this->m_output_dir = output_dir;
}
//---------------------------------------------------------------------------
void Optimize::SetOutputTransformFile(std::string output_transform_file)
{
this->m_output_transform_file = output_transform_file;
}
//---------------------------------------------------------------------------
void Optimize::SetUseMeshBasedAttributes(bool use_mesh_based_attributes)
{
this->m_mesh_based_attributes = use_mesh_based_attributes;
if (this->m_mesh_based_attributes) {
this->m_sampler->RegisterGeneralShapeMatrices();
}
}
//---------------------------------------------------------------------------
bool Optimize::GetUseMeshBasedAttributes()
{
return this->m_mesh_based_attributes;
}
//---------------------------------------------------------------------------
void Optimize::SetUseXYZ(std::vector<bool> use_xyz)
{
this->m_use_xyz = use_xyz;
}
//---------------------------------------------------------------------------
void Optimize::SetUseNormals(std::vector<bool> use_normals)
{
this->m_use_normals = use_normals;
}
//---------------------------------------------------------------------------
void Optimize::SetAttributesPerDomain(std::vector<int> attributes_per_domain)
{
this->m_attributes_per_domain = attributes_per_domain;
this->m_sampler->SetAttributesPerDomain(attributes_per_domain);
}
//---------------------------------------------------------------------------
std::vector<int> Optimize::GetAttributesPerDomain()
{
return this->m_attributes_per_domain;
}
//---------------------------------------------------------------------------
void Optimize::SetDistributionDomainID(int distribution_domain_id)
{
this->m_distribution_domain_id = distribution_domain_id;
}
//---------------------------------------------------------------------------
int Optimize::GetDistributionDomainID()
{
return this->m_distribution_domain_id;
}
//---------------------------------------------------------------------------
void Optimize::SetOutputCuttingPlaneFile(std::string output_cutting_plane_file)
{
this->m_output_cutting_plane_file = output_cutting_plane_file;
}
//---------------------------------------------------------------------------
void Optimize::SetUseCuttingPlanes(bool use_cutting_planes)
{
this->m_use_cutting_planes = use_cutting_planes;
}
//---------------------------------------------------------------------------
void Optimize::SetCuttingPlane(unsigned int i, const vnl_vector_fixed<double, 3> &va,
const vnl_vector_fixed<double, 3> &vb,
const vnl_vector_fixed<double, 3> &vc)
{
this->m_sampler->SetCuttingPlane(i, va, vb, vc);
}
//---------------------------------------------------------------------------
void Optimize::SetProcessingMode(int mode)
{
this->m_processing_mode = mode;
}
//---------------------------------------------------------------------------
void Optimize::SetAdaptivityMode(int adaptivity_mode)
{
this->m_adaptivity_mode = adaptivity_mode;
}
//---------------------------------------------------------------------------
void Optimize::SetAdaptivityStrength(double adaptivity_strength)
{
this->m_adaptivity_strength = adaptivity_strength;
}
//---------------------------------------------------------------------------
void Optimize::ReadTransformFile()
{
object_reader < itk::ParticleSystem < 3 > ::TransformType > reader;
reader.SetFileName(m_transform_file);
reader.Update();
for (unsigned int i = 0; i < m_sampler->GetParticleSystem()->GetNumberOfDomains(); i++) {
m_sampler->GetParticleSystem()->SetTransform(i, reader.GetOutput()[i]);
}
}
//---------------------------------------------------------------------------
void Optimize::ReadPrefixTransformFile(const std::string &fn)
{
object_reader < itk::ParticleSystem < 3 > ::TransformType > reader;
reader.SetFileName(fn.c_str());
reader.Update();
for (unsigned int i = 0; i < m_sampler->GetParticleSystem()->GetNumberOfDomains(); i++) {
m_sampler->GetParticleSystem()->SetPrefixTransform(i, reader.GetOutput()[i]);
}
}
//---------------------------------------------------------------------------
// Initialization and Optimization
void Optimize::InitializeSampler()
{
float nbhd_to_sigma = 3.0; // 3.0 -> 1.0
float flat_cutoff = 0.3; // 0.3 -> 0.85
m_sampler->SetPairwisePotentialType(m_pairwise_potential_type);
m_sampler->GetGradientFunction()->SetFlatCutoff(flat_cutoff);
m_sampler->GetCurvatureGradientFunction()->SetFlatCutoff(flat_cutoff);
m_sampler->GetGradientFunction()->SetNeighborhoodToSigmaRatio(nbhd_to_sigma);
m_sampler->GetCurvatureGradientFunction()->SetNeighborhoodToSigmaRatio(nbhd_to_sigma);
m_sampler->GetModifiedCotangentGradientFunction()->SetFlatCutoff(flat_cutoff);
m_sampler->GetModifiedCotangentGradientFunction()->SetNeighborhoodToSigmaRatio(nbhd_to_sigma);
m_sampler->GetOmegaGradientFunction()->SetFlatCutoff(flat_cutoff);
m_sampler->GetOmegaGradientFunction()->SetNeighborhoodToSigmaRatio(nbhd_to_sigma);
m_sampler->GetEnsembleEntropyFunction()->SetMinimumVariance(m_starting_regularization);
m_sampler->GetEnsembleEntropyFunction()->SetRecomputeCovarianceInterval(1);
m_sampler->GetEnsembleEntropyFunction()->SetHoldMinimumVariance(false);
m_sampler->GetMeshBasedGeneralEntropyGradientFunction()->SetMinimumVariance(
m_starting_regularization);
m_sampler->GetMeshBasedGeneralEntropyGradientFunction()->SetRecomputeCovarianceInterval(1);
m_sampler->GetMeshBasedGeneralEntropyGradientFunction()->SetHoldMinimumVariance(false);
m_sampler->GetEnsembleRegressionEntropyFunction()->SetMinimumVariance(m_starting_regularization);
m_sampler->GetEnsembleRegressionEntropyFunction()->SetRecomputeCovarianceInterval(1);
m_sampler->GetEnsembleRegressionEntropyFunction()->SetHoldMinimumVariance(false);
m_sampler->GetEnsembleMixedEffectsEntropyFunction()->SetMinimumVariance(m_starting_regularization);
m_sampler->GetEnsembleMixedEffectsEntropyFunction()->SetRecomputeCovarianceInterval(1);
m_sampler->GetEnsembleMixedEffectsEntropyFunction()->SetHoldMinimumVariance(false);
m_sampler->GetOptimizer()->SetTimeStep(1.0);
if (m_optimizer_type == 0) {
m_sampler->GetOptimizer()->SetModeToJacobi();
}
else if (m_optimizer_type == 1) {
m_sampler->GetOptimizer()->SetModeToGaussSeidel();
}
else {
m_sampler->GetOptimizer()->SetModeToAdaptiveGaussSeidel();
}
m_sampler->SetSamplingOn();
m_sampler->SetCorrespondenceOn();
m_sampler->SetAdaptivityMode(m_adaptivity_mode);
m_sampler->GetEnsembleEntropyFunction()
->SetRecomputeCovarianceInterval(m_recompute_regularization_interval);
m_sampler->GetMeshBasedGeneralEntropyGradientFunction()
->SetRecomputeCovarianceInterval(m_recompute_regularization_interval);
m_sampler->GetEnsembleRegressionEntropyFunction()
->SetRecomputeCovarianceInterval(m_recompute_regularization_interval);
m_sampler->GetEnsembleMixedEffectsEntropyFunction()
->SetRecomputeCovarianceInterval(m_recompute_regularization_interval);
m_sampler->Initialize();
m_sampler->GetOptimizer()->SetTolerance(0.0);
}
//---------------------------------------------------------------------------
double Optimize::GetMinNeighborhoodRadius()
{
double rad = 0.0;
typename itk::ImageToVTKImageFilter < ImageType > ::Pointer itk2vtkConnector;
for (unsigned int i = 0; i < m_sampler->GetParticleSystem()->GetNumberOfDomains(); i++) {
const itk::ParticleImageDomain < float,
3 >* domain = static_cast < const itk::ParticleImageDomain < float,
3 >
* > (m_sampler->GetParticleSystem()
->GetDomain(i));
itk2vtkConnector = itk::ImageToVTKImageFilter < ImageType > ::New();
itk2vtkConnector->SetInput(domain->GetImage());
vtkSmartPointer < vtkContourFilter > ls = vtkSmartPointer < vtkContourFilter > ::New();
ls->SetInputData(itk2vtkConnector->GetOutput());
ls->SetValue(0, 0.0);
ls->Update();
vtkSmartPointer < vtkMassProperties > mp = vtkSmartPointer < vtkMassProperties > ::New();
mp->SetInputData(ls->GetOutput());
mp->Update();
double area = mp->GetSurfaceArea();
double sigma =
std::sqrt(area / (m_sampler->GetParticleSystem()->GetNumberOfParticles(i) * M_PI));
if (rad < sigma) {
rad = sigma;
}
}
return rad;
}
//---------------------------------------------------------------------------
void Optimize::AddSinglePoint()
{
typedef itk::ParticleSystem < 3 > ParticleSystemType;
typedef ParticleSystemType::PointType PointType;
for (unsigned int i = 0; i < m_sampler->GetParticleSystem()->GetNumberOfDomains();
i++) {
if (m_sampler->GetParticleSystem()->GetNumberOfParticles(i) > 0) {
continue;
}
bool done = false;
ImageType::Pointer img = dynamic_cast < itk::ParticleImageDomain < float, 3 >* > (
m_sampler->GetParticleSystem()->GetDomain(i))->GetImage();
itk::ZeroCrossingImageFilter < ImageType, ImageType > ::Pointer zc =
itk::ZeroCrossingImageFilter < ImageType, ImageType > ::New();
zc->SetInput(img);
zc->Update();
itk::ImageRegionConstIteratorWithIndex < ImageType > it(zc->GetOutput(),
zc->GetOutput()->GetRequestedRegion());
for (it.GoToReverseBegin(); !it.IsAtReverseEnd() && done == false; --it) {
if (it.Get() == 1.0) {
PointType pos;
img->TransformIndexToPhysicalPoint(it.GetIndex(), pos);
done = true;
try
{
m_sampler->GetParticleSystem()->AddPosition(pos, i);
} catch (itk::ExceptionObject &) {
done = false;
}
}
}
}
}
//---------------------------------------------------------------------------
void Optimize::Initialize()
{
if (m_verbosity_level > 0) {
std::cout << "------------------------------\n";
std::cout << "*** Initialize Step\n";
std::cout << "------------------------------\n";
}
m_disable_checkpointing = true;
m_disable_procrustes = false;
if (m_procrustes_interval != 0) { // Initial registration
for (int i = 0; i < this->m_domains_per_shape; i++) {
if (m_sampler->GetParticleSystem()->GetNumberOfParticles(i) > 10) {
m_procrustes->RunRegistration(i);
}
}
this->WritePointFiles();
this->WriteTransformFile();
}
m_disable_procrustes = true;
m_sampler->GetParticleSystem()->SynchronizePositions();
m_sampler->GetCurvatureGradientFunction()->SetRho(0.0);
m_sampler->GetOmegaGradientFunction()->SetRho(0.0);
m_sampler->SetCorrespondenceOn();
if (m_use_shape_statistics_in_init) {
if (m_attributes_per_domain.size() > 0 &&
*std::max_element(m_attributes_per_domain.begin(), m_attributes_per_domain.end()) > 0) {
if (m_mesh_based_attributes) {
m_sampler->SetCorrespondenceMode(5);
}
else {
m_sampler->SetCorrespondenceMode(2);
}
}
else {
if (m_mesh_based_attributes) {
m_sampler->SetCorrespondenceMode(5);
}
else {
m_sampler->SetCorrespondenceMode(1);
}
}
m_sampler->GetEnsembleEntropyFunction()->SetMinimumVarianceDecay(m_starting_regularization,
m_ending_regularization,
m_iterations_per_split);
m_sampler->GetMeshBasedGeneralEntropyGradientFunction()->SetMinimumVarianceDecay(
m_starting_regularization,
m_ending_regularization,
m_iterations_per_split);
}
else {
// force to mean
if ((m_attributes_per_domain.size() > 0 &&
*std::max_element(m_attributes_per_domain.begin(),
m_attributes_per_domain.end()) > 0) || m_mesh_based_attributes) {
m_sampler->SetCorrespondenceMode(6);
}
else {
m_sampler->SetCorrespondenceMode(0);
}
}
m_sampler->GetLinkingFunction()->SetRelativeGradientScaling(m_initial_relative_weighting);
m_sampler->GetLinkingFunction()->SetRelativeEnergyScaling(m_initial_relative_weighting);
this->AddSinglePoint();
m_sampler->GetParticleSystem()->SynchronizePositions();
int split_number = 0;
int n = m_sampler->GetParticleSystem()->GetNumberOfDomains();
vnl_vector_fixed < double, 3 > random;
srand(1);
for (int i = 0; i < 3; i++) {
random[i] = static_cast < double > (rand());
}
double norm = random.magnitude();
random /= norm;
double epsilon = this->m_spacing;
bool flag_split = false;
for (int i = 0; i < n; i++) {
int d = i % m_domains_per_shape;
if (m_sampler->GetParticleSystem()->GetNumberOfParticles(i) < m_number_of_particles[d]) {
flag_split = true;
break;
}
}
while (flag_split) {
// m_Sampler->GetEnsembleEntropyFunction()->PrintShapeMatrix();
this->OptimizerStop();
for (int i = 0; i < n; i++) {
int d = i % m_domains_per_shape;
if (m_sampler->GetParticleSystem()->GetNumberOfParticles(i) < m_number_of_particles[d]) {
m_sampler->GetParticleSystem()->SplitAllParticlesInDomain(random, epsilon, i, 0);
}
}
m_sampler->GetParticleSystem()->SynchronizePositions();
split_number++;
if (m_verbosity_level > 0) {
std::cout << "split number = " << split_number << std::endl;
std::cout << std::endl << "Particle count: ";
for (unsigned int i = 0; i < this->m_domains_per_shape; i++) {
std::cout << m_sampler->GetParticleSystem()->GetNumberOfParticles(i) << " ";
}
std::cout << std::endl;
}
if (m_save_init_splits == true) {
std::stringstream ss;
ss << split_number;
std::stringstream ssp;
std::string dir_name = "split" + ss.str();
for (int i = 0; i < m_domains_per_shape; i++) {
ssp << m_sampler->GetParticleSystem()->GetNumberOfParticles(i);
dir_name += "_" + ssp.str();
ssp.str("");
}
dir_name += "pts_wo_opt";
std::string out_path = m_output_dir;
std::string tmp_dir_name = out_path + "/" + dir_name;
this->WritePointFiles(tmp_dir_name + "/");
this->WritePointFilesWithFeatures(tmp_dir_name + "/");
this->WriteTransformFile(tmp_dir_name + "/" + m_output_transform_file);
this->WriteParameters(split_number);
}
m_energy_a.clear();
m_energy_b.clear();
m_total_energy.clear();
std::stringstream ss;
ss << split_number;
std::stringstream ssp;
ssp << m_sampler->GetParticleSystem()->GetNumberOfParticles(); // size from domain 0
m_str_energy = "split" + ss.str();
for (int i = 0; i < m_domains_per_shape; i++) {
ssp << m_sampler->GetParticleSystem()->GetNumberOfParticles(i);
m_str_energy += "_" + ssp.str();
ssp.str("");
}
m_str_energy += "pts_init";
if (this->m_pairwise_potential_type == 1) {
this->SetCotanSigma();
double minRad = 3.0 * this->GetMinNeighborhoodRadius();
m_sampler->GetModifiedCotangentGradientFunction()->SetMinimumNeighborhoodRadius(minRad);
m_sampler->GetConstrainedModifiedCotangentGradientFunction()->SetMinimumNeighborhoodRadius(
minRad);
}
m_saturation_counter = 0;
m_sampler->GetOptimizer()->SetMaximumNumberOfIterations(m_iterations_per_split);
m_sampler->GetOptimizer()->SetNumberOfIterations(0);
m_sampler->Modified();
m_sampler->Update();
if (m_save_init_splits == true) {
std::stringstream ss;
ss << split_number;
std::stringstream ssp;
std::string dir_name = "split" + ss.str();
for (int i = 0; i < m_domains_per_shape; i++) {
ssp << m_sampler->GetParticleSystem()->GetNumberOfParticles(i);
dir_name += "_" + ssp.str();
ssp.str("");
}
dir_name += "pts_w_opt";
std::string out_path = m_output_dir;
std::string tmp_dir_name = out_path + "/" + dir_name;
this->WritePointFiles(tmp_dir_name + "/");
this->WritePointFilesWithFeatures(tmp_dir_name + "/");
this->WriteTransformFile(tmp_dir_name + "/" + m_output_transform_file);
this->WriteParameters(split_number);
}
this->WritePointFiles();
this->WritePointFilesWithFeatures();
this->WriteEnergyFiles();
this->WriteTransformFile();
flag_split = false;
for (int i = 0; i < n; i++) {
int d = i % m_domains_per_shape;
if (m_sampler->GetParticleSystem()->GetNumberOfParticles(i) < m_number_of_particles[d]) {
flag_split = true;
break;
}
}
}
this->WritePointFiles();
this->WritePointFilesWithFeatures();
this->WriteTransformFile();
this->WriteCuttingPlanePoints();
if (m_verbosity_level > 0) {
std::cout << "Finished initialization!!!" << std::endl;
}
}
//---------------------------------------------------------------------------
void Optimize::AddAdaptivity()
{
if (m_verbosity_level > 0) {
std::cout << "------------------------------\n";
std::cout << "*** AddAdaptivity Step\n";
std::cout << "------------------------------\n";
}
if (m_adaptivity_strength == 0.0) { return;}
m_disable_checkpointing = true;
m_disable_procrustes = true;
if (this->m_pairwise_potential_type == 1) {
this->SetCotanSigma();
}
double minRad = 3.0 * this->GetMinNeighborhoodRadius();
m_sampler->GetModifiedCotangentGradientFunction()->SetMinimumNeighborhoodRadius(minRad);
m_sampler->GetConstrainedModifiedCotangentGradientFunction()->SetMinimumNeighborhoodRadius(minRad);
m_sampler->GetCurvatureGradientFunction()->SetRho(m_adaptivity_strength);
m_sampler->GetOmegaGradientFunction()->SetRho(m_adaptivity_strength);
m_sampler->GetLinkingFunction()->SetRelativeGradientScaling(m_initial_relative_weighting);
m_sampler->GetLinkingFunction()->SetRelativeEnergyScaling(m_initial_relative_weighting);
m_saturation_counter = 0;
m_sampler->GetOptimizer()->SetMaximumNumberOfIterations(m_iterations_per_split);
m_sampler->GetOptimizer()->SetNumberOfIterations(0);
m_sampler->Modified();
m_sampler->Update();
this->WritePointFiles();
this->WritePointFilesWithFeatures();
this->WriteTransformFile();
this->WriteCuttingPlanePoints();
if (m_verbosity_level > 0) {
std::cout << "Finished adaptivity!!!" << std::endl;
}
}
//---------------------------------------------------------------------------
void Optimize::RunOptimize()
{
if (m_verbosity_level > 0) {
std::cout << "------------------------------\n";
std::cout << "*** Optimize Step\n";
std::cout << "------------------------------\n";
}
m_optimizing = true;
m_sampler->GetCurvatureGradientFunction()->SetRho(m_adaptivity_strength);
m_sampler->GetOmegaGradientFunction()->SetRho(m_adaptivity_strength);
m_sampler->GetLinkingFunction()->SetRelativeGradientScaling(m_relative_weighting);
m_sampler->GetLinkingFunction()->SetRelativeEnergyScaling(m_relative_weighting);
if (this->m_pairwise_potential_type == 1) {
this->SetCotanSigma();
double minRad = 3.0 * this->GetMinNeighborhoodRadius();
m_sampler->GetModifiedCotangentGradientFunction()->SetMinimumNeighborhoodRadius(minRad);
m_sampler->GetConstrainedModifiedCotangentGradientFunction()->SetMinimumNeighborhoodRadius(
minRad);
}
m_disable_checkpointing = false;
m_disable_procrustes = false;
if (m_procrustes_interval != 0) { // Initial registration
m_procrustes->RunRegistration();
this->WritePointFiles();
this->WriteTransformFile();
if (m_use_cutting_planes == true && m_distribution_domain_id > -1) {
// transform cutting planes
m_sampler->TransformCuttingPlanes(m_distribution_domain_id);
}
}
if (m_optimizer_type == 0) {
m_sampler->GetOptimizer()->SetModeToJacobi();
}
else if (m_optimizer_type == 1) {
m_sampler->GetOptimizer()->SetModeToGaussSeidel();
}
else {
m_sampler->GetOptimizer()->SetModeToAdaptiveGaussSeidel();
}
// Set up the minimum variance decay
m_sampler->GetEnsembleEntropyFunction()->SetMinimumVarianceDecay(m_starting_regularization,
m_ending_regularization,
m_optimization_iterations -
m_optimization_iterations_completed);
m_sampler->GetMeshBasedGeneralEntropyGradientFunction()->SetMinimumVarianceDecay(
m_starting_regularization,
m_ending_regularization,
m_optimization_iterations -
m_optimization_iterations_completed);
m_sampler->GetEnsembleRegressionEntropyFunction()->SetMinimumVarianceDecay(
m_starting_regularization,
m_ending_regularization,
m_optimization_iterations -
m_optimization_iterations_completed);
m_sampler->GetEnsembleMixedEffectsEntropyFunction()->SetMinimumVarianceDecay(
m_starting_regularization,
m_ending_regularization,
m_optimization_iterations -
m_optimization_iterations_completed);
m_sampler->GetEnsembleMixedEffectsEntropyFunction()->SetMinimumVarianceDecay(
m_starting_regularization,
m_ending_regularization,
m_optimization_iterations -
m_optimization_iterations_completed);
m_sampler->SetCorrespondenceOn();
if ((m_attributes_per_domain.size() > 0 &&
*std::max_element(m_attributes_per_domain.begin(),
m_attributes_per_domain.end()) > 0) || m_mesh_based_attributes) {
m_sampler->SetCorrespondenceMode(5);
}
else if (m_use_regression == true) {
if (m_use_mixed_effects == true) {
m_sampler->SetCorrespondenceMode(4); // MixedEffects
}
else {
m_sampler->SetCorrespondenceMode(3); // Regression
}
}
else if (m_starting_regularization == m_ending_regularization) {
m_sampler->SetCorrespondenceMode(0); // mean force
}
else {
m_sampler->SetCorrespondenceMode(1); // Ensemble Entropy
}
if (m_optimization_iterations - m_optimization_iterations_completed > 0) {
m_sampler->GetOptimizer()->SetMaximumNumberOfIterations(
m_optimization_iterations - m_optimization_iterations_completed);
}
else { m_sampler->GetOptimizer()->SetMaximumNumberOfIterations(0);}
m_energy_a.clear();
m_energy_b.clear();
m_total_energy.clear();
m_str_energy = "opt";
m_saturation_counter = 0;
m_sampler->GetOptimizer()->SetNumberOfIterations(0);
m_sampler->GetOptimizer()->SetTolerance(0.0);
m_sampler->Modified();
m_sampler->Update();
this->WritePointFiles();
this->WritePointFilesWithFeatures();
this->WriteEnergyFiles();
this->WriteTransformFile();
this->WriteModes();
this->WriteCuttingPlanePoints();
this->WriteParameters();
if (m_verbosity_level > 0) {
std::cout << "Finished optimization!!!" << std::endl;
}
}
//---------------------------------------------------------------------------
void Optimize::OptimizeStart()
{
m_sampler->GetOptimizer()->StartOptimization();
}
//---------------------------------------------------------------------------
void Optimize::OptimizerStop()
{
m_sampler->GetOptimizer()->StopOptimization();
}
//---------------------------------------------------------------------------
void Optimize::AbortOptimization()
{
this->m_aborted = true;
this->m_sampler->GetOptimizer()->AbortProcessing();
}
//---------------------------------------------------------------------------
void Optimize::IterateCallback(itk::Object*, const itk::EventObject &)
{
if (m_perform_good_bad == true) {
std::vector < std::vector < int >> tmp;
tmp = m_good_bad->RunAssessment(m_sampler->GetParticleSystem(),
m_sampler->GetMeanCurvatureCache());
if (!tmp.empty()) {
if (this->m_bad_ids.empty()) {
this->m_bad_ids.resize(m_domains_per_shape);
}
for (int i = 0; i < m_domains_per_shape; i++) {
for (int j = 0; j < tmp[i].size(); j++) {
if (m_bad_ids[i].empty()) {
this->m_bad_ids[i].push_back(tmp[i][j]);
}
else {
if (std::count(m_bad_ids[i].begin(), m_bad_ids[i].end(), tmp[i][j]) == 0) {
this->m_bad_ids[i].push_back(tmp[i][j]);
}
}
}
}
}
ReportBadParticles();
}
this->ComputeEnergyAfterIteration();
int lnth = m_total_energy.size();
if (lnth > 1) {
double val = std::abs(m_total_energy[lnth - 1] - m_total_energy[lnth - 2]) / std::abs(
m_total_energy[lnth - 2]);
if ((m_optimizing == false && val < m_initialization_criterion) ||
(m_optimizing == true && val < m_optimization_criterion)) {
m_saturation_counter++;
}
else {
m_saturation_counter = 0;
}
if (m_saturation_counter > 10) {
if (m_verbosity_level > 2) {
std::cout << " \n ----Early termination due to minimal energy decay---- \n";
}
this->OptimizerStop();
}
}
if (m_checkpointing_interval != 0 && m_disable_checkpointing == false) {
m_checkpoint_counter++;
if (m_checkpoint_counter == (int)m_checkpointing_interval) {
m_checkpoint_counter = 0;
this->WritePointFiles();
this->WriteTransformFile();
this->WritePointFilesWithFeatures();
this->WriteModes();
this->WriteParameters();
this->WriteEnergyFiles();
}
}
if (m_optimizing == false) { return;}
if (m_procrustes_interval != 0 && m_disable_procrustes == false) {
m_procrustes_counter++;
if (m_procrustes_counter >= (int)m_procrustes_interval) {
m_procrustes_counter = 0;
m_procrustes->RunRegistration();
if (m_use_cutting_planes == true && m_distribution_domain_id > -1) {
// transform cutting planes
m_sampler->TransformCuttingPlanes(m_distribution_domain_id);
}
}
}
static unsigned int iteration_no = 0;
// Checkpointing after procrustes (override for optimizing step)
if (m_checkpointing_interval != 0 && m_disable_checkpointing == false) {
m_checkpoint_counter++;
if (m_checkpoint_counter == (int)m_checkpointing_interval) {
iteration_no += m_checkpointing_interval;
m_checkpoint_counter = 0;
this->WritePointFiles();
this->WriteTransformFile();
this->WritePointFilesWithFeatures();
this->WriteModes();
this->WriteParameters();
this->WriteEnergyFiles();
if (m_keep_checkpoints) {
this->WritePointFiles(iteration_no);
this->WritePointFilesWithFeatures(iteration_no);
this->WriteTransformFile(iteration_no);
this->WriteParameters(iteration_no);
}
}
}
}
//---------------------------------------------------------------------------
void Optimize::ComputeEnergyAfterIteration()
{
int numShapes = m_sampler->GetParticleSystem()->GetNumberOfDomains();
double corrEnergy = 0.0;
double sampEnergy = 0.0;
for (int i = 0; i < numShapes; i++) {
m_sampler->GetLinkingFunction()->SetDomainNumber(i);
for (int j = 0; j < m_sampler->GetParticleSystem()->GetNumberOfParticles(i); j++) {
if (m_sampler->GetParticleSystem()->GetDomainFlag(i)) {
sampEnergy += 0.0;
}
else {
sampEnergy +=
m_sampler->GetLinkingFunction()->EnergyA(j, i, m_sampler->GetParticleSystem());
}
if (m_sampler->GetCorrespondenceMode() == 0) {
corrEnergy +=
m_sampler->GetLinkingFunction()->EnergyB(j, i, m_sampler->GetParticleSystem());
}
}
}
if (m_sampler->GetCorrespondenceMode() > 0) {
corrEnergy = m_sampler->GetLinkingFunction()->EnergyB(0, 0, m_sampler->GetParticleSystem());
}
double totalEnergy = sampEnergy + corrEnergy;
m_energy_a.push_back(sampEnergy);
m_energy_b.push_back(corrEnergy);
m_total_energy.push_back(totalEnergy);
if (m_verbosity_level > 2) {
std::cout << "Energy: " << totalEnergy << std::endl;
}
}
//---------------------------------------------------------------------------
void Optimize::SetCotanSigma()
{
itk::ImageToVTKImageFilter<ImageType>::Pointer itk2vtkConnector;
m_sampler->GetModifiedCotangentGradientFunction()->ClearGlobalSigma();
for (unsigned int i = 0; i < m_sampler->GetParticleSystem()->GetNumberOfDomains(); i++) {
using DomainType = itk::ParticleImageDomain<float, 3>;
const DomainType* domain =
static_cast<const DomainType*> (m_sampler->GetParticleSystem()->GetDomain(i));
itk2vtkConnector = itk::ImageToVTKImageFilter<ImageType>::New();
itk2vtkConnector->SetInput(domain->GetImage());
vtkSmartPointer<vtkContourFilter> ls = vtkSmartPointer<vtkContourFilter>::New();
ls->SetInputData(itk2vtkConnector->GetOutput());
ls->SetValue(0, 0.0);
ls->Update();
vtkSmartPointer<vtkMassProperties> mp = vtkSmartPointer<vtkMassProperties>::New();
mp->SetInputData(ls->GetOutput());
mp->Update();
double area = mp->GetSurfaceArea();
double sigma = m_cotan_sigma_factor *
std::sqrt(area /
(m_sampler->GetParticleSystem()->GetNumberOfParticles(i) * M_PI));
m_sampler->GetModifiedCotangentGradientFunction()->SetGlobalSigma(sigma);
}
}
// File writers and info display functions
//---------------------------------------------------------------------------
void Optimize::PrintParamInfo()
{
if (m_verbosity_level < 2) {
return;
}
#ifdef SW_USE_OPENMP
std::cout << "OpenMP is enabled ... \n" << std::flush;
#else
std::cout << "OpenMP is disabled ... \n" << std::flush;
#endif
// Write out the parameters
std::cout << "---------------------" << std::endl;
std::cout << " I/O parameters" << std::endl;
std::cout << "---------------------" << std::endl << std::endl;
std::cout << "Domains per shape = " << m_domains_per_shape << std::endl;
std::cout << m_filenames.size() << " image files provided!!!" << std::endl;
if (m_domain_flags.size() > 0) {
std::cout << "Following " << m_domain_flags.size() << " domains have been declared fixed: " <<
std::endl;
for (int i = 0; i < m_domain_flags.size(); i++) {
std::cout << m_domain_flags[i] << "\t" << m_filenames[m_domain_flags[i]] << std::endl;
}
std::cout << std::endl;
}
if (m_adaptivity_mode == 3) {
std::cout << std::endl << std::endl << "*****Using constraints on shapes*****" << std::endl;
}
std::cout << "Target number of particles = ";
if (m_domains_per_shape == 1) {
std::cout << m_number_of_particles[0];
}
else {
for (unsigned int i = 0; i < this->m_domains_per_shape; i++) {
std::cout << "domain " << i << " : " << m_number_of_particles[i] << ", ";
}
}
std::cout << std::endl;
if (m_particle_flags.size() > 0) {
std::cout << "Total " << m_particle_flags.size() / 2 <<
" particles have been declared fixed." <<
std::endl;
}
if (m_mesh_based_attributes) {
std::cout << std::endl << std::endl << "*****Using attributes*****" << std::endl;
std::cout << "Domain(s) using XYZ: ";
for (int i = 0; i < m_domains_per_shape; i++) {
if (m_use_xyz[i]) {
std::cout << i << " ";
}
}
std::cout << std::endl;
std::cout << "Domain(s) using Normals: ";
for (int i = 0; i < m_domains_per_shape; i++) {
if (m_use_normals[i]) {
std::cout << i << " ";
}
}
std::cout << std::endl;
if (this->m_attributes_per_domain.size() > 0) {
std::cout << "Other attributes per domain:" << std::endl;
for (int i = 0; i < m_domains_per_shape; i++) {
std::cout << i << ":" << m_attributes_per_domain[i] << " ";
}
std::cout << std::endl;
}
}
if (m_transform_file.length() > 0) {
std::cout << "m_transform_file = " << m_transform_file << std::endl;
}
if (m_prefix_transform_file.length() > 0) {
std::cout << "m_prefix_transform_file = " << m_prefix_transform_file << std::endl;
}
std::cout << "Output path = " << m_output_dir << std::endl;
std::cout << "Output transform filename = " << m_output_transform_file << std::endl;
std::cout << std::endl;
std::cout << "------------------------------" << std::endl;
std::cout << " Optimization parameters" << std::endl;
std::cout << "------------------------------" << std::endl;
std::cout << "Processing modes = ";
if (m_processing_mode >= 0) {
std::cout << "Initialization";
}
if ((m_processing_mode >= 1 || m_processing_mode == -1) && m_adaptivity_strength > 0.0) {
std::cout << ", Adaptivity";
}
if (m_processing_mode >= 2 || m_processing_mode == -2) {
std::cout << ", Optimization";
}
std::cout << std::endl;
if (m_adaptivity_strength > 0.0) {
std::cout << "adaptivity_strength = " << m_adaptivity_strength << std::endl;
}
std::cout << "pairwise_potential_type = ";
if (m_pairwise_potential_type == 0) {
std::cout << "gaussian" << std::endl;
}
else {
std::cout << "cotan" << std::endl;
}
std::cout << "optimizer_type = ";
if (m_optimizer_type == 0) {
std::cout << "jacobi";
}
else if (m_optimizer_type == 1) {
std::cout << "gauss seidel";
}
else if (m_optimizer_type == 2) {
std::cout << "adaptive gauss seidel (with bad moves)";
}
else {
std::cerr << "Incorrect option!!";
throw 1;
}
std::cout << std::endl;
std::cout << "m_optimization_iterations = " << m_optimization_iterations << std::endl;
std::cout << "m_optimization_iterations_completed = " << m_optimization_iterations_completed <<
std::endl;
std::cout << "m_iterations_per_split = " << m_iterations_per_split << std::endl;
std::cout << "m_init_criterion = " << m_initialization_criterion << std::endl;
std::cout << "m_opt_criterion = " << m_optimization_criterion << std::endl;
std::cout << "m_use_shape_statistics_in_init = " << m_use_shape_statistics_in_init << std::endl;
std::cout << "m_procrustes_interval = " << m_procrustes_interval << std::endl;
std::cout << "m_procrustes_scaling = " << m_procrustes_scaling << std::endl;
std::cout << "m_relative_weighting = " << m_relative_weighting << std::endl;
std::cout << "m_initial_relative_weighting = " << m_initial_relative_weighting << std::endl;
std::cout << "m_starting_regularization = " << m_starting_regularization << std::endl;
std::cout << "m_ending_regularization = " << m_ending_regularization << std::endl;
std::cout << "m_recompute_regularization_interval = " << m_recompute_regularization_interval <<
std::endl;
std::cout << "m_save_init_splits = " << m_save_init_splits << std::endl;
std::cout << "m_checkpointing_interval = " << m_checkpointing_interval << std::endl;
std::cout << "m_keep_checkpoints = " << m_keep_checkpoints << std::endl;
std::cout << std::endl;
if (m_perform_good_bad) {
std::cout <<
"Debug: Bad particles will be reported during optimization, expect significant delays!!! " <<
std::endl;
}
if (m_log_energy) {
std::cout << "Debug: Write energy logs, might increase runtime!!! " << std::endl;
}
}
//---------------------------------------------------------------------------
void Optimize::WriteTransformFile(int iter) const
{
if (!this->m_file_output_enabled) {
return;
}
std::string output_file = m_output_dir + "/" + m_output_transform_file;
if (iter >= 0) {
std::stringstream ss;
ss << iter + m_optimization_iterations_completed;
std::stringstream ssp;
ssp << m_sampler->GetParticleSystem()->GetNumberOfParticles(); // size from domain 0
output_file = m_output_dir + "/iter" + ss.str() + "_p" + ssp.str() + "/" +
m_output_transform_file;
}
this->WriteTransformFile(output_file);
}
//---------------------------------------------------------------------------
void Optimize::WriteTransformFile(std::string iter_prefix) const
{
if (!this->m_file_output_enabled) {
return;
}
std::string output_file = iter_prefix;
std::vector < itk::ParticleSystem < 3 > ::TransformType > tlist;
for (unsigned int i = 0; i < m_sampler->GetParticleSystem()->GetNumberOfDomains();
i++) {
tlist.push_back(m_sampler->GetParticleSystem()->GetTransform(i));
}
std::string str = "writing " + output_file + " ...";
PrintStartMessage(str);
object_writer < itk::ParticleSystem < 3 > ::TransformType > writer;
writer.SetFileName(output_file);
writer.SetInput(tlist);
writer.Update();
PrintDoneMessage();
}
//---------------------------------------------------------------------------
void Optimize::WritePointFiles(int iter)
{
if (!this->m_file_output_enabled) {
return;
}
std::stringstream ss;
ss << iter + m_optimization_iterations_completed;
std::stringstream ssp;
ssp << m_sampler->GetParticleSystem()->GetNumberOfParticles(); // size from domain 0
std::string out_path = m_output_dir;
std::string tmp_dir_name = iter >=
0 ? out_path + "/iter" + ss.str() + "_p" + ssp.str() : out_path;
this->WritePointFiles(tmp_dir_name);
}
//---------------------------------------------------------------------------
void Optimize::WritePointFiles(std::string iter_prefix)
{
if (!this->m_file_output_enabled) {
return;
}
this->PrintStartMessage("Writing point files...\n");
#ifdef _WIN32
mkdir(iter_prefix.c_str());
#else
mkdir(iter_prefix.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
#endif
typedef itk::MaximumEntropyCorrespondenceSampler < ImageType > ::PointType PointType;
const int n = m_sampler->GetParticleSystem()->GetNumberOfDomains();
int counter;
for (int i = 0; i < n; i++) {
counter = 0;
std::string local_file = iter_prefix + "/" + m_filenames[i] + "_local.particles";
std::string world_file = iter_prefix + "/" + m_filenames[i] + "_world.particles";
std::ofstream out(local_file.c_str());
std::ofstream outw(world_file.c_str());
std::string str = "Writing " + world_file + " and " + local_file + " files...";
this->PrintStartMessage(str, 1);
if (!out) {
std::cerr << "Error opening output file: " << local_file << std::endl;
throw 1;
}
if (!outw) {
std::cerr << "Error opening output file: " << world_file << std::endl;
throw 1;
}
for (unsigned int j = 0; j < m_sampler->GetParticleSystem()->GetNumberOfParticles(i); j++) {
PointType pos = m_sampler->GetParticleSystem()->GetPosition(j, i);
PointType wpos = m_sampler->GetParticleSystem()->GetTransformedPosition(j, i);
for (unsigned int k = 0; k < 3; k++) {
out << pos[k] << " ";
}
out << std::endl;
for (unsigned int k = 0; k < 3; k++) {
outw << wpos[k] << " ";
}
outw << std::endl;
counter++;
} // end for points
out.close();
outw.close();
std::stringstream st;
st << counter;
str = "with " + st.str() + "points...";
this->PrintStartMessage(str, 1);
this->PrintDoneMessage(1);
} // end for files
this->PrintDoneMessage();
}
//---------------------------------------------------------------------------
void Optimize::WritePointFilesWithFeatures(int iter)
{
if (!this->m_file_output_enabled) {
return;
}
std::stringstream ss;
ss << iter + m_optimization_iterations_completed;
std::stringstream ssp;
ssp << m_sampler->GetParticleSystem()->GetNumberOfParticles(); // size from domain 0
std::string out_path = m_output_dir;
std::string tmp_dir_name = iter >=
0 ? out_path + "/iter" + ss.str() + "_p" + ssp.str() : out_path;
this->WritePointFilesWithFeatures(tmp_dir_name);
}
//---------------------------------------------------------------------------
void Optimize::WritePointFilesWithFeatures(std::string iter_prefix)
{
if (!this->m_file_output_enabled) {
return;
}
if (!m_mesh_based_attributes) {
return;
}
this->PrintStartMessage("Writing point with attributes files...\n");
typedef itk::MaximumEntropyCorrespondenceSampler < ImageType > ::PointType PointType;
const int n = m_sampler->GetParticleSystem()->GetNumberOfDomains();
int counter;
for (int i = 0; i < n; i++) {
counter = 0;
std::string world_file = iter_prefix + "/" + m_filenames[i] + "_wptsFeatures.particles";
std::ofstream outw(world_file.c_str());
std::string str = "Writing " + world_file + "...";
int attrNum = 3 * int(m_use_xyz[i % m_domains_per_shape]) + 3 *
int(m_use_normals[i % m_domains_per_shape]);
if (m_attributes_per_domain.size() > 0) {
attrNum += m_attributes_per_domain[i % m_domains_per_shape];
}
std::stringstream st;
st << attrNum;
str += "with " + st.str() + " attributes per point...";
this->PrintStartMessage(str, 1);
if (!outw) {
std::cerr << "Error opening output file: " << world_file << std::endl;
throw 1;
}
const itk::ParticleImplicitSurfaceDomain < float, 3 >* domain
= static_cast < const itk::ParticleImplicitSurfaceDomain < float,
3 >* > (m_sampler->
GetParticleSystem()->
GetDomain(i));
const itk::ParticleImageDomainWithGradients < float, 3 >* domainWithGrad
= static_cast < const itk::ParticleImageDomainWithGradients < float,
3 >* > (m_sampler->
GetParticleSystem()->
GetDomain(i));
TriMesh* ptr;
std::vector < float > fVals;
if (m_mesh_based_attributes && m_attributes_per_domain.size() > 0) {
if (m_attributes_per_domain[i % m_domains_per_shape] > 0) {
ptr = domain->GetMesh();
}
}
for (unsigned int j = 0; j < m_sampler->GetParticleSystem()->GetNumberOfParticles(i); j++) {
PointType pos = m_sampler->GetParticleSystem()->GetPosition(j, i);
PointType wpos = m_sampler->GetParticleSystem()->GetTransformedPosition(j, i);
for (unsigned int k = 0; k < 3; k++) {
outw << wpos[k] << " ";
}
if (m_use_normals[i % m_domains_per_shape]) {
// if (m_Sampler->GetParticleSystem()->GetDomainFlag(i))
// {
// outw << 0.0 << " " << 0.0 << " " << 0.0 << " ";
// }
// else
// {
typename itk::ParticleImageDomainWithGradients < float,
3 > ::VnlVectorType pG =
domainWithGrad->SampleNormalVnl(pos);
VectorType pN;
pN[0] = pG[0]; pN[1] = pG[1]; pN[2] = pG[2];
pN = m_sampler->GetParticleSystem()->TransformVector(pN,
m_sampler->GetParticleSystem()->GetTransform(
i) * m_sampler->GetParticleSystem()->GetPrefixTransform(
i));
outw << pN[0] << " " << pN[1] << " " << pN[2] << " ";
// }
}
if (m_attributes_per_domain.size() > 0) {
if (m_attributes_per_domain[i % m_domains_per_shape] > 0) {
// if (m_Sampler->GetParticleSystem()->GetDomainFlag(i))
// {
// for (unsigned int k = 0; k < m_attributes_per_domain[i % m_domains_per_shape]; k++)
// outw << 0.0 << " ";
// }
// else
// {
point pt;
pt.clear();
pt[0] = pos[0];
pt[1] = pos[1];
pt[2] = pos[2];
fVals.clear();
ptr->GetFeatureValues(pt, fVals);
for (unsigned int k = 0; k < m_attributes_per_domain[i % m_domains_per_shape]; k++) {
outw << fVals[k] << " ";
}
// }
}
}
outw << std::endl;
counter++;
} // end for points
outw.close();
this->PrintDoneMessage(1);
} // end for files
this->PrintDoneMessage();
}
//---------------------------------------------------------------------------
void Optimize::WriteEnergyFiles()
{
if (!this->m_file_output_enabled) {
return;
}
if (!this->m_log_energy) {
return;
}
this->PrintStartMessage("Writing energy files...\n");
std::string strA = m_output_dir + "/" + this->m_str_energy + "_samplingEnergy.txt";
std::string strB = m_output_dir + "/" + this->m_str_energy + "_correspondenceEnergy.txt";
std::string strTotal = m_output_dir + "/" + this->m_str_energy + "_totalEnergy.txt";
std::ofstream outA(strA.c_str(), std::ofstream::app);
std::ofstream outB(strB.c_str(), std::ofstream::app);
std::ofstream outTotal(strTotal.c_str(), std::ofstream::app);
if (!outA) {
std::cerr << "Error opening output energy file: " << strA << std::endl;
throw 1;
}
if (!outB) {
std::cerr << "Error opening output energy file: " << strB << std::endl;
throw 1;
}
if (!outTotal) {
std::cerr << "Error opening output energy file: " << strTotal << std::endl;
throw 1;
}
int n = m_energy_a.size() - 1;
n = n < 0 ? 0 : n;
std::string str = "Appending to " + strA + " ...";
this->PrintStartMessage(str, 1);
outA << m_energy_a[n] << std::endl;
outA.close();
this->PrintDoneMessage(1);
str = "Appending to " + strB + " ...";
this->PrintStartMessage(str, 1);
outB << m_energy_b[n] << std::endl;
outB.close();
this->PrintDoneMessage(1);
str = "Appending to " + strTotal + " ...";
this->PrintStartMessage(str, 1);
outTotal << m_total_energy[n] << std::endl;
outTotal.close();
this->PrintDoneMessage(1);
this->PrintDoneMessage();
}
//---------------------------------------------------------------------------
void Optimize::WriteCuttingPlanePoints(int iter)
{
if (!this->m_file_output_enabled) {
return;
}
this->PrintStartMessage("Writing cutting plane points...\n");
std::string output_file = m_output_cutting_plane_file;
if (iter >= 0) {
std::stringstream ss;
ss << iter + m_optimization_iterations_completed;
output_file = "./iter" + ss.str() + "/" + output_file;
}
std::ofstream out(output_file.c_str());
std::string str = "Writing " + output_file + "...";
this->PrintStartMessage(str, 1);
for (unsigned int i = 0; i < m_sampler->GetParticleSystem()->GetNumberOfDomains(); i++) {
const itk::ParticleImplicitSurfaceDomain < float, 3 >* dom
= static_cast < const itk::ParticleImplicitSurfaceDomain < float
, 3 >* > (m_sampler->
GetParticleSystem()->
GetDomain(i));
for (unsigned int j = 0; j < dom->GetNumberOfPlanes(); j++) {
vnl_vector_fixed < double, 3 > a = dom->GetA(j);
vnl_vector_fixed < double, 3 > b = dom->GetB(j);
vnl_vector_fixed < double, 3 > c = dom->GetC(j);
for (int d = 0; d < 3; d++) {
out << a[d] << " ";
}
for (int d = 0; d < 3; d++) {
out << b[d] << " ";
}
for (int d = 0; d < 3; d++) {
out << c[d] << " ";
}
out << std::endl;
}
}
out.close();
this->PrintDoneMessage(1);
this->PrintDoneMessage();
}
//---------------------------------------------------------------------------
void Optimize::WriteParameters(int iter)
{
if (!this->m_file_output_enabled) {
return;
}
if (!m_use_regression) {
return;
}
std::string slopename, interceptname;
slopename = std::string(m_output_dir) + std::string("slope");
interceptname = std::string(m_output_dir) + std::string("intercept");
if (iter >= 0) {
std::stringstream ss;
ss << iter + m_optimization_iterations_completed;
slopename = "./.iter" + ss.str() + "/" + slopename;
interceptname = "./.iter" + ss.str() + "/" + interceptname;
}
std::cout << "writing " << slopename << std::endl;
std::cout << "writing " << interceptname << std::endl;
std::vector < double > slope;
std::vector < double > intercept;
if (m_use_mixed_effects == true) {
vnl_vector < double > slopevec = dynamic_cast < itk::ParticleShapeMixedEffectsMatrixAttribute <
double, 3 >* >
(m_sampler->GetEnsembleMixedEffectsEntropyFunction()->
GetShapeMatrix())->GetSlope();
for (unsigned int i = 0; i < slopevec.size(); i++) {
slope.push_back(slopevec[i]);
}
std::ofstream out(slopename.c_str());
for (unsigned int i = 0; i < slope.size(); i++) {
out << slope[i] << "\n";
}
out.close();
vnl_vector < double > interceptvec = dynamic_cast <
itk::ParticleShapeMixedEffectsMatrixAttribute < double,
3 >* >
(m_sampler->GetEnsembleMixedEffectsEntropyFunction()->
GetShapeMatrix())->GetIntercept();
for (unsigned int i = 0; i < slopevec.size(); i++) {
intercept.push_back(interceptvec[i]);
}
out.open(interceptname.c_str());
for (unsigned int i = 0; i < slope.size(); i++) {
out << intercept[i] << "\n";
}
out.close();
slopename = std::string(m_output_dir) + std::string("sloperand");
interceptname = std::string(m_output_dir) + std::string("interceptrand");
if (iter >= 0) {
std::stringstream ss;
ss << iter + m_optimization_iterations_completed;
slopename = "./.iter" + ss.str() + "/" + slopename;
interceptname = "./.iter" + ss.str() + "/" + interceptname;
}
std::cout << "writing " << slopename << std::endl;
std::cout << "writing " << interceptname << std::endl;
vnl_matrix < double > sloperand_mat = dynamic_cast <
itk::ParticleShapeMixedEffectsMatrixAttribute < double,
3 >* >
(m_sampler->GetEnsembleMixedEffectsEntropyFunction()->
GetShapeMatrix())->GetSlopeRandom();
out.open(slopename.c_str());
for (unsigned int i = 0; i < sloperand_mat.rows(); i++) {
for (unsigned int j = 0; j < sloperand_mat.cols(); j++) {
out << sloperand_mat.get(i, j) << " ";
}
out << "\n";
}
out.close();
vnl_matrix < double > interceptrand_mat = dynamic_cast <
itk::ParticleShapeMixedEffectsMatrixAttribute <
double, 3 >* >
(m_sampler->GetEnsembleMixedEffectsEntropyFunction()->
GetShapeMatrix())->GetInterceptRandom();
out.open(interceptname.c_str());
for (unsigned int i = 0; i < interceptrand_mat.rows(); i++) {
for (unsigned int j = 0; j < interceptrand_mat.cols(); j++) {
out << interceptrand_mat.get(i, j) << " ";
}
out << "\n";
}
out.close();
}
else {
vnl_vector < double > slopevec = dynamic_cast <
itk::ParticleShapeLinearRegressionMatrixAttribute < double,
3 >* >
(m_sampler->GetEnsembleRegressionEntropyFunction()->
GetShapeMatrix())->GetSlope();
for (unsigned int i = 0; i < slopevec.size(); i++) {
slope.push_back(slopevec[i]);
}
std::ofstream out(slopename.c_str());
for (unsigned int i = 0; i < slope.size(); i++) {
out << slope[i] << "\n";
}
out.close();
std::vector < double > intercept;
vnl_vector < double > interceptvec = dynamic_cast <
itk::ParticleShapeLinearRegressionMatrixAttribute < double,
3 >* >
(m_sampler->GetEnsembleRegressionEntropyFunction()->
GetShapeMatrix())->GetIntercept();
for (unsigned int i = 0; i < slopevec.size(); i++) {
intercept.push_back(interceptvec[i]);
}
out.open(interceptname.c_str());
for (unsigned int i = 0; i < slope.size(); i++) {
out << intercept[i] << "\n";
}
out.close();
}
}
//---------------------------------------------------------------------------
void Optimize::ReportBadParticles()
{
if (!this->m_file_output_enabled) {
return;
}
this->PrintStartMessage("Reporting bad particles...", 2);
typedef itk::MaximumEntropyCorrespondenceSampler < ImageType > ::PointType PointType;
const int totalDomains = m_sampler->GetParticleSystem()->GetNumberOfDomains();
const int numShapes = totalDomains / m_domains_per_shape;
std::string outDomDir;
std::string outPtDir;
if (this->m_bad_ids.empty()) {
return;
}
for (int i = 0; i < this->m_domains_per_shape; i++) {
if (this->m_bad_ids[i].empty()) {
continue;
}
std::stringstream ss;
ss << i;
outDomDir = m_output_dir + "/" + this->m_str_energy + "_BadParticles_domain" + ss.str();
#ifdef _WIN32
mkdir(outDomDir.c_str());
#else
mkdir(outDomDir.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
#endif
for (int j = 0; j < this->m_bad_ids[i].size(); j++) {
std::stringstream ssj;
ssj << m_bad_ids[i][j];
outPtDir = outDomDir + "/particle" + ssj.str();
#ifdef _WIN32
mkdir(outPtDir.c_str());
#else
mkdir(outPtDir.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
#endif
for (int k = 0; k < numShapes; k++) {
int dom = k * m_domains_per_shape + i;
std::string localPtFile = outPtDir + "/" + m_filenames[dom] + ".particles";
std::ofstream outl(localPtFile.c_str(), std::ofstream::app);
PointType pos = m_sampler->GetParticleSystem()->GetPosition(m_bad_ids[i][j], dom);
for (unsigned int d = 0; d < 3; d++) {
outl << pos[d] << " ";
}
outl << std::endl;
outl.close();
}
}
}
this->PrintDoneMessage(2);
}
//---------------------------------------------------------------------------
std::vector<std::vector<itk::Point<double>>> Optimize::GetLocalPoints()
{
return this->m_local_points;
}
//---------------------------------------------------------------------------
std::vector<std::vector<itk::Point<double>>> Optimize::GetGlobalPoints()
{
return this->m_global_points;
}
//---------------------------------------------------------------------------
void Optimize::SetCutPlanes(std::vector<std::array<itk::Point<double>, 3>> cut_planes)
{
this->m_cut_planes = cut_planes;
}
//---------------------------------------------------------------------------
bool Optimize::GetAborted()
{
return this->m_aborted;
}
//---------------------------------------------------------------------------
void Optimize::UpdateExportablePoints()
{
this->m_local_points.clear();
this->m_global_points.clear();
for (size_t d = 0; d < this->m_sampler->
GetParticleSystem()->GetNumberOfDomains(); d++) {
// blank set of points
this->m_local_points.push_back(std::vector<itk::Point<double>>());
this->m_global_points.push_back(std::vector<itk::Point<double>>());
// for each particle
for (size_t j = 0; j < this->m_sampler->
GetParticleSystem()->GetNumberOfParticles(d); j++) {
auto pos = this->m_sampler->GetParticleSystem()->GetPosition(j, d);
auto pos2 = this->m_sampler->GetParticleSystem()->GetTransformedPosition(j, d);
this->m_local_points[d].push_back(pos);
this->m_global_points[d].push_back(pos2);
}
}
}
//---------------------------------------------------------------------------
void Optimize::SetPairwisePotentialType(int pairwise_potential_type)
{ this->m_pairwise_potential_type = pairwise_potential_type;}
//---------------------------------------------------------------------------
void Optimize::SetOptimizerType(int optimizer_type)
{ this->m_optimizer_type = optimizer_type;}
//---------------------------------------------------------------------------
void Optimize::SetTimePtsPerSubject(int time_pts_per_subject)
{ this->m_timepts_per_subject = time_pts_per_subject;}
//---------------------------------------------------------------------------
int Optimize::GetTimePtsPerSubject()
{ return this->m_timepts_per_subject; }
//---------------------------------------------------------------------------
void Optimize::SetOptimizationIterations(int optimization_iterations)
{ this->m_optimization_iterations = optimization_iterations;}
//---------------------------------------------------------------------------
void Optimize::SetOptimizationIterationsCompleted(int optimization_iterations_completed)
{ this->m_optimization_iterations_completed = optimization_iterations_completed;}
//---------------------------------------------------------------------------
void Optimize::SetIterationsPerSplit(int iterations_per_split)
{ this->m_iterations_per_split = iterations_per_split;}
//---------------------------------------------------------------------------
void Optimize::SetInitializationCriterion(double init_criterion)
{ this->m_initialization_criterion = init_criterion;}
//---------------------------------------------------------------------------
void Optimize::SetOptimizationCriterion(double opt_criterion)
{ this->m_optimization_criterion = opt_criterion;}
//---------------------------------------------------------------------------
void Optimize::SetUseShapeStatisticsInInit(bool use_shape_statistics_in_init)
{ this->m_use_shape_statistics_in_init = use_shape_statistics_in_init;}
//---------------------------------------------------------------------------
void Optimize::SetProcrustesInterval(int procrustes_interval)
{ this->m_procrustes_interval = procrustes_interval;}
//---------------------------------------------------------------------------
void Optimize::SetProcrustesScaling(int procrustes_scaling)
{ this->m_procrustes_scaling = procrustes_scaling;}
//---------------------------------------------------------------------------
void Optimize::SetRelativeWeighting(double relative_weighting)
{ this->m_relative_weighting = relative_weighting;}
//---------------------------------------------------------------------------
void Optimize::SetInitialRelativeWeighting(double initial_relative_weighting)
{ this->m_initial_relative_weighting = initial_relative_weighting;}
//---------------------------------------------------------------------------
void Optimize::SetStartingRegularization(double starting_regularization)
{ this->m_starting_regularization = starting_regularization;}
//---------------------------------------------------------------------------
void Optimize::SetEndingRegularization(double ending_regularization)
{ this->m_ending_regularization = ending_regularization;}
//---------------------------------------------------------------------------
void Optimize::SetRecomputeRegularizationInterval(int recompute_regularization_interval)
{ this->m_recompute_regularization_interval = recompute_regularization_interval;}
//---------------------------------------------------------------------------
void Optimize::SetSaveInitSplits(bool save_init_splits)
{ this->m_save_init_splits = save_init_splits;}
//---------------------------------------------------------------------------
void Optimize::SetCheckpointingInterval(int checkpointing_interval)
{ this->m_checkpointing_interval = checkpointing_interval;}
//---------------------------------------------------------------------------
void Optimize::SetKeepCheckpoints(int keep_checkpoints)
{ this->m_keep_checkpoints = keep_checkpoints;}
//---------------------------------------------------------------------------
void Optimize::SetCotanSigmaFactor(double cotan_sigma_factor)
{ this->m_cotan_sigma_factor = cotan_sigma_factor;}
//---------------------------------------------------------------------------
void Optimize::SetUseRegression(bool use_regression)
{ this->m_use_regression = use_regression; }
//---------------------------------------------------------------------------
void Optimize::SetUseMixedEffects(bool use_mixed_effects)
{ this->m_use_mixed_effects = use_mixed_effects; }
//---------------------------------------------------------------------------
void Optimize::SetNormalAngle(double normal_angle)
{ this->m_normal_angle = normal_angle;}
//---------------------------------------------------------------------------
void Optimize::SetPerformGoodBad(bool perform_good_bad)
{ this->m_perform_good_bad = perform_good_bad;}
//---------------------------------------------------------------------------
void Optimize::SetLogEnergy(bool log_energy)
{ this->m_log_energy = log_energy;}
//---------------------------------------------------------------------------
void Optimize::SetImages(const std::vector<ImageType::Pointer> &images)
{
this->m_images = images;
this->m_sampler->SetImages(images);
ImageType::Pointer first_image = images[0];
this->m_sampler->SetInput(0, first_image); // set the 0th input
this->m_spacing = first_image->GetSpacing()[0];
this->m_num_shapes = images.size();
}
//---------------------------------------------------------------------------
std::vector<Optimize::ImageType::Pointer> Optimize::GetImages()
{
return this->m_images;
}
//---------------------------------------------------------------------------
void Optimize::SetFilenames(const std::vector<std::string> &filenames)
{ this->m_filenames = filenames; }
//---------------------------------------------------------------------------
void Optimize::SetPointFiles(const std::vector<std::string> &point_files)
{
for (int shapeCount = 0; shapeCount < point_files.size(); shapeCount++) {
this->m_sampler->SetPointsFile(shapeCount, point_files[shapeCount]);
}
}
//---------------------------------------------------------------------------
int Optimize::GetNumShapes()
{
return this->m_num_shapes;
}
//---------------------------------------------------------------------------
void Optimize::SetMeshFiles(const std::vector<std::string> &mesh_files)
{
m_sampler->SetMeshFiles(mesh_files);
}
//---------------------------------------------------------------------------
void Optimize::SetAttributeScales(const std::vector<double> &scales)
{
this->m_sampler->SetAttributeScales(scales);
}
//---------------------------------------------------------------------------
void Optimize::SetFeaFiles(const std::vector<std::string> &files)
{
this->m_sampler->SetFeaFiles(files);
}
//---------------------------------------------------------------------------
void Optimize::SetFeaGradFiles(const std::vector<std::string> &files)
{
this->m_sampler->SetFeaGradFiles(files);
}
//---------------------------------------------------------------------------
void Optimize::SetFidsFiles(const std::vector<std::string> &files)
{
this->m_sampler->SetFidsFiles(files);
}
//---------------------------------------------------------------------------
void Optimize::SetParticleFlags(std::vector<int> flags)
{
this->m_particle_flags = flags;
for (unsigned int i = 0; i < flags.size() / 2; i++) {
this->GetSampler()->GetParticleSystem()->SetFixedParticleFlag(flags[2 * i], flags[2 * i + 1]);
}
}
//---------------------------------------------------------------------------
void Optimize::SetDomainFlags(std::vector<int> flags)
{
this->m_domain_flags = flags;
for (unsigned int i = 0; i < flags.size(); i++) {
this->GetSampler()->GetParticleSystem()->FlagDomain(flags[i]);
}
}
//---------------------------------------------------------------------------
void Optimize::SetFileOutputEnabled(bool enabled)
{
this->m_file_output_enabled = enabled;
}
//---------------------------------------------------------------------------
std::vector<bool> Optimize::GetUseXYZ()
{
return this->m_use_xyz;
}
//---------------------------------------------------------------------------
std::vector<bool> Optimize::GetUseNormals()
{
return this->m_use_normals;
}
//---------------------------------------------------------------------------
void Optimize::SetIterationCallback()
{
this->m_iterate_command = itk::MemberCommand<Optimize>::New();
this->m_iterate_command->SetCallbackFunction(this, &Optimize::IterateCallback);
this->m_sampler->GetOptimizer()->AddObserver(itk::IterationEvent(), m_iterate_command);
}
//---------------------------------------------------------------------------
void Optimize::WriteModes()
{
const int n = m_sampler->GetParticleSystem()->GetNumberOfDomains() % m_domains_per_shape;
if (n >= 5) {
m_sampler->GetEnsembleEntropyFunction()->WriteModes(m_output_dir + "/pts", 5);
}
}
//---------------------------------------------------------------------------
void Optimize::PrintStartMessage(std::string str, unsigned int vlevel) const
{
if (this->m_verbosity_level > vlevel) {
std::cout << str;
std::cout.flush();
}
}
//---------------------------------------------------------------------------
void Optimize::PrintDoneMessage(unsigned int vlevel) const
{
if (m_verbosity_level > vlevel) {
std::cout << "Done." << std::endl;
}
}
| 76,844 | 24,761 |
#ifndef GENERATED_419896c26be84c4028d040a9d3789448_HPP
#define GENERATED_419896c26be84c4028d040a9d3789448_HPP
#include "bullet.hpp"
void stepfunc_10c3a88a8e44bab5c0812abd588467e2_e9c5251663b26b8b849de773f3f9b7a0(BulletInfo *p);
void stepfunc_6536e4546bdcfcf651852434db03b678_e9c5251663b26b8b849de773f3f9b7a0(BulletInfo *p);
void stepfunc_afa1c1a48bcda114ef4e13212c0aee71_e9c5251663b26b8b849de773f3f9b7a0(BulletInfo *p);
void stepfunc_f46bc191f7167f122835b57dc03cf3ba_e9c5251663b26b8b849de773f3f9b7a0(BulletInfo *p);
void stepfunc_faeb9ac81b7a64ffed123259883c3994_e9c5251663b26b8b849de773f3f9b7a0(BulletInfo *p);
void stepfunc_ae9f735c6401a821cc04ce1cd68278bf_e9c5251663b26b8b849de773f3f9b7a0(BulletInfo *p);
void stepfunc_6c1f8924f1816c4b17037ca35cdfb188_e9c5251663b26b8b849de773f3f9b7a0(BulletInfo *p);
void stepfunc_f802ea525850e7f56f2d815678960bc3_e9c5251663b26b8b849de773f3f9b7a0(BulletInfo *p);
extern const BulletStepFunc bullet_2e26dec57daafc633062db6aca6be43b_e9c5251663b26b8b849de773f3f9b7a0[];
const unsigned int bullet_2e26dec57daafc633062db6aca6be43b_e9c5251663b26b8b849de773f3f9b7a0_size = 70;
extern const BulletStepFunc bullet_8edd83cfae72c5dbe91c2e130d65b723_e9c5251663b26b8b849de773f3f9b7a0[];
const unsigned int bullet_8edd83cfae72c5dbe91c2e130d65b723_e9c5251663b26b8b849de773f3f9b7a0_size = 2;
extern const BulletStepFunc bullet_3232f0156ec2c5040d5cdc3a1657932a_e9c5251663b26b8b849de773f3f9b7a0[];
const unsigned int bullet_3232f0156ec2c5040d5cdc3a1657932a_e9c5251663b26b8b849de773f3f9b7a0_size = 2;
#endif
| 1,551 | 1,141 |
#include <stan/math/mix/scal.hpp>
#include <gtest/gtest.h>
#include <math/rev/scal/util.hpp>
TEST(AgradRev, value_of_rec_0) {
using stan::math::fvar;
using stan::math::value_of_rec;
using stan::math::var;
fvar<var> fv_a(5.0);
fvar<fvar<var> > ffv_a(5.0);
fvar<fvar<fvar<fvar<fvar<var> > > > > fffffv_a(5.0);
EXPECT_FLOAT_EQ(5.0, value_of_rec(fv_a));
EXPECT_FLOAT_EQ(5.0, value_of_rec(ffv_a));
EXPECT_FLOAT_EQ(5.0, value_of_rec(fffffv_a));
}
| 462 | 246 |
#include "NuHepMC/Kinematics.hxx"
#include "NuHepMC/ParticleStackReaderHelper.hxx"
#include <iostream>
namespace NuHepMC {
HepMC3::FourVector GetFourMomentumTransfer(HepMC3::GenEvent const &evt) {
auto ISProbe = GetProbe(evt);
if (!ISProbe) {
return HepMC3::FourVector::ZERO_VECTOR();
}
auto FSProbe = GetFSProbe(evt, ISProbe->pid());
if (!FSProbe) {
return HepMC3::FourVector::ZERO_VECTOR();
}
return (ISProbe->momentum() - FSProbe->momentum());
}
double GetQ2(HepMC3::GenEvent const &evt) {
return -GetFourMomentumTransfer(evt).m2();
}
} // namespace NuHepMC
| 592 | 261 |
#include <iostream>
#include <vector>
#include <unordered_set>
#include <unordered_map>
#include <set>
#include <algorithm>
#include <string>
#include <sstream>
#include <cstdlib>
struct Photo {
int id;
char orient;
std::unordered_set<std::string> tags;
};
struct Slide {
int a;
int b;
};
void read_photos(int N, std::vector<Photo>& photos) {
Photo p;
int curr_taglen;
std::string curr_tag;
for(int i = 0; i < N; ++i) {
p.id = i;
std::cin >> p.orient >> curr_taglen;
p.tags.clear();
while (curr_taglen > 0) {
std::cin >> curr_tag;
p.tags.insert(curr_tag);
--curr_taglen;
}
photos.push_back(p);
}
return;
}
std::unordered_set<std::string> get_tags(const Slide& lhs, const std::vector<Photo>& photos) {
std::unordered_set<std::string> lhs_tags;
lhs_tags.insert(photos[lhs.a].tags.begin(), photos[lhs.a].tags.end());
if (photos[lhs.a].orient == 'V') {
lhs_tags.insert(photos[lhs.b].tags.begin(), photos[lhs.b].tags.end());
}
return lhs_tags;
}
int tran_score(const Slide& lhs, const Slide& rhs, const std::vector<Photo>& photos) {
std::set<std::string> lhs_tags;
lhs_tags.insert(photos[lhs.a].tags.begin(), photos[lhs.a].tags.end());
if (photos[lhs.a].orient == 'V') {
lhs_tags.insert(photos[lhs.b].tags.begin(), photos[lhs.b].tags.end());
}
std::set<std::string> rhs_tags;
rhs_tags.insert(photos[rhs.a].tags.begin(), photos[rhs.a].tags.end());
if (photos[rhs.a].orient == 'V') {
rhs_tags.insert(photos[rhs.b].tags.begin(), photos[rhs.b].tags.end());
}
int M = std::max(lhs_tags.size(), rhs_tags.size());
std::vector<std::string> intersect(M);
std::vector<std::string>::iterator it_inter;
it_inter = std::set_intersection(lhs_tags.begin(), lhs_tags.end(),
rhs_tags.begin(), rhs_tags.end(), intersect.begin());
intersect.resize(it_inter - intersect.begin());
std::vector<std::string> lhs_comp(M);
std::vector<std::string>::iterator it_lcomp;
it_lcomp = std::set_difference(lhs_tags.begin(), lhs_tags.end(),
rhs_tags.begin(), rhs_tags.end(), lhs_comp.begin());
lhs_comp.resize(it_lcomp - lhs_comp.begin());
std::vector<std::string> rhs_comp(M);
std::vector<std::string>::iterator it_rcomp;
it_rcomp = std::set_difference(rhs_tags.begin(), rhs_tags.end(),
lhs_tags.begin(), lhs_tags.end(), rhs_comp.begin());
rhs_comp.resize(it_rcomp - rhs_comp.begin());
return std::min(std::min(lhs_comp.size(), rhs_comp.size()),intersect.size());
}
bool get_slide(const std::vector<Photo>& photos,
std::vector<bool>& avail,
int& LAST_USED,
Slide& s) {
for(int i = LAST_USED; i < avail.size(); ++i) {
if (avail[i]) {
if (photos[i].orient == 'H') {
s.a = i;
s.b = -1;
avail[i] = false;
LAST_USED = i;
return true;
} else {
for(int j = i+1; j < avail.size(); ++j) {
if (avail[j] && photos[j].orient == 'V') {
s.a = i;
s.b = j;
avail[i] = false;
avail[j] = false;
LAST_USED = i;
return true;
}
}
}
}
}
return false;
}
std::vector<Photo>* photos_ptr;
bool photo_comp(const int& lhs, const int& rhs) {
std::vector<Photo>& photos = *photos_ptr;
return photos[lhs].tags.size() < photos[rhs].tags.size();
}
bool get_available(const std::vector<Photo>& photos,
std::vector<bool>& avail,
std::vector<int>& c,
Slide& s) {
std::random_shuffle(c.begin(), c.end());
for(int i = 0; i < c.size(); ++i) {
if (avail[c[i]]) {
if (photos[c[i]].orient == 'H') {
s.a = c[i];
s.b = -1;
avail[c[i]] = false;
return true;
} else {
for(int j = c[i]+1; j < avail.size(); ++j) {
if (avail[j] && photos[j].orient == 'V') {
s.a = c[i];
s.b = j;
avail[c[i]] = false;
avail[j] = false;
return true;
}
}
}
}
}
return false;
}
int main() {
int N; // num of photos
std::cin >> N;
std::vector<Photo> photos;
read_photos(N, photos);
std::vector<bool> avail(N, true);
photos_ptr = &photos;
std::unordered_set<std::string>::iterator itp;
std::unordered_map<std::string, std::vector<int> >::iterator itr;
std::unordered_map<std::string, std::vector<int> > ridx;
for(int i = 0; i < N; ++i) {
for(itp = photos[i].tags.begin();
itp != photos[i].tags.end(); ++itp) {
itr = ridx.find(*itp);
if (itr == ridx.end()) {
ridx[*itp] = std::vector<int>();
itr = ridx.find(*itp);
}
itr->second.push_back(i);
}
}
int LAST_USED = 0;
std::vector<Slide> res;
Slide curr;
get_slide(photos, avail, LAST_USED, curr);
res.push_back(curr);
std::unordered_set<std::string> curr_tags;
std::unordered_set<std::string>::iterator itct;
bool found = true;
while(found) {
curr_tags = get_tags(curr, photos);
found = false;
for(itct = curr_tags.begin(); itct != curr_tags.end() && !found; ++itct) {
std::vector<int>& c = ridx[*itct];
if (get_available(photos, avail, c, curr)) {
found = true;
}
}
if (!found) {
if (get_slide(photos, avail, LAST_USED, curr)) {
res.push_back(curr);
found = true;
} else {
found = false;
}
} else {
res.push_back(curr);
}
}
std::cout << res.size() << std::endl;
for(int i = 0; i < res.size(); ++i) {
std::cout << res[i].a;
if (res[i].b != -1) {
std::cout << ' ' << res[i].b;
}
std::cout << std::endl;
}
return 0;
}
| 5,779 | 2,237 |
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int diameterOfBinaryTree(TreeNode* root) {
int diam = 0;
maxDepth(root, diam);
return diam;
}
int maxDepth(TreeNode* root, int& diam) {
if (root == nullptr) {
return 0;
}
int left = maxDepth(root->left, diam);
int right = maxDepth(root->right, diam);
diam = max(diam, left + right);
return 1 + max(left, right);
}
};
| 643 | 213 |
#include <iostream>
using namespace std;
int main() {
int m, k, n, w, t = 0;
cin >> m >> k;
n = m;
while (n) {
w = n % 10;
if (w == 3)
++t;
n /= 10;
}
if (m % 19 == 0 && t == k)
cout << "YES" << endl;
else
cout << "NO" << endl;
return 0;
}
| 329 | 143 |
#include <algorithm>
#include <vector>
#include "caffe/common_layers.hpp"
#include "caffe/layer.hpp"
#include "caffe/util/math_functions.hpp"
namespace caffe {
template <typename Dtype, typename Mtype>
void MVNLayer<Dtype,Mtype>::Reshape(const vector<Blob<Dtype,Mtype>*>& bottom,
const vector<Blob<Dtype,Mtype>*>& top) {
top[0]->Reshape(bottom[0]->num(), bottom[0]->channels(),
bottom[0]->height(), bottom[0]->width());
mean_.Reshape(bottom[0]->num(), bottom[0]->channels(),
1, 1);
variance_.Reshape(bottom[0]->num(), bottom[0]->channels(),
1, 1);
temp_.Reshape(bottom[0]->num(), bottom[0]->channels(),
bottom[0]->height(), bottom[0]->width());
if ( this->layer_param_.mvn_param().across_channels() ) {
sum_multiplier_.Reshape(1, bottom[0]->channels(), bottom[0]->height(),
bottom[0]->width());
} else {
sum_multiplier_.Reshape(1, 1, bottom[0]->height(), bottom[0]->width());
}
Dtype* multiplier_data = sum_multiplier_.mutable_cpu_data();
caffe_set(sum_multiplier_.count(), Get<Dtype>(1), multiplier_data);
eps_ = this->layer_param_.mvn_param().eps();
}
template <typename Dtype, typename Mtype>
void MVNLayer<Dtype,Mtype>::Forward_cpu(const vector<Blob<Dtype,Mtype>*>& bottom,
const vector<Blob<Dtype,Mtype>*>& top) {
const Dtype* bottom_data = bottom[0]->cpu_data();
Dtype* top_data = top[0]->mutable_cpu_data();
int num;
if (this->layer_param_.mvn_param().across_channels())
num = bottom[0]->num();
else
num = bottom[0]->num() * bottom[0]->channels();
int dim = bottom[0]->count() / num;
if (this->layer_param_.mvn_param().normalize_variance()) {
// put the squares of bottom into temp_
caffe_powx<Dtype,Mtype>(bottom[0]->count(), bottom_data, Mtype(2),
temp_.mutable_cpu_data());
// computes variance using var(X) = E(X^2) - (EX)^2
caffe_cpu_gemv<Dtype,Mtype>(CblasNoTrans, num, dim, Mtype(1. / dim), bottom_data,
sum_multiplier_.cpu_data(), Mtype(0.), mean_.mutable_cpu_data()); // EX
caffe_cpu_gemv<Dtype,Mtype>(CblasNoTrans, num, dim, Mtype(1. / dim), temp_.cpu_data(),
sum_multiplier_.cpu_data(), Mtype(0.),
variance_.mutable_cpu_data()); // E(X^2)
caffe_powx<Dtype,Mtype>(mean_.count(), mean_.cpu_data(), Mtype(2),
temp_.mutable_cpu_data()); // (EX)^2
caffe_sub<Dtype,Mtype>(mean_.count(), variance_.cpu_data(), temp_.cpu_data(),
variance_.mutable_cpu_data()); // variance
// do mean and variance normalization
// subtract mean
caffe_cpu_gemm<Dtype,Mtype>(CblasNoTrans, CblasNoTrans, num, dim, 1, Mtype(-1.f),
mean_.cpu_data(), sum_multiplier_.cpu_data(), Mtype(0.f),
temp_.mutable_cpu_data());
caffe_add<Dtype,Mtype>(temp_.count(), bottom_data, temp_.cpu_data(), top_data);
// normalize variance
caffe_powx<Dtype,Mtype>(variance_.count(), variance_.cpu_data(), Mtype(0.5),
variance_.mutable_cpu_data());
caffe_add_scalar<Dtype,Mtype>(variance_.count(), eps_, variance_.mutable_cpu_data());
caffe_cpu_gemm<Dtype,Mtype>(CblasNoTrans, CblasNoTrans, num, dim, 1, Mtype(1.f),
variance_.cpu_data(), sum_multiplier_.cpu_data(), Mtype(0.),
temp_.mutable_cpu_data());
caffe_div<Dtype,Mtype>(temp_.count(), top_data, temp_.cpu_data(), top_data);
} else {
caffe_cpu_gemv<Dtype,Mtype>(CblasNoTrans, num, dim, Mtype(1. / dim), bottom_data,
sum_multiplier_.cpu_data(), Mtype(0.), mean_.mutable_cpu_data()); // EX
// subtract mean
caffe_cpu_gemm<Dtype,Mtype>(CblasNoTrans, CblasNoTrans, num, dim, 1, Mtype(-1.),
mean_.cpu_data(), sum_multiplier_.cpu_data(), Mtype(0.),
temp_.mutable_cpu_data());
caffe_add<Dtype,Mtype>(temp_.count(), bottom_data, temp_.cpu_data(), top_data);
}
}
template <typename Dtype, typename Mtype>
void MVNLayer<Dtype,Mtype>::Backward_cpu(const vector<Blob<Dtype,Mtype>*>& top,
const vector<bool>& propagate_down,
const vector<Blob<Dtype,Mtype>*>& bottom) {
const Dtype* top_diff = top[0]->cpu_diff();
const Dtype* top_data = top[0]->cpu_data();
const Dtype* bottom_data = bottom[0]->cpu_data();
Dtype* bottom_diff = bottom[0]->mutable_cpu_diff();
int num;
if (this->layer_param_.mvn_param().across_channels())
num = bottom[0]->num();
else
num = bottom[0]->num() * bottom[0]->channels();
int dim = bottom[0]->count() / num;
if (this->layer_param_.mvn_param().normalize_variance()) {
caffe_mul<Dtype,Mtype>(temp_.count(), top_data, top_diff, bottom_diff);
caffe_cpu_gemv<Dtype,Mtype>(CblasNoTrans, num, dim, Mtype(1.), bottom_diff,
sum_multiplier_.cpu_data(), Mtype(0.), mean_.mutable_cpu_data());
caffe_cpu_gemm<Dtype,Mtype>(CblasNoTrans, CblasNoTrans, num, dim, 1, Mtype(1.),
mean_.cpu_data(), sum_multiplier_.cpu_data(), Mtype(0.f),
bottom_diff);
caffe_mul<Dtype,Mtype>(temp_.count(), top_data, bottom_diff, bottom_diff);
caffe_cpu_gemv<Dtype,Mtype>(CblasNoTrans, num, dim, Mtype(1.), top_diff,
sum_multiplier_.cpu_data(), Mtype(0.f), mean_.mutable_cpu_data());
caffe_cpu_gemm<Dtype,Mtype>(CblasNoTrans, CblasNoTrans, num, dim, 1, Mtype(1.),
mean_.cpu_data(), sum_multiplier_.cpu_data(), Mtype(1.f),
bottom_diff);
caffe_cpu_axpby<Dtype,Mtype>(temp_.count(), Mtype(1), top_diff, Mtype(-1. / dim),
bottom_diff);
// put the squares of bottom into temp_
caffe_powx<Dtype,Mtype>(temp_.count(), bottom_data, Mtype(2),
temp_.mutable_cpu_data());
caffe_cpu_gemm<Dtype,Mtype>(CblasNoTrans, CblasNoTrans, num, dim, 1, Mtype(1.f),
variance_.cpu_data(), sum_multiplier_.cpu_data(), Mtype(0.f),
temp_.mutable_cpu_data());
caffe_div<Dtype,Mtype>(temp_.count(), bottom_diff, temp_.cpu_data(), bottom_diff);
} else {
caffe_cpu_gemv<Dtype,Mtype>(CblasNoTrans, num, dim, Mtype(1. / dim), top_diff,
sum_multiplier_.cpu_data(), Mtype(0.f), mean_.mutable_cpu_data());
caffe_cpu_gemm<Dtype,Mtype>(CblasNoTrans, CblasNoTrans, num, dim, 1, Mtype(-1.f),
mean_.cpu_data(), sum_multiplier_.cpu_data(), Mtype(0.f),
temp_.mutable_cpu_data());
caffe_add<Dtype,Mtype>(temp_.count(), top_diff, temp_.cpu_data(), bottom_diff);
}
}
#ifdef CPU_ONLY
STUB_GPU(MVNLayer);
#endif
INSTANTIATE_CLASS(MVNLayer);
REGISTER_LAYER_CLASS(MVN);
} // namespace caffe
| 6,364 | 2,469 |
// 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 <windows.h>
#include <setupapi.h>
#include <stddef.h>
#include <winioctl.h>
#include "base/logging.h"
#include "chrome/utility/image_writer/error_message_strings.h"
#include "chrome/utility/image_writer/image_writer.h"
namespace image_writer {
const size_t kStorageQueryBufferSize = 1024;
bool ImageWriter::IsValidDevice() {
base::win::ScopedHandle device_handle(
CreateFile(device_path_.value().c_str(),
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
FILE_FLAG_NO_BUFFERING | FILE_FLAG_WRITE_THROUGH,
NULL));
if (!device_handle.IsValid()) {
Error(error::kOpenDevice);
return false;
}
STORAGE_PROPERTY_QUERY query = STORAGE_PROPERTY_QUERY();
query.PropertyId = StorageDeviceProperty;
query.QueryType = PropertyStandardQuery;
DWORD bytes_returned;
std::unique_ptr<char[]> output_buf(new char[kStorageQueryBufferSize]);
BOOL status = DeviceIoControl(
device_handle.Get(), // Device handle.
IOCTL_STORAGE_QUERY_PROPERTY, // Flag to request device properties.
&query, // Query parameters.
sizeof(STORAGE_PROPERTY_QUERY), // query parameters size.
output_buf.get(), // output buffer.
kStorageQueryBufferSize, // Size of buffer.
&bytes_returned, // Number of bytes returned.
// Must not be null.
NULL); // Optional unused overlapped perameter.
if (!status) {
PLOG(ERROR) << "Storage property query failed";
return false;
}
STORAGE_DEVICE_DESCRIPTOR* device_descriptor =
reinterpret_cast<STORAGE_DEVICE_DESCRIPTOR*>(output_buf.get());
return device_descriptor->RemovableMedia == TRUE ||
device_descriptor->BusType == BusTypeUsb;
}
bool ImageWriter::OpenDevice() {
// Windows requires that device files be opened with FILE_FLAG_NO_BUFFERING
// and FILE_FLAG_WRITE_THROUGH. These two flags are not part of base::File.
device_file_ =
base::File(CreateFile(device_path_.value().c_str(),
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
FILE_FLAG_NO_BUFFERING | FILE_FLAG_WRITE_THROUGH,
NULL));
return device_file_.IsValid();
}
void ImageWriter::UnmountVolumes(base::OnceClosure continuation) {
if (!InitializeFiles()) {
return;
}
STORAGE_DEVICE_NUMBER sdn = {0};
DWORD bytes_returned;
BOOL status = DeviceIoControl(
device_file_.GetPlatformFile(),
IOCTL_STORAGE_GET_DEVICE_NUMBER,
NULL, // Unused, must be NULL.
0, // Unused, must be 0.
&sdn, // An input buffer to hold the STORAGE_DEVICE_NUMBER
sizeof(sdn), // The size of the input buffer.
&bytes_returned, // the actual number of bytes returned.
NULL); // Unused overlap.
if (!status) {
PLOG(ERROR) << "Unable to get device number.";
return;
}
ULONG device_number = sdn.DeviceNumber;
TCHAR volume_path[MAX_PATH + 1];
HANDLE volume_finder = FindFirstVolume(volume_path, MAX_PATH + 1);
if (volume_finder == INVALID_HANDLE_VALUE) {
return;
}
HANDLE volume_handle;
bool first_volume = true;
bool success = true;
while (first_volume ||
FindNextVolume(volume_finder, volume_path, MAX_PATH + 1)) {
first_volume = false;
size_t length = wcsnlen(volume_path, MAX_PATH + 1);
if (length < 1) {
continue;
}
volume_path[length - 1] = L'\0';
volume_handle = CreateFile(volume_path,
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
0,
NULL);
if (volume_handle == INVALID_HANDLE_VALUE) {
PLOG(ERROR) << "Opening volume handle failed.";
success = false;
break;
}
volume_handles_.push_back(volume_handle);
VOLUME_DISK_EXTENTS disk_extents = {0};
status = DeviceIoControl(volume_handle,
IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS,
NULL,
0,
&disk_extents,
sizeof(disk_extents),
&bytes_returned,
NULL);
if (!status) {
DWORD error = GetLastError();
if (error == ERROR_MORE_DATA || error == ERROR_INVALID_FUNCTION ||
error == ERROR_NOT_READY) {
continue;
} else {
PLOG(ERROR) << "Unable to get volume disk extents.";
success = false;
break;
}
}
if (disk_extents.NumberOfDiskExtents != 1 ||
disk_extents.Extents[0].DiskNumber != device_number) {
continue;
}
status = DeviceIoControl(volume_handle,
FSCTL_LOCK_VOLUME,
NULL,
0,
NULL,
0,
&bytes_returned,
NULL);
if (!status) {
PLOG(ERROR) << "Unable to lock volume.";
success = false;
break;
}
status = DeviceIoControl(volume_handle,
FSCTL_DISMOUNT_VOLUME,
NULL,
0,
NULL,
0,
&bytes_returned,
NULL);
if (!status) {
DWORD error = GetLastError();
if (error != ERROR_NOT_SUPPORTED) {
PLOG(ERROR) << "Unable to dismount volume.";
success = false;
break;
}
}
}
if (volume_finder != INVALID_HANDLE_VALUE) {
FindVolumeClose(volume_finder);
}
if (success)
std::move(continuation).Run();
}
} // namespace image_writer
| 6,448 | 1,933 |
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include <AzCore/IO/SystemFile.h>
#include <AzCore/IO/FileIO.h>
#include <AzCore/IO/FileIOEventBus.h>
#include <AzCore/Casting/numeric_cast.h>
#include <AzCore/PlatformIncl.h>
#include <AzCore/Utils/Utils.h>
#include <../Common/UnixLike/AzCore/IO/Internal/SystemFileUtils_UnixLike.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <dirent.h>
namespace AZ::IO
{
namespace UnixLikePlatformUtil
{
// Platform specific helpers
bool CanCreateDirRecursive(char* dirPath);
}
namespace
{
//=========================================================================
// Internal utility to create a folder hierarchy recursively without
// any additional string copies.
// If this function fails (returns false), the error will be available
// via errno on Unix platforms
//=========================================================================
bool CreateDirRecursive(char* dirPath)
{
if (!UnixLikePlatformUtil::CanCreateDirRecursive(dirPath))
{
// Our current platform has told us we have failed
return false;
}
int result = mkdir(dirPath, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
if (result == 0)
{
return true; // Created without error
}
else if (result == -1)
{
// If result == -1, the error is stored in errno
// http://pubs.opengroup.org/onlinepubs/007908799/xsh/mkdir.html
result = errno;
}
if (result == ENOTDIR || result == ENOENT)
{
// try to create our parent hierarchy
for (size_t i = strlen(dirPath); i > 0; --i)
{
if (dirPath[i] == '/' || dirPath[i] == '\\')
{
char delimiter = dirPath[i];
dirPath[i] = 0; // null-terminate at the previous slash
bool ret = CreateDirRecursive(dirPath);
dirPath[i] = delimiter; // restore slash
if (ret)
{
// now that our parent is created, try to create again
return mkdir(dirPath, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == 0;
}
return false;
}
}
// if we reach here then there was no parent folder to create, so we failed for other reasons
}
else if (result == EEXIST)
{
struct stat s;
if (stat(dirPath, &s) == 0)
{
return s.st_mode & S_IFDIR;
}
}
return false;
}
}
namespace Platform
{
void FindFiles(const char* filter, SystemFile::FindFileCB cb)
{
// If we have wildcards, peel off
char filePath[AZ_MAX_PATH_LEN];
char extensionPath[AZ_MAX_PATH_LEN];
if (!AZ::IO::Internal::FormatAndPeelOffWildCardExtension(filter, filePath, sizeof(filePath), extensionPath, sizeof(extensionPath), true))
{
// FormatAndPeelOffWildCardExtension emits an error when it returns false
return;
}
DIR* dir = opendir(filePath);
if (dir != NULL)
{
// clear the errno state so we can distinguish between real errors and end of stream
errno = 0;
struct dirent* entry = readdir(dir);
// List all the other files in the directory.
while (entry != NULL)
{
if (NameMatchesFilter(entry->d_name, extensionPath))
{
cb(entry->d_name, (entry->d_type & DT_DIR) == 0);
}
entry = readdir(dir);
}
int lastError = errno;
if (lastError != 0)
{
EBUS_EVENT(FileIOEventBus, OnError, nullptr, filter, lastError);
}
closedir(dir);
}
else
{
int lastError = errno;
if (lastError != ENOENT)
{
EBUS_EVENT(FileIOEventBus, OnError, nullptr, filter, 0);
}
}
}
AZ::u64 ModificationTime(const char* fileName)
{
struct stat statResult;
if (stat(fileName, &statResult) != 0)
{
return 0;
}
return aznumeric_cast<AZ::u64>(statResult.st_mtime);
}
SystemFile::SizeType Length(const char* fileName)
{
SizeType len = 0;
SystemFile f;
if (f.Open(fileName, SystemFile::SF_OPEN_READ_ONLY))
{
len = f.Length();
f.Close();
}
return len;
}
bool Delete(const char* fileName)
{
int result = remove(fileName);
if (result != 0)
{
EBUS_EVENT(FileIOEventBus, OnError, nullptr, fileName, result);
return false;
}
return true;
}
bool Rename(const char* sourceFileName, const char* targetFileName, bool overwrite)
{
int result = rename(sourceFileName, targetFileName);
if (result)
{
EBUS_EVENT(FileIOEventBus, OnError, nullptr, sourceFileName, result);
return false;
}
return true;
}
#if !(AZ_TRAIT_SYSTEMFILE_UNIX_LIKE_PLATFORM_IS_WRITEABLE_DEFINED_ELSEWHERE)
bool IsWritable(const char* sourceFileName)
{
return (access(sourceFileName, W_OK) == 0);
}
#endif // !(AZ_TRAIT_SYSTEMFILE_UNIX_LIKE_PLATFORM_IS_WRITEABLE_DEFINED_ELSEWHERE)
bool SetWritable(const char* sourceFileName, bool writable)
{
struct stat s;
if (stat(sourceFileName, &s) == 0)
{
int permissions = (s.st_mode & S_IRWXU) | (s.st_mode & S_IRWXO) | (s.st_mode & S_IRWXG);
if (writable)
{
if (s.st_mode & S_IWUSR)
{
return true;
}
return chmod(sourceFileName, permissions | S_IWUSR) == 0;
}
else
{
if (s.st_mode & S_IRUSR)
{
return true;
}
return chmod(sourceFileName, permissions | S_IRUSR) == 0;
}
}
return false;
}
bool CreateDir(const char* dirName)
{
if (dirName)
{
char dirPath[AZ_MAX_PATH_LEN];
if (strlen(dirName) > AZ_MAX_PATH_LEN)
{
return false;
}
azstrcpy(dirPath, AZ_MAX_PATH_LEN, dirName);
bool success = CreateDirRecursive(dirPath);
if (!success)
{
EBUS_EVENT(FileIOEventBus, OnError, nullptr, dirName, errno);
}
return success;
}
return false;
}
bool DeleteDir(const char* dirName)
{
AZ_PROFILE_SCOPE_STALL_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, "SystemFile::DeleteDir(util) - %s", dirName);
if (dirName)
{
return rmdir(dirName) == 0;
}
return false;
}
}
} // namespace AZ::IO
| 7,742 | 2,347 |
// Arquivo pangya_db.cpp
// Criado em 25/12/2017 por Acrisio
// Implementação da classe pangya_db
#if defined(_WIN32)
#pragma pack(1)
#endif
#if defined(_WIN32)
#include <WinSock2.h>
#elif defined(__linux__)
#include "../UTIL/WinPort.h"
#include <unistd.h>
#endif
#include "pangya_db.h"
#include "../UTIL/exception.h"
#include "../UTIL/message_pool.h"
#include "../UTIL/string_util.hpp"
using namespace stdA;
// Teste call db cmd log
#ifdef _DEBUG
#define _TESTCMD_LOG 1
#endif
#if defined(_WIN32) && defined(_TESTCMD_LOG)
// !@ Teste
#include <fstream>
#include <map>
struct call_db_cmd_st {
public:
call_db_cmd_st() : m_hMutex(INVALID_HANDLE_VALUE) {
m_hMutex = CreateMutexA(NULL, FALSE, "xg_CALL_DB_CMD_LOG");
if (m_hMutex == NULL)
_smp::message_pool::getInstance().push(new message("[pangya_db::call_db_cmd_st::call_db_cmd_st][Error] fail to create Mutex. Error: " + std::to_string(GetLastError()), CL_FILE_LOG_AND_CONSOLE));
};
~call_db_cmd_st() {
if (isValid())
CloseHandle(m_hMutex);
};
std::map< std::string, std::string > loadCmds() {
std::map< std::string, std::string > v_cmds;
if (!isValid() || !lock())
return v_cmds;
std::ifstream in(url_log);
if (in.is_open()) {
std::string name, value;
while (in.good()) {
in >> name >> value;
v_cmds.insert(std::make_pair(name, value));
}
in.close();
}
if (!unlock())
_smp::message_pool::getInstance().push(new message("[pangya_db::call_db_cmd_st::loadCmds][Error] fail to release Mutex. Error: " + std::to_string(GetLastError()), CL_FILE_LOG_AND_CONSOLE));
return v_cmds;
};
void saveCmds(std::map< std::string, std::string >& _cmds) {
if (_cmds.empty() || !isValid() || !lock())
return;
std::ofstream out(url_log);
if (out.is_open()) {
for (auto& el : _cmds)
out << el.first << " " << el.second << std::endl;
out.close();
}
if (!unlock())
_smp::message_pool::getInstance().push(new message("[pangya_db::call_db_cmd_st::saveCmds][Error] fail to release Mutex. Error: " + std::to_string(GetLastError()), CL_FILE_LOG_AND_CONSOLE));
};
private:
bool isValid() {
return m_hMutex != INVALID_HANDLE_VALUE && m_hMutex != NULL;
};
bool lock() {
if (!isValid())
return false;
DWORD dwResult = WaitForSingleObject(m_hMutex, INFINITE);
return dwResult == WAIT_OBJECT_0 ? true : false;
};
bool unlock() {
if (!isValid())
return false;
return ReleaseMutex(m_hMutex) == TRUE;
};
private:
HANDLE m_hMutex;
const char url_log[30] = "H:/Server Lib/call_db_cmd.log";
};
// !@ Teste
bool logExecuteCmds(std::string _name) {
static call_db_cmd_st cdcs;
// Load
auto v_cmds = cdcs.loadCmds();
auto it = v_cmds.find(_name);
if (it == v_cmds.end()) {
v_cmds.insert(std::make_pair(_name, "yes"));
// Save
cdcs.saveCmds(v_cmds);
return true; // show log
}else if (it->second.compare("no") == 0) {
it->second = "yes";
// Save
cdcs.saveCmds(v_cmds);
return true; // show log
}
return false;
}
// !@ Teste
#endif
list_fifo_asyc< exec_query > pangya_db::m_query_pool;
list_async< exec_query* > pangya_db::m_cache_query;
pangya_db::pangya_db(bool _waitable) : m_exception("", 0), m_waitable(_waitable),
#if defined(_WIN32)
hEvent(INVALID_HANDLE_VALUE)
#elif defined(__linux__)
hEvent(nullptr)
#endif
{
#if defined(_WIN32)
if (_waitable)
if ((hEvent = CreateEvent(NULL, FALSE, FALSE, NULL)) == INVALID_HANDLE_VALUE)
_smp::message_pool::getInstance().push(new message("[pangya_db::pangya_db][Error] Error ao criar evento. ErrorCode: " + std::to_string(STDA_MAKE_ERROR(STDA_ERROR_TYPE::PANGYA_DB, 52, GetLastError())), CL_FILE_LOG_AND_CONSOLE));
#elif defined(__linux__)
if (_waitable) {
hEvent = new Event(false, 0u);
if (!hEvent->is_good()) {
delete hEvent;
hEvent = nullptr;
_smp::message_pool::getInstance().push(new message("[pangya_db::pangya_db][Error] Error ao criar evento. ErrorCode: " + std::to_string(STDA_MAKE_ERROR(STDA_ERROR_TYPE::PANGYA_DB, 52, errno)), CL_FILE_LOG_AND_CONSOLE));
}
}
#endif
};
pangya_db::~pangya_db() {
#if defined(_WIN32)
if (hEvent != INVALID_HANDLE_VALUE)
CloseHandle(hEvent);
hEvent = INVALID_HANDLE_VALUE;
#elif defined(__linux__)
if (hEvent != nullptr)
delete hEvent;
hEvent = nullptr;
#endif
};
inline void pangya_db::exec(database& _db) {
response *r = nullptr;
try {
if ((r = prepareConsulta(_db)) != nullptr) {
for (auto num_result = 0u; num_result < r->getNumResultSet(); ++num_result) {
if (r->getResultSetAt(num_result) != nullptr && r->getResultSetAt(num_result)->getNumLines() > 0
&& r->getResultSetAt(num_result)->getState() == result_set::HAVE_DATA) {
for (auto _result = r->getResultSetAt(num_result)->getFirstLine(); _result != nullptr; _result = _result->next) {
lineResult(_result, num_result);
}
}// só faz esse else se for mandar uma exception
clear_result(r->getResultSetAt(num_result));
}
clear_response(r);
}
}catch (exception& e) {
//UNREFERENCED_PARAMETER(e);
if (r != nullptr)
clear_response(r);
//throw;
m_exception = e;
_smp::message_pool::getInstance().push(new message("[pangya_db::" + _getName() + "::exec][Error] " + e.getFullMessageError(), CL_FILE_LOG_AND_CONSOLE));
}
#if defined(_WIN32) && defined(_TESTCMD_LOG)
// !@ Teste
if (logExecuteCmds(_getName()))
_smp::message_pool::getInstance().push(new message("[pangya_db::" + _getName() + "::exec][Log] Executado. ------------------->>", CL_FILE_LOG_AND_CONSOLE));
#endif
};
exception& pangya_db::getException() {
return m_exception;
};
void pangya_db::waitEvent() {
#if defined(_WIN32)
if (WaitForSingleObject(hEvent, INFINITE) != WAIT_OBJECT_0)
throw exception("[pangya_db::" + _getName() + "::waitEvent][Error] nao conseguiu esperar pelo evento", STDA_MAKE_ERROR(STDA_ERROR_TYPE::PANGYA_DB, 53, GetLastError()));
#elif defined(__linux__)
if (hEvent == nullptr || hEvent->wait(INFINITE) != WAIT_OBJECT_0)
throw exception("[pangya_db::" + _getName() + "::waitEvent][Error] nao conseguiu esperar pelo evento", STDA_MAKE_ERROR(STDA_ERROR_TYPE::PANGYA_DB, 53, errno));
#endif
}
void pangya_db::wakeupWaiter() {
#if defined(_WIN32)
SetEvent(hEvent);
#elif defined(__linux__)
if (hEvent != nullptr)
hEvent->set();
#endif
};
bool pangya_db::isWaitable() {
return m_waitable;
};
inline response* pangya_db::_insert(database& _db, std::string _query) {
return _insert(_db, MbToWc(_query));
}
inline response* pangya_db::_insert(database& _db, std::wstring _query) {
/*exec_query query(_query, exec_query::_INSERT);
postAndWaitResponseQuery(query);
return query.getRes();*/
return _db.ExecQuery(_query);
}
inline response* pangya_db::_update(database& _db, std::string _query) {
return _update(_db, MbToWc(_query));
};
inline response* pangya_db::_update(database& _db, std::wstring _query) {
//exec_query query(_query, exec_query::_UPDATE);
//postAndWaitResponseQuery(query);
////clear_response(query.getRes());
//return query.getRes();
return _db.ExecQuery(_query);
};
inline response* pangya_db::_delete(database& _db, std::string _query) {
return _delete(_db, MbToWc(_query));
};
inline response* pangya_db::_delete(database& _db, std::wstring _query) {
//exec_query query(_query, exec_query::_DELETE);
//postAndWaitResponseQuery(query);
////clear_response(query.getRes());
//return query.getRes();
return _db.ExecQuery(_query);
};
inline response* pangya_db::consulta(database& _db, std::string _query) {
return consulta(_db, MbToWc(_query));
};
inline response* pangya_db::consulta(database& _db, std::wstring _query) {
/*exec_query query(_query, exec_query::_QUERY);
postAndWaitResponseQuery(query);
return query.getRes();*/
return _db.ExecQuery(_query);
};
inline response* pangya_db::procedure(database& _db, std::string _name, std::string _params) {
return procedure(_db, MbToWc(_name), MbToWc(_params));
};
inline response* pangya_db::procedure(database& _db, std::wstring _name, std::wstring _params) {
/*exec_query query(_name, _params, exec_query::_PROCEDURE);
postAndWaitResponseQuery(query);
return query.getRes();*/
return _db.ExecProc(_name, _params);
};
inline void pangya_db::postAndWaitResponseQuery(exec_query& _query) {
DWORD wait = INFINITE;
//pangya_base_db::m_query_pool.push(&_query); // post query
m_query_pool.push(&_query);
while (1) {
try {
_query.waitEvent(wait);
break;
}catch (exception& e) {
if (STDA_SOURCE_ERROR_DECODE(e.getCodeError()) == STDA_ERROR_TYPE::EXEC_QUERY) {
if (STDA_ERROR_DECODE(e.getCodeError()) == 7 && wait == INFINITE) {
wait = 1000; // Espera um segundo se não for da próxima dá error
continue;
}
//pangya_base_db::m_query_pool.remove(&_query);
m_query_pool.remove(&_query);
throw;
}else throw;
}catch (std::exception& e) {
throw exception("System error: " + std::string(e.what()), STDA_MAKE_ERROR(STDA_ERROR_TYPE::PANGYA_DB, 100, 0));
}catch (...) {
throw exception("System error: Desconhecido", STDA_MAKE_ERROR(STDA_ERROR_TYPE::PANGYA_DB, 100, 1));
}
}
};
inline void pangya_db::clear_result(result_set*& _rs) {
if (_rs != nullptr)
delete _rs;
_rs = nullptr;
};
inline void pangya_db::clear_response(response* _res) {
if (_res != nullptr)
delete _res;
};
inline void pangya_db::checkColumnNumber(uint32_t _number_cols1, uint32_t _number_cols2) {
if (_number_cols1 != 0 && _number_cols1 != _number_cols2)
throw exception("[pangya_db::" + _getName() + "::checkColumnNumber][Error] numero de colunas retornada pela consulta sao diferente do esperado.", STDA_MAKE_ERROR(STDA_ERROR_TYPE::PANGYA_DB, 2, 0));
};
inline void pangya_db::checkResponse(response* r, std::string _exception_msg) {
if (r == nullptr || r->getNumResultSet() <= 0)
throw exception("[pangya_db::" + _getName() + "::checkResponse][Error] " + _exception_msg, STDA_MAKE_ERROR(STDA_ERROR_TYPE::PANGYA_DB, 1, 0));
};
inline void pangya_db::checkResponse(response* r, std::wstring _exception_msg) {
if (r == nullptr || r->getNumResultSet() <= 0)
throw exception(L"[pangya_db::" + _wgetName() + L"::checkResponse][Error] " + _exception_msg, STDA_MAKE_ERROR(STDA_ERROR_TYPE::PANGYA_DB, 1, 0));
};
bool pangya_db::compare(exec_query* _query1, exec_query* _query2) {
return _query1->getQuery().compare(_query2->getQuery()) == 0;
};
| 10,583 | 4,326 |
/*
* Copyright 2016 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "include/core/SkColorSpace.h"
#include "include/core/SkTypes.h"
#include "src/core/SkColorSpaceXformSteps.h"
#include "src/core/SkRasterPipeline.h"
#include "tests/Test.h"
#include <math.h>
DEF_TEST(srgb_roundtrip, r) {
uint32_t reds[256];
for (int i = 0; i < 256; i++) {
reds[i] = i;
}
SkRasterPipeline_MemoryCtx ptr = { reds, 0 };
sk_sp<SkColorSpace> sRGB = SkColorSpace::MakeSRGB(),
linear = sRGB->makeLinearGamma();
const SkAlphaType upm = kUnpremul_SkAlphaType;
SkColorSpaceXformSteps linearize{ sRGB.get(),upm, linear.get(),upm},
reencode {linear.get(),upm, sRGB.get(),upm};
SkRasterPipeline_<256> p;
p.append(SkRasterPipeline::load_8888, &ptr);
linearize.apply(&p);
reencode .apply(&p);
p.append(SkRasterPipeline::store_8888, &ptr);
p.run(0,0,256,1);
for (int i = 0; i < 256; i++) {
if (reds[i] != (uint32_t)i) {
ERRORF(r, "%d doesn't round trip, %d", i, reds[i]);
}
}
}
DEF_TEST(srgb_edge_cases, r) {
// We need to run at least 4 pixels to make sure we hit all specializations.
float colors[4][4] = { {0,1,1,1}, {0,0,0,0}, {0,0,0,0}, {0,0,0,0} };
auto& color = colors[0];
SkRasterPipeline_MemoryCtx dst = { &color, 0 };
sk_sp<SkColorSpace> sRGB = SkColorSpace::MakeSRGB(),
linear = sRGB->makeLinearGamma();
const SkAlphaType upm = kUnpremul_SkAlphaType;
SkColorSpaceXformSteps steps {linear.get(),upm, sRGB.get(),upm};
SkSTArenaAlloc<256> alloc;
SkRasterPipeline p(&alloc);
p.append_constant_color(&alloc, color);
steps.apply(&p);
p.append(SkRasterPipeline::store_f32, &dst);
p.run(0,0,4,1);
if (color[0] != 0.0f) {
ERRORF(r, "expected to_srgb() to map 0.0f to 0.0f, got %f", color[0]);
}
if (color[1] != 1.0f) {
float f = color[1];
uint32_t x;
memcpy(&x, &f, 4);
ERRORF(r, "expected to_srgb() to map 1.0f to 1.0f, got %f (%08x)", color[1], x);
}
}
// Linearize and then re-encode pixel values, testing that the output is close to the input.
DEF_TEST(srgb_roundtrip_extended, r) {
static const int kSteps = 128;
SkColor4f rgba[kSteps];
auto expected = [=](int i) {
float scale = 10000.0f / (3*kSteps);
return SkColor4f{
(3*i+0) * scale,
(3*i+1) * scale,
(3*i+2) * scale,
1.0f,
};
};
for (int i = 0; i < kSteps; i++) {
rgba[i] = expected(i);
}
SkRasterPipeline_MemoryCtx ptr = { rgba, 0 };
sk_sp<SkColorSpace> cs = SkColorSpace::MakeSRGB();
sk_sp<SkColorSpace> linear = cs->makeLinearGamma();
const SkAlphaType upm = kUnpremul_SkAlphaType;
SkColorSpaceXformSteps linearize{ cs.get(),upm, linear.get(),upm},
reencode {linear.get(),upm, cs.get(),upm};
SkRasterPipeline_<256> p;
p.append(SkRasterPipeline::load_f32, &ptr);
linearize.apply(&p);
reencode .apply(&p);
p.append(SkRasterPipeline::store_f32, &ptr);
p.run(0,0,kSteps,1);
auto close = [=](float x, float y) {
return x == y
|| (x/y < 1.001f && y/x < 1.001f);
};
for (int i = 0; i < kSteps; i++) {
SkColor4f want = expected(i);
#if 0
SkDebugf("got %g %g %g, want %g %g %g\n",
rgba[i].fR, rgba[i].fG, rgba[i].fB,
want.fR, want.fG, want.fB);
#endif
REPORTER_ASSERT(r, close(rgba[i].fR, want.fR));
REPORTER_ASSERT(r, close(rgba[i].fG, want.fG));
REPORTER_ASSERT(r, close(rgba[i].fB, want.fB));
}
}
| 3,824 | 1,579 |
#include <bonsai_types.h>
#include <game_constants.h>
#include <game_types.h>
#define RANDOM_HOTKEY_MASHING 0
#if RANDOM_HOTKEY_MASHING
static u32 HotkeyFrameTimeout = 0;
static random_series HotkeyEntropy = {};
static hotkeys StashedHotkeys = {};
#endif
model *
AllocateGameModels(game_state *GameState, memory_arena *Memory)
{
model *Result = Allocate(model, GameState->Memory, ModelIndex_Count);
Result[ModelIndex_Enemy] = LoadVoxModel(Memory, &GameState->Heap, ENEMY_MODEL);
Result[ModelIndex_Player] = LoadCollada(Memory, &GameState->Heap, "models/two-axis-animated-cube.dae");
/* Result[ModelIndex_Player] = LoadVoxModel(Memory, PLAYER_MODEL); */
Result[ModelIndex_Loot] = LoadVoxModel(Memory, &GameState->Heap, LOOT_MODEL);
/* chunk_dimension ProjectileDim = Chunk_Dimension(1,30,1); */
/* Result[ModelIndex_Projectile].Chunk = AllocateChunk(Memory, &GameState->Heap, ProjectileDim); */
/* Result[ModelIndex_Projectile].Dim = ProjectileDim; */
/* FillChunk(Result[ModelIndex_Projectile].Chunk, ProjectileDim, GREEN); */
Result[ModelIndex_Proton] = LoadVoxModel(Memory, &GameState->Heap, PROJECTILE_MODEL);
return Result;
}
BONSAI_API_WORKER_THREAD_CALLBACK()
{
switch (Entry->Type)
{
case type_work_queue_entry_init_world_chunk:
{
world_chunk* DestChunk = (world_chunk*)Entry->work_queue_entry_init_world_chunk.Input;
if (!ChunkIsGarbage(DestChunk))
{
s32 Amplititude = 100;
s32 StartingZDepth = -100;
InitializeWorldChunkPerlinPlane(Thread,
DestChunk,
WORLD_CHUNK_DIM,
Amplititude,
StartingZDepth);
/* Assert(DestChunk->CurrentTriangles->SurfacePoints->Count == 0); */
/* GetBoundingVoxels(DestChunk, DestChunk->CurrentTriangles->SurfacePoints); */
/* Triangulate(DestChunk->LodMesh, DestChunk, WORLD_CHUNK_DIM, Thread->TempMemory); */
/* Triangulate(DestChunk->LodMesh, DestChunk->CurrentTriangles, DestChunk, Thread->TempMemory); */
}
} break;
case type_work_queue_entry_copy_buffer:
{
untextured_3d_geometry_buffer* Src = Entry->work_queue_entry_copy_buffer.Src;
untextured_3d_geometry_buffer* Dest = &Entry->work_queue_entry_copy_buffer.Dest;
Assert(Src->At <= Dest->End);
v3 Basis = Entry->work_queue_entry_copy_buffer.Basis;
BufferVertsChecked(Src, Dest, Basis, V3(1.0f));
} break;
InvalidDefaultCase;
}
return;
}
BONSAI_API_MAIN_THREAD_CALLBACK()
{
TIMED_FUNCTION();
GetDebugState()->Plat = GameState->Plat;
GetDebugState()->GameState = GameState;
/* DebugPrint(*GameState->Plat); */
GL.Disable(GL_CULL_FACE);
#if BONSAI_INTERNAL
if (!GetDebugState)
{
GetDebugState = GameState->GetDebugState;
}
#endif
world *World = GameState->World;
graphics *Graphics = GameState->Graphics;
g_buffer_render_group *gBuffer = Graphics->gBuffer;
ao_render_group *AoGroup = Graphics->AoGroup;
camera *Camera = Graphics->Camera;
Graphics->GpuBufferWriteIndex = (Graphics->GpuBufferWriteIndex + 1) % 2;
gpu_mapped_element_buffer* GpuMap = Graphics->GpuBuffers + Graphics->GpuBufferWriteIndex;
MapGpuElementBuffer(GpuMap);
entity *Player = GameState->Player;
ClearFramebuffers(Graphics);
#if RANDOM_HOTKEY_MASHING
if (HotkeyFrameTimeout == 0)
{
Hotkeys->Left = RandomChoice(&HotkeyEntropy);
Hotkeys->Right = RandomChoice(&HotkeyEntropy);
Hotkeys->Forward = RandomChoice(&HotkeyEntropy);
Hotkeys->Backward = RandomChoice(&HotkeyEntropy);
StashedHotkeys = *Hotkeys;
HotkeyFrameTimeout = 100;
}
else
{
HotkeyFrameTimeout--;
*Hotkeys = StashedHotkeys;
}
#endif
#if DEBUG_DRAW_WORLD_AXIES
{
untextured_3d_geometry_buffer CopyDest = ReserveBufferSpace(&GpuMap->Buffer, VERTS_PER_LINE*3);
DEBUG_DrawLine(&CopyDest, V3(0,0,0), V3(10000, 0, 0), RED, 0.5f );
DEBUG_DrawLine(&CopyDest, V3(0,0,0), V3(0, 10000, 0), GREEN, 0.5f );
DEBUG_DrawLine(&CopyDest, V3(0,0,0), V3(0, 0, 10000), BLUE, 0.5f );
}
#endif
if (Hotkeys->Player_Spawn)
{
Unspawn(Player);
world_position PlayerChunkP = World_Position(0, 0, -2);
SpawnPlayer(GameState->Models, Player, Canonical_Position(V3(0,0,2), World_Position(0,0,0)), &GameState->Entropy);
World->Center = PlayerChunkP;
}
SimulatePlayer(World, Player, Camera, Hotkeys, Plat->dt, g_VisibleRegion);
CollectUnusedChunks(World, &GameState->MeshFreelist, GameState->Memory, g_VisibleRegion);
v2 MouseDelta = GetMouseDelta(Plat);
input* GameInput = &Plat->Input;
#if BONSAI_INTERNAL
if (GetDebugState()->UiGroup.PressedInteractionId != StringHash("GameViewport"))
{
GameInput = 0;
}
#endif
UpdateGameCamera(MouseDelta, GameInput, Player->P, Camera, World->ChunkDim);
SimulateEntities(World, GameState->EntityTable, Plat->dt, g_VisibleRegion);
SimulateAndRenderParticleSystems(GameState->EntityTable, World->ChunkDim, &GpuMap->Buffer, Graphics, Plat->dt);
gBuffer->ViewProjection =
ProjectionMatrix(Camera, Plat->WindowWidth, Plat->WindowHeight) *
ViewMatrix(World->ChunkDim, Camera);
DEBUG_COMPUTE_PICK_RAY(Plat, &gBuffer->ViewProjection);
TIMED_BLOCK("BufferMeshes");
BufferWorld(Plat, &GpuMap->Buffer, World, Graphics, g_VisibleRegion);
BufferEntities( GameState->EntityTable, &GpuMap->Buffer, Graphics, World, Plat->dt);
END_BLOCK("BufferMeshes");
#if BONSAI_INTERNAL
for (u32 ChunkIndex = 0;
ChunkIndex < GetDebugState()->PickedChunkCount;
++ChunkIndex)
{
world_chunk *Chunk = GetDebugState()->PickedChunks[ChunkIndex];
untextured_3d_geometry_buffer CopyDest = ReserveBufferSpace(&GpuMap->Buffer, VERTS_PER_AABB);
u8 Color = GREEN;
if (Chunk == GetDebugState()->HotChunk)
{
Color = PINK;
}
DEBUG_DrawChunkAABB(&CopyDest, Graphics, Chunk, World->ChunkDim, Color, 0.35f);
}
#endif
TIMED_BLOCK("Wait for worker threads");
for (;;) { if (QueueIsEmpty(&Plat->HighPriority)) { break; } }
END_BLOCK("Wait for worker threads");
TIMED_BLOCK("RenderToScreen");
RenderGBuffer(GpuMap, Graphics);
RenderAoTexture(AoGroup);
DrawGBufferToFullscreenQuad(Plat, Graphics);
END_BLOCK("RenderToScreen");
Graphics->Lights->Count = 0;
return;
}
BONSAI_API_MAIN_THREAD_INIT_CALLBACK()
{
Info("Initializing Game");
GL = *GL_in;
GetDebugState = GetDebugState_in;
Init_Global_QuadVertexBuffer();
game_state *GameState = Allocate(game_state, GameMemory, 1);
GameState->Memory = GameMemory;
GameState->Noise = perlin_noise(DEBUG_NOISE_SEED);
GameState->Graphics = GraphicsInit(GameMemory);
if (!GameState->Graphics) { Error("Initializing Graphics"); return False; }
StandardCamera(GameState->Graphics->Camera, 10000.0f, 300.0f);
GameState->Plat = Plat;
GameState->Entropy.Seed = DEBUG_NOISE_SEED;
world_position WorldCenter = World_Position(0, 0, 0);
GameState->Heap = InitHeap(Gigabytes(4));
GameState->World = AllocateAndInitWorld(WorldCenter, WORLD_CHUNK_DIM, g_VisibleRegion);
GameState->EntityTable = AllocateEntityTable(GameMemory, TOTAL_ENTITY_COUNT);
GameState->Models = AllocateGameModels(GameState, GameState->Memory);
GameState->Player = GetFreeEntity(GameState->EntityTable);
SpawnPlayer(GameState->Models, GameState->Player, Canonical_Position(Voxel_Position(0), WorldCenter), &GameState->Entropy);
return GameState;
}
BONSAI_API_WORKER_THREAD_INIT_CALLBACK()
{
Thread->MeshFreelist = &GameState->MeshFreelist;
Thread->Noise = &GameState->Noise;
}
| 7,717 | 2,819 |
#include<iostream>
using namespace std;
int hey(int a){
int c= a+3;
return c;
}
int main(){
int i= 29;
cout<<hey(i);
}
| 145 | 62 |
#include "ExtractZipPassFromCredMan.h"
#include <iostream>
using namespace std;
int main()
{
PCREDENTIALW * credBuf = NULL;
DWORD count;
int result = ExtractZipPassFromCredMan(&credBuf, &count);
if (result == CREDENTIALS_BUFFER_ERROR)
{
cout << "CREDENTIALS_BUFFER_ERROR" << endl;
goto __cleanup;
}
else if (result == ZIP_PASS_NOT_FOUND)
{
cout << "No Zip passwords found!" << endl;
goto __cleanup;
}
else
{
for (DWORD i = 0; i < count; i++)
{
if (credBuf[i]->CredentialBlob && credBuf[i]->TargetName)
{
cout << endl << "------------------------------------------------------" << endl;
wcout << "Target: " << (wchar_t *)credBuf[i]->TargetName << endl << endl;
wcout << "Password: " << (wchar_t *)credBuf[i]->CredentialBlob << endl;
cout << "------------------------------------------------------" << endl << endl;
}
}
}
__cleanup:
if (credBuf)
CredFree(credBuf);
cin.get();
return 0;
}
| 995 | 396 |
/*
* Copyright (c) 2016-2016, ARM Limited, All Rights Reserved
* 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 "mbed.h"
#include "rtos.h"
#include "greentea-client/test_env.h"
#include "unity/unity.h"
#include "utest/utest.h"
#include "SingletonPtr.h"
#include <stdio.h>
#ifdef MBED_RTOS_SINGLE_THREAD
#error [NOT_SUPPORTED] test not supported for single threaded enviroment
#endif
#if !DEVICE_USTICKER
#error [NOT_SUPPORTED] test not supported
#endif
using namespace utest::v1;
#define TEST_STACK_SIZE 512
static uint32_t instance_count = 0;
class TestClass {
public:
TestClass()
{
Thread::wait(500);
instance_count++;
}
void do_something()
{
Thread::wait(100);
}
~TestClass()
{
instance_count--;
}
};
static TestClass *get_test_class()
{
static TestClass tc;
return &tc;
}
static SingletonPtr<TestClass> test_class;
static void main_func_race()
{
get_test_class();
TEST_ASSERT_EQUAL_UINT32(1, instance_count);
}
static void main_class_race()
{
test_class->do_something();
TEST_ASSERT_EQUAL_UINT32(1, instance_count);
}
void test_case_func_race()
{
Callback<void()> cb(main_func_race);
Thread t1(osPriorityNormal, TEST_STACK_SIZE);
Thread t2(osPriorityNormal, TEST_STACK_SIZE);
// Start start first thread
t1.start(cb);
// Start second thread while the first is inside the constructor
Thread::wait(250);
t2.start(cb);
// Wait for the threads to finish
t1.join();
t2.join();
TEST_ASSERT_EQUAL_UINT32(1, instance_count);
// Reset instance count
instance_count = 0;
}
void test_case_class_race()
{
Callback<void()> cb(main_class_race);
Thread t1(osPriorityNormal, TEST_STACK_SIZE);
Thread t2(osPriorityNormal, TEST_STACK_SIZE);
// Start start first thread
t1.start(cb);
// Start second thread while the first is inside the constructor
Thread::wait(250);
t2.start(cb);
// Wait for the threads to finish
t1.join();
t2.join();
TEST_ASSERT_EQUAL_UINT32(1, instance_count);
// Reset instance count
instance_count = 0;
}
Case cases[] = {
Case("function init race", test_case_func_race),
Case("class init race", test_case_class_race),
};
utest::v1::status_t greentea_test_setup(const size_t number_of_cases)
{
GREENTEA_SETUP(20, "default_auto");
return greentea_test_setup_handler(number_of_cases);
}
Specification specification(greentea_test_setup, cases, greentea_test_teardown_handler);
int main()
{
Harness::run(specification);
}
| 3,137 | 1,128 |
// Copyright ilikotsutskiridze 2021
#include <revert_string.hpp>
std::string convert(const int &a)
{
int bin=0, j;
for(j=0; a>0; j++)
{
bin+=(a%2)*pow(10.0,j);
a/=2;
}
std::string s=std::to_string(bin);
return s;
}
| 265 | 125 |
#include <iostream>
#include <string>
#include <pybind11/pybind11.h>
#include <autocxxpy/autocxxpy.hpp>
#include "module.hpp"
#include "wrappers.hpp"
#include "generated_functions.h"
#include "xtp_trader_api.h"
#include "xtp_quote_api.h"
void generate_caster_XTP_API(pybind11::object & parent)
{
struct caster: autocxxpy::caster{};
auto c = autocxxpy::caster::bind<caster>(parent, "caster");
autocxxpy::caster::try_generate<XTP::API::TraderSpi>(c, "toTraderSpi)");
autocxxpy::caster::try_generate<XTP::API::TraderApi>(c, "toTraderApi)");
autocxxpy::caster::try_generate<XTP::API::QuoteSpi>(c, "toQuoteSpi)");
autocxxpy::caster::try_generate<XTP::API::QuoteApi>(c, "toQuoteApi)");
}
void generate_caster_XTP(pybind11::object & parent)
{
struct caster: autocxxpy::caster{};
auto c = autocxxpy::caster::bind<caster>(parent, "caster");
}
void generate_class_XTPRspInfoStruct(pybind11::object & parent)
{
pybind11::class_<XTPRspInfoStruct> c(parent, "XTPRspInfoStruct");
if constexpr (std::is_default_constructible_v<XTPRspInfoStruct>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPRspInfoStruct, "error_id", error_id);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPRspInfoStruct, "error_msg", error_msg);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vnxtp, XTPRspInfoStruct, c);
module_vnxtp::objects.emplace("XTPRspInfoStruct", c);
}
void generate_class_XTPSpecificTickerStruct(pybind11::object & parent)
{
pybind11::class_<XTPSpecificTickerStruct> c(parent, "XTPSpecificTickerStruct");
if constexpr (std::is_default_constructible_v<XTPSpecificTickerStruct>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPSpecificTickerStruct, "exchange_id", exchange_id);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPSpecificTickerStruct, "ticker", ticker);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vnxtp, XTPSpecificTickerStruct, c);
module_vnxtp::objects.emplace("XTPSpecificTickerStruct", c);
}
void generate_class_XTPMarketDataStockExData(pybind11::object & parent)
{
pybind11::class_<XTPMarketDataStockExData> c(parent, "XTPMarketDataStockExData");
if constexpr (std::is_default_constructible_v<XTPMarketDataStockExData>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStockExData, "total_bid_qty", total_bid_qty);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStockExData, "total_ask_qty", total_ask_qty);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStockExData, "ma_bid_price", ma_bid_price);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStockExData, "ma_ask_price", ma_ask_price);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStockExData, "ma_bond_bid_price", ma_bond_bid_price);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStockExData, "ma_bond_ask_price", ma_bond_ask_price);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStockExData, "yield_to_maturity", yield_to_maturity);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStockExData, "iopv", iopv);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStockExData, "etf_buy_count", etf_buy_count);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStockExData, "etf_sell_count", etf_sell_count);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStockExData, "etf_buy_qty", etf_buy_qty);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStockExData, "etf_buy_money", etf_buy_money);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStockExData, "etf_sell_qty", etf_sell_qty);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStockExData, "etf_sell_money", etf_sell_money);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStockExData, "total_warrant_exec_qty", total_warrant_exec_qty);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStockExData, "warrant_lower_price", warrant_lower_price);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStockExData, "warrant_upper_price", warrant_upper_price);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStockExData, "cancel_buy_count", cancel_buy_count);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStockExData, "cancel_sell_count", cancel_sell_count);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStockExData, "cancel_buy_qty", cancel_buy_qty);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStockExData, "cancel_sell_qty", cancel_sell_qty);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStockExData, "cancel_buy_money", cancel_buy_money);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStockExData, "cancel_sell_money", cancel_sell_money);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStockExData, "total_buy_count", total_buy_count);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStockExData, "total_sell_count", total_sell_count);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStockExData, "duration_after_buy", duration_after_buy);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStockExData, "duration_after_sell", duration_after_sell);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStockExData, "num_bid_orders", num_bid_orders);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStockExData, "num_ask_orders", num_ask_orders);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStockExData, "pre_iopv", pre_iopv);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStockExData, "r1", r1);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStockExData, "r2", r2);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vnxtp, XTPMarketDataStockExData, c);
module_vnxtp::objects.emplace("XTPMarketDataStockExData", c);
}
void generate_class_XTPMarketDataOptionExData(pybind11::object & parent)
{
pybind11::class_<XTPMarketDataOptionExData> c(parent, "XTPMarketDataOptionExData");
if constexpr (std::is_default_constructible_v<XTPMarketDataOptionExData>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataOptionExData, "auction_price", auction_price);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataOptionExData, "auction_qty", auction_qty);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataOptionExData, "last_enquiry_time", last_enquiry_time);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vnxtp, XTPMarketDataOptionExData, c);
module_vnxtp::objects.emplace("XTPMarketDataOptionExData", c);
}
void generate_class_XTPMarketDataStruct(pybind11::object & parent)
{
pybind11::class_<XTPMarketDataStruct> c(parent, "XTPMarketDataStruct");
if constexpr (std::is_default_constructible_v<XTPMarketDataStruct>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStruct, "exchange_id", exchange_id);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStruct, "ticker", ticker);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStruct, "last_price", last_price);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStruct, "pre_close_price", pre_close_price);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStruct, "open_price", open_price);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStruct, "high_price", high_price);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStruct, "low_price", low_price);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStruct, "close_price", close_price);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStruct, "pre_total_long_positon", pre_total_long_positon);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStruct, "total_long_positon", total_long_positon);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStruct, "pre_settl_price", pre_settl_price);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStruct, "settl_price", settl_price);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStruct, "upper_limit_price", upper_limit_price);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStruct, "lower_limit_price", lower_limit_price);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStruct, "pre_delta", pre_delta);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStruct, "curr_delta", curr_delta);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStruct, "data_time", data_time);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStruct, "qty", qty);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStruct, "turnover", turnover);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStruct, "avg_price", avg_price);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStruct, "bid", bid);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStruct, "ask", ask);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStruct, "bid_qty", bid_qty);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStruct, "ask_qty", ask_qty);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStruct, "trades_count", trades_count);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStruct, "ticker_status", ticker_status);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStruct, "stk", stk);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStruct, "opt", opt);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStruct, "data_type", data_type);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPMarketDataStruct, "r4", r4);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vnxtp, XTPMarketDataStruct, c);
module_vnxtp::objects.emplace("XTPMarketDataStruct", c);
}
void generate_class_XTPQuoteStaticInfo(pybind11::object & parent)
{
pybind11::class_<XTPQuoteStaticInfo> c(parent, "XTPQuoteStaticInfo");
if constexpr (std::is_default_constructible_v<XTPQuoteStaticInfo>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQuoteStaticInfo, "exchange_id", exchange_id);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQuoteStaticInfo, "ticker", ticker);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQuoteStaticInfo, "ticker_name", ticker_name);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQuoteStaticInfo, "ticker_type", ticker_type);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQuoteStaticInfo, "pre_close_price", pre_close_price);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQuoteStaticInfo, "upper_limit_price", upper_limit_price);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQuoteStaticInfo, "lower_limit_price", lower_limit_price);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQuoteStaticInfo, "price_tick", price_tick);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQuoteStaticInfo, "buy_qty_unit", buy_qty_unit);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQuoteStaticInfo, "sell_qty_unit", sell_qty_unit);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vnxtp, XTPQuoteStaticInfo, c);
module_vnxtp::objects.emplace("XTPQuoteStaticInfo", c);
}
void generate_class_OrderBookStruct(pybind11::object & parent)
{
pybind11::class_<OrderBookStruct> c(parent, "OrderBookStruct");
if constexpr (std::is_default_constructible_v<OrderBookStruct>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, OrderBookStruct, "exchange_id", exchange_id);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, OrderBookStruct, "ticker", ticker);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, OrderBookStruct, "last_price", last_price);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, OrderBookStruct, "qty", qty);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, OrderBookStruct, "turnover", turnover);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, OrderBookStruct, "trades_count", trades_count);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, OrderBookStruct, "bid", bid);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, OrderBookStruct, "ask", ask);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, OrderBookStruct, "bid_qty", bid_qty);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, OrderBookStruct, "ask_qty", ask_qty);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, OrderBookStruct, "data_time", data_time);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vnxtp, OrderBookStruct, c);
module_vnxtp::objects.emplace("OrderBookStruct", c);
}
void generate_class_XTPTickByTickEntrust(pybind11::object & parent)
{
pybind11::class_<XTPTickByTickEntrust> c(parent, "XTPTickByTickEntrust");
if constexpr (std::is_default_constructible_v<XTPTickByTickEntrust>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPTickByTickEntrust, "channel_no", channel_no);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPTickByTickEntrust, "seq", seq);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPTickByTickEntrust, "price", price);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPTickByTickEntrust, "qty", qty);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPTickByTickEntrust, "side", side);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPTickByTickEntrust, "ord_type", ord_type);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vnxtp, XTPTickByTickEntrust, c);
module_vnxtp::objects.emplace("XTPTickByTickEntrust", c);
}
void generate_class_XTPTickByTickTrade(pybind11::object & parent)
{
pybind11::class_<XTPTickByTickTrade> c(parent, "XTPTickByTickTrade");
if constexpr (std::is_default_constructible_v<XTPTickByTickTrade>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPTickByTickTrade, "channel_no", channel_no);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPTickByTickTrade, "seq", seq);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPTickByTickTrade, "price", price);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPTickByTickTrade, "qty", qty);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPTickByTickTrade, "money", money);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPTickByTickTrade, "bid_no", bid_no);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPTickByTickTrade, "ask_no", ask_no);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPTickByTickTrade, "trade_flag", trade_flag);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vnxtp, XTPTickByTickTrade, c);
module_vnxtp::objects.emplace("XTPTickByTickTrade", c);
}
void generate_class_XTPTickByTickStruct(pybind11::object & parent)
{
pybind11::class_<XTPTickByTickStruct> c(parent, "XTPTickByTickStruct");
if constexpr (std::is_default_constructible_v<XTPTickByTickStruct>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPTickByTickStruct, "exchange_id", exchange_id);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPTickByTickStruct, "ticker", ticker);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPTickByTickStruct, "seq", seq);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPTickByTickStruct, "data_time", data_time);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPTickByTickStruct, "type", type);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPTickByTickStruct, "entrust", entrust);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPTickByTickStruct, "trade", trade);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vnxtp, XTPTickByTickStruct, c);
module_vnxtp::objects.emplace("XTPTickByTickStruct", c);
}
void generate_class_XTPTickerPriceInfo(pybind11::object & parent)
{
pybind11::class_<XTPTickerPriceInfo> c(parent, "XTPTickerPriceInfo");
if constexpr (std::is_default_constructible_v<XTPTickerPriceInfo>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPTickerPriceInfo, "exchange_id", exchange_id);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPTickerPriceInfo, "ticker", ticker);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPTickerPriceInfo, "last_price", last_price);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vnxtp, XTPTickerPriceInfo, c);
module_vnxtp::objects.emplace("XTPTickerPriceInfo", c);
}
void generate_class_XTPOrderInsertInfo(pybind11::object & parent)
{
pybind11::class_<XTPOrderInsertInfo> c(parent, "XTPOrderInsertInfo");
if constexpr (std::is_default_constructible_v<XTPOrderInsertInfo>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPOrderInsertInfo, "order_xtp_id", order_xtp_id);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPOrderInsertInfo, "order_client_id", order_client_id);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPOrderInsertInfo, "ticker", ticker);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPOrderInsertInfo, "market", market);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPOrderInsertInfo, "price", price);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPOrderInsertInfo, "stop_price", stop_price);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPOrderInsertInfo, "quantity", quantity);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPOrderInsertInfo, "price_type", price_type);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPOrderInsertInfo, "u32", u32);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPOrderInsertInfo, "side", side);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPOrderInsertInfo, "position_effect", position_effect);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPOrderInsertInfo, "reserved1", reserved1);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPOrderInsertInfo, "reserved2", reserved2);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPOrderInsertInfo, "business_type", business_type);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vnxtp, XTPOrderInsertInfo, c);
module_vnxtp::objects.emplace("XTPOrderInsertInfo", c);
}
void generate_class_XTPOrderCancelInfo(pybind11::object & parent)
{
pybind11::class_<XTPOrderCancelInfo> c(parent, "XTPOrderCancelInfo");
if constexpr (std::is_default_constructible_v<XTPOrderCancelInfo>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPOrderCancelInfo, "order_cancel_xtp_id", order_cancel_xtp_id);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPOrderCancelInfo, "order_xtp_id", order_xtp_id);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vnxtp, XTPOrderCancelInfo, c);
module_vnxtp::objects.emplace("XTPOrderCancelInfo", c);
}
void generate_class_XTPOrderInfo(pybind11::object & parent)
{
pybind11::class_<XTPOrderInfo> c(parent, "XTPOrderInfo");
if constexpr (std::is_default_constructible_v<XTPOrderInfo>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPOrderInfo, "order_xtp_id", order_xtp_id);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPOrderInfo, "order_client_id", order_client_id);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPOrderInfo, "order_cancel_client_id", order_cancel_client_id);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPOrderInfo, "order_cancel_xtp_id", order_cancel_xtp_id);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPOrderInfo, "ticker", ticker);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPOrderInfo, "market", market);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPOrderInfo, "price", price);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPOrderInfo, "quantity", quantity);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPOrderInfo, "price_type", price_type);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPOrderInfo, "u32", u32);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPOrderInfo, "side", side);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPOrderInfo, "position_effect", position_effect);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPOrderInfo, "reserved1", reserved1);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPOrderInfo, "reserved2", reserved2);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPOrderInfo, "business_type", business_type);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPOrderInfo, "qty_traded", qty_traded);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPOrderInfo, "qty_left", qty_left);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPOrderInfo, "insert_time", insert_time);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPOrderInfo, "update_time", update_time);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPOrderInfo, "cancel_time", cancel_time);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPOrderInfo, "trade_amount", trade_amount);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPOrderInfo, "order_local_id", order_local_id);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPOrderInfo, "order_status", order_status);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPOrderInfo, "order_submit_status", order_submit_status);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPOrderInfo, "order_type", order_type);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vnxtp, XTPOrderInfo, c);
module_vnxtp::objects.emplace("XTPOrderInfo", c);
}
void generate_class_XTPTradeReport(pybind11::object & parent)
{
pybind11::class_<XTPTradeReport> c(parent, "XTPTradeReport");
if constexpr (std::is_default_constructible_v<XTPTradeReport>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPTradeReport, "order_xtp_id", order_xtp_id);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPTradeReport, "order_client_id", order_client_id);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPTradeReport, "ticker", ticker);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPTradeReport, "market", market);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPTradeReport, "local_order_id", local_order_id);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPTradeReport, "exec_id", exec_id);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPTradeReport, "price", price);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPTradeReport, "quantity", quantity);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPTradeReport, "trade_time", trade_time);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPTradeReport, "trade_amount", trade_amount);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPTradeReport, "report_index", report_index);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPTradeReport, "order_exch_id", order_exch_id);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPTradeReport, "trade_type", trade_type);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPTradeReport, "u32", u32);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPTradeReport, "side", side);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPTradeReport, "position_effect", position_effect);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPTradeReport, "reserved1", reserved1);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPTradeReport, "reserved2", reserved2);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPTradeReport, "business_type", business_type);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPTradeReport, "branch_pbu", branch_pbu);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vnxtp, XTPTradeReport, c);
module_vnxtp::objects.emplace("XTPTradeReport", c);
}
void generate_class_XTPQueryOrderReq(pybind11::object & parent)
{
pybind11::class_<XTPQueryOrderReq> c(parent, "XTPQueryOrderReq");
if constexpr (std::is_default_constructible_v<XTPQueryOrderReq>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryOrderReq, "ticker", ticker);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryOrderReq, "begin_time", begin_time);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryOrderReq, "end_time", end_time);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vnxtp, XTPQueryOrderReq, c);
module_vnxtp::objects.emplace("XTPQueryOrderReq", c);
}
void generate_class_XTPQueryReportByExecIdReq(pybind11::object & parent)
{
pybind11::class_<XTPQueryReportByExecIdReq> c(parent, "XTPQueryReportByExecIdReq");
if constexpr (std::is_default_constructible_v<XTPQueryReportByExecIdReq>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryReportByExecIdReq, "order_xtp_id", order_xtp_id);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryReportByExecIdReq, "exec_id", exec_id);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vnxtp, XTPQueryReportByExecIdReq, c);
module_vnxtp::objects.emplace("XTPQueryReportByExecIdReq", c);
}
void generate_class_XTPQueryTraderReq(pybind11::object & parent)
{
pybind11::class_<XTPQueryTraderReq> c(parent, "XTPQueryTraderReq");
if constexpr (std::is_default_constructible_v<XTPQueryTraderReq>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryTraderReq, "ticker", ticker);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryTraderReq, "begin_time", begin_time);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryTraderReq, "end_time", end_time);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vnxtp, XTPQueryTraderReq, c);
module_vnxtp::objects.emplace("XTPQueryTraderReq", c);
}
void generate_class_XTPQueryAssetRsp(pybind11::object & parent)
{
pybind11::class_<XTPQueryAssetRsp> c(parent, "XTPQueryAssetRsp");
if constexpr (std::is_default_constructible_v<XTPQueryAssetRsp>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryAssetRsp, "total_asset", total_asset);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryAssetRsp, "buying_power", buying_power);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryAssetRsp, "security_asset", security_asset);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryAssetRsp, "fund_buy_amount", fund_buy_amount);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryAssetRsp, "fund_buy_fee", fund_buy_fee);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryAssetRsp, "fund_sell_amount", fund_sell_amount);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryAssetRsp, "fund_sell_fee", fund_sell_fee);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryAssetRsp, "withholding_amount", withholding_amount);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryAssetRsp, "account_type", account_type);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryAssetRsp, "frozen_margin", frozen_margin);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryAssetRsp, "frozen_exec_cash", frozen_exec_cash);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryAssetRsp, "frozen_exec_fee", frozen_exec_fee);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryAssetRsp, "pay_later", pay_later);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryAssetRsp, "preadva_pay", preadva_pay);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryAssetRsp, "orig_banlance", orig_banlance);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryAssetRsp, "banlance", banlance);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryAssetRsp, "deposit_withdraw", deposit_withdraw);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryAssetRsp, "trade_netting", trade_netting);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryAssetRsp, "captial_asset", captial_asset);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryAssetRsp, "force_freeze_amount", force_freeze_amount);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryAssetRsp, "preferred_amount", preferred_amount);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryAssetRsp, "unknown", unknown);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vnxtp, XTPQueryAssetRsp, c);
module_vnxtp::objects.emplace("XTPQueryAssetRsp", c);
}
void generate_class_XTPQueryStkPositionRsp(pybind11::object & parent)
{
pybind11::class_<XTPQueryStkPositionRsp> c(parent, "XTPQueryStkPositionRsp");
if constexpr (std::is_default_constructible_v<XTPQueryStkPositionRsp>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryStkPositionRsp, "ticker", ticker);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryStkPositionRsp, "ticker_name", ticker_name);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryStkPositionRsp, "market", market);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryStkPositionRsp, "total_qty", total_qty);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryStkPositionRsp, "sellable_qty", sellable_qty);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryStkPositionRsp, "avg_price", avg_price);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryStkPositionRsp, "unrealized_pnl", unrealized_pnl);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryStkPositionRsp, "yesterday_position", yesterday_position);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryStkPositionRsp, "purchase_redeemable_qty", purchase_redeemable_qty);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryStkPositionRsp, "position_direction", position_direction);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryStkPositionRsp, "reserved1", reserved1);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryStkPositionRsp, "executable_option", executable_option);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryStkPositionRsp, "lockable_position", lockable_position);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryStkPositionRsp, "executable_underlying", executable_underlying);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryStkPositionRsp, "locked_position", locked_position);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryStkPositionRsp, "usable_locked_position", usable_locked_position);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryStkPositionRsp, "unknown", unknown);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vnxtp, XTPQueryStkPositionRsp, c);
module_vnxtp::objects.emplace("XTPQueryStkPositionRsp", c);
}
void generate_class_XTPFundTransferNotice(pybind11::object & parent)
{
pybind11::class_<XTPFundTransferNotice> c(parent, "XTPFundTransferNotice");
if constexpr (std::is_default_constructible_v<XTPFundTransferNotice>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPFundTransferNotice, "serial_id", serial_id);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPFundTransferNotice, "transfer_type", transfer_type);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPFundTransferNotice, "amount", amount);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPFundTransferNotice, "oper_status", oper_status);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPFundTransferNotice, "transfer_time", transfer_time);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vnxtp, XTPFundTransferNotice, c);
module_vnxtp::objects.emplace("XTPFundTransferNotice", c);
}
void generate_class_XTPQueryFundTransferLogReq(pybind11::object & parent)
{
pybind11::class_<XTPQueryFundTransferLogReq> c(parent, "XTPQueryFundTransferLogReq");
if constexpr (std::is_default_constructible_v<XTPQueryFundTransferLogReq>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryFundTransferLogReq, "serial_id", serial_id);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vnxtp, XTPQueryFundTransferLogReq, c);
module_vnxtp::objects.emplace("XTPQueryFundTransferLogReq", c);
}
void generate_class_XTPQueryStructuredFundInfoReq(pybind11::object & parent)
{
pybind11::class_<XTPQueryStructuredFundInfoReq> c(parent, "XTPQueryStructuredFundInfoReq");
if constexpr (std::is_default_constructible_v<XTPQueryStructuredFundInfoReq>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryStructuredFundInfoReq, "exchange_id", exchange_id);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryStructuredFundInfoReq, "sf_ticker", sf_ticker);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vnxtp, XTPQueryStructuredFundInfoReq, c);
module_vnxtp::objects.emplace("XTPQueryStructuredFundInfoReq", c);
}
void generate_class_XTPStructuredFundInfo(pybind11::object & parent)
{
pybind11::class_<XTPStructuredFundInfo> c(parent, "XTPStructuredFundInfo");
if constexpr (std::is_default_constructible_v<XTPStructuredFundInfo>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPStructuredFundInfo, "exchange_id", exchange_id);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPStructuredFundInfo, "sf_ticker", sf_ticker);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPStructuredFundInfo, "sf_ticker_name", sf_ticker_name);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPStructuredFundInfo, "ticker", ticker);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPStructuredFundInfo, "ticker_name", ticker_name);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPStructuredFundInfo, "split_merge_status", split_merge_status);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPStructuredFundInfo, "ratio", ratio);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPStructuredFundInfo, "min_split_qty", min_split_qty);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPStructuredFundInfo, "min_merge_qty", min_merge_qty);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPStructuredFundInfo, "net_price", net_price);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vnxtp, XTPStructuredFundInfo, c);
module_vnxtp::objects.emplace("XTPStructuredFundInfo", c);
}
void generate_class_XTPQueryETFBaseReq(pybind11::object & parent)
{
pybind11::class_<XTPQueryETFBaseReq> c(parent, "XTPQueryETFBaseReq");
if constexpr (std::is_default_constructible_v<XTPQueryETFBaseReq>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryETFBaseReq, "market", market);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryETFBaseReq, "ticker", ticker);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vnxtp, XTPQueryETFBaseReq, c);
module_vnxtp::objects.emplace("XTPQueryETFBaseReq", c);
}
void generate_class_XTPQueryETFBaseRsp(pybind11::object & parent)
{
pybind11::class_<XTPQueryETFBaseRsp> c(parent, "XTPQueryETFBaseRsp");
if constexpr (std::is_default_constructible_v<XTPQueryETFBaseRsp>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryETFBaseRsp, "market", market);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryETFBaseRsp, "etf", etf);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryETFBaseRsp, "subscribe_redemption_ticker", subscribe_redemption_ticker);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryETFBaseRsp, "unit", unit);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryETFBaseRsp, "subscribe_status", subscribe_status);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryETFBaseRsp, "redemption_status", redemption_status);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryETFBaseRsp, "max_cash_ratio", max_cash_ratio);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryETFBaseRsp, "estimate_amount", estimate_amount);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryETFBaseRsp, "cash_component", cash_component);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryETFBaseRsp, "net_value", net_value);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryETFBaseRsp, "total_amount", total_amount);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vnxtp, XTPQueryETFBaseRsp, c);
module_vnxtp::objects.emplace("XTPQueryETFBaseRsp", c);
}
void generate_class_XTPQueryETFComponentReq(pybind11::object & parent)
{
pybind11::class_<XTPQueryETFComponentReq> c(parent, "XTPQueryETFComponentReq");
if constexpr (std::is_default_constructible_v<XTPQueryETFComponentReq>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryETFComponentReq, "market", market);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryETFComponentReq, "ticker", ticker);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vnxtp, XTPQueryETFComponentReq, c);
module_vnxtp::objects.emplace("XTPQueryETFComponentReq", c);
}
void generate_class_XTPQueryETFComponentRsp(pybind11::object & parent)
{
pybind11::class_<XTPQueryETFComponentRsp> c(parent, "XTPQueryETFComponentRsp");
if constexpr (std::is_default_constructible_v<XTPQueryETFComponentRsp>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryETFComponentRsp, "market", market);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryETFComponentRsp, "ticker", ticker);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryETFComponentRsp, "component_ticker", component_ticker);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryETFComponentRsp, "component_name", component_name);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryETFComponentRsp, "quantity", quantity);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryETFComponentRsp, "component_market", component_market);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryETFComponentRsp, "replace_type", replace_type);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryETFComponentRsp, "premium_ratio", premium_ratio);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryETFComponentRsp, "amount", amount);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vnxtp, XTPQueryETFComponentRsp, c);
module_vnxtp::objects.emplace("XTPQueryETFComponentRsp", c);
}
void generate_class_XTPQueryIPOTickerRsp(pybind11::object & parent)
{
pybind11::class_<XTPQueryIPOTickerRsp> c(parent, "XTPQueryIPOTickerRsp");
if constexpr (std::is_default_constructible_v<XTPQueryIPOTickerRsp>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryIPOTickerRsp, "market", market);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryIPOTickerRsp, "ticker", ticker);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryIPOTickerRsp, "ticker_name", ticker_name);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryIPOTickerRsp, "price", price);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryIPOTickerRsp, "unit", unit);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryIPOTickerRsp, "qty_upper_limit", qty_upper_limit);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vnxtp, XTPQueryIPOTickerRsp, c);
module_vnxtp::objects.emplace("XTPQueryIPOTickerRsp", c);
}
void generate_class_XTPQueryIPOQuotaRsp(pybind11::object & parent)
{
pybind11::class_<XTPQueryIPOQuotaRsp> c(parent, "XTPQueryIPOQuotaRsp");
if constexpr (std::is_default_constructible_v<XTPQueryIPOQuotaRsp>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryIPOQuotaRsp, "market", market);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryIPOQuotaRsp, "quantity", quantity);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vnxtp, XTPQueryIPOQuotaRsp, c);
module_vnxtp::objects.emplace("XTPQueryIPOQuotaRsp", c);
}
void generate_class_XTPQueryOptionAuctionInfoReq(pybind11::object & parent)
{
pybind11::class_<XTPQueryOptionAuctionInfoReq> c(parent, "XTPQueryOptionAuctionInfoReq");
if constexpr (std::is_default_constructible_v<XTPQueryOptionAuctionInfoReq>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryOptionAuctionInfoReq, "market", market);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryOptionAuctionInfoReq, "ticker", ticker);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vnxtp, XTPQueryOptionAuctionInfoReq, c);
module_vnxtp::objects.emplace("XTPQueryOptionAuctionInfoReq", c);
}
void generate_class_XTPQueryOptionAuctionInfoRsp(pybind11::object & parent)
{
pybind11::class_<XTPQueryOptionAuctionInfoRsp> c(parent, "XTPQueryOptionAuctionInfoRsp");
if constexpr (std::is_default_constructible_v<XTPQueryOptionAuctionInfoRsp>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryOptionAuctionInfoRsp, "ticker", ticker);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryOptionAuctionInfoRsp, "security_id_source", security_id_source);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryOptionAuctionInfoRsp, "symbol", symbol);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryOptionAuctionInfoRsp, "contract_id", contract_id);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryOptionAuctionInfoRsp, "underlying_security_id", underlying_security_id);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryOptionAuctionInfoRsp, "underlying_security_id_source", underlying_security_id_source);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryOptionAuctionInfoRsp, "list_date", list_date);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryOptionAuctionInfoRsp, "last_trade_date", last_trade_date);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryOptionAuctionInfoRsp, "ticker_type", ticker_type);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryOptionAuctionInfoRsp, "day_trading", day_trading);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryOptionAuctionInfoRsp, "call_or_put", call_or_put);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryOptionAuctionInfoRsp, "delivery_day", delivery_day);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryOptionAuctionInfoRsp, "delivery_month", delivery_month);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryOptionAuctionInfoRsp, "exercise_type", exercise_type);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryOptionAuctionInfoRsp, "exercise_begin_date", exercise_begin_date);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryOptionAuctionInfoRsp, "exercise_end_date", exercise_end_date);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryOptionAuctionInfoRsp, "exercise_price", exercise_price);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryOptionAuctionInfoRsp, "qty_unit", qty_unit);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryOptionAuctionInfoRsp, "contract_unit", contract_unit);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryOptionAuctionInfoRsp, "contract_position", contract_position);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryOptionAuctionInfoRsp, "prev_close_price", prev_close_price);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryOptionAuctionInfoRsp, "prev_clearing_price", prev_clearing_price);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryOptionAuctionInfoRsp, "lmt_buy_max_qty", lmt_buy_max_qty);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryOptionAuctionInfoRsp, "lmt_buy_min_qty", lmt_buy_min_qty);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryOptionAuctionInfoRsp, "lmt_sell_max_qty", lmt_sell_max_qty);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryOptionAuctionInfoRsp, "lmt_sell_min_qty", lmt_sell_min_qty);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryOptionAuctionInfoRsp, "mkt_buy_max_qty", mkt_buy_max_qty);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryOptionAuctionInfoRsp, "mkt_buy_min_qty", mkt_buy_min_qty);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryOptionAuctionInfoRsp, "mkt_sell_max_qty", mkt_sell_max_qty);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryOptionAuctionInfoRsp, "mkt_sell_min_qty", mkt_sell_min_qty);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryOptionAuctionInfoRsp, "price_tick", price_tick);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryOptionAuctionInfoRsp, "upper_limit_price", upper_limit_price);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryOptionAuctionInfoRsp, "lower_limit_price", lower_limit_price);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryOptionAuctionInfoRsp, "sell_margin", sell_margin);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryOptionAuctionInfoRsp, "margin_ratio_param1", margin_ratio_param1);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryOptionAuctionInfoRsp, "margin_ratio_param2", margin_ratio_param2);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPQueryOptionAuctionInfoRsp, "unknown", unknown);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vnxtp, XTPQueryOptionAuctionInfoRsp, c);
module_vnxtp::objects.emplace("XTPQueryOptionAuctionInfoRsp", c);
}
void generate_class_XTPFundTransferReq(pybind11::object & parent)
{
pybind11::class_<XTPFundTransferReq> c(parent, "XTPFundTransferReq");
if constexpr (std::is_default_constructible_v<XTPFundTransferReq>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPFundTransferReq, "serial_id", serial_id);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPFundTransferReq, "fund_account", fund_account);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPFundTransferReq, "password", password);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPFundTransferReq, "amount", amount);
c.AUTOCXXPY_DEF_PROPERTY(tag_vnxtp, XTPFundTransferReq, "transfer_type", transfer_type);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vnxtp, XTPFundTransferReq, c);
module_vnxtp::objects.emplace("XTPFundTransferReq", c);
}
void generate_enum_XTP_LOG_LEVEL(pybind11::object & parent)
{
pybind11::enum_<XTP_LOG_LEVEL> e(parent, "XTP_LOG_LEVEL", pybind11::arithmetic());
e.value("XTP_LOG_LEVEL_FATAL", XTP_LOG_LEVEL::XTP_LOG_LEVEL_FATAL);
e.value("XTP_LOG_LEVEL_ERROR", XTP_LOG_LEVEL::XTP_LOG_LEVEL_ERROR);
e.value("XTP_LOG_LEVEL_WARNING", XTP_LOG_LEVEL::XTP_LOG_LEVEL_WARNING);
e.value("XTP_LOG_LEVEL_INFO", XTP_LOG_LEVEL::XTP_LOG_LEVEL_INFO);
e.value("XTP_LOG_LEVEL_DEBUG", XTP_LOG_LEVEL::XTP_LOG_LEVEL_DEBUG);
e.value("XTP_LOG_LEVEL_TRACE", XTP_LOG_LEVEL::XTP_LOG_LEVEL_TRACE);
e.export_values();
module_vnxtp::objects.emplace("XTP_LOG_LEVEL", e);
}
void generate_enum_XTP_PROTOCOL_TYPE(pybind11::object & parent)
{
pybind11::enum_<XTP_PROTOCOL_TYPE> e(parent, "XTP_PROTOCOL_TYPE", pybind11::arithmetic());
e.value("XTP_PROTOCOL_TCP", XTP_PROTOCOL_TYPE::XTP_PROTOCOL_TCP);
e.value("XTP_PROTOCOL_UDP", XTP_PROTOCOL_TYPE::XTP_PROTOCOL_UDP);
e.export_values();
module_vnxtp::objects.emplace("XTP_PROTOCOL_TYPE", e);
}
void generate_enum_XTP_EXCHANGE_TYPE(pybind11::object & parent)
{
pybind11::enum_<XTP_EXCHANGE_TYPE> e(parent, "XTP_EXCHANGE_TYPE", pybind11::arithmetic());
e.value("XTP_EXCHANGE_SH", XTP_EXCHANGE_TYPE::XTP_EXCHANGE_SH);
e.value("XTP_EXCHANGE_SZ", XTP_EXCHANGE_TYPE::XTP_EXCHANGE_SZ);
e.value("XTP_EXCHANGE_UNKNOWN", XTP_EXCHANGE_TYPE::XTP_EXCHANGE_UNKNOWN);
e.export_values();
module_vnxtp::objects.emplace("XTP_EXCHANGE_TYPE", e);
}
void generate_enum_XTP_MARKET_TYPE(pybind11::object & parent)
{
pybind11::enum_<XTP_MARKET_TYPE> e(parent, "XTP_MARKET_TYPE", pybind11::arithmetic());
e.value("XTP_MKT_INIT", XTP_MARKET_TYPE::XTP_MKT_INIT);
e.value("XTP_MKT_SZ_A", XTP_MARKET_TYPE::XTP_MKT_SZ_A);
e.value("XTP_MKT_SH_A", XTP_MARKET_TYPE::XTP_MKT_SH_A);
e.value("XTP_MKT_UNKNOWN", XTP_MARKET_TYPE::XTP_MKT_UNKNOWN);
e.export_values();
module_vnxtp::objects.emplace("XTP_MARKET_TYPE", e);
}
void generate_enum_XTP_PRICE_TYPE(pybind11::object & parent)
{
pybind11::enum_<XTP_PRICE_TYPE> e(parent, "XTP_PRICE_TYPE", pybind11::arithmetic());
e.value("XTP_PRICE_LIMIT", XTP_PRICE_TYPE::XTP_PRICE_LIMIT);
e.value("XTP_PRICE_BEST_OR_CANCEL", XTP_PRICE_TYPE::XTP_PRICE_BEST_OR_CANCEL);
e.value("XTP_PRICE_BEST5_OR_LIMIT", XTP_PRICE_TYPE::XTP_PRICE_BEST5_OR_LIMIT);
e.value("XTP_PRICE_BEST5_OR_CANCEL", XTP_PRICE_TYPE::XTP_PRICE_BEST5_OR_CANCEL);
e.value("XTP_PRICE_ALL_OR_CANCEL", XTP_PRICE_TYPE::XTP_PRICE_ALL_OR_CANCEL);
e.value("XTP_PRICE_FORWARD_BEST", XTP_PRICE_TYPE::XTP_PRICE_FORWARD_BEST);
e.value("XTP_PRICE_REVERSE_BEST_LIMIT", XTP_PRICE_TYPE::XTP_PRICE_REVERSE_BEST_LIMIT);
e.value("XTP_PRICE_LIMIT_OR_CANCEL", XTP_PRICE_TYPE::XTP_PRICE_LIMIT_OR_CANCEL);
e.value("XTP_PRICE_TYPE_UNKNOWN", XTP_PRICE_TYPE::XTP_PRICE_TYPE_UNKNOWN);
e.export_values();
module_vnxtp::objects.emplace("XTP_PRICE_TYPE", e);
}
void generate_enum_XTP_ORDER_ACTION_STATUS_TYPE(pybind11::object & parent)
{
pybind11::enum_<XTP_ORDER_ACTION_STATUS_TYPE> e(parent, "XTP_ORDER_ACTION_STATUS_TYPE", pybind11::arithmetic());
e.value("XTP_ORDER_ACTION_STATUS_SUBMITTED", XTP_ORDER_ACTION_STATUS_TYPE::XTP_ORDER_ACTION_STATUS_SUBMITTED);
e.value("XTP_ORDER_ACTION_STATUS_ACCEPTED", XTP_ORDER_ACTION_STATUS_TYPE::XTP_ORDER_ACTION_STATUS_ACCEPTED);
e.value("XTP_ORDER_ACTION_STATUS_REJECTED", XTP_ORDER_ACTION_STATUS_TYPE::XTP_ORDER_ACTION_STATUS_REJECTED);
e.export_values();
module_vnxtp::objects.emplace("XTP_ORDER_ACTION_STATUS_TYPE", e);
}
void generate_enum_XTP_ORDER_STATUS_TYPE(pybind11::object & parent)
{
pybind11::enum_<XTP_ORDER_STATUS_TYPE> e(parent, "XTP_ORDER_STATUS_TYPE", pybind11::arithmetic());
e.value("XTP_ORDER_STATUS_INIT", XTP_ORDER_STATUS_TYPE::XTP_ORDER_STATUS_INIT);
e.value("XTP_ORDER_STATUS_ALLTRADED", XTP_ORDER_STATUS_TYPE::XTP_ORDER_STATUS_ALLTRADED);
e.value("XTP_ORDER_STATUS_PARTTRADEDQUEUEING", XTP_ORDER_STATUS_TYPE::XTP_ORDER_STATUS_PARTTRADEDQUEUEING);
e.value("XTP_ORDER_STATUS_PARTTRADEDNOTQUEUEING", XTP_ORDER_STATUS_TYPE::XTP_ORDER_STATUS_PARTTRADEDNOTQUEUEING);
e.value("XTP_ORDER_STATUS_NOTRADEQUEUEING", XTP_ORDER_STATUS_TYPE::XTP_ORDER_STATUS_NOTRADEQUEUEING);
e.value("XTP_ORDER_STATUS_CANCELED", XTP_ORDER_STATUS_TYPE::XTP_ORDER_STATUS_CANCELED);
e.value("XTP_ORDER_STATUS_REJECTED", XTP_ORDER_STATUS_TYPE::XTP_ORDER_STATUS_REJECTED);
e.value("XTP_ORDER_STATUS_UNKNOWN", XTP_ORDER_STATUS_TYPE::XTP_ORDER_STATUS_UNKNOWN);
e.export_values();
module_vnxtp::objects.emplace("XTP_ORDER_STATUS_TYPE", e);
}
void generate_enum_XTP_ORDER_SUBMIT_STATUS_TYPE(pybind11::object & parent)
{
pybind11::enum_<XTP_ORDER_SUBMIT_STATUS_TYPE> e(parent, "XTP_ORDER_SUBMIT_STATUS_TYPE", pybind11::arithmetic());
e.value("XTP_ORDER_SUBMIT_STATUS_INSERT_SUBMITTED", XTP_ORDER_SUBMIT_STATUS_TYPE::XTP_ORDER_SUBMIT_STATUS_INSERT_SUBMITTED);
e.value("XTP_ORDER_SUBMIT_STATUS_INSERT_ACCEPTED", XTP_ORDER_SUBMIT_STATUS_TYPE::XTP_ORDER_SUBMIT_STATUS_INSERT_ACCEPTED);
e.value("XTP_ORDER_SUBMIT_STATUS_INSERT_REJECTED", XTP_ORDER_SUBMIT_STATUS_TYPE::XTP_ORDER_SUBMIT_STATUS_INSERT_REJECTED);
e.value("XTP_ORDER_SUBMIT_STATUS_CANCEL_SUBMITTED", XTP_ORDER_SUBMIT_STATUS_TYPE::XTP_ORDER_SUBMIT_STATUS_CANCEL_SUBMITTED);
e.value("XTP_ORDER_SUBMIT_STATUS_CANCEL_REJECTED", XTP_ORDER_SUBMIT_STATUS_TYPE::XTP_ORDER_SUBMIT_STATUS_CANCEL_REJECTED);
e.value("XTP_ORDER_SUBMIT_STATUS_CANCEL_ACCEPTED", XTP_ORDER_SUBMIT_STATUS_TYPE::XTP_ORDER_SUBMIT_STATUS_CANCEL_ACCEPTED);
e.export_values();
module_vnxtp::objects.emplace("XTP_ORDER_SUBMIT_STATUS_TYPE", e);
}
| 48,207 | 20,609 |
/*
Given a linked list, find and return the length of input LL recursively.
Input format :
Linked list elements (separated by space and terminated by -1)
Output format :
Length of LL
Sample Input :
3 4 5 2 6 1 9 -1
Sample Output :
7
*/
/**********
* Following is the Node class that is already written.
class Node{
public:
int data;
Node *next;
Node(int data){
this -> data = data;
this -> next = NULL;
}
};
*********/
#include <iostream>
using namespace std;
class Node{
public:
int data;
Node *next;
Node(int data){
this -> data = data;
this -> next = NULL;
}
};
Node* takeinput() {
int data;
cin >> data;
Node* head = NULL, *tail = NULL;
while(data != -1){
Node *newNode = new Node(data);
if(head == NULL) {
head = newNode;
tail = newNode;
}
else{
tail -> next = newNode;
tail = newNode;
}
cin >> data;
}
return head;
}
int length(Node *head) {
/* Don't write main().
* Don't read input, it is passed as function argument.
* Return output and don't print it.
* Taking input is handled automatically.
*/
if(head==NULL)
return 0;
int ans=length(head->next);
return ans+1;
}
void print(Node *head) {
Node *temp = head;
while(temp != NULL) {
cout << temp -> data << " ";
temp = temp -> next;
}
cout<<endl;
}
int main() {
Node *head = takeinput();
int pos;
cin >> pos;
cout << length(head);
return 0;
}
| 1,631 | 536 |
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <vector>
using namespace std;
const int INF = 1e9;
const int MAX_N = 5e5 + 5;
const int MAX_P = 21;
int f[MAX_N][MAX_P];
int next_right[MAX_N];
int n, m;
int main() {
cin >> n >> m;
for (int i = 0; i < n; ++i) {
int l, r;
cin >> l >> r;
next_right[l] = max(next_right[l], r);
}
for (int i = 1; i < MAX_N; ++i) {
next_right[i] = max(next_right[i], i);
next_right[i] = max(next_right[i], next_right[i - 1]);
f[i][0] = next_right[i];
}
f[0][0] = next_right[0];
for (int j = 1; j < MAX_P; ++j) {
for (int i = 0; i < MAX_N; ++i) {
f[i][j] = f[f[i][j - 1]][j - 1];
}
}
for (int i = 0; i < m; ++i) {
int x, y;
cin >> x >> y;
int cur_p = MAX_P - 1;
// cout << "x: " << x << ", y: " << y << endl;
int ans = 0;
for (int j = MAX_P - 1; j >= 0; --j) {
if (f[x][j] < y) {
// cout << "f[" << x << "][" << j << "] = " << f[x][j] << endl;
x = f[x][j];
ans += 1 << j;
}
}
++ans;
if (ans <= n) {
cout << ans << "\n";
} else {
cout << "-1\n";
}
}
return 0;
}
| 1,187 | 570 |
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
#include "extern/beatsaber-hook/shared/utils/byref.hpp"
// Including type: StandaloneMonobehavior
#include "GlobalNamespace/StandaloneMonobehavior.hpp"
// Including type: IMultiplayerSessionManager
#include "GlobalNamespace/IMultiplayerSessionManager.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: GlobalNamespace
namespace GlobalNamespace {
// Forward declaring type: IConnectionInitParams`1<T>
template<typename T>
class IConnectionInitParams_1;
// Forward declaring type: NetworkPacketSerializer`2<TType, TData>
template<typename TType, typename TData>
class NetworkPacketSerializer_2;
// Forward declaring type: IConnectedPlayer
class IConnectedPlayer;
// Forward declaring type: SynchronizedActionQueue
class SynchronizedActionQueue;
// Forward declaring type: ConnectedPlayerManager
class ConnectedPlayerManager;
// Forward declaring type: INetworkPacketSubSerializer`1<TData>
template<typename TData>
class INetworkPacketSubSerializer_1;
// Forward declaring type: IConnectionManager
class IConnectionManager;
// Skipping declaration: SessionType because it is already included!
// Forward declaring type: UpdateConnectionStateReason
struct UpdateConnectionStateReason;
}
// Forward declaring namespace: System::Collections::Generic
namespace System::Collections::Generic {
// Forward declaring type: Queue`1<T>
template<typename T>
class Queue_1;
// Forward declaring type: List`1<T>
template<typename T>
class List_1;
// Forward declaring type: HashSet`1<T>
template<typename T>
class HashSet_1;
// Forward declaring type: IReadOnlyList`1<T>
template<typename T>
class IReadOnlyList_1;
}
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Action
class Action;
// Forward declaring type: Action`1<T>
template<typename T>
class Action_1;
// Forward declaring type: String
class String;
// Forward declaring type: Action`2<T1, T2>
template<typename T1, typename T2>
class Action_2;
// Forward declaring type: Func`1<TResult>
template<typename TResult>
class Func_1;
}
// Forward declaring namespace: LiteNetLib::Utils
namespace LiteNetLib::Utils {
// Forward declaring type: INetSerializable
class INetSerializable;
}
// Completed forward declares
// Type namespace:
namespace GlobalNamespace {
// Size: 0xB8
#pragma pack(push, 1)
// Autogenerated type: MultiplayerSessionManager
// [TokenAttribute] Offset: FFFFFFFF
class MultiplayerSessionManager : public GlobalNamespace::StandaloneMonobehavior/*, public GlobalNamespace::IMultiplayerSessionManager*/ {
public:
// Writing base type padding for base size: 0x2C to desired offset: 0x30
char ___base_padding[0x4] = {};
// Nested type: GlobalNamespace::MultiplayerSessionManager::SessionType
struct SessionType;
// Nested type: GlobalNamespace::MultiplayerSessionManager::ConnectionState
struct ConnectionState;
// Nested type: GlobalNamespace::MultiplayerSessionManager::$$c__DisplayClass97_0
class $$c__DisplayClass97_0;
// Nested type: GlobalNamespace::MultiplayerSessionManager::$$c
class $$c;
// Size: 0x4
#pragma pack(push, 1)
// Autogenerated type: MultiplayerSessionManager/SessionType
// [TokenAttribute] Offset: FFFFFFFF
struct SessionType/*, public System::Enum*/ {
public:
// public System.Int32 value__
// Size: 0x4
// Offset: 0x0
int value;
// Field size check
static_assert(sizeof(int) == 0x4);
// Creating value type constructor for type: SessionType
constexpr SessionType(int value_ = {}) noexcept : value{value_} {}
// Creating interface conversion operator: operator System::Enum
operator System::Enum() noexcept {
return *reinterpret_cast<System::Enum*>(this);
}
// Creating conversion operator: operator int
constexpr operator int() const noexcept {
return value;
}
// static field const value: static public MultiplayerSessionManager/SessionType Player
static constexpr const int Player = 0;
// Get static field: static public MultiplayerSessionManager/SessionType Player
static GlobalNamespace::MultiplayerSessionManager::SessionType _get_Player();
// Set static field: static public MultiplayerSessionManager/SessionType Player
static void _set_Player(GlobalNamespace::MultiplayerSessionManager::SessionType value);
// static field const value: static public MultiplayerSessionManager/SessionType Spectator
static constexpr const int Spectator = 1;
// Get static field: static public MultiplayerSessionManager/SessionType Spectator
static GlobalNamespace::MultiplayerSessionManager::SessionType _get_Spectator();
// Set static field: static public MultiplayerSessionManager/SessionType Spectator
static void _set_Spectator(GlobalNamespace::MultiplayerSessionManager::SessionType value);
// static field const value: static public MultiplayerSessionManager/SessionType DedicatedServer
static constexpr const int DedicatedServer = 2;
// Get static field: static public MultiplayerSessionManager/SessionType DedicatedServer
static GlobalNamespace::MultiplayerSessionManager::SessionType _get_DedicatedServer();
// Set static field: static public MultiplayerSessionManager/SessionType DedicatedServer
static void _set_DedicatedServer(GlobalNamespace::MultiplayerSessionManager::SessionType value);
// Get instance field reference: public System.Int32 value__
int& dyn_value__();
}; // MultiplayerSessionManager/SessionType
#pragma pack(pop)
static check_size<sizeof(MultiplayerSessionManager::SessionType), 0 + sizeof(int)> __GlobalNamespace_MultiplayerSessionManager_SessionTypeSizeCheck;
static_assert(sizeof(MultiplayerSessionManager::SessionType) == 0x4);
// Size: 0x4
#pragma pack(push, 1)
// Autogenerated type: MultiplayerSessionManager/ConnectionState
// [TokenAttribute] Offset: FFFFFFFF
struct ConnectionState/*, public System::Enum*/ {
public:
// public System.Int32 value__
// Size: 0x4
// Offset: 0x0
int value;
// Field size check
static_assert(sizeof(int) == 0x4);
// Creating value type constructor for type: ConnectionState
constexpr ConnectionState(int value_ = {}) noexcept : value{value_} {}
// Creating interface conversion operator: operator System::Enum
operator System::Enum() noexcept {
return *reinterpret_cast<System::Enum*>(this);
}
// Creating conversion operator: operator int
constexpr operator int() const noexcept {
return value;
}
// static field const value: static public MultiplayerSessionManager/ConnectionState Disconnected
static constexpr const int Disconnected = 0;
// Get static field: static public MultiplayerSessionManager/ConnectionState Disconnected
static GlobalNamespace::MultiplayerSessionManager::ConnectionState _get_Disconnected();
// Set static field: static public MultiplayerSessionManager/ConnectionState Disconnected
static void _set_Disconnected(GlobalNamespace::MultiplayerSessionManager::ConnectionState value);
// static field const value: static public MultiplayerSessionManager/ConnectionState Connecting
static constexpr const int Connecting = 1;
// Get static field: static public MultiplayerSessionManager/ConnectionState Connecting
static GlobalNamespace::MultiplayerSessionManager::ConnectionState _get_Connecting();
// Set static field: static public MultiplayerSessionManager/ConnectionState Connecting
static void _set_Connecting(GlobalNamespace::MultiplayerSessionManager::ConnectionState value);
// static field const value: static public MultiplayerSessionManager/ConnectionState Connected
static constexpr const int Connected = 2;
// Get static field: static public MultiplayerSessionManager/ConnectionState Connected
static GlobalNamespace::MultiplayerSessionManager::ConnectionState _get_Connected();
// Set static field: static public MultiplayerSessionManager/ConnectionState Connected
static void _set_Connected(GlobalNamespace::MultiplayerSessionManager::ConnectionState value);
// static field const value: static public MultiplayerSessionManager/ConnectionState Disconnecting
static constexpr const int Disconnecting = 3;
// Get static field: static public MultiplayerSessionManager/ConnectionState Disconnecting
static GlobalNamespace::MultiplayerSessionManager::ConnectionState _get_Disconnecting();
// Set static field: static public MultiplayerSessionManager/ConnectionState Disconnecting
static void _set_Disconnecting(GlobalNamespace::MultiplayerSessionManager::ConnectionState value);
// Get instance field reference: public System.Int32 value__
int& dyn_value__();
}; // MultiplayerSessionManager/ConnectionState
#pragma pack(pop)
static check_size<sizeof(MultiplayerSessionManager::ConnectionState), 0 + sizeof(int)> __GlobalNamespace_MultiplayerSessionManager_ConnectionStateSizeCheck;
static_assert(sizeof(MultiplayerSessionManager::ConnectionState) == 0x4);
// private readonly NetworkPacketSerializer`2<MultiplayerSessionManager/MessageType,IConnectedPlayer> _packetSerializer
// Size: 0x8
// Offset: 0x30
GlobalNamespace::NetworkPacketSerializer_2<GlobalNamespace::MultiplayerSessionManager_MessageType, GlobalNamespace::IConnectedPlayer*>* packetSerializer;
// Field size check
static_assert(sizeof(GlobalNamespace::NetworkPacketSerializer_2<GlobalNamespace::MultiplayerSessionManager_MessageType, GlobalNamespace::IConnectedPlayer*>*) == 0x8);
// private readonly System.Collections.Generic.List`1<IConnectedPlayer> _connectedPlayers
// Size: 0x8
// Offset: 0x38
System::Collections::Generic::List_1<GlobalNamespace::IConnectedPlayer*>* connectedPlayers;
// Field size check
static_assert(sizeof(System::Collections::Generic::List_1<GlobalNamespace::IConnectedPlayer*>*) == 0x8);
// private readonly System.Collections.Generic.HashSet`1<System.String> _localPlayerState
// Size: 0x8
// Offset: 0x40
System::Collections::Generic::HashSet_1<::Il2CppString*>* localPlayerState;
// Field size check
static_assert(sizeof(System::Collections::Generic::HashSet_1<::Il2CppString*>*) == 0x8);
// private readonly SynchronizedActionQueue _synchronizedActionQueue
// Size: 0x8
// Offset: 0x48
GlobalNamespace::SynchronizedActionQueue* synchronizedActionQueue;
// Field size check
static_assert(sizeof(GlobalNamespace::SynchronizedActionQueue*) == 0x8);
// private System.Int32 _maxPlayerCount
// Size: 0x4
// Offset: 0x50
int maxPlayerCount;
// Field size check
static_assert(sizeof(int) == 0x4);
// private MultiplayerSessionManager/ConnectionState _connectionState
// Size: 0x4
// Offset: 0x54
GlobalNamespace::MultiplayerSessionManager::ConnectionState connectionState;
// Field size check
static_assert(sizeof(GlobalNamespace::MultiplayerSessionManager::ConnectionState) == 0x4);
// private readonly System.Collections.Generic.Queue`1<System.Int32> _freeSortIndices
// Size: 0x8
// Offset: 0x58
System::Collections::Generic::Queue_1<int>* freeSortIndices;
// Field size check
static_assert(sizeof(System::Collections::Generic::Queue_1<int>*) == 0x8);
// private System.Action connectedEvent
// Size: 0x8
// Offset: 0x60
System::Action* connectedEvent;
// Field size check
static_assert(sizeof(System::Action*) == 0x8);
// private System.Action`1<ConnectionFailedReason> connectionFailedEvent
// Size: 0x8
// Offset: 0x68
System::Action_1<GlobalNamespace::ConnectionFailedReason>* connectionFailedEvent;
// Field size check
static_assert(sizeof(System::Action_1<GlobalNamespace::ConnectionFailedReason>*) == 0x8);
// private System.Action`1<IConnectedPlayer> playerConnectedEvent
// Size: 0x8
// Offset: 0x70
System::Action_1<GlobalNamespace::IConnectedPlayer*>* playerConnectedEvent;
// Field size check
static_assert(sizeof(System::Action_1<GlobalNamespace::IConnectedPlayer*>*) == 0x8);
// private System.Action`1<IConnectedPlayer> playerDisconnectedEvent
// Size: 0x8
// Offset: 0x78
System::Action_1<GlobalNamespace::IConnectedPlayer*>* playerDisconnectedEvent;
// Field size check
static_assert(sizeof(System::Action_1<GlobalNamespace::IConnectedPlayer*>*) == 0x8);
// private System.Action`1<IConnectedPlayer> playerAvatarChangedEvent
// Size: 0x8
// Offset: 0x80
System::Action_1<GlobalNamespace::IConnectedPlayer*>* playerAvatarChangedEvent;
// Field size check
static_assert(sizeof(System::Action_1<GlobalNamespace::IConnectedPlayer*>*) == 0x8);
// private System.Action`1<IConnectedPlayer> playerStateChangedEvent
// Size: 0x8
// Offset: 0x88
System::Action_1<GlobalNamespace::IConnectedPlayer*>* playerStateChangedEvent;
// Field size check
static_assert(sizeof(System::Action_1<GlobalNamespace::IConnectedPlayer*>*) == 0x8);
// private System.Action`1<IConnectedPlayer> connectionOwnerStateChangedEvent
// Size: 0x8
// Offset: 0x90
System::Action_1<GlobalNamespace::IConnectedPlayer*>* connectionOwnerStateChangedEvent;
// Field size check
static_assert(sizeof(System::Action_1<GlobalNamespace::IConnectedPlayer*>*) == 0x8);
// private System.Action`1<DisconnectedReason> disconnectedEvent
// Size: 0x8
// Offset: 0x98
System::Action_1<GlobalNamespace::DisconnectedReason>* disconnectedEvent;
// Field size check
static_assert(sizeof(System::Action_1<GlobalNamespace::DisconnectedReason>*) == 0x8);
// private IConnectedPlayer <connectionOwner>k__BackingField
// Size: 0x8
// Offset: 0xA0
GlobalNamespace::IConnectedPlayer* connectionOwner;
// Field size check
static_assert(sizeof(GlobalNamespace::IConnectedPlayer*) == 0x8);
// private System.Boolean _exclusiveConnectedPlayerManager
// Size: 0x1
// Offset: 0xA8
bool exclusiveConnectedPlayerManager;
// Field size check
static_assert(sizeof(bool) == 0x1);
// Padding between fields: exclusiveConnectedPlayerManager and: connectedPlayerManager
char __padding16[0x7] = {};
// private ConnectedPlayerManager _connectedPlayerManager
// Size: 0x8
// Offset: 0xB0
GlobalNamespace::ConnectedPlayerManager* connectedPlayerManager;
// Field size check
static_assert(sizeof(GlobalNamespace::ConnectedPlayerManager*) == 0x8);
// Creating value type constructor for type: MultiplayerSessionManager
MultiplayerSessionManager(GlobalNamespace::NetworkPacketSerializer_2<GlobalNamespace::MultiplayerSessionManager_MessageType, GlobalNamespace::IConnectedPlayer*>* packetSerializer_ = {}, System::Collections::Generic::List_1<GlobalNamespace::IConnectedPlayer*>* connectedPlayers_ = {}, System::Collections::Generic::HashSet_1<::Il2CppString*>* localPlayerState_ = {}, GlobalNamespace::SynchronizedActionQueue* synchronizedActionQueue_ = {}, int maxPlayerCount_ = {}, GlobalNamespace::MultiplayerSessionManager::ConnectionState connectionState_ = {}, System::Collections::Generic::Queue_1<int>* freeSortIndices_ = {}, System::Action* connectedEvent_ = {}, System::Action_1<GlobalNamespace::ConnectionFailedReason>* connectionFailedEvent_ = {}, System::Action_1<GlobalNamespace::IConnectedPlayer*>* playerConnectedEvent_ = {}, System::Action_1<GlobalNamespace::IConnectedPlayer*>* playerDisconnectedEvent_ = {}, System::Action_1<GlobalNamespace::IConnectedPlayer*>* playerAvatarChangedEvent_ = {}, System::Action_1<GlobalNamespace::IConnectedPlayer*>* playerStateChangedEvent_ = {}, System::Action_1<GlobalNamespace::IConnectedPlayer*>* connectionOwnerStateChangedEvent_ = {}, System::Action_1<GlobalNamespace::DisconnectedReason>* disconnectedEvent_ = {}, GlobalNamespace::IConnectedPlayer* connectionOwner_ = {}, bool exclusiveConnectedPlayerManager_ = {}, GlobalNamespace::ConnectedPlayerManager* connectedPlayerManager_ = {}) noexcept : packetSerializer{packetSerializer_}, connectedPlayers{connectedPlayers_}, localPlayerState{localPlayerState_}, synchronizedActionQueue{synchronizedActionQueue_}, maxPlayerCount{maxPlayerCount_}, connectionState{connectionState_}, freeSortIndices{freeSortIndices_}, connectedEvent{connectedEvent_}, connectionFailedEvent{connectionFailedEvent_}, playerConnectedEvent{playerConnectedEvent_}, playerDisconnectedEvent{playerDisconnectedEvent_}, playerAvatarChangedEvent{playerAvatarChangedEvent_}, playerStateChangedEvent{playerStateChangedEvent_}, connectionOwnerStateChangedEvent{connectionOwnerStateChangedEvent_}, disconnectedEvent{disconnectedEvent_}, connectionOwner{connectionOwner_}, exclusiveConnectedPlayerManager{exclusiveConnectedPlayerManager_}, connectedPlayerManager{connectedPlayerManager_} {}
// Creating interface conversion operator: operator GlobalNamespace::IMultiplayerSessionManager
operator GlobalNamespace::IMultiplayerSessionManager() noexcept {
return *reinterpret_cast<GlobalNamespace::IMultiplayerSessionManager*>(this);
}
// static field const value: static private System.String kMultiplayerSessionState
static constexpr const char* kMultiplayerSessionState = "multiplayer_session";
// Get static field: static private System.String kMultiplayerSessionState
static ::Il2CppString* _get_kMultiplayerSessionState();
// Set static field: static private System.String kMultiplayerSessionState
static void _set_kMultiplayerSessionState(::Il2CppString* value);
// Get instance field reference: private readonly NetworkPacketSerializer`2<MultiplayerSessionManager/MessageType,IConnectedPlayer> _packetSerializer
GlobalNamespace::NetworkPacketSerializer_2<GlobalNamespace::MultiplayerSessionManager_MessageType, GlobalNamespace::IConnectedPlayer*>*& dyn__packetSerializer();
// Get instance field reference: private readonly System.Collections.Generic.List`1<IConnectedPlayer> _connectedPlayers
System::Collections::Generic::List_1<GlobalNamespace::IConnectedPlayer*>*& dyn__connectedPlayers();
// Get instance field reference: private readonly System.Collections.Generic.HashSet`1<System.String> _localPlayerState
System::Collections::Generic::HashSet_1<::Il2CppString*>*& dyn__localPlayerState();
// Get instance field reference: private readonly SynchronizedActionQueue _synchronizedActionQueue
GlobalNamespace::SynchronizedActionQueue*& dyn__synchronizedActionQueue();
// Get instance field reference: private System.Int32 _maxPlayerCount
int& dyn__maxPlayerCount();
// Get instance field reference: private MultiplayerSessionManager/ConnectionState _connectionState
GlobalNamespace::MultiplayerSessionManager::ConnectionState& dyn__connectionState();
// Get instance field reference: private readonly System.Collections.Generic.Queue`1<System.Int32> _freeSortIndices
System::Collections::Generic::Queue_1<int>*& dyn__freeSortIndices();
// Get instance field reference: private System.Action connectedEvent
System::Action*& dyn_connectedEvent();
// Get instance field reference: private System.Action`1<ConnectionFailedReason> connectionFailedEvent
System::Action_1<GlobalNamespace::ConnectionFailedReason>*& dyn_connectionFailedEvent();
// Get instance field reference: private System.Action`1<IConnectedPlayer> playerConnectedEvent
System::Action_1<GlobalNamespace::IConnectedPlayer*>*& dyn_playerConnectedEvent();
// Get instance field reference: private System.Action`1<IConnectedPlayer> playerDisconnectedEvent
System::Action_1<GlobalNamespace::IConnectedPlayer*>*& dyn_playerDisconnectedEvent();
// Get instance field reference: private System.Action`1<IConnectedPlayer> playerAvatarChangedEvent
System::Action_1<GlobalNamespace::IConnectedPlayer*>*& dyn_playerAvatarChangedEvent();
// Get instance field reference: private System.Action`1<IConnectedPlayer> playerStateChangedEvent
System::Action_1<GlobalNamespace::IConnectedPlayer*>*& dyn_playerStateChangedEvent();
// Get instance field reference: private System.Action`1<IConnectedPlayer> connectionOwnerStateChangedEvent
System::Action_1<GlobalNamespace::IConnectedPlayer*>*& dyn_connectionOwnerStateChangedEvent();
// Get instance field reference: private System.Action`1<DisconnectedReason> disconnectedEvent
System::Action_1<GlobalNamespace::DisconnectedReason>*& dyn_disconnectedEvent();
// Get instance field reference: private IConnectedPlayer <connectionOwner>k__BackingField
GlobalNamespace::IConnectedPlayer*& dyn_$connectionOwner$k__BackingField();
// Get instance field reference: private System.Boolean _exclusiveConnectedPlayerManager
bool& dyn__exclusiveConnectedPlayerManager();
// Get instance field reference: private ConnectedPlayerManager _connectedPlayerManager
GlobalNamespace::ConnectedPlayerManager*& dyn__connectedPlayerManager();
// public System.Boolean get_isConnectionOwner()
// Offset: 0x16F1FCC
bool get_isConnectionOwner();
// public IConnectedPlayer get_connectionOwner()
// Offset: 0x16F1FE4
GlobalNamespace::IConnectedPlayer* get_connectionOwner();
// private System.Void set_connectionOwner(IConnectedPlayer value)
// Offset: 0x16F1FEC
void set_connectionOwner(GlobalNamespace::IConnectedPlayer* value);
// public System.Boolean get_isSpectating()
// Offset: 0x16F1FF4
bool get_isSpectating();
// public System.Boolean get_isConnectingOrConnected()
// Offset: 0x16F20D0
bool get_isConnectingOrConnected();
// public System.Boolean get_isConnected()
// Offset: 0x16F20F4
bool get_isConnected();
// public System.Boolean get_isConnecting()
// Offset: 0x16F20E4
bool get_isConnecting();
// public System.Boolean get_isDisconnecting()
// Offset: 0x16F2104
bool get_isDisconnecting();
// public System.Collections.Generic.IReadOnlyList`1<IConnectedPlayer> get_connectedPlayers()
// Offset: 0x16F2114
System::Collections::Generic::IReadOnlyList_1<GlobalNamespace::IConnectedPlayer*>* get_connectedPlayers();
// public System.Int32 get_connectedPlayerCount()
// Offset: 0x16F211C
int get_connectedPlayerCount();
// public System.Single get_syncTime()
// Offset: 0x16F216C
float get_syncTime();
// public System.Boolean get_isSyncTimeInitialized()
// Offset: 0x16F2184
bool get_isSyncTimeInitialized();
// public System.Single get_syncTimeDelay()
// Offset: 0x16F2198
float get_syncTimeDelay();
// public IConnectedPlayer get_localPlayer()
// Offset: 0x16F21B0
GlobalNamespace::IConnectedPlayer* get_localPlayer();
// public ConnectedPlayerManager get_connectedPlayerManager()
// Offset: 0x16F21C8
GlobalNamespace::ConnectedPlayerManager* get_connectedPlayerManager();
// public System.Int32 get_maxPlayerCount()
// Offset: 0x16F21D0
int get_maxPlayerCount();
// public System.Void add_connectedEvent(System.Action value)
// Offset: 0x16F158C
void add_connectedEvent(System::Action* value);
// public System.Void remove_connectedEvent(System.Action value)
// Offset: 0x16F1630
void remove_connectedEvent(System::Action* value);
// public System.Void add_connectionFailedEvent(System.Action`1<ConnectionFailedReason> value)
// Offset: 0x16F16D4
void add_connectionFailedEvent(System::Action_1<GlobalNamespace::ConnectionFailedReason>* value);
// public System.Void remove_connectionFailedEvent(System.Action`1<ConnectionFailedReason> value)
// Offset: 0x16F1778
void remove_connectionFailedEvent(System::Action_1<GlobalNamespace::ConnectionFailedReason>* value);
// public System.Void add_playerConnectedEvent(System.Action`1<IConnectedPlayer> value)
// Offset: 0x16F181C
void add_playerConnectedEvent(System::Action_1<GlobalNamespace::IConnectedPlayer*>* value);
// public System.Void remove_playerConnectedEvent(System.Action`1<IConnectedPlayer> value)
// Offset: 0x16F18C0
void remove_playerConnectedEvent(System::Action_1<GlobalNamespace::IConnectedPlayer*>* value);
// public System.Void add_playerDisconnectedEvent(System.Action`1<IConnectedPlayer> value)
// Offset: 0x16F1964
void add_playerDisconnectedEvent(System::Action_1<GlobalNamespace::IConnectedPlayer*>* value);
// public System.Void remove_playerDisconnectedEvent(System.Action`1<IConnectedPlayer> value)
// Offset: 0x16F1A08
void remove_playerDisconnectedEvent(System::Action_1<GlobalNamespace::IConnectedPlayer*>* value);
// public System.Void add_playerAvatarChangedEvent(System.Action`1<IConnectedPlayer> value)
// Offset: 0x16F1AAC
void add_playerAvatarChangedEvent(System::Action_1<GlobalNamespace::IConnectedPlayer*>* value);
// public System.Void remove_playerAvatarChangedEvent(System.Action`1<IConnectedPlayer> value)
// Offset: 0x16F1B50
void remove_playerAvatarChangedEvent(System::Action_1<GlobalNamespace::IConnectedPlayer*>* value);
// public System.Void add_playerStateChangedEvent(System.Action`1<IConnectedPlayer> value)
// Offset: 0x16F1BF4
void add_playerStateChangedEvent(System::Action_1<GlobalNamespace::IConnectedPlayer*>* value);
// public System.Void remove_playerStateChangedEvent(System.Action`1<IConnectedPlayer> value)
// Offset: 0x16F1C98
void remove_playerStateChangedEvent(System::Action_1<GlobalNamespace::IConnectedPlayer*>* value);
// public System.Void add_connectionOwnerStateChangedEvent(System.Action`1<IConnectedPlayer> value)
// Offset: 0x16F1D3C
void add_connectionOwnerStateChangedEvent(System::Action_1<GlobalNamespace::IConnectedPlayer*>* value);
// public System.Void remove_connectionOwnerStateChangedEvent(System.Action`1<IConnectedPlayer> value)
// Offset: 0x16F1DE0
void remove_connectionOwnerStateChangedEvent(System::Action_1<GlobalNamespace::IConnectedPlayer*>* value);
// public System.Void add_disconnectedEvent(System.Action`1<DisconnectedReason> value)
// Offset: 0x16F1E84
void add_disconnectedEvent(System::Action_1<GlobalNamespace::DisconnectedReason>* value);
// public System.Void remove_disconnectedEvent(System.Action`1<DisconnectedReason> value)
// Offset: 0x16F1F28
void remove_disconnectedEvent(System::Action_1<GlobalNamespace::DisconnectedReason>* value);
// public System.Void RegisterSerializer(MultiplayerSessionManager/MessageType serializerType, INetworkPacketSubSerializer`1<IConnectedPlayer> subSerializer)
// Offset: 0x16F2BA4
void RegisterSerializer(GlobalNamespace::MultiplayerSessionManager_MessageType serializerType, GlobalNamespace::INetworkPacketSubSerializer_1<GlobalNamespace::IConnectedPlayer*>* subSerializer);
// public System.Void UnregisterSerializer(MultiplayerSessionManager/MessageType serializerType, INetworkPacketSubSerializer`1<IConnectedPlayer> subSerializer)
// Offset: 0x16F2C14
void UnregisterSerializer(GlobalNamespace::MultiplayerSessionManager_MessageType serializerType, GlobalNamespace::INetworkPacketSubSerializer_1<GlobalNamespace::IConnectedPlayer*>* subSerializer);
// public System.Void RegisterCallback(MultiplayerSessionManager/MessageType serializerType, System.Action`2<T,IConnectedPlayer> callback, System.Func`1<T> constructor)
// Offset: 0xFFFFFFFF
template<class T>
void RegisterCallback(GlobalNamespace::MultiplayerSessionManager_MessageType serializerType, System::Action_2<T, GlobalNamespace::IConnectedPlayer*>* callback, System::Func_1<T>* constructor) {
static_assert(std::is_base_of_v<LiteNetLib::Utils::INetSerializable, std::remove_pointer_t<T>>);
static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::MultiplayerSessionManager::RegisterCallback");
auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "RegisterCallback", std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T>::get()}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(serializerType), ::il2cpp_utils::ExtractType(callback), ::il2cpp_utils::ExtractType(constructor)})));
auto* ___generic__method = THROW_UNLESS(::il2cpp_utils::MakeGenericMethod(___internal__method, std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T>::get()}));
auto ___instance_arg = this;
::il2cpp_utils::RunMethodThrow<void, false>(___instance_arg, ___generic__method, serializerType, callback, constructor);
}
// public System.Void UnregisterCallback(MultiplayerSessionManager/MessageType serializerType)
// Offset: 0xFFFFFFFF
template<class T>
void UnregisterCallback(GlobalNamespace::MultiplayerSessionManager_MessageType serializerType) {
static_assert(std::is_base_of_v<LiteNetLib::Utils::INetSerializable, std::remove_pointer_t<T>>);
static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::MultiplayerSessionManager::UnregisterCallback");
auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "UnregisterCallback", std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T>::get()}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(serializerType)})));
auto* ___generic__method = THROW_UNLESS(::il2cpp_utils::MakeGenericMethod(___internal__method, std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T>::get()}));
auto ___instance_arg = this;
::il2cpp_utils::RunMethodThrow<void, false>(___instance_arg, ___generic__method, serializerType);
}
// public System.Void StartSession(MultiplayerSessionManager/SessionType sessionType, T connectionManager, IConnectionInitParams`1<T> initParams)
// Offset: 0xFFFFFFFF
template<class T>
void StartSession(GlobalNamespace::MultiplayerSessionManager::SessionType sessionType, T connectionManager, GlobalNamespace::IConnectionInitParams_1<T>* initParams) {
static_assert(std::is_base_of_v<GlobalNamespace::IConnectionManager, std::remove_pointer_t<T>>);
static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::MultiplayerSessionManager::StartSession");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "StartSession", std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T>::get()}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(sessionType), ::il2cpp_utils::ExtractType(connectionManager), ::il2cpp_utils::ExtractType(initParams)})));
static auto* ___generic__method = THROW_UNLESS(::il2cpp_utils::MakeGenericMethod(___internal__method, std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T>::get()}));
auto ___instance_arg = this;
::il2cpp_utils::RunMethodThrow<void, false>(___instance_arg, ___generic__method, sessionType, connectionManager, initParams);
}
// public System.Void StartSession(ConnectedPlayerManager connectedPlayerManager)
// Offset: 0x16F2C84
void StartSession(GlobalNamespace::ConnectedPlayerManager* connectedPlayerManager);
// public System.Void SetMaxPlayerCount(System.Int32 maxPlayerCount)
// Offset: 0x16F310C
void SetMaxPlayerCount(int maxPlayerCount);
// private System.Void InitInternal(MultiplayerSessionManager/SessionType sessionType)
// Offset: 0x16F2CD0
void InitInternal(GlobalNamespace::MultiplayerSessionManager::SessionType sessionType);
// public System.Void EndSession()
// Offset: 0x16F2788
void EndSession();
// public System.Void Disconnect()
// Offset: 0x16F3114
void Disconnect();
// public System.Void Send(T message)
// Offset: 0xFFFFFFFF
template<class T>
void Send(T message) {
static_assert(std::is_base_of_v<LiteNetLib::Utils::INetSerializable, std::remove_pointer_t<T>>);
static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::MultiplayerSessionManager::Send");
auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Send", std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T>::get()}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(message)})));
auto* ___generic__method = THROW_UNLESS(::il2cpp_utils::MakeGenericMethod(___internal__method, std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T>::get()}));
auto ___instance_arg = this;
::il2cpp_utils::RunMethodThrow<void, false>(___instance_arg, ___generic__method, message);
}
// public System.Void SendUnreliable(T message)
// Offset: 0xFFFFFFFF
template<class T>
void SendUnreliable(T message) {
static_assert(std::is_base_of_v<LiteNetLib::Utils::INetSerializable, std::remove_pointer_t<T>>);
static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::MultiplayerSessionManager::SendUnreliable");
auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "SendUnreliable", std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T>::get()}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(message)})));
auto* ___generic__method = THROW_UNLESS(::il2cpp_utils::MakeGenericMethod(___internal__method, std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T>::get()}));
auto ___instance_arg = this;
::il2cpp_utils::RunMethodThrow<void, false>(___instance_arg, ___generic__method, message);
}
// public System.Void PerformAtSyncTime(System.Single syncTime, System.Action action)
// Offset: 0x16F317C
void PerformAtSyncTime(float syncTime, System::Action* action);
// private System.Void UpdateSynchronizedActions()
// Offset: 0x16F2314
void UpdateSynchronizedActions();
// private System.Void HandleReinitialized()
// Offset: 0x16F3398
void HandleReinitialized();
// private System.Void HandleConnected()
// Offset: 0x16F33A8
void HandleConnected();
// private System.Void HandleDisconnected(DisconnectedReason disconnectedReason)
// Offset: 0x16F33B8
void HandleDisconnected(GlobalNamespace::DisconnectedReason disconnectedReason);
// private System.Void HandleConnectionFailed(ConnectionFailedReason reason)
// Offset: 0x16F33C8
void HandleConnectionFailed(GlobalNamespace::ConnectionFailedReason reason);
// private System.Void HandleSyncTimeInitialized()
// Offset: 0x16F33D8
void HandleSyncTimeInitialized();
// private System.Void HandlePlayerConnected(IConnectedPlayer player)
// Offset: 0x16F33E8
void HandlePlayerConnected(GlobalNamespace::IConnectedPlayer* player);
// private System.Void HandlePlayerDisconnected(IConnectedPlayer player)
// Offset: 0x16F3A0C
void HandlePlayerDisconnected(GlobalNamespace::IConnectedPlayer* player);
// private System.Void HandlePlayerStateChanged(IConnectedPlayer player)
// Offset: 0x16F3AE0
void HandlePlayerStateChanged(GlobalNamespace::IConnectedPlayer* player);
// private System.Void HandlePlayerAvatarChanged(IConnectedPlayer player)
// Offset: 0x16F3CA0
void HandlePlayerAvatarChanged(GlobalNamespace::IConnectedPlayer* player);
// private System.Void HandlePlayerOrderChanged(IConnectedPlayer player)
// Offset: 0x16F3D38
void HandlePlayerOrderChanged(GlobalNamespace::IConnectedPlayer* player);
// public IConnectedPlayer GetPlayerByUserId(System.String userId)
// Offset: 0x16F3D70
GlobalNamespace::IConnectedPlayer* GetPlayerByUserId(::Il2CppString* userId);
// public IConnectedPlayer GetConnectedPlayer(System.Int32 i)
// Offset: 0x16F3EF8
GlobalNamespace::IConnectedPlayer* GetConnectedPlayer(int i);
// public System.Void SetLocalPlayerState(System.String state, System.Boolean hasState)
// Offset: 0x16F222C
void SetLocalPlayerState(::Il2CppString* state, bool hasState);
// public System.Void KickPlayer(System.String userId)
// Offset: 0x16F3F70
void KickPlayer(::Il2CppString* userId);
// public System.Boolean LocalPlayerHasState(System.String state)
// Offset: 0x16F3F88
bool LocalPlayerHasState(::Il2CppString* state);
// private System.Void UpdateConnectionState(UpdateConnectionStateReason updateReason, DisconnectedReason disconnectedReason, ConnectionFailedReason connectionFailedReason)
// Offset: 0x16F23A8
void UpdateConnectionState(GlobalNamespace::UpdateConnectionStateReason updateReason, GlobalNamespace::DisconnectedReason disconnectedReason, GlobalNamespace::ConnectionFailedReason connectionFailedReason);
// private System.Boolean TryUpdateConnectedPlayer(IConnectedPlayer player, System.Boolean isPlayerConnected)
// Offset: 0x16F34BC
bool TryUpdateConnectedPlayer(GlobalNamespace::IConnectedPlayer* player, bool isPlayerConnected);
// private System.Int32 GetNextAvailableSortIndex()
// Offset: 0x16F40AC
int GetNextAvailableSortIndex();
// public System.Void .ctor()
// Offset: 0x16F4144
// Implemented from: StandaloneMonobehavior
// Base method: System.Void StandaloneMonobehavior::.ctor()
// Base method: System.Void MonoBehaviour::.ctor()
// Base method: System.Void Behaviour::.ctor()
// Base method: System.Void Component::.ctor()
// Base method: System.Void Object::.ctor()
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static MultiplayerSessionManager* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::MultiplayerSessionManager::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<MultiplayerSessionManager*, creationType>()));
}
// protected override System.Void Start()
// Offset: 0x16F21D8
// Implemented from: StandaloneMonobehavior
// Base method: System.Void StandaloneMonobehavior::Start()
void Start();
// protected override System.Void Update()
// Offset: 0x16F22DC
// Implemented from: StandaloneMonobehavior
// Base method: System.Void StandaloneMonobehavior::Update()
void Update();
// protected override System.Void OnDestroy()
// Offset: 0x16F2378
// Implemented from: StandaloneMonobehavior
// Base method: System.Void StandaloneMonobehavior::OnDestroy()
void OnDestroy();
// protected override System.Void OnApplicationPause(System.Boolean pauseStatus)
// Offset: 0x16F2B44
// Implemented from: StandaloneMonobehavior
// Base method: System.Void StandaloneMonobehavior::OnApplicationPause(System.Boolean pauseStatus)
void OnApplicationPause(bool pauseStatus);
}; // MultiplayerSessionManager
#pragma pack(pop)
static check_size<sizeof(MultiplayerSessionManager), 176 + sizeof(GlobalNamespace::ConnectedPlayerManager*)> __GlobalNamespace_MultiplayerSessionManagerSizeCheck;
static_assert(sizeof(MultiplayerSessionManager) == 0xB8);
}
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::MultiplayerSessionManager*, "", "MultiplayerSessionManager");
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::MultiplayerSessionManager::SessionType, "", "MultiplayerSessionManager/SessionType");
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::MultiplayerSessionManager::ConnectionState, "", "MultiplayerSessionManager/ConnectionState");
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::get_isConnectionOwner
// Il2CppName: get_isConnectionOwner
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::get_isConnectionOwner)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "get_isConnectionOwner", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::get_connectionOwner
// Il2CppName: get_connectionOwner
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<GlobalNamespace::IConnectedPlayer* (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::get_connectionOwner)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "get_connectionOwner", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::set_connectionOwner
// Il2CppName: set_connectionOwner
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(GlobalNamespace::IConnectedPlayer*)>(&GlobalNamespace::MultiplayerSessionManager::set_connectionOwner)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "set_connectionOwner", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::get_isSpectating
// Il2CppName: get_isSpectating
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::get_isSpectating)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "get_isSpectating", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::get_isConnectingOrConnected
// Il2CppName: get_isConnectingOrConnected
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::get_isConnectingOrConnected)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "get_isConnectingOrConnected", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::get_isConnected
// Il2CppName: get_isConnected
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::get_isConnected)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "get_isConnected", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::get_isConnecting
// Il2CppName: get_isConnecting
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::get_isConnecting)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "get_isConnecting", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::get_isDisconnecting
// Il2CppName: get_isDisconnecting
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::get_isDisconnecting)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "get_isDisconnecting", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::get_connectedPlayers
// Il2CppName: get_connectedPlayers
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::Collections::Generic::IReadOnlyList_1<GlobalNamespace::IConnectedPlayer*>* (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::get_connectedPlayers)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "get_connectedPlayers", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::get_connectedPlayerCount
// Il2CppName: get_connectedPlayerCount
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::get_connectedPlayerCount)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "get_connectedPlayerCount", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::get_syncTime
// Il2CppName: get_syncTime
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<float (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::get_syncTime)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "get_syncTime", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::get_isSyncTimeInitialized
// Il2CppName: get_isSyncTimeInitialized
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::get_isSyncTimeInitialized)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "get_isSyncTimeInitialized", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::get_syncTimeDelay
// Il2CppName: get_syncTimeDelay
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<float (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::get_syncTimeDelay)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "get_syncTimeDelay", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::get_localPlayer
// Il2CppName: get_localPlayer
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<GlobalNamespace::IConnectedPlayer* (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::get_localPlayer)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "get_localPlayer", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::get_connectedPlayerManager
// Il2CppName: get_connectedPlayerManager
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<GlobalNamespace::ConnectedPlayerManager* (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::get_connectedPlayerManager)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "get_connectedPlayerManager", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::get_maxPlayerCount
// Il2CppName: get_maxPlayerCount
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::get_maxPlayerCount)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "get_maxPlayerCount", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::add_connectedEvent
// Il2CppName: add_connectedEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(System::Action*)>(&GlobalNamespace::MultiplayerSessionManager::add_connectedEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Action")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "add_connectedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::remove_connectedEvent
// Il2CppName: remove_connectedEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(System::Action*)>(&GlobalNamespace::MultiplayerSessionManager::remove_connectedEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Action")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "remove_connectedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::add_connectionFailedEvent
// Il2CppName: add_connectionFailedEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(System::Action_1<GlobalNamespace::ConnectionFailedReason>*)>(&GlobalNamespace::MultiplayerSessionManager::add_connectionFailedEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "ConnectionFailedReason")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "add_connectionFailedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::remove_connectionFailedEvent
// Il2CppName: remove_connectionFailedEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(System::Action_1<GlobalNamespace::ConnectionFailedReason>*)>(&GlobalNamespace::MultiplayerSessionManager::remove_connectionFailedEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "ConnectionFailedReason")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "remove_connectionFailedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::add_playerConnectedEvent
// Il2CppName: add_playerConnectedEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(System::Action_1<GlobalNamespace::IConnectedPlayer*>*)>(&GlobalNamespace::MultiplayerSessionManager::add_playerConnectedEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "add_playerConnectedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::remove_playerConnectedEvent
// Il2CppName: remove_playerConnectedEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(System::Action_1<GlobalNamespace::IConnectedPlayer*>*)>(&GlobalNamespace::MultiplayerSessionManager::remove_playerConnectedEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "remove_playerConnectedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::add_playerDisconnectedEvent
// Il2CppName: add_playerDisconnectedEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(System::Action_1<GlobalNamespace::IConnectedPlayer*>*)>(&GlobalNamespace::MultiplayerSessionManager::add_playerDisconnectedEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "add_playerDisconnectedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::remove_playerDisconnectedEvent
// Il2CppName: remove_playerDisconnectedEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(System::Action_1<GlobalNamespace::IConnectedPlayer*>*)>(&GlobalNamespace::MultiplayerSessionManager::remove_playerDisconnectedEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "remove_playerDisconnectedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::add_playerAvatarChangedEvent
// Il2CppName: add_playerAvatarChangedEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(System::Action_1<GlobalNamespace::IConnectedPlayer*>*)>(&GlobalNamespace::MultiplayerSessionManager::add_playerAvatarChangedEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "add_playerAvatarChangedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::remove_playerAvatarChangedEvent
// Il2CppName: remove_playerAvatarChangedEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(System::Action_1<GlobalNamespace::IConnectedPlayer*>*)>(&GlobalNamespace::MultiplayerSessionManager::remove_playerAvatarChangedEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "remove_playerAvatarChangedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::add_playerStateChangedEvent
// Il2CppName: add_playerStateChangedEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(System::Action_1<GlobalNamespace::IConnectedPlayer*>*)>(&GlobalNamespace::MultiplayerSessionManager::add_playerStateChangedEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "add_playerStateChangedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::remove_playerStateChangedEvent
// Il2CppName: remove_playerStateChangedEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(System::Action_1<GlobalNamespace::IConnectedPlayer*>*)>(&GlobalNamespace::MultiplayerSessionManager::remove_playerStateChangedEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "remove_playerStateChangedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::add_connectionOwnerStateChangedEvent
// Il2CppName: add_connectionOwnerStateChangedEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(System::Action_1<GlobalNamespace::IConnectedPlayer*>*)>(&GlobalNamespace::MultiplayerSessionManager::add_connectionOwnerStateChangedEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "add_connectionOwnerStateChangedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::remove_connectionOwnerStateChangedEvent
// Il2CppName: remove_connectionOwnerStateChangedEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(System::Action_1<GlobalNamespace::IConnectedPlayer*>*)>(&GlobalNamespace::MultiplayerSessionManager::remove_connectionOwnerStateChangedEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "remove_connectionOwnerStateChangedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::add_disconnectedEvent
// Il2CppName: add_disconnectedEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(System::Action_1<GlobalNamespace::DisconnectedReason>*)>(&GlobalNamespace::MultiplayerSessionManager::add_disconnectedEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "DisconnectedReason")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "add_disconnectedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::remove_disconnectedEvent
// Il2CppName: remove_disconnectedEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(System::Action_1<GlobalNamespace::DisconnectedReason>*)>(&GlobalNamespace::MultiplayerSessionManager::remove_disconnectedEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "DisconnectedReason")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "remove_disconnectedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::RegisterSerializer
// Il2CppName: RegisterSerializer
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(GlobalNamespace::MultiplayerSessionManager_MessageType, GlobalNamespace::INetworkPacketSubSerializer_1<GlobalNamespace::IConnectedPlayer*>*)>(&GlobalNamespace::MultiplayerSessionManager::RegisterSerializer)> {
static const MethodInfo* get() {
static auto* serializerType = &::il2cpp_utils::GetClassFromName("", "MultiplayerSessionManager/MessageType")->byval_arg;
static auto* subSerializer = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("", "INetworkPacketSubSerializer`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "RegisterSerializer", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{serializerType, subSerializer});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::UnregisterSerializer
// Il2CppName: UnregisterSerializer
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(GlobalNamespace::MultiplayerSessionManager_MessageType, GlobalNamespace::INetworkPacketSubSerializer_1<GlobalNamespace::IConnectedPlayer*>*)>(&GlobalNamespace::MultiplayerSessionManager::UnregisterSerializer)> {
static const MethodInfo* get() {
static auto* serializerType = &::il2cpp_utils::GetClassFromName("", "MultiplayerSessionManager/MessageType")->byval_arg;
static auto* subSerializer = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("", "INetworkPacketSubSerializer`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "UnregisterSerializer", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{serializerType, subSerializer});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::RegisterCallback
// Il2CppName: RegisterCallback
// Cannot write MetadataGetter for generic methods!
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::UnregisterCallback
// Il2CppName: UnregisterCallback
// Cannot write MetadataGetter for generic methods!
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::StartSession
// Il2CppName: StartSession
// Cannot write MetadataGetter for generic methods!
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::StartSession
// Il2CppName: StartSession
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(GlobalNamespace::ConnectedPlayerManager*)>(&GlobalNamespace::MultiplayerSessionManager::StartSession)> {
static const MethodInfo* get() {
static auto* connectedPlayerManager = &::il2cpp_utils::GetClassFromName("", "ConnectedPlayerManager")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "StartSession", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{connectedPlayerManager});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::SetMaxPlayerCount
// Il2CppName: SetMaxPlayerCount
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(int)>(&GlobalNamespace::MultiplayerSessionManager::SetMaxPlayerCount)> {
static const MethodInfo* get() {
static auto* maxPlayerCount = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "SetMaxPlayerCount", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{maxPlayerCount});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::InitInternal
// Il2CppName: InitInternal
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(GlobalNamespace::MultiplayerSessionManager::SessionType)>(&GlobalNamespace::MultiplayerSessionManager::InitInternal)> {
static const MethodInfo* get() {
static auto* sessionType = &::il2cpp_utils::GetClassFromName("", "MultiplayerSessionManager/SessionType")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "InitInternal", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{sessionType});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::EndSession
// Il2CppName: EndSession
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::EndSession)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "EndSession", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::Disconnect
// Il2CppName: Disconnect
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::Disconnect)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "Disconnect", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::Send
// Il2CppName: Send
// Cannot write MetadataGetter for generic methods!
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::SendUnreliable
// Il2CppName: SendUnreliable
// Cannot write MetadataGetter for generic methods!
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::PerformAtSyncTime
// Il2CppName: PerformAtSyncTime
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(float, System::Action*)>(&GlobalNamespace::MultiplayerSessionManager::PerformAtSyncTime)> {
static const MethodInfo* get() {
static auto* syncTime = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
static auto* action = &::il2cpp_utils::GetClassFromName("System", "Action")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "PerformAtSyncTime", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{syncTime, action});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::UpdateSynchronizedActions
// Il2CppName: UpdateSynchronizedActions
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::UpdateSynchronizedActions)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "UpdateSynchronizedActions", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::HandleReinitialized
// Il2CppName: HandleReinitialized
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::HandleReinitialized)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "HandleReinitialized", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::HandleConnected
// Il2CppName: HandleConnected
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::HandleConnected)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "HandleConnected", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::HandleDisconnected
// Il2CppName: HandleDisconnected
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(GlobalNamespace::DisconnectedReason)>(&GlobalNamespace::MultiplayerSessionManager::HandleDisconnected)> {
static const MethodInfo* get() {
static auto* disconnectedReason = &::il2cpp_utils::GetClassFromName("", "DisconnectedReason")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "HandleDisconnected", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{disconnectedReason});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::HandleConnectionFailed
// Il2CppName: HandleConnectionFailed
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(GlobalNamespace::ConnectionFailedReason)>(&GlobalNamespace::MultiplayerSessionManager::HandleConnectionFailed)> {
static const MethodInfo* get() {
static auto* reason = &::il2cpp_utils::GetClassFromName("", "ConnectionFailedReason")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "HandleConnectionFailed", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{reason});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::HandleSyncTimeInitialized
// Il2CppName: HandleSyncTimeInitialized
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::HandleSyncTimeInitialized)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "HandleSyncTimeInitialized", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::HandlePlayerConnected
// Il2CppName: HandlePlayerConnected
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(GlobalNamespace::IConnectedPlayer*)>(&GlobalNamespace::MultiplayerSessionManager::HandlePlayerConnected)> {
static const MethodInfo* get() {
static auto* player = &::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "HandlePlayerConnected", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{player});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::HandlePlayerDisconnected
// Il2CppName: HandlePlayerDisconnected
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(GlobalNamespace::IConnectedPlayer*)>(&GlobalNamespace::MultiplayerSessionManager::HandlePlayerDisconnected)> {
static const MethodInfo* get() {
static auto* player = &::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "HandlePlayerDisconnected", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{player});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::HandlePlayerStateChanged
// Il2CppName: HandlePlayerStateChanged
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(GlobalNamespace::IConnectedPlayer*)>(&GlobalNamespace::MultiplayerSessionManager::HandlePlayerStateChanged)> {
static const MethodInfo* get() {
static auto* player = &::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "HandlePlayerStateChanged", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{player});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::HandlePlayerAvatarChanged
// Il2CppName: HandlePlayerAvatarChanged
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(GlobalNamespace::IConnectedPlayer*)>(&GlobalNamespace::MultiplayerSessionManager::HandlePlayerAvatarChanged)> {
static const MethodInfo* get() {
static auto* player = &::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "HandlePlayerAvatarChanged", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{player});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::HandlePlayerOrderChanged
// Il2CppName: HandlePlayerOrderChanged
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(GlobalNamespace::IConnectedPlayer*)>(&GlobalNamespace::MultiplayerSessionManager::HandlePlayerOrderChanged)> {
static const MethodInfo* get() {
static auto* player = &::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "HandlePlayerOrderChanged", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{player});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::GetPlayerByUserId
// Il2CppName: GetPlayerByUserId
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<GlobalNamespace::IConnectedPlayer* (GlobalNamespace::MultiplayerSessionManager::*)(::Il2CppString*)>(&GlobalNamespace::MultiplayerSessionManager::GetPlayerByUserId)> {
static const MethodInfo* get() {
static auto* userId = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "GetPlayerByUserId", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{userId});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::GetConnectedPlayer
// Il2CppName: GetConnectedPlayer
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<GlobalNamespace::IConnectedPlayer* (GlobalNamespace::MultiplayerSessionManager::*)(int)>(&GlobalNamespace::MultiplayerSessionManager::GetConnectedPlayer)> {
static const MethodInfo* get() {
static auto* i = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "GetConnectedPlayer", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{i});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::SetLocalPlayerState
// Il2CppName: SetLocalPlayerState
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(::Il2CppString*, bool)>(&GlobalNamespace::MultiplayerSessionManager::SetLocalPlayerState)> {
static const MethodInfo* get() {
static auto* state = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
static auto* hasState = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "SetLocalPlayerState", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{state, hasState});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::KickPlayer
// Il2CppName: KickPlayer
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(::Il2CppString*)>(&GlobalNamespace::MultiplayerSessionManager::KickPlayer)> {
static const MethodInfo* get() {
static auto* userId = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "KickPlayer", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{userId});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::LocalPlayerHasState
// Il2CppName: LocalPlayerHasState
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::MultiplayerSessionManager::*)(::Il2CppString*)>(&GlobalNamespace::MultiplayerSessionManager::LocalPlayerHasState)> {
static const MethodInfo* get() {
static auto* state = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "LocalPlayerHasState", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{state});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::UpdateConnectionState
// Il2CppName: UpdateConnectionState
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(GlobalNamespace::UpdateConnectionStateReason, GlobalNamespace::DisconnectedReason, GlobalNamespace::ConnectionFailedReason)>(&GlobalNamespace::MultiplayerSessionManager::UpdateConnectionState)> {
static const MethodInfo* get() {
static auto* updateReason = &::il2cpp_utils::GetClassFromName("", "UpdateConnectionStateReason")->byval_arg;
static auto* disconnectedReason = &::il2cpp_utils::GetClassFromName("", "DisconnectedReason")->byval_arg;
static auto* connectionFailedReason = &::il2cpp_utils::GetClassFromName("", "ConnectionFailedReason")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "UpdateConnectionState", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{updateReason, disconnectedReason, connectionFailedReason});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::TryUpdateConnectedPlayer
// Il2CppName: TryUpdateConnectedPlayer
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::MultiplayerSessionManager::*)(GlobalNamespace::IConnectedPlayer*, bool)>(&GlobalNamespace::MultiplayerSessionManager::TryUpdateConnectedPlayer)> {
static const MethodInfo* get() {
static auto* player = &::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")->byval_arg;
static auto* isPlayerConnected = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "TryUpdateConnectedPlayer", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{player, isPlayerConnected});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::GetNextAvailableSortIndex
// Il2CppName: GetNextAvailableSortIndex
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::GetNextAvailableSortIndex)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "GetNextAvailableSortIndex", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::Start
// Il2CppName: Start
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::Start)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "Start", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::Update
// Il2CppName: Update
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::Update)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "Update", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::OnDestroy
// Il2CppName: OnDestroy
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)()>(&GlobalNamespace::MultiplayerSessionManager::OnDestroy)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "OnDestroy", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::MultiplayerSessionManager::OnApplicationPause
// Il2CppName: OnApplicationPause
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MultiplayerSessionManager::*)(bool)>(&GlobalNamespace::MultiplayerSessionManager::OnApplicationPause)> {
static const MethodInfo* get() {
static auto* pauseStatus = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MultiplayerSessionManager*), "OnApplicationPause", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{pauseStatus});
}
};
| 87,328 | 25,685 |
#include "imgplane.h"
ImgPlane::ImgPlane(int w, int h) : width(w), height(h)
{
int size = w*h;
for(int i=0; i<size; ++i){
image.push_back(new Color(0,0,0));
raysNumber.push_back(0);
}
}
void ImgPlane::updatePixel(int x, int y, Color &pxl, int rays){
Color *actual = image[x*width+y];
int actualRays = raysNumber[x*width+y];
actual->setColor((actual->getR()*actualRays+pxl.getR()*rays)/(rays+actualRays),
(actual->getG()*actualRays+pxl.getG()*rays)/(rays+actualRays),
(actual->getB()*actualRays+pxl.getB()*rays)/(rays+actualRays)
);
raysNumber[x*width+y] += rays;
}
void ImgPlane::writeImg(const string &fileName){
cv::Mat img(height, width, CV_8UC3);
for(int x=0; x<width; ++x) for(int y=0; y<height; ++y){
Color toAssign = *(image[x*width+y]);
toAssign.clampVars();
img.at<uchar>(y,3*x+2) = (uchar)255*toAssign.getR();
img.at<uchar>(y,3*x+1) = (uchar)255*toAssign.getG();
img.at<uchar>(y,3*x) = (uchar)255*toAssign.getB();
}
cv::imwrite(fileName, img);
}
| 1,122 | 472 |
/**************erik****************/
#include<bits/stdc++.h>
#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long int ll;
typedef unsigned long long int ull;
map<int,int> mp1;
set<int> s1;
//set<int>::iterator it;
#define maxm(a,b,c) max(a,max(c,b))
#define minm(a,b,c) min(a,min(c,b))
#define f(i,n) for(int i=1;i<n;i++)
#define rf(i,n) for(int i=n-1;i>=0;i--)
const int MAX = 100005;
vector<pair<int,int> > vec[MAX];
ll dist[MAX];
bool vis[MAX];
void dijkstra(int source){
dist[source] = 0;
multiset < pair < ll , int > > s;
s.insert({0 , source});
while(!s.empty()){
pair <ll , int> p = *s.begin();
s.erase(s.begin());
int x = p.second;
// if( vis[x] ) continue;
// vis[x] = true;
for(int i = 0; i < vec[x].size(); i++){
int e = vec[x][i].second;
int w = vec[x][i].first;
if(w==1){
if(dist[x]%2==0 && dist[e]>dist[x]+1){
dist[e] = dist[x]+2; //if wgt is odd but arrival time is even
s.insert({dist[e],e});
}
else if(dist[x]%2!=0 && dist[e]>dist[x]+1){
dist[e] = dist[x]+1;
s.insert({dist[e],e});
}
}
else if(w==0){
if(dist[x]%2==0 && dist[e]>dist[x]+1){
dist[e] = dist[x]+1;
s.insert({dist[e],e});
}
else if(dist[x]%2!=0 && dist[e]>dist[x]+1){
dist[e] = dist[x]+2; // if wgt is even but arrival time is odd
s.insert({dist[e],e});
}
}
}
}
}
/*void dfs(int x,ll timed,int n){
vis[x]=1;
tot = timed;
if(vis[n]){
//cout<<x<<"*"<<timed+1<<endl;
return;
}
if(timed%2==0){
if(vec[x][0].size()!=0){
bool f = true;
for(int i=0;i<vec[x][0].size();i++){
int y = vec[x][0][i];
if(vis[y]==0){
f = false;
//cout<<y<<'*'<<timed+1<<endl;
dfs(y,timed+1,n);
}
}
if(f){
//cout<<x<<"*"<<timed+1<<endl;
dfs(x,timed+1,n);
}
}
else {
//cout<<x<<"*"<<timed+1<<endl;
dfs(x,timed+1,n);
}
}
else {
if(vec[x][1].size()!=0){
bool f = true;
for(int i=0;i<vec[x][1].size();i++){
int y = vec[x][1][i];
if(vis[y]==0){
f = false;
//cout<<y<<' '<<timed+1<<endl;
dfs(y,timed+1,n);
}
}
//cout<<x<<"*"<<timed+1<<endl;
dfs(x,timed+1,n);
}
else {
//cout<<x<<"*"<<timed+1<<endl;
dfs(x,timed+1,n);
}
}
}*/
int main() {
int n,m,q;
cin>>n>>m>>q;
for(int i=0;i<m;i++){
int x,y;
cin>>x>>y;
vec[x].push_back({0,y});
vec[y].push_back({1,x});
}
for(int i=1;i<=n+1;i++){
dist[i]=1e12;
vec[i].clear();
}
dist[1]=0;
dijkstra(1);
cout<<dist[n]<<endl;
for(int i=0;i<q;i++){
ll tt;
cin>>tt;
if(tt<dist[n]){
cout<<"FML"<<endl;
}
else {
cout<<"GGMU"<<endl;
}
}
//cout<<tot;
return 0;
} | 3,503 | 1,365 |
/* P U L L B A C K C U R V E . C P P
* BRL-CAD
*
* Copyright (c) 2009-2014 United States Government as represented by
* the U.S. Army Research Laboratory.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this file; see the file named COPYING for more
* information.
*/
/** @file step/PullbackCurve.cpp
*
* Pull curve back into UV space from 3D space
*
*/
#include "common.h"
#include "vmath.h"
#include "dvec.h"
#include <assert.h>
#include <vector>
#include <list>
#include <limits>
#include <set>
#include <map>
#include <string>
#include "brep.h"
/* interface header */
#include "PullbackCurve.h"
#define RANGE_HI 0.55
#define RANGE_LO 0.45
#define UNIVERSAL_SAMPLE_COUNT 1001
/* FIXME: duplicated with opennurbs_ext.cpp */
class BSpline
{
public:
int p; // degree
int m; // num_knots-1
int n; // num_samples-1 (aka number of control points)
std::vector<double> params;
std::vector<double> knots;
ON_2dPointArray controls;
};
bool
isFlat(const ON_2dPoint& p1, const ON_2dPoint& m, const ON_2dPoint& p2, double flatness)
{
ON_Line line = ON_Line(ON_3dPoint(p1), ON_3dPoint(p2));
return line.DistanceTo(ON_3dPoint(m)) <= flatness;
}
void
utah_ray_planes(const ON_Ray &r, ON_3dVector &p1, double &p1d, ON_3dVector &p2, double &p2d)
{
ON_3dPoint ro(r.m_origin);
ON_3dVector rdir(r.m_dir);
double rdx, rdy, rdz;
double rdxmag, rdymag, rdzmag;
rdx = rdir.x;
rdy = rdir.y;
rdz = rdir.z;
rdxmag = fabs(rdx);
rdymag = fabs(rdy);
rdzmag = fabs(rdz);
if (rdxmag > rdymag && rdxmag > rdzmag)
p1 = ON_3dVector(rdy, -rdx, 0);
else
p1 = ON_3dVector(0, rdz, -rdy);
p1.Unitize();
p2 = ON_CrossProduct(p1, rdir);
p1d = -(p1 * ro);
p2d = -(p2 * ro);
}
enum seam_direction
seam_direction(ON_2dPoint uv1, ON_2dPoint uv2)
{
if (NEAR_EQUAL(uv1.x, 0.0, PBC_TOL) && NEAR_EQUAL(uv2.x, 0.0, PBC_TOL)) {
return WEST_SEAM;
} else if (NEAR_EQUAL(uv1.x, 1.0, PBC_TOL) && NEAR_EQUAL(uv2.x, 1.0, PBC_TOL)) {
return EAST_SEAM;
} else if (NEAR_EQUAL(uv1.y, 0.0, PBC_TOL) && NEAR_EQUAL(uv2.y, 0.0, PBC_TOL)) {
return SOUTH_SEAM;
} else if (NEAR_EQUAL(uv1.y, 1.0, PBC_TOL) && NEAR_EQUAL(uv2.y, 1.0, PBC_TOL)) {
return NORTH_SEAM;
} else {
return UNKNOWN_SEAM_DIRECTION;
}
}
ON_BOOL32
GetDomainSplits(
const ON_Surface *surf,
const ON_Interval &u_interval,
const ON_Interval &v_interval,
ON_Interval domSplits[2][2]
)
{
ON_3dPoint min, max;
ON_Interval dom[2];
double length[2];
// initialize intervals
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
domSplits[i][j] = ON_Interval::EmptyInterval;
}
}
min[0] = u_interval.m_t[0];
min[1] = v_interval.m_t[0];
max[0] = u_interval.m_t[1];
max[1] = v_interval.m_t[1];
for (int i=0; i<2; i++) {
if (surf->IsClosed(i)) {
dom[i] = surf->Domain(i);
length[i] = dom[i].Length();
if ((max[i] - min[i]) >= length[i]) {
domSplits[i][0] = dom[i];
} else {
double minbound = min[i];
double maxbound = max[i];
while (minbound < dom[i].m_t[0]) {
minbound += length[i];
maxbound += length[i];
}
while (minbound > dom[i].m_t[1]) {
minbound -= length[i];
maxbound -= length[i];
}
if (maxbound > dom[i].m_t[1]) {
domSplits[i][0].m_t[0] = minbound;
domSplits[i][0].m_t[1] = dom[i].m_t[1];
domSplits[i][1].m_t[0] = dom[i].m_t[0];
domSplits[i][1].m_t[1] = maxbound - length[i];
} else {
domSplits[i][0].m_t[0] = minbound;
domSplits[i][0].m_t[1] = maxbound;
}
}
} else {
domSplits[i][0].m_t[0] = min[i];
domSplits[i][0].m_t[1] = max[i];
}
}
return true;
}
/*
* Wrapped OpenNURBS 'EvNormal()' because it fails when at surface singularity
* but not on edge of domain. If fails and at singularity this wrapper will
* reevaluate at domain edge.
*/
ON_BOOL32
surface_EvNormal( // returns false if unable to evaluate
const ON_Surface *surf,
double s, double t, // evaluation parameters (s,t)
ON_3dPoint& point, // returns value of surface
ON_3dVector& normal, // unit normal
int side, // optional - determines which side to evaluate from
// 0 = default
// 1 from NE quadrant
// 2 from NW quadrant
// 3 from SW quadrant
// 4 from SE quadrant
int* hint // optional - evaluation hint (int[2]) used to speed
// repeated evaluations
)
{
ON_BOOL32 rc = false;
if (!(rc=surf->EvNormal(s, t, point, normal, side, hint))) {
side = IsAtSingularity(surf, s, t, PBC_SEAM_TOL);// 0 = south, 1 = east, 2 = north, 3 = west
if (side >= 0) {
ON_Interval u = surf->Domain(0);
ON_Interval v = surf->Domain(1);
if (side == 0) {
rc=surf->EvNormal(u.m_t[0], v.m_t[0], point, normal, side, hint);
} else if (side == 1) {
rc=surf->EvNormal(u.m_t[1], v.m_t[1], point, normal, side, hint);
} else if (side == 2) {
rc=surf->EvNormal(u.m_t[1], v.m_t[1], point, normal, side, hint);
} else if (side == 3) {
rc=surf->EvNormal(u.m_t[0], v.m_t[0], point, normal, side, hint);
}
}
}
return rc;
}
ON_BOOL32
surface_GetBoundingBox(
const ON_Surface *surf,
const ON_Interval &u_interval,
const ON_Interval &v_interval,
ON_BoundingBox& bbox,
ON_BOOL32 bGrowBox
)
{
/* TODO: Address for threading
* defined static for first time thru initialization, will
* have to do something else here for multiple threads
*/
static ON_RevSurface *rev_surface = ON_RevSurface::New();
static ON_NurbsSurface *nurbs_surface = ON_NurbsSurface::New();
static ON_Extrusion *extr_surface = new ON_Extrusion();
static ON_PlaneSurface *plane_surface = new ON_PlaneSurface();
static ON_SumSurface *sum_surface = ON_SumSurface::New();
static ON_SurfaceProxy *proxy_surface = new ON_SurfaceProxy();
ON_Interval domSplits[2][2] = { { ON_Interval::EmptyInterval, ON_Interval::EmptyInterval }, { ON_Interval::EmptyInterval, ON_Interval::EmptyInterval }};
if (!GetDomainSplits(surf,u_interval,v_interval,domSplits)) {
return false;
}
bool growcurrent = bGrowBox;
for (int i=0; i<2; i++) {
if (domSplits[0][i] == ON_Interval::EmptyInterval)
continue;
for (int j=0; j<2; j++) {
if (domSplits[1][j] != ON_Interval::EmptyInterval) {
if (dynamic_cast<ON_RevSurface * >(const_cast<ON_Surface *>(surf)) != NULL) {
*rev_surface = *dynamic_cast<ON_RevSurface * >(const_cast<ON_Surface *>(surf));
if (rev_surface->Trim(0, domSplits[0][i]) && rev_surface->Trim(1, domSplits[1][j])) {
if (!rev_surface->GetBoundingBox(bbox, growcurrent)) {
return false;
}
growcurrent = true;
}
} else if (dynamic_cast<ON_NurbsSurface * >(const_cast<ON_Surface *>(surf)) != NULL) {
*nurbs_surface = *dynamic_cast<ON_NurbsSurface * >(const_cast<ON_Surface *>(surf));
if (nurbs_surface->Trim(0, domSplits[0][i]) && nurbs_surface->Trim(1, domSplits[1][j])) {
if (!nurbs_surface->GetBoundingBox(bbox, growcurrent)) {
return false;
}
}
growcurrent = true;
} else if (dynamic_cast<ON_Extrusion * >(const_cast<ON_Surface *>(surf)) != NULL) {
*extr_surface = *dynamic_cast<ON_Extrusion * >(const_cast<ON_Surface *>(surf));
if (extr_surface->Trim(0, domSplits[0][i]) && extr_surface->Trim(1, domSplits[1][j])) {
if (!extr_surface->GetBoundingBox(bbox, growcurrent)) {
return false;
}
}
growcurrent = true;
} else if (dynamic_cast<ON_PlaneSurface * >(const_cast<ON_Surface *>(surf)) != NULL) {
*plane_surface = *dynamic_cast<ON_PlaneSurface * >(const_cast<ON_Surface *>(surf));
if (plane_surface->Trim(0, domSplits[0][i]) && plane_surface->Trim(1, domSplits[1][j])) {
if (!plane_surface->GetBoundingBox(bbox, growcurrent)) {
return false;
}
}
growcurrent = true;
} else if (dynamic_cast<ON_SumSurface * >(const_cast<ON_Surface *>(surf)) != NULL) {
*sum_surface = *dynamic_cast<ON_SumSurface * >(const_cast<ON_Surface *>(surf));
if (sum_surface->Trim(0, domSplits[0][i]) && sum_surface->Trim(1, domSplits[1][j])) {
if (!sum_surface->GetBoundingBox(bbox, growcurrent)) {
return false;
}
}
growcurrent = true;
} else if (dynamic_cast<ON_SurfaceProxy * >(const_cast<ON_Surface *>(surf)) != NULL) {
*proxy_surface = *dynamic_cast<ON_SurfaceProxy * >(const_cast<ON_Surface *>(surf));
if (proxy_surface->Trim(0, domSplits[0][i]) && proxy_surface->Trim(1, domSplits[1][j])) {
if (!proxy_surface->GetBoundingBox(bbox, growcurrent)) {
return false;
}
}
growcurrent = true;
} else {
std::cerr << "Unknown Surface Type" << std::endl;
}
}
}
}
return true;
}
ON_BOOL32
face_GetBoundingBox(
const ON_BrepFace &face,
ON_BoundingBox& bbox,
ON_BOOL32 bGrowBox
)
{
const ON_Surface *surf = face.SurfaceOf();
// may be a smaller trimmed subset of surface so worth getting
// face boundary
bool growcurrent = bGrowBox;
ON_3dPoint min, max;
for (int li = 0; li < face.LoopCount(); li++) {
for (int ti = 0; ti < face.Loop(li)->TrimCount(); ti++) {
ON_BrepTrim *trim = face.Loop(li)->Trim(ti);
trim->GetBoundingBox(min, max, growcurrent);
growcurrent = true;
}
}
ON_Interval u_interval(min.x, max.x);
ON_Interval v_interval(min.y, max.y);
if (!surface_GetBoundingBox(surf, u_interval,v_interval,bbox,growcurrent)) {
return false;
}
return true;
}
ON_BOOL32
surface_GetIntervalMinMaxDistance(
const ON_3dPoint& p,
ON_BoundingBox &bbox,
double &min_distance,
double &max_distance
)
{
min_distance = bbox.MinimumDistanceTo(p);
max_distance = bbox.MaximumDistanceTo(p);
return true;
}
ON_BOOL32
surface_GetIntervalMinMaxDistance(
const ON_Surface *surf,
const ON_3dPoint& p,
const ON_Interval &u_interval,
const ON_Interval &v_interval,
double &min_distance,
double &max_distance
)
{
ON_BoundingBox bbox;
if (surface_GetBoundingBox(surf,u_interval,v_interval,bbox, false)) {
min_distance = bbox.MinimumDistanceTo(p);
max_distance = bbox.MaximumDistanceTo(p);
return true;
}
return false;
}
double
surface_GetOptimalNormalUSplit(const ON_Surface *surf, const ON_Interval &u_interval, const ON_Interval &v_interval,double tol)
{
ON_3dVector normal[4];
double u = u_interval.Mid();
if ((normal[0] = surf->NormalAt(u_interval.m_t[0],v_interval.m_t[0])) &&
(normal[2] = surf->NormalAt(u_interval.m_t[0],v_interval.m_t[1]))) {
double step = u_interval.Length()/2.0;
double stepdir = 1.0;
u = u_interval.m_t[0] + stepdir * step;
while (step > tol) {
if ((normal[1] = surf->NormalAt(u,v_interval.m_t[0])) &&
(normal[3] = surf->NormalAt(u,v_interval.m_t[1]))) {
double udot_1 = normal[0] * normal[1];
double udot_2 = normal[2] * normal[3];
if ((udot_1 < 0.0) || (udot_2 < 0.0)) {
stepdir = -1.0;
} else {
stepdir = 1.0;
}
step = step / 2.0;
u = u + stepdir * step;
}
}
}
return u;
}
double
surface_GetOptimalNormalVSplit(const ON_Surface *surf, const ON_Interval &u_interval, const ON_Interval &v_interval,double tol)
{
ON_3dVector normal[4];
double v = v_interval.Mid();
if ((normal[0] = surf->NormalAt(u_interval.m_t[0],v_interval.m_t[0])) &&
(normal[1] = surf->NormalAt(u_interval.m_t[1],v_interval.m_t[0]))) {
double step = v_interval.Length()/2.0;
double stepdir = 1.0;
v = v_interval.m_t[0] + stepdir * step;
while (step > tol) {
if ((normal[2] = surf->NormalAt(u_interval.m_t[0],v)) &&
(normal[3] = surf->NormalAt(u_interval.m_t[1],v))) {
double vdot_1 = normal[0] * normal[2];
double vdot_2 = normal[1] * normal[3];
if ((vdot_1 < 0.0) || (vdot_2 < 0.0)) {
stepdir = -1.0;
} else {
stepdir = 1.0;
}
step = step / 2.0;
v = v + stepdir * step;
}
}
}
return v;
}
//forward for cyclic
double surface_GetClosestPoint3dFirstOrderByRange(const ON_Surface *surf,const ON_3dPoint& p,const ON_Interval& u_range,
const ON_Interval& v_range,double current_closest_dist,ON_2dPoint& p2d,ON_3dPoint& p3d,double same_point_tol, double within_distance_tol,int level);
double surface_GetClosestPoint3dFirstOrderSubdivision(const ON_Surface *surf,
const ON_3dPoint& p, const ON_Interval &u_interval, double u, const ON_Interval &v_interval, double v,
double current_closest_dist, ON_2dPoint& p2d, ON_3dPoint& p3d,
double same_point_tol, double within_distance_tol, int level)
{
double min_distance, max_distance;
ON_Interval new_u_interval = u_interval;
ON_Interval new_v_interval = v_interval;
for (int iu = 0; iu < 2; iu++) {
new_u_interval.m_t[iu] = u_interval.m_t[iu];
new_u_interval.m_t[1 - iu] = u;
for (int iv = 0; iv < 2; iv++) {
new_v_interval.m_t[iv] = v_interval.m_t[iv];
new_v_interval.m_t[1 - iv] = v;
if (surface_GetIntervalMinMaxDistance(surf, p, new_u_interval,new_v_interval, min_distance, max_distance)) {
double distance = DBL_MAX;
if ((min_distance < current_closest_dist) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
ON_3dVector normal[4];
if ((normal[0] = surf->NormalAt(new_u_interval.m_t[0],new_v_interval.m_t[0])) &&
(normal[1] = surf->NormalAt(new_u_interval.m_t[1],new_v_interval.m_t[0])) &&
(normal[2] = surf->NormalAt(new_u_interval.m_t[0],new_v_interval.m_t[1])) &&
(normal[3] = surf->NormalAt(new_u_interval.m_t[1],new_v_interval.m_t[1]))) {
double udot_1 = normal[0] * normal[1];
double udot_2 = normal[2] * normal[3];
double vdot_1 = normal[0] * normal[2];
double vdot_2 = normal[1] * normal[3];
if ((udot_1 < 0.0) || (udot_2 < 0.0) || (vdot_1 < 0.0) || (vdot_2 < 0.0)) {
double u_split,v_split;
if ((udot_1 < 0.0) || (udot_2 < 0.0)) {
//get optimal U split
u_split = surface_GetOptimalNormalUSplit(surf,new_u_interval,new_v_interval,same_point_tol);
} else {
u_split = new_u_interval.Mid();
}
if ((vdot_1 < 0.0) || (vdot_2 < 0.0)) {
//get optimal V split
v_split = surface_GetOptimalNormalVSplit(surf,new_u_interval,new_v_interval,same_point_tol);
} else {
v_split = new_v_interval.Mid();
}
distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,new_u_interval,u_split,new_v_interval,v_split,current_closest_dist,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_closest_dist) {
current_closest_dist = distance;
if (current_closest_dist < same_point_tol)
return current_closest_dist;
}
} else {
distance = surface_GetClosestPoint3dFirstOrderByRange(surf,p,new_u_interval,new_v_interval,current_closest_dist,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_closest_dist) {
current_closest_dist = distance;
if (current_closest_dist < same_point_tol)
return current_closest_dist;
}
}
}
}
}
}
}
return current_closest_dist;
}
double
surface_GetClosestPoint3dFirstOrderByRange(
const ON_Surface *surf,
const ON_3dPoint& p,
const ON_Interval& u_range,
const ON_Interval& v_range,
double current_closest_dist,
ON_2dPoint& p2d,
ON_3dPoint& p3d,
double same_point_tol,
double within_distance_tol,
int level
)
{
ON_3dPoint p0;
ON_2dPoint p2d0;
ON_3dVector ds, dt, dss, dst, dtt;
ON_2dPoint working_p2d;
ON_3dPoint working_p3d;
ON_3dPoint P;
ON_3dVector Ds, Dt, Dss, Dst, Dtt;
bool notdone = true;
double previous_distance = DBL_MAX;
double distance;
int errcnt = 0;
p2d0.x = u_range.Mid();
p2d0.y = v_range.Mid();
while (notdone && (surf->Ev2Der(p2d0.x, p2d0.y, p0, ds, dt, dss, dst, dtt))) {
if ((distance = p0.DistanceTo(p)) >= previous_distance) {
if (++errcnt <= 10) {
p2d0 = (p2d0 + working_p2d) / 2.0;
continue;
} else {
///////////////////////////
// Don't Subdivide just not getting any closer
///////////////////////////
/*
double distance =
surface_GetClosestPoint3dFirstOrderSubdivision(surf, p,
u_range, u_range.Mid(), v_range, v_range.Mid(),
current_closest_dist, p2d, p3d, tol, level++);
if (distance < current_closest_dist) {
current_closest_dist = distance;
if (current_closest_dist < tol)
return current_closest_dist;
}
*/
break;
}
} else {
if (distance < current_closest_dist) {
current_closest_dist = distance;
p3d = p0;
p2d = p2d0;
if (current_closest_dist < same_point_tol)
return current_closest_dist;
}
previous_distance = distance;
working_p3d = p0;
working_p2d = p2d0;
errcnt = 0;
}
ON_3dVector N = ON_CrossProduct(ds, dt);
N.Unitize();
ON_Plane plane(p0, N);
ON_3dPoint q = plane.ClosestPointTo(p);
ON_2dVector pullback;
ON_3dVector vector = q - p0;
double vlength = vector.Length();
if (vlength > 0.0) {
if (ON_Pullback3dVector(vector, 0.0, ds, dt, dss, dst, dtt,
pullback)) {
p2d0 = p2d0 + pullback;
if (!u_range.Includes(p2d0.x, false)) {
int i = (u_range.m_t[0] <= u_range.m_t[1]) ? 0 : 1;
p2d0.x =
(p2d0.x < u_range.m_t[i]) ?
u_range.m_t[i] : u_range.m_t[1 - i];
}
if (!v_range.Includes(p2d0.y, false)) {
int i = (v_range.m_t[0] <= v_range.m_t[1]) ? 0 : 1;
p2d0.y =
(p2d0.y < v_range.m_t[i]) ?
v_range.m_t[i] : v_range.m_t[1 - i];
}
} else {
///////////////////////////
// Subdivide and go again
///////////////////////////
notdone = false;
distance =
surface_GetClosestPoint3dFirstOrderSubdivision(surf, p,
u_range, u_range.Mid(), v_range, v_range.Mid(),
current_closest_dist, p2d, p3d, same_point_tol, within_distance_tol, level++);
if (distance < current_closest_dist) {
current_closest_dist = distance;
if (current_closest_dist < same_point_tol)
return current_closest_dist;
}
break;
}
} else {
// can't get any closer
notdone = false;
break;
}
}
if (previous_distance < current_closest_dist) {
current_closest_dist = previous_distance;
p3d = working_p3d;
p2d = working_p2d;
}
return current_closest_dist;
}
bool surface_GetClosestPoint3dFirstOrder(
const ON_Surface *surf,
const ON_3dPoint& p,
ON_2dPoint& p2d,
ON_3dPoint& p3d,
double ¤t_distance,
int quadrant, // optional - determines which quadrant to evaluate from
// 0 = default
// 1 from NE quadrant
// 2 from NW quadrant
// 3 from SW quadrant
// 4 from SE quadrant
double same_point_tol,
double within_distance_tol
)
{
ON_3dPoint p0;
ON_2dPoint p2d0;
ON_3dVector ds, dt, dss, dst, dtt;
ON_3dVector T, K;
bool rc = false;
static const ON_Surface *prev_surface = NULL;
static int prev_u_spancnt = 0;
static int u_spancnt = 0;
static int v_spancnt = 0;
static double *uspan = NULL;
static double *vspan = NULL;
static ON_BoundingBox **bbox = NULL;
static double umid = 0.0;
static int umid_index = 0;
static double vmid = 0.0;
static int vmid_index = 0;
current_distance = DBL_MAX;
int prec = std::cerr.precision();
std::cerr.precision(15);
if (prev_surface != surf) {
if (uspan)
delete [] uspan;
if (vspan)
delete [] vspan;
if (bbox) {
for( int i = 0 ; i < (prev_u_spancnt + 2) ; i++ )
delete [] bbox[i] ;
delete [] bbox;
}
u_spancnt = prev_u_spancnt = surf->SpanCount(0);
v_spancnt = surf->SpanCount(1);
// adding 2 here because going to divide at midpoint
uspan = new double[u_spancnt + 2];
vspan = new double[v_spancnt + 2];
bbox = new ON_BoundingBox *[(u_spancnt + 2)];
for( int i = 0 ; i < (u_spancnt + 2) ; i++ )
bbox[i] = new ON_BoundingBox [v_spancnt + 2];
if (surf->GetSpanVector(0, uspan) && surf->GetSpanVector(1, vspan)) {
prev_surface = surf;
umid = surf->Domain(0).Mid();
umid_index = u_spancnt/2;
for (int u_span_index = 0; u_span_index < u_spancnt + 1;u_span_index++) {
if (NEAR_EQUAL(uspan[u_span_index],umid,same_point_tol)) {
umid_index = u_span_index;
break;
} else if (uspan[u_span_index] > umid) {
for (u_span_index = u_spancnt + 1; u_span_index > 0;u_span_index--) {
if (uspan[u_span_index-1] < umid) {
uspan[u_span_index] = umid;
umid_index = u_span_index;
u_spancnt++;
u_span_index = u_spancnt+1;
break;
} else {
uspan[u_span_index] = uspan[u_span_index-1];
}
}
}
}
vmid = surf->Domain(1).Mid();
vmid_index = v_spancnt/2;
for (int v_span_index = 0; v_span_index < v_spancnt + 1;v_span_index++) {
if (NEAR_EQUAL(vspan[v_span_index],vmid,same_point_tol)) {
vmid_index = v_span_index;
break;
} else if (vspan[v_span_index] > vmid) {
for (v_span_index = v_spancnt + 1; v_span_index > 0;v_span_index--) {
if (vspan[v_span_index-1] < vmid) {
vspan[v_span_index] = vmid;
vmid_index = v_span_index;
v_spancnt++;
v_span_index = v_spancnt+1;
break;
} else {
vspan[v_span_index] = vspan[v_span_index-1];
}
}
}
}
for (int u_span_index = 1; u_span_index < u_spancnt + 1;
u_span_index++) {
for (int v_span_index = 1; v_span_index < v_spancnt + 1;
v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
if (!surface_GetBoundingBox(surf,u_interval,v_interval,bbox[u_span_index-1][v_span_index-1], false)) {
std::cerr << "Error computing bounding box for surface interval" << std::endl;
}
}
}
} else {
prev_surface = NULL;
}
}
if (prev_surface == surf) {
if (quadrant == 0) {
for (int u_span_index = 1; u_span_index < u_spancnt + 1;
u_span_index++) {
for (int v_span_index = 1; v_span_index < v_spancnt + 1;
v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
if (current_distance < within_distance_tol) {
rc = true;
goto cleanup;
}
} else if (quadrant == 1) {
if (surf->IsClosed(0)) { //NE,SE,NW.SW
// 1 from NE quadrant
for (int u_span_index = umid_index+1; u_span_index < u_spancnt + 1; u_span_index++) {
for (int v_span_index = vmid_index+1; v_span_index < v_spancnt + 1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
// 4 from SE quadrant
for (int u_span_index = umid_index+1; u_span_index < u_spancnt + 1; u_span_index++) {
for (int v_span_index = 1; v_span_index < vmid_index+1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
// 2 from NW quadrant
for (int u_span_index = 1; u_span_index < umid_index+1; u_span_index++) {
for (int v_span_index = vmid_index+1; v_span_index < v_spancnt + 1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
// 3 from SW quadrant
for (int u_span_index = 1; u_span_index < umid_index+1; u_span_index++) {
for (int v_span_index = 1; v_span_index < vmid_index+1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
} else { //NE,NW,SW,SE
// 1 from NE quadrant
for (int u_span_index = umid_index+1; u_span_index < u_spancnt + 1; u_span_index++) {
for (int v_span_index = vmid_index+1; v_span_index < v_spancnt + 1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
// 2 from NW quadrant
for (int u_span_index = 1; u_span_index < umid_index+1; u_span_index++) {
for (int v_span_index = vmid_index+1; v_span_index < v_spancnt + 1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
// 3 from SW quadrant
for (int u_span_index = 1; u_span_index < umid_index+1; u_span_index++) {
for (int v_span_index = 1; v_span_index < vmid_index+1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
// 4 from SE quadrant
for (int u_span_index = umid_index+1; u_span_index < u_spancnt + 1; u_span_index++) {
for (int v_span_index = 1; v_span_index < vmid_index+1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
}
if (current_distance < within_distance_tol) {
rc = true;
goto cleanup;
}
} else if (quadrant == 2) {
if (surf->IsClosed(0)) { // NW,SW,NE,SE
// 2 from NW quadrant
for (int u_span_index = 1; u_span_index < umid_index+1; u_span_index++) {
for (int v_span_index = vmid_index+1; v_span_index < v_spancnt + 1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
// 3 from SW quadrant
for (int u_span_index = 1; u_span_index < umid_index+1; u_span_index++) {
for (int v_span_index = 1; v_span_index < vmid_index+1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
// 1 from NE quadrant
for (int u_span_index = umid_index+1; u_span_index < u_spancnt + 1; u_span_index++) {
for (int v_span_index = vmid_index+1; v_span_index < v_spancnt + 1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
// 4 from SE quadrant
for (int u_span_index = umid_index+1; u_span_index < u_spancnt + 1; u_span_index++) {
for (int v_span_index = 1; v_span_index < vmid_index+1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
} else { // NW,NE,SW,SE
// 2 from NW quadrant
for (int u_span_index = 1; u_span_index < umid_index+1; u_span_index++) {
for (int v_span_index = vmid_index+1; v_span_index < v_spancnt + 1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
// 1 from NE quadrant
for (int u_span_index = umid_index+1; u_span_index < u_spancnt + 1; u_span_index++) {
for (int v_span_index = vmid_index+1; v_span_index < v_spancnt + 1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
// 3 from SW quadrant
for (int u_span_index = 1; u_span_index < umid_index+1; u_span_index++) {
for (int v_span_index = 1; v_span_index < vmid_index+1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
// 4 from SE quadrant
for (int u_span_index = umid_index+1; u_span_index < u_spancnt + 1; u_span_index++) {
for (int v_span_index = 1; v_span_index < vmid_index+1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
}
if (current_distance < within_distance_tol) {
rc = true;
goto cleanup;
}
} else if (quadrant == 3) {
if (surf->IsClosed(0)) { // SW,NW,SE,NE
// 3 from SW quadrant
for (int u_span_index = 1; u_span_index < umid_index+1; u_span_index++) {
for (int v_span_index = 1; v_span_index < vmid_index+1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
// 2 from NW quadrant
for (int u_span_index = 1; u_span_index < umid_index+1; u_span_index++) {
for (int v_span_index = vmid_index+1; v_span_index < v_spancnt + 1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
// 4 from SE quadrant
for (int u_span_index = umid_index+1; u_span_index < u_spancnt + 1; u_span_index++) {
for (int v_span_index = 1; v_span_index < vmid_index+1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
// 1 from NE quadrant
for (int u_span_index = umid_index+1; u_span_index < u_spancnt + 1; u_span_index++) {
for (int v_span_index = vmid_index+1; v_span_index < v_spancnt + 1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
} else { // SW,SE,NW,NE
// 3 from SW quadrant
for (int u_span_index = 1; u_span_index < umid_index+1; u_span_index++) {
for (int v_span_index = 1; v_span_index < vmid_index+1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
// 4 from SE quadrant
for (int u_span_index = umid_index+1; u_span_index < u_spancnt + 1; u_span_index++) {
for (int v_span_index = 1; v_span_index < vmid_index+1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
// 2 from NW quadrant
for (int u_span_index = 1; u_span_index < umid_index+1; u_span_index++) {
for (int v_span_index = vmid_index+1; v_span_index < v_spancnt + 1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
// 1 from NE quadrant
for (int u_span_index = umid_index+1; u_span_index < u_spancnt + 1; u_span_index++) {
for (int v_span_index = vmid_index+1; v_span_index < v_spancnt + 1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
}
if (current_distance < within_distance_tol) {
rc = true;
goto cleanup;
}
} else if (quadrant == 4) {
if (surf->IsClosed(0)) { // SE,NE,SW,NW
// 4 from SE quadrant
for (int u_span_index = umid_index+1; u_span_index < u_spancnt + 1; u_span_index++) {
for (int v_span_index = 1; v_span_index < vmid_index+1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
// 1 from NE quadrant
for (int u_span_index = umid_index+1; u_span_index < u_spancnt + 1; u_span_index++) {
for (int v_span_index = vmid_index+1; v_span_index < v_spancnt + 1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
// 3 from SW quadrant
for (int u_span_index = 1; u_span_index < umid_index+1; u_span_index++) {
for (int v_span_index = 1; v_span_index < vmid_index+1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
// 2 from NW quadrant
for (int u_span_index = 1; u_span_index < umid_index+1; u_span_index++) {
for (int v_span_index = vmid_index+1; v_span_index < v_spancnt + 1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
} else { // SE,SW,NE,NW
// 4 from SE quadrant
for (int u_span_index = umid_index+1; u_span_index < u_spancnt + 1; u_span_index++) {
for (int v_span_index = 1; v_span_index < vmid_index+1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
// 3 from SW quadrant
for (int u_span_index = 1; u_span_index < umid_index+1; u_span_index++) {
for (int v_span_index = 1; v_span_index < vmid_index+1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
// 1 from NE quadrant
for (int u_span_index = umid_index+1; u_span_index < u_spancnt + 1; u_span_index++) {
for (int v_span_index = vmid_index+1; v_span_index < v_spancnt + 1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
// 2 from NW quadrant
for (int u_span_index = 1; u_span_index < umid_index+1; u_span_index++) {
for (int v_span_index = vmid_index+1; v_span_index < v_spancnt + 1; v_span_index++) {
ON_Interval u_interval(uspan[u_span_index - 1],
uspan[u_span_index]);
ON_Interval v_interval(vspan[v_span_index - 1],
vspan[v_span_index]);
double min_distance,max_distance;
int level = 1;
if (surface_GetIntervalMinMaxDistance(p,bbox[u_span_index-1][v_span_index-1],min_distance,max_distance)) {
if ((min_distance < current_distance) && NEAR_ZERO(min_distance,within_distance_tol)) {
/////////////////////////////////////////
// Could check normals and CV angles here
/////////////////////////////////////////
double distance = surface_GetClosestPoint3dFirstOrderSubdivision(surf,p,u_interval,u_interval.Mid(),v_interval,v_interval.Mid(),current_distance,p2d,p3d,same_point_tol,within_distance_tol,level++);
if (distance < current_distance) {
current_distance = distance;
if (current_distance < same_point_tol) {
rc = true;
goto cleanup;
}
}
}
}
}
}
}
if (current_distance < within_distance_tol) {
rc = true;
goto cleanup;
}
}
}
cleanup:
std::cerr.precision(prec);
return rc;
}
bool trim_GetClosestPoint3dFirstOrder(
const ON_BrepTrim& trim,
const ON_3dPoint& p,
ON_2dPoint& p2d,
double& t,
double& distance,
const ON_Interval* interval,
double same_point_tol,
double within_distance_tol
)
{
bool rc = false;
const ON_Surface *surf = trim.SurfaceOf();
double t0 = interval->Mid();
ON_3dPoint p3d;
ON_3dPoint p0;
ON_3dVector ds,dt,dss,dst,dtt;
ON_3dVector T,K;
int prec = std::cerr.precision();
ON_BoundingBox tight_bbox;
std::vector<ON_BoundingBox> bbox;
std::cerr.precision(15);
ON_Curve *c = trim.Brep()->m_C2[trim.m_c2i];
ON_NurbsCurve N;
if ( 0 == c->GetNurbForm(N) )
return false;
if ( N.m_order < 2 || N.m_cv_count < N.m_order )
return false;
p2d = trim.PointAt(t);
int quadrant = 0; // optional - determines which quadrant to evaluate from
// 0 = default
// 1 from NE quadrant
// 2 from NW quadrant
// 3 from SW quadrant
// 4 from SE quadrant
ON_Interval u_interval = surf->Domain(0);
ON_Interval v_interval = surf->Domain(1);
if (p2d.y > v_interval.Mid()) {
// North quadrants -> 1 or 2;
if (p2d.x > u_interval.Mid()) {
quadrant = 1; // NE
} else {
quadrant = 2; //NW
}
} else {
// South quadrants -> 3 or 4;
if (p2d.x > u_interval.Mid()) {
quadrant = 4; // SE
} else {
quadrant = 3; //SW
}
}
if (surface_GetClosestPoint3dFirstOrder(surf,p,p2d,p3d,distance,quadrant,same_point_tol,within_distance_tol)) {
ON_BezierCurve B;
bool bGrowBox = false;
ON_3dVector d1,d2;
double max_dist_to_closest_pt = DBL_MAX;
ON_Interval *span_interval = new ON_Interval[N.m_cv_count - N.m_order + 1];
double *min_distance = new double[N.m_cv_count - N.m_order + 1];
double *max_distance = new double[N.m_cv_count - N.m_order + 1];
bool *skip = new bool[N.m_cv_count - N.m_order + 1];
bbox.resize(N.m_cv_count - N.m_order + 1);
for ( int span_index = 0; span_index <= N.m_cv_count - N.m_order; span_index++ )
{
skip[span_index] = true;
if ( !(N.m_knot[span_index + N.m_order-2] < N.m_knot[span_index + N.m_order-1]) )
continue;
// check for span out of interval
int i = (interval->m_t[0] <= interval->m_t[1]) ? 0 : 1;
if ( N.m_knot[span_index + N.m_order-2] > interval->m_t[1-i] )
continue;
if ( N.m_knot[span_index + N.m_order-1] < interval->m_t[i] )
continue;
if ( !N.ConvertSpanToBezier( span_index, B ) )
continue;
ON_Interval bi = B.Domain();
if ( !B.GetTightBoundingBox(tight_bbox,bGrowBox,NULL) )
continue;
bbox[span_index] = tight_bbox;
d1 = tight_bbox.m_min - p2d;
d2 = tight_bbox.m_max - p2d;
min_distance[span_index] = tight_bbox.MinimumDistanceTo(p2d);
if (min_distance[span_index] > max_dist_to_closest_pt) {
max_distance[span_index] = DBL_MAX;
continue;
}
skip[span_index] = false;
span_interval[span_index].m_t[0] = ((N.m_knot[span_index + N.m_order-2]) < interval->m_t[i]) ? interval->m_t[i] : N.m_knot[span_index + N.m_order-2];
span_interval[span_index].m_t[1] = ((N.m_knot[span_index + N.m_order-1]) > interval->m_t[1 -i]) ? interval->m_t[1 -i] : (N.m_knot[span_index + N.m_order-1]);
ON_3dPoint d1sq(d1.x*d1.x,d1.y*d1.y,0.0),d2sq(d2.x*d2.x,d2.y*d2.y,0.0);
double distancesq;
if (d1sq.x < d2sq.x) {
if (d1sq.y < d2sq.y) {
if ((d1sq.x + d2sq.y) < (d2sq.x + d1sq.y)) {
distancesq = d1sq.x + d2sq.y;
} else {
distancesq = d2sq.x + d1sq.y;
}
} else {
if ((d1sq.x + d1sq.y) < (d2sq.x + d2sq.y)) {
distancesq = d1sq.x + d1sq.y;
} else {
distancesq = d2sq.x + d2sq.y;
}
}
} else {
if (d1sq.y < d2sq.y) {
if ((d1sq.x + d1sq.y) < (d2sq.x + d2sq.y)) {
distancesq = d1sq.x + d1sq.y;
} else {
distancesq = d2sq.x + d2sq.y;
}
} else {
if ((d1sq.x + d2sq.y) < (d2sq.x + d1sq.y)) {
distancesq = d1sq.x + d2sq.y;
} else {
distancesq = d2sq.x + d1sq.y;
}
}
}
max_distance[span_index] = sqrt(distancesq);
if (max_distance[span_index] < max_dist_to_closest_pt) {
max_dist_to_closest_pt = max_distance[span_index];
}
if (max_distance[span_index] < min_distance[span_index]) {
// should only be here for near equal fuzz
min_distance[span_index] = max_distance[span_index];
}
}
for ( int span_index = 0; span_index <= N.m_cv_count - N.m_order; span_index++ )
{
if ( skip[span_index] )
continue;
if (min_distance[span_index] > max_dist_to_closest_pt) {
skip[span_index] = true;
continue;
}
}
ON_3dPoint q;
ON_3dPoint point;
double closest_distance = DBL_MAX;
double closestT = DBL_MAX;
for ( int span_index = 0; span_index <= N.m_cv_count - N.m_order; span_index++ )
{
if (skip[span_index]) {
continue;
}
t0 = span_interval[span_index].Mid();
bool closestfound = false;
bool notdone = true;
double distance = DBL_MAX;
double previous_distance = DBL_MAX;
ON_3dVector firstDervative, secondDervative;
while (notdone
&& trim.Ev2Der(t0, point, firstDervative, secondDervative)
&& ON_EvCurvature(firstDervative, secondDervative, T, K)) {
ON_Line line(point, point + 100.0 * T);
q = line.ClosestPointTo(p2d);
double delta_t = (firstDervative * (q - point))
/ (firstDervative * firstDervative);
double new_t0 = t0 + delta_t;
if (!span_interval[span_index].Includes(new_t0, false)) {
// limit to interval
int i = (span_interval[span_index].m_t[0] <= span_interval[span_index].m_t[1]) ? 0 : 1;
new_t0 =
(new_t0 < span_interval[span_index].m_t[i]) ?
span_interval[span_index].m_t[i] : span_interval[span_index].m_t[1 - i];
}
delta_t = new_t0 - t0;
t0 = new_t0;
point = trim.PointAt(t0);
distance = point.DistanceTo(p2d);
if (distance < previous_distance) {
closestfound = true;
closestT = t0;
previous_distance = distance;
if (fabs(delta_t) < same_point_tol) {
notdone = false;
}
} else {
notdone = false;
}
}
if (closestfound && (distance < closest_distance)) {
closest_distance = distance;
rc = true;
t = closestT;
}
}
delete [] span_interval;
delete [] min_distance;
delete [] max_distance;
delete [] skip;
}
std::cerr.precision(prec);
return rc;
}
bool
toUV(PBCData& data, ON_2dPoint& out_pt, double t, double knudge = 0.0)
{
ON_3dPoint pointOnCurve = data.curve->PointAt(t);
ON_3dPoint knudgedPointOnCurve = data.curve->PointAt(t + knudge);
ON_2dPoint uv;
if (data.surftree->getSurfacePoint((const ON_3dPoint&)pointOnCurve, uv, (const ON_3dPoint&)knudgedPointOnCurve, BREP_EDGE_MISS_TOLERANCE) > 0) {
out_pt.Set(uv.x, uv.y);
return true;
} else {
return false;
}
}
bool
toUV(brlcad::SurfaceTree *surftree, const ON_Curve *curve, ON_2dPoint& out_pt, double t, double knudge = 0.0)
{
if (!surftree)
return false;
const ON_Surface *surf = surftree->getSurface();
if (!surf)
return false;
ON_3dPoint pointOnCurve = curve->PointAt(t);
ON_3dPoint knudgedPointOnCurve = curve->PointAt(t + knudge);
ON_3dVector dt;
curve->Ev1Der(t, pointOnCurve, dt);
ON_3dVector tangent = curve->TangentAt(t);
//data.surf->GetClosestPoint(pointOnCurve, &a, &b, 0.0001);
ON_Ray r(pointOnCurve, tangent);
plane_ray pr;
brep_get_plane_ray(r, pr);
ON_3dVector p1;
double p1d;
ON_3dVector p2;
double p2d;
utah_ray_planes(r, p1, p1d, p2, p2d);
VMOVE(pr.n1, p1);
pr.d1 = p1d;
VMOVE(pr.n2, p2);
pr.d2 = p2d;
try {
pt2d_t uv;
ON_2dPoint uv2d = surftree->getClosestPointEstimate(knudgedPointOnCurve);
move(uv, uv2d);
ON_3dVector dir = surf->NormalAt(uv[0], uv[1]);
dir.Reverse();
ON_Ray ray(pointOnCurve, dir);
brep_get_plane_ray(ray, pr);
//know use this as guess to iterate to closer solution
pt2d_t Rcurr;
pt2d_t new_uv;
ON_3dPoint pt;
ON_3dVector su, sv;
#ifdef SHOW_UNUSED
bool found = false;
#endif
fastf_t Dlast = MAX_FASTF;
for (int i = 0; i < 10; i++) {
brep_r(surf, pr, uv, pt, su, sv, Rcurr);
fastf_t d = v2mag(Rcurr);
if (d < BREP_INTERSECTION_ROOT_EPSILON) {
TRACE1("R:" << ON_PRINT2(Rcurr));
#ifdef SHOW_UNUSED
found = true;
break;
#endif
} else if (d > Dlast) {
#ifdef SHOW_UNUSED
found = false; //break;
#endif
break;
//return brep_edge_check(found, sbv, face, surf, ray, hits);
}
brep_newton_iterate(pr, Rcurr, su, sv, uv, new_uv);
move(uv, new_uv);
Dlast = d;
}
///////////////////////////////////////
out_pt.Set(uv[0], uv[1]);
return true;
} catch (...) {
return false;
}
}
double
randomPointFromRange(PBCData& data, ON_2dPoint& out, double lo, double hi)
{
assert(lo < hi);
double random_pos = drand48() * (RANGE_HI - RANGE_LO) + RANGE_LO;
double newt = random_pos * (hi - lo) + lo;
assert(toUV(data, out, newt));
return newt;
}
bool
sample(PBCData& data,
double t1,
double t2,
const ON_2dPoint& p1,
const ON_2dPoint& p2)
{
ON_2dPoint m;
double t = randomPointFromRange(data, m, t1, t2);
if (!data.segments.empty()) {
ON_2dPointArray * samples = data.segments.back();
if (isFlat(p1, m, p2, data.flatness)) {
samples->Append(p2);
} else {
sample(data, t1, t, p1, m);
sample(data, t, t2, m, p2);
}
return true;
}
return false;
}
void
generateKnots(BSpline& bspline)
{
int num_knots = bspline.m + 1;
bspline.knots.resize(num_knots);
for (int i = 0; i <= bspline.p; i++) {
bspline.knots[i] = 0.0;
}
for (int i = bspline.m - bspline.p; i <= bspline.m; i++) {
bspline.knots[i] = 1.0;
}
for (int i = 1; i <= bspline.n - bspline.p; i++) {
bspline.knots[bspline.p + i] = (double)i / (bspline.n - bspline.p + 1.0);
}
}
int
getKnotInterval(BSpline& bspline, double u)
{
int k = 0;
while (u >= bspline.knots[k]) k++;
k = (k == 0) ? k : k - 1;
return k;
}
ON_NurbsCurve*
interpolateLocalCubicCurve(ON_2dPointArray &Q)
{
int num_samples = Q.Count();
int num_segments = Q.Count() - 1;
int qsize = num_samples + 4;
std::vector < ON_2dVector > qarray(qsize);
for (int i = 1; i < Q.Count(); i++) {
qarray[i + 1] = Q[i] - Q[i - 1];
}
qarray[1] = 2.0 * qarray[2] - qarray[3];
qarray[0] = 2.0 * qarray[1] - qarray[2];
qarray[num_samples + 1] = 2 * qarray[num_samples] - qarray[num_samples - 1];
qarray[num_samples + 2] = 2 * qarray[num_samples + 1] - qarray[num_samples];
qarray[num_samples + 3] = 2 * qarray[num_samples + 2] - qarray[num_samples + 1];
std::vector < ON_2dVector > T(num_samples);
std::vector<double> A(num_samples);
for (int k = 0; k < num_samples; k++) {
ON_3dVector a = ON_CrossProduct(qarray[k], qarray[k + 1]);
ON_3dVector b = ON_CrossProduct(qarray[k + 2], qarray[k + 3]);
double alength = a.Length();
if (NEAR_ZERO(alength, PBC_TOL)) {
A[k] = 1.0;
} else {
A[k] = (a.Length()) / (a.Length() + b.Length());
}
T[k] = (1.0 - A[k]) * qarray[k + 1] + A[k] * qarray[k + 2];
T[k].Unitize();
}
std::vector < ON_2dPointArray > P(num_samples - 1);
ON_2dPointArray control_points;
control_points.Append(Q[0]);
for (int i = 1; i < num_samples; i++) {
ON_2dPoint P0 = Q[i - 1];
ON_2dPoint P3 = Q[i];
ON_2dVector T0 = T[i - 1];
ON_2dVector T3 = T[i];
double a, b, c;
ON_2dVector vT0T3 = T0 + T3;
ON_2dVector dP0P3 = P3 - P0;
a = 16.0 - vT0T3.Length() * vT0T3.Length();
b = 12.0 * (dP0P3 * vT0T3);
c = -36.0 * dP0P3.Length() * dP0P3.Length();
double alpha = (-b + sqrt(b * b - 4.0 * a * c)) / (2.0 * a);
ON_2dPoint P1 = P0 + (1.0 / 3.0) * alpha * T0;
control_points.Append(P1);
ON_2dPoint P2 = P3 - (1.0 / 3.0) * alpha * T3;
control_points.Append(P2);
P[i - 1].Append(P0);
P[i - 1].Append(P1);
P[i - 1].Append(P2);
P[i - 1].Append(P3);
}
control_points.Append(Q[num_samples - 1]);
std::vector<double> u(num_segments + 1);
u[0] = 0.0;
for (int k = 0; k < num_segments; k++) {
u[k + 1] = u[k] + 3.0 * (P[k][1] - P[k][0]).Length();
}
int degree = 3;
int n = control_points.Count();
int p = degree;
int m = n + p - 1;
int dimension = 2;
ON_NurbsCurve* c = ON_NurbsCurve::New(dimension, false, degree + 1, n);
c->ReserveKnotCapacity(m);
for (int i = 0; i < degree; i++) {
c->SetKnot(i, 0.0);
}
for (int i = 1; i < num_segments; i++) {
double knot_value = u[i] / u[num_segments];
c->SetKnot(degree + 2 * (i - 1), knot_value);
c->SetKnot(degree + 2 * (i - 1) + 1, knot_value);
}
for (int i = m - p; i < m; i++) {
c->SetKnot(i, 1.0);
}
// insert the control points
for (int i = 0; i < n; i++) {
ON_3dPoint pnt = control_points[i];
c->SetCV(i, pnt);
}
return c;
}
ON_NurbsCurve*
interpolateLocalCubicCurve(const ON_3dPointArray &Q)
{
int num_samples = Q.Count();
int num_segments = Q.Count() - 1;
int qsize = num_samples + 3;
std::vector<ON_3dVector> qarray(qsize + 1);
ON_3dVector *q = &qarray[1];
for (int i = 1; i < Q.Count(); i++) {
q[i] = Q[i] - Q[i - 1];
}
q[0] = 2.0 * q[1] - q[2];
q[-1] = 2.0 * q[0] - q[1];
q[num_samples] = 2 * q[num_samples - 1] - q[num_samples - 2];
q[num_samples + 1] = 2 * q[num_samples] - q[num_samples - 1];
q[num_samples + 2] = 2 * q[num_samples + 1] - q[num_samples];
std::vector<ON_3dVector> T(num_samples);
std::vector<double> A(num_samples);
for (int k = 0; k < num_samples; k++) {
ON_3dVector avec = ON_CrossProduct(q[k - 1], q[k]);
ON_3dVector bvec = ON_CrossProduct(q[k + 1], q[k + 2]);
double alength = avec.Length();
if (NEAR_ZERO(alength, PBC_TOL)) {
A[k] = 1.0;
} else {
A[k] = (avec.Length()) / (avec.Length() + bvec.Length());
}
T[k] = (1.0 - A[k]) * q[k] + A[k] * q[k + 1];
T[k].Unitize();
}
std::vector<ON_3dPointArray> P(num_samples - 1);
ON_3dPointArray control_points;
control_points.Append(Q[0]);
for (int i = 1; i < num_samples; i++) {
ON_3dPoint P0 = Q[i - 1];
ON_3dPoint P3 = Q[i];
ON_3dVector T0 = T[i - 1];
ON_3dVector T3 = T[i];
double a, b, c;
ON_3dVector vT0T3 = T0 + T3;
ON_3dVector dP0P3 = P3 - P0;
a = 16.0 - vT0T3.Length() * vT0T3.Length();
b = 12.0 * (dP0P3 * vT0T3);
c = -36.0 * dP0P3.Length() * dP0P3.Length();
double alpha = (-b + sqrt(b * b - 4.0 * a * c)) / (2.0 * a);
ON_3dPoint P1 = P0 + (1.0 / 3.0) * alpha * T0;
control_points.Append(P1);
ON_3dPoint P2 = P3 - (1.0 / 3.0) * alpha * T3;
control_points.Append(P2);
P[i - 1].Append(P0);
P[i - 1].Append(P1);
P[i - 1].Append(P2);
P[i - 1].Append(P3);
}
control_points.Append(Q[num_samples - 1]);
std::vector<double> u(num_segments + 1);
u[0] = 0.0;
for (int k = 0; k < num_segments; k++) {
u[k + 1] = u[k] + 3.0 * (P[k][1] - P[k][0]).Length();
}
int degree = 3;
int n = control_points.Count();
int p = degree;
int m = n + p - 1;
int dimension = 3;
ON_NurbsCurve* c = ON_NurbsCurve::New(dimension, false, degree + 1, n);
c->ReserveKnotCapacity(m);
for (int i = 0; i < degree; i++) {
c->SetKnot(i, 0.0);
}
for (int i = 1; i < num_segments; i++) {
double knot_value = u[i] / u[num_segments];
c->SetKnot(degree + 2 * (i - 1), knot_value);
c->SetKnot(degree + 2 * (i - 1) + 1, knot_value);
}
for (int i = m - p; i < m; i++) {
c->SetKnot(i, 1.0);
}
// insert the control points
for (int i = 0; i < n; i++) {
ON_3dPoint pnt = control_points[i];
c->SetCV(i, pnt);
}
return c;
}
ON_NurbsCurve*
newNURBSCurve(BSpline& spline, int dimension = 3)
{
// we now have everything to complete our spline
ON_NurbsCurve* c = ON_NurbsCurve::New(dimension,
false,
spline.p + 1,
spline.n + 1);
c->ReserveKnotCapacity(spline.knots.size() - 2);
for (unsigned int i = 1; i < spline.knots.size() - 1; i++) {
c->m_knot[i - 1] = spline.knots[i];
}
for (int i = 0; i < spline.controls.Count(); i++) {
c->SetCV(i, ON_3dPoint(spline.controls[i]));
}
return c;
}
ON_Curve*
interpolateCurve(ON_2dPointArray &samples)
{
ON_NurbsCurve* nurbs;
if (samples.Count() == 2)
// build a line
return new ON_LineCurve(samples[0], samples[1]);
// local vs. global interpolation for large point sampled curves
nurbs = interpolateLocalCubicCurve(samples);
return nurbs;
}
int
IsAtSeam(const ON_Surface *surf, int dir, double u, double v, double tol)
{
int rc = 0;
if (!surf->IsClosed(dir))
return rc;
double p = (dir) ? v : u;
if (NEAR_EQUAL(p, surf->Domain(dir)[0], tol) || NEAR_EQUAL(p, surf->Domain(dir)[1], tol))
rc += (dir + 1);
return rc;
}
/*
* Similar to openNURBS's surf->IsAtSeam() function but uses tolerance to do a near check versus
* the floating point equality used by openNURBS.
* rc = 0 Not on seam, 1 on East/West seam(umin/umax), 2 on North/South seam(vmin/vmax), 3 seam on both U/V boundaries
*/
int
IsAtSeam(const ON_Surface *surf, double u, double v, double tol)
{
int rc = 0;
int i;
for (i = 0; i < 2; i++) {
rc += IsAtSeam(surf, i, u, v, tol);
}
return rc;
}
int
IsAtSeam(const ON_Surface *surf, int dir, const ON_2dPoint &pt, double tol)
{
int rc = 0;
ON_2dPoint unwrapped_pt = UnwrapUVPoint(surf,pt,tol);
rc = IsAtSeam(surf,dir,unwrapped_pt.x,unwrapped_pt.y,tol);
return rc;
}
/*
* Similar to IsAtSeam(surf,u,v,tol) function but takes a ON_2dPoint
* and unwraps any closed seam extents before passing on IsAtSeam(surf,u,v,tol)
*/
int
IsAtSeam(const ON_Surface *surf, const ON_2dPoint &pt, double tol)
{
int rc = 0;
ON_2dPoint unwrapped_pt = UnwrapUVPoint(surf,pt,tol);
rc = IsAtSeam(surf,unwrapped_pt.x,unwrapped_pt.y,tol);
return rc;
}
int
IsAtSingularity(const ON_Surface *surf, double u, double v, double tol)
{
// 0 = south, 1 = east, 2 = north, 3 = west
//std::cerr << "IsAtSingularity = u, v - " << u << ", " << v << std::endl;
//std::cerr << "surf->Domain(0) - " << surf->Domain(0)[0] << ", " << surf->Domain(0)[1] << std::endl;
//std::cerr << "surf->Domain(1) - " << surf->Domain(1)[0] << ", " << surf->Domain(1)[1] << std::endl;
if (NEAR_EQUAL(u, surf->Domain(0)[0], tol)) {
if (surf->IsSingular(3))
return 3;
} else if (NEAR_EQUAL(u, surf->Domain(0)[1], tol)) {
if (surf->IsSingular(1))
return 1;
}
if (NEAR_EQUAL(v, surf->Domain(1)[0], tol)) {
if (surf->IsSingular(0))
return 0;
} else if (NEAR_EQUAL(v, surf->Domain(1)[1], tol)) {
if (surf->IsSingular(2))
return 2;
}
return -1;
}
int
IsAtSingularity(const ON_Surface *surf, const ON_2dPoint &pt, double tol)
{
int rc = 0;
ON_2dPoint unwrapped_pt = UnwrapUVPoint(surf,pt,tol);
rc = IsAtSingularity(surf,unwrapped_pt.x,unwrapped_pt.y,tol);
return rc;
}
ON_2dPointArray *
pullback_samples(PBCData* data,
double t,
double s)
{
if (!data)
return NULL;
const ON_Curve* curve = data->curve;
const ON_Surface* surf = data->surf;
ON_2dPointArray *samples = new ON_2dPointArray();
int numKnots = curve->SpanCount();
double *knots = new double[numKnots + 1];
curve->GetSpanVector(knots);
int istart = 0;
while (t >= knots[istart])
istart++;
if (istart > 0) {
istart--;
knots[istart] = t;
}
int istop = numKnots;
while (s <= knots[istop])
istop--;
if (istop < numKnots) {
istop++;
knots[istop] = s;
}
int samplesperknotinterval;
int degree = curve->Degree();
if (degree > 1) {
samplesperknotinterval = 3 * degree;
} else {
samplesperknotinterval = 18 * degree;
}
ON_2dPoint pt;
ON_3dPoint p = ON_3dPoint::UnsetPoint;
ON_3dPoint p3d = ON_3dPoint::UnsetPoint;
double distance;
for (int i = istart; i <= istop; i++) {
if (i <= numKnots / 2) {
if (i > 0) {
double delta = (knots[i] - knots[i - 1]) / (double) samplesperknotinterval;
for (int j = 1; j < samplesperknotinterval; j++) {
p = curve->PointAt(knots[i - 1] + j * delta);
p3d = ON_3dPoint::UnsetPoint;
if (surface_GetClosestPoint3dFirstOrder(surf,p,pt,p3d,distance,0,BREP_SAME_POINT_TOLERANCE,BREP_EDGE_MISS_TOLERANCE)) {
samples->Append(pt);
}
}
}
p = curve->PointAt(knots[i]);
p3d = ON_3dPoint::UnsetPoint;
if (surface_GetClosestPoint3dFirstOrder(surf,p,pt,p3d,distance,0,BREP_SAME_POINT_TOLERANCE,BREP_EDGE_MISS_TOLERANCE)) {
samples->Append(pt);
}
} else {
if (i > 0) {
double delta = (knots[i] - knots[i - 1]) / (double) samplesperknotinterval;
for (int j = 1; j < samplesperknotinterval; j++) {
p = curve->PointAt(knots[i - 1] + j * delta);
p3d = ON_3dPoint::UnsetPoint;
if (surface_GetClosestPoint3dFirstOrder(surf,p,pt,p3d,distance,0,BREP_SAME_POINT_TOLERANCE,BREP_EDGE_MISS_TOLERANCE)) {
samples->Append(pt);
}
}
p = curve->PointAt(knots[i]);
p3d = ON_3dPoint::UnsetPoint;
if (surface_GetClosestPoint3dFirstOrder(surf,p,pt,p3d,distance,0,BREP_SAME_POINT_TOLERANCE,BREP_EDGE_MISS_TOLERANCE)) {
samples->Append(pt);
}
}
}
}
delete[] knots;
return samples;
}
/*
* Unwrap 2D UV point values to within actual surface UV. Points often wrap around the closed seam.
*/
ON_2dPoint
UnwrapUVPoint(const ON_Surface *surf,const ON_2dPoint &pt, double tol)
{
ON_2dPoint p = pt;
for (int i=0; i<2; i++) {
if (!surf->IsClosed(i))
continue;
while (p[i] < surf->Domain(i).m_t[0] - tol) {
double length = surf->Domain(i).Length();
if (i<=0) {
p.x = p.x + length;
} else {
p.y = p.y + length;
}
}
while (p[i] >= surf->Domain(i).m_t[1] + tol) {
double length = surf->Domain(i).Length();
if (i<=0) {
p.x = p.x - length;
} else {
p.y = p.y - length;
}
}
}
return p;
}
double
DistToNearestClosedSeam(const ON_Surface *surf,const ON_2dPoint &pt)
{
double dist = -1.0;
ON_2dPoint unwrapped_pt = UnwrapUVPoint(surf,pt);
for (int i=0; i<2; i++) {
if (!surf->IsClosed(i))
continue;
dist = fabs(unwrapped_pt[i] - surf->Domain(i)[0]);
V_MIN(dist,fabs(surf->Domain(i)[1]-unwrapped_pt[i]));
}
return dist;
}
void
GetClosestExtendedPoint(const ON_Surface *surf,ON_2dPoint &pt,ON_2dPoint &prev_pt, double tol) {
if (surf->IsClosed(0)) {
double length = surf->Domain(0).Length();
double delta=pt.x-prev_pt.x;
while (fabs(delta) > length/2.0) {
if (delta > length/2.0) {
pt.x = pt.x - length;
delta=pt.x-prev_pt.x;
} else {
pt.x = pt.x + length;
delta=pt.x - prev_pt.x;
}
}
}
if (surf->IsClosed(1)) {
double length = surf->Domain(1).Length();
double delta=pt.y-prev_pt.y;
while (fabs(delta) > length/2.0) {
if (delta > length/2.0) {
pt.y = pt.y - length;
delta=pt.y - prev_pt.y;
} else {
pt.y = pt.y + length;
delta=pt.y -prev_pt.y;
}
}
}
}
/*
* Simple check to determine if two consecutive points pulled back from 3d curve sampling
* to 2d UV parameter space crosses the seam of the closed UV. The assumption here is that
* the sampling of the 3d curve is a small fraction of the UV domain.
*
* // dir - 0 = not crossing, 1 = south/east bound, 2 = north/west bound
*/
bool
ConsecutivePointsCrossClosedSeam(const ON_Surface *surf,const ON_2dPoint &pt,const ON_2dPoint &prev_pt, int &udir, int &vdir, double tol)
{
bool rc = false;
/*
* if one of the points is at a seam then not crossing
*/
int dir =0;
ON_2dPoint unwrapped_pt = UnwrapUVPoint(surf,pt);
ON_2dPoint unwrapped_prev_pt = UnwrapUVPoint(surf,prev_pt);
if (!IsAtSeam(surf,dir,pt,tol) && !IsAtSeam(surf,dir,prev_pt,tol)) {
udir = vdir = 0;
if (surf->IsClosed(0)) {
double delta=unwrapped_pt.x-unwrapped_prev_pt.x;
if (fabs(delta) > surf->Domain(0).Length()/2.0) {
if (delta < 0.0) {
udir = 1; // east bound
} else {
udir= 2; // west bound
}
rc = true;
}
}
}
dir = 1;
if (!IsAtSeam(surf,dir,pt,tol) && !IsAtSeam(surf,dir,prev_pt,tol)) {
if (surf->IsClosed(1)) {
double delta=unwrapped_pt.y-unwrapped_prev_pt.y;
if (fabs(delta) > surf->Domain(1).Length()/2.0) {
if (delta < 0.0) {
vdir = 2; // north bound
} else {
vdir= 1; // south bound
}
rc = true;
}
}
}
return rc;
}
/*
* If within UV tolerance to a seam force force to actually seam value so surface
* seam function can be used.
*/
void
ForceToClosestSeam(const ON_Surface *surf, ON_2dPoint &pt, double tol)
{
int seam;
ON_2dPoint unwrapped_pt = UnwrapUVPoint(surf,pt,tol);
ON_2dVector wrap = ON_2dVector::ZeroVector;
ON_Interval dom[2] = { ON_Interval::EmptyInterval, ON_Interval::EmptyInterval };
double length[2] = { ON_UNSET_VALUE, ON_UNSET_VALUE};
for (int i=0; i<2; i++) {
dom[i] = surf->Domain(i);
length[i] = dom[i].Length();
if (!surf->IsClosed(i))
continue;
if (pt[i] > (dom[i].m_t[1] + tol)) {
ON_2dPoint p = pt;
while (p[i] > (dom[i].m_t[1] + tol)) {
p[i] -= length[i];
wrap[i] += 1.0;
}
} else if (pt[i] < (dom[i].m_t[0] - tol)) {
ON_2dPoint p = pt;
while (p[i] < (dom[i].m_t[0] - tol)) {
p[i] += length[i];
wrap[i] -= 1.0;
}
}
wrap[i] = wrap[i] * length[i];
}
if ((seam=IsAtSeam(surf, unwrapped_pt, tol)) > 0) {
if (seam == 1) { // east/west seam
if (fabs(unwrapped_pt.x - dom[0].m_t[0]) < length[0]/2.0) {
unwrapped_pt.x = dom[0].m_t[0]; // on east swap to west seam
} else {
unwrapped_pt.x = dom[0].m_t[1]; // on west swap to east seam
}
} else if (seam == 2) { // north/south seam
if (fabs(unwrapped_pt.y - dom[1].m_t[0]) < length[1]/2.0) {
unwrapped_pt.y = dom[1].m_t[0]; // on north swap to south seam
} else {
unwrapped_pt.y = dom[1].m_t[1]; // on south swap to north seam
}
} else { //on both seams
if (fabs(unwrapped_pt.x - dom[0].m_t[0]) < length[0]/2.0) {
unwrapped_pt.x = dom[0].m_t[0]; // on east swap to west seam
} else {
unwrapped_pt.x = dom[0].m_t[1]; // on west swap to east seam
}
if (fabs(pt.y - dom[1].m_t[0]) < length[1]/2.0) {
unwrapped_pt.y = dom[1].m_t[0]; // on north swap to south seam
} else {
unwrapped_pt.y = dom[1].m_t[1]; // on south swap to north seam
}
}
}
pt = unwrapped_pt + wrap;
}
/*
* If point lies on a seam(s) swap to opposite side of UV.
* hint = 1 swap E/W, 2 swap N/S or default 3 swap both
*/
void
SwapUVSeamPoint(const ON_Surface *surf, ON_2dPoint &p, int hint)
{
int seam;
ON_Interval dom[2];
dom[0] = surf->Domain(0);
dom[1] = surf->Domain(1);
if ((seam=surf->IsAtSeam(p.x,p.y)) > 0) {
if (seam == 1) { // east/west seam
if (fabs(p.x - dom[0].m_t[0]) > dom[0].Length()/2.0) {
p.x = dom[0].m_t[0]; // on east swap to west seam
} else {
p.x = dom[0].m_t[1]; // on west swap to east seam
}
} else if (seam == 2) { // north/south seam
if (fabs(p.y - dom[1].m_t[0]) > dom[1].Length()/2.0) {
p.y = dom[1].m_t[0]; // on north swap to south seam
} else {
p.y = dom[1].m_t[1]; // on south swap to north seam
}
} else { //on both seams check hint 1=east/west only, 2=north/south, 3 = both
if (hint == 1) {
if (fabs(p.x - dom[0].m_t[0]) > dom[0].Length()/2.0) {
p.x = dom[0].m_t[0]; // on east swap to west seam
} else {
p.x = dom[0].m_t[1]; // on west swap to east seam
}
} else if (hint == 2) {
if (fabs(p.y - dom[1].m_t[0]) > dom[1].Length()/2.0) {
p.y = dom[1].m_t[0]; // on north swap to south seam
} else {
p.y = dom[1].m_t[1]; // on south swap to north seam
}
} else {
if (fabs(p.x - dom[0].m_t[0]) > dom[0].Length()/2.0) {
p.x = dom[0].m_t[0]; // on east swap to west seam
} else {
p.x = dom[0].m_t[1]; // on west swap to east seam
}
if (fabs(p.y - dom[1].m_t[0]) > dom[1].Length()/2.0) {
p.y = dom[1].m_t[0]; // on north swap to south seam
} else {
p.y = dom[1].m_t[1]; // on south swap to north seam
}
}
}
}
}
/*
* Find where Pullback of 3d curve crosses closed seam of surface UV
*/
bool
Find3DCurveSeamCrossing(PBCData &data,double t0,double t1, double offset,double &seam_t,ON_2dPoint &from,ON_2dPoint &to,double tol)
{
bool rc = true;
const ON_Surface *surf = data.surf;
// quick bail out is surface not closed
if (surf->IsClosed(0) || surf->IsClosed(1)) {
ON_2dPoint p0_2d = ON_2dPoint::UnsetPoint;
ON_2dPoint p1_2d = ON_2dPoint::UnsetPoint;
ON_3dPoint p0_3d = data.curve->PointAt(t0);
ON_3dPoint p1_3d = data.curve->PointAt(t1);
ON_Interval dom[2];
double p0_distance;
double p1_distance;
dom[0] = surf->Domain(0);
dom[1] = surf->Domain(1);
ON_3dPoint check_pt_3d = ON_3dPoint::UnsetPoint;
int udir=0;
int vdir=0;
if (surface_GetClosestPoint3dFirstOrder(surf,p0_3d,p0_2d,check_pt_3d,p0_distance,0,BREP_SAME_POINT_TOLERANCE,BREP_EDGE_MISS_TOLERANCE) &&
surface_GetClosestPoint3dFirstOrder(surf,p1_3d,p1_2d,check_pt_3d,p1_distance,0,BREP_SAME_POINT_TOLERANCE,BREP_EDGE_MISS_TOLERANCE) ) {
if (ConsecutivePointsCrossClosedSeam(surf,p0_2d,p1_2d,udir,vdir,tol)) {
ON_2dPoint p_2d;
//lets check to see if p0 || p1 are already on a seam
int seam0=0;
if ((seam0 = IsAtSeam(surf,p0_2d, tol)) > 0) {
ForceToClosestSeam(surf, p0_2d, tol);
}
int seam1 = 0;
if ((seam1 = IsAtSeam(surf,p1_2d, tol)) > 0) {
ForceToClosestSeam(surf, p1_2d, tol);
}
if (seam0 > 0 ) {
if (seam1 > 0) { // both p0 & p1 on seam shouldn't happen report error and return false
rc = false;
} else { // just p0 on seam
from = to = p0_2d;
seam_t = t0;
SwapUVSeamPoint(surf, to);
}
} else if (seam1 > 0) { // only p1 on seam
from = to = p1_2d;
seam_t = t1;
SwapUVSeamPoint(surf, from);
} else { // crosses the seam somewhere in between the two points
bool seam_not_found = true;
while(seam_not_found) {
double d0 = DistToNearestClosedSeam(surf,p0_2d);
double d1 = DistToNearestClosedSeam(surf,p1_2d);
if ((d0 > 0.0) && (d1 > 0.0)) {
double t = t0 + (t1 - t0)*(d0/(d0+d1));
int seam;
ON_3dPoint p_3d = data.curve->PointAt(t);
double distance;
if (surface_GetClosestPoint3dFirstOrder(surf,p_3d,p_2d,check_pt_3d,distance,0,BREP_SAME_POINT_TOLERANCE,BREP_EDGE_MISS_TOLERANCE)) {
if ((seam=IsAtSeam(surf,p_2d, tol)) > 0) {
ForceToClosestSeam(surf, p_2d, tol);
from = to = p_2d;
seam_t = t;
if (p0_2d.DistanceTo(p_2d) < p1_2d.DistanceTo(p_2d)) {
SwapUVSeamPoint(surf, to);
} else {
SwapUVSeamPoint(surf, from);
}
seam_not_found=false;
rc = true;
} else {
if (ConsecutivePointsCrossClosedSeam(surf,p0_2d,p_2d,udir,vdir,tol)) {
p1_2d = p_2d;
t1 = t;
} else if (ConsecutivePointsCrossClosedSeam(surf,p_2d,p1_2d,udir,vdir,tol)) {
p0_2d = p_2d;
t0=t;
} else {
seam_not_found=false;
rc = false;
}
}
} else {
seam_not_found=false;
rc = false;
}
} else {
seam_not_found=false;
rc = false;
}
}
}
}
}
}
return rc;
}
/*
* Find where 2D trim curve crosses closed seam of surface UV
*/
bool
FindTrimSeamCrossing(const ON_BrepTrim &trim,double t0,double t1,double &seam_t,ON_2dPoint &from,ON_2dPoint &to,double tol)
{
bool rc = true;
const ON_Surface *surf = trim.SurfaceOf();
// quick bail out is surface not closed
if (surf->IsClosed(0) || surf->IsClosed(1)) {
ON_2dPoint p0 = trim.PointAt(t0);
ON_2dPoint p1 = trim.PointAt(t1);
ON_Interval dom[2];
dom[0] = surf->Domain(0);
dom[1] = surf->Domain(1);
p0 = UnwrapUVPoint(surf,p0);
p1 = UnwrapUVPoint(surf,p1);
int udir=0;
int vdir=0;
if (ConsecutivePointsCrossClosedSeam(surf,p0,p1,udir,vdir,tol)) {
ON_2dPoint p;
//lets check to see if p0 || p1 are already on a seam
int seam0=0;
if ((seam0 = IsAtSeam(surf,p0, tol)) > 0) {
ForceToClosestSeam(surf, p0, tol);
}
int seam1 = 0;
if ((seam1 = IsAtSeam(surf,p1, tol)) > 0) {
ForceToClosestSeam(surf, p1, tol);
}
if (seam0 > 0 ) {
if (seam1 > 0) { // both p0 & p1 on seam shouldn't happen report error and return false
rc = false;
} else { // just p0 on seam
from = to = p0;
seam_t = t0;
SwapUVSeamPoint(surf, to);
}
} else if (seam1 > 0) { // only p1 on seam
from = to = p1;
seam_t = t1;
SwapUVSeamPoint(surf, from);
} else { // crosses the seam somewhere in between the two points
bool seam_not_found = true;
while (seam_not_found) {
double d0 = DistToNearestClosedSeam(surf,p0);
double d1 = DistToNearestClosedSeam(surf,p1);
if ((d0 > tol) && (d1 > tol)) {
double t = t0 + (t1 - t0)*(d0/(d0+d1));
int seam;
p = trim.PointAt(t);
if ((seam=IsAtSeam(surf,p, tol)) > 0) {
ForceToClosestSeam(surf, p, tol);
from = to = p;
seam_t = t;
if (p0.DistanceTo(p) < p1.DistanceTo(p)) {
SwapUVSeamPoint(surf, to);
} else {
SwapUVSeamPoint(surf, from);
}
seam_not_found=false;
rc = true;
} else {
if (ConsecutivePointsCrossClosedSeam(surf,p0,p,udir,vdir,tol)) {
p1 = p;
t1 = t;
} else if (ConsecutivePointsCrossClosedSeam(surf,p,p1,udir,vdir,tol)) {
p0 = p;
t0=t;
} else {
seam_not_found=false;
rc = false;
}
}
} else {
seam_not_found=false;
rc = false;
}
}
}
}
}
return rc;
}
void
pullback_samples_from_closed_surface(PBCData* data,
double t,
double s)
{
if (!data)
return;
if (!data->surf || !data->curve)
return;
const ON_Curve* curve= data->curve;
const ON_Surface *surf = data->surf;
ON_2dPointArray *samples= new ON_2dPointArray();
size_t numKnots = curve->SpanCount();
double *knots = new double[numKnots+1];
curve->GetSpanVector(knots);
size_t istart = 0;
while ((istart < (numKnots+1)) && (t >= knots[istart]))
istart++;
if (istart > 0) {
knots[--istart] = t;
}
size_t istop = numKnots;
while ((istop > 0) && (s <= knots[istop]))
istop--;
if (istop < numKnots) {
knots[++istop] = s;
}
size_t degree = curve->Degree();
size_t samplesperknotinterval=18*degree;
ON_2dPoint pt;
ON_2dPoint prev_pt;
double prev_t = knots[istart];
double offset = 0.0;
double delta;
for (size_t i=istart; i<istop; i++) {
delta = (knots[i+1] - knots[i])/(double)samplesperknotinterval;
if (i <= numKnots/2) {
offset = PBC_FROM_OFFSET;
} else {
offset = -PBC_FROM_OFFSET;
}
for (size_t j=0; j<=samplesperknotinterval; j++) {
if ((j == samplesperknotinterval) && (i < istop - 1))
continue;
double curr_t = knots[i]+j*delta;
if (curr_t < (s-t)/2.0) {
offset = PBC_FROM_OFFSET;
} else {
offset = -PBC_FROM_OFFSET;
}
ON_3dPoint p = curve->PointAt(curr_t);
ON_3dPoint p3d = ON_3dPoint::UnsetPoint;
double distance;
if (surface_GetClosestPoint3dFirstOrder(surf,p,pt,p3d,distance,0,BREP_SAME_POINT_TOLERANCE,BREP_EDGE_MISS_TOLERANCE)) {
if (IsAtSeam(surf,pt,PBC_SEAM_TOL) > 0) {
ForceToClosestSeam(surf, pt, PBC_SEAM_TOL);
}
if ((i == istart) && (j == 0)) {
// first point just append and set reference in prev_pt
samples->Append(pt);
prev_pt = pt;
prev_t = curr_t;
continue;
}
int udir= 0;
int vdir= 0;
if (ConsecutivePointsCrossClosedSeam(surf,pt,prev_pt,udir,vdir,PBC_SEAM_TOL)) {
int pt_seam = surf->IsAtSeam(pt.x,pt.y);
int prev_pt_seam = surf->IsAtSeam(prev_pt.x,prev_pt.y);
if ( pt_seam > 0) {
if ((prev_pt_seam > 0) && (samples->Count() == 1)) {
samples->Empty();
SwapUVSeamPoint(surf, prev_pt,pt_seam);
samples->Append(prev_pt);
} else {
if (pt_seam == 3) {
if (prev_pt_seam == 1) {
pt.x = prev_pt.x;
if (ConsecutivePointsCrossClosedSeam(surf,pt,prev_pt,udir,vdir,PBC_SEAM_TOL)) {
SwapUVSeamPoint(surf, pt, 2);
}
} else if (prev_pt_seam == 2) {
pt.y = prev_pt.y;
if (ConsecutivePointsCrossClosedSeam(surf,pt,prev_pt,udir,vdir,PBC_SEAM_TOL)) {
SwapUVSeamPoint(surf, pt, 1);
}
}
} else {
SwapUVSeamPoint(surf, pt, prev_pt_seam);
}
}
} else if (prev_pt_seam > 0) {
if (samples->Count() == 1) {
samples->Empty();
SwapUVSeamPoint(surf, prev_pt);
samples->Append(prev_pt);
}
} else if (data->curve->IsClosed()) {
ON_2dPoint from,to;
double seam_t;
if (Find3DCurveSeamCrossing(*data,prev_t,curr_t,offset,seam_t,from,to,PBC_TOL)) {
samples->Append(from);
data->segments.push_back(samples);
samples= new ON_2dPointArray();
samples->Append(to);
prev_pt = to;
prev_t = seam_t;
} else {
std::cout << "Can not find seam crossing...." << std::endl;
}
}
}
samples->Append(pt);
prev_pt = pt;
prev_t = curr_t;
}
}
}
delete [] knots;
if (samples != NULL) {
data->segments.push_back(samples);
int numsegs = data->segments.size();
if (numsegs > 1) {
if (curve->IsClosed()) {
ON_2dPointArray *reordered_samples= new ON_2dPointArray();
// must have walked over seam but have closed curve so reorder stitching
int seg = 0;
for (std::list<ON_2dPointArray *>::reverse_iterator rit=data->segments.rbegin(); rit!=data->segments.rend(); ++seg) {
samples = *rit;
if (seg < numsegs-1) { // since end points should be repeated
reordered_samples->Append(samples->Count()-1,(const ON_2dPoint *)samples->Array());
} else {
reordered_samples->Append(samples->Count(),(const ON_2dPoint *)samples->Array());
}
data->segments.erase((++rit).base());
rit = data->segments.rbegin();
delete samples;
}
data->segments.clear();
data->segments.push_back(reordered_samples);
} else {
//punt for now
}
}
}
return;
}
PBCData *
pullback_samples(const ON_Surface* surf,
const ON_Curve* curve,
double tolerance,
double flatness)
{
if (!surf)
return NULL;
PBCData *data = new PBCData;
data->tolerance = tolerance;
data->flatness = flatness;
data->curve = curve;
data->surf = surf;
data->surftree = NULL;
double tmin, tmax;
data->curve->GetDomain(&tmin, &tmax);
if (surf->IsClosed(0) || surf->IsClosed(1)) {
if ((tmin < 0.0) && (tmax > 0.0)) {
ON_2dPoint uv = ON_2dPoint::UnsetPoint;
ON_3dPoint p = curve->PointAt(0.0);
ON_3dPoint p3d = ON_3dPoint::UnsetPoint;
double distance;
int quadrant = 0; // optional - 0 = default, 1 from NE quadrant, 2 from NW quadrant, 3 from SW quadrant, 4 from SE quadrant
if (surface_GetClosestPoint3dFirstOrder(surf,p,uv,p3d,distance,quadrant,BREP_SAME_POINT_TOLERANCE,BREP_EDGE_MISS_TOLERANCE)) {
if (IsAtSeam(surf, uv, PBC_SEAM_TOL) > 0) {
ON_2dPointArray *samples1 = pullback_samples(data, tmin, 0.0);
ON_2dPointArray *samples2 = pullback_samples(data, 0.0, tmax);
if (samples1 != NULL) {
data->segments.push_back(samples1);
}
if (samples2 != NULL) {
data->segments.push_back(samples2);
}
} else {
ON_2dPointArray *samples = pullback_samples(data, tmin, tmax);
if (samples != NULL) {
data->segments.push_back(samples);
}
}
} else {
std::cerr << "pullback_samples:Error: cannot evaluate curve at parameter 0.0" << std::endl;
delete data;
return NULL;
}
} else {
pullback_samples_from_closed_surface(data, tmin, tmax);
}
} else {
ON_2dPointArray *samples = pullback_samples(data, tmin, tmax);
if (samples != NULL) {
data->segments.push_back(samples);
}
}
return data;
}
ON_Curve*
refit_edge(const ON_BrepEdge* edge, double UNUSED(tolerance))
{
double edge_tolerance = 0.01;
ON_Brep *brep = edge->Brep();
#ifdef SHOW_UNUSED
ON_3dPoint start = edge->PointAtStart();
ON_3dPoint end = edge->PointAtEnd();
#endif
ON_BrepTrim& trim1 = brep->m_T[edge->m_ti[0]];
ON_BrepTrim& trim2 = brep->m_T[edge->m_ti[1]];
ON_BrepFace *face1 = trim1.Face();
ON_BrepFace *face2 = trim2.Face();
const ON_Surface *surface1 = face1->SurfaceOf();
const ON_Surface *surface2 = face2->SurfaceOf();
bool removeTrimmed = false;
brlcad::SurfaceTree *st1 = new brlcad::SurfaceTree(face1, removeTrimmed);
brlcad::SurfaceTree *st2 = new brlcad::SurfaceTree(face2, removeTrimmed);
ON_Curve *curve = brep->m_C3[edge->m_c3i];
double t0, t1;
curve->GetDomain(&t0, &t1);
ON_Plane plane;
curve->FrameAt(t0, plane);
#ifdef SHOW_UNUSED
ON_3dPoint origin = plane.Origin();
ON_3dVector xaxis = plane.Xaxis();
ON_3dVector yaxis = plane.Yaxis();
ON_3dVector zaxis = plane.zaxis;
ON_3dPoint px = origin + xaxis;
ON_3dPoint py = origin + yaxis;
ON_3dPoint pz = origin + zaxis;
#endif
int numKnots = curve->SpanCount();
double *knots = new double[numKnots + 1];
curve->GetSpanVector(knots);
int samplesperknotinterval;
int degree = curve->Degree();
if (degree > 1) {
samplesperknotinterval = 3 * degree;
} else {
samplesperknotinterval = 18 * degree;
}
ON_2dPoint pt;
double t = 0.0;
ON_3dPoint pointOnCurve;
ON_3dPoint knudgedPointOnCurve;
for (int i = 0; i <= numKnots; i++) {
if (i <= numKnots / 2) {
if (i > 0) {
double delta = (knots[i] - knots[i - 1]) / (double) samplesperknotinterval;
for (int j = 1; j < samplesperknotinterval; j++) {
t = knots[i - 1] + j * delta;
pointOnCurve = curve->PointAt(t);
knudgedPointOnCurve = curve->PointAt(t + PBC_TOL);
ON_3dPoint point = pointOnCurve;
ON_3dPoint knudgepoint = knudgedPointOnCurve;
ON_3dPoint ps1;
ON_3dPoint ps2;
bool found = false;
double dist;
while (!found) {
ON_2dPoint uv;
if (st1->getSurfacePoint((const ON_3dPoint&) point, uv, (const ON_3dPoint&) knudgepoint, edge_tolerance) > 0) {
ps1 = surface1->PointAt(uv.x, uv.y);
if (st2->getSurfacePoint((const ON_3dPoint&) point, uv, (const ON_3dPoint&) knudgepoint, edge_tolerance) > 0) {
ps2 = surface2->PointAt(uv.x, uv.y);
}
}
dist = ps1.DistanceTo(ps2);
if (NEAR_ZERO(dist, PBC_TOL)) {
point = ps1;
found = true;
} else {
ON_3dVector v1 = ps1 - point;
ON_3dVector v2 = ps2 - point;
knudgepoint = point;
ON_3dVector deltav = v1 + v2;
if (NEAR_ZERO(deltav.Length(), PBC_TOL)) {
found = true; // as close as we are going to get
} else {
point = point + v1 + v2;
}
}
}
}
}
t = knots[i];
pointOnCurve = curve->PointAt(t);
knudgedPointOnCurve = curve->PointAt(t + PBC_TOL);
ON_3dPoint point = pointOnCurve;
ON_3dPoint knudgepoint = knudgedPointOnCurve;
ON_3dPoint ps1;
ON_3dPoint ps2;
bool found = false;
double dist;
while (!found) {
ON_2dPoint uv;
if (st1->getSurfacePoint((const ON_3dPoint&) point, uv, (const ON_3dPoint&) knudgepoint, edge_tolerance) > 0) {
ps1 = surface1->PointAt(uv.x, uv.y);
if (st2->getSurfacePoint((const ON_3dPoint&) point, uv, (const ON_3dPoint&) knudgepoint, edge_tolerance) > 0) {
ps2 = surface2->PointAt(uv.x, uv.y);
}
}
dist = ps1.DistanceTo(ps2);
if (NEAR_ZERO(dist, PBC_TOL)) {
point = ps1;
found = true;
} else {
ON_3dVector v1 = ps1 - point;
ON_3dVector v2 = ps2 - point;
knudgepoint = point;
ON_3dVector deltav = v1 + v2;
if (NEAR_ZERO(deltav.Length(), PBC_TOL)) {
found = true; // as close as we are going to get
} else {
point = point + v1 + v2;
}
}
}
} else {
if (i > 0) {
double delta = (knots[i] - knots[i - 1]) / (double) samplesperknotinterval;
for (int j = 1; j < samplesperknotinterval; j++) {
t = knots[i - 1] + j * delta;
pointOnCurve = curve->PointAt(t);
knudgedPointOnCurve = curve->PointAt(t - PBC_TOL);
ON_3dPoint point = pointOnCurve;
ON_3dPoint knudgepoint = knudgedPointOnCurve;
ON_3dPoint ps1;
ON_3dPoint ps2;
bool found = false;
double dist;
while (!found) {
ON_2dPoint uv;
if (st1->getSurfacePoint((const ON_3dPoint&) point, uv, (const ON_3dPoint&) knudgepoint, edge_tolerance) > 0) {
ps1 = surface1->PointAt(uv.x, uv.y);
if (st2->getSurfacePoint((const ON_3dPoint&) point, uv, (const ON_3dPoint&) knudgepoint, edge_tolerance) > 0) {
ps2 = surface2->PointAt(uv.x, uv.y);
}
}
dist = ps1.DistanceTo(ps2);
if (NEAR_ZERO(dist, PBC_TOL)) {
point = ps1;
found = true;
} else {
ON_3dVector v1 = ps1 - point;
ON_3dVector v2 = ps2 - point;
knudgepoint = point;
ON_3dVector deltav = v1 + v2;
if (NEAR_ZERO(deltav.Length(), PBC_TOL)) {
found = true; // as close as we are going to get
} else {
point = point + v1 + v2;
}
}
}
}
t = knots[i];
pointOnCurve = curve->PointAt(t);
knudgedPointOnCurve = curve->PointAt(t - PBC_TOL);
ON_3dPoint point = pointOnCurve;
ON_3dPoint knudgepoint = knudgedPointOnCurve;
ON_3dPoint ps1;
ON_3dPoint ps2;
bool found = false;
double dist;
while (!found) {
ON_2dPoint uv;
if (st1->getSurfacePoint((const ON_3dPoint&) point, uv, (const ON_3dPoint&) knudgepoint, edge_tolerance) > 0) {
ps1 = surface1->PointAt(uv.x, uv.y);
if (st2->getSurfacePoint((const ON_3dPoint&) point, uv, (const ON_3dPoint&) knudgepoint, edge_tolerance) > 0) {
ps2 = surface2->PointAt(uv.x, uv.y);
}
}
dist = ps1.DistanceTo(ps2);
if (NEAR_ZERO(dist, PBC_TOL)) {
point = ps1;
found = true;
} else {
ON_3dVector v1 = ps1 - point;
ON_3dVector v2 = ps2 - point;
knudgepoint = point;
ON_3dVector deltav = v1 + v2;
if (NEAR_ZERO(deltav.Length(), PBC_TOL)) {
found = true; // as close as we are going to get
} else {
point = point + v1 + v2;
}
}
}
}
}
}
delete [] knots;
return NULL;
}
bool
has_singularity(const ON_Surface *surf)
{
bool ret = false;
if (UNLIKELY(!surf)) return ret;
// 0 = south, 1 = east, 2 = north, 3 = west
for (int i = 0; i < 4; i++) {
if (surf->IsSingular(i)) {
/*
switch (i) {
case 0:
std::cout << "Singular South" << std::endl;
break;
case 1:
std::cout << "Singular East" << std::endl;
break;
case 2:
std::cout << "Singular North" << std::endl;
break;
case 3:
std::cout << "Singular West" << std::endl;
}
*/
ret = true;
}
}
return ret;
}
bool is_closed(const ON_Surface *surf)
{
bool ret = false;
if (UNLIKELY(!surf)) return ret;
// dir 0 = "s", 1 = "t"
for (int i = 0; i < 2; i++) {
if (surf->IsClosed(i)) {
// switch (i) {
// case 0:
// std::cout << "Closed in U" << std::endl;
// break;
// case 1:
// std::cout << "Closed in V" << std::endl;
// }
ret = true;
}
}
return ret;
}
bool
check_pullback_closed(std::list<PBCData*> &pbcs)
{
std::list<PBCData*>::iterator d = pbcs.begin();
if ((*d) == NULL || (*d)->surf == NULL)
return false;
const ON_Surface *surf = (*d)->surf;
//TODO:
// 0 = U, 1 = V
if (surf->IsClosed(0) && surf->IsClosed(1)) {
//TODO: need to check how torus UV looks to determine checks
std::cerr << "Is this some kind of torus????" << std::endl;
} else if (surf->IsClosed(0)) {
//check_pullback_closed_U(pbcs);
std::cout << "check closed in U" << std::endl;
} else if (surf->IsClosed(1)) {
//check_pullback_closed_V(pbcs);
std::cout << "check closed in V" << std::endl;
}
return true;
}
bool
check_pullback_singular_east(std::list<PBCData*> &pbcs)
{
std::list<PBCData *>::iterator cs = pbcs.begin();
if ((*cs) == NULL || (*cs)->surf == NULL)
return false;
const ON_Surface *surf = (*cs)->surf;
double umin, umax;
ON_2dPoint *prev = NULL;
surf->GetDomain(0, &umin, &umax);
std::cout << "Umax: " << umax << std::endl;
while (cs != pbcs.end()) {
PBCData *data = (*cs);
std::list<ON_2dPointArray *>::iterator si = data->segments.begin();
int segcnt = 0;
while (si != data->segments.end()) {
ON_2dPointArray *samples = (*si);
std::cerr << std::endl << "Segment:" << ++segcnt << std::endl;
if (true) {
int ilast = samples->Count() - 1;
std::cerr << std::endl << 0 << "- " << (*samples)[0].x << ", " << (*samples)[0].y << std::endl;
std::cerr << ilast << "- " << (*samples)[ilast].x << ", " << (*samples)[ilast].y << std::endl;
} else {
for (int i = 0; i < samples->Count(); i++) {
if (NEAR_EQUAL((*samples)[i].x, umax, PBC_TOL)) {
if (prev != NULL) {
std::cerr << "prev - " << prev->x << ", " << prev->y << std::endl;
}
std::cerr << i << "- " << (*samples)[i].x << ", " << (*samples)[i].y << std::endl << std::endl;
}
prev = &(*samples)[i];
}
}
si ++;
}
cs++;
}
return true;
}
bool
check_pullback_singular(std::list<PBCData*> &pbcs)
{
std::list<PBCData*>::iterator d = pbcs.begin();
if ((*d) == NULL || (*d)->surf == NULL)
return false;
const ON_Surface *surf = (*d)->surf;
int cnt = 0;
for (int i = 0; i < 4; i++) {
if (surf->IsSingular(i)) {
cnt++;
}
}
if (cnt > 2) {
//TODO: I don't think this makes sense but check out
std::cerr << "Is this some kind of sickness????" << std::endl;
return false;
} else if (cnt == 2) {
if (surf->IsSingular(0) && surf->IsSingular(2)) {
std::cout << "check singular North-South" << std::endl;
} else if (surf->IsSingular(1) && surf->IsSingular(2)) {
std::cout << "check singular East-West" << std::endl;
} else {
//TODO: I don't think this makes sense but check out
std::cerr << "Is this some kind of sickness????" << std::endl;
return false;
}
} else {
if (surf->IsSingular(0)) {
std::cout << "check singular South" << std::endl;
} else if (surf->IsSingular(1)) {
std::cout << "check singular East" << std::endl;
if (check_pullback_singular_east(pbcs)) {
return true;
}
} else if (surf->IsSingular(2)) {
std::cout << "check singular North" << std::endl;
} else if (surf->IsSingular(3)) {
std::cout << "check singular West" << std::endl;
}
}
return true;
}
#ifdef _DEBUG_TESTING_
void
print_pullback_data(std::string str, std::list<PBCData*> &pbcs, bool justendpoints)
{
std::list<PBCData*>::iterator cs = pbcs.begin();
int trimcnt = 0;
if (justendpoints) {
// print out endpoints before
std::cerr << "EndPoints " << str << ":" << std::endl;
while (cs != pbcs.end()) {
PBCData *data = (*cs);
if (!data || !data->surf)
continue;
const ON_Surface *surf = data->surf;
std::list<ON_2dPointArray *>::iterator si = data->segments.begin();
int segcnt = 0;
while (si != data->segments.end()) {
ON_2dPointArray *samples = (*si);
std::cerr << std::endl << " Segment:" << ++segcnt << std::endl;
int ilast = samples->Count() - 1;
std::cerr << " T:" << ++trimcnt << std::endl;
int i = 0;
int singularity = IsAtSingularity(surf, (*samples)[i], PBC_SEAM_TOL);
int seam = IsAtSeam(surf, (*samples)[i], PBC_SEAM_TOL);
std::cerr << "--------";
if ((seam > 0) && (singularity >= 0)) {
std::cerr << " S/S " << (*samples)[i].x << ", " << (*samples)[i].y;
} else if (seam > 0) {
std::cerr << " Seam " << (*samples)[i].x << ", " << (*samples)[i].y;
} else if (singularity >= 0) {
std::cerr << " Sing " << (*samples)[i].x << ", " << (*samples)[i].y;
} else {
std::cerr << " " << (*samples)[i].x << ", " << (*samples)[i].y;
}
ON_3dPoint p = surf->PointAt((*samples)[i].x, (*samples)[i].y);
std::cerr << " (" << p.x << ", " << p.y << ", " << p.z << ") " << std::endl;
i = ilast;
singularity = IsAtSingularity(surf, (*samples)[i], PBC_SEAM_TOL);
seam = IsAtSeam(surf, (*samples)[i], PBC_SEAM_TOL);
std::cerr << " ";
if ((seam > 0) && (singularity >= 0)) {
std::cerr << " S/S " << (*samples)[i].x << ", " << (*samples)[i].y << std::endl;
} else if (seam > 0) {
std::cerr << " Seam " << (*samples)[i].x << ", " << (*samples)[i].y << std::endl;
} else if (singularity >= 0) {
std::cerr << " Sing " << (*samples)[i].x << ", " << (*samples)[i].y << std::endl;
} else {
std::cerr << " " << (*samples)[i].x << ", " << (*samples)[i].y << std::endl;
}
p = surf->PointAt((*samples)[i].x, (*samples)[i].y);
std::cerr << " (" << p.x << ", " << p.y << ", " << p.z << ") " << std::endl;
si++;
}
cs++;
}
} else {
// print out all points
trimcnt = 0;
cs = pbcs.begin();
std::cerr << str << ":" << std::endl;
while (cs != pbcs.end()) {
PBCData *data = (*cs);
if (!data || !data->surf)
continue;
const ON_Surface *surf = data->surf;
std::list<ON_2dPointArray *>::iterator si = data->segments.begin();
int segcnt = 0;
std::cerr << "2d surface domain: " << std::endl;
std::cerr << "in rpp rpp" << surf->Domain(0).m_t[0] << " " << surf->Domain(0).m_t[1] << " " << surf->Domain(1).m_t[0] << " " << surf->Domain(1).m_t[1] << " 0.0 0.01" << std::endl;
while (si != data->segments.end()) {
ON_2dPointArray *samples = (*si);
std::cerr << std::endl << " Segment:" << ++segcnt << std::endl;
std::cerr << " T:" << ++trimcnt << std::endl;
for (int i = 0; i < samples->Count(); i++) {
int singularity = IsAtSingularity(surf, (*samples)[i], PBC_SEAM_TOL);
int seam = IsAtSeam(surf, (*samples)[i], PBC_SEAM_TOL);
if (_debug_print_mged2d_points_) {
std::cerr << "in pt_" << _debug_point_count_++ << " sph " << (*samples)[i].x << " " << (*samples)[i].y << " 0.0 0.1000" << std::endl;
} else if (_debug_print_mged3d_points_) {
ON_3dPoint p = surf->PointAt((*samples)[i].x, (*samples)[i].y);
std::cerr << "in pt_" << _debug_point_count_++ << " sph " << p.x << " " << p.y << " " << p.z << " 0.1000" << std::endl;
} else {
if (i == 0) {
std::cerr << "--------";
} else {
std::cerr << " ";
}
if ((seam > 0) && (singularity >= 0)) {
std::cerr << " S/S " << (*samples)[i].x << ", " << (*samples)[i].y;
} else if (seam > 0) {
std::cerr << " Seam " << (*samples)[i].x << ", " << (*samples)[i].y;
} else if (singularity >= 0) {
std::cerr << " Sing " << (*samples)[i].x << ", " << (*samples)[i].y;
} else {
std::cerr << " " << (*samples)[i].x << ", " << (*samples)[i].y;
}
ON_3dPoint p = surf->PointAt((*samples)[i].x, (*samples)[i].y);
std::cerr << " (" << p.x << ", " << p.y << ", " << p.z << ") " << std::endl;
}
}
si++;
}
cs++;
}
}
/////
}
#endif
bool
resolve_seam_segment_from_prev(const ON_Surface *surface, ON_2dPointArray &segment, ON_2dPoint *prev = NULL)
{
bool complete = false;
double umin, umax, umid;
double vmin, vmax, vmid;
surface->GetDomain(0, &umin, &umax);
surface->GetDomain(1, &vmin, &vmax);
umid = (umin + umax) / 2.0;
vmid = (vmin + vmax) / 2.0;
for (int i = 0; i < segment.Count(); i++) {
int singularity = IsAtSingularity(surface, segment[i], PBC_SEAM_TOL);
int seam = IsAtSeam(surface, segment[i], PBC_SEAM_TOL);
if ((seam > 0)) {
if (prev != NULL) {
//std::cerr << " at seam " << seam << " but has prev" << std::endl;
//std::cerr << " prev: " << prev->x << ", " << prev->y << std::endl;
//std::cerr << " curr: " << data->samples[i].x << ", " << data->samples[i].y << std::endl;
switch (seam) {
case 1: //east/west
if (prev->x < umid) {
segment[i].x = umin;
} else {
segment[i].x = umax;
}
break;
case 2: //north/south
if (prev->y < vmid) {
segment[i].y = vmin;
} else {
segment[i].y = vmax;
}
break;
case 3: //both
if (prev->x < umid) {
segment[i].x = umin;
} else {
segment[i].x = umax;
}
if (prev->y < vmid) {
segment[i].y = vmin;
} else {
segment[i].y = vmax;
}
}
prev = &segment[i];
} else {
//std::cerr << " at seam and no prev" << std::endl;
complete = false;
}
} else {
if (singularity < 0) {
prev = &segment[i];
} else {
prev = NULL;
}
}
}
return complete;
}
bool
resolve_seam_segment_from_next(const ON_Surface *surface, ON_2dPointArray &segment, ON_2dPoint *next = NULL)
{
bool complete = false;
double umin, umax, umid;
double vmin, vmax, vmid;
surface->GetDomain(0, &umin, &umax);
surface->GetDomain(1, &vmin, &vmax);
umid = (umin + umax) / 2.0;
vmid = (vmin + vmax) / 2.0;
if (next != NULL) {
complete = true;
for (int i = segment.Count() - 1; i >= 0; i--) {
int singularity = IsAtSingularity(surface, segment[i], PBC_SEAM_TOL);
int seam = IsAtSeam(surface, segment[i], PBC_SEAM_TOL);
if ((seam > 0)) {
if (next != NULL) {
switch (seam) {
case 1: //east/west
if (next->x < umid) {
segment[i].x = umin;
} else {
segment[i].x = umax;
}
break;
case 2: //north/south
if (next->y < vmid) {
segment[i].y = vmin;
} else {
segment[i].y = vmax;
}
break;
case 3: //both
if (next->x < umid) {
segment[i].x = umin;
} else {
segment[i].x = umax;
}
if (next->y < vmid) {
segment[i].y = vmin;
} else {
segment[i].y = vmax;
}
}
next = &segment[i];
} else {
//std::cerr << " at seam and no prev" << std::endl;
complete = false;
}
} else {
if (singularity < 0) {
next = &segment[i];
} else {
next = NULL;
}
}
}
}
return complete;
}
bool
resolve_seam_segment(const ON_Surface *surface, ON_2dPointArray &segment, bool &u_resolved, bool &v_resolved)
{
ON_2dPoint *prev = NULL;
bool complete = false;
double umin, umax, umid;
double vmin, vmax, vmid;
int prev_seam = 0;
surface->GetDomain(0, &umin, &umax);
surface->GetDomain(1, &vmin, &vmax);
umid = (umin + umax) / 2.0;
vmid = (vmin + vmax) / 2.0;
for (int i = 0; i < segment.Count(); i++) {
int singularity = IsAtSingularity(surface, segment[i], PBC_SEAM_TOL);
int seam = IsAtSeam(surface, segment[i], PBC_SEAM_TOL);
if ((seam > 0)) {
if (prev != NULL) {
//std::cerr << " at seam " << seam << " but has prev" << std::endl;
//std::cerr << " prev: " << prev->x << ", " << prev->y << std::endl;
//std::cerr << " curr: " << data->samples[i].x << ", " << data->samples[i].y << std::endl;
switch (seam) {
case 1: //east/west
if (prev->x < umid) {
segment[i].x = umin;
} else {
segment[i].x = umax;
}
break;
case 2: //north/south
if (prev->y < vmid) {
segment[i].y = vmin;
} else {
segment[i].y = vmax;
}
break;
case 3: //both
if (prev->x < umid) {
segment[i].x = umin;
} else {
segment[i].x = umax;
}
if (prev->y < vmid) {
segment[i].y = vmin;
} else {
segment[i].y = vmax;
}
}
prev = &segment[i];
} else {
//std::cerr << " at seam and no prev" << std::endl;
complete = false;
}
prev_seam = seam;
} else {
if (singularity < 0) {
prev = &segment[i];
prev_seam = 0;
} else {
prev = NULL;
}
}
}
prev_seam = 0;
if ((!complete) && (prev != NULL)) {
complete = true;
for (int i = segment.Count() - 2; i >= 0; i--) {
int singularity = IsAtSingularity(surface, segment[i], PBC_SEAM_TOL);
int seam = IsAtSeam(surface, segment[i], PBC_SEAM_TOL);
if ((seam > 0)) {
if (prev != NULL) {
//std::cerr << " at seam " << seam << " but has prev" << std::endl;
//std::cerr << " prev: " << prev->x << ", " << prev->y << std::endl;
//std::cerr << " curr: " << data->samples[i].x << ", " << data->samples[i].y << std::endl;
switch (seam) {
case 1: //east/west
if (prev->x < umid) {
segment[i].x = umin;
} else {
segment[i].x = umax;
}
break;
case 2: //north/south
if (prev->y < vmid) {
segment[i].y = vmin;
} else {
segment[i].y = vmax;
}
break;
case 3: //both
if (prev->x < umid) {
segment[i].x = umin;
} else {
segment[i].x = umax;
}
if (prev->y < vmid) {
segment[i].y = vmin;
} else {
segment[i].y = vmax;
}
}
prev = &segment[i];
} else {
//std::cerr << " at seam and no prev" << std::endl;
complete = false;
}
} else {
if (singularity < 0) {
prev = &segment[i];
} else {
prev = NULL;
}
}
}
}
return complete;
}
/*
* number_of_seam_crossings
*/
int
number_of_seam_crossings(std::list<PBCData*> &pbcs)
{
int rc = 0;
std::list<PBCData*>::iterator cs;
cs = pbcs.begin();
while (cs != pbcs.end()) {
PBCData *data = (*cs);
if (!data || !data->surf)
continue;
const ON_Surface *surf = data->surf;
std::list<ON_2dPointArray *>::iterator si = data->segments.begin();
ON_2dPoint *pt = NULL;
ON_2dPoint *prev_pt = NULL;
ON_2dPoint *next_pt = NULL;
while (si != data->segments.end()) {
ON_2dPointArray *samples = (*si);
for (int i = 0; i < samples->Count(); i++) {
pt = &(*samples)[i];
if (!IsAtSeam(surf,*pt,PBC_SEAM_TOL)) {
if (prev_pt == NULL) {
prev_pt = pt;
} else {
next_pt = pt;
}
int udir=0;
int vdir=0;
if (next_pt != NULL) {
if (ConsecutivePointsCrossClosedSeam(surf,*prev_pt,*next_pt,udir,vdir,PBC_SEAM_TOL)) {
rc++;
}
prev_pt = next_pt;
next_pt = NULL;
}
}
}
if (si != data->segments.end())
si++;
}
if (cs != pbcs.end())
cs++;
}
return rc;
}
/*
* if current and previous point on seam make sure they are on same seam
*/
bool
check_for_points_on_same_seam(std::list<PBCData*> &pbcs)
{
std::list<PBCData*>::iterator cs = pbcs.begin();
ON_2dPoint *prev_pt = NULL;
int prev_seam = 0;
while ( cs != pbcs.end()) {
PBCData *data = (*cs);
const ON_Surface *surf = data->surf;
std::list<ON_2dPointArray *>::iterator seg = data->segments.begin();
while (seg != data->segments.end()) {
ON_2dPointArray *points = (*seg);
for (int i=0; i < points->Count(); i++) {
ON_2dPoint *pt = points->At(i);
int seam = IsAtSeam(surf,*pt,PBC_SEAM_TOL);
if (seam > 0) {
if (prev_seam > 0) {
if ((seam == 1) && ((prev_seam % 2) == 1)) {
pt->x = prev_pt->x;
} else if ((seam == 2) && (prev_seam > 1)) {
pt->y = prev_pt->y;
} else if (seam == 3) {
if ((prev_seam % 2) == 1) {
pt->x = prev_pt->x;
}
if (prev_seam > 1) {
pt->y = prev_pt->y;
}
}
}
prev_seam = seam;
prev_pt = pt;
}
}
seg++;
}
cs++;
}
return true;
}
/*
* extend_pullback_at_shared_3D_curve_seam
*/
bool
extend_pullback_at_shared_3D_curve_seam(std::list<PBCData*> &pbcs)
{
const ON_Curve *next_curve = NULL;
std::set<const ON_Curve *> set;
std::map<const ON_Curve *,int> map;
std::list<PBCData*>::iterator cs = pbcs.begin();
while ( cs != pbcs.end()) {
PBCData *data = (*cs++);
const ON_Curve *curve = data->curve;
const ON_Surface *surf = data->surf;
if (cs != pbcs.end()) {
PBCData *nextdata = (*cs);
next_curve = nextdata->curve;
}
if (curve == next_curve) {
std::cerr << "Consecutive seam usage" << std::endl;
//find which direction we need to extend
if (surf->IsClosed(0) && !surf->IsClosed(1)) {
double length = surf->Domain(0).Length();
std::list<ON_2dPointArray *>::iterator seg = data->segments.begin();
while (seg != data->segments.end()) {
ON_2dPointArray *points = (*seg);
for (int i=0; i < points->Count(); i++) {
points->At(i)->x = points->At(i)->x + length;
}
seg++;
}
} else if (!surf->IsClosed(0) && surf->IsClosed(1)) {
double length = surf->Domain(1).Length();
std::list<ON_2dPointArray *>::iterator seg = data->segments.begin();
while (seg != data->segments.end()) {
ON_2dPointArray *points = (*seg);
for (int i=0; i < points->Count(); i++) {
points->At(i)->y = points->At(i)->y + length;
}
seg++;
}
} else {
std::cerr << "both directions" << std::endl;
}
}
next_curve = NULL;
}
return true;
}
/*
* shift_closed_curve_split_over_seam
*/
bool
shift_single_curve_loop_straddled_over_seam(std::list<PBCData*> &pbcs)
{
if (pbcs.size() == 1) { // single curve for this loop
std::list<PBCData*>::iterator cs;
PBCData *data = pbcs.front();
if (!data || !data->surf)
return false;
const ON_Surface *surf = data->surf;
ON_Interval udom = surf->Domain(0);
ON_Interval vdom = surf->Domain(1);
std::list<ON_2dPointArray *>::iterator si = data->segments.begin();
ON_2dPoint pt;
ON_2dPoint prev_pt;
if (data->curve->IsClosed()) {
int numseamcrossings = number_of_seam_crossings(pbcs);
if (numseamcrossings == 1) {
ON_2dPointArray part1,part2;
ON_2dPointArray* curr_point_array = &part2;
while (si != data->segments.end()) {
ON_2dPointArray *samples = (*si);
for (int i = 0; i < samples->Count(); i++) {
pt = (*samples)[i];
if (i == 0) {
prev_pt = pt;
curr_point_array->Append(pt);
continue;
}
int udir= 0;
int vdir= 0;
if (ConsecutivePointsCrossClosedSeam(surf,pt,prev_pt,udir,vdir,PBC_SEAM_TOL)) {
if (surf->IsAtSeam(pt.x,pt.y) > 0) {
SwapUVSeamPoint(surf, pt);
curr_point_array->Append(pt);
curr_point_array = &part1;
SwapUVSeamPoint(surf, pt);
} else if (surf->IsAtSeam(prev_pt.x,prev_pt.y) > 0) {
SwapUVSeamPoint(surf, prev_pt);
curr_point_array->Append(prev_pt);
} else {
std::cerr << "shift_single_curve_loop_straddled_over_seam(): Error expecting to see seam in sample points" << std::endl;
}
}
curr_point_array->Append(pt);
prev_pt = pt;
}
samples->Empty();
samples->Append(part1.Count(),part1.Array());
samples->Append(part2.Count(),part2.Array());
if (si != data->segments.end())
si++;
}
}
}
}
return true;
}
/*
* extend_over_seam_crossings - all incoming points assumed to be within UV bounds
*/
bool
extend_over_seam_crossings(std::list<PBCData*> &pbcs)
{
std::list<PBCData*>::iterator cs;
ON_2dPoint *pt = NULL;
ON_2dPoint *prev_non_seam_pt = NULL;
ON_2dPoint *prev_pt = NULL;
ON_2dVector curr_uv_offsets = ON_2dVector::ZeroVector;
///// Loop through and fix any seam ambiguities
cs = pbcs.begin();
while (cs != pbcs.end()) {
PBCData *data = (*cs);
if (!data || !data->surf)
continue;
const ON_Surface *surf = data->surf;
ON_Interval udom = surf->Domain(0);
double ulength = udom.Length();
ON_Interval vdom = surf->Domain(1);
double vlength = vdom.Length();
std::list<ON_2dPointArray *>::iterator si = data->segments.begin();
while (si != data->segments.end()) {
ON_2dPointArray *samples = (*si);
for (int i = 0; i < samples->Count(); i++) {
pt = &(*samples)[i];
if (prev_pt != NULL) {
GetClosestExtendedPoint(surf,*pt,*prev_pt,PBC_SEAM_TOL);
}
prev_pt = pt;
}
if (si != data->segments.end())
si++;
}
if (cs != pbcs.end())
cs++;
}
return true;
}
/*
* run through curve loop to determine correct start/end
* points resolving ambiguities when point lies on a seam or
* singularity
*/
bool
resolve_pullback_seams(std::list<PBCData*> &pbcs)
{
std::list<PBCData*>::iterator cs;
///// Loop through and fix any seam ambiguities
ON_2dPoint *prev = NULL;
ON_2dPoint *next = NULL;
bool u_resolved = false;
bool v_resolved = false;
cs = pbcs.begin();
while (cs != pbcs.end()) {
PBCData *data = (*cs);
if (!data || !data->surf)
continue;
const ON_Surface *surf = data->surf;
double umin, umax;
double vmin, vmax;
surf->GetDomain(0, &umin, &umax);
surf->GetDomain(1, &vmin, &vmax);
std::list<ON_2dPointArray *>::iterator si = data->segments.begin();
while (si != data->segments.end()) {
ON_2dPointArray *samples = (*si);
if (resolve_seam_segment(surf, *samples,u_resolved,v_resolved)) {
// Found a starting point
//1) walk back up with resolved next point
next = (*samples).First();
std::list<PBCData*>::reverse_iterator rcs(cs);
rcs--;
std::list<ON_2dPointArray *>::reverse_iterator rsi(si);
while (rcs != pbcs.rend()) {
PBCData *rdata = (*rcs);
while (rsi != rdata->segments.rend()) {
ON_2dPointArray *rsamples = (*rsi);
// first try and resolve on own merits
if (!resolve_seam_segment(surf, *rsamples,u_resolved,v_resolved)) {
resolve_seam_segment_from_next(surf, *rsamples, next);
}
next = (*rsamples).First();
rsi++;
}
rcs++;
if (rcs != pbcs.rend()) {
rdata = (*rcs);
rsi = rdata->segments.rbegin();
}
}
//2) walk rest of way down with resolved prev point
if (samples->Count() > 1)
prev = &(*samples)[samples->Count() - 1];
else
prev = NULL;
si++;
std::list<PBCData*>::iterator current(cs);
while (cs != pbcs.end()) {
while (si != data->segments.end()) {
samples = (*si);
// first try and resolve on own merits
if (!resolve_seam_segment(surf, *samples,u_resolved,v_resolved)) {
resolve_seam_segment_from_prev(surf, *samples, prev);
}
if (samples->Count() > 1)
prev = &(*samples)[samples->Count() - 1];
else
prev = NULL;
si++;
}
cs++;
if (cs != pbcs.end()) {
data = (*cs);
si = data->segments.begin();
}
}
// make sure to wrap back around with previous
cs = pbcs.begin();
data = (*cs);
si = data->segments.begin();
while ((cs != pbcs.end()) && (cs != current)) {
while (si != data->segments.end()) {
samples = (*si);
// first try and resolve on own merits
if (!resolve_seam_segment(surf, *samples,u_resolved,v_resolved)) {
resolve_seam_segment_from_prev(surf, *samples, prev);
}
if (samples->Count() > 1)
prev = &(*samples)[samples->Count() - 1];
else
prev = NULL;
si++;
}
cs++;
if (cs != pbcs.end()) {
data = (*cs);
si = data->segments.begin();
}
}
}
if (si != data->segments.end())
si++;
}
if (cs != pbcs.end())
cs++;
}
return true;
}
/*
* run through curve loop to determine correct start/end
* points resolving ambiguities when point lies on a seam or
* singularity
*/
bool
resolve_pullback_singularities(std::list<PBCData*> &pbcs)
{
std::list<PBCData*>::iterator cs = pbcs.begin();
///// Loop through and fix any seam ambiguities
ON_2dPoint *prev = NULL;
bool complete = false;
int checkcnt = 0;
prev = NULL;
complete = false;
checkcnt = 0;
while (!complete && (checkcnt < 2)) {
cs = pbcs.begin();
complete = true;
checkcnt++;
//std::cerr << "Checkcnt - " << checkcnt << std::endl;
while (cs != pbcs.end()) {
int singularity;
prev = NULL;
PBCData *data = (*cs);
if (!data || !data->surf)
continue;
const ON_Surface *surf = data->surf;
std::list<ON_2dPointArray *>::iterator si = data->segments.begin();
while (si != data->segments.end()) {
ON_2dPointArray *samples = (*si);
for (int i = 0; i < samples->Count(); i++) {
// 0 = south, 1 = east, 2 = north, 3 = west
if ((singularity = IsAtSingularity(surf, (*samples)[i], PBC_SEAM_TOL)) >= 0) {
if (prev != NULL) {
//std::cerr << " at singularity " << singularity << " but has prev" << std::endl;
//std::cerr << " prev: " << prev->x << ", " << prev->y << std::endl;
//std::cerr << " curr: " << data->samples[i].x << ", " << data->samples[i].y << std::endl;
switch (singularity) {
case 0: //south
(*samples)[i].x = prev->x;
(*samples)[i].y = surf->Domain(1)[0];
break;
case 1: //east
(*samples)[i].y = prev->y;
(*samples)[i].x = surf->Domain(0)[1];
break;
case 2: //north
(*samples)[i].x = prev->x;
(*samples)[i].y = surf->Domain(1)[1];
break;
case 3: //west
(*samples)[i].y = prev->y;
(*samples)[i].x = surf->Domain(0)[0];
}
prev = NULL;
//std::cerr << " curr now: " << data->samples[i].x << ", " << data->samples[i].y << std::endl;
} else {
//std::cerr << " at singularity " << singularity << " and no prev" << std::endl;
//std::cerr << " curr: " << data->samples[i].x << ", " << data->samples[i].y << std::endl;
complete = false;
}
} else {
prev = &(*samples)[i];
}
}
if (!complete) {
//std::cerr << "Lets work backward:" << std::endl;
for (int i = samples->Count() - 2; i >= 0; i--) {
// 0 = south, 1 = east, 2 = north, 3 = west
if ((singularity = IsAtSingularity(surf, (*samples)[i], PBC_SEAM_TOL)) >= 0) {
if (prev != NULL) {
//std::cerr << " at singularity " << singularity << " but has prev" << std::endl;
//std::cerr << " prev: " << prev->x << ", " << prev->y << std::endl;
//std::cerr << " curr: " << data->samples[i].x << ", " << data->samples[i].y << std::endl;
switch (singularity) {
case 0: //south
(*samples)[i].x = prev->x;
(*samples)[i].y = surf->Domain(1)[0];
break;
case 1: //east
(*samples)[i].y = prev->y;
(*samples)[i].x = surf->Domain(0)[1];
break;
case 2: //north
(*samples)[i].x = prev->x;
(*samples)[i].y = surf->Domain(1)[1];
break;
case 3: //west
(*samples)[i].y = prev->y;
(*samples)[i].x = surf->Domain(0)[0];
}
prev = NULL;
//std::cerr << " curr now: " << data->samples[i].x << ", " << data->samples[i].y << std::endl;
} else {
//std::cerr << " at singularity " << singularity << " and no prev" << std::endl;
//std::cerr << " curr: " << data->samples[i].x << ", " << data->samples[i].y << std::endl;
complete = false;
}
} else {
prev = &(*samples)[i];
}
}
}
si++;
}
cs++;
}
}
return true;
}
void
remove_consecutive_intersegment_duplicates(std::list<PBCData*> &pbcs)
{
std::list<PBCData*>::iterator cs = pbcs.begin();
while (cs != pbcs.end()) {
PBCData *data = (*cs);
std::list<ON_2dPointArray *>::iterator si = data->segments.begin();
while (si != data->segments.end()) {
ON_2dPointArray *samples = (*si);
if (samples->Count() == 0) {
si = data->segments.erase(si);
} else {
for (int i = 0; i < samples->Count() - 1; i++) {
while ((i < (samples->Count() - 1)) && (*samples)[i].DistanceTo((*samples)[i + 1]) < 1e-9) {
samples->Remove(i + 1);
}
}
si++;
}
}
if (data->segments.empty()) {
cs = pbcs.erase(cs);
} else {
cs++;
}
}
}
bool
check_pullback_data(std::list<PBCData*> &pbcs)
{
std::list<PBCData*>::iterator d = pbcs.begin();
if ((*d) == NULL || (*d)->surf == NULL)
return false;
const ON_Surface *surf = (*d)->surf;
bool singular = has_singularity(surf);
bool closed = is_closed(surf);
if (singular) {
if (!resolve_pullback_singularities(pbcs)) {
std::cerr << "Error: Can not resolve singular ambiguities." << std::endl;
}
}
if (closed) {
// check for same 3D curve use
if (!check_for_points_on_same_seam(pbcs)) {
std::cerr << "Error: Can not extend pullback at shared 3D curve seam." << std::endl;
return false;
}
// check for same 3D curve use
if (!extend_pullback_at_shared_3D_curve_seam(pbcs)) {
std::cerr << "Error: Can not extend pullback at shared 3D curve seam." << std::endl;
return false;
}
if (!shift_single_curve_loop_straddled_over_seam(pbcs)) {
std::cerr << "Error: Can not resolve seam ambiguities." << std::endl;
return false;
}
if (!resolve_pullback_seams(pbcs)) {
std::cerr << "Error: Can not resolve seam ambiguities." << std::endl;
return false;
}
if (!extend_over_seam_crossings(pbcs)) {
std::cerr << "Error: Can not resolve seam ambiguities." << std::endl;
return false;
}
}
// consecutive duplicates within segment will cause problems in curve fit
remove_consecutive_intersegment_duplicates(pbcs);
return true;
}
int
check_pullback_singularity_bridge(const ON_Surface *surf, const ON_2dPoint &p1, const ON_2dPoint &p2)
{
if (has_singularity(surf)) {
int is, js;
if (((is = IsAtSingularity(surf, p1, PBC_SEAM_TOL)) >= 0) && ((js = IsAtSingularity(surf, p2, PBC_SEAM_TOL)) >= 0)) {
//create new singular trim
if (is == js) {
return is;
}
}
}
return -1;
}
int
check_pullback_seam_bridge(const ON_Surface *surf, const ON_2dPoint &p1, const ON_2dPoint &p2)
{
if (is_closed(surf)) {
int is, js;
if (((is = IsAtSeam(surf, p1, PBC_SEAM_TOL)) > 0) && ((js = IsAtSeam(surf, p2, PBC_SEAM_TOL)) > 0)) {
//create new seam trim
if (is == js) {
// need to check if seam 3d points are equal
double endpoint_distance = p1.DistanceTo(p2);
double t0, t1;
int dir = is - 1;
surf->GetDomain(dir, &t0, &t1);
if (endpoint_distance > 0.5 * (t1 - t0)) {
return is;
}
}
}
}
return -1;
}
ON_Curve*
pullback_curve(const brlcad::SurfaceTree* surfacetree,
const ON_Surface* surf,
const ON_Curve* curve,
double tolerance,
double flatness)
{
PBCData data;
data.tolerance = tolerance;
data.flatness = flatness;
data.curve = curve;
data.surf = surf;
data.surftree = (brlcad::SurfaceTree*)surfacetree;
ON_2dPointArray samples;
data.segments.push_back(&samples);
// Step 1 - adaptively sample the curve
double tmin, tmax;
data.curve->GetDomain(&tmin, &tmax);
ON_2dPoint& start = samples.AppendNew(); // new point is added to samples and returned
if (!toUV(data, start, tmin, 0.001)) {
return NULL; // fails if first point is out of tolerance!
}
ON_2dPoint uv;
ON_3dPoint p = curve->PointAt(tmin);
ON_3dPoint from = curve->PointAt(tmin + 0.0001);
brlcad::SurfaceTree *st = (brlcad::SurfaceTree *)surfacetree;
if (st->getSurfacePoint((const ON_3dPoint&)p, uv, (const ON_3dPoint&)from) < 0) {
std::cerr << "Error: Can not get surface point." << std::endl;
}
ON_2dPoint p1, p2;
#ifdef SHOW_UNUSED
if (!data.surf)
return NULL;
const ON_Surface *surf = data.surf;
#endif
if (toUV(data, p1, tmin, PBC_TOL) && toUV(data, p2, tmax, -PBC_TOL)) {
#ifdef SHOW_UNUSED
ON_3dPoint a = surf->PointAt(p1.x, p1.y);
ON_3dPoint b = surf->PointAt(p2.x, p2.y);
#endif
p = curve->PointAt(tmax);
from = curve->PointAt(tmax - 0.0001);
if (st->getSurfacePoint((const ON_3dPoint&)p, uv, (const ON_3dPoint&)from) < 0) {
std::cerr << "Error: Can not get surface point." << std::endl;
}
if (!sample(data, tmin, tmax, p1, p2)) {
return NULL;
}
for (int i = 0; i < samples.Count(); i++) {
std::cerr << samples[i].x << ", " << samples[i].y << std::endl;
}
} else {
return NULL;
}
return interpolateCurve(samples);
}
ON_Curve*
pullback_seam_curve(enum seam_direction seam_dir,
const brlcad::SurfaceTree* surfacetree,
const ON_Surface* surf,
const ON_Curve* curve,
double tolerance,
double flatness)
{
PBCData data;
data.tolerance = tolerance;
data.flatness = flatness;
data.curve = curve;
data.surf = surf;
data.surftree = (brlcad::SurfaceTree*)surfacetree;
ON_2dPointArray samples;
data.segments.push_back(&samples);
// Step 1 - adaptively sample the curve
double tmin, tmax;
data.curve->GetDomain(&tmin, &tmax);
ON_2dPoint& start = samples.AppendNew(); // new point is added to samples and returned
if (!toUV(data, start, tmin, 0.001)) {
return NULL; // fails if first point is out of tolerance!
}
ON_2dPoint p1, p2;
if (toUV(data, p1, tmin, PBC_TOL) && toUV(data, p2, tmax, -PBC_TOL)) {
if (!sample(data, tmin, tmax, p1, p2)) {
return NULL;
}
for (int i = 0; i < samples.Count(); i++) {
if (seam_dir == NORTH_SEAM) {
samples[i].y = 1.0;
} else if (seam_dir == EAST_SEAM) {
samples[i].x = 1.0;
} else if (seam_dir == SOUTH_SEAM) {
samples[i].y = 0.0;
} else if (seam_dir == WEST_SEAM) {
samples[i].x = 0.0;
}
std::cerr << samples[i].x << ", " << samples[i].y << std::endl;
}
} else {
return NULL;
}
return interpolateCurve(samples);
}
// Local Variables:
// tab-width: 8
// mode: C++
// c-basic-offset: 4
// indent-tabs-mode: t
// c-file-style: "stroustrup"
// End:
// ex: shiftwidth=4 tabstop=8
| 143,300 | 62,721 |
//-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (c) 2008-2022 Ryo Suzuki
// Copyright (c) 2016-2022 OpenSiv3D Project
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# include <Siv3D/TCPServer.hpp>
# include <Siv3D/TCPServer/TCPServerDetail.hpp>
namespace s3d
{
TCPServer::TCPServer()
: pImpl{ std::make_shared<TCPServerDetail>() } {}
TCPServer::~TCPServer() {}
void TCPServer::startAccept(const uint16 port)
{
pImpl->startAccept(port);
}
void TCPServer::startAcceptMulti(const uint16 port)
{
pImpl->startAcceptMulti(port);
}
void TCPServer::cancelAccept()
{
pImpl->cancelAccept();
}
bool TCPServer::isAccepting() const
{
return pImpl->isAccepting();
}
void TCPServer::disconnect()
{
return pImpl->disconnect();
}
bool TCPServer::hasSession() const
{
return pImpl->hasSession();
}
bool TCPServer::hasSession(const TCPSessionID id) const
{
return pImpl->hasSession(id);
}
size_t TCPServer::num_sessions() const
{
return pImpl->num_sessions();
}
Array<TCPSessionID> TCPServer::getSessionIDs() const
{
return pImpl->getSessionIDs();
}
uint16 TCPServer::port() const
{
return pImpl->port();
}
size_t TCPServer::available(const Optional<TCPSessionID>& id)
{
return pImpl->available(id);
}
bool TCPServer::skip(const size_t size, const Optional<TCPSessionID>& id)
{
return pImpl->skip(size, id);
}
bool TCPServer::lookahead(void* dst, const size_t size, const Optional<TCPSessionID>& id) const
{
return pImpl->lookahead(dst, size, id);
}
bool TCPServer::read(void* dst, const size_t size, const Optional<TCPSessionID>& id)
{
return pImpl->read(dst, size, id);
}
bool TCPServer::send(const void* data, const size_t size, const Optional<TCPSessionID>& id)
{
return pImpl->send(data, size, id);
}
}
| 1,895 | 732 |
/*
Copyright (c) 2003, Xentronix
Author: Frans van Nispen (frans@xentronix.com)
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
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 Xentronix nor the names of its contributors may be used
to endorse or promote products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdlib.h>
#include <stdio.h>
#include "Globals.h"
#include "PeakFile.h"
#include "VMSystem.h"
CPeakFile Peak;
#define BUFFER_SIZE 64*256 // 64Kb
// ============================================================
CPeakFile::CPeakFile()
{
buffer_left = NULL;
buffer_right = NULL;
buffer = NULL;
}
// ============================================================
CPeakFile::~CPeakFile()
{
if (buffer) delete[] buffer;
if (buffer_left) free(buffer_left);
if (buffer_right) free(buffer_right);
}
// ============================================================
void CPeakFile::Init(int32 size, bool mono)
{
if (buffer)
delete[] buffer;
buffer = new float[BUFFER_SIZE];
m_size = size;
size = (size >> 7) + 1;
m_mono = mono;
int64 mem = size * 4 +16; // 2 int16's for each channel
if (!mono) mem *= 2;
int16 *p = (int16*)realloc(buffer_left, mem);
if (p){
buffer_left = p; // new block
memset( buffer_left, 0, mem); // wipe buffer
}else{
(new BAlert(NULL,Language.get("MEM_ERROR"),Language.get("OK")))->Go();
be_app->Quit();
}
if (!mono){
int16 *p = (int16*)realloc(buffer_right, mem);
if (p){
buffer_right = p; // new block
memset( buffer_right, 0, mem); // wipe buffer
}else{
(new BAlert(NULL,Language.get("MEM_ERROR"),Language.get("OK")))->Go();
be_app->Quit();
}
}else{
if (buffer_right) free(buffer_right);
buffer_right = NULL;
}
}
// ============================================================
void CPeakFile::CreatePeaks(int32 start, int32 end, int32 progress)
{
float min, max, max_r, min_r;
int32 to, ii;
start &= 0xfffffff8; // mask off 1st 7 bits to round on 128 bytes
int32 p_add = 0, p_count = 0, count = 0;
if (progress){ // init progress process
p_count = (end-start)/(100*128);
p_add = progress/100;
if (!m_mono) p_add <<=1;
}
if (m_mono) // mono
{
#ifndef __VM_SYSTEM // RAM
float *p = Pool.sample_memory;
#else
float *p = buffer;
int32 index = 0;
VM.ReadBlockAt(start, p, BUFFER_SIZE);
#endif
for (int32 i=start; i<=end; i+=128){
min = max = 0.0;
to = i+127;
if (to>Pool.size) to = Pool.size;
for (int32 x=i; x<=to; x++){
#ifndef __VM_SYSTEM // RAM
if (p[x]>max) max = p[x];
if (p[x]<min) min = p[x];
#else
if (p[index]>max) max = p[index];
if (p[index]<min) min = p[index];
index++;
if (index == BUFFER_SIZE){
index = 0;
VM.ReadBlock(p, BUFFER_SIZE);
}
#endif
}
ii = i>>6;
buffer_left[ii] = (int16)(min * 32767);
buffer_left[ii+1] = (int16)(max * 32767);
if (progress && count--<0){ count = p_count; Pool.ProgressUpdate( p_add ); }
}
}
else // Stereo
{
#ifndef __VM_SYSTEM // RAM
float *p = Pool.sample_memory;
#else
float *p = buffer;
int32 index = 0;
VM.ReadBlockAt(start, p, BUFFER_SIZE);
#endif
for (int32 i=start*2; i<=end*2; i+=256){
min = max = 0.0;
min_r = max_r = 0.0;
to = i+255;
if (to>Pool.size) to = Pool.size;
for (int32 x=i; x<=to; x+=2){
#ifndef __VM_SYSTEM // RAM
if (p[x]>max) max = p[x];
if (p[x]<min) min = p[x];
if (p[x+1]>max_r) max_r = p[x+1];
if (p[x+1]<min_r) min_r = p[x+1];
#else
if (p[index]>max) max = p[index];
if (p[index]<min) min = p[index];
if (p[index+1]>max_r) max_r = p[index+1];
if (p[index+1]<min_r) min_r = p[index+1];
index+=2;
if (index >= BUFFER_SIZE){
index = 0;
VM.ReadBlock(p, BUFFER_SIZE);
}
#endif
}
ii = i>>6;
buffer_left[ii] = (int16)(min * 32767);
buffer_left[ii+1] = (int16)(max * 32767);
buffer_right[ii] = (int16)(min_r * 32767);
buffer_right[ii+1] = (int16)(max_r * 32767);
if (progress && count--<0){ count = p_count; Pool.ProgressUpdate( p_add ); }
}
}
Pool.update_peak = true;
}
// ============================================================
void CPeakFile::MonoBuffer(float *out, int32 start, int32 end, float w)
{
if (!buffer_left || !m_mono) return;
float step = (end - start)/w;
int32 iStep = (int32)step;
int32 index, to;
#ifdef __VM_SYSTEM // VM
int32 nBufferSize = MIN( BUFFER_SIZE, end-start);
#endif
if ( step <= 1 )
{
#ifndef __VM_SYSTEM // RAM
float *p = Pool.sample_memory;
#else
float *p = buffer;
VM.ReadBlockAt(start, p, nBufferSize);
#endif
for (int32 x = 0; x<w; x++){
#ifndef __VM_SYSTEM // RAM
index = start + (int32)(x * step);
#else
index = (int32)(x * step);
#endif
float fTemp = p[index];
if (fTemp>1.0f) fTemp = 1.0f;
else if (fTemp<-1.0f) fTemp = -1.0f;
*out++ = fTemp;
*out++ = 0.0f;
}
}else
if ( step < 64 )
{ float min, max;
#ifndef __VM_SYSTEM // RAM
float *p = Pool.sample_memory;
#else
float *p = buffer;
int32 idx = 0;
VM.ReadBlockAt(start, p, nBufferSize);
#endif
for (int32 x = 0; x<w; x++){
index = start + (int32)(x * step);
to = index + iStep; if (to>m_size) to = m_size;
min = max = 0;
for (int32 i=index; i<=to; i++){
#ifndef __VM_SYSTEM // RAM
if (p[i]>max) max = p[i];
if (p[i]<min) min = p[i];
#else
if (p[idx]>max) max = p[idx];
if (p[idx]<min) min = p[idx];
idx++;
if (idx == nBufferSize){
idx = 0;
VM.ReadBlock(p, nBufferSize);
}
#endif
}
if (max > -min) *out++ = MIN(max, 1);
else *out++ = MAX(min, -1);
*out++ = 0.0f;
}
}else
if ( step < 128 )
{ float min, max;
#ifndef __VM_SYSTEM // RAM
float *p = Pool.sample_memory;
#else
float *p = buffer;
int32 idx = 0;
VM.ReadBlockAt(start, p, nBufferSize);
#endif
for (int32 x = 0; x<w; x++){
index = start + (int32)(x * step);
to = index + iStep; if (to>m_size) to = m_size;
min = max = 0;
for (int32 i=index; i<=to; i++){
#ifndef __VM_SYSTEM // RAM
if (p[i]>max) max = p[i];
if (p[i]<min) min = p[i];
#else
if (p[idx]>max) max = p[idx];
if (p[idx]<min) min = p[idx];
idx++;
if (idx == nBufferSize){
idx = 0;
VM.ReadBlock(p, nBufferSize);
}
#endif
}
*out++ = min;
*out++ = max;
}
}
else
{ int16 min, max;
for (int32 x = 0; x<w; x++){
index = start + (int32)(x * step);
to = index + iStep; if (to>m_size) to = m_size;
index >>= 6; index &= 0xfffffffe;
to >>= 6; to &= 0xfffffffe;
min = max = 0;
for (int32 i=index; i<=to; i+=2){
if (buffer_left[i]<min) min = buffer_left[i];
if (buffer_left[i+1]>max) max = buffer_left[i+1];
}
*out++ = min/32767.0;
*out++ = max/32767.0;
}
}
}
// ============================================================
void CPeakFile::StereoBuffer(float *out, float *out_r, int32 start, int32 end, float w)
{
if (!buffer_left ||!buffer_right || m_mono)
return;
float step = (end - start)/w;
int32 iStep = (int32)step;
int32 index, to;
#ifdef __VM_SYSTEM // VM
int32 nBufferSize = MIN( BUFFER_SIZE, (end-start)*2);
#endif
if ( step <= 1 )
{
#ifndef __VM_SYSTEM // RAM
float *p = Pool.sample_memory;
#else
float *p = buffer;
VM.ReadBlockAt(start, p, nBufferSize);
#endif
for (int32 x = 0; x<w; x++){
#ifndef __VM_SYSTEM // RAM
index = start + (int32)(x * step);
#else
index = (int32)(x * step);
#endif
float fTemp = p[index*2];
float fTempR = p[index*2+1];
if (fTemp>1.0f) fTemp = 1.0f;
else if (fTemp<-1.0f) fTemp = -1.0f;
if (fTempR>1.0f) fTempR = 1.0f;
else if (fTempR<-1.0f) fTempR = -1.0f;
*out++ = fTemp;
*out++ = 0.0f;
*out_r++ = fTempR;
*out_r++ = 0.0f;
}
}else
if ( step < 64 )
{ float min, max, min_r, max_r;
#ifndef __VM_SYSTEM // RAM
float *p = Pool.sample_memory;
#else
float *p = buffer;
int32 idx = 0;
VM.ReadBlockAt(start, p, nBufferSize);
#endif
for (int32 x = 0; x<w; x++){
index = start + (int32)(x * step);
to = index + iStep; if (to>m_size) to = m_size;
index *= 2;
to *= 2;
min = max = min_r = max_r = 0;
for (int32 i=index; i<=to; i+=2){
#ifndef __VM_SYSTEM // RAM
if (p[i]>max) max = p[i];
if (p[i]<min) min = p[i];
if (p[i+1]>max_r) max_r = p[i+1];
if (p[i+1]<min_r) min_r = p[i+1];
#else
if (p[idx]>max) max = p[idx];
if (p[idx]<min) min = p[idx];
idx++;
if (p[idx]>max_r) max_r = p[idx];
if (p[idx]<min_r) min_r = p[idx];
idx++;
if (idx >= nBufferSize){
idx = 0;
VM.ReadBlock(p, nBufferSize);
}
#endif
}
if (max > -min) *out++ = MIN(max, 1);
else *out++ = MAX(min, -1);
*out++ = 0.0f;
if (max_r > -min_r) *out_r++ = MIN(max_r, 1);
else *out_r++ = MAX(min_r, -1);
*out_r++ = 0.0f;
}
}else
if (step <128)
{ float min, max, min_r, max_r;
#ifndef __VM_SYSTEM // RAM
float *p = Pool.sample_memory;
#else
float *p = buffer;
int32 idx = 0;
VM.ReadBlockAt(start, p, nBufferSize);
#endif
for (int32 x = 0; x<w; x++){
index = start + (int32)(x * step);
to = index + iStep; if (to>m_size) to = m_size;
index *= 2;
to *= 2;
min = max = min_r = max_r = 0;
for (int32 i=index; i<=to; i+=2){
#ifndef __VM_SYSTEM // RAM
if (p[i]>max) max = p[i];
if (p[i]<min) min = p[i];
if (p[i+1]>max_r) max_r = p[i+1];
if (p[i+1]<min_r) min_r = p[i+1];
#else
if (p[idx]>max) max = p[idx];
if (p[idx]<min) min = p[idx];
idx++;
if (p[idx]>max_r) max_r = p[idx];
if (p[idx]<min_r) min_r = p[idx];
idx++;
if (idx >= nBufferSize){
idx = 0;
VM.ReadBlock(p, nBufferSize);
}
#endif
}
*out++ = min;
*out++ = max;
*out_r++ = min_r;
*out_r++ = max_r;
}
}
else
{ int16 min, max, min_r, max_r;
for (int32 x = 0; x<w; x++){
index = start + (int32)(x * step);
to = index + iStep; if (to>m_size) to = m_size;
index >>= 6; index &= 0xfffffffe;
to >>= 6; to &= 0xfffffffe;
min = max = min_r = max_r = 0;
for (int32 i=index; i<=to; i+=2){
if (buffer_left[i]<min) min = buffer_left[i];
if (buffer_left[i+1]>max) max = buffer_left[i+1];
if (buffer_right[i]<min_r) min_r = buffer_right[i];
if (buffer_right[i+1]>max_r) max_r = buffer_right[i+1];
}
*out++ = min/32767.0;
*out++ = max/32767.0;
*out_r++ = min_r/32767.0;
*out_r++ = max_r/32767.0;
}
}
}
| 11,799 | 6,160 |
#include "duckdb/common/sort/comparators.hpp"
#include "duckdb/common/sort/sort.hpp"
namespace duckdb {
//! Calls std::sort on strings that are tied by their prefix after the radix sort
static void SortTiedBlobs(BufferManager &buffer_manager, const data_ptr_t dataptr, const idx_t &start, const idx_t &end,
const idx_t &tie_col, bool *ties, const data_ptr_t blob_ptr, const SortLayout &sort_layout) {
const auto row_width = sort_layout.blob_layout.GetRowWidth();
const idx_t &col_idx = sort_layout.sorting_to_blob_col.at(tie_col);
// Locate the first blob row in question
data_ptr_t row_ptr = dataptr + start * sort_layout.entry_size;
data_ptr_t blob_row_ptr = blob_ptr + Load<uint32_t>(row_ptr + sort_layout.comparison_size) * row_width;
if (!Comparators::TieIsBreakable(col_idx, blob_row_ptr, sort_layout.blob_layout)) {
// Quick check to see if ties can be broken
return;
}
// Fill pointer array for sorting
auto ptr_block = unique_ptr<data_ptr_t[]>(new data_ptr_t[end - start]);
auto entry_ptrs = (data_ptr_t *)ptr_block.get();
for (idx_t i = start; i < end; i++) {
entry_ptrs[i - start] = row_ptr;
row_ptr += sort_layout.entry_size;
}
// Slow pointer-based sorting
const int order = sort_layout.order_types[tie_col] == OrderType::DESCENDING ? -1 : 1;
const auto &tie_col_offset = sort_layout.blob_layout.GetOffsets()[col_idx];
auto logical_type = sort_layout.blob_layout.GetTypes()[col_idx];
std::sort(entry_ptrs, entry_ptrs + end - start,
[&blob_ptr, &order, &sort_layout, &tie_col_offset, &row_width, &logical_type](const data_ptr_t l,
const data_ptr_t r) {
idx_t left_idx = Load<uint32_t>(l + sort_layout.comparison_size);
idx_t right_idx = Load<uint32_t>(r + sort_layout.comparison_size);
data_ptr_t left_ptr = blob_ptr + left_idx * row_width + tie_col_offset;
data_ptr_t right_ptr = blob_ptr + right_idx * row_width + tie_col_offset;
return order * Comparators::CompareVal(left_ptr, right_ptr, logical_type) < 0;
});
// Re-order
auto temp_block =
buffer_manager.Allocate(MaxValue((end - start) * sort_layout.entry_size, (idx_t)Storage::BLOCK_SIZE));
data_ptr_t temp_ptr = temp_block->Ptr();
for (idx_t i = 0; i < end - start; i++) {
memcpy(temp_ptr, entry_ptrs[i], sort_layout.entry_size);
temp_ptr += sort_layout.entry_size;
}
memcpy(dataptr + start * sort_layout.entry_size, temp_block->Ptr(), (end - start) * sort_layout.entry_size);
// Determine if there are still ties (if this is not the last column)
if (tie_col < sort_layout.column_count - 1) {
data_ptr_t idx_ptr = dataptr + start * sort_layout.entry_size + sort_layout.comparison_size;
// Load current entry
data_ptr_t current_ptr = blob_ptr + Load<uint32_t>(idx_ptr) * row_width + tie_col_offset;
for (idx_t i = 0; i < end - start - 1; i++) {
// Load next entry and compare
idx_ptr += sort_layout.entry_size;
data_ptr_t next_ptr = blob_ptr + Load<uint32_t>(idx_ptr) * row_width + tie_col_offset;
ties[start + i] = Comparators::CompareVal(current_ptr, next_ptr, logical_type) == 0;
current_ptr = next_ptr;
}
}
}
//! Identifies sequences of rows that are tied by the prefix of a blob column, and sorts them
static void SortTiedBlobs(BufferManager &buffer_manager, SortedBlock &sb, bool *ties, data_ptr_t dataptr,
const idx_t &count, const idx_t &tie_col, const SortLayout &sort_layout) {
D_ASSERT(!ties[count - 1]);
auto &blob_block = sb.blob_sorting_data->data_blocks.back();
auto blob_handle = buffer_manager.Pin(blob_block.block);
const data_ptr_t blob_ptr = blob_handle->Ptr();
for (idx_t i = 0; i < count; i++) {
if (!ties[i]) {
continue;
}
idx_t j;
for (j = i; j < count; j++) {
if (!ties[j]) {
break;
}
}
SortTiedBlobs(buffer_manager, dataptr, i, j + 1, tie_col, ties, blob_ptr, sort_layout);
i = j;
}
}
//! Returns whether there are any 'true' values in the ties[] array
static bool AnyTies(bool ties[], const idx_t &count) {
D_ASSERT(!ties[count - 1]);
bool any_ties = false;
for (idx_t i = 0; i < count - 1; i++) {
any_ties = any_ties || ties[i];
}
return any_ties;
}
//! Compares subsequent rows to check for ties
static void ComputeTies(data_ptr_t dataptr, const idx_t &count, const idx_t &col_offset, const idx_t &tie_size,
bool ties[], const SortLayout &sort_layout) {
D_ASSERT(!ties[count - 1]);
D_ASSERT(col_offset + tie_size <= sort_layout.comparison_size);
// Align dataptr
dataptr += col_offset;
for (idx_t i = 0; i < count - 1; i++) {
ties[i] = ties[i] && memcmp(dataptr, dataptr + sort_layout.entry_size, tie_size) == 0;
dataptr += sort_layout.entry_size;
}
}
//! Textbook LSD radix sort
static void RadixSort(BufferManager &buffer_manager, data_ptr_t dataptr, const idx_t &count, const idx_t &col_offset,
const idx_t &sorting_size, const SortLayout &sort_layout) {
auto temp_block = buffer_manager.Allocate(MaxValue(count * sort_layout.entry_size, (idx_t)Storage::BLOCK_SIZE));
data_ptr_t temp = temp_block->Ptr();
bool swap = false;
idx_t counts[256];
uint8_t byte;
for (idx_t offset = col_offset + sorting_size - 1; offset + 1 > col_offset; offset--) {
// Init counts to 0
memset(counts, 0, sizeof(counts));
// Collect counts
for (idx_t i = 0; i < count; i++) {
byte = *(dataptr + i * sort_layout.entry_size + offset);
counts[byte]++;
}
// Compute offsets from counts
for (idx_t val = 1; val < 256; val++) {
counts[val] = counts[val] + counts[val - 1];
}
// Re-order the data in temporary array
for (idx_t i = count; i > 0; i--) {
byte = *(dataptr + (i - 1) * sort_layout.entry_size + offset);
memcpy(temp + (counts[byte] - 1) * sort_layout.entry_size, dataptr + (i - 1) * sort_layout.entry_size,
sort_layout.entry_size);
counts[byte]--;
}
std::swap(dataptr, temp);
swap = !swap;
}
// Move data back to original buffer (if it was swapped)
if (swap) {
memcpy(temp, dataptr, count * sort_layout.entry_size);
}
}
//! Identifies sequences of rows that are tied, and calls radix sort on these
static void SubSortTiedTuples(BufferManager &buffer_manager, const data_ptr_t dataptr, const idx_t &count,
const idx_t &col_offset, const idx_t &sorting_size, bool ties[],
const SortLayout &sort_layout) {
D_ASSERT(!ties[count - 1]);
for (idx_t i = 0; i < count; i++) {
if (!ties[i]) {
continue;
}
idx_t j;
for (j = i + 1; j < count; j++) {
if (!ties[j]) {
break;
}
}
RadixSort(buffer_manager, dataptr + i * sort_layout.entry_size, j - i + 1, col_offset, sorting_size,
sort_layout);
i = j;
}
}
void LocalSortState::SortInMemory() {
auto &sb = *sorted_blocks.back();
auto &block = sb.radix_sorting_data.back();
const auto &count = block.count;
auto handle = buffer_manager->Pin(block.block);
const auto dataptr = handle->Ptr();
// Assign an index to each row
data_ptr_t idx_dataptr = dataptr + sort_layout->comparison_size;
for (uint32_t i = 0; i < count; i++) {
Store<uint32_t>(i, idx_dataptr);
idx_dataptr += sort_layout->entry_size;
}
// Radix sort and break ties until no more ties, or until all columns are sorted
idx_t sorting_size = 0;
idx_t col_offset = 0;
unique_ptr<bool[]> ties_ptr;
unique_ptr<BufferHandle> ties_handle;
bool *ties = nullptr;
for (idx_t i = 0; i < sort_layout->column_count; i++) {
sorting_size += sort_layout->column_sizes[i];
if (sort_layout->constant_size[i] && i < sort_layout->column_count - 1 && sorting_size < 32) {
// Add columns to the sorting size until we reach a variable size column, or the last column
continue;
}
if (!ties) {
// This is the first sort
RadixSort(*buffer_manager, dataptr, count, col_offset, sorting_size, *sort_layout);
ties_ptr = unique_ptr<bool[]>(new bool[count]);
ties = ties_ptr.get();
std::fill_n(ties, count - 1, true);
ties[count - 1] = false;
} else {
// For subsequent sorts, we only have to subsort the tied tuples
SubSortTiedTuples(*buffer_manager, dataptr, count, col_offset, sorting_size, ties, *sort_layout);
}
if (sort_layout->constant_size[i] && i == sort_layout->column_count - 1) {
// All columns are sorted, no ties to break because last column is constant size
break;
}
ComputeTies(dataptr, count, col_offset, sorting_size, ties, *sort_layout);
if (!AnyTies(ties, count)) {
// No ties, stop sorting
break;
}
if (!sort_layout->constant_size[i]) {
SortTiedBlobs(*buffer_manager, sb, ties, dataptr, count, i, *sort_layout);
if (!AnyTies(ties, count)) {
// No more ties after tie-breaking, stop
break;
}
}
col_offset += sorting_size;
sorting_size = 0;
}
}
} // namespace duckdb
| 8,914 | 3,442 |
/*
* Copyright :SIAT 异构智能计算体系结构与系统研究中心
* Author : Heldon 764165887@qq.com
* Date :19-03-01
* Description:containerizer(docker) codes
*/
#ifndef CHAMELEON_DOCKER_HPP
#define CHAMELEON_DOCKER_HPP
//C++11 dependencies
#include <list>
#include <map>
#include <set>
#include <string>
//stout dependencies
#include <stout/os.hpp>
//google dependencies
#include <gflags/gflags.h>
//libprocess dependencies
#include <process/owned.hpp>
#include <process/shared.hpp>
#include <process/process.hpp>
//chameleon dependencies
#include <resources.hpp>
#include "docker/docker.hpp"
#include "docker/resources.hpp"
namespace chameleon{
namespace slave{
//Foward declaration
class DockerContainerizerProcess;
class DockerContainerizer{
public:
static Try<DockerContainerizer*> create();
DockerContainerizer(process::Shared<Docker> docker);
virtual process::Future<bool> launch(
const mesos::ContainerID& containerId,
const Option<mesos::TaskInfo>& taskInfo,
const mesos::ExecutorInfo& executorInfo,
const std::string directory,
const Option<std::string>& user,
const mesos::SlaveID& slaveId,
const std::map<std::string, std::string>& environment);
virtual ~DockerContainerizer();
private:
process::Owned<DockerContainerizerProcess> m_process;
};
class DockerContainerizerProcess : public process::Process<DockerContainerizerProcess>{
public:
DockerContainerizerProcess(process::Shared<Docker> _docker) : m_docker(_docker){}
//start launch containerizer
virtual process::Future<bool> launch(
const mesos::ContainerID& contaierId,
const Option<mesos::TaskInfo>& taskInfo,
const mesos::ExecutorInfo& executorInfo,
const std::string& directory,
const Option<std::string>& user,
const mesos::SlaveID& slaveId,
const std::map<std::string, std::string>& environment);
// pull the image
virtual process::Future<Nothing> pull(const mesos::ContainerID& containerId);
private:
process::Future<bool> _launch(
const mesos::ContainerID& containerId,
const Option<mesos::TaskInfo>& taskInfo,
const mesos::ExecutorInfo& executorInfo,
const std::string& directory,
const mesos::SlaveID& slaveId);
// Starts the executor in a Docker container.
process::Future<Docker::Container> launchExecutorContainer(
const mesos::ContainerID& containerId,
const std::string& containerName);
//const Flags m_flags;
process::Shared<Docker> m_docker;
struct Container{
const mesos::ContainerID m_id;
const Option<mesos::TaskInfo> m_task;
const mesos::ExecutorInfo m_executor;
mesos::ContainerInfo m_container;
mesos::CommandInfo m_command;
std::map<std::string, std::string> m_environment;
Option<std::map<std::string, std::string>> m_taskEnvironment;
// The sandbox directory for the container.
std::string m_directory;
const Option<std::string> m_user;
mesos::SlaveID m_slaveId;
//const Flags m_flags;
mesos::Resources m_resources;
process::Future<Docker::Image> m_pull;
process::Future<bool> m_launch;
static Try<Container*> create(
const mesos::ContainerID& id,
const Option<mesos::TaskInfo>& taskInfo,
const mesos::ExecutorInfo& executorInfo,
const std::string& directory,
const Option<std::string>& user,
const mesos::SlaveID& slaveId,
const std::map<std::string, std::string>& environment);
static std::string name(const mesos::SlaveID& slaveId, const std::string& id) {
return "chameleon-" + slaveId.value() + "." +
stringify(id);
}
Container(const mesos::ContainerID& id,
const Option<mesos::TaskInfo>& taskInfo,
const mesos::ExecutorInfo& executorInfo,
const std::string& directory,
const Option<std::string>& user,
const mesos::SlaveID& slaveId,
const Option<mesos::CommandInfo>& _command,
const Option<mesos::ContainerInfo>& _container,
const std::map<std::string, std::string>& _environment)
: m_id(id),
m_task(taskInfo),
m_executor(executorInfo),
m_environment(_environment),
m_directory(directory),
m_user(user),
m_slaveId(slaveId){
LOG(INFO)<<"Heldon Enter construct function Container";
m_resources = m_executor.resources();
if (m_task.isSome()) {
CHECK(m_resources.contains(m_task.get().resources()));
}
if (_command.isSome()) {
m_command = _command.get();
} else if (m_task.isSome()) {
m_command = m_task.get().command();
} else {
m_command = m_executor.command();
}
if (_container.isSome()) {
m_container = _container.get();
} else if (m_task.isSome()) {
m_container = m_task.get().container();
} else {
m_container = m_executor.container();
}
}
~Container() {
os::rm(m_directory);
}
std::string name(){
return name(m_slaveId, stringify(m_id));
}
std::string image() const{
if(m_task.isSome()){
return m_task.get().container().docker().image();
}
return m_executor.container().docker().image();
}
};
hashmap<mesos::ContainerID, Container*> m_containers;
};
}
}
#endif //CHAMELEON_DOCKER_HPP
| 6,493 | 1,736 |
#include "ScoreProcessor.h"
#include "ExecutionManager.h"
#include "ScenePlayer.h"
using namespace std;
PlayableProcessor::PlayableProcessor(ScenePlayer *splayer)
{
player = splayer;
currentState = player->manager->GetControlStateSafe();
SetJudgeWidths(0.033, 0.066, 0.084);
SetJudgeAdjusts(0, 1, 0, 1);
}
PlayableProcessor::PlayableProcessor(ScenePlayer *splayer, const bool autoAir) : PlayableProcessor(splayer)
{
isAutoAir = autoAir;
}
void PlayableProcessor::SetAutoAir(const bool flag)
{
isAutoAir = flag;
}
void PlayableProcessor::SetJudgeWidths(const double jc, const double j, const double a)
{
judgeWidthAttack = a;
judgeWidthJustice = j;
judgeWidthJusticeCritical = jc;
}
void PlayableProcessor::SetJudgeAdjusts(const double jas, const double jms, const double jaa, const double jma)
{
judgeAdjustSlider = jas;
judgeMultiplierSlider = jms;
judgeAdjustAirString = jaa;
judgeMultiplierAir = jma;
}
void PlayableProcessor::Reset()
{
player->currentResult->Reset();
data = player->data;
auto an = 0;
for (auto ¬e : data) {
const auto type = note->Type.to_ulong();
if (type & SU_NOTE_LONG_MASK) {
if (!note->Type.test(size_t(SusNoteType::AirAction))) an++;
for (auto &ex : note->ExtraData)
if (
ex->Type.test(size_t(SusNoteType::End))
|| ex->Type.test(size_t(SusNoteType::Step))
|| ex->Type.test(size_t(SusNoteType::Injection)))
an++;
} else if (type & SU_NOTE_SHORT_MASK) {
an++;
}
}
player->currentResult->SetAllNotes(an);
imageHoldLight = dynamic_cast<SImage*>(player->resources["LaneHoldLight"]);
}
bool PlayableProcessor::ShouldJudge(std::shared_ptr<SusDrawableNoteData> note)
{
auto current = player->currentTime - note->StartTime;
const auto extra = 0.033;
const auto leastWidthAir = judgeWidthAttack * judgeMultiplierAir + extra;
const auto leastWidthSlider = judgeWidthAttack * judgeMultiplierSlider + extra;
if (note->Type.to_ulong() & SU_NOTE_LONG_MASK) {
if (note->Type[size_t(SusNoteType::AirAction)]) {
current -= judgeAdjustAirString;
return current >= -leastWidthAir && current <= note->Duration + leastWidthAir;
} else {
current -= judgeAdjustSlider;
return current >= -leastWidthSlider && current <= note->Duration + leastWidthSlider;
}
}
if (note->Type[size_t(SusNoteType::Air)]) {
current -= judgeAdjustAirString;
return current >= -leastWidthAir && current <= leastWidthAir;
}
current -= judgeAdjustSlider;
return current >= -leastWidthSlider && current <= leastWidthSlider;
}
void PlayableProcessor::Update(vector<shared_ptr<SusDrawableNoteData>>& notes)
{
auto slideCheck = false;
auto holdCheck = false;
auto aaCheck = false;
isInHold = false;
for (auto& note : notes) {
ProcessScore(note);
slideCheck = isInSlide || slideCheck;
holdCheck = isInHold || holdCheck;
aaCheck = isInAA || aaCheck;
}
if (!wasInSlide && slideCheck) player->EnqueueJudgeSound(JudgeSoundType::Sliding);
if (wasInSlide && !slideCheck) player->EnqueueJudgeSound(JudgeSoundType::SlidingStop);
if (!wasInHold && holdCheck) player->EnqueueJudgeSound(JudgeSoundType::Holding);
if (wasInHold && !holdCheck) player->EnqueueJudgeSound(JudgeSoundType::HoldingStop);
if (!wasInAA && aaCheck) player->EnqueueJudgeSound(JudgeSoundType::AirHolding);
if (wasInAA && !aaCheck) player->EnqueueJudgeSound(JudgeSoundType::AirHoldingStop);
player->airActionShown = aaCheck;
wasInHold = holdCheck;
wasInSlide = slideCheck;
wasInAA = aaCheck;
}
void PlayableProcessor::MovePosition(const double relative)
{
const auto newTime = player->currentTime + relative;
player->currentResult->Reset();
wasInHold = isInHold = false;
wasInSlide = isInSlide = false;
wasInAA = isInAA = false;
player->EnqueueJudgeSound(JudgeSoundType::HoldingStop);
player->EnqueueJudgeSound(JudgeSoundType::SlidingStop);
player->EnqueueJudgeSound(JudgeSoundType::AirHoldingStop);
player->RemoveSlideEffect();
// 送り: 飛ばした部分をFinishedに
// 戻し: 入ってくる部分をUn-Finishedに
for (auto ¬e : data) {
if (note->Type.test(size_t(SusNoteType::Hold))
|| note->Type.test(size_t(SusNoteType::Slide))
|| note->Type.test(size_t(SusNoteType::AirAction))) {
if (note->StartTime <= newTime) {
note->OnTheFlyData.set(size_t(NoteAttribute::Finished));
if (!note->Type.test(size_t(SusNoteType::AirAction))) player->currentResult->PerformMiss();
} else {
note->OnTheFlyData.reset(size_t(NoteAttribute::Finished));
}
note->OnTheFlyData.reset(size_t(NoteAttribute::Activated));
for (auto &extra : note->ExtraData) {
if (!extra->Type.test(size_t(SusNoteType::End))
&& !extra->Type.test(size_t(SusNoteType::Step))
&& !extra->Type.test(size_t(SusNoteType::Injection))) continue;
if (extra->StartTime <= newTime) {
extra->OnTheFlyData.set(size_t(NoteAttribute::Finished));
if (
extra->Type.test(size_t(SusNoteType::End))
|| extra->Type.test(size_t(SusNoteType::Step))
|| extra->Type.test(size_t(SusNoteType::Injection))) player->currentResult->PerformMiss();
} else {
extra->OnTheFlyData.reset(size_t(NoteAttribute::Finished));
}
}
} else {
if (note->StartTime <= newTime) {
note->OnTheFlyData.set(size_t(NoteAttribute::Finished));
if (note->Type.to_ulong() & SU_NOTE_SHORT_MASK) player->currentResult->PerformMiss();
} else {
note->OnTheFlyData.reset(size_t(NoteAttribute::Finished));
}
}
}
}
void PlayableProcessor::Draw()
{
if (!imageHoldLight) return;
SetDrawBlendMode(DX_BLENDMODE_ALPHA, 255);
for (auto i = 0; i < 16; i++)
if (currentState->GetCurrentState(ControllerSource::IntegratedSliders, i))
DrawRectRotaGraph3F(
player->widthPerLane * i, player->laneBufferY,
0, 0,
imageHoldLight->GetWidth(), imageHoldLight->GetHeight(),
0, imageHoldLight->GetHeight(),
1, 2, 0,
imageHoldLight->GetHandle(), TRUE, FALSE);
}
void PlayableProcessor::ProcessScore(const shared_ptr<SusDrawableNoteData>& note)
{
if (note->OnTheFlyData.test(size_t(NoteAttribute::Finished)) && note->ExtraData.empty()) return;
if (note->Type.test(size_t(SusNoteType::Hold))) {
isInHold = CheckHoldJudgement(note);
} else if (note->Type.test(size_t(SusNoteType::Slide))) {
isInSlide = CheckSlideJudgement(note);
} else if (note->Type.test(size_t(SusNoteType::AirAction))) {
isInAA = CheckAirActionJudgement(note);
} else if (note->Type.test(size_t(SusNoteType::Air))) {
if (!CheckAirJudgement(note)) return;
if (note->Type[size_t(SusNoteType::Up)]) {
player->EnqueueJudgeSound(JudgeSoundType::Air);
} else {
player->EnqueueJudgeSound(JudgeSoundType::AirDown);
}
player->SpawnJudgeEffect(note, JudgeType::ShortNormal);
player->SpawnJudgeEffect(note, JudgeType::ShortEx);
} else if (note->Type.test(size_t(SusNoteType::Tap))) {
if (!CheckJudgement(note)) return;
player->EnqueueJudgeSound(JudgeSoundType::Tap);
player->SpawnJudgeEffect(note, JudgeType::ShortNormal);
} else if (note->Type.test(size_t(SusNoteType::ExTap))) {
if (!CheckJudgement(note)) return;
player->EnqueueJudgeSound(JudgeSoundType::ExTap);
player->SpawnJudgeEffect(note, JudgeType::ShortNormal);
player->SpawnJudgeEffect(note, JudgeType::ShortEx);
} else if (note->Type.test(size_t(SusNoteType::AwesomeExTap))) {
if (!CheckJudgement(note)) return;
player->EnqueueJudgeSound(JudgeSoundType::ExTap);
player->SpawnJudgeEffect(note, JudgeType::ShortNormal);
player->SpawnJudgeEffect(note, JudgeType::ShortEx);
} else if (note->Type.test(size_t(SusNoteType::Flick))) {
if (!CheckJudgement(note)) return;
player->EnqueueJudgeSound(JudgeSoundType::Flick);
player->SpawnJudgeEffect(note, JudgeType::ShortNormal);
} else if (note->Type.test(size_t(SusNoteType::HellTap))) {
if (!CheckHellJudgement(note)) return;
player->EnqueueJudgeSound(JudgeSoundType::Tap);
player->SpawnJudgeEffect(note, JudgeType::ShortNormal);
}
}
bool PlayableProcessor::CheckJudgement(const shared_ptr<SusDrawableNoteData>& note) const
{
auto reltime = player->currentTime - note->StartTime - judgeAdjustSlider;
reltime /= judgeMultiplierSlider;
if (note->OnTheFlyData.test(size_t(NoteAttribute::Finished))) return false;
if (reltime < -judgeWidthAttack) return false;
if (reltime > judgeWidthAttack) {
if (note->Type[size_t(SusNoteType::ExTap)]) {
ResetCombo(note, AbilityNoteType::ExTap);
} else if (note->Type[size_t(SusNoteType::Flick)]) {
ResetCombo(note, AbilityNoteType::Flick);
} else {
ResetCombo(note, AbilityNoteType::Tap);
}
return false;
}
for (int i = note->StartLane; i < note->StartLane + note->Length; i++) {
if (!currentState->GetTriggerState(ControllerSource::IntegratedSliders, i)) continue;
if (note->Type[size_t(SusNoteType::ExTap)]) {
IncrementComboEx(note, "");
} else if (note->Type[size_t(SusNoteType::AwesomeExTap)]) {
IncrementComboEx(
note,
note->Type[size_t(SusNoteType::Down)]
? "AwesomeExTapDown"
: "AwesomeExTapUp"
);
} else if (note->Type[size_t(SusNoteType::Flick)]) {
IncrementCombo(note, reltime, AbilityNoteType::Flick, "");
} else {
IncrementCombo(note, reltime, AbilityNoteType::Tap, "");
}
return true;
}
return false;
}
bool PlayableProcessor::CheckHellJudgement(const shared_ptr<SusDrawableNoteData>& note) const
{
auto reltime = player->currentTime - note->StartTime - judgeAdjustSlider;
reltime *= judgeMultiplierSlider; // Hellだからね
if (note->OnTheFlyData.test(size_t(NoteAttribute::Finished))) return false;
if (reltime < -judgeWidthAttack) return false;
if (reltime > judgeWidthAttack) {
IncrementComboHell(note, -1, "");
return false;
}
if (reltime >= 0 && !note->OnTheFlyData.test(size_t(NoteAttribute::HellChecking))) {
IncrementComboHell(note, 0, "");
return true;
}
for (int i = note->StartLane; i < note->StartLane + note->Length; i++) {
/* 押しっぱなしにしていた時にJC出るのは違う気がした */
if (!currentState->GetCurrentState(ControllerSource::IntegratedSliders, i)) continue;
IncrementComboHell(note, 1, "");
return false;
}
return false;
}
bool PlayableProcessor::CheckAirJudgement(const shared_ptr<SusDrawableNoteData>& note) const
{
auto reltime = player->currentTime - note->StartTime - judgeAdjustAirString;
reltime /= judgeMultiplierAir;
if (note->OnTheFlyData.test(size_t(NoteAttribute::Finished))) return false;
if (reltime < -judgeWidthAttack) return false;
if (reltime > judgeWidthAttack) {
ResetCombo(note, AbilityNoteType::Air);
return false;
}
if (isAutoAir) {
if (reltime >= 0) {
IncrementComboAir(note, reltime, AbilityNoteType::Air, "");
return true;
}
} else {
const auto judged = currentState->GetTriggerState(
ControllerSource::IntegratedAir,
note->Type[size_t(SusNoteType::Up)] ? int(AirControlSource::AirUp) : int(AirControlSource::AirDown));
if (judged) {
IncrementComboAir(note, (reltime < 0.0) ? 0.0 : reltime, AbilityNoteType::Air, "");
return true;
}
}
return false;
}
bool PlayableProcessor::CheckHoldJudgement(const shared_ptr<SusDrawableNoteData>& note) const
{
const auto reltime = player->currentTime - note->StartTime - judgeAdjustSlider;
if (reltime < -judgeWidthAttack) return false;
if (note->OnTheFlyData[size_t(NoteAttribute::Completed)]) return false;
//現在の判定位置を調べる
const int left = note->StartLane;
const auto right = left + note->Length;
// left <= i < right で判定
auto held = false, trigger = false, release = false;
for (auto i = left; i < right; i++) {
held |= currentState->GetCurrentState(ControllerSource::IntegratedSliders, i);
trigger |= currentState->GetTriggerState(ControllerSource::IntegratedSliders, i);
release |= currentState->GetLastState(ControllerSource::IntegratedSliders, i) && !currentState->GetCurrentState(ControllerSource::IntegratedSliders, i);
}
auto judgeTime = player->currentTime - note->StartTime - judgeAdjustSlider;
judgeTime /= judgeMultiplierSlider;
// Start判定
if (!note->OnTheFlyData[size_t(NoteAttribute::Finished)]) {
if (judgeTime >= judgeWidthAttack) {
ResetCombo(note, AbilityNoteType::Hold);
} else if (trigger) {
IncrementCombo(note, judgeTime, AbilityNoteType::Hold, "");
player->EnqueueJudgeSound(JudgeSoundType::Tap);
player->SpawnJudgeEffect(note, JudgeType::ShortNormal);
}
if (held) {
note->OnTheFlyData.set(size_t(NoteAttribute::Activated));
} else {
note->OnTheFlyData.reset(size_t(NoteAttribute::Activated));
}
return held;
}
if (held) {
note->OnTheFlyData.set(size_t(NoteAttribute::Activated));
}
else {
note->OnTheFlyData.reset(size_t(NoteAttribute::Activated));
}
// Step~End判定
// 手前: 無視
// 0~Att: 判定が入ったタイミングで加算
// Att~: 切る
for (const auto &extra : note->ExtraData) {
judgeTime = player->currentTime - extra->StartTime - judgeAdjustSlider;
judgeTime /= judgeMultiplierSlider;
if (extra->OnTheFlyData[size_t(NoteAttribute::Finished)]) continue;
if (extra->Type[size_t(SusNoteType::Control)]) continue;
if (extra->Type[size_t(SusNoteType::Invisible)]) continue;
if (judgeTime < 0) {
return held;
}
if (judgeTime >= judgeWidthAttack) {
ResetCombo(extra, AbilityNoteType::Hold);
if (extra->Type[size_t(SusNoteType::End)]) {
note->OnTheFlyData.set(size_t(NoteAttribute::Completed));
}
return held;
}
if (held) {
if (extra->Type[size_t(SusNoteType::Injection)]) {
IncrementCombo(extra, judgeTime, AbilityNoteType::Hold, "");
} else {
IncrementCombo(extra, judgeTime, AbilityNoteType::Hold, "");
player->EnqueueJudgeSound(JudgeSoundType::HoldStep);
player->SpawnJudgeEffect(extra, JudgeType::SlideTap);
}
if (extra->Type[size_t(SusNoteType::End)]) {
note->OnTheFlyData.set(size_t(NoteAttribute::Completed));
}
return true;
}
}
return held;
}
bool PlayableProcessor::CheckSlideJudgement(const shared_ptr<SusDrawableNoteData>& note) const
{
const auto reltime = player->currentTime - note->StartTime - judgeAdjustSlider;
if (reltime < -judgeWidthAttack) return false;
if (note->OnTheFlyData[size_t(NoteAttribute::Completed)]) return false;
//現在の判定位置を調べる
auto lastStep = note;
auto refNote = note;
int left, right;
for (const auto &extra : note->ExtraData) {
if (extra->Type[size_t(SusNoteType::Control)]) continue;
if (extra->Type[size_t(SusNoteType::Injection)]) continue;
if (player->currentTime <= extra->StartTime) {
refNote = extra;
break;
}
lastStep = refNote = extra;
}
if (lastStep == refNote) {
// 終点より後
left = lastStep->StartLane;
right = left + lastStep->Length;
} else if (reltime < 0) {
// 始点より前
left = note->StartLane;
right = left + note->Length;
} else {
// カーブデータ存在範囲内
auto &refcurve = player->curveData[refNote];
const auto timeInBlock = player->currentTime - lastStep->StartTime;
auto start = refcurve[0];
auto next = refcurve[0];
for (const auto &segment : refcurve) {
if (get<0>(segment) >= timeInBlock) {
next = segment;
break;
}
start = next = segment;
}
const auto center = glm::mix(get<1>(start), get<1>(next), (timeInBlock - get<0>(start)) / (get<0>(next) - get<0>(start))) * 16;
const auto width = glm::mix(lastStep->Length, refNote->Length, timeInBlock / (refNote->StartTime - lastStep->StartTime));
left = floor(center - width / 2.0);
right = ceil(center + width / 2.0);
ostringstream ss;
// ss << "Curve: " << left << ", " << right << endl;
// WriteDebugConsole(ss.str().c_str());
}
// left <= i < right で判定
auto held = false, trigger = false, release = false;
for (auto i = left; i < right; i++) {
held |= currentState->GetCurrentState(ControllerSource::IntegratedSliders, i);
trigger |= currentState->GetTriggerState(ControllerSource::IntegratedSliders, i);
release |= currentState->GetLastState(ControllerSource::IntegratedSliders, i) && !currentState->GetCurrentState(ControllerSource::IntegratedSliders, i);
}
auto judgeTime = player->currentTime - note->StartTime - judgeAdjustSlider;
judgeTime /= judgeMultiplierSlider;
// Start判定
if (!note->OnTheFlyData[size_t(NoteAttribute::Finished)]) {
if (judgeTime >= judgeWidthAttack) {
ResetCombo(note, AbilityNoteType::Slide);
} else if (trigger) {
IncrementCombo(note, judgeTime, AbilityNoteType::Slide, "");
player->EnqueueJudgeSound(JudgeSoundType::SlideStep);
player->SpawnJudgeEffect(note, JudgeType::ShortNormal);
}
if (held) {
note->OnTheFlyData.set(size_t(NoteAttribute::Activated));
}
else {
note->OnTheFlyData.reset(size_t(NoteAttribute::Activated));
}
return held;
}
if (held) {
note->OnTheFlyData.set(size_t(NoteAttribute::Activated));
}
else {
note->OnTheFlyData.reset(size_t(NoteAttribute::Activated));
}
// Step~End判定
for (const auto &extra : note->ExtraData) {
judgeTime = player->currentTime - extra->StartTime - judgeAdjustSlider;
judgeTime /= judgeMultiplierSlider;
if (extra->OnTheFlyData[size_t(NoteAttribute::Finished)]) continue;
if (extra->Type[size_t(SusNoteType::Control)]) continue;
if (extra->Type[size_t(SusNoteType::Invisible)]) continue;
if (judgeTime < 0) {
return held;
}
if (judgeTime >= judgeWidthAttack) {
ResetCombo(extra, AbilityNoteType::Slide);
if (extra->Type[size_t(SusNoteType::End)]) {
note->OnTheFlyData.set(size_t(NoteAttribute::Completed));
}
return held;
}
if (held) {
if (extra->Type[size_t(SusNoteType::Injection)]) {
IncrementCombo(extra, judgeTime, AbilityNoteType::Slide, "");
} else {
IncrementCombo(extra, judgeTime, AbilityNoteType::Slide, "");
player->EnqueueJudgeSound(JudgeSoundType::Tap);
player->SpawnJudgeEffect(extra, JudgeType::SlideTap);
}
if (extra->Type[size_t(SusNoteType::End)]) {
note->OnTheFlyData.set(size_t(NoteAttribute::Completed));
}
return true;
}
return held;
}
return held;
}
bool PlayableProcessor::CheckAirActionJudgement(const shared_ptr<SusDrawableNoteData>& note) const
{
const auto reltime = player->currentTime - note->StartTime - judgeAdjustAirString;
if (reltime < -judgeWidthAttack * judgeMultiplierAir) return false;
if (note->OnTheFlyData[size_t(NoteAttribute::Completed)]) return false;
const auto held = currentState->GetCurrentState(ControllerSource::IntegratedAir, int(AirControlSource::AirHold)) || isAutoAir;
// Start判定
// なし
if (held) {
note->OnTheFlyData.set(size_t(NoteAttribute::Activated));
}
else {
note->OnTheFlyData.reset(size_t(NoteAttribute::Activated));
}
// Step~End判定
for (const auto &extra : note->ExtraData) {
auto judgeTime = player->currentTime - extra->StartTime - judgeAdjustAirString;
judgeTime /= judgeMultiplierAir;
if (extra->OnTheFlyData[size_t(NoteAttribute::Finished)]) continue;
if (extra->Type[size_t(SusNoteType::Control)]) continue;
if (extra->Type[size_t(SusNoteType::Invisible)]) continue;
if (judgeTime < 0) {
return held;
}
if (judgeTime >= judgeWidthAttack) {
ResetCombo(extra, AbilityNoteType::AirAction);
if (extra->Type[size_t(SusNoteType::End)]) {
note->OnTheFlyData.set(size_t(NoteAttribute::Completed));
}
return held;
}
if (held) {
if (extra->Type[size_t(SusNoteType::Injection)]) {
IncrementCombo(extra, judgeTime, AbilityNoteType::AirAction, "");
} else {
IncrementCombo(extra, judgeTime, AbilityNoteType::AirAction, "");
player->EnqueueJudgeSound(JudgeSoundType::AirAction);
player->SpawnJudgeEffect(extra, JudgeType::Action);
}
if (extra->Type[size_t(SusNoteType::End)]) {
note->OnTheFlyData.set(size_t(NoteAttribute::Completed));
}
return true;
}
return held;
}
return held;
}
void PlayableProcessor::IncrementCombo(const shared_ptr<SusDrawableNoteData>& note, double reltime, const AbilityNoteType type, const string& extra) const
{
reltime = fabs(reltime);
if (reltime <= judgeWidthJusticeCritical) {
note->OnTheFlyData.set(size_t(NoteAttribute::Finished));
player->currentResult->PerformJusticeCritical();
player->currentCharacterInstance->OnJusticeCritical(type, extra);
} else if (reltime <= judgeWidthJustice) {
note->OnTheFlyData.set(size_t(NoteAttribute::Finished));
player->currentResult->PerformJustice();
player->currentCharacterInstance->OnJustice(type, extra);
} else {
note->OnTheFlyData.set(size_t(NoteAttribute::Finished));
player->currentResult->PerformAttack();
player->currentCharacterInstance->OnAttack(type, extra);
}
}
void PlayableProcessor::IncrementComboEx(const shared_ptr<SusDrawableNoteData>& note, const string& extra) const
{
note->OnTheFlyData.set(size_t(NoteAttribute::Finished));
player->currentResult->PerformJusticeCritical();
player->currentCharacterInstance->OnJusticeCritical(
note->Type[size_t(SusNoteType::AwesomeExTap)]
? AbilityNoteType::AwesomeExTap
: AbilityNoteType::ExTap,
extra
);
}
void PlayableProcessor::IncrementComboHell(const std::shared_ptr<SusDrawableNoteData>& note, const int state, const string& extra) const
{
switch (state) {
case -1:
// 無事判定終了、もう心配ない
/* ここで初めてJC扱いにする */
note->OnTheFlyData.reset(size_t(NoteAttribute::HellChecking));
note->OnTheFlyData.set(size_t(NoteAttribute::Finished));
player->currentResult->PerformJusticeCritical();
player->currentCharacterInstance->OnJusticeCritical(AbilityNoteType::HellTap, extra);
break;
case 0:
// とりあえず通過した
/* ここでJC扱いにするとややこしいので何もしない */
note->OnTheFlyData.set(size_t(NoteAttribute::HellChecking));
// player->currentResult->PerformJusticeCritical();
// player->currentCharacterInstance->OnJusticeCritical(AbilityNoteType::HellTap, extra);
break;
case 1:
// 判定失敗
player->currentResult->PerformMiss();
player->currentCharacterInstance->OnMiss(AbilityNoteType::HellTap, extra);
note->OnTheFlyData.set(size_t(NoteAttribute::Finished));
break;
default: break;
}
}
void PlayableProcessor::IncrementComboAir(const std::shared_ptr<SusDrawableNoteData>& note, double reltime, const AbilityNoteType type, const string& extra) const
{
reltime = fabs(reltime);
if (reltime <= judgeWidthJusticeCritical) {
note->OnTheFlyData.set(size_t(NoteAttribute::Finished));
player->currentResult->PerformJusticeCritical();
player->currentCharacterInstance->OnJusticeCritical(type, extra);
} else if (reltime <= judgeWidthJustice) {
note->OnTheFlyData.set(size_t(NoteAttribute::Finished));
player->currentResult->PerformJustice();
player->currentCharacterInstance->OnJustice(type, extra);
} else {
note->OnTheFlyData.set(size_t(NoteAttribute::Finished));
player->currentResult->PerformAttack();
player->currentCharacterInstance->OnAttack(type, extra);
}
}
void PlayableProcessor::ResetCombo(const shared_ptr<SusDrawableNoteData>& note, const AbilityNoteType type) const
{
note->OnTheFlyData.set(size_t(NoteAttribute::Finished));
player->currentResult->PerformMiss();
player->currentCharacterInstance->OnMiss(type, "");
}
| 26,001 | 8,442 |
#include "meleeattackbhv.h"
#include "util/math.h"
#include "objects//enemy.h"
#include "level/level.h"
MeleeAttackBhv::MeleeAttackBhv(Enemy* owner):
Behaviour(owner),
_attackTime { 0.0f }
{
}
void MeleeAttackBhv::collision(float x, float y, float z)
{
(void) x;
(void) y;
(void) z;
}
void MeleeAttackBhv::damage(float damage)
{
(void) damage;
}
void MeleeAttackBhv::update(double dt)
{
if(_attackTime > .0f)
_attackTime -= dt;
auto player = owner->level->player();
vec2 delta(player->x() - owner->x(), player->y() - owner->y());
if(delta.length() < minAttackDistance) {
owner->speedXY(.0f, .0f);
if(_attackTime <= .0f) {
player->damage(attackDamage, vec3(owner->x(), owner->y(), owner->z()));
_attackTime = attackCooldown;
}
if(owner->state() != EnemyState::ES_ATTACK)
owner->state(EnemyState::ES_ATTACK);
} else {
delta.normalize();
delta *= owner->maxSpeed();
owner->dir(atan2(delta.y, delta.x));
owner->speedXY(delta.x, delta.y);
}
}
| 1,147 | 441 |
/***************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2008 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Qt Software Information (qt-info@nokia.com)
**
**
** Non-Open Source Usage
**
** Licensees may use this file in accordance with the Qt Beta Version
** License Agreement, Agreement version 2.2 provided with the Software or,
** alternatively, in accordance with the terms contained in a written
** agreement between you and Nokia.
**
** GNU General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU General
** Public License versions 2.0 or 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the packaging
** of this file. Please review the following information to ensure GNU
** General Public Licensing requirements will be met:
**
** http://www.fsf.org/licensing/licenses/info/GPLv2.html and
** http://www.gnu.org/copyleft/gpl.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt GPL Exception
** version 1.3, included in the file GPL_EXCEPTION.txt in this package.
**
***************************************************************************/
#include <qglobal.h>
// this relies on contents copied from qobject_p.h
#define PRIVATE_OBJECT_ALLOWED 1
#include <QDateTime>
#include <QDebug>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QHash>
#include <QLocale>
#include <QMap>
#include <QMetaObject>
#include <QMetaProperty>
#include <QModelIndex>
#include <QObject>
#include <QPointer>
#include <QString>
#include <QTextCodec>
#include <QVector>
/*!
\class QDumper
\brief Helper class for producing "nice" output in Qt Creator's debugger.
\internal
The whole "custom dumper" implementation is currently far less modular
than it could be. But as the code is still in a flux, making it nicer
from a pure archtectural point of view seems still be a waste of resources.
Some hints:
New dumpers for non-templated classes should be mentioned in
\c{qDumpObjectData440()} in the \c{protocolVersion == 1} branch.
Templated classes need extra support on the IDE level
(see plugins/debugger/gdbengine.cpp) and should not be mentiond in
\c{qDumpObjectData440()}.
In any case, dumper processesing should end up in
\c{handleProtocolVersion2and3()} and needs an entry in the bis switch there.
Next step is to create a suitable \c{static void qDumpFoo(QDumper &d)}
function. At the bare minimum it should contain something like:
\c{
const Foo &foo = *reinterpret_cast<const Foo *>(d.data);
P(d, "value", ...);
P(d, "type", "Foo");
P(d, "numchild", "0");
}
'P(d, name, value)' roughly expands to:
d << (name) << "=\"" << value << "\"";
Useful (i.e. understood by the IDE) names include:
\list
\o "name" shows up in the first column in the Locals&Watchers view.
\o "value" shows up in the second column.
\o "valueencoded" should be set to "1" if the value is base64 encoded.
Always base64-encode values that might use unprintable or otherwise
"confuse" the protocol (like spaces and quotes). [A-Za-z0-9] is "safe".
A value of "3" is used for base64-encoded UCS4, "2" denotes
base64-encoded UTF16.
\o "numchild" return the number of children in the view. Effectively, only
0 and != 0 will be used, so don't try too hard to get the number right.
\endlist
If the current item has children, it might be queried to produce information
about thes children. In this case the dumper should use something like
\c{
if (d.dumpChildren) {
d << ",children=[";
}
*/
int qtGhVersion = QT_VERSION;
#ifdef QT_GUI_LIB
# include <QPixmap>
# include <QImage>
#endif
#include <list>
#include <map>
#include <string>
#include <vector>
#include <ctype.h>
#include <stdio.h>
#ifdef Q_OS_WIN
# include <windows.h>
#endif
#undef NS
#ifdef QT_NAMESPACE
# define STRINGIFY0(s) #s
# define STRINGIFY1(s) STRINGIFY0(s)
# define NS STRINGIFY1(QT_NAMESPACE) "::"
# define NSX "'" STRINGIFY1(QT_NAMESPACE) "::"
# define NSY "'"
#else
# define NS ""
# define NSX ""
# define NSY ""
#endif
#if PRIVATE_OBJECT_ALLOWED
#if defined(QT_BEGIN_NAMESPACE)
QT_BEGIN_NAMESPACE
#endif
class QVariant;
class QThreadData;
class QObjectConnectionListVector;
class QObjectPrivate : public QObjectData
{
Q_DECLARE_PUBLIC(QObject)
public:
QObjectPrivate() {}
virtual ~QObjectPrivate() {}
// preserve binary compatibility with code compiled without Qt 3 support
QList<QObject *> pendingChildInsertedEvents; // unused
// id of the thread that owns the object
QThreadData *threadData;
struct Sender
{
QObject *sender;
int signal;
int ref;
};
Sender *currentSender; // object currently activating the object
QObject *currentChildBeingDeleted;
QList<QPointer<QObject> > eventFilters;
struct ExtraData;
ExtraData *extraData;
mutable quint32 connectedSignals;
QString objectName;
struct Connection
{
QObject *receiver;
int method;
uint connectionType : 3; // 0 == auto, 1 == direct, 2 == queued, 4 == blocking
QBasicAtomicPointer<int> argumentTypes;
};
typedef QList<Connection> ConnectionList;
QObjectConnectionListVector *connectionLists;
QList<Sender> senders;
int *deleteWatch;
};
#if defined(QT_BEGIN_NAMESPACE)
QT_END_NAMESPACE
#endif
#endif // PRIVATE_OBJECT_ALLOWED
// this can be mangled typenames of nested templates, each char-by-char
// comma-separated integer list
static char qDumpInBuffer[10000];
static char qDumpBuffer[1000];
namespace {
static bool isPointerType(const QByteArray &type)
{
return type.endsWith("*") || type.endsWith("* const");
}
static QByteArray stripPointerType(QByteArray type)
{
if (type.endsWith("*"))
type.chop(1);
if (type.endsWith("* const"))
type.chop(7);
if (type.endsWith(' '))
type.chop(1);
return type;
}
// This is used to abort evaluation of custom data dumpers in a "coordinated"
// way. Abortion will happen anyway when we try to access a non-initialized
// non-trivial object, so there is no way to prevent this from occuring at all
// conceptionally. Gdb will catch SIGSEGV and return to the calling frame.
// This is just fine provided we only _read_ memory in the custom handlers
// below.
volatile int qProvokeSegFaultHelper;
static const void *addOffset(const void *p, int offset)
{
return offset + reinterpret_cast<const char *>(p);
}
static const void *skipvtable(const void *p)
{
return sizeof(void*) + reinterpret_cast<const char *>(p);
}
static const void *deref(const void *p)
{
return *reinterpret_cast<const char* const*>(p);
}
static const void *dfunc(const void *p)
{
return deref(skipvtable(p));
}
static bool isEqual(const char *s, const char *t)
{
return qstrcmp(s, t) == 0;
}
static bool startsWith(const char *s, const char *t)
{
return qstrncmp(s, t, strlen(t)) == 0;
}
// provoke segfault when address is not readable
#define qCheckAccess(d) do { qProvokeSegFaultHelper = *(char*)d; } while (0)
#define qCheckPointer(d) do { if (d) qProvokeSegFaultHelper = *(char*)d; } while (0)
// provoke segfault unconditionally
#define qCheck(b) do { if (!(b)) qProvokeSegFaultHelper = *(char*)0; } while (0)
const char *stripNamespace(const char *type)
{
static const size_t nslen = strlen(NS);
return startsWith(type, NS) ? type + nslen : type;
}
static bool isSimpleType(const char *type)
{
switch (type[0]) {
case 'c':
return isEqual(type, "char");
case 'd':
return isEqual(type, "double");
case 'f':
return isEqual(type, "float");
case 'i':
return isEqual(type, "int");
case 'l':
return isEqual(type, "long") || startsWith(type, "long ");
case 's':
return isEqual(type, "short") || isEqual(type, "signed")
|| startsWith(type, "signed ");
case 'u':
return isEqual(type, "unsigned") || startsWith(type, "unsigned ");
}
return false;
}
static bool isShortKey(const char *type)
{
return isSimpleType(type) || isEqual(type, "QString");
}
static bool isMovableType(const char *type)
{
if (isPointerType(type))
return true;
if (isSimpleType(type))
return true;
type = stripNamespace(type);
switch (type[1]) {
case 'B':
return isEqual(type, "QBrush")
|| isEqual(type, "QBitArray")
|| isEqual(type, "QByteArray") ;
case 'C':
return isEqual(type, "QCustomTypeInfo");
case 'D':
return isEqual(type, "QDate")
|| isEqual(type, "QDateTime");
case 'F':
return isEqual(type, "QFileInfo")
|| isEqual(type, "QFixed")
|| isEqual(type, "QFixedPoint")
|| isEqual(type, "QFixedSize");
case 'H':
return isEqual(type, "QHashDummyValue");
case 'I':
return isEqual(type, "QIcon")
|| isEqual(type, "QImage");
case 'L':
return isEqual(type, "QLine")
|| isEqual(type, "QLineF")
|| isEqual(type, "QLocal");
case 'M':
return isEqual(type, "QMatrix")
|| isEqual(type, "QModelIndex");
case 'P':
return isEqual(type, "QPoint")
|| isEqual(type, "QPointF")
|| isEqual(type, "QPen")
|| isEqual(type, "QPersistentModelIndex");
case 'R':
return isEqual(type, "QResourceRoot")
|| isEqual(type, "QRect")
|| isEqual(type, "QRectF")
|| isEqual(type, "QRegExp");
case 'S':
return isEqual(type, "QSize")
|| isEqual(type, "QSizeF")
|| isEqual(type, "QString");
case 'T':
return isEqual(type, "QTime")
|| isEqual(type, "QTextBlock");
case 'U':
return isEqual(type, "QUrl");
case 'V':
return isEqual(type, "QVariant");
case 'X':
return isEqual(type, "QXmlStreamAttribute")
|| isEqual(type, "QXmlStreamNamespaceDeclaration")
|| isEqual(type, "QXmlStreamNotationDeclaration")
|| isEqual(type, "QXmlStreamEntityDeclaration");
}
return false;
}
struct QDumper
{
explicit QDumper();
~QDumper();
void flush();
void checkFill();
QDumper &operator<<(long c);
QDumper &operator<<(int i);
QDumper &operator<<(double d);
QDumper &operator<<(float d);
QDumper &operator<<(unsigned long c);
QDumper &operator<<(unsigned int i);
QDumper &operator<<(const void *p);
QDumper &operator<<(qulonglong c);
QDumper &operator<<(const char *str);
QDumper &operator<<(const QByteArray &ba);
QDumper &operator<<(const QString &str);
void put(char c);
void addCommaIfNeeded();
void putBase64Encoded(const char *buf, int n);
void putEllipsis();
void disarm();
void beginHash(); // start of data hash output
void endHash(); // start of data hash output
void write(const void *buf, int len); // raw write to stdout
// the dumper arguments
int protocolVersion; // dumper protocol version
int token; // some token to show on success
const char *outertype; // object type
const char *iname; // object name used for display
const char *exp; // object expression
const char *innertype; // 'inner type' for class templates
const void *data; // pointer to raw data
bool dumpChildren; // do we want to see children?
// handling of nested templates
void setupTemplateParameters();
enum { maxTemplateParameters = 10 };
const char *templateParameters[maxTemplateParameters + 1];
int templateParametersCount;
// internal state
bool success; // are we finished?
int pos;
int extraInt[4];
};
QDumper::QDumper()
{
success = false;
pos = 0;
}
QDumper::~QDumper()
{
flush();
char buf[30];
int len = qsnprintf(buf, sizeof(buf) - 1, "%d^done\n", token);
write(buf, len);
}
void QDumper::write(const void *buf, int len)
{
::fwrite(buf, len, 1, stdout);
::fflush(stdout);
}
void QDumper::flush()
{
if (pos != 0) {
char buf[30];
int len = qsnprintf(buf, sizeof(buf) - 1, "%d#%d,", token, pos);
write(buf, len);
write(qDumpBuffer, pos);
write("\n", 1);
pos = 0;
}
}
void QDumper::setupTemplateParameters()
{
char *s = const_cast<char *>(innertype);
templateParametersCount = 1;
templateParameters[0] = s;
for (int i = 1; i != maxTemplateParameters + 1; ++i)
templateParameters[i] = 0;
while (*s) {
while (*s && *s != '@')
++s;
if (*s) {
*s = '\0';
++s;
templateParameters[templateParametersCount++] = s;
}
}
}
QDumper &QDumper::operator<<(unsigned long long c)
{
checkFill();
pos += sprintf(qDumpBuffer + pos, "%llu", c);
return *this;
}
QDumper &QDumper::operator<<(unsigned long c)
{
checkFill();
pos += sprintf(qDumpBuffer + pos, "%lu", c);
return *this;
}
QDumper &QDumper::operator<<(float d)
{
checkFill();
pos += sprintf(qDumpBuffer + pos, "%f", d);
return *this;
}
QDumper &QDumper::operator<<(double d)
{
checkFill();
pos += sprintf(qDumpBuffer + pos, "%f", d);
return *this;
}
QDumper &QDumper::operator<<(unsigned int i)
{
checkFill();
pos += sprintf(qDumpBuffer + pos, "%u", i);
return *this;
}
QDumper &QDumper::operator<<(long c)
{
checkFill();
pos += sprintf(qDumpBuffer + pos, "%ld", c);
return *this;
}
QDumper &QDumper::operator<<(int i)
{
checkFill();
pos += sprintf(qDumpBuffer + pos, "%d", i);
return *this;
}
QDumper &QDumper::operator<<(const void *p)
{
static char buf[100];
if (p) {
sprintf(buf, "%p", p);
// we get a '0x' prefix only on some implementations.
// if it isn't there, write it out manually.
if (buf[1] != 'x') {
put('0');
put('x');
}
*this << buf;
} else {
*this << "<null>";
}
return *this;
}
void QDumper::checkFill()
{
if (pos >= int(sizeof(qDumpBuffer)) - 100)
flush();
}
void QDumper::put(char c)
{
checkFill();
qDumpBuffer[pos++] = c;
}
void QDumper::addCommaIfNeeded()
{
if (pos == 0)
return;
char c = qDumpBuffer[pos - 1];
if (c == '}' || c == '"' || c == ']')
put(',');
}
void QDumper::putBase64Encoded(const char *buf, int n)
{
const char alphabet[] = "ABCDEFGH" "IJKLMNOP" "QRSTUVWX" "YZabcdef"
"ghijklmn" "opqrstuv" "wxyz0123" "456789+/";
const char padchar = '=';
int padlen = 0;
//int tmpsize = ((n * 4) / 3) + 3;
int i = 0;
while (i < n) {
int chunk = 0;
chunk |= int(uchar(buf[i++])) << 16;
if (i == n) {
padlen = 2;
} else {
chunk |= int(uchar(buf[i++])) << 8;
if (i == n)
padlen = 1;
else
chunk |= int(uchar(buf[i++]));
}
int j = (chunk & 0x00fc0000) >> 18;
int k = (chunk & 0x0003f000) >> 12;
int l = (chunk & 0x00000fc0) >> 6;
int m = (chunk & 0x0000003f);
put(alphabet[j]);
put(alphabet[k]);
put(padlen > 1 ? padchar : alphabet[l]);
put(padlen > 0 ? padchar : alphabet[m]);
}
}
QDumper &QDumper::operator<<(const char *str)
{
if (!str)
return *this << "<null>";
while (*str)
put(*(str++));
return *this;
}
QDumper &QDumper::operator<<(const QByteArray &ba)
{
putBase64Encoded(ba.constData(), ba.size());
return *this;
}
QDumper &QDumper::operator<<(const QString &str)
{
QByteArray ba = str.toUtf8();
putBase64Encoded(ba.constData(), ba.size());
return *this;
}
void QDumper::disarm()
{
flush();
success = true;
}
void QDumper::beginHash()
{
addCommaIfNeeded();
put('{');
}
void QDumper::endHash()
{
put('}');
}
void QDumper::putEllipsis()
{
addCommaIfNeeded();
*this << "{name=\"<incomplete>\",value=\"\",type=\"" << innertype << "\"}";
}
//
// Some helpers to keep the dumper code short
//
// dump property=value pair
#undef P
#define P(dumper,name,value) \
do { \
dumper.addCommaIfNeeded(); \
dumper << (name) << "=\"" << value << "\""; \
} while (0)
// simple string property
#undef S
#define S(dumper, name, value) \
dumper.beginHash(); \
P(dumper, "name", name); \
P(dumper, "value", value); \
P(dumper, "type", NS"QString"); \
P(dumper, "numchild", "0"); \
P(dumper, "valueencoded", "1"); \
dumper.endHash();
// simple integer property
#undef I
#define I(dumper, name, value) \
dumper.beginHash(); \
P(dumper, "name", name); \
P(dumper, "value", value); \
P(dumper, "type", "int"); \
P(dumper, "numchild", "0"); \
dumper.endHash();
// simple boolean property
#undef BL
#define BL(dumper, name, value) \
dumper.beginHash(); \
P(dumper, "name", name); \
P(dumper, "value", (value ? "true" : "false")); \
P(dumper, "type", "bool"); \
P(dumper, "numchild", "0"); \
dumper.endHash();
// a single QChar
#undef QC
#define QC(dumper, name, value) \
dumper.beginHash(); \
P(dumper, "name", name); \
P(dumper, "value", QString(QLatin1String("'%1' (%2, 0x%3)")) \
.arg(value).arg(value.unicode()).arg(value.unicode(), 0, 16)); \
P(dumper, "valueencoded", "1"); \
P(dumper, "type", NS"QChar"); \
P(dumper, "numchild", "0"); \
dumper.endHash();
#undef TT
#define TT(type, value) \
"<tr><td>" << type << "</td><td> : </td><td>" << value << "</td></tr>"
static void qDumpUnknown(QDumper &d)
{
P(d, "iname", d.iname);
P(d, "addr", d.data);
P(d, "value", "<internal error>");
P(d, "type", d.outertype);
P(d, "numchild", "0");
d.disarm();
}
static void qDumpInnerValueHelper(QDumper &d, const char *type, const void *addr,
const char *key = "value")
{
type = stripNamespace(type);
switch (type[1]) {
case 'l':
if (isEqual(type, "float"))
P(d, key, *(float*)addr);
return;
case 'n':
if (isEqual(type, "int"))
P(d, key, *(int*)addr);
else if (isEqual(type, "unsigned"))
P(d, key, *(unsigned int*)addr);
else if (isEqual(type, "unsigned int"))
P(d, key, *(unsigned int*)addr);
else if (isEqual(type, "unsigned long"))
P(d, key, *(unsigned long*)addr);
else if (isEqual(type, "unsigned long long"))
P(d, key, *(qulonglong*)addr);
return;
case 'o':
if (isEqual(type, "bool"))
switch (*(bool*)addr) {
case 0: P(d, key, "false"); break;
case 1: P(d, key, "true"); break;
default: P(d, key, *(bool*)addr); break;
}
else if (isEqual(type, "double"))
P(d, key, *(double*)addr);
else if (isEqual(type, "long"))
P(d, key, *(long*)addr);
else if (isEqual(type, "long long"))
P(d, key, *(qulonglong*)addr);
return;
case 'B':
if (isEqual(type, "QByteArray")) {
d << key << "encoded=\"1\",";
P(d, key, *(QByteArray*)addr);
}
return;
case 'L':
if (startsWith(type, "QList<")) {
const QListData *ldata = reinterpret_cast<const QListData*>(addr);
P(d, "value", "<" << ldata->size() << " items>");
P(d, "valuedisabled", "true");
P(d, "numchild", ldata->size());
}
return;
case 'O':
if (isEqual(type, "QObject *")) {
if (addr) {
const QObject *ob = reinterpret_cast<const QObject *>(addr);
P(d, "addr", ob);
P(d, "value", ob->objectName());
P(d, "valueencoded", "1");
P(d, "type", NS"QObject");
P(d, "displayedtype", ob->metaObject()->className());
} else {
P(d, "value", "0x0");
P(d, "type", NS"QObject *");
}
}
return;
case 'S':
if (isEqual(type, "QString")) {
d << key << "encoded=\"1\",";
P(d, key, *(QString*)addr);
}
return;
default:
return;
}
}
static void qDumpInnerValue(QDumper &d, const char *type, const void *addr)
{
P(d, "addr", addr);
P(d, "type", type);
if (!type[0])
return;
qDumpInnerValueHelper(d, type, addr);
}
static void qDumpInnerValueOrPointer(QDumper &d,
const char *type, const char *strippedtype, const void *addr)
{
if (strippedtype) {
if (deref(addr)) {
P(d, "addr", deref(addr));
P(d, "type", strippedtype);
qDumpInnerValueHelper(d, strippedtype, deref(addr));
} else {
P(d, "addr", addr);
P(d, "type", strippedtype);
P(d, "value", "<null>");
P(d, "numchild", "0");
}
} else {
P(d, "addr", addr);
P(d, "type", type);
qDumpInnerValueHelper(d, type, addr);
}
}
//////////////////////////////////////////////////////////////////////////////
static void qDumpQByteArray(QDumper &d)
{
const QByteArray &ba = *reinterpret_cast<const QByteArray *>(d.data);
if (!ba.isEmpty()) {
qCheckAccess(ba.constData());
qCheckAccess(ba.constData() + ba.size());
}
if (ba.size() <= 100)
P(d, "value", ba);
else
P(d, "value", ba.left(100) << " <size: " << ba.size() << ", cut...>");
P(d, "valueencoded", "1");
P(d, "type", NS"QByteArray");
P(d, "numchild", ba.size());
P(d, "childtype", "char");
P(d, "childnumchild", "0");
if (d.dumpChildren) {
d << ",children=[";
char buf[20];
for (int i = 0; i != ba.size(); ++i) {
unsigned char c = ba.at(i);
unsigned char u = isprint(c) && c != '"' ? c : '?';
sprintf(buf, "%02x (%u '%c')", c, c, u);
d.beginHash();
P(d, "name", "[" << i << "]");
P(d, "value", buf);
d.endHash();
}
d << "]";
}
d.disarm();
}
static void qDumpQDateTime(QDumper &d)
{
#ifdef QT_NO_DATESTRING
qDumpUnknown(d);
#else
const QDateTime &date = *reinterpret_cast<const QDateTime *>(d.data);
if (date.isNull()) {
P(d, "value", "(null)");
} else {
P(d, "value", date.toString());
P(d, "valueencoded", "1");
}
P(d, "type", NS"QDateTime");
P(d, "numchild", "3");
if (d.dumpChildren) {
d << ",children=[";
BL(d, "isNull", date.isNull());
I(d, "toTime_t", (long)date.toTime_t());
S(d, "toString", date.toString());
S(d, "toString_(ISO)", date.toString(Qt::ISODate));
S(d, "toString_(SystemLocale)", date.toString(Qt::SystemLocaleDate));
S(d, "toString_(Locale)", date.toString(Qt::LocaleDate));
S(d, "toString", date.toString());
#if 0
d.beginHash();
P(d, "name", "toUTC");
P(d, "exp", "(("NSX"QDateTime"NSY"*)" << d.data << ")"
"->toTimeSpec('"NS"Qt::UTC')");
P(d, "type", NS"QDateTime");
P(d, "numchild", "1");
d.endHash();
#endif
#if 0
d.beginHash();
P(d, "name", "toLocalTime");
P(d, "exp", "(("NSX"QDateTime"NSY"*)" << d.data << ")"
"->toTimeSpec('"NS"Qt::LocalTime')");
P(d, "type", NS"QDateTime");
P(d, "numchild", "1");
d.endHash();
#endif
d << "]";
}
d.disarm();
#endif // ifdef QT_NO_DATESTRING
}
static void qDumpQDir(QDumper &d)
{
const QDir &dir = *reinterpret_cast<const QDir *>(d.data);
P(d, "value", dir.path());
P(d, "valueencoded", "1");
P(d, "type", NS"QDir");
P(d, "numchild", "3");
if (d.dumpChildren) {
d << ",children=[";
S(d, "absolutePath", dir.absolutePath());
S(d, "canonicalPath", dir.canonicalPath());
d << "]";
}
d.disarm();
}
static void qDumpQFile(QDumper &d)
{
const QFile &file = *reinterpret_cast<const QFile *>(d.data);
P(d, "value", file.fileName());
P(d, "valueencoded", "1");
P(d, "type", NS"QFile");
P(d, "numchild", "2");
if (d.dumpChildren) {
d << ",children=[";
S(d, "fileName", file.fileName());
BL(d, "exists", file.exists());
d << "]";
}
d.disarm();
}
static void qDumpQFileInfo(QDumper &d)
{
const QFileInfo &info = *reinterpret_cast<const QFileInfo *>(d.data);
P(d, "value", info.filePath());
P(d, "valueencoded", "1");
P(d, "type", NS"QFileInfo");
P(d, "numchild", "3");
if (d.dumpChildren) {
d << ",children=[";
S(d, "absolutePath", info.absolutePath());
S(d, "absoluteFilePath", info.absoluteFilePath());
S(d, "canonicalPath", info.canonicalPath());
S(d, "canonicalFilePath", info.canonicalFilePath());
S(d, "completeBaseName", info.completeBaseName());
S(d, "completeSuffix", info.completeSuffix());
S(d, "baseName", info.baseName());
#ifdef Q_OS_MACX
BL(d, "isBundle", info.isBundle());
S(d, "bundleName", info.bundleName());
#endif
S(d, "completeSuffix", info.completeSuffix());
S(d, "fileName", info.fileName());
S(d, "filePath", info.filePath());
S(d, "group", info.group());
S(d, "owner", info.owner());
S(d, "path", info.path());
I(d, "groupid", (long)info.groupId());
I(d, "ownerid", (long)info.ownerId());
//QFile::Permissions permissions () const
I(d, "permissions", info.permissions());
//QDir absoluteDir () const
//QDir dir () const
BL(d, "caching", info.caching());
BL(d, "exists", info.exists());
BL(d, "isAbsolute", info.isAbsolute());
BL(d, "isDir", info.isDir());
BL(d, "isExecutable", info.isExecutable());
BL(d, "isFile", info.isFile());
BL(d, "isHidden", info.isHidden());
BL(d, "isReadable", info.isReadable());
BL(d, "isRelative", info.isRelative());
BL(d, "isRoot", info.isRoot());
BL(d, "isSymLink", info.isSymLink());
BL(d, "isWritable", info.isWritable());
d.beginHash();
P(d, "name", "created");
P(d, "value", info.created().toString());
P(d, "valueencoded", "1");
P(d, "exp", "(("NSX"QFileInfo"NSY"*)" << d.data << ")->created()");
P(d, "type", NS"QDateTime");
P(d, "numchild", "1");
d.endHash();
d.beginHash();
P(d, "name", "lastModified");
P(d, "value", info.lastModified().toString());
P(d, "valueencoded", "1");
P(d, "exp", "(("NSX"QFileInfo"NSY"*)" << d.data << ")->lastModified()");
P(d, "type", NS"QDateTime");
P(d, "numchild", "1");
d.endHash();
d.beginHash();
P(d, "name", "lastRead");
P(d, "value", info.lastRead().toString());
P(d, "valueencoded", "1");
P(d, "exp", "(("NSX"QFileInfo"NSY"*)" << d.data << ")->lastRead()");
P(d, "type", NS"QDateTime");
P(d, "numchild", "1");
d.endHash();
d << "]";
}
d.disarm();
}
bool isOptimizedIntKey(const char *keyType)
{
return isEqual(keyType, "int")
#if defined(Q_BYTE_ORDER) && Q_BYTE_ORDER == Q_LITTLE_ENDIAN
|| isEqual(keyType, "short")
|| isEqual(keyType, "ushort")
#endif
|| isEqual(keyType, "uint");
}
int hashOffset(bool optimizedIntKey, bool forKey, unsigned keySize, unsigned valueSize)
{
// int-key optimization, small value
struct NodeOS { void *next; uint k; uint v; } nodeOS;
// int-key optimiatzion, large value
struct NodeOL { void *next; uint k; void *v; } nodeOL;
// no optimization, small value
struct NodeNS { void *next; uint h; uint k; uint v; } nodeNS;
// no optimization, large value
struct NodeNL { void *next; uint h; uint k; void *v; } nodeNL;
// complex key
struct NodeL { void *next; uint h; void *k; void *v; } nodeL;
if (forKey) {
// offsetof(...,...) not yet in Standard C++
const ulong nodeOSk ( (char *)&nodeOS.k - (char *)&nodeOS );
const ulong nodeOLk ( (char *)&nodeOL.k - (char *)&nodeOL );
const ulong nodeNSk ( (char *)&nodeNS.k - (char *)&nodeNS );
const ulong nodeNLk ( (char *)&nodeNL.k - (char *)&nodeNL );
const ulong nodeLk ( (char *)&nodeL.k - (char *)&nodeL );
if (optimizedIntKey)
return valueSize > sizeof(int) ? nodeOLk : nodeOSk;
if (keySize > sizeof(int))
return nodeLk;
return valueSize > sizeof(int) ? nodeNLk : nodeNSk;
} else {
const ulong nodeOSv ( (char *)&nodeOS.v - (char *)&nodeOS );
const ulong nodeOLv ( (char *)&nodeOL.v - (char *)&nodeOL );
const ulong nodeNSv ( (char *)&nodeNS.v - (char *)&nodeNS );
const ulong nodeNLv ( (char *)&nodeNL.v - (char *)&nodeNL );
const ulong nodeLv ( (char *)&nodeL.v - (char *)&nodeL );
if (optimizedIntKey)
return valueSize > sizeof(int) ? nodeOLv : nodeOSv;
if (keySize > sizeof(int))
return nodeLv;
return valueSize > sizeof(int) ? nodeNLv : nodeNSv;
}
}
static void qDumpQHash(QDumper &d)
{
QHashData *h = *reinterpret_cast<QHashData *const*>(d.data);
const char *keyType = d.templateParameters[0];
const char *valueType = d.templateParameters[1];
qCheckPointer(h->fakeNext);
qCheckPointer(h->buckets);
unsigned keySize = d.extraInt[0];
unsigned valueSize = d.extraInt[1];
int n = h->size;
if (n < 0)
qCheck(false);
if (n > 0) {
qCheckPointer(h->fakeNext);
qCheckPointer(*h->buckets);
}
P(d, "value", "<" << n << " items>");
P(d, "numchild", n);
if (d.dumpChildren) {
if (n > 1000)
n = 1000;
bool simpleKey = isShortKey(keyType);
bool simpleValue = isShortKey(valueType);
bool opt = isOptimizedIntKey(keyType);
int keyOffset = hashOffset(opt, true, keySize, valueSize);
int valueOffset = hashOffset(opt, false, keySize, valueSize);
P(d, "extra", "simplekey: " << simpleKey << " simpleValue: " << simpleValue
<< " keySize: " << keyOffset << " valueOffset: " << valueOffset
<< " opt: " << opt);
QHashData::Node *node = h->firstNode();
QHashData::Node *end = reinterpret_cast<QHashData::Node *>(h);
int i = 0;
d << ",children=[";
while (node != end) {
d.beginHash();
if (simpleKey) {
qDumpInnerValueHelper(d, keyType, addOffset(node, keyOffset), "name");
P(d, "nameisindex", "1");
if (simpleValue)
qDumpInnerValueHelper(d, valueType, addOffset(node, valueOffset));
P(d, "type", valueType);
P(d, "addr", addOffset(node, valueOffset));
} else {
P(d, "name", "[" << i << "]");
//P(d, "exp", "*(char*)" << node);
P(d, "exp", "*('"NS"QHashNode<" << keyType << "," << valueType << " >'*)" << node);
P(d, "type", "'"NS"QHashNode<" << keyType << "," << valueType << " >'");
}
d.endHash();
++i;
node = QHashData::nextNode(node);
}
d << "]";
}
d.disarm();
}
static void qDumpQHashNode(QDumper &d)
{
const QHashData *h = reinterpret_cast<const QHashData *>(d.data);
const char *keyType = d.templateParameters[0];
const char *valueType = d.templateParameters[1];
P(d, "value", "");
P(d, "numchild", 2);
if (d.dumpChildren) {
unsigned keySize = d.extraInt[0];
unsigned valueSize = d.extraInt[1];
bool opt = isOptimizedIntKey(keyType);
int keyOffset = hashOffset(opt, true, keySize, valueSize);
int valueOffset = hashOffset(opt, false, keySize, valueSize);
// there is a hash specialization in cast the key are integers or shorts
d << ",children=[";
d.beginHash();
P(d, "name", "key");
P(d, "type", keyType);
P(d, "addr", addOffset(h, keyOffset));
d.endHash();
d.beginHash();
P(d, "name", "value");
P(d, "type", valueType);
P(d, "addr", addOffset(h, valueOffset));
d.endHash();
d << "]";
}
d.disarm();
}
static void qDumpQImage(QDumper &d)
{
#ifdef QT_GUI_LIB
const QImage &im = *reinterpret_cast<const QImage *>(d.data);
P(d, "value", "(" << im.width() << "x" << im.height() << ")");
P(d, "type", NS"QImage");
P(d, "numchild", "0");
d.disarm();
#else
Q_UNUSED(d);
#endif
}
static void qDumpQList(QDumper &d)
{
// This uses the knowledge that QList<T> has only a single member
// of type union { QListData p; QListData::Data *d; };
const QListData &ldata = *reinterpret_cast<const QListData*>(d.data);
const QListData::Data *pdata =
*reinterpret_cast<const QListData::Data* const*>(d.data);
int nn = ldata.size();
if (nn < 0)
qCheck(false);
if (nn > 0) {
qCheckAccess(ldata.d->array);
//qCheckAccess(ldata.d->array[0]);
//qCheckAccess(ldata.d->array[nn - 1]);
#if QT_VERSION >= 0x040400
if (ldata.d->ref._q_value <= 0)
qCheck(false);
#endif
}
int n = nn;
P(d, "value", "<" << n << " items>");
P(d, "valuedisabled", "true");
P(d, "numchild", n);
P(d, "childtype", d.innertype);
if (d.dumpChildren) {
unsigned innerSize = d.extraInt[0];
bool innerTypeIsPointer = isPointerType(d.innertype);
QByteArray strippedInnerType = stripPointerType(d.innertype);
// The exact condition here is:
// QTypeInfo<T>::isLarge || QTypeInfo<T>::isStatic
// but this data is available neither in the compiled binary nor
// in the frontend.
// So as first approximation only do the 'isLarge' check:
bool isInternal = innerSize <= int(sizeof(void*))
&& isMovableType(d.innertype);
P(d, "internal", (int)isInternal);
P(d, "childtype", d.innertype);
if (n > 1000)
n = 1000;
d << ",children=[";
for (int i = 0; i != n; ++i) {
d.beginHash();
P(d, "name", "[" << i << "]");
if (innerTypeIsPointer) {
void *p = ldata.d->array + i + pdata->begin;
if (p) {
//P(d, "value","@" << p);
qDumpInnerValue(d, strippedInnerType.data(), deref(p));
} else {
P(d, "value", "<null>");
P(d, "numchild", "0");
}
} else {
void *p = ldata.d->array + i + pdata->begin;
if (isInternal) {
//qDumpInnerValue(d, d.innertype, p);
P(d, "addr", p);
qDumpInnerValueHelper(d, d.innertype, p);
} else {
//qDumpInnerValue(d, d.innertype, deref(p));
P(d, "addr", deref(p));
qDumpInnerValueHelper(d, d.innertype, deref(p));
}
}
d.endHash();
}
if (n < nn)
d.putEllipsis();
d << "]";
}
d.disarm();
}
static void qDumpQLocale(QDumper &d)
{
const QLocale &locale = *reinterpret_cast<const QLocale *>(d.data);
P(d, "value", locale.name());
P(d, "valueencoded", "1");
P(d, "type", NS"QLocale");
P(d, "numchild", "8");
if (d.dumpChildren) {
d << ",children=[";
d.beginHash();
P(d, "name", "country");
P(d, "exp", "(("NSX"QLocale"NSY"*)" << d.data << ")->country()");
d.endHash();
d.beginHash();
P(d, "name", "language");
P(d, "exp", "(("NSX"QLocale"NSY"*)" << d.data << ")->language()");
d.endHash();
d.beginHash();
P(d, "name", "measurementSystem");
P(d, "exp", "(("NSX"QLocale"NSY"*)" << d.data << ")->measurementSystem()");
d.endHash();
d.beginHash();
P(d, "name", "numberOptions");
P(d, "exp", "(("NSX"QLocale"NSY"*)" << d.data << ")->numberOptions()");
d.endHash();
S(d, "timeFormat_(short)", locale.timeFormat(QLocale::ShortFormat));
S(d, "timeFormat_(long)", locale.timeFormat(QLocale::LongFormat));
QC(d, "decimalPoint", locale.decimalPoint());
QC(d, "exponential", locale.exponential());
QC(d, "percent", locale.percent());
QC(d, "zeroDigit", locale.zeroDigit());
QC(d, "groupSeparator", locale.groupSeparator());
QC(d, "negativeSign", locale.negativeSign());
d << "]";
}
d.disarm();
}
static void qDumpQMap(QDumper &d)
{
QMapData *h = *reinterpret_cast<QMapData *const*>(d.data);
const char *keyType = d.templateParameters[0];
const char *valueType = d.templateParameters[1];
int n = h->size;
if (n < 0)
qCheck(false);
if (n > 0) {
qCheckAccess(h->backward);
qCheckAccess(h->forward[0]);
qCheckPointer(h->backward->backward);
qCheckPointer(h->forward[0]->backward);
}
P(d, "value", "<" << n << " items>");
P(d, "numchild", n);
if (d.dumpChildren) {
if (n > 1000)
n = 1000;
//unsigned keySize = d.extraInt[0];
//unsigned valueSize = d.extraInt[1];
unsigned mapnodesize = d.extraInt[2];
unsigned valueOff = d.extraInt[3];
bool simpleKey = isShortKey(keyType);
bool simpleValue = isShortKey(valueType);
// both negative:
int keyOffset = 2 * sizeof(void*) - int(mapnodesize);
int valueOffset = 2 * sizeof(void*) - int(mapnodesize) + valueOff;
P(d, "extra", "simplekey: " << simpleKey << " simpleValue: " << simpleValue
<< " keyOffset: " << keyOffset << " valueOffset: " << valueOffset
<< " mapnodesize: " << mapnodesize);
d << ",children=[";
QMapData::Node *node = reinterpret_cast<QMapData::Node *>(h->forward[0]);
QMapData::Node *end = reinterpret_cast<QMapData::Node *>(h);
int i = 0;
while (node != end) {
d.beginHash();
if (simpleKey) {
P(d, "type", valueType);
qDumpInnerValueHelper(d, keyType, addOffset(node, keyOffset), "name");
P(d, "nameisindex", "1");
if (simpleValue)
qDumpInnerValueHelper(d, valueType, addOffset(node, valueOffset));
P(d, "type", valueType);
P(d, "addr", addOffset(node, valueOffset));
} else {
P(d, "name", "[" << i << "]");
P(d, "type", NS"QMapNode<" << keyType << "," << valueType << " >");
// actually, any type (even 'char') will do...
P(d, "exp", "*('"NS"QMapNode<" << keyType << "," << valueType << " >'*)" << node);
//P(d, "exp", "*('"NS"QMapData'*)" << (void*)node);
//P(d, "exp", "*(char*)" << (void*)node);
// P(d, "addr", node); does not work as gdb fails to parse
// e.g. &((*('"NS"QMapNode<QString,Foo>'*)0x616658))
}
d.endHash();
++i;
node = node->forward[0];
}
d << "]";
}
d.disarm();
}
static void qDumpQModelIndex(QDumper &d)
{
const QModelIndex *mi = reinterpret_cast<const QModelIndex *>(d.data);
P(d, "type", NS"QModelIndex");
if (mi->isValid()) {
P(d, "value", "(" << mi->row() << ", " << mi->column() << ")");
P(d, "numchild", 5);
if (d.dumpChildren) {
d << ",children=[";
I(d, "row", mi->row());
I(d, "column", mi->column());
d.beginHash();
P(d, "name", "parent");
const QModelIndex parent = mi->parent();
if (parent.isValid())
P(d, "value", "(" << mi->row() << ", " << mi->column() << ")");
else
P(d, "value", "<invalid>");
P(d, "exp", "(("NSX"QModelIndex"NSY"*)" << d.data << ")->parent()");
P(d, "type", NS"QModelIndex");
P(d, "numchild", "1");
d.endHash();
S(d, "internalId", QString::number(mi->internalId(), 10));
d.beginHash();
P(d, "name", "model");
P(d, "value", static_cast<const void *>(mi->model()));
P(d, "type", NS"QAbstractItemModel*");
P(d, "numchild", "1");
d.endHash();
d << "]";
}
} else {
P(d, "value", "<invalid>");
P(d, "numchild", 0);
}
d.disarm();
}
static void qDumpQMapNode(QDumper &d)
{
const QMapData *h = reinterpret_cast<const QMapData *>(d.data);
const char *keyType = d.templateParameters[0];
const char *valueType = d.templateParameters[1];
qCheckAccess(h->backward);
qCheckAccess(h->forward[0]);
P(d, "value", "");
P(d, "numchild", 2);
if (d.dumpChildren) {
//unsigned keySize = d.extraInt[0];
//unsigned valueSize = d.extraInt[1];
unsigned mapnodesize = d.extraInt[2];
unsigned valueOff = d.extraInt[3];
unsigned keyOffset = 2 * sizeof(void*) - mapnodesize;
unsigned valueOffset = 2 * sizeof(void*) - mapnodesize + valueOff;
d << ",children=[";
d.beginHash();
P(d, "name", "key");
qDumpInnerValue(d, keyType, addOffset(h, keyOffset));
d.endHash();
d.beginHash();
P(d, "name", "value");
qDumpInnerValue(d, valueType, addOffset(h, valueOffset));
d.endHash();
d << "]";
}
d.disarm();
}
static void qDumpQObject(QDumper &d)
{
const QObject *ob = reinterpret_cast<const QObject *>(d.data);
const QMetaObject *mo = ob->metaObject();
unsigned childrenOffset = d.extraInt[0];
P(d, "value", ob->objectName());
P(d, "valueencoded", "1");
P(d, "type", NS"QObject");
P(d, "displayedtype", mo->className());
P(d, "numchild", 4);
if (d.dumpChildren) {
const QObjectList &children = ob->children();
int slotCount = 0;
int signalCount = 0;
for (int i = mo->methodCount(); --i >= 0; ) {
QMetaMethod::MethodType mt = mo->method(i).methodType();
signalCount += (mt == QMetaMethod::Signal);
slotCount += (mt == QMetaMethod::Slot);
}
d << ",children=[";
d.beginHash();
P(d, "name", "properties");
// FIXME: Note that when simply using '(QObject*)'
// in the cast below, Gdb/MI _sometimes_ misparses
// expressions further down in the tree.
P(d, "exp", "*(class '"NS"QObject'*)" << d.data);
P(d, "type", NS"QObjectPropertyList");
P(d, "value", "<" << mo->propertyCount() << " items>");
P(d, "numchild", mo->propertyCount());
d.endHash();
#if 0
d.beginHash();
P(d, "name", "methods");
P(d, "exp", "*(class '"NS"QObject'*)" << d.data);
P(d, "value", "<" << mo->methodCount() << " items>");
P(d, "numchild", mo->methodCount());
d.endHash();
#endif
#if 0
d.beginHash();
P(d, "name", "senders");
P(d, "exp", "(*(class '"NS"QObjectPrivate'*)" << dfunc(ob) << ")->senders");
P(d, "type", NS"QList<"NS"QObjectPrivateSender>");
d.endHash();
#endif
#if PRIVATE_OBJECT_ALLOWED
d.beginHash();
P(d, "name", "signals");
P(d, "exp", "*(class '"NS"QObject'*)" << d.data);
P(d, "type", NS"QObjectSignalList");
P(d, "value", "<" << signalCount << " items>");
P(d, "numchild", signalCount);
d.endHash();
d.beginHash();
P(d, "name", "slots");
P(d, "exp", "*(class '"NS"QObject'*)" << d.data);
P(d, "type", NS"QObjectSlotList");
P(d, "value", "<" << slotCount << " items>");
P(d, "numchild", slotCount);
d.endHash();
#endif
d.beginHash();
P(d, "name", "children");
// works always, but causes additional traffic on the list
//P(d, "exp", "((class '"NS"QObject'*)" << d.data << ")->children()");
//
//P(d, "addr", addOffset(dfunc(ob), childrenOffset));
//P(d, "type", NS"QList<QObject *>");
//P(d, "value", "<" << children.size() << " items>");
qDumpInnerValue(d, NS"QList<"NS"QObject *>",
addOffset(dfunc(ob), childrenOffset));
P(d, "numchild", children.size());
d.endHash();
#if 0
// Unneeded (and not working): Connections are listes as childen
// of the signal or slot they are connected to.
// d.beginHash();
// P(d, "name", "connections");
// P(d, "exp", "*(*(class "NS"QObjectPrivate*)" << dfunc(ob) << ")->connectionLists");
// P(d, "type", NS"QVector<"NS"QList<"NS"QObjectPrivate::Connection> >");
// d.endHash();
#endif
#if 0
d.beginHash();
P(d, "name", "objectprivate");
P(d, "type", NS"QObjectPrivate");
P(d, "addr", dfunc(ob));
P(d, "value", "");
P(d, "numchild", "1");
d.endHash();
#endif
d.beginHash();
P(d, "name", "parent");
qDumpInnerValueHelper(d, NS"QObject *", ob->parent());
d.endHash();
#if 1
d.beginHash();
P(d, "name", "className");
P(d, "value",ob->metaObject()->className());
P(d, "type", "");
P(d, "numchild", "0");
d.endHash();
#endif
d << "]";
}
d.disarm();
}
static void qDumpQObjectPropertyList(QDumper &d)
{
const QObject *ob = (const QObject *)d.data;
const QMetaObject *mo = ob->metaObject();
P(d, "addr", "<synthetic>");
P(d, "type", NS"QObjectPropertyList");
P(d, "numchild", mo->propertyCount());
if (d.dumpChildren) {
d << ",children=[";
for (int i = mo->propertyCount(); --i >= 0; ) {
const QMetaProperty & prop = mo->property(i);
d.beginHash();
P(d, "name", prop.name());
P(d, "exp", "((" << mo->className() << "*)" << ob
<< ")->" << prop.name() << "()");
if (isEqual(prop.typeName(), "QString")) {
P(d, "value", prop.read(ob).toString());
P(d, "valueencoded", "1");
P(d, "type", NS"QString");
P(d, "numchild", "0");
} else if (isEqual(prop.typeName(), "bool")) {
P(d, "value", (prop.read(ob).toBool() ? "true" : "false"));
P(d, "numchild", "0");
} else if (isEqual(prop.typeName(), "int")) {
P(d, "value", prop.read(ob).toInt());
P(d, "numchild", "0");
}
P(d, "type", prop.typeName());
P(d, "numchild", "1");
d.endHash();
}
d << "]";
}
d.disarm();
}
static void qDumpQObjectMethodList(QDumper &d)
{
const QObject *ob = (const QObject *)d.data;
const QMetaObject *mo = ob->metaObject();
P(d, "addr", "<synthetic>");
P(d, "type", NS"QObjectMethodList");
P(d, "numchild", mo->methodCount());
P(d, "childtype", "QMetaMethod::Method");
P(d, "childnumchild", "0");
if (d.dumpChildren) {
d << ",children=[";
for (int i = 0; i != mo->methodCount(); ++i) {
const QMetaMethod & method = mo->method(i);
int mt = method.methodType();
d.beginHash();
P(d, "name", "[" << i << "] " << mo->indexOfMethod(method.signature())
<< " " << method.signature());
P(d, "value", (mt == QMetaMethod::Signal ? "<Signal>" : "<Slot>") << " (" << mt << ")");
d.endHash();
}
d << "]";
}
d.disarm();
}
#if PRIVATE_OBJECT_ALLOWED
const char * qConnectionTypes[] ={
"auto",
"direct",
"queued",
"autocompat",
"blockingqueued"
};
#if QT_VERSION >= 0x040400
static const QObjectPrivate::ConnectionList &qConnectionList(const QObject *ob, int signalNumber)
{
static const QObjectPrivate::ConnectionList emptyList;
const QObjectPrivate *p = reinterpret_cast<const QObjectPrivate *>(dfunc(ob));
if (!p->connectionLists)
return emptyList;
typedef QVector<QObjectPrivate::ConnectionList> ConnLists;
const ConnLists *lists = reinterpret_cast<const ConnLists *>(p->connectionLists);
// there's an optimization making the lists only large enough to hold the
// last non-empty item
if (signalNumber >= lists->size())
return emptyList;
return lists->at(signalNumber);
}
#endif
static void qDumpQObjectSignal(QDumper &d)
{
unsigned signalNumber = d.extraInt[0];
P(d, "addr", "<synthetic>");
P(d, "numchild", "1");
P(d, "type", NS"QObjectSignal");
#if QT_VERSION >= 0x040400
if (d.dumpChildren) {
const QObject *ob = reinterpret_cast<const QObject *>(d.data);
d << ",children=[";
const QObjectPrivate::ConnectionList &connList = qConnectionList(ob, signalNumber);
for (int i = 0; i != connList.size(); ++i) {
const QObjectPrivate::Connection &conn = connList.at(i);
d.beginHash();
P(d, "name", "[" << i << "] receiver");
qDumpInnerValueHelper(d, NS"QObject *", conn.receiver);
d.endHash();
d.beginHash();
P(d, "name", "[" << i << "] slot");
P(d, "type", "");
if (conn.receiver)
P(d, "value", conn.receiver->metaObject()->method(conn.method).signature());
else
P(d, "value", "<invalid receiver>");
P(d, "numchild", "0");
d.endHash();
d.beginHash();
P(d, "name", "[" << i << "] type");
P(d, "type", "");
P(d, "value", "<" << qConnectionTypes[conn.method] << " connection>");
P(d, "numchild", "0");
d.endHash();
}
d << "]";
P(d, "numchild", connList.size());
}
#endif
d.disarm();
}
static void qDumpQObjectSignalList(QDumper &d)
{
const QObject *ob = reinterpret_cast<const QObject *>(d.data);
const QMetaObject *mo = ob->metaObject();
int count = 0;
for (int i = mo->methodCount(); --i >= 0; )
count += (mo->method(i).methodType() == QMetaMethod::Signal);
P(d, "addr", d.data);
P(d, "numchild", count);
#if QT_VERSION >= 0x040400
if (d.dumpChildren) {
d << ",children=[";
for (int i = 0; i != mo->methodCount(); ++i) {
const QMetaMethod & method = mo->method(i);
if (method.methodType() == QMetaMethod::Signal) {
int k = mo->indexOfSignal(method.signature());
const QObjectPrivate::ConnectionList &connList = qConnectionList(ob, k);
d.beginHash();
P(d, "name", "[" << k << "]");
P(d, "value", method.signature());
P(d, "numchild", connList.size());
//P(d, "numchild", "1");
P(d, "exp", "*(class '"NS"QObject'*)" << d.data);
P(d, "type", NS"QObjectSignal");
d.endHash();
}
}
d << "]";
}
#endif
d.disarm();
}
static void qDumpQObjectSlot(QDumper &d)
{
int slotNumber = d.extraInt[0];
P(d, "addr", d.data);
P(d, "numchild", "1");
P(d, "type", NS"QObjectSlot");
#if QT_VERSION >= 0x040400
if (d.dumpChildren) {
d << ",children=[";
int numchild = 0;
const QObject *ob = reinterpret_cast<const QObject *>(d.data);
const QObjectPrivate *p = reinterpret_cast<const QObjectPrivate *>(dfunc(ob));
for (int s = 0; s != p->senders.size(); ++s) {
const QObjectPrivate::Sender &sender = p->senders.at(s);
const QObjectPrivate::ConnectionList &connList
= qConnectionList(sender.sender, sender.signal);
for (int i = 0; i != connList.size(); ++i) {
const QObjectPrivate::Connection &conn = connList.at(i);
if (conn.receiver == ob && conn.method == slotNumber) {
++numchild;
const QMetaMethod & method =
sender.sender->metaObject()->method(sender.signal);
d.beginHash();
P(d, "name", "[" << s << "] sender");
qDumpInnerValueHelper(d, NS"QObject *", sender.sender);
d.endHash();
d.beginHash();
P(d, "name", "[" << s << "] signal");
P(d, "type", "");
P(d, "value", method.signature());
P(d, "numchild", "0");
d.endHash();
d.beginHash();
P(d, "name", "[" << s << "] type");
P(d, "type", "");
P(d, "value", "<" << qConnectionTypes[conn.method] << " connection>");
P(d, "numchild", "0");
d.endHash();
}
}
}
d << "]";
P(d, "numchild", numchild);
}
#endif
d.disarm();
}
static void qDumpQObjectSlotList(QDumper &d)
{
const QObject *ob = reinterpret_cast<const QObject *>(d.data);
#if QT_VERSION >= 0x040400
const QObjectPrivate *p = reinterpret_cast<const QObjectPrivate *>(dfunc(ob));
#endif
const QMetaObject *mo = ob->metaObject();
int count = 0;
for (int i = mo->methodCount(); --i >= 0; )
count += (mo->method(i).methodType() == QMetaMethod::Slot);
P(d, "addr", d.data);
P(d, "numchild", count);
#if QT_VERSION >= 0x040400
if (d.dumpChildren) {
d << ",children=[";
for (int i = 0; i != mo->methodCount(); ++i) {
const QMetaMethod & method = mo->method(i);
if (method.methodType() == QMetaMethod::Slot) {
d.beginHash();
int k = mo->indexOfSlot(method.signature());
P(d, "name", "[" << k << "]");
P(d, "value", method.signature());
// count senders. expensive...
int numchild = 0;
for (int s = 0; s != p->senders.size(); ++s) {
const QObjectPrivate::Sender & sender = p->senders.at(s);
const QObjectPrivate::ConnectionList &connList
= qConnectionList(sender.sender, sender.signal);
for (int c = 0; c != connList.size(); ++c) {
const QObjectPrivate::Connection &conn = connList.at(c);
if (conn.receiver == ob && conn.method == k)
++numchild;
}
}
P(d, "numchild", numchild);
P(d, "exp", "*(class '"NS"QObject'*)" << d.data);
P(d, "type", NS"QObjectSlot");
d.endHash();
}
}
d << "]";
}
#endif
d.disarm();
}
#endif // PRIVATE_OBJECT_ALLOWED
static void qDumpQPixmap(QDumper &d)
{
#ifdef QT_GUI_LIB
const QPixmap &im = *reinterpret_cast<const QPixmap *>(d.data);
P(d, "value", "(" << im.width() << "x" << im.height() << ")");
P(d, "type", NS"QPixmap");
P(d, "numchild", "0");
d.disarm();
#else
Q_UNUSED(d);
#endif
}
static void qDumpQSet(QDumper &d)
{
// This uses the knowledge that QHash<T> has only a single member
// of union { QHashData *d; QHashNode<Key, T> *e; };
QHashData *hd = *(QHashData**)d.data;
QHashData::Node *node = hd->firstNode();
int n = hd->size;
if (n < 0)
qCheck(false);
if (n > 0) {
qCheckAccess(node);
qCheckPointer(node->next);
}
P(d, "value", "<" << n << " items>");
P(d, "valuedisabled", "true");
P(d, "numchild", 2 * n);
if (d.dumpChildren) {
if (n > 100)
n = 100;
d << ",children=[";
int i = 0;
for (int bucket = 0; bucket != hd->numBuckets && i <= 10000; ++bucket) {
for (node = hd->buckets[bucket]; node->next; node = node->next) {
d.beginHash();
P(d, "name", "[" << i << "]");
P(d, "type", d.innertype);
P(d, "exp", "(('"NS"QHashNode<" << d.innertype
<< ","NS"QHashDummyValue>'*)"
<< static_cast<const void*>(node) << ")->key"
);
d.endHash();
++i;
if (i > 10000) {
d.putEllipsis();
break;
}
}
}
d << "]";
}
d.disarm();
}
static void qDumpQString(QDumper &d)
{
const QString &str = *reinterpret_cast<const QString *>(d.data);
if (!str.isEmpty()) {
qCheckAccess(str.unicode());
qCheckAccess(str.unicode() + str.size());
}
P(d, "value", str);
P(d, "valueencoded", "1");
P(d, "type", NS"QString");
//P(d, "editvalue", str); // handled generically below
P(d, "numchild", "0");
d.disarm();
}
static void qDumpQStringList(QDumper &d)
{
const QStringList &list = *reinterpret_cast<const QStringList *>(d.data);
int n = list.size();
if (n < 0)
qCheck(false);
if (n > 0) {
qCheckAccess(&list.front());
qCheckAccess(&list.back());
}
P(d, "value", "<" << n << " items>");
P(d, "valuedisabled", "true");
P(d, "numchild", n);
P(d, "childtype", NS"QString");
P(d, "childnumchild", "0");
if (d.dumpChildren) {
if (n > 1000)
n = 1000;
d << ",children=[";
for (int i = 0; i != n; ++i) {
d.beginHash();
P(d, "name", "[" << i << "]");
P(d, "value", list[i]);
P(d, "valueencoded", "1");
d.endHash();
}
if (n < list.size())
d.putEllipsis();
d << "]";
}
d.disarm();
}
static void qDumpQTextCodec(QDumper &d)
{
const QTextCodec &codec = *reinterpret_cast<const QTextCodec *>(d.data);
P(d, "value", codec.name());
P(d, "valueencoded", "1");
P(d, "type", NS"QTextCodec");
P(d, "numchild", "2");
if (d.dumpChildren) {
d << ",children=[";
S(d, "name", codec.name());
I(d, "mibEnum", codec.mibEnum());
d << "]";
}
d.disarm();
}
static void qDumpQVariantHelper(const void *data, QString *value,
QString *exp, int *numchild)
{
const QVariant &v = *reinterpret_cast<const QVariant *>(data);
switch (v.type()) {
case QVariant::Invalid:
*value = QLatin1String("<invalid>");
*numchild = 0;
break;
case QVariant::String:
*value = QLatin1Char('"') + v.toString() + QLatin1Char('"');
*numchild = 0;
break;
case QVariant::StringList:
*exp = QString(QLatin1String("((QVariant*)%1)->d.data.c"))
.arg((quintptr)data);
*numchild = v.toStringList().size();
break;
case QVariant::Int:
*value = QString::number(v.toInt());
*numchild= 0;
break;
case QVariant::Double:
*value = QString::number(v.toDouble());
*numchild = 0;
break;
default: {
char buf[1000];
const char *format = (v.typeName()[0] == 'Q')
? "'"NS"%s "NS"qVariantValue<"NS"%s >'(*('"NS"QVariant'*)%p)"
: "'%s "NS"qVariantValue<%s >'(*('"NS"QVariant'*)%p)";
qsnprintf(buf, sizeof(buf) - 1, format, v.typeName(), v.typeName(), data);
*exp = QLatin1String(buf);
*numchild = 1;
break;
}
}
}
static void qDumpQVariant(QDumper &d)
{
const QVariant &v = *reinterpret_cast<const QVariant *>(d.data);
QString value;
QString exp;
int numchild = 0;
qDumpQVariantHelper(d.data, &value, &exp, &numchild);
bool isInvalid = (v.typeName() == 0);
if (isInvalid) {
P(d, "value", "(invalid)");
} else if (value.isEmpty()) {
P(d, "value", "(" << v.typeName() << ") " << qPrintable(value));
} else {
QByteArray ba;
ba += '(';
ba += v.typeName();
ba += ") ";
ba += qPrintable(value);
P(d, "value", ba);
P(d, "valueencoded", "1");
}
P(d, "type", NS"QVariant");
P(d, "numchild", (isInvalid ? "0" : "1"));
if (d.dumpChildren) {
d << ",children=[";
d.beginHash();
P(d, "name", "value");
if (!exp.isEmpty())
P(d, "exp", qPrintable(exp));
if (!value.isEmpty()) {
P(d, "value", value);
P(d, "valueencoded", "1");
}
P(d, "type", v.typeName());
P(d, "numchild", numchild);
d.endHash();
d << "]";
}
d.disarm();
}
static void qDumpQVector(QDumper &d)
{
QVectorData *v = *reinterpret_cast<QVectorData *const*>(d.data);
// Try to provoke segfaults early to prevent the frontend
// from asking for unavailable child details
int nn = v->size;
if (nn < 0)
qCheck(false);
if (nn > 0) {
//qCheckAccess(&vec.front());
//qCheckAccess(&vec.back());
}
unsigned innersize = d.extraInt[0];
unsigned typeddatasize = d.extraInt[1];
int n = nn;
P(d, "value", "<" << n << " items>");
P(d, "valuedisabled", "true");
P(d, "numchild", n);
if (d.dumpChildren) {
QByteArray strippedInnerType = stripPointerType(d.innertype);
const char *stripped =
isPointerType(d.innertype) ? strippedInnerType.data() : 0;
if (n > 1000)
n = 1000;
d << ",children=[";
for (int i = 0; i != n; ++i) {
d.beginHash();
P(d, "name", "[" << i << "]");
qDumpInnerValueOrPointer(d, d.innertype, stripped,
addOffset(v, i * innersize + typeddatasize));
d.endHash();
}
if (n < nn)
d.putEllipsis();
d << "]";
}
d.disarm();
}
static void qDumpStdList(QDumper &d)
{
const std::list<int> &list = *reinterpret_cast<const std::list<int> *>(d.data);
const void *p = d.data;
qCheckAccess(p);
p = deref(p);
qCheckAccess(p);
p = deref(p);
qCheckAccess(p);
p = deref(addOffset(d.data, sizeof(void*)));
qCheckAccess(p);
p = deref(addOffset(p, sizeof(void*)));
qCheckAccess(p);
p = deref(addOffset(p, sizeof(void*)));
qCheckAccess(p);
int nn = 0;
std::list<int>::const_iterator it = list.begin();
for (; nn < 101 && it != list.end(); ++nn, ++it)
qCheckAccess(it.operator->());
if (nn > 100)
P(d, "value", "<more than 100 items>");
else
P(d, "value", "<" << nn << " items>");
P(d, "numchild", nn);
P(d, "valuedisabled", "true");
if (d.dumpChildren) {
QByteArray strippedInnerType = stripPointerType(d.innertype);
const char *stripped =
isPointerType(d.innertype) ? strippedInnerType.data() : 0;
d << ",children=[";
it = list.begin();
for (int i = 0; i < 1000 && it != list.end(); ++i, ++it) {
d.beginHash();
P(d, "name", "[" << i << "]");
qDumpInnerValueOrPointer(d, d.innertype, stripped, it.operator->());
d.endHash();
}
if (it != list.end())
d.putEllipsis();
d << "]";
}
d.disarm();
}
static void qDumpStdMap(QDumper &d)
{
typedef std::map<int, int> DummyType;
const DummyType &map = *reinterpret_cast<const DummyType*>(d.data);
const char *keyType = d.templateParameters[0];
const char *valueType = d.templateParameters[1];
const void *p = d.data;
qCheckAccess(p);
p = deref(p);
int nn = map.size();
qCheck(nn >= 0);
DummyType::const_iterator it = map.begin();
for (int i = 0; i < nn && i < 10 && it != map.end(); ++i, ++it)
qCheckAccess(it.operator->());
QByteArray strippedInnerType = stripPointerType(d.innertype);
P(d, "numchild", nn);
P(d, "value", "<" << nn << " items>");
P(d, "valuedisabled", "true");
P(d, "valueoffset", d.extraInt[2]);
if (d.dumpChildren) {
bool simpleKey = isSimpleType(keyType);
bool simpleValue = isShortKey(valueType);
int valueOffset = d.extraInt[2];
d << ",children=[";
it = map.begin();
for (int i = 0; i < 1000 && it != map.end(); ++i, ++it) {
const void *node = it.operator->();
if (simpleKey) {
d.beginHash();
P(d, "type", valueType);
qDumpInnerValueHelper(d, keyType, node, "name");
P(d, "nameisindex", "1");
if (simpleValue)
qDumpInnerValueHelper(d, valueType, addOffset(node, valueOffset));
P(d, "addr", addOffset(node, valueOffset));
d.endHash();
} else {
d.beginHash();
P(d, "name", "[" << i << "]");
P(d, "addr", it.operator->());
P(d, "type", "std::pair<const " << keyType << "," << valueType << " >");
d.endHash();
}
}
if (it != map.end())
d.putEllipsis();
d << "]";
}
d.disarm();
}
static void qDumpStdString(QDumper &d)
{
const std::string &str = *reinterpret_cast<const std::string *>(d.data);
if (!str.empty()) {
qCheckAccess(str.c_str());
qCheckAccess(str.c_str() + str.size() - 1);
}
d << ",value=\"";
d.putBase64Encoded(str.c_str(), str.size());
d << "\"";
P(d, "valueencoded", "1");
P(d, "type", "std::string");
P(d, "numchild", "0");
d.disarm();
}
static void qDumpStdWString(QDumper &d)
{
const std::wstring &str = *reinterpret_cast<const std::wstring *>(d.data);
if (!str.empty()) {
qCheckAccess(str.c_str());
qCheckAccess(str.c_str() + str.size() - 1);
}
d << "value=\"";
d.putBase64Encoded((const char *)str.c_str(), str.size() * sizeof(wchar_t));
d << "\"";
P(d, "valueencoded", (sizeof(wchar_t) == 2 ? "2" : "3"));
P(d, "type", "std::wstring");
P(d, "numchild", "0");
d.disarm();
}
static void qDumpStdVector(QDumper &d)
{
// Correct type would be something like:
// std::_Vector_base<int,std::allocator<int, std::allocator<int> >>::_Vector_impl
struct VectorImpl {
char *start;
char *finish;
char *end_of_storage;
};
const VectorImpl *v = static_cast<const VectorImpl *>(d.data);
// Try to provoke segfaults early to prevent the frontend
// from asking for unavailable child details
int nn = (v->finish - v->start) / d.extraInt[0];
if (nn < 0)
qCheck(false);
if (nn > 0) {
qCheckAccess(v->start);
qCheckAccess(v->finish);
qCheckAccess(v->end_of_storage);
}
int n = nn;
P(d, "value", "<" << n << " items>");
P(d, "valuedisabled", "true");
P(d, "numchild", n);
if (d.dumpChildren) {
unsigned innersize = d.extraInt[0];
QByteArray strippedInnerType = stripPointerType(d.innertype);
const char *stripped =
isPointerType(d.innertype) ? strippedInnerType.data() : 0;
if (n > 1000)
n = 1000;
d << ",children=[";
for (int i = 0; i != n; ++i) {
d.beginHash();
P(d, "name", "[" << i << "]");
qDumpInnerValueOrPointer(d, d.innertype, stripped,
addOffset(v->start, i * innersize));
d.endHash();
}
if (n < nn)
d.putEllipsis();
d << "]";
}
d.disarm();
}
static void qDumpStdVectorBool(QDumper &d)
{
// FIXME
return qDumpStdVector(d);
}
static void handleProtocolVersion2and3(QDumper & d)
{
if (!d.outertype[0]) {
qDumpUnknown(d);
return;
}
d.setupTemplateParameters();
P(d, "iname", d.iname);
P(d, "addr", d.data);
#ifdef QT_NO_QDATASTREAM
if (d.protocolVersion == 3) {
QVariant::Type type = QVariant::nameToType(d.outertype);
if (type != QVariant::Invalid) {
QVariant v(type, d.data);
QByteArray ba;
QDataStream ds(&ba, QIODevice::WriteOnly);
ds << v;
P(d, "editvalue", ba);
}
}
#endif
const char *type = stripNamespace(d.outertype);
// type[0] is usally 'Q', so don't use it
switch (type[1]) {
case 'B':
if (isEqual(type, "QByteArray"))
qDumpQByteArray(d);
break;
case 'D':
if (isEqual(type, "QDateTime"))
qDumpQDateTime(d);
else if (isEqual(type, "QDir"))
qDumpQDir(d);
break;
case 'F':
if (isEqual(type, "QFile"))
qDumpQFile(d);
else if (isEqual(type, "QFileInfo"))
qDumpQFileInfo(d);
break;
case 'H':
if (isEqual(type, "QHash"))
qDumpQHash(d);
else if (isEqual(type, "QHashNode"))
qDumpQHashNode(d);
break;
case 'I':
if (isEqual(type, "QImage"))
qDumpQImage(d);
break;
case 'L':
if (isEqual(type, "QList"))
qDumpQList(d);
else if (isEqual(type, "QLocale"))
qDumpQLocale(d);
break;
case 'M':
if (isEqual(type, "QMap"))
qDumpQMap(d);
else if (isEqual(type, "QMapNode"))
qDumpQMapNode(d);
else if (isEqual(type, "QModelIndex"))
qDumpQModelIndex(d);
break;
case 'O':
if (isEqual(type, "QObject"))
qDumpQObject(d);
else if (isEqual(type, "QObjectPropertyList"))
qDumpQObjectPropertyList(d);
else if (isEqual(type, "QObjectMethodList"))
qDumpQObjectMethodList(d);
#if PRIVATE_OBJECT_ALLOWED
else if (isEqual(type, "QObjectSignal"))
qDumpQObjectSignal(d);
else if (isEqual(type, "QObjectSignalList"))
qDumpQObjectSignalList(d);
else if (isEqual(type, "QObjectSlot"))
qDumpQObjectSlot(d);
else if (isEqual(type, "QObjectSlotList"))
qDumpQObjectSlotList(d);
#endif
break;
case 'P':
if (isEqual(type, "QPixmap"))
qDumpQPixmap(d);
break;
case 'S':
if (isEqual(type, "QSet"))
qDumpQSet(d);
else if (isEqual(type, "QString"))
qDumpQString(d);
else if (isEqual(type, "QStringList"))
qDumpQStringList(d);
break;
case 'T':
if (isEqual(type, "QTextCodec"))
qDumpQTextCodec(d);
break;
case 'V':
if (isEqual(type, "QVariant"))
qDumpQVariant(d);
else if (isEqual(type, "QVector"))
qDumpQVector(d);
break;
case 's':
if (isEqual(type, "wstring"))
qDumpStdWString(d);
break;
case 't':
if (isEqual(type, "std::vector"))
qDumpStdVector(d);
else if (isEqual(type, "std::vector::bool"))
qDumpStdVectorBool(d);
else if (isEqual(type, "std::list"))
qDumpStdList(d);
else if (isEqual(type, "std::map"))
qDumpStdMap(d);
else if (isEqual(type, "std::string") || isEqual(type, "string"))
qDumpStdString(d);
else if (isEqual(type, "std::wstring"))
qDumpStdWString(d);
break;
}
if (!d.success)
qDumpUnknown(d);
}
} // anonymous namespace
extern "C" Q_DECL_EXPORT
void qDumpObjectData440(
int protocolVersion,
int token,
void *data,
bool dumpChildren,
int extraInt0,
int extraInt1,
int extraInt2,
int extraInt3)
{
if (protocolVersion == 1) {
QDumper d;
d.protocolVersion = protocolVersion;
d.token = token;
//qDebug() << "SOCKET: after connect: state: " << qDumperSocket.state();
// simpledumpers is a list of all available dumpers that are
// _not_ templates. templates currently require special
// hardcoded handling in the debugger plugin.
// don't mention them here in this list
d << "simpledumpers=["
"\""NS"QByteArray\","
"\""NS"QDir\","
"\""NS"QImage\","
"\""NS"QFile\","
"\""NS"QFileInfo\","
"\""NS"QLocale\","
"\""NS"QModelIndex\","
//"\""NS"QHash\"," // handled on GH side
//"\""NS"QHashNode\","
//"\""NS"QMap\"," // handled on GH side
//"\""NS"QMapNode\","
"\""NS"QObject\","
"\""NS"QObjectMethodList\"," // hack to get nested properties display
"\""NS"QObjectPropertyList\","
#if PRIVATE_OBJECT_ALLOWED
"\""NS"QObjectSignal\","
"\""NS"QObjectSignalList\","
"\""NS"QObjectSlot\","
"\""NS"QObjectSlotList\","
#endif // PRIVATE_OBJECT_ALLOWED
"\""NS"QString\","
"\""NS"QStringList\","
"\""NS"QTextCodec\","
"\""NS"QVariant\","
"\""NS"QWidget\","
"\""NS"QDateTime\","
"\"string\","
"\"wstring\","
"\"std::string\","
"\"std::wstring\","
// << "\""NS"QRegion\","
"]";
d << ",namespace=\""NS"\"";
d.disarm();
}
else if (protocolVersion == 2 || protocolVersion == 3) {
QDumper d;
d.protocolVersion = protocolVersion;
d.token = token;
d.data = data;
d.dumpChildren = dumpChildren;
d.extraInt[0] = extraInt0;
d.extraInt[1] = extraInt1;
d.extraInt[2] = extraInt2;
d.extraInt[3] = extraInt3;
const char *inbuffer = qDumpInBuffer;
d.outertype = inbuffer; while (*inbuffer) ++inbuffer; ++inbuffer;
d.iname = inbuffer; while (*inbuffer) ++inbuffer; ++inbuffer;
d.exp = inbuffer; while (*inbuffer) ++inbuffer; ++inbuffer;
d.innertype = inbuffer; while (*inbuffer) ++inbuffer; ++inbuffer;
d.iname = inbuffer; while (*inbuffer) ++inbuffer; ++inbuffer;
handleProtocolVersion2and3(d);
}
else {
qDebug() << "Unsupported protocol version" << protocolVersion;
}
}
| 76,520 | 26,397 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file get_anchor_offset.cc
* \brief
* \author Chenxia Han
*/
#include "./get_anchor_offset-inl.h"
namespace mxnet {
namespace op {
template<>
Operator *CreateOp<cpu>(GetAnchorOffsetParam param, int dtype) {
Operator *op = nullptr;
MSHADOW_REAL_TYPE_SWITCH(dtype, DType, {
op = new GetAnchorOffsetOp<cpu, DType>(param);
});
return op;
}
Operator *GetAnchorOffsetProp::CreateOperatorEx(Context ctx, std::vector<TShape> *in_shape,
std::vector<int> *in_type) const {
std::vector<TShape> out_shape, aux_shape;
std::vector<int> out_type, aux_type;
CHECK(InferType(in_type, &out_type, &aux_type));
CHECK(InferShape(in_shape, &out_shape, &aux_shape));
DO_BIND_DISPATCH(CreateOp, param_, in_type->at(0));
}
DMLC_REGISTER_PARAMETER(GetAnchorOffsetParam);
MXNET_REGISTER_OP_PROPERTY(_contrib_GetAnchorOffset, GetAnchorOffsetProp)
.describe("Compute offset for Deformable Convolution")
.add_argument("data", "NDArray-or-Symbol", "Data to determine height and width")
.add_argument("anchor", "NDArray-or-Symbol", "Anchor to determine offset")
.add_arguments(GetAnchorOffsetParam::__FIELDS__());
} // namespace op
} // namespace mxnet
| 2,011 | 644 |
#ifndef AIKIDO_STATESPACE_SE2STATESPACE_HPP_
#define AIKIDO_STATESPACE_SE2STATESPACE_HPP_
#include <Eigen/Geometry>
#include "aikido/statespace/ScopedState.hpp"
#include "aikido/statespace/StateSpace.hpp"
namespace aikido {
namespace statespace {
/// Defined in detail/SE2-impl.hpp
template <class>
class SE2StateHandle;
/// The two-dimensional special Euclidean group SE(2), i.e. the space of planar
/// rigid body transformations. Note that the group operation for SE(2) differs
/// from the group operation of the Cartesian product space R^2 x SO(2) because
/// it is constructed through the semi-direct product.
class SE2 : public virtual StateSpace
{
public:
class State : public StateSpace::State
{
public:
using Isometry2d
= Eigen::Transform<double, 2, Eigen::Isometry, Eigen::DontAlign>;
/// Constructs the identity element.
State();
~State() = default;
/// Constructs the state from an Eigen transformation object.
///
/// \param _transform Eigen transformation
explicit State(const Isometry2d& _transform);
/// Sets value to an Eigen transfomation object.
///
/// \param _transform Eigen transformation
void setIsometry(const Isometry2d& _transform);
/// Gets value as an Eigen transformation object.
///
/// \return Eigen trasnformation
const Isometry2d& getIsometry() const;
private:
Isometry2d mTransform;
friend class SE2;
};
using StateHandle = SE2StateHandle<State>;
using StateHandleConst = SE2StateHandle<const State>;
using ScopedState = statespace::ScopedState<StateHandle>;
using ScopedStateConst = statespace::ScopedState<StateHandleConst>;
using StateSpace::compose;
using Isometry2d = State::Isometry2d;
/// Constructs a state space representing SE(2).
SE2() = default;
/// Helper function to create a \c ScopedState.
///
/// \return new \c ScopedState
ScopedState createState() const;
/// Creates an identical clone of \c stateIn.
ScopedState cloneState(const StateSpace::State* stateIn) const;
/// Gets value as an Eigen transformation object.
///
/// \param _state a \c State in this state space
/// \return Eigen transformation
const Isometry2d& getIsometry(const State* _state) const;
/// Sets value to an Eigen transfomation object.
///
/// \param _state a \c State in this state space
/// \param _transform Eigen transformation
void setIsometry(State* _state, const Isometry2d& _transform) const;
// Documentation inherited.
std::size_t getStateSizeInBytes() const override;
// Documentation inherited.
StateSpace::State* allocateStateInBuffer(void* _buffer) const override;
// Documentation inherited.
void freeStateInBuffer(StateSpace::State* _state) const override;
// Documentation inherited.
void compose(
const StateSpace::State* _state1,
const StateSpace::State* _state2,
StateSpace::State* _out) const override;
// Documentation inherited
void getIdentity(StateSpace::State* _out) const override;
// Documentation inherited
void getInverse(
const StateSpace::State* _in, StateSpace::State* _out) const override;
// Documentation inherited
std::size_t getDimension() const override;
// Documentation inherited
void copyState(
const StateSpace::State* _source,
StateSpace::State* _destination) const override;
/// Exponential mapping of Lie algebra element to a Lie group element. The
/// tangent space is parameterized a planar twist of the form (translation,
/// translation, rotation).
///
/// \param _tangent element of the tangent space
/// \param[out] _out corresponding element of the Lie group
void expMap(
const Eigen::VectorXd& _tangent, StateSpace::State* _out) const override;
/// Log mapping of Lie group element to a Lie algebra element. The tangent
/// space is parameterized as a planar twist of the form (translation,
/// translation, rotation).
///
/// \param _state element of this Lie group
/// \param[out] _tangent corresponding element of the tangent space
void logMap(const StateSpace::State* _state, Eigen::VectorXd& _tangent)
const override;
/// Print the state. Format: [x, y, theta]
void print(const StateSpace::State* _state, std::ostream& _os) const override;
};
} // namespace statespace
} // namespace aikido
#include "detail/SE2-impl.hpp"
#endif // ifndef AIKIDO_STATESPACE_SE2STATESPACE_HPP_
| 4,446 | 1,339 |
// RUN: %clang_cc1 -no-opaque-pointers -verify -triple x86_64-apple-darwin10 -fopenmp -x c++ -emit-llvm %s -o - | FileCheck %s
// RUN: %clang_cc1 -no-opaque-pointers -fopenmp -x c++ -triple x86_64-apple-darwin10 -emit-pch -o %t %s
// RUN: %clang_cc1 -no-opaque-pointers -fopenmp -x c++ -triple x86_64-apple-darwin10 -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s
// RUN: %clang_cc1 -no-opaque-pointers -fopenmp -x c++ %s -verify -debug-info-kind=limited -emit-llvm -o - -triple x86_64-apple-darwin10 | FileCheck %s --check-prefix=CHECK --check-prefix=DEBUG
// RUN: %clang_cc1 -no-opaque-pointers -verify -triple x86_64-apple-darwin10 -fopenmp-simd -x c++ -emit-llvm %s -o - | FileCheck --check-prefix SIMD-ONLY0 %s
// RUN: %clang_cc1 -no-opaque-pointers -fopenmp-simd -x c++ -triple x86_64-apple-darwin10 -emit-pch -o %t %s
// RUN: %clang_cc1 -no-opaque-pointers -fopenmp-simd -x c++ -triple x86_64-apple-darwin10 -include-pch %t -verify %s -emit-llvm -o - | FileCheck --check-prefix SIMD-ONLY0 %s
// RUN: %clang_cc1 -no-opaque-pointers -fopenmp-simd -x c++ %s -verify -debug-info-kind=limited -emit-llvm -o - -triple x86_64-apple-darwin10 | FileCheck --check-prefix SIMD-ONLY0 %s
// SIMD-ONLY0-NOT: {{__kmpc|__tgt}}
// expected-no-diagnostics
#ifndef HEADER
#define HEADER
typedef void **omp_allocator_handle_t;
extern const omp_allocator_handle_t omp_null_allocator;
extern const omp_allocator_handle_t omp_default_mem_alloc;
extern const omp_allocator_handle_t omp_large_cap_mem_alloc;
extern const omp_allocator_handle_t omp_const_mem_alloc;
extern const omp_allocator_handle_t omp_high_bw_mem_alloc;
extern const omp_allocator_handle_t omp_low_lat_mem_alloc;
extern const omp_allocator_handle_t omp_cgroup_mem_alloc;
extern const omp_allocator_handle_t omp_pteam_mem_alloc;
extern const omp_allocator_handle_t omp_thread_mem_alloc;
// CHECK-DAG: @reduction_size.[[ID:.+]]_[[CID:[0-9]+]].artificial.
// CHECK-DAG: @reduction_size.[[ID]]_[[CID]].artificial..cache.
struct S {
int a;
S() : a(0) {}
S(const S&) {}
S& operator=(const S&) {return *this;}
~S() {}
friend S operator+(const S&a, const S&b) {return a;}
};
int main(int argc, char **argv) {
int a;
float b;
S c[5];
short d[argc];
#pragma omp taskgroup allocate(omp_pteam_mem_alloc: a) task_reduction(+: a, b, argc)
{
#pragma omp taskgroup task_reduction(-:c, d)
;
}
return 0;
}
// CHECK-LABEL: @main
// CHECK: alloca i32,
// CHECK: [[ARGC_ADDR:%.+]] = alloca i32,
// CHECK: [[ARGV_ADDR:%.+]] = alloca i8**,
// CHECK: [[A:%.+]] = alloca i32,
// CHECK: [[B:%.+]] = alloca float,
// CHECK: [[C:%.+]] = alloca [5 x %struct.S],
// CHECK: [[RD_IN1:%.+]] = alloca [3 x [[T1:%[^,]+]]],
// CHECK: [[TD1:%.+]] = alloca i8*,
// CHECK: [[RD_IN2:%.+]] = alloca [2 x [[T2:%[^,]+]]],
// CHECK: [[TD2:%.+]] = alloca i8*,
// CHECK: [[GTID:%.+]] = call i32 @__kmpc_global_thread_num(%struct.ident_t*
// CHECK: [[VLA:%.+]] = alloca i16, i64 [[VLA_SIZE:%[^,]+]],
// CHECK: call void @__kmpc_taskgroup(%struct.ident_t* {{[^,]+}}, i32 [[GTID]])
// CHECK-DAG: [[BC_A:%.+]] = bitcast i32* [[A]] to i8*
// CHECK-DAG: store i8* [[BC_A]], i8** [[A_REF:[^,]+]],
// CHECK-DAG: [[A_REF]] = getelementptr inbounds [[T1]], [[T1]]* [[GEPA:%[^,]+]], i32 0, i32 0
// CHECK-DAG: [[BC_A:%.+]] = bitcast i32* [[A]] to i8*
// CHECK-DAG: store i8* [[BC_A]], i8** [[A_REF:[^,]+]],
// CHECK-DAG: [[A_REF]] = getelementptr inbounds [[T1]], [[T1]]* [[GEPA]], i32 0, i32 1
// CHECK-DAG: [[GEPA]] = getelementptr inbounds [3 x [[T1]]], [3 x [[T1]]]* [[RD_IN1]], i64 0, i64
// CHECK-DAG: [[TMP6:%.+]] = getelementptr inbounds [[T1]], [[T1]]* [[GEPA]], i32 0, i32 2
// CHECK-DAG: store i64 4, i64* [[TMP6]],
// CHECK-DAG: [[TMP7:%.+]] = getelementptr inbounds [[T1]], [[T1]]* [[GEPA]], i32 0, i32 3
// CHECK-DAG: store i8* bitcast (void (i8*, i8*)* @[[AINIT:.+]] to i8*), i8** [[TMP7]],
// CHECK-DAG: [[TMP8:%.+]] = getelementptr inbounds [[T1]], [[T1]]* [[GEPA]], i32 0, i32 4
// CHECK-DAG: store i8* null, i8** [[TMP8]],
// CHECK-DAG: [[TMP9:%.+]] = getelementptr inbounds [[T1]], [[T1]]* [[GEPA]], i32 0, i32 5
// CHECK-DAG: store i8* bitcast (void (i8*, i8*)* @[[ACOMB:.+]] to i8*), i8** [[TMP9]],
// CHECK-DAG: [[TMP10:%.+]] = getelementptr inbounds [[T1]], [[T1]]* [[GEPA]], i32 0, i32 6
// CHECK-DAG: [[TMP11:%.+]] = bitcast i32* [[TMP10]] to i8*
// CHECK-DAG: call void @llvm.memset.p0i8.i64(i8* align 8 [[TMP11]], i8 0, i64 4, i1 false)
// CHECK-DAG: [[TMP13:%.+]] = bitcast float* [[B]] to i8*
// CHECK-DAG: store i8* [[TMP13]], i8** [[TMP12:%[^,]+]],
// CHECK-DAG: [[TMP12]] = getelementptr inbounds [[T1]], [[T1]]* [[GEPB:%[^,]+]], i32 0, i32 0
// CHECK-DAG: [[TMP13:%.+]] = bitcast float* [[B]] to i8*
// CHECK-DAG: store i8* [[TMP13]], i8** [[TMP12:%[^,]+]],
// CHECK-DAG: [[TMP12]] = getelementptr inbounds [[T1]], [[T1]]* [[GEPB]], i32 0, i32 1
// CHECK-DAG: [[GEPB]] = getelementptr inbounds [3 x [[T1]]], [3 x [[T1]]]* [[RD_IN1]], i64 0, i64
// CHECK-DAG: [[TMP14:%.+]] = getelementptr inbounds [[T1]], [[T1]]* [[GEPB]], i32 0, i32 2
// CHECK-DAG: store i64 4, i64* [[TMP14]],
// CHECK-DAG: [[TMP15:%.+]] = getelementptr inbounds [[T1]], [[T1]]* [[GEPB]], i32 0, i32 3
// CHECK-DAG: store i8* bitcast (void (i8*, i8*)* @[[BINIT:.+]] to i8*), i8** [[TMP15]],
// CHECK-DAG: [[TMP16:%.+]] = getelementptr inbounds [[T1]], [[T1]]* [[GEPB]], i32 0, i32 4
// CHECK-DAG: store i8* null, i8** [[TMP16]],
// CHECK-DAG: [[TMP17:%.+]] = getelementptr inbounds [[T1]], [[T1]]* [[GEPB]], i32 0, i32 5
// CHECK-DAG: store i8* bitcast (void (i8*, i8*)* @[[BCOMB:.+]] to i8*), i8** [[TMP17]],
// CHECK-DAG: [[TMP18:%.+]] = getelementptr inbounds [[T1]], [[T1]]* [[GEPB]], i32 0, i32 6
// CHECK-DAG: [[TMP19:%.+]] = bitcast i32* [[TMP18]] to i8*
// CHECK-DAG: call void @llvm.memset.p0i8.i64(i8* align 8 [[TMP19]], i8 0, i64 4, i1 false)
// CHECK-DAG: [[TMP21:%.+]] = bitcast i32* [[ARGC_ADDR]] to i8*
// CHECK-DAG: store i8* [[TMP21]], i8** [[TMP20:%[^,]+]],
// CHECK-DAG: [[TMP20]] = getelementptr inbounds [[T1]], [[T1]]* [[GEPARGC:%[^,]+]], i32 0, i32 0
// CHECK-DAG: [[TMP21:%.+]] = bitcast i32* [[ARGC_ADDR]] to i8*
// CHECK-DAG: store i8* [[TMP21]], i8** [[TMP20:%[^,]+]],
// CHECK-DAG: [[TMP20]] = getelementptr inbounds [[T1]], [[T1]]* [[GEPARGC]], i32 0, i32 1
// CHECK-DAG: [[GEPARGC]] = getelementptr inbounds [3 x [[T1]]], [3 x [[T1]]]* [[RD_IN1]], i64 0, i64
// CHECK-DAG: [[TMP22:%.+]] = getelementptr inbounds [[T1]], [[T1]]* [[GEPARGC]], i32 0, i32 2
// CHECK-DAG: store i64 4, i64* [[TMP22]],
// CHECK-DAG: [[TMP23:%.+]] = getelementptr inbounds [[T1]], [[T1]]* [[GEPARGC]], i32 0, i32 3
// CHECK-DAG: store i8* bitcast (void (i8*, i8*)* @[[ARGCINIT:.+]] to i8*), i8** [[TMP23]],
// CHECK-DAG: [[TMP24:%.+]] = getelementptr inbounds [[T1]], [[T1]]* [[GEPARGC]], i32 0, i32 4
// CHECK-DAG: store i8* null, i8** [[TMP24]],
// CHECK-DAG: [[TMP25:%.+]] = getelementptr inbounds [[T1]], [[T1]]* [[GEPARGC]], i32 0, i32 5
// CHECK-DAG: store i8* bitcast (void (i8*, i8*)* @[[ARGCCOMB:.+]] to i8*), i8** [[TMP25]],
// CHECK-DAG: [[TMP26:%.+]] = getelementptr inbounds [[T1]], [[T1]]* [[GEPARGC]], i32 0, i32 6
// CHECK-DAG: [[TMP27:%.+]] = bitcast i32* [[TMP26]] to i8*
// CHECK-DAG: call void @llvm.memset.p0i8.i64(i8* align 8 [[TMP27]], i8 0, i64 4, i1 false)
// CHECK-DAG: [[TMP28:%.+]] = bitcast [3 x [[T1]]]* [[RD_IN1]] to i8*
// CHECK-DAG: [[TMP29:%.+]] = call i8* @__kmpc_taskred_init(i32 [[GTID]], i32 3, i8* [[TMP28]])
// DEBUG-DAG: call void @llvm.dbg.declare(metadata i8** [[TD1]],
// CHECK-DAG: store i8* [[TMP29]], i8** [[TD1]],
// CHECK-DAG: call void @__kmpc_taskgroup(%struct.ident_t* {{[^,]+}}, i32 [[GTID]])
// CHECK-DAG: [[TMP31:%.+]] = bitcast [5 x %struct.S]* [[C]] to i8*
// CHECK-DAG: store i8* [[TMP31]], i8** [[TMP30:%[^,]+]],
// CHECK-DAG: [[TMP30]] = getelementptr inbounds [[T2]], [[T2]]* [[GEPC:%[^,]+]], i32 0, i32 0
// CHECK-DAG: [[TMP31:%.+]] = bitcast [5 x %struct.S]* [[C]] to i8*
// CHECK-DAG: store i8* [[TMP31]], i8** [[TMP30:%[^,]+]],
// CHECK-DAG: [[TMP30]] = getelementptr inbounds [[T2]], [[T2]]* [[GEPC]], i32 0, i32 1
// CHECK-DAG: [[GEPC]] = getelementptr inbounds [2 x [[T2]]], [2 x [[T2]]]* [[RD_IN2]], i64 0, i64
// CHECK-DAG: [[TMP32:%.+]] = getelementptr inbounds [[T2]], [[T2]]* [[GEPC]], i32 0, i32 2
// CHECK-DAG: store i64 20, i64* [[TMP32]],
// CHECK-DAG: [[TMP33:%.+]] = getelementptr inbounds [[T2]], [[T2]]* [[GEPC]], i32 0, i32 3
// CHECK-DAG: store i8* bitcast (void (i8*, i8*)* @[[CINIT:.+]] to i8*), i8** [[TMP33]],
// CHECK-DAG: [[TMP34:%.+]] = getelementptr inbounds [[T2]], [[T2]]* [[GEPC]], i32 0, i32 4
// CHECK-DAG: store i8* bitcast (void (i8*)* @[[CFINI:.+]] to i8*), i8** [[TMP34]],
// CHECK-DAG: [[TMP35:%.+]] = getelementptr inbounds [[T2]], [[T2]]* [[GEPC]], i32 0, i32 5
// CHECK-DAG: store i8* bitcast (void (i8*, i8*)* @[[CCOMB:.+]] to i8*), i8** [[TMP35]],
// CHECK-DAG: [[TMP36:%.+]] = getelementptr inbounds [[T2]], [[T2]]* [[GEPC]], i32 0, i32 6
// CHECK-DAG: [[TMP37:%.+]] = bitcast i32* [[TMP36]] to i8*
// CHECK-DAG: call void @llvm.memset.p0i8.i64(i8* align 8 [[TMP37]], i8 0, i64 4, i1 false)
// CHECK-DAG: [[TMP39:%.+]] = bitcast i16* [[VLA]] to i8*
// CHECK-DAG: store i8* [[TMP39]], i8** [[TMP38:%[^,]+]],
// CHECK-DAG: [[TMP38]] = getelementptr inbounds [[T2]], [[T2]]* [[GEPVLA:%[^,]+]], i32 0, i32 0
// CHECK-DAG: [[TMP39:%.+]] = bitcast i16* [[VLA]] to i8*
// CHECK-DAG: store i8* [[TMP39]], i8** [[TMP38:%[^,]+]],
// CHECK-DAG: [[TMP38]] = getelementptr inbounds [[T2]], [[T2]]* [[GEPVLA]], i32 0, i32 1
// CHECK-DAG: [[GEPVLA]] = getelementptr inbounds [2 x [[T2]]], [2 x [[T2]]]* [[RD_IN2]], i64 0, i64
// CHECK-DAG: [[TMP40:%.+]] = mul nuw i64 [[VLA_SIZE]], 2
// CHECK-DAG: [[TMP41:%.+]] = udiv exact i64 [[TMP40]], ptrtoint (i16* getelementptr (i16, i16* null, i32 1) to i64)
// CHECK-DAG: [[TMP42:%.+]] = getelementptr inbounds [[T2]], [[T2]]* [[GEPVLA]], i32 0, i32 2
// CHECK-DAG: store i64 [[TMP40]], i64* [[TMP42]],
// CHECK-DAG: [[TMP43:%.+]] = getelementptr inbounds [[T2]], [[T2]]* [[GEPVLA]], i32 0, i32 3
// CHECK-DAG: store i8* bitcast (void (i8*, i8*)* @[[VLAINIT:.+]] to i8*), i8** [[TMP43]],
// CHECK-DAG: [[TMP44:%.+]] = getelementptr inbounds [[T2]], [[T2]]* [[GEPVLA]], i32 0, i32 4
// CHECK-DAG: store i8* null, i8** [[TMP44]],
// CHECK-DAG: [[TMP45:%.+]] = getelementptr inbounds [[T2]], [[T2]]* [[GEPVLA]], i32 0, i32 5
// CHECK-DAG: store i8* bitcast (void (i8*, i8*)* @[[VLACOMB:.+]] to i8*), i8** [[TMP45]],
// CHECK-DAG: [[TMP46:%.+]] = getelementptr inbounds [[T2]], [[T2]]* [[GEPVLA]], i32 0, i32 6
// CHECK-DAG: store i32 1, i32* [[TMP46]],
// CHECK: [[TMP47:%.+]] = bitcast [2 x [[T2]]]* [[RD_IN2]] to i8*
// CHECK: [[TMP48:%.+]] = call i8* @__kmpc_taskred_init(i32 [[GTID]], i32 2, i8* [[TMP47]])
// CHECK: store i8* [[TMP48]], i8** [[TD2]],
// CHECK: call void @__kmpc_end_taskgroup(%struct.ident_t* {{[^,]+}}, i32 [[GTID]])
// CHECK: call void @__kmpc_end_taskgroup(%struct.ident_t* {{[^,]+}}, i32 [[GTID]])
// CHECK-DAG: define internal void @[[AINIT]](i8* noalias noundef %{{.+}}, i8* noalias noundef %{{.+}})
// CHECK-DAG: store i32 0, i32* %
// CHECK-DAG: ret void
// CHECK-DAG: }
// CHECK-DAG: define internal void @[[ACOMB]](i8* noundef %0, i8* noundef %1)
// CHECK-DAG: add nsw i32 %
// CHECK-DAG: store i32 %
// CHECK-DAG: ret void
// CHECK-DAG: }
// CHECK-DAG: define internal void @[[BINIT]](i8* noalias noundef %{{.+}}, i8* noalias noundef %{{.+}})
// CHECK-DAG: store float 0.000000e+00, float* %
// CHECK-DAG: ret void
// CHECK-DAG: }
// CHECK-DAG: define internal void @[[BCOMB]](i8* noundef %0, i8* noundef %1)
// CHECK-DAG: fadd float %
// CHECK-DAG: store float %
// CHECK-DAG: ret void
// CHECK-DAG: }
// CHECK-DAG: define internal void @[[ARGCINIT]](i8* noalias noundef %{{.+}}, i8* noalias noundef %{{.+}})
// CHECK-DAG: store i32 0, i32* %
// CHECK-DAG: ret void
// CHECK-DAG: }
// CHECK-DAG: define internal void @[[ARGCCOMB]](i8* noundef %0, i8* noundef %1)
// CHECK-DAG: add nsw i32 %
// CHECK-DAG: store i32 %
// CHECK-DAG: ret void
// CHECK-DAG: }
// CHECK-DAG: define internal void @[[CINIT]](i8* noalias noundef %{{.+}}, i8* noalias noundef %{{.+}})
// CHECK-DAG: phi %struct.S* [
// CHECK-DAG: call {{.+}}(%struct.S* {{.+}})
// CHECK-DAG: br i1 %
// CHECK-DAG: ret void
// CHECK-DAG: }
// CHECK-DAG: define internal void @[[CFINI]](i8* noundef %0)
// CHECK-DAG: phi %struct.S* [
// CHECK-DAG: call {{.+}}(%struct.S* {{.+}})
// CHECK-DAG: br i1 %
// CHECK-DAG: ret void
// CHECK-DAG: }
// CHECK-DAG: define internal void @[[CCOMB]](i8* noundef %0, i8* noundef %1)
// CHECK-DAG: phi %struct.S* [
// CHECK-DAG: phi %struct.S* [
// CHECK-DAG: call {{.+}}(%struct.S* {{.+}}, %struct.S* {{.+}}, %struct.S* {{.+}})
// CHECK-DAG: call {{.+}}(%struct.S* {{.+}}, %struct.S* {{.+}})
// CHECK-DAG: call {{.+}}(%struct.S* {{.+}})
// CHECK-DAG: br i1 %
// CHECK-DAG: ret void
// CHECK_DAG: }
// CHECK-DAG: define internal void @[[VLAINIT]](i8* noalias noundef %{{.+}}, i8* noalias noundef %{{.+}})
// CHECK-DAG: call i32 @__kmpc_global_thread_num(%struct.ident_t* {{[^,]+}})
// CHECK-DAG: call i8* @__kmpc_threadprivate_cached(%struct.ident_t*
// CHECK-DAG: phi i16* [
// CHECK-DAG: store i16 0, i16* %
// CHECK-DAG: br i1 %
// CHECK-DAG: ret void
// CHECK-DAG: }
// CHECK-DAG: define internal void @[[VLACOMB]](i8* noundef %0, i8* noundef %1)
// CHECK-DAG: call i32 @__kmpc_global_thread_num(%struct.ident_t* {{[^,]+}})
// CHECK-DAG: call i8* @__kmpc_threadprivate_cached(%struct.ident_t*
// CHECK-DAG: phi i16* [
// CHECK-DAG: phi i16* [
// CHECK-DAG: sext i16 %{{.+}} to i32
// CHECK-DAG: add nsw i32 %
// CHECK-DAG: trunc i32 %{{.+}} to i16
// CHECK-DAG: store i16 %
// CHECK_DAG: br i1 %
// CHECK-DAG: ret void
// CHECK-DAG: }
#endif
// DEBUG-LABEL: distinct !DICompileUnit
// DEBUG-DAG: distinct !DISubprogram(linkageName: "[[AINIT]]",
// DEBUG-DAG: distinct !DISubprogram(linkageName: "[[ACOMB]]",
// DEBUG-DAG: distinct !DISubprogram(linkageName: "[[BINIT]]",
// DEBUG-DAG: distinct !DISubprogram(linkageName: "[[BCOMB]]",
// DEBUG-DAG: distinct !DISubprogram(linkageName: "[[ARGCINIT]]",
// DEBUG-DAG: distinct !DISubprogram(linkageName: "[[ARGCCOMB]]",
// DEBUG-DAG: distinct !DISubprogram(linkageName: "[[CINIT]]",
// DEBUG-DAG: distinct !DISubprogram(linkageName: "[[CFINI]]",
// DEBUG-DAG: distinct !DISubprogram(linkageName: "[[CCOMB]]",
// DEBUG-DAG: distinct !DISubprogram(linkageName: "[[VLAINIT]]",
// DEBUG-DAG: distinct !DISubprogram(linkageName: "[[VLACOMB]]",
| 14,710 | 7,010 |
/***************************************************************************
* Copyright 1998-2017 by authors (see AUTHORS.txt) *
* *
* This file is part of LuxRender. *
* *
* 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 <imgui.h>
#include <boost/filesystem.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <nfd.h>
#include "luxcoreapp.h"
using namespace std;
using namespace luxrays;
using namespace luxcore;
//------------------------------------------------------------------------------
// MenuRendering
//------------------------------------------------------------------------------
#if !defined(LUXRAYS_DISABLE_OPENCL)
static void KernelCacheFillProgressHandler(const size_t step, const size_t count) {
LA_LOG("KernelCache FillProgressHandler Step: " << step << "/" << count);
}
#endif
void LuxCoreApp::MenuRendering() {
if (ImGui::MenuItem("Load")) {
nfdchar_t *fileFileName = NULL;
nfdresult_t result = NFD_OpenDialog("cfg;lxs", NULL, &fileFileName);
if (result == NFD_OKAY) {
LoadRenderConfig(fileFileName);
free(fileFileName);
}
}
if (session && ImGui::MenuItem("Export")) {
nfdchar_t *outPath = NULL;
nfdresult_t result = NFD_SaveDialog(NULL, NULL, &outPath);
if (result == NFD_OKAY) {
LA_LOG("Export current scene to directory: " << outPath);
boost::filesystem::path dir(outPath);
boost::filesystem::create_directories(dir);
// Save the current render engine
const string renderEngine = config->GetProperty("renderengine.type").Get<string>();
// Set the render engine to FILESAVER
RenderConfigParse(Properties() <<
Property("renderengine.type")("FILESAVER") <<
Property("filesaver.directory")(outPath) <<
Property("filesaver.renderengine.type")(renderEngine));
// Restore the render engine setting
RenderConfigParse(Properties() <<
Property("renderengine.type")(renderEngine));
}
}
ImGui::Separator();
// Simplified save/resume rendering method: uses predefined names
const string saveResumeName = "current";
if (session && ImGui::MenuItem("Save rendering (simplified)")) {
// Pause the current rendering
session->Pause();
// Save the film
session->GetFilm().SaveFilm(saveResumeName + ".flm");
// Save the render state
RenderState *renderState = session->GetRenderState();
renderState->Save(saveResumeName + ".rst");
delete renderState;
// Resume the current rendering
session->Resume();
}
if (ImGui::MenuItem("Resume rendering (simplified)")) {
// Select the scene
nfdchar_t *sceneFileName = NULL;
nfdresult_t result = NFD_OpenDialog("cfg;lxs", NULL, &sceneFileName);
if (result == NFD_OKAY) {
// Load the start film
Film *startFilm = Film::Create(saveResumeName + ".flm");
// Load the start render state
RenderState *startRenderState = RenderState::Create(saveResumeName + ".rst");
LoadRenderConfig(sceneFileName, startRenderState, startFilm);
free(sceneFileName);
}
}
// Normal saving rendering method: requires to select multiple file names
if (session && ImGui::MenuItem("Save rendering")) {
nfdchar_t *outName = NULL;
nfdresult_t result = NFD_SaveDialog(NULL, NULL, &outName);
if (result == NFD_OKAY) {
// Pause the current rendering
session->Pause();
// Save the film
session->GetFilm().SaveFilm(string(outName) + ".flm");
// Save the render state
RenderState *renderState = session->GetRenderState();
renderState->Save(string(outName) + ".rst");
delete renderState;
// Resume the current rendering
session->Resume();
}
}
if (ImGui::MenuItem("Resume rendering")) {
// Select the scene
nfdchar_t *sceneFileName = NULL;
nfdresult_t result = NFD_OpenDialog("cfg;lxs", NULL, &sceneFileName);
if (result == NFD_OKAY) {
// Select the film
nfdchar_t *filmFileName = NULL;
result = NFD_OpenDialog("flm", NULL, &filmFileName);
if (result == NFD_OKAY) {
// Select the render state
nfdchar_t *renderStateFileName = NULL;
result = NFD_OpenDialog("rst", NULL, &renderStateFileName);
if (result == NFD_OKAY) {
// Load the start film
Film *startFilm = Film::Create(filmFileName);
// Load the start render state
RenderState *startRenderState = RenderState::Create(renderStateFileName);
LoadRenderConfig(sceneFileName, startRenderState, startFilm);
free(renderStateFileName);
}
free(filmFileName);
}
free(sceneFileName);
}
// Film *startFilm = new Film("aa.flm");
// RenderState *startRenderState = new RenderState("aa.rst");
// LoadRenderConfig("scenes/luxball/luxball-hdr.cfg", startRenderState, startFilm);
}
ImGui::Separator();
if (session) {
if (session->IsInPause()) {
if (ImGui::MenuItem("Resume"))
session->Resume();
} else {
if (ImGui::MenuItem("Pause"))
session->Pause();
}
if (ImGui::MenuItem("Cancel"))
DeleteRendering();
if (session && ImGui::MenuItem("Restart", "Space bar")) {
// Restart rendering
session->Stop();
session->Start();
}
ImGui::Separator();
}
#if !defined(LUXRAYS_DISABLE_OPENCL)
if (ImGui::MenuItem("Fill kernel cache")) {
if (session) {
// Stop any current rendering
DeleteRendering();
}
Properties props;
/*props <<
Property("opencl.devices.select")("010") <<
Property("opencl.code.alwaysenabled")(
"MATTE MIRROR GLASS ARCHGLASS MATTETRANSLUCENT GLOSSY2 "
"METAL2 ROUGHGLASS ROUGHMATTE ROUGHMATTETRANSLUCENT "
"GLOSSYTRANSLUCENT "
"GLOSSY2_ABSORPTION GLOSSY2_MULTIBOUNCE "
"HOMOGENEOUS_VOL CLEAR_VOL "
"IMAGEMAPS_BYTE_FORMAT IMAGEMAPS_HALF_FORMAT "
"IMAGEMAPS_1xCHANNELS IMAGEMAPS_3xCHANNELS "
"HAS_BUMPMAPS "
"INFINITE TRIANGLELIGHT") <<
Property("kernelcachefill.renderengine.types")("PATHOCL") <<
Property("kernelcachefill.sampler.types")("SOBOL") <<
Property("kernelcachefill.camera.types")("perspective") <<
Property("kernelcachefill.light.types")("infinite", "trianglelight") <<
Property("kernelcachefill.texture.types")("checkerboard2d", "checkerboard3d");*/
KernelCacheFill(props, KernelCacheFillProgressHandler);
}
ImGui::Separator();
#endif
if (ImGui::MenuItem("Quit", "ESC"))
glfwSetWindowShouldClose(window, GL_TRUE);
}
//------------------------------------------------------------------------------
// MenuEngine
//------------------------------------------------------------------------------
void LuxCoreApp::MenuEngine() {
const string currentEngineType = config->ToProperties().Get("renderengine.type").Get<string>();
if (ImGui::MenuItem("PATHOCL", "1", (currentEngineType == "PATHOCL"))) {
SetRenderingEngineType("PATHOCL");
CloseAllRenderConfigEditors();
}
if (ImGui::MenuItem("LIGHTCPU", "2", (currentEngineType == "LIGHTCPU"))) {
SetRenderingEngineType("LIGHTCPU");
CloseAllRenderConfigEditors();
}
if (ImGui::MenuItem("PATHCPU", "3", (currentEngineType == "PATHCPU"))) {
SetRenderingEngineType("PATHCPU");
CloseAllRenderConfigEditors();
}
if (ImGui::MenuItem("BIDIRCPU", "4", (currentEngineType == "BIDIRCPU"))) {
SetRenderingEngineType("BIDIRCPU");
CloseAllRenderConfigEditors();
}
if (ImGui::MenuItem("BIDIRVMCPU", "5", (currentEngineType == "BIDIRVMCPU"))) {
SetRenderingEngineType("BIDIRVMCPU");
CloseAllRenderConfigEditors();
}
#if !defined(LUXRAYS_DISABLE_OPENCL)
if (ImGui::MenuItem("RTPATHOCL", "6", (currentEngineType == "RTPATHOCL"))) {
SetRenderingEngineType("RTPATHOCL");
CloseAllRenderConfigEditors();
}
#endif
if (ImGui::MenuItem("TILEPATHCPU", "7", (currentEngineType == "TILEPATHCPU"))) {
SetRenderingEngineType("TILEPATHCPU");
CloseAllRenderConfigEditors();
}
#if !defined(LUXRAYS_DISABLE_OPENCL)
if (ImGui::MenuItem("TILEPATHOCL", "8", (currentEngineType == "TILEPATHOCL"))) {
SetRenderingEngineType("TILEPATHOCL");
CloseAllRenderConfigEditors();
}
#endif
if (ImGui::MenuItem("RTPATHCPU", "9", (currentEngineType == "RTPATHCPU"))) {
SetRenderingEngineType("RTPATHCPU");
CloseAllRenderConfigEditors();
}
}
//------------------------------------------------------------------------------
// MenuSampler
//------------------------------------------------------------------------------
void LuxCoreApp::MenuSampler() {
const string currentSamplerType = config->ToProperties().Get("sampler.type").Get<string>();
if (ImGui::MenuItem("RANDOM", NULL, (currentSamplerType == "RANDOM"))) {
samplerWindow.Close();
RenderConfigParse(Properties() << Property("sampler.type")("RANDOM"));
}
if (ImGui::MenuItem("SOBOL", NULL, (currentSamplerType == "SOBOL"))) {
samplerWindow.Close();
RenderConfigParse(Properties() << Property("sampler.type")("SOBOL"));
}
if (ImGui::MenuItem("METROPOLIS", NULL, (currentSamplerType == "METROPOLIS"))) {
samplerWindow.Close();
RenderConfigParse(Properties() << Property("sampler.type")("METROPOLIS"));
}
}
//------------------------------------------------------------------------------
// MenuTiles
//------------------------------------------------------------------------------
void LuxCoreApp::MenuTiles() {
bool showPending = config->GetProperties().Get(Property("screen.tiles.pending.show")(true)).Get<bool>();
if (ImGui::MenuItem("Show pending", NULL, showPending))
RenderConfigParse(Properties() << Property("screen.tiles.pending.show")(!showPending));
bool showConverged = config->GetProperties().Get(Property("screen.tiles.converged.show")(false)).Get<bool>();
if (ImGui::MenuItem("Show converged", NULL, showConverged))
RenderConfigParse(Properties() << Property("screen.tiles.converged.show")(!showConverged));
bool showNotConverged = config->GetProperties().Get(Property("screen.tiles.notconverged.show")(false)).Get<bool>();
if (ImGui::MenuItem("Show not converged", NULL, showNotConverged))
RenderConfigParse(Properties() << Property("screen.tiles.notconverged.show")(!showNotConverged));
ImGui::Separator();
bool showPassCount = config->GetProperties().Get(Property("screen.tiles.passcount.show")(false)).Get<bool>();
if (ImGui::MenuItem("Show pass count", NULL, showPassCount))
RenderConfigParse(Properties() << Property("screen.tiles.passcount.show")(!showPassCount));
bool showError = config->GetProperties().Get(Property("screen.tiles.error.show")(false)).Get<bool>();
if (ImGui::MenuItem("Show error", NULL, showError))
RenderConfigParse(Properties() << Property("screen.tiles.error.show")(!showError));
}
//------------------------------------------------------------------------------
// MenuFilm
//------------------------------------------------------------------------------
void LuxCoreApp::MenuFilm() {
if (ImGui::BeginMenu("Set resolution")) {
if (ImGui::MenuItem("320x240"))
SetFilmResolution(320, 240);
if (ImGui::MenuItem("640x480"))
SetFilmResolution(640, 480);
if (ImGui::MenuItem("800x600"))
SetFilmResolution(800, 600);
if (ImGui::MenuItem("1024x768"))
SetFilmResolution(1024, 768);
if (ImGui::MenuItem("1280x720"))
SetFilmResolution(1280, 720);
if (ImGui::MenuItem("1920x1080"))
SetFilmResolution(1920, 1080);
ImGui::Separator();
if (ImGui::MenuItem("Use window resolution")) {
int currentFrameBufferWidth, currentFrameBufferHeight;
glfwGetFramebufferSize(window, ¤tFrameBufferWidth, ¤tFrameBufferHeight);
SetFilmResolution(currentFrameBufferWidth, currentFrameBufferHeight);
}
ImGui::Separator();
ImGui::TextUnformatted("Width x Height");
ImGui::PushItemWidth(100);
ImGui::InputInt("##width", &menuFilmWidth);
ImGui::PopItemWidth();
ImGui::SameLine();
ImGui::TextUnformatted("x");
ImGui::SameLine();
ImGui::PushItemWidth(100);
ImGui::InputInt("##height", &menuFilmHeight);
ImGui::PopItemWidth();
ImGui::SameLine();
if (ImGui::Button("Apply"))
SetFilmResolution(menuFilmWidth, menuFilmHeight);
ImGui::EndMenu();
}
ImGui::Separator();
if (session && ImGui::MenuItem("Save outputs"))
session->GetFilm().SaveOutputs();
if (session && ImGui::MenuItem("Save film"))
session->GetFilm().SaveFilm("film.flm");
}
//------------------------------------------------------------------------------
// MenuImagePipeline
//------------------------------------------------------------------------------
void LuxCoreApp::MenuImagePipeline() {
const unsigned int imagePipelineCount = session->GetFilm().GetChannelCount(Film::CHANNEL_IMAGEPIPELINE);
for (unsigned int i = 0; i < imagePipelineCount; ++i) {
if (ImGui::MenuItem(string("Pipeline #" + ToString(i)).c_str(), NULL, (i == imagePipelineIndex)))
imagePipelineIndex = i;
}
if (imagePipelineIndex > imagePipelineCount)
imagePipelineIndex = 0;
}
//------------------------------------------------------------------------------
// MenuScreen
//------------------------------------------------------------------------------
void LuxCoreApp::MenuScreen() {
if (ImGui::BeginMenu("Interpolation mode")) {
if (ImGui::MenuItem("Nearest", NULL, (renderFrameBufferTexMinFilter == GL_NEAREST))) {
renderFrameBufferTexMinFilter = GL_NEAREST;
renderFrameBufferTexMagFilter = GL_NEAREST;
}
if (ImGui::MenuItem("Linear", NULL, (renderFrameBufferTexMinFilter == GL_LINEAR))) {
renderFrameBufferTexMinFilter = GL_LINEAR;
renderFrameBufferTexMagFilter = GL_LINEAR;
}
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Refresh interval")) {
if (ImGui::MenuItem("5ms"))
config->Parse(Properties().Set(Property("screen.refresh.interval")(5)));
if (ImGui::MenuItem("10ms"))
config->Parse(Properties().Set(Property("screen.refresh.interval")(10)));
if (ImGui::MenuItem("20ms"))
config->Parse(Properties().Set(Property("screen.refresh.interval")(20)));
if (ImGui::MenuItem("50ms"))
config->Parse(Properties().Set(Property("screen.refresh.interval")(50)));
if (ImGui::MenuItem("100ms"))
config->Parse(Properties().Set(Property("screen.refresh.interval")(100)));
if (ImGui::MenuItem("500ms"))
config->Parse(Properties().Set(Property("screen.refresh.interval")(500)));
if (ImGui::MenuItem("1000ms"))
config->Parse(Properties().Set(Property("screen.refresh.interval")(1000)));
if (ImGui::MenuItem("2000ms"))
config->Parse(Properties().Set(Property("screen.refresh.interval")(2000)));
ImGui::EndMenu();
}
if (ImGui::MenuItem("Decrease refresh interval","n"))
DecScreenRefreshInterval();
if (ImGui::MenuItem("Increase refresh interval","m"))
IncScreenRefreshInterval();
if (ImGui::BeginMenu("UI font scale")) {
ImGuiIO &io = ImGui::GetIO();
if (ImGui::MenuItem("1.0", NULL, (io.FontGlobalScale == 1.f)))
io.FontGlobalScale = 1.f;
if (ImGui::MenuItem("1.25", NULL, (io.FontGlobalScale == 1.25f)))
io.FontGlobalScale = 1.25f;
if (ImGui::MenuItem("1.5", NULL, (io.FontGlobalScale == 1.5f)))
io.FontGlobalScale = 1.5f;
if (ImGui::MenuItem("1.75", NULL, (io.FontGlobalScale == 1.75f)))
io.FontGlobalScale = 1.75f;
if (ImGui::MenuItem("2.0", NULL, (io.FontGlobalScale == 2.f)))
io.FontGlobalScale = 2.f;
ImGui::EndMenu();
}
}
//------------------------------------------------------------------------------
// MenuTool
//------------------------------------------------------------------------------
void LuxCoreApp::MenuTool() {
if (ImGui::MenuItem("Camera edit", NULL, (currentTool == TOOL_CAMERA_EDIT))) {
currentTool = TOOL_CAMERA_EDIT;
RenderConfigParse(Properties() << Property("screen.tool.type")("CAMERA_EDIT"));
}
if (ImGui::MenuItem("Object selection", NULL, (currentTool == TOOL_OBJECT_SELECTION))) {
currentTool = TOOL_OBJECT_SELECTION;
Properties props;
props << Property("screen.tool.type")("OBJECT_SELECTION");
// Check if the session a OBJECT_ID AOV enabled
if(!session->GetFilm().HasOutput(Film::OUTPUT_OBJECT_ID)) {
// Enable OBJECT_ID AOV
props <<
Property("film.outputs.LUXCOREUI_OBJECTSELECTION_AOV.type")("OBJECT_ID") <<
Property("film.outputs.LUXCOREUI_OBJECTSELECTION_AOV.filename")("dummy.png");
}
RenderConfigParse(props);
}
if (ImGui::MenuItem("Image view", NULL, (currentTool == TOOL_IMAGE_VIEW))) {
currentTool = TOOL_IMAGE_VIEW;
RenderConfigParse(Properties() << Property("screen.tool.type")("IMAGE_VIEW"));
}
}
//------------------------------------------------------------------------------
// MenuWindow
//------------------------------------------------------------------------------
void LuxCoreApp::MenuWindow() {
if (session) {
const string currentRenderEngineType = config->ToProperties().Get("renderengine.type").Get<string>();
if (ImGui::MenuItem("Render Engine editor", NULL, renderEngineWindow.IsOpen()))
renderEngineWindow.Toggle();
if (ImGui::MenuItem("Sampler editor", NULL, samplerWindow.IsOpen(),
!boost::starts_with(currentRenderEngineType, "TILE") && !boost::starts_with(currentRenderEngineType, "RT")))
samplerWindow.Toggle();
if (ImGui::MenuItem("Pixel Filter editor", NULL, pixelFilterWindow.IsOpen()))
pixelFilterWindow.Toggle();
if (ImGui::MenuItem("OpenCL Device editor", NULL, oclDeviceWindow.IsOpen(),
boost::ends_with(currentRenderEngineType, "OCL")))
oclDeviceWindow.Toggle();
if (ImGui::MenuItem("Light Strategy editor", NULL, lightStrategyWindow.IsOpen()))
lightStrategyWindow.Toggle();
if (ImGui::MenuItem("Accelerator editor", NULL, acceleratorWindow.IsOpen()))
acceleratorWindow.Toggle();
if (ImGui::MenuItem("Epsilon editor", NULL, epsilonWindow.IsOpen()))
epsilonWindow.Toggle();
ImGui::Separator();
if (ImGui::MenuItem("Film Radiance Groups editor", NULL, filmRadianceGroupsWindow.IsOpen()))
filmRadianceGroupsWindow.Toggle();
if (ImGui::MenuItem("Film Outputs editor", NULL, filmOutputsWindow.IsOpen()))
filmOutputsWindow.Toggle();
if (ImGui::MenuItem("Film Channels window", NULL, filmChannelsWindow.IsOpen()))
filmChannelsWindow.Toggle();
ImGui::Separator();
if (session && ImGui::MenuItem("Statistics", "j", statsWindow.IsOpen()))
statsWindow.Toggle();
}
if (ImGui::MenuItem("Log console", NULL, logWindow.IsOpen()))
logWindow.Toggle();
if (ImGui::MenuItem("Help", NULL, helpWindow.IsOpen()))
helpWindow.Toggle();
}
//------------------------------------------------------------------------------
// MainMenuBar
//------------------------------------------------------------------------------
void LuxCoreApp::MainMenuBar() {
if (ImGui::BeginMainMenuBar()) {
if (ImGui::BeginMenu("Rendering")) {
MenuRendering();
ImGui::EndMenu();
}
if (session) {
const string currentEngineType = config->ToProperties().Get("renderengine.type").Get<string>();
if (ImGui::BeginMenu("Engine")) {
MenuEngine();
ImGui::EndMenu();
}
if ((!boost::starts_with(currentEngineType, "TILE")) &&
(!boost::starts_with(currentEngineType, "RT")) &&
ImGui::BeginMenu("Sampler")) {
MenuSampler();
ImGui::EndMenu();
}
if (boost::starts_with(currentEngineType, "TILE") && ImGui::BeginMenu("Tiles")) {
MenuTiles();
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Film")) {
MenuFilm();
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Image")) {
MenuImagePipeline();
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Screen")) {
MenuScreen();
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Tool")) {
MenuTool();
ImGui::EndMenu();
}
}
if (ImGui::BeginMenu("Window")) {
MenuWindow();
ImGui::EndMenu();
}
menuBarHeight = ImGui::GetWindowHeight();
ImGui::EndMainMenuBar();
}
}
| 20,490 | 7,094 |
#include "stdafx.h"
#pragma hdrstop
#include "ParticleEffect.h"
#ifndef _EDITOR
#include <xmmintrin.h>
#include "../../xrCPU_Pipe/ttapi.h"
#pragma comment(lib,"xrCPU_Pipe.lib")
#endif
using namespace PAPI;
using namespace PS;
const u32 PS::uDT_STEP = 33;
const float PS::fDT_STEP = float(uDT_STEP)/1000.f;
static void ApplyTexgen( const Fmatrix &mVP )
{
Fmatrix mTexgen;
#if defined(USE_DX10) || defined(USE_DX11)
Fmatrix mTexelAdjust =
{
0.5f, 0.0f, 0.0f, 0.0f,
0.0f, -0.5f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, 0.0f, 1.0f
};
#else // USE_DX10
float _w = float(RDEVICE.dwWidth);
float _h = float(RDEVICE.dwHeight);
float o_w = (.5f / _w);
float o_h = (.5f / _h);
Fmatrix mTexelAdjust =
{
0.5f, 0.0f, 0.0f, 0.0f,
0.0f, -0.5f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
0.5f + o_w, 0.5f + o_h, 0.0f, 1.0f
};
#endif // USE_DX10
mTexgen.mul(mTexelAdjust,mVP);
RCache.set_c( "mVPTexgen", mTexgen );
}
void PS::OnEffectParticleBirth(void* owner, u32 , PAPI::Particle& m, u32 )
{
CParticleEffect* PE = static_cast<CParticleEffect*>(owner); VERIFY(PE);
CPEDef* PED = PE->GetDefinition();
if (PED){
if (PED->m_Flags.is(CPEDef::dfRandomFrame))
m.frame = (u16)iFloor(Random.randI(PED->m_Frame.m_iFrameCount)*255.f);
if (PED->m_Flags.is(CPEDef::dfAnimated)&&PED->m_Flags.is(CPEDef::dfRandomPlayback)&&Random.randI(2))
m.flags.set(Particle::ANIMATE_CCW,TRUE);
}
}
void PS::OnEffectParticleDead(void* , u32 , PAPI::Particle& , u32 )
{
// CPEDef* PE = static_cast<CPEDef*>(owner);
}
//------------------------------------------------------------------------------
// class CParticleEffect
//------------------------------------------------------------------------------
CParticleEffect::CParticleEffect()
{
m_HandleEffect = ParticleManager()->CreateEffect(1); VERIFY(m_HandleEffect>=0);
m_HandleActionList = ParticleManager()->CreateActionList(); VERIFY(m_HandleActionList>=0);
m_RT_Flags.zero ();
m_Def = 0;
m_fElapsedLimit = 0.f;
m_MemDT = 0;
m_InitialPosition.set (0,0,0);
m_DestroyCallback = 0;
m_CollisionCallback = 0;
m_XFORM.identity ();
}
CParticleEffect::~CParticleEffect()
{
// Log ("--- destroy PE");
OnDeviceDestroy ();
ParticleManager()->DestroyEffect (m_HandleEffect);
ParticleManager()->DestroyActionList (m_HandleActionList);
}
void CParticleEffect::Play()
{
m_RT_Flags.set (flRT_DefferedStop,FALSE);
m_RT_Flags.set (flRT_Playing,TRUE);
ParticleManager()->PlayEffect(m_HandleEffect,m_HandleActionList);
}
void CParticleEffect::Stop(BOOL bDefferedStop)
{
ParticleManager()->StopEffect(m_HandleEffect,m_HandleActionList,bDefferedStop);
if (bDefferedStop){
m_RT_Flags.set (flRT_DefferedStop,TRUE);
}else{
m_RT_Flags.set (flRT_Playing,FALSE);
}
}
void CParticleEffect::RefreshShader()
{
OnDeviceDestroy();
OnDeviceCreate();
}
void CParticleEffect::UpdateParent(const Fmatrix& m, const Fvector& velocity, BOOL bXFORM)
{
m_RT_Flags.set (flRT_XFORM, bXFORM);
if (bXFORM) m_XFORM.set (m);
else{
m_InitialPosition = m.c;
ParticleManager()->Transform(m_HandleActionList,m,velocity);
}
}
void CParticleEffect::OnFrame(u32 frame_dt)
{
if (m_Def && m_RT_Flags.is(flRT_Playing)){
m_MemDT += frame_dt;
int StepCount = 0;
if (m_MemDT>=uDT_STEP) {
// allow maximum of three steps (99ms) to avoid slowdown after loading
// it will really skip updates at less than 10fps, which is unplayable
StepCount = m_MemDT/uDT_STEP;
m_MemDT = m_MemDT%uDT_STEP;
clamp (StepCount,0,3);
}
for (;StepCount; StepCount--) {
if (m_Def->m_Flags.is(CPEDef::dfTimeLimit)){
if (!m_RT_Flags.is(flRT_DefferedStop)){
m_fElapsedLimit -= fDT_STEP;
if (m_fElapsedLimit<0.f){
m_fElapsedLimit = m_Def->m_fTimeLimit;
Stop (true);
break;
}
}
}
ParticleManager()->Update(m_HandleEffect,m_HandleActionList,fDT_STEP);
PAPI::Particle* particles;
u32 p_cnt;
ParticleManager()->GetParticles(m_HandleEffect,particles,p_cnt);
// our actions
if (m_Def->m_Flags.is(CPEDef::dfFramed|CPEDef::dfAnimated)) m_Def->ExecuteAnimate (particles,p_cnt,fDT_STEP);
if (m_Def->m_Flags.is(CPEDef::dfCollision)) m_Def->ExecuteCollision (particles,p_cnt,fDT_STEP,this,m_CollisionCallback);
//-move action
if (p_cnt)
{
vis.box.invalidate ();
float p_size = 0.f;
for(u32 i = 0; i < p_cnt; i++){
Particle &m = particles[i];
vis.box.modify((Fvector&)m.pos);
if (m.size.x>p_size) p_size = m.size.x;
if (m.size.y>p_size) p_size = m.size.y;
if (m.size.z>p_size) p_size = m.size.z;
}
vis.box.grow (p_size);
vis.box.getsphere (vis.sphere.P,vis.sphere.R);
}
if (m_RT_Flags.is(flRT_DefferedStop)&&(0==p_cnt)){
m_RT_Flags.set (flRT_Playing|flRT_DefferedStop,FALSE);
break;
}
}
} else {
vis.box.set (m_InitialPosition,m_InitialPosition);
vis.box.grow (EPS_L);
vis.box.getsphere (vis.sphere.P,vis.sphere.R);
}
}
BOOL CParticleEffect::Compile(CPEDef* def)
{
m_Def = def;
if (m_Def){
// refresh shader
RefreshShader ();
// append actions
IReader F (m_Def->m_Actions.pointer(),m_Def->m_Actions.size());
ParticleManager()->LoadActions (m_HandleActionList,F);
ParticleManager()->SetMaxParticles (m_HandleEffect,m_Def->m_MaxParticles);
ParticleManager()->SetCallback (m_HandleEffect,OnEffectParticleBirth,OnEffectParticleDead,this,0);
// time limit
if (m_Def->m_Flags.is(CPEDef::dfTimeLimit))
m_fElapsedLimit = m_Def->m_fTimeLimit;
}
if (def) shader = def->m_CachedShader;
return TRUE;
}
void CParticleEffect::SetBirthDeadCB(PAPI::OnBirthParticleCB bc, PAPI::OnDeadParticleCB dc, void* owner, u32 p)
{
ParticleManager()->SetCallback (m_HandleEffect,bc,dc,owner,p);
}
u32 CParticleEffect::ParticlesCount()
{
return ParticleManager()->GetParticlesCount(m_HandleEffect);
}
//------------------------------------------------------------------------------
// Render
//------------------------------------------------------------------------------
void CParticleEffect::Copy(dxRender_Visual* )
{
FATAL ("Can't duplicate particle system - NOT IMPLEMENTED");
}
void CParticleEffect::OnDeviceCreate()
{
if (m_Def){
if (m_Def->m_Flags.is(CPEDef::dfSprite)){
geom.create (FVF::F_LIT, RCache.Vertex.Buffer(), RCache.QuadIB);
if (m_Def) shader = m_Def->m_CachedShader;
}
}
}
void CParticleEffect::OnDeviceDestroy()
{
if (m_Def){
if (m_Def->m_Flags.is(CPEDef::dfSprite)){
geom.destroy ();
shader.destroy ();
}
}
}
#ifndef _EDITOR
//----------------------------------------------------
IC void FillSprite_fpu (FVF::LIT*& pv, const Fvector& T, const Fvector& R, const Fvector& pos, const Fvector2& lt, const Fvector2& rb, float r1, float r2, u32 clr, float angle)
{
float sa = _sin(angle);
float ca = _cos(angle);
Fvector Vr, Vt;
Vr.x = T.x*r1*sa+R.x*r1*ca;
Vr.y = T.y*r1*sa+R.y*r1*ca;
Vr.z = T.z*r1*sa+R.z*r1*ca;
Vt.x = T.x*r2*ca-R.x*r2*sa;
Vt.y = T.y*r2*ca-R.y*r2*sa;
Vt.z = T.z*r2*ca-R.z*r2*sa;
Fvector a,b,c,d;
a.sub (Vt,Vr);
b.add (Vt,Vr);
c.invert (a);
d.invert (b);
pv->set (d.x+pos.x,d.y+pos.y,d.z+pos.z, clr, lt.x,rb.y); pv++;
pv->set (a.x+pos.x,a.y+pos.y,a.z+pos.z, clr, lt.x,lt.y); pv++;
pv->set (c.x+pos.x,c.y+pos.y,c.z+pos.z, clr, rb.x,rb.y); pv++;
pv->set (b.x+pos.x,b.y+pos.y,b.z+pos.z, clr, rb.x,lt.y); pv++;
}
__forceinline void fsincos( const float angle , float &sine , float &cosine )
{ __asm {
fld DWORD PTR [angle]
fsincos
mov eax , DWORD PTR [cosine]
fstp DWORD PTR [eax]
mov eax , DWORD PTR [sine]
fstp DWORD PTR [eax]
} }
IC void FillSprite (FVF::LIT*& pv, const Fvector& T, const Fvector& R, const Fvector& pos, const Fvector2& lt, const Fvector2& rb, float r1, float r2, u32 clr, float sina , float cosa )
{
#ifdef _GPA_ENABLED
TAL_SCOPED_TASK_NAMED( "FillSprite()" );
#endif // _GPA_ENABLED
__m128 Vr, Vt, _T , _R , _pos , _zz , _sa , _ca , a , b , c , d;
_sa = _mm_set1_ps( sina );
_ca = _mm_set1_ps( cosa );
_T = _mm_load_ss( (float*) &T.x );
_T = _mm_loadh_pi( _T , (__m64*) &T.y );
_R = _mm_load_ss( (float*) &R.x );
_R = _mm_loadh_pi( _R , (__m64*) &R.y );
_pos = _mm_load_ss( (float*) &pos.x );
_pos = _mm_loadh_pi( _pos , (__m64*) &pos.y );
_zz = _mm_setzero_ps();
Vr = _mm_mul_ps( _mm_set1_ps( r1 ) , _mm_add_ps( _mm_mul_ps( _T , _sa ) , _mm_mul_ps( _R , _ca ) ) );
Vt = _mm_mul_ps( _mm_set1_ps( r2 ) , _mm_sub_ps( _mm_mul_ps( _T , _ca ) , _mm_mul_ps( _R , _sa ) ) );
a = _mm_sub_ps( Vt , Vr );
b = _mm_add_ps( Vt , Vr );
c = _mm_sub_ps( _zz , a );
d = _mm_sub_ps( _zz , b );
a = _mm_add_ps( a , _pos );
d = _mm_add_ps( d , _pos );
b = _mm_add_ps( b , _pos );
c = _mm_add_ps( c , _pos );
_mm_store_ss( (float*) &pv->p.x , d );
_mm_storeh_pi( (__m64*) &pv->p.y , d );
pv->color = clr;
pv->t.set( lt.x , rb.y );
pv++;
_mm_store_ss( (float*) &pv->p.x , a );
_mm_storeh_pi( (__m64*) &pv->p.y , a );
pv->color = clr;
pv->t.set( lt.x , lt.y );
pv++;
_mm_store_ss( (float*) &pv->p.x , c );
_mm_storeh_pi( (__m64*) &pv->p.y , c );
pv->color = clr;
pv->t.set( rb.x , rb.y );
pv++;
_mm_store_ss( (float*) &pv->p.x , b );
_mm_storeh_pi( (__m64*) &pv->p.y , b );
pv->color = clr;
pv->t.set( rb.x , lt.y );
pv++;
}
IC void FillSprite (FVF::LIT*& pv, const Fvector& pos, const Fvector& dir, const Fvector2& lt, const Fvector2& rb, float r1, float r2, u32 clr, float sina , float cosa )
{
#ifdef _GPA_ENABLED
TAL_SCOPED_TASK_NAMED( "FillSpriteTransform()" );
#endif // _GPA_ENABLED
const Fvector& T = dir;
Fvector R;
// R.crossproduct(T,RDEVICE.vCameraDirection).normalize_safe();
__m128 _t , _t1 , _t2 , _r , _r1 , _r2 ;
// crossproduct
_t = _mm_load_ss( (float*) &T.x );
_t = _mm_loadh_pi( _t , (__m64*) &T.y );
_r = _mm_load_ss( (float*) &RDEVICE.vCameraDirection.x );
_r = _mm_loadh_pi( _r , (__m64*) &RDEVICE.vCameraDirection.y );
_t1 = _mm_shuffle_ps( _t , _t , _MM_SHUFFLE( 0 , 3 , 1 , 2 ) );
_t2 = _mm_shuffle_ps( _t , _t , _MM_SHUFFLE( 2 , 0 , 1 , 3 ) );
_r1 = _mm_shuffle_ps( _r , _r , _MM_SHUFFLE( 2 , 0 , 1 , 3 ) );
_r2 = _mm_shuffle_ps( _r , _r , _MM_SHUFFLE( 0 , 3 , 1 , 2 ) );
_t1 = _mm_mul_ps( _t1 , _r1 );
_t2 = _mm_mul_ps( _t2 , _r2 );
_t1 = _mm_sub_ps( _t1 , _t2 ); // z | y | 0 | x
// normalize_safe
_t2 = _mm_mul_ps( _t1 , _t1 ); // zz | yy | 00 | xx
_r1 = _mm_movehl_ps( _t2 , _t2 ); // zz | yy | zz | yy
_t2 = _mm_add_ss( _t2 , _r1 ); // zz | yy | 00 | xx + yy
_r1 = _mm_shuffle_ps( _r1 , _r1 , _MM_SHUFFLE( 1 , 1 , 1 , 1 ) ); // zz | zz | zz | zz
_t2 = _mm_add_ss( _t2 , _r1 ); // zz | yy | 00 | xx + yy + zz
_r1 = _mm_set_ss( std::numeric_limits<float>::min() );
if ( _mm_comigt_ss( _t2 , _r1 ) ) {
_t2 = _mm_rsqrt_ss( _t2 );
_t2 = _mm_shuffle_ps( _t2 , _t2 , _MM_SHUFFLE( 0 , 0 , 0 , 0 ) );
_t1 = _mm_mul_ps( _t1 , _t2 );
}
_mm_store_ss( (float*) &R.x , _t1 );
_mm_storeh_pi( (__m64*) &R.y , _t1 );
FillSprite( pv , T , R , pos , lt , rb , r1 , r2 , clr , sina , cosa );
}
extern ENGINE_API float psHUD_FOV;
struct PRS_PARAMS {
FVF::LIT* pv;
u32 p_from;
u32 p_to;
PAPI::Particle* particles;
CParticleEffect* pPE;
};
__forceinline void magnitude_sse( Fvector &vec , float &res )
{
__m128 tv,tu;
tv = _mm_load_ss( (float*) &vec.x ); // tv = 0 | 0 | 0 | x
tv = _mm_loadh_pi( tv , (__m64*) &vec.y ); // tv = z | y | 0 | x
tv = _mm_mul_ps( tv , tv ); // tv = zz | yy | 0 | xx
tu = _mm_movehl_ps( tv , tv ); // tu = zz | yy | zz | yy
tv = _mm_add_ss( tv , tu ); // tv = zz | yy | 0 | xx + yy
tu = _mm_shuffle_ps( tu , tu , _MM_SHUFFLE( 1 , 1 , 1 , 1 ) ); // tu = zz | zz | zz | zz
tv = _mm_add_ss( tv , tu ); // tv = zz | yy | 0 | xx + yy + zz
tv = _mm_sqrt_ss( tv ); // tv = zz | yy | 0 | sqrt( xx + yy + zz )
_mm_store_ss( (float*) &res , tv );
}
void ParticleRenderStream( LPVOID lpvParams )
{
#ifdef _GPA_ENABLED
TAL_SCOPED_TASK_NAMED( "ParticleRenderStream()" );
TAL_ID rtID = TAL_MakeID( 1 , Core.dwFrame , 0);
TAL_AddRelationThis(TAL_RELATION_IS_CHILD_OF, rtID);
#endif // _GPA_ENABLED
float sina = 0.0f , cosa = 0.0f;
DWORD angle = 0xFFFFFFFF;
PRS_PARAMS* pParams = (PRS_PARAMS *) lpvParams;
FVF::LIT* pv = pParams->pv;
u32 p_from = pParams->p_from;
u32 p_to = pParams->p_to;
PAPI::Particle* particles = pParams->particles;
CParticleEffect &pPE = *pParams->pPE;
for(u32 i = p_from; i < p_to; i++){
PAPI::Particle &m = particles[i];
Fvector2 lt,rb;
lt.set (0.f,0.f);
rb.set (1.f,1.f);
_mm_prefetch( (char*) &particles[i + 1] , _MM_HINT_NTA );
if ( angle != *((DWORD*)&m.rot.x) ) {
angle = *((DWORD*)&m.rot.x);
__asm {
fld DWORD PTR [angle]
fsincos
fstp DWORD PTR [cosa]
fstp DWORD PTR [sina]
}
}
_mm_prefetch( 64 + (char*) &particles[i + 1] , _MM_HINT_NTA );
if (pPE.m_Def->m_Flags.is(CPEDef::dfFramed))
pPE.m_Def->m_Frame.CalculateTC(iFloor(float(m.frame)/255.f),lt,rb);
float r_x = m.size.x*0.5f;
float r_y = m.size.y*0.5f;
float speed;
BOOL speed_calculated = FALSE;
if (pPE.m_Def->m_Flags.is(CPEDef::dfVelocityScale)){
magnitude_sse( m.vel , speed );
speed_calculated = TRUE;
r_x += speed*pPE.m_Def->m_VelocityScale.x;
r_y += speed*pPE.m_Def->m_VelocityScale.y;
}
if (pPE.m_Def->m_Flags.is(CPEDef::dfAlignToPath)){
if ( ! speed_calculated )
magnitude_sse( m.vel , speed );
if ((speed<EPS_S)&&pPE.m_Def->m_Flags.is(CPEDef::dfWorldAlign)){
Fmatrix M;
M.setXYZ (pPE.m_Def->m_APDefaultRotation);
if (pPE.m_RT_Flags.is(CParticleEffect::flRT_XFORM)){
Fvector p;
pPE.m_XFORM.transform_tiny(p,m.pos);
M.mulA_43 (pPE.m_XFORM);
FillSprite (pv,M.k,M.i,p,lt,rb,r_x,r_y,m.color,sina,cosa);
}else{
FillSprite (pv,M.k,M.i,m.pos,lt,rb,r_x,r_y,m.color,sina,cosa);
}
}else if ((speed>=EPS_S)&&pPE.m_Def->m_Flags.is(CPEDef::dfFaceAlign)){
Fmatrix M; M.identity();
M.k.div (m.vel,speed);
M.j.set (0,1,0); if (_abs(M.j.dotproduct(M.k))>.99f) M.j.set(0,0,1);
M.i.crossproduct (M.j,M.k); M.i.normalize ();
M.j.crossproduct (M.k,M.i); M.j.normalize ();
if (pPE.m_RT_Flags.is(CParticleEffect::flRT_XFORM)){
Fvector p;
pPE.m_XFORM.transform_tiny(p,m.pos);
M.mulA_43 (pPE.m_XFORM);
FillSprite (pv,M.j,M.i,p,lt,rb,r_x,r_y,m.color,sina,cosa);
}else{
FillSprite (pv,M.j,M.i,m.pos,lt,rb,r_x,r_y,m.color,sina,cosa);
}
}else{
Fvector dir;
if (speed>=EPS_S) dir.div (m.vel,speed);
else dir.setHP(-pPE.m_Def->m_APDefaultRotation.y,-pPE.m_Def->m_APDefaultRotation.x);
if (pPE.m_RT_Flags.is(CParticleEffect::flRT_XFORM)){
Fvector p,d;
pPE.m_XFORM.transform_tiny (p,m.pos);
pPE.m_XFORM.transform_dir (d,dir);
FillSprite (pv,p,d,lt,rb,r_x,r_y,m.color,sina,cosa);
}else{
FillSprite (pv,m.pos,dir,lt,rb,r_x,r_y,m.color,sina,cosa);
}
}
}else{
if (pPE.m_RT_Flags.is(CParticleEffect::flRT_XFORM)){
Fvector p;
pPE.m_XFORM.transform_tiny (p,m.pos);
FillSprite (pv,RDEVICE.vCameraTop,RDEVICE.vCameraRight,p,lt,rb,r_x,r_y,m.color,sina,cosa);
}else{
FillSprite (pv,RDEVICE.vCameraTop,RDEVICE.vCameraRight,m.pos,lt,rb,r_x,r_y,m.color,sina,cosa);
}
}
}
}
void CParticleEffect::Render(float )
{
#ifdef _GPA_ENABLED
TAL_SCOPED_TASK_NAMED( "CParticleEffect::Render()" );
#endif // _GPA_ENABLED
u32 dwOffset,dwCount;
// Get a pointer to the particles in gp memory
PAPI::Particle* particles;
u32 p_cnt;
ParticleManager()->GetParticles(m_HandleEffect,particles,p_cnt);
if(p_cnt>0){
if (m_Def&&m_Def->m_Flags.is(CPEDef::dfSprite)){
FVF::LIT* pv_start = (FVF::LIT*)RCache.Vertex.Lock(p_cnt*4*4,geom->vb_stride,dwOffset);
FVF::LIT* pv = pv_start;
u32 nWorkers = ttapi_GetWorkersCount();
if ( p_cnt < nWorkers * 20 )
nWorkers = 1;
PRS_PARAMS* prsParams = (PRS_PARAMS*) _alloca( sizeof(PRS_PARAMS) * nWorkers );
// Give ~1% more for the last worker
// to minimize wait in final spin
u32 nSlice = p_cnt / 128;
u32 nStep = ( ( p_cnt - nSlice ) / nWorkers );
//u32 nStep = ( p_cnt / nWorkers );
//Msg( "Rnd: %u" , nStep );
for ( u32 i = 0 ; i < nWorkers ; ++i ) {
prsParams[i].pv = pv + i*nStep*4;
prsParams[i].p_from = i * nStep;
prsParams[i].p_to = ( i == ( nWorkers - 1 ) ) ? p_cnt : ( prsParams[i].p_from + nStep );
prsParams[i].particles = particles;
prsParams[i].pPE = this;
ttapi_AddWorker( ParticleRenderStream , (LPVOID) &prsParams[i] );
}
ttapi_RunAllWorkers();
dwCount = p_cnt<<2;
RCache.Vertex.Unlock(dwCount,geom->vb_stride);
if (dwCount)
{
#ifndef _EDITOR
Fmatrix Pold = Device.mProject;
Fmatrix FTold = Device.mFullTransform;
if(GetHudMode())
{
RDEVICE.mProject.build_projection( deg2rad(psHUD_FOV*Device.fFOV),
Device.fASPECT,
VIEWPORT_NEAR,
g_pGamePersistent->Environment().CurrentEnv->far_plane);
Device.mFullTransform.mul (Device.mProject, Device.mView);
RCache.set_xform_project (Device.mProject);
RImplementation.rmNear ();
ApplyTexgen(Device.mFullTransform);
}
#endif
RCache.set_xform_world (Fidentity);
RCache.set_Geometry (geom);
RCache.set_CullMode (m_Def->m_Flags.is(CPEDef::dfCulling)?(m_Def->m_Flags.is(CPEDef::dfCullCCW)?CULL_CCW:CULL_CW):CULL_NONE);
RCache.Render (D3DPT_TRIANGLELIST,dwOffset,0,dwCount,0,dwCount/2);
RCache.set_CullMode (CULL_CCW );
#ifndef _EDITOR
if(GetHudMode())
{
RImplementation.rmNormal ();
Device.mProject = Pold;
Device.mFullTransform = FTold;
RCache.set_xform_project (Device.mProject);
ApplyTexgen(Device.mFullTransform);
}
#endif
}
}
}
}
#else
//----------------------------------------------------
IC void FillSprite (FVF::LIT*& pv, const Fvector& T, const Fvector& R, const Fvector& pos, const Fvector2& lt, const Fvector2& rb, float r1, float r2, u32 clr, float angle)
{
float sa = _sin(angle);
float ca = _cos(angle);
Fvector Vr, Vt;
Vr.x = T.x*r1*sa+R.x*r1*ca;
Vr.y = T.y*r1*sa+R.y*r1*ca;
Vr.z = T.z*r1*sa+R.z*r1*ca;
Vt.x = T.x*r2*ca-R.x*r2*sa;
Vt.y = T.y*r2*ca-R.y*r2*sa;
Vt.z = T.z*r2*ca-R.z*r2*sa;
Fvector a,b,c,d;
a.sub (Vt,Vr);
b.add (Vt,Vr);
c.invert (a);
d.invert (b);
pv->set (d.x+pos.x,d.y+pos.y,d.z+pos.z, clr, lt.x,rb.y); pv++;
pv->set (a.x+pos.x,a.y+pos.y,a.z+pos.z, clr, lt.x,lt.y); pv++;
pv->set (c.x+pos.x,c.y+pos.y,c.z+pos.z, clr, rb.x,rb.y); pv++;
pv->set (b.x+pos.x,b.y+pos.y,b.z+pos.z, clr, rb.x,lt.y); pv++;
}
IC void FillSprite (FVF::LIT*& pv, const Fvector& pos, const Fvector& dir, const Fvector2& lt, const Fvector2& rb, float r1, float r2, u32 clr, float angle)
{
float sa = _sin(angle);
float ca = _cos(angle);
const Fvector& T = dir;
Fvector R; R.crossproduct(T,RDEVICE.vCameraDirection).normalize_safe();
Fvector Vr, Vt;
Vr.x = T.x*r1*sa+R.x*r1*ca;
Vr.y = T.y*r1*sa+R.y*r1*ca;
Vr.z = T.z*r1*sa+R.z*r1*ca;
Vt.x = T.x*r2*ca-R.x*r2*sa;
Vt.y = T.y*r2*ca-R.y*r2*sa;
Vt.z = T.z*r2*ca-R.z*r2*sa;
Fvector a,b,c,d;
a.sub (Vt,Vr);
b.add (Vt,Vr);
c.invert (a);
d.invert (b);
pv->set (d.x+pos.x,d.y+pos.y,d.z+pos.z, clr, lt.x,rb.y); pv++;
pv->set (a.x+pos.x,a.y+pos.y,a.z+pos.z, clr, lt.x,lt.y); pv++;
pv->set (c.x+pos.x,c.y+pos.y,c.z+pos.z, clr, rb.x,rb.y); pv++;
pv->set (b.x+pos.x,b.y+pos.y,b.z+pos.z, clr, rb.x,lt.y); pv++;
}
extern ENGINE_API float psHUD_FOV;
void CParticleEffect::Render(float )
{
u32 dwOffset,dwCount;
// Get a pointer to the particles in gp memory
PAPI::Particle* particles;
u32 p_cnt;
ParticleManager()->GetParticles(m_HandleEffect,particles,p_cnt);
if(p_cnt>0){
if (m_Def&&m_Def->m_Flags.is(CPEDef::dfSprite)){
FVF::LIT* pv_start = (FVF::LIT*)RCache.Vertex.Lock(p_cnt*4*4,geom->vb_stride,dwOffset);
FVF::LIT* pv = pv_start;
for(u32 i = 0; i < p_cnt; i++){
PAPI::Particle &m = particles[i];
Fvector2 lt,rb;
lt.set (0.f,0.f);
rb.set (1.f,1.f);
if (m_Def->m_Flags.is(CPEDef::dfFramed)) m_Def->m_Frame.CalculateTC(iFloor(float(m.frame)/255.f),lt,rb);
float r_x = m.size.x*0.5f;
float r_y = m.size.y*0.5f;
if (m_Def->m_Flags.is(CPEDef::dfVelocityScale)){
float speed = m.vel.magnitude();
r_x += speed*m_Def->m_VelocityScale.x;
r_y += speed*m_Def->m_VelocityScale.y;
}
if (m_Def->m_Flags.is(CPEDef::dfAlignToPath)){
float speed = m.vel.magnitude();
if ((speed<EPS_S)&&m_Def->m_Flags.is(CPEDef::dfWorldAlign)){
Fmatrix M;
M.setXYZ (m_Def->m_APDefaultRotation);
if (m_RT_Flags.is(flRT_XFORM)){
Fvector p;
m_XFORM.transform_tiny(p,m.pos);
M.mulA_43 (m_XFORM);
FillSprite (pv,M.k,M.i,p,lt,rb,r_x,r_y,m.color,m.rot.x);
}else{
FillSprite (pv,M.k,M.i,m.pos,lt,rb,r_x,r_y,m.color,m.rot.x);
}
}else if ((speed>=EPS_S)&&m_Def->m_Flags.is(CPEDef::dfFaceAlign)){
Fmatrix M; M.identity();
M.k.div (m.vel,speed);
M.j.set (0,1,0); if (_abs(M.j.dotproduct(M.k))>.99f) M.j.set(0,0,1);
M.i.crossproduct (M.j,M.k); M.i.normalize ();
M.j.crossproduct (M.k,M.i); M.j.normalize ();
if (m_RT_Flags.is(flRT_XFORM)){
Fvector p;
m_XFORM.transform_tiny(p,m.pos);
M.mulA_43 (m_XFORM);
FillSprite (pv,M.j,M.i,p,lt,rb,r_x,r_y,m.color,m.rot.x);
}else{
FillSprite (pv,M.j,M.i,m.pos,lt,rb,r_x,r_y,m.color,m.rot.x);
}
}else{
Fvector dir;
if (speed>=EPS_S) dir.div (m.vel,speed);
else dir.setHP(-m_Def->m_APDefaultRotation.y,-m_Def->m_APDefaultRotation.x);
if (m_RT_Flags.is(flRT_XFORM)){
Fvector p,d;
m_XFORM.transform_tiny (p,m.pos);
m_XFORM.transform_dir (d,dir);
FillSprite (pv,p,d,lt,rb,r_x,r_y,m.color,m.rot.x);
}else{
FillSprite (pv,m.pos,dir,lt,rb,r_x,r_y,m.color,m.rot.x);
}
}
}else{
if (m_RT_Flags.is(flRT_XFORM)){
Fvector p;
m_XFORM.transform_tiny (p,m.pos);
FillSprite (pv,RDEVICE.vCameraTop,RDEVICE.vCameraRight,p,lt,rb,r_x,r_y,m.color,m.rot.x);
}else{
FillSprite (pv,RDEVICE.vCameraTop,RDEVICE.vCameraRight,m.pos,lt,rb,r_x,r_y,m.color,m.rot.x);
}
}
}
dwCount = u32(pv-pv_start);
RCache.Vertex.Unlock(dwCount,geom->vb_stride);
if (dwCount)
{
#ifndef _EDITOR
Fmatrix Pold = Device.mProject;
Fmatrix FTold = Device.mFullTransform;
if(GetHudMode())
{
RDEVICE.mProject.build_projection( deg2rad(psHUD_FOV*Device.fFOV),
Device.fASPECT,
VIEWPORT_NEAR,
g_pGamePersistent->Environment().CurrentEnv->far_plane);
Device.mFullTransform.mul (Device.mProject, Device.mView);
RCache.set_xform_project (Device.mProject);
RImplementation.rmNear ();
ApplyTexgen(Device.mFullTransform);
}
#endif
RCache.set_xform_world (Fidentity);
RCache.set_Geometry (geom);
RCache.set_CullMode (m_Def->m_Flags.is(CPEDef::dfCulling)?(m_Def->m_Flags.is(CPEDef::dfCullCCW)?CULL_CCW:CULL_CW):CULL_NONE);
RCache.Render (D3DPT_TRIANGLELIST,dwOffset,0,dwCount,0,dwCount/2);
RCache.set_CullMode (CULL_CCW );
#ifndef _EDITOR
if(GetHudMode())
{
RImplementation.rmNormal ();
Device.mProject = Pold;
Device.mFullTransform = FTold;
RCache.set_xform_project (Device.mProject);
ApplyTexgen(Device.mFullTransform);
}
#endif
}
}
}
}
#endif // _EDITOR
| 26,189 | 13,214 |
#include <iostream>
#include "Direction.hpp"
#include <string>
#include <stdexcept>
#include <map>
using namespace std;
using namespace ariel;
namespace ariel {
class Notebook {
map<int , map <int , string> > notebook ;
public :
Notebook();
void write(int const & page, int const & row, int const & col, Direction dir, string const & str);
void erase(int page, int row, int col, Direction dir, int length);
string read(int page, int row, int col, Direction dir, int length);
void show(int page);
};
};
| 572 | 177 |
/*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include "StdAfx.h"
#include <Components/BlastFamilyComponentNotificationBusHandler.h>
namespace Blast
{
BlastFamilyComponentNotificationBusHandler::BlastFamilyComponentNotificationBusHandler()
{
m_events.resize(static_cast<int>(Function::Count));
SetEvent(&BlastFamilyComponentNotificationBusHandler::OnActorCreatedDummy, "On Actor Created");
SetEvent(&BlastFamilyComponentNotificationBusHandler::OnActorDestroyedDummy, "On Actor Destroyed");
}
void BlastFamilyComponentNotificationBusHandler::Reflect(AZ::ReflectContext* context)
{
if (AZ::BehaviorContext* behaviorContext = azrtti_cast<AZ::BehaviorContext*>(context))
{
behaviorContext->EBus<BlastFamilyComponentNotificationBus>("BlastFamilyComponentNotificationBus")
->Attribute(AZ::Script::Attributes::Module, "destruction")
->Attribute(AZ::Script::Attributes::Category, "Blast")
->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common)
->Handler<BlastFamilyComponentNotificationBusHandler>();
}
}
void BlastFamilyComponentNotificationBusHandler::Disconnect()
{
BusDisconnect();
}
bool BlastFamilyComponentNotificationBusHandler::Connect(AZ::BehaviorValueParameter* id)
{
return AZ::Internal::EBusConnector<BlastFamilyComponentNotificationBusHandler>::Connect(this, id);
}
bool BlastFamilyComponentNotificationBusHandler::IsConnected()
{
return AZ::Internal::EBusConnector<BlastFamilyComponentNotificationBusHandler>::IsConnected(this);
}
bool BlastFamilyComponentNotificationBusHandler::IsConnectedId(AZ::BehaviorValueParameter* id)
{
return AZ::Internal::EBusConnector<BlastFamilyComponentNotificationBusHandler>::IsConnectedId(this, id);
}
int BlastFamilyComponentNotificationBusHandler::GetFunctionIndex(const char* functionName) const
{
if (strcmp(functionName, "On Actor Created") == 0) {
return static_cast<int>(Function::OnActorCreated);
}
if (strcmp(functionName, "On Actor Destroyed") == 0) {
return static_cast<int>(Function::OnActorDestroyed);
}
return -1;
}
void BlastFamilyComponentNotificationBusHandler::OnActorCreatedDummy([[maybe_unused]] BlastActorData blastActor)
{
// This is never invoked, and only used for type deduction when calling SetEvent
}
void BlastFamilyComponentNotificationBusHandler::OnActorDestroyedDummy([[maybe_unused]] BlastActorData blastActor)
{
// This is never invoked, and only used for type deduction when calling SetEvent
}
void BlastFamilyComponentNotificationBusHandler::OnActorCreated(const BlastActor& blastActor)
{
Call(static_cast<int>(Function::OnActorCreated), BlastActorData(blastActor));
}
void BlastFamilyComponentNotificationBusHandler::OnActorDestroyed(const BlastActor& blastActor)
{
Call(static_cast<int>(Function::OnActorDestroyed), BlastActorData(blastActor));
}
} // namespace Blast
| 3,349 | 937 |
#include "creditsview.h"
#include "gamecontext.h"
CreditsView::CreditsView(GameContext* context) : View(context)
{
}
std::ostream & CreditsView::display()
{
return std::cout
<< "This game was created by Tobi van Bronswijk and Rick van Berlo."
<< std::endl
<< "Thanks for playing!"
<< std::endl;
}
bool CreditsView::handle_input(char c)
{
back();
return true;
}
| 375 | 140 |
// Copyright (C) 2014-2017 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 <cc/command_interpreter.h>
#include <dhcpsrv/testutils/config_result_check.h>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/constants.hpp>
#include <boost/algorithm/string/split.hpp>
#include <string>
namespace isc {
namespace dhcp {
namespace test {
using namespace isc;
using namespace isc::data;
bool errorContainsPosition(ElementPtr error_element,
const std::string& file_name) {
if (error_element->contains(isc::config::CONTROL_RESULT)) {
ElementPtr result = error_element->get(isc::config::CONTROL_RESULT);
ElementPtr text = error_element->get(isc::config::CONTROL_TEXT);
if (!result || (result->getType() != Element::integer) || !text
|| (text->getType() != Element::string)) {
return (false);
}
// Get the error message in the textual format.
std::string error_string = text->stringValue();
// The position of the data element causing an error has the following
// format: <filename>:<linenum>:<pos>. The <filename> has been specified
// by a caller, so let's first check if this file name is present in the
// error message.
size_t pos = error_string.find(file_name);
// If the file name is present, check that it is followed by the line
// number and position within the line.
if (pos != std::string::npos) {
// Split the string starting at the beginning of the <filename>. It
// should return a vector of strings.
std::string sub = error_string.substr(pos);
std::vector<std::string> split_pos;
boost::split(split_pos, sub, boost::is_any_of(":"),
boost::algorithm::token_compress_off);
// There should be at least three elements: <filename>, <linenum>
// and <pos>. There can be even more, because one error string may
// contain more positions of data elements for multiple
// configuration nesting levels. We want at least one position.
if ((split_pos.size() >= 3) && (split_pos[0] == file_name) &&
(!split_pos[1].empty()) && !(split_pos[2].empty())) {
// Make sure that the line number comprises only digits.
for (int i = 0; i < split_pos[1].size(); ++i) {
if (!isdigit(split_pos[1][i])) {
return (false);
}
}
// Go over digits of the position within the line.
int i = 0;
while (isdigit(split_pos[2][i])) {
++i;
}
// Make sure that there has been at least one digit and that the
// position is followed by the paren.
if ((i == 0) || (split_pos[2][i] != ')')) {
return (false);
}
// All checks passed.
return (true);
}
}
}
return (false);
}
}
}
}
| 3,385 | 930 |
#pragma once
#include "KEngine/Interfaces/ISystem.hpp"
namespace pf
{
/// <summary>
///
/// </summary>
class EventFeedbackSystem : public ke::ISystem
{
public:
};
} | 201 | 72 |
// COCOA class implementation file
//Id: ALIUtils.cc
//CAT: ALIUtils
//
// History: v1.0
// Pedro Arce
#include "Alignment/CocoaUtilities/interface/ALIUtils.h"
#include "Alignment/CocoaUtilities/interface/GlobalOptionMgr.h"
#include <cmath>
#include <cstdlib>
#include <iomanip>
ALIint ALIUtils::debug = -1;
ALIint ALIUtils::report = 1;
ALIdouble ALIUtils::_LengthValueDimensionFactor = 1.;
ALIdouble ALIUtils::_LengthSigmaDimensionFactor = 1.;
ALIdouble ALIUtils::_AngleValueDimensionFactor = 1.;
ALIdouble ALIUtils::_AngleSigmaDimensionFactor = 1.;
ALIdouble ALIUtils::_OutputLengthValueDimensionFactor = 1.;
ALIdouble ALIUtils::_OutputLengthSigmaDimensionFactor = 1.;
ALIdouble ALIUtils::_OutputAngleValueDimensionFactor = 1.;
ALIdouble ALIUtils::_OutputAngleSigmaDimensionFactor = 1.;
time_t ALIUtils::_time_now;
ALIdouble ALIUtils::deg = 0.017453293;
ALIbool ALIUtils::firstTime = false;
ALIdouble ALIUtils::maximum_deviation_derivative = 1.E-6;
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//@@ CHECKS THAT EVERY CHARACTER IN A STRING IS NUMBER, ELSE GIVES AN ERROR
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
int ALIUtils::IsNumber(const ALIstring& str) {
int isnum = 1;
int numE = 0;
for (ALIuint ii = 0; ii < str.length(); ii++) {
if (!isdigit(str[ii]) && str[ii] != '.' && str[ii] != '-' && str[ii] != '+') {
//--- check for E(xponential)
if (str[ii] == 'E' || str[ii] == 'e') {
if (numE != 0 || ii == str.length() - 1) {
isnum = 0;
break;
}
numE++;
} else {
isnum = 0;
break;
}
}
}
return isnum;
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//@@ Dump a Hep3DVector with the chosen precision
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
void ALIUtils::dump3v(const CLHEP::Hep3Vector& vec, const std::string& msg) {
// double phicyl = atan( vec.y()/vec.x() );
std::cout << msg << std::setprecision(8) << vec;
std::cout << std::endl;
// std::cout << " " << vec.theta()/deg << " " << vec.phi()/deg << " " << vec.perp() << " " << phicyl/deg << std::endl;
// setw(10);
// std::cout << msg << " x=" << std::setprecision(8) << vec.x() << " y=" << setprecision(8) <<vec.y() << " z=" << std::setprecision(8) << vec.z() << std::endl;
// std::setprecision(8);
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//@@
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
void ALIUtils::dumprm(const CLHEP::HepRotation& rm, const std::string& msg, std::ostream& out) {
out << msg << " xx=" << rm.xx() << " xy=" << rm.xy() << " xz=" << rm.xz() << std::endl;
out << msg << " yx=" << rm.yx() << " yy=" << rm.yy() << " yz=" << rm.yz() << std::endl;
out << msg << " zx=" << rm.zx() << " zy=" << rm.zy() << " zz=" << rm.zz() << std::endl;
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//@@ Set the dimension factor to convert input length values and errors to
//@@ the dimension of errors
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
void ALIUtils::SetLengthDimensionFactors() {
//---------------------------------------- if it doesn exist, GlobalOptions is 0
//---------- Calculate factors to convert to meters
GlobalOptionMgr* gomgr = GlobalOptionMgr::getInstance();
ALIint ad = ALIint(gomgr->getGlobalOption("length_value_dimension"));
_LengthValueDimensionFactor = CalculateLengthDimensionFactorFromInt(ad);
ad = ALIint(gomgr->GlobalOptions()[ALIstring("length_error_dimension")]);
_LengthSigmaDimensionFactor = CalculateLengthDimensionFactorFromInt(ad);
//---------- Change factor to convert to error dimensions
// _LengthValueDimensionFactor /= _LengthSigmaDimensionFactor;
//_LengthSigmaDimensionFactor = 1;
if (ALIUtils::debug >= 6)
std::cout << _LengthValueDimensionFactor << " Set Length DimensionFactors " << _LengthSigmaDimensionFactor
<< std::endl;
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//@@ Set the dimension factor to convert input angle values and errors to
//@@ the dimension of errors
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
void ALIUtils::SetAngleDimensionFactors() {
//--------------------- if it doesn exist, GlobalOptions is 0
//---------- Calculate factors to convert to radians
GlobalOptionMgr* gomgr = GlobalOptionMgr::getInstance();
ALIint ad = ALIint(gomgr->GlobalOptions()[ALIstring("angle_value_dimension")]);
_AngleValueDimensionFactor = CalculateAngleDimensionFactorFromInt(ad);
ad = ALIint(gomgr->GlobalOptions()[ALIstring("angle_error_dimension")]);
_AngleSigmaDimensionFactor = CalculateAngleDimensionFactorFromInt(ad);
//---------- Change factor to convert to error dimensions
// _AngleValueDimensionFactor /= _AngleSigmaDimensionFactor;
//_AngleSigmaDimensionFactor = 1;
if (ALIUtils::debug >= 6)
std::cout << _AngleValueDimensionFactor << "Set Angle DimensionFactors" << _AngleSigmaDimensionFactor << std::endl;
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//@@ Set the dimension factor to convert input length values and errors to
//@@ the dimension of errors
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
void ALIUtils::SetOutputLengthDimensionFactors() {
//---------------------------------------- if it doesn exist, GlobalOptions is 0
//---------- Calculate factors to convert to meters
GlobalOptionMgr* gomgr = GlobalOptionMgr::getInstance();
ALIint ad = ALIint(gomgr->GlobalOptions()[ALIstring("output_length_value_dimension")]);
if (ad == 0)
ad = ALIint(gomgr->GlobalOptions()[ALIstring("length_value_dimension")]);
_OutputLengthValueDimensionFactor = CalculateLengthDimensionFactorFromInt(ad);
ad = ALIint(gomgr->GlobalOptions()[ALIstring("output_length_error_dimension")]);
if (ad == 0)
ad = ALIint(gomgr->GlobalOptions()[ALIstring("length_error_dimension")]);
_OutputLengthSigmaDimensionFactor = CalculateLengthDimensionFactorFromInt(ad);
//---------- Change factor to convert to error dimensions
// _LengthValueDimensionFactor /= _LengthSigmaDimensionFactor;
//_LengthSigmaDimensionFactor = 1;
if (ALIUtils::debug >= 6)
std::cout << _OutputLengthValueDimensionFactor << "Output Length Dimension Factors"
<< _OutputLengthSigmaDimensionFactor << std::endl;
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//@@ Set the dimension factor to convert input angle values and errors to
//@@ the dimension of errors
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
void ALIUtils::SetOutputAngleDimensionFactors() {
//--------------------- if it doesn exist, GlobalOptions is 0
//---------- Calculate factors to convert to radians
GlobalOptionMgr* gomgr = GlobalOptionMgr::getInstance();
ALIint ad = ALIint(gomgr->GlobalOptions()[ALIstring("output_angle_value_dimension")]);
if (ad == 0)
ad = ALIint(gomgr->GlobalOptions()[ALIstring("angle_value_dimension")]);
_OutputAngleValueDimensionFactor = CalculateAngleDimensionFactorFromInt(ad);
ad = ALIint(gomgr->GlobalOptions()[ALIstring("output_angle_error_dimension")]);
if (ad == 0)
ad = ALIint(gomgr->GlobalOptions()[ALIstring("angle_error_dimension")]);
_OutputAngleSigmaDimensionFactor = CalculateAngleDimensionFactorFromInt(ad);
//---------- Change factor to convert to error dimensions
// _AngleValueDimensionFactor /= _AngleSigmaDimensionFactor;
//_AngleSigmaDimensionFactor = 1;
if (ALIUtils::debug >= 9)
std::cout << _OutputAngleValueDimensionFactor << "Output Angle Dimension Factors"
<< _OutputAngleSigmaDimensionFactor << std::endl;
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//@@ Calculate dimension factor to convert any length values and errors to meters
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
ALIdouble ALIUtils::CalculateLengthDimensionFactorFromString(ALIstring dimstr) {
ALIdouble valsig = 1.;
ALIstring internalDim = "m";
if (internalDim == "m") {
if (dimstr == "m") {
valsig = 1.;
} else if (dimstr == "mm") {
valsig = 1.E-3;
} else if (dimstr == "mum") {
valsig = 1.E-6;
} else if (dimstr == "cm") {
valsig = 1.E-2;
} else {
std::cerr << "!!! UNKNOWN DIMENSION SCALING " << dimstr << std::endl
<< "VALUE MUST BE BETWEEN 0 AND 3 " << std::endl;
exit(1);
}
} else if (internalDim == "mm") {
if (dimstr == "m") {
valsig = 1.E3;
} else if (dimstr == "mm") {
valsig = 1.;
} else if (dimstr == "mum") {
valsig = 1.E-3;
} else if (dimstr == "cm") {
valsig = 1.E+1;
} else {
std::cerr << "!!! UNKNOWN DIMENSION SCALING: " << dimstr << std::endl
<< "VALUE MUST BE A LENGTH DIMENSION " << std::endl;
exit(1);
}
}
return valsig;
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//@@ Calculate dimension factor to convert any angle values and errors to radians
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
ALIdouble ALIUtils::CalculateAngleDimensionFactorFromString(ALIstring dimstr) {
ALIdouble valsig;
if (dimstr == "rad") {
valsig = 1.;
} else if (dimstr == "mrad") {
valsig = 1.E-3;
} else if (dimstr == "murad") {
valsig = 1.E-6;
} else if (dimstr == "deg") {
valsig = M_PI / 180.;
} else if (dimstr == "grad") {
valsig = M_PI / 200.;
} else {
std::cerr << "!!! UNKNOWN DIMENSION SCALING: " << dimstr << std::endl
<< "VALUE MUST BE AN ANGLE DIMENSION " << std::endl;
exit(1);
}
return valsig;
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//@@ Calculate dimension factor to convert any length values and errors to meters
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
ALIdouble ALIUtils::CalculateLengthDimensionFactorFromInt(ALIint ad) {
ALIdouble valsig;
switch (ad) {
case 0: //----- metres
valsig = CalculateLengthDimensionFactorFromString("m");
break;
case 1: //----- milimetres
valsig = CalculateLengthDimensionFactorFromString("mm");
break;
case 2: //----- micrometres
valsig = CalculateLengthDimensionFactorFromString("mum");
break;
case 3: //----- centimetres
valsig = CalculateLengthDimensionFactorFromString("cm");
break;
default:
std::cerr << "!!! UNKNOWN DIMENSION SCALING " << ad << std::endl << "VALUE MUST BE BETWEEN 0 AND 3 " << std::endl;
exit(1);
}
// use microradinas instead of radians
//- valsig *= 1000000.;
return valsig;
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//@@ Calculate dimension factor to convert any angle values and errors to radians
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
ALIdouble ALIUtils::CalculateAngleDimensionFactorFromInt(ALIint ad) {
ALIdouble valsig;
switch (ad) {
case 0: //----- radians
valsig = CalculateAngleDimensionFactorFromString("rad");
break;
case 1: //----- miliradians
valsig = CalculateAngleDimensionFactorFromString("mrad");
break;
case 2: //----- microradians
valsig = CalculateAngleDimensionFactorFromString("murad");
break;
case 3: //----- degrees
valsig = CalculateAngleDimensionFactorFromString("deg");
break;
case 4: //----- grads
valsig = CalculateAngleDimensionFactorFromString("grad");
break;
default:
std::cerr << "!!! UNKNOWN DIMENSION SCALING " << ad << std::endl << "VALUE MUST BE BETWEEN 0 AND 3 " << std::endl;
exit(1);
}
// use microradinas instead of radians
//- valsig *= 1000000.;
return valsig;
}
/*template<class T>
ALIuint FindItemInVector( const T* item, const std::vector<T*> std::vector )
{
}
*/
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void ALIUtils::dumpDimensions(std::ofstream& fout) {
fout << "DIMENSIONS: lengths = ";
ALIstring internalDim = "m";
if (_OutputLengthValueDimensionFactor == 1.) {
fout << "m";
} else if (_OutputLengthValueDimensionFactor == 1.E-3) {
fout << "mm";
} else if (_OutputLengthValueDimensionFactor == 1.E-6) {
fout << "mum";
} else if (_OutputLengthValueDimensionFactor == 1.E-2) {
fout << "cm";
} else {
std::cerr << " !! unknown OutputLengthValueDimensionFactor " << _OutputLengthValueDimensionFactor << std::endl;
exit(1);
}
fout << " +- ";
if (_OutputLengthSigmaDimensionFactor == 1.) {
fout << "m";
} else if (_OutputLengthSigmaDimensionFactor == 1.E-3) {
fout << "mm";
} else if (_OutputLengthSigmaDimensionFactor == 1.E-6) {
fout << "mum";
} else if (_OutputLengthSigmaDimensionFactor == 1.E-2) {
fout << "cm";
} else {
std::cerr << " !! unknown OutputLengthSigmaDimensionFactor " << _OutputLengthSigmaDimensionFactor << std::endl;
exit(1);
}
fout << " angles = ";
if (_OutputAngleValueDimensionFactor == 1.) {
fout << "rad";
} else if (_OutputAngleValueDimensionFactor == 1.E-3) {
fout << "mrad";
} else if (_OutputAngleValueDimensionFactor == 1.E-6) {
fout << "murad";
} else if (_OutputAngleValueDimensionFactor == M_PI / 180.) {
fout << "deg";
} else if (_OutputAngleValueDimensionFactor == M_PI / 200.) {
fout << "grad";
} else {
std::cerr << " !! unknown OutputAngleValueDimensionFactor " << _OutputAngleValueDimensionFactor << std::endl;
exit(1);
}
fout << " +- ";
if (_OutputAngleSigmaDimensionFactor == 1.) {
fout << "rad";
} else if (_OutputAngleSigmaDimensionFactor == 1.E-3) {
fout << "mrad";
} else if (_OutputAngleSigmaDimensionFactor == 1.E-6) {
fout << "murad";
} else if (_OutputAngleSigmaDimensionFactor == M_PI / 180.) {
fout << "deg";
} else if (_OutputAngleSigmaDimensionFactor == M_PI / 200.) {
fout << "grad";
} else {
std::cerr << " !! unknown OutputAngleSigmaDimensionFactor " << _OutputAngleSigmaDimensionFactor << std::endl;
exit(1);
}
fout << std::endl;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
double ALIUtils::getFloat(const ALIstring& str) {
//----------- first check that it is a number
if (!IsNumber(str)) {
std::cerr << "!!!! EXITING: trying to get the float from a string that is not a number " << str << std::endl;
exit(1);
}
return atof(str.c_str());
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
int ALIUtils::getInt(const ALIstring& str) {
//----------- first check that it is an integer
if (!IsNumber(str)) {
//----- Check that it is a number
std::cerr << "!!!! EXITING: trying to get the integer from a string that is not a number " << str << std::endl;
exit(1);
} else {
//----- Check that it is not a float, no decimal or E-n
bool isFloat = false;
int ch = str.find('.');
ALIuint ii = 0;
if (ch != -1) {
for (ii = ch + 1; ii < str.size(); ii++) {
if (str[ii] != '0')
isFloat = true;
}
}
ch = str.find('E');
if (ch != -1)
ch = str.find('e');
if (ch != -1) {
if (str[ch + 1] == '-')
isFloat = true;
}
if (isFloat) {
std::cerr << "!!!! EXITING: trying to get the integer from a string that is a float: " << str << std::endl;
std::cerr << ii << " ii " << ch << std::endl;
exit(1);
}
}
return int(atof(str.c_str()));
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
bool ALIUtils::getBool(const ALIstring& str) {
bool val;
//t str = upper( str );
//----------- first check that it is a not number
if (str == "ON" || str == "TRUE") {
val = true;
} else if (str == "OFF" || str == "FALSE") {
val = false;
} else {
std::cerr << "!!!! EXITING: trying to get the float from a string that is not 'ON'/'OFF'/'TRUE'/'FALSE' " << str
<< std::endl;
exit(1);
}
return val;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
ALIstring ALIUtils::subQuotes(const ALIstring& str) {
//---------- Take out leading and trailing '"'
if (str.find('"') != 0 || str.rfind('"') != str.length() - 1) {
std::cerr << "!!!EXITING trying to substract quotes from a word that has no quotes " << str << std::endl;
exit(1);
}
// str = str.strip(ALIstring::both, '\"');
//---------- Take out leading and trallling '"'
ALIstring strt = str.substr(1, str.size() - 2);
//- std::cout << " subquotes " << str << std::endl;
//---------- Look for leading spaces
while (strt[0] == ' ') {
strt = strt.substr(1, strt.size() - 1);
}
//---------- Look for trailing spaces
while (strt[strt.size() - 1] == ' ') {
strt = strt.substr(0, strt.size() - 1);
}
return strt;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void ALIUtils::dumpVS(const std::vector<ALIstring>& wl, const std::string& msg, std::ostream& outs) {
outs << msg << std::endl;
ALIuint siz = wl.size();
for (ALIuint ii = 0; ii < siz; ii++) {
outs << wl[ii] << " ";
/* ostream_iterator<ALIstring> os(outs," ");
copy(wl.begin(), wl.end(), os);*/
}
outs << std::endl;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
ALIdouble ALIUtils::getDimensionValue(const ALIstring& dim, const ALIstring& dimType) {
ALIdouble value;
if (dimType == "Length") {
if (dim == "mm") {
value = 1.E-3;
} else if (dim == "cm") {
value = 1.E-2;
} else if (dim == "m") {
value = 1.;
} else if (dim == "mum") {
value = 1.E-6;
} else if (dim == "dm") {
value = 1.E-1;
} else if (dim == "nm") {
value = 1.E-9;
} else {
std::cerr << "!!!!FATAL ERROR: ALIUtils::GetDimensionValue. " << dim
<< " is a dimension not supported for dimension type " << dimType << std::endl;
abort();
}
} else if (dimType == "Angle") {
if (dim == "rad") {
value = 1.;
} else if (dim == "mrad") {
value = 1.E-3;
} else if (dim == "murad") {
value = 1.E-6;
} else if (dim == "deg") {
value = M_PI / 180.;
} else if (dim == "grad") {
value = M_PI / 200.;
} else {
std::cerr << "!!!!FATAL ERROR: ALIUtils::GetDimensionValue. " << dim
<< " is a dimension not supported for dimension type " << dimType << std::endl;
abort();
}
} else {
std::cerr << "!!!!FATAL ERROR: ALIUtils::GetDimensionValue. " << dimType << " is a dimension type not supported "
<< std::endl;
abort();
}
return value;
}
/*
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
std::ostream& operator << (std::ostream& os, const CLHEP::HepRotation& rm)
{
return os << " xx=" << rm.xx() << " xy=" << rm.xy() << " xz=" << rm.xz() << std::endl
<< " yx=" << rm.yx() << " yy=" << rm.yy() << " yz=" << rm.yz() << std::endl
<< " zx=" << rm.zx() << " zy=" << rm.zy() << " zz=" << rm.zz() << std::endl;
}
*/
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
std::string ALIUtils::changeName(const std::string& oldName, const std::string& subsstr1, const std::string& subsstr2) {
std::string newName = oldName;
int il = oldName.find(subsstr1);
// std::cout << " il " << il << " oldname " << oldName << " " << subsstr1 << std::endl;
while (il >= 0) {
newName = newName.substr(0, il) + subsstr2 + newName.substr(il + subsstr1.length(), newName.length());
// std::cout << " dnewName " << newName << " " << newName.substr( 0, il ) << " " << subsstr2 << " " << newName.substr( il+subsstr1.length(), newName.length() ) << std::endl;
il = oldName.find(subsstr1, il + 1);
}
return newName;
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
std::vector<double> ALIUtils::getRotationAnglesFromMatrix(CLHEP::HepRotation& rmLocal,
double origAngleX,
double origAngleY,
double origAngleZ) {
double pii = acos(0.) * 2;
std::vector<double> newang(3);
double angleX = origAngleX;
double angleY = origAngleY;
double angleZ = origAngleZ;
if (ALIUtils::debug >= 4) {
std::cout << " angles as value entries: X= " << angleX << " Y= " << angleY << " Z " << angleZ << std::endl;
}
//- std::cout << name () << " vdbf " << angleX << " " << angleY << " " << angleZ << std::endl;
double rotzx = approxTo0(rmLocal.zx());
double rotzy = approxTo0(rmLocal.zy());
double rotzz = approxTo0(rmLocal.zz());
double rotyx = approxTo0(rmLocal.yx());
double rotxx = approxTo0(rmLocal.xx());
if (rotzy == 0. && rotzz == 0.) {
//check that entry is z angle
newang[0] = angleX;
//beware of aa <==> pii - aa
if (eq2ang(rmLocal.zx(), -1.)) {
double aa = asin(rmLocal.xy());
if (diff2pi(angleZ, -aa + newang[0]) < diff2pi(angleZ, -pii + aa + newang[0])) {
newang[2] = -aa + newang[0];
if (ALIUtils::debug >= 5)
std::cout << " newang[0] = -aa + newang[0] " << std::endl;
} else {
newang[2] = -pii + aa + newang[0];
if (ALIUtils::debug >= 5)
std::cout << " newang[0] = -pii + aa + newang[0] " << newang[0] << " " << aa << " " << newang[2] << std::endl;
}
} else {
double aa = asin(-rmLocal.xy());
if (diff2pi(angleZ, aa - newang[0]) < diff2pi(angleZ, pii - aa - newang[0])) {
newang[2] = aa - newang[0];
if (ALIUtils::debug >= 5)
std::cout << " newang[0] = aa - newang[2] " << std::endl;
} else {
newang[2] = pii - aa - newang[0];
if (ALIUtils::debug >= 5)
std::cout << " newang[0] = pii - aa - newang[2] " << newang[0] << " " << aa << " " << newang[2] << std::endl;
}
}
} else {
newang[0] = atan(rotzy / rotzz);
newang[2] = atan(rotyx / rotxx);
}
if (rotzx < -1.) {
//- std::cerr << " rotzx too small " << rotzx << " = " << rmLocal.zx() << " " << rotzx-rmLocal.zx() << std::endl;
rotzx = -1.;
} else if (rotzx > 1.) {
//- std::cerr << " rotzx too big " << rotzx << " = " << rmLocal.zx() << " " << rotzx-rmLocal.zx() << std::endl;
rotzx = 1.;
}
newang[1] = -asin(rotzx);
if (ALIUtils::debug >= 5)
std::cout << "First calculation of angles: " << std::endl
<< " newang[0] " << newang[0] << " " << rotzy << " " << rotzz << std::endl
<< " newang[1] " << newang[1] << " " << rotzx << std::endl
<< " newang[2] " << newang[2] << " " << rotyx << " " << rotxx << std::endl;
// newang[2] = acos( rmLocal.xx() / cos( newang[1] ) );
//----- CHECK if the angles are OK (there are several symmetries)
//--- Check if the predictions with the angles obtained match the values of the rotation matrix (they may differ for exampole by a sign or more in complicated formulas)
double rotnewxx = cos(newang[1]) * cos(newang[2]);
double rotnewzz = cos(newang[0]) * cos(newang[1]);
double rotnewxy = sin(newang[0]) * sin(newang[1]) * cos(newang[2]) - cos(newang[0]) * sin(newang[2]);
double rotnewxz = cos(newang[0]) * sin(newang[1]) * cos(newang[2]) + sin(newang[0]) * sin(newang[2]);
double rotnewyy = sin(newang[0]) * sin(newang[1]) * sin(newang[2]) + cos(newang[0]) * cos(newang[2]);
double rotnewyz = cos(newang[0]) * sin(newang[1]) * sin(newang[2]) - sin(newang[0]) * cos(newang[2]);
bool eqxx = eq2ang(rotnewxx, rmLocal.xx());
bool eqzz = eq2ang(rotnewzz, rmLocal.zz());
bool eqxy = eq2ang(rotnewxy, rmLocal.xy());
bool eqxz = eq2ang(rotnewxz, rmLocal.xz());
bool eqyy = eq2ang(rotnewyy, rmLocal.yy());
bool eqyz = eq2ang(rotnewyz, rmLocal.yz());
//--- Check if one of the tree angles should be changed
if (ALIUtils::debug >= 5) {
std::cout << " pred rm.xx " << rotnewxx << " =? " << rmLocal.xx() << " pred rm.zz " << rotnewzz << " =? "
<< rmLocal.zz() << std::endl;
std::cout << " eqxx " << eqxx << " eqzz " << eqzz << std::endl;
//- std::cout << " rotnewxx " << rotnewxx << " = " << rmLocal.xx() << " " << fabs( rotnewxx - rmLocal.xx() ) << " " <<(fabs( rotnewxx - rmLocal.xx() ) < 0.0001) << std::endl;
}
if (eqxx & !eqzz) {
newang[0] = pii + newang[0];
if (ALIUtils::debug >= 5)
std::cout << " change newang[0] " << newang[0] << std::endl;
} else if (!eqxx & !eqzz) {
newang[1] = pii - newang[1];
if (ALIUtils::debug >= 5)
std::cout << " change newang[1] " << newang[1] << std::endl;
} else if (!eqxx & eqzz) {
newang[2] = pii + newang[2];
if (ALIUtils::debug >= 5)
std::cout << " change newang[2] " << newang[2] << std::endl;
}
//--- Check if the 3 angles should be changed (previous check is invariant to the 3 changing)
if (ALIUtils::debug >= 5) {
std::cout << " pred rm.xy " << rotnewxy << " =? " << rmLocal.xy() << " pred rm.xz " << rotnewxz << " =? "
<< rmLocal.xz() << " pred rm.yy " << rotnewyy << " =? " << rmLocal.yy() << " pred rm.yz " << rotnewyz
<< " =? " << rmLocal.yz() << std::endl;
std::cout << " eqxy " << eqxy << " eqxz " << eqxz << " eqyy " << eqyy << " eqyz " << eqyz << std::endl;
}
if (!eqxy || !eqxz || !eqyy || !eqyz) {
// check also cases where one of the above 'eq' is OK because it is = 0
if (ALIUtils::debug >= 5)
std::cout << " change the 3 newang " << std::endl;
newang[0] = addPii(newang[0]);
newang[1] = pii - newang[1];
newang[2] = addPii(newang[2]);
double rotnewxy = -sin(newang[0]) * sin(newang[1]) * cos(newang[2]) - cos(newang[0]) * sin(newang[2]);
double rotnewxz = -cos(newang[0]) * sin(newang[1]) * cos(newang[2]) - sin(newang[0]) * sin(newang[2]);
if (ALIUtils::debug >= 5)
std::cout << " rotnewxy " << rotnewxy << " = " << rmLocal.xy() << " rotnewxz " << rotnewxz << " = "
<< rmLocal.xz() << std::endl;
}
if (diff2pi(angleX, newang[0]) + diff2pi(angleY, newang[1]) + diff2pi(angleZ, newang[2]) >
diff2pi(angleX, pii + newang[0]) + diff2pi(angleY, pii - newang[1]) + diff2pi(angleZ, pii + newang[2])) {
// check also cases where one of the above 'eq' is OK because it is = 0
if (ALIUtils::debug >= 5)
std::cout << " change the 3 newang " << std::endl;
newang[0] = addPii(newang[0]);
newang[1] = pii - newang[1];
newang[2] = addPii(newang[2]);
double rotnewxy = -sin(newang[0]) * sin(newang[1]) * cos(newang[2]) - cos(newang[0]) * sin(newang[2]);
double rotnewxz = -cos(newang[0]) * sin(newang[1]) * cos(newang[2]) - sin(newang[0]) * sin(newang[2]);
if (ALIUtils::debug >= 5)
std::cout << " rotnewxy " << rotnewxy << " = " << rmLocal.xy() << " rotnewxz " << rotnewxz << " = "
<< rmLocal.xz() << std::endl;
}
for (int ii = 0; ii < 3; ii++) {
newang[ii] = approxTo0(newang[ii]);
}
// double rotnewyx = cos( newang[1] ) * sin( newang[2] );
if (checkMatrixEquations(newang[0], newang[1], newang[2], &rmLocal) != 0) {
std::cerr << " wrong rotation matrix " << newang[0] << " " << newang[1] << " " << newang[2] << std::endl;
ALIUtils::dumprm(rmLocal, " matrix is ");
}
if (ALIUtils::debug >= 5) {
std::cout << "Final angles: newang[0] " << newang[0] << " newang[1] " << newang[1] << " newang[2] " << newang[2]
<< std::endl;
CLHEP::HepRotation rot;
rot.rotateX(newang[0]);
ALIUtils::dumprm(rot, " new rot after X ");
rot.rotateY(newang[1]);
ALIUtils::dumprm(rot, " new rot after Y ");
rot.rotateZ(newang[2]);
ALIUtils::dumprm(rot, " new rot ");
ALIUtils::dumprm(rmLocal, " rmLocal ");
//- ALIUtils::dumprm( theRmGlobOriginal, " theRmGlobOriginal " );
}
//- std::cout << " before return newang[0] " << newang[0] << " newang[1] " << newang[1] << " newang[2] " << newang[2] << std::endl;
return newang;
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
double ALIUtils::diff2pi(double ang1, double ang2) {
double pii = acos(0.) * 2;
double diff = fabs(ang1 - ang2);
diff = diff - int(diff / 2. / pii) * 2 * pii;
return diff;
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
bool ALIUtils::eq2ang(double ang1, double ang2) {
bool beq = true;
double pii = acos(0.) * 2;
double diff = diff2pi(ang1, ang2);
if (diff > 0.00001) {
if (fabs(diff - 2 * pii) > 0.00001) {
//- std::cout << " diff " << diff << " " << ang1 << " " << ang2 << std::endl;
beq = false;
}
} else {
beq = true;
}
return beq;
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
double ALIUtils::approxTo0(double val) {
double precision = 1.e-9;
if (fabs(val) < precision)
val = 0;
return val;
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
double ALIUtils::addPii(double val) {
if (val < M_PI) {
val += M_PI;
} else {
val -= M_PI;
}
return val;
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
int ALIUtils::checkMatrixEquations(double angleX, double angleY, double angleZ, CLHEP::HepRotation* rot) {
//- std::cout << " cme " << angleX << " " << angleY << " " << angleZ << std::endl;
if (rot == nullptr) {
rot = new CLHEP::HepRotation();
rot->rotateX(angleX);
rot->rotateY(angleY);
rot->rotateZ(angleZ);
}
double sx = sin(angleX);
double cx = cos(angleX);
double sy = sin(angleY);
double cy = cos(angleY);
double sz = sin(angleZ);
double cz = cos(angleZ);
double rotxx = cy * cz;
double rotxy = sx * sy * cz - cx * sz;
double rotxz = cx * sy * cz + sx * sz;
double rotyx = cy * sz;
double rotyy = sx * sy * sz + cx * cz;
double rotyz = cx * sy * sz - sx * cz;
double rotzx = -sy;
double rotzy = sx * cy;
double rotzz = cx * cy;
int matrixElemBad = 0;
if (!eq2ang(rot->xx(), rotxx)) {
std::cerr << " EQUATION for xx() IS BAD " << rot->xx() << " <> " << rotxx << std::endl;
matrixElemBad++;
}
if (!eq2ang(rot->xy(), rotxy)) {
std::cerr << " EQUATION for xy() IS BAD " << rot->xy() << " <> " << rotxy << std::endl;
matrixElemBad++;
}
if (!eq2ang(rot->xz(), rotxz)) {
std::cerr << " EQUATION for xz() IS BAD " << rot->xz() << " <> " << rotxz << std::endl;
matrixElemBad++;
}
if (!eq2ang(rot->yx(), rotyx)) {
std::cerr << " EQUATION for yx() IS BAD " << rot->yx() << " <> " << rotyx << std::endl;
matrixElemBad++;
}
if (!eq2ang(rot->yy(), rotyy)) {
std::cerr << " EQUATION for yy() IS BAD " << rot->yy() << " <> " << rotyy << std::endl;
matrixElemBad++;
}
if (!eq2ang(rot->yz(), rotyz)) {
std::cerr << " EQUATION for yz() IS BAD " << rot->yz() << " <> " << rotyz << std::endl;
matrixElemBad++;
}
if (!eq2ang(rot->zx(), rotzx)) {
std::cerr << " EQUATION for zx() IS BAD " << rot->zx() << " <> " << rotzx << std::endl;
matrixElemBad++;
}
if (!eq2ang(rot->zy(), rotzy)) {
std::cerr << " EQUATION for zy() IS BAD " << rot->zy() << " <> " << rotzy << std::endl;
matrixElemBad++;
}
if (!eq2ang(rot->zz(), rotzz)) {
std::cerr << " EQUATION for zz() IS BAD " << rot->zz() << " <> " << rotzz << std::endl;
matrixElemBad++;
}
//- std::cout << " cme: matrixElemBad " << matrixElemBad << std::endl;
return matrixElemBad;
}
| 32,625 | 12,377 |
/*
// Copyright (c) 2000-2009, Texas Engineering Experiment Station (TEES), a
// component of the Texas A&M University System.
// All rights reserved.
// The information and source code contained herein is the exclusive
// property of TEES and may not be disclosed, examined or reproduced
// in whole or in part without explicit written authorization from TEES.
*/
#ifndef STAPL_CONTAINERS_MAP_METADATA_HPP
#define STAPL_CONTAINERS_MAP_METADATA_HPP
#include <stapl/domains/iterator_domain.hpp>
#include <stapl/views/metadata/metadata_entry.hpp>
#include <stapl/views/metadata/container_fwd.hpp>
#include <stapl/containers/iterators/gid_of_fwd.hpp>
namespace stapl {
//////////////////////////////////////////////////////////////////////
/// @brief Class for computing the metadata of @ref map_distribution,
/// and all other associative distributions.
/// @tparam Distribution Type of the Distribution.
//////////////////////////////////////////////////////////////////////
template<typename Distribution>
class map_metadata
{
STAPL_IMPORT_TYPE(typename Distribution, index_type)
STAPL_IMPORT_TYPE(typename Distribution, base_container_type)
STAPL_IMPORT_TYPE(typename Distribution, container_manager_type)
typedef typename base_container_type::domain_type bc_domain_type;
typedef iterator_domain<
Distribution, typename bc_domain_type::field_selector
> domain_type;
public:
// public access required to allow the container's distribution class access.
typedef metadata_entry<domain_type, base_container_type*> dom_info_type;
private:
typedef metadata::growable_container<dom_info_type> metadata_type;
public:
typedef metadata_type metadata_cont_type;
typedef std::pair<bool, metadata_cont_type*> return_type;
//////////////////////////////////////////////////////////////////////
/// @brief Return the metadata of the specified container.
/// @see metadata_entry.
/// @param cont A pointer to the container.
///
/// Calls the operator on the distribution of the provided container.
///
/// @return a pair indicating if the metadata container is static and
/// balance distributed and a pointer to the metadata container.
//////////////////////////////////////////////////////////////////////
template <typename Container>
return_type operator()(Container* cont)
{
return operator()(&(cont->distribution()));
}
//////////////////////////////////////////////////////////////////////
/// @brief Return the metadata of the specified distribution.
/// @see metadata_entry.
/// @param dist A pointer to the distribution.
///
/// @return a pair indicating if the metadata container is static and
/// balance distributed and a pointer to the metadata container.
//////////////////////////////////////////////////////////////////////
return_type operator()(Distribution* dist)
{
metadata_cont_type* out_part = new metadata_type;
typedef typename container_manager_type::const_iterator citer_t;
citer_t cit = dist->container_manager().begin();
citer_t cit_end = dist->container_manager().end();
for ( ; cit != cit_end; ++cit)
{
base_container_type& bc = *cit;
if (!bc.domain().empty())
{
domain_type ndom(
bc.domain().first(), bc.domain().last(), *dist, bc.domain().size()
);
out_part->push_back_here(dom_info_type(
typename dom_info_type::cid_type(), ndom, &bc,
LQ_CERTAIN, get_affinity(),
dist->get_rmi_handle(), dist->get_location_id()
));
}
}
out_part->update();
return std::make_pair(false, out_part);
}
}; // class map_metadata
} // namespace stapl
#endif // STAPL_CONTAINERS_MAP_METADATA_HPP
| 3,847 | 1,070 |
#include "event.h"
| 20 | 9 |
/******************************************************************************
* tsp_instance.cpp: Implementation for TSP_Instance class.
*
* (c) Copyright 2015-2019, Carlos Eduardo de Andrade.
* All Rights Reserved.
*
* Created on : Mar 05, 2019 by andrade
* Last update: Mar 05, 2019 by andrade
*
* This code is released under LICENSE.md.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************/
#include "tsp/tsp_instance.hpp"
#include <fstream>
#include <stdexcept>
using namespace std;
//-----------------------------[ Constructor ]--------------------------------//
TSP_Instance::TSP_Instance(const std::string& filename):
num_nodes(0),
distances()
{
ifstream file(filename, ios::in);
if(!file)
throw runtime_error("Cannot open instance file");
file.exceptions(ifstream::failbit | ifstream::badbit);
try {
file >> num_nodes;
distances.resize((num_nodes * (num_nodes - 1)) / 2);
for(unsigned i = 0; i < distances.size(); ++i)
file >> distances[i];
}
catch(std::ifstream::failure& e) {
throw fstream::failure("Error reading the instance file");
}
}
//-------------------------------[ Distance ]---------------------------------//
double TSP_Instance::distance(unsigned i, unsigned j) const {
if(i > j)
swap(i, j);
return distances[(i * (num_nodes - 1)) - ((i - 1) * i / 2) + (j - i - 1)];
}
| 2,233 | 793 |
/*
* Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef otbSharkRandomForestsMachineLearningModel_hxx
#define otbSharkRandomForestsMachineLearningModel_hxx
#include <fstream>
#include "itkMacro.h"
#include "otbSharkRandomForestsMachineLearningModel.h"
#if defined(__GNUC__) || defined(__clang__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wshadow"
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Woverloaded-virtual"
#pragma GCC diagnostic ignored "-Wignored-qualifiers"
#endif
#if defined(__GNUC__) || defined(__clang__)
#pragma GCC diagnostic pop
#endif
#include "otbSharkUtils.h"
#include <algorithm>
namespace otb
{
template <class TInputValue, class TOutputValue>
SharkRandomForestsMachineLearningModel<TInputValue, TOutputValue>::SharkRandomForestsMachineLearningModel()
{
this->m_ConfidenceIndex = true;
this->m_ProbaIndex = true;
this->m_IsRegressionSupported = false;
this->m_IsDoPredictBatchMultiThreaded = true;
this->m_NormalizeClassLabels = true;
this->m_ComputeMargin = false;
}
/** Train the machine learning model */
template <class TInputValue, class TOutputValue>
void SharkRandomForestsMachineLearningModel<TInputValue, TOutputValue>::Train()
{
#ifdef _OPENMP
omp_set_num_threads(itk::MultiThreader::GetGlobalDefaultNumberOfThreads());
#endif
std::vector<shark::RealVector> features;
std::vector<unsigned int> class_labels;
Shark::ListSampleToSharkVector(this->GetInputListSample(), features);
Shark::ListSampleToSharkVector(this->GetTargetListSample(), class_labels);
if (m_NormalizeClassLabels)
{
Shark::NormalizeLabelsAndGetDictionary(class_labels, m_ClassDictionary);
}
shark::ClassificationDataset TrainSamples = shark::createLabeledDataFromRange(features, class_labels);
// Set parameters
m_RFTrainer.setMTry(m_MTry);
m_RFTrainer.setNTrees(m_NumberOfTrees);
m_RFTrainer.setNodeSize(m_NodeSize);
// m_RFTrainer.setOOBratio(m_OobRatio);
m_RFTrainer.train(m_RFModel, TrainSamples);
}
template <class TInputValue, class TOutputValue>
typename SharkRandomForestsMachineLearningModel<TInputValue, TOutputValue>::ConfidenceValueType
SharkRandomForestsMachineLearningModel<TInputValue, TOutputValue>::ComputeConfidence(shark::RealVector& probas, bool computeMargin) const
{
assert(!probas.empty() && "probas vector is empty");
assert((!computeMargin || probas.size() > 1) && "probas size should be at least 2 if computeMargin is true");
ConfidenceValueType conf{0};
if (computeMargin)
{
std::nth_element(probas.begin(), probas.begin() + 1, probas.end(), std::greater<double>());
conf = static_cast<ConfidenceValueType>(probas[0] - probas[1]);
}
else
{
auto max_proba = *(std::max_element(probas.begin(), probas.end()));
conf = static_cast<ConfidenceValueType>(max_proba);
}
return conf;
}
template <class TInputValue, class TOutputValue>
typename SharkRandomForestsMachineLearningModel<TInputValue, TOutputValue>::TargetSampleType
SharkRandomForestsMachineLearningModel<TInputValue, TOutputValue>::DoPredict(const InputSampleType& value, ConfidenceValueType* quality,
ProbaSampleType* proba) const
{
shark::RealVector samples(value.Size());
for (size_t i = 0; i < value.Size(); i++)
{
samples.push_back(value[i]);
}
if (quality != nullptr || proba != nullptr)
{
shark::RealVector probas = m_RFModel.decisionFunction()(samples);
if (quality != nullptr)
{
(*quality) = ComputeConfidence(probas, m_ComputeMargin);
}
if (proba != nullptr)
{
for (size_t i = 0; i < probas.size(); i++)
{
// probas contain the N class probability indexed between 0 and N-1
(*proba)[i] = static_cast<unsigned int>(probas[i] * 1000);
}
}
}
unsigned int res{0};
m_RFModel.eval(samples, res);
TargetSampleType target;
if (m_NormalizeClassLabels)
{
target[0] = m_ClassDictionary[static_cast<TOutputValue>(res)];
}
else
{
target[0] = static_cast<TOutputValue>(res);
}
return target;
}
template <class TInputValue, class TOutputValue>
void SharkRandomForestsMachineLearningModel<TInputValue, TOutputValue>::DoPredictBatch(const InputListSampleType* input, const unsigned int& startIndex,
const unsigned int& size, TargetListSampleType* targets,
ConfidenceListSampleType* quality, ProbaListSampleType* proba) const
{
assert(input != nullptr);
assert(targets != nullptr);
assert(input->Size() == targets->Size() && "Input sample list and target label list do not have the same size.");
assert(((quality == nullptr) || (quality->Size() == input->Size())) &&
"Quality samples list is not null and does not have the same size as input samples list");
assert(((proba == nullptr) || (input->Size() == proba->Size())) && "Proba sample list and target label list do not have the same size.");
if (startIndex + size > input->Size())
{
itkExceptionMacro(<< "requested range [" << startIndex << ", " << startIndex + size << "[ partially outside input sample list range.[0," << input->Size()
<< "[");
}
std::vector<shark::RealVector> features;
Shark::ListSampleRangeToSharkVector(input, features, startIndex, size);
shark::Data<shark::RealVector> inputSamples = shark::createDataFromRange(features);
#ifdef _OPENMP
omp_set_num_threads(itk::MultiThreader::GetGlobalDefaultNumberOfThreads());
#endif
if (proba != nullptr || quality != nullptr)
{
shark::Data<shark::RealVector> probas = m_RFModel.decisionFunction()(inputSamples);
if (proba != nullptr)
{
unsigned int id = startIndex;
for (shark::RealVector&& p : probas.elements())
{
ProbaSampleType prob{(unsigned int)p.size()};
for (size_t i = 0; i < p.size(); i++)
{
prob[i] = p[i] * 1000;
}
proba->SetMeasurementVector(id, prob);
++id;
}
}
if (quality != nullptr)
{
unsigned int id = startIndex;
for (shark::RealVector&& p : probas.elements())
{
ConfidenceSampleType confidence;
auto conf = ComputeConfidence(p, m_ComputeMargin);
confidence[0] = static_cast<ConfidenceValueType>(conf);
quality->SetMeasurementVector(id, confidence);
++id;
}
}
}
auto prediction = m_RFModel(inputSamples);
unsigned int id = startIndex;
for (const auto& p : prediction.elements())
{
TargetSampleType target;
if (m_NormalizeClassLabels)
{
target[0] = m_ClassDictionary[static_cast<TOutputValue>(p)];
}
else
{
target[0] = static_cast<TOutputValue>(p);
}
targets->SetMeasurementVector(id, target);
++id;
}
}
template <class TInputValue, class TOutputValue>
void SharkRandomForestsMachineLearningModel<TInputValue, TOutputValue>::Save(const std::string& filename, const std::string& itkNotUsed(name))
{
std::ofstream ofs(filename);
if (!ofs)
{
itkExceptionMacro(<< "Error opening " << filename.c_str());
}
// Add comment with model file name
ofs << "#" << m_RFModel.name();
if (m_NormalizeClassLabels)
ofs << " with_dictionary";
ofs << std::endl;
if (m_NormalizeClassLabels)
{
ofs << m_ClassDictionary.size() << " ";
for (const auto& l : m_ClassDictionary)
{
ofs << l << " ";
}
ofs << std::endl;
}
shark::TextOutArchive oa(ofs);
m_RFModel.save(oa, 0);
}
template <class TInputValue, class TOutputValue>
void SharkRandomForestsMachineLearningModel<TInputValue, TOutputValue>::Load(const std::string& filename, const std::string& itkNotUsed(name))
{
std::ifstream ifs(filename);
if (ifs.good())
{
// Check if the first line is a comment and verify the name of the model in this case.
std::string line;
getline(ifs, line);
if (line.at(0) == '#')
{
if (line.find(m_RFModel.name()) == std::string::npos)
itkExceptionMacro("The model file : " + filename + " cannot be read.");
if (line.find("with_dictionary") == std::string::npos)
{
m_NormalizeClassLabels = false;
}
}
else
{
// rewind if first line is not a comment
ifs.clear();
ifs.seekg(0, std::ios::beg);
}
if (m_NormalizeClassLabels)
{
size_t nbLabels{0};
ifs >> nbLabels;
m_ClassDictionary.resize(nbLabels);
for (size_t i = 0; i < nbLabels; ++i)
{
unsigned int label;
ifs >> label;
m_ClassDictionary[i] = label;
}
}
shark::TextInArchive ia(ifs);
m_RFModel.load(ia, 0);
}
}
template <class TInputValue, class TOutputValue>
bool SharkRandomForestsMachineLearningModel<TInputValue, TOutputValue>::CanReadFile(const std::string& file)
{
try
{
this->Load(file);
m_RFModel.name();
}
catch (...)
{
return false;
}
return true;
}
template <class TInputValue, class TOutputValue>
bool SharkRandomForestsMachineLearningModel<TInputValue, TOutputValue>::CanWriteFile(const std::string& itkNotUsed(file))
{
return true;
}
template <class TInputValue, class TOutputValue>
void SharkRandomForestsMachineLearningModel<TInputValue, TOutputValue>::PrintSelf(std::ostream& os, itk::Indent indent) const
{
// Call superclass implementation
Superclass::PrintSelf(os, indent);
}
} // end namespace otb
#endif
| 10,338 | 3,363 |
#include "Base64.h"
#include <mutex>
#include <iostream>
using namespace std;
using namespace sensor_tool;
std::string sensor_tool::base64Encode(const std::string & origin_string)
{
static const char base64Char[] ="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::string ret("");
if(origin_string.empty()) return ret;
unsigned const numOrig24BitValues = origin_string.size()/3;
bool havePadding = origin_string.size() > numOrig24BitValues*3;//判断是否有余数
bool havePadding2 = origin_string.size() == numOrig24BitValues*3 + 2;//判断余数是否等于2
unsigned const numResultBytes = 4*(numOrig24BitValues + havePadding);//计算最终结果的size
ret.resize(numResultBytes);//确定返回字符串大小
unsigned i;
for (i = 0; i < numOrig24BitValues; ++i) {
ret[4*i+0] = base64Char[(origin_string[3*i]>>2)&0x3F];
ret[4*i+1] = base64Char[(((origin_string[3*i]&0x3)<<4) | (origin_string[3*i+1]>>4))&0x3F];
ret[4*i+2] = base64Char[((origin_string[3*i+1]<<2) | (origin_string[3*i+2]>>6))&0x3F];
ret[4*i+3] = base64Char[origin_string[3*i+2]&0x3F];
}
//处理不足3位的情况
//余1位需在后面补齐2个'='
//余2位需补齐一个'='
if (havePadding) {
ret[4*i+0] = base64Char[(origin_string[3*i]>>2)&0x3F];
if (havePadding2) {
ret[4*i+1] = base64Char[(((origin_string[3*i]&0x3)<<4) | (origin_string[3*i+1]>>4))&0x3F];
ret[4*i+2] = base64Char[(origin_string[3*i+1]<<2)&0x3F];
} else {
ret[4*i+1] = base64Char[((origin_string[3*i]&0x3)<<4)&0x3F];
ret[4*i+2] = '=';
}
ret[4*i+3] = '=';
}
return ret;
}
std::string sensor_tool::base64Decode(const std::string & origin_string)
{
static char base64DecodeTable[256];
static std::once_flag oc_init;
std::call_once(oc_init,[&](){
int i;//初始化映射表
for (i = 0; i < 256; ++i) base64DecodeTable[i] = (char)0x80;
for (i = 'A'; i <= 'Z'; ++i) base64DecodeTable[i] = 0 + (i - 'A');
for (i = 'a'; i <= 'z'; ++i) base64DecodeTable[i] = 26 + (i - 'a');
for (i = '0'; i <= '9'; ++i) base64DecodeTable[i] = 52 + (i - '0');
base64DecodeTable[(unsigned char)'+'] = 62;
base64DecodeTable[(unsigned char)'/'] = 63;
base64DecodeTable[(unsigned char)'='] = 0;
});
std::string ret("");
if(origin_string.empty()) return ret;
int k=0;
int paddingCount = 0;
int const jMax = origin_string.size() - 3;
ret.resize(3*origin_string.size()/4);
for(int j=0;j<jMax;j+=4)
{
char inTmp[4], outTmp[4];
for (int i = 0; i < 4; ++i) {
inTmp[i] = origin_string[i+j];
if (inTmp[i] == '=') ++paddingCount;
outTmp[i] = base64DecodeTable[(unsigned char)inTmp[i]];
if ((outTmp[i]&0x80) != 0) outTmp[i] = 0; // this happens only if there was an invalid character; pretend that it was 'A'
}
ret[k++]=(outTmp[0]<<2) | (outTmp[1]>>4);
ret[k++] = (outTmp[1]<<4) | (outTmp[2]>>2);
ret[k++] = (outTmp[2]<<6) | outTmp[3];
}
ret.assign(ret.c_str());//清除空白字符
return ret;
}
void Base64_test()
{
std::string qwer("Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure.");
std::string qaz=sensor_tool::base64Encode(qwer);
std::cout<<qaz<<std::endl;
std::cout<<qwer<<std::endl;
std::cout<<(int)(sensor_tool::base64Decode(qaz)==qwer)<<std::endl;
}
| 3,562 | 1,567 |
/*
[auto_generated]
boost/numeric/odeint/iterator/detail/adaptive_time_iterator_controlled_impl.hpp
[begin_description]
tba.
[end_description]
Copyright 2009-2012 Karsten Ahnert
Copyright 2009-2012 Mario Mulansky
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or
copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_NUMERIC_ODEINT_ITERATOR_DETAIL_ADAPTIVE_TIME_ITERATOR_CONTROLLED_IMPL_HPP_DEFINED
#define BOOST_NUMERIC_ODEINT_ITERATOR_DETAIL_ADAPTIVE_TIME_ITERATOR_CONTROLLED_IMPL_HPP_DEFINED
#include <boost/numeric/odeint/util/unit_helper.hpp>
#include <boost/numeric/odeint/stepper/controlled_step_result.hpp>
#include <boost/numeric/odeint/iterator/detail/ode_time_iterator_base.hpp>
namespace boost {
namespace numeric {
namespace odeint {
/*
* Specilization for controlled steppers
*/
/**
* \brief ODE Iterator with adaptive step size control. The value type of this iterator is a pair of state type and time type of the stepper.
*
* Implements an ODE iterator with adaptive step size control. Uses controlled steppers. adaptive_iterator is a model
* of single-pass iterator.
*
* The value type of this iterator is a pair of state type and time type of the stepper.
*
* \tparam Stepper The stepper type which should be used during the iteration.
* \tparam System The type of the system function (ODE) which should be solved.
*/
template< class Stepper , class System >
class adaptive_time_iterator< Stepper , System , controlled_stepper_tag > : public detail::ode_time_iterator_base
<
adaptive_time_iterator< Stepper , System , controlled_stepper_tag > ,
Stepper , System
>
{
private:
typedef Stepper stepper_type;
typedef System system_type;
typedef typename boost::numeric::odeint::unwrap_reference< stepper_type >::type unwrapped_stepper_type;
typedef typename unwrapped_stepper_type::state_type state_type;
typedef typename unwrapped_stepper_type::time_type time_type;
typedef typename unwrapped_stepper_type::value_type ode_value_type;
typedef detail::ode_time_iterator_base<
adaptive_time_iterator< Stepper , System , controlled_stepper_tag > ,
Stepper , System > base_type;
public:
/**
* \brief Constructs an adaptive_time_iterator. This constructor should be used to construct the begin iterator.
*
* \param stepper The stepper to use during the iteration.
* \param sys The system function (ODE) to solve.
* \param s The initial state. adaptive_time_iterator stores a reference of s and changes its value during the iteration.
* \param t The initial time.
* \param t_end The end time, at which the iteration should stop.
* \param dt The initial time step.
*/
adaptive_time_iterator( stepper_type stepper , system_type sys , state_type &s , time_type t , time_type t_end , time_type dt )
: base_type( stepper , sys , s , t , t_end , dt ) {}
/**
* \brief Constructs an adaptive_time_iterator. This constructor should be used to construct the end iterator.
*
* \param stepper The stepper to use during the iteration.
* \param sys The system function (ODE) to solve.
* \param s The initial state. adaptive_time_iterator stores a reference of s and changes its value during the iteration.
*/
adaptive_time_iterator( stepper_type stepper , system_type sys , state_type &s )
: base_type( stepper , sys , s ) {}
private:
friend class boost::iterator_core_access;
void increment()
{
unwrapped_stepper_type &stepper = this->m_stepper;
const size_t max_attempts = 1000;
size_t trials = 0;
controlled_step_result res = success;
do
{
res = stepper.try_step( this->m_system , *this->m_state , this->m_t , this->m_dt );
++trials;
}
while( ( res == fail ) && ( trials < max_attempts ) );
if( trials == max_attempts )
{
throw std::overflow_error( "Adaptive iterator : Maximal number of iterations reached. A step size could not be found." );
}
this->check_end();
}
};
} // namespace odeint
} // namespace numeric
} // namespace boost
#endif // BOOST_NUMERIC_ODEINT_ITERATOR_DETAIL_ADAPTIVE_TIME_ITERATOR_CONTROLLED_IMPL_HPP_DEFINED
| 4,649 | 1,416 |
// generated from rosidl_generator_cpp/resource/srv__struct.hpp.em
// generated code does not contain a copyright notice
#ifndef RCL_INTERFACES__SRV__GET_PARAMETERS__STRUCT_HPP_
#define RCL_INTERFACES__SRV__GET_PARAMETERS__STRUCT_HPP_
#include "rcl_interfaces/srv/get_parameters__request.hpp"
#include "rcl_interfaces/srv/get_parameters__response.hpp"
namespace rcl_interfaces
{
namespace srv
{
struct GetParameters
{
using Request = rcl_interfaces::srv::GetParameters_Request;
using Response = rcl_interfaces::srv::GetParameters_Response;
};
} // namespace srv
} // namespace rcl_interfaces
#endif // RCL_INTERFACES__SRV__GET_PARAMETERS__STRUCT_HPP_
| 666 | 250 |
#include "Geometry/HGCalCommonData/interface/HGCalParameters.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "Geometry/HGCalCommonData/interface/HGCalWaferIndex.h"
//#define EDM_ML_DEBUG
HGCalParameters::HGCalParameters(const std::string& nam) : name_(nam), nCells_(0), waferMaskMode_(0) {
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "Construct HGCalParameters for " << name_;
#endif
}
HGCalParameters::~HGCalParameters() {}
void HGCalParameters::fillModule(const HGCalParameters::hgtrap& mytr, bool reco) {
if (reco) {
moduleLayR_.emplace_back(mytr.lay);
moduleBlR_.emplace_back(mytr.bl);
moduleTlR_.emplace_back(mytr.tl);
moduleHR_.emplace_back(mytr.h);
moduleDzR_.emplace_back(mytr.dz);
moduleAlphaR_.emplace_back(mytr.alpha);
moduleCellR_.emplace_back(mytr.cellSize);
} else {
moduleLayS_.emplace_back(mytr.lay);
moduleBlS_.emplace_back(mytr.bl);
moduleTlS_.emplace_back(mytr.tl);
moduleHS_.emplace_back(mytr.h);
moduleDzS_.emplace_back(mytr.dz);
moduleAlphaS_.emplace_back(mytr.alpha);
moduleCellS_.emplace_back(mytr.cellSize);
}
}
HGCalParameters::hgtrap HGCalParameters::getModule(unsigned int k, bool reco) const {
HGCalParameters::hgtrap mytr;
if (reco) {
if (k < moduleLayR_.size()) {
mytr.lay = moduleLayR_[k];
mytr.bl = moduleBlR_[k];
mytr.tl = moduleTlR_[k];
mytr.h = moduleHR_[k];
mytr.dz = moduleDzR_[k];
mytr.alpha = moduleAlphaR_[k];
mytr.cellSize = moduleCellR_[k];
} else {
mytr.lay = -1;
mytr.bl = mytr.tl = mytr.h = mytr.dz = mytr.alpha = mytr.cellSize = 0;
}
} else {
if (k < moduleLayS_.size()) {
mytr.lay = moduleLayS_[k];
mytr.bl = moduleBlS_[k];
mytr.tl = moduleTlS_[k];
mytr.h = moduleHS_[k];
mytr.dz = moduleDzS_[k];
mytr.alpha = moduleAlphaS_[k];
mytr.cellSize = moduleCellS_[k];
} else {
mytr.lay = -1;
mytr.bl = mytr.tl = mytr.h = mytr.dz = mytr.alpha = mytr.cellSize = 0;
}
}
return mytr;
}
void HGCalParameters::fillTrForm(const HGCalParameters::hgtrform& mytr) {
int zp = (mytr.zp == 1) ? 1 : 0;
uint32_t indx = ((zp & kMaskZside) << kShiftZside);
indx |= ((mytr.lay & kMaskLayer) << kShiftLayer);
indx |= ((mytr.sec & kMaskSector) << kShiftSector);
indx |= ((mytr.subsec & kMaskSubSec) << kShiftSubSec);
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "ZP " << zp << ":" << kMaskZside << ":" << kShiftZside
<< ((zp & kMaskZside) << kShiftZside) << " Lay " << mytr.lay << ":" << kMaskLayer << ":"
<< kShiftLayer << ":" << ((mytr.lay & kMaskLayer) << kShiftLayer) << " Sector "
<< mytr.sec << ":" << kMaskSector << ":" << kShiftSector << ":"
<< ((mytr.sec & kMaskSector) << kShiftSector) << " SubSec " << mytr.subsec << ":"
<< kMaskSubSec << ":" << kShiftSubSec << ":"
<< ((mytr.subsec & kMaskSubSec) << kShiftSubSec) << " Index " << std::hex << indx
<< std::dec;
#endif
trformIndex_.emplace_back(indx);
trformTranX_.emplace_back(mytr.h3v.x());
trformTranY_.emplace_back(mytr.h3v.y());
trformTranZ_.emplace_back(mytr.h3v.z());
trformRotXX_.emplace_back((std::abs(mytr.hr.xx()) > tol) ? mytr.hr.xx() : 0);
trformRotYX_.emplace_back((std::abs(mytr.hr.yx()) > tol) ? mytr.hr.yx() : 0);
trformRotZX_.emplace_back((std::abs(mytr.hr.zx()) > tol) ? mytr.hr.zx() : 0);
trformRotXY_.emplace_back((std::abs(mytr.hr.xy()) > tol) ? mytr.hr.xy() : 0);
trformRotYY_.emplace_back((std::abs(mytr.hr.yy()) > tol) ? mytr.hr.yy() : 0);
trformRotZY_.emplace_back((std::abs(mytr.hr.zy()) > tol) ? mytr.hr.zy() : 0);
trformRotXZ_.emplace_back((std::abs(mytr.hr.xz()) > tol) ? mytr.hr.xz() : 0);
trformRotYZ_.emplace_back((std::abs(mytr.hr.yz()) > tol) ? mytr.hr.yz() : 0);
trformRotZZ_.emplace_back((std::abs(mytr.hr.zz()) > tol) ? mytr.hr.zz() : 0);
#ifdef EDM_ML_DEBUG
unsigned int k = trformIndex_.size() - 1;
edm::LogVerbatim("HGCalGeom") << "HGCalParameters[" << k << "] Index " << std::hex << trformIndex_[k] << std::dec
<< " (" << mytr.zp << ", " << mytr.lay << ", " << mytr.sec << ", " << mytr.subsec
<< ") Translation (" << trformTranX_[k] << ", " << trformTranY_[k] << ", "
<< trformTranZ_[k] << ") Rotation (" << trformRotXX_[k] << ", " << trformRotYX_[k]
<< ", " << trformRotZX_[k] << ", " << trformRotXY_[k] << ", " << trformRotYY_[k] << ", "
<< trformRotZY_[k] << ", " << trformRotXZ_[k] << ", " << trformRotYZ_[k] << ", "
<< trformRotZZ_[k];
#endif
}
HGCalParameters::hgtrform HGCalParameters::getTrForm(unsigned int k) const {
HGCalParameters::hgtrform mytr;
if (k < trformIndex_.size()) {
const auto& id = getID(k);
mytr.zp = id[0];
mytr.lay = id[1];
mytr.sec = id[2];
mytr.subsec = id[3];
mytr.h3v = CLHEP::Hep3Vector(trformTranX_[k], trformTranY_[k], trformTranZ_[k]);
const CLHEP::HepRep3x3 rotation(trformRotXX_[k],
trformRotXY_[k],
trformRotXZ_[k],
trformRotYX_[k],
trformRotYY_[k],
trformRotYZ_[k],
trformRotZX_[k],
trformRotZY_[k],
trformRotZZ_[k]);
mytr.hr = CLHEP::HepRotation(rotation);
} else {
mytr.zp = mytr.lay = mytr.sec = mytr.subsec = 0;
}
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "HGCalParameters[" << k << "] Index " << std::hex << trformIndex_[k] << std::dec
<< " (" << mytr.zp << ", " << mytr.lay << ", " << mytr.sec << ", " << mytr.subsec
<< ") Translation (" << mytr.h3v.x() << ", " << mytr.h3v.y() << ", " << mytr.h3v.z()
<< ") Rotation (" << mytr.hr.xx() << ", " << mytr.hr.yx() << ", " << mytr.hr.zx()
<< ", " << mytr.hr.xy() << ", " << mytr.hr.yy() << ", " << mytr.hr.zy() << ", "
<< mytr.hr.xz() << ", " << mytr.hr.yz() << ", " << mytr.hr.zz();
#endif
return mytr;
}
void HGCalParameters::addTrForm(const CLHEP::Hep3Vector& h3v) {
unsigned int k = trformTranX_.size();
if (k > 0) {
trformTranX_[k - 1] += h3v.x();
trformTranY_[k - 1] += h3v.y();
trformTranZ_[k - 1] += h3v.z();
}
}
void HGCalParameters::scaleTrForm(double scale) {
unsigned int k = trformTranX_.size();
if (k > 0) {
trformTranX_[k - 1] *= scale;
trformTranY_[k - 1] *= scale;
trformTranZ_[k - 1] *= scale;
}
}
std::array<int, 4> HGCalParameters::getID(unsigned int k) const {
int zp = ((trformIndex_[k] >> kShiftZside) & kMaskZside);
if (zp != 1)
zp = -1;
int lay = ((trformIndex_[k] >> kShiftLayer) & kMaskLayer);
int sec = ((trformIndex_[k] >> kShiftSector) & kMaskSector);
int subsec = ((trformIndex_[k] >> kShiftSubSec) & kMaskSubSec);
return std::array<int, 4>{{zp, lay, sec, subsec}};
}
#include "FWCore/Utilities/interface/typelookup.h"
TYPELOOKUP_DATA_REG(HGCalParameters);
| 7,477 | 2,985 |
////http://www.ogre3d.org/tikiwiki/DynamicLineDrawing
#include "DynamicLines.h"
#include <Ogre.h>
#include <cassert>
#include <cmath>
using namespace Ogre;
enum {
POSITION_BINDING,
TEXCOORD_BINDING
};
DynamicLines::DynamicLines(OperationType opType)
{
initialize(opType,false);
setMaterial("BaseWhiteNoLighting");
mDirty = true;
}
DynamicLines::~DynamicLines()
{
}
void DynamicLines::setOperationType(OperationType opType)
{
mRenderOp.operationType = opType;
}
RenderOperation::OperationType DynamicLines::getOperationType() const
{
return mRenderOp.operationType;
}
void DynamicLines::addPoint(const Vector3 &p)
{
mPoints.push_back(p);
mDirty = true;
}
void DynamicLines::addPoint(Real x, Real y, Real z)
{
mPoints.push_back(Vector3(x,y,z));
mDirty = true;
}
const Vector3& DynamicLines::getPoint(unsigned short index) const
{
assert(index < mPoints.size() && "Point index is out of bounds!!");
return mPoints[index];
}
unsigned short DynamicLines::getNumPoints(void) const
{
return (unsigned short)mPoints.size();
}
void DynamicLines::setPoint(unsigned short index, const Vector3 &value)
{
assert(index < mPoints.size() && "Point index is out of bounds!!");
mPoints[index] = value;
mDirty = true;
}
void DynamicLines::clear()
{
mPoints.clear();
mDirty = true;
}
void DynamicLines::update()
{
if (mDirty) fillHardwareBuffers();
}
void DynamicLines::createVertexDeclaration()
{
VertexDeclaration *decl = mRenderOp.vertexData->vertexDeclaration;
decl->addElement(POSITION_BINDING, 0, VET_FLOAT3, VES_POSITION);
}
void DynamicLines::fillHardwareBuffers()
{
int size = mPoints.size();
prepareHardwareBuffers(size,0);
if (!size) {
mBox.setExtents(Vector3::ZERO,Vector3::ZERO);
mDirty=false;
return;
}
Vector3 vaabMin = mPoints[0];
Vector3 vaabMax = mPoints[0];
HardwareVertexBufferSharedPtr vbuf =
mRenderOp.vertexData->vertexBufferBinding->getBuffer(0);
Real *prPos = static_cast<Real*>(vbuf->lock(HardwareBuffer::HBL_DISCARD));
{
for(int i = 0; i < size; i++)
{
*prPos++ = mPoints[i].x;
*prPos++ = mPoints[i].y;
*prPos++ = mPoints[i].z;
if(mPoints[i].x < vaabMin.x)
vaabMin.x = mPoints[i].x;
if(mPoints[i].y < vaabMin.y)
vaabMin.y = mPoints[i].y;
if(mPoints[i].z < vaabMin.z)
vaabMin.z = mPoints[i].z;
if(mPoints[i].x > vaabMax.x)
vaabMax.x = mPoints[i].x;
if(mPoints[i].y > vaabMax.y)
vaabMax.y = mPoints[i].y;
if(mPoints[i].z > vaabMax.z)
vaabMax.z = mPoints[i].z;
}
}
vbuf->unlock();
mBox.setExtents(vaabMin, vaabMax);
mDirty = false;
}
/*
void DynamicLines::getWorldTransforms(Matrix4 *xform) const
{
// return identity matrix to prevent parent transforms
*xform = Matrix4::IDENTITY;
}
*/
/*
const Quaternion &DynamicLines::getWorldOrientation(void) const
{
return Quaternion::IDENTITY;
}
const Vector3 &DynamicLines::getWorldPosition(void) const
{
return Vector3::ZERO;
}
*/ | 3,044 | 1,169 |
YAML::Node default_config;
default_config["species"]["num"] = "0";
default_config["species"]["insertion_type"] = "random";
default_config["species"]["insert_file"] = "none";
default_config["species"]["overlap"] = "0";
default_config["species"]["draw_type"] = "orientation";
default_config["species"]["color"] = "0";
default_config["species"]["posit_flag"] = "0";
default_config["species"]["spec_flag"] = "0";
default_config["species"]["checkpoint_flag"] = "0";
default_config["species"]["n_posit"] = "100";
default_config["species"]["n_spec"] = "100";
default_config["species"]["n_checkpoint"] = "10000";
default_config["filament"]["diameter"] = "1";
default_config["filament"]["length"] = "-1";
default_config["filament"]["persistence_length"] = "400";
default_config["filament"]["max_length"] = "500";
default_config["filament"]["min_bond_length"] = "1.5";
default_config["filament"]["spiral_flag"] = "0";
default_config["filament"]["spiral_number_fail_condition"] = "0";
default_config["filament"]["driving_factor"] = "0";
default_config["filament"]["friction_ratio"] = "2";
default_config["filament"]["dynamic_instability_flag"] = "0";
default_config["filament"]["force_induced_catastrophe_flag"] = "0";
default_config["filament"]["optical_trap_flag"] = "0";
default_config["filament"]["optical_trap_spring"] = "20";
default_config["filament"]["optical_trap_fixed"] = "0";
default_config["filament"]["cilia_trap_flag"] = "0";
default_config["filament"]["fic_factor"] = "0.828";
default_config["filament"]["f_shrink_to_grow"] = "0.017";
default_config["filament"]["f_shrink_to_pause"] = "0.0";
default_config["filament"]["f_pause_to_grow"] = "0.0";
default_config["filament"]["f_pause_to_shrink"] = "0.0";
default_config["filament"]["f_grow_to_pause"] = "0.0";
default_config["filament"]["f_grow_to_shrink"] = "0.00554";
default_config["filament"]["metric_forces"] = "1";
default_config["filament"]["v_poly"] = "0.44";
default_config["filament"]["v_depoly"] = "0.793";
default_config["filament"]["theta_analysis"] = "0";
default_config["filament"]["lp_analysis"] = "0";
default_config["filament"]["global_order_analysis"] = "0";
default_config["filament"]["packing_fraction"] = "-1";
default_config["filament"]["perlen_ratio"] = "-1";
default_config["filament"]["n_bonds"] = "-1";
default_config["filament"]["driving_method"] = "0";
default_config["filament"]["n_equil"] = "0";
default_config["filament"]["orientation_corr_analysis"] = "0";
default_config["filament"]["orientation_corr_n_steps"] = "1000";
default_config["filament"]["crossing_analysis"] = "0";
default_config["filament"]["intrinsic_curvature"] = "0";
default_config["filament"]["flagella_flag"] = "0";
default_config["filament"]["flagella_freq"] = "1";
default_config["filament"]["flagella_period"] = "2";
default_config["filament"]["flagella_amplitude"] = "1";
default_config["filament"]["flocking_analysis"] = "0";
default_config["filament"]["polydispersity_flag"] = "0";
default_config["filament"]["polydispersity_factor"] = "0.03";
default_config["filament"]["polydispersity_warn_on_truncate"] = "0";
default_config["passive_filament"]["diameter"] = "1";
default_config["passive_filament"]["length"] = "-1";
default_config["passive_filament"]["persistence_length"] = "400";
default_config["passive_filament"]["max_length"] = "500";
default_config["passive_filament"]["min_length"] = "1";
default_config["passive_filament"]["max_bond_length"] = "5";
default_config["passive_filament"]["min_bond_length"] = "1.5";
default_config["passive_filament"]["driving_factor"] = "0";
default_config["passive_filament"]["friction_ratio"] = "2";
default_config["passive_filament"]["metric_forces"] = "1";
default_config["passive_filament"]["theta_analysis"] = "0";
default_config["passive_filament"]["lp_analysis"] = "0";
default_config["passive_filament"]["packing_fraction"] = "-1";
default_config["passive_filament"]["perlen_ratio"] = "-1";
default_config["passive_filament"]["n_bonds"] = "-1";
default_config["hard_rod"]["diameter"] = "1";
default_config["hard_rod"]["length"] = "40";
default_config["hard_rod"]["min_length"] = "3";
default_config["hard_rod"]["max_length"] = "300";
default_config["hard_rod"]["max_bond_length"] = "5";
default_config["hard_rod"]["driving_factor"] = "0";
default_config["br_bead"]["diameter"] = "1";
default_config["br_bead"]["driving_factor"] = "0";
default_config["br_bead"]["packing_fraction"] = "-1";
default_config["md_bead"]["diameter"] = "1";
default_config["md_bead"]["mass"] = "1";
default_config["md_bead"]["driving_factor"] = "0";
default_config["centrosome"]["diameter"] = "10";
default_config["centrosome"]["n_filaments_min"] = "0";
default_config["centrosome"]["n_filaments_max"] = "10";
default_config["centrosome"]["fixed_spacing"] = "0";
default_config["centrosome"]["alignment_potential"] = "0";
default_config["centrosome"]["k_spring"] = "1000";
default_config["centrosome"]["k_align"] = "0";
default_config["centrosome"]["spring_length"] = "0";
default_config["motor"]["diameter"] = "3";
default_config["motor"]["walker"] = "0";
default_config["motor"]["step_direction"] = "0";
default_config["motor"]["k_off"] = "2";
default_config["motor"]["k_on"] = "10";
default_config["motor"]["concentration"] = "0";
default_config["motor"]["velocity"] = "1";
default_config["motor"]["diffusion_flag"] = "1";
default_config["motor"]["k_spring"] = "1000";
default_config["motor"]["f_spring_max"] = "100";
default_config["bead_spring"]["diameter"] = "1";
default_config["bead_spring"]["length"] = "40";
default_config["bead_spring"]["persistence_length"] = "4000";
default_config["bead_spring"]["max_bond_length"] = "1";
default_config["bead_spring"]["bond_rest_length"] = "0.8";
default_config["bead_spring"]["bond_spring"] = "100";
default_config["bead_spring"]["driving_factor"] = "0";
default_config["bead_spring"]["lp_analysis"] = "0";
default_config["bead_spring"]["theta_analysis"] = "0";
default_config["bead_spring"]["packing_fraction"] = "-1";
default_config["spherocylinder"]["diameter"] = "1";
default_config["spherocylinder"]["length"] = "5";
default_config["spherocylinder"]["diffusion_analysis"] = "0";
default_config["spherocylinder"]["n_diffusion_samples"] = "1";
default_config["spherocylinder"]["midstep"] = "0";
default_config["spindle"]["diameter"] = "10";
default_config["spindle"]["length"] = "20";
default_config["spindle"]["n_filaments_bud"] = "1";
default_config["spindle"]["n_filaments_mother"] = "0";
default_config["spindle"]["alignment_potential"] = "0";
default_config["spindle"]["k_spring"] = "1000";
default_config["spindle"]["k_align"] = "0";
default_config["spindle"]["spring_length"] = "0";
default_config["spindle"]["spb_diameter"] = "5";
default_config["crosslink"]["concentration"] = "0";
default_config["crosslink"]["diameter"] = "1";
default_config["crosslink"]["walker"] = "0";
default_config["crosslink"]["velocity"] = "1";
default_config["crosslink"]["diffusion_flag"] = "0";
default_config["crosslink"]["k_on"] = "10";
default_config["crosslink"]["k_off"] = "2";
default_config["crosslink"]["k_on_d"] = "10";
default_config["crosslink"]["k_off_d"] = "2";
default_config["crosslink"]["force_dep_factor"] = "1";
default_config["crosslink"]["polar_affinity"] = "0";
default_config["crosslink"]["k_spring"] = "10";
default_config["crosslink"]["f_spring_max"] = "1000";
default_config["crosslink"]["f_stall"] = "100";
default_config["crosslink"]["force_dep_vel_flag"] = "1";
default_config["crosslink"]["k_align"] = "0";
default_config["crosslink"]["rest_length"] = "0";
default_config["crosslink"]["step_direction"] = "0";
default_config["crosslink"]["tether_draw_type"] = "orientation";
default_config["crosslink"]["tether_diameter"] = "0.5";
default_config["crosslink"]["tether_color"] = "3.1416";
default_config["crosslink"]["end_pausing"] = "0";
default_config["crosslink"]["r_capture"] = "5";
default_config["seed"] = "7859459105545";
default_config["n_runs"] = "1";
default_config["n_random"] = "1";
default_config["run_name"] = "sc";
default_config["n_dim"] = "3";
default_config["n_periodic"] = "0";
default_config["boundary"] = "0";
default_config["system_radius"] = "100";
default_config["n_steps"] = "1000000";
default_config["i_step"] = "0";
default_config["delta"] = "0.001";
default_config["cell_length"] = "10";
default_config["n_update_cells"] = "0";
default_config["graph_flag"] = "0";
default_config["n_graph"] = "1000";
default_config["graph_diameter"] = "0";
default_config["graph_background"] = "1";
default_config["draw_boundary"] = "1";
default_config["load_checkpoint"] = "0";
default_config["checkpoint_run_name"] = "sc";
default_config["n_load"] = "0";
default_config["print_complete"] = "0";
default_config["insertion_type"] = "species";
default_config["movie_flag"] = "0";
default_config["movie_directory"] = "frames";
default_config["time_analysis"] = "0";
default_config["bud_height"] = "680";
default_config["bud_radius"] = "300";
default_config["lj_epsilon"] = "1";
default_config["wca_eps"] = "1";
default_config["wca_sig"] = "1";
default_config["ss_a"] = "1";
default_config["ss_rs"] = "1.5";
default_config["ss_eps"] = "1";
default_config["f_cutoff"] = "2000";
default_config["max_overlap"] = "100000";
default_config["constant_pressure"] = "0";
default_config["constant_volume"] = "0";
default_config["target_pressure"] = "0";
default_config["target_radius"] = "100";
default_config["pressure_time"] = "100";
default_config["compressibility"] = "1";
default_config["stoch_flag"] = "1";
default_config["thermo_flag"] = "0";
default_config["n_thermo"] = "1000";
default_config["interaction_flag"] = "1";
default_config["species_insertion_failure_threshold"] = "10000";
default_config["species_insertion_reattempt_threshold"] = "10";
default_config["uniform_crystal"] = "0";
default_config["n_steps_equil"] = "0";
default_config["n_steps_target"] = "100000";
default_config["static_particle_number"] = "0";
default_config["checkpoint_from_spec"] = "0";
default_config["potential"] = "wca";
default_config["soft_potential_mag"] = "10";
default_config["soft_potential_mag_target"] = "-1";
default_config["like_like_interactions"] = "1";
default_config["auto_graph"] = "0";
default_config["local_order_analysis"] = "0";
default_config["local_order_width"] = "50";
default_config["local_order_bin_width"] = "0.5";
default_config["local_order_average"] = "1";
default_config["local_order_n_analysis"] = "100";
default_config["density_analysis"] = "0";
default_config["density_bin_width"] = "0.1";
default_config["density_com_only"] = "0";
default_config["polar_order_analysis"] = "0";
default_config["polar_order_n_bins"] = "100";
default_config["polar_order_contact_cutoff"] = "3";
default_config["polar_order_color"] = "0";
default_config["overlap_analysis"] = "0";
default_config["highlight_overlaps"] = "0";
default_config["reduced"] = "0";
default_config["reload_reduce_switch"] = "0";
default_config["flock_polar_min"] = "0.5";
default_config["flock_contact_min"] = "1.5";
default_config["highlight_flock"] = "0";
default_config["flock_color_ext"] = "1.57";
default_config["flock_color_int"] = "4.71";
default_config["in_out_flag"] = "0";
| 11,578 | 4,412 |
#include <windows.h>
#include <tchar.h>
#include <commctrl.h>
#include <richedit.h>
#include <iostream>
#include <string>
#include <atlstr.h>
#include <cassert>
#include "appconst.h"
#include "toolbarControl.h"
#include "statusControl.h"
#include "mainWindowProc.h"
#include "menuids.h"
#include "mainPrefs.h"
#include "fileIO.h"
#include "globalVars.h"
#include "recentFiles.h"
#include "translations.h"
#include "service.h"
//converts menuindex to vector index and gets the filename from the string vector
WPARAM convertMenu2VecIndex(WPARAM menuIndex) {
//use throw catch here if menuIndex<22
WPARAM vecIndex = recentDocsList.size()-(menuIndex-IDM_REC_CLEAR);
//WPARAM vecIndex = (menuIndex - IDM_REC_CLEAR - 1);
return vecIndex;
}
std::string getRecentlyOpenedFileName(WPARAM index) {
return recentDocsList.at(index);
}
int detectFileType(std::string strPath) {
int startingPos = strPath.length()-4-1;
return strPath.find("rtf",startingPos)==-1?1:2;
}
int getActivatedFileMode(void) {
return OPENMODE; //1 - txt, 2 - rtf.
}
LPCTSTR getCurrentlyOpenedFileName(void) {
return (LPCTSTR)currentlyOpenedFile;
}
DWORD CALLBACK EditStreamCallbackIn(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, PLONG pcb) {
HANDLE hFile = (HANDLE)dwCookie;
if (ReadFile(hFile, lpBuff, cb, (DWORD *)pcb, NULL)) {
return 0;
}
return -1;
}
DWORD CALLBACK EditStreamCallbackOut(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, PLONG pcb) {
HANDLE hFile = (HANDLE)dwCookie;
if (WriteFile(hFile, lpBuff, cb, (DWORD *)pcb, NULL)) {
return 0;
}
return -1;
}
void openFileDiag(HWND mainWindow, int mode) { //0 - open, 1 - save as {
int fileTypeSaveOpen = 0;
OPENFILENAME fileName;
TCHAR szFile[MAX_PATH];
ZeroMemory(&fileName, sizeof(fileName));
fileName.lStructSize = sizeof(fileName);
fileName.lpstrFile = szFile;
fileName.lpstrFile[0] = '\0';
fileName.hwndOwner = mainWindow;
fileName.nMaxFile = sizeof(szFile);
fileName.lpstrFilter = _T("Text Files (*.txt)\0*.txt\0RTF files (*.rtf)\0*.rtf*\0");
//_T("Text Files (*.txt)\0*.txt\0All Files (*.*)\0*.*\0");
fileName.nFilterIndex = OPENMODE; //1 - .txt, 2 - .rtf
if (mode) {
fileName.Flags =
OFN_PATHMUSTEXIST
| OFN_OVERWRITEPROMPT
| OFN_EXPLORER
| OFN_HIDEREADONLY;
}
else {
fileName.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
}
if (mode) {
if (GetSaveFileName(&fileName)) {
fileTypeSaveOpen = fileName.nFilterIndex;
loadSaveFile(fileName.lpstrFile,mode,fileTypeSaveOpen);
_tcscpy(currentlyOpenedFile, szFile);
SetWindowText(hwnd, getCurrentlyOpenedFileName());
changeStatusControlMessage(2);
fileChanged = false;
fileLoaded = true;
disableFastSaveIcon();
}
//usr canceled out
else {
fileChanged = true;
}
}
else {
if (GetOpenFileName(&fileName)) {
fileTypeSaveOpen = fileName.nFilterIndex;
loadSaveFile(fileName.lpstrFile,mode,fileTypeSaveOpen);
_tcscpy(currentlyOpenedFile,szFile);
SetWindowText(hwnd, getCurrentlyOpenedFileName());
changeStatusControlMessage(1);
fileLoaded = true;
fileChanged = false;
//append
if (!recentDocsList.size()) {
recentDocsList_push(getCurrentlyOpenedFileName(), 0);
}
//insert before currAddRecent-1
else {
recentDocsList_push(getCurrentlyOpenedFileName(), 1);
}
}
}
}
//stream mode: 1 - write to file, 0 - write to editor
void loadSaveFile(LPTSTR filePath, int streamMode, int fileType) {
streamMode?FillFileFromRichEdit((LPCTSTR(filePath)),fileType):FillRichEditFromFile((LPCTSTR)filePath,fileType);
}
//1 - txt, 2 - rtf
void FillRichEditFromFile(LPCTSTR pszFile, int fileType) {
//settings.recentDocsList.push_back(pszFile);
WPARAM OPENFILETYPE;
assert(fileType>0);
if (fileType == 1) {
OPENMODE = 1;
OPENFILETYPE = SF_TEXT;
}
else if (fileType == 2) {
OPENMODE = 2;
OPENFILETYPE = SF_RTF;
}
BOOL fSuccess = FALSE;
HANDLE hFile = CreateFile(pszFile, GENERIC_READ,
FILE_SHARE_READ, 0, OPEN_EXISTING,
FILE_FLAG_SEQUENTIAL_SCAN, NULL);
//file exists
if (hFile != INVALID_HANDLE_VALUE) {
EDITSTREAM es = {0}; //main stream structure
es.pfnCallback = EditStreamCallbackIn;
es.dwCookie = (DWORD_PTR)hFile;
if (SendMessage(richEditControl, EM_STREAMIN, OPENFILETYPE, (LPARAM)&es) && es.dwError == 0) {
fSuccess = TRUE;
}
CloseHandle(hFile);
//TODO change to string CA2T/CT2A
std::wstring str = CW2W(pszFile);
//incrementRecentDocs(str); non-functional
//setting titlebar text to file path
//TODO resolve for settings file
if (settings.bShowCompleteFilePathInTitle) {
setWindowTitleToFile(pszFile, 1);
}
else {
setWindowTitleToFile(pszFile, 0);
}
//cutoff
//txt clause block toolbar formatting
if (!OPENMODE) {
disableFormattingOptions();
}
else {
enableFormattingOptions();
}
//save pszFile to global tracker
}
else {
//if file isn't found
MessageBox(hwnd, commDlgMsgError_EN[1], commDlgMsgErrorCaptions_EN[0], MB_ICONERROR | MB_OK);
if (askForDeletion())
{
recentDocsList_delete(pszFile);
}
//TODO: Prompt to delete from the recent list of files
}
}
void saveFile(void)
{
//stub
}
void FillFileFromRichEdit(LPCTSTR pszFile, int fileType) {
WPARAM SAVEFILETYPE;
assert(fileType);
if (fileType == 1) {
_tcscat((wchar_t*)pszFile,txtExt); //appending extension
SAVEFILETYPE = SF_TEXT;
}
else if (fileType == 2) {
_tcscat((wchar_t*)pszFile, rtfExt);
SAVEFILETYPE = SF_RTF;
}
BOOL fSuccess = FALSE;
HANDLE hFile = CreateFile(pszFile, GENERIC_WRITE,
0, 0, CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile != INVALID_HANDLE_VALUE) {
EDITSTREAM es = { 0 }; //main stream structure
es.pfnCallback = EditStreamCallbackOut;
es.dwCookie = (DWORD_PTR)hFile;
if (SendMessage(richEditControl, EM_STREAMOUT, (CP_UTF8 << 16) | SF_USECODEPAGE | SF_TEXT, (LPARAM)&es) && es.dwError == 0)
{
fSuccess = TRUE;
}
//cursor goes back to normal here
CloseHandle(hFile);
_tcscpy(currentlyOpenedFile, pszFile);
}
else {
MessageBox(hwnd, commDlgMsgError_EN[0], commDlgMsgErrorCaptions_EN[0], MB_OK | MB_ICONERROR);
}
}
void silentSaving(void) {
//silentSaving();
//initWaitCursor();
FillFileFromRichEdit(getCurrentlyOpenedFileName(), getActivatedFileMode()); //EXPLICIT CALL BE CAREFUL HERE
//resetCursor();
//MessageBox(hwnd, _T("Silently saved"), _T("Notification"), MB_ICONINFORMATION | MB_OK);
changeStatusControlMessage(3);
SetWindowText(hwnd, getCurrentlyOpenedFileName());
fileChanged = false;
fileSaved = true;
disableFastSaveIcon();
}
void setWindowTitleToFile(LPCTSTR filePath, int mode)
{
TCHAR titleAppend[126];
LPCTSTR *file;
//complete
if (mode) {
_tcscpy(titleAppend, filePath);
_tcscat(titleAppend, _T(" - TexEdit"));
}
else {
file = cutoffFileName(filePath);
_tcscpy(titleAppend,(const wchar_t*)file);
}
SetWindowText(hwnd, titleAppend);
}
LPCTSTR *cutoffFileName(LPCTSTR fullPath) {
wchar_t fileNameExt[CHAR_MAX];
wchar_t drive[CHAR_MAX];
wchar_t dir[CHAR_MAX];
wchar_t fileName[CHAR_MAX];
wchar_t ext[CHAR_MAX];
_wsplitpath(fullPath,drive,dir,fileName,ext);
//LPCTSTR *res = (LPCTSTR*)_tcsrchr((const wchar_t*)fullPath,(wchar_t)'\\');
//assert(res);
//res = (LPCTSTR*)_tcstok((wchar_t*)res,(const wchar_t*)'\\');
_tcscpy(fileNameExt,fileName);
_tcscat(fileNameExt,ext);
return (LPCTSTR*)fileNameExt;
}
//save as
void initSavingAsSequence(void) {
openFileDiag(hwnd,1);
}
void initSilentSavingSequence(void) {
if (fileLoaded) {
if (fileChanged) {
silentSaving();
}
}
else {
if (fileChanged) {
openFileDiag(hwnd, 1);
}
else {
MessageBox(hwnd, _T("Save blanks prompt here"), _T("Notification"), MB_ICONINFORMATION | MB_OK);
}
}
}
//1 - txt, 2 - rtf
void fromRecent::initOpeningSequence(LPCTSTR filePath,int mode) {
if (fileLoaded) {
if (fileChanged) {
if (MessageBox(hwnd, _T("You have unsaved changes\nSave them now?"), _T("Warning"), MB_ICONWARNING | MB_YESNOCANCEL) == IDYES) {
silentSaving();
}
else{
FillRichEditFromFile(filePath, mode);
}
}
else {
FillRichEditFromFile(filePath, mode);
}
}
else {
if (fileChanged) {
switch (MessageBox(hwnd, _T("You have unsaved changes\nSave them now?"), _T("Warning"), MB_ICONWARNING | MB_YESNOCANCEL)) {
case IDYES: {
openFileDiag(hwnd, 1);
break;
}
case IDNO: {
FillRichEditFromFile(filePath, mode);
break;
}
case IDCANCEL: {
break;
}
}
}
else {
FillRichEditFromFile(filePath, mode);
//MessageBox(hwnd, _T("Save blanks prompt here"), _T("Notification"), MB_ICONINFORMATION | MB_OK);
}
}
}
void normal::initOpeningSequence(void) {
if (fileLoaded) {
if (fileChanged) {
if (MessageBox(hwnd, _T("You have unsaved changes\nSave them now?"), _T("Warning"), MB_ICONWARNING | MB_YESNOCANCEL) == IDYES) {
silentSaving();
}
else {
openFileDiag(hwnd,0);
}
}
else {
openFileDiag(hwnd,0);
}
}
else {
if (fileChanged) {
switch (MessageBox(hwnd, _T("You have unsaved changes\nSave them now?"), _T("Warning"), MB_ICONWARNING | MB_YESNOCANCEL)) {
case IDYES: {
openFileDiag(hwnd, 1);
break;
}
case IDNO: {
openFileDiag(hwnd, 0);
break;
}
case IDCANCEL: {
break;
}
}
}
else {
openFileDiag(hwnd,0);
//MessageBox(hwnd, _T("Save blanks prompt here"), _T("Notification"), MB_ICONINFORMATION | MB_OK);
}
}
}
//1 - txt, 2 - rtf
void initNewSequence(int mode) {
if (fileLoaded) {
if (fileChanged) {
if (MessageBox(hwnd, _T("You have unsaved changes\nSave them now?"), _T("Warning"), MB_ICONWARNING | MB_YESNOCANCEL) == IDYES) {
silentSaving();
}
else {
activateRespMode(mode);
}
}
else {
activateRespMode(mode);
}
}
else {
//bug with multiple new instances
if (fileChanged) {
switch (MessageBox(hwnd, _T("You have unsaved changes\nSave them now?"), _T("Warning"), MB_ICONWARNING | MB_YESNOCANCEL)) {
case IDYES: {
openFileDiag(hwnd, 1);
break;
}
case IDNO: {
activateRespMode(mode);
break;
}
case IDCANCEL: {
break;
}
}
}
else {
//MessageBox(hwnd, _T("Save blanks prompt here"), _T("Notification"), MB_ICONINFORMATION | MB_OK);
activateRespMode(mode);
}
}
}
void activateRespMode(int mode) {
if (mode == 2) {
activateNewRTFMode();
}
else if (mode == 1) {
activateNewTXTMode();
}
fileLoaded = false;
fileChanged = false;
} | 10,417 | 4,508 |
#include "OnlinePolicyGradient.h"
PolicyGradientActorCritic::PolicyGradientActorCritic(int n_states_, int n_actions_, real gamma_, real step_size_) :
n_states(n_states_),
n_actions(n_actions_),
gamma(gamma_),
step_size(step_size_),
critic(n_states, n_actions, gamma, 0.0, step_size),
policy(n_states, n_actions),
params(n_states, n_actions),
Q(n_states, n_actions)
{
Reset();
}
real PolicyGradientActorCritic::Observe(real reward, const int& next_state, const int& next_action)
{
real d = 0;
if (state >= 0) {
d = GradientUpdate(state, action); // not sure how much difference it makes to update the next state-action pair instead
//printf("%d %d %d %d%f\n", state, action, d);
Q(state, action) += step_size * (reward + gamma * Q(next_state, next_action) - Q(state, action));
}
critic.Observe(reward, next_state, next_action);
UpdatePolicy();
state = next_state;
action = next_action;
return d;
}
int PolicyGradientActorCritic::Act(real reward, const int& next_state)
{
policy.Observe(reward, next_state);
int next_action = policy.SelectAction();
Observe(reward, next_state, next_action);
return next_action;
}
real PolicyGradientActorCritic::GradientUpdate(int s, int a)
{
//real U = critic.getValue(s);
//real U = critic.getValue(s);
real U = Q(s,a);
printf("s:%d, a:%d: Q_w:%f Q_S:%f\n", s, a, U, critic.getValue(s,a));
real delta = 0;
for (int j=0; j<n_actions; ++j) {
real p_a = policy.getActionProbability(s, j);
real d_sj = 0;
if (j==a) {
d_sj = (1.0 - p_a) * U;
} else {
d_sj = -p_a * U;
}
params(s,j) += step_size * d_sj;
delta += fabs(d_sj);
}
return delta;
}
void PolicyGradientActorCritic::UpdatePolicy()
{
for (int s=0; s<n_states; ++s) {
Vector eW = exp(params.getRow(s));
eW /= eW.Sum();
Vector* pS = policy.getActionProbabilitiesPtr(s);
(*pS) = eW;
}
}
// --- PGAC with features --- //
PolicyGradientActorCriticPhi::PolicyGradientActorCriticPhi(BasisSet<Vector, int>& basis_,
int n_states_,
int n_actions_,
real gamma_,
real step_size_) :
basis(basis_),
n_states(n_states_),
n_actions(n_actions_),
gamma(gamma_),
step_size(step_size_),
critic(n_states, n_actions, basis, gamma),
policy(n_states, n_actions, basis), // bug?
params(basis.size())
{
Reset();
}
real PolicyGradientActorCriticPhi::Observe(real reward, const Vector& next_state, const int& next_action)
{
basis.Observe(action, reward, next_state);
real d = 0;
if (valid_state) {
d = GradientUpdate(state, action);
}
critic.Observe(reward, next_state, next_action);
UpdatePolicy();
state = next_state;
action = next_action;
valid_state = true;
return d;
}
int PolicyGradientActorCriticPhi::Act(real reward, const Vector& next_state)
{
basis.Observe(action, reward, next_state);
//Vector features = basis.F();
int next_action = policy.SelectAction(next_state);
Observe(reward, next_state, next_action);
return next_action;
}
real PolicyGradientActorCriticPhi::GradientUpdate(const Vector& s, int a)
{
basis.Observe(s);
Vector phi = basis.F();
// copy the state-features into a larger state-action feature vector
Vector features(phi.Size()*n_actions);
int k = a * phi.Size();
for (int i=0; i<phi.Size(); ++i) {
features(k) = phi(i);
}
real U = critic.getValue(s);
Vector delta = policy.GradientUpdate(s, a, U);
policy.GradientUpdateForward(delta, step_size);
return U;
}
void PolicyGradientActorCriticPhi::UpdatePolicy()
{
}
| 3,487 | 1,449 |
/*
* Copyright (C) 2018-2021 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "shared/source/os_interface/windows/os_time_win.h"
#include "shared/source/os_interface/windows/device_time_wddm.h"
#include "shared/source/os_interface/windows/wddm/wddm.h"
#include <memory>
#undef WIN32_NO_STATUS
namespace NEO {
bool OSTimeWin::getCpuTime(uint64_t *timeStamp) {
uint64_t time;
this->QueryPerfomanceCounterFnc((LARGE_INTEGER *)&time);
*timeStamp = static_cast<uint64_t>((static_cast<double>(time) * NSEC_PER_SEC / frequency.QuadPart));
return true;
};
std::unique_ptr<OSTime> OSTimeWin::create(OSInterface *osInterface) {
return std::unique_ptr<OSTime>(new OSTimeWin(osInterface));
}
OSTimeWin::OSTimeWin(OSInterface *osInterface) {
this->osInterface = osInterface;
Wddm *wddm = osInterface ? osInterface->getDriverModel()->as<Wddm>() : nullptr;
this->deviceTime = std::make_unique<DeviceTimeWddm>(wddm);
QueryPerformanceFrequency(&frequency);
}
double OSTimeWin::getHostTimerResolution() const {
double retValue = 0;
if (frequency.QuadPart) {
retValue = 1e9 / frequency.QuadPart;
}
return retValue;
}
uint64_t OSTimeWin::getCpuRawTimestamp() {
LARGE_INTEGER cpuRawTimestamp = {};
this->QueryPerfomanceCounterFnc(&cpuRawTimestamp);
return cpuRawTimestamp.QuadPart;
}
} // namespace NEO
| 1,386 | 521 |
//
// FILE NAME: CIDCtrls_ImgCacheItem.hpp
//
// AUTHOR: Dean Roddey
//
// CREATED: 10/28/2005
//
// COPYRIGHT: Charmed Quark Systems, Ltd @ 2019
//
// This software is copyrighted by 'Charmed Quark Systems, Ltd' and
// the author (Dean Roddey.) It is licensed under the MIT Open Source
// license:
//
// https://opensource.org/licenses/MIT
//
// DESCRIPTION:
//
// This is the header for the CIDCtrls_ImgCacheItem.cpp file, which implements
// a simple image cache item that various programs may want to use (after
// extending) to create an image cache.
//
// CAVEATS/GOTCHAS:
//
// LOG:
//
// $_CIDLib_Log_$
//
#pragma once
#pragma CIDLIB_PACK(CIDLIBPACK)
// ---------------------------------------------------------------------------
// CLASS: TImgCacheItem
// PREFIX: ici
// ---------------------------------------------------------------------------
class CIDGRDEVEXP TImgCacheItem : public TObject
{
public :
// -------------------------------------------------------------------
// Public, static methods
// -------------------------------------------------------------------
static const TString& strImgName
(
const TImgCacheItem& iciSrc
);
// -------------------------------------------------------------------
// Constructors and Destructor
// -------------------------------------------------------------------
TImgCacheItem
(
const TString& strImgName
, const tCIDLib::TBoolean bThumb
);
TImgCacheItem
(
const TString& strImgName
, const tCIDLib::TBoolean bThumb
, const tCIDLib::TCard4 c4Size
, const TBitmap& bmpData
, const tCIDLib::TBoolean bDeepCopy
);
TImgCacheItem
(
const TImgCacheItem& I_NsClientBindSearch
);
~TImgCacheItem();
// -------------------------------------------------------------------
// Public operators
// -------------------------------------------------------------------
TImgCacheItem& operator=
(
const TImgCacheItem& iciSrc
);
// -------------------------------------------------------------------
// Public, virtual methods
// -------------------------------------------------------------------
virtual tCIDLib::TVoid Reset
(
const TString& strImgName
, const tCIDLib::TBoolean bThumb
);
virtual tCIDLib::TVoid Set
(
const tCIDLib::TBoolean bThumb
, const tCIDLib::TCard4 c4Size
, const TMemBuf& mbufData
, const tCIDLib::TCard4 c4SerialNum
, const TGraphDrawDev& gdevCompat
);
// -------------------------------------------------------------------
// Public, non-virtual methods
// -------------------------------------------------------------------
tCIDLib::TBoolean bHasAlpha() const;
tCIDLib::TBoolean bStillGood
(
const TString& strExpiresStamp
) const;
tCIDLib::TBoolean bThumb() const;
tCIDLib::TBoolean bTransparent() const;
const TBitmap& bmpImage() const;
const TBitmap& bmpMask() const;
tCIDLib::TCard4 c4SerialNum() const;
tCIDLib::TCard4 c4Size() const;
tCIDLib::TCard4 c4TransClr() const;
tCIDLib::TVoid DropImage();
tCIDLib::TEncodedTime enctLastAccess() const;
tCIDLib::TEncodedTime enctLastCheck() const;
tCIDLib::TEncodedTime enctGoodTill() const;
const TString& strExpiresStamp() const;
const TString& strExpiresStamp
(
const TString& strToSet
);
const TString& strImageName() const;
const TString& strTagData() const;
const TString& strTagData
(
const TString& strToSet
);
tCIDLib::TVoid SetLastAccess();
tCIDLib::TVoid SetLastCheck();
tCIDLib::TVoid SetGoodTill
(
const tCIDLib::TCard4 c4Seconds
);
const TSize& szImage() const;
protected :
// -------------------------------------------------------------------
// Protected, non-virtual methods
// -------------------------------------------------------------------
TBitmap& bmpWriteable();
private :
// -------------------------------------------------------------------
// Private data members
//
// m_bThumb
// Indicatse if this is a thumbnail or the full size image.
//
// m_bTrans
// Indicates if this a color based transparency image. If so, then the
// mask images are needed for drawing.
//
// m_bmpImage
// m_bmpMask
// The image and the mask for the image if it is transparent.
//
// m_c4Size
// The size of the original raw image data, so we'll know how much is
// required if we have to send it.
//
// m_enctLastAccess
// Updated each time the image is accessed, and used to do a least recently
// used algorithm if our cache gets full.
//
// m_enctLastCheck
// The last time that the client code checked to see if the image
// is still up to date with any external source. This can be
// used to prevent repeated checks when the image is accessed
// multipled times quickly.
//
// m_enctGoodTill
// In some cases, it's known that an image will be valid for some length of
// time, in which case this can be set and used to avoid re-validating the
// cached image for that period. Defaults to zero, which means it will by
// default never be good.
//
// m_c4TransClr
// If color transparency based (m_bTrans is true), then this is the color that
// was used to create the masks.
//
// m_strExpiresStamp
// This is used to store an expiration stamp, generally for use with HTTP
// servers, which may provide such a stamp. If it provides a max-age that
// will be set via the SetGoodTill and will override this. If the good till
// is zero, then we try this guy.
//
// m_strImageName
// The original name of the image, whihc is whatever is meaningful
// to the user of this class.
//
// m_strTagData
// This is for the use of the application, to store some kind of tag info.
//
// m_szImage
// Get the size out up front, since we have to return it fairly often, and
// the bitmap itself returns it by value, so we can be more efficient.
// -------------------------------------------------------------------
tCIDLib::TBoolean m_bThumb;
tCIDLib::TBoolean m_bTrans;
TBitmap m_bmpImage;
TBitmap m_bmpMask;
tCIDLib::TCard4 m_c4Size;
tCIDLib::TCard4 m_c4TransClr;
tCIDLib::TEncodedTime m_enctLastAccess;
tCIDLib::TEncodedTime m_enctLastCheck;
tCIDLib::TEncodedTime m_enctGoodTill;
TString m_strExpiresStamp;
TString m_strImageName;
TString m_strTagData;
TSize m_szImage;
// -------------------------------------------------------------------
// Magic Macros
// -------------------------------------------------------------------
RTTIDefs(TImgCacheItem,TObject)
};
// ---------------------------------------------------------------------------
// Define a counter pointer to an image cache object. This is what normally would be
// handed out to callers when they want to use an image. This insures that the image
// will not be dropped from the cache as long as someone is holding it.
// ---------------------------------------------------------------------------
using TImgCacheItemPtr = TCntPtr<TImgCacheItem>;
inline const TString&
strExtractImgCacheItemPtrKey(const TImgCacheItemPtr& cptrSrc)
{
return cptrSrc->strImageName();
}
#pragma CIDLIB_POPPACK
| 8,778 | 2,311 |
/*!
* \file digital_out.hpp
* \brief Header file for digital out gpio state.
* \author garciay.yann@gmail.com
* \copyright Copyright (c) 2015 ygarcia. All rights reserved
* \license This project is released under the MIT License
* \version 0.1
*/
#pragma once
#include "libhal.h"
/*!
* \class digital_out
* \brief digital output gpio state
* @see ::digital_write
*/
class digital_out {
protected:
/*! The gpio idenifier */
pin_name _gpio;
/*! The gpio state */
digital_state_t _state;
public:
/*!
* \brief Constructor
* State is set to low
* \param[in] The gpio to connect
*/
digital_out(const pin_name p_gpio_name) : _gpio(p_gpio_name), _state(digital_state_t::digital_state_low) { ::digital_write(_gpio, _state); };
/*!
* \brief Constructor
* \param[in] The gpio to connect
* \param[in] p_state The gpio state
*/
digital_out(const pin_name p_gpio_name, const digital_state_t p_state) : _gpio(p_gpio_name), _state(p_state) { ::digital_write(_gpio, _state); };
/*!
* \brief Destructor
* The gpio state is set to low before to destroy this class reference
*/
virtual ~digital_out() { ::digital_write(_gpio, digital_state_t::digital_state_low); };
/*!
* \brief Set the gpio state
* \param[in] The new gpio state
*/
inline void write(const digital_state_t p_state) { _state = p_state; ::digital_write(_gpio, _state); };
/*!
* \brief Indicates the gpio state
* \return The gpio state
* @see digital_state_t
*/
inline digital_state_t read() const { return _state; };
inline digital_out & operator = (const digital_state_t p_state) { write(p_state); return *this; };
inline digital_out & operator = (const digital_out & p_gpio) { write(p_gpio.read()); return *this; };
inline operator const digital_state_t() const { return read(); };
}; // End of class digital_out
| 1,869 | 671 |
//Memory get free as scope ends and this pointers can have copy of them.
#include<iostream>
#include<memory>
using namespace std;
class User{
public:
User(){
cout<<"User Created\n";
}
~User(){
cout<<"User Destroyed\n";
}
void testFunc(){
cout<<"I am a test function\n";
}
};
int main(){
{
shared_ptr<User> tim = make_shared<User>();
weak_ptr<User> wtim = tim; // Created a weak pointer
shared_ptr<User> yo = wtim.lock(); // Using weak pointer back to shared
yo->testFunc();
}
cout<<"Outside scope\n";
return 0;
} | 629 | 208 |
#include "ResourceShaderProgram.h"
#include "Application.h"
#include "ModuleShaders.h"
#include "JSONManager.h"
ResourceShaderProgram::ResourceShaderProgram() : Resource(RES_SHADER)
{
}
ResourceShaderProgram::ResourceShaderProgram(std::string& file) : Resource(RES_SHADER, file)
{
}
ResourceShaderProgram::~ResourceShaderProgram()
{
}
bool ResourceShaderProgram::CompileShaderProgram()
{
bool ret = false;
uint tmp_program_index = 0;
std::vector<uint> indexList;
for (std::vector<uint>::iterator it = shaderObjects.begin(); it != shaderObjects.end(); it++)
{
bool isVertex = false;
char* data = App->shaders->FindShaderObjectFromUID(*it, isVertex);
uint index = 0;
if (App->shaders->CompileShader(data, isVertex, &index))
indexList.push_back(index);
}
if(App->shaders->CreateShaderProgram(indexList, &program));
ret = true;
return ret;
}
void ResourceShaderProgram::AddNewObjectToProgram(uint uuid)
{
bool isVertex = false;
if (App->shaders->FindShaderObjectFromUID(uuid, isVertex))
{
shaderObjects.push_back(uuid);
JSON_File* hmm = App->JSON_manager->openWriteFile(("Library\\ShaderPrograms\\" + file).c_str());
JSON_Value* val = hmm->createValue();
for (std::vector<uint>::iterator item = shaderObjects.begin(); item != shaderObjects.end(); item++)
{
val->addUint("uid", (*item));
}
hmm->addValue("", val);
hmm->Write();
hmm->closeFile();
CompileShaderProgram();
}
}
bool ResourceShaderProgram::ContainsShader(uint uuid)
{
for (std::vector<uint>::iterator item = shaderObjects.begin(); item != shaderObjects.end(); item++)
{
if ((*item) == uuid)
{
return true;
}
}
return false;
}
| 1,656 | 612 |
// Copyright 2017 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 "mojo/public/cpp/bindings/lib/buffer.h"
#include <cstring>
#include "base/check_op.h"
#include "base/notreached.h"
#include "base/numerics/safe_math.h"
#include "mojo/public/c/system/message_pipe.h"
#include "mojo/public/cpp/bindings/lib/bindings_internal.h"
namespace mojo {
namespace internal {
Buffer::Buffer() = default;
Buffer::Buffer(void* data, size_t size, size_t cursor)
: data_(data), size_(size), cursor_(cursor) {
DCHECK(IsAligned(data_));
}
Buffer::Buffer(MessageHandle message,
size_t message_payload_size,
void* data,
size_t size)
: message_(message),
message_payload_size_(message_payload_size),
data_(data),
size_(size),
cursor_(0) {
DCHECK(IsAligned(data_));
}
Buffer::Buffer(Buffer&& other) {
*this = std::move(other);
}
Buffer::~Buffer() = default;
Buffer& Buffer::operator=(Buffer&& other) {
message_ = other.message_;
message_payload_size_ = other.message_payload_size_;
data_ = other.data_;
size_ = other.size_;
cursor_ = other.cursor_;
other.Reset();
return *this;
}
size_t Buffer::Allocate(size_t num_bytes) {
const size_t aligned_num_bytes = Align(num_bytes);
const size_t new_cursor = cursor_ + aligned_num_bytes;
if (new_cursor < cursor_ || (new_cursor > size_ && !message_.is_valid())) {
// Either we've overflowed or exceeded a fixed capacity.
NOTREACHED();
return 0;
}
if (new_cursor > size_) {
// If we have an underlying message object we can extend its payload to
// obtain more storage capacity.
DCHECK_LE(message_payload_size_, new_cursor);
size_t additional_bytes = new_cursor - message_payload_size_;
DCHECK(base::IsValueInRangeForNumericType<uint32_t>(additional_bytes));
uint32_t new_size;
MojoResult rv = MojoAppendMessageData(
message_.value(), static_cast<uint32_t>(additional_bytes), nullptr, 0,
nullptr, &data_, &new_size);
DCHECK_EQ(MOJO_RESULT_OK, rv);
message_payload_size_ = new_cursor;
size_ = new_size;
}
DCHECK_LE(new_cursor, size_);
size_t block_start = cursor_;
cursor_ = new_cursor;
// Ensure that all the allocated space is zeroed to avoid uninitialized bits
// leaking into messages.
//
// TODO(rockot): We should consider only clearing the alignment padding. This
// means being careful about generated bindings zeroing padding explicitly,
// which itself gets particularly messy with e.g. packed bool bitfields.
memset(static_cast<uint8_t*>(data_) + block_start, 0, aligned_num_bytes);
return block_start;
}
bool Buffer::AttachHandles(std::vector<ScopedHandle>* handles) {
DCHECK(message_.is_valid());
uint32_t new_size = 0;
MojoResult rv = MojoAppendMessageData(
message_.value(), 0, reinterpret_cast<MojoHandle*>(handles->data()),
static_cast<uint32_t>(handles->size()), nullptr, &data_, &new_size);
if (rv != MOJO_RESULT_OK)
return false;
size_ = new_size;
for (auto& handle : *handles)
ignore_result(handle.release());
handles->clear();
return true;
}
void Buffer::Seal() {
if (!message_.is_valid())
return;
// Ensure that the backing message has the final accumulated payload size.
DCHECK_LE(message_payload_size_, cursor_);
size_t additional_bytes = cursor_ - message_payload_size_;
DCHECK(base::IsValueInRangeForNumericType<uint32_t>(additional_bytes));
MojoAppendMessageDataOptions options;
options.struct_size = sizeof(options);
options.flags = MOJO_APPEND_MESSAGE_DATA_FLAG_COMMIT_SIZE;
void* data;
uint32_t size;
MojoResult rv = MojoAppendMessageData(message_.value(),
static_cast<uint32_t>(additional_bytes),
nullptr, 0, &options, &data, &size);
DCHECK_EQ(MOJO_RESULT_OK, rv);
message_ = MessageHandle();
message_payload_size_ = cursor_;
data_ = data;
size_ = size;
}
void Buffer::Reset() {
message_ = MessageHandle();
data_ = nullptr;
size_ = 0;
cursor_ = 0;
}
} // namespace internal
} // namespace mojo
| 4,235 | 1,443 |
#include <concepts>
template <typename T>
concept type_test = requires {
typename T::ElementType; // ElementType member type must exist
};
void function(type_test auto x) {}
struct X { using ElementType = int; };
int main() {
function(X{}); // OK
function(1); // Fails
}
| 281 | 93 |
#include "deadeye.h"
#include <chrono>
#include <thread>
using namespace deadeye;
namespace {
constexpr auto NTGT_SLEEP_MS = std::chrono::milliseconds(10);
}
Deadeye::Deadeye(std::shared_ptr<cpptoml::table> config)
: logger_(spdlog::get("deadeye")),
link_(config),
boiler_camera_(config),
gear_camera_(config) {
LoadConfigSettings(config);
link_.Start();
}
/**
* Main loop for camera frame aquistion and processing.
*/
void Deadeye::Run() {
while (true) {
int mode = link_.GetMode();
if (mode != current_mode_) {
logger_->info("switching mode to: {}", mode);
SwitchMode(mode);
current_mode_ = mode;
}
switch (mode) {
case Link::Mode::boiler:
ProcessBoilerTarget();
break;
case Link::Mode::gear:
ProcessGearTarget();
break;
case Link::Mode::idle:
std::this_thread::sleep_for(NTGT_SLEEP_MS);
continue;
}
}
}
/**
* Switch active mode.
*/
void Deadeye::SwitchMode(int mode) {
switch (mode) {
case Link::Mode::boiler:
logger_->info("Deadeye switching to boiler camera capture");
SPDLOG_TRACE(logger_, "start StopCapture");
if (!boiler_camera_.IsConnected()) {
SPDLOG_TRACE(logger_, "start Connect");
boiler_camera_.Connect();
}
SPDLOG_TRACE(logger_, "start StartCapture");
boiler_camera_.StartCapture();
SPDLOG_TRACE(logger_, "done configuring camera");
break;
case Link::Mode::gear:
logger_->info("Deadeye switching to gear camera capture");
boiler_camera_.StopCapture();
if (!gear_camera_.IsConnected()) {
gear_camera_.Connect();
}
break;
case Link::Mode::idle:
logger_->info("deadeye mode set to idle");
boiler_camera_.StopCapture();
break;
default:
logger_->info("EnableCamera called with unknown mode");
}
}
/**
* Called in boiler mode after frame acquired.
*/
void Deadeye::ProcessBoilerTarget() {
#ifdef LOG_FPS
static int framerate_count = 0;
if (framerate_count == 0) {
fps_.Start();
}
if (framerate_count++ > display_framerate_int_) {
fps_.Stop();
logger_->info("FPS = {}", fps_.FramesPerSecond());
framerate_count = 0;
}
fps_.Update();
#endif
int centerline_error; // vertical target separation
int azimuth_error;
bool success = boiler_camera_.ProcessFrame(azimuth_error, centerline_error);
#ifdef DISPLAY_FRAME
boiler_camera_.DisplayFrame();
#endif
#ifdef LOG_BOILER
static int boiler_count = 0;
if (boiler_count++ > display_boiler_int_) {
logger_->info("boiler acquired = {}, azimuth = {}, centerline = {}",
success, azimuth_error, centerline_error);
boiler_count = 0;
}
#endif
if (success) {
link_.SendBoilerSolution(azimuth_error, centerline_error);
return;
}
// logger_->warn("boiler targets not visible");
link_.SendNoTarget();
std::this_thread::sleep_for(NTGT_SLEEP_MS);
}
void Deadeye::ProcessGearTarget() {
#ifdef LOG_FPS
static int framerate_count = 0;
if (framerate_count == 0) {
fps_.Start();
}
if (framerate_count++ > display_framerate_int_) {
fps_.Stop();
logger_->info("FPS = {}", fps_.FramesPerSecond());
framerate_count = 0;
}
fps_.Update();
#endif
int azimuth_error;
int target_height;
bool success = gear_camera_.ProcessFrame(azimuth_error, target_height);
#ifdef DISPLAY_FRAME
gear_camera_.DisplayFrame();
#endif
#ifdef LOG_GEAR
static int gear_count = 0;
if (gear_count++ > display_gear_int_) {
logger_->info("gear acquired = {}, azimuth = {}, target height = {}",
success, azimuth_error, target_height);
gear_count = 0;
}
#endif
if (success) {
link_.SendGearSolution(azimuth_error, target_height);
return;
}
link_.SendNoTarget();
std::this_thread::sleep_for(NTGT_SLEEP_MS);
}
void Deadeye::LoadConfigSettings(
const std::shared_ptr<cpptoml::table> config_in) {
assert(config_in);
auto config = config_in->get_table("DEADEYE")->get_table("DEBUG");
#ifdef LOG_FPS
auto framerate_opt = config->get_as<int>("framerate");
if (framerate_opt) {
display_framerate_int_ = *framerate_opt;
}
logger_->warn("logging framerate every {} frames", display_framerate_int_);
#else
logger_->info("framerate logging disabled");
#endif
#ifdef LOG_BOILER
auto boiler_opt = config->get_as<int>("boiler");
if (boiler_opt) {
display_boiler_int_ = *boiler_opt;
}
logger_->warn("logging boiler solution every {} frames", display_boiler_int_);
#else
logger_->info("boiler solution logging disabled");
#endif
#ifdef LOG_GEAR
auto gear_opt = config->get_as<int>("gear");
if (gear_opt) {
display_gear_int_ = *gear_opt;
}
logger_->warn("logging gear solution every {} frames", display_gear_int_);
#else
logger_->info("gear solution logging disabled");
#endif
}
| 4,886 | 1,743 |
/*
To use .lib file, go to Project > References... > Configuration Properties > Linker >
> General > Additional Library directories | add the directory the .lib is in.
Then go to Project > References... > Configuration Properties > Linker > Input > Additional dependencies |
add the name of the .lib file ("<name>.lib")
*/
/*
Image taking proccess is currently under a second, compare efficiency of GUI verses our technique
*/
/* TODO:
- Allow users to input date format using strptime()
- Make a Makefile to make building project with other compilers
*/
#include "stdafx.h"
#include <cstdio>
#include <direct.h>
#include "fitsio.h"
#include "getopt.h"
#include <iostream>
#include "longnam.h"
#include <sstream>
#include "Shlwapi.h"
#include <string>
#include <time.h>
#include "SXUSB.h"
#include <Windows.h>
/* for camera */
#define NUMBER_OF_CAMERAS 1
#define PIXEL_WIDTH 1392
#define PIXEL_HEIGHT 1040
/* for hdus */
#define OBJECT "allsky"
#define ORIGIN ""
#define TELESCOP ""
#define INSTRUME "Starlight Xpress Oculus"
#define OBSERVER "UMD Observatory"
/* path info */
#ifdef MAX_PATH
#define MAX_FILE_LEN MAX_PATH
#else
#define MAX_FILE_LEN 1024
#endif
bool dirExists(const char *);
bool my_mkdir(char *);
bool unix_mkdir(const char *);
bool windows_mkdir(const char *);
int numDigits(int);
int takeStandardImage(HANDLE handle, int camIndex, USHORT *pixelArray, struct Params * params);
int writeImage(HANDLE handle, int camIndex, USHORT *pixelArray, char *, struct Params * params);
int writeMultipleImages(HANDLE handle, int camIndex, USHORT *pixelArray, struct Params * params);
std::string getDate();
std::string getTime();
std::string numberToString(int number);
void correctDir(char dir[]);
void printError(int, const char *);
void setDate(fitsfile *, int);
struct Params /* structure used to store parameter information */
{
bool overwrite; /* -f */
bool verbose; /* -v */
char dirName[MAX_PATH]; /* -d <string> */
char observatory[MAX_PATH]; /* -o <string> */
char templateName[MAX_PATH]; /* -t <string> */
float exposure; /* -e <float> NOTE: in seconds */
float sleepTime; /* -s <float> Sleep time in between taking images */
int dateOption; /* -u <int> */
int initialIndex; /* -i <int> */
int numImages; /* -n <int> */
Params():
overwrite(false),
verbose(false),
exposure(1.0),
sleepTime(0.0),
dateOption(0),
initialIndex(0),
numImages(1){}
};
/* declare these out here so that memory is stored in the heap */
USHORT pixels[PIXEL_WIDTH * PIXEL_HEIGHT];
/* constants */
short const BITPIX = USHORT_IMG;
short const NAXIS = 2;
short const NAXIS1 = PIXEL_HEIGHT;
short const NAXIS2 = PIXEL_WIDTH;
const long NAXES[2] = {PIXEL_WIDTH, PIXEL_HEIGHT};
int main(int argc, char **argv)
{
/* local variables */
HANDLE handles[NUMBER_OF_CAMERAS];
t_sxccd_params cam_params[NUMBER_OF_CAMERAS];
long firmwareVersions[NUMBER_OF_CAMERAS];
int openVal, cameraModels[NUMBER_OF_CAMERAS];
struct Params *params = new Params();
/* default values for strings in params */
strcpy(params->dirName, "test_data\\");
strcpy(params->templateName, "IMG%05d.fits");
strcpy(params->observatory, "defaultObs");
/* parse command line arguments */
int c;
while ((c = getopt(argc, argv, "o:e:n:d:t:s:i:ufv")) != -1)
switch (c){
case 'o':
strcpy(params->observatory, optarg);
break;
case 'e':
params->exposure = strtol(optarg, NULL, 10);
break;
case 'n':
params->numImages = strtol(optarg, NULL, 10);
break;
case 'd':
strcpy(params->dirName, optarg);
break;
case 't':
strcpy(params->templateName, optarg);
break;
case 's':
params->sleepTime = strtol(optarg, NULL, 10);
break;
case 'u':
params->dateOption = strtol(optarg, NULL, 10);
break;
case 'i':
params->initialIndex = strtol(optarg, NULL, 10);
break;
case 'f':
params->overwrite = true;
break;
case 'v':
params->verbose = true;
break;
default:
break;
}
/* open the connected cameras */
openVal = sxOpen(handles);
if (params->verbose){
printf("Opened Cameras: %d\n", openVal);
}
/* error check the number of cameras */
if (openVal > NUMBER_OF_CAMERAS){
printf("MORE CAMERAS CONNECTED (%d) THAN SPECIFIED BY CODE (%d)\nTERMINATING PROGRAM\n", openVal, NUMBER_OF_CAMERAS);
return 0;
}
if (openVal < NUMBER_OF_CAMERAS){
printf("LESS CAMERAS CONNECTED (%d) THAN SPECIFIED BY CODE (%d)\nCODE WILL RUN, MEMEORY WILL BE WASTED\n", openVal, NUMBER_OF_CAMERAS);
}
/* Get and display camera information */
for (int i = 0; i < openVal; i++){
if (params->verbose){
printf("Camera %d:\n", i);
printf("\tCamera Firmware Version: %d\n", (firmwareVersions[i] = sxGetFirmwareVersion(handles[i])));
printf("\tCamera Model: %d\n", (cameraModels[i] = sxGetCameraModel(handles[i])));
}
sxGetCameraParams(handles[i], i, cam_params);
}
/* Taking images */
writeMultipleImages(handles[0], 0, pixels, params);
return 0;
}
/**
Takes an image with a connected camera. The camera exposes for the given time and then reads the image into pixels
@param exposure - this is measured in milliseconds
@return - 1 if the image was taken correctly, 0 if the image had an error. Will attempt to print error message.
*/
int takeStandardImage(HANDLE handle, int camIndex, USHORT *pixelArray, struct Params *params){
try{
int bytesRead;
/* clear pixels on the camera and expose them to take the image */
sxClearPixels(handle, 0x00, camIndex);
sxExposePixels(handle, 0x8B, camIndex, 0, 0, PIXEL_WIDTH, PIXEL_HEIGHT, 1, 1, (ULONG) (params->exposure * 1000));
/* read the pixels from the camera into an array */
if ((bytesRead = sxReadPixels(handle, pixelArray, PIXEL_WIDTH * PIXEL_HEIGHT)) <= 0){
printf("Error reading pixels\n");
return 0;
}
}
catch(int e){
printf("Error while taking image. Error number: %d\n", e);
return 0;
}
return 1;
}
/**
attempts to take multiple images with the camera stored in handle with an index of camIndex. This function will expose, read, and write the images
on its own.
@return - number of images successfully written.
*/
int writeMultipleImages(HANDLE handle, int camIndex, USHORT *pixelArray, struct Params * params){
int imagesTaken = 0;
char newPath[MAX_PATH];
if (params->verbose){
printf("Attempting to write %d images\n", params->numImages);
}
for (int i = 0; i < params->numImages; i++){
try{
/* <templateName>.fits */
sprintf_s(newPath, MAX_PATH - 1, params->templateName, imagesTaken + params->initialIndex);
writeImage(handle, camIndex, pixelArray, newPath, params);
}
catch(int e){
printf("CAUGHT ERROR %d while taking multiple images, stopped after %d images\n", e, imagesTaken);
return imagesTaken;
}
imagesTaken++;
Sleep(params->sleepTime);
}
if (params->verbose){
printf("Succeeded writing %d images\n", imagesTaken);
}
return imagesTaken;
}
/**
writes image to given pixelArray to path (NOTE: path does not include extension, that is added by the function).
@return - 0 if failed, 1 if successfully wrote image.
*/
int writeImage(HANDLE handle, int camIndex, USHORT *pixelArray, char * filename, struct Params * params){
takeStandardImage(handle, 0, pixels, params);
/* set up a fits file with proper hdu to write to a file */
fitsfile *file;
int status = 0;
char newPath[MAX_PATH], finalPath[MAX_PATH];
printf("*Before my_mkdir(): %s\n", params->dirName);
my_mkdir(params->dirName);
strcpy(newPath, params->dirName);
strcat(newPath, filename);
printf("*After strcat(): %s\n", params->dirName);
/* if overwrite flag is true add an '!' to the front so that fitsio overwrites files of
of the same name */
if (params->overwrite == true){
strcpy(finalPath, "!");
strcat(finalPath, newPath);
}
else{
strcpy(finalPath, newPath);
}
if (params->verbose){
printf("Writing %s\n", finalPath);
}
if (fits_create_file(&file, finalPath, &status)){
/*fits_report_error(stdout, status);*/
printError(status, "writeImage, while creating file");
}
/* basic header information (BITPIX, NAXIS, NAXES, etc) is taken care of through this function as well) */
if (fits_create_img(file, BITPIX, NAXIS, (long *) NAXES, &status)){
printError(status, "writeImage, while creating image");
}
/* extended header information */
if (fits_write_key(file, TSTRING, "OBJECT", OBJECT, "", &status)){
printError(status, "writeImage, while writing OBJECT");
}
if (fits_write_key(file, TSTRING, "TELESCOP", TELESCOP, "", &status)){
printError(status, "writeImage, while writing TELESCOP");
}
if (fits_write_key(file, TSTRING, "ORIGIN", ORIGIN, "", &status)){
printError(status, "writeImage, while writing ORIGIN");
}
if (fits_write_key(file, TSTRING, "INSTRUME", INSTRUME, "", &status)){
printError(status, "writeImage, while writing INSTRUME");
}
if (fits_write_key(file, TSTRING, "OBSERVER", (void *) params->observatory, "", &status)){
printError(status, "writeImage, while writing OBSERVER");
}
if (fits_write_key(file, TFLOAT, "EXPTIME", (void *) &(params->exposure), "", &status)){
printError(status, "writeImage, while writing EXPTIME");
}
/* find the current date and time and write it to a keyword(s) */
setDate(file, params->dateOption);
/* write the image data to the file */
if (fits_write_img(file, TUSHORT, 1, PIXEL_HEIGHT * PIXEL_WIDTH, pixels, &status)){
fits_report_error(stderr, status);
}
/* close the file */
if (fits_close_file(file, &status)){
fits_report_error(stdout, status);
}
return 1;
}
/**
returns number of digits in an int
*/
int numDigits(int number){
int length = 1;
while ( number /= 10 )
length++;
return length;
}
/**
returns the time in the format HH:MM:DD as a string in UTC time
*/
std::string getTime(){
time_t rawtime;
struct tm * ptm;
time(&rawtime);
/* pointer to time object with UTC time */
ptm = gmtime(&rawtime);
;
int hours = ptm->tm_hour;
int minutes = ptm->tm_min;
int seconds = ptm->tm_sec;
/* pad the hours, minutes, seconds with a zero if its only 1 digit long eg. 0-9) */
std::string h = std::string(2 - numDigits(hours), '0').append(numberToString(hours));
std::string m = std::string(2 - numDigits(minutes), '0').append(numberToString(minutes));
std::string s = std::string(2 - numDigits(seconds), '0').append(numberToString(seconds));
std::string time = h + ":" + m + ":" + s;
//@TODO check if seconds could contain the fractional seconds as well
return time;
}
/**
returns the data in the format YYYY-MM-DD as a string in UTC time
*/
std::string getDate(){
time_t rawtime;
struct tm * ptm;
time(&rawtime);
/* pointer to time object with UTC time */
ptm = gmtime(&rawtime);
int year = ptm->tm_year + 1900; /* ptm->tm_year == years since 1900 */
int month = ptm->tm_mon + 1;
int day = ptm->tm_mday;
/* pad the months with a zero if its only 1 digit long eg. 0-9) */
std::string y = numberToString(year);
std::string m = std::string(2 - numDigits(month), '0').append(numberToString(month));
std::string d = std::string(2 - numDigits(day), '0').append(numberToString(day));
std::string date = y + "-" + m + "-" + d;
return date;
}
/**
converts an int into a string
*/
std::string numberToString(int Number)
{
std::stringstream ss;
ss << Number;
return ss.str();
}
/**
Sets the date of the fits file in the HDU and the time (in universal time)
@param option 0: format is DATE-OBS: <YYYY>-<MM>-<DD>
TIME-OBS: <HH>:<MM>:<SS>
1: format is DATE-OBS: <YYYY>-<MM>-<DD>T<HH>:<MM>:<SS>
*/
void setDate(fitsfile *file, int option){
int status = 0;
std::string date = getDate();
std::string time = getTime();
if (option == 0){
if (fits_write_key(file, TSTRING, "DATE-OBS", (void *) date.c_str(), "", &status)){
printError(status, "setDate while writing keyword DATE-OBS");
}
if (fits_write_key(file, TSTRING, "TIME-OBS", (void *) time.c_str(), "", &status)){
printError(status, "setDate while writing keyword TIME-OBS");
}
}
else if (option == 1){
if (fits_write_key(file, TSTRING, "DATE-OBS", (void *) (date.append("T").append(time)).c_str(), "", &status)){
printError(status, "setDate while writing keyword DATE-OBS, option == 1");
}
}
else{
printf("INCORRECT USE OF setDate() INVALID PARAMETER OPTION (must be 0 or 1, your input: %d)", option);
}
}
/* Note: for proper output, include function name at beginning of message */
void printError(int status, const char * message){
printf("(FITSIO) ERROR OCCURED IN FUNCTION %s, STATUS NUMBER: %d\n", message, status);
}
/**
Checks if the directory exists, if it does not, creates it
NOTE: will add a \ to the end of dir if it does not end in one
@return true if it creates it or it already exists
false if it could not create the directory
*/
bool windows_mkdir(char * dir){
correctDir(dir); // correct the directory if it doesnt end in a slash
unsigned int i = 0;
/* the logic here is that _mkdir cannot create two new directories inside of each other at the same time
(first create \firstDir\ then /firstDir/secondDir/ rather than at the same time)
so we copy the original directory over to a temporary and everytime it meets a \ create that directory
then once at the end of the string, make that directory too even if it didn't end in a back slash
*/
char temp[MAX_PATH];
while (i < strlen(dir)){
/* copy the current character */
temp[i] = dir[i];
/* if its a backslash, create the directory if it doesn't already exist */
if (dir[i] == '\\'){
temp[i + 1] = 0;
if (!dirExists(temp)){
if (_mkdir(temp) == -1){
printf("Could not make directory %s :", *dir);
perror(""); //perror is an empty string since our error note is from the printf above
printf("\n");
return false;
}
}
}
i++;
}
return true;
}
bool unix_mkdir(const char * dir){
printf("unix_mkdir() NOT YET IMPLEMENTED!\n");
return false;
}
/**
Calling this function will simply call the corresponding mkdir function for Windows or Unix
*/
bool my_mkdir(char * dir){
#ifdef OS_WINDOWS
return windows_mkdir(dir);
#else
return unix_mkdir(dir);
#endif
}
/**
Checks whether a directory exists
@return true if it exists
false if it does not exists
*/
bool dirExists(const char * dirName_in)
{
DWORD ftyp = GetFileAttributesA(dirName_in);
if (ftyp == INVALID_FILE_ATTRIBUTES)
return false; //something is wrong with your path!
if (ftyp & FILE_ATTRIBUTE_DIRECTORY)
return true; // this is a directory!
return false; // this is not a directory!
}
/**
checks if the directory ends in a backslash for Windows or forward slash for other machines
if it does not, then it will add a backslash/forward slash so it can be created successfully.
*/
void correctDir(char dir[]){
#ifdef OS_WINDOWS
if (dir[strlen(dir) - 1] != '\\'){
/* must store strlen(dir) into an int here because once you make dir[len] = \, dir[len] is no longer
the terminating character and thus if the array had characters after the terminating character
the code will not work as intended */
int len = strlen(dir);
dir[len] = '\\';
dir[len + 1] = 0;
}
#else
if (dir[strlen(dir) - 1] != '/'){
dir[strlen(dir)] = '/';
dir[strlen(dir) + 1] = 0;
}
#endif
} | 15,751 | 5,913 |