hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5c5cb63f8c38f0913721f1412e817fd696369a99 | 1,634 | cpp | C++ | C++/problems/0036_level_order.cpp | oxone-999/algorithms | 52dc527111e7422923a0e25684d8f4837e81a09b | [
"MIT"
] | 6 | 2019-03-20T22:23:26.000Z | 2020-08-28T03:10:27.000Z | C++/problems/0036_level_order.cpp | oxone-999/algorithms | 52dc527111e7422923a0e25684d8f4837e81a09b | [
"MIT"
] | 15 | 2019-10-13T20:53:53.000Z | 2022-03-31T02:01:35.000Z | C++/problems/0036_level_order.cpp | oxone-999/algorithms | 52dc527111e7422923a0e25684d8f4837e81a09b | [
"MIT"
] | 3 | 2019-03-11T10:57:46.000Z | 2020-02-26T21:13:21.000Z | // Problem Statement
// Given a binary tree, return the level order traversal of its nodes' values.
// (ie, from left to right, level by level).
//
// For example:
// Given binary tree [3,9,20,null,null,15,7],
// 3
// / \
// 9 20
// / \
// 15 7
// return its level order traversal as:
// [
// [3],
// [9,20],
// [15,7]
// ]
class Solution {
public:
vector<vector<int>> levelOrderRecursive(TreeNode* root) {
vector<vector<int>> result;
helperRecursive(root,result,0);
return result;
}
void helperRecursive(TreeNode* node, vector<vector<int>> &result, int depth){
if(!node)
return;
if(depth>=result.size()){
vector<int> level;
result.push_back(level);
}
result[depth].push_back(node->val);
helperRecursive(node->left,result,depth+1);
helperRecursive(node->right,result,depth+1);
}
vector<vector<int>> levelOrderIterative(TreeNode* root) {
vector<vector<int>> result;
if(!root)
return result;
queue<TreeNode*> bfs;
bfs.push(root);
while(!bfs.empty()){
vector<int> level;
int tam = bfs.size();
for(int i=0;i<tam;i++){
TreeNode *actual = bfs.front();
bfs.pop();
level.push_back(actual->val);
if(actual->left)
bfs.push(actual->left);
if(actual->right)
bfs.push(actual->right);
}
result.push_back(level);
}
return result;
}
};
| 24.38806 | 81 | 0.5153 | [
"vector"
] |
5c5eae721484d04c38328d33edf6a8fdfebab197 | 3,715 | cc | C++ | src/pks/transport/test/transport_implicit.cc | fmyuan/amanzi | edb7b815ae6c22956c8519acb9d87b92a9915ed4 | [
"RSA-MD"
] | 37 | 2017-04-26T16:27:07.000Z | 2022-03-01T07:38:57.000Z | src/pks/transport/test/transport_implicit.cc | fmyuan/amanzi | edb7b815ae6c22956c8519acb9d87b92a9915ed4 | [
"RSA-MD"
] | 494 | 2016-09-14T02:31:13.000Z | 2022-03-13T18:57:05.000Z | src/pks/transport/test/transport_implicit.cc | fmyuan/amanzi | edb7b815ae6c22956c8519acb9d87b92a9915ed4 | [
"RSA-MD"
] | 43 | 2016-09-26T17:58:40.000Z | 2022-03-25T02:29:59.000Z | /*
The transport component of the Amanzi code, serial unit tests.
License: BSD
Author: Konstantin Lipnikov (lipnikov@lanl.gov)
*/
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <vector>
// TPLs
#include "Teuchos_RCP.hpp"
#include "Teuchos_ParameterList.hpp"
#include "Teuchos_ParameterXMLFileReader.hpp"
#include "Teuchos_XMLParameterListHelpers.hpp"
#include "UnitTest++.h"
// Amanzi
#include "MeshFactory.hh"
#include "State.hh"
// Transport
#include "TransportImplicit_PK.hh"
TEST(ADVANCE_WITH_MESH_FRAMEWORK) {
using namespace Teuchos;
using namespace Amanzi;
using namespace Amanzi::AmanziMesh;
using namespace Amanzi::Transport;
using namespace Amanzi::AmanziGeometry;
std::string framework_name = "MSTK";
Framework framework = Framework::MSTK;
std::cout << "Test: implicit advance "<< std::endl;
Comm_ptr_type comm = Amanzi::getDefaultComm();
// read parameter list
std::string xmlFileName("test/transport_implicit.xml");
Teuchos::RCP<Teuchos::ParameterList> plist = Teuchos::getParametersFromXmlFile(xmlFileName);
// create a mesh
ParameterList region_list = plist->get<Teuchos::ParameterList>("regions");
auto gm = Teuchos::rcp(new Amanzi::AmanziGeometry::GeometricModel(3, region_list, *comm));
Preference pref;
pref.clear();
pref.push_back(framework);
MeshFactory meshfactory(comm, gm);
meshfactory.set_preference(pref);
RCP<const Mesh> mesh;
mesh = meshfactory.create("test/hex_3x3x3_ss.exo");
// mesh = meshfactory.create(0.0, 0.0, 1.0, 1.0, 10, 10);
// create a simple state and populate it
Amanzi::VerboseObject::global_hide_line_prefix = false;
std::vector<std::string> component_names;
component_names.push_back("Component 0");
Teuchos::ParameterList state_list = plist->sublist("state");
RCP<State> S = rcp(new State(state_list));
S->RegisterDomainMesh(rcp_const_cast<Mesh>(mesh));
S->set_time(0.0);
S->set_intermediate_time(0.0);
Teuchos::ParameterList pk_tree = plist->sublist("cycle driver").sublist("pk_tree")
.sublist("transport implicit");
// create the global solution vector
Teuchos::RCP<TreeVector> soln = Teuchos::rcp(new TreeVector());
TransportImplicit_PK TPK(pk_tree, plist, S, soln);
TPK.Setup(S.ptr());
TPK.CreateDefaultState(mesh, 2);
S->InitializeFields();
S->InitializeEvaluators();
// modify the default state for the problem at hand
std::string passwd("state");
Teuchos::RCP<Epetra_MultiVector>
flux = S->GetFieldData("darcy_flux", passwd)->ViewComponent("face", false);
AmanziGeometry::Point velocity(1.0, 1.0, 0.0);
int nfaces_owned = mesh->num_entities(AmanziMesh::FACE, AmanziMesh::Parallel_type::OWNED);
for (int f = 0; f < nfaces_owned; f++) {
const AmanziGeometry::Point& normal = mesh->face_normal(f);
(*flux)[0][f] = velocity * normal;
}
// initialize a transport process kernel
TPK.Initialize(S.ptr());
// advance the state
double t_old(0.0), t_new, dt;
dt = 0.01;
t_new = t_old + dt;
TPK.AdvanceStep(t_old, t_new);
TPK.CommitStep(t_old, t_new, S);
//printing cell concentration
Teuchos::RCP<Epetra_MultiVector>
tcc = S->GetFieldData("total_component_concentration", passwd)->ViewComponent("cell");
while(t_new < 1.2) {
t_new = t_old + dt;
TPK.AdvanceStep(t_old, t_new);
TPK.CommitStep(t_old, t_new, S);
t_old = t_new;
if (t_new < 0.4) {
printf("T=%6.2f C_0(x):", t_new);
for (int k = 0; k < 9; k++) printf("%7.4f", (*tcc)[0][k]); std::cout << std::endl;
}
}
// check that the final state is constant
for (int k = 0; k < 4; k++)
CHECK_CLOSE((*tcc)[0][k], 1.0, 1e-5);
}
| 28.358779 | 94 | 0.68533 | [
"mesh",
"vector"
] |
5c65f2ed471f8722426f31b09dba0fb5625004a5 | 6,983 | cpp | C++ | grt_knn_classification/src/ofApp.cpp | npisanti/np-stubs | 65d7de9080e403542335e76b2491c2787bd7c4d2 | [
"MIT"
] | 1 | 2019-04-26T02:35:10.000Z | 2019-04-26T02:35:10.000Z | grt_knn_classification/src/ofApp.cpp | npisanti/np-stubs | 65d7de9080e403542335e76b2491c2787bd7c4d2 | [
"MIT"
] | null | null | null | grt_knn_classification/src/ofApp.cpp | npisanti/np-stubs | 65d7de9080e403542335e76b2491c2787bd7c4d2 | [
"MIT"
] | null | null | null | #include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
K = 3;
GRT::KNN knn;
knn.setK( K );
pipeline << knn;
examples.setNumDimensions( 2 );
ofBackground( 0 );
guess.x = -100;
guess.y = -100;
guess.z = 0;
grid.allocate( ofGetWidth(), ofGetHeight() );
grid.begin();
ofClear( 0, 0, 0, 0);
grid.end();
ofSetWindowTitle( "knn classification study" );
}
//--------------------------------------------------------------
void ofApp::update(){
}
//--------------------------------------------------------------
void ofApp::draw(){
if( mode==1 && pipeline.getTrained() ){
ofSetColor( 255 );
grid.draw(0, 0);
switch( int( guess.z ) ){
case 1: ofSetColor(255, 0, 0 ); break;
case 2: ofSetColor(0, 255, 0 ); break;
case 3: ofSetColor(0, 0, 255 ); break;
default: ofSetColor(255); break;
}
ofDrawCircle( guess.x, guess.y, 12 );
}
for( size_t i=0; i<examples.getNumSamples(); ++i ){
switch( examples[i].getClassLabel() ){
case 1: ofSetColor(255, 0, 0 ); break;
case 2: ofSetColor(0, 255, 0 ); break;
case 3: ofSetColor(0, 0, 255 ); break;
default: ofSetColor(255); break;
}
float x = examples[i][0]*ofGetWidth();
float y = examples[i][1]*ofGetHeight();
ofDrawCircle( x, y, 5 );
}
drawInfo();
}
//--------------------------------------------------------------
void ofApp::drawInfo(){
ofSetColor( 255 );
string info = "mode = ";
if( mode == 0 ){
info += "training\n";
info += "click with different mouse buttons for example input\n";
info += "backspace to clear all the examples\n";
info += "K=";
info += ofToString( K );
info += " press 1-5 to change\n";
info += "spacebar to train model and run";
} else {
info += "run";
if(pipeline.getTrained()) {
info+= " (training successful)\n";
info += "click and drag to test input and output\n";
}else{
info+= " (training failed)\n";
}
info += "K=";
info += ofToString( K );
info += " press 1-5 to change\n";
info += "spacebar to return to examples input";
}
ofDrawBitmapString( info, 20, 20 );
}
//--------------------------------------------------------------
void ofApp::train(){
pipeline.train( examples );
if(pipeline.getTrained()){
std::cout<<"training succesfull\n";
}else{
std::cout<<"training failed\n";
}
guess.x = -100;
guess.y = -100;
updateGrid();
}
//--------------------------------------------------------------
void ofApp::updateGrid(){
grid.begin();
ofClear(0, 0, 0, 0);
if(pipeline.getTrained()){
for( int x = 0; x<grid.getWidth(); x+=10 ){
for (int y = 0; y<grid.getHeight(); y+=10){
GRT::VectorFloat sample(2);
sample[0] = double(x) / grid.getWidth();
sample[1] = double(y) / grid.getHeight();
pipeline.predict( sample );
int output = pipeline.getPredictedClassLabel();
switch( output ){
case 1: ofSetColor( 80, 0, 0 ); break;
case 2: ofSetColor( 0, 80, 0 ); break;
case 3: ofSetColor( 0, 0, 80 ); break;
default: ofSetColor( 80 ); break;
}
ofDrawLine( x, y+5, x+10, y+5);
ofDrawLine( x+5, y, x+5, y+10);
}
}
}
grid.end();
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
if( mode==1 && pipeline.getTrained() ){
guess.x = x / ofGetWidth();
guess.y = y / ofGetHeight();
GRT::VectorFloat sample(2);
sample[0] = double(x);
sample[1] = double(y);
pipeline.predict( sample );
guess.z = pipeline.getPredictedClassLabel();
}
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
switch( mode ){
case 0: // training
{
double dx = double(x) / ofGetWidth();
double dy = double(y) / ofGetHeight();
GRT::VectorFloat sample(2);
sample[0] = dx; //mouseX / double(ofGetWidth());
sample[1] = dy; //mouseY / double(ofGetHeight());
examples.addSample( button+1, sample ); // class, input
std::cout<< "added point "<<dx<<" "<<dy<<" to class "<<button+1<<"\n";
}
break;
case 1: // run
{
if(pipeline.getTrained()){
guess.x = double(x) / ofGetWidth();
guess.y = double(y) / ofGetHeight();
GRT::VectorFloat sample(2);
sample[0] = double(x);
sample[1] = double(y);
pipeline.predict( sample );
guess.z = pipeline.getPredictedClassLabel();
}
}
break;
}
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
switch( key ){
case ' ':
if (mode==0){ train(); }
mode = mode ? 0 : 1;
break;
case OF_KEY_BACKSPACE:
if( mode==0 ){
examples.clear();
}
break;
}
int newK = key - '1' + 1;
if(newK>0 && newK<=5){
K = newK;
GRT::KNN knn;
knn.setK( K );
pipeline << knn;
if(mode==1){
train();
}
}
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
| 27.710317 | 86 | 0.39052 | [
"model"
] |
5c6eba77a0620b5a486046412c0ca6cae20e456d | 28,459 | cpp | C++ | test-suite/catbonds.cpp | haozhangphd/QuantLib-noBoost | ddded069868161099843c04840454f00816113ad | [
"BSD-3-Clause"
] | 76 | 2017-06-28T21:24:38.000Z | 2021-12-19T18:07:37.000Z | test-suite/catbonds.cpp | haozhangphd/QuantLib-noBoost | ddded069868161099843c04840454f00816113ad | [
"BSD-3-Clause"
] | 2 | 2017-07-05T09:20:13.000Z | 2019-10-31T12:06:51.000Z | test-suite/catbonds.cpp | haozhangphd/QuantLib-noBoost | ddded069868161099843c04840454f00816113ad | [
"BSD-3-Clause"
] | 34 | 2017-07-02T14:49:21.000Z | 2021-11-26T15:32:04.000Z | /* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2012, 2013 Grzegorz Andruszkiewicz
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy of the license along with this program; if not, please email
<quantlib-dev@lists.sf.net>. The license is also available online at
<http://quantlib.org/license.shtml>.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the license for more details.
*/
#include "utilities.hpp"
#include <ql/types.hpp>
#include <ql/experimental/catbonds/all.hpp>
#include <ql/instruments/bonds/floatingratebond.hpp>
#include <ql/time/calendars/target.hpp>
#include <ql/time/calendars/unitedstates.hpp>
#include <ql/time/calendars/brazil.hpp>
#include <ql/time/calendars/nullcalendar.hpp>
#include <ql/time/daycounters/thirty360.hpp>
#include <ql/time/daycounters/actual360.hpp>
#include <ql/time/daycounters/actualactual.hpp>
#include <ql/time/daycounters/business252.hpp>
#include <ql/indexes/ibor/usdlibor.hpp>
#include <ql/quotes/simplequote.hpp>
#include <ql/utilities/dataformatters.hpp>
#include <ql/time/schedule.hpp>
#include <ql/cashflows/fixedratecoupon.hpp>
#include <ql/cashflows/simplecashflow.hpp>
#include <ql/cashflows/couponpricer.hpp>
#include <ql/cashflows/cashflows.hpp>
#include <ql/pricingengines/bond/discountingbondengine.hpp>
#include <ql/pricingengines/bond/bondfunctions.hpp>
#include <ql/termstructures/yield/flatforward.hpp>
using namespace QuantLib;
using std::shared_ptr;
namespace {
std::pair<Date, Real> data[] = {std::pair < Date, Real > (Date(1, February, 2012), 100), std::pair < Date,
Real > (Date(1, July, 2013), 150), std::pair < Date,
Real > (Date(5, January, 2014), 50)};
std::shared_ptr<std::vector<std::pair<Date, Real>>> sampleEvents =
std::make_shared<std::vector<std::pair<Date, Real>>>(std::vector<std::pair<Date, Real>>(data, data + 3));
Date eventsStart(1, January, 2011);
Date eventsEnd(31, December, 2014);
template<typename lhs_t, typename rhs_t, typename tolerance_t>
bool close(lhs_t lhs, rhs_t rhs, tolerance_t tolerance) {
return std::abs(rhs - lhs) <= tolerance;
}
}
TEST_CASE("CatBond_EventSetForWholeYears", "[CatBond]") {
INFO("Testing that catastrophe events are split correctly for periods of whole years...");
EventSet catRisk(sampleEvents, eventsStart, eventsEnd);
std::shared_ptr < CatSimulation > simulation = catRisk.newSimulation(Date(1, January, 2015),
Date(31, December, 2015));
REQUIRE(simulation);
std::vector<std::pair<Date, Real>> path;
REQUIRE(simulation->nextPath(path));
CHECK(Size(0) == path.size());
REQUIRE(simulation->nextPath(path));
CHECK(Size(1) == path.size());
CHECK(Date(1, February, 2015) == path.at(0).first);
CHECK(100 == path.at(0).second);
REQUIRE(simulation->nextPath(path));
CHECK(Size(1) == path.size());
CHECK(Date(1, July, 2015) == path.at(0).first);
CHECK(150 == path.at(0).second);
REQUIRE(simulation->nextPath(path));
CHECK(Size(1) == path.size());
CHECK(Date(5, January, 2015) == path.at(0).first);
CHECK(50 == path.at(0).second);
REQUIRE(!simulation->nextPath(path));
}
TEST_CASE("CatBond_EventSetForIrregularPeriods", "[CatBond]") {
INFO("Testing that catastrophe events are split correctly for irregular periods...");
EventSet catRisk(sampleEvents, eventsStart, eventsEnd);
std::shared_ptr < CatSimulation > simulation = catRisk.newSimulation(Date(2, January, 2015),
Date(5, January, 2016));
REQUIRE(simulation);
std::vector<std::pair<Date, Real>> path;
REQUIRE(simulation->nextPath(path));
CHECK(Size(0) == path.size());
REQUIRE(simulation->nextPath(path));
CHECK(Size(2) == path.size());
CHECK(Date(1, July, 2015) == path.at(0).first);
CHECK(150 == path.at(0).second);
CHECK(Date(5, January, 2016) == path.at(1).first);
CHECK(50 == path.at(1).second);
REQUIRE(!simulation->nextPath(path));
}
TEST_CASE("CatBond_EventSetForNoEvents", "[CatBond]") {
INFO("Testing that catastrophe events are split correctly when there are no simulated events...");
std::shared_ptr < std::vector<std::pair<Date, Real>> >
emptyEvents = std::make_shared<std::vector<std::pair<Date, Real>>>();
EventSet catRisk(emptyEvents, eventsStart, eventsEnd);
std::shared_ptr < CatSimulation > simulation = catRisk.newSimulation(Date(2, January, 2015),
Date(5, January, 2016));
REQUIRE(simulation);
std::vector<std::pair<Date, Real>> path;
REQUIRE(simulation->nextPath(path));
CHECK(Size(0) == path.size());
REQUIRE(simulation->nextPath(path));
CHECK(Size(0) == path.size());
REQUIRE(!simulation->nextPath(path));
}
TEST_CASE("CatBond_BetaRisk", "[CatBond]") {
INFO("Testing that beta risk gives correct terminal distribution...");
const size_t PATHS = 1000000;
BetaRisk catRisk(100.0, 100.0, 10.0, 15.0);
std::shared_ptr < CatSimulation > simulation = catRisk.newSimulation(Date(2, January, 2015),
Date(2, January, 2018));
REQUIRE(simulation);
std::vector<std::pair<Date, Real>> path;
Real sum = 0.0;
Real sumSquares = 0.0;
Real poissonSum = 0.0;
Real poissonSumSquares = 0.0;
for (size_t i = 0; i < PATHS; ++i) {
REQUIRE(simulation->nextPath(path));
Real processValue = 0.0;
for (size_t j = 0; j < path.size(); ++j) processValue += path[j].second;
sum += processValue;
sumSquares += processValue * processValue;
poissonSum += path.size();
poissonSumSquares += path.size() * path.size();
}
Real poissonMean = poissonSum / PATHS;
CHECK(close(Real(3.0 / 100.0), poissonMean, 2));
Real poissonVar = poissonSumSquares / PATHS - poissonMean * poissonMean;
CHECK(close(Real(3.0 / 100.0), poissonVar, 5));
Real expectedMean = 3.0 * 10.0 / 100.0;
Real actualMean = sum / PATHS;
CHECK(close(expectedMean, actualMean, 1));
Real expectedVar = 3.0 * (15.0 * 15.0 + 10 * 10) / 100.0;
Real actualVar = sumSquares / PATHS - actualMean * actualMean;
CHECK(close(expectedVar, actualVar, 1));
}
namespace {
struct CommonVars {
// common data
Calendar calendar;
Date today;
Real faceAmount;
// cleanup
SavedSettings backup;
// setup
CommonVars() {
calendar = TARGET();
today = calendar.adjust(Date::todaysDate());
Settings::instance().evaluationDate() = today;
faceAmount = 1000000.0;
}
};
}
TEST_CASE("CatBond_RiskFreeAgainstFloatingRateBond", "[CatBond]") {
INFO("Testing floating-rate cat bond against risk-free floating-rate bond...");
CommonVars vars;
Date today(22, November, 2004);
Settings::instance().evaluationDate() = today;
Natural settlementDays = 1;
Handle<YieldTermStructure> riskFreeRate(flatRate(today, 0.025, Actual360()));
Handle<YieldTermStructure> discountCurve(flatRate(today, 0.03, Actual360()));
shared_ptr < IborIndex > index = std::make_shared<USDLibor>(6 * Months, riskFreeRate);
Natural fixingDays = 1;
Real tolerance = 1.0e-6;
shared_ptr < IborCouponPricer > pricer =
std::make_shared<BlackIborCouponPricer>(Handle<OptionletVolatilityStructure>());
// plain
Schedule sch(Date(30, November, 2004),
Date(30, November, 2008),
Period(Semiannual),
UnitedStates(UnitedStates::GovernmentBond),
ModifiedFollowing, ModifiedFollowing,
DateGeneration::Backward, false);
std::shared_ptr < CatRisk > noCatRisk = std::make_shared<EventSet>(
std::make_shared<std::vector<std::pair<Date, Real>>>(),
Date(1, Jan, 2000), Date(31, Dec, 2010));
std::shared_ptr < EventPaymentOffset > paymentOffset = std::make_shared<NoOffset>();
std::shared_ptr < NotionalRisk > notionalRisk = std::make_shared<DigitalNotionalRisk>(paymentOffset, 100);
FloatingRateBond bond1(settlementDays, vars.faceAmount, sch,
index, ActualActual(ActualActual::ISMA),
ModifiedFollowing, fixingDays,
std::vector<Real>(), std::vector<Spread>(),
std::vector<Rate>(), std::vector<Rate>(),
false,
100.0, Date(30, November, 2004));
FloatingCatBond catBond1(settlementDays, vars.faceAmount, sch,
index, ActualActual(ActualActual::ISMA),
notionalRisk,
ModifiedFollowing, fixingDays,
std::vector<Real>(), std::vector<Spread>(),
std::vector<Rate>(), std::vector<Rate>(),
false,
100.0, Date(30, November, 2004));
shared_ptr < PricingEngine > bondEngine =
std::make_shared<DiscountingBondEngine>(riskFreeRate);
bond1.setPricingEngine(bondEngine);
setCouponPricer(bond1.cashflows(), pricer);
shared_ptr < PricingEngine > catBondEngine = std::make_shared<MonteCarloCatBondEngine>(noCatRisk, riskFreeRate);
catBond1.setPricingEngine(catBondEngine);
setCouponPricer(catBond1.cashflows(), pricer);
#if defined(QL_USE_INDEXED_COUPON)
Real cachedPrice1 = 99.874645;
#else
Real cachedPrice1 = 99.874646;
#endif
Real price = bond1.cleanPrice();
Real catPrice = catBond1.cleanPrice();
if (std::fabs(price - cachedPrice1) > tolerance || std::fabs(catPrice - price) > tolerance) {
FAIL("failed to reproduce floating rate bond price:\n"
<< std::fixed
<< " floating bond: " << price << "\n"
<< " catBond bond: " << catPrice << "\n"
<< " expected: " << cachedPrice1 << "\n"
<< " error: " << catPrice - price);
}
// different risk-free and discount curve
FloatingRateBond bond2(settlementDays, vars.faceAmount, sch,
index, ActualActual(ActualActual::ISMA),
ModifiedFollowing, fixingDays,
std::vector<Rate>(), std::vector<Spread>(),
std::vector<Rate>(), std::vector<Rate>(),
false,
100.0, Date(30, November, 2004));
FloatingCatBond catBond2(settlementDays, vars.faceAmount, sch,
index, ActualActual(ActualActual::ISMA),
notionalRisk,
ModifiedFollowing, fixingDays,
std::vector<Rate>(), std::vector<Spread>(),
std::vector<Rate>(), std::vector<Rate>(),
false,
100.0, Date(30, November, 2004));
shared_ptr < PricingEngine > bondEngine2 =
std::make_shared<DiscountingBondEngine>(discountCurve);
bond2.setPricingEngine(bondEngine2);
setCouponPricer(bond2.cashflows(), pricer);
shared_ptr < PricingEngine > catBondEngine2 = std::make_shared<MonteCarloCatBondEngine>(noCatRisk, discountCurve);
catBond2.setPricingEngine(catBondEngine2);
setCouponPricer(catBond2.cashflows(), pricer);
#if defined(QL_USE_INDEXED_COUPON)
Real cachedPrice2 = 97.955904;
#else
Real cachedPrice2 = 97.955904;
#endif
price = bond2.cleanPrice();
catPrice = catBond2.cleanPrice();
if (std::fabs(price - cachedPrice2) > tolerance || std::fabs(catPrice - price) > tolerance) {
FAIL("failed to reproduce floating rate bond price:\n"
<< std::fixed
<< " floating bond: " << price << "\n"
<< " catBond bond: " << catPrice << "\n"
<< " expected: " << cachedPrice2 << "\n"
<< " error: " << catPrice - price);
}
// varying spread
std::vector<Rate> spreads(4);
spreads[0] = 0.001;
spreads[1] = 0.0012;
spreads[2] = 0.0014;
spreads[3] = 0.0016;
FloatingRateBond bond3(settlementDays, vars.faceAmount, sch,
index, ActualActual(ActualActual::ISMA),
ModifiedFollowing, fixingDays,
std::vector<Real>(), spreads,
std::vector<Rate>(), std::vector<Rate>(),
false,
100.0, Date(30, November, 2004));
FloatingCatBond catBond3(settlementDays, vars.faceAmount, sch,
index, ActualActual(ActualActual::ISMA),
notionalRisk,
ModifiedFollowing, fixingDays,
std::vector<Real>(), spreads,
std::vector<Rate>(), std::vector<Rate>(),
false,
100.0, Date(30, November, 2004));
bond3.setPricingEngine(bondEngine2);
setCouponPricer(bond3.cashflows(), pricer);
catBond3.setPricingEngine(catBondEngine2);
setCouponPricer(catBond3.cashflows(), pricer);
#if defined(QL_USE_INDEXED_COUPON)
Real cachedPrice3 = 98.495458;
#else
Real cachedPrice3 = 98.495459;
#endif
price = bond3.cleanPrice();
catPrice = catBond3.cleanPrice();
if (std::fabs(price - cachedPrice3) > tolerance || std::fabs(catPrice - price) > tolerance) {
FAIL("failed to reproduce floating rate bond price:\n"
<< std::fixed
<< " floating bond: " << price << "\n"
<< " catBond bond: " << catPrice << "\n"
<< " expected: " << cachedPrice2 << "\n"
<< " error: " << catPrice - price);
}
}
TEST_CASE("CatBond_CatBondInDoomScenario", "[CatBond]") {
INFO("Testing floating-rate cat bond in a doom scenario (certain default)...");
CommonVars vars;
Date today(22, November, 2004);
Settings::instance().evaluationDate() = today;
Natural settlementDays = 1;
Handle<YieldTermStructure> riskFreeRate(flatRate(today, 0.025, Actual360()));
Handle<YieldTermStructure> discountCurve(flatRate(today, 0.03, Actual360()));
shared_ptr < IborIndex > index = std::make_shared<USDLibor>(6 * Months, riskFreeRate);
Natural fixingDays = 1;
Real tolerance = 1.0e-6;
shared_ptr < IborCouponPricer > pricer =
std::make_shared<BlackIborCouponPricer>(Handle<OptionletVolatilityStructure>());
Schedule sch(Date(30, November, 2004),
Date(30, November, 2008),
Period(Semiannual),
UnitedStates(UnitedStates::GovernmentBond),
ModifiedFollowing, ModifiedFollowing,
DateGeneration::Backward, false);
std::shared_ptr < std::vector<std::pair<Date, Real>> >
events = std::make_shared<std::vector<std::pair<Date, Real>>>();
events->emplace_back(std::pair < Date, Real > (Date(30, November, 2004), 1000));
std::shared_ptr < CatRisk > doomCatRisk = std::make_shared<EventSet>(events, Date(30, November, 2004),
Date(30, November, 2008));
std::shared_ptr < EventPaymentOffset > paymentOffset = std::make_shared<NoOffset>();
std::shared_ptr < NotionalRisk > notionalRisk = std::make_shared<DigitalNotionalRisk>(paymentOffset, 100);
FloatingCatBond catBond(settlementDays, vars.faceAmount, sch,
index, ActualActual(ActualActual::ISMA),
notionalRisk,
ModifiedFollowing, fixingDays,
std::vector<Rate>(), std::vector<Spread>(),
std::vector<Rate>(), std::vector<Rate>(),
false,
100.0, Date(30, November, 2004));
shared_ptr < PricingEngine > catBondEngine = std::make_shared<MonteCarloCatBondEngine>(doomCatRisk, discountCurve);
catBond.setPricingEngine(catBondEngine);
setCouponPricer(catBond.cashflows(), pricer);
Real price = catBond.cleanPrice();
CHECK(0 == price);
Real lossProbability = catBond.lossProbability();
Real exhaustionProbability = catBond.exhaustionProbability();
Real expectedLoss = catBond.expectedLoss();
CHECK(close(Real(1.0), lossProbability, tolerance));
CHECK(close(Real(1.0), exhaustionProbability, tolerance));
CHECK(close(Real(1.0), expectedLoss, tolerance));
}
TEST_CASE("CatBond_CatBondWithDoomOnceInTenYears", "[CatBond]") {
INFO("Testing floating-rate cat bond in a doom once in 10 years scenario...");
CommonVars vars;
Date today(22, November, 2004);
Settings::instance().evaluationDate() = today;
Natural settlementDays = 1;
Handle<YieldTermStructure> riskFreeRate(flatRate(today, 0.025, Actual360()));
Handle<YieldTermStructure> discountCurve(flatRate(today, 0.03, Actual360()));
shared_ptr < IborIndex > index = std::make_shared<USDLibor>(6 * Months, riskFreeRate);
Natural fixingDays = 1;
Real tolerance = 1.0e-6;
shared_ptr < IborCouponPricer > pricer =
std::make_shared<BlackIborCouponPricer>(Handle<OptionletVolatilityStructure>());
Schedule sch(Date(30, November, 2004),
Date(30, November, 2008),
Period(Semiannual),
UnitedStates(UnitedStates::GovernmentBond),
ModifiedFollowing, ModifiedFollowing,
DateGeneration::Backward, false);
std::shared_ptr < std::vector<std::pair<Date, Real>> >
events = std::make_shared<std::vector<std::pair<Date, Real>>>();
events->emplace_back(std::pair < Date, Real > (Date(30, November, 2008), 1000));
std::shared_ptr < CatRisk > doomCatRisk = std::make_shared<EventSet>(events, Date(30, November, 2004),
Date(30, November, 2044));
std::shared_ptr < CatRisk > noCatRisk = std::make_shared<EventSet>(
std::make_shared<std::vector<std::pair<Date, Real>>>(), Date(1, Jan, 2000), Date(31, Dec, 2010));
std::shared_ptr < EventPaymentOffset > paymentOffset = std::make_shared<NoOffset>();
std::shared_ptr < NotionalRisk > notionalRisk = std::make_shared<DigitalNotionalRisk>(paymentOffset, 100);
FloatingCatBond catBond(settlementDays, vars.faceAmount, sch,
index, ActualActual(ActualActual::ISMA),
notionalRisk,
ModifiedFollowing, fixingDays,
std::vector<Rate>(), std::vector<Spread>(),
std::vector<Rate>(), std::vector<Rate>(),
false,
100.0, Date(30, November, 2004));
shared_ptr < PricingEngine > catBondEngine = std::make_shared<MonteCarloCatBondEngine>(doomCatRisk, discountCurve);
catBond.setPricingEngine(catBondEngine);
setCouponPricer(catBond.cashflows(), pricer);
Real price = catBond.cleanPrice();
Real yield = catBond.yield(ActualActual(ActualActual::ISMA), Simple, Annual);
Real lossProbability = catBond.lossProbability();
Real exhaustionProbability = catBond.exhaustionProbability();
Real expectedLoss = catBond.expectedLoss();
CHECK(close(Real(0.1), lossProbability, tolerance));
CHECK(close(Real(0.1), exhaustionProbability, tolerance));
CHECK(close(Real(0.1), expectedLoss, tolerance));
shared_ptr < PricingEngine > catBondEngineRF = std::make_shared<MonteCarloCatBondEngine>(noCatRisk, discountCurve);
catBond.setPricingEngine(catBondEngineRF);
Real riskFreePrice = catBond.cleanPrice();
Real riskFreeYield = catBond.yield(ActualActual(ActualActual::ISMA), Simple, Annual);
Real riskFreeLossProbability = catBond.lossProbability();
Real riskFreeExhaustionProbability = catBond.exhaustionProbability();
Real riskFreeExpectedLoss = catBond.expectedLoss();
CHECK(close(Real(0.0), riskFreeLossProbability, tolerance));
CHECK(close(Real(0.0), riskFreeExhaustionProbability, tolerance));
CHECK(std::abs(riskFreeExpectedLoss) < tolerance);
CHECK(close(riskFreePrice * 0.9, price, tolerance));
CHECK(riskFreeYield < yield);
}
TEST_CASE("CatBond_CatBondWithDoomOnceInTenYearsProportional", "[CatBond]") {
INFO("Testing floating-rate cat bond in a doom once in 10 years scenario with proportional notional reduction...");
CommonVars vars;
Date today(22, November, 2004);
Settings::instance().evaluationDate() = today;
Natural settlementDays = 1;
Handle<YieldTermStructure> riskFreeRate(flatRate(today, 0.025, Actual360()));
Handle<YieldTermStructure> discountCurve(flatRate(today, 0.03, Actual360()));
shared_ptr < IborIndex > index = std::make_shared<USDLibor>(6 * Months, riskFreeRate);
Natural fixingDays = 1;
Real tolerance = 1.0e-6;
shared_ptr < IborCouponPricer > pricer =
std::make_shared<BlackIborCouponPricer>(Handle<OptionletVolatilityStructure>());
Schedule sch(Date(30, November, 2004),
Date(30, November, 2008),
Period(Semiannual),
UnitedStates(UnitedStates::GovernmentBond),
ModifiedFollowing, ModifiedFollowing,
DateGeneration::Backward, false);
std::shared_ptr < std::vector<std::pair<Date, Real>> >
events = std::make_shared<std::vector<std::pair<Date, Real>>>();
events->emplace_back(std::pair < Date, Real > (Date(30, November, 2008), 1000));
std::shared_ptr < CatRisk > doomCatRisk = std::make_shared<EventSet>(events, Date(30, November, 2004),
Date(30, November, 2044));
std::shared_ptr < CatRisk > noCatRisk = std::make_shared<EventSet>(
std::make_shared<std::vector<std::pair<Date, Real>>>(),
Date(1, Jan, 2000), Date(31, Dec, 2010));
std::shared_ptr < EventPaymentOffset > paymentOffset = std::make_shared<NoOffset>();
std::shared_ptr < NotionalRisk > notionalRisk = std::make_shared<ProportionalNotionalRisk>(paymentOffset, 500,
1500);
FloatingCatBond catBond(settlementDays, vars.faceAmount, sch,
index, ActualActual(ActualActual::ISMA),
notionalRisk,
ModifiedFollowing, fixingDays,
std::vector<Rate>(), std::vector<Spread>(),
std::vector<Rate>(), std::vector<Rate>(),
false,
100.0, Date(30, November, 2004));
shared_ptr < PricingEngine > catBondEngine = std::make_shared<MonteCarloCatBondEngine>(doomCatRisk, discountCurve);
catBond.setPricingEngine(catBondEngine);
setCouponPricer(catBond.cashflows(), pricer);
Real price = catBond.cleanPrice();
Real yield = catBond.yield(ActualActual(ActualActual::ISMA), Simple, Annual);
Real lossProbability = catBond.lossProbability();
Real exhaustionProbability = catBond.exhaustionProbability();
Real expectedLoss = catBond.expectedLoss();
CHECK(close(Real(0.1), lossProbability, tolerance));
CHECK(close(Real(0.0), exhaustionProbability, tolerance));
CHECK(close(Real(0.05), expectedLoss, tolerance));
shared_ptr < PricingEngine > catBondEngineRF = std::make_shared<MonteCarloCatBondEngine>(noCatRisk, discountCurve);
catBond.setPricingEngine(catBondEngineRF);
Real riskFreePrice = catBond.cleanPrice();
Real riskFreeYield = catBond.yield(ActualActual(ActualActual::ISMA), Simple, Annual);
Real riskFreeLossProbability = catBond.lossProbability();
Real riskFreeExpectedLoss = catBond.expectedLoss();
CHECK(close(Real(0.0), riskFreeLossProbability, tolerance));
CHECK(std::abs(riskFreeExpectedLoss) < tolerance);
CHECK(close(riskFreePrice * 0.95, price, tolerance));
CHECK(riskFreeYield < yield);
}
TEST_CASE("CatBond_CatBondWithGeneratedEventsProportional", "[CatBond]") {
INFO("Testing floating-rate cat bond in a generated scenario with proportional notional reduction...");
CommonVars vars;
Date today(22, November, 2004);
Settings::instance().evaluationDate() = today;
Natural settlementDays = 1;
Handle<YieldTermStructure> riskFreeRate(flatRate(today, 0.025, Actual360()));
Handle<YieldTermStructure> discountCurve(flatRate(today, 0.03, Actual360()));
shared_ptr < IborIndex > index = std::make_shared<USDLibor>(6 * Months, riskFreeRate);
Natural fixingDays = 1;
Real tolerance = 1.0e-6;
shared_ptr < IborCouponPricer > pricer =
std::make_shared<BlackIborCouponPricer>(Handle<OptionletVolatilityStructure>());
Schedule sch(Date(30, November, 2004),
Date(30, November, 2008),
Period(Semiannual),
UnitedStates(UnitedStates::GovernmentBond),
ModifiedFollowing, ModifiedFollowing,
DateGeneration::Backward, false);
std::shared_ptr < CatRisk > betaCatRisk = std::make_shared<BetaRisk>(5000, 50, 500, 500);
std::shared_ptr < CatRisk > noCatRisk = std::make_shared<EventSet>(
std::make_shared<std::vector<std::pair<Date, Real>>>(),
Date(1, Jan, 2000), Date(31, Dec, 2010));
std::shared_ptr < EventPaymentOffset > paymentOffset = std::make_shared<NoOffset>();
std::shared_ptr < NotionalRisk > notionalRisk = std::make_shared<ProportionalNotionalRisk>(paymentOffset, 500,
1500);
FloatingCatBond catBond(settlementDays, vars.faceAmount, sch,
index, ActualActual(ActualActual::ISMA),
notionalRisk,
ModifiedFollowing, fixingDays,
std::vector<Rate>(), std::vector<Spread>(),
std::vector<Rate>(), std::vector<Rate>(),
false,
100.0, Date(30, November, 2004));
shared_ptr < PricingEngine > catBondEngine = std::make_shared<MonteCarloCatBondEngine>(betaCatRisk, discountCurve);
catBond.setPricingEngine(catBondEngine);
setCouponPricer(catBond.cashflows(), pricer);
Real price = catBond.cleanPrice();
Real yield = catBond.yield(ActualActual(ActualActual::ISMA), Simple, Annual);
Real lossProbability = catBond.lossProbability();
Real exhaustionProbability = catBond.exhaustionProbability();
Real expectedLoss = catBond.expectedLoss();
CHECK(lossProbability < 1.0);
CHECK(lossProbability > 0.0);
CHECK(exhaustionProbability < 1.0);
CHECK(exhaustionProbability > 0.0);
CHECK(expectedLoss > 0.0);
shared_ptr < PricingEngine > catBondEngineRF = std::make_shared<MonteCarloCatBondEngine>(noCatRisk, discountCurve);
catBond.setPricingEngine(catBondEngineRF);
Real riskFreePrice = catBond.cleanPrice();
Real riskFreeYield = catBond.yield(ActualActual(ActualActual::ISMA), Simple, Annual);
Real riskFreeLossProbability = catBond.lossProbability();
Real riskFreeExpectedLoss = catBond.expectedLoss();
CHECK(close(Real(0.0), riskFreeLossProbability, tolerance));
CHECK(std::abs(riskFreeExpectedLoss) < tolerance);
CHECK(riskFreePrice > price);
CHECK(riskFreeYield < yield);
}
| 41.606725 | 119 | 0.619347 | [
"vector"
] |
f079edb206c1d2fd7623d584262ae463c53bbc86 | 45,085 | cpp | C++ | BulletSim.cpp | Misterblue/BulletSim | e59f070fc853f79513a67685356a42137e40a2f7 | [
"BSD-3-Clause"
] | null | null | null | BulletSim.cpp | Misterblue/BulletSim | e59f070fc853f79513a67685356a42137e40a2f7 | [
"BSD-3-Clause"
] | null | null | null | BulletSim.cpp | Misterblue/BulletSim | e59f070fc853f79513a67685356a42137e40a2f7 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* 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 copyrightD
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project 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 DEVELOPERS ``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 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 "BulletSim.h"
#include "Util.h"
#include "BulletCollision/CollisionDispatch/btSimulationIslandManager.h"
#include "BulletCollision/CollisionShapes/btTriangleShape.h"
#include "LinearMath/btGeometryUtil.h"
#include "BulletCollision/Gimpact/btGImpactCollisionAlgorithm.h"
#include "BulletCollision/Gimpact/btGImpactShape.h"
#if defined(USEBULLETHACD)
#if defined(__linux__) || defined(__APPLE__)
#include "HACD/hacdHACD.h"
#elif defined(_WIN32) || defined(_WIN64)
#include "../extras/HACD/hacdHACD.h"
#else
#error "Platform type not understood."
#endif
#endif
#if defined(USEVHACD)
#include "VHACD.h"
using namespace VHACD;
#endif
// Linkages to debugging dump routines
extern "C" void DumpPhysicsStatistics2(BulletSim* sim);
extern "C" void DumpActivationInfo2(BulletSim* sim);
// Bullet has some parameters that are just global variables
extern ContactAddedCallback gContactAddedCallback;
extern btScalar gContactBreakingThreshold;
BulletSim::BulletSim(btScalar maxX, btScalar maxY, btScalar maxZ)
{
bsDebug_Initialize();
// Make sure structures that will be created in initPhysics are marked as not created
m_worldData.dynamicsWorld = NULL;
m_worldData.sim = this;
m_worldData.MinPosition = btVector3(0, 0, 0);
m_worldData.MaxPosition = btVector3(maxX, maxY, maxZ);
}
// Called when a collision point is being added to the manifold.
// This is used to modify the collision normal to make meshes collidable on only one side.
// Based on rule: "Ignore collisions if dot product of hit normal and a vector pointing to the center of the the object
// is less than zero."
// Code based on example code given in: http://www.bulletphysics.org/Bullet/phpBB3/viewtopic.php?f=9&t=3052&start=15#p12308
// Code used under Creative Commons, ShareAlike, Attribution as per Bullet forums.
static void SingleSidedMeshCheck(btManifoldPoint& cp, const btCollisionObjectWrapper* colObj, int partId, int index)
{
const btCollisionShape* shape = colObj->getCollisionShape();
// TODO: compound shapes don't have this proxy type. How to get vector pointing to object middle?
if (shape->getShapeType() != TRIANGLE_SHAPE_PROXYTYPE) return;
const btTriangleShape* tshape = static_cast<const btTriangleShape*>(colObj->getCollisionShape());
btVector3 v1 = tshape->m_vertices1[0];
btVector3 v2 = tshape->m_vertices1[1];
btVector3 v3 = tshape->m_vertices1[2];
// Create a normal pointing to the center of the mesh based on the first triangle
btVector3 normal = (v2-v1).cross(v3-v1);
// Since the collision points are in local coordinates, create a transform for the collided
// object like it was at <0, 0, 0>.
btTransform orient = colObj->getWorldTransform();
orient.setOrigin( btVector3(0.0, 0.0, 0.0) );
// Rotate that normal to world coordinates and normalize
normal = orient * normal;
normal.normalize();
// Dot the normal to the center and the collision normal to see if the collision normal is pointing in or out.
btScalar dot = normal.dot(cp.m_normalWorldOnB);
btScalar magnitude = cp.m_normalWorldOnB.length();
normal *= dot > 0 ? magnitude : -magnitude;
cp.m_normalWorldOnB = normal;
}
// Check the collision point and modify the collision direction normal to only point "out" of the mesh
static bool SingleSidedMeshCheckCallback(btManifoldPoint& cp,
const btCollisionObjectWrapper* colObj0, int partId0, int index0,
const btCollisionObjectWrapper* colObj1, int partId1, int index1)
{
SingleSidedMeshCheck(cp, colObj0, partId0, index0);
SingleSidedMeshCheck(cp, colObj1, partId1, index1);
return true;
}
void BulletSim::initPhysics2(ParamBlock* parms,
int maxCollisions, CollisionDesc* collisionArray,
int maxUpdates, EntityProperties* updateArray)
{
// Tell the world we're initializing and output size of types so we can
// debug mis-alignments when changing architecture.
// m_worldData.BSLog("InitPhysics: sizeof(int)=%d, sizeof(long)=%d, sizeof(long long)=%d, sizeof(float)=%d",
// sizeof(int), sizeof(long), sizeof(long long), sizeof(float));
// remember the pointers to pinned memory for returning collisions and property updates
m_maxCollisionsPerFrame = maxCollisions;
m_collidersThisFrameArray = collisionArray;
m_maxUpdatesPerFrame = maxUpdates;
m_updatesThisFrameArray = updateArray;
// Parameters are in a block of pinned memory
m_worldData.params = parms;
// create the functional parts of the physics simulation
btDefaultCollisionConstructionInfo cci;
// if you are setting a pool size, you should disable dynamic allocation
if (m_worldData.params->maxPersistantManifoldPoolSize > 0)
{
cci.m_defaultMaxPersistentManifoldPoolSize = (int)m_worldData.params->maxPersistantManifoldPoolSize;
m_worldData.BSLog("initPhysics2: setting defaultMaxPersistentManifoldPoolSize = %f", m_worldData.params->maxPersistantManifoldPoolSize);
}
if (m_worldData.params->maxCollisionAlgorithmPoolSize > 0)
{
cci.m_defaultMaxCollisionAlgorithmPoolSize = m_worldData.params->maxCollisionAlgorithmPoolSize;
m_worldData.BSLog("initPhysics2: setting defaultMaxCollisionAlgorithmPoolSize = %f", m_worldData.params->maxCollisionAlgorithmPoolSize);
}
m_collisionConfiguration = new btDefaultCollisionConfiguration(cci);
m_dispatcher = new btCollisionDispatcher(m_collisionConfiguration);
// optional but not a good idea
if (m_worldData.params->shouldDisableContactPoolDynamicAllocation != ParamFalse)
{
m_dispatcher->setDispatcherFlags(
btCollisionDispatcher::CD_DISABLE_CONTACTPOOL_DYNAMIC_ALLOCATION | m_dispatcher->getDispatcherFlags());
m_worldData.BSLog("initPhysics2: adding CD_DISABLE_CONTACTPOOL_DYNAMIC_ALLOCATION to dispatcherFlags");
}
m_broadphase = new btDbvtBroadphase();
// the following is needed to enable GhostObjects
m_broadphase->getOverlappingPairCache()->setInternalGhostPairCallback(new btGhostPairCallback());
m_solver = new btSequentialImpulseConstraintSolver();
// Create the world
btDiscreteDynamicsWorld* dynamicsWorld = new btDiscreteDynamicsWorld(m_dispatcher, m_broadphase, m_solver, m_collisionConfiguration);
m_worldData.dynamicsWorld = dynamicsWorld;
// Register GImpact collsions since that type can be created
btGImpactCollisionAlgorithm::registerAlgorithm((btCollisionDispatcher*)dynamicsWorld->getDispatcher());
// disable or enable the continuious recalculation of the static AABBs
// http://www.bulletphysics.org/Bullet/phpBB3/viewtopic.php?f=9&t=4991
// Note that if disabled, movement or changes to a static object will not update the AABB. Must do it explicitly.
dynamicsWorld->setForceUpdateAllAabbs(m_worldData.params->shouldForceUpdateAllAabbs != ParamFalse);
m_worldData.BSLog("initPhysics2: setForceUpdateAllAabbs = %d", (m_worldData.params->shouldForceUpdateAllAabbs != ParamFalse));
// Randomizing the solver order makes object stacking more stable at a slight performance cost
if (m_worldData.params->shouldRandomizeSolverOrder != ParamFalse)
{
dynamicsWorld->getSolverInfo().m_solverMode |= SOLVER_RANDMIZE_ORDER;
m_worldData.BSLog("initPhysics2: setting SOLVER_RANMIZE_ORDER");
}
// Change the breaking threshold if specified.
if (m_worldData.params->globalContactBreakingThreshold != 0)
{
gContactBreakingThreshold = m_worldData.params->globalContactBreakingThreshold;
m_worldData.BSLog("initPhysics2: setting gContactBreakingThreshold = %f", m_worldData.params->globalContactBreakingThreshold);
}
// setting to false means the islands are not reordered and split up for individual processing
if (m_worldData.params->shouldSplitSimulationIslands != ParamFalse)
{
dynamicsWorld->getSimulationIslandManager()->setSplitIslands(true);
m_worldData.BSLog("initPhysics2: setting setSplitIslands => true");
}
else
{
dynamicsWorld->getSimulationIslandManager()->setSplitIslands(false);
m_worldData.BSLog("initPhysics2: setting setSplitIslands => false");
}
if (m_worldData.params->useSingleSidedMeshes != ParamFalse)
{
gContactAddedCallback = SingleSidedMeshCheckCallback;
m_worldData.BSLog("initPhysics2: enabling SingleSidedMeshCheckCallback");
}
/*
// Performance speedup: http://bulletphysics.org/Bullet/phpBB3/viewtopic.php?p=14367
// Actually a NOOP unless Bullet is compiled with USE_SEPDISTANCE_UTIL2 set.
dynamicsWorld->getDispatchInfo().m_useConvexConservativeDistanceUtil = true;
dynamicsWorld->getDispatchInfo().m_convexConservativeDistanceThreshold = btScalar(0.01);
*/
// Performance speedup: from BenchmarkDemo.cpp, ln 381
if (m_worldData.params->shouldEnableFrictionCaching != ParamFalse)
{
m_worldData.dynamicsWorld->getSolverInfo().m_solverMode |= SOLVER_ENABLE_FRICTION_DIRECTION_CACHING; //don't recalculate friction values each frame
m_worldData.BSLog("initPhysics2: enabling SOLVER_ENABLE_FRICTION_DIRECTION_CACHING");
}
// Increasing solver interations can increase stability.
if (m_worldData.params->numberOfSolverIterations > 0)
{
m_worldData.dynamicsWorld->getSolverInfo().m_numIterations = (int)m_worldData.params->numberOfSolverIterations;
m_worldData.BSLog("initPhysics2: setting solver iterations = %f", m_worldData.params->numberOfSolverIterations);
}
// Earth-like gravity
dynamicsWorld->setGravity(btVector3(0.f, 0.f, m_worldData.params->gravity));
m_dumpStatsCount = 0;
if (m_worldData.debugLogCallback != NULL)
{
m_dumpStatsCount = (int)m_worldData.params->physicsLoggingFrames;
if (m_dumpStatsCount != 0)
m_worldData.BSLog("Logging detailed physics stats every %d frames", m_dumpStatsCount);
}
// Information on creating a custom collision computation routine and a pointer to the computation
// of friction and restitution at:
// http://bulletphysics.org/Bullet/phpBB3/viewtopic.php?f=9&t=7922
// foreach body that you want the callback, enable it with:
// body->setCollisionFlags(body->getCollisionFlags() | btCollisionObject::CF_CUSTOM_MATERIAL_CALLBACK);
}
void BulletSim::exitPhysics2()
{
if (m_worldData.dynamicsWorld == NULL)
return;
// Delete solver
if (m_solver != NULL)
{
delete m_solver;
m_solver = NULL;
}
// Delete broadphase
if (m_broadphase != NULL)
{
delete m_broadphase;
m_broadphase = NULL;
}
// Delete dispatcher
if (m_dispatcher != NULL)
{
delete m_dispatcher;
m_dispatcher = NULL;
}
// Delete collision config
if (m_collisionConfiguration != NULL)
{
delete m_collisionConfiguration;
m_collisionConfiguration = NULL;
}
}
// Step the simulation forward by one full step and potentially some number of substeps
int BulletSim::PhysicsStep2(btScalar timeStep, int maxSubSteps, btScalar fixedTimeStep, int* updatedEntityCount, int* collidersCount)
{
int numSimSteps = 0;
if (m_worldData.dynamicsWorld)
{
// The simulation calls the SimMotionState to put object updates into updatesThisFrame.
// m_worldData.BSLog("Before step");
numSimSteps = m_worldData.dynamicsWorld->stepSimulation(timeStep, maxSubSteps, fixedTimeStep);
// m_worldData.BSLog("After step. Steps=%d,updates=%d", numSimSteps, m_worldData.updatesThisFrame.size());
if (m_dumpStatsCount != 0)
{
if (--m_dumpStatsCount <= 0)
{
m_dumpStatsCount = (int)m_worldData.params->physicsLoggingFrames;
// DumpPhysicsStatistics2(this);
DumpActivationInfo2(this);
}
}
// OBJECT UPDATES =================================================================
// Put all of the updates this frame into m_updatesThisFrameArray
int updates = 0;
if (m_worldData.updatesThisFrame.size() > 0)
{
WorldData::UpdatesThisFrameMapType::const_iterator it = m_worldData.updatesThisFrame.begin();
for (; it != m_worldData.updatesThisFrame.end(); it++)
{
m_updatesThisFrameArray[updates] = *(it->second);
updates++;
if (updates >= m_maxUpdatesPerFrame)
break;
}
m_worldData.updatesThisFrame.clear();
}
// Update the values passed by reference into this function
*updatedEntityCount = updates;
// COLLISIONS =================================================================
// Put all of the colliders this frame into m_collidersThisFrameArray
m_collidersThisFrame.clear();
m_collisionsThisFrame = 0;
// m_worldData.BSLog("Checking collision manifolds");
int numManifolds = m_worldData.dynamicsWorld->getDispatcher()->getNumManifolds();
for (int j = 0; j < numManifolds; j++)
{
btPersistentManifold* contactManifold = m_worldData.dynamicsWorld->getDispatcher()->getManifoldByIndexInternal(j);
int numContacts = contactManifold->getNumContacts();
if (numContacts == 0)
continue;
const btCollisionObject* objA = static_cast<const btCollisionObject*>(contactManifold->getBody0());
const btCollisionObject* objB = static_cast<const btCollisionObject*>(contactManifold->getBody1());
// When two objects collide, we only report one contact point
const btManifoldPoint& manifoldPoint = contactManifold->getContactPoint(0);
const btVector3& contactPoint = manifoldPoint.getPositionWorldOnB();
const btVector3 contactNormal = -manifoldPoint.m_normalWorldOnB; // make relative to A
const float penetration = manifoldPoint.getDistance();
RecordCollision(objA, objB, contactPoint, contactNormal, penetration);
if (m_collisionsThisFrame >= m_maxCollisionsPerFrame)
break;
}
// m_worldData.BSLog("Checked manifolds. Collisions=%d", m_collisionsThisFrame);
// Any ghost objects must be relieved of their collisions.
WorldData::SpecialCollisionObjectMapType::iterator it = m_worldData.specialCollisionObjects.begin();
for (; it != m_worldData.specialCollisionObjects.end(); it++)
{
if (m_collisionsThisFrame >= m_maxCollisionsPerFrame)
break;
btCollisionObject* collObj = it->second;
btPairCachingGhostObject* obj = (btPairCachingGhostObject*)btGhostObject::upcast(collObj);
if (obj)
{
RecordGhostCollisions(obj);
}
}
// m_worldData.BSLog("Ghost collisions checked. Total collisions=%d", m_collisionsThisFrame);
*collidersCount = m_collisionsThisFrame;
}
return numSimSteps;
}
void BulletSim::RecordCollision(const btCollisionObject* objA, const btCollisionObject* objB,
const btVector3& contact, const btVector3& norm, const float penetration)
{
btVector3 contactNormal = norm;
// One of the objects has to want to hear about collisions
if ((objA->getCollisionFlags() & BS_WANTS_COLLISIONS) == 0
&& (objB->getCollisionFlags() & BS_WANTS_COLLISIONS) == 0)
{
return;
}
// Get the IDs of colliding objects (stored in the one user definable field)
IDTYPE idA = CONVLOCALID(objA->getUserPointer());
IDTYPE idB = CONVLOCALID(objB->getUserPointer());
// Make sure idA is the lower ID so we don't record both 'A hit B' and 'B hit A'
if (idA > idB)
{
IDTYPE temp = idA;
idA = idB;
idB = temp;
contactNormal = -contactNormal;
}
// m_worldData.BSLog("Collision: idA=%d, idB=%d, contact=<%f,%f,%f>", idA, idB, contact.getX(), contact.getY(), contact.getZ());
// Create a unique ID for this collision from the two colliding object IDs
// We check for duplicate collisions between the two objects because
// there may be multiple hulls involved and thus multiple collisions.
// TODO: decide if this is really a problem -- can this checking be removed?
// How many duplicate manifolds are there?
// Also, using obj->getCollisionFlags() we can pass up only the collisions
// for one object if it's the only one requesting. Wouldn't have to do
// the "Collide(a,b);Collide(b,a)" in BSScene.
COLLIDERKEYTYPE collisionID = ((COLLIDERKEYTYPE)idA << 32) | idB;
// If this collision has not been seen yet, record it
if (m_collidersThisFrame.find(collisionID) == m_collidersThisFrame.end())
{
m_collidersThisFrame.insert(collisionID);
CollisionDesc cDesc;
cDesc.aID = idA;
cDesc.bID = idB;
cDesc.point = contact;
cDesc.normal = contactNormal;
cDesc.penetration = penetration;
m_collidersThisFrameArray[m_collisionsThisFrame] = cDesc;
m_collisionsThisFrame++;
}
}
void BulletSim::RecordGhostCollisions(btPairCachingGhostObject* obj)
{
btManifoldArray manifoldArray;
btBroadphasePairArray& pairArray = obj->getOverlappingPairCache()->getOverlappingPairArray();
int numPairs = pairArray.size();
// For all the pairs of sets of contact points
for (int i=0; i < numPairs; i++)
{
if (m_collisionsThisFrame >= m_maxCollisionsPerFrame)
break;
manifoldArray.clear();
const btBroadphasePair& pair = pairArray[i];
// The real representation is over in the world pair cache
btBroadphasePair* collisionPair = m_worldData.dynamicsWorld->getPairCache()->findPair(pair.m_pProxy0,pair.m_pProxy1);
if (!collisionPair)
continue;
if (collisionPair->m_algorithm)
collisionPair->m_algorithm->getAllContactManifolds(manifoldArray);
// The collision pair has sets of collision points (manifolds)
for (int j=0; j < manifoldArray.size(); j++)
{
btPersistentManifold* contactManifold = manifoldArray[j];
int numContacts = contactManifold->getNumContacts();
const btCollisionObject* objA = static_cast<const btCollisionObject*>(contactManifold->getBody0());
const btCollisionObject* objB = static_cast<const btCollisionObject*>(contactManifold->getBody1());
// TODO: this is a more thurough check than the regular collision code --
// here we find the penetrating contact in the manifold but for regular
// collisions we assume the first point in the manifold is good enough.
// Decide of this extra checking is required or if first point is good enough.
for (int p=0; p < numContacts; p++)
{
const btManifoldPoint& pt = contactManifold->getContactPoint(p);
// If a penetrating contact, this is a hit
if (pt.getDistance()<0.f)
{
const btVector3& contactPoint = pt.getPositionWorldOnA();
const btVector3& normalOnA = -pt.m_normalWorldOnB;
RecordCollision(objA, objB, contactPoint, normalOnA, pt.getDistance());
// Only one contact point for each set of colliding objects
break;
}
}
}
}
}
btCollisionShape* BulletSim::CreateMeshShape2(int indicesCount, int* indices, int verticesCount, float* vertices)
{
// We must copy the indices and vertices since the passed memory is released when this call returns.
btIndexedMesh indexedMesh;
int* copiedIndices = new int[indicesCount];
__wrap_memcpy(copiedIndices, indices, indicesCount * sizeof(int));
int numVertices = verticesCount * 3;
float* copiedVertices = new float[numVertices];
__wrap_memcpy(copiedVertices, vertices, numVertices * sizeof(float));
indexedMesh.m_indexType = PHY_INTEGER;
indexedMesh.m_triangleIndexBase = (const unsigned char*)copiedIndices;
indexedMesh.m_triangleIndexStride = sizeof(int) * 3;
indexedMesh.m_numTriangles = indicesCount / 3;
indexedMesh.m_vertexType = PHY_FLOAT;
indexedMesh.m_numVertices = verticesCount;
indexedMesh.m_vertexBase = (const unsigned char*)copiedVertices;
indexedMesh.m_vertexStride = sizeof(float) * 3;
btTriangleIndexVertexArray* vertexArray = new btTriangleIndexVertexArray();
vertexArray->addIndexedMesh(indexedMesh, PHY_INTEGER);
bool useQuantizedAabbCompression = true;
bool buildBvh = true;
btBvhTriangleMeshShape* meshShape = new btBvhTriangleMeshShape(vertexArray, useQuantizedAabbCompression, buildBvh);
meshShape->setMargin(m_worldData.params->collisionMargin);
return meshShape;
}
btCollisionShape* BulletSim::CreateGImpactShape2(int indicesCount, int* indices, int verticesCount, float* vertices)
{
// We must copy the indices and vertices since the passed memory is released when this call returns.
btIndexedMesh indexedMesh;
int* copiedIndices = new int[indicesCount];
__wrap_memcpy(copiedIndices, indices, indicesCount * sizeof(int));
int numVertices = verticesCount * 3;
float* copiedVertices = new float[numVertices];
__wrap_memcpy(copiedVertices, vertices, numVertices * sizeof(float));
indexedMesh.m_indexType = PHY_INTEGER;
indexedMesh.m_triangleIndexBase = (const unsigned char*)copiedIndices;
indexedMesh.m_triangleIndexStride = sizeof(int) * 3;
indexedMesh.m_numTriangles = indicesCount / 3;
indexedMesh.m_vertexType = PHY_FLOAT;
indexedMesh.m_numVertices = verticesCount;
indexedMesh.m_vertexBase = (const unsigned char*)copiedVertices;
indexedMesh.m_vertexStride = sizeof(float) * 3;
btTriangleIndexVertexArray* vertexArray = new btTriangleIndexVertexArray();
vertexArray->addIndexedMesh(indexedMesh, PHY_INTEGER);
btGImpactMeshShape* meshShape = new btGImpactMeshShape(vertexArray);
m_worldData.BSLog("GreateGImpactShape2: ind=%d, vert=%d", indicesCount, verticesCount);
meshShape->setMargin(m_worldData.params->collisionMargin);
// The gimpact shape needs some help to create its AABBs
meshShape->updateBound();
return meshShape;
}
btCollisionShape* BulletSim::CreateHullShape2(int hullCount, float* hulls )
{
// Create a compound shape that will wrap the set of convex hulls
btCompoundShape* compoundShape = new btCompoundShape(false);
btTransform childTrans;
childTrans.setIdentity();
compoundShape->setMargin(m_worldData.params->collisionMargin);
// Loop through all of the convex hulls and add them to our compound shape
int ii = 1;
for (int i = 0; i < hullCount; i++)
{
int vertexCount = (int)hulls[ii];
// Offset this child hull by its calculated centroid
btVector3 centroid = btVector3((btScalar)hulls[ii+1], (btScalar)hulls[ii+2], (btScalar)hulls[ii+3]);
childTrans.setOrigin(centroid);
// m_worldData.BSLog("CreateHullShape2: %d Centroid = <%f,%f,%f>", i, centroid.getX(), ¢roid.getY(), ¢roid.getZ()); // DEBUG DEBUG
// Create the child hull and add it to our compound shape
btScalar* hullVertices = (btScalar*)&hulls[ii+4];
btConvexHullShape* convexShape = new btConvexHullShape(hullVertices, vertexCount, sizeof(Vector3));
// for (int j = 0; j < vertexCount; j += 3) // DEBUG DEBUG
// { // DEBUG DEBUG
// m_worldData.BSLog("CreateHullShape2: %d %d <%f,%f,%f>", i, j, // DEBUG DEBUG
// hullVertices[j] + 0, // DEBUG DEBUG
// hullVertices[j] + 1, // DEBUG DEBUG
// hullVertices[j] + 2 // DEBUG DEBUG
// ); // DEBUG DEBUG
// } // DEBUG DEBUG
convexShape->setMargin(m_worldData.params->collisionMargin);
compoundShape->addChildShape(childTrans, convexShape);
ii += (vertexCount * 3 + 4);
}
return compoundShape;
}
// If using Bullet' convex hull code, refer to following link for parameter setting
// http://kmamou.blogspot.com/2011/11/hacd-parameters.html
// Another useful reference for ConvexDecomp
// http://www.bulletphysics.org/Bullet/phpBB3/viewtopic.php?t=7159
// From a previously created mesh shape, create a convex hull using the Bullet
// HACD hull creation code. The created hull will go into the hull collection
// so remember to delete it later.
// Returns the created collision shape or NULL if couldn't create
btCollisionShape* BulletSim::BuildHullShapeFromMesh2(btCollisionShape* mesh, HACDParams* parms)
{
#if defined(USEBULLETHACD)
// Get the triangle mesh data out of the passed mesh shape
int shapeType = mesh->getShapeType();
if (shapeType != TRIANGLE_MESH_SHAPE_PROXYTYPE)
{
// If the passed shape doesn't have a triangle mesh, we cannot hullify it.
m_worldData.BSLog("HACD: passed mesh not TRIANGLE_MESH_SHAPE"); // DEBUG DEBUG
return NULL;
}
btStridingMeshInterface* meshInfo = ((btTriangleMeshShape*)mesh)->getMeshInterface();
const unsigned char* vertexBase;
int numVerts;
PHY_ScalarType vertexType;
int vertexStride;
const unsigned char* indexBase;
int indexStride;
int numFaces;
PHY_ScalarType indicesType;
meshInfo->getLockedReadOnlyVertexIndexBase(&vertexBase, numVerts, vertexType, vertexStride, &indexBase, indexStride, numFaces, indicesType);
if (vertexType != PHY_FLOAT || indicesType != PHY_INTEGER)
{
// If an odd data structure, we cannot hullify
m_worldData.BSLog("HACD: triangle mesh not of right types"); // DEBUG DEBUG
return NULL;
}
// Create pointers to the vertices and indices as the PHY types that they are
float* tVertex = (float*)vertexBase;
int tVertexStride = vertexStride / sizeof(float);
int* tIndices = (int*) indexBase;
int tIndicesStride = indexStride / sizeof(int);
m_worldData.BSLog("HACD: nVertices=%d, nIndices=%d", numVerts, numFaces*3); // DEBUG DEBUG
// Copy the vertices/indices into the HACD data structures
std::vector< HACD::Vec3<HACD::Real> > points;
std::vector< HACD::Vec3<long> > triangles;
for (int ii=0; ii < (numVerts * tVertexStride); ii += tVertexStride)
{
HACD::Vec3<HACD::Real> vertex(tVertex[ii], tVertex[ii+1],tVertex[ii+2]);
points.push_back(vertex);
}
for(int ii=0; ii < (numFaces * tIndicesStride); ii += tIndicesStride )
{
HACD::Vec3<long> vertex( tIndices[ii], tIndices[ii+1], tIndices[ii+2]);
triangles.push_back(vertex);
}
meshInfo->unLockReadOnlyVertexBase(0);
m_worldData.BSLog("HACD: structures copied"); // DEBUG DEBUG
// Setup HACD parameters
HACD::HACD myHACD;
myHACD.SetPoints(&points[0]);
myHACD.SetNPoints(points.size());
myHACD.SetTriangles(&triangles[0]);
myHACD.SetNTriangles(triangles.size());
myHACD.SetCompacityWeight((double)parms->compacityWeight);
myHACD.SetVolumeWeight((double)parms->volumeWeight);
myHACD.SetNClusters((size_t)parms->minClusters);
myHACD.SetNVerticesPerCH((size_t)parms->maxVerticesPerHull);
myHACD.SetConcavity((double)parms->concavity);
myHACD.SetAddExtraDistPoints(parms->addExtraDistPoints == ParamTrue ? true : false);
myHACD.SetAddNeighboursDistPoints(parms->addNeighboursDistPoints == ParamTrue ? true : false);
myHACD.SetAddFacesPoints(parms->addFacesPoints == ParamTrue ? true : false);
m_worldData.BSLog("HACD: Before compute. nPoints=%d, nTriangles=%d, minClusters=%f, maxVerts=%f",
points.size(), triangles.size(), parms->minClusters, parms->maxVerticesPerHull); // DEBUG DEBUG
// Hullify the mesh
myHACD.Compute();
int nHulls = myHACD.GetNClusters();
m_worldData.BSLog("HACD: After compute. nHulls=%d", nHulls); // DEBUG DEBUG
// Create the compound shape all the hulls will be added to
btCompoundShape* compoundShape = new btCompoundShape(true);
compoundShape->setMargin(m_worldData.params->collisionMargin);
// Convert each of the built hulls into btConvexHullShape objects and add to the compoundShape
for (int hul=0; hul < nHulls; hul++)
{
size_t nPoints = myHACD.GetNPointsCH(hul);
size_t nTriangles = myHACD.GetNTrianglesCH(hul);
m_worldData.BSLog("HACD: Add hull %d. nPoints=%d, nTriangles=%d", hul, nPoints, nTriangles); // DEBUG DEBUG
// Get the vertices and indices for one hull
HACD::Vec3<HACD::Real> * pointsCH = new HACD::Vec3<HACD::Real>[nPoints];
HACD::Vec3<long> * trianglesCH = new HACD::Vec3<long>[nTriangles];
myHACD.GetCH(hul, pointsCH, trianglesCH);
// Average the location of all the vertices to create a centriod for the hull.
btAlignedObjectArray<btVector3> vertices;
btVector3 centroid;
centroid.setValue(0,0,0);
for (int ii=0; ii < nTriangles; ii++)
{
long tri = trianglesCH[ii].X();
btVector3 corner1(pointsCH[tri].X(), pointsCH[tri].Y(), pointsCH[tri].Z() );
vertices.push_back(corner1);
centroid += corner1;
tri = trianglesCH[ii].Y();
btVector3 corner2(pointsCH[tri].X(), pointsCH[tri].Y(), pointsCH[tri].Z() );
vertices.push_back(corner2);
centroid += corner2;
tri = trianglesCH[ii].Z();
btVector3 corner3(pointsCH[tri].X(), pointsCH[tri].Y(), pointsCH[tri].Z() );
vertices.push_back(corner3);
centroid += corner3;
}
centroid *= 1.f/((float)(nTriangles * 3));
for (int ii=0; ii < vertices.size(); ii++)
{
vertices[ii] -= centroid;
}
delete [] pointsCH;
delete [] trianglesCH;
btConvexHullShape* convexShape;
// Optionally compress the hull a little bit to account for the collision margin.
if (parms->shouldAdjustCollisionMargin == ParamTrue)
{
float collisionMargin = 0.01f;
btAlignedObjectArray<btVector3> planeEquations;
btGeometryUtil::getPlaneEquationsFromVertices(vertices, planeEquations);
btAlignedObjectArray<btVector3> shiftedPlaneEquations;
for (int p=0; p<planeEquations.size(); p++)
{
btVector3 plane = planeEquations[p];
plane[3] += collisionMargin;
shiftedPlaneEquations.push_back(plane);
}
btAlignedObjectArray<btVector3> shiftedVertices;
btGeometryUtil::getVerticesFromPlaneEquations(shiftedPlaneEquations,shiftedVertices);
convexShape = new btConvexHullShape(&(shiftedVertices[0].getX()),shiftedVertices.size());
}
else
{
convexShape = new btConvexHullShape(&(vertices[0].getX()),vertices.size());
}
convexShape->setMargin(m_worldData.params->collisionMargin);
// Add the hull shape to the compound shape
btTransform childTrans;
childTrans.setIdentity();
childTrans.setOrigin(centroid);
m_worldData.BSLog("HACD: Add child shape %d", hul); // DEBUG DEBUG
compoundShape->addChildShape(childTrans, convexShape);
}
return compoundShape;
#else
return NULL;
#endif
}
#if defined(USEVHACD)
// Instance that is called by VHACD to report hulling progress
class VHACDProgressLog : public IVHACD::IUserCallback
{
WorldData* m_WorldData;
public:
VHACDProgressLog(WorldData* wd) {m_WorldData = wd; }
~VHACDProgressLog() {}
void Update(const double overallProgress,
const double stageProgress,
const double operationProgress,
const char * const stage,
const char * const operation)
{
m_WorldData->BSLog("VHACD: progress=%f, stageProg=%f, opProgress=%f, state=%s, op=%s",
overallProgress, stageProgress, operationProgress, stage, operation);
}
};
#endif
btCollisionShape* BulletSim::BuildVHACDHullShapeFromMesh2(btCollisionShape* mesh, HACDParams* parms)
{
#if defined(USEVHACD)
int* triangles; // array of indesex
float* points; // array of coordinates
// copy the mesh into the structures
btStridingMeshInterface* meshInfo = ((btTriangleMeshShape*)mesh)->getMeshInterface();
const unsigned char* vertexBase; // base of the vertice array
int numVerts; // the num of vertices
PHY_ScalarType vertexType; // the data type representing the vertices
int vertexStride; // bytes between each vertex
const unsigned char* indexBase; // base of the index array
int indexStride; // bytes between the index values
int numFaces; // the number of triangles specified by the indexes
PHY_ScalarType indicesType; // the data type of the indexes
meshInfo->getLockedReadOnlyVertexIndexBase(&vertexBase, numVerts, vertexType, vertexStride, &indexBase, indexStride, numFaces, indicesType);
if (vertexType != PHY_FLOAT || indicesType != PHY_INTEGER)
{
// If an odd data structure, we cannot hullify
m_worldData.BSLog("VHACD: triangle mesh not of right types"); // DEBUG DEBUG
return NULL;
}
// Create pointers to the vertices and indices as the PHY types that they are
float* tVertex = (float*)vertexBase;
int tVertexStride = vertexStride / sizeof(float);
int* tIndices = (int*) indexBase;
int tIndicesStride = indexStride / sizeof(int);
m_worldData.BSLog("VHACD: nVertices=%d, nIndices=%d", numVerts, numFaces*3); // DEBUG DEBUG
// Copy the vertices/indices into the HACD data structures
points = new float[numVerts * 3];
triangles = new int[numFaces * 3];
int pp = 0;
for (int ii=0; ii < (numVerts * tVertexStride); ii += tVertexStride)
{
points[pp+0] = tVertex[ii+0];
points[pp+1] = tVertex[ii+1];
points[pp+2] = tVertex[ii+2];
pp += 3;
}
pp = 0;
for(int ii=0; ii < (numFaces * tIndicesStride); ii += tIndicesStride )
{
triangles[pp+0] = tIndices[ii+0];
triangles[pp+1] = tIndices[ii+1];
triangles[pp+2] = tIndices[ii+2];
pp += 3;
}
meshInfo->unLockReadOnlyVertexBase(0);
m_worldData.BSLog("VHACD: structures copied"); // DEBUG DEBUG
IVHACD::Parameters vParams;
vParams.m_resolution = (unsigned int)parms->vHACDresolution;
vParams.m_depth = (int)parms->vHACDdepth;
vParams.m_concavity = (double)parms->vHACDconcavity;
vParams.m_planeDownsampling = (int)parms->vHACDplaneDownsampling;
vParams.m_convexhullDownsampling = (int)parms->vHACDconvexHullDownsampling;
vParams.m_alpha = (double)parms->vHACDalpha;
vParams.m_beta = (double)parms->vHACDbeta;
vParams.m_delta = (double)parms->vHACDdelta;
vParams.m_gamma = (double)parms->vHACDgamma;
vParams.m_pca = (int)parms->vHACDpca;
vParams.m_mode = (int)parms->vHACDmode;
vParams.m_maxNumVerticesPerCH = (unsigned int)parms->vHACDmaxNumVerticesPerCH;
vParams.m_minVolumePerCH = (double)parms->vHACDminVolumePerCH;
vParams.m_callback = new VHACDProgressLog(&m_worldData);
// vParams.m_logger =
vParams.m_convexhullApproximation = (parms->vHACDconvexHullApprox == ParamTrue);
vParams.m_oclAcceleration = (parms->vHACDoclAcceleration == ParamTrue);
IVHACD* interfaceVHACD = CreateVHACD();
bool res = interfaceVHACD->Compute(points, 1, numFaces * 3, triangles, 3, numVerts, vParams);
unsigned int nConvexHulls = interfaceVHACD->GetNConvexHulls();
m_worldData.BSLog("VHACD: After compute. nHulls=%d", nConvexHulls); // DEBUG DEBUG
// Create the compound shape all the hulls will be added to
btCompoundShape* compoundShape = new btCompoundShape(true);
compoundShape->setMargin(m_worldData.params->collisionMargin);
// Convert each of the built hulls into btConvexHullShape objects and add to the compoundShape
IVHACD::ConvexHull ch;
for (unsigned int hul = 0; hul < nConvexHulls; hul++)
{
interfaceVHACD->GetConvexHull(hul, ch);
size_t nPoints = ch.m_nPoints;
size_t nTriangles = ch.m_nTriangles;
m_worldData.BSLog("VHACD: Add hull %d. nPoints=%d, nTriangles=%d", hul, nPoints, nTriangles); // DEBUG DEBUG
// Average the location of all the vertices to create a centriod for the hull.
btAlignedObjectArray<btVector3> vertices;
vertices.reserve(nTriangles);
btVector3 centroid;
centroid.setValue(0,0,0);
/*
int pp = 0;
for (int ii=0; ii < nPoints; ii++)
{
btVector3 vertex(ch.m_points[pp + 0], ch.m_points[pp + 1], ch.m_points[pp + 2] );
vertices.push_back(vertex);
centroid += vertex;
pp += 3;
m_worldData.BSLog("VHACD: Hull %d, vertex %d:<%f,%f,%f>", hul, ii, vertex.getX(), vertex.getY(), vertex.getZ()); // DEBUG DEBUG
}
// centroid *= 1.f/((float)(nPoints));
// Move the vertices to have the common centroid
for (int ii=0; ii < nPoints; ii++)
{
vertices[ii] -= centroid;
}
*/
for (int ii=0; ii < nTriangles; ii++)
{
int tri = ch.m_triangles[ii] * 3;
btVector3 vertex(ch.m_points[tri+0], ch.m_points[tri+1], ch.m_points[tri+2]);
vertices.push_back(vertex);
}
btConvexHullShape* convexShape;
// Optionally compress the hull a little bit to account for the collision margin.
if (parms->shouldAdjustCollisionMargin == ParamTrue)
{
float collisionMargin = 0.01f;
btAlignedObjectArray<btVector3> planeEquations;
btGeometryUtil::getPlaneEquationsFromVertices(vertices, planeEquations);
btAlignedObjectArray<btVector3> shiftedPlaneEquations;
for (int p=0; p<planeEquations.size(); p++)
{
btVector3 plane = planeEquations[p];
plane[3] += collisionMargin;
shiftedPlaneEquations.push_back(plane);
}
btAlignedObjectArray<btVector3> shiftedVertices;
btGeometryUtil::getVerticesFromPlaneEquations(shiftedPlaneEquations,shiftedVertices);
convexShape = new btConvexHullShape(shiftedVertices[0], shiftedVertices.size(), sizeof(btVector3));
}
else
{
convexShape = new btConvexHullShape(vertices[0], vertices.size(), sizeof(btVector3));
}
convexShape->setMargin(m_worldData.params->collisionMargin);
// Add the hull shape to the compound shape
btTransform childTrans;
childTrans.setIdentity();
childTrans.setOrigin(centroid);
m_worldData.BSLog("HACD: Add child shape %d", hul); // DEBUG DEBUG
compoundShape->addChildShape(childTrans, convexShape);
}
// The params structure doesn't have a destructor to get rid of logging and progress callbacks
if (vParams.m_callback)
{
delete vParams.m_callback;
vParams.m_callback = 0;
}
delete [] points;
delete [] triangles;
interfaceVHACD->Clean();
interfaceVHACD->Release();
return compoundShape;
#else
return NULL;
#endif
}
// Return a btConvexHullShape constructed from the passed btCollisonShape.
// Used to create the separate hulls if using the C# HACD algorithm.
btCollisionShape* BulletSim::BuildConvexHullShapeFromMesh2(btCollisionShape* mesh)
{
btConvexHullShape* hullShape = new btConvexHullShape();
// Get the triangle mesh data out of the passed mesh shape
int shapeType = mesh->getShapeType();
if (shapeType != TRIANGLE_MESH_SHAPE_PROXYTYPE)
{
// If the passed shape doesn't have a triangle mesh, we cannot hullify it.
m_worldData.BSLog("BuildConvexHullShapeFromMesh2: passed mesh not TRIANGLE_MESH_SHAPE"); // DEBUG DEBUG
return NULL;
}
btStridingMeshInterface* meshInfo = ((btTriangleMeshShape*)mesh)->getMeshInterface();
const unsigned char* vertexBase;
int numVerts;
PHY_ScalarType vertexType;
int vertexStride;
const unsigned char* indexBase;
int indexStride;
int numFaces;
PHY_ScalarType indicesType;
meshInfo->getLockedReadOnlyVertexIndexBase(&vertexBase, numVerts, vertexType, vertexStride, &indexBase, indexStride, numFaces, indicesType);
if (vertexType != PHY_FLOAT || indicesType != PHY_INTEGER)
{
// If an odd data structure, we cannot hullify
m_worldData.BSLog("BuildConvexHullShapeFromMesh2: triangle mesh not of right types"); // DEBUG DEBUG
return NULL;
}
// Create pointers to the vertices and indices as the PHY types that they are
float* tVertex = (float*)vertexBase;
int tVertexStride = vertexStride / sizeof(float);
int* tIndices = (int*) indexBase;
int tIndicesStride = indexStride / sizeof(int);
m_worldData.BSLog("BuildConvexHullShapeFromMesh2: nVertices=%d, nIndices=%d", numVerts, numFaces*3); // DEBUG DEBUG
// Add points to the hull shape
for(int ii=0; ii < (numFaces * tIndicesStride); ii += tIndicesStride )
{
int point1Index = tIndices[ii + 0] * tVertexStride;
btVector3 point1 = btVector3(tVertex[point1Index + 0], tVertex[point1Index + 1], tVertex[point1Index + 2] );
hullShape->addPoint(point1);
int point2Index = tIndices[ii + 1] * tVertexStride;
btVector3 point2 = btVector3(tVertex[point2Index + 0], tVertex[point2Index + 1], tVertex[point2Index + 2] );
hullShape->addPoint(point2);
int point3Index = tIndices[ii + 2] * tVertexStride;
btVector3 point3 = btVector3(tVertex[point3Index + 0], tVertex[point3Index + 1], tVertex[point3Index + 2] );
hullShape->addPoint(point3);
}
meshInfo->unLockReadOnlyVertexBase(0);
return hullShape;
}
btCollisionShape* BulletSim::CreateConvexHullShape2(int indicesCount, int* indices, int verticesCount, float* vertices)
{
btConvexHullShape* hullShape = new btConvexHullShape();
for (int ii = 0; ii < indicesCount; ii += 3)
{
int point1Index = indices[ii + 0] * 3;
btVector3 point1 = btVector3(vertices[point1Index + 0], vertices[point1Index + 1], vertices[point1Index + 2] );
hullShape->addPoint(point1);
int point2Index = indices[ii + 1] * 3;
btVector3 point2 = btVector3(vertices[point2Index + 0], vertices[point2Index + 1], vertices[point2Index + 2] );
hullShape->addPoint(point2);
int point3Index = indices[ii + 2] * 3;
btVector3 point3 = btVector3(vertices[point3Index + 0], vertices[point3Index + 1], vertices[point3Index + 2] );
hullShape->addPoint(point3);
}
return hullShape;
}
// TODO: get this code working
SweepHit BulletSim::ConvexSweepTest(IDTYPE id, btVector3& fromPos, btVector3& targetPos, btScalar extraMargin)
{
return SweepHit();
/*
SweepHit hit;
hit.ID = ID_INVALID_HIT;
btCollisionObject* castingObject = NULL;
// Look for a character
CharactersMapType::iterator cit = m_characters.find(id);
if (cit != m_characters.end())
castingObject = cit->second;
if (!castingObject)
{
// Look for a rigid body
BodiesMapType::iterator bit = m_bodies.find(id);
if (bit != m_bodies.end())
castingObject = bit->second;
}
if (castingObject)
{
btCollisionShape* shape = castingObject->getCollisionShape();
// Convex sweep test only works with convex objects
if (shape->isConvex())
{
btConvexShape* convex = static_cast<btConvexShape*>(shape);
// Create transforms to sweep from and to
btTransform from;
from.setIdentity();
from.setOrigin(fromPos);
btTransform to;
to.setIdentity();
to.setOrigin(targetPos);
btScalar originalMargin = convex->getMargin();
convex->setMargin(originalMargin + extraMargin);
// Create a callback for the test
ClosestNotMeConvexResultCallback callback(castingObject);
// Do the sweep test
m_worldData.dynamicsWorld->convexSweepTest(convex, from, to, callback, m_worldData.dynamicsWorld->getDispatchInfo().m_allowedCcdPenetration);
if (callback.hasHit())
{
hit.ID = CONVLOCALID(callback.m_hitCollisionObject->getCollisionShape()->getUserPointer());
hit.Fraction = callback.m_closestHitFraction;
hit.Normal = callback.m_hitNormalWorld;
hit.Point = callback.m_hitPointWorld;
}
convex->setMargin(originalMargin);
}
}
return hit;
*/
}
// TODO: get this code working
RaycastHit BulletSim::RayTest(IDTYPE id, btVector3& from, btVector3& to)
{
return RaycastHit();
/*
RaycastHit hit;
hit.ID = ID_INVALID_HIT;
btCollisionObject* castingObject = NULL;
// Look for a character
CharactersMapType::iterator cit = m_characters.find(id);
if (cit != m_characters.end())
castingObject = cit->second;
if (!castingObject)
{
// Look for a rigid body
BodiesMapType::iterator bit = m_bodies.find(id);
if (bit != m_bodies.end())
castingObject = bit->second;
}
if (castingObject)
{
// Create a callback for the test
ClosestNotMeRayResultCallback callback(castingObject);
// Do the raycast test
m_worldData.dynamicsWorld->rayTest(from, to, callback);
if (callback.hasHit())
{
hit.ID = CONVLOCALID(callback.m_collisionObject->getUserPointer());
hit.Fraction = callback.m_closestHitFraction;
hit.Normal = callback.m_hitNormalWorld;
//hit.Point = callback.m_hitPointWorld; // TODO: Is this useful?
}
}
return hit;
*/
}
// TODO: get this code working
const btVector3 BulletSim::RecoverFromPenetration(IDTYPE id)
{
/*
// Look for a character
CharactersMapType::iterator cit = m_characters.find(id);
if (cit != m_characters.end())
{
btCollisionObject* character = cit->second;
ContactSensorCallback contactCallback(character);
m_worldData.dynamicsWorld->contactTest(character, contactCallback);
return contactCallback.mOffset;
}
*/
return btVector3(0.0, 0.0, 0.0);
}
bool BulletSim::UpdateParameter2(IDTYPE localID, const char* parm, float val)
{
btScalar btVal = btScalar(val);
btVector3 btZeroVector3 = btVector3(0, 0, 0);
// changes to the environment
if (strcmp(parm, "gravity") == 0)
{
m_worldData.dynamicsWorld->setGravity(btVector3(0.f, 0.f, val));
return true;
}
return false;
}
// #include "LinearMath/btQuickprof.h"
// Call Bullet to dump its performance stats
// Bullet must be patched to make this work. See BulletDetailLogging.patch
void BulletSim::DumpPhysicsStats()
{
// CProfileManager::dumpAll();
return;
}
| 37.446013 | 149 | 0.738516 | [
"mesh",
"object",
"shape",
"vector",
"transform"
] |
f07a61f37b42c6f288deb59cb2be8b310a50bf17 | 18,160 | cpp | C++ | applis/CompColorees/cCC_OneChannel.cpp | kikislater/micmac | 3009dbdad62b3ad906ec882b74b85a3db86ca755 | [
"CECILL-B"
] | 451 | 2016-11-25T09:40:28.000Z | 2022-03-30T04:20:42.000Z | applis/CompColorees/cCC_OneChannel.cpp | kikislater/micmac | 3009dbdad62b3ad906ec882b74b85a3db86ca755 | [
"CECILL-B"
] | 143 | 2016-11-25T20:35:57.000Z | 2022-03-01T11:58:02.000Z | applis/CompColorees/cCC_OneChannel.cpp | kikislater/micmac | 3009dbdad62b3ad906ec882b74b85a3db86ca755 | [
"CECILL-B"
] | 139 | 2016-12-02T10:26:21.000Z | 2022-03-10T19:40:29.000Z | /*Header-MicMac-eLiSe-25/06/2007
MicMac : Multi Image Correspondances par Methodes Automatiques de Correlation
eLiSe : ELements of an Image Software Environnement
www.micmac.ign.fr
Copyright : Institut Geographique National
Author : Marc Pierrot Deseilligny
Contributors : Gregoire Maillet, Didier Boldo.
[1] M. Pierrot-Deseilligny, N. Paparoditis.
"A multiresolution and optimization-based image matching approach:
An application to surface reconstruction from SPOT5-HRS stereo imagery."
In IAPRS vol XXXVI-1/W41 in ISPRS Workshop On Topographic Mapping From Space
(With Special Emphasis on Small Satellites), Ankara, Turquie, 02-2006.
[2] M. Pierrot-Deseilligny, "MicMac, un lociel de mise en correspondance
d'images, adapte au contexte geograhique" to appears in
Bulletin d'information de l'Institut Geographique National, 2007.
Francais :
MicMac est un logiciel de mise en correspondance d'image adapte
au contexte de recherche en information geographique. Il s'appuie sur
la bibliotheque de manipulation d'image eLiSe. Il est distibue sous la
licences Cecill-B. Voir en bas de fichier et http://www.cecill.info.
English :
MicMac is an open source software specialized in image matching
for research in geographic information. MicMac is built on the
eLiSe image library. MicMac is governed by the "Cecill-B licence".
See below and http://www.cecill.info.
Header-MicMac-eLiSe-25/06/2007*/
#include "CompColore.h"
/*************************************************/
/* */
/* cCC_OneChannel */
/* */
/*************************************************/
Pt2di P0_CornerMort(const cImageCmpCol & aICC)
{
return aICC.BoxPixMort().IsInit() ?
aICC.BoxPixMort().Val().HautG() :
Pt2di(0,0);
}
Pt2di P1_CornerMort(const cImageCmpCol & aICC)
{
return aICC.BoxPixMort().IsInit() ?
aICC.BoxPixMort().Val().BasD() :
Pt2di(0,0);
}
cCC_OneChannel::cCC_OneChannel
(
double aScale,
const cImageCmpCol & anICC,
cCC_Appli & anAppli,
cCC_OneChannel * aMaster
) :
mICC (anICC),
mAppli (anAppli),
mDir (mAppli.WorkDir()),
mNameInit (anICC.NameOrKey()),
mNameCorrige ( (aMaster!=0) ?
anAppli.ICNM()->StdCorrect(mNameInit,aMaster->mNameGeomCorrige,true) :
mNameInit
),
mNameGeomCorrige (
anICC.KeyCalcNameImOfGeom().IsInit() ?
anAppli.ICNM()->Assoc1To1(anICC.KeyCalcNameImOfGeom().Val(),mNameCorrige,true) :
mNameCorrige
),
mNameFile (mAppli.WorkDir() + mNameCorrige),
mFileIm (Tiff_Im::UnivConvStd(mNameFile)),
mTypeIn (
anICC.TypeTmpIn().IsInit() ?
Xml2EL(anICC.TypeTmpIn().Val()) :
mFileIm.type_el()
),
mP0GlobIn (P0_CornerMort(anICC)),
mP1GlobIn (mFileIm.sz()-P1_CornerMort(anICC)),
mCam ( CamCompatible_doublegrid(mDir+anAppli.ICNM()->Assoc1To1(anAppli.CCC().KeyCalcNameCalib(),mNameGeomCorrige,true))),
// mCam ( Std_Cal_From_File(mDir+anAppli.ICNM()->Assoc1To1(anAppli.CCC().KeyCalcNameCalib(),mNameGeomCorrige,true))),
// mCam ( Std_Cal_From_File(mDir+mICC.CalibCam())),
mGrid (0),
mOriFus (0.0,0.0),
mScaleF (aScale),
mChInMade (false),
mMaxChOut (-1)
{
Pt2dr aMil = Pt2dr(mCam->Sz()) / 2.0;
Pt2dr aP1 = aMil + Pt2dr(1,0);
Pt2dr aP2 = aMil - Pt2dr(1,0);
Pt2dr aQ1 = mCam->F2toC2(aP1);
Pt2dr aQ2 = mCam->F2toC2(aP2);
double aDist = euclid(aQ1,aQ2)/2.0;
mFactF2C2 = 1/aDist;
std::cout << "================ Fact " << mFactF2C2 << "\n";
}
Pt2di cCC_OneChannel::SzCurInput() const
{
return mCurP1In-mCurP0In;
}
CamStenope & cCC_OneChannel::Cam()
{
return *mCam;
}
Box2dr cCC_OneChannel::BoxIm2BoxFus(const Box2dr & aBox)
{
return ImageOfBox(aBox,50);
}
Box2dr cCC_OneChannel::GlobBoxFus()
{
return BoxIm2BoxFus(Box2dr(mP0GlobIn,mP1GlobIn));
}
cCC_OneChannel::~cCC_OneChannel()
{
delete mGrid;
DeleteAndClear(mChIns);
}
Pt2dr cCC_OneChannel::Direct(Pt2dr aP) const
{
aP = aP;
return (mAppli.CCC().CorDist().Val()?mCam->DistInverse(aP):aP) * mScaleF;
}
bool cCC_OneChannel::OwnInverse(Pt2dr & aP) const
{
aP = aP/mScaleF;
aP = mAppli.CCC().CorDist().Val()?mCam->DistDirecte(aP):aP;
aP= aP;
return true;
}
bool cCC_OneChannel::SetBoxOut(const Box2di & aBox)
{
Pt2di aPRin(aRabInput,aRabInput);
mOriFus = Pt2dr(aBox._p0);
Box2dr aBoxI = ImageRecOfBox(I2R(aBox),50);
mCurP0In = Sup(mP0GlobIn,round_down(aBoxI._p0)-aPRin);
mCurP1In = Inf(mP1GlobIn,round_up(aBoxI._p1)+aPRin);
if ((mCurP0In.x>= mCurP1In.x) || (mCurP0In.y>= mCurP1In.y))
return false;
return true;
}
void cCC_OneChannel::VirtualPostInit()
{
mGrid = new cDbleGrid
(
true,
Pt2dr(mP0GlobIn),
Pt2dr(mP1GlobIn),
Pt2dr(mAppli.CCC().StepGrid(), mAppli.CCC().StepGrid()),
*this
);
}
Pt2dr cCC_OneChannel::ToFusionSpace(const Pt2dr & aP) const
{
// return (mGrid->Direct(aP+mP0In) - mOriFus) * mScale;
return (mGrid->Direct(aP+Pt2dr(mCurP0In)) - mOriFus) ;
}
Pt2dr cCC_OneChannel::FromFusionSpace(const Pt2dr & aP) const
{
// return mGrid->Inverse(aP/mScale + mOriFus) -mP0In;
return mGrid->Inverse((aP+mOriFus) ) -Pt2dr(mCurP0In);
}
int cCC_OneChannel::MaxChOut()
{
return mMaxChOut;
}
const std::string & cCC_OneChannel::NameCorrige() const
{
return mNameCorrige;
}
const std::string & cCC_OneChannel::NameGeomCorrige() const
{
return mNameGeomCorrige;
}
void cCC_OneChannel::DoChIn()
{
Output aOutGlob = Output::onul();
Fonc_Num aFFRef= 0;
int aCptChIn=0;
for (int aK=0 ; aK<mFileIm.in().dimf_out() ; aK++)
{
Output aOutLoc = Output::onul();
bool First = true;
for
(
std::list<cChannelCmpCol>::const_iterator itCCC = mICC.ChannelCmpCol().begin();
itCCC != mICC.ChannelCmpCol().end();
itCCC++
)
{
if (itCCC->In() == aK)
{
ElSetMax(mMaxChOut,itCCC->Out());
if (! mChInMade)
{
mChIns.push_back
(
new cChannelIn
(
mAppli,
mTypeIn,
*this,
SzCurInput(),
*itCCC
)
);
}
else
mChIns[aCptChIn]->Resize(SzCurInput());
if (First)
aOutLoc = mChIns[aCptChIn]->OutForInit();
else
aOutLoc = aOutLoc | mChIns[aCptChIn]->OutForInit();
First = false;
aCptChIn++;
}
}
if (mICC.FlattField().IsInit())
{
const cFlattField & aFF = mICC.FlattField().Val();
double aVRef = aFF.RefValue()[ElMin(aK,int(aFF.RefValue().size()-1))];
if (aK==0)
aFFRef = aVRef;
else
aFFRef = Virgule(aFFRef,aVRef);
}
if (aK==0)
aOutGlob = aOutLoc;
else
aOutGlob = Virgule(aOutGlob,aOutLoc);
}
Fonc_Num aFMult = 1;
if (mICC.FlattField().IsInit())
{
const cFlattField & aFF = mICC.FlattField().Val();
aFMult = aFFRef / Tiff_Im::BasicConvStd(mAppli.WorkDir()+aFF.NameFile()).in_proj();
}
Fonc_Num aFin = mFileIm.in_proj();
for (int aK=0 ; aK<mICC.NbFilter().Val() ; aK++)
{
int aSzF = mICC.SzFilter().Val();
aFin = rect_som(aFin,aSzF) /ElSquare(1+2*aSzF);
}
// std::cout << mICC.NbFilter().Val() << " " << mNameFile << "\n";
// Video_Win aW = Video_Win::WStd(Pt2di(800,800),1);
ELISE_COPY
(
rectangle(Pt2di(0,0),SzCurInput()),
trans(aFin*aFMult,mCurP0In),
aOutGlob
);
mChInMade = true;
// getchar();
}
const std::vector<cChannelIn *> & cCC_OneChannel::ChIn()
{
return mChIns;
}
/*************************************************/
/* */
/* cCC_OneChannelSec */
/* */
/*************************************************/
cCC_OneChannelSec::cCC_OneChannelSec
(
double aScale,
const cImSec & anIS,
cCC_OneChannel & aMaster,
cCC_Appli & anAppli
) :
cCC_OneChannel (aScale,anIS.Im(),anAppli,&aMaster),
mIS (anIS),
mNameCorresp ( mIS.DirCalcCorrep().Val()
+ anAppli.ICNM()->NamePackWithAutoSym
(
mIS.KeyCalcNameCorresp(),
aMaster.NameGeomCorrige(),
NameGeomCorrige()
)
),
mMaster (aMaster),
mH_M2This (cElHomographie::Id()),
mH_This2M (cElHomographie::Id()),
mGM2This (0)
{
bool ByGrid = false;
if (StdPostfix(mNameCorresp)=="xml")
{
cElXMLTree aTree (mDir + mNameCorresp);
ByGrid = (aTree.Get("GridDirecteEtInverse") != 0);
}
if (ByGrid)
{
cDbleGrid::cXMLMode aXmlMode;
mGM2This = new cDbleGrid(aXmlMode,mDir,mNameCorresp);
}
else
{
ElPackHomologue aPackInit = ElPackHomologue::FromFile(mDir + mNameCorresp);
if (mIS.OffsetPt().IsInit())
{
Pt2dr anOfs = mIS.OffsetPt().Val();
for
(
ElPackHomologue::iterator itPt = aPackInit.begin();
itPt != aPackInit.end();
itPt++
)
{
itPt->P1() = itPt->P1()+anOfs;
itPt->P2() = itPt->P2()+anOfs;
}
}
ElPackHomologue aPackCorDist;
for
(
ElPackHomologue::const_iterator itP = aPackInit.begin();
itP != aPackInit.end();
itP++
)
{
/*
std::cout << "PTS : " << itP->P1() << itP->P2() << "\n";
std::cout << "DIR : " << mMaster.Cam().DistDirecte(itP->P1()) << mCam->DistDirecte(itP->P2()) << "\n";
std::cout << "INV : " << mMaster.Cam().DistInverse(itP->P1()) << mCam->DistInverse(itP->P2()) << "\n";
getchar();
*/
aPackCorDist.Cple_Add
(
ElCplePtsHomologues
(
mMaster.Cam().DistInverse(itP->P1()),
mCam->DistInverse(itP->P2())
/*
mMaster.Cam().DistInverse( mMaster.Cam().DistDirecte(itP->P1())),
mCam->DistInverse( mCam->DistDirecte(itP->P1()))
*/
)
);
}
if (mIS.L2EstimH().Val())
mH_M2This = cElHomographie(aPackCorDist,true);
else if (mIS.L1EstimH().Val())
mH_M2This = cElHomographie(aPackCorDist,false);
else
mH_M2This = cElHomographie::RansacInitH
(
aPackCorDist,
mIS.NbTestRansacEstimH().Val(),
mIS.NbPtsRansacEstimH().Val()
);
for
(
std::list<Pt2dr>::const_iterator itP=mIS.PonderaL2Iter().begin();
itP!=mIS.PonderaL2Iter().end();
itP++
)
{
double aMax = itP->x;
double aPond = itP->y;
int aNb=0;
int aNbOK=0;
double aSomDist=0;
for
(
ElPackHomologue::iterator itCpl=aPackCorDist.begin();
itCpl!=aPackCorDist.end();
itCpl++
)
{
Pt2dr aP1 = itCpl->P1();
Pt2dr aP2 = itCpl->P2();
Pt2dr aQ2 = mH_M2This.Direct(aP1);
double aDist = euclid(aP2,aQ2) * mFactF2C2;
double aPds = (aDist>aMax) ?
0 :
1/sqrt(1+ElSquare(aDist/aPond)) ;
itCpl->Pds() = aPds;
aNb++;
if (aDist<aMax)
{
aNbOK++;
aSomDist+=aDist;
}
}
mH_M2This = cElHomographie(aPackCorDist,true);
std::cout << "OK = " << aNbOK << " on " << aNb << " DMoy " << (aSomDist/aNbOK) << "\n";
}
mH_This2M = mH_M2This.Inverse();
}
}
Pt2dr cCC_OneChannelSec::Direct(Pt2dr aP) const
{
if (mGM2This)
{
aP = mGM2This->Inverse(aP);
return (mAppli.CCC().CorDist().Val()? mMaster.Cam().DistInverse(aP) : aP) * mScaleF;
}
aP = mH_This2M.Direct(mCam->DistInverse(aP));
return (mAppli.CCC().CorDist().Val()? aP : mMaster.Cam().DistDirecte(aP)) * mScaleF;
}
bool cCC_OneChannelSec::OwnInverse(Pt2dr & aP) const
{
aP = aP/mScaleF;
if (mGM2This)
{
aP = mAppli.CCC().CorDist().Val()? mMaster.Cam().DistDirecte(aP) : aP;
aP = mGM2This->Direct(aP);
}
else
{
aP = mAppli.CCC().CorDist().Val()?aP :mMaster.Cam().DistInverse(aP);
aP = mCam->DistDirecte(mH_M2This.Direct(aP));
}
return true;
}
cCC_OneChannelSec::~cCC_OneChannelSec()
{
delete mGM2This;
}
void cCC_OneChannelSec::TestVerif()
{
if (!mIS.VerifHoms().IsInit())
return;
const cVerifHoms & aVH = mIS.VerifHoms().Val();
double aSD = 0.0;
double aSDV = 0.0;
double aS1 = 0.0;
double aDZ =0,anExag=0;
El_Window * aW=0;
Bitm_Win * aBW = 0;
bool aVXY=false;
double anExagXY=0;
Im2D_REAL4 aVX(1,1);
Im2D_REAL4 aVY(1,1);
std::string aNameFile;
if (aVH.VisuEcart().IsInit())
{
cVisuEcart aVE = aVH.VisuEcart().Val();
Pt2dr aSz = Pt2dr(mFileIm.sz());
aDZ = aVE.SzW() / ElMax(aSz.x,aSz.y);
if (aVE.NameFile().IsInit())
{
aBW = new Bitm_Win("Toto.tif",GlobPal(),Pt2di(aSz*aDZ));
ELISE_COPY(aBW->all_pts(),P8COL::black,aBW->odisc());
aW = aBW;
aNameFile = mAppli.WorkDir() + aVE.NameFile().Val();
// aW = new Bitm_Win("Toto.tif",aSz*aDZ);
}
else
aW = Video_Win::PtrWStd(Pt2di(aSz*aDZ));
anExag = aVE.Exag();
if (aVE.Images2Verif().IsInit())
{
cImages2Verif aCI2V = aVE.Images2Verif().Val();
aVX = Im2D_REAL4::FromFileStd(mDir+aCI2V.X());
aVY = Im2D_REAL4::FromFileStd(mDir+aCI2V.Y());
anExagXY = aCI2V.ExagXY();
aVXY = true;
}
}
TIm2D<REAL4,REAL8> aTX(aVX);
TIm2D<REAL4,REAL8> aTY(aVY);
std::string aNamePck = mAppli.ICNM()->StdCorrect2
(
aVH.NameOrKeyHomologues(),
mMaster.NameCorrige(),
mNameCorrige,
true
);
ElPackHomologue aPackV = ElPackHomologue::FromFile(mDir+aNamePck);
for
(
ElPackHomologue::const_iterator itP = aPackV.begin();
itP != aPackV.end();
itP++
)
{
Pt2dr aV12 = itP->P2() - FromFusionSpace(mMaster.ToFusionSpace(itP->P1()));
Pt2dr aDifVXY(0,0);
if (aVXY)
{
Pt2dr aR2(aTX.getprojR(itP->P1()),aTY.getprojR(itP->P1()));
aDifVXY = itP->P2()-aR2;
aSDV += euclid(aDifVXY);
}
double aDist = euclid(aV12) ;
aS1++;
aSD += aDist;
if (aW)
{
Pt2dr aPC = itP->P1() * aDZ;
// aW->draw_circle_abs(aPC,2.0,aW->pdisc()(P8COL::green));
Pt2dr aLarg(1,1);
aW->fill_rect(aPC-aLarg,aPC+aLarg,aW->pdisc()(P8COL::green));
aW->draw_seg(aPC,aPC+aV12*anExag,aW->pdisc()(P8COL::red));
if (aVXY)
aW->draw_seg(aPC,aPC+aDifVXY*anExagXY,aW->pdisc()(P8COL::blue));
}
}
std::cout << "Dist Moyenne " << aSD / aS1 << "\n";
std::cout << "Verif Dist Moyenne " << aSDV / aS1 << "\n";
if (aBW)
{
aBW->make_gif(aNameFile.c_str());
std::cout << "Done bitm "<< aNameFile << "\n";
}
}
/*Footer-MicMac-eLiSe-25/06/2007
Ce logiciel est un programme informatique servant à la mise en
correspondances d'images pour la reconstruction du relief.
Ce logiciel est régi par la licence CeCILL-B soumise au droit français et
respectant les principes de diffusion des logiciels libres. Vous pouvez
utiliser, modifier et/ou redistribuer ce programme sous les conditions
de la licence CeCILL-B telle que diffusée par le CEA, le CNRS et l'INRIA
sur le site "http://www.cecill.info".
En contrepartie de l'accessibilité au code source et des droits de copie,
de modification et de redistribution accordés par cette licence, il n'est
offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
seule une responsabilité restreinte pèse sur l'auteur du programme, le
titulaire des droits patrimoniaux et les concédants successifs.
A cet égard l'attention de l'utilisateur est attirée sur les risques
associés au chargement, à l'utilisation, à la modification et/ou au
développement et à la reproduction du logiciel par l'utilisateur étant
donné sa spécificité de logiciel libre, qui peut le rendre complexe à
manipuler et qui le réserve donc à des développeurs et des professionnels
avertis possédant des connaissances informatiques approfondies. Les
utilisateurs sont donc invités à charger et tester l'adéquation du
logiciel à leurs besoins dans des conditions permettant d'assurer la
sécurité de leurs systèmes et ou de leurs données et, plus généralement,
à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
pris connaissance de la licence CeCILL-B, et que vous en avez accepté les
termes.
Footer-MicMac-eLiSe-25/06/2007*/
| 28.419405 | 130 | 0.549449 | [
"vector"
] |
f07fff4135b3793370090166c10f6d683c926072 | 518 | cpp | C++ | GY/1156.cpp | windcry1/My-ACM-ICPC | b85b1c83b72c6b51731dae946a0df57c31d3e7a1 | [
"MIT"
] | null | null | null | GY/1156.cpp | windcry1/My-ACM-ICPC | b85b1c83b72c6b51731dae946a0df57c31d3e7a1 | [
"MIT"
] | null | null | null | GY/1156.cpp | windcry1/My-ACM-ICPC | b85b1c83b72c6b51731dae946a0df57c31d3e7a1 | [
"MIT"
] | null | null | null | #include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<cctype>
#include<ctime>
#include<iostream>
#include<string>
#include<map>
#include<queue>
#include<stack>
#include<set>
#include<vector>
#include<iomanip>
#include<bitset>
#include<algorithm>
#define ll long long
using namespace std;
int main(){
ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
string s1,s2;
while(cin>>s1>>s2){
int res=(s1[0]-'0')*10+s1[1]-'0'+(s2[0]-'0')*10+s2[1]-'0';
cout<<res<<endl;
}
return 0;
}
| 17.862069 | 61 | 0.675676 | [
"vector"
] |
f080ce2e4cbc95eb9571ebb9853647bcfee86701 | 5,413 | cxx | C++ | dune/stuff/test/common.cxx | ftalbrecht/dune-stuff-simplified | fc1f80dedaa78fae6e6d67e8f5424a6b3ec86b5d | [
"BSD-2-Clause"
] | null | null | null | dune/stuff/test/common.cxx | ftalbrecht/dune-stuff-simplified | fc1f80dedaa78fae6e6d67e8f5424a6b3ec86b5d | [
"BSD-2-Clause"
] | null | null | null | dune/stuff/test/common.cxx | ftalbrecht/dune-stuff-simplified | fc1f80dedaa78fae6e6d67e8f5424a6b3ec86b5d | [
"BSD-2-Clause"
] | null | null | null | // This file is part of the dune-stuff project:
// https://github.com/wwu-numerik/dune-stuff
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#include "config.h"
#include <cmath>
#include <sys/time.h>
#include <vector>
#include <map>
#include <string>
#include <sstream>
#include <dune/stuff/test/gtest/gtest.h>
#include <dune/stuff/common/configuration.hh>
#include <dune/stuff/common/exceptions.hh>
#include "common.hh"
void busywait(const size_t ms)
{
// "round" up to next full 10 ms to align with native timer res
const size_t milliseconds = (ms / 10) * 10 + 10;
timeval start, end;
gettimeofday(&start, NULL);
do {
gettimeofday(&end, NULL);
} while (((end.tv_sec - start.tv_sec) * 1e6) + ((end.tv_usec - start.tv_usec)) < milliseconds * 1000);
} // ... busywait(...)
namespace Dune {
namespace Stuff {
namespace Test {
namespace internal {
std::pair<size_t, ssize_t> convert_to_scientific(const double number, const size_t precision)
{
// see http://www.mathworks.com/matlabcentral/newsreader/view_thread/151859
const double sign = (number > 0.0) ? 1.0 : -1.0;
const double tmp = std::log10(std::abs(number));
ssize_t exponent = ((tmp > 0) ? 1 : -1) * std::floor(std::abs(tmp));
double coefficient = sign * std::pow(10.0, tmp - exponent);
if (std::abs(coefficient) < 1.0) {
coefficient *= 10.0;
exponent -= 1;
}
const double factor = std::pow(10, precision);
return std::make_pair(size_t(std::round(factor * coefficient)), exponent);
} // ... convert_to_scientific(...)
std::string print_vector(const std::vector<double>& vec)
{
if (vec.empty())
return "{}";
else {
std::stringstream ss;
ss << "{" << std::setprecision(2) << std::scientific << vec[0];
for (size_t ii = 1; ii < vec.size(); ++ii)
ss << ", " << std::setprecision(2) << std::scientific << vec[ii];
ss << "}";
return ss.str();
}
} // ... print_vector(...)
} // namespace internal
void check_eoc_study_for_success(const Dune::Stuff::Common::ConvergenceStudy& study,
const std::map<std::string, std::vector<double>>& results_map)
{
for (const auto& norm : study.used_norms()) {
const auto expected_results = study.expected_results(norm);
const auto results_search = results_map.find(norm);
EXPECT_NE(results_search, results_map.end()) << " norm = " << norm;
if (results_search == results_map.end())
return;
const auto& actual_results = results_search->second;
EXPECT_LE(actual_results.size(), expected_results.size()) << " norm = " << norm;
if (actual_results.size() > expected_results.size())
return;
for (size_t ii = 0; ii < actual_results.size(); ++ii) {
const auto actual_result = internal::convert_to_scientific(actual_results[ii], 2);
const auto expected_result = internal::convert_to_scientific(expected_results[ii], 2);
const auto actual_exponent = actual_result.second;
const auto expected_exponent = expected_result.second;
EXPECT_EQ(expected_exponent, actual_exponent)
<< " Exponent comparison (in scientific notation, precision 2) failed for\n"
<< " norm: " << norm << "\n"
<< " actual_results[" << ii << "] = " << actual_results[ii] << "\n"
<< " expected_results[" << ii << "] = " << expected_results[ii];
if (actual_exponent != expected_exponent)
return;
const auto actual_coefficient = actual_result.first;
const auto expected_coefficient = expected_result.first;
EXPECT_EQ(expected_coefficient, actual_coefficient)
<< " Coefficient comparison (in scientific notation, precision 2) failed for\n"
<< " norm: " << norm << "\n"
<< " actual_results[" << ii << "] = " << actual_results[ii] << "\n"
<< " expected_results[" << ii << "] = " << expected_results[ii];
}
}
} // ... check_eoc_study_for_success(...)
void print_collected_eoc_study_results(const std::map<std::string, std::vector<double>>& results, std::ostream& out)
{
if (results.empty())
DUNE_THROW(Exceptions::wrong_input_given, "Given results must not be empty!");
std::vector<std::string> actually_used_norms;
for (const auto& element : results)
actually_used_norms.push_back(element.first);
out << "if (type == \"" << actually_used_norms[0] << "\")\n";
out << " return " << internal::print_vector(results.at(actually_used_norms[0])) << ";\n";
for (size_t ii = 1; ii < actually_used_norms.size(); ++ii) {
out << "else if (type == \"" << actually_used_norms[ii] << "\")\n";
out << " return " << internal::print_vector(results.at(actually_used_norms[ii])) << ";\n";
}
out << "else\n";
out << " EXPECT_TRUE(false) << \"test results missing for type: \" << type;\n";
out << "return {};" << std::endl;
} // ... print_collected_eoc_study_results(...)
unsigned int grid_elements()
{
return DSC_CONFIG.has_key("test.gridelements") // <- doing this so complicated to
? DSC_CONFIG.get<unsigned int>(
"test.gridelements", 3u, DSC::ValidateLess<unsigned int>(2u)) // silence the WARNING: ...
: 3u;
} // ... grid_elements(...)
} // namespace Test
} // namespace Stuff
} // namespace Dune
| 40.395522 | 116 | 0.628117 | [
"vector"
] |
f080ec97ed8f697e992b4fa67ebd4328e8f737c6 | 4,735 | cpp | C++ | libNCUI/module/dll/DllManager.cpp | realmark1r8h/tomoyadeng | aceab8fe403070bc12f9d49fdb7add0feb20424d | [
"BSD-2-Clause"
] | 24 | 2018-11-20T14:45:57.000Z | 2021-12-30T13:38:42.000Z | libNCUI/module/dll/DllManager.cpp | realmark1r8h/tomoyadeng | aceab8fe403070bc12f9d49fdb7add0feb20424d | [
"BSD-2-Clause"
] | null | null | null | libNCUI/module/dll/DllManager.cpp | realmark1r8h/tomoyadeng | aceab8fe403070bc12f9d49fdb7add0feb20424d | [
"BSD-2-Clause"
] | 11 | 2018-11-29T00:09:14.000Z | 2021-11-23T08:13:17.000Z | #include "stdafx.h"
#include "module/dll/DllManager.h"
#include <amo/path.hpp>
#include <amo/loader.hpp>
#pragma comment(lib, "Dbghelp.lib")
namespace amo {
DllManagerBase::DllManagerBase() {
setRunOnRenderThread(false);
setExtensionDir(amo::u8string("renderer_modules", true));
}
DllManagerBase::~DllManagerBase() {
clear();
}
std::vector<amo::u8string> DllManagerBase::exports(const amo::u8string& name) {
std::shared_ptr<amo::loader> ptr = load(name);
std::vector<amo::u8string> vec;
if (!ptr) {
return vec;
}
ptr->exports(vec);
return vec;
}
std::shared_ptr<amo::loader> DllManagerBase::load(const amo::u8string& name) {
amo::u8string path = getFullPath(name);
if (path.empty()) {
return std::shared_ptr<amo::loader>();
}
auto iter = m_oMap.find(path);
std::shared_ptr<amo::loader> ptr;
if (iter != m_oMap.end()) {
ptr = iter->second;
} else {
ptr.reset(new amo::loader(path));
bool bOk = ptr->load();
if (!bOk) {
ptr.reset();
} else {
m_oMap[path] = ptr;
}
}
return ptr;
}
void DllManagerBase::unload(const amo::u8string& name) {
}
amo::u8string DllManagerBase::getFullPath(const amo::u8string& str) {
// 添加后缀名
amo::u8string name = addSuffix(str);
amo::u8path p(name);
// 判断当前路径是否为绝对路径,如果是那么直接返回
if (!p.is_relative()) {
return name;
}
// 如果不是,那么以当前程序所在目录为当前目录
amo::u8string exeDir(amo::u8path::getExeDir(), true);
amo::u8path pa(exeDir);
// 1. 假设所dll在当前目录
pa.append(name.str());
$cdevel(pa.generic_ansi_string());
// 如果这个dll存在,那么返回
if (pa.file_exists()) {
return amo::u8string(pa.c_str(), true);
}
pa = amo::u8path(exeDir);
// 2. 在扩展目录下查找
pa.append(getExtensionDir().str()).append(name.str());
$cdevel(pa.generic_ansi_string());
if (pa.file_exists()) {
return amo::u8string(pa.c_str(), true);
}
// 3. 到系统目录下查找
pa = amo::u8path("C:\\windows\\system32\\");
pa.append(name.str());
$cdevel(pa.generic_ansi_string());
if (pa.file_exists()) {
return amo::u8string(pa.c_str(), true);
}
return amo::u8string("", true);
}
std::shared_ptr<amo::loader> DllManagerBase::get(const amo::u8string& name) {
amo::u8string str = getFullPath(name);
auto iter = m_oMap.find(str);
return iter->second;
}
amo::u8string DllManagerBase::addSuffix(const amo::u8string& name) {
amo::u8string str = name;
if (!str.end_with(amo::u8string(".dll", true))) {
str += ".dll";
}
return str;
}
void DllManagerBase::addArgsList(const std::string& dllName,
const std::string& argsList) {
DllFunctionWrapper& funcWrapper = getDllFunctionWrapper(dllName);
funcWrapper.addArgsList(argsList);
}
DllFunctionWrapper& DllManagerBase::getDllFunctionWrapper(
const std::string& dllName) {
auto iter = m_oDllArgsMap.find(amo::u8string(dllName, true));
if (iter == m_oDllArgsMap.end()) {
iter = m_oDllArgsMap.insert(std::make_pair(amo::u8string(dllName, true),
DllFunctionWrapper(dllName))).first;
}
return iter->second;
}
amo::u8string DllManagerBase::getExtensionDir() const {
return m_strExtensionDir;
}
void DllManagerBase::setExtensionDir(amo::u8string val) {
m_strExtensionDir = val;
}
bool DllManagerBase::getRunOnRenderThread() const {
return m_bRunOnRenderThread;
}
void DllManagerBase::setRunOnRenderThread(bool val) {
m_bRunOnRenderThread = val;
if (m_bRunOnRenderThread) {
setExtensionDir(amo::u8string("renderer_modules", true));
} else {
setExtensionDir(amo::u8string("browser_modules", true));
}
}
void DllManagerBase::clear() {
for (auto p : m_oMap) {
p.second->exec<amo::nil>("unregisterTransfer");
}
m_oMap.clear();
m_oDllArgsMap.clear();
}
}
| 26.903409 | 84 | 0.523126 | [
"vector"
] |
f093fb1fc220e957d05df5964c557e356f4e13e9 | 11,325 | cpp | C++ | Official Windows Platform Sample/Windows 8.1 desktop samples/[C++]-Windows 8.1 desktop samples/How to Use InteractionContext/C++/InteractionContextSample.cpp | zzgchina888/msdn-code-gallery-microsoft | 21cb9b6bc0da3b234c5854ecac449cb3bd261f29 | [
"MIT"
] | 8 | 2017-04-30T17:38:27.000Z | 2021-11-29T00:59:03.000Z | Samples/InteractionContextProduceTouchInput/cpp/InteractionContextSample.cpp | TomeSq/Windows-classic-samples | 96f883e4c900948e39660ec14a200a5164a3c7b7 | [
"MIT"
] | 1 | 2022-03-15T04:21:41.000Z | 2022-03-15T04:21:41.000Z | Samples/InteractionContextProduceTouchInput/cpp/InteractionContextSample.cpp | TomeSq/Windows-classic-samples | 96f883e4c900948e39660ec14a200a5164a3c7b7 | [
"MIT"
] | 2 | 2020-08-11T13:21:49.000Z | 2021-09-01T10:41:51.000Z | //// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
//// PARTICULAR PURPOSE.
////
//// Copyright (c) Microsoft Corporation. All rights reserved
#include "pch.h"
#include "InteractionContextSample.h"
#include <InteractionContext.h>
// C RunTime header files
#define _USE_MATH_DEFINES // has to be defined to activate definition of M_PI
#include <math.h>
#include <limits.h>
#define GESTURE_ENGINE_TIMER_ID 42
using namespace std;
using namespace Microsoft::WRL;
// <summary>
// Initializes the elements that will be used to draw the application UI.
// Unless otherwise specified, each of these elements is intended to
// resize, relayout or show different UI in response to DPI changes.
// </summary>
CInteractionContextSample::CInteractionContextSample()
{
m_interactionContext = NULL;
m_timerId = 0;
m_frameId = 0xffffffff;
}
CInteractionContextSample::~CInteractionContextSample()
{
if (m_interactionContext)
{
DestroyInteractionContext(m_interactionContext);
m_interactionContext = NULL;
}
m_deviceResources->RegisterDeviceNotify(nullptr);
}
// <summary>
// This method initializes member variables and objects required by this class.
// This method will be called once base class initialize functionality completes.
// </summary>
HRESULT
CInteractionContextSample::Initialize(
_In_ RECT bounds,
_In_ std::wstring title
)
{
HRESULT hr = S_OK;
// Initialize object state
m_diagonalsOn = false;
m_initializeDone = false;
// First run Initialize method for base class.
hr = __super::Initialize(bounds, title);
// Register this class as a DeviceLostHandler. This enables the app to release and recreate the
// device specific resources associated with the app.
m_deviceResources->RegisterDeviceNotify(this);
if (SUCCEEDED(hr))
{
hr = CreateInteractionContext(&m_interactionContext);
}
if (SUCCEEDED(hr))
{
hr = RegisterOutputCallbackInteractionContext(m_interactionContext, InteractionOutputCallback, this);
}
if (SUCCEEDED(hr))
{
hr = SetPropertyInteractionContext(m_interactionContext, INTERACTION_CONTEXT_PROPERTY_FILTER_POINTERS, FALSE);
}
if (SUCCEEDED(hr))
{
// Configure the recognizer to support the set of gestures we will be using for the sample. Each gesture
// you want to support must be listed.
INTERACTION_CONTEXT_CONFIGURATION cfg[] =
{
{INTERACTION_ID_MANIPULATION,
INTERACTION_CONFIGURATION_FLAG_MANIPULATION |
INTERACTION_CONFIGURATION_FLAG_MANIPULATION_TRANSLATION_X |
INTERACTION_CONFIGURATION_FLAG_MANIPULATION_TRANSLATION_Y |
INTERACTION_CONFIGURATION_FLAG_MANIPULATION_ROTATION |
INTERACTION_CONFIGURATION_FLAG_MANIPULATION_SCALING |
INTERACTION_CONFIGURATION_FLAG_MANIPULATION_TRANSLATION_INERTIA |
INTERACTION_CONFIGURATION_FLAG_MANIPULATION_ROTATION_INERTIA |
INTERACTION_CONFIGURATION_FLAG_MANIPULATION_SCALING_INERTIA},
{INTERACTION_ID_TAP,
INTERACTION_CONFIGURATION_FLAG_TAP},
{INTERACTION_ID_SECONDARY_TAP,
INTERACTION_CONFIGURATION_FLAG_SECONDARY_TAP},
};
hr = SetInteractionConfigurationInteractionContext(
m_interactionContext, sizeof(cfg) / sizeof(cfg[0]), cfg);
}
return hr;
}
void
CInteractionContextSample::CreateDeviceIndependentResources()
{
}
void
CInteractionContextSample::ReleaseDeviceIndependentResources()
{
}
void
CInteractionContextSample::CreateDeviceResources()
{
auto d2dContext = m_deviceResources->GetD2DDeviceContext();
d2dContext->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &m_blackBrush);
}
void
CInteractionContextSample::ReleaseDeviceResources()
{
m_blackBrush.Reset();
}
// <summary>
// Draw client area.
// Function overrides virtual member function to
// draw member components defined in DPI window class.
// </summary>
void
CInteractionContextSample::Draw()
{
HRESULT hr = S_OK;
BOOL fResult = FALSE;
RECT rect = { };
auto d2dContext = m_deviceResources->GetD2DDeviceContext();
auto sizeF = d2dContext->GetSize();
if (!m_initializeDone)
{
ResetRect();
m_initializeDone = true;
}
d2dContext->SetTransform(m_transformToUpdate);
d2dContext->DrawRectangle(
D2D1::RectF(
-(sizeF.width / 4),
-(sizeF.height / 4),
sizeF.width/4,
sizeF.height/4),
m_blackBrush.Get()
);
if (m_diagonalsOn)
{
d2dContext->DrawLine(
D2D1::Point2F(-(sizeF.width / 4), -(sizeF.height / 4)),
D2D1::Point2F(sizeF.width / 4, sizeF.height / 4),
m_blackBrush.Get()
);
d2dContext->DrawLine(
D2D1::Point2F(sizeF.width / 4, -(sizeF.height / 4)),
D2D1::Point2F(-(sizeF.width / 4), sizeF.height / 4),
m_blackBrush.Get()
);
}
}
void
CInteractionContextSample::ResetRect()
{
auto d2dContext = m_deviceResources->GetD2DDeviceContext();
auto sizeF = d2dContext->GetSize();
m_transformToUpdate = (
D2D1::Matrix3x2F::Translation(sizeF.width / 2, sizeF.height / 2)
);
}
void
CInteractionContextSample::OnPointerUp(
_In_ float /* x */,
_In_ float /* y */,
_In_ UINT pointerId
)
{
PointerHandling(pointerId);
}
void
CInteractionContextSample::OnPointerDown(
_In_ float /* x */,
_In_ float /* y */,
_In_ UINT pointerId
)
{
PointerHandling(pointerId);
}
void
CInteractionContextSample::OnPointerUpdate(
_In_ float /* x */,
_In_ float /* y */,
_In_ UINT pointerId
)
{
PointerHandling(pointerId);
}
void
CInteractionContextSample::OnPointerWheel(
_In_ UINT pointerId
)
{
PointerHandling(pointerId);
}
void
CInteractionContextSample::OnPointerHWheel(
_In_ UINT pointerId
)
{
PointerHandling(pointerId);
}
void
CInteractionContextSample::PointerHandling(UINT pointerId)
{
// Get frame id from current message.
POINTER_INFO pointerInfo = {};
if (GetPointerInfo(pointerId, &pointerInfo))
{
if (pointerInfo.frameId != m_frameId)
{
// This is the new frame to process.
m_frameId = pointerInfo.frameId;
// Find out pointer count and frame history length.
UINT entriesCount = 0;
UINT pointerCount = 0;
if (GetPointerFrameInfoHistory(pointerId, &entriesCount, &pointerCount, NULL))
{
// Allocate space for pointer frame history.
POINTER_INFO *pointerInfoFrameHistory = NULL;
try
{
pointerInfoFrameHistory = new POINTER_INFO[entriesCount * pointerCount];
}
catch (...)
{
pointerInfoFrameHistory = NULL;
}
if (pointerInfoFrameHistory != NULL)
{
// Retrieve pointer frame history.
if (GetPointerFrameInfoHistory(pointerId, &entriesCount, &pointerCount, pointerInfoFrameHistory))
{
// As multiple frames may have occurred, we need to process them.
ProcessPointerFramesInteractionContext(m_interactionContext, entriesCount, pointerCount, pointerInfoFrameHistory);
}
delete [] pointerInfoFrameHistory;
pointerInfoFrameHistory = NULL;
}
}
}
}
}
void CALLBACK
CInteractionContextSample::InteractionOutputCallback(
__in_opt void *clientData,
__in_ecount(1) const INTERACTION_CONTEXT_OUTPUT *output)
{
CInteractionContextSample* icSample = reinterpret_cast<CInteractionContextSample*>(clientData);
if (icSample == NULL)
{
return;
}
icSample->OnInteractionOutputCallback(output);
}
void
CInteractionContextSample::OnInteractionOutputCallback(__in_ecount(1) const INTERACTION_CONTEXT_OUTPUT *output)
{
switch (output->interactionId)
{
default:
case INTERACTION_ID_NONE:
break;
case INTERACTION_ID_MANIPULATION:
{
// Apply delta transform to the object.
if (!(output->interactionFlags & INTERACTION_FLAG_END))
{
POINT pt =
{
static_cast<long>(output->x),
static_cast<long>(output->y)
};
ScreenToClient(&pt);
auto d2dContext = m_deviceResources->GetD2DDeviceContext();
d2dContext->GetTransform(&m_transformToUpdate);
// A manipulation is composed of scaling, translation, and rotation. This applies
// those aspects to the existing state of the object to make it stick to the finger(s).
m_transformToUpdate = m_transformToUpdate *
D2D1::Matrix3x2F::Rotation(
output->arguments.manipulation.delta.rotation * 180 / static_cast<float>(M_PI),
D2D1::Point2F(static_cast<float>(pt.x), static_cast<float>(pt.y))
) * D2D1::Matrix3x2F::Scale(
output->arguments.manipulation.delta.scale,
output->arguments.manipulation.delta.scale,
D2D1::Point2F(static_cast<float>(pt.x), static_cast<float>(pt.y))
) * D2D1::Matrix3x2F::Translation(
output->arguments.manipulation.delta.translationX,
output->arguments.manipulation.delta.translationY
);
}
// Kick-off inertia timer.
if (output->interactionFlags & INTERACTION_FLAG_INERTIA)
{
if ((output->interactionFlags & INTERACTION_FLAG_END) != 0)
{
if (m_timerId != 0)
{
KillTimer(m_timerId);
m_timerId = 0;
}
}
else
{
if (m_timerId == 0)
{
m_timerId = SetTimer(GESTURE_ENGINE_TIMER_ID, 15, NULL);
}
}
}
}
break;
case INTERACTION_ID_SECONDARY_TAP:
ResetRect();
break;
case INTERACTION_ID_TAP:
m_diagonalsOn = !m_diagonalsOn;
break;
}
}
void
CInteractionContextSample::OnPointerCaptureChange(_In_ WPARAM /* wparam */)
{
StopInteractionContext(m_interactionContext);
}
void
CInteractionContextSample::OnTimerUpdate(_In_ WPARAM wparam)
{
if ((wparam == GESTURE_ENGINE_TIMER_ID) && (m_timerId != 0))
{
ProcessInertiaInteractionContext(m_interactionContext);
}
}
// <summary>
// This method is called when the m_deviceResources class determines that there has been an error in the
// underlying graphics hardware device. All device dependent resources should be released on this event.
// </summary>
void
CInteractionContextSample::OnDeviceLost()
{
ReleaseDeviceResources();
}
// <summary>
// This method is called when the m_deviceResources class is recovering from an error in the
// underlying graphics hardware device. A new device has been created and all device dependent
// resources should be recreated on this event.
// </summary>
void
CInteractionContextSample::OnDeviceRestored()
{
CreateDeviceResources();
}
void
CInteractionContextSample::OnDisplayChange()
{
RECT current;
ZeroMemory(¤t, sizeof(current) );
GetWindowRect(¤t);
float oldDpix, oldDpiy, newDpi;
m_deviceResources->GetD2DDeviceContext()->GetDpi(&oldDpix, &oldDpiy);
newDpi = GetDpiForWindow();
if (oldDpix != newDpi)
{
auto newRect = CalcWindowRectNewDpi(current, oldDpix, newDpi);
SetNewDpi(newDpi);
SetWindowPos(0, &newRect, 0);
m_dpiString.clear();
}
}
void
CInteractionContextSample::OnDpiChange(
_In_ int dpi,
_In_ LPRECT newRect
)
{
float changedDpi = static_cast<float>(dpi);
SetNewDpi(changedDpi);
SetWindowPos(0, newRect, 0);
}
| 26.215278 | 121 | 0.704283 | [
"object",
"transform"
] |
f09aa974e531359839c2c7daeda3bf7963137c04 | 13,531 | cpp | C++ | test/ssw-test.cpp | mgawan/mhm2_staging | 0b59be2c2b4d7745d2f89b9b1b342cfe5ef6bd32 | [
"BSD-3-Clause-LBNL"
] | null | null | null | test/ssw-test.cpp | mgawan/mhm2_staging | 0b59be2c2b4d7745d2f89b9b1b342cfe5ef6bd32 | [
"BSD-3-Clause-LBNL"
] | null | null | null | test/ssw-test.cpp | mgawan/mhm2_staging | 0b59be2c2b4d7745d2f89b9b1b342cfe5ef6bd32 | [
"BSD-3-Clause-LBNL"
] | null | null | null | #include "ssw.hpp"
#include "gtest/gtest.h"
#include "klign.hpp"
#include <sstream>
#include <string>
#include <vector>
#ifdef ENABLE_GPUS
#include "adept-sw/driver.hpp"
#endif
using std::vector;
using std::string;
using std::min;
using std::max;
using namespace StripedSmithWaterman;
#ifdef ENABLE_GPUS
void translate_adept_to_ssw(Alignment &aln, const adept_sw::AlignmentResults &aln_results, int idx) {
aln.sw_score = aln_results.top_scores[idx];
aln.sw_score_next_best = 0;
#ifndef REF_IS_QUERY
aln.ref_begin = aln_results.ref_begin[idx];
aln.ref_end = aln_results.ref_end[idx];
aln.query_begin = aln_results.query_begin[idx];
aln.query_end = aln_results.query_end[idx];
#else
aln.query_begin = aln_results.ref_begin[idx];
aln.query_end = aln_results.ref_end[idx];
aln.ref_begin = aln_results.query_begin[idx];
aln.ref_end = aln_results.query_end[idx];
#endif
aln.ref_end_next_best = 0;
aln.mismatches = 0;
aln.cigar_string.clear();
aln.cigar.clear();
}
#endif
#ifdef ENABLE_GPUS
void test_aligns_gpu(vector<Alignment> &alns, vector<string> query, vector<string> ref, adept_sw::GPUDriver &gpu_driver) {
alns.reserve(query.size());
unsigned max_q_len = 0, max_ref_len = 0;
for(int i = 0; i < query.size(); i++){
if(max_q_len < query[i].size())
max_q_len = query[i].size();
if(max_ref_len < ref[i].size())
max_ref_len = ref[i].size();
}
gpu_driver.run_kernel_forwards(query, ref, max_q_len, max_ref_len);
gpu_driver.kernel_block();
gpu_driver.run_kernel_backwards(query, ref, max_q_len, max_ref_len);
gpu_driver.kernel_block();
auto aln_results = gpu_driver.get_aln_results();
for(int i = 0; i < query.size(); i++){
alns.push_back({});
Alignment &alignment = alns[i];
translate_adept_to_ssw(alignment, aln_results, i);
}
}
#endif
#ifdef ENABLE_GPUS
void check_alns_gpu(vector<Alignment> &alns, vector<int> qstart, vector<int> qend, vector<int> rstart, vector<int> rend) {
int i = 0;
for (Alignment &aln : alns) {
if(i == 15) {// mismatch test
EXPECT_TRUE(aln.ref_end - aln.ref_begin <= 3)<<"adept.ref_begin:"<<aln.ref_begin<<"\tadept.ref_end:"<<aln.ref_end;
EXPECT_TRUE(aln.query_end - aln.query_begin <= 3)<<"\tadept.query_begin:"<<aln.query_begin<<"\tadept.query_end:"<<aln.query_end;
EXPECT_TRUE(aln.sw_score <= 4);
EXPECT_TRUE(aln.sw_score_next_best == 0);
}else{
EXPECT_EQ(aln.ref_begin, rstart[i])<<"adept.ref_begin:"<<aln.ref_begin<<"\t"<<"correct ref_begin:"<<rstart[i];
EXPECT_EQ(aln.ref_end, rend[i])<<"\tadept.ref_end:"<<aln.ref_end<<"\tcorrect ref_end:"<<rend[i];
EXPECT_EQ(aln.query_begin, qstart[i])<<"\tadept.query_begin:"<<aln.query_begin<<"\tcorrect query_begin:"<<qstart[i];
EXPECT_EQ(aln.query_end, qend[i])<<"\tadept.query_end:"<<aln.query_end<<"\tcorrect query end:"<<qend[i];
}
i++;
}
}
#endif
string aln2string(Alignment &aln) {
std::stringstream ss;
ss << "score=" << aln.sw_score << " score2=" << aln.sw_score_next_best;
ss << " rbegin=" << aln.ref_begin << " rend=" << aln.ref_end;
ss << " qbegin=" << aln.query_begin << " qend=" << aln.query_end;
ss << " rend2=" << aln.ref_end_next_best << " mismatches=" << aln.mismatches;
ss << " cigarstr=" << aln.cigar_string;
return ss.str();
}
AlnScoring aln_scoring = {.match = ALN_MATCH_SCORE,
.mismatch = ALN_MISMATCH_COST,
.gap_opening = ALN_GAP_OPENING_COST,
.gap_extending = ALN_GAP_EXTENDING_COST,
.ambiguity = ALN_AMBIGUITY_COST};
AlnScoring cigar_aln_scoring = {.match = 2, .mismatch = 4, .gap_opening = 4, .gap_extending = 2, .ambiguity = 1};
Aligner ssw_aligner;
Aligner ssw_aligner_mhm2(aln_scoring.match, aln_scoring.mismatch, aln_scoring.gap_opening, aln_scoring.gap_extending,
aln_scoring.ambiguity);
Aligner ssw_aligner_cigar(cigar_aln_scoring.match, cigar_aln_scoring.mismatch, cigar_aln_scoring.gap_opening,
cigar_aln_scoring.gap_extending, cigar_aln_scoring.ambiguity);
Filter ssw_filter(true, false, 0, 32767), ssw_filter_cigar(true, true, 0, 32767);
void test_aligns(vector<Alignment> &alns, string query, string ref) {
alns.resize(6);
auto reflen = ref.size();
auto qlen = query.size();
auto masklen = max((int)min(reflen, qlen) / 2, 15);
ssw_aligner.Align(query.c_str(), ref.c_str(), reflen, ssw_filter, &alns[0], masklen);
ssw_aligner.Align(query.c_str(), ref.c_str(), reflen, ssw_filter_cigar, &alns[1], masklen);
ssw_aligner_mhm2.Align(query.c_str(), ref.c_str(), reflen, ssw_filter, &alns[2], masklen);
ssw_aligner_mhm2.Align(query.c_str(), ref.c_str(), reflen, ssw_filter_cigar, &alns[3], masklen);
ssw_aligner_cigar.Align(query.c_str(), ref.c_str(), reflen, ssw_filter, &alns[4], masklen);
ssw_aligner_cigar.Align(query.c_str(), ref.c_str(), reflen, ssw_filter_cigar, &alns[5], masklen);
}
void check_alns(vector<Alignment> &alns, int qstart, int qend, int rstart, int rend, int mismatches, string query = "",
string ref = "", string cigar = "") {
for (Alignment &aln : alns) {
EXPECT_EQ(aln.ref_begin, rstart) << "query=" << query << " ref=" << ref << " aln=" << aln2string(aln);
EXPECT_EQ(aln.ref_end, rend) << "query=" << query << " ref=" << ref << " aln=" << aln2string(aln);
EXPECT_EQ(aln.query_begin, qstart) << "query=" << query << " ref=" << ref << " aln=" << aln2string(aln);
EXPECT_EQ(aln.query_end, qend) << "query=" << query << " ref=" << ref << " aln=" << aln2string(aln);
if (!aln.cigar_string.empty()) { // mismatches should be recorded...
EXPECT_EQ(aln.mismatches, mismatches) << "query=" << query << " ref=" << ref << " aln=" << aln2string(aln);
if (!cigar.empty()) EXPECT_STREQ(aln.cigar_string.c_str(), cigar.c_str()) << "query=" << query << " ref=" << ref << " aln=" << aln2string(aln);
}
}
}
void check_not_alns(vector<Alignment> &alns, string query = "", string ref = "") {
for (Alignment &aln : alns) {
EXPECT_TRUE(aln.ref_end - aln.ref_begin <= 2) << "query=" << query << " ref=" << ref << " aln=" << aln2string(aln);
EXPECT_TRUE(aln.query_end - aln.query_begin <= 2) << "query=" << query << " ref=" << ref << " aln=" << aln2string(aln);
EXPECT_TRUE(aln.sw_score <= 4) << "query=" << query << " ref=" << ref << " aln=" << aln2string(aln);
EXPECT_TRUE(aln.sw_score_next_best == 0) << "query=" << query << " ref=" << ref << " aln=" << aln2string(aln);
}
}
TEST(MHMTest, ssw) {
// arrange
// act
// assert
EXPECT_EQ(ssw_filter.report_cigar, false);
EXPECT_EQ(ssw_filter_cigar.report_cigar, true);
vector<Alignment> alns;
string ref = "ACGT";
string query = ref;
test_aligns(alns, query, ref);
check_alns(alns, 0, 3, 0, 3, 0, query, ref, "4=");
ref = "AACGT";
test_aligns(alns, query, ref);
check_alns(alns, 0, 3, 1, 4, 0, query, ref, "4=");
ref = "ACGTT";
test_aligns(alns, query, ref);
check_alns(alns, 0, 3, 0, 3, 0, query, ref, "4=");
ref = "ACGT";
query = "TACGT";
test_aligns(alns, query, ref);
check_alns(alns, 1, 4, 0, 3, 0, query, ref, "1S4=");
query = "TTACGT";
test_aligns(alns, query, ref);
check_alns(alns, 2, 5, 0, 3, 0, query, ref, "2S4=");
query = "ACGTT";
test_aligns(alns, query, ref);
check_alns(alns, 0, 3, 0, 3, 0, query, ref, "4=1S");
query = "ACGTTT";
test_aligns(alns, query, ref);
check_alns(alns, 0, 3, 0, 3, 0, query, ref, "4=2S");
query = "TACGTT";
test_aligns(alns, query, ref);
check_alns(alns, 1, 4, 0, 3, 0, query, ref, "1S4=1S");
query = "TTACGTT";
test_aligns(alns, query, ref);
check_alns(alns, 2, 5, 0, 3, 0, query, ref, "2S4=1S");
query = "TACGTTT";
test_aligns(alns, query, ref);
check_alns(alns, 1, 4, 0, 3, 0, query, ref, "1S4=2S");
query = "TTACGTTT";
test_aligns(alns, query, ref);
check_alns(alns, 2, 5, 0, 3, 0, query, ref, "2S4=2S");
string r = "AAAATTTTCCCCGGGG";
string q = "AAAATTTTCCCCGGGG";
test_aligns(alns, q, r);
check_alns(alns, 0, 15, 0, 15, 0, q, r, "16=");
// 1 subst
q = "AAAATTTTACCCGGGG";
test_aligns(alns, q, r);
check_alns(alns, 0, 15, 0, 15, 1, q, r, "8=1X7=");
// 1 insert
q = "AAAATTTTACCCCGGGG";
test_aligns(alns, q, r);
check_alns(alns, 0, 16, 0, 15, 1, q, r, "8=1I8=");
// 1 del
q = "AAAATTTCCCCGGGG";
test_aligns(alns, q, r);
check_alns(alns, 0, 14, 0, 15, 1, q, r, "4=1D11=");
// no match
q = "GCTAGCTAGCTAGCTA";
test_aligns(alns, q, r);
check_not_alns(alns, q, r);
// soft clip start
q = "GCTAAAATTTTCCCCGGGG";
test_aligns(alns, q, r);
check_alns(alns, 3, 18, 0, 15, 0, q, r, "3S16=");
// soft clip end
q = "AAAATTTTCCCCGGGGACT";
test_aligns(alns, q, r);
check_alns(alns, 0, 15, 0, 15, 0, q, r, "16=3S");
}
#ifdef ENABLE_GPUS
TEST(MHMTest, AdeptSW) {
// arrange
// act
// assert
double time_to_initialize;
int device_count;
size_t total_mem;
adept_sw::initialize_gpu(time_to_initialize, device_count, total_mem);
if (device_count > 0) {
EXPECT_TRUE(total_mem > 32 * 1024 * 1024); // >32 MB
}
adept_sw::GPUDriver gpu_driver;
auto init_time = gpu_driver.init(0, 1, (short)aln_scoring.match, (short)-aln_scoring.mismatch, (short)-aln_scoring.gap_opening,
(short)-aln_scoring.gap_extending, 300);
std::cout << "Initialized gpu in " << time_to_initialize << "s and " << init_time << "s\n";
vector<Alignment> alns;
vector<string> refs, queries;
vector<int> qstarts, qends, rstarts, rends;
//first test
string ref = "ACGT";
string query = ref;
queries.push_back(query);
refs.push_back(ref);
qstarts.push_back(0);
qends.push_back(3);
rstarts.push_back(0);
rends.push_back(3);
//second test
ref = "AACGT";
query = "ACGT";
queries.push_back(query);
refs.push_back(ref);
qstarts.push_back(0);
qends.push_back(3);
rstarts.push_back(1);
rends.push_back(4);
//third test
ref = "ACGTT";
query = "ACGT";
queries.push_back(query);
refs.push_back(ref);
qstarts.push_back(0);
qends.push_back(3);
rstarts.push_back(0);
rends.push_back(3);
//fourth test
ref = "ACGT";
query = "TACGT";
queries.push_back(query);
refs.push_back(ref);
qstarts.push_back(1);
qends.push_back(4);
rstarts.push_back(0);
rends.push_back(3);
// fifth test
ref = "ACGT";
query = "TTACGT";
queries.push_back(query);
refs.push_back(ref);
qstarts.push_back(2);
qends.push_back(5);
rstarts.push_back(0);
rends.push_back(3);
// sixth test
ref = "ACGT";
query = "ACGTT";
queries.push_back(query);
refs.push_back(ref);
qstarts.push_back(0);
qends.push_back(3);
rstarts.push_back(0);
rends.push_back(3);
//seventh test
ref = "ACGT";
query = "ACGTTT";
queries.push_back(query);
refs.push_back(ref);
qstarts.push_back(0);
qends.push_back(3);
rstarts.push_back(0);
rends.push_back(3);
//eighth test
ref = "ACGT";
query = "TACGTT";
queries.push_back(query);
refs.push_back(ref);
qstarts.push_back(1);
qends.push_back(4);
rstarts.push_back(0);
rends.push_back(3);
//ninth test
ref = "ACGT";
query = "TTACGTT";
queries.push_back(query);
refs.push_back(ref);
qstarts.push_back(2);
qends.push_back(5);
rstarts.push_back(0);
rends.push_back(3);
//tenth test
ref = "ACGT";
query = "TACGTTT";
queries.push_back(query);
refs.push_back(ref);
qstarts.push_back(1);
qends.push_back(4);
rstarts.push_back(0);
rends.push_back(3);
//eleventh test
ref = "ACGT";
query = "TTACGTTT";
queries.push_back(query);
refs.push_back(ref);
qstarts.push_back(2);
qends.push_back(5);
rstarts.push_back(0);
rends.push_back(3);
//twelvth test
ref = "AAAATTTTCCCCGGGG";
query = "AAAATTTTCCCCGGGG";
queries.push_back(query);
refs.push_back(ref);
qstarts.push_back(0);
qends.push_back(15);
rstarts.push_back(0);
rends.push_back(15);
// thirteenth test
ref = "AAAATTTTCCCCGGGG";
query = "AAAATTTTACCCGGGG";
queries.push_back(query);
refs.push_back(ref);
qstarts.push_back(0);
qends.push_back(15);
rstarts.push_back(0);
rends.push_back(15);
// 1 insert // fourteenth test
ref = "AAAATTTTCCCCGGGG";
query = "AAAATTTTACCCCGGGG";
queries.push_back(query);
refs.push_back(ref);
qstarts.push_back(0);
qends.push_back(16);
rstarts.push_back(0);
rends.push_back(15);
// 1 del // fifteenth test
ref = "AAAATTTTCCCCGGGG";
query = "AAAATTTCCCCGGGG";
queries.push_back(query);
refs.push_back(ref);
qstarts.push_back(0);
qends.push_back(14);
rstarts.push_back(0);
rends.push_back(15);
// no match // sixteenth
ref = "AAAATTTTCCCCGGGG";
query = "GCTAGCTAGCTAGCTA";
queries.push_back(query);
refs.push_back(ref);
qstarts.push_back(0);
qends.push_back(14);
rstarts.push_back(0);
rends.push_back(15);
// soft clip start // seventeenth test
ref = "AAAATTTTCCCCGGGG";
query = "GCTAAAATTTTCCCCGGGG";
queries.push_back(query);
refs.push_back(ref);
qstarts.push_back(3);
qends.push_back(18);
rstarts.push_back(0);
rends.push_back(15);
//soft clip end // eighteenth test
ref = "AAAATTTTCCCCGGGG";
query = "AAAATTTTCCCCGGGGACT";
queries.push_back(query);
refs.push_back(ref);
qstarts.push_back(0);
qends.push_back(15);
rstarts.push_back(0);
rends.push_back(15);
//run kernel
test_aligns_gpu(alns, queries, refs, gpu_driver);
// verify results
check_alns_gpu(alns, qstarts, qends, rstarts, rends);
// cuda tear down happens in driver destructor
}
#endif
| 31.249423 | 149 | 0.654867 | [
"vector"
] |
f09c5adbb3c87dc4fcb54102f8491322ac1a57c6 | 3,177 | cxx | C++ | base/fs/utils/xcopy/support.cxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | base/fs/utils/xcopy/support.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | base/fs/utils/xcopy/support.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /*++
Copyright (c) 1990 Microsoft Corporation
Module Name:
Support
Abstract:
Miscelaneous support functions for the XCopy directory copy
utility. All functions that are not involved directly in the
copy process go here.
Author:
Ramon Juan San Andres (ramonsa) 02-May-1991
Revision History:
--*/
#include "ulib.hxx"
#include "system.hxx"
#include "xcopy.hxx"
VOID
XCOPY::DisplayMessageAndExit (
IN MSGID MsgId,
IN PWSTRING String,
IN ULONG ExitCode
)
/*++
Routine Description:
Displays a message and exits the program with the supplied error code.
We support a maximum of one string parameter for the message.
Arguments:
MsgId - Supplies the Id of the message to display.
String - Supplies a string parameter for the message.
ExitCode - Supplies the exit code with which to exit.
Return Value:
None.
Notes:
--*/
{
//
// XCopy first displays the error message (if any) and then
// displays the number of files copied.
//
if ( MsgId != 0 ) {
if ( String ) {
DisplayMessage( MsgId, ERROR_MESSAGE, "%W", String );
} else {
DisplayMessage( MsgId, ERROR_MESSAGE );
}
}
if ( _DontCopySwitch ) {
DisplayMessage( XCOPY_MESSAGE_FILES, NORMAL_MESSAGE, "%d", _FilesCopied );
} else if ( !_StructureOnlySwitch ) {
DisplayMessage( XCOPY_MESSAGE_FILES_COPIED, NORMAL_MESSAGE, "%d", _FilesCopied );
}
ExitProgram( ExitCode );
}
PWSTRING
XCOPY::QueryMessageString (
IN MSGID MsgId
)
/*++
Routine Description:
Obtains a string object initialized to the contents of some message
Arguments:
MsgId - Supplies ID of the message
Return Value:
PWSTRING - Pointer to initialized string object
Notes:
--*/
{
PWSTRING String;
if ( ((String = NEW DSTRING) == NULL ) ||
!(SYSTEM::QueryResourceString( String, MsgId, "" )) ) {
DisplayMessageAndExit( XCOPY_ERROR_NO_MEMORY, NULL, EXIT_MISC_ERROR );
}
return String;
}
VOID
XCOPY::ExitWithError(
IN DWORD ErrorCode
)
/*++
Routine Description:
Displays a message based on a WIN32 error code, and exits.
Arguments:
ErrorCode - Supplies Windows error code
Return Value:
none
--*/
{
MSGID ReadWriteMsgId = 0;
switch ( ErrorCode ) {
case ERROR_DISK_FULL:
ReadWriteMsgId = XCOPY_ERROR_DISK_FULL;
break;
case ERROR_WRITE_PROTECT:
ReadWriteMsgId = XCOPY_ERROR_WRITE_PROTECT;
break;
case ERROR_ACCESS_DENIED:
ReadWriteMsgId = XCOPY_ERROR_ACCESS_DENIED;
break;
case ERROR_SHARING_VIOLATION:
ReadWriteMsgId = XCOPY_ERROR_SHARING_VIOLATION;
break;
case ERROR_TOO_MANY_OPEN_FILES:
ReadWriteMsgId = XCOPY_ERROR_TOO_MANY_OPEN_FILES;
break;
case ERROR_LOCK_VIOLATION:
ReadWriteMsgId = XCOPY_ERROR_LOCK_VIOLATION;
break;
case ERROR_CANNOT_MAKE:
ReadWriteMsgId = XCOPY_ERROR_CANNOT_MAKE;
break;
default:
break;
}
if ( ReadWriteMsgId != 0 ) {
DisplayMessageAndExit( ReadWriteMsgId, NULL, EXIT_READWRITE_ERROR );
}
Fatal( EXIT_MISC_ERROR, XCOPY_ERROR_EXTENDED, "%d", ErrorCode );
}
| 17.266304 | 90 | 0.677054 | [
"object"
] |
f09df13afde9477f6c4e12d6987cf44306e44cc6 | 12,607 | cpp | C++ | Engine/Source/Runtime/UtilityShaders/Private/ClearQuad.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | 1 | 2022-01-29T18:36:12.000Z | 2022-01-29T18:36:12.000Z | Engine/Source/Runtime/UtilityShaders/Private/ClearQuad.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | Engine/Source/Runtime/UtilityShaders/Private/ClearQuad.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "ClearQuad.h"
#include "Shader.h"
#include "RHIStaticStates.h"
#include "OneColorShader.h"
#include "PipelineStateCache.h"
#include "ClearReplacementShaders.h"
#include "RendererInterface.h"
#include "Logging/LogMacros.h"
DEFINE_LOG_CATEGORY_STATIC(LogClearQuad, Log, Log)
static void ClearQuadSetup( FRHICommandList& RHICmdList, bool bClearColor, int32 NumClearColors, const FLinearColor* ClearColorArray, bool bClearDepth, float Depth, bool bClearStencil, uint32 Stencil )
{
if (UNLIKELY(!FApp::CanEverRender()))
{
return;
}
// Set new states
FBlendStateRHIParamRef BlendStateRHI;
BlendStateRHI = bClearColor
? TStaticBlendState<>::GetRHI()
: TStaticBlendStateWriteMask<CW_NONE,CW_NONE,CW_NONE,CW_NONE,CW_NONE,CW_NONE,CW_NONE,CW_NONE>::GetRHI();
const FDepthStencilStateRHIParamRef DepthStencilStateRHI =
(bClearDepth && bClearStencil)
? TStaticDepthStencilState<
true, CF_Always,
true,CF_Always,SO_Replace,SO_Replace,SO_Replace,
false,CF_Always,SO_Replace,SO_Replace,SO_Replace,
0xff,0xff
>::GetRHI()
: bClearDepth
? TStaticDepthStencilState<true, CF_Always>::GetRHI()
: bClearStencil
? TStaticDepthStencilState<
false, CF_Always,
true,CF_Always,SO_Replace,SO_Replace,SO_Replace,
false,CF_Always,SO_Replace,SO_Replace,SO_Replace,
0xff,0xff
>::GetRHI()
: TStaticDepthStencilState<false, CF_Always>::GetRHI();
FGraphicsPipelineStateInitializer GraphicsPSOInit;
RHICmdList.ApplyCachedRenderTargets(GraphicsPSOInit);
GraphicsPSOInit.RasterizerState = TStaticRasterizerState<FM_Solid, CM_None>::GetRHI();
GraphicsPSOInit.BlendState = BlendStateRHI;
GraphicsPSOInit.DepthStencilState = DepthStencilStateRHI;
auto ShaderMap = GetGlobalShaderMap(GMaxRHIFeatureLevel);
// Set the new shaders
TShaderMapRef<TOneColorVS<true> > VertexShader(ShaderMap);
FOneColorPS* PixelShader = NULL;
// Set the shader to write to the appropriate number of render targets
// On AMD PC hardware, outputting to a color index in the shader without a matching render target set has a significant performance hit
if (NumClearColors <= 1)
{
TShaderMapRef<TOneColorPixelShaderMRT<1> > MRTPixelShader(ShaderMap);
PixelShader = *MRTPixelShader;
}
else if (NumClearColors == 2)
{
TShaderMapRef<TOneColorPixelShaderMRT<2> > MRTPixelShader(ShaderMap);
PixelShader = *MRTPixelShader;
}
else if (NumClearColors == 3)
{
TShaderMapRef<TOneColorPixelShaderMRT<3> > MRTPixelShader(ShaderMap);
PixelShader = *MRTPixelShader;
}
else if (NumClearColors == 4)
{
TShaderMapRef<TOneColorPixelShaderMRT<4> > MRTPixelShader(ShaderMap);
PixelShader = *MRTPixelShader;
}
else if (NumClearColors == 5)
{
TShaderMapRef<TOneColorPixelShaderMRT<5> > MRTPixelShader(ShaderMap);
PixelShader = *MRTPixelShader;
}
else if (NumClearColors == 6)
{
TShaderMapRef<TOneColorPixelShaderMRT<6> > MRTPixelShader(ShaderMap);
PixelShader = *MRTPixelShader;
}
else if (NumClearColors == 7)
{
TShaderMapRef<TOneColorPixelShaderMRT<7> > MRTPixelShader(ShaderMap);
PixelShader = *MRTPixelShader;
}
else if (NumClearColors == 8)
{
TShaderMapRef<TOneColorPixelShaderMRT<8> > MRTPixelShader(ShaderMap);
PixelShader = *MRTPixelShader;
}
GraphicsPSOInit.BoundShaderState.VertexDeclarationRHI = GetVertexDeclarationFVector4();
GraphicsPSOInit.BoundShaderState.VertexShaderRHI = GETSAFERHISHADER_VERTEX(*VertexShader);
GraphicsPSOInit.BoundShaderState.PixelShaderRHI = GETSAFERHISHADER_PIXEL(PixelShader);
GraphicsPSOInit.PrimitiveType = PT_TriangleStrip;
SetGraphicsPipelineState(RHICmdList, GraphicsPSOInit);
RHICmdList.SetStencilRef(Stencil);
PixelShader->SetColors(RHICmdList, ClearColorArray, NumClearColors);
}
const uint32 GMaxSizeUAVDMA = 0;
static void ClearUAVShader(FRHICommandList& RHICmdList, FUnorderedAccessViewRHIParamRef UnorderedAccessViewRHI, uint32 SizeInBytes, uint32 ClearValue)
{
UE_CLOG((SizeInBytes & 0x3) != 0, LogClearQuad, Warning,
TEXT("Buffer size is not a multiple of DWORDs. Up to 3 bytes after buffer end will also be cleared"));
TShaderMapRef<FClearBufferReplacementCS> ComputeShader(GetGlobalShaderMap(GMaxRHIFeatureLevel));
FComputeShaderRHIParamRef ShaderRHI = ComputeShader->GetComputeShader();
uint32 NumDWordsToClear = (SizeInBytes + 3) / 4;
uint32 NumThreadGroupsX = (NumDWordsToClear + 63) / 64;
RHICmdList.SetComputeShader(ShaderRHI);
ComputeShader->SetParameters(RHICmdList, UnorderedAccessViewRHI, NumDWordsToClear, ClearValue);
RHICmdList.DispatchComputeShader(NumThreadGroupsX, 1, 1);
ComputeShader->FinalizeParameters(RHICmdList, UnorderedAccessViewRHI);
}
void ClearUAV(FRHICommandList& RHICmdList, const FRWBufferStructured& StructuredBuffer, uint32 Value)
{
if (StructuredBuffer.NumBytes <= GMaxSizeUAVDMA)
{
uint32 Values[4] = { Value, Value, Value, Value };
RHICmdList.ClearTinyUAV(StructuredBuffer.UAV, Values);
}
else
{
ClearUAVShader(RHICmdList, StructuredBuffer.UAV, StructuredBuffer.NumBytes, Value);
}
}
void ClearUAV(FRHICommandList& RHICmdList, const FRWBuffer& Buffer, uint32 Value)
{
if (Buffer.NumBytes <= GMaxSizeUAVDMA)
{
uint32 Values[4] = { Value, Value, Value, Value };
RHICmdList.ClearTinyUAV(Buffer.UAV, Values);
}
else
{
ClearUAVShader(RHICmdList, Buffer.UAV, Buffer.NumBytes, Value);
}
}
void ClearUAV(FRHICommandList& RHICmdList, FRHIUnorderedAccessView* Buffer, uint32 NumBytes, uint32 Value)
{
if (NumBytes <= GMaxSizeUAVDMA)
{
uint32 Values[4] = { Value, Value, Value, Value };
RHICmdList.ClearTinyUAV(Buffer, Values);
}
else
{
ClearUAVShader(RHICmdList, Buffer, NumBytes, Value);
}
}
template< typename T >
inline void ClearUAV_T(FRHICommandList& RHICmdList, const FSceneRenderTargetItem& RenderTargetItem, const T(&ClearValues)[4])
{
if (auto Texture2d = RenderTargetItem.TargetableTexture->GetTexture2D())
{
TShaderMapRef< FClearTexture2DReplacementCS<T> > ComputeShader(GetGlobalShaderMap(GMaxRHIFeatureLevel));
FComputeShaderRHIParamRef ShaderRHI = ComputeShader->GetComputeShader();
RHICmdList.SetComputeShader(ShaderRHI);
ComputeShader->SetParameters(RHICmdList, RenderTargetItem.UAV, ClearValues);
uint32 x = (Texture2d->GetSizeX() + 7) / 8;
uint32 y = (Texture2d->GetSizeY() + 7) / 8;
RHICmdList.DispatchComputeShader(x, y, 1);
ComputeShader->FinalizeParameters(RHICmdList, RenderTargetItem.UAV);
}
else if (auto Texture2dArray = RenderTargetItem.TargetableTexture->GetTexture2DArray())
{
TShaderMapRef< FClearTexture2DArrayReplacementCS<T> > ComputeShader(GetGlobalShaderMap(GMaxRHIFeatureLevel));
FComputeShaderRHIParamRef ShaderRHI = ComputeShader->GetComputeShader();
RHICmdList.SetComputeShader(ShaderRHI);
ComputeShader->SetParameters(RHICmdList, RenderTargetItem.UAV, ClearValues);
uint32 x = (Texture2dArray->GetSizeX() + 7) / 8;
uint32 y = (Texture2dArray->GetSizeY() + 7) / 8;
uint32 z = Texture2dArray->GetSizeZ();
RHICmdList.DispatchComputeShader(x, y, z);
ComputeShader->FinalizeParameters(RHICmdList, RenderTargetItem.UAV);
}
else if (auto TextureCube = RenderTargetItem.TargetableTexture->GetTextureCube())
{
TShaderMapRef< FClearTexture2DArrayReplacementCS<T> > ComputeShader(GetGlobalShaderMap(GMaxRHIFeatureLevel));
FComputeShaderRHIParamRef ShaderRHI = ComputeShader->GetComputeShader();
RHICmdList.SetComputeShader(ShaderRHI);
ComputeShader->SetParameters(RHICmdList, RenderTargetItem.UAV, ClearValues);
uint32 x = (TextureCube->GetSize() + 7) / 8;
uint32 y = (TextureCube->GetSize() + 7) / 8;
RHICmdList.DispatchComputeShader(x, y, 6);
ComputeShader->FinalizeParameters(RHICmdList, RenderTargetItem.UAV);
}
else if (auto Texture3d = RenderTargetItem.TargetableTexture->GetTexture3D())
{
TShaderMapRef< FClearVolumeReplacementCS<T> > ComputeShader(GetGlobalShaderMap(GMaxRHIFeatureLevel));
FComputeShaderRHIParamRef ShaderRHI = ComputeShader->GetComputeShader();
RHICmdList.SetComputeShader(ShaderRHI);
ComputeShader->SetParameters(RHICmdList, RenderTargetItem.UAV, ClearValues);
uint32 x = (Texture3d->GetSizeX() + 3) / 4;
uint32 y = (Texture3d->GetSizeY() + 3) / 4;
uint32 z = (Texture3d->GetSizeZ() + 3) / 4;
RHICmdList.DispatchComputeShader(x, y, z);
ComputeShader->FinalizeParameters(RHICmdList, RenderTargetItem.UAV);
}
else
{
check(0);
}
}
void ClearTexture2DUAV(FRHICommandList& RHICmdList, FUnorderedAccessViewRHIParamRef UAV, int32 Width, int32 Height, const FLinearColor& ClearColor)
{
TShaderMapRef< FClearTexture2DReplacementCS<float> > ComputeShader(GetGlobalShaderMap(GMaxRHIFeatureLevel));
FComputeShaderRHIParamRef ShaderRHI = ComputeShader->GetComputeShader();
RHICmdList.SetComputeShader(ShaderRHI);
ComputeShader->SetParameters(RHICmdList, UAV, reinterpret_cast<const float(&)[4]>(ClearColor));
uint32 x = (Width + 7) / 8;
uint32 y = (Height + 7) / 8;
RHICmdList.DispatchComputeShader(x, y, 1);
ComputeShader->FinalizeParameters(RHICmdList, UAV);
}
void ClearUAV(FRHICommandList& RHICmdList, const FSceneRenderTargetItem& RenderTargetItem, const float(&ClearValues)[4])
{
ClearUAV_T(RHICmdList, RenderTargetItem, ClearValues);
}
void ClearUAV(FRHICommandList& RHICmdList, const FSceneRenderTargetItem& RenderTargetItem, const uint32(&ClearValues)[4])
{
ClearUAV_T(RHICmdList, RenderTargetItem, ClearValues);
}
void ClearUAV(FRHICommandList& RHICmdList, const FSceneRenderTargetItem& RenderTargetItem, const FLinearColor& ClearColor)
{
ClearUAV_T(RHICmdList, RenderTargetItem, reinterpret_cast<const float(&)[4]>(ClearColor));
}
void DrawClearQuadMRT(FRHICommandList& RHICmdList, bool bClearColor, int32 NumClearColors, const FLinearColor* ClearColorArray, bool bClearDepth, float Depth, bool bClearStencil, uint32 Stencil)
{
ClearQuadSetup(RHICmdList, bClearColor, NumClearColors, ClearColorArray, bClearDepth, Depth, bClearStencil, Stencil);
// without a hole
FVector4 Vertices[4];
Vertices[0].Set(-1.0f, 1.0f, Depth, 1.0f);
Vertices[1].Set(1.0f, 1.0f, Depth, 1.0f);
Vertices[2].Set(-1.0f, -1.0f, Depth, 1.0f);
Vertices[3].Set(1.0f, -1.0f, Depth, 1.0f);
DrawPrimitiveUP(RHICmdList, PT_TriangleStrip, 2, Vertices, sizeof(Vertices[0]));
}
void DrawClearQuadMRT(FRHICommandList& RHICmdList, bool bClearColor, int32 NumClearColors, const FLinearColor* ClearColorArray, bool bClearDepth, float Depth, bool bClearStencil, uint32 Stencil, FIntPoint ViewSize, FIntRect ExcludeRect)
{
if (ExcludeRect.Min == FIntPoint::ZeroValue && ExcludeRect.Max == ViewSize)
{
// Early out if the entire surface is excluded
return;
}
ClearQuadSetup(RHICmdList, bClearColor, NumClearColors, ClearColorArray, bClearDepth, Depth, bClearStencil, Stencil);
// Draw a fullscreen quad
if (ExcludeRect.Width() > 0 && ExcludeRect.Height() > 0)
{
// with a hole in it
FVector4 OuterVertices[4];
OuterVertices[0].Set(-1.0f, 1.0f, Depth, 1.0f);
OuterVertices[1].Set(1.0f, 1.0f, Depth, 1.0f);
OuterVertices[2].Set(1.0f, -1.0f, Depth, 1.0f);
OuterVertices[3].Set(-1.0f, -1.0f, Depth, 1.0f);
float InvViewWidth = 1.0f / ViewSize.X;
float InvViewHeight = 1.0f / ViewSize.Y;
FVector4 FractionRect = FVector4(ExcludeRect.Min.X * InvViewWidth, ExcludeRect.Min.Y * InvViewHeight, (ExcludeRect.Max.X - 1) * InvViewWidth, (ExcludeRect.Max.Y - 1) * InvViewHeight);
FVector4 InnerVertices[4];
InnerVertices[0].Set(FMath::Lerp(-1.0f, 1.0f, FractionRect.X), FMath::Lerp(1.0f, -1.0f, FractionRect.Y), Depth, 1.0f);
InnerVertices[1].Set(FMath::Lerp(-1.0f, 1.0f, FractionRect.Z), FMath::Lerp(1.0f, -1.0f, FractionRect.Y), Depth, 1.0f);
InnerVertices[2].Set(FMath::Lerp(-1.0f, 1.0f, FractionRect.Z), FMath::Lerp(1.0f, -1.0f, FractionRect.W), Depth, 1.0f);
InnerVertices[3].Set(FMath::Lerp(-1.0f, 1.0f, FractionRect.X), FMath::Lerp(1.0f, -1.0f, FractionRect.W), Depth, 1.0f);
FVector4 Vertices[10];
Vertices[0] = OuterVertices[0];
Vertices[1] = InnerVertices[0];
Vertices[2] = OuterVertices[1];
Vertices[3] = InnerVertices[1];
Vertices[4] = OuterVertices[2];
Vertices[5] = InnerVertices[2];
Vertices[6] = OuterVertices[3];
Vertices[7] = InnerVertices[3];
Vertices[8] = OuterVertices[0];
Vertices[9] = InnerVertices[0];
DrawPrimitiveUP(RHICmdList, PT_TriangleStrip, 8, Vertices, sizeof(Vertices[0]));
}
else
{
// without a hole
FVector4 Vertices[4];
Vertices[0].Set(-1.0f, 1.0f, Depth, 1.0f);
Vertices[1].Set(1.0f, 1.0f, Depth, 1.0f);
Vertices[2].Set(-1.0f, -1.0f, Depth, 1.0f);
Vertices[3].Set(1.0f, -1.0f, Depth, 1.0f);
DrawPrimitiveUP(RHICmdList, PT_TriangleStrip, 2, Vertices, sizeof(Vertices[0]));
}
}
| 38.910494 | 236 | 0.76402 | [
"render"
] |
f0afc2f6519a3cb57d83943680d5b3cfbe2c5181 | 1,066 | hpp | C++ | flexcore/core/connection_util.hpp | vacing/flexcore | 08c08e98556f92d1993e2738cbcb975b3764fa2d | [
"Apache-2.0"
] | 47 | 2016-09-23T10:27:17.000Z | 2021-12-14T07:31:40.000Z | flexcore/core/connection_util.hpp | vacing/flexcore | 08c08e98556f92d1993e2738cbcb975b3764fa2d | [
"Apache-2.0"
] | 10 | 2016-12-04T16:40:29.000Z | 2020-04-28T08:46:50.000Z | flexcore/core/connection_util.hpp | vacing/flexcore | 08c08e98556f92d1993e2738cbcb975b3764fa2d | [
"Apache-2.0"
] | 20 | 2016-09-23T17:14:41.000Z | 2021-10-09T18:24:47.000Z | #ifndef SRC_PORTS_CONNECTION_UTIL_HPP_
#define SRC_PORTS_CONNECTION_UTIL_HPP_
#include <flexcore/core/traits.hpp>
#include <utility>
namespace fc
{
/**
* \brief generalization of get_source
* Stopping criterion for recursion
*/
template <class T>
constexpr auto get_source(T& s)
-> std::enable_if_t<!has_source<T>(0), decltype(s)>
{
return s;
}
/**
* \brief recursively extracts the source of a connection
*/
template <class T>
constexpr auto get_source(T& c)
-> std::enable_if_t<has_source<T>(0),
decltype(get_source(c.source))>
{
return get_source(c.source);
}
/**
* \brief generalization of get_sink
* Stopping criterion for recursion
*/
template <class T>
constexpr auto get_sink(T& s)
-> std::enable_if_t<!has_sink<T>(0), decltype(s)>
{
return s;
}
/**
* \brief recursively extracts the sink of an object with member "sink"
*/
template <class T>
constexpr auto get_sink(T& c)
-> std::enable_if_t<has_sink<T>(0),
decltype(get_sink(c.sink))>
{
return get_sink(c.sink);
}
}// namespace fc
#endif /* SRC_PORTS_CONNECTION_UTIL_HPP_ */
| 19.035714 | 71 | 0.714822 | [
"object"
] |
f0c976c54be14597f3269b6bd39f1109f7abc298 | 318 | cpp | C++ | Sunny-Core/07_SERVER/BossLocker.cpp | adunStudio/Sunny | 9f71c1816aa62bbc0d02d2f8d6414f4bf9aee7e7 | [
"Apache-2.0"
] | 20 | 2018-01-19T06:28:36.000Z | 2021-08-06T14:06:13.000Z | Sunny-Core/07_SERVER/BossLocker.cpp | adunStudio/Sunny | 9f71c1816aa62bbc0d02d2f8d6414f4bf9aee7e7 | [
"Apache-2.0"
] | null | null | null | Sunny-Core/07_SERVER/BossLocker.cpp | adunStudio/Sunny | 9f71c1816aa62bbc0d02d2f8d6414f4bf9aee7e7 | [
"Apache-2.0"
] | 3 | 2019-01-29T08:58:04.000Z | 2021-01-02T06:33:20.000Z | #include "BossLocker.h"
unordered_map<int, Player*> BossLocker::players;
Player* BossLocker::player = nullptr;
int BossLocker::id = 0;
vector<Entity*> BossLocker::player_bullets;
PoolList* BossLocker::bulletList = nullptr;
unordered_map<int, SCBullet*> BossLocker::sc_bulletList;
int BossLocker::shooterIndex = 0;
| 24.461538 | 56 | 0.773585 | [
"vector"
] |
f0d096153fe44a1fe8f364d1ff5f62beb0f8ede7 | 7,544 | cc | C++ | tests/unit/model_tests.cc | stbd/stoolbox | 4535e1df2795cb0157420e7d4b1a01f3bda441da | [
"MIT"
] | null | null | null | tests/unit/model_tests.cc | stbd/stoolbox | 4535e1df2795cb0157420e7d4b1a01f3bda441da | [
"MIT"
] | null | null | null | tests/unit/model_tests.cc | stbd/stoolbox | 4535e1df2795cb0157420e7d4b1a01f3bda441da | [
"MIT"
] | null | null | null | #define BOOST_TEST_MODULE unit_test_model
#include <boost/test/unit_test.hpp>
#include "stb_model.hh"
#include "stb_types.hh"
#include "stb_util.hh"
using namespace stb;
BOOST_AUTO_TEST_CASE(test_single_buffer_single_attribute)
{
const float attrData[] = {
//Vertice x 3, rest are not used
-0.5, 0.5, -1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.5, 0.5, -1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.5, -.5, -1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
-0.5, -.5, -1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0
};
const U32 indicesData[] = {
0, 1, 2, 0, 2, 3
};
const ModelData::AttributeData attr1(
(const char *)attrData,
sizeof(attrData),
{ 3 },
sizeof(float) * 9,
ModelData::FLOAT
);
const ModelData model(
{
stb::ModelData::AttributeElement(&attr1, stb::emptyDeleter<stb::ModelData::AttributeData>)
},
(const char *)indicesData,
sizeof(indicesData),
sizeof(indicesData[0]),
ModelData::TRIANGLE
);
//Attribute metadata
BOOST_CHECK_EQUAL(model.numberOfAttributes(), (size_t)1);
BOOST_CHECK_EQUAL(model.numberOfAttrBuffers(), (size_t)1);
BOOST_CHECK_EQUAL(model.numberOfAttrInBuffer(0), (size_t)1);
BOOST_CHECK_EQUAL(model.attrBufferDataType(0), ModelData::FLOAT);
BOOST_CHECK_EQUAL(model.attrBufferSize(0), sizeof(attrData));
BOOST_CHECK_EQUAL(model.attrBufferSizeOfElement(0), 9 * sizeof(float));
BOOST_CHECK_EQUAL(model.valuesPerAttribute(0, 0), (size_t)3);
BOOST_CHECK_EQUAL(model.pointerToDataInBuffer(0, 0), (size_t)0);
//Attribute data
const float * attrDataP = (const float *)model.attrBuffer(0);
BOOST_CHECK_EQUAL(attrDataP[0], -0.5f);
BOOST_CHECK_EQUAL(attrDataP[1], 0.5f);
BOOST_CHECK_EQUAL(attrDataP[2], -1.0f);
BOOST_CHECK_EQUAL(attrDataP[3], 0.0f); //First index not used for anything
//Indices metadata and data
BOOST_CHECK_EQUAL(model.indicesDataSize(), 6 * sizeof(U32));
BOOST_CHECK_EQUAL(model.sizeOfIndiceElement(), (size_t)4);
BOOST_CHECK_EQUAL(model.indicesDataSize(), sizeof(indicesData));
BOOST_CHECK_EQUAL(model.attributeDataMode(), ModelData::TRIANGLE);
const U32 * indicesDataP = (const U32 *)model.indicesData();
BOOST_CHECK_EQUAL(indicesDataP[0], (size_t)0);
BOOST_CHECK_EQUAL(indicesDataP[1], (size_t)1);
BOOST_CHECK_EQUAL(indicesDataP[2], (size_t)2);
BOOST_CHECK_EQUAL(indicesDataP[3], (size_t)0);
}
BOOST_AUTO_TEST_CASE(test_multiple_buffers_multiple_attribute)
{
const float attrData1[] = {
//3 x vertice, 6 x unused
-0.5, 0.5, -1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.5, 0.5, -1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.5, -.5, -1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
-0.5, -.5, -1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0
};
const U32 attrData2[] = {
//3 x vertice, 2 x something else
0, 1, 1, 2, 3,
1, 2, 2, 3, 4,
2, 3, 4, 4, 5,
3, 4, 5, 5, 6,
};
const U32 indicesData[] = {
0, 1, 2, 0, 2, 3
};
const ModelData::AttributeData attr1(
(const char *)attrData1,
sizeof(attrData1),
{ 3 },
sizeof(float)* 9,
ModelData::FLOAT
);
const ModelData::AttributeData attr2(
(const char *)attrData2,
sizeof(attrData2),
{3, 2},
sizeof(U32)* 5,
ModelData::UINT32
);
const ModelData model(
{
stb::ModelData::AttributeElement(&attr1, stb::emptyDeleter<stb::ModelData::AttributeData>),
stb::ModelData::AttributeElement(&attr2, stb::emptyDeleter<stb::ModelData::AttributeData>)
},
(const char *)indicesData,
sizeof(indicesData),
sizeof(indicesData[0]),
ModelData::TRIANGLE
);
//Attribute metadata
BOOST_CHECK_EQUAL(model.numberOfAttributes(), (size_t)3);
BOOST_CHECK_EQUAL(model.numberOfAttrBuffers(), (size_t)2);
BOOST_CHECK_EQUAL(model.numberOfAttrInBuffer(0), (size_t)1);
BOOST_CHECK_EQUAL(model.numberOfAttrInBuffer(1), (size_t)2);
BOOST_CHECK_EQUAL(model.attrBufferDataType(0), ModelData::FLOAT);
BOOST_CHECK_EQUAL(model.attrBufferDataType(1), ModelData::UINT32);
BOOST_CHECK_EQUAL(model.attrBufferSize(0), sizeof(attrData1));
BOOST_CHECK_EQUAL(model.attrBufferSize(1), sizeof(attrData2));
BOOST_CHECK_EQUAL(model.attrBufferSizeOfElement(0), 9 * sizeof(float));
BOOST_CHECK_EQUAL(model.attrBufferSizeOfElement(1), 5 * sizeof(U32));
BOOST_CHECK_EQUAL(model.valuesPerAttribute(0, 0), (size_t)3);
BOOST_CHECK_EQUAL(model.valuesPerAttribute(1, 0), (size_t)3);
BOOST_CHECK_EQUAL(model.valuesPerAttribute(1, 1), (size_t)2);
BOOST_CHECK_EQUAL(model.pointerToDataInBuffer(0, 0), (size_t)0);
BOOST_CHECK_EQUAL(model.pointerToDataInBuffer(1, 0), (size_t)0);
BOOST_CHECK_EQUAL(model.pointerToDataInBuffer(1, 1), sizeof(U32) * 3);
//Attribute data
const float * attrDataP1 = (const float *)model.attrBuffer(0);
BOOST_CHECK_EQUAL(attrDataP1[0], attrData1[0]);
BOOST_CHECK_EQUAL(attrDataP1[1], attrData1[1]);
BOOST_CHECK_EQUAL(attrDataP1[2], attrData1[2]);
BOOST_CHECK_EQUAL(attrDataP1[3], attrData1[3]); //First index not used for anything
const U32 * attrDataP2 = (const U32 *)model.attrBuffer(1);
BOOST_CHECK_EQUAL(attrDataP2[0], attrData2[0]);
BOOST_CHECK_EQUAL(attrDataP2[1], attrData2[1]);
BOOST_CHECK_EQUAL(attrDataP2[2], attrData2[2]);
BOOST_CHECK_EQUAL(attrDataP2[3], attrData2[3]); //First index not used for anything
//Indices metadata and data
BOOST_CHECK_EQUAL(model.indicesDataSize(), 6 * sizeof(U32));
BOOST_CHECK_EQUAL(model.sizeOfIndiceElement(), (size_t)4);
BOOST_CHECK_EQUAL(model.indicesDataSize(), sizeof(indicesData));
BOOST_CHECK_EQUAL(model.attributeDataMode(), ModelData::TRIANGLE);
const U32 * indicesDataP = (const U32 *)model.indicesData();
BOOST_CHECK_EQUAL(indicesDataP[0], (size_t)0);
BOOST_CHECK_EQUAL(indicesDataP[1], (size_t)1);
BOOST_CHECK_EQUAL(indicesDataP[2], (size_t)2);
BOOST_CHECK_EQUAL(indicesDataP[3], (size_t)0);
}
BOOST_AUTO_TEST_CASE(test_allocating_invalid_model_and_copyconstructor_for_it)
{
const ModelData model;
BOOST_CHECK_EQUAL(model.valid(), false);
const ModelData model2(model);
BOOST_CHECK_EQUAL(model2.valid(), false);
}
/*
* This will cause a compile time error, uncomment to test
*/
/*
BOOST_AUTO_TEST_CASE(test_allocating_from_heap)
{
const float attrData[] = {
//3 x vertice, 6 x unused
-0.5, 0.5, -1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.5, 0.5, -1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.5, -.5, -1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
-0.5, -.5, -1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0
};
const U32 indicesData[] = {
0, 1, 2, 0, 2, 3
};
const ModelData::AttributeData attr1(
(const char *)attrData,
sizeof(attrData),
{ 3 },
sizeof(float) * 9,
ModelData::FLOAT
);
const ModelData * model = new ModelData(
{
stb::ModelData::AttributeElement(&attr1, stb::emptyDeleter<stb::ModelData::AttributeData>)
},
(const char *)indicesData,
sizeof(indicesData),
sizeof(indicesData[0]),
ModelData::TRIANGLE
);
}
*/ | 36.269231 | 104 | 0.623542 | [
"model"
] |
f0d20ffbf778f51339e23b08ca9dc8a430762bdf | 3,196 | hpp | C++ | include/psn_defs.hpp | Wason-Fok/PosiStageNet | 5f22fdbedd0f9233b36d719ec99d921684f911c4 | [
"MIT"
] | 3 | 2019-04-18T05:26:42.000Z | 2021-12-18T11:30:41.000Z | include/psn_defs.hpp | Wason-Fok/PosiStageNet | 5f22fdbedd0f9233b36d719ec99d921684f911c4 | [
"MIT"
] | null | null | null | include/psn_defs.hpp | Wason-Fok/PosiStageNet | 5f22fdbedd0f9233b36d719ec99d921684f911c4 | [
"MIT"
] | null | null | null | //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
/*
The MIT License (MIT)
Copyright (c) 2014 VYV Corporation
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
#ifndef PSN_DEFS_HPP
#define PSN_DEFS_HPP
#include <stdint.h>
#include <map>
#include <vector>
#include <string>
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
namespace psn
{
// PSN VERSION
#define PSN_HIGH_VERSION 2
#define PSN_LOW_VERSION 0
// DEFAULT UDP PORT and MULTICAST ADDRESS
#define PSN_DEFAULT_UDP_PORT 56565
#define PSN_DEFAULT_UDP_MULTICAST_ADDR "236.10.10.10"
// MAX UDP PACKET SIZE
#define PSN_MAX_UDP_PACKET_SIZE 1500
// - PSN INFO -
#define PSN_INFO_PACKET 0x6756
#define PSN_INFO_PACKET_HEADER 0x0000
#define PSN_INFO_SYSTEM_NAME 0x0001
#define PSN_INFO_TRACKER_LIST 0x0002
//#define PSN_INFO_TRACKER tracker_id
#define PSN_INFO_TRACKER_NAME 0x0000
// - PSN DATA -
#define PSN_DATA_PACKET 0x6755
#define PSN_DATA_PACKET_HEADER 0x0000
#define PSN_DATA_TRACKER_LIST 0x0001
//#define PSN_DATA_TRACKER tracker_id
#define PSN_DATA_TRACKER_POS 0x0000
#define PSN_DATA_TRACKER_SPEED 0x0001
#define PSN_DATA_TRACKER_ORI 0x0002
#define PSN_DATA_TRACKER_STATUS 0x0003
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
struct float3
{
float3( float px = 0 , float py = 0 , float pz = 0 )
: x( px ) , y( py ) , z( pz )
{}
float x , y , z ;
} ;
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
struct psn_tracker
{
psn_tracker( uint16_t id = 0 ,
const ::std::string & name = "" ,
float3 pos = float3() ,
float3 speed = float3() ,
float3 ori = float3() ,
float validity = 0.f )
: id_( id )
, name_( name )
, pos_( pos )
, speed_( speed )
, ori_( ori )
, validity_( validity )
{}
uint16_t id_ ;
::std::string name_ ;
float3 pos_ ;
float3 speed_ ;
float3 ori_ ;
float validity_ ;
} ;
typedef ::std::map< uint16_t , psn_tracker > psn_tracker_array ; // map< id , psn_tracker >
} // namespace psn
#endif
| 28.792793 | 91 | 0.635795 | [
"vector"
] |
f0d32e5f4d54eb5f9865b30eb7cc9fd9cb5e084a | 33,410 | cpp | C++ | src/modules/osg/generated_code/BufferData.pypp.cpp | JaneliaSciComp/osgpyplusplus | a5ae3f69c7e9101a32d8cc95fe680dab292f75ac | [
"BSD-3-Clause"
] | 17 | 2015-06-01T12:19:46.000Z | 2022-02-12T02:37:48.000Z | src/modules/osg/generated_code/BufferData.pypp.cpp | JaneliaSciComp/osgpyplusplus | a5ae3f69c7e9101a32d8cc95fe680dab292f75ac | [
"BSD-3-Clause"
] | 7 | 2015-07-04T14:36:49.000Z | 2015-07-23T18:09:49.000Z | src/modules/osg/generated_code/BufferData.pypp.cpp | JaneliaSciComp/osgpyplusplus | a5ae3f69c7e9101a32d8cc95fe680dab292f75ac | [
"BSD-3-Clause"
] | 7 | 2015-11-28T17:00:31.000Z | 2020-01-08T07:00:59.000Z | // This file has been generated by Py++.
#include "boost/python.hpp"
#include "wrap_osg.h"
#include "wrap_referenced.h"
#include "bufferdata.pypp.hpp"
namespace bp = boost::python;
struct BufferData_wrapper : osg::BufferData, bp::wrapper< osg::BufferData > {
struct ModifiedCallback_wrapper : osg::BufferData::ModifiedCallback, bp::wrapper< osg::BufferData::ModifiedCallback > {
virtual char const * className( ) const {
if( bp::override func_className = this->get_override( "className" ) )
return func_className( );
else{
return this->osg::BufferData::ModifiedCallback::className( );
}
}
char const * default_className( ) const {
return osg::BufferData::ModifiedCallback::className( );
}
virtual ::osg::Object * clone( ::osg::CopyOp const & copyop ) const {
if( bp::override func_clone = this->get_override( "clone" ) )
return func_clone( boost::ref(copyop) );
else{
return this->osg::BufferData::ModifiedCallback::clone( boost::ref(copyop) );
}
}
::osg::Object * default_clone( ::osg::CopyOp const & copyop ) const {
return osg::BufferData::ModifiedCallback::clone( boost::ref(copyop) );
}
virtual ::osg::Object * cloneType( ) const {
if( bp::override func_cloneType = this->get_override( "cloneType" ) )
return func_cloneType( );
else{
return this->osg::BufferData::ModifiedCallback::cloneType( );
}
}
::osg::Object * default_cloneType( ) const {
return osg::BufferData::ModifiedCallback::cloneType( );
}
virtual bool isSameKindAs( ::osg::Object const * obj ) const {
if( bp::override func_isSameKindAs = this->get_override( "isSameKindAs" ) )
return func_isSameKindAs( boost::python::ptr(obj) );
else{
return this->osg::BufferData::ModifiedCallback::isSameKindAs( boost::python::ptr(obj) );
}
}
bool default_isSameKindAs( ::osg::Object const * obj ) const {
return osg::BufferData::ModifiedCallback::isSameKindAs( boost::python::ptr(obj) );
}
virtual char const * libraryName( ) const {
if( bp::override func_libraryName = this->get_override( "libraryName" ) )
return func_libraryName( );
else{
return this->osg::BufferData::ModifiedCallback::libraryName( );
}
}
char const * default_libraryName( ) const {
return osg::BufferData::ModifiedCallback::libraryName( );
}
virtual void modified( ::osg::BufferData * arg0 ) const {
if( bp::override func_modified = this->get_override( "modified" ) )
func_modified( boost::python::ptr(arg0) );
else{
this->osg::BufferData::ModifiedCallback::modified( boost::python::ptr(arg0) );
}
}
void default_modified( ::osg::BufferData * arg0 ) const {
osg::BufferData::ModifiedCallback::modified( boost::python::ptr(arg0) );
}
virtual void computeDataVariance( ) {
if( bp::override func_computeDataVariance = this->get_override( "computeDataVariance" ) )
func_computeDataVariance( );
else{
this->osg::Object::computeDataVariance( );
}
}
void default_computeDataVariance( ) {
osg::Object::computeDataVariance( );
}
virtual ::osg::Referenced * getUserData( ) {
if( bp::override func_getUserData = this->get_override( "getUserData" ) )
return func_getUserData( );
else{
return this->osg::Object::getUserData( );
}
}
::osg::Referenced * default_getUserData( ) {
return osg::Object::getUserData( );
}
virtual ::osg::Referenced const * getUserData( ) const {
if( bp::override func_getUserData = this->get_override( "getUserData" ) )
return func_getUserData( );
else{
return this->osg::Object::getUserData( );
}
}
::osg::Referenced const * default_getUserData( ) const {
return osg::Object::getUserData( );
}
virtual void resizeGLObjectBuffers( unsigned int arg0 ) {
if( bp::override func_resizeGLObjectBuffers = this->get_override( "resizeGLObjectBuffers" ) )
func_resizeGLObjectBuffers( arg0 );
else{
this->osg::Object::resizeGLObjectBuffers( arg0 );
}
}
void default_resizeGLObjectBuffers( unsigned int arg0 ) {
osg::Object::resizeGLObjectBuffers( arg0 );
}
virtual void setName( ::std::string const & name ) {
if( bp::override func_setName = this->get_override( "setName" ) )
func_setName( name );
else{
this->osg::Object::setName( name );
}
}
void default_setName( ::std::string const & name ) {
osg::Object::setName( name );
}
virtual void setThreadSafeRefUnref( bool threadSafe ) {
if( bp::override func_setThreadSafeRefUnref = this->get_override( "setThreadSafeRefUnref" ) )
func_setThreadSafeRefUnref( threadSafe );
else{
this->osg::Object::setThreadSafeRefUnref( threadSafe );
}
}
void default_setThreadSafeRefUnref( bool threadSafe ) {
osg::Object::setThreadSafeRefUnref( threadSafe );
}
virtual void setUserData( ::osg::Referenced * obj ) {
if( bp::override func_setUserData = this->get_override( "setUserData" ) )
func_setUserData( boost::python::ptr(obj) );
else{
this->osg::Object::setUserData( boost::python::ptr(obj) );
}
}
void default_setUserData( ::osg::Referenced * obj ) {
osg::Object::setUserData( boost::python::ptr(obj) );
}
};
virtual ::osg::Array * asArray( ) {
if( bp::override func_asArray = this->get_override( "asArray" ) )
return func_asArray( );
else{
return this->osg::BufferData::asArray( );
}
}
::osg::Array * default_asArray( ) {
return osg::BufferData::asArray( );
}
virtual ::osg::Array const * asArray( ) const {
if( bp::override func_asArray = this->get_override( "asArray" ) )
return func_asArray( );
else{
return this->osg::BufferData::asArray( );
}
}
::osg::Array const * default_asArray( ) const {
return osg::BufferData::asArray( );
}
virtual char const * className( ) const {
if( bp::override func_className = this->get_override( "className" ) )
return func_className( );
else{
return this->osg::BufferData::className( );
}
}
char const * default_className( ) const {
return osg::BufferData::className( );
}
virtual ::GLvoid const * getDataPointer( ) const {
bp::override func_getDataPointer = this->get_override( "getDataPointer" );
return func_getDataPointer( );
}
virtual unsigned int getTotalDataSize( ) const {
bp::override func_getTotalDataSize = this->get_override( "getTotalDataSize" );
return func_getTotalDataSize( );
}
virtual bool isSameKindAs( ::osg::Object const * obj ) const {
if( bp::override func_isSameKindAs = this->get_override( "isSameKindAs" ) )
return func_isSameKindAs( boost::python::ptr(obj) );
else{
return this->osg::BufferData::isSameKindAs( boost::python::ptr(obj) );
}
}
bool default_isSameKindAs( ::osg::Object const * obj ) const {
return osg::BufferData::isSameKindAs( boost::python::ptr(obj) );
}
virtual char const * libraryName( ) const {
if( bp::override func_libraryName = this->get_override( "libraryName" ) )
return func_libraryName( );
else{
return this->osg::BufferData::libraryName( );
}
}
char const * default_libraryName( ) const {
return osg::BufferData::libraryName( );
}
virtual void resizeGLObjectBuffers( unsigned int maxSize ) {
if( bp::override func_resizeGLObjectBuffers = this->get_override( "resizeGLObjectBuffers" ) )
func_resizeGLObjectBuffers( maxSize );
else{
this->osg::BufferData::resizeGLObjectBuffers( maxSize );
}
}
void default_resizeGLObjectBuffers( unsigned int maxSize ) {
osg::BufferData::resizeGLObjectBuffers( maxSize );
}
virtual ::osg::Object * clone( ::osg::CopyOp const & arg0 ) const {
bp::override func_clone = this->get_override( "clone" );
return func_clone( boost::ref(arg0) );
}
virtual ::osg::Object * cloneType( ) const {
bp::override func_cloneType = this->get_override( "cloneType" );
return func_cloneType( );
}
virtual void computeDataVariance( ) {
if( bp::override func_computeDataVariance = this->get_override( "computeDataVariance" ) )
func_computeDataVariance( );
else{
this->osg::Object::computeDataVariance( );
}
}
void default_computeDataVariance( ) {
osg::Object::computeDataVariance( );
}
virtual ::osg::Referenced * getUserData( ) {
if( bp::override func_getUserData = this->get_override( "getUserData" ) )
return func_getUserData( );
else{
return this->osg::Object::getUserData( );
}
}
::osg::Referenced * default_getUserData( ) {
return osg::Object::getUserData( );
}
virtual ::osg::Referenced const * getUserData( ) const {
if( bp::override func_getUserData = this->get_override( "getUserData" ) )
return func_getUserData( );
else{
return this->osg::Object::getUserData( );
}
}
::osg::Referenced const * default_getUserData( ) const {
return osg::Object::getUserData( );
}
virtual void setName( ::std::string const & name ) {
if( bp::override func_setName = this->get_override( "setName" ) )
func_setName( name );
else{
this->osg::Object::setName( name );
}
}
void default_setName( ::std::string const & name ) {
osg::Object::setName( name );
}
virtual void setThreadSafeRefUnref( bool threadSafe ) {
if( bp::override func_setThreadSafeRefUnref = this->get_override( "setThreadSafeRefUnref" ) )
func_setThreadSafeRefUnref( threadSafe );
else{
this->osg::Object::setThreadSafeRefUnref( threadSafe );
}
}
void default_setThreadSafeRefUnref( bool threadSafe ) {
osg::Object::setThreadSafeRefUnref( threadSafe );
}
virtual void setUserData( ::osg::Referenced * obj ) {
if( bp::override func_setUserData = this->get_override( "setUserData" ) )
func_setUserData( boost::python::ptr(obj) );
else{
this->osg::Object::setUserData( boost::python::ptr(obj) );
}
}
void default_setUserData( ::osg::Referenced * obj ) {
osg::Object::setUserData( boost::python::ptr(obj) );
}
};
void register_BufferData_class(){
{ //::osg::BufferData
typedef bp::class_< BufferData_wrapper, bp::bases< osg::Object >, osg::ref_ptr< ::osg::BufferData >, boost::noncopyable > BufferData_exposer_t;
BufferData_exposer_t BufferData_exposer = BufferData_exposer_t( "BufferData", bp::no_init );
bp::scope BufferData_scope( BufferData_exposer );
bp::class_< BufferData_wrapper::ModifiedCallback_wrapper, bp::bases< osg::Object >, osg::ref_ptr< BufferData_wrapper::ModifiedCallback_wrapper >, boost::noncopyable >( "ModifiedCallback" )
.def(
"className"
, (char const * ( ::osg::BufferData::ModifiedCallback::* )( )const)(&::osg::BufferData::ModifiedCallback::className)
, (char const * ( BufferData_wrapper::ModifiedCallback_wrapper::* )( )const)(&BufferData_wrapper::ModifiedCallback_wrapper::default_className) )
.def(
"clone"
, (::osg::Object * ( ::osg::BufferData::ModifiedCallback::* )( ::osg::CopyOp const & )const)(&::osg::BufferData::ModifiedCallback::clone)
, (::osg::Object * ( BufferData_wrapper::ModifiedCallback_wrapper::* )( ::osg::CopyOp const & )const)(&BufferData_wrapper::ModifiedCallback_wrapper::default_clone)
, ( bp::arg("copyop") )
, bp::return_value_policy< bp::reference_existing_object >() )
.def(
"cloneType"
, (::osg::Object * ( ::osg::BufferData::ModifiedCallback::* )( )const)(&::osg::BufferData::ModifiedCallback::cloneType)
, (::osg::Object * ( BufferData_wrapper::ModifiedCallback_wrapper::* )( )const)(&BufferData_wrapper::ModifiedCallback_wrapper::default_cloneType)
, bp::return_value_policy< bp::reference_existing_object >() )
.def(
"isSameKindAs"
, (bool ( ::osg::BufferData::ModifiedCallback::* )( ::osg::Object const * )const)(&::osg::BufferData::ModifiedCallback::isSameKindAs)
, (bool ( BufferData_wrapper::ModifiedCallback_wrapper::* )( ::osg::Object const * )const)(&BufferData_wrapper::ModifiedCallback_wrapper::default_isSameKindAs)
, ( bp::arg("obj") ) )
.def(
"libraryName"
, (char const * ( ::osg::BufferData::ModifiedCallback::* )( )const)(&::osg::BufferData::ModifiedCallback::libraryName)
, (char const * ( BufferData_wrapper::ModifiedCallback_wrapper::* )( )const)(&BufferData_wrapper::ModifiedCallback_wrapper::default_libraryName) )
.def(
"modified"
, (void ( ::osg::BufferData::ModifiedCallback::* )( ::osg::BufferData * )const)(&::osg::BufferData::ModifiedCallback::modified)
, (void ( BufferData_wrapper::ModifiedCallback_wrapper::* )( ::osg::BufferData * )const)(&BufferData_wrapper::ModifiedCallback_wrapper::default_modified)
, ( bp::arg("arg0") ) )
.def(
"computeDataVariance"
, (void ( ::osg::Object::* )( ))(&::osg::Object::computeDataVariance)
, (void ( BufferData_wrapper::ModifiedCallback_wrapper::* )( ))(&BufferData_wrapper::ModifiedCallback_wrapper::default_computeDataVariance) )
.def(
"getUserData"
, (::osg::Referenced * ( ::osg::Object::* )( ))(&::osg::Object::getUserData)
, (::osg::Referenced * ( BufferData_wrapper::ModifiedCallback_wrapper::* )( ))(&BufferData_wrapper::ModifiedCallback_wrapper::default_getUserData)
, bp::return_internal_reference< >() )
.def(
"getUserData"
, (::osg::Referenced const * ( ::osg::Object::* )( )const)(&::osg::Object::getUserData)
, (::osg::Referenced const * ( BufferData_wrapper::ModifiedCallback_wrapper::* )( )const)(&BufferData_wrapper::ModifiedCallback_wrapper::default_getUserData)
, bp::return_internal_reference< >() )
.def(
"resizeGLObjectBuffers"
, (void ( ::osg::Object::* )( unsigned int ))(&::osg::Object::resizeGLObjectBuffers)
, (void ( BufferData_wrapper::ModifiedCallback_wrapper::* )( unsigned int ))(&BufferData_wrapper::ModifiedCallback_wrapper::default_resizeGLObjectBuffers)
, ( bp::arg("arg0") ) )
.def(
"setName"
, (void ( ::osg::Object::* )( ::std::string const & ))(&::osg::Object::setName)
, (void ( BufferData_wrapper::ModifiedCallback_wrapper::* )( ::std::string const & ))(&BufferData_wrapper::ModifiedCallback_wrapper::default_setName)
, ( bp::arg("name") ) )
.def(
"setName"
, (void ( ::osg::Object::* )( char const * ))( &::osg::Object::setName )
, ( bp::arg("name") )
, " Set the name of object using a C style string." )
.def(
"setThreadSafeRefUnref"
, (void ( ::osg::Object::* )( bool ))(&::osg::Object::setThreadSafeRefUnref)
, (void ( BufferData_wrapper::ModifiedCallback_wrapper::* )( bool ))(&BufferData_wrapper::ModifiedCallback_wrapper::default_setThreadSafeRefUnref)
, ( bp::arg("threadSafe") ) )
.def(
"setUserData"
, (void ( ::osg::Object::* )( ::osg::Referenced * ))(&::osg::Object::setUserData)
, (void ( BufferData_wrapper::ModifiedCallback_wrapper::* )( ::osg::Referenced * ))(&BufferData_wrapper::ModifiedCallback_wrapper::default_setUserData)
, ( bp::arg("obj") ) );
{ //::osg::BufferData::addClient
typedef void ( ::osg::BufferData::*addClient_function_type)( ::osg::Object * ) ;
BufferData_exposer.def(
"addClient"
, addClient_function_type( &::osg::BufferData::addClient )
, ( bp::arg("arg0") ) );
}
{ //::osg::BufferData::asArray
typedef ::osg::Array * ( ::osg::BufferData::*asArray_function_type)( ) ;
typedef ::osg::Array * ( BufferData_wrapper::*default_asArray_function_type)( ) ;
BufferData_exposer.def(
"asArray"
, asArray_function_type(&::osg::BufferData::asArray)
, default_asArray_function_type(&BufferData_wrapper::default_asArray)
, bp::return_internal_reference< >() );
}
{ //::osg::BufferData::asArray
typedef ::osg::Array const * ( ::osg::BufferData::*asArray_function_type)( ) const;
typedef ::osg::Array const * ( BufferData_wrapper::*default_asArray_function_type)( ) const;
BufferData_exposer.def(
"asArray"
, asArray_function_type(&::osg::BufferData::asArray)
, default_asArray_function_type(&BufferData_wrapper::default_asArray)
, bp::return_internal_reference< >() );
}
{ //::osg::BufferData::className
typedef char const * ( ::osg::BufferData::*className_function_type)( ) const;
typedef char const * ( BufferData_wrapper::*default_className_function_type)( ) const;
BufferData_exposer.def(
"className"
, className_function_type(&::osg::BufferData::className)
, default_className_function_type(&BufferData_wrapper::default_className) );
}
{ //::osg::BufferData::dirty
typedef void ( ::osg::BufferData::*dirty_function_type)( ) ;
BufferData_exposer.def(
"dirty"
, dirty_function_type( &::osg::BufferData::dirty )
, " Dirty the primitive, which increments the modified count, to force buffer objects to update.\n If a ModifiedCallback is attached to this BufferData then the callback is called prior to the bufferObjects dirty is called." );
}
{ //::osg::BufferData::getBufferIndex
typedef unsigned int ( ::osg::BufferData::*getBufferIndex_function_type)( ) const;
BufferData_exposer.def(
"getBufferIndex"
, getBufferIndex_function_type( &::osg::BufferData::getBufferIndex ) );
}
{ //::osg::BufferData::getBufferObject
typedef ::osg::BufferObject * ( ::osg::BufferData::*getBufferObject_function_type)( ) ;
BufferData_exposer.def(
"getBufferObject"
, getBufferObject_function_type( &::osg::BufferData::getBufferObject )
, bp::return_internal_reference< >() );
}
{ //::osg::BufferData::getBufferObject
typedef ::osg::BufferObject const * ( ::osg::BufferData::*getBufferObject_function_type)( ) const;
BufferData_exposer.def(
"getBufferObject"
, getBufferObject_function_type( &::osg::BufferData::getBufferObject )
, bp::return_internal_reference< >() );
}
{ //::osg::BufferData::getDataPointer
typedef ::GLvoid const * ( ::osg::BufferData::*getDataPointer_function_type)( ) const;
BufferData_exposer.def(
"getDataPointer"
, bp::pure_virtual( getDataPointer_function_type(&::osg::BufferData::getDataPointer) )
, bp::return_value_policy< bp::return_opaque_pointer >() );
}
{ //::osg::BufferData::getGLBufferObject
typedef ::osg::GLBufferObject * ( ::osg::BufferData::*getGLBufferObject_function_type)( unsigned int ) const;
BufferData_exposer.def(
"getGLBufferObject"
, getGLBufferObject_function_type( &::osg::BufferData::getGLBufferObject )
, ( bp::arg("contextID") )
, bp::return_internal_reference< >() );
}
{ //::osg::BufferData::getModifiedCallback
typedef ::osg::BufferData::ModifiedCallback * ( ::osg::BufferData::*getModifiedCallback_function_type)( ) ;
BufferData_exposer.def(
"getModifiedCallback"
, getModifiedCallback_function_type( &::osg::BufferData::getModifiedCallback )
, bp::return_internal_reference< >() );
}
{ //::osg::BufferData::getModifiedCallback
typedef ::osg::BufferData::ModifiedCallback const * ( ::osg::BufferData::*getModifiedCallback_function_type)( ) const;
BufferData_exposer.def(
"getModifiedCallback"
, getModifiedCallback_function_type( &::osg::BufferData::getModifiedCallback )
, bp::return_internal_reference< >() );
}
{ //::osg::BufferData::getModifiedCount
typedef unsigned int ( ::osg::BufferData::*getModifiedCount_function_type)( ) const;
BufferData_exposer.def(
"getModifiedCount"
, getModifiedCount_function_type( &::osg::BufferData::getModifiedCount )
, " Get modified count value." );
}
{ //::osg::BufferData::getNumClients
typedef unsigned int ( ::osg::BufferData::*getNumClients_function_type)( ) const;
BufferData_exposer.def(
"getNumClients"
, getNumClients_function_type( &::osg::BufferData::getNumClients ) );
}
{ //::osg::BufferData::getOrCreateGLBufferObject
typedef ::osg::GLBufferObject * ( ::osg::BufferData::*getOrCreateGLBufferObject_function_type)( unsigned int ) const;
BufferData_exposer.def(
"getOrCreateGLBufferObject"
, getOrCreateGLBufferObject_function_type( &::osg::BufferData::getOrCreateGLBufferObject )
, ( bp::arg("contextID") )
, bp::return_internal_reference< >() );
}
{ //::osg::BufferData::getTotalDataSize
typedef unsigned int ( ::osg::BufferData::*getTotalDataSize_function_type)( ) const;
BufferData_exposer.def(
"getTotalDataSize"
, bp::pure_virtual( getTotalDataSize_function_type(&::osg::BufferData::getTotalDataSize) ) );
}
{ //::osg::BufferData::isSameKindAs
typedef bool ( ::osg::BufferData::*isSameKindAs_function_type)( ::osg::Object const * ) const;
typedef bool ( BufferData_wrapper::*default_isSameKindAs_function_type)( ::osg::Object const * ) const;
BufferData_exposer.def(
"isSameKindAs"
, isSameKindAs_function_type(&::osg::BufferData::isSameKindAs)
, default_isSameKindAs_function_type(&BufferData_wrapper::default_isSameKindAs)
, ( bp::arg("obj") ) );
}
{ //::osg::BufferData::libraryName
typedef char const * ( ::osg::BufferData::*libraryName_function_type)( ) const;
typedef char const * ( BufferData_wrapper::*default_libraryName_function_type)( ) const;
BufferData_exposer.def(
"libraryName"
, libraryName_function_type(&::osg::BufferData::libraryName)
, default_libraryName_function_type(&BufferData_wrapper::default_libraryName) );
}
{ //::osg::BufferData::removeClient
typedef void ( ::osg::BufferData::*removeClient_function_type)( ::osg::Object * ) ;
BufferData_exposer.def(
"removeClient"
, removeClient_function_type( &::osg::BufferData::removeClient )
, ( bp::arg("arg0") ) );
}
{ //::osg::BufferData::resizeGLObjectBuffers
typedef void ( ::osg::BufferData::*resizeGLObjectBuffers_function_type)( unsigned int ) ;
typedef void ( BufferData_wrapper::*default_resizeGLObjectBuffers_function_type)( unsigned int ) ;
BufferData_exposer.def(
"resizeGLObjectBuffers"
, resizeGLObjectBuffers_function_type(&::osg::BufferData::resizeGLObjectBuffers)
, default_resizeGLObjectBuffers_function_type(&BufferData_wrapper::default_resizeGLObjectBuffers)
, ( bp::arg("maxSize") ) );
}
{ //::osg::BufferData::setBufferIndex
typedef void ( ::osg::BufferData::*setBufferIndex_function_type)( unsigned int ) ;
BufferData_exposer.def(
"setBufferIndex"
, setBufferIndex_function_type( &::osg::BufferData::setBufferIndex )
, ( bp::arg("index") ) );
}
{ //::osg::BufferData::setBufferObject
typedef void ( ::osg::BufferData::*setBufferObject_function_type)( ::osg::BufferObject * ) ;
BufferData_exposer.def(
"setBufferObject"
, setBufferObject_function_type( &::osg::BufferData::setBufferObject )
, ( bp::arg("bufferObject") ) );
}
{ //::osg::BufferData::setModifiedCallback
typedef void ( ::osg::BufferData::*setModifiedCallback_function_type)( ::osg::BufferData::ModifiedCallback * ) ;
BufferData_exposer.def(
"setModifiedCallback"
, setModifiedCallback_function_type( &::osg::BufferData::setModifiedCallback )
, ( bp::arg("md") ) );
}
{ //::osg::BufferData::setModifiedCount
typedef void ( ::osg::BufferData::*setModifiedCount_function_type)( unsigned int ) ;
BufferData_exposer.def(
"setModifiedCount"
, setModifiedCount_function_type( &::osg::BufferData::setModifiedCount )
, ( bp::arg("value") )
, " Set the modified count value." );
}
{ //::osg::Object::clone
typedef ::osg::Object * ( ::osg::Object::*clone_function_type)( ::osg::CopyOp const & ) const;
BufferData_exposer.def(
"clone"
, bp::pure_virtual( clone_function_type(&::osg::Object::clone) )
, ( bp::arg("arg0") )
, bp::return_value_policy< bp::reference_existing_object >()
, "\n Clone an object, with Object* return type.\n Must be defined by derived classes.\n" );
}
{ //::osg::Object::cloneType
typedef ::osg::Object * ( ::osg::Object::*cloneType_function_type)( ) const;
BufferData_exposer.def(
"cloneType"
, bp::pure_virtual( cloneType_function_type(&::osg::Object::cloneType) )
, bp::return_value_policy< bp::reference_existing_object >()
, "\n Clone the type of an object, with Object* return type.\n Must be defined by derived classes.\n" );
}
{ //::osg::Object::computeDataVariance
typedef void ( ::osg::Object::*computeDataVariance_function_type)( ) ;
typedef void ( BufferData_wrapper::*default_computeDataVariance_function_type)( ) ;
BufferData_exposer.def(
"computeDataVariance"
, computeDataVariance_function_type(&::osg::Object::computeDataVariance)
, default_computeDataVariance_function_type(&BufferData_wrapper::default_computeDataVariance) );
}
{ //::osg::Object::getUserData
typedef ::osg::Referenced * ( ::osg::Object::*getUserData_function_type)( ) ;
typedef ::osg::Referenced * ( BufferData_wrapper::*default_getUserData_function_type)( ) ;
BufferData_exposer.def(
"getUserData"
, getUserData_function_type(&::osg::Object::getUserData)
, default_getUserData_function_type(&BufferData_wrapper::default_getUserData)
, bp::return_internal_reference< >() );
}
{ //::osg::Object::getUserData
typedef ::osg::Referenced const * ( ::osg::Object::*getUserData_function_type)( ) const;
typedef ::osg::Referenced const * ( BufferData_wrapper::*default_getUserData_function_type)( ) const;
BufferData_exposer.def(
"getUserData"
, getUserData_function_type(&::osg::Object::getUserData)
, default_getUserData_function_type(&BufferData_wrapper::default_getUserData)
, bp::return_internal_reference< >() );
}
{ //::osg::Object::setName
typedef void ( ::osg::Object::*setName_function_type)( ::std::string const & ) ;
typedef void ( BufferData_wrapper::*default_setName_function_type)( ::std::string const & ) ;
BufferData_exposer.def(
"setName"
, setName_function_type(&::osg::Object::setName)
, default_setName_function_type(&BufferData_wrapper::default_setName)
, ( bp::arg("name") ) );
}
{ //::osg::Object::setName
typedef void ( ::osg::Object::*setName_function_type)( char const * ) ;
BufferData_exposer.def(
"setName"
, setName_function_type( &::osg::Object::setName )
, ( bp::arg("name") )
, " Set the name of object using a C style string." );
}
{ //::osg::Object::setThreadSafeRefUnref
typedef void ( ::osg::Object::*setThreadSafeRefUnref_function_type)( bool ) ;
typedef void ( BufferData_wrapper::*default_setThreadSafeRefUnref_function_type)( bool ) ;
BufferData_exposer.def(
"setThreadSafeRefUnref"
, setThreadSafeRefUnref_function_type(&::osg::Object::setThreadSafeRefUnref)
, default_setThreadSafeRefUnref_function_type(&BufferData_wrapper::default_setThreadSafeRefUnref)
, ( bp::arg("threadSafe") ) );
}
{ //::osg::Object::setUserData
typedef void ( ::osg::Object::*setUserData_function_type)( ::osg::Referenced * ) ;
typedef void ( BufferData_wrapper::*default_setUserData_function_type)( ::osg::Referenced * ) ;
BufferData_exposer.def(
"setUserData"
, setUserData_function_type(&::osg::Object::setUserData)
, default_setUserData_function_type(&BufferData_wrapper::default_setUserData)
, ( bp::arg("obj") ) );
}
}
}
| 43.333333 | 243 | 0.557827 | [
"object"
] |
f0d96016a067b6b86eb8fce2d899854231310515 | 4,182 | cxx | C++ | Parts/actors/common/src/ausampla.cxx | magic-lantern-studio/mle-parts | 551cdb0757fcd6623cd5c7572dca681165b43a29 | [
"MIT"
] | 1 | 2021-02-04T22:44:16.000Z | 2021-02-04T22:44:16.000Z | Parts/actors/common/src/ausampla.cxx | magic-lantern-studio/mle-parts | 551cdb0757fcd6623cd5c7572dca681165b43a29 | [
"MIT"
] | null | null | null | Parts/actors/common/src/ausampla.cxx | magic-lantern-studio/mle-parts | 551cdb0757fcd6623cd5c7572dca681165b43a29 | [
"MIT"
] | null | null | null | /** @defgroup MleParts Magic Lantern Parts */
/**
* @file ausampla.cxx
* @ingroup MleParts
*
* This file implements the class for a Magic Lantern Sound Actor.
*
* @author Mark S. Millard
* @date May 1, 2003
*/
// COPYRIGHT_BEGIN
//
// Copyright (C) 2000-2007 Wizzer Works
//
// Wizzer Works makes available all content in this file ("Content").
// Unless otherwise indicated below, the Content is provided to you
// under the terms and conditions of the Common Public License Version 1.0
// ("CPL"). A copy of the CPL is available at
//
// http://opensource.org/licenses/cpl1.0.php
//
// For purposes of the CPL, "Program" will mean the Content.
//
// For information concerning this Makefile, contact Mark S. Millard,
// of Wizzer Works at msm@wizzerworks.com.
//
// More information concerning Wizzer Works may be found at
//
// http://www.wizzerworks.com
//
// COPYRIGHT_END
#include "mle/MleScheduler.h"
#include "mle/MleDirector.h"
#include "mle/ausampla.h"
MleSampleActor *MleSampleActor::sampleActor = NULL;
MLE_ACTOR_SOURCE(MleSampleActor,MleActor);
#ifdef MLE_REHEARSAL
void MleSampleActor::initClass ( void )
{
mlRegisterActorClass ( MleSampleActor, MleActor );
mlRegisterActorMember ( MleSampleActor, music, MediaRef );
mlRegisterActorMember ( MleSampleActor, volume, float );
mlRegisterActorMember ( MleSampleActor, bufferSize, int );
mlRegisterActorMember ( MleSampleActor, stoppingTime, float );
}
void MleSampleActor::resolveEdit ( const char * property )
{
if (!property) return;
if ( strcmp ( property, "music" ) == 0 )
{
delete sound;
sound = NULL;
} else if ( strcmp ( property, "volume" ) == 0 )
{
if ( sound )
sound->setVolume ( volume );
} else if ( strcmp ( property, "bufferSize" ) == 0 )
{
if ( sound )
sound->setMaxBuffSize ( bufferSize );
} else if ( strcmp ( property, "stoppingTime" ) == 0 )
{
if ( sound )
sound->setStoppingTime ( stoppingTime );
}
}
#endif /* MLE_REHEARSAL */
// Audio actor default constructor for music.
MleSampleActor::MleSampleActor ( void ) : MleActor ()
{
if ( MleSampleActor::sampleActor == NULL )
MleSampleActor::sampleActor = this;
sound = NULL;
music = MLE_NO_MEDIA;
volume = 1.0f;
bufferSize = 0;
stoppingTime = 0.0f;
firstTime = TRUE;
}
MleSampleActor::~MleSampleActor ( void )
{
if ( sound )
delete sound;
g_theTitle->m_theScheduler->remove ( this );
if ( MleSampleActor::sampleActor == this )
MleSampleActor::sampleActor = NULL;
}
void MleSampleActor::init ( void )
{
if ( music != MLE_NO_MEDIA )
{
g_theTitle->m_theScheduler->insertFunc ( PHASE_ACTOR, update, this, this);
}
}
void MleSampleActor::setMediaRef ( MediaRef mediaRef )
{
music = mediaRef;
init ();
}
void MleSampleActor::update ( void * client )
{
MleSampleActor * actor = (MleSampleActor *) client;
if ( actor->firstTime )
{
actor->firstTime = FALSE;
} else if ( ! actor->sound )
{
// The following operations must be done in this order!
// Create a new MleSampleSound object.
actor->sound = new MleSampleSound;
// The MaxBuffSize and the StoppingTime are used by the open
// function to allocate resources at the same time as the audio
// file is opened and, optionally, read into memory.
if ( actor->bufferSize )
actor->sound->setMaxBuffSize ( actor->bufferSize );
if ( actor->stoppingTime )
actor->sound->setStoppingTime ( actor->stoppingTime );
// Open the audio file, allocate buffers, load the data, etc.
actor->sound->open ( actor->music );
// These functions affect data structures created by the open.
actor->sound->setRepeat (); // play music forever
actor->sound->setVolume ( actor->volume );
actor->sound->play ();
}
}
void MleSampleActor::setVolume ( float v )
{
sound->setVolume ( v );
}
void MleSampleActor::play ()
{
if ( sound )
sound->play ();
}
void MleSampleActor::pause ()
{
if ( sound )
sound->pause ();
}
void MleSampleActor::resume ()
{
if ( sound )
sound->resume ();
}
void MleSampleActor::stop ()
{
if ( sound )
sound->stop ();
}
| 22.126984 | 76 | 0.663797 | [
"object"
] |
f0ddf723628c45bc051440809c68683afa43b78f | 57,599 | hpp | C++ | include/libtorrent/miniz.hpp | gqw/libtorrent | 2407f8348cbc3af883c38ce53c18c68d99306182 | [
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | include/libtorrent/miniz.hpp | gqw/libtorrent | 2407f8348cbc3af883c38ce53c18c68d99306182 | [
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | include/libtorrent/miniz.hpp | gqw/libtorrent | 2407f8348cbc3af883c38ce53c18c68d99306182 | [
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | /*
miniz.c v1.15 - public domain deflate/inflate, zlib-subset, ZIP
reading/writing/appending, PNG writing See "unlicense" statement at the end
of this file. Rich Geldreich <richgel99@gmail.com>, last updated Oct. 13,
2013 Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951:
http://www.ietf.org/rfc/rfc1951.txt
Most API's defined in miniz.c are optional. For example, to disable the
archive related functions just define MINIZ_NO_ARCHIVE_APIS, or to get rid of
all stdio usage define MINIZ_NO_STDIO (see the list below for more macros).
* Change History
10/13/13 v1.15 r4 - Interim bugfix release while I work on the next major
release with Zip64 support (almost there!):
- Critical fix for the MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY bug
(thanks kahmyong.moon@hp.com) which could cause locate files to not find
files. This bug would only have occured in earlier versions if you explicitly
used this flag, OR if you used mz_zip_extract_archive_file_to_heap() or
mz_zip_add_mem_to_archive_file_in_place() (which used this flag). If you
can't switch to v1.15 but want to fix this bug, just remove the uses of this
flag from both helper funcs (and of course don't use the flag).
- Bugfix in mz_zip_reader_extract_to_mem_no_alloc() from kymoon when
pUser_read_buf is not NULL and compressed size is > uncompressed size
- Fixing mz_zip_reader_extract_*() funcs so they don't try to extract
compressed data from directory entries, to account for weird zipfiles which
contain zero-size compressed data on dir entries. Hopefully this fix won't
cause any issues on weird zip archives, because it assumes the low 16-bits of
zip external attributes are DOS attributes (which I believe they always are
in practice).
- Fixing mz_zip_reader_is_file_a_directory() so it doesn't check the
internal attributes, just the filename and external attributes
- mz_zip_reader_init_file() - missing MZ_FCLOSE() call if the seek failed
- Added cmake support for Linux builds which builds all the examples,
tested with clang v3.3 and gcc v4.6.
- Clang fix for tdefl_write_image_to_png_file_in_memory() from toffaletti
- Merged MZ_FORCEINLINE fix from hdeanclark
- Fix <time.h> include before config #ifdef, thanks emil.brink
- Added tdefl_write_image_to_png_file_in_memory_ex(): supports Y flipping
(super useful for OpenGL apps), and explicit control over the compression
level (so you can set it to 1 for real-time compression).
- Merged in some compiler fixes from paulharris's github repro.
- Retested this build under Windows (VS 2010, including static analysis),
tcc 0.9.26, gcc v4.6 and clang v3.3.
- Added example6.c, which dumps an image of the mandelbrot set to a PNG
file.
- Modified example2 to help test the
MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY flag more.
- In r3: Bugfix to mz_zip_writer_add_file() found during merge: Fix
possible src file fclose() leak if alignment bytes+local header file write
faiiled
- In r4: Minor bugfix to mz_zip_writer_add_from_zip_reader(): Was pushing the
wrong central dir header offset, appears harmless in this release, but it
became a problem in the zip64 branch 5/20/12 v1.14 - MinGW32/64 GCC 4.6.1
compiler fixes: added MZ_FORCEINLINE, #include <time.h> (thanks fermtect).
5/19/12 v1.13 - From jason@cornsyrup.org and kelwert@mtu.edu - Fix
mz_crc32() so it doesn't compute the wrong CRC-32's when mz_ulong is 64-bit.
- Temporarily/locally slammed in "typedef unsigned long mz_ulong" and
re-ran a randomized regression test on ~500k files.
- Eliminated a bunch of warnings when compiling with GCC 32-bit/64.
- Ran all examples, miniz.c, and tinfl.c through MSVC 2008's /analyze
(static analysis) option and fixed all warnings (except for the silly "Use of
the comma-operator in a tested expression.." analysis warning, which I
purposely use to work around a MSVC compiler warning).
- Created 32-bit and 64-bit Codeblocks projects/workspace. Built and
tested Linux executables. The codeblocks workspace is compatible with
Linux+Win32/x64.
- Added miniz_tester solution/project, which is a useful little app
derived from LZHAM's tester app that I use as part of the regression test.
- Ran miniz.c and tinfl.c through another series of regression testing on
~500,000 files and archives.
- Modified example5.c so it purposely disables a bunch of high-level
functionality (MINIZ_NO_STDIO, etc.). (Thanks to corysama for the
MINIZ_NO_STDIO bug report.)
- Fix ftell() usage in examples so they exit with an error on files which
are too large (a limitation of the examples, not miniz itself). 4/12/12 v1.12
- More comments, added low-level example5.c, fixed a couple minor
level_and_flags issues in the archive API's. level_and_flags can now be set
to MZ_DEFAULT_COMPRESSION. Thanks to Bruce Dawson <bruced@valvesoftware.com>
for the feedback/bug report. 5/28/11 v1.11 - Added statement from
unlicense.org 5/27/11 v1.10 - Substantial compressor optimizations:
- Level 1 is now ~4x faster than before. The L1 compressor's throughput
now varies between 70-110MB/sec. on a
- Core i7 (actual throughput varies depending on the type of data, and x64
vs. x86).
- Improved baseline L2-L9 compression perf. Also, greatly improved
compression perf. issues on some file types.
- Refactored the compression code for better readability and
maintainability.
- Added level 10 compression level (L10 has slightly better ratio than
level 9, but could have a potentially large drop in throughput on some
files). 5/15/11 v1.09 - Initial stable release.
* Low-level Deflate/Inflate implementation notes:
Compression: Use the "tdefl" API's. The compressor supports raw, static,
and dynamic blocks, lazy or greedy parsing, match length filtering, RLE-only,
and Huffman-only streams. It performs and compresses approximately as well as
zlib.
Decompression: Use the "tinfl" API's. The entire decompressor is
implemented as a single function coroutine: see tinfl_decompress(). It
supports decompression into a 32KB (or larger power of 2) wrapping buffer, or
into a memory block large enough to hold the entire file.
The low-level tdefl/tinfl API's do not make any use of dynamic memory
allocation.
* zlib-style API notes:
miniz.c implements a fairly large subset of zlib. There's enough
functionality present for it to be a drop-in zlib replacement in many apps:
The z_stream struct, optional memory allocation callbacks
deflateInit/deflateInit2/deflate/deflateReset/deflateEnd/deflateBound
inflateInit/inflateInit2/inflate/inflateEnd
compress, compress2, compressBound, uncompress
CRC-32, Adler-32 - Using modern, minimal code size, CPU cache friendly
routines. Supports raw deflate streams or standard zlib streams with adler-32
checking.
Limitations:
The callback API's are not implemented yet. No support for gzip headers or
zlib static dictionaries. I've tried to closely emulate zlib's various
flavors of stream flushing and return status codes, but there are no
guarantees that miniz.c pulls this off perfectly.
* PNG writing: See the tdefl_write_image_to_png_file_in_memory() function,
originally written by Alex Evans. Supports 1-4 bytes/pixel images.
* ZIP archive API notes:
The ZIP archive API's where designed with simplicity and efficiency in
mind, with just enough abstraction to get the job done with minimal fuss.
There are simple API's to retrieve file information, read files from existing
archives, create new archives, append new files to existing archives, or
clone archive data from one archive to another. It supports archives located
in memory or the heap, on disk (using stdio.h), or you can specify custom
file read/write callbacks.
- Archive reading: Just call this function to read a single file from a
disk archive:
void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const
char *pArchive_name, size_t *pSize, mz_uint zip_flags);
For more complex cases, use the "mz_zip_reader" functions. Upon opening an
archive, the entire central directory is located and read as-is into memory,
and subsequent file access only occurs when reading individual files.
- Archives file scanning: The simple way is to use this function to scan a
loaded archive for a specific file:
int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName,
const char *pComment, mz_uint flags);
The locate operation can optionally check file comments too, which (as one
example) can be used to identify multiple versions of the same file in an
archive. This function uses a simple linear search through the central
directory, so it's not very fast.
Alternately, you can iterate through all the files in an archive (using
mz_zip_reader_get_num_files()) and retrieve detailed info on each file by
calling mz_zip_reader_file_stat().
- Archive creation: Use the "mz_zip_writer" functions. The ZIP writer
immediately writes compressed file data to disk and builds an exact image of
the central directory in memory. The central directory image is written all
at once at the end of the archive file when the archive is finalized.
The archive writer can optionally align each file's local header and file
data to any power of 2 alignment, which can be useful when the archive will
be read from optical media. Also, the writer supports placing arbitrary data
blobs at the very beginning of ZIP archives. Archives written using either
feature are still readable by any ZIP tool.
- Archive appending: The simple way to add a single file to an archive is
to call this function:
mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename,
const char *pArchive_name, const void *pBuf, size_t buf_size, const void
*pComment, mz_uint16 comment_size, mz_uint level_and_flags);
The archive will be created if it doesn't already exist, otherwise it'll be
appended to. Note the appending is done in-place and is not an atomic
operation, so if something goes wrong during the operation it's possible the
archive could be left without a central directory (although the local file
headers and file data will be fine, so the archive will be recoverable).
For more complex archive modification scenarios:
1. The safest way is to use a mz_zip_reader to read the existing archive,
cloning only those bits you want to preserve into a new archive using using
the mz_zip_writer_add_from_zip_reader() function (which compiles the
compressed file data as-is). When you're done, delete the old archive and
rename the newly written archive, and you're done. This is safe but requires
a bunch of temporary disk space or heap memory.
2. Or, you can convert an mz_zip_reader in-place to an mz_zip_writer using
mz_zip_writer_init_from_reader(), append new files as needed, then finalize
the archive which will write an updated central directory to the original
archive. (This is basically what mz_zip_add_mem_to_archive_file_in_place()
does.) There's a possibility that the archive's central directory could be
lost with this method if anything goes wrong, though.
- ZIP archive support limitations:
No zip64 or spanning support. Extraction functions can only handle
unencrypted, stored or deflated files. Requires streams capable of seeking.
* This is a header file library, like stb_image.c. To get only a header file,
either cut and paste the below header, or create miniz.h, #define
MINIZ_HEADER_FILE_ONLY, and then include miniz.c from it.
* Important: For best perf. be sure to customize the below macros for your
target platform: #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 #define
MINIZ_LITTLE_ENDIAN 1 #define MINIZ_HAS_64BIT_REGISTERS 1
* On platforms using glibc, Be sure to "#define _LARGEFILE64_SOURCE 1" before
including miniz.c to ensure miniz uses the 64-bit variants: fopen64(),
stat64(), etc. Otherwise you won't be able to process large files (i.e.
32-bit stat() fails for me on files > 0x7FFFFFFF bytes).
*/
#ifndef MINIZ_HEADER_INCLUDED
#define MINIZ_HEADER_INCLUDED
#include <stdint.h>
#include <stdlib.h>
// Defines to completely disable specific portions of miniz.c:
// If all macros here are defined the only functionality remaining will be
// CRC-32, adler-32, tinfl, and tdefl.
// Define MINIZ_NO_STDIO to disable all usage and any functions which rely on
// stdio for file I/O.
//#define MINIZ_NO_STDIO
// If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able
// to get the current time, or get/set file times, and the C run-time funcs that
// get/set times won't be called. The current downside is the times written to
// your archives will be from 1979.
//#define MINIZ_NO_TIME
// Define MINIZ_NO_ARCHIVE_APIS to disable all ZIP archive API's.
//#define MINIZ_NO_ARCHIVE_APIS
// Define MINIZ_NO_ARCHIVE_APIS to disable all writing related ZIP archive
// API's.
//#define MINIZ_NO_ARCHIVE_WRITING_APIS
// Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression
// API's.
//#define MINIZ_NO_ZLIB_APIS
// Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent
// conflicts against stock zlib.
//#define MINIZ_NO_ZLIB_COMPATIBLE_NAMES
// Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc.
// Note if MINIZ_NO_MALLOC is defined then the user must always provide custom
// user alloc/free/realloc callbacks to the zlib and archive API's, and a few
// stand-alone helper API's which don't provide custom user functions (such as
// tdefl_compress_mem_to_heap() and tinfl_decompress_mem_to_heap()) won't work.
//#define MINIZ_NO_MALLOC
#if defined(__TINYC__) && (defined(__linux) || defined(__linux__))
// TODO: Work around "error: include file 'sys\utime.h' when compiling with tcc
// on Linux
#define MINIZ_NO_TIME
#endif
#if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_ARCHIVE_APIS)
#include <time.h>
#endif
#if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || \
defined(__i386) || defined(__i486__) || defined(__i486) || \
defined(i386) || defined(__ia64__) || defined(__x86_64__)
// MINIZ_X86_OR_X64_CPU is only used to help set the below macros.
#define MINIZ_X86_OR_X64_CPU 1
#endif
#if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU
// Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian.
#define MINIZ_LITTLE_ENDIAN 1
#endif
/* Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES only if not set */
#if !defined(MINIZ_USE_UNALIGNED_LOADS_AND_STORES)
#if MINIZ_X86_OR_X64_CPU
/* Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient
* integer loads and stores from unaligned addresses. */
#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1
#define MINIZ_UNALIGNED_USE_MEMCPY
#else
#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 0
#endif
#endif
#if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || \
defined(_LP64) || defined(__LP64__) || defined(__ia64__) || \
defined(__x86_64__)
// Set MINIZ_HAS_64BIT_REGISTERS to 1 if operations on 64-bit integers are
// reasonably fast (and don't involve compiler generated calls to helper
// functions).
#define MINIZ_HAS_64BIT_REGISTERS 1
#endif
#ifdef __APPLE__
#define ftello64 ftello
#define fseeko64 fseeko
#define fopen64 fopen
#define freopen64 freopen
// Darwin OSX
#define MZ_PLATFORM 19
#endif
#ifndef MZ_PLATFORM
#if defined(_WIN64) || defined(_WIN32) || defined(__WIN32__)
#define MZ_PLATFORM 0
#else
// UNIX
#define MZ_PLATFORM 3
#endif
#endif
#ifdef __cplusplus
extern "C" {
#endif
// ------------------- zlib-style API Definitions.
// For more compatibility with zlib, miniz.c uses unsigned long for some
// parameters/struct members. Beware: mz_ulong can be either 32 or 64-bits!
typedef unsigned long mz_ulong;
// mz_free() internally uses the MZ_FREE() macro (which by default calls free()
// unless you've modified the MZ_MALLOC macro) to release a block allocated from
// the heap.
void mz_free(void* p);
#define MZ_ADLER32_INIT (1)
// mz_adler32() returns the initial adler-32 value to use when called with
// ptr==NULL.
mz_ulong mz_adler32(mz_ulong adler, const unsigned char* ptr, size_t buf_len);
#define MZ_CRC32_INIT (0)
// mz_crc32() returns the initial CRC-32 value to use when called with
// ptr==NULL.
mz_ulong mz_crc32(mz_ulong crc, const void* ptr, size_t buf_len);
// Compression strategies.
enum {
MZ_DEFAULT_STRATEGY = 0,
MZ_FILTERED = 1,
MZ_HUFFMAN_ONLY = 2,
MZ_RLE = 3,
MZ_FIXED = 4
};
/* miniz error codes. Be sure to update mz_zip_get_error_string() if you add or
* modify this enum. */
typedef enum {
MZ_ZIP_NO_ERROR = 0,
MZ_ZIP_UNDEFINED_ERROR,
MZ_ZIP_TOO_MANY_FILES,
MZ_ZIP_FILE_TOO_LARGE,
MZ_ZIP_UNSUPPORTED_METHOD,
MZ_ZIP_UNSUPPORTED_ENCRYPTION,
MZ_ZIP_UNSUPPORTED_FEATURE,
MZ_ZIP_FAILED_FINDING_CENTRAL_DIR,
MZ_ZIP_NOT_AN_ARCHIVE,
MZ_ZIP_INVALID_HEADER_OR_CORRUPTED,
MZ_ZIP_UNSUPPORTED_MULTIDISK,
MZ_ZIP_DECOMPRESSION_FAILED,
MZ_ZIP_COMPRESSION_FAILED,
MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE,
MZ_ZIP_CRC_CHECK_FAILED,
MZ_ZIP_UNSUPPORTED_CDIR_SIZE,
MZ_ZIP_ALLOC_FAILED,
MZ_ZIP_FILE_OPEN_FAILED,
MZ_ZIP_FILE_CREATE_FAILED,
MZ_ZIP_FILE_WRITE_FAILED,
MZ_ZIP_FILE_READ_FAILED,
MZ_ZIP_FILE_CLOSE_FAILED,
MZ_ZIP_FILE_SEEK_FAILED,
MZ_ZIP_FILE_STAT_FAILED,
MZ_ZIP_INVALID_PARAMETER,
MZ_ZIP_INVALID_FILENAME,
MZ_ZIP_BUF_TOO_SMALL,
MZ_ZIP_INTERNAL_ERROR,
MZ_ZIP_FILE_NOT_FOUND,
MZ_ZIP_ARCHIVE_TOO_LARGE,
MZ_ZIP_VALIDATION_FAILED,
MZ_ZIP_WRITE_CALLBACK_FAILED,
MZ_ZIP_TOTAL_ERRORS
} mz_zip_error;
// Method
#define MZ_DEFLATED 8
#ifndef MINIZ_NO_ZLIB_APIS
// Heap allocation callbacks.
// Note that mz_alloc_func parameter types purposely differ from zlib's:
// items/size is size_t, not unsigned long.
typedef void* (*mz_alloc_func)(void* opaque, size_t items, size_t size);
typedef void (*mz_free_func)(void* opaque, void* address);
typedef void* (*mz_realloc_func)(void* opaque, void* address, size_t items,
size_t size);
#define MZ_VERSION "9.1.15"
#define MZ_VERNUM 0x91F0
#define MZ_VER_MAJOR 9
#define MZ_VER_MINOR 1
#define MZ_VER_REVISION 15
#define MZ_VER_SUBREVISION 0
// Flush values. For typical usage you only need MZ_NO_FLUSH and MZ_FINISH. The
// other values are for advanced use (refer to the zlib docs).
enum {
MZ_NO_FLUSH = 0,
MZ_PARTIAL_FLUSH = 1,
MZ_SYNC_FLUSH = 2,
MZ_FULL_FLUSH = 3,
MZ_FINISH = 4,
MZ_BLOCK = 5
};
// Return status codes. MZ_PARAM_ERROR is non-standard.
enum {
MZ_OK = 0,
MZ_STREAM_END = 1,
MZ_NEED_DICT = 2,
MZ_ERRNO = -1,
MZ_STREAM_ERROR = -2,
MZ_DATA_ERROR = -3,
MZ_MEM_ERROR = -4,
MZ_BUF_ERROR = -5,
MZ_VERSION_ERROR = -6,
MZ_PARAM_ERROR = -10000
};
// Compression levels: 0-9 are the standard zlib-style levels, 10 is best
// possible compression (not zlib compatible, and may be very slow),
// MZ_DEFAULT_COMPRESSION=MZ_DEFAULT_LEVEL.
enum {
MZ_NO_COMPRESSION = 0,
MZ_BEST_SPEED = 1,
MZ_BEST_COMPRESSION = 9,
MZ_UBER_COMPRESSION = 10,
MZ_DEFAULT_LEVEL = 6,
MZ_DEFAULT_COMPRESSION = -1
};
// Window bits
#define MZ_DEFAULT_WINDOW_BITS 15
struct mz_internal_state;
// Compression/decompression stream struct.
typedef struct mz_stream_s {
const unsigned char* next_in; // pointer to next byte to read
unsigned int avail_in; // number of bytes available at next_in
mz_ulong total_in; // total number of bytes consumed so far
unsigned char* next_out; // pointer to next byte to write
unsigned int avail_out; // number of bytes that can be written to next_out
mz_ulong total_out; // total number of bytes produced so far
char* msg; // error msg (unused)
struct mz_internal_state* state; // internal state, allocated by zalloc/zfree
mz_alloc_func
zalloc; // optional heap allocation function (defaults to malloc)
mz_free_func zfree; // optional heap free function (defaults to free)
void* opaque; // heap alloc function user pointer
int data_type; // data_type (unused)
mz_ulong adler; // adler32 of the source or uncompressed data
mz_ulong reserved; // not used
} mz_stream;
typedef mz_stream* mz_streamp;
// Returns the version string of miniz.c.
const char* mz_version(void);
// mz_deflateInit() initializes a compressor with default options:
// Parameters:
// pStream must point to an initialized mz_stream struct.
// level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION].
// level 1 enables a specially optimized compression function that's been
// optimized purely for performance, not ratio. (This special func. is
// currently only enabled when MINIZ_USE_UNALIGNED_LOADS_AND_STORES and
// MINIZ_LITTLE_ENDIAN are defined.)
// Return values:
// MZ_OK on success.
// MZ_STREAM_ERROR if the stream is bogus.
// MZ_PARAM_ERROR if the input parameters are bogus.
// MZ_MEM_ERROR on out of memory.
int mz_deflateInit(mz_streamp pStream, int level);
// mz_deflateInit2() is like mz_deflate(), except with more control:
// Additional parameters:
// method must be MZ_DEFLATED
// window_bits must be MZ_DEFAULT_WINDOW_BITS (to wrap the deflate stream with
// zlib header/adler-32 footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate/no
// header or footer) mem_level must be between [1, 9] (it's checked but
// ignored by miniz.c)
int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits,
int mem_level, int strategy);
// Quickly resets a compressor without having to reallocate anything. Same as
// calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2().
int mz_deflateReset(mz_streamp pStream);
// mz_deflate() compresses the input to output, consuming as much of the input
// and producing as much output as possible. Parameters:
// pStream is the stream to read from and write to. You must initialize/update
// the next_in, avail_in, next_out, and avail_out members. flush may be
// MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or MZ_FINISH.
// Return values:
// MZ_OK on success (when flushing, or if more input is needed but not
// available, and/or there's more output to be written but the output buffer
// is full). MZ_STREAM_END if all input has been consumed and all output bytes
// have been written. Don't call mz_deflate() on the stream anymore.
// MZ_STREAM_ERROR if the stream is bogus.
// MZ_PARAM_ERROR if one of the parameters is invalid.
// MZ_BUF_ERROR if no forward progress is possible because the input and/or
// output buffers are empty. (Fill up the input buffer or free up some output
// space and try again.)
int mz_deflate(mz_streamp pStream, int flush);
// mz_deflateEnd() deinitializes a compressor:
// Return values:
// MZ_OK on success.
// MZ_STREAM_ERROR if the stream is bogus.
int mz_deflateEnd(mz_streamp pStream);
// mz_deflateBound() returns a (very) conservative upper bound on the amount of
// data that could be generated by deflate(), assuming flush is set to only
// MZ_NO_FLUSH or MZ_FINISH.
mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len);
// Single-call compression functions mz_compress() and mz_compress2():
// Returns MZ_OK on success, or one of the error codes from mz_deflate() on
// failure.
int mz_compress(unsigned char* pDest, mz_ulong* pDest_len,
const unsigned char* pSource, mz_ulong source_len);
int mz_compress2(unsigned char* pDest, mz_ulong* pDest_len,
const unsigned char* pSource, mz_ulong source_len, int level);
// mz_compressBound() returns a (very) conservative upper bound on the amount of
// data that could be generated by calling mz_compress().
mz_ulong mz_compressBound(mz_ulong source_len);
// Initializes a decompressor.
int mz_inflateInit(mz_streamp pStream);
// mz_inflateInit2() is like mz_inflateInit() with an additional option that
// controls the window size and whether or not the stream has been wrapped with
// a zlib header/footer: window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse
// zlib header/footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate).
int mz_inflateInit2(mz_streamp pStream, int window_bits);
// Decompresses the input stream to the output, consuming only as much of the
// input as needed, and writing as much to the output as possible. Parameters:
// pStream is the stream to read from and write to. You must initialize/update
// the next_in, avail_in, next_out, and avail_out members. flush may be
// MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH. On the first call, if flush is
// MZ_FINISH it's assumed the input and output buffers are both sized large
// enough to decompress the entire stream in a single call (this is slightly
// faster). MZ_FINISH implies that there are no more source bytes available
// beside what's already in the input buffer, and that the output buffer is
// large enough to hold the rest of the decompressed data.
// Return values:
// MZ_OK on success. Either more input is needed but not available, and/or
// there's more output to be written but the output buffer is full.
// MZ_STREAM_END if all needed input has been consumed and all output bytes
// have been written. For zlib streams, the adler-32 of the decompressed data
// has also been verified. MZ_STREAM_ERROR if the stream is bogus.
// MZ_DATA_ERROR if the deflate stream is invalid.
// MZ_PARAM_ERROR if one of the parameters is invalid.
// MZ_BUF_ERROR if no forward progress is possible because the input buffer is
// empty but the inflater needs more input to continue, or if the output
// buffer is not large enough. Call mz_inflate() again with more input data,
// or with more room in the output buffer (except when using single call
// decompression, described above).
int mz_inflate(mz_streamp pStream, int flush);
// Deinitializes a decompressor.
int mz_inflateEnd(mz_streamp pStream);
// Single-call decompression.
// Returns MZ_OK on success, or one of the error codes from mz_inflate() on
// failure.
int mz_uncompress(unsigned char* pDest, mz_ulong* pDest_len,
const unsigned char* pSource, mz_ulong source_len);
// Returns a string description of the specified error code, or NULL if the
// error code is invalid.
const char* mz_error(int err);
// Redefine zlib-compatible names to miniz equivalents, so miniz.c can be used
// as a drop-in replacement for the subset of zlib that miniz.c supports. Define
// MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you use zlib
// in the same project.
#ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES
typedef unsigned char Byte;
typedef unsigned int uInt;
typedef mz_ulong uLong;
typedef Byte Bytef;
typedef uInt uIntf;
typedef char charf;
typedef int intf;
typedef void* voidpf;
typedef uLong uLongf;
typedef void* voidp;
typedef void* const voidpc;
#define Z_NULL 0
#define Z_NO_FLUSH MZ_NO_FLUSH
#define Z_PARTIAL_FLUSH MZ_PARTIAL_FLUSH
#define Z_SYNC_FLUSH MZ_SYNC_FLUSH
#define Z_FULL_FLUSH MZ_FULL_FLUSH
#define Z_FINISH MZ_FINISH
#define Z_BLOCK MZ_BLOCK
#define Z_OK MZ_OK
#define Z_STREAM_END MZ_STREAM_END
#define Z_NEED_DICT MZ_NEED_DICT
#define Z_ERRNO MZ_ERRNO
#define Z_STREAM_ERROR MZ_STREAM_ERROR
#define Z_DATA_ERROR MZ_DATA_ERROR
#define Z_MEM_ERROR MZ_MEM_ERROR
#define Z_BUF_ERROR MZ_BUF_ERROR
#define Z_VERSION_ERROR MZ_VERSION_ERROR
#define Z_PARAM_ERROR MZ_PARAM_ERROR
#define Z_NO_COMPRESSION MZ_NO_COMPRESSION
#define Z_BEST_SPEED MZ_BEST_SPEED
#define Z_BEST_COMPRESSION MZ_BEST_COMPRESSION
#define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION
#define Z_DEFAULT_STRATEGY MZ_DEFAULT_STRATEGY
#define Z_FILTERED MZ_FILTERED
#define Z_HUFFMAN_ONLY MZ_HUFFMAN_ONLY
#define Z_RLE MZ_RLE
#define Z_FIXED MZ_FIXED
#define Z_DEFLATED MZ_DEFLATED
#define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS
#define alloc_func mz_alloc_func
#define free_func mz_free_func
#define internal_state mz_internal_state
#define z_stream mz_stream
#define deflateInit mz_deflateInit
#define deflateInit2 mz_deflateInit2
#define deflateReset mz_deflateReset
#define deflate mz_deflate
#define deflateEnd mz_deflateEnd
#define deflateBound mz_deflateBound
#define compress mz_compress
#define compress2 mz_compress2
#define compressBound mz_compressBound
#define inflateInit mz_inflateInit
#define inflateInit2 mz_inflateInit2
#define inflate mz_inflate
#define inflateEnd mz_inflateEnd
#define uncompress mz_uncompress
#define crc32 mz_crc32
#define adler32 mz_adler32
#define MAX_WBITS 15
#define MAX_MEM_LEVEL 9
#define zError mz_error
#define ZLIB_VERSION MZ_VERSION
#define ZLIB_VERNUM MZ_VERNUM
#define ZLIB_VER_MAJOR MZ_VER_MAJOR
#define ZLIB_VER_MINOR MZ_VER_MINOR
#define ZLIB_VER_REVISION MZ_VER_REVISION
#define ZLIB_VER_SUBREVISION MZ_VER_SUBREVISION
#define zlibVersion mz_version
#define zlib_version mz_version()
#endif // #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES
#endif // MINIZ_NO_ZLIB_APIS
// ------------------- Types and macros
typedef unsigned char mz_uint8;
typedef signed short mz_int16;
typedef unsigned short mz_uint16;
typedef unsigned int mz_uint32;
typedef unsigned int mz_uint;
typedef long long mz_int64;
typedef unsigned long long mz_uint64;
typedef int mz_bool;
#define MZ_FALSE (0)
#define MZ_TRUE (1)
// An attempt to work around MSVC's spammy "warning C4127: conditional
// expression is constant" message.
#ifdef _MSC_VER
#define MZ_MACRO_END while (0, 0)
#else
#define MZ_MACRO_END while (0)
#endif
// ------------------- ZIP archive reading/writing
#ifndef MINIZ_NO_ARCHIVE_APIS
enum {
MZ_ZIP_MAX_IO_BUF_SIZE = 64 * 1024,
MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE = 260,
MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE = 256
};
typedef struct {
mz_uint32 m_file_index;
mz_uint32 m_central_dir_ofs;
mz_uint16 m_version_made_by;
mz_uint16 m_version_needed;
mz_uint16 m_bit_flag;
mz_uint16 m_method;
#ifndef MINIZ_NO_TIME
time_t m_time;
#endif
mz_uint32 m_crc32;
mz_uint64 m_comp_size;
mz_uint64 m_uncomp_size;
mz_uint16 m_internal_attr;
mz_uint32 m_external_attr;
mz_uint64 m_local_header_ofs;
mz_uint32 m_comment_size;
char m_filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE];
char m_comment[MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE];
} mz_zip_archive_file_stat;
typedef size_t(*mz_file_read_func)(void* pOpaque, mz_uint64 file_ofs,
void* pBuf, size_t n);
typedef size_t(*mz_file_write_func)(void* pOpaque, mz_uint64 file_ofs,
const void* pBuf, size_t n);
typedef mz_bool(*mz_file_needs_keepalive)(void* pOpaque);
struct mz_zip_internal_state_tag;
typedef struct mz_zip_internal_state_tag mz_zip_internal_state;
typedef enum {
MZ_ZIP_MODE_INVALID = 0,
MZ_ZIP_MODE_READING = 1,
MZ_ZIP_MODE_WRITING = 2,
MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED = 3
} mz_zip_mode;
typedef enum {
MZ_ZIP_TYPE_INVALID = 0,
MZ_ZIP_TYPE_USER,
MZ_ZIP_TYPE_MEMORY,
MZ_ZIP_TYPE_HEAP,
MZ_ZIP_TYPE_FILE,
MZ_ZIP_TYPE_CFILE,
MZ_ZIP_TOTAL_TYPES
} mz_zip_type;
typedef struct {
mz_uint64 m_archive_size;
mz_uint64 m_central_directory_file_ofs;
/* We only support up to UINT32_MAX files in zip64 mode. */
mz_uint32 m_total_files;
mz_zip_mode m_zip_mode;
mz_zip_type m_zip_type;
mz_zip_error m_last_error;
mz_uint64 m_file_offset_alignment;
mz_alloc_func m_pAlloc;
mz_free_func m_pFree;
mz_realloc_func m_pRealloc;
void* m_pAlloc_opaque;
mz_file_read_func m_pRead;
mz_file_write_func m_pWrite;
mz_file_needs_keepalive m_pNeeds_keepalive;
void* m_pIO_opaque;
mz_zip_internal_state* m_pState;
} mz_zip_archive;
typedef enum {
MZ_ZIP_FLAG_CASE_SENSITIVE = 0x0100,
MZ_ZIP_FLAG_IGNORE_PATH = 0x0200,
MZ_ZIP_FLAG_COMPRESSED_DATA = 0x0400,
MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY = 0x0800
} mz_zip_flags;
// ZIP archive reading
// Inits a ZIP archive reader.
// These functions read and validate the archive's central directory.
mz_bool mz_zip_reader_init(mz_zip_archive* pZip, mz_uint64 size,
mz_uint32 flags);
mz_bool mz_zip_reader_init_mem(mz_zip_archive* pZip, const void* pMem,
size_t size, mz_uint32 flags);
#ifndef MINIZ_NO_STDIO
mz_bool mz_zip_reader_init_file(mz_zip_archive* pZip, const char* pFilename,
mz_uint32 flags);
#endif
// Returns the total number of files in the archive.
mz_uint mz_zip_reader_get_num_files(mz_zip_archive* pZip);
// Returns detailed information about an archive file entry.
mz_bool mz_zip_reader_file_stat(mz_zip_archive* pZip, mz_uint file_index,
mz_zip_archive_file_stat* pStat);
// Determines if an archive file entry is a directory entry.
mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive* pZip,
mz_uint file_index);
mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive* pZip,
mz_uint file_index);
// Retrieves the filename of an archive file entry.
// Returns the number of bytes written to pFilename, or if filename_buf_size is
// 0 this function returns the number of bytes needed to fully store the
// filename.
mz_uint mz_zip_reader_get_filename(mz_zip_archive* pZip, mz_uint file_index,
char* pFilename, mz_uint filename_buf_size);
// Attempts to locates a file in the archive's central directory.
// Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH
// Returns -1 if the file cannot be found.
int mz_zip_reader_locate_file(mz_zip_archive* pZip, const char* pName,
const char* pComment, mz_uint flags);
// Extracts a archive file to a memory buffer using no memory allocation.
mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive* pZip,
mz_uint file_index, void* pBuf,
size_t buf_size, mz_uint flags,
void* pUser_read_buf,
size_t user_read_buf_size);
mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(
mz_zip_archive* pZip, const char* pFilename, void* pBuf, size_t buf_size,
mz_uint flags, void* pUser_read_buf, size_t user_read_buf_size);
// Extracts a archive file to a memory buffer.
mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive* pZip, mz_uint file_index,
void* pBuf, size_t buf_size,
mz_uint flags);
mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive* pZip,
const char* pFilename, void* pBuf,
size_t buf_size, mz_uint flags);
// Extracts a archive file to a dynamically allocated heap buffer.
void* mz_zip_reader_extract_to_heap(mz_zip_archive* pZip, mz_uint file_index,
size_t* pSize, mz_uint flags);
void* mz_zip_reader_extract_file_to_heap(mz_zip_archive* pZip,
const char* pFilename, size_t* pSize,
mz_uint flags);
// Extracts a archive file using a callback function to output the file's data.
mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive* pZip,
mz_uint file_index,
mz_file_write_func pCallback,
void* pOpaque, mz_uint flags);
mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive* pZip,
const char* pFilename,
mz_file_write_func pCallback,
void* pOpaque, mz_uint flags);
#ifndef MINIZ_NO_STDIO
// Extracts a archive file to a disk file and sets its last accessed and
// modified times. This function only extracts files, not archive directory
// records.
mz_bool mz_zip_reader_extract_to_file(mz_zip_archive* pZip, mz_uint file_index,
const char* pDst_filename, mz_uint flags);
mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive* pZip,
const char* pArchive_filename,
const char* pDst_filename,
mz_uint flags);
#endif
// Ends archive reading, freeing all allocations, and closing the input archive
// file if mz_zip_reader_init_file() was used.
mz_bool mz_zip_reader_end(mz_zip_archive* pZip);
// ZIP archive writing
#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
// Inits a ZIP archive writer.
mz_bool mz_zip_writer_init(mz_zip_archive* pZip, mz_uint64 existing_size);
mz_bool mz_zip_writer_init_heap(mz_zip_archive* pZip,
size_t size_to_reserve_at_beginning,
size_t initial_allocation_size);
#ifndef MINIZ_NO_STDIO
mz_bool mz_zip_writer_init_file(mz_zip_archive* pZip, const char* pFilename,
mz_uint64 size_to_reserve_at_beginning);
#endif
// Converts a ZIP archive reader object into a writer object, to allow efficient
// in-place file appends to occur on an existing archive. For archives opened
// using mz_zip_reader_init_file, pFilename must be the archive's filename so it
// can be reopened for writing. If the file can't be reopened,
// mz_zip_reader_end() will be called. For archives opened using
// mz_zip_reader_init_mem, the memory block must be growable using the realloc
// callback (which defaults to realloc unless you've overridden it). Finally,
// for archives opened using mz_zip_reader_init, the mz_zip_archive's user
// provided m_pWrite function cannot be NULL. Note: In-place archive
// modification is not recommended unless you know what you're doing, because if
// execution stops or something goes wrong before the archive is finalized the
// file's central directory will be hosed.
mz_bool mz_zip_writer_init_from_reader(mz_zip_archive* pZip,
const char* pFilename);
// Adds the contents of a memory buffer to an archive. These functions record
// the current local time into the archive. To add a directory entry, call this
// method with an archive name ending in a forwardslash with empty buffer.
// level_and_flags - compression level (0-10, see MZ_BEST_SPEED,
// MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or
// just set to MZ_DEFAULT_COMPRESSION.
mz_bool mz_zip_writer_add_mem(mz_zip_archive* pZip, const char* pArchive_name,
const void* pBuf, size_t buf_size,
mz_uint level_and_flags);
mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive* pZip,
const char* pArchive_name, const void* pBuf,
size_t buf_size, const void* pComment,
mz_uint16 comment_size,
mz_uint level_and_flags, mz_uint64 uncomp_size,
mz_uint32 uncomp_crc32);
#ifndef MINIZ_NO_STDIO
// Adds the contents of a disk file to an archive. This function also records
// the disk file's modified time into the archive. level_and_flags - compression
// level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd
// with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION.
mz_bool mz_zip_writer_add_file(mz_zip_archive* pZip, const char* pArchive_name,
const char* pSrc_filename, const void* pComment,
mz_uint16 comment_size, mz_uint level_and_flags,
mz_uint32 ext_attributes);
#endif
// Adds a file to an archive by fully cloning the data from another archive.
// This function fully clones the source file's compressed data (no
// recompression), along with its full filename, extra data, and comment fields.
mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive* pZip,
mz_zip_archive* pSource_zip,
mz_uint file_index);
// Finalizes the archive by writing the central directory records followed by
// the end of central directory record. After an archive is finalized, the only
// valid call on the mz_zip_archive struct is mz_zip_writer_end(). An archive
// must be manually finalized by calling this function for it to be valid.
mz_bool mz_zip_writer_finalize_archive(mz_zip_archive* pZip);
mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive* pZip, void** pBuf,
size_t* pSize);
// Ends archive writing, freeing all allocations, and closing the output file if
// mz_zip_writer_init_file() was used. Note for the archive to be valid, it must
// have been finalized before ending.
mz_bool mz_zip_writer_end(mz_zip_archive* pZip);
// Misc. high-level helper functions:
// mz_zip_add_mem_to_archive_file_in_place() efficiently (but not atomically)
// appends a memory blob to a ZIP archive. level_and_flags - compression level
// (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero
// or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION.
mz_bool mz_zip_add_mem_to_archive_file_in_place(
const char* pZip_filename, const char* pArchive_name, const void* pBuf,
size_t buf_size, const void* pComment, mz_uint16 comment_size,
mz_uint level_and_flags);
// Reads a single file from an archive into a heap block.
// Returns NULL on failure.
void* mz_zip_extract_archive_file_to_heap(const char* pZip_filename,
const char* pArchive_name,
size_t* pSize, mz_uint zip_flags);
#endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
#endif // #ifndef MINIZ_NO_ARCHIVE_APIS
// ------------------- Low-level Decompression API Definitions
// Decompression flags used by tinfl_decompress().
// TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and
// ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the
// input is a raw deflate stream. TINFL_FLAG_HAS_MORE_INPUT: If set, there are
// more input bytes available beyond the end of the supplied input buffer. If
// clear, the input buffer contains all remaining input.
// TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large
// enough to hold the entire decompressed stream. If clear, the output buffer is
// at least the size of the dictionary (typically 32KB).
// TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the
// decompressed bytes.
enum {
TINFL_FLAG_PARSE_ZLIB_HEADER = 1,
TINFL_FLAG_HAS_MORE_INPUT = 2,
TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4,
TINFL_FLAG_COMPUTE_ADLER32 = 8
};
// High level decompression functions:
// tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block
// allocated via malloc(). On entry:
// pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data
// to decompress.
// On return:
// Function returns a pointer to the decompressed data, or NULL on failure.
// *pOut_len will be set to the decompressed data's size, which could be larger
// than src_buf_len on uncompressible data. The caller must call mz_free() on
// the returned block when it's no longer needed.
void* tinfl_decompress_mem_to_heap(const void* pSrc_buf, size_t src_buf_len,
size_t* pOut_len, int flags);
// tinfl_decompress_mem_to_mem() decompresses a block in memory to another block
// in memory. Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the
// number of bytes written on success.
#define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1))
size_t tinfl_decompress_mem_to_mem(void* pOut_buf, size_t out_buf_len,
const void* pSrc_buf, size_t src_buf_len,
int flags);
// tinfl_decompress_mem_to_callback() decompresses a block in memory to an
// internal 32KB buffer, and a user provided callback function will be called to
// flush the buffer. Returns 1 on success or 0 on failure.
typedef int (*tinfl_put_buf_func_ptr)(const void* pBuf, int len, void* pUser);
int tinfl_decompress_mem_to_callback(const void* pIn_buf, size_t* pIn_buf_size,
tinfl_put_buf_func_ptr pPut_buf_func,
void* pPut_buf_user, int flags);
struct tinfl_decompressor_tag;
typedef struct tinfl_decompressor_tag tinfl_decompressor;
// Max size of LZ dictionary.
#define TINFL_LZ_DICT_SIZE 32768
// Return status.
typedef enum {
TINFL_STATUS_BAD_PARAM = -3,
TINFL_STATUS_ADLER32_MISMATCH = -2,
TINFL_STATUS_FAILED = -1,
TINFL_STATUS_DONE = 0,
TINFL_STATUS_NEEDS_MORE_INPUT = 1,
TINFL_STATUS_HAS_MORE_OUTPUT = 2
} tinfl_status;
// Initializes the decompressor to its initial state.
#define tinfl_init(r) \
do { \
(r)->m_state = 0; \
} \
MZ_MACRO_END
#define tinfl_get_adler32(r) (r)->m_check_adler32
// Main low-level decompressor coroutine function. This is the only function
// actually needed for decompression. All the other functions are just
// high-level helpers for improved usability. This is a universal API, i.e. it
// can be used as a building block to build any desired higher level
// decompression API. In the limit case, it can be called once per every byte
// input or output.
tinfl_status tinfl_decompress(tinfl_decompressor* r,
const mz_uint8* pIn_buf_next,
size_t* pIn_buf_size, mz_uint8* pOut_buf_start,
mz_uint8* pOut_buf_next, size_t* pOut_buf_size,
const mz_uint32 decomp_flags);
// Internal/private bits follow.
enum {
TINFL_MAX_HUFF_TABLES = 3,
TINFL_MAX_HUFF_SYMBOLS_0 = 288,
TINFL_MAX_HUFF_SYMBOLS_1 = 32,
TINFL_MAX_HUFF_SYMBOLS_2 = 19,
TINFL_FAST_LOOKUP_BITS = 10,
TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS
};
typedef struct {
mz_uint8 m_code_size[TINFL_MAX_HUFF_SYMBOLS_0];
mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE],
m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2];
} tinfl_huff_table;
#if MINIZ_HAS_64BIT_REGISTERS
#define TINFL_USE_64BIT_BITBUF 1
#endif
#if TINFL_USE_64BIT_BITBUF
typedef mz_uint64 tinfl_bit_buf_t;
#define TINFL_BITBUF_SIZE (64)
#else
typedef mz_uint32 tinfl_bit_buf_t;
#define TINFL_BITBUF_SIZE (32)
#endif
struct tinfl_decompressor_tag {
mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type,
m_check_adler32, m_dist, m_counter, m_num_extra,
m_table_sizes[TINFL_MAX_HUFF_TABLES];
tinfl_bit_buf_t m_bit_buf;
size_t m_dist_from_out_buf_start;
tinfl_huff_table m_tables[TINFL_MAX_HUFF_TABLES];
mz_uint8 m_raw_header[4],
m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137];
};
// ------------------- Low-level Compression API Definitions
// Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly
// slower, and raw/dynamic blocks will be output more frequently).
#define TDEFL_LESS_MEMORY 0
// tdefl_init() compression flags logically OR'd together (low 12 bits contain
// the max. number of probes per dictionary search): TDEFL_DEFAULT_MAX_PROBES:
// The compressor defaults to 128 dictionary probes per dictionary search.
// 0=Huffman only, 1=Huffman+LZ (fastest/crap compression), 4095=Huffman+LZ
// (slowest/best compression).
enum {
TDEFL_HUFFMAN_ONLY = 0,
TDEFL_DEFAULT_MAX_PROBES = 128,
TDEFL_MAX_PROBES_MASK = 0xFFF
};
// TDEFL_WRITE_ZLIB_HEADER: If set, the compressor outputs a zlib header before
// the deflate data, and the Adler-32 of the source data at the end. Otherwise,
// you'll get raw deflate data. TDEFL_COMPUTE_ADLER32: Always compute the
// adler-32 of the input data (even when not writing zlib headers).
// TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more
// efficient lazy parsing. TDEFL_NONDETERMINISTIC_PARSING_FLAG: Enable to
// decrease the compressor's initialization time to the minimum, but the output
// may vary from run to run given the same input (depending on the contents of
// memory). TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a
// distance of 1) TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled.
// TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables.
// TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks.
// The low 12 bits are reserved to control the max # of hash probes per
// dictionary lookup (see TDEFL_MAX_PROBES_MASK).
enum {
TDEFL_WRITE_ZLIB_HEADER = 0x01000,
TDEFL_COMPUTE_ADLER32 = 0x02000,
TDEFL_GREEDY_PARSING_FLAG = 0x04000,
TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000,
TDEFL_RLE_MATCHES = 0x10000,
TDEFL_FILTER_MATCHES = 0x20000,
TDEFL_FORCE_ALL_STATIC_BLOCKS = 0x40000,
TDEFL_FORCE_ALL_RAW_BLOCKS = 0x80000
};
// High level compression functions:
// tdefl_compress_mem_to_heap() compresses a block in memory to a heap block
// allocated via malloc(). On entry:
// pSrc_buf, src_buf_len: Pointer and size of source block to compress.
// flags: The max match finder probes (default is 128) logically OR'd against
// the above flags. Higher probes are slower but improve compression.
// On return:
// Function returns a pointer to the compressed data, or NULL on failure.
// *pOut_len will be set to the compressed data's size, which could be larger
// than src_buf_len on uncompressible data. The caller must free() the returned
// block when it's no longer needed.
void* tdefl_compress_mem_to_heap(const void* pSrc_buf, size_t src_buf_len,
size_t* pOut_len, int flags);
// tdefl_compress_mem_to_mem() compresses a block in memory to another block in
// memory. Returns 0 on failure.
size_t tdefl_compress_mem_to_mem(void* pOut_buf, size_t out_buf_len,
const void* pSrc_buf, size_t src_buf_len,
int flags);
// Output stream interface. The compressor uses this interface to write
// compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time.
typedef mz_bool(*tdefl_put_buf_func_ptr)(const void* pBuf, int len,
void* pUser);
// tdefl_compress_mem_to_output() compresses a block to an output stream. The
// above helpers use this function internally.
mz_bool tdefl_compress_mem_to_output(const void* pBuf, size_t buf_len,
tdefl_put_buf_func_ptr pPut_buf_func,
void* pPut_buf_user, int flags);
enum {
TDEFL_MAX_HUFF_TABLES = 3,
TDEFL_MAX_HUFF_SYMBOLS_0 = 288,
TDEFL_MAX_HUFF_SYMBOLS_1 = 32,
TDEFL_MAX_HUFF_SYMBOLS_2 = 19,
TDEFL_LZ_DICT_SIZE = 32768,
TDEFL_LZ_DICT_SIZE_MASK = TDEFL_LZ_DICT_SIZE - 1,
TDEFL_MIN_MATCH_LEN = 3,
TDEFL_MAX_MATCH_LEN = 258
};
// TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed
// output block (using static/fixed Huffman codes).
#if TDEFL_LESS_MEMORY
enum {
TDEFL_LZ_CODE_BUF_SIZE = 24 * 1024,
TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10,
TDEFL_MAX_HUFF_SYMBOLS = 288,
TDEFL_LZ_HASH_BITS = 12,
TDEFL_LEVEL1_HASH_SIZE_MASK = 4095,
TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3,
TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS
};
#else
enum {
TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024,
TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10,
TDEFL_MAX_HUFF_SYMBOLS = 288,
TDEFL_LZ_HASH_BITS = 15,
TDEFL_LEVEL1_HASH_SIZE_MASK = 4095,
TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3,
TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS
};
#endif
// The low-level tdefl functions below may be used directly if the above helper
// functions aren't flexible enough. The low-level functions don't make any heap
// allocations, unlike the above helper functions.
typedef enum {
TDEFL_STATUS_BAD_PARAM = -2,
TDEFL_STATUS_PUT_BUF_FAILED = -1,
TDEFL_STATUS_OKAY = 0,
TDEFL_STATUS_DONE = 1,
} tdefl_status;
// Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums
typedef enum {
TDEFL_NO_FLUSH = 0,
TDEFL_SYNC_FLUSH = 2,
TDEFL_FULL_FLUSH = 3,
TDEFL_FINISH = 4
} tdefl_flush;
// tdefl's compression state structure.
typedef struct {
tdefl_put_buf_func_ptr m_pPut_buf_func;
void* m_pPut_buf_user;
mz_uint m_flags, m_max_probes[2];
int m_greedy_parsing;
mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size;
mz_uint8* m_pLZ_code_buf, * m_pLZ_flags, * m_pOutput_buf, * m_pOutput_buf_end;
mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in,
m_bit_buffer;
mz_uint m_saved_match_dist, m_saved_match_len, m_saved_lit,
m_output_flush_ofs, m_output_flush_remaining, m_finished, m_block_index,
m_wants_to_finish;
tdefl_status m_prev_return_status;
const void* m_pIn_buf;
void* m_pOut_buf;
size_t* m_pIn_buf_size, * m_pOut_buf_size;
tdefl_flush m_flush;
const mz_uint8* m_pSrc;
size_t m_src_buf_left, m_out_buf_ofs;
mz_uint8 m_dict[TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1];
mz_uint16 m_huff_count[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
mz_uint16 m_huff_codes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
mz_uint8 m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
mz_uint8 m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE];
mz_uint16 m_next[TDEFL_LZ_DICT_SIZE];
mz_uint16 m_hash[TDEFL_LZ_HASH_SIZE];
mz_uint8 m_output_buf[TDEFL_OUT_BUF_SIZE];
} tdefl_compressor;
// Initializes the compressor.
// There is no corresponding deinit() function because the tdefl API's do not
// dynamically allocate memory. pBut_buf_func: If NULL, output data will be
// supplied to the specified callback. In this case, the user should call the
// tdefl_compress_buffer() API for compression. If pBut_buf_func is NULL the
// user should always call the tdefl_compress() API. flags: See the above enums
// (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER, etc.)
tdefl_status tdefl_init(tdefl_compressor* d,
tdefl_put_buf_func_ptr pPut_buf_func,
void* pPut_buf_user, int flags);
// Compresses a block of data, consuming as much of the specified input buffer
// as possible, and writing as much compressed data to the specified output
// buffer as possible.
tdefl_status tdefl_compress(tdefl_compressor* d, const void* pIn_buf,
size_t* pIn_buf_size, void* pOut_buf,
size_t* pOut_buf_size, tdefl_flush flush);
// tdefl_compress_buffer() is only usable when the tdefl_init() is called with a
// non-NULL tdefl_put_buf_func_ptr. tdefl_compress_buffer() always consumes the
// entire input buffer.
tdefl_status tdefl_compress_buffer(tdefl_compressor* d, const void* pIn_buf,
size_t in_buf_size, tdefl_flush flush);
tdefl_status tdefl_get_prev_return_status(tdefl_compressor* d);
mz_uint32 tdefl_get_adler32(tdefl_compressor* d);
// Can't use tdefl_create_comp_flags_from_zip_params if MINIZ_NO_ZLIB_APIS isn't
// defined, because it uses some of its macros.
#ifndef MINIZ_NO_ZLIB_APIS
// Create tdefl_compress() flags given zlib-style compression parameters.
// level may range from [0,10] (where 10 is absolute max compression, but may be
// much slower on some files) window_bits may be -15 (raw deflate) or 15 (zlib)
// strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY,
// MZ_RLE, or MZ_FIXED
mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits,
int strategy);
#endif // #ifndef MINIZ_NO_ZLIB_APIS
#define MZ_UINT16_MAX (0xFFFFU)
#define MZ_UINT32_MAX (0xFFFFFFFFU)
#ifdef __cplusplus
}
#endif
#endif // MINIZ_HEADER_INCLUDED | 44.035933 | 86 | 0.727027 | [
"object"
] |
f0e02135b1856fc2f1948e09e03899cb4d12406d | 116,743 | cpp | C++ | PyCommon/modules/Simulator/csVpModel.cpp | hpgit/HumanFoot | f9a1a341b7c43747bddcd5584b8c98a0d1ac2973 | [
"Apache-2.0"
] | null | null | null | PyCommon/modules/Simulator/csVpModel.cpp | hpgit/HumanFoot | f9a1a341b7c43747bddcd5584b8c98a0d1ac2973 | [
"Apache-2.0"
] | null | null | null | PyCommon/modules/Simulator/csVpModel.cpp | hpgit/HumanFoot | f9a1a341b7c43747bddcd5584b8c98a0d1ac2973 | [
"Apache-2.0"
] | null | null | null | #include "stdafx.h"
#include <algorithm>
#include "boostPythonUtil.h"
#include "VPUtil.h"
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>
//#define make_tuple boost::python::make_tuple
//using boost::python::make_tuple;
namespace bp = boost::python;
namespace np = boost::python::numpy;
using boost::python::numpy::ndarray;
namespace ublas = boost::numeric::ublas;
#include "csVpModel.h"
#include "csVpWorld.h"
#include "myGeom.h"
//#include "hpBJoint.h"
//#include "hpUJoint.h"
//#include "hpRJoint.h"
#define MAX_X 1 // 0001
#define MAX_Y 2 // 0010
#define MAX_Z 4 // 0100
#define QP
BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(getJointPositionGlobal_py_overloads, getJointPositionGlobal, 1, 2);
BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(getBodyPositionGlobal_py_overloads, getBodyPositionGlobal_py, 1, 2);
BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(getBodyVelocityGlobal_py_overloads, getBodyVelocityGlobal_py, 1, 2);
BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(getBodyAccelerationGlobal_py_overloads, getBodyAccelerationGlobal_py, 1, 2);
BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(VpMotionModel_recordVelByFiniteDiff_overloads, recordVelByFiniteDiff, 0, 2);
BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(VpControlModel_applyBodyGenForceGlobal_overloads, applyBodyGenForceGlobal, 3, 4);
BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(VpControlModel_applyBodyForceGlobal_overloads, applyBodyForceGlobal, 2, 3);
BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(initializeHybridDynamics_overloads, initializeHybridDynamics, 0, 1);
BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(VpControlModel_SetJointElasticity_overloads, SetJointElasticity, 2, 4);
BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(VpControlModel_SetJointsElasticity_overloads, SetJointsElasticity, 1, 3);
BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(VpControlModel_SetJointDamping_overloads, SetJointDamping, 2, 4);
BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(VpControlModel_SetJointsDamping_overloads, SetJointsDamping, 1, 3);
BOOST_PYTHON_MODULE(csVpModel)
{
class_<VpModel>("VpModel", init<VpWorld*, object, object>())
.def("__str__", &VpModel::__str__)
.def("getBodyNum", &VpModel::getBodyNum)
.def("getBodyMasses", &VpModel::getBodyMasses)
.def("getTotalMass", &VpModel::getTotalMass)
.def("getBodyVerticesPositionGlobal", &VpModel::getBodyVerticesPositionGlobal)
.def("getBodyGeomNum", &VpModel::getBodyGeomNum)
.def("getBodyGeomsType", &VpModel::getBodyGeomsType)
.def("getBodyGeomsSize", &VpModel::getBodyGeomsSize)
.def("getBodyGeomsLocalFrame", &VpModel::getBodyGeomsLocalFrame)
.def("getBodyGeomsGlobalFrame", &VpModel::getBodyGeomsGlobalFrame)
.def("getBodyShape", &VpModel::getBodyShape)
.def("getBodyByIndex", &VpModel::getBodyByIndex, return_value_policy<reference_existing_object>())
.def("getBodyByName", &VpModel::getBodyByName, return_value_policy<reference_existing_object>())
.def("getJointByIndex", &VpModel::getJointByIndex, return_value_policy<reference_existing_object>())
.def("getJointByName", &VpModel::getJointByName, return_value_policy<reference_existing_object>())
.def("index2name", &VpModel::index2name)
.def("index2vpid", &VpModel::index2vpid)
.def("name2index", &VpModel::name2index)
.def("name2vpid", &VpModel::name2vpid)
.def("getBodyInertiaLocal", &VpModel::getBodyInertiaLocal_py)
.def("getBodyInertiaGlobal", &VpModel::getBodyInertiaGlobal_py)
.def("getBodyInertiasLocal", &VpModel::getBodyInertiasLocal)
.def("getBodyInertiasGlobal", &VpModel::getBodyInertiasGlobal)
.def("getCOM", &VpModel::getCOM)
.def("getBoneT", &VpModel::getBoneT)
.def("getInvBoneT", &VpModel::getInvBoneT)
.def("getBodyGenVelLocal", &VpModel::getBodyGenVelLocal)
.def("getBodyGenVelGlobal", &VpModel::getBodyGenVelGlobal)
.def("getBodyGenAccLocal", &VpModel::getBodyGenAccLocal)
.def("getBodyGenAccGlobal", &VpModel::getBodyGenAccGlobal)
.def("getBodyPositionGlobal", &VpModel::getBodyPositionGlobal_py, getBodyPositionGlobal_py_overloads())
.def("getBodyVelocityGlobal", &VpModel::getBodyVelocityGlobal_py, getBodyVelocityGlobal_py_overloads())
.def("getBodyAccelerationGlobal", &VpModel::getBodyAccelerationGlobal_py, getBodyAccelerationGlobal_py_overloads())
.def("getBodyAngVelocityGlobal", &VpModel::getBodyAngVelocityGlobal)
.def("getBodyAngAccelerationGlobal", &VpModel::getBodyAngAccelerationGlobal)
.def("getBodyOrientationGlobal", &VpModel::getBodyOrientationGlobal)
.def("getBodyFrame", &VpModel::getBodyFrame)
.def("getBodyPositionsGlobal", &VpModel::getBodyPositionsGlobal)
.def("getBodyVelocitiesGlobal", &VpModel::getBodyVelocitiesGlobal)
.def("getBodyAccelerationsGlobal", &VpModel::getBodyAccelerationsGlobal)
.def("getBodyAngVelocitiesGlobal", &VpModel::getBodyAngVelocitiesGlobal)
.def("getBodyAngAccelerationsGlobal", &VpModel::getBodyAngAccelerationsGlobal)
.def("getBodyOrientationsGlobal", &VpModel::getBodyOrientationsGlobal)
.def("getBodyTransformGlobal", &VpModel::getBodyTransformGlobal)
.def("setBodyPositionGlobal", &VpModel::setBodyPositionGlobal_py)
.def("setBodyVelocityGlobal", &VpModel::setBodyVelocityGlobal_py)
.def("setBodyAccelerationGlobal", &VpModel::setBodyAccelerationGlobal_py)
.def("setBodyAngVelocityGlobal", &VpModel::setBodyAngVelocityGlobal)
.def("setBodyAngAccelerationGlobal", &VpModel::setBodyAngAccelerationGlobal)
.def("translateByOffset", &VpModel::translateByOffset)
.def("rotate", &VpModel::rotate)
.def("SetGround", &VpModel::SetGround)
.def("SetBodyColor", &VpModel::SetBodyColor)
.def("vpid2index", &VpModel::vpid2index)
;
class_<VpMotionModel, bases<VpModel> >("VpMotionModel", init<VpWorld*, object, object>())
.def("update", &VpMotionModel::update)
.def("recordVelByFiniteDiff", &VpMotionModel::recordVelByFiniteDiff, VpMotionModel_recordVelByFiniteDiff_overloads())
;
class_<VpControlModel, bases<VpModel> >("VpControlModel", init<VpWorld*, object, object>())
.def("__str__", &VpControlModel::__str__)
.def("getJointNum", &VpControlModel::getJointNum)
.def("getInternalJointNum", &VpControlModel::getInternalJointNum)
.def("getDOFs", &VpControlModel::getDOFs)
.def("getInternalJointDOFs", &VpControlModel::getInternalJointDOFs)
.def("getTotalDOF", &VpControlModel::getTotalDOF)
.def("getTotalInternalJointDOF", &VpControlModel::getTotalInternalJointDOF)
.def("getJointDOFIndexes", &VpControlModel::getJointDOFIndexes)
.def("getJointDOFInternalIndexes", &VpControlModel::getJointDOFInternalIndexes)
.def("update", &VpControlModel::update)
.def("fixBody", &VpControlModel::fixBody)
.def("initializeHybridDynamics", &VpControlModel::initializeHybridDynamics, initializeHybridDynamics_overloads())
.def("initializeForwardDynamics", &VpControlModel::initializeForwardDynamics)
.def("setHybridDynamics", &VpControlModel::setHybridDynamics)
.def("solveHybridDynamics", &VpControlModel::solveHybridDynamics)
.def("solveForwardDynamics", &VpControlModel::solveForwardDynamics)
.def("solveInverseDynamics", &VpControlModel::solveInverseDynamics)
.def("set_q", &VpControlModel::set_q)
// .def("set_dq", &VpControlModel::set_dq)
.def("get_q", &VpControlModel::get_q)
.def("get_dq", &VpControlModel::get_dq)
.def("get_dq_nested", &VpControlModel::get_dq_nested)
.def("set_ddq", &VpControlModel::set_ddq)
.def("computeJacobian", &VpControlModel::computeJacobian)
.def("computeCom_J_dJdq", &VpControlModel::computeCom_J_dJdq)
.def("getDOFPositions", &VpControlModel::getDOFPositions)
.def("getDOFVelocities", &VpControlModel::getDOFVelocities)
.def("getDOFAccelerations", &VpControlModel::getDOFAccelerations)
.def("getDOFAxeses", &VpControlModel::getDOFAxeses)
.def("getDOFPositionsLocal", &VpControlModel::getDOFPositionsLocal)
.def("getDOFVelocitiesLocal", &VpControlModel::getDOFVelocitiesLocal)
.def("getDOFAccelerationsLocal", &VpControlModel::getDOFAccelerationsLocal)
.def("getDOFAxesesLocal", &VpControlModel::getDOFAxesesLocal)
.def("getBodyRootDOFVelocitiesLocal", &VpControlModel::getBodyRootDOFVelocitiesLocal)
.def("getBodyRootDOFAccelerationsLocal", &VpControlModel::getBodyRootDOFAccelerationsLocal)
.def("getBodyRootDOFAxeses", &VpControlModel::getBodyRootDOFAxeses)
.def("setDOFVelocities", &VpControlModel::setDOFVelocities)
.def("setDOFAccelerations", &VpControlModel::setDOFAccelerations)
.def("setDOFTorques", &VpControlModel::setDOFTorques)
.def("getJointOrientationLocal", &VpControlModel::getJointOrientationLocal)
.def("getJointAngVelocityLocal", &VpControlModel::getJointAngVelocityLocal)
.def("getJointAngAccelerationLocal", &VpControlModel::getJointAngAccelerationLocal)
.def("getLocalJacobian", &VpControlModel::getLocalJacobian)
.def("getLocalJointVelocity", &VpControlModel::getLocalJointVelocity)
.def("getLocalJointDisplacementDerivatives", &VpControlModel::getLocalJointDisplacementDerivatives)
.def("getJointTransform", &VpControlModel::getJointTransform)
.def("getJointAfterTransformGlobal", &VpControlModel::getJointAfterTransformGlobal)
.def("getJointPositionGlobal", &VpControlModel::getJointPositionGlobal, getJointPositionGlobal_py_overloads())
// .def("getJointPositionGlobal", &VpControlModel::getJointPositionGlobal)
.def("getJointVelocityGlobal", &VpControlModel::getJointVelocityGlobal)
.def("getJointAccelerationGlobal", &VpControlModel::getJointAccelerationGlobal)
.def("getJointOrientationGlobal", &VpControlModel::getJointOrientationGlobal)
.def("getJointAngVelocityGlobal", &VpControlModel::getJointAngVelocityGlobal)
.def("getJointAngAccelerationGlobal", &VpControlModel::getJointAngAccelerationGlobal)
.def("getJointOrientationsLocal", &VpControlModel::getJointOrientationsLocal)
.def("getJointAngVelocitiesLocal", &VpControlModel::getJointAngVelocitiesLocal)
.def("getJointAngAccelerationsLocal", &VpControlModel::getJointAngAccelerationsLocal)
.def("getJointPositionsGlobal", &VpControlModel::getJointPositionsGlobal)
.def("getJointVelocitiesGlobal", &VpControlModel::getJointVelocitiesGlobal)
.def("getJointAccelerationsGlobal", &VpControlModel::getJointAccelerationsGlobal)
.def("getJointOrientationsGlobal", &VpControlModel::getJointOrientationsGlobal)
.def("getJointAngVelocitiesGlobal", &VpControlModel::getJointAngVelocitiesGlobal)
.def("getJointAngAccelerationsGlobal", &VpControlModel::getJointAngAccelerationsGlobal)
.def("getInternalJointOrientationsLocal", &VpControlModel::getInternalJointOrientationsLocal)
.def("getInternalJointAngVelocitiesLocal", &VpControlModel::getInternalJointAngVelocitiesLocal)
.def("getInternalJointAngAccelerationsLocal", &VpControlModel::getInternalJointAngAccelerationsLocal)
.def("getInternalJointPositionsGlobal", &VpControlModel::getInternalJointPositionsGlobal)
.def("getInternalJointOrientationsGlobal", &VpControlModel::getInternalJointOrientationsGlobal)
.def("setJointAngVelocityLocal", &VpControlModel::setJointAngVelocityLocal)
.def("setJointAngAccelerationLocal", &VpControlModel::setJointAngAccelerationLocal)
.def("setJointAccelerationGlobal", &VpControlModel::setJointAccelerationGlobal)
.def("setJointAngAccelerationGlobal", &VpControlModel::setJointAngAccelerationGlobal)
.def("setJointAngAccelerationsLocal", &VpControlModel::setJointAngAccelerationsLocal)
.def("setInternalJointAngAccelerationsLocal", &VpControlModel::setInternalJointAngAccelerationsLocal)
.def("applyBodyGenForceGlobal", &VpControlModel::applyBodyGenForceGlobal, VpControlModel_applyBodyGenForceGlobal_overloads())
.def("applyBodyForceGlobal", &VpControlModel::applyBodyForceGlobal, VpControlModel_applyBodyForceGlobal_overloads())
.def("applyBodyTorqueGlobal", &VpControlModel::applyBodyTorqueGlobal)
.def("getBodyForceLocal", &VpControlModel::getBodyForceLocal)
.def("getBodyNetForceLocal", &VpControlModel::getBodyNetForceLocal)
.def("getBodyGravityForceLocal", &VpControlModel::getBodyGravityForceLocal)
.def("SetJointElasticity", &VpControlModel::SetJointElasticity, VpControlModel_SetJointElasticity_overloads())
.def("SetJointsElasticity", &VpControlModel::SetJointsElasticity, VpControlModel_SetJointsElasticity_overloads())
.def("SetJointDamping", &VpControlModel::SetJointDamping, VpControlModel_SetJointDamping_overloads())
.def("SetJointsDamping", &VpControlModel::SetJointsDamping, VpControlModel_SetJointsDamping_overloads())
.def("getJointTorqueLocal", &VpControlModel::getJointTorqueLocal)
.def("getInternalJointTorquesLocal", &VpControlModel::getInternalJointTorquesLocal)
.def("setJointTorqueLocal", &VpControlModel::setJointTorqueLocal)
.def("setInternalJointTorquesLocal", &VpControlModel::setInternalJointTorquesLocal)
.def("setSpring", &VpControlModel::setSpring)
.def("getInverseEquationOfMotion", &VpControlModel::getInverseEquationOfMotion)
.def("getEquationOfMotion", &VpControlModel::getEquationOfMotion)
.def("stepKinematics", &VpControlModel::stepKinematics)
;
}
/*
static SE3 skewVec3(const Vec3 &v)
{
return SE3(0., v[2], -v[1], -v[2], 0., v[0], v[1], -v[0], 0.);
}
static SE3 skewVec3(const Axis &v)
{
return SE3(0., v[2], -v[1], -v[2], 0., v[0], v[1], -v[0], 0.);
}
//*/
VpModel::VpModel( VpWorld* pWorld, const object& createPosture, const object& config )
{
if(pWorld != nullptr)
{
_config = config;
_skeleton = createPosture.attr("skeleton");
_pWorld = &pWorld->_world;
int num = XI(createPosture.attr("skeleton").attr("getJointNum")());
_nodes.resize(num, NULL);
_boneTs.resize(num, SE3());
createBodies(createPosture);
build_name2index();
}
}
VpModel::~VpModel()
{
for( NODES_ITOR it=_nodes.begin(); it!=_nodes.end(); ++it)
if(*it)
delete *it;
}
void VpModel::SetGround(int index, bool flag)
{
_nodes[index]->body.SetGround(flag);
}
void VpModel::createBodies( const object& posture )
{
object joint = posture.attr("skeleton").attr("root");
object rootPos = posture.attr("rootPos");
SE3 T = SE3(pyVec3_2_Vec3(rootPos));
object tpose = posture.attr("getTPose")();
_createBody(joint, T, tpose);
}
void VpModel::_createBody( const object& joint, const SE3& parentT, const object& posture )
{
int len_joint_children = len(joint.attr("children"));
if (len_joint_children == 0 )
return;
SE3 T = parentT;
SE3 P = SE3(pyVec3_2_Vec3(joint.attr("offset")));
T = T * P;
string joint_name = XS(joint.attr("name"));
// int joint_index = XI(posture.attr("skeleton").attr("getElementIndex")(joint_name));
// SE3 R = pySO3_2_SE3(posture.attr("getLocalR")(joint_index));
int joint_index = XI(posture.attr("skeleton").attr("getJointIndex")(joint_name));
SE3 R = pySO3_2_SE3(posture.attr("getJointOrientationLocal")(joint_index));
T = T * R;
// if (len_joint_children > 0 && _config.attr("hasNode")(joint_name))
if (_config.attr("hasNode")(joint_name))
{
Vec3 offset(0);
object cfgNode = _config.attr("getNode")(joint_name);
object bone_dir_child = cfgNode.attr("bone_dir_child");
if (!bone_dir_child.is_none())
{
string bone_dir_child_name = XS(cfgNode.attr("bone_dir_child"));
int child_joint_index = XI(posture.attr("skeleton").attr("getJointIndex")(bone_dir_child_name));
offset += pyVec3_2_Vec3(posture.attr("skeleton").attr("getJoint")(child_joint_index).attr("offset"));
// std::cout << joint_name << " " << offset <<std::endl;
}
else
{
for( int i=0 ; i<len_joint_children; ++i)
offset += pyVec3_2_Vec3(joint.attr("children")[i].attr("offset"));
offset *= (1./len_joint_children);
}
SE3 boneT(offset*.5);
Vec3 defaultBoneV(0,0,1);
SE3 boneR = getSE3FromVectors(defaultBoneV, offset);
boneT = boneT * boneR;
Node* pNode = new Node(joint_name);
_nodes[joint_index] = pNode;
_nodes[joint_index]->offset_from_parent = pyVec3_2_Vec3(joint.attr("offset"));
///*
int numGeom = len(cfgNode.attr("geoms"));
if (numGeom != 0)
{
for (int i=0; i<numGeom; i++)
{
string geomType = XS(cfgNode.attr("geoms")[i]);
if (0 == geomType.compare("MyFoot3") || 0 == geomType.compare("MyFoot4")
|| 0 == geomType.compare("MyFoot5") || 0 == geomType.compare("MyFoot6"))
{
scalar density = XD(cfgNode.attr("geomMaterial")[i].attr("density"));
scalar radius = XD(cfgNode.attr("geomMaterial")[i].attr("radius"));
scalar height = XD(cfgNode.attr("geomMaterial")[i].attr("height"));
if (height <= 0.)
height = Norm(offset) + 2*radius;
// vpMaterial *pMaterial = new vpMaterial();
// pMaterial->SetDensity(density);
// pNode->body.SetMaterial(pMaterial);
pNode->material.SetDensity(density);
pNode->body.SetMaterial(&(pNode->material));
SE3 geomT;
geomT.SetEye();
if(cfgNode.attr("geomTs")[i])
{
geomT = pySO3_2_SE3(cfgNode.attr("geomTs")[i][1]);
// geomT.SetPosition(geomT*pyVec3_2_Vec3(cfgNode.attr("geomTs")[i][0]));
geomT.SetPosition(pyVec3_2_Vec3(cfgNode.attr("geomTs")[i][0]));
}
else
std::cout << "there is no geom Ts!" << std::endl;
if (0 == geomType.compare("MyFoot3"))
pNode->body.AddGeometry(new MyFoot3(radius, height), geomT);
else if(0 == geomType.compare("MyFoot4"))
pNode->body.AddGeometry(new MyFoot4(radius, height), geomT);
else if(0 == geomType.compare("MyFoot6"))
pNode->body.AddGeometry(new MyFoot6(radius, height), geomT);
else
pNode->body.AddGeometry(new MyFoot5(radius, height), geomT);
}
else
{
scalar density = XD(cfgNode.attr("geomMaterial")[i].attr("density"));
scalar width = XD(cfgNode.attr("geomMaterial")[i].attr("width"));
scalar length = XD(cfgNode.attr("geomMaterial")[i].attr("length"));
scalar height = XD(cfgNode.attr("geomMaterial")[i].attr("height"));
// vpMaterial *pMaterial = new vpMaterial();
// pMaterial->SetDensity(density);
// pNode->body.SetMaterial(pMaterial);
pNode->material.SetDensity(density);
pNode->body.SetMaterial(&(pNode->material));
SE3 geomT;
geomT.SetEye();
if(cfgNode.attr("geomTs")[i])
{
geomT = pySO3_2_SE3(cfgNode.attr("geomTs")[i][1]);
geomT.SetPosition(pyVec3_2_Vec3(cfgNode.attr("geomTs")[i][0]));
}
pNode->body.AddGeometry(new vpBox(Vec3(width, height, length)), geomT);
}
}
}
else
{
//*/
///*
string geomType = XS(cfgNode.attr("geom"));
if (0 == geomType.compare("MyFoot3") || 0 == geomType.compare("MyFoot4")
|| 0 == geomType.compare("MyFoot5")|| 0 == geomType.compare("MyFoot6"))
{
scalar radius = .05;
object width_object = cfgNode.attr("width");
if( !width_object.is_none() )
radius = XD(cfgNode.attr("width"));
scalar length = Norm(offset) + 2*radius;
scalar density = XD(cfgNode.attr("density"));
scalar mass = 1.;
object mass_object = cfgNode.attr("mass");
if( !mass_object.is_none() )
{
mass = XD(cfgNode.attr("mass"));
density = mass/ (radius * radius * M_PI * length);
}
else
mass = density * radius * radius * M_PI * length;
// density = mass/ (width*width*M_PI*(length+width));
if (0 == geomType.compare("MyFoot3"))
pNode->body.AddGeometry(new MyFoot3(radius, length));
else if(0 == geomType.compare("MyFoot4"))
pNode->body.AddGeometry(new MyFoot4(radius, length));
else if(0 == geomType.compare("MyFoot6"))
pNode->body.AddGeometry(new MyFoot6(radius, length));
else
pNode->body.AddGeometry(new MyFoot5(radius, length));
pNode->body.SetInertia(CylinderInertia(density, radius, length));
}
else
{
object mass_object = cfgNode.attr("mass");
object length_object = cfgNode.attr("length");
object width_object = cfgNode.attr("width");
object height_object = cfgNode.attr("height");
scalar length;
if( !length_object.is_none() )
length = XD(cfgNode.attr("length")) * XD(cfgNode.attr("boneRatio"));
else
length = Norm(offset) * XD(cfgNode.attr("boneRatio"));
scalar density = XD(cfgNode.attr("density"));
scalar width, height;
if( !width_object.is_none() )
{
width = XD(cfgNode.attr("width"));
if( !mass_object.is_none() )
height = (XD(cfgNode.attr("mass")) / (density * length)) / width;
else if ( !height_object.is_none())
height = XD(cfgNode.attr("height"));
else
height = .1;
}
else
{
if( !mass_object.is_none() )
{
if ( !height_object.is_none())
{
height = XD(cfgNode.attr("height"));
width = (XD(cfgNode.attr("mass")) / (density * length)) / height;
}
else
{
width = sqrt( (XD(cfgNode.attr("mass")) / (density * length)) );
height = width;
}
}
else
{
if ( !height_object.is_none())
{
height = XD(cfgNode.attr("height"));
width = height;
}
else
{
width = .1;
height = width;
}
}
}
string geomType = XS(cfgNode.attr("geom"));
if(0 == geomType.compare("MyBox"))
pNode->body.AddGeometry(new MyBox(Vec3(width, height, length)));
else if(0 == geomType.compare("MyFoot1"))
pNode->body.AddGeometry(new MyFoot1(Vec3(width, height, length)));
else if(0 == geomType.compare("MyFoot2"))
pNode->body.AddGeometry(new MyFoot2(Vec3(width, height, length)));
// else if(geomType == "MyShin")
// pNode->body.AddGeometry(new MyShin(Vec3(width, height, length)));
else
{
pNode->body.AddGeometry(new vpBox(Vec3(width, height, length)));
cout << geomType << " : undefined geom type!" << endl;
}
// pNode->body.AddGeometry(new vpBox(Vec3(width, height, length)));
pNode->body.SetInertia(BoxInertia(density, Vec3(width/2.,height/2.,length/2.)));
//*/
}
}
// pNode->body.SetInertia(BoxInertia(density, Vec3(width,height,length)));
//pNode->body.SetInertia(BoxInertia(density, Vec3(width/2.,height/2.,length/2.)));
boneT = boneT * SE3(pyVec3_2_Vec3(cfgNode.attr("offset")));
object parent_object = joint.attr("parent");
if(parent_object.is_none())
boneT=SE3();
_boneTs[joint_index] = boneT;
SE3 newT = T * boneT;
// if (joint.attr("parent") == object())
// pNode->body.SetFrame(T);
// else
pNode->body.SetFrame(newT);
_id2index[pNode->body.GetID()] = joint_index;
}
for( int i=0 ; i<len_joint_children; ++i)
_createBody(joint.attr("children")[i], T, posture);
}
//int VpModel::getParentIndex( int index )
//{
// object parent = _skeleton.attr("getParentJointIndex")(index);
// if(parent==object())
// return -1;
// else
// return XI(parent);
//}
std::string VpModel::__str__()
{
stringstream ss;
// ss << "<NODES>" << endl;
// for(int i=0; i<_nodes.size(); ++i)
// {
// ss << "[" << i << "]:";
//// if(_nodes[i]==NULL)
//// ss << "NULL, ";
//// else
// ss << _nodes[i]->name << ", ";
// }
// ss << endl;
//
// ss << "<BODIES INDEX:(NODE INDEX) NODE NAME>\n";
// for(int i=0; i<_bodyElementIndexes.size(); ++i)
// ss << "[" << i << "]:(" << _bodyElementIndexes[i] << ") " << _nodes[_bodyElementIndexes[i]]->name << ", ";
// ss << endl;
ss << "<BODIES (,JOINTS)>" << endl;
for(std::vector<int>::size_type i=0; i<_nodes.size(); ++i)
ss << "[" << i << "]:" << _nodes[i]->name << ", ";
ss << endl;
ss << "<BODY MASSES>" << endl;
for(std::vector<int>::size_type i=0; i<_nodes.size(); ++i)
// if(_nodes[i])
ss << "[" << i << "]:" << _nodes[i]->body.GetInertia().GetMass() << ", ";
ss << endl;
// ss << "<BODY INERTIAS>" << endl;
// ss << "I11 I22 I33 I12 I13 I23 offset.x offset.y offset.z mass" << endl;
// for(int i=0; i<_nodes.size(); ++i)
// if(_nodes[i])
// {
// ss << "[" << i << "]:";
// for(int j=0; j<10; ++j)
// ss << _nodes[i]->body.GetInertia()[j] << " ";
// ss << endl;
// }
// ss << endl;
return ss.str();
}
bp::list VpModel::getBodyMasses()
{
bp::list ls;
for(std::vector<int>::size_type i=0; i<_nodes.size(); ++i)
ls.append(_nodes[i]->body.GetInertia().GetMass());
return ls;
}
scalar VpModel::getTotalMass()
{
scalar mass = 0.;
for(std::vector<int>::size_type i=0; i<_nodes.size(); ++i)
mass += _nodes[i]->body.GetInertia().GetMass();
return mass;
}
int VpModel::getBodyGeomNum(int index)
{
return _nodes[index]->body.GetNumGeometry();
}
bp::list VpModel::getBodyGeomsType(int index)
{
char type;
scalar data[3];
bp::list ls;
for(int i=0; i<_nodes[index]->body.GetNumGeometry(); ++i)
{
_nodes[index]->body.GetGeometry(i)->GetShape(&type, data);
ls.append(type);
}
return ls;
}
bp::list VpModel::getBodyGeomsSize(int index)
{
char type;
scalar data[3];
bp::list ls;
for(int i=0; i<_nodes[index]->body.GetNumGeometry(); ++i)
{
ndarray O = np::array(bp::make_tuple(0.,0.,0.));
_nodes[index]->body.GetGeometry(i)->GetShape(&type, data);
object pyV = O.copy();
pyV[0] = data[0];
pyV[1] = data[1];
pyV[2] = data[2];
ls.append(pyV);
}
return ls;
}
bp::list VpModel::getBodyGeomsLocalFrame(int index)
{
bp::list ls;
for(int i=0; i<_nodes[index]->body.GetNumGeometry(); ++i)
{
ndarray O = np::array(bp::make_tuple(
bp::make_tuple(0.,0.,0.,0.),
bp::make_tuple(0.,0.,0.,0.),
bp::make_tuple(0.,0.,0.,0.),
bp::make_tuple(0.,0.,0.,1.)
)
);
const SE3& geomFrame = _nodes[index]->body.GetGeometry(i)->GetLocalFrame();
object pyT = O.copy();
for(int j=0; j<12; j++)
pyT[bp::make_tuple(j%3, j/3)] = geomFrame[j];
ls.append(pyT);
}
return ls;
}
bp::list VpModel::getBodyGeomsGlobalFrame(int index)
{
bp::list ls;
for(int i=0; i<_nodes[index]->body.GetNumGeometry(); ++i)
{
ndarray O = np::array(bp::make_tuple(
bp::make_tuple(0.,0.,0.,0.),
bp::make_tuple(0.,0.,0.,0.),
bp::make_tuple(0.,0.,0.,0.),
bp::make_tuple(0.,0.,0.,1.)
)
);
const SE3& geomFrame = _nodes[index]->body.GetGeometry(i)->GetGlobalFrame();
object pyT = O.copy();
for(int j=0; j<12; j++)
pyT[bp::make_tuple(j%3, j/3)] = geomFrame[j];
ls.append(pyT);
}
return ls;
}
object VpModel::getBodyShape(int index)
{
ndarray O = np::array(bp::make_tuple(0.,0.,0.));
char type;
scalar data[3];
_nodes[index]->body.GetGeometry(0)->GetShape(&type, data);
object pyV = O.copy();
pyV[0] = data[0];
pyV[1] = data[1];
pyV[2] = data[2];
return pyV;
}
bp::list VpModel::getBodyVerticesPositionGlobal(int index)
{
ndarray O = np::array(bp::make_tuple(0.,0.,0.));
const vpGeom *pGeom;
char type;
scalar data[3];
bp::list ls_point;
pGeom = _nodes[index]->body.GetGeometry(0);
pGeom->GetShape(&type, data);
const SE3& geomFrame = pGeom->GetGlobalFrame();
Vec3 point;
for( int p=0; p<8; ++p)
{
point[0] = (p & MAX_X) ? data[0]/2. : -data[0]/2.;
point[1] = (p & MAX_Y) ? data[1]/2. : -data[1]/2.;
point[2] = (p & MAX_Z) ? data[2]/2. : -data[2]/2.;
point = geomFrame * point;
object pyV = O.copy();
Vec3_2_pyVec3(point, pyV);
ls_point.append(pyV);
}
return ls_point;
}
//bp::list VpModel::getBodyPoints()
//{
// bp::list ls;
// char type;
// scalar data[3];
//
// const vpGeom *pGeom;
//
// for(int i=0; i<_nodes.size(); ++i)
// if(_nodes[i])
// {
// bp::list ls_point;
// for( int j=0; j<_nodes[i]->body.GetNumGeometry(); ++j)
// {
// pGeom = _nodes[i]->body.GetGeometry(j);
// pGeom->GetShape(&type, data);
// const SE3& geomFrame = pGeom->GetGlobalFrame();
//
// Vec3 point;
// for( int p=0; p<8; ++p)
// {
// point[0] = (p & MAX_X) ? data[0]/2. : -data[0]/2.;
// point[1] = (p & MAX_Y) ? data[1]/2. : -data[1]/2.;
// point[2] = (p & MAX_Z) ? data[2]/2. : -data[2]/2.;
// point = geomFrame * point;
//
// object pyV = _O_Vec3->copy();
// Vec3_2_pyVec3(point, pyV);
// ls_point.append(pyV);
// }
// }
// ls.append(ls_point);
// }
// return ls;
//}
//bp::list VpModel::getBodyShapes()
//{
// bp::list ls;
// char type;
// scalar data[3];
//
// for(int i=0; i<_nodes.size(); ++i)
// if(_nodes[i])
// {
// bp::list ls_geom;
// for( int j=0; j<_nodes[i]->body.GetNumGeometry(); ++j)
// {
// _nodes[i]->body.GetGeometry(j)->GetShape(&type, data);
// ls_geom.append(bp::make_tuple(data[0], data[1], data[2]));
// }
// ls.append(ls_geom);
// }
// return ls;
//}
void VpModel::getBodyInertiaLocal(int index, SE3& Tin)
{
// if(!_nodes[index]) return;
// ss << "I11 I22 I33 I12 I13 I23 offset.x offset.y offset.z mass" << endl;
// pyIn[bp::make_tuple(0,0)] = in[0];
// pyIn[bp::make_tuple(1,1)] = in[1];
// pyIn[bp::make_tuple(2,2)] = in[2];
// pyIn[bp::make_tuple(0,1)] = pyIn[bp::make_tuple(1,0)] = in[3];
// pyIn[bp::make_tuple(0,2)] = pyIn[bp::make_tuple(2,0)] = in[4];
// pyIn[bp::make_tuple(1,2)] = pyIn[bp::make_tuple(2,1)] = in[5];
// | T[0] T[3] T[6] T[ 9] |
// | T[1] T[4] T[7] T[10] |
// | T[2] T[5] T[8] T[11] |
const Inertia& in = _nodes[index]->body.GetInertia();
Tin[0] = in[0];
Tin[4] = in[1];
Tin[8] = in[2];
Tin[3] = Tin[1] = in[3];
Tin[6] = Tin[2] = in[4];
Tin[7] = Tin[5] = in[5];
}
boost::python::object VpModel::getBodyInertiaLocal_py( int index )
{
ndarray I = np::array( bp::make_tuple(bp::make_tuple(1.,0.,0.), bp::make_tuple(0.,1.,0.), bp::make_tuple(0.,0.,1.)) );
SE3 Tin;
object pyIn = I.copy();
getBodyInertiaLocal(index, Tin);
SE3_2_pySO3(Tin, pyIn);
return pyIn;
}
boost::python::object VpModel::getBodyInertiaGlobal_py( int index )
{
ndarray I = np::array( bp::make_tuple(bp::make_tuple(1.,0.,0.), bp::make_tuple(0.,1.,0.), bp::make_tuple(0.,0.,1.)) );
SE3 Tin_local, bodyFrame;
object pyIn = I.copy();
getBodyInertiaLocal(index, Tin_local);
bodyFrame = _nodes[index]->body.GetFrame() * SE3(_nodes[index]->body.GetCenterOfMass());
SE3_2_pySO3(bodyFrame * Tin_local * Inv(bodyFrame), pyIn);
return pyIn;
}
bp::list VpModel::getBodyInertiasLocal()
{
bp::list ls;
for(std::vector<int>::size_type i=0; i<_nodes.size(); ++i)
ls.append(getBodyInertiaLocal_py(i));
return ls;
}
bp::list VpModel::getBodyInertiasGlobal()
{
bp::list ls;
for(std::vector<int>::size_type i=0; i<_nodes.size(); ++i)
ls.append(getBodyInertiaGlobal_py(i));
return ls;
}
object VpModel::getCOM()
{
object pyV;
make_pyVec3(pyV);
Vec3 com(0., 0., 0.);
for(std::vector<int>::size_type i=0; i<_nodes.size(); ++i)
com += _nodes[i]->body.GetInertia().GetMass() * _nodes[i]->body.GetFrame().GetPosition();
com *= 1./getTotalMass();
Vec3_2_pyVec3(com, pyV);
return pyV;
}
bp::list VpModel::getBoneT(int index)
{
bp::list ls;
ndarray I = np::array( bp::make_tuple(bp::make_tuple(1.,0.,0.), bp::make_tuple(0.,1.,0.), bp::make_tuple(0.,0.,1.)) );
ndarray O = np::array(bp::make_tuple(0.,0.,0.));
SE3_2_pySO3(_boneTs[index], I);
Vec3_2_pyVec3(_boneTs[index].GetPosition(), O);
ls.append(I);
ls.append(O);
return ls;
}
bp::list VpModel::getInvBoneT(int index)
{
bp::list ls;
ndarray I = np::array( bp::make_tuple(bp::make_tuple(1.,0.,0.), bp::make_tuple(0.,1.,0.), bp::make_tuple(0.,0.,1.)) );
ndarray O = np::array(bp::make_tuple(0.,0.,0.));
SE3 invBoneT = Inv(_boneTs[index]);
SE3_2_pySO3(invBoneT, I);
Vec3_2_pyVec3(invBoneT.GetPosition(), O);
ls.append(I);
ls.append(O);
return ls;
}
object VpModel::getBodyGenVelLocal(int index)
{
ndarray O = np::array( bp::make_tuple(0., 0., 0., 0.,0.,0.) );
object pyV = O.copy();
se3_2_pyVec6(_nodes[index]->body.GetGenVelocityLocal(), pyV);
return pyV;
}
object VpModel::getBodyGenVelGlobal(int index)
{
ndarray O = np::array( bp::make_tuple(0., 0., 0., 0.,0.,0.) );
object pyV = O.copy();
se3_2_pyVec6(_nodes[index]->body.GetGenVelocity(), pyV);
return pyV;
}
object VpModel::getBodyGenAccLocal(int index)
{
ndarray O = np::array( bp::make_tuple(0., 0., 0., 0.,0.,0.) );
object pyV = O.copy();
se3_2_pyVec6(_nodes[index]->body.GetGenAccelerationLocal(), pyV);
return pyV;
}
object VpModel::getBodyGenAccGlobal(int index)
{
ndarray O = np::array( bp::make_tuple(0., 0., 0., 0.,0.,0.) );
object pyV = O.copy();
se3_2_pyVec6(_nodes[index]->body.GetGenAcceleration(), pyV);
return pyV;
}
object VpModel::getBodyPositionGlobal_py( int index, const object& positionLocal/*=object() */ )
{
ndarray O = np::array(bp::make_tuple(0.,0.,0.));
object pyV = O.copy();
Vec3 positionLocal_;
if(positionLocal.is_none())
Vec3_2_pyVec3(getBodyPositionGlobal(index), pyV);
else
{
pyVec3_2_Vec3(positionLocal, positionLocal_);
Vec3_2_pyVec3(getBodyPositionGlobal(index, &positionLocal_), pyV);
}
return pyV;
}
object VpModel::getBodyVelocityGlobal_py( int index, const object& positionLocal/*=object() */ )
{
ndarray O = np::array(bp::make_tuple(0.,0.,0.));
object pyV = O.copy();
Vec3 positionLocal_;
if(positionLocal.is_none())
Vec3_2_pyVec3(getBodyVelocityGlobal(index), pyV);
else
{
pyVec3_2_Vec3(positionLocal, positionLocal_);
Vec3_2_pyVec3(getBodyVelocityGlobal(index, positionLocal_), pyV);
}
return pyV;
}
bp::list VpModel::getBodyVelocitiesGlobal()
{
bp::list ls;
for(std::vector<int>::size_type i=0; i<_nodes.size(); ++i)
ls.append(getBodyVelocityGlobal_py(i));
return ls;
}
object VpModel::getBodyAngVelocityGlobal( int index )
{
se3 genVel;
ndarray O = np::array(bp::make_tuple(0.,0.,0.));
object pyV = O.copy();
genVel = _nodes[index]->body.GetGenVelocity();
pyV[0] = genVel[0];
pyV[1] = genVel[1];
pyV[2] = genVel[2];
return pyV;
}
bp::list VpModel::getBodyAngVelocitiesGlobal()
{
bp::list ls;
for(std::vector<int>::size_type i=0; i<_nodes.size(); ++i)
ls.append(getBodyAngVelocityGlobal(i));
return ls;
}
object VpModel::getBodyAccelerationGlobal_py(int index, const object& positionLocal )
{
se3 genAcc;
Vec3 positionLocal_;
ndarray O = np::array(bp::make_tuple(0.,0.,0.));
object pyV = O.copy();
if(positionLocal.is_none())
Vec3_2_pyVec3(getBodyAccelerationGlobal(index), pyV);
else
{
pyVec3_2_Vec3(positionLocal, positionLocal_);
Vec3_2_pyVec3(getBodyAccelerationGlobal(index, &positionLocal_), pyV);
}
return pyV;
}
object VpModel::getBodyOrientationGlobal(int index)
{
ndarray I = np::array(bp::make_tuple(bp::make_tuple(1., 0., 0.), bp::make_tuple(0., 1., 0.), bp::make_tuple(0., 0., 1.)));
SE3 bodyFrame;
object pyR = I.copy();
bodyFrame = _nodes[index]->body.GetFrame();
SE3_2_pySO3(bodyFrame, pyR);
return pyR;
}
object VpModel::getBodyTransformGlobal(int index)
{
ndarray I = np::array(bp::make_tuple(
bp::make_tuple(1., 0., 0., 0.),
bp::make_tuple(0., 1., 0., 0.),
bp::make_tuple(0., 0., 1., 0.),
bp::make_tuple(0., 0., 0., 1.)
));
SE3 bodyFrame;
object pyT = I.copy();
bodyFrame = _nodes[index]->body.GetFrame();
SE3_2_pySE3(bodyFrame, pyT);
return pyT;
}
bp::list VpModel::getBodyAccelerationsGlobal()
{
bp::list ls;
for(std::vector<int>::size_type i=0; i<_nodes.size(); ++i)
ls.append(getBodyAccelerationGlobal_py(i));
return ls;
}
void VpModel::setBodyPositionGlobal_py( int index, const object& pos )
{
Vec3 position;
pyVec3_2_Vec3(pos, position);
setBodyPositionGlobal(index, position);
}
object VpModel::getBodyFrame(int index)
{
object pyT;
make_pySE3(pyT);
SE3 bodyFrame = _nodes[index]->body.GetFrame();
SE3_2_pySE3(bodyFrame, pyT);
return pyT;
}
void VpModel::setBodyVelocityGlobal_py( int index, const object& vel )
{
se3 genVel;
genVel = _nodes[index]->body.GetGenVelocity();
genVel[3] = XD(vel[0]);
genVel[4] = XD(vel[1]);
genVel[5] = XD(vel[2]);
_nodes[index]->body.SetGenVelocity(genVel);
}
void VpModel::setBodyAccelerationGlobal_py( int index, const object& acc )
{
se3 genAcc;
genAcc = _nodes[index]->body.GetGenAcceleration();
genAcc[3] = XD(acc[0]);
genAcc[4] = XD(acc[1]);
genAcc[5] = XD(acc[2]);
_nodes[index]->body.SetGenAcceleration(genAcc);
}
void VpModel::setBodyAngVelocityGlobal( int index, const object& angvel )
{
se3 genVel;
genVel = _nodes[index]->body.GetGenVelocity();
genVel[0] = XD(angvel[0]);
genVel[1] = XD(angvel[1]);
genVel[2] = XD(angvel[2]);
_nodes[index]->body.SetGenVelocity(genVel);
}
void VpModel::setBodyAngAccelerationGlobal( int index, const object& angacc )
{
se3 genAcc;
genAcc = _nodes[index]->body.GetGenAcceleration();
genAcc[0] = XD(angacc[0]);
genAcc[1] = XD(angacc[1]);
genAcc[2] = XD(angacc[2]);
_nodes[index]->body.SetGenAcceleration(genAcc);
}
bp::list VpModel::getBodyPositionsGlobal()
{
bp::list ls;
for(std::vector<int>::size_type i=0; i<_nodes.size(); ++i)
ls.append(getBodyPositionGlobal_py(i));
return ls;
}
bp::list VpModel::getBodyOrientationsGlobal()
{
bp::list ls;
for(std::vector<int>::size_type i=0; i<_nodes.size(); ++i)
ls.append(getBodyOrientationGlobal(i));
return ls;
}
object VpModel::getBodyAngAccelerationGlobal( int index )
{
se3 genAcc;
ndarray O = np::array(bp::make_tuple(0.,0.,0.));
object pyV = O.copy();
genAcc = _nodes[index]->body.GetGenAcceleration();
pyV[0] = genAcc[0];
pyV[1] = genAcc[1];
pyV[2] = genAcc[2];
return pyV;
}
bp::list VpModel::getBodyAngAccelerationsGlobal()
{
bp::list ls;
for(std::vector<int>::size_type i=0; i<_nodes.size(); ++i)
ls.append(getBodyAngAccelerationGlobal(i));
return ls;
}
void VpModel::translateByOffset( const object& offset )
{
Vec3 v;
pyVec3_2_Vec3(offset, v);
for(std::vector<int>::size_type i=0; i<_nodes.size(); ++i)
setBodyPositionGlobal(i, getBodyPositionGlobal(i) + v);
}
void VpModel::rotate( const object& rotation )
{
SE3 R, bodyFrame;
pySO3_2_SE3(rotation, R);
bodyFrame = _nodes[0]->body.GetFrame();
_nodes[0]->body.SetFrame(bodyFrame * R);
// �ٲ� root body frame�� ���� joint�� ����� ������ body�� frame ������Ʈ. �̰��� ���� ������ root body �ϳ��� rotation�� ����ȴ�.
_pWorld->UpdateFrame();
}
void VpModel::ignoreCollisionWith( vpBody* pBody )
{
for(std::vector<int>::size_type i=0; i<_nodes.size(); ++i)
_pWorld->IgnoreCollision( &_nodes[i]->body, pBody );
}
void VpModel::ignoreCollisionWith_py( vpBody* pBody )
{
ignoreCollisionWith(pBody);
}
Vec3 VpModel::getBodyPositionGlobal( int index, const Vec3* pPositionLocal )
{
SE3 bodyFrame;
bodyFrame = _nodes[index]->body.GetFrame();
if(!pPositionLocal)
return bodyFrame.GetPosition();
else
return bodyFrame * (*pPositionLocal);
}
Vec3 VpModel::getBodyVelocityGlobal( int index, const Vec3& positionLocal)
{
return _nodes[index]->body.GetLinVelocity(positionLocal);
// static se3 genAccLocal, genAccGlobal;
// genAccLocal = _nodes[index]->body.GetGenVelocityLocal();
// genAccLocal = MinusLinearAd(positionLocal, genAccLocal);
// genAccGlobal = Rotate(_nodes[index]->body.GetFrame(), genAccLocal);
// return Vec3(genAccGlobal[3], genAccGlobal[4], genAccGlobal[5]);
}
Vec3 VpModel::getBodyAccelerationGlobal( int index, const Vec3* pPositionLocal)
{
se3 genAccLocal, genAccGlobal;
genAccLocal = _nodes[index]->body.GetGenAccelerationLocal();
if(pPositionLocal)
genAccLocal = MinusLinearAd(*pPositionLocal, genAccLocal);
genAccGlobal = Rotate(_nodes[index]->body.GetFrame(), genAccLocal);
return Vec3(genAccGlobal[3], genAccGlobal[4], genAccGlobal[5]);
}
void VpModel::setBodyPositionGlobal( int index, const Vec3& position )
{
SE3 bodyFrame;
bodyFrame = _nodes[index]->body.GetFrame();
bodyFrame.SetPosition(position);
_nodes[index]->body.SetFrame(bodyFrame);
}
void VpModel::setBodyVelocityGlobal( int index, const Vec3& vel, const Vec3* pPositionLocal)
{
// if(pPositionLocal)
// cout << "pPositionLocal : not implemented functionality yet" << endl;
se3 genVel;
genVel = _nodes[index]->body.GetGenVelocity();
genVel[3] = vel[0];
genVel[4] = vel[1];
genVel[5] = vel[2];
_nodes[index]->body.SetGenVelocity(genVel);
}
void VpModel::setBodyAccelerationGlobal( int index, const Vec3& acc, const Vec3* pPositionLocal)
{
// if(pPositionLocal)
// cout << "pPositionLocal : not implemented functionality yet" << endl;
se3 genAcc;
genAcc = _nodes[index]->body.GetGenAcceleration();
genAcc[3] = acc[0];
genAcc[4] = acc[1];
genAcc[5] = acc[2];
_nodes[index]->body.SetGenAcceleration(genAcc);
}
VpMotionModel::VpMotionModel( VpWorld* pWorld, const object& createPosture, const object& config )
:VpModel(pWorld, createPosture, config), _recordVelByFiniteDiff(false), _inverseMotionTimeStep(30.)
{
// OdeMotionModel�� node.body.disable()�� VpMotionModel������ pWorld->AddBody()��
// �� ���ִ� ������ �� ������ �ϵ��� �Ѵ�.
update(createPosture);
// addBody(false);
}
void VpMotionModel::update( const object& posture)
{
object joint = posture.attr("skeleton").attr("root");
object rootPos = posture.attr("rootPos");
SE3 T = SE3(pyVec3_2_Vec3(rootPos));
_updateBody(joint, T, posture);
}
void VpMotionModel::_updateBody( const object& joint, const SE3& parentT, const object& posture)
{
int len_joint_children = len(joint.attr("children"));
if (len_joint_children == 0 )
return;
SE3 T = parentT;
SE3 P = SE3(pyVec3_2_Vec3(joint.attr("offset")));
T = T * P;
string joint_name = XS(joint.attr("name"));
// int joint_index = XI(posture.attr("skeleton").attr("getElementIndex")(joint_name));
// SE3 R = pySO3_2_SE3(posture.attr("getLocalR")(joint_index));
int joint_index = XI(posture.attr("skeleton").attr("getJointIndex")(joint_name));
SE3 R = pySO3_2_SE3(posture.attr("getJointOrientationLocal")(joint_index));
T = T * R;
// int len_joint_children = len(joint.attr("children"));
// if (len_joint_children > 0 && _config.attr("hasNode")(joint_name))
if (_config.attr("hasNode")(joint_name))
{
SE3 boneT = _boneTs[joint_index];
SE3 newT = T * boneT;
Node* pNode = _nodes[joint_index];
if(_recordVelByFiniteDiff)
{
SE3 oldT, diffT;
oldT = pNode->body.GetFrame();
diffT = newT * Inv(oldT);
Vec3 p = newT.GetPosition() - oldT.GetPosition();
diffT.SetPosition(p);
pNode->body.SetGenVelocity(Log(diffT) * _inverseMotionTimeStep);
}
pNode->body.SetFrame(newT);
}
for( int i=0 ; i<len_joint_children; ++i)
_updateBody(joint.attr("children")[i], T, posture);
}
VpControlModel::VpControlModel( VpWorld* pWorld, const object& createPosture, const object& config )
:VpModel(pWorld, createPosture, config)
{
if(pWorld != nullptr)
{
addBodiesToWorld(createPosture);
ignoreCollisionBtwnBodies();
object tpose = createPosture.attr("getTPose")();
createJoints(tpose);
update(createPosture);
_nodes[0]->dof = 6;
m_total_dof = 0;
int dof_start_index = 0;
for(std::vector<int>::size_type i=0; i<_nodes.size(); i++)
{
_nodes[i]->dof_start_index = dof_start_index;
dof_start_index += _nodes[i]->dof;
m_total_dof += _nodes[i]->dof;
// for(std::vector<int>::size_type j=0; j<_nodes[i]->ancestors.size(); j++)
// std::cout << _nodes[i]->ancestors[j] << " ";
// std::cout << std::endl;
}
for(std::vector<int>::size_type body_idx=0; body_idx<_nodes.size(); body_idx++)
{
std::vector<int> &ancestors = _nodes[body_idx]->ancestors;
for(std::vector<int>::size_type j=0; j<_nodes.size(); j++)
{
if(std::find(ancestors.begin(), ancestors.end(), j) != ancestors.end())
{
_nodes[body_idx]->is_ancestor.push_back(true);
}
else
{
_nodes[body_idx]->is_ancestor.push_back(false);
}
}
}
// addBody(true);
}
}
std::string VpControlModel::__str__()
{
string s1 = VpModel::__str__();
stringstream ss;
ss << "<INTERNAL JOINTS>" << endl;
for(std::vector<int>::size_type i=1; i<_nodes.size(); ++i)
ss << "[" << i-1 << "]:" << _nodes[i]->name << ", ";
ss << endl;
return s1 + ss.str();
}
bp::list VpControlModel::getInternalJointDOFs()
{
bp::list ls;
for(std::vector<int>::size_type i=1; i<_nodes.size(); ++i)
{
ls.append(_nodes[i]->dof);
}
return ls;
}
int VpControlModel::getTotalInternalJointDOF()
{
int dof = 0;
for(std::vector<int>::size_type i=1; i<_nodes.size(); ++i)
dof += _nodes[i]->dof;
// dof += 3;
return dof;
}
bp::list VpControlModel::getDOFs()
{
bp::list ls;
ls.append(6);
for(std::vector<int>::size_type i=1; i<_nodes.size(); ++i)
{
ls.append(_nodes[i]->dof);
}
return ls;
}
int VpControlModel::getTotalDOF()
{
int dof = 0;
dof += 6;
for(std::vector<int>::size_type i=1; i<_nodes.size(); ++i)
dof += _nodes[i]->dof;
// dof += 3;
return dof;
}
bp::list VpControlModel::getJointDOFIndexes(int index)
{
bp::list ls;
int dof_index = _nodes[index]->dof_start_index;
for(int i=0; i<_nodes[index]->dof; i++)
ls.append(dof_index++);
return ls;
}
bp::list VpControlModel::getJointDOFInternalIndexes(int index)
{
assert(index > 0);
bp::list ls;
int dof_index = _nodes[index]->dof_start_index;
for(int i=0; i<_nodes[index]->dof; i++)
ls.append(dof_index++ - 6);
return ls;
}
void VpControlModel::createJoints( const object& posture )
{
object joint = posture.attr("skeleton").attr("root");
std::vector<int> empty;
_createJoint(joint, posture, empty);
}
void VpControlModel::_createJoint( const object& joint, const object& posture, const std::vector<int> &parent_ancestors)
{
int len_joint_children = len(joint.attr("children"));
if (len_joint_children == 0 )
return;
SE3 invLocalT;
object offset = joint.attr("offset");
SE3 P = SE3(pyVec3_2_Vec3(joint.attr("offset")));
string joint_name = XS(joint.attr("name"));
// int joint_index = XI(posture.attr("skeleton").attr("getElementIndex")(joint_name));
// SE3 R = pySO3_2_SE3(posture.attr("getLocalR")(joint_index));
int joint_index = XI(posture.attr("skeleton").attr("getJointIndex")(joint_name));
SE3 R = pySO3_2_SE3(posture.attr("getJointOrientationLocal")(joint_index));
// parent <---------> child
// link L1 L2 L3 L4
// L4_M = P1*R1 * P2*R2 * P3*R3 * P4*R4 (forward kinematics matrix of L4)
// ���� ��Ÿ�������� ����� while loop�� ��� ������ back tracking�� �����
// L4_M = Inv( Inv(R4)*Inv(P4) * Inv(R3)*Inv(P3) * ...)
// ���� �ڵ�����.
invLocalT = invLocalT * Inv(R);
invLocalT = invLocalT * Inv(P);
object temp_joint = joint;
object nodeExistParentJoint = object();
string temp_parent_name;
int temp_parent_index;
while(true)
{
object temp_parent_object = temp_joint.attr("parent");
if(temp_parent_object.is_none())
{
nodeExistParentJoint = object();
break;
}
else
{
temp_parent_name = XS(temp_joint.attr("parent").attr("name"));
// temp_parent_index = XI(posture.attr("skeleton").attr("getElementIndex")(temp_parent_name));
temp_parent_index = XI(posture.attr("skeleton").attr("getJointIndex")(temp_parent_name));
if(_nodes[temp_parent_index] != NULL)
{
nodeExistParentJoint = temp_joint.attr("parent");
break;
}
else
{
temp_joint = temp_joint.attr("parent");
object offset = temp_joint.attr("offset");
SE3 P = SE3(pyVec3_2_Vec3(offset));
string joint_name = XS(temp_joint.attr("name"));
object localSO3 = posture.attr("localRs")[joint_index];
SE3 R = pySO3_2_SE3(localSO3);
invLocalT = invLocalT * Inv(R);
invLocalT = invLocalT * Inv(P);
}
}
}
// int len_joint_children = len(joint.attr("children"));
// if ( nodeExistParentJoint!=object() && len_joint_children > 0 &&
// _config.attr("hasNode")(joint_name))
if ( !nodeExistParentJoint.is_none() && _config.attr("hasNode")(joint_name))
{
Node* pNode = _nodes[joint_index];
object cfgNode = _config.attr("getNode")(joint_name);
string parent_name = XS(nodeExistParentJoint.attr("name"));
// int parent_index = XI(posture.attr("skeleton").attr("getElementIndex")(parent_name));
int parent_index = XI(posture.attr("skeleton").attr("getJointIndex")(parent_name));
Node* pParentNode = _nodes[parent_index];
object parentCfgNode = _config.attr("getNode")(parent_name);
//object offset = cfgNode.attr("offset");
//SE3 offsetT = SE3(pyVec3_2_Vec3(offset));
//object parentOffset = parentCfgNode.attr("offset");
//SE3 parentOffsetT = SE3(pyVec3_2_Vec3(parentOffset));
if (0 == std::string(XS(cfgNode.attr("jointType"))).compare("B"))
{
pParentNode->body.SetJoint(&pNode->joint, Inv(_boneTs[parent_index])*Inv(invLocalT));
pNode->body.SetJoint(&pNode->joint, Inv(_boneTs[joint_index]));
}
else if (0 == std::string(XS(cfgNode.attr("jointType"))).compare("R"))
{
pParentNode->body.SetJoint(&pNode->joint_revolute, Inv(_boneTs[parent_index])*Inv(invLocalT));
pNode->body.SetJoint(&pNode->joint_revolute, Inv(_boneTs[joint_index]));
if (0 == std::string(XS(cfgNode.attr("jointAxes")[0])).compare("X"))
pNode->joint_revolute.SetAxis(Vec3(1., 0., 0.));
else if (0 == std::string(XS(cfgNode.attr("jointAxes")[0])).compare("Y"))
pNode->joint_revolute.SetAxis(Vec3(0., 1., 0.));
else if (0 == std::string(XS(cfgNode.attr("jointAxes")[0])).compare("Z"))
pNode->joint_revolute.SetAxis(Vec3(0., 0., 1.));
pNode->dof = 1;
}
else
std::cout << joint_name <<" " << std::string(XS(cfgNode.attr("jointType"))) << " is an unsupported joint type." << std::endl;
scalar kt = 16.;
scalar dt = 8.;
SpatialSpring el(kt);
SpatialDamper dam(dt);
//std::cout << el <<std::endl;
// pNode->joint.SetElasticity(el);
// pNode->joint.SetDamping(dam);
pNode->use_joint = true;
_nodes[joint_index]->parent_index = parent_index;
}
for (std::vector<int>::size_type i=0; i<parent_ancestors.size(); i++)
_nodes[joint_index]->ancestors.push_back(parent_ancestors[i]);
_nodes[joint_index]->ancestors.push_back(joint_index);
for( int i=0 ; i<len_joint_children; ++i)
_createJoint(joint.attr("children")[i], posture, _nodes[joint_index]->ancestors);
}
void VpControlModel::ignoreCollisionBtwnBodies()
{
for( VpModel::NODES_ITOR it=_nodes.begin(); it!=_nodes.end(); ++it)
{
for( VpModel::NODES_ITOR it2=_nodes.begin(); it2!=_nodes.end(); ++it2)
{
Node* pNode0 = *it;
Node* pNode1 = *it2;
// if(pNode0 && pNode1)
_pWorld->IgnoreCollision(&pNode0->body, &pNode1->body);
}
}
}
void VpControlModel::addBodiesToWorld( const object& createPosture )
{
// object joint = createPosture.attr("skeleton").attr("root");
// string root_name = XS(joint.attr("name"));
// int root_index = XI(createPosture.attr("skeleton").attr("getElementIndex")(root_name));
// vpBody* pRootBody = &_nodes[root_index]->body;
vpBody* pRootBody = &_nodes[0]->body;
_pWorld->AddBody(pRootBody);
}
void VpControlModel::update( const object& posture )
{
object joint = posture.attr("skeleton").attr("root");
_updateJoint(joint, posture);
}
void VpControlModel::_updateJoint( const object& joint, const object& posture )
{
int len_joint_children = len(joint.attr("children"));
if (len_joint_children == 0 )
return;
SE3 invLocalT;
SE3 P = SE3(pyVec3_2_Vec3(joint.attr("offset")));
string joint_name = XS(joint.attr("name"));
// int joint_index = XI(posture.attr("skeleton").attr("getElementIndex")(joint_name));
// SE3 R = pySO3_2_SE3(posture.attr("getLocalR")(joint_index));
int joint_index = XI(posture.attr("skeleton").attr("getJointIndex")(joint_name));
SE3 R = pySO3_2_SE3(posture.attr("getJointOrientationLocal")(joint_index));
// parent <---------> child
// link L1 L2 L3 L4
// L4_M = P1*R1 * P2*R2 * P3*R3 * P4*R4 (forward kinematics matrix of L4)
// ���� ��Ÿ�������� ����� while loop�� ��� ������ back tracking�� �����
// L4_M = Inv( Inv(R4)*Inv(P4) * Inv(R3)*Inv(P3) * ...)
// ���� �ڵ�����.
invLocalT = invLocalT * Inv(R);
invLocalT = invLocalT * Inv(P);
object temp_joint = joint;
object nodeExistParentJoint = object();
string temp_parent_name;
int temp_parent_index;
while(true)
{
object temp_parent_object = temp_joint.attr("parent");
if(temp_parent_object.is_none())
{
nodeExistParentJoint = object();
break;
}
else
{
temp_parent_name = XS(temp_joint.attr("parent").attr("name"));
// temp_parent_index = XI(posture.attr("skeleton").attr("getElementIndex")(temp_parent_name));
temp_parent_index = XI(posture.attr("skeleton").attr("getJointIndex")(temp_parent_name));
if(_nodes[temp_parent_index] != NULL)
{
nodeExistParentJoint = temp_joint.attr("parent");
break;
}
else
{
temp_joint = temp_joint.attr("parent");
object offset = temp_joint.attr("offset");
SE3 P = SE3(pyVec3_2_Vec3(offset));
string joint_name = XS(temp_joint.attr("name"));
object localSO3 = posture.attr("localRs")[joint_index];
SE3 R = pySO3_2_SE3(localSO3);
invLocalT = invLocalT * Inv(R);
invLocalT = invLocalT * Inv(P);
}
}
}
// int len_joint_children = len(joint.attr("children"));
// if(len_joint_children > 0 && _config.attr("hasNode")(joint_name))
if(_config.attr("hasNode")(joint_name))
{
Node* pNode = _nodes[joint_index];
if( !nodeExistParentJoint.is_none())
pNode->joint.SetOrientation(R);
else
// root�� ���� body�� ���� SetFrame() ���ش�.
pNode->body.SetFrame(SE3(pyVec3_2_Vec3(posture.attr("rootPos")))*P*R*_boneTs[joint_index]);
}
for( int i=0 ; i<len_joint_children; ++i)
_updateJoint(joint.attr("children")[i], posture);
}
void VpControlModel::fixBody( int index )
{
_nodes[index]->body.SetGround();
}
void VpControlModel::initializeHybridDynamics(bool floatingBase)
{
std::vector<int>::size_type rootIndex = 0;
for(std::vector<int>::size_type i=0; i<_nodes.size(); ++i)
{
if(i == rootIndex)
{
if(floatingBase)
_nodes[i]->body.SetHybridDynamicsType(VP::DYNAMIC);
else
_nodes[i]->body.SetHybridDynamicsType(VP::KINEMATIC);
}
else
_nodes[i]->joint.SetHybridDynamicsType(VP::KINEMATIC);
}
}
void VpControlModel::initializeForwardDynamics()
{
std::vector<int>::size_type rootIndex = 0;
for(std::vector<int>::size_type i=0; i<_nodes.size(); ++i)
{
_nodes[i]->body.SetHybridDynamicsType(VP::DYNAMIC);
if(i != rootIndex)
_nodes[i]->joint.SetHybridDynamicsType(VP::DYNAMIC);
}
}
void VpControlModel::setHybridDynamics(int jointIndex, std::string dynamicsType)
{
if(dynamicsType == "DYNAMIC")
{
_nodes[jointIndex]->body.SetHybridDynamicsType(VP::DYNAMIC);
_nodes[jointIndex]->joint.SetHybridDynamicsType(VP::DYNAMIC);
}
else if(dynamicsType == "KINEMATIC")
_nodes[jointIndex]->joint.SetHybridDynamicsType(VP::KINEMATIC);
}
void VpControlModel::solveHybridDynamics()
{
_nodes[0]->body.GetSystem()->HybridDynamics();
}
void VpControlModel::solveForwardDynamics()
{
_nodes[0]->body.GetSystem()->ForwardDynamics();
}
void VpControlModel::solveInverseDynamics()
{
_nodes[0]->body.GetSystem()->InverseDynamics();
}
static Axis GetDq_Body(const SE3& R, const Vec3& V)
{
Axis m_rDq;
Axis m_rQ = LogR(R);
Axis W(V[0], V[1], V[2]);
scalar t = Norm(m_rQ), delta, zeta, t2 = t * t;
if ( t < BJOINT_EPS )
{
delta = SCALAR_1_12 + SCALAR_1_720 * t2;
zeta = SCALAR_1 - SCALAR_1_12 * t2;
} else
{
zeta = SCALAR_1_2 * t * (SCALAR_1 + cos(t)) / sin(t);
delta = (SCALAR_1 - zeta) / t2;
}
return (delta * Inner(m_rQ, V)) * m_rQ + zeta * W + SCALAR_1_2 * Cross(m_rQ, W);
}
static Axis GetDq_Spatial(const SE3& R, const Vec3& V)
{
Axis m_rDq;
Axis m_rQ = LogR(R);
Axis W(V[0], V[1], V[2]);
scalar t = Norm(m_rQ), delta, zeta, t2 = t * t;
if ( t < BJOINT_EPS )
{
delta = SCALAR_1_12 + SCALAR_1_720 * t2;
zeta = SCALAR_1 - SCALAR_1_12 * t2;
} else
{
zeta = SCALAR_1_2 * t * (SCALAR_1 + cos(t)) / sin(t);
delta = (SCALAR_1 - zeta) / t2;
}
return (delta * Inner(m_rQ, V)) * m_rQ + zeta * W - SCALAR_1_2 * Cross(m_rQ, W);
}
void VpControlModel::set_q(const object &q)
{
SE3 rootJointFrame = Exp(Axis(XD(q[0]), XD(q[1]), XD(q[2])));
rootJointFrame.SetPosition(Vec3(XD(q[3]), XD(q[4]), XD(q[5])));
SE3 rootBodyFrame = rootJointFrame * _boneTs[0];
_nodes[0]->body.SetFrame(rootBodyFrame);
int q_idx = 6;
for(std::vector<int>::size_type j=1; j<_nodes.size(); j++)
{
_nodes[j]->joint.SetOrientation(Exp(Axis(XD(q[q_idx]), XD(q[q_idx+1]), XD(q[q_idx+2]))));
q_idx = q_idx + 3;
}
_pWorld->UpdateFrame();
for(std::vector<int>::size_type j=0; j<_nodes.size(); j++)
{
_nodes[j]->body.UpdateGeomFrame();
}
}
bp::list VpControlModel::get_q()
{
// Angular First for root joint
bp::list ls;
SE3 rootBodyFrame = _nodes[0]->body.GetFrame();
SE3 rootJointFrame = rootBodyFrame * Inv(_boneTs[0]);
Vec3 rootJointPos = rootJointFrame.GetPosition();
Axis rootJointQ = LogR(rootJointFrame);
Axis jointQ;
for(int i=0; i<3; i++)
{
ls.append(rootJointQ[i]);
}
for(int i=0; i<3; i++)
{
ls.append(rootJointPos[i]);
}
for(std::vector<int>::size_type j=1; j<_nodes.size(); j++)
{
if (_nodes[j]->dof == 3)
{
jointQ = _nodes[j]->joint.GetDisplacement();
for(int i=0; i<3; i++)
{
ls.append(jointQ[i]);
}
}
}
return ls;
}
bp::list VpControlModel::get_dq()
{
// Linear First for root joint
bp::list ls;
SE3 rootJointFrame = _nodes[0]->body.GetFrame() * Inv(_boneTs[0]);
se3 rootBodyGenVelLocal = _nodes[0]->body.GetGenVelocityLocal();
se3 rootJointGenVelLocal = rootBodyGenVelLocal;
Vec3 rootJointAngVelLocal(rootJointGenVelLocal[0], rootJointGenVelLocal[1], rootJointGenVelLocal[2]);
Axis rootJointDq = GetDq_Body(rootJointFrame, rootJointAngVelLocal);
Vec3 rootJointLinVelGlobal = _nodes[0]->body.GetLinVelocity(Inv(_boneTs[0]).GetPosition());
for(int i=0; i<3; i++)
{
ls.append(rootJointLinVelGlobal[i]);
}
for(int i=0; i<3; i++)
{
// ls.append(rootJointDq);
ls.append(rootJointAngVelLocal[i]);
}
for(std::vector<int>::size_type j=1; j<_nodes.size(); j++)
{
if (_nodes[j]->dof == 3)
{
// Axis jointDq = _nodes[j]->joint.GetDisplacementDerivate();
Vec3 jointDq = _nodes[j]->joint.GetVelocity();
for(int i=0; i<3; i++)
{
ls.append(jointDq[i]);
}
}
else if(_nodes[j]->dof == 1)
{
ls.append(_nodes[j]->joint_revolute.GetVelocity());
}
}
return ls;
}
bp::list VpControlModel::get_dq_nested()
{
// Angular First for root joint
bp::list ls;
ndarray rootGenVel = np::array(bp::make_tuple(0.,0.,0.,0.,0.,0.));
SE3 rootJointFrame = _nodes[0]->body.GetFrame() * Inv(_boneTs[0]);
se3 rootBodyGenVelLocal = _nodes[0]->body.GetGenVelocityLocal();
se3 rootJointGenVelLocal = rootBodyGenVelLocal;
Vec3 rootJointAngVelLocal(rootJointGenVelLocal[0], rootJointGenVelLocal[1], rootJointGenVelLocal[2]);
Axis rootJointDq = GetDq_Body(rootJointFrame, rootJointAngVelLocal);
Vec3 rootJointLinVelGlobal = _nodes[0]->body.GetLinVelocity(Inv(_boneTs[0]).GetPosition());
for(int i=0; i<3; i++)
{
// rootGenVel[i] = rootJointDq[i];
rootGenVel[i+3] = rootJointAngVelLocal[i];
}
for(int i=0; i<3; i++)
{
rootGenVel[i] = rootJointLinVelGlobal[i];
}
ls.append(rootGenVel);
for(std::vector<int>::size_type j=1; j<_nodes.size(); j++)
{
if (_nodes[j]->dof == 3)
{
// Axis jointDq = _nodes[j]->joint.GetDisplacementDerivate();
// ls.append(Axis_2_pyVec3(jointDq));
Vec3 jointDq = _nodes[j]->joint.GetVelocity();
ls.append(Vec3_2_pyVec3(jointDq));
}
else if(_nodes[j]->dof == 1)
{
Vec3 jointDq = _nodes[j]->joint_revolute.GetVelocity() * _nodes[j]->joint_revolute.GetAxis();
ls.append(Vec3_2_pyVec3(jointDq));
}
}
return ls;
}
void VpControlModel::set_ddq(const object & ddq)
{
//TODO:
int ddq_index = 6;
SE3 rootJointFrame = _nodes[0]->body.GetFrame() * Inv(_boneTs[0]);
Axis rootJointDdq(XD(ddq[3]), XD(ddq[4]), XD(ddq[5]));
_nodes[0]->joint.SetDdq(rootJointDdq);
Vec3 rootJointAngAccLocal = _nodes[0]->joint.GetAcceleration();
Vec3 rootBodyAngAccLocal = rootJointAngAccLocal;
Vec3 rootJointLinAccGlobal(XD(ddq[0]), XD(ddq[1]), XD(ddq[2]));
Vec3 rootJointLinAccLocal = InvRotate(rootJointFrame, rootJointLinAccGlobal);
Vec3 rootBodyLinAccLocal = rootJointLinAccLocal;
se3 rootBodyGenAccLocal(rootBodyAngAccLocal[0], rootBodyAngAccLocal[1], rootBodyAngAccLocal[2],
rootBodyLinAccLocal[0], rootBodyLinAccLocal[1], rootBodyLinAccLocal[2]);
_nodes[0]->body.SetGenAccelerationLocal(rootBodyGenAccLocal);
for(std::vector<int>::size_type j=1; j<_nodes.size(); j++)
{
if(_nodes[j]->dof == 3)
{
// Axis jointDdq(XD(ddq[ddq_index]), XD(ddq[ddq_index+1]), XD(ddq[ddq_index+2]));
// _nodes[j]->joint.SetDdq(jointDdq);
Vec3 jointDdq(XD(ddq[ddq_index]), XD(ddq[ddq_index+1]), XD(ddq[ddq_index+2]));
_nodes[j]->joint.SetAcceleration(jointDdq);
ddq_index += 3;
}
else if(_nodes[j]->dof == 1)
{
_nodes[j]->joint_revolute.SetAcceleration(XD(ddq[ddq_index]));
ddq_index += 1;
}
}
}
void VpControlModel::set_ddq_vp(const std::vector<double> & ddq)
{
//TODO:
int ddq_index = 6;
SE3 rootJointFrame = _nodes[0]->body.GetFrame() * Inv(_boneTs[0]);
Axis rootJointDdq(ddq[3], ddq[4], ddq[5]);
_nodes[0]->joint.SetDdq(rootJointDdq);
Vec3 rootJointAngAccLocal = _nodes[0]->joint.GetAcceleration();
Vec3 rootBodyAngAccLocal = rootJointAngAccLocal;
Vec3 rootJointLinAccGlobal(ddq[0], ddq[1], ddq[2]);
Vec3 rootJointLinAccLocal = InvRotate(rootJointFrame, rootJointLinAccGlobal);
Vec3 rootBodyLinAccLocal = rootJointLinAccLocal;
se3 rootBodyGenAccLocal(rootBodyAngAccLocal[0], rootBodyAngAccLocal[1], rootBodyAngAccLocal[2],
rootBodyLinAccLocal[0], rootBodyLinAccLocal[1], rootBodyLinAccLocal[2]);
_nodes[0]->body.SetGenAccelerationLocal(rootBodyGenAccLocal);
for(std::vector<int>::size_type j=1; j<_nodes.size(); j++)
{
if(_nodes[j]->dof == 3)
{
// Axis jointDdq(ddq[ddq_index], ddq[ddq_index+1], ddq[ddq_index+2]);
// _nodes[j]->joint.SetDdq(jointDdq);
Vec3 jointDdq(ddq[ddq_index], ddq[ddq_index+1], ddq[ddq_index+2]);
_nodes[j]->joint.SetAcceleration(jointDdq);
ddq_index += 3;
}
else if(_nodes[j]->dof == 1)
{
_nodes[j]->joint_revolute.SetAcceleration(ddq[ddq_index]);
ddq_index += 1;
}
}
}
bp::list VpControlModel::getDOFPositions()
{
// static ndarray rootFrame( bp::make_tuple(bp::make_tuple(1.,0.,0.,0.), bp::make_tuple(0.,1.,0.,0.), bp::make_tuple(0.,0.,1.,0.), bp::make_tuple(0.,0.,0.,1.)) );
//
// bp::list ls = getInternalJointOrientationsLocal();
// SE3_2_pySE3(_nodes[0]->body.GetFrame() * Inv(_boneTs[0]), rootFrame);
// ls.insert(0, rootFrame );
// return ls;
ndarray I = np::array( bp::make_tuple(bp::make_tuple(1.,0.,0.), bp::make_tuple(0.,1.,0.), bp::make_tuple(0.,0.,1.)) );
ndarray O = np::array(bp::make_tuple(0.,0.,0.));
SE3 rootFrame;
object pyR = I.copy();
object pyV = O.copy();
bp::list ls = getInternalJointOrientationsLocal();
rootFrame = _nodes[0]->body.GetFrame() * Inv(_boneTs[0]);
Vec3_2_pyVec3(rootFrame.GetPosition(), pyV);
SE3_2_pySO3(rootFrame, pyR);
ls.insert(0, bp::make_tuple(pyV, pyR));
return ls;
}
bp::list VpControlModel::getDOFVelocities()
{
ndarray rootGenVel = np::array(bp::make_tuple(0.,0.,0.,0.,0.,0.));
rootGenVel.slice(0,3) = getJointVelocityGlobal(0);
// rootGenVel.slice(3,6) = getJointAngVelocityGlobal(0);
rootGenVel.slice(3,6) = getJointAngVelocityLocal(0);
bp::list ls = getInternalJointAngVelocitiesLocal();
ls.insert(0, rootGenVel);
return ls;
}
bp::list VpControlModel::getDOFAccelerations()
{
ndarray rootGenAcc = np::array(bp::make_tuple(0.,0.,0.,0.,0.,0.));
rootGenAcc.slice(0,3) = getJointAccelerationGlobal(0);
// rootGenAcc.slice(3,6) = getJointAngAccelerationGlobal(0);
rootGenAcc.slice(3,6) = getJointAngAccelerationLocal(0);
bp::list ls = getInternalJointAngAccelerationsLocal();
ls.insert(0, rootGenAcc);
return ls;
}
bp::list VpControlModel::getDOFAxeses()
{
ndarray rootAxeses = np::array( bp::make_tuple(bp::make_tuple(1.,0.,0.), bp::make_tuple(0.,1.,0.), bp::make_tuple(0.,0.,1.),
bp::make_tuple(1.,0.,0.), bp::make_tuple(0.,1.,0.), bp::make_tuple(0.,0.,1.)) );
//ndarray rootAxesTmp = (ndarray)getJointOrientationGlobal(0);
ndarray rootAxesTmp = np::array(getJointOrientationGlobal(0));
ndarray rootAxes = transpose_pySO3(rootAxesTmp);
rootAxeses[3] = rootAxes[0];
rootAxeses[4] = rootAxes[1];
rootAxeses[5] = rootAxes[2];
bp::list ls = getInternalJointOrientationsGlobal();
for(int i=0; i<len(ls); ++i)
{
//ndarray lsTmp = (ndarray)ls[i];
ndarray lsTmp = np::array(ls[i]);
ls[i] = transpose_pySO3(lsTmp);
}
ls.insert(0, rootAxeses);
return ls;
}
bp::list VpControlModel::getDOFPositionsLocal()
{
// static ndarray rootFrame( bp::make_tuple(bp::make_tuple(1.,0.,0.,0.), bp::make_tuple(0.,1.,0.,0.), bp::make_tuple(0.,0.,1.,0.), bp::make_tuple(0.,0.,0.,1.)) );
//
// bp::list ls = getInternalJointOrientationsLocal();
// SE3_2_pySE3(_nodes[0]->body.GetFrame() * Inv(_boneTs[0]), rootFrame);
// ls.insert(0, rootFrame );
// return ls;
ndarray I = np::array( bp::make_tuple(bp::make_tuple(1.,0.,0.), bp::make_tuple(0.,1.,0.), bp::make_tuple(0.,0.,1.)) );
ndarray O = np::array(bp::make_tuple(0.,0.,0.));
SE3 rootFrame;
object pyR = I.copy();
object pyV = O.copy();
bp::list ls = getInternalJointOrientationsLocal();
rootFrame = _nodes[0]->body.GetFrame() * Inv(_boneTs[0]);
Vec3_2_pyVec3(-Inv(rootFrame).GetPosition(), pyV);
SE3_2_pySO3(rootFrame, pyR);
ls.insert(0, bp::make_tuple(pyV, pyR));
return ls;
}
bp::list VpControlModel::getDOFVelocitiesLocal()
{
ndarray rootGenVel = np::array(bp::make_tuple(0.,0.,0.,0.,0.,0.));
//rootGenVel.slice(0,3) = getJointVelocityGlobal(0);
//rootGenVel.slice(3,6) = getJointAngVelocityGlobal(0);
rootGenVel.slice(0,3) = getJointVelocityLocal(0);
rootGenVel.slice(3,6) = getJointAngVelocityLocal(0);
bp::list ls = getInternalJointAngVelocitiesLocal();
ls.insert(0, rootGenVel);
return ls;
}
bp::list VpControlModel::getDOFAccelerationsLocal()
{
ndarray rootGenAcc = np::array(bp::make_tuple(0.,0.,0.,0.,0.,0.));
//rootGenAcc.slice(0,3) = getJointAccelerationGlobal(0);
//rootGenAcc.slice(3,6) = getJointAngAccelerationGlobal(0);
rootGenAcc.slice(0,3) = getJointAccelerationLocal(0);
rootGenAcc.slice(3,6) = getJointAngAccelerationLocal(0);
bp::list ls = getInternalJointAngAccelerationsLocal();
ls.insert(0, rootGenAcc);
return ls;
}
bp::list VpControlModel::getDOFAxesesLocal()
{
ndarray rootAxeses = np::array( bp::make_tuple(bp::make_tuple(1.,0.,0.), bp::make_tuple(0.,1.,0.), bp::make_tuple(0.,0.,1.),
bp::make_tuple(1.,0.,0.), bp::make_tuple(0.,1.,0.), bp::make_tuple(0.,0.,1.)) );
//ndarray rootAxesTmp = (ndarray)getJointOrientationGlobal(0);
ndarray rootAxesTmp = np::array(getJointOrientationGlobal(0));
ndarray rootAxes = transpose_pySO3(rootAxesTmp);
rootAxeses[0] = rootAxes[0];
rootAxeses[1] = rootAxes[1];
rootAxeses[2] = rootAxes[2];
rootAxeses[3] = rootAxes[0];
rootAxeses[4] = rootAxes[1];
rootAxeses[5] = rootAxes[2];
bp::list ls = getInternalJointOrientationsGlobal();
// bp::list ls = getInternalJointOrientationsLocal();
for(int i=0; i<len(ls); ++i)
{
//ndarray lsTmp = (ndarray)ls[i];
ndarray lsTmp = np::array(ls[i]);
ls[i] = transpose_pySO3(lsTmp);
}
ls.insert(0, rootAxeses);
return ls;
}
bp::list VpControlModel::getBodyRootDOFVelocitiesLocal()
{
ndarray rootGenVel = np::array(bp::make_tuple(0.,0.,0.,0.,0.,0.));
rootGenVel.slice(0,3) = getBodyGenVelLocal(0).slice(3,6);
rootGenVel.slice(3,6) = getBodyGenVelLocal(0).slice(0,3);
bp::list ls = getInternalJointAngVelocitiesLocal();
ls.insert(0, rootGenVel);
return ls;
}
bp::list VpControlModel::getBodyRootDOFAccelerationsLocal()
{
ndarray rootGenAcc = np::array(bp::make_tuple(0.,0.,0.,0.,0.,0.));
rootGenAcc.slice(0,3) = getBodyGenAccLocal(0).slice(3,6);
rootGenAcc.slice(3,6) = getBodyGenAccLocal(0).slice(0,3);
bp::list ls = getInternalJointAngAccelerationsLocal();
ls.insert(0, rootGenAcc);
return ls;
}
bp::list VpControlModel::getBodyRootDOFAxeses()
{
ndarray rootAxeses = np::array( bp::make_tuple(bp::make_tuple(1.,0.,0.), bp::make_tuple(0.,1.,0.), bp::make_tuple(0.,0.,1.),
bp::make_tuple(1.,0.,0.), bp::make_tuple(0.,1.,0.), bp::make_tuple(0.,0.,1.)) );
//ndarray rootAxesTmp = (ndarray)getBodyOrientationGlobal(0);
ndarray rootAxesTmp = np::array(getBodyOrientationGlobal(0));
ndarray rootAxes = transpose_pySO3(rootAxesTmp);
rootAxeses[0] = rootAxes[0];
rootAxeses[1] = rootAxes[1];
rootAxeses[2] = rootAxes[2];
rootAxeses[3] = rootAxes[0];
rootAxeses[4] = rootAxes[1];
rootAxeses[5] = rootAxes[2];
bp::list ls = getInternalJointOrientationsGlobal();
// bp::list ls = getInternalJointOrientationsLocal();
for(int i=0; i<len(ls); ++i)
{
//ndarray lsTmp = (ndarray)ls[i];
ndarray lsTmp = np::array(ls[i]);
ls[i] = transpose_pySO3(lsTmp);
}
ls.insert(0, rootAxeses);
return ls;
}
void VpControlModel::setDOFVelocities( const bp::list& dofvels)
{
ndarray O = np::array(bp::make_tuple(0.,0.,0.));
setJointVelocityGlobal(0, dofvels[0].slice(0,3));
setJointAngVelocityLocal(0, dofvels[0].slice(3,6));
for(std::vector<int>::size_type i=1; i<_nodes.size(); ++i)
{
if (_nodes[i]->dof == 3)
_nodes[i]->joint.SetVelocity(pyVec3_2_Vec3(dofvels[i]));
}
}
void VpControlModel::setDOFAccelerations( const bp::list& dofaccs)
{
ndarray O = np::array(bp::make_tuple(0.,0.,0.));
setJointAccelerationGlobal(0, dofaccs[0].slice(0,3));
// setJointAngAccelerationGlobal(0, dofaccs[0].slice(3,6));
setJointAngAccelerationLocal(0, dofaccs[0].slice(3,6));
setInternalJointAngAccelerationsLocal( ((bp::list)dofaccs.slice(1,_)) );
}
void VpControlModel::setDOFTorques(const bp::list& dofTorque)
{
for(std::vector<int>::size_type i=1; i<_nodes.size(); ++i)
{
//std::cout << _nodes[i]->name << std::endl;
//std::cout << pyVec3_2_Vec3(dofTorque[i-1]) << std::endl;
_nodes[i]->joint.SetTorque(pyVec3_2_Vec3(dofTorque[i-1]));
}
}
boost::python::object VpControlModel::getJointTransform( int index )
{
ndarray pyT = np::array( bp::make_tuple(bp::make_tuple(1.,0.,0.,0.),
bp::make_tuple(0.,1.,0.,0.),
bp::make_tuple(0.,0.,1.,0.),
bp::make_tuple(0.,0.,0.,1.)) );
if (index == 0)
{
SE3 bodyFrame = _nodes[index]->body.GetFrame();
SE3_2_pySE3(bodyFrame * Inv(_boneTs[index]), pyT);
}
else
{
SE3_2_pySE3(_nodes[index]->joint.GetOrientation(), pyT);
}
return pyT;
}
boost::python::object VpControlModel::getJointAfterTransformGlobal( int index )
{
ndarray pyT = np::array( bp::make_tuple(bp::make_tuple(1.,0.,0.,0.),
bp::make_tuple(0.,1.,0.,0.),
bp::make_tuple(0.,0.,1.,0.),
bp::make_tuple(0.,0.,0.,1.)) );
SE3 bodyFrame = _nodes[index]->body.GetFrame();
SE3_2_pySE3(bodyFrame * Inv(_boneTs[index]), pyT);
return pyT;
}
boost::python::object VpControlModel::getJointOrientationLocal( int index )
{
ndarray I = np::array( bp::make_tuple(bp::make_tuple(1.,0.,0.), bp::make_tuple(0.,1.,0.), bp::make_tuple(0.,0.,1.)) );
if(index == 0)
return getJointOrientationGlobal(index);
else
{
object pyR = I.copy();
if(_nodes[index]->dof == 3)
{
SE3_2_pySO3(_nodes[index]->joint.GetOrientation(), pyR);
}
else if(_nodes[index]->dof == 1)
{
SE3_2_pySO3(Exp(_nodes[index]->joint_revolute.GetAngle() * Vec3_2_Axis(_nodes[index]->joint_revolute.GetAxis())), pyR);
}
return pyR;
}
}
boost::python::object VpControlModel::getJointAngVelocityLocal( int index )
{
ndarray O = np::array(bp::make_tuple(0.,0.,0.));
object pyV = O.copy();
if(index == 0)
{
se3 genVelBodyLocal, genVelJointLocal;
genVelBodyLocal = _nodes[index]->body.GetGenVelocityLocal();
genVelJointLocal = InvAd(Inv(_boneTs[index]), genVelBodyLocal);
// genVelJointLocal = Ad(_boneTs[index], genVelBodyLocal); // �� ���ΰ� ���� ����
pyV[0] = genVelJointLocal[0];
pyV[1] = genVelJointLocal[1];
pyV[2] = genVelJointLocal[2];
}
else
{
if( _nodes[index]->dof == 3)
{
Vec3_2_pyVec3(_nodes[index]->joint.GetVelocity(), pyV);
}
if( _nodes[index]->dof == 1)
{
Vec3_2_pyVec3(_nodes[index]->joint_revolute.GetVelocity() * _nodes[index]->joint_revolute.GetAxis(), pyV);
}
}
return pyV;
}
boost::python::object VpControlModel::getJointAngAccelerationLocal( int index )
{
ndarray O = np::array(bp::make_tuple(0.,0.,0.));
object pyV = O.copy();
if(index == 0)
{
se3 genAccBodyLocal, genAccJointLocal;
genAccBodyLocal = _nodes[index]->body.GetGenAccelerationLocal();
genAccJointLocal = InvAd(Inv(_boneTs[index]), genAccBodyLocal);
pyV[0] = genAccJointLocal[0];
pyV[1] = genAccJointLocal[1];
pyV[2] = genAccJointLocal[2];
}
else
Vec3_2_pyVec3(_nodes[index]->joint.GetAcceleration(), pyV);
return pyV;
}
//object VpControlModel::getJointPositionGlobal( int index )
object VpControlModel::getJointPositionGlobal( int index, const object& positionLocal/*=object() */ )
{
ndarray O = np::array(bp::make_tuple(0.,0.,0.));
SE3 bodyFrame;
object pyV = O.copy();
Vec3 positionLocal_;
// body frame�� Inv(boneT)�� ���� joint ��ġ ã�´�.
bodyFrame = _nodes[index]->body.GetFrame();
if(positionLocal.is_none())
Vec3_2_pyVec3((bodyFrame * Inv(_boneTs[index])).GetPosition(), pyV);
else
{
pyVec3_2_Vec3(positionLocal, positionLocal_);
Vec3_2_pyVec3((bodyFrame * Inv(_boneTs[index])) * positionLocal_, pyV);
}
return pyV;
// if(!_nodes[index]) // ������ ��� parent joint frame�� ã�� offset��ŭ transformation ��Ų��.
// {
// static SE3 parentJointFrame;
// static Vec3 offset;
//// int parent = XI(_skeleton.attr("getParentIndex")(index));
// int parent = XI(_skeleton.attr("getParentJointIndex")(index));
// parentJointFrame = _nodes[parent]->body.GetFrame() * Inv(_boneTs[parent]);
// offset = pyVec3_2_Vec3(_skeleton.attr("getOffset")(index));
// Vec3_2_pyVec3(parentJointFrame * offset, pyV);
// }
// else // ������ �ƴ� ��� body frame�� Inv(boneT)�� ���� joint ��ġ ã�´�.
// {
// static SE3 bodyFrame;
// bodyFrame = _nodes[index]->body.GetFrame();
// Vec3_2_pyVec3((bodyFrame * Inv(_boneTs[index])).GetPosition(), pyV);
// }
// return pyV;
}
object VpControlModel::getJointVelocityGlobal( int index )
{
ndarray O = np::array(bp::make_tuple(0.,0.,0.));
object pyV = O.copy();
Vec3_2_pyVec3(getBodyVelocityGlobal(index, Inv(_boneTs[index]).GetPosition()), pyV);
return pyV;
}
object VpControlModel::getJointAccelerationGlobal( int index )
{
ndarray O = np::array(bp::make_tuple(0.,0.,0.));
object pyV = O.copy();
Vec3 pospos = Inv(_boneTs[index]).GetPosition();
Vec3_2_pyVec3(getBodyAccelerationGlobal(index, &(pospos)), pyV);
return pyV;
}
boost::python::object VpControlModel::getJointOrientationGlobal( int index )
{
ndarray I = np::array( bp::make_tuple(bp::make_tuple(1.,0.,0.), bp::make_tuple(0.,1.,0.), bp::make_tuple(0.,0.,1.)) );
SE3 bodyFrame;
object pyR = I.copy();
// body frame�� Inv(boneT)�� ���� joint frame ���Ѵ�
bodyFrame = _nodes[index]->body.GetFrame();
SE3_2_pySO3(bodyFrame * Inv(_boneTs[index]), pyR);
return pyR;
}
boost::python::object VpControlModel::getJointAngVelocityGlobal( int index )
{
return getBodyAngVelocityGlobal(index);
// static ndarray O(bp::make_tuple(0.,0.,0.));
// static Vec3 angVel, parentAngVel;
// object pyV = O.copy();
//
// angVel = _nodes[index]->body.GetAngVelocity();
//
// int parentIndex = getParentIndex(index);
// if(parentIndex==-1)
// parentAngVel = Vec3(0.,0.,0.);
// else
// parentAngVel = _nodes[parentIndex]->body.GetAngVelocity();
//
// Vec3_2_pyVec3(angVel - parentAngVel, pyV);
// return pyV;
}
boost::python::object VpControlModel::getJointAngAccelerationGlobal( int index )
{
return getBodyAngAccelerationGlobal(index);
}
boost::python::object VpControlModel::getJointFrame( int index )
{
ndarray frame = np::array( bp::make_tuple(bp::make_tuple(1.,0.,0.,0.), bp::make_tuple(0.,1.,0.,0.), bp::make_tuple(0.,0.,1.,0.), bp::make_tuple(0.,0.,0.,1.)) );
SE3 T = _nodes[index]->body.GetFrame() * Inv(_boneTs[index]);
SE3_2_pySE3(T, frame);
return frame;
}
object VpControlModel::getJointVelocityLocal( int index )
{
ndarray O = np::array(bp::make_tuple(0.,0.,0.));
object pyV = O.copy();
SE3 jointFrame = _nodes[index]->body.GetFrame() * Inv(_boneTs[index]);
Vec3_2_pyVec3(InvRotate(jointFrame, getBodyVelocityGlobal(index, Inv(_boneTs[index]).GetPosition())), pyV);
return pyV;
}
object VpControlModel::getJointAccelerationLocal( int index )
{
ndarray O = np::array(bp::make_tuple(0.,0.,0.));
object pyV = O.copy();
Vec3 pospos = Inv(_boneTs[index]).GetPosition();
SE3 jointFrame = _nodes[index]->body.GetFrame() * Inv(_boneTs[index]);
Vec3_2_pyVec3(InvRotate(jointFrame, getBodyAccelerationGlobal(index, &(pospos))), pyV);
return pyV;
}
bp::list VpControlModel::getJointOrientationsLocal()
{
bp::list ls;
for(std::vector<int>::size_type i=0; i<_nodes.size(); ++i)
ls.append(getJointOrientationLocal(i));
return ls;
}
bp::list VpControlModel::getJointAngVelocitiesLocal()
{
bp::list ls;
for(std::vector<int>::size_type i=0; i<_nodes.size(); ++i)
ls.append(getJointAngVelocityLocal(i));
return ls;
}
bp::list VpControlModel::getJointAngAccelerationsLocal()
{
bp::list ls;
for(std::vector<int>::size_type i=0; i<_nodes.size(); ++i)
ls.append(getJointAngAccelerationLocal(i));
return ls;
}
bp::list VpControlModel::getJointPositionsGlobal()
{
bp::list ls;
for(std::vector<int>::size_type i=0; i<_nodes.size(); ++i)
ls.append(getJointPositionGlobal(i));
return ls;
}
bp::list VpControlModel::getJointVelocitiesGlobal()
{
bp::list ls;
for(std::vector<int>::size_type i=0; i<_nodes.size(); ++i)
ls.append(getJointVelocityGlobal(i));
return ls;
}
bp::list VpControlModel::getJointAccelerationsGlobal()
{
bp::list ls;
for(std::vector<int>::size_type i=0; i<_nodes.size(); ++i)
ls.append(getJointAccelerationGlobal(i));
return ls;
}
bp::list VpControlModel::getJointOrientationsGlobal()
{
bp::list ls;
for(std::vector<int>::size_type i=0; i<_nodes.size(); ++i)
ls.append(getJointOrientationGlobal(i));
return ls;
}
bp::list VpControlModel::getJointAngVelocitiesGlobal()
{
bp::list ls;
for(std::vector<int>::size_type i=0; i<_nodes.size(); ++i)
ls.append(getJointAngVelocityGlobal(i));
return ls;
}
bp::list VpControlModel::getJointAngAccelerationsGlobal()
{
bp::list ls;
for(std::vector<int>::size_type i=0; i<_nodes.size(); ++i)
ls.append(getJointAngAccelerationGlobal(i));
return ls;
}
bp::list VpControlModel::getInternalJointOrientationsLocal()
{
bp::list ls;
for(std::vector<int>::size_type i=1; i<_nodes.size(); ++i)
ls.append(getJointOrientationLocal(i));
return ls;
}
bp::list VpControlModel::getInternalJointAngVelocitiesLocal()
{
bp::list ls;
for(std::vector<int>::size_type i=1; i<_nodes.size(); ++i)
ls.append(getJointAngVelocityLocal(i));
return ls;
}
bp::list VpControlModel::getInternalJointAngAccelerationsLocal()
{
bp::list ls;
for(std::vector<int>::size_type i=1; i<_nodes.size(); ++i)
ls.append(getJointAngAccelerationLocal(i));
return ls;
}
bp::list VpControlModel::getInternalJointPositionsGlobal()
{
bp::list ls;
// for(int i=1; i<_jointElementIndexes.size(); ++i)
for(std::vector<int>::size_type i=1; i<_nodes.size(); ++i)
ls.append(getJointPositionGlobal(i));
return ls;
}
bp::list VpControlModel::getInternalJointOrientationsGlobal()
{
bp::list ls;
for(std::vector<int>::size_type i=1; i<_nodes.size(); ++i)
ls.append(getJointOrientationGlobal(i));
return ls;
}
void VpControlModel::setJointAngVelocityLocal( int index, const object& angvel )
{
if(index == 0)
{
se3 genVelBodyLocal, genVelJointLocal;
genVelBodyLocal = _nodes[index]->body.GetGenVelocityLocal();
genVelJointLocal = InvAd(Inv(_boneTs[index]), genVelBodyLocal);
genVelJointLocal[0] = XD(angvel[0]);
genVelJointLocal[1] = XD(angvel[1]);
genVelJointLocal[2] = XD(angvel[2]);
genVelBodyLocal = Ad(Inv(_boneTs[index]), genVelJointLocal);;
_nodes[index]->body.SetGenVelocityLocal(genVelBodyLocal);
}
else
_nodes[index]->joint.SetVelocity(pyVec3_2_Vec3(angvel));
}
void VpControlModel::setJointAngAccelerationLocal( int index, const object& angacc )
{
if(index == 0)
{
se3 genAccBodyLocal, genAccJointLocal;
genAccBodyLocal = _nodes[index]->body.GetGenAccelerationLocal();
genAccJointLocal = InvAd(Inv(_boneTs[index]), genAccBodyLocal);
genAccJointLocal[0] = XD(angacc[0]);
genAccJointLocal[1] = XD(angacc[1]);
genAccJointLocal[2] = XD(angacc[2]);
genAccBodyLocal = Ad(Inv(_boneTs[index]), genAccJointLocal);;
_nodes[index]->body.SetGenAccelerationLocal(genAccBodyLocal);
}
else
_nodes[index]->joint.SetAcceleration(pyVec3_2_Vec3(angacc));
}
void VpControlModel::setJointVelocityGlobal( int index, const object& vel )
{
if(index == 0)
{
Vec3 pospos = Inv(_boneTs[index]).GetPosition();
setBodyVelocityGlobal(index, pyVec3_2_Vec3(vel), &(pospos));
}
else
cout << "setJointAccelerationGlobal() : not completely implemented" << endl;
}
void VpControlModel::setJointAccelerationGlobal( int index, const object& acc )
{
if(index == 0)
{
Vec3 pospos = Inv(_boneTs[index]).GetPosition();
setBodyAccelerationGlobal(index, pyVec3_2_Vec3(acc), &(pospos));
}
else
cout << "setJointAccelerationGlobal() : not completely implemented" << endl;
}
void VpControlModel::setJointAngAccelerationGlobal( int index, const object& angacc )
{
setBodyAngAccelerationGlobal(index, angacc);
}
void VpControlModel::setJointAngAccelerationsLocal( const bp::list& angaccs )
{
for(std::vector<int>::size_type i=0; i<_nodes.size(); ++i)
setJointAngAccelerationLocal(i, angaccs[i]);
}
void VpControlModel::setInternalJointAngAccelerationsLocal( const bp::list& angaccs )
{
for(std::vector<int>::size_type i=1; i<_nodes.size(); ++i)
{
if (_nodes[i]->dof == 3)
_nodes[i]->joint.SetAcceleration(pyVec3_2_Vec3(angaccs[i-1]));
else if(_nodes[i]->dof == 1)
_nodes[i]->joint_revolute.SetAcceleration(XD(angaccs[i-1][0]));
}
}
void VpControlModel::SetJointElasticity(int index, scalar Kx, scalar Ky, scalar Kz)
{
assert(Kx < 0. && "Joint Elasticity must larger than 0");
if(Ky < 0.)
{
SpatialSpring k(Kx);
_nodes[index]->joint.SetElasticity(k);
}
else
{
SpatialSpring k(0., Kx, Ky, Kz);
_nodes[index]->joint.SetElasticity(k);
}
}
void VpControlModel::SetJointsElasticity(scalar Kx, scalar Ky, scalar Kz)
{
for (std::vector<int>::size_type i=1; i<_nodes.size(); i++)
SetJointElasticity(i, Kx, Ky, Kz);
}
void VpControlModel::SetJointDamping(int index, scalar Dx, scalar Dy, scalar Dz)
{
assert(Dx < 0. && "Joint Damping must larger than 0");
if(Dy < 0.)
{
SpatialDamper d(Dx);
_nodes[index]->joint.SetDamping(d);
}
else
{
SpatialDamper d(0., Dx, Dy, Dz);
_nodes[index]->joint.SetDamping(d);
}
}
void VpControlModel::SetJointsDamping(scalar Dx, scalar Dy, scalar Dz)
{
for (std::vector<int>::size_type i=1; i<_nodes.size(); i++)
SetJointDamping(i, Dx, Dy, Dz);
}
boost::python::object VpControlModel::getJointTorqueLocal( int index )
{
ndarray O = np::array(bp::make_tuple(0.,0.,0.));
object pyV = O.copy();
if(index==0) return pyV;
Vec3_2_pyVec3(_nodes[index]->joint.GetTorque(), pyV);
return pyV;
}
bp::list VpControlModel::getInternalJointTorquesLocal()
{
bp::list ls;
// for(int i=1; i<_jointElementIndexes.size(); ++i)
for(std::vector<int>::size_type i=1; i<_nodes.size(); ++i)
ls.append(getJointTorqueLocal(i));
return ls;
}
void VpControlModel::setJointTorqueLocal( int index, const object& torque )
{
// int index = _jointElementIndexes[jointIndex];
if(_nodes[index]->dof == 3)
_nodes[index]->joint.SetTorque(pyVec3_2_Vec3(torque));
}
void VpControlModel::setInternalJointTorquesLocal( const bp::list& torques )
{
// int index;
// for(int i=1; i<_jointElementIndexes.size(); ++i)
// {
// index = _jointElementIndexes[i];
// _nodes[index]->joint.SetTorque(pyVec3_2_Vec3(torques[i]));
// }
for(std::vector<int>::size_type i=1; i<_nodes.size(); ++i)
_nodes[i]->joint.SetTorque(pyVec3_2_Vec3(torques[i-1]));
}
void VpControlModel::applyBodyGenForceGlobal( int index, const object& torque, const object& force, const object& positionLocal/*=object()*/ )
{
Vec3 zero(0,0,0);
if(positionLocal.is_none())
_nodes[index]->body.ApplyGlobalForce(dse3(XD(torque[0]), XD(torque[1]), XD(torque[2]), XD(force[0]), XD(force[1]), XD(force[2])), zero);
else
_nodes[index]->body.ApplyGlobalForce(dse3(XD(torque[0]), XD(torque[1]), XD(torque[2]), XD(force[0]), XD(force[1]), XD(force[2])), pyVec3_2_Vec3(positionLocal));
}
void VpControlModel::applyBodyForceGlobal( int index, const object& force, const object& positionLocal/*=object()*/ )
{
Vec3 zero(0,0,0);
if(positionLocal.is_none())
_nodes[index]->body.ApplyGlobalForce(dse3(0.,0.,0., XD(force[0]), XD(force[1]), XD(force[2])), zero);
else
_nodes[index]->body.ApplyGlobalForce(dse3(0.,0.,0., XD(force[0]), XD(force[1]), XD(force[2])), pyVec3_2_Vec3(positionLocal));
}
void VpControlModel::applyBodyTorqueGlobal( int index, const object& torque )
{
Vec3 zero(0,0,0);
_nodes[index]->body.ApplyGlobalForce(dse3(XD(torque[0]), XD(torque[1]), XD(torque[2]), 0.,0.,0.), zero);
}
object VpControlModel::getBodyForceLocal( int index )
{
dse3 genForce;
ndarray O = np::array(bp::make_tuple(0.,0.,0.));
object pyV = O.copy();
genForce = _nodes[index]->body.GetForce();
pyV[0] = genForce[3];
pyV[1] = genForce[4];
pyV[2] = genForce[5];
return pyV;
}
object VpControlModel::getBodyNetForceLocal( int index )
{
dse3 genForce;
ndarray O = np::array(bp::make_tuple(0.,0.,0.));
object pyV = O.copy();
genForce = _nodes[index]->body.GetNetForce();
pyV[0] = genForce[3];
pyV[1] = genForce[4];
pyV[2] = genForce[5];
return pyV;
}
object VpControlModel::getBodyGravityForceLocal( int index )
{
dse3 genForce;
ndarray O = np::array(bp::make_tuple(0.,0.,0.));
object pyV = O.copy();
genForce = _nodes[index]->body.GetGravityForce();
pyV[0] = genForce[3];
pyV[1] = genForce[4];
pyV[2] = genForce[5];
return pyV;
}
static ublas::vector<double> ToUblasVector(const Vec3 &v_vp)
{
ublas::vector<double> v(3);
for(int i=0; i<3; i++)
v(i) = v_vp[i];
return v;
}
static ublas::vector<double> ToUblasVector(const Axis &v_vp)
{
ublas::vector<double> v(3);
for(int i=0; i<3; i++)
v(i) = v_vp[i];
return v;
}
static ublas::matrix<double> ToUblasMatrix(const Vec3 &v_vp)
{
ublas::matrix<double> m(3, 1);
for(int i=0; i<3; i++)
m(i, 0) = v_vp[i];
return m;
}
static ublas::matrix<double> ToUblasMatrix(const Axis &v_vp)
{
ublas::matrix<double> m(3, 1);
for(int i=0; i<3; i++)
m(i, 0) = v_vp[i];
return m;
}
static ublas::matrix<double> SE3ToUblasRotate(const SE3 &T_vp)
{
ublas::matrix<double> T(3, 3);
for(int i=0; i<3; i++)
for(int j=0; j<3; j++)
T(j, i) = T_vp[i*3 + j];
return T;
}
static ublas::vector<double> cross(const ublas::vector<double> &v1, const ublas::vector<double> &v2)
{
ublas::vector<double> v(3);
v(0) = v1(1)*v2(2) - v1(2) * v2(1);
v(1) = v1(2)*v2(0) - v1(0) * v2(2);
v(2) = v1(0)*v2(1) - v1(1) * v2(0);
return v;
}
static ublas::matrix<double> GetCrossMatrix(const ublas::vector<double> &r)
{
ublas::matrix<double> R(3, 3);
R(0, 0) = 0;
R(1, 0) = r[2];
R(2, 0) = -r[1];
R(0, 1) = -r[2];
R(1, 1) = 0;
R(2, 1) = r[0];
R(0, 2) = r[1];
R(1, 2) = -r[0];
R(2, 2) = 0;
return R;
}
Axis GetBJointDq(const Axis &m_rQ, const Vec3 &V)
{
Axis W(V[0], V[1], V[2]);
scalar t = Norm(m_rQ), delta, zeta, t2 = t * t;
if ( t < BJOINT_EPS )
{
delta = SCALAR_1_12 + SCALAR_1_720 * t2;
zeta = SCALAR_1 - SCALAR_1_12 * t2;
} else
{
zeta = SCALAR_1_2 * t * (SCALAR_1 + cos(t)) / sin(t);
delta = (SCALAR_1 - zeta) / t2;
}
return (delta * Inner(m_rQ, V)) * m_rQ + zeta * W + SCALAR_1_2 * Cross(m_rQ, W);
}
static ublas::matrix<double> GetBJointJacobian(const Axis &m_rQ)
{
ublas::matrix<double> J(3, 3);
ublas::vector<double> m_rQ_ub = ToUblasVector(m_rQ);
scalar t = Norm(m_rQ), alpha, beta, gamma, t2 = t * t;
if ( t < BJOINT_EPS )
{
alpha = SCALAR_1_6 - SCALAR_1_120 * t2;
beta = SCALAR_1 - SCALAR_1_6 * t2;
gamma = SCALAR_1_2 - SCALAR_1_24 * t2;
} else
{
beta = sin(t) / t;
alpha = (SCALAR_1 - beta) / t2;
gamma = (SCALAR_1 - cos(t)) / t2;
}
// Axis V = (alpha * Inner(m_rQ, m_rDq)) * m_rQ + beta * m_rDq + gamma * Cross(m_rDq, m_rQ);
J = alpha * outer_prod(m_rQ_ub, m_rQ_ub) + beta * ublas::identity_matrix<double>(3) - gamma * GetCrossMatrix(m_rQ_ub);
// J(0, 0) = alpha * m_rQ[0] * m_rQ[0] + beta;
// J(1, 0) = alpha * m_rQ[1] * m_rQ[0] - gamma * m_rQ[2];
// J(2, 0) = alpha * m_rQ[2] * m_rQ[0] + gamma * m_rQ[1];
// J(0, 1) = alpha * m_rQ[0] * m_rQ[1] + gamma * m_rQ[2];
// J(1, 1) = alpha * m_rQ[1] * m_rQ[1] + beta;
// J(2, 1) = alpha * m_rQ[2] * m_rQ[1] - gamma * m_rQ[0];
// J(0, 2) = alpha * m_rQ[0] * m_rQ[2] - gamma * m_rQ[1];
// J(1, 2) = alpha * m_rQ[1] * m_rQ[2] + gamma * m_rQ[0];
// J(2, 2) = alpha * m_rQ[2] * m_rQ[2] + beta;
// return alpha * mm.getDyadMatrixForm(q) + beta * np.eye(3) - gamma * mm.getCrossMatrixForm(q)
return J;
}
static Axis GetBJointJDQ(const Axis &m_rQ, const Axis &m_rDq)
{
ublas::vector<double> JDQ(3);
ublas::vector<double> m_rQ_ub = ToUblasVector(m_rQ);
scalar t = Norm(m_rQ), alpha, beta, gamma, t2 = t * t;
if ( t < BJOINT_EPS )
{
alpha = SCALAR_1_6 - SCALAR_1_120 * t2;
beta = SCALAR_1 - SCALAR_1_6 * t2;
gamma = SCALAR_1_2 - SCALAR_1_24 * t2;
} else
{
beta = sin(t) / t;
alpha = (SCALAR_1 - beta) / t2;
gamma = (SCALAR_1 - cos(t)) / t2;
}
Axis V = (alpha * Inner(m_rQ, m_rDq)) * m_rQ + beta * m_rDq + gamma * Cross(m_rDq, m_rQ);
JDQ(0) = V[0];
JDQ(1) = V[1];
JDQ(2) = V[2];
return V;
}
static Axis GetBJointDJDQ(const Axis &m_rQ, const Axis &m_rDq)
{
ublas::vector<double> DJDQ(3);
ublas::vector<double> m_rQ_ub = ToUblasVector(m_rQ);
scalar t = Norm(m_rQ), alpha, beta, gamma, d_alpha, d_beta, d_gamma, q_dq = Inner(m_rQ, m_rDq), t2 = t * t;
if ( t < BJOINT_EPS )
{
alpha = SCALAR_1_6 - SCALAR_1_120 * t2;
beta = SCALAR_1 - SCALAR_1_6 * t2;
gamma = SCALAR_1_2 - SCALAR_1_24 * t2;
d_alpha = (SCALAR_1_1260 * t2 - SCALAR_1_60) * q_dq;
d_beta = (SCALAR_1_30 * t2 - SCALAR_1_3) * q_dq;
d_gamma = (SCALAR_1_180 * t2 - SCALAR_1_12) * q_dq;
} else
{
beta = sin(t) / t;
alpha = (SCALAR_1 - beta) / t2;
gamma = (SCALAR_1 - cos(t)) / t2;
d_alpha = (gamma - SCALAR_3 * alpha) / t2 * q_dq;
d_beta = (alpha - gamma) * q_dq;
d_gamma = (beta - SCALAR_2 * gamma) / t2 * q_dq;
}
Axis dJdq = (d_alpha * q_dq + alpha * SquareSum(m_rDq)) * m_rQ
+ (alpha*q_dq + d_beta) * m_rDq
+ Cross(d_gamma*m_rDq, m_rQ);
DJDQ(0) = dJdq[0];
DJDQ(1) = dJdq[1];
DJDQ(2) = dJdq[2];
return dJdq;
}
static object ToNumpyArray(const ublas::matrix<double> &m)
{
bp::tuple shape = bp::make_tuple(m.size1(), m.size2());
np::dtype dtype = np::dtype::get_builtin<float>();
ndarray m_np = np::empty(shape, dtype);
for(ublas::matrix<double>::size_type i=0; i<m.size1(); i++)
{
for(ublas::matrix<double>::size_type j=0; j<m.size2(); j++)
{
m_np[i][j] = m(i, j);
}
}
return m_np;
}
object VpControlModel::getLocalJacobian(int index)
{
return ToNumpyArray(GetBJointJacobian(_nodes[index]->joint.GetDisplacement()));
}
object VpControlModel::getLocalJointVelocity(int index)
{
return Vec3_2_pyVec3(_nodes[index]->joint.GetVelocity());
}
object VpControlModel::getLocalJointDisplacementDerivatives(int index)
{
Axis vec = _nodes[index]->joint.GetDisplacementDerivate();
return Vec3_2_pyVec3(Vec3(vec[0], vec[1], vec[2]));
}
object VpControlModel::computeJacobian(int index, const object& positionGlobal)
{
//TODO:
Vec3 effector_position = pyVec3_2_Vec3(positionGlobal);
vpBJoint *joint;
SE3 joint_frame;
bp::tuple shape = bp::make_tuple(6, m_total_dof);
np::dtype dtype = np::dtype::get_builtin<float>();
ndarray J = np::zeros(shape, dtype);
ublas::vector<double> offset;
ublas::matrix<double> _Jw, _Jv;
//root joint
J[0][3] = 1.;
J[1][4] = 1.;
J[2][5] = 1.;
joint_frame = _nodes[0]->body.GetFrame() * Inv(_boneTs[0]);
offset = ToUblasVector(effector_position - joint_frame.GetPosition());
_Jw = prod(SE3ToUblasRotate(joint_frame), GetBJointJacobian(LogR(joint_frame)));
_Jv = -prod(GetCrossMatrix(offset), _Jw);
for (int dof_index = 0; dof_index < 3; dof_index++)
{
for (int j=0; j<3; j++)
{
J[j+0][dof_index] = _Jv(j, dof_index);
J[j+3][dof_index] = _Jw(j, dof_index);
}
}
//internal joint
std::vector<int> &ancestors = _nodes[index]->ancestors;
int dof_start_index = 0;
for(std::vector<int>::size_type i=1; i<_nodes.size();i++)
{
if(std::find(ancestors.begin(), ancestors.end(), i) != ancestors.end())
{
joint = &(_nodes[i]->joint);
joint_frame = _nodes[i]->body.GetFrame() * Inv(_boneTs[i]);
offset = ToUblasVector(effector_position - joint_frame.GetPosition());
_Jw = prod(SE3ToUblasRotate(joint_frame), GetBJointJacobian(joint->GetDisplacement()));
_Jv = -prod(GetCrossMatrix(offset), _Jw);
dof_start_index = _nodes[i]->dof_start_index;
for (int dof_index = 0; dof_index < _nodes[i]->dof; dof_index++)
{
for (int j=0; j<3; j++)
{
J[j+0][dof_start_index + dof_index] = _Jv(j, dof_index);
J[j+3][dof_start_index + dof_index] = _Jw(j, dof_index);
}
}
}
}
return J;
}
bp::tuple VpControlModel::computeCom_J_dJdq()
{
int body_num = this->getBodyNum();
bp::tuple shape_J = bp::make_tuple(6*body_num, m_total_dof);
bp::tuple shape_dJdq = bp::make_tuple(6*body_num);
np::dtype dtype = np::dtype::get_builtin<float>();
ndarray J = np::zeros(shape_J, dtype);
ndarray dJdq = np::zeros(shape_dJdq, dtype);
ublas::vector<double> offset, offset_velocity;
ublas::matrix<double> _Jw, _Jv;
ublas::vector<double> _dJdqw, _dJdqv;
//preprocessing : get joint frames
std::vector<SE3> joint_frames;
for (std::vector<Node*>::size_type i=0; i < _nodes.size(); i++)
joint_frames.push_back(_nodes[i]->body.GetFrame() * Inv(_boneTs[i]));
//root joint
// jacobian
Vec3 effector_position, effector_velocity;
_Jw = SE3ToUblasRotate(joint_frames[0]);
for(std::vector<Node*>::size_type body_idx=0; body_idx < _nodes.size(); body_idx++)
{
effector_position = _nodes[body_idx]->get_body_position();
offset = ToUblasVector(effector_position - joint_frames[0].GetPosition());
_Jv = -prod(GetCrossMatrix(offset), _Jw);
for (int dof_index = 0; dof_index < 3; dof_index++)
{
J[6*body_idx + dof_index][dof_index] = 1.;
for (int j=0; j<3; j++)
{
// J[6*body_idx + 0 + j][3 + dof_index] = joint_frames[0][3*dof_index + j];
J[6*body_idx + 0 + j][3+dof_index] = _Jv(j, dof_index);
J[6*body_idx + 3 + j][3+dof_index] = _Jw(j, dof_index);
}
}
}
// jacobian derivative
Vec3 joint_global_pos = joint_frames[0].GetPosition();
Vec3 joint_global_velocity = _nodes[0]->body.GetLinVelocity(Inv(_boneTs[0]).GetPosition());
Vec3 joint_global_ang_vel = _nodes[0]->body.GetAngVelocity();
_dJdqw = ToUblasVector(Vec3(0.));
for(std::vector<Node*>::size_type body_idx=0; body_idx < _nodes.size(); body_idx++)
{
effector_position = _nodes[body_idx]->get_body_position();
offset = ToUblasVector(effector_position - joint_global_pos);
effector_velocity = _nodes[body_idx]->get_body_com_velocity();
offset_velocity = ToUblasVector(effector_velocity - joint_global_velocity);
_dJdqv = -cross(offset, _dJdqw) - cross(offset_velocity, ToUblasVector(joint_global_ang_vel));
for (int j=0; j<3; j++)
{
dJdq[6*body_idx + 0 + j] += _dJdqv(j);
dJdq[6*body_idx + 3 + j] += _dJdqw(j);
}
}
//internal joint
for(std::vector<Node*>::size_type i=1; i<_nodes.size(); i++)
{
int parent_joint_index = _nodes[i]->parent_index;
int dof_start_index = _nodes[i]->dof_start_index;
joint_global_pos = joint_frames[i].GetPosition();
joint_global_velocity = _nodes[i]->body.GetLinVelocity(Inv(_boneTs[i]).GetPosition());
joint_global_ang_vel = _nodes[i]->body.GetAngVelocity() - _nodes[parent_joint_index]->body.GetAngVelocity();
if (_nodes[i]->dof == 3)
{
_Jw = SE3ToUblasRotate(joint_frames[i]);
// joint_global_ang_vel = Rotate(joint_frames[i], _nodes[i]->joint.GetVelocity());
}
else if(_nodes[i]->dof == 1)
{
_Jw = prod(SE3ToUblasRotate(joint_frames[i]), ToUblasMatrix(_nodes[i]->joint_revolute.GetAxis()));
// joint_global_ang_vel = Rotate(joint_frames[i], _nodes[i]->joint_revolute.GetVelocity() * _nodes[i]->joint_revolute.GetAxis());
}
_dJdqw = ToUblasVector(Cross(_nodes[parent_joint_index]->body.GetAngVelocity(), joint_global_ang_vel));
for(std::vector<Node*>::size_type body_idx=1; body_idx < _nodes.size(); body_idx++)
{
std::vector<bool> &is_body_ancestors = _nodes[body_idx]->is_ancestor;
effector_position = _nodes[body_idx]->get_body_position();
effector_velocity = _nodes[body_idx]->get_body_com_velocity();
if(is_body_ancestors[i])
{
// jacobian
offset = ToUblasVector(effector_position - joint_global_pos);
_Jv = -prod(GetCrossMatrix(offset), _Jw);
dof_start_index = _nodes[i]->dof_start_index;
for (int dof_index = 0; dof_index < _nodes[i]->dof; dof_index++)
{
for (int j=0; j<3; j++)
{
J[6*body_idx + 0+j][dof_start_index + dof_index] = _Jv(j, dof_index);
J[6*body_idx + 3+j][dof_start_index + dof_index] = _Jw(j, dof_index);
}
}
// jacobian derivatives
offset_velocity = ToUblasVector(effector_velocity - joint_global_velocity);
_dJdqv = -cross(offset, _dJdqw) - cross(offset_velocity, ToUblasVector(joint_global_ang_vel));
for (int j=0; j<3; j++)
{
dJdq[6*body_idx + 0 + j] += _dJdqv(j);
dJdq[6*body_idx + 3 + j] += _dJdqw(j);
}
}
}
}
return bp::make_tuple(J, dJdq);
}
/////////////////////////////////////////
// Additional
void VpModel::addBody(bool flagControl)
{
int n = _nodes.size();
_nodes.resize(n + 1);
_boneTs.resize(n + 1);
//add body
Node* pNode = new Node("Left_Toes");
scalar density = 1000;
scalar width = 0.1;
scalar height = 0.1;
scalar length = 0.1;
pNode->body.AddGeometry(new vpBox(Vec3(width, height, length)));
pNode->body.SetInertia(BoxInertia(density, Vec3(width / 2., height / 2., length / 2.)));
//boneT = boneT * SE3(pyVec3_2_Vec3(cfgNode.attr("offset")));
//_boneTs[joint_index] = boneT;
SE3 newT;// = T * boneT;
pNode->body.SetFrame(newT);
_nodes[n] = pNode;
_boneTs[n] = newT;
if (flagControl == true)
_pWorld->AddBody(&pNode->body);
//create new joint
int parent_index = n - 1;
SE3 invLocalT;
Node* pParentNode = _nodes[parent_index];
pParentNode->body.SetJoint(&pNode->joint, Inv(_boneTs[parent_index])*Inv(invLocalT));
pNode->body.SetJoint(&pNode->joint, Inv(_boneTs[n]));
pNode->use_joint = true;
}
int VpModel::vpid2index(int id)
{
int index = 0;
for (int i = 0; i < getBodyNum(); i++)
{
if (id == index2vpid(i))
{
index = i;
break;
}
}
return index;
}
void VpModel::SetBodyColor(int id, unsigned char r, unsigned char g, unsigned char b, unsigned char a)
{
int index = vpid2index(id);
Node* pNode = _nodes[index];
pNode->color[0] = r;
pNode->color[1] = g;
pNode->color[2] = b;
pNode->color[3] = a;
}
void VpControlModel::setSpring(int body1Index, int body2Index, scalar elasticity, scalar damping, const object& p1, const object& p2, scalar initialDistance)
{
vpSpring* spring = new vpSpring;
Vec3 v1 = pyVec3_2_Vec3(p1);
Vec3 v2 = pyVec3_2_Vec3(p2);
spring->Connect(&(_nodes[body1Index]->body), &(_nodes[body2Index]->body), v1, v2);
spring->SetElasticity(elasticity);
spring->SetDamping(damping);
spring->SetInitialDistance(initialDistance);
_springs.push_back(spring);
}
// must be called at first:clear all torques and accelerations
bp::list VpControlModel::getInverseEquationOfMotion(object &invM, object &invMb)
{
bp::list ls;
ls.append(_nodes.size());
// M^-1 * tau - M^-1 * b = ddq
// ddq^T = [rootjointLin^T rootjointAng^T joints^T]^T
//vpBody *Hip = &(_nodes.at(0)->body);
//Hip->ResetForce();
//for(size_t i=0; i<_nodes.size(); i++)
//{
//_nodes.at(i)->body.ResetForce();
//_nodes.at(i)->joint.SetTorque(Vec3(0,0,0));
//}
//Hip->GetSystem()->ForwardDynamics();
//std::cout << Hip->GetGenAccelerationLocal();
//for(size_t i=1; i<_nodes.size(); i++)
//{
//std::cout << _nodes[i]->joint.GetAcceleration();
//}
int n = _nodes.size()-1;
int N = 6+3*n;
dse3 zero_dse3(0.0);
Vec3 zero_Vec3(0.0);
vpBody *Hip = &(_nodes.at(0)->body);
//save current ddq and tau
std::vector<Vec3> accBackup;
std::vector<Vec3> torBackup;
for(int i=0; i<n; i++)
{
vpBJoint *joint = &(_nodes.at(i+1)->joint);
accBackup.push_back(joint->GetAcceleration());
torBackup.push_back(joint->GetTorque());
}
// se3 hipAccBackup = Hip->GetGenAcceleration();
// dse3 hipTorBackup = Hip->GetForce();
Hip->ResetForce();
for(std::vector<int>::size_type i=0; i<_nodes.size(); i++)
{
_nodes.at(i)->body.ResetForce();
_nodes.at(i)->joint.SetTorque(Vec3(0,0,0));
}
//get invMb
Hip->ApplyLocalForce(zero_dse3, zero_Vec3);
for(int i=0; i<n; i++)
{
vpBJoint *joint = &(_nodes.at(i+1)->joint);
joint->SetTorque(zero_Vec3);
}
Hip->GetSystem()->ForwardDynamics();
se3 hipAcc_tmp = Hip->GetGenAccelerationLocal(); // represented in body frame
// se3 hipAcc_tmp = InvAd((_boneTs[0]), Hip->GetGenAccelerationLocal()); // represented in body frame
// se3 hipAcc_tmp = InvAd(_boneTs[0], Hip->GetGenAccelerationLocal());
// se3 hipVelLocal_joint = InvAd(_boneTs[0], Hip->GetGenVelocityLocal());
// Vec3 hipAngVelLocal_joint(hipVelLocal_joint[0], hipVelLocal_joint[1], hipVelLocal_joint[2]);
// Vec3 hipLinVelLocal_joint(hipVelLocal_joint[3], hipVelLocal_joint[4], hipVelLocal_joint[5]);
//
// hipAcc_tmp += Cross(hipAngVelLocal_joint, hipLinVelLocal_joint);
// Vec3 hipJointPosLocal = Inv(_boneTs[0]).GetPosition();
// SE3 hipFrame_joint = Hip->GetFrame() * Inv(_boneTs[0]);
// SE3 hipFrame_body = Hip->GetFrame();
//
// Vec3 hipAngVelGlobal = Hip->GetAngVelocity();
//
// se3 hipGenAccLocal_body = Hip->GetGenAccelerationLocal();
// Vec3 hipAngAccLocal_body(hipGenAccLocal_body[0], hipGenAccLocal_body[1], hipGenAccLocal_body[2]);
// Vec3 hipLinAccLocal_body(hipGenAccLocal_body[3], hipGenAccLocal_body[4], hipGenAccLocal_body[5]);
//
// Vec3 hipAngAccGlobal_body = Rotate(hipFrame_body, hipAngAccLocal_body);
// Vec3 hipLinAccGlobal_body = Rotate(hipFrame_body, hipLinAccLocal_body);
//
// Vec3 hipAngAccGlobal_joint = hipAngAccGlobal_body;
// Vec3 hipLinAccGlobal_joint = hipLinAccGlobal_body + Cross(hipAngAccGlobal_body, hipJointPosLocal)
// + Cross(hipAngVelGlobal, Cross(hipAngVelGlobal, hipJointPosLocal));
//
// Vec3 hipAngAccLocal_joint = InvRotate(hipFrame_joint, hipAngAccGlobal_joint);
// Vec3 hipLinAccLocal_joint = InvRotate(hipFrame_joint, hipLinAccGlobal_joint);
//
//// se3 hipAcc_tmp(hipAngAccGlobal_joint[0], hipAngAccGlobal_joint[1], hipAngAccGlobal_joint[2],
//// hipLinAccGlobal_joint[0], hipLinAccGlobal_joint[1], hipLinAccGlobal_joint[2]);
// se3 hipAcc_tmp(hipAngAccLocal_joint[0], hipAngAccLocal_joint[1], hipAngAccLocal_joint[2],
// hipLinAccLocal_joint[0], hipLinAccLocal_joint[1], hipLinAccLocal_joint[2]);
{
invMb[0] = -hipAcc_tmp[3];
invMb[1] = -hipAcc_tmp[4];
invMb[2] = -hipAcc_tmp[5];
invMb[3] = -hipAcc_tmp[0];
invMb[4] = -hipAcc_tmp[1];
invMb[5] = -hipAcc_tmp[2];
}
//std::cout << "Hip velocity: " << Hip->GetGenVelocity();
for(int i=0; i<n; i++)
{
Vec3 acc(0,0,0);
vpBJoint *joint = &(_nodes.at(i+1)->joint);
acc = joint->GetAcceleration();
for(int j=0; j<3; j++)
{
invMb[6+3*i+j] = -acc[j];
}
}
//get M
for(int i=0; i<N; i++)
{
Hip->ResetForce();
for(std::vector<int>::size_type i=0; i<_nodes.size(); i++)
{
_nodes.at(i)->body.ResetForce();
_nodes.at(i)->joint.SetTorque(Vec3(0,0,0));
}
dse3 genForceLocal(0.0);
if (i < 3) genForceLocal[i+3] = 1.0;
else if(i<6) genForceLocal[i-3] = 1.0;
for(int j=0; j<n; j++)
{
Vec3 torque(0., 0., 0.);
if ( i >= 6 && (i-6)/3 == j )
torque[ (i-6)%3 ] = 1.;
vpBJoint *joint = &(_nodes.at(j+1)->joint);
joint->SetTorque(torque);
}
Hip->ApplyLocalForce(genForceLocal, zero_Vec3);
Hip->GetSystem()->ForwardDynamics();
se3 hipAcc_tmp = Hip->GetGenAccelerationLocal();
//// se3 hipAcc_tmp_1 = Ad((_boneTs[0]), Hip->GetGenAccelerationLocal());
//// se3 hipAcc_tmp_1 = InvAd(_boneTs[0], Hip->GetGenAccelerationLocal());
//// se3 hipVelLocal_joint_1 = InvAd(_boneTs[0], Hip->GetGenVelocityLocal());
//// Vec3 hipAngVelLocal_joint_1(hipVelLocal_joint_1[0], hipVelLocal_joint_1[1], hipVelLocal_joint_1[2]);
//// Vec3 hipLinVelLocal_joint_1(hipVelLocal_joint_1[3], hipVelLocal_joint_1[4], hipVelLocal_joint_1[5]);
////
//// hipAcc_tmp_1 += Cross(hipAngVelLocal_joint_1, hipLinVelLocal_joint_1);
//
// Vec3 hipJointPosLocal = Inv(_boneTs[0]).GetPosition();
// SE3 hipFrame_joint = Hip->GetFrame() * Inv(_boneTs[0]);
// SE3 hipFrame_body = Hip->GetFrame();
//
// Vec3 hipAngVelGlobal = Hip->GetAngVelocity();
//
// se3 hipGenAccLocal_body = Hip->GetGenAccelerationLocal();
// Vec3 hipAngAccLocal_body(hipGenAccLocal_body[0], hipGenAccLocal_body[1], hipGenAccLocal_body[2]);
// Vec3 hipLinAccLocal_body(hipGenAccLocal_body[3], hipGenAccLocal_body[4], hipGenAccLocal_body[5]);
//
// Vec3 hipAngAccGlobal_body = Rotate(hipFrame_body, hipAngAccLocal_body);
// Vec3 hipLinAccGlobal_body = Rotate(hipFrame_body, hipLinAccLocal_body);
//
// Vec3 hipAngAccGlobal_joint = hipAngAccGlobal_body;
// Vec3 hipLinAccGlobal_joint = hipLinAccGlobal_body + Cross(hipAngAccGlobal_body, hipJointPosLocal)
// + Cross(hipAngVelGlobal, Cross(hipAngVelGlobal, hipJointPosLocal));
//
// Vec3 hipAngAccLocal_joint = InvRotate(hipFrame_joint, hipAngAccGlobal_joint);
// Vec3 hipLinAccLocal_joint = InvRotate(hipFrame_joint, hipLinAccGlobal_joint);
//
//// se3 hipAcc_tmp(hipAngAccGlobal_joint[0], hipAngAccGlobal_joint[1], hipAngAccGlobal_joint[2],
//// hipLinAccGlobal_joint[0], hipLinAccGlobal_joint[1], hipLinAccGlobal_joint[2]);
// se3 hipAcc_tmp(hipAngAccLocal_joint[0], hipAngAccLocal_joint[1], hipAngAccLocal_joint[2],
// hipLinAccLocal_joint[0], hipLinAccLocal_joint[1], hipLinAccLocal_joint[2]);
for (int j = 0; j < 3; j++)
{
invM[j][i] = hipAcc_tmp[j+3] + invMb[j];
}
for (int j = 3; j < 6; j++)
{
invM[j][i] = hipAcc_tmp[j-3] + invMb[j];
}
for(int j=0; j<n; j++)
{
Vec3 acc(0,0,0);
vpBJoint *joint = &(_nodes.at(j+1)->joint);
acc = joint->GetAcceleration();
for(int k=0; k<3; k++)
{
invM[6+3*j+k][i] = acc[k] + invMb[6+3*j+k];
}
}
}
// restore ddq and tau
for(int i=0; i<n; i++)
{
vpBJoint *joint = &(_nodes.at(i+1)->joint);
joint->SetAcceleration(accBackup.at(i));
joint->SetTorque(torBackup.at(i));
joint->SetAcceleration(Vec3(0., 0., 0.));
joint->SetTorque(Vec3(0., 0., 0.));
}
//Hip->SetGenAcceleration(hipAccBackup);
Hip->ResetForce();
// Hip->ApplyGlobalForce(hipTorBackup, zero_Vec3);
return ls;
}
bp::list VpControlModel::getEquationOfMotion(object& M, object& b)
{
bp::list ls;
ls.append(_nodes.size());
//for(int i=0; i<_nodes.size(); i++)
//{
//ls.append(_nodes.at(i)->name);
//ls.append(_nodes.at(i)->dof);
//}
//
//RMatrix ddq = get_ddq(), tau = get_tau(); // save current ddq and tau
//int n = getNumCoordinates();
//M.ReNew(n,n);
//set_ddq(Zeros(n,1));
//GSystem::calcInverseDynamics();
//b = get_tau();
//for (int i=0; i<n; i++) {
// RMatrix unit = Zeros(n,1);
// unit[i] = 1;
// set_ddq(unit);
// GSystem::calcInverseDynamics();
// get_tau(&M[i*n]);
// for (int j=0; j<n; j++) {
// M[i*n+j] -= b[j];
// }
//}
//set_ddq(ddq); set_tau(tau); // restore ddq and tau
// M * ddq + b = tau
// ddq^T = [rootjointLin^T rootjointAng^T joints^T]^T
int n = _nodes.size()-1;
int N = 6+3*n;
vpBody *Hip = &(_nodes.at(0)->body);
//save current ddq and tau
std::vector<Vec3> accBackup;
std::vector<Vec3> torBackup;
for(int i=0; i<n; i++)
{
vpBJoint *joint = &(_nodes.at(i+1)->joint);
accBackup.push_back(joint->GetAcceleration());
torBackup.push_back(joint->GetTorque());
}
se3 hipAccBackup = Hip->GetGenAcceleration();
dse3 hipTorBackup = Hip->GetForce();
//Hip->ResetForce();
//for(int i=0; i<_nodes.size(); i++)
//{
////_nodes.at(i)->body.ResetForce();
//_nodes.at(i)->joint.SetTorque(Vec3(0,0,0));
//}
//get b
std::vector<double> ddq;
for(int i=0; i<N; i++)
ddq.push_back(0.);
set_ddq_vp(ddq);
_nodes[0]->body.GetSystem()->InverseDynamics();
//get M
for(int i=0; i<N; i++)
{
ddq[i] = 1.;
if(i > 0)
ddq[i+1] = 0.;
_nodes[0]->body.GetSystem()->InverseDynamics();
}
// restore ddq and tau
Vec3 zero_Vec3(0.);
for(int i=0; i<n; i++)
{
vpBJoint *joint = &(_nodes.at(i+1)->joint);
joint->SetAcceleration(accBackup.at(i));
joint->SetTorque(torBackup.at(i));
}
Hip->SetGenAcceleration(hipAccBackup);
Hip->ResetForce();
Hip->ApplyGlobalForce(hipTorBackup, zero_Vec3);
return ls;
}
//void VpControlModel::stepKinematics(double dt, const object& acc)
//{
//Vec3 ddq = pyVec3_2_Vec3(acc);
//Vec3 dq(0.0);
//SE3 q;
//vpBJoint *joint = &(_nodes.at(2)->joint);
//dq = joint->GetVelocity() + ddq * dt;
//joint->SetVelocity(dq);
////q = joint->GetOrientation() * Exp(Axis(dq*dt));
//q = Exp(Axis(dq*dt))*joint->GetOrientation();
//joint->SetOrientation(q);
//}
#include <VP/vpWorld.h>
void VpControlModel::stepKinematics(double dt, const bp::list& accs)
{
vpBody *Hip = &(_nodes.at(0)->body);
Vec3 hipacc = pyVec3_2_Vec3(accs[0].slice(0,3));
Axis hipangacc(pyVec3_2_Vec3(accs[0].slice(3,6)));
{
se3 genAccBodyLocal(hipangacc, hipacc);
se3 genVelBodyLocal = Hip->GetGenVelocityLocal() + genAccBodyLocal*dt ;
Hip->SetGenVelocityLocal(genVelBodyLocal);
SE3 rootFrame = Hip->GetFrame() * Exp(dt*genVelBodyLocal);
Hip->SetFrame(rootFrame);
}
Vec3 ddq(0.0), dq(0.0), zero_Vec3(0.0);
SE3 q;
for(std::vector<int>::size_type i=1; i<_nodes.size(); ++i)
{
ddq = pyVec3_2_Vec3(accs[i]);
vpBJoint *joint = &(_nodes[i]->joint);
dq = joint->GetVelocity() + ddq * dt;
joint->SetVelocity(dq);
q = joint->GetOrientation() * Exp(Axis(dq*dt));
joint->SetOrientation(q);
}
for(std::vector<int>::size_type i=0; i<_nodes.size(); ++i)
_nodes[i]->body.UpdateGeomFrame();
se3 zero_se3(0.0);
Hip->ResetForce();
//for(int i=0; i<_nodes.size(); i++)
//{
////_nodes.at(i)->body.ResetForce();
//_nodes.at(i)->body.SetGenAcceleration(zero_se3);
//}
}
| 31.827426 | 163 | 0.636586 | [
"object",
"shape",
"vector"
] |
f0e2f5d3c8dbf8e504e24968fd3b38525cf13ab4 | 607 | cpp | C++ | Borcane/main.cpp | rusucosmin/Cplusplus | 0e95cd01d20b22404aa4166c71d5a9e834a5a21b | [
"MIT"
] | 11 | 2015-08-29T13:41:22.000Z | 2020-01-08T20:34:06.000Z | Borcane/main.cpp | rusucosmin/Cplusplus | 0e95cd01d20b22404aa4166c71d5a9e834a5a21b | [
"MIT"
] | null | null | null | Borcane/main.cpp | rusucosmin/Cplusplus | 0e95cd01d20b22404aa4166c71d5a9e834a5a21b | [
"MIT"
] | 5 | 2016-01-20T18:17:01.000Z | 2019-10-30T11:57:15.000Z | #include<fstream>
#include<math.h>
#include<stdlib.h>
using namespace std;
ifstream fin("borcane.in");
ofstream fout("borcane.out");
struct vector
{
long val,l;
};
long n,i,j,l,ok,s;
vector v[101],x[101];
int comp(const void *a,const void *b)
{
if(*(long *)a> *(long *)b)
return 1;
else
return -1;
}
int main()
{
fin>>n;
for(i=1;i<=n;i++)
{
fin>>v[i].val;
v[i].l=i;
}
qsort(v+1, n , sizeof(v[0]), comp);
i=1;
while(i<n)
{
while(v[i].val)
{
v[n].val+=2;
v[i].val--;
v[i+1].val--;
fout<<v[i].l<<v[i+1].l<<v[n].l<<endl;
}
i++;
}
return 0;
}
| 14.116279 | 40 | 0.517298 | [
"vector"
] |
f0f29cef28106d8a806785e1e0df7d47da1534a2 | 9,159 | cpp | C++ | src/game/world.cpp | CoryNull/gold | b990ec6f874434b6e46f838213b5f4936aa86792 | [
"Apache-2.0"
] | null | null | null | src/game/world.cpp | CoryNull/gold | b990ec6f874434b6e46f838213b5f4936aa86792 | [
"Apache-2.0"
] | null | null | null | src/game/world.cpp | CoryNull/gold | b990ec6f874434b6e46f838213b5f4936aa86792 | [
"Apache-2.0"
] | null | null | null | #include "world.hpp"
#include <BulletDynamics/ConstraintSolver/btSequentialImpulseConstraintSolver.h>
#include <BulletDynamics/Dynamics/btDiscreteDynamicsWorld.h>
#include <bgfx/bgfx.h>
#include <btBulletCollisionCommon.h>
#include "camera.hpp"
#include "engine.hpp"
#include "entity.hpp"
#include "graphics.hpp"
#include "physicsBody.hpp"
#include "shaderWireframe.hpp"
#include "transform.hpp"
namespace gold {
using namespace bgfx;
class btDebugDraw;
binary getWireframeShaderData(shaderType stype);
struct PosColorVertex {
float x, y, z;
float r, g, b, a;
};
struct DebugLine {
PosColorVertex p1;
PosColorVertex p2;
};
class btDebugDraw : public btIDebugDraw {
protected:
world w;
float lineWidth = 2;
shaderProgram program;
vertexLayout layout;
vertexBuffer vbh;
vector<DebugLine> lines;
int mode = DBG_DrawWireframe;
public:
btDebugDraw(world w) {
this->w = w;
program = shaderProgram::findInCache("Wireframe");
if (!program)
program = shaderProgram({
{"name", "Wireframe"},
{"vert",
shaderObject({
{"data", getWireframeShaderData(VertexShaderType)},
})},
{"frag", shaderObject({
{"data", getWireframeShaderData(
FragmentShaderType)},
})},
});
using a = vertexLayout::attrib;
using aT = vertexLayout::attribType;
layout = vertexLayout::findInCache("Wireframe");
if (!layout)
layout = vertexLayout({{"name", "Wireframe"}})
.begin()
.add(a::Position, aT::Float, 3)
.add(a::Color0, aT::Float, 4)
.end();
lines = vector<DebugLine>();
using uT = uniformType;
shaderProgram::createUniform("u_thickness", uT::Vec4);
}
void drawLine(
const btVector3& from,
const btVector3& to,
const btVector3& color) {
// TODO: override methods, get more use out of the layout
lines.push_back(DebugLine{
{
from.x(),
from.y(),
from.z(),
color.x(),
color.y(),
color.z(),
1.0f,
},
{
to.x(),
to.y(),
to.z(),
color.x(),
color.y(),
color.z(),
1.0f,
},
});
}
void clearLines() { lines.clear(); }
void flushLines() {
auto eng = w.getObject<engine>("engine");
auto cam = eng.getPrimaryCamera().getObject<camera>();
auto trans = cam.getTransform();
auto pos = trans.relative({});
const auto viewId = uint16_t(0);
auto vBinSize = sizeof(DebugLine) * lines.size() * 2;
auto vBin = binary();
vBin.resize(vBinSize, 0);
memcpy(vBin.data(), lines.data(), vBinSize);
vbh = vertexBuffer({
{"count", lines.size() * 2},
{"type", transientBufferType},
{"layout", layout},
});
vbh.update(vBin);
vbh.set(0);
float u_thickness[4] = {lineWidth, 0.0, 0.0, 0.0};
shaderProgram::setUniform("u_thickness", u_thickness);
program.setState({
{"type", "lines"},
{"MSAA", true},
{"lineAA", true},
});
program.submit(viewId);
}
void drawContactPoint(
const btVector3& PointOnB,
const btVector3& normalOnB,
btScalar distance,
int lifeTime,
const btVector3& color) {}
void reportErrorWarning(const char* warningString) {}
void draw3dText(
const btVector3& location, const char* textString) {}
void setDebugMode(int debugMode) { mode = debugMode; }
int getDebugMode() const { return mode; }
};
object& world::getPrototype() {
static object proto = obj({
{"bodies", list()},
{"gravity", vec3f(0, -9.8, 0)},
{"maxSubSteps", 1},
{"fixedTimeStep", 1.0 / 60.0},
});
return proto;
}
world::world() : object() {}
world::world(object config) : object(config) {
setParent(getPrototype());
}
var world::step(list args) {
auto fixedTimeStep = getFloat("fixedTimeStep");
auto timeStep = args.getFloat(0, fixedTimeStep);
auto maxSubSteps = getInt32("maxSubSteps");
auto bodies = getList("bodies");
auto dWorld =
(btDiscreteDynamicsWorld*)getPtr("dynamicsWorld");
dWorld->stepSimulation(
timeStep, maxSubSteps, fixedTimeStep);
auto comp = physicsBody();
auto body = (btRigidBody*)nullptr;
auto ent = entity();
auto trans = transform();
for (auto it = bodies.begin(); it != bodies.end(); ++it) {
if (
(comp = it->getObject<physicsBody>()) &&
(body = (btRigidBody*)comp.getPtr("body")) &&
(ent = comp.getObject<entity>("object")) &&
(trans = ent.getComponent({transform::getPrototype()})
.getObject<transform>())) {
auto wTrans = body->getWorldTransform();
auto rot = wTrans.getRotation();
auto pos = wTrans.getOrigin();
trans.setPosition({vec3f(pos.x(), pos.y(), pos.z())});
trans.setRotation(
{quatf(rot.x(), rot.y(), rot.z(), rot.w())});
} else {
it = bodies.erase(it);
}
}
return var();
}
var world::setGravity(list args) {
auto dWorld =
(btDiscreteDynamicsWorld*)getPtr("dynamicsWorld");
float g[3];
if (args.isAllNumber() && args.size() >= 3)
args.assign(typeFloat, g, 3);
else if (args.size() >= 1 && args[0].isVec3()) {
auto v = args[0];
g[0] = v.getFloat(0);
g[1] = v.getFloat(1);
g[2] = v.getFloat(2);
}
auto ret = vec3f(g[0], g[1], g[2]);
setVar("gravity", ret);
dWorld->setGravity(btVector3(g[0], g[1], g[2]));
return ret;
}
var world::raytrace(list args) {
float from[3];
float to[3];
args[0].getList().assign(typeFloat, from, 3);
args[1].getList().assign(typeFloat, to, 3);
return var();
}
var world::initialize(list args) {
setList("bodies", list({}));
auto engIt = args.find(engine::getPrototype());
if (engIt != args.end()) {
auto eng = engIt->getObject<engine>();
setObject("engine", eng);
} else {
return genericError("Expected engine to be first arg");
}
auto gravity = getVar("gravity");
auto collisionConfiguration =
new btDefaultCollisionConfiguration();
setPtr("collisionConfiguration", collisionConfiguration);
auto dispatcher =
new btCollisionDispatcher(collisionConfiguration);
setPtr("dispatcher", dispatcher);
auto broadphase = new btDbvtBroadphase();
setPtr("broadphase", broadphase);
auto solver = new btSequentialImpulseConstraintSolver;
setPtr("solver", solver);
auto dynamicsWorld = new btDiscreteDynamicsWorld(
dispatcher, broadphase, solver, collisionConfiguration);
setPtr("dynamicsWorld", dynamicsWorld);
dynamicsWorld->setGravity(btVector3(
gravity.getFloat(0),
gravity.getFloat(1),
gravity.getFloat(2)));
auto debugDrawer = new btDebugDraw(*this);
setPtr("debugDrawer", debugDrawer);
dynamicsWorld->setDebugDrawer(debugDrawer);
return var();
}
var world::destroy() {
auto dynamicsWorld =
(btDiscreteDynamicsWorld*)getPtr("dynamicsWorld");
if (dynamicsWorld) delete dynamicsWorld;
auto solver =
(btSequentialImpulseConstraintSolver*)getPtr("solver");
if (solver) delete solver;
auto broadphase = (btDbvtBroadphase*)getPtr("broadphase");
if (broadphase) delete broadphase;
auto dispatcher =
(btCollisionDispatcher*)getPtr("dispatcher");
if (dispatcher) delete dispatcher;
auto collisionConfiguration =
(btDefaultCollisionConfiguration*)getPtr(
"collisionConfiguration");
if (collisionConfiguration) delete collisionConfiguration;
auto debugDraw = (btDebugDraw*)getPtr("debugDrawer");
if (debugDraw) delete debugDraw;
empty();
return var();
}
var world::debugDraw() {
auto dynamicsWorld =
(btDiscreteDynamicsWorld*)getPtr("dynamicsWorld");
dynamicsWorld->debugDrawWorld();
return var();
}
binary getWireframeShaderData(shaderType stype) {
auto renderType = getRendererType();
switch (renderType) {
case bgfx::RendererType::Direct3D11:
case bgfx::RendererType::Direct3D12: {
switch (stype) {
case VertexShaderType:
return dx11_vs_wireframe;
case FragmentShaderType:
return dx11_fs_wireframe;
default:
break;
}
}
case bgfx::RendererType::Direct3D9: {
switch (stype) {
case VertexShaderType:
return dx9_vs_wireframe;
case FragmentShaderType:
return dx9_fs_wireframe;
default:
break;
}
}
case bgfx::RendererType::Metal: {
switch (stype) {
case VertexShaderType:
return metal_vs_wireframe;
case FragmentShaderType:
return metal_fs_wireframe;
default:
break;
}
}
case bgfx::RendererType::OpenGLES: {
switch (stype) {
case VertexShaderType:
return essl_vs_wireframe;
case FragmentShaderType:
return essl_fs_wireframe;
default:
break;
}
}
case bgfx::RendererType::OpenGL: {
switch (stype) {
case VertexShaderType:
return glsl_vs_wireframe;
case FragmentShaderType:
return glsl_fs_wireframe;
default:
break;
}
}
case bgfx::RendererType::Vulkan: {
switch (stype) {
case VertexShaderType:
return spirv_vs_wireframe;
case FragmentShaderType:
return spirv_fs_wireframe;
default:
break;
}
}
case bgfx::RendererType::Gnm:
case bgfx::RendererType::Nvn:
case bgfx::RendererType::Noop:
default:
break;
}
return binary();
}
} // namespace gold | 24.620968 | 80 | 0.648652 | [
"object",
"vector",
"transform"
] |
e7ca7fde05ed5f34aa76a4de5e0b8dc5487d8c89 | 30,655 | cpp | C++ | calculator.cpp | ghostofcoolidge/probability_compound_events_calculator | 304bdf3e1690c3613c89108dcb54d7abcb781ae2 | [
"MIT"
] | 1 | 2021-07-09T14:55:55.000Z | 2021-07-09T14:55:55.000Z | calculator.cpp | ghostofcoolidge/probability_compound_events_calculator | 304bdf3e1690c3613c89108dcb54d7abcb781ae2 | [
"MIT"
] | null | null | null | calculator.cpp | ghostofcoolidge/probability_compound_events_calculator | 304bdf3e1690c3613c89108dcb54d7abcb781ae2 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <conio.h>
#include <cmath>
#include <vector>
#include <sstream>
using namespace std;
double p1;
double t1;
double r1;
double n1;
string uinput;
bool isnum;
bool ischar;
string event;
string response = "y";
double independent_event(double &p, double &t, double &r, double &n, vector <int>fn, vector <int>fnr);
double dependent_event(double &p, double &t, double &r, double &n);
int calc_independent_event(double &p, double &t, double &r, double &n, vector <int>&fn, vector <int>&fnr, double &multiple, double &q);
void largeArrayFactorial();
double longDivideArrayNum(vector <int>&divisor, double &divisor_size, vector <int>÷nd, double ÷nd_size);
double oldlongDivideArrayNum(vector <int>&divisor, double &divisor_size, vector <int>÷nd, double ÷nd_size);
void longMultiplyArrayNum();
int multiply(double x,vector <int>&a ,int size);
int multiply_final(double x,vector <int>&a ,int size);
void printArrayNum(vector <int>ft);
void additionByTens(vector <int>&a, int sd);
double percentage;
bool isNumber(const string& str)
{
for (char const &c : str) {
if (std::isdigit(c) == 0) return false;
}
return true;
}
int main()
{
while (response == "y")
{
cout << "Are these independent (a) or dependent events? (b)? ";
cin >> event;
while (true)
{
if (event == "a"){
break;
}
if(event == "b") {
break;
}
cout << "\nERROR: please enter valid selection: independent (a) or dependent events (b)? ";
cout << "\nAre these independent (a) or dependent events? (b)? ";
cin >> event;
}
if (event == "a")
{
while (true)
{
cout << "\nPlease enter the total number of trials (limit 300): ";
cin >> uinput;
isnum = isNumber(uinput);
while (isnum == false)
{
cout << "\nERROR: Please enter a valid number: ";
continue;
}
n1 = std::stod(uinput);
while (n1 > 300)
{
cout << "\nERROR: Number must be less than 301.";
}
break;
}
cout << "\nPlease enter the number of desired outcome(s): ";
cin >> uinput;
isnum = isNumber(uinput);
while (isnum == false)
{
cout << "\nERROR: Please enter a valid number: ";
cin >> uinput;
isnum = isNumber(uinput);
}
p1 = std::stod(uinput);
cout <<"\nPlease enter the total number of outcomes: ";
cin >> uinput;
isnum = isNumber(uinput);
while (isnum == false)
{
cout << "\nERROR: Please enter a valid number: ";
cin >> uinput;
isnum = isNumber(uinput);
}
t1 = std::stod(uinput);
while (p1 > t1)
{
cout << "\nERROR: number of desired outcomes, " << p1 << " cannot exceed total number of outcomes, " << t1;
cout << "\nPlease enter the number of desired outcome(s): ";
cin >> uinput;
isnum = isNumber(uinput);
while (isnum == false)
{
cout << "\nERROR: Please enter a valid number: ";
cin >> uinput;
isnum = isNumber(uinput);
}
p1 = std::stod(uinput);
cout <<"\nPlease enter the total number of outcomes: ";
cin >> uinput;
isnum = isNumber(uinput);
while (isnum == false)
{
cout << "\nERROR: Please enter a valid number: ";
cin >> uinput;
isnum = isNumber(uinput);
}
t1 = std::stod(uinput);
}
cout << "\nPlease enter the number of times you wish to obtain number of desired outcome(s): ";
cin >> uinput;
isnum = isNumber(uinput);
while (isnum == false)
{
cout << "\nERROR: Please enter a valid number: ";
cin >> uinput;
isnum = isNumber(uinput);
}
r1 = std::stod(uinput);
while (r1 > n1)
{
cout << "\nERROR: Number of times you wish to obtain number of desired outcome(s), " << r1 << ", cannot exceed the number of trials, " << n1;
cout << ".\nPlease enter the number of times you wish to obtain number of desired outcome(s): ";
cin >> uinput;
isnum = isNumber(uinput);
while (isnum == false)
{
cout << "\nERROR: Please enter a valid number: ";
cin >> uinput;
isnum = isNumber(uinput);
}
r1 = std::stod(uinput);
while (true)
{
cout << "\nPlease enter the total number of trials (limit: 300): ";
cin >> uinput;
isnum = isNumber(uinput);
while (isnum == false)
{
cout << "\nERROR: Please enter a valid number: ";
continue;
}
n1 = std::stod(uinput);
while (n1 > 300)
{
cout << "\nERROR: Number must be less than 301.\n";
continue;
}
break;
}
}
vector <int> factn(1,1);
vector <int> factnr(1, 1);
independent_event(p1, t1, r1, n1, factn, factnr);
}
if (event == "b")
{
while (true)
{
cout << "\nPlease enter the total number of trials (limit 20): ";
cin >> uinput;
isnum = isNumber(uinput);
if (isnum == false)
{
cout << "\nERROR: invalid input!";
continue;
}
n1 = std::stod(uinput);
if (n1 > 21)
{
cout << "\nERROR: number must be less than 21.";
continue;
}
break;
}
cout <<"\nPlease enter the desired number of outcomes: ";
cin >> uinput;
isnum = isNumber(uinput);
while (isnum == false)
{
cout << "\nERROR: Please enter a valid number: ";
cin >> uinput;
isnum = isNumber(uinput);
}
p1 = std::stod(uinput);
cout <<"\nPlease enter the total number of outcomes: ";
cin >> uinput;
isnum = isNumber(uinput);
while (isnum == false)
{
cout << "\nERROR: Please enter a valid number: ";
cin >> uinput;
isnum = isNumber(uinput);
}
t1 = std::stod(uinput);
while ((p1 >= t1) || (t1 <= n1) )
{
cout << "\nERROR: total number of outcomes, " << t1 << ", must be bigger than desired outcomes, "<< p1 << ", but smaller than number of trials, " << n1;
while (true)
{
cout << "\nPlease enter the total number of trials (limit 20): ";
cin >> uinput;
isnum = isNumber(uinput);
if (isnum == false)
{
cout << "\nERROR: invalid input!\n";
continue;
}
n1 = std::stod(uinput);
if (n1 > 21)
{
cout << "\nERROR: number must be less than 21.";
continue;
}
break;
}
cout <<"\nPlease enter the desired number of outcomes: ";
cin >> uinput;
isnum = isNumber(uinput);
while (isnum == false)
{
cout << "\nERROR: Please enter a valid number: ";
cin >> uinput;
isnum = isNumber(uinput);
}
p1 = std::stod(uinput);
cout <<"\nPlease enter the total number of outcomes: ";
cin >> uinput;
isnum = isNumber(uinput);
while (isnum == false)
{
cout << "\nERROR: Please enter a valid number: ";
cin >> uinput;
isnum = isNumber(uinput);
}
t1 = std::stod(uinput);
}
cout << "\nPlease enter the number of times you wish to obtain number of desired outcome(s): ";
cin >> uinput;
isnum = isNumber(uinput);
while (isnum == false)
{
cout << "\nERROR: Please enter a valid number: ";
cin >> uinput;
isnum = isNumber(uinput);
}
r1 = std::stod(uinput);
while (r1 > p1)
{
cout << "\nERROR: total number of times you wish to obtain number of desired outcome(s), " << r1 << ", cannot exceed total number of desired outcomes, " << p1 << ".";
cout <<"\nPlease enter the desired number of outcomes: ";
cin >> uinput;
isnum = isNumber(uinput);
while (isnum == false)
{
cout << "\nERROR: Please enter a valid number: ";
cin >> uinput;
isnum = isNumber(uinput);
}
p1 = std::stod(uinput);
cout << "\nPlease enter the number of times you wish to obtain number of desired outcome(s): ";
cin >> uinput;
isnum = isNumber(uinput);
while (isnum == false)
{
cout << "\nERROR: Please enter a valid number: ";
cin >> uinput;
isnum = isNumber(uinput);
}
r1 = std::stod(uinput);
}
vector <int> factn(1,1);
vector <int> factnr(1, 1);
percentage = dependent_event(p1,t1,r1,n1);
cout << "\nanswer is " << percentage << "%\n";
}
cout << "\n\nWould you like to calculate another probability? (y) or (n): ";
cin >> response;
while (true)
{
if (response == "y")
{
break;
}
if (response == "n")
{
break;
}
cout << "\nInvalid input!";
cout << "\nWould you like to calculate another probability? (y) or (n): ";
}
}
return 0;
}
double independent_event(double &p, double &t, double &r, double &n, vector <int>fn, vector <int>fnr) {
string a1;
double p1 = (*&p/ *&t);
double q = (1 - p1);
double percentage = 0;
double multiple;
vector <int> hundred(3, NULL);
hundred[0] = 0;
hundred[1] = 0;
hundred[2] = 1;
double hundred_size = 3;
cout << "\nAt least (a), at most (b) or exact (c)? ";
cin >> a1;
while (true)
{
if (a1 == "a")
{
break;
}
if (a1 == "b")
{
break;
}
if (a1 == "c")
{
break;
}
cout << "\nERROR; please enter valid selection: at least (a), at most (b), or exact (c) ";
cin >> a1;
}
if (a1 == "c")
{
int fin_dec_place = calc_independent_event(p1, t, r, n, fn, fnr,multiple, q);
cout << "\n\nThe answer is: ~";
bool improbable_check = true;
bool definite_check = true;
if (fn.size() >= fin_dec_place)
{
for (int j = (fn.size() - 1); j >= (fn.size() - 3); j--)
{
if (fn[j] > 0)
{
improbable_check = false;
}
if (fn[j] < 9)
{
definite_check = false;
}
cout << fn[j];
if (j == (fin_dec_place))
{
cout <<".";
}
}
}
else
{
cout << ".";
for (int i = (fin_dec_place - fn.size()); i > 0; i--)
{
cout << "0";
}
for (int j = (fn.size() - 1); j >= 0; j--)
{
if (fn[j] > 0)
{
improbable_check = false;
}
if (fn[j] < 9)
{
definite_check = false;
}
cout << fn[j];
}
}
cout << "% ";
if (improbable_check)
{
cout << " (chances are virtually zero)";
}
if (definite_check)
{
cout << " (chances are practically 100%)";
}
cout << "\n\n";
return percentage;
}
if (a1 == "a")
{
double final_answer = 0;
string final2string;
while (*&r <= *&n)
{
string bresult = "";
double b2num;
vector <int> fn(1,1);
vector <int> fnr(1, 1);
int fin_dec_place = calc_independent_event(p1, t, r, n, fn, fnr,multiple, q);
for (int i = (fn.size() - 1); i >= 0; i--)
{
bresult += to_string(fn[i]);
}
if (bresult.size() < fin_dec_place)
{
for (int i = 0; i < fin_dec_place; i++)
{
bresult.insert(bresult.begin(), '0');
}
*&r += 1;
// continue;
}
fin_dec_place = bresult.size() - fin_dec_place;
bresult.insert(fin_dec_place, ".");
b2num = std::stod(bresult);
final_answer += b2num;
*&r += 1;
}
int exponent = 1;
final_answer = final_answer * pow(10,1);
int int_fa = 0;
int_fa += final_answer;
while (true)
{
if (int_fa > 0)
{
break;
}
else
{
exponent ++;
final_answer = final_answer * pow(10,1);
int_fa = 0;
int_fa += final_answer;
}
}
int_fa+= 1;
final_answer = int_fa;
final_answer = final_answer / pow(10,exponent);
cout << "\n\nthe answer is";
if (final_answer > 99)
{
cout << " over 99%!\n\n";
}
else
{
cout << ": ~" << final_answer << "%\n\n";
}
return percentage;
}
if (a1 == "b")
{
double final_answer = 0;
string final2string;
while (*&r >= 0)
{
string bresult = "";
double b2num;
vector <int> fn(1,1);
vector <int> fnr(1, 1);
int fin_dec_place = calc_independent_event(p1, t, r, n, fn, fnr,multiple, q);
for (int i = (fn.size() - 1); i >= 0; i--)
{
bresult += to_string(fn[i]);
}
if (bresult.size() < fin_dec_place)
{
for (int i = 0; i < fin_dec_place; i++)
{
bresult.insert(bresult.begin(), '0');
}
*&r -= 1;
// continue;
}
fin_dec_place = bresult.size() - fin_dec_place;
bresult.insert(fin_dec_place, ".");
b2num = std::stod(bresult);
final_answer += b2num;
*&r -= 1;
}
int exponent = 1;
final_answer = final_answer * pow(10,1);
int int_fa = 0;
int_fa += final_answer;
while (true)
{
if (int_fa > 0)
{
break;
}
else
{
exponent ++;
final_answer = final_answer * pow(10,1);
int_fa = 0;
int_fa += final_answer;
}
}
int_fa+= 1;
final_answer = int_fa;
final_answer = final_answer / pow(10,exponent);
cout << "\n\nthe answer is";
if (final_answer > 99)
{
cout << " over 99%!\n\n";
}
else
{
cout << ": ~" << final_answer << "%\n\n";
}
}
return percentage;
}
double dependent_event(double &p, double &t, double &r, double &n) {
string a1;
int index_0;
int index_1;
int index_2;
cout << "\nAt least (a), at most (b) or exact (c)? ";
cin >> a1;
while (true)
{
if (a1 == "a")
{
break;
}
if (a1 == "b")
{
break;
}
if (a1 == "c")
{
break;
}
cout << "\nERROR; please enter valid selection: at least (a), at most (b), or exact (c) ";
cin >> a1;
}
int trial = 0;
int final_calculations = 6;
int chances_losing = (*&t - *&p);
int size;
double answer = 0;
double y;
double x;
vector <double> calculations(6, 1);
vector <double> temp_calc(6, 1);
while (trial < *&n)
{
if (trial == 0)
{
calculations[0] = double(*&p / *&t);
calculations[1] = 1;
calculations[2] = 0;
calculations[3] = (*&p / *& t);
calculations[4] = 0;
calculations[5] = 1;
trial += 1;
temp_calc.clear();
continue;
}
for (int i = 0; i < calculations.size(); i++)
{
temp_calc.push_back(calculations[i]);
}
calculations.clear();
size = temp_calc.size();
for (int i = 0; i < size / 3; i++)
{
index_0 = (0 + (i * 3));
index_1 = (1 + (i * 3));
index_2 = (2 + (i*3));
y = temp_calc[index_0] * ((chances_losing - temp_calc[index_2]) / (*&t - trial));
calculations.push_back(y);
calculations.push_back(temp_calc[index_1]);
calculations.push_back(temp_calc[index_2] + 1);
x = temp_calc[index_0] * ((chances_losing - temp_calc[index_1]) / (*&t - trial));
calculations.push_back(x);
calculations.push_back(temp_calc[index_1]+ 1);
calculations.push_back(temp_calc[index_2]);
}
trial += 1;
temp_calc.clear();
}
if (a1 == "c")
{
size = calculations.size();
for (int i = 0; i < size / 3; i++)
{
index_0 = (0 + (i * 3));
index_1 = (1 + (i * 3));
if (calculations[index_1] == *&r)
{
answer += calculations[index_0];
}
}
}
if (a1 == "a")
{
size = calculations.size();
for (int i = 0; i < size / 3; i++)
{
index_0 = (0 + (i * 3));
index_1 = (1 + (i * 3));
if (calculations[index_1] >= *&r)
{
answer += calculations[index_0];
}
}
}
if (a1 == "b")
{
size = calculations.size();
for (int i = 0; i < size / 3; i++)
{
index_0 = (0 + (i * 3));
index_1 = (1 + (i * 3));
if (calculations[index_1] <= *&r)
{
answer += calculations[index_0];
}
}
}
return answer;
}
double longDivideArrayNum(vector <int>&divisor, double &divisor_size, vector <int>÷nd, double ÷nd_size)
{
int size_difference = (dividend_size - divisor_size) - 1;
int temp_size_difference = 0;
temp_size_difference += size_difference;
int leftover;
int carry;
int zero_counter;
vector <int> answer(1,0);
string stranswer;
zero_counter = 0;
carry = 0;
int check = 0;
int temp_i;
int str2int;
string indchar;
for (int i = 0; i < size_difference; i++)
{
answer.insert(answer.begin(), 0);
}
for (int i = 0; i < size_difference; i++)
{
divisor.insert(divisor.begin(), 0);
divisor_size +=1;
}
while (dividend_size >= divisor_size)
{
if (dividend_size == divisor_size)
{
for (int i = divisor_size; i <= 0; i--)
{
if (divisor[i] > dividend[i])
{
check = 1;
break;
}
}
}
if (check == 1)
{
break;
}
else
{
additionByTens(answer, size_difference);
for (int i = 0; i < divisor_size; i++)
{
temp_i = 0;
if (divisor[i] > dividend[i])
{
leftover = divisor[i] - dividend[i];
leftover = 10 - leftover;
dividend[i] = leftover;
temp_i = i + 1;
while (true)
{
if (dividend[temp_i] > 0)
{
dividend[temp_i] -= 1;
break;
}
else
{
dividend[temp_i] = 9;
temp_i += 1;
}
}
}
else
{
dividend[i] -= divisor[i];
}
}
for (int i = (dividend_size - 1); i >= 0; i--)
{
if (dividend[i] == 0)
{
dividend.pop_back();
dividend_size -= 1;
if (size_difference >= 1)
{
divisor.erase(divisor.begin());
divisor_size -= 1;
size_difference-= 1;
}
}
else
{
break;
}
}
}
}
dividend.clear();
for (int i = 0; i < answer.size(); i++)
{
dividend.insert(dividend.begin(),answer[i]);
}
dividend_size = dividend.size();
int dp = dividend_size - temp_size_difference;
return dp;
}
int multiply(double x,vector <int>&a ,int size)
{
x = floor(x * 1000);
int carry=0,i,p;
for(i=0;i<size;++i)
{
p=a[i]*x+carry;
a[i]=p%10;
carry=p/10;
}
while(carry!=0)
{
a.push_back((carry%10));
carry=carry/10;
size++;
}
a.erase(a.begin());
a.erase(a.begin());
a.erase(a.begin());
size--;
size--;
size--;
return size;
}
int multiply_final(double x,vector <int>&a ,int size)
{
size = a.size();
bool exponent_found = false;
std::ostringstream streamObj2;
streamObj2 << x;
std::string strObj2 = streamObj2.str();
string exponent = "";
int exponent2num;
for (int i = 0; i < (strObj2.size() - 1); i++)
{
if (strObj2[i] == '-')
{
exponent_found = true;
i++;
exponent+= strObj2[i];
i++;
exponent+= strObj2[i];
break;
}
continue;
}
if (exponent_found)
{
exponent2num = std::stoi(exponent);
}
else
{
exponent2num = size;
}
x = floor(x * pow(10,(exponent2num + 2)));
int carry=0,i,p;
for(i=0;i<size;++i)
{
p=a[i]*x+carry;
a[i]=p%10;
carry=p/10;
}
while(carry!=0)
{
a.push_back((carry%10));
carry=carry/10;
size++;
}
exponent2num++;
exponent2num++;
return exponent2num;
}
int calc_independent_event(double &p, double &t, double &r, double &n, vector <int>&fn, vector <int>&fnr, double &multiple, double &q)
{
double factn_size, factnr_size;
factn_size = 1;
factnr_size = 1;
for(double i=2;i<=*&n;++i)
{
if (i <= *&r)
{
continue;
}
factn_size = multiply(i,fn,factn_size);
}
int nr;
nr = (*&n - *&r);
for(double i=2;i<=nr;++i)
{
factnr_size = multiply(i,fnr,factnr_size);
}
int dec_place = longDivideArrayNum(fnr, factnr_size, fn, factn_size);
multiple = pow(*&p, *&r) * pow(q, (*&n - *&r)) * 100;
int fin_dec_place = multiply_final(multiple, fn, factn_size);
return fin_dec_place;
}
void printArrayNum(vector <int>ArrayNum)
{
cout << "\nAMOUNT OF DIGITS:" << ArrayNum.size() <<"\n";
for (int i = (ArrayNum.size() - 1); i >= 0; i--)
{
cout << ArrayNum[i];
}
cout << "\n\n";
}
void additionByTens(vector <int>&a, int sd)
{
string straddition = "1";
for (int i = 0; i < sd; i++)
{
straddition+= "0";
}
int carry = 1;
int INDEX_NUMBER = a.size() - straddition.size();
int size = 0;
size+= straddition.size();
while (true)
{
if (carry == 0)
{
break;
}
else
{
carry--;
if (a[INDEX_NUMBER] == 9)
{
carry ++;
a[INDEX_NUMBER] = 0;
size++;
if (size > a.size())
{
a.insert(a.begin(),1);
break;
}
else
{
INDEX_NUMBER--;
continue;
}
}
else
{
a[INDEX_NUMBER]++;
continue;
}
}
}
}
double oldlongDivideArrayNum(vector <int>&divisor, double &divisor_size, vector <int>÷nd, double ÷nd_size)
{
int size_difference = (dividend_size - divisor_size) - 1;
int temp_size_difference = 0;
temp_size_difference += size_difference;
int leftover;
int carry;
int zero_counter;
long long int answer;
answer = 0;
string stranswer;
zero_counter = 0;
carry = 0;
int check = 0;
int temp_i;
int str2int;
string indchar;
for (int i = 0; i < size_difference; i++)
{
divisor.insert(divisor.begin(), 0);
divisor_size +=1;
}
while (dividend_size >= divisor_size)
{
if (dividend_size == divisor_size)
{
for (int i = divisor_size; i <= 0; i--)
{
if (divisor[i] > dividend[i])
{
check = 1;
break;
}
}
}
if (check == 1)
{
break;
}
else
{
answer += 1* pow(10, size_difference);
for (int i = 0; i < divisor_size; i++)
{
temp_i = 0;
if (divisor[i] > dividend[i])
{
leftover = divisor[i] - dividend[i];
leftover = 10 - leftover;
dividend[i] = leftover;
temp_i = i + 1;
while (true)
{
if (dividend[temp_i] > 0)
{
dividend[temp_i] -= 1;
break;
}
else
{
dividend[temp_i] = 9;
temp_i += 1;
}
}
}
else
{
dividend[i] -= divisor[i];
}
}
for (int i = (dividend_size - 1); i >= 0; i--)
{
if (dividend[i] == 0)
{
dividend.pop_back();
dividend_size -= 1;
if (size_difference >= 1)
{
divisor.erase(divisor.begin());
divisor_size -= 1;
size_difference-= 1;
}
}
else
{
break;
}
}
}
}
stranswer = to_string(answer);
dividend.clear();
for (int i = (stranswer.length() - 1); i >= 0; i--)
{
indchar = stranswer[i];
str2int = std::stoi(indchar);
dividend.push_back(str2int);
}
dividend_size = dividend.size();
int dp = dividend_size - temp_size_difference;
return dp;
}
| 29.618357 | 183 | 0.391258 | [
"vector"
] |
e7ce1c19fa14f8483965707f66cd7a296812ecd8 | 4,556 | hpp | C++ | OptFrame/Heuristics/ILS/BasicILSPerturbation.hpp | 216k155/bft-pos | 80c1c84b8ca9a5c1c7462b21b011c89ae97666ae | [
"MIT"
] | 2 | 2018-05-24T11:04:12.000Z | 2020-03-03T13:37:07.000Z | OptFrame/Heuristics/ILS/BasicILSPerturbation.hpp | 216k155/bft-pos | 80c1c84b8ca9a5c1c7462b21b011c89ae97666ae | [
"MIT"
] | null | null | null | OptFrame/Heuristics/ILS/BasicILSPerturbation.hpp | 216k155/bft-pos | 80c1c84b8ca9a5c1c7462b21b011c89ae97666ae | [
"MIT"
] | 1 | 2019-06-06T16:57:49.000Z | 2019-06-06T16:57:49.000Z | // OptFrame - Optimization Framework
// Copyright (C) 2009-2015
// http://optframe.sourceforge.net/
//
// This file is part of the OptFrame optimization framework. This framework
// is free software; you can redistribute it and/or modify it under the
// terms of the GNU Lesser General Public License v3 as published by the
// Free Software Foundation.
// This framework 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 v3 for more details.
// You should have received a copy of the GNU Lesser General Public License v3
// along with this library; see the file COPYING. If not, write to the Free
// Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
// USA.
#ifndef OPTFRAME_BASICILSPerturbation_HPP_
#define OPTFRAME_BASICILSPerturbation_HPP_
#include <math.h>
#include <vector>
#include "../../NS.hpp"
#include "../../RandGen.hpp"
#include "../../ComponentBuilder.h"
#include "ILS.h"
namespace optframe
{
template<class R, class ADS = OPTFRAME_DEFAULT_ADS>
class BasicILSPerturbation: public ILS, public Component
{
private:
Evaluator<R, ADS>& evaluator;
int pMin;
int pMax;
vector<NS<R, ADS>*> ns;
RandGen& rg;
public:
BasicILSPerturbation(Evaluator<R, ADS>& e, int _pMin, int _pMax, vector<NS<R, ADS>*>& _ns, RandGen& _rg) :
evaluator(e), pMin(_pMin), pMax(_pMax), ns(_ns), rg(_rg)
{
if(pMax < pMin)
{
cout << "BasicILSPerturbation warning: pMax > pMin! Swapping both." << endl;
int aux = pMax;
pMax = pMin;
pMin = aux;
}
if(ns.size()==0)
cout << "BasicILSPerturbation warning: empty neighborhood list." << endl;
}
BasicILSPerturbation(Evaluator<R, ADS>& e, int _pMin, int _pMax, NS<R, ADS>& _ns, RandGen& _rg) :
evaluator(e), pMin(_pMin), pMax(_pMax), rg(_rg)
{
ns.push_back(&_ns);
if(pMax < pMin)
{
cout << "BasicILSPerturbation warning: pMax > pMin! Swapping both." << endl;
int aux = pMax;
pMax = pMin;
pMin = aux;
}
if(ns.size()==0)
cout << "BasicILSPerturbation warning: empty neighborhood list." << endl;
}
virtual ~BasicILSPerturbation()
{
}
void add_ns(NS<R, ADS>& _ns)
{
ns.push_back(&_ns);
}
void perturb(Solution<R, ADS>& s, Evaluation& e, SOSC& stopCriteria)
{
for (int i = pMin; i < pMax; i++)
{
int nk = rand() % ns.size();
Move<R, ADS>* mp = ns[nk]->validRandomMoveSolution(s);
if (!mp)
{
cout << "BasicILSPerturbation warning: perturbation found no valid move for neighborhood: ";
ns[nk]->print();
}
else
{
Move<R, ADS>& m = *mp;
Component::safe_delete(m.applyUpdateSolution(e, s));
delete &m;
}
}
evaluator.reevaluateSolution(e, s); // updates 'e'
}
virtual string id() const
{
return idComponent();
}
static string idComponent()
{
stringstream ss;
ss << Component::idComponent() << ":" << ILS::family() << "basic_pert";
return ss.str();
}
};
template<class R, class ADS = OPTFRAME_DEFAULT_ADS>
class BasicILSPerturbationBuilder : public ComponentBuilder<R, ADS>
{
public:
virtual ~BasicILSPerturbationBuilder()
{
}
virtual Component* buildComponent(Scanner& scanner, HeuristicFactory<R, ADS>& hf, string family = "")
{
Evaluator<R, ADS>* eval;
hf.assign(eval, scanner.nextInt(), scanner.next()); // reads backwards!
int pMin = scanner.nextInt();
int pMax = scanner.nextInt();
vector<NS<R, ADS>*> ns_list;
hf.assignList(ns_list, scanner.nextInt(), scanner.next()); // reads backwards!
return new BasicILSPerturbation<R, ADS>(*eval, pMin, pMax, ns_list, hf.getRandGen());
}
virtual vector<pair<string, string> > parameters()
{
vector<pair<string, string> > params;
params.push_back(make_pair(Evaluator<R, ADS>::idComponent(), "evaluation function"));
params.push_back(make_pair("OptFrame:int", "pMin: min number of moves"));
params.push_back(make_pair("OptFrame:int", "pMax: max number of moves"));
stringstream ss;
ss << NS<R, ADS>::idComponent() << "[]";
params.push_back(make_pair(ss.str(), "list of neighborhood structures"));
return params;
}
virtual bool canBuild(string component)
{
return component == BasicILSPerturbation<R, ADS>::idComponent();
}
static string idComponent()
{
stringstream ss;
ss << ComponentBuilder<R, ADS>::idComponent() << ILS::family() << "basic_pert";
return ss.str();
}
virtual string id() const
{
return idComponent();
}
};
}
#endif /*OPTFRAME_BASICILSPerturbation_HPP_*/
| 25.171271 | 107 | 0.682177 | [
"vector"
] |
e7cfc37d252bd9e178b1e677b89ee8f65626bae7 | 39,230 | cpp | C++ | tinygizmo/tiny-gizmo.cpp | ousttrue/tinygizmo | 0eb067c4a942af0105097c653b697fe234e94b07 | [
"Unlicense"
] | null | null | null | tinygizmo/tiny-gizmo.cpp | ousttrue/tinygizmo | 0eb067c4a942af0105097c653b697fe234e94b07 | [
"Unlicense"
] | null | null | null | tinygizmo/tiny-gizmo.cpp | ousttrue/tinygizmo | 0eb067c4a942af0105097c653b697fe234e94b07 | [
"Unlicense"
] | null | null | null | // This is free and unencumbered software released into the public domain.
// For more information, please refer to <http://unlicense.org>
#include "tiny-gizmo.hpp"
#include <assert.h>
#include <chrono>
#include <functional>
#include <iostream>
#include <map>
#include <memory>
#include <minalg.h>
#include <string>
#include <vector>
using namespace minalg;
///////////////////////
// Utility Math //
///////////////////////
struct rigid_transform {
rigid_transform() {}
rigid_transform(const minalg::float4 &orientation,
const minalg::float3 &position, const minalg::float3 &scale)
: orientation(orientation), position(position), scale(scale) {}
rigid_transform(const minalg::float4 &orientation,
const minalg::float3 &position, float scale)
: orientation(orientation), position(position), scale(scale) {}
rigid_transform(const minalg::float4 &orientation,
const minalg::float3 &position)
: orientation(orientation), position(position) {}
minalg::float3 position{0, 0, 0};
minalg::float4 orientation{0, 0, 0, 1};
minalg::float3 scale{1, 1, 1};
bool uniform_scale() const {
return scale.x == scale.y && scale.x == scale.z;
}
minalg::float4x4 matrix() const {
return {{qxdir(orientation) * scale.x, 0},
{qydir(orientation) * scale.y, 0},
{qzdir(orientation) * scale.z, 0},
{position, 1}};
}
minalg::float3 transform_vector(const minalg::float3 &vec) const {
return qrot(orientation, vec * scale);
}
minalg::float3 transform_point(const minalg::float3 &p) const {
return position + transform_vector(p);
}
minalg::float3 detransform_point(const minalg::float3 &p) const {
return detransform_vector(p - position);
}
minalg::float3 detransform_vector(const minalg::float3 &vec) const {
return qrot(qinv(orientation), vec) / scale;
}
};
static const float EPSILON = 0.001f;
inline bool fuzzy_equality(float a, float b, float eps = EPSILON) {
return std::abs(a - b) < eps;
}
inline bool fuzzy_equality(minalg::float3 a, minalg::float3 b,
float eps = EPSILON) {
return fuzzy_equality(a.x, b.x) && fuzzy_equality(a.y, b.y) &&
fuzzy_equality(a.z, b.z);
}
inline bool fuzzy_equality(minalg::float4 a, minalg::float4 b,
float eps = EPSILON) {
return fuzzy_equality(a.x, b.x) && fuzzy_equality(a.y, b.y) &&
fuzzy_equality(a.z, b.z) && fuzzy_equality(a.w, b.w);
}
inline bool operator!=(const rigid_transform &a, const rigid_transform &b) {
return (!fuzzy_equality(a.position, b.position) ||
!fuzzy_equality(a.orientation, b.orientation) ||
!fuzzy_equality(a.scale, b.scale));
}
struct geometry_vertex {
minalg::float3 position, normal;
minalg::float4 color;
};
struct geometry_mesh {
std::vector<geometry_vertex> vertices;
std::vector<minalg::uint3> triangles;
};
///////////////////////
// Utility Math //
///////////////////////
static const float4x4 Identity4x4 = {
{1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {0, 0, 0, 1}};
static const float3x3 Identity3x3 = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}};
static const float tau = 6.28318530718f;
void flush_to_zero(float3 &f) {
if (std::abs(f.x) < 0.02f)
f.x = 0.f;
if (std::abs(f.y) < 0.02f)
f.y = 0.f;
if (std::abs(f.z) < 0.02f)
f.z = 0.f;
}
// 32 bit Fowler�Noll�Vo Hash
uint32_t hash_fnv1a(const std::string &str) {
static const uint32_t fnv1aBase32 = 0x811C9DC5u;
static const uint32_t fnv1aPrime32 = 0x01000193u;
uint32_t result = fnv1aBase32;
for (auto &c : str) {
result ^= static_cast<uint32_t>(c);
result *= fnv1aPrime32;
}
return result;
}
float3 snap(const float3 &value, const float snap) {
if (snap > 0.0f)
return float3(floor(value / snap) * snap);
return value;
}
float4 make_rotation_quat_axis_angle(const float3 &axis, float angle) {
return {axis * std::sin(angle / 2), std::cos(angle / 2)};
}
float4 make_rotation_quat_between_vectors_snapped(const float3 &from,
const float3 &to,
const float angle) {
auto a = normalize(from);
auto b = normalize(to);
auto snappedAcos = std::floor(std::acos(dot(a, b)) / angle) * angle;
return make_rotation_quat_axis_angle(normalize(cross(a, b)), snappedAcos);
}
template <typename T> T clamp(const T &val, const T &min, const T &max) {
return std::min(std::max(val, min), max);
}
struct gizmo_mesh_component {
geometry_mesh mesh;
float4 base_color, highlight_color;
};
struct gizmo_renderable {
geometry_mesh mesh;
float4 color;
};
struct Ray {
float3 origin, direction;
Ray(const float3 &o, const float3 &d) : origin(o), direction(d) {}
Ray(const std::array<float, 3> &o, const std::array<float, 3> &d)
: origin(*((float3 *)&o)), direction(*((float3 *)&d)) {}
};
Ray transform(const rigid_transform &p, const Ray &r) {
return {p.transform_point(r.origin), p.transform_vector(r.direction)};
}
Ray detransform(const rigid_transform &p, const Ray &r) {
return {p.detransform_point(r.origin), p.detransform_vector(r.direction)};
}
float3 transform_coord(const float4x4 &transform, const float3 &coord) {
auto r = mul(transform, float4(coord, 1));
return (r.xyz() / r.w);
}
float3 transform_vector(const float4x4 &transform, const float3 &vector) {
return mul(transform, float4(vector, 0)).xyz();
}
void transform(const float scale, Ray &r) {
r.origin *= scale;
r.direction *= scale;
}
void detransform(const float scale, Ray &r) {
r.origin /= scale;
r.direction /= scale;
}
/////////////////////////////////////////
// Ray-Geometry Intersection Functions //
/////////////////////////////////////////
bool intersect_ray_plane(const Ray &ray, const float4 &plane, float *hit_t) {
float denom = dot(plane.xyz(), ray.direction);
if (std::abs(denom) == 0)
return false;
if (hit_t)
*hit_t = -dot(plane, float4(ray.origin, 1)) / denom;
return true;
}
bool intersect_ray_triangle(const Ray &ray, const float3 &v0, const float3 &v1,
const float3 &v2, float *hit_t) {
auto e1 = v1 - v0, e2 = v2 - v0, h = cross(ray.direction, e2);
auto a = dot(e1, h);
if (std::abs(a) == 0)
return false;
float f = 1 / a;
auto s = ray.origin - v0;
auto u = f * dot(s, h);
if (u < 0 || u > 1)
return false;
auto q = cross(s, e1);
auto v = f * dot(ray.direction, q);
if (v < 0 || u + v > 1)
return false;
auto t = f * dot(e2, q);
if (t < 0)
return false;
if (hit_t)
*hit_t = t;
return true;
}
bool intersect_ray_mesh(const Ray &ray, const geometry_mesh &mesh,
float *hit_t) {
float best_t = std::numeric_limits<float>::infinity(), t;
int32_t best_tri = -1;
for (auto &tri : mesh.triangles) {
if (intersect_ray_triangle(ray, mesh.vertices[tri[0]].position,
mesh.vertices[tri[1]].position,
mesh.vertices[tri[2]].position, &t) &&
t < best_t) {
best_t = t;
best_tri = uint32_t(&tri - mesh.triangles.data());
}
}
if (best_tri == -1)
return false;
if (hit_t)
*hit_t = best_t;
return true;
}
///////////////////////////////
// Geometry + Mesh Utilities //
///////////////////////////////
void compute_normals(geometry_mesh &mesh) {
static const double NORMAL_EPSILON = 0.0001;
std::vector<uint32_t> uniqueVertIndices(mesh.vertices.size(), 0);
for (uint32_t i = 0; i < uniqueVertIndices.size(); ++i) {
if (uniqueVertIndices[i] == 0) {
uniqueVertIndices[i] = i + 1;
const float3 v0 = mesh.vertices[i].position;
for (auto j = i + 1; j < mesh.vertices.size(); ++j) {
const float3 v1 = mesh.vertices[j].position;
if (length2(v1 - v0) < NORMAL_EPSILON) {
uniqueVertIndices[j] = uniqueVertIndices[i];
}
}
}
}
uint32_t idx0, idx1, idx2;
for (auto &t : mesh.triangles) {
idx0 = uniqueVertIndices[t.x] - 1;
idx1 = uniqueVertIndices[t.y] - 1;
idx2 = uniqueVertIndices[t.z] - 1;
geometry_vertex &v0 = mesh.vertices[idx0], &v1 = mesh.vertices[idx1],
&v2 = mesh.vertices[idx2];
const float3 n =
cross(v1.position - v0.position, v2.position - v0.position);
v0.normal += n;
v1.normal += n;
v2.normal += n;
}
for (uint32_t i = 0; i < mesh.vertices.size(); ++i)
mesh.vertices[i].normal = mesh.vertices[uniqueVertIndices[i] - 1].normal;
for (geometry_vertex &v : mesh.vertices)
v.normal = normalize(v.normal);
}
geometry_mesh make_box_geometry(const float3 &min_bounds,
const float3 &max_bounds) {
const auto a = min_bounds, b = max_bounds;
geometry_mesh mesh;
mesh.vertices = {
{{a.x, a.y, a.z}, {-1, 0, 0}}, {{a.x, a.y, b.z}, {-1, 0, 0}},
{{a.x, b.y, b.z}, {-1, 0, 0}}, {{a.x, b.y, a.z}, {-1, 0, 0}},
{{b.x, a.y, a.z}, {+1, 0, 0}}, {{b.x, b.y, a.z}, {+1, 0, 0}},
{{b.x, b.y, b.z}, {+1, 0, 0}}, {{b.x, a.y, b.z}, {+1, 0, 0}},
{{a.x, a.y, a.z}, {0, -1, 0}}, {{b.x, a.y, a.z}, {0, -1, 0}},
{{b.x, a.y, b.z}, {0, -1, 0}}, {{a.x, a.y, b.z}, {0, -1, 0}},
{{a.x, b.y, a.z}, {0, +1, 0}}, {{a.x, b.y, b.z}, {0, +1, 0}},
{{b.x, b.y, b.z}, {0, +1, 0}}, {{b.x, b.y, a.z}, {0, +1, 0}},
{{a.x, a.y, a.z}, {0, 0, -1}}, {{a.x, b.y, a.z}, {0, 0, -1}},
{{b.x, b.y, a.z}, {0, 0, -1}}, {{b.x, a.y, a.z}, {0, 0, -1}},
{{a.x, a.y, b.z}, {0, 0, +1}}, {{b.x, a.y, b.z}, {0, 0, +1}},
{{b.x, b.y, b.z}, {0, 0, +1}}, {{a.x, b.y, b.z}, {0, 0, +1}},
};
mesh.triangles = {{0, 1, 2}, {0, 2, 3}, {4, 5, 6}, {4, 6, 7},
{8, 9, 10}, {8, 10, 11}, {12, 13, 14}, {12, 14, 15},
{16, 17, 18}, {16, 18, 19}, {20, 21, 22}, {20, 22, 23}};
return mesh;
}
geometry_mesh make_cylinder_geometry(const float3 &axis, const float3 &arm1,
const float3 &arm2, uint32_t slices) {
// Generated curved surface
geometry_mesh mesh;
for (uint32_t i = 0; i <= slices; ++i) {
const float tex_s = static_cast<float>(i) / slices,
angle = (float)(i % slices) * tau / slices;
const float3 arm = arm1 * std::cos(angle) + arm2 * std::sin(angle);
mesh.vertices.push_back({arm, normalize(arm)});
mesh.vertices.push_back({arm + axis, normalize(arm)});
}
for (uint32_t i = 0; i < slices; ++i) {
mesh.triangles.push_back({i * 2, i * 2 + 2, i * 2 + 3});
mesh.triangles.push_back({i * 2, i * 2 + 3, i * 2 + 1});
}
// Generate caps
uint32_t base = (uint32_t)mesh.vertices.size();
for (uint32_t i = 0; i < slices; ++i) {
const float angle = static_cast<float>(i % slices) * tau / slices,
c = std::cos(angle), s = std::sin(angle);
const float3 arm = arm1 * c + arm2 * s;
mesh.vertices.push_back({arm + axis, normalize(axis)});
mesh.vertices.push_back({arm, -normalize(axis)});
}
for (uint32_t i = 2; i < slices; ++i) {
mesh.triangles.push_back({base, base + i * 2 - 2, base + i * 2});
mesh.triangles.push_back({base + 1, base + i * 2 + 1, base + i * 2 - 1});
}
return mesh;
}
geometry_mesh make_lathed_geometry(const float3 &axis, const float3 &arm1,
const float3 &arm2, int slices,
const std::vector<float2> &points,
const float eps = 0.0f) {
geometry_mesh mesh;
for (int i = 0; i <= slices; ++i) {
const float angle = (static_cast<float>(i % slices) * tau / slices) +
(tau / 8.f),
c = std::cos(angle), s = std::sin(angle);
const float3x2 mat = {axis, arm1 * c + arm2 * s};
for (auto &p : points)
mesh.vertices.push_back({mul(mat, p) + eps, float3(0.f)});
if (i > 0) {
for (uint32_t j = 1; j < (uint32_t)points.size(); ++j) {
uint32_t i0 = (i - 1) * uint32_t(points.size()) + (j - 1);
uint32_t i1 = (i - 0) * uint32_t(points.size()) + (j - 1);
uint32_t i2 = (i - 0) * uint32_t(points.size()) + (j - 0);
uint32_t i3 = (i - 1) * uint32_t(points.size()) + (j - 0);
mesh.triangles.push_back({i0, i1, i2});
mesh.triangles.push_back({i0, i2, i3});
}
}
}
compute_normals(mesh);
return mesh;
}
//////////////////////////////////
// Gizmo Context Implementation //
//////////////////////////////////
namespace tinygizmo {
enum class interact {
none,
translate_x,
translate_y,
translate_z,
translate_yz,
translate_zx,
translate_xy,
translate_xyz,
rotate_x,
rotate_y,
rotate_z,
scale_x,
scale_y,
scale_z,
scale_xyz,
};
struct interaction_state {
bool active{
false}; // Flag to indicate if the gizmo is being actively manipulated
bool hover{false}; // Flag to indicate if the gizmo is being hovered
float3 original_position; // Original position of an object being manipulated
// with a gizmo
float4 original_orientation; // Original orientation of an object being
// manipulated with a gizmo
float3 original_scale; // Original scale of an object being manipulated with a
// gizmo
float3 click_offset; // Offset from position of grabbed object to coordinates
// of clicked point
interact interaction_mode; // Currently active component
};
struct gizmo_context::gizmo_context_impl {
gizmo_context *ctx;
gizmo_context_impl(gizmo_context *ctx);
std::map<interact, gizmo_mesh_component> mesh_components;
std::vector<gizmo_renderable> drawlist;
std::map<uint32_t, interaction_state> gizmos;
gizmo_application_state active_state;
gizmo_application_state last_state;
bool local_toggle{
true}; // State to describe if the gizmo should use transform-local math
bool has_clicked{false}; // State to describe if the user has pressed the left
// mouse button during the last frame
bool has_released{false}; // State to describe if the user has released the
// left mouse button during the last frame
// Public methods
void update(const gizmo_application_state &state);
VertexBuffer draw();
};
gizmo_context::gizmo_context_impl::gizmo_context_impl(gizmo_context *ctx)
: ctx(ctx) {
std::vector<float2> arrow_points = {
{0.25f, 0}, {0.25f, 0.05f}, {1, 0.05f}, {1, 0.10f}, {1.2f, 0}};
std::vector<float2> mace_points = {{0.25f, 0}, {0.25f, 0.05f}, {1, 0.05f},
{1, 0.1f}, {1.25f, 0.1f}, {1.25f, 0}};
std::vector<float2> ring_points = {
{+0.025f, 1}, {-0.025f, 1}, {-0.025f, 1}, {-0.025f, 1.1f},
{-0.025f, 1.1f}, {+0.025f, 1.1f}, {+0.025f, 1.1f}, {+0.025f, 1}};
mesh_components[interact::translate_x] = {
make_lathed_geometry({1, 0, 0}, {0, 1, 0}, {0, 0, 1}, 16, arrow_points),
{1, 0.5f, 0.5f, 1.f},
{1, 0, 0, 1.f}};
mesh_components[interact::translate_y] = {
make_lathed_geometry({0, 1, 0}, {0, 0, 1}, {1, 0, 0}, 16, arrow_points),
{0.5f, 1, 0.5f, 1.f},
{0, 1, 0, 1.f}};
mesh_components[interact::translate_z] = {
make_lathed_geometry({0, 0, 1}, {1, 0, 0}, {0, 1, 0}, 16, arrow_points),
{0.5f, 0.5f, 1, 1.f},
{0, 0, 1, 1.f}};
mesh_components[interact::translate_yz] = {
make_box_geometry({-0.01f, 0.25, 0.25}, {0.01f, 0.75f, 0.75f}),
{0.5f, 1, 1, 0.5f},
{0, 1, 1, 0.6f}};
mesh_components[interact::translate_zx] = {
make_box_geometry({0.25, -0.01f, 0.25}, {0.75f, 0.01f, 0.75f}),
{1, 0.5f, 1, 0.5f},
{1, 0, 1, 0.6f}};
mesh_components[interact::translate_xy] = {
make_box_geometry({0.25, 0.25, -0.01f}, {0.75f, 0.75f, 0.01f}),
{1, 1, 0.5f, 0.5f},
{1, 1, 0, 0.6f}};
mesh_components[interact::translate_xyz] = {
make_box_geometry({-0.05f, -0.05f, -0.05f}, {0.05f, 0.05f, 0.05f}),
{0.9f, 0.9f, 0.9f, 0.25f},
{1, 1, 1, 0.35f}};
mesh_components[interact::rotate_x] = {
make_lathed_geometry({1, 0, 0}, {0, 1, 0}, {0, 0, 1}, 32, ring_points,
0.003f),
{1, 0.5f, 0.5f, 1.f},
{1, 0, 0, 1.f}};
mesh_components[interact::rotate_y] = {
make_lathed_geometry({0, 1, 0}, {0, 0, 1}, {1, 0, 0}, 32, ring_points,
-0.003f),
{0.5f, 1, 0.5f, 1.f},
{0, 1, 0, 1.f}};
mesh_components[interact::rotate_z] = {
make_lathed_geometry({0, 0, 1}, {1, 0, 0}, {0, 1, 0}, 32, ring_points),
{0.5f, 0.5f, 1, 1.f},
{0, 0, 1, 1.f}};
mesh_components[interact::scale_x] = {
make_lathed_geometry({1, 0, 0}, {0, 1, 0}, {0, 0, 1}, 16, mace_points),
{1, 0.5f, 0.5f, 1.f},
{1, 0, 0, 1.f}};
mesh_components[interact::scale_y] = {
make_lathed_geometry({0, 1, 0}, {0, 0, 1}, {1, 0, 0}, 16, mace_points),
{0.5f, 1, 0.5f, 1.f},
{0, 1, 0, 1.f}};
mesh_components[interact::scale_z] = {
make_lathed_geometry({0, 0, 1}, {1, 0, 0}, {0, 1, 0}, 16, mace_points),
{0.5f, 0.5f, 1, 1.f},
{0, 0, 1, 1.f}};
}
void gizmo_context::gizmo_context_impl::update(
const gizmo_application_state &state) {
active_state = state;
local_toggle = (!last_state.hotkey_local && active_state.hotkey_local &&
active_state.hotkey_ctrl)
? !local_toggle
: local_toggle;
has_clicked =
(!last_state.mouse_left && active_state.mouse_left) ? true : false;
has_released =
(last_state.mouse_left && !active_state.mouse_left) ? true : false;
drawlist.clear();
}
geometry_mesh r; // Combine all gizmo sub-meshes into one super-mesh
VertexBuffer gizmo_context::gizmo_context_impl::draw() {
r.vertices.clear();
r.triangles.clear();
for (auto &m : drawlist) {
uint32_t numVerts = (uint32_t)r.vertices.size();
auto it = r.vertices.insert(r.vertices.end(), m.mesh.vertices.begin(),
m.mesh.vertices.end());
for (auto &f : m.mesh.triangles)
r.triangles.push_back({numVerts + f.x, numVerts + f.y, numVerts + f.z});
for (; it != r.vertices.end(); ++it)
it->color =
m.color; // Take the color and shove it into a per-vertex attribute
}
last_state = active_state;
return VertexBuffer{
(const Vertex *)r.vertices.data(),
r.vertices.size(),
(const uint32_t *)r.triangles.data(),
r.triangles.size() * 3
};
}
// This will calculate a scale constant based on the number of screenspace
// pixels passed as pixel_scale.
float scale_screenspace(gizmo_context::gizmo_context_impl &g,
const float3 position, const float pixel_scale) {
float dist = length(position - *((float3 *)&g.active_state.cam.position));
return std::tan(g.active_state.cam.yfov) * dist *
(pixel_scale / g.active_state.viewport_size[1]);
}
// The only purpose of this is readability: to reduce the total column width of
// the intersect(...) statements in every gizmo
bool intersect(gizmo_context::gizmo_context_impl &g, const Ray &r, interact i,
float &t, const float best_t) {
if (intersect_ray_mesh(r, g.mesh_components[i].mesh, &t) && t < best_t)
return true;
return false;
}
///////////////////////////////////
// Private Gizmo Implementations //
///////////////////////////////////
void axis_rotation_dragger(const uint32_t id,
gizmo_context::gizmo_context_impl &g,
const float3 &axis, const float3 ¢er,
const float4 &start_orientation,
float4 &orientation) {
interaction_state &interaction = g.gizmos[id];
if (g.active_state.mouse_left) {
rigid_transform original_pose = {start_orientation,
interaction.original_position};
float3 the_axis = original_pose.transform_vector(axis);
float4 the_plane = {the_axis, -dot(the_axis, interaction.click_offset)};
const Ray r = {g.active_state.ray_origin, g.active_state.ray_direction};
float t;
if (intersect_ray_plane(r, the_plane, &t)) {
float3 center_of_rotation =
interaction.original_position +
the_axis * dot(the_axis, interaction.click_offset -
interaction.original_position);
float3 arm1 = normalize(interaction.click_offset - center_of_rotation);
float3 arm2 = normalize(r.origin + r.direction * t - center_of_rotation);
float d = dot(arm1, arm2);
if (d > 0.999f) {
orientation = start_orientation;
return;
}
float angle = std::acos(d);
if (angle < 0.001f) {
orientation = start_orientation;
return;
}
if (g.active_state.snap_rotation) {
auto snapped = make_rotation_quat_between_vectors_snapped(
arm1, arm2, g.active_state.snap_rotation);
orientation = qmul(snapped, start_orientation);
} else {
auto a = normalize(cross(arm1, arm2));
orientation = qmul(rotation_quat(a, angle), start_orientation);
}
}
}
}
void plane_translation_dragger(const uint32_t id,
gizmo_context::gizmo_context_impl &g,
const float3 &plane_normal, float3 &point) {
interaction_state &interaction = g.gizmos[id];
// Mouse clicked
if (g.has_clicked)
interaction.original_position = point;
if (g.active_state.mouse_left) {
// Define the plane to contain the original position of the object
const float3 plane_point = interaction.original_position;
const Ray r = {g.active_state.ray_origin, g.active_state.ray_direction};
// If an intersection exists between the ray and the plane, place the object
// at that point
const float denom = dot(r.direction, plane_normal);
if (std::abs(denom) == 0)
return;
const float t = dot(plane_point - r.origin, plane_normal) / denom;
if (t < 0)
return;
point = r.origin + r.direction * t;
if (g.active_state.snap_translation)
point = snap(point, g.active_state.snap_translation);
}
}
void axis_translation_dragger(const uint32_t id,
gizmo_context::gizmo_context_impl &g,
const float3 &axis, float3 &point) {
interaction_state &interaction = g.gizmos[id];
if (g.active_state.mouse_left) {
// First apply a plane translation dragger with a plane that contains the
// desired axis and is oriented to face the camera
const float3 plane_tangent =
cross(axis, point - *((float3 *)&g.active_state.cam.position));
const float3 plane_normal = cross(axis, plane_tangent);
plane_translation_dragger(id, g, plane_normal, point);
// Constrain object motion to be along the desired axis
point = interaction.original_position +
axis * dot(point - interaction.original_position, axis);
}
}
///////////////////////////////
// Gizmo Implementations //
///////////////////////////////
void position_gizmo(const std::string &name,
gizmo_context::gizmo_context_impl &g,
const float4 &orientation, float3 &position) {
rigid_transform p = rigid_transform(
g.local_toggle ? orientation : float4(0, 0, 0, 1), position);
const float draw_scale =
(g.active_state.screenspace_scale > 0.f)
? scale_screenspace(g, p.position, g.active_state.screenspace_scale)
: 1.f;
const uint32_t id = hash_fnv1a(name);
// interaction_mode will only change on clicked
if (g.has_clicked)
g.gizmos[id].interaction_mode = interact::none;
{
interact updated_state = interact::none;
auto ray = detransform(
p, {g.active_state.ray_origin, g.active_state.ray_direction});
detransform(draw_scale, ray);
float best_t = std::numeric_limits<float>::infinity(), t;
if (intersect(g, ray, interact::translate_x, t, best_t)) {
updated_state = interact::translate_x;
best_t = t;
}
if (intersect(g, ray, interact::translate_y, t, best_t)) {
updated_state = interact::translate_y;
best_t = t;
}
if (intersect(g, ray, interact::translate_z, t, best_t)) {
updated_state = interact::translate_z;
best_t = t;
}
if (intersect(g, ray, interact::translate_yz, t, best_t)) {
updated_state = interact::translate_yz;
best_t = t;
}
if (intersect(g, ray, interact::translate_zx, t, best_t)) {
updated_state = interact::translate_zx;
best_t = t;
}
if (intersect(g, ray, interact::translate_xy, t, best_t)) {
updated_state = interact::translate_xy;
best_t = t;
}
if (intersect(g, ray, interact::translate_xyz, t, best_t)) {
updated_state = interact::translate_xyz;
best_t = t;
}
if (g.has_clicked) {
g.gizmos[id].interaction_mode = updated_state;
if (g.gizmos[id].interaction_mode != interact::none) {
transform(draw_scale, ray);
g.gizmos[id].click_offset =
g.local_toggle ? p.transform_vector(ray.origin + ray.direction * t)
: ray.origin + ray.direction * t;
g.gizmos[id].active = true;
} else
g.gizmos[id].active = false;
}
g.gizmos[id].hover =
(best_t == std::numeric_limits<float>::infinity()) ? false : true;
}
std::vector<float3> axes;
if (g.local_toggle)
axes = {qxdir(p.orientation), qydir(p.orientation), qzdir(p.orientation)};
else
axes = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}};
if (g.gizmos[id].active) {
position += g.gizmos[id].click_offset;
switch (g.gizmos[id].interaction_mode) {
case interact::translate_x:
axis_translation_dragger(id, g, axes[0], position);
break;
case interact::translate_y:
axis_translation_dragger(id, g, axes[1], position);
break;
case interact::translate_z:
axis_translation_dragger(id, g, axes[2], position);
break;
case interact::translate_yz:
plane_translation_dragger(id, g, axes[0], position);
break;
case interact::translate_zx:
plane_translation_dragger(id, g, axes[1], position);
break;
case interact::translate_xy:
plane_translation_dragger(id, g, axes[2], position);
break;
case interact::translate_xyz:
plane_translation_dragger(
id, g, -minalg::qzdir(*((float4 *)&g.active_state.cam.orientation)),
position);
break;
}
position -= g.gizmos[id].click_offset;
}
if (g.has_released) {
g.gizmos[id].interaction_mode = interact::none;
g.gizmos[id].active = false;
}
std::vector<interact> draw_interactions{
interact::translate_x, interact::translate_y, interact::translate_z,
interact::translate_yz, interact::translate_zx, interact::translate_xy,
interact::translate_xyz};
float4x4 modelMatrix = p.matrix();
float4x4 scaleMatrix = scaling_matrix(float3(draw_scale));
modelMatrix = mul(modelMatrix, scaleMatrix);
for (auto c : draw_interactions) {
gizmo_renderable r;
r.mesh = g.mesh_components[c].mesh;
r.color = (c == g.gizmos[id].interaction_mode)
? g.mesh_components[c].base_color
: g.mesh_components[c].highlight_color;
for (auto &v : r.mesh.vertices) {
v.position = transform_coord(
modelMatrix,
v.position); // transform local coordinates into worldspace
v.normal = transform_vector(modelMatrix, v.normal);
}
g.drawlist.push_back(r);
}
}
void orientation_gizmo(const std::string &name,
gizmo_context::gizmo_context_impl &g,
const float3 ¢er, float4 &orientation) {
assert(length2(orientation) > float(1e-6));
rigid_transform p =
rigid_transform(g.local_toggle ? orientation : float4(0, 0, 0, 1),
center); // Orientation is local by default
const float draw_scale =
(g.active_state.screenspace_scale > 0.f)
? scale_screenspace(g, p.position, g.active_state.screenspace_scale)
: 1.f;
const uint32_t id = hash_fnv1a(name);
// interaction_mode will only change on clicked
if (g.has_clicked)
g.gizmos[id].interaction_mode = interact::none;
{
interact updated_state = interact::none;
auto ray = detransform(
p, {g.active_state.ray_origin, g.active_state.ray_direction});
detransform(draw_scale, ray);
float best_t = std::numeric_limits<float>::infinity(), t;
if (intersect(g, ray, interact::rotate_x, t, best_t)) {
updated_state = interact::rotate_x;
best_t = t;
}
if (intersect(g, ray, interact::rotate_y, t, best_t)) {
updated_state = interact::rotate_y;
best_t = t;
}
if (intersect(g, ray, interact::rotate_z, t, best_t)) {
updated_state = interact::rotate_z;
best_t = t;
}
if (g.has_clicked) {
g.gizmos[id].interaction_mode = updated_state;
if (g.gizmos[id].interaction_mode != interact::none) {
transform(draw_scale, ray);
g.gizmos[id].original_position = center;
g.gizmos[id].original_orientation = orientation;
g.gizmos[id].click_offset =
p.transform_point(ray.origin + ray.direction * t);
g.gizmos[id].active = true;
} else
g.gizmos[id].active = false;
}
}
float3 activeAxis;
if (g.gizmos[id].active) {
const float4 starting_orientation =
g.local_toggle ? g.gizmos[id].original_orientation : float4(0, 0, 0, 1);
switch (g.gizmos[id].interaction_mode) {
case interact::rotate_x:
axis_rotation_dragger(id, g, {1, 0, 0}, center, starting_orientation,
p.orientation);
activeAxis = {1, 0, 0};
break;
case interact::rotate_y:
axis_rotation_dragger(id, g, {0, 1, 0}, center, starting_orientation,
p.orientation);
activeAxis = {0, 1, 0};
break;
case interact::rotate_z:
axis_rotation_dragger(id, g, {0, 0, 1}, center, starting_orientation,
p.orientation);
activeAxis = {0, 0, 1};
break;
}
}
if (g.has_released) {
g.gizmos[id].interaction_mode = interact::none;
g.gizmos[id].active = false;
}
float4x4 modelMatrix = p.matrix();
float4x4 scaleMatrix = scaling_matrix(float3(draw_scale));
modelMatrix = mul(modelMatrix, scaleMatrix);
std::vector<interact> draw_interactions;
if (!g.local_toggle && g.gizmos[id].interaction_mode != interact::none)
draw_interactions = {g.gizmos[id].interaction_mode};
else
draw_interactions = {interact::rotate_x, interact::rotate_y,
interact::rotate_z};
for (auto c : draw_interactions) {
gizmo_renderable r;
r.mesh = g.mesh_components[c].mesh;
r.color = (c == g.gizmos[id].interaction_mode)
? g.mesh_components[c].base_color
: g.mesh_components[c].highlight_color;
for (auto &v : r.mesh.vertices) {
v.position = transform_coord(
modelMatrix,
v.position); // transform local coordinates into worldspace
v.normal = transform_vector(modelMatrix, v.normal);
}
g.drawlist.push_back(r);
}
// For non-local transformations, we only present one rotation ring
// and draw an arrow from the center of the gizmo to indicate the degree of
// rotation
if (g.local_toggle == false &&
g.gizmos[id].interaction_mode != interact::none) {
interaction_state &interaction = g.gizmos[id];
// Create orthonormal basis for drawing the arrow
float3 a = qrot(p.orientation,
interaction.click_offset - interaction.original_position);
float3 zDir = normalize(activeAxis), xDir = normalize(cross(a, zDir)),
yDir = cross(zDir, xDir);
// Ad-hoc geometry
std::initializer_list<float2> arrow_points = {
{0.0f, 0.f}, {0.0f, 0.05f}, {0.8f, 0.05f}, {0.9f, 0.10f}, {1.0f, 0}};
auto geo = make_lathed_geometry(yDir, xDir, zDir, 32, arrow_points);
gizmo_renderable r;
r.mesh = geo;
r.color = float4(1);
for (auto &v : r.mesh.vertices) {
v.position = transform_coord(modelMatrix, v.position);
v.normal = transform_vector(modelMatrix, v.normal);
}
g.drawlist.push_back(r);
orientation = qmul(p.orientation, interaction.original_orientation);
} else if (g.local_toggle == true &&
g.gizmos[id].interaction_mode != interact::none)
orientation = p.orientation;
}
void axis_scale_dragger(const uint32_t &id,
gizmo_context::gizmo_context_impl &g,
const float3 &axis, const float3 ¢er, float3 &scale,
const bool uniform) {
interaction_state &interaction = g.gizmos[id];
if (g.active_state.mouse_left) {
const float3 plane_tangent =
cross(axis, center - *((float3 *)&g.active_state.cam.position));
const float3 plane_normal = cross(axis, plane_tangent);
float3 distance;
if (g.active_state.mouse_left) {
// Define the plane to contain the original position of the object
const float3 plane_point = center;
const Ray ray = {g.active_state.ray_origin, g.active_state.ray_direction};
// If an intersection exists between the ray and the plane, place the
// object at that point
const float denom = dot(ray.direction, plane_normal);
if (std::abs(denom) == 0)
return;
const float t = dot(plane_point - ray.origin, plane_normal) / denom;
if (t < 0)
return;
distance = ray.origin + ray.direction * t;
}
float3 offset_on_axis = (distance - interaction.click_offset) * axis;
flush_to_zero(offset_on_axis);
float3 new_scale = interaction.original_scale + offset_on_axis;
if (uniform)
scale = float3(clamp(dot(distance, new_scale), 0.01f, 1000.f));
else
scale = float3(clamp(new_scale.x, 0.01f, 1000.f),
clamp(new_scale.y, 0.01f, 1000.f),
clamp(new_scale.z, 0.01f, 1000.f));
if (g.active_state.snap_scale)
scale = snap(scale, g.active_state.snap_scale);
}
}
void scale_gizmo(const std::string &name, gizmo_context::gizmo_context_impl &g,
const float4 &orientation, const float3 ¢er,
float3 &scale) {
rigid_transform p = rigid_transform(orientation, center);
const float draw_scale =
(g.active_state.screenspace_scale > 0.f)
? scale_screenspace(g, p.position, g.active_state.screenspace_scale)
: 1.f;
const uint32_t id = hash_fnv1a(name);
if (g.has_clicked)
g.gizmos[id].interaction_mode = interact::none;
{
interact updated_state = interact::none;
auto ray = detransform(
p, {g.active_state.ray_origin, g.active_state.ray_direction});
detransform(draw_scale, ray);
float best_t = std::numeric_limits<float>::infinity(), t;
if (intersect(g, ray, interact::scale_x, t, best_t)) {
updated_state = interact::scale_x;
best_t = t;
}
if (intersect(g, ray, interact::scale_y, t, best_t)) {
updated_state = interact::scale_y;
best_t = t;
}
if (intersect(g, ray, interact::scale_z, t, best_t)) {
updated_state = interact::scale_z;
best_t = t;
}
if (g.has_clicked) {
g.gizmos[id].interaction_mode = updated_state;
if (g.gizmos[id].interaction_mode != interact::none) {
transform(draw_scale, ray);
g.gizmos[id].original_scale = scale;
g.gizmos[id].click_offset =
p.transform_point(ray.origin + ray.direction * t);
g.gizmos[id].active = true;
} else
g.gizmos[id].active = false;
}
}
if (g.has_released) {
g.gizmos[id].interaction_mode = interact::none;
g.gizmos[id].active = false;
}
if (g.gizmos[id].active) {
switch (g.gizmos[id].interaction_mode) {
case interact::scale_x:
axis_scale_dragger(id, g, {1, 0, 0}, center, scale,
g.active_state.hotkey_ctrl);
break;
case interact::scale_y:
axis_scale_dragger(id, g, {0, 1, 0}, center, scale,
g.active_state.hotkey_ctrl);
break;
case interact::scale_z:
axis_scale_dragger(id, g, {0, 0, 1}, center, scale,
g.active_state.hotkey_ctrl);
break;
}
}
float4x4 modelMatrix = p.matrix();
float4x4 scaleMatrix = scaling_matrix(float3(draw_scale));
modelMatrix = mul(modelMatrix, scaleMatrix);
std::vector<interact> draw_components{interact::scale_x, interact::scale_y,
interact::scale_z};
for (auto c : draw_components) {
gizmo_renderable r;
r.mesh = g.mesh_components[c].mesh;
r.color = (c == g.gizmos[id].interaction_mode)
? g.mesh_components[c].base_color
: g.mesh_components[c].highlight_color;
for (auto &v : r.mesh.vertices) {
v.position = transform_coord(
modelMatrix,
v.position); // transform local coordinates into worldspace
v.normal = transform_vector(modelMatrix, v.normal);
}
g.drawlist.push_back(r);
}
}
//////////////////////////////////
// Public Gizmo Implementations //
//////////////////////////////////
gizmo_context::gizmo_context() { impl.reset(new gizmo_context_impl(this)); };
gizmo_context::~gizmo_context() {}
void gizmo_context::update(const gizmo_application_state &state) {
impl->update(state);
}
VertexBuffer gizmo_context::draw() { return impl->draw(); }
void position(const std::string &name, gizmo_context &g,
const std::array<float, 4> &orientation,
std::array<float, 3> &position) {
position_gizmo(name, *g.impl, *((const float4 *)&orientation),
*((float3 *)&position));
}
void orientation(const std::string &name, gizmo_context &g,
const std::array<float, 3> &position,
std::array<float, 4> &orientation) {
orientation_gizmo(name, *g.impl, *((const float3 *)&position),
*((float4 *)&orientation));
}
void scale(const std::string &name, gizmo_context &g,
const std::array<float, 4> &orientation,
const std::array<float, 3> &position, std::array<float, 3> &scale) {
scale_gizmo(name, *g.impl, *((const float4 *)&orientation),
*((const float3 *)&position), *((float3 *)&scale));
}
static bool transform_gizmo(const std::string &name, gizmo_context &g,
std::array<float, 3> &position,
std::array<float, 4> &orientation,
std::array<float, 3> &scale) {
bool activated = false;
// if (g.impl->mode == transform_mode::translate)
// ;
// else if (g.impl->mode == transform_mode::rotate)
// ;
// else if (g.impl->mode == transform_mode::scale)
// ;
const interaction_state s = g.impl->gizmos[hash_fnv1a(name)];
if (s.hover == true || s.active == true)
activated = true;
return activated;
}
} // namespace tinygizmo | 34.99554 | 80 | 0.599771 | [
"mesh",
"geometry",
"object",
"vector",
"transform"
] |
e7d1724e907073a80c4b1ec00462bc1cca2cfbdc | 16,865 | hpp | C++ | include/dpp/dpp_new/lstm.hpp | Lemon-cmd/DeepPP-Learning | 1211c1400eb04d1c689a4d876b3cb3e727184809 | [
"MIT"
] | null | null | null | include/dpp/dpp_new/lstm.hpp | Lemon-cmd/DeepPP-Learning | 1211c1400eb04d1c689a4d876b3cb3e727184809 | [
"MIT"
] | null | null | null | include/dpp/dpp_new/lstm.hpp | Lemon-cmd/DeepPP-Learning | 1211c1400eb04d1c689a4d876b3cb3e727184809 | [
"MIT"
] | null | null | null | #ifndef LSTM_HPP
#define LSTM_HPP
#include "layer.hpp"
namespace dpp {
class LSTM : public Layer {
/* Long Short Term Memory Layer */
public:
LSTM(const int neurons = 1, const std::string activation = "tanh", const std::string recurrent_activation = "sigmoid",
const float lrate = 0.001, const float erate = 1e-8) {
/* Save the parameters, and initalize parallelism and set the appropriate activation and recurrent activation functions */
assert(neurons > 0 && lrate > 0.0f && erate > 0.0f);
// etc parameters
lrate_ = lrate; erate_ = erate;
out_dim_[1] = neurons;
// set size of layer's parameter-vectors
state_.resize(4); gate_.resize(4); dgate_.resize(4); x_weight_.resize(4); h_weight_.resize(4); bias_.resize(4);
// save the activation name for when saving to a file
activation_ = activation == "normal" ? activation : activation == "softsign" ? activation : activation == "softmax" ? activation : activation == "relu" ? \
activation : activation == "sigmoid" ? activation : "tanh";
// save the recurrent activation name for when saving to a file
recurrent_activation_ = recurrent_activation == "normal" ? recurrent_activation : recurrent_activation == "tanh" ? recurrent_activation : recurrent_activation == "softmax" ? \
recurrent_activation : recurrent_activation == "relu" ? recurrent_activation : recurrent_activation == "softsign" ? recurrent_activation : "sigmoid";
// make any necessary changes to the activation functions
SetActivation(activate_, activation_);
SetActivation(reactivate_, recurrent_activation_);
}
const std::string type() { return "2D"; }
const std::string name() { return "LSTM"; }
const MatrixXf& Get2dDelta() override { return delta_; }
const MatrixXf& Get2dOutput() override { return output_; }
const Dim2d Get2dOutputDim() override { return out_dim_; }
void Reset() override {
static const int limit = in_dim_[0] - 1;
output_.row(limit) = output_.row(limit).setZero();
state_[0].row(limit) = state_[0].row(limit).setZero();
}
void SetDelta(const MatrixXf &delta) override {
dh_ = delta;
}
void Topology() {
std::cout << "\n\t------------- LSTM Layer ---------------\n"
<< "\n\tParameters:\t(" << out_dim_[1] * out_dim_[1] * 4 + in_dim_[1] * out_dim_[0] * 4 + out_dim_[1] * 4 << ')'
<< "\n\tInput-dim:\t(" << in_dim_[0] << ", " << in_dim_[1] << ')'
<< "\n\tOutput-dim:\t(" << out_dim_[0] << ", " << out_dim_[1] << ")\n"
<< "\n\t----------------------------------------\n\n";
}
void init(const Dim2d in_dim) override {
/* Initialize the parameters of the layer and save the input shape */
assert(in_dim[0] > 0 && in_dim[1] > 0);
// set initialized flag
init_flag_ = true;
// save shapes
in_dim_ = in_dim; out_dim_[0] = in_dim_[0];
// set shape of layer delta and layer output
delta_ = MatrixXf::Zero(in_dim_[0], in_dim_[1]);
output_ = MatrixXf::Zero(in_dim_[0], out_dim_[1]);
// set the shape of d(activated(C(t)) and other states (C(t), activated C(t), C(t - 1), H(t - 1))
dh_ct_ = MatrixXf::Zero(in_dim_[0], out_dim_[1]);
std::for_each(state_.begin(), state_.end(), [this](auto &mat) { mat = MatrixXf::Zero(in_dim_[0], out_dim_[1]); });
// set the shape of each gate and their gradient
std::for_each(gate_.begin(), gate_.end(), [this](auto &mat) { mat = MatrixXf::Zero(in_dim_[0], out_dim_[1]); });
std::for_each(dgate_.begin(), dgate_.end(), [this](auto &mat) { mat = MatrixXf::Zero(in_dim_[0], out_dim_[1]); });
// initialize weight
std::for_each(bias_.begin(), bias_.end(), [this](auto &mat) { mat = MatrixXf::Ones(1, out_dim_[1]); });
std::for_each(h_weight_.begin(), h_weight_.end(), [this](auto &mat) { mat = MatrixXf::Constant(out_dim_[1], out_dim_[1], 2.0f / out_dim_[1]); });
std::for_each(x_weight_.begin(), x_weight_.end(), [this](auto &mat) { mat = MatrixXf::Constant(in_dim_[1], out_dim_[1], 2.0f / sqrtf(in_dim_[1] * out_dim_[1])); });
// select the appropriate size of thread pool and calculate the spread in thread executions
thread_pool_.resize(in_dim_[0] <= std::thread::hardware_concurrency() ? in_dim_[0] : in_dim_[0] % std::thread::hardware_concurrency() + 1);
slope_ = in_dim_[0] / thread_pool_.size();
}
void Forward(const MatrixXf &X) override {
assert(X.rows() == in_dim_[0] && X.cols() == in_dim_[1] && init_flag_);
input_ = X; // store X
static const int limit = in_dim_[0] - 1; // last index of sequence
state_[3].row(0) = output_.row(limit); // store H(t - 1)
state_[2].row(0) = state_[0].row(limit); // store C(t - 1)
for (int w = 0; w < in_dim_[0]; w ++) {
// calculate Z of each gate
gate_[0].row(w) = input_.row(w) * x_weight_[0] + state_[3].row(w) * h_weight_[0] + bias_[0]; // forget gate
gate_[1].row(w) = input_.row(w) * x_weight_[1] + state_[3].row(w) * h_weight_[1] + bias_[1]; // input gate
gate_[2].row(w) = input_.row(w) * x_weight_[2] + state_[3].row(w) * h_weight_[2] + bias_[2]; // output gate
gate_[3].row(w) = input_.row(w) * x_weight_[3] + state_[3].row(w) * h_weight_[3] + bias_[3]; // memory gate
// activate LSTM gates
reactivate_(gate_[0], dgate_[0], w); // forget gate
reactivate_(gate_[1], dgate_[1], w); // input gate
reactivate_(gate_[2], dgate_[2], w); // output gate
activate_(gate_[3], dgate_[3], w); // mem. gate
// calculate cell state : ft * c(t - 1) + it * gt
state_[1].row(w) = gate_[0].row(w).array() * state_[2].row(w).array()
+ gate_[1].row(w).array() * gate_[3].row(w).array();
state_[0].row(w) = state_[1].row(w); // save c(t)
activate_(state_[1], dh_ct_, w); // activate c(t)
output_.row(w) = gate_[2].row(w).cwiseProduct(state_[1].row(w)); // calculate h(t)
if (w < limit) {
state_[3].row(w + 1) = output_.row(w); // set h(t - 1) for next t
state_[2].row(w + 1) = state_[0].row(w); // set c(t - 1) for next t
}
}
}
void Update() {
static MatrixXfVec dc, db, dhg, dxw, dhw;
dc.resize(3); db.resize(4); dhg.resize(4); dxw.resize(4); dhw.resize(4);
#pragma omp parallel
{
#pragma omp for simd nowait
for (int j = 0; j < 4; j ++) {
db[j] = MatrixXf::Zero(1, out_dim_[1]);
dhg[j] = MatrixXf::Zero(in_dim_[0], out_dim_[1]);
dxw[j] = MatrixXf::Zero(in_dim_[1], out_dim_[1]);
dhw[j] = MatrixXf::Zero(out_dim_[1], out_dim_[1]);
h_weight_[j].transposeInPlace(); // transpose all h-weight
}
}
dc[1] = dgate_[1].cwiseProduct(gate_[3]); // di(t)
dc[2] = dgate_[3].cwiseProduct(gate_[1]); // dm(t)
dc[0] = dgate_[0].cwiseProduct(state_[2]); // df(t)
dgate_[2] = dgate_[2].cwiseProduct(state_[1]); // do(t)
dgate_[0] = gate_[2].cwiseProduct(dh_ct_).cwiseProduct(dc[0]); // dc(t) / df(t)
dgate_[1] = gate_[2].cwiseProduct(dh_ct_).cwiseProduct(dc[1]); // dc(t) / di(t)
dgate_[3] = gate_[2].cwiseProduct(dh_ct_).cwiseProduct(dc[2]); // dc(t) / dm(t)
input_.transposeInPlace(); // X.T
state_[3].transposeInPlace(); // H(t - 1).T
delta_ = delta_.setZero();
#pragma omp parallel
{
#pragma omp for simd nowait
for (int j = 0; j < 4; j ++) {
dhg[j] = dh_.cwiseProduct(dgate_[j]); // dJ / gradient of gate respectively
delta_ = delta_ + dhg[j] * x_weight_[j].transpose(); // calculate dJ/dX
}
}
start_ = in_dim_[0] - 1; end_ = start_ - slope_; // indices for thread
for (int t = 0; t < thread_pool_.size(); t ++) { // initialize thread pool
thread_pool_[t] = std::move(std::thread(&LSTM::RUpdate, this,
std::ref(dc), std::ref(dhg),
std::ref(db), std::ref(dxw), std::ref(dhw),
start_, end_));
start_ -= slope_; end_ -= slope_;
}
for (int t = 0; t < thread_pool_.size(); t ++) {
thread_pool_[t].join(); // join threads
}
if (out_dim_[0] % thread_pool_.size() > 0) {
RUpdate(dc, dhg, db, dxw, dhw, start_, -1); // perform the remaining time-steps
}
// perform change to parameters
#pragma omp parallel
{
#pragma omp for simd nowait
for (int j = 0; j < 4; j ++) {
vb_[j] = 0.1 * vb_[j] + 0.9 * db[j].array().square().sum(); // bias momentum
vw_[j] = 0.1 * vw_[j] + 0.9 * dxw[j].array().square().sum(); // X-weight momentum
vh_[j] = 0.1 * vh_[j] + 0.9 * dhw[j].array().square().sum(); // H-weight momentum
bias_[j] = bias_[j].array() - lrate_ / sqrtf(vb_[j] + erate_) * db[j].array(); // change bias
x_weight_[j] = x_weight_[j].array() - lrate_ / sqrtf(vw_[j] + erate_) * dxw[j].array(); // change x-weight
h_weight_[j] = h_weight_[j].array() - lrate_ / sqrtf(vh_[j] + erate_) * dhw[j].array(); // change h-weight
}
}
input_.transposeInPlace();
state_[3].transposeInPlace();
std::for_each(std::execution::par_unseq, h_weight_.begin(), h_weight_.end(), [](MatrixXf &wh) { wh.transposeInPlace(); });
}
const float MeanSquaredError(const MatrixXf &Y, float &accuracy) override {
dh_ = output_ - Y; // dH = H - Y
accuracy = output_.unaryExpr<float(*)(float)>(&roundf).isApprox(Y) ? accuracy + 1 : accuracy;
return 0.5 * dh_.array().square().sum();
}
const float CrossEntropyError(const MatrixXf &Y, float &accuracy) override {
static float hits; hits = 0.0; // matches of each row
dh_ = -Y.array() / output_.array(); // set new dJ
start_ = 0; end_ = slope_; // initalize start and end index of thread
// measure accuracy of H concurrently
for (int t = 0; t < thread_pool_.size(); t ++) {
thread_pool_[t] = std::thread(&LSTM::Measure, this,
std::ref(output_), std::ref(Y), std::ref(hits), start_, end_);
start_ += slope_; end_ += slope_;
}
for (int t = 0; t < thread_pool_.size(); t ++) {
thread_pool_[t].join();
}
if (out_dim_[0] % thread_pool_.size() > 0) {
Measure(output_, Y, hits, start_, out_dim_[0]); // perform calculation on the remainder if exists
}
accuracy = hits / out_dim_[0] + accuracy; // accuracy = average of matches argmax of H to Y
return (1.0 - Y.array() * output_.array().log()).sum();
}
void Save(std::ofstream &file) {
assert(init_flag_);
// convert all parameters into vectors
std::vector <VectorXf> vx_bias, vx_weight, vh_weight; vx_bias.resize(4); vx_weight.resize(4); vh_weight.resize(4);
// convert matrices to vectors
for (int j = 0; j < 4; j ++) {
vx_bias[j] = Eigen::Map <VectorXf> (bias_[j].data(), bias_[j].size());
vx_weight[j] = Eigen::Map <VectorXf> (x_weight_[j].data(), x_weight_[j].size());
vh_weight[j] = Eigen::Map <VectorXf> (h_weight_[j].data(), h_weight_[j].size());
}
// write to file
file << "\nLSTM\n";
file << "Activation: " << activation_ << '\n';
file << "Recurrent_Activation: " << recurrent_activation_ << '\n';
file << "Learning_rate: (" << lrate_ << ")\n";
file << "Momentum_rate: (" << erate_ << ")\n";
file << "Input_shape: [" << in_dim_[0] << ',' << in_dim_[1] << "]\n";
file << "Output_shape: [" << out_dim_[0] << ',' << out_dim_[1] << "]\n";
file << "Forget_gate_bias: ["; WriteVector(vx_bias[0], file);
file << "Forget_gate_weight: ["; WriteVector(vx_weight[0], file);
file << "Forget_gate_uweight: ["; WriteVector(vh_weight[0], file);
file << "Input_gate_bias: ["; WriteVector(vx_bias[1], file);
file << "Input_gate_weight: ["; WriteVector(vx_weight[1], file);
file << "Input_gate_uweight: ["; WriteVector(vh_weight[1], file);
file << "Output_gate_bias: ["; WriteVector(vx_bias[2], file);
file << "Output_gate_weight: ["; WriteVector(vx_weight[2], file);
file << "Output_gate_uweight: ["; WriteVector(vh_weight[2], file);
file << "Memory_gate_bias: ["; WriteVector(vx_bias[3], file);
file << "Memory_gate_weight: ["; WriteVector(vx_weight[3], file);
file << "Memory_gate_uweight: ["; WriteVector(vh_weight[3], file);
}
void Load(const Dim2d &in_dim, const Dim2d &out_dim, const std::vector <VectorXf> &weight) override {
assert(weight.size() == 12);
// set initialized flag
init_flag_ = true;
// save shapes
in_dim_ = in_dim; out_dim_[0] = in_dim_[0];
// set shape of layer delta and layer output
delta_ = MatrixXf::Zero(in_dim_[0], in_dim_[1]);
output_ = MatrixXf::Zero(in_dim_[0], out_dim_[1]);
// set the shape of d(activated(C(t)) and other states (C(t), activated C(t), C(t - 1), H(t - 1))
dh_ct_ = MatrixXf::Zero(in_dim_[0], out_dim_[1]);
std::for_each(state_.begin(), state_.end(), [this](auto &mat) { mat = MatrixXf::Zero(in_dim_[0], out_dim_[1]); });
// set the shape of each gate and their gradient
std::for_each(gate_.begin(), gate_.end(), [this](auto &mat) { mat = MatrixXf::Zero(in_dim_[0], out_dim_[1]); });
std::for_each(dgate_.begin(), dgate_.end(), [this](auto &mat) { mat = MatrixXf::Zero(in_dim_[0], out_dim_[1]); });
// reload biases
for (int j = 0; j < 4; j ++) {
bias_[j] = Eigen::Map <const MatrixXf> (weight[j].data(), 1, out_dim_[1]);
}
// load X-weight
for (int j = 4; j < 8; j ++) {
x_weight_[j] = Eigen::Map <const MatrixXf> (weight[j].data(), in_dim_[1], out_dim_[1]);
}
// load H-weight
for (int j = 8; j < 12; j ++) {
h_weight_[j] = Eigen::Map <const MatrixXf> (weight[j].data(), out_dim_[1], out_dim_[1]);
}
// select the appropriate size of thread pool and calculate the spread in thread executions
thread_pool_.resize(in_dim_[0] <= std::thread::hardware_concurrency() ? in_dim_[0] : in_dim_[0] % std::thread::hardware_concurrency() + 1);
slope_ = in_dim_[0] / thread_pool_.size();
}
private:
Dim2d in_dim_, out_dim_; // input and output shapes
std::string recurrent_activation_; // recurrent act. name
MatrixXf input_, output_, delta_, dh_, dh_ct_; // input and dH matrices
std::vector<float> vw_ {4, 1.0}, vh_ {4, 1.0}, vb_ {4, 1.0}; // weight- and bias-momentum vectors
MatrixXfVec x_weight_, h_weight_, bias_, gate_, dgate_, state_; // weight, bias, gate ouutputs, state = [c(t), g(c(t)), c(t - 1), h(t - 1)]
std::function <void (MatrixXf &, MatrixXf &, const int &)> activate_, reactivate_; // empty functions for activation and recurrent activation functions
void RUpdate(MatrixXfVec &dc, MatrixXfVec &dhg,
MatrixXfVec &db, MatrixXfVec &dxw,
MatrixXfVec &dhw, int s, const int end) {
int e; // end time
MatrixXfVec dzp; dzp.resize(4); // gradient of each gate during bptt
MatrixXf dhp = MatrixXf::Zero(1, out_dim_[1]), // dH(t - 1)
dcp = MatrixXf::Zero(1, out_dim_[1]); // dC(t - 1)
for (s; s > end; s --) {
e = randint <int> (-1, s);
#pragma omp parallel
{
#pragma omp for simd nowait
for (int j = 0; j < 4; j ++) {
db[j] = db[j] + dhg[j].row(s);
dxw[j] = dxw[j] + (input_.col(s) * dhg[j].row(s));
dhw[j] = dhw[j] + (state_[3].col(s) * dhg[j].row(s));
}
}
dhp = dhg[0].row(s) * h_weight_[0] + dhg[1].row(s) * h_weight_[1] + dhg[2].row(s) * h_weight_[2] + dhg[3].row(s) * h_weight_[3];
dcp = dh_.row(s).cwiseProduct(gate_[2].row(s)).cwiseProduct(dh_ct_.row(s)).cwiseProduct(gate_[0].row(s));
for (int t = s - 1; t > e; t --) {
// calculate gradient of each gate for each time step
dzp[0] = dhp.cwiseProduct(dgate_[0].row(t)) + dcp.cwiseProduct(dc[0].row(t));
dzp[1] = dhp.cwiseProduct(dgate_[1].row(t)) + dcp.cwiseProduct(dc[1].row(t));
dzp[3] = dhp.cwiseProduct(dgate_[3].row(t)) + dcp.cwiseProduct(dc[2].row(t));
dzp[2] = dhp.cwiseProduct(dgate_[2].row(t));
#pragma omp parallel
{
#pragma omp for simd nowait
for (int j = 0; j < 4; j ++) {
db[j] = db[j] + dzp[0];
dxw[j] = dxw[j] + input_.col(t) * dzp[j];
dhw[j] = dhw[j] + state_[3].col(t) * dzp[j];
}
}
if (t > e + 1) {
dhp = dzp[0] * h_weight_[0] + dzp[1] * h_weight_[1] + dzp[2] * h_weight_[2] + dzp[3] * h_weight_[3];
dcp = dcp.cwiseProduct(gate_[0].row(t));
}
}
}
}
};
}
#endif
| 43.919271 | 178 | 0.575274 | [
"shape",
"vector"
] |
e7d6f4ec82b8ade05a37bf536a6f5300bf0490c1 | 481 | hpp | C++ | source/discord/guild.hpp | kociap/Discord- | fcbf30d199ec217e0e6289aee96e365de383dbda | [
"MIT"
] | null | null | null | source/discord/guild.hpp | kociap/Discord- | fcbf30d199ec217e0e6289aee96e365de383dbda | [
"MIT"
] | 2 | 2019-01-15T07:38:54.000Z | 2019-01-15T07:44:35.000Z | source/discord/guild.hpp | kociap/Discord- | fcbf30d199ec217e0e6289aee96e365de383dbda | [
"MIT"
] | 1 | 2018-10-25T12:12:34.000Z | 2018-10-25T12:12:34.000Z | #ifndef DISCORD_GUILD_HPP
#define DISCORD_GUILD_HPP
#include "nlohmann/json.hpp"
#include "types.hpp"
namespace discord {
struct Guild {
String name;
Snowflake id;
uint64 permissions;
bool owner;
static Guild from_json(nlohmann::json const&);
};
using Guilds = std::vector<Guild>;
// nlohmann::json specific function
void from_json(nlohmann::json const&, Guild&);
} // namespace discord
#endif // DISCORD_GUILD_HPP
| 20.041667 | 54 | 0.665281 | [
"vector"
] |
e7dd216e0eea35497d308e891956ab1f32f4a769 | 5,258 | cpp | C++ | src/lab_m1/lab1/lab1.cpp | bogpie/ComputerGraphics | 750a1d16d1e37d492438a93f05159b4e9a9ea226 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | src/lab_m1/lab1/lab1.cpp | bogpie/ComputerGraphics | 750a1d16d1e37d492438a93f05159b4e9a9ea226 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | src/lab_m1/lab1/lab1.cpp | bogpie/ComputerGraphics | 750a1d16d1e37d492438a93f05159b4e9a9ea226 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | #include "lab_m1/lab1/lab1.h"
#include <vector>
#include <iostream>
#include <string>
using namespace std;
using namespace m1;
float redValue, greenValue, blueValue, xPos, yPos, zPos, yLimit;
bool falling;
vector<string> primitives{ "teapot", "box", "sphere" };
int currentPrimitive;
/*
* To find out more about `FrameStart`, `Update`, `FrameEnd`
* and the order in which they are called, see `world.cpp`.
*/
Lab1::Lab1()
{
// TODO(student): Never forget to initialize class variables!
}
Lab1::~Lab1()
{
}
bool isGrounded() {
return yPos == 0;
}
void Lab1::Init()
{
redValue = 0;
greenValue = 0;
blueValue = 0;
currentPrimitive = 0;
xPos = 0;
yPos = 0;
zPos = 0;
yLimit = 0.3;
falling = false;
// Load a mesh from file into GPU memory. We only need to do it once,
// no matter how many times we want to draw this mesh.
{
Mesh* mesh = new Mesh("box");
mesh->LoadMesh(PATH_JOIN(window->props.selfDir, RESOURCE_PATH::MODELS, "primitives"), "box.obj");
meshes[mesh->GetMeshID()] = mesh;
}
// TODO(student): Load some more meshes. The value of RESOURCE_PATH::MODELS
// is actually a path on disk, go there and you will find more meshes.
{
Mesh* mesh = new Mesh("teapot");
mesh->LoadMesh(PATH_JOIN(window->props.selfDir, RESOURCE_PATH::MODELS, "primitives"), "teapot.obj");
meshes[mesh->GetMeshID()] = mesh;
}
{
Mesh* mesh = new Mesh("sphere");
mesh->LoadMesh(PATH_JOIN(window->props.selfDir, RESOURCE_PATH::MODELS, "primitives"), "sphere.obj");
meshes[mesh->GetMeshID()] = mesh;
}
}
void Lab1::FrameStart()
{
}
void Lab1::Update(float deltaTimeSeconds)
{
glm::ivec2 resolution = window->props.resolution;
// Sets the clear color for the color buffer
// TODO(student): Generalize the arguments of `glClearColor`.
// You can, for example, declare three variables in the class header,
// that will store the color components (red, green, blue).
glClearColor(redValue, greenValue, blueValue, 1);
// Clears the color buffer (using the previously set color) and depth buffer
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Sets the screen area where to draw
glViewport(0, 0, resolution.x, resolution.y);
// Render the object
RenderMesh(meshes["box"], glm::vec3(1, 0.5f, 0), glm::vec3(0.5f));
// Render the object again but with different properties
RenderMesh(meshes["box"], glm::vec3(-1, 0.5f, 0));
// TODO(student): We need to render (a.k.a. draw) the mesh that
// was previously loaded. We do this using `RenderMesh`. Check the
// signature of this function to see the meaning of its parameters.
// You can draw the same mesh any number of times.
if (isGrounded()) {
falling = false;
}
// Simulate gravity
if (falling) {
yPos = yPos - deltaTimeSeconds >= 0 ? yPos - deltaTimeSeconds * 0.75 : 0;
}
RenderMesh(meshes[primitives[currentPrimitive]], glm::vec3(xPos, yPos, zPos));
}
void Lab1::FrameEnd()
{
DrawCoordinateSystem();
}
/*
* These are callback functions. To find more about callbacks and
* how they behave, see `input_controller.h`.
*/
void Lab1::OnInputUpdate(float deltaTime, int mods)
{
// Treat continuous update based on input
// TODO(student): Add some key hold events that will let you move
// a mesh instance on all three axes. You will also need to
// generalize the position used by `RenderMesh`.
if (window->KeyHold(GLFW_KEY_W)) {
zPos -= deltaTime;
}
if (window->KeyHold(GLFW_KEY_A)) {
xPos -= deltaTime;
}
if (window->KeyHold(GLFW_KEY_S)) {
zPos += deltaTime;
}
if (window->KeyHold(GLFW_KEY_D)) {
xPos += deltaTime;
}
// Ensure it always stays above ground
if (window->KeyHold(GLFW_KEY_E) && yPos - deltaTime >= 0) {
yPos -= deltaTime;
}
if (window->KeyHold(GLFW_KEY_Q)) {
yPos += deltaTime;
}
if (window->KeyHold(GLFW_KEY_SPACE)) {
if (!falling) {
if (yPos + deltaTime <= yLimit) {
yPos += deltaTime;
}
else {
falling = true;
}
}
}
else {
// Prevent double jumping
falling = true;
/*if (yPos - deltaTime >= 0) {
yPos -= deltaTime * 0.5f;
}*/
}
}
void Lab1::OnKeyPress(int key, int mods)
{
// Add key press event
if (key == GLFW_KEY_F) {
// TODO(student): Change the values of the color components.
redValue = 1;
blueValue = 1;
greenValue = 0.2f;
}
// TODO(student): Add a key press event that will let you cycle
// through at least two meshes, rendered at the same position.
// You will also need to generalize the mesh name used by `RenderMesh`.
if (key == GLFW_KEY_R) {
currentPrimitive = currentPrimitive == primitives.size() - 1 ? 0 : currentPrimitive + 1;
}
if (key == GLFW_KEY_SPACE) {
falling = !isGrounded();
}
}
void Lab1::OnKeyRelease(int key, int mods)
{
// Add key release event
}
void Lab1::OnMouseMove(int mouseX, int mouseY, int deltaX, int deltaY)
{
// Add mouse move event
}
void Lab1::OnMouseBtnPress(int mouseX, int mouseY, int button, int mods)
{
// Add mouse button press event
}
void Lab1::OnMouseBtnRelease(int mouseX, int mouseY, int button, int mods)
{
// Add mouse button release event
}
void Lab1::OnMouseScroll(int mouseX, int mouseY, int offsetX, int offsetY)
{
// Treat mouse scroll event
}
void Lab1::OnWindowResize(int width, int height)
{
// Treat window resize event
}
| 21.727273 | 102 | 0.679726 | [
"mesh",
"render",
"object",
"vector"
] |
e7fbc5e12733f694377b39e4f7598b5196aec3d2 | 10,277 | cpp | C++ | higan/target-bsnes/program/platform.cpp | 13824125580/higan | fbdd3f980b65412c362096579869ae76730e4118 | [
"Intel",
"ISC"
] | 10 | 2019-12-19T01:19:41.000Z | 2021-02-18T16:30:29.000Z | higan/target-bsnes/program/platform.cpp | 13824125580/higan | fbdd3f980b65412c362096579869ae76730e4118 | [
"Intel",
"ISC"
] | null | null | null | higan/target-bsnes/program/platform.cpp | 13824125580/higan | fbdd3f980b65412c362096579869ae76730e4118 | [
"Intel",
"ISC"
] | null | null | null | #include <nall/encode/bmp.hpp>
#include <icarus/heuristics/heuristics.hpp>
#include <icarus/heuristics/heuristics.cpp>
#include <icarus/heuristics/super-famicom.cpp>
#include <icarus/heuristics/game-boy.cpp>
#include <icarus/heuristics/bs-memory.cpp>
#include <icarus/heuristics/sufami-turbo.cpp>
//ROM data is held in memory to support compressed archives, soft-patching, and game hacks
auto Program::open(uint id, string name, vfs::file::mode mode, bool required) -> vfs::shared::file {
vfs::shared::file result;
if(id == 0) { //System
if(name == "boards.bml" && mode == vfs::file::mode::read) {
result = vfs::memory::file::open(Resource::System::Boards, sizeof(Resource::System::Boards));
}
if(name == "ipl.rom" && mode == vfs::file::mode::read) {
result = vfs::memory::file::open(Resource::System::IPLROM, sizeof(Resource::System::IPLROM));
}
}
if(id == 1) { //Super Famicom
if(name == "manifest.bml" && mode == vfs::file::mode::read) {
result = vfs::memory::file::open(superFamicom.manifest.data<uint8_t>(), superFamicom.manifest.size());
} else if(name == "program.rom" && mode == vfs::file::mode::read) {
result = vfs::memory::file::open(superFamicom.program.data(), superFamicom.program.size());
} else if(name == "data.rom" && mode == vfs::file::mode::read) {
result = vfs::memory::file::open(superFamicom.data.data(), superFamicom.data.size());
} else if(name == "expansion.rom" && mode == vfs::file::mode::read) {
result = vfs::memory::file::open(superFamicom.expansion.data(), superFamicom.expansion.size());
} else if(superFamicom.location.endsWith("/")) {
result = openPakSuperFamicom(name, mode);
} else {
result = openRomSuperFamicom(name, mode);
}
}
if(id == 2) { //Game Boy
if(name == "manifest.bml" && mode == vfs::file::mode::read) {
result = vfs::memory::file::open(gameBoy.manifest.data<uint8_t>(), gameBoy.manifest.size());
} else if(name == "program.rom" && mode == vfs::file::mode::read) {
result = vfs::memory::file::open(gameBoy.program.data(), gameBoy.program.size());
} else if(gameBoy.location.endsWith("/")) {
result = openPakGameBoy(name, mode);
} else {
result = openRomGameBoy(name, mode);
}
}
if(id == 3) { //BS Memory
if(name == "manifest.bml" && mode == vfs::file::mode::read) {
result = vfs::memory::file::open(bsMemory.manifest.data<uint8_t>(), bsMemory.manifest.size());
} else if(name == "program.rom" && mode == vfs::file::mode::read) {
result = vfs::memory::file::open(bsMemory.program.data(), bsMemory.program.size());
} else if(name == "program.flash") {
//writes are not flushed to disk in bsnes
result = vfs::memory::file::open(bsMemory.program.data(), bsMemory.program.size());
} else if(bsMemory.location.endsWith("/")) {
result = openPakBSMemory(name, mode);
} else {
result = openRomBSMemory(name, mode);
}
}
if(id == 4) { //Sufami Turbo - Slot A
if(name == "manifest.bml" && mode == vfs::file::mode::read) {
result = vfs::memory::file::open(sufamiTurboA.manifest.data<uint8_t>(), sufamiTurboA.manifest.size());
} else if(name == "program.rom" && mode == vfs::file::mode::read) {
result = vfs::memory::file::open(sufamiTurboA.program.data(), sufamiTurboA.program.size());
} else if(sufamiTurboA.location.endsWith("/")) {
result = openPakSufamiTurboA(name, mode);
} else {
result = openRomSufamiTurboA(name, mode);
}
}
if(id == 5) { //Sufami Turbo - Slot B
if(name == "manifest.bml" && mode == vfs::file::mode::read) {
result = vfs::memory::file::open(sufamiTurboB.manifest.data<uint8_t>(), sufamiTurboB.manifest.size());
} else if(name == "program.rom" && mode == vfs::file::mode::read) {
result = vfs::memory::file::open(sufamiTurboB.program.data(), sufamiTurboB.program.size());
} else if(sufamiTurboB.location.endsWith("/")) {
result = openPakSufamiTurboB(name, mode);
} else {
result = openRomSufamiTurboB(name, mode);
}
}
if(!result && required) {
if(MessageDialog({
"Error: missing required data: ", name, "\n\n",
"Would you like to view the online documentation for more information?"
}).setParent(*presentation).error({"Yes", "No"}) == "Yes") {
presentation.documentation.doActivate();
}
}
return result;
}
auto Program::load(uint id, string name, string type, vector<string> options) -> Emulator::Platform::Load {
BrowserDialog dialog;
dialog.setParent(*presentation);
dialog.setOptions(options);
if(id == 1 && name == "Super Famicom" && type == "sfc") {
if(gameQueue) {
auto game = gameQueue.takeLeft().split(";", 1L);
superFamicom.option = game(0);
superFamicom.location = game(1);
} else {
dialog.setTitle("Load Super Famicom");
dialog.setPath(path("Games", settings.path.recent.superFamicom));
dialog.setFilters({string{"Super Famicom Games|*.sfc:*.smc:*.zip"}});
superFamicom.location = dialog.openObject();
superFamicom.option = dialog.option();
}
if(inode::exists(superFamicom.location)) {
settings.path.recent.superFamicom = Location::dir(superFamicom.location);
if(loadSuperFamicom(superFamicom.location)) {
return {id, superFamicom.option};
}
}
}
if(id == 2 && name == "Game Boy" && type == "gb") {
if(gameQueue) {
auto game = gameQueue.takeLeft().split(";", 1L);
gameBoy.option = game(0);
gameBoy.location = game(1);
} else {
dialog.setTitle("Load Game Boy");
dialog.setPath(path("Games", settings.path.recent.gameBoy));
dialog.setFilters({string{"Game Boy Games|*.gb:*.gbc:*.zip"}});
gameBoy.location = dialog.openObject();
gameBoy.option = dialog.option();
}
if(inode::exists(gameBoy.location)) {
settings.path.recent.gameBoy = Location::dir(gameBoy.location);
if(loadGameBoy(gameBoy.location)) {
return {id, gameBoy.option};
}
}
}
if(id == 3 && name == "BS Memory" && type == "bs") {
if(gameQueue) {
auto game = gameQueue.takeLeft().split(";", 1L);
bsMemory.option = game(0);
bsMemory.location = game(1);
} else {
dialog.setTitle("Load BS Memory");
dialog.setPath(path("Games", settings.path.recent.bsMemory));
dialog.setFilters({string{"BS Memory Games|*.bs:*.zip"}});
bsMemory.location = dialog.openObject();
bsMemory.option = dialog.option();
}
if(inode::exists(bsMemory.location)) {
settings.path.recent.bsMemory = Location::dir(bsMemory.location);
if(loadBSMemory(bsMemory.location)) {
return {id, bsMemory.option};
}
}
}
if(id == 4 && name == "Sufami Turbo" && type == "st") {
if(gameQueue) {
auto game = gameQueue.takeLeft().split(";", 1L);
sufamiTurboA.option = game(0);
sufamiTurboA.location = game(1);
} else {
dialog.setTitle("Load Sufami Turbo - Slot A");
dialog.setPath(path("Games", settings.path.recent.sufamiTurboA));
dialog.setFilters({string{"Sufami Turbo Games|*.st:*.zip"}});
sufamiTurboA.location = dialog.openObject();
sufamiTurboA.option = dialog.option();
}
if(inode::exists(sufamiTurboA.location)) {
settings.path.recent.sufamiTurboA = Location::dir(sufamiTurboA.location);
if(loadSufamiTurboA(sufamiTurboA.location)) {
return {id, sufamiTurboA.option};
}
}
}
if(id == 5 && name == "Sufami Turbo" && type == "st") {
if(gameQueue) {
auto game = gameQueue.takeLeft().split(";", 1L);
sufamiTurboB.option = game(0);
sufamiTurboB.location = game(1);
} else {
dialog.setTitle("Load Sufami Turbo - Slot B");
dialog.setPath(path("Games", settings.path.recent.sufamiTurboB));
dialog.setFilters({string{"Sufami Turbo Games|*.st:*.zip"}});
sufamiTurboB.location = dialog.openObject();
sufamiTurboB.option = dialog.option();
}
if(inode::exists(sufamiTurboB.location)) {
settings.path.recent.sufamiTurboB = Location::dir(sufamiTurboB.location);
if(loadSufamiTurboB(sufamiTurboB.location)) {
return {id, sufamiTurboB.option};
}
}
}
return {};
}
auto Program::videoRefresh(uint display, const uint32* data, uint pitch, uint width, uint height) -> void {
uint32_t* output;
uint length;
//this relies on the UI only running between Emulator::Scheduler::Event::Frame events
//this will always be the case; so we can avoid an unnecessary copy or one-frame delay here
//if the core were to exit between a frame event, the next frame might've been only partially rendered
screenshot.data = data;
screenshot.pitch = pitch;
screenshot.width = width;
screenshot.height = height;
pitch >>= 2;
if(!presentation.showOverscanArea.checked()) {
if(height == 240) data += 8 * pitch, height -= 16;
if(height == 480) data += 16 * pitch, height -= 32;
}
if(video.acquire(output, length, width, height)) {
length >>= 2;
for(auto y : range(height)) {
memory::copy<uint32>(output + y * length, data + y * pitch, width);
}
video.release();
video.output();
}
inputManager.frame();
if(frameAdvance) {
frameAdvance = false;
presentation.pauseEmulation.setChecked();
}
static uint frameCounter = 0;
static uint64 previous, current;
frameCounter++;
current = chrono::timestamp();
if(current != previous) {
previous = current;
showFrameRate({frameCounter, " FPS"});
frameCounter = 0;
}
}
auto Program::audioSample(const double* samples, uint channels) -> void {
audio.output(samples);
}
auto Program::inputPoll(uint port, uint device, uint input) -> int16 {
if(focused() || emulatorSettings.allowInput().checked()) {
inputManager.poll();
if(auto mapping = inputManager.mapping(port, device, input)) {
return mapping->poll();
}
}
return 0;
}
auto Program::inputRumble(uint port, uint device, uint input, bool enable) -> void {
if(focused() || emulatorSettings.allowInput().checked() || !enable) {
if(auto mapping = inputManager.mapping(port, device, input)) {
return mapping->rumble(enable);
}
}
}
| 36.835125 | 108 | 0.633356 | [
"vector"
] |
f011ea67a9ef12574349843f86973f75d8fa4f40 | 53,229 | cxx | C++ | com/rpc/runtime/trans/common/protocol.cxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | com/rpc/runtime/trans/common/protocol.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | com/rpc/runtime/trans/common/protocol.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /*++
Copyright (C) Microsoft Corporation, 1996 - 1999
Module Name:
Protocol.cxx
Abstract:
Transport Protocol abstraction used mainly by PnP.
The following is a brief description of the current RPC PnP mechanism:
Whenever a non-local transport level object (a socket, or an address) is opened
for a given protocol, it is added to the list of objects for the given protocol.
This alllows all objects for a given protocol to be tracked down and closed if
the protocol is unloaded. By the same token, objects closed are removed from
the list of the given protocol.
When a PnP notification arrives, the lower level transport code call into this PnP module
to tell it that there may be a change of state. For each PnP protocol, the PnP code
examines whether the protocol is active, and what was its last state. Depending of
the outcome of this comparison, it will take appropriate action. Here's the finite
state automaton with the transitions:
Currently, RPC differentiates between four networking states of each protocol -
protocol is not loaded, protocol is partially loaded (i.e. it is active, but
does not have an address on it yet), it is fully loaded (or functional), and
it is fully loaded and network address change monitoring is required. The
fully loaded state with address change monitoring may be abbreviated to
FunctionalMon for the purpose of this document.
Note that Partially Loaded, and loaded without address are equivalent terms
for the purpose of this module. Also, note that currently the networking
code does not allow reloading of a protocol, so some of the code paths will
never get exercised.
RPC in turn maintains the following RPC (as opposed to networking) states:
ProtocolNotLoaded
ProtocolLoadedWithoutAddress
ProtocolWasLoadedOrNeedsActivation
ProtocolLoaded
ProtocolWasLoadedOrNeedsActivationWithoutAddress
ProtocolLoadedAndMonitored
Depending on the last RPC state, and the new networking state, the following changes
and state transitions are effected:
If a PnP notification fails asynchronously, the completion port code will call into PnP
code to try to resubmit the queries.
Note that the threads on which overlapped WSAIoctl's are submitted are not protected.
If a thread dies, the IO will fail, and the thread that picks the failure will resubmit
the WSAIoctl. This strategy allows up to keep the thread pool smaller.
Networking State Action
RPC State
ProtocolNotLoaded NotLoaded No-op
PartiallyLoaded Submit a WSAIoctl to be notified
when the protocol becomes
functional.
State = ProtocolLoadedWithoutAddress
Functional State = ProtocolLoaded
FunctionalMon Submit address change WSAIoctl.
State = ProtocolLoadedAndMonitored
ProtocolLoadedWithoutAddress NotLoaded Cancel WSAIoctl
State = ProtocolNotLoaded
PartiallyLoaded No-op
Functional CancelWSAIoctl
State = ProtocolLoaded
FunctionalMon Submit address change WSAIoctl if necessary
State = ProtocolLoadedAndMonitored
ProtocolWasLoadedOrNeedsActivation NotLoaded No-op
PartiallyLoaded Submit a WSAIoctl to be notified
when the protocol becomes
functional.
State = ProtocolWasLoadedOrNeedsActivationWithoutAddress
Functional Restart protocol
State = ProtocolLoaded
FunctionalMon Submit address change WSAIoctl.
State = ProtocolLoadedAndMonitored
ProtocolLoaded NotLoaded Unload protocol
State = ProtocolWasLoadedOrNeedsActivation
PartiallyLoaded Invalid
Functional No-op
FunctionalMon Invalid transition
ProtocolWasLoadedOrNeedsActivationWithoutAddress
NotLoaded Cancel WSAIoctl
State = ProtocolWasLoadedOrNeedsActivation
PartiallyLoaded No-op
Functional Restart protocol
State = ProtocolLoaded
FunctionalMon Submit address change WSAIoctl.
State = ProtocolLoadedAndMonitored
ProtocolLoadedAndMonitored NotLoaded Cancel address change WSAIoctl
Unload protocol
State = ProtocolWasLoadedOrNeedsActivation
PartiallyLoaded Resubmit address change WSAIoclt if necessary
Functional Invalid transition
FunctionalMon No-op
ProtocolNeedToLoadWhenReady NotLoaded No-op
PartiallyLoaded Submit a WSAIoctl to be notified
when the protocol becomes
functional.
State = ProtocolNeedToLoadWhenReadyWithoutAddress
Functional Restart protocol
State = ProtocolLoaded
FunctionalMon Submit address change WSAIoctl.
State = ProtocolLoadedAndMonitored
ProtocolNeedToLoadWhenReadyWithoutAddress
NotLoaded Cancel WSAIoctl
State = ProtocolNeedToLoadWhenReady
PartiallyLoaded No-op
Functional Restart protocol
State = ProtocolLoaded
FunctionalMon Submit address change WSAIoctl.
State = ProtocolLoadedAndMonitored
Author:
Kamen Moutafov [KamenM]
Revision History:
KamenM 12/22/1998 Creation
KamenM 03/05/1999 Adding state ProtocolLoadedAndMonitored and support for it.
KamenM 07/17/2000 Adding support for ProtocolWasLoadedOrNeedsActivation/
ProtocolWasLoadedOrNeedsActivationWithoutAddress
--*/
#include <precomp.hxx>
#include <Protocol.hxx>
void RPC_ENTRY NullAddressChangeFn( PVOID arg )
{
}
RPC_ADDRESS_CHANGE_FN * AddressChangeFn = NullAddressChangeFn;
#ifdef MAJOR_PNP_DEBUG
const char *ProtocolStateNames[];
#endif
void TransportProtocol::DetectedAsFunctional(PROTOCOL_ID ProtocolId)
{
if (IsAddressChangeMonitoringOn(ProtocolId))
{
EnterCriticalSection(&AddressListLock);
// monitor functional protocols for address change will
// set the state
MonitorFunctionalProtocolForAddressChange(ProtocolId);
LeaveCriticalSection(&AddressListLock);
}
else
{
// we also need to take the critical section, and cancel any address change
// notification (if any), to avoid race between a successful listen making
// the protocol functional, and the address change notification completing
EnterCriticalSection(&AddressListLock);
CancelAddressChangeRequestIfNecessary(FALSE, ProtocolId);
SetState(ProtocolLoaded, ProtocolId);
LeaveCriticalSection(&AddressListLock);
}
}
void TransportProtocol::HandleProtocolChange(IN WSAPROTOCOL_INFO *lpProtocolBuffer,
IN int ProtocolCount,
IN PROTOCOL_ID thisProtocolId)
/*++
Function Name: HandleProtocolChange
Parameters:
lpProtocolBuffer - an array of WSAPROTOCOL_INFO structures as returned by EnumProtocols
ProtocolCount - the number of elements in the lpProtocolBuffer array
thisProtocolId - the ID of the protocol for this object
Description:
This handles protocol state change for a particular protocol. The function is idempotent - it
can be called many times safely, regardless of previous calls. It will turn into no-op if
it is redundant.
Returns:
--*/
{
int i;
BOOL fProtocolActive = FALSE;
const WS_TRANS_INFO *pInfo;
ASSERT(ProtocolCount >= 0);
ASSERT(lpProtocolBuffer != NULL);
ASSERT_TRANSPORT_PROTOCOL_STATE(thisProtocolId);
if (
#ifdef NETBIOS_ON
(thisProtocolId == NBF) || (thisProtocolId == NBT) || (thisProtocolId == NBI) ||
#endif
#ifdef NCADG_MQ_ON
(thisProtocolId == MSMQ) ||
#endif
(thisProtocolId == CDP)
)
return;
if (IsTrailingProtocol(thisProtocolId))
return;
for (i = 0; i < ProtocolCount; i ++)
{
// if the enumerated protocol is the current protocol, break out of the loop
if (MapProtocolId(lpProtocolBuffer[i].iProtocol, lpProtocolBuffer[i].iAddressFamily) == thisProtocolId)
{
fProtocolActive = TRUE;
break;
}
}
pInfo = &WsTransportTable[thisProtocolId];
switch(State)
{
case ProtocolNotLoaded:
case ProtocolLoadedWithoutAddress:
// if the protocol was not loaded, but now it is active, attempt to verify
// it is operational
if (fProtocolActive)
{
#ifdef MAJOR_PNP_DEBUG
if (State == ProtocolNotLoaded)
{
DbgPrint("Protocol %d was just loaded\n", thisProtocolId);
}
#endif
// If the protocol is not fully functional, we will submit an address change
// request to get notified when it does
if (VerifyProtocolIsFunctional(thisProtocolId) == TRUE)
{
// we succeeded in changing the state of the protocol
ASSERT((State == ProtocolLoaded) || (State == ProtocolLoadedAndMonitored));
if (IsAddressChangeMonitoringOn(thisProtocolId))
{
if (FirewallTableNeedsUpdating())
{
DoFirewallUpdate();
}
// If the only reason we were monitoring this protocol
// is to finish initializing the firewall table, then
// we may not continue monitoring for address change if
// the table has finished initializing after DoFirewallUpdate().
if(IsAddressChangeMonitoringOn(thisProtocolId))
{
MonitorFunctionalProtocolForAddressChange(thisProtocolId);
}
if (IsAddressChangeFnDefined())
{
(*AddressChangeFn)((PVOID) State);
}
}
}
#ifdef MAJOR_PNP_DEBUG
if (State == ProtocolLoadedWithoutAddress)
{
DbgPrint("Protocol %d was without an address\n", thisProtocolId);
}
#endif
}
else
{
if (State == ProtocolLoadedWithoutAddress)
{
// a protocol was removed without being fully initialized
// cancel the pending query if any, and reset the state to not loaded
CancelAddressChangeRequestIfNecessary(TRUE, thisProtocolId);
SetState(ProtocolNotLoaded, thisProtocolId);
#ifdef MAJOR_PNP_DEBUG
DbgPrint("Protocol %d was removed without being fully initialized\n", thisProtocolId);
#endif
}
// else - don't care. The protocol state is not loaded, and will remain so
}
break;
case ProtocolWasLoadedOrNeedsActivation:
case ProtocolWasLoadedOrNeedsActivationWithoutAddress:
if (fProtocolActive)
{
// If the protocol is not fully functional, we will submit an address change
// request to get notified when it does
if (VerifyProtocolIsFunctional(thisProtocolId))
{
// if a protocol was loaded, and now is active, restart the addresses on it
RestartProtocol(thisProtocolId);
if (thisProtocolId == TCP)
{
GetTransportProtocol(HTTP)->RestartProtocol(HTTP);
}
// we succeeded in changing the state of the protocol
ASSERT(State == ProtocolLoaded);
if (IsAddressChangeMonitoringOn(thisProtocolId))
{
MonitorFunctionalProtocolForAddressChange(thisProtocolId);
}
}
}
else
{
// if the protocol was loaded, but it's not active, we don't care;
// if it was trying to get an address, but then it was unloaded,
// cancel the request
if (State == ProtocolWasLoadedOrNeedsActivationWithoutAddress)
{
CancelAddressChangeRequestIfNecessary(TRUE, thisProtocolId);
SetState(ProtocolWasLoadedOrNeedsActivation, thisProtocolId);
#ifdef MAJOR_PNP_DEBUG
DbgPrint("Protocol %d was removed without being fully initialized\n", thisProtocolId);
#endif
}
}
break;
case ProtocolLoaded:
ASSERT(IsAddressChangeMonitoringOn(thisProtocolId) == FALSE);
// if the protocol was loaded, and it is active, we don't need to do anything;
// if it was loaded, but is not active currently, we need to unload the protocol
if (!fProtocolActive)
{
#ifdef MAJOR_PNP_DEBUG
DbgPrint("Protocol %d was just unloaded\n", thisProtocolId);
#endif
UnloadProtocol(thisProtocolId);
if (thisProtocolId == TCP)
{
GetTransportProtocol(HTTP)->UnloadProtocol(HTTP);
}
SetState(ProtocolWasLoadedOrNeedsActivation, thisProtocolId);
}
break;
case ProtocolLoadedAndMonitored:
// if it was loaded, but is not active currently, we need to unload the protocol
if (!fProtocolActive)
{
#ifdef MAJOR_PNP_DEBUG
DbgPrint("Protocol %d was just unloaded\n", thisProtocolId);
#endif
if (FirewallTableNeedsUpdating())
{
DoFirewallUpdate();
}
CancelAddressChangeRequestIfNecessary(TRUE, thisProtocolId);
UnloadProtocol(thisProtocolId);
if (thisProtocolId == TCP)
{
GetTransportProtocol(HTTP)->UnloadProtocol(HTTP);
}
SetState(ProtocolWasLoadedOrNeedsActivation, thisProtocolId);
if (IsAddressChangeFnDefined())
{
(*AddressChangeFn)((PVOID) State);
}
}
else
{
#ifdef MAJOR_PNP_DEBUG
DbgPrint("Protocol %d is monitored and received event\n", thisProtocolId);
#endif
if (FirewallTableNeedsUpdating())
{
DoFirewallUpdate();
}
if (IsAddressChangeFnDefined())
{
(*AddressChangeFn)((PVOID) State);
}
}
break;
#if defined(DBG) || defined(_DEBUG)
default:
ASSERT(!"Invalid State");
#endif
}
ASSERT_TRANSPORT_PROTOCOL_STATE(thisProtocolId);
}
void TransportProtocol::AddObjectToList(IN OUT BASE_ASYNC_OBJECT *pObj)
/*++
Function Name: AddObjectToList
Parameters:
pObj - the object to be added
Description:
Add the object to the list of transport objects for this protocol.
Returns:
--*/
{
EnterCriticalSection(&AddressListLock);
RpcpfInsertHeadList(&ObjectList, &pObj->ObjectList);
LeaveCriticalSection(&AddressListLock);
}
void TransportProtocol::RemoveObjectFromList(IN OUT BASE_ASYNC_OBJECT *pObj)
/*++
Function Name: RemoveObjectFromList
Parameters:
pObj - the object to be removed
Description:
Removes the object from the list of transport objects for this protocol.
Returns:
--*/
{
BASE_ASYNC_OBJECT *Prev, *Cur;
Prev = NULL;
EnterCriticalSection(&AddressListLock);
RpcpfRemoveEntryList(&pObj->ObjectList);
LeaveCriticalSection(&AddressListLock);
}
BOOL TransportProtocol::ResubmitQueriesIfNecessary(PROTOCOL_ID ProtocolId)
/*++
Function Name: ResubmitQueriesIfNecessary
Parameters:
ProtocolId - the ID of the current protocol
Description:
If there was a WSAIoctl pending that failed, it will be resubmitted.
If this protocol was being monitored, try to restart monitoring if necessary
Returns:
FALSE if the WSAIoctl was not resubmitted successfully.
TRUE if the WSAIoctl was resubmitted successfully, or there was no need to resubmit it.
--*/
{
if (addressChangeSocket)
{
if ((addressChangeOverlapped.Internal != 0) && (addressChangeOverlapped.Internal != STATUS_PENDING))
{
if (SubmitAddressChangeQuery() == FALSE)
return FALSE;
}
}
if (State == ProtocolLoadedAndMonitored)
{
if (MonitorFunctionalProtocolForAddressChange(ProtocolId) == FALSE)
return FALSE;
}
return TRUE;
}
PROTOCOL_ID
MapProtocolId (
IN UINT ProtocolId,
IN UINT AddressFamily
)
/*++
Function Name: MapProtocolId
Parameters:
ProtocolId - Winsock protocol ID
AddressFamily - Winsock address family
Description:
Converts a Winsock Protocol ID to a RPC Transport protocol ID.
Returns:
The RPC Transport Protocol ID if successfull, or -1 if no mapping can be found
--*/
{
unsigned id;
for (id = 1; id < cWsTransportTable; id++)
{
if ((WsTransportTable[id].Protocol == (int) ProtocolId)
&& (WsTransportTable[id].AddressFamily == (int) AddressFamily))
{
return id;
}
}
return -1;
}
BOOL TransportProtocol::HandlePnPStateChange(void)
/*++
Function Name: HandlePnPNotification
Parameters:
Description:
Whenever a PnP notification (NewAddress) arrives, the completion port will direct it
to this routine, which will handle all state management and all handling of the PnP
notification.
Returns:
TRUE if the runtime should be notified that a protocol state change has occurred.
FALSE if the run time should not be notified, or need not be notified that a
protocol state change has occurred.
--*/
{
int i;
//
// Enumerate the currently loaded protocols
//
WSAPROTOCOL_INFO *lpProtocolBuffer;
DWORD dwBufferLength = 512;
int ProtocolCount;
PROTOCOL_ID ProtocolId;
TransportProtocol *pCurrentProtocol;
BOOL fRetVal;
EnterCriticalSection(&AddressListLock);
ASSERT(hWinsock2);
while (1)
{
lpProtocolBuffer = (WSAPROTOCOL_INFO *) I_RpcAllocate(dwBufferLength);
if (lpProtocolBuffer == 0)
{
fRetVal = FALSE;
goto CleanupAndReturn;
}
ProtocolCount = WSAEnumProtocolsT(
0,
lpProtocolBuffer,
&dwBufferLength
);
if (ProtocolCount != SOCKET_ERROR)
{
break;
}
I_RpcFree(lpProtocolBuffer);
if (GetLastError() != WSAENOBUFS)
{
fRetVal = FALSE;
goto CleanupAndReturn;
}
}
for (i = 1; i < MAX_PROTOCOLS; i++)
{
pCurrentProtocol = GetTransportProtocol(i);
pCurrentProtocol->HandleProtocolChange(lpProtocolBuffer, ProtocolCount, i);
}
I_RpcFree(lpProtocolBuffer);
fRetVal = g_NotifyRt;
CleanupAndReturn:
LeaveCriticalSection(&AddressListLock);
#ifdef MAJOR_PNP_DEBUG
DumpProtocolState();
#endif
return fRetVal;
}
BOOL TransportProtocol::ResubmitQueriesIfNecessary(void)
/*++
Function Name: ResubmitQueriesIfNecessary
Parameters:
Description:
Iterates through all protocols and calls their ResubmitQueriesIfNecessary
Returns:
FALSE if at least one protocol needed to resubmit a query, but failed to do so
TRUE otherwise
--*/
{
int i;
BOOL fAllResubmitsSucceeded = TRUE;
TransportProtocol *pCurrentProtocol;
#ifdef MAJOR_PNP_DEBUG
DbgPrint("Resubmitting queries for process %d\n", GetCurrentProcessId());
#endif
EnterCriticalSection(&AddressListLock);
for (i = 1; i < MAX_PROTOCOLS; i++)
{
pCurrentProtocol = GetTransportProtocol(i);
if (!pCurrentProtocol->ResubmitQueriesIfNecessary(i))
fAllResubmitsSucceeded = FALSE;
}
LeaveCriticalSection(&AddressListLock);
return fAllResubmitsSucceeded;
}
void TransportProtocol::AddObjectToProtocolList(BASE_ASYNC_OBJECT *pObj)
{
GetTransportProtocol(pObj->id)->AddObjectToList(pObj);
}
#if defined(DBG) || defined(_DEBUG)
void TransportProtocol::AssertProtocolListIntegrity(IN BASE_ASYNC_OBJECT *pObj)
{
GetTransportProtocol(pObj->id)->AssertListIntegrity(pObj->id);
}
#endif // DBG || _DEBUG
void TransportProtocol::RemoveObjectFromProtocolList(IN OUT BASE_ASYNC_OBJECT *pObj)
{
// in some cases, we can legally have the id set to INVALID_PROTOCOL_ID
// this happens when we have initialized the connection, but have failed
// before calling Open on it, and then we attempt to destroy it
if (pObj->id != INVALID_PROTOCOL_ID)
{
GetTransportProtocol(pObj->id)->RemoveObjectFromList(pObj);
}
}
BOOL TransportProtocol::VerifyProtocolIsFunctional(IN PROTOCOL_ID ProtocolId)
/*++
Function Name: VerifyProtocolIsFunctional
Parameters: ProtocolId - the protocol which we're attempting to verify as functional or not
Description: Tries to find out the listening address for a loaded protocol. The address
itself is not used anywhere. It just testifies that the protocol is fully operational.
Depending on how far it gets with testing whether the protocol is operational,
it will change the State to ProtocolLoaded, ProtocolLoadedWithoutAddress or
ProtocolWasLoadedOrNeedsActivationWithoutAddress. It will return TRUE iff the state is moved to
ProtocolLoaded.
Returns: TRUE if the address was found and the protocol was fully operational
FALSE if the address could not be found, and the protocol is not
fully operational. Note that there are two subcases here. One is when
the protocol is not operational (or we cannot confirm that for lack of
resources for example) and it has no sign of becoming operational. The
second is when the protocol is not operational, but there are chances of
it becoming operational. This happens with protocols that take some
time to initialize. In the second case, this function will arrange for
a retry attempt by posting an async WSAIoctl request to the completion
port. In the current code base, we don't differentiate between the two
cases because we don't need to. We may need to do so in the future.
--*/
{
ASSERT((State == ProtocolNotLoaded)
|| (State == ProtocolWasLoadedOrNeedsActivation)
|| (State == ProtocolLoadedWithoutAddress)
|| (State == ProtocolWasLoadedOrNeedsActivationWithoutAddress));
ASSERT_TRANSPORT_PROTOCOL_STATE(ProtocolId);
if (OpenAddressChangeRequestSocket(ProtocolId) == FALSE)
goto AbortAndCleanup;
// if the socket already has an address, skip further checks
// NOTE: this check provides a fast way to check initialization state of
// protocols that initialize quickly, but more importantly, it provides a
// handling path for protocols that have submitted an address list change query
// and now are getting back the result
if (DoesAddressSocketHaveAddress())
{
#ifdef MAJOR_PNP_DEBUG
DbgPrint("Protocol %d is functional (1)\n", ProtocolId);
#endif
CancelAddressChangeRequestIfNecessary(FALSE, ProtocolId);
SetStateToLoadedAndMonitorProtocolIfNecessary(ProtocolId);
ASSERT_TRANSPORT_PROTOCOL_STATE(ProtocolId);
return TRUE;
}
// if there isn't a pending request, and there isn't a successful request (i.e. there is either
// a failed request, or no request has been submitted so far)
if ((addressChangeOverlapped.Internal != 0) && (addressChangeOverlapped.Internal != STATUS_PENDING))
{
#ifdef MAJOR_PNP_DEBUG
DbgPrint("Submitting WSAIoclt for protocol %d\n", ProtocolId);
#endif
if (!SubmitAddressChangeQuery())
goto AbortAndCleanup;
}
// check once more whether we have address - this takes care of the race where the
// address did arrive between the time we checked for it in the beginning of this
// function and the time we submitted the address change query
if (DoesAddressSocketHaveAddress())
{
#ifdef MAJOR_PNP_DEBUG
DbgPrint("Protocol %d is functional (2)\n", ProtocolId);
#endif
CancelAddressChangeRequestIfNecessary(FALSE, ProtocolId);
SetStateToLoadedAndMonitorProtocolIfNecessary(ProtocolId);
ASSERT_TRANSPORT_PROTOCOL_STATE(ProtocolId);
return TRUE;
}
// regardless of whether we succeeded immediately or we are pending, advance the
// state to ProtocolLoadedWithoutAddress and return not loaded. The completion at the
// completion port will take care of the rest
if (State == ProtocolWasLoadedOrNeedsActivation)
SetState(ProtocolWasLoadedOrNeedsActivationWithoutAddress, ProtocolId);
else if (State == ProtocolNotLoaded)
SetState(ProtocolLoadedWithoutAddress, ProtocolId);
#ifdef MAJOR_PNP_DEBUG
else
{
DbgPrint("VerifyProtocolIsFunctional did not change state for protocol %d, state: %s\n", ProtocolId,
ProtocolStateNames[State]);
}
#endif
ASSERT_TRANSPORT_PROTOCOL_STATE(ProtocolId);
return FALSE;
AbortAndCleanup:
// TRUE or FALSE for this argument doesn't matter here -
// the operation has failed
CancelAddressChangeRequestIfNecessary(FALSE, ProtocolId);
ASSERT_TRANSPORT_PROTOCOL_STATE(ProtocolId);
return FALSE;
}
BOOL TransportProtocol::DoesAddressSocketHaveAddress(void)
/*++
Function Name: DoesAddressSocketHaveAddress
Parameters:
Description:
Checks if a valid address can be obtained for this protocol.
Returns:
TRUE - a valid address could be obtained for this protocol
FALSE - otherwise
--*/
{
DWORD byteRet = 0;
char buf[40];
ASSERT(addressChangeSocket != 0);
if (WSAIoctl(addressChangeSocket, SIO_ADDRESS_LIST_QUERY,
0, 0, buf, sizeof(buf), &byteRet, NULL, NULL) == SOCKET_ERROR)
{
return FALSE;
}
// if the result has non-zero length ...
if (byteRet != 0)
{
#if 0
int i;
DbgPrint("WSAIoctl returned:\n");
for (i = 0; i < byteRet; i ++)
{
DbgPrint(" %X", (unsigned long) buf[i]);
}
DbgPrint("\nWSAIoctl with ADDRESS_LIST_QUERY returned addresses success\n");
#endif
// ... and the resulting value is non zero ...
if (*(long *)buf != 0)
{
// ... we have managed to get the true address
return TRUE;
}
}
return FALSE;
}
void TransportProtocol::CancelAddressChangeRequestIfNecessary(BOOL fForceCancel, IN PROTOCOL_ID ProtocolId)
/*++
Function Name: CancelAddressChangeRequestIfNecessary
Parameters:
Description:
If there's an active WSAIoctl on the protocol, cancel it by closing the socket.
Returns:
--*/
{
if (addressChangeSocket != 0)
{
// if the address change monitoring is off, or cancel is
// forced, do the actual cancelling. That is, we don't
// cancel if this is a monitored protocol and cancel is
// optional
if (!IsAddressChangeMonitoringOn(ProtocolId) || fForceCancel)
{
#ifdef MAJOR_PNP_DEBUG
DbgPrint("Address change request cancelled\n");
#endif
closesocket(addressChangeSocket);
addressChangeSocket = 0;
addressChangeOverlapped.Internal = -1;
}
}
}
void TransportProtocol::RestartProtocol(PROTOCOL_ID ProtocolId)
/*++
Function Name: RestartProtocol
Parameters:
ProtocolId - the protocol to be restarted.
Description:
Restarts all addresses on this protocol.
Returns:
--*/
{
BASE_ASYNC_OBJECT *Obj;
BOOL fAddressFound = 0;
RPC_STATUS Status;
LIST_ENTRY *CurrentEntry;
VALIDATE(ProtocolId)
{
TCP,
#ifdef SPX_ON
SPX,
#endif
#ifdef APPLETALK_ON
DSP,
#endif
HTTP,
UDP,
#ifdef IPX_ON
IPX,
#endif
TCP_IPv6
} END_VALIDATE;
CurrentEntry = ObjectList.Flink;
while(CurrentEntry != &ObjectList)
{
Obj = CONTAINING_RECORD(CurrentEntry, BASE_ASYNC_OBJECT, ObjectList);
ASSERT(Obj->id == (int) ProtocolId);
if (Obj->type & ADDRESS)
{
if (Obj->type & DATAGRAM)
{
Status = DG_ReactivateAddress((WS_DATAGRAM_ENDPOINT *) Obj);
}
else
{
Status = WS_ReactivateAddress((WS_ADDRESS *) Obj);
}
if (Status == RPC_S_OK)
{
fAddressFound = 1;
COMMON_AddressManager((BASE_ADDRESS *) Obj);
}
}
CurrentEntry = CurrentEntry->Flink;
}
if (fAddressFound)
{
COMMON_PostNonIoEvent(TRANSPORT, 0, NULL);
}
}
void TransportProtocol::InitNewAddresses(PROTOCOL_ID ProtocolId)
/*++
Function Name: RestartProtocol
Parameters:
ProtocolId - the protocol for which the addresses are to be
initialized.
Description:
Initializes transport address objects that listen on
interfaces that were assigned addresses. Works for TCP only.
Returns:
--*/
{
BASE_ASYNC_OBJECT *Obj;
WS_ADDRESS *WsAddr;
BASE_ADDRESS *pSavedFirstAddress, *pSavedNextAddress;
BOOL fAddressFound = FALSE;
RPC_STATUS Status;
LIST_ENTRY *CurrentEntry;
ASSERT(ProtocolId == TCP);
// For each new address in the firewall table, find tranport address
// objects that have not been initialized and make them listen on
// the net address. Make sure that a given transport address list
// listens on all the available network addresses.
// Go through the firewall table
for (DWORD j = 0; j < pFirewallTable->NumAddresses; j++)
{
// Pick a newly-initialized and enabled address from the table.
if (pFirewallTable->Entries[j].fNewAddress == FALSE
|| pFirewallTable->Entries[j].fEnabled == FALSE)
{
continue;
}
// Go through the list of transport addresses.
CurrentEntry = ObjectList.Flink;
while(CurrentEntry != &ObjectList)
{
Obj = CONTAINING_RECORD(CurrentEntry, BASE_ASYNC_OBJECT, ObjectList);
ASSERT(Obj->id == (int) ProtocolId);
WsAddr = (WS_ADDRESS *)Obj;
#ifdef MAJOR_TRANS_DEBUG
DbgPrint("RPC: TransportProtocol::InitNewAddresses: Processing address 0x%x.\n", WsAddr);
#endif
// Initialize the object if it is a TCP address that has not yet been initialized
// and if the address list that it is a part of is not listening on all of the available
// network addresses yet.
if (Obj->type & ADDRESS
&& Obj->id == TCP
&& WsAddr->fAddressInitialized == FALSE
&& FirewallTableNumActiveEntries > ((WS_ADDRESS *)WsAddr->pFirstAddress)->NumActiveAddresses)
{
// Initialize the address from the firewall table entry.
//
// Note that we do not have to syncronize with the other users of
// pFirewallTable since the only possible update would come from a PnP
// notification and this function will be executing during a notification
// after the table update. UseProtseq* path does not modify an initialized table
// and can't race with this path.
#ifdef MAJOR_TRANS_DEBUG
DbgPrint("RPC: TransportProtocol::InitNewAddresses: Initializing address 0x%x from pFirewalTable entry with index 0x%x.\n", WsAddr, j);
#endif
WsAddr->ListenAddr.inetaddr.sin_addr.s_addr = pFirewallTable->Entries[j].Address;
// Pass in fResetAddressListEntries = FALSE since the address is already in the list
// and the fields have been initialized.
Status = WS_ReactivateAddress(WsAddr, FALSE);
#ifdef MAJOR_TRANS_DEBUG
DbgPrint("RPC: TransportProtocol::InitNewAddresses: WS_ReactivateAddress for address 0x%x returned 0x%x.\n", WsAddr, Status);
#endif
if (Status == RPC_S_OK)
{
WsAddr->fAddressInitialized = TRUE;
fAddressFound = TRUE;
((WS_ADDRESS *)WsAddr->pFirstAddress)->NumActiveAddresses++;
COMMON_AddressManager((BASE_ADDRESS *) Obj);
}
// Re-build the address vector.
Status = IP_BuildAddressVector(
&(WsAddr->pFirstAddress->pAddressVector),
0, //OsfAddress->NICFlags,
NULL, // Not listening on a specific address.
(WS_ADDRESS *)WsAddr->pFirstAddress);
// If we were not able to find an entry in the pFirewallTable to initialize this address,
// there is nothing to do - wait for another address change event when the
// NIC may finish initializing.
//
// Note that if an interface gets disabled, it may disapper from the pFirewallTable during
// an update. In this case, we will remain with un-initialized transport address objects,
// but there is nothing that we can do about this since the interface on which they should have
// listened is not up.
}
CurrentEntry = CurrentEntry->Flink;
}
}
if (fAddressFound)
{
COMMON_PostNonIoEvent(TRANSPORT, 0, NULL);
}
}
void TransportProtocol::UnloadProtocol(PROTOCOL_ID ProtocolId)
/*++
Function Name: UnloadProtocol
Parameters:
ProtocolId - the protocol to be unloaded.
Description:
Walks the list of the protocol transport objects. Closes the connections, and removes the
addresses from the list. Thus failing requests on addresses will not be retried.
Returns:
--*/
{
BASE_ASYNC_OBJECT *Obj;
LIST_ENTRY *CurrentEntry;
VALIDATE(ProtocolId)
{
TCP,
#ifdef SPX_ON
SPX,
#endif
#ifdef APPLETALK_ON
DSP,
#endif
HTTP,
UDP,
#ifdef IPX_ON
IPX,
#endif
TCP_IPv6,
HTTPv2
} END_VALIDATE;
CurrentEntry = ObjectList.Flink;
//
// - Cleanup all the objects (ie: close the socket).
// - Remove all objects other than address objects
// from the list.
//
while(CurrentEntry != &ObjectList)
{
Obj = CONTAINING_RECORD(CurrentEntry, BASE_ASYNC_OBJECT, ObjectList);
ASSERT(Obj->id == (int)ProtocolId);
if (Obj->type & ADDRESS)
{
COMMON_RemoveAddress((BASE_ADDRESS *) Obj);
}
else
{
RpcpfRemoveEntryList(&Obj->ObjectList);
if (ProtocolId != HTTPv2)
WS_Abort(Obj);
else
HTTP_Abort(Obj);
}
CurrentEntry = CurrentEntry->Flink;
}
}
BOOL TransportProtocol::SubmitAddressChangeQuery(void)
/*++
Function Name: SubmitAddressChangeQuery
Parameters:
Description:
Submits an address change query (WSAIoctl)
Returns:
TRUE if the WSAIoctl was successfully posted.
FALSE otherwise
--*/
{
ASSERT(addressChangeSocket != 0);
static DWORD dwBytesReturned;
//
// Post an address list change request
//
addressChangeOverlapped.hEvent = 0;
addressChangeOverlapped.Offset = 0;
addressChangeOverlapped.OffsetHigh = 0;
addressChangeOverlapped.Internal = 0;
// submit the address change request - it will always complete on the completion port
// we don't care about the dwBytesReturned. The provider requires a valid address, or
// it rejects the request
if (WSAIoctl(addressChangeSocket, SIO_ADDRESS_LIST_CHANGE,
0, 0, 0, 0, &dwBytesReturned, &addressChangeOverlapped, 0) == SOCKET_ERROR)
{
if (WSAGetLastError() != ERROR_IO_PENDING)
{
#ifdef MAJOR_PNP_DEBUG
DbgPrint("Submitting WSAIoclt failed with: %d\n", GetLastError());
#endif
return FALSE;
}
}
return TRUE;
}
void TransportProtocol::SetState(TransportProtocolStates newState, PROTOCOL_ID ProtocolId)
/*++
Function Name: SetState
Parameters:
newState - the new state that the protocol needs to move to
ProtocolId - the protocol number of this protocol
Description:
Sets the state of the protocol. Nobody should write the state directly, because
protocol state mirroring will stop working.
Returns:
--*/
{
TransportProtocol *CurrentProtocol;
#ifdef MAJOR_PNP_DEBUG
DbgPrint("Protocol %d moved from state: %s to state: %s\n", ProtocolId, ProtocolStateNames[State],
ProtocolStateNames[newState]);
#endif
// either the address change monitoring is not on for this protocol, or
// the protocol doesn't move to loaded state, but not both
ASSERT(!IsAddressChangeMonitoringOn(ProtocolId) || (newState != ProtocolLoaded));
State = newState;
if (ProtocolId == TCP)
{
// if a base protocols is moved into loaded and monitored, make sure
// the trailing protocols doesn't follow it there. In such a case
// the trailing protocol becomes only loaded
if (newState == ProtocolLoadedAndMonitored)
{
GetTransportProtocol(HTTP)->State = ProtocolLoaded;
}
else
{
GetTransportProtocol(HTTP)->State = newState;
}
MirrorProtocolState(TCP_IPv6);
}
else if (ProtocolId == TCP_IPv6)
{
MirrorProtocolState(TCP);
}
}
void TransportProtocol::SetStateToLoadedAndMonitorProtocolIfNecessary(PROTOCOL_ID ProtocolId)
{
if (IsAddressChangeMonitoringOn(ProtocolId))
{
// monitor functional protocols for address change will
// set the state
MonitorFunctionalProtocolForAddressChange(ProtocolId);
}
else
SetState(ProtocolLoaded, ProtocolId);
}
RPC_STATUS InitTransportProtocols(void)
/*++
Function Name: InitTransportProtocols
Parameters:
Description:
Initializes all transport level protocols. This function should be called before
any of the TransportProtocol functions.
Returns:
--*/
{
TransportProtocolArray = new TransportProtocol[MAX_PROTOCOLS];
if (TransportProtocolArray == NULL)
return (RPC_S_OUT_OF_MEMORY);
else
return RPC_S_OK;
}
#if defined(DBG) || defined(_DEBUG)
void TransportProtocol::AssertTransportProtocolState(void)
/*++
Function Name: AssertTransportProtocolState
Parameters:
Description:
Loops through all protocols and calls AssertState on them
Returns:
--*/
{
int i;
for (i = 1; i < MAX_PROTOCOLS; i ++)
{
GetTransportProtocol(i)->AssertState(i);
}
}
void TransportProtocol::AssertState(PROTOCOL_ID ProtocolId)
/*++
Function Name: AssertState
Parameters:
ProtocolId - the protocol number of the this protocol
Description:
Currently this includes that addressChangeSocket is set only in the *WithoutAddress states
and that all the objects in this protocol list are of the same protocol as this protocol.
Returns:
--*/
{
// make sure that the internal state of the object is consistent
ASSERT (State >= ProtocolNotLoaded);
ASSERT (State <= ProtocolLoadedAndMonitored);
if (IsTrailingProtocol(ProtocolId))
{
ASSERT(addressChangeSocket == 0);
}
else
{
// if we are in one of these states, there should be no address change request pending
if ((State == ProtocolNotLoaded)
|| (State == ProtocolWasLoadedOrNeedsActivation)
|| (State == ProtocolLoaded))
{
ASSERT(addressChangeSocket == 0);
}
else
{
// if we are in one of the else states, there must be address change request pending
ASSERT(addressChangeSocket != 0);
}
}
AssertListIntegrity(ProtocolId);
}
void
TransportProtocol::AssertListIntegrity (
IN PROTOCOL_ID ProtocolId
)
/*++
Routine Description:
Verifies the integrity of the protocol list by walking
through every entry and making sure it has the same (and
expected) protocol id.
Arguments:
ProtocolId - the protocol id of the current protocol
Return Value:
--*/
{
BASE_ASYNC_OBJECT *pObject;
LIST_ENTRY *CurrentEntry;
EnterCriticalSection(&AddressListLock);
// walk the object list and make sure every object is of the same protocol
CurrentEntry = ObjectList.Flink;
while (CurrentEntry != &ObjectList)
{
pObject = CONTAINING_RECORD(CurrentEntry, BASE_ASYNC_OBJECT, ObjectList);
ASSERT(pObject->id == ProtocolId);
CurrentEntry = CurrentEntry->Flink;
}
LeaveCriticalSection(&AddressListLock);
}
#endif
BOOL TransportProtocol::MonitorFunctionalProtocolForAddressChange(PROTOCOL_ID ProtocolId)
/*++
Function Name: MonitorFunctionalProtocolForAddressChange
Parameters:
ProtocolId - the protocol id of the current protocol
Description:
Makes sure that an already functional protocol is monitored for address change. This is done
by:
- if an address change socket does not exist, one is opened.
- if no address change WSAIoctl is pending on the socket, one is posted.
Returns:
TRUE if the posting of address change was successful
FALSE if it wasn't
--*/
{
BOOL bRetVal = FALSE;
// OpenAddressChangeRequestSocket will take care to check whether there's already
// a socket opened
if (OpenAddressChangeRequestSocket(ProtocolId) == FALSE)
goto Cleanup;
if (addressChangeOverlapped.Internal != STATUS_PENDING)
{
if (SubmitAddressChangeQuery() == FALSE)
goto Cleanup;
}
bRetVal = TRUE;
Cleanup:
if (State != ProtocolLoadedAndMonitored)
SetState(ProtocolLoadedAndMonitored, ProtocolId);
return bRetVal;
}
BOOL TransportProtocol::OpenAddressChangeRequestSocket(PROTOCOL_ID ProtocolId)
/*++
Function Name: OpenAddressChangeRequestSocket
Parameters:
ProtocolId - the protocol id of the current protocol
Description:
Makes sure that an address change request socket is opened.
Returns:
TRUE if the opening was successful
FALSE if it wasn't
--*/
{
const WS_TRANS_INFO *pInfo = &WsTransportTable[ProtocolId];
HANDLE h;
// we may end up with non-zero addressChangeSocket if this is an address change query
// request coming back to us. In this case we don't need to open up another socket
if (addressChangeSocket == 0)
{
ASSERT((State == ProtocolNotLoaded)
|| (State == ProtocolWasLoadedOrNeedsActivation)
|| (State == ProtocolLoaded));
//
// Create a socket
//
addressChangeSocket = WSASocketT(pInfo->AddressFamily,
pInfo->SocketType,
pInfo->Protocol,
0,
0,
WSA_FLAG_OVERLAPPED);
if (addressChangeSocket == INVALID_SOCKET)
{
//
// We should be able to at least open a socket on the protocol,
// if not we got a bogus notification or we're out of resources
addressChangeSocket = 0;
return FALSE;
}
//
// make the handle non-inheritable so it goes away when we close it.
//
if (FALSE == SetHandleInformation( (HANDLE) addressChangeSocket, HANDLE_FLAG_INHERIT, 0))
{
closesocket(addressChangeSocket);
addressChangeSocket = 0;
return FALSE;
}
// associate the socket with the completion port so that we get the notification there
h = CreateIoCompletionPort((HANDLE)addressChangeSocket,
RpcCompletionPort,
NewAddress,
0);
if (h == 0)
{
closesocket(addressChangeSocket);
addressChangeSocket = 0;
return FALSE;
}
else if (RpcCompletionPort != h)
{
ASSERT(RpcCompletionPort == h);
CloseHandle(h);
closesocket(addressChangeSocket);
addressChangeSocket = 0;
return FALSE;
}
}
else
{
// we may have a protocol in state ProtocolNotLoaded, because we are just trying
// to bring it to loaded state
ASSERT((State == ProtocolLoadedWithoutAddress)
|| (State == ProtocolWasLoadedOrNeedsActivationWithoutAddress)
|| (State == ProtocolLoadedAndMonitored) || (State == ProtocolNotLoaded));
}
#ifdef MAJOR_PNP_DEBUG
DbgPrint("Socket was successfully opened for protocol %d\n", ProtocolId);
#endif
return TRUE;
}
void
TransportProtocol::MirrorProtocolState (
IN PROTOCOL_ID MirrorProtocolId
)
/*++
Function Name: MirrorProtocolState
Parameters:
MirrorProtocolId - the protocol which is mirrored
Description:
If this is one of the protocols in a dual stack configuration, change
the other protocol into appropriate state
Returns:
--*/
{
TransportProtocol *MirrorProtocol;
MirrorProtocol = GetTransportProtocol(MirrorProtocolId);
if ((State == ProtocolLoadedAndMonitored) || (State == ProtocolLoaded))
{
if (MirrorProtocol->State == ProtocolNotLoaded)
{
MirrorProtocol->SetState(ProtocolWasLoadedOrNeedsActivation, MirrorProtocolId);
}
else if (MirrorProtocol->State == ProtocolLoadedWithoutAddress)
{
MirrorProtocol->SetState(ProtocolWasLoadedOrNeedsActivationWithoutAddress, MirrorProtocolId);
}
}
}
#ifdef MAJOR_PNP_DEBUG
void TransportProtocol::DumpProtocolState(void)
/*++
Function Name: DumpProtocolState
Parameters:
Description:
Iterates through all protocol and calls their DumpProtocolState
Returns:
--*/
{
int i;
DbgPrint("Dumping protocol state for process %d\n", GetCurrentProcessId());
for (i = 1; i < MAX_PROTOCOLS; i ++)
{
GetTransportProtocol(i)->DumpProtocolState(i);
}
}
const char *ProtocolStateNames[] = {"ProtocolNotLoaded", "ProtocolLoadedWithoutAddress" ,
"ProtocolWasLoadedOrNeedsActivation", "ProtocolLoaded",
"ProtocolWasLoadedOrNeedsActivationWithoutAddress",
"ProtocolLoadedAndMonitored"};
void TransportProtocol::DumpProtocolState(PROTOCOL_ID ProtocolId)
/*++
Function Name: DumpProtocolState
Parameters:
ProtocolId - the protocol number for this protocol.
Description:
Dumps all significant information for this protcool on the debugger
Returns:
--*/
{
BASE_ASYNC_OBJECT *pCurrentObject;
LIST_ENTRY *pCurrentEntry = ObjectList.Flink;
int fFirstTime = TRUE;
const RPC_CHAR *Protseq;
if (TransportTable[ProtocolId].pInfo)
Protseq = TransportTable[ProtocolId].pInfo->ProtocolSequence;
else
Protseq = L"(null)";
DbgPrint("Protocol: %S\n", Protseq);
DbgPrint("State: %s, Addr Change Socket: %X, Addr Change Overlapped: %X\n",
ProtocolStateNames[State], addressChangeSocket, (ULONG_PTR)&addressChangeOverlapped);
while (pCurrentEntry != &ObjectList)
{
if (fFirstTime)
{
DbgPrint("Object List:\n");
fFirstTime = FALSE;
}
pCurrentObject = CONTAINING_RECORD(pCurrentEntry, BASE_ASYNC_OBJECT, ObjectList);
DbgPrint("\t%X\n", (ULONG_PTR)pCurrentObject);
pCurrentEntry = pCurrentEntry->Flink;
}
}
#endif
TransportProtocol *TransportProtocolArray;
| 34.055662 | 152 | 0.586654 | [
"object",
"vector"
] |
f0121838c7705d2f4338b23eebb4ea0219319fca | 5,734 | cpp | C++ | Examples/Cpp/source/IMAP/ReadMessagesRecursively.cpp | kashifiqb/Aspose.Email-for-C | 96684cb6ed9f4e321a00c74ca219440baaef8ba8 | [
"MIT"
] | 4 | 2019-12-01T16:19:12.000Z | 2022-03-28T18:51:42.000Z | Examples/Cpp/source/IMAP/ReadMessagesRecursively.cpp | kashifiqb/Aspose.Email-for-C | 96684cb6ed9f4e321a00c74ca219440baaef8ba8 | [
"MIT"
] | 1 | 2022-02-15T01:02:15.000Z | 2022-02-15T01:02:15.000Z | Examples/Cpp/source/IMAP/ReadMessagesRecursively.cpp | kashifiqb/Aspose.Email-for-C | 96684cb6ed9f4e321a00c74ca219440baaef8ba8 | [
"MIT"
] | 5 | 2017-09-27T14:43:20.000Z | 2021-11-16T06:47:11.000Z | #include <system/string.h>
#include <system/shared_ptr.h>
#include <system/object_ext.h>
#include <system/object.h>
#include <system/io/directory.h>
#include <system/exceptions.h>
#include <system/environment.h>
#include <system/console.h>
#include <system/collections/ienumerator.h>
#include <SaveOptions.h>
#include <MsgSaveOptions.h>
#include <MailMessage.h>
#include <cstdint>
#include <Clients/SecurityOptions.h>
#include <Clients/Imap/ImapMessageInfoCollection.h>
#include <Clients/Imap/ImapMessageInfo.h>
#include <Clients/Imap/ImapFolderInfoCollection.h>
#include <Clients/Imap/ImapFolderInfo.h>
#include <Clients/Imap/ImapClient/ImapClient.h>
#include "Examples.h"
using namespace Aspose::Email::Clients::Imap;
using namespace Aspose::Email::Clients;
using namespace Aspose::Email;
void ListMessagesInFolder(System::SharedPtr<Aspose::Email::Clients::Imap::ImapFolderInfo> folderInfo, System::String rootFolder, System::SharedPtr<Aspose::Email::Clients::Imap::ImapClient> client)
{
// Create the folder in disk (same name as on IMAP server)
System::String currentFolder = GetDataDir_IMAP();
System::IO::Directory::CreateDirectory_(currentFolder);
// Read the messages from the current folder, if it is selectable
if (folderInfo->get_Selectable())
{
// Send status command to get folder info
System::SharedPtr<ImapFolderInfo> folderInfoStatus = client->GetFolderInfo(folderInfo->get_Name());
System::Console::WriteLine(folderInfoStatus->get_Name() + u" folder selected. New messages: " + folderInfoStatus->get_NewMessageCount() + u", Total messages: " + folderInfoStatus->get_TotalMessageCount());
// Select the current folder and List messages
client->SelectFolder(folderInfo->get_Name());
System::SharedPtr<ImapMessageInfoCollection> msgInfoColl = client->ListMessages();
System::Console::WriteLine(u"Listing messages....");
{
auto msgInfo_enumerator = (msgInfoColl)->GetEnumerator();
decltype(msgInfo_enumerator->get_Current()) msgInfo;
while (msgInfo_enumerator->MoveNext() && (msgInfo = msgInfo_enumerator->get_Current(), true))
{
// Get subject and other properties of the message
System::Console::WriteLine(System::String(u"Subject: ") + msgInfo->get_Subject());
System::Console::WriteLine(System::String(u"Read: ") + msgInfo->get_IsRead() + u", Recent: " + msgInfo->get_Recent() + u", Answered: " + msgInfo->get_Answered());
// Get rid of characters like ? and :, which should not be included in a file name and Save the message in MSG format
System::String fileName = msgInfo->get_Subject().Replace(u":", u" ").Replace(u"?", u" ");
System::SharedPtr<MailMessage> msg = client->FetchMessage(msgInfo->get_SequenceNumber());
msg->Save(currentFolder + u"\\" + fileName + u"-" + msgInfo->get_SequenceNumber() + u".msg", SaveOptions::get_DefaultMsgUnicode());
}
}
System::Console::WriteLine(u"============================\n");
}
else
{
System::Console::WriteLine(folderInfo->get_Name() + u" is not selectable.");
}
try
{
// If this folder has sub-folders, call this method recursively to get messages
System::SharedPtr<ImapFolderInfoCollection> folderInfoCollection = client->ListFolders(folderInfo->get_Name());
{
auto subfolderInfo_enumerator = (folderInfoCollection)->GetEnumerator();
decltype(subfolderInfo_enumerator->get_Current()) subfolderInfo;
while (subfolderInfo_enumerator->MoveNext() && (subfolderInfo = subfolderInfo_enumerator->get_Current(), true))
{
ListMessagesInFolder(subfolderInfo, rootFolder, client);
}
}
}
catch (System::Exception& ) { }
}
void ReadMessagesRecursively()
{
// Create an instance of the ImapClient class
System::SharedPtr<ImapClient> client = System::MakeObject<ImapClient>();
// Specify host, username, password, Port and SecurityOptions for your client
client->set_Host(u"imap.gmail.com");
client->set_Username(u"your.username@gmail.com");
client->set_Password(u"your.password");
client->set_Port(993);
client->set_SecurityOptions(Aspose::Email::Clients::SecurityOptions::Auto);
try
{
// The root folder (which will be created on disk) consists of host and username
System::String rootFolder = client->get_Host() + u"-" + client->get_Username();
// Create the root folder and List all the folders from IMAP server
System::IO::Directory::CreateDirectory_(rootFolder);
System::SharedPtr<ImapFolderInfoCollection> folderInfoCollection = client->ListFolders();
{
auto folderInfo_enumerator = (folderInfoCollection)->GetEnumerator();
decltype(folderInfo_enumerator->get_Current()) folderInfo;
while (folderInfo_enumerator->MoveNext() && (folderInfo = folderInfo_enumerator->get_Current(), true))
{
// Call the recursive method to read messages and get sub-folders
ListMessagesInFolder(folderInfo, rootFolder, client);
}
}
// Disconnect to the remote IMAP server
client->Dispose();
}
catch (System::Exception& ex)
{
System::Console::Write(System::Environment::get_NewLine() + System::ObjectExt::ToString(ex));
}
System::Console::WriteLine(System::Environment::get_NewLine() + u"Downloaded messages recursively from IMAP server.");
}
| 44.796875 | 213 | 0.663586 | [
"object"
] |
f013a4f89160952f4f38419c350c2b879582a971 | 3,928 | cpp | C++ | codes/misc/accelerator.cpp | chessbot108/solved-problems | 0945be829a8ea9f0d5896c89331460d70d076691 | [
"MIT"
] | null | null | null | codes/misc/accelerator.cpp | chessbot108/solved-problems | 0945be829a8ea9f0d5896c89331460d70d076691 | [
"MIT"
] | null | null | null | codes/misc/accelerator.cpp | chessbot108/solved-problems | 0945be829a8ea9f0d5896c89331460d70d076691 | [
"MIT"
] | null | null | null |
//misaka will carry me to master
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <utility>
#include <cassert>
#include <algorithm>
#include <vector>
#include <functional>
#include <numeric>
#include <set>
#include <map>
#define ll long long
#define lb long double
#define sz(vec) ((int)(vec.size()))
#define all(x) x.begin(), x.end()
#define pb push_back
#define mp make_pair
const lb eps = 1e-9;
//const ll mod = 1e9 + 7, ll_max = 1e18;
const ll mod = (1 << (23)) * 119 +1;
const int MX = 2e5 +10, int_max = 0x3f3f3f3f;
using namespace std;
int rev(unsigned int x, int b){ //lots of trust
x = (((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1));
x = (((x & 0xcccccccc) >> 2) | ((x & 0x33333333) << 2));
x = (((x & 0xf0f0f0f0) >> 4) | ((x & 0x0f0f0f0f) << 4));
x = (((x & 0xff00ff00) >> 8) | ((x & 0x00ff00ff) << 8));
//https://aticleworld.com/5-way-to-reverse-bits-of-an-integer/ method 4
return((x >> 16) | (x << 16)) >> (32 - b);
}
#define lp ll
#define hsb(x) (31 - __builtin_clz(x))
const int NN = (1 << 19);
ll binpow(ll a, ll b= mod-2){
ll ans = 1;
for(ll i = 1; i<=b; i <<= 1){
if(i&b) (ans *= a) %= mod;
(a *= a) %= mod;
}
return ans;
}
vector<lp> halfft(const vector<lp>& poly, const vector<lp>& rt, int op = 0){
vector<lp> ans(sz(poly));
if(sz(poly) == 1){
ans[0] = poly[0];
return ans;
}
int p2 = hsb(sz(poly));
for(int i = 0; i<sz(poly); i++){
ans[rev(i, p2)] = poly[i];
}
for(int k = 1, n = 2; k<=p2; k++, n *= 2){
for(int pos = 0; pos < sz(poly); pos += n){
for(int i = 0; i<n/2; i++){
int i1 = i, i2 = i + n/2;
lp r1 = ans[pos + i] + rt[i1 * (1 << (p2 - k))] * ans[pos + n/2 + i];
lp r2 = ans[pos + i] + rt[i2 * (1 << (p2 - k))] * ans[pos + n/2 + i];
ans[pos + i1] = r1%mod;
ans[pos + i2] = r2%mod;
}
}
}
if(op) reverse(1 + all(ans));
return ans;
}
const int magic = 64;
vector<lp> fft(const vector<lp>& a, const vector<lp>& b){
int s;
for(s = 1; s<(sz(a) +sz(b)); s*=2);
if(s <= magic){
vector<lp> ans(sz(a) + sz(b) -1, 0);
for(int i = 0; i<sz(a); i++){
for(int j = 0; j<sz(b); j++){
ans[i + j] += (a[i] * b[j])%mod;
if(ans[i+j] > mod) ans[i+j] -= mod;
}
}
return ans;
}
vector<lp> A(s, 0), B(s, 0), rt(s);
for(int i = 0; i<sz(a); i++){
A[i] = a[i];
}
for(int i = 0; i<sz(b); i++){
B[i] = b[i];
}
rt[0] = 1;
ll convert = binpow(3, (mod - 1)/s);
for(int i = 1; i<s; i++){
rt[i] = (rt[i - 1] * convert)%mod;
}
vector<lp> aa = halfft(A, rt), bb = halfft(B, rt);
for(int i = 0; i<sz(aa); i++){
aa[i] *= bb[i];
aa[i] %= mod;
}
vector<lp> ans = halfft(aa, rt, 1);
ll tmp = binpow(s);
for(int i = 0; i<s; i++){
//cout << res[i] << " ";
ans[i] *= tmp;
ans[i] %= mod;
}
ans.resize(sz(a) + sz(b) -1);
return ans;
}
vector<lp> poly[MX];
vector<lp> dnq(vector<int> arr){
for(int i = 0; i<sz(arr); i++){
poly[i] = {1, arr[i]};
}
for(int i = 2; i<=sz(arr)*2; i*=2){
for(int j = 0; j<sz(arr); j+=i){
if(j + i/2 < sz(arr)){
poly[j] = fft(poly[j], poly[j+i/2]);
}
}
}
return poly[0];
}
ll fac[MX], ifac[MX];
ll choose(int a, int b){
if(b > a || b < 0) return 0;
ll tmp = ifac[a - b] * ifac[b]%mod;
return (tmp*fac[a])%mod;
}
void precomp(){
const int T = 1e5 +1;
fac[0] = 1;
for(int i = 1; i<=T; i++){
fac[i] = 1ll*i*fac[i-1]%mod;
}
ifac[T] = binpow(fac[T]);
for(int i = T; i >= 1; i--){
ifac[i-1] = 1ll*ifac[i] * i%mod;
}
assert(ifac[0] == 1);
}
void solve(){
int n;
cin >> n;
vector<int> arr(n);
for(int i = 0; i<n; i++){
cin >> arr[i];
}
vector<lp> res = dnq(arr);
assert(sz(res) == n+1);
ll ans = 0;
for(int i = 1; i<sz(res); i++){
res[i] *= (binpow(choose(n, i)))%mod;
res[i] %= mod;
ans += res[i];
}
//ans *= binpow(fac[n]);
ans %= mod;
cout << ans << "\n";
}
int main(){
cin.tie(0) -> sync_with_stdio(0);
precomp();
int T = 1;
cin >> T;
while(T--){
solve();
}
return 0;
}
| 20.565445 | 76 | 0.505855 | [
"vector"
] |
f015e4690a0a82b372fb0136d21dbea5f20fbdaf | 28,912 | cc | C++ | market/src/MarketClient.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | 89 | 2018-02-02T03:54:39.000Z | 2021-12-13T01:32:55.000Z | market/src/MarketClient.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | 89 | 2018-03-14T07:44:54.000Z | 2021-11-26T07:43:25.000Z | market/src/MarketClient.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 69 | 2018-01-22T09:45:52.000Z | 2022-03-28T07:58:38.000Z | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/market/MarketClient.h>
#include <alibabacloud/core/SimpleCredentialsProvider.h>
using namespace AlibabaCloud;
using namespace AlibabaCloud::Location;
using namespace AlibabaCloud::Market;
using namespace AlibabaCloud::Market::Model;
namespace
{
const std::string SERVICE_NAME = "Market";
}
MarketClient::MarketClient(const Credentials &credentials, const ClientConfiguration &configuration) :
RpcServiceClient(SERVICE_NAME, std::make_shared<SimpleCredentialsProvider>(credentials), configuration)
{
auto locationClient = std::make_shared<LocationClient>(credentials, configuration);
endpointProvider_ = std::make_shared<EndpointProvider>(locationClient, configuration.regionId(), SERVICE_NAME, "market");
}
MarketClient::MarketClient(const std::shared_ptr<CredentialsProvider>& credentialsProvider, const ClientConfiguration & configuration) :
RpcServiceClient(SERVICE_NAME, credentialsProvider, configuration)
{
auto locationClient = std::make_shared<LocationClient>(credentialsProvider, configuration);
endpointProvider_ = std::make_shared<EndpointProvider>(locationClient, configuration.regionId(), SERVICE_NAME, "market");
}
MarketClient::MarketClient(const std::string & accessKeyId, const std::string & accessKeySecret, const ClientConfiguration & configuration) :
RpcServiceClient(SERVICE_NAME, std::make_shared<SimpleCredentialsProvider>(accessKeyId, accessKeySecret), configuration)
{
auto locationClient = std::make_shared<LocationClient>(accessKeyId, accessKeySecret, configuration);
endpointProvider_ = std::make_shared<EndpointProvider>(locationClient, configuration.regionId(), SERVICE_NAME, "market");
}
MarketClient::~MarketClient()
{}
MarketClient::ActivateLicenseOutcome MarketClient::activateLicense(const ActivateLicenseRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return ActivateLicenseOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return ActivateLicenseOutcome(ActivateLicenseResult(outcome.result()));
else
return ActivateLicenseOutcome(outcome.error());
}
void MarketClient::activateLicenseAsync(const ActivateLicenseRequest& request, const ActivateLicenseAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, activateLicense(request), context);
};
asyncExecute(new Runnable(fn));
}
MarketClient::ActivateLicenseOutcomeCallable MarketClient::activateLicenseCallable(const ActivateLicenseRequest &request) const
{
auto task = std::make_shared<std::packaged_task<ActivateLicenseOutcome()>>(
[this, request]()
{
return this->activateLicense(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
MarketClient::BindImagePackageOutcome MarketClient::bindImagePackage(const BindImagePackageRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return BindImagePackageOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return BindImagePackageOutcome(BindImagePackageResult(outcome.result()));
else
return BindImagePackageOutcome(outcome.error());
}
void MarketClient::bindImagePackageAsync(const BindImagePackageRequest& request, const BindImagePackageAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, bindImagePackage(request), context);
};
asyncExecute(new Runnable(fn));
}
MarketClient::BindImagePackageOutcomeCallable MarketClient::bindImagePackageCallable(const BindImagePackageRequest &request) const
{
auto task = std::make_shared<std::packaged_task<BindImagePackageOutcome()>>(
[this, request]()
{
return this->bindImagePackage(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
MarketClient::CreateCommodityOutcome MarketClient::createCommodity(const CreateCommodityRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return CreateCommodityOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return CreateCommodityOutcome(CreateCommodityResult(outcome.result()));
else
return CreateCommodityOutcome(outcome.error());
}
void MarketClient::createCommodityAsync(const CreateCommodityRequest& request, const CreateCommodityAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, createCommodity(request), context);
};
asyncExecute(new Runnable(fn));
}
MarketClient::CreateCommodityOutcomeCallable MarketClient::createCommodityCallable(const CreateCommodityRequest &request) const
{
auto task = std::make_shared<std::packaged_task<CreateCommodityOutcome()>>(
[this, request]()
{
return this->createCommodity(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
MarketClient::CreateOrderOutcome MarketClient::createOrder(const CreateOrderRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return CreateOrderOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return CreateOrderOutcome(CreateOrderResult(outcome.result()));
else
return CreateOrderOutcome(outcome.error());
}
void MarketClient::createOrderAsync(const CreateOrderRequest& request, const CreateOrderAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, createOrder(request), context);
};
asyncExecute(new Runnable(fn));
}
MarketClient::CreateOrderOutcomeCallable MarketClient::createOrderCallable(const CreateOrderRequest &request) const
{
auto task = std::make_shared<std::packaged_task<CreateOrderOutcome()>>(
[this, request]()
{
return this->createOrder(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
MarketClient::CreateRateOutcome MarketClient::createRate(const CreateRateRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return CreateRateOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return CreateRateOutcome(CreateRateResult(outcome.result()));
else
return CreateRateOutcome(outcome.error());
}
void MarketClient::createRateAsync(const CreateRateRequest& request, const CreateRateAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, createRate(request), context);
};
asyncExecute(new Runnable(fn));
}
MarketClient::CreateRateOutcomeCallable MarketClient::createRateCallable(const CreateRateRequest &request) const
{
auto task = std::make_shared<std::packaged_task<CreateRateOutcome()>>(
[this, request]()
{
return this->createRate(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
MarketClient::DeleteCommodityOutcome MarketClient::deleteCommodity(const DeleteCommodityRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DeleteCommodityOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DeleteCommodityOutcome(DeleteCommodityResult(outcome.result()));
else
return DeleteCommodityOutcome(outcome.error());
}
void MarketClient::deleteCommodityAsync(const DeleteCommodityRequest& request, const DeleteCommodityAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, deleteCommodity(request), context);
};
asyncExecute(new Runnable(fn));
}
MarketClient::DeleteCommodityOutcomeCallable MarketClient::deleteCommodityCallable(const DeleteCommodityRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DeleteCommodityOutcome()>>(
[this, request]()
{
return this->deleteCommodity(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
MarketClient::DescribeCommoditiesOutcome MarketClient::describeCommodities(const DescribeCommoditiesRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DescribeCommoditiesOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DescribeCommoditiesOutcome(DescribeCommoditiesResult(outcome.result()));
else
return DescribeCommoditiesOutcome(outcome.error());
}
void MarketClient::describeCommoditiesAsync(const DescribeCommoditiesRequest& request, const DescribeCommoditiesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, describeCommodities(request), context);
};
asyncExecute(new Runnable(fn));
}
MarketClient::DescribeCommoditiesOutcomeCallable MarketClient::describeCommoditiesCallable(const DescribeCommoditiesRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DescribeCommoditiesOutcome()>>(
[this, request]()
{
return this->describeCommodities(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
MarketClient::DescribeCommodityOutcome MarketClient::describeCommodity(const DescribeCommodityRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DescribeCommodityOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DescribeCommodityOutcome(DescribeCommodityResult(outcome.result()));
else
return DescribeCommodityOutcome(outcome.error());
}
void MarketClient::describeCommodityAsync(const DescribeCommodityRequest& request, const DescribeCommodityAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, describeCommodity(request), context);
};
asyncExecute(new Runnable(fn));
}
MarketClient::DescribeCommodityOutcomeCallable MarketClient::describeCommodityCallable(const DescribeCommodityRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DescribeCommodityOutcome()>>(
[this, request]()
{
return this->describeCommodity(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
MarketClient::DescribeInstanceOutcome MarketClient::describeInstance(const DescribeInstanceRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DescribeInstanceOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DescribeInstanceOutcome(DescribeInstanceResult(outcome.result()));
else
return DescribeInstanceOutcome(outcome.error());
}
void MarketClient::describeInstanceAsync(const DescribeInstanceRequest& request, const DescribeInstanceAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, describeInstance(request), context);
};
asyncExecute(new Runnable(fn));
}
MarketClient::DescribeInstanceOutcomeCallable MarketClient::describeInstanceCallable(const DescribeInstanceRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DescribeInstanceOutcome()>>(
[this, request]()
{
return this->describeInstance(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
MarketClient::DescribeInstancesOutcome MarketClient::describeInstances(const DescribeInstancesRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DescribeInstancesOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DescribeInstancesOutcome(DescribeInstancesResult(outcome.result()));
else
return DescribeInstancesOutcome(outcome.error());
}
void MarketClient::describeInstancesAsync(const DescribeInstancesRequest& request, const DescribeInstancesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, describeInstances(request), context);
};
asyncExecute(new Runnable(fn));
}
MarketClient::DescribeInstancesOutcomeCallable MarketClient::describeInstancesCallable(const DescribeInstancesRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DescribeInstancesOutcome()>>(
[this, request]()
{
return this->describeInstances(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
MarketClient::DescribeLicenseOutcome MarketClient::describeLicense(const DescribeLicenseRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DescribeLicenseOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DescribeLicenseOutcome(DescribeLicenseResult(outcome.result()));
else
return DescribeLicenseOutcome(outcome.error());
}
void MarketClient::describeLicenseAsync(const DescribeLicenseRequest& request, const DescribeLicenseAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, describeLicense(request), context);
};
asyncExecute(new Runnable(fn));
}
MarketClient::DescribeLicenseOutcomeCallable MarketClient::describeLicenseCallable(const DescribeLicenseRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DescribeLicenseOutcome()>>(
[this, request]()
{
return this->describeLicense(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
MarketClient::DescribeOrderOutcome MarketClient::describeOrder(const DescribeOrderRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DescribeOrderOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DescribeOrderOutcome(DescribeOrderResult(outcome.result()));
else
return DescribeOrderOutcome(outcome.error());
}
void MarketClient::describeOrderAsync(const DescribeOrderRequest& request, const DescribeOrderAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, describeOrder(request), context);
};
asyncExecute(new Runnable(fn));
}
MarketClient::DescribeOrderOutcomeCallable MarketClient::describeOrderCallable(const DescribeOrderRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DescribeOrderOutcome()>>(
[this, request]()
{
return this->describeOrder(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
MarketClient::DescribePriceOutcome MarketClient::describePrice(const DescribePriceRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DescribePriceOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DescribePriceOutcome(DescribePriceResult(outcome.result()));
else
return DescribePriceOutcome(outcome.error());
}
void MarketClient::describePriceAsync(const DescribePriceRequest& request, const DescribePriceAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, describePrice(request), context);
};
asyncExecute(new Runnable(fn));
}
MarketClient::DescribePriceOutcomeCallable MarketClient::describePriceCallable(const DescribePriceRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DescribePriceOutcome()>>(
[this, request]()
{
return this->describePrice(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
MarketClient::DescribeProductOutcome MarketClient::describeProduct(const DescribeProductRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DescribeProductOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DescribeProductOutcome(DescribeProductResult(outcome.result()));
else
return DescribeProductOutcome(outcome.error());
}
void MarketClient::describeProductAsync(const DescribeProductRequest& request, const DescribeProductAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, describeProduct(request), context);
};
asyncExecute(new Runnable(fn));
}
MarketClient::DescribeProductOutcomeCallable MarketClient::describeProductCallable(const DescribeProductRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DescribeProductOutcome()>>(
[this, request]()
{
return this->describeProduct(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
MarketClient::DescribeProductsOutcome MarketClient::describeProducts(const DescribeProductsRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DescribeProductsOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DescribeProductsOutcome(DescribeProductsResult(outcome.result()));
else
return DescribeProductsOutcome(outcome.error());
}
void MarketClient::describeProductsAsync(const DescribeProductsRequest& request, const DescribeProductsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, describeProducts(request), context);
};
asyncExecute(new Runnable(fn));
}
MarketClient::DescribeProductsOutcomeCallable MarketClient::describeProductsCallable(const DescribeProductsRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DescribeProductsOutcome()>>(
[this, request]()
{
return this->describeProducts(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
MarketClient::DescribeRateOutcome MarketClient::describeRate(const DescribeRateRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DescribeRateOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DescribeRateOutcome(DescribeRateResult(outcome.result()));
else
return DescribeRateOutcome(outcome.error());
}
void MarketClient::describeRateAsync(const DescribeRateRequest& request, const DescribeRateAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, describeRate(request), context);
};
asyncExecute(new Runnable(fn));
}
MarketClient::DescribeRateOutcomeCallable MarketClient::describeRateCallable(const DescribeRateRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DescribeRateOutcome()>>(
[this, request]()
{
return this->describeRate(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
MarketClient::NotifyContractEventOutcome MarketClient::notifyContractEvent(const NotifyContractEventRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return NotifyContractEventOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return NotifyContractEventOutcome(NotifyContractEventResult(outcome.result()));
else
return NotifyContractEventOutcome(outcome.error());
}
void MarketClient::notifyContractEventAsync(const NotifyContractEventRequest& request, const NotifyContractEventAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, notifyContractEvent(request), context);
};
asyncExecute(new Runnable(fn));
}
MarketClient::NotifyContractEventOutcomeCallable MarketClient::notifyContractEventCallable(const NotifyContractEventRequest &request) const
{
auto task = std::make_shared<std::packaged_task<NotifyContractEventOutcome()>>(
[this, request]()
{
return this->notifyContractEvent(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
MarketClient::PushMeteringDataOutcome MarketClient::pushMeteringData(const PushMeteringDataRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return PushMeteringDataOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return PushMeteringDataOutcome(PushMeteringDataResult(outcome.result()));
else
return PushMeteringDataOutcome(outcome.error());
}
void MarketClient::pushMeteringDataAsync(const PushMeteringDataRequest& request, const PushMeteringDataAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, pushMeteringData(request), context);
};
asyncExecute(new Runnable(fn));
}
MarketClient::PushMeteringDataOutcomeCallable MarketClient::pushMeteringDataCallable(const PushMeteringDataRequest &request) const
{
auto task = std::make_shared<std::packaged_task<PushMeteringDataOutcome()>>(
[this, request]()
{
return this->pushMeteringData(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
MarketClient::QueryMarketCategoriesOutcome MarketClient::queryMarketCategories(const QueryMarketCategoriesRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return QueryMarketCategoriesOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return QueryMarketCategoriesOutcome(QueryMarketCategoriesResult(outcome.result()));
else
return QueryMarketCategoriesOutcome(outcome.error());
}
void MarketClient::queryMarketCategoriesAsync(const QueryMarketCategoriesRequest& request, const QueryMarketCategoriesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, queryMarketCategories(request), context);
};
asyncExecute(new Runnable(fn));
}
MarketClient::QueryMarketCategoriesOutcomeCallable MarketClient::queryMarketCategoriesCallable(const QueryMarketCategoriesRequest &request) const
{
auto task = std::make_shared<std::packaged_task<QueryMarketCategoriesOutcome()>>(
[this, request]()
{
return this->queryMarketCategories(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
MarketClient::QueryMarketImagesOutcome MarketClient::queryMarketImages(const QueryMarketImagesRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return QueryMarketImagesOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return QueryMarketImagesOutcome(QueryMarketImagesResult(outcome.result()));
else
return QueryMarketImagesOutcome(outcome.error());
}
void MarketClient::queryMarketImagesAsync(const QueryMarketImagesRequest& request, const QueryMarketImagesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, queryMarketImages(request), context);
};
asyncExecute(new Runnable(fn));
}
MarketClient::QueryMarketImagesOutcomeCallable MarketClient::queryMarketImagesCallable(const QueryMarketImagesRequest &request) const
{
auto task = std::make_shared<std::packaged_task<QueryMarketImagesOutcome()>>(
[this, request]()
{
return this->queryMarketImages(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
MarketClient::UpdateCommodityOutcome MarketClient::updateCommodity(const UpdateCommodityRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return UpdateCommodityOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return UpdateCommodityOutcome(UpdateCommodityResult(outcome.result()));
else
return UpdateCommodityOutcome(outcome.error());
}
void MarketClient::updateCommodityAsync(const UpdateCommodityRequest& request, const UpdateCommodityAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, updateCommodity(request), context);
};
asyncExecute(new Runnable(fn));
}
MarketClient::UpdateCommodityOutcomeCallable MarketClient::updateCommodityCallable(const UpdateCommodityRequest &request) const
{
auto task = std::make_shared<std::packaged_task<UpdateCommodityOutcome()>>(
[this, request]()
{
return this->updateCommodity(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
MarketClient::UploadCommodityFileOutcome MarketClient::uploadCommodityFile(const UploadCommodityFileRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return UploadCommodityFileOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return UploadCommodityFileOutcome(UploadCommodityFileResult(outcome.result()));
else
return UploadCommodityFileOutcome(outcome.error());
}
void MarketClient::uploadCommodityFileAsync(const UploadCommodityFileRequest& request, const UploadCommodityFileAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, uploadCommodityFile(request), context);
};
asyncExecute(new Runnable(fn));
}
MarketClient::UploadCommodityFileOutcomeCallable MarketClient::uploadCommodityFileCallable(const UploadCommodityFileRequest &request) const
{
auto task = std::make_shared<std::packaged_task<UploadCommodityFileOutcome()>>(
[this, request]()
{
return this->uploadCommodityFile(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
| 34.174941 | 204 | 0.778397 | [
"model"
] |
f02698674b5be67de4bfbffb33fef77945a56b0b | 1,769 | cc | C++ | projects/ipdg_stokes/post_processing/solution_to_mesh_data_set.cc | Fytch/lehrfempp | c804b3e350aa893180f1a02ce57a93b3d7686e91 | [
"MIT"
] | 16 | 2018-08-30T19:55:43.000Z | 2022-02-16T16:38:06.000Z | projects/ipdg_stokes/post_processing/solution_to_mesh_data_set.cc | Fytch/lehrfempp | c804b3e350aa893180f1a02ce57a93b3d7686e91 | [
"MIT"
] | 151 | 2018-05-27T13:01:50.000Z | 2021-08-04T14:50:50.000Z | projects/ipdg_stokes/post_processing/solution_to_mesh_data_set.cc | Fytch/lehrfempp | c804b3e350aa893180f1a02ce57a93b3d7686e91 | [
"MIT"
] | 20 | 2018-11-13T13:46:38.000Z | 2022-02-18T17:33:52.000Z |
#include "solution_to_mesh_data_set.h"
#include <lf/uscalfe/lagr_fe.h>
namespace projects::ipdg_stokes::post_processing {
lf::mesh::utils::CodimMeshDataSet<double> extractBasisFunctionCoefficients(
const std::shared_ptr<const lf::mesh::Mesh> &mesh,
const lf::assemble::DofHandler &dofh, const Eigen::VectorXd &solution) {
lf::mesh::utils::CodimMeshDataSet<double> coefficients(mesh, 2);
for (const auto *const node : mesh->Entities(2)) {
coefficients(*node) = solution[dofh.GlobalDofIndices(*node)[0]];
}
return coefficients;
}
lf::mesh::utils::CodimMeshDataSet<Eigen::Vector2d> extractVelocity(
const std::shared_ptr<const lf::mesh::Mesh> &mesh,
const lf::assemble::DofHandler &dofh, const Eigen::VectorXd &solution) {
lf::mesh::utils::CodimMeshDataSet<Eigen::Vector2d> velocity(mesh, 0);
for (const auto *const cell : mesh->Entities(0)) {
const auto *geom = cell->Geometry();
// Construct the basis functions from the curl of the standard hat functions
const lf::uscalfe::FeLagrangeO1Tria<double> hat_func;
const Eigen::MatrixXd ref_grads =
hat_func.GradientsReferenceShapeFunctions(Eigen::VectorXd::Zero(2))
.transpose();
const Eigen::MatrixXd J_inv_trans =
geom->JacobianInverseGramian(Eigen::VectorXd::Zero(2));
const Eigen::MatrixXd grads = J_inv_trans * ref_grads;
Eigen::MatrixXd basis_funct(2, 3);
basis_funct << grads.row(1), -grads.row(0);
const auto idx = dofh.GlobalDofIndices(*cell);
velocity(*cell) = solution[idx[0]] * basis_funct.col(0) +
solution[idx[1]] * basis_funct.col(1) +
solution[idx[2]] * basis_funct.col(2);
}
return velocity;
}
} // end namespace projects::ipdg_stokes::post_processing
| 41.139535 | 80 | 0.693612 | [
"mesh",
"geometry"
] |
f027ef155b265991863097b98f2fc786e4053afe | 1,030 | hh | C++ | xhp/pane-contents.hh | appertly/axe | 4a15b4bed0a249bb3a7ce34661c98a14ab7b66b9 | [
"MIT"
] | 1 | 2016-06-07T17:12:27.000Z | 2016-06-07T17:12:27.000Z | xhp/pane-contents.hh | appertly/axe | 4a15b4bed0a249bb3a7ce34661c98a14ab7b66b9 | [
"MIT"
] | null | null | null | xhp/pane-contents.hh | appertly/axe | 4a15b4bed0a249bb3a7ce34661c98a14ab7b66b9 | [
"MIT"
] | null | null | null | <?hh // strict
/**
* Axe
*
* @copyright 2015-2016 Appertly contributors
* @license http://opensource.org/licenses/MIT MIT License
*/
/**
* Pane Contents
*/
class :axe:pane-contents extends :x:element implements HasXHPHelpers
{
use XHPHelpers;
category %flow;
children (:axe:toolbar?, %flow+);
attribute :div;
protected function render(): XHPRoot
{
$buttons = null;
$inner = <div class="pane-contents-inner"/>;
foreach ($this->getChildren() as $kid) {
if ($kid instanceof :axe:toolbar) {
$buttons = $kid;
$kid->addClass('pane-toolbar');
$this->addClass(($kid->getChildren()->isEmpty() ? 'empty' : 'with') . '-toolbar');
} else {
$inner->appendChild($kid);
}
}
if ($buttons === null) {
$this->addClass('no-toolbar');
}
return <div class="pane-contents-outer">
{$buttons}
{$inner}
</div>;
}
}
| 24.52381 | 98 | 0.513592 | [
"render"
] |
f02dd5d45c951193d40e26aa9075c73428174b57 | 206 | cc | C++ | 20181102/plugins/push/api/parts/apn/apns.cc | zengxingqi/countly-node-server | b91a823914286c2d624c467eebf3e6934a3dd2c5 | [
"MIT"
] | 1 | 2019-09-18T12:39:42.000Z | 2019-09-18T12:39:42.000Z | 20181102/plugins/push/api/parts/apn/apns.cc | zengxingqi/countly-node-server | b91a823914286c2d624c467eebf3e6934a3dd2c5 | [
"MIT"
] | 1 | 2019-09-18T12:35:10.000Z | 2019-09-18T12:38:22.000Z | 20181102/plugins/push/api/parts/apn/apns.cc | zengxingqi/countly-node-server | b91a823914286c2d624c467eebf3e6934a3dd2c5 | [
"MIT"
] | null | null | null | #include <nan.h>
#include "h2.h"
namespace apns {
using v8::Local;
using v8::Object;
void InitAll(Local<Object> exports) {
H2::Init(exports);
}
NODE_MODULE(addon, InitAll)
} // namespace demo
| 12.117647 | 38 | 0.665049 | [
"object"
] |
f035197be9c9ccceb9a69f0be8fe9b8729fe17a2 | 4,810 | hpp | C++ | include/lightsky/utils/generic/AlignedAllocatorImpl.hpp | hamsham/LightUtils | ae909ee0e6d8915b1447cbb41aceceb98df1a2e6 | [
"BSD-3-Clause"
] | 1 | 2021-09-04T19:23:37.000Z | 2021-09-04T19:23:37.000Z | include/lightsky/utils/generic/AlignedAllocatorImpl.hpp | hamsham/LightUtils | ae909ee0e6d8915b1447cbb41aceceb98df1a2e6 | [
"BSD-3-Clause"
] | null | null | null | include/lightsky/utils/generic/AlignedAllocatorImpl.hpp | hamsham/LightUtils | ae909ee0e6d8915b1447cbb41aceceb98df1a2e6 | [
"BSD-3-Clause"
] | 1 | 2015-10-16T06:07:58.000Z | 2015-10-16T06:07:58.000Z |
#include <limits> // std::numeric_limits<>
#include <utility> // std::forward()
#include <memory>
#include "lightsky/utils/Pointer.h"
namespace ls
{
namespace utils
{
/*-----------------------------------------------------------------------------
* AlignedAllocator Member Functions
-----------------------------------------------------------------------------*/
/*-------------------------------------
* Constructor
-------------------------------------*/
template <typename T>
constexpr AlignedAllocator<T>::AlignedAllocator() noexcept
{
}
/*-------------------------------------
* Copy Constructor
-------------------------------------*/
template <typename T>
constexpr AlignedAllocator<T>::AlignedAllocator(const AlignedAllocator&) noexcept
{
}
/*-------------------------------------
* Move Constructor
-------------------------------------*/
//template <typename T>
//AlignedAllocator<T>::AlignedAllocator(AlignedAllocator&&) noexcept
//{
//}
/*-------------------------------------
* Copy Constructor (rebound)
-------------------------------------*/
template <typename T>
template <typename U>
constexpr AlignedAllocator<T>::AlignedAllocator(const AlignedAllocator<U>&) noexcept
{
}
/*-------------------------------------
* Move Constructor (rebound)
-------------------------------------*/
//template <typename T>
//template <typename U>
//AlignedAllocator<T>::AlignedAllocator(AlignedAllocator<U>&&) noexcept
//{
//}
/*-------------------------------------
* Pointer from a reference
-------------------------------------*/
template <typename T>
typename AlignedAllocator<T>::pointer AlignedAllocator<T>::address(reference x) const noexcept
{
return &x;
}
/*-------------------------------------
* Pointer from a referecne (const)
-------------------------------------*/
template <typename T>
typename AlignedAllocator<T>::const_pointer AlignedAllocator<T>::address(const_reference x) const noexcept
{
return &x;
}
/*-------------------------------------
* Allocator
-------------------------------------*/
template <typename T>
typename AlignedAllocator<T>::pointer AlignedAllocator<T>::allocate(size_type n) noexcept
{
return (pointer)ls::utils::aligned_malloc(sizeof(T)*n);
}
/*-------------------------------------
* Hinted Allocator
-------------------------------------*/
template <typename T>
typename AlignedAllocator<T>::pointer AlignedAllocator<T>::allocate(size_type n, const void* hint) noexcept
{
(void)hint;
return (pointer)ls::utils::aligned_malloc(sizeof(T)*n);
}
/*-------------------------------------
* Deallocate
-------------------------------------*/
template <typename T>
void AlignedAllocator<T>::deallocate(pointer p, std::size_t n)
{
(void)n;
ls::utils::aligned_free(p);
}
/*-------------------------------------
* Maximum allocation size
-------------------------------------*/
template <typename T>
constexpr typename AlignedAllocator<T>::size_type AlignedAllocator<T>::max_size() const noexcept
{
return std::numeric_limits<std::size_t>::max() / sizeof(T);
}
/*-------------------------------------
* Object Construction
-------------------------------------*/
template <typename T>
void AlignedAllocator<T>::construct(pointer p, const_reference val)
{
::new((void*)p) T{val};
}
/*-------------------------------------
* Aggregated construction
-------------------------------------*/
template <typename T>
template <typename U, typename... Args>
void AlignedAllocator<T>::construct(U* p, Args&&... args)
{
::new((void*)p) U(std::forward<Args...>(args)...);
}
/*-------------------------------------
* Object Destruction
-------------------------------------*/
template <typename T>
void AlignedAllocator<T>::destroy(pointer p)
{
((pointer)p)->~T();
}
/*-------------------------------------
* Rebound Destruction
-------------------------------------*/
template <typename T>
template <typename U>
void AlignedAllocator<T>::destroy(U* p)
{
p->~U();
}
/*-----------------------------------------------------------------------------
* AlignedAllocator Non-Member Functions
-----------------------------------------------------------------------------*/
/*-------------------------------------
* Compare allocators
-------------------------------------*/
template <typename T1, typename T2>
constexpr bool operator==(const AlignedAllocator<T1>& lhs, const AlignedAllocator<T2>& rhs) noexcept
{
return &lhs == &rhs;
}
/*-------------------------------------
* Compare Allocators (not-equal).
-------------------------------------*/
template <typename T1, typename T2>
constexpr bool operator!=(const AlignedAllocator<T1>& lhs, const AlignedAllocator<T2>& rhs) noexcept
{
return &lhs != &rhs;
}
} // end utils namespace
} // end ls namespace
| 22.796209 | 107 | 0.468399 | [
"object"
] |
f039a6dbe53fef06a4f83dd2a89192fed290298f | 36,717 | cpp | C++ | src/core/SkShaderCodeDictionary.cpp | TheRakeshPurohit/skia | 817dd601f85f986a99d102de8dc42ee8638a56f9 | [
"BSD-3-Clause"
] | null | null | null | src/core/SkShaderCodeDictionary.cpp | TheRakeshPurohit/skia | 817dd601f85f986a99d102de8dc42ee8638a56f9 | [
"BSD-3-Clause"
] | null | null | null | src/core/SkShaderCodeDictionary.cpp | TheRakeshPurohit/skia | 817dd601f85f986a99d102de8dc42ee8638a56f9 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright 2022 Google LLC
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "src/core/SkShaderCodeDictionary.h"
#include "include/core/SkCombinationBuilder.h"
#include "include/effects/SkRuntimeEffect.h"
#include "include/private/SkSLString.h"
#include "src/core/SkOpts.h"
#include "src/sksl/SkSLUtil.h"
#ifdef SK_GRAPHITE_ENABLED
#include "include/gpu/graphite/Context.h"
#endif
// We need to ensure that the user-defined snippet ID can't conflict with the SkBlendMode
// values (since they are used "raw" in the combination system).
static const int kMinUserDefinedSnippetID = std::max(kBuiltInCodeSnippetIDCount, kSkBlendModeCount);
namespace {
std::string get_mangled_local_var_name(const char* baseName, int manglingSuffix) {
return std::string(baseName) + "_" + std::to_string(manglingSuffix);
}
void add_indent(std::string* result, int indent) {
result->append(4*indent, ' ');
}
#if SK_SUPPORT_GPU && defined(SK_GRAPHITE_ENABLED) && defined(SK_METAL)
std::string generate_default_before_children_glue_code(int entryIndex,
const SkPaintParamsKey::BlockReader& reader,
const std::string& parentPreLocalName,
int indent) {
std::string result;
if (reader.entry()->needsLocalCoords()) {
// Every snippet that requests local coordinates must have a preLocalMatrix as its first
// uniform
SkASSERT(reader.entry()->fUniforms.size() >= 1);
SkASSERT(reader.entry()->fUniforms[0].type() == SkSLType::kFloat4x4);
std::string localMatrixUniformName = reader.entry()->getMangledUniformName(0, entryIndex);
std::string preLocalMatrixVarName = get_mangled_local_var_name("preLocal", entryIndex);
add_indent(&result, indent);
SkSL::String::appendf(&result,
"float4x4 %s = %s * %s;\n",
preLocalMatrixVarName.c_str(),
parentPreLocalName.c_str(),
localMatrixUniformName.c_str());
}
return result;
}
#endif
} // anonymous namespace
std::string SkShaderSnippet::getMangledUniformName(int uniformIndex, int mangleId) const {
std::string result;
result = fUniforms[uniformIndex].name() + std::string("_") + std::to_string(mangleId);
return result;
}
// TODO: SkShaderInfo::toSkSL needs to work outside of both just graphite and metal. To do
// so we'll need to switch over to using SkSL's uniform capabilities.
#if SK_SUPPORT_GPU && defined(SK_GRAPHITE_ENABLED) && defined(SK_METAL)
// TODO: switch this over to using SkSL's uniform system
namespace skgpu::graphite {
std::string GetMtlUniforms(int bufferID,
const char* name,
const std::vector<SkPaintParamsKey::BlockReader>&,
bool needsDev2Local);
std::string GetMtlTexturesAndSamplers(const std::vector<SkPaintParamsKey::BlockReader>&,
int* binding);
} // namespace skgpu::graphite
// Emit the glue code needed to invoke a single static helper isolated w/in its own scope.
// The structure of this will be:
//
// half4 outColor%d;
// {
// half4 child-outColor%d; // for each child
// {
// /* emitted snippet sksl assigns to child-outColor%d */
// }
//
// /* emitted snippet sksl assigns to outColor%d - taking a vector of child var names */
// }
// Where the %d is filled in with 'entryIndex'.
std::string SkShaderInfo::emitGlueCodeForEntry(int* entryIndex,
const std::string& priorStageOutputName,
const std::string& parentPreLocalName,
std::string* result,
int indent) const {
const SkPaintParamsKey::BlockReader& reader = fBlockReaders[*entryIndex];
int curEntryIndex = *entryIndex;
std::string scopeOutputVar = get_mangled_local_var_name("outColor", curEntryIndex);
add_indent(result, indent);
SkSL::String::appendf(result,
"half4 %s; // output of %s\n",
scopeOutputVar.c_str(),
reader.entry()->fName);
add_indent(result, indent);
*result += "{\n";
*result += generate_default_before_children_glue_code(curEntryIndex, reader,
parentPreLocalName, indent+1);
// TODO: this could be returned by generate_default_before_children_glue_code
std::string currentPreLocalName;
if (reader.entry()->needsLocalCoords()) {
currentPreLocalName = get_mangled_local_var_name("preLocal", curEntryIndex);
} else {
currentPreLocalName = parentPreLocalName;
}
// Although the children appear after the parent in the shader info they are emitted
// before the parent
std::vector<std::string> childOutputVarNames;
for (int j = 0; j < reader.numChildren(); ++j) {
*entryIndex += 1;
std::string childOutputVar = this->emitGlueCodeForEntry(entryIndex,
priorStageOutputName,
currentPreLocalName,
result, indent+1);
childOutputVarNames.push_back(childOutputVar);
}
*result += (reader.entry()->fGlueCodeGenerator)(scopeOutputVar, curEntryIndex, reader,
priorStageOutputName,
childOutputVarNames, indent+1);
add_indent(result, indent);
*result += "}\n";
return scopeOutputVar;
}
// The current, incomplete, model for shader construction is:
// - Static code snippets (which can have an arbitrary signature) live in the Graphite
// pre-compiled module, which is located at `src/sksl/sksl_graphite_frag.sksl`.
// - Glue code is generated in a `main` method which calls these static code snippets.
// The glue code is responsible for:
// 1) gathering the correct (mangled) uniforms
// 2) passing the uniforms and any other parameters to the helper method
// - The result of the final code snippet is then copied into "sk_FragColor".
// Note: each entry's 'fStaticFunctionName' field is expected to match the name of a function
// in the Graphite pre-compiled module.
std::string SkShaderInfo::toSkSL() const {
// The uniforms are mangled by having their index in 'fEntries' as a suffix (i.e., "_%d")
std::string result = skgpu::graphite::GetMtlUniforms(2, "FS", fBlockReaders,
this->needsLocalCoords());
int binding = 0;
result += skgpu::graphite::GetMtlTexturesAndSamplers(fBlockReaders, &binding);
result += "layout(location = 0, index = 0) out half4 sk_FragColor;\n";
result += "void main() {\n";
if (this->needsLocalCoords()) {
result += "const float4x4 initialPreLocal = float4x4(1);\n";
}
std::string parentPreLocal = "initialPreLocal";
std::string lastOutputVar = "initialColor";
// TODO: what is the correct initial color to feed in?
add_indent(&result, 1);
SkSL::String::appendf(&result, " half4 %s = half4(0.0);", lastOutputVar.c_str());
for (int entryIndex = 0; entryIndex < (int) fBlockReaders.size(); ++entryIndex) {
lastOutputVar = this->emitGlueCodeForEntry(&entryIndex, lastOutputVar, parentPreLocal,
&result, 1);
}
SkSL::String::appendf(&result, " sk_FragColor = %s;\n", lastOutputVar.c_str());
result += "}\n";
return result;
}
#endif
SkShaderCodeDictionary::Entry* SkShaderCodeDictionary::makeEntry(
const SkPaintParamsKey& key
#ifdef SK_GRAPHITE_ENABLED
, const SkPipelineDataGatherer::BlendInfo& blendInfo
#endif
) {
uint8_t* newKeyData = fArena.makeArray<uint8_t>(key.sizeInBytes());
memcpy(newKeyData, key.data(), key.sizeInBytes());
SkSpan<const uint8_t> newKeyAsSpan = SkMakeSpan(newKeyData, key.sizeInBytes());
#ifdef SK_GRAPHITE_ENABLED
return fArena.make([&](void *ptr) { return new(ptr) Entry(newKeyAsSpan, blendInfo); });
#else
return fArena.make([&](void *ptr) { return new(ptr) Entry(newKeyAsSpan); });
#endif
}
size_t SkShaderCodeDictionary::Hash::operator()(const SkPaintParamsKey* key) const {
return SkOpts::hash_fn(key->data(), key->sizeInBytes(), 0);
}
const SkShaderCodeDictionary::Entry* SkShaderCodeDictionary::findOrCreate(
const SkPaintParamsKey& key
#ifdef SK_GRAPHITE_ENABLED
, const SkPipelineDataGatherer::BlendInfo& blendInfo
#endif
) {
SkAutoSpinlock lock{fSpinLock};
auto iter = fHash.find(&key);
if (iter != fHash.end()) {
SkASSERT(fEntryVector[iter->second->uniqueID().asUInt()] == iter->second);
return iter->second;
}
#ifdef SK_GRAPHITE_ENABLED
Entry* newEntry = this->makeEntry(key, blendInfo);
#else
Entry* newEntry = this->makeEntry(key);
#endif
newEntry->setUniqueID(fEntryVector.size());
fHash.insert(std::make_pair(&newEntry->paintParamsKey(), newEntry));
fEntryVector.push_back(newEntry);
return newEntry;
}
const SkShaderCodeDictionary::Entry* SkShaderCodeDictionary::lookup(
SkUniquePaintParamsID codeID) const {
if (!codeID.isValid()) {
return nullptr;
}
SkAutoSpinlock lock{fSpinLock};
SkASSERT(codeID.asUInt() < fEntryVector.size());
return fEntryVector[codeID.asUInt()];
}
SkSpan<const SkUniform> SkShaderCodeDictionary::getUniforms(SkBuiltInCodeSnippetID id) const {
return fBuiltInCodeSnippets[(int) id].fUniforms;
}
SkSpan<const SkPaintParamsKey::DataPayloadField> SkShaderCodeDictionary::dataPayloadExpectations(
int codeSnippetID) const {
// All callers of this entry point should already have ensured that 'codeSnippetID' is valid
return this->getEntry(codeSnippetID)->fDataPayloadExpectations;
}
const SkShaderSnippet* SkShaderCodeDictionary::getEntry(int codeSnippetID) const {
if (codeSnippetID < 0) {
return nullptr;
}
if (codeSnippetID < kBuiltInCodeSnippetIDCount) {
return &fBuiltInCodeSnippets[codeSnippetID];
}
if (codeSnippetID < kMinUserDefinedSnippetID) {
return nullptr;
}
int userDefinedCodeSnippetID = codeSnippetID - kMinUserDefinedSnippetID;
if (userDefinedCodeSnippetID < SkTo<int>(fUserDefinedCodeSnippets.size())) {
return fUserDefinedCodeSnippets[userDefinedCodeSnippetID].get();
}
return nullptr;
}
const SkShaderSnippet* SkShaderCodeDictionary::getEntry(SkBlenderID id) const {
return this->getEntry(id.asUInt());
}
void SkShaderCodeDictionary::getShaderInfo(SkUniquePaintParamsID uniqueID, SkShaderInfo* info) {
auto entry = this->lookup(uniqueID);
entry->paintParamsKey().toShaderInfo(this, info);
#ifdef SK_GRAPHITE_ENABLED
info->setBlendInfo(entry->blendInfo());
#endif
}
//--------------------------------------------------------------------------------------------------
namespace {
using DataPayloadField = SkPaintParamsKey::DataPayloadField;
// The default glue code just calls a helper function with the signature:
// half4 fStaticFunctionName(/* all uniforms as parameters */,
// /* all child output variable names as parameters */);
// and stores the result in a variable named "resultName".
std::string GenerateDefaultGlueCode(const std::string& resultName,
int entryIndex,
const SkPaintParamsKey::BlockReader& reader,
const std::string& priorStageOutputName,
const std::vector<std::string>& childOutputVarNames,
int indent) {
const SkShaderSnippet* entry = reader.entry();
SkASSERT((int)childOutputVarNames.size() == entry->numExpectedChildren());
if (entry->needsLocalCoords()) {
// Every snippet that requests local coordinates must have a localMatrix as its first
// uniform
SkASSERT(reader.entry()->fUniforms.size() >= 1);
SkASSERT(reader.entry()->fUniforms[0].type() == SkSLType::kFloat4x4);
}
std::string result;
add_indent(&result, indent);
SkSL::String::appendf(&result,
"%s = %s(",
resultName.c_str(),
entry->fStaticFunctionName);
for (size_t i = 0; i < entry->fUniforms.size(); ++i) {
if (i == 0 && reader.entry()->needsLocalCoords()) {
std::string preLocalMatrixVarName = get_mangled_local_var_name("preLocal",
entryIndex);
result += preLocalMatrixVarName;
result += " * dev2LocalUni";
} else {
result += entry->getMangledUniformName(i, entryIndex);
}
if (i+1 < entry->fUniforms.size() + childOutputVarNames.size()) {
result += ", ";
}
}
for (size_t i = 0; i < childOutputVarNames.size(); ++i) {
result += childOutputVarNames[i].c_str();
if (i+1 < childOutputVarNames.size()) {
result += ", ";
}
}
result += ");\n";
return result;
}
//--------------------------------------------------------------------------------------------------
static constexpr int kFourStopGradient = 4;
static constexpr int kEightStopGradient = 8;
static constexpr int kNumLinearGradientUniforms = 9;
static constexpr SkUniform kLinearGradientUniforms4[kNumLinearGradientUniforms] = {
{ "localMatrix", SkSLType::kFloat4x4 },
{ "colors", SkSLType::kFloat4, kFourStopGradient },
{ "offsets", SkSLType::kFloat, kFourStopGradient },
{ "point0", SkSLType::kFloat2 },
{ "point1", SkSLType::kFloat2 },
{ "tilemode", SkSLType::kInt },
{ "padding1", SkSLType::kFloat }, // TODO: add automatic uniform padding
{ "padding2", SkSLType::kFloat },
{ "padding3", SkSLType::kFloat },
};
static constexpr SkUniform kLinearGradientUniforms8[kNumLinearGradientUniforms] = {
{ "localMatrix", SkSLType::kFloat4x4 },
{ "colors", SkSLType::kFloat4, kEightStopGradient },
{ "offsets", SkSLType::kFloat, kEightStopGradient },
{ "point0", SkSLType::kFloat2 },
{ "point1", SkSLType::kFloat2 },
{ "tilemode", SkSLType::kInt },
{ "padding1", SkSLType::kFloat }, // TODO: add automatic uniform padding
{ "padding2", SkSLType::kFloat },
{ "padding3", SkSLType::kFloat },
};
static constexpr int kNumRadialGradientUniforms = 6;
static constexpr SkUniform kRadialGradientUniforms4[kNumRadialGradientUniforms] = {
{ "localMatrix", SkSLType::kFloat4x4 },
{ "colors", SkSLType::kFloat4, kFourStopGradient },
{ "offsets", SkSLType::kFloat, kFourStopGradient },
{ "center", SkSLType::kFloat2 },
{ "radius", SkSLType::kFloat },
{ "tilemode", SkSLType::kInt },
};
static constexpr SkUniform kRadialGradientUniforms8[kNumRadialGradientUniforms] = {
{ "localMatrix", SkSLType::kFloat4x4 },
{ "colors", SkSLType::kFloat4, kEightStopGradient },
{ "offsets", SkSLType::kFloat, kEightStopGradient },
{ "center", SkSLType::kFloat2 },
{ "radius", SkSLType::kFloat },
{ "tilemode", SkSLType::kInt },
};
static constexpr int kNumSweepGradientUniforms = 10;
static constexpr SkUniform kSweepGradientUniforms4[kNumSweepGradientUniforms] = {
{ "localMatrix", SkSLType::kFloat4x4 },
{ "colors", SkSLType::kFloat4, kFourStopGradient },
{ "offsets", SkSLType::kFloat, kFourStopGradient },
{ "center", SkSLType::kFloat2 },
{ "bias", SkSLType::kFloat },
{ "scale", SkSLType::kFloat },
{ "tilemode", SkSLType::kInt },
{ "padding1", SkSLType::kFloat }, // TODO: add automatic uniform padding
{ "padding2", SkSLType::kFloat },
{ "padding3", SkSLType::kFloat },
};
static constexpr SkUniform kSweepGradientUniforms8[kNumSweepGradientUniforms] = {
{ "localMatrix", SkSLType::kFloat4x4 },
{ "colors", SkSLType::kFloat4, kEightStopGradient },
{ "offsets", SkSLType::kFloat, kEightStopGradient },
{ "center", SkSLType::kFloat2 },
{ "bias", SkSLType::kFloat },
{ "scale", SkSLType::kFloat },
{ "tilemode", SkSLType::kInt },
{ "padding1", SkSLType::kFloat }, // TODO: add automatic uniform padding
{ "padding2", SkSLType::kFloat },
{ "padding3", SkSLType::kFloat },
};
static constexpr int kNumConicalGradientUniforms = 9;
static constexpr SkUniform kConicalGradientUniforms4[kNumConicalGradientUniforms] = {
{ "localMatrix", SkSLType::kFloat4x4 },
{ "colors", SkSLType::kFloat4, kFourStopGradient },
{ "offsets", SkSLType::kFloat, kFourStopGradient },
{ "point0", SkSLType::kFloat2 },
{ "point1", SkSLType::kFloat2 },
{ "radius0", SkSLType::kFloat },
{ "radius1", SkSLType::kFloat },
{ "tilemode", SkSLType::kInt },
{ "padding", SkSLType::kFloat }, // TODO: add automatic uniform padding
};
static constexpr SkUniform kConicalGradientUniforms8[kNumConicalGradientUniforms] = {
{ "localMatrix", SkSLType::kFloat4x4 },
{ "colors", SkSLType::kFloat4, kEightStopGradient },
{ "offsets", SkSLType::kFloat, kEightStopGradient },
{ "point0", SkSLType::kFloat2 },
{ "point1", SkSLType::kFloat2 },
{ "radius0", SkSLType::kFloat },
{ "radius1", SkSLType::kFloat },
{ "tilemode", SkSLType::kInt },
{ "padding", SkSLType::kFloat }, // TODO: add automatic uniform padding
};
static constexpr char kLinearGradient4Name[] = "sk_linear_grad_4_shader";
static constexpr char kLinearGradient8Name[] = "sk_linear_grad_8_shader";
static constexpr char kRadialGradient4Name[] = "sk_radial_grad_4_shader";
static constexpr char kRadialGradient8Name[] = "sk_radial_grad_8_shader";
static constexpr char kSweepGradient4Name[] = "sk_sweep_grad_4_shader";
static constexpr char kSweepGradient8Name[] = "sk_sweep_grad_8_shader";
static constexpr char kConicalGradient4Name[] = "sk_conical_grad_4_shader";
static constexpr char kConicalGradient8Name[] = "sk_conical_grad_8_shader";
//--------------------------------------------------------------------------------------------------
static constexpr int kNumSolidShaderUniforms = 1;
static constexpr SkUniform kSolidShaderUniforms[kNumSolidShaderUniforms] = {
{ "color", SkSLType::kFloat4 }
};
static constexpr char kSolidShaderName[] = "sk_solid_shader";
//--------------------------------------------------------------------------------------------------
static constexpr int kNumLocalMatrixShaderUniforms = 1;
static constexpr SkUniform kLocalMatrixShaderUniforms[kNumLocalMatrixShaderUniforms] = {
{ "localMatrix", SkSLType::kFloat4x4 },
};
static constexpr int kNumLocalMatrixShaderChildren = 1;
static constexpr char kLocalMatrixShaderName[] = "sk_local_matrix_shader";
//--------------------------------------------------------------------------------------------------
static constexpr int kNumImageShaderUniforms = 6;
static constexpr SkUniform kImageShaderUniforms[kNumImageShaderUniforms] = {
{ "localMatrix", SkSLType::kFloat4x4 },
{ "subset", SkSLType::kFloat4 },
{ "tilemodeX", SkSLType::kInt },
{ "tilemodeY", SkSLType::kInt },
{ "imgWidth", SkSLType::kInt },
{ "imgHeight", SkSLType::kInt },
};
static constexpr int kNumImageShaderTexturesAndSamplers = 1;
static constexpr SkTextureAndSampler kISTexturesAndSamplers[kNumImageShaderTexturesAndSamplers] = {
{"sampler"},
};
static_assert(0 == static_cast<int>(SkTileMode::kClamp), "ImageShader code depends on SkTileMode");
static_assert(1 == static_cast<int>(SkTileMode::kRepeat), "ImageShader code depends on SkTileMode");
static_assert(2 == static_cast<int>(SkTileMode::kMirror), "ImageShader code depends on SkTileMode");
static_assert(3 == static_cast<int>(SkTileMode::kDecal), "ImageShader code depends on SkTileMode");
static constexpr char kImageShaderName[] = "sk_compute_coords";
// This is _not_ what we want to do.
// Ideally the "compute_coords" code snippet could just take texture and
// sampler references and do everything. That is going to take more time to figure out though so,
// for the sake of expediency, we're generating custom code to do the sampling.
std::string GenerateImageShaderGlueCode(const std::string& resultName,
int entryIndex,
const SkPaintParamsKey::BlockReader& reader,
const std::string& priorStageOutputName,
const std::vector<std::string>& childNames,
int indent) {
SkASSERT(childNames.empty());
std::string samplerVarName = std::string("sampler_") + std::to_string(entryIndex) + "_0";
std::string preLocalMatrixVarName = get_mangled_local_var_name("preLocal", entryIndex);
// Uniform slot 0 is being used for the localMatrix but is handled in
// generate_default_before_children_glue_code.
std::string subsetName = reader.entry()->getMangledUniformName(1, entryIndex);
std::string tmXName = reader.entry()->getMangledUniformName(2, entryIndex);
std::string tmYName = reader.entry()->getMangledUniformName(3, entryIndex);
std::string imgWidthName = reader.entry()->getMangledUniformName(4, entryIndex);
std::string imgHeightName = reader.entry()->getMangledUniformName(5, entryIndex);
std::string result;
add_indent(&result, indent);
SkSL::String::appendf(&result,
"float2 coords = %s(%s * dev2LocalUni, %s, %s, %s, %s, %s);",
reader.entry()->fStaticFunctionName,
preLocalMatrixVarName.c_str(),
subsetName.c_str(),
tmXName.c_str(),
tmYName.c_str(),
imgWidthName.c_str(),
imgHeightName.c_str());
add_indent(&result, indent);
SkSL::String::appendf(&result,
"%s = sample(%s, coords);\n",
resultName.c_str(),
samplerVarName.c_str());
return result;
}
//--------------------------------------------------------------------------------------------------
static constexpr int kNumBlendShaderUniforms = 4;
static constexpr SkUniform kBlendShaderUniforms[kNumBlendShaderUniforms] = {
{ "blendMode", SkSLType::kInt },
{ "padding1", SkSLType::kInt }, // TODO: add automatic uniform padding
{ "padding2", SkSLType::kInt },
{ "padding3", SkSLType::kInt },
};
static constexpr int kNumBlendShaderChildren = 2;
static constexpr char kBlendShaderName[] = "sk_blend_shader";
//--------------------------------------------------------------------------------------------------
static constexpr char kErrorName[] = "sk_error";
//--------------------------------------------------------------------------------------------------
// This method generates the glue code for the case where the SkBlendMode-based blending is
// handled with fixed function blending.
std::string GenerateFixedFunctionBlenderGlueCode(const std::string& resultName,
int entryIndex,
const SkPaintParamsKey::BlockReader& reader,
const std::string& priorStageOutputName,
const std::vector<std::string>& childNames,
int indent) {
SkASSERT(childNames.empty());
SkASSERT(reader.entry()->fUniforms.empty());
SkASSERT(reader.numDataPayloadFields() == 0);
// The actual blending is set up via the fixed function pipeline so we don't actually
// need to access the blend mode in the glue code.
std::string result;
add_indent(&result, indent);
result += "// Fixed-function blending\n";
add_indent(&result, indent);
SkSL::String::appendf(&result, "%s = %s;", resultName.c_str(), priorStageOutputName.c_str());
return result;
}
//--------------------------------------------------------------------------------------------------
static constexpr int kNumShaderBasedBlenderUniforms = 4;
static constexpr SkUniform kShaderBasedBlenderUniforms[kNumShaderBasedBlenderUniforms] = {
{ "blendMode", SkSLType::kInt },
{ "padding1", SkSLType::kInt }, // TODO: add automatic uniform padding
{ "padding2", SkSLType::kInt },
{ "padding3", SkSLType::kInt },
};
static constexpr char kBlendHelperName[] = "sk_blend";
// This method generates the glue code for the case where the SkBlendMode-based blending must occur
// in the shader (i.e., fixed function blending isn't possible).
// It exists as custom glue code so that we can deal with the dest reads. If that can be
// standardized (e.g., via a snippets requirement flag) this could be removed.
std::string GenerateShaderBasedBlenderGlueCode(const std::string& resultName,
int entryIndex,
const SkPaintParamsKey::BlockReader& reader,
const std::string& priorStageOutputName,
const std::vector<std::string>& childNames,
int indent) {
SkASSERT(childNames.empty());
SkASSERT(reader.entry()->fUniforms.size() == 4); // actual blend uniform + 3 padding int
SkASSERT(reader.numDataPayloadFields() == 0);
std::string uniformName = reader.entry()->getMangledUniformName(0, entryIndex);
std::string result;
add_indent(&result, indent);
result += "// Shader-based blending\n";
// TODO: emit code to perform dest read here
add_indent(&result, indent);
result += "half4 dummyDst = half4(1.0, 1.0, 1.0, 1.0);\n";
add_indent(&result, indent);
SkSL::String::appendf(&result, "%s = %s(%s, %s, dummyDst);",
resultName.c_str(),
reader.entry()->fStaticFunctionName,
uniformName.c_str(),
priorStageOutputName.c_str());
return result;
}
//--------------------------------------------------------------------------------------------------
} // anonymous namespace
bool SkShaderCodeDictionary::isValidID(int snippetID) const {
if (snippetID < 0) {
return false;
}
if (snippetID < kBuiltInCodeSnippetIDCount) {
return true;
}
if (snippetID < kMinUserDefinedSnippetID) {
return false;
}
int userDefinedCodeSnippetID = snippetID - kMinUserDefinedSnippetID;
return userDefinedCodeSnippetID < SkTo<int>(fUserDefinedCodeSnippets.size());
}
static constexpr int kNoChildren = 0;
// TODO: this version needs to be removed
int SkShaderCodeDictionary::addUserDefinedSnippet(
const char* name,
SkSpan<const SkPaintParamsKey::DataPayloadField> dataPayloadExpectations) {
std::unique_ptr<SkShaderSnippet> entry(new SkShaderSnippet("UserDefined",
{}, // no uniforms
SnippetRequirementFlags::kNone,
{}, // no samplers
name,
GenerateDefaultGlueCode,
kNoChildren,
dataPayloadExpectations));
// TODO: the memory for user-defined entries could go in the dictionary's arena but that
// would have to be a thread safe allocation since the arena also stores entries for
// 'fHash' and 'fEntryVector'
fUserDefinedCodeSnippets.push_back(std::move(entry));
return kMinUserDefinedSnippetID + fUserDefinedCodeSnippets.size() - 1;
}
SkBlenderID SkShaderCodeDictionary::addUserDefinedBlender(sk_sp<SkRuntimeEffect> effect) {
if (!effect) {
return {};
}
// TODO: at this point we need to extract the uniform definitions, children and helper functions
// from the runtime effect in order to create a real SkShaderSnippet
// Additionally, we need to hash the provided code to deduplicate the runtime effects in case
// the client keeps giving us different rtEffects w/ the same backing SkSL.
std::unique_ptr<SkShaderSnippet> entry(new SkShaderSnippet("UserDefined",
{}, // missing uniforms
SnippetRequirementFlags::kNone,
{}, // missing samplers
"foo",
GenerateDefaultGlueCode,
kNoChildren,
{})); // missing data payload
// TODO: the memory for user-defined entries could go in the dictionary's arena but that
// would have to be a thread safe allocation since the arena also stores entries for
// 'fHash' and 'fEntryVector'
fUserDefinedCodeSnippets.push_back(std::move(entry));
return SkBlenderID(kMinUserDefinedSnippetID + fUserDefinedCodeSnippets.size() - 1);
}
SkShaderCodeDictionary::SkShaderCodeDictionary() {
// The 0th index is reserved as invalid
fEntryVector.push_back(nullptr);
fBuiltInCodeSnippets[(int) SkBuiltInCodeSnippetID::kError] = {
"Error",
{ }, // no uniforms
SnippetRequirementFlags::kNone,
{ }, // no samplers
kErrorName,
GenerateDefaultGlueCode,
kNoChildren,
{ }
};
fBuiltInCodeSnippets[(int) SkBuiltInCodeSnippetID::kSolidColorShader] = {
"SolidColor",
SkMakeSpan(kSolidShaderUniforms, kNumSolidShaderUniforms),
SnippetRequirementFlags::kNone,
{ }, // no samplers
kSolidShaderName,
GenerateDefaultGlueCode,
kNoChildren,
{ }
};
fBuiltInCodeSnippets[(int) SkBuiltInCodeSnippetID::kLinearGradientShader4] = {
"LinearGradient4",
SkMakeSpan(kLinearGradientUniforms4, kNumLinearGradientUniforms),
SnippetRequirementFlags::kLocalCoords,
{ }, // no samplers
kLinearGradient4Name,
GenerateDefaultGlueCode,
kNoChildren,
{ }
};
fBuiltInCodeSnippets[(int) SkBuiltInCodeSnippetID::kLinearGradientShader8] = {
"LinearGradient8",
SkMakeSpan(kLinearGradientUniforms8, kNumLinearGradientUniforms),
SnippetRequirementFlags::kLocalCoords,
{ }, // no samplers
kLinearGradient8Name,
GenerateDefaultGlueCode,
kNoChildren,
{ }
};
fBuiltInCodeSnippets[(int) SkBuiltInCodeSnippetID::kRadialGradientShader4] = {
"RadialGradient4",
SkMakeSpan(kRadialGradientUniforms4, kNumRadialGradientUniforms),
SnippetRequirementFlags::kLocalCoords,
{ }, // no samplers
kRadialGradient4Name,
GenerateDefaultGlueCode,
kNoChildren,
{ }
};
fBuiltInCodeSnippets[(int) SkBuiltInCodeSnippetID::kRadialGradientShader8] = {
"RadialGradient8",
SkMakeSpan(kRadialGradientUniforms8, kNumRadialGradientUniforms),
SnippetRequirementFlags::kLocalCoords,
{ }, // no samplers
kRadialGradient8Name,
GenerateDefaultGlueCode,
kNoChildren,
{ }
};
fBuiltInCodeSnippets[(int) SkBuiltInCodeSnippetID::kSweepGradientShader4] = {
"SweepGradient4",
SkMakeSpan(kSweepGradientUniforms4, kNumSweepGradientUniforms),
SnippetRequirementFlags::kLocalCoords,
{ }, // no samplers
kSweepGradient4Name,
GenerateDefaultGlueCode,
kNoChildren,
{ }
};
fBuiltInCodeSnippets[(int) SkBuiltInCodeSnippetID::kSweepGradientShader8] = {
"SweepGradient8",
SkMakeSpan(kSweepGradientUniforms8, kNumSweepGradientUniforms),
SnippetRequirementFlags::kLocalCoords,
{ }, // no samplers
kSweepGradient8Name,
GenerateDefaultGlueCode,
kNoChildren,
{ }
};
fBuiltInCodeSnippets[(int) SkBuiltInCodeSnippetID::kConicalGradientShader4] = {
"ConicalGradient4",
SkMakeSpan(kConicalGradientUniforms4, kNumConicalGradientUniforms),
SnippetRequirementFlags::kLocalCoords,
{ }, // no samplers
kConicalGradient4Name,
GenerateDefaultGlueCode,
kNoChildren,
{ }
};
fBuiltInCodeSnippets[(int) SkBuiltInCodeSnippetID::kConicalGradientShader8] = {
"ConicalGradient8",
SkMakeSpan(kConicalGradientUniforms8, kNumConicalGradientUniforms),
SnippetRequirementFlags::kLocalCoords,
{ }, // no samplers
kConicalGradient8Name,
GenerateDefaultGlueCode,
kNoChildren,
{ }
};
fBuiltInCodeSnippets[(int) SkBuiltInCodeSnippetID::kLocalMatrixShader] = {
"LocalMatrixShader",
SkMakeSpan(kLocalMatrixShaderUniforms, kNumLocalMatrixShaderUniforms),
SnippetRequirementFlags::kLocalCoords,
{ }, // no samplers
kLocalMatrixShaderName,
GenerateDefaultGlueCode,
kNumLocalMatrixShaderChildren,
{ }
};
fBuiltInCodeSnippets[(int) SkBuiltInCodeSnippetID::kImageShader] = {
"ImageShader",
SkMakeSpan(kImageShaderUniforms, kNumImageShaderUniforms),
SnippetRequirementFlags::kLocalCoords,
SkMakeSpan(kISTexturesAndSamplers, kNumImageShaderTexturesAndSamplers),
kImageShaderName,
GenerateImageShaderGlueCode,
kNoChildren,
{ }
};
fBuiltInCodeSnippets[(int) SkBuiltInCodeSnippetID::kBlendShader] = {
"BlendShader",
{ kBlendShaderUniforms, kNumBlendShaderUniforms },
SnippetRequirementFlags::kNone,
{ }, // no samplers
kBlendShaderName,
GenerateDefaultGlueCode,
kNumBlendShaderChildren,
{ }
};
fBuiltInCodeSnippets[(int) SkBuiltInCodeSnippetID::kFixedFunctionBlender] = {
"FixedFunctionBlender",
{ }, // no uniforms
SnippetRequirementFlags::kNone,
{ }, // no samplers
"FF-blending", // fixed function blending doesn't use static SkSL
GenerateFixedFunctionBlenderGlueCode,
kNoChildren,
{ }
};
fBuiltInCodeSnippets[(int) SkBuiltInCodeSnippetID::kShaderBasedBlender] = {
"ShaderBasedBlender",
{ kShaderBasedBlenderUniforms, kNumShaderBasedBlenderUniforms },
SnippetRequirementFlags::kNone,
{ }, // no samplers
kBlendHelperName,
GenerateShaderBasedBlenderGlueCode,
kNoChildren,
{ }
};
}
| 42.694186 | 100 | 0.595174 | [
"vector",
"model"
] |
f0518a42543b9e37bd84bb996011e4d9705ecfe6 | 8,609 | hpp | C++ | src/app/obstacle-shape.hpp | mimo31/fluid-sim | 481c3e5a5456350bccb8795aa119a3487dff3021 | [
"MIT"
] | 1 | 2020-11-26T17:20:28.000Z | 2020-11-26T17:20:28.000Z | src/app/obstacle-shape.hpp | mimo31/brandy0 | 481c3e5a5456350bccb8795aa119a3487dff3021 | [
"MIT"
] | null | null | null | src/app/obstacle-shape.hpp | mimo31/brandy0 | 481c3e5a5456350bccb8795aa119a3487dff3021 | [
"MIT"
] | null | null | null | /**
* obstacle-shape.hpp
*
* Author: Viktor Fukala
* Created on 2021/01/14
*/
#ifndef OBSTACLE_SHAPE_HPP
#define OBSTACLE_SHAPE_HPP
#define _USE_MATH_DEFINES
#include <cairomm/context.h>
#include <array>
#include "grid.hpp"
#include "ptr.hpp"
#include "str.hpp"
#include "tests.hpp"
#include "vec.hpp"
#include "vec2d.hpp"
namespace brandy0
{
/**
* Mode of the shape configuration window for adding a shape
*/
struct AddShapeMode
{
/// Name of the mode
str name;
/**
* Constructs an AddShapeMode
* @param name name of the mode
*/
AddShapeMode(const str name) : name(name)
{
}
};
/// Array of all AddShapeMode supported by the shape configuration window
const std::array<AddShapeMode, 4> AddShapeModes{
AddShapeMode("rectangle"), AddShapeMode("polygon"), AddShapeMode("circle"), AddShapeMode("ellipse")
};
/// Index of the AddShapeMode for adding a rectangle
constexpr uint32_t AddShapeRectangle = 0;
/// Index of the AddShapeMode for adding an arbitrary polygon
constexpr uint32_t AddShapePolygon = 1;
/// Index of the AddShapeMode for adding a circle
constexpr uint32_t AddShapeCircle = 2;
/// Index of the AddShapeMode for adding an ellipse
constexpr uint32_t AddShapeEllipse = 3;
/// Index of the default AddShapeMode
constexpr uint32_t AddShapeModeDefault = AddShapeRectangle;
/**
* Abstract class representing the shape of an obstacle in the simulated container
*/
class ObstacleShape
{
protected:
/**
* Constructs the ObstacleShape
* @param negative true iff the shape is negative @see ObstacleShape::negative
*/
ObstacleShape(bool negative);
public:
/// True iff this shape doesn't make grid points inside of it solid, but instead makes them not solid if they were solid due to some previous shape
bool negative;
/**
* Draws the shape. Draws into the (0, 0) -- (1, 1) square (transform coordinates beforehand to draw as needed).
* @param cr context used for drawing
*/
virtual void draw(const Cairo::RefPtr<Cairo::Context>& cr) const = 0;
/**
* Applies this shape to the provided grid by setting the solidness of the grid points inside this shape.
* For the purposes of the coordinate transform, assumes the grid is the (0, 0) -- (1, 1) square.
* @param grid grid to modify
*/
virtual void fill(Grid<bool> &grid) const = 0;
};
typedef vec<sptr<ObstacleShape>>::iterator ObstacleShapeStackIterator;
typedef vec<sptr<ObstacleShape>>::const_iterator ObstacleShapeStackConstIterator;
/**
* A stack of obstacle shapes with an index of the topmost shown shape.
* Aallows for undo -- decrement index, redo -- increment index, add shape -- pop down to index & push new shape
*/
class ObstacleShapeStack
{
private:
/// The number of shown shapes (the first shownPointer shapes from the bottom of the stack are shown)
uint32_t shownPointer = 0;
public:
/// Stack of all the shapes (possibly even some which are not shown (@see shownPointer))
vec<sptr<ObstacleShape>> shapes;
/**
* Constructs an empty shape stack
*/
ObstacleShapeStack() = default;
/**
* Constructs a shape stack with given shapes in which all shapes are shown
*/
ObstacleShapeStack(const vec<sptr<ObstacleShape>> &shapes);
/**
* @return begin (bottom) iterator for the segment of shown shapes
*/
ObstacleShapeStackIterator begin();
/**
* @return end (towards top) iterator for the segment of shown shapes
*/
ObstacleShapeStackIterator end();
/**
* @return begin (bottom) const iterator for the segment of shown shapes
*/
ObstacleShapeStackConstIterator begin() const;
/**
* @return end (towards top) iterator for the segment of shown shapes
*/
ObstacleShapeStackConstIterator end() const;
/**
* Adds a shape to the stack and shows it, irreversibly removing all shapes that were in the stack but were not shown
*/
void push(const sptr<ObstacleShape> &shape);
/**
* Decrements the number of shown shapes by one, but does not irreversibly remove the now newly hidden shape.
* Does nothing if canUndo were to return false (@see canUndo).
* @see redo for the inverse operation
*/
void undo();
/**
* Increments the number of shown shapes by one by showing a shape that has previously been hidden (through undo).
* Does nothing if canRedo were to return false (@see canRedo).
* @see undo for the inverse operation
*/
void redo();
/**
* Irreversibly removes all shapes
*/
void clear();
/**
* @return true iff there is at least one shown shape, i.e., it makes sense to undo its addition
* @see undo
*/
bool canUndo() const;
/**
* @return true iff there is at least one shape present in this stack but hidden due to an earlier undo operation, i.e., it is possible to redo its addition
* @see redo
*/
bool canRedo() const;
/**
* @return true iff this stack contains at least one shape (no matter if it's hidden or shown)
*/
bool empty() const;
/**
* Applies all the shown shapes to a grid
* @param grid grid to be modified
*/
void fill(Grid<bool>& grid) const;
/**
* Sets all points of a grid based on what shapes of this stack they are contained in.
* @param grid grid to be set
* Equivalent to setting all points of the grid to false and then calling this->fill(grid)
*/
void set(Grid<bool>& grid) const;
};
/**
* Obstacle shape representing an ellipse (with axes parallel to the x and y axes)
*/
class ObstacleEllipse : public ObstacleShape
{
private:
/// Coordinates of the center of this ellipse
vec2d center;
/// Length of the semiaxis parallel to the x axis
double xhaxis;
/// Length of the semiaxis parallel to the y axis
double yhaxis;
public:
/**
* Constructs an ObstacleEllipse object representing an ellipse inscribed in a rectangle
* @param negative true iff the ellipse should be negative
* @param p0 first corner of the circumscribed rectangle
* @param p1 second corner of the circumscribed rectangle
*/
ObstacleEllipse(bool negative, const vec2d& p0, const vec2d& p1);
/**
* Constrcuts an ObstacleEllipse object given the center and semiaxis lengths
* @param negative true iff the ellipse should be negative
* @param center coordinates of the center point
* @param xhaxis length of the semiaxis parallel to the x axis
* @param yhaxis length of the semiaxis parallel to the y axis
*/
ObstacleEllipse(bool negative, const vec2d& center, double xhaxis, double yhaxis);
void draw(const Cairo::RefPtr<Cairo::Context>& cr) const override;
void fill(Grid<bool>& grid) const override;
};
/**
* Obstacle shape representing an arbitrary polygon.
* The interior of the polygon is defined by the non-zero winding rule.
*/
class ObstaclePolygon : public ObstacleShape
{
friend Tests;
private:
/// Ordered list of this polygon's vertices
vec<vec2d> ps;
/**
* Implements the non-zero winding rule
* @param p point to investigate
* @return true iff the specified point is inside the polygon
*/
bool inside(vec2d p) const;
public:
/**
* Constructs an ObstaclePolygon object
* @param negative true iff the polygon should be negative
* @param ps ordered list of the polygon's vertices
*/
ObstaclePolygon(bool negative, const vec<vec2d>& ps);
void draw(const Cairo::RefPtr<Cairo::Context>& cr) const override;
void fill(Grid<bool>& grid) const override;
};
/**
* Obstacle shape representing a rectangle with sides parallel to the x and y axes
*/
class ObstacleRectangle : public ObstaclePolygon
{
public:
/**
* Constructs an ObstacleRectangle object
* @param negative true iff the rectangle should be negative
* @param v0 coordinates of one vertex
* @param v1 coordinates of the vertex opposite to v0
*/
ObstacleRectangle(bool negative, vec2d v0, vec2d v1);
};
/**
* Obstacle shape representing a circle
*/
class ObstacleCircle : public ObstacleEllipse
{
public:
/**
* Constructs an ObstacleCircle object
* @param negative true iff the circle should be negative
* @param center coordinates of the circle center
* @param r radius of the circle
*/
ObstacleCircle(bool negative, vec2d center, double r);
/**
* Constructs an ObstacleCircle object
* @param negative true iff the circle should be negative
* @param center coordinates of the circle center
* @param v1 coordinates of some point on the boundary of the circle
* @param physW physical width of the container in which the shape is a circle (instead of a general ellipse)
* @param physH physical height of the container in which the shape is a circle (instread of a general ellipse)
*/
ObstacleCircle(bool negative, vec2d center, vec2d v1, double physW, double physH);
};
}
#endif // OBSTACLE_SHAPE_HPP | 30.31338 | 157 | 0.729121 | [
"object",
"shape",
"transform",
"solid"
] |
f051b44ec0831ab98290ba323c6f1fcb4f63a942 | 4,598 | cxx | C++ | ThirdParty/QtTesting/vtkqttesting/pqLineEditEventTranslator.cxx | brown-ccv/paraview-scalable | 64b221a540737d2ac94a120039bd8d1e661bdc8f | [
"Apache-2.0",
"BSD-3-Clause"
] | 2 | 2021-07-07T22:53:19.000Z | 2021-07-31T19:29:35.000Z | ThirdParty/QtTesting/vtkqttesting/pqLineEditEventTranslator.cxx | brown-ccv/paraview-scalable | 64b221a540737d2ac94a120039bd8d1e661bdc8f | [
"Apache-2.0",
"BSD-3-Clause"
] | 2 | 2020-11-18T16:50:34.000Z | 2022-01-21T13:31:47.000Z | ThirdParty/QtTesting/vtkqttesting/pqLineEditEventTranslator.cxx | brown-ccv/paraview-scalable | 64b221a540737d2ac94a120039bd8d1e661bdc8f | [
"Apache-2.0",
"BSD-3-Clause"
] | 5 | 2020-10-02T10:14:35.000Z | 2022-03-10T07:50:22.000Z | /*=========================================================================
Program: ParaView
Module: pqLineEditEventTranslator.cxx
Copyright (c) 2005-2008 Sandia Corporation, Kitware Inc.
All rights reserved.
ParaView is a free software; you can redistribute it and/or modify it
under the terms of the ParaView license version 1.2.
See License_v1.2.txt for the full ParaView license.
A copy of this license can be obtained by contacting
Kitware Inc.
28 Corporate Drive
Clifton Park, NY 12065
USA
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 AUTHORS 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 "pqLineEditEventTranslator.h"
#include <QDebug>
#include <QEvent>
#include <QKeyEvent>
#include <QLineEdit>
#include <QPlainTextEdit>
#include <QSpinBox>
#include <QTextDocument>
#include <QTextEdit>
#include "pqEventTypes.h"
pqLineEditEventTranslator::pqLineEditEventTranslator(QObject* p)
: pqWidgetEventTranslator(p)
{
}
bool pqLineEditEventTranslator::translateEvent(
QObject* object, QEvent* event, int eventType, bool& error)
{
QObject* tmpObject = object;
QLineEdit* leObject = qobject_cast<QLineEdit*>(object);
QTextEdit* teObject = qobject_cast<QTextEdit*>(object);
QPlainTextEdit* pteObject = qobject_cast<QPlainTextEdit*>(object);
if (!leObject && !teObject && !pteObject && object->parent() != NULL)
{
// MouseEvent can be received by viewport
tmpObject = object->parent();
leObject = qobject_cast<QLineEdit*>(tmpObject);
teObject = qobject_cast<QTextEdit*>(tmpObject);
pteObject = qobject_cast<QPlainTextEdit*>(tmpObject);
}
if (!leObject && !teObject && !pteObject)
{
return false;
}
if (eventType == pqEventTypes::ACTION_EVENT)
{
// If this line edit is part of a spinbox, don't translate events
// (the spinbox translator will receive the final value directly)
if (qobject_cast<QSpinBox*>(tmpObject->parent()))
{
return false;
}
switch (event->type())
{
case QEvent::KeyRelease:
{
QKeyEvent* ke = static_cast<QKeyEvent*>(event);
QString keyText = ke->text();
if (keyText.length() && keyText.at(0).isPrint())
{
if (leObject)
{
emit recordEvent(tmpObject, "set_string", leObject->text());
}
else if (teObject)
{
emit recordEvent(tmpObject, "set_string", teObject->document()->toPlainText());
}
else if (pteObject)
{
emit recordEvent(tmpObject, "set_string", pteObject->document()->toPlainText());
}
}
// if we record F2 event, will cause some issue with the TreeView
// Need test to know if we need to record those events
else if (ke->key() != Qt::Key_F2)
{
emit recordEvent(tmpObject, "key", QString("%1").arg(ke->key()));
}
return true;
break;
}
default:
break;
}
}
else if (eventType == pqEventTypes::CHECK_EVENT)
{
// TextEdit only, LineEdit does not need specific check
if (teObject != NULL || pteObject != NULL)
{
if (event->type() == QEvent::MouseMove)
{
return true;
}
// Clicking while checking, actual check event
if (event->type() == QEvent::MouseButtonRelease)
{
if (teObject != NULL)
{
emit this->recordEvent(teObject, "plainText", teObject->toPlainText().replace("\t", " "),
pqEventTypes::CHECK_EVENT);
}
else /* if (pteObject != NULL)*/
{
emit this->recordEvent(pteObject, "plainText",
pteObject->toPlainText().replace("\t", " "), pqEventTypes::CHECK_EVENT);
}
return true;
}
}
}
return this->Superclass::translateEvent(object, event, eventType, error);
}
| 32.380282 | 99 | 0.632449 | [
"object"
] |
f05b286ecc75ef4a0a646e674686c85e85c15e52 | 742 | cpp | C++ | Count Distinct Subsequences/code_1.cpp | Jatin-Goyal5/Data-Structures-and-Algorithms | f6bd0f77e5640c2e0568f3fffc4694758e77af96 | [
"MIT"
] | 27 | 2019-01-31T10:22:29.000Z | 2021-08-29T08:25:12.000Z | Count Distinct Subsequences/code_1.cpp | Jatin-Goyal5/Data-Structures-and-Algorithms | f6bd0f77e5640c2e0568f3fffc4694758e77af96 | [
"MIT"
] | 6 | 2020-09-30T19:01:49.000Z | 2020-12-17T15:10:54.000Z | Count Distinct Subsequences/code_1.cpp | Jatin-Goyal5/Data-Structures-and-Algorithms | f6bd0f77e5640c2e0568f3fffc4694758e77af96 | [
"MIT"
] | 27 | 2019-09-21T14:19:32.000Z | 2021-09-15T03:06:41.000Z | //
// code_1.cpp
// Algorithm
//
// Created by Mohd Shoaib Rayeen on 23/11/18.
// Copyright © 2018 Shoaib Rayeen. All rights reserved.
//
#include <iostream>
#include <vector>
#include <string>
using namespace std;
const int MAX_CHAR = 256;
int countSub(string str) {
vector<int> last(MAX_CHAR, -1);
long n = str.length();
int dp[n+1];
dp[0] = 1;
for (int i=1; i<=n; i++) {
dp[i] = 2*dp[i-1];
if (last[str[i-1]] != -1) {
dp[i] = dp[i] - dp[last[str[i-1]]];
}
last[str[i-1]] = (i-1);
}
return dp[n];
}
int main() {
string s;
cout << "\nEnter Sequence\t:\t";
cin >> s;
cout << "\nNumber of Subsequences\t:\t" << countSub(s) << endl;
return 0;
}
| 20.054054 | 67 | 0.525606 | [
"vector"
] |
f0693c269745662381c9d69e6f44514ef89a3d5e | 16,875 | cc | C++ | test/logging.cc | centreon-lab/centreon-clib | 1703b5eccea527bf5237a698a6866a152168825d | [
"Apache-2.0"
] | 6 | 2015-08-04T13:12:12.000Z | 2021-07-20T17:44:10.000Z | test/logging.cc | centreon-lab/centreon-clib | 1703b5eccea527bf5237a698a6866a152168825d | [
"Apache-2.0"
] | 16 | 2015-05-06T06:42:31.000Z | 2022-03-09T08:22:27.000Z | test/logging.cc | centreon-lab/centreon-clib | 1703b5eccea527bf5237a698a6866a152168825d | [
"Apache-2.0"
] | 6 | 2016-02-04T16:24:19.000Z | 2021-07-20T17:44:09.000Z | /*
** Copyright 2011-2020 Centreon
**
** 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.
**
** For more information : contact@centreon.com
*/
#include <gtest/gtest.h>
#include <stdio.h>
#include <fstream>
#include "backend_test.hh"
#include "com/centreon/handle_listener.hh"
#include "com/centreon/handle_manager.hh"
#include "com/centreon/io/file_stream.hh"
#include "com/centreon/logging/engine.hh"
#include "com/centreon/logging/file.hh"
#include "com/centreon/logging/temp_logger.hh"
using namespace com::centreon;
using namespace com::centreon::logging;
class listener : public handle_listener {
public:
listener() {}
~listener() throw() {}
void error(handle& h) { (void)h; }
};
static bool null_handle() {
try {
handle_manager hm;
listener l;
hm.add(NULL, &l);
} catch (std::exception const& e) {
(void)e;
return (true);
}
return (false);
}
static bool null_listener() {
try {
handle_manager hm;
io::file_stream fs;
hm.add(&fs, NULL);
} catch (std::exception const& e) {
(void)e;
return (true);
}
return (false);
}
static bool basic_add() {
try {
handle_manager hm;
io::file_stream fs(stdin);
listener l;
hm.add(&fs, &l);
} catch (std::exception const& e) {
(void)e;
return (false);
}
return (true);
}
static bool double_add() {
try {
handle_manager hm;
io::file_stream fs(stdin);
listener l;
hm.add(&fs, &l);
try {
hm.add(&fs, &l);
} catch (std::exception const& e) {
(void)e;
return (true);
}
} catch (std::exception const& e) {
(void)e;
}
return (false);
}
static bool is_same(backend const& b1, backend const& b2) {
return (b1.enable_sync() == b2.enable_sync() &&
b1.show_pid() == b2.show_pid() &&
b1.show_timestamp() == b2.show_timestamp() &&
b1.show_thread_id() == b2.show_thread_id());
}
static bool check_pid(std::string const& data, char const* msg) {
if (data[0] != '[' || data.size() < 4)
return (false);
unsigned int pid_size(
static_cast<unsigned int>(data.size() - strlen(msg) - 1 - 3));
for (unsigned int i(1); i < pid_size; ++i)
if (!isdigit(data[i]))
return (false);
if (data.compare(3 + pid_size, strlen(msg), msg))
return (false);
return (true);
}
static bool check_thread_id(std::string const& data, char const* msg) {
void* ptr(NULL);
char message[1024];
int ret(sscanf(data.c_str(), "[%p] %s\n", &ptr, message));
return (ret == 2 && !strncmp(msg, message, strlen(msg)));
}
/**
* Check time.
*
* @return True on success, otherwise false.
*/
static bool check_time(std::string const& data, char const* msg) {
if (data[0] != '[' || data.size() < 4)
return (false);
unsigned int time_size(
static_cast<unsigned int>(data.size() - strlen(msg) - 1 - 3));
for (unsigned int i(1); i < time_size; ++i)
if (!isdigit(data[i]))
return (false);
if (data.compare(3 + time_size, strlen(msg), msg))
return (false);
return (true);
}
static bool null_pointer() {
try {
engine& e(engine::instance());
e.add(NULL, 0, 0);
} catch (std::exception const& e) {
(void)e;
return (true);
}
return (false);
}
static bool check_log_message(std::string const& path, std::string const& msg) {
std::ifstream stream(path.c_str());
char buffer[1024];
stream.get(buffer, sizeof(buffer));
return (buffer == msg);
}
static bool check_log_message2(std::string const& path,
std::string const& msg) {
std::ifstream stream(path.c_str());
char buffer[32 * 1024];
memset(buffer, 0, sizeof(buffer));
stream.read(buffer, sizeof(buffer));
return buffer == msg;
}
TEST(ClibLogging, HandleManagerAdd) {
ASSERT_TRUE(null_handle());
ASSERT_TRUE(null_listener());
ASSERT_TRUE(basic_add());
ASSERT_TRUE(double_add());
}
TEST(ClibLogging, BackendCopy) {
backend_test ref(false, true, none, false);
backend_test c1(ref);
ASSERT_TRUE(is_same(ref, c1));
backend_test c2 = ref;
ASSERT_TRUE(is_same(ref, c2));
}
TEST(ClibLogging, BackendWithPid) {
static char msg[] = "Centreon Clib test";
engine& e(engine::instance());
std::unique_ptr<backend_test> obj(new backend_test(false, true, none, false));
auto id = e.add(obj.get(), 1, 0);
e.log(1, 0, msg, sizeof(msg));
ASSERT_TRUE(check_pid(obj->data(), msg));
e.remove(id);
}
TEST(ClibLogging, BackendWithThreadId) {
static char msg[] = "Centreon_Clib_test";
engine& e(engine::instance());
std::unique_ptr<backend_test> obj(new backend_test(false, false, none, true));
auto id = e.add(obj.get(), 1, 0);
e.log(1, 0, msg, sizeof(msg));
ASSERT_TRUE(check_thread_id(obj->data(), msg));
e.remove(id);
}
TEST(ClibLogging, BackendWithTimestamp) {
static char msg[] = "Centreon Clib test";
engine& e(engine::instance());
std::unique_ptr<backend_test> obj(
new backend_test(false, false, none, false));
auto id = e.add(obj.get(), 1, 0);
obj->show_timestamp(second);
e.log(1, 0, msg, sizeof(msg));
ASSERT_TRUE(check_time(obj->data(), msg));
obj->reset();
obj->show_timestamp(millisecond);
e.log(1, 0, msg, sizeof(msg));
ASSERT_TRUE(check_time(obj->data(), msg));
obj->reset();
obj->show_timestamp(microsecond);
e.log(1, 0, msg, sizeof(msg));
ASSERT_TRUE(check_time(obj->data(), msg));
obj->reset();
e.remove(id);
}
TEST(ClibLogging, EngineAdd) {
engine& e(engine::instance());
ASSERT_TRUE(null_pointer());
std::unique_ptr<backend_test> obj(new backend_test);
unsigned long id(e.add(obj.get(), 0, 0));
ASSERT_TRUE(id);
e.remove(id);
}
TEST(ClibLogging, EngineIsLog) {
engine& e(engine::instance());
std::unique_ptr<backend_test> obj(new backend_test);
unsigned int limits(sizeof(unsigned int) * CHAR_BIT);
for (unsigned int i(0); i < 3; ++i) {
for (unsigned int j(0); j < limits; ++j) {
unsigned long id(e.add(obj.get(), 1 << j, i));
for (unsigned int k(0); k < limits; ++k) {
ASSERT_EQ(e.is_log(1 << k, i), (k == j));
for (unsigned int k(0); k < 3; ++k) {
ASSERT_EQ(e.is_log(1 << j, k), (i >= k));
}
}
ASSERT_TRUE(e.remove(id));
}
}
}
TEST(ClibLogging, EngineLog) {
engine& e(engine::instance());
std::unique_ptr<backend_test> obj(new backend_test);
e.log(1, 0, NULL, 0);
unsigned int limits(sizeof(unsigned int) * CHAR_BIT);
for (unsigned int i(0); i < 3; ++i) {
for (unsigned int j(0); j < limits; ++j) {
unsigned long id(e.add(obj.get(), 1 << j, i));
for (unsigned int k(0); k < limits; ++k)
e.log(1 << k, i, "", 0);
ASSERT_TRUE(e.remove(id));
}
}
ASSERT_EQ(obj->get_nb_call(), 3 * limits);
}
TEST(ClibLogging, EngineRemoveByBackend) {
engine& e(engine::instance());
ASSERT_TRUE(null_pointer());
std::unique_ptr<backend_test> obj(new backend_test);
e.add(obj.get(), 1, 0);
ASSERT_EQ(e.remove(obj.get()), 1);
static unsigned int const nb_backend(1000);
for (unsigned int i(1); i < nb_backend; ++i)
e.add(obj.get(), i, 0);
ASSERT_EQ(e.remove(obj.get()), nb_backend - 1);
}
TEST(ClibLogging, EngineRemoveById) {
engine& e(engine::instance());
ASSERT_FALSE(e.remove(1));
ASSERT_FALSE(e.remove(42));
std::unique_ptr<backend_test> obj(new backend_test);
unsigned long id(e.add(obj.get(), 1, 0));
ASSERT_TRUE(e.remove(id));
}
TEST(ClibLogging, EngineWithThread) {
static uint32_t const nb_writter(10);
engine& e(engine::instance());
std::unique_ptr<backend_test> obj(new backend_test);
auto id = e.add(obj.get(), 1, 0);
std::vector<std::thread> threads;
for (uint32_t i = 0; i < nb_writter; ++i)
threads.push_back(std::thread([]() {
engine& e(engine::instance());
for (uint32_t i = 0; i < nb_writter; ++i) {
std::ostringstream oss;
oss << std::this_thread::get_id() << ":" << i;
e.log(1, 0, oss.str().c_str(), oss.str().size());
}
}));
for (auto& t : threads)
t.join();
for (uint32_t i(0); i < nb_writter; ++i) {
for (uint32_t j(0); j < nb_writter; ++j) {
std::ostringstream oss;
oss << &threads[i] << ":" << j << "\n";
ASSERT_TRUE(obj->data().find(oss.str()));
}
}
e.remove(id);
}
TEST(ClibLogging, FileLog) {
static char msg[] = "Centreon Clib test";
char* tmp(com::centreon::io::file_stream::temp_path());
{
file f(tmp, false, false, none, false);
f.log(1, 0, msg, sizeof(msg));
}
ASSERT_TRUE(check_log_message(tmp, msg));
{
FILE* out(NULL);
ASSERT_TRUE((out = fopen(tmp, "w")));
file f(out, false, false, none, false);
f.log(1, 0, msg, sizeof(msg));
}
ASSERT_TRUE(check_log_message(tmp, msg));
}
TEST(ClibLogging, FileLogMultiline) {
static unsigned int const nb_line(1024);
char* tmpfile(com::centreon::io::file_stream::temp_path());
std::ostringstream tmp;
std::ostringstream tmpref;
for (unsigned int i(0); i < nb_line; ++i) {
tmp << i << "\n";
tmpref << "[" << std::this_thread::get_id() << "] " << i << "\n";
}
std::string msg(tmp.str());
std::string ref(tmpref.str());
{
file f(tmpfile, false, false, none, true);
f.log(1, 0, msg.c_str(), msg.size());
}
ASSERT_TRUE(check_log_message2(tmpfile, ref));
}
TEST(ClibLogging, TempLoggerCtor) {
engine& e(engine::instance());
std::unique_ptr<backend_test> obj(new backend_test);
auto id = e.add(obj.get(), 3, 0);
temp_logger(0, 0) << "Centreon Clib test";
ASSERT_EQ(obj->get_nb_call(), 0);
temp_logger(1, 0) << "Centreon Clib test";
ASSERT_EQ(obj->get_nb_call(), 1);
e.remove(id);
}
TEST(ClibLogging, TempLoggerCopy) {
engine& e(engine::instance());
std::unique_ptr<backend_test> obj(new backend_test);
auto id = e.add(obj.get(), 3, 0);
temp_logger tmp(1, 0);
tmp << "Centreon Clib test";
temp_logger(tmp) << " copy";
ASSERT_NE(obj->data().find("copy"), std::string::npos);
e.remove(id);
}
TEST(ClibLogging, TempLoggerDoNothingChar) {
engine& e(engine::instance());
std::unique_ptr<backend_test> obj(new backend_test);
auto id = e.add(obj.get(), 2, 0);
temp_logger(1, 2) << 'c';
ASSERT_FALSE(obj->get_nb_call());
e.remove(id);
}
TEST(ClibLogging, TempLoggerDoNothingDouble) {
engine& e(engine::instance());
std::unique_ptr<backend_test> obj(new backend_test);
auto id = e.add(obj.get(), 2, 0);
temp_logger(1, 2) << double(42.42);
ASSERT_FALSE(obj->get_nb_call());
e.remove(id);
}
TEST(ClibLogging, TempLoggerDoNothingInt) {
engine& e(engine::instance());
std::unique_ptr<backend_test> obj(new backend_test);
auto id = e.add(obj.get(), 2, 0);
temp_logger(1, 2) << int(42);
ASSERT_FALSE(obj->get_nb_call());
e.remove(id);
}
TEST(ClibLogging, TempLoggerDoNothingLong) {
engine& e(engine::instance());
std::unique_ptr<backend_test> obj(new backend_test);
auto id = e.add(obj.get(), 2, 0);
temp_logger(1, 2) << 42L;
ASSERT_FALSE(obj->get_nb_call());
e.remove(id);
}
TEST(ClibLogging, TempLoggerDoNothingLongLong) {
engine& e(engine::instance());
std::unique_ptr<backend_test> obj(new backend_test);
auto id = e.add(obj.get(), 2, 0);
temp_logger(1, 2) << 42LL;
ASSERT_FALSE(obj->get_nb_call());
e.remove(id);
}
TEST(ClibLogging, TempLoggerDoNothingPVoid) {
engine& e(engine::instance());
std::unique_ptr<backend_test> obj(new backend_test);
auto id = e.add(obj.get(), 2, 0);
temp_logger(1, 2) << obj.get();
ASSERT_FALSE(obj->get_nb_call());
e.remove(id);
}
TEST(ClibLogging, TempLoggerDoNothingStdString) {
engine& e(engine::instance());
std::unique_ptr<backend_test> obj(new backend_test);
auto id = e.add(obj.get(), 2, 0);
temp_logger(1, 2) << std::string("Centreon Clib test");
ASSERT_FALSE(obj->get_nb_call());
e.remove(id);
}
TEST(ClibLogging, TempLoggerDoNothingString) {
engine& e(engine::instance());
std::unique_ptr<backend_test> obj(new backend_test);
auto id = e.add(obj.get(), 2, 0);
temp_logger(1, 2) << "Centreon Clib test";
ASSERT_FALSE(obj->get_nb_call());
e.remove(id);
}
TEST(ClibLogging, TempLoggerDoNothingUint) {
engine& e(engine::instance());
std::unique_ptr<backend_test> obj(new backend_test);
auto id = e.add(obj.get(), 2, 0);
unsigned int ui(42);
temp_logger(1, 2) << ui;
ASSERT_FALSE(obj->get_nb_call());
e.remove(id);
}
TEST(ClibLogging, TempLoggerDoNothingULong) {
engine& e(engine::instance());
std::unique_ptr<backend_test> obj(new backend_test);
auto id = e.add(obj.get(), 2, 0);
unsigned long ul(42);
temp_logger(1, 2) << ul;
ASSERT_FALSE(obj->get_nb_call());
e.remove(id);
}
TEST(ClibLogging, TempLoggerDoNothingULongLong) {
engine& e(engine::instance());
std::unique_ptr<backend_test> obj(new backend_test);
auto id = e.add(obj.get(), 2, 0);
unsigned long long ull(42);
temp_logger(1, 2) << ull;
ASSERT_FALSE(obj->get_nb_call());
e.remove(id);
}
TEST(ClibLogging, TempLoggerLogChar) {
engine& e(engine::instance());
std::unique_ptr<backend_test> obj(new backend_test);
auto id = e.add(obj.get(), 3, 0);
temp_logger(1, 0) << 'c';
ASSERT_EQ(obj->get_nb_call(), 1);
e.remove(id);
}
TEST(ClibLogging, TempLoggerLogDouble) {
engine& e(engine::instance());
std::unique_ptr<backend_test> obj(new backend_test);
auto id = e.add(obj.get(), 3, 0);
temp_logger(1, 0) << double(42.42);
ASSERT_EQ(obj->get_nb_call(), 1);
e.remove(id);
}
TEST(ClibLogging, TempLoggerLogInt) {
engine& e(engine::instance());
std::unique_ptr<backend_test> obj(new backend_test);
auto id = e.add(obj.get(), 3, 0);
temp_logger(1, 0) << int(42);
ASSERT_EQ(obj->get_nb_call(), 1);
e.remove(id);
}
TEST(ClibLogging, TempLoggerLogLong) {
engine& e(engine::instance());
std::unique_ptr<backend_test> obj(new backend_test);
auto id = e.add(obj.get(), 3, 0);
temp_logger(1, 0) << 42L;
ASSERT_EQ(obj->get_nb_call(), 1);
e.remove(id);
}
TEST(ClibLogging, TempLoggerLogLongLong) {
engine& e(engine::instance());
std::unique_ptr<backend_test> obj(new backend_test);
auto id = e.add(obj.get(), 3, 0);
temp_logger(1, 0) << 42LL;
ASSERT_EQ(obj->get_nb_call(), 1);
e.remove(id);
}
TEST(ClibLogging, TempLoggerLogPVoid) {
engine& e(engine::instance());
std::unique_ptr<backend_test> obj(new backend_test);
auto id = e.add(obj.get(), 3, 0);
temp_logger(1, 0) << obj.get();
ASSERT_EQ(obj->get_nb_call(), 1);
e.remove(id);
}
TEST(ClibLogging, TempLoggerLogStdString) {
engine& e(engine::instance());
std::unique_ptr<backend_test> obj(new backend_test);
auto id = e.add(obj.get(), 3, 0);
temp_logger(1, 0) << std::string("Centreon Clib test");
ASSERT_EQ(obj->get_nb_call(), 1);
e.remove(id);
}
TEST(ClibLogging, TempLoggerLogString) {
engine& e(engine::instance());
std::unique_ptr<backend_test> obj(new backend_test);
auto id = e.add(obj.get(), 3, 0);
temp_logger(1, 0) << "Centreon Clib test";
ASSERT_EQ(obj->get_nb_call(), 1);
e.remove(id);
}
TEST(ClibLogging, TempLoggerLogUint) {
engine& e(engine::instance());
std::unique_ptr<backend_test> obj(new backend_test);
auto id = e.add(obj.get(), 3, 0);
unsigned int ui(42);
temp_logger(1, 0) << ui;
ASSERT_EQ(obj->get_nb_call(), 1);
e.remove(id);
}
TEST(ClibLogging, TempLoggerLogULong) {
engine& e(engine::instance());
std::unique_ptr<backend_test> obj(new backend_test);
auto id = e.add(obj.get(), 3, 0);
unsigned long ul(42);
temp_logger(1, 0) << ul;
ASSERT_EQ(obj->get_nb_call(), 1);
e.remove(id);
}
TEST(ClibLogging, TempLoggerLogULongLong) {
engine& e(engine::instance());
std::unique_ptr<backend_test> obj(new backend_test);
auto id = e.add(obj.get(), 3, 0);
unsigned long long ull(42);
temp_logger(1, 0) << ull;
ASSERT_EQ(obj->get_nb_call(), 1);
e.remove(id);
} | 26.700949 | 81 | 0.617956 | [
"vector"
] |
f06a0327ff450c381910ea75dd126d59e644e2c5 | 1,490 | hpp | C++ | practices/20211007/members.hpp | liff-engineer/articles | ad3386ef9cda5083793f485e309a9f85ab36f664 | [
"MIT"
] | 2 | 2020-12-01T06:44:41.000Z | 2021-11-22T06:07:52.000Z | practices/20211007/members.hpp | liff-engineer/articles | ad3386ef9cda5083793f485e309a9f85ab36f664 | [
"MIT"
] | null | null | null | practices/20211007/members.hpp | liff-engineer/articles | ad3386ef9cda5083793f485e309a9f85ab36f664 | [
"MIT"
] | null | null | null | #pragma once
#include <type_traits>
namespace abc {
namespace detail {
template<typename T>
struct member_helper : std::false_type {};
template<typename T, typename R>
struct member_helper<R T::*> : std::is_member_object_pointer<R T::*> {
using type = T;
using member_type = R;
};
}
template<typename T, typename R, R T::* M>
struct member {
static constexpr auto mp = M;
const char* name;
std::size_t offset;
};
#ifdef __cpp_nontype_template_parameter_auto
template<auto m>
constexpr auto make_member(const char* name, std::size_t offset) {
using helper = detail::member_helper<decltype(m)>;
static_assert(helper::value, "is't member object pointer");
return member<helper::type, helper::member_type, m>{name, offset};
}
#else
template<typename M, M m>
constexpr auto make_member(const char* name, std::size_t offset) {
using helper = detail::member_helper<M>;
static_assert(helper::value, "is't member object pointer");
return member<helper::type, helper::member_type, m>{name, offset};
}
#endif
template<typename T, typename E = void>
struct members :std::false_type {};
}
#ifdef __cpp_nontype_template_parameter_auto
#define ABC_MAKE_MEMBER(s,m) abc::make_member<&s::m>(#m,offsetof(s,m))
#else
#define ABC_MAKE_MEMBER(s,m) abc::make_member<decltype(&s::m),&s::m>(#m,offsetof(s,m))
#endif
| 31.041667 | 88 | 0.64698 | [
"object"
] |
f06d7590d75c6f3a0d8586a053435707626234be | 22,972 | cpp | C++ | src/Engine/text/TextWindow.cpp | mpavlinsky/bobsgame | dd4c0713828594ef601c61785164b3fa41e27e2a | [
"Unlicense"
] | 13 | 2021-06-30T15:47:33.000Z | 2021-09-18T15:44:34.000Z | src/Engine/text/TextWindow.cpp | mpavlinsky/bobsgame | dd4c0713828594ef601c61785164b3fa41e27e2a | [
"Unlicense"
] | null | null | null | src/Engine/text/TextWindow.cpp | mpavlinsky/bobsgame | dd4c0713828594ef601c61785164b3fa41e27e2a | [
"Unlicense"
] | 7 | 2021-06-30T17:14:41.000Z | 2021-10-14T01:41:18.000Z |
#include "stdafx.h"
//------------------------------------------------------------------------------
//Copyright Robert Pelloni.
//All Rights Reserved.
//------------------------------------------------------------------------------
//#pragma once
Logger TextWindow::log = Logger("TextWindow");
//=========================================================================================================================
TextWindow::TextWindow(Engine* g)
{//=========================================================================================================================
this->e = g;
borderTexture = GLUtils::getTextureFromPNG("data/textbox/border.png");
scrollPercent = 0;
}
//=========================================================================================================================
void TextWindow::init()
{//=========================================================================================================================
if (spriteWindowEntity != nullptr)
{
delete spriteWindowEntity;
spriteWindowEntity = nullptr;
}
if (textBoxTextureByteArray != nullptr)
{
delete[] textBoxTextureByteArray;
textBoxTextureByteArray = nullptr;
}
textBoxTextureByteArray = new u8[getTextManager()->pow2TexWidth * getTextManager()->pow2TexHeight * 4];
// for(int i=0;i<getTextManager()->textureWidth*getTextManager()->textureHeight;i++)
// {
// textBoxTextureByteArray[(i*4)+0]=(byte)0;
// textBoxTextureByteArray[(i*4)+1]=(byte)0;
// textBoxTextureByteArray[(i*4)+2]=(byte)0;
// textBoxTextureByteArray[(i*4)+3]=(byte)0;
// }
clearByteArray();
textBoxTexture = GLUtils::getTextureFromData("textBox", getTextManager()->pow2TexWidth, getTextManager()->pow2TexHeight, textBoxTextureByteArray);
// ----------------------------
// sprite window
// ----------------------------
if (spriteWindowTextureByteArray != nullptr)
{
delete[] spriteWindowTextureByteArray;
spriteWindowTextureByteArray = nullptr;
}
spriteWindowTextureByteArray = new u8[((64) * (64)) * 4];
for (int i = 0; i < (64) * (64); i++)
{
spriteWindowTextureByteArray[(i * 4) + 0] = 0;
spriteWindowTextureByteArray[(i * 4) + 1] = 0;
spriteWindowTextureByteArray[(i * 4) + 2] = 0;
spriteWindowTextureByteArray[(i * 4) + 3] = 255;
}
spriteBoxTexture = GLUtils::getTextureFromData("spriteWindow", 64, 64, spriteWindowTextureByteArray);
}
void TextWindow::render()
{ // =========================================================================================================================
//render getText window at 25% screen height, let's make "scroll in" a float where 1.0 is height + 16px or whatever
int screenWidth = (int)(getEngine()->getWidth());
int screenHeight = (int)(getEngine()->getHeight());
float scaledTextWindowHeight = screenHeight * 0.15f; //not including borders!
float widthToHeightRatio = (float)(getTextManager()->width) / (float)(getTextManager()->height);
float scaledTextWindowWidth = scaledTextWindowHeight * widthToHeightRatio;
float heightScale = scaledTextWindowHeight / (float)(getTextManager()->height);
float widthScale = scaledTextWindowWidth / (float)(getTextManager()->width);
float scaledSpriteWindowWidth = getTextManager()->spriteWindowWidth * widthScale;
float borderWidth = 10;
float scaledBorderWidth = borderWidth * widthScale;
float borderHeight = 16;
float scaledBorderHeight = borderHeight * heightScale;
float totalScaledWidth = scaledTextWindowWidth + scaledSpriteWindowWidth + scaledBorderWidth * 3;
float totalScaledHeight = scaledTextWindowHeight + scaledBorderHeight * 2;
if (totalScaledWidth > getEngine()->getWidth() * 0.90f)
{
//getScale width to 90%
//getScale height from that
scaledTextWindowWidth = (float)(getEngine()->getWidth() * 0.75f);
widthScale = scaledTextWindowWidth / (float)(getTextManager()->width);
scaledSpriteWindowWidth = getTextManager()->spriteWindowWidth * widthScale;
//float heightToWidthRatio = (float)(getTextManager()->height) / (float)(getTextManager()->width);
scaledTextWindowHeight = scaledTextWindowWidth / widthToHeightRatio;
heightScale = scaledTextWindowHeight / (float)(getTextManager()->height);
scaledBorderWidth = borderWidth * widthScale;
scaledBorderHeight = borderHeight * heightScale;
totalScaledWidth = scaledTextWindowWidth + scaledSpriteWindowWidth + scaledBorderWidth * 3;
totalScaledHeight = scaledTextWindowHeight + scaledBorderHeight * 2;
}
float tx0 = 0.0f;
float tx1 = 1.0f;
float ty0 = 0.0f;
float ty1 = 1.0f;
float x0 = 0;
float x1 = 0;
float y0 = 0;
float y1 = 0;
float y = 0;
//scroll from bottom
float startScrollPosition = (float)getEngine()->getHeight();
float finalScrollPosition = getEngine()->getHeight() - totalScaledHeight - 16;
if (this == getTextManager()->textBox->get(1))
{
//scroll from top
startScrollPosition = (float)0 - totalScaledHeight;
finalScrollPosition = (float)0 + StatusBar::sizeY + 16;
}
y = (startScrollPosition + (finalScrollPosition - startScrollPosition) * scrollPercent) + shakeY;
float x = ((screenWidth - totalScaledWidth) / 2) + shakeX;
// -----------------------
// border
// ----------------------
tx0 = 0.0f; // 672 x 160
tx1 = 672.0f / borderTexture->getTextureWidth();
ty0 = 0.0f;
ty1 = 160.0f / borderTexture->getTextureHeight();
// x0=(int)((getScreenX)-(getTextManager()->spriteWindowWidth))-16;
// x1=(int)(getScreenX)+(getTextManager()->textWindowWidth)+16;
// y0=(int)(getScreenY-16);
// y1=(int)(getScreenY)+(getTextManager()->textWindowHeight)+16;
x0 = x;
x1 = x0 + totalScaledWidth;
y0 = y;
y1 = y0 + totalScaledHeight;
GLUtils::drawTexture(borderTexture, tx0, tx1, ty0, ty1, x0, x1, y0, y1, alpha, GLUtils::FILTER_NEAREST);
// ------------------
// getText box itself
// ------------------
tx0 = 0.0f;
tx1 = (float)(textBoxTexture->getImageWidth()) / (float)(textBoxTexture->getTextureWidth());
ty0 = 0.0f;
ty1 = (float)(textBoxTexture->getImageHeight()) / (float)(textBoxTexture->getTextureHeight());
// x0=(int)(getScreenX);
// x1=(int)((getScreenX)+(getTextManager()->textWindowWidth));
// y0=(int)(getScreenY);
// y1=(int)((getScreenY)+(getTextManager()->textWindowHeight));
x0 = x + scaledBorderWidth + scaledSpriteWindowWidth + scaledBorderWidth;
x1 = x0 + scaledTextWindowWidth;
y0 = y + scaledBorderHeight;
y1 = y0 + scaledTextWindowHeight;
GLUtils::drawTexture(textBoxTexture, tx0, tx1, ty0, ty1, x0, x1, y0, y1, alpha, GLUtils::FILTER_LINEAR);
// -----------------------
// sprite window
// ----------------------
/*
* spriteBoxTexture.bind();
* tx0 = 0.0f;
* tx1 = 1.0f;
* ty0 = 0.0f;
* ty1 = 1.0f;
* x0 = (int)((screen_x)-(64*2));
* x1 = (int)(screen_x);
* y0 = (int)(screen_y);
* y1 = (int)((screen_y)+(G.textManager.size_y));
* draw_texture(tx0, tx1, ty0, ty1, x0, x1, y0, y1);
*/
// ----------------------
// sprite window sprite
// ----------------------
tx0 = 0.0f;
tx1 = 1.0f;
ty0 = 0.0f;
ty1 = 1.0f;
// x0=(int)((getScreenX)-((64*2)));
// x1=(int)(getScreenX);
// y0=(int)(getScreenY);
// y1=(int)((getScreenY)+(64*2));
x0 = x + scaledBorderWidth;
x1 = x0 + scaledSpriteWindowWidth;
y0 = y + scaledBorderHeight;
y1 = y0 + scaledTextWindowHeight;
// if(sprite_window_gfx==null)sprite_window_gfx = TM.questionMarkTexture;
GLUtils::drawTexture(spriteBoxTexture, tx0, tx1, ty0, ty1, x0, x1, y0, y1, alpha, GLUtils::FILTER_NEAREST);
// ----------------------
// label underneath sprite window
// ----------------------
/*
* if(sprite_window_npc==null)
* {
* sprite_window_npc = G.cameraman;
* }
* else
* {
* label = sprite_window_npc.name;
* }
* if(sprite_window_npc==G.cameraman)
* {
* label = "???";
* }
*/
//getTextManager()->ttfFont.drawString(x0+48,y1+10-6,label,Color.white);//TODO
if (this == getTextManager()->textBox->get(getTextManager()->selectedTextbox))
{
tx0 = 0.0f;
tx1 = 1.0f;
ty0 = 0.0f;
ty1 = 1.0f;
x0 = x + scaledBorderWidth + scaledSpriteWindowWidth + scaledBorderWidth + scaledTextWindowWidth;
x1 = x0 + 16;
y0 = y + scaledBorderHeight + scaledTextWindowHeight;
//if(getTextManager()->buttonIconUpDownToggle)y0-=1;
y1 = y0 + 16;
getTextManager()->actionIconScreenSprite->setX(x0 - 36);
getTextManager()->actionIconScreenSprite->setY(y0 - 20);
//GLUtils.drawTexture(spriteBoxTexture,tx0,tx1,ty0,ty1,x0,x1,y0,y1,alpha,GLUtils.FILTER_NEAREST);
}
}
void TextWindow::updateSpriteWindowTexture()
{ // =========================================================================================================================
u8* oldtex = spriteWindowTexture->getTextureData();
int size_x = spriteWindowTexture->getTextureWidth();
int size_y = spriteWindowTexture->getTextureHeight();
// go through sprite texture data, which should be 32 x 64 or 32 x 32
// find top pixel by shooting rays down from top to bottom for 0-32
int top_filled_pixel = size_y;
for (int x = 0; x < 32; x++)
{
for (int y = 0; y < size_y; y++)
{
// skip checking y values lower than the previous known top pixel, dont need them
if (y >= top_filled_pixel)
{
break;
}
if (oldtex[((size_x * y) + x) * 4 + 0] != static_cast<char>(0) || oldtex[((size_x * y) + x) * 4 + 1] != static_cast<char>(0) || oldtex[((size_x * y) + x) * 4 + 2] != static_cast<char>(0)) // b - g - r
{
if (y < top_filled_pixel)
{
top_filled_pixel = y;
}
break;
}
}
}
// make 64 * 64 pixel box
u8* newtex = new u8[64 * 64 * 4];
// fill with transparent
for (int i = 0; i < 64 * 64 * 4; i++)
{
newtex[i] = static_cast<char>(0);
}
// take 32 x 32 pixels starting at line *above* top pixel (so there is one empty line), draw them float sized into 64 * 64 box
// if (top pixel-1) + 32 is more than bottom, break and leave transparent.
for (int y = top_filled_pixel; y < top_filled_pixel + 31 && y < size_y; y++)
{
for (int x = 0; x < 32; x++)
{
char r = oldtex[((size_x * y) + x) * 4 + 0];
char g = oldtex[((size_x * y) + x) * 4 + 1];
char b = oldtex[((size_x * y) + x) * 4 + 2];
char a = oldtex[((size_x * y) + x) * 4 + 3];
for (int xx = 0; xx < 2; xx++)
{
for (int yy = 0; yy < 2; yy++)
{
int newy = (y + 1) - top_filled_pixel;
newtex[(((64 * (((newy) * 2) + yy)) + ((x * 2) + xx)) * 4) + 0] = r;
newtex[(((64 * (((newy) * 2) + yy)) + ((x * 2) + xx)) * 4) + 1] = g;
newtex[(((64 * (((newy) * 2) + yy)) + ((x * 2) + xx)) * 4) + 2] = b;
newtex[(((64 * (((newy) * 2) + yy)) + ((x * 2) + xx)) * 4) + 3] = a;
}
}
}
}
// go through each pixel
// if a pixel isn't transparent and isn't completely white (so it ignores already-outlined areas)
// if the surrounding pixels are transparent, set it to white.
for (int t = 127 - 32; t >= 0; t -= 16)
{
for (int x = 0; x < 64; x++)
{
for (int y = 0; y < 64; y++)
{
if (newtex[((64 * y) + x) * 4 + 3] != static_cast<char>(0) && (newtex[((64 * y) + x) * 4 + 0] != static_cast<char>(t) || newtex[((64 * y) + x) * 4 + 1] != static_cast<char>(t) || newtex[((64 * y) + x) * 4 + 2] != static_cast<char>(t))) // b - g - r
{
for (int i = 0; i < 8; i++)
{
int xx = 0;
int yy = 0;
if (i == 0)
{
xx = -1;
yy = 0;
}
if (i == 1)
{
xx = 1;
yy = 0;
}
if (i == 2)
{
xx = 0;
yy = -1;
}
if (i == 3)
{
xx = 0;
yy = 1;
}
if (i == 4)
{
xx = -1;
yy = 1;
}
if (i == 5)
{
xx = 1;
yy = -1;
}
if (i == 6)
{
xx = -1;
yy = -1;
}
if (i == 7)
{
xx = 1;
yy = 1;
}
if (y + yy >= 0 && y + yy < 64 && x + xx >= 0 && x + xx < 64)
{
if (newtex[((64 * (y + yy)) + (x + xx)) * 4 + 3] == static_cast<char>(0))
{
newtex[((64 * (y + yy)) + (x + xx)) * 4 + 0] = static_cast<char>(t);
newtex[((64 * (y + yy)) + (x + xx)) * 4 + 1] = static_cast<char>(t);
newtex[((64 * (y + yy)) + (x + xx)) * 4 + 2] = static_cast<char>(t);
newtex[((64 * (y + yy)) + (x + xx)) * 4 + 3] = static_cast<char>(t);
}
}
}
}
}
}
}
// make texture from new 64*64 array
delete [] spriteWindowTextureByteArray;
spriteWindowTextureByteArray = newtex;
spriteBoxTexture->release();
spriteBoxTexture = GLUtils::getTextureFromData("spriteWindow", 64, 64, spriteWindowTextureByteArray);
/*
* int textureHandle = spriteBoxTexture.getTextureID();
* glBindTexture(GL_TEXTURE_2D,textureHandle);
* glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
* glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
* glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); //GL11.GL_NEAREST);
* glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); //GL11.GL_NEAREST);
* glTexImage2D(GL_TEXTURE_2D, //type of texture we're creating
* 0, //level-of-detail: use 0
* GL_RGBA, //texture pixel format
* 64, 64, //width and height of texture image (powers of 2)
* 0, //width of the border (either 0 or 1, use 0)
* GL_RGBA, //image pixel format
* GL_UNSIGNED_BYTE, //image pixel data type
* spriteWindowTexturePixelsByteBuffer//image pixel data
* );
*/
}
void TextWindow::setSpriteWindow(Entity* entity, BobTexture* texture, const string& newLabel)
{ // =========================================================================================================================
if (entity != nullptr || texture != nullptr)
{
// if no texture is input, just take it from the entity
if (entity != nullptr && texture == nullptr)
{
voicePitch = entity->getVoicePitch();
if ((dynamic_cast<Player*>(entity) != NULL))
{
texture = (static_cast<Player*>(entity))->uniqueTexture;
}
if ((dynamic_cast<RandomCharacter*>(entity) != NULL))
{
texture = (static_cast<RandomCharacter*>(entity))->uniqueTexture;
}
if (texture == nullptr && entity->sprite != nullptr)
{
texture = entity->sprite->texture;
}
if (texture == nullptr || texture == GLUtils::blankTexture)
{
texture = TextManager::questionMarkTexture;
}
if (newLabel == "")
{
if (entity != nullptr)
{
if (entity->sprite != nullptr)
{
label = entity->sprite->getDisplayName();
}
}
}
else
{
label = newLabel;
}
}
// if there isn't an entity, stay on camera. this way just putting in a gfx works, but the camera won't try to move
if (entity == nullptr)
{
entity = getCameraman();
voicePitch = 0;
if (newLabel != "")
{
label = newLabel;
}
else
{
label = "???";
}
}
// else, follow npc and use gfx for sprite window :)
spriteWindowEntity = entity; // TODO: each npc should have a voice pitch!!!
spriteWindowTexture = texture;
// if(TM.GLOBAL_text_engine_state!=TM.CLOSED)
// {
updateSpriteWindowTexture();
// }
}
else
{
string e = "Tried to update sprite window with both npc and gfx null.";
Console::error(e);
log.error(e);
}
}
void TextWindow::updateTextureFromByteArray()
{ // =========================================================================================================================
if (redraw == true)
{
// TODO: it might actually be more efficient to overwrite the previous texture, the way i had it before, instead of releasing and recreating.
textBoxTexture->release();
textBoxTexture = GLUtils::getTextureFromData("textBox", getTextManager()->pow2TexWidth, getTextManager()->pow2TexHeight, textBoxTextureByteArray);
redraw = false;
}
}
void TextWindow::clearByteArray()
{ // =========================================================================================================================
for (int x = 0; x < getTextManager()->pow2TexWidth; x++)
{
for (int y = 0; y < getTextManager()->pow2TexHeight; y++)
{
textBoxTextureByteArray[((x + (y * getTextManager()->pow2TexWidth)) * 4) + 0] = 0;
textBoxTextureByteArray[((x + (y * getTextManager()->pow2TexWidth)) * 4) + 1] = 0;
textBoxTextureByteArray[((x + (y * getTextManager()->pow2TexWidth)) * 4) + 2] = 0;
textBoxTextureByteArray[((x + (y * getTextManager()->pow2TexWidth)) * 4) + 3] = 0;
if (x < getTextManager()->width && y < getTextManager()->height)
{
textBoxTextureByteArray[((x + (y * getTextManager()->pow2TexWidth)) * 4) + 3] = 255;
}
}
}
}
int TextWindow::getPixelValue(int letter_index, int y, int x_in_letter, bool blank)
{ // =========================================================================================================================
if (blank == true)
{
return 0;
}
int index = BobFont::getFontPixelValueAtIndex((letter_index * getTextManager()->font->blockHeight * getTextManager()->font->blockWidth) + (y * getTextManager()->font->blockWidth) + x_in_letter, getTextManager()->font);
return index;
}
void TextWindow::setPixel(int index, BobColor* c)
{ // =========================================================================================================================
textBoxTextureByteArray[index + 0] = static_cast<char>(c->ri());
textBoxTextureByteArray[index + 1] = static_cast<char>(c->gi());
textBoxTextureByteArray[index + 2] = static_cast<char>(c->bi());
textBoxTextureByteArray[index + 3] = static_cast<char>(c->ai()); // was 255
}
u8* BobFont::font_Palette_ByteArray;
void TextWindow::drawColumn(int letter_index, int x_in_letter, bool blank)
{ // =========================================================================================================================
int y = 0;
int h = getTextManager()->font->maxCharHeight;
bool draw2X = true;
if (h > 12)
{
draw2X = false;
}
int lineHeight = 12;
if (draw2X == false)
{
lineHeight = 24; // because the font is float, we don't need to draw at 2x
}
for (y = 0; y < lineHeight && y < h; y++)
{
int index = getPixelValue(letter_index, y, x_in_letter, blank);
if (index != 0)
{
BobColor* pixelColor = getTextManager()->textColor;
if (index == 0)
{
pixelColor = getTextManager()->textBGColor;
}
if (index == 1)
{
pixelColor = getTextManager()->textColor;
}
if (index == 2)
{
pixelColor = getTextManager()->textAAColor;
}
if (index == 3)
{
pixelColor = getTextManager()->textShadowColor;
}
if (index > 2)
{
// get the gray color from the getText palette
int byte1 = (int)(BobFont::font_Palette_ByteArray[index * 2 + 0] & 255);
//int byte2 = (int)(BobFont::font_Palette_ByteArray[index * 2 + 1] & 255);
//int abgr1555 = (byte2 << 8) + byte1;
int r = 255 - (int)((((byte1 & 31)) / 32.0f) * 255.0f);
// int r = 255-(int)((((byte1&0b00011111))/32.0f)*255.0f);
// Color gray = new Color(b,b,b);
// now r is the gray value (since r=g=b)
int a = r; // gray.getRed();
if (a < 0)
{
a = 0;
}
pixelColor = new BobColor(pixelColor->ri(), pixelColor->gi(), pixelColor->bi(), a);
}
if (index == 1 && y < h * 0.75f)
{
int r = (int)(min(255,(int)(pixelColor->ri() + (((float)(h - y) / (float)(h))*255.0f))));
int g = (int)(min(255,(int)(pixelColor->gi() + (((float)(h - y) / (float)(h))*255.0f))));
int b = (int)(min(255,(int)(pixelColor->bi() + (((float)(h - y) / (float)(h))*255.0f))));
pixelColor = new BobColor(r, g, b);
}
if (draw2X)
{
// draw each pixel 4 times (2x getScale)
for (int yy = 0; yy < 2; yy++)
{
for (int xx = 0; xx < 2; xx++)
{
setPixel((getTextManager()->pow2TexWidth * 4 * line * lineHeight * 2) + (((getTextManager()->pow2TexWidth * ((y * 2) + yy)) + ((xInLine * 2) + xx)) * 4), pixelColor);
}
}
}
else
{
setPixel((getTextManager()->pow2TexWidth * 4 * line * lineHeight) + (((getTextManager()->pow2TexWidth * ((y))) + ((xInLine))) * 4), pixelColor);
}
}
// do shadow
// if this value is 1 and the value of x_in_letter+1 is 0, set x_in_letter+1 to 3
if (index == 1)
{
BobColor* shadowColor = getTextManager()->textShadowColor;
if (draw2X)
{
if (getPixelValue(letter_index, y, x_in_letter + 1, blank) == 0)
{
for (int yy = 0; yy < 2; yy++)
{
for (int xx = 0; xx < 2; xx++)
{
setPixel((getTextManager()->pow2TexWidth * 4 * line * lineHeight) + (((getTextManager()->pow2TexWidth * ((y) + yy)) + (((xInLine + 1)) + xx)) * 4), shadowColor);
}
}
}
if (getPixelValue(letter_index, y + 1, x_in_letter, blank) == 0)
{
for (int yy = 0; yy < 2; yy++)
{
for (int xx = 0; xx < 2; xx++)
{
setPixel((getTextManager()->pow2TexWidth * 4 * line * lineHeight) + (((getTextManager()->pow2TexWidth * (((y + 1)) + yy)) + (((xInLine)) + xx)) * 4), shadowColor);
}
}
}
if (getPixelValue(letter_index, y + 1, x_in_letter + 1, blank) == 0)
{
for (int yy = 0; yy < 2; yy++)
{
for (int xx = 0; xx < 2; xx++)
{
setPixel((getTextManager()->pow2TexWidth * 4 * line * lineHeight) + (((getTextManager()->pow2TexWidth * (((y + 1)) + yy)) + (((xInLine + 1)) + xx)) * 4), shadowColor);
}
}
}
}
else
{
if (getPixelValue(letter_index, y, x_in_letter + 1, blank) == 0)
{
for (int yy = 0; yy < 2; yy++)
{
for (int xx = 0; xx < 2; xx++)
{
setPixel((getTextManager()->pow2TexWidth * 4 * line * lineHeight) + (((getTextManager()->pow2TexWidth * ((y) + yy)) + (((xInLine + 1)) + xx)) * 4), shadowColor);
}
}
}
if (getPixelValue(letter_index, y + 1, x_in_letter, blank) == 0)
{
for (int yy = 0; yy < 2; yy++)
{
for (int xx = 0; xx < 2; xx++)
{
setPixel((getTextManager()->pow2TexWidth * 4 * line * lineHeight) + (((getTextManager()->pow2TexWidth * (((y + 1)) + yy)) + (((xInLine)) + xx)) * 4), shadowColor);
}
}
}
if (getPixelValue(letter_index, y + 1, x_in_letter + 1, blank) == 0)
{
for (int yy = 0; yy < 2; yy++)
{
for (int xx = 0; xx < 2; xx++)
{
setPixel((getTextManager()->pow2TexWidth * 4 * line * lineHeight) + (((getTextManager()->pow2TexWidth * (((y + 1)) + yy)) + (((xInLine + 1)) + xx)) * 4), shadowColor);
}
}
}
// if(TEXT_get_letter_pixel_color(letter_index,y,x_in_letter+1,blank)==0)TEXT_set_pixel((textMan().size_x*4*line*lineHeight)+(((textMan().size_x*((y)))+(((x_in_line+1))))*4),c2);
// if(TEXT_get_letter_pixel_color(letter_index,y+1,x_in_letter,blank)==0)TEXT_set_pixel((textMan().size_x*4*line*lineHeight)+(((textMan().size_x*(((y+1))))+(((x_in_line))))*4),c2);
// if(TEXT_get_letter_pixel_color(letter_index,y+1,x_in_letter+1,blank)==0)TEXT_set_pixel((textMan().size_x*4*line*lineHeight)+(((textMan().size_x*(((y+1))))+(((x_in_line+1))))*4),c2);
}
}
}
}
| 28.823087 | 254 | 0.555024 | [
"render"
] |
f06f27821287435a82dbaeb55d70045c40ab50bf | 7,723 | cpp | C++ | kits/appkit/native/test/mock/include/mock_resourceManager_interface1.cpp | openharmony-sig-ci/appexecfwk_standard | 609acd8632803202bd8af4c2a6bfc99ecf61ea2e | [
"Apache-2.0"
] | 1 | 2021-11-23T08:13:14.000Z | 2021-11-23T08:13:14.000Z | kits/appkit/native/test/mock/include/mock_resourceManager_interface1.cpp | openharmony-sig-ci/appexecfwk_standard | 609acd8632803202bd8af4c2a6bfc99ecf61ea2e | [
"Apache-2.0"
] | null | null | null | kits/appkit/native/test/mock/include/mock_resourceManager_interface1.cpp | openharmony-sig-ci/appexecfwk_standard | 609acd8632803202bd8af4c2a6bfc99ecf61ea2e | [
"Apache-2.0"
] | 1 | 2021-09-13T11:17:54.000Z | 2021-09-13T11:17:54.000Z | /*
* 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 <singleton.h>
#include <gtest/gtest.h>
#include "gmock/gmock.h"
#include "mock_resourceManager_interface1.h"
#include "res_config.h"
#include <string>
#include <vector>
#include <map>
namespace OHOS {
namespace Global {
namespace Resource {
class ResourceManagerTestInstance : public ResourceManager2 {
public:
ResourceManagerTestInstance(){};
virtual ~ResourceManagerTestInstance(){};
virtual bool AddResource(const char *path)
{
return false;
};
virtual RState UpdateResConfig(ResConfig &resConfig)
{
return ERROR;
};
virtual void GetResConfig(ResConfig &resConfig){};
virtual RState GetStringById(uint32_t id, std::string &outValue)
{
auto iter = StringById_.find(id);
if (iter == StringById_.end()) {
return ERROR;
}
outValue = iter->second;
return SUCCESS;
};
virtual void SetStringById(uint32_t id, std::string &inValue)
{
if (!StringById_.empty()) {
StringById_.clear();
}
StringById_[id] = inValue;
};
virtual RState GetStringByName(const char *name, std::string &outValue)
{
return ERROR;
};
virtual RState GetStringFormatById(std::string &outValue, uint32_t id, ...)
{
return ERROR;
};
virtual void SetStringFormatById(std::string &inValue, uint32_t id, ...){};
virtual RState GetStringFormatByName(std::string &outValue, const char *name, ...)
{
return ERROR;
};
virtual RState GetStringArrayById(uint32_t id, std::vector<std::string> &outValue)
{
auto iter = StringArrayById_.find(id);
if (iter == StringArrayById_.end()) {
return ERROR;
}
outValue = iter->second;
return SUCCESS;
};
virtual void SetStringArrayById(uint32_t id, std::vector<std::string> &inValue)
{
if (!StringArrayById_.empty()) {
StringArrayById_.clear();
}
StringArrayById_[id] = inValue;
};
virtual RState GetStringArrayByName(const char *name, std::vector<std::string> &outValue)
{
return ERROR;
};
virtual RState GetPatternById(uint32_t id, std::map<std::string, std::string> &outValue)
{
auto iter = PatternById_.find(id);
if (iter == PatternById_.end()) {
return ERROR;
}
outValue = iter->second;
return SUCCESS;
};
virtual void SetPatternById(uint32_t id, std::map<std::string, std::string> &inValue)
{
if (!PatternById_.empty()) {
PatternById_.clear();
}
PatternById_[id] = inValue;
};
virtual RState GetPatternByName(const char *name, std::map<std::string, std::string> &outValue)
{
return ERROR;
};
virtual RState GetPluralStringById(uint32_t id, int quantity, std::string &outValue)
{
return ERROR;
};
virtual RState GetPluralStringByName(const char *name, int quantity, std::string &outValue)
{
return ERROR;
};
virtual RState GetPluralStringByIdFormat(std::string &outValue, uint32_t id, int quantity, ...)
{
return ERROR;
};
virtual RState GetPluralStringByNameFormat(std::string &outValue, const char *name, int quantity, ...)
{
return ERROR;
};
virtual RState GetThemeById(uint32_t id, std::map<std::string, std::string> &outValue)
{
auto iter = ThemeById_.find(id);
if (iter == ThemeById_.end()) {
return ERROR;
}
outValue = iter->second;
return SUCCESS;
};
virtual void SetThemeById(uint32_t id, std::map<std::string, std::string> &inValue)
{
if (!ThemeById_.empty()) {
ThemeById_.clear();
}
ThemeById_[id] = inValue;
};
virtual RState GetThemeByName(const char *name, std::map<std::string, std::string> &outValue)
{
return ERROR;
};
virtual RState GetBooleanById(uint32_t id, bool &outValue)
{
return ERROR;
};
virtual RState GetBooleanByName(const char *name, bool &outValue)
{
return ERROR;
};
virtual RState GetIntegerById(uint32_t id, int &outValue)
{
return ERROR;
};
virtual RState GetIntegerByName(const char *name, int &outValue)
{
return ERROR;
};
virtual RState GetFloatById(uint32_t id, float &outValue)
{
return ERROR;
};
virtual RState GetFloatByName(const char *name, float &outValue)
{
return ERROR;
};
virtual RState GetIntArrayById(uint32_t id, std::vector<int> &outValue)
{
auto iter = IntArrayById_.find(id);
if (iter == IntArrayById_.end()) {
return ERROR;
}
outValue = iter->second;
return SUCCESS;
};
virtual void SetIntArrayById(uint32_t id, std::vector<int> &inValue)
{
if (!IntArrayById_.empty()) {
IntArrayById_.clear();
}
IntArrayById_[id] = inValue;
};
virtual RState GetIntArrayByName(const char *name, std::vector<int> &outValue)
{
return ERROR;
};
virtual RState GetColorById(uint32_t id, uint32_t &outValue)
{
auto iter = ColorById_.find(id);
if (iter == ColorById_.end()) {
return ERROR;
}
outValue = iter->second;
return SUCCESS;
};
virtual void SetColorById(uint32_t id, uint32_t &inValue)
{
if (!ColorById_.empty()) {
ColorById_.clear();
}
ColorById_[id] = inValue;
};
virtual RState GetColorByName(const char *name, uint32_t &outValue)
{
return ERROR;
};
virtual RState GetProfileById(uint32_t id, std::string &outValue)
{
return ERROR;
};
virtual RState GetProfileByName(const char *name, std::string &outValue)
{
return ERROR;
};
virtual RState GetMediaById(uint32_t id, std::string &outValue)
{
return ERROR;
};
virtual RState GetMediaByName(const char *name, std::string &outValue)
{
return ERROR;
};
public:
std::map<int, std::string> StringById_;
std::map<int, std::string> StringFormatById_;
std::map<int, std::vector<std::string>> StringArrayById_;
std::map<int, std::map<std::string, std::string>> PatternById_;
std::map<int, std::map<std::string, std::string>> ThemeById_;
std::map<int, std::vector<int>> IntArrayById_;
std::map<int, uint32_t> ColorById_;
// static ResourceManagerTestInstance* instance;
static std::shared_ptr<ResourceManagerTestInstance> instance;
};
std::shared_ptr<ResourceManagerTestInstance> ResourceManagerTestInstance::instance = nullptr;
std::shared_ptr<ResourceManager2> CreateResourceManager2()
{
if (ResourceManagerTestInstance::instance == nullptr) { /* */
ResourceManagerTestInstance::instance = std::make_shared<ResourceManagerTestInstance>();
}
return ResourceManagerTestInstance::instance;
}
} // namespace Resource
} // namespace Global
} // namespace OHOS | 27.098246 | 106 | 0.625664 | [
"vector"
] |
7eba72f88833d4039bb3c7d1ad1554bb0177b7db | 668 | hpp | C++ | include/game/skirmish/meta/deploymentzonemetaclass.hpp | namelessvoid/qrwar | bbc4036cd3bab6b0edcaccbc95286379ef51f12b | [
"MIT"
] | 3 | 2015-03-28T02:51:58.000Z | 2018-11-08T16:49:53.000Z | include/game/skirmish/meta/deploymentzonemetaclass.hpp | namelessvoid/qrwar | bbc4036cd3bab6b0edcaccbc95286379ef51f12b | [
"MIT"
] | 39 | 2015-05-18T08:29:16.000Z | 2020-07-18T21:17:44.000Z | include/game/skirmish/meta/deploymentzonemetaclass.hpp | namelessvoid/qrwar | bbc4036cd3bab6b0edcaccbc95286379ef51f12b | [
"MIT"
] | null | null | null | #ifndef QRW_DEPLOYMENTZONEMETACLASS_HPP
#define QRW_DEPLOYMENTZONEMETACLASS_HPP
#include "meta/reflectable.hpp"
#include "meta/metaclass.hpp"
namespace qrw {
class DeploymentZoneMetaClass final : public MetaClass
{
public:
explicit DeploymentZoneMetaClass(const MetaManager& metaManager);
void serialize(const Reflectable* object, YAML::Emitter& out) const override;
Reflectable* deserialize(const YAML::Node& in) const override;
private:
DeploymentZoneMetaClass(const DeploymentZoneMetaClass& rhs) = delete;
DeploymentZoneMetaClass& operator=(const DeploymentZoneMetaClass& rhs) = delete;
};
} // namespace qrw
#endif // QRW_DEPLOYMENTZONEMETACLASS_HPP
| 24.740741 | 81 | 0.80988 | [
"object"
] |
7eba8276cefe2ba6ea09ed2510d1b9ebe5ca2223 | 6,501 | cc | C++ | tools/springio/springio.cc | originalsouth/libmd | bf5423713328cbe5757603f8ee3700fb075dd7c1 | [
"BSD-4-Clause-UC"
] | 2 | 2019-05-27T14:19:03.000Z | 2019-09-03T12:59:22.000Z | tools/springio/springio.cc | originalsouth/libmd | bf5423713328cbe5757603f8ee3700fb075dd7c1 | [
"BSD-4-Clause-UC"
] | null | null | null | tools/springio/springio.cc | originalsouth/libmd | bf5423713328cbe5757603f8ee3700fb075dd7c1 | [
"BSD-4-Clause-UC"
] | null | null | null | ////////////////////////////////////
// I/O for 2D spring networks //
// Convenience functions for //
// interfacing with files such as //
// Stephan's MD input/output //
////////////////////////////////////
#include <iostream>
#include <fstream>
using namespace std;
#define INDEXSHIFT 0 // set to 1 for Stephan's conn.txt files, for which point indexing starts from 1
int dummy; // swallows integer returned by fscanf
string dataprecision = "%2.8"; // precision for string datafile output
string floatformat = string(F_LDFs).erase(0,1); // strip leading '%' from F_LDFs format string
string formatstring_ = dataprecision + floatformat + " ";
const char* formatstring = formatstring_.c_str(); // format string for datafile output
ui number_of_lines(string ptfile) {
int nl = 0;
string line;
ifstream myfile(ptfile);
while (getline(myfile, line))
++nl;
return nl;
}
int read_points(string ptfile, ldf *x, ldf* y) {
/* Read two-dimensional point data from ptfile into 'x' and 'y' arrays
* Each row of ptfile must contain two entries, corresponding to 'x' and 'y' coordinates */
FILE* inputM;
ldf xin, yin;
vector<ldf> xv(0);
vector<ldf> yv(0);
inputM = fopen(ptfile.c_str(), "r");
if(inputM!=NULL) {
while (!(feof(inputM))) {
dummy = fscanf(inputM, F_LDFs " " F_LDFs "\n", &xin, &yin);
xv.push_back(xin); yv.push_back(yin);
}
copy(xv.begin(), xv.end(), x);
copy(yv.begin(), yv.end(), y);
fclose(inputM);
return 0;
} else {
cout << "Couldn't open " << ptfile << endl;
return 1;
}
}
int read_points(string ptfile, ldf *x, ldf* y, ldf* z) {
/* Read three-dimensional point data from ptfile into 'x', 'y', 'z' arrays
* Each row of ptfile must contain three entries */
FILE* inputM;
ldf xin, yin, zin;
vector<ldf> xv(0);
vector<ldf> yv(0);
vector<ldf> zv(0);
inputM = fopen(ptfile.c_str(), "r");
if(inputM!=NULL) {
while (!(feof(inputM))) {
dummy = fscanf(inputM, F_LDFs " " F_LDFs " " F_LDFs "\n", &xin, &yin, &zin);
xv.push_back(xin); yv.push_back(yin); zv.push_back(zin);
}
copy(xv.begin(), xv.end(), x);
copy(yv.begin(), yv.end(), y);
copy(zv.begin(), zv.end(), z);
fclose(inputM);
return 0;
} else {
cout << "Couldn't open " << ptfile << endl;
return 1;
}
}
template<ui dim> int read_bonds(string bfile, md<dim> &sys) {
/* Read in connectivity data from bfile into md structure, creating harmonic bonds.
* each row of bfile contains five entries: idx1 idx2 bondtype springconstant restlength */
ui p1in, p2in, dummy;
ldf kin, l0in;
FILE* inputM = fopen(bfile.c_str(), "r");
if(inputM!=NULL) {
while (!(feof(inputM))) {
dummy = fscanf(inputM, F_UI " " F_UI " " F_UI " " F_LDFs " " F_LDFs "\n", &p1in, &p2in, &dummy, &kin, &l0in);
// spring with k and r0
sys.add_spring(p1in-INDEXSHIFT, p2in-INDEXSHIFT,kin,l0in);
}
fclose(inputM);
return 0;
} else {
cout << "Couldn't open " << bfile << endl;
return 1;
}
}
template<ui dim> int read_bonds(string bfile, md<dim> &sys,vector<vector<ui>> &nbrlist, ldf kfactor=1.) {
/* Read neighbors into a list of neighbor indices, in addition to adding springs to md structure */
ui p1in, p2in, dummy;
ldf kin, l0in;
FILE* inputM = fopen(bfile.c_str(), "r");
if(inputM!=NULL) {
while (!(feof(inputM))) {
dummy = fscanf(inputM, F_UI " " F_UI " " F_UI " " F_LDFs " " F_LDFs "\n", &p1in, &p2in, &dummy, &kin, &l0in);
// spring with k and r0
sys.add_spring(p1in-INDEXSHIFT, p2in-INDEXSHIFT,kin*kfactor,l0in);
// update nbrlist
nbrlist[p1in-INDEXSHIFT].push_back(p2in-INDEXSHIFT);
nbrlist[p2in-INDEXSHIFT].push_back(p1in-INDEXSHIFT);
}
fclose(inputM);
return 0;
} else {
cout << "Couldn't open " << bfile << endl;
return 1;
}
}
template<ui dim> void write_points_x(string filename, md<dim> &sys) {
/* write N*dim array of point positions */
FILE* op = fopen(filename.c_str(),"w");
for (unsigned int i = 0; i < sys.N; i++) {
for (unsigned int d = 0; d < dim; d++) {
fprintf(op, formatstring, sys.particles[i].x[d]);
}
fprintf (op, "\n");
}
fclose(op);
}
template<ui dim> void write_points_v(string filename, md<dim> &sys) {
/* write N*dim array of point velocities */
FILE* op = fopen(filename.c_str(),"w");
for (unsigned int i = 0; i < sys.N; i++) {
for (unsigned int d = 0; d < dim; d++) {
fprintf(op, formatstring, sys.particles[i].dx[d]);
}
fprintf (op, "\n");
}
fclose(op);
}
template<ui dim> void write_points_f(string filename, md<dim> &sys) {
/* write N*dim array of forces */
FILE* op = fopen(filename.c_str(),"w");
for (unsigned int i = 0; i < sys.N; i++) {
for (unsigned int d = 0; d < dim; d++) {
fprintf(op, formatstring, sys.particles[i].F[d]);
}
fprintf (op, "\n");
}
fclose(op);
}
template<ui dim> void write_bonds(string filename, md<dim> &sys) {
/* write connectivity data from the skins structures. */
FILE* op = fopen(filename.c_str(),"w");
for (unsigned int i = 0; i < sys.N; i++) {
for(unsigned int j=sys.network.skins[i].size()-1;j<UI_MAX;j--) if(i>sys.network.skins[i][j].neighbor) {
fprintf(op, "%d %d\n", i, sys.network.skins[i][j].neighbor);
}
}
fclose(op);
}
template<ui dim> void write_energies(string filename, md<dim> &sys) {
/* write energies (H, T, V) to filename : use scientific notation */
FILE* op = fopen(filename.c_str(),"w");
fprintf(op, formatstring, sys.H());
fprintf(op, formatstring, sys.T());
fprintf(op, formatstring, sys.V());
fprintf (op, "\n");
fclose(op);
}
template<ui dim> void append_energies(string filename, md<dim> &sys) {
/* append(!) energies (H, T, V) to filename : use scientific notation */
FILE* op = fopen(filename.c_str(),"a");
fprintf(op, formatstring, sys.H());
fprintf(op, formatstring, sys.T());
fprintf(op, formatstring, sys.V());
fprintf (op, "\n");
fclose(op);
}
template<ui dim> void write_data(string prefix, md<dim> &sys) {
write_points_x(prefix+".pts",sys);
write_points_v(prefix+".vel",sys);
write_points_f(prefix+".f",sys);
write_bonds(prefix+".bds",sys);
}
| 32.183168 | 117 | 0.588679 | [
"vector"
] |
7ec656678e3c882ccbbd760749d018abef30f1de | 2,662 | cpp | C++ | Greedy Algorithms/Kruskal's Algorithm/SolutionbyKarna.cpp | Mdanish777/Programmers-Community | b5ca9582fc1cd4337baa7077ff62130a1052583f | [
"MIT"
] | 261 | 2019-09-30T19:47:29.000Z | 2022-03-29T18:20:07.000Z | Greedy Algorithms/Kruskal's Algorithm/SolutionbyKarna.cpp | Mdanish777/Programmers-Community | b5ca9582fc1cd4337baa7077ff62130a1052583f | [
"MIT"
] | 647 | 2019-10-01T16:51:29.000Z | 2021-12-16T20:39:44.000Z | Greedy Algorithms/Kruskal's Algorithm/SolutionbyKarna.cpp | Mdanish777/Programmers-Community | b5ca9582fc1cd4337baa7077ff62130a1052583f | [
"MIT"
] | 383 | 2019-09-30T19:32:07.000Z | 2022-03-24T16:18:26.000Z | #include <iostream>
#include <vector>
#include <utility>
#include <algorithm>
/* Define an edge struct to handle edges more easily.*/
struct edge {
int first, second, weight;
};
/* Needed to typedef to reduce keystrokes or copy/paste */
typedef std::vector< std::vector< std::pair<int,int> > > adj_list;
std::vector<edge> kruskal(const adj_list& graph);
int get_pred(int vertex, const std::vector<int>& pred);
int main() {
int n,m; std::cin >> n >> m;
adj_list graph(n);
int f,s,w;
while (m-- > 0) {
std::cin >> f >> s >> w;
if (f == s) continue; /* avoid loops */
graph[ f-1 ].push_back( std::make_pair( s-1 , w ) );
}
std::vector<edge> result = kruskal(graph);
std::cout << "Here is the minimal tree:\n";
for (auto& _edge : result) {
std::cout << char(_edge.first+65) << " connects to " << char(_edge.second+65) << std::endl;
}
return 0;
}
std::vector<edge> kruskal(const adj_list& graph) {
std::vector<edge> edges, minimum_spanning_tree;
/*
`pred` will represent our Disjointed sets by naming a set head.
In the beginning, each node is its own head in its own set.
We merge sets in the while loop.
*/
std::vector<int> pred(graph.size());
for (int i = 0, n = graph.size(); i < n; i++) {
for (auto& _edge : graph[i])
edges.push_back( { i, _edge.first, _edge.second } );
pred[i] = i;
}
/*
Let's reverse-sort our edge vector
so that we can just pop off the last (smallest)
element.
*/
auto comp = [&](edge left, edge right) { return left.weight > right.weight; };
std::sort(edges.begin(), edges.end(), comp);
while( !edges.empty() ) {
/* get shortest/least-heavy edge */
edge shortest = edges.back();
edges.pop_back();
int f_head,s_head; /* first_head, second... */
f_head = get_pred(shortest.first, pred);
s_head = get_pred(shortest.second, pred);
/*
If the nodes making up a certain edge are
not already in the same set...
*/
if (f_head != s_head) {
/* Add that edge to the Min. Span. Tree*/
minimum_spanning_tree.push_back(shortest);
/*
Merge the sets by setting
the head of one set to the head
of the other set.
If the head of one set is A and the other is C,
as long as we point C to A, all nodes part of the
set once headed by C will find A in linear time.
*/
if (f_head < s_head)
pred[s_head] = f_head;
else
pred[f_head] = s_head;
}
}
return minimum_spanning_tree;
}
int get_pred(int vertex, const std::vector<int>& pred) {
/*
We stop when a node/vertex is its own predecessor.
This means we have found the head of the set.
*/
while(pred[vertex] != vertex)
vertex = pred[vertex];
return vertex;
}
| 24.422018 | 93 | 0.643125 | [
"vector"
] |
7ed849e76bd99bff87dc728c1957b4ecfcc7782a | 9,335 | cpp | C++ | RcsPySim/src/cpp/core/action/AMTaskActivation.cpp | jacarvalho/SimuRLacra | a6c982862e2ab39a9f65d1c09aa59d9a8b7ac6c5 | [
"BSD-3-Clause"
] | null | null | null | RcsPySim/src/cpp/core/action/AMTaskActivation.cpp | jacarvalho/SimuRLacra | a6c982862e2ab39a9f65d1c09aa59d9a8b7ac6c5 | [
"BSD-3-Clause"
] | null | null | null | RcsPySim/src/cpp/core/action/AMTaskActivation.cpp | jacarvalho/SimuRLacra | a6c982862e2ab39a9f65d1c09aa59d9a8b7ac6c5 | [
"BSD-3-Clause"
] | null | null | null | #include "AMTaskActivation.h"
#include "ActionModelIK.h"
#include "../util/eigen_matnd.h"
#include <Rcs_macros.h>
#include <utility>
/*! Compute the column-wise softmax \f$ \sigma(x)_{i,j} = \frac{e^{x_{i,j}}}{\sum_{k=1}^{K} e^{x_{k,j}}} \f$.
* The entries of the resulting matrix sum to one
* @param[in] src input matrix
* @param[in] beta scaling factor, as beta goes to infinity we get the argmax
* @param[out] dst output matrix
*/
void MatNd_softMax(MatNd* dst, const MatNd* src, double beta)
{
RCHECK_MSG((dst->m == src->m) && (dst->n == src->n), "dst: [%d x %d] src: [%d x %d]", dst->m, dst->n, src->m,
src->n);
RCHECK_MSG(beta > 0, "beta: %f", beta);
for (unsigned int j = 0; j < src->n; j++)
{
double dnom = 0.;
for (unsigned int i = 0; i < src->m; i++)
{
dnom += exp(beta*MatNd_get2(src, i, j));
}
for (unsigned int i = 0; i < src->m; i++)
{
MatNd_set2(dst, i, j, exp(beta*MatNd_get2(src, i, j))/dnom);
}
}
}
/*! Find all unique combinations of 0s and 1s for N binary events.
* @param[out] allComb 2^N x N output matrix containing the combinations,
* with N being the number of events that could be 0 or 1
*/
void findAllBitCombinations(MatNd* allComb)
{
// Get the dimension
size_t N = allComb->n;
// Set all entries to 0. The first row will be used directly as a result
MatNd_setZero(allComb);
size_t i = 1; // row index
for (size_t k = 1; k <= N; k++)
{
std::vector<size_t> vec(N, 0);
std::vector<size_t> currOnes(k, 1);
// Set last k bits to 1
std::copy(begin(currOnes), end(currOnes), end(vec) - k);
// Get the combinations / permutations and set them into the matrix
do
{
for (size_t v = 0; v < vec.size(); v++)
{
// Fill the current row
MatNd_set2(allComb, i, v, vec[v]);
}
i++;
} while (std::next_permutation(vec.begin(), vec.end())); // returns false if no valid permutation was found
}
}
namespace Rcs
{
AMTaskActivation::AMTaskActivation(ActionModel* wrapped, std::vector<DynamicalSystem*> ds, TaskCombinationMethod tcm)
: ActionModel(wrapped->getGraph()), wrapped(wrapped), dynamicalSystems(std::move(ds)), taskCombinationMethod(tcm)
{
activation = MatNd_create((unsigned int) dynamicalSystems.size(), 1);
}
AMTaskActivation::~AMTaskActivation()
{
delete wrapped;
delete activation;
for (auto* ds : dynamicalSystems)
{
delete ds;
}
}
unsigned int AMTaskActivation::getDim() const
{
return (unsigned int) dynamicalSystems.size();
}
void AMTaskActivation::getMinMax(double* min, double* max) const
{
// All activations are between -1 and 1
for (unsigned int i = 0; i < getDim(); i++)
{
min[i] = -1;
max[i] = 1;
}
}
std::vector<std::string> AMTaskActivation::getNames() const
{
std::vector<std::string> names;
for (unsigned int i = 0; i < getDim(); ++i)
{
names.push_back("a_" + std::to_string(i));
}
return names;
}
void AMTaskActivation::computeCommand(MatNd* q_des, MatNd* q_dot_des, MatNd* T_des, const MatNd* action, double dt)
{
RCHECK(action->n == 1); // actions are column vectors
// Remember x_dot from last step as integration input.
Eigen::VectorXd x_dot_old = x_dot;
x_dot.setConstant(0);
// Collect data from each DS
for (unsigned int i = 0; i < getDim(); ++i)
{
// Fill a temp x_dot with the old x_dot
Eigen::VectorXd x_dot_ds = x_dot_old;
// Step the DS
dynamicalSystems[i]->step(x_dot_ds, x, dt);
// Remember x_dot for OMDynamicalSystemDiscrepancy
dynamicalSystems[i]->x_dot_des = x_dot_ds;
// Combine the individual x_dot of every DS
switch (taskCombinationMethod)
{
case TaskCombinationMethod::Sum:
case TaskCombinationMethod::Mean:
{
x_dot += action->ele[i]*x_dot_ds;
MatNd_set(activation, i, 0, action->ele[i]);
break;
}
case TaskCombinationMethod::SoftMax:
{
MatNd* a = NULL;
MatNd_create2(a, action->m, action->n);
MatNd_softMax(a, action, action->m); // action->m is a neat heuristic for beta
x_dot += MatNd_get(a, i, 0)*x_dot_ds;
MatNd_set(activation, i, 0, MatNd_get(a, i, 0));
MatNd_destroy(a);
break;
}
case TaskCombinationMethod::Product:
{
// Create temp matrix
MatNd* otherActions = NULL; // other actions are all actions without the current
MatNd_clone2(otherActions, action);
MatNd_deleteRow(otherActions, i);
// Treat the actions as probability of events and compute the probability that all other actions are false
double prod = 1; // 1 is the neutral element for multiplication
for (unsigned int a = 0; a < otherActions->m; a++)
{
REXEC(7)
{
std::cout << "factor " << (1 - otherActions->ele[a]) << std::endl;
}
// One part of the product is always 1
prod *= (1 - otherActions->ele[a]);
}
REXEC(7)
{
std::cout << "prod " << prod << std::endl;
}
x_dot += action->ele[i]*prod*x_dot_ds;
MatNd_set(activation, i, 0, action->ele[i]*prod);
MatNd_destroy(otherActions);
break;
}
}
// Print if debug level is exceeded
REXEC(5)
{
std::cout << "action DS " << i << " = " << action->ele[i] << std::endl;
std::cout << "x_dot DS " << i << " =" << std::endl << x_dot_ds << std::endl;
}
}
if (taskCombinationMethod == TaskCombinationMethod::Mean)
{
double normalizer = MatNd_getNormL1(action) + 1e-8;
x_dot /= normalizer;
MatNd_constMulSelf(activation, 1./normalizer);
}
// Integrate to x
x += x_dot*dt;
// Pass x to wrapped action model
MatNd x_rcs = viewEigen2MatNd(x);
// Compute the joint angle positions (joint angle velocities, and torques)
wrapped->computeCommand(q_des, q_dot_des, T_des, &x_rcs, dt);
// Print if debug level is exceeded
REXEC(5)
{
std::cout << "x_dot (combined MP) =\n" << x_dot << std::endl;
std::cout << "x (combined MP) =\n" << x << std::endl;
}
REXEC(7)
{
MatNd_printComment("q_des", q_des);
MatNd_printComment("q_dot_des", q_dot_des);
if (T_des)
MatNd_printComment("T_des", T_des);
}
}
void AMTaskActivation::reset()
{
wrapped->reset();
// Initialize shapes
x.setZero(wrapped->getDim());
x_dot.setZero(wrapped->getDim());
// Obtain current stable action from wrapped action model
MatNd x_rcs = viewEigen2MatNd(x);
wrapped->getStableAction(&x_rcs);
}
void AMTaskActivation::getStableAction(MatNd* action) const
{
// All zero activations is stable
MatNd_setZero(action);
}
Eigen::VectorXd AMTaskActivation::getX() const
{
return x;
}
Eigen::VectorXd AMTaskActivation::getXdot() const
{
return x_dot;
}
ActionModel* AMTaskActivation::getWrappedActionModel() const
{
return wrapped;
}
const std::vector<DynamicalSystem*>& AMTaskActivation::getDynamicalSystems() const
{
return dynamicalSystems;
}
ActionModel* AMTaskActivation::clone(RcsGraph* newGraph) const
{
std::vector<DynamicalSystem*> dsvc;
for (auto ds : dynamicalSystems)
{
dsvc.push_back(ds->clone());
}
return new AMTaskActivation(wrapped->clone(newGraph), dsvc, TaskCombinationMethod::Mean);
}
TaskCombinationMethod AMTaskActivation::checkTaskCombinationMethod(std::string tcmName)
{
TaskCombinationMethod tcm;
if (tcmName == "sum")
{
tcm = TaskCombinationMethod::Sum;
}
else if (tcmName == "mean")
{
tcm = TaskCombinationMethod::Mean;
}
else if (tcmName == "softmax")
{
tcm = TaskCombinationMethod::SoftMax;
}
else if (tcmName == "product")
{
tcm = TaskCombinationMethod::Product;
}
else
{
std::ostringstream os;
os << "Unsupported task combination method: " << tcmName;
throw std::invalid_argument(os.str());
}
return tcm;
}
const char* AMTaskActivation::getTaskCombinationMethodName() const
{
if (taskCombinationMethod == TaskCombinationMethod::Sum)
{
return "sum";
}
else if (taskCombinationMethod == TaskCombinationMethod::Mean)
{
return "mean";
}
else if (taskCombinationMethod == TaskCombinationMethod::SoftMax)
{
return "softmax";
}
else if (taskCombinationMethod == TaskCombinationMethod::Product)
{
return "product";
}
else
{
return nullptr;
}
}
MatNd* AMTaskActivation::getActivation() const
{
return activation;
}
} /* namespace Rcs */
| 27.865672 | 122 | 0.576111 | [
"vector",
"model"
] |
7edb1ced301624d7a8d1c0555a7f1ad28dc2e834 | 17,021 | cpp | C++ | PrototypeEngine/src/core/PrototypeShaderBuffer.cpp | o-micron/Prototype | 5b9d60d9dd80e7c8a1a2b0aaf19c2d90c1814139 | [
"Apache-2.0"
] | 2 | 2021-08-19T17:15:49.000Z | 2021-12-28T22:48:47.000Z | PrototypeEngine/src/core/PrototypeShaderBuffer.cpp | o-micron/Prototype | 5b9d60d9dd80e7c8a1a2b0aaf19c2d90c1814139 | [
"Apache-2.0"
] | null | null | null | PrototypeEngine/src/core/PrototypeShaderBuffer.cpp | o-micron/Prototype | 5b9d60d9dd80e7c8a1a2b0aaf19c2d90c1814139 | [
"Apache-2.0"
] | null | null | null | /// Copyright 2021 Omar Sherif Fathy
///
/// 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 "PrototypeShaderBuffer.h"
#include "PrototypeDatabase.h"
#include "PrototypeEngine.h"
#include "PrototypeRenderer.h"
#include "PrototypeStaticInitializer.h"
#include "PrototypeUI.h"
#include <PrototypeCommon/IO.h>
#include <PrototypeCommon/Logger.h>
#include <algorithm>
#include <regex>
void
parseBindingSource(std::vector<std::shared_ptr<PrototypeShaderBufferSource>>& sources)
{
for (size_t i = 0; i < sources.size(); ++i) {
if (sources[i]->type == PrototypeShaderBufferSourceType_VertexShader) {
std::vector<std::pair<std::string, f32>> oldFloatData = sources[i]->bindingSource.floatData;
sources[i]->bindingSource.floatData.clear();
std::vector<std::pair<std::string, glm::vec2>> oldVec2Data = sources[i]->bindingSource.vec2Data;
sources[i]->bindingSource.vec2Data.clear();
std::vector<std::pair<std::string, glm::vec3>> oldVec3Data = sources[i]->bindingSource.vec3Data;
sources[i]->bindingSource.vec3Data.clear();
std::vector<std::pair<std::string, glm::vec4>> oldVec4Data = sources[i]->bindingSource.vec4Data;
sources[i]->bindingSource.vec4Data.clear();
std::stringstream ss(sources[i]->code);
std::string to;
bool isGui = false;
std::string isGuiBuffer = "";
while (std::getline(ss, to, '\n')) {
std::smatch pieces_match;
if (std::regex_search(to, pieces_match, std::regex(R"~([ ]*#pragma[ ]+gui[ ]*((.*)))~"))) {
isGui = true;
if (pieces_match.size() >= 2) {
isGuiBuffer = pieces_match[1].str().substr(1);
isGuiBuffer = isGuiBuffer.substr(0, isGuiBuffer.size() - 1);
}
} else if (isGui && std::regex_search(
to, pieces_match, std::regex(R"~([ ]*uniform[ ]+float[ ]+([a-z-A-Z-0-9-_]+)[ ]*)~"))) {
if (pieces_match.size() == 2) {
auto varName = pieces_match[1].str();
auto it = std::find_if(
oldFloatData.begin(), oldFloatData.end(), [&](const auto& item) { return item.first == varName; });
if (it == oldFloatData.end()) {
std::stringstream isGuiBufferStream(isGuiBuffer);
float v0;
isGuiBufferStream >> v0;
if (!isGuiBufferStream.fail()) {
sources[i]->bindingSource.floatData.push_back({ varName, v0 });
} else {
sources[i]->bindingSource.floatData.push_back({ varName, 0.0f });
}
isGui = false;
isGuiBuffer = "";
} else {
sources[i]->bindingSource.floatData.push_back({ varName, it->second });
isGui = false;
isGuiBuffer = "";
}
}
} else if (isGui && std::regex_search(
to, pieces_match, std::regex(R"~([ ]*uniform[ ]+vec2[ ]+([a-z-A-Z-0-9-_]+)[ ]*)~"))) {
if (pieces_match.size() == 2) {
auto varName = pieces_match[1].str();
auto it = std::find_if(
oldVec2Data.begin(), oldVec2Data.end(), [&](const auto& item) { return item.first == varName; });
if (it == oldVec2Data.end()) {
std::stringstream isGuiBufferStream(isGuiBuffer);
float v0, v1;
isGuiBufferStream >> v0;
if (!isGuiBufferStream.fail()) {
isGuiBufferStream >> v1;
if (!isGuiBufferStream.fail()) {
sources[i]->bindingSource.vec2Data.push_back({ varName, { v0, v1 } });
} else {
sources[i]->bindingSource.vec2Data.push_back({ varName, { 0.0f, 0.0f } });
}
} else {
sources[i]->bindingSource.vec2Data.push_back({ varName, { 0.0f, 0.0f } });
}
isGui = false;
isGuiBuffer = "";
} else {
sources[i]->bindingSource.vec2Data.push_back({ varName, it->second });
isGui = false;
isGuiBuffer = "";
}
}
} else if (isGui && std::regex_search(
to, pieces_match, std::regex(R"~([ ]*uniform[ ]+vec3[ ]+([a-z-A-Z-0-9-_]+)[ ]*)~"))) {
if (pieces_match.size() == 2) {
auto varName = pieces_match[1].str();
auto it = std::find_if(
oldVec3Data.begin(), oldVec3Data.end(), [&](const auto& item) { return item.first == varName; });
if (it == oldVec3Data.end()) {
std::stringstream isGuiBufferStream(isGuiBuffer);
float v0, v1, v2;
isGuiBufferStream >> v0;
if (!isGuiBufferStream.fail()) {
isGuiBufferStream >> v1;
if (!isGuiBufferStream.fail()) {
isGuiBufferStream >> v2;
if (!isGuiBufferStream.fail()) {
sources[i]->bindingSource.vec3Data.push_back({ varName, { v0, v1, v2 } });
} else {
sources[i]->bindingSource.vec3Data.push_back({ varName, { 0.0f, 0.0f, 0.0f } });
}
} else {
sources[i]->bindingSource.vec3Data.push_back({ varName, { 0.0f, 0.0f, 0.0f } });
}
} else {
sources[i]->bindingSource.vec3Data.push_back({ varName, { 0.0f, 0.0f, 0.0f } });
}
isGui = false;
isGuiBuffer = "";
} else {
sources[i]->bindingSource.vec3Data.push_back({ varName, it->second });
isGui = false;
isGuiBuffer = "";
}
}
} else if (isGui && std::regex_search(
to, pieces_match, std::regex(R"~([ ]*uniform[ ]+vec4[ ]+([a-z-A-Z-0-9-_]+)[ ]*)~"))) {
if (pieces_match.size() == 2) {
auto varName = pieces_match[1].str();
auto it = std::find_if(
oldVec4Data.begin(), oldVec4Data.end(), [&](const auto& item) { return item.first == varName; });
if (it == oldVec4Data.end()) {
std::stringstream isGuiBufferStream(isGuiBuffer);
float v0, v1, v2, v3;
isGuiBufferStream >> v0;
if (!isGuiBufferStream.fail()) {
isGuiBufferStream >> v1;
if (!isGuiBufferStream.fail()) {
isGuiBufferStream >> v2;
if (!isGuiBufferStream.fail()) {
isGuiBufferStream >> v3;
if (!isGuiBufferStream.fail()) {
sources[i]->bindingSource.vec4Data.push_back({ varName, { v0, v1, v2, v3 } });
} else {
sources[i]->bindingSource.vec4Data.push_back({ varName, { 0.0f, 0.0f, 0.0f, 0.0f } });
}
} else {
sources[i]->bindingSource.vec4Data.push_back({ varName, { 0.0f, 0.0f, 0.0f, 0.0f } });
}
} else {
sources[i]->bindingSource.vec4Data.push_back({ varName, { 0.0f, 0.0f, 0.0f, 0.0f } });
}
} else {
sources[i]->bindingSource.vec4Data.push_back({ varName, { 0.0f, 0.0f, 0.0f, 0.0f } });
}
isGui = false;
isGuiBuffer = "";
} else {
sources[i]->bindingSource.vec4Data.push_back({ varName, it->second });
isGui = false;
isGuiBuffer = "";
}
}
}
}
} else if (sources[i]->type == PrototypeShaderBufferSourceType_FragmentShader) {
std::vector<std::string> oldTextureData = sources[i]->bindingSource.textureData;
sources[i]->bindingSource.textureData.clear();
std::stringstream ss(sources[i]->code);
std::string to;
bool isGui = true;
while (std::getline(ss, to, '\n')) {
std::smatch pieces_match;
if (std::regex_search(to, pieces_match, std::regex(R"~([ ]*#pragma[ ]+gui[ ]*)~"))) {
isGui = true;
} else if (isGui && std::regex_search(
to, pieces_match, std::regex(R"~([ ]*uniform[ ]+sampler2D[ ]+([a-z-A-Z-0-9-_]+)[ ]*)~"))) {
if (pieces_match.size() == 2) {
auto varName = pieces_match[1].str();
auto it = std::find_if(
oldTextureData.begin(), oldTextureData.end(), [&](const auto& item) { return item == varName; });
if (it == oldTextureData.end()) {
isGui = false;
sources[i]->bindingSource.textureData.push_back(varName);
} else {
isGui = false;
sources[i]->bindingSource.textureData.push_back(*it);
}
}
}
}
}
}
}
void
loadSourceFromFile(std::vector<std::shared_ptr<PrototypeShaderBufferSource>>& sources)
{
sources[0]->code = "";
sources[1]->code = "";
if (PrototypeIo::readFileBlock(sources[0]->fullpath.c_str(), sources[0]->code)) {
if (PrototypeIo::readFileBlock(sources[1]->fullpath.c_str(), sources[1]->code)) {
parseBindingSource(sources);
} else {
PrototypeLogger::warn("Fragment shader file not found %s", sources[1]->fullpath.c_str());
return;
}
} else {
PrototypeLogger::warn("Vertex shader file not found %s", sources[0]->fullpath.c_str());
return;
}
}
PrototypeShaderBuffer::PrototypeShaderBuffer(const std::string name)
: _id(++PrototypeStaticInitializer::_shaderBufferUUID)
, _name(name)
, userData(nullptr)
, _needsUpload(false)
{}
PrototypeShaderBuffer::~PrototypeShaderBuffer() { unsetData(); }
const u32&
PrototypeShaderBuffer::id() const
{
return _id;
}
const std::string&
PrototypeShaderBuffer::name() const
{
return _name;
}
const bool&
PrototypeShaderBuffer::needsUpload() const
{
return _needsUpload;
}
const std::vector<std::shared_ptr<PrototypeShaderBufferSource>>&
PrototypeShaderBuffer::sources() const
{
bool unloaded = false;
for (const auto& source : _sources) {
if (source->code.empty()) {
unloaded = true;
break;
}
}
if (unloaded) { loadSourceFromFile(_sources); }
return _sources;
}
void
PrototypeShaderBuffer::setSources(std::vector<std::shared_ptr<PrototypeShaderBufferSource>>& sources)
{
_sources.resize(sources.size());
for (size_t i = 0; i < sources.size(); ++i) { _sources[i] = std::move(sources[i]); }
}
void
PrototypeShaderBuffer::stageChange()
{
for (auto& source : _sources) { source->timestamp = PrototypeIo::filestamp(source->fullpath); }
loadSourceFromFile(_sources);
_needsUpload = true;
#ifdef PROTOTYPE_ENGINE_DEVELOPMENT_MODE
PrototypeEngineInternalApplication::renderer->ui()->signalBuffersChanged(true);
#endif
}
void
PrototypeShaderBuffer::commitChange()
{
if (_needsUpload) {
_needsUpload = false;
PrototypeEngineInternalApplication::renderer->onShaderBufferGpuUpload(this);
}
}
void
PrototypeShaderBuffer::unsetData()
{
for (auto& source : _sources) {
source->code.clear();
source->code.shrink_to_fit();
}
}
void
PrototypeShaderBuffer::to_json(nlohmann::json& j, const PrototypeShaderBuffer& shaderBuffer)
{
j["id"] = shaderBuffer.id();
j["name"] = shaderBuffer.name();
}
void
PrototypeShaderBuffer::from_json(const nlohmann::json& j)
{
if (j.is_null()) { return; }
const std::string shaderPath = j.get<std::string>();
std::string vertexShaderPath = "";
std::string fragmentShaderPath = "";
if (shaderPath.empty()) { return; }
if (PrototypeEngineInternalApplication::database->shaderBuffers.find(shaderPath) !=
PrototypeEngineInternalApplication::database->shaderBuffers.end()) {
return;
}
// detect rendering api and set path and extension accordingly
switch (PrototypeEngineInternalApplication::renderingApi) {
case PrototypeEngineERenderingApi_OPENGL4_1: {
vertexShaderPath = PROTOTYPE_OPENGL_SHADER_PATH("") + shaderPath + "/vert.glsl";
fragmentShaderPath = PROTOTYPE_OPENGL_SHADER_PATH("") + shaderPath + "/frag.glsl";
} break;
case PrototypeEngineERenderingApi_OPENGLES_3_0: {
vertexShaderPath = PROTOTYPE_OPENGL_SHADER_PATH("") + shaderPath + "/vert.glsl";
fragmentShaderPath = PROTOTYPE_OPENGL_SHADER_PATH("") + shaderPath + "/frag.glsl";
} break;
case PrototypeEngineERenderingApi_VULKAN_1: {
vertexShaderPath = PROTOTYPE_VULKAN_SHADER_PATH("") + shaderPath + "/vert.spv";
fragmentShaderPath = PROTOTYPE_VULKAN_SHADER_PATH("") + shaderPath + "/frag.spv";
} break;
default: {
PrototypeLogger::fatal("renderingApi: Unimplemented!(Unreachable");
} break;
}
std::vector<std::shared_ptr<PrototypeShaderBufferSource>> shaderBufferSources = {
std::make_unique<PrototypeShaderBufferSource>(
vertexShaderPath, "", PrototypeShaderBufferSourceType_VertexShader, PrototypeIo::filestamp(vertexShaderPath)),
std::make_unique<PrototypeShaderBufferSource>(
fragmentShaderPath, "", PrototypeShaderBufferSourceType_FragmentShader, PrototypeIo::filestamp(fragmentShaderPath))
};
loadSourceFromFile(shaderBufferSources);
if (!shaderBufferSources[0]->code.empty() && !shaderBufferSources[1]->code.empty()) {
auto shaderBuffer = PrototypeEngineInternalApplication::database->allocateShaderBuffer(shaderPath);
shaderBuffer->setSources(shaderBufferSources);
PrototypeEngineInternalApplication::database->shaderBuffers.insert({ shaderPath, shaderBuffer });
}
} | 47.677871 | 131 | 0.485283 | [
"vector"
] |
7edc649b3b2baaf8d362c4ad4ae6d5f8ea8efc89 | 9,789 | cpp | C++ | Tools/EntityInterface/PlacementEntities.cpp | yorung/XLE | 083ce4c9d3fe32002ff5168e571cada2715bece4 | [
"MIT"
] | 1 | 2016-06-01T10:41:12.000Z | 2016-06-01T10:41:12.000Z | Tools/EntityInterface/PlacementEntities.cpp | yorung/XLE | 083ce4c9d3fe32002ff5168e571cada2715bece4 | [
"MIT"
] | null | null | null | Tools/EntityInterface/PlacementEntities.cpp | yorung/XLE | 083ce4c9d3fe32002ff5168e571cada2715bece4 | [
"MIT"
] | null | null | null | // Copyright 2015 XLGAMES Inc.
//
// Distributed under the MIT License (See
// accompanying file "LICENSE" or the website
// http://www.opensource.org/licenses/mit-license.php)
#include "PlacementEntities.h"
#include "../../SceneEngine/PlacementsManager.h"
#include "../../Utility/StringFormat.h"
#include "../../Utility/ParameterBox.h"
#include "../../Utility/UTFUtils.h"
#include "../../Utility/StringUtils.h"
#include "../../Math/Transformations.h"
namespace EntityInterface
{
static const DocumentTypeId DocumentType_Placements = 1;
static const ObjectTypeId ObjectType_Placement = 1;
static const PropertyId Property_Transform = 100;
static const PropertyId Property_Visible = 101;
static const PropertyId Property_Model = 102;
static const PropertyId Property_Material = 103;
static const PropertyId Property_Bounds = 104;
static const PropertyId Property_LocalBounds = 105;
DocumentId PlacementEntities::CreateDocument(DocumentTypeId docType, const char initializer[])
{
if (docType != DocumentType_Placements) { assert(0); return 0; }
StringMeld<MaxPath, ::Assets::ResChar> meld;
meld << "[dyn] " << initializer << (_cellCounter++);
return (DocumentId)_editor->CreateCell(
*_manager,
meld, Float2(-1000.f, -1000.f), Float2( 1000.f, 1000.f));
}
bool PlacementEntities::DeleteDocument(DocumentId doc, DocumentTypeId docType)
{
if (docType != DocumentType_Placements) { assert(0); return false; }
return _editor->RemoveCell(*_manager, doc);
}
ObjectId PlacementEntities::AssignObjectId(DocumentId doc, ObjectTypeId type) const
{
if (type != ObjectType_Placement) { assert(0); return 0; }
return _editor->GenerateObjectGUID();
}
static bool SetObjProperty(
SceneEngine::PlacementsEditor::ObjTransDef& obj,
const PropertyInitializer& prop)
{
if (prop._prop == Property_Transform) {
// note -- putting in a transpose here, because the level editor matrix
// math uses a transposed form
if (prop._elementType == (unsigned)ImpliedTyping::TypeCat::Float && prop._arrayCount >= 16) {
obj._localToWorld = AsFloat3x4(Transpose(*(const Float4x4*)prop._src));
return true;
}
} else if (prop._prop == Property_Model || prop._prop == Property_Material) {
Assets::ResChar buffer[MaxPath];
ucs2_2_utf8(
(const ucs2*)prop._src, prop._arrayCount,
(utf8*)buffer, dimof(buffer));
if (prop._prop == Property_Model) {
obj._model = buffer;
} else {
obj._material = buffer;
}
return true;
}
return false;
}
bool PlacementEntities::CreateObject(
const Identifier& id,
const PropertyInitializer initializers[], size_t initializerCount)
{
if (id.ObjectType() != ObjectType_Placement) { assert(0); return false; }
SceneEngine::PlacementsEditor::ObjTransDef newObj;
newObj._localToWorld = Identity<decltype(newObj._localToWorld)>();
newObj._model = "game/model/nature/bushtree/BushE";
newObj._material = "game/model/nature/bushtree/BushE";
auto guid = SceneEngine::PlacementGUID(id.Document(), id.Object());
auto transaction = _editor->Transaction_Begin(nullptr, nullptr);
if (transaction->Create(guid, newObj)) {
if (initializerCount) {
auto originalObject = transaction->GetObject(0);
bool result = false;
for (size_t c=0; c<initializerCount; ++c)
result |= SetObjProperty(originalObject, initializers[c]);
if (result)
transaction->SetObject(0, originalObject);
}
transaction->Commit();
return true;
}
return false;
}
bool PlacementEntities::DeleteObject(const Identifier& id)
{
if (id.ObjectType() != ObjectType_Placement) { assert(0); return false; }
auto guid = SceneEngine::PlacementGUID(id.Document(), id.Object());
auto transaction = _editor->Transaction_Begin(
&guid, &guid+1,
SceneEngine::PlacementsEditor::TransactionFlags::IgnoreIdTop32Bits);
if (transaction->GetObjectCount()==1) {
transaction->Delete(0);
transaction->Commit();
return true;
}
return false;
}
bool PlacementEntities::SetProperty(
const Identifier& id,
const PropertyInitializer initializers[], size_t initializerCount)
{
// find the object, and set the given property (as per the new value specified in the string)
// We need to create a transaction, make the change and then commit it back.
// If the transaction returns no results, then we must have got a bad object or document id.
if (id.ObjectType() != ObjectType_Placement) { assert(0); return false; }
// note -- This object search is quite slow! We might need a better way to
// record a handle to the object. Perhaps the "ObjectId" should not
// match the actual placements guid. Some short-cut will probably be
// necessary given that we could get there several thousand times during
// startup for an average scene.
auto guid = SceneEngine::PlacementGUID(id.Document(), id.Object());
auto transaction = _editor->Transaction_Begin(
&guid, &guid+1,
SceneEngine::PlacementsEditor::TransactionFlags::IgnoreIdTop32Bits);
if (transaction && transaction->GetObjectCount()==1) {
auto originalObject = transaction->GetObject(0);
bool result = false;
for (size_t c=0; c<initializerCount; ++c) {
result |= SetObjProperty(originalObject, initializers[c]);
}
if (result) {
transaction->SetObject(0, originalObject);
transaction->Commit();
return true;
}
}
return false;
}
bool PlacementEntities::GetProperty(
const Identifier& id, PropertyId prop,
void* dest, unsigned* destSize) const
{
if (id.ObjectType() != ObjectType_Placement) { assert(0); return false; }
if (prop != Property_Transform && prop != Property_Visible
&& prop != Property_Bounds && prop != Property_LocalBounds) { assert(0); return false; }
assert(destSize);
typedef std::pair<Float3, Float3> BoundingBox;
auto guid = SceneEngine::PlacementGUID(id.Document(), id.Object());
auto transaction = _editor->Transaction_Begin(
&guid, &guid+1,
SceneEngine::PlacementsEditor::TransactionFlags::IgnoreIdTop32Bits);
if (transaction->GetObjectCount()==1) {
if (prop == Property_Transform) {
if (*destSize >= sizeof(Float4x4)) {
auto originalObject = transaction->GetObject(0);
// note -- putting in a transpose here, because the level editor matrix
// math uses a transposed form
*(Float4x4*)dest = Transpose(AsFloat4x4(originalObject._localToWorld));
return true;
}
*destSize = sizeof(Float4x4);
} else if (prop == Property_Bounds) {
if (*destSize >= sizeof(BoundingBox)) {
*(BoundingBox*)dest = transaction->GetWorldBoundingBox(0);
return true;
}
*destSize = sizeof(BoundingBox);
} else if (prop == Property_LocalBounds) {
if (*destSize >= sizeof(BoundingBox)) {
*(BoundingBox*)dest = transaction->GetLocalBoundingBox(0);
return true;
}
*destSize = sizeof(BoundingBox);
}
}
return false;
}
bool PlacementEntities::SetParent(const Identifier& child, const Identifier& parent, int insertionPosition)
{
return false;
}
ObjectTypeId PlacementEntities::GetTypeId(const char name[]) const
{
if (!XlCompareString(name, "PlacementObject")) return ObjectType_Placement;
return 0;
}
DocumentTypeId PlacementEntities::GetDocumentTypeId(const char name[]) const
{
if (!XlCompareString(name, "PlacementsDocument")) return DocumentType_Placements;
return 0;
}
PropertyId PlacementEntities::GetPropertyId(ObjectTypeId type, const char name[]) const
{
if (!XlCompareString(name, "transform")) return Property_Transform;
if (!XlCompareString(name, "visible")) return Property_Visible;
if (!XlCompareString(name, "model")) return Property_Model;
if (!XlCompareString(name, "material")) return Property_Material;
if (!XlCompareString(name, "Bounds")) return Property_Bounds;
if (!XlCompareString(name, "LocalBounds")) return Property_LocalBounds;
return 0;
}
ChildListId PlacementEntities::GetChildListId(ObjectTypeId type, const char name[]) const
{
return 0;
}
PlacementEntities::PlacementEntities(
std::shared_ptr<SceneEngine::PlacementsManager> manager,
std::shared_ptr<SceneEngine::PlacementsEditor> editor)
: _manager(std::move(manager))
, _editor(std::move(editor))
, _cellCounter(0)
{}
PlacementEntities::~PlacementEntities() {}
}
| 38.845238 | 111 | 0.607212 | [
"object",
"model",
"transform"
] |
7edcfc3dab91d32cd7f716abbda563986de09ca1 | 10,236 | cpp | C++ | src/gpgmm/vk/ResourceAllocatorVk.cpp | intel/GPGMM | 75b953cb0fc6ffd265eb0a77fab36bdb6a401e4f | [
"Apache-2.0"
] | 1 | 2022-02-13T15:48:36.000Z | 2022-02-13T15:48:36.000Z | src/gpgmm/vk/ResourceAllocatorVk.cpp | intel/GPGMM | 75b953cb0fc6ffd265eb0a77fab36bdb6a401e4f | [
"Apache-2.0"
] | 16 | 2021-10-05T21:32:14.000Z | 2022-03-30T11:39:21.000Z | src/gpgmm/vk/ResourceAllocatorVk.cpp | intel/GPGMM | 75b953cb0fc6ffd265eb0a77fab36bdb6a401e4f | [
"Apache-2.0"
] | null | null | null | // Copyright 2021 The GPGMM Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "gpgmm/vk/ResourceAllocatorVk.h"
#include "gpgmm/common/Debug.h"
#include "gpgmm/common/TraceEvent.h"
#include "gpgmm/vk/BackendVk.h"
#include "gpgmm/vk/CapsVk.h"
#include "gpgmm/vk/DeviceMemoryAllocatorVk.h"
#include "gpgmm/vk/DeviceMemoryVk.h"
#include "gpgmm/vk/ErrorVk.h"
namespace gpgmm { namespace vk {
VkResult gpCreateResourceAllocator(const GpCreateAllocatorInfo& info,
GpResourceAllocator* allocatorOut) {
return GpResourceAllocator_T::CreateAllocator(info, allocatorOut);
}
void gpDestroyResourceAllocator(GpResourceAllocator allocator) {
if (allocator == VK_NULL_HANDLE) {
return;
}
SafeDelete(allocator);
}
VkResult gpCreateBuffer(GpResourceAllocator allocator,
const VkBufferCreateInfo* pBufferCreateInfo,
VkBuffer* bufferOut,
const GpResourceAllocationCreateInfo* pAllocationCreateInfo,
GpResourceAllocation* allocationOut) {
*allocationOut = VK_NULL_HANDLE;
*bufferOut = VK_NULL_HANDLE;
if (allocator == VK_NULL_HANDLE) {
return VK_INCOMPLETE;
}
// Create the buffer.
VkBuffer buffer = VK_NULL_HANDLE;
ReturnIfFailed(
allocator->GetFunctions().CreateBuffer(allocator->GetDevice(), pBufferCreateInfo,
/*allocationCallbacks*/ nullptr, &buffer));
VkMemoryRequirements requirements = {};
allocator->GetBufferMemoryRequirements(buffer, &requirements);
// Create memory for the buffer.
GpResourceAllocation allocation = VK_NULL_HANDLE;
VkResult result =
allocator->TryAllocateMemory(requirements, *pAllocationCreateInfo, &allocation);
if (result != VK_SUCCESS) {
allocator->GetFunctions().DestroyBuffer(allocator->GetDevice(), buffer,
/*allocationCallbacks*/ nullptr);
return result;
}
// Associate memory with the buffer.
result = allocator->GetFunctions().BindBufferMemory(
allocator->GetDevice(), buffer, ToBackend(allocation->GetMemory())->GetDeviceMemory(),
allocation->GetOffset());
if (result != VK_SUCCESS) {
allocator->GetFunctions().DestroyBuffer(allocator->GetDevice(), buffer,
/*allocationCallbacks*/ nullptr);
allocator->DeallocateMemory(allocation);
return result;
}
*allocationOut = allocation;
*bufferOut = buffer;
return VK_SUCCESS;
}
void gpDestroyBuffer(GpResourceAllocator allocator,
VkBuffer buffer,
GpResourceAllocation allocation) {
if (allocator == VK_NULL_HANDLE || buffer == VK_NULL_HANDLE) {
return;
}
allocator->GetFunctions().DestroyBuffer(allocator->GetDevice(), buffer,
/*allocationCallbacks*/ nullptr);
if (allocation == VK_NULL_HANDLE) {
return;
}
allocator->DeallocateMemory(allocation);
}
// GpResourceAllocation_T
GpResourceAllocation_T::GpResourceAllocation_T(const MemoryAllocation& allocation)
: MemoryAllocation(allocation) {
}
// GpResourceAllocator_T
// static
VkResult GpResourceAllocator_T::CreateAllocator(const GpCreateAllocatorInfo& info,
GpResourceAllocator* allocatorOut) {
VulkanFunctions vulkanFunctions = {};
{
if (info.pVulkanFunctions != nullptr) {
vulkanFunctions.ImportDeviceFunctions(info.pVulkanFunctions);
} else {
#if defined(GPGMM_STATIC_VULKAN_FUNCTIONS)
vulkanFunctions.ImportDeviceFunctions();
#else // GPGMM_DYNAMIC_VULKAN_FUNCTIONS
vulkanFunctions.LoadInstanceFunctions(info.instance);
vulkanFunctions.LoadDeviceFunctions(info.device);
#endif
}
#ifndef NDEBUG
vulkanFunctions.AssertVulkanFunctionsAreValid();
#endif
}
std::unique_ptr<Caps> caps;
{
Caps* ptr = nullptr;
ReturnIfFailed(Caps::CreateCaps(info.physicalDevice, vulkanFunctions,
info.vulkanApiVersion, &ptr));
caps.reset(ptr);
}
if (allocatorOut != VK_NULL_HANDLE) {
*allocatorOut = new GpResourceAllocator_T(info, vulkanFunctions, std::move(caps));
}
return VK_SUCCESS;
}
GpResourceAllocator_T::GpResourceAllocator_T(const GpCreateAllocatorInfo& info,
const VulkanFunctions& vulkanFunctions,
std::unique_ptr<Caps> caps)
: mDevice(info.device), mVulkanFunctions(vulkanFunctions), mCaps(std::move(caps)) {
VkPhysicalDeviceMemoryProperties memoryProperties = {};
mVulkanFunctions.GetPhysicalDeviceMemoryProperties(info.physicalDevice, &memoryProperties);
{
mMemoryTypes.assign(memoryProperties.memoryTypes,
memoryProperties.memoryTypes + memoryProperties.memoryTypeCount);
std::vector<VkMemoryHeap> memoryHeaps;
memoryHeaps.assign(memoryProperties.memoryHeaps,
memoryProperties.memoryHeaps + memoryProperties.memoryHeapCount);
for (uint32_t memoryTypeIndex = 0; memoryTypeIndex < mMemoryTypes.size();
memoryTypeIndex++) {
mDeviceAllocatorsPerType.emplace_back(std::make_unique<DeviceMemoryAllocator>(
this, memoryTypeIndex,
memoryHeaps[mMemoryTypes[memoryTypeIndex].heapIndex].size));
}
}
}
VkResult GpResourceAllocator_T::FindMemoryTypeIndex(
uint32_t memoryTypeBits,
const GpResourceAllocationCreateInfo& allocationInfo,
uint32_t* memoryTypeIndexOut) {
*memoryTypeIndexOut = UINT32_MAX;
const VkFlags& requiredPropertyFlags = allocationInfo.requiredPropertyFlags;
uint32_t bestMemoryTypeIndex = UINT32_MAX;
for (uint32_t memoryTypeIndex = 0; memoryTypeIndex < mMemoryTypes.size();
++memoryTypeIndex) {
const VkMemoryPropertyFlags& currPropertyFlags =
mMemoryTypes[memoryTypeIndex].propertyFlags;
// Memory type must be acceptable for this memoryTypeBits.
if ((memoryTypeBits & (1 << memoryTypeIndex)) == 0) {
continue;
}
// Memory type must have all the required property flags.
if ((currPropertyFlags & requiredPropertyFlags) != requiredPropertyFlags) {
continue;
}
// Found the first candidate memory type
if (*memoryTypeIndexOut == UINT32_MAX) {
bestMemoryTypeIndex = memoryTypeIndex;
continue;
}
}
if (bestMemoryTypeIndex == UINT32_MAX) {
return VK_ERROR_FEATURE_NOT_PRESENT;
}
*memoryTypeIndexOut = bestMemoryTypeIndex;
return VK_SUCCESS;
}
void GpResourceAllocator_T::GetBufferMemoryRequirements(VkBuffer buffer,
VkMemoryRequirements* requirementsOut) {
mVulkanFunctions.GetBufferMemoryRequirements(mDevice, buffer, requirementsOut);
}
VkResult GpResourceAllocator_T::TryAllocateMemory(
const VkMemoryRequirements& requirements,
const GpResourceAllocationCreateInfo& allocationInfo,
GpResourceAllocation* allocationOut) {
uint32_t memoryTypeIndex;
ReturnIfFailed(
FindMemoryTypeIndex(requirements.memoryTypeBits, allocationInfo, &memoryTypeIndex));
MemoryAllocator* allocator = mDeviceAllocatorsPerType[memoryTypeIndex].get();
MEMORY_ALLOCATION_REQUEST request = {};
request.SizeInBytes = requirements.size;
request.Alignment = requirements.alignment;
request.NeverAllocate = (allocationInfo.flags & GP_ALLOCATION_FLAG_NEVER_ALLOCATE_MEMORY);
request.CacheSize = false;
request.AlwaysPrefetch = (allocationInfo.flags & GP_ALLOCATION_FLAG_ALWAYS_PREFETCH_MEMORY);
std::unique_ptr<MemoryAllocation> memoryAllocation = allocator->TryAllocateMemory(request);
if (memoryAllocation == nullptr) {
InfoEvent("GpResourceAllocator.TryAllocateResource",
ALLOCATOR_MESSAGE_ID_ALLOCATOR_FAILED)
<< std::string(allocator->GetTypename()) +
" failed to allocate memory for resource.";
return VK_ERROR_UNKNOWN;
}
*allocationOut = new GpResourceAllocation_T(*memoryAllocation);
return VK_SUCCESS;
}
void GpResourceAllocator_T::DeallocateMemory(GpResourceAllocation allocation) {
if (allocation == VK_NULL_HANDLE) {
return;
}
allocation->GetAllocator()->DeallocateMemory(std::unique_ptr<MemoryAllocation>(allocation));
}
VkDevice GpResourceAllocator_T::GetDevice() const {
return mDevice;
}
VulkanFunctions GpResourceAllocator_T::GetFunctions() const {
return mVulkanFunctions;
}
Caps* GpResourceAllocator_T::GetCaps() const {
return mCaps.get();
}
}} // namespace gpgmm::vk
| 38.337079 | 100 | 0.628273 | [
"vector"
] |
7ede1792dbbfbce2d102074f798ad631cb0a7ed8 | 23,488 | cpp | C++ | Max3D/hoa.3d.map_tilde.cpp | CICM/HoaLibrary-Max | cfe110ff040cfda0dd3547ee7e9ec7c11d6dd3b6 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 71 | 2015-02-23T12:24:05.000Z | 2022-02-15T00:18:30.000Z | Max3D/hoa.3d.map_tilde.cpp | pb5/HoaLibrary-Max | cfe110ff040cfda0dd3547ee7e9ec7c11d6dd3b6 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 13 | 2015-04-22T17:13:53.000Z | 2020-11-12T10:54:29.000Z | Max3D/hoa.3d.map_tilde.cpp | pb5/HoaLibrary-Max | cfe110ff040cfda0dd3547ee7e9ec7c11d6dd3b6 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 8 | 2015-04-11T21:34:51.000Z | 2020-02-29T14:37:53.000Z | /*
// Copyright (c) 2012-2013 Eliott Paris & Pierre Guillot, CICM, Universite Paris 8.
// For information on usage and redistribution, and for a DISCLAIMER OF ALL
// WARRANTIES, see the file, "LICENSE.txt," in this distribution.
*/
/**
@file hoa.3d.map~.cpp
@name hoa.3d.map~
@realname hoa.3d.map~
@type object
@module hoa
@author Julien Colafrancesco, Pierre Guillot, Eliott Paris.
@digest
A 3d ambisonic multisource spatializer
@description
<o>hoa.3d.map~</o> is a tool that encodes several sources in the spherical harmonics domain, it's easy to use and work with the GUI <o>hoa.3d.map</o>. With a single source's configuration you can manage coordinates at signal rate
@discussion
<o>hoa.3d.map~</o> is a tool that encodes several sources in the spherical harmonics domain, it's easy to use and work with the GUI <o>hoa.3d.map</o>. With a single source's configuration you can manage coordinates at signal rate
@category 3d, Ambisonics, MSP
@seealso hoa.2d.map~, hoa.3d.map, hoa.3d.encoder~, hoa.3d.decoder~, hoa.3d.optim~, hoa.3d.scope~, hoa.3d.wider~
*/
#include "Hoa3D.max.h"
typedef struct _hoa_3d_map
{
t_pxobject f_ob;
Encoder<Hoa3d, t_sample>::Multi* f_map;
PolarLines<Hoa3d, t_sample>* f_lines;
t_sample* f_sig_ins;
t_sample* f_sig_outs;
t_sample* f_lines_vector;
double f_ramp;
int f_mode;
} t_hoa_3d_map;
t_class *hoa_3d_map_class;
t_hoa_err hoa_getinfos(t_hoa_3d_map* x, t_hoa_boxinfos* boxinfos)
{
boxinfos->object_type = HOA_OBJECT_3D;
boxinfos->autoconnect_inputs = x->f_map->getNumberOfSources();
boxinfos->autoconnect_outputs = x->f_map->getNumberOfHarmonics();
boxinfos->autoconnect_inputs_type = HOA_CONNECT_TYPE_STANDARD;
boxinfos->autoconnect_outputs_type = HOA_CONNECT_TYPE_AMBISONICS;
return HOA_ERR_NONE;
}
void hoa_3d_map_assist(t_hoa_3d_map *x, void *b, long m, long a, char *s)
{
if(m == ASSIST_INLET)
{
if(x->f_map->getNumberOfSources() == 1)
{
if(a == 0)
sprintf(s,"(signal) Input");
else if(a == 1)
sprintf(s,"(signal/float) Radius");
else if(a == 2)
sprintf(s,"(signal/float) Azimuth");
else
sprintf(s,"(signal/float) Elevation");
}
else
{
if(a == 0)
sprintf(s,"(signal and messages) Input 0 and sources coordinates");
else
sprintf(s,"(signal/float) Input %ld", a);
}
}
else
{
sprintf(s,"(signal) %s", x->f_map->getHarmonicName(a).c_str());
}
}
void hoa_3d_map_free(t_hoa_3d_map *x)
{
dsp_free((t_pxobject *)x);
delete x->f_lines;
delete x->f_map;
delete [] x->f_sig_ins;
delete [] x->f_sig_outs;
delete [] x->f_lines_vector;
}
void *hoa_3d_map_new(t_symbol *s, long argc, t_atom *argv)
{
// @arg 0 @name decomposition-order @optional 0 @type int @digest The ambisonic order of decomposition
// @description First argument is the ambisonic order of decomposition.
// @arg 1 @name number-of-sources @optional 0 @type int @digest The number of sources
// @description Second argument is the number of sources to spatialize.
// If there is a single source, <o>hoa.2d.map~</o> object owns 4 inlets, the first one correspond to the signal to encode, the three other ones can be used to control source position at control or signal rate. If you have more than one source to spatialize, the number of signal inlets will be equal to the number of sources to encode, and coordinates will be given with list messages.
t_hoa_3d_map *x = (t_hoa_3d_map *)object_alloc(hoa_3d_map_class);
if (x)
{
ulong order = 1;
ulong numberOfSources = 1;
if(argc && atom_gettype(argv) == A_LONG)
order = max<long>(atom_getlong(argv), 0);
if(argc > 1 && atom_gettype(argv+1) == A_LONG)
numberOfSources = Math<long>::clip(atom_getlong(argv+1), 1, HOA_MAX_PLANEWAVES);
x->f_mode = 0;
if(argc > 2 && atom_gettype(argv+2) == A_SYM)
{
if(atom_getsym(argv+2) == hoa_sym_car || atom_getsym(argv+2) == hoa_sym_cartesian)
x->f_mode = 1;
}
x->f_ramp = 100;
x->f_map = new Encoder<Hoa3d, t_sample>::Multi(order, numberOfSources);
x->f_lines = new PolarLines<Hoa3d, t_sample>(x->f_map->getNumberOfSources());
x->f_lines->setRamp((ulong)(0.1 * sys_getsr()));
for (int i = 0; i < x->f_map->getNumberOfSources(); i++)
{
x->f_lines->setRadiusDirect(i, 1);
x->f_lines->setAzimuthDirect(i, 0.);
x->f_lines->setElevationDirect(i, 0);
}
if(x->f_map->getNumberOfSources() == 1)
dsp_setup((t_pxobject *)x, 4);
else
dsp_setup((t_pxobject *)x, x->f_map->getNumberOfSources());
for (int i = 0; i < x->f_map->getNumberOfHarmonics(); i++)
outlet_new(x, "signal");
if(x->f_map->getNumberOfSources() == 1)
x->f_sig_ins = new t_sample[4 * HOA_MAXBLKSIZE];
else
x->f_sig_ins = new t_sample[x->f_map->getNumberOfSources() * HOA_MAXBLKSIZE];
x->f_sig_outs = new t_sample[x->f_map->getNumberOfHarmonics() * HOA_MAXBLKSIZE];
x->f_lines_vector = new t_sample[x->f_map->getNumberOfSources() * 3];
attr_args_process(x, argc, argv);
}
return (x);
}
void hoa_3d_map_float(t_hoa_3d_map *x, double f)
{
if(x->f_map->getNumberOfSources() == 1)
{
if(x->f_mode == 0)
{
if(proxy_getinlet((t_object *)x) == 1)
{
x->f_lines->setRadius(0, max<double>(f, 0.));
}
else if(proxy_getinlet((t_object *)x) == 2)
{
x->f_lines->setAzimuth(0, f);
}
else if(proxy_getinlet((t_object *)x) == 3)
{
x->f_lines->setElevation(0, f);
}
}
else if(x->f_mode == 1)
{
if(proxy_getinlet((t_object *)x) == 1)
{
float abs = f;
float ord = Math<float>::ordinate(x->f_lines->getRadius(0), x->f_lines->getAzimuth(0), x->f_lines->getElevation(0));
float hei = Math<float>::height(x->f_lines->getRadius(0), x->f_lines->getAzimuth(0), x->f_lines->getElevation(0));
x->f_lines->setRadius(0, Math<float>::radius(abs, ord, hei));
x->f_lines->setAzimuth(0, Math<float>::azimuth(abs, ord, hei));
x->f_lines->setElevation(0, Math<float>::elevation(abs, ord, hei));
}
else if(proxy_getinlet((t_object *)x) == 2)
{
float abs = Math<float>::abscissa(x->f_lines->getRadius(0), x->f_lines->getAzimuth(0), x->f_lines->getElevation(0));
float ord = f;
float hei = Math<float>::height(x->f_lines->getRadius(0), x->f_lines->getAzimuth(0), x->f_lines->getElevation(0));
x->f_lines->setRadius(0, Math<float>::radius(abs, ord, hei));
x->f_lines->setAzimuth(0, Math<float>::azimuth(abs, ord, hei));
x->f_lines->setElevation(0, Math<float>::elevation(abs, ord, hei));
}
else if(proxy_getinlet((t_object *)x) == 3)
{
float abs = Math<float>::abscissa(x->f_lines->getRadius(0), x->f_lines->getAzimuth(0), x->f_lines->getElevation(0));
float ord = Math<float>::ordinate(x->f_lines->getRadius(0), x->f_lines->getAzimuth(0), x->f_lines->getElevation(0));
float hei = f;
x->f_lines->setRadius(0, Math<float>::radius(abs, ord, hei));
x->f_lines->setAzimuth(0, Math<float>::azimuth(abs, ord, hei));
x->f_lines->setElevation(0, Math<float>::elevation(abs, ord, hei));
}
}
}
}
void hoa_3d_map_int(t_hoa_3d_map *x, long n)
{
hoa_3d_map_float(x, n);
}
t_max_err ramp_set(t_hoa_3d_map *x, t_object *attr, long argc, t_atom *argv)
{
if(argc && argv && atom_isNumber(argv))
{
x->f_ramp = max<double>(atom_getfloat(argv), 0);
x->f_lines->setRamp((ulong)(x->f_ramp / 1000. * sys_getsr()));
}
return MAX_ERR_NONE;
}
void hoa_3d_map_list(t_hoa_3d_map *x, t_symbol* s, long argc, t_atom* argv)
{
if(argc > 2 && argv && atom_gettype(argv) == A_LONG && argv+1 && atom_gettype(argv+1) == A_SYM)
{
int index = atom_getlong(argv);
if(index < 1 || index > x->f_map->getNumberOfSources())
return;
if(argc > 4 && (atom_getsym(argv+1) == hoa_sym_polar || atom_getsym(argv+1) == hoa_sym_pol))
{
x->f_lines->setRadius(index-1, atom_getfloat(argv+2));
x->f_lines->setAzimuth(index-1, atom_getfloat(argv+3));
x->f_lines->setElevation(index-1, atom_getfloat(argv+4));
}
else if(argc > 4 && (atom_getsym(argv+1) == hoa_sym_cartesian || atom_getsym(argv+1) == hoa_sym_car))
{
x->f_lines->setRadius(index-1, Math<float>::radius(atom_getfloat(argv+2), atom_getfloat(argv+3), atom_getfloat(argv+4)));
x->f_lines->setAzimuth(index-1, Math<float>::azimuth(atom_getfloat(argv+2), atom_getfloat(argv+3), atom_getfloat(argv+4)));
x->f_lines->setElevation(index-1, Math<float>::elevation(atom_getfloat(argv+2), atom_getfloat(argv+3), atom_getfloat(argv+4)));
}
else if(argc > 2 && atom_getsym(argv+1) == hoa_sym_mute)
{
x->f_map->setMute(index-1, atom_getlong(argv+2));
}
}
}
void hoa_3d_map_perform64_multisources(t_hoa_3d_map *x, t_object *dsp64, double **ins, long numins, double **outs, long numouts, long sampleframes, long flags, void *userparam)
{
int nsources = x->f_map->getNumberOfSources();
for(int i = 0; i < numins; i++)
{
Signal<t_sample>::copy(sampleframes, ins[i], 1, x->f_sig_ins+i, numins);
}
for(int i = 0; i < sampleframes; i++)
{
x->f_lines->process(x->f_lines_vector);
for(int j = 0; j < nsources; j++)
x->f_map->setRadius(j, x->f_lines_vector[j]);
for(int j = 0; j < nsources; j++)
x->f_map->setAzimuth(j, x->f_lines_vector[j + nsources]);
for(int j = 0; j < nsources; j++)
x->f_map->setElevation(j, x->f_lines_vector[j + nsources * 2]);
x->f_map->process(x->f_sig_ins + numins * i, x->f_sig_outs + numouts * i);
}
for(int i = 0; i < numouts; i++)
{
Signal<t_sample>::copy(sampleframes, x->f_sig_outs+i, numouts, outs[i], 1);
}
}
void hoa_3d_map_perform_in1_in2_in3(t_hoa_3d_map *x, t_object *dsp64, double **ins, long numins, double **outs, long numouts, long sampleframes, long flags, void *userparam)
{
for(int i = 0; i < sampleframes; i++)
{
if(x->f_mode == 0)
{
x->f_map->setRadius(0, ins[1][i]);
x->f_map->setAzimuth(0, ins[2][i]);
x->f_map->setElevation(0, ins[3][i]);
}
else if(x->f_mode == 1)
{
x->f_map->setAzimuth(0, Math<t_sample>::azimuth(ins[1][i], ins[2][i], ins[3][i]));
x->f_map->setRadius(0, Math<t_sample>::radius(ins[1][i], ins[2][i], ins[3][i]));
x->f_map->setElevation(0, Math<t_sample>::elevation(ins[1][i], ins[2][i], ins[3][i]));
}
x->f_map->process(&ins[0][i], x->f_sig_outs + numouts * i);
}
for(int i = 0; i < numouts; i++)
{
Signal<t_sample>::copy(sampleframes, x->f_sig_outs+i, numouts, outs[i], 1);
}
}
void hoa_3d_map_perform_in1_in2(t_hoa_3d_map *x, t_object *dsp64, double **ins, long numins, double **outs, long numouts, long sampleframes, long flags, void *userparam)
{
for(int i = 0; i < sampleframes; i++)
{
x->f_lines->process(x->f_lines_vector);
if(x->f_mode == 0)
{
x->f_map->setRadius(0, ins[1][i]);
x->f_map->setAzimuth(0, ins[2][i]);
x->f_map->setElevation(0, x->f_lines_vector[2]);
}
else if(x->f_mode == 1)
{
x->f_map->setAzimuth(0, Math<t_sample>::azimuth(ins[1][i], ins[2][i], x->f_lines_vector[2]));
x->f_map->setRadius(0, Math<t_sample>::radius(ins[1][i], ins[2][i], x->f_lines_vector[2]));
x->f_map->setElevation(0, Math<t_sample>::elevation(ins[1][i], ins[2][i], x->f_lines_vector[2]));
}
x->f_map->process(&ins[0][i], x->f_sig_outs + numouts * i);
}
for(int i = 0; i < numouts; i++)
{
Signal<t_sample>::copy(sampleframes, x->f_sig_outs+i, numouts, outs[i], 1);
}
}
void hoa_3d_map_perform_in1_in3(t_hoa_3d_map *x, t_object *dsp64, double **ins, long numins, double **outs, long numouts, long sampleframes, long flags, void *userparam)
{
for(int i = 0; i < sampleframes; i++)
{
x->f_lines->process(x->f_lines_vector);
if(x->f_mode == 0)
{
x->f_map->setRadius(0, ins[1][i]);
x->f_map->setAzimuth(0, x->f_lines_vector[1]);
x->f_map->setElevation(0, ins[3][i]);
}
else if(x->f_mode == 1)
{
x->f_map->setAzimuth(0, Math<t_sample>::azimuth(ins[1][i], x->f_lines_vector[1], ins[3][i]));
x->f_map->setRadius(0, Math<t_sample>::radius(ins[1][i], x->f_lines_vector[1], ins[3][i]));
x->f_map->setElevation(0, Math<t_sample>::elevation(ins[1][i], x->f_lines_vector[1], ins[3][i]));
}
x->f_map->process(&ins[0][i], x->f_sig_outs + numouts * i);
}
for(int i = 0; i < numouts; i++)
{
Signal<t_sample>::copy(sampleframes, x->f_sig_outs+i, numouts, outs[i], 1);
}
}
void hoa_3d_map_perform_in2_in3(t_hoa_3d_map *x, t_object *dsp64, double **ins, long numins, double **outs, long numouts, long sampleframes, long flags, void *userparam)
{
for(int i = 0; i < sampleframes; i++)
{
x->f_lines->process(x->f_lines_vector);
if(x->f_mode == 0)
{
x->f_map->setRadius(0, x->f_lines_vector[0]);
x->f_map->setAzimuth(0, ins[2][i]);
x->f_map->setElevation(0, ins[3][i]);
}
else if(x->f_mode == 1)
{
x->f_map->setAzimuth(0, Math<t_sample>::azimuth(x->f_lines_vector[0], ins[2][i], ins[3][i]));
x->f_map->setRadius(0, Math<t_sample>::radius(x->f_lines_vector[0], ins[2][i], ins[3][i]));
x->f_map->setElevation(0, Math<t_sample>::elevation(x->f_lines_vector[0], ins[2][i], ins[3][i]));
}
x->f_map->process(&ins[0][i], x->f_sig_outs + numouts * i);
}
for(int i = 0; i < numouts; i++)
{
Signal<t_sample>::copy(sampleframes, x->f_sig_outs+i, numouts, outs[i], 1);
}
}
void hoa_3d_map_perform_in1(t_hoa_3d_map *x, t_object *dsp64, double **ins, long numins, double **outs, long numouts, long sampleframes, long flags, void *userparam)
{
for(int i = 0; i < sampleframes; i++)
{
x->f_lines->process(x->f_lines_vector);
if(x->f_mode == 0)
{
x->f_map->setRadius(0, ins[1][i]);
x->f_map->setAzimuth(0, x->f_lines_vector[1]);
x->f_map->setElevation(0, x->f_lines_vector[2]);
}
else if(x->f_mode == 1)
{
x->f_map->setAzimuth(0, Math<t_sample>::azimuth(ins[1][i], x->f_lines_vector[1], x->f_lines_vector[2]));
x->f_map->setRadius(0, Math<t_sample>::radius(ins[1][i], x->f_lines_vector[1], x->f_lines_vector[2]));
x->f_map->setElevation(0, Math<t_sample>::elevation(ins[1][i], x->f_lines_vector[1], x->f_lines_vector[2]));
}
x->f_map->process(&ins[0][i], x->f_sig_outs + numouts * i);
}
for(int i = 0; i < numouts; i++)
{
Signal<t_sample>::copy(sampleframes, x->f_sig_outs+i, numouts, outs[i], 1);
}
}
void hoa_3d_map_perform_in2(t_hoa_3d_map *x, t_object *dsp64, double **ins, long numins, double **outs, long numouts, long sampleframes, long flags, void *userparam)
{
for(int i = 0; i < sampleframes; i++)
{
x->f_lines->process(x->f_lines_vector);
if(x->f_mode == 0)
{
x->f_map->setRadius(0, x->f_lines_vector[0]);
x->f_map->setAzimuth(0, ins[2][i]);
x->f_map->setElevation(0, x->f_lines_vector[2]);
}
else if(x->f_mode == 1)
{
x->f_map->setAzimuth(0, Math<t_sample>::azimuth(x->f_lines_vector[0], ins[2][i], x->f_lines_vector[2]));
x->f_map->setRadius(0, Math<t_sample>::radius(x->f_lines_vector[0], ins[2][i], x->f_lines_vector[2]));
x->f_map->setElevation(0, Math<t_sample>::elevation(x->f_lines_vector[0], ins[2][i], x->f_lines_vector[2]));
}
x->f_map->process(&ins[0][i], x->f_sig_outs + numouts * i);
}
for(int i = 0; i < numouts; i++)
{
Signal<t_sample>::copy(sampleframes, x->f_sig_outs+i, numouts, outs[i], 1);
}
}
void hoa_3d_map_perform_in3(t_hoa_3d_map *x, t_object *dsp64, double **ins, long numins, double **outs, long numouts, long sampleframes, long flags, void *userparam)
{
for(int i = 0; i < sampleframes; i++)
{
x->f_lines->process(x->f_lines_vector);
if(x->f_mode == 0)
{
x->f_map->setRadius(0, x->f_lines_vector[0]);
x->f_map->setAzimuth(0, x->f_lines_vector[1]);
x->f_map->setElevation(0, ins[3][i]);
}
else if(x->f_mode == 1)
{
x->f_map->setAzimuth(0, Math<t_sample>::azimuth(x->f_lines_vector[0], x->f_lines_vector[1], ins[3][i]));
x->f_map->setRadius(0, Math<t_sample>::radius(x->f_lines_vector[0], x->f_lines_vector[1], ins[3][i]));
x->f_map->setElevation(0, Math<t_sample>::elevation(x->f_lines_vector[0], x->f_lines_vector[1], ins[3][i]));
}
x->f_map->process(&ins[0][i], x->f_sig_outs + numouts * i);
}
for(int i = 0; i < numouts; i++)
{
Signal<t_sample>::copy(sampleframes, x->f_sig_outs+i, numouts, outs[i], 1);
}
}
void hoa_3d_map_perform(t_hoa_3d_map *x, t_object *dsp64, double **ins, long numins, double **outs, long numouts, long sampleframes, long flags, void *userparam)
{
for(int i = 0; i < sampleframes; i++)
{
x->f_lines->process(x->f_lines_vector);
x->f_map->setRadius(0, x->f_lines_vector[0]);
x->f_map->setAzimuth(0, x->f_lines_vector[1]);
x->f_map->setElevation(0, x->f_lines_vector[2]);
x->f_map->process(&ins[0][i], x->f_sig_outs + numouts * i);
}
for(int i = 0; i < numouts; i++)
{
Signal<t_sample>::copy(sampleframes, x->f_sig_outs+i, numouts, outs[i], 1);
}
}
void hoa_3d_map_perform_multisources(t_hoa_3d_map *x, t_object *dsp64, double **ins, long numins, double **outs, long numouts, long sampleframes, long flags, void *userparam)
{
int nsources = x->f_map->getNumberOfSources();
for(int i = 0; i < numins; i++)
{
Signal<t_sample>::copy(sampleframes, ins[i], 1, x->f_sig_ins+i, numins);
}
for(int i = 0; i < sampleframes; i++)
{
x->f_lines->process(x->f_lines_vector);
for(int j = 0; j < nsources; j++)
x->f_map->setRadius(j, x->f_lines_vector[j]);
for(int j = 0; j < nsources; j++)
x->f_map->setAzimuth(j, x->f_lines_vector[j + nsources]);
for(int j = 0; j < nsources; j++)
x->f_map->setElevation(j, x->f_lines_vector[j + nsources * 2]);
x->f_map->process(x->f_sig_ins + numins * i, x->f_sig_outs + numouts * i);
}
for(int i = 0; i < numouts; i++)
{
Signal<t_sample>::copy(sampleframes, x->f_sig_outs+i, numouts, outs[i], 1);
}
}
void hoa_3d_map_dsp64(t_hoa_3d_map *x, t_object *dsp64, short *count, double samplerate, long maxvectorsize, long flags)
{
x->f_lines->setRamp((ulong)(x->f_ramp / 1000. * samplerate));
if(x->f_map->getNumberOfSources() == 1)
{
if(count[1] && count[2] && count[3])
object_method(dsp64, gensym("dsp_add64"), x, (method)hoa_3d_map_perform_in1_in2_in3, 0, NULL);
else if(count[1] && count[2] && !count[3])
object_method(dsp64, gensym("dsp_add64"), x, (method)hoa_3d_map_perform_in1_in2, 0, NULL);
else if(count[1] && !count[2] && count[3])
object_method(dsp64, gensym("dsp_add64"), x, (method)hoa_3d_map_perform_in1_in3, 0, NULL);
else if(!count[1] && count[2] && count[3])
object_method(dsp64, gensym("dsp_add64"), x, (method)hoa_3d_map_perform_in1_in3, 0, NULL);
else if(count[1] && !count[2])
object_method(dsp64, gensym("dsp_add64"), x, (method)hoa_3d_map_perform_in1, 0, NULL);
else if(!count[1] && count[2])
object_method(dsp64, gensym("dsp_add64"), x, (method)hoa_3d_map_perform_in2, 0, NULL);
else if(!count[1] && count[2])
object_method(dsp64, gensym("dsp_add64"), x, (method)hoa_3d_map_perform_in3, 0, NULL);
else if(!count[1] && !count[2] && !count[3])
object_method(dsp64, gensym("dsp_add64"), x, (method)hoa_3d_map_perform, 0, NULL);
}
else
{
object_method(dsp64, gensym("dsp_add64"), x, (method)hoa_3d_map_perform_multisources, 0, NULL);
}
}
#ifdef HOA_PACKED_LIB
int hoa_3d_map_main(void)
#else
void ext_main(void *r)
#endif
{
t_class *c;
c = class_new("hoa.3d.map~", (method)hoa_3d_map_new, (method)hoa_3d_map_free, (long)sizeof(t_hoa_3d_map), 0L, A_GIMME, 0);
class_setname((char *)"hoa.3d.map~", (char *)"hoa.3d.map~");
hoa_initclass(c, (method)hoa_getinfos);
// @method float @digest Set single source coordinate with messages depending on the mode.
// @description Set single source coordinate with messages depending on the mode.
// @marg 0 @name coord @optional 0 @type float
class_addmethod(c, (method)hoa_3d_map_float, "float", A_FLOAT, 0);
// @method int @digest Set single source coordinate with messages depending on the mode.
// @description Set single source coordinate with messages depending on the mode.
// @marg 0 @name coord @optional 0 @type int
class_addmethod(c, (method)hoa_3d_map_int, "int", A_LONG, 0);
// @method list @digest Send source messages (coordinates and mute state).
// @description Send source messages like coordinates and mute state. The list must be formatted like this : source-index input-mode radius azimuth elevation to set source positions or like this : source-index 'mute' mute-state to set the mute state of a source.
// marg 0 @name source-index @optional 0 @type int
// marg 1 @name input-mode/mute @optional 0 @type symbol
// marg 2 @name coord-1/mute-state @optional 0 @type float/int
// marg 3 @name coord-2 @optional 0 @type float
// marg 4 @name coord-3 @optional 0 @type float
class_addmethod(c, (method)hoa_3d_map_list, "list", A_GIMME, 0);
// @method signal @digest Sources signals to encode.
// @description If you have a single source, the first signal inlet is for the source to encode, the three other ones are to control source position at signal rate. If you have more than one source to spatialize, all of the inputs represent a signal to encode and coordonates are given with messages.
class_addmethod(c, (method)hoa_3d_map_dsp64, "dsp64", A_CANT, 0);
class_addmethod(c, (method)hoa_3d_map_assist, "assist", A_CANT, 0);
CLASS_ATTR_DOUBLE (c, "ramp", 0, t_hoa_3d_map, f_ramp);
CLASS_ATTR_CATEGORY (c, "ramp", 0, "Behavior");
CLASS_ATTR_LABEL (c, "ramp", 0, "Ramp Time (ms)");
CLASS_ATTR_ORDER (c, "ramp", 0, "1");
CLASS_ATTR_ACCESSORS (c, "ramp", NULL, ramp_set);
// @description The ramp time in milliseconds.
class_dspinit(c);
class_register(CLASS_BOX, c);
hoa_3d_map_class = c;
}
| 40.991274 | 386 | 0.606437 | [
"object",
"3d"
] |
7ee1bde2e3c63a04b0bab553efaac68e77804313 | 1,280 | cpp | C++ | online_judges/cf/1253/b/b.cpp | miaortizma/competitive-programming | ea5adfc07e49935acfc0697eeb0a12c7dc6cd8cc | [
"MIT"
] | 2 | 2018-02-20T14:44:57.000Z | 2018-02-20T14:45:03.000Z | online_judges/cf/1253/b/b.cpp | miaortizma/competitive-programming | ea5adfc07e49935acfc0697eeb0a12c7dc6cd8cc | [
"MIT"
] | null | null | null | online_judges/cf/1253/b/b.cpp | miaortizma/competitive-programming | ea5adfc07e49935acfc0697eeb0a12c7dc6cd8cc | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
const int N = 1e5 + 100, M = 1e6 + 100;
int arr[N], in[M], out[M];
int flag = 0;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(NULL);
int n;
cin >> n;
for (int i = 0; i < n; ++i)
cin >> arr[i];
bool ok = true;
if (n % 2 == 1)
ok = false;
int i = 0;
vector<int> ans;
while (i < n && ok) {
if (arr[i] < 0) {
ok = false;
break;
}
++flag;
in[arr[i]] = flag;
int sum = arr[i];
int left = 1;
int cnt = 0;
while (i < n && sum != 0 && left != 0) {
++i;
int val = abs(arr[i]);
if (arr[i] < 0) {
if (in[val] == flag && out[val] != flag) {
++cnt;
out[val] = flag;
sum += arr[i];
--left;
} else {
ok = false;
i = n;
break;
}
} else {
if (in[val] != flag) {
in[val] = flag;
++left;
sum += arr[i];
} else {
ok = false;
i = n;
break;
}
}
}
if (sum != 0)
ok = false;
ans.push_back(cnt * 2);
++i;
}
if (ok) {
cout << ans.size() << "\n";
for (int v : ans) {
cout << v << " ";
}
} else {
cout << -1;
}
return 0;
}
| 18.285714 | 50 | 0.375 | [
"vector"
] |
7ee24e663daedb0c7fb40d564682070642f24557 | 3,370 | cpp | C++ | tests/window_test/window_secondary_menubar_test.cpp | GuangfuWang/threedbody | 31c544c25e524cecf107a505c3b4438fc04cd766 | [
"BSD-2-Clause"
] | null | null | null | tests/window_test/window_secondary_menubar_test.cpp | GuangfuWang/threedbody | 31c544c25e524cecf107a505c3b4438fc04cd766 | [
"BSD-2-Clause"
] | null | null | null | tests/window_test/window_secondary_menubar_test.cpp | GuangfuWang/threedbody | 31c544c25e524cecf107a505c3b4438fc04cd766 | [
"BSD-2-Clause"
] | null | null | null | #include "imgui.h"
#include "imgui_impl_glfw.h"
#include "imgui_impl_opengl3.h"
#include <stdio.h>
#include <filesystem>
#include <GLFW/glfw3.h> // Will drag system OpenGL headers
#define STB_IMAGE_IMPLEMENTATION
#include <stb_image.h>
#include <iostream>
#include <imgui_internal.h>
int main() {
if (!glfwInit())
return 1;
// GL 3.0 + GLSL 130
const char *glsl_version = "#version 430";
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
//glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // 3.2+ only
//glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // 3.0+ only
GLFWimage image;
std::filesystem::path icon_path = std::filesystem::current_path();
std::filesystem::path parent_path = icon_path.parent_path();
parent_path /= "resources";
parent_path /= "icons";
parent_path /= "window_icons";
parent_path /= "icon_1.png";
std::string icon_1 = parent_path.string();
int comp;
image.pixels = stbi_load(icon_1.c_str(), &image.width, &image.height, &comp, STBI_rgb_alpha);
// image = load_icon("my_icon.png");
//
// Create window with graphics context
GLFWwindow *window = glfwCreateWindow(1280, 720, u8"演示", NULL, NULL);
if (window == NULL)
return 1;
glfwSetWindowIcon(window, 2, &image);
glfwMakeContextCurrent(window);
glfwSwapInterval(1); // Enable vsync
// Setup Dear ImGui context
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO &io = ImGui::GetIO();
// Setup Platform/Renderer backends
ImGui_ImplGlfw_InitForOpenGL(window, true);
ImGui_ImplOpenGL3_Init(glsl_version);
while (!glfwWindowShouldClose(window)) {
glfwPollEvents();
glClearColor(0.45f, 0.55f, 0.60f, 1.00f);
glClear(GL_COLOR_BUFFER_BIT);
// feed inputs to dear imgui, start new frame
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
ImGuiViewportP *viewport = (ImGuiViewportP *) (void *) ImGui::GetMainViewport();
ImGuiWindowFlags window_flags =
ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_MenuBar;
float height = ImGui::GetFrameHeight();
if (ImGui::BeginViewportSideBar("##SecondaryMenuBar", viewport, ImGuiDir_Up, height, window_flags)) {
if (ImGui::BeginMenuBar()) {
ImGui::Text("Happy secondary menu bar");
ImGui::EndMenuBar();
}
}
ImGui::End();
if (ImGui::BeginViewportSideBar("##MainStatusBar", viewport, ImGuiDir_Down, height, window_flags)) {
if (ImGui::BeginMenuBar()) {
ImGui::Text("Happy status bar");
ImGui::EndMenuBar();
}
}
ImGui::End();
ImGui::Render();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
int display_w, display_h;
glfwGetFramebufferSize(window, &display_w, &display_h);
glViewport(0, 0, display_w, display_h);
glfwSwapBuffers(window);
}
ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplGlfw_Shutdown();
ImGui::DestroyContext();
glfwDestroyWindow(window);
glfwTerminate();//清除退出
stbi_image_free(&image.pixels);
return 0;
}
| 28.803419 | 109 | 0.648071 | [
"render"
] |
7eed5e9294a6766035f39542bb8300e021f8d73f | 3,930 | cpp | C++ | NavigationDG/jni/ScaleEstimation/ScaleEstimation_export.cpp | LRMPUT/DiamentowyGrant | e824c5c6442c28f960a42e2507c0eec22f7e9754 | [
"Apache-2.0"
] | 10 | 2015-11-20T18:49:41.000Z | 2021-09-03T04:01:26.000Z | NavigationDGWithSubmodules/OpenAIL/openAILdemo/src/main/jni/ScaleEstimation/ScaleEstimation_export.cpp | LRMPUT/DiamentowyGrant | e824c5c6442c28f960a42e2507c0eec22f7e9754 | [
"Apache-2.0"
] | null | null | null | NavigationDGWithSubmodules/OpenAIL/openAILdemo/src/main/jni/ScaleEstimation/ScaleEstimation_export.cpp | LRMPUT/DiamentowyGrant | e824c5c6442c28f960a42e2507c0eec22f7e9754 | [
"Apache-2.0"
] | 3 | 2015-07-01T09:47:15.000Z | 2018-01-05T04:37:02.000Z | // OpenAIL - Open Android Indoor Localization
// Copyright (C) 2015 Michal Nowicki (michal.nowicki@put.poznan.pl)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <jni.h>
#include <opencv2/core/core.hpp>
#include <vector>
#include "ScaleEKF/ScaleEKF.h"
using namespace std;
using namespace cv;
extern "C" {
//
// Export declarations
//
// Create object
JNIEXPORT jlong JNICALL Java_org_dg_main_scaleEstimation_EKFcreate(JNIEnv*, jobject, jfloat Q,
jfloat R, jfloat dt);
// get estimate
JNIEXPORT jlong JNICALL Java_org_dg_main_scaleEstimation_EKFgetEstimate(JNIEnv*, jobject, jlong addrEKF);
// Predict
JNIEXPORT void JNICALL Java_org_dg_main_scaleEstimation_EKFpredict(JNIEnv*, jobject,
jlong addrEKF, jlong addrW, jfloat dt);
// Update from: Acc, Vision, QR
JNIEXPORT void JNICALL Java_org_dg_main_scaleEstimation_EKFcorrectAcc(JNIEnv*, jobject,
jlong addrEKF, jlong addrZ);
JNIEXPORT void JNICALL Java_org_dg_main_scaleEstimation_EKFcorrectVision(JNIEnv*, jobject,
jlong addrEKF, jlong addrZ);
JNIEXPORT void JNICALL Java_org_dg_main_scaleEstimation_EKFcorrectQR(JNIEnv*, jobject,
jlong addrEKF, jlong addrZ);
// Destroy object
JNIEXPORT void JNICALL Java_org_dg_main_scaleEstimation_EKFdestroy(JNIEnv*, jobject,
jlong addrEKF);
//
// Implementation of export methods
//
JNIEXPORT jlong JNICALL Java_org_dg_main_scaleEstimation_EKFcreate(JNIEnv*, jobject, jfloat Q,
jfloat R, jfloat dt) {
// Create new object
return (long) (new EKF(Q, R, dt));
}
JNIEXPORT jlong JNICALL Java_org_dg_main_scaleEstimation_EKFgestEstimate(JNIEnv*, jobject, jlong addrEKF)
{
EKF &ekf = *(EKF*) addrEKF;
cv::Mat estimate = ekf.getEstimate();
return estimate.at<float>(3);
}
JNIEXPORT void JNICALL Java_org_dg_main_scaleEstimation_EKFpredict(JNIEnv*, jobject,
jlong addrEKF, jlong addrW, jfloat dt) {
// Calling predict
EKF &ekf = *(EKF*) addrEKF;
ekf.predict(dt);
}
JNIEXPORT void JNICALL Java_org_dg_main_scaleEstimation_EKFcorrectAcc(JNIEnv*, jobject,
jlong addrEKF, jlong addrZ) {
// Calling correct
EKF &ekf = *(EKF*) addrEKF;
ekf.correctAcc(addrZ);
}
JNIEXPORT void JNICALL Java_org_dg_main_scaleEstimation_EKFcorrectVison(JNIEnv*, jobject,
jlong addrEKF, jlong addrZ) {
// Calling correct
EKF &ekf = *(EKF*) addrEKF;
ekf.correctVision(addrZ);
}
JNIEXPORT void JNICALL Java_org_dg_main_scaleEstimation_EKFcorrectQR(JNIEnv*, jobject,
jlong addrEKF, jlong addrZ) {
// Calling correct
EKF &ekf = *(EKF*) addrEKF;
ekf.correctQR(addrZ);
}
JNIEXPORT void JNICALL Java_org_dg_main_scaleEstimation_EKFdestroy(JNIEnv* env, jobject,
jlong addrEKF) {
// Destroy object
delete (EKF*) (addrEKF);
}
}
| 31.693548 | 105 | 0.773028 | [
"object",
"vector"
] |
7eed78fd6122ee2e33a87d7ca82d19ec9458f15a | 13,390 | cpp | C++ | mac/SimpleLlc.cpp | willcode/PothosComms | 6c6ae8ccb6a9c996a67e2ca646aff79c74bb83fa | [
"BSL-1.0"
] | 14 | 2017-10-28T08:40:08.000Z | 2022-03-19T06:08:55.000Z | mac/SimpleLlc.cpp | BelmY/PothosComms | 9aa48b827b3813b3ba2b98773f3359b30ebce346 | [
"BSL-1.0"
] | 22 | 2015-08-25T21:18:13.000Z | 2016-12-31T02:23:47.000Z | mac/SimpleLlc.cpp | pothosware/pothos-comms | cff998cca2c9610d3e7e5480fd4fc692c13d3066 | [
"BSL-1.0"
] | 13 | 2018-01-03T15:29:44.000Z | 2022-03-19T06:09:00.000Z | // Copyright (c) 2015-2017 Josh Blum
// SPDX-License-Identifier: BSL-1.0
#include <Pothos/Framework.hpp>
#include <Pothos/Util/RingDeque.hpp>
#include <Pothos/Util/SpinLock.hpp>
#include <thread>
#include <mutex> //lock_guard
#include <chrono>
#include <iostream>
#include <cstdint>
#include <cstring> //memcpy
/***********************************************************************
* |PothosDoc Simple LLC
*
* The Simple LLC block is a simple implementation of a logic link control
* that supports the retransmission of lost data.
* This block is intended to be used with the simple MAC
* to interface between user data and the lower layer MAC.
* The LLC uses imposes an additional packet header over the MAC layer
* to monitor packet flow and to implement control communication.
*
* http://en.wikipedia.org/wiki/Logical_link_control
*
* http://en.wikipedia.org/wiki/Go-Back-N_ARQ
*
* <h3>Ports</h3>
* Multiple LLC blocks can be connected to a single MAC block,
* using the port number to differentiate between data channels.
* The port number is used for both source and destination addressing.
* Communicating pairs of LLC blocks should use the same port number.
*
* <h2>Interfaces</h2>
* The Simple LLC block has 4 ports that operate on packet streams:
* <ul>
* <li><b>dataIn</b> - This port accepts a packet of user data.</li>
* <li><b>macOut</b> - This port produces a packet intended for the macIn port on the Simple MAC block.
* This packet may contain user data or control data with an additional LLC header appended.
* The packet metadata has the "recipient" field set to the remote destination MAC.</li>
* <li><b>macIn</b> - This port accepts a packet from the macOut port on the Simple MAC block.
* The LLC header is inspected for destination port, control information, and user data.</li>
* <li><b>dataOut</b> - This port produces a packet of user data.</li>
* </ul>
*
* |category /MAC
* |keywords LLC MAC packet
* |alias /blocks/simple_llc
*
* |param port[Port Number] The port number that this LLC will servicing.
* The port number is 8-bits and should match the port of the remote LLC.
* |default 0
*
* |param recipient[Recipient ID] The 16-bit ID of the remote destination MAC.
* |default 0
*
* |param resendTimeout[Resend Timeout] Timeout in seconds before re-sending the outgoing packet.
* The LLC will resend any packets that have not been acknowledged within this time window.
* |default 0.01
* |units seconds
*
* |param expireTimeout[Expire Timeout] Maximum time in seconds that LLC can hold a packet.
* The LLC will try to guarantee delivery of a packet by resending within this time window.
* |default 0.1
* |units seconds
*
* |param windowSize[Window Size] The number of packets allowed out before an acknowledgment is required.
* |default 4
*
* |factory /comms/simple_llc()
* |setter setPort(port)
* |setter setRecipient(recipient)
* |setter setResendTimeout(resendTimeout)
* |setter setExpireTimeout(expireTimeout)
* |setter setWindowSize(windowSize)
**********************************************************************/
class SimpleLlc : public Pothos::Block
{
static const uint8_t PSH = 0x1; //push data packet type
static const uint8_t REQ = 0x4; //request packet type
static const uint8_t SYN = 0x8; //synchronize sequence
public:
SimpleLlc(void):
_resendCount(0),
_expiredCount(0),
_port(0),
_recipient(0),
_windowSize(0),
_seqBase(0),
_seqOut(0),
_reqSeq(0),
_resendMsg(1)
{
this->setupInput("macIn");
this->setupInput("dataIn");
this->setupOutput("macOut");
this->setupOutput("dataOut");
this->registerCall(this, POTHOS_FCN_TUPLE(SimpleLlc, setPort));
this->registerCall(this, POTHOS_FCN_TUPLE(SimpleLlc, setRecipient));
this->registerCall(this, POTHOS_FCN_TUPLE(SimpleLlc, setResendTimeout));
this->registerCall(this, POTHOS_FCN_TUPLE(SimpleLlc, setExpireTimeout));
this->registerCall(this, POTHOS_FCN_TUPLE(SimpleLlc, setWindowSize));
this->registerCall(this, POTHOS_FCN_TUPLE(SimpleLlc, getResendCount));
this->registerCall(this, POTHOS_FCN_TUPLE(SimpleLlc, getExpiredCount));
this->registerProbe("getResendCount");
this->registerProbe("getExpiredCount");
this->setWindowSize(4); //initial state
this->setRecipient(0); //initial state
this->setResendTimeout(0.01); //initial state
this->setExpireTimeout(0.1); //initial state
}
static Block *make(void)
{
return new SimpleLlc();
}
void activate(void)
{
//we must be able to synchronize to any random starting sequence
_reqSeq = std::rand() & 0xffff;
_seqBase = std::rand() & 0xffff;
_seqOut = _seqBase;
//grab pointers to the ports
_macIn = this->input("macIn");
_dataIn = this->input("dataIn");
_macOut = this->output("macOut");
_dataOut = this->output("dataOut");
//start the monitor thread
_monitorThread = std::thread(&SimpleLlc::monitorTimeoutsTask, this);
}
void deactivate(void)
{
_monitorThread.join();
}
void monitorTimeoutsTask(void)
{
while (this->isActive())
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
const auto timeNow = std::chrono::high_resolution_clock::now();
std::lock_guard<Pothos::Util::SpinLock> lock(_lock);
//remove expired packets, oldest to newest
while (not _sentPackets.empty() and _sentPackets.front().expiredTime < timeNow)
{
_sentPackets.pop_front();
_seqBase++;
_expiredCount++;
}
//check if the oldest packet should cause full resend
if (_sentPackets.empty()) continue;
const auto delta = timeNow - _sentPackets.front().lastSentTime;
if (delta > _resendTimeout) _macIn->pushMessage(_resendMsg);
}
}
void setRecipient(const uint16_t recipient)
{
_recipient = recipient;
_metadata["recipient"] = Pothos::Object(_recipient);
}
void setPort(const uint16_t port)
{
_port = port;
}
void setResendTimeout(const double timeout)
{
_resendTimeout = std::chrono::duration_cast<std::chrono::high_resolution_clock::duration>(std::chrono::nanoseconds(long(timeout*1e9)));
}
void setExpireTimeout(const double timeout)
{
_expireTimeout = std::chrono::duration_cast<std::chrono::high_resolution_clock::duration>(std::chrono::nanoseconds(long(timeout*1e9)));
}
void setWindowSize(const size_t windowSize)
{
_windowSize = windowSize;
_sentPackets.set_capacity(_windowSize);
}
unsigned long long getResendCount(void) const
{
return _resendCount;
}
unsigned long long getExpiredCount(void) const
{
return _expiredCount;
}
void work(void)
{
// handle incoming data from MAC
while (_macIn->hasMessage())
{
auto msg = _macIn->popMessage();
//handle the resend message from the timeout monitor thread
if (msg == _resendMsg)
{
this->resendPackets();
continue;
}
//extract the packet
const auto &pkt = msg.extract<Pothos::Packet>();
if (pkt.payload.length < 4) continue;
const uint8_t *byteBuf = pkt.payload;
//parse the header
uint8_t port = 0;
uint16_t nonce = 0;
uint8_t control = 0;
extractHeader(byteBuf, port, nonce, control);
//was this packet intended for this LLC?
if(port != _port) continue;
//got a synchronize packet from sender
if ((control & SYN) != 0) _reqSeq = nonce;
//got a datagram packet from sender
if((control & PSH) != 0)
{
//got the expected sequence, forward the packet
if (nonce == _reqSeq)
{
auto pktOut = pkt;
pktOut.payload.address += 4;
pktOut.payload.length -= 4;
_dataOut->postMessage(std::move(pktOut));
_reqSeq++;
}
//always reply with a request
postControlPacket(_reqSeq, REQ);
}
//got a request packet from receiver
if((control & REQ) != 0)
{
std::lock_guard<Pothos::Util::SpinLock> lock(_lock);
//check for sequence obviously out of range and request resync
if (nonce < _seqBase or nonce > _seqOut)
{
this->postControlPacket(_seqBase, SYN);
}
//otherwise clear everything sent up to but not including the latest request
else for (; _seqBase < nonce; _seqBase++)
{
if (not _sentPackets.empty()) _sentPackets.pop_front();
}
}
}
// return without handling the user data if we are flow controlled
{
std::lock_guard<Pothos::Util::SpinLock> lock(_lock);
if (_sentPackets.full()) return;
}
// handle outgoing data to MAC
while (_dataIn->hasMessage())
{
//extract the packet
auto msg = _dataIn->popMessage();
const auto &pktIn = msg.extract<Pothos::Packet>();
const auto &data = pktIn.payload;
//append the LLC header
Pothos::Packet pktOut = pktIn;
pktOut.metadata = _metadata;
pktOut.payload = Pothos::BufferChunk(data.length + 4);
pktOut.payload.dtype = pktIn.payload.dtype;
uint8_t *byteBuf = pktOut.payload;
fillHeader(byteBuf, _seqOut++, PSH);
std::memcpy(byteBuf + 4, data.as<const uint8_t*>(), data.length);
_macOut->postMessage(pktOut);
//save the packet for resending
const auto timeNow = std::chrono::high_resolution_clock::now();
PacketItem item {std::move(pktOut), timeNow + _expireTimeout, timeNow};
//stash the packet and check capacity (locked)
std::lock_guard<Pothos::Util::SpinLock> lock(_lock);
_sentPackets.push_back(std::move(item));
if (_sentPackets.full()) break;
}
}
private:
void fillHeader(uint8_t *byteBuf, uint16_t nonce, uint8_t control)
{
// Data byte format: RECIPIENT_PORT NONCE_MSB NONCE_LSB CONTROL [DATA]*
byteBuf[0] = _port;
byteBuf[1] = nonce >> 8;
byteBuf[2] = nonce % 256;
byteBuf[3] = control;
}
void extractHeader(const uint8_t *byteBuf, uint8_t &port, uint16_t &nonce, uint8_t &control)
{
// Data byte format: RECIPIENT_PORT NONCE_MSB NONCE_LSB CONTROL [DATA]*
port = byteBuf[0];
nonce = (byteBuf[1] << 8) | byteBuf[2];
control = byteBuf[3];
}
void postControlPacket(uint16_t nonce, uint8_t control)
{
//FIXME: Save the previously sent ack packet and use the .unique() to check if
// that previous packet could be reused, so as to avoid reallocation of buffer space that happens below
Pothos::Packet packet;
packet.metadata = _metadata;
packet.payload = Pothos::BufferChunk(4);
fillHeader(packet.payload.as<uint8_t *>(), nonce, control);
_macOut->postMessage(std::move(packet));
}
void resendPackets(void)
{
const auto timeNow = std::chrono::high_resolution_clock::now();
std::lock_guard<Pothos::Util::SpinLock> lock(_lock);
for (size_t i = 0; i < _sentPackets.size(); i++)
{
_macOut->postMessage(_sentPackets[i].packet);
_sentPackets[i].lastSentTime = timeNow;
_resendCount++;
}
}
struct PacketItem
{
Pothos::Packet packet;
std::chrono::high_resolution_clock::time_point expiredTime; //used for expiration
std::chrono::high_resolution_clock::time_point lastSentTime; //used for resending
};
//status counts
unsigned long long _resendCount;
unsigned long long _expiredCount;
//configuration
uint8_t _port;
uint16_t _recipient;
Pothos::ObjectKwargs _metadata;
std::chrono::high_resolution_clock::duration _resendTimeout;
std::chrono::high_resolution_clock::duration _expireTimeout;
uint16_t _windowSize;
//sender side state
Pothos::Util::SpinLock _lock;
Pothos::Util::RingDeque<PacketItem> _sentPackets;
uint16_t _seqBase;
uint16_t _seqOut;
//receiver side state
uint16_t _reqSeq;
std::thread _monitorThread;
const Pothos::Object _resendMsg;
//pointers for port access
Pothos::OutputPort *_macOut;
Pothos::OutputPort *_dataOut;
Pothos::InputPort *_macIn;
Pothos::InputPort *_dataIn;
};
static Pothos::BlockRegistry registerSimpleLlc(
"/comms/simple_llc", &SimpleLlc::make);
static Pothos::BlockRegistry registerSimpleLlcOldPath(
"/blocks/simple_llc", &SimpleLlc::make);
| 34.599483 | 143 | 0.617252 | [
"object"
] |
7ef0cd770604d57d0c8d9b9b0b947d9845bdc903 | 1,700 | hpp | C++ | courses/value_semantics/salesman/salesman.hpp | JohanMabille/MAP586 | d20e01f101ff3f57c96129833835a1cd46071a6d | [
"BSD-3-Clause"
] | 4 | 2022-01-28T15:55:49.000Z | 2022-02-15T12:14:32.000Z | courses/value_semantics/salesman/salesman.hpp | JohanMabille/MAP586 | d20e01f101ff3f57c96129833835a1cd46071a6d | [
"BSD-3-Clause"
] | null | null | null | courses/value_semantics/salesman/salesman.hpp | JohanMabille/MAP586 | d20e01f101ff3f57c96129833835a1cd46071a6d | [
"BSD-3-Clause"
] | 3 | 2021-12-27T08:57:07.000Z | 2022-01-17T22:22:02.000Z | #ifndef SALESMAN_HPP
#define SALESMAP_HPP
#include <string>
#include <vector>
namespace hpc
{
/********
* CITY *
********/
class city
{
public:
city(const std::string& name,
double longitude,
double latitude);
const std::string& get_name() const;
double distance(const city& other) const;
private:
std::string m_name;
double m_longitude;
double m_latitude;
};
double distance(const city& lhs, const city& rhs);
/***********
* CIRCUIT *
***********/
using city_list = std::vector<city>;
class circuit
{
public:
explicit circuit(size_t size);
size_t size() const;
const city& get_city(size_t index) const;
bool has_city(const city& c) const;
void set_city(size_t index, const city& c);
void generate(const city_list& cm);
double get_fitness() const;
double get_distance() const;
private:
city_list m_city_list;
mutable double m_fitness;
};
/**************
* POPULATION *
**************/
class population
{
public:
population(size_t population_size, size_t circuit_size);
population(size_t size, const city_list& cl);
size_t size() const;
const circuit& get_circuit(size_t index) const;
void save_circuit(size_t index, const circuit& c);
const circuit& get_fittest() const;
private:
std::vector<circuit> m_circuit_list;
};
/*********************
* GENETIC_ALGORITHM *
*********************/
class genetic_algorithm
{
};
}
#endif
| 18.085106 | 64 | 0.542941 | [
"vector"
] |
7ef1cd9134fc9fd852ad75cb327292c22e1c4714 | 1,013 | hpp | C++ | include/cloud_bridge/cloud_bridge_client.hpp | swgu931/cloud_bridge | 9201a7664cabb91265a822d7c269b36d48e45388 | [
"MIT"
] | 3 | 2020-10-06T23:27:08.000Z | 2021-07-10T08:50:04.000Z | include/cloud_bridge/cloud_bridge_client.hpp | swgu931/cloud_bridge | 9201a7664cabb91265a822d7c269b36d48e45388 | [
"MIT"
] | 3 | 2021-01-27T07:43:41.000Z | 2021-02-03T08:35:24.000Z | include/cloud_bridge/cloud_bridge_client.hpp | lge-ros2/cloud_bridge | 8e1c3a3a3f2c661c60acad2ff32467d462d0edf7 | [
"MIT"
] | 2 | 2021-01-21T08:31:27.000Z | 2021-04-12T07:38:41.000Z | /**
* @file cloud_bridge_client.hpp
* @date 2021-01-28
* @author Sungkyu Kang
* @brief
* Cloud Bridge class Transfer ROS2 message to cloud using ZeroMQ
* @remark
* @copyright
* LGE Advanced Robotics Laboratory
* Copyright(C) 2020 LG Electronics Co., LTD., Seoul, Korea
* All Rights are Reserved.
*
* SPDX-License-Identifier: MIT
*/
#ifndef _CLOUD_BRIDGE_BRIDGE_CLIENT_H_
#define _CLOUD_BRIDGE_BRIDGE_CLIENT_H_
#include "cloud_bridge/cloud_bridge_base.hpp"
using namespace std;
class CloudBridgeClient: public CloudBridgeBase
{
public:
CloudBridgeClient(string nodeName);
virtual ~CloudBridgeClient();
protected:
bool Setup();
bool Connect();
private:
void SetPorts();
std::vector<uint8_t> SetManageReq(uint8_t op, std::string topic, std::string type);
bool SendManageRequest(const void* buffer, const int bufferLength, bool isNonBlockingMode, void** recvBuffer, int& recvBufferLength);
};
#endif // _CLOUD_BRIDGE_BRIDGE_CLIENT_H_
| 25.325 | 135 | 0.722606 | [
"vector"
] |
7ef7c29409ad42f11ea081b5d14370ed8b7fff19 | 13,861 | cpp | C++ | risc_visual/src/pong.cpp | riscmaster/risc_maap | 48b0ab79c1938bc3ed36442894dd4bf3091a2942 | [
"BSD-2-Clause"
] | 1 | 2017-04-30T19:33:37.000Z | 2017-04-30T19:33:37.000Z | risc_visual/src/pong.cpp | riscmaster/risc_maap | 48b0ab79c1938bc3ed36442894dd4bf3091a2942 | [
"BSD-2-Clause"
] | 1 | 2019-09-12T02:29:39.000Z | 2019-09-12T02:29:39.000Z | risc_visual/src/pong.cpp | riscmaster/risc_maap | 48b0ab79c1938bc3ed36442894dd4bf3091a2942 | [
"BSD-2-Clause"
] | 2 | 2016-03-07T00:47:59.000Z | 2018-10-06T17:43:10.000Z | /*
* Copyright (c) 2011, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Willow Garage, Inc. 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 <interactive_markers/interactive_marker_server.h>
#include <ros/ros.h>
#include <math.h>
#include <boost/thread/mutex.hpp>
using namespace visualization_msgs;
static const float FIELD_WIDTH = 12.0;
static const float FIELD_HEIGHT = 8.0;
static const float BORDER_SIZE = 0.5;
static const float PADDLE_SIZE = 2.0;
static const float UPDATE_RATE = 1.0 / 30.0;
static const float PLAYER_X = FIELD_WIDTH * 0.5 + BORDER_SIZE;
static const float AI_SPEED_LIMIT = 0.25;
class PongGame
{
public:
PongGame() :
server_("pong", "", false),
last_ball_pos_x_(0),
last_ball_pos_y_(0)
{
player_contexts_.resize(2);
makeFieldMarker();
makePaddleMarkers();
makeBallMarker();
reset();
updateScore();
ros::NodeHandle nh;
game_loop_timer_ = nh.createTimer(ros::Duration(UPDATE_RATE), boost::bind( &PongGame::spinOnce, this ) );
}
private:
// main control loop
void spinOnce()
{
if ( player_contexts_[0].active || player_contexts_[1].active )
{
float ball_dx = speed_ * ball_dir_x_;
float ball_dy = speed_ * ball_dir_y_;
ball_pos_x_ += ball_dx;
ball_pos_y_ += ball_dy;
// bounce off top / bottom
float t = 0;
if ( reflect ( ball_pos_y_, last_ball_pos_y_, FIELD_HEIGHT * 0.5, t ) )
{
ball_pos_x_ -= t * ball_dx;
ball_pos_y_ -= t * ball_dy;
ball_dir_y_ *= -1.0;
ball_dx = speed_ * ball_dir_x_;
ball_dy = speed_ * ball_dir_y_;
ball_pos_x_ += t * ball_dx;
ball_pos_y_ += t * ball_dy;
}
int player = ball_pos_x_ > 0 ? 1 : 0;
// reflect on paddles
if ( fabs(last_ball_pos_x_) < FIELD_WIDTH * 0.5 &&
fabs(ball_pos_x_) >= FIELD_WIDTH * 0.5 )
{
// check if the paddle is roughly at the right position
if ( ball_pos_y_ > player_contexts_[player].pos - PADDLE_SIZE * 0.5 - 0.5*BORDER_SIZE &&
ball_pos_y_ < player_contexts_[player].pos + PADDLE_SIZE * 0.5 + 0.5*BORDER_SIZE )
{
reflect ( ball_pos_x_, last_ball_pos_x_, FIELD_WIDTH * 0.5, t );
ball_pos_x_ -= t * ball_dx;
ball_pos_y_ -= t * ball_dy;
// change direction based on distance to paddle center
float offset = (ball_pos_y_ - player_contexts_[player].pos) / PADDLE_SIZE;
ball_dir_x_ *= -1.0;
ball_dir_y_ += offset*2.0;
normalizeVel();
// limit angle to 45 deg
if ( fabs(ball_dir_y_) > 0.707106781 )
{
ball_dir_x_ = ball_dir_x_ > 0.0 ? 1.0 : -1.0;
ball_dir_y_ = ball_dir_y_ > 0.0 ? 1.0 : -1.0;
normalizeVel();
}
ball_dx = speed_ * ball_dir_x_;
ball_dy = speed_ * ball_dir_y_;
ball_pos_x_ += t * ball_dx;
ball_pos_y_ += t * ball_dy;
}
}
// ball hits the left/right border of the playing field
if ( fabs(ball_pos_x_) >= FIELD_WIDTH * 0.5 + 1.5*BORDER_SIZE )
{
reflect ( ball_pos_x_, last_ball_pos_x_, FIELD_WIDTH * 0.5 + 1.5*BORDER_SIZE, t );
ball_pos_x_ -= t * ball_dx;
ball_pos_y_ -= t * ball_dy;
updateBall();
player_contexts_[1-player].score++;
updateScore();
server_.applyChanges();
reset();
ros::Duration(1.0).sleep();
}
else
{
updateBall();
}
last_ball_pos_x_ = ball_pos_x_;
last_ball_pos_y_ = ball_pos_y_;
// control computer player
if ( !player_contexts_[0].active || !player_contexts_[1].active )
{
int player = player_contexts_[0].active ? 1 : 0;
float delta = ball_pos_y_ - player_contexts_[player].pos;
// limit movement speed
if ( delta > AI_SPEED_LIMIT ) delta = AI_SPEED_LIMIT;
if ( delta < -AI_SPEED_LIMIT ) delta = -AI_SPEED_LIMIT;
setPaddlePos( player, player_contexts_[player].pos + delta );
}
speed_ += 0.0003;
}
server_.applyChanges();
}
void setPaddlePos( unsigned player, float pos )
{
if ( player > 1 )
{
return;
}
// clamp
if ( pos > (FIELD_HEIGHT - PADDLE_SIZE) * 0.5 )
{
pos = (FIELD_HEIGHT - PADDLE_SIZE) * 0.5;
}
if ( pos < (FIELD_HEIGHT - PADDLE_SIZE) * -0.5 )
{
pos = (FIELD_HEIGHT - PADDLE_SIZE) * -0.5;
}
player_contexts_[player].pos = pos;
geometry_msgs::Pose pose;
pose.position.x = (player == 0) ? -PLAYER_X : PLAYER_X;
pose.position.y = pos;
std::string marker_name = (player == 0) ? "paddle0" : "paddle1";
server_.setPose( marker_name, pose );
server_.setPose( marker_name+"_display", pose );
}
void processPaddleFeedback( unsigned player, const visualization_msgs::InteractiveMarkerFeedbackConstPtr &feedback )
{
if ( player > 1 )
{
return;
}
std::string control_marker_name = feedback->marker_name;
geometry_msgs::Pose pose = feedback->pose;
setPaddlePos( player, pose.position.y );
if ( feedback->event_type == visualization_msgs::InteractiveMarkerFeedback::MOUSE_DOWN )
{
player_contexts_[player].active = true;
}
if ( feedback->event_type == visualization_msgs::InteractiveMarkerFeedback::MOUSE_UP )
{
player_contexts_[player].active = false;
}
}
// restart round
void reset()
{
speed_ = 6.0 * UPDATE_RATE;
ball_pos_x_ = 0.0;
ball_pos_y_ = 0.0;
ball_dir_x_ = ball_dir_x_ > 0.0 ? 1.0 : -1.0;
ball_dir_y_ = rand() % 2 ? 1.0 : -1.0;
normalizeVel();
}
// set length of velocity vector to 1
void normalizeVel()
{
float l = sqrt( ball_dir_x_*ball_dir_x_ + ball_dir_y_*ball_dir_y_ );
ball_dir_x_ /= l;
ball_dir_y_ /= l;
}
// compute reflection
// returns true if the given limit has been surpassed
// t [0...1] says how much the limit has been surpassed, relative to the distance
// between last_pos and pos
bool reflect( float &pos, float last_pos, float limit, float &t )
{
if ( pos > limit )
{
t = (pos - limit) / (pos - last_pos);
return true;
}
if ( -pos > limit )
{
t = (-pos - limit) / (last_pos - pos);
return true;
}
return false;
}
// update ball marker
void updateBall()
{
geometry_msgs::Pose pose;
pose.position.x = ball_pos_x_;
pose.position.y = ball_pos_y_;
server_.setPose( "ball", pose );
}
// update score marker
void updateScore()
{
InteractiveMarker int_marker;
int_marker.header.frame_id = "/base_link";
int_marker.name = "score";
InteractiveMarkerControl control;
control.always_visible = true;
Marker marker;
marker.type = Marker::TEXT_VIEW_FACING;
marker.color.r = 1.0;
marker.color.g = 1.0;
marker.color.b = 1.0;
marker.color.a = 1.0;
marker.scale.x = 1.5;
marker.scale.y = 1.5;
marker.scale.z = 1.5;
std::ostringstream s;
s << player_contexts_[0].score;
marker.text = s.str();
marker.pose.position.y = FIELD_HEIGHT*0.5 + 4.0*BORDER_SIZE;
marker.pose.position.x = -1.0 * ( FIELD_WIDTH * 0.5 + BORDER_SIZE );
control.markers.push_back( marker );
s.str("");
s << player_contexts_[1].score;
marker.text = s.str();
marker.pose.position.x *= -1;
control.markers.push_back( marker );
int_marker.controls.push_back( control );
server_.insert( int_marker );
}
void makeFieldMarker()
{
InteractiveMarker int_marker;
int_marker.header.frame_id = "/base_link";
int_marker.name = "field";
InteractiveMarkerControl control;
control.always_visible = true;
Marker marker;
marker.type = Marker::CUBE;
marker.color.r = 1.0;
marker.color.g = 1.0;
marker.color.b = 1.0;
marker.color.a = 1.0;
// Top Border
marker.scale.x = FIELD_WIDTH + 6.0 * BORDER_SIZE;
marker.scale.y = BORDER_SIZE;
marker.scale.z = BORDER_SIZE;
marker.pose.position.x = 0;
marker.pose.position.y = FIELD_HEIGHT*0.5 + BORDER_SIZE;
control.markers.push_back( marker );
// Bottom Border
marker.pose.position.y *= -1;
control.markers.push_back( marker );
// Left Border
marker.scale.x = BORDER_SIZE;
marker.scale.y = FIELD_HEIGHT + 3.0*BORDER_SIZE;
marker.scale.z = BORDER_SIZE;
marker.pose.position.x = FIELD_WIDTH*0.5 + 2.5*BORDER_SIZE;
marker.pose.position.y = 0;
control.markers.push_back( marker );
// Right Border
marker.pose.position.x *= -1;
control.markers.push_back( marker );
// store
int_marker.controls.push_back( control );
server_.insert( int_marker );
}
void makePaddleMarkers()
{
InteractiveMarker int_marker;
int_marker.header.frame_id = "/base_link";
// Add a control for moving the paddle
InteractiveMarkerControl control;
control.always_visible = false;
control.interaction_mode = InteractiveMarkerControl::MOVE_AXIS;
control.orientation.w = 1;
control.orientation.z = 1;
// Add a visualization marker
Marker marker;
marker.type = Marker::CUBE;
marker.color.r = 1.0;
marker.color.g = 1.0;
marker.color.b = 1.0;
marker.color.a = 0.0;
marker.scale.x = BORDER_SIZE + 0.1;
marker.scale.y = PADDLE_SIZE + 0.1;
marker.scale.z = BORDER_SIZE + 0.1;
marker.pose.position.z = 0;
marker.pose.position.y = 0;
control.markers.push_back( marker );
int_marker.controls.push_back( control );
// Control for player 1
int_marker.name = "paddle0";
int_marker.pose.position.x = -PLAYER_X;
server_.insert( int_marker );
server_.setCallback( int_marker.name, boost::bind( &PongGame::processPaddleFeedback, this, 0, _1 ) );
// Control for player 2
int_marker.name = "paddle1";
int_marker.pose.position.x = PLAYER_X;
server_.insert( int_marker );
server_.setCallback( int_marker.name, boost::bind( &PongGame::processPaddleFeedback, this, 1, _1 ) );
// Make display markers
marker.scale.x = BORDER_SIZE;
marker.scale.y = PADDLE_SIZE;
marker.scale.z = BORDER_SIZE;
marker.color.r = 0.5;
marker.color.a = 1.0;
control.interaction_mode = InteractiveMarkerControl::NONE;
control.always_visible = true;
// Display for player 1
int_marker.name = "paddle0_display";
int_marker.pose.position.x = -PLAYER_X;
marker.color.g = 1.0;
marker.color.b = 0.5;
int_marker.controls.clear();
control.markers.clear();
control.markers.push_back( marker );
int_marker.controls.push_back( control );
server_.insert( int_marker );
// Display for player 2
int_marker.name = "paddle1_display";
int_marker.pose.position.x = PLAYER_X;
marker.color.g = 0.5;
marker.color.b = 1.0;
int_marker.controls.clear();
control.markers.clear();
control.markers.push_back( marker );
int_marker.controls.push_back( control );
server_.insert( int_marker );
}
void makeBallMarker()
{
InteractiveMarker int_marker;
int_marker.header.frame_id = "/base_link";
InteractiveMarkerControl control;
control.always_visible = true;
// Ball
int_marker.name = "ball";
control.interaction_mode = InteractiveMarkerControl::NONE;
control.orientation.w = 1;
control.orientation.y = 1;
Marker marker;
marker.color.r = 1.0;
marker.color.g = 1.0;
marker.color.b = 1.0;
marker.color.a = 1.0;
marker.type = Marker::CYLINDER;
marker.scale.x = BORDER_SIZE;
marker.scale.y = BORDER_SIZE;
marker.scale.z = BORDER_SIZE;
control.markers.push_back( marker );
int_marker.controls.push_back( control );
server_.insert( int_marker );
}
interactive_markers::InteractiveMarkerServer server_;
ros::Timer game_loop_timer_;
InteractiveMarker field_marker_;
struct PlayerContext
{
PlayerContext(): pos(0),active(false),score(0) {}
float pos;
bool active;
int score;
};
std::vector<PlayerContext> player_contexts_;
float last_ball_pos_x_;
float last_ball_pos_y_;
float ball_pos_x_;
float ball_pos_y_;
float ball_dir_x_;
float ball_dir_y_;
float speed_;
};
int main(int argc, char** argv)
{
ros::init(argc, argv, "pong");
PongGame pong_game;
ros::spin();
ROS_INFO("Exiting..");
}
| 27.666667 | 118 | 0.645408 | [
"vector"
] |
7efa6e4c2cc45c8cc2041a3d33b44d20d2001d2a | 22,053 | cpp | C++ | frame/aio/src/aioselector_epoll.cpp | joydit/solidframe | 0539b0a1e77663ac4c701a88f56723d3e3688e8c | [
"BSL-1.0"
] | null | null | null | frame/aio/src/aioselector_epoll.cpp | joydit/solidframe | 0539b0a1e77663ac4c701a88f56723d3e3688e8c | [
"BSL-1.0"
] | null | null | null | frame/aio/src/aioselector_epoll.cpp | joydit/solidframe | 0539b0a1e77663ac4c701a88f56723d3e3688e8c | [
"BSL-1.0"
] | null | null | null | // frame/aio/src/aioselector_epoll.cpp
//
// Copyright (c) 2007, 2008, 2013 Valentin Palade (vipalade @ gmail . com)
//
// This file is part of SolidFrame framework.
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt.
//
#include "system/common.hpp"
#include <fcntl.h>
#include <sys/epoll.h>
#include "system/exception.hpp"
#ifndef UPIPESIGNAL
#ifdef HAS_EVENTFD_H
#include <sys/eventfd.h>
#else
#define UPIPESIGNAL
#endif
#endif
#include <vector>
#include <cerrno>
#include <cstring>
#include "system/debug.hpp"
#include "system/timespec.hpp"
#include "system/mutex.hpp"
#include "utility/queue.hpp"
#include "utility/stack.hpp"
#include "frame/object.hpp"
#include "frame/common.hpp"
#include "frame/aio/aioselector.hpp"
#include "frame/aio/aioobject.hpp"
#include "aiosocket.hpp"
namespace solid{
namespace frame{
namespace aio{
//=============================================================
// TODO:
// - investigate if you can use timerfd_create (man timerfd_create)
//
//=============================================================
struct Selector::Stub{
enum State{
InExecQueue,
OutExecQueue
};
Stub():
timepos(TimeSpec::maximum),
itimepos(TimeSpec::maximum),
otimepos(TimeSpec::maximum),
state(OutExecQueue),
events(0){
}
void reset(){
timepos = TimeSpec::maximum;
state = OutExecQueue;
events = 0;
}
ObjectPointerT objptr;
TimeSpec timepos;//object timepos
TimeSpec itimepos;//input timepos
TimeSpec otimepos;//output timepos
State state;
uint events;
};
struct Selector::Data{
enum{
EPOLLMASK = EPOLLET | EPOLLIN | EPOLLOUT,
MAXPOLLWAIT = 0x7FFFFFFF,
EXIT_LOOP = 1,
FULL_SCAN = 2,
READ_PIPE = 4,
MAX_EVENTS_COUNT = 1024 * 2,
};
typedef Stack<uint32> Uint32StackT;
typedef Queue<uint32> Uint32QueueT;
typedef std::vector<Stub> StubVectorT;
ulong objcp;
ulong objsz;
// ulong sockcp;
ulong socksz;
int selcnt;
int epollfd;
epoll_event events[MAX_EVENTS_COUNT];
StubVectorT stubs;
Uint32QueueT execq;
Uint32StackT freestubsstk;
#ifdef UPIPESIGNAL
int pipefds[2];
#else
int efd;//eventfd
Mutex m;
Uint32QueueT sigq;//a signal queue
uint64 efdv;//the eventfd value
#endif
TimeSpec ntimepos;//next timepos == next timeout
TimeSpec ctimepos;//current time pos
//reporting data:
uint rep_fullscancount;
public://methods:
Data();
~Data();
int computeWaitTimeout()const;
void addNewSocket();
epoll_event* eventPrepare(epoll_event &_ev, const uint32 _objpos, const uint32 _sockpos);
void stub(uint32 &_objpos, uint32 &_sockpos, const epoll_event &_ev);
};
//-------------------------------------------------------------
Selector::Data::Data():
objcp(0), objsz(0), /*sockcp(0),*/ socksz(0), selcnt(0), epollfd(-1),
rep_fullscancount(0){
#ifdef UPIPESIGNAL
pipefds[0] = -1;
pipefds[1] = -1;
#else
efd = -1;
efdv = 0;
#endif
}
Selector::Data::~Data(){
if(epollfd >= 0){
close(epollfd);
}
#ifdef UPIPESIGNAL
if(pipefds[0] >= 0){
close(pipefds[0]);
}
if(pipefds[1] >= 0){
close(pipefds[1]);
}
#else
close(efd);
#endif
}
int Selector::Data::computeWaitTimeout()const{
if(ntimepos.isMax()) return -1;//return MAXPOLLWAIT;
int rv = (ntimepos.seconds() - ctimepos.seconds()) * 1000;
rv += ((long)ntimepos.nanoSeconds() - ctimepos.nanoSeconds()) / 1000000;
if(rv < 0) return MAXPOLLWAIT;
return rv;
}
void Selector::Data::addNewSocket(){
++socksz;
}
inline epoll_event* Selector::Data::eventPrepare(
epoll_event &_ev, const uint32 _objpos, const uint32 _sockpos
){
//TODO:we are now limited to uint32 objects and uint32 sockets per object
_ev.data.u64 = _objpos;
_ev.data.u64 <<= 32;
_ev.data.u64 |= _sockpos;
return &_ev;
}
void Selector::Data::stub(uint32 &_objpos, uint32 &_sockpos, const epoll_event &_ev){
_objpos = (_ev.data.u64 >> 32);
_sockpos = (_ev.data.u64 & 0xffffffff);
}
//=============================================================
Selector::Selector():d(*(new Data)){
}
Selector::~Selector(){
delete &d;
}
bool Selector::init(ulong _cp){
idbgx(Debug::aio, "aio::Selector "<<(void*)this);
cassert(_cp);
d.objcp = _cp;
//d.sockcp = _cp;
setCurrentTimeSpecific(d.ctimepos);
//first create the epoll descriptor:
cassert(d.epollfd < 0);
d.epollfd = epoll_create(_cp);
if(d.epollfd < 0){
edbgx(Debug::aio, "epoll_create: "<<strerror(errno));
cassert(false);
return false;
}
#ifdef UPIPESIGNAL
//next create the pipefds:
cassert(d.pipefds[0] < 0 && d.pipefds[1] < 0);
if(pipe(d.pipefds)){
edbgx(Debug::aio, "pipe: "<<strerror(errno));
cassert(false);
return false;
}
//make the pipes nonblocking
fcntl(d.pipefds[0], F_SETFL, O_NONBLOCK);
fcntl(d.pipefds[1], F_SETFL, O_NONBLOCK);
//register the pipes onto epoll
epoll_event ev;
ev.data.u64 = 0;
ev.events = EPOLLIN | EPOLLPRI;//must be LevelTriggered
if(epoll_ctl(d.epollfd, EPOLL_CTL_ADD, d.pipefds[0], &ev)){
edbgx(Debug::aio, "epoll_ctl: "<<strerror(errno));
cassert(false);
return false;
}
#else
cassert(d.efd < 0);
d.efd = eventfd(0, EFD_NONBLOCK);
//register the pipes onto epoll
epoll_event ev;
ev.data.u64 = 0;
ev.events = EPOLLIN | EPOLLPRI;//must be LevelTriggered
if(epoll_ctl(d.epollfd, EPOLL_CTL_ADD, d.efd, &ev)){
edbgx(Debug::aio, "epoll_ctl: "<<strerror(errno));
cassert(false);
return false;
}
#endif
//allocate the events
//d.events = new epoll_event[d.sockcp];
for(ulong i = 0; i < Data::MAX_EVENTS_COUNT; ++i){
d.events[i].events = 0;
d.events[i].data.u64 = 0L;
}
//We need to have the stubs preallocated
//because of aio::Object::ptimeout
d.stubs.reserve(d.objcp);
//add the pipe stub:
doAddNewStub();
d.ctimepos.set(0);
d.ntimepos = TimeSpec::maximum;
d.objsz = 1;
d.socksz = 1;
return true;
}
void Selector::prepare(){
setCurrentTimeSpecific(d.ctimepos);
}
void Selector::unprepare(){
}
void Selector::raise(uint32 _pos){
#ifdef UPIPESIGNAL
idbgx(Debug::aio, "signal connection pipe: "<<_pos<<" this "<<(void*)this);
write(d.pipefds[1], &_pos, sizeof(uint32));
#else
idbgx(Debug::aio, "signal connection evnt: "<<_pos<<" this "<<(void*)this);
uint64 v(1);
{
Locker<Mutex> lock(d.m);
d.sigq.push(_pos);
}
int rv = write(d.efd, &v, sizeof(v));
cassert(rv == sizeof(v));
#endif
}
ulong Selector::capacity()const{
return d.objcp;
}
ulong Selector::size() const{
return d.objsz;
}
bool Selector::empty()const{
return d.objsz == 1;
}
bool Selector::full()const{
return d.objsz == d.objcp;
}
bool Selector::push(JobT &_objptr){
if(full()){
//NOTE:we cannot increase selvec because, objects keep pointers to Stub structures from vector
//if we'd use deque instead, we'd have a performance penalty
THROW_EXCEPTION("Selector full");
}
uint stubpos = doAddNewStub();
Stub &stub = d.stubs[stubpos];
if(!this->setObjectThread(*_objptr, stubpos)){
return false;
}
stub.timepos = TimeSpec::maximum;
stub.itimepos = TimeSpec::maximum;
stub.otimepos = TimeSpec::maximum;
_objptr->doPrepare(&stub.itimepos, &stub.otimepos);
//add events for every socket
bool fail = false;
uint failpos = 0;
{
epoll_event ev;
ev.data.u64 = 0L;
ev.events = 0;
Object::SocketStub *psockstub = _objptr->pstubs;
for(uint i = 0; i < _objptr->stubcp; ++i, ++psockstub){
Socket *psock = psockstub->psock;
if(psock && psock->descriptor() >= 0){
if(
epoll_ctl(d.epollfd, EPOLL_CTL_ADD, psock->descriptor(), d.eventPrepare(ev, stubpos, i))
){
edbgx(Debug::aio, "epoll_ctl adding filedesc "<<psock->descriptor()<<" stubpos = "<<stubpos<<" pos = "<<i<<" err = "<<strerror(errno));
fail = true;
failpos = i;
break;
}else{
//success adding new
d.addNewSocket();
psock->doPrepare();
}
}
}
}
if(fail){
doUnregisterObject(*_objptr, failpos);
stub.reset();
d.freestubsstk.push(stubpos);
return false;
}else{
++d.objsz;
stub.objptr = _objptr;
stub.objptr->doPrepare(&stub.itimepos, &stub.otimepos);
vdbgx(Debug::aio, "pushing object "<<&(*(stub.objptr))<<" on position "<<stubpos);
stub.state = Stub::InExecQueue;
d.execq.push(stubpos);
}
return true;
}
inline ulong Selector::doExecuteQueue(){
ulong flags = 0;
ulong qsz(d.execq.size());
while(qsz){//we only do a single scan:
const uint pos = d.execq.front();
d.execq.pop();
--qsz;
flags |= doExecute(pos);
}
return flags;
}
void Selector::run(){
static const int maxnbcnt = 16;
uint flags;
int nbcnt = -1; //non blocking opperations count,
//used to reduce the number of calls for the system time.
int pollwait = 0;
do{
flags = 0;
if(nbcnt < 0){
d.ctimepos.currentMonotonic();
nbcnt = maxnbcnt;
}
if(d.selcnt){
--nbcnt;
flags |= doAllIo();
}
if(flags & Data::READ_PIPE){
--nbcnt;
flags |= doReadPipe();
}
if(d.ctimepos >= d.ntimepos || (flags & Data::FULL_SCAN)){
nbcnt -= 4;
flags |= doFullScan();
}
if(d.execq.size()){
nbcnt -= d.execq.size();
flags |= doExecuteQueue();
}
if(empty()) flags |= Data::EXIT_LOOP;
if(flags || d.execq.size()){
pollwait = 0;
--nbcnt;
}else{
pollwait = d.computeWaitTimeout();
vdbgx(Debug::aio, "pollwait "<<pollwait<<" ntimepos.s = "<<d.ntimepos.seconds()<<" ntimepos.ns = "<<d.ntimepos.nanoSeconds());
vdbgx(Debug::aio, "ctimepos.s = "<<d.ctimepos.seconds()<<" ctimepos.ns = "<<d.ctimepos.nanoSeconds());
nbcnt = -1;
}
d.selcnt = epoll_wait(d.epollfd, d.events, Data::MAX_EVENTS_COUNT, pollwait);
vdbgx(Debug::aio, "epollwait = "<<d.selcnt);
if(d.selcnt < 0) d.selcnt = 0;
}while(!(flags & Data::EXIT_LOOP));
}
//-------------------------------------------------------------
ulong Selector::doReadPipe(){
#ifdef UPIPESIGNAL
enum {BUFSZ = 128, BUFLEN = BUFSZ * sizeof(uint32)};
uint32 buf[128];
ulong rv(0);//no
long rsz(0);
long j(0);
long maxcnt((d.objcp / BUFSZ) + 1);
Stub *pstub(NULL);
while((++j <= maxcnt) && ((rsz = read(d.pipefds[0], buf, BUFLEN)) == BUFLEN)){
for(int i = 0; i < BUFSZ; ++i){
uint pos(buf[i]);
if(pos){
if(pos < d.stubs.size() && !(pstub = &d.stubs[pos])->objptr.empty() && pstub->objptr->notified(S_RAISE)){
pstub->events |= EventSignal;
if(pstub->state == Stub::OutExecQueue){
d.execq.push(pos);
pstub->state = Stub::InExecQueue;
}
}
}else rv = Data::EXIT_LOOP;
}
}
if(rsz){
rsz >>= 2;
for(int i = 0; i < rsz; ++i){
uint pos(buf[i]);
if(pos){
if(pos < d.stubs.size() && !(pstub = &d.stubs[pos])->objptr.empty() && pstub->objptr->notified(S_RAISE)){
pstub->events |= EventSignal;
if(pstub->state == Stub::OutExecQueue){
d.execq.push(pos);
pstub->state = Stub::InExecQueue;
}
}
}else rv = Data::EXIT_LOOP;
}
}
if(j > maxcnt){
//dummy read:
rv = Data::EXIT_LOOP | Data::FULL_SCAN;//scan all filedescriptors for events
wdbgx(Debug::aio, "reading pipe dummy");
while((rsz = read(d.pipefds[0], buf, BUFSZ)) > 0);
}
return rv;
#else
//using eventfd
int rv = 0;
uint64 v = 0;
bool mustempty = false;
Stub *pstub(NULL);
while(read(d.efd, &v, sizeof(v)) == sizeof(v)){
Locker<Mutex> lock(d.m);
uint limiter = 16;
while(d.sigq.size() && --limiter){
uint pos(d.sigq.front());
d.sigq.pop();
if(pos){
idbgx(Debug::aio, "signaling object on pos "<<pos);
if(pos < d.stubs.size() && (pstub = &d.stubs[pos])->objptr && pstub->objptr->signaled(S_RAISE)){
idbgx(Debug::aio, "signaled object on pos "<<pos);
pstub->events |= EventSignal;
if(pstub->state == Stub::OutExecQueue){
d.execq.push(pos);
pstub->state = Stub::InExecQueue;
}
}
}else rv = Data::EXIT_LOOP;
}
if(limiter == 0){
//d.sigq.size() != 0
mustempty = true;
}else{
mustempty = false;
}
}
if(mustempty){
Locker<Mutex> lock(d.m);
while(d.sigq.size()){
uint pos(d.sigq.front());
d.sigq.pop();
if(pos){
if(pos < d.stubs.size() && (pstub = &d.stubs[pos])->objptr && pstub->objptr->signaled(S_RAISE)){
pstub->events |= EventSignal;
if(pstub->state == Stub::OutExecQueue){
d.execq.push(pos);
pstub->state = Stub::InExecQueue;
}
}
}else rv = Data::EXIT_LOOP;
}
}
return rv;
#endif
}
void Selector::doUnregisterObject(Object &_robj, int _lastfailpos){
Object::SocketStub *psockstub = _robj.pstubs;
uint to = _robj.stubcp;
if(_lastfailpos >= 0){
to = _lastfailpos + 1;
}
for(uint i = 0; i < to; ++i, ++psockstub){
Socket *psock = psockstub->psock;
if(psock && psock->descriptor() >= 0){
check_call(Debug::aio, 0, epoll_ctl(d.epollfd, EPOLL_CTL_DEL, psock->descriptor(), NULL));
--d.socksz;
psock->doUnprepare();
}
}
}
inline ulong Selector::doIo(Socket &_rsock, ulong _evs, ulong){
if(_evs & (EPOLLERR | EPOLLHUP)){
_rsock.doClear();
int err(0);
socklen_t len(sizeof(err));
int rv = getsockopt(_rsock.descriptor(), SOL_SOCKET, SO_ERROR, &err, &len);
wdbgx(Debug::aio, "sock error evs = "<<_evs<<" err = "<<err<<" errstr = "<<strerror(err));
wdbgx(Debug::aio, "rv = "<<rv<<" "<<strerror(errno)<<" desc"<<_rsock.descriptor());
if(rv || err || (_evs & EPOLLERR)){
return EventDoneError;
}//else ignore spurious EPOLLHUP for just created sockets
}
ulong rv = 0;
if(_evs & EPOLLIN){
rv = _rsock.doRecv();
}
if(!(rv & EventDoneError) && (_evs & EPOLLOUT)){
rv |= _rsock.doSend();
}
return rv;
}
ulong Selector::doAllIo(){
ulong flags = 0;
TimeSpec crttout;
uint32 evs;
uint32 stubpos;
uint32 sockpos;
const ulong selcnt = d.selcnt;
for(ulong i = 0; i < selcnt; ++i){
d.stub(stubpos, sockpos, d.events[i]);
vdbgx(Debug::aio, "stubpos = "<<stubpos);
if(stubpos){
cassert(stubpos < d.stubs.size());
Stub &stub(d.stubs[stubpos]);
Object::SocketStub &sockstub(stub.objptr->pstubs[sockpos]);
Socket &sock(*sockstub.psock);
cassert(sockpos < stub.objptr->stubcp);
cassert(stub.objptr->pstubs[sockpos].psock);
vdbgx(Debug::aio, "io events stubpos = "<<stubpos<<" events = "<<d.events[i].events);
evs = doIo(sock, d.events[i].events);
{
const uint t = sockstub.psock->ioRequest();
if((sockstub.selevents & Data::EPOLLMASK) != t){
sockstub.selevents = t;
epoll_event ev;
ev.events = t | EPOLLERR | EPOLLHUP | EPOLLET;
ev.data.u64 = d.events[i].data.u64;
check_call(Debug::aio, 0, epoll_ctl(d.epollfd, EPOLL_CTL_MOD, sockstub.psock->descriptor(), &ev));
}
}
if(evs){
//first mark the socket in connection
vdbgx(Debug::aio, "evs = "<<evs<<" indone = "<<EventDoneRecv<<" stubpos = "<<stubpos);
stub.objptr->socketPostEvents(sockpos, evs);
stub.events |= evs;
//push channel execqueue
if(stub.state == Stub::OutExecQueue){
d.execq.push(stubpos);
stub.state = Stub::InExecQueue;
}
}
}else{//the pipe stub
flags |= Data::READ_PIPE;
}
}
return flags;
}
void Selector::doFullScanCheck(Stub &_rstub, const ulong _pos){
ulong evs = 0;
if(d.ctimepos >= _rstub.itimepos){
evs |= _rstub.objptr->doOnTimeoutRecv(d.ctimepos);
if(d.ntimepos > _rstub.itimepos){
d.ntimepos = _rstub.itimepos;
}
}else if(d.ntimepos > _rstub.itimepos){
d.ntimepos = _rstub.itimepos;
}
if(d.ctimepos >= _rstub.otimepos){
evs |= _rstub.objptr->doOnTimeoutSend(d.ctimepos);
if(d.ntimepos > _rstub.otimepos){
d.ntimepos = _rstub.otimepos;
}
}else if(d.ntimepos > _rstub.otimepos){
d.ntimepos = _rstub.otimepos;
}
if(d.ctimepos >= _rstub.timepos){
evs |= EventTimeout;
}else if(d.ntimepos > _rstub.timepos){
d.ntimepos = _rstub.timepos;
}
if(_rstub.objptr->notified(S_RAISE)){
evs |= EventSignal;//should not be checked by objs
}
if(evs){
_rstub.events |= evs;
if(_rstub.state == Stub::OutExecQueue){
d.execq.push(_pos);
_rstub.state = Stub::InExecQueue;
}
}
}
ulong Selector::doFullScan(){
++d.rep_fullscancount;
idbgx(Debug::aio, "fullscan count "<<d.rep_fullscancount);
d.ntimepos = TimeSpec::maximum;
for(Data::StubVectorT::iterator it(d.stubs.begin()); it != d.stubs.end(); it += 4){
if(!it->objptr.empty()){
doFullScanCheck(*it, it - d.stubs.begin());
}
if(!(it + 1)->objptr.empty()){
doFullScanCheck(*(it + 1), it - d.stubs.begin() + 1);
}
if(!(it + 2)->objptr.empty()){
doFullScanCheck(*(it + 2), it - d.stubs.begin() + 2);
}
if(!(it + 3)->objptr.empty()){
doFullScanCheck(*(it + 3), it - d.stubs.begin() + 3);
}
}
return 0;
}
ulong Selector::doExecute(const ulong _pos){
Stub &stub(d.stubs[_pos]);
cassert(stub.state == Stub::InExecQueue);
stub.state = Stub::OutExecQueue;
ulong rv(0);
Object::ExecuteController exectl(stub.events, d.ctimepos);
stub.timepos = TimeSpec::maximum;
stub.events = 0;
stub.objptr->doClearRequests();//clears the requests from object to selector
idbgx(Debug::aio, "execute object "<<_pos);
this->associateObjectToCurrentThread(*stub.objptr);
this->executeObject(*stub.objptr, exectl);
switch(exectl.returnValue()){
case Object::ExecuteContext::RescheduleRequest:
d.execq.push(_pos);
stub.state = Stub::InExecQueue;
stub.events |= EventReschedule;
case Object::ExecuteContext::WaitRequest:
doPrepareObjectWait(_pos, d.ctimepos);
break;
case Object::ExecuteContext::WaitUntilRequest:
doPrepareObjectWait(_pos, exectl.waitTime());
break;
case Object::ExecuteContext::CloseRequest:
idbgx(Debug::aio, "BAD: removing the connection");
d.freestubsstk.push(_pos);
//unregister all channels
doUnregisterObject(*stub.objptr);
//stub.objptr->doUnprepare();
this->stopObject(*stub.objptr);
stub.objptr.clear();
stub.timepos = TimeSpec::maximum;
--d.objsz;
rv = Data::EXIT_LOOP;
break;
case Object::ExecuteContext::LeaveRequest:
d.freestubsstk.push(_pos);
doUnregisterObject(*stub.objptr);
stub.timepos = TimeSpec::maximum;
--d.objsz;
stub.objptr->doUnprepare();
stub.objptr.release();
rv = Data::EXIT_LOOP;
default:
cassert(false);
}
return rv;
}
void Selector::doPrepareObjectWait(const size_t _pos, const TimeSpec &_timepos){
Stub &stub(d.stubs[_pos]);
const size_t * const pend(stub.objptr->reqpos);
bool mustwait = true;
vdbgx(Debug::aio, "stub "<<_pos);
for(const size_t *pit(stub.objptr->reqbeg); pit != pend; ++pit){
Object::SocketStub &sockstub(stub.objptr->pstubs[*pit]);
const uint8 reqtp = sockstub.requesttype;
sockstub.requesttype = 0;
switch(reqtp){
case Object::SocketStub::IORequest:{
uint t = sockstub.psock->ioRequest();
vdbgx(Debug::aio, "sockstub "<<*pit<<" ioreq "<<t);
if((sockstub.selevents & Data::EPOLLMASK) != t){
vdbgx(Debug::aio, "sockstub "<<*pit);
epoll_event ev;
sockstub.selevents = t;
ev.events = t | EPOLLERR | EPOLLHUP | EPOLLET;
check_call(Debug::aio, 0, epoll_ctl(d.epollfd, EPOLL_CTL_MOD, sockstub.psock->descriptor(), d.eventPrepare(ev, _pos, *pit)));
}
}break;
case Object::SocketStub::RegisterRequest:{
vdbgx(Debug::aio, "sockstub "<<*pit<<" regreq");
/*
NOTE: may be a good ideea to add RegisterAndIORequest
Epoll doesn't like sockets that are only created, it signals
EPOLLET on them.
*/
epoll_event ev;
sockstub.psock->doPrepare();
sockstub.selevents = 0;
ev.events = EPOLLERR | EPOLLHUP | EPOLLET;
check_call(Debug::aio, 0, epoll_ctl(d.epollfd, EPOLL_CTL_ADD, sockstub.psock->descriptor(), d.eventPrepare(ev, _pos, *pit)));
stub.objptr->socketPostEvents(*pit, EventDoneSuccess);
d.addNewSocket();
mustwait = false;
}break;
case Object::SocketStub::UnregisterRequest:{
vdbgx(Debug::aio, "sockstub "<<*pit<<" unregreq");
if(sockstub.psock->ok()){
check_call(Debug::aio, 0, epoll_ctl(d.epollfd, EPOLL_CTL_DEL, sockstub.psock->descriptor(), NULL));
--d.socksz;
sockstub.psock->doUnprepare();
stub.objptr->socketPostEvents(*pit, EventDoneSuccess);
mustwait = false;
}
}break;
default:
cassert(false);
}
}
if(mustwait){
//will step here when, for example, the object waits for an external signal.
if(_timepos < stub.timepos && _timepos != d.ctimepos){
stub.timepos = _timepos;
}
if(stub.timepos == d.ctimepos){
stub.timepos = TimeSpec::maximum;
}else if(d.ntimepos > stub.timepos){
d.ntimepos = stub.timepos;
}
if(d.ntimepos > stub.itimepos){
d.ntimepos = stub.itimepos;
}
if(d.ntimepos > stub.otimepos){
d.ntimepos = stub.otimepos;
}
}else if(stub.state != Stub::InExecQueue){
d.execq.push(_pos);
stub.state = Stub::InExecQueue;
}
}
ulong Selector::doAddNewStub(){
ulong pos = 0;
if(d.freestubsstk.size()){
pos = d.freestubsstk.top();
d.freestubsstk.pop();
}else{
size_t cp = d.stubs.capacity();
pos = d.stubs.size();
size_t nextsize(fast_padding_size(pos, 2));
d.stubs.push_back(Stub());
for(size_t i(pos + 1); i < nextsize; ++i){
d.stubs.push_back(Stub());
d.freestubsstk.push(i);
}
if(cp != d.stubs.capacity()){
//we need to reset the aioobject's pointer to timepos
for(Data::StubVectorT::iterator it(d.stubs.begin()); it != d.stubs.end(); it += 4){
if(!it->objptr.empty()){
//TODO: is it ok commenting the following lines?!
//it->timepos = TimeSpec::maximum;
//it->itimepos = TimeSpec::maximum;
//it->otimepos = TimeSpec::maximum;
it->objptr->doPrepare(&it->itimepos, &it->otimepos);
}
if(!(it + 1)->objptr.empty()){
//TODO: see above
(it + 1)->objptr->doPrepare(&(it + 1)->itimepos, &(it + 1)->otimepos);
}
if(!(it + 2)->objptr.empty()){
//TODO: see above
(it + 2)->objptr->doPrepare(&(it + 2)->itimepos, &(it + 2)->otimepos);
}
if(!(it + 3)->objptr.empty()){
//TODO: see above
(it + 3)->objptr->doPrepare(&(it + 3)->itimepos, &(it + 3)->otimepos);
}
}
}
}
return pos;
}
//-------------------------------------------------------------
}//namespace aio
}//namespace frame
}//namespace solid
| 26.47419 | 140 | 0.63497 | [
"object",
"vector",
"solid"
] |
7d068937de0c50253fa4f28894b78f0d7033cc21 | 35,723 | cpp | C++ | PestRidDlg-back.cpp | GregoryMorse/PestRid | e9670a020f13c0fab8de18a8d54a8caf13e673c5 | [
"Unlicense"
] | 3 | 2016-08-30T09:19:12.000Z | 2019-04-09T06:46:59.000Z | PestRidDlg-back.cpp | GregoryMorse/PestRid | e9670a020f13c0fab8de18a8d54a8caf13e673c5 | [
"Unlicense"
] | null | null | null | PestRidDlg-back.cpp | GregoryMorse/PestRid | e9670a020f13c0fab8de18a8d54a8caf13e673c5 | [
"Unlicense"
] | null | null | null | // Gregory Morse
// PestRidDlg.cpp : implementation file
//
#include "stdafx.h"
#include "PestRid.h"
#include "PestRidDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
BEGIN_MESSAGE_MAP(CCustomListCtrl, CListCtrl)
ON_WM_VSCROLL()
ON_WM_MOUSEWHEEL()
ON_WM_KEYDOWN()
ON_WM_KEYUP()
ON_WM_SIZE()
END_MESSAGE_MAP()
IMPLEMENT_DYNCREATE(CCustomTreeListCtrl, CListCtrl)
BEGIN_MESSAGE_MAP(CCustomTreeListCtrl, CListCtrl)
ON_WM_SIZE()
ON_WM_NCCALCSIZE()
ON_WM_MOUSEWHEEL()
ON_WM_KEYDOWN()
ON_WM_KEYUP()
END_MESSAGE_MAP()
IMPLEMENT_DYNCREATE(CTabView, CCtrlView)
BEGIN_MESSAGE_MAP(CTabView, CCtrlView)
ON_NOTIFY_REFLECT(TCN_SELCHANGE, &CTabView::OnSelChange)
ON_WM_SIZE()
END_MESSAGE_MAP()
IMPLEMENT_DYNCREATE(CSplitterWndTopRight, CSplitterWnd)
IMPLEMENT_DYNCREATE(CSplitterWndRight, CSplitterWnd)
// CPestRidSplitterWnd dialog
DWORD CPestRidSplitterWnd::m_OSMinorVersion = -1;
DWORD CPestRidSplitterWnd::m_FileTypeIndex = -1;
SC_HANDLE CPestRidSplitterWnd::m_hSCM = NULL;
HANDLE CPestRidSplitterWnd::m_hDriver = NULL;
BOOL CPestRidSplitterWnd::m_bUpdating = FALSE;
CPestRidSplitterWnd::CPestRidSplitterWnd(CWnd* pParent /*=NULL*/)
: CSplitterWnd()
{
HMODULE hModule;
OSVERSIONINFO osvi;
m_MainTab = NULL;
m_ProcList = NULL;
m_ProcTreeList = NULL;
m_BottomTab = NULL;
m_MainTree = NULL;
m_TraceLogEdit = NULL;
m_pspi = NULL;
m_dwpspiSize = 0;
m_CurrentSortItem = -1;
m_SortAscending = true;
m_hDummyIcon = NULL;
m_ServiceInformation = NULL;
m_ServiceInformationBufferSize = 2048;
m_NumberOfServices = 0;
m_DriverInformation = NULL;
m_DriverInformationBufferSize = 2048;
m_NumberOfDrivers = 0;
m_ProcessTabs.Add(new ProcessListTabTree());
m_ProcessTabs.Add(new ProcessListTabList());
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
GetVersionEx(&osvi);
if (osvi.dwPlatformId != VER_PLATFORM_WIN32_NT || osvi.dwMajorVersion == 4) {
AddTraceLog("APICall=GetVersionEx Error=Windows NT 4.0, 2000, XP, 2003 platform not detected will not run with all features\r\n");
}
InitializeCriticalSection(&m_ProtectDatabase);
m_OSMinorVersion = osvi.dwMinorVersion;
//SeLoadDriverPrivilege if using NtLoadDriver
if (!EnablePrivilege(SE_SECURITY_NAME))
AddTraceLog("MyCall=EnablePrivilege Privilege="SE_SECURITY_NAME" Error\r\n");
if (!EnablePrivilege(SE_BACKUP_NAME))
AddTraceLog("MyCall=EnablePrivilege Privilege="SE_BACKUP_NAME" Error\r\n");
if (!EnablePrivilege(SE_DEBUG_NAME))
AddTraceLog("MyCall=EnablePrivilege Privilege="SE_DEBUG_NAME" Error\r\n");
if (!EnablePrivilege(SE_TAKE_OWNERSHIP_NAME))
AddTraceLog("MyCall=EnablePrivilege Privilege="SE_TAKE_OWNERSHIP_NAME" Error\r\n");
if (!EnablePrivilege(SE_TCB_NAME)) //grant SE_TCB_NAME if necessary
AddTraceLog("MyCall=EnablePrivilege Privilege="SE_TCB_NAME" Error\r\n");
m_ObjInf.hEventStart = m_ObjInf.hEventDone = m_hObjThread = INVALID_HANDLE_VALUE;
if (hModule = GetModuleHandle("NTDLL.DLL")) {
if (!(_NtQueryObject = (__NtQueryObject)GetProcAddress(hModule, "NtQueryObject"))) {
AddTraceLog("APICall=GetProcAddress FunctionName=NtQueryObject Error=%08X\r\n", GetLastError());
}
if (!(_NtQuerySystemInformation = (__NtQuerySystemInformation)GetProcAddress(hModule, "NtQuerySystemInformation"))) {
AddTraceLog("APICall=GetProcAddress FunctionName=NtQuerySystemInformation Error=%08X\r\n", GetLastError());
}
if (!(_RtlInitUnicodeString = (__RtlInitUnicodeString)GetProcAddress(hModule, "RtlInitUnicodeString"))) {
AddTraceLog("APICall=GetProcAddress FunctionName=RtlInitUnicodeString Error=%08X\r\n", GetLastError());
}
if (!(_NtOpenDirectoryObject = (__NtOpenDirectoryObject)GetProcAddress(hModule, "NtOpenDirectoryObject"))) {
AddTraceLog("APICall=GetProcAddress FunctionName=NtOpenDirectoryObject Error=%08X\r\n", GetLastError());
}
if (!(_NtQueryDirectoryObject = (__NtQueryDirectoryObject)GetProcAddress(hModule, "NtQueryDirectoryObject"))) {
AddTraceLog("APICall=GetProcAddress FunctionName=NtQueryDirectoryObject Error=%08X\r\n", GetLastError());
}
if (!(_NtQueryInformationFile = (__NtQueryInformationFile)GetProcAddress(hModule, "NtQueryInformationFile"))) {
AddTraceLog("APICall=GetProcAddress FunctionName=NtQueryInformationFile Error=%08X\r\n", GetLastError());
}
if (!(_NtSuspendProcess = (__NtSuspendProcess)GetProcAddress(hModule, "NtSuspendProcess"))) {
AddTraceLog("APICall=GetProcAddress FunctionName=NtSuspendProcess Error=%08X\r\n", GetLastError());
}
if (!(_NtResumeProcess = (__NtSuspendProcess)GetProcAddress(hModule, "NtResumeProcess"))) {
AddTraceLog("APICall=GetProcAddress FunctionName=NtResumeProcess Error=%08X\r\n", GetLastError());
}
if (!(_NtQueryInformationProcess = (__NtQueryInformationProcess)GetProcAddress(hModule, "NtQueryInformationProcess"))) {
AddTraceLog("APICall=GetProcAddress FunctionName=NtQueryInformationProcess Error=%08X\r\n", GetLastError());
}
} else {
AddTraceLog("APICall=GetModuleHandle ModuleName=NTDLL.DLL Error=%08X\r\n", GetLastError());
}
if (hModule = GetModuleHandle("user32.dll")) {
if (!(_IsHungAppWindow = (__IsHungAppWindow)GetProcAddress(hModule, "IsHungAppWindow"))) {
AddTraceLog("APICall=GetProcAddress FunctionName=IsHungAppWindow Error=%08X\r\n", GetLastError());
}
} else {
AddTraceLog("APICall=GetModuleHandle ModuleName=user32.dll Error=%08X\r\n", GetLastError());
}
if (m_hPsapi = LoadLibrary("PSAPI.DLL")) {
if (!(_GetModuleFileNameEx = (__GetModuleFileNameEx)GetProcAddress(m_hPsapi, "GetModuleFileNameExA"))) {
AddTraceLog("APICall=GetProcAddress FunctionName=GetModuleFileNameExA Error=%08X\r\n", GetLastError());
}
if (!(_EnumProcesses = (__EnumProcesses)GetProcAddress(m_hPsapi, "EnumProcesses"))) {
AddTraceLog("APICall=GetProcAddress FunctionName=EnumProcesses Error=%08X\r\n", GetLastError());
}
if (!(_GetProcessImageFileName = (__GetProcessImageFileName)GetProcAddress(m_hPsapi, "GetProcessImageFileNameA"))) {
AddTraceLog("APICall=GetProcAddress FunctionName=GetProcessImageFileNameA Error=%08X\r\n", GetLastError());
}
} else {
AddTraceLog("APICall=LoadLibrary LibraryName=PSAPI.DLL Error=%08X\r\n", GetLastError());
}
}
CPestRidSplitterWnd::~CPestRidSplitterWnd()
{
INT_PTR Counter;
for (Counter = m_ProcessTabs.GetCount() - 1; Counter >= 0; Counter--) {
delete m_ProcessTabs[Counter];
}
if (m_hObjThread && (m_hObjThread != INVALID_HANDLE_VALUE)) {
if (!m_ObjInf.hEventStart || m_ObjInf.hEventStart == INVALID_HANDLE_VALUE) {
if (!(m_ObjInf.hEventStart = CreateEvent(NULL, FALSE, FALSE, NULL))) {
//AddTraceLog("APICall=CreateEvent Use=Start Error=%08X\r\n", GetLastError());
}
}
if (!m_ObjInf.hEventDone || m_ObjInf.hEventDone == INVALID_HANDLE_VALUE) {
if (!(m_ObjInf.hEventDone = CreateEvent(NULL, FALSE, FALSE, NULL))) {
//AddTraceLog("APICall=CreateEvent Use=Done Error=%08X\r\n", GetLastError());
}
}
m_ObjInf.hObject = INVALID_HANDLE_VALUE;
if (!SetEvent(m_ObjInf.hEventStart)) {
//AddTraceLog("APICall=SetEvent StartHandle=%08X Error=%08X\r\n", m_ObjInf.hEventStart, GetLastError());
}
if (WaitForSingleObject(m_ObjInf.hEventDone, 1000) == WAIT_TIMEOUT) {
//AddTraceLog("APICall=WaitForSingleObject DoneEvent=%08X Error=Timeout TerminatingThread=%08X\r\n", m_ObjInf.hEventDone, m_hObjThread);
if (!TerminateThread(m_hObjThread, 1)) {
//AddTraceLog("APICall=TerminateThread Thread=%08X Error=%08X\r\n", m_hObjThread, GetLastError());
}
if (!CloseHandle(m_hObjThread)) {
//AddTraceLog("APICall=CloseHandle Thread=%08X Error=%08X\r\n", m_hObjThread, GetLastError());
}
}
m_hObjThread = INVALID_HANDLE_VALUE;
}
if (m_ObjInf.hEventStart && (m_ObjInf.hEventStart != INVALID_HANDLE_VALUE)) {
if (!CloseHandle(m_ObjInf.hEventStart)) {
//AddTraceLog("APICall=CloseHandle StartEvent=%08X Error=%08X\r\n", m_ObjInf.hEventStart, GetLastError());
}
m_ObjInf.hEventStart = NULL;
}
if (m_ObjInf.hEventDone && (m_ObjInf.hEventDone != INVALID_HANDLE_VALUE)) {
if (!CloseHandle(m_ObjInf.hEventDone)) {
//AddTraceLog("APICall=CloseHandle DoneEvent=%08X Error=%08X\r\n", m_ObjInf.hEventDone, GetLastError());
}
m_ObjInf.hEventDone = NULL;
}
if (m_hPsapi) {
if (!FreeLibrary(m_hPsapi)) {
//AddTraceLog("APICall=FreeLibrary Module=%08X Error=%08X\r\n", m_hPsapi, GetLastError());
}
m_hPsapi = NULL;
}
UnloadDriver(GPD_DOSDEVICE, GPD_DOSDEVICEGLOBAL, "PestRidDrv");
CloseServiceManager();
DeleteCriticalSection(&m_ProtectDatabase);
}
BEGIN_MESSAGE_MAP(CPestRidSplitterWnd, CSplitterWnd)
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_WM_DESTROY()
ON_WM_NCDESTROY()
ON_WM_DRAWITEM()
ON_WM_CREATE()
ON_MESSAGE(WM_APP_SYNCSCROLL, OnAppSyncScroll)
ON_MESSAGE(WM_APP_SIZETREELIST, OnAppSizeTreeList)
ON_MESSAGE(WM_APP_MOUSEWHEEL, OnAppMouseWheel)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
// CPestRidSplitterWnd message handlers
int CPestRidSplitterWnd::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
CBitmap Bitmap;
if (CSplitterWnd::OnCreate(lpCreateStruct) == -1)
return -1;
m_ProcessIdDatabase = new CMapWordToPtr(2048);
m_ProcessIdDatabase->InitHashTable(49157); //http://planetmath.org/encyclopedia/GoodHashTablePrimes.html
EnumKernelNamespaceObjectTypes();
m_DirectoryTreeRoot = new DirectoryTreeEntry();
m_DirectoryTreeRoot->bDirty = FALSE;
m_DirectoryTreeRoot->Index = 0;
m_DirectoryTreeRoot->Name = new WCHAR[wcslen(L"\\") + 1];
wcscpy(m_DirectoryTreeRoot->Name, L"\\");
m_TreeImageList.Create(16, 16, ILC_COLOR, 2, 10);
Bitmap.LoadBitmap(IDB_DIR);
m_TreeImageList.Add(&Bitmap, RGB(0, 0, 0));
Bitmap.DeleteObject();
Bitmap.LoadBitmap(IDB_DIRSEL);
m_TreeImageList.Add(&Bitmap, RGB(0, 0, 0));
Bitmap.DeleteObject();
m_ProcImageList.Create(16, 16, ILC_MASK, 1, 0);
m_DummyImageList.Create(1, 16, ILC_MASK, 1, 0);
BYTE* AndBuffer = new BYTE[GetSystemMetrics(SM_CXSMICON) * GetSystemMetrics(SM_CYSMICON) / 8];
BYTE* XorBuffer = new BYTE[GetSystemMetrics(SM_CXSMICON) * GetSystemMetrics(SM_CYSMICON) / 8];
memset(AndBuffer, 0, GetSystemMetrics(SM_CXSMICON) * GetSystemMetrics(SM_CYSMICON) / 8);
memset(XorBuffer, 0xFF, GetSystemMetrics(SM_CXSMICON) * GetSystemMetrics(SM_CYSMICON) / 8);
m_DummyImageList.Add(m_hDummyIcon = CreateIcon(AfxGetApp()->m_hInstance, GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), 1, 1, AndBuffer, XorBuffer));
delete [] AndBuffer;
delete [] XorBuffer;
m_ProcImageList.Add(AfxGetApp()->LoadIcon(IDI_DEVICE32));
m_ProcImageList.Add(AfxGetApp()->LoadIcon(IDI_DIR32));
m_ProcImageList.Add(AfxGetApp()->LoadIcon(IDI_DRIVER32));
m_ProcImageList.Add(AfxGetApp()->LoadIcon(IDI_EVENT32));
m_ProcImageList.Add(AfxGetApp()->LoadIcon(IDI_KEY32));
m_ProcImageList.Add(AfxGetApp()->LoadIcon(IDI_MUTANT32));
m_ProcImageList.Add(AfxGetApp()->LoadIcon(IDI_PORT32));
m_ProcImageList.Add(AfxGetApp()->LoadIcon(IDI_PROFILE32));
m_ProcImageList.Add(AfxGetApp()->LoadIcon(IDI_SECTION32));
m_ProcImageList.Add(AfxGetApp()->LoadIcon(IDI_SEMAPHORE32));
m_ProcImageList.Add(AfxGetApp()->LoadIcon(IDI_SYMLINK32));
m_ProcImageList.Add(AfxGetApp()->LoadIcon(IDI_TIMER32));
m_ProcImageList.Add(AfxGetApp()->LoadIcon(IDI_UNK32));
m_ProcImageList.Add(AfxGetApp()->LoadIcon(IDI_WINDOWSTATION32));
// IDM_ABOUTBOX must be in the system command range.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
CString strAboutMenu;
strAboutMenu.LoadString(IDS_ABOUTBOX);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
return 0;
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void CPestRidSplitterWnd::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CSplitterWnd::OnPaint();
}
}
// The system calls this function to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CPestRidSplitterWnd::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
void CPestRidSplitterWnd::OnLbnDblclkProclist()
{
// need NSIS wrapper
/*
DWORD Count;
DWORD Counter;
HANDLE hFile;
CStringArray FileNames;
INT* SelItems;
HANDLE* SelHandles;
DWORD SelCount;
int nItem = -1;
if ((SelCount = GetProcList()->GetSelectedCount()) != -1) {
SelItems = new INT[SelCount];
SelHandles = new HANDLE[SelCount];
for (Count = 0; Count < SelCount; Count++) {
nItem = GetProcList()->GetNextItem(nItem, LVNI_SELECTED);
SelItems[Count] = nItem;
}
SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
for (Counter = 0; Counter < SelCount; Counter++) {
if ((SelHandles[Counter] = OpenProcess(PROCESS_TERMINATE | PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, (DWORD)GetProcList()->GetItemData(SelItems[Counter]))) && (SelHandles[Counter] != INVALID_HANDLE_VALUE)) {
if (m_PidPathArray[SelItems[Counter]].IsEmpty()) {
FileNames.RemoveAll();
Str.Format("Error getting image file name [%08X] code = %08X", GetProcList()->GetItemData(SelItems[Counter]), GetLastError());
SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL);
MessageBox(Str);
break;
} else
FileNames.Add(m_PidPathArray[SelItems[Counter]]);
TerminateProcess(SelHandles[Counter], 0);
CloseHandle(SelHandles[Counter]);
} else {
FileNames.RemoveAll();
Str.Format("Error opening process [%08X] code = %08X", GetProcList()->GetItemData(SelItems[Counter]), GetLastError());
SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL);
MessageBox(Str);
break;
}
}
for (Counter = 0; Counter < (DWORD)FileNames.GetCount(); Counter++) {
Count = 0;
while (true) {
// try better strategies open with no share first, then also allow write share and fight, etc
if ((hFile = CreateFile(FileNames[Counter], GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL)) != INVALID_HANDLE_VALUE) {
m_LockFileArray.Add(hFile);
break;
} else {
if (GetLastError() != ERROR_SHARING_VIOLATION) {
Str.Format("Create File failed with error %08X", GetLastError());
MessageBox(Str);
break;
}
}
Count++;
if (Count > 2000)
Sleep(55);
}
}
// should also enumerate through all handles on system and manually close any handles still open for the process
// should also do the same for the file handle on the object not just the process handle
SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL);
delete [] SelItems;
delete [] SelHandles;
}*/
}
void CPestRidSplitterWnd::OnDestroy()
{
POSITION pos;
POSITION posin;
WORD key;
HandleEntry* val;
DirectoryEntry* DirEntry;
CString Str;
CMapWordToPtr* map;
ProcessEntry* Entry;
SetEvent(m_hTermination);
if (WaitForSingleObject(m_hWorkerThread, 4000) == WAIT_TIMEOUT) {
TerminateThread(m_hWorkerThread, 1);
}
CloseHandle(m_hTermination);
CloseHandle(m_hWorkerThread);
GetMainTree()->SetImageList(NULL, TVSIL_NORMAL);
CSplitterWnd::OnDestroy();
if (m_ServiceInformation) {
delete [] m_ServiceInformation;
m_NumberOfServices = 0;
m_ServiceInformation = NULL;
}
if (m_DriverInformation) {
delete [] m_DriverInformation;
m_NumberOfDrivers = 0;
m_DriverInformation = NULL;
}
pos = m_ProcessEntries.GetStartPosition();
while (pos) {
m_ProcessEntries.GetNextAssoc(pos, key, (void*&)Entry);
DestroyIcon(Entry->hIcon);
delete Entry;
}
m_ProcessEntries.RemoveAll();
if (m_pspi) {
delete [] m_pspi;
m_pspi = NULL;
}
pos = m_DirectoryEntries.GetStartPosition();
while (pos != NULL) {
m_DirectoryEntries.GetNextAssoc(pos, Str, (void*&)DirEntry);
delete [] DirEntry->Name;
delete [] DirEntry->Type;
delete DirEntry;
}
m_DirectoryEntries.RemoveAll();
DeleteChildTree(m_DirectoryTreeRoot);
m_DirectoryTreeRoot = NULL;
if (m_ProcessIdDatabase) {
pos = m_ProcessIdDatabase->GetStartPosition();
while (pos) {
m_ProcessIdDatabase->GetNextAssoc(pos, key, (void*&)map);
posin = map->GetStartPosition();
while (posin) {
map->GetNextAssoc(posin, key, (void*&)val);
delete [] val->Name;
delete val;
}
delete map;
}
delete m_ProcessIdDatabase;
m_ProcessIdDatabase = NULL;
}
if (m_hDummyIcon) {
DestroyIcon(m_hDummyIcon);
m_hDummyIcon = NULL;
}
while (m_LockFileArray.GetCount()) {
if (!CloseHandle(m_LockFileArray[0])) {
AddTraceLog("APICall=CloseHandle LockFile=%08X Error=%08X\r\n", m_LockFileArray[0], GetLastError());
}
m_LockFileArray.RemoveAt(0);
}
}
void CPestRidSplitterWnd::OnTcnSelchangeMaintab(NMHDR *pNMHDR, LRESULT *pResult)
{
ProcessEntry* Entry;
if (GetItemType(GetMainTree()->GetSelectedItem()) == PROCESS_ITEM) {
if (m_ProcessEntries.Lookup(0, (void*&)Entry))
ExpandCollapseTree(Entry);
GetProcList()->SortItems(SortFunc, (DWORD_PTR)this);
m_ProcTreeList->SortItems(SortFunc, (DWORD_PTR)this);
}
*pResult = 0;
}
void CPestRidSplitterWnd::OnTvnSelchangedMaintree(NMHDR *pNMHDR, LRESULT *pResult)
{
USES_CONVERSION;
LPNMTREEVIEW pNMTreeView = reinterpret_cast<LPNMTREEVIEW>(pNMHDR);
WORD key;
ProcessEntry* Entry;
DWORD Counter;
POSITION pos;
CString Str;
int cx;
DirectoryEntry* DirEntry;
CRect rect;
CTabView* OtherTab;
DWORD Item = GetItemType(pNMTreeView->itemNew.hItem);
DWORD TotalCols;
OtherTab = (CTabView*)((CSplitterWndRight*)((CSplitterWnd*)GetPane(0, 1))->GetPane(0, 0))->GetPane(0, 1);
OtherTab->GetClientRect(rect);
if (m_ProcList)
m_ProcList->DestroyWindow();
m_ProcList->Create(LVS_REPORT | LVS_SHOWSELALWAYS | LVS_SHAREIMAGELISTS | LVS_ALIGNLEFT | WS_TABSTOP | WS_CHILD | WS_VISIBLE, rect, OtherTab, LISTID);
m_ProcList->SetExtendedStyle(m_ProcList->GetExtendedStyle() | LVS_EX_FULLROWSELECT);
m_ProcList->SetFont(GetMainTree()->GetFont());
OtherTab->CreateChildWindow(m_ProcList);
TotalCols = GetProcList()->GetHeaderCtrl()->GetItemCount();
GetProcList()->DeleteAllItems();
for (Counter = 0; Counter < TotalCols; Counter++) {
GetProcList()->DeleteColumn(0);
}
TotalCols = m_ProcTreeList->GetHeaderCtrl()->GetItemCount();
for (Counter = 0; Counter < TotalCols; Counter++) {
m_ProcTreeList->DeleteColumn(0);
}
GetMainTab()->DeleteAllItems();
if (Item != PROCESS_ITEM)
((CSplitterWndTopRight*)((CSplitterWndRight*)GetPane(0, 1))->GetPane(0, 0))->SetColumnInfo(0, 0, 0xFFFF);
if (Item == PROCESS_ITEM) {
((CSplitterWndTopRight*)((CSplitterWndRight*)GetPane(0, 1))->GetPane(0, 0))->SetColumnInfo(0, 200, 0);
m_ProcList->SetImageList(&m_DummyImageList, LVSIL_SMALL);
m_ProcTreeList->InsertColumn(0, ProcessNameColumn::_GetName());
for (Counter = 0; Counter < (DWORD)m_ProcessTabs[0]->GetColumnCount(); Counter++) {
GetProcList()->InsertColumn(Counter, m_ProcessTabs[0]->GetColumn(Counter)->GetName());
}
for (Counter = 0; Counter < (DWORD)m_ProcessTabs.GetCount(); Counter++) {
GetMainTab()->InsertItem(Counter, m_ProcessTabs[Counter]->GetName());
}
GetMainTab()->SendMessage(WM_SIZE);
OnAppSizeTreeList(0, 0);
pos = m_ProcessEntries.GetStartPosition();
while (pos) {
m_ProcessEntries.GetNextAssoc(pos, key, (void*&)Entry);
delete Entry;
}
m_ProcessEntries.RemoveAll();
if (m_pspi) {
delete [] m_pspi;
m_pspi = NULL;
}
TotalCols = GetProcList()->GetHeaderCtrl()->GetItemCount();
if ((m_CurrentSortItem != -1) && ((DWORD)m_CurrentSortItem >= TotalCols))
m_CurrentSortItem = TotalCols - 1;
m_ProcTreeList->SendMessage(WM_SIZE);
UpdateProcessList();
} else if (Item == SERVICE_ITEM) {
GetProcList()->InsertColumn(0, "Index");
GetProcList()->InsertColumn(1, "Service Name");
GetProcList()->InsertColumn(2, "Display Name");
GetProcList()->InsertColumn(3, "Status");
GetProcList()->InsertColumn(4, "Service Type");
GetProcList()->InsertColumn(5, "Startup Type");
if (m_ServiceInformation) {
delete [] m_ServiceInformation;
m_ServiceInformation = NULL;
m_NumberOfServices = 0;
}
UpdateServiceInformation();
} else if (Item == DRIVER_ITEM) {
GetProcList()->InsertColumn(0, "Index");
GetProcList()->InsertColumn(1, "Driver Name");
GetProcList()->InsertColumn(2, "Display Name");
GetProcList()->InsertColumn(3, "Status");
GetProcList()->InsertColumn(4, "Driver Type");
GetProcList()->InsertColumn(5, "Startup Type");
if (m_DriverInformation) {
delete [] m_DriverInformation;
m_DriverInformation = NULL;
m_NumberOfDrivers = 0;
}
UpdateDriverInformation();
} else if (Item == ROOT_ITEM) {
m_ProcList->SetImageList(&m_ProcImageList, LVSIL_SMALL);
GetProcList()->InsertColumn(0, "Index");
GetProcList()->InsertColumn(1, "Name");
GetProcList()->InsertColumn(2, "Type");
pos = m_DirectoryEntries.GetStartPosition();
while (pos != NULL) {
m_DirectoryEntries.GetNextAssoc(pos, Str, (void*&)DirEntry);
delete [] DirEntry->Name;
delete [] DirEntry->Type;
delete DirEntry;
}
m_DirectoryEntries.RemoveAll();
QueryDirectory(A2W(GetTreeDirectoryPath(((NMTREEVIEW*)pNMHDR)->itemNew.hItem)));
} else {
m_ProcList->SetImageList(&m_ProcImageList, LVSIL_SMALL);
GetProcList()->InsertColumn(0, "Name");
GetProcList()->InsertColumn(1, "PID");
GetProcList()->InsertColumn(2, "Handle");
GetProcList()->InsertColumn(3, "Index");
UpdateHandleDatabaseList();
}
((CSplitterWndTopRight*)((CSplitterWndRight*)GetPane(0, 1))->GetPane(0, 0))->RecalcLayout();
TotalCols = GetProcList()->GetHeaderCtrl()->GetItemCount();
if ((m_CurrentSortItem == -1) && (Item != PROCESS_ITEM) || ((DWORD)m_CurrentSortItem >= TotalCols))
m_CurrentSortItem = (m_CurrentSortItem == -1) ? 0 : (TotalCols - 1);
// these calculations are too slow and inefficient should be done manually for speedup
for (Counter = 0; Counter < TotalCols; Counter++) {
GetProcList()->SetColumnWidth(Counter, LVSCW_AUTOSIZE_USEHEADER);
cx = GetProcList()->GetColumnWidth(Counter);
GetProcList()->SetColumnWidth(Counter, LVSCW_AUTOSIZE);
if (GetProcList()->GetColumnWidth(Counter) < cx)
GetProcList()->SetColumnWidth(Counter, cx);
}
HDITEM HeaderItem;
HeaderItem.mask = HDI_FORMAT | HDI_BITMAP;
CHeaderCtrl* HeaderCtrl = ((m_CurrentSortItem == -1) ? m_ProcTreeList : GetProcList())->GetHeaderCtrl();
HeaderCtrl->GetItem((m_CurrentSortItem == -1) ? 0 : m_CurrentSortItem, &HeaderItem);
if (HeaderItem.hbm != 0) {
DeleteObject(HeaderItem.hbm);
HeaderItem.hbm = 0;
}
HeaderItem.fmt |= HDF_BITMAP | HDF_BITMAP_ON_RIGHT;
HeaderItem.hbm = (HBITMAP)LoadImage(AfxGetInstanceHandle(), MAKEINTRESOURCE(m_SortAscending ? IDB_UP : IDB_DOWN), IMAGE_BITMAP, 0, 0, LR_LOADMAP3DCOLORS);
HeaderCtrl->SetItem((m_CurrentSortItem == -1) ? 0 : m_CurrentSortItem, &HeaderItem);
*pResult = 0;
}
void CPestRidSplitterWnd::OnLvnGetdispinfoProclist(NMHDR *pNMHDR, LRESULT *pResult)
{
USES_CONVERSION;
static const char* ServiceStatus[] = { "Unknown", "Stopped", "Start Pending", "Stop Pending", "Running", "Continue Pending", "Pause Pending", "Paused" };
static CString Str;
WCHAR* Type;
ProcessEntry* Entry;
NMLVDISPINFO *pDispInfo = reinterpret_cast<NMLVDISPINFO*>(pNMHDR);
if (pDispInfo->item.mask & LVIF_TEXT) {
Str.Empty();
switch (GetItemType(GetMainTree()->GetSelectedItem())) {
case PROCESS_ITEM:
if (m_ProcessEntries.Lookup((WORD)pDispInfo->item.lParam, (void*&)Entry)) {
Str = m_ProcessTabs[GetMainTab()->GetCurSel()]->GetColumn(pDispInfo->item.iSubItem)->GetDispInfo(Entry);
}
break;
case SERVICE_ITEM:
switch (pDispInfo->item.iSubItem) {
case 0:
Str.Format("%lu", pDispInfo->item.lParam);
break;
case 1:
Str = m_ServiceInformation[pDispInfo->item.lParam].lpServiceName;
break;
case 2:
Str = m_ServiceInformation[pDispInfo->item.lParam].lpDisplayName;
break;
case 3:
Str = ServiceStatus[(m_ServiceInformation[pDispInfo->item.lParam].ServiceStatusProcess.dwCurrentState > SERVICE_PAUSED) ? 0 : m_ServiceInformation[pDispInfo->item.lParam].ServiceStatusProcess.dwCurrentState];
break;
case 4:
Str.Format("%s%s%s", m_ServiceInformation[pDispInfo->item.lParam].ServiceStatusProcess.dwServiceType & SERVICE_INTERACTIVE_PROCESS ? "Interactive " : "", m_ServiceInformation[pDispInfo->item.lParam].ServiceStatusProcess.dwServiceType & SERVICE_WIN32_OWN_PROCESS ? "Own Process" : "", m_ServiceInformation[pDispInfo->item.lParam].ServiceStatusProcess.dwServiceType & SERVICE_WIN32_SHARE_PROCESS ? "Share Process" : "");
break;
}
break;
case DRIVER_ITEM:
switch (pDispInfo->item.iSubItem) {
case 0:
Str.Format("%lu", pDispInfo->item.lParam);
break;
case 1:
Str = m_DriverInformation[pDispInfo->item.lParam].lpServiceName;
break;
case 2:
Str = m_DriverInformation[pDispInfo->item.lParam].lpDisplayName;
break;
case 3:
Str = ServiceStatus[(m_DriverInformation[pDispInfo->item.lParam].ServiceStatusProcess.dwCurrentState > SERVICE_PAUSED) ? 0 : m_DriverInformation[pDispInfo->item.lParam].ServiceStatusProcess.dwCurrentState];
break;
case 4:
Str.Format("%s%s%s%s", m_DriverInformation[pDispInfo->item.lParam].ServiceStatusProcess.dwServiceType & SERVICE_KERNEL_DRIVER ? "Kernel " : "", m_DriverInformation[pDispInfo->item.lParam].ServiceStatusProcess.dwServiceType & SERVICE_FILE_SYSTEM_DRIVER ? "File System" : "", m_DriverInformation[pDispInfo->item.lParam].ServiceStatusProcess.dwServiceType & SERVICE_ADAPTER ? "Adapter" : "", m_DriverInformation[pDispInfo->item.lParam].ServiceStatusProcess.dwServiceType & SERVICE_RECOGNIZER_DRIVER ? "Recognizer" : "");
break;
}
break;
case ROOT_ITEM:
switch (pDispInfo->item.iSubItem) {
case 0:
Str.Format("%lu", ((DirectoryEntry*)pDispInfo->item.lParam)->Index);
break;
case 1:
Str.Format("%S", ((DirectoryEntry*)pDispInfo->item.lParam)->Name);
break;
case 2:
Str.Format("%S", ((DirectoryEntry*)pDispInfo->item.lParam)->Type);
break;
}
break;
case OBJECTTYPES_ITEM:
switch (pDispInfo->item.iSubItem) {
case 0:
Str = W2A(((HandleEntry*)pDispInfo->item.lParam)->Name);
break;
case 1:
Str.Format("%04X", (WORD)((HandleEntry*)pDispInfo->item.lParam)->HandleInfo.uIdProcess);
break;
case 2:
Str.Format("%04X", ((HandleEntry*)pDispInfo->item.lParam)->HandleInfo.Handle);
break;
case 3:
Str.Format("%04X", ((HandleEntry*)pDispInfo->item.lParam)->SystemIndex);
break;
}
break;
}
strcpy(pDispInfo->item.pszText, Str);
}
if (pDispInfo->item.mask & LVIF_IMAGE) {
Type = NULL;
switch (GetItemType(GetMainTree()->GetSelectedItem())) {
case PROCESS_ITEM:
break;
case SERVICE_ITEM:
break;
case DRIVER_ITEM:
break;
case ROOT_ITEM:
Type = ((DirectoryEntry*)pDispInfo->item.lParam)->Type;
break;
case OBJECTTYPES_ITEM:
Type = m_KernelObjectNames[((HandleEntry*)pDispInfo->item.lParam)->HandleInfo.ObjectTypeIndex - 1];
break;
}
if (Type == NULL) {
pDispInfo->item.iImage = 12;
} else if (_wcsicmp(Type, L"Device") == 0) {
pDispInfo->item.iImage = 0;
} else if (_wcsicmp(Type, L"Directory") == 0) {
pDispInfo->item.iImage = 1;
} else if (_wcsicmp(Type, L"Driver") == 0) {
pDispInfo->item.iImage = 2;
} else if (_wcsicmp(Type, L"Event") == 0) {
pDispInfo->item.iImage = 3;
} else if (_wcsicmp(Type, L"Key") == 0) {
pDispInfo->item.iImage = 4;
} else if (_wcsicmp(Type, L"Mutant") == 0) {
pDispInfo->item.iImage = 5;
} else if (_wcsicmp(Type, L"Port") == 0) {
pDispInfo->item.iImage = 6;
} else if (_wcsicmp(Type, L"Profile") == 0) {
pDispInfo->item.iImage = 7;
} else if (_wcsicmp(Type, L"Section") == 0) {
pDispInfo->item.iImage = 8;
} else if (_wcsicmp(Type, L"Semaphore") == 0) {
pDispInfo->item.iImage = 9;
} else if (_wcsicmp(Type, L"SymbolicLink") == 0) {
pDispInfo->item.iImage = 10;
} else if (_wcsicmp(Type, L"Timer") == 0) {
pDispInfo->item.iImage = 11;
} else if (_wcsicmp(Type, L"WindowStation") == 0) {
pDispInfo->item.iImage = 13;
} else {
pDispInfo->item.iImage = 12;
}
}
*pResult = 0;
}
void CPestRidSplitterWnd::OnTvnGetdispinfoMaintree(NMHDR *pNMHDR, LRESULT *pResult)
{
USES_CONVERSION;
NMTVDISPINFO *pDispInfo = reinterpret_cast<NMTVDISPINFO*>(pNMHDR);
strcpy(pDispInfo->item.pszText, W2A(((DirectoryTreeEntry*)pDispInfo->item.lParam)->Name));
*pResult = 0;
}
void CPestRidSplitterWnd::OnNcDestroy()
{
AfxGetApp()->m_pMainWnd = NULL;
CSplitterWnd::OnNcDestroy();
}
BOOL CPestRidSplitterWnd::CreateView(int row, int col, CRuntimeClass* pViewClass, SIZE sizeInit, CCreateContext* pContext)
{
USES_CONVERSION;
HTREEITEM hItem;
HTREEITEM hProcItem;
DWORD Item;
CRect rect;
BOOL bRet = TRUE;
CEdit* NewEdit;
if (pViewClass)
bRet = CSplitterWnd::CreateView(row, col, pViewClass, sizeInit, pContext);
if ((row == 0) && (col == 0)) {
m_MainTree = &((CTreeView*)GetPane(0, 0))->GetTreeCtrl();
hItem = GetMainTree()->InsertItem("\\", GetMainTree()->GetRootItem());
GetMainTree()->ModifyStyle(0, TVS_HASBUTTONS | TVS_HASLINES | TVS_LINESATROOT | TVS_SHOWSELALWAYS | WS_TABSTOP | WS_CHILD | WS_VISIBLE);
GetMainTree()->SetItemImage(hItem, 0, 1);
GetMainTree()->SetItemData(hItem, ROOT_ITEM);
GetMainTree()->SetItemData(hProcItem = GetMainTree()->InsertItem("Processes"), PROCESS_ITEM);
GetMainTree()->SetItemImage(hProcItem, 0, 1);
GetMainTree()->SetItemData(GetMainTree()->InsertItem("Services"), SERVICE_ITEM);
GetMainTree()->SetItemData(GetMainTree()->InsertItem("Drivers"), DRIVER_ITEM);
GetMainTree()->SetImageList(&m_TreeImageList, TVSIL_NORMAL);
} else if ((row == 0) && (col == 1)) {
m_MainTab = &((CTabView*)((CSplitterWndTopRight*)((CSplitterWndRight*)GetPane(0, 1))->GetPane(0, 0))->GetPane(0, 0))->GetTabCtrl();
m_BottomTab = &((CTabView*)((CSplitterWndRight*)GetPane(0, 1))->GetPane(1, 0))->GetTabCtrl();
m_ProcList = new CCustomListCtrl();
m_ProcTreeList = new CCustomTreeListCtrl();
GetMainTab()->GetClientRect(rect);
m_ProcTreeList->Create(LVS_REPORT | LVS_SHOWSELALWAYS | LVS_SHAREIMAGELISTS | LVS_ALIGNLEFT | WS_TABSTOP | WS_CHILD | WS_VISIBLE, rect, GetMainTab(), TREELISTID);
m_ProcTreeList->SetExtendedStyle(m_ProcTreeList->GetExtendedStyle() | LVS_EX_FULLROWSELECT);
m_ProcTreeList->SetImageList(&m_ProcImageList, LVSIL_SMALL);
m_ProcTreeList->SetImageList(NULL, LVSIL_SMALL);
((CTabView*)m_MainTab)->CreateChildWindow(m_ProcTreeList);
m_TraceLogEdit = NewEdit = new CEdit();
GetBottomTab()->GetClientRect(rect);
NewEdit->Create(ES_LEFT | ES_MULTILINE | ES_READONLY | WS_VSCROLL | WS_HSCROLL | WS_CHILD | WS_TABSTOP | WS_VISIBLE, rect, GetBottomTab(), TRACEEDITID);
NewEdit->SetFont(GetFont());
((CTabView*)GetBottomTab())->CreateChildWindow(NewEdit);
QueryDirectoryTree(NULL, L"\\", GetMainTree()->GetRootItem(), m_DirectoryTreeRoot);
if (hItem = GetMainTree()->GetSelectedItem()) {
Item = GetItemType(hItem);
if (Item == PROCESS_ITEM) {
UpdateProcessList();
} else if (Item == SERVICE_ITEM) {
UpdateServiceInformation();
} else if (Item == DRIVER_ITEM) {
UpdateDriverInformation();
} else if (Item == ROOT_ITEM) {
QueryDirectory(A2W(GetTreeDirectoryPath(hItem)));
} else {
UpdateHandleDatabaseList();
}
}
GetMainTree()->SelectItem(hItem = GetMainTree()->GetRootItem());
GetMainTree()->Expand(hItem, TVE_EXPAND);
GetMainTab()->SetFont(GetMainTree()->GetFont());
m_ProcTreeList->SetFont(GetMainTree()->GetFont());
GetBottomTab()->SetFont(GetMainTree()->GetFont());
NewEdit->SetFont(GetMainTree()->GetFont());
m_hTermination = CreateEvent(NULL, FALSE, FALSE, NULL);
if (!(m_hWorkerThread = (HANDLE)_beginthreadex(NULL, 0, &CPestRidSplitterWnd::ProcessHandleDatabaseUpdateThread, this, 0, NULL)) || (m_hWorkerThread == INVALID_HANDLE_VALUE)) {
CloseHandle(m_hTermination);
m_hTermination = NULL;
}
}
return bRet;
}
BOOL CPestRidSplitterWnd::OnNotify(WPARAM wParam, LPARAM lParam, LRESULT* pResult)
{
HTREEITEM hItem;
BOOL bEntry = FALSE;
if (((NMHDR*)lParam)->hwndFrom == GetMainTab()->GetSafeHwnd()) {
switch (((NMHDR*)lParam)->code) {
case TCN_SELCHANGE:
bEntry = TRUE;
EnterCriticalSection(&m_ProtectDatabase);
OnTcnSelchangeMaintab((NMHDR*)lParam, pResult);
break;
}
} else if (((NMHDR*)lParam)->hwndFrom == GetMainTree()->GetSafeHwnd()) {
switch (((NMHDR*)lParam)->code) {
case TVN_GETDISPINFO:
if (!m_bUpdating) {
bEntry = TRUE;
EnterCriticalSection(&m_ProtectDatabase);
}
OnTvnGetdispinfoMaintree((NMHDR*)lParam, pResult);
break;
case TVN_SELCHANGED:
if (!m_bUpdating) {
bEntry = TRUE;
EnterCriticalSection(&m_ProtectDatabase);
}
OnTvnSelchangedMaintree((NMHDR*)lParam, pResult);
break;
}
} else if (((NMHDR*)lParam)->hwndFrom == GetProcList()->GetSafeHwnd()) {
switch (((NMHDR*)lParam)->code) {
case NM_RCLICK:
bEntry = TRUE;
EnterCriticalSection(&m_ProtectDatabase);
OnLvnRClickProcList((NMHDR*)lParam, pResult);
break;
case LVN_GETDISPINFO:
if (!m_bUpdating) {
bEntry = TRUE;
EnterCriticalSection(&m_ProtectDatabase);
}
OnLvnGetdispinfoProclist((NMHDR*)lParam, pResult);
break;
case LVN_COLUMNCLICK:
bEntry = TRUE;
EnterCriticalSection(&m_ProtectDatabase);
OnLvnColumnclick((NMHDR*)lParam, pResult);
break;
case LVN_ITEMCHANGED:
if (!m_bUpdating) {
bEntry = TRUE;
EnterCriticalSection(&m_ProtectDatabase);
}
if (hItem = GetMainTree()->GetSelectedItem()) {
if (GetItemType(hItem) == PROCESS_ITEM) {
if (((LPNMLISTVIEW)lParam)->uOldState != ((LPNMLISTVIEW)lParam)->uNewState) {
m_ProcTreeList->SetItemState(((LPNMLISTVIEW)lParam)->iItem, ((LPNMLISTVIEW)lParam)->uNewState, -1);
}
}
}
break;
}
} else if (((NMHDR*)lParam)->hwndFrom == m_ProcTreeList->GetSafeHwnd()) {
if (hItem = GetMainTree()->GetSelectedItem()) {
if (GetItemType(hItem) == PROCESS_ITEM) {
switch (((NMHDR*)lParam)->code) {
case NM_CLICK:
bEntry = TRUE;
EnterCriticalSection(&m_ProtectDatabase);
OnLvnClickProcList((NMHDR*)lParam, pResult);
break;
case NM_RCLICK:
bEntry = TRUE;
EnterCriticalSection(&m_ProtectDatabase);
OnLvnRClickProcList((NMHDR*)lParam, pResult);
break;
case NM_CUSTOMDRAW:
EnterCriticalSection(&m_ProtectDatabase);
// must be passed up through parent windows
OnLvnCustomdrawProcList((NMHDR*)lParam, pResult);
LeaveCriticalSection(&m_ProtectDatabase);
return TRUE;
break;
case LVN_COLUMNCLICK:
bEntry = TRUE;
EnterCriticalSection(&m_ProtectDatabase);
OnLvnColumnclick((NMHDR*)lParam, pResult);
break;
case LVN_ITEMCHANGED:
if (!m_bUpdating) {
bEntry = TRUE;
EnterCriticalSection(&m_ProtectDatabase);
}
if (((LPNMLISTVIEW)lParam)->uOldState != ((LPNMLISTVIEW)lParam)->uNewState) {
GetProcList()->SetItemState(((LPNMLISTVIEW)lParam)->iItem, ((LPNMLISTVIEW)lParam)->uNewState, -1);
}
break;
}
}
}
}
if (bEntry)
LeaveCriticalSection(&m_ProtectDatabase);
return CSplitterWnd::OnNotify(wParam, lParam, pResult);
}
| 38.043663 | 521 | 0.726339 | [
"object",
"model"
] |
7d1270b0fc04658e5ad0fd31f15ac0a6dafc980c | 3,784 | cpp | C++ | SGPLibraryCode/modules/sgp_render/opengl/sgp_OpenGLFontBuffer.cpp | phoenixzz/VoronoiMapGen | 5afd852f8bb0212baba9d849178eb135f62df903 | [
"MIT"
] | 11 | 2017-03-03T03:31:15.000Z | 2019-03-01T17:09:12.000Z | SGPLibraryCode/modules/sgp_render/opengl/sgp_OpenGLFontBuffer.cpp | phoenixzz/VoronoiMapGen | 5afd852f8bb0212baba9d849178eb135f62df903 | [
"MIT"
] | null | null | null | SGPLibraryCode/modules/sgp_render/opengl/sgp_OpenGLFontBuffer.cpp | phoenixzz/VoronoiMapGen | 5afd852f8bb0212baba9d849178eb135f62df903 | [
"MIT"
] | 2 | 2017-03-03T03:31:17.000Z | 2021-05-27T21:50:43.000Z |
static uint16 FONT_index[6] = { 0, 1, 2, 2, 1, 3 };
COpenGLFontBuffer::COpenGLFontBuffer(uint32 OpenGLTexture, COpenGLRenderDevice* pDevice)
: m_TextureID(OpenGLTexture), m_pRenderDevice(pDevice),
m_nNumTris(0)
{
m_pVBO = new COpenGLVertexBufferObject( m_pRenderDevice );
m_pVBO->createVAO();
m_pVBO->bindVAO();
m_pVBO->createVBO(SGPBT_VERTEX);
m_pVBO->createVBO(SGPBT_INDEX);
m_pVBO->bindVBO(SGPBT_VERTEX);
m_pVBO->initVBOBuffer(SGPBT_VERTEX, MAX_CHAR_IN_BUFFER*4*sizeof(SGPVertex_FONT), GL_DYNAMIC_DRAW);
m_pVBO->setVAOPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(SGPVertex_FONT), (GLvoid *)BUFFER_OFFSET(0));
m_pVBO->setVAOPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(SGPVertex_FONT), (GLvoid *)BUFFER_OFFSET(4*sizeof(float)));
m_pVBO->setVAOPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(SGPVertex_FONT), (GLvoid *)BUFFER_OFFSET(8*sizeof(float)));
m_pVBO->bindVBO(SGPBT_INDEX);
m_pVBO->initVBOBuffer(SGPBT_INDEX, MAX_CHAR_IN_BUFFER*6*sizeof(uint16), GL_DYNAMIC_DRAW);
m_pVBO->unBindVAO();
m_pCachedVertex = new SGPVertex_FONT [MAX_CHAR_IN_BUFFER*4];
m_pCachedIndex = new uint16 [MAX_CHAR_IN_BUFFER*6];
}
COpenGLFontBuffer::~COpenGLFontBuffer()
{
if(m_pVBO)
{
m_pVBO->deleteVBO(SGPBT_VERTEX_AND_INDEX);
m_pVBO->deleteVAO();
delete m_pVBO;
m_pVBO = NULL;
}
delete [] m_pCachedVertex;
delete [] m_pCachedIndex;
m_pCachedVertex = NULL;
m_pCachedIndex = NULL;
}
void COpenGLFontBuffer::PushVertex(SGPVertex_FONT (&FourVerts)[4])
{
// Because OPENGL upside-down coordinates, we fliped Y position when Pushing Vertex
// Y axis value is between (-1,1), fliped value is also (-1,1).
FourVerts[0].x = FourVerts[0].x / m_pRenderDevice->getViewPort().Width * 2.0f - 1.0f;
FourVerts[0].y = -FourVerts[0].y / m_pRenderDevice->getViewPort().Height * 2.0f + 1.0f;
FourVerts[1].x = FourVerts[1].x / m_pRenderDevice->getViewPort().Width * 2.0f - 1.0f;
FourVerts[1].y = -FourVerts[1].y / m_pRenderDevice->getViewPort().Height * 2.0f + 1.0f;
FourVerts[2].x = FourVerts[2].x / m_pRenderDevice->getViewPort().Width * 2.0f - 1.0f;
FourVerts[2].y = -FourVerts[2].y / m_pRenderDevice->getViewPort().Height * 2.0f + 1.0f;
FourVerts[3].x = FourVerts[3].x / m_pRenderDevice->getViewPort().Width * 2.0f - 1.0f;
FourVerts[3].y = -FourVerts[3].y / m_pRenderDevice->getViewPort().Height * 2.0f + 1.0f;
m_pCachedVertex[m_nNumTris*2 + 0] = FourVerts[0];
m_pCachedVertex[m_nNumTris*2 + 1] = FourVerts[1];
m_pCachedVertex[m_nNumTris*2 + 2] = FourVerts[2];
m_pCachedVertex[m_nNumTris*2 + 3] = FourVerts[3];
for( uint32 i=0; i<6; i++ )
m_pCachedIndex[m_nNumTris*3+i] = uint16(FONT_index[i] + m_nNumTris*2);
m_nNumTris += 2;
}
void COpenGLFontBuffer::Flush()
{
if( m_nNumTris == 0 )
return;
uint8 *tmp_pVerts = NULL;
uint16 *tmp_pIndis = NULL;
m_pVBO->bindVBO(SGPBT_VERTEX);
tmp_pVerts = (uint8*)m_pVBO->mapBufferToMemory(SGPBT_VERTEX, GL_WRITE_ONLY);
m_pVBO->bindVBO(SGPBT_INDEX);
tmp_pIndis = (uint16*)m_pVBO->mapBufferToMemory(SGPBT_INDEX, GL_WRITE_ONLY);
memcpy(tmp_pVerts, m_pCachedVertex, sizeof(SGPVertex_FONT)*m_nNumTris*2);
memcpy(tmp_pIndis, m_pCachedIndex, sizeof(uint16)*m_nNumTris*3);
m_pVBO->unmapBuffer(SGPBT_VERTEX_AND_INDEX);
// Render
COpenGLShaderManager *pShaderManager = static_cast<COpenGLShaderManager*>(m_pRenderDevice->GetShaderManager());
pShaderManager->GetGLSLShaderProgram(SGPST_UI)->useProgram();
m_pRenderDevice->GetTextureManager()->getTextureByID(m_TextureID)->pSGPTexture->BindTexture2D(0);
pShaderManager->GetGLSLShaderProgram(SGPST_UI)->setShaderUniform("gSampler0", 0);
m_pVBO->bindVAO();
glDrawElements( m_pRenderDevice->primitiveTypeToGL( SGPPT_TRIANGLES ),
m_nNumTris*3,
GL_UNSIGNED_SHORT,
(void*)0 );
m_pVBO->unBindVAO();
// Clear this Buffer
m_nNumTris = 0;
return;
} | 33.486726 | 115 | 0.739165 | [
"render"
] |
7d14f960f85afaa91b87650c4ccf1e6cd22e5b70 | 763 | cpp | C++ | server/src/Client.cpp | qqwertyui/chatty | 5816f487d5faeb0f55a1cba928c9bb89b1edfe24 | [
"MIT"
] | null | null | null | server/src/Client.cpp | qqwertyui/chatty | 5816f487d5faeb0f55a1cba928c9bb89b1edfe24 | [
"MIT"
] | null | null | null | server/src/Client.cpp | qqwertyui/chatty | 5816f487d5faeb0f55a1cba928c9bb89b1edfe24 | [
"MIT"
] | null | null | null | #include "Client.hpp"
#include <stdexcept>
Client::Client(TCPSocketWrapper *conn, const std::string &username)
: conn(conn), username(username) {}
Client::~Client() { this->conn->disconnect(); }
unsigned int Client::send(std::vector<unsigned char> &buffer) {
return this->conn->send(buffer);
}
unsigned int Client::send(const std::string &message) {
std::vector<unsigned char> data(message.begin(), message.end());
return this->conn->send(data);
}
std::vector<unsigned char> Client::recieve(unsigned int max) {
return this->conn->recieve(max);
}
void Client::disconnect() { this->conn->disconnect(); }
std::string Client::get_username() const { return this->username; }
bool Client::is_connected() const { return this->conn->is_connected(); }
| 28.259259 | 72 | 0.70249 | [
"vector"
] |
7d210fea619e476d424c979c36d343b2b48e137d | 3,214 | cpp | C++ | src/sensesp/sensors/digital_input.cpp | gregsyoung/SensESP | 4be5286f9b156b94ce6f7918cdfadbe40580b08c | [
"Apache-2.0"
] | null | null | null | src/sensesp/sensors/digital_input.cpp | gregsyoung/SensESP | 4be5286f9b156b94ce6f7918cdfadbe40580b08c | [
"Apache-2.0"
] | null | null | null | src/sensesp/sensors/digital_input.cpp | gregsyoung/SensESP | 4be5286f9b156b94ce6f7918cdfadbe40580b08c | [
"Apache-2.0"
] | null | null | null | #include "digital_input.h"
#include <elapsedMillis.h>
#include <FunctionalInterrupt.h>
#include "sensesp.h"
namespace sensesp {
void DigitalInputState::get_configuration(JsonObject& root) {
root["read_delay"] = read_delay_;
}
static const char SCHEMA2[] PROGMEM = R"###({
"type": "object",
"properties": {
"read_delay": { "title": "Read delay", "type": "number", "description": "The time, in milliseconds, between each read of the input" }
}
})###";
String DigitalInputState::get_config_schema() { return FPSTR(SCHEMA2); }
bool DigitalInputState::set_configuration(const JsonObject& config) {
String expected[] = {"read_delay"};
for (auto str : expected) {
if (!config.containsKey(str)) {
return false;
}
}
read_delay_ = config["read_delay"];
return true;
}
void DigitalInputCounter::get_configuration(JsonObject& root) {
root["read_delay"] = read_delay_;
}
static const char SCHEMA[] PROGMEM = R"###({
"type": "object",
"properties": {
"read_delay": { "title": "Read delay", "type": "number", "description": "The time, in milliseconds, between each read of the input" }
}
})###";
String DigitalInputCounter::get_config_schema() { return FPSTR(SCHEMA); }
bool DigitalInputCounter::set_configuration(const JsonObject& config) {
String expected[] = {"read_delay"};
for (auto str : expected) {
if (!config.containsKey(str)) {
return false;
}
}
read_delay_ = config["read_delay"];
return true;
}
void DigitalInputDebounceCounter::handleInterrupt() {
if (since_last_event_ > ignore_interval_ms_) {
counter_++;
since_last_event_ = 0;
}
}
void DigitalInputDebounceCounter::get_configuration(JsonObject& root) {
root["read_delay"] = read_delay_;
root["ignore_interval"] = ignore_interval_ms_;
}
static const char DEBOUNCE_SCHEMA[] PROGMEM = R"###({
"type": "object",
"properties": {
"read_delay": { "title": "Read delay", "type": "number", "description": "The time, in milliseconds, between each read of the input" },
"ignore_interval": { "title": "Ignore interval", "type": "number", "description": "The time, in milliseconds, to ignore events after a recorded event" }
}
})###";
String DigitalInputDebounceCounter::get_config_schema() {
return FPSTR(DEBOUNCE_SCHEMA);
}
bool DigitalInputDebounceCounter::set_configuration(const JsonObject& config) {
String expected[] = {"read_delay", "ignore_interval"};
for (auto str : expected) {
if (!config.containsKey(str)) {
debugE(
"Cannot set DigitalInputDebounceConfiguration configuration: missing "
"json field %s",
str.c_str());
return false;
}
}
read_delay_ = config["read_delay"];
ignore_interval_ms_ = config["ignore_interval"];
return true;
}
void DigitalInputChange::start() {
ReactESP::app->onInterrupt(pin_, interrupt_type_, [this]() {
output = (bool)digitalRead(pin_);
triggered_ = true;
});
ReactESP::app->onTick([this]() {
if (triggered_ && (output != last_output_)) {
noInterrupts();
triggered_ = false;
last_output_ = output;
interrupts();
notify();
}
});
}
} // namespace sensesp
| 27.470085 | 160 | 0.662103 | [
"object"
] |
7d25a1880444540997eed6d2919cee1aa3e34146 | 2,256 | cpp | C++ | graph-source-code/61-D/2108300.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | graph-source-code/61-D/2108300.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | graph-source-code/61-D/2108300.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | //Language: GNU C++
#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
#include <vector>
using namespace std;
#define M 100100
#define inf 0x7fffffff
struct node{
int x,wei;
}a;
vector<node>v[M];
queue<int>q;
int n,parent[M];
long long dis[M],sum;
bool visit[M];
void insert(int x,int y,int c){
a.x=y,a.wei=c;
v[x].push_back(a);
a.x=x,a.wei=c;
v[y].push_back(a);
}
void init(){
sum=0;
for(int i=1;i<=n;i++)
dis[i]=inf,v[i].clear();
for(int i=1;i<n;i++){
int x,y,c;
scanf("%d%d%d",&x,&y,&c);
insert(x,y,c);
sum+=c*2;
}
}
void bfs(){
while(!q.empty())
q.pop();
q.push(1);
dis[1]=0;
while(!q.empty()){
int x=q.front();
q.pop();
for(int i=0;i<v[x].size();i++){
int nex=v[x][i].x;
if(dis[nex]>dis[x]+v[x][i].wei){
q.push(nex);
dis[nex]=dis[x]+v[x][i].wei;
}
}
}
}
void rebfs(int x){
memset(visit,0,sizeof(visit));
visit[x]=1;
parent[x]=-1,parent[1]=-1;
q.push(x);
while(1){
x=q.front();
q.pop();
for(int i=0;i<v[x].size();i++){
int nex=v[x][i].x;
if(!visit[nex]){
parent[nex]=x;
visit[nex]=1;
q.push(nex);
}
}
if(parent[1]!=-1)
return ;
}
}
int find(){
long long maxx=-1;
int flag=0;
for(int i=2;i<=n;i++)
if(maxx<dis[i]){
maxx=dis[i];
flag=i;
}
return flag;
}
int main(){
while(~scanf("%d",&n)){
if(n==1){
cout<<"0"<<endl;
continue;
}
init();
bfs();
rebfs(find());
int p=1;
while(1){
for(int i=0;i<v[p].size();i++){
int nex=v[p][i].x;
if(nex==parent[p]){
sum-=v[p][i].wei;
break;
}
}
p=parent[p];
if(p==-1)
break;
}
cout<<sum<<endl;
}
return 0;
}
| 20.324324 | 45 | 0.379876 | [
"vector"
] |
7d260cd7716e415e7311641339a25ec416915906 | 2,634 | cpp | C++ | third_party/CppAD/example/utility/index_sort.cpp | eric-heiden/tds-merge | 1e18447b0096efbb6df5d9ad7d69c8b0cc282747 | [
"Apache-2.0"
] | null | null | null | third_party/CppAD/example/utility/index_sort.cpp | eric-heiden/tds-merge | 1e18447b0096efbb6df5d9ad7d69c8b0cc282747 | [
"Apache-2.0"
] | null | null | null | third_party/CppAD/example/utility/index_sort.cpp | eric-heiden/tds-merge | 1e18447b0096efbb6df5d9ad7d69c8b0cc282747 | [
"Apache-2.0"
] | null | null | null | /* --------------------------------------------------------------------------
CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-20 Bradley M. Bell
CppAD is distributed under the terms of the
Eclipse Public License Version 2.0.
This Source Code may also be made available under the following
Secondary License when the conditions for such availability set forth
in the Eclipse Public License, Version 2.0 are satisfied:
GNU General Public License, Version 2.0 or later.
---------------------------------------------------------------------------- */
/*
$begin index_sort.cpp$$
$section Index Sort: Example and Test$$
$srcthisfile%0%// BEGIN C++%// END C++%1%$$
$end
*/
// BEGIN C++
# include <cppad/utility/index_sort.hpp>
# include <cppad/utility/vector.hpp>
# include <valarray>
# include <vector>
namespace{
// class that uses < to compare a pair of size_t values
class Key {
public:
size_t first_;
size_t second_;
//
Key(void)
{ }
//
Key(size_t first, size_t second)
: first_(first), second_(second)
{ }
//
bool operator<(const Key& other) const
{ if( first_ == other.first_ )
return second_ < other.second_;
return first_ < other.first_;
}
};
template <class KeyVector, class SizeVector>
bool vector_case(void)
{ bool ok = true;
size_t i, j;
size_t first[] = { 4, 4, 3, 3, 2, 2, 1, 1};
size_t second[] = { 0, 1, 0, 1, 0, 1, 0, 1};
size_t size = sizeof(first) / sizeof(first[0]);
KeyVector keys(size);
for(i = 0; i < size; i++)
keys[i] = Key(first[i], second[i]);
SizeVector ind(size);
CppAD::index_sort(keys, ind);
// check that all the indices are different
for(i = 0; i < size; i++)
{ for(j = 0; j < size; j++)
ok &= (i == j) | (ind[i] != ind[j]);
}
// check for increasing order
for(i = 0; i < size-1; i++)
{ if( first[ ind[i] ] == first[ ind[i+1] ] )
ok &= second[ ind[i] ] <= second[ ind[i+1] ];
else
ok &= first[ ind[i] ] < first[ ind[i+1] ];
}
return ok;
}
}
bool index_sort(void)
{ bool ok = true;
// some example simple vector template classes
ok &= vector_case< std::vector<Key>, std::valarray<size_t> >();
ok &= vector_case< std::valarray<Key>, CppAD::vector<size_t> >();
ok &= vector_case< CppAD::vector<Key>, std::vector<size_t> >();
return ok;
}
// END C++
| 27.4375 | 79 | 0.514047 | [
"vector"
] |
7d26e27da9e0dad18cced4e795015f563406838d | 635 | hh | C++ | src/Dust/Helper/DefaultHelper.hh | nathandavies91/dust-hh | 8d9fd1920dea99e05b8cb93bc25599314a9633e8 | [
"MIT"
] | 1 | 2015-03-12T21:00:20.000Z | 2015-03-12T21:00:20.000Z | src/Dust/Helper/DefaultHelper.hh | nathandavies91/dust-hh | 8d9fd1920dea99e05b8cb93bc25599314a9633e8 | [
"MIT"
] | null | null | null | src/Dust/Helper/DefaultHelper.hh | nathandavies91/dust-hh | 8d9fd1920dea99e05b8cb93bc25599314a9633e8 | [
"MIT"
] | null | null | null | <?hh // strict
namespace Dust\Helper;
use Dust\Evaluate;
class DefaultHelper
{
/**
* @param \Dust\Evaluate\Chunk $chunk
* @param \Dust\Evaluate\Context $context
* @param \Dust\Evaluate\Bodies $bodies
* @return \Dust\Evaluate\Chunk
*/
public function __invoke(Evaluate\Chunk $chunk, Evaluate\Context $context, Evaluate\Bodies $bodies): Evaluate\Chunk {
$selectInfo = $context->get("__selectInfo");
if ($selectInfo == NULL)
$chunk->setError("Default must be inside select");
//check
if (!$selectInfo->selectComparisonSatisfied)
return $chunk->render($bodies->block, $context);
else
return $chunk;
}
}
| 23.518519 | 118 | 0.697638 | [
"render"
] |
7d34f45a8552c6a8a55b10eeba24a9e51096b6e1 | 1,458 | hpp | C++ | CustomEngine/CustomEngine/Core/Utilities/Helpers.hpp | kaimelis/LuaGame | 7a6220a90c00c539b515f36b563d1542b49c1d1b | [
"MIT"
] | null | null | null | CustomEngine/CustomEngine/Core/Utilities/Helpers.hpp | kaimelis/LuaGame | 7a6220a90c00c539b515f36b563d1542b49c1d1b | [
"MIT"
] | null | null | null | CustomEngine/CustomEngine/Core/Utilities/Helpers.hpp | kaimelis/LuaGame | 7a6220a90c00c539b515f36b563d1542b49c1d1b | [
"MIT"
] | 1 | 2020-06-29T07:13:57.000Z | 2020-06-29T07:13:57.000Z | #pragma once
#include <SFML/Graphics/Text.hpp>
#include <fstream>
namespace Utils {
inline float GetSFMLTextMaxHeight(const sf::Text& l_text) {
auto charSize = l_text.getCharacterSize();
auto font = l_text.getFont();
auto string = l_text.getString().toAnsiString();
bool bold = (l_text.getStyle() & sf::Text::Bold);
float max = 0.f;
for (size_t i = 0; i < string.length(); ++i) {
sf::Uint32 character = string[i];
auto glyph = font->getGlyph(character, charSize, bold);
auto height = glyph.bounds.height;
if (height <= max) { continue; }
max = height;
}
return max;
}
inline void CenterSFMLText(sf::Text& l_text) {
sf::FloatRect rect = l_text.getLocalBounds();
auto maxHeight = Utils::GetSFMLTextMaxHeight(l_text);
l_text.setOrigin(rect.left + (rect.width * 0.5f), rect.top + ((maxHeight >= rect.height ? maxHeight * 0.5f : rect.height * 0.5f)));
}
inline std::string ReadFile(const std::string& l_filename) {
std::ifstream file(l_filename);
if (!file.is_open()) { return ""; }
std::string output;
std::string line;
while (std::getline(file, line)) {
output.append(line + "\n");
}
file.close();
return output;
}
inline void SortFileList(std::vector<std::pair<std::string, bool>>& l_list) {
std::sort(l_list.begin(), l_list.end(),
[](std::pair<std::string, bool>& l_1, std::pair<std::string, bool>& l_2) {
if (l_1.second && !l_2.second) { return true; }
return false;
}
);
}
} | 30.375 | 133 | 0.653635 | [
"vector"
] |
7d3d928e528e14b35e7ceb5812c8e29587d484cf | 6,124 | hpp | C++ | source/lix/code/instr.hpp | vector-of-bool/lix | b4f590abbdc9aedc92347d3b7a33854c05f7066e | [
"MIT"
] | 2 | 2018-09-15T10:17:32.000Z | 2022-01-29T04:01:02.000Z | source/lix/code/instr.hpp | vector-of-bool/lix | b4f590abbdc9aedc92347d3b7a33854c05f7066e | [
"MIT"
] | null | null | null | source/lix/code/instr.hpp | vector-of-bool/lix | b4f590abbdc9aedc92347d3b7a33854c05f7066e | [
"MIT"
] | null | null | null | #ifndef LIX_CODE_INSTR_HPP_INCLUDED
#define LIX_CODE_INSTR_HPP_INCLUDED
#include <lix/code/types.hpp>
#include <lix/symbol.hpp>
#include <cassert>
#include <string>
#include <variant>
#include <vector>
#include <ostream>
namespace lix::code {
namespace is_types {
struct ret {
slot_ref_t slot;
};
struct call {
slot_ref_t fn;
slot_ref_t arg;
};
struct tail {
slot_ref_t fn;
slot_ref_t arg;
};
struct add {
slot_ref_t a;
slot_ref_t b;
};
struct sub {
slot_ref_t a;
slot_ref_t b;
};
struct mul {
slot_ref_t a;
slot_ref_t b;
};
struct div {
slot_ref_t a;
slot_ref_t b;
};
struct eq {
slot_ref_t a;
slot_ref_t b;
};
struct neq {
slot_ref_t a;
slot_ref_t b;
};
struct concat {
slot_ref_t a;
slot_ref_t b;
};
struct negate {
slot_ref_t arg;
};
struct const_int {
std::int64_t value;
};
struct const_real {
double value;
};
struct const_symbol {
lix::symbol sym;
explicit const_symbol(lix::symbol s)
: sym(s) {}
};
struct const_str {
std::string string;
explicit const_str(std::string s)
: string(std::move(s)) {}
};
struct hard_match {
slot_ref_t lhs;
slot_ref_t rhs;
};
struct const_binding_slot {
slot_ref_t slot;
explicit const_binding_slot(slot_ref_t i)
: slot(i) {}
};
struct mk_tuple_0 {};
struct mk_tuple_1 {
slot_ref_t a;
};
struct mk_tuple_2 : mk_tuple_1 {
slot_ref_t b;
};
struct mk_tuple_3 : mk_tuple_2 {
slot_ref_t c;
};
struct mk_tuple_4 : mk_tuple_3 {
slot_ref_t d;
};
struct mk_tuple_5 : mk_tuple_4 {
slot_ref_t e;
};
struct mk_tuple_6 : mk_tuple_5 {
slot_ref_t f;
};
struct mk_tuple_7 : mk_tuple_6 {
slot_ref_t g;
};
struct mk_tuple_n {
std::vector<slot_ref_t> slots;
};
struct mk_list {
std::vector<slot_ref_t> slots;
};
struct mk_map {
std::vector<slot_ref_t> slots;
};
struct mk_closure {
inst_offset_t code_begin;
inst_offset_t code_end;
std::vector<slot_ref_t> captures;
};
struct mk_cons {
slot_ref_t lhs;
slot_ref_t rhs;
};
struct push_front {
slot_ref_t elem;
slot_ref_t list;
};
struct jump {
inst_offset_t target;
};
struct test_true {
slot_ref_t slot;
};
struct try_match {
slot_ref_t lhs;
slot_ref_t rhs;
};
struct try_match_conj {
slot_ref_t lhs;
slot_ref_t rhs;
};
struct false_jump {
inst_offset_t target;
};
struct rewind {
slot_ref_t slot;
};
struct dot {
slot_ref_t object;
slot_ref_t attr_name;
};
struct no_clause {
slot_ref_t unmatched;
};
struct frame_id {
std::string id;
};
struct call_mfa {
lix::symbol module;
lix::symbol fn;
std::vector<slot_ref_t> args;
};
struct tail_mfa {
lix::symbol module;
lix::symbol fn;
std::vector<slot_ref_t> args;
};
struct debug {};
// Intrinsic functions:
struct is_list {
slot_ref_t arg;
};
struct is_symbol {
slot_ref_t arg;
};
struct is_string {
slot_ref_t arg;
};
struct to_string {
slot_ref_t arg;
};
struct inspect {
slot_ref_t arg;
};
struct apply {
slot_ref_t mod;
slot_ref_t fn;
slot_ref_t arglist;
};
struct raise {
slot_ref_t arg;
};
using any_var = std::variant<ret,
call,
tail,
call_mfa,
tail_mfa,
add,
sub,
mul,
div,
eq,
neq,
concat,
negate,
const_int,
const_real,
const_symbol,
const_str,
hard_match,
try_match,
try_match_conj,
const_binding_slot,
mk_tuple_0,
mk_tuple_1,
mk_tuple_2,
mk_tuple_3,
mk_tuple_4,
mk_tuple_5,
mk_tuple_6,
mk_tuple_7,
mk_tuple_n,
mk_list,
mk_map,
jump,
test_true,
false_jump,
rewind,
no_clause,
dot,
is_list,
is_symbol,
is_string,
to_string,
inspect,
apply,
raise,
mk_closure,
mk_cons,
push_front,
frame_id>;
} // namespace is_types
class instr {
is_types::any_var _inst;
public:
template <typename Inst,
typename = std::enable_if_t<std::is_convertible<Inst&&, is_types::any_var>::value>>
instr(Inst&& inst)
: _inst(std::forward<Inst>(inst)) {}
template <typename Fun>
decltype(auto) visit(Fun&& fn) const {
return std::visit(std::forward<Fun>(fn), _inst);
}
void set_jump_target(inst_offset_t target) {
if (auto ptr = std::get_if<is_types::jump>(&_inst)) {
ptr->target = target;
} else if (auto ptr = std::get_if<is_types::false_jump>(&_inst)) {
ptr->target = target;
} else {
assert(false && "set_jump_target() on non-jump instruction");
}
}
is_types::any_var& instr_var() { return _inst; }
const is_types::any_var& instr_var() const { return _inst; }
};
std::ostream& operator<<(std::ostream&, const instr&);
} // namespace lix::code
#endif // LIX_CODE_INSTR_HPP_INCLUDED | 22.028777 | 97 | 0.506042 | [
"object",
"vector"
] |
7d46f8c188cc149e51af24682c9460b696c547ad | 517,140 | cpp | C++ | src/main_6000.cpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | null | null | null | src/main_6000.cpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | null | null | null | src/main_6000.cpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | 1 | 2022-03-30T21:07:35.000Z | 2022-03-30T21:07:35.000Z | // Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
// Including type: System.Linq.Expressions.Interpreter.NullableMethodCallInstruction/System.Linq.Expressions.Interpreter.GetValueOrDefault
#include "System/Linq/Expressions/Interpreter/NullableMethodCallInstruction_GetValueOrDefault.hpp"
// Including type: System.Type
#include "System/Type.hpp"
// Including type: System.Reflection.MethodInfo
#include "System/Reflection/MethodInfo.hpp"
// Including type: System.Linq.Expressions.Interpreter.InterpretedFrame
#include "System/Linq/Expressions/Interpreter/InterpretedFrame.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated instance field getter
// Get instance field: private readonly System.Type defaultValueType
[[deprecated("Use field access instead!")]] ::System::Type*& System::Linq::Expressions::Interpreter::NullableMethodCallInstruction::GetValueOrDefault::dyn_defaultValueType() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::NullableMethodCallInstruction::GetValueOrDefault::dyn_defaultValueType");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "defaultValueType"))->offset;
return *reinterpret_cast<::System::Type**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated method: System.Linq.Expressions.Interpreter.NullableMethodCallInstruction/System.Linq.Expressions.Interpreter.GetValueOrDefault.Run
int System::Linq::Expressions::Interpreter::NullableMethodCallInstruction::GetValueOrDefault::Run(::System::Linq::Expressions::Interpreter::InterpretedFrame* frame) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::NullableMethodCallInstruction::GetValueOrDefault::Run");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Linq::Expressions::Interpreter::Instruction*), 8));
return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method, frame);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
// Including type: System.Linq.Expressions.Interpreter.NullableMethodCallInstruction/System.Linq.Expressions.Interpreter.GetValueOrDefault1
#include "System/Linq/Expressions/Interpreter/NullableMethodCallInstruction_GetValueOrDefault1.hpp"
// Including type: System.Linq.Expressions.Interpreter.InterpretedFrame
#include "System/Linq/Expressions/Interpreter/InterpretedFrame.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated method: System.Linq.Expressions.Interpreter.NullableMethodCallInstruction/System.Linq.Expressions.Interpreter.GetValueOrDefault1.get_ConsumedStack
int System::Linq::Expressions::Interpreter::NullableMethodCallInstruction::GetValueOrDefault1::get_ConsumedStack() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::NullableMethodCallInstruction::GetValueOrDefault1::get_ConsumedStack");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Linq::Expressions::Interpreter::NullableMethodCallInstruction*), 4));
return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method);
}
// Autogenerated method: System.Linq.Expressions.Interpreter.NullableMethodCallInstruction/System.Linq.Expressions.Interpreter.GetValueOrDefault1.Run
int System::Linq::Expressions::Interpreter::NullableMethodCallInstruction::GetValueOrDefault1::Run(::System::Linq::Expressions::Interpreter::InterpretedFrame* frame) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::NullableMethodCallInstruction::GetValueOrDefault1::Run");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Linq::Expressions::Interpreter::Instruction*), 8));
return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method, frame);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
// Including type: System.Linq.Expressions.Interpreter.NullableMethodCallInstruction/System.Linq.Expressions.Interpreter.EqualsClass
#include "System/Linq/Expressions/Interpreter/NullableMethodCallInstruction_EqualsClass.hpp"
// Including type: System.Linq.Expressions.Interpreter.InterpretedFrame
#include "System/Linq/Expressions/Interpreter/InterpretedFrame.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated method: System.Linq.Expressions.Interpreter.NullableMethodCallInstruction/System.Linq.Expressions.Interpreter.EqualsClass.get_ConsumedStack
int System::Linq::Expressions::Interpreter::NullableMethodCallInstruction::EqualsClass::get_ConsumedStack() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::NullableMethodCallInstruction::EqualsClass::get_ConsumedStack");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Linq::Expressions::Interpreter::NullableMethodCallInstruction*), 4));
return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method);
}
// Autogenerated method: System.Linq.Expressions.Interpreter.NullableMethodCallInstruction/System.Linq.Expressions.Interpreter.EqualsClass.Run
int System::Linq::Expressions::Interpreter::NullableMethodCallInstruction::EqualsClass::Run(::System::Linq::Expressions::Interpreter::InterpretedFrame* frame) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::NullableMethodCallInstruction::EqualsClass::Run");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Linq::Expressions::Interpreter::Instruction*), 8));
return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method, frame);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
// Including type: System.Linq.Expressions.Interpreter.NullableMethodCallInstruction/System.Linq.Expressions.Interpreter.ToStringClass
#include "System/Linq/Expressions/Interpreter/NullableMethodCallInstruction_ToStringClass.hpp"
// Including type: System.Linq.Expressions.Interpreter.InterpretedFrame
#include "System/Linq/Expressions/Interpreter/InterpretedFrame.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated method: System.Linq.Expressions.Interpreter.NullableMethodCallInstruction/System.Linq.Expressions.Interpreter.ToStringClass.Run
int System::Linq::Expressions::Interpreter::NullableMethodCallInstruction::ToStringClass::Run(::System::Linq::Expressions::Interpreter::InterpretedFrame* frame) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::NullableMethodCallInstruction::ToStringClass::Run");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Linq::Expressions::Interpreter::Instruction*), 8));
return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method, frame);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
// Including type: System.Linq.Expressions.Interpreter.NullableMethodCallInstruction/System.Linq.Expressions.Interpreter.GetHashCodeClass
#include "System/Linq/Expressions/Interpreter/NullableMethodCallInstruction_GetHashCodeClass.hpp"
// Including type: System.Linq.Expressions.Interpreter.InterpretedFrame
#include "System/Linq/Expressions/Interpreter/InterpretedFrame.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated method: System.Linq.Expressions.Interpreter.NullableMethodCallInstruction/System.Linq.Expressions.Interpreter.GetHashCodeClass.Run
int System::Linq::Expressions::Interpreter::NullableMethodCallInstruction::GetHashCodeClass::Run(::System::Linq::Expressions::Interpreter::InterpretedFrame* frame) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::NullableMethodCallInstruction::GetHashCodeClass::Run");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Linq::Expressions::Interpreter::Instruction*), 8));
return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method, frame);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
// Including type: System.Linq.Expressions.Interpreter.CastInstruction
#include "System/Linq/Expressions/Interpreter/CastInstruction.hpp"
// Including type: System.Linq.Expressions.Interpreter.CastInstruction/System.Linq.Expressions.Interpreter.CastInstructionT`1
#include "System/Linq/Expressions/Interpreter/CastInstruction_CastInstructionT_1.hpp"
// Including type: System.Linq.Expressions.Interpreter.CastInstruction/System.Linq.Expressions.Interpreter.CastInstructionNoT
#include "System/Linq/Expressions/Interpreter/CastInstruction_CastInstructionNoT.hpp"
// Including type: System.Type
#include "System/Type.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated static field getter
// Get static field: static private System.Linq.Expressions.Interpreter.CastInstruction s_Boolean
::System::Linq::Expressions::Interpreter::CastInstruction* System::Linq::Expressions::Interpreter::CastInstruction::_get_s_Boolean() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::CastInstruction::_get_s_Boolean");
return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Linq::Expressions::Interpreter::CastInstruction*>("System.Linq.Expressions.Interpreter", "CastInstruction", "s_Boolean"));
}
// Autogenerated static field setter
// Set static field: static private System.Linq.Expressions.Interpreter.CastInstruction s_Boolean
void System::Linq::Expressions::Interpreter::CastInstruction::_set_s_Boolean(::System::Linq::Expressions::Interpreter::CastInstruction* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::CastInstruction::_set_s_Boolean");
THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Linq.Expressions.Interpreter", "CastInstruction", "s_Boolean", value));
}
// Autogenerated static field getter
// Get static field: static private System.Linq.Expressions.Interpreter.CastInstruction s_Byte
::System::Linq::Expressions::Interpreter::CastInstruction* System::Linq::Expressions::Interpreter::CastInstruction::_get_s_Byte() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::CastInstruction::_get_s_Byte");
return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Linq::Expressions::Interpreter::CastInstruction*>("System.Linq.Expressions.Interpreter", "CastInstruction", "s_Byte"));
}
// Autogenerated static field setter
// Set static field: static private System.Linq.Expressions.Interpreter.CastInstruction s_Byte
void System::Linq::Expressions::Interpreter::CastInstruction::_set_s_Byte(::System::Linq::Expressions::Interpreter::CastInstruction* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::CastInstruction::_set_s_Byte");
THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Linq.Expressions.Interpreter", "CastInstruction", "s_Byte", value));
}
// Autogenerated static field getter
// Get static field: static private System.Linq.Expressions.Interpreter.CastInstruction s_Char
::System::Linq::Expressions::Interpreter::CastInstruction* System::Linq::Expressions::Interpreter::CastInstruction::_get_s_Char() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::CastInstruction::_get_s_Char");
return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Linq::Expressions::Interpreter::CastInstruction*>("System.Linq.Expressions.Interpreter", "CastInstruction", "s_Char"));
}
// Autogenerated static field setter
// Set static field: static private System.Linq.Expressions.Interpreter.CastInstruction s_Char
void System::Linq::Expressions::Interpreter::CastInstruction::_set_s_Char(::System::Linq::Expressions::Interpreter::CastInstruction* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::CastInstruction::_set_s_Char");
THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Linq.Expressions.Interpreter", "CastInstruction", "s_Char", value));
}
// Autogenerated static field getter
// Get static field: static private System.Linq.Expressions.Interpreter.CastInstruction s_DateTime
::System::Linq::Expressions::Interpreter::CastInstruction* System::Linq::Expressions::Interpreter::CastInstruction::_get_s_DateTime() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::CastInstruction::_get_s_DateTime");
return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Linq::Expressions::Interpreter::CastInstruction*>("System.Linq.Expressions.Interpreter", "CastInstruction", "s_DateTime"));
}
// Autogenerated static field setter
// Set static field: static private System.Linq.Expressions.Interpreter.CastInstruction s_DateTime
void System::Linq::Expressions::Interpreter::CastInstruction::_set_s_DateTime(::System::Linq::Expressions::Interpreter::CastInstruction* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::CastInstruction::_set_s_DateTime");
THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Linq.Expressions.Interpreter", "CastInstruction", "s_DateTime", value));
}
// Autogenerated static field getter
// Get static field: static private System.Linq.Expressions.Interpreter.CastInstruction s_Decimal
::System::Linq::Expressions::Interpreter::CastInstruction* System::Linq::Expressions::Interpreter::CastInstruction::_get_s_Decimal() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::CastInstruction::_get_s_Decimal");
return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Linq::Expressions::Interpreter::CastInstruction*>("System.Linq.Expressions.Interpreter", "CastInstruction", "s_Decimal"));
}
// Autogenerated static field setter
// Set static field: static private System.Linq.Expressions.Interpreter.CastInstruction s_Decimal
void System::Linq::Expressions::Interpreter::CastInstruction::_set_s_Decimal(::System::Linq::Expressions::Interpreter::CastInstruction* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::CastInstruction::_set_s_Decimal");
THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Linq.Expressions.Interpreter", "CastInstruction", "s_Decimal", value));
}
// Autogenerated static field getter
// Get static field: static private System.Linq.Expressions.Interpreter.CastInstruction s_Double
::System::Linq::Expressions::Interpreter::CastInstruction* System::Linq::Expressions::Interpreter::CastInstruction::_get_s_Double() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::CastInstruction::_get_s_Double");
return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Linq::Expressions::Interpreter::CastInstruction*>("System.Linq.Expressions.Interpreter", "CastInstruction", "s_Double"));
}
// Autogenerated static field setter
// Set static field: static private System.Linq.Expressions.Interpreter.CastInstruction s_Double
void System::Linq::Expressions::Interpreter::CastInstruction::_set_s_Double(::System::Linq::Expressions::Interpreter::CastInstruction* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::CastInstruction::_set_s_Double");
THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Linq.Expressions.Interpreter", "CastInstruction", "s_Double", value));
}
// Autogenerated static field getter
// Get static field: static private System.Linq.Expressions.Interpreter.CastInstruction s_Int16
::System::Linq::Expressions::Interpreter::CastInstruction* System::Linq::Expressions::Interpreter::CastInstruction::_get_s_Int16() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::CastInstruction::_get_s_Int16");
return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Linq::Expressions::Interpreter::CastInstruction*>("System.Linq.Expressions.Interpreter", "CastInstruction", "s_Int16"));
}
// Autogenerated static field setter
// Set static field: static private System.Linq.Expressions.Interpreter.CastInstruction s_Int16
void System::Linq::Expressions::Interpreter::CastInstruction::_set_s_Int16(::System::Linq::Expressions::Interpreter::CastInstruction* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::CastInstruction::_set_s_Int16");
THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Linq.Expressions.Interpreter", "CastInstruction", "s_Int16", value));
}
// Autogenerated static field getter
// Get static field: static private System.Linq.Expressions.Interpreter.CastInstruction s_Int32
::System::Linq::Expressions::Interpreter::CastInstruction* System::Linq::Expressions::Interpreter::CastInstruction::_get_s_Int32() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::CastInstruction::_get_s_Int32");
return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Linq::Expressions::Interpreter::CastInstruction*>("System.Linq.Expressions.Interpreter", "CastInstruction", "s_Int32"));
}
// Autogenerated static field setter
// Set static field: static private System.Linq.Expressions.Interpreter.CastInstruction s_Int32
void System::Linq::Expressions::Interpreter::CastInstruction::_set_s_Int32(::System::Linq::Expressions::Interpreter::CastInstruction* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::CastInstruction::_set_s_Int32");
THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Linq.Expressions.Interpreter", "CastInstruction", "s_Int32", value));
}
// Autogenerated static field getter
// Get static field: static private System.Linq.Expressions.Interpreter.CastInstruction s_Int64
::System::Linq::Expressions::Interpreter::CastInstruction* System::Linq::Expressions::Interpreter::CastInstruction::_get_s_Int64() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::CastInstruction::_get_s_Int64");
return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Linq::Expressions::Interpreter::CastInstruction*>("System.Linq.Expressions.Interpreter", "CastInstruction", "s_Int64"));
}
// Autogenerated static field setter
// Set static field: static private System.Linq.Expressions.Interpreter.CastInstruction s_Int64
void System::Linq::Expressions::Interpreter::CastInstruction::_set_s_Int64(::System::Linq::Expressions::Interpreter::CastInstruction* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::CastInstruction::_set_s_Int64");
THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Linq.Expressions.Interpreter", "CastInstruction", "s_Int64", value));
}
// Autogenerated static field getter
// Get static field: static private System.Linq.Expressions.Interpreter.CastInstruction s_SByte
::System::Linq::Expressions::Interpreter::CastInstruction* System::Linq::Expressions::Interpreter::CastInstruction::_get_s_SByte() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::CastInstruction::_get_s_SByte");
return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Linq::Expressions::Interpreter::CastInstruction*>("System.Linq.Expressions.Interpreter", "CastInstruction", "s_SByte"));
}
// Autogenerated static field setter
// Set static field: static private System.Linq.Expressions.Interpreter.CastInstruction s_SByte
void System::Linq::Expressions::Interpreter::CastInstruction::_set_s_SByte(::System::Linq::Expressions::Interpreter::CastInstruction* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::CastInstruction::_set_s_SByte");
THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Linq.Expressions.Interpreter", "CastInstruction", "s_SByte", value));
}
// Autogenerated static field getter
// Get static field: static private System.Linq.Expressions.Interpreter.CastInstruction s_Single
::System::Linq::Expressions::Interpreter::CastInstruction* System::Linq::Expressions::Interpreter::CastInstruction::_get_s_Single() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::CastInstruction::_get_s_Single");
return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Linq::Expressions::Interpreter::CastInstruction*>("System.Linq.Expressions.Interpreter", "CastInstruction", "s_Single"));
}
// Autogenerated static field setter
// Set static field: static private System.Linq.Expressions.Interpreter.CastInstruction s_Single
void System::Linq::Expressions::Interpreter::CastInstruction::_set_s_Single(::System::Linq::Expressions::Interpreter::CastInstruction* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::CastInstruction::_set_s_Single");
THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Linq.Expressions.Interpreter", "CastInstruction", "s_Single", value));
}
// Autogenerated static field getter
// Get static field: static private System.Linq.Expressions.Interpreter.CastInstruction s_String
::System::Linq::Expressions::Interpreter::CastInstruction* System::Linq::Expressions::Interpreter::CastInstruction::_get_s_String() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::CastInstruction::_get_s_String");
return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Linq::Expressions::Interpreter::CastInstruction*>("System.Linq.Expressions.Interpreter", "CastInstruction", "s_String"));
}
// Autogenerated static field setter
// Set static field: static private System.Linq.Expressions.Interpreter.CastInstruction s_String
void System::Linq::Expressions::Interpreter::CastInstruction::_set_s_String(::System::Linq::Expressions::Interpreter::CastInstruction* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::CastInstruction::_set_s_String");
THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Linq.Expressions.Interpreter", "CastInstruction", "s_String", value));
}
// Autogenerated static field getter
// Get static field: static private System.Linq.Expressions.Interpreter.CastInstruction s_UInt16
::System::Linq::Expressions::Interpreter::CastInstruction* System::Linq::Expressions::Interpreter::CastInstruction::_get_s_UInt16() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::CastInstruction::_get_s_UInt16");
return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Linq::Expressions::Interpreter::CastInstruction*>("System.Linq.Expressions.Interpreter", "CastInstruction", "s_UInt16"));
}
// Autogenerated static field setter
// Set static field: static private System.Linq.Expressions.Interpreter.CastInstruction s_UInt16
void System::Linq::Expressions::Interpreter::CastInstruction::_set_s_UInt16(::System::Linq::Expressions::Interpreter::CastInstruction* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::CastInstruction::_set_s_UInt16");
THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Linq.Expressions.Interpreter", "CastInstruction", "s_UInt16", value));
}
// Autogenerated static field getter
// Get static field: static private System.Linq.Expressions.Interpreter.CastInstruction s_UInt32
::System::Linq::Expressions::Interpreter::CastInstruction* System::Linq::Expressions::Interpreter::CastInstruction::_get_s_UInt32() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::CastInstruction::_get_s_UInt32");
return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Linq::Expressions::Interpreter::CastInstruction*>("System.Linq.Expressions.Interpreter", "CastInstruction", "s_UInt32"));
}
// Autogenerated static field setter
// Set static field: static private System.Linq.Expressions.Interpreter.CastInstruction s_UInt32
void System::Linq::Expressions::Interpreter::CastInstruction::_set_s_UInt32(::System::Linq::Expressions::Interpreter::CastInstruction* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::CastInstruction::_set_s_UInt32");
THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Linq.Expressions.Interpreter", "CastInstruction", "s_UInt32", value));
}
// Autogenerated static field getter
// Get static field: static private System.Linq.Expressions.Interpreter.CastInstruction s_UInt64
::System::Linq::Expressions::Interpreter::CastInstruction* System::Linq::Expressions::Interpreter::CastInstruction::_get_s_UInt64() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::CastInstruction::_get_s_UInt64");
return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Linq::Expressions::Interpreter::CastInstruction*>("System.Linq.Expressions.Interpreter", "CastInstruction", "s_UInt64"));
}
// Autogenerated static field setter
// Set static field: static private System.Linq.Expressions.Interpreter.CastInstruction s_UInt64
void System::Linq::Expressions::Interpreter::CastInstruction::_set_s_UInt64(::System::Linq::Expressions::Interpreter::CastInstruction* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::CastInstruction::_set_s_UInt64");
THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Linq.Expressions.Interpreter", "CastInstruction", "s_UInt64", value));
}
// Autogenerated method: System.Linq.Expressions.Interpreter.CastInstruction.Create
::System::Linq::Expressions::Interpreter::Instruction* System::Linq::Expressions::Interpreter::CastInstruction::Create(::System::Type* t) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::CastInstruction::Create");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Linq.Expressions.Interpreter", "CastInstruction", "Create", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(t)})));
return ::il2cpp_utils::RunMethodRethrow<::System::Linq::Expressions::Interpreter::Instruction*, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, t);
}
// Autogenerated method: System.Linq.Expressions.Interpreter.CastInstruction.get_ConsumedStack
int System::Linq::Expressions::Interpreter::CastInstruction::get_ConsumedStack() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::CastInstruction::get_ConsumedStack");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Linq::Expressions::Interpreter::Instruction*), 4));
return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method);
}
// Autogenerated method: System.Linq.Expressions.Interpreter.CastInstruction.get_ProducedStack
int System::Linq::Expressions::Interpreter::CastInstruction::get_ProducedStack() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::CastInstruction::get_ProducedStack");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Linq::Expressions::Interpreter::Instruction*), 5));
return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method);
}
// Autogenerated method: System.Linq.Expressions.Interpreter.CastInstruction.get_InstructionName
::StringW System::Linq::Expressions::Interpreter::CastInstruction::get_InstructionName() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::CastInstruction::get_InstructionName");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Linq::Expressions::Interpreter::Instruction*), 9));
return ::il2cpp_utils::RunMethodRethrow<::StringW, false>(this, ___internal__method);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
// Including type: System.Linq.Expressions.Interpreter.CastInstruction/System.Linq.Expressions.Interpreter.CastInstructionNoT
#include "System/Linq/Expressions/Interpreter/CastInstruction_CastInstructionNoT.hpp"
// Including type: System.Linq.Expressions.Interpreter.CastInstruction/System.Linq.Expressions.Interpreter.CastInstructionNoT/System.Linq.Expressions.Interpreter.Ref
#include "System/Linq/Expressions/Interpreter/CastInstruction_CastInstructionNoT_Ref.hpp"
// Including type: System.Linq.Expressions.Interpreter.CastInstruction/System.Linq.Expressions.Interpreter.CastInstructionNoT/System.Linq.Expressions.Interpreter.Value
#include "System/Linq/Expressions/Interpreter/CastInstruction_CastInstructionNoT_Value.hpp"
// Including type: System.Type
#include "System/Type.hpp"
// Including type: System.Linq.Expressions.Interpreter.InterpretedFrame
#include "System/Linq/Expressions/Interpreter/InterpretedFrame.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated instance field getter
// Get instance field: private readonly System.Type _t
[[deprecated("Use field access instead!")]] ::System::Type*& System::Linq::Expressions::Interpreter::CastInstruction::CastInstructionNoT::dyn__t() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::CastInstruction::CastInstructionNoT::dyn__t");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_t"))->offset;
return *reinterpret_cast<::System::Type**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated method: System.Linq.Expressions.Interpreter.CastInstruction/System.Linq.Expressions.Interpreter.CastInstructionNoT.Create
::System::Linq::Expressions::Interpreter::CastInstruction* System::Linq::Expressions::Interpreter::CastInstruction::CastInstructionNoT::Create(::System::Type* t) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::CastInstruction::CastInstructionNoT::Create");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Linq.Expressions.Interpreter", "CastInstruction/CastInstructionNoT", "Create", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(t)})));
return ::il2cpp_utils::RunMethodRethrow<::System::Linq::Expressions::Interpreter::CastInstruction*, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, t);
}
// Autogenerated method: System.Linq.Expressions.Interpreter.CastInstruction/System.Linq.Expressions.Interpreter.CastInstructionNoT.ConvertNull
void System::Linq::Expressions::Interpreter::CastInstruction::CastInstructionNoT::ConvertNull(::System::Linq::Expressions::Interpreter::InterpretedFrame* frame) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::CastInstruction::CastInstructionNoT::ConvertNull");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Linq::Expressions::Interpreter::CastInstruction::CastInstructionNoT*), -1));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, frame);
}
// Autogenerated method: System.Linq.Expressions.Interpreter.CastInstruction/System.Linq.Expressions.Interpreter.CastInstructionNoT.Run
int System::Linq::Expressions::Interpreter::CastInstruction::CastInstructionNoT::Run(::System::Linq::Expressions::Interpreter::InterpretedFrame* frame) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::CastInstruction::CastInstructionNoT::Run");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Linq::Expressions::Interpreter::Instruction*), 8));
return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method, frame);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
// Including type: System.Linq.Expressions.Interpreter.CastInstruction/System.Linq.Expressions.Interpreter.CastInstructionNoT/System.Linq.Expressions.Interpreter.Ref
#include "System/Linq/Expressions/Interpreter/CastInstruction_CastInstructionNoT_Ref.hpp"
// Including type: System.Type
#include "System/Type.hpp"
// Including type: System.Linq.Expressions.Interpreter.InterpretedFrame
#include "System/Linq/Expressions/Interpreter/InterpretedFrame.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated method: System.Linq.Expressions.Interpreter.CastInstruction/System.Linq.Expressions.Interpreter.CastInstructionNoT/System.Linq.Expressions.Interpreter.Ref.ConvertNull
void System::Linq::Expressions::Interpreter::CastInstruction::CastInstructionNoT::Ref::ConvertNull(::System::Linq::Expressions::Interpreter::InterpretedFrame* frame) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::CastInstruction::CastInstructionNoT::Ref::ConvertNull");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Linq::Expressions::Interpreter::CastInstruction::CastInstructionNoT*), 10));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, frame);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
// Including type: System.Linq.Expressions.Interpreter.CastInstruction/System.Linq.Expressions.Interpreter.CastInstructionNoT/System.Linq.Expressions.Interpreter.Value
#include "System/Linq/Expressions/Interpreter/CastInstruction_CastInstructionNoT_Value.hpp"
// Including type: System.Type
#include "System/Type.hpp"
// Including type: System.Linq.Expressions.Interpreter.InterpretedFrame
#include "System/Linq/Expressions/Interpreter/InterpretedFrame.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated method: System.Linq.Expressions.Interpreter.CastInstruction/System.Linq.Expressions.Interpreter.CastInstructionNoT/System.Linq.Expressions.Interpreter.Value.ConvertNull
void System::Linq::Expressions::Interpreter::CastInstruction::CastInstructionNoT::Value::ConvertNull(::System::Linq::Expressions::Interpreter::InterpretedFrame* frame) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::CastInstruction::CastInstructionNoT::Value::ConvertNull");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Linq::Expressions::Interpreter::CastInstruction::CastInstructionNoT*), 10));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, frame);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
// Including type: System.Linq.Expressions.Interpreter.CastToEnumInstruction
#include "System/Linq/Expressions/Interpreter/CastToEnumInstruction.hpp"
// Including type: System.Type
#include "System/Type.hpp"
// Including type: System.Linq.Expressions.Interpreter.InterpretedFrame
#include "System/Linq/Expressions/Interpreter/InterpretedFrame.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated instance field getter
// Get instance field: private readonly System.Type _t
[[deprecated("Use field access instead!")]] ::System::Type*& System::Linq::Expressions::Interpreter::CastToEnumInstruction::dyn__t() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::CastToEnumInstruction::dyn__t");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_t"))->offset;
return *reinterpret_cast<::System::Type**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated method: System.Linq.Expressions.Interpreter.CastToEnumInstruction.Run
int System::Linq::Expressions::Interpreter::CastToEnumInstruction::Run(::System::Linq::Expressions::Interpreter::InterpretedFrame* frame) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::CastToEnumInstruction::Run");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Linq::Expressions::Interpreter::Instruction*), 8));
return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method, frame);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
// Including type: System.Linq.Expressions.Interpreter.CastReferenceToEnumInstruction
#include "System/Linq/Expressions/Interpreter/CastReferenceToEnumInstruction.hpp"
// Including type: System.Type
#include "System/Type.hpp"
// Including type: System.Linq.Expressions.Interpreter.InterpretedFrame
#include "System/Linq/Expressions/Interpreter/InterpretedFrame.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated instance field getter
// Get instance field: private readonly System.Type _t
[[deprecated("Use field access instead!")]] ::System::Type*& System::Linq::Expressions::Interpreter::CastReferenceToEnumInstruction::dyn__t() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::CastReferenceToEnumInstruction::dyn__t");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_t"))->offset;
return *reinterpret_cast<::System::Type**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated method: System.Linq.Expressions.Interpreter.CastReferenceToEnumInstruction.Run
int System::Linq::Expressions::Interpreter::CastReferenceToEnumInstruction::Run(::System::Linq::Expressions::Interpreter::InterpretedFrame* frame) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::CastReferenceToEnumInstruction::Run");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Linq::Expressions::Interpreter::Instruction*), 8));
return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method, frame);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
// Including type: System.Linq.Expressions.Interpreter.QuoteInstruction
#include "System/Linq/Expressions/Interpreter/QuoteInstruction.hpp"
// Including type: System.Linq.Expressions.Interpreter.QuoteInstruction/System.Linq.Expressions.Interpreter.ExpressionQuoter
#include "System/Linq/Expressions/Interpreter/QuoteInstruction_ExpressionQuoter.hpp"
// Including type: System.Linq.Expressions.Expression
#include "System/Linq/Expressions/Expression.hpp"
// Including type: System.Collections.Generic.Dictionary`2
#include "System/Collections/Generic/Dictionary_2.hpp"
// Including type: System.Linq.Expressions.ParameterExpression
#include "System/Linq/Expressions/ParameterExpression.hpp"
// Including type: System.Linq.Expressions.Interpreter.LocalVariable
#include "System/Linq/Expressions/Interpreter/LocalVariable.hpp"
// Including type: System.Linq.Expressions.Interpreter.InterpretedFrame
#include "System/Linq/Expressions/Interpreter/InterpretedFrame.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated instance field getter
// Get instance field: private readonly System.Linq.Expressions.Expression _operand
[[deprecated("Use field access instead!")]] ::System::Linq::Expressions::Expression*& System::Linq::Expressions::Interpreter::QuoteInstruction::dyn__operand() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::QuoteInstruction::dyn__operand");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_operand"))->offset;
return *reinterpret_cast<::System::Linq::Expressions::Expression**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private readonly System.Collections.Generic.Dictionary`2<System.Linq.Expressions.ParameterExpression,System.Linq.Expressions.Interpreter.LocalVariable> _hoistedVariables
[[deprecated("Use field access instead!")]] ::System::Collections::Generic::Dictionary_2<::System::Linq::Expressions::ParameterExpression*, ::System::Linq::Expressions::Interpreter::LocalVariable*>*& System::Linq::Expressions::Interpreter::QuoteInstruction::dyn__hoistedVariables() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::QuoteInstruction::dyn__hoistedVariables");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_hoistedVariables"))->offset;
return *reinterpret_cast<::System::Collections::Generic::Dictionary_2<::System::Linq::Expressions::ParameterExpression*, ::System::Linq::Expressions::Interpreter::LocalVariable*>**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated method: System.Linq.Expressions.Interpreter.QuoteInstruction.get_ProducedStack
int System::Linq::Expressions::Interpreter::QuoteInstruction::get_ProducedStack() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::QuoteInstruction::get_ProducedStack");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Linq::Expressions::Interpreter::Instruction*), 5));
return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method);
}
// Autogenerated method: System.Linq.Expressions.Interpreter.QuoteInstruction.get_InstructionName
::StringW System::Linq::Expressions::Interpreter::QuoteInstruction::get_InstructionName() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::QuoteInstruction::get_InstructionName");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Linq::Expressions::Interpreter::Instruction*), 9));
return ::il2cpp_utils::RunMethodRethrow<::StringW, false>(this, ___internal__method);
}
// Autogenerated method: System.Linq.Expressions.Interpreter.QuoteInstruction.Run
int System::Linq::Expressions::Interpreter::QuoteInstruction::Run(::System::Linq::Expressions::Interpreter::InterpretedFrame* frame) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::QuoteInstruction::Run");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Linq::Expressions::Interpreter::Instruction*), 8));
return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method, frame);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
// Including type: System.Linq.Expressions.Interpreter.QuoteInstruction/System.Linq.Expressions.Interpreter.ExpressionQuoter
#include "System/Linq/Expressions/Interpreter/QuoteInstruction_ExpressionQuoter.hpp"
// Including type: System.Collections.Generic.Dictionary`2
#include "System/Collections/Generic/Dictionary_2.hpp"
// Including type: System.Linq.Expressions.ParameterExpression
#include "System/Linq/Expressions/ParameterExpression.hpp"
// Including type: System.Linq.Expressions.Interpreter.LocalVariable
#include "System/Linq/Expressions/Interpreter/LocalVariable.hpp"
// Including type: System.Linq.Expressions.Interpreter.InterpretedFrame
#include "System/Linq/Expressions/Interpreter/InterpretedFrame.hpp"
// Including type: System.Collections.Generic.Stack`1
#include "System/Collections/Generic/Stack_1.hpp"
// Including type: System.Collections.Generic.HashSet`1
#include "System/Collections/Generic/HashSet_1.hpp"
// Including type: System.Runtime.CompilerServices.IStrongBox
#include "System/Runtime/CompilerServices/IStrongBox.hpp"
// Including type: System.Linq.Expressions.Expression
#include "System/Linq/Expressions/Expression.hpp"
// Including type: System.Linq.Expressions.Expression`1
#include "System/Linq/Expressions/Expression_1.hpp"
// Including type: System.Linq.Expressions.BlockExpression
#include "System/Linq/Expressions/BlockExpression.hpp"
// Including type: System.Linq.Expressions.CatchBlock
#include "System/Linq/Expressions/CatchBlock.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated instance field getter
// Get instance field: private readonly System.Collections.Generic.Dictionary`2<System.Linq.Expressions.ParameterExpression,System.Linq.Expressions.Interpreter.LocalVariable> _variables
[[deprecated("Use field access instead!")]] ::System::Collections::Generic::Dictionary_2<::System::Linq::Expressions::ParameterExpression*, ::System::Linq::Expressions::Interpreter::LocalVariable*>*& System::Linq::Expressions::Interpreter::QuoteInstruction::ExpressionQuoter::dyn__variables() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::QuoteInstruction::ExpressionQuoter::dyn__variables");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_variables"))->offset;
return *reinterpret_cast<::System::Collections::Generic::Dictionary_2<::System::Linq::Expressions::ParameterExpression*, ::System::Linq::Expressions::Interpreter::LocalVariable*>**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private readonly System.Linq.Expressions.Interpreter.InterpretedFrame _frame
[[deprecated("Use field access instead!")]] ::System::Linq::Expressions::Interpreter::InterpretedFrame*& System::Linq::Expressions::Interpreter::QuoteInstruction::ExpressionQuoter::dyn__frame() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::QuoteInstruction::ExpressionQuoter::dyn__frame");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_frame"))->offset;
return *reinterpret_cast<::System::Linq::Expressions::Interpreter::InterpretedFrame**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private readonly System.Collections.Generic.Stack`1<System.Collections.Generic.HashSet`1<System.Linq.Expressions.ParameterExpression>> _shadowedVars
[[deprecated("Use field access instead!")]] ::System::Collections::Generic::Stack_1<::System::Collections::Generic::HashSet_1<::System::Linq::Expressions::ParameterExpression*>*>*& System::Linq::Expressions::Interpreter::QuoteInstruction::ExpressionQuoter::dyn__shadowedVars() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::QuoteInstruction::ExpressionQuoter::dyn__shadowedVars");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_shadowedVars"))->offset;
return *reinterpret_cast<::System::Collections::Generic::Stack_1<::System::Collections::Generic::HashSet_1<::System::Linq::Expressions::ParameterExpression*>*>**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated method: System.Linq.Expressions.Interpreter.QuoteInstruction/System.Linq.Expressions.Interpreter.ExpressionQuoter.GetBox
::System::Runtime::CompilerServices::IStrongBox* System::Linq::Expressions::Interpreter::QuoteInstruction::ExpressionQuoter::GetBox(::System::Linq::Expressions::ParameterExpression* variable) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::QuoteInstruction::ExpressionQuoter::GetBox");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "GetBox", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(variable)})));
return ::il2cpp_utils::RunMethodRethrow<::System::Runtime::CompilerServices::IStrongBox*, false>(this, ___internal__method, variable);
}
// Autogenerated method: System.Linq.Expressions.Interpreter.QuoteInstruction/System.Linq.Expressions.Interpreter.ExpressionQuoter.VisitBlock
::System::Linq::Expressions::Expression* System::Linq::Expressions::Interpreter::QuoteInstruction::ExpressionQuoter::VisitBlock(::System::Linq::Expressions::BlockExpression* node) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::QuoteInstruction::ExpressionQuoter::VisitBlock");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Linq::Expressions::ExpressionVisitor*), 6));
return ::il2cpp_utils::RunMethodRethrow<::System::Linq::Expressions::Expression*, false>(this, ___internal__method, node);
}
// Autogenerated method: System.Linq.Expressions.Interpreter.QuoteInstruction/System.Linq.Expressions.Interpreter.ExpressionQuoter.VisitCatchBlock
::System::Linq::Expressions::CatchBlock* System::Linq::Expressions::Interpreter::QuoteInstruction::ExpressionQuoter::VisitCatchBlock(::System::Linq::Expressions::CatchBlock* node) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::QuoteInstruction::ExpressionQuoter::VisitCatchBlock");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Linq::Expressions::ExpressionVisitor*), 22));
return ::il2cpp_utils::RunMethodRethrow<::System::Linq::Expressions::CatchBlock*, false>(this, ___internal__method, node);
}
// Autogenerated method: System.Linq.Expressions.Interpreter.QuoteInstruction/System.Linq.Expressions.Interpreter.ExpressionQuoter.VisitParameter
::System::Linq::Expressions::Expression* System::Linq::Expressions::Interpreter::QuoteInstruction::ExpressionQuoter::VisitParameter(::System::Linq::Expressions::ParameterExpression* node) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::QuoteInstruction::ExpressionQuoter::VisitParameter");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Linq::Expressions::ExpressionVisitor*), 21));
return ::il2cpp_utils::RunMethodRethrow<::System::Linq::Expressions::Expression*, false>(this, ___internal__method, node);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
// Including type: System.Linq.Expressions.Interpreter.DelegateHelpers
#include "System/Linq/Expressions/Interpreter/DelegateHelpers.hpp"
// Including type: System.Linq.Expressions.Interpreter.DelegateHelpers/System.Linq.Expressions.Interpreter.<>c
#include "System/Linq/Expressions/Interpreter/DelegateHelpers_--c.hpp"
// Including type: System.Type
#include "System/Type.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated method: System.Linq.Expressions.Interpreter.DelegateHelpers.MakeDelegate
::System::Type* System::Linq::Expressions::Interpreter::DelegateHelpers::MakeDelegate(::ArrayW<::System::Type*> types) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::DelegateHelpers::MakeDelegate");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Linq.Expressions.Interpreter", "DelegateHelpers", "MakeDelegate", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(types)})));
return ::il2cpp_utils::RunMethodRethrow<::System::Type*, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, types);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
// Including type: System.Linq.Expressions.Interpreter.DelegateHelpers/System.Linq.Expressions.Interpreter.<>c
#include "System/Linq/Expressions/Interpreter/DelegateHelpers_--c.hpp"
// Including type: System.Func`2
#include "System/Func_2.hpp"
// Including type: System.Type
#include "System/Type.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated static field getter
// Get static field: static public readonly System.Linq.Expressions.Interpreter.DelegateHelpers/System.Linq.Expressions.Interpreter.<>c <>9
::System::Linq::Expressions::Interpreter::DelegateHelpers::$$c* System::Linq::Expressions::Interpreter::DelegateHelpers::$$c::_get_$$9() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::DelegateHelpers::$$c::_get_$$9");
return THROW_UNLESS((il2cpp_utils::GetFieldValue<::System::Linq::Expressions::Interpreter::DelegateHelpers::$$c*>("System.Linq.Expressions.Interpreter", "DelegateHelpers/<>c", "<>9")));
}
// Autogenerated static field setter
// Set static field: static public readonly System.Linq.Expressions.Interpreter.DelegateHelpers/System.Linq.Expressions.Interpreter.<>c <>9
void System::Linq::Expressions::Interpreter::DelegateHelpers::$$c::_set_$$9(::System::Linq::Expressions::Interpreter::DelegateHelpers::$$c* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::DelegateHelpers::$$c::_set_$$9");
THROW_UNLESS((il2cpp_utils::SetFieldValue("System.Linq.Expressions.Interpreter", "DelegateHelpers/<>c", "<>9", value)));
}
// Autogenerated static field getter
// Get static field: static public System.Func`2<System.Type,System.Boolean> <>9__1_0
::System::Func_2<::System::Type*, bool>* System::Linq::Expressions::Interpreter::DelegateHelpers::$$c::_get_$$9__1_0() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::DelegateHelpers::$$c::_get_$$9__1_0");
return THROW_UNLESS((il2cpp_utils::GetFieldValue<::System::Func_2<::System::Type*, bool>*>("System.Linq.Expressions.Interpreter", "DelegateHelpers/<>c", "<>9__1_0")));
}
// Autogenerated static field setter
// Set static field: static public System.Func`2<System.Type,System.Boolean> <>9__1_0
void System::Linq::Expressions::Interpreter::DelegateHelpers::$$c::_set_$$9__1_0(::System::Func_2<::System::Type*, bool>* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::DelegateHelpers::$$c::_set_$$9__1_0");
THROW_UNLESS((il2cpp_utils::SetFieldValue("System.Linq.Expressions.Interpreter", "DelegateHelpers/<>c", "<>9__1_0", value)));
}
// Autogenerated method: System.Linq.Expressions.Interpreter.DelegateHelpers/System.Linq.Expressions.Interpreter.<>c..cctor
void System::Linq::Expressions::Interpreter::DelegateHelpers::$$c::_cctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::DelegateHelpers::$$c::.cctor");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Linq.Expressions.Interpreter", "DelegateHelpers/<>c", ".cctor", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
::il2cpp_utils::RunMethodRethrow<void, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method);
}
// Autogenerated method: System.Linq.Expressions.Interpreter.DelegateHelpers/System.Linq.Expressions.Interpreter.<>c.<MakeDelegate>b__1_0
bool System::Linq::Expressions::Interpreter::DelegateHelpers::$$c::$MakeDelegate$b__1_0(::System::Type* t) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::DelegateHelpers::$$c::<MakeDelegate>b__1_0");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "<MakeDelegate>b__1_0", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(t)})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, t);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
// Including type: System.Linq.Expressions.Interpreter.ScriptingRuntimeHelpers
#include "System/Linq/Expressions/Interpreter/ScriptingRuntimeHelpers.hpp"
// Including type: System.Type
#include "System/Type.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated method: System.Linq.Expressions.Interpreter.ScriptingRuntimeHelpers.Int32ToObject
::Il2CppObject* System::Linq::Expressions::Interpreter::ScriptingRuntimeHelpers::Int32ToObject(int i) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::ScriptingRuntimeHelpers::Int32ToObject");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Linq.Expressions.Interpreter", "ScriptingRuntimeHelpers", "Int32ToObject", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(i)})));
return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, i);
}
// Autogenerated method: System.Linq.Expressions.Interpreter.ScriptingRuntimeHelpers.GetPrimitiveDefaultValue
::Il2CppObject* System::Linq::Expressions::Interpreter::ScriptingRuntimeHelpers::GetPrimitiveDefaultValue(::System::Type* type) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::ScriptingRuntimeHelpers::GetPrimitiveDefaultValue");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Linq.Expressions.Interpreter", "ScriptingRuntimeHelpers", "GetPrimitiveDefaultValue", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(type)})));
return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, type);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
// Including type: System.Linq.Expressions.Interpreter.ExceptionHelpers
#include "System/Linq/Expressions/Interpreter/ExceptionHelpers.hpp"
// Including type: System.Reflection.TargetInvocationException
#include "System/Reflection/TargetInvocationException.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated method: System.Linq.Expressions.Interpreter.ExceptionHelpers.UnwrapAndRethrow
void System::Linq::Expressions::Interpreter::ExceptionHelpers::UnwrapAndRethrow(::System::Reflection::TargetInvocationException* exception) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::ExceptionHelpers::UnwrapAndRethrow");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Linq.Expressions.Interpreter", "ExceptionHelpers", "UnwrapAndRethrow", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(exception)})));
::il2cpp_utils::RunMethodRethrow<void, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, exception);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
// Including type: System.Runtime.CompilerServices.RuntimeOps
#include "System/Runtime/CompilerServices/RuntimeOps.hpp"
// Including type: System.Dynamic.ExpandoObject
#include "System/Dynamic/ExpandoObject.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated method: System.Runtime.CompilerServices.RuntimeOps.ExpandoTryGetValue
bool System::Runtime::CompilerServices::RuntimeOps::ExpandoTryGetValue(::System::Dynamic::ExpandoObject* expando, ::Il2CppObject* indexClass, int index, ::StringW name, bool ignoreCase, ByRef<::Il2CppObject*> value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::CompilerServices::RuntimeOps::ExpandoTryGetValue");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.CompilerServices", "RuntimeOps", "ExpandoTryGetValue", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(expando), ::il2cpp_utils::ExtractType(indexClass), ::il2cpp_utils::ExtractType(index), ::il2cpp_utils::ExtractType(name), ::il2cpp_utils::ExtractType(ignoreCase), ::il2cpp_utils::ExtractIndependentType<::Il2CppObject*&>()})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, expando, indexClass, index, name, ignoreCase, byref(value));
}
// Autogenerated method: System.Runtime.CompilerServices.RuntimeOps.ExpandoTrySetValue
::Il2CppObject* System::Runtime::CompilerServices::RuntimeOps::ExpandoTrySetValue(::System::Dynamic::ExpandoObject* expando, ::Il2CppObject* indexClass, int index, ::Il2CppObject* value, ::StringW name, bool ignoreCase) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::CompilerServices::RuntimeOps::ExpandoTrySetValue");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.CompilerServices", "RuntimeOps", "ExpandoTrySetValue", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(expando), ::il2cpp_utils::ExtractType(indexClass), ::il2cpp_utils::ExtractType(index), ::il2cpp_utils::ExtractType(value), ::il2cpp_utils::ExtractType(name), ::il2cpp_utils::ExtractType(ignoreCase)})));
return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, expando, indexClass, index, value, name, ignoreCase);
}
// Autogenerated method: System.Runtime.CompilerServices.RuntimeOps.ExpandoTryDeleteValue
bool System::Runtime::CompilerServices::RuntimeOps::ExpandoTryDeleteValue(::System::Dynamic::ExpandoObject* expando, ::Il2CppObject* indexClass, int index, ::StringW name, bool ignoreCase) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::CompilerServices::RuntimeOps::ExpandoTryDeleteValue");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.CompilerServices", "RuntimeOps", "ExpandoTryDeleteValue", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(expando), ::il2cpp_utils::ExtractType(indexClass), ::il2cpp_utils::ExtractType(index), ::il2cpp_utils::ExtractType(name), ::il2cpp_utils::ExtractType(ignoreCase)})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, expando, indexClass, index, name, ignoreCase);
}
// Autogenerated method: System.Runtime.CompilerServices.RuntimeOps.ExpandoCheckVersion
bool System::Runtime::CompilerServices::RuntimeOps::ExpandoCheckVersion(::System::Dynamic::ExpandoObject* expando, ::Il2CppObject* version) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::CompilerServices::RuntimeOps::ExpandoCheckVersion");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.CompilerServices", "RuntimeOps", "ExpandoCheckVersion", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(expando), ::il2cpp_utils::ExtractType(version)})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, expando, version);
}
// Autogenerated method: System.Runtime.CompilerServices.RuntimeOps.ExpandoPromoteClass
void System::Runtime::CompilerServices::RuntimeOps::ExpandoPromoteClass(::System::Dynamic::ExpandoObject* expando, ::Il2CppObject* oldClass, ::Il2CppObject* newClass) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::CompilerServices::RuntimeOps::ExpandoPromoteClass");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.CompilerServices", "RuntimeOps", "ExpandoPromoteClass", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(expando), ::il2cpp_utils::ExtractType(oldClass), ::il2cpp_utils::ExtractType(newClass)})));
::il2cpp_utils::RunMethodRethrow<void, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, expando, oldClass, newClass);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
// Including type: System.Runtime.CompilerServices.CallSite
#include "System/Runtime/CompilerServices/CallSite.hpp"
// Including type: System.Runtime.CompilerServices.CallSiteBinder
#include "System/Runtime/CompilerServices/CallSiteBinder.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated instance field getter
// Get instance field: readonly System.Runtime.CompilerServices.CallSiteBinder _binder
[[deprecated("Use field access instead!")]] ::System::Runtime::CompilerServices::CallSiteBinder*& System::Runtime::CompilerServices::CallSite::dyn__binder() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::CompilerServices::CallSite::dyn__binder");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_binder"))->offset;
return *reinterpret_cast<::System::Runtime::CompilerServices::CallSiteBinder**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: System.Boolean _match
[[deprecated("Use field access instead!")]] bool& System::Runtime::CompilerServices::CallSite::dyn__match() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::CompilerServices::CallSite::dyn__match");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_match"))->offset;
return *reinterpret_cast<bool*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated method: System.Runtime.CompilerServices.CallSite.get_Binder
::System::Runtime::CompilerServices::CallSiteBinder* System::Runtime::CompilerServices::CallSite::get_Binder() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::CompilerServices::CallSite::get_Binder");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_Binder", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<::System::Runtime::CompilerServices::CallSiteBinder*, false>(this, ___internal__method);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
// Including type: System.Runtime.CompilerServices.CallSiteBinder
#include "System/Runtime/CompilerServices/CallSiteBinder.hpp"
// Including type: System.Runtime.CompilerServices.CallSiteBinder/System.Runtime.CompilerServices.LambdaSignature`1
#include "System/Runtime/CompilerServices/CallSiteBinder_LambdaSignature_1.hpp"
// Including type: System.Collections.Generic.Dictionary`2
#include "System/Collections/Generic/Dictionary_2.hpp"
// Including type: System.Type
#include "System/Type.hpp"
// Including type: System.Linq.Expressions.LabelTarget
#include "System/Linq/Expressions/LabelTarget.hpp"
// Including type: System.Linq.Expressions.Expression
#include "System/Linq/Expressions/Expression.hpp"
// Including type: System.Collections.ObjectModel.ReadOnlyCollection`1
#include "System/Collections/ObjectModel/ReadOnlyCollection_1.hpp"
// Including type: System.Linq.Expressions.ParameterExpression
#include "System/Linq/Expressions/ParameterExpression.hpp"
// Including type: System.Runtime.CompilerServices.CallSite`1
#include "System/Runtime/CompilerServices/CallSite_1.hpp"
// Including type: System.Linq.Expressions.Expression`1
#include "System/Linq/Expressions/Expression_1.hpp"
// Including type: System.Runtime.CompilerServices.RuleCache`1
#include "System/Runtime/CompilerServices/RuleCache_1.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated static field getter
// Get static field: static private readonly System.Linq.Expressions.LabelTarget <UpdateLabel>k__BackingField
::System::Linq::Expressions::LabelTarget* System::Runtime::CompilerServices::CallSiteBinder::_get_$UpdateLabel$k__BackingField() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::CompilerServices::CallSiteBinder::_get_$UpdateLabel$k__BackingField");
return THROW_UNLESS((il2cpp_utils::GetFieldValue<::System::Linq::Expressions::LabelTarget*>("System.Runtime.CompilerServices", "CallSiteBinder", "<UpdateLabel>k__BackingField")));
}
// Autogenerated static field setter
// Set static field: static private readonly System.Linq.Expressions.LabelTarget <UpdateLabel>k__BackingField
void System::Runtime::CompilerServices::CallSiteBinder::_set_$UpdateLabel$k__BackingField(::System::Linq::Expressions::LabelTarget* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::CompilerServices::CallSiteBinder::_set_$UpdateLabel$k__BackingField");
THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.CompilerServices", "CallSiteBinder", "<UpdateLabel>k__BackingField", value));
}
// Autogenerated instance field getter
// Get instance field: System.Collections.Generic.Dictionary`2<System.Type,System.Object> Cache
[[deprecated("Use field access instead!")]] ::System::Collections::Generic::Dictionary_2<::System::Type*, ::Il2CppObject*>*& System::Runtime::CompilerServices::CallSiteBinder::dyn_Cache() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::CompilerServices::CallSiteBinder::dyn_Cache");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "Cache"))->offset;
return *reinterpret_cast<::System::Collections::Generic::Dictionary_2<::System::Type*, ::Il2CppObject*>**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated method: System.Runtime.CompilerServices.CallSiteBinder.get_UpdateLabel
::System::Linq::Expressions::LabelTarget* System::Runtime::CompilerServices::CallSiteBinder::get_UpdateLabel() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::CompilerServices::CallSiteBinder::get_UpdateLabel");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.CompilerServices", "CallSiteBinder", "get_UpdateLabel", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<::System::Linq::Expressions::LabelTarget*, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method);
}
// Autogenerated method: System.Runtime.CompilerServices.CallSiteBinder..cctor
void System::Runtime::CompilerServices::CallSiteBinder::_cctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::CompilerServices::CallSiteBinder::.cctor");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.CompilerServices", "CallSiteBinder", ".cctor", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
::il2cpp_utils::RunMethodRethrow<void, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method);
}
// Autogenerated method: System.Runtime.CompilerServices.CallSiteBinder.Bind
::System::Linq::Expressions::Expression* System::Runtime::CompilerServices::CallSiteBinder::Bind(::ArrayW<::Il2CppObject*> args, ::System::Collections::ObjectModel::ReadOnlyCollection_1<::System::Linq::Expressions::ParameterExpression*>* parameters, ::System::Linq::Expressions::LabelTarget* returnLabel) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::CompilerServices::CallSiteBinder::Bind");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Runtime::CompilerServices::CallSiteBinder*), -1));
return ::il2cpp_utils::RunMethodRethrow<::System::Linq::Expressions::Expression*, false>(this, ___internal__method, args, parameters, returnLabel);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
// Including type: System.Runtime.CompilerServices.CallSiteOps
#include "System/Runtime/CompilerServices/CallSiteOps.hpp"
// Including type: System.Runtime.CompilerServices.CallSite`1
#include "System/Runtime/CompilerServices/CallSite_1.hpp"
// Including type: System.Runtime.CompilerServices.CallSite
#include "System/Runtime/CompilerServices/CallSite.hpp"
// Including type: System.Runtime.CompilerServices.RuleCache`1
#include "System/Runtime/CompilerServices/RuleCache_1.hpp"
// Including type: System.Runtime.CompilerServices.CallSiteBinder
#include "System/Runtime/CompilerServices/CallSiteBinder.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated method: System.Runtime.CompilerServices.CallSiteOps.SetNotMatched
bool System::Runtime::CompilerServices::CallSiteOps::SetNotMatched(::System::Runtime::CompilerServices::CallSite* site) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::CompilerServices::CallSiteOps::SetNotMatched");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.CompilerServices", "CallSiteOps", "SetNotMatched", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(site)})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, site);
}
// Autogenerated method: System.Runtime.CompilerServices.CallSiteOps.GetMatch
bool System::Runtime::CompilerServices::CallSiteOps::GetMatch(::System::Runtime::CompilerServices::CallSite* site) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::CompilerServices::CallSiteOps::GetMatch");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.CompilerServices", "CallSiteOps", "GetMatch", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(site)})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, site);
}
// Autogenerated method: System.Runtime.CompilerServices.CallSiteOps.ClearMatch
void System::Runtime::CompilerServices::CallSiteOps::ClearMatch(::System::Runtime::CompilerServices::CallSite* site) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::CompilerServices::CallSiteOps::ClearMatch");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.CompilerServices", "CallSiteOps", "ClearMatch", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(site)})));
::il2cpp_utils::RunMethodRethrow<void, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, site);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
// Including type: System.Runtime.CompilerServices.IStrongBox
#include "System/Runtime/CompilerServices/IStrongBox.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated method: System.Runtime.CompilerServices.IStrongBox.get_Value
::Il2CppObject* System::Runtime::CompilerServices::IStrongBox::get_Value() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::CompilerServices::IStrongBox::get_Value");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Runtime::CompilerServices::IStrongBox*), -1));
return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method);
}
// Autogenerated method: System.Runtime.CompilerServices.IStrongBox.set_Value
void System::Runtime::CompilerServices::IStrongBox::set_Value(::Il2CppObject* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::CompilerServices::IStrongBox::set_Value");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Runtime::CompilerServices::IStrongBox*), -1));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
// Including type: System.Dynamic.BindingRestrictions
#include "System/Dynamic/BindingRestrictions.hpp"
// Including type: System.Dynamic.BindingRestrictions/System.Dynamic.TestBuilder
#include "System/Dynamic/BindingRestrictions_TestBuilder.hpp"
// Including type: System.Dynamic.BindingRestrictions/System.Dynamic.MergedRestriction
#include "System/Dynamic/BindingRestrictions_MergedRestriction.hpp"
// Including type: System.Dynamic.BindingRestrictions/System.Dynamic.CustomRestriction
#include "System/Dynamic/BindingRestrictions_CustomRestriction.hpp"
// Including type: System.Dynamic.BindingRestrictions/System.Dynamic.TypeRestriction
#include "System/Dynamic/BindingRestrictions_TypeRestriction.hpp"
// Including type: System.Dynamic.BindingRestrictions/System.Dynamic.InstanceRestriction
#include "System/Dynamic/BindingRestrictions_InstanceRestriction.hpp"
// Including type: System.Dynamic.BindingRestrictions/System.Dynamic.BindingRestrictionsProxy
#include "System/Dynamic/BindingRestrictions_BindingRestrictionsProxy.hpp"
// Including type: System.Linq.Expressions.Expression
#include "System/Linq/Expressions/Expression.hpp"
// Including type: System.Type
#include "System/Type.hpp"
// Including type: System.Dynamic.DynamicMetaObject
#include "System/Dynamic/DynamicMetaObject.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated static field getter
// Get static field: static public readonly System.Dynamic.BindingRestrictions Empty
::System::Dynamic::BindingRestrictions* System::Dynamic::BindingRestrictions::_get_Empty() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::BindingRestrictions::_get_Empty");
return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Dynamic::BindingRestrictions*>("System.Dynamic", "BindingRestrictions", "Empty"));
}
// Autogenerated static field setter
// Set static field: static public readonly System.Dynamic.BindingRestrictions Empty
void System::Dynamic::BindingRestrictions::_set_Empty(::System::Dynamic::BindingRestrictions* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::BindingRestrictions::_set_Empty");
THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Dynamic", "BindingRestrictions", "Empty", value));
}
// Autogenerated method: System.Dynamic.BindingRestrictions..cctor
void System::Dynamic::BindingRestrictions::_cctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::BindingRestrictions::.cctor");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic", "BindingRestrictions", ".cctor", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
::il2cpp_utils::RunMethodRethrow<void, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method);
}
// Autogenerated method: System.Dynamic.BindingRestrictions.GetExpression
::System::Linq::Expressions::Expression* System::Dynamic::BindingRestrictions::GetExpression() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::BindingRestrictions::GetExpression");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::BindingRestrictions*), -1));
return ::il2cpp_utils::RunMethodRethrow<::System::Linq::Expressions::Expression*, false>(this, ___internal__method);
}
// Autogenerated method: System.Dynamic.BindingRestrictions.Merge
::System::Dynamic::BindingRestrictions* System::Dynamic::BindingRestrictions::Merge(::System::Dynamic::BindingRestrictions* restrictions) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::BindingRestrictions::Merge");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Merge", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(restrictions)})));
return ::il2cpp_utils::RunMethodRethrow<::System::Dynamic::BindingRestrictions*, false>(this, ___internal__method, restrictions);
}
// Autogenerated method: System.Dynamic.BindingRestrictions.GetTypeRestriction
::System::Dynamic::BindingRestrictions* System::Dynamic::BindingRestrictions::GetTypeRestriction(::System::Linq::Expressions::Expression* expression, ::System::Type* type) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::BindingRestrictions::GetTypeRestriction");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic", "BindingRestrictions", "GetTypeRestriction", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(expression), ::il2cpp_utils::ExtractType(type)})));
return ::il2cpp_utils::RunMethodRethrow<::System::Dynamic::BindingRestrictions*, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, expression, type);
}
// Autogenerated method: System.Dynamic.BindingRestrictions.GetTypeRestriction
::System::Dynamic::BindingRestrictions* System::Dynamic::BindingRestrictions::GetTypeRestriction(::System::Dynamic::DynamicMetaObject* obj) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::BindingRestrictions::GetTypeRestriction");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic", "BindingRestrictions", "GetTypeRestriction", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(obj)})));
return ::il2cpp_utils::RunMethodRethrow<::System::Dynamic::BindingRestrictions*, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, obj);
}
// Autogenerated method: System.Dynamic.BindingRestrictions.GetInstanceRestriction
::System::Dynamic::BindingRestrictions* System::Dynamic::BindingRestrictions::GetInstanceRestriction(::System::Linq::Expressions::Expression* expression, ::Il2CppObject* instance) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::BindingRestrictions::GetInstanceRestriction");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic", "BindingRestrictions", "GetInstanceRestriction", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(expression), ::il2cpp_utils::ExtractType(instance)})));
return ::il2cpp_utils::RunMethodRethrow<::System::Dynamic::BindingRestrictions*, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, expression, instance);
}
// Autogenerated method: System.Dynamic.BindingRestrictions.ToExpression
::System::Linq::Expressions::Expression* System::Dynamic::BindingRestrictions::ToExpression() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::BindingRestrictions::ToExpression");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "ToExpression", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<::System::Linq::Expressions::Expression*, false>(this, ___internal__method);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
// Including type: System.Dynamic.BindingRestrictions/System.Dynamic.TestBuilder
#include "System/Dynamic/BindingRestrictions_TestBuilder.hpp"
// Including type: System.Linq.Expressions.Expression
#include "System/Linq/Expressions/Expression.hpp"
// Including type: System.Collections.Generic.HashSet`1
#include "System/Collections/Generic/HashSet_1.hpp"
// Including type: System.Collections.Generic.Stack`1
#include "System/Collections/Generic/Stack_1.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated instance field getter
// Get instance field: private readonly System.Collections.Generic.HashSet`1<System.Dynamic.BindingRestrictions> _unique
[[deprecated("Use field access instead!")]] ::System::Collections::Generic::HashSet_1<::System::Dynamic::BindingRestrictions*>*& System::Dynamic::BindingRestrictions::TestBuilder::dyn__unique() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::BindingRestrictions::TestBuilder::dyn__unique");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_unique"))->offset;
return *reinterpret_cast<::System::Collections::Generic::HashSet_1<::System::Dynamic::BindingRestrictions*>**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private readonly System.Collections.Generic.Stack`1<System.Dynamic.BindingRestrictions/System.Dynamic.TestBuilder/System.Dynamic.AndNode> _tests
[[deprecated("Use field access instead!")]] ::System::Collections::Generic::Stack_1<::System::Dynamic::BindingRestrictions::TestBuilder::AndNode>*& System::Dynamic::BindingRestrictions::TestBuilder::dyn__tests() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::BindingRestrictions::TestBuilder::dyn__tests");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_tests"))->offset;
return *reinterpret_cast<::System::Collections::Generic::Stack_1<::System::Dynamic::BindingRestrictions::TestBuilder::AndNode>**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated method: System.Dynamic.BindingRestrictions/System.Dynamic.TestBuilder.Append
void System::Dynamic::BindingRestrictions::TestBuilder::Append(::System::Dynamic::BindingRestrictions* restrictions) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::BindingRestrictions::TestBuilder::Append");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Append", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(restrictions)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, restrictions);
}
// Autogenerated method: System.Dynamic.BindingRestrictions/System.Dynamic.TestBuilder.ToExpression
::System::Linq::Expressions::Expression* System::Dynamic::BindingRestrictions::TestBuilder::ToExpression() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::BindingRestrictions::TestBuilder::ToExpression");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "ToExpression", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<::System::Linq::Expressions::Expression*, false>(this, ___internal__method);
}
// Autogenerated method: System.Dynamic.BindingRestrictions/System.Dynamic.TestBuilder.Push
void System::Dynamic::BindingRestrictions::TestBuilder::Push(::System::Linq::Expressions::Expression* node, int depth) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::BindingRestrictions::TestBuilder::Push");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Push", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(node), ::il2cpp_utils::ExtractType(depth)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, node, depth);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
// Including type: System.Dynamic.BindingRestrictions/System.Dynamic.MergedRestriction
#include "System/Dynamic/BindingRestrictions_MergedRestriction.hpp"
// Including type: System.Linq.Expressions.Expression
#include "System/Linq/Expressions/Expression.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated instance field getter
// Get instance field: readonly System.Dynamic.BindingRestrictions Left
[[deprecated("Use field access instead!")]] ::System::Dynamic::BindingRestrictions*& System::Dynamic::BindingRestrictions::MergedRestriction::dyn_Left() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::BindingRestrictions::MergedRestriction::dyn_Left");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "Left"))->offset;
return *reinterpret_cast<::System::Dynamic::BindingRestrictions**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: readonly System.Dynamic.BindingRestrictions Right
[[deprecated("Use field access instead!")]] ::System::Dynamic::BindingRestrictions*& System::Dynamic::BindingRestrictions::MergedRestriction::dyn_Right() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::BindingRestrictions::MergedRestriction::dyn_Right");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "Right"))->offset;
return *reinterpret_cast<::System::Dynamic::BindingRestrictions**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated method: System.Dynamic.BindingRestrictions/System.Dynamic.MergedRestriction.GetExpression
::System::Linq::Expressions::Expression* System::Dynamic::BindingRestrictions::MergedRestriction::GetExpression() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::BindingRestrictions::MergedRestriction::GetExpression");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::BindingRestrictions*), 4));
return ::il2cpp_utils::RunMethodRethrow<::System::Linq::Expressions::Expression*, false>(this, ___internal__method);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
// Including type: System.Dynamic.BindingRestrictions/System.Dynamic.CustomRestriction
#include "System/Dynamic/BindingRestrictions_CustomRestriction.hpp"
// Including type: System.Linq.Expressions.Expression
#include "System/Linq/Expressions/Expression.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated instance field getter
// Get instance field: private readonly System.Linq.Expressions.Expression _expression
[[deprecated("Use field access instead!")]] ::System::Linq::Expressions::Expression*& System::Dynamic::BindingRestrictions::CustomRestriction::dyn__expression() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::BindingRestrictions::CustomRestriction::dyn__expression");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_expression"))->offset;
return *reinterpret_cast<::System::Linq::Expressions::Expression**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated method: System.Dynamic.BindingRestrictions/System.Dynamic.CustomRestriction.Equals
bool System::Dynamic::BindingRestrictions::CustomRestriction::Equals(::Il2CppObject* obj) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::BindingRestrictions::CustomRestriction::Equals");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::Il2CppObject*), 0));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, obj);
}
// Autogenerated method: System.Dynamic.BindingRestrictions/System.Dynamic.CustomRestriction.GetHashCode
int System::Dynamic::BindingRestrictions::CustomRestriction::GetHashCode() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::BindingRestrictions::CustomRestriction::GetHashCode");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::Il2CppObject*), 2));
return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method);
}
// Autogenerated method: System.Dynamic.BindingRestrictions/System.Dynamic.CustomRestriction.GetExpression
::System::Linq::Expressions::Expression* System::Dynamic::BindingRestrictions::CustomRestriction::GetExpression() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::BindingRestrictions::CustomRestriction::GetExpression");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::BindingRestrictions*), 4));
return ::il2cpp_utils::RunMethodRethrow<::System::Linq::Expressions::Expression*, false>(this, ___internal__method);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
// Including type: System.Dynamic.BindingRestrictions/System.Dynamic.TypeRestriction
#include "System/Dynamic/BindingRestrictions_TypeRestriction.hpp"
// Including type: System.Linq.Expressions.Expression
#include "System/Linq/Expressions/Expression.hpp"
// Including type: System.Type
#include "System/Type.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated instance field getter
// Get instance field: private readonly System.Linq.Expressions.Expression _expression
[[deprecated("Use field access instead!")]] ::System::Linq::Expressions::Expression*& System::Dynamic::BindingRestrictions::TypeRestriction::dyn__expression() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::BindingRestrictions::TypeRestriction::dyn__expression");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_expression"))->offset;
return *reinterpret_cast<::System::Linq::Expressions::Expression**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private readonly System.Type _type
[[deprecated("Use field access instead!")]] ::System::Type*& System::Dynamic::BindingRestrictions::TypeRestriction::dyn__type() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::BindingRestrictions::TypeRestriction::dyn__type");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_type"))->offset;
return *reinterpret_cast<::System::Type**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated method: System.Dynamic.BindingRestrictions/System.Dynamic.TypeRestriction.Equals
bool System::Dynamic::BindingRestrictions::TypeRestriction::Equals(::Il2CppObject* obj) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::BindingRestrictions::TypeRestriction::Equals");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::Il2CppObject*), 0));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, obj);
}
// Autogenerated method: System.Dynamic.BindingRestrictions/System.Dynamic.TypeRestriction.GetHashCode
int System::Dynamic::BindingRestrictions::TypeRestriction::GetHashCode() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::BindingRestrictions::TypeRestriction::GetHashCode");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::Il2CppObject*), 2));
return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method);
}
// Autogenerated method: System.Dynamic.BindingRestrictions/System.Dynamic.TypeRestriction.GetExpression
::System::Linq::Expressions::Expression* System::Dynamic::BindingRestrictions::TypeRestriction::GetExpression() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::BindingRestrictions::TypeRestriction::GetExpression");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::BindingRestrictions*), 4));
return ::il2cpp_utils::RunMethodRethrow<::System::Linq::Expressions::Expression*, false>(this, ___internal__method);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
// Including type: System.Dynamic.BindingRestrictions/System.Dynamic.InstanceRestriction
#include "System/Dynamic/BindingRestrictions_InstanceRestriction.hpp"
// Including type: System.Linq.Expressions.Expression
#include "System/Linq/Expressions/Expression.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated instance field getter
// Get instance field: private readonly System.Linq.Expressions.Expression _expression
[[deprecated("Use field access instead!")]] ::System::Linq::Expressions::Expression*& System::Dynamic::BindingRestrictions::InstanceRestriction::dyn__expression() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::BindingRestrictions::InstanceRestriction::dyn__expression");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_expression"))->offset;
return *reinterpret_cast<::System::Linq::Expressions::Expression**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private readonly System.Object _instance
[[deprecated("Use field access instead!")]] ::Il2CppObject*& System::Dynamic::BindingRestrictions::InstanceRestriction::dyn__instance() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::BindingRestrictions::InstanceRestriction::dyn__instance");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_instance"))->offset;
return *reinterpret_cast<::Il2CppObject**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated method: System.Dynamic.BindingRestrictions/System.Dynamic.InstanceRestriction.Equals
bool System::Dynamic::BindingRestrictions::InstanceRestriction::Equals(::Il2CppObject* obj) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::BindingRestrictions::InstanceRestriction::Equals");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::Il2CppObject*), 0));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, obj);
}
// Autogenerated method: System.Dynamic.BindingRestrictions/System.Dynamic.InstanceRestriction.GetHashCode
int System::Dynamic::BindingRestrictions::InstanceRestriction::GetHashCode() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::BindingRestrictions::InstanceRestriction::GetHashCode");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::Il2CppObject*), 2));
return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method);
}
// Autogenerated method: System.Dynamic.BindingRestrictions/System.Dynamic.InstanceRestriction.GetExpression
::System::Linq::Expressions::Expression* System::Dynamic::BindingRestrictions::InstanceRestriction::GetExpression() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::BindingRestrictions::InstanceRestriction::GetExpression");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::BindingRestrictions*), 4));
return ::il2cpp_utils::RunMethodRethrow<::System::Linq::Expressions::Expression*, false>(this, ___internal__method);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
// Including type: System.Dynamic.DynamicMetaObject
#include "System/Dynamic/DynamicMetaObject.hpp"
// Including type: System.Linq.Expressions.Expression
#include "System/Linq/Expressions/Expression.hpp"
// Including type: System.Dynamic.BindingRestrictions
#include "System/Dynamic/BindingRestrictions.hpp"
// Including type: System.Type
#include "System/Type.hpp"
// Including type: System.Dynamic.GetMemberBinder
#include "System/Dynamic/GetMemberBinder.hpp"
// Including type: System.Dynamic.SetMemberBinder
#include "System/Dynamic/SetMemberBinder.hpp"
// Including type: System.Collections.Generic.IEnumerable`1
#include "System/Collections/Generic/IEnumerable_1.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated static field getter
// Get static field: static public readonly System.Dynamic.DynamicMetaObject[] EmptyMetaObjects
::ArrayW<::System::Dynamic::DynamicMetaObject*> System::Dynamic::DynamicMetaObject::_get_EmptyMetaObjects() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::DynamicMetaObject::_get_EmptyMetaObjects");
return THROW_UNLESS(il2cpp_utils::GetFieldValue<::ArrayW<::System::Dynamic::DynamicMetaObject*>>("System.Dynamic", "DynamicMetaObject", "EmptyMetaObjects"));
}
// Autogenerated static field setter
// Set static field: static public readonly System.Dynamic.DynamicMetaObject[] EmptyMetaObjects
void System::Dynamic::DynamicMetaObject::_set_EmptyMetaObjects(::ArrayW<::System::Dynamic::DynamicMetaObject*> value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::DynamicMetaObject::_set_EmptyMetaObjects");
THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Dynamic", "DynamicMetaObject", "EmptyMetaObjects", value));
}
// Autogenerated instance field getter
// Get instance field: private readonly System.Linq.Expressions.Expression <Expression>k__BackingField
[[deprecated("Use field access instead!")]] ::System::Linq::Expressions::Expression*& System::Dynamic::DynamicMetaObject::dyn_$Expression$k__BackingField() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::DynamicMetaObject::dyn_$Expression$k__BackingField");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "<Expression>k__BackingField"))->offset;
return *reinterpret_cast<::System::Linq::Expressions::Expression**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private readonly System.Dynamic.BindingRestrictions <Restrictions>k__BackingField
[[deprecated("Use field access instead!")]] ::System::Dynamic::BindingRestrictions*& System::Dynamic::DynamicMetaObject::dyn_$Restrictions$k__BackingField() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::DynamicMetaObject::dyn_$Restrictions$k__BackingField");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "<Restrictions>k__BackingField"))->offset;
return *reinterpret_cast<::System::Dynamic::BindingRestrictions**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private readonly System.Object <Value>k__BackingField
[[deprecated("Use field access instead!")]] ::Il2CppObject*& System::Dynamic::DynamicMetaObject::dyn_$Value$k__BackingField() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::DynamicMetaObject::dyn_$Value$k__BackingField");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "<Value>k__BackingField"))->offset;
return *reinterpret_cast<::Il2CppObject**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private readonly System.Boolean <HasValue>k__BackingField
[[deprecated("Use field access instead!")]] bool& System::Dynamic::DynamicMetaObject::dyn_$HasValue$k__BackingField() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::DynamicMetaObject::dyn_$HasValue$k__BackingField");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "<HasValue>k__BackingField"))->offset;
return *reinterpret_cast<bool*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated method: System.Dynamic.DynamicMetaObject.get_Expression
::System::Linq::Expressions::Expression* System::Dynamic::DynamicMetaObject::get_Expression() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::DynamicMetaObject::get_Expression");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_Expression", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<::System::Linq::Expressions::Expression*, false>(this, ___internal__method);
}
// Autogenerated method: System.Dynamic.DynamicMetaObject.get_Restrictions
::System::Dynamic::BindingRestrictions* System::Dynamic::DynamicMetaObject::get_Restrictions() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::DynamicMetaObject::get_Restrictions");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_Restrictions", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<::System::Dynamic::BindingRestrictions*, false>(this, ___internal__method);
}
// Autogenerated method: System.Dynamic.DynamicMetaObject.get_Value
::Il2CppObject* System::Dynamic::DynamicMetaObject::get_Value() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::DynamicMetaObject::get_Value");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_Value", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method);
}
// Autogenerated method: System.Dynamic.DynamicMetaObject.get_HasValue
bool System::Dynamic::DynamicMetaObject::get_HasValue() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::DynamicMetaObject::get_HasValue");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_HasValue", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method);
}
// Autogenerated method: System.Dynamic.DynamicMetaObject.get_RuntimeType
::System::Type* System::Dynamic::DynamicMetaObject::get_RuntimeType() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::DynamicMetaObject::get_RuntimeType");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_RuntimeType", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<::System::Type*, false>(this, ___internal__method);
}
// Autogenerated method: System.Dynamic.DynamicMetaObject.get_LimitType
::System::Type* System::Dynamic::DynamicMetaObject::get_LimitType() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::DynamicMetaObject::get_LimitType");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_LimitType", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<::System::Type*, false>(this, ___internal__method);
}
// Autogenerated method: System.Dynamic.DynamicMetaObject..cctor
void System::Dynamic::DynamicMetaObject::_cctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::DynamicMetaObject::.cctor");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic", "DynamicMetaObject", ".cctor", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
::il2cpp_utils::RunMethodRethrow<void, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method);
}
// Autogenerated method: System.Dynamic.DynamicMetaObject.BindGetMember
::System::Dynamic::DynamicMetaObject* System::Dynamic::DynamicMetaObject::BindGetMember(::System::Dynamic::GetMemberBinder* binder) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::DynamicMetaObject::BindGetMember");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::DynamicMetaObject*), 4));
return ::il2cpp_utils::RunMethodRethrow<::System::Dynamic::DynamicMetaObject*, false>(this, ___internal__method, binder);
}
// Autogenerated method: System.Dynamic.DynamicMetaObject.BindSetMember
::System::Dynamic::DynamicMetaObject* System::Dynamic::DynamicMetaObject::BindSetMember(::System::Dynamic::SetMemberBinder* binder, ::System::Dynamic::DynamicMetaObject* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::DynamicMetaObject::BindSetMember");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::DynamicMetaObject*), 5));
return ::il2cpp_utils::RunMethodRethrow<::System::Dynamic::DynamicMetaObject*, false>(this, ___internal__method, binder, value);
}
// Autogenerated method: System.Dynamic.DynamicMetaObject.GetDynamicMemberNames
::System::Collections::Generic::IEnumerable_1<::StringW>* System::Dynamic::DynamicMetaObject::GetDynamicMemberNames() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::DynamicMetaObject::GetDynamicMemberNames");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::DynamicMetaObject*), 6));
return ::il2cpp_utils::RunMethodRethrow<::System::Collections::Generic::IEnumerable_1<::StringW>*, false>(this, ___internal__method);
}
// Autogenerated method: System.Dynamic.DynamicMetaObject.Create
::System::Dynamic::DynamicMetaObject* System::Dynamic::DynamicMetaObject::Create(::Il2CppObject* value, ::System::Linq::Expressions::Expression* expression) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::DynamicMetaObject::Create");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic", "DynamicMetaObject", "Create", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value), ::il2cpp_utils::ExtractType(expression)})));
return ::il2cpp_utils::RunMethodRethrow<::System::Dynamic::DynamicMetaObject*, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, value, expression);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
// Including type: System.Dynamic.DynamicMetaObjectBinder
#include "System/Dynamic/DynamicMetaObjectBinder.hpp"
// Including type: System.Type
#include "System/Type.hpp"
// Including type: System.Dynamic.DynamicMetaObject
#include "System/Dynamic/DynamicMetaObject.hpp"
// Including type: System.Collections.ObjectModel.ReadOnlyCollection`1
#include "System/Collections/ObjectModel/ReadOnlyCollection_1.hpp"
// Including type: System.Linq.Expressions.ParameterExpression
#include "System/Linq/Expressions/ParameterExpression.hpp"
// Including type: System.Linq.Expressions.Expression
#include "System/Linq/Expressions/Expression.hpp"
// Including type: System.Linq.Expressions.LabelTarget
#include "System/Linq/Expressions/LabelTarget.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated method: System.Dynamic.DynamicMetaObjectBinder.get_ReturnType
::System::Type* System::Dynamic::DynamicMetaObjectBinder::get_ReturnType() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::DynamicMetaObjectBinder::get_ReturnType");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::DynamicMetaObjectBinder*), 6));
return ::il2cpp_utils::RunMethodRethrow<::System::Type*, false>(this, ___internal__method);
}
// Autogenerated method: System.Dynamic.DynamicMetaObjectBinder.get_IsStandardBinder
bool System::Dynamic::DynamicMetaObjectBinder::get_IsStandardBinder() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::DynamicMetaObjectBinder::get_IsStandardBinder");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::DynamicMetaObjectBinder*), 8));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method);
}
// Autogenerated method: System.Dynamic.DynamicMetaObjectBinder.CreateArgumentMetaObjects
::ArrayW<::System::Dynamic::DynamicMetaObject*> System::Dynamic::DynamicMetaObjectBinder::CreateArgumentMetaObjects(::ArrayW<::Il2CppObject*> args, ::System::Collections::ObjectModel::ReadOnlyCollection_1<::System::Linq::Expressions::ParameterExpression*>* parameters) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::DynamicMetaObjectBinder::CreateArgumentMetaObjects");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic", "DynamicMetaObjectBinder", "CreateArgumentMetaObjects", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(args), ::il2cpp_utils::ExtractType(parameters)})));
return ::il2cpp_utils::RunMethodRethrow<::ArrayW<::System::Dynamic::DynamicMetaObject*>, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, args, parameters);
}
// Autogenerated method: System.Dynamic.DynamicMetaObjectBinder.Bind
::System::Dynamic::DynamicMetaObject* System::Dynamic::DynamicMetaObjectBinder::Bind(::System::Dynamic::DynamicMetaObject* target, ::ArrayW<::System::Dynamic::DynamicMetaObject*> args) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::DynamicMetaObjectBinder::Bind");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::DynamicMetaObjectBinder*), -1));
return ::il2cpp_utils::RunMethodRethrow<::System::Dynamic::DynamicMetaObject*, false>(this, ___internal__method, target, args);
}
// Autogenerated method: System.Dynamic.DynamicMetaObjectBinder.GetUpdateExpression
::System::Linq::Expressions::Expression* System::Dynamic::DynamicMetaObjectBinder::GetUpdateExpression(::System::Type* type) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::DynamicMetaObjectBinder::GetUpdateExpression");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "GetUpdateExpression", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(type)})));
return ::il2cpp_utils::RunMethodRethrow<::System::Linq::Expressions::Expression*, false>(this, ___internal__method, type);
}
// Autogenerated method: System.Dynamic.DynamicMetaObjectBinder.Bind
::System::Linq::Expressions::Expression* System::Dynamic::DynamicMetaObjectBinder::Bind(::ArrayW<::Il2CppObject*> args, ::System::Collections::ObjectModel::ReadOnlyCollection_1<::System::Linq::Expressions::ParameterExpression*>* parameters, ::System::Linq::Expressions::LabelTarget* returnLabel) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::DynamicMetaObjectBinder::Bind");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Runtime::CompilerServices::CallSiteBinder*), 4));
return ::il2cpp_utils::RunMethodRethrow<::System::Linq::Expressions::Expression*, false>(this, ___internal__method, args, parameters, returnLabel);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
// Including type: System.Dynamic.ExpandoClass
#include "System/Dynamic/ExpandoClass.hpp"
// Including type: System.Collections.Generic.Dictionary`2
#include "System/Collections/Generic/Dictionary_2.hpp"
// Including type: System.Collections.Generic.List`1
#include "System/Collections/Generic/List_1.hpp"
// Including type: System.WeakReference
#include "System/WeakReference.hpp"
// Including type: System.Dynamic.ExpandoObject
#include "System/Dynamic/ExpandoObject.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated static field getter
// Get static field: static readonly System.Dynamic.ExpandoClass Empty
::System::Dynamic::ExpandoClass* System::Dynamic::ExpandoClass::_get_Empty() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoClass::_get_Empty");
return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Dynamic::ExpandoClass*>("System.Dynamic", "ExpandoClass", "Empty"));
}
// Autogenerated static field setter
// Set static field: static readonly System.Dynamic.ExpandoClass Empty
void System::Dynamic::ExpandoClass::_set_Empty(::System::Dynamic::ExpandoClass* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoClass::_set_Empty");
THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Dynamic", "ExpandoClass", "Empty", value));
}
// Autogenerated instance field getter
// Get instance field: private readonly System.String[] _keys
[[deprecated("Use field access instead!")]] ::ArrayW<::StringW>& System::Dynamic::ExpandoClass::dyn__keys() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoClass::dyn__keys");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_keys"))->offset;
return *reinterpret_cast<::ArrayW<::StringW>*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private readonly System.Int32 _hashCode
[[deprecated("Use field access instead!")]] int& System::Dynamic::ExpandoClass::dyn__hashCode() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoClass::dyn__hashCode");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_hashCode"))->offset;
return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.Collections.Generic.Dictionary`2<System.Int32,System.Collections.Generic.List`1<System.WeakReference>> _transitions
[[deprecated("Use field access instead!")]] ::System::Collections::Generic::Dictionary_2<int, ::System::Collections::Generic::List_1<::System::WeakReference*>*>*& System::Dynamic::ExpandoClass::dyn__transitions() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoClass::dyn__transitions");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_transitions"))->offset;
return *reinterpret_cast<::System::Collections::Generic::Dictionary_2<int, ::System::Collections::Generic::List_1<::System::WeakReference*>*>**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated method: System.Dynamic.ExpandoClass.get_Keys
::ArrayW<::StringW> System::Dynamic::ExpandoClass::get_Keys() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoClass::get_Keys");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_Keys", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<::ArrayW<::StringW>, false>(this, ___internal__method);
}
// Autogenerated method: System.Dynamic.ExpandoClass..cctor
void System::Dynamic::ExpandoClass::_cctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoClass::.cctor");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic", "ExpandoClass", ".cctor", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
::il2cpp_utils::RunMethodRethrow<void, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method);
}
// Autogenerated method: System.Dynamic.ExpandoClass.FindNewClass
::System::Dynamic::ExpandoClass* System::Dynamic::ExpandoClass::FindNewClass(::StringW newKey) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoClass::FindNewClass");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "FindNewClass", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(newKey)})));
return ::il2cpp_utils::RunMethodRethrow<::System::Dynamic::ExpandoClass*, false>(this, ___internal__method, newKey);
}
// Autogenerated method: System.Dynamic.ExpandoClass.GetTransitionList
::System::Collections::Generic::List_1<::System::WeakReference*>* System::Dynamic::ExpandoClass::GetTransitionList(int hashCode) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoClass::GetTransitionList");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "GetTransitionList", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(hashCode)})));
return ::il2cpp_utils::RunMethodRethrow<::System::Collections::Generic::List_1<::System::WeakReference*>*, false>(this, ___internal__method, hashCode);
}
// Autogenerated method: System.Dynamic.ExpandoClass.GetValueIndex
int System::Dynamic::ExpandoClass::GetValueIndex(::StringW name, bool caseInsensitive, ::System::Dynamic::ExpandoObject* obj) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoClass::GetValueIndex");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "GetValueIndex", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(name), ::il2cpp_utils::ExtractType(caseInsensitive), ::il2cpp_utils::ExtractType(obj)})));
return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method, name, caseInsensitive, obj);
}
// Autogenerated method: System.Dynamic.ExpandoClass.GetValueIndexCaseSensitive
int System::Dynamic::ExpandoClass::GetValueIndexCaseSensitive(::StringW name) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoClass::GetValueIndexCaseSensitive");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "GetValueIndexCaseSensitive", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(name)})));
return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method, name);
}
// Autogenerated method: System.Dynamic.ExpandoClass.GetValueIndexCaseInsensitive
int System::Dynamic::ExpandoClass::GetValueIndexCaseInsensitive(::StringW name, ::System::Dynamic::ExpandoObject* obj) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoClass::GetValueIndexCaseInsensitive");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "GetValueIndexCaseInsensitive", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(name), ::il2cpp_utils::ExtractType(obj)})));
return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method, name, obj);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
// Including type: System.Dynamic.ExpandoObject
#include "System/Dynamic/ExpandoObject.hpp"
// Including type: System.Dynamic.ExpandoObject/System.Dynamic.ValueCollectionDebugView
#include "System/Dynamic/ExpandoObject_ValueCollectionDebugView.hpp"
// Including type: System.Dynamic.ExpandoObject/System.Dynamic.ValueCollection
#include "System/Dynamic/ExpandoObject_ValueCollection.hpp"
// Including type: System.Dynamic.ExpandoObject/System.Dynamic.MetaExpando
#include "System/Dynamic/ExpandoObject_MetaExpando.hpp"
// Including type: System.Dynamic.ExpandoObject/System.Dynamic.ExpandoData
#include "System/Dynamic/ExpandoObject_ExpandoData.hpp"
// Including type: System.Dynamic.ExpandoObject/System.Dynamic.<GetExpandoEnumerator>d__51
#include "System/Dynamic/ExpandoObject_-GetExpandoEnumerator-d__51.hpp"
// Including type: System.ComponentModel.PropertyChangedEventHandler
#include "System/ComponentModel/PropertyChangedEventHandler.hpp"
// Including type: System.Reflection.MethodInfo
#include "System/Reflection/MethodInfo.hpp"
// Including type: System.Dynamic.ExpandoClass
#include "System/Dynamic/ExpandoClass.hpp"
// Including type: System.Collections.Generic.ICollection`1
#include "System/Collections/Generic/ICollection_1.hpp"
// Including type: System.Dynamic.DynamicMetaObject
#include "System/Dynamic/DynamicMetaObject.hpp"
// Including type: System.Linq.Expressions.Expression
#include "System/Linq/Expressions/Expression.hpp"
// Including type: System.Collections.Generic.IEnumerator`1
#include "System/Collections/Generic/IEnumerator_1.hpp"
// Including type: System.Collections.IEnumerator
#include "System/Collections/IEnumerator.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated static field getter
// Get static field: static private readonly System.Reflection.MethodInfo ExpandoTryGetValue
::System::Reflection::MethodInfo* System::Dynamic::ExpandoObject::_get_ExpandoTryGetValue() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::_get_ExpandoTryGetValue");
return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Reflection::MethodInfo*>("System.Dynamic", "ExpandoObject", "ExpandoTryGetValue"));
}
// Autogenerated static field setter
// Set static field: static private readonly System.Reflection.MethodInfo ExpandoTryGetValue
void System::Dynamic::ExpandoObject::_set_ExpandoTryGetValue(::System::Reflection::MethodInfo* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::_set_ExpandoTryGetValue");
THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Dynamic", "ExpandoObject", "ExpandoTryGetValue", value));
}
// Autogenerated static field getter
// Get static field: static private readonly System.Reflection.MethodInfo ExpandoTrySetValue
::System::Reflection::MethodInfo* System::Dynamic::ExpandoObject::_get_ExpandoTrySetValue() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::_get_ExpandoTrySetValue");
return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Reflection::MethodInfo*>("System.Dynamic", "ExpandoObject", "ExpandoTrySetValue"));
}
// Autogenerated static field setter
// Set static field: static private readonly System.Reflection.MethodInfo ExpandoTrySetValue
void System::Dynamic::ExpandoObject::_set_ExpandoTrySetValue(::System::Reflection::MethodInfo* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::_set_ExpandoTrySetValue");
THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Dynamic", "ExpandoObject", "ExpandoTrySetValue", value));
}
// Autogenerated static field getter
// Get static field: static private readonly System.Reflection.MethodInfo ExpandoTryDeleteValue
::System::Reflection::MethodInfo* System::Dynamic::ExpandoObject::_get_ExpandoTryDeleteValue() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::_get_ExpandoTryDeleteValue");
return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Reflection::MethodInfo*>("System.Dynamic", "ExpandoObject", "ExpandoTryDeleteValue"));
}
// Autogenerated static field setter
// Set static field: static private readonly System.Reflection.MethodInfo ExpandoTryDeleteValue
void System::Dynamic::ExpandoObject::_set_ExpandoTryDeleteValue(::System::Reflection::MethodInfo* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::_set_ExpandoTryDeleteValue");
THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Dynamic", "ExpandoObject", "ExpandoTryDeleteValue", value));
}
// Autogenerated static field getter
// Get static field: static private readonly System.Reflection.MethodInfo ExpandoPromoteClass
::System::Reflection::MethodInfo* System::Dynamic::ExpandoObject::_get_ExpandoPromoteClass() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::_get_ExpandoPromoteClass");
return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Reflection::MethodInfo*>("System.Dynamic", "ExpandoObject", "ExpandoPromoteClass"));
}
// Autogenerated static field setter
// Set static field: static private readonly System.Reflection.MethodInfo ExpandoPromoteClass
void System::Dynamic::ExpandoObject::_set_ExpandoPromoteClass(::System::Reflection::MethodInfo* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::_set_ExpandoPromoteClass");
THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Dynamic", "ExpandoObject", "ExpandoPromoteClass", value));
}
// Autogenerated static field getter
// Get static field: static private readonly System.Reflection.MethodInfo ExpandoCheckVersion
::System::Reflection::MethodInfo* System::Dynamic::ExpandoObject::_get_ExpandoCheckVersion() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::_get_ExpandoCheckVersion");
return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Reflection::MethodInfo*>("System.Dynamic", "ExpandoObject", "ExpandoCheckVersion"));
}
// Autogenerated static field setter
// Set static field: static private readonly System.Reflection.MethodInfo ExpandoCheckVersion
void System::Dynamic::ExpandoObject::_set_ExpandoCheckVersion(::System::Reflection::MethodInfo* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::_set_ExpandoCheckVersion");
THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Dynamic", "ExpandoObject", "ExpandoCheckVersion", value));
}
// Autogenerated static field getter
// Get static field: static readonly System.Object Uninitialized
::Il2CppObject* System::Dynamic::ExpandoObject::_get_Uninitialized() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::_get_Uninitialized");
return THROW_UNLESS(il2cpp_utils::GetFieldValue<::Il2CppObject*>("System.Dynamic", "ExpandoObject", "Uninitialized"));
}
// Autogenerated static field setter
// Set static field: static readonly System.Object Uninitialized
void System::Dynamic::ExpandoObject::_set_Uninitialized(::Il2CppObject* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::_set_Uninitialized");
THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Dynamic", "ExpandoObject", "Uninitialized", value));
}
// Autogenerated instance field getter
// Get instance field: readonly System.Object LockObject
[[deprecated("Use field access instead!")]] ::Il2CppObject*& System::Dynamic::ExpandoObject::dyn_LockObject() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::dyn_LockObject");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "LockObject"))->offset;
return *reinterpret_cast<::Il2CppObject**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.Dynamic.ExpandoObject/System.Dynamic.ExpandoData _data
[[deprecated("Use field access instead!")]] ::System::Dynamic::ExpandoObject::ExpandoData*& System::Dynamic::ExpandoObject::dyn__data() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::dyn__data");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_data"))->offset;
return *reinterpret_cast<::System::Dynamic::ExpandoObject::ExpandoData**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.Int32 _count
[[deprecated("Use field access instead!")]] int& System::Dynamic::ExpandoObject::dyn__count() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::dyn__count");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_count"))->offset;
return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.ComponentModel.PropertyChangedEventHandler _propertyChanged
[[deprecated("Use field access instead!")]] ::System::ComponentModel::PropertyChangedEventHandler*& System::Dynamic::ExpandoObject::dyn__propertyChanged() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::dyn__propertyChanged");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_propertyChanged"))->offset;
return *reinterpret_cast<::System::ComponentModel::PropertyChangedEventHandler**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated method: System.Dynamic.ExpandoObject.get_Class
::System::Dynamic::ExpandoClass* System::Dynamic::ExpandoObject::get_Class() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::get_Class");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_Class", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<::System::Dynamic::ExpandoClass*, false>(this, ___internal__method);
}
// Autogenerated method: System.Dynamic.ExpandoObject.System.Collections.Generic.IDictionary<System.String,System.Object>.get_Values
::System::Collections::Generic::ICollection_1<::Il2CppObject*>* System::Dynamic::ExpandoObject::System_Collections_Generic_IDictionary$System_String_System_Object$_get_Values() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::System.Collections.Generic.IDictionary<System.String,System.Object>.get_Values");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::ExpandoObject*), 7));
return ::il2cpp_utils::RunMethodRethrow<::System::Collections::Generic::ICollection_1<::Il2CppObject*>*, false>(this, ___internal__method);
}
// Autogenerated method: System.Dynamic.ExpandoObject.System.Collections.Generic.IDictionary<System.String,System.Object>.get_Item
::Il2CppObject* System::Dynamic::ExpandoObject::System_Collections_Generic_IDictionary$System_String_System_Object$_get_Item(::StringW key) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::System.Collections.Generic.IDictionary<System.String,System.Object>.get_Item");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::ExpandoObject*), 5));
return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method, key);
}
// Autogenerated method: System.Dynamic.ExpandoObject.System.Collections.Generic.IDictionary<System.String,System.Object>.set_Item
void System::Dynamic::ExpandoObject::System_Collections_Generic_IDictionary$System_String_System_Object$_set_Item(::StringW key, ::Il2CppObject* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::System.Collections.Generic.IDictionary<System.String,System.Object>.set_Item");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::ExpandoObject*), 6));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, key, value);
}
// Autogenerated method: System.Dynamic.ExpandoObject.System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<System.String,System.Object>>.get_Count
int System::Dynamic::ExpandoObject::System_Collections_Generic_ICollection$System_Collections_Generic_KeyValuePair$System_String_System_Object$$_get_Count() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<System.String,System.Object>>.get_Count");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::ExpandoObject*), 11));
return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method);
}
// Autogenerated method: System.Dynamic.ExpandoObject.System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<System.String,System.Object>>.get_IsReadOnly
bool System::Dynamic::ExpandoObject::System_Collections_Generic_ICollection$System_Collections_Generic_KeyValuePair$System_String_System_Object$$_get_IsReadOnly() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<System.String,System.Object>>.get_IsReadOnly");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::ExpandoObject*), 12));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method);
}
// Autogenerated method: System.Dynamic.ExpandoObject..cctor
void System::Dynamic::ExpandoObject::_cctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::.cctor");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic", "ExpandoObject", ".cctor", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
::il2cpp_utils::RunMethodRethrow<void, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method);
}
// Autogenerated method: System.Dynamic.ExpandoObject.TryGetValue
bool System::Dynamic::ExpandoObject::TryGetValue(::Il2CppObject* indexClass, int index, ::StringW name, bool ignoreCase, ByRef<::Il2CppObject*> value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::TryGetValue");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "TryGetValue", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(indexClass), ::il2cpp_utils::ExtractType(index), ::il2cpp_utils::ExtractType(name), ::il2cpp_utils::ExtractType(ignoreCase), ::il2cpp_utils::ExtractIndependentType<::Il2CppObject*&>()})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, indexClass, index, name, ignoreCase, byref(value));
}
// Autogenerated method: System.Dynamic.ExpandoObject.TrySetValue
void System::Dynamic::ExpandoObject::TrySetValue(::Il2CppObject* indexClass, int index, ::Il2CppObject* value, ::StringW name, bool ignoreCase, bool add) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::TrySetValue");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "TrySetValue", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(indexClass), ::il2cpp_utils::ExtractType(index), ::il2cpp_utils::ExtractType(value), ::il2cpp_utils::ExtractType(name), ::il2cpp_utils::ExtractType(ignoreCase), ::il2cpp_utils::ExtractType(add)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, indexClass, index, value, name, ignoreCase, add);
}
// Autogenerated method: System.Dynamic.ExpandoObject.TryDeleteValue
bool System::Dynamic::ExpandoObject::TryDeleteValue(::Il2CppObject* indexClass, int index, ::StringW name, bool ignoreCase, ::Il2CppObject* deleteValue) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::TryDeleteValue");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "TryDeleteValue", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(indexClass), ::il2cpp_utils::ExtractType(index), ::il2cpp_utils::ExtractType(name), ::il2cpp_utils::ExtractType(ignoreCase), ::il2cpp_utils::ExtractType(deleteValue)})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, indexClass, index, name, ignoreCase, deleteValue);
}
// Autogenerated method: System.Dynamic.ExpandoObject.IsDeletedMember
bool System::Dynamic::ExpandoObject::IsDeletedMember(int index) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::IsDeletedMember");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "IsDeletedMember", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(index)})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, index);
}
// Autogenerated method: System.Dynamic.ExpandoObject.PromoteClassCore
::System::Dynamic::ExpandoObject::ExpandoData* System::Dynamic::ExpandoObject::PromoteClassCore(::System::Dynamic::ExpandoClass* oldClass, ::System::Dynamic::ExpandoClass* newClass) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::PromoteClassCore");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "PromoteClassCore", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(oldClass), ::il2cpp_utils::ExtractType(newClass)})));
return ::il2cpp_utils::RunMethodRethrow<::System::Dynamic::ExpandoObject::ExpandoData*, false>(this, ___internal__method, oldClass, newClass);
}
// Autogenerated method: System.Dynamic.ExpandoObject.PromoteClass
void System::Dynamic::ExpandoObject::PromoteClass(::Il2CppObject* oldClass, ::Il2CppObject* newClass) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::PromoteClass");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "PromoteClass", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(oldClass), ::il2cpp_utils::ExtractType(newClass)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, oldClass, newClass);
}
// Autogenerated method: System.Dynamic.ExpandoObject.System.Dynamic.IDynamicMetaObjectProvider.GetMetaObject
::System::Dynamic::DynamicMetaObject* System::Dynamic::ExpandoObject::System_Dynamic_IDynamicMetaObjectProvider_GetMetaObject(::System::Linq::Expressions::Expression* parameter) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::System.Dynamic.IDynamicMetaObjectProvider.GetMetaObject");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::ExpandoObject*), 4));
return ::il2cpp_utils::RunMethodRethrow<::System::Dynamic::DynamicMetaObject*, false>(this, ___internal__method, parameter);
}
// Autogenerated method: System.Dynamic.ExpandoObject.TryAddMember
void System::Dynamic::ExpandoObject::TryAddMember(::StringW key, ::Il2CppObject* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::TryAddMember");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "TryAddMember", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(key), ::il2cpp_utils::ExtractType(value)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, key, value);
}
// Autogenerated method: System.Dynamic.ExpandoObject.TryGetValueForKey
bool System::Dynamic::ExpandoObject::TryGetValueForKey(::StringW key, ByRef<::Il2CppObject*> value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::TryGetValueForKey");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "TryGetValueForKey", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(key), ::il2cpp_utils::ExtractIndependentType<::Il2CppObject*&>()})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, key, byref(value));
}
// Autogenerated method: System.Dynamic.ExpandoObject.System.Collections.Generic.IDictionary<System.String,System.Object>.Add
void System::Dynamic::ExpandoObject::System_Collections_Generic_IDictionary$System_String_System_Object$_Add(::StringW key, ::Il2CppObject* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::System.Collections.Generic.IDictionary<System.String,System.Object>.Add");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::ExpandoObject*), 8));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, key, value);
}
// Autogenerated method: System.Dynamic.ExpandoObject.System.Collections.Generic.IDictionary<System.String,System.Object>.Remove
bool System::Dynamic::ExpandoObject::System_Collections_Generic_IDictionary$System_String_System_Object$_Remove(::StringW key) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::System.Collections.Generic.IDictionary<System.String,System.Object>.Remove");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::ExpandoObject*), 9));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, key);
}
// Autogenerated method: System.Dynamic.ExpandoObject.System.Collections.Generic.IDictionary<System.String,System.Object>.TryGetValue
bool System::Dynamic::ExpandoObject::System_Collections_Generic_IDictionary$System_String_System_Object$_TryGetValue(::StringW key, ByRef<::Il2CppObject*> value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::System.Collections.Generic.IDictionary<System.String,System.Object>.TryGetValue");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::ExpandoObject*), 10));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, key, byref(value));
}
// Autogenerated method: System.Dynamic.ExpandoObject.System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<System.String,System.Object>>.Add
void System::Dynamic::ExpandoObject::System_Collections_Generic_ICollection$System_Collections_Generic_KeyValuePair$System_String_System_Object$$_Add(::System::Collections::Generic::KeyValuePair_2<::StringW, ::Il2CppObject*> item) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<System.String,System.Object>>.Add");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::ExpandoObject*), 13));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, item);
}
// Autogenerated method: System.Dynamic.ExpandoObject.System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<System.String,System.Object>>.Clear
void System::Dynamic::ExpandoObject::System_Collections_Generic_ICollection$System_Collections_Generic_KeyValuePair$System_String_System_Object$$_Clear() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<System.String,System.Object>>.Clear");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::ExpandoObject*), 14));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method);
}
// Autogenerated method: System.Dynamic.ExpandoObject.System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<System.String,System.Object>>.Contains
bool System::Dynamic::ExpandoObject::System_Collections_Generic_ICollection$System_Collections_Generic_KeyValuePair$System_String_System_Object$$_Contains(::System::Collections::Generic::KeyValuePair_2<::StringW, ::Il2CppObject*> item) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<System.String,System.Object>>.Contains");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::ExpandoObject*), 15));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, item);
}
// Autogenerated method: System.Dynamic.ExpandoObject.System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<System.String,System.Object>>.CopyTo
void System::Dynamic::ExpandoObject::System_Collections_Generic_ICollection$System_Collections_Generic_KeyValuePair$System_String_System_Object$$_CopyTo(::ArrayW<::System::Collections::Generic::KeyValuePair_2<::StringW, ::Il2CppObject*>> array, int arrayIndex) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<System.String,System.Object>>.CopyTo");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::ExpandoObject*), 16));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, array, arrayIndex);
}
// Autogenerated method: System.Dynamic.ExpandoObject.System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<System.String,System.Object>>.Remove
bool System::Dynamic::ExpandoObject::System_Collections_Generic_ICollection$System_Collections_Generic_KeyValuePair$System_String_System_Object$$_Remove(::System::Collections::Generic::KeyValuePair_2<::StringW, ::Il2CppObject*> item) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<System.String,System.Object>>.Remove");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::ExpandoObject*), 17));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, item);
}
// Autogenerated method: System.Dynamic.ExpandoObject.System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<System.String,System.Object>>.GetEnumerator
::System::Collections::Generic::IEnumerator_1<::System::Collections::Generic::KeyValuePair_2<::StringW, ::Il2CppObject*>>* System::Dynamic::ExpandoObject::System_Collections_Generic_IEnumerable$System_Collections_Generic_KeyValuePair$System_String_System_Object$$_GetEnumerator() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<System.String,System.Object>>.GetEnumerator");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::ExpandoObject*), 18));
return ::il2cpp_utils::RunMethodRethrow<::System::Collections::Generic::IEnumerator_1<::System::Collections::Generic::KeyValuePair_2<::StringW, ::Il2CppObject*>>*, false>(this, ___internal__method);
}
// Autogenerated method: System.Dynamic.ExpandoObject.System.Collections.IEnumerable.GetEnumerator
::System::Collections::IEnumerator* System::Dynamic::ExpandoObject::System_Collections_IEnumerable_GetEnumerator() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::System.Collections.IEnumerable.GetEnumerator");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::ExpandoObject*), 19));
return ::il2cpp_utils::RunMethodRethrow<::System::Collections::IEnumerator*, false>(this, ___internal__method);
}
// Autogenerated method: System.Dynamic.ExpandoObject.GetExpandoEnumerator
::System::Collections::Generic::IEnumerator_1<::System::Collections::Generic::KeyValuePair_2<::StringW, ::Il2CppObject*>>* System::Dynamic::ExpandoObject::GetExpandoEnumerator(::System::Dynamic::ExpandoObject::ExpandoData* data, int version) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::GetExpandoEnumerator");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "GetExpandoEnumerator", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(data), ::il2cpp_utils::ExtractType(version)})));
return ::il2cpp_utils::RunMethodRethrow<::System::Collections::Generic::IEnumerator_1<::System::Collections::Generic::KeyValuePair_2<::StringW, ::Il2CppObject*>>*, false>(this, ___internal__method, data, version);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
// Including type: System.Dynamic.ExpandoObject/System.Dynamic.ValueCollection
#include "System/Dynamic/ExpandoObject_ValueCollection.hpp"
// Including type: System.Dynamic.ExpandoObject/System.Dynamic.ValueCollection/System.Dynamic.<GetEnumerator>d__15
#include "System/Dynamic/ExpandoObject_ValueCollection_-GetEnumerator-d__15.hpp"
// Including type: System.Collections.Generic.IEnumerator`1
#include "System/Collections/Generic/IEnumerator_1.hpp"
// Including type: System.Collections.IEnumerator
#include "System/Collections/IEnumerator.hpp"
// Including type: System.Dynamic.ExpandoObject/System.Dynamic.ExpandoData
#include "System/Dynamic/ExpandoObject_ExpandoData.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated instance field getter
// Get instance field: private readonly System.Dynamic.ExpandoObject _expando
[[deprecated("Use field access instead!")]] ::System::Dynamic::ExpandoObject*& System::Dynamic::ExpandoObject::ValueCollection::dyn__expando() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::ValueCollection::dyn__expando");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_expando"))->offset;
return *reinterpret_cast<::System::Dynamic::ExpandoObject**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private readonly System.Int32 _expandoVersion
[[deprecated("Use field access instead!")]] int& System::Dynamic::ExpandoObject::ValueCollection::dyn__expandoVersion() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::ValueCollection::dyn__expandoVersion");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_expandoVersion"))->offset;
return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private readonly System.Int32 _expandoCount
[[deprecated("Use field access instead!")]] int& System::Dynamic::ExpandoObject::ValueCollection::dyn__expandoCount() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::ValueCollection::dyn__expandoCount");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_expandoCount"))->offset;
return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private readonly System.Dynamic.ExpandoObject/System.Dynamic.ExpandoData _expandoData
[[deprecated("Use field access instead!")]] ::System::Dynamic::ExpandoObject::ExpandoData*& System::Dynamic::ExpandoObject::ValueCollection::dyn__expandoData() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::ValueCollection::dyn__expandoData");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_expandoData"))->offset;
return *reinterpret_cast<::System::Dynamic::ExpandoObject::ExpandoData**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated method: System.Dynamic.ExpandoObject/System.Dynamic.ValueCollection.get_Count
int System::Dynamic::ExpandoObject::ValueCollection::get_Count() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::ValueCollection::get_Count");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::ExpandoObject::ValueCollection*), 4));
return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method);
}
// Autogenerated method: System.Dynamic.ExpandoObject/System.Dynamic.ValueCollection.get_IsReadOnly
bool System::Dynamic::ExpandoObject::ValueCollection::get_IsReadOnly() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::ValueCollection::get_IsReadOnly");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::ExpandoObject::ValueCollection*), 5));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method);
}
// Autogenerated method: System.Dynamic.ExpandoObject/System.Dynamic.ValueCollection.CheckVersion
void System::Dynamic::ExpandoObject::ValueCollection::CheckVersion() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::ValueCollection::CheckVersion");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "CheckVersion", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method);
}
// Autogenerated method: System.Dynamic.ExpandoObject/System.Dynamic.ValueCollection.Add
void System::Dynamic::ExpandoObject::ValueCollection::Add(::Il2CppObject* item) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::ValueCollection::Add");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::ExpandoObject::ValueCollection*), 6));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, item);
}
// Autogenerated method: System.Dynamic.ExpandoObject/System.Dynamic.ValueCollection.Clear
void System::Dynamic::ExpandoObject::ValueCollection::Clear() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::ValueCollection::Clear");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::ExpandoObject::ValueCollection*), 7));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method);
}
// Autogenerated method: System.Dynamic.ExpandoObject/System.Dynamic.ValueCollection.Contains
bool System::Dynamic::ExpandoObject::ValueCollection::Contains(::Il2CppObject* item) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::ValueCollection::Contains");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::ExpandoObject::ValueCollection*), 8));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, item);
}
// Autogenerated method: System.Dynamic.ExpandoObject/System.Dynamic.ValueCollection.CopyTo
void System::Dynamic::ExpandoObject::ValueCollection::CopyTo(::ArrayW<::Il2CppObject*> array, int arrayIndex) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::ValueCollection::CopyTo");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::ExpandoObject::ValueCollection*), 9));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, array, arrayIndex);
}
// Autogenerated method: System.Dynamic.ExpandoObject/System.Dynamic.ValueCollection.Remove
bool System::Dynamic::ExpandoObject::ValueCollection::Remove(::Il2CppObject* item) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::ValueCollection::Remove");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::ExpandoObject::ValueCollection*), 10));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, item);
}
// Autogenerated method: System.Dynamic.ExpandoObject/System.Dynamic.ValueCollection.GetEnumerator
::System::Collections::Generic::IEnumerator_1<::Il2CppObject*>* System::Dynamic::ExpandoObject::ValueCollection::GetEnumerator() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::ValueCollection::GetEnumerator");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::ExpandoObject::ValueCollection*), 11));
return ::il2cpp_utils::RunMethodRethrow<::System::Collections::Generic::IEnumerator_1<::Il2CppObject*>*, false>(this, ___internal__method);
}
// Autogenerated method: System.Dynamic.ExpandoObject/System.Dynamic.ValueCollection.System.Collections.IEnumerable.GetEnumerator
::System::Collections::IEnumerator* System::Dynamic::ExpandoObject::ValueCollection::System_Collections_IEnumerable_GetEnumerator() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::ValueCollection::System.Collections.IEnumerable.GetEnumerator");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::ExpandoObject::ValueCollection*), 12));
return ::il2cpp_utils::RunMethodRethrow<::System::Collections::IEnumerator*, false>(this, ___internal__method);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
// Including type: System.Dynamic.ExpandoObject/System.Dynamic.ValueCollection/System.Dynamic.<GetEnumerator>d__15
#include "System/Dynamic/ExpandoObject_ValueCollection_-GetEnumerator-d__15.hpp"
// Including type: System.Dynamic.ExpandoObject/System.Dynamic.ExpandoData
#include "System/Dynamic/ExpandoObject_ExpandoData.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated instance field getter
// Get instance field: private System.Int32 <>1__state
[[deprecated("Use field access instead!")]] int& System::Dynamic::ExpandoObject::ValueCollection::$GetEnumerator$d__15::dyn_$$1__state() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::ValueCollection::$GetEnumerator$d__15::dyn_$$1__state");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "<>1__state"))->offset;
return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.Object <>2__current
[[deprecated("Use field access instead!")]] ::Il2CppObject*& System::Dynamic::ExpandoObject::ValueCollection::$GetEnumerator$d__15::dyn_$$2__current() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::ValueCollection::$GetEnumerator$d__15::dyn_$$2__current");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "<>2__current"))->offset;
return *reinterpret_cast<::Il2CppObject**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: public System.Dynamic.ExpandoObject/System.Dynamic.ValueCollection <>4__this
[[deprecated("Use field access instead!")]] ::System::Dynamic::ExpandoObject::ValueCollection*& System::Dynamic::ExpandoObject::ValueCollection::$GetEnumerator$d__15::dyn_$$4__this() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::ValueCollection::$GetEnumerator$d__15::dyn_$$4__this");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "<>4__this"))->offset;
return *reinterpret_cast<::System::Dynamic::ExpandoObject::ValueCollection**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.Dynamic.ExpandoObject/System.Dynamic.ExpandoData <data>5__1
[[deprecated("Use field access instead!")]] ::System::Dynamic::ExpandoObject::ExpandoData*& System::Dynamic::ExpandoObject::ValueCollection::$GetEnumerator$d__15::dyn_$data$5__1() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::ValueCollection::$GetEnumerator$d__15::dyn_$data$5__1");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "<data>5__1"))->offset;
return *reinterpret_cast<::System::Dynamic::ExpandoObject::ExpandoData**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.Int32 <i>5__2
[[deprecated("Use field access instead!")]] int& System::Dynamic::ExpandoObject::ValueCollection::$GetEnumerator$d__15::dyn_$i$5__2() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::ValueCollection::$GetEnumerator$d__15::dyn_$i$5__2");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "<i>5__2"))->offset;
return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated method: System.Dynamic.ExpandoObject/System.Dynamic.ValueCollection/System.Dynamic.<GetEnumerator>d__15.System.Collections.Generic.IEnumerator<System.Object>.get_Current
::Il2CppObject* System::Dynamic::ExpandoObject::ValueCollection::$GetEnumerator$d__15::System_Collections_Generic_IEnumerator$System_Object$_get_Current() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::ValueCollection::$GetEnumerator$d__15::System.Collections.Generic.IEnumerator<System.Object>.get_Current");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::ExpandoObject::ValueCollection::$GetEnumerator$d__15*), 4));
return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method);
}
// Autogenerated method: System.Dynamic.ExpandoObject/System.Dynamic.ValueCollection/System.Dynamic.<GetEnumerator>d__15.System.Collections.IEnumerator.get_Current
::Il2CppObject* System::Dynamic::ExpandoObject::ValueCollection::$GetEnumerator$d__15::System_Collections_IEnumerator_get_Current() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::ValueCollection::$GetEnumerator$d__15::System.Collections.IEnumerator.get_Current");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::ExpandoObject::ValueCollection::$GetEnumerator$d__15*), 7));
return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method);
}
// Autogenerated method: System.Dynamic.ExpandoObject/System.Dynamic.ValueCollection/System.Dynamic.<GetEnumerator>d__15.System.IDisposable.Dispose
void System::Dynamic::ExpandoObject::ValueCollection::$GetEnumerator$d__15::System_IDisposable_Dispose() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::ValueCollection::$GetEnumerator$d__15::System.IDisposable.Dispose");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::ExpandoObject::ValueCollection::$GetEnumerator$d__15*), 5));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method);
}
// Autogenerated method: System.Dynamic.ExpandoObject/System.Dynamic.ValueCollection/System.Dynamic.<GetEnumerator>d__15.MoveNext
bool System::Dynamic::ExpandoObject::ValueCollection::$GetEnumerator$d__15::MoveNext() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::ValueCollection::$GetEnumerator$d__15::MoveNext");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::ExpandoObject::ValueCollection::$GetEnumerator$d__15*), 6));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method);
}
// Autogenerated method: System.Dynamic.ExpandoObject/System.Dynamic.ValueCollection/System.Dynamic.<GetEnumerator>d__15.System.Collections.IEnumerator.Reset
void System::Dynamic::ExpandoObject::ValueCollection::$GetEnumerator$d__15::System_Collections_IEnumerator_Reset() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::ValueCollection::$GetEnumerator$d__15::System.Collections.IEnumerator.Reset");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::ExpandoObject::ValueCollection::$GetEnumerator$d__15*), 8));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
// Including type: System.Dynamic.ExpandoObject/System.Dynamic.MetaExpando
#include "System/Dynamic/ExpandoObject_MetaExpando.hpp"
// Including type: System.Dynamic.ExpandoObject/System.Dynamic.MetaExpando/System.Dynamic.<GetDynamicMemberNames>d__6
#include "System/Dynamic/ExpandoObject_MetaExpando_-GetDynamicMemberNames-d__6.hpp"
// Including type: System.Linq.Expressions.Expression
#include "System/Linq/Expressions/Expression.hpp"
// Including type: System.Dynamic.DynamicMetaObjectBinder
#include "System/Dynamic/DynamicMetaObjectBinder.hpp"
// Including type: System.Func`2
#include "System/Func_2.hpp"
// Including type: System.Dynamic.ExpandoClass
#include "System/Dynamic/ExpandoClass.hpp"
// Including type: System.Dynamic.BindingRestrictions
#include "System/Dynamic/BindingRestrictions.hpp"
// Including type: System.Dynamic.GetMemberBinder
#include "System/Dynamic/GetMemberBinder.hpp"
// Including type: System.Dynamic.SetMemberBinder
#include "System/Dynamic/SetMemberBinder.hpp"
// Including type: System.Collections.Generic.IEnumerable`1
#include "System/Collections/Generic/IEnumerable_1.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated method: System.Dynamic.ExpandoObject/System.Dynamic.MetaExpando.get_Value
::System::Dynamic::ExpandoObject* System::Dynamic::ExpandoObject::MetaExpando::get_Value() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::MetaExpando::get_Value");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_Value", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<::System::Dynamic::ExpandoObject*, false>(this, ___internal__method);
}
// Autogenerated method: System.Dynamic.ExpandoObject/System.Dynamic.MetaExpando.BindGetOrInvokeMember
::System::Dynamic::DynamicMetaObject* System::Dynamic::ExpandoObject::MetaExpando::BindGetOrInvokeMember(::System::Dynamic::DynamicMetaObjectBinder* binder, ::StringW name, bool ignoreCase, ::System::Dynamic::DynamicMetaObject* fallback, ::System::Func_2<::System::Dynamic::DynamicMetaObject*, ::System::Dynamic::DynamicMetaObject*>* fallbackInvoke) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::MetaExpando::BindGetOrInvokeMember");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "BindGetOrInvokeMember", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(binder), ::il2cpp_utils::ExtractType(name), ::il2cpp_utils::ExtractType(ignoreCase), ::il2cpp_utils::ExtractType(fallback), ::il2cpp_utils::ExtractType(fallbackInvoke)})));
return ::il2cpp_utils::RunMethodRethrow<::System::Dynamic::DynamicMetaObject*, false>(this, ___internal__method, binder, name, ignoreCase, fallback, fallbackInvoke);
}
// Autogenerated method: System.Dynamic.ExpandoObject/System.Dynamic.MetaExpando.AddDynamicTestAndDefer
::System::Dynamic::DynamicMetaObject* System::Dynamic::ExpandoObject::MetaExpando::AddDynamicTestAndDefer(::System::Dynamic::DynamicMetaObjectBinder* binder, ::System::Dynamic::ExpandoClass* klass, ::System::Dynamic::ExpandoClass* originalClass, ::System::Dynamic::DynamicMetaObject* succeeds) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::MetaExpando::AddDynamicTestAndDefer");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "AddDynamicTestAndDefer", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(binder), ::il2cpp_utils::ExtractType(klass), ::il2cpp_utils::ExtractType(originalClass), ::il2cpp_utils::ExtractType(succeeds)})));
return ::il2cpp_utils::RunMethodRethrow<::System::Dynamic::DynamicMetaObject*, false>(this, ___internal__method, binder, klass, originalClass, succeeds);
}
// Autogenerated method: System.Dynamic.ExpandoObject/System.Dynamic.MetaExpando.GetClassEnsureIndex
::System::Dynamic::ExpandoClass* System::Dynamic::ExpandoObject::MetaExpando::GetClassEnsureIndex(::StringW name, bool caseInsensitive, ::System::Dynamic::ExpandoObject* obj, ByRef<::System::Dynamic::ExpandoClass*> klass, ByRef<int> index) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::MetaExpando::GetClassEnsureIndex");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "GetClassEnsureIndex", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(name), ::il2cpp_utils::ExtractType(caseInsensitive), ::il2cpp_utils::ExtractType(obj), ::il2cpp_utils::ExtractIndependentType<::System::Dynamic::ExpandoClass*&>(), ::il2cpp_utils::ExtractIndependentType<int&>()})));
return ::il2cpp_utils::RunMethodRethrow<::System::Dynamic::ExpandoClass*, false>(this, ___internal__method, name, caseInsensitive, obj, byref(klass), byref(index));
}
// Autogenerated method: System.Dynamic.ExpandoObject/System.Dynamic.MetaExpando.GetLimitedSelf
::System::Linq::Expressions::Expression* System::Dynamic::ExpandoObject::MetaExpando::GetLimitedSelf() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::MetaExpando::GetLimitedSelf");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "GetLimitedSelf", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<::System::Linq::Expressions::Expression*, false>(this, ___internal__method);
}
// Autogenerated method: System.Dynamic.ExpandoObject/System.Dynamic.MetaExpando.GetRestrictions
::System::Dynamic::BindingRestrictions* System::Dynamic::ExpandoObject::MetaExpando::GetRestrictions() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::MetaExpando::GetRestrictions");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "GetRestrictions", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<::System::Dynamic::BindingRestrictions*, false>(this, ___internal__method);
}
// Autogenerated method: System.Dynamic.ExpandoObject/System.Dynamic.MetaExpando.BindGetMember
::System::Dynamic::DynamicMetaObject* System::Dynamic::ExpandoObject::MetaExpando::BindGetMember(::System::Dynamic::GetMemberBinder* binder) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::MetaExpando::BindGetMember");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::DynamicMetaObject*), 4));
return ::il2cpp_utils::RunMethodRethrow<::System::Dynamic::DynamicMetaObject*, false>(this, ___internal__method, binder);
}
// Autogenerated method: System.Dynamic.ExpandoObject/System.Dynamic.MetaExpando.BindSetMember
::System::Dynamic::DynamicMetaObject* System::Dynamic::ExpandoObject::MetaExpando::BindSetMember(::System::Dynamic::SetMemberBinder* binder, ::System::Dynamic::DynamicMetaObject* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::MetaExpando::BindSetMember");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::DynamicMetaObject*), 5));
return ::il2cpp_utils::RunMethodRethrow<::System::Dynamic::DynamicMetaObject*, false>(this, ___internal__method, binder, value);
}
// Autogenerated method: System.Dynamic.ExpandoObject/System.Dynamic.MetaExpando.GetDynamicMemberNames
::System::Collections::Generic::IEnumerable_1<::StringW>* System::Dynamic::ExpandoObject::MetaExpando::GetDynamicMemberNames() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::MetaExpando::GetDynamicMemberNames");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::DynamicMetaObject*), 6));
return ::il2cpp_utils::RunMethodRethrow<::System::Collections::Generic::IEnumerable_1<::StringW>*, false>(this, ___internal__method);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
// Including type: System.Dynamic.ExpandoObject/System.Dynamic.MetaExpando/System.Dynamic.<GetDynamicMemberNames>d__6
#include "System/Dynamic/ExpandoObject_MetaExpando_-GetDynamicMemberNames-d__6.hpp"
// Including type: System.Dynamic.ExpandoClass
#include "System/Dynamic/ExpandoClass.hpp"
// Including type: System.Collections.IEnumerator
#include "System/Collections/IEnumerator.hpp"
// Including type: System.Dynamic.ExpandoObject/System.Dynamic.ExpandoData
#include "System/Dynamic/ExpandoObject_ExpandoData.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated instance field getter
// Get instance field: private System.Int32 <>1__state
[[deprecated("Use field access instead!")]] int& System::Dynamic::ExpandoObject::MetaExpando::$GetDynamicMemberNames$d__6::dyn_$$1__state() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::MetaExpando::$GetDynamicMemberNames$d__6::dyn_$$1__state");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "<>1__state"))->offset;
return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.String <>2__current
[[deprecated("Use field access instead!")]] ::StringW& System::Dynamic::ExpandoObject::MetaExpando::$GetDynamicMemberNames$d__6::dyn_$$2__current() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::MetaExpando::$GetDynamicMemberNames$d__6::dyn_$$2__current");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "<>2__current"))->offset;
return *reinterpret_cast<::StringW*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.Int32 <>l__initialThreadId
[[deprecated("Use field access instead!")]] int& System::Dynamic::ExpandoObject::MetaExpando::$GetDynamicMemberNames$d__6::dyn_$$l__initialThreadId() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::MetaExpando::$GetDynamicMemberNames$d__6::dyn_$$l__initialThreadId");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "<>l__initialThreadId"))->offset;
return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: public System.Dynamic.ExpandoObject/System.Dynamic.MetaExpando <>4__this
[[deprecated("Use field access instead!")]] ::System::Dynamic::ExpandoObject::MetaExpando*& System::Dynamic::ExpandoObject::MetaExpando::$GetDynamicMemberNames$d__6::dyn_$$4__this() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::MetaExpando::$GetDynamicMemberNames$d__6::dyn_$$4__this");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "<>4__this"))->offset;
return *reinterpret_cast<::System::Dynamic::ExpandoObject::MetaExpando**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.Dynamic.ExpandoObject/System.Dynamic.ExpandoData <expandoData>5__1
[[deprecated("Use field access instead!")]] ::System::Dynamic::ExpandoObject::ExpandoData*& System::Dynamic::ExpandoObject::MetaExpando::$GetDynamicMemberNames$d__6::dyn_$expandoData$5__1() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::MetaExpando::$GetDynamicMemberNames$d__6::dyn_$expandoData$5__1");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "<expandoData>5__1"))->offset;
return *reinterpret_cast<::System::Dynamic::ExpandoObject::ExpandoData**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.Dynamic.ExpandoClass <klass>5__2
[[deprecated("Use field access instead!")]] ::System::Dynamic::ExpandoClass*& System::Dynamic::ExpandoObject::MetaExpando::$GetDynamicMemberNames$d__6::dyn_$klass$5__2() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::MetaExpando::$GetDynamicMemberNames$d__6::dyn_$klass$5__2");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "<klass>5__2"))->offset;
return *reinterpret_cast<::System::Dynamic::ExpandoClass**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.Int32 <i>5__3
[[deprecated("Use field access instead!")]] int& System::Dynamic::ExpandoObject::MetaExpando::$GetDynamicMemberNames$d__6::dyn_$i$5__3() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::MetaExpando::$GetDynamicMemberNames$d__6::dyn_$i$5__3");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "<i>5__3"))->offset;
return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated method: System.Dynamic.ExpandoObject/System.Dynamic.MetaExpando/System.Dynamic.<GetDynamicMemberNames>d__6.System.Collections.Generic.IEnumerator<System.String>.get_Current
::StringW System::Dynamic::ExpandoObject::MetaExpando::$GetDynamicMemberNames$d__6::System_Collections_Generic_IEnumerator$System_String$_get_Current() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::MetaExpando::$GetDynamicMemberNames$d__6::System.Collections.Generic.IEnumerator<System.String>.get_Current");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::ExpandoObject::MetaExpando::$GetDynamicMemberNames$d__6*), 6));
return ::il2cpp_utils::RunMethodRethrow<::StringW, false>(this, ___internal__method);
}
// Autogenerated method: System.Dynamic.ExpandoObject/System.Dynamic.MetaExpando/System.Dynamic.<GetDynamicMemberNames>d__6.System.Collections.IEnumerator.get_Current
::Il2CppObject* System::Dynamic::ExpandoObject::MetaExpando::$GetDynamicMemberNames$d__6::System_Collections_IEnumerator_get_Current() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::MetaExpando::$GetDynamicMemberNames$d__6::System.Collections.IEnumerator.get_Current");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::ExpandoObject::MetaExpando::$GetDynamicMemberNames$d__6*), 9));
return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method);
}
// Autogenerated method: System.Dynamic.ExpandoObject/System.Dynamic.MetaExpando/System.Dynamic.<GetDynamicMemberNames>d__6.System.IDisposable.Dispose
void System::Dynamic::ExpandoObject::MetaExpando::$GetDynamicMemberNames$d__6::System_IDisposable_Dispose() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::MetaExpando::$GetDynamicMemberNames$d__6::System.IDisposable.Dispose");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::ExpandoObject::MetaExpando::$GetDynamicMemberNames$d__6*), 7));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method);
}
// Autogenerated method: System.Dynamic.ExpandoObject/System.Dynamic.MetaExpando/System.Dynamic.<GetDynamicMemberNames>d__6.MoveNext
bool System::Dynamic::ExpandoObject::MetaExpando::$GetDynamicMemberNames$d__6::MoveNext() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::MetaExpando::$GetDynamicMemberNames$d__6::MoveNext");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::ExpandoObject::MetaExpando::$GetDynamicMemberNames$d__6*), 8));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method);
}
// Autogenerated method: System.Dynamic.ExpandoObject/System.Dynamic.MetaExpando/System.Dynamic.<GetDynamicMemberNames>d__6.System.Collections.IEnumerator.Reset
void System::Dynamic::ExpandoObject::MetaExpando::$GetDynamicMemberNames$d__6::System_Collections_IEnumerator_Reset() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::MetaExpando::$GetDynamicMemberNames$d__6::System.Collections.IEnumerator.Reset");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::ExpandoObject::MetaExpando::$GetDynamicMemberNames$d__6*), 10));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method);
}
// Autogenerated method: System.Dynamic.ExpandoObject/System.Dynamic.MetaExpando/System.Dynamic.<GetDynamicMemberNames>d__6.System.Collections.Generic.IEnumerable<System.String>.GetEnumerator
::System::Collections::Generic::IEnumerator_1<::StringW>* System::Dynamic::ExpandoObject::MetaExpando::$GetDynamicMemberNames$d__6::System_Collections_Generic_IEnumerable$System_String$_GetEnumerator() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::MetaExpando::$GetDynamicMemberNames$d__6::System.Collections.Generic.IEnumerable<System.String>.GetEnumerator");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::ExpandoObject::MetaExpando::$GetDynamicMemberNames$d__6*), 4));
return ::il2cpp_utils::RunMethodRethrow<::System::Collections::Generic::IEnumerator_1<::StringW>*, false>(this, ___internal__method);
}
// Autogenerated method: System.Dynamic.ExpandoObject/System.Dynamic.MetaExpando/System.Dynamic.<GetDynamicMemberNames>d__6.System.Collections.IEnumerable.GetEnumerator
::System::Collections::IEnumerator* System::Dynamic::ExpandoObject::MetaExpando::$GetDynamicMemberNames$d__6::System_Collections_IEnumerable_GetEnumerator() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::MetaExpando::$GetDynamicMemberNames$d__6::System.Collections.IEnumerable.GetEnumerator");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::ExpandoObject::MetaExpando::$GetDynamicMemberNames$d__6*), 5));
return ::il2cpp_utils::RunMethodRethrow<::System::Collections::IEnumerator*, false>(this, ___internal__method);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
// Including type: System.Dynamic.ExpandoObject/System.Dynamic.ExpandoData
#include "System/Dynamic/ExpandoObject_ExpandoData.hpp"
// Including type: System.Dynamic.ExpandoClass
#include "System/Dynamic/ExpandoClass.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated static field getter
// Get static field: static System.Dynamic.ExpandoObject/System.Dynamic.ExpandoData Empty
::System::Dynamic::ExpandoObject::ExpandoData* System::Dynamic::ExpandoObject::ExpandoData::_get_Empty() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::ExpandoData::_get_Empty");
return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Dynamic::ExpandoObject::ExpandoData*>("System.Dynamic", "ExpandoObject/ExpandoData", "Empty"));
}
// Autogenerated static field setter
// Set static field: static System.Dynamic.ExpandoObject/System.Dynamic.ExpandoData Empty
void System::Dynamic::ExpandoObject::ExpandoData::_set_Empty(::System::Dynamic::ExpandoObject::ExpandoData* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::ExpandoData::_set_Empty");
THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Dynamic", "ExpandoObject/ExpandoData", "Empty", value));
}
// Autogenerated instance field getter
// Get instance field: readonly System.Dynamic.ExpandoClass Class
[[deprecated("Use field access instead!")]] ::System::Dynamic::ExpandoClass*& System::Dynamic::ExpandoObject::ExpandoData::dyn_Class() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::ExpandoData::dyn_Class");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "Class"))->offset;
return *reinterpret_cast<::System::Dynamic::ExpandoClass**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private readonly System.Object[] _dataArray
[[deprecated("Use field access instead!")]] ::ArrayW<::Il2CppObject*>& System::Dynamic::ExpandoObject::ExpandoData::dyn__dataArray() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::ExpandoData::dyn__dataArray");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_dataArray"))->offset;
return *reinterpret_cast<::ArrayW<::Il2CppObject*>*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.Int32 _version
[[deprecated("Use field access instead!")]] int& System::Dynamic::ExpandoObject::ExpandoData::dyn__version() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::ExpandoData::dyn__version");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_version"))->offset;
return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated method: System.Dynamic.ExpandoObject/System.Dynamic.ExpandoData.get_Item
::Il2CppObject* System::Dynamic::ExpandoObject::ExpandoData::get_Item(int index) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::ExpandoData::get_Item");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_Item", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(index)})));
return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method, index);
}
// Autogenerated method: System.Dynamic.ExpandoObject/System.Dynamic.ExpandoData.set_Item
void System::Dynamic::ExpandoObject::ExpandoData::set_Item(int index, ::Il2CppObject* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::ExpandoData::set_Item");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_Item", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(index), ::il2cpp_utils::ExtractType(value)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, index, value);
}
// Autogenerated method: System.Dynamic.ExpandoObject/System.Dynamic.ExpandoData.get_Version
int System::Dynamic::ExpandoObject::ExpandoData::get_Version() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::ExpandoData::get_Version");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_Version", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method);
}
// Autogenerated method: System.Dynamic.ExpandoObject/System.Dynamic.ExpandoData.get_Length
int System::Dynamic::ExpandoObject::ExpandoData::get_Length() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::ExpandoData::get_Length");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_Length", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method);
}
// Autogenerated method: System.Dynamic.ExpandoObject/System.Dynamic.ExpandoData..cctor
void System::Dynamic::ExpandoObject::ExpandoData::_cctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::ExpandoData::.cctor");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic", "ExpandoObject/ExpandoData", ".cctor", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
::il2cpp_utils::RunMethodRethrow<void, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method);
}
// Autogenerated method: System.Dynamic.ExpandoObject/System.Dynamic.ExpandoData.UpdateClass
::System::Dynamic::ExpandoObject::ExpandoData* System::Dynamic::ExpandoObject::ExpandoData::UpdateClass(::System::Dynamic::ExpandoClass* newClass) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::ExpandoData::UpdateClass");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "UpdateClass", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(newClass)})));
return ::il2cpp_utils::RunMethodRethrow<::System::Dynamic::ExpandoObject::ExpandoData*, false>(this, ___internal__method, newClass);
}
// Autogenerated method: System.Dynamic.ExpandoObject/System.Dynamic.ExpandoData.GetAlignedSize
int System::Dynamic::ExpandoObject::ExpandoData::GetAlignedSize(int len) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::ExpandoData::GetAlignedSize");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic", "ExpandoObject/ExpandoData", "GetAlignedSize", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(len)})));
return ::il2cpp_utils::RunMethodRethrow<int, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, len);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
// Including type: System.Dynamic.ExpandoObject/System.Dynamic.<GetExpandoEnumerator>d__51
#include "System/Dynamic/ExpandoObject_-GetExpandoEnumerator-d__51.hpp"
// Including type: System.Dynamic.ExpandoObject/System.Dynamic.ExpandoData
#include "System/Dynamic/ExpandoObject_ExpandoData.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated instance field getter
// Get instance field: private System.Int32 <>1__state
[[deprecated("Use field access instead!")]] int& System::Dynamic::ExpandoObject::$GetExpandoEnumerator$d__51::dyn_$$1__state() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::$GetExpandoEnumerator$d__51::dyn_$$1__state");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "<>1__state"))->offset;
return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.Collections.Generic.KeyValuePair`2<System.String,System.Object> <>2__current
[[deprecated("Use field access instead!")]] ::System::Collections::Generic::KeyValuePair_2<::StringW, ::Il2CppObject*>& System::Dynamic::ExpandoObject::$GetExpandoEnumerator$d__51::dyn_$$2__current() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::$GetExpandoEnumerator$d__51::dyn_$$2__current");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "<>2__current"))->offset;
return *reinterpret_cast<::System::Collections::Generic::KeyValuePair_2<::StringW, ::Il2CppObject*>*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: public System.Dynamic.ExpandoObject <>4__this
[[deprecated("Use field access instead!")]] ::System::Dynamic::ExpandoObject*& System::Dynamic::ExpandoObject::$GetExpandoEnumerator$d__51::dyn_$$4__this() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::$GetExpandoEnumerator$d__51::dyn_$$4__this");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "<>4__this"))->offset;
return *reinterpret_cast<::System::Dynamic::ExpandoObject**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: public System.Int32 version
[[deprecated("Use field access instead!")]] int& System::Dynamic::ExpandoObject::$GetExpandoEnumerator$d__51::dyn_version() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::$GetExpandoEnumerator$d__51::dyn_version");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "version"))->offset;
return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: public System.Dynamic.ExpandoObject/System.Dynamic.ExpandoData data
[[deprecated("Use field access instead!")]] ::System::Dynamic::ExpandoObject::ExpandoData*& System::Dynamic::ExpandoObject::$GetExpandoEnumerator$d__51::dyn_data() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::$GetExpandoEnumerator$d__51::dyn_data");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "data"))->offset;
return *reinterpret_cast<::System::Dynamic::ExpandoObject::ExpandoData**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.Int32 <i>5__1
[[deprecated("Use field access instead!")]] int& System::Dynamic::ExpandoObject::$GetExpandoEnumerator$d__51::dyn_$i$5__1() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::$GetExpandoEnumerator$d__51::dyn_$i$5__1");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "<i>5__1"))->offset;
return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated method: System.Dynamic.ExpandoObject/System.Dynamic.<GetExpandoEnumerator>d__51.System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<System.String,System.Object>>.get_Current
::System::Collections::Generic::KeyValuePair_2<::StringW, ::Il2CppObject*> System::Dynamic::ExpandoObject::$GetExpandoEnumerator$d__51::System_Collections_Generic_IEnumerator$System_Collections_Generic_KeyValuePair$System_String_System_Object$$_get_Current() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::$GetExpandoEnumerator$d__51::System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<System.String,System.Object>>.get_Current");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::ExpandoObject::$GetExpandoEnumerator$d__51*), 4));
return ::il2cpp_utils::RunMethodRethrow<::System::Collections::Generic::KeyValuePair_2<::StringW, ::Il2CppObject*>, false>(this, ___internal__method);
}
// Autogenerated method: System.Dynamic.ExpandoObject/System.Dynamic.<GetExpandoEnumerator>d__51.System.Collections.IEnumerator.get_Current
::Il2CppObject* System::Dynamic::ExpandoObject::$GetExpandoEnumerator$d__51::System_Collections_IEnumerator_get_Current() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::$GetExpandoEnumerator$d__51::System.Collections.IEnumerator.get_Current");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::ExpandoObject::$GetExpandoEnumerator$d__51*), 7));
return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method);
}
// Autogenerated method: System.Dynamic.ExpandoObject/System.Dynamic.<GetExpandoEnumerator>d__51.System.IDisposable.Dispose
void System::Dynamic::ExpandoObject::$GetExpandoEnumerator$d__51::System_IDisposable_Dispose() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::$GetExpandoEnumerator$d__51::System.IDisposable.Dispose");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::ExpandoObject::$GetExpandoEnumerator$d__51*), 5));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method);
}
// Autogenerated method: System.Dynamic.ExpandoObject/System.Dynamic.<GetExpandoEnumerator>d__51.MoveNext
bool System::Dynamic::ExpandoObject::$GetExpandoEnumerator$d__51::MoveNext() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::$GetExpandoEnumerator$d__51::MoveNext");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::ExpandoObject::$GetExpandoEnumerator$d__51*), 6));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method);
}
// Autogenerated method: System.Dynamic.ExpandoObject/System.Dynamic.<GetExpandoEnumerator>d__51.System.Collections.IEnumerator.Reset
void System::Dynamic::ExpandoObject::$GetExpandoEnumerator$d__51::System_Collections_IEnumerator_Reset() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::ExpandoObject::$GetExpandoEnumerator$d__51::System.Collections.IEnumerator.Reset");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::ExpandoObject::$GetExpandoEnumerator$d__51*), 8));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
// Including type: System.Dynamic.GetMemberBinder
#include "System/Dynamic/GetMemberBinder.hpp"
// Including type: System.Dynamic.DynamicMetaObject
#include "System/Dynamic/DynamicMetaObject.hpp"
// Including type: System.Type
#include "System/Type.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated instance field getter
// Get instance field: private readonly System.String <Name>k__BackingField
[[deprecated("Use field access instead!")]] ::StringW& System::Dynamic::GetMemberBinder::dyn_$Name$k__BackingField() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::GetMemberBinder::dyn_$Name$k__BackingField");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "<Name>k__BackingField"))->offset;
return *reinterpret_cast<::StringW*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private readonly System.Boolean <IgnoreCase>k__BackingField
[[deprecated("Use field access instead!")]] bool& System::Dynamic::GetMemberBinder::dyn_$IgnoreCase$k__BackingField() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::GetMemberBinder::dyn_$IgnoreCase$k__BackingField");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "<IgnoreCase>k__BackingField"))->offset;
return *reinterpret_cast<bool*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated method: System.Dynamic.GetMemberBinder.get_Name
::StringW System::Dynamic::GetMemberBinder::get_Name() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::GetMemberBinder::get_Name");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_Name", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<::StringW, false>(this, ___internal__method);
}
// Autogenerated method: System.Dynamic.GetMemberBinder.get_IgnoreCase
bool System::Dynamic::GetMemberBinder::get_IgnoreCase() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::GetMemberBinder::get_IgnoreCase");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_IgnoreCase", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method);
}
// Autogenerated method: System.Dynamic.GetMemberBinder.FallbackGetMember
::System::Dynamic::DynamicMetaObject* System::Dynamic::GetMemberBinder::FallbackGetMember(::System::Dynamic::DynamicMetaObject* target) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::GetMemberBinder::FallbackGetMember");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "FallbackGetMember", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(target)})));
return ::il2cpp_utils::RunMethodRethrow<::System::Dynamic::DynamicMetaObject*, false>(this, ___internal__method, target);
}
// Autogenerated method: System.Dynamic.GetMemberBinder.FallbackGetMember
::System::Dynamic::DynamicMetaObject* System::Dynamic::GetMemberBinder::FallbackGetMember(::System::Dynamic::DynamicMetaObject* target, ::System::Dynamic::DynamicMetaObject* errorSuggestion) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::GetMemberBinder::FallbackGetMember");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::GetMemberBinder*), -1));
return ::il2cpp_utils::RunMethodRethrow<::System::Dynamic::DynamicMetaObject*, false>(this, ___internal__method, target, errorSuggestion);
}
// Autogenerated method: System.Dynamic.GetMemberBinder.get_ReturnType
::System::Type* System::Dynamic::GetMemberBinder::get_ReturnType() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::GetMemberBinder::get_ReturnType");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::DynamicMetaObjectBinder*), 6));
return ::il2cpp_utils::RunMethodRethrow<::System::Type*, false>(this, ___internal__method);
}
// Autogenerated method: System.Dynamic.GetMemberBinder.get_IsStandardBinder
bool System::Dynamic::GetMemberBinder::get_IsStandardBinder() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::GetMemberBinder::get_IsStandardBinder");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::DynamicMetaObjectBinder*), 8));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method);
}
// Autogenerated method: System.Dynamic.GetMemberBinder.Bind
::System::Dynamic::DynamicMetaObject* System::Dynamic::GetMemberBinder::Bind(::System::Dynamic::DynamicMetaObject* target, ::ArrayW<::System::Dynamic::DynamicMetaObject*> args) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::GetMemberBinder::Bind");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::DynamicMetaObjectBinder*), 7));
return ::il2cpp_utils::RunMethodRethrow<::System::Dynamic::DynamicMetaObject*, false>(this, ___internal__method, target, args);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
// Including type: System.Dynamic.IDynamicMetaObjectProvider
#include "System/Dynamic/IDynamicMetaObjectProvider.hpp"
// Including type: System.Dynamic.DynamicMetaObject
#include "System/Dynamic/DynamicMetaObject.hpp"
// Including type: System.Linq.Expressions.Expression
#include "System/Linq/Expressions/Expression.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated method: System.Dynamic.IDynamicMetaObjectProvider.GetMetaObject
::System::Dynamic::DynamicMetaObject* System::Dynamic::IDynamicMetaObjectProvider::GetMetaObject(::System::Linq::Expressions::Expression* parameter) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::IDynamicMetaObjectProvider::GetMetaObject");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::IDynamicMetaObjectProvider*), -1));
return ::il2cpp_utils::RunMethodRethrow<::System::Dynamic::DynamicMetaObject*, false>(this, ___internal__method, parameter);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
// Including type: System.Dynamic.SetMemberBinder
#include "System/Dynamic/SetMemberBinder.hpp"
// Including type: System.Dynamic.DynamicMetaObject
#include "System/Dynamic/DynamicMetaObject.hpp"
// Including type: System.Type
#include "System/Type.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated instance field getter
// Get instance field: private readonly System.String <Name>k__BackingField
[[deprecated("Use field access instead!")]] ::StringW& System::Dynamic::SetMemberBinder::dyn_$Name$k__BackingField() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::SetMemberBinder::dyn_$Name$k__BackingField");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "<Name>k__BackingField"))->offset;
return *reinterpret_cast<::StringW*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private readonly System.Boolean <IgnoreCase>k__BackingField
[[deprecated("Use field access instead!")]] bool& System::Dynamic::SetMemberBinder::dyn_$IgnoreCase$k__BackingField() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::SetMemberBinder::dyn_$IgnoreCase$k__BackingField");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "<IgnoreCase>k__BackingField"))->offset;
return *reinterpret_cast<bool*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated method: System.Dynamic.SetMemberBinder.get_Name
::StringW System::Dynamic::SetMemberBinder::get_Name() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::SetMemberBinder::get_Name");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_Name", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<::StringW, false>(this, ___internal__method);
}
// Autogenerated method: System.Dynamic.SetMemberBinder.get_IgnoreCase
bool System::Dynamic::SetMemberBinder::get_IgnoreCase() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::SetMemberBinder::get_IgnoreCase");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_IgnoreCase", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method);
}
// Autogenerated method: System.Dynamic.SetMemberBinder.FallbackSetMember
::System::Dynamic::DynamicMetaObject* System::Dynamic::SetMemberBinder::FallbackSetMember(::System::Dynamic::DynamicMetaObject* target, ::System::Dynamic::DynamicMetaObject* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::SetMemberBinder::FallbackSetMember");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "FallbackSetMember", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(target), ::il2cpp_utils::ExtractType(value)})));
return ::il2cpp_utils::RunMethodRethrow<::System::Dynamic::DynamicMetaObject*, false>(this, ___internal__method, target, value);
}
// Autogenerated method: System.Dynamic.SetMemberBinder.FallbackSetMember
::System::Dynamic::DynamicMetaObject* System::Dynamic::SetMemberBinder::FallbackSetMember(::System::Dynamic::DynamicMetaObject* target, ::System::Dynamic::DynamicMetaObject* value, ::System::Dynamic::DynamicMetaObject* errorSuggestion) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::SetMemberBinder::FallbackSetMember");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::SetMemberBinder*), -1));
return ::il2cpp_utils::RunMethodRethrow<::System::Dynamic::DynamicMetaObject*, false>(this, ___internal__method, target, value, errorSuggestion);
}
// Autogenerated method: System.Dynamic.SetMemberBinder.get_ReturnType
::System::Type* System::Dynamic::SetMemberBinder::get_ReturnType() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::SetMemberBinder::get_ReturnType");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::DynamicMetaObjectBinder*), 6));
return ::il2cpp_utils::RunMethodRethrow<::System::Type*, false>(this, ___internal__method);
}
// Autogenerated method: System.Dynamic.SetMemberBinder.get_IsStandardBinder
bool System::Dynamic::SetMemberBinder::get_IsStandardBinder() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::SetMemberBinder::get_IsStandardBinder");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::DynamicMetaObjectBinder*), 8));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method);
}
// Autogenerated method: System.Dynamic.SetMemberBinder.Bind
::System::Dynamic::DynamicMetaObject* System::Dynamic::SetMemberBinder::Bind(::System::Dynamic::DynamicMetaObject* target, ::ArrayW<::System::Dynamic::DynamicMetaObject*> args) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::SetMemberBinder::Bind");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Dynamic::DynamicMetaObjectBinder*), 7));
return ::il2cpp_utils::RunMethodRethrow<::System::Dynamic::DynamicMetaObject*, false>(this, ___internal__method, target, args);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
// Including type: System.Dynamic.Utils.CollectionExtensions
#include "System/Dynamic/Utils/CollectionExtensions.hpp"
// Including type: System.Runtime.CompilerServices.TrueReadOnlyCollection`1
#include "System/Runtime/CompilerServices/TrueReadOnlyCollection_1.hpp"
// Including type: System.Collections.ObjectModel.ReadOnlyCollection`1
#include "System/Collections/ObjectModel/ReadOnlyCollection_1.hpp"
// Including type: System.Collections.Generic.IEnumerable`1
#include "System/Collections/Generic/IEnumerable_1.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
// Including type: System.Dynamic.Utils.ContractUtils
#include "System/Dynamic/Utils/ContractUtils.hpp"
// Including type: System.Exception
#include "System/Exception.hpp"
// Including type: System.Collections.Generic.IList`1
#include "System/Collections/Generic/IList_1.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated method: System.Dynamic.Utils.ContractUtils.get_Unreachable
::System::Exception* System::Dynamic::Utils::ContractUtils::get_Unreachable() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::ContractUtils::get_Unreachable");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "ContractUtils", "get_Unreachable", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<::System::Exception*, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method);
}
// Autogenerated method: System.Dynamic.Utils.ContractUtils.Requires
void System::Dynamic::Utils::ContractUtils::Requires(bool precondition, ::StringW paramName) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::ContractUtils::Requires");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "ContractUtils", "Requires", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(precondition), ::il2cpp_utils::ExtractType(paramName)})));
::il2cpp_utils::RunMethodRethrow<void, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, precondition, paramName);
}
// Autogenerated method: System.Dynamic.Utils.ContractUtils.RequiresNotNull
void System::Dynamic::Utils::ContractUtils::RequiresNotNull(::Il2CppObject* value, ::StringW paramName) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::ContractUtils::RequiresNotNull");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "ContractUtils", "RequiresNotNull", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value), ::il2cpp_utils::ExtractType(paramName)})));
::il2cpp_utils::RunMethodRethrow<void, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, value, paramName);
}
// Autogenerated method: System.Dynamic.Utils.ContractUtils.RequiresNotNull
void System::Dynamic::Utils::ContractUtils::RequiresNotNull(::Il2CppObject* value, ::StringW paramName, int index) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::ContractUtils::RequiresNotNull");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "ContractUtils", "RequiresNotNull", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value), ::il2cpp_utils::ExtractType(paramName), ::il2cpp_utils::ExtractType(index)})));
::il2cpp_utils::RunMethodRethrow<void, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, value, paramName, index);
}
// Autogenerated method: System.Dynamic.Utils.ContractUtils.GetParamName
::StringW System::Dynamic::Utils::ContractUtils::GetParamName(::StringW paramName, int index) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::ContractUtils::GetParamName");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "ContractUtils", "GetParamName", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(paramName), ::il2cpp_utils::ExtractType(index)})));
return ::il2cpp_utils::RunMethodRethrow<::StringW, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, paramName, index);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
// Including type: System.Dynamic.Utils.ExpressionUtils
#include "System/Dynamic/Utils/ExpressionUtils.hpp"
// Including type: System.Collections.ObjectModel.ReadOnlyCollection`1
#include "System/Collections/ObjectModel/ReadOnlyCollection_1.hpp"
// Including type: System.Collections.Generic.IReadOnlyList`1
#include "System/Collections/Generic/IReadOnlyList_1.hpp"
// Including type: System.Reflection.MethodBase
#include "System/Reflection/MethodBase.hpp"
// Including type: System.Linq.Expressions.ExpressionType
#include "System/Linq/Expressions/ExpressionType.hpp"
// Including type: System.Linq.Expressions.Expression
#include "System/Linq/Expressions/Expression.hpp"
// Including type: System.Reflection.ParameterInfo
#include "System/Reflection/ParameterInfo.hpp"
// Including type: System.Type
#include "System/Type.hpp"
// Including type: System.Collections.Generic.IEnumerable`1
#include "System/Collections/Generic/IEnumerable_1.hpp"
// Including type: System.Collections.Generic.ICollection`1
#include "System/Collections/Generic/ICollection_1.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated method: System.Dynamic.Utils.ExpressionUtils.ValidateArgumentTypes
void System::Dynamic::Utils::ExpressionUtils::ValidateArgumentTypes(::System::Reflection::MethodBase* method, ::System::Linq::Expressions::ExpressionType nodeKind, ByRef<::System::Collections::ObjectModel::ReadOnlyCollection_1<::System::Linq::Expressions::Expression*>*> arguments, ::StringW methodParamName) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::ExpressionUtils::ValidateArgumentTypes");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "ExpressionUtils", "ValidateArgumentTypes", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(method), ::il2cpp_utils::ExtractType(nodeKind), ::il2cpp_utils::ExtractType(arguments), ::il2cpp_utils::ExtractType(methodParamName)})));
::il2cpp_utils::RunMethodRethrow<void, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, method, nodeKind, byref(arguments), methodParamName);
}
// Autogenerated method: System.Dynamic.Utils.ExpressionUtils.ValidateArgumentCount
void System::Dynamic::Utils::ExpressionUtils::ValidateArgumentCount(::System::Reflection::MethodBase* method, ::System::Linq::Expressions::ExpressionType nodeKind, int count, ::ArrayW<::System::Reflection::ParameterInfo*> pis) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::ExpressionUtils::ValidateArgumentCount");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "ExpressionUtils", "ValidateArgumentCount", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(method), ::il2cpp_utils::ExtractType(nodeKind), ::il2cpp_utils::ExtractType(count), ::il2cpp_utils::ExtractType(pis)})));
::il2cpp_utils::RunMethodRethrow<void, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, method, nodeKind, count, pis);
}
// Autogenerated method: System.Dynamic.Utils.ExpressionUtils.ValidateOneArgument
::System::Linq::Expressions::Expression* System::Dynamic::Utils::ExpressionUtils::ValidateOneArgument(::System::Reflection::MethodBase* method, ::System::Linq::Expressions::ExpressionType nodeKind, ::System::Linq::Expressions::Expression* arguments, ::System::Reflection::ParameterInfo* pi, ::StringW methodParamName, ::StringW argumentParamName, int index) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::ExpressionUtils::ValidateOneArgument");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "ExpressionUtils", "ValidateOneArgument", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(method), ::il2cpp_utils::ExtractType(nodeKind), ::il2cpp_utils::ExtractType(arguments), ::il2cpp_utils::ExtractType(pi), ::il2cpp_utils::ExtractType(methodParamName), ::il2cpp_utils::ExtractType(argumentParamName), ::il2cpp_utils::ExtractType(index)})));
return ::il2cpp_utils::RunMethodRethrow<::System::Linq::Expressions::Expression*, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, method, nodeKind, arguments, pi, methodParamName, argumentParamName, index);
}
// Autogenerated method: System.Dynamic.Utils.ExpressionUtils.RequiresCanRead
void System::Dynamic::Utils::ExpressionUtils::RequiresCanRead(::System::Linq::Expressions::Expression* expression, ::StringW paramName) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::ExpressionUtils::RequiresCanRead");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "ExpressionUtils", "RequiresCanRead", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(expression), ::il2cpp_utils::ExtractType(paramName)})));
::il2cpp_utils::RunMethodRethrow<void, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, expression, paramName);
}
// Autogenerated method: System.Dynamic.Utils.ExpressionUtils.RequiresCanRead
void System::Dynamic::Utils::ExpressionUtils::RequiresCanRead(::System::Linq::Expressions::Expression* expression, ::StringW paramName, int idx) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::ExpressionUtils::RequiresCanRead");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "ExpressionUtils", "RequiresCanRead", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(expression), ::il2cpp_utils::ExtractType(paramName), ::il2cpp_utils::ExtractType(idx)})));
::il2cpp_utils::RunMethodRethrow<void, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, expression, paramName, idx);
}
// Autogenerated method: System.Dynamic.Utils.ExpressionUtils.TryQuote
bool System::Dynamic::Utils::ExpressionUtils::TryQuote(::System::Type* parameterType, ByRef<::System::Linq::Expressions::Expression*> argument) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::ExpressionUtils::TryQuote");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "ExpressionUtils", "TryQuote", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(parameterType), ::il2cpp_utils::ExtractType(argument)})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, parameterType, byref(argument));
}
// Autogenerated method: System.Dynamic.Utils.ExpressionUtils.GetParametersForValidation
::ArrayW<::System::Reflection::ParameterInfo*> System::Dynamic::Utils::ExpressionUtils::GetParametersForValidation(::System::Reflection::MethodBase* method, ::System::Linq::Expressions::ExpressionType nodeKind) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::ExpressionUtils::GetParametersForValidation");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "ExpressionUtils", "GetParametersForValidation", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(method), ::il2cpp_utils::ExtractType(nodeKind)})));
return ::il2cpp_utils::RunMethodRethrow<::ArrayW<::System::Reflection::ParameterInfo*>, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, method, nodeKind);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
// Including type: System.Dynamic.Utils.ExpressionVisitorUtils
#include "System/Dynamic/Utils/ExpressionVisitorUtils.hpp"
// Including type: System.Linq.Expressions.Expression
#include "System/Linq/Expressions/Expression.hpp"
// Including type: System.Linq.Expressions.ExpressionVisitor
#include "System/Linq/Expressions/ExpressionVisitor.hpp"
// Including type: System.Linq.Expressions.BlockExpression
#include "System/Linq/Expressions/BlockExpression.hpp"
// Including type: System.Linq.Expressions.ParameterExpression
#include "System/Linq/Expressions/ParameterExpression.hpp"
// Including type: System.Linq.Expressions.IParameterProvider
#include "System/Linq/Expressions/IParameterProvider.hpp"
// Including type: System.Linq.Expressions.IArgumentProvider
#include "System/Linq/Expressions/IArgumentProvider.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated method: System.Dynamic.Utils.ExpressionVisitorUtils.VisitBlockExpressions
::ArrayW<::System::Linq::Expressions::Expression*> System::Dynamic::Utils::ExpressionVisitorUtils::VisitBlockExpressions(::System::Linq::Expressions::ExpressionVisitor* visitor, ::System::Linq::Expressions::BlockExpression* block) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::ExpressionVisitorUtils::VisitBlockExpressions");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "ExpressionVisitorUtils", "VisitBlockExpressions", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(visitor), ::il2cpp_utils::ExtractType(block)})));
return ::il2cpp_utils::RunMethodRethrow<::ArrayW<::System::Linq::Expressions::Expression*>, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, visitor, block);
}
// Autogenerated method: System.Dynamic.Utils.ExpressionVisitorUtils.VisitParameters
::ArrayW<::System::Linq::Expressions::ParameterExpression*> System::Dynamic::Utils::ExpressionVisitorUtils::VisitParameters(::System::Linq::Expressions::ExpressionVisitor* visitor, ::System::Linq::Expressions::IParameterProvider* nodes, ::StringW callerName) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::ExpressionVisitorUtils::VisitParameters");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "ExpressionVisitorUtils", "VisitParameters", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(visitor), ::il2cpp_utils::ExtractType(nodes), ::il2cpp_utils::ExtractType(callerName)})));
return ::il2cpp_utils::RunMethodRethrow<::ArrayW<::System::Linq::Expressions::ParameterExpression*>, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, visitor, nodes, callerName);
}
// Autogenerated method: System.Dynamic.Utils.ExpressionVisitorUtils.VisitArguments
::ArrayW<::System::Linq::Expressions::Expression*> System::Dynamic::Utils::ExpressionVisitorUtils::VisitArguments(::System::Linq::Expressions::ExpressionVisitor* visitor, ::System::Linq::Expressions::IArgumentProvider* nodes) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::ExpressionVisitorUtils::VisitArguments");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "ExpressionVisitorUtils", "VisitArguments", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(visitor), ::il2cpp_utils::ExtractType(nodes)})));
return ::il2cpp_utils::RunMethodRethrow<::ArrayW<::System::Linq::Expressions::Expression*>, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, visitor, nodes);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
// Including type: System.Dynamic.Utils.TypeExtensions
#include "System/Dynamic/Utils/TypeExtensions.hpp"
// Including type: System.Dynamic.Utils.CacheDict`2
#include "System/Dynamic/Utils/CacheDict_2.hpp"
// Including type: System.Reflection.MethodBase
#include "System/Reflection/MethodBase.hpp"
// Including type: System.Reflection.ParameterInfo
#include "System/Reflection/ParameterInfo.hpp"
// Including type: System.Reflection.MethodInfo
#include "System/Reflection/MethodInfo.hpp"
// Including type: System.Type
#include "System/Type.hpp"
// Including type: System.TypeCode
#include "System/TypeCode.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated static field getter
// Get static field: static private readonly System.Dynamic.Utils.CacheDict`2<System.Reflection.MethodBase,System.Reflection.ParameterInfo[]> s_paramInfoCache
::System::Dynamic::Utils::CacheDict_2<::System::Reflection::MethodBase*, ::ArrayW<::System::Reflection::ParameterInfo*>>* System::Dynamic::Utils::TypeExtensions::_get_s_paramInfoCache() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::TypeExtensions::_get_s_paramInfoCache");
return THROW_UNLESS((il2cpp_utils::GetFieldValue<::System::Dynamic::Utils::CacheDict_2<::System::Reflection::MethodBase*, ::ArrayW<::System::Reflection::ParameterInfo*>>*>("System.Dynamic.Utils", "TypeExtensions", "s_paramInfoCache")));
}
// Autogenerated static field setter
// Set static field: static private readonly System.Dynamic.Utils.CacheDict`2<System.Reflection.MethodBase,System.Reflection.ParameterInfo[]> s_paramInfoCache
void System::Dynamic::Utils::TypeExtensions::_set_s_paramInfoCache(::System::Dynamic::Utils::CacheDict_2<::System::Reflection::MethodBase*, ::ArrayW<::System::Reflection::ParameterInfo*>>* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::TypeExtensions::_set_s_paramInfoCache");
THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Dynamic.Utils", "TypeExtensions", "s_paramInfoCache", value));
}
// Autogenerated method: System.Dynamic.Utils.TypeExtensions..cctor
void System::Dynamic::Utils::TypeExtensions::_cctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::TypeExtensions::.cctor");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "TypeExtensions", ".cctor", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
::il2cpp_utils::RunMethodRethrow<void, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method);
}
// Autogenerated method: System.Dynamic.Utils.TypeExtensions.GetAnyStaticMethodValidated
::System::Reflection::MethodInfo* System::Dynamic::Utils::TypeExtensions::GetAnyStaticMethodValidated(::System::Type* type, ::StringW name, ::ArrayW<::System::Type*> types) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::TypeExtensions::GetAnyStaticMethodValidated");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "TypeExtensions", "GetAnyStaticMethodValidated", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(type), ::il2cpp_utils::ExtractType(name), ::il2cpp_utils::ExtractType(types)})));
return ::il2cpp_utils::RunMethodRethrow<::System::Reflection::MethodInfo*, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, type, name, types);
}
// Autogenerated method: System.Dynamic.Utils.TypeExtensions.MatchesArgumentTypes
bool System::Dynamic::Utils::TypeExtensions::MatchesArgumentTypes(::System::Reflection::MethodInfo* mi, ::ArrayW<::System::Type*> argTypes) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::TypeExtensions::MatchesArgumentTypes");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "TypeExtensions", "MatchesArgumentTypes", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(mi), ::il2cpp_utils::ExtractType(argTypes)})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, mi, argTypes);
}
// Autogenerated method: System.Dynamic.Utils.TypeExtensions.GetReturnType
::System::Type* System::Dynamic::Utils::TypeExtensions::GetReturnType(::System::Reflection::MethodBase* mi) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::TypeExtensions::GetReturnType");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "TypeExtensions", "GetReturnType", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(mi)})));
return ::il2cpp_utils::RunMethodRethrow<::System::Type*, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, mi);
}
// Autogenerated method: System.Dynamic.Utils.TypeExtensions.GetTypeCode
::System::TypeCode System::Dynamic::Utils::TypeExtensions::GetTypeCode(::System::Type* type) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::TypeExtensions::GetTypeCode");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "TypeExtensions", "GetTypeCode", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(type)})));
return ::il2cpp_utils::RunMethodRethrow<::System::TypeCode, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, type);
}
// Autogenerated method: System.Dynamic.Utils.TypeExtensions.GetParametersCached
::ArrayW<::System::Reflection::ParameterInfo*> System::Dynamic::Utils::TypeExtensions::GetParametersCached(::System::Reflection::MethodBase* method) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::TypeExtensions::GetParametersCached");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "TypeExtensions", "GetParametersCached", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(method)})));
return ::il2cpp_utils::RunMethodRethrow<::ArrayW<::System::Reflection::ParameterInfo*>, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, method);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
// Including type: System.Dynamic.Utils.TypeUtils
#include "System/Dynamic/Utils/TypeUtils.hpp"
// Including type: System.Reflection.Assembly
#include "System/Reflection/Assembly.hpp"
// Including type: System.Type
#include "System/Type.hpp"
// Including type: System.Reflection.MemberInfo
#include "System/Reflection/MemberInfo.hpp"
// Including type: System.Reflection.MethodInfo
#include "System/Reflection/MethodInfo.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated static field getter
// Get static field: static private System.Reflection.Assembly s_mscorlib
::System::Reflection::Assembly* System::Dynamic::Utils::TypeUtils::_get_s_mscorlib() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::TypeUtils::_get_s_mscorlib");
return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Reflection::Assembly*>("System.Dynamic.Utils", "TypeUtils", "s_mscorlib"));
}
// Autogenerated static field setter
// Set static field: static private System.Reflection.Assembly s_mscorlib
void System::Dynamic::Utils::TypeUtils::_set_s_mscorlib(::System::Reflection::Assembly* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::TypeUtils::_set_s_mscorlib");
THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Dynamic.Utils", "TypeUtils", "s_mscorlib", value));
}
// Autogenerated method: System.Dynamic.Utils.TypeUtils.get_MsCorLib
::System::Reflection::Assembly* System::Dynamic::Utils::TypeUtils::get_MsCorLib() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::TypeUtils::get_MsCorLib");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "TypeUtils", "get_MsCorLib", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<::System::Reflection::Assembly*, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method);
}
// Autogenerated method: System.Dynamic.Utils.TypeUtils.GetNonNullableType
::System::Type* System::Dynamic::Utils::TypeUtils::GetNonNullableType(::System::Type* type) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::TypeUtils::GetNonNullableType");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "TypeUtils", "GetNonNullableType", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(type)})));
return ::il2cpp_utils::RunMethodRethrow<::System::Type*, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, type);
}
// Autogenerated method: System.Dynamic.Utils.TypeUtils.GetNullableType
::System::Type* System::Dynamic::Utils::TypeUtils::GetNullableType(::System::Type* type) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::TypeUtils::GetNullableType");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "TypeUtils", "GetNullableType", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(type)})));
return ::il2cpp_utils::RunMethodRethrow<::System::Type*, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, type);
}
// Autogenerated method: System.Dynamic.Utils.TypeUtils.IsNullableType
bool System::Dynamic::Utils::TypeUtils::IsNullableType(::System::Type* type) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::TypeUtils::IsNullableType");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "TypeUtils", "IsNullableType", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(type)})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, type);
}
// Autogenerated method: System.Dynamic.Utils.TypeUtils.IsNullableOrReferenceType
bool System::Dynamic::Utils::TypeUtils::IsNullableOrReferenceType(::System::Type* type) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::TypeUtils::IsNullableOrReferenceType");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "TypeUtils", "IsNullableOrReferenceType", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(type)})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, type);
}
// Autogenerated method: System.Dynamic.Utils.TypeUtils.IsBool
bool System::Dynamic::Utils::TypeUtils::IsBool(::System::Type* type) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::TypeUtils::IsBool");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "TypeUtils", "IsBool", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(type)})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, type);
}
// Autogenerated method: System.Dynamic.Utils.TypeUtils.IsNumeric
bool System::Dynamic::Utils::TypeUtils::IsNumeric(::System::Type* type) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::TypeUtils::IsNumeric");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "TypeUtils", "IsNumeric", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(type)})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, type);
}
// Autogenerated method: System.Dynamic.Utils.TypeUtils.IsInteger
bool System::Dynamic::Utils::TypeUtils::IsInteger(::System::Type* type) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::TypeUtils::IsInteger");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "TypeUtils", "IsInteger", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(type)})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, type);
}
// Autogenerated method: System.Dynamic.Utils.TypeUtils.IsArithmetic
bool System::Dynamic::Utils::TypeUtils::IsArithmetic(::System::Type* type) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::TypeUtils::IsArithmetic");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "TypeUtils", "IsArithmetic", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(type)})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, type);
}
// Autogenerated method: System.Dynamic.Utils.TypeUtils.IsUnsignedInt
bool System::Dynamic::Utils::TypeUtils::IsUnsignedInt(::System::Type* type) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::TypeUtils::IsUnsignedInt");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "TypeUtils", "IsUnsignedInt", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(type)})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, type);
}
// Autogenerated method: System.Dynamic.Utils.TypeUtils.IsIntegerOrBool
bool System::Dynamic::Utils::TypeUtils::IsIntegerOrBool(::System::Type* type) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::TypeUtils::IsIntegerOrBool");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "TypeUtils", "IsIntegerOrBool", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(type)})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, type);
}
// Autogenerated method: System.Dynamic.Utils.TypeUtils.IsNumericOrBool
bool System::Dynamic::Utils::TypeUtils::IsNumericOrBool(::System::Type* type) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::TypeUtils::IsNumericOrBool");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "TypeUtils", "IsNumericOrBool", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(type)})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, type);
}
// Autogenerated method: System.Dynamic.Utils.TypeUtils.IsValidInstanceType
bool System::Dynamic::Utils::TypeUtils::IsValidInstanceType(::System::Reflection::MemberInfo* member, ::System::Type* instanceType) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::TypeUtils::IsValidInstanceType");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "TypeUtils", "IsValidInstanceType", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(member), ::il2cpp_utils::ExtractType(instanceType)})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, member, instanceType);
}
// Autogenerated method: System.Dynamic.Utils.TypeUtils.HasIdentityPrimitiveOrNullableConversionTo
bool System::Dynamic::Utils::TypeUtils::HasIdentityPrimitiveOrNullableConversionTo(::System::Type* source, ::System::Type* dest) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::TypeUtils::HasIdentityPrimitiveOrNullableConversionTo");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "TypeUtils", "HasIdentityPrimitiveOrNullableConversionTo", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(source), ::il2cpp_utils::ExtractType(dest)})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, source, dest);
}
// Autogenerated method: System.Dynamic.Utils.TypeUtils.HasReferenceConversionTo
bool System::Dynamic::Utils::TypeUtils::HasReferenceConversionTo(::System::Type* source, ::System::Type* dest) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::TypeUtils::HasReferenceConversionTo");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "TypeUtils", "HasReferenceConversionTo", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(source), ::il2cpp_utils::ExtractType(dest)})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, source, dest);
}
// Autogenerated method: System.Dynamic.Utils.TypeUtils.IsCovariant
bool System::Dynamic::Utils::TypeUtils::IsCovariant(::System::Type* t) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::TypeUtils::IsCovariant");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "TypeUtils", "IsCovariant", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(t)})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, t);
}
// Autogenerated method: System.Dynamic.Utils.TypeUtils.IsContravariant
bool System::Dynamic::Utils::TypeUtils::IsContravariant(::System::Type* t) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::TypeUtils::IsContravariant");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "TypeUtils", "IsContravariant", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(t)})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, t);
}
// Autogenerated method: System.Dynamic.Utils.TypeUtils.IsInvariant
bool System::Dynamic::Utils::TypeUtils::IsInvariant(::System::Type* t) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::TypeUtils::IsInvariant");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "TypeUtils", "IsInvariant", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(t)})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, t);
}
// Autogenerated method: System.Dynamic.Utils.TypeUtils.IsDelegate
bool System::Dynamic::Utils::TypeUtils::IsDelegate(::System::Type* t) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::TypeUtils::IsDelegate");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "TypeUtils", "IsDelegate", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(t)})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, t);
}
// Autogenerated method: System.Dynamic.Utils.TypeUtils.IsLegalExplicitVariantDelegateConversion
bool System::Dynamic::Utils::TypeUtils::IsLegalExplicitVariantDelegateConversion(::System::Type* source, ::System::Type* dest) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::TypeUtils::IsLegalExplicitVariantDelegateConversion");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "TypeUtils", "IsLegalExplicitVariantDelegateConversion", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(source), ::il2cpp_utils::ExtractType(dest)})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, source, dest);
}
// Autogenerated method: System.Dynamic.Utils.TypeUtils.IsConvertible
bool System::Dynamic::Utils::TypeUtils::IsConvertible(::System::Type* type) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::TypeUtils::IsConvertible");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "TypeUtils", "IsConvertible", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(type)})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, type);
}
// Autogenerated method: System.Dynamic.Utils.TypeUtils.HasReferenceEquality
bool System::Dynamic::Utils::TypeUtils::HasReferenceEquality(::System::Type* left, ::System::Type* right) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::TypeUtils::HasReferenceEquality");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "TypeUtils", "HasReferenceEquality", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(left), ::il2cpp_utils::ExtractType(right)})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, left, right);
}
// Autogenerated method: System.Dynamic.Utils.TypeUtils.HasBuiltInEqualityOperator
bool System::Dynamic::Utils::TypeUtils::HasBuiltInEqualityOperator(::System::Type* left, ::System::Type* right) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::TypeUtils::HasBuiltInEqualityOperator");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "TypeUtils", "HasBuiltInEqualityOperator", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(left), ::il2cpp_utils::ExtractType(right)})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, left, right);
}
// Autogenerated method: System.Dynamic.Utils.TypeUtils.IsImplicitlyConvertibleTo
bool System::Dynamic::Utils::TypeUtils::IsImplicitlyConvertibleTo(::System::Type* source, ::System::Type* destination) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::TypeUtils::IsImplicitlyConvertibleTo");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "TypeUtils", "IsImplicitlyConvertibleTo", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(source), ::il2cpp_utils::ExtractType(destination)})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, source, destination);
}
// Autogenerated method: System.Dynamic.Utils.TypeUtils.GetUserDefinedCoercionMethod
::System::Reflection::MethodInfo* System::Dynamic::Utils::TypeUtils::GetUserDefinedCoercionMethod(::System::Type* convertFrom, ::System::Type* convertToType) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::TypeUtils::GetUserDefinedCoercionMethod");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "TypeUtils", "GetUserDefinedCoercionMethod", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(convertFrom), ::il2cpp_utils::ExtractType(convertToType)})));
return ::il2cpp_utils::RunMethodRethrow<::System::Reflection::MethodInfo*, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, convertFrom, convertToType);
}
// Autogenerated method: System.Dynamic.Utils.TypeUtils.FindConversionOperator
::System::Reflection::MethodInfo* System::Dynamic::Utils::TypeUtils::FindConversionOperator(::ArrayW<::System::Reflection::MethodInfo*> methods, ::System::Type* typeFrom, ::System::Type* typeTo) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::TypeUtils::FindConversionOperator");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "TypeUtils", "FindConversionOperator", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(methods), ::il2cpp_utils::ExtractType(typeFrom), ::il2cpp_utils::ExtractType(typeTo)})));
return ::il2cpp_utils::RunMethodRethrow<::System::Reflection::MethodInfo*, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, methods, typeFrom, typeTo);
}
// Autogenerated method: System.Dynamic.Utils.TypeUtils.IsImplicitNumericConversion
bool System::Dynamic::Utils::TypeUtils::IsImplicitNumericConversion(::System::Type* source, ::System::Type* destination) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::TypeUtils::IsImplicitNumericConversion");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "TypeUtils", "IsImplicitNumericConversion", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(source), ::il2cpp_utils::ExtractType(destination)})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, source, destination);
}
// Autogenerated method: System.Dynamic.Utils.TypeUtils.IsImplicitReferenceConversion
bool System::Dynamic::Utils::TypeUtils::IsImplicitReferenceConversion(::System::Type* source, ::System::Type* destination) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::TypeUtils::IsImplicitReferenceConversion");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "TypeUtils", "IsImplicitReferenceConversion", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(source), ::il2cpp_utils::ExtractType(destination)})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, source, destination);
}
// Autogenerated method: System.Dynamic.Utils.TypeUtils.IsImplicitBoxingConversion
bool System::Dynamic::Utils::TypeUtils::IsImplicitBoxingConversion(::System::Type* source, ::System::Type* destination) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::TypeUtils::IsImplicitBoxingConversion");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "TypeUtils", "IsImplicitBoxingConversion", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(source), ::il2cpp_utils::ExtractType(destination)})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, source, destination);
}
// Autogenerated method: System.Dynamic.Utils.TypeUtils.IsImplicitNullableConversion
bool System::Dynamic::Utils::TypeUtils::IsImplicitNullableConversion(::System::Type* source, ::System::Type* destination) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::TypeUtils::IsImplicitNullableConversion");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "TypeUtils", "IsImplicitNullableConversion", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(source), ::il2cpp_utils::ExtractType(destination)})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, source, destination);
}
// Autogenerated method: System.Dynamic.Utils.TypeUtils.FindGenericType
::System::Type* System::Dynamic::Utils::TypeUtils::FindGenericType(::System::Type* definition, ::System::Type* type) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::TypeUtils::FindGenericType");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "TypeUtils", "FindGenericType", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(definition), ::il2cpp_utils::ExtractType(type)})));
return ::il2cpp_utils::RunMethodRethrow<::System::Type*, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, definition, type);
}
// Autogenerated method: System.Dynamic.Utils.TypeUtils.GetBooleanOperator
::System::Reflection::MethodInfo* System::Dynamic::Utils::TypeUtils::GetBooleanOperator(::System::Type* type, ::StringW name) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::TypeUtils::GetBooleanOperator");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "TypeUtils", "GetBooleanOperator", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(type), ::il2cpp_utils::ExtractType(name)})));
return ::il2cpp_utils::RunMethodRethrow<::System::Reflection::MethodInfo*, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, type, name);
}
// Autogenerated method: System.Dynamic.Utils.TypeUtils.GetNonRefType
::System::Type* System::Dynamic::Utils::TypeUtils::GetNonRefType(::System::Type* type) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::TypeUtils::GetNonRefType");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "TypeUtils", "GetNonRefType", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(type)})));
return ::il2cpp_utils::RunMethodRethrow<::System::Type*, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, type);
}
// Autogenerated method: System.Dynamic.Utils.TypeUtils.AreEquivalent
bool System::Dynamic::Utils::TypeUtils::AreEquivalent(::System::Type* t1, ::System::Type* t2) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::TypeUtils::AreEquivalent");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "TypeUtils", "AreEquivalent", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(t1), ::il2cpp_utils::ExtractType(t2)})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, t1, t2);
}
// Autogenerated method: System.Dynamic.Utils.TypeUtils.AreReferenceAssignable
bool System::Dynamic::Utils::TypeUtils::AreReferenceAssignable(::System::Type* dest, ::System::Type* src) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::TypeUtils::AreReferenceAssignable");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "TypeUtils", "AreReferenceAssignable", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(dest), ::il2cpp_utils::ExtractType(src)})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, dest, src);
}
// Autogenerated method: System.Dynamic.Utils.TypeUtils.IsSameOrSubclass
bool System::Dynamic::Utils::TypeUtils::IsSameOrSubclass(::System::Type* type, ::System::Type* subType) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::TypeUtils::IsSameOrSubclass");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "TypeUtils", "IsSameOrSubclass", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(type), ::il2cpp_utils::ExtractType(subType)})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, type, subType);
}
// Autogenerated method: System.Dynamic.Utils.TypeUtils.ValidateType
void System::Dynamic::Utils::TypeUtils::ValidateType(::System::Type* type, ::StringW paramName) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::TypeUtils::ValidateType");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "TypeUtils", "ValidateType", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(type), ::il2cpp_utils::ExtractType(paramName)})));
::il2cpp_utils::RunMethodRethrow<void, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, type, paramName);
}
// Autogenerated method: System.Dynamic.Utils.TypeUtils.ValidateType
void System::Dynamic::Utils::TypeUtils::ValidateType(::System::Type* type, ::StringW paramName, bool allowByRef, bool allowPointer) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::TypeUtils::ValidateType");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "TypeUtils", "ValidateType", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(type), ::il2cpp_utils::ExtractType(paramName), ::il2cpp_utils::ExtractType(allowByRef), ::il2cpp_utils::ExtractType(allowPointer)})));
::il2cpp_utils::RunMethodRethrow<void, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, type, paramName, allowByRef, allowPointer);
}
// Autogenerated method: System.Dynamic.Utils.TypeUtils.ValidateType
bool System::Dynamic::Utils::TypeUtils::ValidateType(::System::Type* type, ::StringW paramName, int index) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::TypeUtils::ValidateType");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "TypeUtils", "ValidateType", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(type), ::il2cpp_utils::ExtractType(paramName), ::il2cpp_utils::ExtractType(index)})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, type, paramName, index);
}
// Autogenerated method: System.Dynamic.Utils.TypeUtils.CanCache
bool System::Dynamic::Utils::TypeUtils::CanCache(::System::Type* t) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::TypeUtils::CanCache");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "TypeUtils", "CanCache", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(t)})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, t);
}
// Autogenerated method: System.Dynamic.Utils.TypeUtils.GetInvokeMethod
::System::Reflection::MethodInfo* System::Dynamic::Utils::TypeUtils::GetInvokeMethod(::System::Type* delegateType) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Dynamic::Utils::TypeUtils::GetInvokeMethod");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Dynamic.Utils", "TypeUtils", "GetInvokeMethod", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(delegateType)})));
return ::il2cpp_utils::RunMethodRethrow<::System::Reflection::MethodInfo*, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, delegateType);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
// Including type: System.Collections.Generic.EnumerableHelpers
#include "System/Collections/Generic/EnumerableHelpers.hpp"
// Including type: System.Collections.Generic.IEnumerable`1
#include "System/Collections/Generic/IEnumerable_1.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
// Including type: SR
#include "GlobalNamespace/SR__.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated method: SR.GetString
::StringW GlobalNamespace::SR__::GetString(::StringW name) {
static auto ___internal__logger = ::Logger::get().WithContext("::GlobalNamespace::SR__::GetString");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("", "SR", "GetString", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(name)})));
return ::il2cpp_utils::RunMethodRethrow<::StringW, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, name);
}
// Autogenerated method: SR.Format
::StringW GlobalNamespace::SR__::Format(::StringW resourceFormat, ::Il2CppObject* p1) {
static auto ___internal__logger = ::Logger::get().WithContext("::GlobalNamespace::SR__::Format");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("", "SR", "Format", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(resourceFormat), ::il2cpp_utils::ExtractType(p1)})));
return ::il2cpp_utils::RunMethodRethrow<::StringW, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, resourceFormat, p1);
}
// Autogenerated method: SR.Format
::StringW GlobalNamespace::SR__::Format(::StringW resourceFormat, ::Il2CppObject* p1, ::Il2CppObject* p2) {
static auto ___internal__logger = ::Logger::get().WithContext("::GlobalNamespace::SR__::Format");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("", "SR", "Format", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(resourceFormat), ::il2cpp_utils::ExtractType(p1), ::il2cpp_utils::ExtractType(p2)})));
return ::il2cpp_utils::RunMethodRethrow<::StringW, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, resourceFormat, p1, p2);
}
// Autogenerated method: SR.Format
::StringW GlobalNamespace::SR__::Format(::StringW resourceFormat, ::Il2CppObject* p1, ::Il2CppObject* p2, ::Il2CppObject* p3) {
static auto ___internal__logger = ::Logger::get().WithContext("::GlobalNamespace::SR__::Format");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("", "SR", "Format", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(resourceFormat), ::il2cpp_utils::ExtractType(p1), ::il2cpp_utils::ExtractType(p2), ::il2cpp_utils::ExtractType(p3)})));
return ::il2cpp_utils::RunMethodRethrow<::StringW, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, resourceFormat, p1, p2, p3);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
// Including type: System.Data.AcceptRejectRule
#include "System/Data/AcceptRejectRule.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated static field getter
// Get static field: static public System.Data.AcceptRejectRule None
::System::Data::AcceptRejectRule System::Data::AcceptRejectRule::_get_None() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AcceptRejectRule::_get_None");
return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Data::AcceptRejectRule>("System.Data", "AcceptRejectRule", "None"));
}
// Autogenerated static field setter
// Set static field: static public System.Data.AcceptRejectRule None
void System::Data::AcceptRejectRule::_set_None(::System::Data::AcceptRejectRule value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AcceptRejectRule::_set_None");
THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Data", "AcceptRejectRule", "None", value));
}
// Autogenerated static field getter
// Get static field: static public System.Data.AcceptRejectRule Cascade
::System::Data::AcceptRejectRule System::Data::AcceptRejectRule::_get_Cascade() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AcceptRejectRule::_get_Cascade");
return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Data::AcceptRejectRule>("System.Data", "AcceptRejectRule", "Cascade"));
}
// Autogenerated static field setter
// Set static field: static public System.Data.AcceptRejectRule Cascade
void System::Data::AcceptRejectRule::_set_Cascade(::System::Data::AcceptRejectRule value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AcceptRejectRule::_set_Cascade");
THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Data", "AcceptRejectRule", "Cascade", value));
}
// Autogenerated instance field getter
// Get instance field: public System.Int32 value__
[[deprecated("Use field access instead!")]] int& System::Data::AcceptRejectRule::dyn_value__() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AcceptRejectRule::dyn_value__");
auto ___internal__instance = *this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "value__"))->offset;
return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
// Including type: System.Data.AggregateType
#include "System/Data/AggregateType.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated static field getter
// Get static field: static public System.Data.AggregateType None
::System::Data::AggregateType System::Data::AggregateType::_get_None() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AggregateType::_get_None");
return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Data::AggregateType>("System.Data", "AggregateType", "None"));
}
// Autogenerated static field setter
// Set static field: static public System.Data.AggregateType None
void System::Data::AggregateType::_set_None(::System::Data::AggregateType value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AggregateType::_set_None");
THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Data", "AggregateType", "None", value));
}
// Autogenerated static field getter
// Get static field: static public System.Data.AggregateType Sum
::System::Data::AggregateType System::Data::AggregateType::_get_Sum() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AggregateType::_get_Sum");
return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Data::AggregateType>("System.Data", "AggregateType", "Sum"));
}
// Autogenerated static field setter
// Set static field: static public System.Data.AggregateType Sum
void System::Data::AggregateType::_set_Sum(::System::Data::AggregateType value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AggregateType::_set_Sum");
THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Data", "AggregateType", "Sum", value));
}
// Autogenerated static field getter
// Get static field: static public System.Data.AggregateType Mean
::System::Data::AggregateType System::Data::AggregateType::_get_Mean() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AggregateType::_get_Mean");
return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Data::AggregateType>("System.Data", "AggregateType", "Mean"));
}
// Autogenerated static field setter
// Set static field: static public System.Data.AggregateType Mean
void System::Data::AggregateType::_set_Mean(::System::Data::AggregateType value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AggregateType::_set_Mean");
THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Data", "AggregateType", "Mean", value));
}
// Autogenerated static field getter
// Get static field: static public System.Data.AggregateType Min
::System::Data::AggregateType System::Data::AggregateType::_get_Min() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AggregateType::_get_Min");
return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Data::AggregateType>("System.Data", "AggregateType", "Min"));
}
// Autogenerated static field setter
// Set static field: static public System.Data.AggregateType Min
void System::Data::AggregateType::_set_Min(::System::Data::AggregateType value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AggregateType::_set_Min");
THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Data", "AggregateType", "Min", value));
}
// Autogenerated static field getter
// Get static field: static public System.Data.AggregateType Max
::System::Data::AggregateType System::Data::AggregateType::_get_Max() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AggregateType::_get_Max");
return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Data::AggregateType>("System.Data", "AggregateType", "Max"));
}
// Autogenerated static field setter
// Set static field: static public System.Data.AggregateType Max
void System::Data::AggregateType::_set_Max(::System::Data::AggregateType value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AggregateType::_set_Max");
THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Data", "AggregateType", "Max", value));
}
// Autogenerated static field getter
// Get static field: static public System.Data.AggregateType First
::System::Data::AggregateType System::Data::AggregateType::_get_First() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AggregateType::_get_First");
return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Data::AggregateType>("System.Data", "AggregateType", "First"));
}
// Autogenerated static field setter
// Set static field: static public System.Data.AggregateType First
void System::Data::AggregateType::_set_First(::System::Data::AggregateType value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AggregateType::_set_First");
THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Data", "AggregateType", "First", value));
}
// Autogenerated static field getter
// Get static field: static public System.Data.AggregateType Count
::System::Data::AggregateType System::Data::AggregateType::_get_Count() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AggregateType::_get_Count");
return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Data::AggregateType>("System.Data", "AggregateType", "Count"));
}
// Autogenerated static field setter
// Set static field: static public System.Data.AggregateType Count
void System::Data::AggregateType::_set_Count(::System::Data::AggregateType value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AggregateType::_set_Count");
THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Data", "AggregateType", "Count", value));
}
// Autogenerated static field getter
// Get static field: static public System.Data.AggregateType Var
::System::Data::AggregateType System::Data::AggregateType::_get_Var() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AggregateType::_get_Var");
return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Data::AggregateType>("System.Data", "AggregateType", "Var"));
}
// Autogenerated static field setter
// Set static field: static public System.Data.AggregateType Var
void System::Data::AggregateType::_set_Var(::System::Data::AggregateType value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AggregateType::_set_Var");
THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Data", "AggregateType", "Var", value));
}
// Autogenerated static field getter
// Get static field: static public System.Data.AggregateType StDev
::System::Data::AggregateType System::Data::AggregateType::_get_StDev() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AggregateType::_get_StDev");
return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Data::AggregateType>("System.Data", "AggregateType", "StDev"));
}
// Autogenerated static field setter
// Set static field: static public System.Data.AggregateType StDev
void System::Data::AggregateType::_set_StDev(::System::Data::AggregateType value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AggregateType::_set_StDev");
THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Data", "AggregateType", "StDev", value));
}
// Autogenerated instance field getter
// Get instance field: public System.Int32 value__
[[deprecated("Use field access instead!")]] int& System::Data::AggregateType::dyn_value__() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AggregateType::dyn_value__");
auto ___internal__instance = *this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "value__"))->offset;
return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
// Including type: System.Data.InternalDataCollectionBase
#include "System/Data/InternalDataCollectionBase.hpp"
// Including type: System.ComponentModel.CollectionChangeEventArgs
#include "System/ComponentModel/CollectionChangeEventArgs.hpp"
// Including type: System.Collections.ArrayList
#include "System/Collections/ArrayList.hpp"
// Including type: System.Array
#include "System/Array.hpp"
// Including type: System.Collections.IEnumerator
#include "System/Collections/IEnumerator.hpp"
// Including type: System.Globalization.CultureInfo
#include "System/Globalization/CultureInfo.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated static field getter
// Get static field: static readonly System.ComponentModel.CollectionChangeEventArgs s_refreshEventArgs
::System::ComponentModel::CollectionChangeEventArgs* System::Data::InternalDataCollectionBase::_get_s_refreshEventArgs() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::InternalDataCollectionBase::_get_s_refreshEventArgs");
return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::ComponentModel::CollectionChangeEventArgs*>("System.Data", "InternalDataCollectionBase", "s_refreshEventArgs"));
}
// Autogenerated static field setter
// Set static field: static readonly System.ComponentModel.CollectionChangeEventArgs s_refreshEventArgs
void System::Data::InternalDataCollectionBase::_set_s_refreshEventArgs(::System::ComponentModel::CollectionChangeEventArgs* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::InternalDataCollectionBase::_set_s_refreshEventArgs");
THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Data", "InternalDataCollectionBase", "s_refreshEventArgs", value));
}
// Autogenerated method: System.Data.InternalDataCollectionBase.get_Count
int System::Data::InternalDataCollectionBase::get_Count() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::InternalDataCollectionBase::get_Count");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::InternalDataCollectionBase*), 8));
return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.InternalDataCollectionBase.get_SyncRoot
::Il2CppObject* System::Data::InternalDataCollectionBase::get_SyncRoot() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::InternalDataCollectionBase::get_SyncRoot");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::InternalDataCollectionBase*), 6));
return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.InternalDataCollectionBase.get_List
::System::Collections::ArrayList* System::Data::InternalDataCollectionBase::get_List() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::InternalDataCollectionBase::get_List");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::InternalDataCollectionBase*), 11));
return ::il2cpp_utils::RunMethodRethrow<::System::Collections::ArrayList*, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.InternalDataCollectionBase..cctor
void System::Data::InternalDataCollectionBase::_cctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::InternalDataCollectionBase::.cctor");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Data", "InternalDataCollectionBase", ".cctor", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
::il2cpp_utils::RunMethodRethrow<void, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method);
}
// Autogenerated method: System.Data.InternalDataCollectionBase.CopyTo
void System::Data::InternalDataCollectionBase::CopyTo(::System::Array* ar, int index) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::InternalDataCollectionBase::CopyTo");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::InternalDataCollectionBase*), 9));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, ar, index);
}
// Autogenerated method: System.Data.InternalDataCollectionBase.GetEnumerator
::System::Collections::IEnumerator* System::Data::InternalDataCollectionBase::GetEnumerator() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::InternalDataCollectionBase::GetEnumerator");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::InternalDataCollectionBase*), 10));
return ::il2cpp_utils::RunMethodRethrow<::System::Collections::IEnumerator*, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.InternalDataCollectionBase.NamesEqual
int System::Data::InternalDataCollectionBase::NamesEqual(::StringW s1, ::StringW s2, bool fCaseSensitive, ::System::Globalization::CultureInfo* locale) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::InternalDataCollectionBase::NamesEqual");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "NamesEqual", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(s1), ::il2cpp_utils::ExtractType(s2), ::il2cpp_utils::ExtractType(fCaseSensitive), ::il2cpp_utils::ExtractType(locale)})));
return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method, s1, s2, fCaseSensitive, locale);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
// Including type: System.Data.ColumnTypeConverter
#include "System/Data/ColumnTypeConverter.hpp"
// Including type: System.Type
#include "System/Type.hpp"
// Including type: System.ComponentModel.ITypeDescriptorContext
#include "System/ComponentModel/ITypeDescriptorContext.hpp"
// Including type: System.Globalization.CultureInfo
#include "System/Globalization/CultureInfo.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated static field getter
// Get static field: static private readonly System.Type[] s_types
::ArrayW<::System::Type*> System::Data::ColumnTypeConverter::_get_s_types() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ColumnTypeConverter::_get_s_types");
return THROW_UNLESS(il2cpp_utils::GetFieldValue<::ArrayW<::System::Type*>>("System.Data", "ColumnTypeConverter", "s_types"));
}
// Autogenerated static field setter
// Set static field: static private readonly System.Type[] s_types
void System::Data::ColumnTypeConverter::_set_s_types(::ArrayW<::System::Type*> value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ColumnTypeConverter::_set_s_types");
THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Data", "ColumnTypeConverter", "s_types", value));
}
// Autogenerated method: System.Data.ColumnTypeConverter..cctor
void System::Data::ColumnTypeConverter::_cctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ColumnTypeConverter::.cctor");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Data", "ColumnTypeConverter", ".cctor", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
::il2cpp_utils::RunMethodRethrow<void, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method);
}
// Autogenerated method: System.Data.ColumnTypeConverter.CanConvertTo
bool System::Data::ColumnTypeConverter::CanConvertTo(::System::ComponentModel::ITypeDescriptorContext* context, ::System::Type* destinationType) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ColumnTypeConverter::CanConvertTo");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::ComponentModel::TypeConverter*), 5));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, context, destinationType);
}
// Autogenerated method: System.Data.ColumnTypeConverter.ConvertTo
::Il2CppObject* System::Data::ColumnTypeConverter::ConvertTo(::System::ComponentModel::ITypeDescriptorContext* context, ::System::Globalization::CultureInfo* culture, ::Il2CppObject* value, ::System::Type* destinationType) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ColumnTypeConverter::ConvertTo");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::ComponentModel::TypeConverter*), 7));
return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method, context, culture, value, destinationType);
}
// Autogenerated method: System.Data.ColumnTypeConverter.CanConvertFrom
bool System::Data::ColumnTypeConverter::CanConvertFrom(::System::ComponentModel::ITypeDescriptorContext* context, ::System::Type* sourceType) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ColumnTypeConverter::CanConvertFrom");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::ComponentModel::TypeConverter*), 4));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, context, sourceType);
}
// Autogenerated method: System.Data.ColumnTypeConverter.ConvertFrom
::Il2CppObject* System::Data::ColumnTypeConverter::ConvertFrom(::System::ComponentModel::ITypeDescriptorContext* context, ::System::Globalization::CultureInfo* culture, ::Il2CppObject* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ColumnTypeConverter::ConvertFrom");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::ComponentModel::TypeConverter*), 6));
return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method, context, culture, value);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
// Including type: System.Data.DataCommonEventSource
#include "System/Data/DataCommonEventSource.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated static field getter
// Get static field: static readonly System.Data.DataCommonEventSource Log
::System::Data::DataCommonEventSource* System::Data::DataCommonEventSource::_get_Log() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataCommonEventSource::_get_Log");
return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Data::DataCommonEventSource*>("System.Data", "DataCommonEventSource", "Log"));
}
// Autogenerated static field setter
// Set static field: static readonly System.Data.DataCommonEventSource Log
void System::Data::DataCommonEventSource::_set_Log(::System::Data::DataCommonEventSource* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataCommonEventSource::_set_Log");
THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Data", "DataCommonEventSource", "Log", value));
}
// Autogenerated static field getter
// Get static field: static private System.Int64 s_nextScopeId
int64_t System::Data::DataCommonEventSource::_get_s_nextScopeId() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataCommonEventSource::_get_s_nextScopeId");
return THROW_UNLESS(il2cpp_utils::GetFieldValue<int64_t>("System.Data", "DataCommonEventSource", "s_nextScopeId"));
}
// Autogenerated static field setter
// Set static field: static private System.Int64 s_nextScopeId
void System::Data::DataCommonEventSource::_set_s_nextScopeId(int64_t value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataCommonEventSource::_set_s_nextScopeId");
THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Data", "DataCommonEventSource", "s_nextScopeId", value));
}
// Autogenerated method: System.Data.DataCommonEventSource..cctor
void System::Data::DataCommonEventSource::_cctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataCommonEventSource::.cctor");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Data", "DataCommonEventSource", ".cctor", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
::il2cpp_utils::RunMethodRethrow<void, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method);
}
// Autogenerated method: System.Data.DataCommonEventSource.Trace
void System::Data::DataCommonEventSource::Trace(::StringW message) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataCommonEventSource::Trace");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Trace", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(message)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, message);
}
// Autogenerated method: System.Data.DataCommonEventSource.EnterScope
int64_t System::Data::DataCommonEventSource::EnterScope(::StringW message) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataCommonEventSource::EnterScope");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "EnterScope", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(message)})));
return ::il2cpp_utils::RunMethodRethrow<int64_t, false>(this, ___internal__method, message);
}
// Autogenerated method: System.Data.DataCommonEventSource.ExitScope
void System::Data::DataCommonEventSource::ExitScope(int64_t scopeId) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataCommonEventSource::ExitScope");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "ExitScope", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(scopeId)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, scopeId);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
// Including type: System.Data.Constraint
#include "System/Data/Constraint.hpp"
// Including type: System.Data.DataSet
#include "System/Data/DataSet.hpp"
// Including type: System.Data.PropertyCollection
#include "System/Data/PropertyCollection.hpp"
// Including type: System.Data.DataTable
#include "System/Data/DataTable.hpp"
// Including type: System.Data.DataColumn
#include "System/Data/DataColumn.hpp"
// Including type: System.Data.ConstraintCollection
#include "System/Data/ConstraintCollection.hpp"
// Including type: System.Data.DataRow
#include "System/Data/DataRow.hpp"
// Including type: System.Data.DataRowAction
#include "System/Data/DataRowAction.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated instance field getter
// Get instance field: private System.String _schemaName
[[deprecated("Use field access instead!")]] ::StringW& System::Data::Constraint::dyn__schemaName() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::Constraint::dyn__schemaName");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_schemaName"))->offset;
return *reinterpret_cast<::StringW*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.Boolean _inCollection
[[deprecated("Use field access instead!")]] bool& System::Data::Constraint::dyn__inCollection() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::Constraint::dyn__inCollection");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_inCollection"))->offset;
return *reinterpret_cast<bool*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.Data.DataSet _dataSet
[[deprecated("Use field access instead!")]] ::System::Data::DataSet*& System::Data::Constraint::dyn__dataSet() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::Constraint::dyn__dataSet");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_dataSet"))->offset;
return *reinterpret_cast<::System::Data::DataSet**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: System.String _name
[[deprecated("Use field access instead!")]] ::StringW& System::Data::Constraint::dyn__name() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::Constraint::dyn__name");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_name"))->offset;
return *reinterpret_cast<::StringW*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: System.Data.PropertyCollection _extendedProperties
[[deprecated("Use field access instead!")]] ::System::Data::PropertyCollection*& System::Data::Constraint::dyn__extendedProperties() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::Constraint::dyn__extendedProperties");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_extendedProperties"))->offset;
return *reinterpret_cast<::System::Data::PropertyCollection**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated method: System.Data.Constraint.get_ConstraintName
::StringW System::Data::Constraint::get_ConstraintName() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::Constraint::get_ConstraintName");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::Constraint*), 4));
return ::il2cpp_utils::RunMethodRethrow<::StringW, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.Constraint.set_ConstraintName
void System::Data::Constraint::set_ConstraintName(::StringW value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::Constraint::set_ConstraintName");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::Constraint*), 5));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value);
}
// Autogenerated method: System.Data.Constraint.get_SchemaName
::StringW System::Data::Constraint::get_SchemaName() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::Constraint::get_SchemaName");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_SchemaName", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<::StringW, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.Constraint.set_SchemaName
void System::Data::Constraint::set_SchemaName(::StringW value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::Constraint::set_SchemaName");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_SchemaName", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value);
}
// Autogenerated method: System.Data.Constraint.get_InCollection
bool System::Data::Constraint::get_InCollection() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::Constraint::get_InCollection");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::Constraint*), 6));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.Constraint.set_InCollection
void System::Data::Constraint::set_InCollection(bool value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::Constraint::set_InCollection");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::Constraint*), 7));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value);
}
// Autogenerated method: System.Data.Constraint.get_Table
::System::Data::DataTable* System::Data::Constraint::get_Table() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::Constraint::get_Table");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::Constraint*), -1));
return ::il2cpp_utils::RunMethodRethrow<::System::Data::DataTable*, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.Constraint.get_ExtendedProperties
::System::Data::PropertyCollection* System::Data::Constraint::get_ExtendedProperties() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::Constraint::get_ExtendedProperties");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_ExtendedProperties", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<::System::Data::PropertyCollection*, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.Constraint.get__DataSet
::System::Data::DataSet* System::Data::Constraint::get__DataSet() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::Constraint::get__DataSet");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::Constraint*), 17));
return ::il2cpp_utils::RunMethodRethrow<::System::Data::DataSet*, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.Constraint.ContainsColumn
bool System::Data::Constraint::ContainsColumn(::System::Data::DataColumn* column) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::Constraint::ContainsColumn");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::Constraint*), -1));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, column);
}
// Autogenerated method: System.Data.Constraint.CanEnableConstraint
bool System::Data::Constraint::CanEnableConstraint() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::Constraint::CanEnableConstraint");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::Constraint*), -1));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.Constraint.Clone
::System::Data::Constraint* System::Data::Constraint::Clone(::System::Data::DataSet* destination) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::Constraint::Clone");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::Constraint*), -1));
return ::il2cpp_utils::RunMethodRethrow<::System::Data::Constraint*, false>(this, ___internal__method, destination);
}
// Autogenerated method: System.Data.Constraint.Clone
::System::Data::Constraint* System::Data::Constraint::Clone(::System::Data::DataSet* destination, bool ignoreNSforTableLookup) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::Constraint::Clone");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::Constraint*), -1));
return ::il2cpp_utils::RunMethodRethrow<::System::Data::Constraint*, false>(this, ___internal__method, destination, ignoreNSforTableLookup);
}
// Autogenerated method: System.Data.Constraint.CheckConstraint
void System::Data::Constraint::CheckConstraint() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::Constraint::CheckConstraint");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "CheckConstraint", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.Constraint.CheckCanAddToCollection
void System::Data::Constraint::CheckCanAddToCollection(::System::Data::ConstraintCollection* constraint) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::Constraint::CheckCanAddToCollection");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::Constraint*), -1));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, constraint);
}
// Autogenerated method: System.Data.Constraint.CanBeRemovedFromCollection
bool System::Data::Constraint::CanBeRemovedFromCollection(::System::Data::ConstraintCollection* constraint, bool fThrowException) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::Constraint::CanBeRemovedFromCollection");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::Constraint*), -1));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, constraint, fThrowException);
}
// Autogenerated method: System.Data.Constraint.CheckConstraint
void System::Data::Constraint::CheckConstraint(::System::Data::DataRow* row, ::System::Data::DataRowAction action) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::Constraint::CheckConstraint");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::Constraint*), -1));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, row, action);
}
// Autogenerated method: System.Data.Constraint.CheckState
void System::Data::Constraint::CheckState() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::Constraint::CheckState");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::Constraint*), -1));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.Constraint.CheckStateForProperty
void System::Data::Constraint::CheckStateForProperty() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::Constraint::CheckStateForProperty");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "CheckStateForProperty", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.Constraint.IsConstraintViolated
bool System::Data::Constraint::IsConstraintViolated() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::Constraint::IsConstraintViolated");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::Constraint*), -1));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.Constraint.ToString
::StringW System::Data::Constraint::ToString() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::Constraint::ToString");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::Il2CppObject*), 3));
return ::il2cpp_utils::RunMethodRethrow<::StringW, false>(this, ___internal__method);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
// Including type: System.Data.ConstraintCollection
#include "System/Data/ConstraintCollection.hpp"
// Including type: System.Data.DataTable
#include "System/Data/DataTable.hpp"
// Including type: System.Collections.ArrayList
#include "System/Collections/ArrayList.hpp"
// Including type: System.ComponentModel.CollectionChangeEventHandler
#include "System/ComponentModel/CollectionChangeEventHandler.hpp"
// Including type: System.Data.Constraint
#include "System/Data/Constraint.hpp"
// Including type: System.Data.DataColumn
#include "System/Data/DataColumn.hpp"
// Including type: System.Data.UniqueConstraint
#include "System/Data/UniqueConstraint.hpp"
// Including type: System.Data.ForeignKeyConstraint
#include "System/Data/ForeignKeyConstraint.hpp"
// Including type: System.ComponentModel.CollectionChangeEventArgs
#include "System/ComponentModel/CollectionChangeEventArgs.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated instance field getter
// Get instance field: private readonly System.Data.DataTable _table
[[deprecated("Use field access instead!")]] ::System::Data::DataTable*& System::Data::ConstraintCollection::dyn__table() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ConstraintCollection::dyn__table");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_table"))->offset;
return *reinterpret_cast<::System::Data::DataTable**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private readonly System.Collections.ArrayList _list
[[deprecated("Use field access instead!")]] ::System::Collections::ArrayList*& System::Data::ConstraintCollection::dyn__list() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ConstraintCollection::dyn__list");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_list"))->offset;
return *reinterpret_cast<::System::Collections::ArrayList**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.Int32 _defaultNameIndex
[[deprecated("Use field access instead!")]] int& System::Data::ConstraintCollection::dyn__defaultNameIndex() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ConstraintCollection::dyn__defaultNameIndex");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_defaultNameIndex"))->offset;
return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.ComponentModel.CollectionChangeEventHandler _onCollectionChanged
[[deprecated("Use field access instead!")]] ::System::ComponentModel::CollectionChangeEventHandler*& System::Data::ConstraintCollection::dyn__onCollectionChanged() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ConstraintCollection::dyn__onCollectionChanged");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_onCollectionChanged"))->offset;
return *reinterpret_cast<::System::ComponentModel::CollectionChangeEventHandler**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.Data.Constraint[] _delayLoadingConstraints
[[deprecated("Use field access instead!")]] ::ArrayW<::System::Data::Constraint*>& System::Data::ConstraintCollection::dyn__delayLoadingConstraints() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ConstraintCollection::dyn__delayLoadingConstraints");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_delayLoadingConstraints"))->offset;
return *reinterpret_cast<::ArrayW<::System::Data::Constraint*>*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.Boolean _fLoadForeignKeyConstraintsOnly
[[deprecated("Use field access instead!")]] bool& System::Data::ConstraintCollection::dyn__fLoadForeignKeyConstraintsOnly() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ConstraintCollection::dyn__fLoadForeignKeyConstraintsOnly");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_fLoadForeignKeyConstraintsOnly"))->offset;
return *reinterpret_cast<bool*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated method: System.Data.ConstraintCollection.get_Item
::System::Data::Constraint* System::Data::ConstraintCollection::get_Item(int index) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ConstraintCollection::get_Item");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_Item", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(index)})));
return ::il2cpp_utils::RunMethodRethrow<::System::Data::Constraint*, false>(this, ___internal__method, index);
}
// Autogenerated method: System.Data.ConstraintCollection.get_Table
::System::Data::DataTable* System::Data::ConstraintCollection::get_Table() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ConstraintCollection::get_Table");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_Table", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<::System::Data::DataTable*, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.ConstraintCollection.get_Item
::System::Data::Constraint* System::Data::ConstraintCollection::get_Item(::StringW name) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ConstraintCollection::get_Item");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_Item", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(name)})));
return ::il2cpp_utils::RunMethodRethrow<::System::Data::Constraint*, false>(this, ___internal__method, name);
}
// Autogenerated method: System.Data.ConstraintCollection.Add
void System::Data::ConstraintCollection::Add(::System::Data::Constraint* constraint) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ConstraintCollection::Add");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Add", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(constraint)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, constraint);
}
// Autogenerated method: System.Data.ConstraintCollection.Add
void System::Data::ConstraintCollection::Add(::System::Data::Constraint* constraint, bool addUniqueWhenAddingForeign) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ConstraintCollection::Add");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Add", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(constraint), ::il2cpp_utils::ExtractType(addUniqueWhenAddingForeign)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, constraint, addUniqueWhenAddingForeign);
}
// Autogenerated method: System.Data.ConstraintCollection.Add
::System::Data::Constraint* System::Data::ConstraintCollection::Add(::StringW name, ::ArrayW<::System::Data::DataColumn*> columns, bool primaryKey) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ConstraintCollection::Add");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Add", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(name), ::il2cpp_utils::ExtractType(columns), ::il2cpp_utils::ExtractType(primaryKey)})));
return ::il2cpp_utils::RunMethodRethrow<::System::Data::Constraint*, false>(this, ___internal__method, name, columns, primaryKey);
}
// Autogenerated method: System.Data.ConstraintCollection.AddUniqueConstraint
void System::Data::ConstraintCollection::AddUniqueConstraint(::System::Data::UniqueConstraint* constraint) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ConstraintCollection::AddUniqueConstraint");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "AddUniqueConstraint", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(constraint)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, constraint);
}
// Autogenerated method: System.Data.ConstraintCollection.AddForeignKeyConstraint
void System::Data::ConstraintCollection::AddForeignKeyConstraint(::System::Data::ForeignKeyConstraint* constraint) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ConstraintCollection::AddForeignKeyConstraint");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "AddForeignKeyConstraint", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(constraint)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, constraint);
}
// Autogenerated method: System.Data.ConstraintCollection.AutoGenerated
bool System::Data::ConstraintCollection::AutoGenerated(::System::Data::Constraint* constraint) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ConstraintCollection::AutoGenerated");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "AutoGenerated", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(constraint)})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, constraint);
}
// Autogenerated method: System.Data.ConstraintCollection.ArrayAdd
void System::Data::ConstraintCollection::ArrayAdd(::System::Data::Constraint* constraint) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ConstraintCollection::ArrayAdd");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "ArrayAdd", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(constraint)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, constraint);
}
// Autogenerated method: System.Data.ConstraintCollection.ArrayRemove
void System::Data::ConstraintCollection::ArrayRemove(::System::Data::Constraint* constraint) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ConstraintCollection::ArrayRemove");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "ArrayRemove", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(constraint)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, constraint);
}
// Autogenerated method: System.Data.ConstraintCollection.AssignName
::StringW System::Data::ConstraintCollection::AssignName() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ConstraintCollection::AssignName");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "AssignName", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<::StringW, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.ConstraintCollection.BaseAdd
void System::Data::ConstraintCollection::BaseAdd(::System::Data::Constraint* constraint) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ConstraintCollection::BaseAdd");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "BaseAdd", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(constraint)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, constraint);
}
// Autogenerated method: System.Data.ConstraintCollection.BaseGroupSwitch
void System::Data::ConstraintCollection::BaseGroupSwitch(::ArrayW<::System::Data::Constraint*> oldArray, int oldLength, ::ArrayW<::System::Data::Constraint*> newArray, int newLength) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ConstraintCollection::BaseGroupSwitch");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "BaseGroupSwitch", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(oldArray), ::il2cpp_utils::ExtractType(oldLength), ::il2cpp_utils::ExtractType(newArray), ::il2cpp_utils::ExtractType(newLength)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, oldArray, oldLength, newArray, newLength);
}
// Autogenerated method: System.Data.ConstraintCollection.BaseRemove
void System::Data::ConstraintCollection::BaseRemove(::System::Data::Constraint* constraint) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ConstraintCollection::BaseRemove");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "BaseRemove", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(constraint)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, constraint);
}
// Autogenerated method: System.Data.ConstraintCollection.CanRemove
bool System::Data::ConstraintCollection::CanRemove(::System::Data::Constraint* constraint, bool fThrowException) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ConstraintCollection::CanRemove");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "CanRemove", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(constraint), ::il2cpp_utils::ExtractType(fThrowException)})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, constraint, fThrowException);
}
// Autogenerated method: System.Data.ConstraintCollection.Clear
void System::Data::ConstraintCollection::Clear() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ConstraintCollection::Clear");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Clear", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.ConstraintCollection.Contains
bool System::Data::ConstraintCollection::Contains(::StringW name) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ConstraintCollection::Contains");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Contains", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(name)})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, name);
}
// Autogenerated method: System.Data.ConstraintCollection.Contains
bool System::Data::ConstraintCollection::Contains(::StringW name, bool caseSensitive) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ConstraintCollection::Contains");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Contains", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(name), ::il2cpp_utils::ExtractType(caseSensitive)})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, name, caseSensitive);
}
// Autogenerated method: System.Data.ConstraintCollection.FindConstraint
::System::Data::Constraint* System::Data::ConstraintCollection::FindConstraint(::System::Data::Constraint* constraint) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ConstraintCollection::FindConstraint");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "FindConstraint", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(constraint)})));
return ::il2cpp_utils::RunMethodRethrow<::System::Data::Constraint*, false>(this, ___internal__method, constraint);
}
// Autogenerated method: System.Data.ConstraintCollection.FindKeyConstraint
::System::Data::UniqueConstraint* System::Data::ConstraintCollection::FindKeyConstraint(::ArrayW<::System::Data::DataColumn*> columns) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ConstraintCollection::FindKeyConstraint");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "FindKeyConstraint", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(columns)})));
return ::il2cpp_utils::RunMethodRethrow<::System::Data::UniqueConstraint*, false>(this, ___internal__method, columns);
}
// Autogenerated method: System.Data.ConstraintCollection.FindKeyConstraint
::System::Data::UniqueConstraint* System::Data::ConstraintCollection::FindKeyConstraint(::System::Data::DataColumn* column) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ConstraintCollection::FindKeyConstraint");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "FindKeyConstraint", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(column)})));
return ::il2cpp_utils::RunMethodRethrow<::System::Data::UniqueConstraint*, false>(this, ___internal__method, column);
}
// Autogenerated method: System.Data.ConstraintCollection.FindForeignKeyConstraint
::System::Data::ForeignKeyConstraint* System::Data::ConstraintCollection::FindForeignKeyConstraint(::ArrayW<::System::Data::DataColumn*> parentColumns, ::ArrayW<::System::Data::DataColumn*> childColumns) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ConstraintCollection::FindForeignKeyConstraint");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "FindForeignKeyConstraint", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(parentColumns), ::il2cpp_utils::ExtractType(childColumns)})));
return ::il2cpp_utils::RunMethodRethrow<::System::Data::ForeignKeyConstraint*, false>(this, ___internal__method, parentColumns, childColumns);
}
// Autogenerated method: System.Data.ConstraintCollection.CompareArrays
bool System::Data::ConstraintCollection::CompareArrays(::ArrayW<::System::Data::DataColumn*> a1, ::ArrayW<::System::Data::DataColumn*> a2) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ConstraintCollection::CompareArrays");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Data", "ConstraintCollection", "CompareArrays", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(a1), ::il2cpp_utils::ExtractType(a2)})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, a1, a2);
}
// Autogenerated method: System.Data.ConstraintCollection.InternalIndexOf
int System::Data::ConstraintCollection::InternalIndexOf(::StringW constraintName) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ConstraintCollection::InternalIndexOf");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "InternalIndexOf", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(constraintName)})));
return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method, constraintName);
}
// Autogenerated method: System.Data.ConstraintCollection.MakeName
::StringW System::Data::ConstraintCollection::MakeName(int index) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ConstraintCollection::MakeName");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "MakeName", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(index)})));
return ::il2cpp_utils::RunMethodRethrow<::StringW, false>(this, ___internal__method, index);
}
// Autogenerated method: System.Data.ConstraintCollection.OnCollectionChanged
void System::Data::ConstraintCollection::OnCollectionChanged(::System::ComponentModel::CollectionChangeEventArgs* ccevent) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ConstraintCollection::OnCollectionChanged");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "OnCollectionChanged", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(ccevent)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, ccevent);
}
// Autogenerated method: System.Data.ConstraintCollection.RegisterName
void System::Data::ConstraintCollection::RegisterName(::StringW name) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ConstraintCollection::RegisterName");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "RegisterName", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(name)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, name);
}
// Autogenerated method: System.Data.ConstraintCollection.Remove
void System::Data::ConstraintCollection::Remove(::System::Data::Constraint* constraint) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ConstraintCollection::Remove");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Remove", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(constraint)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, constraint);
}
// Autogenerated method: System.Data.ConstraintCollection.UnregisterName
void System::Data::ConstraintCollection::UnregisterName(::StringW name) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ConstraintCollection::UnregisterName");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "UnregisterName", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(name)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, name);
}
// Autogenerated method: System.Data.ConstraintCollection.get_List
::System::Collections::ArrayList* System::Data::ConstraintCollection::get_List() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ConstraintCollection::get_List");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::InternalDataCollectionBase*), 11));
return ::il2cpp_utils::RunMethodRethrow<::System::Collections::ArrayList*, false>(this, ___internal__method);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
// Including type: System.Data.ConstraintConverter
#include "System/Data/ConstraintConverter.hpp"
// Including type: System.ComponentModel.ITypeDescriptorContext
#include "System/ComponentModel/ITypeDescriptorContext.hpp"
// Including type: System.Type
#include "System/Type.hpp"
// Including type: System.Globalization.CultureInfo
#include "System/Globalization/CultureInfo.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated method: System.Data.ConstraintConverter.CanConvertTo
bool System::Data::ConstraintConverter::CanConvertTo(::System::ComponentModel::ITypeDescriptorContext* context, ::System::Type* destinationType) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ConstraintConverter::CanConvertTo");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::ComponentModel::TypeConverter*), 5));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, context, destinationType);
}
// Autogenerated method: System.Data.ConstraintConverter.ConvertTo
::Il2CppObject* System::Data::ConstraintConverter::ConvertTo(::System::ComponentModel::ITypeDescriptorContext* context, ::System::Globalization::CultureInfo* culture, ::Il2CppObject* value, ::System::Type* destinationType) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ConstraintConverter::ConvertTo");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::ComponentModel::TypeConverter*), 7));
return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method, context, culture, value, destinationType);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
// Including type: System.Data.ConstraintEnumerator
#include "System/Data/ConstraintEnumerator.hpp"
// Including type: System.Collections.IEnumerator
#include "System/Collections/IEnumerator.hpp"
// Including type: System.Data.Constraint
#include "System/Data/Constraint.hpp"
// Including type: System.Data.DataSet
#include "System/Data/DataSet.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated instance field getter
// Get instance field: private System.Collections.IEnumerator _tables
[[deprecated("Use field access instead!")]] ::System::Collections::IEnumerator*& System::Data::ConstraintEnumerator::dyn__tables() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ConstraintEnumerator::dyn__tables");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_tables"))->offset;
return *reinterpret_cast<::System::Collections::IEnumerator**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.Collections.IEnumerator _constraints
[[deprecated("Use field access instead!")]] ::System::Collections::IEnumerator*& System::Data::ConstraintEnumerator::dyn__constraints() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ConstraintEnumerator::dyn__constraints");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_constraints"))->offset;
return *reinterpret_cast<::System::Collections::IEnumerator**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.Data.Constraint _currentObject
[[deprecated("Use field access instead!")]] ::System::Data::Constraint*& System::Data::ConstraintEnumerator::dyn__currentObject() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ConstraintEnumerator::dyn__currentObject");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_currentObject"))->offset;
return *reinterpret_cast<::System::Data::Constraint**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated method: System.Data.ConstraintEnumerator.get_CurrentObject
::System::Data::Constraint* System::Data::ConstraintEnumerator::get_CurrentObject() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ConstraintEnumerator::get_CurrentObject");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_CurrentObject", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<::System::Data::Constraint*, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.ConstraintEnumerator.GetNext
bool System::Data::ConstraintEnumerator::GetNext() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ConstraintEnumerator::GetNext");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "GetNext", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.ConstraintEnumerator.GetConstraint
::System::Data::Constraint* System::Data::ConstraintEnumerator::GetConstraint() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ConstraintEnumerator::GetConstraint");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "GetConstraint", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<::System::Data::Constraint*, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.ConstraintEnumerator.IsValidCandidate
bool System::Data::ConstraintEnumerator::IsValidCandidate(::System::Data::Constraint* constraint) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ConstraintEnumerator::IsValidCandidate");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::ConstraintEnumerator*), 4));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, constraint);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
// Including type: System.Data.ForeignKeyConstraintEnumerator
#include "System/Data/ForeignKeyConstraintEnumerator.hpp"
// Including type: System.Data.ForeignKeyConstraint
#include "System/Data/ForeignKeyConstraint.hpp"
// Including type: System.Data.DataSet
#include "System/Data/DataSet.hpp"
// Including type: System.Data.Constraint
#include "System/Data/Constraint.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated method: System.Data.ForeignKeyConstraintEnumerator.GetForeignKeyConstraint
::System::Data::ForeignKeyConstraint* System::Data::ForeignKeyConstraintEnumerator::GetForeignKeyConstraint() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ForeignKeyConstraintEnumerator::GetForeignKeyConstraint");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "GetForeignKeyConstraint", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<::System::Data::ForeignKeyConstraint*, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.ForeignKeyConstraintEnumerator.IsValidCandidate
bool System::Data::ForeignKeyConstraintEnumerator::IsValidCandidate(::System::Data::Constraint* constraint) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ForeignKeyConstraintEnumerator::IsValidCandidate");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::ConstraintEnumerator*), 4));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, constraint);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
// Including type: System.Data.ChildForeignKeyConstraintEnumerator
#include "System/Data/ChildForeignKeyConstraintEnumerator.hpp"
// Including type: System.Data.DataTable
#include "System/Data/DataTable.hpp"
// Including type: System.Data.DataSet
#include "System/Data/DataSet.hpp"
// Including type: System.Data.Constraint
#include "System/Data/Constraint.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated instance field getter
// Get instance field: private readonly System.Data.DataTable _table
[[deprecated("Use field access instead!")]] ::System::Data::DataTable*& System::Data::ChildForeignKeyConstraintEnumerator::dyn__table() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ChildForeignKeyConstraintEnumerator::dyn__table");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_table"))->offset;
return *reinterpret_cast<::System::Data::DataTable**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated method: System.Data.ChildForeignKeyConstraintEnumerator.IsValidCandidate
bool System::Data::ChildForeignKeyConstraintEnumerator::IsValidCandidate(::System::Data::Constraint* constraint) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ChildForeignKeyConstraintEnumerator::IsValidCandidate");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::ForeignKeyConstraintEnumerator*), 4));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, constraint);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
// Including type: System.Data.ParentForeignKeyConstraintEnumerator
#include "System/Data/ParentForeignKeyConstraintEnumerator.hpp"
// Including type: System.Data.DataTable
#include "System/Data/DataTable.hpp"
// Including type: System.Data.DataSet
#include "System/Data/DataSet.hpp"
// Including type: System.Data.Constraint
#include "System/Data/Constraint.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated instance field getter
// Get instance field: private readonly System.Data.DataTable _table
[[deprecated("Use field access instead!")]] ::System::Data::DataTable*& System::Data::ParentForeignKeyConstraintEnumerator::dyn__table() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ParentForeignKeyConstraintEnumerator::dyn__table");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_table"))->offset;
return *reinterpret_cast<::System::Data::DataTable**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated method: System.Data.ParentForeignKeyConstraintEnumerator.IsValidCandidate
bool System::Data::ParentForeignKeyConstraintEnumerator::IsValidCandidate(::System::Data::Constraint* constraint) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::ParentForeignKeyConstraintEnumerator::IsValidCandidate");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::ForeignKeyConstraintEnumerator*), 4));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, constraint);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
// Including type: System.Data.DataColumn
#include "System/Data/DataColumn.hpp"
// Including type: System.Type
#include "System/Type.hpp"
// Including type: System.Data.DataExpression
#include "System/Data/DataExpression.hpp"
// Including type: System.Data.Index
#include "System/Data/Index.hpp"
// Including type: System.Data.DataTable
#include "System/Data/DataTable.hpp"
// Including type: System.Collections.Generic.List`1
#include "System/Collections/Generic/List_1.hpp"
// Including type: System.Data.PropertyCollection
#include "System/Data/PropertyCollection.hpp"
// Including type: System.Data.Common.DataStorage
#include "System/Data/Common/DataStorage.hpp"
// Including type: System.Data.AutoIncrementValue
#include "System/Data/AutoIncrementValue.hpp"
// Including type: System.Data.SimpleType
#include "System/Data/SimpleType.hpp"
// Including type: System.ComponentModel.PropertyChangedEventHandler
#include "System/ComponentModel/PropertyChangedEventHandler.hpp"
// Including type: System.IFormatProvider
#include "System/IFormatProvider.hpp"
// Including type: System.Globalization.CultureInfo
#include "System/Globalization/CultureInfo.hpp"
// Including type: System.Data.DataRow
#include "System/Data/DataRow.hpp"
// Including type: System.Data.DataRowVersion
#include "System/Data/DataRowVersion.hpp"
// Including type: System.Data.DataRowAction
#include "System/Data/DataRowAction.hpp"
// Including type: System.Data.AggregateType
#include "System/Data/AggregateType.hpp"
// Including type: System.ComponentModel.PropertyChangedEventArgs
#include "System/ComponentModel/PropertyChangedEventArgs.hpp"
// Including type: System.Xml.XmlReader
#include "System/Xml/XmlReader.hpp"
// Including type: System.Xml.Serialization.XmlRootAttribute
#include "System/Xml/Serialization/XmlRootAttribute.hpp"
// Including type: System.Xml.XmlWriter
#include "System/Xml/XmlWriter.hpp"
// Including type: System.Collections.BitArray
#include "System/Collections/BitArray.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated static field getter
// Get static field: static private System.Int32 s_objectTypeCount
int System::Data::DataColumn::_get_s_objectTypeCount() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::_get_s_objectTypeCount");
return THROW_UNLESS(il2cpp_utils::GetFieldValue<int>("System.Data", "DataColumn", "s_objectTypeCount"));
}
// Autogenerated static field setter
// Set static field: static private System.Int32 s_objectTypeCount
void System::Data::DataColumn::_set_s_objectTypeCount(int value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::_set_s_objectTypeCount");
THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Data", "DataColumn", "s_objectTypeCount", value));
}
// Autogenerated instance field getter
// Get instance field: private System.Boolean _allowNull
[[deprecated("Use field access instead!")]] bool& System::Data::DataColumn::dyn__allowNull() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::dyn__allowNull");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_allowNull"))->offset;
return *reinterpret_cast<bool*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.String _caption
[[deprecated("Use field access instead!")]] ::StringW& System::Data::DataColumn::dyn__caption() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::dyn__caption");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_caption"))->offset;
return *reinterpret_cast<::StringW*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.String _columnName
[[deprecated("Use field access instead!")]] ::StringW& System::Data::DataColumn::dyn__columnName() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::dyn__columnName");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_columnName"))->offset;
return *reinterpret_cast<::StringW*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.Type _dataType
[[deprecated("Use field access instead!")]] ::System::Type*& System::Data::DataColumn::dyn__dataType() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::dyn__dataType");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_dataType"))->offset;
return *reinterpret_cast<::System::Type**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.Data.Common.StorageType _storageType
[[deprecated("Use field access instead!")]] ::System::Data::Common::StorageType& System::Data::DataColumn::dyn__storageType() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::dyn__storageType");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_storageType"))->offset;
return *reinterpret_cast<::System::Data::Common::StorageType*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: System.Object _defaultValue
[[deprecated("Use field access instead!")]] ::Il2CppObject*& System::Data::DataColumn::dyn__defaultValue() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::dyn__defaultValue");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_defaultValue"))->offset;
return *reinterpret_cast<::Il2CppObject**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.Data.DataSetDateTime _dateTimeMode
[[deprecated("Use field access instead!")]] ::System::Data::DataSetDateTime& System::Data::DataColumn::dyn__dateTimeMode() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::dyn__dateTimeMode");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_dateTimeMode"))->offset;
return *reinterpret_cast<::System::Data::DataSetDateTime*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.Data.DataExpression _expression
[[deprecated("Use field access instead!")]] ::System::Data::DataExpression*& System::Data::DataColumn::dyn__expression() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::dyn__expression");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_expression"))->offset;
return *reinterpret_cast<::System::Data::DataExpression**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.Int32 _maxLength
[[deprecated("Use field access instead!")]] int& System::Data::DataColumn::dyn__maxLength() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::dyn__maxLength");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_maxLength"))->offset;
return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.Int32 _ordinal
[[deprecated("Use field access instead!")]] int& System::Data::DataColumn::dyn__ordinal() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::dyn__ordinal");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_ordinal"))->offset;
return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.Boolean _readOnly
[[deprecated("Use field access instead!")]] bool& System::Data::DataColumn::dyn__readOnly() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::dyn__readOnly");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_readOnly"))->offset;
return *reinterpret_cast<bool*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: System.Data.Index _sortIndex
[[deprecated("Use field access instead!")]] ::System::Data::Index*& System::Data::DataColumn::dyn__sortIndex() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::dyn__sortIndex");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_sortIndex"))->offset;
return *reinterpret_cast<::System::Data::Index**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: System.Data.DataTable _table
[[deprecated("Use field access instead!")]] ::System::Data::DataTable*& System::Data::DataColumn::dyn__table() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::dyn__table");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_table"))->offset;
return *reinterpret_cast<::System::Data::DataTable**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.Boolean _unique
[[deprecated("Use field access instead!")]] bool& System::Data::DataColumn::dyn__unique() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::dyn__unique");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_unique"))->offset;
return *reinterpret_cast<bool*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: System.Data.MappingType _columnMapping
[[deprecated("Use field access instead!")]] ::System::Data::MappingType& System::Data::DataColumn::dyn__columnMapping() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::dyn__columnMapping");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_columnMapping"))->offset;
return *reinterpret_cast<::System::Data::MappingType*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: System.Int32 _hashCode
[[deprecated("Use field access instead!")]] int& System::Data::DataColumn::dyn__hashCode() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::dyn__hashCode");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_hashCode"))->offset;
return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: System.Int32 _errors
[[deprecated("Use field access instead!")]] int& System::Data::DataColumn::dyn__errors() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::dyn__errors");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_errors"))->offset;
return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.Boolean _isSqlType
[[deprecated("Use field access instead!")]] bool& System::Data::DataColumn::dyn__isSqlType() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::dyn__isSqlType");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_isSqlType"))->offset;
return *reinterpret_cast<bool*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.Boolean _implementsINullable
[[deprecated("Use field access instead!")]] bool& System::Data::DataColumn::dyn__implementsINullable() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::dyn__implementsINullable");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_implementsINullable"))->offset;
return *reinterpret_cast<bool*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.Boolean _implementsIChangeTracking
[[deprecated("Use field access instead!")]] bool& System::Data::DataColumn::dyn__implementsIChangeTracking() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::dyn__implementsIChangeTracking");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_implementsIChangeTracking"))->offset;
return *reinterpret_cast<bool*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.Boolean _implementsIRevertibleChangeTracking
[[deprecated("Use field access instead!")]] bool& System::Data::DataColumn::dyn__implementsIRevertibleChangeTracking() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::dyn__implementsIRevertibleChangeTracking");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_implementsIRevertibleChangeTracking"))->offset;
return *reinterpret_cast<bool*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.Boolean _implementsIXMLSerializable
[[deprecated("Use field access instead!")]] bool& System::Data::DataColumn::dyn__implementsIXMLSerializable() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::dyn__implementsIXMLSerializable");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_implementsIXMLSerializable"))->offset;
return *reinterpret_cast<bool*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.Boolean _defaultValueIsNull
[[deprecated("Use field access instead!")]] bool& System::Data::DataColumn::dyn__defaultValueIsNull() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::dyn__defaultValueIsNull");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_defaultValueIsNull"))->offset;
return *reinterpret_cast<bool*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: System.Collections.Generic.List`1<System.Data.DataColumn> _dependentColumns
[[deprecated("Use field access instead!")]] ::System::Collections::Generic::List_1<::System::Data::DataColumn*>*& System::Data::DataColumn::dyn__dependentColumns() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::dyn__dependentColumns");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_dependentColumns"))->offset;
return *reinterpret_cast<::System::Collections::Generic::List_1<::System::Data::DataColumn*>**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: System.Data.PropertyCollection _extendedProperties
[[deprecated("Use field access instead!")]] ::System::Data::PropertyCollection*& System::Data::DataColumn::dyn__extendedProperties() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::dyn__extendedProperties");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_extendedProperties"))->offset;
return *reinterpret_cast<::System::Data::PropertyCollection**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.Data.Common.DataStorage _storage
[[deprecated("Use field access instead!")]] ::System::Data::Common::DataStorage*& System::Data::DataColumn::dyn__storage() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::dyn__storage");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_storage"))->offset;
return *reinterpret_cast<::System::Data::Common::DataStorage**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.Data.AutoIncrementValue _autoInc
[[deprecated("Use field access instead!")]] ::System::Data::AutoIncrementValue*& System::Data::DataColumn::dyn__autoInc() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::dyn__autoInc");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_autoInc"))->offset;
return *reinterpret_cast<::System::Data::AutoIncrementValue**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: System.String _columnUri
[[deprecated("Use field access instead!")]] ::StringW& System::Data::DataColumn::dyn__columnUri() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::dyn__columnUri");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_columnUri"))->offset;
return *reinterpret_cast<::StringW*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.String _columnPrefix
[[deprecated("Use field access instead!")]] ::StringW& System::Data::DataColumn::dyn__columnPrefix() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::dyn__columnPrefix");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_columnPrefix"))->offset;
return *reinterpret_cast<::StringW*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: System.String _encodedColumnName
[[deprecated("Use field access instead!")]] ::StringW& System::Data::DataColumn::dyn__encodedColumnName() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::dyn__encodedColumnName");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_encodedColumnName"))->offset;
return *reinterpret_cast<::StringW*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: System.Data.SimpleType _simpleType
[[deprecated("Use field access instead!")]] ::System::Data::SimpleType*& System::Data::DataColumn::dyn__simpleType() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::dyn__simpleType");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_simpleType"))->offset;
return *reinterpret_cast<::System::Data::SimpleType**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private readonly System.Int32 _objectID
[[deprecated("Use field access instead!")]] int& System::Data::DataColumn::dyn__objectID() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::dyn__objectID");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_objectID"))->offset;
return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.String <XmlDataType>k__BackingField
[[deprecated("Use field access instead!")]] ::StringW& System::Data::DataColumn::dyn_$XmlDataType$k__BackingField() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::dyn_$XmlDataType$k__BackingField");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "<XmlDataType>k__BackingField"))->offset;
return *reinterpret_cast<::StringW*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.ComponentModel.PropertyChangedEventHandler PropertyChanging
[[deprecated("Use field access instead!")]] ::System::ComponentModel::PropertyChangedEventHandler*& System::Data::DataColumn::dyn_PropertyChanging() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::dyn_PropertyChanging");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "PropertyChanging"))->offset;
return *reinterpret_cast<::System::ComponentModel::PropertyChangedEventHandler**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated method: System.Data.DataColumn.get_AllowDBNull
bool System::Data::DataColumn::get_AllowDBNull() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::get_AllowDBNull");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_AllowDBNull", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumn.set_AllowDBNull
void System::Data::DataColumn::set_AllowDBNull(bool value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::set_AllowDBNull");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_AllowDBNull", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value);
}
// Autogenerated method: System.Data.DataColumn.get_AutoIncrement
bool System::Data::DataColumn::get_AutoIncrement() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::get_AutoIncrement");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_AutoIncrement", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumn.set_AutoIncrement
void System::Data::DataColumn::set_AutoIncrement(bool value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::set_AutoIncrement");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_AutoIncrement", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value);
}
// Autogenerated method: System.Data.DataColumn.get_AutoIncrementCurrent
::Il2CppObject* System::Data::DataColumn::get_AutoIncrementCurrent() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::get_AutoIncrementCurrent");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_AutoIncrementCurrent", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumn.set_AutoIncrementCurrent
void System::Data::DataColumn::set_AutoIncrementCurrent(::Il2CppObject* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::set_AutoIncrementCurrent");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_AutoIncrementCurrent", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value);
}
// Autogenerated method: System.Data.DataColumn.get_AutoInc
::System::Data::AutoIncrementValue* System::Data::DataColumn::get_AutoInc() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::get_AutoInc");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_AutoInc", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<::System::Data::AutoIncrementValue*, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumn.get_AutoIncrementSeed
int64_t System::Data::DataColumn::get_AutoIncrementSeed() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::get_AutoIncrementSeed");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_AutoIncrementSeed", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<int64_t, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumn.set_AutoIncrementSeed
void System::Data::DataColumn::set_AutoIncrementSeed(int64_t value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::set_AutoIncrementSeed");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_AutoIncrementSeed", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value);
}
// Autogenerated method: System.Data.DataColumn.get_AutoIncrementStep
int64_t System::Data::DataColumn::get_AutoIncrementStep() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::get_AutoIncrementStep");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_AutoIncrementStep", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<int64_t, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumn.set_AutoIncrementStep
void System::Data::DataColumn::set_AutoIncrementStep(int64_t value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::set_AutoIncrementStep");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_AutoIncrementStep", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value);
}
// Autogenerated method: System.Data.DataColumn.get_Caption
::StringW System::Data::DataColumn::get_Caption() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::get_Caption");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_Caption", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<::StringW, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumn.set_Caption
void System::Data::DataColumn::set_Caption(::StringW value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::set_Caption");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_Caption", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value);
}
// Autogenerated method: System.Data.DataColumn.get_ColumnName
::StringW System::Data::DataColumn::get_ColumnName() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::get_ColumnName");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_ColumnName", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<::StringW, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumn.set_ColumnName
void System::Data::DataColumn::set_ColumnName(::StringW value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::set_ColumnName");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_ColumnName", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value);
}
// Autogenerated method: System.Data.DataColumn.get_EncodedColumnName
::StringW System::Data::DataColumn::get_EncodedColumnName() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::get_EncodedColumnName");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_EncodedColumnName", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<::StringW, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumn.get_FormatProvider
::System::IFormatProvider* System::Data::DataColumn::get_FormatProvider() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::get_FormatProvider");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_FormatProvider", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<::System::IFormatProvider*, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumn.get_Locale
::System::Globalization::CultureInfo* System::Data::DataColumn::get_Locale() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::get_Locale");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_Locale", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<::System::Globalization::CultureInfo*, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumn.get_ObjectID
int System::Data::DataColumn::get_ObjectID() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::get_ObjectID");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_ObjectID", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumn.get_Prefix
::StringW System::Data::DataColumn::get_Prefix() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::get_Prefix");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_Prefix", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<::StringW, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumn.set_Prefix
void System::Data::DataColumn::set_Prefix(::StringW value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::set_Prefix");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_Prefix", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value);
}
// Autogenerated method: System.Data.DataColumn.get_Computed
bool System::Data::DataColumn::get_Computed() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::get_Computed");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_Computed", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumn.get_DataExpression
::System::Data::DataExpression* System::Data::DataColumn::get_DataExpression() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::get_DataExpression");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_DataExpression", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<::System::Data::DataExpression*, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumn.get_DataType
::System::Type* System::Data::DataColumn::get_DataType() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::get_DataType");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_DataType", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<::System::Type*, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumn.set_DataType
void System::Data::DataColumn::set_DataType(::System::Type* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::set_DataType");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_DataType", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value);
}
// Autogenerated method: System.Data.DataColumn.get_DateTimeMode
::System::Data::DataSetDateTime System::Data::DataColumn::get_DateTimeMode() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::get_DateTimeMode");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_DateTimeMode", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<::System::Data::DataSetDateTime, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumn.set_DateTimeMode
void System::Data::DataColumn::set_DateTimeMode(::System::Data::DataSetDateTime value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::set_DateTimeMode");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_DateTimeMode", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value);
}
// Autogenerated method: System.Data.DataColumn.get_DefaultValue
::Il2CppObject* System::Data::DataColumn::get_DefaultValue() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::get_DefaultValue");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_DefaultValue", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumn.set_DefaultValue
void System::Data::DataColumn::set_DefaultValue(::Il2CppObject* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::set_DefaultValue");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_DefaultValue", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value);
}
// Autogenerated method: System.Data.DataColumn.get_DefaultValueIsNull
bool System::Data::DataColumn::get_DefaultValueIsNull() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::get_DefaultValueIsNull");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_DefaultValueIsNull", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumn.get_Expression
::StringW System::Data::DataColumn::get_Expression() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::get_Expression");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_Expression", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<::StringW, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumn.set_Expression
void System::Data::DataColumn::set_Expression(::StringW value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::set_Expression");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_Expression", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value);
}
// Autogenerated method: System.Data.DataColumn.get_ExtendedProperties
::System::Data::PropertyCollection* System::Data::DataColumn::get_ExtendedProperties() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::get_ExtendedProperties");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_ExtendedProperties", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<::System::Data::PropertyCollection*, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumn.get_HasData
bool System::Data::DataColumn::get_HasData() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::get_HasData");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_HasData", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumn.get_ImplementsINullable
bool System::Data::DataColumn::get_ImplementsINullable() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::get_ImplementsINullable");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_ImplementsINullable", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumn.get_ImplementsIChangeTracking
bool System::Data::DataColumn::get_ImplementsIChangeTracking() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::get_ImplementsIChangeTracking");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_ImplementsIChangeTracking", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumn.get_ImplementsIRevertibleChangeTracking
bool System::Data::DataColumn::get_ImplementsIRevertibleChangeTracking() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::get_ImplementsIRevertibleChangeTracking");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_ImplementsIRevertibleChangeTracking", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumn.get_IsValueType
bool System::Data::DataColumn::get_IsValueType() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::get_IsValueType");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_IsValueType", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumn.get_IsSqlType
bool System::Data::DataColumn::get_IsSqlType() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::get_IsSqlType");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_IsSqlType", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumn.get_MaxLength
int System::Data::DataColumn::get_MaxLength() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::get_MaxLength");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_MaxLength", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumn.set_MaxLength
void System::Data::DataColumn::set_MaxLength(int value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::set_MaxLength");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_MaxLength", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value);
}
// Autogenerated method: System.Data.DataColumn.get_Namespace
::StringW System::Data::DataColumn::get_Namespace() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::get_Namespace");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_Namespace", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<::StringW, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumn.set_Namespace
void System::Data::DataColumn::set_Namespace(::StringW value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::set_Namespace");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_Namespace", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value);
}
// Autogenerated method: System.Data.DataColumn.get_Ordinal
int System::Data::DataColumn::get_Ordinal() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::get_Ordinal");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_Ordinal", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumn.get_ReadOnly
bool System::Data::DataColumn::get_ReadOnly() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::get_ReadOnly");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_ReadOnly", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumn.set_ReadOnly
void System::Data::DataColumn::set_ReadOnly(bool value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::set_ReadOnly");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_ReadOnly", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value);
}
// Autogenerated method: System.Data.DataColumn.get_SortIndex
::System::Data::Index* System::Data::DataColumn::get_SortIndex() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::get_SortIndex");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_SortIndex", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<::System::Data::Index*, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumn.get_Table
::System::Data::DataTable* System::Data::DataColumn::get_Table() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::get_Table");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_Table", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<::System::Data::DataTable*, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumn.get_Item
::Il2CppObject* System::Data::DataColumn::get_Item(int record) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::get_Item");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_Item", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(record)})));
return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method, record);
}
// Autogenerated method: System.Data.DataColumn.set_Item
void System::Data::DataColumn::set_Item(int record, ::Il2CppObject* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::set_Item");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_Item", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(record), ::il2cpp_utils::ExtractType(value)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, record, value);
}
// Autogenerated method: System.Data.DataColumn.get_Unique
bool System::Data::DataColumn::get_Unique() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::get_Unique");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_Unique", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumn.set_Unique
void System::Data::DataColumn::set_Unique(bool value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::set_Unique");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_Unique", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value);
}
// Autogenerated method: System.Data.DataColumn.get_XmlDataType
::StringW System::Data::DataColumn::get_XmlDataType() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::get_XmlDataType");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_XmlDataType", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<::StringW, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumn.set_XmlDataType
void System::Data::DataColumn::set_XmlDataType(::StringW value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::set_XmlDataType");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_XmlDataType", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value);
}
// Autogenerated method: System.Data.DataColumn.get_SimpleType
::System::Data::SimpleType* System::Data::DataColumn::get_SimpleType() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::get_SimpleType");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_SimpleType", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<::System::Data::SimpleType*, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumn.set_SimpleType
void System::Data::DataColumn::set_SimpleType(::System::Data::SimpleType* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::set_SimpleType");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_SimpleType", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value);
}
// Autogenerated method: System.Data.DataColumn.get_ColumnMapping
::System::Data::MappingType System::Data::DataColumn::get_ColumnMapping() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::get_ColumnMapping");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::DataColumn*), 10));
return ::il2cpp_utils::RunMethodRethrow<::System::Data::MappingType, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumn.set_ColumnMapping
void System::Data::DataColumn::set_ColumnMapping(::System::Data::MappingType value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::set_ColumnMapping");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::DataColumn*), 11));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value);
}
// Autogenerated method: System.Data.DataColumn.get_IsCustomType
bool System::Data::DataColumn::get_IsCustomType() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::get_IsCustomType");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_IsCustomType", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumn.get_ImplementsIXMLSerializable
bool System::Data::DataColumn::get_ImplementsIXMLSerializable() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::get_ImplementsIXMLSerializable");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_ImplementsIXMLSerializable", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumn.UpdateColumnType
void System::Data::DataColumn::UpdateColumnType(::System::Type* type, ::System::Data::Common::StorageType typeCode) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::UpdateColumnType");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "UpdateColumnType", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(type), ::il2cpp_utils::ExtractType(typeCode)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, type, typeCode);
}
// Autogenerated method: System.Data.DataColumn.GetColumnValueAsString
::StringW System::Data::DataColumn::GetColumnValueAsString(::System::Data::DataRow* row, ::System::Data::DataRowVersion version) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::GetColumnValueAsString");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "GetColumnValueAsString", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(row), ::il2cpp_utils::ExtractType(version)})));
return ::il2cpp_utils::RunMethodRethrow<::StringW, false>(this, ___internal__method, row, version);
}
// Autogenerated method: System.Data.DataColumn.SetMaxLengthSimpleType
void System::Data::DataColumn::SetMaxLengthSimpleType() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::SetMaxLengthSimpleType");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "SetMaxLengthSimpleType", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumn.SetOrdinalInternal
void System::Data::DataColumn::SetOrdinalInternal(int ordinal) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::SetOrdinalInternal");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "SetOrdinalInternal", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(ordinal)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, ordinal);
}
// Autogenerated method: System.Data.DataColumn.SetTable
void System::Data::DataColumn::SetTable(::System::Data::DataTable* table) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::SetTable");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "SetTable", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(table)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, table);
}
// Autogenerated method: System.Data.DataColumn.GetDataRow
::System::Data::DataRow* System::Data::DataColumn::GetDataRow(int index) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::GetDataRow");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "GetDataRow", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(index)})));
return ::il2cpp_utils::RunMethodRethrow<::System::Data::DataRow*, false>(this, ___internal__method, index);
}
// Autogenerated method: System.Data.DataColumn.InitializeRecord
void System::Data::DataColumn::InitializeRecord(int record) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::InitializeRecord");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "InitializeRecord", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(record)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, record);
}
// Autogenerated method: System.Data.DataColumn.SetValue
void System::Data::DataColumn::SetValue(int record, ::Il2CppObject* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::SetValue");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "SetValue", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(record), ::il2cpp_utils::ExtractType(value)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, record, value);
}
// Autogenerated method: System.Data.DataColumn.FreeRecord
void System::Data::DataColumn::FreeRecord(int record) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::FreeRecord");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "FreeRecord", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(record)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, record);
}
// Autogenerated method: System.Data.DataColumn.InternalUnique
void System::Data::DataColumn::InternalUnique(bool value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::InternalUnique");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "InternalUnique", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value);
}
// Autogenerated method: System.Data.DataColumn.CheckColumnConstraint
void System::Data::DataColumn::CheckColumnConstraint(::System::Data::DataRow* row, ::System::Data::DataRowAction action) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::CheckColumnConstraint");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "CheckColumnConstraint", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(row), ::il2cpp_utils::ExtractType(action)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, row, action);
}
// Autogenerated method: System.Data.DataColumn.CheckMaxLength
bool System::Data::DataColumn::CheckMaxLength() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::CheckMaxLength");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "CheckMaxLength", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumn.CheckMaxLength
void System::Data::DataColumn::CheckMaxLength(::System::Data::DataRow* dr) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::CheckMaxLength");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "CheckMaxLength", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(dr)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, dr);
}
// Autogenerated method: System.Data.DataColumn.CheckNotAllowNull
void System::Data::DataColumn::CheckNotAllowNull() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::CheckNotAllowNull");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "CheckNotAllowNull", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumn.CheckNullable
void System::Data::DataColumn::CheckNullable(::System::Data::DataRow* row) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::CheckNullable");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "CheckNullable", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(row)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, row);
}
// Autogenerated method: System.Data.DataColumn.CheckUnique
void System::Data::DataColumn::CheckUnique() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::CheckUnique");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "CheckUnique", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumn.Compare
int System::Data::DataColumn::Compare(int record1, int record2) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::Compare");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Compare", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(record1), ::il2cpp_utils::ExtractType(record2)})));
return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method, record1, record2);
}
// Autogenerated method: System.Data.DataColumn.CompareValueTo
bool System::Data::DataColumn::CompareValueTo(int record1, ::Il2CppObject* value, bool checkType) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::CompareValueTo");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "CompareValueTo", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(record1), ::il2cpp_utils::ExtractType(value), ::il2cpp_utils::ExtractType(checkType)})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, record1, value, checkType);
}
// Autogenerated method: System.Data.DataColumn.CompareValueTo
int System::Data::DataColumn::CompareValueTo(int record1, ::Il2CppObject* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::CompareValueTo");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "CompareValueTo", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(record1), ::il2cpp_utils::ExtractType(value)})));
return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method, record1, value);
}
// Autogenerated method: System.Data.DataColumn.ConvertValue
::Il2CppObject* System::Data::DataColumn::ConvertValue(::Il2CppObject* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::ConvertValue");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "ConvertValue", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));
return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method, value);
}
// Autogenerated method: System.Data.DataColumn.Copy
void System::Data::DataColumn::Copy(int srcRecordNo, int dstRecordNo) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::Copy");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Copy", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(srcRecordNo), ::il2cpp_utils::ExtractType(dstRecordNo)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, srcRecordNo, dstRecordNo);
}
// Autogenerated method: System.Data.DataColumn.Clone
::System::Data::DataColumn* System::Data::DataColumn::Clone() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::Clone");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Clone", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<::System::Data::DataColumn*, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumn.GetAggregateValue
::Il2CppObject* System::Data::DataColumn::GetAggregateValue(::ArrayW<int> records, ::System::Data::AggregateType kind) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::GetAggregateValue");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "GetAggregateValue", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(records), ::il2cpp_utils::ExtractType(kind)})));
return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method, records, kind);
}
// Autogenerated method: System.Data.DataColumn.GetStringLength
int System::Data::DataColumn::GetStringLength(int record) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::GetStringLength");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "GetStringLength", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(record)})));
return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method, record);
}
// Autogenerated method: System.Data.DataColumn.Init
void System::Data::DataColumn::Init(int record) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::Init");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Init", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(record)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, record);
}
// Autogenerated method: System.Data.DataColumn.IsAutoIncrementType
bool System::Data::DataColumn::IsAutoIncrementType(::System::Type* dataType) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::IsAutoIncrementType");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Data", "DataColumn", "IsAutoIncrementType", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(dataType)})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, dataType);
}
// Autogenerated method: System.Data.DataColumn.IsValueCustomTypeInstance
bool System::Data::DataColumn::IsValueCustomTypeInstance(::Il2CppObject* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::IsValueCustomTypeInstance");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "IsValueCustomTypeInstance", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, value);
}
// Autogenerated method: System.Data.DataColumn.IsInRelation
bool System::Data::DataColumn::IsInRelation() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::IsInRelation");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "IsInRelation", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumn.IsMaxLengthViolated
bool System::Data::DataColumn::IsMaxLengthViolated() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::IsMaxLengthViolated");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "IsMaxLengthViolated", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumn.IsNotAllowDBNullViolated
bool System::Data::DataColumn::IsNotAllowDBNullViolated() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::IsNotAllowDBNullViolated");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "IsNotAllowDBNullViolated", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumn.OnPropertyChanging
void System::Data::DataColumn::OnPropertyChanging(::System::ComponentModel::PropertyChangedEventArgs* pcevent) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::OnPropertyChanging");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::DataColumn*), 12));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, pcevent);
}
// Autogenerated method: System.Data.DataColumn.RaisePropertyChanging
void System::Data::DataColumn::RaisePropertyChanging(::StringW name) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::RaisePropertyChanging");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "RaisePropertyChanging", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(name)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, name);
}
// Autogenerated method: System.Data.DataColumn.InsureStorage
void System::Data::DataColumn::InsureStorage() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::InsureStorage");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "InsureStorage", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumn.SetCapacity
void System::Data::DataColumn::SetCapacity(int capacity) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::SetCapacity");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "SetCapacity", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(capacity)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, capacity);
}
// Autogenerated method: System.Data.DataColumn.OnSetDataSet
void System::Data::DataColumn::OnSetDataSet() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::OnSetDataSet");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "OnSetDataSet", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumn.ConvertXmlToObject
::Il2CppObject* System::Data::DataColumn::ConvertXmlToObject(::StringW s) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::ConvertXmlToObject");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "ConvertXmlToObject", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(s)})));
return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method, s);
}
// Autogenerated method: System.Data.DataColumn.ConvertXmlToObject
::Il2CppObject* System::Data::DataColumn::ConvertXmlToObject(::System::Xml::XmlReader* xmlReader, ::System::Xml::Serialization::XmlRootAttribute* xmlAttrib) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::ConvertXmlToObject");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "ConvertXmlToObject", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(xmlReader), ::il2cpp_utils::ExtractType(xmlAttrib)})));
return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method, xmlReader, xmlAttrib);
}
// Autogenerated method: System.Data.DataColumn.ConvertObjectToXml
::StringW System::Data::DataColumn::ConvertObjectToXml(::Il2CppObject* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::ConvertObjectToXml");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "ConvertObjectToXml", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));
return ::il2cpp_utils::RunMethodRethrow<::StringW, false>(this, ___internal__method, value);
}
// Autogenerated method: System.Data.DataColumn.ConvertObjectToXml
void System::Data::DataColumn::ConvertObjectToXml(::Il2CppObject* value, ::System::Xml::XmlWriter* xmlWriter, ::System::Xml::Serialization::XmlRootAttribute* xmlAttrib) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::ConvertObjectToXml");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "ConvertObjectToXml", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value), ::il2cpp_utils::ExtractType(xmlWriter), ::il2cpp_utils::ExtractType(xmlAttrib)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value, xmlWriter, xmlAttrib);
}
// Autogenerated method: System.Data.DataColumn.GetEmptyColumnStore
::Il2CppObject* System::Data::DataColumn::GetEmptyColumnStore(int recordCount) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::GetEmptyColumnStore");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "GetEmptyColumnStore", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(recordCount)})));
return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method, recordCount);
}
// Autogenerated method: System.Data.DataColumn.CopyValueIntoStore
void System::Data::DataColumn::CopyValueIntoStore(int record, ::Il2CppObject* store, ::System::Collections::BitArray* nullbits, int storeIndex) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::CopyValueIntoStore");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "CopyValueIntoStore", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(record), ::il2cpp_utils::ExtractType(store), ::il2cpp_utils::ExtractType(nullbits), ::il2cpp_utils::ExtractType(storeIndex)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, record, store, nullbits, storeIndex);
}
// Autogenerated method: System.Data.DataColumn.SetStorage
void System::Data::DataColumn::SetStorage(::Il2CppObject* store, ::System::Collections::BitArray* nullbits) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::SetStorage");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "SetStorage", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(store), ::il2cpp_utils::ExtractType(nullbits)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, store, nullbits);
}
// Autogenerated method: System.Data.DataColumn.AddDependentColumn
void System::Data::DataColumn::AddDependentColumn(::System::Data::DataColumn* expressionColumn) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::AddDependentColumn");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "AddDependentColumn", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(expressionColumn)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, expressionColumn);
}
// Autogenerated method: System.Data.DataColumn.RemoveDependentColumn
void System::Data::DataColumn::RemoveDependentColumn(::System::Data::DataColumn* expressionColumn) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::RemoveDependentColumn");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "RemoveDependentColumn", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(expressionColumn)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, expressionColumn);
}
// Autogenerated method: System.Data.DataColumn.HandleDependentColumnList
void System::Data::DataColumn::HandleDependentColumnList(::System::Data::DataExpression* oldExpression, ::System::Data::DataExpression* newExpression) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::HandleDependentColumnList");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "HandleDependentColumnList", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(oldExpression), ::il2cpp_utils::ExtractType(newExpression)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, oldExpression, newExpression);
}
// Autogenerated method: System.Data.DataColumn.ToString
::StringW System::Data::DataColumn::ToString() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumn::ToString");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::ComponentModel::MarshalByValueComponent*), 3));
return ::il2cpp_utils::RunMethodRethrow<::StringW, false>(this, ___internal__method);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
// Including type: System.Data.AutoIncrementValue
#include "System/Data/AutoIncrementValue.hpp"
// Including type: System.Type
#include "System/Type.hpp"
// Including type: System.IFormatProvider
#include "System/IFormatProvider.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated instance field getter
// Get instance field: private System.Boolean <Auto>k__BackingField
[[deprecated("Use field access instead!")]] bool& System::Data::AutoIncrementValue::dyn_$Auto$k__BackingField() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AutoIncrementValue::dyn_$Auto$k__BackingField");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "<Auto>k__BackingField"))->offset;
return *reinterpret_cast<bool*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated method: System.Data.AutoIncrementValue.get_Auto
bool System::Data::AutoIncrementValue::get_Auto() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AutoIncrementValue::get_Auto");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_Auto", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.AutoIncrementValue.set_Auto
void System::Data::AutoIncrementValue::set_Auto(bool value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AutoIncrementValue::set_Auto");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_Auto", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value);
}
// Autogenerated method: System.Data.AutoIncrementValue.get_Current
::Il2CppObject* System::Data::AutoIncrementValue::get_Current() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AutoIncrementValue::get_Current");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::AutoIncrementValue*), -1));
return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.AutoIncrementValue.set_Current
void System::Data::AutoIncrementValue::set_Current(::Il2CppObject* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AutoIncrementValue::set_Current");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::AutoIncrementValue*), -1));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value);
}
// Autogenerated method: System.Data.AutoIncrementValue.get_Seed
int64_t System::Data::AutoIncrementValue::get_Seed() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AutoIncrementValue::get_Seed");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::AutoIncrementValue*), -1));
return ::il2cpp_utils::RunMethodRethrow<int64_t, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.AutoIncrementValue.set_Seed
void System::Data::AutoIncrementValue::set_Seed(int64_t value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AutoIncrementValue::set_Seed");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::AutoIncrementValue*), -1));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value);
}
// Autogenerated method: System.Data.AutoIncrementValue.get_Step
int64_t System::Data::AutoIncrementValue::get_Step() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AutoIncrementValue::get_Step");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::AutoIncrementValue*), -1));
return ::il2cpp_utils::RunMethodRethrow<int64_t, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.AutoIncrementValue.set_Step
void System::Data::AutoIncrementValue::set_Step(int64_t value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AutoIncrementValue::set_Step");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::AutoIncrementValue*), -1));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value);
}
// Autogenerated method: System.Data.AutoIncrementValue.get_DataType
::System::Type* System::Data::AutoIncrementValue::get_DataType() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AutoIncrementValue::get_DataType");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::AutoIncrementValue*), -1));
return ::il2cpp_utils::RunMethodRethrow<::System::Type*, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.AutoIncrementValue.SetCurrent
void System::Data::AutoIncrementValue::SetCurrent(::Il2CppObject* value, ::System::IFormatProvider* formatProvider) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AutoIncrementValue::SetCurrent");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::AutoIncrementValue*), -1));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value, formatProvider);
}
// Autogenerated method: System.Data.AutoIncrementValue.SetCurrentAndIncrement
void System::Data::AutoIncrementValue::SetCurrentAndIncrement(::Il2CppObject* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AutoIncrementValue::SetCurrentAndIncrement");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::AutoIncrementValue*), -1));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value);
}
// Autogenerated method: System.Data.AutoIncrementValue.MoveAfter
void System::Data::AutoIncrementValue::MoveAfter() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AutoIncrementValue::MoveAfter");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::AutoIncrementValue*), -1));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.AutoIncrementValue.Clone
::System::Data::AutoIncrementValue* System::Data::AutoIncrementValue::Clone() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AutoIncrementValue::Clone");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Clone", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<::System::Data::AutoIncrementValue*, false>(this, ___internal__method);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
// Including type: System.Data.AutoIncrementInt64
#include "System/Data/AutoIncrementInt64.hpp"
// Including type: System.Numerics.BigInteger
#include "System/Numerics/BigInteger.hpp"
// Including type: System.Type
#include "System/Type.hpp"
// Including type: System.IFormatProvider
#include "System/IFormatProvider.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated instance field getter
// Get instance field: private System.Int64 _current
[[deprecated("Use field access instead!")]] int64_t& System::Data::AutoIncrementInt64::dyn__current() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AutoIncrementInt64::dyn__current");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_current"))->offset;
return *reinterpret_cast<int64_t*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.Int64 _seed
[[deprecated("Use field access instead!")]] int64_t& System::Data::AutoIncrementInt64::dyn__seed() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AutoIncrementInt64::dyn__seed");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_seed"))->offset;
return *reinterpret_cast<int64_t*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.Int64 _step
[[deprecated("Use field access instead!")]] int64_t& System::Data::AutoIncrementInt64::dyn__step() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AutoIncrementInt64::dyn__step");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_step"))->offset;
return *reinterpret_cast<int64_t*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated method: System.Data.AutoIncrementInt64.BoundaryCheck
bool System::Data::AutoIncrementInt64::BoundaryCheck(::System::Numerics::BigInteger value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AutoIncrementInt64::BoundaryCheck");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "BoundaryCheck", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, value);
}
// Autogenerated method: System.Data.AutoIncrementInt64.get_Current
::Il2CppObject* System::Data::AutoIncrementInt64::get_Current() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AutoIncrementInt64::get_Current");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::AutoIncrementValue*), 4));
return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.AutoIncrementInt64.set_Current
void System::Data::AutoIncrementInt64::set_Current(::Il2CppObject* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AutoIncrementInt64::set_Current");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::AutoIncrementValue*), 5));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value);
}
// Autogenerated method: System.Data.AutoIncrementInt64.get_DataType
::System::Type* System::Data::AutoIncrementInt64::get_DataType() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AutoIncrementInt64::get_DataType");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::AutoIncrementValue*), 10));
return ::il2cpp_utils::RunMethodRethrow<::System::Type*, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.AutoIncrementInt64.get_Seed
int64_t System::Data::AutoIncrementInt64::get_Seed() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AutoIncrementInt64::get_Seed");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::AutoIncrementValue*), 6));
return ::il2cpp_utils::RunMethodRethrow<int64_t, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.AutoIncrementInt64.set_Seed
void System::Data::AutoIncrementInt64::set_Seed(int64_t value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AutoIncrementInt64::set_Seed");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::AutoIncrementValue*), 7));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value);
}
// Autogenerated method: System.Data.AutoIncrementInt64.get_Step
int64_t System::Data::AutoIncrementInt64::get_Step() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AutoIncrementInt64::get_Step");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::AutoIncrementValue*), 8));
return ::il2cpp_utils::RunMethodRethrow<int64_t, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.AutoIncrementInt64.set_Step
void System::Data::AutoIncrementInt64::set_Step(int64_t value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AutoIncrementInt64::set_Step");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::AutoIncrementValue*), 9));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value);
}
// Autogenerated method: System.Data.AutoIncrementInt64.MoveAfter
void System::Data::AutoIncrementInt64::MoveAfter() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AutoIncrementInt64::MoveAfter");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::AutoIncrementValue*), 13));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.AutoIncrementInt64.SetCurrent
void System::Data::AutoIncrementInt64::SetCurrent(::Il2CppObject* value, ::System::IFormatProvider* formatProvider) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AutoIncrementInt64::SetCurrent");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::AutoIncrementValue*), 11));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value, formatProvider);
}
// Autogenerated method: System.Data.AutoIncrementInt64.SetCurrentAndIncrement
void System::Data::AutoIncrementInt64::SetCurrentAndIncrement(::Il2CppObject* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AutoIncrementInt64::SetCurrentAndIncrement");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::AutoIncrementValue*), 12));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
// Including type: System.Data.AutoIncrementBigInteger
#include "System/Data/AutoIncrementBigInteger.hpp"
// Including type: System.Type
#include "System/Type.hpp"
// Including type: System.IFormatProvider
#include "System/IFormatProvider.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated instance field getter
// Get instance field: private System.Numerics.BigInteger _current
[[deprecated("Use field access instead!")]] ::System::Numerics::BigInteger& System::Data::AutoIncrementBigInteger::dyn__current() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AutoIncrementBigInteger::dyn__current");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_current"))->offset;
return *reinterpret_cast<::System::Numerics::BigInteger*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.Int64 _seed
[[deprecated("Use field access instead!")]] int64_t& System::Data::AutoIncrementBigInteger::dyn__seed() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AutoIncrementBigInteger::dyn__seed");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_seed"))->offset;
return *reinterpret_cast<int64_t*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.Numerics.BigInteger _step
[[deprecated("Use field access instead!")]] ::System::Numerics::BigInteger& System::Data::AutoIncrementBigInteger::dyn__step() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AutoIncrementBigInteger::dyn__step");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_step"))->offset;
return *reinterpret_cast<::System::Numerics::BigInteger*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated method: System.Data.AutoIncrementBigInteger.BoundaryCheck
bool System::Data::AutoIncrementBigInteger::BoundaryCheck(::System::Numerics::BigInteger value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AutoIncrementBigInteger::BoundaryCheck");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "BoundaryCheck", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, value);
}
// Autogenerated method: System.Data.AutoIncrementBigInteger.get_Current
::Il2CppObject* System::Data::AutoIncrementBigInteger::get_Current() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AutoIncrementBigInteger::get_Current");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::AutoIncrementValue*), 4));
return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.AutoIncrementBigInteger.set_Current
void System::Data::AutoIncrementBigInteger::set_Current(::Il2CppObject* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AutoIncrementBigInteger::set_Current");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::AutoIncrementValue*), 5));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value);
}
// Autogenerated method: System.Data.AutoIncrementBigInteger.get_DataType
::System::Type* System::Data::AutoIncrementBigInteger::get_DataType() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AutoIncrementBigInteger::get_DataType");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::AutoIncrementValue*), 10));
return ::il2cpp_utils::RunMethodRethrow<::System::Type*, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.AutoIncrementBigInteger.get_Seed
int64_t System::Data::AutoIncrementBigInteger::get_Seed() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AutoIncrementBigInteger::get_Seed");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::AutoIncrementValue*), 6));
return ::il2cpp_utils::RunMethodRethrow<int64_t, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.AutoIncrementBigInteger.set_Seed
void System::Data::AutoIncrementBigInteger::set_Seed(int64_t value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AutoIncrementBigInteger::set_Seed");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::AutoIncrementValue*), 7));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value);
}
// Autogenerated method: System.Data.AutoIncrementBigInteger.get_Step
int64_t System::Data::AutoIncrementBigInteger::get_Step() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AutoIncrementBigInteger::get_Step");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::AutoIncrementValue*), 8));
return ::il2cpp_utils::RunMethodRethrow<int64_t, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.AutoIncrementBigInteger.set_Step
void System::Data::AutoIncrementBigInteger::set_Step(int64_t value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AutoIncrementBigInteger::set_Step");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::AutoIncrementValue*), 9));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value);
}
// Autogenerated method: System.Data.AutoIncrementBigInteger.MoveAfter
void System::Data::AutoIncrementBigInteger::MoveAfter() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AutoIncrementBigInteger::MoveAfter");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::AutoIncrementValue*), 13));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.AutoIncrementBigInteger.SetCurrent
void System::Data::AutoIncrementBigInteger::SetCurrent(::Il2CppObject* value, ::System::IFormatProvider* formatProvider) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AutoIncrementBigInteger::SetCurrent");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::AutoIncrementValue*), 11));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value, formatProvider);
}
// Autogenerated method: System.Data.AutoIncrementBigInteger.SetCurrentAndIncrement
void System::Data::AutoIncrementBigInteger::SetCurrentAndIncrement(::Il2CppObject* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::AutoIncrementBigInteger::SetCurrentAndIncrement");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::AutoIncrementValue*), 12));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
// Including type: System.Data.DataColumnChangeEventArgs
#include "System/Data/DataColumnChangeEventArgs.hpp"
// Including type: System.Data.DataColumn
#include "System/Data/DataColumn.hpp"
// Including type: System.Data.DataRow
#include "System/Data/DataRow.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated instance field getter
// Get instance field: private System.Data.DataColumn _column
[[deprecated("Use field access instead!")]] ::System::Data::DataColumn*& System::Data::DataColumnChangeEventArgs::dyn__column() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnChangeEventArgs::dyn__column");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_column"))->offset;
return *reinterpret_cast<::System::Data::DataColumn**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private readonly System.Data.DataRow <Row>k__BackingField
[[deprecated("Use field access instead!")]] ::System::Data::DataRow*& System::Data::DataColumnChangeEventArgs::dyn_$Row$k__BackingField() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnChangeEventArgs::dyn_$Row$k__BackingField");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "<Row>k__BackingField"))->offset;
return *reinterpret_cast<::System::Data::DataRow**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.Object <ProposedValue>k__BackingField
[[deprecated("Use field access instead!")]] ::Il2CppObject*& System::Data::DataColumnChangeEventArgs::dyn_$ProposedValue$k__BackingField() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnChangeEventArgs::dyn_$ProposedValue$k__BackingField");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "<ProposedValue>k__BackingField"))->offset;
return *reinterpret_cast<::Il2CppObject**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated method: System.Data.DataColumnChangeEventArgs.get_ProposedValue
::Il2CppObject* System::Data::DataColumnChangeEventArgs::get_ProposedValue() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnChangeEventArgs::get_ProposedValue");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_ProposedValue", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumnChangeEventArgs.set_ProposedValue
void System::Data::DataColumnChangeEventArgs::set_ProposedValue(::Il2CppObject* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnChangeEventArgs::set_ProposedValue");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_ProposedValue", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value);
}
// Autogenerated method: System.Data.DataColumnChangeEventArgs.InitializeColumnChangeEvent
void System::Data::DataColumnChangeEventArgs::InitializeColumnChangeEvent(::System::Data::DataColumn* column, ::Il2CppObject* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnChangeEventArgs::InitializeColumnChangeEvent");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "InitializeColumnChangeEvent", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(column), ::il2cpp_utils::ExtractType(value)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, column, value);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
// Including type: System.Data.DataColumnChangeEventHandler
#include "System/Data/DataColumnChangeEventHandler.hpp"
// Including type: System.Data.DataColumnChangeEventArgs
#include "System/Data/DataColumnChangeEventArgs.hpp"
// Including type: System.IAsyncResult
#include "System/IAsyncResult.hpp"
// Including type: System.AsyncCallback
#include "System/AsyncCallback.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated method: System.Data.DataColumnChangeEventHandler.Invoke
void System::Data::DataColumnChangeEventHandler::Invoke(::Il2CppObject* sender, ::System::Data::DataColumnChangeEventArgs* e) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnChangeEventHandler::Invoke");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::DataColumnChangeEventHandler*), 12));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, sender, e);
}
// Autogenerated method: System.Data.DataColumnChangeEventHandler.BeginInvoke
::System::IAsyncResult* System::Data::DataColumnChangeEventHandler::BeginInvoke(::Il2CppObject* sender, ::System::Data::DataColumnChangeEventArgs* e, ::System::AsyncCallback* callback, ::Il2CppObject* object) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnChangeEventHandler::BeginInvoke");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::DataColumnChangeEventHandler*), 13));
return ::il2cpp_utils::RunMethodRethrow<::System::IAsyncResult*, false>(this, ___internal__method, sender, e, callback, object);
}
// Autogenerated method: System.Data.DataColumnChangeEventHandler.EndInvoke
void System::Data::DataColumnChangeEventHandler::EndInvoke(::System::IAsyncResult* result) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnChangeEventHandler::EndInvoke");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::DataColumnChangeEventHandler*), 14));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, result);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
// Including type: System.Data.DataColumnCollection
#include "System/Data/DataColumnCollection.hpp"
// Including type: System.Data.DataTable
#include "System/Data/DataTable.hpp"
// Including type: System.Collections.ArrayList
#include "System/Collections/ArrayList.hpp"
// Including type: System.Data.DataColumn
#include "System/Data/DataColumn.hpp"
// Including type: System.Collections.Generic.Dictionary`2
#include "System/Collections/Generic/Dictionary_2.hpp"
// Including type: System.ComponentModel.CollectionChangeEventHandler
#include "System/ComponentModel/CollectionChangeEventHandler.hpp"
// Including type: System.ComponentModel.CollectionChangeEventArgs
#include "System/ComponentModel/CollectionChangeEventArgs.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated instance field getter
// Get instance field: private readonly System.Data.DataTable _table
[[deprecated("Use field access instead!")]] ::System::Data::DataTable*& System::Data::DataColumnCollection::dyn__table() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnCollection::dyn__table");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_table"))->offset;
return *reinterpret_cast<::System::Data::DataTable**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private readonly System.Collections.ArrayList _list
[[deprecated("Use field access instead!")]] ::System::Collections::ArrayList*& System::Data::DataColumnCollection::dyn__list() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnCollection::dyn__list");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_list"))->offset;
return *reinterpret_cast<::System::Collections::ArrayList**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.Int32 _defaultNameIndex
[[deprecated("Use field access instead!")]] int& System::Data::DataColumnCollection::dyn__defaultNameIndex() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnCollection::dyn__defaultNameIndex");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_defaultNameIndex"))->offset;
return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.Data.DataColumn[] _delayedAddRangeColumns
[[deprecated("Use field access instead!")]] ::ArrayW<::System::Data::DataColumn*>& System::Data::DataColumnCollection::dyn__delayedAddRangeColumns() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnCollection::dyn__delayedAddRangeColumns");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_delayedAddRangeColumns"))->offset;
return *reinterpret_cast<::ArrayW<::System::Data::DataColumn*>*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private readonly System.Collections.Generic.Dictionary`2<System.String,System.Data.DataColumn> _columnFromName
[[deprecated("Use field access instead!")]] ::System::Collections::Generic::Dictionary_2<::StringW, ::System::Data::DataColumn*>*& System::Data::DataColumnCollection::dyn__columnFromName() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnCollection::dyn__columnFromName");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_columnFromName"))->offset;
return *reinterpret_cast<::System::Collections::Generic::Dictionary_2<::StringW, ::System::Data::DataColumn*>**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.Boolean _fInClear
[[deprecated("Use field access instead!")]] bool& System::Data::DataColumnCollection::dyn__fInClear() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnCollection::dyn__fInClear");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_fInClear"))->offset;
return *reinterpret_cast<bool*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.Data.DataColumn[] _columnsImplementingIChangeTracking
[[deprecated("Use field access instead!")]] ::ArrayW<::System::Data::DataColumn*>& System::Data::DataColumnCollection::dyn__columnsImplementingIChangeTracking() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnCollection::dyn__columnsImplementingIChangeTracking");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_columnsImplementingIChangeTracking"))->offset;
return *reinterpret_cast<::ArrayW<::System::Data::DataColumn*>*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.Int32 _nColumnsImplementingIChangeTracking
[[deprecated("Use field access instead!")]] int& System::Data::DataColumnCollection::dyn__nColumnsImplementingIChangeTracking() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnCollection::dyn__nColumnsImplementingIChangeTracking");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_nColumnsImplementingIChangeTracking"))->offset;
return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.Int32 _nColumnsImplementingIRevertibleChangeTracking
[[deprecated("Use field access instead!")]] int& System::Data::DataColumnCollection::dyn__nColumnsImplementingIRevertibleChangeTracking() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnCollection::dyn__nColumnsImplementingIRevertibleChangeTracking");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_nColumnsImplementingIRevertibleChangeTracking"))->offset;
return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.ComponentModel.CollectionChangeEventHandler CollectionChanged
[[deprecated("Use field access instead!")]] ::System::ComponentModel::CollectionChangeEventHandler*& System::Data::DataColumnCollection::dyn_CollectionChanged() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnCollection::dyn_CollectionChanged");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "CollectionChanged"))->offset;
return *reinterpret_cast<::System::ComponentModel::CollectionChangeEventHandler**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.ComponentModel.CollectionChangeEventHandler CollectionChanging
[[deprecated("Use field access instead!")]] ::System::ComponentModel::CollectionChangeEventHandler*& System::Data::DataColumnCollection::dyn_CollectionChanging() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnCollection::dyn_CollectionChanging");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "CollectionChanging"))->offset;
return *reinterpret_cast<::System::ComponentModel::CollectionChangeEventHandler**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.ComponentModel.CollectionChangeEventHandler ColumnPropertyChanged
[[deprecated("Use field access instead!")]] ::System::ComponentModel::CollectionChangeEventHandler*& System::Data::DataColumnCollection::dyn_ColumnPropertyChanged() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnCollection::dyn_ColumnPropertyChanged");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "ColumnPropertyChanged"))->offset;
return *reinterpret_cast<::System::ComponentModel::CollectionChangeEventHandler**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated method: System.Data.DataColumnCollection.get_ColumnsImplementingIChangeTracking
::ArrayW<::System::Data::DataColumn*> System::Data::DataColumnCollection::get_ColumnsImplementingIChangeTracking() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnCollection::get_ColumnsImplementingIChangeTracking");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_ColumnsImplementingIChangeTracking", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<::ArrayW<::System::Data::DataColumn*>, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumnCollection.get_ColumnsImplementingIChangeTrackingCount
int System::Data::DataColumnCollection::get_ColumnsImplementingIChangeTrackingCount() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnCollection::get_ColumnsImplementingIChangeTrackingCount");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_ColumnsImplementingIChangeTrackingCount", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumnCollection.get_ColumnsImplementingIRevertibleChangeTrackingCount
int System::Data::DataColumnCollection::get_ColumnsImplementingIRevertibleChangeTrackingCount() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnCollection::get_ColumnsImplementingIRevertibleChangeTrackingCount");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_ColumnsImplementingIRevertibleChangeTrackingCount", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumnCollection.get_Item
::System::Data::DataColumn* System::Data::DataColumnCollection::get_Item(int index) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnCollection::get_Item");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_Item", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(index)})));
return ::il2cpp_utils::RunMethodRethrow<::System::Data::DataColumn*, false>(this, ___internal__method, index);
}
// Autogenerated method: System.Data.DataColumnCollection.get_Item
::System::Data::DataColumn* System::Data::DataColumnCollection::get_Item(::StringW name) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnCollection::get_Item");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_Item", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(name)})));
return ::il2cpp_utils::RunMethodRethrow<::System::Data::DataColumn*, false>(this, ___internal__method, name);
}
// Autogenerated method: System.Data.DataColumnCollection.get_Item
::System::Data::DataColumn* System::Data::DataColumnCollection::get_Item(::StringW name, ::StringW ns) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnCollection::get_Item");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_Item", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(name), ::il2cpp_utils::ExtractType(ns)})));
return ::il2cpp_utils::RunMethodRethrow<::System::Data::DataColumn*, false>(this, ___internal__method, name, ns);
}
// Autogenerated method: System.Data.DataColumnCollection.add_CollectionChanged
void System::Data::DataColumnCollection::add_CollectionChanged(::System::ComponentModel::CollectionChangeEventHandler* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnCollection::add_CollectionChanged");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "add_CollectionChanged", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value);
}
// Autogenerated method: System.Data.DataColumnCollection.remove_CollectionChanged
void System::Data::DataColumnCollection::remove_CollectionChanged(::System::ComponentModel::CollectionChangeEventHandler* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnCollection::remove_CollectionChanged");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "remove_CollectionChanged", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value);
}
// Autogenerated method: System.Data.DataColumnCollection.add_ColumnPropertyChanged
void System::Data::DataColumnCollection::add_ColumnPropertyChanged(::System::ComponentModel::CollectionChangeEventHandler* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnCollection::add_ColumnPropertyChanged");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "add_ColumnPropertyChanged", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value);
}
// Autogenerated method: System.Data.DataColumnCollection.remove_ColumnPropertyChanged
void System::Data::DataColumnCollection::remove_ColumnPropertyChanged(::System::ComponentModel::CollectionChangeEventHandler* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnCollection::remove_ColumnPropertyChanged");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "remove_ColumnPropertyChanged", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value);
}
// Autogenerated method: System.Data.DataColumnCollection.Add
void System::Data::DataColumnCollection::Add(::System::Data::DataColumn* column) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnCollection::Add");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Add", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(column)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, column);
}
// Autogenerated method: System.Data.DataColumnCollection.AddAt
void System::Data::DataColumnCollection::AddAt(int index, ::System::Data::DataColumn* column) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnCollection::AddAt");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "AddAt", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(index), ::il2cpp_utils::ExtractType(column)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, index, column);
}
// Autogenerated method: System.Data.DataColumnCollection.ArrayAdd
void System::Data::DataColumnCollection::ArrayAdd(::System::Data::DataColumn* column) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnCollection::ArrayAdd");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "ArrayAdd", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(column)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, column);
}
// Autogenerated method: System.Data.DataColumnCollection.ArrayAdd
void System::Data::DataColumnCollection::ArrayAdd(int index, ::System::Data::DataColumn* column) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnCollection::ArrayAdd");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "ArrayAdd", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(index), ::il2cpp_utils::ExtractType(column)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, index, column);
}
// Autogenerated method: System.Data.DataColumnCollection.ArrayRemove
void System::Data::DataColumnCollection::ArrayRemove(::System::Data::DataColumn* column) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnCollection::ArrayRemove");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "ArrayRemove", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(column)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, column);
}
// Autogenerated method: System.Data.DataColumnCollection.AssignName
::StringW System::Data::DataColumnCollection::AssignName() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnCollection::AssignName");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "AssignName", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<::StringW, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumnCollection.BaseAdd
void System::Data::DataColumnCollection::BaseAdd(::System::Data::DataColumn* column) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnCollection::BaseAdd");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "BaseAdd", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(column)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, column);
}
// Autogenerated method: System.Data.DataColumnCollection.BaseGroupSwitch
void System::Data::DataColumnCollection::BaseGroupSwitch(::ArrayW<::System::Data::DataColumn*> oldArray, int oldLength, ::ArrayW<::System::Data::DataColumn*> newArray, int newLength) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnCollection::BaseGroupSwitch");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "BaseGroupSwitch", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(oldArray), ::il2cpp_utils::ExtractType(oldLength), ::il2cpp_utils::ExtractType(newArray), ::il2cpp_utils::ExtractType(newLength)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, oldArray, oldLength, newArray, newLength);
}
// Autogenerated method: System.Data.DataColumnCollection.BaseRemove
void System::Data::DataColumnCollection::BaseRemove(::System::Data::DataColumn* column) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnCollection::BaseRemove");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "BaseRemove", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(column)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, column);
}
// Autogenerated method: System.Data.DataColumnCollection.CanRemove
bool System::Data::DataColumnCollection::CanRemove(::System::Data::DataColumn* column, bool fThrowException) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnCollection::CanRemove");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "CanRemove", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(column), ::il2cpp_utils::ExtractType(fThrowException)})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, column, fThrowException);
}
// Autogenerated method: System.Data.DataColumnCollection.CheckIChangeTracking
void System::Data::DataColumnCollection::CheckIChangeTracking(::System::Data::DataColumn* column) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnCollection::CheckIChangeTracking");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "CheckIChangeTracking", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(column)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, column);
}
// Autogenerated method: System.Data.DataColumnCollection.Clear
void System::Data::DataColumnCollection::Clear() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnCollection::Clear");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Clear", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumnCollection.Contains
bool System::Data::DataColumnCollection::Contains(::StringW name) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnCollection::Contains");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Contains", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(name)})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, name);
}
// Autogenerated method: System.Data.DataColumnCollection.Contains
bool System::Data::DataColumnCollection::Contains(::StringW name, bool caseSensitive) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnCollection::Contains");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Contains", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(name), ::il2cpp_utils::ExtractType(caseSensitive)})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, name, caseSensitive);
}
// Autogenerated method: System.Data.DataColumnCollection.IndexOf
int System::Data::DataColumnCollection::IndexOf(::StringW columnName) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnCollection::IndexOf");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "IndexOf", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(columnName)})));
return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method, columnName);
}
// Autogenerated method: System.Data.DataColumnCollection.IndexOfCaseInsensitive
int System::Data::DataColumnCollection::IndexOfCaseInsensitive(::StringW name) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnCollection::IndexOfCaseInsensitive");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "IndexOfCaseInsensitive", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(name)})));
return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method, name);
}
// Autogenerated method: System.Data.DataColumnCollection.MakeName
::StringW System::Data::DataColumnCollection::MakeName(int index) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnCollection::MakeName");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "MakeName", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(index)})));
return ::il2cpp_utils::RunMethodRethrow<::StringW, false>(this, ___internal__method, index);
}
// Autogenerated method: System.Data.DataColumnCollection.OnCollectionChanged
void System::Data::DataColumnCollection::OnCollectionChanged(::System::ComponentModel::CollectionChangeEventArgs* ccevent) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnCollection::OnCollectionChanged");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "OnCollectionChanged", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(ccevent)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, ccevent);
}
// Autogenerated method: System.Data.DataColumnCollection.OnCollectionChanging
void System::Data::DataColumnCollection::OnCollectionChanging(::System::ComponentModel::CollectionChangeEventArgs* ccevent) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnCollection::OnCollectionChanging");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "OnCollectionChanging", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(ccevent)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, ccevent);
}
// Autogenerated method: System.Data.DataColumnCollection.OnColumnPropertyChanged
void System::Data::DataColumnCollection::OnColumnPropertyChanged(::System::ComponentModel::CollectionChangeEventArgs* ccevent) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnCollection::OnColumnPropertyChanged");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "OnColumnPropertyChanged", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(ccevent)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, ccevent);
}
// Autogenerated method: System.Data.DataColumnCollection.RegisterColumnName
void System::Data::DataColumnCollection::RegisterColumnName(::StringW name, ::System::Data::DataColumn* column) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnCollection::RegisterColumnName");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "RegisterColumnName", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(name), ::il2cpp_utils::ExtractType(column)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, name, column);
}
// Autogenerated method: System.Data.DataColumnCollection.CanRegisterName
bool System::Data::DataColumnCollection::CanRegisterName(::StringW name) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnCollection::CanRegisterName");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "CanRegisterName", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(name)})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, name);
}
// Autogenerated method: System.Data.DataColumnCollection.Remove
void System::Data::DataColumnCollection::Remove(::System::Data::DataColumn* column) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnCollection::Remove");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Remove", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(column)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, column);
}
// Autogenerated method: System.Data.DataColumnCollection.UnregisterName
void System::Data::DataColumnCollection::UnregisterName(::StringW name) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnCollection::UnregisterName");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "UnregisterName", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(name)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, name);
}
// Autogenerated method: System.Data.DataColumnCollection.AddColumnsImplementingIChangeTrackingList
void System::Data::DataColumnCollection::AddColumnsImplementingIChangeTrackingList(::System::Data::DataColumn* dataColumn) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnCollection::AddColumnsImplementingIChangeTrackingList");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "AddColumnsImplementingIChangeTrackingList", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(dataColumn)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, dataColumn);
}
// Autogenerated method: System.Data.DataColumnCollection.RemoveColumnsImplementingIChangeTrackingList
void System::Data::DataColumnCollection::RemoveColumnsImplementingIChangeTrackingList(::System::Data::DataColumn* dataColumn) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnCollection::RemoveColumnsImplementingIChangeTrackingList");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "RemoveColumnsImplementingIChangeTrackingList", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(dataColumn)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, dataColumn);
}
// Autogenerated method: System.Data.DataColumnCollection.get_List
::System::Collections::ArrayList* System::Data::DataColumnCollection::get_List() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnCollection::get_List");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Data::InternalDataCollectionBase*), 11));
return ::il2cpp_utils::RunMethodRethrow<::System::Collections::ArrayList*, false>(this, ___internal__method);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
// Including type: System.Data.DataColumnPropertyDescriptor
#include "System/Data/DataColumnPropertyDescriptor.hpp"
// Including type: System.Data.DataColumn
#include "System/Data/DataColumn.hpp"
// Including type: System.ComponentModel.AttributeCollection
#include "System/ComponentModel/AttributeCollection.hpp"
// Including type: System.Type
#include "System/Type.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated instance field getter
// Get instance field: private readonly System.Data.DataColumn <Column>k__BackingField
[[deprecated("Use field access instead!")]] ::System::Data::DataColumn*& System::Data::DataColumnPropertyDescriptor::dyn_$Column$k__BackingField() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnPropertyDescriptor::dyn_$Column$k__BackingField");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "<Column>k__BackingField"))->offset;
return *reinterpret_cast<::System::Data::DataColumn**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated method: System.Data.DataColumnPropertyDescriptor.get_Column
::System::Data::DataColumn* System::Data::DataColumnPropertyDescriptor::get_Column() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnPropertyDescriptor::get_Column");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_Column", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<::System::Data::DataColumn*, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumnPropertyDescriptor.get_Attributes
::System::ComponentModel::AttributeCollection* System::Data::DataColumnPropertyDescriptor::get_Attributes() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnPropertyDescriptor::get_Attributes");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::ComponentModel::MemberDescriptor*), 6));
return ::il2cpp_utils::RunMethodRethrow<::System::ComponentModel::AttributeCollection*, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumnPropertyDescriptor.get_ComponentType
::System::Type* System::Data::DataColumnPropertyDescriptor::get_ComponentType() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnPropertyDescriptor::get_ComponentType");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::ComponentModel::PropertyDescriptor*), 13));
return ::il2cpp_utils::RunMethodRethrow<::System::Type*, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumnPropertyDescriptor.get_IsReadOnly
bool System::Data::DataColumnPropertyDescriptor::get_IsReadOnly() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnPropertyDescriptor::get_IsReadOnly");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::ComponentModel::PropertyDescriptor*), 15));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumnPropertyDescriptor.get_PropertyType
::System::Type* System::Data::DataColumnPropertyDescriptor::get_PropertyType() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnPropertyDescriptor::get_PropertyType");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::ComponentModel::PropertyDescriptor*), 16));
return ::il2cpp_utils::RunMethodRethrow<::System::Type*, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumnPropertyDescriptor.Equals
bool System::Data::DataColumnPropertyDescriptor::Equals(::Il2CppObject* other) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnPropertyDescriptor::Equals");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::ComponentModel::PropertyDescriptor*), 0));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, other);
}
// Autogenerated method: System.Data.DataColumnPropertyDescriptor.GetHashCode
int System::Data::DataColumnPropertyDescriptor::GetHashCode() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnPropertyDescriptor::GetHashCode");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::ComponentModel::PropertyDescriptor*), 2));
return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataColumnPropertyDescriptor.GetValue
::Il2CppObject* System::Data::DataColumnPropertyDescriptor::GetValue(::Il2CppObject* component) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnPropertyDescriptor::GetValue");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::ComponentModel::PropertyDescriptor*), 17));
return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method, component);
}
// Autogenerated method: System.Data.DataColumnPropertyDescriptor.SetValue
void System::Data::DataColumnPropertyDescriptor::SetValue(::Il2CppObject* component, ::Il2CppObject* value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnPropertyDescriptor::SetValue");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::ComponentModel::PropertyDescriptor*), 19));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, component, value);
}
// Autogenerated method: System.Data.DataColumnPropertyDescriptor.ShouldSerializeValue
bool System::Data::DataColumnPropertyDescriptor::ShouldSerializeValue(::Il2CppObject* component) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataColumnPropertyDescriptor::ShouldSerializeValue");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::ComponentModel::PropertyDescriptor*), 20));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, component);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
// Including type: System.Data.DataError
#include "System/Data/DataError.hpp"
// Including type: System.Data.DataColumn
#include "System/Data/DataColumn.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated instance field getter
// Get instance field: private System.String _rowError
[[deprecated("Use field access instead!")]] ::StringW& System::Data::DataError::dyn__rowError() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataError::dyn__rowError");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_rowError"))->offset;
return *reinterpret_cast<::StringW*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.Int32 _count
[[deprecated("Use field access instead!")]] int& System::Data::DataError::dyn__count() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataError::dyn__count");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_count"))->offset;
return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field getter
// Get instance field: private System.Data.DataError/System.Data.ColumnError[] _errorList
[[deprecated("Use field access instead!")]] ::ArrayW<::System::Data::DataError::ColumnError>& System::Data::DataError::dyn__errorList() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataError::dyn__errorList");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_errorList"))->offset;
return *reinterpret_cast<::ArrayW<::System::Data::DataError::ColumnError>*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated method: System.Data.DataError.get_Text
::StringW System::Data::DataError::get_Text() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataError::get_Text");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_Text", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<::StringW, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataError.set_Text
void System::Data::DataError::set_Text(::StringW value) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataError::set_Text");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_Text", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value);
}
// Autogenerated method: System.Data.DataError.get_HasErrors
bool System::Data::DataError::get_HasErrors() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataError::get_HasErrors");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_HasErrors", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataError.SetColumnError
void System::Data::DataError::SetColumnError(::System::Data::DataColumn* column, ::StringW error) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataError::SetColumnError");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "SetColumnError", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(column), ::il2cpp_utils::ExtractType(error)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, column, error);
}
// Autogenerated method: System.Data.DataError.GetColumnError
::StringW System::Data::DataError::GetColumnError(::System::Data::DataColumn* column) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataError::GetColumnError");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "GetColumnError", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(column)})));
return ::il2cpp_utils::RunMethodRethrow<::StringW, false>(this, ___internal__method, column);
}
// Autogenerated method: System.Data.DataError.Clear
void System::Data::DataError::Clear(::System::Data::DataColumn* column) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataError::Clear");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Clear", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(column)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, column);
}
// Autogenerated method: System.Data.DataError.Clear
void System::Data::DataError::Clear() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataError::Clear");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Clear", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataError.GetColumnsInError
::ArrayW<::System::Data::DataColumn*> System::Data::DataError::GetColumnsInError() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataError::GetColumnsInError");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "GetColumnsInError", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<::ArrayW<::System::Data::DataColumn*>, false>(this, ___internal__method);
}
// Autogenerated method: System.Data.DataError.SetText
void System::Data::DataError::SetText(::StringW errorText) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataError::SetText");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "SetText", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(errorText)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, errorText);
}
// Autogenerated method: System.Data.DataError.IndexOf
int System::Data::DataError::IndexOf(::System::Data::DataColumn* column) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Data::DataError::IndexOf");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "IndexOf", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(column)})));
return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method, column);
}
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
// Including type: System.Data.DataException
#include "System/Data/DataException.hpp"
// Including type: System.Runtime.Serialization.SerializationInfo
#include "System/Runtime/Serialization/SerializationInfo.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
// Including type: System.Data.ConstraintException
#include "System/Data/ConstraintException.hpp"
// Including type: System.Runtime.Serialization.SerializationInfo
#include "System/Runtime/Serialization/SerializationInfo.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
// Including type: System.Data.DeletedRowInaccessibleException
#include "System/Data/DeletedRowInaccessibleException.hpp"
// Including type: System.Runtime.Serialization.SerializationInfo
#include "System/Runtime/Serialization/SerializationInfo.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
// Including type: System.Data.DuplicateNameException
#include "System/Data/DuplicateNameException.hpp"
// Including type: System.Runtime.Serialization.SerializationInfo
#include "System/Runtime/Serialization/SerializationInfo.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Autogenerated from CppSourceCreator
// Created by Sc2ad
// =========================================================================
// Begin includes
// Including type: System.Data.InRowChangingEventException
#include "System/Data/InRowChangingEventException.hpp"
// Including type: System.Runtime.Serialization.SerializationInfo
#include "System/Runtime/Serialization/SerializationInfo.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
| 86.175637 | 488 | 0.77905 | [
"object",
"vector"
] |
7d4de20e14a938a9998319b82a42fade628b6289 | 11,689 | cpp | C++ | training/src/compiler/training/base/layers/activations/impl/SoftMaxActivationCPU.cpp | steelONIONknight/bolt | 9bd3d08f2abb14435ca3ad0179889e48fa7e9b47 | [
"MIT"
] | null | null | null | training/src/compiler/training/base/layers/activations/impl/SoftMaxActivationCPU.cpp | steelONIONknight/bolt | 9bd3d08f2abb14435ca3ad0179889e48fa7e9b47 | [
"MIT"
] | null | null | null | training/src/compiler/training/base/layers/activations/impl/SoftMaxActivationCPU.cpp | steelONIONknight/bolt | 9bd3d08f2abb14435ca3ad0179889e48fa7e9b47 | [
"MIT"
] | null | null | null | // Copyright (C) 2022. Huawei Technologies Co., Ltd. All rights reserved.
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#include "SoftMaxActivationCPU.h"
#include "../SoftMaxActivation.h"
#include <algorithm>
#include <training/base/impl/ImplFactory.h>
namespace
{
std::tuple<size_t, size_t, size_t, size_t> reassign(raul::Dimension dim, size_t i, size_t j, size_t k, size_t q)
{
if (dim == raul::Dimension::Depth)
{
return std::make_tuple(j, i, k, q);
}
if (dim == raul::Dimension::Height)
{
return std::make_tuple(j, k, i, q);
}
return std::make_tuple(i, j, k, q);
}
bool reg1 = raul::TheImplFactory::Instance().regCPUFP32<raul::SoftMaxActivation, raul::SoftMaxActivationCPU<raul::MemoryManager>>();
bool reg2 = raul::TheImplFactory::Instance().regCPUFP16<raul::SoftMaxActivation, raul::SoftMaxActivationCPU<raul::MemoryManagerFP16>>();
} // anonymous namespace
namespace raul
{
template<typename MM>
void SoftMaxActivationCPU<MM>::forwardComputeImpl(NetworkMode)
{
Workflow& work = mLayer.mNetworkParams.mWorkflow;
const auto& inputs = work.getMemoryManager<MM>()[mLayer.mInputName];
auto& output = work.getMemoryManager<MM>()[mLayer.mOutputName];
const size_t batchSize = inputs.getBatchSize();
if (mLayer.mDimension == Dimension::Default)
{
for (size_t q = 0; q < batchSize; ++q)
{
size_t batchOffset = q * mLayer.mInputsCount;
auto sum = static_cast<typename MM::type>(0.0_dt);
auto max = (*std::max_element(inputs.begin() + batchOffset, inputs.begin() + batchOffset + mLayer.mInputsCount));
for (size_t i = 0; i < mLayer.mInputsCount; ++i)
{
output[batchOffset + i] = static_cast<typename MM::type>(std::exp(TODTYPE(inputs[batchOffset + i] - max)));
sum += output[batchOffset + i];
}
for (size_t i = 0; i < mLayer.mInputsCount; ++i)
{
output[batchOffset + i] /= sum;
}
}
}
else if (mLayer.mDimension == Dimension::Width)
{
size_t size = batchSize * inputs.getDepth() * inputs.getHeight();
auto input2D = inputs.reshape(yato::dims(size, inputs.getWidth()));
auto output2D = output.reshape(yato::dims(size, inputs.getWidth()));
#if defined(_OPENMP)
#pragma omp parallel for
#endif
for (size_t q = 0; q < size; ++q)
{
auto sum = 0.0_dt;
auto max = (*std::max_element(inputs.begin() + q * inputs.getWidth(), inputs.begin() + (q + 1) * inputs.getWidth()));
for (size_t i = 0; i < inputs.getWidth(); ++i)
{
output2D[q][i] = static_cast<typename MM::type>(std::exp(TODTYPE(input2D[q][i]) - max));
sum += output2D[q][i];
}
for (size_t i = 0; i < inputs.getWidth(); ++i)
{
output2D[q][i] = static_cast<typename MM::type>(TODTYPE(output2D[q][i]) / sum);
}
}
}
else
{
// Output Strides
auto outputShape = output.getShape();
const auto outputStrides = Common::getStrides(outputShape);
// Divisor strides
outputShape[static_cast<size_t>(mLayer.mDimension)] = 1;
const auto divStrides = Common::getStrides(outputShape);
// Reshape intput in 4D view
const auto input4D = inputs.get4DView();
auto inputShape = inputs.getShape();
// Pick chosen dimension
const auto chosenDimSize = inputShape[static_cast<size_t>(mLayer.mDimension)];
// Delete it
std::vector<size_t> otherDims;
size_t otherDimsSize = 1u;
for (size_t i = 0; i < inputShape.dimensions_num(); ++i)
{
if (i != static_cast<size_t>(mLayer.mDimension))
{
otherDims.push_back(inputShape[i]);
otherDimsSize *= inputShape[i];
}
}
// Store divisors
std::vector<raul::dtype> divisors(otherDimsSize, 0.0_dt);
// Store indices mapping
std::vector<size_t> divIndices(output.size(), 0u);
// Main loop
#if defined(_OPENMP)
#pragma omp parallel for
#endif
for (size_t j = 0; j < otherDims[0]; ++j)
{
for (size_t k = 0; k < otherDims[1]; ++k)
{
for (size_t q = 0; q < otherDims[2]; ++q)
{
auto max = 0.0_dt;
for (size_t i = 0; i < chosenDimSize; ++i)
{
auto [realI, realJ, realK, realQ] = reassign(mLayer.mDimension, i, j, k, q);
max = std::max(max, TODTYPE(input4D[realI][realJ][realK][realQ]));
}
for (size_t i = 0; i < chosenDimSize; ++i)
{
// Rearrange indices in proper way
auto [realI, realJ, realK, realQ] = reassign(mLayer.mDimension, i, j, k, q);
// Find offset in output and divisors
raul::shape outputIndices{ realI, realJ, realK, realQ };
const auto outputOffset = Common::indexesToOffset(outputIndices, outputStrides);
// Fill output with exp(input)
auto val = std::exp(TODTYPE(input4D[realI][realJ][realK][realQ]) - max);
output[outputOffset] = TOMMTYPE(val);
// Calculate reduce_sum(exp(input), axis=mDimension)
outputIndices[static_cast<size_t>(mLayer.mDimension)] = 1;
const auto divOffset = Common::indexesToOffset(outputIndices, divStrides);
divisors[divOffset] += val;
divIndices[outputOffset] = divOffset;
}
}
}
}
// Normalize values
#if defined(_OPENMP)
#pragma omp parallel for
#endif
for (size_t n = 0; n < output.size(); ++n)
{
output[n] = TOMMTYPE(TODTYPE(output[n]) / divisors[divIndices[n]]);
}
}
}
template<typename MM>
void SoftMaxActivationCPU<MM>::backwardComputeImpl()
{
Workflow& work = mLayer.mNetworkParams.mWorkflow;
const auto& output = work.getMemoryManager<MM>()[mLayer.mOutputName];
const size_t batchSize = output.getBatchSize();
////if (mLayer.mNetworkParams.isGradNeeded(mLayer.mInputName))
{
const auto& deltas = work.getMemoryManager<MM>()[mLayer.mOutputName.grad()];
auto& prevLayerDelta = work.getMemoryManager<MM>()[mLayer.mInputName.grad()];
if (mLayer.mDimension == Dimension::Default)
{
for (size_t q = 0; q < batchSize; ++q)
{
size_t batchOffset = q * mLayer.mInputsCount;
for (size_t i = 0; i < mLayer.mInputsCount; ++i)
{
auto sum = static_cast<typename MM::type>(0.0_dt);
for (size_t j = 0; j < mLayer.mInputsCount; ++j)
{
sum += deltas[batchOffset + j] *
((j == i) ? output[batchOffset + j] * (static_cast<typename MM::type>(1.0_dt) - output[batchOffset + j]) : -output[batchOffset + i] * output[batchOffset + j]);
}
prevLayerDelta[batchOffset + i] += sum;
}
}
}
else if (mLayer.mDimension == Dimension::Width)
{
size_t size = batchSize * deltas.getDepth() * deltas.getHeight();
auto deltas2D = deltas.reshape(yato::dims(size, deltas.getWidth()));
auto prevLayerDelta2D = prevLayerDelta.reshape(yato::dims(size, deltas.getWidth()));
auto output2D = output.reshape(yato::dims(size, deltas.getWidth()));
#if defined(_OPENMP)
#pragma omp parallel for
#endif
for (size_t q = 0; q < size; ++q)
{
for (size_t i = 0; i < deltas.getWidth(); ++i)
{
dtype sum = 0.0_dt;
for (size_t j = 0; j < deltas.getWidth(); ++j)
{
sum += TODTYPE(deltas2D[q][j]) * ((j == i) ? TODTYPE(output2D[q][j]) * (1.0_dt - TODTYPE(output2D[q][j])) : -TODTYPE(output2D[q][i]) * TODTYPE(output2D[q][j]));
}
prevLayerDelta2D[q][i] += static_cast<typename MM::type>(sum);
}
}
}
else
{
auto deltas4D = deltas.get4DView();
auto output4D = output.get4DView();
auto prevLayerDelta4D = prevLayerDelta.get4DView();
const auto outputShape = output.getShape();
const auto chosenDimSize = outputShape[static_cast<size_t>(mLayer.mDimension)];
std::vector<size_t> otherDims;
for (size_t i = 0; i < outputShape.dimensions_num(); ++i)
{
if (i != static_cast<size_t>(mLayer.mDimension))
{
otherDims.push_back(outputShape[i]);
}
}
#if defined(_OPENMP)
#pragma omp parallel for
#endif
for (size_t j = 0; j < otherDims[0]; ++j)
{
for (size_t k = 0; k < otherDims[1]; ++k)
{
for (size_t q = 0; q < otherDims[2]; ++q)
{
for (size_t i = 0; i < chosenDimSize; ++i)
{
raul::dtype sum = 0.0_dt;
auto [realI1, realJ1, realK1, realQ1] = reassign(mLayer.mDimension, i, j, k, q);
for (size_t n = 0; n < chosenDimSize; ++n)
{
auto [realI2, realJ2, realK2, realQ2] = reassign(mLayer.mDimension, n, j, k, q);
sum += TODTYPE(deltas4D[realI2][realJ2][realK2][realQ2]) *
((n == i) ? TODTYPE(output4D[realI1][realJ1][realK1][realQ1]) * (1.0_dt - TODTYPE(output4D[realI1][realJ1][realK1][realQ1]))
: -TODTYPE(output4D[realI1][realJ1][realK1][realQ1]) * TODTYPE(output4D[realI2][realJ2][realK2][realQ2]));
}
prevLayerDelta4D[realI1][realJ1][realK1][realQ1] += static_cast<typename MM::type>(sum);
}
}
}
}
}
}
}
template class SoftMaxActivationCPU<MemoryManager>;
template class SoftMaxActivationCPU<MemoryManagerFP16>;
} // namespace raul | 41.896057 | 190 | 0.548464 | [
"shape",
"vector"
] |
7d58c0fb5f1aa12445081023c69c5877d6a71e1e | 1,423 | cpp | C++ | HeatingControl/src/main.cpp | nagda91/HeatingControl | f0fbb3ec257761caadf2024651ae886b231680f0 | [
"Apache-2.0"
] | 2 | 2020-04-28T18:17:39.000Z | 2020-09-06T17:57:03.000Z | HeatingControl/src/main.cpp | nagda91/HeatingControl | f0fbb3ec257761caadf2024651ae886b231680f0 | [
"Apache-2.0"
] | 2 | 2021-01-24T16:32:14.000Z | 2021-02-12T14:52:40.000Z | HeatingControl/src/main.cpp | nagda91/HeatingControl | f0fbb3ec257761caadf2024651ae886b231680f0 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <fstream>
#include <string>
#include <ctime>
#include <time.h>
#include <sstream>
#include <vector>
#include <wiringPi.h>
#include <thread>
#include <mosquittopp.h>
#include <mosquitto.h>
#include "Core.h"
#define CLIENT_ID "HeatingControl"
#define MQTT_PORT 1883;
#define MQTT_TOPIC "topic"
#define MQTT_USER "USR"
#define MQTT_PWD "PSW"
using namespace std;
int main() {
/////wiringPi///// its not necessaary, but good to be here
wiringPiSetup();
pinMode(0, OUTPUT);
pinMode(1, OUTPUT);
pinMode(2, OUTPUT);
pinMode(3, OUTPUT);
digitalWrite(0, HIGH);
digitalWrite(1, HIGH);
digitalWrite(2, HIGH);
digitalWrite(3, HIGH);
/////wiringPi/////
////MQTT/////
class Core* iot_client;
//Connection data
char client_id[] = CLIENT_ID;
const char* USER = MQTT_USER;
const char* PASSW = MQTT_PWD;
char host[] = "localhost";
int port = MQTT_PORT;
string topicString = MQTT_TOPIC;
mosqpp::lib_init();
iot_client = new Core(client_id, host, port, USER, PASSW);
iot_client->loop_start();
////MQTT/////
//Starting the main thread
std::thread mainthread = iot_client->basicFuncthread();
//Starting the user interface
string comm;
do
{
cout << "Waiting for command: ";
cin >> comm;
cout << iot_client->commFunc(comm) << endl;
if (comm == "exit") {
mainthread.join();
iot_client->disconnect();
cout << "Bye!\n";
}
} while (comm != "exit");
return 0;
}
| 20.042254 | 59 | 0.672523 | [
"vector"
] |
7d64e3de27160d8dcebe6bc1b45bfa83fab5f10b | 13,409 | cpp | C++ | drivers/storage/volsnap/vss/server/tests/writer/writerconfig.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | drivers/storage/volsnap/vss/server/tests/writer/writerconfig.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | drivers/storage/volsnap/vss/server/tests/writer/writerconfig.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /*
**++
**
** Copyright (c) 2002 Microsoft Corporation
**
**
** Module Name:
**
** writerconfig.cpp
**
**
** Abstract:
**
** defines classes that encapsulate the Test writer's configuration
**
** Author:
**
** Reuven Lax [reuvenl] 04-June-2002
**
**
**
** Revision History:
**
**--
*/
////////////////////////////////////////////////////////////////////////
// Includes
#include "stdafx.h"
#include "writerconfig.h"
#include "vs_xml.hxx"
#include "msxml2.h"
#include <string>
#include <sstream>
#include <algorithm>
////////////////////////////////////////////////////////////////////////
// Declarations
using Utility::checkReturn;
using Utility::AutoCS;
using std::wstring;
using std::wstringstream;
namespace XMLData {
// names of attributes and elements
wchar_t Name[] =L"name";
wchar_t Xmlns[] = L"xmlns";
wchar_t SchemaPointer[] = L"x-schema:#VssTestWriterConfig";
wchar_t RootStart[] = L"<root>";
wchar_t RootEnd[] = L"</root>\n";
wchar_t Root[] = L"root";
wchar_t TestWriter[] = L"TestWriter";
wchar_t Verbosity[] = L"verbosity";
wchar_t CheckExcludes[] = L"checkExcludes";
wchar_t CheckIncludes[] = L"checkIncludes";
wchar_t Path[] = L"path";
wchar_t Filespec[] = L"filespec";
wchar_t Recursive[] = L"recursive";
wchar_t AlternatePath[] = L"alternatePath";
wchar_t Usage[] = L"usage";
wchar_t RestoreMethod[] = L"RestoreMethod";
wchar_t Method[] = L"method";
wchar_t WriterRestore[] = L"writerRestore";
wchar_t Service[] = L"service";
wchar_t RebootRequired[] = L"rebootRequired";
wchar_t AlternateLocationMapping[] = L"AlternateLocationMapping";
wchar_t Component[] = L"Component";
wchar_t ComponentType[] = L"componentType";
wchar_t LogicalPath[] = L"logicalPath";
wchar_t Selectable[] = L"selectable";
wchar_t SelectableForRestore[] = L"selectableForRestore";
wchar_t ComponentName[] = L"componentName";
wchar_t ComponentFile[] = L"ComponentFile";
wchar_t Dependency[] = L"Dependency";
wchar_t WriterId[] = L"writerId";
wchar_t ExcludeFile[] = L"ExcludeFile";
wchar_t RestoreTarget[] = L"restoreTarget";
wchar_t NewTarget[] = L"NewTarget";
wchar_t FailEvent[] = L"FailEvent";
wchar_t WriterEvent[] = L"writerEvent";
wchar_t Retryable[] = L"retryable";
wchar_t NumFailures[] = L"numFailures";
// string containing the Test writer schema
#include "schema.h"
}
////////////////////////////////////////////////////////////////////////
// Implementation for the File struct
File::File(CXMLDocument node)
{
// read the attributes from the document and store in the structure
CComBSTR path;
if (!node.FindAttribute(XMLData::Path, &path))
missingAttribute(XMLData::Path);
CComBSTR filespec;
if (!node.FindAttribute(XMLData::Filespec, &filespec))
missingAttribute(XMLData::Filespec);
CComBSTR recursive;
if (!node.FindAttribute(XMLData::Recursive, &recursive))
missingAttribute(XMLData::Recursive);
m_path = (BSTR)path;
std::transform(m_path.begin(), m_path.end(), m_path.begin(), towupper);
m_filespec = (BSTR)filespec;
std::transform(m_filespec.begin(), m_filespec.end(), m_filespec.begin(), towupper);
// path and filespec should never be empty.
if (m_path.empty())
throw Utility::TestWriterException(L"File specification has empty path");
if (m_filespec.empty())
throw Utility::TestWriterException(L"File specification has empty filespec");
if (m_path[m_path.size() -1] != L'\\')
m_path += L'\\';
m_recursive = Utility::toBoolean(recursive);
}
wstring File::toString() const
{
wstringstream msg;
msg << L"Path: " << m_path << std::endl <<
L"Filespec: " << m_filespec << std::endl <<
L"Recursive: " << Utility::toString(m_recursive);
return msg.str();
}
////////////////////////////////////////////////////////////////////////
// Implementation for the TargetedFile struct
TargetedFile::TargetedFile(CXMLDocument node) : File(node)
{
// read the alternatePath attribute and store it
CComBSTR alternatePath;
if (!node.FindAttribute(XMLData::AlternatePath, &alternatePath))
return;
assert(alternatePath);
m_alternatePath = (BSTR)alternatePath;
std::transform(m_alternatePath.begin(), m_alternatePath.end(), m_alternatePath.begin(), towupper);
if (m_alternatePath.empty())
throw Utility::TestWriterException(L"File specification has empty alternate path");
if (m_alternatePath[m_alternatePath.size()-1] != L'\\')
m_alternatePath += L'\\';
}
wstring TargetedFile::toString() const
{
wstringstream msg;
msg << File::toString() << std::endl <<
L"AlternatePath: " << m_alternatePath;
return msg.str();
}
////////////////////////////////////////////////////////////////////////
// Implementation for the RestoreMethod struct
RestoreMethod::RestoreMethod(CXMLDocument node)
{
node.SetToplevel();
CComBSTR method, writerRestore, service, rebootRequired;
// read attributes and elements from document
if (!node.FindAttribute(XMLData::Method, &method))
missingAttribute(XMLData::Method);
if (!node.FindAttribute(XMLData::WriterRestore, &writerRestore))
missingAttribute(XMLData::WriterRestore);
node.FindAttribute(XMLData::Service, &service);
if(!node.FindAttribute(XMLData::RebootRequired, &rebootRequired))
missingAttribute(XMLData::RebootRequired);
if (node.FindElement(XMLData::AlternateLocationMapping, true))
m_alternateLocations = AlternateList(node);
m_method = Utility::toMethod(method);
m_writerRestore = Utility::toWriterRestore(writerRestore);
m_service = (service.Length() > 0) ? service : L"";
m_rebootRequired = Utility::toBoolean(rebootRequired);
}
wstring RestoreMethod::toString() const
{
wstringstream msg;
msg << L"method: " << Utility::toString(m_method) << std::endl <<
L"service: " << m_service << std::endl <<
L"writerRestore: " << Utility::toString(m_writerRestore) << std::endl <<
L"reboot: " << Utility::toString(m_rebootRequired);
return msg.str();
}
////////////////////////////////////////////////////////////////////////
// Implementation for the Dependency struct
Dependency::Dependency(CXMLDocument node)
{
node.SetToplevel();
CComBSTR logicalPath, componentName, writerId;
if(!node.FindAttribute(XMLData::WriterId, &writerId))
missingAttribute(XMLData::WriterId);
node.FindAttribute(XMLData::LogicalPath, &logicalPath);
if(!node.FindAttribute(XMLData::ComponentName, &componentName))
missingAttribute(XMLData::ComponentName);
HRESULT hr = ::UuidFromString(writerId, &m_writerId);
checkReturn(hr, L"CLSIDFromString");
m_logicalPath = (logicalPath.Length() > 0) ? logicalPath : L"";
m_componentName = componentName;
}
wstring Dependency::toString() const
{
wstringstream msg;
msg << L"WriterId: " << (wchar_t*)CComBSTR(m_writerId) << std::endl <<
L"Logical Path: " << m_logicalPath << std::endl <<
L"Component Name: " << m_componentName;
return msg.str();
}
////////////////////////////////////////////////////////////////////////
// Implementation for the Component struct
Component::Component(CXMLDocument node)
{
node.SetToplevel();
CComBSTR componentType, restoreTarget, logicalPath, name, selectable,
selectableForRestore;
// read attributes from document and store them
if (!node.FindAttribute(XMLData::ComponentType, &componentType))
missingAttribute(XMLData::ComponentType);
node.FindAttribute(XMLData::RestoreTarget, &restoreTarget);
node.FindAttribute(XMLData::LogicalPath, &logicalPath);
if (!node.FindAttribute(XMLData::ComponentName, &name))
missingAttribute(XMLData::ComponentName);
if (!node.FindAttribute(XMLData::Selectable, &selectable))
missingAttribute(XMLData::Selectable);
if (!node.FindAttribute(XMLData::SelectableForRestore, &selectableForRestore))
missingAttribute(XMLData::SelectableForRestore);
m_componentType = Utility::toComponentType(componentType);
m_restoreTarget = (restoreTarget.Length() > 0) ? Utility::toRestoreTarget(restoreTarget) : VSS_RT_UNDEFINED;
m_logicalPath = (logicalPath.Length() > 0) ? logicalPath : L"";
m_selectable = Utility::toBoolean(selectable);
m_selectableForRestore = Utility::toBoolean(selectableForRestore);
m_name = name;
if (m_name.empty())
throw Utility::TestWriterException(L"Component has empty name");
// read elements from document and store them
if (node.FindElement(XMLData::ComponentFile, true))
m_files = ComponentFileList(node);
node.ResetToDocument();
if (node.FindElement(XMLData::Dependency, true))
m_dependencies = DependencyList(node);
}
wstring ComponentBase::toString() const
{
wstringstream msg;
msg << L"Logical Path: " << m_logicalPath << std::endl <<
L"Name: " << m_name << std::endl;
return msg.str();
}
// comparison operations for writer components
bool operator==(const ComponentBase& left, const ComponentBase& right)
{
return (left.m_name == right.m_name) &&
(left.m_logicalPath == right.m_logicalPath);
}
bool operator!=(const ComponentBase& left, const ComponentBase& right)
{
return !(left == right);
}
bool operator==(const Component& left, const Component& right)
{
return ((ComponentBase&)left == (ComponentBase&)right) &&
(left.m_componentType == right.m_componentType) &&
(left.m_restoreTarget == right.m_restoreTarget) &&
(left.m_selectable == right.m_selectable) &&
(left.m_selectableForRestore == right.m_selectableForRestore) &&
(left.m_files == right.m_files) &&
(left.m_newTargets == right.m_newTargets);
}
bool operator!=(const Component& left, const Component& right)
{
return !(left == right);
}
////////////////////////////////////////////////////////////////////////
// Implementation for the WriterEvent struct
WriterEvent::WriterEvent(CXMLDocument node)
{
CComBSTR event;
if (!node.FindAttribute(XMLData::WriterEvent, &event))
missingAttribute(XMLData::WriterEvent);
CComBSTR retryable;
if (!node.FindAttribute(XMLData::Retryable, &retryable))
missingAttribute(XMLData::Retryable);
CComBSTR numFailures;
if (!node.FindAttribute(XMLData::NumFailures, &numFailures))
missingAttribute(XMLData::NumFailures);
m_writerEvent = Utility::toWriterEvent(event);
m_retryable = Utility::toBoolean(retryable);
m_numFailures = Utility::toLong(numFailures);
}
////////////////////////////////////////////////////////////////////////
// Implementation for the WriterConfiguration class
// load configuration from the XML file
void WriterConfiguration::loadFromXML(const wstring& xml)
{
AutoCS critical(m_section);
// load the document from the XML string
wstring xmlString = XMLData::RootStart;
xmlString += XMLData::Schema;
xmlString += xml;
xmlString += XMLData::RootEnd;
// load twice so we can do schema validation the second time
for (int x = 0; x < 2; x++) {
if (!m_doc.LoadFromXML(const_cast<wchar_t*> (xmlString.c_str())))
Utility::parseError(m_doc);
// --- skip to the part of the document we care about
if (!m_doc.FindElement(XMLData::Root, true))
missingElement(XMLData::Root);
if (!m_doc.FindElement(XMLData::TestWriter, true))
missingElement(XMLData::TestWriter);
// --- set the schema namespace
if (x == 0) {
CXMLNode testNode(m_doc.GetCurrentNode(), m_doc.GetInterface());
testNode.SetAttribute(XMLData::Xmlns, XMLData::SchemaPointer);
xmlString = m_doc.SaveAsXML();
}
}
m_doc.SetToplevel();
}
VSS_USAGE_TYPE WriterConfiguration::usage() const
{
assert(m_doc.GetLevel() == 0);
AutoCS critical(m_section);
Resetter reset(m_doc);
CComBSTR value;
if (!m_doc.FindAttribute(XMLData::Usage, &value))
missingAttribute(XMLData::Usage);
return Utility::toUsage(value);
}
Utility::Verbosity WriterConfiguration::verbosity() const
{
assert(m_doc.GetLevel() == 0);
AutoCS critical(m_section);
Resetter reset(m_doc);
CComBSTR value;
if (!m_doc.FindAttribute(XMLData::Verbosity, &value))
missingAttribute(XMLData::Verbosity);
return Utility::toVerbosity(value);
}
bool WriterConfiguration::checkExcludes() const
{
assert(m_doc.GetLevel() == 0);
AutoCS critical(m_section);
Resetter reset(m_doc);
CComBSTR value;
if (!m_doc.FindAttribute(XMLData::CheckExcludes, &value))
missingAttribute(XMLData::CheckExcludes);
return Utility::toBoolean(value);
}
bool WriterConfiguration::checkIncludes() const
{
assert(m_doc.GetLevel() == 0);
AutoCS critical(m_section);
Resetter reset(m_doc);
CComBSTR value;
if (!m_doc.FindAttribute(XMLData::CheckIncludes, &value))
missingAttribute(XMLData::CheckIncludes);
return Utility::toBoolean(value);
}
// get the writer's restore method
RestoreMethod WriterConfiguration::restoreMethod() const
{
assert(m_doc.GetLevel() == 0);
AutoCS critical(m_section);
Resetter reset(m_doc);
if (!m_doc.FindElement(XMLData::RestoreMethod, true))
missingElement(XMLData::RestoreMethod);
return RestoreMethod(m_doc);
}
| 30.20045 | 110 | 0.657394 | [
"transform"
] |
de11b7207b4a59803a2b6f27b7112d434f3f968f | 19,636 | cpp | C++ | easy-ip.cpp | PetterS/easy-IP | d57607333b9844a32723db5e1d748b9eeb4fb2a2 | [
"BSD-2-Clause"
] | 12 | 2015-12-04T05:59:12.000Z | 2020-08-01T00:33:30.000Z | easy-ip.cpp | PetterS/easy-IP | d57607333b9844a32723db5e1d748b9eeb4fb2a2 | [
"BSD-2-Clause"
] | 1 | 2020-10-04T19:41:26.000Z | 2020-10-04T19:41:26.000Z | easy-ip.cpp | PetterS/easy-IP | d57607333b9844a32723db5e1d748b9eeb4fb2a2 | [
"BSD-2-Clause"
] | 6 | 2016-04-10T20:31:03.000Z | 2020-10-04T06:13:27.000Z | // Petter Strandmark 2013
// petter.strandmark@gmail.com
#include <memory>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <vector>
#ifdef HAS_OPENMP
#include <omp.h>
#endif
#include <easy-ip.h>
#include <easy-ip-internal.h>
void check(bool expr, const char* message)
{
if (!expr) {
throw std::invalid_argument(message);
}
}
void assertion_failed(const char* expr, const char* file_cstr, int line)
{
using namespace std;
// Extract the file name only.
string file(file_cstr);
auto pos = file.find_last_of("/\\");
if (pos == string::npos) {
pos = 0;
}
file = file.substr(pos + 1); // Returns empty string if pos + 1 == length.
stringstream sout;
sout << "Assertion failed: " << expr << " in " << file << ":" << line << ".";
throw runtime_error(sout.str().c_str());
}
double EASY_IP_API wall_time()
{
#ifdef HAS_OPENMP
return ::omp_get_wtime();
#else
return 0;
#endif
}
double Variable::value() const
{
return creator->get_solution(*this);
}
bool BooleanVariable::bool_value() const
{
return creator->get_solution(*this);
}
std::ostream& operator << (std::ostream& out, const Variable& variable)
{
out << variable.value();
return out;
}
std::ostream& operator << (std::ostream& out, const BooleanVariable& variable)
{
out << variable.bool_value();
return out;
}
Sum::Sum()
: impl(new Implementation)
{ }
Sum::Sum(const Sum& sum)
: impl(new Implementation(*sum.impl))
{ }
Sum& Sum::operator = (const Sum& sum)
{
*impl = *sum.impl;
return *this;
}
Sum::Sum(Sum&& sum)
: impl(nullptr)
{
impl = sum.impl;
sum.impl = nullptr;
}
Sum& Sum::operator = (Sum&& sum)
{
if (impl) {
delete impl;
}
impl = sum.impl;
sum.impl = nullptr;
return *this;
}
Sum::Sum(double constant_)
: impl(new Implementation(constant_))
{ }
Sum::Sum(const Variable& variable)
: impl(new Implementation(variable))
{ }
Sum::~Sum()
{
if (impl) {
delete impl;
}
}
void Sum::add_term(double coeff, const Variable& variable)
{
impl->cols.push_back(static_cast<int>(variable.index));
impl->values.push_back(coeff);
}
double Sum::value() const
{
if (!impl->creator) {
// This happens if Sum is constant. No variables
// have been added.
attest(impl->cols.empty());
return impl->constant;
}
return impl->creator->get_solution(*this);
}
Sum& Sum::operator += (const Sum& rhs)
{
match_solvers(rhs);
impl->constant += rhs.impl->constant;
for (size_t i = 0; i < rhs.impl->cols.size(); ++i) {
impl->cols.push_back(rhs.impl->cols[i]);
impl->values.push_back(rhs.impl->values[i]);
}
return *this;
}
Sum& Sum::operator -= (const Sum& rhs)
{
match_solvers(rhs);
impl->constant -= rhs.impl->constant;
for (size_t i = 0; i < rhs.impl->cols.size(); ++i) {
impl->cols.push_back(rhs.impl->cols[i]);
impl->values.push_back(-rhs.impl->values[i]);
}
return *this;
}
Sum& Sum::operator *= (double coeff)
{
if (coeff == 0.0) {
impl->values.clear();
impl->cols.clear();
impl->constant = 0.0;
return *this;
}
for (auto& value : impl->values) {
value *= coeff;
}
impl->constant *= coeff;
return *this;
}
Sum& Sum::operator /= (double coeff)
{
if (coeff == 0.0) {
throw std::runtime_error("Sum: Division by zero.");
}
*this *= (1.0 / coeff);
return *this;
}
Sum operator * (double coeff, const Variable& variable)
{
Sum sum(variable);
sum *= coeff;
return sum;
}
Sum operator * (double coeff, Sum sum)
{
sum *= coeff;
return sum;
}
Sum operator * (Sum sum, double coeff)
{
sum *= coeff;
return sum;
}
Sum operator / (Sum sum, double coeff)
{
sum /= coeff;
return sum;
}
Sum operator + (const Sum& lhs, const Sum& rhs)
{
// Copy needed.
Sum sum(rhs);
sum += lhs;
return sum;
}
Sum operator + (const Sum& lhs, Sum&& rhs)
{
Sum sum(std::move(rhs));
sum += lhs;
return sum;
}
Sum operator + (Sum&& lhs, const Sum& rhs)
{
Sum sum(std::move(lhs));
sum += rhs;
return sum;
}
Sum operator + (Sum&& lhs, Sum&& rhs)
{
Sum sum(std::move(lhs));
sum += rhs;
return sum;
}
Sum operator - (Sum sum)
{
sum.negate();
return sum;
}
Sum operator - (const Variable& variable)
{
Sum sum(variable);
return -sum;
}
void Sum::negate()
{
impl->constant = -impl->constant;
for (auto& value : impl->values) {
value = -value;
}
}
Sum operator - (const Sum& lhs, const Sum& rhs)
{
// Copy needed.
Sum sum(lhs);
sum -= rhs;
return sum;
}
Sum operator - (const Sum& lhs, Sum&& rhs)
{
Sum sum(std::move(rhs));
sum.negate();
sum += lhs;
return sum;
}
Sum operator - (Sum&& lhs, const Sum& rhs)
{
Sum sum(std::move(lhs));
sum -= rhs;
return sum;
}
Sum operator - (Sum&& lhs, Sum&& rhs)
{
Sum sum(std::move(rhs));
sum.negate();
sum += lhs;
return sum;
}
void Sum::match_solvers(const Sum& sum)
{
check(impl->creator == nullptr || sum.impl->creator == nullptr || impl->creator == sum.impl->creator,
"Variables from different solver can not be mixed.");
if (impl->creator == nullptr) {
impl->creator = sum.impl->creator;
}
}
LogicalExpression operator ! (const BooleanVariable& variable)
{
// TODO: check that variable is integer through creator.
return LogicalExpression(variable, true);
}
LogicalExpression::LogicalExpression(const BooleanVariable& variable, bool is_negated)
{
if (is_negated) {
sum += 1;
sum -= variable;
}
else {
sum += variable;
}
}
LogicalExpression::LogicalExpression()
{ }
LogicalExpression::LogicalExpression(const LogicalExpression& expr)
{
*this = expr;
}
LogicalExpression& LogicalExpression::operator = (const LogicalExpression& expr)
{
sum = expr.sum;
return *this;
}
LogicalExpression::LogicalExpression(LogicalExpression&& expr)
{
*this = std::move(expr);
}
LogicalExpression& LogicalExpression::operator = (LogicalExpression&& expr)
{
sum = std::move(expr.sum);
return *this;
}
LogicalExpression& LogicalExpression::operator |= (const LogicalExpression& lhs)
{
sum.match_solvers(lhs.sum);
sum += lhs.sum;
return *this;
}
LogicalExpression operator || (const LogicalExpression& lhs, const LogicalExpression& rhs)
{
// Copying necessary.
LogicalExpression result(lhs);
result |= rhs;
return result;
}
EASY_IP_API LogicalExpression operator || (LogicalExpression&& lhs, const LogicalExpression& rhs)
{
LogicalExpression result(std::move(lhs));
result |= rhs;
return result;
}
EASY_IP_API LogicalExpression operator || (const LogicalExpression& lhs, LogicalExpression&& rhs)
{
LogicalExpression result(std::move(rhs));
result |= lhs;
return result;
}
EASY_IP_API LogicalExpression operator || (LogicalExpression&& lhs, LogicalExpression&& rhs)
{
LogicalExpression result(std::move(lhs));
result |= rhs;
return result;
}
LogicalExpression implication(const BooleanVariable& antecedent, const LogicalExpression& consequent)
{
return !antecedent || consequent;
}
LogicalExpression implication(const BooleanVariable& antecedent, LogicalExpression&& consequent)
{
return !antecedent || std::move(consequent);
}
Constraint::Constraint(const LogicalExpression& expression)
: lower_bound(1), upper_bound(static_cast<double>(expression.sum.impl->values.size())), sum(expression.sum)
{ }
Constraint::Constraint(LogicalExpression&& expression)
: lower_bound(1), upper_bound(static_cast<double>(expression.sum.impl->values.size())), sum(std::move(expression.sum))
{ }
Constraint::Constraint(double lower_bound_, const Sum& sum_, double upper_bound_)
: lower_bound(lower_bound_), upper_bound(upper_bound_), sum(sum_)
{ }
Constraint::Constraint(double lower_bound_, Sum&& sum_, double upper_bound_)
: lower_bound(lower_bound_), upper_bound(upper_bound_), sum(std::move(sum_))
{ }
Constraint operator <= (Sum lhs, const Sum& rhs)
{
lhs -= rhs;
return Constraint(-1e100, std::move(lhs), 0.0);
}
Constraint operator >= (Sum lhs, const Sum& rhs)
{
lhs -= rhs;
return Constraint(0.0, std::move(lhs), 1e100);
}
Constraint operator == (Sum lhs, const Sum& rhs)
{
lhs -= rhs;
return Constraint(0.0, std::move(lhs), 0.0);
}
class ConstraintList::Implementation
{
public:
Implementation() { }
template<typename T>
Implementation(T&& t) : constraints(std::forward<T>(t)) { }
vector<Constraint> constraints;
};
ConstraintList::ConstraintList()
: impl(new Implementation)
{ }
ConstraintList::ConstraintList(ConstraintList&& rhs)
: impl(rhs.impl)
{
rhs.impl = nullptr;
}
ConstraintList::ConstraintList(Constraint&& constraint)
: impl(new Implementation)
{
impl->constraints.push_back(std::move(constraint));
}
ConstraintList& ConstraintList::operator &= (Constraint&& rhs)
{
impl->constraints.push_back(std::move(rhs));
return *this;
}
ConstraintList::~ConstraintList()
{
if (impl) {
delete impl;
}
}
ConstraintList operator && (Constraint&& lhs, Constraint&& rhs)
{
ConstraintList list(std::move(lhs));
list &= std::move(rhs);
return list;
}
ConstraintList operator && (ConstraintList&& lhs, Constraint&& rhs)
{
ConstraintList list(std::move(lhs));
list &= std::move(rhs);
return list;
}
IP::IP()
: impl(new Implementation(this))
{
};
IP::IP(IP&& lhs)
: impl(lhs.impl)
{
impl->creator = this;
lhs.impl = nullptr;
};
IP::~IP()
{
if (impl) {
delete impl;
impl = nullptr;
}
}
Variable IP::add_variable(VariableType type, double this_cost)
{
if (type == Boolean) {
impl->var_lb.push_back(0.0);
impl->var_ub.push_back(1.0);
}
else {
impl->var_lb.push_back(-1e100);
impl->var_ub.push_back(1e100);
}
impl->cost.push_back(this_cost);
auto index = impl->cost.size() - 1;
if (type == Boolean || type == Integer) {
impl->integer_variables.push_back(index);
}
attest(impl->var_lb.size() == impl->cost.size());
attest(impl->var_ub.size() == impl->cost.size());
return Variable(index, this);
}
BooleanVariable IP::add_boolean(double this_cost)
{
auto variable = add_variable(Boolean, this_cost);
return BooleanVariable(variable);
}
Sum IP::add_variable_as_booleans(int lower_bound, int upper_bound)
{
Sum sum = 0;
Sum constraint = 0;
for (int i = lower_bound; i <= upper_bound; ++i) {
auto var = add_boolean();
sum += i * var;
constraint += var;
}
add_constraint(constraint == 1);
return sum;
}
Sum IP::add_variable_as_booleans(const std::initializer_list<int>& values)
{
Sum sum = 0;
Sum constraint = 0;
for (int i: values) {
auto var = add_boolean();
sum += i * var;
constraint += var;
}
add_constraint(constraint == 1);
return sum;
}
vector<Variable> IP::add_vector(int n, VariableType type, double this_cost)
{
vector<Variable> v;
for (int i = 0; i < n; ++i) {
v.push_back(add_variable(type, this_cost));
}
return v;
}
vector<BooleanVariable> IP::add_boolean_vector(int n, double this_cost)
{
vector<BooleanVariable> v;
for (int i = 0; i < n; ++i) {
v.push_back(add_boolean(this_cost));
}
return v;
}
template<typename Var>
vector<vector<Var>> grid_creator(int m, int n, std::function<Var()> var_creator)
{
attest(m >= 0 && n >= 0);
vector<vector<Var>> grid;
for (int i = 0; i < m; ++i) {
grid.push_back(vector<Var>());
for (int j = 0; j < n; ++j) {
grid.back().push_back(var_creator());
}
}
return grid;
}
vector<vector<Variable>> IP::add_grid(int m, int n, VariableType type, double this_cost)
{
auto var_creator = [&]() { return add_variable(type, this_cost); };
return grid_creator<Variable>(m, n, var_creator);
}
vector<vector<BooleanVariable>> IP::add_boolean_grid(int m, int n, double this_cost)
{
auto var_creator = [&]() { return add_boolean(this_cost); };
return grid_creator<BooleanVariable>(m, n, var_creator);
}
template<typename Var>
vector<vector<vector<Var>>> cube_creator(int m, int n, int o, std::function<Var()> var_creator)
{
attest(m >= 0 && n >= 0 && o >= 0);
vector<vector<vector<Var>>> grid;
for (int i = 0; i < m; ++i) {
grid.push_back(vector<vector<Var>>());
for (int j = 0; j < n; ++j) {
grid.back().push_back(vector<Var>());
for (int k = 0; k < o; ++k) {
grid.back().back().push_back(var_creator());
}
}
}
return grid;
}
vector<vector<vector<Variable>>> IP::add_cube(int m, int n, int o, VariableType type, double this_cost)
{
auto var_creator = [&]() { return add_variable(type, this_cost); };
return cube_creator<Variable>(m, n, o, var_creator);
}
vector<vector<vector<BooleanVariable>>> IP::add_boolean_cube(int m, int n, int o, double this_cost)
{
auto var_creator = [&]() { return add_boolean(this_cost); };
return cube_creator<BooleanVariable>(m, n, o, var_creator);
}
// Adds the constraint
// L <= constraint <= U
int IP::add_constraint(double L, const Sum& sum, double U)
{
impl->check_creator(sum);
//std::cerr << L-sum.constant << " <= ";
//for (int i = 0; i < sum.cols.size(); ++i) {
// std::cerr << sum.values[i] << "*x" << sum.cols[i] << " ";
//}
//std::cerr << " <= " << U-sum.constant << std::endl;
if (sum.impl->cols.empty()) {
check(L <= sum.impl->constant && sum.impl->constant <= U,
"A constraint that is always false may not be added.");
return 0;
}
impl->rhs_lower.push_back(L - sum.impl->constant);
impl->rhs_upper.push_back(U - sum.impl->constant);
auto row_index = impl->rhs_upper.size() - 1;
for (size_t i = 0; i < sum.impl->cols.size(); ++i) {
impl->rows.push_back(static_cast<int>(row_index));
impl->cols.push_back(sum.impl->cols[i]);
impl->values.push_back(sum.impl->values[i]);
}
attest(impl->rows.size() == impl->values.size());
attest(impl->cols.size() == impl->values.size());
attest(impl->rhs_lower.size() == impl->rhs_upper.size());
return 1;
}
int IP::add_constraint(const Constraint& constraint)
{
return add_constraint(constraint.lower_bound, constraint.sum, constraint.upper_bound);
}
int IP::add_constraint(const ConstraintList& list)
{
int added = 0;
for (auto& constraint: list.impl->constraints) {
added += add_constraint(constraint);
}
return added;
}
void IP::add_constraint(const BooleanVariable& variable)
{
set_bounds(1, variable, 1);
}
// Adds the constraint
// L <= variable <= U
void IP::set_bounds(double L, const Variable& variable, double U)
{
impl->check_creator(variable);
impl->var_lb[variable.index] = L;
impl->var_ub[variable.index] = U;
}
void IP::add_objective(const Sum& sum)
{
impl->check_creator(sum);
for (size_t i = 0; i < sum.impl->cols.size(); ++i) {
impl->cost.at(sum.impl->cols[i]) += sum.impl->values[i];
}
impl->objective_constant += sum.impl->constant;
}
void IP::Implementation::check_creator(const Variable& t) const
{
check(t.creator == nullptr || t.creator == creator,
"Variable comes from a different solver.");
}
void IP::Implementation::check_creator(const Sum& t) const
{
check(t.impl->creator == nullptr || t.impl->creator == creator,
"Sum comes from a different solver.");
}
double IP::get_solution(const Variable& variable) const
{
impl->check_creator(variable);
return impl->solution.at(variable.index);
}
bool IP::get_solution(const BooleanVariable& variable) const
{
impl->check_creator(variable);
return impl->solution.at(variable.index) > 0.5;
}
double IP::get_solution(const Sum& sum) const
{
impl->check_creator(sum);
double value = sum.impl->constant;
for (size_t i = 0; i < sum.impl->cols.size(); ++i) {
value += sum.impl->values[i] * impl->solution.at(sum.impl->cols[i]);
}
return value;
}
bool IP::get_solution(const LogicalExpression& expression) const
{
return get_solution(expression.sum) > 0.5;
}
void IP::set_external_solver(Solver solver)
{
impl->external_solver = solver;
impl->minisat_solver.release();
impl->literals.clear();
impl->objective_function_literals.clear();
impl->objective_function_slack_literals.clear();
if (solver == CPLEX) {
#ifndef HAS_CPLEX
throw std::runtime_error("IP::set_external_solver: CPLEX not installed.");
#endif
}
else if (solver == MOSEK) {
#ifndef HAS_MOSEK
throw std::runtime_error("IP::set_external_solver: MOSEK not installed.");
#endif
}
}
void IP::set_time_limit(double seconds)
{
impl->time_limit_in_seconds = seconds;
}
void IP::allow_ignoring_cost_function()
{
impl->allow_ignoring_cost_function = true;
}
size_t IP::get_number_of_variables() const
{
return impl->cost.size();
}
void IP::clear()
{
impl->rhs_lower.clear();
impl->rhs_upper.clear();
impl->rows.clear();
impl->cols.clear();
impl->values.clear();
impl->var_lb.clear();
impl->var_ub.clear();
impl->cost.clear();
impl->solution.clear();
impl->integer_variables.clear();
}
int IP::add_max_consequtive_constraints(int N, const std::vector<Sum>& variables)
{
if (N >= variables.size()) {
return 0;
}
int constraints_added = 0;
for (int d = 0; d < variables.size() - N; ++d) {
Sum active_in_window = 0;
for (int d2 = d; d2 < d + N + 1; ++d2) {
active_in_window += variables.at(d2);
}
constraints_added += add_constraint(active_in_window <= N);
}
return constraints_added;
}
int IP::add_min_consequtive_constraints(int N, const std::vector<Sum>& variables, bool OK_at_the_border)
{
if (N <= 1) {
return 0;
}
attest(N <= variables.size());
if (N == variables.size()) {
for (auto& var: variables) {
add_constraint(var == 1);
}
return 0;
}
int constraints_added = 0;
for (int window_size = 1; window_size <= N - 1; ++window_size) {
// Look for windows of size minimum - 1 along with the
// surrounding slots.
//
// […] [x1] [y1] [x2] […]
//
// x1 = 0 ∧ x2 = 0 ⇒ y1 = 0
// ⇔
// x1 + x2 - y1 ≥ 0
//
// Then add windows with more y variables. E.g.
//
// x1 + x2 - y1 - y2 - y3 ≥ -2.
for (int window_start = 0; window_start < variables.size() - window_size + 1; ++window_start) {
Sum constraint = 0;
if (window_start - 1 >= 0) {
constraint += variables.at(window_start - 1);
}
else if (OK_at_the_border) {
continue;
}
for (int i = window_start; i < window_start + window_size; ++i) {
constraint -= variables.at(i);
}
if (window_start + window_size < variables.size()) {
constraint += variables.at(window_start + window_size);
}
else if (OK_at_the_border) {
continue;
}
constraints_added += add_constraint(constraint >= -window_size + 1);
}
}
return constraints_added;
}
void IP::save_MPS(const std::string& file_name)
{
OsiSolverInterface* solver = nullptr;
std::unique_ptr<OsiSolverInterface> new_problem;
if (impl->use_osi() && impl->problem) {
solver = impl->problem.get();
}
else if (impl->model) {
attest(impl->model);
solver = impl->model->solver();
}
else {
get_problem(new_problem);
solver = new_problem.get();
}
solver->writeMps(file_name.c_str());
}
void IP::save_CNF(const std::string& file_name)
{
impl->convert_to_minisat();
auto f = std::fopen(file_name.c_str(), "w");
impl->minisat_solver->toDimacs(f, {});
std::fclose(f);
}
vector<double>& IP::get_rhs_lower() { return impl->rhs_lower; }
vector<double>& IP::get_rhs_upper() { return impl->rhs_upper; }
vector<int>& IP::get_rows() { return impl->rows; }
vector<int>& IP::get_cols() { return impl->cols; }
vector<double>& IP::get_values() { return impl->values; }
const vector<double>& IP::get_rhs_lower() const { return impl->rhs_lower; }
const vector<double>& IP::get_rhs_upper() const { return impl->rhs_upper; }
const vector<int>& IP::get_rows() const { return impl->rows; }
const vector<int>& IP::get_cols() const { return impl->cols; }
const vector<double>& IP::get_values() const { return impl->values; }
const vector<double>& IP::get_var_lb() const { return impl->var_lb; }
const vector<double>& IP::get_var_ub() const { return impl->var_ub; }
const vector<double>& IP::get_cost() const { return impl->cost; }
const vector<std::size_t>& IP::get_integer_variables() const { return impl->integer_variables; }
vector<double>& IP::get_solution() { return impl->solution; }
| 21.343478 | 119 | 0.672031 | [
"vector",
"model"
] |
de13bdafcf80cbf419568228c3a7a7a210ee8b12 | 1,356 | cpp | C++ | 08_06_heap/heap/heap.cpp | Thanalan/GameBookServer-master | 506b4fe1eece1a3c0bd1100fe14764b63885b2bf | [
"MIT"
] | 83 | 2019-12-03T08:42:15.000Z | 2022-03-30T13:22:37.000Z | 08_06_heap/heap/heap.cpp | Thanalan/GameBookServer-master | 506b4fe1eece1a3c0bd1100fe14764b63885b2bf | [
"MIT"
] | 1 | 2021-08-06T10:40:57.000Z | 2021-08-09T06:33:43.000Z | 08_06_heap/heap/heap.cpp | Thanalan/GameBookServer-master | 506b4fe1eece1a3c0bd1100fe14764b63885b2bf | [
"MIT"
] | 45 | 2020-05-29T03:22:48.000Z | 2022-03-21T16:19:01.000Z | // heap.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <cstdio>
#include <vector>
#include <algorithm>
#include <functional>
#include <iostream>
#define HeapMin 1
void Show(std::vector<int>& data)
{
std::cout << "数据列表:";
for (int x : data)
std::cout << x << " ";
std::cout << "顶端:" << data.front() << std::endl;
std::cout << std::endl << std::endl;
}
void PopData(std::vector<int>& data)
{
#ifdef HeapMin
// 弹出heap顶元素, 将其放置于区间末尾
pop_heap(data.begin(), data.end(), std::greater<int>());
#else
pop_heap(data.begin(), data.end());
#endif
std::cout << "弹出数据:" << data.back() << std::endl;
data.pop_back();
Show(data);
}
void PushData(std::vector<int>& data, const int value)
{
std::cout << "往堆中添加元素:" << value << std::endl;
data.push_back(value);
#ifdef HeapMin
push_heap(data.begin(), data.end(), std::greater<int>());
#else
push_heap(data.begin(), data.end());
#endif
Show(data);
}
int main()
{
std::vector<int> data{ 9, 1, 6, 3, 8, 9 };
Show(data);
std::cout << "执行make_heap." << std::endl;
#ifdef HeapMin
make_heap(data.begin(), data.end(), std::greater<int>());
#else
make_heap(data.begin(), data.end());
#endif
Show(data);
PopData(data);
PopData(data);
PushData(data, 5);
PushData(data, 1);
PopData(data);
return 0;
}
| 18.08 | 61 | 0.581858 | [
"vector"
] |
de14866162a11b243824f3ca85914da7cba6e26e | 18,609 | cpp | C++ | wpn-config.cpp | commandus/wpn | 7064b4effd1d1e502daf6bddcdf126165706ca32 | [
"MIT"
] | 2 | 2020-11-22T23:45:19.000Z | 2020-12-14T06:54:31.000Z | wpn-config.cpp | commandus/wpn | 7064b4effd1d1e502daf6bddcdf126165706ca32 | [
"MIT"
] | null | null | null | wpn-config.cpp | commandus/wpn | 7064b4effd1d1e502daf6bddcdf126165706ca32 | [
"MIT"
] | 1 | 2021-05-13T12:23:19.000Z | 2021-05-13T12:23:19.000Z | #include "wpn-config.h"
#include <iostream>
#include <argtable3/argtable3.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fstream>
#include "google/protobuf/stubs/common.h"
#include "config-filename.h"
#ifdef _MSC_VER
#else
#include <dlfcn.h>
#endif
#include "platform.h"
#include "utilstring.h"
#define DEF_FILE_NAME ".wpn.js"
#define DEF_FCM_ENDPOINT_PREFIX "https://fcm.googleapis.com/fcm/send/"
#define DEF_OUTPUT_SO_FN "libwpn-stdout.so"
#define DEF_FUNC_NOTIFY "desktopNotify"
#define DEF_COMMON_NAME "everyone"
#ifdef _MSC_VER
#define DEF_PLUGIN_FILE_EXT ".dll"
#else
#define DEF_PLUGIN_FILE_EXT ".so"
#endif
#define DEF_FILE_NAME ".wpn.js"
static const char* progname = "wpn";
static const char* SUBSCRIBE_URLS[SUBSCRIBE_URL_COUNT] = {
SUBSCRIBE_URL_1
};
std::string WpnConfig::getDefaultFCMEndPoint()
{
std::string r(DEF_FCM_ENDPOINT_PREFIX);
if (config->androidCredentials)
r = r + config->androidCredentials->getGCMToken();
return r;
}
WpnConfig::WpnConfig
(
int argc,
char* argv[]
)
{
errorcode = parseCmd(argc, argv);
}
WpnConfig::~WpnConfig()
{
if (config)
delete config;
}
/**
* Parse command line into WpnConfig class
* Return 0- success
* 1- show help and exit, or command syntax error
* 2- output file does not exists or can not open to write
**/
int WpnConfig::parseCmd
(
int argc,
char* argv[]
)
{
subscriptionMode = SUBSCRIBE_DB;
struct arg_lit *a_list = arg_lit0("P", "list", "Print subscription list");
struct arg_lit *a_list_qrcode = arg_lit0("q", "qrcode", "QRCode list subscriptions");
struct arg_lit *a_invert_qrcode = arg_lit0("Q", "qrcode-inverted", "inverted QR code (white console)");
struct arg_str *a_list_email = arg_str0("M", "mailto", "<common name>", "e-mail list subscriptions to the person. Use with optional --subject --template-file ");
struct arg_lit *a_link_email = arg_lit0("E", "link", "list subscriptions link");
struct arg_lit *a_keys = arg_lit0("y", "keys", "Print VAPID keys");
struct arg_lit *a_credentials = arg_lit0(NULL, "id", "Print device identifiers and security tokens");
struct arg_lit *a_subscribe_vapid = arg_lit0("s", "subscribe", "Subscribe with VAPID. Mandatory -u -n --private-key --public-key --auth-secret");
struct arg_lit *a_subscribe_fcm = arg_lit0("S", "subscribe-fcm", "Subscribe with FCM. Mandatory -e -n, optional -r, -k");
struct arg_lit *a_unsubscribe = arg_lit0("u", "unsubscribe", "Unsubscribe with -e");
struct arg_lit *a_send = arg_lit0("m", "message", "Send message with -k (FCM), -d, -a (VAPID) or -n; execute -x. Or -t, -b, -i, -a");
struct arg_str *a_sub = arg_str0(NULL, "sub", "<URL>", "sub link e.g. mailto://alice@acme.com");
struct arg_str *a_file_name = arg_str0("c", "config", "<file>", "Configuration file. Default ~/" DEF_FILE_NAME);
struct arg_str *a_name = arg_str0("n", "name", "<name>", "Subscription name");
struct arg_str *a_subscribe_url = arg_str0("r", "registrar", "<URL>", "Subscription registrar URL, like https://fcm.googleapis.com/fcm/connect/subscribe or 1. Default 1");
struct arg_str *a_authorized_entity = arg_str0("e", "entity", "<entity-id>", "Push message sender identifier, usually decimal number");
// send options
struct arg_str *a_server_key = arg_str0("K", "fcm-key", "<key>", "FCM server key to send");
struct arg_str *a_recipient_tokens = arg_strn(NULL, NULL, "<account#>", 0, 100, "Recipient token.");
struct arg_str *a_recipient_token_file = arg_str0("j", "json", "<file name or URL>", "Recipient token JSON file e.g. [[1,\"token\",..");
// notification options
struct arg_str *a_subject = arg_str0("t", "subject", "<Text>", "Subject (topic)");
struct arg_str *a_body = arg_str0("b", "body", "<Text>", "Body");
struct arg_str *a_icon = arg_str0("i", "icon", "<URL>", "http[s]:// icon address.");
struct arg_str *a_link = arg_str0("l", "link", "<URL>", "http[s]:// action address.");
struct arg_str *a_data = arg_str0("D", "data", "<text>", "Extra data");
struct arg_str *a_command = arg_str0("x", "execute", "<command line>", "e.g. ls");
// VAPID sender's options
struct arg_str *a_contact = arg_str0("f", "from", "<email>", "Sender's email e.g. mailto:alice@acme.com");
// VAPID subscriber's options
struct arg_str *a_p256dh = arg_str0("d", "p256dh", "<key>", "Recipient's p256dh public key");
struct arg_str *a_auth = arg_str0("a", "auth", "<secret>", "Recipient's auth secret");
// other options
struct arg_str *a_output = arg_str0("o", "format", "<text|json>", "Output format. Default text.");
struct arg_str *a_template_file = arg_str0(NULL, "template-file", "<file>", "e-mail HTML template file with $name $subject $body");
// output options
struct arg_str *a_output_lib_filenames = arg_strn(NULL, "plugin", "<file name>", 0, 100, "Output shared library file name or directory");
struct arg_str *a_notify_function_name = arg_str0(NULL, "plugin-func", "<name>", "Output function name. Default " DEF_FUNC_NOTIFY);
// other
struct arg_lit *a_aesgcm = arg_lit0("1", "aesgcm", "Force AESGCM. Default AES128GCM");
struct arg_lit *a_verbosity = arg_litn("v", "verbose", 0, 4, "0- quiet (default), 1- errors, 2- warnings, 3- debug, 4- debug libs");
struct arg_str *a_endpoint = arg_str0(NULL, "fcm-endpoint", "<URL>", "Override FCM push service endpoint URL prefix.");
// override 'sender' VAPID keys
struct arg_str *a_vapid_private_key = arg_str0("p", "private-key", "<base64>", "Override VAPID private key.");
struct arg_str *a_vapid_public_key = arg_str0("k", "public-key", "<base64>", "Override VAPID public key");
struct arg_str *a_vapid_auth_secret = arg_str0(NULL, "auth-secret", "<base64>", "Override VAPID auth secret");
// last
struct arg_str *a_last_persistent_id = arg_str0(NULL, "last", "<id>", "Last persistent id");
// helper options
struct arg_lit *a_version = arg_lit0(NULL, "version", "Print version");
struct arg_lit *a_generatevapidkeys = arg_lit0(NULL, "generate-vapid-keys", "Generate VAPID keys");
struct arg_lit *a_help = arg_lit0("h", "help", "Show this help");
struct arg_end *a_end = arg_end(20);
void* argtable[] = {
a_list, a_list_qrcode, a_invert_qrcode, a_list_email, a_link_email, a_credentials, a_keys,
a_subscribe_vapid, a_subscribe_fcm, a_unsubscribe, a_send, a_sub,
a_name, a_subscribe_url, a_authorized_entity, a_file_name,
a_server_key, a_subject, a_body, a_icon, a_link, a_data, a_command,
a_contact, a_p256dh, a_auth,
a_recipient_tokens, a_recipient_token_file, a_output, a_template_file,
a_output_lib_filenames, a_notify_function_name,
a_aesgcm, a_verbosity, a_vapid_private_key, a_vapid_public_key, a_vapid_auth_secret,
a_endpoint,
a_version, a_generatevapidkeys,
a_last_persistent_id,
a_help, a_end
};
int nerrors;
// verify the argtable[] entries were allocated successfully
if (arg_nullcheck(argtable) != 0)
{
arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
return 1;
}
// Parse the command line as defined by argtable[]
nerrors = arg_parse(argc, argv, argtable);
if (a_file_name->count)
file_name = *a_file_name->sval;
else
file_name = getDefaultConfigFileName(DEF_FILE_NAME);
// read config
config = new ConfigFile(file_name);
if (config->errorCode) {
std::cerr << "Error " << config->errorCode << ": " << config->errorDescription << std::endl;
return config->errorCode;
}
config->clientOptions->setVerbosity(a_verbosity->count);
if (a_subscribe_url->count)
subscribeUrl = *a_subscribe_url->sval;
else
subscribeUrl = "";
if (a_name->count)
name = *a_name->sval;
else
name = "";
if (a_sub->count)
sub = *a_sub->sval;
else
sub = "";
int m = strtol(subscribeUrl.c_str(), NULL, 10);
if ((m > 0) && (m <= SUBSCRIBE_URL_COUNT))
{
m--;
subscribeUrl = SUBSCRIBE_URLS[m];
}
if (subscribeUrl.empty())
subscribeUrl = SUBSCRIBE_URLS[0];
if (a_authorized_entity->count)
authorizedEntity = *a_authorized_entity->sval;
else
authorizedEntity = "";
cmd = CMD_LISTEN;
if (a_list->count)
cmd = CMD_LIST;
else
if ((a_list_qrcode->count) || (a_invert_qrcode->count))
cmd = CMD_LIST_QRCODE;
else
if (a_link_email->count)
cmd = CMD_LIST_LINK;
else
if (a_list_email->count)
{
cmd = CMD_LIST_EMAIL;
cn = std::string(*a_list_email->sval);
}
else
if (a_keys->count)
cmd = CMD_KEYS;
else
if (a_credentials->count)
cmd = CMD_CREDENTIALS;
else
if (a_subscribe_vapid->count)
cmd = CMD_SUBSCRIBE_VAPID;
else
if (a_subscribe_fcm->count)
cmd = CMD_SUBSCRIBE_FCM;
else
if (a_unsubscribe->count)
cmd = CMD_UNSUBSCRIBE;
else
if (a_send->count)
cmd = CMD_PUSH;
else
if (a_generatevapidkeys->count)
cmd = CMD_GENERATE_VAPID_KEYS;
else
if (a_version->count)
cmd = CMD_PRINT_VERSION;
if (a_endpoint->count)
fcm_endpoint = *a_endpoint->sval;
else {
fcm_endpoint = getDefaultFCMEndPoint();
}
if (a_vapid_private_key->count) {
subscriptionMode = SUBSCRIBE_FORCE_VAPID;;
private_key = *a_vapid_private_key->sval;
}
if (a_vapid_public_key->count) {
subscriptionMode = SUBSCRIBE_FORCE_VAPID;;
public_key = *a_vapid_public_key->sval;
}
if (a_vapid_auth_secret->count) {
subscriptionMode = SUBSCRIBE_FORCE_VAPID;;
vapid_recipient_auth = *a_vapid_auth_secret->sval;
}
if (a_last_persistent_id->count) {
lastPersistentId = *a_last_persistent_id->sval;
}
if (a_contact->count) {
vapid_sender_contact = *a_contact->sval;
}
if (a_p256dh->count) {
vapid_recipient_p256dh = *a_p256dh->sval;
}
if (a_auth->count) {
auth_secret = *a_auth->sval;
}
if (a_notify_function_name->count)
notifyFunctionName = *a_notify_function_name->sval;
else
notifyFunctionName = DEF_FUNC_NOTIFY;
if (a_template_file->count)
{
std::string fn = std::string(*a_template_file->sval);
email_template = file2string(fn);
if (email_template.empty())
{
// try load from the Internet;
email_template = url2string(fn);
}
}
if (cn.empty())
{
cn = DEF_COMMON_NAME;
}
if (a_output_lib_filenames->count)
{
for (int i = 0; i < a_output_lib_filenames->count; i++)
{
notifyLibFileNames.push_back(a_output_lib_filenames->sval[i]);
}
}
else
{
notifyLibFileNames.push_back(DEF_OUTPUT_SO_FN);
}
if (cmd == CMD_PUSH)
{
if (a_server_key->count == 0)
{
if (a_name->count == 0)
{
if ((a_recipient_tokens->count == 0) && (a_recipient_token_file->count == 0)) {
std::cerr << "Recipient endpoint missed. " << std::endl;
nerrors++;
}
if (a_p256dh->count == 0) {
std::cerr << "-d, --p256dh missed. " << std::endl;
nerrors++;
}
if (a_auth->count == 0) {
std::cerr << "-a, --auth missed. " << std::endl;
nerrors++;
}
}
}
if (a_command->count == 0)
{
if (a_subject->count == 0)
{
std::cerr << "-s missed." << std::endl;
nerrors++;
}
if (a_body->count == 0)
{
std::cerr << "-b missed." << std::endl;
nerrors++;
}
/*
if (a_icon->count == 0)
{
std::cerr << "-i missed." << std::endl;
nerrors++;
}
if (a_link->count == 0)
{
std::cerr << "-l missed." << std::endl;
nerrors++;
}
*/
}
}
if (cmd == CMD_SUBSCRIBE_FCM)
{
if (name.empty())
{
std::cerr << "No subscription name. Set valid -n option." << std::endl;
nerrors++;
}
if (subscribeUrl.empty())
{
std::cerr << "Unknown registar. Set valid -r option." << std::endl;
nerrors++;
}
if (authorizedEntity.empty())
{
std::cerr << "Missing -e <entity-id> option." << std::endl;
nerrors++;
}
}
if (cmd == CMD_SUBSCRIBE_VAPID)
{
if (name.empty())
{
std::cerr << "No subscription name. Set valid -n option." << std::endl;
nerrors++;
}
if (private_key.empty())
{
std::cerr << "No VAPID private key. Set valid --private-key option." << std::endl;
nerrors++;
}
if (public_key.empty())
{
std::cerr << "No VAPID public key. Set valid --public-key option." << std::endl;
nerrors++;
}
if (auth_secret.empty())
{
std::cerr << "No VAPID auth secret key. Set valid --auth-secret option." << std::endl;
nerrors++;
}
}
if (a_server_key->count)
{
subscriptionMode = SUBSCRIBE_FORCE_FIREBASE;
serverKey = *a_server_key->sval;
}
else
{
serverKey = "";
}
if (a_subject->count)
{
subject = *a_subject->sval;
}
else
{
subject = "";
}
if (a_body->count)
{
body = *a_body->sval;
}
else
{
body = "";
}
if (a_icon->count)
{
icon = *a_icon->sval;
}
else
{
icon = "";
}
if (a_link->count)
{
link = *a_link->sval;
}
else
{
link = "";
}
if (a_data->count)
{
data = *a_data->sval;
}
else
{
data = "";
}
if (a_command->count)
{
command = *a_command->sval;
}
else
{
command = "";
}
for (int i = 0; i < a_recipient_tokens->count; i++)
{
recipientTokens.push_back(a_recipient_tokens->sval[i]);
}
if (a_recipient_token_file->count)
{
std::string fn(*a_recipient_token_file->sval);
std::string data = file2string(fn);
if (data.empty())
{
// try load from the Internet;
data = url2string(fn);
}
if (!data.empty()) {
parseJsonRecipientTokens(recipientTokens, data);
}
}
outputFormat = 0; // 0- text, 1- json
if (a_output->count)
{
if (strcmp("json", *a_output->sval) == 0)
outputFormat = 1;
}
aesgcm = a_aesgcm->count > 0;
invert_qrcode = a_invert_qrcode->count > 0;
// special case: '--help' takes precedence over error reporting
if ((a_help->count) || nerrors)
{
if (nerrors)
arg_print_errors(stderr, a_end, progname);
std::cerr << "Usage: " << progname << std::endl;
arg_print_syntax(stderr, argtable, "\n");
std::cerr << "Web push notification command line interface client" << std::endl;
arg_print_glossary(stderr, argtable, " %-25s %s\n");
arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
return 1;
}
arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
return 0;
}
int WpnConfig::error()
{
return errorcode;
}
SO_INSTANCE loadPlugin(const std::string &fileName)
{
#ifdef _MSC_VER
return LoadLibrary(fileName.c_str());
#else
return dlopen(fileName.c_str(), RTLD_LAZY);
#endif
}
void unloadPlugin(SO_INSTANCE so)
{
#ifdef _MSC_VER
FreeLibrary(so);
#else
dlclose(so);
#endif
}
static OnNotifyC loadDesktopNotifyC
(
SO_INSTANCE so,
const std::string &functionName
)
{
#ifdef _MSC_VER
return (OnNotifyC) GetProcAddress(so, functionName.c_str());
#else
return (OnNotifyC) dlsym(so, functionName.c_str());
#endif
}
size_t WpnConfig::loadNotifyFuncs()
{
notifyLibs.clear();
onNotifyList.clear();
size_t r = 0;
for (std::vector <std::string>::const_iterator it(notifyLibFileNames.begin()); it != notifyLibFileNames.end(); ++it)
{
std::string rp;
str_realpath(rp, (*it));
std::vector<std::string > files;
if (isDir(rp))
{
filesInPath(rp, DEF_PLUGIN_FILE_EXT, 1, &files);
}
else
{
files.push_back(rp);
}
for (std::vector<std::string>::const_iterator it(files.begin()); it != files.end(); ++it)
{
SO_INSTANCE so = loadPlugin(*it);
if (!so)
{
if (config && config->clientOptions && config->clientOptions->getVerbosity() > 1)
{
std::cerr << "Can not open shared library file: " << *it << std::endl;
}
continue;
}
notifyLibs.push_back(so);
OnNotifyC desktopNotify = loadDesktopNotifyC(so, notifyFunctionName);
if (!desktopNotify)
{
if (config && config->clientOptions && config->clientOptions->getVerbosity() > 1)
{
std::cerr << "Can not bind " << notifyFunctionName << "() from shared library file: " << *it << std::endl;
}
continue;
}
if (config && config->clientOptions && config->clientOptions->getVerbosity() > 2)
{
std::cerr << "Shared library " << *it << " loaded successfully." << std::endl;
}
onNotifyList.push_back(desktopNotify);
r++;
}
}
if (config && config->clientOptions && config->clientOptions->getVerbosity() > 1)
{
std::cerr << "Shared libraries loaded: " << r << std::endl;
}
return r;
}
void WpnConfig::unloadNotifyFuncs()
{
for (std::vector <SO_INSTANCE>::const_iterator it(notifyLibs.begin()); it != notifyLibs.end(); ++it)
{
unloadPlugin(*it);
}
notifyLibs.clear();
}
void WpnConfig::getPersistentIds(std::vector<std::string> &retval)
{
retval.clear();
retval.push_back(config->subscriptions->getReceivedPersistentId());
for (std::vector<Subscription>::iterator it(config->subscriptions->list.begin()); it != config->subscriptions->list.end(); ++it)
{
std::string v = it->getPersistentId();
if (!v.empty())
{
retval.push_back(v);
}
}
}
/**
* Get subscription by name
* @param subscriptionName subscription name
* @return server key from subscription by the name of subscription
*/
const Subscription *WpnConfig::getSubscription(const std::string &subscriptionName) const
{
for (std::vector<Subscription>::const_iterator it(config->subscriptions->list.begin()); it != config->subscriptions->list.end(); ++it)
{
std::string n = it->getName();
if (n == subscriptionName)
{
return &*it;
}
}
return NULL;
}
/**
* Get server key
* @param subscriptionName subscription name
* @return server key from subscription by the name of subscription
*/
std::string WpnConfig::getSubscriptionServerKey
(
const std::string &subscriptionName
) const
{
const Subscription *subscription = getSubscription(subscriptionName);
if (subscription)
return subscription->getServerKey();
return "";
}
/**
* Get FCM token
* @param subscriptionName subscription name
* @return FCM token from subscription by the name of subscription
*/
std::string WpnConfig::getSubscriptionToken
(
const std::string &subscriptionName
) const
{
const Subscription *subscription = getSubscription(subscriptionName);
if (subscription)
return subscription->getToken();
return "";
}
bool WpnConfig::setPersistentId
(
const std::string &authorizedEntity,
const std::string &persistentId
)
{
if (!config->subscriptions)
return false;
for (std::vector<Subscription>::iterator it(config->subscriptions->list.begin()); it != config->subscriptions->list.end(); ++it)
{
if (it->getAuthorizedEntity() == authorizedEntity)
{
it->setPersistentId(persistentId);
return true;
}
}
config->subscriptions->setReceivedPersistentId(persistentId);
return true;
}
std::string WpnConfig::versionString()
{
std::stringstream r;
r << "libprotobuf: " << google::protobuf::internal::VersionString(GOOGLE_PROTOBUF_VERSION);
return r.str();
}
| 26.470839 | 172 | 0.666989 | [
"vector"
] |
de18fa42e63b3f6e3d5ce32987943fafbec67a1c | 4,301 | hpp | C++ | src/gpu-sparse-matrix.hpp | inducer/iterative-cuda | e6413cff0466457957d99402f624cae0be06c3cc | [
"MIT"
] | null | null | null | src/gpu-sparse-matrix.hpp | inducer/iterative-cuda | e6413cff0466457957d99402f624cae0be06c3cc | [
"MIT"
] | null | null | null | src/gpu-sparse-matrix.hpp | inducer/iterative-cuda | e6413cff0466457957d99402f624cae0be06c3cc | [
"MIT"
] | 1 | 2020-11-23T09:55:57.000Z | 2020-11-23T09:55:57.000Z | /*
Iterative CUDA is licensed to you under the MIT/X Consortium license:
Copyright (c) 2009 Andreas Kloeckner.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the Software), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#ifndef AAFADFJ_ITERATIVE_CUDA_GPU_SPARSE_MATRIX_HPP_SEEN
#define AAFADFJ_ITERATIVE_CUDA_GPU_SPARSE_MATRIX_HPP_SEEN
#include <iterative-cuda.hpp>
#include <stdint.h>
#include <iostream>
#include "helpers.hpp"
#include "partition.h"
#include "csr_to_pkt.h"
#include "utils.h"
#include "kernels/spmv_pkt_device.cu.h"
#include "cpu-sparse-matrix.hpp"
namespace iterative_cuda
{
typedef uint32_t packed_index_type;
template <typename ValueType, typename IndexType>
struct gpu_sparse_pkt_matrix_pimpl
{
pkt_matrix<IndexType, ValueType> matrix;
};
template <typename VT, typename IT>
inline gpu_sparse_pkt_matrix<VT, IT>::gpu_sparse_pkt_matrix(
cpu_sparse_csr_matrix<VT, IT> const &csr_mat)
: pimpl(new gpu_sparse_pkt_matrix_pimpl<VT, IT>)
{
index_type rows_per_packet =
(SHARED_MEM_BYTES - 100)
/ (2*sizeof(value_type));
index_type block_count = ICUDA_DIVIDE_INTO(
csr_mat.row_count(), rows_per_packet);
std::vector<index_type> partition;
bool partition_ok;
partition.resize(csr_mat.row_count());
do
{
partition_csr(csr_mat.pimpl->matrix, block_count, partition, /*Kway*/ true);
std::vector<index_type> block_occupancy(block_count, 0);
for (index_type i = 0; i < csr_mat.row_count(); ++i)
++block_occupancy[partition[i]];
partition_ok = true;
for (index_type i = 0; i < block_count; ++i)
if (block_occupancy[i] > rows_per_packet)
{
std::cerr << "Metis partition invalid, retrying with more parts..." << std::endl;
partition_ok = false;
block_count += 2 + int(1.02*block_count);
break;
}
}
while (!partition_ok);
pkt_matrix<index_type, value_type> host_matrix =
csr_to_pkt(csr_mat.pimpl->matrix, partition.data());
pimpl->matrix = copy_matrix_to_device(host_matrix);
delete_pkt_matrix(host_matrix, HOST_MEMORY);
}
template <typename VT, typename IT>
inline gpu_sparse_pkt_matrix<VT, IT>::~gpu_sparse_pkt_matrix()
{
delete_pkt_matrix(pimpl->matrix, DEVICE_MEMORY);
}
template <typename VT, typename IT>
inline IT gpu_sparse_pkt_matrix<VT, IT>::row_count() const
{
return pimpl->matrix.num_rows;
}
template <typename VT, typename IT>
inline IT gpu_sparse_pkt_matrix<VT, IT>::column_count() const
{
return pimpl->matrix.num_cols;
}
template <typename VT, typename IT>
inline void gpu_sparse_pkt_matrix<VT, IT>::permute(
vector_type &dest,
vector_type const &src) const
{
gather_device(dest.ptr(), src.ptr(),
pimpl->matrix.permute_new_to_old, row_count());
}
template <typename VT, typename IT>
inline void gpu_sparse_pkt_matrix<VT, IT>::unpermute(
vector_type &dest,
vector_type const &src) const
{
gather_device(dest.ptr(), src.ptr(),
pimpl->matrix.permute_old_to_new, row_count());
}
template <typename VT, typename IT>
inline void gpu_sparse_pkt_matrix<VT, IT>::operator()(
vector_type &dest, vector_type const &src) const
{
spmv_pkt_device(pimpl->matrix, src.ptr(), dest.ptr());
}
}
#endif
| 25.005814 | 91 | 0.715648 | [
"vector"
] |
de19327473670e4507ada382a2bcbcea8e0045ce | 29,135 | cpp | C++ | deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgPlugins/shp/ESRIShape.cpp | UM-ARM-Lab/mab_ms | f199f05b88060182cfbb47706bd1ff3479032c43 | [
"BSD-2-Clause"
] | 3 | 2018-08-20T12:12:43.000Z | 2021-06-06T09:43:27.000Z | deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgPlugins/shp/ESRIShape.cpp | UM-ARM-Lab/mab_ms | f199f05b88060182cfbb47706bd1ff3479032c43 | [
"BSD-2-Clause"
] | null | null | null | deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgPlugins/shp/ESRIShape.cpp | UM-ARM-Lab/mab_ms | f199f05b88060182cfbb47706bd1ff3479032c43 | [
"BSD-2-Clause"
] | 1 | 2022-03-31T03:12:23.000Z | 2022-03-31T03:12:23.000Z |
#if defined(_MSC_VER) || defined(__MINGW32__)
#include <stdio.h>
#include <io.h>
namespace esri
{
int read(int fd, void * buf, size_t nbytes) { return _read(fd, buf, nbytes); }
}
#else
#include <unistd.h>
namespace esri
{
int read(int fd, void * buf, size_t nbytes) { return ::read(fd, buf, nbytes); }
}
#endif
#include "ESRIShape.h"
using namespace ESRIShape ;
#define SAFE_DELETE_ARRAY( ptr ) delete[] ptr; ptr = 0L;
template <class T>
inline void swapBytes( T &s )
{
if( sizeof( T ) == 1 ) return;
T d = s;
BytePtr sptr = (BytePtr)&s;
BytePtr dptr = &(((BytePtr)&d)[sizeof(T)-1]);
for( unsigned int i = 0; i < sizeof(T); i++ )
*(sptr++) = *(dptr--);
}
inline ByteOrder getByteOrder()
{
int one = 1;
unsigned char *ptr = (unsigned char *)&one;
if( ptr[0] == 1 )
return LittleEndian;
else
return BigEndian;
}
template <class T>
inline bool readVal( int fd, T &val, ByteOrder bo = LittleEndian )
{
int nbytes = 0;
if( (nbytes = esri::read( fd, &val, sizeof(T))) <= 0 )
return false;
if( getByteOrder() != bo )
swapBytes<T>(val);
return true;
}
inline void printType( ShapeType type )
{
printf( "%s",
type == ShapeTypeNullShape ? "NullShape" :
type == ShapeTypePoint ? "Point" :
type == ShapeTypePolyLine ? "PolyLine" :
type == ShapeTypePolygon ? "Polygon" :
type == ShapeTypeMultiPoint ? "MultiPoint" :
type == ShapeTypePointZ ? "PointZ" :
type == ShapeTypePolyLineZ ? "PolyLineZ" :
type == ShapeTypePolygonZ ? "PolygonZ" :
type == ShapeTypeMultiPointZ ? "MultiPointZ" :
type == ShapeTypePointM ? "PointM" :
type == ShapeTypePolyLineM ? "PolyLineM" :
type == ShapeTypePolygonM ? "PolygonM" :
type == ShapeTypeMultiPointM ? "MultiPointM" :
type == ShapeTypeMultiPatch ? "MultiPatch" : "Unknown" );
}
bool BoundingBox::read( int fd )
{
if( readVal<Double>(fd, Xmin, LittleEndian ) == false ) return false;
if( readVal<Double>(fd, Ymin, LittleEndian ) == false ) return false;
if( readVal<Double>(fd, Xmax, LittleEndian ) == false ) return false;
if( readVal<Double>(fd, Ymax, LittleEndian ) == false ) return false;
if( readVal<Double>(fd, Zmin, LittleEndian ) == false ) return false;
if( readVal<Double>(fd, Zmax, LittleEndian ) == false ) return false;
if( readVal<Double>(fd, Mmin, LittleEndian ) == false ) return false;
if( readVal<Double>(fd, Mmax, LittleEndian ) == false ) return false;
return true;
}
void BoundingBox::print()
{
printf( " Xmin: %G\n", Xmin );
printf( " Ymin: %G\n", Ymin );
printf( " Xmax: %G\n", Xmax );
printf( " Ymax: %G\n", Ymax );
printf( " Zmin: %G\n", Zmin );
printf( " Zmax: %G\n", Zmax );
printf( " Mmin: %G\n", Mmin );
printf( " Mmax: %G\n", Mmax );
}
bool ShapeHeader::read(int fd)
{
if( readVal<Integer>( fd, fileCode, BigEndian ) == false ) return false;
if( esri::read( fd, _unused_0, sizeof(_unused_0)) <= 0 ) return false;
if( readVal<Integer>( fd, fileLength, BigEndian ) == false ) return false;
if( readVal<Integer>( fd, version, LittleEndian ) == false ) return false;
if( readVal<Integer>( fd, shapeType, LittleEndian ) == false ) return false;
bbox.read(fd);
return true;
}
void ShapeHeader::print()
{
printf( "File Code: %d\n", fileCode );
printf( "File Length: %d\n", fileLength );
printf( "Version: %d\n", version );
printf( "Shape Type: "); printType( ShapeType(shapeType) ); printf( "\n" );
printf( "Bounding Box:\n" );
bbox.print();
}
RecordHeader::RecordHeader():
recordNumber(-1),
contentLength(0)
{
}
bool RecordHeader::read( int fd )
{
if( readVal<Integer>( fd, recordNumber, BigEndian ) == false ) return false;
if( readVal<Integer>( fd, contentLength, BigEndian ) == false ) return false;
return true;
}
void RecordHeader::print()
{
printf( " Record Number: %d\n", recordNumber );
printf( "Content Length: %d\n", contentLength );
}
NullRecord::NullRecord():
shapeType(ShapeTypeNullShape)
{}
bool NullRecord::read( int fd )
{
if( readVal<Integer>( fd, shapeType, LittleEndian ) == false ) return false;
return true;
}
Box::Box() {}
Box::Box(const Box &b ):
Xmin(b.Xmin),
Ymin(b.Ymin),
Xmax(b.Xmax),
Ymax(b.Ymax)
{}
bool Box::read( int fd )
{
if( readVal<Double>(fd, Xmin, LittleEndian) == false ) return false;
if( readVal<Double>(fd, Ymin, LittleEndian) == false ) return false;
if( readVal<Double>(fd, Xmax, LittleEndian) == false ) return false;
if( readVal<Double>(fd, Ymax, LittleEndian) == false ) return false;
return true;
}
Range::Range() {}
Range::Range( const Range &r ): min(r.min), max(r.max) {}
bool Range::read( int fd )
{
if( readVal<Double>(fd, min, LittleEndian ) == false ) return false;
if( readVal<Double>(fd, max, LittleEndian ) == false ) return false;
return true;
}
ShapeObject::ShapeObject(ShapeType s):
shapeType(s)
{}
ShapeObject::~ShapeObject()
{ }
Point::Point():
ShapeObject(ShapeTypePoint),
x(0.0),
y(0.0)
{}
Point::Point(const Point &p):
ShapeObject(ShapeTypePoint),
x(p.x),
y(p.y)
{}
Point::~Point() {}
bool Point::read( int fd )
{
if( readVal<Double>( fd, x, LittleEndian ) == false ) return false;
if( readVal<Double>( fd, y, LittleEndian ) == false ) return false;
return true;
}
bool PointRecord::read( int fd )
{
RecordHeader rh;
if( rh.read(fd) == false )
return false;
Integer shapeType;
if( readVal<Integer>(fd, shapeType, LittleEndian ) == false )
return false;
if( shapeType != ShapeTypePoint )
return false;
return point.read(fd);
}
void Point::print()
{
printf( " %G %G\n", x, y );
}
MultiPoint::MultiPoint():
ShapeObject(ShapeTypeMultiPoint),
numPoints(0),
points(0L)
{}
MultiPoint::MultiPoint( const struct MultiPoint &mpoint ): ShapeObject(ShapeTypeMultiPoint),
bbox(mpoint.bbox),
numPoints(mpoint.numPoints)
{
points = new Point[numPoints];
for( int i = 0; i < numPoints; i++ )
points[i] = mpoint.points[i];
}
MultiPoint::~MultiPoint()
{
delete[] points;
}
bool MultiPoint::read( int fd )
{
RecordHeader rh;
if( rh.read(fd) == false )
return false;
SAFE_DELETE_ARRAY( points );
Integer shapeType;
if( readVal<Integer>(fd, shapeType, LittleEndian ) == false )
return false;
if( shapeType != ShapeTypeMultiPoint )
return false;
if( bbox.read(fd) == false )
return false;
if( readVal<Integer>(fd, numPoints, LittleEndian ) == false )
return false;
points = new struct Point[numPoints];
for( Integer i = 0; i < numPoints; i++ )
{
if( points[i].read(fd) == false )
return false;
}
return true;
}
void MultiPoint::print()
{
printf( "Point - numPoints: %d\n", numPoints );
for( int i= 0; i < numPoints; i++ )
points[i].print();
}
PolyLine::PolyLine():
ShapeObject(ShapeTypePolyLine),
numParts(0),
numPoints(0),
parts(0L),
points(0L) {}
PolyLine::PolyLine( const PolyLine &p ):
ShapeObject(ShapeTypePolyLine),
numParts(p.numParts),
numPoints(p.numPoints)
{
parts = new Integer[numParts];
Integer i;
for(i = 0; i < numParts; i++ )
parts[i] = p.parts[i];
points = new Point[numPoints];
for(i = 0; i < numPoints; i++ )
points[i] = p.points[i];
}
PolyLine::~PolyLine()
{
delete [] parts;
delete [] points;
}
bool PolyLine::read( int fd )
{
RecordHeader rh;
if( rh.read(fd) == false )
return false;
SAFE_DELETE_ARRAY( parts );
SAFE_DELETE_ARRAY( points );
Integer shapeType;
if( readVal<Integer>(fd, shapeType, LittleEndian ) == false )
return false;
if( shapeType != ShapeTypePolyLine )
return false;
if( bbox.read(fd) == false )
return false;
if( readVal<Integer>(fd, numParts, LittleEndian ) == false )
return false;
if( readVal<Integer>(fd, numPoints, LittleEndian ) == false )
return false;
parts = new Integer[numParts];
int i;
for( i = 0; i < numParts; i++ )
{
if( readVal<Integer>(fd, parts[i], LittleEndian ) == false )
return false;
}
points = new struct Point[numPoints];
for( i = 0; i < numPoints; i++ )
{
if( points[i].read(fd ) == false )
return false;
}
return true;
}
Polygon::Polygon():
ShapeObject(ShapeTypePolygon),
numParts(0),
numPoints(0),
parts(0L),
points(0L) {}
Polygon::Polygon( const Polygon &p ):
ShapeObject(ShapeTypePolygon),
numParts(p.numParts),
numPoints(p.numPoints)
{
parts = new Integer[numParts];
Integer i;
for( i = 0; i < numParts; i++ )
parts[i] = p.parts[i];
points = new Point[numPoints];
for( i = 0; i < numPoints; i++ )
points[i] = p.points[i];
}
Polygon::~Polygon()
{
delete [] parts;
delete [] points;
}
bool Polygon::read( int fd )
{
RecordHeader rh;
if( rh.read(fd) == false )
return false;
SAFE_DELETE_ARRAY( parts );
SAFE_DELETE_ARRAY( points );
Integer shapeType;
if( readVal<Integer>(fd, shapeType, LittleEndian ) == false )
return false;
if( shapeType != ShapeTypePolygon )
return false;
if( bbox.read(fd) == false )
return false;
if( readVal<Integer>(fd, numParts, LittleEndian ) == false )
return false;
if( readVal<Integer>(fd, numPoints, LittleEndian ) == false )
return false;
parts = new Integer[numParts];
int i;
for( i = 0; i < numParts; i++ )
{
if( readVal<Integer>(fd, parts[i], LittleEndian ) == false )
return false;
}
points = new struct Point[numPoints];
for( i = 0; i < numPoints; i++ )
{
if( points[i].read(fd ) == false )
return false;
}
return true;
}
//////////////////////////////////////////////////////////////////////
PointM::PointM():
ShapeObject(ShapeTypePointM),
x(0.0),
y(0.0),
m(0.0)
{}
PointM::PointM(const PointM &p):
ShapeObject(ShapeTypePointM),
x(p.x),
y(p.y),
m(p.m)
{}
PointM::~PointM() {}
bool PointM::read( int fd )
{
if( readVal<Double>( fd, x, LittleEndian ) == false ) return false;
if( readVal<Double>( fd, y, LittleEndian ) == false ) return false;
if( readVal<Double>( fd, m, LittleEndian ) == false ) return false;
return true;
}
void PointM::print()
{
printf( " %G %G (%G)\n", x, y, m );
}
bool PointMRecord::read( int fd )
{
RecordHeader rh;
if( rh.read(fd) == false )
return false;
Integer shapeType;
if( readVal<Integer>(fd, shapeType, LittleEndian ) == false )
return false;
if( shapeType != ShapeTypePointM )
return false;
return pointM.read(fd);
}
MultiPointM::MultiPointM():
ShapeObject(ShapeTypeMultiPointM),
numPoints(0),
points(0L),
mArray(0L)
{}
MultiPointM::MultiPointM( const struct MultiPointM &mpointm ):
ShapeObject(ShapeTypeMultiPointM),
bbox(mpointm.bbox),
numPoints(mpointm.numPoints),
mRange(mpointm.mRange)
{
points = new Point[numPoints];
mArray = new Double[numPoints];
for( int i = 0; i < numPoints; i++ )
{
points[i] = mpointm.points[i];
mArray[i] = mpointm.mArray[i];
}
}
MultiPointM::~MultiPointM()
{
delete [] points;
delete [] mArray;
}
bool MultiPointM::read( int fd )
{
RecordHeader rh;
if( rh.read(fd) == false )
return false;
SAFE_DELETE_ARRAY( points );
SAFE_DELETE_ARRAY( mArray );
Integer shapeType;
if( readVal<Integer>(fd, shapeType, LittleEndian ) == false )
return false;
if( shapeType != ShapeTypeMultiPointM )
return false;
if( bbox.read(fd) == false )
return false;
if( readVal<Integer>(fd, numPoints, LittleEndian ) == false )
return false;
points = new struct Point[numPoints];
Integer i;
for( i = 0; i < numPoints; i++ )
{
if( points[i].read(fd) == false )
return false;
}
int X = 40 + (16 * numPoints);
if( rh.contentLength > X )
{
if( mRange.read(fd) == false )
return false;
mArray = new Double[numPoints];
for( i = 0; i < numPoints; i++ )
{
if( readVal<Double>(fd, mArray[i], LittleEndian ) == false )
return false;
}
}
return true;
}
void MultiPointM::print()
{
printf( "Point - numPoints: %d\n", numPoints );
for( int i= 0; i < numPoints; i++ )
points[i].print();
}
PolyLineM::PolyLineM():
ShapeObject(ShapeTypePolyLineM),
numParts(0),
numPoints(0),
parts(0L),
points(0L),
mArray(0L)
{}
PolyLineM::PolyLineM(const PolyLineM &p):
ShapeObject(ShapeTypePolyLineM),
numParts(p.numParts),
numPoints(p.numPoints),
parts(0L),
points(0L),
mArray(0L)
{
parts = new Integer[numParts];
Integer i;
for( i = 0; i < numParts; i++ )
parts[i] = p.parts[i];
points = new Point[numPoints];
mArray = new Double[numPoints];
for( i = 0; i < numPoints; i++ )
{
points[i] = p.points[i];
mArray[i] = p.mArray[i];
}
}
PolyLineM::~PolyLineM()
{
delete [] parts;
delete [] points;
delete [] mArray;
}
bool PolyLineM::read( int fd )
{
RecordHeader rh;
if( rh.read(fd) == false )
return false;
SAFE_DELETE_ARRAY( parts );
SAFE_DELETE_ARRAY( points );
SAFE_DELETE_ARRAY( mArray );
Integer shapeType;
if( readVal<Integer>(fd, shapeType, LittleEndian ) == false )
return false;
if( shapeType != ShapeTypePolyLineM )
return false;
if( bbox.read(fd) == false )
return false;
if( readVal<Integer>(fd, numParts, LittleEndian ) == false )
return false;
if( readVal<Integer>(fd, numPoints, LittleEndian ) == false )
return false;
parts = new Integer[numParts];
int i;
for( i = 0; i < numParts; i++ )
{
if( readVal<Integer>(fd, parts[i], LittleEndian ) == false )
return false;
}
points = new struct Point[numPoints];
for( i = 0; i < numPoints; i++ )
{
if( points[i].read(fd ) == false )
return false;
}
int X = 44 + (4 * numParts);
int Y = X + (16 * numPoints);
if( rh.contentLength > Y )
{
mRange.read(fd);
mArray = new Double[numPoints];
for( i = 0; i < numPoints; i++ )
{
if( readVal<Double>(fd, mArray[i], LittleEndian ) == false )
return false;
}
}
return true;
}
PolygonM::PolygonM():
ShapeObject(ShapeTypePolygonM),
numParts(0),
numPoints(0),
parts(0L),
points(0L) ,
mArray(0L)
{}
PolygonM::PolygonM(const PolygonM &p):
ShapeObject(ShapeTypePolygonM),
numParts(p.numParts),
numPoints(p.numPoints),
parts(0L),
points(0L) ,
mArray(0L)
{
parts = new Integer[numParts];
Integer i;
for( i = 0; i < numParts; i++ )
parts[i] = p.parts[i];
points = new Point[numPoints];
mArray = new Double[numPoints];
for( i = 0; i < numPoints; i++ )
{
points[i] = p.points[i];
mArray[i] = p.mArray[i];
}
}
PolygonM::~PolygonM()
{
delete[] parts;
delete[] points;
delete[] mArray;
}
bool PolygonM::read( int fd )
{
RecordHeader rh;
if( rh.read(fd) == false )
return false;
SAFE_DELETE_ARRAY( parts );
SAFE_DELETE_ARRAY( points );
SAFE_DELETE_ARRAY( mArray );
Integer shapeType;
if( readVal<Integer>(fd, shapeType, LittleEndian ) == false )
return false;
if( shapeType != ShapeTypePolygonM )
return false;
if( bbox.read(fd) == false )
return false;
if( readVal<Integer>(fd, numParts, LittleEndian ) == false )
return false;
if( readVal<Integer>(fd, numPoints, LittleEndian ) == false )
return false;
parts = new Integer[numParts];
int i;
for( i = 0; i < numParts; i++ )
{
if( readVal<Integer>(fd, parts[i], LittleEndian ) == false )
return false;
}
points = new struct Point[numPoints];
for( i = 0; i < numPoints; i++ )
{
if( points[i].read(fd ) == false )
return false;
}
int X = 44 + (4 * numParts);
int Y = X + (16 * numPoints);
if( rh.contentLength > Y )
{
if( mRange.read(fd) == false )
return false;
mArray = new Double[numPoints];
for( i = 0; i < numPoints; i++ )
{
if( readVal<Double>(fd, mArray[i], LittleEndian ) == false )
return false;
}
}
return true;
}
//////////////////////////////////////////////////////////////////////
PointZ::PointZ():
ShapeObject(ShapeTypePointZ),
x(0.0),
y(0.0),
z(0.0),
m(0.0)
{}
PointZ::PointZ(const PointZ &p):
ShapeObject(ShapeTypePointZ),
x(p.x),
y(p.y),
z(p.z),
m(p.m)
{}
PointZ::~PointZ() {}
bool PointZ::read( int fd )
{
RecordHeader rh;
if( rh.read(fd) == false )
return false;
Integer shapeType;
if( readVal<Integer>(fd, shapeType, LittleEndian ) == false )
return false;
if( shapeType != ShapeTypePointZ )
return false;
if( readVal<Double>( fd, x, LittleEndian ) == false )
return false;
if( readVal<Double>( fd, y, LittleEndian ) == false )
return false;
if( readVal<Double>( fd, z, LittleEndian ) == false )
return false;
// Sometimes, M field is not supplied
if( rh.contentLength >= 18 )
if( readVal<Double>( fd, m, LittleEndian ) == false )
return false;
return true;
}
void PointZ::print()
{
printf( " %G %G %G (%G)\n", x, y, z, m );
}
MultiPointZ::MultiPointZ():
ShapeObject(ShapeTypeMultiPointZ),
numPoints(0),
points(0L),
zArray(0L),
mArray(0L)
{}
MultiPointZ::MultiPointZ( const struct MultiPointZ &mpointm ):
ShapeObject(ShapeTypeMultiPointZ),
bbox(mpointm.bbox),
numPoints(mpointm.numPoints),
zRange(mpointm.zRange),
mRange(mpointm.mRange)
{
points = new Point[numPoints];
zArray = new Double[numPoints];
mArray = new Double[numPoints];
for( int i = 0; i < numPoints; i++ )
{
points[i] = mpointm.points[i];
zArray[i] = mpointm.zArray[i];
mArray[i] = mpointm.mArray[i];
}
}
MultiPointZ::~MultiPointZ()
{
delete [] points;
delete [] zArray;
delete [] mArray;
}
bool MultiPointZ::read( int fd )
{
RecordHeader rh;
if( rh.read(fd) == false )
return false;
SAFE_DELETE_ARRAY( points );
SAFE_DELETE_ARRAY( zArray );
SAFE_DELETE_ARRAY( mArray );
Integer shapeType;
if( readVal<Integer>(fd, shapeType, LittleEndian ) == false )
return false;
if( shapeType != ShapeTypeMultiPointZ )
return false;
if( bbox.read(fd) == false )
return false;
if( readVal<Integer>(fd, numPoints, LittleEndian ) == false )
return false;
points = new struct Point[numPoints];
Integer i;
for( i = 0; i < numPoints; i++ )
{
if( points[i].read(fd) == false )
return false;
}
if( zRange.read(fd) == false )
return false;
zArray = new Double[numPoints];
for( i = 0; i < numPoints; i++ )
{
if( readVal<Double>(fd, zArray[i], LittleEndian) == false )
return false;
}
int X = 40 + (16*numPoints);
int Y = X + 16 + (8*numPoints);
if( rh.contentLength > Y )
{
if( mRange.read(fd) == false )
return false;
mArray = new Double[numPoints];
for( i = 0; i < numPoints; i++ )
{
if( readVal<Double>(fd, mArray[i], LittleEndian ) == false )
return false;
}
}
return true;
}
void MultiPointZ::print()
{
printf( "Point - numPoints: %d\n", numPoints );
for( int i= 0; i < numPoints; i++ )
points[i].print();
}
PolyLineZ::PolyLineZ():
ShapeObject(ShapeTypePolyLineZ),
numParts(0),
numPoints(0),
parts(0L),
points(0L),
zArray(0L) ,
mArray(0L)
{}
PolyLineZ::PolyLineZ(const PolyLineZ &p):
ShapeObject(ShapeTypePolyLineZ),
numParts(p.numParts),
numPoints(p.numPoints),
parts(0L),
points(0L),
zArray(0L) ,
mArray(0L)
{
parts = new Integer[numParts];
Integer i;
for( i = 0; i < numParts; i++ )
parts[i] = p.parts[i];
points = new Point[numPoints];
zArray = new Double[numPoints];
for( i = 0; i < numPoints; i++ )
{
points[i] = p.points[i];
zArray[i] = p.zArray[i];
}
// Sometimes, M Array is not present on the file
if( p.mArray != NULL )
{
mArray = new Double[numPoints];
for( i = 0; i < numPoints; i++ )
mArray[i] = p.mArray[i];
}
}
PolyLineZ::~PolyLineZ()
{
delete [] parts;
delete [] points;
delete [] zArray;
delete [] mArray;
}
bool PolyLineZ::read( int fd )
{
RecordHeader rh;
if( rh.read(fd) == false )
return false;
SAFE_DELETE_ARRAY( parts );
SAFE_DELETE_ARRAY( points );
SAFE_DELETE_ARRAY( zArray );
SAFE_DELETE_ARRAY( mArray );
Integer shapeType;
if( readVal<Integer>(fd, shapeType, LittleEndian ) == false )
return false;
if( shapeType != ShapeTypePolyLineZ )
return false;
if( bbox.read(fd) == false )
return false;
if( readVal<Integer>(fd, numParts, LittleEndian ) == false )
return false;
if( readVal<Integer>(fd, numPoints, LittleEndian ) == false )
return false;
parts = new Integer[numParts];
int i;
for( i = 0; i < numParts; i++ )
{
if( readVal<Integer>(fd, parts[i], LittleEndian ) == false )
return false;
}
points = new struct Point[numPoints];
for( i = 0; i < numPoints; i++ )
{
if( points[i].read(fd ) == false )
return false;
}
zRange.read(fd);
zArray = new Double[numPoints];
for( i = 0; i < numPoints; i++ )
{
if( readVal<Double>(fd, zArray[i], LittleEndian ) == false )
return false;
}
int X = 44 + (4 * numParts);
int Y = X + (15 * numPoints);
int Z = Y + 16 + (8 * numPoints);
if( rh.contentLength != Z )
{
mRange.read(fd);
mArray = new Double[numPoints];
for( i = 0; i < numPoints; i++ )
{
if( readVal<Double>(fd, mArray[i], LittleEndian ) == false )
return false;
}
}
return true;
}
PolygonZ::PolygonZ():
ShapeObject(ShapeTypePolygonZ),
numParts(0),
numPoints(0),
parts(0L),
points(0L),
zArray(0L),
mArray(0L)
{}
PolygonZ::PolygonZ(const PolygonZ &p):
ShapeObject(ShapeTypePolygonZ),
numParts(p.numParts),
numPoints(p.numPoints),
parts(0L),
points(0L) ,
mArray(0L)
{
parts = new Integer[numParts];
Integer i;
for( i = 0; i < numParts; i++ )
parts[i] = p.parts[i];
points = new Point[numPoints];
zArray = new Double[numPoints]; // jcm
mArray = new Double[numPoints];
for( i = 0; i < numPoints; i++ )
{
points[i] = p.points[i];
zArray[i] = p.zArray[i]; // jcm
// M-Array seems to be missing sometimes
if(p.mArray)
mArray[i] = p.mArray[i];
}
}
PolygonZ::~PolygonZ()
{
delete [] parts;
delete [] points;
delete [] zArray;
delete [] mArray;
}
bool PolygonZ::read( int fd )
{
RecordHeader rh;
if( rh.read(fd) == false )
return false;
SAFE_DELETE_ARRAY( parts );
SAFE_DELETE_ARRAY( points );
SAFE_DELETE_ARRAY( zArray );
SAFE_DELETE_ARRAY( mArray );
Integer shapeType;
if( readVal<Integer>(fd, shapeType, LittleEndian ) == false )
return false;
if( shapeType != ShapeTypePolygonZ )
return false;
if( bbox.read(fd) == false )
return false;
if( readVal<Integer>(fd, numParts, LittleEndian ) == false )
return false;
if( readVal<Integer>(fd, numPoints, LittleEndian ) == false )
return false;
parts = new Integer[numParts];
int i;
for( i = 0; i < numParts; i++ )
{
if( readVal<Integer>(fd, parts[i], LittleEndian ) == false )
return false;
}
points = new struct Point[numPoints];
for( i = 0; i < numPoints; i++ )
{
if( points[i].read(fd ) == false )
return false;
}
if( zRange.read(fd) == false )
return false;
zArray = new Double[numPoints];
for( i = 0; i < numPoints; i++ )
{
if( readVal<Double>(fd, zArray[i], LittleEndian ) == false )
return false;
}
int X = 44 + (4*numParts);
int Y = X + (16*numPoints);
int Z = Y + 16 + (8*numPoints);
if( rh.contentLength != Z )
{
if( mRange.read(fd) == false )
return false;
mArray = new Double[numPoints];
for( i = 0; i < numPoints; i++ )
{
if( readVal<Double>(fd, mArray[i], LittleEndian ) == false )
return false;
}
}
return true;
}
//////////////////////////////////////////////////////////////////////
/*
struct MultiPatch
{
Box bbox;
Integer numParts;
Integer numPoints;
Integer *parts;
Integer *partTypes;
struct Point *points;
Range zRange;
Double *zArray;
Range mRange;
Double *mArray;
MultiPatch();
MultiPatch( const MultiPatch &);
virtual ~MultiPatch();
bool read( fd );
};
*/
MultiPatch::MultiPatch():
numParts(0),
numPoints(0),
parts(0L),
partTypes(0L),
points(0L),
zArray(0L),
mArray(0L)
{ }
MultiPatch::MultiPatch( const MultiPatch &mp):
bbox(mp.bbox),
numParts(mp.numParts),
numPoints(mp.numPoints),
zRange(mp.zRange),
mRange(mp.mRange)
{
parts = new Integer[numParts];
partTypes = new Integer[numParts];
Integer i;
for( i = 0; i < numParts; i++ )
{
parts[i] = mp.parts[i];
partTypes[i] = mp.partTypes[i];
}
points = new Point[numPoints];
zArray = new Double[numPoints];
mArray = new Double[numPoints];
for( i = 0; i < numPoints; i++ )
{
points[i] = mp.points[i];
zArray[i] = mp.zArray[i];
if( mp.mArray != 0L )
mArray[i] = mp.mArray[i];
}
}
MultiPatch::~MultiPatch()
{
delete [] parts;
delete [] partTypes;
delete [] points;
delete [] zArray;
delete [] mArray;
}
bool MultiPatch::read( int fd )
{
RecordHeader rh;
if( rh.read(fd) == false )
return false;
SAFE_DELETE_ARRAY( parts );
SAFE_DELETE_ARRAY( partTypes );
SAFE_DELETE_ARRAY( points );
SAFE_DELETE_ARRAY( zArray );
SAFE_DELETE_ARRAY( mArray );
Integer shapeType;
if( readVal<Integer>(fd, shapeType, LittleEndian ) == false )
return false;
if( shapeType != ShapeTypeMultiPatch )
return false;
if( bbox.read(fd) == false )
return false;
if( readVal<Integer>(fd, numParts, LittleEndian ) == false )
return false;
if( readVal<Integer>(fd, numPoints, LittleEndian ) == false )
return false;
parts = new Integer[numParts];
int i;
for( i = 0; i < numParts; i++ )
{
if( readVal<Integer>(fd, parts[i], LittleEndian ) == false )
return false;
}
partTypes = new Integer[numParts];
for( i = 0; i < numParts; i++ )
{
if( readVal<Integer>(fd, partTypes[i], LittleEndian ) == false )
return false;
}
points = new struct Point[numPoints];
for( i = 0; i < numPoints; i++ )
{
if( points[i].read(fd ) == false )
return false;
}
if( zRange.read(fd) == false )
return false;
zArray = new Double[numPoints];
for( i = 0; i < numPoints; i++ )
{
if( readVal<Double>(fd, zArray[i], LittleEndian ) == false )
return false;
}
int W = 44 + (4*numParts);
int X = W + (4 * numParts);
int Y = X + (16 *numPoints);
int Z = Y + 16 + (8 *numPoints);
if( rh.contentLength > Z )
{
if( mRange.read(fd) == false )
return false;
mArray = new Double[numPoints];
for( i = 0; i < numPoints; i++ )
{
if( readVal<Double>(fd, mArray[i], LittleEndian ) == false )
return false;
}
}
return true;
}
| 22.274465 | 93 | 0.554865 | [
"shape"
] |
de1e402d6ee9a3f6e3efd648154dfba191a8834a | 1,772 | cpp | C++ | sender/ReviewSendermain.cpp | amutamil/review-case-s1b4 | f40a87465cbaacf67adf3bcfb12473ee7553210b | [
"MIT"
] | null | null | null | sender/ReviewSendermain.cpp | amutamil/review-case-s1b4 | f40a87465cbaacf67adf3bcfb12473ee7553210b | [
"MIT"
] | null | null | null | sender/ReviewSendermain.cpp | amutamil/review-case-s1b4 | f40a87465cbaacf67adf3bcfb12473ee7553210b | [
"MIT"
] | 1 | 2020-10-16T05:43:12.000Z | 2020-10-16T05:43:12.000Z |
#include<iostream>
#include<vector>
#include<fstream>
#include"fileToArrayConverter.h"
#include"ColumnFilter.h"
using namespace std;
void MessageWhenFileNameNotEntered(int argc)
{
if (FileToArrayConverter::IsArgumentCountEqaulToOne(argc))
{
cerr << "File name not passsed" << endl;
exit(1);
}
}
void MessageWhenFileIsNotOpen(ifstream& fin, char* argv[])
{
if (FileToArrayConverter::IsFileNotOpen(fin, argv[1]))
{
cerr << "File cannot be opened" << endl;
exit(1);
}
}
void MessageWhenFileIsEmpty(vector<vector<string>> csvFileArray)
{
if (FileToArrayConverter::IsFileArrayIsEmpty(csvFileArray))
{
cerr << "File is Empty" << endl;
exit(1);
}
}
void MessageWhenIncorrectColumnNumberIsEntered(vector<vector<string>> csvFileArray, string colNum)
{
if (!(ColumnFilter::IsColumnNumberCorrect(csvFileArray, colNum)))
{
cerr << "Incorrect Column Number" << endl;
exit(1);
}
}
int main(int argc,char*argv[])
{
ifstream fin;
MessageWhenFileNameNotEntered(argc);
MessageWhenFileIsNotOpen(fin,argv);
FileToArrayConverter::FileToArrayConverter *filepointer;
filepointer= new(nothrow)FileToArrayConverter::CSVFileToArrayConverter(fin);
vector<vector<string>> csvFileArray;
if(filepointer!=NULL)
csvFileArray = filepointer->getFileArray();
MessageWhenFileIsEmpty(csvFileArray);
fin.close();
vector<string> ColumnReview;
if (argc > 2)
{
MessageWhenIncorrectColumnNumberIsEntered(csvFileArray, argv[2]);
int colNum = stoi(argv[2]);
ColumnFilter::ColumnFilter colFilter(csvFileArray,colNum);
ColumnReview = colFilter.getColumn();
ColumnFilter::printColumnReview(ColumnReview);
}
else
FileToArrayConverter::printReview(csvFileArray);
return 0;
} | 23.945946 | 99 | 0.721219 | [
"vector"
] |
de2256976a464783d0595e2cb455ac9865b3511e | 11,308 | cpp | C++ | Common/MdfParser/IOVectorLayerDefinition.cpp | achilex/MgDev | f7baf680a88d37659af32ee72b9a2046910b00d8 | [
"PHP-3.0"
] | 2 | 2017-04-19T01:38:30.000Z | 2020-07-31T03:05:32.000Z | Common/MdfParser/IOVectorLayerDefinition.cpp | achilex/MgDev | f7baf680a88d37659af32ee72b9a2046910b00d8 | [
"PHP-3.0"
] | null | null | null | Common/MdfParser/IOVectorLayerDefinition.cpp | achilex/MgDev | f7baf680a88d37659af32ee72b9a2046910b00d8 | [
"PHP-3.0"
] | 1 | 2021-12-29T10:46:12.000Z | 2021-12-29T10:46:12.000Z | //
// Copyright (C) 2004-2011 by Autodesk, Inc.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of version 2.1 of the GNU Lesser
// General Public License 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 library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
#include "stdafx.h"
#include "IOVectorLayerDefinition.h"
#include "IONameStringPair.h"
#include "IOVectorScaleRange.h"
#include "IOWatermarkInstance.h"
#include "IOURLData.h"
#include "IOUnknown.h"
using namespace XERCES_CPP_NAMESPACE;
using namespace MDFMODEL_NAMESPACE;
using namespace MDFPARSER_NAMESPACE;
CREATE_ELEMENT_MAP;
ELEM_MAP_ENTRY(1, VectorLayerDefinition);
ELEM_MAP_ENTRY(2, ResourceId);
ELEM_MAP_ENTRY(3, Opacity);
ELEM_MAP_ENTRY(4, FeatureName);
ELEM_MAP_ENTRY(5, FeatureNameType);
ELEM_MAP_ENTRY(6, Filter);
ELEM_MAP_ENTRY(7, PropertyMapping);
ELEM_MAP_ENTRY(8, Geometry);
ELEM_MAP_ENTRY(9, Url);
ELEM_MAP_ENTRY(10, ToolTip);
ELEM_MAP_ENTRY(11, VectorScaleRange);
ELEM_MAP_ENTRY(12, ExtendedData1);
ELEM_MAP_ENTRY(13, Watermarks);
ELEM_MAP_ENTRY(14, Watermark);
ELEM_MAP_ENTRY(15, UrlData);
IOVectorLayerDefinition::IOVectorLayerDefinition(Version& version) : SAX2ElementHandler(version)
{
this->m_layer = NULL;
}
IOVectorLayerDefinition::IOVectorLayerDefinition(VectorLayerDefinition* layer, Version& version) : SAX2ElementHandler(version)
{
this->m_layer = layer;
}
IOVectorLayerDefinition::~IOVectorLayerDefinition()
{
}
void IOVectorLayerDefinition::StartElement(const wchar_t* name, HandlerStack* handlerStack)
{
this->m_currElemName = name;
this->m_currElemId = _ElementIdFromName(name);
switch (this->m_currElemId)
{
case eVectorLayerDefinition:
this->m_startElemName = name;
break;
case eWatermark:
{
Version wdVersion;
if (!IOVectorLayerDefinition::GetWatermarkDefinitionVersion(&this->m_version, wdVersion))
return;
WatermarkInstance* watermark = new WatermarkInstance(L"", L"");
this->m_layer->GetWatermarks()->Adopt(watermark);
IOWatermarkInstance* IO = new IOWatermarkInstance(watermark, wdVersion);
handlerStack->push(IO);
IO->StartElement(name, handlerStack);
}
break;
case ePropertyMapping:
{
IONameStringPair* IO = new IONameStringPair(this->m_layer, this->m_version);
handlerStack->push(IO);
IO->StartElement(name, handlerStack);
}
break;
case eUrlData:
{
IOURLData* IO = new IOURLData(this->m_layer, this->m_version);
handlerStack->push(IO);
IO->StartElement(name, handlerStack);
}
break;
case eVectorScaleRange:
{
IOVectorScaleRange* IO = new IOVectorScaleRange(this->m_layer, this->m_version);
handlerStack->push(IO);
IO->StartElement(name, handlerStack);
}
break;
case eExtendedData1:
this->m_procExtData = true;
break;
case eUnknown:
ParseUnknownXml(name, handlerStack);
break;
}
}
void IOVectorLayerDefinition::ElementChars(const wchar_t* ch)
{
switch (this->m_currElemId)
{
case eResourceId:
this->m_layer->SetResourceID(ch);
break;
case eOpacity:
this->m_layer->SetOpacity(wstrToDouble(ch));
break;
case eFeatureName:
this->m_layer->SetFeatureName(ch);
break;
case eFeatureNameType:
if (::wcscmp(ch, L"FeatureClass") == 0) // NOXLATE
this->m_layer->SetFeatureNameType(VectorLayerDefinition::FeatureClass);
else if (::wcscmp(ch, L"NamedExtension") == 0) // NOXLATE
this->m_layer->SetFeatureNameType(VectorLayerDefinition::NamedExtension);
break;
case eFilter:
this->m_layer->SetFilter(ch);
break;
case eGeometry:
this->m_layer->SetGeometry(ch);
break;
case eUrl:
// Handle layer definition <= 2.3.0
if (m_version <= Version(2, 3, 0))
{
URLData* urlData = this->m_layer->GetUrlData();
if (!urlData)
{
urlData = new URLData();
this->m_layer->AdoptUrlData(urlData);
}
urlData->SetUrlContent(ch);
}
break;
case eToolTip:
this->m_layer->SetToolTip(ch);
break;
}
}
void IOVectorLayerDefinition::EndElement(const wchar_t* name, HandlerStack* handlerStack)
{
if (this->m_startElemName == name)
{
this->m_layer->SetUnknownXml(this->m_unknownXml);
this->m_layer = NULL;
this->m_startElemName = L"";
handlerStack->pop();
delete this;
}
else if (eExtendedData1 == _ElementIdFromName(name))
{
this->m_procExtData = false;
}
}
// Determine which WatermarkDefinition schema version to use based
// on the supplied LayerDefinition version:
// * LDF version == 2.4.0 => WD version 2.4.0
// * LDF version <= 2.3.0 => WD version 2.3.0
bool IOVectorLayerDefinition::GetWatermarkDefinitionVersion(Version* ldfVersion, Version& wdVersion)
{
if (!ldfVersion || *ldfVersion >= Version(2, 4, 0))
wdVersion = Version(2, 4, 0);
else if (*ldfVersion <= Version(2, 3, 0))
wdVersion = Version(2, 3, 0);
return true;
}
void IOVectorLayerDefinition::Write(MdfStream& fd, VectorLayerDefinition* vectorLayer, Version* version, MgTab& tab)
{
// verify the LDF version
MdfString strVersion;
if (version)
{
if (*version == Version(0, 9, 0))
{
// LDF in MapGuide 2006
strVersion = L"1.0.0";
}
else if ((*version >= Version(1, 0, 0)) && (*version <= Version(2, 4, 0)))
{
// LDF in MapGuide 2007 - current
strVersion = version->ToString();
}
else
{
// unsupported LDF version
// TODO - need a way to return error information
_ASSERT(false);
return;
}
}
else
{
// use the current highest version
strVersion = L"2.4.0";
}
fd << tab.tab() << "<LayerDefinition xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"LayerDefinition-" << EncodeString(strVersion) << ".xsd\" version=\"" << EncodeString(strVersion) << "\">" << std::endl; // NOXLATE
tab.inctab();
fd << tab.tab() << startStr(sVectorLayerDefinition) << std::endl;
tab.inctab();
MdfStringStream fdExtData;
// Property: ResourceId
fd << tab.tab() << startStr(sResourceId);
fd << EncodeString(vectorLayer->GetResourceID());
fd << endStr(sResourceId) << std::endl;
// Property: Opacity (optional)
if (vectorLayer->GetOpacity() != 1.0)
{
fd << tab.tab() << startStr(sOpacity);
fd << DoubleToStr(vectorLayer->GetOpacity());
fd << endStr(sOpacity) << std::endl;
}
// Property: Watermarks (optional)
int watermarkCount = vectorLayer->GetWatermarks()->GetCount();
if (watermarkCount != 0)
{
if (!version || (*version >= Version(2, 3, 0)))
{
// only write Watermarks if the LDF version is 2.3.0 or greater
fd << tab.tab() << startStr(sWatermarks) << std::endl;
tab.inctab();
for (int i=0; i<watermarkCount; ++i)
IOWatermarkInstance::Write(fd, vectorLayer->GetWatermarks()->GetAt(i), version, tab);
tab.dectab();
fd << tab.tab() << endStr(sWatermarks) << std::endl;
}
else if (*version >= Version(1, 0, 0))
{
// save Watermarks as extended data for LDF versions 1.0.0 - 1.3.0
tab.inctab();
fdExtData << tab.tab() << startStr(sWatermarks) << std::endl;
tab.inctab();
for (int i=0; i<watermarkCount; ++i)
IOWatermarkInstance::Write(fdExtData, vectorLayer->GetWatermarks()->GetAt(i), version, tab);
tab.dectab();
fdExtData << tab.tab() << endStr(sWatermarks) << std::endl;
tab.dectab();
}
}
// Property: FeatureName
fd << tab.tab() << startStr(sFeatureName);
fd << EncodeString(vectorLayer->GetFeatureName());
fd << endStr(sFeatureName) << std::endl;
// Property: FeatureNameType
fd << tab.tab() << startStr(sFeatureNameType);
if (vectorLayer->GetFeatureNameType() == VectorLayerDefinition::FeatureClass)
fd << "FeatureClass"; // NOXLATE
else
fd << "NamedExtension"; // NOXLATE
fd << endStr(sFeatureNameType) << std::endl;
// Property: Filter
if (!vectorLayer->GetFilter().empty())
{
fd << tab.tab() << startStr(sFilter);
fd << EncodeString(vectorLayer->GetFilter());
fd << endStr(sFilter) << std::endl;
}
// Property: PropertyMappings
for (int i=0; i<vectorLayer->GetPropertyMappings()->GetCount(); ++i)
IONameStringPair::Write(fd, sPropertyMapping, vectorLayer->GetPropertyMappings()->GetAt(i), version, tab);
// Property: Geometry
fd << tab.tab() << startStr(sGeometry);
fd << EncodeString(vectorLayer->GetGeometry());
fd << endStr(sGeometry) << std::endl;
// Property: Url / UrlData
URLData* urlData = vectorLayer->GetUrlData();
if (urlData)
{
if (!version || (*version >= Version(2, 4, 0)))
{
// write new version 2.4.0 property
IOURLData::Write(fd, urlData, version, tab);
}
else
{
// save original url property for LDF versions <= 2.3.0
if (!urlData->GetUrlContent().empty())
{
fd << tab.tab() << startStr(sUrl);
fd << EncodeString(urlData->GetUrlContent());
fd << endStr(sUrl) << std::endl;
}
// save new property as extended data for LDF versions <= 2.3.0
tab.inctab();
IOURLData::Write(fdExtData, urlData, version, tab);
tab.dectab();
}
}
// Property: ToolTip
if (!vectorLayer->GetToolTip().empty())
{
fd << tab.tab() << startStr(sToolTip);
fd << EncodeString(vectorLayer->GetToolTip());
fd << endStr(sToolTip) << std::endl;
}
// Property: VectorScaleRange
for (int i=0; i<vectorLayer->GetScaleRanges()->GetCount(); ++i)
IOVectorScaleRange::Write(fd, vectorLayer->GetScaleRanges()->GetAt(i), version, tab);
// Write any unknown XML / extended data
IOUnknown::Write(fd, vectorLayer->GetUnknownXml(), fdExtData.str(), version, tab);
tab.dectab();
fd << tab.tab() << endStr(sVectorLayerDefinition) << std::endl;
tab.dectab();
fd << tab.tab() << "</LayerDefinition>" << std::endl; // NOXLATE
}
| 30.728261 | 259 | 0.60833 | [
"geometry"
] |
de2d1847ddd0e0fb6cb0769eed543f61ecc1dd8d | 1,062 | hpp | C++ | src/org/apache/poi/poifs/storage/BlockList.hpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | src/org/apache/poi/poifs/storage/BlockList.hpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | src/org/apache/poi/poifs/storage/BlockList.hpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | // Generated from /POI/java/org/apache/poi/poifs/storage/BlockList.java
#pragma once
#include <fwd-POI.hpp>
#include <java/lang/fwd-POI.hpp>
#include <org/apache/poi/poifs/storage/fwd-POI.hpp>
#include <java/lang/Object.hpp>
template<typename ComponentType, typename... Bases> struct SubArray;
namespace poi
{
namespace poifs
{
namespace storage
{
typedef ::SubArray< ::poi::poifs::storage::ListManagedBlock, ::java::lang::ObjectArray > ListManagedBlockArray;
} // storage
} // poifs
} // poi
struct poi::poifs::storage::BlockList
: public virtual ::java::lang::Object
{
virtual void zap(int32_t index) = 0;
virtual ListManagedBlock* remove(int32_t index) /* throws(IOException) */ = 0;
virtual ListManagedBlockArray* fetchBlocks(int32_t startBlock, int32_t headerPropertiesStartBlock) /* throws(IOException) */ = 0;
virtual void setBAT(BlockAllocationTableReader* bat) /* throws(IOException) */ = 0;
virtual int32_t blockCount() = 0;
// Generated
static ::java::lang::Class *class_();
};
| 31.235294 | 133 | 0.699623 | [
"object"
] |
de34a6c52f9718dffd20e7a6161bc866158af83e | 6,807 | hpp | C++ | include/quickcpplib/erasure_cast.hpp | BurningEnlightenment/quickcpplib | 9a3892eb10fdbe19fb335b508e0f6db0b88254d0 | [
"Apache-2.0"
] | 72 | 2017-06-27T07:14:18.000Z | 2022-03-29T08:03:18.000Z | include/quickcpplib/erasure_cast.hpp | BurningEnlightenment/quickcpplib | 9a3892eb10fdbe19fb335b508e0f6db0b88254d0 | [
"Apache-2.0"
] | 25 | 2017-08-17T13:42:10.000Z | 2022-02-07T14:03:23.000Z | include/quickcpplib/erasure_cast.hpp | BurningEnlightenment/quickcpplib | 9a3892eb10fdbe19fb335b508e0f6db0b88254d0 | [
"Apache-2.0"
] | 16 | 2017-10-08T15:31:16.000Z | 2022-03-29T08:03:21.000Z | /* Erasure cast extending bit cast.
(C) 2018 - 2019 Niall Douglas <http://www.nedproductions.biz/> (3 commits)
File Created: May 2019
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 in the accompanying file
Licence.txt or 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.
Distributed under the Boost Software License, Version 1.0.
(See accompanying file Licence.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef QUICKCPPLIB_ERASURE_CAST_HPP
#define QUICKCPPLIB_ERASURE_CAST_HPP
#include "bit_cast.hpp"
QUICKCPPLIB_NAMESPACE_BEGIN
namespace erasure_cast
{
using bit_cast::bit_cast;
namespace traits = bit_cast::traits;
namespace detail
{
using namespace bit_cast::detail;
/* A partially compliant implementation of C++20's std::bit_cast function contributed
by Jesse Towner.
erasure_cast performs a bit_cast with additional rules to handle types
of differing sizes. For integral & enum types, it may perform a narrowing
or widing conversion with static_cast if necessary, before doing the final
conversion with bit_cast. When casting to or from non-integral, non-enum
types it may insert the value into another object with extra padding bytes
to satisfy bit_cast's preconditions that both types have the same size. */
template <class To, class From> using is_erasure_castable = std::integral_constant<bool, traits::is_move_relocating<To>::value && traits::is_move_relocating<From>::value>;
template <class T, bool = std::is_enum<T>::value> struct identity_or_underlying_type
{
using type = T;
};
template <class T> struct identity_or_underlying_type<T, true>
{
using type = typename std::underlying_type<T>::type;
};
template <class OfSize, class OfSign>
using erasure_integer_type = typename std::conditional<std::is_signed<typename identity_or_underlying_type<OfSign>::type>::value, typename std::make_signed<typename identity_or_underlying_type<OfSize>::type>::type, typename std::make_unsigned<typename identity_or_underlying_type<OfSize>::type>::type>::type;
template <class ErasedType, std::size_t N> struct padded_erasure_object
{
static_assert(traits::is_move_relocating<ErasedType>::value, "ErasedType must be TriviallyCopyable or MoveRelocating");
static_assert(alignof(ErasedType) <= sizeof(ErasedType), "ErasedType must not be over-aligned");
ErasedType value;
char padding[N];
constexpr explicit padded_erasure_object(const ErasedType &v) noexcept
: value(v)
, padding{}
{
}
};
struct bit_cast_equivalence_overload
{
};
struct static_cast_dest_smaller_overload
{
};
struct static_cast_dest_larger_overload
{
};
struct union_cast_dest_smaller_overload
{
};
struct union_cast_dest_larger_overload
{
};
} // namespace detail
/*! \brief Erasure cast implementation chosen if types are move relocating or trivally copyable,
have identical size, and are bit castable. Constexpr. Forwards to `bit_cast()` directly.
*/
QUICKCPPLIB_TEMPLATE(class To, class From)
QUICKCPPLIB_TREQUIRES(QUICKCPPLIB_TPRED(detail::is_erasure_castable<To, From>::value //
&& (sizeof(To) == sizeof(From))))
constexpr inline To erasure_cast(const From &from, detail::bit_cast_equivalence_overload = {}) noexcept { return bit_cast<To>(from); }
/*! \brief Erasure cast implementation chosen if types are move relocating or trivally copyable,
are statically castable, and destination type is smaller than source type. Constexpr.
*/
QUICKCPPLIB_TEMPLATE(class To, class From)
QUICKCPPLIB_TREQUIRES(QUICKCPPLIB_TPRED(detail::is_erasure_castable<To, From>::value //
&&detail::is_static_castable<To, From>::value //
&& (sizeof(To) < sizeof(From))))
constexpr inline To erasure_cast(const From &from, detail::static_cast_dest_smaller_overload = {}) noexcept { return static_cast<To>(bit_cast<detail::erasure_integer_type<From, To>>(from)); }
/*! \brief Erasure cast implementation chosen if types are move relocating or trivally copyable,
are statically castable, and destination type is larger than source type. Constexpr.
*/
QUICKCPPLIB_TEMPLATE(class To, class From)
QUICKCPPLIB_TREQUIRES(QUICKCPPLIB_TPRED(detail::is_erasure_castable<To, From>::value //
&&detail::is_static_castable<To, From>::value //
&& (sizeof(To) > sizeof(From))))
constexpr inline To erasure_cast(const From &from, detail::static_cast_dest_larger_overload = {}) noexcept { return bit_cast<To>(static_cast<detail::erasure_integer_type<To, From>>(from)); }
/*! \brief Erasure cast implementation chosen if types are move relocating or trivally copyable,
are union castable, and destination type is smaller than source type. May be constexpr if
underlying bit cast is constexpr.
*/
QUICKCPPLIB_TEMPLATE(class To, class From)
QUICKCPPLIB_TREQUIRES(QUICKCPPLIB_TPRED(detail::is_erasure_castable<To, From>::value //
&& !detail::is_static_castable<To, From>::value //
&& (sizeof(To) < sizeof(From))))
constexpr inline To erasure_cast(const From &from, detail::union_cast_dest_smaller_overload = {}) noexcept { return bit_cast<detail::padded_erasure_object<To, sizeof(From) - sizeof(To)>>(from).value; }
/*! \brief Erasure cast implementation chosen if types are move relocating or trivally copyable,
are union castable, and destination type is larger than source type. May be constexpr if
underlying bit cast is constexpr.
*/
QUICKCPPLIB_TEMPLATE(class To, class From)
QUICKCPPLIB_TREQUIRES(QUICKCPPLIB_TPRED(detail::is_erasure_castable<To, From>::value //
&& !detail::is_static_castable<To, From>::value //
&& (sizeof(To) > sizeof(From))))
constexpr inline To erasure_cast(const From &from, detail::union_cast_dest_larger_overload = {}) noexcept { return bit_cast<To>(detail::padded_erasure_object<From, sizeof(To) - sizeof(From)>{from}); }
} // namespace erasure_cast
QUICKCPPLIB_NAMESPACE_END
#endif
| 47.93662 | 312 | 0.707948 | [
"object"
] |
de3bf90fada37c55f966d75866369acbd887ef71 | 8,248 | cpp | C++ | iwiwi/trace_binarize.cpp | cmk/icfpc2018 | 2868cdd290879efa263a305171a36c9fac54c733 | [
"MIT"
] | 12 | 2018-07-23T16:34:49.000Z | 2019-05-31T04:31:00.000Z | iwiwi/trace_binarize.cpp | cmk/icfpc2018 | 2868cdd290879efa263a305171a36c9fac54c733 | [
"MIT"
] | 6 | 2018-08-02T17:25:08.000Z | 2019-07-01T06:28:20.000Z | iwiwi/trace_binarize.cpp | cmk/icfpc2018 | 2868cdd290879efa263a305171a36c9fac54c733 | [
"MIT"
] | 1 | 2018-10-02T04:51:09.000Z | 2018-10-02T04:51:09.000Z | #include <iostream>
#include <sstream>
#include <vector>
#include <memory>
#include <fstream>
#include <cassert>
using namespace std;
// TODO: user-friendly error messages
#define CHECK(expr) \
if (expr) { \
} else { \
fprintf(stderr, "CHECK Failed (%s:%d): %s\n", \
__FILE__, __LINE__, #expr); \
exit(EXIT_FAILURE); \
}
#define CHECK_PERROR(expr) \
if (expr) { \
} else { \
fprintf(stderr, "CHECK Failed (%s:%d): %s: ", \
__FILE__, __LINE__, #expr); \
perror(nullptr); \
exit(EXIT_FAILURE); \
}
template<typename T>
void WriteBinary(std::ostream &os, const T &t) {
CHECK_PERROR(os.write((char*)&t, sizeof(T)));
}
struct Direction {
char dir;
static Direction Parse(const string &token) {
CHECK(token.length() == 1);
char dir = tolower(token[0]);
CHECK(dir == 'x' || dir == 'y' || dir == 'z');
return Direction{ dir };
}
uint8_t ToBinary() {
switch (dir) {
case 'x': return 0b01;
case 'y': return 0b10;
case 'z': return 0b11;
}
assert(false);
}
};
struct NearCoordinates {
int x, y, z;
static NearCoordinates Parse(const vector<string> &tokens, size_t token_offset) {
NearCoordinates a;
a.x = stoi(tokens[token_offset + 0]);
a.y = stoi(tokens[token_offset + 1]);
a.z = stoi(tokens[token_offset + 2]);
CHECK(abs(a.x) + abs(a.y) + abs(a.z) <= 2);
CHECK(max(max(abs(a.x), abs(a.y)), abs(a.z)) == 1);
return a;
}
uint8_t ToBinary() {
return (x + 1) * 9 + (y + 1) * 3 + (z + 1);
}
};
struct FarCoordinates {
int x, y, z;
static FarCoordinates Parse(const vector<string> &tokens, size_t token_offset) {
FarCoordinates a;
a.x = stoi(tokens[token_offset + 0]);
a.y = stoi(tokens[token_offset + 1]);
a.z = stoi(tokens[token_offset + 2]);
CHECK(abs(a.x) + abs(a.y) + abs(a.z) >= 1);
CHECK(max(max(abs(a.x), abs(a.y)), abs(a.z)) <= 30);
return a;
}
uint8_t ToBinary() {
return (x + 1) * 9 + (y + 1) * 3 + (z + 1);
}
};
//
// Base operation classes
//
struct Operation {
virtual void Emit(ostream &os) = 0;
virtual ~Operation() {}
};
template<class Derived>
struct NullaryOperation : public Operation {
static Derived Parse(const vector<string> &tokens) {
CHECK(tokens.size() == 1);
return Derived();
}
virtual uint8_t GetSignature() = 0;
virtual void Emit(ostream &os) {
WriteBinary<uint8_t>(os, GetSignature());
}
};
template<class Derived>
struct NCOnlyOperation : public Operation {
NearCoordinates nc;
static Derived Parse(const vector<string> &tokens) {
CHECK(tokens.size() == 4);
Derived a;
a.nc = NearCoordinates::Parse(tokens, 1);
return a;
}
virtual uint8_t GetSignature() = 0;
virtual void Emit(ostream &os) {
WriteBinary<uint8_t>(os, (nc.ToBinary() << 3) | GetSignature());
}
};
template<class Derived>
struct NCFCOperation : public Operation {
NearCoordinates nc;
FarCoordinates fc;
static Derived Parse(const vector<string> &tokens) {
CHECK(tokens.size() == 7);
Derived a;
a.nc = NearCoordinates::Parse(tokens, 1);
a.fc = FarCoordinates::Parse(tokens, 4);
return a;
}
virtual uint8_t GetSignature() = 0;
virtual void Emit(ostream &os) {
WriteBinary<uint8_t>(os, (nc.ToBinary() << 3) | GetSignature());
WriteBinary<uint8_t>(os, fc.x + 30);
WriteBinary<uint8_t>(os, fc.y + 30);
WriteBinary<uint8_t>(os, fc.z + 30);
}
};
//
// Concrete operation classes
//
struct Halt : public NullaryOperation<Halt> {
virtual uint8_t GetSignature() {
return 0b11111111;
}
};
struct Wait : public NullaryOperation<Wait> {
virtual uint8_t GetSignature() {
return 0b11111110;
}
};
struct Flip : public NullaryOperation<Flip> {
virtual uint8_t GetSignature() {
return 0b11111101;
}
};
struct SMove : public Operation {
Direction dir;
int dis;
static SMove Parse(const vector<string> &tokens) {
CHECK(tokens.size() == 3);
SMove a;
a.dir = Direction::Parse(tokens[1]);
a.dis = stoi(tokens[2]);
CHECK(abs(a.dis) <= 15);
return a;
}
virtual void Emit(ostream &os) {
WriteBinary<uint8_t>(os, (dir.ToBinary() << 4) | 0b0100);
WriteBinary<uint8_t>(os, dis + 15);
}
};
struct LMove : public Operation {
Direction dir1, dir2;
int dis1, dis2;
static LMove Parse(const vector<string> &tokens) {
CHECK(tokens.size() == 5);
LMove a;
a.dir1 = Direction::Parse(tokens[1]);
a.dis1 = stoi(tokens[2]);
CHECK(abs(a.dis1) <= 5);
a.dir2 = Direction::Parse(tokens[3]);
a.dis2 = stoi(tokens[4]);
CHECK(abs(a.dis2) <= 5);
return a;
}
virtual void Emit(ostream &os) {
WriteBinary<uint8_t>(os, (dir2.ToBinary() << 6) | (dir1.ToBinary() << 4) | 0b1100);
WriteBinary<uint8_t>(os, ((dis2 + 5) << 4) | (dis1 + 5));
}
};
struct FusionP : public NCOnlyOperation<FusionP> {
virtual uint8_t GetSignature() {
return 0b111;
}
};
struct FusionS : public NCOnlyOperation<FusionS> {
virtual uint8_t GetSignature() {
return 0b110;
}
};
struct Fission : Operation {
NearCoordinates nc;
int m;
static Fission Parse(const vector<string> &tokens) {
CHECK(tokens.size() == 5);
Fission a;
a.nc = NearCoordinates::Parse(tokens, 1);
a.m = stoi(tokens[4]);
return a;
}
virtual void Emit(ostream &os) {
WriteBinary<uint8_t>(os, (nc.ToBinary() << 3) | 0b101);
WriteBinary<uint8_t>(os, m);
}
};
struct Fill : public NCOnlyOperation<Fill> {
virtual uint8_t GetSignature() {
return 0b011;
}
};
struct Void : public NCOnlyOperation<Void> {
virtual uint8_t GetSignature() {
return 0b010;
}
};
struct GFill : public NCFCOperation<GFill> {
virtual uint8_t GetSignature() {
return 0b001;
}
};
struct GVoid : public NCFCOperation<GVoid> {
virtual uint8_t GetSignature() {
return 0b000;
}
};
//
// Main
//
template<class T> vector<T> Split(const string &str) {
stringstream ss(str);
vector<T> res;
T t;
while (ss >> t) res.push_back(t);
return res;
}
Operation *ParseOperation(string line, size_t lineno) {
auto pos = line.find('#');
if (pos != std::string::npos) {
line = line.substr(0, pos);
}
vector<string> tokens = Split<string>(line);
if (tokens.size() == 0) return nullptr;
string &op = tokens[0];
for (char &c: op) c = tolower(c);
if (op == "halt") {
return new Halt(Halt::Parse(tokens));
} else if (op == "wait") {
return new Wait(Wait::Parse(tokens));
} else if (op == "flip") {
return new Flip(Flip::Parse(tokens));
} else if (op == "smove") {
return new SMove(SMove::Parse(tokens));
} else if (op == "lmove") {
return new LMove(LMove::Parse(tokens));
} else if (op == "fusionp") {
return new FusionP(FusionP::Parse(tokens));
} else if (op == "fusions") {
return new FusionS(FusionS::Parse(tokens));
} else if (op == "fission") {
return new Fission(Fission::Parse(tokens));
} else if (op == "fill") {
return new Fill(Fill::Parse(tokens));
} else if (op == "void") {
return new Void(Void::Parse(tokens));
} else if (op == "gfill") {
return new GFill(GFill::Parse(tokens));
} else if (op == "gvoid") {
return new GVoid(GVoid::Parse(tokens));
} else {
cerr << "Error at Line " << lineno << ": Unknown operation: " << op << endl;
}
return nullptr;
}
void ConvertAll(istream &is, ostream &os) {
string line;
for (int lineno = 0; getline(is, line); ++lineno) {
auto op = ParseOperation(line, lineno);
if (op) {
op->Emit(os);
}
}
}
int main(int argc, char **argv) {
CHECK(argc == 2);
ofstream ofs(argv[1]);
ios::sync_with_stdio(false);
ConvertAll(cin, ofs);
}
| 23.83815 | 87 | 0.569956 | [
"vector"
] |
de3de4fa3f6923c03c7effb2da0ee65ff259b8a8 | 3,554 | hpp | C++ | cbits/detail/copy.hpp | twesterhout/tcm-swarm | e632d493a9dc0b78c2634c2ac6311abc5f99168a | [
"BSD-3-Clause"
] | null | null | null | cbits/detail/copy.hpp | twesterhout/tcm-swarm | e632d493a9dc0b78c2634c2ac6311abc5f99168a | [
"BSD-3-Clause"
] | null | null | null | cbits/detail/copy.hpp | twesterhout/tcm-swarm | e632d493a9dc0b78c2634c2ac6311abc5f99168a | [
"BSD-3-Clause"
] | null | null | null | // Copyright Tom Westerhout (c) 2018
//
// 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 Tom Westerhout nor the names of other
// 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.
#ifndef TCM_SWARM_DETAIL_COPY_HPP
#define TCM_SWARM_DETAIL_COPY_HPP
#include "../detail/config.hpp"
#include "../detail/mkl.hpp"
TCM_SWARM_BEGIN_NAMESPACE
namespace mkl {
namespace detail {
namespace {
#define TCM_SWARM_COPY_SIGNATURE_FOR(T) \
auto copy(difference_type const n, T const* const x, \
difference_type const inc_x, T* const y, \
difference_type const inc_y) noexcept->void
TCM_SWARM_FORCEINLINE
TCM_SWARM_COPY_SIGNATURE_FOR(float)
{
cblas_scopy(n, x, inc_x, y, inc_y);
}
TCM_SWARM_FORCEINLINE
TCM_SWARM_COPY_SIGNATURE_FOR(double)
{
cblas_dcopy(n, x, inc_x, y, inc_y);
}
TCM_SWARM_FORCEINLINE
TCM_SWARM_COPY_SIGNATURE_FOR(std::complex<float>)
{
cblas_ccopy(n, x, inc_x, y, inc_y);
}
TCM_SWARM_FORCEINLINE
TCM_SWARM_COPY_SIGNATURE_FOR(std::complex<double>)
{
cblas_zcopy(n, x, inc_x, y, inc_y);
}
#undef TCM_SWARM_COPY_SIGNATURE_FOR
} // namespace
} // namespace detail
struct copy_fn {
template <class T>
TCM_SWARM_FORCEINLINE auto operator()(size_type const n,
T const* const x, difference_type const inc_x, T* const y,
difference_type const inc_y) const noexcept -> void
{
return detail::copy(
static_cast<difference_type>(n), x, inc_x, y, inc_y);
}
template <class T>
TCM_SWARM_FORCEINLINE auto operator()(size_type const n,
T const* const x, T* const y) const noexcept -> void
{
return detail::copy(static_cast<difference_type>(n), x,
difference_type{1}, y, difference_type{1});
}
};
/// \brief Copies first vector into the second.
TCM_SWARM_INLINE_VARIABLE(copy_fn, copy)
} // namespace mkl
TCM_SWARM_END_NAMESPACE
#endif // TCM_SWARM_DETAIL_COPY_HPP
| 34.173077 | 78 | 0.684862 | [
"vector"
] |
de4e6ca80b5749b058329ea25ea2f0864c0d2680 | 3,139 | cpp | C++ | tree/hld.cpp | firiexp/library | 5b792b1387ed825739d4a83e6dba52ca22f114d2 | [
"CC0-1.0"
] | 1 | 2020-11-06T03:36:03.000Z | 2020-11-06T03:36:03.000Z | tree/hld.cpp | firiexp/library | 5b792b1387ed825739d4a83e6dba52ca22f114d2 | [
"CC0-1.0"
] | null | null | null | tree/hld.cpp | firiexp/library | 5b792b1387ed825739d4a83e6dba52ca22f114d2 | [
"CC0-1.0"
] | 2 | 2020-11-06T03:39:10.000Z | 2021-04-04T04:38:30.000Z |
class HeavyLightDecomposition {
void dfs_sz(int v){
for (auto &&u : G[v]) {
if(u == par[v]) continue;
par[u] = v; dep[u] = dep[v] + 1;
dfs_sz(u);
sub_size[v] += sub_size[u];
if(sub_size[u] > sub_size[G[v][0]]) swap(u, G[v][0]);
}
}
void dfs_hld(int v, int c, int &pos){
id[v] = pos++;
id_inv[id[v]]= v;
tree_id[v] = c;
for (auto &&u : G[v]) {
if(u == par[v]) continue;
head[u] = (u == G[v][0] ? head[v] : u);
dfs_hld(u, c, pos);
}
}
public:
int n;
vector<vector<int>> G;
vector<int> par, dep, sub_size, id, id_inv, tree_id, head;
explicit HeavyLightDecomposition(int n) : n(n), G(n), par(n), dep(n), sub_size(n, 1), id(n), id_inv(n), tree_id(n), head(n){}
explicit HeavyLightDecomposition(vector<vector<int>> &G) :G(G), n(G.size()), par(n), dep(n), sub_size(n, 1), id(n), id_inv(n), tree_id(n), head(n) {}
void add_edge(int u, int v){
G[u].emplace_back(v);
G[v].emplace_back(u);
}
void build(vector<int> roots = {0}){
int c = 0, pos = 0;
for (auto &&i : roots) {
dfs_sz(i);
head[i] = i;
dfs_hld(i, c++, pos);
}
}
int lca(int u, int v){
while(true){
if(id[u] > id[v]) swap(u, v);
if(head[u] == head[v]) return u;
v = par[head[v]];
}
}
int ancestor(int v, int k) {
if(dep[v] < k) return -1;
while(true) {
int u = head[v];
if(id[v] - k >= id[u]) return id_inv[id[v] - k];
k -= id[v]-id[u]+1;
v = par[u];
}
}
int distance(int u, int v){ return dep[u] + dep[v] - 2*dep[lca(u, v)]; }
template<typename F>
void add(int u, int v, const F &f, bool edge){
while (head[u] != head[v]){
if(id[u] > id[v]) swap(u, v);
f(id[head[v]], id[v]+1);
v = par[head[v]];
}
if(id[u] > id[v]) swap(u, v);
f(id[u]+edge, id[v]+1);
}
template<typename T, typename Q, typename F>
T query(int u, int v, const T &e, const Q &q, const F &f, bool edge){
T l = e, r = e;
while(head[u] != head[v]){
if(id[u] > id[v]) swap(u, v), swap(l, r);
l = f(l, q(id[head[v]], id[v]+1));
v = par[head[v]];
}
if(id[u] > id[v]) swap(u, v), swap(l, r);
return f(q(id[u]+edge, id[v]+1), f(l, r));
}
template<typename T, typename QL, typename QR, typename F>
T query_order(int u, int v, const T &e, const QL &ql, const QR &qr, const F &f, bool edge){
T l = e, r = e;
while(head[u] != head[v]){
if(id[u] > id[v]) {
l = f(l, qr(id[head[u]], id[u]+1));
u = par[head[u]];
}else {
r = f(ql(id[head[v]], id[v]+1), r);
v = par[head[v]];
}
}
T mid = (id[u] > id[v] ? qr(id[v]+edge, id[u]+1) : ql(id[u]+edge, id[v]+1));
return f(f(l, mid), r);
}
}; | 31.079208 | 153 | 0.427843 | [
"vector"
] |
de5462ceb698786d8ddf67e8b0847bb54712aed6 | 1,472 | cpp | C++ | Cplus/InvalidTransactions.cpp | JumHorn/leetcode | 1447237ae8fc3920b19f60b30c71a84b088cc200 | [
"MIT"
] | 1 | 2018-01-22T12:06:28.000Z | 2018-01-22T12:06:28.000Z | Cplus/InvalidTransactions.cpp | JumHorn/leetcode | 1447237ae8fc3920b19f60b30c71a84b088cc200 | [
"MIT"
] | null | null | null | Cplus/InvalidTransactions.cpp | JumHorn/leetcode | 1447237ae8fc3920b19f60b30c71a84b088cc200 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <sstream>
#include <string>
#include <unordered_set>
#include <vector>
using namespace std;
class Solution
{
private:
struct trans
{
string name;
int time;
int amount;
string city;
int index;
};
public:
vector<string> invalidTransactions(vector<string> &transactions)
{
vector<trans> v;
unordered_set<int> seen; //{index}
int N = transactions.size();
for (int i = 0; i < N; ++i)
{
trans s = split(transactions[i]);
s.index = i;
if (s.amount >= 1000)
seen.insert(i);
v.push_back(s);
}
sort(v.begin(), v.end(), *this);
for (int i = 0; i < N - 1; ++i)
{
for (int j = i + 1; j < N; ++j)
{
if (v[j].name != v[i].name)
break;
if (v[j].time - v[i].time > 60)
break;
if (v[j].city != v[i].city)
{
seen.insert(v[i].index);
seen.insert(v[j].index);
}
}
}
vector<string> res;
for (auto n : seen)
res.push_back(transactions[n]);
return res;
}
trans split(const string &tran)
{
stringstream ss(tran);
trans res;
char comma;
getline(ss, res.name, ',');
ss >> res.time;
ss >> comma;
ss >> res.amount;
ss >> comma;
ss >> res.city;
return res;
}
bool operator()(const trans &lhs, const trans &rhs)
{
if (lhs.name != rhs.name)
return lhs.name < rhs.name;
if (lhs.time != rhs.time)
return lhs.time < rhs.time;
if (lhs.amount != rhs.amount)
return lhs.amount < rhs.amount;
return lhs.city < rhs.city;
}
}; | 18.4 | 65 | 0.581522 | [
"vector"
] |
de576d2f611efffb1c3576dfe91672d67be9aeb7 | 5,223 | cpp | C++ | Source/src/components/MeshComponent.cpp | armandojaga/boxer-engine | 47d57989e6bf431eea6732ccee6b64083f03472b | [
"MIT"
] | 4 | 2021-11-19T03:31:02.000Z | 2021-12-09T19:33:32.000Z | Source/src/components/MeshComponent.cpp | armandojaga/boxer-engine | 47d57989e6bf431eea6732ccee6b64083f03472b | [
"MIT"
] | 3 | 2021-12-17T22:48:00.000Z | 2022-01-11T11:47:57.000Z | Source/src/components/MeshComponent.cpp | armandojaga/boxer-engine | 47d57989e6bf431eea6732ccee6b64083f03472b | [
"MIT"
] | null | null | null | #include "core/bepch.h"
#include "MeshComponent.h"
#include "modules/ModuleTexture.h"
#include "ImGuiFileDialog.h"
#include "TransformComponent.h"
#include "modules/ModuleProgram.h"
static const char* texture_types[]{"Diffuse", "Specular"};
BoxerEngine::MeshComponent::MeshComponent(Entity* entity)
: Component(Type::MESH, entity)
{
}
BoxerEngine::MeshComponent::~MeshComponent()
{
for (const auto mesh : meshes)
{
delete mesh;
}
delete model;
}
void BoxerEngine::MeshComponent::UpdateUI()
{
if (model_loaded)
{
DisplayLoadedUI();
}
else
{
DisplayNotLoadedUI();
}
}
void BoxerEngine::MeshComponent::Update()
{
}
const char* BoxerEngine::MeshComponent::GetName() const
{
return "Mesh";
}
const char* BoxerEngine::MeshComponent::GetModelPath() const
{
if (!model_loaded)
{
return nullptr;
}
return model->GetPath();
}
void BoxerEngine::MeshComponent::LoadModel(const char* path)
{
if (model)
{
delete model;
}
std::filesystem::path model_path(path);
model_path = model_path.filename().replace_extension();
model = new Model(model_path.string().c_str());
meshes.reserve(model->GetMeshesCount());
for (int i = 0; i < model->GetMeshesCount(); ++i)
{
meshes.emplace_back(new MeshData());
}
model_loaded = true;
}
void BoxerEngine::MeshComponent::LoadTexture(const char* path, int mesh_index, int type)
{
const unsigned int textureId = App->textures->Load(path);
model->SetMeshTexture(mesh_index, textureId, texture_types[type]);
meshes[mesh_index]->texture_loaded = true;
meshes[mesh_index]->texture_name = path;
meshes[mesh_index]->texture_type = type;
}
void BoxerEngine::MeshComponent::Save(YAML::Node)
{
}
void BoxerEngine::MeshComponent::Load(YAML::Node)
{
}
void BoxerEngine::MeshComponent::Draw()
{
if (!model_loaded || !enabled)
{
return;
}
App->program->SetUniform("model", GetEntity()->GetComponent<TransformComponent>()->GetGlobalMatrix());
model->Draw();
}
void BoxerEngine::MeshComponent::DisplayLoadedUI()
{
ImGui::TextWrapped("Meshes");
ImGui::Separator();
for (int i = 0; i < model->GetMeshesCount(); ++i)
{
ImGui::TextWrapped(StringUtils::Concat(ICON_MD_ARROW_FORWARD_IOS, " ", std::to_string(i), " Mesh:").c_str());
AddTextureDisplay(i);
ImGui::NewLine();
}
}
void BoxerEngine::MeshComponent::DisplayNotLoadedUI()
{
if (ImGui::Button("Browse"))
{
ImGuiFileDialog::Instance()->OpenDialog("Select Mesh", "Select Mesh", ".*", "./library/models/", 1, nullptr,
ImGuiFileDialogFlags_DontShowHiddenFiles |
ImGuiFileDialogFlags_HideColumnType |
ImGuiFileDialogFlags_DisableCreateDirectoryButton |
ImGuiFileDialogFlags_HideColumnDate);
}
if (ImGuiFileDialog::Instance()->Display("Select Mesh"))
{
if (ImGuiFileDialog::Instance()->IsOk())
{
// TODO: If filepath is not asset. Import mesh
const std::filesystem::path file_path = ImGuiFileDialog::Instance()->GetFilePathName();
LoadModel(file_path.filename().replace_extension().string().c_str());
}
ImGuiFileDialog::Instance()->Close();
}
}
void BoxerEngine::MeshComponent::AddTextureDisplay(const int mesh_index)
{
const std::string title = StringUtils::Concat("Select texture##%d", std::to_string(mesh_index));
ImGui::PushID(mesh_index);
const int index = TexturesTypesListBox();
ImGui::PopID();
ImGui::Text(ICON_MD_IMAGE_SEARCH);
ImGui::SameLine();
if (ImGui::Button(StringUtils::Concat(std::to_string(mesh_index).c_str(), " Texture").c_str()))
{
ImGuiFileDialog::Instance()->OpenDialog(title.c_str(), "Select Texture", ".*", "./library/textures/", 1, nullptr,
ImGuiFileDialogFlags_DontShowHiddenFiles |
ImGuiFileDialogFlags_DisableCreateDirectoryButton |
ImGuiFileDialogFlags_HideColumnType |
ImGuiFileDialogFlags_HideColumnDate);
}
ImGui::SameLine();
if (meshes[mesh_index]->texture_loaded && ImGui::Button(ICON_MD_HIGHLIGHT_REMOVE))
{
model->SetMeshTexture(mesh_index, 0, texture_types[0]);
meshes[mesh_index]->texture_loaded = false;
}
if (ImGuiFileDialog::Instance()->Display(title.c_str()))
{
if (ImGuiFileDialog::Instance()->IsOk())
{
const std::filesystem::path texture_path = ImGuiFileDialog::Instance()->GetFilePathName().c_str();
LoadTexture(texture_path.filename().replace_extension().string().c_str(), mesh_index, index);
}
ImGuiFileDialog::Instance()->Close();
}
}
int BoxerEngine::MeshComponent::TexturesTypesListBox()
{
static int selection;
ImGui::Combo("", &selection, texture_types, IM_ARRAYSIZE(texture_types));
return selection;
}
| 28.38587 | 121 | 0.623205 | [
"mesh",
"model"
] |
de68aae48288fadc755d29b823e0486d221f3847 | 104 | hpp | C++ | NeuralNetwork/LayerAlias.hpp | FerMod/NeuralNetwork | 639eaf1a2e0566f5ff7f04dff8ad0156b1691a13 | [
"MIT"
] | 1 | 2019-01-27T21:37:46.000Z | 2019-01-27T21:37:46.000Z | NeuralNetwork/LayerAlias.hpp | FerMod/NeuralNetwork | 639eaf1a2e0566f5ff7f04dff8ad0156b1691a13 | [
"MIT"
] | null | null | null | NeuralNetwork/LayerAlias.hpp | FerMod/NeuralNetwork | 639eaf1a2e0566f5ff7f04dff8ad0156b1691a13 | [
"MIT"
] | null | null | null | #pragma once
#include <vector>
namespace NeuralNetwork {
typedef std::vector<class Neuron> Layer;
}
| 11.555556 | 41 | 0.740385 | [
"vector"
] |
de7066efeaf39bf59334612490a46a915e33b72b | 2,912 | cpp | C++ | demos/demo03.cpp | quantombone/esvmTestCPP | 8a698ae12ec3a081a23b94f605c0f044b5e35dd5 | [
"MIT"
] | 8 | 2017-03-27T09:05:28.000Z | 2021-07-09T15:46:49.000Z | demos/demo03.cpp | bygreencn/esvmTestCPP | 8a698ae12ec3a081a23b94f605c0f044b5e35dd5 | [
"MIT"
] | null | null | null | demos/demo03.cpp | bygreencn/esvmTestCPP | 8a698ae12ec3a081a23b94f605c0f044b5e35dd5 | [
"MIT"
] | 9 | 2015-06-10T12:40:24.000Z | 2017-08-16T07:02:42.000Z | /*
* Author: Ishan Misra
* Copyright (C) 2012-13 by Ishan Misra
* This file is part of the esvmTestCPP library.
* It is released under the MIT License.
* Project Homepage: https://github.com/imisra/esvmTestCPP
*
* demo03.cpp : Using the testing pipeline for Exemplar-SVMs
*/
#include "esvm.h"
#include "esvm_utils.h"
#include <getopt.h>
#include <execinfo.h>
#include <signal.h>
#include <errno.h>
using namespace std;
void handler(int sig) {
void *array[100];
size_t size;
size = backtrace(array,100);
fprintf(stderr,"Signal %d caught\n",sig);
fprintf(stderr,"Signal Name: %s\n",strsignal(sig));
fprintf(stderr,"Error Name: %s\n",strerror(errno));
backtrace_symbols_fd(array,size,2);
exit(1);
}
int main(int argc, char *argv[])
{
const char *imageName = "../sample-data/aeroplane.jpg";
const char *descFile = "../sample-data/exemplars/exemplar-txt-files-list";
int numExemplars = 20;
//this image is loaded only for display purposes. SIMEWrapper loads its own image.
IplImage *img = cvLoadImage(imageName,CV_LOAD_IMAGE_COLOR);
//install handler for debugging
signal(SIGSEGV,handler);
signal(SIGABRT,handler);
//load the models
esvmModel *model = loadExemplars(descFile,numExemplars);
if(numExemplars != model->hogpyr->num) {
fprintf(stderr,"could not load %d exemplars. Will work with %d exemplars\n",
numExemplars,model->hogpyr->num);
numExemplars = model->hogpyr->num;
}
//get default parameters for classification
esvmParameters *params = esvmDefaultParameters();
params->detectionThreshold = -1.0;
esvmOutput *output = esvmSIMEWrapper(params,imageName,model);
printf("Image %s; Hog levels %d; Weights %d; Tasks %d; Boxes %d;"
" Levels per octave %d; Hog Time %0.4lf; "
"Conv Time %0.4lf; NMS_etc Time %0.4lf\n",
imageName,output->hogpyr->num,model->num,
params->userTasks,output->boxes->num,params->levelsPerOctave,
output->perf.hogTime,output->perf.convTime,output->perf.nmsTime);
printf("Total Boxes %d\n",output->boxes->num);
for(int j=0;j<output->boxes->num;j++) {
printf("bbox (%0.2f %0.2f %0.2f %0.2f); score %0.3f; scale %0.3f; exid %d; class %s\n",
BOX_RMIN((output->boxes),j), BOX_CMIN((output->boxes),j),
BOX_RMAX((output->boxes),j), BOX_CMAX((output->boxes),j),
BOX_SCORE((output->boxes),j), BOX_SCALE((output->boxes),j),
BOX_EXID((output->boxes),j),
model->idMap[BOX_CLASS((output->boxes),j)].c_str());
cvRectangle(img,
cvPoint(BOX_CMIN((output->boxes),j),BOX_RMIN((output->boxes),j)),
cvPoint(BOX_CMAX((output->boxes),j),BOX_RMAX((output->boxes),j)),
cvScalar(0,0,255),
3,8,0
);
}
cvNamedWindow("hog-pipeline",CV_WINDOW_AUTOSIZE);
cvShowImage("hog-pipeline",img);
cvWaitKey(0);
cvDestroyWindow("hog-pipeline");
cvSaveImage("detect-results.png",img);
cvReleaseImage(&img);
printf("Saved detections as detect-results.png\n");
return 0;
}
| 28.54902 | 89 | 0.691277 | [
"model"
] |
de725fc4c9694b1c222a9e1501ad2a7fe33b617c | 19,715 | cpp | C++ | extensions/scripting/lua-bindings/auto/CCRegisterLuaCoreAuto_03.cpp | wzhengsen/engine-x | f398b94a9a5bb9645c16d12d82d6366589db4e21 | [
"MIT"
] | null | null | null | extensions/scripting/lua-bindings/auto/CCRegisterLuaCoreAuto_03.cpp | wzhengsen/engine-x | f398b94a9a5bb9645c16d12d82d6366589db4e21 | [
"MIT"
] | null | null | null | extensions/scripting/lua-bindings/auto/CCRegisterLuaCoreAuto_03.cpp | wzhengsen/engine-x | f398b94a9a5bb9645c16d12d82d6366589db4e21 | [
"MIT"
] | null | null | null | #include "scripting/lua-bindings/auto/CCRegisterLuaCoreAuto.hpp"
#include "cocos2d.h"
#include "2d/CCProtectedNode.h"
#include "base/CCAsyncTaskPool.h"
#include "renderer/CCRenderer.h"
#include "renderer/CCPipelineDescriptor.h"
#include "renderer/backend/RenderTarget.h"
#include "navmesh/CCNavMesh.h"
#include "ui/UIWidget.h"
#include "base/TGAlib.h"
#include "network/CCConnection.h"
void RegisterLuaCoreAutoPolygonAuto(cocos2d::extension::Lua& lua){
cocos2d::extension::Lua::Id2Meta[typeid(cocos2d::AutoPolygon).name()] = sol::usertype_traits<cocos2d::AutoPolygon*>::metatable();
auto dep=lua.new_usertype<cocos2d::AutoPolygon>("deprecated.cocos2d::AutoPolygon");
sol::table mt=lua.NewClass(sol::usertype_traits<cocos2d::AutoPolygon*>::metatable());
lua["cc"]["AutoPolygon"]=mt;
mt["Trace"]=sol::overload([](cocos2d::AutoPolygon* obj,const cocos2d::Rect& arg0,float arg1){return obj->trace(arg0,arg1);},[](cocos2d::AutoPolygon* obj,const cocos2d::Rect& arg0){return obj->trace(arg0);});
mt["Reduce"]=sol::overload([](cocos2d::AutoPolygon* obj,const std::vector<cocos2d::Vec2, std::allocator<cocos2d::Vec2> >& arg0,const cocos2d::Rect& arg1,float arg2){return obj->reduce(arg0,arg1,arg2);},[](cocos2d::AutoPolygon* obj,const std::vector<cocos2d::Vec2, std::allocator<cocos2d::Vec2> >& arg0,const cocos2d::Rect& arg1){return obj->reduce(arg0,arg1);});
mt["Expand"]=static_cast<std::vector<cocos2d::Vec2, std::allocator<cocos2d::Vec2> >(cocos2d::AutoPolygon::*)(const std::vector<cocos2d::Vec2, std::allocator<cocos2d::Vec2> >&,const cocos2d::Rect&,float)>(&cocos2d::AutoPolygon::expand);
mt["Triangulate"]=static_cast<cocos2d::TrianglesCommand::Triangles(cocos2d::AutoPolygon::*)(const std::vector<cocos2d::Vec2, std::allocator<cocos2d::Vec2> >&)>(&cocos2d::AutoPolygon::triangulate);
mt["CalculateUV"]=static_cast<void(cocos2d::AutoPolygon::*)(const cocos2d::Rect&,cocos2d::V3F_C4B_T2F*,ssize_t)>(&cocos2d::AutoPolygon::calculateUV);
mt["GenerateTriangles"]=sol::overload([](cocos2d::AutoPolygon* obj,const cocos2d::Rect& arg0,float arg1,float arg2){return obj->generateTriangles(arg0,arg1,arg2);},[](cocos2d::AutoPolygon* obj,const cocos2d::Rect& arg0,float arg1){return obj->generateTriangles(arg0,arg1);},[](cocos2d::AutoPolygon* obj,const cocos2d::Rect& arg0){return obj->generateTriangles(arg0);},[](cocos2d::AutoPolygon* obj){return obj->generateTriangles();});
mt["static"]["GeneratePolygon"]=sol::overload([](const std::string& arg0,const cocos2d::Rect& arg1,float arg2,float arg3){return cocos2d::AutoPolygon::generatePolygon(arg0,arg1,arg2,arg3);},[](const std::string& arg0,const cocos2d::Rect& arg1,float arg2){return cocos2d::AutoPolygon::generatePolygon(arg0,arg1,arg2);},[](const std::string& arg0,const cocos2d::Rect& arg1){return cocos2d::AutoPolygon::generatePolygon(arg0,arg1);},[](const std::string& arg0){return cocos2d::AutoPolygon::generatePolygon(arg0);});
}
void RegisterLuaCoreSpriteFrameAuto(cocos2d::extension::Lua& lua){
cocos2d::extension::Lua::Id2Meta[typeid(cocos2d::SpriteFrame).name()] = sol::usertype_traits<cocos2d::SpriteFrame*>::metatable();
auto dep=lua.new_usertype<cocos2d::SpriteFrame>("deprecated.cocos2d::SpriteFrame");
dep[sol::base_classes]=sol::bases<cocos2d::Ref,cocos2d::extension::LuaObject,cocos2d::Clonable>();
sol::table mt=lua.NewClass(sol::usertype_traits<cocos2d::SpriteFrame*>::metatable(),sol::usertype_traits<cocos2d::Ref*>::metatable(),sol::usertype_traits<cocos2d::Clonable*>::metatable());
lua["cc"]["SpriteFrame"]=mt;
mt["__new__"]=sol::overload(static_cast<cocos2d::SpriteFrame*(*)(const std::string&,const cocos2d::Rect&,bool,const cocos2d::Vec2&,const cocos2d::Size&)>(&cocos2d::SpriteFrame::create),static_cast<cocos2d::SpriteFrame*(*)(const std::string&,const cocos2d::Rect&)>(&cocos2d::SpriteFrame::create));
mt["static"]["CreateWithTexture"]=sol::overload(static_cast<cocos2d::SpriteFrame*(*)(cocos2d::Texture2D*,const cocos2d::Rect&,bool,const cocos2d::Vec2&,const cocos2d::Size&)>(&cocos2d::SpriteFrame::createWithTexture),static_cast<cocos2d::SpriteFrame*(*)(cocos2d::Texture2D*,const cocos2d::Rect&)>(&cocos2d::SpriteFrame::createWithTexture));
mt["GetRectInPixels"]=static_cast<const cocos2d::Rect&(cocos2d::SpriteFrame::*)()const>(&cocos2d::SpriteFrame::getRectInPixels);
mt["get"]["RectInPixels"]=mt["GetRectInPixels"];
mt["SetRectInPixels"]=static_cast<void(cocos2d::SpriteFrame::*)(const cocos2d::Rect&)>(&cocos2d::SpriteFrame::setRectInPixels);
mt["set"]["RectInPixels"]=mt["SetRectInPixels"];
mt["IsRotated"]=static_cast<bool(cocos2d::SpriteFrame::*)()const>(&cocos2d::SpriteFrame::isRotated);
mt["get"]["Rotated"]=mt["IsRotated"];
mt["SetRotated"]=static_cast<void(cocos2d::SpriteFrame::*)(bool)>(&cocos2d::SpriteFrame::setRotated);
mt["set"]["Rotated"]=mt["SetRotated"];
mt["GetRect"]=static_cast<const cocos2d::Rect&(cocos2d::SpriteFrame::*)()const>(&cocos2d::SpriteFrame::getRect);
mt["get"]["Rect"]=mt["GetRect"];
mt["SetRect"]=static_cast<void(cocos2d::SpriteFrame::*)(const cocos2d::Rect&)>(&cocos2d::SpriteFrame::setRect);
mt["set"]["Rect"]=mt["SetRect"];
mt["GetCenterRect"]=static_cast<const cocos2d::Rect&(cocos2d::SpriteFrame::*)()const>(&cocos2d::SpriteFrame::getCenterRect);
mt["get"]["CenterRect"]=mt["GetCenterRect"];
mt["SetCenterRectInPixels"]=static_cast<void(cocos2d::SpriteFrame::*)(const cocos2d::Rect&)>(&cocos2d::SpriteFrame::setCenterRectInPixels);
mt["set"]["CenterRectInPixels"]=mt["SetCenterRectInPixels"];
mt["HasCenterRect"]=static_cast<bool(cocos2d::SpriteFrame::*)()const>(&cocos2d::SpriteFrame::hasCenterRect);
mt["GetOffsetInPixels"]=static_cast<const cocos2d::Vec2&(cocos2d::SpriteFrame::*)()const>(&cocos2d::SpriteFrame::getOffsetInPixels);
mt["get"]["OffsetInPixels"]=mt["GetOffsetInPixels"];
mt["SetOffsetInPixels"]=static_cast<void(cocos2d::SpriteFrame::*)(const cocos2d::Vec2&)>(&cocos2d::SpriteFrame::setOffsetInPixels);
mt["set"]["OffsetInPixels"]=mt["SetOffsetInPixels"];
mt["GetOriginalSizeInPixels"]=static_cast<const cocos2d::Size&(cocos2d::SpriteFrame::*)()const>(&cocos2d::SpriteFrame::getOriginalSizeInPixels);
mt["get"]["OriginalSizeInPixels"]=mt["GetOriginalSizeInPixels"];
mt["SetOriginalSizeInPixels"]=static_cast<void(cocos2d::SpriteFrame::*)(const cocos2d::Size&)>(&cocos2d::SpriteFrame::setOriginalSizeInPixels);
mt["set"]["OriginalSizeInPixels"]=mt["SetOriginalSizeInPixels"];
mt["GetOriginalSize"]=static_cast<const cocos2d::Size&(cocos2d::SpriteFrame::*)()const>(&cocos2d::SpriteFrame::getOriginalSize);
mt["get"]["OriginalSize"]=mt["GetOriginalSize"];
mt["SetOriginalSize"]=static_cast<void(cocos2d::SpriteFrame::*)(const cocos2d::Size&)>(&cocos2d::SpriteFrame::setOriginalSize);
mt["set"]["OriginalSize"]=mt["SetOriginalSize"];
mt["GetTexture"]=static_cast<cocos2d::Texture2D*(cocos2d::SpriteFrame::*)()>(&cocos2d::SpriteFrame::getTexture);
mt["get"]["Texture"]=mt["GetTexture"];
mt["SetTexture"]=static_cast<void(cocos2d::SpriteFrame::*)(cocos2d::Texture2D*)>(&cocos2d::SpriteFrame::setTexture);
mt["set"]["Texture"]=mt["SetTexture"];
mt["GetOffset"]=static_cast<const cocos2d::Vec2&(cocos2d::SpriteFrame::*)()const>(&cocos2d::SpriteFrame::getOffset);
mt["get"]["Offset"]=mt["GetOffset"];
mt["SetOffset"]=static_cast<void(cocos2d::SpriteFrame::*)(const cocos2d::Vec2&)>(&cocos2d::SpriteFrame::setOffset);
mt["set"]["Offset"]=mt["SetOffset"];
mt["GetAnchorPoint"]=static_cast<const cocos2d::Vec2&(cocos2d::SpriteFrame::*)()const>(&cocos2d::SpriteFrame::getAnchorPoint);
mt["get"]["AnchorPoint"]=mt["GetAnchorPoint"];
mt["SetAnchorPoint"]=static_cast<void(cocos2d::SpriteFrame::*)(const cocos2d::Vec2&)>(&cocos2d::SpriteFrame::setAnchorPoint);
mt["set"]["AnchorPoint"]=mt["SetAnchorPoint"];
mt["HasAnchorPoint"]=static_cast<bool(cocos2d::SpriteFrame::*)()const>(&cocos2d::SpriteFrame::hasAnchorPoint);
mt["SetPolygonInfo"]=static_cast<void(cocos2d::SpriteFrame::*)(const cocos2d::PolygonInfo&)>(&cocos2d::SpriteFrame::setPolygonInfo);
mt["set"]["PolygonInfo"]=mt["SetPolygonInfo"];
mt["GetPolygonInfo"]=static_cast<const cocos2d::PolygonInfo&(cocos2d::SpriteFrame::*)()const>(&cocos2d::SpriteFrame::getPolygonInfo);
mt["get"]["PolygonInfo"]=mt["GetPolygonInfo"];
mt["HasPolygonInfo"]=static_cast<bool(cocos2d::SpriteFrame::*)()const>(&cocos2d::SpriteFrame::hasPolygonInfo);
}
void RegisterLuaCoreAnimationFrameAuto(cocos2d::extension::Lua& lua){
cocos2d::extension::Lua::Id2Meta[typeid(cocos2d::AnimationFrame).name()] = sol::usertype_traits<cocos2d::AnimationFrame*>::metatable();
auto dep=lua.new_usertype<cocos2d::AnimationFrame>("deprecated.cocos2d::AnimationFrame");
dep[sol::base_classes]=sol::bases<cocos2d::Ref,cocos2d::extension::LuaObject,cocos2d::Clonable>();
sol::table mt=lua.NewClass(sol::usertype_traits<cocos2d::AnimationFrame*>::metatable(),sol::usertype_traits<cocos2d::Ref*>::metatable(),sol::usertype_traits<cocos2d::Clonable*>::metatable());
lua["cc"]["AnimationFrame"]=mt;
mt["__new__"]=static_cast<cocos2d::AnimationFrame*(*)(cocos2d::SpriteFrame*,float,const cocos2d::ValueMap&)>(&cocos2d::AnimationFrame::create);
mt["GetSpriteFrame"]=static_cast<cocos2d::SpriteFrame*(cocos2d::AnimationFrame::*)()const>(&cocos2d::AnimationFrame::getSpriteFrame);
mt["get"]["SpriteFrame"]=mt["GetSpriteFrame"];
mt["SetSpriteFrame"]=static_cast<void(cocos2d::AnimationFrame::*)(cocos2d::SpriteFrame*)>(&cocos2d::AnimationFrame::setSpriteFrame);
mt["set"]["SpriteFrame"]=mt["SetSpriteFrame"];
mt["GetDelayUnits"]=static_cast<float(cocos2d::AnimationFrame::*)()const>(&cocos2d::AnimationFrame::getDelayUnits);
mt["get"]["DelayUnits"]=mt["GetDelayUnits"];
mt["SetDelayUnits"]=static_cast<void(cocos2d::AnimationFrame::*)(float)>(&cocos2d::AnimationFrame::setDelayUnits);
mt["set"]["DelayUnits"]=mt["SetDelayUnits"];
mt["GetUserInfo"]=static_cast<const cocos2d::ValueMap&(cocos2d::AnimationFrame::*)()const>(&cocos2d::AnimationFrame::getUserInfo);
mt["get"]["UserInfo"]=mt["GetUserInfo"];
mt["SetUserInfo"]=static_cast<void(cocos2d::AnimationFrame::*)(const cocos2d::ValueMap&)>(&cocos2d::AnimationFrame::setUserInfo);
mt["set"]["UserInfo"]=mt["SetUserInfo"];
}
void RegisterLuaCoreAnimationAuto(cocos2d::extension::Lua& lua){
cocos2d::extension::Lua::Id2Meta[typeid(cocos2d::Animation).name()] = sol::usertype_traits<cocos2d::Animation*>::metatable();
auto dep=lua.new_usertype<cocos2d::Animation>("deprecated.cocos2d::Animation");
dep[sol::base_classes]=sol::bases<cocos2d::Ref,cocos2d::extension::LuaObject,cocos2d::Clonable>();
sol::table mt=lua.NewClass(sol::usertype_traits<cocos2d::Animation*>::metatable(),sol::usertype_traits<cocos2d::Ref*>::metatable(),sol::usertype_traits<cocos2d::Clonable*>::metatable());
lua["cc"]["Animation"]=mt;
mt["__new__"]=sol::overload([](const cocos2d::Vector<cocos2d::AnimationFrame *>& arg0,float arg1,unsigned int arg2){return cocos2d::Animation::create(arg0,arg1,arg2);},[](const cocos2d::Vector<cocos2d::AnimationFrame *>& arg0,float arg1){return cocos2d::Animation::create(arg0,arg1);},static_cast<cocos2d::Animation*(*)()>(&cocos2d::Animation::create));
mt["static"]["CreateWithSpriteFrames"]=sol::overload([](const cocos2d::Vector<cocos2d::SpriteFrame *>& arg0,float arg1,unsigned int arg2){return cocos2d::Animation::createWithSpriteFrames(arg0,arg1,arg2);},[](const cocos2d::Vector<cocos2d::SpriteFrame *>& arg0,float arg1){return cocos2d::Animation::createWithSpriteFrames(arg0,arg1);},[](const cocos2d::Vector<cocos2d::SpriteFrame *>& arg0){return cocos2d::Animation::createWithSpriteFrames(arg0);});
mt["AddSpriteFrame"]=static_cast<void(cocos2d::Animation::*)(cocos2d::SpriteFrame*)>(&cocos2d::Animation::addSpriteFrame);
mt["AddSpriteFrameWithFile"]=static_cast<void(cocos2d::Animation::*)(const std::string&)>(&cocos2d::Animation::addSpriteFrameWithFile);
mt["AddSpriteFrameWithTexture"]=static_cast<void(cocos2d::Animation::*)(cocos2d::Texture2D*,const cocos2d::Rect&)>(&cocos2d::Animation::addSpriteFrameWithTexture);
mt["GetTotalDelayUnits"]=static_cast<float(cocos2d::Animation::*)()const>(&cocos2d::Animation::getTotalDelayUnits);
mt["get"]["TotalDelayUnits"]=mt["GetTotalDelayUnits"];
mt["SetDelayPerUnit"]=static_cast<void(cocos2d::Animation::*)(float)>(&cocos2d::Animation::setDelayPerUnit);
mt["set"]["DelayPerUnit"]=mt["SetDelayPerUnit"];
mt["GetDelayPerUnit"]=static_cast<float(cocos2d::Animation::*)()const>(&cocos2d::Animation::getDelayPerUnit);
mt["get"]["DelayPerUnit"]=mt["GetDelayPerUnit"];
mt["GetDuration"]=static_cast<float(cocos2d::Animation::*)()const>(&cocos2d::Animation::getDuration);
mt["get"]["Duration"]=mt["GetDuration"];
mt["GetFrames"]=static_cast<const cocos2d::Vector<cocos2d::AnimationFrame *>&(cocos2d::Animation::*)()const>(&cocos2d::Animation::getFrames);
mt["get"]["Frames"]=mt["GetFrames"];
mt["SetFrames"]=static_cast<void(cocos2d::Animation::*)(const cocos2d::Vector<cocos2d::AnimationFrame *>&)>(&cocos2d::Animation::setFrames);
mt["set"]["Frames"]=mt["SetFrames"];
mt["GetRestoreOriginalFrame"]=static_cast<bool(cocos2d::Animation::*)()const>(&cocos2d::Animation::getRestoreOriginalFrame);
mt["get"]["RestoreOriginalFrame"]=mt["GetRestoreOriginalFrame"];
mt["SetRestoreOriginalFrame"]=static_cast<void(cocos2d::Animation::*)(bool)>(&cocos2d::Animation::setRestoreOriginalFrame);
mt["set"]["RestoreOriginalFrame"]=mt["SetRestoreOriginalFrame"];
mt["GetLoops"]=static_cast<unsigned int(cocos2d::Animation::*)()const>(&cocos2d::Animation::getLoops);
mt["get"]["Loops"]=mt["GetLoops"];
mt["SetLoops"]=static_cast<void(cocos2d::Animation::*)(unsigned int)>(&cocos2d::Animation::setLoops);
mt["set"]["Loops"]=mt["SetLoops"];
}
void RegisterLuaCoreActionIntervalAuto(cocos2d::extension::Lua& lua){
cocos2d::extension::Lua::Id2Meta[typeid(cocos2d::ActionInterval).name()] = sol::usertype_traits<cocos2d::ActionInterval*>::metatable();
auto dep=lua.new_usertype<cocos2d::ActionInterval>("deprecated.cocos2d::ActionInterval");
dep[sol::base_classes]=sol::bases<cocos2d::FiniteTimeAction,cocos2d::Action,cocos2d::Ref,cocos2d::extension::LuaObject,cocos2d::Clonable>();
sol::table mt=lua.NewClass(sol::usertype_traits<cocos2d::ActionInterval*>::metatable(),sol::usertype_traits<cocos2d::FiniteTimeAction*>::metatable());
lua["cc"]["ActionInterval"]=mt;
mt["__new__"] = [](){return nullptr;};
mt["GetElapsed"]=static_cast<float(cocos2d::ActionInterval::*)()>(&cocos2d::ActionInterval::getElapsed);
mt["get"]["Elapsed"]=mt["GetElapsed"];
mt["SetAmplitudeRate"]=static_cast<void(cocos2d::ActionInterval::*)(float)>(&cocos2d::ActionInterval::setAmplitudeRate);
mt["set"]["AmplitudeRate"]=mt["SetAmplitudeRate"];
mt["GetAmplitudeRate"]=static_cast<float(cocos2d::ActionInterval::*)()>(&cocos2d::ActionInterval::getAmplitudeRate);
mt["get"]["AmplitudeRate"]=mt["GetAmplitudeRate"];
}
void RegisterLuaCoreSequenceAuto(cocos2d::extension::Lua& lua){
cocos2d::extension::Lua::Id2Meta[typeid(cocos2d::Sequence).name()] = sol::usertype_traits<cocos2d::Sequence*>::metatable();
auto dep=lua.new_usertype<cocos2d::Sequence>("deprecated.cocos2d::Sequence");
dep[sol::base_classes]=sol::bases<cocos2d::ActionInterval,cocos2d::FiniteTimeAction,cocos2d::Action,cocos2d::Ref,cocos2d::extension::LuaObject,cocos2d::Clonable>();
sol::table mt=lua.NewClass(sol::usertype_traits<cocos2d::Sequence*>::metatable(),sol::usertype_traits<cocos2d::ActionInterval*>::metatable());
lua["cc"]["Sequence"]=mt;
mt["__new__"]=static_cast<cocos2d::Sequence*(*)(const cocos2d::Vector<cocos2d::FiniteTimeAction *>&)>(&cocos2d::Sequence::create);
mt["static"]["CreateWithVariableList"]=static_cast<cocos2d::Sequence*(*)(cocos2d::FiniteTimeAction*,va_list)>(&cocos2d::Sequence::createWithVariableList);
mt["static"]["CreateWithTwoActions"]=static_cast<cocos2d::Sequence*(*)(cocos2d::FiniteTimeAction*,cocos2d::FiniteTimeAction*)>(&cocos2d::Sequence::createWithTwoActions);
}
void RegisterLuaCoreRepeatAuto(cocos2d::extension::Lua& lua){
cocos2d::extension::Lua::Id2Meta[typeid(cocos2d::Repeat).name()] = sol::usertype_traits<cocos2d::Repeat*>::metatable();
auto dep=lua.new_usertype<cocos2d::Repeat>("deprecated.cocos2d::Repeat");
dep[sol::base_classes]=sol::bases<cocos2d::ActionInterval,cocos2d::FiniteTimeAction,cocos2d::Action,cocos2d::Ref,cocos2d::extension::LuaObject,cocos2d::Clonable>();
sol::table mt=lua.NewClass(sol::usertype_traits<cocos2d::Repeat*>::metatable(),sol::usertype_traits<cocos2d::ActionInterval*>::metatable());
lua["cc"]["Repeat"]=mt;
mt["__new__"]=static_cast<cocos2d::Repeat*(*)(cocos2d::FiniteTimeAction*,unsigned int)>(&cocos2d::Repeat::create);
mt["SetInnerAction"]=static_cast<void(cocos2d::Repeat::*)(cocos2d::FiniteTimeAction*)>(&cocos2d::Repeat::setInnerAction);
mt["set"]["InnerAction"]=mt["SetInnerAction"];
mt["GetInnerAction"]=static_cast<cocos2d::FiniteTimeAction*(cocos2d::Repeat::*)()>(&cocos2d::Repeat::getInnerAction);
mt["get"]["InnerAction"]=mt["GetInnerAction"];
}
void RegisterLuaCoreRepeatForeverAuto(cocos2d::extension::Lua& lua){
cocos2d::extension::Lua::Id2Meta[typeid(cocos2d::RepeatForever).name()] = sol::usertype_traits<cocos2d::RepeatForever*>::metatable();
auto dep=lua.new_usertype<cocos2d::RepeatForever>("deprecated.cocos2d::RepeatForever");
dep[sol::base_classes]=sol::bases<cocos2d::ActionInterval,cocos2d::FiniteTimeAction,cocos2d::Action,cocos2d::Ref,cocos2d::extension::LuaObject,cocos2d::Clonable>();
sol::table mt=lua.NewClass(sol::usertype_traits<cocos2d::RepeatForever*>::metatable(),sol::usertype_traits<cocos2d::ActionInterval*>::metatable());
lua["cc"]["RepeatForever"]=mt;
mt["__new__"]=static_cast<cocos2d::RepeatForever*(*)(cocos2d::ActionInterval*)>(&cocos2d::RepeatForever::create);
mt["SetInnerAction"]=static_cast<void(cocos2d::RepeatForever::*)(cocos2d::ActionInterval*)>(&cocos2d::RepeatForever::setInnerAction);
mt["set"]["InnerAction"]=mt["SetInnerAction"];
mt["GetInnerAction"]=static_cast<cocos2d::ActionInterval*(cocos2d::RepeatForever::*)()>(&cocos2d::RepeatForever::getInnerAction);
mt["get"]["InnerAction"]=mt["GetInnerAction"];
}
void RegisterLuaCoreSpawnAuto(cocos2d::extension::Lua& lua){
cocos2d::extension::Lua::Id2Meta[typeid(cocos2d::Spawn).name()] = sol::usertype_traits<cocos2d::Spawn*>::metatable();
auto dep=lua.new_usertype<cocos2d::Spawn>("deprecated.cocos2d::Spawn");
dep[sol::base_classes]=sol::bases<cocos2d::ActionInterval,cocos2d::FiniteTimeAction,cocos2d::Action,cocos2d::Ref,cocos2d::extension::LuaObject,cocos2d::Clonable>();
sol::table mt=lua.NewClass(sol::usertype_traits<cocos2d::Spawn*>::metatable(),sol::usertype_traits<cocos2d::ActionInterval*>::metatable());
lua["cc"]["Spawn"]=mt;
mt["static"]["CreateWithVariableList"]=static_cast<cocos2d::Spawn*(*)(cocos2d::FiniteTimeAction*,va_list)>(&cocos2d::Spawn::createWithVariableList);
mt["__new__"]=static_cast<cocos2d::Spawn*(*)(const cocos2d::Vector<cocos2d::FiniteTimeAction *>&)>(&cocos2d::Spawn::create);
mt["static"]["CreateWithTwoActions"]=static_cast<cocos2d::Spawn*(*)(cocos2d::FiniteTimeAction*,cocos2d::FiniteTimeAction*)>(&cocos2d::Spawn::createWithTwoActions);
}
void RegisterLuaCoreRotateToAuto(cocos2d::extension::Lua& lua){
cocos2d::extension::Lua::Id2Meta[typeid(cocos2d::RotateTo).name()] = sol::usertype_traits<cocos2d::RotateTo*>::metatable();
auto dep=lua.new_usertype<cocos2d::RotateTo>("deprecated.cocos2d::RotateTo");
dep[sol::base_classes]=sol::bases<cocos2d::ActionInterval,cocos2d::FiniteTimeAction,cocos2d::Action,cocos2d::Ref,cocos2d::extension::LuaObject,cocos2d::Clonable>();
sol::table mt=lua.NewClass(sol::usertype_traits<cocos2d::RotateTo*>::metatable(),sol::usertype_traits<cocos2d::ActionInterval*>::metatable());
lua["cc"]["RotateTo"]=mt;
mt["__new__"]=sol::overload(static_cast<cocos2d::RotateTo*(*)(float,float,float)>(&cocos2d::RotateTo::create),static_cast<cocos2d::RotateTo*(*)(float,const cocos2d::Vec3&)>(&cocos2d::RotateTo::create),static_cast<cocos2d::RotateTo*(*)(float,float)>(&cocos2d::RotateTo::create));
}
| 99.070352 | 512 | 0.759726 | [
"vector"
] |
de7c5edad3d3a27057773ff849e871d2887477e7 | 1,485 | cc | C++ | src/accepted/11150.cc | cbarnson/UVa | 0dd73fae656613e28b5aaf5880c5dad529316270 | [
"Unlicense",
"MIT"
] | 2 | 2019-09-07T17:00:26.000Z | 2020-08-05T02:08:35.000Z | src/accepted/11150.cc | cbarnson/UVa | 0dd73fae656613e28b5aaf5880c5dad529316270 | [
"Unlicense",
"MIT"
] | null | null | null | src/accepted/11150.cc | cbarnson/UVa | 0dd73fae656613e28b5aaf5880c5dad529316270 | [
"Unlicense",
"MIT"
] | null | null | null | // Problem # : 11150
// Created on : 2018-05-28 20:52:39
// Title : Cola
// Accepted : Yes
#include <assert.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <algorithm>
#include <bitset>
#include <deque>
#include <functional>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <limits>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <utility>
#include <vector>
using namespace std;
typedef vector<vector<int>> vec2d;
typedef vector<int> vi;
typedef pair<int, int> ii;
typedef long long ll;
int dp[205][205];
int n;
int f(int i, int j)
{
if (i < 3 && j < (3 - i))
{
return dp[i][j];
}
if (dp[i][j] != -1)
{
return dp[i][j];
}
if (i > 0)
{
return i + f(0, i + j);
}
return f(j / 3, j % 3);
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
// pre-compute; init
for (int i = 0; i < 205; i++)
{
memset(dp[i], -1, sizeof dp[i]);
}
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < (3 - i); j++)
{
if (i + j == 2)
dp[i][j] = i + 1;
else
dp[i][j] = i;
}
}
int N = 201;
for (int k = 3; k < N; k++)
{
for (int i = 0; i <= k; i++)
{
int j = k - i;
dp[i][j] = f(i, j);
}
}
int n;
while (cin >> n)
{
cout << dp[n][0] << endl;
}
return 0;
}
| 14.70297 | 37 | 0.515152 | [
"vector"
] |
de885db2c047458b1a2ea20d9b8613fb0c65ba5f | 12,539 | cpp | C++ | ExternalCode/copasi/UI/CQReactionDM.cpp | dhlee4/Tinkercell_new | c4d1848bbb905f0e1f9e011837268ac80aff8711 | [
"BSD-3-Clause"
] | 1 | 2021-01-07T13:12:51.000Z | 2021-01-07T13:12:51.000Z | ExternalCode/copasi/UI/CQReactionDM.cpp | dhlee4/Tinkercell_new | c4d1848bbb905f0e1f9e011837268ac80aff8711 | [
"BSD-3-Clause"
] | 7 | 2020-04-12T22:25:46.000Z | 2020-04-13T07:50:40.000Z | ExternalCode/copasi/UI/CQReactionDM.cpp | daniel-anavaino/tinkercell | 7896a7f809a0373ab3c848d25e3691d10a648437 | [
"BSD-3-Clause"
] | 2 | 2020-04-12T21:57:01.000Z | 2020-04-12T21:59:29.000Z | // Begin CVS Header
// $Source: /fs/turing/cvs/copasi_dev/copasi/UI/CQReactionDM.cpp,v $
// $Revision: 1.15.4.3 $
// $Name: Build-33 $
// $Author: shoops $
// $Date: 2010/09/30 17:02:30 $
// End CVS Header
// Copyright (C) 2010 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.
// Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., EML Research, gGmbH, University of Heidelberg,
// and The University of Manchester.
// All rights reserved.
#include <QString>
#include <QList>
#include "CopasiDataModel/CCopasiDataModel.h"
#include "report/CCopasiRootContainer.h"
#include "model/CChemEqInterface.h"
#include "model/CReaction.h"
#include "model/CReactionInterface.h"
#include "CQMessageBox.h"
#include "CQReactionDM.h"
#include "qtUtilities.h"
CQReactionDM::CQReactionDM(QObject *parent)
: CQBaseDataModel(parent)
{
}
int CQReactionDM::rowCount(const QModelIndex& C_UNUSED(parent)) const
{
return (*CCopasiRootContainer::getDatamodelList())[0]->getModel()->getReactions().size() + 1;
}
int CQReactionDM::columnCount(const QModelIndex& C_UNUSED(parent)) const
{
return TOTAL_COLS_REACTIONS;
}
Qt::ItemFlags CQReactionDM::flags(const QModelIndex &index) const
{
if (!index.isValid())
return Qt::ItemIsEnabled;
if (index.column() == COL_NAME_REACTIONS || index.column() == COL_EQUATION)
return QAbstractItemModel::flags(index) | Qt::ItemIsEditable;
else
return QAbstractItemModel::flags(index);
}
QVariant CQReactionDM::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
if (index.row() >= rowCount())
return QVariant();
if (index.column() > 0 && role == Qt::ForegroundRole && !(flags(index) & Qt::ItemIsEditable))
return QColor(Qt::darkGray);
if (role == Qt::DisplayRole || role == Qt::EditRole)
{
if (isDefaultRow(index))
{
switch (index.column())
{
case COL_ROW_NUMBER:
return QVariant(index.row() + 1);
case COL_NAME_REACTIONS:
return QVariant(QString("New Reaction"));
default:
return QVariant(QString(""));
}
}
else
{
CReaction *pRea = (*CCopasiRootContainer::getDatamodelList())[0]->getModel()->getReactions()[index.row()];
switch (index.column())
{
case COL_ROW_NUMBER:
return QVariant(index.row() + 1);
case COL_NAME_REACTIONS:
return QVariant(QString(FROM_UTF8(pRea->getObjectName())));
case COL_EQUATION:
return QVariant(QString(FROM_UTF8(CChemEqInterface::getChemEqString((*CCopasiRootContainer::getDatamodelList())[0]->getModel(), *pRea, false))));
case COL_RATE_LAW:
if (pRea->getFunction())
return QVariant(QString(FROM_UTF8(pRea->getFunction()->getObjectName())));
case COL_FLUX:
return QVariant(pRea->getFlux());
case COL_PARTICLE_FLUX:
return QVariant(pRea->getParticleFlux());
}
}
}
return QVariant();
}
QVariant CQReactionDM::headerData(int section, Qt::Orientation orientation,
int role) const
{
if (role != Qt::DisplayRole)
return QVariant();
if (orientation == Qt::Horizontal)
{
switch (section)
{
case COL_ROW_NUMBER:
return QVariant(QString("#"));
case COL_NAME_REACTIONS:
return QVariant(QString("Name"));
case COL_EQUATION:
return QVariant(QString("Equation"));
case COL_RATE_LAW:
return QVariant(QString("Rate Law"));
case COL_FLUX:
{
const CModel * pModel = (*CCopasiRootContainer::getDatamodelList())[0]->getModel();
if (pModel == NULL) return QVariant();
QString RateUnits;
if (pModel)
RateUnits = FROM_UTF8(pModel->getQuantityRateUnitsDisplayString());
if (!RateUnits.isEmpty())
RateUnits = "\n(" + RateUnits + ")";
return QVariant("Flux" + RateUnits);
}
case COL_PARTICLE_FLUX:
{
const CModel * pModel = (*CCopasiRootContainer::getDatamodelList())[0]->getModel();
if (pModel == NULL) return QVariant();
QString FrequencyUnits;
if (pModel)
FrequencyUnits = FROM_UTF8(pModel->getFrequencyUnitsDisplayString());
if (!FrequencyUnits.isEmpty())
FrequencyUnits = "\n(" + FrequencyUnits + ")";
return QVariant("Flux" + FrequencyUnits);
}
default:
return QVariant();
}
}
else
return QString("%1").arg(section + 1);
}
bool CQReactionDM::setData(const QModelIndex &index, const QVariant &value,
int role)
{
if (index.isValid() && role == Qt::EditRole)
{
bool defaultRow = isDefaultRow(index);
if (defaultRow)
{
if (index.data() != value)
insertRow();
else
return false;
}
// this loads the reaction into a CReactionInterface object.
// the gui works on this object and later writes back the changes to ri;
assert(CCopasiRootContainer::getDatamodelList()->size() > 0);
CReactionInterface ri((*CCopasiRootContainer::getDatamodelList())[0]->getModel());
CReaction *pRea = (*CCopasiRootContainer::getDatamodelList())[0]->getModel()->getReactions()[index.row()];
if (index.column() == COL_NAME_REACTIONS)
pRea->setObjectName(TO_UTF8(value.toString()));
else if (index.column() == COL_EQUATION)
setEquation(pRea, index, value);
if (defaultRow && this->index(index.row(), COL_NAME_REACTIONS).data().toString() == "reaction")
pRea->setObjectName(TO_UTF8(createNewName("reaction", COL_NAME_REACTIONS)));
emit dataChanged(index, index);
emit notifyGUI(ListViews::REACTION, ListViews::CHANGE, pRea->getKey());
}
return true;
}
void CQReactionDM::setEquation(const CReaction *pRea, const QModelIndex& index, const QVariant &value)
{
std::string objKey = pRea->getKey();
QString equation = value.toString();
assert(CCopasiRootContainer::getDatamodelList()->size() > 0);
CCopasiDataModel* pDataModel = (*CCopasiRootContainer::getDatamodelList())[0];
assert(pDataModel != NULL);
CModel * pModel = pDataModel->getModel();
if (pModel == NULL) return;
// this loads the reaction into a CReactionInterface object.
// the gui works on this object and later writes back the changes to ri;
assert(CCopasiRootContainer::getDatamodelList()->size() > 0);
CReactionInterface ri((*CCopasiRootContainer::getDatamodelList())[0]->getModel());
ri.initFromReaction(objKey);
if (TO_UTF8(equation) != ri.getChemEqString())
{
//first check if the string is a valid equation
if (!CChemEqInterface::isValidEq(TO_UTF8(equation)))
{
return;
}
else
{
//tell the reaction interface
ri.setChemEqString(TO_UTF8(equation), "");
}
}
// Before we save any changes we must check whether any local reaction parameters,
// which are used in any mathematical expression in the model are removed.
// If that is the case the user must have option to cancel the changes or remove the
// affected expressions.
std::set< const CCopasiObject * > DeletedParameters = ri.getDeletedParameters();
if (DeletedParameters.size() != 0)
{
QString ObjectType = "parameter(s) of reaction " + this->index(index.row(), COL_NAME_REACTIONS).data().toString();
QString Objects;
std::set< const CCopasiObject * >::const_iterator itParameter, endParameter = DeletedParameters.end();
std::set< const CCopasiObject * > DeletedObjects;
for (itParameter = DeletedParameters.begin(); itParameter != endParameter; ++itParameter) //all parameters
{
Objects.append(FROM_UTF8((*itParameter)->getObjectName()) + ", ");
DeletedObjects.insert((*itParameter)->getObject(CCopasiObjectName("Reference=Value")));
}
Objects.remove(Objects.length() - 2, 2);
QMessageBox::StandardButton choice =
CQMessageBox::confirmDelete(NULL, ObjectType,
Objects, DeletedObjects);
switch (choice)
{
case QMessageBox::Ok:
for (itParameter = DeletedParameters.begin(); itParameter != endParameter; ++itParameter) //all parameters
pModel->removeLocalReactionParameter((*itParameter)->getKey());
break;
default:
return;
break;
}
}
// We need to check whether the current reaction still exists, since it is possible that
// removing a local reaction parameter triggers its deletion.
CReaction * reac = dynamic_cast< CReaction * >(CCopasiRootContainer::getKeyFactory()->get(objKey));
if (reac == NULL)
{
ri.setFunctionWithEmptyMapping("");
emit notifyGUI(ListViews::REACTION, ListViews::DELETE, objKey);
emit notifyGUI(ListViews::REACTION, ListViews::DELETE, ""); //Refresh all as there may be dependencies.
return;
}
//first check if new metabolites need to be created
bool createdMetabs = ri.createMetabolites();
bool createdObjects = ri.createOtherObjects();
//this writes all changes to the reaction
ri.writeBackToReaction(NULL);
//(*CCopasiRootContainer::getDatamodelList())[0]->getModel()->compile();
//this tells the gui what it needs to know.
if (createdObjects)
emit notifyGUI(ListViews::MODEL, ListViews::CHANGE, "");
else
{
if (createdMetabs) emit notifyGUI(ListViews::METABOLITE, ListViews::ADD, "");
}
}
bool CQReactionDM::insertRows(int position, int rows, const QModelIndex&)
{
beginInsertRows(QModelIndex(), position, position + rows - 1);
for (int row = 0; row < rows; ++row)
{
CReaction *pRea = (*CCopasiRootContainer::getDatamodelList())[0]->getModel()->createReaction(TO_UTF8(createNewName("reaction", COL_NAME_REACTIONS)));
emit notifyGUI(ListViews::REACTION, ListViews::ADD, pRea->getKey());
}
endInsertRows();
return true;
}
bool CQReactionDM::removeRows(int position, int rows, const QModelIndex&)
{
if (rows <= 0)
return true;
beginRemoveRows(QModelIndex(), position, position + rows - 1);
for (int row = 0; row < rows; ++row)
{
std::string deletedKey = (*CCopasiRootContainer::getDatamodelList())[0]->getModel()->getReactions()[position]->getKey();
(*CCopasiRootContainer::getDatamodelList())[0]->getModel()->removeReaction(position);
emit notifyGUI(ListViews::REACTION, ListViews::DELETE, deletedKey);
emit notifyGUI(ListViews::REACTION, ListViews::DELETE, "");//Refresh all as there may be dependencies.
}
endRemoveRows();
return true;
}
bool CQReactionDM::removeRows(QModelIndexList rows, const QModelIndex&)
{
if (rows.isEmpty())
return false;
assert(CCopasiRootContainer::getDatamodelList()->size() > 0);
CCopasiDataModel* pDataModel = (*CCopasiRootContainer::getDatamodelList())[0];
assert(pDataModel != NULL);
CModel * pModel = pDataModel->getModel();
if (pModel == NULL)
return false;
//Build the list of pointers to items to be deleted
//before actually deleting any item.
QList <CReaction *> pReactions;
QModelIndexList::const_iterator i;
for (i = rows.begin(); i != rows.end(); ++i)
{
if (!isDefaultRow(*i) && pModel->getReactions()[(*i).row()])
pReactions.append(pModel->getReactions()[(*i).row()]);
}
QList <CReaction *>::const_iterator j;
for (j = pReactions.begin(); j != pReactions.end(); ++j)
{
CReaction * pReaction = *j;
unsigned C_INT32 delRow =
pModel->getReactions().CCopasiVector< CReaction >::getIndex(pReaction);
if (delRow != C_INVALID_INDEX)
{
QMessageBox::StandardButton choice =
CQMessageBox::confirmDelete(NULL, "reaction",
FROM_UTF8(pReaction->getObjectName()),
pReaction->getDeletedObjects());
if (choice == QMessageBox::Ok)
removeRow(delRow);
}
}
return true;
}
| 31.987245 | 161 | 0.631071 | [
"object",
"model"
] |
de8b6c0c1408e0c0d5778e5c351a5a451ad9daf7 | 802 | cpp | C++ | android-31/java/util/IllegalFormatFlagsException.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 12 | 2020-03-26T02:38:56.000Z | 2022-03-14T08:17:26.000Z | android-31/java/util/IllegalFormatFlagsException.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 1 | 2021-01-27T06:07:45.000Z | 2021-11-13T19:19:43.000Z | android-29/java/util/IllegalFormatFlagsException.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 3 | 2021-02-02T12:34:55.000Z | 2022-03-08T07:45:57.000Z | #include "../../JString.hpp"
#include "./IllegalFormatFlagsException.hpp"
namespace java::util
{
// Fields
// QJniObject forward
IllegalFormatFlagsException::IllegalFormatFlagsException(QJniObject obj) : java::util::IllegalFormatException(obj) {}
// Constructors
IllegalFormatFlagsException::IllegalFormatFlagsException(JString arg0)
: java::util::IllegalFormatException(
"java.util.IllegalFormatFlagsException",
"(Ljava/lang/String;)V",
arg0.object<jstring>()
) {}
// Methods
JString IllegalFormatFlagsException::getFlags() const
{
return callObjectMethod(
"getFlags",
"()Ljava/lang/String;"
);
}
JString IllegalFormatFlagsException::getMessage() const
{
return callObjectMethod(
"getMessage",
"()Ljava/lang/String;"
);
}
} // namespace java::util
| 22.277778 | 118 | 0.724439 | [
"object"
] |
de966b61f054eab17d4ca3029a16ce81fd38a5f2 | 18,979 | cpp | C++ | SDK/Examples/Cpp/Source/SecureCube.cpp | alexanderoster/lib3mf | 30d5c2e0e8ed7febb5c10a84dc2db9d53fee6d05 | [
"BSD-2-Clause"
] | 171 | 2015-04-30T21:54:02.000Z | 2022-03-13T13:33:59.000Z | SDK/Examples/Cpp/Source/SecureCube.cpp | alexanderoster/lib3mf | 30d5c2e0e8ed7febb5c10a84dc2db9d53fee6d05 | [
"BSD-2-Clause"
] | 190 | 2015-07-21T22:15:54.000Z | 2022-03-30T15:48:37.000Z | SDK/Examples/Cpp/Source/SecureCube.cpp | alexanderoster/lib3mf | 30d5c2e0e8ed7febb5c10a84dc2db9d53fee6d05 | [
"BSD-2-Clause"
] | 80 | 2015-04-30T22:15:54.000Z | 2022-03-09T12:38:49.000Z | /*++
Copyright (C) 2020 3MF Consortium
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL MICROSOFT AND/OR NETFABB 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.
Abstract:
SecureCube.cpp : 3MF encrypted Cube creation and read example. This is a sample
skeleton code provided to guide you to the process of reading and writing a 3MF
file using the Secure Content spec. Encryption and decryption processes are abstracted
so to avoid binding this sample to any particular implementation. If you would like
to check a working version of the process, there's a unit tests available on the 3MF code
base that implements the entire workflow using LibreSSL: EncryptionMethods.cpp
Tip: you could also copy buffers around - file won't be valid but you will be able
to run the entire process.
--*/
#include <iostream>
#include <string>
#include <algorithm>
#include <map>
#include "lib3mf_implicit.hpp"
using namespace Lib3MF;
namespace SecureContentCallbacks {
// Sample random number generation callback. Do not use this beyond the scope of this example as it is not really a random number generation function.
static void NotRandomBytesAtAll(Lib3MF_uint64 byteData, Lib3MF_uint64 size, Lib3MF_pvoid userData, Lib3MF_uint64 * bytesWritten) {
static Lib3MF_uint8 random = 0;
Lib3MF_uint8 * buffer = (Lib3MF_uint8 *)byteData;
*bytesWritten = size;
while (size > 0)
*(buffer + (--size)) = ++random;
}
// Structure to hold encryption context for keys
struct KeyWrappingCbData {
CWrapper * wrapper;
};
// Structure to hold encryption context for resources
struct ContentEncryptionCbData {
CWrapper * wrapper;
std::map<Lib3MF_uint64, Lib3MF_uint64> context;
};
// Sample callback to wrap the key of an encryption process
static void WriteKeyWrappingCbSample(
Lib3MF_AccessRight access,
Lib3MF_uint64 inSize,
const Lib3MF_uint8 * inBuffer,
const Lib3MF_uint64 outSize,
Lib3MF_uint64 * outNeeded,
Lib3MF_uint8 * outBuffer,
Lib3MF_pvoid userData,
Lib3MF_uint64 * status) {
KeyWrappingCbData * cp = (KeyWrappingCbData *)userData;
// Since we're using CAccessRight constructure, we have to account for
// the use of 'access' by calling Acquire on the CWrapper
CAccessRight accessRight(cp->wrapper, access);
cp->wrapper->Acquire(&accessRight);
// This is going to be called for each consumer you've registered to
PConsumer consumer = accessRight.GetConsumer();
std::string consumerId = consumer->GetConsumerID();
std::cout << "ConsumerID " << consumer->GetConsumerID() << std::endl;
// You can also check for keyid and keyvalue
// A call could be made to first identify what the output buffer size should be.
// In that case, outSize will be 0 or outBuffer will be null, and the proper size must be placed in outNeeded.
if (nullptr == outBuffer || outSize == 0) {
*outNeeded = inSize;
*status = inSize;
return;
}
// Query the data about the encryption process to be done
eWrappingAlgorithm algorithm = accessRight.GetWrappingAlgorithm();
eMgfAlgorithm mask = accessRight.GetMgfAlgorithm();
eDigestMethod diges = accessRight.GetDigestMethod();
// You should deal with the encryption process of the key.
// Use the encryption process to wrap inBuffer (plain) into outBuffer (cipher) using details above.
// Use KeyWrappingCbData to hold any information you'll be needing at this point.
throw std::runtime_error("TODO: Add your encryption wrapping process here");
//std::copy(inBuffer, inBuffer + outSize, outBuffer);
// Finally, this function should use status to return the number of bytes needed,
// encrypted - or zero to indicate a failure.
*status = outSize;
}
// Sample callback to encrypt contents of a resource
static void WriteContentEncryptionCbSample(
Lib3MF_ContentEncryptionParams params,
Lib3MF_uint64 inSize,
const Lib3MF_uint8 * inBuffer,
const Lib3MF_uint64 outSize,
Lib3MF_uint64 * outNeededSize,
Lib3MF_uint8 * outBuffer,
Lib3MF_pvoid userData,
Lib3MF_uint64 * status) {
ContentEncryptionCbData * cb = (ContentEncryptionCbData *)userData;
// Since we're using CAccessRight constructure, we have to account for
// the use of 'access' by calling Acquire on the CWrapper
CContentEncryptionParams cd(cb->wrapper, params);
cb->wrapper->Acquire(&cd);
// A descriptor uniquely identifies the encryption process for a resource
Lib3MF_uint64 descriptor = cd.GetDescriptor();
// You can map the descriptor in use as you'll probably keep several
// contexts initialized at same time
auto localDescriptor = cb->context.find(cd.GetDescriptor());
if (localDescriptor != cb->context.end())
// Use an existing context
localDescriptor->second++;
else {
// Initialize a new context
// Retrieve the encryption key, if there is one
std::vector<Lib3MF_uint8> key;
cd.GetKey(key);
// You can also use keyuuid to look up a key externally
std::string keyUUID = cd.GetKeyUUID();
// Retrieve the additional authenticaton data, if it has been used to encrypt
std::vector<Lib3MF_uint8> aad;
cd.GetAdditionalAuthenticationData(aad);
// TODO: Initialize the encryption context
cb->context[cd.GetDescriptor()] = 0;
}
// Attention to the order in which params are tested, it matters
if (0 == inSize || nullptr == inBuffer) {
// When input buffer is null or input size is 0, this is a request
// to finalize this encryption process and generating the authentication tag
// TODO: generate proper tag
std::vector<Lib3MF_uint8> tag = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
cd.SetAuthenticationTag(tag);
//add tag verification status here
*status = tag.size();
} else if (0 == outSize || nullptr == outBuffer) {
// If outSize is zero or outBuffer is null (but inSize and inBuffer are not),
// this is a call to figure out the output buffer size.
// Put the respective value in outNeededSize.
*outNeededSize = inSize;
*status = inSize;
} else {
// Else, perform the encryption process
throw std::runtime_error("TODO: Add your encryption process here");
//std::copy(inBuffer, inBuffer + outSize, outBuffer);
*status = outSize;
}
//This function should use status to return the number of bytes needed, encrypted
// or verified - or zero to indicate a failure.
}
static void ReadKeyWrappingCbSample(
Lib3MF_AccessRight access,
Lib3MF_uint64 inSize,
const Lib3MF_uint8 * inBuffer,
const Lib3MF_uint64 outSize,
Lib3MF_uint64 * outNeeded,
Lib3MF_uint8 * outBuffer,
Lib3MF_pvoid userData,
Lib3MF_uint64 * status) {
// A call could be made to first identify what the output buffer size should be.
// In that case, outSize will be 0 or outBuffer will be null, and the proper size must be placed in outNeeded.
if (nullptr == outBuffer || outSize == 0) {
*outNeeded = inSize;
*status = inSize;
return;
}
KeyWrappingCbData * cp = (KeyWrappingCbData *)userData;
// Since we're using CAccessRight constructure, we have to account for
// the use of 'access' by calling Acquire on the CWrapper
CAccessRight accessRight(cp->wrapper, access);
cp->wrapper->Acquire(&accessRight);
// This is going to be called for each consumer you've registered to
PConsumer consumer = accessRight.GetConsumer();
std::string consumerId = consumer->GetConsumerID();
std::cout << "ConsumerID " << consumer->GetConsumerID() << std::endl;
// You can also check for keyid and keyvalue
// Query the data about the encryption process to be done
eWrappingAlgorithm algorithm = accessRight.GetWrappingAlgorithm();
eMgfAlgorithm mask = accessRight.GetMgfAlgorithm();
eDigestMethod diges = accessRight.GetDigestMethod();
// You should deal with the encryption process of the key.
// Use the encryption process to wrap inBuffer (cipher) into outBuffer (plain) using details above.
// Use KeyWrappingCbData to hold any information you'll be needing at this point.
throw std::runtime_error("TODO: Add your decryption wrapping process here");
//std::copy(inBuffer, inBuffer + outSize, outBuffer);
// Finally, this function should use status to return the number of bytes needed,
// decrypted - or zero to indicate a failure.
*status = outSize;
}
static void ReadContentEncryptionCbSample(
Lib3MF_ContentEncryptionParams params,
Lib3MF_uint64 inSize,
const Lib3MF_uint8 * inBuffer,
const Lib3MF_uint64 outSize,
Lib3MF_uint64 * outNeededSize,
Lib3MF_uint8 * outBuffer,
Lib3MF_pvoid userData,
Lib3MF_uint64 * status) {
ContentEncryptionCbData * cb = (ContentEncryptionCbData *)userData;
// Since we're using CAccessRight constructure, we have to account for
// the use of 'access' by calling Acquire on the CWrapper
CContentEncryptionParams cd(cb->wrapper, params);
cb->wrapper->Acquire(&cd);
// A descriptor uniquely identifies the encryption process for a resource
Lib3MF_uint64 descriptor = cd.GetDescriptor();
// You can map the descriptor in use as you'll probably keep several
// contexts initialized at same time
auto localDescriptor = cb->context.find(cd.GetDescriptor());
if (localDescriptor != cb->context.end())
// Use an existing context
localDescriptor->second++;
else {
// Initialize a new context
// Retrieve the encryption key, if there is one
std::vector<Lib3MF_uint8> key;
cd.GetKey(key);
// You can also use keyuuid to look up a key externally
std::string keyUUID = cd.GetKeyUUID();
// Retrieve the additional authenticaton data, if it has been used to encrypt
std::vector<Lib3MF_uint8> aad;
cd.GetAdditionalAuthenticationData(aad);
// TODO: Initialize the encryption context
cb->context[cd.GetDescriptor()] = 0;
}
// Attention to the order in which params are tested, it matters
if (0 == inSize || nullptr == inBuffer) {
// When input buffer is null or input size is 0, this is a request
// to finalize this encryption process and verify the authentication tag
std::vector<Lib3MF_uint8> tag;
cd.GetAuthenticationTag(tag);
// TODO: verify tag
*status = tag.size();
} else if (0 == outSize || nullptr == outBuffer) {
// If outSize is zero or outBuffer is null (but inSize and inBuffer are not),
// this is a call to figure out the output buffer size.
// Put the respective value in outNeededSize.
*outNeededSize = inSize;
*status = inSize;
return;
} else {
// Else, perform the descryption process
throw std::runtime_error("TODO: Add your encryption process here");
//std::copy(inBuffer, inBuffer + outSize, outBuffer);
*status = outSize;
}
//This function should use status to return the number of bytes needed, decrypted
// or verified - or zero to indicate a failure.
}
};
void printVersion(CWrapper & wrapper) {
Lib3MF_uint32 nMajor, nMinor, nMicro;
wrapper.GetLibraryVersion(nMajor, nMinor, nMicro);
std::cout << "lib3mf version = " << nMajor << "." << nMinor << "." << nMicro;
std::string sReleaseInfo, sBuildInfo;
if (wrapper.GetPrereleaseInformation(sReleaseInfo)) {
std::cout << "-" << sReleaseInfo;
}
if (wrapper.GetBuildInformation(sBuildInfo)) {
std::cout << "+" << sBuildInfo;
}
std::cout << std::endl;
}
// Utility functions to create vertices and triangles
sLib3MFPosition fnCreateVertex(float x, float y, float z) {
sLib3MFPosition result;
result.m_Coordinates[0] = x;
result.m_Coordinates[1] = y;
result.m_Coordinates[2] = z;
return result;
}
sLib3MFTriangle fnCreateTriangle(int v0, int v1, int v2) {
sLib3MFTriangle result;
result.m_Indices[0] = v0;
result.m_Indices[1] = v1;
result.m_Indices[2] = v2;
return result;
}
void WriteSecureContentExample(CWrapper & wrapper) {
PModel model = wrapper.CreateModel();
// After initializing the model, set the random number generation callback
// A default one will be used if you don't, current implementation uses std::mt19937
model->SetRandomNumberCallback(SecureContentCallbacks::NotRandomBytesAtAll, nullptr);
PMeshObject meshObject = model->AddMeshObject();
meshObject->SetName("Box");
// Create mesh structure of a cube
std::vector<sLib3MFPosition> vertices(8);
std::vector<sLib3MFTriangle> triangles(12);
float fSizeX = 100.0f;
float fSizeY = 200.0f;
float fSizeZ = 300.0f;
// Manually create vertices
vertices[0] = fnCreateVertex(0.0f, 0.0f, 0.0f);
vertices[1] = fnCreateVertex(fSizeX, 0.0f, 0.0f);
vertices[2] = fnCreateVertex(fSizeX, fSizeY, 0.0f);
vertices[3] = fnCreateVertex(0.0f, fSizeY, 0.0f);
vertices[4] = fnCreateVertex(0.0f, 0.0f, fSizeZ);
vertices[5] = fnCreateVertex(fSizeX, 0.0f, fSizeZ);
vertices[6] = fnCreateVertex(fSizeX, fSizeY, fSizeZ);
vertices[7] = fnCreateVertex(0.0f, fSizeY, fSizeZ);
// Manually create triangles
triangles[0] = fnCreateTriangle(2, 1, 0);
triangles[1] = fnCreateTriangle(0, 3, 2);
triangles[2] = fnCreateTriangle(4, 5, 6);
triangles[3] = fnCreateTriangle(6, 7, 4);
triangles[4] = fnCreateTriangle(0, 1, 5);
triangles[5] = fnCreateTriangle(5, 4, 0);
triangles[6] = fnCreateTriangle(2, 3, 7);
triangles[7] = fnCreateTriangle(7, 6, 2);
triangles[8] = fnCreateTriangle(1, 2, 6);
triangles[9] = fnCreateTriangle(6, 5, 1);
triangles[10] = fnCreateTriangle(3, 0, 4);
triangles[11] = fnCreateTriangle(4, 7, 3);
meshObject->SetGeometry(vertices, triangles);
// Add build item
model->AddBuildItem(meshObject.get(), wrapper.GetIdentityTransform());
// Move this mesh out of the root model file into another model
PPackagePart nonRootModel = model->FindOrCreatePackagePart("/3D/securecube.model");
meshObject->SetPackagePart(nonRootModel.get());
// Locate the keystore and setup the resource as a secure content
PKeyStore keystore = model->GetKeyStore();
// Add you (client) as consumer of the resource. You'll need to do this
// to be able to have a chance to wrap the content key
// You can set optional public key and an optional key id
PConsumer consumer = keystore->AddConsumer("MyConsumerID", std::string(), std::string());
// Add a container for your secured resources. Resources within the same container will have a shared key.
PResourceDataGroup dataGroup = keystore->AddResourceDataGroup();
// Add access rights for your consumer into the datagroup
PAccessRight accessRight = dataGroup->AddAccessRight(consumer.get(), eWrappingAlgorithm::RSA_OAEP, eMgfAlgorithm::MGF1_SHA1, eDigestMethod::SHA1);
// Specify additional authentication data that you could use to further validate your encryption process
std::vector<Lib3MF_uint8> aad = { '3','M','F','C','o','n','s','o','r','t','i','u','m',' ','S','a','m','p','l','e' };
// This will effectively add your nonRootModel as a secure content
PResourceData resourceData = keystore->AddResourceData(dataGroup.get(), nonRootModel.get(), eEncryptionAlgorithm::AES256_GCM, eCompression::Deflate, aad);
// Query the writer and setup the encryption before saving results
PWriter writer = model->QueryWriter("3mf");
// Setup Key Wrapping process
SecureContentCallbacks::KeyWrappingCbData keyData;
keyData.wrapper = &wrapper;
writer->AddKeyWrappingCallback(consumer->GetConsumerID(), SecureContentCallbacks::WriteKeyWrappingCbSample, &keyData);
// Content Encryption process
SecureContentCallbacks::ContentEncryptionCbData contentData;
contentData.wrapper = &wrapper;
writer->SetContentEncryptionCallback(SecureContentCallbacks::WriteContentEncryptionCbSample, &contentData);
// You'll need to complete the callback code for this call to work properly.
writer->WriteToFile("secureCube.3mf");
std::cout << "Writing Done." << std::endl;
}
void ReadSecureContentExample(CWrapper & wrapper) {
PModel model = wrapper.CreateModel();
// After initializing the model, set the random number generation callback
// A default one will be used if you don't, current implementation uses std::mt19937
model->SetRandomNumberCallback(SecureContentCallbacks::NotRandomBytesAtAll, nullptr);
// Query the reader and setup the encryption before saving results
PReader reader = model->QueryReader("3mf");
// Setup Key Wrapping process
SecureContentCallbacks::KeyWrappingCbData keyData;
keyData.wrapper = &wrapper;
reader->AddKeyWrappingCallback("MyConsumerID", SecureContentCallbacks::ReadKeyWrappingCbSample, &keyData);
// Content Encryption process
SecureContentCallbacks::ContentEncryptionCbData contentData;
contentData.wrapper = &wrapper;
reader->SetContentEncryptionCallback(SecureContentCallbacks::ReadContentEncryptionCbSample, &contentData);
// You'll need to complete the callback code for this call to work properly.
reader->ReadFromFile("secureCube.3mf");
PKeyStore keystore = model->GetKeyStore();
// If you know the part you're interested in, look for its resource data
PPackagePart partPath = model->FindOrCreatePackagePart("/3D/securecube.model");
PResourceData resourceData = keystore->FindResourceData(partPath.get());
// You can retrieve additional authenticated data using in the encryption
// to further verify the consistency of the process. At this time, it is
// already verified.
std::vector<Lib3MF_uint8> aad;
resourceData->GetAdditionalAuthenticationData(aad);
std::cout << "Additional Authenticated Data: ";
for (auto it = aad.begin(); it != aad.end(); ++it) {
std::cout << (char)*it;
}
std::cout << std::endl;
std::cout << "Reading Done." << std::endl;
}
int main() {
PWrapper wrapper = CWrapper::loadLibrary();
std::cout << "------------------------------------------------------------------" << std::endl;
std::cout << "3MF SecureContent example" << std::endl;
printVersion(*wrapper);
std::cout << "------------------------------------------------------------------" << std::endl;
try {
WriteSecureContentExample(*wrapper);
ReadSecureContentExample(*wrapper);
} catch (ELib3MFException &e) {
std::cout << e.what() << std::endl;
return e.getErrorCode();
}
return 0;
}
| 38.891393 | 155 | 0.734918 | [
"mesh",
"vector",
"model",
"3d"
] |
de9aeeff303bee2aace539b92f07a39f4a3bdac5 | 5,682 | cpp | C++ | src/atomdata.cpp | MarcoPolimeni/faunus | 87fc4638c4bec68314f34ec251ea034fc0427515 | [
"MIT"
] | null | null | null | src/atomdata.cpp | MarcoPolimeni/faunus | 87fc4638c4bec68314f34ec251ea034fc0427515 | [
"MIT"
] | null | null | null | src/atomdata.cpp | MarcoPolimeni/faunus | 87fc4638c4bec68314f34ec251ea034fc0427515 | [
"MIT"
] | null | null | null | #include <spdlog/spdlog.h>
#include "atomdata.h"
#include "units.h"
#include "aux/eigensupport.h"
namespace Faunus {
AtomData::Tid &AtomData::id() { return _id; }
const AtomData::Tid &AtomData::id() const { return _id; }
void AtomData::setProperty(const TPropertyName name, const double value) {
property[name] = value;
// an ugly temporal hack needed until the refactorization is finished
// as sigma is unfortunately accessed in loops
if (name == "sigma") {
sigma = 1.0_angstrom * value;
}
}
double AtomData::getProperty(const TPropertyName name) const {
try {
return property.at(name);
} catch (const std::out_of_range &e) {
faunus_logger->error("Unknown property {} of atom {}", name, this->name);
// cannot throw until non-used atomic pairs are eliminated from the potential matrices
// throw std::runtime_error("unknown atom property");
return std::numeric_limits<double>::signaling_NaN();
}
}
double &AtomData::getProperty(const TPropertyName name) {
if(property.count(name) == 0) {
setProperty(name, std::numeric_limits<double>::signaling_NaN());
}
return property.at(name);
}
void to_json(json &j, const AtomData &a) {
auto &_j = j[a.name];
_j = {{"activity", a.activity / 1.0_molar},
{"pactivity", -std::log10(a.activity / 1.0_molar)},
{"alphax", a.alphax},
{"mw", a.mw},
{"q", a.charge},
{"dp", a.dp / 1.0_angstrom},
{"dprot", a.dprot / 1.0_rad},
{"tension", a.tension * 1.0_angstrom * 1.0_angstrom / 1.0_kJmol},
{"tfe", a.tfe * 1.0_angstrom * 1.0_angstrom * 1.0_molar / 1.0_kJmol},
{"mu", a.mu},
{"mulen", a.mulen},
{"scdir", a.scdir},
{"sclen", a.sclen},
{"id", a.id()}};
for (const auto &property : a.property) {
_j[property.first] = property.second;
}
if (a.hydrophobic)
_j["hydrophobic"] = a.hydrophobic;
if (a.implicit)
_j["implicit"] = a.implicit;
}
void from_json(const json &j, AtomData &a) {
if (j.is_object() == false || j.size() != 1)
throw std::runtime_error("Invalid JSON data for AtomData");
for (auto atom_iter : j.items()) {
a.name = atom_iter.key();
SingleUseJSON val = atom_iter.value();
a.alphax = val.value("alphax", a.alphax);
a.charge = val.value("q", a.charge);
a.dp = val.value("dp", a.dp) * 1.0_angstrom;
a.dprot = val.value("dprot", a.dprot) * 1.0_rad;
a.id() = val.value("id", a.id());
a.mu = val.value("mu", a.mu);
a.mulen = val.value("mulen", a.mulen);
if (a.mu.norm() > 1e-6) { // if mu is given...
if (std::fabs(a.mulen) < 1e-6) // if mulen is not given ...
a.mulen = a.mu.norm(); // ... then set mulen
a.mu = a.mu / a.mu.norm(); // normalize mu
}
a.scdir = val.value("scdir", a.scdir);
a.sclen = val.value("sclen", a.sclen);
a.mw = val.value("mw", a.mw);
a.tension = val.value("tension", a.tension) * 1.0_kJmol / (1.0_angstrom * 1.0_angstrom);
a.tfe = val.value("tfe", a.tfe) * 1.0_kJmol / (1.0_angstrom * 1.0_angstrom * 1.0_molar);
a.hydrophobic = val.value("hydrophobic", false);
a.implicit = val.value("implicit", false);
if (val.count("activity") == 1)
a.activity = val.at("activity").get<double>() * 1.0_molar;
if (val.count("pactivity") == 1) {
if (val.count("activity") == 1) {
throw std::runtime_error("Specify either activity or pactivity for atom '"s + a.name + "'!");
}
a.activity = std::pow(10, -val.at("pactivity").get<double>()) * 1.0_molar;
}
if (val.count("r") == 1) {
faunus_logger->warn("Atom property `r` is obsolete; use `sigma = 2*r` instead on atom {}", a.name);
}
a.setProperty("sigma", val.value("sigma", 0.0) * 1.0_angstrom);
if (fabs(a.getProperty("sigma")) < 1e-20)
a.setProperty("sigma", 2.0 * val.value("r", 0.0) * 1.0_angstrom);
json j_remaining_properties = val;
for (auto &property_iter : j_remaining_properties.items()) {
if (property_iter.value().is_number()) {
a.setProperty(property_iter.key(), property_iter.value());
} else {
throw std::runtime_error("unused key(s) for atom '"s + a.name + "':\n" + property_iter.key() +
usageTip["atomlist"]);
}
}
}
}
void from_json(const json &j, std::vector<AtomData> &v) {
auto j_list_iter = j.find("atomlist");
auto j_list = (j_list_iter == j.end()) ? j : *j_list_iter;
v.reserve(v.size() + j_list.size());
for (auto &j_atom : j_list) {
if (j_atom.is_string()) // treat ax external file to load
from_json(openjson(j_atom.get<std::string>()), v);
else if (j_atom.is_object()) {
AtomData a = j_atom;
auto atom_iter = findName(v, a.name);
if (atom_iter == v.end()) {
v.push_back(a); // add new atom
} else {
faunus_logger->warn("Redefining atomic properties of atom {}.", atom_iter->name);
*atom_iter = a;
}
}
}
for (size_t i = 0; i < v.size(); i++) {
if (std::numeric_limits<AtomData::Tid>::max() < i) {
throw std::overflow_error("Number of atoms to high.");
}
v[i].id() = i; // id must match position in vector
}
}
std::vector<AtomData> atoms;
} // namespace Faunus
| 38.917808 | 111 | 0.548574 | [
"vector"
] |
de9d0faed6547f4b149ebabdfd0b0ef993b71306 | 5,682 | cc | C++ | src/foreign_if/server/expose_wrapper.cc | XpressAI/frovedis | bda0f2c688fb832671c5b542dd8df1c9657642ff | [
"BSD-2-Clause"
] | 63 | 2018-06-21T14:11:59.000Z | 2022-03-30T11:24:36.000Z | src/foreign_if/server/expose_wrapper.cc | XpressAI/frovedis | bda0f2c688fb832671c5b542dd8df1c9657642ff | [
"BSD-2-Clause"
] | 5 | 2018-09-22T14:01:53.000Z | 2021-12-27T16:11:05.000Z | src/foreign_if/server/expose_wrapper.cc | XpressAI/frovedis | bda0f2c688fb832671c5b542dd8df1c9657642ff | [
"BSD-2-Clause"
] | 12 | 2018-08-23T15:59:44.000Z | 2022-02-20T06:47:22.000Z | #include "exrpc_svd.hpp"
#include "exrpc_eigen.hpp"
#include "exrpc_pca.hpp"
#include "exrpc_tsne.hpp"
#include "exrpc_pblas.hpp"
#include "exrpc_scalapack.hpp"
#include "short_hand_dense_type.hpp"
#include "short_hand_sparse_type.hpp"
using namespace frovedis;
void expose_frovedis_wrapper_functions() {
// --- frovedis pca ---
expose((frovedis_pca<R_MAT1,DT1>)); // for spark + python
expose((frovedis_pca<R_MAT2,DT2>)); // for python
expose((frovedis_pca_transform<R_MAT2,R_LMAT2,DT2>));
expose((frovedis_pca_transform<R_MAT1,R_LMAT1,DT1>));
expose((frovedis_pca_inverse_transform<R_MAT2,R_LMAT2,DT2>));
expose((frovedis_pca_inverse_transform<R_MAT1,R_LMAT1,DT1>));
// --- frovedis svd ---
expose((compute_var_sum<DT1,R_MAT1>));
expose((compute_var_sum<DT2,R_MAT2>));
expose((frovedis_sparse_truncated_svd<S_MAT1,DT1>)); // for spark
expose((frovedis_sparse_truncated_svd<S_MAT14,DT1,DT4>)); // for python
expose((frovedis_sparse_truncated_svd<S_MAT15,DT1,DT5>)); // for python
expose((frovedis_sparse_truncated_svd<S_MAT24,DT2,DT4>)); // for python
expose((frovedis_sparse_truncated_svd<S_MAT25,DT2,DT5>)); // for python
expose((frovedis_dense_truncated_svd<R_MAT1,DT1>)); // for spark/python
expose((frovedis_dense_truncated_svd<R_MAT2,DT2>)); // for python
// --- for fit_transform ---
expose(frovedis_svd_self_transform<DT1>); // for python (spark: to be added)
expose(frovedis_svd_self_transform<DT2>); // for python
// --- for transform ---
expose((frovedis_svd_transform<R_MAT1,DT1>)); // for python (spark: to be added)
expose((frovedis_svd_transform<R_MAT2,DT2>)); // for python
expose((frovedis_svd_transform<S_MAT14,DT1>)); // for python
expose((frovedis_svd_transform<S_MAT15,DT1>)); // for python (spark: to be added)
expose((frovedis_svd_transform<S_MAT24,DT2>)); // for python
expose((frovedis_svd_transform<S_MAT25,DT2>)); // for python
// --- for inverse_transform ---
expose((frovedis_svd_inv_transform<R_MAT1,DT1>)); // for python (spark: to be added)
expose((frovedis_svd_inv_transform<R_MAT2,DT2>)); // for python
expose((frovedis_svd_inv_transform<S_MAT14,DT1>)); // for python
expose((frovedis_svd_inv_transform<S_MAT15,DT1>)); // for python (spark: to be added)
expose((frovedis_svd_inv_transform<S_MAT24,DT2>)); // for python
expose((frovedis_svd_inv_transform<S_MAT25,DT2>)); // for python
expose(load_cmm_svd_results<DT1>); //GesvdResult (arpack/lapack)
expose(load_bcm_svd_results<DT1>); //PGesvdResult (scalapack)
expose(load_cmm_svd_results<DT2>); //GesvdResult (arpack/lapack)
expose(load_bcm_svd_results<DT2>); //PGesvdResult (scalapack)
// --- frovedis blas/pblas wrappers ---
expose((frovedis_swap<DT1,C_LMAT1>));
expose((frovedis_swap<DT1,B_MAT1>));
expose((frovedis_swap<DT2,B_MAT2>));
expose((frovedis_copy<DT1,C_LMAT1>));
expose((frovedis_copy<DT1,B_MAT1>));
expose((frovedis_copy<DT2,B_MAT2>));
//expose((frovedis_scal<DT1,C_LMAT1>));
expose((frovedis_scal<DT1,B_MAT1,B_LMAT1>));
expose((frovedis_scal<DT2,B_MAT2,B_LMAT2>));
expose((frovedis_axpy<DT1,C_LMAT1>));
expose((frovedis_axpy<DT1,B_MAT1>));
expose((frovedis_axpy<DT2,B_MAT2>));
expose((frovedis_dot<DT1,C_LMAT1>));
expose((frovedis_dot<DT1,B_MAT1>));
expose((frovedis_dot<DT2,B_MAT2>));
expose((frovedis_nrm2<DT1,C_LMAT1>));
expose((frovedis_nrm2<DT1,B_MAT1>));
expose((frovedis_nrm2<DT2,B_MAT2>));
expose((frovedis_gemv<DT1,C_LMAT1>));
expose((frovedis_gemv<DT1,B_MAT1>));
expose((frovedis_gemv<DT2,B_MAT2>));
expose((frovedis_ger<DT1,C_LMAT1>));
expose((frovedis_ger<DT1,B_MAT1>));
expose((frovedis_ger<DT2,B_MAT2>));
expose((frovedis_gemm<DT1,C_LMAT1>));
expose((frovedis_gemm<DT1,B_MAT1>));
expose((frovedis_gemm<DT2,B_MAT2>));
// blas doesn't have geadd()
expose((frovedis_geadd<DT1,B_MAT1>));
expose((frovedis_geadd<DT2,B_MAT2>));
// ------ frovedis arpack wrappers -----
expose((frovedis_sparse_eigsh<S_MAT1,DT1>)); // for spark
expose((frovedis_sparse_eigsh<S_MAT14,DT1,DT4>)); // for python
expose((frovedis_sparse_eigsh<S_MAT15,DT1,DT5>)); // for python
expose((frovedis_sparse_eigsh<S_MAT24,DT2,DT4>)); // for python
expose((frovedis_sparse_eigsh<S_MAT25,DT2,DT5>)); // for python
expose((frovedis_dense_eigsh<R_MAT1,DT1>)); // for spark/python
expose((frovedis_dense_eigsh<R_MAT2,DT2>)); // for python
// --- frovedis lapack/scalapack wrappers ---
expose((frovedis_getrf<DT1,C_LMAT1,std::vector<int>>));
expose((frovedis_getrf<DT1,B_MAT1,lvec<int>>));
expose((frovedis_getrf<DT2,B_MAT2,lvec<int>>));
expose((frovedis_getri<DT1,C_LMAT1,std::vector<int>>));
expose((frovedis_getri<DT1,B_MAT1,lvec<int>>));
expose((frovedis_getri<DT2,B_MAT2,lvec<int>>));
expose((frovedis_getrs<DT1,C_LMAT1,std::vector<int>>));
expose((frovedis_getrs<DT1,B_MAT1,lvec<int>>));
expose((frovedis_getrs<DT2,B_MAT2,lvec<int>>));
expose((frovedis_gesv<DT1,C_LMAT1,std::vector<int>>));
expose((frovedis_gesv<DT1,B_MAT1,lvec<int>>));
expose((frovedis_gesv<DT2,B_MAT2,lvec<int>>));
expose((frovedis_gels<DT1,C_LMAT1>));
expose((frovedis_gels<DT1,B_MAT1>));
expose((frovedis_gels<DT2,B_MAT2>));
expose((frovedis_gesvd<DT1,C_LMAT1>));
expose((frovedis_gesvd<DT1,B_MAT1>));
expose((frovedis_gesvd<DT2,B_MAT2>));
// --- frovedis tsne ---
expose((frovedis_tsne<R_MAT1,DT1>)); // for python
expose((frovedis_tsne<R_MAT2,DT2>)); // for python
}
| 50.283186 | 95 | 0.696234 | [
"vector",
"transform"
] |
deab8d4bc1751383f63d2ee93ef15137c72d8203 | 5,160 | hpp | C++ | include/codegen/include/UnityEngine/EventSystems/PhysicsRaycaster.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 1 | 2021-11-12T09:29:31.000Z | 2021-11-12T09:29:31.000Z | include/codegen/include/UnityEngine/EventSystems/PhysicsRaycaster.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | null | null | null | include/codegen/include/UnityEngine/EventSystems/PhysicsRaycaster.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 2 | 2021-10-03T02:14:20.000Z | 2021-11-12T09:29:36.000Z | // Autogenerated from CppHeaderCreator on 7/27/2020 3:10:39 PM
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "utils/typedefs.h"
// Including type: UnityEngine.EventSystems.BaseRaycaster
#include "UnityEngine/EventSystems/BaseRaycaster.hpp"
// Including type: UnityEngine.LayerMask
#include "UnityEngine/LayerMask.hpp"
// Including type: System.Int32
#include "System/Int32.hpp"
#include "utils/il2cpp-utils.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: UnityEngine::EventSystems
namespace UnityEngine::EventSystems {
// Forward declaring type: PointerEventData
class PointerEventData;
}
// Forward declaring namespace: UnityEngine
namespace UnityEngine {
// Forward declaring type: Camera
class Camera;
// Forward declaring type: RaycastHit
struct RaycastHit;
// Forward declaring type: Ray
struct Ray;
}
// Forward declaring namespace: System::Collections::Generic
namespace System::Collections::Generic {
// Forward declaring type: List`1<T>
template<typename T>
class List_1;
}
// Completed forward declares
// Type namespace: UnityEngine.EventSystems
namespace UnityEngine::EventSystems {
// Autogenerated type: UnityEngine.EventSystems.PhysicsRaycaster
class PhysicsRaycaster : public UnityEngine::EventSystems::BaseRaycaster {
public:
// Nested type: UnityEngine::EventSystems::PhysicsRaycaster::RaycastHitComparer
class RaycastHitComparer;
// static field const value: static protected System.Int32 kNoEventMaskSet
static constexpr const int kNoEventMaskSet = -1;
// Get static field: static protected System.Int32 kNoEventMaskSet
static int _get_kNoEventMaskSet();
// Set static field: static protected System.Int32 kNoEventMaskSet
static void _set_kNoEventMaskSet(int value);
// protected UnityEngine.Camera m_EventCamera
// Offset: 0x20
UnityEngine::Camera* m_EventCamera;
// protected UnityEngine.LayerMask m_EventMask
// Offset: 0x28
UnityEngine::LayerMask m_EventMask;
// protected System.Int32 m_MaxRayIntersections
// Offset: 0x2C
int m_MaxRayIntersections;
// protected System.Int32 m_LastMaxRayIntersections
// Offset: 0x30
int m_LastMaxRayIntersections;
// private UnityEngine.RaycastHit[] m_Hits
// Offset: 0x38
::Array<UnityEngine::RaycastHit>* m_Hits;
// public System.Int32 get_depth()
// Offset: 0xDE80D8
int get_depth();
// public System.Int32 get_finalEventMask()
// Offset: 0xDE7F44
int get_finalEventMask();
// public UnityEngine.LayerMask get_eventMask()
// Offset: 0xDE8198
UnityEngine::LayerMask get_eventMask();
// public System.Void set_eventMask(UnityEngine.LayerMask value)
// Offset: 0xDE81A0
void set_eventMask(UnityEngine::LayerMask value);
// public System.Int32 get_maxRayIntersections()
// Offset: 0xDE81A8
int get_maxRayIntersections();
// public System.Void set_maxRayIntersections(System.Int32 value)
// Offset: 0xDE81B0
void set_maxRayIntersections(int value);
// protected System.Boolean ComputeRayAndDistance(UnityEngine.EventSystems.PointerEventData eventData, UnityEngine.Ray ray, System.Int32 eventDisplayIndex, System.Single distanceToClipPlane)
// Offset: 0xDE7BE8
bool ComputeRayAndDistance(UnityEngine::EventSystems::PointerEventData* eventData, UnityEngine::Ray& ray, int& eventDisplayIndex, float& distanceToClipPlane);
// protected System.Void .ctor()
// Offset: 0xDE7648
// Implemented from: UnityEngine.EventSystems.BaseRaycaster
// Base method: System.Void BaseRaycaster::.ctor()
// Base method: System.Void UIBehaviour::.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()
static PhysicsRaycaster* New_ctor();
// public override UnityEngine.Camera get_eventCamera()
// Offset: 0xDE8018
// Implemented from: UnityEngine.EventSystems.BaseRaycaster
// Base method: UnityEngine.Camera BaseRaycaster::get_eventCamera()
UnityEngine::Camera* get_eventCamera();
// public override System.Void Raycast(UnityEngine.EventSystems.PointerEventData eventData, System.Collections.Generic.List`1<UnityEngine.EventSystems.RaycastResult> resultAppendList)
// Offset: 0xDE81B8
// Implemented from: UnityEngine.EventSystems.BaseRaycaster
// Base method: System.Void BaseRaycaster::Raycast(UnityEngine.EventSystems.PointerEventData eventData, System.Collections.Generic.List`1<UnityEngine.EventSystems.RaycastResult> resultAppendList)
void Raycast(UnityEngine::EventSystems::PointerEventData* eventData, System::Collections::Generic::List_1<UnityEngine::EventSystems::RaycastResult>* resultAppendList);
}; // UnityEngine.EventSystems.PhysicsRaycaster
}
DEFINE_IL2CPP_ARG_TYPE(UnityEngine::EventSystems::PhysicsRaycaster*, "UnityEngine.EventSystems", "PhysicsRaycaster");
#pragma pack(pop)
| 46.071429 | 199 | 0.749225 | [
"object"
] |
deadfb4c6bcce04b0e368150a3eaf73f6df4c00f | 19,834 | hpp | C++ | deps/UMFLP/src/Functions.hpp | vOptSolver/vOptSpecific | 9705cf4fde20dfb14c7f7f6e32b7df1d597b383d | [
"MIT"
] | 5 | 2017-10-06T06:25:28.000Z | 2021-10-15T13:23:44.000Z | deps/UMFLP/src/Functions.hpp | vOptSolver/vOptSpecific | 9705cf4fde20dfb14c7f7f6e32b7df1d597b383d | [
"MIT"
] | 6 | 2018-02-09T17:14:20.000Z | 2021-07-24T14:10:09.000Z | deps/UMFLP/src/Functions.hpp | vOptSolver/vOptSpecific | 9705cf4fde20dfb14c7f7f6e32b7df1d597b383d | [
"MIT"
] | 4 | 2017-08-28T22:28:05.000Z | 2020-02-08T11:13:33.000Z | /*
#License and Copyright
#Version : 1.3
#This file is part of BiUFLv2017.
#BiUFLv2017 is Copyright © 2017, University of Nantes
#BiUFLv2017 is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
#This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#You should have received a copy of the GNU General Public License along with this program; if not, you can also find the GPL on the GNU web site.
#In addition, we kindly ask you to acknowledge BiUFLv2017 and its authors in any program or publication in which you use BiUFLv2017. (You are not required to do so; it is up to your common sense to decide whether you want to comply with this request or not.) For general publications, we suggest referencing: BiUFLv2017, MSc ORO, University of Nantes.
#Non-free versions of BiUFLv2017 are available under terms different from those of the General Public License. (e.g. they do not require you to accompany any object code using BiUFLv2012 with the corresponding source code.) For these alternative terms you must purchase a license from Technology Transfer Office of the University of Nantes. Users interested in such a license should contact us (valorisation@univ-nantes.fr) for more information.
*/
/*!
* \file Functions.hpp
* \brief A set of functions usefull for our software.
* \author Quentin DELMEE & Xavier GANDIBLEUX & Anthony PRZYBYLSKI
* \date 01 January 2017
* \version 1.3
* \copyright GNU General Public License
*
* This file groups all the functions for solving our problem which are not methods of Class.
*
*/
#ifndef FUNCTIONS_H
#define FUNCTIONS_H
#include <vector>
#include <map>
#include <list>
#include <iostream>
#include <cmath>
#include <time.h>
#include "Data.hpp"
#include "Box.hpp"
#include "Dualoc.hpp"
/*! \namespace std
*
* Using the standard namespace std of the IOstream library of C++.
*/
using namespace std;
/*!
* \defgroup paving Methods of Paving
*/
/*!
* \fn long int createBox(vector<Box*> &vectorBox, Data &data)
* \ingroup paving
* \brief This method computes all the initial \c Boxes of our algorithm.
*
* This method computes all the \c Boxes in whichones the Label Setting algorithm will runs. This method uses a smart Branch&Bound (Breadth First Search, splitting on facility setup variables) to compute all the feasible and important \c Boxes. Useless \c Boxes are avoided by the Branch&Bound.
* \param[in,out] vectorBox : A vector of \c Box, empty a the beginning, and containing all the \c Boxes at the end of this method.
* \param[in] openedFacility : A vector of string representing the boxes calculated if ImprovedUB mode is on.
* \param[in] data : A \c Data object which contains all the values of the instance.
* \return A long int which represents the number of \c Boxes computed by the method.
*/
long int createBox(vector<Box*> &vectorBox, vector<string> openedFacility, Data &data);
/*!
* \fn addChildren(Box *boxMother, vector<Box*> &vBox)
* \ingroup paving
* \brief This method adds children of a \c Box into a vector of \c Boxes.
*
* This method computes all the children \c Boxes of a \c Box into a vector of \c Boxes. A children is defined by a combination of facility in which indices have not yet been opened.
* \param[in] boxMother : A \c Box for which ones wants to add children \c Boxes.
* \param[in,out] vBox : A vector of \c Box in whichone ones add all the children \c Boxes at the end (enqueue at the end of the vector).
*/
void addChildren(Box *boxMother, vector<Box*> &vBox, Data &data);
/*!
* \fn computeUpperBound(vector<Box*> &vectorBox, vector<bool> &dichoSearch, Data &data)
* \ingroup paving
* \brief Compute the weighted sum method to calculate supported point of the problem.
*
* This method computes a weighted sum for all pair of point in the vector of \c Boxes. It updates the vector of boolean if the new points found are better w.r.t. the pair used. It correspond to one step of the dichotomich search.
* \param[in,out] vectorBox : A vector of \c Box in which we can find all current supported point of the problem that we calculated and where we will add the new points.
* \param[in,out] dichoSearch : A vector representing if it is interesting or not to apply a weighted sum between two points. When a new point is added to vectorBox, it is updated considering that a priori, the new pairs of points generated are interesting.
* \param[in] data : A \c Data object which contains all the values of the instance.
*/
void computeUpperBound(vector<Box*> &vectorBox, vector<bool> &dichoSearch, Data &data);
/*!
* \fn computeLowerBound(vector<Box*> &vectorBox, Data &data)
* \ingroup paving
* \brief Compute the weighted sum method to calculate supported point of the problem.
*
* This method computes a weighted sum for all pair of point in the vector of \c Boxes. It updates the vector of boolean if the new points found are better w.r.t. the pair used. It correspond to one step of the dichotomich search.
* \param[in,out] vectorBox : A vector of \c Box in which we can find all current supported point of the problem that we calculated and where we will add the new points.
* \param[in] data : A \c Data object which contains all the values of the instance.
*/
void computeLowerBound(Box *box, Data &data);
/*!
* \fn filter(vector<Box*> &vectorBox)
* \ingroup paving
* \brief This method filters all the \c Boxes of a vector of \c Box.
*
* This method filters \c Boxes by eliminating all \c Box that are dominated by an other one.
* \param[in,out] vectorBox : A vector of \c Boxes we need to filter.
*/
void filter(vector<Box*> &vectorBox);
/*!
* \defgroup resolution Methods of Resolution
*/
/*!
* \fn boxFiltering(vector<Box*> &vectorBox, Data &data)
* \ingroup resolution
* \brief This method filters all the \c Boxes of a vector of \c Box while computing their non-dominated points.
*
* One step of this method is to compute a weighted sum on all pair of point on all \c Boxes then to filter all the boxes with those new points. This methods repeat those two step as long as we have not calculated the non-dominated points of each \c Boxes.
* \param[in,out] vectorBox : A vector of \c Box in which we can find all current supported point of the problem that we calculated and where we will add the new points.
* \param[in] data : A \c Data object which contains all the values of the instance.
*/
void boxFiltering(vector<Box*> &vectorBox, Data &data);
/*!
* \fn weightedSumOneStep(Box* box, Data &data)
* \ingroup resolution
* \brief Compute the weighted sum on all pair of points of a \c Box.
*
* This method computes a weighted sum on all pair of point of a \c Box if the edge is not dominated.
* \param[in,out] box : A box in which we compute the weighted sum method on all pair of points.
* \param[in] data : A \c Data object which contains all the values of the instance.
*/
void weightedSumOneStep(Box* box, Data &data);
/*!
* \fn weightedSumOneStepLB(Box* box, Data &data)
* \ingroup resolution paving
* \brief Compute the weighted sum on all pair of points in the lower bound set of a \c Box.
*
* This method computes a weighted sum on all pair of point in the lower bound set of a \c Box if the corresponding lower bound edge is not dominated.
* \param[in,out] box : A box in which we compute the weighted sum method on all pair of points of the lower bound.
* \param[in] data : A \c Data object which contains all the values of the instance.
*/
void weightedSumOneStepLB(Box* box, Data &data);
/*!
* \fn weightedSumOneStepAll(vector<Box*> &vectorBox, Data &data)
* \ingroup resolution paving
* \brief Compute the weighted sum on all pair of points of all \c Boxes of a vector of \c Box.
*
* This method compute a weighted sum on all pair of point of all \c Boxes of a vector of \c Box if the corresponding edge is not already dominated.
* \param[in,out] vectorBox : A vector of \c Box in which, for all \c Boxes, we compute the weighted sum method on all pair of points.
* \param[in] data : A \c Data object which contains all the values of the instance.
* \param[in,out] MoreStep : A boolean which value is true that we will update to false if there is no more weighted sum to do on any \c Box in the vector.
*/
void weightedSumOneStepAll(vector<Box*> &vectorBox, Data &data, bool &MoreStep);
/*!
* \fn parametricSearch(Box* box, Data &data)
* \ingroup resolution
* \brief Compute the supported solution of the allocation subproblem defined by the \c Box
*
* This method computes the supported solution of the allocation subproblem defined by the set of facilities of this \c Box. This method uses a specific algorithm as proposed by Fernandez.
* \param[in,out] box : A box in which we compute the supported solutions.
* \param[in] data : A \c Data object which contains all the values of the instance.
*/
void parametricSearch(Box* box, Data &data);
/*!
* \fn parametricSearchUB(Box* box, Data &data)
* \ingroup resolution paving
* \brief Compute the supported solution of the allocation subproblem defined by the \c Box calculated in the Upper Bound Set.
*
* This method computes the supported solution of the allocation subproblem defined by the set of facilities of this \c Box. This method uses a specific algorithm as proposed by Fernandez. It is specifically defined for the \c Box obtained with the upper bound set.
* \param[in,out] box : A box in which we compute the supported solutions.
* \param[in] data : A \c Data object which contains all the values of the instance.
*/
void parametricSearchUB(Box* box, Data &data);
/*!
* \fn parametricSearchLB(Box* box, Data &data)
* \ingroup resolution paving
* \brief Computes the supported solution of the allocation subproblem defined by the \c Box and its potentially opened facilities
*
* This method computes the supported solution of the allocation subproblem defined by the set of facilities of this \c Box and the set of potentially opened facilities. This method uses a specific algorithm as proposed by Fernandez. The solutions obtained this way are a lower bound set for the current \c Box and all its children.
* \param[in,out] box : A box in which we compute the supported solutions of the lower bound set.
* \param[in] data : A \c Data object which contains all the values of the instance.
*/
void parametricSearchLB(Box* box, Data &data);
/*!
* \fn postProcessing(Box* box, Data &data)
* \ingroup resolution
* \brief Compute the allocation matrices of all client for \c Box box.
*
* This method computes the allocation matrices of all client for \c Box box for every point in the box.
* \param[in,out] box : A box in which we compute the allocation matrices solutions.
* \param[in] data : A \c Data object which contains all the values of the instance.
*/
void postProcessing(Box* box, Data &data);
/*!
* \fn isPointDominated(Box *box1, Box *box2)
* \ingroup resolution
* \brief Verifies if a point is dominated or not an other point.
*
* This methods compares the relative position of the two point and return if box1 is dominated by box2.
* \param[in] box1 : A \c Box which is a point.
* \param[in] box2 : A \c Box which is a point.
* \return A boolean which represents if box1 is dominated by box2.
*/
bool isPointDominated(Box *box1, Box *box2);
/*!
* \fn dominancePointEdge(Box *box1, Box *box2)
* \ingroup resolution
* \brief Verifies if a point is dominated or not an other point.
*
* This methods compares the relative position of the two point and return if box1 is dominated by box2.
* \param[in] box1 : A \c Box which is a point.
* \param[in] box2 : A \c Box composed of points and edges.
* \return An integer which represents if box1 is dominated by box2 or box2 is partially dominated by box1 or box2 is totally dominated by box1.
*/
int dominancePointEdge(Box *box1, Box *box2, Data &data);
/*!
* \fn dominanceEdgeEdge(Box *box1, Box *box2)
* \ingroup resolution
* \brief Verifies and Compares the dominance between all the edges of two \c Boxes.
*
* This methods compares all the edges of the two boxes to eliminates all dominated parts.
* \param[in] box1 : A \c Box composed of points and edges.
* \param[in] box2 : A \c Box composed of points and edges.
* \return An integer which represents if box1 is totally dominated by box2 or box2 is totally dominated by box1 or no box are totally dominated.
*/
int dominanceEdgeEdge(Box *box1, Box *box2, Data &data);
/*!
* \fn prefiltering(Box* box);
* \ingroup resolution
* \brief Filters the consecutive dominated edges of a \c Box.
*
* This method filters all consecutive edges of a \c Box by removing corresponding edges and points. It also verifies that no edges at the beggining or end of the box are dominated and if so, it eliminates them.
* \param[in,out] box : A \c Box in which we filter consecutive dominated edges.
*/
void prefiltering(Box* box, Data &data);
/*!
* \fn edgefiltering(vector<Box*> &vectorBox);
* \ingroup resolution
* \brief Filters the edges and points of all \c Boxes in the vector of \c Box.
*
* This method compares all boxes to each other and filter all dominated points and edges from those boxes. The resulting edges and points are all non-dominated thus we obtain the exact solution of the problem.
* \param[in,out] vectorBox : A vector of \c Boxes which will be filtered.
*/
void edgefiltering(vector<Box*> &vectorBox, Data &data);
/*!
* \defgroup others Others Methods
*/
/*!
* \fn computeCorrelation(Data &data)
* \ingroup others
* \brief This method computes the correlation.
*
* This method computes the correlation between the two objectives w.r.t. to the \c Data.
* \param[in] data : A \c Data object which contains all the values of the instance.
* \return A double representing the correlation between the two objectives.
*/
double computeCorrelation(Data &data);
/*!
* \fn quicksortedge(vector<Box*> &toSort, int begin, int end)
* \ingroup others
* \brief Sorts all the box considering their first point.
*
* This method lexicographically sorts all the box considering their first point. It allows us some assumption we use in the filtering of boxes and edges.
* \param[in,out] vectorBox : A vector of \c Box that will be sorted.
* \param[in] begin : An integer which represent where we begin the sort.
* \param[in] end : An integer which represent where we end the sort.
*/
void quicksortedge(vector<Box*> &toSort, int begin, int end);
/*!
* \fn quicksortCusto(vector<Box*> &toSort, int begin, int end)
* \ingroup others
* \brief Sorts all the facilities considering the preference of a customer.
*
* This method lexicographically sorts all the facilities considering the preference of a customer. It allows the algorithm to speed up the research of prefered facilities from customer.
* \param[in,out] toHelp : A vector of double with the affilition cost of one objective to help sort the facilities.
* \param[in,out] lexHelp : A vector of double with the affiliation cost of the other objective to help sort the facilities.
* \param[in,out] toSort : A vector of int corresponding to the order of facilities.
* \param[in] begin : An integer which represent where we begin the sort.
* \param[in] end : An integer which represent where we end the sort.
*/
void quicksortCusto(vector<double> &toHelp, vector<double> &lexHelp, vector<int> &toSort, int begin, int end);
/*!
* \fn quicksortFacility(vector<Box*> &toSort, int begin, int end)
* \ingroup others
* \brief Sorts all the facilities considering their interest value.
*
* This method sorts all the facilities considering an interest value we heuristically choosed. It could be further improved with better and cleverer interest value.
* \param[in,out] toSort: A vector of int representing the order of the facilities.
* \param[in] begin : An integer which represent where we begin the sort.
* \param[in] end : An integer which represent where we end the sort.
*/
void quicksortFacility(vector<double> &toSort, int begin, int end);
/*!
* \fn isAlreadyIn(vector<string> openedFacility, Box* box)
* \ingroup others
* \brief Verifies if a \c Box has already been opened with the upper bound set.
*
* This method verifies in the vector of string if a \c Box has already been computed while computing the upper bound set. If it has been computed, its ID will be found in the vector of string.
* \param[in] openedFacility : A vector of string which represent all the IDs of box already opened during the computation of the upper bound set.
* \param[in] box : A \c Box we verify the presence in the vector of string.
*/
bool isAlreadyIn(vector<string> openedFacility, Box* box);
/*!
* \fn sortFacility(Data &data, vector<double> clientfacilitycost1,vector<double> clientfacilitycost2)
* \ingroup others
* \brief Computes the interest value of each facility.
*
* This method computes the interest value of all facility so we can sort them later by increasing value.
* \param[in] data : A \c Data object which contains all the values of the instance.
* \param[in] clientfacilitycost1 : A vector of double which represent the total cost of assigning all client to one facility w.r.t. first objective.
* \param[in] clientfacilitycost2 : A vector of double which represent the total cost of assigning all client to one facility w.r.t. second objective.
*/
void sortFacility(Data &data, vector<double> clientfacilitycost1,vector<double> clientfacilitycost2);
/*!
* \fn crono_start(timeval &start_utime)
* \ingroup others
* \brief Initialize the timeval at current starting time.
*
* This method update the timeval with current time.
* \param[in] start_utime : A timeval we want to initialize at starting time.
*/
void crono_start(clock_t &start_utime);
/*!
* \fn crono_stop(timeval &stop_utime)
* \ingroup others
* \brief Initialize the timeval at current stoping time.
*
* This method update the timeval with current time.
* \param[in] stop_utime : A timeval we want to initialize at stoping time.
*/
void crono_stop(clock_t &stop_utime);
/*!
* \fn crono_ms(timeval start_utime, timeval stop_utime)
* \ingroup others
* \brief Computes the difference in milliseconds between starting and stoping time.
*
* This method computes the differences in milliseconds between the starting time and stoping time and return the result.
* \param[in] start_utime : A timeval with the value of starting time.
* \param[in] stop_utime : A timeval with the value of stoping time.
* \return a double which represent the difference between starting and stoping time in milliseconds.
*/
double crono_ms(clock_t start_utime, clock_t stop_utime);
/*!
* \fn quicksortFacilityOBJ1(vector<Box*> &toSort, int begin, int end)
* \ingroup others
* \brief Sorts all the facilities considering the objective 1.
*
* This method sorts all the facilities considering their objective 1 value.
* \param[in,out] toSort: A vector of double representing the cost of the facilities.
* \param[in] begin : An integer which represent where we begin the sort.
* \param[in] end : An integer which represent where we end the sort.
*/
void quicksortFacilityOBJ1(vector<double> &toSort, int begin, int end);
/*!
* \fn quicksortFacilityOBJ2(vector<Box*> &toSort, int begin, int end)
* \ingroup others
* \brief Sorts all the facilities considering the objective 2.
*
* This method sorts all the facilities considering their objective 2 value.
* \param[in,out] toSort: A vector of double representing the cost of the facilities.
* \param[in] begin : An integer which represent where we begin the sort.
* \param[in] end : An integer which represent where we end the sort.
*/
void quicksortFacilityOBJ2(vector<double> &toSort, int begin, int end);
#endif
| 49.959698 | 446 | 0.752647 | [
"object",
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.