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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2d8284d4ee4c71fd58d708c2e26a4193c19f450f | 1,637 | cpp | C++ | src/data/Frames.cpp | PacificBiosciences/pbcopper | ba98ddd79371c2218ca5110d07d5f881c995ff93 | [
"BSD-3-Clause-Clear"
] | 5 | 2018-01-15T13:40:30.000Z | 2021-01-19T18:28:30.000Z | src/data/Frames.cpp | PacificBiosciences/pbcopper | ba98ddd79371c2218ca5110d07d5f881c995ff93 | [
"BSD-3-Clause-Clear"
] | 4 | 2016-09-20T20:25:14.000Z | 2020-12-22T19:21:49.000Z | src/data/Frames.cpp | PacificBiosciences/pbcopper | ba98ddd79371c2218ca5110d07d5f881c995ff93 | [
"BSD-3-Clause-Clear"
] | 7 | 2017-05-15T08:47:02.000Z | 2021-04-28T18:38:09.000Z | #include <pbcopper/data/Frames.h>
#include <ostream>
#include <type_traits>
#include <boost/algorithm/string/join.hpp>
#include <boost/range/adaptor/transformed.hpp>
#include <pbcopper/data/FrameEncoders.h>
namespace PacBio {
namespace Data {
Frames::Frames(std::vector<uint16_t> frames) noexcept : std::vector<uint16_t>{std::move(frames)} {}
const std::vector<uint16_t>& Frames::Data() const { return *this; }
std::vector<uint16_t>& Frames::Data() { return *this; }
std::vector<uint16_t>& Frames::DataRaw() { return *this; }
Frames Frames::Decode(const std::vector<uint8_t>& codedData)
{
return Decode(codedData, V1FrameEncoder{});
}
std::vector<uint8_t> Frames::Encode(const std::vector<uint16_t>& frames)
{
return Encode(frames, V1FrameEncoder{});
}
std::vector<uint8_t> Frames::Encode(FrameCodec /*unused*/) const { return Encode(*this); }
Frames& Frames::Data(std::vector<uint16_t> frames)
{
*this = std::move(frames);
return *this;
}
bool Frames::operator==(const Frames& other) const noexcept
{
return static_cast<const std::vector<uint16_t>&>(*this) ==
static_cast<const std::vector<uint16_t>&>(other);
}
bool Frames::operator!=(const Frames& other) const noexcept { return !(*this == other); }
std::ostream& operator<<(std::ostream& os, const Frames& frames)
{
return os << "Frames("
<< boost::algorithm::join(frames | boost::adaptors::transformed(
[](uint16_t i) { return std::to_string(i); }),
", ")
<< ')';
}
} // namespace Data
} // namespace PacBio
| 27.745763 | 99 | 0.638363 | [
"vector"
] |
2d99e6cbcf9e45f35018087de34dc9746c9e3a9e | 1,797 | hpp | C++ | Activities/Menu.hpp | Derjik/Outpost | 93a419df75c1a17c1ffa30b0b9061bb3dfd7ce57 | [
"0BSD"
] | 1 | 2018-10-26T08:48:07.000Z | 2018-10-26T08:48:07.000Z | Activities/Menu.hpp | Derjik/Outpost | 93a419df75c1a17c1ffa30b0b9061bb3dfd7ce57 | [
"0BSD"
] | null | null | null | Activities/Menu.hpp | Derjik/Outpost | 93a419df75c1a17c1ffa30b0b9061bb3dfd7ce57 | [
"0BSD"
] | null | null | null | #ifndef MENU_HPP_INCLUDED
#define MENU_HPP_INCLUDED
#include "../GameContext.hpp"
#include <VBN/IModel.hpp>
#include <VBN/IView.hpp>
#include <VBN/IEventHandler.hpp>
#include <array>
#define NB_MENU_ENTRIES 5
class WindowManager;
namespace Menu
{
class Factory
{
public:
static std::shared_ptr<GameContext> createMenu(
std::shared_ptr<Platform> platform);
};
class Model : public IModel
{
public:
enum Item
{
APP_1,
APP_2,
APP_3,
APP_4,
EXIT
};
private:
std::array<Menu::Model::Item, NB_MENU_ENTRIES> _menuEntries;
unsigned int _currentSelection;
SDL_Color _backgroundColor;
SDL_Color _textColor;
SDL_Color _selectionColor;
bool _ascend;
public:
Model(void);
Item getCurrentSelection(void);
void setCurrentSelection(unsigned int const);
void cycleUp(void);
void cycleDown(void);
void cycleTo(Item const app);
SDL_Color getBackgroundColor(void);
SDL_Color getTextColor(void);
SDL_Color getSelectionColor(void);
void elapse(Uint32 const, std::shared_ptr<EngineUpdate>);
};
class View : public IView
{
private:
std::shared_ptr<Model> _model;
std::shared_ptr<Platform> _platform;
public:
View(std::shared_ptr<Platform> platform,
std::shared_ptr<Model> data);
void display(void);
};
class Controller : public IEventHandler
{
private:
std::shared_ptr<Platform> _platform;
std::shared_ptr<Model> _model;
void performAction(std::shared_ptr<EngineUpdate> engineUpdate);
void quickExit(std::shared_ptr<EngineUpdate> engineUpdate);
public:
Controller(std::shared_ptr<Platform> platform,
std::shared_ptr<Model> model);
void handleEvent(SDL_Event const & event,
std::shared_ptr<EngineUpdate> engineUpdate);
};
};
#endif // MENU_HPP_INCLUDED
| 20.895349 | 66 | 0.717307 | [
"model"
] |
2d9c8b4a99a9d323ee6d2044d236ea59783af966 | 11,835 | cpp | C++ | untitled1/main.cpp | Hramkanvas/needandnotneed | f28ef4a4be428370e2148883c06126f5be9ccd4e | [
"MIT"
] | 1 | 2019-12-28T13:57:09.000Z | 2019-12-28T13:57:09.000Z | untitled1/main.cpp | Hramkanvas/needandnotneed | f28ef4a4be428370e2148883c06126f5be9ccd4e | [
"MIT"
] | null | null | null | untitled1/main.cpp | Hramkanvas/needandnotneed | f28ef4a4be428370e2148883c06126f5be9ccd4e | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <fstream>
#include <string>
int vecNum;
class BinaryTree
{
public:
BinaryTree *leftArcPointer = nullptr;
BinaryTree *rightArcPointer = nullptr;
BinaryTree *parentNodePointer = nullptr;
int *key = nullptr;
int *b = nullptr;//number of pairwise different half-ways this node - ways from children
int *a = nullptr;//number of pairwise different half-ways this node - ways from parent
int *c = nullptr;//number of pairwise different half-ways this node = a + b
int *height = nullptr;
int *leafsOnHeight = nullptr;
int *MSL = nullptr;
void add(int, BinaryTree *);
};
void insideVectorFilling(BinaryTree *&, std::vector<int> &, int &);
void allProgram(BinaryTree *&);
void firstPart(BinaryTree *&, int &);
void secondPart(BinaryTree *&, int &, int &);
void setABC(BinaryTree *&, int &);
void setHeight_MSL_LOH(BinaryTree *&);
void straightLeftBypass(BinaryTree, std::vector<int> &);
void setTree(BinaryTree &, std::vector<int>);
std::vector<int> readTree(const std::string &);
void writeSLB(const std::string &, std::vector<int> &);
int getMinRight(BinaryTree *&);
void rightRemoval(BinaryTree *&, int);
int main()
{
auto *tree = new BinaryTree();
setTree(*tree, readTree("input.txt"));
allProgram(tree);
std::vector<int> result;
straightLeftBypass(*tree, result);
writeSLB("output.txt", result);
return 0;
}
void BinaryTree::add(int newKey, BinaryTree *parent)
{
if (this->key == nullptr)
{
this->parentNodePointer = parent;
this->key = new int(newKey);
} else if (newKey > *this->key)
{
if (this->rightArcPointer == nullptr)
{
this->rightArcPointer = new BinaryTree();
}
this->rightArcPointer->add(newKey, this);
} else if (newKey < *this->key)
{
if (this->leftArcPointer == nullptr)
{
this->leftArcPointer = new BinaryTree();
}
this->leftArcPointer->add(newKey, this);
}
}
void straightLeftBypass(BinaryTree tree, std::vector<int> &result)
{
result.push_back(*tree.key);
if (tree.leftArcPointer != nullptr)
{
straightLeftBypass(*tree.leftArcPointer, result);
}
if (tree.rightArcPointer != nullptr)
{
straightLeftBypass(*tree.rightArcPointer, result);
}
}
void setTree(BinaryTree &tree, std::vector<int> list)
{
for (auto &it : list)
{
tree.add(it, nullptr);
}
}
std::vector<int> readTree(const std::string &source)
{
std::ifstream in(source);
std::string str;
std::vector<int> result;
vecNum = 0;
if (in.is_open())
{
while (getline(in, str))
{
vecNum++;
}
result = std::vector<int>(static_cast<const unsigned int>(vecNum));
in.clear();
in.seekg(0, std::ios::beg);
auto it = result.begin();
getline(in, str);
getline(in, str);
while (getline(in, str))
{
*it = std::stoi(str);
++it;
}
}
in.close();
return result;
}
void writeSLB(const std::string &path, std::vector<int> &list)
{
std::ofstream out(path);
if (out.is_open())
{
for (auto &it : list)
{
out << it << std::endl;
}
}
out.close();
}
int getMinRight(BinaryTree *&tree)
{
if ((*tree).leftArcPointer == nullptr)
{
BinaryTree *temp = tree;
int newKey = *tree->key;
if ((*tree).rightArcPointer != nullptr)
{
(*tree).rightArcPointer->parentNodePointer = (*tree).parentNodePointer;
if ((*tree).parentNodePointer->leftArcPointer == tree)
{
(*tree).parentNodePointer->leftArcPointer = (*tree).rightArcPointer;
} else
{
(*tree).parentNodePointer->rightArcPointer = (*tree).rightArcPointer;
}
} else
{
if ((*tree).parentNodePointer->leftArcPointer == tree)
{
(*tree).parentNodePointer->leftArcPointer = nullptr;
} else
{
(*tree).parentNodePointer->rightArcPointer = nullptr;
}
}
delete temp;
temp = nullptr;
delete temp;
return newKey;
} else
{
return getMinRight((*tree).leftArcPointer);
}
}
void rightRemoval(BinaryTree *&tree, int key)
{
if (*(*tree).key == key)
{
BinaryTree *temp = tree;
if ((*tree).leftArcPointer == nullptr && (*tree).rightArcPointer == nullptr)
{
delete tree;
tree = nullptr;
delete tree;
} else if ((*tree).leftArcPointer == nullptr)
{
(*tree).rightArcPointer->parentNodePointer = (*tree).parentNodePointer;
if ((*tree).parentNodePointer != nullptr)
{
if ((*tree).parentNodePointer->leftArcPointer == tree)
{
(*tree).parentNodePointer->leftArcPointer = (*tree).rightArcPointer;
} else
{
(*tree).parentNodePointer->rightArcPointer = (*tree).rightArcPointer;
}
} else
{
tree = (*tree).rightArcPointer;
}
delete temp;
temp = nullptr;
delete temp;
} else if ((*tree).rightArcPointer == nullptr)
{
(*tree).leftArcPointer->parentNodePointer = (*tree).parentNodePointer;
if ((*tree).parentNodePointer != nullptr)
{
if ((*tree).parentNodePointer->leftArcPointer == tree)
{
((*tree).parentNodePointer)->leftArcPointer = (*tree).leftArcPointer;
} else
{
(*tree).parentNodePointer->rightArcPointer = (*tree).leftArcPointer;
}
} else
{
tree = (*tree).leftArcPointer;
}
delete temp;
temp = nullptr;
delete temp;
} else
{
*(*tree).key = getMinRight((*tree).rightArcPointer);
}
} else if (*(*tree).key > key && (*tree).leftArcPointer != nullptr)
{
rightRemoval((*tree).leftArcPointer, key);
} else if (*(*tree).key < key && (*tree).rightArcPointer != nullptr)
{
rightRemoval((*tree).rightArcPointer, key);
}
}
void firstPart(BinaryTree *&tree, int &MSLT)
{
if (tree->rightArcPointer != nullptr)
{
firstPart(tree->rightArcPointer, MSLT);
}
if (tree->leftArcPointer != nullptr)
{
firstPart(tree->leftArcPointer, MSLT);
}
setHeight_MSL_LOH(tree);
if (*(tree->MSL) > MSLT)
{
MSLT = *(tree->MSL);
}
}
void setHeight_MSL_LOH(BinaryTree *&tree)
{
if (tree->rightArcPointer != nullptr && tree->leftArcPointer != nullptr)
{
*(tree->height) =
*(tree->rightArcPointer->height) > *(tree->leftArcPointer->height) ? (*(tree->rightArcPointer->height) +
1) : (
*(tree->leftArcPointer->height) + 1);
//height is ready
*(tree->MSL) = *(tree->rightArcPointer->height) + *(tree->leftArcPointer->height) + 2;
//MSL is ready
if (*(tree->rightArcPointer->height) == *(tree->leftArcPointer->height))
{
*(tree->leafsOnHeight) = *(tree->rightArcPointer->leafsOnHeight) + *(tree->leftArcPointer->leafsOnHeight);
} else
{
*(tree->leafsOnHeight) =
*(tree->rightArcPointer->height) > *(tree->leftArcPointer->height)
? *(tree->rightArcPointer->leafsOnHeight) : *(tree->leftArcPointer->leafsOnHeight);
}//leafsOnHeight ready
} else if (tree->rightArcPointer != nullptr)
{
*(tree->height) = *(tree->rightArcPointer->height) + 1;
//height is ready
*(tree->MSL) = *(tree->rightArcPointer->height) + 1;
//MSL is ready
*(tree->leafsOnHeight) = *(tree->rightArcPointer->leafsOnHeight);
//leafsOnHeight ready
} else if (tree->leftArcPointer != nullptr)
{
*(tree->height) = *(tree->leftArcPointer->height) + 1;
//height is ready
*(tree->MSL) = *(tree->leftArcPointer->height) + 1;
//MSL is ready
*(tree->leafsOnHeight) = *(tree->leftArcPointer->leafsOnHeight);
//leafsOnHeight ready
} else
{
*(tree->height) = 0;
//height is ready
*(tree->MSL) = 0;
//MSL is ready
*(tree->leafsOnHeight) = 1;
}
}
void secondPart(BinaryTree *&tree, int &MPN, int &MSLT)
{
setABC(tree, MSLT);
if (MPN < *(tree->c))
{
MPN = *(tree->c);
}
if (tree->rightArcPointer != nullptr)
{
secondPart(tree->rightArcPointer, MPN, MSLT);
}
if (tree->leftArcPointer != nullptr)
{
secondPart(tree->leftArcPointer, MPN, MSLT);
}
}
void setABC(BinaryTree *&tree, int &MSLT)
{
if (*(tree->MSL) == MSLT)
{
if (tree->rightArcPointer != nullptr && tree->leftArcPointer != nullptr)
{
*(tree->b) = *(tree->rightArcPointer->leafsOnHeight) * *(tree->leftArcPointer->leafsOnHeight);
} else if (tree->rightArcPointer != nullptr)
{
*(tree->b) = *(tree->rightArcPointer->leafsOnHeight);
} else if (tree->leftArcPointer != nullptr)
{
*(tree->b) = *(tree->leftArcPointer->leafsOnHeight);
} else
{
*(tree->b) = 1;
}
} else
{
*(tree->b) = 0;
}//b completed
if (tree->parentNodePointer == nullptr)
{
*(tree->a) = 0;
}
if (tree->rightArcPointer != nullptr && tree->leftArcPointer != nullptr)
{
if (*(tree->leftArcPointer->height) == *(tree->rightArcPointer->height))
{
*(tree->leftArcPointer->a) =
*(tree->b) + *(tree->leftArcPointer->leafsOnHeight) * *(tree->a) / *(tree->leafsOnHeight);
*(tree->rightArcPointer->a) =
*(tree->b) + *(tree->rightArcPointer->leafsOnHeight) * *(tree->a) / *(tree->leafsOnHeight);
} else if (*(tree->leftArcPointer->height) > *(tree->rightArcPointer->height))
{
*(tree->leftArcPointer->a) = *(tree->a) + *(tree->b);
*(tree->rightArcPointer->a) = *(tree->b);
} else
{
*(tree->rightArcPointer->a) = *(tree->a) + *(tree->b);
*(tree->leftArcPointer->a) = *(tree->b);
}
} else if (tree->rightArcPointer != nullptr)
{
*(tree->rightArcPointer->a) = *(tree->a) + *(tree->b);
} else if (tree->leftArcPointer != nullptr)
{
*(tree->leftArcPointer->a) = *(tree->a) + *(tree->b);
}//a completed
*(tree->c) = *(tree->a) + *(tree->b);
//c completed
}
void allProgram(BinaryTree *&tree)
{
int MPN = 0;
int MSLT = 0;
std::vector<int> vector;
vector.reserve(static_cast<const unsigned int>(vecNum));
firstPart(tree, MSLT);
secondPart(tree, MPN, MSLT);
if (MPN % 2 == 0)
{
insideVectorFilling(tree, vector, MPN);
if(vector.size()%2 != 0)
{
rightRemoval(tree, vector[vector.size()/2]);
}
}
}
void insideVectorFilling(BinaryTree *&tree, std::vector<int> &vector, int &MPN)
{
if (tree->leftArcPointer != nullptr)
{
insideVectorFilling(tree->leftArcPointer, vector, MPN);
}
if (*(tree->c) == MPN)
{
vector.push_back(*(tree->key));
}
if (tree->rightArcPointer != nullptr)
{
insideVectorFilling(tree->rightArcPointer, vector, MPN);
}
} | 28.725728 | 120 | 0.537474 | [
"vector"
] |
2da23baeef79db58b32d0f72e90c052eada9ef6c | 4,451 | cpp | C++ | tx.cpp | majacQ/cpu-load-side-channel | 3290c42cec1ee5049dc3dfea9b4d26a306dc55f9 | [
"MIT"
] | 44 | 2021-05-30T19:30:42.000Z | 2021-11-10T12:54:20.000Z | tx.cpp | majacQ/cpu-load-side-channel | 3290c42cec1ee5049dc3dfea9b4d26a306dc55f9 | [
"MIT"
] | null | null | null | tx.cpp | majacQ/cpu-load-side-channel | 3290c42cec1ee5049dc3dfea9b4d26a306dc55f9 | [
"MIT"
] | 3 | 2021-05-31T14:22:53.000Z | 2021-06-02T05:05:22.000Z | /// Pavel Kirienko <pavel@uavcan.org>
/// Distributed under the terms of the MIT license.
/// g++ -std=c++17 -O2 -Wall tx.cpp -lpthread -o tx && ./tx
#include "side_channel_params.hpp"
#include <cstdio>
#include <iostream>
#include <fstream>
#include <iterator>
#include <thread>
#include <vector>
#include <atomic>
#include <cassert>
#include <stdexcept>
static void drivePHY(const bool level, const std::chrono::nanoseconds duration)
{
// Use delta relative to fixed state to avoid accumulation of phase error, because phase error attenuates the
// useful signal at the receiver.
static auto deadline = std::chrono::steady_clock::now();
deadline += duration;
if (level)
{
std::atomic<bool> finish = false;
const auto loop = [&finish]() {
while (!finish)
{
// This busyloop is only needed to generate dummy CPU load between possibly contentious checks.
volatile std::uint16_t i = 1;
while (i != 0)
{
i = i + 1U;
}
}
};
static const auto thread_count = std::max<unsigned>(1, std::min<unsigned>(MAX_CONCURRENCY,
std::thread::hardware_concurrency()));
std::vector<std::thread> pool;
assert(thread_count > 0);
for (auto i = 0U; i < (thread_count - 1); i++)
{
pool.emplace_back(loop);
}
while (std::chrono::steady_clock::now() < deadline)
{
volatile std::uint16_t i = 1; // Dummy load in case now() is blocking.
while (i != 0)
{
i = i + 1U;
}
}
finish = true;
for (auto& t : pool)
{
t.join();
}
}
else
{
std::this_thread::sleep_for(deadline - std::chrono::steady_clock::now());
}
}
static void emitBit(const bool value)
{
using side_channel::params::ChipPeriod;
using side_channel::params::CDMACode;
for (auto i = 0U; i < CDMACode.size(); i++)
{
const bool code_position = CDMACode[i];
const bool bit = value ? code_position : !code_position;
drivePHY(bit, ChipPeriod);
}
}
/// Each byte is preceded by a single high start bit.
static void emitByte(const std::uint8_t data)
{
auto i = sizeof(data) * 8U;
std::printf("byte 0x%02x\n", data);
emitBit(1); // START BIT
while (i --> 0)
{
const bool bit = (static_cast<std::uintmax_t>(data) & (1ULL << i)) != 0U;
emitBit(bit);
}
}
/// The delimiter shall be at least 9 zero bits long (longer is ok).
/// Longer delimiter allows the reciever to find correlation before the data transmission is started.
static void emitFrameDelimiter()
{
std::printf("delimiter\n");
for (auto i = 0U; i < 20; i++)
{
emitBit(0);
}
}
static void emitPacket(const std::vector<std::uint8_t>& data)
{
emitFrameDelimiter();
std::uint16_t crc = side_channel::CRCInitial;
for (std::uint8_t v : data)
{
emitByte(v);
crc = side_channel::crcAdd(crc, v);
}
emitByte(static_cast<std::uint8_t>(crc >> 8U));
emitByte(static_cast<std::uint8_t>(crc >> 0U));
emitFrameDelimiter();
}
static std::vector<std::uint8_t> readFile(const std::string& path)
{
std::ifstream ifs(path, std::ios::binary);
if (ifs)
{
ifs.unsetf(std::ios::skipws);
ifs.seekg(0, std::ios::end);
std::vector<std::uint8_t> buf;
buf.reserve(ifs.tellg());
ifs.seekg(0, std::ios::beg);
buf.insert(buf.begin(), std::istream_iterator<std::uint8_t>(ifs), std::istream_iterator<std::uint8_t>());
return buf;
}
throw std::logic_error("Cannot read file " + path);
}
int main(const int argc, const char* const argv[])
{
std::cout << "SPREAD CODE LENGTH: " << side_channel::params::CDMACodeLength << " bit" << std::endl;
std::cout << "SPREAD CHIP PERIOD: " << side_channel::params::ChipPeriod.count() * 1e-6 << " ms" << std::endl;
if (argc < 2)
{
std::cerr << "Usage:\n\t" << argv[0] << " <file>" << std::endl;
return 1;
}
side_channel::initThread();
const auto data = readFile(argv[1]);
std::cerr << "Transmitting " << data.size() << " bytes read from " << argv[1] << std::endl;
emitPacket(data);
return 0;
}
| 30.486301 | 120 | 0.56639 | [
"vector"
] |
2da38a17b81d5993f5264d21fa70a9b47494076b | 11,233 | cpp | C++ | ext/include/osgEarthSymbology/MarkerSymbolizer.cpp | energonQuest/dtEarth | 47b04bb272ec8781702dea46f5ee9a03d4a22196 | [
"MIT"
] | 6 | 2015-09-26T15:33:41.000Z | 2021-06-13T13:21:50.000Z | ext/include/osgEarthSymbology/MarkerSymbolizer.cpp | energonQuest/dtEarth | 47b04bb272ec8781702dea46f5ee9a03d4a22196 | [
"MIT"
] | null | null | null | ext/include/osgEarthSymbology/MarkerSymbolizer.cpp | energonQuest/dtEarth | 47b04bb272ec8781702dea46f5ee9a03d4a22196 | [
"MIT"
] | 5 | 2015-05-04T09:02:23.000Z | 2019-06-17T11:34:12.000Z | /* -*-c++-*- */
/* osgEarth - Dynamic map generation toolkit for OpenSceneGraph
* Copyright 2008-2010 Pelican Mapping
* http://osgearth.org
*
* osgEarth is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
#include <osgEarthSymbology/MarkerSymbolizer>
#include <osgEarthSymbology/MarkerSymbol>
#include <osgDB/ReadFile>
#include <osgDB/ReaderWriter>
#include <osg/Geometry>
#include <osg/MatrixTransform>
#include <osg/Material>
#include <osg/Geode>
#include <osg/Version>
using namespace osgEarth::Symbology;
static osg::Node* getNode(const std::string& str)
{
#if OSG_VERSION_LESS_THAN(2,9,8)
osg::ref_ptr<osgDB::ReaderWriter::Options> options = new osgDB::ReaderWriter::Options;
options->setObjectCacheHint(osgDB::ReaderWriter::Options::CACHE_ALL);
osg::Node* node = osgDB::readNodeFile(str, options.get());
return node;
#else
osg::ref_ptr<osgDB::Options> options = new osgDB::Options;
options->setObjectCacheHint(osgDB::Options::CACHE_ALL);
osg::Node* node = osgDB::readNodeFile(str, options.get());
return node;
#endif
}
static double getRandomValueInRange(double value)
{
return (-value/2) + ((rand() * value)/(RAND_MAX-1));
}
MarkerSymbolizer::MarkerSymbolizer()
{
}
bool MarkerSymbolizer::pointInPolygon(const osg::Vec3d& point, osg::Vec3dArray* pointList)
{
if (!pointList)
return false;
bool result = false;
const osg::Vec3dArray& polygon = *pointList;
for( unsigned int i=0, j=polygon.size()-1; i<polygon.size(); j = i++ )
{
if ((((polygon[i].y() <= point.y()) && (point.y() < polygon[j].y())) ||
((polygon[j].y() <= point.y()) && (point.y() < polygon[i].y()))) &&
(point.x() < (polygon[j].x()-polygon[i].x()) * (point.y()-polygon[i].y())/(polygon[j].y()-polygon[i].y())+polygon[i].x()))
{
result = !result;
}
}
return result;
}
bool
MarkerSymbolizer::compile(MarkerSymbolizerState* state,
osg::Group* attachPoint)
{
if ( !state || !attachPoint || !state->getContent() || !state->getStyle() )
return false;
osg::ref_ptr<osg::Group> newSymbolized = new osg::Group;
const GeometryList& geometryList = state->getContent()->getGeometryList();
for (GeometryList::const_iterator it = geometryList.begin(); it != geometryList.end(); ++it)
{
Geometry* geometry = *it;
if (!geometry)
continue;
GeometryIterator geomIterator( geometry );
geomIterator.traverseMultiGeometry() = true;
geomIterator.traversePolygonHoles() = true;
while( geomIterator.hasMore() )
{
Geometry* part = geomIterator.next();
if (!part)
continue;
switch( part->getType())
{
case Geometry::TYPE_POINTSET:
{
const MarkerSymbol* point = state->getStyle()->getSymbol<MarkerSymbol>();
if (point)
{
if (point && part->size() && !point->marker().value().empty())
{
osg::Node* node = getNode(point->marker().value());
if (!node) {
osg::notify(osg::WARN) << "can't load Marker Node " << point->marker().value() << std::endl;
continue;
}
osg::Group* group = new osg::Group;
for ( osg::Vec3dArray::iterator it = part->begin(); it != part->end(); ++it)
{
osg::Vec3d pos = *it;
osg::MatrixTransform* tr = new osg::MatrixTransform;
tr->setMatrix(osg::Matrix::translate(pos));
tr->addChild(node);
group->addChild(tr);
}
newSymbolized->addChild(group);
}
}
}
break;
case Geometry::TYPE_LINESTRING:
case Geometry::TYPE_RING:
{
const MarkerLineSymbol* line = state->getStyle()->getSymbol<MarkerLineSymbol>();
if (line)
{
if (line && part->size() && !line->marker().value().empty())
{
osg::Node* node = getNode(line->marker().value());
if (!node) {
osg::notify(osg::WARN) << "can't load Marker Node " << line->marker().value() << std::endl;
continue;
}
float interval = line->interval().value();
if (!interval)
interval = 1.0;
osg::Group* group = new osg::Group;
float currentDist = 0;
// start to put one first node
{
osg::MatrixTransform* tr = new osg::MatrixTransform;
tr->setMatrix(osg::Matrix::translate(*part->begin()));
tr->addChild(node);
group->addChild(tr);
}
for ( unsigned int i = 0; i < part->size(); ++i)
{
osg::Vec3d start = (*part)[i];
osg::Vec3d end;
if (i < (part->size() - 1)) {
end = (*part)[i+1];
} else {
if (part->getType() == Geometry::TYPE_RING) {
end = (*part)[0];
} else {
end = start;
}
}
osg::Vec3d direction = end - start;
float segmentSize = direction.length();
direction.normalize();
float previousDist = currentDist;
currentDist += segmentSize;
if (currentDist < interval)
continue;
float offset = interval - previousDist;
float rate = currentDist / interval;
int nbItems = static_cast<int>(floorf(rate));
rate -= (float)nbItems;
float remaining = rate * interval;
currentDist = remaining;
osg::Vec3d startOnTheLine = start + direction * offset;
for (int j = 0; j < nbItems; ++j)
{
osg::MatrixTransform* tr = new osg::MatrixTransform;
tr->setMatrix(osg::Matrix::translate(startOnTheLine + direction*j*interval));
tr->addChild(node);
group->addChild(tr);
}
}
newSymbolized->addChild(group);
}
}
}
break;
case Geometry::TYPE_POLYGON:
{
const MarkerPolygonSymbol* poly = state->getStyle()->getSymbol<MarkerPolygonSymbol>();
if (poly)
{
if (poly && part->size() && !poly->marker().value().empty())
{
osg::Node* node = getNode(poly->marker().value());
if (!node) {
osg::notify(osg::WARN) << "can't load Marker Node " << poly->marker().value() << std::endl;
continue;
}
float interval = poly->interval().value();
if (!interval)
interval = 1.0;
float randomRatio = poly->randomRatio().value();
osg::Group* group = new osg::Group;
osg::BoundingBox bb;
for (osg::Vec3dArray::iterator it = part->begin(); it != part->end(); ++it)
{
bb.expandBy(*it);
}
// use a grid on x and y
osg::Vec3d startOnGrid = bb.corner(0);
float sizex = bb.xMax() - bb.xMin();
float sizey = bb.yMax() - bb.yMin();
int numX = static_cast<int>(floorf(sizex / interval));
int numY = static_cast<int>(floorf(sizey / interval));
for (int y = 0; y < numY; ++y)
{
for (int x = 0; x < numX; ++x)
{
// get two random number in interval
osg::Vec3d randOffset(0, 0, 0);
randOffset = osg::Vec3d(getRandomValueInRange(1.0), getRandomValueInRange(1.0), 0);
if (randOffset.length2() > 0.0)
randOffset.normalize();
randOffset *= ( getRandomValueInRange( interval) ) * randomRatio;
osg::Vec3d point = startOnGrid + randOffset + osg::Vec3d(x*interval, y*interval, 0);
if (pointInPolygon(point, part))
{
osg::MatrixTransform* tr = new osg::MatrixTransform;
tr->setMatrix(osg::Matrix::translate(point));
tr->addChild(node);
group->addChild(tr);
}
}
}
newSymbolized->addChild(group);
}
}
}
break;
default:
break;
}
}
}
if (newSymbolized->getNumChildren())
{
attachPoint->removeChildren(0, attachPoint->getNumChildren());
attachPoint->addChild(newSymbolized.get());
return true;
}
return false;
}
| 39.975089 | 134 | 0.442624 | [
"geometry"
] |
2dbbb1d06aae427bac492a6e7f2b87da826b57eb | 4,285 | cpp | C++ | src/ui/screens/loginscreen.cpp | hrxcodes/cbftp | bf2784007dcc4cc42775a2d40157c51b80383f81 | [
"MIT"
] | 8 | 2019-04-30T00:37:00.000Z | 2022-02-03T13:35:31.000Z | src/ui/screens/loginscreen.cpp | Xtravaganz/cbftp | 31a3465e2cd539f6cf35a5d9a0bb9c5c2f639cd5 | [
"MIT"
] | 2 | 2019-11-19T12:46:13.000Z | 2019-12-20T22:13:57.000Z | src/ui/screens/loginscreen.cpp | Xtravaganz/cbftp | 31a3465e2cd539f6cf35a5d9a0bb9c5c2f639cd5 | [
"MIT"
] | 9 | 2020-01-15T02:38:36.000Z | 2022-02-15T20:05:20.000Z | #include "loginscreen.h"
#include <cstdlib>
#include <ctime>
#include "../termint.h"
#include "../ui.h"
#include "../chardraw.h"
#include "../../buildinfo.h"
LoginScreen::LoginScreen(Ui* ui) : UIWindow(ui, "LoginScreen") {
allowimplicitgokeybinds = false;
}
void LoginScreen::initialize(unsigned int row, unsigned int col) {
passfield = TextInputField(25, 32, true);
attempt = false;
drawword = BuildInfo::tag();
drawx = 0;
drawy = 0;
srand(time(NULL));
init(row, col);
}
void LoginScreen::redraw() {
ui->erase();
randomizeDrawLocation();
background.clear();
for (unsigned int i = 0; i < row; i++) {
background.push_back(std::vector<int>());
background[i].resize(col);
}
pass_row = row-2;
pass_col = col-27;
ui->showCursor();
std::string svnstring = " cbftp version tag: " + BuildInfo::version() + " ";
std::string compilestring = " Compiled: " + BuildInfo::compileTime() + " ";
int boxchar = 0;
for(unsigned int i = 1; i < row; i++) {
for(unsigned int j = 0; j < col; j++) {
if(i == 1) boxchar = (i+j)%2==0 ? BOX_HLINE_BOT : BOX_HLINE;
else if (i == row-1) {
if (j < col-29) boxchar = (i+j)%2==0 ? BOX_HLINE : BOX_HLINE_TOP;
else if (j == col-29) boxchar = BOX_CORNER_BR;
else continue;
}
else if ((i == row-2 || i == row-3) && j >= col-29) {
if (j == col-29) boxchar = (i+j)%2==0 ? BOX_VLINE : BOX_VLINE_L;
else continue;
}
else if (i == row-4 && j >= col-29) {
if (j == col-29) boxchar = (i+j)%2==0 ? BOX_CORNER_TL : BOX_CROSS;
else boxchar = (i+j)%2==0 ? BOX_HLINE : BOX_HLINE_TOP;
}
else boxchar = (i+j)%2==0 ? BOX_CORNER_TL : BOX_CORNER_BR;
if (boxchar) {
ui->printChar(i, j, boxchar);
background[i][j] = boxchar;
}
}
}
ui->printStr(0, 3, svnstring);
ui->printStr(0, col - compilestring.length() - 3, compilestring);
update();
}
void LoginScreen::update() {
std::string passtext = "AES passphrase required:";
if (attempt) {
passtext = "Invalid key, try again: ";
ui->showCursor();
}
int currdrawx = drawx;
ui->printStr(pass_row-1, pass_col, passtext);
ui->printStr(pass_row, pass_col, passfield.getVisualText());
ui->moveCursor(pass_row, pass_col + passfield.getVisualCursorPosition());
for (unsigned int drawchar = 0; drawchar < drawword.length(); drawchar++) {
bool show = passfield.getText().length() > drawchar &&
passfield.getText().length() - drawchar < drawword.length() + 1;
for (int i = 0; i < CHARDRAW_SIZE; i++) {
std::string draw = CharDraw::getCharLine(drawword[drawchar], i);
for (unsigned int j = 0; j < draw.length(); j++) {
int bgchar = background[drawy + i][currdrawx + j];
int c = show ? CharDraw::getMixedChar(bgchar, draw[j]) : bgchar;
if (c) {
ui->printChar(drawy + i, currdrawx + j, c);
}
}
}
currdrawx = currdrawx + CHARDRAW_SIZE;
}
if (passfield.getText().length() == drawword.length() * 2 || !passfield.getText().length()) {
randomizeDrawLocation();
}
}
bool LoginScreen::keyPressed(unsigned int ch) {
if (ch >= 32 && ch <= 126) {
passfield.addchar(ch);
}
else {
switch(ch) {
case 8:
case 127:
case KEY_BACKSPACE:
passfield.erase();
break;
case KEY_HOME:
passfield.moveCursorHome();
break;
case KEY_END:
passfield.moveCursorEnd();
break;
case KEY_LEFT:
passfield.moveCursorLeft();
break;
case KEY_RIGHT:
passfield.moveCursorRight();
break;
case KEY_DC:
passfield.eraseForward();
break;
case 23:
passfield.eraseCursoredWord();
break;
case KEY_ENTER:
case 10:
case 13:
ui->hideCursor();
attempt = true;
std::string pass = passfield.getText();
passfield.clear();
ui->key(pass);
return true;
}
}
ui->update();
return true;
}
void LoginScreen::randomizeDrawLocation() {
int ymin = 2;
int ymax = row - 2 - CHARDRAW_SIZE - ymin;
int xmin = 1;
int xmax = col - 2 - CHARDRAW_SIZE * drawword.length() - xmin;
drawy = rand() % ymax + ymin;
drawx = rand() % xmax + xmin;
}
| 28.377483 | 95 | 0.58063 | [
"vector"
] |
2dbf8ace989758f352bb1ac463e5f72c32e4b7d1 | 4,633 | cpp | C++ | Source/Engine/SDLInit.cpp | SirRamEsq/LEngine | 24f748a4f9e29cd5d35d012b46e1bc7a2c285f9c | [
"Apache-2.0"
] | 1 | 2020-05-24T14:04:12.000Z | 2020-05-24T14:04:12.000Z | Source/Engine/SDLInit.cpp | SirRamEsq/LEngine | 24f748a4f9e29cd5d35d012b46e1bc7a2c285f9c | [
"Apache-2.0"
] | 21 | 2017-09-20T13:39:12.000Z | 2018-01-27T22:21:13.000Z | Source/Engine/SDLInit.cpp | SirRamEsq/LEngine | 24f748a4f9e29cd5d35d012b46e1bc7a2c285f9c | [
"Apache-2.0"
] | null | null | null | #include "SDLInit.h"
#include "Kernel.h"
#include "gui/imgui.h"
SDLInit *SDLInit::pointertoself = NULL;
SDLInit::SDLInit() {}
SDL_Window *SDLInit::mMainWindow = NULL;
SDL_GLContext SDLInit::mMainContextGL;
SDLInit *SDLInit::Inst() {
pointertoself = new SDLInit();
return pointertoself;
}
SDL_Window *SDLInit::GetWindow() { return mMainWindow; }
void SDLInit::CloseSDL() {
Mix_CloseAudio();
Mix_Quit();
SDL_Quit();
}
bool InitImgGui(SDL_Window *window) {
ImGuiIO &io = ImGui::GetIO();
io.KeyMap[ImGuiKey_Tab] = SDLK_TAB; // Keyboard mapping. ImGui will use those
// indices to peek into the io.KeyDown[]
// array.
io.KeyMap[ImGuiKey_LeftArrow] = SDL_SCANCODE_LEFT;
io.KeyMap[ImGuiKey_RightArrow] = SDL_SCANCODE_RIGHT;
io.KeyMap[ImGuiKey_UpArrow] = SDL_SCANCODE_UP;
io.KeyMap[ImGuiKey_DownArrow] = SDL_SCANCODE_DOWN;
io.KeyMap[ImGuiKey_PageUp] = SDL_SCANCODE_PAGEUP;
io.KeyMap[ImGuiKey_PageDown] = SDL_SCANCODE_PAGEDOWN;
io.KeyMap[ImGuiKey_Home] = SDL_SCANCODE_HOME;
io.KeyMap[ImGuiKey_End] = SDL_SCANCODE_END;
io.KeyMap[ImGuiKey_Delete] = SDLK_DELETE;
io.KeyMap[ImGuiKey_Backspace] = SDLK_BACKSPACE;
io.KeyMap[ImGuiKey_Enter] = SDLK_RETURN;
io.KeyMap[ImGuiKey_Escape] = SDLK_ESCAPE;
io.KeyMap[ImGuiKey_A] = SDLK_a;
io.KeyMap[ImGuiKey_C] = SDLK_c;
io.KeyMap[ImGuiKey_V] = SDLK_v;
io.KeyMap[ImGuiKey_X] = SDLK_x;
io.KeyMap[ImGuiKey_Y] = SDLK_y;
io.KeyMap[ImGuiKey_Z] = SDLK_z;
// io.RenderDrawListsFn = ImGui_ImplSdlGL3_RenderDrawLists; // Alternatively
// you can set this to NULL and call ImGui::GetDrawData() after ImGui::Render()
// to get the same ImDrawData pointer.
// io.SetClipboardTextFn = ImGui_ImplSdlGL3_SetClipboardText;
// io.GetClipboardTextFn = ImGui_ImplSdlGL3_GetClipboardText;
// io.ClipboardUserData = NULL;
#ifdef _WIN32
SDL_SysWMinfo wmInfo;
SDL_VERSION(&wmInfo.version);
SDL_GetWindowWMInfo(window, &wmInfo);
io.ImeWindowHandle = wmInfo.info.win.window;
#else
(void)window;
#endif
return true;
}
bool SDLInit::InitOpenGL() {
glViewport(0, 0, 1024, 768);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_TEXTURE_2D); // Enable Texture Mapping
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
// Bottom is the height, Top is 0
glOrtho(0.0f, 1024, 768, 0, 0, 1); // 2D
// gluPerspective(45.0,(GLfloat)SCREEN_W/(GLfloat)SCREEN_H,0.1,100.0); //3D
glClearColor(0, 0, 0, 1);
// Initialize modelview matrix
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glEnable(GL_BLEND);
glEnable(GL_DEPTH_TEST);
// negative values nearer to camera
glDepthFunc(GL_GEQUAL);
// write to depth
glDepthMask(GL_TRUE);
glClearDepth(0.0f);
// Do not render any fragments with an alpha of 0.0
glEnable(GL_ALPHA_TEST);
glAlphaFunc(GL_GREATER, 0.0f);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnable(GL_COLOR_MATERIAL);
SDL_GL_SetSwapInterval(1);
if (glGetError() != GL_NO_ERROR) {
return 0;
}
return 1;
}
void SDLInit::InitSDL() {
if (SDL_Init(SDL_INIT_JOYSTICK) == -1) {
LOG_FATAL("Didn't init SDL properly");
return;
}
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
mMainWindow = SDL_CreateWindow("LEngine", // name
SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
1024, 768, // x,y,w,h
SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE |
SDL_WINDOW_MAXIMIZED); // flags
mMainContextGL = SDL_GL_CreateContext(mMainWindow);
if (InitOpenGL() == 0) {
LOG_FATAL("Didn't Initialize OpenGL");
return;
}
if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 4096) == -1) {
LOG_FATAL("Didn't init SDL Mixer properly");
return;
}
int flags = MIX_INIT_OGG;
int initted = Mix_Init(flags);
if ((initted & flags) != flags) {
std::stringstream ss;
ss << "SDL_Mix_Init: Failed to init required ogg and mod support!"
<< "\n"
<< "SDL_Mix_Init: " << Mix_GetError();
LOG_FATAL(ss.str());
}
GLenum err = glewInit();
if (GLEW_OK != err) {
std::stringstream ss;
ss << "Error in GLEW INIT: " << glewGetErrorString(err);
LOG_FATAL(ss.str());
}
if (InitImgGui(mMainWindow) != true) {
LOG_FATAL("Couldn't Initialize ImgGui");
}
SDL_GL_SetSwapInterval(1);
//Needed?
// SDL_EnableUNICODE(1);
}
| 28.776398 | 80 | 0.685085 | [
"render",
"3d"
] |
2dc9af4b8d1f469e0d4978974b1fbe9c324a9973 | 5,473 | cpp | C++ | src/models/mesh/meshGrid.cpp | TheSpyGeek/Green-Engine | cdfbd55410ee5d90cbeb51390f2ae9a4e84f4792 | [
"MIT"
] | 1 | 2021-07-04T12:33:49.000Z | 2021-07-04T12:33:49.000Z | src/models/mesh/meshGrid.cpp | TheSpyGeek/Green-Engine | cdfbd55410ee5d90cbeb51390f2ae9a4e84f4792 | [
"MIT"
] | 2 | 2019-10-29T11:46:09.000Z | 2019-11-21T20:44:02.000Z | src/models/mesh/meshGrid.cpp | TheSpyGeek/Green-Engine | cdfbd55410ee5d90cbeb51390f2ae9a4e84f4792 | [
"MIT"
] | null | null | null | #include "meshGrid.h"
#include <imgui.h>
#include <stdio.h>
#include <iostream>
using namespace glm;
MeshGrid::MeshGrid(unsigned int size, float w, float y, float amp, float freq, float pers, int octaves){
assert(size >= 1);
nbPointPerRowColumn = size;
width = w;
gridY = y;
amplitude = amp;
frequency = freq;
persistence = pers;
nboctaves = octaves;
nb_vertices = 0;
nb_faces = 0;
recreate();
}
MeshGrid::~MeshGrid(){
cleanup();
}
void MeshGrid::recreate(){
cleanup();
createMesh(nbPointPerRowColumn, width, gridY);
applyNoiseModification();
hasChanged = false;
}
void MeshGrid::update(){
if(hasChanged){
recreate();
}
}
void MeshGrid::createMesh(int size, float w, float y){
assert(size >= 1);
const float startingWidth = -(width/2.0f);
const float offset = width/(size-1);
nb_vertices = size*size;
nb_faces = (size-1)*(size-1)*2;
vertices.resize(nb_vertices);
normals.resize(nb_vertices);
tangents.resize(nb_vertices);
colors.resize(nb_vertices);
coords.resize(nb_vertices);
faces.resize(3*nb_faces);
// points creation
for(unsigned int i=0; i<size; i++){
for(unsigned int j=0; j<size; j++){
int arrayPos = i*size + j;
vec3 pos = vec3(startingWidth + i*offset, y, startingWidth + j*offset);
vec2 uv = vec2((float)i/(float)size, (float)j/(float)size);
addVertex(arrayPos, pos, defaultNormal, defaultTangent, defaultColor, uv);
}
}
// creation faces
unsigned int p1,p2,p3,p4;
unsigned int numFace;
numFace = 0;
for(unsigned int i=0; i<size-1; i++){
for(unsigned int j=0; j<size-1; j++){
p1 = i*size + j;
p2 = i*size + j+1;
p3 = (i+1)*size + j+1;
p4 = (i+1)*size + j;
faces[numFace] = p1;
faces[numFace+1] = p2;
faces[numFace+2] = p4;
faces[numFace+3] = p4;
faces[numFace+4] = p2;
faces[numFace+5] = p3;
numFace += 6;
}
}
center = vec3(0,y,0);
radius = width/2;
}
void MeshGrid::addVertex(unsigned int arrayPos, vec3 pos, vec3 n, vec3 tangent, vec3 col, vec2 uv){
// position
vertices[arrayPos] = pos;
// normal
normals[arrayPos] = n;
// tangent
tangents[arrayPos] = tangent;
// color
colors[arrayPos] = col;
// uv coordinates
coords[arrayPos] = uv;
}
void MeshGrid::cleanup(){
}
void MeshGrid::createUI(){
ImGui::TextColored(ImVec4(1.0f,1.0f,0.0f,1.0f), "Mesh Grid");
// nbPointPerRowColumn, width, gridY
ImGui::Text("Size :"); ImGui::SameLine();
if(ImGui::InputInt("##size", &nbPointPerRowColumn, 1, 10)){}
ImGui::Text("Width :"); ImGui::SameLine();
ImGui::InputFloat("##width", &width, 0.01f, 1.0f, "%.3f");
ImGui::Text("Z plane :"); ImGui::SameLine();
ImGui::InputFloat("##gridY", &gridY, 0.01f, 1.0f, "%.3f");
bool node_mesh = ImGui::TreeNodeEx("Noise modifier", 0);
if(node_mesh){
ImGui::Text("Frequency :"); ImGui::SameLine();
ImGui::InputFloat("##frequency", &frequency, 0.01f, 100.0f, "%.3f");
ImGui::Text("Amplitude :"); ImGui::SameLine();
ImGui::InputFloat("##amplitude", &litude, 0.01f, 100.0f, "%.3f");
ImGui::Text("Persistence :"); ImGui::SameLine();
ImGui::InputFloat("##persistence", &persistence, 0.01f, 100.0f, "%.3f");
ImGui::Text("Number of octaves : "); ImGui::SameLine();
ImGui::InputInt("##NbOctaves", &nboctaves, 1, 20);
ImGui::TreePop();
}
this->Mesh::createUI();
}
void MeshGrid::applyNoiseModification(){
for(unsigned int i=0; i<vertices.size(); i++){
float height = pnoise(glm::vec2(vertices[i].x, vertices[i].z), amplitude, frequency, persistence, nboctaves);
glm::vec3 n = normalPoint(vertices[i]);
vertices[i].y = height;
normals[i] = n;
}
}
// CREATION DU BRUIT DE PERLIN
glm::vec2 MeshGrid::hash(glm::vec2 p) {
p = glm::vec2( dot(p,glm::vec2(127.1f,311.7f)),
glm::dot(p,glm::vec2(269.5f,183.3f)) );
return -1.0f + 2.0f*glm::fract(glm::sin(p)*43758.5453123f);
}
float MeshGrid::gnoise(glm::vec2 p) {
glm::vec2 i = glm::floor( p );
glm::vec2 f = glm::fract( p );
glm::vec2 u = f*f*(3.0f-2.0f*f);
return glm::mix( glm::mix( glm::dot( hash( i + glm::vec2(0.0f,0.0f) ), f - glm::vec2(0.0f,0.0f) ),
glm::dot( hash( i + glm::vec2(1.0f,0.0f) ), f - glm::vec2(1.0f,0.0f) ), u.x),
glm::mix( glm::dot( hash( i + glm::vec2(0.0f,1.0f) ), f - glm::vec2(0.0f,1.0f) ),
glm::dot( hash( i + glm::vec2(1.0f,1.0f) ), f - glm::vec2(1.0f,1.0f) ), u.x), u.y);
}
float MeshGrid::pnoise(glm::vec2 p,float amplitude,float frequency,float persistence, int nboctaves) {
float a = amplitude;
float f = frequency;
float n = 0.0;
for(int i=0;i<nboctaves;++i) {
n = n+a*gnoise(p*f);
f = f*2.;
a = a*persistence;
}
return n;
}
// CALCUL NORMAL FROM NOISE
// calcul de la normale a partir du bruit
glm::vec3 MeshGrid::normalPoint(glm::vec3 point){
// vec2 ps = 1./vec2(textureSize(heightmap,0));
glm::vec2 ps = glm::vec2(0.01f);
glm::vec2 p = glm::vec2(point.x, point.z);
glm::vec2 g = glm::vec2(pnoise(p+glm::vec2(ps.x,0.0f),amplitude,frequency,persistence,nboctaves) - pnoise(p-glm::vec2(ps.x,0.0f),amplitude,frequency,persistence,nboctaves),
pnoise(p+glm::vec2(0.0f,ps.y),amplitude,frequency,persistence,nboctaves) - pnoise(p+glm::vec2(0.0f,ps.y),amplitude,frequency,persistence,nboctaves))/2.f;
float scale = 100.f;
glm::vec3 n1 = glm::vec3(1.,0.,g.x*scale);
glm::vec3 n2 = glm::vec3(0.,1.,-g.y*scale);
glm::vec3 n = glm::normalize(glm::cross(n1,n2));
return n;
}
| 22.804167 | 173 | 0.623241 | [
"mesh"
] |
2dd48bcfb2ca8dc84ee41e512514066274779eab | 14,381 | cpp | C++ | Pixel Lighting Engine 2/Pixel Lighting Engine 2.cpp | mallocc/Pixel-Light-Rendering-Test | 2c71626d8e7b08f59d1540640f65e4e1936977a2 | [
"MIT"
] | null | null | null | Pixel Lighting Engine 2/Pixel Lighting Engine 2.cpp | mallocc/Pixel-Light-Rendering-Test | 2c71626d8e7b08f59d1540640f65e4e1936977a2 | [
"MIT"
] | null | null | null | Pixel Lighting Engine 2/Pixel Lighting Engine 2.cpp | mallocc/Pixel-Light-Rendering-Test | 2c71626d8e7b08f59d1540640f65e4e1936977a2 | [
"MIT"
] | null | null | null | // Pixel Lighting Engine 2.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <CL\cl.hpp>
#include <CL\opencl.h>
#include <GL\glut.h>
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <sstream>
#include <cmath>
#include <stdlib.h>
#include <time.h>
#include <Windows.h>
const int pxlsize = 3;
const int winW = 1600;
const int winH = 900;
const int pxlsrow = winW / pxlsize;
const int pxlscol = winH / pxlsize;
static const int nthread = 256;
static const int dataSize = pxlsrow * pxlscol;
static const int maxlights = 5;
static const int maxwalls = 40;
cl_float mbc = 10.0;
cl_float4 pxltrans = { pxlsize / 2.0f, pxlsize / 2.0f, 0.0f, 0.0f };
cl_float4 ambcolour = { 0.1f, 0.1f, 0.1f, 0.0f };
bool showentities = false;
inline float rndN() { return ((double)rand() / (RAND_MAX)); }
inline void calc();
inline void CheckError(cl_int error);
const char * ker = "test2";
cl_command_queue queue;
cl_kernel kernel;
std::vector<cl_device_id> deviceIds;
cl_int error;
cl_context context;
cl_float4 p[dataSize], c[dataSize], li[maxlights], lic[maxlights], wp1[maxwalls], wp2[maxwalls], lim[maxlights*dataSize];
cl_bool liu[maxlights*dataSize];
cl_mem pB, cB, liB, licB, wp1B, wp2B, limB, liuB;
float fps, afps, asfps;
int counter, counter2, counter3, counter4;
cl_int4 mousepos = { 0.0f, 0.0f, 0.0f, 0.0f };
float zoom = 1;
float zoominc = zoom / 10;
int framc = 0;
cl_int4 target = { 0, 0, 0, 0 };
void drawScene()
{
float beginT = GetTickCount();
counter4 += 1;
if (counter4 > 0)
{
counter4 = 0;
calc();
framc++;
if (framc > 1) framc = 0;
}
counter += 1;
if (counter > 10)
{
counter = 0;
POINT mp;
GetCursorPos(&mp);
mousepos.s[0] = (mp.x - glutGet(GLUT_WINDOW_X)) / zoom;
mousepos.s[1] = (mp.y - glutGet(GLUT_WINDOW_Y)) / zoom;
// Get the results back to the host
CheckError(clEnqueueReadBuffer(queue, cB, CL_TRUE, 0,
sizeof(cl_float4) * dataSize,
c,
0, nullptr, nullptr));
if (GetAsyncKeyState(VK_UP))
{
}
if (GetAsyncKeyState(VK_DOWN))
{
}
if (GetAsyncKeyState('W')){}
//target.s[1] -= 1;
if (GetAsyncKeyState('S')){}
// target.s[1] += 1;
if (GetAsyncKeyState('A')){}
//target.s[0] -= 1;
if (GetAsyncKeyState('D')){}
// target.s[0] += 1;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glShadeModel(GL_SMOOTH);
//draw shit here
glPushMatrix();
//glScalef(1 / zoom, 1 / zoom, 0.0f);
//glTranslatef(zoom *winW / 2, zoom * winH / 2, 0.0f);
glBegin(GL_QUADS);
int nc = 0;
for (int i = 0; i < pxlsrow; i++)
{
for (int j = 0; j < pxlscol; j++, nc++)
{
//glBegin(GL_POLYGON);
glColor3f(c[nc].s[0], c[nc].s[1], c[nc].s[2]);
//glColor3f(0.5f, 0.5f, 0.5f);
float x = p[nc].s[0];
float y = p[nc].s[1];
glVertex2f(0 + x, 0 + y);
glVertex2f(pxlsize + x, 0 + y);
glVertex2f(pxlsize + x, pxlsize + y);
glVertex2f(0 + x, pxlsize + y);
//glEnd();
}
}
glEnd();
if (showentities)
{
glBegin(GL_POINTS);
for (int i = 0; i < maxlights; i++)
{
glColor3f(1, 1, 1);
glVertex2f(li[i].s[0], li[i].s[1]);
}
glEnd();
glBegin(GL_LINES);
for (int i = 0; i < maxwalls; i++)
{
glColor3f(1, 1, 0);
glVertex2f(wp1[i].s[0], wp1[i].s[1]);
glVertex2f(wp2[i].s[0], wp2[i].s[1]);
}
glEnd();
}
glPopMatrix();
float dT = GetTickCount() - beginT;
if (dT > 0) fps = 1000.0f / (dT);
int fpsf = 10;
afps += fps / fpsf;
counter3 += 1;
if (counter3 > fpsf - 1)
{
counter3 = 0;
asfps = afps;
afps = 0;
}
}
counter2 += 1;
if (counter2 > 200)
{
counter2 = 0;
std::system("CLS");
//std::cout << "FPS: " << fps << std::endl;
std::cout << "FPS: " << asfps << std::endl;
std::cout << "Pixels: " << dataSize << std::endl;
std::cout << "Lights: " << maxlights << std::endl;
std::cout << "Walls: " << maxwalls << std::endl;
std::cout << "Max Combinations: " << dataSize*maxlights*maxwalls << std::endl;
std::cout << "Work Group Size: " << nthread << std::endl;
std::cout << "Kernel Running: " << ker << std::endl;
std::cout << "Zoom scale: " << 1 / zoom << std::endl;
}
li[0].s[0] = mousepos.s[0];
li[0].s[1] = mousepos.s[1];
for (int j = 0; j < dataSize; j++)
{
liu[0 * dataSize + j] = true;
}
if (ker == "test") CheckError(clEnqueueWriteBuffer(queue, liuB, CL_TRUE, 0,
sizeof(cl_bool) * (maxlights*dataSize),
liu,
0, nullptr, nullptr));
CheckError(clEnqueueWriteBuffer(queue, liB, CL_TRUE, 0,
sizeof(cl_float4) * (maxlights),
li,
0, nullptr, nullptr));
CheckError(clEnqueueUnmapMemObject(queue,
cB, c, 0, NULL, NULL));
glutSwapBuffers();
glutPostRedisplay();
}
void changeSize(int w, int h)
{
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, w, h, 0);
}
void startGLscene(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA);
glutInitWindowPosition(100, 100);
glutInitWindowSize(winW, winH);
glutCreateWindow("A Window");
glDepthMask(GL_FALSE);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_COLOR);
glPointSize(1.0);
//glClearColor(0.3f, 0.3f, 0.3f, 1.0f);
//glColor3f(0.8f, 0.8f, 0.8f);
glutDisplayFunc(drawScene);
glutReshapeFunc(changeSize);
glutMainLoop();
}
std::string GetPlatformName(cl_platform_id id)
{
size_t size = 0;
clGetPlatformInfo(id, CL_PLATFORM_NAME, 0, nullptr, &size);
std::string result;
result.resize(size);
clGetPlatformInfo(id, CL_PLATFORM_NAME, size,
const_cast<char*> (result.data()), nullptr);
return result;
}
std::string GetDeviceName(cl_device_id id)
{
size_t size = 0;
clGetDeviceInfo(id, CL_DEVICE_NAME, 0, nullptr, &size);
std::string result;
result.resize(size);
clGetDeviceInfo(id, CL_DEVICE_NAME, size,
const_cast<char*> (result.data()), nullptr);
return result;
}
inline void CheckError(cl_int error)
{
if (error != CL_SUCCESS) {
std::cerr << "OpenCL call failed with error " << error << std::endl;
std::system("PAUSE");
std::exit(1);
}
}
std::string LoadKernel(const char* name)
{
std::ifstream in(name);
std::string result(
(std::istreambuf_iterator<char>(in)),
std::istreambuf_iterator<char>());
return result;
}
cl_program CreateProgram(const std::string& source,
cl_context context)
{
size_t lengths[1] = { source.size() };
const char* sources[1] = { source.data() };
cl_int error = 0;
cl_program program = clCreateProgramWithSource(context, 1, sources, lengths, &error);
CheckError(error);
return program;
}
inline void calc()
{
if (ker == "test")
{
clSetKernelArg(kernel, 0, sizeof(int), &maxlights);
clSetKernelArg(kernel, 1, sizeof(int), &maxwalls);
clSetKernelArg(kernel, 2, sizeof(cl_mem), &cB);
clSetKernelArg(kernel, 3, sizeof(cl_mem), &pB);
clSetKernelArg(kernel, 4, sizeof(cl_mem), &liB);
clSetKernelArg(kernel, 5, sizeof(cl_mem), &licB);
clSetKernelArg(kernel, 6, sizeof(cl_mem), &wp1B);
clSetKernelArg(kernel, 7, sizeof(cl_mem), &wp2B);
clSetKernelArg(kernel, 8, sizeof(cl_float4), &pxltrans);
clSetKernelArg(kernel, 9, sizeof(cl_float4), &ambcolour);
clSetKernelArg(kernel, 10, sizeof(cl_float), &mbc);
clSetKernelArg(kernel, 11, sizeof(cl_mem), &limB);
clSetKernelArg(kernel, 12, sizeof(int), &dataSize);
clSetKernelArg(kernel, 13, sizeof(cl_mem), &liuB);
clSetKernelArg(kernel, 14, sizeof(int), &framc);
clSetKernelArg(kernel, 15, sizeof(int), &pxlsrow);
clSetKernelArg(kernel, 16, sizeof(int), &pxlscol);
}
else if (ker == "test2")
{
clSetKernelArg(kernel, 0, sizeof(int), &maxlights);
clSetKernelArg(kernel, 1, sizeof(int), &maxwalls);
clSetKernelArg(kernel, 2, sizeof(cl_mem), &cB);
clSetKernelArg(kernel, 3, sizeof(cl_mem), &pB);
clSetKernelArg(kernel, 4, sizeof(cl_mem), &liB);
clSetKernelArg(kernel, 5, sizeof(cl_mem), &licB);
clSetKernelArg(kernel, 6, sizeof(cl_mem), &wp1B);
clSetKernelArg(kernel, 7, sizeof(cl_mem), &wp2B);
clSetKernelArg(kernel, 8, sizeof(cl_float4), &pxltrans);
clSetKernelArg(kernel, 9, sizeof(cl_float4), &ambcolour);
clSetKernelArg(kernel, 10, sizeof(cl_float), &mbc);
clSetKernelArg(kernel, 11, sizeof(int), &dataSize);
clSetKernelArg(kernel, 12, sizeof(int), &pxlsrow);
clSetKernelArg(kernel, 13, sizeof(int), &pxlscol);
}
cl_event eve;
const size_t globalWorkSize[] = { dataSize, 0, 0 };
const size_t localWorkSize[] = { nthread, 0, 0 };
CheckError(clEnqueueNDRangeKernel(queue, kernel, 1,
nullptr,
globalWorkSize,
localWorkSize,
0, nullptr, &eve));
CheckError(clFlush(queue));
}
inline void createBuffers()
{
cB = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR,
sizeof(cl_float4) * (dataSize),
c, &error);
CheckError(error);
pB = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR,
sizeof(cl_float4) * (dataSize),
p, &error);
CheckError(error);
liB = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR,
sizeof(cl_float4) * (maxlights),
li, &error);
CheckError(error);
licB = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR,
sizeof(cl_float4) * (maxlights),
lic, &error);
CheckError(error);
wp1B = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR,
sizeof(cl_float4) * (maxwalls),
wp1, &error);
CheckError(error);
wp2B = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR,
sizeof(cl_float4) * (maxwalls),
wp2, &error);
CheckError(error);
limB = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR,
sizeof(cl_float4) * (maxlights*dataSize),
lim, &error);
CheckError(error);
liuB = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR,
sizeof(cl_bool) * (maxlights*dataSize),
liu, &error);
CheckError(error);
}
inline void setupData()
{
int i = 0;
int k = 0;
for (; i < pxlsrow; i++)
{
for (int j = 0; j < pxlscol; j++, k++)
{
c[k].s[0] = 0.0f;
c[k].s[1] = 0.0f;
c[k].s[2] = 0.0f;
c[k].s[3] = 0.0f;
//c[k].s[0] = rndN()/10;
p[k].s[0] = i * pxlsize;
p[k].s[1] = j * pxlsize;
p[k].s[2] = 0.0f;
p[k].s[3] = 0.0f;
}
}
i = 0;
for (; i < maxlights; i++)
{
li[i].s[0] = rndN() * winW;
li[i].s[1] = rndN() * winH;
lic[i].s[0] = rndN() * 0.5+0.5;
lic[i].s[1] = rndN() * 0.5+0.5;
lic[i].s[2] = rndN() * 0.5+0.5;
//lic[i].s[0] = 1.0f;
//lic[i].s[1] = 0.5f;
//lic[i].s[2] = 0.5f;
lic[i].s[3] = 500.0f;
for (int j = 0; j < dataSize; j++)
{
lim[i * dataSize + j].s[0] = 0.0f;
lim[i * dataSize + j].s[1] = 0.0f;
lim[i * dataSize + j].s[2] = 0.0f;
lim[i * dataSize + j].s[3] = 0.0f;
liu[i * dataSize + j] = true;
}
}
lic[0].s[3] = 5000.0f;
//li[1].s[0] = 0.0f;
//li[1].s[1] = -1000;
//lic[1].s[0] = 0.8f;
//lic[1].s[1] = 0.8f;
//lic[1].s[2] = 1.0f;
//lic[1].s[3] = 200000.0f;
i = 0;
//for (; i < maxwalls; i++)
//{
// wp1[i].s[0] = rndN() * winW;
// wp1[i].s[1] = rndN() * winH;
// wp2[i].s[0] = rndN() * winW;
// wp2[i].s[1] = rndN() * winH;
//}
//float dr = 4.0f*3.141f / maxwalls;
//for (; i < maxwalls; i++)
//{
// wp1[i].s[0] = cos(dr * i) * 200 + 300 + dr * i*50;
// wp1[i].s[1] = sin(dr * i) * 200 + 300;
// wp2[i].s[0] = cos(dr * (i + 1)) * 200 + 300 + dr * (i+1)*50;
// wp2[i].s[1] = sin(dr * (i + 1)) * 200 + 300;
//}
int nums = maxwalls / 4;
for (int j = 0; j < nums; j++)
{
int count = j * 4;
int wid = 50;
float x = rndN() * winW;
float y = rndN() * winH;
wp1[count].s[0] = x;
wp1[count].s[1] = y;
wp2[count].s[0] = x + wid;
wp2[count].s[1] = y;
wp1[count + 1].s[0] = x + wid;
wp1[count + 1].s[1] = y;
wp2[count + 1].s[0] = x + wid;
wp2[count + 1].s[1] = y + wid;
wp1[count + 2].s[0] = x + wid;
wp1[count + 2].s[1] = y + wid;
wp2[count + 2].s[0] = x;
wp2[count + 2].s[1] = y + wid;
wp1[count + 3].s[0] = x;
wp1[count + 3].s[1] = y + wid;
wp2[count + 3].s[0] = x;
wp2[count + 3].s[1] = y;
}
}
int _tmain(int argc, char* argv[]){
srand(time(NULL));
setupData();
cl_uint platformIdCount = 0;
clGetPlatformIDs(0, nullptr, &platformIdCount);
if (platformIdCount == 0) {
std::cerr << "No OpenCL platform found" << std::endl;
return 1;
}
else {
std::cout << "Found " << platformIdCount << " platform(s)" << std::endl;
}
std::vector<cl_platform_id> platformIds(platformIdCount);
clGetPlatformIDs(platformIdCount, platformIds.data(), nullptr);
for (cl_uint i = 0; i < platformIdCount; ++i) {
std::cout << "\t (" << (i + 1) << ") : " << GetPlatformName(platformIds[i]) << std::endl;
}
//find devices
cl_uint deviceIdCount = 0;
clGetDeviceIDs(platformIds[0], CL_DEVICE_TYPE_ALL, 0, nullptr,
&deviceIdCount);
if (deviceIdCount == 0) {
std::cerr << "No OpenCL devices found" << std::endl;
return 1;
}
else {
std::cout << "Found " << deviceIdCount << " device(s)" << std::endl;
}
std::vector<cl_device_id> deviceIds(deviceIdCount);
clGetDeviceIDs(platformIds[0], CL_DEVICE_TYPE_ALL, deviceIdCount,
deviceIds.data(), nullptr);
for (cl_uint i = 0; i < deviceIdCount; ++i) {
std::cout << "\t (" << (i + 1) << ") : " << GetDeviceName(deviceIds[i]) << std::endl;
}
//create the context
const cl_context_properties contextProperties[] =
{
CL_CONTEXT_PLATFORM, reinterpret_cast<cl_context_properties> (platformIds[0]),
0, 0
};
cl_int error = CL_SUCCESS;
context = clCreateContext(contextProperties, deviceIdCount,
deviceIds.data(), nullptr, nullptr, &error);
CheckError(error);
std::cout << "Context created" << std::endl;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
//create a program from the CL file
cl_program program = CreateProgram(LoadKernel("kernels.cl"),
context);
CheckError(clBuildProgram(program, deviceIdCount, deviceIds.data(), nullptr, nullptr, nullptr));
kernel = clCreateKernel(program, ker, &error);
CheckError(error);
///////////////////////////////////////////////////////////////////////////////////////////////////////
createBuffers();
queue = clCreateCommandQueue(context, deviceIds[0],
0, &error);
CheckError(error);
startGLscene(argc, argv);
clReleaseCommandQueue(queue);
clReleaseMemObject(cB);
clReleaseMemObject(pB);
clReleaseMemObject(liB);
clReleaseMemObject(licB);
clReleaseMemObject(wp1B);
clReleaseMemObject(wp2B);
clReleaseKernel(kernel);
clReleaseProgram(program);
clReleaseContext(context);
return 0;
}
| 25.229825 | 121 | 0.623948 | [
"vector"
] |
2ddd7971511862a3cac73beff7c37191e9af400b | 2,173 | cpp | C++ | src/pairwise/0_GEN/Correlation_fft_fftw.cpp | JaneliaSciComp/TileAlignment | 64f6732445f0c965122c143c8ca285428a371dc8 | [
"Unlicense"
] | 2 | 2018-07-02T17:20:40.000Z | 2019-04-10T15:03:26.000Z | src/pairwise/0_GEN/Correlation_fft_fftw.cpp | JaneliaSciComp/TileAlignment | 64f6732445f0c965122c143c8ca285428a371dc8 | [
"Unlicense"
] | null | null | null | src/pairwise/0_GEN/Correlation_fft_fftw.cpp | JaneliaSciComp/TileAlignment | 64f6732445f0c965122c143c8ca285428a371dc8 | [
"Unlicense"
] | null | null | null |
#include "fftw3.h"
/* --------------------------------------------------------------- */
/* Statics ------------------------------------------------------- */
/* --------------------------------------------------------------- */
/* --------------------------------------------------------------- */
/* _FFT_2D ------------------------------------------------------- */
/* --------------------------------------------------------------- */
static void _FFT_2D(
vector<CD> &out,
const vector<double> &in,
int Nfast,
int Nslow )
{
int M = Nslow * (Nfast/2 + 1);
out.resize( M );
fftw_plan p;
p = fftw_plan_dft_r2c_2d( Nslow, Nfast, (double*)&in[0],
(double (*)[2])&out[0], FFTW_ESTIMATE );
fftw_execute( p );
fftw_destroy_plan( p );
}
/* --------------------------------------------------------------- */
/* FFT_2D -------------------------------------------------------- */
/* --------------------------------------------------------------- */
// Forward FFT of 2D data (real to complex).
//
// Assumes input data in row-major order. That is,
// ordered like a C-array: in[Nslow][Nfast].
//
int FFT_2D(
vector<CD> &out,
const vector<double> &in,
int Nfast,
int Nslow,
bool cached )
{
int M = Nslow * (Nfast/2 + 1);
pthread_mutex_lock( &mutex_fft );
if( !cached || out.size() != M )
_FFT_2D( out, in, Nfast, Nslow );
pthread_mutex_unlock( &mutex_fft );
return M;
}
/* --------------------------------------------------------------- */
/* IFT_2D -------------------------------------------------------- */
/* --------------------------------------------------------------- */
// Inverse FFT of 2D data (complex to real).
//
// Creates output data in row-major order. That is,
// ordered like a C-array: out[Nslow][Nfast].
//
void IFT_2D(
vector<double> &out,
const vector<CD> &in,
int Nfast,
int Nslow )
{
int N = Nslow * Nfast;
out.resize( N );
pthread_mutex_lock( &mutex_fft );
fftw_plan p;
p = fftw_plan_dft_c2r_2d( Nslow, Nfast, (double (*)[2])&in[0],
&out[0], FFTW_ESTIMATE );
fftw_execute( p );
fftw_destroy_plan( p );
pthread_mutex_unlock( &mutex_fft );
}
| 21.949495 | 69 | 0.390244 | [
"vector"
] |
2de1d3c2321d39ce6e708e4e5c93bd2aa2bdb099 | 4,197 | hpp | C++ | Source/AllProjects/DataUtils/CIDXML/CIDXML_DocumentEvents.hpp | eudora-jia/CIDLib | 02795d283d95f8a5a4fafa401b6189851901b81b | [
"MIT"
] | 1 | 2019-05-28T06:33:01.000Z | 2019-05-28T06:33:01.000Z | Source/AllProjects/DataUtils/CIDXML/CIDXML_DocumentEvents.hpp | eudora-jia/CIDLib | 02795d283d95f8a5a4fafa401b6189851901b81b | [
"MIT"
] | null | null | null | Source/AllProjects/DataUtils/CIDXML/CIDXML_DocumentEvents.hpp | eudora-jia/CIDLib | 02795d283d95f8a5a4fafa401b6189851901b81b | [
"MIT"
] | null | null | null | //
// FILE NAME: CIDXML_DocumentEvents.hpp
//
// AUTHOR: Dean Roddey
//
// CREATED: 09/04/1999
//
// COPYRIGHT: Charmed Quark Systems, Ltd @ 2019
//
// This software is copyrighted by 'Charmed Quark Systems, Ltd' and
// the author (Dean Roddey.) It is licensed under the MIT Open Source
// license:
//
// https://opensource.org/licenses/MIT
//
// DESCRIPTION:
//
// This file defines a mixin class that represents the event callouts for
// the events from an XML document's content (prologue, content, misc.) The
// parser core accepts an object of this type and will call back on it for
// the events that the client code wants to see.
//
// To avoid making every implementor of this mixin implement every method,
// default dummy implementations are provided for most of them.
//
// CAVEATS/GOTCHAS:
//
// LOG:
//
// $_CIDLib_Log_$
//
#pragma once
#pragma CIDLIB_PACK(CIDLIBPACK)
class TXMLParserCore;
// ---------------------------------------------------------------------------
// CLASS: MXMLDocEvents
// PREFIX: mxev
// ---------------------------------------------------------------------------
class CIDXMLEXP MXMLDocEvents
{
public :
// -------------------------------------------------------------------
// Destructor
// -------------------------------------------------------------------
virtual ~MXMLDocEvents()
{
}
protected :
// -------------------------------------------------------------------
// Declare our friends.
//
// The parser core is our friend because only he can call the event
// methods
// -------------------------------------------------------------------
friend class TXMLParserCore;
// -------------------------------------------------------------------
// Hidden constructors
// -------------------------------------------------------------------
MXMLDocEvents()
{
}
// -------------------------------------------------------------------
// Protected, virtual methods
// -------------------------------------------------------------------
virtual tCIDLib::TVoid DocCharacters
(
const TString& strChars
, const tCIDLib::TBoolean bIsCDATA
, const tCIDLib::TBoolean bIsIgnorable
, const tCIDXML::ELocations eLocation
);
virtual tCIDLib::TVoid DocComment
(
const TString& strCommentText
, const tCIDXML::ELocations eLocation
);
virtual tCIDLib::TVoid DocPI
(
const TString& strTarget
, const TString& strValue
, const tCIDXML::ELocations eLocation
);
virtual tCIDLib::TVoid EndDocument
(
const TXMLEntitySrc& xsrcOfRoot
);
virtual tCIDLib::TVoid EndTag
(
const TXMLElemDecl& xdeclElem
);
virtual tCIDLib::TVoid ResetDocument() = 0;
virtual tCIDLib::TVoid StartDocument
(
const TXMLEntitySrc& xsrcOfRoot
);
virtual tCIDLib::TVoid StartTag
(
TXMLParserCore& xprsSrc
, const TXMLElemDecl& xdeclElem
, const tCIDLib::TBoolean bEmpty
, const TVector<TXMLAttr>& colAttrList
, const tCIDLib::TCard4 c4AttrListSize
);
virtual tCIDLib::TVoid XMLDecl
(
const TString& strVersion
, const TString& strEncoding
, const TString& strStandalone
);
private :
// -------------------------------------------------------------------
// Unimplemented constructors and operators
// -------------------------------------------------------------------
MXMLDocEvents(const MXMLDocEvents&);
tCIDLib::TVoid operator=(const MXMLDocEvents&);
};
#pragma CIDLIB_POPPACK
| 29.765957 | 78 | 0.435311 | [
"object"
] |
2deb89a65cd5d05b0dd8c5d6242fbc82a8ca7bad | 32,972 | cxx | C++ | Modules/TrafficMonitor/CWrapper/TrafficMonitor_wrap.cxx | 5nefarious/icarous | bfd759d88a47d9ee079fe35deaa6cf6d4459dcd8 | [
"Unlicense"
] | null | null | null | Modules/TrafficMonitor/CWrapper/TrafficMonitor_wrap.cxx | 5nefarious/icarous | bfd759d88a47d9ee079fe35deaa6cf6d4459dcd8 | [
"Unlicense"
] | null | null | null | Modules/TrafficMonitor/CWrapper/TrafficMonitor_wrap.cxx | 5nefarious/icarous | bfd759d88a47d9ee079fe35deaa6cf6d4459dcd8 | [
"Unlicense"
] | null | null | null | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 2.0.6
*
* This file is not intended to be easily readable and contains a number of
* coding conventions designed to improve portability and efficiency. Do not make
* changes to this file unless you know what you are doing--modify the SWIG
* interface file instead.
* ----------------------------------------------------------------------------- */
#ifdef __cplusplus
/* SwigValueWrapper is described in swig.swg */
template<typename T> class SwigValueWrapper {
struct SwigMovePointer {
T *ptr;
SwigMovePointer(T *p) : ptr(p) { }
~SwigMovePointer() { delete ptr; }
SwigMovePointer& operator=(SwigMovePointer& rhs) { T* oldptr = ptr; ptr = 0; delete oldptr; ptr = rhs.ptr; rhs.ptr = 0; return *this; }
} pointer;
SwigValueWrapper& operator=(const SwigValueWrapper<T>& rhs);
SwigValueWrapper(const SwigValueWrapper<T>& rhs);
public:
SwigValueWrapper() : pointer(0) { }
SwigValueWrapper& operator=(const T& t) { SwigMovePointer tmp(new T(t)); pointer = tmp; return *this; }
operator T&() const { return *pointer.ptr; }
T *operator&() { return pointer.ptr; }
};
template <typename T> T SwigValueInit() {
return T();
}
#endif
/* -----------------------------------------------------------------------------
* This section contains generic SWIG labels for method/variable
* declarations/attributes, and other compiler dependent labels.
* ----------------------------------------------------------------------------- */
/* template workaround for compilers that cannot correctly implement the C++ standard */
#ifndef SWIGTEMPLATEDISAMBIGUATOR
# if defined(__SUNPRO_CC) && (__SUNPRO_CC <= 0x560)
# define SWIGTEMPLATEDISAMBIGUATOR template
# elif defined(__HP_aCC)
/* Needed even with `aCC -AA' when `aCC -V' reports HP ANSI C++ B3910B A.03.55 */
/* If we find a maximum version that requires this, the test would be __HP_aCC <= 35500 for A.03.55 */
# define SWIGTEMPLATEDISAMBIGUATOR template
# else
# define SWIGTEMPLATEDISAMBIGUATOR
# endif
#endif
/* inline attribute */
#ifndef SWIGINLINE
# if defined(__cplusplus) || (defined(__GNUC__) && !defined(__STRICT_ANSI__))
# define SWIGINLINE inline
# else
# define SWIGINLINE
# endif
#endif
/* attribute recognised by some compilers to avoid 'unused' warnings */
#ifndef SWIGUNUSED
# if defined(__GNUC__)
# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))
# define SWIGUNUSED __attribute__ ((__unused__))
# else
# define SWIGUNUSED
# endif
# elif defined(__ICC)
# define SWIGUNUSED __attribute__ ((__unused__))
# else
# define SWIGUNUSED
# endif
#endif
#ifndef SWIG_MSC_UNSUPPRESS_4505
# if defined(_MSC_VER)
# pragma warning(disable : 4505) /* unreferenced local function has been removed */
# endif
#endif
#ifndef SWIGUNUSEDPARM
# ifdef __cplusplus
# define SWIGUNUSEDPARM(p)
# else
# define SWIGUNUSEDPARM(p) p SWIGUNUSED
# endif
#endif
/* internal SWIG method */
#ifndef SWIGINTERN
# define SWIGINTERN static SWIGUNUSED
#endif
/* internal inline SWIG method */
#ifndef SWIGINTERNINLINE
# define SWIGINTERNINLINE SWIGINTERN SWIGINLINE
#endif
/* exporting methods */
#if (__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)
# ifndef GCC_HASCLASSVISIBILITY
# define GCC_HASCLASSVISIBILITY
# endif
#endif
#ifndef SWIGEXPORT
# if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)
# if defined(STATIC_LINKED)
# define SWIGEXPORT
# else
# define SWIGEXPORT __declspec(dllexport)
# endif
# else
# if defined(__GNUC__) && defined(GCC_HASCLASSVISIBILITY)
# define SWIGEXPORT __attribute__ ((visibility("default")))
# else
# define SWIGEXPORT
# endif
# endif
#endif
/* calling conventions for Windows */
#ifndef SWIGSTDCALL
# if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)
# define SWIGSTDCALL __stdcall
# else
# define SWIGSTDCALL
# endif
#endif
/* Deal with Microsoft's attempt at deprecating C standard runtime functions */
#if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE)
# define _CRT_SECURE_NO_DEPRECATE
#endif
/* Deal with Microsoft's attempt at deprecating methods in the standard C++ library */
#if !defined(SWIG_NO_SCL_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_SCL_SECURE_NO_DEPRECATE)
# define _SCL_SECURE_NO_DEPRECATE
#endif
/* -----------------------------------------------------------------------------
* clabels.swg
*
* Definitions of C specific preprocessor symbols.
* ----------------------------------------------------------------------------- */
// this is used instead of default SWIGEXPORT symbol
#ifndef SWIGEXPORTC
# if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) || defined(__APPLE__)
# define SWIGEXPORTC
# else
# if defined(__GNUC__) && defined(GCC_HASCLASSVISIBILITY)
# define SWIGEXPORTC __attribute__ ((visibility("default")))
# else
# define SWIGEXPORTC
# endif
# endif
#endif
#ifndef SWIGPROTECT
# if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) || defined(__APPLE__)
# define SWIGPROTECT(x)
# else
# if defined(__GNUC__) && defined(GCC_HASCLASSVISIBILITY)
# define SWIGPROTECT(x) __attribute__ ((visibility("protected"))) x
# else
# define SWIGPROTECT(x)
# endif
# endif
#endif
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <setjmp.h>
#define SWIG_STR(x) #x
#define SWIG_contract_assert(expr, msg) if(!(expr)) { printf("%s\n", msg); SWIG_exit(0); } else
typedef struct {
void *obj;
const char **typenames;
} SwigObj;
#define SWIG_MAX_RT_STACK 256
#define SWIG_REGISTRY_INIT 256
SWIGINTERN SwigObj **SWIG_registry_base = 0;
SWIGINTERN SwigObj **SWIG_registry = 0;
SWIGINTERN int SWIG_registry_size = SWIG_REGISTRY_INIT;
SWIGINTERN SwigObj *SWIG_create_object(const char *classname);
SWIGINTERN void SWIG_destroy_object(SwigObj *object);
SWIGINTERN void SWIG_free_SwigObj(SwigObj *object);
SWIGEXPORTC struct SWIG_exc_struct {
int code;
char *msg;
SwigObj *klass;
int handled;
} SWIG_exc = { 0, 0, 0, 0 };
SWIGEXPORTC jmp_buf SWIG_rt_env;
SWIGEXPORTC int SWIG_rt_init = 0;
SWIGINTERN jmp_buf SWIG_cpp_back_env;
SWIGINTERN jmp_buf *SWIG_rt_stack_base = 0;
SWIGINTERN jmp_buf *SWIG_rt_stack_ptr = 0;
SWIGINTERN void SWIG_rt_stack_push() {
// TODO: check for stack overflow
memcpy(SWIG_rt_stack_ptr, SWIG_rt_env, sizeof(SWIG_rt_env));
SWIG_rt_stack_ptr++;
}
SWIGINTERN void SWIG_rt_stack_pop() {
if (SWIG_rt_stack_ptr == SWIG_rt_stack_base)
return;
SWIG_rt_stack_ptr--;
memcpy(SWIG_rt_env, SWIG_rt_stack_ptr, sizeof(SWIG_rt_env));
}
SWIGINTERN void SWIG_add_registry_entry(SwigObj *entry) {
if (SWIG_registry_base == 0) {
SWIG_registry_base = SWIG_registry = (SwigObj **) malloc(SWIG_registry_size * sizeof(SwigObj *));
memset(SWIG_registry_base, 0, SWIG_registry_size * sizeof(SwigObj *));
}
*SWIG_registry = entry;
SWIG_registry++;
if ((SWIG_registry - SWIG_registry_base) == SWIG_registry_size) {
SWIG_registry = SWIG_registry_base;
SWIG_registry_size += SWIG_REGISTRY_INIT;
int new_size = SWIG_registry_size * sizeof(SwigObj *);
SWIG_registry_base = (SwigObj **) malloc(new_size);
memset(SWIG_registry_base, 0, new_size);
memcpy(SWIG_registry_base, SWIG_registry, (SWIG_registry_size - SWIG_REGISTRY_INIT) * sizeof(SwigObj *));
free(SWIG_registry);
SWIG_registry = SWIG_registry_base + (SWIG_registry_size - SWIG_REGISTRY_INIT);
}
}
SWIGINTERN void SWIG_remove_registry_entry(SwigObj *entry) {
int i;
for (i = 0; i < SWIG_registry_size; ++i) {
if (*(SWIG_registry_base + i) == entry) {
*(SWIG_registry_base + i) = 0;
break;
}
}
}
SWIGINTERN void SWIG_free_SwigObj(SwigObj *object) {
if (object) {
if (object->typenames)
free(object->typenames);
free(object);
object = (SwigObj *) 0;
}
}
SWIGINTERN void SWIG_cleanup() {
if (SWIG_rt_stack_base)
free(SWIG_rt_stack_base);
if (SWIG_exc.msg)
free(SWIG_exc.msg);
if (SWIG_exc.klass) {
if (SWIG_exc.klass->typenames)
free(SWIG_exc.klass->typenames);
free(SWIG_exc.klass);
}
int i;
if (SWIG_registry_base) {
for (i = 0; i < SWIG_registry_size; ++i) {
if (*(SWIG_registry_base + i)) {
SWIG_free_SwigObj(*(SWIG_registry_base + i));
*(SWIG_registry_base + i) = 0;
}
}
}
free(SWIG_registry_base);
SWIG_registry_base = 0;
}
#ifdef __cplusplus
extern "C" {
#endif
SWIGEXPORTC void SWIG_rt_try() {
SWIG_rt_stack_push();
}
SWIGEXPORTC int SWIG_rt_catch(const char *type) {
int result = 0;
if (!type || (strcmp("SWIG_AnyException", type) == 0)) {
result = 1;
}
else if (SWIG_exc.klass) {
int i = 0;
while (SWIG_exc.klass->typenames[i]) {
if (strcmp(SWIG_exc.klass->typenames[i++], type) == 0) {
result = 1;
break;
}
}
}
if (result) {
SWIG_rt_stack_pop();
SWIG_exc.handled = 1;
}
return result;
}
SWIGEXPORTC void SWIG_rt_throw(SwigObj *klass, const char *msg) {
if (SWIG_exc.msg) {
free(SWIG_exc.msg);
SWIG_exc.msg = (char *) 0;
}
if (msg) {
SWIG_exc.msg = (char *) malloc(strlen(msg) + 1);
strcpy(SWIG_exc.msg, msg);
}
SWIG_exc.klass = klass;
SWIG_exc.handled = 0;
longjmp(SWIG_rt_env, 1);
}
SWIGEXPORTC void SWIG_rt_unhandled() {
if (SWIG_exc.msg) {
free(SWIG_exc.msg);
SWIG_exc.msg = 0;
}
SWIG_rt_stack_pop();
longjmp(SWIG_rt_env, SWIG_exc.code);
}
SWIGEXPORTC void SWIG_rt_endtry() {
if (SWIG_exc.handled) {
if (setjmp(SWIG_rt_env) == 0) {
SWIG_rt_stack_push();
longjmp(SWIG_cpp_back_env, 1);
}
}
else {
SWIG_rt_stack_pop(); // pop the SWIG_try context
}
}
SWIGEXPORTC int SWIG_exit(int code) {
SWIG_cleanup();
exit(code);
}
#ifdef __cplusplus
}
#endif
SWIGINTERN void SWIG_terminate() {
fprintf(stderr, "Unhandled exception: %s\n%s\nExitting...\n",
SWIG_exc.klass->typenames[0],
SWIG_exc.msg ? SWIG_exc.msg : "");
SWIG_exit(SWIG_exc.code);
}
SWIGINTERN void SWIG_runtime_init() {
int i, code;
if (!SWIG_rt_init) {
SWIG_rt_init = 1;
SWIG_rt_stack_base = SWIG_rt_stack_ptr = (jmp_buf *) malloc(sizeof(jmp_buf) * SWIG_MAX_RT_STACK);
if (SWIG_exc.code = setjmp(SWIG_rt_env)) {
// deallocate C++ exception
if (setjmp(SWIG_rt_env) == 0) {
SWIG_rt_stack_push();
SWIG_exc.handled = 1;
longjmp(SWIG_cpp_back_env, 1);
}
SWIG_terminate();
}
}
}
#define SWIG_CThrowException(klass, msg) \
if (setjmp(SWIG_cpp_back_env) == 0) \
SWIG_rt_throw((SwigObj *) klass, msg);
SwigObj *SWIG_temporary = (SwigObj *) malloc(sizeof(SwigObj));
/* Includes the header in the wrapper code */
#include "TrafficMonitor.h"
const char* Swig_typename_FlightData = "FlightData";
const char* Swig_typename_TrafficMonitor = "TrafficMonitor";
SWIGINTERN SwigObj *SWIG_create_object(const char *classname) {
SWIG_runtime_init();
SwigObj *result;
result = (SwigObj *) malloc(sizeof(SwigObj));
result->obj = 0;
if (strcmp(classname, "FlightData") == 0) {
result->typenames = (const char **) malloc(2*sizeof(const char*));
result->typenames[0] = Swig_typename_FlightData;
result->typenames[1] = 0;
}
if (strcmp(classname, "TrafficMonitor") == 0) {
result->typenames = (const char **) malloc(2*sizeof(const char*));
result->typenames[0] = Swig_typename_TrafficMonitor;
result->typenames[1] = 0;
}
SWIG_add_registry_entry(result);
return result;
}
SWIGINTERN void SWIG_destroy_object(SwigObj *object) {
if (object) {
if (object->typenames) {
if (strcmp(object->typenames[0], "FlightData") == 0) {
if (object->obj)
delete (FlightData *) (object->obj);
}
if (strcmp(object->typenames[0], "TrafficMonitor") == 0) {
if (object->obj)
delete (TrafficMonitor *) (object->obj);
}
SWIG_free_SwigObj(object);
}
}
}
#ifdef __cplusplus
extern "C" {
#endif
SWIGEXPORTC void _wrap_FlightData_paramData_set(SwigObj * carg1, SwigObj * carg2) {
FlightData *arg1 = (FlightData *) 0 ;
ParameterData arg2 ;
{
if (carg1)
arg1 = (FlightData *) carg1->obj;
}
{
arg2 = *(ParameterData *) (carg2->obj);
}
if (arg1) (arg1)->paramData = arg2;
}
SWIGEXPORTC SwigObj * _wrap_FlightData_paramData_get(SwigObj * carg1) {
ParameterData * cppresult;
FlightData *arg1 = (FlightData *) 0 ;
SwigObj * result;
{
if (carg1)
arg1 = (FlightData *) carg1->obj;
}
{
const ParameterData &_result_ref = ((arg1)->paramData);cppresult = (ParameterData*) &_result_ref;
}
{
result = (SwigObj*) SWIG_create_object(SWIG_STR(ParameterData));
result->obj = (void*) &cppresult;
}
return result;
}
SWIGEXPORTC SwigObj * _wrap_new_FlightData(/*aaa*/ char * carg1) {
char *arg1 ;
SwigObj * result;
arg1 = (char *) carg1;
result = SWIG_create_object("FlightData");
result->obj = (void*) new FlightData(arg1);
return result;
}
SWIGEXPORTC void _wrap_FlightData_AddMissionItem(SwigObj * carg1, SwigObj * carg2) {
FlightData *arg1 = (FlightData *) 0 ;
waypoint_t *arg2 = (waypoint_t *) 0 ;
{
if (carg1)
arg1 = (FlightData *) carg1->obj;
}
{
if (carg2)
arg2 = (waypoint_t *) carg2->obj;
}
(arg1)->AddMissionItem(arg2);
}
SWIGEXPORTC void _wrap_FlightData_AddResolutionItem(SwigObj * carg1, SwigObj * carg2) {
FlightData *arg1 = (FlightData *) 0 ;
waypoint_t *arg2 = (waypoint_t *) 0 ;
{
if (carg1)
arg1 = (FlightData *) carg1->obj;
}
{
if (carg2)
arg2 = (waypoint_t *) carg2->obj;
}
(arg1)->AddResolutionItem(arg2);
}
SWIGEXPORTC void _wrap_FlightData_SetStartMissionFlag(SwigObj * carg1, SwigObj * carg2) {
FlightData *arg1 = (FlightData *) 0 ;
uint8_t arg2 ;
{
if (carg1)
arg1 = (FlightData *) carg1->obj;
}
{
arg2 = *(uint8_t *) (carg2->obj);
}
(arg1)->SetStartMissionFlag(arg2);
}
SWIGEXPORTC void _wrap_FlightData_ConstructMissionPlan(SwigObj * carg1) {
FlightData *arg1 = (FlightData *) 0 ;
{
if (carg1)
arg1 = (FlightData *) carg1->obj;
}
(arg1)->ConstructMissionPlan();
}
SWIGEXPORTC void _wrap_FlightData_ConstructResolutionPlan(SwigObj * carg1) {
FlightData *arg1 = (FlightData *) 0 ;
{
if (carg1)
arg1 = (FlightData *) carg1->obj;
}
(arg1)->ConstructResolutionPlan();
}
SWIGEXPORTC void _wrap_FlightData_InputState(SwigObj * carg1, double carg2, double carg3, double carg4, double carg5, double carg6, double carg7, double carg8) {
FlightData *arg1 = (FlightData *) 0 ;
double arg2 ;
double arg3 ;
double arg4 ;
double arg5 ;
double arg6 ;
double arg7 ;
double arg8 ;
{
if (carg1)
arg1 = (FlightData *) carg1->obj;
}
arg2 = (double) carg2;
arg3 = (double) carg3;
arg4 = (double) carg4;
arg5 = (double) carg5;
arg6 = (double) carg6;
arg7 = (double) carg7;
arg8 = (double) carg8;
(arg1)->InputState(arg2,arg3,arg4,arg5,arg6,arg7,arg8);
}
SWIGEXPORTC void _wrap_FlightData_AddTraffic(SwigObj * carg1, int carg2, double carg3, double carg4, double carg5, double carg6, double carg7, double carg8) {
FlightData *arg1 = (FlightData *) 0 ;
int arg2 ;
double arg3 ;
double arg4 ;
double arg5 ;
double arg6 ;
double arg7 ;
double arg8 ;
{
if (carg1)
arg1 = (FlightData *) carg1->obj;
}
arg2 = (int) carg2;
arg3 = (double) carg3;
arg4 = (double) carg4;
arg5 = (double) carg5;
arg6 = (double) carg6;
arg7 = (double) carg7;
arg8 = (double) carg8;
(arg1)->AddTraffic(arg2,arg3,arg4,arg5,arg6,arg7,arg8);
}
SWIGEXPORTC void _wrap_FlightData_GetTraffic_pFlightData_i_pd_pd_pd_pd_pd_pd(SwigObj * carg1, int carg2, double * carg3, double * carg4, double * carg5, double * carg6, double * carg7, double * carg8) {
FlightData *arg1 = (FlightData *) 0 ;
int arg2 ;
double *arg3 = (double *) 0 ;
double *arg4 = (double *) 0 ;
double *arg5 = (double *) 0 ;
double *arg6 = (double *) 0 ;
double *arg7 = (double *) 0 ;
double *arg8 = (double *) 0 ;
{
if (carg1)
arg1 = (FlightData *) carg1->obj;
}
arg2 = (int) carg2;
arg3 = (double *) carg3;
arg4 = (double *) carg4;
arg5 = (double *) carg5;
arg6 = (double *) carg6;
arg7 = (double *) carg7;
arg8 = (double *) carg8;
(arg1)->GetTraffic(arg2,arg3,arg4,arg5,arg6,arg7,arg8);
}
SWIGEXPORTC void _wrap_FlightData_ClearMissionList(SwigObj * carg1) {
FlightData *arg1 = (FlightData *) 0 ;
{
if (carg1)
arg1 = (FlightData *) carg1->obj;
}
(arg1)->ClearMissionList();
}
SWIGEXPORTC void _wrap_FlightData_ClearResolutionList(SwigObj * carg1) {
FlightData *arg1 = (FlightData *) 0 ;
{
if (carg1)
arg1 = (FlightData *) carg1->obj;
}
(arg1)->ClearResolutionList();
}
SWIGEXPORTC void _wrap_FlightData_ClearFenceList(SwigObj * carg1) {
FlightData *arg1 = (FlightData *) 0 ;
{
if (carg1)
arg1 = (FlightData *) carg1->obj;
}
(arg1)->ClearFenceList();
}
SWIGEXPORTC void _wrap_FlightData_InputNextMissionWP(SwigObj * carg1, int carg2) {
FlightData *arg1 = (FlightData *) 0 ;
int arg2 ;
{
if (carg1)
arg1 = (FlightData *) carg1->obj;
}
arg2 = (int) carg2;
(arg1)->InputNextMissionWP(arg2);
}
SWIGEXPORTC void _wrap_FlightData_InputNextResolutionWP(SwigObj * carg1, int carg2) {
FlightData *arg1 = (FlightData *) 0 ;
int arg2 ;
{
if (carg1)
arg1 = (FlightData *) carg1->obj;
}
arg2 = (int) carg2;
(arg1)->InputNextResolutionWP(arg2);
}
SWIGEXPORTC void _wrap_FlightData_InputTakeoffAlt(SwigObj * carg1, double carg2) {
FlightData *arg1 = (FlightData *) 0 ;
double arg2 ;
{
if (carg1)
arg1 = (FlightData *) carg1->obj;
}
arg2 = (double) carg2;
(arg1)->InputTakeoffAlt(arg2);
}
SWIGEXPORTC void _wrap_FlightData_InputCruisingAlt(SwigObj * carg1, double carg2) {
FlightData *arg1 = (FlightData *) 0 ;
double arg2 ;
{
if (carg1)
arg1 = (FlightData *) carg1->obj;
}
arg2 = (double) carg2;
(arg1)->InputCruisingAlt(arg2);
}
SWIGEXPORTC void _wrap_FlightData_InputGeofenceData(SwigObj * carg1, SwigObj * carg2) {
FlightData *arg1 = (FlightData *) 0 ;
geofence_t *arg2 = (geofence_t *) 0 ;
{
if (carg1)
arg1 = (FlightData *) carg1->obj;
}
{
if (carg2)
arg2 = (geofence_t *) carg2->obj;
}
(arg1)->InputGeofenceData(arg2);
}
SWIGEXPORTC double _wrap_FlightData_GetTakeoffAlt(SwigObj * carg1) {
double cppresult;
FlightData *arg1 = (FlightData *) 0 ;
double result;
{
if (carg1)
arg1 = (FlightData *) carg1->obj;
}
cppresult = (double)(arg1)->GetTakeoffAlt();
result = cppresult;
return result;
}
SWIGEXPORTC double _wrap_FlightData_GetCruisingAlt(SwigObj * carg1) {
double cppresult;
FlightData *arg1 = (FlightData *) 0 ;
double result;
{
if (carg1)
arg1 = (FlightData *) carg1->obj;
}
cppresult = (double)(arg1)->GetCruisingAlt();
result = cppresult;
return result;
}
SWIGEXPORTC double _wrap_FlightData_GetAltitude(SwigObj * carg1) {
double cppresult;
FlightData *arg1 = (FlightData *) 0 ;
double result;
{
if (carg1)
arg1 = (FlightData *) carg1->obj;
}
cppresult = (double)(arg1)->GetAltitude();
result = cppresult;
return result;
}
SWIGEXPORTC double _wrap_FlightData_GetAllowedXtracDeviation(SwigObj * carg1) {
double cppresult;
FlightData *arg1 = (FlightData *) 0 ;
double result;
{
if (carg1)
arg1 = (FlightData *) carg1->obj;
}
cppresult = (double)(arg1)->GetAllowedXtracDeviation();
result = cppresult;
return result;
}
SWIGEXPORTC double _wrap_FlightData_GetResolutionSpeed(SwigObj * carg1) {
double cppresult;
FlightData *arg1 = (FlightData *) 0 ;
double result;
{
if (carg1)
arg1 = (FlightData *) carg1->obj;
}
cppresult = (double)(arg1)->GetResolutionSpeed();
result = cppresult;
return result;
}
SWIGEXPORTC int _wrap_FlightData_GetTotalMissionWP(SwigObj * carg1) {
int cppresult;
FlightData *arg1 = (FlightData *) 0 ;
int result;
{
if (carg1)
arg1 = (FlightData *) carg1->obj;
}
cppresult = (int)(arg1)->GetTotalMissionWP();
result = cppresult;
return result;
}
SWIGEXPORTC int _wrap_FlightData_GetTotalResolutionWP(SwigObj * carg1) {
int cppresult;
FlightData *arg1 = (FlightData *) 0 ;
int result;
{
if (carg1)
arg1 = (FlightData *) carg1->obj;
}
cppresult = (int)(arg1)->GetTotalResolutionWP();
result = cppresult;
return result;
}
SWIGEXPORTC int _wrap_FlightData_GetTotalTraffic(SwigObj * carg1) {
int cppresult;
FlightData *arg1 = (FlightData *) 0 ;
int result;
{
if (carg1)
arg1 = (FlightData *) carg1->obj;
}
cppresult = (int)(arg1)->GetTotalTraffic();
result = cppresult;
return result;
}
SWIGEXPORTC void _wrap_FlightData_Reset(SwigObj * carg1) {
FlightData *arg1 = (FlightData *) 0 ;
{
if (carg1)
arg1 = (FlightData *) carg1->obj;
}
(arg1)->Reset();
}
SWIGEXPORTC void _wrap_FlightData_InputAck(SwigObj * carg1, SwigObj * carg2) {
FlightData *arg1 = (FlightData *) 0 ;
CmdAck_t *arg2 = (CmdAck_t *) 0 ;
{
if (carg1)
arg1 = (FlightData *) carg1->obj;
}
{
if (carg2)
arg2 = (CmdAck_t *) carg2->obj;
}
(arg1)->InputAck(arg2);
}
SWIGEXPORTC bool _wrap_FlightData_CheckAck(SwigObj * carg1, SwigObj * carg2) {
bool cppresult;
FlightData *arg1 = (FlightData *) 0 ;
command_name_t arg2 ;
bool result;
{
if (carg1)
arg1 = (FlightData *) carg1->obj;
}
{
arg2 = *(command_name_t *) (carg2->obj);
}
cppresult = (bool)(arg1)->CheckAck(arg2);
result = (bool) cppresult;
return result;
}
SWIGEXPORTC SwigObj * _wrap_FlightData_GetStartMissionFlag(SwigObj * carg1) {
int8_t * cppresult;
FlightData *arg1 = (FlightData *) 0 ;
SwigObj * result;
{
if (carg1)
arg1 = (FlightData *) carg1->obj;
}
{
const int8_t &_result_ref = (arg1)->GetStartMissionFlag();cppresult = (int8_t*) &_result_ref;
}
{
result = (SwigObj*) SWIG_create_object(SWIG_STR(int8_t));
result->obj = (void*) &cppresult;
}
return result;
}
SWIGEXPORTC SwigObj * _wrap_FlightData_GetMissionPlanSize(SwigObj * carg1) {
uint16_t * cppresult;
FlightData *arg1 = (FlightData *) 0 ;
SwigObj * result;
{
if (carg1)
arg1 = (FlightData *) carg1->obj;
}
{
const uint16_t &_result_ref = (arg1)->GetMissionPlanSize();cppresult = (uint16_t*) &_result_ref;
}
{
result = (SwigObj*) SWIG_create_object(SWIG_STR(uint16_t));
result->obj = (void*) &cppresult;
}
return result;
}
SWIGEXPORTC SwigObj * _wrap_FlightData_GetResolutionPlanSize(SwigObj * carg1) {
uint16_t * cppresult;
FlightData *arg1 = (FlightData *) 0 ;
SwigObj * result;
{
if (carg1)
arg1 = (FlightData *) carg1->obj;
}
{
const uint16_t &_result_ref = (arg1)->GetResolutionPlanSize();cppresult = (uint16_t*) &_result_ref;
}
{
result = (SwigObj*) SWIG_create_object(SWIG_STR(uint16_t));
result->obj = (void*) &cppresult;
}
return result;
}
SWIGEXPORTC SwigObj * _wrap_FlightData_GetNextMissionWP(SwigObj * carg1) {
uint16_t * cppresult;
FlightData *arg1 = (FlightData *) 0 ;
SwigObj * result;
{
if (carg1)
arg1 = (FlightData *) carg1->obj;
}
{
const uint16_t &_result_ref = (arg1)->GetNextMissionWP();cppresult = (uint16_t*) &_result_ref;
}
{
result = (SwigObj*) SWIG_create_object(SWIG_STR(uint16_t));
result->obj = (void*) &cppresult;
}
return result;
}
SWIGEXPORTC SwigObj * _wrap_FlightData_GetNextResolutionWP(SwigObj * carg1) {
uint16_t * cppresult;
FlightData *arg1 = (FlightData *) 0 ;
SwigObj * result;
{
if (carg1)
arg1 = (FlightData *) carg1->obj;
}
{
const uint16_t &_result_ref = (arg1)->GetNextResolutionWP();cppresult = (uint16_t*) &_result_ref;
}
{
result = (SwigObj*) SWIG_create_object(SWIG_STR(uint16_t));
result->obj = (void*) &cppresult;
}
return result;
}
SWIGEXPORTC int _wrap_FlightData_GetTrafficResolutionType(SwigObj * carg1) {
int cppresult;
FlightData *arg1 = (FlightData *) 0 ;
int result;
{
if (carg1)
arg1 = (FlightData *) carg1->obj;
}
cppresult = (int)(arg1)->GetTrafficResolutionType();
result = cppresult;
return result;
}
SWIGEXPORTC int _wrap_FlightData_GetTotalFences(SwigObj * carg1) {
int cppresult;
FlightData *arg1 = (FlightData *) 0 ;
int result;
{
if (carg1)
arg1 = (FlightData *) carg1->obj;
}
cppresult = (int)(arg1)->GetTotalFences();
result = cppresult;
return result;
}
SWIGEXPORTC double _wrap_FlightData_getFlightPlanSpeed(SwigObj * carg1, SwigObj * carg2, int carg3) {
double cppresult;
FlightData *arg1 = (FlightData *) 0 ;
Plan *arg2 = (Plan *) 0 ;
int arg3 ;
double result;
{
if (carg1)
arg1 = (FlightData *) carg1->obj;
}
{
if (carg2)
arg2 = (Plan *) carg2->obj;
}
arg3 = (int) carg3;
cppresult = (double)(arg1)->getFlightPlanSpeed(arg2,arg3);
result = cppresult;
return result;
}
SWIGEXPORTC void _wrap_FlightData_GetTraffic_pFlightData_i_rlarcfm_Position_rlarcfm_Velocity(SwigObj * carg1, int carg2, SwigObj * carg3, SwigObj * carg4) {
FlightData *arg1 = (FlightData *) 0 ;
int arg2 ;
larcfm::Position *arg3 = 0 ;
larcfm::Velocity *arg4 = 0 ;
{
if (carg1)
arg1 = (FlightData *) carg1->obj;
}
arg2 = (int) carg2;
{
if (carg3)
arg3 = (larcfm::Position *) carg3->obj;
else
arg3 = (larcfm::Position *) 0;
}
{
if (carg4)
arg4 = (larcfm::Velocity *) carg4->obj;
else
arg4 = (larcfm::Velocity *) 0;
}
(arg1)->GetTraffic(arg2,*arg3,*arg4);
}
SWIGEXPORTC /*aaaaaa*/SwigObj * _wrap_FlightData_GetGeofence(SwigObj * carg1, int carg2) {
fence * cppresult;
FlightData *arg1 = (FlightData *) 0 ;
int arg2 ;
/*aaaaaa*/SwigObj * result;
{
if (carg1)
arg1 = (FlightData *) carg1->obj;
}
arg2 = (int) carg2;
cppresult = (fence *)(arg1)->GetGeofence(arg2);
{
result = (SwigObj*) SWIG_create_object(SWIG_STR(fence));
result->obj = (void*) cppresult;
}
return result;
}
SWIGEXPORTC /*aaaaaa*/SwigObj * _wrap_FlightData_GetPolyPath(SwigObj * carg1) {
PolyPath * cppresult;
FlightData *arg1 = (FlightData *) 0 ;
/*aaaaaa*/SwigObj * result;
{
if (carg1)
arg1 = (FlightData *) carg1->obj;
}
cppresult = (PolyPath *)(arg1)->GetPolyPath();
{
result = (SwigObj*) SWIG_create_object(SWIG_STR(PolyPath));
result->obj = (void*) cppresult;
}
return result;
}
SWIGEXPORTC void _wrap_delete_FlightData(SwigObj * carg1) {
SWIG_remove_registry_entry(carg1);
SWIG_destroy_object(carg1);
}
SWIGEXPORTC void _wrap_TrafficMonitor_DAA_set(SwigObj * carg1, SwigObj * carg2) {
TrafficMonitor *arg1 = (TrafficMonitor *) 0 ;
larcfm::Daidalus arg2 ;
{
if (carg1)
arg1 = (TrafficMonitor *) carg1->obj;
}
{
arg2 = *(larcfm::Daidalus *) (carg2->obj);
}
if (arg1) (arg1)->DAA = arg2;
}
SWIGEXPORTC SwigObj * _wrap_TrafficMonitor_DAA_get(SwigObj * carg1) {
larcfm::Daidalus * cppresult;
TrafficMonitor *arg1 = (TrafficMonitor *) 0 ;
SwigObj * result;
{
if (carg1)
arg1 = (TrafficMonitor *) carg1->obj;
}
{
const larcfm::Daidalus &_result_ref = ((arg1)->DAA);cppresult = (larcfm::Daidalus*) &_result_ref;
}
{
result = (SwigObj*) SWIG_create_object(SWIG_STR(larcfm::Daidalus));
result->obj = (void*) &cppresult;
}
return result;
}
SWIGEXPORTC void _wrap_TrafficMonitor_KMB_set(SwigObj * carg1, SwigObj * carg2) {
TrafficMonitor *arg1 = (TrafficMonitor *) 0 ;
larcfm::KinematicMultiBands arg2 ;
{
if (carg1)
arg1 = (TrafficMonitor *) carg1->obj;
}
{
arg2 = *(larcfm::KinematicMultiBands *) (carg2->obj);
}
if (arg1) (arg1)->KMB = arg2;
}
SWIGEXPORTC SwigObj * _wrap_TrafficMonitor_KMB_get(SwigObj * carg1) {
larcfm::KinematicMultiBands * cppresult;
TrafficMonitor *arg1 = (TrafficMonitor *) 0 ;
SwigObj * result;
{
if (carg1)
arg1 = (TrafficMonitor *) carg1->obj;
}
{
const larcfm::KinematicMultiBands &_result_ref = ((arg1)->KMB);cppresult = (larcfm::KinematicMultiBands*) &_result_ref;
}
{
result = (SwigObj*) SWIG_create_object(SWIG_STR(larcfm::KinematicMultiBands));
result->obj = (void*) &cppresult;
}
return result;
}
SWIGEXPORTC SwigObj * _wrap_new_TrafficMonitor(SwigObj * carg1) {
FlightData *arg1 = (FlightData *) 0 ;
SwigObj * result;
{
if (carg1)
arg1 = (FlightData *) carg1->obj;
}
result = SWIG_create_object("TrafficMonitor");
result->obj = (void*) new TrafficMonitor(arg1);
return result;
}
SWIGEXPORTC bool _wrap_TrafficMonitor_CheckTurnConflict(SwigObj * carg1, double carg2, double carg3, double carg4, double carg5) {
bool cppresult;
TrafficMonitor *arg1 = (TrafficMonitor *) 0 ;
double arg2 ;
double arg3 ;
double arg4 ;
double arg5 ;
bool result;
{
if (carg1)
arg1 = (TrafficMonitor *) carg1->obj;
}
arg2 = (double) carg2;
arg3 = (double) carg3;
arg4 = (double) carg4;
arg5 = (double) carg5;
cppresult = (bool)(arg1)->CheckTurnConflict(arg2,arg3,arg4,arg5);
result = (bool) cppresult;
return result;
}
SWIGEXPORTC bool _wrap_TrafficMonitor_MonitorTraffic(SwigObj * carg1, bool carg2, double carg3, /*aaa*/ double * carg4, /*aaa*/ double * carg5, /*aaa*/ double * carg6, SwigObj * carg7) {
bool cppresult;
TrafficMonitor *arg1 = (TrafficMonitor *) 0 ;
bool arg2 ;
double arg3 ;
double *arg4 ;
double *arg5 ;
double *arg6 ;
visbands_t *arg7 = (visbands_t *) 0 ;
bool result;
{
if (carg1)
arg1 = (TrafficMonitor *) carg1->obj;
}
arg2 = (bool) carg2;
arg3 = (double) carg3;
arg4 = (double *) carg4;
arg5 = (double *) carg5;
arg6 = (double *) carg6;
{
if (carg7)
arg7 = (visbands_t *) carg7->obj;
}
cppresult = (bool)(arg1)->MonitorTraffic(arg2,arg3,arg4,arg5,arg6,arg7);
result = (bool) cppresult;
return result;
}
SWIGEXPORTC void _wrap_TrafficMonitor_GetVisualizationBands(SwigObj * carg1, SwigObj * carg2) {
TrafficMonitor *arg1 = (TrafficMonitor *) 0 ;
visbands_t *arg2 = 0 ;
{
if (carg1)
arg1 = (TrafficMonitor *) carg1->obj;
}
{
if (carg2)
arg2 = (visbands_t *) carg2->obj;
else
arg2 = (visbands_t *) 0;
}
(arg1)->GetVisualizationBands(*arg2);
}
SWIGEXPORTC bool _wrap_TrafficMonitor_CheckSafeToTurn(SwigObj * carg1, /*aaa*/ double * carg2, /*aaa*/ double * carg3, double carg4, double carg5) {
bool cppresult;
TrafficMonitor *arg1 = (TrafficMonitor *) 0 ;
double *arg2 ;
double *arg3 ;
double arg4 ;
double arg5 ;
bool result;
{
if (carg1)
arg1 = (TrafficMonitor *) carg1->obj;
}
arg2 = (double *) carg2;
arg3 = (double *) carg3;
arg4 = (double) carg4;
arg5 = (double) carg5;
cppresult = (bool)(arg1)->CheckSafeToTurn(arg2,arg3,arg4,arg5);
result = (bool) cppresult;
return result;
}
SWIGEXPORTC void _wrap_delete_TrafficMonitor(SwigObj * carg1) {
SWIG_remove_registry_entry(carg1);
SWIG_destroy_object(carg1);
}
#ifdef __cplusplus
}
#endif
| 25.131098 | 204 | 0.622983 | [
"object"
] |
2dee388a01f55d8a0a60186c942325034cbaabec | 20,326 | hpp | C++ | include/dca/phys/domains/cluster/interpolation/deprecated/wannier_interpolation/wannier_interpolation_kernel.hpp | PMDee/DCA | a8196ec3c88d07944e0499ff00358ea3c830b329 | [
"BSD-3-Clause"
] | 27 | 2018-08-02T04:28:23.000Z | 2021-07-08T02:14:20.000Z | include/dca/phys/domains/cluster/interpolation/deprecated/wannier_interpolation/wannier_interpolation_kernel.hpp | PMDee/DCA | a8196ec3c88d07944e0499ff00358ea3c830b329 | [
"BSD-3-Clause"
] | 200 | 2018-08-02T18:19:03.000Z | 2022-03-16T21:28:41.000Z | include/dca/phys/domains/cluster/interpolation/deprecated/wannier_interpolation/wannier_interpolation_kernel.hpp | PMDee/DCA | a8196ec3c88d07944e0499ff00358ea3c830b329 | [
"BSD-3-Clause"
] | 22 | 2018-08-15T15:50:00.000Z | 2021-09-30T13:41:46.000Z | // Copyright (C) 2018 ETH Zurich
// Copyright (C) 2018 UT-Battelle, LLC
// All rights reserved.
//
// See LICENSE for terms of usage.
// See CITATION.md for citation guidelines, if DCA++ is used for scientific publications.
//
// Author: Peter Staar (taa@zurich.ibm.com)
//
// This class implements the Wannier interpolation kernel using the NFFT library.
#ifndef DCA_PHYS_DOMAINS_CLUSTER_INTERPOLATION_WANNIER_INTERPOLATION_WANNIER_INTERPOLATION_KERNEL_HPP
#define DCA_PHYS_DOMAINS_CLUSTER_INTERPOLATION_WANNIER_INTERPOLATION_WANNIER_INTERPOLATION_KERNEL_HPP
#include <cassert>
#include <complex>
#include <iostream>
#include <stdexcept>
#include <vector>
#include <nfft3.h>
#include "dca/function/domains.hpp"
#include "dca/function/function.hpp"
#include "dca/math/util/vector_operations.hpp"
#include "dca/phys/domains/cluster/cluster_definitions.hpp"
#include "dca/phys/domains/cluster/cluster_domain.hpp"
namespace dca {
namespace phys {
namespace domains {
// dca::phys::domains::
// Empty template class declaration.
template <typename source_dmn_type, typename target_dmn_type>
class wannier_interpolation_kernel {};
// Template specialization for Wannier interpolation in momentum space.
template <typename scalar_type, int D, CLUSTER_NAMES N, CLUSTER_SHAPE S, typename target_dmn_type>
class wannier_interpolation_kernel<cluster_domain<scalar_type, D, N, MOMENTUM_SPACE, S>, target_dmn_type> {
typedef cluster_domain<scalar_type, D, N, MOMENTUM_SPACE, S> k_cluster_type;
const static int DIMENSION = k_cluster_type::DIMENSION;
typedef typename k_cluster_type::dual_type source_r_cluster_type;
typedef typename k_cluster_type::this_type source_k_cluster_type;
typedef func::dmn_0<source_r_cluster_type> source_r_dmn_t;
typedef func::dmn_0<source_k_cluster_type> source_k_dmn_t;
typedef func::dmn_0<target_dmn_type> target_k_dmn_t;
public:
wannier_interpolation_kernel();
~wannier_interpolation_kernel();
void reset_input();
void reset_output();
void set(std::complex<double>* input_ptr);
void get(std::complex<double>* output_ptr);
void execute(std::complex<double>* input_ptr, std::complex<double>* output_ptr);
std::complex<double>& get_F_r(int i);
private:
// Checks whether the grid size is larger or equal to the size of the source-k-domain.
void check_grid_sizes();
void initialize_centered_r_cluster();
void initialize_nfft_K_2_R();
void initialize_nfft_R_2_k();
void initialize_cut_off();
void FT_to_centered_function_NFFT();
void FT_F_K__to__F_R(std::complex<double>* input_ptr);
void FT_F_R__to__F_k(std::complex<double>* output_ptr);
private:
struct centered_r_cluster {
typedef centered_r_cluster this_type;
typedef std::vector<double> element_type;
static int get_size() {
return get_elements().size();
}
static std::vector<element_type>& get_elements() {
static std::vector<element_type> elements(0);
return elements;
}
};
public:
typedef func::dmn_0<centered_r_cluster> centered_r_cluster_dmn_t;
private:
static bool INITIALIZED;
static func::function<int, centered_r_cluster_dmn_t> lies_within_cutoff;
std::vector<int> grid_size;
nfft_plan nfft_K_2_R;
nfft_plan nfft_R_2_k;
func::function<std::complex<double>, centered_r_cluster_dmn_t> F_R;
};
template <typename scalar_type, int D, CLUSTER_NAMES N, CLUSTER_SHAPE S, typename target_dmn_type>
bool wannier_interpolation_kernel<cluster_domain<scalar_type, D, N, MOMENTUM_SPACE, S>,
target_dmn_type>::INITIALIZED = false;
template <typename scalar_type, int D, CLUSTER_NAMES N, CLUSTER_SHAPE S, typename target_dmn_type>
func::function<int, typename wannier_interpolation_kernel<cluster_domain<scalar_type, D, N, MOMENTUM_SPACE, S>, target_dmn_type>::centered_r_cluster_dmn_t> wannier_interpolation_kernel<
cluster_domain<scalar_type, D, N, MOMENTUM_SPACE, S>,
target_dmn_type>::lies_within_cutoff("cutoff");
template <typename scalar_type, int D, CLUSTER_NAMES N, CLUSTER_SHAPE S, typename target_dmn_type>
wannier_interpolation_kernel<cluster_domain<scalar_type, D, N, MOMENTUM_SPACE, S>,
target_dmn_type>::wannier_interpolation_kernel()
: grid_size(DIMENSION, 32),
nfft_K_2_R(),
nfft_R_2_k(),
F_R("wannier_interpolation_kernel__F_r") {
for (int i = 0; i < DIMENSION; ++i)
grid_size[i] = grid_size[i] <= 4 ? 6 : grid_size[i];
check_grid_sizes();
if (!INITIALIZED) {
initialize_centered_r_cluster();
// Reset functions since their domain has changed.
F_R.reset();
lies_within_cutoff.reset();
initialize_cut_off();
INITIALIZED = true;
}
initialize_nfft_K_2_R();
initialize_nfft_R_2_k();
}
template <typename scalar_type, int D, CLUSTER_NAMES N, CLUSTER_SHAPE S, typename target_dmn_type>
wannier_interpolation_kernel<cluster_domain<scalar_type, D, N, MOMENTUM_SPACE, S>,
target_dmn_type>::~wannier_interpolation_kernel() {
nfft_finalize(&nfft_K_2_R);
nfft_finalize(&nfft_R_2_k);
}
template <typename scalar_type, int D, CLUSTER_NAMES N, CLUSTER_SHAPE S, typename target_dmn_type>
void wannier_interpolation_kernel<cluster_domain<scalar_type, D, N, MOMENTUM_SPACE, S>,
target_dmn_type>::check_grid_sizes() {
int size = 1;
for (int i = 0; i < DIMENSION; ++i)
size *= grid_size[i];
if (size < source_k_dmn_t::dmn_size()) {
std::cout << "\n\n\t INCREASE LDA-grid FOR WANNIER-INTERPOLATION!!! \n\n\n";
throw std::logic_error(__FUNCTION__);
}
}
template <typename scalar_type, int D, CLUSTER_NAMES N, CLUSTER_SHAPE S, typename target_dmn_type>
std::complex<double>& wannier_interpolation_kernel<cluster_domain<scalar_type, D, N, MOMENTUM_SPACE, S>,
target_dmn_type>::get_F_r(int i) {
return F_R(i);
}
template <typename scalar_type, int D, CLUSTER_NAMES N, CLUSTER_SHAPE S, typename target_dmn_type>
void wannier_interpolation_kernel<cluster_domain<scalar_type, D, N, MOMENTUM_SPACE, S>,
target_dmn_type>::reset_input() {
nfft_finalize(&nfft_K_2_R);
initialize_nfft_K_2_R();
}
template <typename scalar_type, int D, CLUSTER_NAMES N, CLUSTER_SHAPE S, typename target_dmn_type>
void wannier_interpolation_kernel<cluster_domain<scalar_type, D, N, MOMENTUM_SPACE, S>,
target_dmn_type>::reset_output() {
nfft_finalize(&nfft_R_2_k);
initialize_nfft_R_2_k();
}
template <typename scalar_type, int D, CLUSTER_NAMES N, CLUSTER_SHAPE S, typename target_dmn_type>
void wannier_interpolation_kernel<cluster_domain<scalar_type, D, N, MOMENTUM_SPACE, S>,
target_dmn_type>::execute(std::complex<double>* input_ptr,
std::complex<double>* output_ptr) {
FT_F_K__to__F_R(input_ptr);
FT_F_R__to__F_k(output_ptr);
}
template <typename scalar_type, int D, CLUSTER_NAMES N, CLUSTER_SHAPE S, typename target_dmn_type>
void wannier_interpolation_kernel<cluster_domain<scalar_type, D, N, MOMENTUM_SPACE, S>,
target_dmn_type>::set(std::complex<double>* input_ptr) {
FT_F_K__to__F_R(input_ptr);
}
template <typename scalar_type, int D, CLUSTER_NAMES N, CLUSTER_SHAPE S, typename target_dmn_type>
void wannier_interpolation_kernel<cluster_domain<scalar_type, D, N, MOMENTUM_SPACE, S>,
target_dmn_type>::get(std::complex<double>* output_ptr) {
FT_F_R__to__F_k(output_ptr);
}
template <typename scalar_type, int D, CLUSTER_NAMES N, CLUSTER_SHAPE S, typename target_dmn_type>
void wannier_interpolation_kernel<cluster_domain<scalar_type, D, N, MOMENTUM_SPACE, S>,
target_dmn_type>::initialize_nfft_K_2_R() {
nfft_init(&nfft_K_2_R, DIMENSION, &grid_size[0], source_k_dmn_t::dmn_size());
std::vector<std::vector<double>>& collection_k_vecs = source_k_dmn_t::get_elements();
std::vector<std::vector<double>> collection_k_vecs_affine(source_k_dmn_t::dmn_size(),
std::vector<double>(DIMENSION, 0));
for (int j = 0; j < source_k_dmn_t::dmn_size(); j++) {
// collection_k_vecs_affine[j] =
// source_k_cluster_type::get_affine_coordinate(collection_k_vecs[j]);
collection_k_vecs_affine[j] = math::util::coordinates(
collection_k_vecs[j], source_k_cluster_type::get_super_basis_vectors());
// math::util::print(collection_k_vecs_affine[j]); cout<<endl;
}
// cout<<endl;
for (int j = 0; j < source_k_dmn_t::dmn_size(); j++) {
for (int i = 0; i < DIMENSION; i++) {
while (collection_k_vecs_affine[j][i] < -1. / 2.)
collection_k_vecs_affine[j][i] += 1.;
while (collection_k_vecs_affine[j][i] > 1. / 2. - 1.e-6)
collection_k_vecs_affine[j][i] -= 1.;
}
}
for (int j = 0; j < source_k_dmn_t::dmn_size(); j++) {
for (int i = 0; i < DIMENSION; i++) {
nfft_K_2_R.x[j * DIMENSION + i] = collection_k_vecs_affine[j][i];
assert(nfft_K_2_R.x[j * DIMENSION + i] >= -0.5 - 1.e-6);
assert(nfft_K_2_R.x[j * DIMENSION + i] < 0.5);
}
}
if (nfft_K_2_R.flags & PRE_ONE_PSI)
nfft_precompute_one_psi(&nfft_K_2_R);
}
template <typename scalar_type, int D, CLUSTER_NAMES N, CLUSTER_SHAPE S, typename target_dmn_type>
void wannier_interpolation_kernel<cluster_domain<scalar_type, D, N, MOMENTUM_SPACE, S>,
target_dmn_type>::initialize_nfft_R_2_k() {
nfft_init(&nfft_R_2_k, DIMENSION, &grid_size[0], target_k_dmn_t::dmn_size());
std::vector<std::vector<double>>& collection_k_vecs = target_k_dmn_t::get_elements();
std::vector<std::vector<double>> collection_k_vecs_affine(target_k_dmn_t::dmn_size(),
std::vector<double>(DIMENSION, 0));
for (int j = 0; j < target_k_dmn_t::dmn_size(); j++) {
collection_k_vecs_affine[j] = math::util::coordinates(
collection_k_vecs[j], source_k_cluster_type::get_super_basis_vectors());
}
for (int j = 0; j < target_k_dmn_t::dmn_size(); j++) {
for (int i = 0; i < DIMENSION; i++) {
while (collection_k_vecs_affine[j][i] < -1. / 2.)
collection_k_vecs_affine[j][i] += 1.;
while (collection_k_vecs_affine[j][i] > 1. / 2. - 1.e-6)
collection_k_vecs_affine[j][i] -= 1.;
}
}
for (int j = 0; j < target_k_dmn_t::dmn_size(); j++) {
for (int i = 0; i < DIMENSION; i++) {
nfft_R_2_k.x[j * DIMENSION + i] = collection_k_vecs_affine[j][i];
assert(nfft_R_2_k.x[j * DIMENSION + i] >= -0.5 - 1.e-6);
assert(nfft_R_2_k.x[j * DIMENSION + i] < 0.5);
}
}
if (nfft_R_2_k.flags & PRE_ONE_PSI)
nfft_precompute_one_psi(&nfft_R_2_k);
}
template <typename scalar_type, int D, CLUSTER_NAMES N, CLUSTER_SHAPE S, typename target_dmn_type>
void wannier_interpolation_kernel<cluster_domain<scalar_type, D, N, MOMENTUM_SPACE, S>,
target_dmn_type>::FT_F_K__to__F_R(std::complex<double>* input_ptr) {
assert(source_k_dmn_t::dmn_size() > 0);
for (int K_ind = 0; K_ind < source_k_dmn_t::dmn_size(); K_ind++) {
nfft_K_2_R.f[K_ind][0] = real(input_ptr[K_ind]);
nfft_K_2_R.f[K_ind][1] = imag(input_ptr[K_ind]);
}
nfft_adjoint(&nfft_K_2_R);
for (int R_ind = 0; R_ind < centered_r_cluster_dmn_t::dmn_size(); R_ind++) {
if (lies_within_cutoff(R_ind) > 0) {
F_R(R_ind)
.real(nfft_K_2_R.f_hat[R_ind][0] /
double(source_k_dmn_t::dmn_size() * lies_within_cutoff(R_ind)));
F_R(R_ind)
.imag(nfft_K_2_R.f_hat[R_ind][1] /
double(source_k_dmn_t::dmn_size() * lies_within_cutoff(R_ind)));
}
else
F_R(R_ind) = 0.;
}
}
template <typename scalar_type, int D, CLUSTER_NAMES N, CLUSTER_SHAPE S, typename target_dmn_type>
void wannier_interpolation_kernel<cluster_domain<scalar_type, D, N, MOMENTUM_SPACE, S>,
target_dmn_type>::FT_F_R__to__F_k(std::complex<double>* output_ptr) {
for (int r_ind = 0; r_ind < centered_r_cluster_dmn_t::dmn_size(); r_ind++) {
nfft_R_2_k.f_hat[r_ind][0] = real(F_R(r_ind));
nfft_R_2_k.f_hat[r_ind][1] = imag(F_R(r_ind));
}
nfft_trafo(&nfft_R_2_k);
for (int k_ind = 0; k_ind < target_k_dmn_t::dmn_size(); k_ind++) {
output_ptr[k_ind].real(nfft_R_2_k.f[k_ind][0]);
output_ptr[k_ind].imag(nfft_R_2_k.f[k_ind][1]);
}
}
/*!
* \brief the centered_r_cluster is in row-major order because of the FFTW, on which NFFT relies!
*/
template <typename scalar_type, int D, CLUSTER_NAMES N, CLUSTER_SHAPE S, typename target_dmn_type>
void wannier_interpolation_kernel<cluster_domain<scalar_type, D, N, MOMENTUM_SPACE, S>,
target_dmn_type>::initialize_centered_r_cluster() {
centered_r_cluster::get_elements().resize(0);
switch (DIMENSION) {
case 1: {
for (int i0 = -grid_size[0] / 2; i0 < grid_size[0] / 2; i0++) {
std::vector<double> r_vec(DIMENSION, 0);
r_vec[0] = i0;
centered_r_cluster::get_elements().push_back(r_vec);
}
} break;
case 2: {
for (int i1 = -grid_size[1] / 2; i1 < grid_size[1] / 2; i1++) {
for (int i0 = -grid_size[0] / 2; i0 < grid_size[0] / 2; i0++) {
std::vector<double> r_vec(DIMENSION, 0);
r_vec[0] = i1;
r_vec[1] = i0;
centered_r_cluster::get_elements().push_back(r_vec);
}
}
} break;
case 3: {
for (int i2 = -grid_size[2] / 2; i2 < grid_size[2] / 2; i2++) {
for (int i1 = -grid_size[1] / 2; i1 < grid_size[1] / 2; i1++) {
for (int i0 = -grid_size[0] / 2; i0 < grid_size[0] / 2; i0++) {
std::vector<double> r_vec(DIMENSION, 0);
r_vec[0] = i2;
r_vec[1] = i1;
r_vec[2] = i0;
centered_r_cluster::get_elements().push_back(r_vec);
}
}
}
} break;
default:
throw std::logic_error(__FUNCTION__);
}
assert(int(centered_r_cluster::get_elements().size()) == centered_r_cluster::get_size());
}
template <typename scalar_type, int D, CLUSTER_NAMES N, CLUSTER_SHAPE S, typename target_dmn_type>
void wannier_interpolation_kernel<cluster_domain<scalar_type, D, N, MOMENTUM_SPACE, S>,
target_dmn_type>::initialize_cut_off() {
for (int l = 0; l < lies_within_cutoff.size(); l++)
lies_within_cutoff(l) = 0;
for (int R_ind = 0; R_ind < source_r_dmn_t::dmn_size(); R_ind++) {
std::vector<double> R_vec = source_r_dmn_t::get_elements()[R_ind];
std::vector<std::vector<double>> r_vecs = cluster_operations::equivalent_vectors(
R_vec, source_r_cluster_type::get_super_basis_vectors());
for (size_t l = 0; l < r_vecs.size(); l++) {
std::vector<double> r_aff =
math::util::coordinates(r_vecs[l], source_r_cluster_type::get_basis_vectors());
for (int R_cen_ind = 0; R_cen_ind < centered_r_cluster_dmn_t::dmn_size(); R_cen_ind++)
if (math::util::distance2(r_aff, centered_r_cluster_dmn_t::get_elements()[R_cen_ind]) < 1.e-3)
lies_within_cutoff(R_cen_ind) += r_vecs.size();
}
}
if (DIMENSION == 2) {
for (int l = 0; l < lies_within_cutoff.size(); l++) {
if (centered_r_cluster_dmn_t::get_elements()[l][0] == -grid_size[1] / 2 or
centered_r_cluster_dmn_t::get_elements()[l][1] == -grid_size[0] / 2)
lies_within_cutoff(l) = 0;
}
}
if (DIMENSION == 3) {
for (int l = 0; l < lies_within_cutoff.size(); l++) {
if (centered_r_cluster_dmn_t::get_elements()[l][0] == -grid_size[2] / 2 or
centered_r_cluster_dmn_t::get_elements()[l][1] == -grid_size[1] / 2 or
centered_r_cluster_dmn_t::get_elements()[l][2] == -grid_size[0] / 2)
lies_within_cutoff(l) = 0;
}
}
}
// Template specialization for source and target domains that include spin-orbital subdomains.
template <typename b_dmn_t, typename source_k_dmn_type, typename target_k_dmn_type>
class wannier_interpolation_kernel<func::dmn_variadic<b_dmn_t, b_dmn_t, source_k_dmn_type>,
func::dmn_variadic<b_dmn_t, b_dmn_t, target_k_dmn_type>> {
typedef typename source_k_dmn_type::parameter_type source_k_cluster_type;
typedef typename target_k_dmn_type::parameter_type target_k_cluster_type;
// typedef typename source_k_cluster_type::base_cluster source_base_cluster_type;
// typedef typename target_k_cluster_type::base_cluster target_base_cluster_type;
typedef wannier_interpolation_kernel<source_k_cluster_type, target_k_cluster_type>
wannier_interpolation_kernel_type;
// typedef wannier_interpolation_kernel<source_base_cluster_type, target_k_cluster_type>
// wannier_interpolation_kernel_type;
typedef typename wannier_interpolation_kernel_type::centered_r_cluster_dmn_t centered_r_dmn_t;
// typedef func::dmn_0<centered_r_LDA> centered_r_dmn_t;
typedef func::dmn_variadic<b_dmn_t, b_dmn_t, source_k_dmn_type> input_dmn_t;
typedef func::dmn_variadic<b_dmn_t, b_dmn_t, target_k_dmn_type> output_dmn_t;
public:
wannier_interpolation_kernel();
void reset();
void reset_functions();
void set(func::function<std::complex<double>, input_dmn_t>& H_K);
void get(func::function<std::complex<double>, output_dmn_t>& H_k);
private:
b_dmn_t dmn;
wannier_interpolation_kernel_type wannier_kernel_object;
// func::function<std::complex<double>, centered_r_dmn_t> in;
func::function<std::complex<double>, source_k_dmn_type> in;
func::function<std::complex<double>, target_k_dmn_type> out;
func::function<std::complex<double>, func::dmn_variadic<b_dmn_t, b_dmn_t, centered_r_dmn_t>> F_R;
};
template <typename b_dmn_t, typename source_k_dmn_type, typename target_k_dmn_type>
wannier_interpolation_kernel<
func::dmn_variadic<b_dmn_t, b_dmn_t, source_k_dmn_type>,
func::dmn_variadic<b_dmn_t, b_dmn_t, target_k_dmn_type>>::wannier_interpolation_kernel()
: wannier_kernel_object(),
F_R("wannier_interpolation_kernel__F_r") {}
template <typename b_dmn_t, typename source_k_dmn_type, typename target_k_dmn_type>
void wannier_interpolation_kernel<func::dmn_variadic<b_dmn_t, b_dmn_t, source_k_dmn_type>,
func::dmn_variadic<b_dmn_t, b_dmn_t, target_k_dmn_type>>::reset() {
wannier_kernel_object.reset_output();
}
template <typename b_dmn_t, typename source_k_dmn_type, typename target_k_dmn_type>
void wannier_interpolation_kernel<
func::dmn_variadic<b_dmn_t, b_dmn_t, source_k_dmn_type>,
func::dmn_variadic<b_dmn_t, b_dmn_t, target_k_dmn_type>>::reset_functions() {
in.reset();
out.reset();
F_R.reset();
}
template <typename b_dmn_t, typename source_k_dmn_type, typename target_k_dmn_type>
void wannier_interpolation_kernel<func::dmn_variadic<b_dmn_t, b_dmn_t, source_k_dmn_type>,
func::dmn_variadic<b_dmn_t, b_dmn_t, target_k_dmn_type>>::
set(func::function<std::complex<double>, input_dmn_t>& H_K) {
for (int i = 0; i < dmn.get_size(); ++i) {
for (int j = 0; j < dmn.get_size(); ++j) {
for (int k = 0; k < source_k_cluster_type::get_size(); ++k)
in(k) = H_K(i, j, k);
wannier_kernel_object.set(&in(0));
for (int r = 0; r < centered_r_dmn_t::dmn_size(); ++r)
F_R(i, j, r) = wannier_kernel_object.get_F_r(r);
}
}
}
template <typename b_dmn_t, typename source_k_dmn_type, typename target_k_dmn_type>
void wannier_interpolation_kernel<func::dmn_variadic<b_dmn_t, b_dmn_t, source_k_dmn_type>,
func::dmn_variadic<b_dmn_t, b_dmn_t, target_k_dmn_type>>::
get(func::function<std::complex<double>, output_dmn_t>& H_k) {
for (int i = 0; i < dmn.get_size(); ++i) {
for (int j = 0; j < dmn.get_size(); ++j) {
for (int r = 0; r < centered_r_dmn_t::dmn_size(); ++r)
wannier_kernel_object.get_F_r(r) = F_R(i, j, r);
wannier_kernel_object.get(&out(0));
for (int k = 0; k < target_k_cluster_type::get_size(); ++k)
H_k(i, j, k) = out(k);
}
}
}
} // domains
} // phys
} // dca
#endif // DCA_PHYS_DOMAINS_CLUSTER_INTERPOLATION_WANNIER_INTERPOLATION_WANNIER_INTERPOLATION_KERNEL_HPP
| 37.710575 | 185 | 0.68833 | [
"vector"
] |
2df4f976f5a720d835fa1833c36877ffd519e362 | 3,746 | cpp | C++ | Src/LPerceptron.cpp | BurnellLiu/TinyML | 3acc757567fb3ef276d79260142cfe0e79f85552 | [
"MIT"
] | 36 | 2018-01-19T07:06:41.000Z | 2021-12-21T06:59:40.000Z | Src/LPerceptron.cpp | BurnellLiu/TinyML | 3acc757567fb3ef276d79260142cfe0e79f85552 | [
"MIT"
] | null | null | null | Src/LPerceptron.cpp | BurnellLiu/TinyML | 3acc757567fb3ef276d79260142cfe0e79f85552 | [
"MIT"
] | 11 | 2017-09-29T07:52:28.000Z | 2020-12-04T11:40:59.000Z |
#include "LPerceptron.h"
#include <vector>
using std::vector;
/// @brief 感知机 实现类
class CPerceptron
{
public:
/// @brief 构造函数
CPerceptron()
{
m_learningRate = 1.0f;
}
/// @brief析构函数
~CPerceptron()
{
}
/// @brief 设置学习速率(默认值为1.0f)
/// 详细解释见头文件LPerceptron中的声明
bool SetLearningRate(IN float rate)
{
if (rate <= 0)
return false;
this->m_learningRate = rate;
return true;
}
/// @brief 训练模型
/// 详细解释见头文件LPerceptron中的声明
bool TrainModel(IN const LPerceptronProblem& problem)
{
const LPerceptronMatrix& X = problem.XMatrix;
const LPerceptronMatrix& Y = problem.YVector;
vector<float>& W = this->m_weightVector;
float& B = this->m_b;
const float Alpha = this->m_learningRate;
// 检查参数 符不符合要求
if (X.ColumnLen < 1)
return false;
if (X.RowLen < 2)
return false;
if (Y.ColumnLen != 1)
return false;
if (X.RowLen != Y.RowLen)
return false;
for (unsigned int n = 0; n < Y.RowLen; n++)
{
if (Y[n][0] != LPERCEPTRON_SUN &&
Y[n][0] != LPERCEPTRON_MOON)
return false;
}
// 初始化权重向量和截距
W.resize(X.ColumnLen, 0.0f);
B = 0.0f;
bool bErrorClass = false; // 标记是否存在错误分类
while (true)
{
// 检验每一个训练样本查看是否被错误分类
for (unsigned int i = 0; i < X.RowLen; i++)
{
float WXi = 0.0f;
for (unsigned int n = 0; n < W.size(); n++)
{
WXi += W[n] * X[i][n];
}
// 误分类点
if (Y[i][0] * (WXi + B) <= 0)
{
bErrorClass = true;
// 更新W和B
for (unsigned int n = 0; n < W.size(); n++)
{
W[n] = W[n] + Alpha * Y[i][0] * X[i][n];
}
B = B + Alpha * Y[i][0];
}
}
// 如果没有错误分类则退出循环
if (!bErrorClass)
{
break;
}
// 如果有错误分类则继续
if (bErrorClass)
{
bErrorClass = false;
continue;
}
}
return true;
}
/// @brief 使用训练好的模型进行预测(单样本预测)
/// 详细解释见头文件LPerceptron中的声明
float Predict(IN const LPerceptronMatrix& sample)
{
if (sample.RowLen != 1)
return 0.0f;
if (this->m_weightVector.size() < 1)
return 0.0f;
if (this->m_weightVector.size() != sample.ColumnLen)
return 0.0f;
float y = 0.0f;
for (unsigned int i = 0; i < sample.ColumnLen; i++)
{
y += sample[0][i] * m_weightVector[i];
}
y += m_b;
if (y >= 0)
return LPERCEPTRON_SUN;
else
return LPERCEPTRON_MOON;
}
private:
float m_learningRate; ///< 学习速率
float m_b; ///< 分割超平面的截距
vector<float> m_weightVector; ///< 权重向量(列向量), 列数为1, 行数为样本的特征数
};
LPerceptron::LPerceptron()
{
m_pPerceptron = 0;
m_pPerceptron = new CPerceptron();
}
LPerceptron::~LPerceptron()
{
if (0 != m_pPerceptron)
{
delete m_pPerceptron;
m_pPerceptron = 0;
}
}
bool LPerceptron::SetLearningRate(IN float rate)
{
return m_pPerceptron->SetLearningRate(rate);
}
bool LPerceptron::TrainModel(IN const LPerceptronProblem& problem)
{
return m_pPerceptron->TrainModel(problem);
}
float LPerceptron::Predict(IN const LPerceptronMatrix& sample)
{
return m_pPerceptron->Predict(sample);
} | 21.405714 | 66 | 0.477843 | [
"vector"
] |
2df84d378829d40f04a65c759f4c71eb23ac352a | 982 | cpp | C++ | 401-500/493-Reverse_Pairs-h.cpp | ysmiles/leetcode-cpp | e7e6ef11224c7383071ed8efbe2feac313824a71 | [
"BSD-3-Clause"
] | 1 | 2018-10-02T22:44:52.000Z | 2018-10-02T22:44:52.000Z | 401-500/493-Reverse_Pairs-h.cpp | ysmiles/leetcode-cpp | e7e6ef11224c7383071ed8efbe2feac313824a71 | [
"BSD-3-Clause"
] | null | null | null | 401-500/493-Reverse_Pairs-h.cpp | ysmiles/leetcode-cpp | e7e6ef11224c7383071ed8efbe2feac313824a71 | [
"BSD-3-Clause"
] | null | null | null | // Given an array nums, we call (i, j) an important reverse pair if i < j and
// nums[i] > 2*nums[j].
// You need to return the number of important reverse pairs in the given array.
// Example1:
// Input: [1,3,2,3,1]
// Output: 2
// Example2:
// Input: [2,4,3,5,1]
// Output: 3
// Note:
// The length of the given array will not exceed 50,000.
// All the numbers in the input array are in the range of 32-bit integer.
// TODO: self implemented inplace_merge
class Solution {
int sort_cnt(auto b, auto e) {
if (e - b <= 1)
return 0;
auto mid = b + (e - b) / 2;
int cnt = sort_cnt(b, mid) + sort_cnt(mid, e);
for (auto i = b, j = mid; i != mid; ++i) {
while (j != e && *i > 2LL * *j)
++j;
cnt += j - mid;
}
inplace_merge(b, mid, e);
return cnt;
}
public:
int reversePairs(vector<int> &nums) {
return sort_cnt(nums.begin(), nums.end());
}
}; | 23.380952 | 79 | 0.534623 | [
"vector"
] |
2df9cdb0260ecf91ce5003d8ee39abc89051e3fc | 16,081 | cpp | C++ | qt-creator-opensource-src-4.6.1/src/plugins/projectexplorer/buildconfiguration.cpp | kevinlq/Qt-Creator-Opensource-Study | b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f | [
"MIT"
] | 5 | 2018-12-22T14:49:13.000Z | 2022-01-13T07:21:46.000Z | qt-creator-opensource-src-4.6.1/src/plugins/projectexplorer/buildconfiguration.cpp | kevinlq/Qt-Creator-Opensource-Study | b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f | [
"MIT"
] | null | null | null | qt-creator-opensource-src-4.6.1/src/plugins/projectexplorer/buildconfiguration.cpp | kevinlq/Qt-Creator-Opensource-Study | b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f | [
"MIT"
] | 8 | 2018-07-17T03:55:48.000Z | 2021-12-22T06:37:53.000Z | /****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/
#include "buildconfiguration.h"
#include "buildinfo.h"
#include "buildsteplist.h"
#include "projectexplorer.h"
#include "kitmanager.h"
#include "target.h"
#include "project.h"
#include "kit.h"
#include <projectexplorer/buildenvironmentwidget.h>
#include <projectexplorer/kitinformation.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/projectmacroexpander.h>
#include <projectexplorer/target.h>
#include <coreplugin/idocument.h>
#include <utils/qtcassert.h>
#include <utils/macroexpander.h>
#include <utils/algorithm.h>
#include <utils/mimetypes/mimetype.h>
#include <utils/mimetypes/mimedatabase.h>
#include <QDebug>
static const char BUILD_STEP_LIST_COUNT[] = "ProjectExplorer.BuildConfiguration.BuildStepListCount";
static const char BUILD_STEP_LIST_PREFIX[] = "ProjectExplorer.BuildConfiguration.BuildStepList.";
static const char CLEAR_SYSTEM_ENVIRONMENT_KEY[] = "ProjectExplorer.BuildConfiguration.ClearSystemEnvironment";
static const char USER_ENVIRONMENT_CHANGES_KEY[] = "ProjectExplorer.BuildConfiguration.UserEnvironmentChanges";
static const char BUILDDIRECTORY_KEY[] = "ProjectExplorer.BuildConfiguration.BuildDirectory";
namespace ProjectExplorer {
BuildConfiguration::BuildConfiguration(Target *target, Core::Id id)
: ProjectConfiguration(target, id)
{
Utils::MacroExpander *expander = macroExpander();
expander->setDisplayName(tr("Build Settings"));
expander->setAccumulating(true);
expander->registerSubProvider([target] { return target->macroExpander(); });
expander->registerVariable("buildDir", tr("Build directory"),
[this] { return buildDirectory().toUserOutput(); });
expander->registerVariable(Constants::VAR_CURRENTBUILD_NAME, tr("Name of current build"),
[this] { return displayName(); }, false);
expander->registerPrefix(Constants::VAR_CURRENTBUILD_ENV,
tr("Variables in the current build environment"),
[this](const QString &var) { return environment().value(var); });
updateCacheAndEmitEnvironmentChanged();
connect(target, &Target::kitChanged,
this, &BuildConfiguration::handleKitUpdate);
connect(this, &BuildConfiguration::environmentChanged,
this, &BuildConfiguration::emitBuildDirectoryChanged);
}
Utils::FileName BuildConfiguration::buildDirectory() const
{
const QString path = macroExpander()->expand(QDir::cleanPath(environment().expandVariables(m_buildDirectory.toString())));
return Utils::FileName::fromString(QDir::cleanPath(QDir(target()->project()->projectDirectory().toString()).absoluteFilePath(path)));
}
Utils::FileName BuildConfiguration::rawBuildDirectory() const
{
return m_buildDirectory;
}
void BuildConfiguration::setBuildDirectory(const Utils::FileName &dir)
{
if (dir == m_buildDirectory)
return;
m_buildDirectory = dir;
emitBuildDirectoryChanged();
}
void BuildConfiguration::initialize(const BuildInfo *info)
{
setDisplayName(info->displayName);
setDefaultDisplayName(info->displayName);
setBuildDirectory(info->buildDirectory);
m_stepLists.append(new BuildStepList(this, Constants::BUILDSTEPS_BUILD));
m_stepLists.append(new BuildStepList(this, Constants::BUILDSTEPS_CLEAN));
}
QList<NamedWidget *> BuildConfiguration::createSubConfigWidgets()
{
return QList<NamedWidget *>() << new BuildEnvironmentWidget(this);
}
QList<Core::Id> BuildConfiguration::knownStepLists() const
{
return Utils::transform(m_stepLists, &BuildStepList::id);
}
BuildStepList *BuildConfiguration::stepList(Core::Id id) const
{
return Utils::findOrDefault(m_stepLists, Utils::equal(&BuildStepList::id, id));
}
QVariantMap BuildConfiguration::toMap() const
{
QVariantMap map(ProjectConfiguration::toMap());
map.insert(QLatin1String(CLEAR_SYSTEM_ENVIRONMENT_KEY), m_clearSystemEnvironment);
map.insert(QLatin1String(USER_ENVIRONMENT_CHANGES_KEY), Utils::EnvironmentItem::toStringList(m_userEnvironmentChanges));
map.insert(QLatin1String(BUILDDIRECTORY_KEY), m_buildDirectory.toString());
map.insert(QLatin1String(BUILD_STEP_LIST_COUNT), m_stepLists.count());
for (int i = 0; i < m_stepLists.count(); ++i)
map.insert(QLatin1String(BUILD_STEP_LIST_PREFIX) + QString::number(i), m_stepLists.at(i)->toMap());
return map;
}
bool BuildConfiguration::fromMap(const QVariantMap &map)
{
m_clearSystemEnvironment = map.value(QLatin1String(CLEAR_SYSTEM_ENVIRONMENT_KEY)).toBool();
m_userEnvironmentChanges = Utils::EnvironmentItem::fromStringList(map.value(QLatin1String(USER_ENVIRONMENT_CHANGES_KEY)).toStringList());
m_buildDirectory = Utils::FileName::fromString(map.value(QLatin1String(BUILDDIRECTORY_KEY)).toString());
updateCacheAndEmitEnvironmentChanged();
qDeleteAll(m_stepLists);
m_stepLists.clear();
int maxI = map.value(QLatin1String(BUILD_STEP_LIST_COUNT), 0).toInt();
for (int i = 0; i < maxI; ++i) {
QVariantMap data = map.value(QLatin1String(BUILD_STEP_LIST_PREFIX) + QString::number(i)).toMap();
if (data.isEmpty()) {
qWarning() << "No data for build step list" << i << "found!";
continue;
}
auto list = new BuildStepList(this, idFromMap(data));
if (!list->fromMap(data)) {
qWarning() << "Failed to restore build step list" << i;
delete list;
return false;
}
m_stepLists.append(list);
}
// We currently assume there to be at least a clean and build list!
QTC_CHECK(knownStepLists().contains(Core::Id(Constants::BUILDSTEPS_BUILD)));
QTC_CHECK(knownStepLists().contains(Core::Id(Constants::BUILDSTEPS_CLEAN)));
return ProjectConfiguration::fromMap(map);
}
void BuildConfiguration::updateCacheAndEmitEnvironmentChanged()
{
Utils::Environment env = baseEnvironment();
env.modify(userEnvironmentChanges());
if (env == m_cachedEnvironment)
return;
m_cachedEnvironment = env;
emit environmentChanged(); // might trigger buildDirectoryChanged signal!
}
void BuildConfiguration::handleKitUpdate()
{
updateCacheAndEmitEnvironmentChanged();
}
void BuildConfiguration::emitBuildDirectoryChanged()
{
if (buildDirectory() != m_lastEmmitedBuildDirectory) {
m_lastEmmitedBuildDirectory = buildDirectory();
emit buildDirectoryChanged();
}
}
Target *BuildConfiguration::target() const
{
return static_cast<Target *>(parent());
}
Project *BuildConfiguration::project() const
{
return target()->project();
}
Utils::Environment BuildConfiguration::baseEnvironment() const
{
Utils::Environment result;
if (useSystemEnvironment())
result = Utils::Environment::systemEnvironment();
addToEnvironment(result);
target()->kit()->addToEnvironment(result);
return result;
}
QString BuildConfiguration::baseEnvironmentText() const
{
if (useSystemEnvironment())
return tr("System Environment");
else
return tr("Clean Environment");
}
Utils::Environment BuildConfiguration::environment() const
{
return m_cachedEnvironment;
}
void BuildConfiguration::setUseSystemEnvironment(bool b)
{
if (useSystemEnvironment() == b)
return;
m_clearSystemEnvironment = !b;
updateCacheAndEmitEnvironmentChanged();
}
void BuildConfiguration::addToEnvironment(Utils::Environment &env) const
{
Q_UNUSED(env);
}
bool BuildConfiguration::useSystemEnvironment() const
{
return !m_clearSystemEnvironment;
}
QList<Utils::EnvironmentItem> BuildConfiguration::userEnvironmentChanges() const
{
return m_userEnvironmentChanges;
}
void BuildConfiguration::setUserEnvironmentChanges(const QList<Utils::EnvironmentItem> &diff)
{
if (m_userEnvironmentChanges == diff)
return;
m_userEnvironmentChanges = diff;
updateCacheAndEmitEnvironmentChanged();
}
bool BuildConfiguration::isEnabled() const
{
return true;
}
QString BuildConfiguration::disabledReason() const
{
return QString();
}
QString BuildConfiguration::buildTypeName(BuildConfiguration::BuildType type)
{
switch (type) {
case ProjectExplorer::BuildConfiguration::Debug:
return QLatin1String("debug");
case ProjectExplorer::BuildConfiguration::Profile:
return QLatin1String("profile");
case ProjectExplorer::BuildConfiguration::Release:
return QLatin1String("release");
case ProjectExplorer::BuildConfiguration::Unknown: // fallthrough
default:
return QLatin1String("unknown");
}
}
bool BuildConfiguration::isActive() const
{
return target()->isActive() && target()->activeBuildConfiguration() == this;
}
/*!
* Helper function that prepends the directory containing the C++ toolchain to
* PATH. This is used to in build configurations targeting broken build systems
* to provide hints about which compiler to use.
*/
void BuildConfiguration::prependCompilerPathToEnvironment(Utils::Environment &env) const
{
return prependCompilerPathToEnvironment(target()->kit(), env);
}
void BuildConfiguration::prependCompilerPathToEnvironment(Kit *k, Utils::Environment &env)
{
const ToolChain *tc
= ToolChainKitInformation::toolChain(k, ProjectExplorer::Constants::CXX_LANGUAGE_ID);
if (!tc)
return;
const Utils::FileName compilerDir = tc->compilerCommand().parentDir();
if (!compilerDir.isEmpty())
env.prependOrSetPath(compilerDir.toString());
}
///
// IBuildConfigurationFactory
///
static QList<IBuildConfigurationFactory *> g_buildConfigurationFactories;
IBuildConfigurationFactory::IBuildConfigurationFactory()
{
g_buildConfigurationFactories.append(this);
}
IBuildConfigurationFactory::~IBuildConfigurationFactory()
{
g_buildConfigurationFactories.removeOne(this);
}
int IBuildConfigurationFactory::priority(const Target *parent) const
{
return canHandle(parent) ? m_basePriority : -1;
}
bool IBuildConfigurationFactory::supportsTargetDeviceType(Core::Id id) const
{
if (m_supportedTargetDeviceTypes.isEmpty())
return true;
return m_supportedTargetDeviceTypes.contains(id);
}
int IBuildConfigurationFactory::priority(const Kit *k, const QString &projectPath) const
{
QTC_ASSERT(!m_supportedProjectMimeTypeName.isEmpty(), return -1);
if (k && Utils::mimeTypeForFile(projectPath).matchesName(m_supportedProjectMimeTypeName)
&& supportsTargetDeviceType(DeviceTypeKitInformation::deviceTypeId(k))) {
return m_basePriority;
}
return -1;
}
// restore
IBuildConfigurationFactory *IBuildConfigurationFactory::find(Target *parent, const QVariantMap &map)
{
IBuildConfigurationFactory *factory = 0;
int priority = -1;
for (IBuildConfigurationFactory *i : g_buildConfigurationFactories) {
if (i->canRestore(parent, map)) {
int iPriority = i->priority(parent);
if (iPriority > priority) {
factory = i;
priority = iPriority;
}
}
}
return factory;
}
// setup
IBuildConfigurationFactory *IBuildConfigurationFactory::find(const Kit *k, const QString &projectPath)
{
IBuildConfigurationFactory *factory = 0;
int priority = -1;
for (IBuildConfigurationFactory *i : g_buildConfigurationFactories) {
int iPriority = i->priority(k, projectPath);
if (iPriority > priority) {
factory = i;
priority = iPriority;
}
}
return factory;
}
// create
IBuildConfigurationFactory * IBuildConfigurationFactory::find(Target *parent)
{
IBuildConfigurationFactory *factory = 0;
int priority = -1;
for (IBuildConfigurationFactory *i : g_buildConfigurationFactories) {
int iPriority = i->priority(parent);
if (iPriority > priority) {
factory = i;
priority = iPriority;
}
}
return factory;
}
// clone
IBuildConfigurationFactory *IBuildConfigurationFactory::find(Target *parent, BuildConfiguration *bc)
{
IBuildConfigurationFactory *factory = 0;
int priority = -1;
for (IBuildConfigurationFactory *i : g_buildConfigurationFactories) {
if (i->canClone(parent, bc)) {
int iPriority = i->priority(parent);
if (iPriority > priority) {
factory = i;
priority = iPriority;
}
}
}
return factory;
}
void IBuildConfigurationFactory::setSupportedProjectType(Core::Id id)
{
m_supportedProjectType = id;
}
void IBuildConfigurationFactory::setSupportedProjectMimeTypeName(const QString &mimeTypeName)
{
m_supportedProjectMimeTypeName = mimeTypeName;
}
void IBuildConfigurationFactory::setSupportedTargetDeviceTypes(const QList<Core::Id> &ids)
{
m_supportedTargetDeviceTypes = ids;
}
void IBuildConfigurationFactory::setBasePriority(int basePriority)
{
m_basePriority = basePriority;
}
bool IBuildConfigurationFactory::canHandle(const Target *target) const
{
if (m_supportedProjectType.isValid() && m_supportedProjectType != target->project()->id())
return false;
if (!target->project()->supportsKit(target->kit()))
return false;
if (!supportsTargetDeviceType(DeviceTypeKitInformation::deviceTypeId(target->kit())))
return false;
return true;
}
BuildConfiguration *IBuildConfigurationFactory::create(Target *parent, const BuildInfo *info) const
{
if (!canHandle(parent))
return nullptr;
QTC_ASSERT(m_creator, return nullptr);
BuildConfiguration *bc = m_creator(parent);
if (!bc)
return nullptr;
bc->initialize(info);
return bc;
}
bool IBuildConfigurationFactory::canClone(const Target *parent, BuildConfiguration *product) const
{
if (!canHandle(parent))
return false;
const Core::Id id = product->id();
return id == m_buildConfigId;
}
BuildConfiguration *IBuildConfigurationFactory::restore(Target *parent, const QVariantMap &map)
{
if (!canRestore(parent, map))
return nullptr;
QTC_ASSERT(m_creator, return nullptr);
BuildConfiguration *bc = m_creator(parent);
QTC_ASSERT(bc, return nullptr);
if (!bc->fromMap(map)) {
delete bc;
bc = nullptr;
}
return bc;
}
bool IBuildConfigurationFactory::canRestore(const Target *parent, const QVariantMap &map) const
{
if (!canHandle(parent))
return false;
const Core::Id id = idFromMap(map);
return id.name().startsWith(m_buildConfigId.name());
}
BuildConfiguration *IBuildConfigurationFactory::clone(Target *parent, BuildConfiguration *product)
{
QTC_ASSERT(m_creator, return nullptr);
if (!canClone(parent, product))
return nullptr;
BuildConfiguration *bc = m_creator(parent);
QVariantMap data = product->toMap();
if (!bc->fromMap(data)) {
delete bc;
bc = nullptr;
}
return bc;
}
} // namespace ProjectExplorer
| 31.531373 | 141 | 0.713948 | [
"transform"
] |
2dfabcbfc9c1e3a94b72d768f3b6135adeca7d05 | 34,227 | cpp | C++ | firmware/MK4duo440/MK4duo/src/core/mechanics/delta_mechanics.cpp | michelebonacina/3DPrinterDIY | 985ed4bd58200b55e9dfd9683477a4b5c93d86bc | [
"MIT"
] | null | null | null | firmware/MK4duo440/MK4duo/src/core/mechanics/delta_mechanics.cpp | michelebonacina/3DPrinterDIY | 985ed4bd58200b55e9dfd9683477a4b5c93d86bc | [
"MIT"
] | null | null | null | firmware/MK4duo440/MK4duo/src/core/mechanics/delta_mechanics.cpp | michelebonacina/3DPrinterDIY | 985ed4bd58200b55e9dfd9683477a4b5c93d86bc | [
"MIT"
] | null | null | null | /**
* MK4duo Firmware for 3D Printer, Laser and CNC
*
* Based on Marlin, Sprinter and grbl
* Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm
* Copyright (c) 2020 Alberto Cotronei @MagoKimbra
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
/**
* delta_mechanics.cpp
*
* Copyright (c) 2020 Alberto Cotronei @MagoKimbra
*/
#include "../../../MK4duo.h"
#if MECH(DELTA)
Delta_Mechanics mechanics;
#if ENABLED(DELTA_FAST_SQRT) && ENABLED(__AVR__)
#define _SQRT(n) (1.0f / Q_rsqrt(n))
#else
#define _SQRT(n) SQRT(n)
#endif
/** Public Parameters */
mechanics_data_t Delta_Mechanics::data;
abc_pos_t Delta_Mechanics::delta{0.0f};
float Delta_Mechanics::delta_clip_start_height = 0;
/** Private Parameters */
abc_float_t Delta_Mechanics::D2{0.0f}, // Diagonal rod ^2
Delta_Mechanics::towerX{0.0f}, // The X coordinate of each tower
Delta_Mechanics::towerY{0.0f}; // The Y coordinate of each tower
float Delta_Mechanics::Xbc = 0.0f,
Delta_Mechanics::Xca = 0.0f,
Delta_Mechanics::Xab = 0.0f,
Delta_Mechanics::Ybc = 0.0f,
Delta_Mechanics::Yca = 0.0f,
Delta_Mechanics::Yab = 0.0f,
Delta_Mechanics::coreKa = 0.0f,
Delta_Mechanics::coreKb = 0.0f,
Delta_Mechanics::coreKc = 0.0f,
Delta_Mechanics::Q = 0.0f,
Delta_Mechanics::Q2 = 0.0f;
/** Public Function */
void Delta_Mechanics::factory_parameters() {
static const float tmp_step[] PROGMEM = DEFAULT_AXIS_STEPS_PER_UNIT,
tmp_maxfeedrate[] PROGMEM = DEFAULT_MAX_FEEDRATE;
static const uint32_t tmp_maxacc[] PROGMEM = DEFAULT_MAX_ACCELERATION;
LOOP_XYZ(axis) {
data.axis_steps_per_mm[axis] = pgm_read_float(&tmp_step[axis < COUNT(tmp_step) ? axis : COUNT(tmp_step) - 1]);
data.max_feedrate_mm_s[axis] = pgm_read_float(&tmp_maxfeedrate[axis < COUNT(tmp_maxfeedrate) ? axis : COUNT(tmp_maxfeedrate) - 1]);
data.max_acceleration_mm_per_s2[axis] = pgm_read_dword_near(&tmp_maxacc[axis < COUNT(tmp_maxacc) ? axis : COUNT(tmp_maxacc) - 1]);
}
data.acceleration = DEFAULT_ACCELERATION;
data.travel_acceleration = DEFAULT_TRAVEL_ACCELERATION;
data.min_feedrate_mm_s = DEFAULT_MIN_FEEDRATE;
data.min_segment_time_us = DEFAULT_MIN_SEGMENT_TIME;
data.min_travel_feedrate_mm_s = DEFAULT_MIN_TRAVEL_FEEDRATE;
#if ENABLED(JUNCTION_DEVIATION)
data.junction_deviation_mm = float(JUNCTION_DEVIATION_MM);
#endif
data.max_jerk.set(DEFAULT_XJERK, DEFAULT_YJERK, DEFAULT_ZJERK);
data.diagonal_rod = DELTA_DIAGONAL_ROD;
data.radius = DELTA_RADIUS;
data.segments_per_second_print = DELTA_SEGMENTS_PER_SECOND_PRINT;
data.segments_per_second_move = DELTA_SEGMENTS_PER_SECOND_MOVE;
data.segments_per_line = DELTA_SEGMENTS_PER_LINE;
data.print_radius = DELTA_PRINTABLE_RADIUS;
data.probe_radius = DELTA_PROBEABLE_RADIUS;
data.height = DELTA_HEIGHT;
delta_clip_start_height = DELTA_HEIGHT;
data.endstop_adj.set(TOWER_A_ENDSTOP_ADJ, TOWER_B_ENDSTOP_ADJ, TOWER_C_ENDSTOP_ADJ);
data.tower_angle_adj.set(TOWER_A_ANGLE_ADJ, TOWER_B_ANGLE_ADJ, TOWER_C_ANGLE_ADJ);
data.tower_radius_adj.set(TOWER_A_RADIUS_ADJ, TOWER_B_RADIUS_ADJ, TOWER_C_RADIUS_ADJ);
data.diagonal_rod_adj.set(TOWER_A_DIAGROD_ADJ, TOWER_B_DIAGROD_ADJ, TOWER_C_DIAGROD_ADJ);
}
/**
* Get the stepper positions in the cartesian_position[] array.
* Forward kinematics are applied for DELTA.
*
* The result is in the current coordinate space with
* leveling applied. The coordinates need to be run through
* unapply_leveling to obtain the "ideal" coordinates
* suitable for position, etc.
*/
void Delta_Mechanics::get_cartesian_from_steppers() {
InverseTransform(
planner.get_axis_position_mm(A_AXIS),
planner.get_axis_position_mm(B_AXIS),
planner.get_axis_position_mm(C_AXIS),
cartesian_position
);
}
#if DISABLED(AUTO_BED_LEVELING_UBL)
/**
* Prepare a linear move in a DELTA setup.
*
* This calls buffer_line several times, adding
* small incremental moves for DELTA.
*/
bool Delta_Mechanics::prepare_move_to_destination_mech_specific() {
// Get the top feedrate of the move in the XY plane
const float _feedrate_mm_s = MMS_SCALED(feedrate_mm_s);
// Get the cartesian distances moved in XYZE
const xyze_float_t difference = destination - position;
// If the move is only in Z/E don't split up the move
if (!difference.x && !difference.y) {
planner.buffer_line(destination, _feedrate_mm_s, toolManager.extruder.active);
return false; // caller will update position
}
// Fail if attempting move outside printable radius
if (endstops.isSoftEndstop() && !position_is_reachable(destination.x, destination.y)) return true;
// Get the cartesian distance in XYZ
float cartesian_distance = SQRT(sq(difference.x) + sq(difference.y) + sq(difference.z));
// If the move is very short, check the E move distance
if (UNEAR_ZERO(cartesian_distance)) cartesian_distance = ABS(difference.e);
// No E move either? Game over.
if (UNEAR_ZERO(cartesian_distance)) return true;
// Minimum number of seconds to move the given distance
const float seconds = cartesian_distance / _feedrate_mm_s;
// The number of segments-per-second times the duration
// gives the number of segments we should produce
const uint16_t sps = difference.e ? data.segments_per_second_print : data.segments_per_second_move;
const uint16_t segments = MAX(1U, sps * seconds);
// Now compute the number of lines needed
uint16_t numLines = (segments + data.segments_per_line - 1) / data.segments_per_line;
// The approximate length of each segment
const float inv_numLines = 1.0f / float(numLines),
cartesian_segment_mm = cartesian_distance * inv_numLines;
const xyze_float_t segment_distance = difference * inv_numLines;
/*
DEBUG_MV("mm=", cartesian_distance);
DEBUG_MV(" seconds=", seconds);
DEBUG_MV(" segments=", segments);
DEBUG_MV(" numLines=", numLines);
DEBUG_MV(" segment_mm=", cartesian_segment_mm);
DEBUG_EOL();
//*/
// Get the current position as starting point
xyze_pos_t raw = position;
// Calculate and execute the segments
while (--numLines) {
static short_timer_t next_idle_timer(millis());
if (next_idle_timer.expired(200)) printer.idle();
raw += segment_distance;
if (!planner.buffer_line(raw, _feedrate_mm_s, toolManager.extruder.active, cartesian_segment_mm))
break;
}
planner.buffer_line(destination, _feedrate_mm_s, toolManager.extruder.active, cartesian_segment_mm);
return false; // caller will update position.x
}
#endif // DISABLED(AUTO_BED_LEVELING_UBL)
/**
* Move the planner to the current position from wherever it last moved
* (or from wherever it has been told it is located).
*/
void Delta_Mechanics::internal_move_to_destination(const feedrate_t &fr_mm_s/*=0.0f*/, const bool is_fast/*=false*/) {
REMEMBER(old_fr, feedrate_mm_s);
if (fr_mm_s) feedrate_mm_s = fr_mm_s;
REMEMBER(old_pct, feedrate_percentage, 100);
REMEMBER(old_fac, extruders[toolManager.extruder.active]->e_factor, 1.0f);
if (is_fast)
prepare_uninterpolated_move_to_destination();
else
prepare_move_to_destination();
}
/**
* Plan a move to (X, Y, Z) and set the position
*/
void Delta_Mechanics::do_blocking_move_to(const float rx, const float ry, const float rz, const feedrate_t &fr_mm_s/*=0.0f*/) {
if (printer.debugFeature()) DEBUG_XYZ(">>> do_blocking_move_to", rx, ry, rz);
const feedrate_t z_feedrate = fr_mm_s ? fr_mm_s : homing_feedrate_mm_s.z,
xy_feedrate = fr_mm_s ? fr_mm_s : feedrate_t(XY_PROBE_FEEDRATE_MM_S);
if (!position_is_reachable(rx, ry)) return;
REMEMBER(fr, feedrate_mm_s, xy_feedrate);
destination = position; // sync destination at the start
if (printer.debugFeature()) DEBUG_POS("set_destination_to_current", destination);
// when in the danger zone
if (position.z > delta_clip_start_height) {
if (rz > delta_clip_start_height) { // staying in the danger zone
destination.set(rx, ry, rz); // move directly (uninterpolated)
prepare_uninterpolated_move_to_destination(); // set_current_to_destination
if (printer.debugFeature()) DEBUG_POS("danger zone move", position);
return;
}
destination.z = delta_clip_start_height;
prepare_uninterpolated_move_to_destination(); // set_current_to_destination
if (printer.debugFeature()) DEBUG_POS("zone border move", position);
}
if (rz > position.z) { // raising?
destination.z = rz;
prepare_uninterpolated_move_to_destination(z_feedrate); // set_current_to_destination
if (printer.debugFeature()) DEBUG_POS("z raise move", position);
}
destination.set(rx, ry);
prepare_move_to_destination(); // set_current_to_destination
if (printer.debugFeature()) DEBUG_POS("xy move", position);
if (rz < position.z) { // lowering?
destination.z = rz;
prepare_uninterpolated_move_to_destination(z_feedrate); // set_current_to_destination
if (printer.debugFeature()) DEBUG_POS("z lower move", position);
}
if (printer.debugFeature()) DEBUG_EM("<<< do_blocking_move_to");
planner.synchronize();
}
void Delta_Mechanics::do_blocking_move_to(const xy_pos_t &raw, const feedrate_t &fr_mm_s/*=0.0f*/) {
do_blocking_move_to(raw.x, raw.y, position.z, fr_mm_s);
}
void Delta_Mechanics::do_blocking_move_to(const xyz_pos_t &raw, const feedrate_t &fr_mm_s/*=0.0f*/) {
do_blocking_move_to(raw.x, raw.y, raw.z, fr_mm_s);
}
void Delta_Mechanics::do_blocking_move_to(const xyze_pos_t &raw, const feedrate_t &fr_mm_s/*=0.0f*/) {
do_blocking_move_to(raw.x, raw.y, raw.z, fr_mm_s);
}
void Delta_Mechanics::do_blocking_move_to_x(const float &rx, const feedrate_t &fr_mm_s/*=0.0f*/) {
do_blocking_move_to(rx, position.y, position.z, fr_mm_s);
}
void Delta_Mechanics::do_blocking_move_to_y(const float &ry, const feedrate_t &fr_mm_s/*=0.0f*/) {
do_blocking_move_to(position.x, ry, position.z, fr_mm_s);
}
void Delta_Mechanics::do_blocking_move_to_z(const float &rz, const feedrate_t &fr_mm_s/*=0.0f*/) {
do_blocking_move_to(position.x, position.y, rz, fr_mm_s);
}
void Delta_Mechanics::do_blocking_move_to_xy(const float &rx, const float &ry, const feedrate_t &fr_mm_s/*=0.0f*/) {
do_blocking_move_to(rx, ry, position.z, fr_mm_s);
}
void Delta_Mechanics::do_blocking_move_to_xy(const xy_pos_t &raw, const feedrate_t &fr_mm_s/*=0.0f*/) {
do_blocking_move_to(raw.x, raw.y, position.z, fr_mm_s);
}
void Delta_Mechanics::do_blocking_move_to_xy_z(const xy_pos_t &raw, const float &z, const feedrate_t &fr_mm_s/*=0.0f*/) {
do_blocking_move_to(raw.x, raw.y, z, fr_mm_s);
}
/**
* Delta InverseTransform
*
* See the Wikipedia article "Trilateration"
* https://en.wikipedia.org/wiki/Trilateration
*
* Establish a new coordinate system in the plane of the
* three carriage points. This system has its origin at
* tower1, with tower2 on the X axis. Tower3 is in the X-Y
* plane with a Z component of zero.
* We will define unit vectors in this coordinate system
* in our original coordinate system. Then when we calculate
* the Xnew, Ynew and Znew values, we can translate back into
* the original system by moving along those unit vectors
* by the corresponding values.
*
* Variable names matched to Mk4duo, c-version, and avoid the
* use of any vector library.
*
* by Andreas Hardtung 07-06-2016
* based on a Java function from "Delta Robot Mechanics V3"
* by Steve Graves
*
* The result is stored in the cartesian[] array.
*/
void Delta_Mechanics::InverseTransform(const float Ha, const float Hb, const float Hc, xyz_pos_t &cartesian) {
// Calculate RSUT such that x = (Uz + S)/Q, y = -(Rz + T)/Q
const float R = 2 * ((Xbc * Ha) + (Xca * Hb) + (Xab * Hc)),
U = 2 * ((Ybc * Ha) + (Yca * Hb) + (Yab * Hc));
const float Ka = coreKa + (sq(Hc) - sq(Hb)),
Kb = coreKb + (sq(Ha) - sq(Hc)),
Kc = coreKc + (sq(Hb) - sq(Ha));
const float S = Ka * towerY.a + Kb * towerY.b + Kc * towerY.c,
T = Ka * towerX.a + Kb * towerX.b + Kc * towerX.c;
const float A = sq(U) + sq(R) + Q2;
const float minusHalfB = Q2 * Ha + Q * (U * towerX.a - R * towerY.a) - (R * T + U * S),
C = sq(towerX.a * Q - S) + sq(towerY.a * Q + T) + (sq(Ha) - D2.a) * Q2;
const float z = (minusHalfB - SQRT(sq(minusHalfB) - A * C)) / A;
cartesian.x = (U * z + S) / Q;
cartesian.y = -(R * z + T) / Q;
cartesian.z = z;
}
/**
* Delta Transform
*
* Calculate the tower positions for a given machine
* position, storing the result in the delta[] array.
*
* This is an expensive calculation, requiring 3 square
* roots per segmented linear move, and strains the limits
* of a Mega2560 with a Graphical Display.
*/
void Delta_Mechanics::Transform(const xyz_pos_t &raw) {
// Delta hotend offsets must be applied in Cartesian space
const xyz_pos_t pos = { raw.x - nozzle.data.hotend_offset[toolManager.active_hotend()].x,
raw.y - nozzle.data.hotend_offset[toolManager.active_hotend()].y,
raw.z
};
delta.a = pos.z + _SQRT(D2.a - sq(pos.x - towerX.a) - sq(pos.y - towerY.a));
delta.b = pos.z + _SQRT(D2.b - sq(pos.x - towerX.b) - sq(pos.y - towerY.b));
delta.c = pos.z + _SQRT(D2.c - sq(pos.x - towerX.c) - sq(pos.y - towerY.c));
}
void Delta_Mechanics::recalc_delta_settings() {
// Get a minimum radius for clamping
endstops.soft_endstop_radius_2 = sq(data.print_radius);
D2.a = sq(data.diagonal_rod + data.diagonal_rod_adj.a);
D2.b = sq(data.diagonal_rod + data.diagonal_rod_adj.b);
D2.c = sq(data.diagonal_rod + data.diagonal_rod_adj.c);
// Effective X/Y positions of the three vertical towers.
towerX.a = COS(RADIANS(210 + data.tower_angle_adj.a)) * (data.radius + data.tower_radius_adj.a); // front left tower
towerY.a = SIN(RADIANS(210 + data.tower_angle_adj.a)) * (data.radius + data.tower_radius_adj.a);
towerX.b = COS(RADIANS(330 + data.tower_angle_adj.b)) * (data.radius + data.tower_radius_adj.b); // front right tower
towerY.b = SIN(RADIANS(330 + data.tower_angle_adj.b)) * (data.radius + data.tower_radius_adj.b);
towerX.c = COS(RADIANS( 90 + data.tower_angle_adj.c)) * (data.radius + data.tower_radius_adj.c); // back middle tower
towerY.c = SIN(RADIANS( 90 + data.tower_angle_adj.c)) * (data.radius + data.tower_radius_adj.c);
Xbc = towerX.c - towerX.b;
Xca = towerX.a - towerX.c;
Xab = towerX.b - towerX.a;
Ybc = towerY.c - towerY.b;
Yca = towerY.a - towerY.c;
Yab = towerY.b - towerY.a;
Q = 2 * (Xab * towerY.c + Xca * towerY.b + Xbc * towerY.a);
Q2 = sq(Q);
const float coreFa = sq(towerX.a) + sq(towerY.a),
coreFb = sq(towerX.b) + sq(towerY.b),
coreFc = sq(towerX.c) + sq(towerY.c);
coreKa = (D2.b - D2.c) + (coreFc - coreFb);
coreKb = (D2.c - D2.a) + (coreFa - coreFc);
coreKc = (D2.a - D2.b) + (coreFb - coreFa);
NOMORE(data.probe_radius, data.print_radius);
unsetHomedAll();
Set_clip_start_height();
}
/**
* Home Delta
*/
void Delta_Mechanics::home(const bool report/*=true*/) {
if (printer.debugSimulation()) {
LOOP_XYZ(axis) set_axis_is_at_home((AxisEnum)axis);
#if HAS_NEXTION_LCD && ENABLED(NEXTION_GFX)
nextion_gfx_clear();
#endif
return;
}
#if HAS_POWER_SWITCH
powerManager.power_on(); // Power On if power is off
#endif
// Wait for planner moves to finish!
planner.synchronize();
// Cancel the active G29 session
#if HAS_LEVELING && HAS_PROBE_MANUALLY
bedlevel.flag.g29_in_progress = false;
#endif
// Disable the leveling matrix before homing
#if HAS_LEVELING
bedlevel.set_bed_leveling_enabled(false);
#endif
// Reduce Acceleration and Jerk for Homing
#if ENABLED(SLOW_HOMING) || ENABLED(IMPROVE_HOMING_RELIABILITY)
REMEMBER(accel_x, data.max_acceleration_mm_per_s2.x, 100);
REMEMBER(accel_y, data.max_acceleration_mm_per_s2.y, 100);
REMEMBER(accel_z, data.max_acceleration_mm_per_s2.z, 100);
#if HAS_CLASSIC_JERK
REMEMBER(jerk_x, data.max_jerk.x, 0);
REMEMBER(jerk_y, data.max_jerk.y, 0);
REMEMBER(jerk_z, data.max_jerk.z, 0);
#endif
planner.reset_acceleration_rates();
#endif
// Always home with tool 0 active
#if HOTENDS > 1
const uint8_t old_tool_index = toolManager.extruder.active;
toolManager.change(0, true);
#endif
setup_for_endstop_or_probe_move();
endstops.setEnabled(true); // Enable endstops for next homing move
bool come_back = parser.boolval('B');
REMEMBER(fr, feedrate_mm_s);
stored_position[0] = position;
if (printer.debugFeature()) DEBUG_POS(">>> home", position);
// Init the current position of all carriages to 0,0,0
position.reset();
destination.reset();
sync_plan_position();
// Disable stealthChop if used. Enable diag1 pin on driver.
#if ENABLED(SENSORLESS_HOMING)
sensorless_flag_t stealth_states;
stealth_states.x = tmcManager.enable_stallguard(driver.x);
stealth_states.y = tmcManager.enable_stallguard(driver.y);
stealth_states.z = tmcManager.enable_stallguard(driver.z);
#if ENABLED(SPI_ENDSTOPS)
endstops.clear_state();
endstops.tmc_spi_homing.any = true;
#endif
#endif
// Move all carriages together linearly until an endstop is hit.
destination.z = data.height + 10;
planner.buffer_line(destination, homing_feedrate_mm_s.z, toolManager.extruder.active);
planner.synchronize();
// Re-enable stealthChop if used. Disable diag1 pin on driver.
#if ENABLED(SENSORLESS_HOMING)
tmcManager.disable_stallguard(driver.x, stealth_states.x);
tmcManager.disable_stallguard(driver.y, stealth_states.y);
tmcManager.disable_stallguard(driver.z, stealth_states.z);
#if ENABLED(SPI_ENDSTOPS)
endstops.tmc_spi_homing.any = false;
endstops.clear_state();
#endif
destination.z -= 5;
planner.buffer_line(destination, homing_feedrate_mm_s.z, toolManager.extruder.active);
planner.synchronize();
#endif
endstops.validate_homing_move();
// At least one carriage has reached the top.
// Now re-home each carriage separately.
homeaxis(A_AXIS);
homeaxis(B_AXIS);
homeaxis(C_AXIS);
// Set all carriages to their home positions
// Do this here all at once for Delta, because
// XYZ isn't ABC. Applying this per-tower would
// give the impression that they are the same.
LOOP_XYZ(i) set_axis_is_at_home((AxisEnum)i);
sync_plan_position();
if (printer.debugFeature()) DEBUG_POS("<<< home", position);
endstops.setNotHoming();
// Clear endstop state for polled stallGuard endstops
#if ENABLED(SPI_ENDSTOPS)
endstops.clear_state();
#endif
#if ENABLED(SLOW_HOMING) || ENABLED(IMPROVE_HOMING_RELIABILITY)
RESTORE(accel_x);
RESTORE(accel_y);
RESTORE(accel_z);
#if HAS_CLASSIC_JERK
RESTORE(jerk_x);
RESTORE(jerk_y);
RESTORE(jerk_z);
#endif
planner.reset_acceleration_rates();
#endif
#if ENABLED(DELTA_HOME_TO_SAFE_ZONE)
// move to a height where we can use the full xy-area
do_blocking_move_to_z(delta_clip_start_height, homing_feedrate_mm_s.z);
#endif
if (come_back) {
feedrate_mm_s = homing_feedrate_mm_s.z;
destination = stored_position[0];
prepare_move_to_destination();
RESTORE(fr);
}
#if HAS_NEXTION_LCD && ENABLED(NEXTION_GFX)
nextion_gfx_clear();
#endif
// Re-enable bed level correction if it had been on
#if HAS_LEVELING
bedlevel.restore_bed_leveling_state();
#endif
clean_up_after_endstop_or_probe_move();
planner.synchronize();
// Restore the active tool after homing
#if HOTENDS > 1
toolManager.change(old_tool_index, true);
#endif
lcdui.refresh();
if (report) report_position();
if (printer.debugFeature()) DEBUG_EM("<<< G28");
}
/**
* Home an individual linear axis
*/
void Delta_Mechanics::do_homing_move(const AxisEnum axis, const float distance, const feedrate_t fr_mm_s/*=0.0f*/) {
const feedrate_t real_fr_mm_s = fr_mm_s ? fr_mm_s : homing_feedrate_mm_s.z;
if (printer.debugFeature()) {
DEBUG_MC(">>> do_homing_move(", axis_codes[axis]);
DEBUG_MV(", ", distance);
DEBUG_MSG(", ");
if (fr_mm_s)
DEBUG_VAL(fr_mm_s);
else {
DEBUG_MV(" [", real_fr_mm_s);
DEBUG_CHR(']');
}
DEBUG_CHR(')');
DEBUG_EOL();
}
// Only do some things when moving towards an endstop
const bool is_home_dir = distance > 0;
#if ENABLED(SENSORLESS_HOMING)
sensorless_flag_t stealth_states;
#endif
if (is_home_dir) {
// Enable diag1 pin on driver.
#if ENABLED(SENSORLESS_HOMING)
stealth_states = start_sensorless_homing_per_axis(axis);
#endif
}
abce_pos_t target = planner.get_axis_positions_mm();
target[axis] = 0;
planner.set_machine_position_mm(target);
target[axis] = distance;
#if HAS_DIST_MM_ARG
const xyze_pos_t cart_dist_mm{0};
#endif
// Set delta axes directly
planner.buffer_segment(target
#if HAS_DIST_MM_ARG
, cart_dist_mm
#endif
, real_fr_mm_s, toolManager.extruder.active
);
planner.synchronize();
if (is_home_dir) {
endstops.validate_homing_move();
// Re-enable stealthChop if used. Disable diag1 pin on driver.
#if ENABLED(SENSORLESS_HOMING)
stop_sensorless_homing_per_axis(axis, stealth_states);
#endif
}
if (printer.debugFeature()) {
DEBUG_MC("<<< do_homing_move(", axis_codes[axis]);
DEBUG_CHR(')'); DEBUG_EOL();
}
}
/**
* Set an axis' current position to its home position (after homing).
*
* DELTA should wait until all homing is done before setting the XYZ
* position.x to home, because homing is a single operation.
* In the case where the axis positions are already known and previously
* homed, DELTA could home to X or Y individually by moving either one
* to the center. However, homing Z always homes XY and Z.
*
* Callers must sync the planner position after calling this!
*/
void Delta_Mechanics::set_axis_is_at_home(const AxisEnum axis) {
if (printer.debugFeature()) {
DEBUG_MC(">>> set_axis_is_at_home(", axis_codes[axis]);
DEBUG_CHR(')'); DEBUG_EOL();
}
setAxisHomed(axis, true);
position[axis] = (axis == C_AXIS ? data.height : 0.0f);
#if ENABLED(BABYSTEPPING) && ENABLED(BABYSTEP_DISPLAY_TOTAL)
babystep.reset_total(axis);
#endif
if (printer.debugFeature()) {
DEBUG_POS("", position);
DEBUG_MC("<<< set_axis_is_at_home(", axis_codes[axis]);
DEBUG_CHR(')'); DEBUG_EOL();
}
}
// Return true if the given point is within the printable area
bool Delta_Mechanics::position_is_reachable(const float &rx, const float &ry) {
return HYPOT2(rx, ry) <= sq(data.print_radius);
}
// Return true if the both nozzle and the probe can reach the given point.
bool Delta_Mechanics::position_is_reachable_by_probe(const float &rx, const float &ry) {
return position_is_reachable(rx, ry) &&
position_is_reachable(rx - probe.data.offset.x, ry - probe.data.offset.y);
}
// Report the real current position according to the steppers
void Delta_Mechanics::report_real_position() {
get_cartesian_from_steppers();
#if HAS_POSITION_MODIFIERS
xyze_pos_t npos = cartesian_position;
planner.unapply_modifiers(npos
#if HAS_LEVELING
, true
#endif
);
#else
const xyze_pos_t &npos = cartesian_position;
#endif
xyze_pos_t lpos = npos.asLogical();
lpos.e = planner.get_axis_position_mm(E_AXIS);
report_some_position(lpos);
}
// Report detail current position to host
void Delta_Mechanics::report_detail_position() {
SERIAL_MSG("\nLogical:");
report_xyz(position.asLogical());
SERIAL_MSG("Raw: ");
report_xyz(position);
xyze_pos_t leveled = position;
#if HAS_LEVELING
SERIAL_MSG("Leveled:");
bedlevel.apply_leveling(leveled);
report_xyz(leveled);
SERIAL_MSG("UnLevel:");
xyze_pos_t unleveled = leveled;
bedlevel.unapply_leveling(unleveled);
report_xyz(unleveled);
#endif
SERIAL_MSG("DeltaK: ");
Transform(leveled);
report_xyz(delta);
planner.synchronize();
SERIAL_MSG("Stepper:");
LOOP_XYZE(i) {
SERIAL_CHR(' ');
SERIAL_CHR(axis_codes[i]);
SERIAL_CHR(':');
SERIAL_VAL(stepper.position((AxisEnum)i));
}
SERIAL_EOL();
SERIAL_MSG("FromStp:");
get_cartesian_from_steppers();
xyze_pos_t from_steppers = { cartesian_position.x, cartesian_position.y, cartesian_position.z, planner.get_axis_position_mm(E_AXIS) };
report_xyze(from_steppers);
const xyze_float_t diff = from_steppers - leveled;
SERIAL_MSG("Differ: ");
report_xyze(diff);
}
// Report the logical current position according to the most recent G-code command.
void Delta_Mechanics::report_logical_position() {
xyze_pos_t rpos = position;
#if HAS_POSITION_MODIFIERS
planner.apply_modifiers(rpos);
#endif
Transform(rpos);
const abc_pos_t &kpos = delta;
abc_float_t aspmm;
aspmm.set(mechanics.steps_to_mm);
const abc_long_t spos = (kpos * aspmm).asLong().ROUNDL();
report_some_position(position.asLogical());
stepper.report_positions(spos);
}
#if DISABLED(DISABLE_M503)
void Delta_Mechanics::print_parameters() {
print_M92();
print_M201();
print_M203();
print_M204();
print_M205();
print_M666();
}
void Delta_Mechanics::print_M92() {
SERIAL_LM(CFG, "Steps per unit:");
SERIAL_LMV(CFG, " M92 X", LINEAR_UNIT(data.axis_steps_per_mm.x), 3);
LOOP_EXTRUDER() {
SERIAL_SMV(CFG, " M92 T", (int)e);
SERIAL_EMV(" E", VOLUMETRIC_UNIT(extruders[e]->data.axis_steps_per_mm), 3);
}
}
void Delta_Mechanics::print_M201() {
SERIAL_LM(CFG, "Maximum Acceleration (units/s2):");
SERIAL_LMV(CFG, " M201 X", LINEAR_UNIT(data.max_acceleration_mm_per_s2.x));
LOOP_EXTRUDER() {
SERIAL_SMV(CFG, " M201 T", (int)e);
SERIAL_EMV(" E", VOLUMETRIC_UNIT(extruders[e]->data.max_acceleration_mm_per_s2));
}
}
void Delta_Mechanics::print_M203() {
SERIAL_LM(CFG, "Maximum feedrates (units/s):");
SERIAL_LMV(CFG, " M203 X", LINEAR_UNIT(data.max_feedrate_mm_s.x), 3);
LOOP_EXTRUDER() {
SERIAL_SMV(CFG, " M203 T", (int)e);
SERIAL_EMV(" E", VOLUMETRIC_UNIT(extruders[e]->data.max_feedrate_mm_s), 3);
}
}
void Delta_Mechanics::print_M204() {
SERIAL_LM(CFG, "Acceleration (units/s2): P<DEFAULT_ACCELERATION> V<DEFAULT_TRAVEL_ACCELERATION> T* R<DEFAULT_RETRACT_ACCELERATION>");
SERIAL_SMV(CFG," M204 P", LINEAR_UNIT(data.acceleration), 3);
SERIAL_EMV(" V", LINEAR_UNIT(data.travel_acceleration), 3);
LOOP_EXTRUDER() {
SERIAL_SMV(CFG, " M204 T", (int)e);
SERIAL_EMV(" R", LINEAR_UNIT(extruders[e]->data.retract_acceleration), 3);
}
}
void Delta_Mechanics::print_M205() {
SERIAL_LM(CFG, "Advanced: B<DEFAULT_MIN_SEGMENT_TIME> S<DEFAULT_MIN_FEEDRATE> V<DEFAULT_MIN_TRAVEL_FEEDRATE>");
SERIAL_SMV(CFG, " M205 B", data.min_segment_time_us);
SERIAL_MV(" S", LINEAR_UNIT(data.min_feedrate_mm_s), 3);
SERIAL_EMV(" V", LINEAR_UNIT(data.min_travel_feedrate_mm_s), 3);
#if ENABLED(JUNCTION_DEVIATION)
SERIAL_LM(CFG, "Junction Deviation: J<JUNCTION_DEVIATION_MM>");
SERIAL_LMV(CFG, " M205 J", data.junction_deviation_mm, 2);
#endif
SERIAL_SM(CFG, "Jerk: X<DEFAULT_XJERK>");
#if DISABLED(JUNCTION_DEVIATION) || DISABLED(LIN_ADVANCE)
SERIAL_MSG(" T* E<DEFAULT_EJERK>");
#endif
SERIAL_EOL();
SERIAL_LMV(CFG, " M205 X", LINEAR_UNIT(data.max_jerk.x), 3);
#if DISABLED(JUNCTION_DEVIATION) || DISABLED(LIN_ADVANCE)
LOOP_EXTRUDER() {
SERIAL_SMV(CFG, " M205 T", (int)e);
SERIAL_EMV(" E" , LINEAR_UNIT(extruders[e]->data.max_jerk), 3);
}
#endif
}
void Delta_Mechanics::print_M666() {
SERIAL_LM(CFG, "Endstop adjustment:");
SERIAL_SM(CFG, " M666");
SERIAL_MV(" X", LINEAR_UNIT(data.endstop_adj.a));
SERIAL_MV(" Y", LINEAR_UNIT(data.endstop_adj.b));
SERIAL_MV(" Z", LINEAR_UNIT(data.endstop_adj.c));
SERIAL_EOL();
SERIAL_LM(CFG, "Delta Geometry adjustment: ABC<TOWER_*_DIAGROD_ADJ> IJK<TOWER_*_ANGLE_ADJ> UVW<TOWER_*_RADIUS_ADJ>");
SERIAL_SM(CFG, " M666");
SERIAL_MV(" A", LINEAR_UNIT(data.diagonal_rod_adj.a), 3);
SERIAL_MV(" B", LINEAR_UNIT(data.diagonal_rod_adj.b), 3);
SERIAL_MV(" C", LINEAR_UNIT(data.diagonal_rod_adj.c), 3);
SERIAL_MV(" I", data.tower_angle_adj.a, 3);
SERIAL_MV(" J", data.tower_angle_adj.b, 3);
SERIAL_MV(" K", data.tower_angle_adj.c, 3);
SERIAL_MV(" U", LINEAR_UNIT(data.tower_radius_adj.a), 3);
SERIAL_MV(" V", LINEAR_UNIT(data.tower_radius_adj.b), 3);
SERIAL_MV(" W", LINEAR_UNIT(data.tower_radius_adj.c), 3);
SERIAL_EOL();
SERIAL_LM(CFG, "Delta Geometry adjustment: R<DELTA_RADIUS> D<DELTA_DIAGONAL_ROD>");
SERIAL_SM(CFG, " M666");
SERIAL_MV(" R", LINEAR_UNIT(data.radius));
SERIAL_MV(" D", LINEAR_UNIT(data.diagonal_rod));
SERIAL_EOL();
SERIAL_LM(CFG, "Delta Geometry adjustment: S<DELTA_SEGMENTS_PER_SECOND_PRINT> F<DELTA_SEGMENTS_PER_SECOND_MOVE> L<DELTA_SEGMENTS_PER_LINE>");
SERIAL_SM(CFG, " M666");
SERIAL_MV(" S", data.segments_per_second_print);
SERIAL_MV(" F", data.segments_per_second_move);
SERIAL_MV(" L", data.segments_per_line);
SERIAL_EOL();
SERIAL_LM(CFG, "Delta Geometry adjustment: O<DELTA_PRINTABLE_RADIUS> P<DELTA_PROBEABLE_RADIUS> H<DELTA_HEIGHT>");
SERIAL_SM(CFG, " M666");
SERIAL_MV(" O", LINEAR_UNIT(data.print_radius));
SERIAL_MV(" P", LINEAR_UNIT(data.probe_radius));
SERIAL_MV(" H", LINEAR_UNIT(data.height), 3);
SERIAL_EOL();
}
#endif // DISABLED(DISABLE_M503)
#if HAS_NEXTION_LCD && ENABLED(NEXTION_GFX)
void Delta_Mechanics::nextion_gfx_clear() {
nexlcd.gfx_clear(data.print_radius * 2, data.print_radius * 2, data.height);
nexlcd.gfx_cursor_to(position);
}
#endif
/** Private Function */
void Delta_Mechanics::homeaxis(const AxisEnum axis) {
if (printer.debugFeature()) {
DEBUG_MC(">>> homeaxis(", axis_codes[axis]);
DEBUG_CHR(')'); DEBUG_EOL();
}
// Fast move towards endstop until triggered
do_homing_move(axis, 1.5f * data.height);
// When homing Z with probe respect probe clearance
const float bump = home_bump_mm[axis];
// If a second homing move is configured...
if (bump) {
// Move away from the endstop by the axis HOME_BUMP_MM
if (printer.debugFeature()) DEBUG_EM("Move Away:");
do_homing_move(axis, -bump);
// Slow move towards endstop until triggered
if (printer.debugFeature()) DEBUG_EM("Home 2 Slow:");
do_homing_move(axis, 2 * bump, get_homing_bump_feedrate(axis));
}
#if HAS_TRINAMIC
tmcManager.go_to_homing_phase(axis, get_homing_bump_feedrate(axis));
#endif // HAS_TRINAMIC
// Delta has already moved all three towers up in G28
// so here it re-homes each tower in turn.
// Delta homing treats the axes as normal linear axes.
const float adjDistance = data.endstop_adj[axis];
const float minDistance = (MIN_STEPS_PER_SEGMENT) * steps_to_mm[axis];
// retrace by the amount specified in delta_endstop_adj if more than min steps.
if (adjDistance < 0 && ABS(adjDistance) > minDistance) { // away from endstop, more than min distance
if (printer.debugFeature()) DEBUG_EMV("endstop_adj:", adjDistance);
do_homing_move(axis, adjDistance, get_homing_bump_feedrate(axis));
}
// Clear retracted status if homing the Z axis
#if ENABLED(FWRETRACT)
if (axis == Z_AXIS) fwretract.current_hop = 0.0f;
#endif
if (printer.debugFeature()) {
DEBUG_MC("<<< homeaxis(", axis_codes[axis]);
DEBUG_CHR(')'); DEBUG_EOL();
}
}
/**
* Buffer a fast move without interpolation. Set position to destination
*/
void Delta_Mechanics::prepare_uninterpolated_move_to_destination(const feedrate_t &fr_mm_s/*=0.0f*/) {
if (printer.debugFeature()) DEBUG_POS("prepare_uninterpolated_move_to_destination", destination);
#if UBL_DELTA
// ubl segmented line will do z-only moves in single segment
ubl.line_to_destination_segmented(MMS_SCALED(fr_mm_s ? fr_mm_s : feedrate_mm_s));
#else
if (position == destination) return;
planner.buffer_line(destination, MMS_SCALED(fr_mm_s ? fr_mm_s : feedrate_mm_s), toolManager.extruder.active);
#endif
position = destination;
}
void Delta_Mechanics::Set_clip_start_height() {
xyz_pos_t cartesian{0};
Transform(cartesian);
float distance = delta.a;
cartesian.y = data.print_radius;
Transform(cartesian);
delta_clip_start_height = data.height - ABS(distance - delta.a);
}
#if ENABLED(DELTA_FAST_SQRT) && ENABLED(__AVR__)
/**
* Fast inverse SQRT from Quake III Arena
* See: https://en.wikipedia.org/wiki/Fast_inverse_square_root
*/
float Delta_Mechanics::Q_rsqrt(float number) {
long i;
float x2, y;
const float threehalfs = 1.5f;
x2 = number * 0.5f;
y = number;
i = * ( long * ) &y; // evil floating point bit level hacking
i = 0x5F3759DF - ( i >> 1 );
y = * ( float * ) &i;
y = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration
// y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed
return y;
}
#endif
#endif // MECH(DELTA)
| 33.359649 | 145 | 0.695007 | [
"geometry",
"vector",
"transform",
"3d"
] |
930126bb4dd366829240156c04faef666070dc78 | 2,282 | cpp | C++ | main.cpp | JulienHora/Vector2D-3D | 55980d34f5c1995417be52806ef5cd79d1618174 | [
"MIT"
] | null | null | null | main.cpp | JulienHora/Vector2D-3D | 55980d34f5c1995417be52806ef5cd79d1618174 | [
"MIT"
] | null | null | null | main.cpp | JulienHora/Vector2D-3D | 55980d34f5c1995417be52806ef5cd79d1618174 | [
"MIT"
] | null | null | null | #include "iostream"
// #include "Vector2D.h"
#include "Vector3D.h"
int main()
{
Vector3D VectorA(1, 2, -5);
Vector3D VectorB(4, 6, 7);
VectorA.SplitToStruct();
Vector3D VectorC = VectorA.CrossProduct(VectorB);
double DProductAC = VectorA.DotProduct(VectorC);
double DProductBC = VectorB.DotProduct(VectorC);
double DistanceAtoB = VectorA.Distance(VectorB);
Vector3D VectorAPlusB = VectorA + VectorB;
Vector3D VectorAMinusB = VectorA - VectorB;
Vector3D VectorAMultipliedByB = VectorA * VectorB;
Vector3D VectorADividedByB = VectorA / VectorB;
Vector3D VectorAMultipliedByTwo = VectorA * 2.0;
bool VectorAIsEqualToA = VectorA == VectorA;
bool VectorAIsEqualToB = VectorA == VectorB;
std::cout << "Cross Product of Vectors A & B: { x: " << VectorC.x << ", y: " << VectorC.y << ", z: " << VectorC.z << " }" << std::endl;
std::cout << std::endl;
std::cout << "Dot Product of Vectors A & C: " << DProductAC << std::endl;
std::cout << "Dot Product of Vectors B & C: " << DProductBC << std::endl;
std::cout << std::endl;
std::cout << "Distance Between Vectors A & B: " << DistanceAtoB << std::endl;
std::cout << std::endl;
std::cout << "Vector A + B value: { x: " << VectorAPlusB.x << ", y: " << VectorAPlusB.y << ", z: " << VectorAPlusB.z << " }" << std::endl;
std::cout << "Vector A - B value: { x: " << VectorAMinusB.x << ", y: " << VectorAMinusB.y << ", z: " << VectorAMinusB.z << " }" << std::endl;
std::cout << "Vector A * B value: { x: " << VectorAMultipliedByB.x << ", y: " << VectorAMultipliedByB.y << ", z: " << VectorAMultipliedByB.z << " }" << std::endl;
std::cout << "Vector A / B value: { x: " << VectorADividedByB.x << ", y: " << VectorADividedByB.y << ", z: " << VectorADividedByB.z << " }" << std::endl;
std::cout << std::endl;
std::cout << "Vector A Multiplied By 2: { x: " << VectorAMultipliedByTwo.x << ", y: " << VectorAMultipliedByTwo.y << ", z: " << VectorAMultipliedByTwo.z << " }" << std::endl;
std::cout << "Vector A is equal to A: " << (VectorAIsEqualToA ? "true" : "false") << std::endl;
std::cout << "Vector A is equal to B: " << (VectorAIsEqualToB ? "true" : "false") << std::endl;
std::cout << std::endl;
return 0;
}
| 44.745098 | 178 | 0.591148 | [
"vector"
] |
9302e4820514008b6a4a6043af4fd7b0ebefc78a | 1,004 | cxx | C++ | src/mlio/data_stores/file_hierarchy.cxx | aws-patlin/ml-io | 047e7d40609ced6f839d0b08d1917e9742a785af | [
"Apache-2.0"
] | null | null | null | src/mlio/data_stores/file_hierarchy.cxx | aws-patlin/ml-io | 047e7d40609ced6f839d0b08d1917e9742a785af | [
"Apache-2.0"
] | null | null | null | src/mlio/data_stores/file_hierarchy.cxx | aws-patlin/ml-io | 047e7d40609ced6f839d0b08d1917e9742a785af | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You
* may not use this file except in compliance with the License. A copy of
* the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
* ANY KIND, either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*/
#include "mlio/data_stores/file_hierarchy.h"
#include "mlio/data_stores/data_store.h"
#include "mlio/intrusive_ptr.h"
namespace mlio {
inline namespace v1 {
std::vector<intrusive_ptr<data_store>>
list_files(std::string const &pathname, std::string const &pattern)
{
stdx::span<std::string const> pathnames{&pathname, 1};
return list_files({pathnames, &pattern});
}
} // namespace v1
} // namespace mlio
| 29.529412 | 74 | 0.728088 | [
"vector"
] |
930e5977bd480b8032d71932bf325782af06e354 | 7,484 | hpp | C++ | source/vector.hpp | evanbowman/skyland | a62827a0dbcab705ba8ddf75cb74e975ceadec39 | [
"MIT"
] | 24 | 2021-07-03T02:27:25.000Z | 2022-03-29T05:21:32.000Z | source/vector.hpp | evanbowman/skyland | a62827a0dbcab705ba8ddf75cb74e975ceadec39 | [
"MIT"
] | 3 | 2021-09-24T18:52:49.000Z | 2021-11-13T00:16:47.000Z | source/vector.hpp | evanbowman/skyland | a62827a0dbcab705ba8ddf75cb74e975ceadec39 | [
"MIT"
] | 1 | 2021-07-11T08:05:59.000Z | 2021-07-11T08:05:59.000Z | #pragma once
#include "bulkAllocator.hpp"
// A Vector implementation backed by ScratchBuffers.
// Our program allocates memory only as reference-counted 2k buffers. We have a
// realtime program that runs on an embedded system with limited ram, and we
// want to avoid malloc. Here, we provide an implementation of a Dynamic Array
// compatible with our atypical memory allocators. No, this cannot be
// implemented instead as an allocator for std::vector.
template <typename T> class Vector {
private:
struct Chunk {
struct Header {
std::optional<ScratchBufferPtr> next_;
Chunk* prev_;
};
static constexpr u32 elems()
{
return ((SCRATCH_BUFFER_SIZE - sizeof(Chunk::Header)) -
alignof(T)) /
sizeof(T);
}
static void initialize(ScratchBufferPtr source, Chunk* prev)
{
new (source->data_) Chunk();
((Chunk*)source->data_)->header_.prev_ = prev;
}
Chunk() = default;
Chunk(const Chunk& other) = delete;
~Chunk()
{
if (header_.next_) {
((Chunk*)(*header_.next_)->data_)->~Chunk();
}
}
T* array()
{
return (T*)buffer_;
}
Header header_;
alignas(T) char buffer_[elems() * sizeof(T)];
};
void seek_chunk(Chunk*& current, int& index)
{
while ((u32)index >= Chunk::elems()) {
if (current->header_.next_) {
current = (Chunk*)(*current->header_.next_)->data_;
index -= Chunk::elems();
} else {
return;
}
}
}
public:
struct Iterator {
Iterator(int index, Chunk* chunk)
: chunk_(chunk), index_(index), chunk_index_(index % Chunk::elems())
{
}
bool operator==(const Iterator& other) const
{
return index_ == other.index_;
}
bool operator<(const Iterator& other) const
{
return index_ < other.index_;
}
bool operator>(const Iterator& other) const
{
return index_ > other.index_;
}
bool operator>=(const Iterator& other) const
{
return index_ >= other.index_;
}
bool operator<=(const Iterator& other) const
{
return index_ <= other.index_;
}
int operator-(const Iterator& other) const
{
return index_ - other.index_;
}
bool operator not_eq(const Iterator& other) const
{
return index_ not_eq other.index_;
}
T* operator->()
{
return &((chunk_->array())[chunk_index_]);
}
T& operator*()
{
return (chunk_->array())[chunk_index_];
}
Iterator operator++(int)
{
Iterator temp = *this;
++(*this);
return temp;
}
const Iterator& operator++()
{
++chunk_index_;
++index_;
if (chunk_index_ == Chunk::elems()) {
chunk_index_ = 0;
if (chunk_->header_.next_) {
chunk_ = (Chunk*)(*chunk_->header_.next_)->data_;
}
}
return *this;
}
const Iterator& operator--()
{
--chunk_index_;
--index_;
if (index_ == 0) {
chunk_index_ = 0;
index_ = 0;
return *this;
}
if (chunk_index_ < 0) {
chunk_index_ = Chunk::elems() - 1;
chunk_ = chunk_->header_.prev_;
}
return *this;
}
int index() const
{
return index_;
}
private:
Chunk* chunk_;
int index_;
int chunk_index_;
};
Iterator begin()
{
return Iterator(0, (Chunk*)data_->data_);
}
Iterator end()
{
int size = size_;
Chunk* current = (Chunk*)data_->data_;
seek_chunk(current, size);
return Iterator(size_, current);
}
void erase(Iterator position)
{
auto last = end();
for (; position not_eq last;) {
auto next = position;
++next;
// NOTE: we're copying the next element into the current
// one. Because the last element does not have a next element, skip.
if (position.index() not_eq last.index() - 1) {
*position = std::move(*next);
} else {
// We copied the final element into the previous one in the
// previous iteration. Simply destroy the final element.
position->~T();
}
position = next;
}
--size_;
}
void insert(Iterator position, const T& elem)
{
push_back(elem);
auto last = Iterator(size_ - 1, [this] {
int index = size_ - 1;
Chunk* chunk = (Chunk*)data_->data_;
seek_chunk(chunk, index);
return chunk;
}());
for (; position not_eq last; ++position) {
std::swap(*position, *last);
}
}
Vector(Platform& pfrm) : pfrm_(pfrm), data_(pfrm.make_scratch_buffer())
{
Chunk::initialize(data_, nullptr);
}
Vector(Vector&& other)
: pfrm_(other.pfrm_), data_(other.data_), size_(other.size_)
{
other.size_ = 0; // Should be sufficient to invalidate the other
// vector. It will hold onto its scratch buffer, which
// cannot be null, but it's just a reference count and
// will be decremented eventually.
}
Vector(const Vector& other) = delete;
void push_back(const T& elem)
{
Chunk* current = (Chunk*)data_->data_;
int size = size_;
seek_chunk(current, size);
if (size == Chunk::elems() and not current->header_.next_) {
auto sbr = pfrm_.make_scratch_buffer();
Chunk::initialize(sbr, current);
current->header_.next_ = sbr;
current = (Chunk*)(*current->header_.next_)->data_;
size = 0;
}
new (current->array() + size) T(elem);
++size_;
}
void pop_back()
{
Chunk* current = (Chunk*)data_->data_;
int size = size_;
seek_chunk(current, size);
--size_;
(current->array() + (size - 1))->~T();
*(current->array() + (size - 1)) = 0; // TODO: Remove this line!
}
T& operator[](int index)
{
Chunk* current = (Chunk*)data_->data_;
seek_chunk(current, index);
// TODO: bounds check!
return current->array()[index];
}
~Vector()
{
// TODO: Don't bother to pop anything if elements are trivially
// destructible.
while (size_ > Chunk::elems()) {
pop_back();
}
((Chunk*)data_->data_)->~Chunk();
}
int chunks_used()
{
return size_ / Chunk::elems() + (size_ % Chunk::elems() > 0);
}
u32 size() const
{
return size_;
}
private:
Platform& pfrm_;
ScratchBufferPtr data_;
u32 size_ = 0;
};
| 21.321937 | 80 | 0.490513 | [
"vector"
] |
931244383e056c9b177d5d3bafcfbed9d68fbda8 | 1,410 | cpp | C++ | thirdparty/embree/common/sys/string.cpp | dsrw/godot | 61ea011e05dd182351eef1e59ab14cd26bbd73a1 | [
"MIT",
"Apache-2.0",
"CC-BY-4.0",
"Unlicense"
] | 441 | 2018-12-26T14:50:23.000Z | 2021-11-05T03:13:27.000Z | thirdparty/embree/common/sys/string.cpp | dsrw/godot | 61ea011e05dd182351eef1e59ab14cd26bbd73a1 | [
"MIT",
"Apache-2.0",
"CC-BY-4.0",
"Unlicense"
] | 221 | 2018-12-29T17:40:23.000Z | 2021-11-06T21:41:55.000Z | thirdparty/embree/common/sys/string.cpp | dsrw/godot | 61ea011e05dd182351eef1e59ab14cd26bbd73a1 | [
"MIT",
"Apache-2.0",
"CC-BY-4.0",
"Unlicense"
] | 101 | 2018-12-29T13:08:10.000Z | 2021-11-02T09:58:37.000Z | // Copyright 2009-2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
#include "string.h"
#include <algorithm>
#include <ctype.h>
namespace embree
{
char to_lower(char c) { return char(tolower(int(c))); }
char to_upper(char c) { return char(toupper(int(c))); }
std::string toLowerCase(const std::string& s) { std::string dst(s); std::transform(dst.begin(), dst.end(), dst.begin(), to_lower); return dst; }
std::string toUpperCase(const std::string& s) { std::string dst(s); std::transform(dst.begin(), dst.end(), dst.begin(), to_upper); return dst; }
Vec2f string_to_Vec2f ( std::string str )
{
size_t next = 0;
const float x = std::stof(str,&next); str = str.substr(next+1);
const float y = std::stof(str,&next);
return Vec2f(x,y);
}
Vec3f string_to_Vec3f ( std::string str )
{
size_t next = 0;
const float x = std::stof(str,&next); str = str.substr(next+1);
const float y = std::stof(str,&next); str = str.substr(next+1);
const float z = std::stof(str,&next);
return Vec3f(x,y,z);
}
Vec4f string_to_Vec4f ( std::string str )
{
size_t next = 0;
const float x = std::stof(str,&next); str = str.substr(next+1);
const float y = std::stof(str,&next); str = str.substr(next+1);
const float z = std::stof(str,&next); str = str.substr(next+1);
const float w = std::stof(str,&next);
return Vec4f(x,y,z,w);
}
}
| 32.790698 | 146 | 0.632624 | [
"transform"
] |
9316d1af31b353c69855d8817b3a9bb6841cfe08 | 14,434 | cpp | C++ | source/Tools/Index.cpp | badbrainz/pme | 1c8e6f3d154cc59613f5ef3f2f8293f488c64b28 | [
"WTFPL"
] | null | null | null | source/Tools/Index.cpp | badbrainz/pme | 1c8e6f3d154cc59613f5ef3f2f8293f488c64b28 | [
"WTFPL"
] | null | null | null | source/Tools/Index.cpp | badbrainz/pme | 1c8e6f3d154cc59613f5ef3f2f8293f488c64b28 | [
"WTFPL"
] | null | null | null | // ATI's code
#include "Index.h"
#define INIT_ALLOC 1000
int indexBinaryTraverse(void *value, void *data, int *index, int stride, int count, int *result, int (*compare)(const void *, const void *));
int indexAddElement(IndexT *index, int value, int position, char append);
int indexAppend(IndexT *index, int value, int position);
int indexAppendBack(IndexT *index, int value);
int indexCheckAlloc(IndexT *index);
int indexInsert(IndexT *index, int value, int position);
int indexRemovePosition(IndexT *index, int position);
int indexRemoveSortedElement(IndexT *index, void *element);
int indexSortedInsert(IndexT *ind, int value);
int indexSortedInsertDup(IndexT *ind, int value);
int indexFind(IndexT *index, void *element, int *result);
void indexArray(IndexT *index, char *array, int size, int count, sortFunction sortFunc)
{
int i;
memset(index, 0, sizeof(IndexT));
index->data = array;
index->dataSize = size;
index->sortFunc = sortFunc;
for (i=0;i<count;i++)
indexSortedInsert(index, i);
}
void indexArrayCB(IndexT *index, char *array, int size, int count, sortFunction sortFunc, sortFunction callback)
{
int i, position, compValue, result;
memset(index, 0, sizeof(IndexT));
index->data=array;
index->dataSize=size;
index->sortFunc=sortFunc;
for (i=0;i<count;i++)
{
position=indexBinaryTraverse((char *)index->data+(i*index->dataSize), index->data, index->indices, index->dataSize, index->count, &compValue, index->sortFunc);
if (compValue==0)
callback((char *)index->data+(index->indices[position]*index->dataSize), (char *)index->data+(i*index->dataSize));
else
{
if (compValue<0)
result=indexInsert(index, i, position);
else
result=indexAppend(index, i, position);
}
}
}
void indexSortArray(IndexT *index, char *array, int size, int count, sortFunction sortFunc)
{
int i;
memset(index, 0, sizeof(IndexT));
index->data=array;
index->dataSize=size;
index->sortFunc=sortFunc;
for (i=0;i<count;i++)
indexSortedInsertDup(index, i);
}
//=============================================================================
// adds the passed element to the vector and either inserts or appends the
// element with respect to the specified index based on the boolean value passed
// calling this function directly could result in an unsorted vector
//=============================================================================
int indexAddElement(IndexT* index, int value, int position, char append)
{
int result;
result = indexCheckAlloc(index);
if (result == INDEX_MEMORY_ERROR)
{
return result;
}
if (append)
{
result = indexAppend(index, value, position);
}
else
{
result = indexInsert(index, value, position);
}
return result;
}
//=============================================================================
// appends the passed element after the specified index
// calling this function directly could result in an unsorted vector
//=============================================================================
int indexAppend(IndexT* index, int value, int position)
{
int result;
if ((position < 0) || ((position >= index->count) && (index->count != 0)))
{
return INDEX_OUT_OF_RANGE;
}
result = indexCheckAlloc(index);
if (result == INDEX_MEMORY_ERROR)
{
return result;
}
if ((index->count != 0) && (position < (index->count - 1)))
{
//=====================================================//
// shift down by one element from the index to the end //
//=====================================================//
memmove(&index->indices[position + 2], &index->indices[position+ 1], (index->count - position - 1) * sizeof(int));
}
//=========================//
// copy the new element in //
//=========================//
index->indices[position + 1] = value;
index->count++;
return INDEX_OK;
}
//=============================================================================
// appends the passed element to the back of the vector
// calling this function directly could result in an unsorted vector
//=============================================================================
int indexAppendBack(IndexT* index, int value)
{
int result;
result = indexCheckAlloc(index);
if (result == INDEX_MEMORY_ERROR)
{
return result;
}
//=========================//
// copy the new element in //
//=========================//
index->indices[index->count] = value;
index->count++;
return INDEX_OK;
}
//=============================================================================
// checks if memory is still available in the vector and allocates more if
// necessary
//=============================================================================
int indexCheckAlloc(IndexT* index)
{
int* buffer;
int allocSize = 0;
if ((index->allocCount == 0) && (index->count == 0))
{
index->allocCount = INIT_ALLOC;
index->indices = (int*)malloc(index->allocCount * sizeof(int));
if (index->indices == NULL)
{
return INDEX_MEMORY_ERROR;
}
memset(index->indices, 0, index->allocCount * sizeof(int));
}
if (index->count >= index->allocCount)
{
//============================================================//
// we will allocate twice as much memory as is currently used //
//============================================================//
allocSize = (index->count << 1);
buffer = (int*)malloc(allocSize * sizeof(int));
if (buffer == NULL)
{
return INDEX_MEMORY_ERROR;
}
memset(buffer, 0, allocSize * sizeof(int));
//==============================================================================//
// if we had memory allocated before then copy the old data into the new buffer //
//==============================================================================//
if ((index->allocCount != 0) && (index->indices != NULL))
{
memcpy(buffer, index->indices, index->allocCount * sizeof(int));
}
//================================//
// free the old data if necessary //
//================================//
if (index->indices != NULL)
{
free(index->indices);
}
//===============================================//
// set the data pointer to point to the new data //
//===============================================//
index->indices = buffer;
//============================//
// record the allocation size //
//============================//
index->allocCount = allocSize;
return INDEX_REALLOCATE;
}
return INDEX_OK;
}
//=============================================================================
// frees all resources used by the vector
//=============================================================================
void indexFree(IndexT* index)
{
if (index->indices != NULL)
{
free(index->indices);
}
memset(index, 0, sizeof(IndexT));
}
//=============================================================================
// inserts the passed element into the vector before the index specified
// calling this function directly could result in an unsorted vector
//=============================================================================
int indexInsert(IndexT* index, int value, int position)
{
int result;
if ((position < 0) || ((position >= index->count) && (index->count != 0)))
{
return INDEX_OUT_OF_RANGE;
}
result = indexCheckAlloc(index);
if (result == INDEX_MEMORY_ERROR)
{
return result;
}
//=====================================================//
// shift down by one element from the index to the end //
//=====================================================//
if (index->count != 0)
{
memmove(&index->indices[position + 1], &index->indices[position], (index->count - position) * sizeof(int));
}
//=========================//
// copy the new element in //
//=========================//
index->indices[position] = value;
index->count++;
return INDEX_OK;
}
//=============================================================================
// removes the element at the specified index
//=============================================================================
int indexRemovePosition(IndexT* index, int position)
{
int result = INDEX_NOT_FOUND;
if ((position < 0) || (position >= index->count))
{
return INDEX_OUT_OF_RANGE;
}
//=====================================================//
// shift back by one element from the index to the end //
//=====================================================//
if (position < (index->count - 1))
{
memmove(&index->indices[position], &index->indices[position + 1], (index->count - position - 1) * sizeof(int));
}
index->count--;
return INDEX_OK;
}
//=============================================================================
// finds the specified element and removes it
// INDEX MUST BE SORTED
//=============================================================================
int indexRemoveSortedElement(IndexT* index, void* element)
{
int position;
int value;
int result = INDEX_NOT_FOUND;
//=========================================================================//
// Traverse the list of sorted data to find the index where we will insert //
//=========================================================================//
position = indexBinaryTraverse(
element, index->data, index->indices, index->dataSize, index->count, &value, index->sortFunc);
if (value == 0)
{
result = indexRemovePosition(index, position);
}
return result;
}
//=============================================================================
// inserts the passed element into the vector such that the vector is sorted
// INDEX MUST BE SORTED
//=============================================================================
int indexSortedInsert(IndexT* ind, int value)
{
int position;
int compValue;
int result;
//=========================================================================//
// Traverse the list of sorted data to find the index where we will insert //
//=========================================================================//
position = indexBinaryTraverse(
(char*)ind->data + (value * ind->dataSize), ind->data, ind->indices, ind->dataSize, ind->count, &compValue, ind->sortFunc);
if (compValue == 0)
{
result = INDEX_OK;
}
else if (compValue < 0) // we are inserting before this index
{
result = indexInsert(ind, value, position);
}
else // we are appending after this index
{
result = indexAppend(ind, value, position);
}
return result;
}
//=============================================================================
// inserts the passed element into the vector such that the vector is sorted
// INDEX MUST BE SORTED
//=============================================================================
int indexSortedInsertDup(IndexT* ind, int value)
{
int position;
int compValue;
int result;
//=========================================================================//
// Traverse the list of sorted data to find the index where we will insert //
//=========================================================================//
position = indexBinaryTraverse(
(char*)ind->data + (value * ind->dataSize), ind->data, ind->indices, ind->dataSize, ind->count, &compValue, ind->sortFunc);
if (compValue <= 0) // we are inserting before this index
{
result = indexInsert(ind, value, position);
}
else // we are appending after this index
{
result = indexAppend(ind, value, position);
}
return result;
}
//=============================================================================
// finds the specified element in the vector and returns its index
// INDEX MUST BE SORTED
//=============================================================================
int indexFind(IndexT* index, void* element, int* result)
{
int position;
//======================================================//
// Traverse the list of sorted data to find the element //
//======================================================//
position = indexBinaryTraverse(
element, index->data, index->indices, index->dataSize, index->count, result, index->sortFunc);
return position;
}
//=============================================================================
// generic binary traversal function
//=============================================================================
int indexBinaryTraverse(
void* value, // pointer to the reference element
void* data, // pointer to the indexed data
int* indices, // pointer index
int stride, // data stride
int count, // number of items in the array
int* result, // buffer for the result of the last compare
int (*compare)(const void*, const void*) // pointer to the compare function
)
{
#pragma warning(push, 2)
#pragma warning(disable:4311)
#pragma warning(disable:4312)
int high;
int low;
int mid;
int nextMid;
high = count;
low = 0;
mid = low + ((high - low) >> 1);
*result = -1;
while (low != high)
{
*result = compare(value, (void*)((unsigned int)data + indices[mid] * stride));
if (*result == 0)
{
break;
}
else if (*result < 0)
{
high = mid;
}
else
{
low = mid;
}
nextMid = low + ((high - low) >> 1);
if (mid == nextMid)
{
break;
}
mid = nextMid;
}
#pragma warning(pop)
return mid;
}
| 31.515284 | 164 | 0.456561 | [
"vector"
] |
931854174311dd48a8bb5537c60de03498707522 | 901 | cpp | C++ | Solutions-to-Books/C++Primer/Chapter12/12.06.cpp | Horizon-Blue/playground | 4bd42bfcec60b8e89e127f4784c99f6ba669d359 | [
"MIT"
] | 2 | 2016-08-31T19:13:24.000Z | 2017-02-18T18:48:31.000Z | Solutions-to-Books/C++Primer/Chapter12/12.06.cpp | Horizon-Blue/playground | 4bd42bfcec60b8e89e127f4784c99f6ba669d359 | [
"MIT"
] | 1 | 2018-12-10T16:32:26.000Z | 2018-12-27T19:50:48.000Z | Solutions-to-Books/C++Primer/Chapter12/12.06.cpp | Horizon-Blue/playground | 4bd42bfcec60b8e89e127f4784c99f6ba669d359 | [
"MIT"
] | null | null | null | // Exercise 12.6
// Write a function that returns a dynamically allocated vector of ints. Pass that
// vector to another function that reads the standard input to give values to the
// elements. Pass the vector to another function to print the values that were read.
// Remember to delete the vector at the appropriate time.
// Xiaoyan Wang 8/1/2016
#include <iostream>
#include <vector>
using namespace std;
vector<int>* createVec();
vector<int>* readVec(vector<int> *ivec);
ostream& printVec(vector<int> *ivec);
int main() {
vector<int> *ivec = createVec();
readVec(ivec);
printVec(ivec);
delete ivec;
return 0;
}
vector<int>* createVec() {
return new vector<int>();
}
vector<int>* readVec(vector<int> *ivec) {
for(int temp; cin >> temp; ivec->push_back(temp))
;
return ivec;
}
ostream& printVec(vector<int> *ivec) {
for(const int &num : *ivec)
cout << num << ' ';
return cout;
} | 23.710526 | 84 | 0.700333 | [
"vector"
] |
7933ddc9a0480372abcc7f719426fbb184cf08bf | 5,062 | hpp | C++ | rgbd/VideoSourceKinect.hpp | Mavericklsd/rgb_mapping_and_relocalisation | feb10285dc2694557f23096d9a89743ccf85f062 | [
"MIT"
] | 18 | 2017-04-04T09:31:32.000Z | 2021-02-25T09:19:07.000Z | rgbd/VideoSourceKinect.hpp | Mavericklsd/rgb_mapping_and_relocalisation | feb10285dc2694557f23096d9a89743ccf85f062 | [
"MIT"
] | 1 | 2017-09-27T14:29:56.000Z | 2017-09-27T14:29:56.000Z | rgbd/VideoSourceKinect.hpp | Mavericklsd/rgb_mapping_and_relocalisation | feb10285dc2694557f23096d9a89743ccf85f062 | [
"MIT"
] | 9 | 2017-04-01T00:14:56.000Z | 2019-08-28T16:05:53.000Z | //Copyright(c) 2015 Shuda Li[lishuda1980@gmail.com]
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files(the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions :
//
//The above copyright notice and this permission notice shall be included in
//all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
//FOR A PARTICULAR PURPOSE AND NON - INFRINGEMENT.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 BTL_EXTRA_VIDEOSOURCE_VIDEOSOURCEKINECT
#define BTL_EXTRA_VIDEOSOURCE_VIDEOSOURCEKINECT
#include "DllExportDef.h"
using namespace openni;
namespace btl{
namespace kinect{
namespace btl_img = btl::image;
namespace btl_knt = btl::kinect;
class CVideoSourceKinect
{
public:
//type
typedef std::shared_ptr<CVideoSourceKinect> tp_shared_ptr;
enum tp_mode { SIMPLE_CAPTURING = 1, RECORDING = 2, PLAYING_BACK = 3};
enum tp_status { CONTINUE=01, PAUSE=02, MASK1 =07, START_RECORDING=010, STOP_RECORDING=020, CONTINUE_RECORDING=030, DUMP_RECORDING=040, MASK_RECORDER = 070 };
enum tp_raw_data_processing_methods {
BIFILTER_IN_ORIGINAL = 0, BIFILTER_IN_DISPARITY, BIFILTER_DYNAMIC
};
//constructor
CVideoSourceKinect(ushort uResolution_, ushort uPyrHeight_, bool bUseNIRegistration_,const Eigen::Vector3f& eivCw_,const string& cam_param_path_ );
virtual ~CVideoSourceKinect();
void initKinect();
void initRecorder(std::string& strPath_);
virtual void initPlayer(std::string& strPathFileName_);
// 1. need to call getNextFrame() before hand
// 2. RGB color channel (rather than BGR as used by cv::imread())
virtual bool getNextFrame(int* pnStatus_);
// 0 VGA
// 1 QVGA
Status setVideoMode(ushort uLevel_);
void setDumpFileName( const std::string& strFileName_ ){_strDumpFileName = strFileName_;}
protected:
virtual void importYML();
// convert the depth map/ir camera to be aligned with the rgb camera
virtual void init();
void gpuBuildPyramidUseNICVmBiFilteringInOriginalDepth( );
void gpu_build_pyramid_dynamic_bilatera();
virtual void gpuBuildPyramidUseNICVm();
bool loadCoefficient(int nResolution_, int size_, Mat* coeff_, Mat* mask_);
bool loadLocation(vector<float>* pvLocations_);
public:
//depth calibration parameters
GpuMat _calibXYxZ[2];
GpuMat _mask[2];
vector<float> _vRegularLocations;
string _serial_number;
bool _bMapUndistortionOn;
//parameters
float _fThresholdDepthInMeter; //threshold for filtering depth
float _fSigmaSpace; //degree of blur for the bilateral filter
float _fSigmaDisparity;
unsigned int _uPyrHeight;//the height of pyramid
ushort _uResolution;//0 640x480; 1 320x240; 2 160x120 3 80x60
float _fScaleRGB;//scale the input video source to standard resolution 0,1,2,.. __aKinectW[]
float _fScaleDepth;// __aKinectW[] / ( # of columns of input video )
float _fMtr2Depth; // 100
int _nRawDataProcessingMethod;
bool _bFast;
//cameras
btl_img::SCamera::tp_shared_ptr _pRGBCamera;
btl_img::SCamera::tp_shared_ptr _pIRCamera;
btl_knt::CRGBDFrame::tp_shared_ptr _pCurrFrame;
//rgb
cv::Mat _cvmRGB;
Mat _cvmDep;
protected:
//openni
Device _device;
VideoStream _color;
VideoStream _depth;
VideoStream** _streams;//array of pointers
Recorder _recorder;
VideoFrameRef _depthFrame;
VideoFrameRef _colorFrame;
const openni::SensorInfo* _depthSensorInfo;
const openni::SensorInfo* _colorSensorInfo;
const openni::SensorInfo* _irSensorInfo;
cv::cuda::GpuMat _gpu_rgb;
cv::Mat _undist_rgb;
cv::cuda::GpuMat _gpu_undist_rgb;
//depth
cv::Mat _depth_float;
cv::cuda::GpuMat _gpu_depth;
cv::Mat _undist_depth;
cv::cuda::GpuMat _gpu_undist_depth;
cv::cuda::GpuMat _gpu_depth_float;
// duplicated camera parameters for speed up the VideoSourceKinect::align() in . because Eigen and cv matrix class is very slow.
// initialized in constructor after load of the _cCalibKinect.
float _aR[9]; // Relative rotation transpose
float _aRT[3]; // aRT =_aR * T, the relative translation
// Create and initialize the cyclic buffer
//controlling flag
static bool _bIsSequenceEnds;
std::string _strDumpFileName;
int _nMode;
float _fCutOffDistance;
// (opencv-default camera reference system convention)
Eigen::Vector3f _eivCw;
string _cam_param_file;
string _cam_param;
};//class VideoSourceKinect
} //namespace kinect
} //namespace btl
#endif //BTL_EXTRA_VIDEOSOURCE_VIDEOSOURCEKINECT
| 34.202703 | 159 | 0.771632 | [
"vector"
] |
793d0d31dfbf3623516e229dbab809e041b7d2d7 | 5,986 | hpp | C++ | apps/dawn-app/include/dawn_store.hpp | ghsecuritylab/comanche | a8862eaed59045377874b95b120832a0cba42193 | [
"Apache-2.0"
] | 19 | 2017-10-03T16:01:49.000Z | 2021-06-07T10:21:46.000Z | apps/dawn-app/include/dawn_store.hpp | ghsecuritylab/comanche | a8862eaed59045377874b95b120832a0cba42193 | [
"Apache-2.0"
] | 25 | 2018-02-21T23:43:03.000Z | 2020-09-02T08:47:32.000Z | apps/dawn-app/include/dawn_store.hpp | ghsecuritylab/comanche | a8862eaed59045377874b95b120832a0cba42193 | [
"Apache-2.0"
] | 19 | 2017-10-24T17:41:40.000Z | 2022-02-22T02:17:18.000Z | /*
* dawn_store.hpp
*
* Created on: May 21, 2019
* Author: yanzhao
*/
#ifndef INCLUDE_DAWN_STORE_HPP_
#define INCLUDE_DAWN_STORE_HPP_
#include<stdio.h>
#include<stdlib.h>
#include<vector>
#include<iostream>
// Memory Headers
#include <sys/mman.h>
// Comanche Headers
#include<common/exceptions.h>
#include<common/logging.h>
#include<common/types.h>
#include<api/components.h>
#include<api/kvstore_itf.h>
// CUDA Headers
#include<cuda.h>
#include<cuda_runtime_api.h>
// xms related headers
#include "core/physical_memory.h"
#include "core/xms.h"
#include "api/memory_itf.h"
// dawn-app headers
#include "cudautility.hpp"
#include "kvstoreutility.hpp"
// DAWN options
#define DAWN_TEST // For module testing
using namespace Component;
using namespace std;
class DawnKVStore_wrapper {
private:
/* Comanche Config */
string _comanche_component = "libcomanche-dawn-client.so";
uuid_t _component_id = dawn_client_factory;
/* DawnKVStore Config */
unsigned _debug_level = 0;
string _owner = "public";
string _addr_port = "10.0.0.51:11900";
string _device = "mlx5_0";
IKVStore * _kvstore;
/* Put large data -> put_direct*/
IKVStore::memory_handle_t _direct_handle = nullptr;
size_t _direct_size = 0;
void * _direct_mem;
vector<Pool_wrapper*> * _pools_vptr; //
public:
DawnKVStore_wrapper(string owner, string addr_port, string device, \
string comanche_component = "libcomanche-dawn-client.so", \
uuid_t component_id = dawn_client_factory, unsigned debug_level = 0):
_owner(owner),
_addr_port(addr_port),
_device(device),
_comanche_component(comanche_component),
_component_id(component_id),
_debug_level(debug_level)
{
IBase * comp = load_component(_comanche_component.c_str(), _component_id);
assert(comp);
IKVStore_factory * fact = (IKVStore_factory *) comp->query_interface(IKVStore_factory::iid());
_kvstore = fact->create(_debug_level,
_owner,
_addr_port.c_str(),
_device.c_str());
PINF("Create KVStore: %s", _comanche_component.c_str());
fact->release_ref();
_pools_vptr = new vector<Pool_wrapper*>();
}
DawnKVStore_wrapper(string owner, string addr_port, string device, unsigned debug_level = 0):
DawnKVStore_wrapper(owner, addr_port, device, \
"libcomanche-dawn-client.so", \
dawn_client_factory, debug_level) { }
~DawnKVStore_wrapper() {
_kvstore -> release_ref();
}
inline status_t put(Pool_wrapper * pool_wrapper, const std::string key, const void * value, const size_t value_len) {
//status_t rv =_kvstore->put(pool_wrapper->_pool, key, value, value_len);
status_t rv;
if (1) {//rv == IKVStore::E_TOO_LARGE) {
if (_direct_size == 0 || _direct_size < value_len) {
if (_direct_handle != nullptr) {
_kvstore->unregister_direct_memory(_direct_handle);
}
_direct_size = value_len;
_direct_mem = aligned_alloc(MiB(2), _direct_size); // TODO: Free
madvise(_direct_mem, _direct_size, MADV_HUGEPAGE);
_direct_handle = _kvstore->register_direct_memory(_direct_mem, _direct_size);
}
memcpy(_direct_mem, value, value_len);
rv = _kvstore->put_direct(pool_wrapper->_pool, key, value, value_len, _direct_handle);
}
return rv;
}
inline status_t put_direct(Pool_wrapper * pool_wrapper, const std::string key, const void * value, const size_t value_len, IKVStore::memory_handle_t handle) {
return _kvstore->put_direct(pool_wrapper->_pool, key, value, value_len, handle);
}
inline status_t get_direct(Pool_wrapper * pool_wrapper, const std::string key, void * out_value, size_t out_value_len, IKVStore::memory_handle_t handle) {
return _kvstore->get_direct(pool_wrapper->_pool, key, out_value, out_value_len, handle);
}
inline status_t get(Pool_wrapper * pool_wrapper, const std::string key, void * & out_value, size_t& out_value_len) {
return _kvstore->get(pool_wrapper->_pool, key, out_value, out_value_len);
}
inline IKVStore::memory_handle_t register_direct_memory(void * vaddr, size_t len) {
return _kvstore->register_direct_memory(vaddr, len);
}
inline status_t unregister_direct_memory(IKVStore::memory_handle_t handle) {
return _kvstore->unregister_direct_memory(handle);
}
bool create_pool(Pool_wrapper * pool_wrapper) {
try {
pool_wrapper->_pool = _kvstore->create_pool(pool_wrapper->_pool_dir,
pool_wrapper->_pool_name,
pool_wrapper->_pool_size);
PINF("Create Pool id: %d", pool_wrapper->_pool);
if (pool_wrapper->_pool == 0 || pool_wrapper->_pool == IKVStore::POOL_ERROR) {
PINF("Error: create pool");
PINF("Try to open the pool");
pool_wrapper->_pool = _kvstore->open_pool(pool_wrapper->_pool_dir, pool_wrapper->_pool_name);
}
}
catch(...) {
PINF("Error: create pool error!");
}
}
bool open_pool(Pool_wrapper * pool_wrapper) {
// Create a pool. TODO: An array of pools.
try {
pool_wrapper->_pool = _kvstore->open_pool(pool_wrapper->_pool_dir,
pool_wrapper->_pool_name);
}
catch(...) {
PINF("Error: create pool error!");
}
_pools_vptr->push_back(pool_wrapper);
return (pool_wrapper->_pool != Component::IKVStore::POOL_ERROR);
}
void close_pool(Pool_wrapper * pool_wrapper) {
_kvstore -> close_pool(pool_wrapper->_pool);
}
};
#ifdef DAWN_STORE_TEST
static void compare_buf(uint32_t *ref_buf, uint32_t *buf, size_t size)
{
int diff = 0;
assert(size % 4 == 0U);
for(unsigned w = 0; w<size/sizeof(uint32_t); ++w) {
if (ref_buf[w] != buf[w]) {
if (diff < 10)
printf("[word %d] %08x != %08x\n", w, buf[w], ref_buf[w]);
++diff;
}
}
if (diff) {
cout << "check error: diff(s)=" << diff << endl;
}
}
#endif /* DAWN_STORE_TEST */
#endif /* INCLUDE_DAWN_STORE_HPP_ */
| 30.540816 | 160 | 0.678583 | [
"vector"
] |
793dc0caebd359ede771fdb6ad77451cad9f047b | 418,392 | cpp | C++ | elenasrc2/elc/compiler.cpp | drkameleon/elena-lang | 8585e93a3bc0b19f8d60029ffbe01311d0b711a3 | [
"MIT"
] | null | null | null | elenasrc2/elc/compiler.cpp | drkameleon/elena-lang | 8585e93a3bc0b19f8d60029ffbe01311d0b711a3 | [
"MIT"
] | null | null | null | elenasrc2/elc/compiler.cpp | drkameleon/elena-lang | 8585e93a3bc0b19f8d60029ffbe01311d0b711a3 | [
"MIT"
] | null | null | null | //---------------------------------------------------------------------------
// E L E N A P r o j e c t: ELENA Compiler
//
// This file contains ELENA compiler class implementation.
//
// (C)2005-2020, by Alexei Rakov
//---------------------------------------------------------------------------
//#define FULL_OUTOUT_INFO 1
#include "elena.h"
// --------------------------------------------------------------------------
#include "compiler.h"
#include "errors.h"
#include <errno.h>
using namespace _ELENA_;
//void test2(SNode node)
//{
// SNode current = node.firstChild();
// while (current != lxNone) {
// test2(current);
// current = current.nextNode();
// }
//}
// --- Expr hint constants ---
constexpr auto HINT_NODEBUGINFO = EAttr::eaNoDebugInfo;
// --- Scope hint constants ---
constexpr auto HINT_NESTEDNS = EAttr::eaNestedNs;
constexpr auto HINT_INTERNALOP = EAttr::eaIntern;
//constexpr auto HINT_CLOSURE_MASK = EAttr::eaClosureMask;
constexpr auto HINT_SCOPE_MASK = EAttr::eaScopeMask;
constexpr auto HINT_OBJECT_MASK = EAttr::eaObjectMask;
constexpr auto HINT_MODULESCOPE = EAttr::eaModuleScope;
constexpr auto HINT_PREVSCOPE = EAttr::eaPreviousScope;
constexpr auto HINT_NEWOP = EAttr::eaNewOp;
constexpr auto HINT_CASTOP = EAttr::eaCast;
constexpr auto HINT_SILENT = EAttr::eaSilent;
constexpr auto HINT_ROOTSYMBOL = EAttr::eaRootSymbol;
constexpr auto HINT_ROOT = EAttr::eaRoot;
constexpr auto HINT_INLINE_EXPR = EAttr::eaInlineExpr;
constexpr auto HINT_NOPRIMITIVES = EAttr::eaNoPrimitives;
constexpr auto HINT_DYNAMIC_OBJECT = EAttr::eaDynamicObject; // indicates that the structure MUST be boxed
constexpr auto HINT_NOBOXING = EAttr::eaNoBoxing;
constexpr auto HINT_NOUNBOXING = EAttr::eaNoUnboxing;
constexpr auto HINT_MEMBER = EAttr::eaMember;
constexpr auto HINT_REFOP = EAttr::eaRef;
constexpr auto HINT_PROP_MODE = EAttr::eaPropExpr;
constexpr auto HINT_METAFIELD = EAttr::eaMetaField;
constexpr auto HINT_LOOP = EAttr::eaLoop;
constexpr auto HINT_EXTERNALOP = EAttr::eaExtern;
constexpr auto HINT_FORWARD = EAttr::eaForward;
constexpr auto HINT_PARAMSOP = EAttr::eaParams;
constexpr auto HINT_SWITCH = EAttr::eaSwitch;
constexpr auto HINT_CLASSREF = EAttr::eaClass;
constexpr auto HINT_YIELD_EXPR = EAttr::eaYieldExpr;
constexpr auto HINT_MESSAGEREF = EAttr::eaMssg;
constexpr auto HINT_VIRTUALEXPR = EAttr::eaVirtualExpr;
constexpr auto HINT_SUBJECTREF = EAttr::eaSubj;
constexpr auto HINT_DIRECTCALL = EAttr::eaDirectCall;
constexpr auto HINT_PARAMETER = EAttr::eaParameter;
constexpr auto HINT_LAZY_EXPR = EAttr::eaLazy;
constexpr auto HINT_INLINEARGMODE = EAttr::eaInlineArg; // indicates that the argument list should be unboxed
constexpr auto HINT_CONSTEXPR = EAttr::eaConstExpr;
constexpr auto HINT_CALLOP = EAttr::eaCallOp;
constexpr auto HINT_REFEXPR = EAttr::eaRefExpr;
constexpr auto HINT_CONVERSIONOP = EAttr::eaConversionOp;
// scope modes
constexpr auto INITIALIZER_SCOPE = EAttr::eaInitializerScope; // indicates the constructor or initializer method
typedef Compiler::ObjectInfo ObjectInfo; // to simplify code, ommiting compiler qualifier
typedef ClassInfo::Attribute Attribute;
//typedef _CompilerLogic::ExpressionAttributes ExpressionAttributes;
typedef _CompilerLogic::FieldAttributes FieldAttributes;
EAttr operator | (const EAttr& l, const EAttr& r)
{
return (EAttr)((uint64_t)l | (uint64_t)r);
}
EAttr operator & (const EAttr& l, const EAttr& r)
{
return (EAttr)((uint64_t)l & (uint64_t)r);
}
// --- Auxiliary routines ---
inline bool isPrimitiveArrRef(ref_t reference)
{
switch (reference) {
case V_OBJARRAY:
case V_INT32ARRAY:
case V_INT16ARRAY:
case V_INT8ARRAY:
case V_BINARYARRAY:
return true;
default:
return false;
}
}
inline SNode findParent(SNode node, LexicalType type)
{
while (node.type != type && node != lxNone) {
node = node.parentNode();
}
return node;
}
inline SNode findParent(SNode node, LexicalType type1, LexicalType type2)
{
while (node.type != type1 && node.type != type2 && node != lxNone) {
node = node.parentNode();
}
return node;
}
inline SNode findRootNode(SNode node, LexicalType type1, LexicalType type2, LexicalType type3)
{
SNode lastNode = node;
while (!node.compare(type1, type2, type3, lxNone)) {
lastNode = node;
node = node.parentNode();
}
return lastNode;
}
inline bool validateGenericClosure(ref_t* signature, size_t length)
{
for (size_t i = 1; i < length; i++) {
if (signature[i - 1] != signature[i])
return false;
}
return true;
}
inline bool isConstantArg(SNode current)
{
switch (current.type) {
case lxLiteral:
case lxWide:
case lxCharacter:
case lxInteger:
case lxLong:
case lxHexInteger:
case lxReal:
case lxExplicitConst:
case lxMessage:
return true;
default:
return false;
}
}
inline bool isConstantArguments(SNode node)
{
if (node == lxNone)
return true;
SNode current = node.firstChild();
while (current != lxNone) {
if (current == lxExpression) {
if (!isConstantArguments(current))
return false;
}
else if (isConstantArg(current))
return false;
current = current.nextNode();
}
return true;
}
// --- Compiler::NamespaceScope ---
Compiler::NamespaceScope :: NamespaceScope(_ModuleScope* moduleScope, ExtensionMap* outerExtensionList)
: Scope(moduleScope), constantHints(INVALID_REF), extensions(Pair<ref_t, ref_t>(0, 0)), importedNs(NULL, freestr),
extensionDispatchers(INVALID_REF), extensionTargets(INVALID_REF), extensionTemplates(NULL, freestr),
declaredExtensions(Pair<ref_t, ref_t>(0, 0))
{
// by default - private visibility
defaultVisibility = Visibility::Private;
this->outerExtensionList = outerExtensionList;
// // HOTFIX : package section should be created if at least literal class is declated
// if (moduleScope->literalReference != 0) {
// packageReference = module->mapReference(ReferenceNs("'", PACKAGE_SECTION));
// }
// else packageReference = 0;
}
Compiler::NamespaceScope :: NamespaceScope(NamespaceScope* parent)
: Scope(parent), constantHints(INVALID_REF), extensions(Pair<ref_t, ref_t>(0, 0)), importedNs(NULL, freestr),
extensionDispatchers(INVALID_REF), extensionTargets(INVALID_REF), extensionTemplates(NULL, freestr),
declaredExtensions(Pair<ref_t, ref_t>(0, 0))
{
outerExtensionList = parent->outerExtensionList;
defaultVisibility = parent->defaultVisibility;
sourcePath.copy(parent->sourcePath);
nsName.copy(parent->ns);
}
ref_t Compiler::NamespaceScope :: resolveExtensionTarget(ref_t reference)
{
ref_t resolved = extensionTargets.get(reference);
if (resolved == INVALID_REF) {
ClassInfo info;
moduleScope->loadClassInfo(info, reference);
auto key = info.fieldTypes.get(-1);
resolved = key.value1;
if (resolved)
extensionTargets.add(reference, resolved);
}
return resolved;
}
pos_t Compiler::NamespaceScope :: saveSourcePath(ByteCodeWriter& writer)
{
return saveSourcePath(writer, sourcePath);
}
pos_t Compiler::NamespaceScope :: saveSourcePath(ByteCodeWriter& writer, ident_t path)
{
if (!emptystr(path)) {
int position = moduleScope->savedPaths.get(path);
if (position == -1) {
position = writer.writeSourcePath(moduleScope->debugModule, path);
moduleScope->savedPaths.add(path, position);
}
return position;
}
else return 0;
}
ObjectInfo Compiler::NamespaceScope :: mapGlobal(ident_t identifier)
{
if (NamespaceName::isIncluded(FORWARD_MODULE, identifier)) {
IdentifierString forwardName(FORWARD_PREFIX_NS, identifier + getlength(FORWARD_MODULE) + 1);
// if it is a forward reference
return defineObjectInfo(moduleScope->mapFullReference(forwardName.c_str(), false), false);
}
// if it is an existing full reference
ref_t reference = moduleScope->mapFullReference(identifier, true);
if (reference) {
return defineObjectInfo(reference, true);
}
// if it is a forward reference
else return defineObjectInfo(moduleScope->mapFullReference(identifier, false), false);
}
ObjectInfo Compiler::NamespaceScope :: mapWeakReference(ident_t identifier, bool directResolved)
{
ref_t reference = 0;
if (directResolved) {
reference = moduleScope->mapWeakReference(identifier);
}
else reference = moduleScope->mapFullReference(identifier);
return defineObjectInfo(reference, true);
}
ObjectInfo Compiler::NamespaceScope :: mapTerminal(ident_t identifier, bool referenceOne, EAttr mode)
{
ref_t reference = 0;
if (!referenceOne) {
// try resolve as type-alias
reference = moduleScope->attributes.get(identifier);
if (isPrimitiveRef(reference))
reference = 0;
}
if (!reference)
reference = resolveImplicitIdentifier(identifier, referenceOne, !EAttrs::test(mode, HINT_NESTEDNS));
if (reference)
return defineObjectInfo(reference, true);
if (parent == NULL) {
// outer most ns
if (referenceOne) {
if (isWeakReference(identifier)) {
return mapWeakReference(identifier, false);
}
else return mapGlobal(identifier);
}
else if (identifier.compare(NIL_VAR)) {
return ObjectInfo(okNil);
}
}
return Scope::mapTerminal(identifier, referenceOne, mode | HINT_NESTEDNS);
}
ref_t Compiler::NamespaceScope :: resolveImplicitIdentifier(ident_t identifier, bool referenceOne, bool innermost)
{
ref_t reference = forwards.get(identifier);
if (reference)
return reference;
reference = moduleScope->resolveImplicitIdentifier(ns, identifier, Visibility::Public);
// check if it is an internal one
if (!reference)
reference = moduleScope->resolveImplicitIdentifier(ns, identifier, Visibility::Internal);
// check if it is a private one for the inner most
if (innermost && !reference)
reference = moduleScope->resolveImplicitIdentifier(ns, identifier, Visibility::Private);
if (!reference && !referenceOne)
reference = moduleScope->resolveImportedIdentifier(identifier, &importedNs);
if (reference) {
forwards.add(identifier, reference);
}
return reference;
}
ref_t Compiler::NamespaceScope :: mapNewTerminal(SNode terminal, Visibility visibility)
{
if (terminal == lxNameAttr) {
// verify if the name is unique
ident_t name = terminal.firstChild(lxTerminalMask).identifier();
terminal.setArgument(moduleScope->mapNewIdentifier(ns.c_str(), name, visibility));
ref_t reference = terminal.argument;
if (visibility == Visibility::Public) {
ref_t dup = moduleScope->resolveImplicitIdentifier(ns.c_str(), name, Visibility::Internal);
if (!dup)
dup = moduleScope->resolveImplicitIdentifier(ns.c_str(), name, Visibility::Private);
if (dup)
reference = dup;
}
else if (visibility == Visibility::Internal) {
ref_t dup = moduleScope->resolveImplicitIdentifier(ns.c_str(), name, Visibility::Public);
if (!dup)
dup = moduleScope->resolveImplicitIdentifier(ns.c_str(), name, Visibility::Private);
if (dup)
reference = dup;
}
else if (visibility == Visibility::Private) {
ref_t dup = moduleScope->resolveImplicitIdentifier(ns.c_str(), name, Visibility::Public);
if (!dup)
dup = moduleScope->resolveImplicitIdentifier(ns.c_str(), name, Visibility::Internal);
if (dup)
reference = dup;
}
if (module->mapSection(reference | mskSymbolRef, true))
raiseError(errDuplicatedSymbol, terminal.firstChild(lxTerminalMask));
return terminal.argument;
}
else if (terminal == lxNone) {
return moduleScope->mapAnonymous();
}
else throw InternalError("Cannot map new terminal"); // !! temporal
}
ObjectInfo Compiler::NamespaceScope :: defineObjectInfo(ref_t reference, bool checkState)
{
// if reference is zero the symbol is unknown
if (reference == 0) {
return ObjectInfo();
}
// check if symbol should be treated like constant one
else if (constantHints.exist(reference)) {
return ObjectInfo(okConstantSymbol, reference, constantHints.get(reference));
}
else if (checkState) {
ClassInfo info;
// check if the object can be treated like a constant object
ref_t r = moduleScope->loadClassInfo(info, reference, true);
if (r) {
// if it is an extension
if (test(info.header.flags, elExtension)) {
return ObjectInfo(okExtension, reference, reference);
}
// if it is a stateless symbol
else if (test(info.header.flags, elStateless)) {
return ObjectInfo(okSingleton, reference, reference);
}
// if it is a normal class
// then the symbol is reference to the class class
else if (test(info.header.flags, elStandartVMT) && info.header.classRef != 0) {
return ObjectInfo(okClass, reference, info.header.classRef);
}
}
else {
// check if the object is typed expression
SymbolExpressionInfo symbolInfo;
// check if the object can be treated like a constant object
r = moduleScope->loadSymbolExpressionInfo(symbolInfo, module->resolveReference(reference));
if (r) {
ref_t outputRef = symbolInfo.exprRef;
// if it is a constant
if (symbolInfo.type == SymbolExpressionInfo::Type::Constant) {
//ref_t classRef = symbolInfo.exprRef;
/*if (symbolInfo.listRef != 0) {
return ObjectInfo(okArrayConst, symbolInfo.listRef, classRef);
}
else */return ObjectInfo(okConstantSymbol, reference, outputRef);
}
else if (symbolInfo.type == SymbolExpressionInfo::Type::Singleton) {
return ObjectInfo(okSingleton, outputRef, outputRef);
}
else if (symbolInfo.type == SymbolExpressionInfo::Type::ConstantSymbol) {
return defineObjectInfo(outputRef, true);
}
// if it is a typed symbol
else if (outputRef != 0) {
return ObjectInfo(okSymbol, reference, outputRef);
}
}
}
}
// otherwise it is a normal one
return ObjectInfo(okSymbol, reference);
}
//////void Compiler::ModuleScope :: validateReference(SNode terminal, ref_t reference)
//////{
////// // check if the reference may be resolved
////// bool found = false;
//////
////// if (warnOnWeakUnresolved || !isWeakReference(terminal.identifier())) {
////// int mask = reference & mskAnyRef;
////// reference &= ~mskAnyRef;
//////
////// ref_t ref = 0;
////// _Module* refModule = project->resolveModule(module->resolveReference(reference), ref, true);
//////
////// if (refModule != NULL) {
////// found = (refModule->mapSection(ref | mask, true)!=NULL);
////// }
////// if (!found) {
////// if (!refModule || refModule == module) {
////// forwardsUnresolved->add(Unresolved(sourcePath, reference | mask, module,
////// terminal.findChild(lxRow).argument,
////// terminal.findChild(lxCol).argument));
////// }
////// else raiseWarning(WARNING_LEVEL_1, wrnUnresovableLink, terminal);
////// }
////// }
//////}
void Compiler::NamespaceScope :: loadExtensions(ident_t ns)
{
ReferenceNs sectionName(ns, EXTENSION_SECTION);
ref_t extRef = 0;
_Module* extModule = moduleScope->loadReferenceModule(module->mapReference(sectionName, false), extRef);
_Memory* section = extModule ? extModule->mapSection(extRef | mskMetaRDataRef, true) : NULL;
if (section) {
MemoryReader metaReader(section);
while (!metaReader.Eof()) {
extRef = metaReader.getDWord();
ref_t message = metaReader.getDWord();
ref_t strongMessage = metaReader.getDWord();
if (extModule != module) {
extRef = importReference(extModule, extRef, module);
message = importMessage(extModule, message, module);
strongMessage = importMessage(extModule, strongMessage, module);
}
if (!extRef) {
// if it is an extension template
ident_t pattern = metaReader.getLiteral(DEFAULT_STR);
extensionTemplates.add(message, pattern.clone());
}
else extensions.add(message, Pair<ref_t, ref_t>(extRef, strongMessage));
}
}
}
void Compiler::NamespaceScope :: saveExtension(ref_t message, ref_t extRef, ref_t strongMessage, bool internalOne)
{
// if (typeRef == INVALID_REF || typeRef == moduleScope->superReference)
// typeRef = 0;
Pair<ref_t, ref_t> extInfo(extRef, strongMessage);
if (outerExtensionList != nullptr) {
// COMPILER MAGIC : if it is template extension compilation
outerExtensionList->add(message, extInfo);
}
else {
IdentifierString sectionName(internalOne ? PRIVATE_PREFIX_NS : "'");
if (!emptystr(ns)) {
sectionName.append(ns);
sectionName.append("'");
}
sectionName.append(EXTENSION_SECTION);
MemoryWriter metaWriter(module->mapSection(module->mapReference(sectionName, false) | mskMetaRDataRef, false));
// if (typeRef == moduleScope->superReference) {
// metaWriter.writeDWord(0);
// }
/*else */metaWriter.writeDWord(extRef);
metaWriter.writeDWord(message);
metaWriter.writeDWord(strongMessage);
declaredExtensions.add(message, extInfo);
}
extensions.add(message, extInfo);
}
void Compiler::NamespaceScope :: saveExtensionTemplate(ref_t message, ident_t pattern)
{
IdentifierString sectionName(/*internalOne ? PRIVATE_PREFIX_NS : */"'");
if (!emptystr(ns)) {
sectionName.append(ns);
sectionName.append("'");
}
sectionName.append(EXTENSION_SECTION);
MemoryWriter metaWriter(module->mapSection(module->mapReference(sectionName, false) | mskMetaRDataRef, false));
metaWriter.writeDWord(0);
metaWriter.writeDWord(message);
metaWriter.writeDWord(0);
metaWriter.writeLiteral(pattern.c_str());
extensionTemplates.add(message, pattern.clone());
}
// --- Compiler::SourceScope ---
Compiler::SourceScope :: SourceScope(Scope* moduleScope, ref_t reference, Visibility visibility)
: Scope(moduleScope)
{
this->reference = reference;
this->visibility = visibility;
}
// --- Compiler::SymbolScope ---
Compiler::SymbolScope :: SymbolScope(NamespaceScope* parent, ref_t reference, Visibility visibility)
: SourceScope(parent, reference, visibility)
{
staticOne = false;
preloaded = false;
}
//ObjectInfo Compiler::SymbolScope :: mapTerminal(ident_t identifier)
//{
// return Scope::mapTerminal(identifier);
//}
void Compiler::SymbolScope :: save()
{
// save class meta data
MemoryWriter metaWriter(moduleScope->module->mapSection(reference | mskMetaRDataRef, false), 0);
info.save(&metaWriter);
}
// --- Compiler::ClassScope ---
Compiler::ClassScope :: ClassScope(Scope* parent, ref_t reference, Visibility visibility)
: SourceScope(parent, reference, visibility)
{
info.header.parentRef = moduleScope->superReference;
info.header.flags = elStandartVMT;
info.header.count = 0;
info.header.classRef = 0;
info.header.staticSize = 0;
info.size = 0;
extensionClassRef = 0;
stackSafe = false;
classClassMode = false;
abstractMode = false;
abstractBaseMode = false;
withInitializers = false;
extensionDispatcher = false;
}
ObjectInfo Compiler::ClassScope :: mapField(ident_t terminal, EAttr scopeMode)
{
int offset = info.fields.get(terminal);
if (offset >= 0) {
bool readOnlyMode = test(info.header.flags, elReadOnlyRole) && !EAttrs::test(scopeMode, INITIALIZER_SCOPE);
ClassInfo::FieldInfo fieldInfo = info.fieldTypes.get(offset);
if (test(info.header.flags, elStructureRole)) {
return ObjectInfo(readOnlyMode ? okReadOnlyFieldAddress : okFieldAddress, offset, fieldInfo.value1, fieldInfo.value2, 0);
}
else return ObjectInfo(readOnlyMode ? okReadOnlyField : okField, offset, fieldInfo.value1, fieldInfo.value2, 0);
}
else if (offset == -2 && test(info.header.flags, elDynamicRole)) {
auto fieldInfo = info.fieldTypes.get(-1);
return ObjectInfo(okSelfParam, 1, fieldInfo.value1, fieldInfo.value2, (ref_t)-2);
}
else {
ClassInfo::FieldInfo staticInfo = info.statics.get(terminal);
if (staticInfo.value1 != 0) {
if (!isSealedStaticField(staticInfo.value1)) {
//ref_t val = info.staticValues.get(staticInfo.value1);
// if (val != mskStatRef) {
if (classClassMode) {
return ObjectInfo(okClassStaticConstantField, staticInfo.value1, staticInfo.value2);
}
else return ObjectInfo(okStaticConstantField, staticInfo.value1, staticInfo.value2);
// }
}
else if(info.staticValues.exist(staticInfo.value1, mskConstantRef)) {
// if it is a constant static sealed field
if (classClassMode) {
return ObjectInfo(okClassStaticConstantField, staticInfo.value1, staticInfo.value2);
}
else return ObjectInfo(okStaticConstantField, staticInfo.value1, staticInfo.value2);
}
//
// if (classClassMode) {
// return ObjectInfo(okClassStaticField, 0, staticInfo.value2, 0, staticInfo.value1);
// }
/*else */return ObjectInfo(okStaticField, staticInfo.value1, staticInfo.value2, 0, 0);
//
}
return ObjectInfo();
}
}
ObjectInfo Compiler::ClassScope :: mapTerminal(ident_t identifier, bool referenceOne, EAttr mode)
{
if (!referenceOne && identifier.compare(SUPER_VAR)) {
return ObjectInfo(okSuper, 1, info.header.parentRef, 0, stackSafe ? -1 : 0);
}
else {
if (!referenceOne) {
ObjectInfo fieldInfo = mapField(identifier, mode);
if (fieldInfo.kind != okUnknown) {
return fieldInfo;
}
}
ObjectInfo retVal = Scope::mapTerminal(identifier, referenceOne, mode);
if (retVal.kind == okClass) {
}
return retVal;
}
}
// --- Compiler::MetodScope ---
Compiler::MethodScope :: MethodScope(ClassScope* parent)
: Scope(parent), parameters(Parameter())
{
this->message = 0;
this->reserved1 = this->reserved2 = 0;
this->scopeMode = EAttr::eaNone;
// this->rootToFree = 1;
this->hints = 0;
this->outputRef = INVALID_REF; // to indicate lazy load
this->withOpenArg = false;
this->classStacksafe = false;
this->generic = false;
this->extensionMode = false;
this->multiMethod = false;
this->functionMode = false;
this->nestedMode = parent->getScope(Scope::ScopeLevel::slOwnerClass) != parent;
// this->subCodeMode = false;
this->abstractMethod = false;
this->mixinFunction = false;
this->embeddableRetMode = false;
this->targetSelfMode = false;
this->yieldMethod = false;
//// this->dispatchMode = false;
this->constMode = false;
this->preallocated = 0;
}
ObjectInfo Compiler::MethodScope :: mapSelf()
{
if (extensionMode) {
//COMPILER MAGIC : if it is an extension ; replace self with this self
ClassScope* extensionScope = (ClassScope*)getScope(ScopeLevel::slClass);
return ObjectInfo(okLocal, (ref_t)-1, extensionScope->extensionClassRef, 0, extensionScope->stackSafe ? -1 : 0);
}
else if (classStacksafe) {
return ObjectInfo(okSelfParam, 1, getClassRef(false), 0, (ref_t)-1);
}
else return ObjectInfo(okSelfParam, 1, getClassRef(false));
}
ObjectInfo Compiler::MethodScope :: mapGroup()
{
return ObjectInfo(okParam, (size_t)-1);
}
ObjectInfo Compiler::MethodScope :: mapParameter(Parameter param, EAttr mode)
{
int prefix = functionMode ? 0 : -1;
if (withOpenArg && param.class_ref == V_ARGARRAY) {
return ObjectInfo(okParams, prefix - param.offset, param.class_ref, param.element_ref, 0);
}
else if (param.class_ref != 0 && param.size != 0) {
// if the parameter may be stack-allocated
return ObjectInfo(okParam, prefix - param.offset, param.class_ref, param.element_ref, (ref_t)-1);
}
else if (param.class_ref == V_WRAPPER && !EAttrs::testany(mode, HINT_PROP_MODE | HINT_REFEXPR)) {
return ObjectInfo(okParamField, prefix - param.offset, param.element_ref, 0, 0);
}
else return ObjectInfo(okParam, prefix - param.offset, param.class_ref, param.element_ref, 0);
}
ObjectInfo Compiler::MethodScope :: mapTerminal(ident_t terminal, bool referenceOne, EAttr mode)
{
if (!referenceOne && !EAttrs::test(mode, HINT_MODULESCOPE)) {
Parameter param = parameters.get(terminal);
if (param.offset >= 0) {
return mapParameter(param, mode);
}
else {
if (terminal.compare(SELF_VAR)) {
if (targetSelfMode) {
return mapGroup();
}
else if (functionMode || nestedMode) {
return parent->mapTerminal(OWNER_VAR, false, mode | scopeMode);
}
else return mapSelf();
}
else if (!functionMode && (terminal.compare(GROUP_VAR))) {
if (extensionMode) {
return mapSelf();
}
else return mapGroup();
}
// else if (terminal.compare(RETVAL_VAR) && subCodeMode) {
// ObjectInfo retVar = parent->mapTerminal(terminal, referenceOne, mode | scopeMode);
// if (retVar.kind == okUnknown) {
// InlineClassScope* closure = (InlineClassScope*)getScope(Scope::slClass);
//
// retVar = closure->allocateRetVar();
// }
//
// return retVar;
// }
}
}
return Scope::mapTerminal(terminal, referenceOne, mode | scopeMode);
}
// --- Compiler::YieldMethodScope ---
Compiler::YieldScope :: YieldScope(MethodScope* parent)
: Scope(parent)
{
}
// --- Compiler::CodeScope ---
Compiler::CodeScope :: CodeScope(SourceScope* parent)
: Scope(parent), locals(Parameter(0))
{
this->allocated1 = this->reserved1 = 0;
this->allocated2 = this->reserved2 = 0;
this->withRetStatement = this->genericMethod = false;
}
Compiler::CodeScope :: CodeScope(MethodScope* parent)
: Scope(parent), locals(Parameter(0))
{
this->allocated1 = this->reserved1 = 0;
this->allocated2 = this->reserved2 = 0;
this->genericMethod = parent->generic;
this->withRetStatement = false;
}
Compiler::CodeScope :: CodeScope(YieldScope* parent)
: Scope(parent), locals(Parameter(0))
{
MethodScope* methodScope = (MethodScope*)parent->getScope(ScopeLevel::slMethod);
this->allocated1 = this->reserved1 = 0;
this->allocated2 = this->reserved2 = 0;
this->genericMethod = methodScope->generic;
this->withRetStatement = false;
}
Compiler::CodeScope :: CodeScope(CodeScope* parent)
: Scope(parent), locals(Parameter(0))
{
this->allocated1 = parent->allocated1;
this->reserved1 = parent->reserved1;
this->allocated2 = parent->allocated2;
this->reserved2 = parent->reserved2;
this->genericMethod = parent->genericMethod;
this->withRetStatement = false;
}
//ObjectInfo Compiler::CodeScope :: mapGlobal(ident_t identifier)
//{
// NamespaceScope* nsScope = (NamespaceScope*)getScope(Scope::slNamespace);
//
// return nsScope->mapGlobal(identifier);
//}
ObjectInfo Compiler::CodeScope :: mapLocal(ident_t identifier)
{
Parameter local = locals.get(identifier);
if (local.offset) {
if (genericMethod && identifier.compare(MESSAGE_VAR)) {
return ObjectInfo(okMessage, local.offset, V_MESSAGE);
}
else if (local.size != 0) {
return ObjectInfo(okLocalAddress, local.offset, local.class_ref, local.element_ref, 0);
}
else return ObjectInfo(okLocal, local.offset, local.class_ref, local.element_ref, 0);
}
else return ObjectInfo();
}
ObjectInfo Compiler::CodeScope :: mapTerminal(ident_t identifier, bool referenceOne, EAttr mode)
{
if (!referenceOne) {
if (!EAttrs::testany(mode, HINT_MODULESCOPE | HINT_PREVSCOPE)) {
ObjectInfo info = mapLocal(identifier);
if (info.kind != okUnknown)
return info;
}
else mode = EAttrs::exclude(mode, HINT_PREVSCOPE);
}
return Scope::mapTerminal(identifier, referenceOne, mode);
}
bool Compiler::CodeScope :: resolveAutoType(ObjectInfo& info, ref_t reference, ref_t element)
{
if (info.kind == okLocal) {
for (auto it = locals.start(); !it.Eof(); it++) {
if ((*it).offset == (int)info.param) {
if ((*it).class_ref == V_AUTO) {
(*it).class_ref = reference;
(*it).element_ref = element;
info.extraparam = reference;
info.element = element;
return true;
}
}
}
}
return Scope::resolveAutoType(info, reference, element);
}
// --- Compiler::ExprScope ---
Compiler::ExprScope :: ExprScope(CodeScope* parent)
: Scope(parent), tempLocals(NOTFOUND_POS)
{
callNode = parent->parentCallNode;
tempAllocated1 = parent->allocated1;
tempAllocated2 = parent->allocated2;
ignoreDuplicates = false;
}
Compiler::ExprScope :: ExprScope(SourceScope* parent)
: Scope(parent), tempLocals(NOTFOUND_POS)
{
tempAllocated1 = -1;
tempAllocated2 = -1;
ignoreDuplicates = false;
}
int Compiler::ExprScope :: newTempLocal()
{
CodeScope* codeScope = (CodeScope*)getScope(Scope::ScopeLevel::slCode);
tempAllocated1++;
if (tempAllocated1 > codeScope->reserved1)
codeScope->reserved1 = tempAllocated1;
return tempAllocated1;
}
inline int newLocalAddr(int allocated)
{
return -2 - allocated;
}
int Compiler::ExprScope :: newTempLocalAddress()
{
CodeScope* codeScope = (CodeScope*)getScope(Scope::ScopeLevel::slCode);
int allocated = tempAllocated2;
tempAllocated2++;
if (tempAllocated2 > codeScope->reserved2)
codeScope->reserved2 = tempAllocated2;
return newLocalAddr(allocated);
}
ObjectInfo Compiler::ExprScope :: mapGlobal(ident_t identifier)
{
NamespaceScope* nsScope = (NamespaceScope*)getScope(ScopeLevel::slNamespace);
return nsScope->mapGlobal(identifier);
}
ObjectInfo Compiler::ExprScope :: mapMember(ident_t identifier)
{
MethodScope* methodScope = (MethodScope*)getScope(Scope::ScopeLevel::slMethod);
if (identifier.compare(SELF_VAR)) {
if (methodScope != nullptr) {
return methodScope->mapSelf();
}
}
//else if (identifier.compare(GROUP_VAR)) {
// if (methodScope != NULL) {
// return methodScope->mapGroup();
// }
//}
else {
ClassScope* classScope = (ClassScope*)getScope(Scope::ScopeLevel::slClass);
if (classScope != nullptr) {
if (methodScope != nullptr) {
return classScope->mapField(identifier, methodScope->scopeMode);
}
else return classScope->mapField(identifier, INITIALIZER_SCOPE);
}
}
return ObjectInfo();
}
// --- Compiler::ResendScope ---
inline bool isField(Compiler::ObjectKind kind)
{
switch (kind) {
case Compiler::okField:
case Compiler::okReadOnlyField:
case Compiler::okFieldAddress:
case Compiler::okReadOnlyFieldAddress:
default:
return false;
}
}
ObjectInfo Compiler::ResendScope :: mapTerminal(ident_t identifier, bool referenceOne, EAttr mode)
{
if (!withFrame && (identifier.compare(SELF_VAR) || identifier.compare(GROUP_VAR)))
{
return ObjectInfo();
}
ObjectInfo info = ExprScope::mapTerminal(identifier, referenceOne, mode);
if (consructionMode && isField(info.kind)) {
return ObjectInfo();
}
else return info;
}
// --- Compiler::InlineClassScope ---
Compiler::InlineClassScope :: InlineClassScope(ExprScope* owner, ref_t reference)
: ClassScope(owner, reference, Visibility::Internal), outers(Outer())//, outerFieldTypes(ClassInfo::FieldInfo(0, 0))
{
// this->returningMode = false;
// //this->parent = owner;
info.header.flags |= elNestedClass;
}
Compiler::InlineClassScope::Outer Compiler::InlineClassScope :: mapParent()
{
Outer parentVar = outers.get(PARENT_VAR);
// if owner reference is not yet mapped, add it
if (parentVar.outerObject.kind == okUnknown) {
parentVar.reference = info.fields.Count();
ExprScope* exprScope = (ExprScope*)parent->getScope(Scope::ScopeLevel::slExpression);
if (exprScope) {
parentVar.outerObject = exprScope->mapMember(SELF_VAR);
}
else parentVar = mapOwner();
outers.add(PARENT_VAR, parentVar);
mapKey(info.fields, PARENT_VAR, (int)parentVar.reference);
}
return parentVar;
}
Compiler::InlineClassScope::Outer Compiler::InlineClassScope :: mapSelf()
{
Outer owner = outers.get(SELF_VAR);
// if owner reference is not yet mapped, add it
if (owner.outerObject.kind == okUnknown) {
owner.reference = info.fields.Count();
owner.outerObject = parent->mapTerminal(SELF_VAR, false, EAttr::eaNone);
if (owner.outerObject.kind == okUnknown) {
// HOTFIX : if it is a singleton nested class
owner.outerObject = ObjectInfo(okSelfParam, 1, reference);
}
else if (owner.outerObject.kind == okSelfParam) {
owner.outerObject.reference = ((CodeScope*)parent)->getClassRefId(false);
}
outers.add(SELF_VAR, owner);
mapKey(info.fields, SELF_VAR, (int)owner.reference);
}
return owner;
}
Compiler::InlineClassScope::Outer Compiler::InlineClassScope :: mapOwner()
{
Outer owner = outers.get(OWNER_VAR);
// if owner reference is not yet mapped, add it
if (owner.outerObject.kind == okUnknown) {
owner.outerObject = parent->mapTerminal(OWNER_VAR, false, EAttr::eaNone);
if (owner.outerObject.kind != okUnknown) {
owner.reference = info.fields.Count();
if (owner.outerObject.extraparam == 0)
owner.outerObject.extraparam = ((CodeScope*)parent)->getClassRefId(false);
outers.add(OWNER_VAR, owner);
mapKey(info.fields, OWNER_VAR, (int)owner.reference);
}
else return mapSelf();
}
return owner;
}
ObjectInfo Compiler::InlineClassScope :: mapTerminal(ident_t identifier, bool referenceOne, EAttr mode)
{
if (identifier.compare(SUPER_VAR)) {
return ObjectInfo(okSuper, 0, info.header.parentRef);
}
else if (identifier.compare(OWNER_VAR)) {
Outer owner = mapOwner();
// map as an outer field (reference to outer object and outer object field index)
return ObjectInfo(okOuterSelf, owner.reference, owner.outerObject.reference, owner.outerObject.element, owner.outerObject.extraparam);
}
else {
Outer outer = outers.get(identifier);
// if object already mapped
if (outer.reference != -1) {
if (outer.outerObject.kind == okSuper) {
return ObjectInfo(okSuper, 0, outer.reference);
}
else return ObjectInfo(okOuter, outer.reference, outer.outerObject.reference, outer.outerObject.element, outer.outerObject.extraparam);
}
else {
outer.outerObject = parent->mapTerminal(identifier, referenceOne, mode);
switch (outer.outerObject.kind) {
case okReadOnlyField:
case okField:
// case okStaticField:
{
// handle outer fields in a special way: save only self
Outer owner = mapParent();
// map as an outer field (reference to outer object and outer object field index)
if (outer.outerObject.kind == okOuterField) {
return ObjectInfo(okOuterField, owner.reference, outer.outerObject.reference, outer.outerObject.element, outer.outerObject.extraparam);
}
else if (outer.outerObject.kind == okOuterReadOnlyField) {
return ObjectInfo(okOuterReadOnlyField, owner.reference, outer.outerObject.reference, outer.outerObject.element, outer.outerObject.extraparam);
}
/*else if (outer.outerObject.kind == okOuterStaticField) {
return ObjectInfo(okOuterStaticField, owner.reference, outer.outerObject.reference, outer.outerObject.element, outer.outerObject.extraparam);
}
else if (outer.outerObject.kind == okStaticField) {
return ObjectInfo(okOuterStaticField, owner.reference, outer.outerObject.reference, outer.outerObject.element, outer.outerObject.extraparam);
}*/
else if (outer.outerObject.kind == okReadOnlyField) {
return ObjectInfo(okOuterReadOnlyField, owner.reference, outer.outerObject.reference, outer.outerObject.element, outer.outerObject.param);
}
else return ObjectInfo(okOuterField, owner.reference, outer.outerObject.reference, outer.outerObject.element, outer.outerObject.param);
}
case okParam:
case okLocal:
case okOuter:
case okSuper:
case okSelfParam:
case okLocalAddress:
case okFieldAddress:
case okReadOnlyFieldAddress:
case okOuterField:
//case okOuterStaticField:
case okOuterSelf:
case okParams:
{
// map if the object is outer one
outer.reference = info.fields.Count();
outers.add(identifier, outer);
mapKey(info.fields, identifier, (int)outer.reference);
if (outer.outerObject.kind == okOuter && identifier.compare(RETVAL_VAR)) {
// HOTFIX : quitting several clsoures
(*outers.getIt(identifier)).preserved = true;
}
else if (outer.outerObject.kind == okOuterSelf) {
// HOTFIX : to support self in deep nested closures
return ObjectInfo(okOuterSelf, outer.reference, outer.outerObject.reference, outer.outerObject.element, outer.outerObject.extraparam);
}
return ObjectInfo(okOuter, outer.reference, outer.outerObject.reference);
}
case okUnknown:
{
// check if there is inherited fields
ObjectInfo fieldInfo = mapField(identifier, EAttr::eaNone);
if (fieldInfo.kind != okUnknown) {
return fieldInfo;
}
else return outer.outerObject;
}
default:
return outer.outerObject;
}
}
}
}
bool Compiler::InlineClassScope :: markAsPresaved(ObjectInfo object)
{
if (object.kind == okOuter) {
Map<ident_t, Outer>::Iterator it = outers.start();
while (!it.Eof()) {
if ((*it).reference == object.param) {
if ((*it).outerObject.kind == okLocal || (*it).outerObject.kind == okLocalAddress) {
(*it).preserved = true;
return true;
}
else if ((*it).outerObject.kind == okOuter) {
InlineClassScope* closure = (InlineClassScope*)parent->getScope(Scope::ScopeLevel::slClass);
if (closure->markAsPresaved((*it).outerObject)) {
(*it).preserved = true;
return true;
}
else return false;
}
break;
}
it++;
}
}
return false;
}
//ObjectInfo Compiler::InlineClassScope :: allocateRetVar()
//{
// returningMode = true;
//
// Outer outer;
// outer.reference = info.fields.Count();
// outer.outerObject = ObjectInfo(okNil, (ref_t)-1);
//
// outers.add(RETVAL_VAR, outer);
// mapKey(info.fields, RETVAL_VAR, (int)outer.reference);
//
// return ObjectInfo(okOuter, outer.reference);
//}
// --- Compiler ---
Compiler :: Compiler(_CompilerLogic* logic)
: _sourceRules(SNodePattern(lxNone))
{
_optFlag = 0;
_autoSystemImport = false;
_dynamicDispatching = true; // !! temporal
this->_logic = logic;
ByteCodeCompiler::loadOperators(_operators);
}
void Compiler :: writeMessageInfo(SNode node, _ModuleScope& scope, ref_t messageRef)
{
ref_t actionRef, flags;
int argCount;
decodeMessage(messageRef, actionRef, argCount, flags);
IdentifierString name;
ref_t signature = 0;
name.append(scope.module->resolveAction(actionRef, signature));
name.append('[');
name.appendInt(argCount);
name.append(']');
node.appendNode(lxMessageVariable, name);
}
void Compiler :: loadRules(StreamReader* optimization)
{
_rules.load(optimization);
}
void Compiler :: loadSourceRules(StreamReader* optimization)
{
_sourceRules.load(optimization);
}
bool Compiler :: optimizeIdleBreakpoints(CommandTape& tape)
{
return CommandTape::optimizeIdleBreakpoints(tape);
}
bool Compiler :: optimizeJumps(CommandTape& tape)
{
return CommandTape::optimizeJumps(tape);
}
bool Compiler :: applyRules(CommandTape& tape)
{
if (!_rules.loaded)
return false;
if (_rules.apply(tape)) {
while (_rules.apply(tape));
return true;
}
else return false;
}
void Compiler :: optimizeTape(CommandTape& tape)
{
// HOTFIX : remove all breakpoints which follows jumps
while (optimizeIdleBreakpoints(tape));
// optimize unused and idle jumps
while (optimizeJumps(tape));
// optimize the code
bool modified = false;
while (applyRules(tape)) {
modified = true;
}
if (modified) {
optimizeTape(tape);
}
}
bool Compiler :: calculateIntOp(int operation_id, int arg1, int arg2, int& retVal)
{
switch (operation_id)
{
case ADD_OPERATOR_ID:
retVal = arg1 + arg2;
break;
case SUB_OPERATOR_ID:
retVal = arg1 - arg2;
break;
case MUL_OPERATOR_ID:
retVal = arg1 * arg2;
break;
case DIV_OPERATOR_ID:
retVal = arg1 / arg2;
break;
case AND_OPERATOR_ID:
retVal = arg1 & arg2;
break;
case OR_OPERATOR_ID:
retVal = arg1 | arg2;
break;
case XOR_OPERATOR_ID:
retVal = arg1 ^ arg2;
break;
case SHIFTR_OPERATOR_ID:
retVal = arg1 >> arg2;
break;
case SHIFTL_OPERATOR_ID:
retVal = arg1 << arg2;
break;
default:
return false;
}
return true;
}
bool Compiler :: calculateRealOp(int operation_id, double arg1, double arg2, double& retVal)
{
switch (operation_id)
{
case ADD_OPERATOR_ID:
retVal = arg1 + arg2;
break;
case SUB_OPERATOR_ID:
retVal = arg1 - arg2;
break;
case MUL_OPERATOR_ID:
retVal = arg1 * arg2;
break;
case DIV_OPERATOR_ID:
retVal = arg1 / arg2;
break;
default:
return false;
}
return true;
}
ref_t Compiler :: resolveConstantObjectReference(_CompileScope& scope, ObjectInfo object)
{
switch (object.kind) {
case okIntConstant:
return scope.moduleScope->intReference;
//case okSignatureConstant:
// return scope.moduleScope->signatureReference;
default:
return resolveObjectReference(scope, object, false);
}
}
ref_t Compiler :: resolveObjectReference(_CompileScope& scope, ObjectInfo object, bool noPrimitivesMode, bool unboxWapper)
{
ref_t retVal = object.reference;
ref_t elementRef = object.element;
/*if (object.kind == okSelfParam) {
if (object.extraparam == (ref_t)-2) {
// HOTFIX : to return the primitive array
retVal = object.reference;
}
else retVal = scope.getClassRefId(false);
}
else */if (unboxWapper && object.reference == V_WRAPPER) {
elementRef = 0;
retVal = object.element;
}
else if (object.kind == okNil) {
return V_NIL;
}
if (noPrimitivesMode && isPrimitiveRef(retVal)) {
return resolvePrimitiveReference(scope, retVal, elementRef, false);
}
else return retVal;
}
inline void writeClassNameInfo(SNode& node, _Module* module, ref_t reference)
{
ident_t className = module->resolveReference(reference);
if (isTemplateWeakReference(className)) {
// HOTFIX : save weak template-based class name directly
node.appendNode(lxClassName, className);
}
else {
IdentifierString fullName(module->Name(), className);
node.appendNode(lxClassName, fullName.c_str());
}
}
void Compiler :: declareCodeDebugInfo(SNode node, MethodScope& scope)
{
node.appendNode(lxSourcePath, scope.saveSourcePath(_writer, node.identifier()));
}
void Compiler :: declareProcedureDebugInfo(SNode node, MethodScope& scope, bool withSelf/*, bool withTargetSelf*/)
{
_ModuleScope* moduleScope = scope.moduleScope;
// declare built-in variables
if (withSelf) {
if (scope.classStacksafe) {
SNode selfNode = node.appendNode(lxBinarySelf, 1);
writeClassNameInfo(selfNode, scope.module, scope.getClassRef());
}
else node.appendNode(lxSelfVariable, 1);
}
// if (withTargetSelf)
// writer.appendNode(lxSelfVariable, -1);
writeMessageInfo(node, *moduleScope, scope.message);
int prefix = scope.functionMode ? 0 : -1;
SNode current = node.firstChild();
// method parameter debug info
while (current != lxNone) {
if (current == lxMethodParameter/* || current == lxIdentifier*/) {
SNode identNode = current.findChild(lxNameAttr);
if (identNode != lxNone) {
identNode = identNode.firstChild(lxTerminalMask);
}
// else identNode = current.firstChild(lxTerminalMask);
if (identNode != lxNone) {
Parameter param = scope.parameters.get(identNode.identifier());
if (param.offset != -1) {
SNode varNode;
if (param.class_ref == V_ARGARRAY) {
varNode = node.appendNode(lxParamsVariable);
}
else if (param.class_ref == moduleScope->intReference) {
varNode = node.appendNode(lxIntVariable);
}
else if (param.class_ref == moduleScope->longReference) {
varNode = node.appendNode(lxLongVariable);
}
else if (param.class_ref == moduleScope->realReference) {
varNode = node.appendNode(lxReal64Variable);
}
else if (param.size != 0 && param.class_ref != 0) {
ref_t classRef = param.class_ref;
if (classRef != 0 && _logic->isEmbeddable(*moduleScope, classRef)) {
varNode = node.appendNode(lxBinaryVariable);
writeClassNameInfo(node, scope.module, classRef);
}
else varNode = node.appendNode(lxVariable);
}
else varNode = node.appendNode(lxVariable);
varNode.appendNode(lxLevel, prefix - param.offset);
IdentifierString name(identNode.identifier());
varNode.appendNode(lxIdentifier, name.c_str());
}
}
}
else if (current == lxSourcePath) {
current.setArgument(scope.saveSourcePath(_writer, current.identifier()));
}
current = current.nextNode();
}
}
inline SNode findIdentifier(SNode current)
{
if (current.firstChild(lxTerminalMask))
return current.firstChild(lxTerminalMask);
return current;
}
void Compiler :: importCode(SNode node, Scope& scope, ref_t functionRef, ref_t message)
{
_ModuleScope* moduleScope = scope.moduleScope;
IdentifierString virtualReference(scope.module->resolveReference(functionRef));
virtualReference.append('.');
int argCount;
ref_t actionRef, flags;
decodeMessage(message, actionRef, argCount, flags);
// // HOTFIX : include self as a parameter
// paramCount++;
size_t signIndex = virtualReference.Length();
virtualReference.append('0' + (char)argCount);
if (test(message, STATIC_MESSAGE)) {
virtualReference.append(scope.module->Name());
virtualReference.append("$");
}
if (test(flags, VARIADIC_MESSAGE))
virtualReference.append("params#");
ref_t signature = 0;
virtualReference.append(moduleScope->module->resolveAction(actionRef, signature));
if (signature) {
ref_t signatures[ARG_COUNT];
size_t len = moduleScope->module->resolveSignature(signature, signatures);
for (size_t i = 0; i < len; i++) {
ident_t paramName = moduleScope->module->resolveReference(signatures[i]);
NamespaceName ns(paramName);
if (isTemplateWeakReference(paramName)) {
virtualReference.append('$');
virtualReference.append(paramName + getlength(ns));
}
else if (isWeakReference(paramName)) {
virtualReference.append('$');
virtualReference.append(scope.module->Name());
virtualReference.append(paramName);
}
else {
virtualReference.append('$');
virtualReference.append(paramName);
}
}
}
virtualReference.replaceAll('\'', '@', signIndex);
ref_t reference = 0;
_Module* api = moduleScope->project->resolveModule(virtualReference, reference);
_Memory* section = api != NULL ? api->mapSection(reference | mskCodeRef, true) : NULL;
if (section != NULL) {
node.set(lxImporting, _writer.registerImportInfo(section, api, moduleScope->module));
}
else scope.raiseError(errInvalidLink, findIdentifier(node.findChild(lxInternalRef)));
}
Compiler::InheritResult Compiler :: inheritClass(ClassScope& scope, ref_t parentRef, bool ignoreFields, bool ignoreSealed)
{
_ModuleScope* moduleScope = scope.moduleScope;
size_t flagCopy = scope.info.header.flags;
size_t classClassCopy = scope.info.header.classRef;
// get module reference
ref_t moduleRef = 0;
_Module* module = moduleScope->loadReferenceModule(parentRef, moduleRef);
if (module == NULL || moduleRef == 0)
return InheritResult::irUnsuccessfull;
// load parent meta data
_Memory* metaData = module->mapSection(moduleRef | mskMetaRDataRef, true);
if (metaData != NULL) {
MemoryReader reader(metaData);
// import references if we inheriting class from another module
if (moduleScope->module != module) {
ClassInfo copy;
copy.load(&reader);
moduleScope->importClassInfo(copy, scope.info, module, false, true, ignoreFields);
}
else {
scope.info.load(&reader, false, ignoreFields);
// mark all methods as inherited
// private methods are not inherited
ClassInfo::MethodMap::Iterator it = scope.info.methods.start();
while (!it.Eof()) {
ref_t message = it.key();
(*it) = false;
it++;
if (test(message, STATIC_MESSAGE) && message != scope.moduleScope->init_message) {
scope.info.methods.exclude(message);
scope.info.methodHints.exclude(Attribute(message, maHint));
scope.info.methodHints.exclude(Attribute(message, maReference));
}
}
}
// meta attributes are not directly inherited
scope.info.mattributes.clear();
if (!ignoreSealed && test(scope.info.header.flags, elFinal)) {
// COMPILER MAGIC : if it is a unsealed nested class inheriting its owner
if (!test(scope.info.header.flags, elSealed) && test(flagCopy, elNestedClass)) {
ClassScope* owner = (ClassScope*)scope.getScope(Scope::ScopeLevel::slOwnerClass);
if (owner->classClassMode && scope.info.header.classRef == owner->reference) {
// HOTFIX : if it is owner class class - allow it as well
}
else if (owner->reference != parentRef) {
return InheritResult::irSealed;
}
}
else return InheritResult::irSealed;
}
// restore parent and flags
scope.info.header.parentRef = parentRef;
scope.info.header.classRef = classClassCopy;
if (test(scope.info.header.flags, elAbstract)) {
// exclude abstract flag
scope.info.header.flags &= ~elAbstract;
scope.abstractBaseMode = true;
}
scope.info.header.flags |= flagCopy;
return InheritResult::irSuccessfull;
}
else return InheritResult::irUnsuccessfull;
}
void Compiler :: compileParentDeclaration(SNode baseNode, ClassScope& scope, ref_t parentRef, bool ignoreFields)
{
scope.info.header.parentRef = parentRef;
InheritResult res = InheritResult::irSuccessfull;
if (scope.info.header.parentRef != 0) {
res = inheritClass(scope, scope.info.header.parentRef, ignoreFields, test(scope.info.header.flags, elVirtualVMT));
}
//if (res == irObsolete) {
// scope.raiseWarning(wrnObsoleteClass, node.Terminal());
//}
//if (res == irInvalid) {
// scope.raiseError(errInvalidParent/*, baseNode*/);
//}
/*else */if (res == InheritResult::irSealed) {
scope.raiseError(errSealedParent, baseNode);
}
else if (res == InheritResult::irUnsuccessfull)
scope.raiseError(errUnknownBaseClass, baseNode);
}
ref_t Compiler :: resolveTypeIdentifier(Scope& scope, SNode terminal, bool declarationMode, bool extensionAllowed)
{
return resolveTypeIdentifier(scope, terminal.identifier(), terminal.type, declarationMode, extensionAllowed);
}
ref_t Compiler :: resolveTypeIdentifier(Scope& scope, ident_t terminal, LexicalType type,
bool declarationMode, bool extensionAllowed)
{
ObjectInfo identInfo;
NamespaceScope* ns = (NamespaceScope*)scope.getScope(Scope::ScopeLevel::slNamespace);
if (type == lxReference && isWeakReference(terminal)) {
identInfo = ns->mapWeakReference(terminal, false);
}
else if (type == lxGlobalReference) {
identInfo = ns->mapGlobal(terminal);
}
else identInfo = ns->mapTerminal(terminal, type == lxReference, EAttr::eaNone);
switch (identInfo.kind) {
case okClass:
case okSingleton:
return identInfo.param;
case okSymbol:
if (declarationMode)
return identInfo.param;
case okExtension:
if (extensionAllowed)
return identInfo.param;;
default:
return 0;
}
}
bool isExtensionDeclaration(SNode node)
{
SNode current = node.firstChild();
while (current != lxNone) {
if (current == lxAttribute) {
if (current.argument == V_EXTENSION) {
return true;
}
}
else if (current == lxClassFlag) {
if (current.argument == elExtension) {
return true;
}
}
else if (current != lxNameAttr)
break;
current = current.nextNode();
}
return false;
}
void Compiler :: compileParentDeclaration(SNode node, ClassScope& scope, bool extensionMode)
{
ref_t parentRef = 0;
if (node == lxParent) {
parentRef = resolveParentRef(node, scope, false);
}
// else if (node != lxNone) {
// while (node == lxAttribute)
// // HOTFIX : skip attributes
// node = node.nextNode();
//
// if (node == lxTemplate || test(node.type, lxTerminalMask))
// parentRef = resolveParentRef(node, scope, false);
// }
if (scope.info.header.parentRef == scope.reference) {
if (parentRef != 0) {
scope.raiseError(errInvalidSyntax, node);
}
}
else if (parentRef == 0) {
parentRef = scope.info.header.parentRef;
}
if (extensionMode) {
// COMPLIER MAGIC : treat the parent declaration in the special way for the extension
scope.extensionClassRef = parentRef;
compileParentDeclaration(node, scope, scope.moduleScope->superReference);
}
else compileParentDeclaration(node, scope, parentRef);
}
void Compiler :: declareClassAttributes(SNode node, ClassScope& scope, bool visibilityOnly)
{
int flags = scope.info.header.flags;
SNode current = node.firstChild();
while (current != lxNone) {
if (current == lxAttribute) {
int value = current.argument;
if (!_logic->validateClassAttribute(value, scope.visibility)) {
current.setArgument(0); // HOTFIX : to prevent duplicate warnings
scope.raiseWarning(WARNING_LEVEL_1, wrnInvalidHint, current);
}
else if (!visibilityOnly) {
current.set(lxClassFlag, value);
if (value != 0 && test(flags, value)) {
scope.raiseWarning(WARNING_LEVEL_1, wrnDuplicateAttribute, current);
}
else if (test(value, elAbstract))
scope.abstractMode = true;
flags |= value;
}
}
else if (current == lxType) {
scope.raiseError(errInvalidSyntax, current);
}
current = current.nextNode();
}
}
void Compiler :: validateType(Scope& scope, SNode current, ref_t typeRef, bool ignoreUndeclared, bool allowType)
{
if (!typeRef)
scope.raiseError(errUnknownClass, current);
if (!_logic->isValidType(*scope.moduleScope, typeRef, ignoreUndeclared, allowType))
scope.raiseError(errInvalidType, current);
}
//ref_t Compiler :: resolveTypeAttribute(Scope& scope, SNode node, bool declarationMode)
//{
// ref_t typeRef = 0;
//
// SNode current = node.firstChild();
// if (current == lxArrayType) {
// typeRef = resolvePrimitiveArray(scope, resolveTypeAttribute(scope, current, declarationMode), declarationMode);
// }
// else if (current == lxTarget) {
// if (current.argument == V_TEMPLATE) {
// typeRef = resolveTemplateDeclaration(current, scope, declarationMode);
// }
// else typeRef = current.argument != 0 ? current.argument : resolveImplicitIdentifier(scope, current.firstChild(lxTerminalMask));
// }
//
// validateType(scope, node, typeRef, declarationMode);
//
// return typeRef;
//}
void Compiler :: declareSymbolAttributes(SNode node, SymbolScope& scope, bool declarationMode, bool ignoreType)
{
bool constant = false;
ref_t outputRef = 0;
SNode current = node.firstChild();
while (current != lxNone) {
if (current == lxAttribute) {
int value = current.argument;
if (!_logic->validateSymbolAttribute(value, constant, scope.staticOne, scope.preloaded,
scope.visibility))
{
current.setArgument(0); // HOTFIX : to prevent duplicate warnings
scope.raiseWarning(WARNING_LEVEL_1, wrnInvalidHint, current);
}
}
else if (current.compare(lxType, lxArrayType) && !ignoreType) {
// HOTFIX : do not resolve the output type for identifier declaration mode
outputRef = resolveTypeAttribute(current, scope, declarationMode, false);
}
current = current.nextNode();
}
scope.info.exprRef = outputRef;
if (constant)
scope.info.type = SymbolExpressionInfo::Type::Constant;
}
int Compiler :: resolveSize(SNode node, Scope& scope)
{
if (node == lxInteger) {
return node.identifier().toInt();
}
else if (node == lxHexInteger) {
return node.identifier().toInt(16);
}
else {
scope.raiseError(errInvalidSyntax, node);
return 0;
}
}
void Compiler :: declareFieldAttributes(SNode node, ClassScope& scope, FieldAttributes& attrs)
{
bool inlineArray = false;
SNode current = node.firstChild();
while (current != lxNone) {
if (current == lxAttribute) {
int value = current.argument;
if (_logic->validateFieldAttribute(value, attrs)) {
if (value == lxStaticAttr) {
attrs.isStaticField = true;
}
else if (value == -1) {
// ignore if constant / sealed attribute was set
}
else if (!value && isPrimitiveRef(current.argument)) {
if (current.argument == V_STRING) {
// if it is an inline array attribute
inlineArray = true;
}
// if it is a primitive type
else attrs.fieldRef = current.argument;
}
else scope.raiseError(errInvalidHint, node);
}
else scope.raiseError(errInvalidHint, current);
}
else if (current.compare(lxType, lxArrayType)) {
if (attrs.fieldRef == 0) {
if (inlineArray) {
// if it is an inline array - it should be compiled differently
if (current == lxArrayType) {
attrs.fieldRef = resolveTypeAttribute(current.firstChild(), scope, false, false);
attrs.size = -1;
}
else scope.raiseError(errInvalidHint, current);
}
// NOTE : the field type should be already declared only for the structure
else {
attrs.fieldRef = resolveTypeAttribute(current, scope,
!test(scope.info.header.flags, elStructureRole), false);
attrs.isArray = current == lxArrayType;
}
}
else scope.raiseError(errInvalidHint, node);
}
else if (current == lxSize) {
if (attrs.size == 0) {
if (current.argument) {
attrs.size = current.argument;
}
else attrs.size = resolveSize(current.firstChild(lxTerminalMask), scope);
}
else scope.raiseError(errInvalidHint, node);
}
// else if (current == lxMessage) {
// // COMPILER MAGIC : if the field should be mapped to the message
// attrs.messageRef = current.argument;
// attrs.messageAttr = current.findChild(lxAttribute).argument;
// }
current = current.nextNode();
}
//HOTFIX : recognize raw data
if (attrs.fieldRef == V_INTBINARY) {
switch (attrs.size) {
case 1:
case 2:
case 4:
// treat it like dword
attrs.fieldRef = V_INT32;
break;
case 8:
// treat it like qword
attrs.fieldRef = V_INT64;
break;
default:
scope.raiseError(errInvalidHint, node);
break;
}
}
else if (attrs.fieldRef == V_BINARY) {
switch (attrs.size) {
case 4:
// treat it like dword
attrs.fieldRef = V_DWORD;
break;
default:
scope.raiseError(errInvalidHint, node);
break;
}
}
else if (attrs.fieldRef == V_PTRBINARY) {
switch (attrs.size) {
case 4:
// treat it like dword
attrs.fieldRef = V_PTR32;
break;
default:
scope.raiseError(errInvalidHint, node);
break;
}
}
else if (attrs.fieldRef == V_MESSAGE || attrs.fieldRef == V_SUBJECT) {
if (attrs.size == 8 && attrs.fieldRef == V_MESSAGE) {
attrs.fieldRef = V_EXTMESSAGE;
}
else if (attrs.size != 4) {
scope.raiseError(errInvalidHint, node);
}
}
else if (attrs.fieldRef == V_FLOAT) {
switch (attrs.size) {
case 8:
// treat it like dword
attrs.fieldRef = V_REAL64;
break;
default:
scope.raiseError(errInvalidHint, node);
break;
}
}
}
void Compiler :: compileSwitch(SNode node, ExprScope& scope)
{
SNode targetNode = node.firstChild();
bool immMode = true;
int localOffs = 0;
ObjectInfo loperand;
if (targetNode == lxExpression) {
immMode = false;
localOffs = scope.newTempLocal();
loperand = compileExpression(targetNode, scope, 0, EAttr::eaNone);
targetNode.injectAndReplaceNode(lxAssigning);
targetNode.insertNode(lxLocal, localOffs);
}
// HOTFIX : the argument should not be type-less
// to use the branching over sending IF message
if (!loperand.reference)
loperand.reference = scope.moduleScope->superReference;
SNode current = node.findChild(lxOption, lxElse);
while (current == lxOption) {
SNode optionNode = current.injectNode(lxExpression);
SNode blockNode = optionNode.firstChild(lxObjectMask);
// find option value
SNode exprNode = optionNode.firstChild();
exprNode.injectAndReplaceNode(lxExpression);
int operator_id = current.argument;
if (!immMode) {
exprNode.insertNode(lxLocal, localOffs);
}
else {
SNode localNode = SyntaxTree::insertNodeCopy(targetNode, exprNode);
if (localNode != lxExpression) {
localNode.injectAndReplaceNode(lxExpression);
}
loperand = compileExpression(localNode, scope, 0, EAttr::eaNone);
}
ObjectInfo roperand = mapTerminal(exprNode.lastChild(), scope, EAttr::eaNone);
ObjectInfo operationInfo = compileOperator(exprNode, scope, operator_id, 2, loperand, roperand, ObjectInfo(), EAttr::eaNone);
ObjectInfo retVal;
compileBranchingOp(blockNode, scope, HINT_SWITCH, IF_OPERATOR_ID, operationInfo, retVal);
current = current.nextNode();
}
if (current == lxElse) {
bool withRetStatement = false;
compileSubCode(current, scope, false, withRetStatement);
//scope.setCodeRetStatementFlag(ifRetStatement && elseRetStatement);
//CodeScope subScope(&scope);
//SNode thenCode = current.findSubNode(lxCode);
//SNode statement = thenCode.firstChild(lxObjectMask);
//if (statement.nextNode() != lxNone || statement == lxEOF) {
// compileCode(writer, thenCode, subScope);
//}
//// if it is inline action
//else compileRetExpression(writer, statement, scope, EAttr::eaNone);
//// preserve the allocated space
//scope.level = subScope.level;
}
}
size_t Compiler :: resolveArraySize(SNode node, Scope& scope)
{
if (isSingleStatement(node)) {
SNode terminal = node.findSubNodeMask(lxTerminalMask);
if (terminal.type == lxInteger) {
return terminal.identifier().toInt();
}
else scope.raiseError(errInvalidSyntax, node);
}
else scope.raiseError(errInvalidSyntax, node);
return 0; // !! dummy returning statement, the code never reaches this point
}
LexicalType Compiler :: declareVariableType(CodeScope& scope, ObjectInfo& variable, ClassInfo& localInfo, int size, bool binaryArray,
int& variableArg, ident_t& className)
{
LexicalType variableType = lxVariable;
if (size > 0) {
switch (localInfo.header.flags & elDebugMask) {
case elDebugDWORD:
variableType = lxIntVariable;
break;
case elDebugQWORD:
variableType = lxLongVariable;
break;
case elDebugReal64:
variableType = lxReal64Variable;
break;
case elDebugIntegers:
variableType = lxIntsVariable;
variableArg = size;
break;
case elDebugShorts:
variableType = lxShortsVariable;
variableArg = size;
break;
case elDebugBytes:
variableType = lxBytesVariable;
variableArg = size;
break;
default:
if (isPrimitiveRef(variable.extraparam)) {
variableType = lxBytesVariable;
variableArg = size;
}
else {
variableType = lxBinaryVariable;
// HOTFIX : size should be provide only for dynamic variables
if (binaryArray)
variableArg = size;
if (variable.reference != 0 && !isPrimitiveRef(variable.reference)) {
className = scope.moduleScope->module->resolveReference(variable.reference);
}
}
break;
}
}
else {
}
return variableType;
}
void Compiler :: declareVariable(SNode& terminal, ExprScope& scope, ref_t typeRef/*, bool dynamicArray*/, bool canBeIdle)
{
CodeScope* codeScope = (CodeScope*)scope.getScope(Scope::ScopeLevel::slCode);
IdentifierString identifier(terminal.identifier());
ident_t className = NULL;
LexicalType variableType = lxVariable;
int variableArg = 0;
int size = /*dynamicArray ? -1 : */0;
// COMPILER MAGIC : if it is a fixed-sized array
SNode opNode = terminal.nextNode();
if (opNode == lxArrOperator/* && opNode.argument == REFER_OPERATOR_ID*/) {
if (size && opNode.nextNode() != lxNone)
scope.raiseError(errInvalidSyntax, terminal);
SNode sizeExprNode = opNode.nextNode();
size = resolveArraySize(sizeExprNode, scope);
// HOTFIX : remove the size attribute
opNode = lxIdle;
sizeExprNode = lxIdle;
opNode = sizeExprNode.nextNode();
}
ObjectInfo variable;
variable.reference = typeRef;
if (size != 0 && variable.reference != 0) {
if (!isPrimitiveRef(variable.reference)) {
// if it is a primitive array
variable.element = variable.reference;
variable.reference = _logic->definePrimitiveArray(*scope.moduleScope, variable.element, true);
}
else scope.raiseError(errInvalidHint, terminal);
}
ClassInfo localInfo;
bool binaryArray = false;
if (!_logic->defineClassInfo(*scope.moduleScope, localInfo, variable.reference))
scope.raiseError(errUnknownVariableType, terminal);
if (variable.reference == V_BINARYARRAY && variable.element != 0) {
localInfo.size *= _logic->defineStructSize(*scope.moduleScope, variable.element, 0);
}
if (_logic->isEmbeddableArray(localInfo) && size != 0) {
binaryArray = true;
size = size * (-((int)localInfo.size));
}
else if (variable.reference == V_OBJARRAY && size == -1) {
// if it is a primitive dynamic array
}
else if (_logic->isEmbeddable(localInfo) && size == 0) {
bool dummy = false;
size = _logic->defineStructSize(localInfo, dummy);
}
else if (size != 0)
scope.raiseError(errInvalidOperation, terminal);
variable.kind = okLocal;
if (size > 0) {
if (scope.tempAllocated2 > codeScope->allocated2) {
codeScope->allocated2 = scope.tempAllocated2;
if (codeScope->allocated2 > codeScope->reserved2)
codeScope->reserved2 = codeScope->allocated2;
}
if (!allocateStructure(*codeScope, size, binaryArray, variable))
scope.raiseError(errInvalidOperation, terminal);
// make the reservation permanent
if (codeScope->reserved2 < codeScope->allocated2)
codeScope->reserved2 = codeScope->allocated2;
// take into account allocated space if requiered
if (scope.tempAllocated2 < codeScope->allocated2)
scope.tempAllocated2 = codeScope->allocated2;
}
else {
if (size < 0) {
size = 0;
}
if (scope.tempAllocated1 > codeScope->allocated1) {
codeScope->allocated1 = scope.tempAllocated1;
if (codeScope->allocated1 > codeScope->reserved1)
codeScope->reserved1 = codeScope->allocated1;
}
variable.param = codeScope->newLocal();
// take into account allocated space if requiered
if (scope.tempAllocated1 < codeScope->allocated1)
scope.tempAllocated1 = codeScope->allocated1;
}
variableType = declareVariableType(*codeScope, variable, localInfo, size, binaryArray, variableArg, className);
if (!codeScope->locals.exist(identifier)) {
codeScope->mapLocal(identifier, variable.param, variable.reference, variable.element, size);
// injecting variable label
SNode rootNode = findRootNode(terminal, lxNewFrame, lxCode, lxCodeExpression);
SNode varNode = rootNode.prependSibling(variableType, variableArg);
varNode.appendNode(lxLevel, variable.param);
varNode.appendNode(lxIdentifier, identifier);
if (!emptystr(className)) {
if (isWeakReference(className)) {
if (isTemplateWeakReference(className)) {
// HOTFIX : save weak template-based class name directly
varNode.appendNode(lxClassName, className);
}
else {
IdentifierString fullName(scope.module->Name(), className);
varNode.appendNode(lxClassName, fullName);
}
}
else varNode.appendNode(lxClassName, className);
}
}
else scope.raiseError(errDuplicatedLocal, terminal);
if (opNode == lxNone && canBeIdle) {
// HOTFIX : remove the variable if the statement contains only a declaration
terminal = lxIdle;
}
}
//inline void insertNodeChild(SNode target, SNode terminal, LexicalType type)
//{
// SNode current = terminal.findChild(type);
// if (current != lxNone)
// target.insertNode(current.type, current.argument);
//}
//
//inline void insertTerminalInfo(SNode target, SNode terminal)
//{
// if (terminal != lxNone) {
// SNode current = target.insertNode(terminal.type);
// insertNodeChild(current, terminal, lxRow);
// insertNodeChild(current, terminal, lxCol);
// insertNodeChild(current, terminal, lxLength);
// }
//}
//inline void writeTarget(SyntaxWriter& writer, ref_t targetRef, ref_t elementRef)
//{
// if (targetRef)
// writer.appendNode(lxTarget, targetRef);
//
// if (isPrimitiveRef(targetRef) && elementRef)
// writer.appendNode(lxElement, elementRef);
//}
int Compiler :: defineFieldSize(Scope& scope, int offset)
{
ClassScope* classScope = (ClassScope*)scope.getScope(Scope::ScopeLevel::slClass);
ClassInfo::FieldMap::Iterator it = retrieveIt(classScope->info.fields.start(), offset);
it++;
if (!it.Eof()) {
return *it - offset;
}
else return classScope->info.size - offset;
}
void Compiler :: setParamFieldTerminal(SNode& node, ExprScope&, ObjectInfo object, EAttr, LexicalType type)
{
node.set(lxFieldExpression, 0);
node.appendNode(type, object.param);
node.appendNode(lxField, 0);
}
void Compiler :: appendBoxingInfo(SNode node, _CompileScope& scope, ObjectInfo object, bool noUnboxing,
int fixedSize, ref_t targetRef)
{
// if the parameter may be stack-allocated
bool variable = false;
int size = _logic->defineStructSizeVariable(*scope.moduleScope, targetRef, object.element, variable);
if (fixedSize)
// use fixed size (for fixed-sized array fields)
// note that we still need to execute defineStructSizeVariable to set variable bool value
size = fixedSize;
node.appendNode(lxType, targetRef);
if (isPrimitiveRef(targetRef))
node.appendNode(lxElementType, object.element);
node.appendNode(lxSize, size);
if (variable && !noUnboxing)
node.setArgument(INVALID_REF);
}
void Compiler :: setSuperTerminal(SNode& node, ExprScope& scope, ObjectInfo object, EAttr mode, LexicalType type)
{
node.set(type, object.param);
if (object.extraparam == -1 && !EAttrs::test(mode, HINT_NOBOXING)) {
node.injectAndReplaceNode(lxCondBoxableExpression);
appendBoxingInfo(node, scope, object, EAttrs::test(mode, HINT_NOUNBOXING), 0,
scope.getClassRefId());
}
}
void Compiler :: setParamTerminal(SNode& node, ExprScope& scope, ObjectInfo object, EAttr mode, LexicalType type)
{
node.set(type, object.param);
if (object.extraparam == -1 && !EAttrs::test(mode, HINT_NOBOXING)) {
node.injectAndReplaceNode(lxCondBoxableExpression);
appendBoxingInfo(node, scope, object, EAttrs::test(mode, HINT_NOUNBOXING), 0,
resolveObjectReference(scope, object, false));
}
}
void Compiler :: setParamsTerminal(SNode& node, _CompileScope&, ObjectInfo object, EAttr, ref_t wrapRef)
{
node.set(lxBlockLocalAddr, object.param);
node.injectAndReplaceNode(lxArgBoxableExpression);
node.appendNode(lxType, wrapRef);
// writer.newNode(lxArgBoxing, 0);
// writer.appendNode(lxBlockLocalAddr, object.param);
// writer.appendNode(lxTarget, r);
// if (EAttrs::test(mode, HINT_DYNAMIC_OBJECT))
// writer.appendNode(lxBoxingRequired);
}
void Compiler :: setVariableTerminal(SNode& node, _CompileScope& scope, ObjectInfo object, EAttr mode, LexicalType type, int fixedSize)
{
node.set(type, object.param);
if (!EAttrs::test(mode, HINT_NOBOXING)) {
node.injectAndReplaceNode(lxBoxableExpression);
appendBoxingInfo(node, scope, object, EAttrs::test(mode, HINT_NOUNBOXING), fixedSize,
resolveObjectReference(scope, object, false));
}
}
ObjectInfo Compiler :: mapClassSymbol(Scope& scope, int classRef)
{
if (classRef) {
ObjectInfo retVal(okClass);
retVal.param = classRef;
ClassInfo info;
scope.moduleScope->loadClassInfo(info, classRef, true);
retVal.reference = info.header.classRef;
ClassScope* classScope = (ClassScope*)scope.getScope(Scope::ScopeLevel::slClass);
if (classScope != nullptr && classScope->reference == retVal.reference)
retVal.kind = okClassSelf;
return retVal;
}
else return ObjectInfo(okUnknown);
}
ObjectInfo Compiler :: compileTypeSymbol(SNode node, ExprScope& scope, EAttr mode)
{
ObjectInfo retVal = mapClassSymbol(scope, resolveTemplateDeclaration(node, scope, false));
recognizeTerminal(node, retVal, scope, mode);
return retVal;
}
ObjectInfo Compiler :: compileYieldExpression(SNode objectNode, ExprScope& scope, EAttr mode)
{
CodeScope* codeScope = (CodeScope*)scope.getScope(Scope::ScopeLevel::slCode);
MethodScope* methodScope = (MethodScope*)codeScope->getScope(Scope::ScopeLevel::slMethod);
int index = methodScope->getAttribute(maYieldContext);
int index2 = methodScope->getAttribute(maYieldLocals);
EAttrs objectMode(mode);
objectMode.include(HINT_NOPRIMITIVES);
objectNode.injectAndReplaceNode(lxSeqExpression);
SNode retExprNode = objectNode.firstChild(lxObjectMask);
YieldScope* yieldScope = (YieldScope*)scope.getScope(Scope::ScopeLevel::slYieldScope);
// save context
if (codeScope->reserved2 > 0) {
SNode exprNode = objectNode.insertNode(lxExpression);
SNode copyNode = exprNode.appendNode(lxCopying, codeScope->reserved2 << 2);
SNode fieldNode = copyNode.appendNode(lxFieldExpression);
fieldNode.appendNode(lxSelfLocal, 1);
fieldNode.appendNode(lxField, index);
fieldNode.appendNode(lxFieldAddress, 4);
copyNode.appendNode(lxLocalAddress, -2);
yieldScope->yieldContext.add(copyNode);
}
// save locals
int localsSize = codeScope->allocated1 - methodScope->preallocated;
if (localsSize) {
SNode expr2Node = objectNode.insertNode(lxExpression);
SNode copy2Node = expr2Node.appendNode(lxCopying, localsSize << 2);
SNode field2Node = copy2Node.appendNode(lxFieldExpression);
field2Node.appendNode(lxSelfLocal, 1);
field2Node.appendNode(lxField, index2);
SNode localNode = copy2Node.appendNode(lxLocalAddress, methodScope->preallocated/* + localsSize*//* - 1*/);
yieldScope->yieldLocals.add(localNode);
// HOTFIX : reset yield locals field on yield return to mark mg->yg reference
SNode expr3Node = objectNode.insertNode(lxAssigning);
SNode src3 = expr3Node.appendNode(lxFieldExpression);
src3.appendNode(lxSelfLocal, 1);
src3.appendNode(lxField, index2);
SNode dst3 = expr3Node.appendNode(lxFieldExpression);
dst3.appendNode(lxSelfLocal, 1);
dst3.appendNode(lxField, index2);
}
ObjectInfo retVal;
if (codeScope->withEmbeddableRet()) {
retVal = scope.mapTerminal(SELF_VAR, false, EAttr::eaNone);
// HOTFIX : the node should be compiled as returning expression
LexicalType ori = objectNode.type;
objectNode = lxReturning;
compileEmbeddableRetExpression(retExprNode, scope);
objectNode = ori;
recognizeTerminal(objectNode, retVal, scope, HINT_NODEBUGINFO | HINT_NOBOXING);
retExprNode.set(lxYieldReturning, index);
}
else {
//writer.appendNode(lxBreakpoint, dsStep);
retVal = compileExpression(retExprNode, scope, 0, objectMode);
analizeOperands(retExprNode, scope, 0, true);
retExprNode.injectAndReplaceNode(lxYieldReturning, index);
}
return retVal;
}
ObjectInfo Compiler :: compileMessageReference(SNode terminal, ExprScope& scope)
{
ObjectInfo retVal;
IdentifierString message;
int argCount = 0;
SNode paramNode = terminal.nextNode();
bool invalid = true;
if (paramNode == lxArrOperator && paramNode.argument == REFER_OPERATOR_ID) {
if (isSingleStatement(paramNode.nextNode())) {
ObjectInfo sizeInfo = mapTerminal(paramNode.nextNode().firstChild(lxTerminalMask), scope, HINT_VIRTUALEXPR);
if (sizeInfo.kind == okIntConstant) {
argCount = sizeInfo.extraparam;
invalid = false;
}
}
}
if (invalid)
scope.raiseError(errNotApplicable, terminal);
// HOTFIX : prevent further compilation of the expression
paramNode = lxIdle;
if (terminal == lxIdentifier) {
message.append('0' + (char)argCount);
message.append(terminal.identifier());
retVal.kind = okMessageConstant;
retVal.reference = V_MESSAGE;
}
else if (terminal == lxType) {
SNode typeNode = terminal.findChild(lxType);
if (typeNode.nextNode() != lxNone)
scope.raiseError(errNotApplicable, terminal);
ref_t extensionRef = resolveTypeAttribute(typeNode, scope, false, true);
message.append(scope.moduleScope->module->resolveReference(extensionRef));
message.append('.');
message.append('0' + (char)argCount);
message.append(terminal.firstChild(lxTerminalMask).identifier());
retVal.kind = okExtMessageConstant;
retVal.param = scope.moduleScope->module->mapReference(message);
retVal.reference = V_EXTMESSAGE;
}
retVal.param = scope.moduleScope->module->mapReference(message);
return retVal;
}
ObjectInfo Compiler :: compileSubjectReference(SNode terminal, ExprScope& scope, EAttr)
{
ObjectInfo retVal;
IdentifierString messageName;
if (terminal == lxIdentifier) {
ident_t name = terminal.identifier();
messageName.copy(name);
}
else if (terminal == lxSubjectRef) {
ref_t dummy = 0;
ident_t name = scope.module->resolveAction(terminal.argument, dummy);
messageName.copy(name);
}
retVal.kind = okMessageNameConstant;
retVal.param = scope.moduleScope->module->mapReference(messageName);
retVal.reference = V_SUBJECT;
//writeTerminal(writer, terminal, scope, retVal, mode);
return retVal;
}
ref_t Compiler :: mapMessage(SNode node, ExprScope& scope, bool variadicOne, bool extensionCall)
{
ref_t actionFlags = variadicOne ? VARIADIC_MESSAGE : 0;
if (extensionCall)
actionFlags |= FUNCTION_MESSAGE;
// IdentifierString signature;
IdentifierString messageStr;
SNode current = node;
//if (node.argument != 0)
// // if the message is already declared
// return node.argument;
SNode name = current.firstChild(lxTerminalMask);
//HOTFIX : if generated by a script / closure call
if (name == lxNone)
name = current;
if (name == lxNone)
scope.raiseError(errInvalidOperation, node);
messageStr.copy(name.identifier());
current = current.nextNode();
int argCount = 1;
// if message has generic argument list
while (true) {
if (current == lxPropertyParam) {
// COMPILER MAGIC : recognize the property get call
actionFlags = PROPERTY_MESSAGE;
}
else if (test(current.type, lxObjectMask)) {
argCount++;
}
// else if (current == lxMessage) {
// messageStr.append(':');
// messageStr.append(current.firstChild(lxTerminalMask).identifier());
// }
else break;
current = current.nextNode();
}
if (argCount >= ARG_COUNT) {
actionFlags |= VARIADIC_MESSAGE;
argCount = 2;
}
if (messageStr.Length() == 0) {
actionFlags |= FUNCTION_MESSAGE;
// if it is an implicit message
messageStr.copy(INVOKE_MESSAGE);
}
if (test(actionFlags, FUNCTION_MESSAGE))
// exclude the target from the arg counter for the function
argCount--;
// if signature is presented
ref_t actionRef = scope.moduleScope->module->mapAction(messageStr, 0, false);
// create a message id
return encodeMessage(actionRef, argCount, actionFlags);
}
ref_t Compiler :: mapExtension(Scope& scope, ref_t& messageRef, ref_t implicitSignatureRef, ObjectInfo object, int& stackSafeAttr)
{
ref_t objectRef = resolveObjectReference(scope, object, true);
if (objectRef == 0) {
objectRef = scope.moduleScope->superReference;
}
NamespaceScope* nsScope = (NamespaceScope*)scope.getScope(Scope::ScopeLevel::slNamespace);
if (implicitSignatureRef) {
// auto generate extension template for strong-typed signature
for (auto it = nsScope->extensionTemplates.getIt(messageRef); !it.Eof(); it = nsScope->extensionTemplates.nextIt(messageRef, it)) {
ref_t resolvedTemplateExtension = _logic->resolveExtensionTemplate(*scope.moduleScope, *this, *it,
implicitSignatureRef, nsScope->ns, nsScope->outerExtensionList ? nsScope->outerExtensionList : &nsScope->extensions);
if (resolvedTemplateExtension) {
//ref_t strongMessage = encodeMessage()
//nsScope->extensions.add(messageRef, Pair<ref_t, ref_t>(resolvedTemplateExtension, strongMessage));
}
}
}
// check extensions
auto it = nsScope->extensions.getIt(messageRef);
bool found = !it.Eof();
if (found) {
// generate an extension signature
ref_t signatures[ARG_COUNT];
ref_t signatureLen = scope.module->resolveSignature(implicitSignatureRef, signatures);
for (size_t i = signatureLen; i > 0; i--)
signatures[i] = signatures[i - 1];
signatures[0] = objectRef;
signatureLen++;
int argCount = getArgCount(messageRef);
while (signatureLen < (ref_t)argCount) {
signatures[signatureLen] = scope.moduleScope->superReference;
signatureLen++;
}
/*ref_t full_sign = */scope.module->mapSignature(signatures, signatureLen, false);
ref_t resolvedMessage = 0;
ref_t resolvedExtRef = 0;
int resolvedStackSafeAttr = 0;
int counter = 0;
while (!it.Eof()) {
auto extInfo = *it;
ref_t targetRef = nsScope->resolveExtensionTarget(extInfo.value1);
int extStackAttr = 0;
if (_logic->isMessageCompatibleWithSignature(*scope.moduleScope, targetRef, extInfo.value2,
signatures, signatureLen, extStackAttr))
{
if (!resolvedMessage) {
resolvedMessage = extInfo.value2;
resolvedExtRef = extInfo.value1;
resolvedStackSafeAttr = extStackAttr;
}
else if (!_logic->isSignatureCompatible(*scope.moduleScope, extInfo.value2, resolvedMessage)) {
resolvedMessage = 0;
break;
}
}
counter++;
it = nsScope->extensions.nextIt(messageRef, it);
}
if (resolvedMessage) {
if (counter > 1 && implicitSignatureRef == 0) {
// HOTFIX : does not resolve an ambigous extension for a weak message
}
else {
// if we are lucky - use the resolved one
messageRef = resolvedMessage;
stackSafeAttr = resolvedStackSafeAttr;
return resolvedExtRef;
}
}
// bad luck - we have to generate run-time extension dispatcher
ref_t extRef = nsScope->extensionDispatchers.get(messageRef);
if (extRef == INVALID_REF) {
extRef = compileExtensionDispatcher(*nsScope, messageRef);
nsScope->extensionDispatchers.add(messageRef, extRef);
}
messageRef |= FUNCTION_MESSAGE;
return extRef;
}
return 0;
}
void Compiler :: compileBranchingNodes(SNode node, ExprScope& scope, ref_t ifReference, bool loopMode, bool switchMode)
{
if (loopMode) {
SNode thenCode = node.findSubNode(lxCode);
if (thenCode == lxNone) {
//HOTFIX : inline branching operator
node.injectAndReplaceNode(lxElse, ifReference);
thenCode = node.firstChild();
}
else node.set(lxElse, ifReference);
bool dummy = false;
compileSubCode(thenCode, scope, true, dummy);
}
else {
SNode thenCode = node.findSubNode(lxCode);
if (thenCode == lxNone) {
//HOTFIX : inline branching operator
node.injectAndReplaceNode(lxIf, ifReference);
thenCode = node.firstChild();
}
else node.set(lxIf, ifReference);
bool ifRetStatement = false;
compileSubCode(thenCode, scope, true, ifRetStatement);
// HOTFIX : switch mode - ignore else
if (!switchMode) {
node = node.nextNode(lxObjectMask);
if (node != lxNone) {
SNode elseCode = node.findSubNode(lxCode);
if (elseCode == lxNone) {
node.injectAndReplaceNode(lxElse, ifReference);
elseCode = node.firstChild();
}
else node.set(lxElse, 0);
if (elseCode == lxNone)
//HOTFIX : inline branching operator
elseCode = node;
bool elseRetStatement = false;
compileSubCode(elseCode, scope, true, elseRetStatement);
scope.setCodeRetStatementFlag(ifRetStatement && elseRetStatement);
}
}
}
}
ref_t Compiler :: resolveOperatorMessage(Scope& scope, ref_t operator_id, int argCount)
{
switch (operator_id) {
case IF_OPERATOR_ID:
return encodeMessage(scope.module->mapAction(IF_MESSAGE, 0, false), argCount, 0);
case IFNOT_OPERATOR_ID:
return encodeMessage(scope.module->mapAction(IFNOT_MESSAGE, 0, false), argCount, 0);
case EQUAL_OPERATOR_ID:
return encodeMessage(scope.module->mapAction(EQUAL_MESSAGE, 0, false), argCount, 0);
case NOTEQUAL_OPERATOR_ID:
return encodeMessage(scope.module->mapAction(NOTEQUAL_MESSAGE, 0, false), argCount, 0);
case LESS_OPERATOR_ID:
return encodeMessage(scope.module->mapAction(LESS_MESSAGE, 0, false), argCount, 0);
case NOTLESS_OPERATOR_ID:
return encodeMessage(scope.module->mapAction(NOTLESS_MESSAGE, 0, false), argCount, 0);
case GREATER_OPERATOR_ID:
return encodeMessage(scope.module->mapAction(GREATER_MESSAGE, 0, false), argCount, 0);
case NOTGREATER_OPERATOR_ID:
return encodeMessage(scope.module->mapAction(NOTGREATER_MESSAGE, 0, false), argCount, 0);
case ADD_OPERATOR_ID:
return encodeMessage(scope.module->mapAction(ADD_MESSAGE, 0, false), argCount, 0);
case SUB_OPERATOR_ID:
return encodeMessage(scope.module->mapAction(SUB_MESSAGE, 0, false), argCount, 0);
case MUL_OPERATOR_ID:
return encodeMessage(scope.module->mapAction(MUL_MESSAGE, 0, false), argCount, 0);
case DIV_OPERATOR_ID:
return encodeMessage(scope.module->mapAction(DIV_MESSAGE, 0, false), argCount, 0);
case AND_OPERATOR_ID:
return encodeMessage(scope.module->mapAction(AND_MESSAGE, 0, false), argCount, 0);
case OR_OPERATOR_ID:
return encodeMessage(scope.module->mapAction(OR_MESSAGE, 0, false), argCount, 0);
case XOR_OPERATOR_ID:
return encodeMessage(scope.module->mapAction(XOR_MESSAGE, 0, false), argCount, 0);
case SHIFTR_OPERATOR_ID:
return encodeMessage(scope.module->mapAction(SHIFTR_MESSAGE, 0, false), argCount, 0);
case SHIFTL_OPERATOR_ID:
return encodeMessage(scope.module->mapAction(SHIFTL_MESSAGE, 0, false), argCount, 0);
case REFER_OPERATOR_ID:
return encodeMessage(scope.module->mapAction(REFER_MESSAGE, 0, false), argCount, 0);
case SET_REFER_OPERATOR_ID:
return encodeMessage(scope.module->mapAction(SET_REFER_MESSAGE, 0, false), argCount, 0);
default:
throw InternalError("Not supported operator");
break;
}
}
inline EAttr defineBranchingOperandMode(SNode node)
{
EAttr mode = /*HINT_SUBCODE_CLOSURE | */HINT_NODEBUGINFO;
if (node.firstChild() != lxCode) {
mode = mode | HINT_INLINE_EXPR;
}
return mode;
}
void Compiler :: compileBranchingOp(SNode roperandNode, ExprScope& scope, EAttr mode, int operator_id,
ObjectInfo loperand, ObjectInfo& retVal)
{
bool loopMode = EAttrs::test(mode, HINT_LOOP);
bool switchMode = EAttrs::test(mode, HINT_SWITCH);
// HOTFIX : in loop expression, else node is used to be similar with branching code
// because of optimization rules
ref_t original_id = operator_id;
if (loopMode) {
operator_id = operator_id == IF_OPERATOR_ID ? IFNOT_OPERATOR_ID : IF_OPERATOR_ID;
}
ref_t ifReference = 0;
ref_t resolved_operator_id = operator_id;
// try to resolve the branching operator directly
if (_logic->resolveBranchOperation(*scope.moduleScope, resolved_operator_id,
resolveObjectReference(scope, loperand, false), ifReference))
{
// we are lucky : we can implement branching directly
compileBranchingNodes(roperandNode, scope, ifReference, loopMode, switchMode);
SNode branchNode = roperandNode.parentNode();
branchNode.set(loopMode ? lxLooping : lxBranching, switchMode ? -1 : 0);
if (loopMode) {
// check if the loop has root boxing operations
SNode exprNode = branchNode;
SNode rootExpr = exprNode.parentNode();
while (rootExpr != lxSeqExpression || rootExpr.argument != -1) {
exprNode = rootExpr;
rootExpr = rootExpr.parentNode();
}
if (exprNode.prevNode() != lxNone && rootExpr == lxSeqExpression) {
// bad luck : we have to relocate boxing expressions into the loop
SNode seqNode = branchNode.insertNode(lxSeqExpression);
exprNode = exprNode.prevNode();
while (exprNode != lxNone) {
// copy to the new location
SNode copyNode = seqNode.insertNode(exprNode.type, exprNode.argument);
SyntaxTree::copyNode(exprNode, copyNode);
// commenting out old one
exprNode = lxIdle;
exprNode = exprNode.prevNode();
}
}
}
}
else {
operator_id = original_id;
// bad luck : we have to create a closure
int message = resolveOperatorMessage(scope, operator_id, 2);
compileClosure(roperandNode, scope, defineBranchingOperandMode(roperandNode));
// HOTFIX : comment out the method code
roperandNode = lxIdle;
SNode elseNode = roperandNode.nextNode();
if (elseNode != lxNone) {
message = overwriteArgCount(message, 3);
compileClosure(elseNode, scope, defineBranchingOperandMode(elseNode));
// HOTFIX : comment out the method code
elseNode = lxIdle;
}
SNode parentNode = roperandNode.parentNode();
bool dummy = false;
retVal = compileMessage(parentNode, scope, loperand, message, EAttr::eaNone, 0, dummy);
if (loopMode) {
parentNode.injectAndReplaceNode(lxLooping);
}
}
}
ObjectInfo Compiler :: compileBranchingOperator(SNode roperandNode, ExprScope& scope, ObjectInfo loperand, EAttr mode, int operator_id)
{
ObjectInfo retVal(okObject);
compileBranchingOp(roperandNode, scope, mode, operator_id, loperand, retVal);
return retVal;
}
ObjectInfo Compiler :: compileIsNilOperator(SNode current, ExprScope& scope, ObjectInfo loperand)
{
SNode exprNode = current.parentNode();
if (loperand.kind == okObject) {
SNode firstNode = exprNode.firstChild(lxObjectMask);
firstNode.injectAndReplaceNode(lxAlt);
firstNode.appendNode(lxExpression).appendNode(lxNil);
}
ObjectInfo roperand = compileExpression(current, scope, 0, EAttr::eaNone);
exprNode.set(lxNilOp, ISNIL_OPERATOR_ID);
ref_t loperandRef = resolveObjectReference(scope, loperand, false);
ref_t roperandRef = resolveObjectReference(scope, roperand, false);
ref_t resultRef = _logic->isCompatible(*scope.moduleScope, loperandRef, roperandRef, false) ? loperandRef : 0;
return ObjectInfo(okObject, 0, resultRef);
}
inline bool IsArrExprOperator(int operator_id, LexicalType type)
{
switch (type) {
case lxIntArrOp:
case lxShortArrOp:
case lxByteArrOp:
return operator_id == REFER_OPERATOR_ID;
case lxBinArrOp:
return operator_id == REFER_OPERATOR_ID;
default:
return false;
}
}
ObjectInfo Compiler :: compileOperator(SNode& node, ExprScope& scope, int operator_id, int argCount, ObjectInfo loperand,
ObjectInfo roperand, ObjectInfo roperand2, EAttr mode)
{
ObjectInfo retVal;
if (loperand.kind == okIntConstant && roperand.kind == okIntConstant) {
int result = 0;
if (calculateIntOp(operator_id, loperand.extraparam, roperand.extraparam, result)) {
retVal = mapIntConstant(scope, result);
node.set(lxConstantInt, retVal.param);
node.appendNode(lxIntValue, result);
return retVal;
}
}
else if (loperand.kind == okRealConstant && roperand.kind == okRealConstant) {
double l = scope.module->resolveConstant(loperand.param).toDouble();
double r = scope.module->resolveConstant(roperand.param).toDouble();
double result = 0;
if (calculateRealOp(operator_id, l, r, result)) {
retVal = mapRealConstant(scope, result);
node.set(lxConstantReal, retVal.param);
return retVal;
}
}
ref_t loperandRef = resolveObjectReference(scope, loperand, false);
ref_t roperandRef = resolveObjectReference(scope, roperand, false);
// ref_t roperand2Ref = 0;
ref_t resultClassRef = 0;
int operationType = 0;
// if (roperand2.kind != okUnknown) {
// roperand2Ref = resolveObjectReference(scope, roperand2, false);
// //HOTFIX : allow to work with int constants
// if (roperand2.kind == okIntConstant && loperandRef == V_OBJARRAY)
// roperand2Ref = 0;
//
// operationType = _logic->resolveOperationType(*scope.moduleScope, operator_id, loperandRef, roperandRef, roperand2Ref, resultClassRef);
//
// //if (roperand2Ref == V_NIL && loperandRef == V_INT32ARRAY && operator_id == SET_REFER_MESSAGE_ID) {
// // //HOTFIX : allow set operation with nil
// // operator_id = SETNIL_REFER_MESSAGE_ID;
// //}
// }
/*else */operationType = _logic->resolveOperationType(*scope.moduleScope, operator_id, loperandRef, roperandRef,
resultClassRef);
// HOTFIX : primitive operations can be implemented only in the method
// because the symbol implementations do not open a new stack frame
if (operationType != 0 && resultClassRef != V_FLAG && scope.getScope(Scope::ScopeLevel::slMethod) == NULL) {
operationType = 0;
}
// //bool assignMode = false;
if (operationType != 0) {
// if it is a primitive operation
if (IsExprOperator(operator_id) || IsArrExprOperator(operator_id, (LexicalType)operationType)) {
retVal = allocateResult(scope, /*false, */resultClassRef, loperand.element);
}
else retVal = ObjectInfo(okObject, 0, resultClassRef, loperand.element, 0);
// HOTFIX : remove boxing expressions
analizeOperands(node, scope, -1, false);
ref_t opElementRef = loperand.element;
if (operator_id == LEN_OPERATOR_ID)
opElementRef = roperand.element;
_logic->injectOperation(node, scope, *this, operator_id, operationType, resultClassRef, opElementRef, retVal.param);
// HOTFIX : update the result type
retVal.reference = resultClassRef;
if (IsArrExprOperator(operator_id, (LexicalType)operationType)) {
// inject to target for array operation
node.appendNode(lxLocalAddress, retVal.param);
node.injectAndReplaceNode(lxSeqExpression);
SNode valExpr = node.appendNode(lxBoxableExpression);
valExpr.appendNode(lxLocalAddress, retVal.param);
appendBoxingInfo(valExpr, scope, retVal, EAttrs::test(mode, HINT_NOUNBOXING),
0, resolveObjectReference(scope, retVal, false));
}
}
// if not , replace with appropriate method call
else {
EAttr operationMode = HINT_NODEBUGINFO;
ref_t implicitSignatureRef = 0;
if (roperand2.kind != okUnknown) {
implicitSignatureRef = resolveStrongArgument(scope, roperand, roperand2);
}
else implicitSignatureRef = resolveStrongArgument(scope, roperand);
int stackSafeAttr = 0;
int messageRef = resolveMessageAtCompileTime(loperand, scope, resolveOperatorMessage(scope, operator_id, argCount),
implicitSignatureRef, true, stackSafeAttr);
if (!test(stackSafeAttr, 1)) {
operationMode = operationMode | HINT_DYNAMIC_OBJECT;
}
else stackSafeAttr &= 0xFFFFFFFE; // exclude the stack safe target attribute, it should be set by compileMessage
bool dummy = false;
retVal = compileMessage(node, scope, loperand, messageRef, operationMode, stackSafeAttr, dummy);
}
return retVal;
}
ObjectInfo Compiler :: compileOperator(SNode& node, ExprScope& scope, ObjectInfo loperand, EAttr mode, int operator_id)
{
SNode opNode = node.parentNode();
ObjectInfo retVal(okObject);
int argCount = 2;
ObjectInfo roperand;
ObjectInfo roperand2;
SNode roperandNode = node;
if (operator_id == SET_REFER_OPERATOR_ID) {
// HOTFIX : overwrite the assigning part
SNode roperand2Node = node.parentNode().nextNode();
if (roperand2Node == lxAssign) {
roperand2Node = lxIdle;
roperand2Node = roperand2Node.nextNode();
}
SyntaxTree::copyNode(roperand2Node, opNode.appendNode(roperand2Node.type, roperand2Node.argument));
roperand2Node = lxIdle;
roperand2Node = node.nextNode();
roperand = compileExpression(roperandNode, scope, 0, EAttr::eaNone);
roperand2 = compileExpression(roperand2Node, scope, 0, EAttr::eaNone);
argCount++;
}
else {
// /*if (roperandNode == lxLocal) {
// // HOTFIX : to compile switch statement
// roperand = ObjectInfo(okLocal, roperandNode.argument);
// }*/
if (test(roperandNode.type, lxTerminalMask)) {
roperand = mapTerminal(roperandNode, scope, EAttr::eaNone);
}
else roperand = compileExpression(roperandNode, scope, 0, EAttr::eaNone);
}
return compileOperator(opNode, scope, operator_id, argCount, loperand, roperand, roperand2, mode);
}
inline ident_t resolveOperatorName(SNode node)
{
SNode terminal = node.firstChild(lxTerminalMask);
if (terminal != lxNone) {
return terminal.identifier();
}
else return node.identifier();
}
ObjectInfo Compiler :: compileOperator(SNode& node, ExprScope& scope, ObjectInfo target, EAttr mode)
{
SNode current = node;
int operator_id = (int)current.argument > 0 ? current.argument : _operators.get(resolveOperatorName(current));
SNode roperand = node.nextNode();
// if (operatorNode.prevNode() == lxNone)
// roperand = roperand.nextNode(lxObjectMask);
switch (operator_id) {
case IF_OPERATOR_ID:
case IFNOT_OPERATOR_ID:
// if it is branching operators
return compileBranchingOperator(roperand, scope, target, mode, operator_id);
case CATCH_OPERATOR_ID:
case FINALLY_OPERATOR_ID:
return compileCatchOperator(roperand, scope/*, target, mode*/, operator_id);
case ALT_OPERATOR_ID:
return compileAltOperator(roperand, scope, target/*, mode, operator_id*/);
case ISNIL_OPERATOR_ID:
return compileIsNilOperator(roperand, scope, target);
case APPEND_OPERATOR_ID:
node.setArgument(ADD_OPERATOR_ID);
return compileAssigning(node, scope, target, false);
case REDUCE_OPERATOR_ID:
node.setArgument(SUB_OPERATOR_ID);
return compileAssigning(node, scope, target, false);
case INCREASE_OPERATOR_ID:
node.setArgument(MUL_OPERATOR_ID);
return compileAssigning(node, scope, target, false);
case SEPARATE_OPERATOR_ID:
node.setArgument(DIV_OPERATOR_ID);
return compileAssigning(node, scope, target, false);
default:
return compileOperator(roperand, scope, target, mode, operator_id);
}
}
ObjectInfo Compiler :: compileMessage(SNode& node, ExprScope& scope, ObjectInfo target, int messageRef,
EAttr mode, int stackSafeAttr, bool& embeddableRet)
{
ObjectInfo retVal(okObject);
LexicalType operation = lxCalling_0;
int argument = messageRef;
// try to recognize the operation
ref_t classReference = resolveObjectReference(scope, target, true);
ref_t constRef = 0;
bool inlineArgCall = EAttrs::test(mode, HINT_INLINEARGMODE);
// bool dispatchCall = false;
bool directCall = EAttrs::test(mode, HINT_DIRECTCALL);
_CompilerLogic::ChechMethodInfo result;
int callType = 0;
if (!inlineArgCall && !directCall) {
callType = _logic->resolveCallType(*scope.moduleScope, classReference, messageRef, result);
}
if (callType == tpPrivate) {
if (isSelfCall(target)) {
messageRef |= STATIC_MESSAGE;
callType = tpSealed;
}
else result.found = false;
}
if (result.found) {
retVal.reference = result.outputReference;
constRef = result.constRef;
}
//// else if (classReference == scope.moduleScope->signatureReference) {
//// dispatchCall = test(mode, HINT_EXTENSION_MODE);
//// }
//// else if (classReference == scope.moduleScope->messageReference) {
//// dispatchCall = test(mode, HINT_EXTENSION_MODE);
//// }
/*else */if (target.kind == okSuper) {
// parent methods are always sealed
callType = tpSealed;
}
if (inlineArgCall) {
operation = lxInlineArgCall;
argument = messageRef;
}
// else if (dispatchCall) {
// operation = lxDirectCalling;
// argument = scope.moduleScope->dispatch_message;
//
// writer.appendNode(lxOvreriddenMessage, messageRef);
// }
else if (callType == tpClosed || callType == tpSealed) {
operation = callType == tpClosed ? lxSDirectCalling : lxDirectCalling;
argument = messageRef;
if (!EAttrs::test(mode, HINT_DYNAMIC_OBJECT)) {
// if the method directly resolved and the target is not required to be dynamic, mark it as stacksafe
if (target.kind == okParams) {
// HOTFIX : if variadic argument should not be dynamic, mark it as stacksafe
stackSafeAttr |= 1;
}
else if (_logic->isStacksafeArg(*scope.moduleScope, classReference) && result.stackSafe)
stackSafeAttr |= 1;
}
}
else {
// if the sealed / closed class found and the message is not supported - warn the programmer and raise an exception
if (EAttrs::test(mode, HINT_SILENT)) {
// do nothing in silent mode
}
else if (result.found && !result.withCustomDispatcher && callType == tpUnknown) {
if (target.reference == scope.moduleScope->superReference || !target.reference) {
// ignore warning for super class / type-less one
}
else if (EAttrs::test(mode, HINT_CONVERSIONOP)) {
SNode terminal = node.firstChild(lxObjectMask).firstChild(lxTerminalMask);
if (terminal != lxNone) {
scope.raiseWarning(WARNING_LEVEL_1, wrnUnknownConversion, node);
}
else if (node.parentNode() == lxNewFrame){
scope.raiseWarning(WARNING_LEVEL_1, wrnUnknownEOPConversion, node.parentNode().findChild(lxEOP));
}
}
else if (node.findChild(lxMessage).firstChild(lxTerminalMask) == lxNone) {
scope.raiseWarning(WARNING_LEVEL_1, wrnUnknownFunction, node);
}
else scope.raiseWarning(WARNING_LEVEL_1, wrnUnknownMessage, node.findChild(lxMessage));
}
}
if (result.withEmbeddableRet) {
embeddableRet = result.withEmbeddableRet;
}
if (result.embeddable) {
node.appendNode(lxEmbeddableAttr);
}
// if (stackSafeAttr && !dispatchCall && !result.dynamicRequired)
// writer.appendNode(lxStacksafeAttr, stackSafeAttr);
if (classReference)
node.insertNode(lxCallTarget, classReference);
if (constRef && callType == tpSealed) {
node.appendNode(lxConstAttr, constRef);
NamespaceScope* ns = (NamespaceScope*)scope.getScope(Scope::ScopeLevel::slNamespace);
retVal = ns->defineObjectInfo(constRef, true);
}
// define the message target if required
if (target.kind == okConstantRole/* || target.kind == okSubject*/) {
node.insertNode(lxConstantSymbol, target.reference);
}
// inserting calling expression
node.set(operation, argument);
analizeOperands(node, scope, stackSafeAttr, false);
scope.originals.clear();
return retVal;
}
void Compiler :: boxArgument(SNode boxExprNode, SNode current, ExprScope& scope,
bool boxingMode, bool withoutLocalBoxing, bool inPlace, bool condBoxing)
{
if (current == lxExpression) {
boxArgument(boxExprNode, current.firstChild(lxObjectMask), scope, boxingMode, withoutLocalBoxing,
inPlace, condBoxing);
}
else if (current == lxSeqExpression) {
boxArgument(boxExprNode, current.lastChild(lxObjectMask), scope, boxingMode, withoutLocalBoxing,
true, condBoxing);
}
else if (current.compare(lxBoxableExpression, lxCondBoxableExpression)) {
// resolving double boxing
current.set(lxExpression, 0);
boxArgument(boxExprNode, current.firstChild(lxObjectMask), scope, boxingMode, withoutLocalBoxing,
inPlace, condBoxing);
}
else if (current == lxArgBoxableExpression) {
throw InternalError("Not yet implemented");
}
else {
if (current == lxNewArrOp) {
ref_t typeRef = boxExprNode.findChild(lxType).argument;
current.setArgument(typeRef);
}
else if (current.compare(lxStdExternalCall, lxExternalCall, lxCoreAPICall)) {
if (boxingMode) {
injectIndexBoxing(boxExprNode, current, scope);
}
}
else if (boxingMode || (current == lxFieldExpression && !withoutLocalBoxing)) {
if (inPlace || (test(current.type, lxOpScopeMask) && current != lxFieldExpression)) {
boxExpressionInPlace(boxExprNode, current, scope, !boxingMode, condBoxing);
}
else {
SNode argNode = current;
if (current == lxFieldExpression) {
argNode = current.lastChild(lxObjectMask);
}
if (boxingMode || (!withoutLocalBoxing && argNode == lxFieldAddress)) {
Attribute key(argNode.type, argNode.argument);
int tempLocal = scope.tempLocals.get(key);
if (tempLocal == NOTFOUND_POS) {
tempLocal = scope.newTempLocal();
scope.tempLocals.add(key, tempLocal);
boxExpressionInRoot(boxExprNode, current, scope, lxTempLocal, tempLocal,
!boxingMode, condBoxing);
}
else current.set(lxTempLocal, tempLocal);
}
}
}
}
}
void Compiler :: analizeOperand(SNode& current, ExprScope& scope, bool boxingMode, bool withoutLocalBoxing, bool inPlace)
{
switch (current.type) {
case lxArgBoxableExpression:
case lxBoxableExpression:
case lxCondBoxableExpression:
case lxPrimArrBoxableExpression:
boxArgument(current, current.firstChild(lxObjectMask), scope, boxingMode, withoutLocalBoxing,
inPlace, current == lxCondBoxableExpression);
current.set(lxExpression, 0);
break;
case lxExpression:
case lxYieldReturning:
{
SNode opNode = current.firstChild(lxObjectMask);
analizeOperand(opNode, scope, boxingMode, withoutLocalBoxing, inPlace);
break;
}
case lxSeqExpression:
{
SNode opNode = current.lastChild(lxObjectMask);
// HOTFIX : box in-place the result of sub operation
analizeOperand(opNode, scope, boxingMode, withoutLocalBoxing, true);
break;
}
case lxFieldExpression:
{
SNode opNode = current.lastChild(lxObjectMask);
analizeOperand(opNode, scope, boxingMode, withoutLocalBoxing, inPlace);
break;
}
default:
break;
}
}
void Compiler :: analizeOperands(SNode& node, ExprScope& scope, int stackSafeAttr, bool inPlace)
{
// if boxing / unboxing required - insert SeqExpression, prepand boxing, replace operand with boxed arg, append unboxing
SNode current = node.firstChild(lxObjectMask);
int argBit = 1;
while (current != lxNone) {
analizeOperand(current, scope, !test(stackSafeAttr, argBit), false, inPlace);
argBit <<= 1;
current = current.nextNode(lxObjectMask);
}
}
ObjectInfo Compiler :: convertObject(SNode& node, ExprScope& scope, ref_t targetRef, ObjectInfo source, EAttr mode)
{
//NamespaceScope* nsScope = (NamespaceScope*)scope.getScope(Scope::ScopeLevel::slNamespace);
bool noUnboxing = EAttrs::test(mode, HINT_NOUNBOXING);
ref_t sourceRef = resolveObjectReference(scope, source, false);
int stackSafeAttrs = 0;
if (!_logic->isCompatible(*scope.moduleScope, targetRef, sourceRef, false)) {
if ((source.kind == okIntConstant || source.kind == okUIntConstant)
&& targetRef == scope.moduleScope->intReference && !EAttrs::test(mode, HINT_DYNAMIC_OBJECT))
{
// HOTFIX : allow to pass the constant directly
source.reference = scope.moduleScope->intReference;
return source;
}
else if ((source.kind == okLongConstant)
&& targetRef == scope.moduleScope->longReference && !EAttrs::test(mode, HINT_DYNAMIC_OBJECT))
{
// HOTFIX : allow to pass the constant directly
source.reference = scope.moduleScope->longReference;
return source;
}
else if ((source.kind == okRealConstant)
&& targetRef == scope.moduleScope->realReference && !EAttrs::test(mode, HINT_DYNAMIC_OBJECT))
{
// HOTFIX : allow to pass the constant directly
source.reference = scope.moduleScope->realReference;
return source;
}
else if (source.kind == okExternal &&
_logic->isCompatible(*scope.moduleScope, sourceRef, targetRef, true))
{
// HOTFIX : allow to pass the result of external operation directly
return source;
}
else {
int fixedArraySize = 0;
if (source.kind == okFieldAddress && isPrimitiveArrRef(sourceRef))
fixedArraySize = defineFieldSize(scope, source.param);
if (_logic->injectImplicitConversion(scope, node, *this, targetRef, sourceRef,
source.element, noUnboxing, stackSafeAttrs, fixedArraySize))
{
if (node.compare(lxDirectCalling, lxSDirectCalling)) {
// HOTFIX : box arguments if required
analizeOperands(node, scope, stackSafeAttrs, false);
}
return ObjectInfo(okObject, 0, targetRef);
}
else return sendTypecast(node, scope, targetRef, source);
}
}
return source;
}
ObjectInfo Compiler :: sendTypecast(SNode& node, ExprScope& scope, ref_t targetRef, ObjectInfo source)
{
if (targetRef != 0 /*&& !isPrimitiveRef(targetRef)*/) {
if (targetRef != scope.moduleScope->superReference) {
//HOTFIX : ignore super object
ref_t signRef = scope.module->mapSignature(&targetRef, 1, false);
ref_t actionRef = scope.module->mapAction(CAST_MESSAGE, signRef, false);
node.refresh();
if (node != lxExpression)
node.injectAndReplaceNode(lxExpression);
bool dummy;
compileMessage(node, scope, source, encodeMessage(actionRef, 1, 0), HINT_NODEBUGINFO | HINT_CONVERSIONOP, 0, dummy);
return ObjectInfo(okObject, 0, targetRef);
}
else return source;
}
// NOTE : if the typecasting is not possible, it returns unknown result
else return ObjectInfo();
}
ref_t Compiler :: resolveStrongArgument(ExprScope& scope, ObjectInfo info)
{
ref_t argRef = resolveObjectReference(scope, info, true);
if (!argRef) {
return 0;
}
return scope.module->mapSignature(&argRef, 1, false);
}
ref_t Compiler :: resolveStrongArgument(ExprScope& scope, ObjectInfo info1, ObjectInfo info2)
{
ref_t argRef[2];
argRef[0] = resolveObjectReference(scope, info1, true);
argRef[1] = resolveObjectReference(scope, info2, true);
if (!argRef[0] || !argRef[1])
return 0;
return scope.module->mapSignature(argRef, 2, false);
}
ref_t Compiler :: resolvePrimitiveReference(_CompileScope& scope, ref_t argRef, ref_t elementRef, bool declarationMode)
{
switch (argRef) {
case V_WRAPPER:
return resolveReferenceTemplate(scope, elementRef, declarationMode);
case V_ARGARRAY:
return resolvePrimitiveArray(scope, scope.moduleScope->argArrayTemplateReference, elementRef, declarationMode);
case V_INT32:
return scope.moduleScope->intReference;
case V_INT64:
return scope.moduleScope->longReference;
case V_REAL64:
return scope.moduleScope->realReference;
case V_SUBJECT:
return scope.moduleScope->messageNameReference;
case V_MESSAGE:
return scope.moduleScope->messageReference;
case V_EXTMESSAGE:
return scope.moduleScope->extMessageReference;
case V_UNBOXEDARGS:
// HOTFIX : should be returned as is
return argRef;
case V_NIL:
return scope.moduleScope->superReference;
default:
if (isPrimitiveArrRef(argRef)) {
return resolvePrimitiveArray(scope, scope.moduleScope->arrayTemplateReference, elementRef, declarationMode);
}
throw InternalError("Not yet implemented"); // !! temporal
// return scope.superReference;
}
}
ref_t Compiler :: compileMessageParameters(SNode& node, ExprScope& scope, EAttr mode, bool& variadicOne, bool& inlineArg)
{
// HOTFIX : save the previous call node and set the new one : used for closure unboxing
SNode prevCallNode = scope.callNode;
if (node != lxNone)
scope.callNode = node.parentNode();
EAttr paramMode = HINT_PARAMETER;
bool externalMode = false;
if (EAttrs::test(mode, HINT_EXTERNALOP)) {
externalMode = true;
}
else paramMode = paramMode | HINT_NOPRIMITIVES;
SNode current = node;
// compile the message argument list
ref_t signatures[ARG_COUNT];
ref_t signatureLen = 0;
while (/*current != lxMessage && */current != lxNone) {
if (test(current.type, lxObjectMask)) {
// if (externalMode)
// writer.newNode(lxExtArgument);
// try to recognize the message signature
ObjectInfo paramInfo = compileExpression(current, scope, 0, paramMode);
ref_t argRef = resolveObjectReference(scope, paramInfo, false);
if (signatureLen >= ARG_COUNT) {
signatureLen++;
}
else if (inlineArg) {
scope.raiseError(errNotApplicable, current);
}
else if (argRef == V_UNBOXEDARGS) {
if (paramInfo.element) {
signatures[signatureLen++] = paramInfo.element;
}
else signatures[signatureLen++] = scope.moduleScope->superReference;
if (!variadicOne) {
variadicOne = true;
}
else scope.raiseError(errNotApplicable, current);
}
else if (argRef == V_INLINEARG) {
if (signatureLen == 0) {
inlineArg = true;
}
else scope.raiseError(errNotApplicable, current);
}
else if (argRef) {
signatures[signatureLen++] = argRef;
if (externalMode && !current.existChild(lxType))
current.appendNode(lxType, argRef);
}
else signatures[signatureLen++] = scope.moduleScope->superReference;
// if (externalMode) {
// writer.appendNode(lxExtArgumentRef, argRef);
// writer.closeNode();
// }
}
current = current.nextNode();
}
// HOTFIX : restore the previous call node
scope.callNode = prevCallNode;
if (signatureLen > 0 && signatureLen <= ARG_COUNT) {
bool anonymous = true;
for (ref_t i = 0; i < signatureLen; i++) {
if (signatures[i] != scope.moduleScope->superReference) {
anonymous = false;
break;
}
}
if (!anonymous || variadicOne)
return scope.module->mapSignature(signatures, signatureLen, false);
}
return 0;
}
ref_t Compiler :: resolveVariadicMessage(Scope& scope, ref_t message)
{
int argCount = 0;
ref_t actionRef = 0, flags = 0, dummy = 0;
decodeMessage(message, actionRef, argCount, flags);
ident_t actionName = scope.module->resolveAction(actionRef, dummy);
int argMultuCount = test(message, FUNCTION_MESSAGE) ? 1 : 2;
return encodeMessage(scope.module->mapAction(actionName, 0, false), argMultuCount, flags | VARIADIC_MESSAGE);
}
bool Compiler :: isSelfCall(ObjectInfo target)
{
switch (target.kind) {
case okSelfParam:
case okOuterSelf:
case okClassSelf:
case okInternalSelf:
return true;
default:
return false;
}
}
ref_t Compiler :: resolveMessageAtCompileTime(ObjectInfo& target, ExprScope& scope, ref_t generalMessageRef, ref_t implicitSignatureRef,
bool withExtension, int& stackSafeAttr)
{
int resolvedStackSafeAttr = 0;
ref_t resolvedMessageRef = 0;
ref_t targetRef = resolveObjectReference(scope, target, true);
// try to resolve the message as is
resolvedMessageRef = _logic->resolveMultimethod(*scope.moduleScope, generalMessageRef, targetRef,
implicitSignatureRef, resolvedStackSafeAttr, isSelfCall(target));
if (resolvedMessageRef != 0) {
stackSafeAttr = resolvedStackSafeAttr;
// if the object handles the compile-time resolved message - use it
return resolvedMessageRef;
}
// check if the object handles the variadic message
if (targetRef) {
resolvedStackSafeAttr = 0;
resolvedMessageRef = _logic->resolveMultimethod(*scope.moduleScope,
resolveVariadicMessage(scope, generalMessageRef),
targetRef, implicitSignatureRef, resolvedStackSafeAttr, isSelfCall(target));
if (resolvedMessageRef != 0) {
stackSafeAttr = resolvedStackSafeAttr;
// if the object handles the compile-time resolved variadic message - use it
return resolvedMessageRef;
}
}
if (withExtension) {
resolvedMessageRef = generalMessageRef;
// check the existing extensions if allowed
if (checkMethod(*scope.moduleScope, targetRef, generalMessageRef) != tpUnknown) {
// could be stacksafe
stackSafeAttr |= 1;
// if the object handles the general message - do not use extensions
return generalMessageRef;
}
resolvedStackSafeAttr = 0;
ref_t extensionRef = mapExtension(scope, resolvedMessageRef, implicitSignatureRef, target, resolvedStackSafeAttr);
if (extensionRef != 0) {
stackSafeAttr = resolvedStackSafeAttr;
// if there is an extension to handle the compile-time resolved message - use it
target = ObjectInfo(okConstantRole, extensionRef, extensionRef);
return resolvedMessageRef;
}
// check if the extension handles the variadic message
ref_t variadicMessage = resolveVariadicMessage(scope, generalMessageRef);
resolvedStackSafeAttr = 0;
extensionRef = mapExtension(scope, variadicMessage, implicitSignatureRef, target, resolvedStackSafeAttr);
if (extensionRef != 0) {
stackSafeAttr = resolvedStackSafeAttr;
// if there is an extension to handle the compile-time resolved message - use it
target = ObjectInfo(okConstantRole, extensionRef, extensionRef);
return variadicMessage;
}
}
// otherwise - use the general message
return generalMessageRef;
}
ObjectInfo Compiler :: compileMessage(SNode node, ExprScope& scope, ref_t expectedRef, ObjectInfo target, EAttr mode)
{
EAttr paramsMode = EAttr::eaNone;
if (target.kind == okExternal) {
paramsMode = paramsMode | HINT_EXTERNALOP;
}
ObjectInfo retVal;
bool variadicOne = false;
bool inlineArg = false;
ref_t implicitSignatureRef = compileMessageParameters(node, scope, paramsMode, variadicOne, inlineArg);
// bool externalMode = false;
if (target.kind == okExternal) {
EAttr extMode = mode & HINT_ROOT;
retVal = compileExternalCall(node, scope, expectedRef, extMode);
}
else {
ref_t messageRef = mapMessage(node, scope, variadicOne, target.kind == okExtension);
if (target.kind == okInternal) {
retVal = compileInternalCall(node.parentNode(), scope, messageRef, implicitSignatureRef, target);
}
else if (inlineArg) {
SNode parentNode = node.parentNode();
bool dummy = false;
retVal = compileMessage(parentNode, scope, target, messageRef, mode | HINT_INLINEARGMODE, 0, dummy);
}
else {
int stackSafeAttr = 0;
if (!EAttrs::test(mode, HINT_DIRECTCALL))
messageRef = resolveMessageAtCompileTime(target, scope, messageRef, implicitSignatureRef, true, stackSafeAttr);
if (!test(stackSafeAttr, 1)) {
mode = mode | HINT_DYNAMIC_OBJECT;
}
else if (target.kind != okConstantRole)
stackSafeAttr &= 0xFFFFFFFE; // exclude the stack safe target attribute, it should be set by compileMessage
SNode opNode = node.parentNode();
bool withEmbeddableRet = false;
retVal = compileMessage(opNode, scope, target, messageRef, mode, stackSafeAttr, withEmbeddableRet);
if (expectedRef && withEmbeddableRet) {
ref_t byRefMessageRef = _logic->resolveEmbeddableRetMessage(
scope, *this, resolveObjectReference(scope, target, true),
messageRef, expectedRef);
if (byRefMessageRef) {
ObjectInfo tempVar = allocateResult(scope, expectedRef);
if (tempVar.kind == okLocalAddress) {
opNode.appendNode(lxLocalAddress, tempVar.param);
opNode.appendNode(lxRetEmbeddableAttr);
opNode.setArgument(byRefMessageRef);
opNode.injectAndReplaceNode(lxSeqExpression);
opNode.appendNode(lxLocalAddress, tempVar.param);
opNode.injectAndReplaceNode(lxBoxableExpression);
opNode.appendNode(lxType, expectedRef);
opNode.appendNode(lxSize, _logic->defineStructSize(*scope.moduleScope, expectedRef, 0));
}
else if (tempVar.kind == okLocal){
SNode tempExpr = opNode.appendNode(lxExpression);
tempExpr.appendNode(lxAttribute, V_WRAPPER);
tempExpr.appendNode(lxTempLocal, tempVar.param).appendNode(lxType, expectedRef);
ObjectInfo paramInfo = compileExpression(tempExpr, scope, 0, HINT_PARAMETER);
//SNode tempNode = opNode.appendNode(lxTempLocal, tempVar.param);
//ref_t targetRef = resolveReferenceTemplate(scope, expectedRef, false);
////SNode opNode = node.parentNode();
//ObjectInfo retVal = convertObject(tempNode, scope, targetRef, tempVar, mode);
opNode.appendNode(lxRetEmbeddableAttr);
opNode.setArgument(byRefMessageRef);
opNode.injectAndReplaceNode(lxSeqExpression, -2);
opNode.appendNode(lxTempLocal, tempVar.param);
opNode = opNode.firstChild(lxObjectMask);
//SNode boxExprNode = opNode.findChild(lxBoxableExpression);
//boxExpressionInRoot(boxExprNode, boxExprNode.firstChild(lxObjectMask), scope, lxTempLocal, tempVar.param,
// false, false);
analizeOperands(opNode, scope, stackSafeAttr, false);
}
else throw InternalError("Not yet implemented"); // !! temporal
retVal = tempVar;
}
}
}
}
return retVal;
}
void Compiler :: inheritClassConstantList(_ModuleScope& scope, ref_t sourceRef, ref_t targetRef)
{
ref_t moduleRef = 0;
_Module* parent = scope.loadReferenceModule(sourceRef, moduleRef);
_Memory* source = parent->mapSection(moduleRef | mskRDataRef, true);
_Memory* target = scope.module->mapSection(targetRef | mskRDataRef, false);
MemoryReader reader(source);
MemoryWriter writer(target);
writer.read(&reader, source->Length());
_ELENA_::RelocationMap::Iterator it(source->getReferences());
ref_t currentMask = 0;
ref_t currentRef = 0;
while (!it.Eof()) {
currentMask = it.key() & mskAnyRef;
currentRef = it.key() & ~mskAnyRef;
target->addReference(importReference(parent, currentRef, scope.module) | currentMask, *it);
it++;
}
}
inline SNode findBookmarkOwner(SNode node, ref_t bookmark)
{
while (!node.compare(lxClass, lxNestedClass, lxNone))
node = node.parentNode();
SNode current = node.firstChild();
while (current != lxNone) {
if (current.compare(lxClassMethod, lxConstructor, lxClassField, lxStaticMethod)) {
SNode bm = current.findChild(lxBookmark);
if (bm.argument == bookmark)
return current;
}
current = current.nextNode();
}
return node;
}
void Compiler :: compileMetaConstantAssigning(ObjectInfo, SNode node, ClassScope& scope)
{
int bm = node.parentNode().findChild(lxBookmarkReference).argument;
ExprScope exprScope(&scope);
ObjectInfo source = mapObject(node, exprScope, EAttr::eaNone);
ref_t sourceRef = resolveConstantObjectReference(scope, source);
if (isPrimitiveRef(sourceRef))
sourceRef = resolvePrimitiveReference(scope, sourceRef, source.element, false);
bool valid = false;
ident_t info;
if (sourceRef == scope.moduleScope->literalReference) {
if (source.kind == okLiteralConstant) {
info = scope.module->resolveConstant(source.param);
valid = true;
}
}
if (valid) {
// resolve the meta field target
SNode targetNode = findBookmarkOwner(node.parentNode(), bm);
Attribute key;
if (targetNode == lxClass) {
key = Attribute(caInfo, 0);
}
else if (targetNode.compare(lxClassMethod, lxConstructor, lxStaticMethod)) {
key = Attribute(caInfo, targetNode.argument);
}
if (targetNode == lxStaticMethod) {
// HOTFIX : recognize class class meta info
ClassScope classClassScope(&scope, scope.info.header.classRef, scope.visibility);
scope.moduleScope->loadClassInfo(classClassScope.info, scope.module->resolveReference(classClassScope.reference), false);
classClassScope.info.mattributes.add(key, saveMetaInfo(*scope.moduleScope, info));
classClassScope.save();
}
else {
scope.info.mattributes.add(key, saveMetaInfo(*scope.moduleScope, info));
scope.save();
}
}
else scope.raiseError(errIllegalOperation, node);
}
inline ref_t mapStaticField(_ModuleScope* moduleScope, ref_t reference, bool isArray)
{
int mask = isArray ? mskConstArray : mskConstantRef;
IdentifierString name(moduleScope->module->resolveReference(reference));
name.append(STATICFIELD_POSTFIX);
return moduleScope->mapAnonymous(name.c_str() + 1) | mask;
}
inline ref_t mapConstant(_ModuleScope* moduleScope, ref_t reference)
{
IdentifierString name(moduleScope->module->resolveReference(reference));
name.append(CONSTANT_POSTFIX);
return moduleScope->mapAnonymous(name.c_str() + 1);
}
inline bool isInherited(_Module* module, ref_t reference, ref_t staticRef)
{
ident_t name = module->resolveReference(reference);
ident_t statName = module->resolveReference(staticRef);
size_t len = getlength(name);
if (statName[len] == '#' && statName.compare(name, 0, len)) {
return true;
}
else return false;
}
void Compiler :: compileClassConstantAssigning(ObjectInfo target, SNode node, ClassScope& scope, bool accumulatorMode)
{
ref_t valueRef = scope.info.staticValues.get(target.param);
if (accumulatorMode) {
// HOTFIX : inherit accumulating attribute list
ClassInfo parentInfo;
scope.moduleScope->loadClassInfo(parentInfo, scope.info.header.parentRef);
ref_t targtListRef = valueRef & ~mskAnyRef;
ref_t parentListRef = parentInfo.staticValues.get(target.param) & ~mskAnyRef;
if (parentListRef != 0 && !isInherited(scope.module, scope.reference, targtListRef)) {
valueRef = mapStaticField(scope.moduleScope, scope.reference, true);
scope.info.staticValues.exclude(target.param);
scope.info.staticValues.add(target.param, valueRef);
scope.save();
targtListRef = valueRef & ~mskAnyRef;
// inherit the parent list
inheritClassConstantList(*scope.moduleScope, parentListRef, targtListRef);
}
}
SymbolScope constantScope((NamespaceScope*)scope.getScope(Scope::ScopeLevel::slNamespace), valueRef & ~mskAnyRef, Visibility::Public);
ExprScope exprScope(&constantScope);
ObjectInfo source = mapObject(node, exprScope, EAttr::eaNone);
ref_t targetRef = accumulatorMode ? target.element : target.reference;
if (accumulatorMode && !targetRef)
targetRef = _logic->resolveArrayElement(*scope.moduleScope, target.reference);
ref_t sourceRef = resolveConstantObjectReference(scope, source);
if (isPrimitiveRef(sourceRef))
sourceRef = resolvePrimitiveReference(scope, sourceRef, source.element, false);
if (compileSymbolConstant(/*node, */constantScope, source, accumulatorMode, target.reference)
&& _logic->isCompatible(*scope.moduleScope, targetRef, sourceRef, false))
{
}
else scope.raiseError(errInvalidOperation, node);
}
bool Compiler :: resolveAutoType(ObjectInfo source, ObjectInfo& target, ExprScope& scope)
{
ref_t sourceRef = resolveObjectReference(scope, source, true);
if (!_logic->validateAutoType(*scope.moduleScope, sourceRef))
return false;
return scope.resolveAutoType(target, sourceRef, source.element);
}
inline ref_t resolveSubjectVar(SNode current)
{
int bm = current.findChild(lxBookmarkReference).argument;
if (bm) {
SNode targetNode = findBookmarkOwner(current.parentNode(), bm);
if (targetNode.compare(lxClassMethod, lxConstructor, lxStaticMethod)) {
return getAction(targetNode.argument);
}
}
return 0;
}
void Compiler :: resolveMetaConstant(SNode node)
{
SNode assignNode = node.findChild(lxAssign);
if (assignNode != lxNone) {
SNode exprNode = assignNode.nextNode().findSubNode(lxMetaConstant);
if (exprNode != lxNone) {
if (exprNode.identifier().compare(SUBJECT_VAR)) {
ref_t subjRef = resolveSubjectVar(node);
if (subjRef) {
exprNode.set(lxSubjectRef, subjRef);
}
}
}
}
}
bool Compiler :: recognizeCompileTimeAssigning(SNode node, ClassScope& scope)
{
bool idle = true;
SNode current = node.firstChild();
while (current != lxNone) {
if (current == lxFieldInit) {
ref_t dummy = 0;
bool dummy2 = false;
SNode identNode = current.firstChild();
if (identNode == lxBookmarkReference) {
resolveMetaConstant(current);
}
EAttr mode = recognizeExpressionAttributes(identNode, scope, dummy, dummy2);
if (identNode != lxNone) {
ObjectInfo field;
if (EAttrs::test(mode, HINT_METAFIELD)) {
field = mapMetaField(identNode.identifier());
}
else field = scope.mapField(identNode.identifier(), mode);
switch (field.kind)
{
case okStaticConstantField:
case okStaticField:
case okMetaField:
// HOTFIX : compile-time assigning should be implemented directly
current = lxStaticFieldInit;
break;
default:
idle = false;
break;
}
}
else idle = false;
}
current = current.nextNode();
}
return idle;
}
void Compiler :: compileCompileTimeAssigning(SNode node, ClassScope& classScope)
{
SNode assignNode = node.findChild(lxAssign);
SNode sourceNode = assignNode.nextNode();
bool accumulateMode = assignNode.argument == INVALID_REF;
ExprScope scope(&classScope);
ObjectInfo target = mapObject(node, scope, EAttr::eaNone);
// HOTFIX : recognize static field initializer
if (target.kind == okStaticField || target.kind == okStaticConstantField || target.kind == okMetaField) {
if (target.kind == okMetaField) {
compileMetaConstantAssigning(target, sourceNode, *((ClassScope*)scope.getScope(Scope::ScopeLevel::slClass))/*, accumulateMode*/);
}
else if (!isSealedStaticField(target.param) && target.kind == okStaticConstantField) {
// HOTFIX : static field initializer should be compiled as preloaded symbol
compileClassConstantAssigning(target, sourceNode, *((ClassScope*)scope.getScope(Scope::ScopeLevel::slClass)), accumulateMode);
}
else compileStaticAssigning(target, sourceNode, *((ClassScope*)scope.getScope(Scope::ScopeLevel::slClass))/*, accumulateMode*/);
}
}
ObjectInfo Compiler :: compileAssigning(SNode node, ExprScope& scope, ObjectInfo target, bool accumulateMode)
{
ObjectInfo retVal = target;
LexicalType operationType = lxAssigning;
int operand = 0;
SNode current = node;
node = current.parentNode();
SNode sourceNode;
// if (current == lxReturning) {
// sourceNode = current.firstChild(lxObjectMask);
// if (test(sourceNode.type, lxTerminalMask)) {
// // HOTFIX
// sourceNode = current;
// }
// }
/*else */sourceNode = current.nextNode(lxObjectMask);
if (accumulateMode)
// !! temporally
scope.raiseError(errInvalidOperation, sourceNode);
EAttr assignMode = HINT_NOUNBOXING/* | HINT_ASSIGNING_EXPR*/;
ref_t targetRef = resolveObjectReference(scope, target, false, false);
bool noBoxing = false;
// bool byRefAssigning = false;
switch (target.kind) {
case okLocal:
case okField:
case okStaticField:
// case okClassStaticField:
case okOuterField:
// case okOuterStaticField:
break;
case okLocalAddress:
case okFieldAddress:
{
size_t size = _logic->defineStructSize(*scope.moduleScope, targetRef, 0u);
if (size != 0) {
noBoxing = true;
operationType = lxCopying;
operand = size;
assignMode = assignMode | HINT_NOBOXING;
}
else scope.raiseError(errInvalidOperation, sourceNode);
break;
}
case okOuter:
case okOuterSelf:
{
InlineClassScope* closure = (InlineClassScope*)scope.getScope(Scope::ScopeLevel::slClass);
//MethodScope* method = (MethodScope*)scope.getScope(Scope::slMethod);
if (/*!method->subCodeMode || */!closure->markAsPresaved(target))
scope.raiseError(errInvalidOperation, sourceNode);
size_t size = _logic->defineStructSize(*scope.moduleScope, targetRef, 0u);
if (size != 0 && target.kind == okOuter) {
operand = size;
//byRefAssigning = true;
}
break;
}
case okReadOnlyField:
case okReadOnlyFieldAddress:
case okOuterReadOnlyField:
scope.raiseError(errReadOnlyField, node.parentNode());
break;
case okParam:
if (targetRef == V_WRAPPER) {
//byRefAssigning = true;
targetRef = target.element;
size_t size = _logic->defineStructSize(*scope.moduleScope, targetRef, 0u);
if (size != 0) {
operand = size;
operationType = lxCopying;
noBoxing = true;
}
else operationType = lxByRefAssigning;
break;
}
default:
scope.raiseError(errInvalidOperation, node.firstChild(lxObjectMask));
break;
}
ObjectInfo exprVal;
// if (operand == 0)
// assignMode = assignMode | HINT_DYNAMIC_OBJECT | HINT_NOPRIMITIVES;
//
// if (isPrimitiveArrRef(targetRef))
// targetRef = resolvePrimitiveReference(scope, targetRef, target.element, false);
//
if (current == lxOperator) {
// COMPILER MAGIC : implementing assignment operators
sourceNode.injectAndReplaceNode(lxExpression);
SNode roperand = sourceNode.firstChild(lxObjectMask);
SNode loperand = sourceNode.insertNode(lxVirtualReference);
recognizeTerminal(loperand, target, scope, EAttr::eaNoDebugInfo);
compileOperator(roperand, scope, target, assignMode, current.argument);
}
else if (targetRef == V_AUTO) {
// support auto attribute
exprVal = compileExpression(sourceNode, scope, 0, assignMode);
if (resolveAutoType(exprVal, target, scope)) {
targetRef = resolveObjectReference(scope, exprVal, false);
retVal.reference = targetRef;
}
else scope.raiseError(errInvalidOperation, node);
}
else if (sourceNode == lxYieldContext) {
int size = scope.getAttribute(sourceNode.argument, maYieldContextLength);
sourceNode.set(lxCreatingStruct, size << 2);
node.set(lxAssigning, 0);
}
else if (sourceNode == lxYieldLocals) {
int len = scope.getAttribute(sourceNode.argument, maYieldLocalLength);
if (len != 0) {
sourceNode.set(lxCreatingClass, len);
node.set(lxAssigning, 0);
}
else operationType = lxIdle;
}
else exprVal = compileExpression(sourceNode, scope, targetRef, assignMode);
if (exprVal.kind == okExternal && operationType == lxCopying) {
noBoxing = true;
operationType = exprVal.param == -1 ? lxFloatSaving : lxSaving;
}
node.set(operationType, operand);
SNode fieldNode = node.firstChild(lxObjectMask);
analizeOperand(fieldNode, scope, false, true, true);
SNode rargNode = fieldNode.nextNode(lxObjectMask);
analizeOperand(rargNode, scope, !noBoxing, true, true);
return retVal;
}
ObjectInfo Compiler :: compilePropAssigning(SNode node, ExprScope& scope, ObjectInfo target)
{
ObjectInfo retVal;
// tranfer the message into the property set one
ref_t messageRef = mapMessage(node, scope, false, false);
ref_t actionRef, flags;
int argCount;
decodeMessage(messageRef, actionRef, argCount, flags);
if (argCount == 1 && test(flags, PROPERTY_MESSAGE)) {
messageRef = encodeMessage(actionRef, 2, flags);
}
else scope.raiseError(errInvalidOperation, node);
// find and compile the parameter
SNode roperand2Node = node.parentNode().nextNode();
if (roperand2Node == lxAssign) {
roperand2Node = lxIdle;
roperand2Node = roperand2Node.nextNode();
}
SNode opNode = node.parentNode();
SyntaxTree::copyNode(roperand2Node, opNode.appendNode(roperand2Node.type, roperand2Node.argument));
// remove the assign node to prevent the duplication
roperand2Node = lxIdle;
roperand2Node = node.nextNode().nextNode();
ObjectInfo source = compileExpression(roperand2Node, scope, 0, EAttr::eaNone);
EAttr mode = HINT_NODEBUGINFO;
int stackSafeAttr = 0;
messageRef = resolveMessageAtCompileTime(target, scope, messageRef, resolveStrongArgument(scope, source), true, stackSafeAttr);
if (!test(stackSafeAttr, 1))
mode = mode | HINT_DYNAMIC_OBJECT;
bool dummy = false;
retVal = compileMessage(opNode, scope, target, messageRef, mode, stackSafeAttr, dummy);
return retVal;
}
bool Compiler :: declareActionScope(ClassScope& scope, SNode argNode, MethodScope& methodScope, EAttr mode)
{
bool lazyExpression = EAttrs::test(mode, HINT_LAZY_EXPR);
ref_t invokeAction = scope.module->mapAction(INVOKE_MESSAGE, 0, false);
methodScope.message = encodeMessage(invokeAction, 0, FUNCTION_MESSAGE);
if (argNode != lxNone) {
// define message parameter
methodScope.message = declareInlineArgumentList(argNode, methodScope, false);
}
return lazyExpression;
}
inline void copyMethodParameters(SNode target, SNode arg)
{
while (arg != lxNone) {
if (arg == lxMethodParameter) {
SNode paramNode = target.insertNode(lxMethodParameter).appendNode(lxNameAttr);
SyntaxTree::copyNode(arg, paramNode);
}
arg = arg.nextNode();
}
}
void Compiler :: compileAction(SNode& node, ClassScope& scope, SNode argNode, EAttr mode)
{
MethodScope methodScope(&scope);
bool lazyExpression = declareActionScope(scope, argNode, methodScope, mode);
bool inlineExpression = EAttrs::test(mode, HINT_INLINE_EXPR);
methodScope.functionMode = true;
ref_t multiMethod = resolveMultimethod(scope, methodScope.message);
// // HOTFIX : if the closure emulates code brackets
// if (EAttrs::test(mode, HINT_SUBCODE_CLOSURE))
// methodScope.subCodeMode = true;
// if it is single expression
if (inlineExpression || lazyExpression) {
//inject a method
node.injectAndReplaceNode(lxClass);
SNode current = node.firstChild();
current.injectAndReplaceNode(lxClassMethod, methodScope.message);
compileExpressionMethod(current, methodScope, lazyExpression);
}
else {
// inject a method
SNode current = node.findChild(lxCode, lxReturning);
current.injectAndReplaceNode(lxClassMethod, methodScope.message);
//!!HOTFIX : copy method parameters to be used for debug info
copyMethodParameters(current, argNode);
initialize(scope, methodScope);
methodScope.functionMode = true;
if (multiMethod)
// if it is a strong-typed closure, output should be defined by the closure
methodScope.outputRef = V_AUTO;
compileActionMethod(current, methodScope);
// HOTFIX : inject an output type if required or used super class
if (methodScope.outputRef == V_AUTO) {
methodScope.outputRef = scope.moduleScope->superReference;
}
if (methodScope.outputRef)
current.insertNode(lxType, methodScope.outputRef);
}
// the parent is defined after the closure compilation to define correctly the output type
ref_t parentRef = scope.info.header.parentRef;
if (lazyExpression) {
parentRef = scope.moduleScope->lazyExprReference;
}
else {
NamespaceScope* nsScope = (NamespaceScope*)scope.getScope(Scope::ScopeLevel::slNamespace);
ref_t closureRef = scope.moduleScope->resolveClosure(methodScope.message, methodScope.outputRef, nsScope->nsName);
// ref_t actionRef = scope.moduleScope->actionHints.get(methodScope.message);
if (closureRef) {
parentRef = closureRef;
}
else throw InternalError(errClosureError);
}
// NOTE : the fields are presaved, so the closure parent should be stateless
compileParentDeclaration(SNode(), scope, parentRef, true);
// set the message output if available
if (methodScope.outputRef)
scope.addAttribute(methodScope.message, maReference, methodScope.outputRef);
if (multiMethod) {
// inject a virtual invoke multi-method if required
List<ref_t> implicitMultimethods;
implicitMultimethods.add(multiMethod);
_logic->injectVirtualMultimethods(*scope.moduleScope, node, *this, implicitMultimethods, lxClassMethod, scope.info);
generateClassDeclaration(node, scope);
// HOTFIX : temporally commenting out the function code, to prevent if from double compiling
SNode current = node.findChild(lxClassMethod);
current = lxIdle;
compileVMT(node, scope);
current = lxClassMethod;
}
else {
// include the message, it is done after the compilation due to the implemetation
scope.include(methodScope.message);
scope.addHint(methodScope.message, tpFunction);
// exclude abstract flag if presented
scope.removeHint(methodScope.message, tpAbstract);
generateClassDeclaration(SNode(), scope);
}
scope.save();
// if (scope.info.staticValues.Count() > 0)
// copyStaticFieldValues(node, scope);
generateClassImplementation(node, scope);
// COMPILER MAGIC : prepand a virtual identifier, terminal info should be copied from the leading attribute
SNode attrTerminal = argNode.firstChild(lxTerminalMask);
node = node.prependSibling(lxVirtualReference);
SyntaxTree::copyNode(attrTerminal, node);
}
void Compiler :: compileNestedVMT(SNode& node, InlineClassScope& scope)
{
SNode current = node.firstChild();
bool virtualClass = true;
while (current != lxNone) {
if (current == lxAttribute) {
EAttrs attributes;
bool dummy = false;
if (_logic->validateExpressionAttribute(current.argument, attributes, dummy) && attributes.test(EAttr::eaNewOp)) {
// only V_NEWOP attribute is allowed
current.setArgument(0);
}
else scope.raiseError(errInvalidHint, current);
}
else if (current == lxType) {
current.injectAndReplaceNode(lxParent);
}
if (current == lxClassField) {
virtualClass = false;
}
else if (current == lxClassMethod) {
if (!current.findChild(lxNameAttr).firstChild(lxTerminalMask).identifier().compare(INIT_MESSAGE)) {
// HOTFIX : ignore initializer auto-generated method
virtualClass = false;
break;
}
}
current = current.nextNode();
}
if (virtualClass)
scope.info.header.flags |= elVirtualVMT;
compileParentDeclaration(node.findChild(lxParent), scope, false);
if (scope.abstractBaseMode && test(scope.info.header.flags, elClosed | elNoCustomDispatcher) && _logic->isWithEmbeddableDispatcher(*scope.moduleScope, node)) {
// COMPILER MAGIC : inject interface implementation
_logic->injectInterfaceDispatch(*scope.moduleScope, *this, node, scope.info.header.parentRef);
}
bool withConstructors = false;
bool withDefaultConstructor = false;
declareVMT(node, scope, withConstructors, withDefaultConstructor);
if (withConstructors)
scope.raiseError(errIllegalConstructor, node);
if (node.existChild(lxStaticMethod))
scope.raiseError(errIllegalStaticMethod, node);
generateClassDeclaration(node, scope, true);
scope.save();
// if (!test(scope.info.header.flags, elVirtualVMT) && scope.info.staticValues.Count() > 0)
// // do not inherit the static fields for the virtual class declaration
// copyStaticFieldValues(node, scope);
// NOTE : ignore auto generated methods - multi methods should be compiled after the class flags are set
compileVMT(node, scope, true, true);
// set flags once again
// NOTE : it should be called after the code compilation to take into consideration outer fields
_logic->tweakClassFlags(*scope.moduleScope, *this, scope.reference, scope.info, false);
// NOTE : compile once again only auto generated methods
compileVMT(node, scope, true, false);
scope.save();
generateClassImplementation(node, scope);
// COMPILER MAGIC : prepand a virtual identifier, terminal info should be copied from the leading attribute
SNode attrTerminal = node.findChild(lxAttribute).firstChild(lxTerminalMask);
node = node.prependSibling(lxVirtualReference);
SyntaxTree::copyNode(attrTerminal, node);
}
ref_t Compiler :: resolveMessageOwnerReference(_ModuleScope& scope, ClassInfo& classInfo, ref_t reference, ref_t message,
bool ignoreSelf)
{
if (!classInfo.methods.exist(message, true) || ignoreSelf) {
ClassInfo parentInfo;
_logic->defineClassInfo(scope, parentInfo, classInfo.header.parentRef, false);
return resolveMessageOwnerReference(scope, parentInfo, classInfo.header.parentRef, message);
}
else return reference;
}
ObjectInfo Compiler :: compileClosure(SNode node, ExprScope& ownerScope, InlineClassScope& scope, EAttr mode)
{
bool noUnboxing = EAttrs::test(mode, HINT_NOUNBOXING);
ref_t closureRef = scope.reference;
if (test(scope.info.header.flags, elVirtualVMT))
closureRef = scope.info.header.parentRef;
if (test(scope.info.header.flags, elStateless)) {
ObjectInfo retVal = ObjectInfo(okSingleton, closureRef, closureRef);
recognizeTerminal(node, retVal, ownerScope, mode);
// if it is a stateless class
return retVal;
}
else if (test(scope.info.header.flags, elDynamicRole)) {
scope.raiseError(errInvalidInlineClass, node);
// idle return
return ObjectInfo();
}
else {
// dynamic binary symbol
if (test(scope.info.header.flags, elStructureRole)) {
node.set(lxCreatingStruct, scope.info.size);
node.appendNode(lxType, closureRef);
if (scope.outers.Count() > 0)
scope.raiseError(errInvalidInlineClass, node);
}
else {
// dynamic normal symbol
node.set(lxCreatingClass, scope.info.fields.Count());
node.appendNode(lxType, closureRef);
}
node.injectAndReplaceNode(lxInitializing);
Map<ident_t, InlineClassScope::Outer>::Iterator outer_it = scope.outers.start();
//int toFree = 0;
int tempLocal = 0;
while(!outer_it.Eof()) {
ObjectInfo info = (*outer_it).outerObject;
SNode member = node.appendNode(lxMember, (*outer_it).reference);
SNode objNode = member.appendNode(lxVirtualReference);
recognizeTerminal(objNode, info, ownerScope, EAttr::eaNone);
analizeOperand(objNode, ownerScope, true, false, false);
if ((*outer_it).preserved && !noUnboxing) {
if (!tempLocal) {
// save the closure in the temp variable
tempLocal = ownerScope.newTempLocal();
node.injectAndReplaceNode(lxAssigning);
node.insertNode(lxTempLocal, tempLocal);
node.injectAndReplaceNode(lxSeqExpression);
node.appendNode(lxTempLocal, tempLocal);
// hotfix : find initializing node again
node = member.parentNode();
}
// HOTFIX : save original to prevent double unboxing
int oriTempLocal = info.kind == okLocal ? ownerScope.originals.get(info.param) : 0;
bool hasToBeSaved = oriTempLocal == -1;
injectMemberPreserving(member, ownerScope, lxTempLocal, tempLocal, info, (*outer_it).reference, oriTempLocal);
if (hasToBeSaved) {
ownerScope.originals.erase(info.param);
ownerScope.originals.add(info.param, oriTempLocal);
}
else if (!oriTempLocal && info.kind == okLocal) {
ownerScope.originals.add(info.param, -1);
}
}
outer_it++;
}
// if (scope.returningMode) {
// // injecting returning code if required
// InlineClassScope::Outer retVal = scope.outers.get(RETVAL_VAR);
//
// writer.newNode(lxCode);
// writer.newNode(lxExpression);
// writer.newNode(lxBranching);
//
// writer.newNode(lxExpression);
// writer.appendNode(lxCurrent);
// writer.appendNode(lxResultField, retVal.reference); // !! current field
// writer.closeNode();
//
// writer.newNode(lxIfNot, -1);
// writer.newNode(lxCode);
// writer.newNode(lxReturning);
// writer.appendNode(lxResult);
// writer.closeNode();
// writer.closeNode();
// writer.closeNode();
//
// writer.closeNode();
// writer.closeNode();
// writer.closeNode();
// }
if (scope.info.methods.exist(scope.moduleScope->init_message)) {
ref_t messageOwnerRef = resolveMessageOwnerReference(*scope.moduleScope, scope.info, scope.reference,
scope.moduleScope->init_message);
// if implicit constructor is declared - it should be automatically called
node.injectAndReplaceNode(lxDirectCalling, scope.moduleScope->init_message);
node.appendNode(lxCallTarget, messageOwnerRef);
}
return ObjectInfo(okObject, 0, closureRef);
}
}
ObjectInfo Compiler :: compileClosure(SNode node, ExprScope& ownerScope, EAttr mode)
{
ref_t nestedRef = 0;
// //bool singleton = false;
if (EAttrs::test(mode, HINT_ROOTSYMBOL)) {
SymbolScope* owner = (SymbolScope*)ownerScope.getScope(Scope::ScopeLevel::slSymbol);
if (owner) {
nestedRef = owner->reference;
// HOTFIX : symbol should refer to self and $self for singleton closure
//singleton = node.existChild(lxCode);
}
}
else if (EAttrs::test(mode, HINT_ROOT)) {
MethodScope* ownerMeth = (MethodScope*)ownerScope.getScope(Scope::ScopeLevel::slMethod);
if (ownerMeth && ownerMeth->constMode) {
ref_t dummyRef = 0;
// HOTFIX : recognize property constant
IdentifierString name(ownerScope.module->resolveReference(ownerScope.getClassRefId()));
if (name.ident().endsWith(CLASSCLASS_POSTFIX)) {
name.truncate(name.Length() - getlength(CLASSCLASS_POSTFIX));
}
name.append('#');
name.append(ownerScope.module->resolveAction(getAction(ownerMeth->message), dummyRef));
nestedRef = ownerMeth->module->mapReference(name.c_str());
}
}
if (!nestedRef) {
nestedRef = ownerScope.moduleScope->mapAnonymous();
}
InlineClassScope scope(&ownerScope, nestedRef);
// if it is a lazy expression / multi-statement closure without parameters
SNode argNode = node.firstChild();
if (EAttrs::testany(mode, HINT_LAZY_EXPR | HINT_INLINE_EXPR)) {
compileAction(node, scope, SNode(), mode);
}
else if (argNode == lxCode) {
compileAction(node, scope, SNode(), /*singleton ? mode | HINT_SINGLETON : */mode);
}
else if (node.existChild(lxCode, lxReturning)) {
//SNode codeNode = node.findChild(lxCode, lxReturning);
// if it is a closure / lambda function with a parameter
EAttr actionMode = mode;
// //if (singleton)
// // actionMode |= HINT_SINGLETON;
compileAction(node, scope, node.findChild(lxIdentifier, /*lxPrivate, */lxMethodParameter/*, lxClosureMessage*/), actionMode);
// // HOTFIX : hide code node because it is no longer required
// codeNode = lxIdle;
}
// if it is a nested class
else compileNestedVMT(node, scope);
return compileClosure(node, ownerScope, scope, mode);
}
inline bool isConstant(SNode current)
{
switch (current.type) {
case lxConstantString:
case lxConstantWideStr:
case lxConstantSymbol:
case lxConstantInt:
case lxClassSymbol:
return true;
default:
return false;
}
}
inline bool isConstantList(SNode node)
{
bool constant = true;
SNode current = node.firstChild();
while (current != lxNone) {
if (current == lxMember) {
SNode object = current.findSubNodeMask(lxObjectMask);
if (!isConstant(object)) {
constant = false;
break;
}
}
current = current.nextNode();
}
return constant;
}
ObjectInfo Compiler :: compileCollection(SNode node, ExprScope& scope, ObjectInfo target, EAttr mode)
{
if (target.reference == V_OBJARRAY) {
target.reference = resolvePrimitiveArray(scope, scope.moduleScope->arrayTemplateReference, target.element, false);
}
else if (target.kind == okClass) {
// HOTFIX : class class reference should be turned into class one
IdentifierString className(scope.module->resolveReference(target.reference));
className.cut(getlength(className) - getlength(CLASSCLASS_POSTFIX), getlength(CLASSCLASS_POSTFIX));
target.reference = scope.moduleScope->mapFullReference(className);
}
else scope.raiseError(errInvalidOperation, node);
int counter = 0;
int size = _logic->defineStructSize(*scope.moduleScope, target.reference, 0);
// HOTFIX : comment out idle symbol
SNode dummyNode = node.prevNode(lxObjectMask);
if (dummyNode != lxNone)
dummyNode = lxIdle;
node.set(lxInitializing, 0);
// all collection memebers should be created before the collection itself
SNode current = node.findChild(lxExpression);
int index = 0;
while (current != lxNone) {
current.injectAndReplaceNode(lxMember, index++);
SNode memberNode = current.firstChild();
compileExpression(memberNode, scope, target.element, EAttr::eaNone);
analizeOperand(memberNode, scope, true, true, true);
current = current.nextNode();
counter++;
}
target.kind = okObject;
if (size < 0) {
SNode op = node.insertNode(lxCreatingStruct, counter * (-size));
op.appendNode(lxType, target.reference);
op.appendNode(lxSize, -size);
// writer.appendNode(lxSize);
// writer.inject(lxStruct, counter * (-size));
}
else {
if (EAttrs::test(mode, HINT_CONSTEXPR) && isConstantList(node)) {
ref_t reference = 0;
SymbolScope* owner = (SymbolScope*)scope.getScope(Scope::ScopeLevel::slSymbol);
if (owner) {
reference = mapConstant(scope.moduleScope, owner->reference);
}
else reference = scope.moduleScope->mapAnonymous();
node = lxConstantList;
node.setArgument(reference | mskConstArray);
node.appendNode(lxType, target.reference);
_writer.generateConstantList(node, scope.module, reference);
target.kind = okArrayConst;
target.param = reference;
}
else {
SNode op = node.insertNode(lxCreatingClass, counter);
op.appendNode(lxType, target.reference);
}
}
return target;
}
ObjectInfo Compiler :: compileRetExpression(SNode node, CodeScope& scope, EAttr mode)
{
bool autoMode = false;
ref_t targetRef = 0;
if (EAttrs::test(mode, HINT_ROOT)) {
targetRef = scope.getReturningRef();
if (targetRef == V_AUTO) {
autoMode = true;
targetRef = 0;
}
}
node.injectNode(lxExpression);
node = node.findChild(lxExpression);
ExprScope exprScope(&scope);
ObjectInfo info = compileExpression(node, exprScope, targetRef, mode);
if (autoMode) {
targetRef = resolveObjectReference(exprScope, info, true);
_logic->validateAutoType(*scope.moduleScope, targetRef);
scope.resolveAutoOutput(targetRef);
}
// // HOTFIX : implementing closure exit
// if (EAttrs::test(mode, HINT_ROOT)) {
// ObjectInfo retVar = scope.mapTerminal(RETVAL_VAR, false, EAttr::eaNone);
// if (retVar.kind != okUnknown) {
// writer.inject(lxAssigning);
// writer.insertNode(lxField, retVar.param);
// writer.closeNode();
// }
// }
int stackSafeAttr = 0;
if (info.kind == okSelfParam && !EAttrs::test(mode, HINT_DYNAMIC_OBJECT)) {
stackSafeAttr = 1;
}
node = node.parentNode();
analizeOperands(node, exprScope, stackSafeAttr, true);
return info;
}
ObjectInfo Compiler :: compileCatchOperator(SNode node, ExprScope& scope, ref_t operator_id)
{
SNode opNode = node.parentNode();
// writer.inject(lxExpression);
// writer.closeNode();
// SNode current = node.firstChild();
if (operator_id == FINALLY_OPERATOR_ID) {
SNode finalExpr = node;
finalExpr.injectAndReplaceNode(lxFinalblock);
SNode objNode = finalExpr.firstChild(lxObjectMask);
compileExpression(objNode, scope, 0, EAttr::eaNone);
// catch operation follow the finally operation
node = node.nextNode();
}
node.insertNode(lxResult);
compileOperation(node, scope, ObjectInfo(okObject), 0, EAttr::eaNone, false);
opNode.set(lxTrying, 0);
return ObjectInfo(okObject);
}
ObjectInfo Compiler :: compileAltOperator(SNode node, ExprScope& scope, ObjectInfo target)
{
SNode opNode = node.parentNode();
SNode targetNode = opNode.firstChild(lxObjectMask);
while (test(targetNode.type, lxOpScopeMask)) {
targetNode = targetNode.firstChild(lxObjectMask);
}
SNode altNode = node;
opNode.injectNode(lxAlt);
opNode.set(lxSeqExpression, 0);
SNode assignNode = opNode.insertNode(lxAssigning);
// allocate a temporal local
int tempLocal = scope.newTempLocal();
assignNode.appendNode(lxTempLocal, tempLocal);
SyntaxTree::copyNode(assignNode.appendNode(targetNode.type, targetNode.argument), targetNode);
targetNode.set(lxTempLocal, tempLocal);
SNode op = node.firstChild(lxOperatorMask);
altNode.insertNode(lxTempLocal, tempLocal);
compileMessage(op, scope, 0, target, EAttr::eaNone);
return ObjectInfo(okObject);
}
ref_t Compiler :: resolveReferenceTemplate(_CompileScope& scope, ref_t operandRef, bool declarationMode)
{
if (!operandRef) {
operandRef = scope.moduleScope->superReference;
}
else if (isPrimitiveRef(operandRef))
operandRef = resolvePrimitiveReference(scope, operandRef, 0, declarationMode);
List<SNode> parameters;
// HOTFIX : generate a temporal template to pass the type
SyntaxTree dummyTree;
SyntaxWriter dummyWriter(dummyTree);
dummyWriter.newNode(lxRoot);
dummyWriter.newNode(lxType, operandRef);
ident_t refName = scope.moduleScope->module->resolveReference(operandRef);
if (isWeakReference(refName)) {
dummyWriter.appendNode(lxReference, refName);
}
else dummyWriter.appendNode(lxGlobalReference, refName);
dummyWriter.closeNode();
dummyWriter.closeNode();
parameters.add(dummyTree.readRoot().firstChild());
return scope.moduleScope->generateTemplate(scope.moduleScope->refTemplateReference, parameters, scope.ns,
declarationMode, nullptr);
}
//ref_t Compiler :: resolveReferenceTemplate(Scope& scope, ref_t elementRef, bool declarationMode)
//{
// NamespaceScope* nsScope = (NamespaceScope*)scope.getScope(Scope::slNamespace);
//
// return resolveReferenceTemplate(*scope.moduleScope, elementRef, nsScope->ns.c_str(), declarationMode);
//}
ref_t Compiler :: resolvePrimitiveArray(_CompileScope& scope, ref_t templateRef, ref_t elementRef, bool declarationMode)
{
_ModuleScope* moduleScope = scope.moduleScope;
if (!elementRef)
elementRef = moduleScope->superReference;
// generate a reference class
List<SNode> parameters;
// HOTFIX : generate a temporal template to pass the type
SyntaxTree dummyTree;
SyntaxWriter dummyWriter(dummyTree);
dummyWriter.newNode(lxRoot);
dummyWriter.newNode(lxType, elementRef);
ident_t refName = moduleScope->module->resolveReference(elementRef);
if (isWeakReference(refName)) {
dummyWriter.appendNode(lxReference, refName);
}
else dummyWriter.appendNode(lxGlobalReference, refName);
dummyWriter.closeNode();
dummyWriter.closeNode();
parameters.add(dummyTree.readRoot().firstChild());
return moduleScope->generateTemplate(templateRef, parameters, scope.ns, declarationMode, nullptr);
}
ObjectInfo Compiler :: compileReferenceExpression(SNode node, ExprScope& scope, EAttr mode)
{
ObjectInfo objectInfo;
if (node == lxTempLocal) {
// HOTFIX : to support return value dispatching
objectInfo.kind = okLocal;
objectInfo.param = node.argument;
objectInfo.reference = node.findChild(lxType).argument;
}
else objectInfo = mapTerminal(node, scope, mode | HINT_REFEXPR);
ref_t operandRef = resolveObjectReference(scope, objectInfo, true, false);
if (!operandRef)
operandRef = scope.moduleScope->superReference;
ref_t targetRef = 0;
if (objectInfo.reference == V_WRAPPER) {
// if the reference is passed further - do nothing
targetRef = operandRef;
}
else {
// generate an reference class
targetRef = resolveReferenceTemplate(scope, operandRef, false);
SNode opNode = node.parentNode();
ObjectInfo retVal = convertObject(opNode, scope, targetRef, objectInfo, mode);
if (retVal.kind == okUnknown)
scope.raiseError(errInvalidOperation, node);
}
return ObjectInfo(okObject, 0, targetRef);
}
ObjectInfo Compiler :: compileVariadicUnboxing(SNode node, ExprScope& scope, EAttr mode)
{
ObjectInfo objectInfo = mapTerminal(node, scope, mode);
// HOTFIX : refresh node to see the changes
node.refresh();
analizeOperand(node, scope, false, true, true);
ref_t operandRef = resolveObjectReference(scope, objectInfo, false, false);
if (operandRef == V_ARGARRAY && EAttrs::test(mode, HINT_PARAMETER)) {
objectInfo.reference = V_UNBOXEDARGS;
node.injectAndReplaceNode(lxArgArray);
}
else if (_logic->isArray(*scope.moduleScope, operandRef)) {
objectInfo.reference = V_UNBOXEDARGS;
node.injectAndReplaceNode(lxArgArray, (ref_t)-1);
}
else scope.raiseError(errNotApplicable, node);
return objectInfo;
}
ObjectInfo Compiler :: compileCastingExpression(SNode node, ExprScope& scope, ObjectInfo target, EAttr mode)
{
ref_t targetRef = 0;
if (target.kind == okClass || target.kind == okClassSelf) {
targetRef = target.param;
}
else targetRef = resolveObjectReference(scope, target, true);
ObjectInfo retVal(okObject, 0, targetRef);
int paramCount = SyntaxTree::countNodeMask(node, lxObjectMask);
if (paramCount == 1) {
SNode current = node.nextNode();
// if it is a cast expression
ObjectInfo object = compileExpression(current, scope, /*targetRef*/0, mode);
SNode opNode = node.parentNode();
retVal = convertObject(opNode, scope, targetRef, object, mode);
if(retVal.kind == okUnknown)
scope.raiseError(errInvalidOperation, node);
}
else scope.raiseError(errInvalidOperation, node.parentNode());
return retVal;
}
ObjectInfo Compiler :: compileBoxingExpression(SNode node, ExprScope& scope, ObjectInfo target, EAttr mode)
{
ref_t targetRef = 0;
if (target.kind == okClass || target.kind == okClassSelf) {
targetRef = target.param;
}
EAttr paramsMode = EAttr::eaNone;
bool variadicOne = false;
bool inlineArg = false;
int paramCount = SyntaxTree::countNodeMask(node, lxObjectMask);
ref_t implicitSignatureRef = compileMessageParameters(node, scope, paramsMode, variadicOne, inlineArg);
if (inlineArg)
scope.raiseError(errInvalidOperation, node);
SNode exprNode = node.parentNode();
ref_t messageRef = overwriteArgCount(scope.moduleScope->constructor_message, paramCount + 1);
int stackSafeAttr = 0;
if (target.reference == V_OBJARRAY && paramCount == 1) {
// HOTFIX : if it is an array creation
ref_t roperand = 0;
scope.module->resolveSignature(implicitSignatureRef, &roperand);
int operationType = _logic->resolveNewOperationType(*scope.moduleScope, targetRef, roperand);
if (operationType != 0) {
// if it is a primitive operation
_logic->injectNewOperation(exprNode, *scope.moduleScope, operationType, targetRef, target.element);
// HOTFIX : remove class symbol - the array will be created directly
SNode classNode = exprNode.firstChild(lxObjectMask);
classNode = lxIdle;
// mark the argument as a stack safe
analizeOperands(exprNode, scope, 1, true);
return ObjectInfo(okObject, 0, target.reference, target.element, 0);
}
else scope.raiseError(errInvalidOperation, node.parentNode());
}
else messageRef = resolveMessageAtCompileTime(target, scope, messageRef, implicitSignatureRef, false, stackSafeAttr);
bool dummy = false;
ObjectInfo retVal = compileMessage(exprNode, scope, target, messageRef, mode | HINT_SILENT, stackSafeAttr, dummy);
if (targetRef && !resolveObjectReference(scope, retVal, false)) {
scope.raiseError(errDefaultConstructorNotFound, exprNode);
}
// HOTFIX : set the correct template reference (weak template one) if required
retVal.reference = targetRef;
return retVal;
}
ObjectInfo Compiler :: compileOperation(SNode& node, ExprScope& scope, ObjectInfo objectInfo, ref_t expectedRef,
EAttr mode, bool propMode)
{
SNode current = node.firstChild(lxOperatorMask);
switch (current.type) {
case lxCollection:
objectInfo = compileCollection(current, scope, objectInfo, mode);
break;
case lxMessage:
if (EAttrs::test(mode, HINT_LOOP)) {
EAttrs subMode(mode, HINT_LOOP);
objectInfo = compileMessage(current, scope, expectedRef, objectInfo, subMode);
SNode parentNode = current.parentNode().parentNode();
if (parentNode == lxSeqExpression) {
// HOTFIX : to correctly unbox the arguments for every loop cycle
parentNode.injectAndReplaceNode(lxLooping);
}
else current.parentNode().injectAndReplaceNode(lxLooping);
}
else if (propMode) {
objectInfo = compilePropAssigning(current, scope, objectInfo);
}
else objectInfo = compileMessage(current, scope, expectedRef, objectInfo, mode);
break;
case lxNewOperation:
objectInfo = compileBoxingExpression(current, scope, objectInfo, mode);
break;
case lxCastOperation:
objectInfo = compileCastingExpression(current, scope, objectInfo, mode);
break;
// case lxTypecast:
// objectInfo = compileBoxingExpression(writer, current, scope, objectInfo, mode);
// break;
case lxAssign:
objectInfo = compileAssigning(current, scope, objectInfo, current.argument == -1);
break;
case lxArrOperator:
if (propMode) {
current.setArgument(SET_REFER_OPERATOR_ID);
}
case lxOperator:
objectInfo = compileOperator(current, scope, objectInfo, mode);
break;
// case lxWrapping:
// objectInfo = compileWrapping(writer, current, scope, objectInfo, EAttrs::test(mode, HINT_CALL_MODE));
// break;
}
node.refresh();
return objectInfo;
}
ref_t Compiler :: mapTemplateAttribute(SNode node, Scope& scope)
{
SNode terminalNode = node.firstChild(lxTerminalMask);
IdentifierString templateName(terminalNode.identifier());
int paramCounter = 0;
SNode current = node.findChild(lxType);
while (current != lxNone) {
if (current.compare(lxType, lxTemplateParam)) {
paramCounter++;
}
else scope.raiseError(errInvalidOperation, node);
current = current.nextNode();
}
templateName.append('#');
templateName.appendInt(paramCounter);
// NOTE : check it in declararion mode - we need only reference
return resolveTypeIdentifier(scope, templateName.c_str(), terminalNode.type, true, false);
}
//ref_t Compiler :: mapTypeAttribute(SNode member, Scope& scope)
//{
// ref_t ref = member.argument ? member.argument : resolveImplicitIdentifier(scope, member.firstChild(lxTerminalMask));
// if (!ref)
// scope.raiseError(errUnknownClass, member);
//
// return ref;
//}
SNode Compiler :: injectAttributeIdentidier(SNode current, Scope& scope)
{
ident_t refName = scope.module->resolveReference(current.argument);
SNode terminalNode = current.firstChild(lxTerminalMask);
if (terminalNode != lxNone) {
if (isWeakReference(refName)) {
terminalNode.set(lxReference, refName);
}
else terminalNode.set(lxGlobalReference, refName);
}
return terminalNode;
}
void Compiler :: compileTemplateAttributes(SNode current, List<SNode>& parameters, Scope& scope, bool declarationMode)
{
// if (current.compare(lxIdentifier, lxReference))
// current = current.nextNode();
//
// ExpressionAttributes attributes;
while (current != lxNone) {
if (current.compare(lxType, lxArrayType)) {
ref_t typeRef = current.argument;
if (!typeRef || typeRef == V_TEMPLATE) {
typeRef = resolveTypeAttribute(current, scope, declarationMode, false);
current.set(lxType, typeRef);
SNode terminalNode = injectAttributeIdentidier(current, scope);
}
// SNode targetNode = current.firstChild();
// bool templateOne = targetNode.argument == V_TEMPLATE;
// targetNode.set(lxTarget, typeRef);
// // HOTFIX : inject the reference and comment the target nodes out
// if (templateOne) {
// do {
// terminalNode = terminalNode.nextNode();
// if (terminalNode == lxTypeAttribute) {
// // NOTE : Type attributes should be removed to correctly compile the array of templates
// terminalNode = lxIdle;
// }
// } while (terminalNode != lxNone);
// }
//
parameters.add(/*targetNode*/current);
}
current = current.nextNode();
}
}
//bool Compiler :: isTemplateParameterDeclared(SNode node, Scope& scope)
//{
// SNode current = node.firstChild();
// if (current == lxIdentifier)
// current = current.nextNode();
//
// while (current != lxNone) {
// if (current == lxTarget) {
// ref_t arg = mapTypeAttribute(current, scope);
// if (!scope.moduleScope->isClassDeclared(arg))
// return 0;
// }
//
// current = current.nextNode();
// }
//
// return true;
//}
ref_t Compiler :: resolveTemplateDeclarationUnsafe(SNode node, Scope& scope, bool declarationMode)
{
// generate an reference class - inner implementation
List<SNode> parameters;
compileTemplateAttributes(node.firstChild(), parameters, scope, declarationMode);
ref_t templateRef = mapTemplateAttribute(node, scope);
if (!templateRef)
scope.raiseError(errInvalidHint, node);
SNode terminalNode = node.firstChild(lxTerminalMask);
if (terminalNode != lxNone) {
SNode sourceNode = terminalNode.findChild(lxTemplateSource);
if (sourceNode == lxNone) {
sourceNode = terminalNode.appendNode(lxTemplateSource);
SNode col = terminalNode.findChild(lxCol);
sourceNode.appendNode(col.type, col.argument);
SNode row = terminalNode.findChild(lxRow);
sourceNode.appendNode(row.type, row.argument);
NamespaceScope* nsScope = (NamespaceScope*)scope.getScope(Scope::ScopeLevel::slNamespace);
sourceNode.appendNode(lxSourcePath, nsScope->sourcePath.c_str());
}
parameters.add(sourceNode);
}
NamespaceScope* ns = (NamespaceScope*)scope.getScope(Scope::ScopeLevel::slNamespace);
return scope.moduleScope->generateTemplate(templateRef, parameters, ns->nsName.c_str(), declarationMode, nullptr);
}
ref_t Compiler :: resolveTemplateDeclaration(SNode node, Scope& scope, bool declarationMode)
{
// generate an reference class - safe implementation
if (declarationMode) {
// HOTFIX : clone the type attribute tree to prevent it from modifications
SyntaxTree dummyTree;
SyntaxWriter dummyWriter(dummyTree);
dummyWriter.newNode(node.type);
SyntaxTree::copyNode(dummyWriter, node);
dummyWriter.closeNode();
SNode dummyNode = dummyTree.readRoot();
return resolveTemplateDeclarationUnsafe(dummyTree.readRoot(), scope, declarationMode);
}
else return resolveTemplateDeclarationUnsafe(node, scope, declarationMode);
}
ref_t Compiler :: resolveTypeAttribute(SNode node, Scope& scope, bool declarationMode, bool allowRole)
{
ref_t typeRef = 0;
if (test(node.type, lxTerminalMask)) {
typeRef = resolveTypeIdentifier(scope, node, declarationMode, allowRole);
}
else if (node == lxArrayType) {
typeRef = resolvePrimitiveArray(scope,
scope.moduleScope->arrayTemplateReference,
resolveTypeAttribute(node.firstChild(), scope, declarationMode, false), declarationMode);
}
else {
typeRef = node.argument;
if (typeRef == V_TEMPLATE) {
typeRef = resolveTemplateDeclaration(node, scope, declarationMode);
}
else if (!typeRef)
typeRef = resolveTypeIdentifier(scope, node.firstChild(lxTerminalMask), declarationMode, allowRole);
}
validateType(scope, node, typeRef, declarationMode, allowRole);
return typeRef;
}
EAttr Compiler :: recognizeExpressionAttributes(SNode& current, Scope& scope, ref_t& typeRef, bool& newVariable)
{
EAttrs exprAttr = EAttr::eaNone;
// HOTFIX : skip bookmark reference
if (current == lxBookmarkReference)
current = current.nextNode();
while (current == lxAttribute) {
int value = current.argument;
if (!_logic->validateExpressionAttribute(value, exprAttr, newVariable))
scope.raiseError(errInvalidHint, current);
if (value == V_AUTO)
typeRef = value;
current = current.nextNode();
}
return exprAttr;
}
EAttr Compiler :: declareExpressionAttributes(SNode& current, ExprScope& scope, EAttr)
{
bool newVariable = false;
ref_t typeRef = 0;
EAttrs exprAttr = recognizeExpressionAttributes(current, scope, typeRef, newVariable);
if (exprAttr.testAndExclude(EAttr::eaIgnoreDuplicates)) {
scope.ignoreDuplicates = true;
}
if (current.compare(lxType, lxArrayType) && test(current.nextNode(), lxTerminalMask)) {
if (typeRef == 0) {
typeRef = resolveTypeAttribute(current, scope, false, false);
newVariable = true;
}
else scope.raiseError(errIllegalOperation, current);
current = current.nextNode();
}
if (newVariable) {
if (!typeRef)
typeRef = scope.moduleScope->superReference;
// COMPILER MAGIC : make possible to ignore duplicates - used for some code templates
if (scope.ignoreDuplicates && scope.checkLocal(current.identifier())) {
// ignore duplicates
}
else declareVariable(current, scope, typeRef/*, dynamicSize*/, !exprAttr.testany(HINT_REFOP));
}
return exprAttr;
}
//inline SNode findLeftMostNode(SNode current, LexicalType type)
//{
// if (current == lxExpression) {
// return findLeftMostNode(current.firstChild(), type);
// }
// else return current;
//}
ObjectInfo Compiler :: compileRootExpression(SNode node, CodeScope& scope, ref_t targetRef, EAttr mode)
{
// renaming top expression into sequence one to be used in root boxing routines
node.set(lxSeqExpression, (ref_t)-1);
// inject a root expression
node = node.injectNode(lxExpression);
ExprScope exprScope(&scope);
ObjectInfo retVal = compileExpression(node, exprScope, targetRef, mode);
node = node.parentNode();
int stackSafeAttr = EAttrs::test(mode, HINT_DYNAMIC_OBJECT) ? 0 : 1;
analizeOperands(node, exprScope, stackSafeAttr, true);
return retVal;
}
void Compiler :: recognizeTerminal(SNode& terminal, ObjectInfo object, ExprScope& scope, EAttr mode)
{
if (EAttrs::test(mode, HINT_VIRTUALEXPR))
return;
// injecting an expression node
terminal.injectAndReplaceNode(lxExpression);
if (!EAttrs::test(mode, HINT_NODEBUGINFO))
terminal.insertNode(lxBreakpoint, dsStep);
switch (object.kind) {
case okUnknown:
scope.raiseError(errUnknownObject, terminal);
break;
case okSymbol:
// scope.moduleScope->validateReference(terminal, object.param | mskSymbolRef);
terminal.set(lxSymbolReference, object.param);
break;
case okClass:
case okClassSelf:
terminal.set(lxClassSymbol, object.param);
break;
case okExtension:
if (!EAttrs::test(mode, HINT_CALLOP)) {
scope.raiseWarning(WARNING_LEVEL_3, wrnExplicitExtension, terminal);
}
case okConstantSymbol:
case okSingleton:
terminal.set(lxConstantSymbol, object.param);
break;
case okLiteralConstant:
terminal.set(lxConstantString, object.param);
break;
case okWideLiteralConstant:
terminal.set(lxConstantWideStr, object.param);
break;
case okCharConstant:
terminal.set(lxConstantChar, object.param);
break;
case okIntConstant:
case okUIntConstant:
terminal.set(lxConstantInt, object.param);
terminal.appendNode(lxIntValue, object.extraparam);
break;
case okLongConstant:
terminal.set(lxConstantLong, object.param);
break;
case okRealConstant:
terminal.set(lxConstantReal, object.param);
break;
case okArrayConst:
terminal.set(lxConstantList, object.param);
break;
case okParam:
case okLocal:
setParamTerminal(terminal, scope, object, mode, lxLocal);
break;
case okParamField:
setParamFieldTerminal(terminal, scope, object, mode, lxLocal);
break;
case okSelfParam:
// if (EAttrs::test(mode, HINT_RETEXPR))
// mode = mode | HINT_NOBOXING;
setParamTerminal(terminal, scope, object, mode, lxSelfLocal);
break;
case okSuper:
setSuperTerminal(terminal, scope, object, mode, lxSelfLocal);
break;
case okReadOnlyField:
case okField:
case okOuter:
case okOuterSelf:
terminal.set(lxFieldExpression, 0);
terminal.appendNode(lxSelfLocal, 1);
terminal.appendNode(lxField, object.param);
break;
case okStaticField:
// if ((int)object.param < 0) {
// // if it is a normal static field - field expression should be used
// writer.newNode(lxFieldExpression, 0);
// writer.appendNode(lxClassRefField, 1);
// writer.appendNode(lxStaticField, object.param);
// }
// if it is a sealed static field
/*else */terminal.set(lxStaticField, object.param);
break;
// case okClassStaticField:
// writer.newNode(lxFieldExpression, 0);
// if (!object.param) {
// writer.appendNode(lxSelfLocal, 1);
// }
// else writer.appendNode(lxClassSymbol, object.param);
// writer.appendNode(lxStaticField, object.extraparam);
// break;
case okStaticConstantField:
if ((int)object.param < 0) {
terminal.set(lxFieldExpression, 0);
terminal.appendNode(lxSelfLocal, 1);
terminal.appendNode(lxClassRef, scope.getClassRefId());
terminal.appendNode(lxStaticConstField, object.param);
}
else terminal.set(lxStaticField, object.param);
break;
case okClassStaticConstantField:
if ((int)object.param < 0) {
terminal.set(lxFieldExpression, 0);
terminal.appendNode(lxSelfLocal, 1);
terminal.appendNode(lxStaticConstField, object.param);
}
else throw InternalError("Not yet implemented"); // !! temporal
break;
case okOuterField:
case okOuterReadOnlyField:
terminal.set(lxFieldExpression, 0);
terminal.appendNode(lxSelfLocal, 1);
terminal.appendNode(lxField, object.param);
terminal.appendNode(lxField, object.extraparam);
break;
// case okOuterStaticField:
// writer.newNode(lxFieldExpression, 0);
// writer.newNode(lxFieldExpression, 0);
// writer.appendNode(lxField, object.param);
// //writer.appendNode(lxClassRefAttr, object.param);
// writer.closeNode();
// writer.appendNode(lxStaticField, object.extraparam);
// break;
case okFieldAddress:
case okReadOnlyFieldAddress:
terminal.set(lxFieldExpression, 0);
terminal.appendNode(lxSelfLocal, 1);
if (object.param || (!EAttrs::test(mode, HINT_PROP_MODE)
&& (_logic->defineStructSize(*scope.moduleScope, object.reference, 0) & 3) != 0))
{
// if it a field address (except the first one, which size is 4-byte aligned)
terminal.appendNode(lxFieldAddress, object.param);
// the field address expression should always be boxed (either local or dynamic)
mode = EAttrs(mode, HINT_NOBOXING);
}
if (isPrimitiveArrRef(object.reference)) {
int size = defineFieldSize(scope, object.param);
setVariableTerminal(terminal, scope, object, mode, lxFieldExpression, size);
}
else setVariableTerminal(terminal, scope, object, mode, lxFieldExpression);
break;
case okLocalAddress:
setVariableTerminal(terminal, scope, object, mode, lxLocalAddress);
break;
case okMessage:
setVariableTerminal(terminal, scope, object, mode, lxLocalAddress);
break;
case okNil:
terminal.set(lxNil, 0/*object.param*/);
break;
case okMessageConstant:
terminal.set(lxMessageConstant, object.param);
break;
case okExtMessageConstant:
terminal.set(lxExtMessageConstant, object.param);
break;
case okMessageNameConstant:
terminal.set(lxSubjectConstant, object.param);
break;
////// case okBlockLocal:
////// terminal.set(lxBlockLocal, object.param);
////// break;
case okParams:
{
ref_t r = resolvePrimitiveReference(scope, object.reference, object.element, false);
if (!r)
throw InternalError("Cannot resolve variadic argument template");
setParamsTerminal(terminal, scope, object, mode, r);
break;
}
// case okObject:
// writer.newNode(lxResult, 0);
// break;
// case okConstantRole:
// writer.newNode(lxConstantSymbol, object.param);
// break;
case okExternal:
return;
case okInternal:
terminal.set(lxInternalRef, object.param);
return;
//case okPrimitive:
//case okPrimCollection:
//{
// terminal.set(lxSeqExpression);
// SNode exprNode = terminal.appendNode(object.kind == okPrimitive ? lxCreatingStruct : lxCreatingClass, object.param);
// // writer.newBookmark();
// if (EAttrs::test(mode, HINT_AUTOSIZE) && !writeSizeArgument(exprNode))
// scope.raiseError(errInvalidOperation, terminal);
// // writer.appendNode();
// // writer.inject(lxSeqExpression);
// // writer.removeBookmark();
// break;
//}
}
//
// writeTarget(writer, resolveObjectReference(scope, object, false), object.element);
//
// writeTerminalInfo(writer, terminal);
}
ObjectInfo Compiler :: mapIntConstant(ExprScope& scope, int integer)
{
String<char, 20> s;
// convert back to string as a decimal integer
s.appendHex(integer);
return ObjectInfo(okIntConstant, scope.module->mapConstant((const char*)s), V_INT32, 0, integer);
}
ObjectInfo Compiler :: mapRealConstant(ExprScope& scope, double val)
{
String<char, 30> s;
s.appendDouble(val);
// HOT FIX : to support 0r constant
if (s.Length() == 1) {
s.append(".0");
}
return ObjectInfo(okRealConstant, scope.moduleScope->module->mapConstant((const char*)s), V_REAL64);
}
ObjectInfo Compiler :: mapMetaField(ident_t token)
{
if (token.compare(META_INFO_NAME)) {
return ObjectInfo(okMetaField, ClassAttribute::caInfo);
}
else return ObjectInfo();
}
ObjectInfo Compiler :: mapTerminal(SNode terminal, ExprScope& scope, EAttr mode)
{
// EAttrs mode(modeAttr);
ident_t token = terminal.identifier();
ObjectInfo object;
if (EAttrs::testany(mode, HINT_INTERNALOP | HINT_MEMBER | HINT_METAFIELD | HINT_EXTERNALOP | HINT_FORWARD
| HINT_MESSAGEREF | HINT_SUBJECTREF))
{
bool invalid = false;
if (EAttrs::test(mode, HINT_INTERNALOP)) {
if (terminal == lxReference) {
object = ObjectInfo(okInternal, scope.module->mapReference(token), V_INT32);
}
else if (terminal == lxGlobalReference) {
object = ObjectInfo(okInternal, scope.moduleScope->mapFullReference(token), V_INT32);
}
else invalid = true;
}
else if (EAttrs::test(mode, HINT_EXTERNALOP)) {
object = ObjectInfo(okExternal, 0, V_INT32);
}
else if (EAttrs::test(mode, HINT_MEMBER)) {
object = scope.mapMember(token);
}
else if (EAttrs::test(mode, HINT_METAFIELD)) {
object = mapMetaField(token);
}
else if (EAttrs::test(mode, HINT_FORWARD)) {
IdentifierString forwardName(FORWARD_MODULE, "'", token);
object = scope.mapTerminal(forwardName.ident(), true, EAttr::eaNone);
}
else if (EAttrs::test(mode, HINT_MESSAGEREF)) {
// HOTFIX : if it is an extension message
object = compileMessageReference(terminal, scope);
}
else if (EAttrs::test(mode, HINT_SUBJECTREF)) {
object = compileSubjectReference(terminal, scope, mode);
}
if (invalid)
scope.raiseError(errInvalidOperation, terminal);
}
else {
switch (terminal.type) {
case lxLiteral:
object = ObjectInfo(okLiteralConstant, scope.moduleScope->module->mapConstant(token), scope.moduleScope->literalReference);
break;
case lxWide:
object = ObjectInfo(okWideLiteralConstant, scope.moduleScope->module->mapConstant(token), scope.moduleScope->wideReference);
break;
case lxCharacter:
object = ObjectInfo(okCharConstant, scope.moduleScope->module->mapConstant(token), scope.moduleScope->charReference);
break;
case lxInteger:
{
int integer = token.toInt();
if (errno == ERANGE)
scope.raiseError(errInvalidIntNumber, terminal);
object = mapIntConstant(scope, integer);
break;
}
case lxLong:
{
String<char, 30> s("_"); // special mark to tell apart from integer constant
s.append(token, getlength(token) - 1);
token.toLongLong(10, 1);
if (errno == ERANGE)
scope.raiseError(errInvalidIntNumber, terminal);
object = ObjectInfo(okLongConstant, scope.moduleScope->module->mapConstant((const char*)s), V_INT64);
break;
}
case lxHexInteger:
{
int integer = token.toULong(16);
if (errno == ERANGE)
scope.raiseError(errInvalidIntNumber, terminal);
object = mapIntConstant(scope, integer);
break;
}
case lxReal:
{
double val = token.toDouble();
if (errno == ERANGE)
scope.raiseError(errInvalidIntNumber, terminal);
object = mapRealConstant(scope, val);
break;
}
case lxGlobalReference:
object = scope.mapGlobal(token.c_str());
break;
case lxMetaConstant:
// NOTE : is not allowed to be used outside const initialization
scope.raiseError(errIllegalOperation, terminal);
break;
case lxExplicitConst:
{
// try to resolve explicit constant
size_t len = getlength(token);
IdentifierString action(token + len - 1);
action.append(CONSTRUCTOR_MESSAGE);
ref_t dummyRef = 0;
ref_t actionRef = scope.module->mapAction(action, scope.module->mapSignature(&scope.moduleScope->literalReference, 1, false), dummyRef);
action.copy(token, len - 1);
object = ObjectInfo(okExplicitConstant, scope.moduleScope->module->mapConstant(action), 0, 0, actionRef);
break;
}
case lxSubjectRef:
object = compileSubjectReference(terminal, scope, mode);
break;
default:
object = scope.mapTerminal(token, terminal == lxReference, mode & HINT_SCOPE_MASK);
break;
}
}
if (object.kind == okExplicitConstant) {
// replace an explicit constant with the appropriate object
recognizeTerminal(terminal, ObjectInfo(okLiteralConstant, object.param), scope, mode);
ref_t messageRef = encodeMessage(object.extraparam, 2, 0);
NamespaceScope* nsScope = (NamespaceScope*)scope.getScope(Scope::ScopeLevel::slNamespace);
Pair<ref_t, ref_t> constInfo = nsScope->extensions.get(messageRef);
if (constInfo.value1 != 0) {
ref_t signRef = 0;
scope.module->resolveAction(object.extraparam, signRef);
if (!_logic->injectConstantConstructor(terminal, *scope.moduleScope, *this, constInfo.value1, messageRef))
scope.raiseError(errInvalidConstant, terminal);
}
else scope.raiseError(errInvalidConstant, terminal);
object = ObjectInfo(okObject, constInfo.value1);
}
else if (object.kind == okUnknown) {
scope.raiseError(errUnknownObject, terminal);
}
else recognizeTerminal(terminal, object, scope, mode);
return object;
}
ObjectInfo Compiler :: mapObject(SNode node, ExprScope& scope, EAttr exprMode)
{
EAttrs mode(exprMode & HINT_OBJECT_MASK);
ObjectInfo result;
SNode current = node.firstChild();
if (current.compare(lxAttribute, lxType, lxArrayType, lxBookmarkReference)) {
mode.include(declareExpressionAttributes(current, scope, exprMode));
// if (targetMode.testAndExclude(HINT_INLINEARGMODE)) {
// noPrimMode = true;
// inlineArgMode = true;
// }
}
if (mode.testAndExclude(HINT_NEWOP)) {
if (current == lxArrayType) {
// if it is an array creation
result.kind = okClass;
result.element = resolveTypeAttribute(current.firstChild(), scope, false, false);
result.param = resolvePrimitiveArray(scope,
scope.moduleScope->arrayTemplateReference, result.element, false);
result.reference = V_OBJARRAY;
recognizeTerminal(current, result, scope, mode);
}
else if (current == lxType) {
ref_t typeRef = resolveTypeAttribute(current, scope, false, false);
result = mapClassSymbol(scope, typeRef);
recognizeTerminal(current, result, scope, mode);
}
else result = mapTerminal(current, scope, mode);
SNode mssgNode = node.findChild(lxMessage, lxCollection);
if (mssgNode == lxMessage) {
mssgNode.set(lxNewOperation, CONSTRUCTOR_MESSAGE);
}
else if (mssgNode == lxNone)
scope.raiseError(errInvalidOperation, node);
}
else if (mode.testAndExclude(HINT_CASTOP)) {
ref_t typeRef = resolveTypeAttribute(current, scope, false, false);
result = mapClassSymbol(scope, typeRef);
SNode mssgNode = node.findChild(lxMessage);
if (mssgNode != lxNone) {
mssgNode.set(lxCastOperation, 0);
}
else scope.raiseError(errInvalidOperation, node);
}
else if (mode.testAndExclude(HINT_CLASSREF)) {
ref_t typeRef = resolveTypeAttribute(current, scope, false, false);
result = mapClassSymbol(scope, typeRef);
recognizeTerminal(current, result, scope, mode);
}
else if (mode.testAndExclude(HINT_REFOP)) {
result = compileReferenceExpression(current, scope, mode);
}
else if (mode.testAndExclude(HINT_PARAMSOP)) {
result = compileVariadicUnboxing(current, scope, mode);
}
else if (mode.testAndExclude(HINT_YIELD_EXPR)) {
compileYieldExpression(current, scope, mode);
}
else if (mode.test(HINT_LAZY_EXPR)) {
result = compileClosure(node, scope, mode);
}
else {
switch (current.type) {
// case lxCollection:
// result = compileCollection(writer, node, scope, ObjectInfo(okObject, 0, V_OBJARRAY, scope.moduleScope->superReference, 0));
// break;
case lxCode:
current = lxCodeExpression;
case lxCodeExpression:
{
if (EAttrs::test(exprMode, HINT_EXTERNALOP)) {
current.injectAndReplaceNode(lxExternFrame);
current = current.firstChild(lxObjectMask);
}
bool withRetStatement = false;
result = compileSubCode(current, scope, false, withRetStatement);
scope.setCodeRetStatementFlag(withRetStatement);
break;
}
case lxType:
if (mode.testAndExclude(HINT_MESSAGEREF)) {
// HOTFIX : if it is an extension message
result = compileMessageReference(current, scope);
recognizeTerminal(current, result, scope, mode);
}
else result = compileTypeSymbol(current, scope, mode);
break;
case lxNestedClass:
result = compileClosure(current, scope, mode/* & HINT_CLOSURE_MASK*/);
break;
case lxClosureExpr:
result = compileClosure(current, scope, mode/* & HINT_CLOSURE_MASK*/);
break;
case lxExpression:
result = compileExpression(current, scope, 0, mode);
break;
case lxSwitching:
compileSwitch(current, scope);
result = ObjectInfo(okObject);
break;
case lxIdle:
result = ObjectInfo(okUnknown);
break;
default:
result = mapTerminal(current, scope, mode);
break;
}
}
if (mode.test(HINT_INLINEARGMODE)) {
result.element = result.reference;
result.reference = V_INLINEARG;
}
return result;
}
inline bool isAssigmentOp(SNode node)
{
return node == lxAssign/* || (node == lxOperator && node.argument == -1)*/;
}
inline bool isCallingOp(SNode node)
{
return node == lxMessage;
}
ObjectInfo Compiler :: compileExpression(SNode& node, ExprScope& scope, ref_t targetRef, EAttr mode)
{
EAttrs objMode(mode, HINT_PROP_MODE);
SNode operationNode = node.firstChild(lxOperatorMask);
if (isAssigmentOp(operationNode)) {
objMode.include(HINT_PROP_MODE);
mode = mode | HINT_PROP_MODE;
}
else if (isCallingOp(operationNode)) {
if (EAttrs::testany(mode, HINT_NOBOXING)) {
objMode.exclude(HINT_NOBOXING);
mode = EAttrs::exclude(mode, HINT_NOBOXING);
}
objMode.include(HINT_CALLOP);
}
return compileExpression(node, scope,
mapObject(node, scope, objMode), targetRef, mode);
}
ObjectInfo Compiler :: compileExpression(SNode& node, ExprScope& scope, ObjectInfo objectInfo, ref_t exptectedRef, EAttr modeAttrs)
{
bool noPrimMode = EAttrs::test(modeAttrs, HINT_NOPRIMITIVES);
bool noUnboxing = EAttrs::test(modeAttrs, HINT_NOUNBOXING);
// bool boxingMode = false;
EAttrs mode(modeAttrs, HINT_OBJECT_MASK);
ObjectInfo retVal = compileOperation(node, scope, objectInfo, exptectedRef, mode, EAttrs::test(modeAttrs, HINT_PROP_MODE));
ref_t sourceRef = resolveObjectReference(scope, retVal, false/*, exptectedRef*/);
if (!exptectedRef && isPrimitiveRef(sourceRef) && noPrimMode) {
if (objectInfo.reference == V_INLINEARG && EAttrs::test(modeAttrs, HINT_PARAMETER)) {
// HOTFIX : do not resolve inline argument
}
else exptectedRef = resolvePrimitiveReference(scope, sourceRef, objectInfo.element, false);
}
if (exptectedRef) {
if (noUnboxing)
mode = mode | HINT_NOUNBOXING;
retVal = convertObject(node, scope, exptectedRef, retVal, mode);
if (retVal.kind == okUnknown) {
scope.raiseError(errInvalidOperation, node);
}
}
return retVal;
}
ObjectInfo Compiler :: compileSubCode(SNode codeNode, ExprScope& scope, bool branchingMode, bool& withRetStatement)
{
CodeScope* codeScope = (CodeScope*)scope.getScope(Scope::ScopeLevel::slCode);
CodeScope subScope(codeScope);
subScope.parentCallNode = scope.callNode;
if (branchingMode && codeNode == lxExpression) {
//HOTFIX : inline branching operator
codeNode.injectAndReplaceNode(lxCode);
compileRootExpression(codeNode.firstChild(), subScope, 0, HINT_ROOT | HINT_DYNAMIC_OBJECT);
}
else compileCode(codeNode, subScope);
// preserve the allocated space
subScope.syncStack(codeScope);
withRetStatement = subScope.withRetStatement;
return ObjectInfo(okObject);
}
void Compiler :: compileEmbeddableRetExpression(SNode node, ExprScope& scope)
{
node.injectNode(lxExpression);
node = node.findChild(lxExpression);
node.injectNode(lxExpression);
ObjectInfo retVar = scope.mapTerminal(RETVAL_ARG, false, HINT_PROP_MODE);
SNode refNode = node.insertNode(lxVirtualReference);
recognizeTerminal(refNode, retVar, scope, HINT_NOBOXING);
compileAssigning(node.firstChild(), scope, retVar, false);
}
ObjectInfo Compiler :: compileCode(SNode node, CodeScope& scope)
{
ObjectInfo retVal;
bool needVirtualEnd = true;
SNode current = node.firstChild();
while (current != lxNone) {
switch(current) {
case lxExpression:
compileRootExpression(current, scope, 0, HINT_ROOT);
break;
case lxReturning:
{
needVirtualEnd = false;
//if (test(scope.getMessageID(), SPECIAL_MESSAGE))
// scope.raiseError(errIllegalOperation, current);
if (scope.withEmbeddableRet()) {
ExprScope exprScope(&scope);
retVal = scope.mapTerminal(SELF_VAR, false, EAttr::eaNone);
compileEmbeddableRetExpression(current, exprScope);
current.injectAndReplaceNode(lxSeqExpression);
SNode retNode = current.appendNode(lxReturning);
retNode.appendNode(lxExpression);
SNode objNode = retNode.firstChild();
recognizeTerminal(objNode, retVal, exprScope, HINT_NODEBUGINFO | HINT_NOBOXING);
}
else retVal = compileRetExpression(current, scope, HINT_ROOT/* | HINT_RETEXPR*/);
scope.withRetStatement = true;
break;
}
case lxCode:
{
// compile sub code
ExprScope exprScope(&scope);
bool withRetStatement = false;
compileSubCode(current, exprScope, false, withRetStatement);
exprScope.setCodeRetStatementFlag(withRetStatement);
break;
}
case lxEOP:
needVirtualEnd = false;
current.injectNode(lxTerminalMask); // injecting virtual terminal token
current.insertNode(lxBreakpoint, dsEOP);
break;
}
// scope.freeSpace();
current = current.nextNode();
}
if (needVirtualEnd) {
SNode eop = node.appendNode(lxEOP);
eop.insertNode(lxBreakpoint, dsVirtualEnd);
}
return retVal;
}
void Compiler :: compileExternalArguments(SNode node, ExprScope& scope, SNode callNode)
{
SNode current = node.firstChild(lxObjectMask);
while (current != lxNone && current != callNode) {
SNode objNode = current;
ref_t typeRef = current.findChild(lxType).argument;
if (objNode == lxExpression) {
objNode = current.findSubNodeMask(lxObjectMask);
}
if (objNode == lxConstantInt) {
// move constant directly to ext call
SyntaxTree::copyNode(objNode, callNode.appendNode(lxExtIntConst));
current = lxIdle;
}
else {
if (objNode.compare(lxBoxableExpression, lxCondBoxableExpression)) {
if (!typeRef)
typeRef = objNode.findChild(lxType).argument;
analizeOperand(objNode, scope, false, false, false);
objNode = objNode.findSubNodeMask(lxObjectMask);
}
if (objNode.type != lxSymbolReference && (!test(objNode.type, lxOpScopeMask) || objNode == lxFieldExpression)) {
if (_logic->isCompatible(*scope.moduleScope, V_DWORD, typeRef, true)
&& !_logic->isVariable(*scope.moduleScope, typeRef))
{
// if it is a integer variable
SyntaxTree::copyNode(objNode, callNode
.appendNode(lxExtIntArg)
.appendNode(objNode.type, objNode.argument));
}
else SyntaxTree::copyNode(objNode, callNode
.appendNode(objNode.type, objNode.argument));
current = lxIdle;
}
else scope.raiseError(errInvalidOperation, current); // !! temporal
}
current = current.nextNode(lxObjectMask);
}
}
ObjectInfo Compiler :: compileExternalCall(SNode node, ExprScope& scope, ref_t expectedRef, EAttr)
{
ObjectInfo retVal(okExternal);
_ModuleScope* moduleScope = scope.moduleScope;
bool stdCall = false;
bool apiCall = false;
SNode targetNode = node.prevNode();
ident_t dllAlias = targetNode.findSubNodeMask(lxTerminalMask).identifier();
ident_t functionName = node.firstChild(lxTerminalMask).identifier();
ident_t dllName = NULL;
if (dllAlias.compare(RT_MODULE)) {
// if run time dll is used
dllName = RTDLL_FORWARD;
if (functionName.compare(COREAPI_MASK, COREAPI_MASK_LEN))
apiCall = true;
}
else dllName = moduleScope->project->resolveExternalAlias(dllAlias, stdCall);
// legacy : if dll is not mapped, use the name directly
if (emptystr(dllName))
dllName = dllAlias;
ReferenceNs name;
if (!apiCall) {
name.copy(DLL_NAMESPACE);
name.combine(dllName);
name.append(".");
name.append(functionName);
}
else {
name.copy(NATIVE_MODULE);
name.combine(CORE_MODULE);
name.combine(functionName);
}
ref_t reference = moduleScope->module->mapReference(name);
SNode exprNode = node.parentNode();
exprNode.set(lxSeqExpression, 0);
SNode callNode = exprNode.appendNode(lxVirtualReference);
// To tell apart coreapi calls, the name convention is used
if (apiCall) {
callNode.set(lxCoreAPICall, reference);
}
else callNode.set(stdCall ? lxStdExternalCall : lxExternalCall, reference);
LexicalType opType = callNode.type;
// HOTFIX : remove the dll identifier
targetNode = lxIdle;
compileExternalArguments(exprNode, scope, callNode);
callNode.injectAndReplaceNode(lxBoxableExpression);
if (expectedRef != 0 && _logic->isCompatible(*scope.moduleScope, V_DWORD, expectedRef, true)) {
retVal.reference = expectedRef;
callNode.appendNode(lxSize, 4);
}
else if (expectedRef != 0 && _logic->isCompatible(*scope.moduleScope, V_REAL64, expectedRef, true)) {
retVal.reference = expectedRef;
retVal.param = (ref_t)-1; // ot indicate Float mode
callNode.appendNode(lxSize, 8);
// retVal = assignResult(writer, scope, true, V_REAL64);
}
else if (expectedRef != 0 && _logic->isCompatible(*scope.moduleScope, V_INT64, expectedRef, true)) {
retVal.reference = expectedRef;
callNode.appendNode(lxSize, 8);
callNode.findChild(opType).appendNode(lxLongMode);
// retVal = assignResult(writer, scope, false, expectedRef);
}
else {
retVal.reference = V_DWORD;
callNode.appendNode(lxSize, 4);
}
callNode.appendNode(lxType, retVal.reference);
return retVal;
}
ObjectInfo Compiler :: compileInternalCall(SNode node, ExprScope& scope, ref_t message, ref_t signature, ObjectInfo routine)
{
_ModuleScope* moduleScope = scope.moduleScope;
IdentifierString virtualReference(moduleScope->module->resolveReference(routine.param));
virtualReference.append('.');
int argCount;
ref_t actionRef, flags;
ref_t dummy = 0;
decodeMessage(message, actionRef, argCount, flags);
size_t signIndex = virtualReference.Length();
virtualReference.append('0' + (char)(argCount - 1));
virtualReference.append(moduleScope->module->resolveAction(actionRef, dummy));
ref_t signatures[ARG_COUNT];
size_t len = scope.module->resolveSignature(signature, signatures);
for (size_t i = 0; i < len; i++) {
if (isPrimitiveRef(signatures[i])) {
// !!
scope.raiseError(errIllegalOperation, node);
}
else {
virtualReference.append("$");
ident_t name = scope.module->resolveReference(signatures[i]);
if (isTemplateWeakReference(name)) {
NamespaceName ns(name);
virtualReference.append(name + getlength(ns));
}
else if (isWeakReference(name)) {
virtualReference.append(scope.module->Name());
virtualReference.append(name);
}
else virtualReference.append(name);
}
}
virtualReference.replaceAll('\'', '@', signIndex);
node.set(lxInternalCall, moduleScope->module->mapReference(virtualReference));
// NOTE : all arguments are passed directly
analizeOperands(node, scope, -1, true);
return ObjectInfo(okObject);
}
int Compiler :: allocateStructure(bool bytearray, int& allocatedSize, int& reserved)
{
if (bytearray) {
// plus space for size
allocatedSize = ((allocatedSize + 3) >> 2) + 2;
}
else allocatedSize = (allocatedSize + 3) >> 2;
int retVal = reserved;
reserved += allocatedSize;
// the offset should include frame header offset
retVal = newLocalAddr(retVal);
// reserve place for byte array header if required
if (bytearray)
retVal -= 2;
return retVal;
}
bool Compiler :: allocateStructure(CodeScope& scope, int size, bool binaryArray, ObjectInfo& exprOperand)
{
if (size <= 0)
return false;
MethodScope* methodScope = (MethodScope*)scope.getScope(Scope::ScopeLevel::slMethod);
if (methodScope == NULL)
return false;
int offset = allocateStructure(binaryArray, size, scope.allocated2);
exprOperand.kind = okLocalAddress;
exprOperand.param = offset;
return true;
}
bool Compiler :: allocateTempStructure(ExprScope& scope, int size, bool binaryArray, ObjectInfo& exprOperand)
{
if (size <= 0 || scope.tempAllocated2 == -1)
return false;
CodeScope* codeScope = (CodeScope*)scope.getScope(Scope::ScopeLevel::slCode);
int offset = allocateStructure(binaryArray, size, scope.tempAllocated2);
if (scope.tempAllocated2 > codeScope->reserved2)
codeScope->reserved2 = scope.tempAllocated2;
exprOperand.kind = okLocalAddress;
exprOperand.param = offset;
return true;
}
ref_t Compiler :: declareInlineArgumentList(SNode arg, MethodScope& scope, bool declarationMode)
{
// IdentifierString signature;
IdentifierString messageStr;
ref_t actionRef = 0;
ref_t signRef = 0;
// SNode sign = goToNode(arg, lxTypeAttr);
ref_t signatures[ARG_COUNT];
size_t signatureLen = 0;
// bool first = true;
bool weakSingature = true;
while (arg == lxMethodParameter/* || arg == lxIdentifier || arg == lxPrivate*/) {
SNode terminalNode = arg;
if (terminalNode == lxMethodParameter) {
terminalNode = terminalNode.firstChild(lxTerminalMask);
}
ident_t terminal = terminalNode.identifier();
int index = 1 + scope.parameters.Count();
// !! check duplicates
if (scope.parameters.exist(terminal))
scope.raiseError(errDuplicatedLocal, arg);
ref_t elementRef = 0;
ref_t classRef = 0;
declareArgumentAttributes(arg, scope, classRef, elementRef, declarationMode);
int size = classRef != 0 ? _logic->defineStructSize(*scope.moduleScope, classRef, 0) : 0;
scope.parameters.add(terminal, Parameter(index, classRef, elementRef, size));
if (classRef != 0)
weakSingature = false;
if (isPrimitiveRef(classRef)) {
// primitive arguments should be replaced with wrapper classes
signatures[signatureLen++] = resolvePrimitiveReference(scope, classRef, elementRef, declarationMode);
}
else signatures[signatureLen++] = classRef;
arg = arg.nextNode();
}
//if (sign == lxTypeAttr) {
// // if the returning type is provided
// ref_t elementRef = 0;
// outputRef = declareArgumentType(sign, scope, /*first, messageStr, signature, */elementRef);
// if (sign.nextNode() == lxTypeAttr)
// scope.raiseError(errInvalidOperation, arg);
//}
if (emptystr(messageStr)) {
messageStr.copy(INVOKE_MESSAGE);
}
//messageStr.append(signature);
if (signatureLen > 0 && !weakSingature) {
if (scope.parameters.Count() == signatureLen) {
signRef = scope.module->mapSignature(signatures, signatureLen, false);
}
else scope.raiseError(errInvalidOperation, arg);
}
actionRef = scope.moduleScope->module->mapAction(messageStr, signRef, false);
return encodeMessage(actionRef, scope.parameters.Count(), FUNCTION_MESSAGE);
}
//inline SNode findTerminal(SNode node)
//{
// SNode ident = node.findChild(lxIdentifier/*, lxPrivate*/);
// if (ident == lxNone)
// //HOTFIX : if the tree is generated by the script engine
// ident = node;
//
// return ident;
//}
void Compiler :: declareArgumentAttributes(SNode node, Scope& scope, ref_t& classRef, ref_t& elementRef, bool declarationMode)
{
bool byRefArg = false;
bool paramsArg = false;
SNode current = node.firstChild();
while (current != lxNone) {
if (current == lxAttribute) {
if (_logic->validateArgumentAttribute(current.argument, byRefArg, paramsArg)) {
}
else scope.raiseWarning(WARNING_LEVEL_1, wrnInvalidHint, current);
}
else if (current.compare(lxType, lxArrayType)) {
if (paramsArg) {
if (current != lxArrayType)
scope.raiseError(errIllegalMethod, node);
classRef = resolveTypeAttribute(current.firstChild(), scope, declarationMode, false);
}
else classRef = resolveTypeAttribute(current, scope, declarationMode, false);
}
current = current.nextNode();
}
if (byRefArg) {
elementRef = classRef;
classRef = V_WRAPPER;
}
if (paramsArg) {
elementRef = classRef;
classRef = V_ARGARRAY;
}
}
ref_t Compiler :: mapMethodName(MethodScope& scope, int paramCount, ref_t actionRef, int flags,
IdentifierString& actionStr, ref_t* signature, size_t signatureLen,
bool withoutWeakMessages, bool noSignature)
{
if (test(flags, VARIADIC_MESSAGE)) {
paramCount = 1;
// HOTFIX : extension is a special case - target should be included as well for variadic function
if (scope.extensionMode && test(flags, FUNCTION_MESSAGE))
paramCount++;
}
// NOTE : a message target should be included as well for a normal message
int argCount = test(flags, FUNCTION_MESSAGE) ? 0 : 1;
argCount += paramCount;
if (actionRef != 0) {
// HOTFIX : if the action was already resolved - do nothing
}
else if (actionStr.Length() > 0) {
ref_t signatureRef = 0;
if (signatureLen > 0)
signatureRef = scope.moduleScope->module->mapSignature(signature, signatureLen, false);
actionRef = scope.moduleScope->module->mapAction(actionStr.c_str(), signatureRef, false);
if (withoutWeakMessages && noSignature && test(scope.getClassFlags(false), elClosed)) {
// HOTFIX : for the nested closed class - special handling is requiered
ClassScope* classScope = (ClassScope*)scope.getScope(Scope::ScopeLevel::slClass);
if (!classScope->info.methods.exist(encodeMessage(actionRef, argCount, flags))) {
actionRef = scope.moduleScope->module->mapAction(actionStr.c_str(), 0, false);
}
}
}
else return 0;
return encodeMessage(actionRef, argCount, flags);
}
void Compiler :: declareArgumentList(SNode node, MethodScope& scope, bool withoutWeakMessages, bool declarationMode)
{
if (withoutWeakMessages && test(scope.hints, tpGeneric))
// HOTFIX : nested generic message should not have a multimethod
withoutWeakMessages = false;
IdentifierString actionStr;
ref_t actionRef = 0;
ref_t signature[ARG_COUNT];
size_t signatureLen = 0;
bool constantConversion = false;
bool unnamedMessage = false;
ref_t flags = 0;
SNode nameNode = node.findChild(lxNameAttr/*, lxMessage*/);
SNode identNode = nameNode.firstChild(lxTerminalMask);
SNode current = /*action == lxNone ? */node.findChild(lxMethodParameter)/* : action.nextNode()*/;
if (identNode == lxIdentifier) {
actionStr.copy(identNode.identifier());
}
else unnamedMessage = true;
bool weakSignature = true;
int paramCount = 0;
if (scope.extensionMode) {
// COMPILER MAGIC : for an extension method, self is a parameter
paramCount++;
signature[0] = ((ClassScope*)scope.parent)->extensionClassRef;
signatureLen++;
weakSignature = false;
int size = 0;
if (!declarationMode)
size = _logic->defineStructSize(*scope.moduleScope, signature[0], 0);
scope.parameters.add(SELF_VAR, Parameter(1, signature[0], 0, size));
flags |= FUNCTION_MESSAGE;
}
bool noSignature = true; // NOTE : is similar to weakSignature except if withoutWeakMessages=true
// if method has an argument list
while (current != lxNone) {
if (current == lxMethodParameter) {
int index = 1 + scope.parameters.Count();
int size = 0;
ref_t classRef = 0;
ref_t elementRef = 0;
declareArgumentAttributes(current, scope, classRef, elementRef, declarationMode);
//// NOTE : for the nested classes there should be no weak methods (see compileNestedVMT)
// NOTE : an extension method must be strong-resolved
if (withoutWeakMessages && !classRef) {
classRef = scope.moduleScope->superReference;
}
else noSignature = false;
if (!classRef) {
classRef = scope.moduleScope->superReference;
}
else weakSignature = false;
ident_t terminal = current.findChild(lxNameAttr).firstChild(lxTerminalMask).identifier();
if (scope.parameters.exist(terminal))
scope.raiseError(errDuplicatedLocal, current);
paramCount++;
if (paramCount >= ARG_COUNT || test(flags, VARIADIC_MESSAGE))
scope.raiseError(errTooManyParameters, current);
if (classRef == V_ARGARRAY) {
// to indicate open argument list
flags |= VARIADIC_MESSAGE;
// the generic arguments should be free by the method exit
scope.withOpenArg = true;
if (!elementRef)
elementRef = scope.moduleScope->superReference;
signature[signatureLen++] = elementRef;
}
else if (isPrimitiveRef(classRef)) {
// primitive arguments should be replaced with wrapper classes
signature[signatureLen++] = resolvePrimitiveReference(scope, classRef, elementRef, declarationMode);
}
else signature[signatureLen++] = classRef;
size = _logic->defineStructSize(*scope.moduleScope, classRef, elementRef);
scope.parameters.add(terminal, Parameter(index, classRef, elementRef, size));
}
// else if (current == lxMessage) {
// actionStr.append(":");
// actionStr.append(current.findChild(lxIdentifier).identifier());
// }
else break;
current = current.nextNode();
}
// if the signature consists only of generic parameters - ignore it
if (weakSignature)
signatureLen = 0;
// HOTFIX : do not overrwrite the message on the second pass
if (scope.message == 0) {
// if (test(scope.hints, tpSpecial))
// flags |= SPECIAL_MESSAGE;
if ((scope.hints & tpMask) == tpDispatcher) {
if (paramCount == 0 && unnamedMessage) {
actionRef = getAction(scope.moduleScope->dispatch_message);
unnamedMessage = false;
}
else scope.raiseError(errIllegalMethod, node);
}
else if (test(scope.hints, tpConversion)) {
if (paramCount == 0 && unnamedMessage && scope.outputRef) {
ref_t signatureRef = scope.moduleScope->module->mapSignature(&scope.outputRef, 1, false);
actionRef = scope.moduleScope->module->mapAction(CAST_MESSAGE, signatureRef, false);
unnamedMessage = false;
}
else if (paramCount == 1 && !unnamedMessage && signature[0] == scope.moduleScope->literalReference) {
constantConversion = true;
actionStr.append(CONSTRUCTOR_MESSAGE);
scope.hints |= tpConstructor;
}
else scope.raiseError(errIllegalMethod, node);
}
else if (test(scope.hints, tpConstructor) && unnamedMessage) {
actionStr.copy(CONSTRUCTOR_MESSAGE);
unnamedMessage = false;
}
else if (test(scope.hints, tpSealed | tpGeneric)) {
if (signatureLen > 0 || !unnamedMessage || test(scope.hints, tpFunction))
scope.raiseError(errInvalidHint, node);
actionStr.copy(GENERIC_PREFIX);
unnamedMessage = false;
}
else if (test(scope.hints, tpFunction)) {
if (!unnamedMessage)
scope.raiseError(errInvalidHint, node);
actionStr.copy(INVOKE_MESSAGE);
flags |= FUNCTION_MESSAGE;
// Compiler Magic : if it is a generic closure - ignore fixed argument
if (test(scope.hints, tpMixin)) {
if (scope.withOpenArg && validateGenericClosure(signature, signatureLen)) {
signatureLen = 1;
scope.mixinFunction = true;
}
// mixin function should have a homogeneous signature (i.e. same types) and be variadic
else scope.raiseError(errIllegalMethod, node);
}
}
if (test(scope.hints, tpMixin) && !test(scope.hints, tpFunction))
// only mixin function is supported
scope.raiseError(errIllegalMethod, node);
if (testany(scope.hints, tpGetAccessor | tpSetAccessor)) {
flags |= PROPERTY_MESSAGE;
}
if (test(scope.hints, tpInternal)) {
actionStr.insert("$$", 0);
actionStr.insert(scope.module->Name(), 0);
}
else if (test(scope.hints, tpProtected)) {
if (actionStr.compare(CONSTRUCTOR_MESSAGE) && paramCount == 0) {
//HOTFIX : protected default constructor has a special name
actionStr.copy(CONSTRUCTOR_MESSAGE2);
}
else {
// check if protected method already declared
ref_t publicMessage = mapMethodName(scope, paramCount, actionRef, flags, actionStr,
signature, signatureLen, withoutWeakMessages, noSignature);
ref_t declaredMssg = scope.getAttribute(publicMessage, maProtected);
if (!declaredMssg) {
ident_t className = scope.module->resolveReference(scope.getClassRef());
actionStr.insert("$$", 0);
actionStr.insert(className + 1, 0);
actionStr.insert("@", 0);
actionStr.insert(scope.module->Name(), 0);
actionStr.replaceAll('\'', '@', 0);
}
else scope.message = declaredMssg;
}
}
else if ((scope.hints & tpMask) == tpPrivate) {
flags |= STATIC_MESSAGE;
}
if (!scope.message) {
scope.message = mapMethodName(scope, paramCount, actionRef, flags, actionStr,
signature, signatureLen, withoutWeakMessages, noSignature);
if (!scope.message)
scope.raiseError(errIllegalMethod, node);
}
// if it is an explicit constant conversion
if (constantConversion) {
NamespaceScope* nsScope = (NamespaceScope*)scope.getScope(Scope::ScopeLevel::slNamespace);
nsScope->saveExtension(scope.message, scope.getClassRef(), scope.message,
scope.getClassVisibility() != Visibility::Public);
}
}
if (scope.mixinFunction) {
// Compiler Magic : if it is a mixin function - argument size cannot be directly defined
scope.message = overwriteArgCount(scope.message, 0);
}
}
void Compiler :: compileDispatcher(SNode node, MethodScope& scope, LexicalType methodType,
bool withGenericMethods, bool withOpenArgGenerics)
{
node.set(methodType, scope.message);
SNode dispatchNode = node.findChild(lxDispatchCode);
if (dispatchNode != lxNone) {
CodeScope codeScope(&scope);
ExprScope exprScope(&codeScope);
ObjectInfo target = mapObject(dispatchNode, exprScope, EAttr::eaNone);
if (target.kind != okInternal) {
dispatchNode.injectAndReplaceNode(lxDispatching);
if (withGenericMethods) {
dispatchNode.setArgument(encodeMessage(codeScope.moduleScope->module->mapAction(GENERIC_PREFIX, 0, false), 0, 0));
}
dispatchNode = dispatchNode.firstChild();
}
compileDispatchExpression(dispatchNode, target, exprScope);
}
else {
dispatchNode = node.appendNode(lxDispatching);
SNode resendNode = dispatchNode.appendNode(lxResending, 0);
// if it is generic handler without redirect statement
if (withGenericMethods) {
// !! temporally
if (withOpenArgGenerics)
scope.raiseError(errInvalidOperation, node);
resendNode.appendNode(lxMessage,
encodeMessage(scope.moduleScope->module->mapAction(GENERIC_PREFIX, 0, false), 1, 0));
resendNode
.appendNode(lxCallTarget, scope.moduleScope->superReference)
.appendNode(lxMessage, scope.moduleScope->dispatch_message);
}
// if it is open arg generic without redirect statement
else if (withOpenArgGenerics) {
// HOTFIX : an extension is a special case of a variadic function and a target should be included
int argCount = !scope.extensionMode && test(scope.message, FUNCTION_MESSAGE) ? 1 : 2;
resendNode.appendNode(lxMessage, encodeMessage(getAction(scope.moduleScope->dispatch_message),
argCount, VARIADIC_MESSAGE));
resendNode
.appendNode(lxCallTarget, scope.moduleScope->superReference)
.appendNode(lxMessage, scope.moduleScope->dispatch_message);
}
else throw InternalError("Not yet implemented"); // !! temporal
}
}
void Compiler :: compileActionMethod(SNode node, MethodScope& scope)
{
declareProcedureDebugInfo(node, scope, false/*, false*/);
CodeScope codeScope(&scope);
SNode body = node.findChild(lxCode, lxReturning);
if (body != lxCode) {
body.injectAndReplaceNode(lxNewFrame);
body = body.firstChild();
}
else body.set(lxNewFrame, 0);
// new stack frame
// stack already contains previous $self value
codeScope.allocated1++;
scope.preallocated = codeScope.allocated1;
ObjectInfo retVal = compileCode(body == lxReturning ? body.parentNode() : body, codeScope);
codeScope.syncStack(&scope);
endMethod(node, scope);
}
void Compiler :: compileExpressionMethod(SNode node, MethodScope& scope, bool lazyMode)
{
declareProcedureDebugInfo(node, scope, false/*, false*/);
CodeScope codeScope(&scope);
SNode current = node.findChild(lxExpression);
current.injectAndReplaceNode(lxNewFrame);
current = current.firstChild();
// new stack frame
// stack already contains previous $self value
codeScope.allocated1++;
scope.preallocated = codeScope.allocated1;
if (lazyMode) {
int tempLocal = newLocalAddr(codeScope.allocated2++);
SNode frameNode = current.parentNode();
// HOTFIX : lazy expression should presave incoming message
frameNode.insertNode(lxIndexSaving).appendNode(lxLocalAddress, tempLocal);
SNode attrNode = current.firstChild();
while ((attrNode != lxAttribute || attrNode.argument != V_LAZY) && attrNode != lxNone)
attrNode = attrNode.nextNode();
// HOTFIX : comment lazy attribute out to prevent short circuit
if (attrNode == lxAttribute && attrNode.argument == V_LAZY)
attrNode.setArgument(0);
compileRetExpression(current, codeScope, EAttr::eaNone);
// HOTFIX : lazy expression should presave incoming message
frameNode.appendNode(lxIndexLoading).appendNode(lxLocalAddress, tempLocal);;
}
else compileRetExpression(current, codeScope, EAttr::eaNone);
codeScope.syncStack(&scope);
endMethod(node, scope);
}
void Compiler :: compileDispatchExpression(SNode node, CodeScope& scope)
{
ExprScope exprScope(&scope);
ObjectInfo target = mapObject(node, exprScope, EAttr::eaNone);
compileDispatchExpression(node, target, exprScope);
}
void Compiler :: warnOnUnresolvedDispatch(SNode node, Scope& scope, ref_t message, bool errorMode)
{
// ingore dispatch message
if (message == scope.moduleScope->dispatch_message)
return;
scope.moduleScope->printMessageInfo(infoAbstractMetod, message);
SNode terminal = node.firstChild(lxTerminalMask);
if (terminal != lxNone) {
if (errorMode) {
scope.raiseError(errUnresolvedDispatch, node);
}
else scope.raiseWarning(WARNING_LEVEL_1, wrnUnresolvedDispatch, node);
}
else {
SNode current = node.parentNode();
if (current == lxClassMethod && current.existChild(lxAutogenerated)) {
while (current != lxNone) {
current = current.parentNode();
if (current == lxClass && current.existChild(lxNameAttr)) {
SNode nameNode = current.findChild(lxNameAttr).firstChild(lxTerminalMask);
if (nameNode != lxNone) {
if (errorMode) {
scope.raiseError(errUnresolvedInterface, nameNode);
}
else scope.raiseWarning(WARNING_LEVEL_1, wrnUnresolvedInterface, nameNode);
break;
}
}
else if (current == lxRoot) {
SNode sourceNode = current.findChild(lxTemplateSource);
if (errorMode) {
scope.raiseError(errUnresolvedInterface, sourceNode);
}
else scope.raiseWarning(WARNING_LEVEL_1, wrnUnresolvedInterface, sourceNode);
break;
}
}
}
}
}
void Compiler :: compileDispatchExpression(SNode node, ObjectInfo target, ExprScope& exprScope)
{
if (target.kind == okInternal) {
importCode(node, exprScope, target.param, exprScope.getMessageID());
}
else {
MethodScope* methodScope = (MethodScope*)exprScope.getScope(Scope::ScopeLevel::slMethod);
// try to implement light-weight resend operation
ref_t targetRef = methodScope->getReturningRef(false);
ref_t sourceRef = resolveObjectReference(exprScope, target, false, false);
int stackSafeAttrs = 0;
bool directOp = _logic->isCompatible(*exprScope.moduleScope, targetRef, exprScope.moduleScope->superReference, false);
bool simpleOp = isSingleStatement(node);
int dispatcHint = tpUnknown;
if (simpleOp) {
_CompilerLogic::ChechMethodInfo methodInfo;
dispatcHint = _logic->checkMethod(*exprScope.moduleScope, sourceRef, methodScope->message, methodInfo, false);
if (methodInfo.found && dispatcHint == tpUnknown) {
// warn if the dispatch target is not found
warnOnUnresolvedDispatch(node, exprScope, methodScope->message, _logic->isSealedOrClosed(*exprScope.moduleScope, sourceRef));
}
if (!directOp) {
// try to find out if direct dispatch is possible
if (dispatcHint != tpUnknown) {
directOp = _logic->isCompatible(*exprScope.moduleScope, targetRef, methodInfo.outputReference, false);
}
}
}
LexicalType op = lxResending;
if (methodScope->message == methodScope->moduleScope->dispatch_message) {
// HOTFIX : if it is a generic message resending
op = lxGenericResending;
}
// check if direct dispatch can be done
if (directOp) {
// we are lucky and can dispatch the message directly
switch (target.kind) {
case okConstantSymbol:
case okField:
case okReadOnlyField:
case okOuterSelf:
case okOuter:
if (simpleOp)
{
// HOTFIX : use direct dispatching only for object expression
node.set(op, methodScope->message);
if (target.kind != okConstantSymbol) {
SNode fieldExpr = node.findChild(lxFieldExpression);
if (fieldExpr != lxNone) {
fieldExpr.set(lxField, target.param);
}
}
if (op == lxResending && dispatcHint == tpSealed && sourceRef)
node.appendNode(lxCallTarget, sourceRef);
break;
}
default:
{
node.set(op, methodScope->message);
SNode frameNode = node.injectNode(lxNewFrame);
SNode exprNode = frameNode.injectNode(lxExpression);
exprScope.tempAllocated1++;
int preserved = exprScope.tempAllocated1;
target = compileExpression(exprNode, exprScope, target, 0, EAttr::eaNone);
analizeOperands(exprNode, exprScope, 0, false);
// HOTFIX : allocate temporal variables
if (exprScope.tempAllocated1 != preserved)
frameNode.appendNode(lxReserved, exprScope.tempAllocated1 - preserved);
break;
}
}
}
else {
EAttr mode = EAttr::eaNone;
// bad luck - we have to dispatch and type cast the result
node.set(lxNewFrame, 0);
node.injectNode(lxExpression);
SNode exprNode = node.firstChild(lxObjectMask);
for (auto it = methodScope->parameters.start(); !it.Eof(); it++) {
ObjectInfo param = methodScope->mapParameter(*it, EAttr::eaNone);
SNode refNode = exprNode.appendNode(lxVirtualReference);
setParamTerminal(refNode, exprScope, param, mode, lxLocal);
}
bool dummy = false;
ObjectInfo retVal = compileMessage(exprNode, exprScope, target, methodScope->message, mode | HINT_NODEBUGINFO,
stackSafeAttrs, dummy);
retVal = convertObject(exprNode, exprScope, targetRef, retVal, mode);
if (retVal.kind == okUnknown) {
exprScope.raiseError(errInvalidOperation, node);
}
}
}
}
inline ref_t resolveProtectedMessage(ClassInfo& info, ref_t protectedMessage)
{
for (auto it = info.methodHints.start(); !it.Eof(); it++) {
if (*it == protectedMessage) {
Attribute key = it.key();
if (key.value2 == maProtected) {
return key.value1;
}
}
}
return 0;
}
void Compiler :: compileConstructorResendExpression(SNode node, CodeScope& codeScope, ClassScope& classClassScope,
bool& withFrame)
{
ResendScope resendScope(&codeScope);
resendScope.consructionMode = true;
// inject a root expression
SNode expr = node.findChild(lxExpression).injectNode(lxExpression);
_ModuleScope* moduleScope = codeScope.moduleScope;
MethodScope* methodScope = (MethodScope*)codeScope.getScope(Scope::ScopeLevel::slMethod);
SNode messageNode = expr.findChild(lxMessage);
ref_t messageRef = mapMessage(messageNode, resendScope, false, false);
ref_t classRef = classClassScope.reference;
bool found = false;
if (node.existChild(lxCode) || !isConstantArguments(expr)) {
withFrame = true;
// new stack frame
// stack already contains $self value
node.set(lxNewFrame, 0);
codeScope.allocated1++;
// HOTFIX : take into account saved self variable
resendScope.tempAllocated1 = codeScope.allocated1;
methodScope->preallocated = codeScope.allocated1;
}
else node.set(lxExpression, 0);
if (withFrame) {
expr.insertNode(lxSelfLocal, 1);
}
else expr.insertNode(lxResult);
resendScope.withFrame = withFrame;
bool variadicOne = false;
bool inlineArg = false;
SNode argNode = expr.findChild(lxMessage).nextNode();
ref_t implicitSignatureRef = compileMessageParameters(argNode, resendScope, EAttr::eaNone,
variadicOne, inlineArg);
// HOTFIX : (re)initialize expr node in case the parent node was modified (due to unboxing)
if (argNode != lxNone)
expr = argNode.parentNode();
ObjectInfo target(okClassSelf, resendScope.getClassRefId(), classRef);
int stackSafeAttr = 0;
// if (implicitConstructor) {
// ref_t resolvedMessageRef = _logic->resolveImplicitConstructor(*scope.moduleScope, target.param, implicitSignatureRef, getParamCount(messageRef),
// stackSafeAttr, false);
//
// if (resolvedMessageRef)
// messageRef = resolvedMessageRef;
// }
/*else */messageRef = resolveMessageAtCompileTime(target, resendScope, messageRef, implicitSignatureRef, false, stackSafeAttr);
// find where the target constructor is declared in the current class
// but it is not equal to the current method
ClassScope* classScope = (ClassScope*)resendScope.getScope(Scope::ScopeLevel::slClass);
int hints = methodScope->message != messageRef ? checkMethod(*moduleScope, classScope->info.header.classRef, messageRef) : tpUnknown;
if (hints != tpUnknown) {
found = true;
}
// otherwise search in the parent class constructors
else {
ref_t publicRef = resolveProtectedMessage(classClassScope.info, messageRef);
// HOTFIX : replace protected message with public one
if (publicRef)
messageRef = publicRef;
ref_t parent = classScope->info.header.parentRef;
ClassInfo info;
while (parent != 0) {
moduleScope->loadClassInfo(info, moduleScope->module->resolveReference(parent));
ref_t protectedConstructor = 0;
if (checkMethod(*moduleScope, info.header.classRef, messageRef, protectedConstructor) != tpUnknown) {
classRef = info.header.classRef;
found = true;
target.reference = classRef;
messageRef = resolveMessageAtCompileTime(target, resendScope, messageRef, implicitSignatureRef,
false, stackSafeAttr);
break;
}
else if (protectedConstructor) {
classRef = info.header.classRef;
found = true;
target.reference = classRef;
messageRef = resolveMessageAtCompileTime(target, resendScope, protectedConstructor, implicitSignatureRef,
false, stackSafeAttr);
break;
}
else parent = info.header.parentRef;
}
}
if (found) {
bool dummy = false;
compileMessage(expr, resendScope, target, messageRef, EAttr::eaNone, stackSafeAttr, dummy);
if (withFrame) {
// HOT FIX : inject saving of the created object
SNode codeNode = node.findChild(lxCode);
if (codeNode != lxNone) {
SNode assignNode = codeNode.insertNode(lxAssigning);
assignNode.appendNode(lxLocal, 1);
assignNode.appendNode(lxResult);
}
}
}
else resendScope.raiseError(errUnknownMessage, node);
}
void Compiler :: compileConstructorDispatchExpression(SNode node, CodeScope& scope, bool isDefault)
{
SNode redirect = node.findChild(lxRedirect);
if (redirect != lxNone) {
if (!isDefault) {
SNode callNode = node.prependSibling(lxCalling_1, scope.moduleScope->constructor_message);
callNode.appendNode(lxResult);
}
else {
MethodScope* methodScope = (MethodScope*)scope.getScope(Scope::ScopeLevel::slMethod);
compileDefConvConstructor(node.parentNode(), *methodScope);
}
node.set(lxImplicitJump, redirect.argument);
node.appendNode(lxCallTarget, scope.getClassRefId());
}
else {
ExprScope exprScope(&scope);
ObjectInfo target = mapObject(node, exprScope, EAttr::eaNone);
if (target.kind == okInternal) {
importCode(node, exprScope, target.param, exprScope.getMessageID());
}
else scope.raiseError(errInvalidOperation, node);
}
}
void Compiler :: compileMultidispatch(SNode node, CodeScope& scope, ClassScope& classScope)
{
ref_t message = scope.getMessageID();
ref_t overloadRef = classScope.info.methodHints.get(Attribute(message, maOverloadlist));
if (!overloadRef)
scope.raiseError(errIllegalOperation, node);
LexicalType op = lxMultiDispatching;
if (test(classScope.info.header.flags, elSealed) || test(message, STATIC_MESSAGE)) {
op = lxSealedMultiDispatching;
}
if (node == lxResendExpression) {
node.prependSibling(op, overloadRef);
// if (node.existChild(lxTypecasting)) {
// // if it is multi-method implicit conversion method
// ref_t targetRef = scope.getClassRefId();
// ref_t signRef = scope.module->mapSignature(&targetRef, 1, false);
//
// writer.newNode(lxCalling, encodeAction(scope.module->mapAction(CAST_MESSAGE, signRef, false)));
// writer.appendNode(lxCurrent, 2);
// writer.closeNode();
// }
// else {
if (classScope.extensionDispatcher) {
node.set(lxResending, node.argument & ~FUNCTION_MESSAGE);
node.appendNode(lxCurrent, 1);
}
else node.set(lxResending, node.argument);
// writer.newNode(lxDispatching, node.argument);
// SyntaxTree::copyNode(writer, lxTarget, node);
// writer.closeNode();
// }
}
else node.insertNode(op, overloadRef);
}
void Compiler :: compileResendExpression(SNode node, CodeScope& codeScope, bool multiMethod)
{
if (node.firstChild() == lxImplicitJump) {
// do nothing for redirect method
node = lxExpression;
}
else if (node.argument != 0 && multiMethod) {
ClassScope* classScope = (ClassScope*)codeScope.getScope(Scope::ScopeLevel::slClass);
compileMultidispatch(node, codeScope, *classScope);
}
else {
if (multiMethod) {
ClassScope* classScope = (ClassScope*)codeScope.getScope(Scope::ScopeLevel::slClass);
compileMultidispatch(node.parentNode(), codeScope, *classScope);
}
bool silentMode = node.existChild(lxAutogenerated);
SNode expr = node.findChild(lxExpression);
// new stack frame
// stack already contains $self value
node.set(lxNewFrame, 0);
codeScope.allocated1++;
expr.insertNode(lxSelfLocal, 1);
SNode messageNode = expr.findChild(lxMessage);
ExprScope scope(&codeScope);
ObjectInfo target = scope.mapMember(SELF_VAR);
EAttr resendMode = silentMode ? EAttr::eaSilent : EAttr::eaNone;
compileMessage(messageNode, scope, 0, target, resendMode);
if (node.existChild(lxCode))
scope.raiseError(errInvalidOperation, node);
}
}
bool Compiler :: isMethodEmbeddable(MethodScope& scope, SNode)
{
if (test(scope.hints, tpEmbeddable)) {
ClassScope* ownerScope = (ClassScope*)scope.parent;
return ownerScope->info.methodHints.exist(Attribute(scope.message, maEmbeddableRet));
}
else return false;
}
void Compiler :: compileEmbeddableMethod(SNode node, MethodScope& scope)
{
ClassScope* ownerScope = (ClassScope*)scope.parent;
// generate private static method with an extra argument - retVal
MethodScope privateScope(ownerScope);
privateScope.message = ownerScope->info.methodHints.get(Attribute(scope.message, maEmbeddableRet));
ref_t ref = resolvePrimitiveReference(scope, V_WRAPPER, scope.outputRef, false);
validateType(scope, node, ref, false, false);
declareArgumentList(node, privateScope, true, false);
privateScope.parameters.add(RETVAL_ARG, Parameter(1 + scope.parameters.Count(), V_WRAPPER, scope.outputRef, 0));
privateScope.classStacksafe = scope.classStacksafe;
privateScope.extensionMode = scope.extensionMode;
privateScope.embeddableRetMode = true;
// !! TEMPORAL : clone the method node, to compile it safely : until the proper implementation
SNode cloneNode = node.prependSibling(node.type, privateScope.message);
SyntaxTree::copyNode(node, cloneNode);
if (scope.abstractMethod) {
// COMPILER MAGIC : if the method retunging value can be passed as an extra argument
compileAbstractMethod(node, scope);
compileAbstractMethod(cloneNode, privateScope);
}
else {
if (scope.yieldMethod) {
compileYieldableMethod(cloneNode, privateScope);
//compileMethod(writer, node, privateScope);
compileYieldableMethod(node, scope);
}
else {
compileMethod(cloneNode, privateScope);
//compileMethod(node, privateScope);
compileMethod(node, scope);
}
}
}
void Compiler :: beginMethod(SNode node, MethodScope& scope)
{
// if (scope.functionMode) {
// scope.rootToFree -= 1;
// }
declareProcedureDebugInfo(node, scope, true/*, test(scope.getClassFlags(), elExtension)*/);
}
void Compiler :: endMethod(SNode node, MethodScope& scope)
{
node.insertNode(lxAllocated, scope.reserved1 - scope.preallocated); // allocate the space for the local variables excluding preallocated ones ("$this", "$message")
if (scope.mixinFunction) {
// generic functions are special case of functions, consuming only fixed part of the argument list
node.insertNode(lxArgCount, scope.parameters.Count() - 1);
}
else node.insertNode(lxArgCount, getArgCount(scope.message));
node.insertNode(lxReserved, scope.reserved2);
}
ref_t Compiler :: resolveConstant(ObjectInfo retVal, ref_t& parentRef)
{
switch (retVal.kind) {
case okSingleton:
parentRef = retVal.param;
return retVal.param;
case okConstantSymbol:
parentRef = retVal.reference;
return retVal.param;
case okArrayConst:
parentRef = retVal.reference;
return retVal.param;
default:
return 0;
}
}
ref_t Compiler :: generateConstant(_CompileScope& scope, ObjectInfo retVal)
{
switch (retVal.kind) {
case okSingleton:
return retVal.param;
case okLiteralConstant:
case okWideLiteralConstant:
case okIntConstant:
break;
default:
return 0;
}
ref_t parentRef = 0;
ref_t constRef = scope.moduleScope->mapAnonymous("const");
_Module* module = scope.moduleScope->module;
MemoryWriter dataWriter(module->mapSection(constRef | mskRDataRef, false));
if (retVal.kind == okIntConstant || retVal.kind == okUIntConstant) {
size_t value = module->resolveConstant(retVal.param).toULong(16);
dataWriter.writeDWord(value);
parentRef = scope.moduleScope->intReference;
}
else if (retVal.kind == okLongConstant) {
long long value = module->resolveConstant(retVal.param).toLongLong(10, 1);
dataWriter.write(&value, 8u);
parentRef = scope.moduleScope->longReference;
}
else if (retVal.kind == okRealConstant) {
double value = module->resolveConstant(retVal.param).toDouble();
dataWriter.write(&value, 8u);
parentRef = scope.moduleScope->realReference;
}
else if (retVal.kind == okLiteralConstant) {
ident_t value = module->resolveConstant(retVal.param);
dataWriter.writeLiteral(value, getlength(value) + 1);
parentRef = scope.moduleScope->literalReference;
}
else if (retVal.kind == okWideLiteralConstant) {
WideString wideValue(module->resolveConstant(retVal.param));
dataWriter.writeLiteral(wideValue, getlength(wideValue) + 1);
parentRef = scope.moduleScope->wideReference;
}
else if (retVal.kind == okCharConstant) {
ident_t value = module->resolveConstant(retVal.param);
dataWriter.writeLiteral(value, getlength(value));
parentRef = scope.moduleScope->charReference;
}
else if (retVal.kind == okMessageNameConstant) {
dataWriter.Memory()->addReference(retVal.param | mskMessageName, dataWriter.Position());
dataWriter.writeDWord(0);
parentRef = scope.moduleScope->messageNameReference;
}
// else if (retVal.kind == okObject) {
// SNode root = node.findSubNodeMask(lxObjectMask);
//
// if (root == lxConstantList/* && !accumulatorMode*/) {
// SymbolExpressionInfo info;
// info.expressionClassRef = scope.outputRef;
// info.constant = scope.constant;
// info.listRef = root.argument;
//
// // save class meta data
// MemoryWriter metaWriter(scope.moduleScope->module->mapSection(scope.reference | mskMetaRDataRef, false), 0);
// info.save(&metaWriter);
//
// return true;
// }
// else return false;
// }
dataWriter.Memory()->addReference(parentRef | mskVMTRef, (ref_t)-4);
SymbolExpressionInfo info;
info.type = SymbolExpressionInfo::Type::Constant;
info.exprRef = parentRef;
// save constant meta data
MemoryWriter metaWriter(scope.moduleScope->module->mapSection(constRef | mskMetaRDataRef, false), 0);
info.save(&metaWriter);
return constRef;
}
void Compiler :: compileMethodCode(SNode node, SNode body, MethodScope& scope, CodeScope& codeScope)
{
if (scope.multiMethod) {
ClassScope* classScope = (ClassScope*)scope.getScope(Scope::ScopeLevel::slClass);
compileMultidispatch(node, codeScope, *classScope);
}
int frameArg = scope.generic ? -1 : 0;
if (body != lxCode) {
body.injectAndReplaceNode(lxNewFrame, frameArg);
body = body.firstChild();
}
else body.set(lxNewFrame, frameArg);
// new stack frame
// stack already contains current self reference
// the original message should be restored if it is a generic method
codeScope.allocated1++;
// declare the current subject for a generic method
if (scope.generic) {
codeScope.allocated2++;
codeScope.mapLocal(MESSAGE_VAR, -2, V_MESSAGE, 0, 0);
}
scope.preallocated = codeScope.allocated1;
if (body == lxReturning)
body = body.parentNode();
ObjectInfo retVal = compileCode(body, codeScope);
// if the method returns itself
if (retVal.kind == okUnknown && !codeScope.withRetStatement) {
if (test(scope.hints, tpSetAccessor)) {
retVal = scope.mapParameter(*scope.parameters.start(), EAttr::eaNone);
}
else retVal = scope.mapSelf();
// adding the code loading self / parameter (for set accessor)
SNode retNode = body.appendNode(lxReturning);
ExprScope exprScope(&codeScope);
SNode exprNode = retNode.appendNode(lxExpression);
recognizeTerminal(exprNode, retVal, exprScope, HINT_NODEBUGINFO | HINT_NOBOXING);
ref_t resultRef = scope.getReturningRef(false);
if (resultRef != 0) {
if (convertObject(retNode, exprScope, resultRef, retVal, EAttr::eaNone).kind == okUnknown)
scope.raiseError(errInvalidOperation, node);
}
}
if (scope.constMode) {
ClassScope* classScope = (ClassScope*)scope.getScope(Scope::ScopeLevel::slClass);
ref_t constRef = generateConstant(scope, retVal);
if (constRef) {
classScope->addAttribute(scope.message, maConstant, constRef);
classScope->save();
}
else scope.raiseError(errInvalidConstAttr, node);
}
}
void Compiler :: compileMethod(SNode node, MethodScope& scope)
{
beginMethod(node, scope);
scope.preallocated = 0;
CodeScope codeScope(&scope);
SNode body = node.findChild(lxCode, lxReturning, lxDispatchCode, lxResendExpression, lxNoBody);
// check if it is a resend
if (body == lxResendExpression) {
compileResendExpression(body, codeScope, scope.multiMethod);
scope.preallocated = 1;
}
// check if it is a dispatch
else if (body == lxDispatchCode) {
compileDispatchExpression(body, codeScope);
}
else if (body == lxNoBody) {
scope.raiseError(errNoBodyMethod, body);
}
else compileMethodCode(node, body, scope, codeScope);
codeScope.syncStack(&scope);
endMethod(node, scope);
}
void Compiler :: compileYieldDispatch(SNode node, MethodScope& scope)
{
int size1 = scope.reserved1 - scope.preallocated;
int size2 = scope.reserved2;
int index = scope.getAttribute(maYieldContext);
int index2 = scope.getAttribute(maYieldLocals);
// dispatch
SNode dispNode = node.insertNode(lxYieldDispatch);
SNode contextExpr = dispNode.appendNode(lxFieldExpression);
contextExpr.appendNode(lxSelfLocal, 1);
contextExpr.appendNode(lxField, index);
// load context
if (size2 != 0) {
SNode exprNode = node.insertNode(lxExpression);
SNode copyNode = exprNode.appendNode(lxCopying, size2 << 2);
copyNode.appendNode(lxLocalAddress, -2);
SNode fieldNode = copyNode.appendNode(lxFieldExpression);
fieldNode.appendNode(lxSelfLocal, 1);
fieldNode.appendNode(lxField, index);
fieldNode.appendNode(lxFieldAddress, 4);
}
// load locals
if (size1 != 0) {
SNode expr2Node = node.insertNode(lxExpression);
SNode copy2Node = expr2Node.appendNode(lxCopying, size1 << 2);
copy2Node.appendNode(lxLocalAddress, scope.preallocated + size1);
SNode field2Node = copy2Node.appendNode(lxFieldExpression);
field2Node.appendNode(lxSelfLocal, 1);
field2Node.appendNode(lxField, index2);
}
}
void Compiler :: compileYieldableMethod(SNode node, MethodScope& scope)
{
beginMethod(node, scope);
scope.preallocated = 0;
YieldScope yieldScope(&scope);
CodeScope codeScope(&yieldScope);
SNode body = node.findChild(lxCode, lxReturning, lxDispatchCode, lxResendExpression, lxNoBody);
if (body == lxCode) {
compileMethodCode(node, body, scope, codeScope);
}
else scope.raiseError(errInvalidOperation, body);
codeScope.syncStack(&scope);
compileYieldDispatch(body, scope);
endMethod(node, scope);
scope.addAttribute(maYieldContextLength, scope.reserved2 + 1);
scope.addAttribute(maYieldLocalLength, scope.reserved1 - scope.preallocated);
// HOTFIX : set correct context & locals offsets
//codeScope->reserved2 << 2
for (auto it = yieldScope.yieldLocals.start(); !it.Eof(); it++) {
SNode localNode = *it;
localNode.setArgument((*it).argument + scope.reserved1 - scope.preallocated);
SNode copyNode = localNode.parentNode();
if (copyNode == lxCopying) {
copyNode.setArgument((scope.reserved1 - scope.preallocated) << 2);
}
}
for (auto it = yieldScope.yieldContext.start(); !it.Eof(); it++) {
SNode copyNode = *it;
if (copyNode == lxCopying) {
copyNode.setArgument(scope.reserved2 << 2);
}
}
}
void Compiler :: compileAbstractMethod(SNode node, MethodScope& scope)
{
SNode body = node.findChild(lxCode, lxNoBody);
// abstract method should have an empty body
if (body == lxNoBody) {
// NOTE : abstract method should not have a body
}
else if (body != lxNone) {
if (body.firstChild() == lxEOP) {
scope.raiseWarning(WARNING_LEVEL_2, wrnAbstractMethodBody, body);
}
else scope.raiseError(errAbstractMethodCode, node);
}
else scope.raiseError(errAbstractMethodCode, node);
body.set(lxNil, 0);
}
void Compiler :: compileInitializer(SNode node, MethodScope& scope)
{
SNode methodNode = node.appendNode(lxClassMethod, scope.message);
beginMethod(methodNode, scope);
scope.preallocated = 0;
CodeScope codeScope(&scope);
ClassScope* classScope = (ClassScope*)scope.getScope(Scope::ScopeLevel::slClass);
if (checkMethod(*scope.moduleScope, classScope->info.header.parentRef, scope.message) != tpUnknown) {
ref_t messageOwnerRef = resolveMessageOwnerReference(*scope.moduleScope, classScope->info, classScope->reference,
scope.message, true);
// check if the parent has implicit constructor - call it
SNode callNode = methodNode.appendNode(lxDirectCalling, scope.message);
callNode.appendNode(lxResult);
callNode.appendNode(lxCallTarget, messageOwnerRef);
}
SNode frameNode = methodNode.appendNode(lxNewFrame);
// new stack frame
// stack already contains current $self reference
// the original message should be restored if it is a generic method
codeScope.allocated1++;
scope.preallocated = codeScope.allocated1;
SNode current = node.firstChild();
while (current != lxNone) {
if (current.compare(lxFieldInit, lxFieldAccum)) {
SNode sourceNode = current.findChild(lxSourcePath);
if (sourceNode != lxNone)
declareCodeDebugInfo(frameNode, scope);
SNode exprNode = frameNode.insertNode(lxExpression);
SyntaxTree::copyNode(current, exprNode);
compileRootExpression(exprNode, codeScope, 0, HINT_ROOT);
}
current = current.nextNode();
}
frameNode.appendNode(lxExpression).appendNode(lxSelfLocal, 1);
codeScope.syncStack(&scope);
endMethod(methodNode, scope);
}
void Compiler :: compileDefConvConstructor(SNode node, MethodScope& scope)
{
ClassScope* classScope = (ClassScope*)scope.getScope(Scope::ScopeLevel::slClass);
if (test(classScope->info.header.flags, elDynamicRole))
throw InternalError("Invalid constructor");
SNode exprNode = node.insertNode(lxSeqExpression);
if (test(classScope->info.header.flags, elStructureRole)) {
exprNode
.appendNode(lxCreatingStruct, classScope->info.size)
.appendNode(lxType, classScope->reference);
}
else {
exprNode
.appendNode(lxCreatingClass, classScope->info.fields.Count())
.appendNode(lxType, classScope->reference);
}
// call field initilizers if available for default constructor
compileSpecialMethodCall(exprNode, *classScope, scope.moduleScope->init_message);
}
bool Compiler :: isDefaultOrConversionConstructor(Scope& scope, ref_t message, bool& isProtectedDefConst)
{
ref_t actionRef = getAction(message);
if (actionRef == getAction(scope.moduleScope->constructor_message)) {
return true;
}
else if (actionRef == getAction(scope.moduleScope->protected_constructor_message)) {
isProtectedDefConst = true;
return true;
}
else if (getArgCount(message) > 1) {
ref_t dummy = 0;
ident_t actionName = scope.module->resolveAction(actionRef, dummy);
if (actionName.compare(CONSTRUCTOR_MESSAGE2)) {
isProtectedDefConst = true;
return true;
}
else return actionName.endsWith(CONSTRUCTOR_MESSAGE);
}
else return false;
}
void Compiler :: compileConstructor(SNode node, MethodScope& scope, ClassScope& classClassScope)
{
// if it is a default / conversion (unnamed) constructor
bool isProtectedDefConst = false;
bool isDefConvConstructor = isDefaultOrConversionConstructor(scope, scope.message, isProtectedDefConst);
ref_t defConstrMssg = scope.moduleScope->constructor_message;
if (classClassScope.checkAttribute(defConstrMssg, maProtected)) {
// if protected default constructor is declared - use it
defConstrMssg = classClassScope.getAttribute(defConstrMssg, maProtected);
isProtectedDefConst = true;
}
else if (classClassScope.info.methods.exist(defConstrMssg | STATIC_MESSAGE)) {
// if private default constructor is declared - use it
defConstrMssg = defConstrMssg | STATIC_MESSAGE;
}
// SNode attrNode = node.findChild(lxEmbeddableMssg);
// if (attrNode != lxNone) {
// // COMPILER MAGIC : copy an attribute so it will be recognized as embeddable call
// writer.appendNode(attrNode.type, attrNode.argument);
// }
declareProcedureDebugInfo(node, scope, true/*, false*/);
CodeScope codeScope(&scope);
bool retExpr = false;
bool withFrame = false;
int classFlags = codeScope.getClassFlags();
scope.preallocated = 0;
SNode bodyNode = node.findChild(lxResendExpression, lxCode, lxReturning, lxDispatchCode, lxNoBody);
if (bodyNode == lxDispatchCode) {
compileConstructorDispatchExpression(bodyNode, codeScope, scope.message == defConstrMssg);
return;
}
else if (bodyNode == lxResendExpression) {
if (scope.multiMethod && bodyNode.argument != 0) {
compileMultidispatch(bodyNode, codeScope, classClassScope);
bodyNode = SNode();
}
else {
if (isDefConvConstructor && getArgCount(scope.message) <= 1)
scope.raiseError(errInvalidOperation, node);
if (scope.multiMethod) {
compileMultidispatch(bodyNode.parentNode(), codeScope, classClassScope);
}
compileConstructorResendExpression(bodyNode, codeScope, classClassScope, withFrame);
bodyNode = bodyNode.findChild(lxCode);
}
}
else if (bodyNode == lxReturning) {
retExpr = true;
}
else if (isDefConvConstructor && !test(classFlags, elDynamicRole)) {
// if it is a default / conversion (unnamed) constructor
// it should create the object
compileDefConvConstructor(node, scope);
}
// if no redirect statement - call the default constructor
else if (!test(classFlags, elDynamicRole) && classClassScope.info.methods.exist(defConstrMssg)) {
// HOTFIX : use dispatching routine for the protected default constructor
SNode callNode = node.insertNode(lxCalling_1, defConstrMssg);
callNode.appendNode(lxResult);
}
else if (!test(classFlags, elDynamicRole) && test(classFlags, elAbstract)) {
// HOTFIX : allow to call the non-declared default constructor for abstract
// class constructors
SNode callNode = node.insertNode(lxCalling_1, defConstrMssg);
callNode.appendNode(lxResult);
}
// if it is a dynamic object implicit constructor call is not possible
else scope.raiseError(errIllegalConstructor, node);
if (bodyNode != lxNone) {
if (!withFrame) {
if (bodyNode != lxCode) {
bodyNode.injectAndReplaceNode(lxNewFrame);
bodyNode = bodyNode.firstChild();
}
else bodyNode.set(lxNewFrame, 0);
withFrame = true;
// new stack frame
// stack already contains $self value
codeScope.allocated1++;
}
scope.preallocated = codeScope.allocated1;
if (retExpr) {
//ObjectInfo retVal = compileRootExpression(bodyNode, codeScope, codeScope.getClassRefId(), EAttr::eaNone);
//retVal = convertObject(bodyNode, )
compileRootExpression(bodyNode, codeScope, codeScope.getClassRefId(), HINT_DYNAMIC_OBJECT | HINT_NOPRIMITIVES);
}
else {
compileCode(bodyNode, codeScope);
// HOT FIX : returning the created object
bodyNode.appendNode(lxExpression).appendNode(lxLocal, 1);
}
}
else if (withFrame) {
scope.preallocated = codeScope.allocated1;
}
codeScope.syncStack(&scope);
endMethod(node, scope);
}
void Compiler :: compileSpecialMethodCall(SNode& node, ClassScope& classScope, ref_t message)
{
if (classScope.info.methods.exist(message)) {
if (classScope.info.methods.exist(message, true)) {
// call the field in-place initialization
SNode argNode = node.appendNode(lxDirectCalling, message);
argNode.appendNode(lxResult);
argNode.appendNode(lxCallTarget, classScope.reference);
}
else {
ref_t parentRef = classScope.info.header.parentRef;
while (parentRef != 0) {
// call the parent field in-place initialization
ClassInfo parentInfo;
_logic->defineClassInfo(*classScope.moduleScope, parentInfo, parentRef);
if (parentInfo.methods.exist(message, true)) {
SNode argNode = node.appendNode(lxDirectCalling, message);
argNode.appendNode(lxResult);
argNode.appendNode(lxCallTarget, parentRef);
break;
}
parentRef = parentInfo.header.parentRef;
}
}
}
}
//void Compiler :: compileDynamicDefaultConstructor(SyntaxWriter& writer, MethodScope& scope)
//{
// writer.newNode(lxClassMethod, scope.message);
//
// ClassScope* classScope = (ClassScope*)scope.getScope(Scope::slClass);
//
// if (test(classScope->info.header.flags, elStructureRole)) {
// writer.newNode(lxCreatingStruct, classScope->info.size);
// writer.appendNode(lxTarget, classScope->reference);
// writer.closeNode();
// }
// else {
// writer.newNode(lxCreatingClass, -1);
// writer.appendNode(lxTarget, classScope->reference);
// writer.closeNode();
// }
//
// writer.closeNode();
//}
void Compiler :: compileVMT(SNode node, ClassScope& scope, bool exclusiveMode, bool ignoreAutoMultimethods)
{
scope.withInitializers = scope.info.methods.exist(scope.moduleScope->init_message, true);
SNode current = node.firstChild();
while (current != lxNone) {
switch(current) {
case lxStaticFieldInit:
compileCompileTimeAssigning(current, scope);
if (exclusiveMode) {
// HOTFIX : comment out to prevent duplicate compilation for nested classes
current = lxIdle;
}
break;
case lxClassMethod:
{
if (exclusiveMode && (ignoreAutoMultimethods == current.existChild(lxAutoMultimethod))) {
current = current.nextNode();
continue;
}
MethodScope methodScope(&scope);
methodScope.message = current.argument;
#ifdef FULL_OUTOUT_INFO
// info
int x = 0;
scope.moduleScope->printMessageInfo("method %s", methodScope.message);
#endif // FULL_OUTOUT_INFO
initialize(scope, methodScope);
if (methodScope.outputRef) {
// HOTFIX : validate the output type once again in case it was declared later in the code
SNode typeNode = current.findChild(lxType, lxArrayType);
if (typeNode) {
resolveTypeAttribute(typeNode, scope, false, false);
}
else validateType(scope, current, methodScope.outputRef, false, false);
}
// if it is a dispatch handler
if (methodScope.message == scope.moduleScope->dispatch_message) {
compileDispatcher(current, methodScope,
lxClassMethod,
test(scope.info.header.flags, elWithGenerics),
test(scope.info.header.flags, elWithVariadics));
}
// if it is a normal method
else {
declareArgumentList(current, methodScope, false, false);
if (methodScope.abstractMethod) {
if (isMethodEmbeddable(methodScope, current)) {
compileEmbeddableMethod(current, methodScope);
}
else compileAbstractMethod(current, methodScope);
}
else if (isMethodEmbeddable(methodScope, current)) {
// COMPILER MAGIC : if the method retunging value can be passed as an extra argument
compileEmbeddableMethod(current, methodScope);
}
else if (methodScope.yieldMethod) {
compileYieldableMethod(current, methodScope);
}
else compileMethod(current, methodScope);
}
break;
}
}
current = current.nextNode();
}
if (scope.withInitializers && (ignoreAutoMultimethods || !exclusiveMode)) {
// HOTFIX : compileVMT is called twice for nested classes - initializer should be called only once
MethodScope methodScope(&scope);
methodScope.message = scope.moduleScope->init_message;
initialize(scope, methodScope);
// if it is in-place class member initialization
compileInitializer(node, methodScope);
}
// if the VMT conatains newly defined generic handlers, overrides default one
if (testany(scope.info.header.flags, elWithGenerics | elWithVariadics)
&& scope.info.methods.exist(scope.moduleScope->dispatch_message, false))
{
MethodScope methodScope(&scope);
methodScope.message = scope.moduleScope->dispatch_message;
scope.include(methodScope.message);
SNode methodNode = node.appendNode(lxClassMethod, methodScope.message);
scope.info.header.flags |= elWithCustomDispatcher;
compileDispatcher(methodNode, methodScope,
lxClassMethod,
test(scope.info.header.flags, elWithGenerics),
test(scope.info.header.flags, elWithVariadics));
// overwrite the class info
scope.save();
}
}
void Compiler :: compileClassVMT(SNode node, ClassScope& classClassScope, ClassScope& classScope)
{
SNode current = node.firstChild();
while (current != lxNone) {
switch (current) {
case lxConstructor:
{
MethodScope methodScope(&classScope);
methodScope.message = current.argument;
#ifdef FULL_OUTOUT_INFO
// info
int x = 0;
classClassScope.moduleScope->printMessageInfo("method %s", methodScope.message);
#endif // FULL_OUTOUT_INFO
initialize(classClassScope, methodScope);
declareArgumentList(current, methodScope, false, false);
compileConstructor(current, methodScope, classClassScope);
break;
}
case lxStaticMethod:
{
MethodScope methodScope(&classClassScope);
methodScope.message = current.argument;
initialize(classClassScope, methodScope);
declareArgumentList(current, methodScope, false, false);
if (isMethodEmbeddable(methodScope, current)) {
compileEmbeddableMethod(current, methodScope);
}
else compileMethod(current, methodScope);
break;
}
}
current = current.nextNode();
}
// if the VMT conatains newly defined generic handlers, overrides default one
if (testany(classClassScope.info.header.flags, elWithGenerics | elWithVariadics)
&& classClassScope.info.methods.exist(classClassScope.moduleScope->dispatch_message, false))
{
MethodScope methodScope(&classClassScope);
methodScope.message = classClassScope.moduleScope->dispatch_message;
classClassScope.include(methodScope.message);
SNode methodNode = node.appendNode(lxStaticMethod, methodScope.message);
classClassScope.info.header.flags |= elWithCustomDispatcher;
compileDispatcher(methodNode, methodScope,
lxStaticMethod,
test(classClassScope.info.header.flags, elWithGenerics),
test(classClassScope.info.header.flags, elWithVariadics));
// overwrite the class info
classClassScope.save();
}
}
inline int countFields(SNode node)
{
int counter = 0;
SNode current = node.firstChild();
while (current != lxNone) {
if (current == lxClassField) {
counter++;
}
current = current.nextNode();
}
return counter;
}
void Compiler :: validateClassFields(SNode node, ClassScope& scope)
{
SNode current = node.firstChild();
while (current != lxNone) {
if (current == lxClassField) {
SNode typeNode = current.findChild(lxType, lxArrayType);
if (typeNode != lxNone) {
resolveTypeAttribute(typeNode, scope, false, false);
}
}
current = current.nextNode();
}
}
//bool Compiler :: isValidAttributeType(Scope& scope, FieldAttributes& attrs)
//{
//// _ModuleScope* moduleScope = scope.moduleScope;
////
//// if (attrs.isSealedAttr && attrs.isConstAttr)
//// return false;
////
//// //if ()
////
//// //if (size != 0) {
//// // return false;
//// //}
//// //else if (fieldRef == moduleScope->literalReference) {
//// // return true;
//// //}
// /*else */return true;
//}
void Compiler :: generateClassFields(SNode node, ClassScope& scope, bool singleField)
{
SNode current = node.firstChild();
bool isClassClassMode = scope.classClassMode;
while (current != lxNone) {
if (current == lxClassField) {
FieldAttributes attrs;
declareFieldAttributes(current, scope, attrs);
if (attrs.isStaticField || attrs.isConstAttr) {
//if (!isValidAttributeType(scope, attrs))
// scope.raiseError(errIllegalField, current);
generateClassStaticField(scope, current, attrs.fieldRef, attrs.elementRef, attrs.isStaticField, attrs.isConstAttr, attrs.isArray);
}
else if (!isClassClassMode)
generateClassField(scope, current, attrs, singleField);
}
current = current.nextNode();
}
}
void Compiler :: compileSymbolCode(ClassScope& scope)
{
CommandTape tape;
bool publicAttr = scope.info.mattributes.exist(Attribute(caSerializable, 0));
SyntaxTree tree;
SyntaxWriter writer(tree);
generateClassSymbol(writer, scope);
_writer.generateSymbol(tape, tree.readRoot(), false, INVALID_REF);
// create byte code sections
_writer.saveTape(tape, *scope.moduleScope);
compileSymbolAttribtes(*scope.moduleScope, scope.reference, publicAttr);
}
void Compiler :: compilePreloadedExtensionCode(ClassScope& scope)
{
_Module* module = scope.moduleScope->module;
IdentifierString sectionName("'", EXT_INITIALIZER_SECTION);
CommandTape tape;
_writer.generateInitializer(tape, module->mapReference(sectionName), lxClassSymbol, scope.reference);
// create byte code sections
_writer.saveTape(tape, *scope.moduleScope);
}
void Compiler :: compilePreloadedCode(SymbolScope& scope)
{
_Module* module = scope.moduleScope->module;
IdentifierString sectionName("'", INITIALIZER_SECTION);
CommandTape tape;
_writer.generateInitializer(tape, module->mapReference(sectionName), lxSymbolReference, scope.reference);
// create byte code sections
_writer.saveTape(tape, *scope.moduleScope);
}
ref_t Compiler :: compileClassPreloadedCode(_ModuleScope& scope, ref_t classRef, SNode node)
{
_Module* module = scope.module;
IdentifierString sectionName(scope.module->resolveReference(classRef));
sectionName.append(INITIALIZER_SECTION);
ref_t actionRef = module->mapReference(sectionName);
CommandTape tape;
_writer.generateInitializer(tape, actionRef, node);
// create byte code sections
_writer.saveTape(tape, scope);
return actionRef;
}
//void Compiler :: compilePreloadedCode(_ModuleScope& scope, SNode node)
//{
// _Module* module = scope.module;
//
// IdentifierString sectionName("'", INITIALIZER_SECTION);
//
// CommandTape tape;
// _writer.generateInitializer(tape, module->mapReference(sectionName), node);
//
// // create byte code sections
// _writer.saveTape(tape, scope);
//}
void Compiler :: compileClassClassDeclaration(SNode node, ClassScope& classClassScope, ClassScope& classScope)
{
if (classScope.abstractMode || test(classScope.info.header.flags, elDynamicRole)) {
// dynamic class should not have default constructor
classClassScope.abstractMode = true;
}
if (classScope.stackSafe) {
classClassScope.stackSafe = true;
}
// NOTE : class class is not inheritable
classClassScope.info.header.parentRef = classScope.moduleScope->superReference;
compileParentDeclaration(node, classClassScope, classClassScope.info.header.parentRef/*, true*/);
generateClassDeclaration(node, classClassScope);
// generate constructor attributes
ClassInfo::MethodMap::Iterator it = classClassScope.info.methods.start();
while (!it.Eof()) {
int hints = classClassScope.info.methodHints.get(Attribute(it.key(), maHint));
if (test(hints, tpConstructor)) {
classClassScope.info.methodHints.exclude(Attribute(it.key(), maReference));
classClassScope.info.methodHints.add(Attribute(it.key(), maReference), classScope.reference);
}
else if (test(hints, tpSealed | tpStatic) && *it) {
classScope.addAttribute(it.key(), maStaticInherited, classClassScope.reference);
classScope.save();
}
it++;
}
classClassScope.save();
}
void Compiler :: compileClassClassImplementation(SNode node, ClassScope& classClassScope, ClassScope& classScope)
{
//// HOTFIX : due to current implementation the default constructor can be declared as a special method and a constructor;
//// only one is allowed
//if (classScope.withImplicitConstructor && classClassScope.info.methods.exist(encodeAction(DEFAULT_MESSAGE_ID)))
// classScope.raiseError(errOneDefaultConstructor, node.findChild(lxNameAttr));
//if (classClassScope.info.staticValues.Count() > 0)
// copyStaticFieldValues(node, classClassScope);
compileClassVMT(node, classClassScope, classScope);
generateClassImplementation(node, classClassScope);
}
void Compiler :: initialize(ClassScope& scope, MethodScope& methodScope)
{
methodScope.hints = scope.info.methodHints.get(Attribute(methodScope.message, maHint));
methodScope.outputRef = scope.info.methodHints.get(ClassInfo::Attribute(methodScope.message, maReference));
if (test(methodScope.hints, tpInitializer))
methodScope.scopeMode = methodScope.scopeMode | INITIALIZER_SCOPE;
//// methodScope.dispatchMode = _logic->isDispatcher(scope.info, methodScope.message);
methodScope.classStacksafe= _logic->isStacksafeArg(scope.info);
methodScope.withOpenArg = isOpenArg(methodScope.message);
methodScope.extensionMode = scope.extensionClassRef != 0;
methodScope.functionMode = test(methodScope.message, FUNCTION_MESSAGE);
methodScope.multiMethod = _logic->isMultiMethod(scope.info, methodScope.message);
methodScope.abstractMethod = _logic->isMethodAbstract(scope.info, methodScope.message);
methodScope.yieldMethod = _logic->isMethodYieldable(scope.info, methodScope.message);
methodScope.generic = _logic->isMethodGeneric(scope.info, methodScope.message);
if (_logic->isMixinMethod(scope.info, methodScope.message)) {
if (methodScope.withOpenArg && methodScope.functionMode)
methodScope.mixinFunction = true;
}
methodScope.targetSelfMode = test(methodScope.hints, tpTargetSelf);
methodScope.constMode = test(methodScope.hints, tpConstant);
}
void Compiler :: declareVMT(SNode node, ClassScope& scope, bool& withConstructors, bool& withDefaultConstructor)
{
SNode current = node.firstChild();
while (current != lxNone) {
if (current.compare(lxFieldInit, lxFieldAccum)) {
scope.withInitializers = true;
}
else if (current == lxClassMethod) {
MethodScope methodScope(&scope);
declareMethodAttributes(current, methodScope);
if (current.argument == 0) {
if (scope.extensionClassRef != 0)
methodScope.extensionMode = true;
// NOTE : an extension message must be strong-resolved
declareArgumentList(current, methodScope, methodScope.extensionMode | test(scope.info.header.flags, elNestedClass), true);
current.setArgument(methodScope.message);
}
else methodScope.message = current.argument;
if (test(methodScope.hints, tpConstructor)) {
if ((_logic->isAbstract(scope.info) || scope.abstractMode) && !methodScope.isPrivate()
&& !test(methodScope.hints, tpProtected))
{
// abstract class cannot have nonpublic constructors
scope.raiseError(errIllegalConstructorAbstract, current);
}
else current = lxConstructor;
withConstructors = true;
if ((methodScope.message & ~STATIC_MESSAGE) == scope.moduleScope->constructor_message) {
withDefaultConstructor = true;
}
else if (getArgCount(methodScope.message) == 1 && test(methodScope.hints, tpProtected)) {
// check if it is protected default constructor
ref_t dummy = 0;
ident_t actionName = scope.module->resolveAction(getAction(methodScope.message), dummy);
if (actionName.endsWith(CONSTRUCTOR_MESSAGE))
withDefaultConstructor = true;
}
}
else if (test(methodScope.hints, tpPredefined)) {
// recognize predefined message signatures
predefineMethod(current, scope, methodScope);
current = lxIdle;
}
else if (test(methodScope.hints, tpStatic)) {
current = lxStaticMethod;
}
else if (test(methodScope.hints, tpYieldable)) {
scope.info.header.flags |= elWithYieldable;
// HOTFIX : the class should have intializer method
scope.withInitializers = true;
}
if (!_logic->validateMessage(*methodScope.moduleScope, methodScope.message, methodScope.hints)) {
if (test(methodScope.hints, tpConstant)) {
scope.raiseError(errInvalidConstAttr, current);
}
else scope.raiseError(errIllegalMethod, current);
}
}
current = current.nextNode();
}
}
void Compiler :: generateClassFlags(ClassScope& scope, SNode root)
{
// ref_t extensionTypeRef = 0;
SNode current = root.firstChild();
while (current != lxNone) {
if (current == lxClassFlag) {
scope.info.header.flags |= current.argument;
//// if (test(current.argument, elExtension)) {
//// SNode argRef = current.findChild(lxClassRefAttr, lxAttribute);
//// if (argRef == lxClassRefAttr) {
//// extensionTypeRef = scope.moduleScope->mapFullReference(argRef.identifier(), true);
//// }
//// else if (argRef == lxAttribute) {
//// if (argRef.argument == V_ARGARRAY) {
//// // HOTFIX : recognize open argument extension
//// extensionTypeRef = V_ARGARRAY;
//// }
//// else scope.raiseError(errInvalidHint, root);
//// }
//// }
}
//// else if (current == lxTarget) {
//// extensionTypeRef = current.argument;
//// }
current = current.nextNode();
}
// check if extension is qualified
bool extensionMode = test(scope.info.header.flags, elExtension);
if (extensionMode) {
scope.info.fieldTypes.add(-1, ClassInfo::FieldInfo(scope.extensionClassRef, 0));
}
}
void Compiler :: generateClassField(ClassScope& scope, SyntaxTree::Node current, FieldAttributes& attrs, bool singleField)
{
ref_t classRef = attrs.fieldRef;
ref_t elementRef = attrs.elementRef;
int sizeHint = attrs.size;
bool embeddable = attrs.isEmbeddable;
if (sizeHint == -1) {
if (singleField) {
scope.info.header.flags |= elDynamicRole;
}
else if (!test(scope.info.header.flags, elStructureRole)) {
classRef = resolvePrimitiveArray(scope,
scope.moduleScope->arrayTemplateReference,
classRef, false);
}
else scope.raiseError(errIllegalField, current);
sizeHint = 0;
}
int flags = scope.info.header.flags;
int offset = 0;
ident_t terminal = current.findChild(lxNameAttr).firstChild(lxTerminalMask).identifier();
// a role cannot have fields
if (test(flags, elStateless))
scope.raiseError(errIllegalField, current);
int size = (classRef != 0) ? _logic->defineStructSize(*scope.moduleScope, classRef, elementRef) : 0;
bool fieldArray = false;
if (sizeHint != 0) {
if (isPrimitiveRef(classRef) && (size == sizeHint || (classRef == V_INT32 && sizeHint <= size))) {
// for primitive types size should be specified
size = sizeHint;
}
else if (size > 0) {
size *= sizeHint;
// HOTFIX : to recognize the fixed length array
if (elementRef == 0 && !isPrimitiveRef(classRef))
elementRef = classRef;
fieldArray = true;
classRef = _logic->definePrimitiveArray(*scope.moduleScope, elementRef, true);
}
else scope.raiseError(errIllegalField, current);
}
if (test(flags, elWrapper) && scope.info.fields.Count() > 0) {
// wrapper may have only one field
scope.raiseError(errIllegalField, current);
}
// if the sealed class has only one strong typed field (structure) it should be considered as a field wrapper
else if (embeddable && !fieldArray) {
if (!singleField || scope.info.fields.Count() > 0)
scope.raiseError(errIllegalField, current);
// if the sealed class has only one strong typed field (structure) it should be considered as a field wrapper
if (test(scope.info.header.flags, elSealed)) {
scope.info.header.flags |= elWrapper;
if (size > 0 && !test(scope.info.header.flags, elNonStructureRole))
scope.info.header.flags |= elStructureRole;
}
}
// a class with a dynamic length structure must have no fields
if (test(scope.info.header.flags, elDynamicRole)) {
if (scope.info.size == 0 && scope.info.fields.Count() == 0) {
// compiler magic : turn a field declaration into an array or string one
if (size > 0 && !test(scope.info.header.flags, elNonStructureRole)) {
scope.info.header.flags |= elStructureRole;
scope.info.size = -size;
}
ref_t arrayRef = _logic->definePrimitiveArray(*scope.moduleScope, classRef, test(scope.info.header.flags, elStructureRole));
scope.info.fieldTypes.add(-1, ClassInfo::FieldInfo(arrayRef, classRef));
scope.info.fields.add(terminal, -2);
}
else scope.raiseError(errIllegalField, current);
}
else {
if (scope.info.fields.exist(terminal)) {
//if (current.argument == INVALID_REF) {
// //HOTFIX : ignore duplicate autogenerated fields
// return;
//}
/*else */scope.raiseError(errDuplicatedField, current);
}
// if it is a structure field
if (test(scope.info.header.flags, elStructureRole)) {
if (size <= 0)
scope.raiseError(errIllegalField, current);
if (scope.info.size != 0 && scope.info.fields.Count() == 0)
scope.raiseError(errIllegalField, current);
offset = scope.info.size;
scope.info.size += size;
scope.info.fields.add(terminal, offset);
scope.info.fieldTypes.add(offset, ClassInfo::FieldInfo(classRef, elementRef));
if (isPrimitiveRef(classRef))
_logic->tweakPrimitiveClassFlags(classRef, scope.info);
}
// if it is a normal field
else {
// primitive / virtual classes cannot be declared
if (size != 0 && isPrimitiveRef(classRef))
scope.raiseError(errIllegalField, current);
scope.info.header.flags |= elNonStructureRole;
offset = scope.info.fields.Count();
scope.info.fields.add(terminal, offset);
if (classRef != 0)
scope.info.fieldTypes.add(offset, ClassInfo::FieldInfo(classRef, 0));
}
}
// if (attrs.messageRef != 0) {
// scope.addAttribute(attrs.messageRef, attrs.messageAttr, offset);
// }
}
inline SNode findInitNode(SNode node, ident_t name)
{
SNode current = node.firstChild();
while (current != lxNone) {
if (current == lxFieldInit) {
SNode terminalNode = current.firstChild(lxTerminalMask);
if (terminalNode.identifier().compare(name))
break;
}
current = current.nextNode();
}
return current;
}
void Compiler :: generateClassStaticField(ClassScope& scope, SNode current, ref_t fieldRef, ref_t, bool isStatic,
bool isConst, bool isArray)
{
_Module* module = scope.module;
ident_t terminal = current.findChild(lxNameAttr).firstChild(lxTerminalMask).identifier();
if (scope.info.statics.exist(terminal)) {
if (current.argument == INVALID_REF) {
//HOTFIX : ignore duplicate autogenerated fields
return;
}
else scope.raiseError(errDuplicatedField, current);
}
if (isStatic) {
// if it is a static field
ref_t ref = current.argument;
if (!ref) {
// generate static reference
IdentifierString name(module->resolveReference(scope.reference));
name.append(STATICFIELD_POSTFIX);
ref = scope.moduleScope->mapAnonymous(name.c_str());
current.setArgument(ref);
}
scope.info.statics.add(terminal, ClassInfo::FieldInfo(ref, fieldRef));
if (isConst) {
// HOTFIX : add read-only attribute (!= mskStatRef)
scope.info.staticValues.add(ref, mskConstantRef);
}
}
else {
if (scope.classClassMode) {
int index = current.findChild(lxStatIndex).argument;
ref_t statRef = current.findChild(lxStatConstRef).argument;
if (!statRef)
throw InternalError("Cannot compile const field"); // !! temporal
scope.info.statics.add(terminal, ClassInfo::FieldInfo(index, fieldRef));
scope.info.staticValues.add(index, statRef);
}
else {
int index = ++scope.info.header.staticSize;
index = -index - 4;
scope.info.statics.add(terminal, ClassInfo::FieldInfo(index, fieldRef));
if (isConst) {
ref_t statRef = 0;
// HOTFIX : constant must have initialization part
SNode initNode = findInitNode(current.parentNode(), terminal);
if (initNode != lxNone) {
SNode assignNode = initNode.findChild(lxAssign).nextNode(lxObjectMask);
if (assignNode == lxExpression)
assignNode = assignNode.firstChild();
if (assignNode == lxMetaConstant) {
// HOTFIX : recognize meta constants
if (assignNode.identifier().compare(CLASSNAME_VAR)) {
statRef = CLASSNAME_CONST;
// comment out the initializer
initNode = lxIdle;
}
else if (assignNode.identifier().compare(PACKAGE_VAR)) {
statRef = PACKAGE_CONST;
// comment out the initializer
initNode = lxIdle;
}
else if (assignNode.identifier().compare(SUBJECT_VAR)) {
ref_t subjRef = resolveSubjectVar(current);
if (subjRef) {
assignNode.set(lxSubjectRef, subjRef);
statRef = mapStaticField(scope.moduleScope, scope.reference, isArray);
}
else scope.raiseError(errInvalidOperation, current);
}
else scope.raiseError(errInvalidOperation, current);
}
else statRef = mapStaticField(scope.moduleScope, scope.reference, isArray);
}
else if (isArray) {
//HOTFIX : allocate an empty array
statRef = mapStaticField(scope.moduleScope, scope.reference, isArray);
auto section = scope.module->mapSection((statRef & ~mskAnyRef) | mskRDataRef, false);
section->addReference(fieldRef | mskVMTRef, (ref_t)-4);
}
else scope.raiseError(errInvalidOperation, current);
scope.info.staticValues.add(index, statRef);
current.appendNode(lxStatConstRef, statRef);
current.appendNode(lxStatIndex, index);
}
else scope.raiseError(errDuplicatedField, current);
//else scope.info.staticValues.add(index, (ref_t)mskStatRef);
}
}
}
inline SNode findName(SNode node)
{
return node.findChild(lxNameAttr).firstChild(lxTerminalMask);
}
void Compiler :: generateMethodAttributes(ClassScope& scope, SNode node, ref_t message, bool allowTypeAttribute)
{
ref_t outputRef = scope.info.methodHints.get(Attribute(message, maReference));
bool hintChanged = false, outputChanged = false;
int hint = scope.info.methodHints.get(Attribute(message, maHint));
SNode current = node.firstChild();
while (current != lxNone) {
if (current == lxAttribute) {
if (test(current.argument, tpAbstract)) {
if (!_logic->isAbstract(scope.info))
// only abstract class may have an abstract methods
scope.raiseError(errNotAbstractClass, current);
if (scope.info.methods.exist(message))
// abstract method should be newly declared
scope.raiseError(errNoMethodOverload, current);
}
hint |= current.argument;
hintChanged = true;
}
else if (current.compare(lxType, lxArrayType)) {
if (!allowTypeAttribute) {
scope.raiseError(errTypeNotAllowed, node);
}
else {
ref_t ref = resolveTypeAttribute(current, scope, true, false);
if (!outputRef) {
outputRef = ref;
}
else if (outputRef != ref)
scope.raiseError(errTypeAlreadyDeclared, node);
outputChanged = true;
}
}
current = current.nextNode();
}
if (test(hint, tpPrivate)) {
if (scope.info.methods.exist(message & ~STATIC_MESSAGE)) {
// there should be no public method with the same name
scope.raiseError(errDupPublicMethod, findName(node));
}
// if it is private message save the visibility attribute
else scope.addAttribute(message & ~STATIC_MESSAGE, maPrivate, message);
}
else if (testany(hint, tpInternal | tpProtected)) {
// if it is internal / protected message save the visibility attribute
ref_t signRef = 0;
ident_t name = scope.module->resolveAction(getAction(message), signRef);
ref_t publicMessage = 0;
if (name.compare(CONSTRUCTOR_MESSAGE2)) {
publicMessage = scope.moduleScope->constructor_message;
}
else {
int index = name.find("$$");
if (index == NOTFOUND_POS)
scope.raiseError(errDupInternalMethod, findName(node));
publicMessage = overwriteAction(message, scope.module->mapAction(name + index + 2, 0, false));
}
if (scope.info.methods.exist(publicMessage)) {
// there should be no public method with the same name
scope.raiseError(errDupPublicMethod, findName(node));
}
// if it is protected / internal message save the visibility attribute
else if (test(hint, tpProtected)) {
scope.addAttribute(publicMessage, maProtected, message);
}
else scope.addAttribute(publicMessage, maInternal, message);
}
if (outputRef) {
if (outputRef == scope.reference && _logic->isEmbeddable(scope.info)) {
hintChanged = true;
hint |= tpEmbeddable;
}
else if (_logic->isEmbeddable(*scope.moduleScope, outputRef)) {
hintChanged = true;
hint |= tpEmbeddable;
}
}
if (hintChanged) {
scope.addHint(message, hint);
}
if (outputChanged) {
scope.info.methodHints.add(Attribute(message, maReference), outputRef);
}
else if (outputRef != 0 && !node.existChild(lxAutogenerated) && !test(hint, tpConstructor)
&& outputRef != scope.moduleScope->superReference)
{
//warn if the method output was not redeclared, ignore auto generated methods
//!!hotfix : ignore the warning for the constructor
scope.raiseWarning(WARNING_LEVEL_1, wrnTypeInherited, node);
}
}
void Compiler :: saveExtension(ClassScope& scope, ref_t message, bool internalOne)
{
ref_t extensionMessage = 0;
// get generic message
ref_t signRef = 0;
ident_t actionName = scope.module->resolveAction(getAction(message), signRef);
if (signRef) {
extensionMessage = overwriteAction(message, scope.module->mapAction(actionName, 0, false));
if (test(extensionMessage, VARIADIC_MESSAGE))
extensionMessage = overwriteArgCount(extensionMessage, 2);
}
else extensionMessage = message;
// exclude function flag
extensionMessage = extensionMessage & ~FUNCTION_MESSAGE;
NamespaceScope* nsScope = (NamespaceScope*)scope.getScope(Scope::ScopeLevel::slNamespace);
nsScope->saveExtension(extensionMessage, scope.reference, message, internalOne);
}
//inline bool isGeneralMessage(_Module* module, ref_t message)
//{
// if (getParamCount(message) == 0) {
// return true;
// }
// else {
// ref_t signRef = 0;
// module->resolveAction(getAction(message), signRef);
//
// return signRef == 0;
// }
//}
void Compiler :: predefineMethod(SNode node, ClassScope& classScope, MethodScope& scope)
{
SNode body = node.findChild(lxCode);
if (body != lxCode || body.firstChild() != lxEOP)
scope.raiseError(errPedefineMethodCode, node);
if (test(scope.hints, tpAbstract) || (scope.hints & tpMask) == tpPrivate)
// abstract or private methods cannot be predefined
scope.raiseError(errIllegalMethod, node);
if (scope.extensionMode)
// an extension cannot have predefined methods
scope.raiseError(errIllegalMethod, node);
ref_t signRef;
scope.module->resolveAction(scope.message, signRef);
if (signRef)
// a predefine method should not contain a strong typed signature
scope.raiseError(errIllegalMethod, node);
generateMethodAttributes(classScope, node, scope.message, true);
}
inline bool checkNonpublicDuplicates(ClassInfo& info, ref_t publicMessage)
{
for (auto it = info.methodHints.start(); !it.Eof(); it++) {
Attribute key = it.key();
if (key.value1 == publicMessage && (key.value2 == maPrivate || key.value2 == maProtected || key.value2 == maInternal))
return true;
}
return false;
}
inline bool isDeclaredProtected(ClassInfo& info, ref_t publicMessage, ref_t& protectedMessage)
{
for (auto it = info.methodHints.start(); !it.Eof(); it++) {
Attribute key = it.key();
if (key.value1 == publicMessage && (key.value2 == maProtected)) {
protectedMessage = *it;
return true;
}
}
return false;
}
void Compiler :: generateParamNameInfo(ClassScope& scope, SNode node, ref_t message)
{
SNode current = node.findChild(lxMethodParameter);
while (current != lxNone) {
if (current == lxMethodParameter) {
ident_t terminal = current.findChild(lxNameAttr).firstChild(lxTerminalMask).identifier();
Attribute key(caParamName, message);
scope.info.mattributes.add(key, saveMetaInfo(*scope.moduleScope, terminal));
}
current = current.nextNode();
}
}
void Compiler :: generateMethodDeclaration(SNode current, ClassScope& scope, bool hideDuplicates, bool closed,
bool allowTypeAttribute)
{
ref_t message = current.argument;
if (scope.info.methods.exist(message, true) && hideDuplicates) {
// ignoring autogenerated duplicates
current = lxIdle;
return;
}
generateMethodAttributes(scope, current, message, allowTypeAttribute);
generateParamNameInfo(scope, current, message);
int methodHints = scope.info.methodHints.get(ClassInfo::Attribute(message, maHint));
if (isOpenArg(message)) {
scope.info.header.flags |= elWithVariadics;
}
else if (_logic->isMethodGeneric(scope.info, message)) {
scope.info.header.flags |= elWithGenerics;
}
// check if there is no duplicate method
if (scope.info.methods.exist(message, true)) {
scope.raiseError(errDuplicatedMethod, current);
}
else {
bool privateOne = (methodHints & tpMask) == tpPrivate;
bool included = scope.include(message);
bool sealedMethod = (methodHints & tpMask) == tpSealed;
// if the class is closed, no new methods can be declared
// except private sealed ones (which are declared outside the class VMT)
if (included && closed && !privateOne) {
//ref_t dummy = 0;
//ident_t msg = scope.module->resolveAction(getAction(message), dummy);
scope.moduleScope->printMessageInfo(infoNewMethod, message);
scope.raiseError(errClosedParent, findParent(current, lxClass/*, lxNestedClass*/));
}
// if the method is sealed, it cannot be overridden
if (!included && sealedMethod/* && !test(methodHints, tpAbstract)*/) {
scope.raiseError(errClosedMethod, findParent(current, lxClass/*, lxNestedClass*/));
}
// HOTFIX : make sure there are no duplicity between public and private / internal / statically linked ones
if (!test(message, STATIC_MESSAGE)) {
if (scope.info.methods.exist(message | STATIC_MESSAGE))
scope.raiseError(errDuplicatedMethod, current);
}
if (!privateOne && !testany(methodHints, tpInternal | tpProtected)) {
if (checkNonpublicDuplicates(scope.info, message))
scope.raiseError(errDuplicatedMethod, current);
}
if (_logic->isStacksafeArg(scope.info) && !test(methodHints, tpMultimethod)) {
// add a stacksafe attribute for the embeddable structure automatically, except multi-methods
methodHints |= tpStackSafe;
scope.addHint(message, tpStackSafe);
if (privateOne) {
// HOTFIX : if it is private message save its hints as public one
scope.addHint(message & ~STATIC_MESSAGE, tpStackSafe);
}
}
if (!included && test(methodHints, tpAbstract)) {
scope.removeHint(message, tpAbstract);
}
if (test(methodHints, tpPredefined)) {
// exclude the predefined attribute from declared method
scope.removeHint(message, tpPredefined);
}
if (test(scope.info.header.flags, elExtension) && (privateOne || test(methodHints, tpInternal)))
// private / internal methods cannot be declared in the extension
scope.raiseError(errIllegalPrivate, current);
if (test(scope.info.header.flags, elExtension) && !privateOne && !scope.extensionDispatcher) {
// HOTFIX : ignore auto generated multi-methods
if (!current.existChild(lxAutoMultimethod))
saveExtension(scope, message, scope.visibility != Visibility::Public);
}
if (!closed && test(methodHints, tpEmbeddable)
&& !testany(methodHints, tpDispatcher | tpFunction | tpConstructor | tpConversion | tpGeneric | tpCast)
&& !test(message, VARIADIC_MESSAGE)
&& !current.existChild(lxDispatchCode, lxResendExpression))
{
// COMPILER MAGIC : if embeddable returning argument is allowed
ref_t outputRef = scope.info.methodHints.get(Attribute(message, maReference));
bool embeddable = false;
bool multiret = false;
if (test(methodHints, tpSetAccessor)) {
// HOTFIX : the result of set accessor should not be embeddable
}
else if (outputRef == scope.reference && _logic->isEmbeddable(scope.info)) {
embeddable = true;
}
else if (_logic->isEmbeddable(*scope.moduleScope, outputRef)) {
embeddable = true;
}
else if (test(methodHints, tpMultiRetVal)) {
// supporting return value dispatching for dynamic types as well
// when it is required
multiret = true;
}
if (embeddable) {
ref_t dummy, flags;
int argCount;
decodeMessage(message, dummy, argCount, flags);
// declare a method with an extra argument - retVal
IdentifierString privateName(EMBEDDAMLE_PREFIX);
ref_t signRef = 0;
privateName.append(scope.module->resolveAction(getAction(message), signRef));
ref_t signArgs[ARG_COUNT];
size_t signLen = scope.module->resolveSignature(signRef, signArgs);
if (signLen == (size_t)argCount - 1) {
// HOTFIX : inject emmeddable returning argument attribute only if the message is strong
signArgs[signLen++] = resolvePrimitiveReference(scope, V_WRAPPER, outputRef, true);
ref_t embeddableMessage = encodeMessage(
scope.module->mapAction(privateName.c_str(), scope.module->mapSignature(signArgs, signLen, false), false),
argCount + 1,
flags);
if (!test(scope.info.header.flags, elSealed) || scope.info.methods.exist(embeddableMessage)) {
scope.include(embeddableMessage);
}
else embeddableMessage |= STATIC_MESSAGE;
scope.addAttribute(message, maEmbeddableRet, embeddableMessage);
}
}
else if (multiret) {
ref_t actionRef, flags;
ref_t signRef = 0;
int argCount;
decodeMessage(message, actionRef, argCount, flags);
ident_t actionName = scope.module->resolveAction(actionRef, signRef);
if (argCount > 1 && signRef != 0) {
ref_t signArgs[ARG_COUNT];
size_t signLen = scope.module->resolveSignature(signRef, signArgs);
signLen--;
argCount--;
if (signLen > 0) {
signRef = scope.module->mapSignature(signArgs, signLen, false);
}
else signRef = 0;
ref_t targetMessage = encodeMessage(
scope.module->mapAction(actionName, signRef, false),
argCount,
flags);
scope.addAttribute(targetMessage, maEmbeddableRet, message);
}
else scope.raiseError(errInvalidHint, current);
}
}
}
}
ref_t Compiler :: resolveMultimethod(ClassScope& scope, ref_t messageRef)
{
int argCount = 0;
ref_t actionRef = 0, flags = 0, signRef = 0;
decodeMessage(messageRef, actionRef, argCount, flags);
if (test(messageRef, FUNCTION_MESSAGE)) {
if (argCount == 0)
return 0;
}
else if (argCount == 1)
return 0;
ident_t actionStr = scope.module->resolveAction(actionRef, signRef);
if (test(flags, VARIADIC_MESSAGE)) {
// COMPILER MAGIC : for variadic message - use the most general message
ref_t genericActionRef = scope.moduleScope->module->mapAction(actionStr, 0, false);
int genericArgCount = 2;
// HOTFIX : a variadic extension is a special case of variadic function
// - so the target should be included as well
if (test(messageRef, FUNCTION_MESSAGE) && scope.extensionClassRef == 0)
genericArgCount = 1;
ref_t genericMessage = encodeMessage(genericActionRef, genericArgCount, flags);
return genericMessage;
}
else if (signRef) {
ref_t genericActionRef = scope.moduleScope->module->mapAction(actionStr, 0, false);
ref_t genericMessage = encodeMessage(genericActionRef, argCount, flags);
return genericMessage;
}
return 0;
}
void Compiler :: generateMethodDeclarations(SNode root, ClassScope& scope, bool closed, LexicalType methodType,
bool allowTypeAttribute)
{
//bool extensionMode = scope.extensionClassRef != 0;
bool templateMethods = false;
List<ref_t> implicitMultimethods;
// first pass - mark all multi-methods
SNode current = root.firstChild();
while (current != lxNone) {
if (current == methodType) {
ref_t multiMethod = resolveMultimethod(scope, current.argument);
if (multiMethod) {
//COMPILER MAGIC : if explicit signature is declared - the compiler should contain the virtual multi method
Attribute attr(current.argument, maMultimethod);
scope.info.methodHints.exclude(attr);
scope.info.methodHints.add(attr, multiMethod);
if (retrieveIndex(implicitMultimethods.start(), multiMethod) == -1) {
implicitMultimethods.add(multiMethod);
templateMethods = true;
// HOTFIX : mark the generic message as a multi-method
scope.addHint(multiMethod, tpMultimethod);
}
}
}
current = current.nextNode();
}
// second pass - ignore template based / autogenerated methods
current = root.firstChild();
while (current != lxNone) {
if (current == methodType) {
if (!current.existChild(lxAutogenerated)) {
generateMethodDeclaration(current, scope, false, closed, allowTypeAttribute);
}
else templateMethods = true;
}
current = current.nextNode();
}
//COMPILER MAGIC : if strong signature is declared - the compiler should contain the virtual multi method
if (implicitMultimethods.Count() > 0) {
_logic->injectVirtualMultimethods(*scope.moduleScope, root, *this, implicitMultimethods, methodType, scope.info);
}
if (templateMethods) {
// third pass - do not include overwritten template-based methods
current = root.firstChild();
while (current != lxNone) {
if (current.existChild(lxAutogenerated) && (current == methodType)) {
generateMethodDeclaration(current, scope, true, closed, allowTypeAttribute);
}
current = current.nextNode();
}
}
if (implicitMultimethods.Count() > 0)
_logic->verifyMultimethods(*scope.moduleScope, root, scope.info, implicitMultimethods);
}
void Compiler :: generateClassDeclaration(SNode node, ClassScope& scope, bool nestedDeclarationMode)
{
bool closed = test(scope.info.header.flags, elClosed);
if (scope.classClassMode) {
// generate static fields
generateClassFields(node, scope, countFields(node) == 1);
}
else {
// HOTFIX : flags / fields should be compiled only for the class itself
generateClassFlags(scope, node);
//// if (test(scope.info.header.flags, elExtension)) {
//// scope.extensionClassRef = scope.info.fieldTypes.get(-1).value1;
//// }
// inject virtual fields
_logic->injectVirtualFields(*scope.moduleScope, node, scope.reference, scope.info, *this);
// generate fields
generateClassFields(node, scope, countFields(node) == 1);
if (_logic->isStacksafeArg(scope.info))
scope.stackSafe = true;
if (scope.extensionClassRef != 0 && _logic->isStacksafeArg(*scope.moduleScope, scope.extensionClassRef))
scope.stackSafe = true;
if (scope.withInitializers) {
// HOTFIX : recognize compile-time assinging
if (!recognizeCompileTimeAssigning(node, scope)) {
// add special method initalizer
scope.include(scope.moduleScope->init_message);
int attrValue = V_INITIALIZER;
bool dummy = false;
_logic->validateMethodAttribute(attrValue, dummy);
scope.addAttribute(scope.moduleScope->init_message, maHint, attrValue);
}
}
}
_logic->injectVirtualCode(*scope.moduleScope, node, scope.reference, scope.info, *this, closed);
// generate methods
if (scope.classClassMode) {
generateMethodDeclarations(node, scope, closed, lxConstructor, false);
generateMethodDeclarations(node, scope, closed, lxStaticMethod, true);
}
else generateMethodDeclarations(node, scope, closed, lxClassMethod, true);
bool withAbstractMethods = false;
bool disptacherNotAllowed = false;
bool emptyStructure = false;
_logic->validateClassDeclaration(*scope.moduleScope, scope.info, withAbstractMethods, disptacherNotAllowed, emptyStructure);
if (withAbstractMethods) {
scope.raiseError(errAbstractMethods, node);
}
if (disptacherNotAllowed)
scope.raiseError(errDispatcherInInterface, node);
if (emptyStructure)
scope.raiseError(errEmptyStructure, node.findChild(lxNameAttr));
// do not set flags for closure declaration - they will be set later
if (!nestedDeclarationMode) {
_logic->tweakClassFlags(*scope.moduleScope, *this, scope.reference, scope.info, scope.classClassMode);
}
}
void Compiler :: declareMethodAttributes(SNode node, MethodScope& scope)
{
SNode current = node.firstChild();
while (current != lxNone) {
bool explicitMode = false;
if (current == lxAttribute) {
int value = current.argument;
if (_logic->validateMethodAttribute(value, explicitMode)) {
scope.hints |= value;
current.setArgument(value);
}
else {
current.setArgument(0);
scope.raiseWarning(WARNING_LEVEL_1, wrnInvalidHint, current);
}
}
else if (current.compare(lxType, lxArrayType)) {
// if it is a type attribute
scope.outputRef = resolveTypeAttribute(current, scope, true, false);
}
else if (current == lxNameAttr && !explicitMode) {
// resolving implicit method attributes
int attr = scope.moduleScope->attributes.get(current.firstChild(lxTerminalMask).identifier());
if (_logic->validateImplicitMethodAttribute(attr/*, current.nextNode().type == lxMessage*/)) {
scope.hints |= attr;
current.set(lxAttribute, attr);
}
}
current = current.nextNode();
}
}
//inline SNode findBaseParent(SNode node)
//{
// SNode baseNode = node.findChild(lxBaseParent);
// //if (baseNode != lxNone) {
// // if (baseNode.argument == -1 && existChildWithArg(node, lxBaseParent, 0u)) {
// // // HOTFIX : allow to override the template parent
// // baseNode = lxIdle;
// // baseNode = node.findChild(lxBaseParent);
// // }
// //}
//
// return baseNode;
//}
ref_t Compiler :: resolveParentRef(SNode node, Scope& scope, bool silentMode)
{
ref_t parentRef = 0;
if (node == lxNone) {
}
else {
SNode typeNode = node.findChild(lxType);
parentRef = resolveTypeAttribute(typeNode, scope, silentMode, false);
}
// else if (test(node.type, lxTerminalMask)) {
// parentRef = resolveImplicitIdentifier(scope, node);
// }
// else if (node.existChild(lxTypeAttribute)) {
// // if it is a template based class
// parentRef = resolveTemplateDeclaration(node, scope, silentMode);
// }
// else parentRef = resolveImplicitIdentifier(scope, node.firstChild(lxTerminalMask));
//
// if (parentRef == 0 && !silentMode)
// scope.raiseError(errUnknownClass, node);
return parentRef;
}
ref_t Compiler :: retrieveImplicitIdentifier(NamespaceScope& scope, ident_t identifier, bool referenceOne, bool innermost)
{
ref_t reference = scope.resolveImplicitIdentifier(identifier, false, innermost);
if (!reference && scope.parent != nullptr) {
NamespaceScope* parentScope = (NamespaceScope*)scope.parent->getScope(Scope::ScopeLevel::slNamespace);
if (parentScope)
return retrieveImplicitIdentifier(*parentScope, identifier, referenceOne, false);
}
return reference;
}
void Compiler :: importClassMembers(SNode classNode, SNode importNode, NamespaceScope& scope)
{
SNode nameNode = importNode.firstChild(lxTerminalMask);
List<SNode> parameters;
IdentifierString templateName;
templateName.copy(nameNode.identifier());
SNode current = importNode.findChild(lxType);
while (current == lxType) {
parameters.add(current);
current = current.nextNode();
}
templateName.append('#');
templateName.appendInt(parameters.Count());
ref_t templateRef = retrieveImplicitIdentifier(scope, templateName.c_str(), false, true);
if (!templateRef)
scope.raiseError(errInvalidSyntax, importNode);
SyntaxTree bufferTree;
SyntaxWriter bufferWriter(bufferTree);
bufferWriter.newNode(lxRoot);
scope.moduleScope->importClassTemplate(bufferWriter, templateRef, parameters);
bufferWriter.closeNode();
SyntaxTree::copyNode(bufferTree.readRoot(), classNode);
}
void Compiler :: compileClassDeclaration(SNode node, ClassScope& scope)
{
bool extensionDeclaration = isExtensionDeclaration(node);
compileParentDeclaration(node.findChild(lxParent), scope, extensionDeclaration);
if (scope.visibility == Visibility::Public) {
// add seriazible meta attribute for the public class
scope.info.mattributes.add(Attribute(caSerializable, 0), INVALID_REF);
}
// COMPILER MAGIC : "inherit" sealed static methods
for (auto a_it = scope.info.methodHints.start(); !a_it.Eof(); a_it++) {
auto key = a_it.key();
if (key.value2 == maStaticInherited) {
SNode methNode = node.insertNode(lxStaticMethod, key.value1);
methNode
.appendNode(lxResendExpression)
.appendNode(lxImplicitJump, key.value1)
.appendNode(lxCallTarget, *a_it);
}
}
bool withConstructors = false;
bool withDefaultConstructor = false;
declareVMT(node, scope, withConstructors, withDefaultConstructor);
// NOTE : generateClassDeclaration should be called for the proper class before a class class one
// due to dynamic array implementation (auto-generated default constructor should be removed)
generateClassDeclaration(node, scope);
if (_logic->isRole(scope.info)) {
// class is its own class class
scope.info.header.classRef = scope.reference;
}
else {
// define class class name
IdentifierString classClassName(scope.moduleScope->resolveFullName(scope.reference));
classClassName.append(CLASSCLASS_POSTFIX);
scope.info.header.classRef = scope.moduleScope->module->mapReference(classClassName);
}
// if it is a super class validate it, generate built-in attributes
if (scope.info.header.parentRef == 0 && scope.reference == scope.moduleScope->superReference) {
if (!scope.info.methods.exist(scope.moduleScope->dispatch_message))
scope.raiseError(errNoDispatcher, node);
// HOTFIX - constant fields cannot be compiled for super class class (because they are already
// declared in super class itself), so we mark them as auto-generated, so they will be
// skipped
SNode current = node.firstChild();
while (current != lxNone) {
if (current == lxClassField)
current.setArgument(INVALID_REF);
current = current.nextNode();
}
}
// save declaration
scope.save();
// compile class class if it available
if (scope.info.header.classRef != scope.reference && scope.info.header.classRef != 0) {
ClassScope classClassScope((NamespaceScope*)scope.parent, scope.info.header.classRef, scope.visibility);
classClassScope.info.header.flags |= elClassClass; // !! IMPORTANT : classclass flags should be set
classClassScope.classClassMode = true;
if (!withDefaultConstructor && !scope.abstractMode && !test(scope.info.header.flags, elDynamicRole)) {
// if default constructor has to be created
injectDefaultConstructor(*scope.moduleScope, node, scope.reference, withConstructors);
}
compileClassClassDeclaration(node, classClassScope, scope);
// HOTFIX : if the default constructor is private - a class cannot be inherited
int hints = classClassScope.info.methodHints.get(Attribute(scope.moduleScope->constructor_message | STATIC_MESSAGE, maHint));
if ((hints & tpMask) == tpPrivate) {
scope.info.header.flags |= elFinal;
scope.save();
}
}
}
bool isClassMethod(LexicalType type)
{
return type == lxClassMethod;
}
bool isClassClassMethod(LexicalType type)
{
return type == lxConstructor || type == lxStaticMethod;
}
void Compiler :: generateClassImplementation(SNode node, ClassScope& scope)
{
analizeClassTree(node, scope,
scope.classClassMode ? isClassClassMethod : isClassMethod);
pos_t sourcePathRef = scope.saveSourcePath(_writer);
CommandTape tape;
_writer.generateClass(*scope.moduleScope, tape, node, scope.reference, sourcePathRef,
scope.classClassMode ? isClassClassMethod : isClassMethod);
// optimize
optimizeTape(tape);
//// create byte code sections
//scope.save();
_writer.saveTape(tape, *scope.moduleScope);
}
void Compiler :: compileClassImplementation(SNode node, ClassScope& scope)
{
if (test(scope.info.header.flags, elExtension)) {
scope.extensionClassRef = scope.info.fieldTypes.get(-1).value1;
scope.stackSafe = _logic->isStacksafeArg(*scope.moduleScope, scope.extensionClassRef);
}
else if (_logic->isStacksafeArg(scope.info)) {
scope.stackSafe = true;
}
// validate field types
if (scope.info.fieldTypes.Count() > 0) {
validateClassFields(node, scope);
}
else if (scope.info.statics.Count() > 0) {
//HOTFIX : validate static fields as well
validateClassFields(node, scope);
}
compileVMT(node, scope);
generateClassImplementation(node, scope);
// compile explicit symbol
// extension cannot be used stand-alone, so the symbol should not be generated
if (scope.extensionClassRef == 0 && scope.info.header.classRef != 0) {
compileSymbolCode(scope);
}
}
void Compiler :: compileSymbolDeclaration(SNode node, SymbolScope& scope)
{
declareSymbolAttributes(node, scope, true, false);
// if (scope.moduleScope->module->mapSection(scope.reference | mskMetaRDataRef, true) == nullptr) {
scope.save();
// }
}
bool Compiler :: compileSymbolConstant(SymbolScope& scope, ObjectInfo retVal, bool accumulatorMode, ref_t accumulatorRef)
{
NamespaceScope* nsScope = (NamespaceScope*)scope.getScope(Scope::ScopeLevel::slNamespace);
ref_t parentRef = 0;
ref_t classRef = resolveConstant(retVal, parentRef);
if (classRef) {
if (retVal.kind == okSingleton) {
// HOTFIX : singleton should be treated differently
scope.info.type = SymbolExpressionInfo::Type::Singleton;
scope.info.exprRef = classRef;
}
else if (retVal.kind == okConstantSymbol) {
scope.info.type = SymbolExpressionInfo::Type::ConstantSymbol;
scope.info.exprRef = classRef;
}
else if (retVal.kind == okArrayConst) {
scope.info.type = SymbolExpressionInfo::Type::ConstantSymbol;
scope.info.exprRef = classRef;
}
nsScope->defineConstantSymbol(classRef, parentRef);
return true;
}
_Module* module = scope.moduleScope->module;
MemoryWriter dataWriter(module->mapSection(scope.reference | mskRDataRef, false));
if (accumulatorMode) {
if (dataWriter.Position() == 0 && ((Section*)dataWriter.Memory())->References().Eof()) {
dataWriter.Memory()->addReference(accumulatorRef | mskVMTRef, (ref_t)-4);
}
if (retVal.kind == okLiteralConstant) {
dataWriter.Memory()->addReference(retVal.param | mskLiteralRef, dataWriter.Position());
dataWriter.writeDWord(0);
}
else if (retVal.kind == okWideLiteralConstant) {
dataWriter.Memory()->addReference(retVal.param | mskWideLiteralRef, dataWriter.Position());
dataWriter.writeDWord(0);
}
else if (retVal.kind == okMessageConstant) {
dataWriter.Memory()->addReference(retVal.param | mskMessage, dataWriter.Position());
dataWriter.writeDWord(0);
}
else if (retVal.kind == okMessageNameConstant) {
dataWriter.Memory()->addReference(retVal.param | mskMessageName, dataWriter.Position());
dataWriter.writeDWord(0);
}
else if (retVal.kind == okClass || retVal.kind == okClassSelf) {
dataWriter.Memory()->addReference(retVal.param | mskVMTRef, dataWriter.Position());
dataWriter.writeDWord(0);
}
else {
SymbolScope memberScope(nsScope, nsScope->moduleScope->mapAnonymous(), Visibility::Public);
if (!compileSymbolConstant(memberScope, retVal, false, 0))
return false;
dataWriter.Memory()->addReference(memberScope.reference | mskConstantRef, dataWriter.Position());
dataWriter.writeDWord(0);
}
return true;
}
else {
if (dataWriter.Position() > 0)
return false;
if (retVal.kind == okIntConstant || retVal.kind == okUIntConstant) {
size_t value = module->resolveConstant(retVal.param).toULong(16);
dataWriter.writeDWord(value);
parentRef = scope.moduleScope->intReference;
}
else if (retVal.kind == okLongConstant) {
long long value = module->resolveConstant(retVal.param).toLongLong(10, 1);
dataWriter.write(&value, 8u);
parentRef = scope.moduleScope->longReference;
}
else if (retVal.kind == okRealConstant) {
double value = module->resolveConstant(retVal.param).toDouble();
dataWriter.write(&value, 8u);
parentRef = scope.moduleScope->realReference;
}
else if (retVal.kind == okLiteralConstant) {
ident_t value = module->resolveConstant(retVal.param);
dataWriter.writeLiteral(value, getlength(value) + 1);
parentRef = scope.moduleScope->literalReference;
}
else if (retVal.kind == okWideLiteralConstant) {
WideString wideValue(module->resolveConstant(retVal.param));
dataWriter.writeLiteral(wideValue, getlength(wideValue) + 1);
parentRef = scope.moduleScope->wideReference;
}
else if (retVal.kind == okCharConstant) {
ident_t value = module->resolveConstant(retVal.param);
dataWriter.writeLiteral(value, getlength(value));
parentRef = scope.moduleScope->charReference;
}
else if (retVal.kind == okMessageNameConstant) {
dataWriter.Memory()->addReference(retVal.param | mskMessageName, dataWriter.Position());
dataWriter.writeDWord(0);
parentRef = scope.moduleScope->messageNameReference;
}
else if (retVal.kind == okClass || retVal.kind == okClassSelf) {
dataWriter.Memory()->addReference(retVal.param | mskVMTRef, dataWriter.Position());
dataWriter.writeDWord(0);
parentRef = scope.moduleScope->superReference;
}
else return false;
dataWriter.Memory()->addReference(parentRef | mskVMTRef, (ref_t)-4);
if (parentRef == scope.moduleScope->intReference) {
nsScope->defineConstantSymbol(scope.reference, V_INT32);
}
else nsScope->defineConstantSymbol(scope.reference, parentRef);
}
return true;
}
void Compiler :: compileSymbolAttribtes(_ModuleScope& moduleScope, ref_t reference, bool publicAttr)
{
ClassInfo::CategoryInfoMap mattributes;
if (publicAttr) {
// add seriazible meta attribute for the public symbol
mattributes.add(Attribute(caSymbolSerializable, 0), INVALID_REF);
}
if (mattributes.Count() > 0) {
// initialize attribute section writers
MemoryWriter attrWriter(moduleScope.mapSection(reference | mskSymbolAttributeRef, false));
mattributes.write(&attrWriter);
}
}
void Compiler :: compileSymbolImplementation(SNode node, SymbolScope& scope)
{
bool isStatic = scope.staticOne;
SNode expression = node.findChild(lxExpression);
EAttr exprMode = scope.info.type == SymbolExpressionInfo::Type::Constant ? HINT_CONSTEXPR : EAttr::eaNone;
ExprScope exprScope(&scope);
// HOTFIX : due to implementation (compileSymbolConstant requires constant types) typecast should be done explicitly
ObjectInfo retVal = compileExpression(expression, exprScope,
mapObject(expression, exprScope, HINT_ROOTSYMBOL), 0, exprMode);
if (scope.info.exprRef == 0) {
ref_t ref = resolveObjectReference(scope, retVal, true);
if (ref != 0 && scope.info.type != SymbolExpressionInfo::Type::Normal) {
// HOTFIX : if the result of the operation is qualified - it should be saved as symbol type
scope.info.exprRef = ref;
}
}
else retVal = convertObject(expression, exprScope, scope.info.exprRef, retVal, EAttr::eaNone);
expression.refresh();
analizeSymbolTree(expression, scope);
// create constant if required
if (scope.info.type == SymbolExpressionInfo::Type::Constant) {
// static symbol cannot be constant
if (isStatic)
scope.raiseError(errInvalidOperation, expression);
if (!compileSymbolConstant(scope, retVal, false, 0))
scope.raiseError(errInvalidOperation, expression);
}
scope.save();
if (scope.preloaded) {
compilePreloadedCode(scope);
}
pos_t sourcePathRef = scope.saveSourcePath(_writer);
CommandTape tape;
_writer.generateSymbol(tape, node, isStatic, sourcePathRef);
// optimize
optimizeTape(tape);
compileSymbolAttribtes(*scope.moduleScope, scope.reference, scope.visibility == Visibility::Public);
// create byte code sections
_writer.saveTape(tape, *scope.moduleScope);
}
void Compiler :: compileStaticAssigning(ObjectInfo target, SNode node, ClassScope& scope/*, int mode*//*, bool accumulatorMode*/)
{
// // !! temporal
// if (accumulatorMode)
// scope.raiseError(errIllegalOperation, node);
SyntaxTree expressionTree;
SyntaxWriter writer(expressionTree);
CodeScope codeScope(&scope);
ExprScope exprScope(&codeScope);
writer.newNode(lxExpression);
SNode exprNode = writer.CurrentNode();
writer.closeNode();
SNode assignNode = exprNode.appendNode(lxAssigning);
SNode targetNode = assignNode.appendNode(lxVirtualReference);
SNode sourceNode = assignNode.appendNode(lxExpression);
// if (!isSealedStaticField(target.param)) {
// if (target.kind == okStaticField) {
// writeTerminal(writer, node, codeScope, ObjectInfo(okClassStaticField, scope.reference, target.reference, target.element, target.param), HINT_NODEBUGINFO);
// }
// else if (target.kind == okStaticConstantField) {
// writeTerminal(writer, node, codeScope, ObjectInfo(okClassStaticConstantField, scope.reference, target.reference, target.element, target.param), HINT_NODEBUGINFO);
// }
// }
/*else */recognizeTerminal(targetNode, target, exprScope, HINT_NODEBUGINFO);
SyntaxTree::copyNode(node, sourceNode);
ObjectInfo source = compileExpression(sourceNode, exprScope, target.extraparam, HINT_NODEBUGINFO);
analizeSymbolTree(expressionTree.readRoot(), scope);
ref_t actionRef = compileClassPreloadedCode(*scope.moduleScope, scope.reference, expressionTree.readRoot());
scope.info.mattributes.add(Attribute(caInitializer, 0), actionRef);
scope.save();
}
ref_t targetResolver(void* param, ref_t mssg)
{
return ((Map<ref_t, ref_t>*)param)->get(mssg);
}
void Compiler :: compileModuleExtensionDispatcher(NamespaceScope& scope)
{
List<ref_t> genericMethods;
ClassInfo::CategoryInfoMap methods(0);
Map<ref_t, ref_t> taregts;
auto it = scope.declaredExtensions.start();
while (!it.Eof()) {
auto extInfo = *it;
ref_t genericMessageRef = it.key();
ident_t refName = scope.module->resolveReference(extInfo.value1);
if (isWeakReference(refName)) {
if (NamespaceName::compare(refName, scope.ns)) {
// if the extension is declared in the module namespace
// add it to the list to be generated
if (retrieveIndex(genericMethods.start(), genericMessageRef) == -1)
genericMethods.add(genericMessageRef);
methods.add(Attribute(extInfo.value2, maMultimethod), genericMessageRef | FUNCTION_MESSAGE);
taregts.add(extInfo.value2, extInfo.value1);
}
}
it++;
}
if (genericMethods.Count() > 0) {
// if there are extension methods in the namespace
ref_t extRef = scope.moduleScope->mapAnonymous();
ClassScope classScope(&scope, extRef, Visibility::Private);
classScope.extensionDispatcher = true;
// declare the extension
SyntaxTree classTree;
SyntaxWriter writer(classTree);
// build the class tree
writer.newNode(lxRoot);
writer.newNode(lxClass, extRef);
writer.closeNode();
writer.closeNode();
SNode classNode = classTree.readRoot().firstChild();
compileParentDeclaration(classNode, classScope, scope.moduleScope->superReference);
classScope.info.header.flags |= (elExtension | elSealed);
classScope.info.header.classRef = classScope.reference;
classScope.extensionClassRef = scope.moduleScope->superReference;
classScope.info.fieldTypes.add(-1, ClassInfo::FieldInfo(classScope.extensionClassRef, 0));
for (auto g_it = genericMethods.start(); !g_it.Eof(); g_it++) {
ref_t genericMessageRef = *g_it;
ref_t dispatchListRef = _logic->generateOverloadList(*scope.moduleScope, *this, genericMessageRef | FUNCTION_MESSAGE,
methods, (void*)&taregts, targetResolver, elSealed);
classScope.info.mattributes.add(Attribute(caExtOverloadlist, genericMessageRef), dispatchListRef);
}
classScope.save();
// compile the extension
compileVMT(classNode, classScope);
generateClassImplementation(classNode, classScope);
compilePreloadedExtensionCode(classScope);
}
}
ref_t Compiler :: compileExtensionDispatcher(NamespaceScope& scope, ref_t genericMessageRef)
{
ref_t extRef = scope.moduleScope->mapAnonymous();
ClassScope classScope(&scope, extRef, Visibility::Private);
classScope.extensionDispatcher = true;
// create a new overload list
ClassInfo::CategoryInfoMap methods(0);
Map<ref_t, ref_t> taregts;
auto it = scope.extensions.getIt(genericMessageRef);
while (!it.Eof()) {
auto extInfo = *it;
methods.add(Attribute(extInfo.value2, maMultimethod), genericMessageRef | FUNCTION_MESSAGE);
taregts.add(extInfo.value2, extInfo.value1);
it = scope.extensions.nextIt(genericMessageRef, it);
}
ref_t dispatchListRef = _logic->generateOverloadList(*scope.moduleScope, *this, genericMessageRef | FUNCTION_MESSAGE, methods,
(void*)&taregts, targetResolver, elSealed);
SyntaxTree classTree;
SyntaxWriter writer(classTree);
// build the class tree
writer.newNode(lxRoot);
writer.newNode(lxClass, extRef);
injectVirtualMultimethod(*scope.moduleScope, writer.CurrentNode(),
genericMessageRef | FUNCTION_MESSAGE, lxClassMethod, genericMessageRef, false, 0);
writer.closeNode();
writer.closeNode();
SNode classNode = classTree.readRoot().firstChild();
// declare the extension
compileParentDeclaration(classNode, classScope, scope.moduleScope->superReference);
classScope.info.header.flags |= (elExtension | elSealed);
classScope.info.header.classRef = classScope.reference;
classScope.extensionClassRef = scope.moduleScope->superReference;
classScope.info.fieldTypes.add(-1, ClassInfo::FieldInfo(classScope.extensionClassRef, 0));
classScope.info.methodHints.exclude(Attribute(genericMessageRef | FUNCTION_MESSAGE, maOverloadlist));
classScope.info.methodHints.add(Attribute(genericMessageRef | FUNCTION_MESSAGE, maOverloadlist), dispatchListRef);
generateMethodDeclaration(classNode.findChild(lxClassMethod), classScope, false, false, false);
//generateMethodDeclarations(classNode, classScope, false, lxClassMethod, true);
classScope.save();
// compile the extension
compileVMT(classNode, classScope);
generateClassImplementation(classNode, classScope);
return extRef;
}
// NOTE : elementRef is used for binary arrays
ObjectInfo Compiler :: allocateResult(ExprScope& scope, /*bool fpuMode, */ref_t targetRef, ref_t elementRef)
{
int size = _logic->defineStructSize(*scope.moduleScope, targetRef, elementRef);
if (size > 0) {
ObjectInfo retVal;
allocateTempStructure(scope, size, false, retVal);
retVal.reference = targetRef;
return retVal;
}
else {
int tempLocal = scope.newTempLocal();
return ObjectInfo(okLocal, tempLocal, targetRef, /*elementRef*/0, 0);
}
}
int Compiler :: allocateStructure(SNode node, int& size)
{
// finding method's reserved attribute
SNode methodNode = node.parentNode();
while (methodNode != lxClassMethod)
methodNode = methodNode.parentNode();
SNode reserveNode = methodNode.findChild(lxReserved);
int reserved = reserveNode.argument;
if (reserveNode == lxNone) {
reserved = 0;
}
// allocating space
int offset = allocateStructure(false, size, reserved);
// HOT FIX : size should be in bytes
size *= 4;
reserveNode.setArgument(reserved);
return offset;
}
inline SNode injectRootSeqExpression(SNode& parent)
{
SNode current;
while (!parent.compare(lxNewFrame, lxCodeExpression, lxCode/*, lxReturning*/)) {
current = parent;
parent = parent.parentNode();
if (current == lxSeqExpression && current.argument == -2) {
// HOTFIX : to correctly unbox the variable in some cases (e.g. ret value dispatching)
return current;
}
}
if (current != lxSeqExpression) {
current.injectAndReplaceNode(lxSeqExpression);
}
return current;
}
void Compiler :: injectMemberPreserving(SNode node, ExprScope& scope, LexicalType tempType, int tempLocal, ObjectInfo member,
int memberIndex, int& oriTempLocal)
{
SNode parent = node;
SNode current;
if (scope.callNode != lxNone) {
// HOTFIX : closure member unboxing should be done right after the operation if it is possible
if (scope.callNode == lxExpression) {
scope.callNode.injectAndReplaceNode(lxSeqExpression);
current = scope.callNode.appendNode(lxNestedSeqExpression);
}
else if (scope.callNode == lxSeqExpression) {
current = scope.callNode.findChild(lxNestedSeqExpression);
}
else current = injectRootSeqExpression(parent);
}
else current = injectRootSeqExpression(parent);
ref_t targetRef = resolveObjectReference(scope, member, false);
if (member.kind == okLocalAddress) {
// if the parameter may be stack-allocated
bool variable = false;
int size = _logic->defineStructSizeVariable(*scope.moduleScope, targetRef, member.element, variable);
SNode assignNode = current.appendNode(lxCopying, size);
assignNode.appendNode(lxLocalAddress, member.param);
SNode fieldAssignExpr = assignNode.appendNode(lxFieldExpression);
fieldAssignExpr.appendNode(tempType, tempLocal);
fieldAssignExpr.appendNode(lxField, memberIndex);
Attribute key(lxLocalAddress, member.param);
int boxedLocal = scope.tempLocals.get(key);
if (boxedLocal != NOTFOUND_POS) {
// HOTFIX : check if the variable is used several times - modify the boxed argument as well
SNode assignBoxNode = current.appendNode(lxCopying, size);
assignBoxNode.appendNode(lxTempLocal, boxedLocal);
SNode fieldExpr = assignBoxNode.appendNode(lxFieldExpression);
fieldExpr.appendNode(tempType, tempLocal);
fieldExpr.appendNode(lxField, memberIndex);
}
}
else if (member.kind == okLocal) {
if (oriTempLocal == -1) {
// HOTFIX : presave the original value
oriTempLocal = scope.newTempLocal();
SNode oriAssignNode = current.insertNode(lxAssigning);
oriAssignNode.appendNode(lxTempLocal, oriTempLocal);
oriAssignNode.appendNode(lxLocal, member.param);
}
SNode assignNode = current.appendNode(lxAssigning);
if (oriTempLocal) {
assignNode.set(lxCondAssigning, oriTempLocal);
}
assignNode.appendNode(lxLocal, member.param);
SNode fieldExpr = assignNode.appendNode(lxFieldExpression);
fieldExpr.appendNode(tempType, tempLocal);
fieldExpr.appendNode(lxField, memberIndex);
}
else if (member.kind == okOuter) {
SNode assignNode = current.appendNode(lxAssigning);
SNode target = assignNode.appendNode(lxVirtualReference);
recognizeTerminal(target, member, scope, HINT_NODEBUGINFO);
SNode fieldExpr = assignNode.appendNode(lxFieldExpression);
fieldExpr.appendNode(tempType, tempLocal);
fieldExpr.appendNode(lxField, memberIndex);
}
else throw InternalError("Not yet implemented"); // !! temporal
}
void Compiler :: injectIndexBoxing(SNode node, SNode objNode, ExprScope& scope)
{
ref_t typeRef = node.findChild(lxType).argument;
int size = node.findChild(lxSize).argument;
if (typeRef == V_DWORD)
typeRef = scope.moduleScope->intReference;
objNode.injectAndReplaceNode(lxSaving, size);
SNode newNode = objNode.insertNode(lxCreatingStruct, size);
newNode.appendNode(lxType, typeRef);
}
void Compiler :: injectCopying(SNode& copyingNode, int size, bool variadic, bool primArray)
{
// copying boxed object
if (variadic) {
// NOTE : structure command is used to copy variadic argument list
copyingNode.injectAndReplaceNode(lxCloning);
}
else if (size < 0) {
// if it is a dynamic srtructure boxing
copyingNode.injectAndReplaceNode(lxCloning);
}
else if (primArray) {
// if it is a dynamic srtructure boxing
copyingNode.injectAndReplaceNode(lxCloning);
}
else if (size != 0) {
copyingNode.injectAndReplaceNode(lxCopying, size);
}
// otherwise consider it as a byref variable
else copyingNode.injectAndReplaceNode(lxByRefAssigning);
}
void Compiler :: injectCreating(SNode& assigningNode, SNode objNode, ExprScope& scope, bool insertMode, int size,
ref_t typeRef, bool variadic)
{
// NOTE that objNode may be no longer valid, so only cached values are used!
SNode newNode = insertMode ?
assigningNode.insertNode(lxCreatingStruct, size) : assigningNode.appendNode(lxCreatingStruct, size);
if (variadic) {
int tempSizeLocal = scope.newTempLocalAddress();
SNode sizeSetNode = assigningNode.prependSibling(lxArgArrOp, LEN_OPERATOR_ID);
sizeSetNode.appendNode(lxLocalAddress, tempSizeLocal);
sizeSetNode.appendNode(objNode.type, objNode.argument);
newNode.set(lxNewArrOp, typeRef);
newNode.appendNode(lxSize, 0);
newNode.appendNode(lxLocalAddress, tempSizeLocal);
}
else if (!size) {
// HOTFIX : recognize byref boxing
newNode.set(lxCreatingClass, 1);
}
newNode.appendNode(lxType, typeRef);
}
void Compiler :: boxExpressionInRoot(SNode node, SNode objNode, ExprScope& scope, LexicalType tempType,
int tempLocal, bool localBoxingMode, bool condBoxing)
{
SNode parent = node;
SNode current = injectRootSeqExpression(parent);
SNode boxingNode = current;
if (condBoxing)
boxingNode = current.insertNode(lxCondBoxing);
ref_t typeRef = node.findChild(lxType).argument;
int size = node.findChild(lxSize).argument;
bool isVariable = node.argument == INVALID_REF;
bool variadic = node == lxArgBoxableExpression;
bool primArray = node == lxPrimArrBoxableExpression;
if (typeRef != 0) {
bool fixedSizeArray = isPrimitiveArrRef(typeRef) && size > 0;
if (isPrimitiveRef(typeRef)) {
ref_t elementRef = node.findChild(lxElementType).argument;
typeRef = resolvePrimitiveReference(scope, typeRef, elementRef, false);
}
SNode copyNode = boxingNode.insertNode(objNode.type, objNode.argument);
if (test(objNode.type, lxOpScopeMask))
SyntaxTree::copyNode(objNode, copyNode);
if (size < 0 || primArray) {
injectCopying(copyNode, size, variadic, primArray);
copyNode.appendNode(lxType, typeRef);
copyNode.injectAndReplaceNode(lxAssigning);
copyNode.insertNode(tempType, tempLocal);
}
else {
SNode assignNode = boxingNode.insertNode(lxAssigning);
assignNode.appendNode(tempType, tempLocal);
if (localBoxingMode) {
copyNode.injectAndReplaceNode(lxCopying, size);
// inject local boxed object
ObjectInfo tempBuffer;
allocateTempStructure(scope, size, fixedSizeArray, tempBuffer);
assignNode.appendNode(lxLocalAddress, tempBuffer.param);
copyNode.insertNode(lxLocalAddress, tempBuffer.param);
}
else {
injectCreating(assignNode, objNode, scope, false, size, typeRef, variadic);
injectCopying(copyNode, size, variadic, primArray);
copyNode.insertNode(tempType, tempLocal);
}
}
if (isVariable) {
SNode unboxing = current.appendNode(lxCopying, size);
if (size < 0 || primArray) {
unboxing.set(lxCloning, 0);
}
else if (condBoxing)
unboxing.set(lxCondCopying, size);
SyntaxTree::copyNode(objNode, unboxing.appendNode(objNode.type, objNode.argument));
if (size == 0 && !primArray) {
// HOTFIX : if it is byref variable unboxing
unboxing.set(lxAssigning, 0);
SNode unboxingByRef = unboxing.appendNode(lxFieldExpression);
unboxingByRef.appendNode(tempType, tempLocal);
unboxingByRef.appendNode(lxField);
}
else unboxing.appendNode(tempType, tempLocal);
}
// replace object with a temp local
objNode.set(tempType, tempLocal);
}
else scope.raiseError(errInvalidBoxing, node);
}
void Compiler :: boxExpressionInPlace(SNode node, SNode objNode, ExprScope& scope,
bool localBoxingMode, bool condBoxing)
{
SNode rootNode = node.parentNode();
while (rootNode == lxExpression)
rootNode = rootNode.parentNode();
SNode target;
if (rootNode == lxAssigning) {
target = rootNode.findSubNodeMask(lxObjectMask);
}
ref_t typeRef = node.findChild(lxType).argument;
int size = node.findChild(lxSize).argument;
bool variadic = node == lxArgBoxableExpression;
bool primArray = node == lxPrimArrBoxableExpression;
if (typeRef != 0) {
if (localBoxingMode) {
bool fixedSizeArray = isPrimitiveArrRef(typeRef) && size > 0;
SNode assignNode = objNode;
assignNode.injectAndReplaceNode(lxAssigning);
// inject local boxed object
ObjectInfo tempBuffer;
allocateTempStructure(scope, size, fixedSizeArray, tempBuffer);
assignNode.insertNode(lxLocalAddress, tempBuffer.param);
assignNode.set(lxCopying, size);
assignNode.injectAndReplaceNode(lxSeqExpression);
assignNode.appendNode(lxLocalAddress, tempBuffer.param);
}
else {
if (isPrimitiveRef(typeRef)) {
ref_t elementRef = node.findChild(lxElementType).argument;
typeRef = resolvePrimitiveReference(scope, typeRef, elementRef, false);
}
int tempLocal = 0;
if (target == lxLocal) {
tempLocal = target.argument;
}
else tempLocal = scope.newTempLocal();
SNode seqNode= objNode;
seqNode.injectAndReplaceNode(lxSeqExpression);
SNode boxExpr = seqNode;
if (condBoxing)
boxExpr = seqNode.injectNode(lxCondBoxing);
SNode copyingNode = boxExpr.firstChild();
injectCopying(copyingNode, size, variadic, primArray);
if (size < 0 || primArray) {
copyingNode.appendNode(lxType, typeRef);
copyingNode.injectAndReplaceNode(lxAssigning);
copyingNode.insertNode(lxTempLocal, tempLocal);
}
else {
copyingNode.insertNode(lxTempLocal, tempLocal);
SNode assignNode = boxExpr.insertNode(lxAssigning);
assignNode.insertNode(lxTempLocal, tempLocal);
// !!NOTE: objNode is no longer valid, but injectCreating uses only
// cached values of a type and an argument
injectCreating(assignNode, objNode, scope, false, size, typeRef, variadic);
}
if (target == lxLocal) {
// comment out double assigning
target = lxIdle;
rootNode = lxExpression;
}
else seqNode.appendNode(lxTempLocal, tempLocal);
}
}
else scope.raiseError(errInvalidBoxing, node);
}
bool Compiler :: optimizeEmbeddable(_ModuleScope& scope, SNode& node/*, bool argMode*/)
{
bool applied = false;
// verify the path
SNode callNode = node.parentNode();
SNode rootNode = callNode.parentNode();
if (rootNode == lxCopying) {
applied = _logic->optimizeEmbeddableOp(scope, *this, rootNode);
}
if (applied)
node = lxIdle;
return applied;
}
bool Compiler :: optimizeEmbeddableCall(_ModuleScope& scope, SNode& node)
{
SNode rootNode = node.parentNode();
if (_logic->optimizeEmbeddable(rootNode, scope)) {
node = lxIdle;
return true;
}
else return false;
}
bool Compiler :: optimizeConstantAssigning(_ModuleScope&, SNode& node)
{
SNode parent = node.parentNode();
while (parent == lxExpression)
parent = parent.parentNode();
SNode larg = parent.findSubNodeMask(lxObjectMask);
if (larg == lxLocalAddress && parent.argument == 4) {
// direct operation with numeric constants
parent.set(lxIntOp, SET_OPERATOR_ID);
return true;
}
else return false;
}
//inline bool existSubNode(SNode node, SNode target, bool skipFirstOpArg)
//{
// SNode current = node.firstChild(lxObjectMask);
//
// if (skipFirstOpArg && test(node.type, lxPrimitiveOpMask))
// current = current.nextNode(lxObjectMask);
//
// while (current != lxNone) {
// if (current.type == target.type && current.argument == target.argument) {
// return true;
// }
// else if (existSubNode(current, target, false))
// return true;
//
// current = current.nextNode(lxObjectMask);
// }
//
// return false;
//}
inline bool compareNodes(SNode node, SNode target)
{
return (node.type == target.type && node.argument == target.argument);
}
inline bool existsNode(SNode node, SNode target)
{
if (compareNodes(node, target))
return true;
SNode current = node.firstChild(lxObjectMask);
while (current != lxNone) {
if (existsNode(current, target))
return true;
current = current.nextNode(lxObjectMask);
}
return false;
}
inline void commentNode(SNode& node)
{
node = lxIdle;
SNode parent = node.parentNode();
while (parent == lxExpression) {
parent = lxIdle;
parent = parent.parentNode();
}
}
bool Compiler :: optimizeOpDoubleAssigning(_ModuleScope&, SNode& node)
{
bool applied = false;
// seqNode
SNode seqNode = node.parentNode();
SNode seqRet = seqNode.lastChild(lxObjectMask);
if (seqRet == lxExpression)
seqRet = seqRet.findSubNodeMask(lxObjectMask);
// opNode
SNode opNode = node.nextNode(lxObjectMask);
SNode larg = opNode.firstChild(lxObjectMask);
SNode rarg = larg.nextNode(lxObjectMask);
// target
SNode targetCopying = seqNode.parentNode();
while (targetCopying == lxExpression)
targetCopying = targetCopying.parentNode();
SNode target = targetCopying.findSubNodeMask(lxObjectMask);
if (target != lxLocalAddress)
return false;
SNode temp = node.firstChild(lxObjectMask);
SNode tempSrc = temp.nextNode(lxObjectMask);
if (tempSrc == lxExpression)
tempSrc = tempSrc.findSubNodeMask(lxObjectMask);
// validate if the target is not used in roperand
if (existsNode(rarg, target))
return false;
// validate if temp is used in op and is returned in seq
if (compareNodes(seqRet, temp) && compareNodes(larg, temp)) {
temp.set(target.type, target.argument);
seqRet.set(target.type, target.argument);
larg.set(target.type, target.argument);
if (compareNodes(tempSrc, target)) {
node = lxIdle;
}
commentNode(target);
targetCopying = lxExpression;
applied = true;
}
return applied;
}
bool Compiler :: optimizeBranching(_ModuleScope& scope, SNode& node)
{
return _logic->optimizeBranchingOp(scope, node);
}
bool Compiler :: optimizeConstProperty(_ModuleScope&, SNode& node)
{
SNode callNode = node.parentNode();
callNode.set(lxConstantSymbol, node.argument);
return false;
}
inline void commetNode(SNode& node)
{
node = lxIdle;
SNode parent = node.parentNode();
while (parent == lxExpression) {
parent = lxIdle;
parent = parent.parentNode();
}
}
bool Compiler :: optimizeCallDoubleAssigning(_ModuleScope&, SNode& node)
{
SNode callNode = node.parentNode();
SNode seqNode = callNode.parentNode();
while (seqNode == lxExpression)
seqNode = seqNode.parentNode();
if (seqNode != lxSeqExpression)
return false;
SNode copyNode = seqNode.parentNode();
while (copyNode == lxExpression)
copyNode = copyNode.parentNode();
SNode src = copyNode.findSubNodeMask(lxObjectMask);
if (src.type != lxLocalAddress) {
node = lxIdle;
return false;
}
SNode temp = callNode.lastChild(lxObjectMask);
if (temp == lxExpression)
temp = temp.findSubNodeMask(lxObjectMask);
SNode seqRes = seqNode.lastChild(lxObjectMask);
if (seqRes == lxExpression)
seqRes = seqRes.findSubNodeMask(lxObjectMask);
if (temp == lxLocalAddress && compareNodes(seqRes, temp)) {
temp.setArgument(src.argument);
seqRes.setArgument(src.argument);
commentNode(src);
copyNode = lxExpression;
node = lxIdle;
return true;
}
return false;
}
bool Compiler :: optimizeTriePattern(_ModuleScope& scope, SNode& node, int patternId)
{
switch (patternId) {
case 1:
return optimizeConstProperty(scope, node);
case 2:
return optimizeEmbeddable(scope, node/*, false*/);
case 3:
return optimizeEmbeddableCall(scope, node);
case 4:
return optimizeBranching(scope, node);
case 5:
return optimizeConstantAssigning(scope, node);
case 6:
return optimizeOpDoubleAssigning(scope, node);
case 7:
return optimizeCallDoubleAssigning(scope, node);
default:
break;
}
return false;
}
bool Compiler :: matchTriePatterns(_ModuleScope& scope, SNode& node, SyntaxTrie& trie, List<SyntaxTrieNode>& matchedPatterns)
{
List<SyntaxTrieNode> nextPatterns;
if (test(node.type, lxOpScopeMask) || node.type == lxCode) {
SyntaxTrieNode rootTrieNode(&trie._trie);
nextPatterns.add(rootTrieNode);
}
// match existing patterns
for (auto it = matchedPatterns.start(); !it.Eof(); it++) {
auto pattern = *it;
for (auto child_it = pattern.Children(); !child_it.Eof(); child_it++) {
auto currentPattern = child_it.Node();
auto currentPatternValue = currentPattern.Value();
if (currentPatternValue.match(node)) {
nextPatterns.add(currentPattern);
if (currentPatternValue.patternId != 0 && optimizeTriePattern(scope, node, currentPatternValue.patternId))
return true;
}
}
}
if (nextPatterns.Count() > 0) {
SNode current = node.firstChild();
while (current != lxNone) {
if (current == lxExpression) {
SNode subNode = current.findSubNodeMask(lxObjectMask);
if (matchTriePatterns(scope, subNode, trie, nextPatterns))
return true;
}
else if(matchTriePatterns(scope, current, trie, nextPatterns))
return true;
current = current.nextNode();
}
}
return false;
}
void Compiler :: analizeCodePatterns(SNode node, NamespaceScope& scope)
{
if (test(_optFlag, 1)) {
//test2(node);
bool applied = true;
List<SyntaxTrieNode> matched;
while (applied) {
matched.clear();
SyntaxTrieNode rootTrieNode(&_sourceRules._trie);
matched.add(rootTrieNode);
applied = matchTriePatterns(*scope.moduleScope, node, _sourceRules, matched);
}
//test2(node);
}
}
void Compiler :: analizeMethod(SNode node, NamespaceScope& scope)
{
SNode current = node.firstChild();
while (current != lxNone) {
if (current == lxNewFrame) {
analizeCodePatterns(current, scope);
}
current = current.nextNode();
}
}
void Compiler :: analizeClassTree(SNode node, ClassScope& scope, bool(*cond)(LexicalType))
{
NamespaceScope* nsScope = (NamespaceScope*)scope.getScope(Scope::ScopeLevel::slNamespace);
//LexicalType type = scope.classClassMode ? lxConstructor : lxClassMethod;
SNode current = node.firstChild();
while (current != lxNone) {
if (cond(current)) {
analizeMethod(current, *nsScope);
if (test(_optFlag, 1)) {
if (test(scope.info.methodHints.get(Attribute(current.argument, maHint)), tpEmbeddable)) {
defineEmbeddableAttributes(scope, current);
}
}
}
current = current.nextNode();
}
}
void Compiler :: analizeSymbolTree(SNode node, Scope& scope)
{
NamespaceScope* nsScope = (NamespaceScope*)scope.getScope(Scope::ScopeLevel::slNamespace);
analizeCodePatterns(node, *nsScope);
}
void Compiler :: defineEmbeddableAttributes(ClassScope& classScope, SNode methodNode)
{
// Optimization : subject'get = self / $self
if (_logic->recognizeEmbeddableIdle(methodNode, classScope.extensionClassRef != 0)) {
classScope.info.methodHints.add(Attribute(methodNode.argument, maEmbeddableIdle), INVALID_REF);
classScope.save();
}
// Optimization : embeddable constructor call
ref_t message = 0;
if (_logic->recognizeEmbeddableMessageCall(methodNode, message)) {
classScope.info.methodHints.add(Attribute(methodNode.argument, maEmbeddableNew), message);
classScope.save();
}
}
//void Compiler :: compileForward(SNode ns, NamespaceScope& scope)
//{
// ident_t shortcut = ns.findChild(lxNameAttr).firstChild(lxTerminalMask).identifier();
// ident_t reference = ns.findChild(lxForward).firstChild(lxTerminalMask).identifier();
//
// if (!scope.defineForward(shortcut, reference))
// scope.raiseError(errDuplicatedDefinition, ns);
//}
//
////////bool Compiler :: validate(_ProjectManager& project, _Module* module, int reference)
//////{
////// int mask = reference & mskAnyRef;
////// ref_t extReference = 0;
////// ident_t refName = module->resolveReference(reference & ~mskAnyRef);
////// _Module* extModule = project.resolveModule(refName, extReference, true);
//////
////// return (extModule != NULL && extModule->mapSection(extReference | mask, true) != NULL);
//////}
//
////void Compiler :: validateUnresolved(Unresolveds& unresolveds, _ProjectManager& project)
////{
//// //for (List<Unresolved>::Iterator it = unresolveds.start() ; !it.Eof() ; it++) {
//// // if (!validate(project, (*it).module, (*it).reference)) {
//// // ident_t refName = (*it).module->resolveReference((*it).reference & ~mskAnyRef);
////
//// // project.raiseWarning(wrnUnresovableLink, (*it).fileName, (*it).row, (*it).col, refName);
//// // }
//// //}
////}
inline void addPackageItem(SyntaxWriter& writer, _Module* module, ident_t str)
{
writer.newNode(lxMember);
if (!emptystr(str)) {
writer.appendNode(lxConstantString, module->mapConstant(str));
}
else writer.appendNode(lxNil);
writer.closeNode();
}
inline ref_t mapForwardRef(_Module* module, _ProjectManager& project, ident_t forward)
{
ident_t name = project.resolveForward(forward);
return emptystr(name) ? 0 : module->mapReference(name);
}
void Compiler :: createPackageInfo(_Module* module, _ProjectManager& project)
{
ReferenceNs sectionName("'", PACKAGE_SECTION);
ref_t reference = module->mapReference(sectionName);
ref_t vmtReference = mapForwardRef(module, project, SUPER_FORWARD);
if (vmtReference == 0)
return;
SyntaxTree tree;
SyntaxWriter writer(tree);
writer.newNode(lxConstantList, reference);
writer.appendNode(lxType, vmtReference);
// namespace
addPackageItem(writer, module, module->Name());
// package name
addPackageItem(writer, module, project.getManinfestName());
// package version
addPackageItem(writer, module, project.getManinfestVersion());
// package author
addPackageItem(writer, module, project.getManinfestAuthor());
writer.closeNode();
_writer.generateConstantList(tree.readRoot(), module, reference);
}
int Compiler :: saveMetaInfo(_ModuleScope& scope, ident_t info)
{
int position = 0;
ReferenceNs sectionName("'", METAINFO_SECTION);
_Memory* section = scope.module->mapSection(scope.module->mapReference(sectionName, false) | mskMetaRDataRef, false);
if (section) {
MemoryWriter metaWriter(section);
position = metaWriter.Position();
if (!position) {
metaWriter.writeByte(0);
position++;
}
metaWriter.writeLiteral(info);
}
return position;
}
void Compiler :: saveNamespaceInfo(SNode node, NamespaceScope& scope, bool innerMost)
{
if (innerMost) {
node.appendNode(lxSourcePath, scope.sourcePath);
}
IdentifierString nsFullName(scope.module->Name());
if (scope.name.Length() > 0) {
nsFullName.append("'");
nsFullName.append(scope.name.c_str());
}
node.appendNode(lxImport, nsFullName.c_str());
for (auto it = scope.importedNs.start(); !it.Eof(); it++) {
node.appendNode(lxImport, *it);
}
if (scope.parent)
saveNamespaceInfo(node, *(NamespaceScope*)scope.parent, false);
}
void Compiler :: declareTemplate(SNode node, NamespaceScope& scope)
{
// COMPILER MAGIC : inject imported namespaces & source path
saveNamespaceInfo(node, scope, true);
SNode current = node.firstChild();
ref_t templateRef = scope.mapNewTerminal(current.findChild(lxNameAttr), Visibility::Public);
// check for duplicate declaration
if (scope.module->mapSection(templateRef | mskSyntaxTreeRef, true))
scope.raiseError(errDuplicatedSymbol, current.findChild(lxNameAttr));
_Memory* target = scope.module->mapSection(templateRef | mskSyntaxTreeRef, false);
if (node == lxExtensionTemplate) {
registerExtensionTemplate(current, scope, templateRef);
}
SyntaxTree::saveNode(node, target);
// HOTFIX : to prevent template double declaration in repeating mode
node = lxIdle;
}
void Compiler :: compileImplementations(SNode current, NamespaceScope& scope)
{
// second pass - implementation
while (current != lxNone) {
switch (current) {
// case lxInclude:
// compileForward(current, scope);
// break;
case lxClass:
{
#ifdef FULL_OUTOUT_INFO
// info
ident_t name = scope.module->resolveReference(current.argument);
scope.moduleScope->printInfo("class %s", name);
#endif // FULL_OUTOUT_INFO
// compile class
ClassScope classScope(&scope, current.argument, scope.defaultVisibility);
declareClassAttributes(current, classScope, false);
scope.moduleScope->loadClassInfo(classScope.info, current.argument, false);
compileClassImplementation(current, classScope);
// compile class class if it available
if (classScope.info.header.classRef != classScope.reference && classScope.info.header.classRef != 0) {
ClassScope classClassScope(&scope, classScope.info.header.classRef, classScope.visibility);
scope.moduleScope->loadClassInfo(classClassScope.info, scope.module->resolveReference(classClassScope.reference), false);
classClassScope.classClassMode = true;
#ifdef FULL_OUTOUT_INFO
// info
ident_t classClassName = scope.module->resolveReference(current.argument);
scope.moduleScope->printInfo("class %s#class", classClassName);
#endif // FULL_OUTOUT_INFO
compileClassClassImplementation(current, classClassScope, classScope);
}
break;
}
case lxSymbol:
{
SymbolScope symbolScope(&scope, current.argument, scope.defaultVisibility);
declareSymbolAttributes(current, symbolScope, false, false);
compileSymbolImplementation(current, symbolScope);
break;
}
case lxNamespace:
{
SNode node = current.firstChild();
NamespaceScope namespaceScope(&scope/*, true*/);
declareNamespace(node, namespaceScope, false, true);
copyParentNamespaceExtensions(scope, namespaceScope);
compileImplementations(node, namespaceScope);
break;
}
}
current = current.nextNode();
}
}
bool Compiler :: compileDeclarations(SNode current, NamespaceScope& scope, bool forced, bool& repeatMode)
{
if (scope.moduleScope->superReference == 0)
scope.raiseError(errNotDefinedBaseClass);
// first pass - declaration
bool declared = false;
while (current != lxNone) {
switch (current) {
case lxNamespace:
{
SNode node = current.firstChild();
NamespaceScope namespaceScope(&scope);
declareNamespace(node, namespaceScope, false, false);
// declare classes several times to ignore the declaration order
declared |= compileDeclarations(node, namespaceScope, forced, repeatMode);
break;
}
case lxClass:
if (!scope.moduleScope->isDeclared(current.argument)) {
if (forced || !current.findChild(lxParent)
|| _logic->doesClassExist(*scope.moduleScope, resolveParentRef(current.findChild(lxParent), scope, true)))
{
// HOTFIX : import template classes
SNode importNode = current.findChild(lxClassImport);
while (importNode == lxClassImport) {
importClassMembers(current, importNode, scope);
importNode = importNode.nextNode();
}
ClassScope classScope(&scope, current.argument, scope.defaultVisibility);
declareClassAttributes(current, classScope, false);
// declare class
compileClassDeclaration(current, classScope);
declared = true;
}
else repeatMode = true;
}
break;
case lxSymbol:
if (!scope.moduleScope->isDeclared(current.argument)) {
SymbolScope symbolScope(&scope, current.argument, scope.defaultVisibility);
declareSymbolAttributes(current, symbolScope, true, false);
// declare symbol
compileSymbolDeclaration(current, symbolScope);
declared = true;
}
break;
case lxTemplate:
case lxExtensionTemplate:
declareTemplate(current, scope);
break;
}
current = current.nextNode();
}
if (scope.declaredExtensions.Count() > 0) {
compileModuleExtensionDispatcher(scope);
scope.declaredExtensions.clear();
}
return declared;
}
void Compiler :: copyParentNamespaceExtensions(NamespaceScope& source, NamespaceScope& target)
{
for (auto it = source.extensions.start(); !it.Eof(); it++) {
auto ext = *it;
target.extensions.add(it.key(), Pair<ref_t, ref_t>(ext.value1, ext.value2));
}
}
void Compiler :: declareNamespace(SNode& current, NamespaceScope& scope, bool ignoreImports, bool withFullInfo)
{
if (!ignoreImports && !scope.module->Name().compare(STANDARD_MODULE) && _autoSystemImport) {
bool dummy = false;
scope.moduleScope->includeNamespace(scope.importedNs, STANDARD_MODULE, dummy);
}
while (current != lxNone) {
if (current == lxSourcePath) {
scope.sourcePath.copy(current.identifier());
}
else if (current == lxNameAttr) {
// overwrite the parent namespace name
scope.name.copy(current.firstChild(lxTerminalMask).identifier());
if (scope.nsName.Length() > 0)
scope.nsName.append('\'');
scope.nsName.append(scope.name.c_str());
scope.ns = scope.nsName.c_str();
}
else if (current == lxAttribute) {
if (!_logic->validateNsAttribute(current.argument, scope.defaultVisibility))
scope.raiseError(errInvalidHint, current);
}
else if (current == lxImport && !ignoreImports) {
bool duplicateInclusion = false;
ident_t name = current.identifier();
if (emptystr(name))
name = current.firstChild(lxTerminalMask).identifier();
if (scope.moduleScope->includeNamespace(scope.importedNs, name, duplicateInclusion)) {
//if (duplicateExtensions)
// scope.raiseWarning(WARNING_LEVEL_1, wrnDuplicateExtension, ns);
}
else if (duplicateInclusion) {
if (current.identifier().compare(STANDARD_MODULE) && _autoSystemImport) {
// HOTFIX : ignore the auto loaded module
}
else scope.raiseWarning(WARNING_LEVEL_1, wrnDuplicateInclude, current);
// HOTFIX : comment out, to prevent duplicate warnings
current = lxIdle;
}
else {
scope.raiseWarning(WARNING_LEVEL_1, wrnUnknownModule, current);
current = lxIdle; // remove the node, to prevent duplicate warnings
}
}
else if (current == lxIdle) {
// skip idle node
}
else break;
current = current.nextNode();
}
if (withFullInfo) {
// HOTFIX : load the module internal and public extensions
scope.loadExtensions(scope.module->Name(), scope.nsName.c_str(), false);
scope.loadExtensions(scope.module->Name(), scope.nsName.c_str(), true);
for (auto it = scope.importedNs.start(); !it.Eof(); it++) {
ident_t imported_ns = *it;
scope.loadModuleInfo(imported_ns);
}
}
}
void Compiler :: declareMembers(SNode current, NamespaceScope& scope)
{
while (current != lxNone) {
switch (current) {
case lxNamespace:
{
SNode node = current.firstChild();
NamespaceScope namespaceScope(&scope);
declareNamespace(node, namespaceScope, true, false);
scope.moduleScope->declareNamespace(namespaceScope.ns.c_str());
declareMembers(node, namespaceScope);
break;
}
case lxClass:
{
ClassScope classScope(&scope, scope.defaultVisibility);
declareClassAttributes(current, classScope, true);
if (current.argument == INVALID_REF) {
// if it is a template based class - its name was already resolved
classScope.reference = current.findChild(lxNameAttr).argument;
}
else classScope.reference = scope.mapNewTerminal(current.findChild(lxNameAttr), classScope.visibility);
current.setArgument(classScope.reference);
// NOTE : the symbol section is created even if the class symbol doesn't exist
scope.moduleScope->mapSection(classScope.reference | mskSymbolRef, false);
break;
}
case lxSymbol:
{
SymbolScope symbolScope(&scope, scope.defaultVisibility);
declareSymbolAttributes(current, symbolScope, true, true);
symbolScope.reference = scope.mapNewTerminal(current.findChild(lxNameAttr), symbolScope.visibility);
current.setArgument(symbolScope.reference);
scope.moduleScope->mapSection(symbolScope.reference | mskSymbolRef, false);
break;
}
}
current = current.nextNode();
}
}
void Compiler :: declareModuleIdentifiers(SyntaxTree& syntaxTree, _ModuleScope& scope)
{
SNode node = syntaxTree.readRoot().firstChild();
while (node != lxNone) {
if (node == lxNamespace) {
SNode current = node.firstChild();
NamespaceScope namespaceScope(&scope, nullptr);
declareNamespace(current, namespaceScope, true, false);
scope.declareNamespace(namespaceScope.ns.c_str());
// declare all module members - map symbol identifiers
declareMembers(current, namespaceScope);
}
node = node.nextNode();
}
}
bool Compiler :: declareModule(SyntaxTree& syntaxTree, _ModuleScope& scope, bool forced, bool& repeatMode,
ExtensionMap* outerExtensionList)
{
SNode node = syntaxTree.readRoot().firstChild();
bool retVal = false;
while (node != lxNone) {
if (node == lxNamespace) {
SNode current = node.firstChild();
NamespaceScope namespaceScope(&scope, outerExtensionList);
declareNamespace(current, namespaceScope, false, false);
// compile class declarations several times to ignore the declaration order
retVal |= compileDeclarations(current, namespaceScope, forced, repeatMode);
}
node = node.nextNode();
}
return retVal;
}
void Compiler :: compileModule(SyntaxTree& syntaxTree, _ModuleScope& scope, ident_t greeting,
ExtensionMap* outerExtensionList)
{
SNode node = syntaxTree.readRoot().firstChild();
while (node != lxNone) {
if (node == lxNamespace) {
SNode current = node.firstChild();
NamespaceScope namespaceScope(&scope, outerExtensionList);
declareNamespace(current, namespaceScope, false, true);
if (!emptystr(greeting))
scope.project->printInfo("%s", greeting);
compileImplementations(current, namespaceScope);
}
node = node.nextNode();
}
}
inline ref_t safeMapReference(_Module* module, _ProjectManager* project, ident_t referenceName)
{
if (!emptystr(referenceName)) {
// HOTFIX : for the standard module the references should be mapped forcefully
if (module->Name().compare(STANDARD_MODULE)) {
return module->mapReference(referenceName + getlength(module->Name()));
}
else {
ref_t extRef = 0;
_Module* extModule = project->resolveModule(referenceName, extRef, true);
return importReference(extModule, extRef, module);
}
}
else return 0;
}
inline ref_t safeMapWeakReference(_Module* module, ident_t referenceName)
{
if (!emptystr(referenceName)) {
// HOTFIX : for the standard module the references should be mapped forcefully
if (module->Name().compare(STANDARD_MODULE)) {
return module->mapReference(referenceName + getlength(module->Name()), false);
}
else return module->mapReference(referenceName, false);
}
else return 0;
}
bool Compiler :: loadAttributes(_ModuleScope& scope, ident_t name, MessageMap* attributes, bool silenMode)
{
_Module* extModule = scope.project->loadModule(name, silenMode);
if (extModule) {
ReferenceNs sectionName("'", ATTRIBUTE_SECTION);
_Memory* section = extModule->mapSection(extModule->mapReference(sectionName, true) | mskMetaRDataRef, true);
if (section) {
MemoryReader metaReader(section);
while (!metaReader.Eof()) {
ref_t attrRef = metaReader.getDWord();
if (!isPrimitiveRef(attrRef)) {
attrRef = importReference(extModule, attrRef, scope.module);
}
ident_t attrName = metaReader.getLiteral(DEFAULT_STR);
if (!attributes->add(attrName, attrRef, true))
scope.printInfo(wrnDuplicateAttribute, attrName);
}
}
return true;
}
else return false;
}
void Compiler :: initializeScope(ident_t name, _ModuleScope& scope, bool withDebugInfo)
{
scope.module = scope.project->createModule(name);
if (withDebugInfo) {
scope.debugModule = scope.project->createDebugModule(name);
// HOTFIX : save the module name in strings table
_writer.writeSourcePath(scope.debugModule, name);
}
// cache the frequently used references
scope.superReference = safeMapReference(scope.module, scope.project, scope.project->resolveForward(SUPER_FORWARD));
scope.intReference = safeMapReference(scope.module, scope.project, scope.project->resolveForward(INT_FORWARD));
scope.longReference = safeMapReference(scope.module, scope.project, scope.project->resolveForward(LONG_FORWARD));
scope.realReference = safeMapReference(scope.module, scope.project, scope.project->resolveForward(REAL_FORWARD));
scope.literalReference = safeMapReference(scope.module, scope.project, scope.project->resolveForward(STR_FORWARD));
scope.wideReference = safeMapReference(scope.module, scope.project, scope.project->resolveForward(WIDESTR_FORWARD));
scope.charReference = safeMapReference(scope.module, scope.project, scope.project->resolveForward(CHAR_FORWARD));
scope.messageReference = safeMapReference(scope.module, scope.project, scope.project->resolveForward(MESSAGE_FORWARD));
scope.refTemplateReference = safeMapReference(scope.module, scope.project, scope.project->resolveForward(REFTEMPLATE_FORWARD));
scope.arrayTemplateReference = safeMapReference(scope.module, scope.project, scope.project->resolveForward(ARRAYTEMPLATE_FORWARD));
scope.argArrayTemplateReference = safeMapReference(scope.module, scope.project, scope.project->resolveForward(ARGARRAYTEMPLATE_FORWARD));
scope.messageNameReference = safeMapReference(scope.module, scope.project, scope.project->resolveForward(MESSAGENAME_FORWARD));
scope.extMessageReference = safeMapReference(scope.module, scope.project, scope.project->resolveForward(EXT_MESSAGE_FORWARD));
scope.lazyExprReference = safeMapReference(scope.module, scope.project, scope.project->resolveForward(LAZYEXPR_FORWARD));
scope.closureTemplateReference = safeMapWeakReference(scope.module, scope.project->resolveForward(CLOSURETEMPLATE_FORWARD));
// scope.wrapReference = safeMapReference(scope.module, scope.project, scope.project->resolveForward(WRAP_FORWARD));
scope.branchingInfo.reference = safeMapReference(scope.module, scope.project, scope.project->resolveForward(BOOL_FORWARD));
scope.branchingInfo.trueRef = safeMapReference(scope.module, scope.project, scope.project->resolveForward(TRUE_FORWARD));
scope.branchingInfo.falseRef = safeMapReference(scope.module, scope.project, scope.project->resolveForward(FALSE_FORWARD));
// cache the frequently used messages
scope.dispatch_message = encodeMessage(scope.module->mapAction(DISPATCH_MESSAGE, 0, false), 1, 0);
scope.init_message = encodeMessage(scope.module->mapAction(INIT_MESSAGE, 0, false), 0, FUNCTION_MESSAGE | STATIC_MESSAGE);
scope.constructor_message = encodeMessage(scope.module->mapAction(CONSTRUCTOR_MESSAGE, 0, false), 1, 0);
scope.protected_constructor_message = encodeMessage(scope.module->mapAction(CONSTRUCTOR_MESSAGE2, 0, false), 1, 0);
if (!scope.module->Name().compare(STANDARD_MODULE)) {
// system attributes should be loaded automatically
if (!loadAttributes(scope, STANDARD_MODULE, &scope.attributes, true))
scope.printInfo(wrnInvalidModule, STANDARD_MODULE);
}
createPackageInfo(scope.module, *scope.project);
}
void Compiler :: injectVirtualField(SNode classNode, LexicalType sourceType, ref_t sourceArg, int postfixIndex)
{
// declare field
IdentifierString fieldName(VIRTUAL_FIELD);
fieldName.appendInt(postfixIndex);
SNode fieldNode = classNode.appendNode(lxClassField, INVALID_REF);
fieldNode.appendNode(lxNameAttr).appendNode(lxIdentifier, fieldName.c_str());
// assing field
SNode assignNode = classNode.appendNode(lxFieldInit, INVALID_REF); // INVALID_REF indicates the virtual code
assignNode.appendNode(lxIdentifier, fieldName.c_str());
assignNode.appendNode(lxAssign);
assignNode.appendNode(sourceType, sourceArg);
}
void Compiler :: generateOverloadListMember(_ModuleScope& scope, ref_t listRef, ref_t messageRef)
{
MemoryWriter metaWriter(scope.module->mapSection(listRef | mskRDataRef, false));
if (metaWriter.Position() == 0) {
metaWriter.writeRef(0, messageRef);
metaWriter.writeDWord(0);
metaWriter.writeDWord(0);
}
else {
metaWriter.insertDWord(0, 0);
metaWriter.insertDWord(0, messageRef);
metaWriter.Memory()->addReference(0, 0);
}
}
void Compiler :: generateClosedOverloadListMember(_ModuleScope& scope, ref_t listRef, ref_t messageRef, ref_t classRef)
{
MemoryWriter metaWriter(scope.module->mapSection(listRef | mskRDataRef, false));
if (metaWriter.Position() == 0) {
metaWriter.writeRef(0, messageRef);
metaWriter.writeRef(classRef | mskVMTEntryOffset, messageRef);
metaWriter.writeDWord(0);
}
else {
metaWriter.insertDWord(0, messageRef);
metaWriter.insertDWord(0, messageRef);
metaWriter.Memory()->addReference(0, 0);
metaWriter.Memory()->addReference(classRef | mskVMTEntryOffset, 4);
}
}
void Compiler :: generateSealedOverloadListMember(_ModuleScope& scope, ref_t listRef, ref_t messageRef, ref_t classRef)
{
MemoryWriter metaWriter(scope.module->mapSection(listRef | mskRDataRef, false));
if (metaWriter.Position() == 0) {
metaWriter.writeRef(0, messageRef);
metaWriter.writeRef(classRef | mskVMTMethodAddress, messageRef);
metaWriter.writeDWord(0);
}
else {
metaWriter.insertDWord(0, messageRef);
metaWriter.insertDWord(0, messageRef);
metaWriter.Memory()->addReference(0, 0);
metaWriter.Memory()->addReference(classRef | mskVMTMethodAddress, 4);
}
}
////ref_t Compiler :: readEnumListMember(_CompilerScope& scope, _Module* extModule, MemoryReader& reader)
////{
//// ref_t memberRef = reader.getDWord() & ~mskAnyRef;
////
//// return importReference(extModule, memberRef, scope.module);
////}
void Compiler :: injectBoxingExpr(SNode& node, bool variable, int size, ref_t targetClassRef, bool arrayMode)
{
node.injectAndReplaceNode(lxBoxableExpression, variable ? INVALID_REF : 0);
if (arrayMode && size == 0) {
// HOTFIX : to indicate a primitive array boxing
node = lxPrimArrBoxableExpression;
}
node.appendNode(lxType, targetClassRef);
node.appendNode(lxSize, size);
// writer.inject(boxingType, argument);
// writer.appendNode(lxTarget, targetClassRef);
// writer.closeNode();
}
void Compiler :: injectConverting(SNode& node, LexicalType convertOp, int convertArg, LexicalType targetOp, int targetArg, ref_t targetClassRef, int, bool embeddableAttr)
{
if (node == lxExpression) {
}
else node.injectAndReplaceNode(lxExpression);
node.appendNode(lxCallTarget, targetClassRef);
if (embeddableAttr)
node.appendNode(lxEmbeddableAttr);
node.set(convertOp, convertArg);
node.insertNode(targetOp, targetArg/*, lxTarget, targetClassRef*/);
//analizeOperands(node, stackSafeAttr);
}
//void Compiler :: injectEmbeddableRet(SNode assignNode, SNode callNode, ref_t messageRef)
//{
// // move assigning target into the call node
// SNode assignTarget;
// if (assignNode == lxByRefAssigning) {
// assignTarget = assignNode.findSubNode(lxLocal);
// }
// else assignTarget = assignNode.findSubNode(lxLocalAddress);
//
// if (assignTarget != lxNone) {
// // removing assinging operation
// assignNode = lxExpression;
//
// callNode.appendNode(assignTarget.type, assignTarget.argument);
// assignTarget = lxIdle;
// callNode.setArgument(messageRef);
// }
//}
void Compiler :: injectEmbeddableOp(_ModuleScope& scope, SNode assignNode, SNode callNode, ref_t subject, int paramCount/*, int verb*/)
{
SNode assignTarget = assignNode.findSubNode(lxLocalAddress);
if (assignTarget == lxNone)
//HOTFIX : embeddable constructor should be applied only for the stack-allocated varaible
return;
if (paramCount == -1/* && verb == 0*/) {
// if it is an embeddable constructor call
SNode sourceNode = assignNode.findSubNodeMask(lxObjectMask);
SNode callTargetNode = callNode.firstChild(lxObjectMask);
callTargetNode.set(sourceNode.type, sourceNode.argument);
callNode.setArgument(subject);
// HOTFIX : class class reference should be turned into class one
SNode callTarget = callNode.findChild(lxCallTarget);
IdentifierString className(scope.module->resolveReference(callTarget.argument));
className.cut(getlength(className) - getlength(CLASSCLASS_POSTFIX), getlength(CLASSCLASS_POSTFIX));
callTarget.setArgument(scope.mapFullReference(className));
assignNode = lxExpression;
sourceNode = lxIdle;
// check if inline initializer is declared
ClassInfo targetInfo;
scope.loadClassInfo(targetInfo, callTarget.argument);
if (targetInfo.methods.exist(scope.init_message)) {
// inject inline initializer call
callTargetNode.injectAndReplaceNode(lxDirectCalling, scope.init_message);
callTargetNode.appendNode(lxCallTarget, callTarget.argument);
callTargetNode = callTargetNode.firstChild(lxObjectMask);
}
}
//else {
// // removing assinging operation
// assignNode = lxExpression;
// // move assigning target into the call node
// if (assignTarget != lxNone) {
// callNode.appendNode(assignTarget.type, assignTarget.argument);
// assignTarget = lxIdle;
// callNode.setArgument(encodeMessage(subject, paramCount));
// }
//}
}
SNode Compiler :: injectTempLocal(SNode node, int size, bool boxingMode)
{
SNode tempLocalNode;
//HOTFIX : using size variable copy to prevent aligning
int dummy = size;
int offset = allocateStructure(node, dummy);
if (boxingMode) {
// allocate place for the local copy
node.injectNode(node.type, node.argument);
node.set(lxCopying, size);
//node.insertNode(lxTempAttr, 0); // NOTE _ should be the last child
tempLocalNode = node.insertNode(lxLocalAddress, offset);
}
else {
tempLocalNode = node.appendNode(lxLocalAddress, offset);
}
return tempLocalNode;
}
void Compiler :: injectEmbeddableConstructor(SNode classNode, ref_t message, ref_t embeddedMessageRef)
{
SNode methNode = classNode.appendNode(lxConstructor, message);
methNode.appendNode(lxEmbeddableMssg, embeddedMessageRef);
methNode.appendNode(lxAttribute, tpEmbeddable);
methNode.appendNode(lxAttribute, tpConstructor);
SNode codeNode = methNode.appendNode(lxDispatchCode);
codeNode.appendNode(lxRedirect, embeddedMessageRef);
}
inline SNode newVirtualMultimethod(SNode classNode, ref_t message, LexicalType methodType, bool privateOne)
{
SNode methNode = classNode.appendNode(methodType, message);
methNode.appendNode(lxAutogenerated); // !! HOTFIX : add a template attribute to enable explicit method declaration
methNode.appendNode(lxAutoMultimethod); // !! HOTFIX : add a attribute for the nested class compilation (see compileNestedVMT)
methNode.appendNode(lxAttribute, tpMultimethod);
if (methodType == lxConstructor)
methNode.appendNode(lxAttribute, tpConstructor);
if (test(message, FUNCTION_MESSAGE))
methNode.appendNode(lxAttribute, tpFunction);
if (privateOne)
methNode.appendNode(lxAttribute, tpPrivate);
return methNode;
}
void Compiler :: injectVirtualMultimethod(_ModuleScope&, SNode classNode, ref_t message, LexicalType methodType,
ref_t resendMessage, bool privateOne, ref_t callTargetRef)
{
SNode methNode = newVirtualMultimethod(classNode, message, methodType, privateOne);
SNode resendNode = methNode.appendNode(lxResendExpression, resendMessage);
if (callTargetRef)
resendNode.appendNode(lxCallTarget, callTargetRef);
}
bool Compiler :: injectVirtualStrongTypedMultimethod(_ModuleScope& moduleScope, SNode classNode, ref_t message, LexicalType methodType,
ref_t resendMessage, bool privateOne)
{
ref_t actionRef = getAction(resendMessage);
ref_t signRef = 0;
ident_t actionName = moduleScope.module->resolveAction(actionRef, signRef);
ref_t signatures[ARG_COUNT];
size_t len = moduleScope.module->resolveSignature(signRef, signatures);
// HOTFIX : make sure it has at least one strong-typed argument
bool strongOne = false;
for (size_t i = 0; i < len; i++) {
if (signatures[i] != moduleScope.superReference) {
strongOne = true;
break;
}
}
// HOTFIX : the weak argument list should not be type-casted
// to avoid dispatching to the same method
if (!strongOne)
return false;
SNode methNode = newVirtualMultimethod(classNode, message, methodType, privateOne);
SNode resendNode = methNode.appendNode(lxResendExpression);
SNode resendExpr = resendNode.appendNode(lxExpression);
SNode messageNode = resendExpr.appendNode(lxMessage);;
if (!test(resendMessage, FUNCTION_MESSAGE)) {
// NOTE : for a function message - ignore the message name
messageNode.appendNode(lxIdentifier, actionName);
}
messageNode.appendNode(lxTemplate, actionName);
if (test(resendMessage, PROPERTY_MESSAGE))
resendExpr.appendNode(lxPropertyParam);
IdentifierString arg;
for (size_t i = 0; i < len; i++) {
arg.copy("$");
arg.appendInt(i);
SNode paramNode = methNode.appendNode(lxMethodParameter);
paramNode.appendNode(lxNameAttr).appendNode(lxIdentifier, arg.c_str());
SNode exprNode = resendExpr.appendNode(lxExpression);
if (signatures[i] != moduleScope.superReference) {
// HOTFIX : typecasting to super object should be omitted (it is useless)
exprNode.appendNode(lxAttribute, V_CONVERSION);
exprNode.appendNode(lxType, signatures[i]);
exprNode.appendNode(lxMessage);
exprNode.appendNode(lxExpression).appendNode(lxIdentifier, arg.c_str());
}
else exprNode.appendNode(lxExpression).appendNode(lxIdentifier, arg.c_str());
}
// HOTFIX : to ignore typecasting warnings
resendNode.appendNode(lxAutogenerated);
return true;
}
inline bool isSingleDispatch(ClassInfo& info, ref_t message, ref_t& targetMessage)
{
ref_t foundMessage = 0;
for (auto it = info.methodHints.start(); !it.Eof(); it++) {
if (it.key().value2 == maMultimethod && *it == message) {
if (foundMessage) {
return false;
}
else foundMessage = it.key().value1;
}
}
if (foundMessage) {
targetMessage = foundMessage;
return true;
}
else return false;
}
void Compiler :: injectVirtualMultimethod(_ModuleScope& scope, SNode classNode, ref_t message,
LexicalType methodType, ClassInfo& info)
{
bool privateOne = false;
ref_t resendMessage = message;
ref_t callTargetRef = 0;
ref_t actionRef, flags;
int argCount;
decodeMessage(message, actionRef, argCount, flags);
if (test(flags, STATIC_MESSAGE)) {
privateOne = true;
}
// !! temporally do not support variadic arguments
// try to resolve an argument list in run-time if it is only a single dispatch and argument list is not weak
if (!isSingleDispatch(info, message, resendMessage) || test(message, VARIADIC_MESSAGE)
|| !injectVirtualStrongTypedMultimethod(scope, classNode, message, methodType, resendMessage, privateOne))
{
if (info.methods.exist(message, false)) {
// if virtual multi-method handler is overridden
// redirect to the parent one
callTargetRef = info.header.parentRef;
}
else {
ref_t dummy = 0;
ident_t actionName = scope.module->resolveAction(actionRef, dummy);
ref_t signatureLen = 0;
ref_t signatures[ARG_COUNT];
int firstArg = test(flags, FUNCTION_MESSAGE) ? 0 : 1;
if (test(message, VARIADIC_MESSAGE)) {
}
else {
for (int i = firstArg; i < argCount; i++) {
signatures[signatureLen++] = scope.superReference;
}
}
ref_t signRef = scope.module->mapAction(actionName, scope.module->mapSignature(signatures, signatureLen, false), false);
resendMessage = encodeMessage(signRef, argCount, flags);
}
injectVirtualMultimethod(scope, classNode, message, methodType, resendMessage, privateOne, callTargetRef);
}
}
void Compiler :: injectVirtualDispatchMethod(SNode classNode, ref_t message, LexicalType type, ident_t argument)
{
SyntaxTree subTree;
SyntaxWriter subWriter(subTree);
subWriter.newNode(lxRoot);
subWriter.newNode(lxClassMethod, message);
subWriter.appendNode(lxAutogenerated); // !! HOTFIX : add a template attribute to enable explicit method declaration
subWriter.appendNode(lxAttribute, V_EMBEDDABLE);
subWriter.newNode(lxDispatchCode);
subWriter.appendNode(type, argument);
subWriter.closeNode();
subWriter.closeNode();
subWriter.closeNode();
SyntaxTree::copyNode(subTree.readRoot(), classNode);
}
void Compiler :: injectVirtualReturningMethod(_ModuleScope&, SNode classNode, ref_t message, ident_t variable, ref_t outputRef)
{
SNode methNode = classNode.appendNode(lxClassMethod, message);
methNode.appendNode(lxAutogenerated); // !! HOTFIX : add a template attribute to enable explicit method declaration
methNode.appendNode(lxAttribute, tpEmbeddable);
methNode.appendNode(lxAttribute, tpSealed);
methNode.appendNode(lxAttribute, tpCast);
if (outputRef) {
methNode.appendNode(lxType, outputRef);
}
SNode exprNode = methNode.appendNode(lxReturning).appendNode(lxExpression);
exprNode.appendNode(lxAttribute, V_NODEBUGINFO);
exprNode.appendNode(lxIdentifier, variable);
}
void Compiler :: injectDefaultConstructor(_ModuleScope& scope, SNode classNode, ref_t, bool protectedOne)
{
ref_t message = protectedOne ? scope.protected_constructor_message : scope.constructor_message;
SNode methNode = classNode.appendNode(lxConstructor, message);
methNode.appendNode(lxAutogenerated);
methNode.appendNode(lxAttribute, tpConstructor);
if (protectedOne)
methNode.appendNode(lxAttribute, tpProtected);
}
void Compiler :: generateClassSymbol(SyntaxWriter& writer, ClassScope& scope)
{
ExprScope exprScope(&scope);
writer.newNode(lxSymbol, scope.reference);
writer.newNode(lxAutogenerated);
SNode current = writer.CurrentNode();
recognizeTerminal(current, ObjectInfo(okClass, scope.reference/*, scope.info.header.classRef*/), exprScope, HINT_NODEBUGINFO);
writer.closeNode();
writer.closeNode();
}
//////void Compiler :: generateSymbolWithInitialization(SyntaxWriter& writer, ClassScope& scope, ref_t implicitConstructor)
//////{
////// CodeScope codeScope(&scope);
//////
////// writer.newNode(lxSymbol, scope.reference);
////// writeTerminal(writer, SNode(), codeScope, ObjectInfo(okConstantClass, scope.reference, scope.info.header.classRef), HINT_NODEBUGINFO);
////// writer.newNode(lxImplicitCall, implicitConstructor);
////// writer.appendNode(lxTarget, scope.reference);
////// writer.closeNode();
////// writer.closeNode();
//////}
void Compiler :: registerTemplateSignature(SNode node, NamespaceScope& scope, IdentifierString& signature)
{
signature.append(TEMPLATE_PREFIX_NS);
int signIndex = signature.Length();
IdentifierString templateName(node.firstChild(lxTerminalMask).identifier());
int paramCounter = SyntaxTree::countChild(node, lxType, lxTemplateParam);
templateName.append('#');
templateName.appendInt(paramCounter);
ref_t ref = /*mapTemplateAttribute(node, scope)*/scope.resolveImplicitIdentifier(templateName.c_str(), false, true);
ident_t refName = scope.module->resolveReference(ref);
if (isWeakReference(refName))
signature.append(scope.module->Name());
signature.append(refName);
SNode current = node.firstChild();
while (current != lxNone) {
if (current == lxTemplateParam) {
signature.append('&');
signature.append('{');
signature.appendInt(current.argument);
signature.append('}');
}
else if (current.compare(lxType, lxArrayType)) {
signature.append('&');
ref_t classRef = resolveTypeAttribute(current, scope, true, false);
if (!classRef)
scope.raiseError(errUnknownClass, current);
ident_t className = scope.module->resolveReference(classRef);
if (isWeakReference(className))
signature.append(scope.module->Name());
signature.append(className);
}
//else scope.raiseError(errNotApplicable, current);
//}
else if (current == lxIdentifier) {
// !! ignore identifier
}
else scope.raiseError(errNotApplicable, current);
current = current.nextNode();
}
// '$auto'system@Func#2&CharValue&Object
signature.replaceAll('\'', '@', signIndex);
}
void Compiler :: registerExtensionTemplateMethod(SNode node, NamespaceScope& scope, ref_t extensionRef)
{
IdentifierString messageName;
int argCount = 1;
ref_t flags = 0;
IdentifierString signaturePattern;
ident_t extensionName = scope.module->resolveReference(extensionRef);
if (isWeakReference(extensionName)) {
signaturePattern.append(scope.module->Name());
}
signaturePattern.append(extensionName);
signaturePattern.append('.');
SNode current = node.firstChild();
while (current != lxNone) {
if (current == lxNameAttr) {
messageName.copy(current.firstChild(lxTerminalMask).identifier());
}
else if (current == lxMethodParameter) {
argCount++;
signaturePattern.append('/');
SNode typeAttr = current.findChild(lxType, lxArrayType, lxTemplateParam);
if (typeAttr == lxTemplateParam) {
signaturePattern.append('{');
signaturePattern.appendInt(typeAttr.argument);
signaturePattern.append('}');
}
else if (typeAttr != lxNone) {
if (typeAttr == lxType && typeAttr.argument == V_TEMPLATE) {
registerTemplateSignature(typeAttr, scope, signaturePattern);
}
else {
ref_t classRef = resolveTypeAttribute(typeAttr, scope, true, false);
ident_t className = scope.module->resolveReference(classRef);
if (isWeakReference(className))
signaturePattern.append(scope.module->Name());
signaturePattern.append(className);
}
}
else scope.raiseError(errNotApplicable, current);
}
current = current.nextNode();
}
ref_t messageRef = encodeMessage(scope.module->mapAction(messageName.c_str(), 0, false), argCount, flags);
scope.saveExtensionTemplate(messageRef, signaturePattern.ident());
}
void Compiler :: registerExtensionTemplate(SNode node, NamespaceScope& scope, ref_t extensionRef)
{
SNode current = node.firstChild();
while (current != lxNone) {
if (current == lxClassMethod) {
registerExtensionTemplateMethod(current, scope, extensionRef);
}
current = current.nextNode();
}
}
//void Compiler :: registerExtensionTemplate(SyntaxTree& tree, _ModuleScope& scope, ident_t ns, ref_t extensionRef)
//{
// SNode node = tree.readRoot();
//
// // declare classes several times to ignore the declaration order
// NamespaceScope namespaceScope(&scope, ns);
// declareNamespace(node, namespaceScope, false);
//
// registerExtensionTemplate(node.findChild(lxClass), namespaceScope, extensionRef);
//}
ref_t Compiler :: generateExtensionTemplate(_ModuleScope& moduleScope, ref_t templateRef, size_t argumentLen,
ref_t* arguments, ident_t ns, ExtensionMap* outerExtensionList)
{
List<SNode> parameters;
// generate an extension if matched
// HOTFIX : generate a temporal template to pass the type
SyntaxTree dummyTree;
SyntaxWriter dummyWriter(dummyTree);
dummyWriter.newNode(lxRoot);
for (size_t i = 0; i < argumentLen; i++) {
dummyWriter.appendNode(lxType, arguments[i]);
}
dummyWriter.closeNode();
SNode current = dummyTree.readRoot().firstChild();
while (current != lxNone) {
parameters.add(current);
current = current.nextNode();
}
return moduleScope.generateTemplate(templateRef, parameters, ns, false, outerExtensionList);
}
void Compiler :: injectExprOperation(_CompileScope& scope, SNode& node, int size, int tempLocal, LexicalType op,
int opArg, ref_t reference)
{
SNode current = node;
if (current != lxExpression) {
current.injectNode(lxExpression);
current = current.findChild(lxExpression);
}
SNode loperand = current.firstChild(lxObjectMask);
loperand.injectAndReplaceNode(lxCopying, size);
loperand.insertNode(lxLocalAddress, tempLocal);
SNode roperand = loperand.nextNode(lxObjectMask);
roperand.injectAndReplaceNode(op, opArg);
roperand.insertNode(lxLocalAddress, tempLocal);
current = lxSeqExpression;
SNode retNode = current.appendNode(lxVirtualReference);
setVariableTerminal(retNode, scope, ObjectInfo(okLocalAddress, tempLocal, reference), EAttr::eaNone, lxLocalAddress);
}
| 35.589656 | 174 | 0.641939 | [
"object"
] |
793dde884a2980b121f3c29a21d48ead16b45922 | 2,044 | hpp | C++ | src/servo/es9257.hpp | g-vidal/upm | 8115c3b64468f22fb27053ba9dfc952ae0e32633 | [
"MIT"
] | 2 | 2017-06-19T13:14:30.000Z | 2018-07-12T06:17:49.000Z | src/servo/es9257.hpp | g-vidal/upm | 8115c3b64468f22fb27053ba9dfc952ae0e32633 | [
"MIT"
] | 1 | 2018-11-13T18:03:56.000Z | 2018-11-14T18:17:57.000Z | src/servo/es9257.hpp | g-vidal/upm | 8115c3b64468f22fb27053ba9dfc952ae0e32633 | [
"MIT"
] | 4 | 2017-03-06T14:39:59.000Z | 2018-06-28T11:07:41.000Z | /*
* Author: Mihai Tudor Panu <mihai.tudor.panu@intel.com>
* Copyright (c) 2015 Intel 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.
*/
#pragma once
#include <string>
#include "servo.hpp"
namespace upm {
/**
* @library servo
* @sensor es9257
* @comname Micro Digital 3D Tail Servo
* @altname Grove Servo
* @type servos
* @man emax
* @web https://www.seeedstudio.com/EMAX-ES9257-2.5kg%26amp%3B-.05-sec-Micro-Digital-3D-Tail-Servo-p-762.html
* @con pwm
* @kit gsk
*
* @brief API for the ES9257 Servo
*
* This module defines the ES9257 interface for ES9257 servos.
* The ES9257 servo is a fast, heavy duty servo that is popular for moving the
* control surfaces on RC models.
*
* @image html es9257.jpg
*/
class ES9257 : public Servo {
public:
/**
* Instantiates an ES9257 object
*
* @param pin Servo pin number
*/
ES9257 (int pin);
/**
* ES9257 object destructor
*/
~ES9257 ();
};
}
| 30.969697 | 109 | 0.696673 | [
"object",
"3d"
] |
7947920be43d57816e39b9ed1d2809f81be33aee | 1,462 | cpp | C++ | GeeksforGeeks/Complete Interview Preparation/Tree/Binary Tree/LCA.cpp | rs-ravi2/Codes | 8fc8bb64b429b3825e52394916c623ffcd0d5e21 | [
"MIT"
] | null | null | null | GeeksforGeeks/Complete Interview Preparation/Tree/Binary Tree/LCA.cpp | rs-ravi2/Codes | 8fc8bb64b429b3825e52394916c623ffcd0d5e21 | [
"MIT"
] | null | null | null | GeeksforGeeks/Complete Interview Preparation/Tree/Binary Tree/LCA.cpp | rs-ravi2/Codes | 8fc8bb64b429b3825e52394916c623ffcd0d5e21 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
struct Node
{
int key;
struct Node *left;
struct Node *right;
Node(int k){
key=k;
left=right=NULL;
}
};
// bool findPath(Node *root, vector<Node *> &p, int n){ NAIVE : O[n] and O[n]
// if(root==NULL)return false;
// p.push_back(root);
// if(root->key==n)return true;
// if(findPath(root->left,p,n)||findPath(root->right,p,n))return true;
// p.pop_back();
// return false;
// }
// Node *lca(Node *root, int n1, int n2){
// vector <Node *> path1, path2;
// if(findPath(root,path1,n1)==false||findPath(root,path2,n2)==false)
// return NULL;
// for(int i=0;i<path1.size()-1 && i<path2.size()-1;i++)
// if(path1[i+1]!=path2[i+1])
// return path1[i];
// return NULL;
}
Node *lca(Node *root, int n1, int n2){ // Assuming both n1 and n2 are present in the tree O[n] and O[h]
if(root==NULL)return NULL;
if(root->key==n1||root->key==n2)
return root;
Node *lca1=lca(root->left,n1,n2);
Node *lca2=lca(root->right,n1,n2);
if(lca1!=NULL && lca2!=NULL)
return root;
if(lca1!=NULL)
return lca1;
else
return lca2;
}
int main() {
Node *root=new Node(10);
root->left=new Node(20);
root->right=new Node(30);
root->right->left=new Node(40);
root->right->right=new Node(50);
int n1=20,n2=50;
Node *ans=lca(root,n1,n2);
cout<<"LCA: "<<ans->key;
} | 23.206349 | 103 | 0.562927 | [
"vector"
] |
794b522c727ebe5d2cfffc32b5cc71cba6ac5cf3 | 19,076 | cpp | C++ | src/test.cpp | sifaserdarozen/ConcurrentDecoder | 3d437796a479755b9a878a9d6285753fd8d2dd6a | [
"BSD-Source-Code"
] | null | null | null | src/test.cpp | sifaserdarozen/ConcurrentDecoder | 3d437796a479755b9a878a9d6285753fd8d2dd6a | [
"BSD-Source-Code"
] | 3 | 2016-05-25T09:00:58.000Z | 2016-05-31T08:51:49.000Z | src/test.cpp | sifaserdarozen/ConcurrentDecoder | 3d437796a479755b9a878a9d6285753fd8d2dd6a | [
"BSD-Source-Code"
] | null | null | null | #include <iostream>
#include <cstdio>
#include <ctime>
#include <time.h>
#include <stdlib.h>
#include <cstring> // for g++ std::memcpy
#include <cmath>
#include <iomanip> // for std::setprecision
#include <vector>
#include <fstream>
#include "sample_data.h"
#include "cuda_decoders.h"
#include "cpu_decoders.h"
#define NO_OF_TEST_PACKET 1000000
#define DEFAULT_START_OF_ITERATIONS 250
#define DEFAULT_END_OF_ITERATIONS 128000
#define DEFAULT_NUMBER_OF_ITERATIONS 10
#define DEFAULT_NUMBER_OF_AVERAGING 1000
enum DataType {
NAIVE,
COALESCED
};
int GenerateG711aData(unsigned char* alaw_data_ptr, unsigned int no_of_data, DataType choice = NAIVE)
{
if(!alaw_data_ptr)
return -1;
unsigned char* dst_ptr = alaw_data_ptr;
const unsigned char* src_ptr = NULL;
unsigned int no_of_source_data = sizeof(sample_g711a_data) / sizeof(sample_g711a_data[0]);
unsigned int no_of_full_repetition = no_of_data/no_of_source_data;
unsigned int last_repetition_remeinder = no_of_data%no_of_source_data;
if(NAIVE == choice)
{
// copy full repetitions
for(unsigned int k=0; k<no_of_full_repetition; k++)
{
src_ptr = sample_g711a_data;
for(unsigned int j=0; j<no_of_source_data; j++)
// *dst_ptr++ = *src_ptr++;
*dst_ptr++ = rand() % 256;
}
// copy remeinder datas
src_ptr = sample_g711a_data;
for(unsigned int j=0; j<last_repetition_remeinder; j++)
// *dst_ptr++ = *src_ptr++;
*dst_ptr++ = rand() % 256;
}
else if (COALESCED == choice)
{
// copy full repetitions
src_ptr = sample_g711u_data;
for(unsigned int j=0; j<no_of_source_data; j++)
{
for(unsigned int k=0; k<no_of_full_repetition; k++)
{
//*dst_ptr++ = *src_ptr;
*dst_ptr++ = rand() % 256;
}
if(j<last_repetition_remeinder)
{
//*dst_ptr++ = *src_ptr++;
*dst_ptr++ = rand() % 256;
}
else
{
src_ptr++;
}
}
}
return 0;
}
int GenerateG711uData(unsigned char* ulaw_data_ptr, unsigned int no_of_data, DataType choice = NAIVE)
{
if(!ulaw_data_ptr)
return -1;
unsigned char* dst_ptr = ulaw_data_ptr;
const unsigned char* src_ptr = NULL;
unsigned int no_of_source_data = sizeof(sample_g711u_data) / sizeof(sample_g711u_data[0]);
unsigned int no_of_full_repetition = no_of_data/no_of_source_data;
unsigned int last_repetition_remeinder = no_of_data%no_of_source_data;
if(NAIVE == choice)
{
// copy full repetitions
for(unsigned int k=0; k<no_of_full_repetition; k++)
{
src_ptr = sample_g711u_data;
for(unsigned int j=0; j<no_of_source_data; j++)
//*dst_ptr++ = *src_ptr++;
*dst_ptr++ = rand() % 256;
}
// copy remeinder datas
src_ptr = sample_g711a_data;
for(unsigned int j=0; j<last_repetition_remeinder; j++)
//*dst_ptr++ = *src_ptr++;
*dst_ptr++ = rand() % 256;
}
else if (COALESCED == choice)
{
// copy full repetitions
src_ptr = sample_g711u_data;
for(unsigned int j=0; j<no_of_source_data; j++)
{
for(unsigned int k=0; k<no_of_full_repetition; k++)
{
//*dst_ptr++ = *src_ptr;
*dst_ptr++ = rand() % 256;
}
if(j<last_repetition_remeinder)
{
//*dst_ptr++ = *src_ptr++;
*dst_ptr++ = rand() % 256;
}
else
{
src_ptr++;
}
}
}
return 0;
}
int GenerateG722Data(unsigned char* g722_data_ptr, int* g722_band_ptr, unsigned int no_of_data, DataType choice = NAIVE)
{
if(!g722_data_ptr)
return -1;
unsigned char* dst_ptr = g722_data_ptr;
const unsigned char* src_ptr = NULL;
unsigned int no_of_source_data = sizeof(sample_g722_data) / sizeof(sample_g722_data[0]);
unsigned int no_of_full_repetition = no_of_data/no_of_source_data;
unsigned int last_repetition_remeinder = no_of_data%no_of_source_data;
unsigned int no_of_total_repetitions = ceil(no_of_data/((float)no_of_source_data));
unsigned int band_size_of_total_repetitions = 45 * sizeof(int) * no_of_total_repetitions;
std::memset(g722_band_ptr, 0, band_size_of_total_repetitions);
if(NAIVE == choice)
{
// copy full repetitions
for(unsigned int k=0; k<no_of_full_repetition; k++)
{
src_ptr = sample_g711u_data;
for(unsigned int j=0; j<no_of_source_data; j++)
//*dst_ptr++ = *src_ptr++;
*dst_ptr++ = rand() % 256;
}
// copy remeinder datas
src_ptr = sample_g722_data;
for(unsigned int j=0; j<last_repetition_remeinder; j++)
//*dst_ptr++ = *src_ptr++;
*dst_ptr++ = rand() % 256;
for(unsigned int k=0; k<no_of_total_repetitions; k++)
g722_band_ptr[k*45 + 44] = 32;
}
else if (COALESCED == choice)
{
// copy full repetitions
src_ptr = sample_g722_data;
for(unsigned int j=0; j<no_of_source_data; j++)
{
for(unsigned int k=0; k<no_of_full_repetition; k++)
{
//*dst_ptr++ = *src_ptr;
*dst_ptr++ = rand() % 256;
}
if(j<last_repetition_remeinder)
{
//*dst_ptr++ = *src_ptr++;
*dst_ptr++ = rand() % 256;
}
else
{
src_ptr++;
}
}
for(unsigned int k=0; k<no_of_total_repetitions; k++)
g722_band_ptr[k + 44*no_of_total_repetitions] = 32;
}
return 0;
}
template <class T>
bool CompareArrays(const T* first_data_ptr, const T* second_data_ptr, unsigned int no_of_data)
{
for(unsigned int k=0; k<no_of_data; k++)
{
if(*first_data_ptr++ != *second_data_ptr++)
{
std::cout << "match failed at index " << k << std::endl;
return false;
}
}
std::cout << "match succedded..." << std::endl;
return true;
}
int main(int argc, char *argv[])
{
std::vector<int> iteration_vector;
std::vector<int>::iterator itr;
std::vector<float> cpu_alaw_vector;
std::vector<float> gpu_alaw_vector;
std::vector<float> cpu_ulaw_vector;
std::vector<float> gpu_ulaw_vector;
std::vector<float> cpu_g722_vector;
std::vector<float> gpu_g722_vector;
std::vector<float>::iterator flt_itr;
int start_of_iterations = DEFAULT_START_OF_ITERATIONS;
int end_of_iterations = DEFAULT_END_OF_ITERATIONS;
int number_of_iterations = DEFAULT_NUMBER_OF_ITERATIONS;
int number_of_averaging = DEFAULT_NUMBER_OF_AVERAGING;
// process input arguments and generate necessary data
if (3 == argc)
{
start_of_iterations = atoi(argv[1]);
number_of_iterations = atoi(argv[2]);
}
else if (4==argc)
{
start_of_iterations = atoi(argv[1]);
number_of_iterations = atoi(argv[2]);
number_of_averaging = atoi(argv[3]);
}
else
{
// values are already set, print for usage for customization
std::cout << "calculation will be done by defaut values, to customize, for example" << std::endl;
std::cout << "in order to calculate 13 iterations from 250 to 1024000 use..." << std::endl;
std::cout << "---> test 250 13" << std::endl << std::endl;
}
std::cout << "simulation will run with following parameters" << std::endl;
std::cout << "start of iterations : " << start_of_iterations << " "
<< "end of iterations: " << end_of_iterations << " "
<< "number of iterations : " << number_of_iterations << std::endl << std::endl;
iteration_vector.resize(number_of_iterations);
float step_size = (end_of_iterations - start_of_iterations) / ((float)(number_of_iterations - 1));
int current_iteration = start_of_iterations;
for (itr = iteration_vector.begin(); itr != iteration_vector.end(); current_iteration = current_iteration << 1)
*itr++ = round(current_iteration);
std::ofstream out_file;
out_file.open("iteration_results.txt");
float avg_cpu_alaw_time = 0;
float avg_gpu_alaw_time = 0;
float avg_cpu_ulaw_time = 0;
float avg_gpu_ulaw_time = 0;
float avg_cpu_g722_time = 0;
float avg_gpu_g722_time = 0;
cpu_alaw_vector.resize(number_of_averaging);
gpu_alaw_vector.resize(number_of_averaging);
cpu_ulaw_vector.resize(number_of_averaging);
gpu_ulaw_vector.resize(number_of_averaging);
cpu_g722_vector.resize(number_of_averaging);
gpu_g722_vector.resize(number_of_averaging);
unsigned int no_of_test_packet = end_of_iterations;
unsigned int no_of_test_data = no_of_test_packet * 160;
unsigned char* alaw_data_ptr = NULL;
unsigned char* ulaw_data_ptr = NULL;
unsigned char* g722_data_ptr = NULL;
short int* cpu_decoded_alaw_data_ptr = NULL;
short int* cpu_decoded_ulaw_data_ptr = NULL;
short int* cpu_decoded_g722_data_ptr = NULL;
short int* gpu_decoded_alaw_data_ptr = NULL;
short int* gpu_decoded_ulaw_data_ptr = NULL;
short int* gpu_decoded_g722_data_ptr = NULL;
unsigned int size_of_g722_band = no_of_test_packet * 45;
int* cpu_band_ptr = NULL;
int* gpu_band_ptr = NULL;
int* g722_band_ptr = NULL;
alaw_data_ptr = new unsigned char[no_of_test_data];
ulaw_data_ptr = new unsigned char[no_of_test_data];
g722_data_ptr = new unsigned char[no_of_test_data];
cpu_decoded_alaw_data_ptr = new short int[no_of_test_data];
cpu_decoded_ulaw_data_ptr = new short int[no_of_test_data];
cpu_decoded_g722_data_ptr = new short int[no_of_test_data];
gpu_decoded_alaw_data_ptr = new short int[no_of_test_data];
gpu_decoded_ulaw_data_ptr = new short int[no_of_test_data];
gpu_decoded_g722_data_ptr = new short int[no_of_test_data];
cpu_band_ptr = new int[size_of_g722_band];
gpu_band_ptr = new int[size_of_g722_band];
g722_band_ptr = new int[size_of_g722_band];
//std::memset(cpu_band_ptr, 0, size_of_g722_band * sizeof(int));
//std::memset(gpu_band_ptr, 0, size_of_g722_band * sizeof(int));
srand(time(NULL));
// initialize gpu
CudaGpuInitialize();
std::cout << "iterations" << '\t'
<< "g711a cpu" << '\t' << "g711a gpu" << '\t' << "speedup" << '\t'
<< "g711u cpu" << '\t' << "g711u gpu" << '\t' << "speedup" << '\t'
<< "g722 cpu" << '\t' << "g722 gpu" << '\t' << "speedup" << std::endl;
std::cout << "---------------------------------------------------------------------------------------------------------" << std::endl;
out_file << "iterations" << '\t'
<< "g711a cpu" << '\t' << "g711a gpu" << '\t' << "speedup" << '\t'
<< "g711u cpu" << '\t' << "g711u gpu" << '\t' << "speedup" << '\t'
<< "g722 cpu" << '\t' << "g722 gpu" << '\t' << "speedup" << std::endl;
// loop through iteration vector
std::cout << std::fixed << std::setprecision(5);
for (itr = iteration_vector.begin(); itr != iteration_vector.end();)
{
no_of_test_packet = *itr++;
no_of_test_data = no_of_test_packet * 160;
size_of_g722_band = no_of_test_packet * 45;
avg_cpu_alaw_time = 0;
avg_gpu_alaw_time = 0;
avg_cpu_ulaw_time = 0;
avg_gpu_ulaw_time = 0;
avg_cpu_g722_time = 0;
avg_gpu_g722_time = 0;
float cpu_ulaw_time = 0;
float cpu_alaw_time = 0;
float cpu_g722_time = 0;
for (int k=0; k<number_of_averaging; k++)
{
// generate alaw test data
GenerateG711aData(alaw_data_ptr, no_of_test_data, COALESCED);
// generate ulaw test data
GenerateG711uData(ulaw_data_ptr, no_of_test_data, COALESCED);
// generate g722 test data
GenerateG722Data(g722_data_ptr, g722_band_ptr, no_of_test_data, COALESCED);
std::memcpy(cpu_band_ptr, g722_band_ptr, size_of_g722_band * sizeof(int));
std::memcpy(gpu_band_ptr, g722_band_ptr, size_of_g722_band * sizeof(int));
// calculate cpu cases once since it takes too much time to complete
//if (10 > k)
{
// decode ulaw using cpu
std::clock_t cpu_ulaw_start = std::clock();
G711uToPcm(ulaw_data_ptr, no_of_test_data, cpu_decoded_ulaw_data_ptr);
std::clock_t cpu_ulaw_stop = std::clock();
cpu_ulaw_time = (cpu_ulaw_stop - cpu_ulaw_start)/((float) CLOCKS_PER_SEC);
//std::cout << cpu_ulaw_time << std::endl;
// decode alaw using cpu
std::clock_t cpu_alaw_start = std::clock();
G711aToPcm(alaw_data_ptr, no_of_test_data, cpu_decoded_alaw_data_ptr);
std::clock_t cpu_alaw_stop = std::clock();
cpu_alaw_time = (cpu_alaw_stop - cpu_alaw_start)/((float) CLOCKS_PER_SEC);
//std::cout << cpu_alaw_time << std::endl;
// decode g722 using cpu
std::clock_t cpu_g722_start = std::clock();
G722ToPcm(g722_data_ptr, cpu_band_ptr, no_of_test_data, cpu_decoded_g722_data_ptr);
std::clock_t cpu_g722_stop = std::clock();
cpu_g722_time = (cpu_g722_stop - cpu_g722_start)/((float) CLOCKS_PER_SEC);
}
// decode ulaw using gpu
std::clock_t gpu_ulaw_start = std::clock();
CudaG711uToPcm(ulaw_data_ptr, no_of_test_data, gpu_decoded_ulaw_data_ptr);
std::clock_t gpu_ulaw_stop = std::clock();
float gpu_ulaw_time = (gpu_ulaw_stop - gpu_ulaw_start)/((float) CLOCKS_PER_SEC);
// decode alaw using gpu
std::clock_t gpu_alaw_start = std::clock();
CudaG711aToPcm(alaw_data_ptr, no_of_test_data, gpu_decoded_alaw_data_ptr);
std::clock_t gpu_alaw_stop = std::clock();
float gpu_alaw_time = (gpu_alaw_stop - gpu_alaw_start)/((float) CLOCKS_PER_SEC);
// decode g722 using gpu
std::clock_t gpu_g722_start = std::clock();
CudaG722ToPcm(g722_data_ptr, gpu_band_ptr, no_of_test_data, gpu_decoded_g722_data_ptr);
std::clock_t gpu_g722_stop = std::clock();
float gpu_g722_time = (gpu_g722_stop - gpu_g722_start)/((float) CLOCKS_PER_SEC);
/*out_file << no_of_test_packet << "\t"
<< cpu_alaw_time << "\t" << gpu_alaw_time << "\t"
<< cpu_ulaw_time << "\t" << gpu_ulaw_time << "\t"
<< cpu_g722_time << "\t" << gpu_g722_time << std::endl; */
cpu_alaw_vector[k] = cpu_alaw_time;
gpu_alaw_vector[k] = gpu_alaw_time;
cpu_ulaw_vector[k] = cpu_ulaw_time;
gpu_ulaw_vector[k] = gpu_ulaw_time;
cpu_g722_vector[k] = cpu_g722_time;
gpu_g722_vector[k] = gpu_g722_time;
avg_cpu_alaw_time += (cpu_alaw_time/number_of_averaging);
avg_gpu_alaw_time += (gpu_alaw_time/number_of_averaging);
avg_cpu_ulaw_time += (cpu_ulaw_time/number_of_averaging);
avg_gpu_ulaw_time += (gpu_ulaw_time/number_of_averaging);
avg_cpu_g722_time += (cpu_g722_time/number_of_averaging);
avg_gpu_g722_time += (gpu_g722_time/number_of_averaging);
}
// calculate std variance
float std_cpu_alaw_time = 0;
float std_gpu_alaw_time = 0;
float std_cpu_ulaw_time = 0;
float std_gpu_ulaw_time = 0;
float std_cpu_g722_time = 0;
float std_gpu_g722_time = 0;
for (int k=0; k<number_of_averaging; k++)
{
std_cpu_alaw_time += pow((cpu_alaw_vector[k] - avg_cpu_alaw_time), 2.0);
std_gpu_alaw_time += pow((gpu_alaw_vector[k] - avg_gpu_alaw_time), 2.0);
std_cpu_ulaw_time += pow((cpu_ulaw_vector[k] - avg_cpu_ulaw_time), 2.0);
std_gpu_ulaw_time += pow((gpu_ulaw_vector[k] - avg_gpu_ulaw_time), 2.0);
std_cpu_g722_time += pow((cpu_g722_vector[k] - avg_cpu_g722_time), 2.0);
std_gpu_g722_time += pow((gpu_g722_vector[k] - avg_gpu_g722_time), 2.0);
}
// display results
std::cout << no_of_test_packet << "\t\t"
<< avg_cpu_alaw_time << '(' << std_cpu_alaw_time << ')' << "\t"
<< avg_gpu_alaw_time << '(' << std_gpu_alaw_time << ')' << "\t"
<< avg_cpu_alaw_time/avg_gpu_alaw_time << "\t"
<< avg_cpu_ulaw_time << '(' << std_cpu_ulaw_time << ')' << "\t"
<< avg_gpu_ulaw_time << '(' << std_gpu_ulaw_time << ')' << "\t"
<< avg_cpu_ulaw_time/avg_gpu_ulaw_time << "\t"
<< avg_cpu_g722_time << '(' << std_cpu_g722_time << ')' << "\t"
<< avg_gpu_g722_time << '(' << std_gpu_g722_time << ')' << "\t"
<< avg_cpu_g722_time/avg_gpu_g722_time << std::endl;
out_file << no_of_test_packet << "\t"
<< avg_cpu_alaw_time << '(' << std_cpu_alaw_time << ')' << "\t"
<< avg_gpu_alaw_time << '(' << std_gpu_alaw_time << ')' << "\t"
<< avg_cpu_alaw_time/avg_gpu_alaw_time << "\t"
<< avg_cpu_ulaw_time << '(' << std_cpu_ulaw_time << ')' << "\t"
<< avg_gpu_ulaw_time << '(' << std_gpu_ulaw_time << ')' << "\t"
<< avg_cpu_ulaw_time/avg_gpu_ulaw_time << "\t"
<< avg_cpu_g722_time << '(' << std_cpu_g722_time << ')' << "\t"
<< avg_gpu_g722_time << '(' << std_gpu_g722_time << ')' << "\t"
<< avg_cpu_g722_time/avg_gpu_g722_time << std::endl;
}
CompareArrays<short int>(cpu_decoded_alaw_data_ptr, gpu_decoded_alaw_data_ptr, no_of_test_data);
std::cout << std::endl;
CompareArrays<short int>(cpu_decoded_ulaw_data_ptr, gpu_decoded_ulaw_data_ptr, no_of_test_data);
std::cout << std::endl;
CompareArrays<short int>(cpu_decoded_g722_data_ptr, gpu_decoded_g722_data_ptr, no_of_test_data);
CompareArrays<int>(cpu_band_ptr, gpu_band_ptr, size_of_g722_band);
std::cout << std::endl;
out_file.close();
if(alaw_data_ptr)
delete []alaw_data_ptr;
if(ulaw_data_ptr)
delete []ulaw_data_ptr;
if(g722_data_ptr)
delete []g722_data_ptr;
if(cpu_decoded_alaw_data_ptr)
delete []cpu_decoded_alaw_data_ptr;
if(cpu_decoded_ulaw_data_ptr)
delete []cpu_decoded_ulaw_data_ptr;
if(cpu_decoded_g722_data_ptr)
delete []cpu_decoded_g722_data_ptr;
if(cpu_band_ptr)
delete []cpu_band_ptr;
if(gpu_decoded_alaw_data_ptr)
delete []gpu_decoded_alaw_data_ptr;
if(gpu_decoded_ulaw_data_ptr)
delete []gpu_decoded_ulaw_data_ptr;
if(gpu_decoded_g722_data_ptr)
delete []gpu_decoded_g722_data_ptr;
if(gpu_band_ptr)
delete []gpu_band_ptr;
return 0;
}
| 37.185185 | 138 | 0.609562 | [
"vector"
] |
795dcd947985d481acea0c12890b04e768e666cb | 10,065 | cpp | C++ | TreeGenesis/main.cpp | Angramme/TreeGenerator | 943e36f4e1894fd048390d32648fbe22276e9b90 | [
"MIT"
] | 2 | 2020-12-18T18:42:05.000Z | 2021-09-06T20:04:40.000Z | TreeGenesis/main.cpp | Angramme/TreeGenerator | 943e36f4e1894fd048390d32648fbe22276e9b90 | [
"MIT"
] | null | null | null | TreeGenesis/main.cpp | Angramme/TreeGenerator | 943e36f4e1894fd048390d32648fbe22276e9b90 | [
"MIT"
] | null | null | null | #include <string>
#include <sstream>
#include <math.h>
#include <ctime>
#include <iostream>
#include <Urho3D/Core/CoreEvents.h>
#include <Urho3D/Engine/Application.h>
#include <Urho3D/Engine/Engine.h>
#include <Urho3D/Input/Input.h>
#include <Urho3D/Input/InputEvents.h>
#include <Urho3D/Resource/ResourceCache.h>
#include <Urho3D/Resource/XMLFile.h>
#include <Urho3D/IO/Log.h>
#include <Urho3D/UI/UI.h>
#include <Urho3D/UI/Text.h>
#include <Urho3D/UI/Font.h>
#include <Urho3D/UI/Button.h>
#include <Urho3D/UI/Window.h>
#include <Urho3D/UI/UIEvents.h>
#include <Urho3D/Scene/Scene.h>
#include <Urho3D/Scene/SceneEvents.h>
#include <Urho3D/Graphics/Graphics.h>
#include <Urho3D/Graphics/Camera.h>
#include <Urho3D/Graphics/Geometry.h>
#include <Urho3D/Graphics/Renderer.h>
#include <Urho3D/Graphics/DebugRenderer.h>
#include <Urho3D/Graphics/Octree.h>
#include <Urho3D/Graphics/Light.h>
#include <Urho3D/Graphics/Model.h>
#include <Urho3D/Graphics/StaticModel.h>
#include <Urho3D/Graphics/Material.h>
#include <Urho3D/Graphics/Skybox.h>
#include <Urho3D\Graphics\BillboardSet.h>
#include <Urho3D/Core/Context.h>
//////////////////////
#include "Tree.h"
using namespace Urho3D;
/**
* Using the convenient Application API we don't have
* to worry about initializing the engine or writing a main.
* You can probably mess around with initializing the engine
* and running a main manually, but this is convenient and portable.
*/
class MyApp : public Application
{
public:
int framecount_;
float time_;
SharedPtr<Text> text_;
SharedPtr<Scene> scene_;
SharedPtr<Node> cameraNode_;
SharedPtr<Window> window_;
MyApp(Context * context) : Application(context), framecount_(0), time_(0)
{
}
virtual void Setup()
{
engineParameters_["FullScreen"] = false;
engineParameters_["WindowWidth"] = 1280;
engineParameters_["WindowHeight"] = 720;
engineParameters_["WindowResizable"] = true;
}
virtual void Start()
{
OpenConsoleWindow();
ResourceCache* cache = GetSubsystem<ResourceCache>();
//GUI
initUI(context_);
//RENDERING
scene_ = new Scene(context_);
scene_->CreateComponent<Octree>();
Node* skyNode = scene_->CreateChild("Sky");
//skyNode->SetScale(500.0f); // The scale actually does not matter
Skybox* skybox = skyNode->CreateComponent<Skybox>();
skybox->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
skybox->SetMaterial(cache->GetResource<Material>("Materials/Skybox.xml"));
cameraNode_ = scene_->CreateChild("Camera");
cameraNode_->SetPosition(Vector3(-15, 40, -15));
Camera* camera = cameraNode_->CreateComponent<Camera>();
camera->SetFarClip(2000);
{ // SunLight
Node* lightNode = scene_->CreateChild();
lightNode->SetDirection(Vector3::FORWARD);
lightNode->Yaw(30);
lightNode->Pitch(75);
Light* light = lightNode->CreateComponent<Light>();
light->SetLightType(LIGHT_DIRECTIONAL);
light->SetBrightness(1.6);
light->SetColor(Color(1.0, .99, 0.99, 1));
light->SetCastShadows(true);
}
Tree::tParameters treeparams = {
Tree::CrownType::BOX, 1500, {0, 20, 0}, {16,16,16},
8.0f, 3.0f, 1.0f,
{Tree::vec3f(0,0,0)},
1, true, 0.2, 2.5, 4, 7,
{50,50,50}
};
SharedPtr<Model> treemodel = Tree::getUrhoModelFromParams(context_, treeparams);
Node* treenode = scene_->CreateChild("tree-node");
StaticModel* treeobj = treenode->CreateComponent<StaticModel>();
treeobj->SetModel(treemodel);
treeobj->SetMaterial(cache->GetResource<Material>("Materials/TreeTrunk.xml"));
treeobj->SetCastShadows(true);
{ //save geometry to external file!
PODVector<Drawable*> pod;
pod.Push(treeobj);
String filename = "output.obj";
SharedPtr<File>file = SharedPtr<File>(new File(context_, filename, FILE_WRITE));
WriteDrawablesToOBJ(pod, file, false, false);
file->Close();
}
Node* boxnode = scene_->CreateChild("ground");
boxnode->SetPosition({0,0,0});
boxnode->SetScale({15,1,15});
StaticModel* boxobj = boxnode->CreateComponent<StaticModel>();
boxobj->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
boxobj->SetMaterial(cache->GetResource<Material>("Materials/Dirt.xml"));
boxobj->SetCastShadows(true);
// Now we setup the viewport. Of course, you can have more than one!
Renderer* renderer = GetSubsystem<Renderer>();
SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
renderer->SetViewport(0, viewport);
SubscribeToEvent(E_POSTRENDERUPDATE, URHO3D_HANDLER(MyApp, HandlePostRenderUpdate));
SubscribeToEvent(E_KEYDOWN, URHO3D_HANDLER(MyApp, HandleKeyDown));
SubscribeToEvent(E_UPDATE, URHO3D_HANDLER(MyApp, HandleUpdate));
SubscribeToEvent(E_UIMOUSECLICK, URHO3D_HANDLER(MyApp, HandleControlClicked));
}
virtual void Stop()
{
}
void initUI(Context* context_)
{
auto* cache = GetSubsystem<ResourceCache>();
auto* graphics = GetSubsystem<Graphics>();
auto* ui_root = GetSubsystem<UI>()->GetRoot();
auto* ui_ = GetSubsystem<UI>();
auto* style = cache->GetResource<XMLFile>("UI/DefaultStyle.xml");
ui_root->SetDefaultStyle(style);
context_->GetSubsystem<Urho3D::Input>()->SetMouseVisible(true);
static Urho3D::Cursor* cursor = new Urho3D::Cursor(context_);
cursor->SetShape(Urho3D::CursorShape::CS_IBEAM);
//if(!GetSubsystem<Urho3D::UI>()->GetCursor()) // If I uncomment this it doesn't crash but does also nothing
///////separate
//GetSubsystem<Urho3D::UI>()->SetCursor(cursor);
text_ = new Text(context_);
text_->SetText("Keys: Mouse2 = rotate camera, Mouse2 + AWSD = move camera, Shift = fast mode, Esc = quit.\nWait a bit to see FPS.");
text_->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 10);
text_->SetColor(Color(0, 0, 0));
text_->SetHorizontalAlignment(HA_LEFT);
text_->SetVerticalAlignment(VA_TOP);
ui_root->AddChild(text_);
window_ = new Window(context_);
ui_root->AddChild(window_);
window_->SetMinWidth(384);
window_->SetLayout(LM_VERTICAL, 6, IntRect(6, 6, 6, 6));
//window_->SetAlignment(HA_LEFT, VA_CENTER);
window_->SetPosition({ 10, 35 });
window_->SetName("Window");
window_->SetColor({0, 0, 0, 0.5});
// Create Window 'titlebar' container
auto* titleBar = new UIElement(context_);
titleBar->SetMinSize(0, 24);
titleBar->SetVerticalAlignment(VA_TOP);
titleBar->SetLayoutMode(LM_HORIZONTAL);
// Create the Window title Text
auto* windowTitle = new Text(context_);
windowTitle->SetName("WindowTitle");
windowTitle->SetText("Hello GUI!");
// Create the Window's close button
auto* buttonClose = new Button(context_);
buttonClose->SetName("CloseButton");
// Add the controls to the title bar
titleBar->AddChild(windowTitle);
titleBar->AddChild(buttonClose);
// Add the title bar to the Window
window_->AddChild(titleBar);
window_->SetStyleAuto();
windowTitle->SetStyleAuto();
buttonClose->SetStyle("CloseButton");
}
void HandleControlClicked(StringHash eventType, VariantMap& eventData) //handles clicks anywhere on the screen
{
// Get the Text control acting as the Window's title
auto* windowTitle = window_->GetChildStaticCast<Text>("WindowTitle", true);
// Get control that was clicked
auto* clicked = static_cast<UIElement*>(eventData[UIMouseClick::P_ELEMENT].GetPtr());
String name = "...?";
if (clicked)
{
// Get the name of the control that was clicked
name = clicked->GetName();
}
// Update the Window's title text
windowTitle->SetText("Hello " + name + "!");
}
void HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData)
{
}
void HandleKeyDown(StringHash eventType, VariantMap& eventData)
{
using namespace KeyDown;
int key = eventData[P_KEY].GetInt();
if (key == KEY_ESCAPE)
engine_->Exit();
/*if (key == KEY_TAB) // toggle mouse cursor when pressing tab
{
GetSubsystem<Input>()->SetMouseVisible(!GetSubsystem<Input>()->IsMouseVisible());
//GetSubsystem<Input>()->SetMouseGrabbed(!GetSubsystem<Input>()->IsMouseGrabbed());
}*/
}
void HandleUpdate(StringHash eventType, VariantMap& eventData)
{
float timeStep = eventData[Update::P_TIMESTEP].GetFloat();
framecount_++;
time_ += timeStep;
// Movement speed as world units per second
float MOVE_SPEED = 10.0f;
// Mouse sensitivity as degrees per pixel
const float MOUSE_SENSITIVITY = 0.1f;
if (time_ >= 3.14159 * 2)
{
std::string str;
{
std::ostringstream ss;
ss << (float)framecount_ / time_;
std::string s(ss.str());
str.append(s.substr(0, 6));
}
str.append(" fps \nPlease hold Mouse2 to move and rotate the camera");
String s(str.c_str(), str.size());
text_->SetText(s);
//URHO3D_LOGINFO(s); // this shows how to put stuff into the log
framecount_ = 0;
time_ = 0;
}
auto* input = GetSubsystem<Input>();
input->SetMouseVisible(!input->GetMouseButtonDown(4));
if (input->GetMouseButtonDown(4)) { //m2 pressed
if (input->GetQualifierDown(1)) // 1 is shift, 2 is ctrl, 4 is alt
MOVE_SPEED *= 10;
if (input->GetScancodeDown(26))
cameraNode_->Translate(Vector3(0, 0, 1)*MOVE_SPEED*timeStep);
if (input->GetScancodeDown(22))
cameraNode_->Translate(Vector3(0, 0, -1)*MOVE_SPEED*timeStep);
if (input->GetScancodeDown(4))
cameraNode_->Translate(Vector3(-1, 0, 0)*MOVE_SPEED*timeStep);
if (input->GetScancodeDown(7))
cameraNode_->Translate(Vector3(1, 0, 0)*MOVE_SPEED*timeStep);
}
//if (!GetSubsystem<Input>()->IsMouseVisible())
if (input->GetMouseButtonDown(4))
{
// Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
IntVector2 mouseMove = input->GetMouseMove();
static float yaw_ = 45;
static float pitch_ = 45;
yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;
pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;
pitch_ = Clamp(pitch_, -90.0f, 90.0f);
// Reset rotation and set yaw and pitch again
cameraNode_->SetDirection(Vector3::FORWARD);
cameraNode_->Yaw(yaw_);
cameraNode_->Pitch(pitch_);
}
}
};
URHO3D_DEFINE_APPLICATION_MAIN(MyApp) | 30.225225 | 134 | 0.706508 | [
"geometry",
"model"
] |
795fcc4d1ca6e5e66d345aa6d69bfb142fdbad6e | 3,915 | cc | C++ | minkindr_conversions/test/kindr_msg_test.cc | kamilritz/minkindr_ros | 5ab62e86a5ae495476a014b1e318bbac6b6b044e | [
"BSD-3-Clause"
] | 2 | 2020-11-24T11:16:48.000Z | 2021-04-02T05:14:44.000Z | minkindr_conversions/test/kindr_msg_test.cc | kamilritz/minkindr_ros | 5ab62e86a5ae495476a014b1e318bbac6b6b044e | [
"BSD-3-Clause"
] | 1 | 2021-02-19T14:31:39.000Z | 2021-12-24T02:55:39.000Z | minkindr_conversions/test/kindr_msg_test.cc | kamilritz/minkindr_ros | 5ab62e86a5ae495476a014b1e318bbac6b6b044e | [
"BSD-3-Clause"
] | 3 | 2021-03-24T08:34:25.000Z | 2022-02-28T07:17:54.000Z | #include <Eigen/Core>
#include <Eigen/Geometry>
#include <glog/logging.h>
#include <gtest/gtest.h>
#include <kindr/minimal/quat-transformation.h>
#include <kindr/minimal/transform-2d.h>
#include "minkindr_conversions/kindr_msg.h"
#include "testing_predicates.h"
namespace tf {
const double kTestTolerance = std::numeric_limits<double>::epsilon() * 3;
TEST(KindrMsgTest, poseKindrToMsgToKindr) {
Eigen::Quaterniond rotation(Eigen::Vector4d::Random());
rotation.normalize();
Eigen::Vector3d position(Eigen::Vector3d::Random());
kindr::minimal::QuatTransformation kindr_transform(rotation, position);
geometry_msgs::Pose msg;
poseKindrToMsg(kindr_transform, &msg);
kindr::minimal::QuatTransformation output_transform;
poseMsgToKindr(msg, &output_transform);
EXPECT_NEAR_EIGEN(
output_transform.getRotation().toImplementation().coeffs(),
rotation.coeffs(), kTestTolerance);
EXPECT_NEAR_EIGEN(output_transform.getPosition(), position, kTestTolerance);
}
TEST(KindrMsgTest, poseKindr2DToMsgToKindr2D) {
static constexpr double kTestRotationAngleRad = 0.5;
Eigen::Rotation2D<double> rotation(kTestRotationAngleRad);
const Eigen::Vector2d position = Eigen::Vector2d::Random();
kindr::minimal::Transformation2D kindr_transform(rotation, position);
geometry_msgs::Pose msg;
poseKindr2DToMsg(kindr_transform, &msg);
kindr::minimal::Transformation2D output_transform;
poseMsgToKindr2D(msg, &output_transform);
EXPECT_NEAR(
output_transform.getRotation().angle(), rotation.angle(), kTestTolerance);
EXPECT_NEAR_EIGEN(output_transform.getPosition(), position, kTestTolerance);
}
TEST(KindrMsgTest, poseMsgToKindr2DFailsForInvalidInputPose) {
geometry_msgs::Pose invalid_position_msg;
invalid_position_msg.position.z = 1.0;
kindr::minimal::Transformation2D invalid_position_output_transform;
EXPECT_DEATH(
poseMsgToKindr2D(
invalid_position_msg, &invalid_position_output_transform),
"No proper 2D position.");
geometry_msgs::Pose invalid_rotation_msg;
kindr::minimal::Transformation2D invalid_rotation_output_transform;
const kindr::minimal::RotationQuaternion invalid_2d_rotation(
kindr::minimal::AngleAxis(0.5, 0.0, 1.0, 0.0));
quaternionKindrToMsg(invalid_2d_rotation, &invalid_rotation_msg.orientation);
EXPECT_DEATH(
poseMsgToKindr2D(invalid_rotation_msg, &invalid_rotation_output_transform),
"No proper 2D rotation.");
}
TEST(KindrMsgTest, transformKindrToMsgToKindr) {
Eigen::Quaterniond rotation(Eigen::Vector4d::Random());
rotation.normalize();
Eigen::Vector3d position(Eigen::Vector3d::Random());
kindr::minimal::QuatTransformation kindr_transform(rotation, position);
geometry_msgs::Transform msg;
transformKindrToMsg(kindr_transform, &msg);
kindr::minimal::QuatTransformation output_transform;
transformMsgToKindr(msg, &output_transform);
EXPECT_NEAR_EIGEN(
output_transform.getRotation().toImplementation().coeffs(),
rotation.coeffs(), kTestTolerance);
EXPECT_NEAR_EIGEN(output_transform.getPosition(), position, kTestTolerance);
}
TEST(KindrMsgTest, quaternionKindrToMsgToKindr) {
Eigen::Quaterniond rotation(Eigen::Vector4d::Random());
rotation.normalize();
geometry_msgs::Quaternion msg;
quaternionKindrToMsg(rotation, &msg);
Eigen::Quaterniond output_rotation;
quaternionMsgToKindr(msg, &output_rotation);
EXPECT_NEAR_EIGEN(
output_rotation.coeffs(), rotation.coeffs(), kTestTolerance);
}
TEST(KindrMsgTest, vectorKindrToMsgToKindr) {
Eigen::Vector3d position(Eigen::Vector3d::Random());
geometry_msgs::Vector3 msg;
vectorKindrToMsg(position, &msg);
Eigen::Vector3d output_position;
vectorMsgToKindr(msg, &output_position);
EXPECT_NEAR_EIGEN(output_position, position, kTestTolerance);
}
} // namespace tf
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 34.342105 | 81 | 0.774713 | [
"geometry",
"transform"
] |
7964994428b4b4818f0d088796fd7498300cc414 | 3,257 | cpp | C++ | src/day03/day03.cpp | wilcorook/advent-of-code-2021 | 8c7f51484c3cd28a90b304cbc924e9f05a03a052 | [
"MIT"
] | 3 | 2021-12-01T08:05:57.000Z | 2021-12-09T12:10:29.000Z | src/day03/day03.cpp | wilcorook/advent-of-code-2021 | 8c7f51484c3cd28a90b304cbc924e9f05a03a052 | [
"MIT"
] | null | null | null | src/day03/day03.cpp | wilcorook/advent-of-code-2021 | 8c7f51484c3cd28a90b304cbc924e9f05a03a052 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <vector>
#include "../util/util.h"
int day03puzzle1()
{
std::string gammaStr = "";
std::string epsilonStr = "";
std::vector<std::string> input;
std::string fileName = "day03.txt";
input = getStringsFromFile(fileName.c_str(), 1000);
// character
for (int i = 0; i < 12; i++)
{
int zero = 0;
int one = 0;
// line
for (int c = 0; c < 1000; c++)
{
if (input[c][i] == '0')
{
zero++;
}
if (input[c][i] == '1')
{
one++;
}
}
if (zero > one)
{
gammaStr += std::to_string(0);
epsilonStr += std::to_string(1);
}
else
{
gammaStr += std::to_string(1);
epsilonStr += std::to_string(0);
}
zero = 0;
one = 0;
}
int gammaDecimal = std::stoi(gammaStr, 0, 2);
int epsilonDecimal = std::stoi(epsilonStr, 0, 2);
return gammaDecimal * epsilonDecimal;
}
int findOxygenNumbers(std::vector<std::string> input, int pos)
{
int zero = 0;
int one = 0;
// line
for (int c = 0; c < input.size(); c++)
{
if ((char)input[c][pos] == '0')
{
zero++;
}
if ((char)input[c][pos] == '1')
{
one++;
}
}
if (zero == one)
{
return 1;
}
else if (zero > one)
{
return 0;
}
else
{
return 1;
}
}
int findCO2Numbers(std::vector<std::string> input, int pos)
{
int zero = 0;
int one = 0;
// line
for (int c = 0; c < input.size(); c++)
{
if ((char)input[c][pos] == '0')
{
zero++;
}
if ((char)input[c][pos] == '1')
{
one++;
}
}
if (zero == one)
{
return 0;
}
else if (zero > one)
{
return 1;
}
else
{
return 0;
}
}
void removeNumbers(std::vector<std::string> &input, int index, int bit)
{
char compareChar;
if (bit == 0)
{
compareChar = 48;
}
else
{
compareChar = 49;
}
for (int i = 0; i < input.size(); i++)
{
if ((char)input[i][index] != compareChar)
{
input.erase(input.begin() + i);
// decrease i because the vector size was just decreased
i--;
}
}
}
int day03puzzle2()
{
std::vector<std::string> input;
std::string fileName = "day03.txt";
input = getStringsFromFile(fileName.c_str(), 1000);
std::vector<std::string> oxygen(input);
std::vector<std::string> co2(input);
// check for most and least common, remove from vectors accordingly
for (int i = 0; i < 12; i++)
{
int oxy = findOxygenNumbers(oxygen, i);
int co = findCO2Numbers(co2, i);
removeNumbers(oxygen, i, oxy);
removeNumbers(co2, i, co);
if (oxygen.size() == 1 && co2.size() == 1)
{
break;
}
}
int oxygenDecimal = std::stoi(oxygen[0], 0, 2);
int co2Decimal = std::stoi(co2[0], 0, 2);
return oxygenDecimal * co2Decimal;
} | 19.272189 | 71 | 0.454713 | [
"vector"
] |
7969921f84981a2f74f4776f7a4d127e8a2e4592 | 29,588 | cpp | C++ | src/ftagparams.cpp | glennhickey/context | e7cdb988e2bb6eed5be78567ae7b88378eda9411 | [
"MIT-0"
] | 1 | 2018-04-22T22:16:47.000Z | 2018-04-22T22:16:47.000Z | src/ftagparams.cpp | glennhickey/context | e7cdb988e2bb6eed5be78567ae7b88378eda9411 | [
"MIT-0"
] | null | null | null | src/ftagparams.cpp | glennhickey/context | e7cdb988e2bb6eed5be78567ae7b88378eda9411 | [
"MIT-0"
] | null | null | null | //Copyright (C) 2010 by Glenn Hickey
//
//Released under the MIT license, see LICENSE.txt
#include <vector>
#include <string>
#include <istream>
#include <ostream>
#include <cstdlib>
#include <algorithm>
#include <cassert>
#include <limits>
#include <sstream>
#include <cmath>
#include "ftagparams.h"
using namespace std;
FTAGParams::FTAGParams()
{
for (size_t i = 0; i < Par_Max; ++i)
{
_params[i] = 0.;
_fixed[i] = false;
_clamps[0][i] = 0.;
_clamps[1][i] = numeric_limits<double>::max();
_phases[0][i] = 0;
_phases[1][i] = numeric_limits<size_t>::max();
}
_clamps[1][Par_PE] = 1.;
_clamps[1][Par_PCD] = 1.;
_clamps[1][Par_PCI] = 1.;
_clamps[1][Par_KD] = 1.;
_clamps[1][Par_KI] = 1.;
_clamps[1][Par_P0] = 1;
_clamps[1][Par_P1] = 1;
_clamps[1][Par_P2] = 1;
_clamps[1][Par_P3] = 1;
_clamps[1][Par_Q0] = 1;
_clamps[1][Par_Q1] = 1;
_clamps[1][Par_Q2] = 1;
_clamps[1][Par_Q3] = 1;/*
_clamps[0][Par_P0] = .1;
_clamps[0][Par_P1] = .1;
_clamps[0][Par_P2] = .1;
_clamps[0][Par_P3] = .1;
_clamps[0][Par_Q0] = .1;
_clamps[0][Par_Q1] = .1;
_clamps[0][Par_Q2] = .1;
_clamps[0][Par_Q3] = .1;*/
_isSymmetric = true;
_isUniGap = false;
_singleF84 = false;
_doubleF84 = false;
_isPLinkedGC = false;
_isPLinkedGA = false;
_isQLinkedGC = false;
_isQLinkedGA = false;
_params[Par_P0] = 0.25;
_params[Par_P1] = 0.25;
_params[Par_P2] = 0.25;
_params[Par_P3] = 0.25;
_params[Par_Q0] = 0.25;
_params[Par_Q1] = 0.25;
_params[Par_Q2] = 0.25;
_params[Par_Q3] = 0.25;
}
FTAGParams::FTAGParams(const FTAGParams& params)
{
for (size_t i = 0; i < Par_Max; ++i)
{
_params[i] = params._params[i];
_fixed[i] = params._fixed[i];
_clamps[0][i] = params._clamps[0][i];
_clamps[1][i] = params._clamps[1][i];
_phases[0][i] = params._phases[0][i];
_phases[1][i] = params._phases[1][i];
}
_isSymmetric = params._isSymmetric;
_isUniGap = params._isUniGap;
_singleF84 = params._singleF84;
_doubleF84 = params._doubleF84;
_isPLinkedGC = params._isPLinkedGC;
_isPLinkedGA = params._isPLinkedGA;
_isQLinkedGC = params._isQLinkedGC;
_isQLinkedGA = params._isQLinkedGA;
}
FTAGParams::~FTAGParams()
{
}
FTAGParams& FTAGParams::operator=(const FTAGParams& params)
{
for (size_t i = 0; i < Par_Max; ++i)
{
_params[i] = params._params[i];
_fixed[i] = params._fixed[i];
_clamps[0][i] = params._clamps[0][i];
_clamps[1][i] = params._clamps[1][i];
_phases[0][i] = params._phases[0][i];
_phases[1][i] = params._phases[1][i];
}
_isSymmetric = params._isSymmetric;
_isUniGap = params._isUniGap;
_singleF84 = params._singleF84;
_doubleF84 = params._doubleF84;
_isPLinkedGC = params._isPLinkedGC;
_isPLinkedGA = params._isPLinkedGA;
_isQLinkedGC = params._isQLinkedGC;
_isQLinkedGA = params._isQLinkedGA;
return *this;
}
FTAGParams FTAGParams::operator-(const FTAGParams& params) const
{
FTAGParams diff(*this);
assert(params._isSymmetric == _isSymmetric);
assert(params._singleF84 == _singleF84);
assert(params._doubleF84 == _doubleF84);
for (size_t i = 0; i < Par_Max; ++i)
{
diff._params[i] = _params[i] - params._params[i];
assert(_fixed[i] == params._fixed[i]);
diff._fixed[i] = _fixed[i];
}
return diff;
}
FTAGParams FTAGParams::operator/(const FTAGParams& params) const
{
FTAGParams quot(*this);
assert(params._isSymmetric == _isSymmetric);
assert(params._singleF84 == _singleF84);
assert(params._doubleF84 == _doubleF84);
assert(params._isUniGap == _isUniGap);
for (size_t i = 0; i < Par_Max; ++i)
{
quot._params[i] = _params[i] / params._params[i];
assert(_fixed[i] == params._fixed[i]);
quot._fixed[i] = _fixed[i];
}
return quot;
}
FTAGParams FTAGParams::operator*(const FTAGParams& params) const
{
FTAGParams prod(*this);
assert(params._isSymmetric == _isSymmetric);
assert(params._singleF84 == _singleF84);
assert(params._doubleF84 == _doubleF84);
assert(params._isUniGap == _isUniGap);
for (size_t i = 0; i < Par_Max; ++i)
{
prod._params[i] = _params[i] * params._params[i];
assert(_fixed[i] == params._fixed[i]);
prod._fixed[i] = _fixed[i];
}
return prod;
}
bool FTAGParams::operator==(const FTAGParams& params) const
{
// symmetric flag not tested. should it be?
for (size_t i = 0; i < Par_Max; ++i)
{
if (_params[i] != params._params[i] ||
_fixed[i] != params._fixed[i] ||
_clamps[0][i] != params._clamps[0][i] ||
_clamps[1][i] != params._clamps[1][i] ||
_phases[0][i] != params._phases[0][i] ||
_phases[1][i] != params._phases[1][i])
{
return false;
}
}
return true;
}
bool FTAGParams::isDependent(FTAGParams::Param param) const
{
return (_isSymmetric && param == Par_KI) ||
(_isSymmetric && param == Par_RMI) ||
(_isUniGap && param == Par_RMD) ||
(_isUniGap && param == Par_RMI) ||
((_isPLinkedGC || _isPLinkedGA) &&
(param == Par_P1 || param == Par_P2 || param == Par_P3)) ||
((_isQLinkedGC || _isQLinkedGA) &&
(param == Par_Q1 || param == Par_Q2 || param == Par_Q3));
}
FTAGParams FTAGParams::abs() const
{
FTAGParams par = *this;
for (size_t i = 0; i < Par_Max; ++i)
{
par._params[i] = fabs(par._params[i]);
}
return par;
}
double FTAGParams::mse(const FTAGParams& params) const
{
double total = 0;
double diff;
for (size_t i = 0; i < Par_Max; ++i)
{
diff = _params[i] - params._params[i];
total += diff * diff;
}
return total / (double) Par_Max;
}
void FTAGParams::setA(double a)
{
_params[Par_A] = clamp(Par_A, a);
if (rand() % 5 == 0)
{
double delta = a - _params[Par_A];
_params[Par_B] = clamp(Par_B, _params[Par_B] + delta);
}
if (rand() % 25 == 0)
{
swap(_params[Par_A], _params[Par_B]);
}
}
void FTAGParams::setB(double b)
{
_params[Par_B] = clamp(Par_B, b);
}
void FTAGParams::setC(double c)
{
_params[Par_C] = clamp(Par_C, c);
if (rand() % 5 == 0)
{
double delta = c - _params[Par_C];
_params[Par_D] = clamp(Par_D, _params[Par_D] + delta);
}
if (rand() % 25 == 0)
{
swap(_params[Par_C], _params[Par_D]);
}
}
void FTAGParams::setD(double d)
{
_params[Par_D] = clamp(Par_D, d);
}
void FTAGParams::setP0(double p0)
{
if (rand() % 50)
{
if (_isPLinkedGC == true)
{
_params[Par_P0] = clamp(Par_P0, p0) > 0.5 ? 0.5 : clamp(Par_P0, p0);
_params[Par_P1] = 0.5 - _params[Par_P0];
_params[Par_P2] = _params[Par_P1];
_params[Par_P3] = _params[Par_P0];
}
else if (_isPLinkedGA == true)
{
_params[Par_P0] = clamp(Par_P0, p0) > 0.5 ? 0.5 : clamp(Par_P0, p0);
_params[Par_P1] = 0.5 - _params[Par_P0];
_params[Par_P2] = _params[Par_P0];
_params[Par_P3] = _params[Par_P1];
}
else
{
double delta = clamp(Par_P0, p0) - _params[Par_P0];
double fracDelta;
_params[Par_P0] += delta;
size_t sel = rand() % 4;
switch(sel) {
case 0 :
fracDelta = delta / 3. ;
_params[Par_P1] = clamp(Par_P1, _params[Par_P1] - fracDelta);
_params[Par_P2] = clamp(Par_P2, _params[Par_P2] - fracDelta);
_params[Par_P3] = clamp(Par_P3, _params[Par_P3] - fracDelta);
break;
case 1: _params[Par_P1] = clamp(Par_P1, _params[Par_P1] - delta);
break;
case 2: _params[Par_P2] = clamp(Par_P2, _params[Par_P2] - delta);
break;
case 3: _params[Par_P3] = clamp(Par_P3, _params[Par_P3] - delta);
break;
default : break;
}
normalizeP();
}
}
else if (rand() % 2)
{
_params[Par_P0] = .25; _params[Par_P1] = .25;
_params[Par_P2] = .25; _params[Par_P3] = .25;
}
else
{
randomSwapP();
}
}
void FTAGParams::setP1(double p1)
{
if (!_isPLinkedGC && ! _isPLinkedGA)
{
double delta = clamp(Par_P1, p1) - _params[Par_P1];
double fracDelta;
_params[Par_P1] += delta;
size_t sel = rand() % 4;
switch(sel) {
case 0 :
fracDelta = delta / 3. ;
_params[Par_P0] = clamp(Par_P0, _params[Par_P0] - fracDelta);
_params[Par_P2] = clamp(Par_P2, _params[Par_P2] - fracDelta);
_params[Par_P3] = clamp(Par_P3, _params[Par_P3] - fracDelta);
break;
case 1: _params[Par_P0] = clamp(Par_P0, _params[Par_P0] - delta); break;
case 2: _params[Par_P2] = clamp(Par_P2, _params[Par_P2] - delta); break;
case 3: _params[Par_P3] = clamp(Par_P3, _params[Par_P3] - delta); break;
default : break;
}
normalizeP();
}
}
void FTAGParams::setP2(double p2)
{
if (!_isPLinkedGC && ! _isPLinkedGA)
{
double delta = clamp(Par_P2, p2) - _params[Par_P2];
double fracDelta;
_params[Par_P2] += delta;
size_t sel = rand() % 4;
switch(sel) {
case 0 :
fracDelta = delta / 3. ;
_params[Par_P0] = clamp(Par_P0, _params[Par_P0] - fracDelta);
_params[Par_P1] = clamp(Par_P1, _params[Par_P1] - fracDelta);
_params[Par_P3] = clamp(Par_P3, _params[Par_P3] - fracDelta);
break;
case 1: _params[Par_P0] = clamp(Par_P0, _params[Par_P0] - delta); break;
case 2: _params[Par_P1] = clamp(Par_P1, _params[Par_P1] - delta); break;
case 3: _params[Par_P3] = clamp(Par_P2, _params[Par_P3] - delta); break;
default : break;
}
normalizeP();
}
}
void FTAGParams::setP3(double p3)
{
if (!_isPLinkedGC && ! _isPLinkedGA)
{
double delta = clamp(Par_P3, p3) - _params[Par_P3];
double fracDelta;
_params[Par_P3] += delta;
size_t sel = rand() % 4;
switch(sel) {
case 0 :
fracDelta = delta / 3. ;
_params[Par_P0] = clamp(Par_P0, _params[Par_P0] - fracDelta);
_params[Par_P1] = clamp(Par_P1, _params[Par_P1] - fracDelta);
_params[Par_P2] = clamp(Par_P2, _params[Par_P2] - fracDelta);
break;
case 1: _params[Par_P0] = clamp(Par_P0, _params[Par_P0] - delta); break;
case 2: _params[Par_P1] = clamp(Par_P1, _params[Par_P1] - delta); break;
case 3: _params[Par_P2] = clamp(Par_P2, _params[Par_P2] - delta); break;
default : break;
}
normalizeP();
}
}
void FTAGParams::setQ0(double q0)
{
if (rand() % 50)
{
if (_isQLinkedGC == true)
{
_params[Par_Q0] = clamp(Par_Q0, q0) > 0.5 ? 0.5 : clamp(Par_Q0, q0);
_params[Par_Q1] = 0.5 - _params[Par_Q0];
_params[Par_Q2] = _params[Par_Q1];
_params[Par_Q3] = _params[Par_Q0];
}
else if (_isQLinkedGA == true)
{
_params[Par_Q0] = clamp(Par_Q0, q0) > 0.5 ? 0.5 : clamp(Par_Q0, q0);
_params[Par_Q1] = 0.5 - _params[Par_Q0];
_params[Par_Q2] = _params[Par_Q0];
_params[Par_Q3] = _params[Par_Q1];
}
else
{
double delta = clamp(Par_Q0, q0) - _params[Par_Q0];
double fracDelta;
_params[Par_Q0] += delta;
size_t sel = rand() % 4;
switch(sel) {
case 0 :
fracDelta = delta / 3. ;
_params[Par_Q1] = clamp(Par_Q1, _params[Par_Q1] - fracDelta);
_params[Par_Q2] = clamp(Par_Q2, _params[Par_Q2] - fracDelta);
_params[Par_Q3] = clamp(Par_Q3, _params[Par_Q3] - fracDelta);
break;
case 1: _params[Par_Q1] = clamp(Par_Q1, _params[Par_Q1] - delta);
break;
case 2: _params[Par_Q2] = clamp(Par_Q2, _params[Par_Q2] - delta);
break;
case 3: _params[Par_Q3] = clamp(Par_Q3, _params[Par_Q3] - delta);
break;
default : break;
}
normalizeQ();
}
}
else if (rand() % 2)
{
_params[Par_Q0] = .25; _params[Par_Q1] = .25;
_params[Par_Q2] = .25; _params[Par_Q3] = .25;
}
else
{
randomSwapQ();
}
}
void FTAGParams::setQ1(double q1)
{
if (!_isQLinkedGC && ! _isQLinkedGA)
{
double delta = clamp(Par_Q1, q1) - _params[Par_Q1];
double fracDelta;
_params[Par_Q1] += delta;
size_t sel = rand() % 4;
switch(sel) {
case 0 :
fracDelta = delta / 3. ;
_params[Par_Q0] = clamp(Par_Q0, _params[Par_Q0] - fracDelta);
_params[Par_Q2] = clamp(Par_Q2, _params[Par_Q2] - fracDelta);
_params[Par_Q3] = clamp(Par_Q3, _params[Par_Q3] - fracDelta);
break;
case 1: _params[Par_Q0] = clamp(Par_Q0, _params[Par_Q0] - delta); break;
case 2: _params[Par_Q2] = clamp(Par_Q2, _params[Par_Q2] - delta); break;
case 3: _params[Par_Q3] = clamp(Par_Q3, _params[Par_Q3] - delta); break;
default : break;
}
normalizeQ();
}
}
void FTAGParams::setQ2(double q2)
{
if (!_isQLinkedGC && ! _isQLinkedGA)
{
double delta = clamp(Par_Q2, q2) - _params[Par_Q2];
double fracDelta;
_params[Par_Q2] += delta;
size_t sel = rand() % 4;
switch(sel) {
case 0 :
fracDelta = delta / 3. ;
_params[Par_Q0] = clamp(Par_Q0, _params[Par_Q0] - fracDelta);
_params[Par_Q1] = clamp(Par_Q1, _params[Par_Q1] - fracDelta);
_params[Par_Q3] = clamp(Par_Q3, _params[Par_Q3] - fracDelta);
break;
case 1: _params[Par_Q0] = clamp(Par_Q0, _params[Par_Q0] - delta); break;
case 2: _params[Par_Q1] = clamp(Par_Q1, _params[Par_Q1] - delta); break;
case 3: _params[Par_Q3] = clamp(Par_Q3, _params[Par_Q3] - delta); break;
default : break;
}
normalizeQ();
}
}
void FTAGParams::setQ3(double q3)
{
if (!_isQLinkedGC && ! _isQLinkedGA)
{
double delta = clamp(Par_Q3, q3) - _params[Par_Q3];
double fracDelta;
_params[Par_Q3] += delta;
size_t sel = rand() % 4;
switch(sel) {
case 0 :
fracDelta = delta / 3. ;
_params[Par_Q0] = clamp(Par_Q0, _params[Par_Q0] - fracDelta);
_params[Par_Q1] = clamp(Par_Q1, _params[Par_Q1] - fracDelta);
_params[Par_Q2] = clamp(Par_Q2, _params[Par_Q2] - fracDelta);
break;
case 1: _params[Par_Q0] = clamp(Par_Q0, _params[Par_Q0] - delta); break;
case 2: _params[Par_Q1] = clamp(Par_Q1, _params[Par_Q1] - delta); break;
case 3: _params[Par_Q2] = clamp(Par_Q2, _params[Par_Q2] - delta); break;
default : break;
}
normalizeQ();
}
}
void FTAGParams::normalizeP()
{
double tot = _params[Par_P0] + _params[Par_P1] +
_params[Par_P2] + _params[Par_P3];
if (tot != 0 && tot != 1.)
{
_params[Par_P0] /= tot;
_params[Par_P1] /= tot;
_params[Par_P2] /= tot;
_params[Par_P3] /= tot;
}
// hack
if (_params[Par_P0] < _clamps[0][Par_P0] ||
_params[Par_P0] > _clamps[1][Par_P0] ||
_params[Par_P1] < _clamps[0][Par_P1] ||
_params[Par_P1] > _clamps[1][Par_P1] ||
_params[Par_P2] < _clamps[0][Par_P2] ||
_params[Par_P2] > _clamps[1][Par_P2] ||
_params[Par_P3] < _clamps[0][Par_P3] ||
_params[Par_P3] > _clamps[1][Par_P3])
{
_params[Par_P0] = _params[Par_P1] =
_params[Par_P2] = _params[Par_P3] = .25;
}
}
void FTAGParams::normalizeQ()
{
double tot = _params[Par_Q0] + _params[Par_Q1] +
_params[Par_Q2] + _params[Par_Q3];
if (tot != 0. && tot != 1.)
{
_params[Par_Q0] /= tot;
_params[Par_Q1] /= tot;
_params[Par_Q2] /= tot;
_params[Par_Q3] /= tot;
}
// hack
if (_params[Par_Q0] < _clamps[0][Par_Q0] ||
_params[Par_Q0] > _clamps[1][Par_Q0] ||
_params[Par_Q1] < _clamps[0][Par_Q1] ||
_params[Par_Q1] > _clamps[1][Par_Q1] ||
_params[Par_Q2] < _clamps[0][Par_Q2] ||
_params[Par_Q2] > _clamps[1][Par_Q2] ||
_params[Par_Q3] < _clamps[0][Par_Q3] ||
_params[Par_Q3] > _clamps[1][Par_Q3])
{
_params[Par_Q0] = _params[Par_Q1] =
_params[Par_Q2] = _params[Par_Q3] = .25;
}
}
void FTAGParams::randomSwapP()
{
if (_isPLinkedGC || _isPLinkedGA)
{
swap(_params[Par_P0], _params[Par_P1]);
swap(_params[Par_P2], _params[Par_P3]);
}
else
{
size_t i = rand() % 4;
size_t j = rand() % 4;
while (j == i) j = rand() % 4;
swap(_params[Par_P0 + i], _params[Par_P0 + j]);
}
}
void FTAGParams::randomSwapQ()
{
if (_isQLinkedGC || _isQLinkedGA)
{
swap(_params[Par_Q0], _params[Par_Q1]);
swap(_params[Par_Q2], _params[Par_Q3]);
}
else
{
size_t i = rand() % 4;
size_t j = rand() % 4;
while (j == i) j = rand() % 4;
swap(_params[Par_Q0 + i], _params[Par_Q0 + j]);
}
}
void FTAGParams::setSingleF84(bool sf)
{
_singleF84 = sf;
if (sf == true)
{
setMu(0);
setMuFixed(true);
}
else
{
setPFlatFixed(true);
setA(0);
setAFixed(true);
setB(0);
setBFixed(true);
}
}
void FTAGParams::setDoubleF84(bool df)
{
_doubleF84 = df;
if (df == true)
{
setGamma(0);
setGammaFixed(true);
}
else
{
setQFlatFixed(true);
setC(0);
setCFixed(true);
setD(0);
setDFixed(true);
}
}
void FTAGParams::set(Param param, double val)
{
switch (param)
{
case Par_T:
setT(val);
break;
case Par_Mu:
setMu(val);
break;
case Par_A:
setA(val);
break;
case Par_B:
setB(val);
break;
case Par_P0:
setP0(val);
break;
case Par_P1:
setP1(val);
break;
case Par_P2:
setP2(val);
break;
case Par_P3:
setP3(val);
break;
case Par_Gamma:
setGamma(val);
break;
case Par_C:
setC(val);
break;
case Par_D:
setD(val);
break;
case Par_Q0:
setQ0(val);
break;
case Par_Q1:
setQ1(val);
break;
case Par_Q2:
setQ2(val);
break;
case Par_Q3:
setQ3(val);
break;
case Par_PE:
setPE(val);
break;
case Par_RD:
setRD(val);
break;
case Par_RI:
setRI(val);
break;
case Par_RMD:
setRMD(val);
break;
case Par_RMI:
setRMI(val);
break;
case Par_PCD:
setPCD(val);
break;
case Par_PCI:
setPCI(val);
break;
case Par_KD:
setKD(val);
break;
case Par_KI:
setKI(val);
break;
case Par_Max:
assert(false);
break;
}
}
void FTAGParams::setAll(double val)
{
for (size_t i = 0; i < Par_Max; ++i)
{
_params[i] = val;
}
}
void FTAGParams::setFixed(Param param, bool val)
{
if (!_isSymmetric)
{
_fixed[param] = val;
}
else
{
switch (param)
{
case Par_T:
case Par_Mu:
case Par_A:
case Par_B:
case Par_Gamma:
case Par_C:
case Par_D:
case Par_PE:
_fixed[param] = val;
break;
case Par_RD:
_fixed[param] = val;
_fixed[Par_RI] = val;
break;
case Par_RMD:
_fixed[param] = val;
_fixed[Par_RMI] = val;
break;
case Par_PCD:
_fixed[param] = val;
_fixed[Par_PCI] = val;
break;
case Par_KD:
_fixed[param] = val;
_fixed[Par_KI] = val;
break;
default:
break;
}
}
if (_isUniGap)
{
_fixed[Par_PCI] = _fixed[Par_KI];
_fixed[Par_PCD] = _fixed[Par_KD];
}
}
void FTAGParams::setClamp(Param param, double lower, double upper)
{
assert(lower < upper);
_clamps[0][param] = lower;
_clamps[1][param] = upper;
}
void FTAGParams::randomizeNonFixed()
{
for (size_t i = 0; i < Par_Max; ++i)
{
// redundant since set() should check already
if (isFixed((Param)i) == false)
{
set((Param)i, drand48() * (min(1., _clamps[1][i]) - _clamps[0][i]));
}
}
// seeding with a high PE can be irrecoverable sincel longer
// sequences will run out of precision and get pr=0 every time
// so we prevent with this little hack
if (!isPEFixed() && getPE() > 0.8)
{
setPE(getPE() * 0.8);
}
// same goes for indel rates
// to do: clean this up:
if (!isRDFixed() && getRD() > 0.1)
{
setRD(getRD() * 0.1);
}
if (!isRIFixed() && getRI() > 0.1)
{
setRI(getRI() * 0.1);
}
if (!isKDFixed() && getKD() > 0.5)
{
setKD(getKD() * 0.25);
}
if (!isKIFixed() && getKI() > 0.5)
{
setKI(getKI() * 0.5);
}
if (!isRMDFixed() && getRMD() > 0.1)
{
setRMD(getRMD() * 0.1);
}
if (!isRMIFixed() && getRMI() > 0.1)
{
setRMI(getRMI() * 0.1);
}
if (!isPCDFixed() && getPCD() > 0.95)
{
setPCD(getPCD() * 0.95);
}
if (!isPCIFixed() && getPCI() > 0.95)
{
setPCI(getPCI() * 0.95);
}
if (!isMuFixed() && getMu() > 0.5)
{
setMu(getMu() * 0.5);
}
if (!isAFixed() && getA() > 0.5)
{
setA(getA() * 0.5);
}
if (!isBFixed() && getB() > 0.5)
{
setB(getB() * 0.5);
}
if (!isGammaFixed() && getGamma() > 0.5)
{
setGamma(getGamma() * 0.5);
}
if (!isCFixed() && getC() > 0.5)
{
setC(getC() * 0.5);
}
if (!isDFixed() && getD() > 0.5)
{
setD(getD() * 0.5);
}
// don't randomize priors.
if (!isP0Fixed()) _params[Par_P0] = 0.25;
if (!isP1Fixed()) _params[Par_P1] = 0.25;
if (!isP2Fixed()) _params[Par_P2] = 0.25;
if (!isP3Fixed()) _params[Par_P3] = 0.25;
if (!isQ0Fixed()) _params[Par_Q0] = 0.25;
if (!isQ1Fixed()) _params[Par_Q1] = 0.25;
if (!isQ2Fixed()) _params[Par_Q2] = 0.25;
if (!isQ3Fixed()) _params[Par_Q3] = 0.25;
}
string FTAGParams::asRow() const
{
stringstream row;
row << getT() << " ";
row << getMu() << " ";
row << getA() << " ";
row << getB() << " ";
row << getP0() << " ";
row << getP1() << " ";
row << getP2() << " ";
row << getP3() << " ";
row << getGamma() << " ";
row << getC() << " ";
row << getD() << " ";
row << getQ0() << " ";
row << getQ1() << " ";
row << getQ2() << " ";
row << getQ3() << " ";
row << getRD() << " ";
row << getRI() << " ";
row << getRMD() << " ";
row << getRMI() << " ";
row << getPE() << " ";
row << getPCD() << " ";
row << getPCI() << " ";
row << getKD() << " ";
row << getKI();
return row.str();
}
ostream& operator<<(ostream& os, const FTAGParams& params)
{
os << "<";
if (params.isTFixed()) os << "*";
os << "t= " << params.getT() << " ";
if (params.isMuFixed()) os << "*";
os << "mu= " << params.getMu() << " ";
if (params.isAFixed()) os << "*";
os << "a= " << params.getA() << " ";
if (params.isBFixed()) os << "*";
os << "b= " << params.getB() << " ";
if (params.isP0Fixed()) os << "*";
os << "p0= " << params.getP0() << " ";
if (params.isP1Fixed()) os << "*";
os << "p1= " << params.getP1() << " ";
if (params.isP2Fixed()) os << "*";
os << "p2= " << params.getP2() << " ";
if (params.isP3Fixed()) os << "*";
os << "p3= " << params.getP3() << " ";
if (params.isGammaFixed()) os << "*";
os << "ga= " << params.getGamma() << " ";
if (params.isCFixed()) os << "*";
os << "c= " << params.getC() << " ";
if (params.isDFixed()) os << "*";
os << "d= " << params.getD() << " ";
if (params.isQ0Fixed()) os << "*";
os << "q0= " << params.getQ0() << " ";
if (params.isQ1Fixed()) os << "*";
os << "q1= " << params.getQ1() << " ";
if (params.isQ2Fixed()) os << "*";
os << "q2= " << params.getQ2() << " ";
if (params.isQ3Fixed()) os << "*";
os << "q3= " << params.getQ3() << " ";
if (params.isRDFixed()) os << "*";
os << "RD= " << params.getRD() << " ";
if (params.isRIFixed()) os << "*";
os << "RI= " << params.getRI() << " ";
if (params.isRMDFixed()) os << "*";
os << "RMD= " << params.getRMD() << " ";
if (params.isRMIFixed()) os << "*";
os << "RMI= " << params.getRMI() << " ";
if (params.isPEFixed()) os << "*";
os << "PE= " << params.getPE() << " ";
if (params.isPCDFixed()) os << "*";
os << "PCD= " << params.getPCD() << " ";
if (params.isPCIFixed()) os << "*";
os << "PCI= " << params.getPCI() << " ";
if (params.isKDFixed()) os << "*";
os << "KD= " << params.getKD() << " ";
if (params.isKIFixed()) os << "*";
os << "KI= " << params.getKI() << " >";
os << endl;
return os;
}
istream& operator>>(istream& is, FTAGParams& params)
{
string sbuf;
double dbuf;
is >> sbuf >> dbuf;
if (!is || !(sbuf == "<*t=" || sbuf == "<t="))
{
throw string("Param read error t");
}
params.setTFixed(sbuf[1] == '*');
params.setT(dbuf);
is >> sbuf >> dbuf;
if (!is || !(sbuf == "*mu=" || sbuf == "mu="))
{
throw string("Param read error mu");
}
params.setMuFixed(sbuf[0] == '*');
params.setMu(dbuf);
is >> sbuf >> dbuf;
if (!is || !(sbuf == "*a=" || sbuf == "a="))
{
throw string("Param read error a");
}
params.setAFixed(sbuf[0] == '*');
params.setA(dbuf);
is >> sbuf >> dbuf;
if (!is || !(sbuf == "*b=" || sbuf == "b="))
{
throw string("Param read error b");
}
params.setBFixed(sbuf[0] == '*');
params.setB(dbuf);
is >> sbuf >> dbuf;
if (!is || !(sbuf == "*p0=" || sbuf == "p0="))
{
throw string("Param read error p0");
}
params.setP0Fixed(sbuf[0] == '*');
params.setDirect(FTAGParams::Par_P0, dbuf);
is >> sbuf >> dbuf;
if (!is || !(sbuf == "*p1=" || sbuf == "p1="))
{
throw string("Param read error p1");
}
params.setP1Fixed(sbuf[0] == '*');
params.setDirect(FTAGParams::Par_P1, dbuf);
is >> sbuf >> dbuf;
if (!is || !(sbuf == "*p2=" || sbuf == "p2="))
{
throw string("Param read error p2");
}
params.setP2Fixed(sbuf[0] == '*');
params.setDirect(FTAGParams::Par_P2, dbuf);
is >> sbuf >> dbuf;
if (!is || !(sbuf == "*p3=" || sbuf == "p3="))
{
throw string("Param read error p3");
}
params.setP3Fixed(sbuf[0] == '*');
params.setDirect(FTAGParams::Par_P3, dbuf);
is >> sbuf >> dbuf;
if (!is || !(sbuf == "*ga=" || sbuf == "ga="))
{
throw string("Param read error ga: ") + sbuf;
}
params.setGammaFixed(sbuf[0] == '*');
params.setGamma(dbuf);
is >> sbuf >> dbuf;
if (!is || !(sbuf == "*c=" || sbuf == "c="))
{
throw string("Param read error c");
}
params.setCFixed(sbuf[0] == '*');
params.setC(dbuf);
is >> sbuf >> dbuf;
if (!is || !(sbuf == "*d=" || sbuf == "d="))
{
throw string("Param read error d");
}
params.setDFixed(sbuf[0] == '*');
params.setD(dbuf);
is >> sbuf >> dbuf;
if (!is || !(sbuf == "*q0=" || sbuf == "q0="))
{
throw string("Param read error q0");
}
params.setQ0Fixed(sbuf[0] == '*');
params.setDirect(FTAGParams::Par_Q0, dbuf);
is >> sbuf >> dbuf;
if (!is || !(sbuf == "*q1=" || sbuf == "q1="))
{
throw string("Param read error q1");
}
params.setQ1Fixed(sbuf[0] == '*');
params.setDirect(FTAGParams::Par_Q1, dbuf);
is >> sbuf >> dbuf;
if (!is || !(sbuf == "*q2=" || sbuf == "q2="))
{
throw string("Param read error q2");
}
params.setQ2Fixed(sbuf[0] == '*');
params.setDirect(FTAGParams::Par_Q2, dbuf);
is >> sbuf >> dbuf;
if (!is || !(sbuf == "*q3=" || sbuf == "q3="))
{
throw string("Param read error q3");
}
params.setQ3Fixed(sbuf[0] == '*');
params.setDirect(FTAGParams::Par_Q3, dbuf);
is >> sbuf >> dbuf;
if (!is || !(sbuf == "*RD=" || sbuf == "RD="))
{
throw string("Param read error RD");
}
params.setRDFixed(sbuf[0] == '*');
params.setRD(dbuf);
is >> sbuf >> dbuf;
if (!is || !(sbuf == "*RI=" || sbuf == "RI="))
{
throw string("Param read error RI");
}
params.setRIFixed(sbuf[0] == '*');
params.setRI(dbuf);
is >> sbuf >> dbuf;
if (!is || !(sbuf == "*RMD=" || sbuf == "RMD="))
{
throw string("Param read error RMD");
}
params.setRMDFixed(sbuf[0] == '*');
params.setRMD(dbuf);
is >> sbuf >> dbuf;
if (!is || !(sbuf == "*RMI=" || sbuf == "RMI="))
{
throw string("Param read error RMI");
}
params.setRMIFixed(sbuf[0] == '*');
params.setRMI(dbuf);
is >> sbuf >> dbuf;
if (!is || !(sbuf == "*PE=" || sbuf == "PE="))
{
throw string("Param read error PE");
}
params.setPEFixed(sbuf[0] == '*');
params.setPE(dbuf);
is >> sbuf >> dbuf;
if (!is || !(sbuf == "*PCD=" || sbuf == "PCD="))
{
throw string("Param read error PCD");
}
params.setPCDFixed(sbuf[0] == '*');
params.setPCD(dbuf);
is >> sbuf >> dbuf;
if (!is || !(sbuf == "*PCI=" || sbuf == "PCI="))
{
throw string("Param read error PCI");
}
params.setPCIFixed(sbuf[0] == '*');
params.setPCI(dbuf);
is >> sbuf >> dbuf;
if (!is || !(sbuf == "*KD=" || sbuf == "KD="))
{
throw string("Param read error KD");
}
params.setKDFixed(sbuf[0] == '*');
params.setKD(dbuf);
is >> sbuf >> dbuf;
if (!is || !(sbuf == "*KI=" || sbuf == "KI="))
{
throw string("Param read error KI");
}
params.setKIFixed(sbuf[0] == '*');
params.setKI(dbuf);
is >> sbuf;
return is;
}
| 25.684028 | 78 | 0.533088 | [
"vector"
] |
797831246095639bc493151d9bdcdd1e0c253c9e | 4,253 | cpp | C++ | src/libraries/postProcessing/functionObjects/fvTools/calcFvcDiv/calcFvcDiv.cpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | src/libraries/postProcessing/functionObjects/fvTools/calcFvcDiv/calcFvcDiv.cpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | src/libraries/postProcessing/functionObjects/fvTools/calcFvcDiv/calcFvcDiv.cpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | /*---------------------------------------------------------------------------*\
Copyright (C) 2013-2015 OpenFOAM Foundation
-------------------------------------------------------------------------------
License
This file is part of Caelus.
Caelus is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Caelus 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 Caelus. If not, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
#include "calcFvcDiv.hpp"
#include "volFields.hpp"
#include "dictionary.hpp"
#include "calcFvcDiv.hpp"
// * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * //
namespace CML
{
defineTypeNameAndDebug(calcFvcDiv, 0);
}
// * * * * * * * * * * * * * Private Member Functions * * * * * * * * * * * //
CML::volScalarField& CML::calcFvcDiv::divField
(
const word& divName,
const dimensionSet& dims
)
{
const fvMesh& mesh = refCast<const fvMesh>(obr_);
if (!mesh.foundObject<volScalarField>(divName))
{
volScalarField* divFieldPtr
(
new volScalarField
(
IOobject
(
divName,
mesh.time().timeName(),
mesh,
IOobject::NO_READ,
IOobject::NO_WRITE
),
mesh,
dimensionedScalar("zero", dims/dimLength, 0.0)
)
);
mesh.objectRegistry::store(divFieldPtr);
}
const volScalarField& field = mesh.lookupObject<volScalarField>(divName);
return const_cast<volScalarField&>(field);
}
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
CML::calcFvcDiv::calcFvcDiv
(
const word& name,
const objectRegistry& obr,
const dictionary& dict,
const bool loadFromFiles
)
:
name_(name),
obr_(obr),
active_(true),
fieldName_("undefined-fieldName"),
resultName_("undefined-resultName")
{
// Check if the available mesh is an fvMesh, otherwise deactivate
if (!isA<fvMesh>(obr_))
{
active_ = false;
WarningInFunction
<< "No fvMesh available, deactivating." << nl
<< endl;
}
read(dict);
}
// * * * * * * * * * * * * * * * * Destructor * * * * * * * * * * * * * * * //
CML::calcFvcDiv::~calcFvcDiv()
{}
// * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
void CML::calcFvcDiv::read(const dictionary& dict)
{
if (active_)
{
dict.lookup("fieldName") >> fieldName_;
dict.lookup("resultName") >> resultName_;
if (resultName_ == "none")
{
resultName_ = "fvc::div(" + fieldName_ + ")";
}
}
}
void CML::calcFvcDiv::execute()
{
if (active_)
{
bool processed = false;
calcDiv<surfaceScalarField>(fieldName_, resultName_, processed);
calcDiv<volVectorField>(fieldName_, resultName_, processed);
if (!processed)
{
WarningInFunction
<< "Unprocessed field " << fieldName_ << endl;
}
}
}
void CML::calcFvcDiv::end()
{
if (active_)
{
execute();
}
}
void CML::calcFvcDiv::timeSet()
{
// Do nothing
}
void CML::calcFvcDiv::write()
{
if (active_)
{
if (obr_.foundObject<regIOobject>(resultName_))
{
const regIOobject& field =
obr_.lookupObject<regIOobject>(resultName_);
Info<< type() << " " << name_ << " output:" << nl
<< " writing field " << field.name() << nl << endl;
field.write();
}
}
}
// ************************************************************************* //
| 24.028249 | 79 | 0.501763 | [
"mesh"
] |
798015d475fd7cc63901026e121e50492334eb71 | 12,174 | cpp | C++ | lugre/src/lugre_thread_L.cpp | ghoulsblade/vegaogre | 2ece3b799f9bd667f081d47c1a0f3ef5e78d3e0f | [
"MIT"
] | 1 | 2020-10-18T14:33:05.000Z | 2020-10-18T14:33:05.000Z | lugre/src/lugre_thread_L.cpp | ghoulsblade/vegaogre | 2ece3b799f9bd667f081d47c1a0f3ef5e78d3e0f | [
"MIT"
] | null | null | null | lugre/src/lugre_thread_L.cpp | ghoulsblade/vegaogre | 2ece3b799f9bd667f081d47c1a0f3ef5e78d3e0f | [
"MIT"
] | null | null | null | #include "lugre_prefix.h"
#include "lugre_thread.h"
#include "lugre_fifo.h"
#include "lugre_luabind.h"
#include "lugre_luabind_direct.h"
#include "lugre_scripting.h"
#ifdef ENABLE_THREADS
#include <boost/thread/xtime.hpp>
#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>
#endif
namespace Lugre {
class cThread_NetRequest_L : public cLuaBind<cThread_NetRequest> { public:
// implementation of cLuaBind
/// called by Register(), registers object-methods (see cLuaBind constructor for examples)
virtual void RegisterMethods (lua_State *L) { PROFILE
#define REGISTER_METHOD(methodname) mlMethod.push_back(make_luaL_reg(#methodname,&cThread_NetRequest_L::methodname));
REGISTER_METHOD(Destroy);
REGISTER_METHOD(IsFinished);
REGISTER_METHOD(HasError);
#undef REGISTER_METHOD
lua_register(L,"CreateThread_NetRequest", &cThread_NetRequest_L::CreateThread_NetRequest);
}
// static methods exported to lua
/// pSendData is used by the thread, DO NOT USE OR RELEASE IT UNTIL THE THREAD IS FINISHED
/// pAnswerBuffer is used by the thread, DO NOT USE OR RELEASE IT UNTIL THE THREAD IS FINISHED
/// thread_netr CreateThread_NetRequest (sHost,iPort,fifo_SendData=nil,fifo_pAnswerBuffer=nil)
static int CreateThread_NetRequest (lua_State *L) { PROFILE
std::string sHost = luaL_checkstring(L,1);
int iPort = luaL_checkint(L,2);
cFIFO* pSendData = (lua_gettop(L) >= 3 && !lua_isnil(L,3)) ? cLuaBind<cFIFO>::checkudata(L,3) : 0;
cFIFO* pAnswerBuffer = (lua_gettop(L) >= 4 && !lua_isnil(L,4)) ? cLuaBind<cFIFO>::checkudata(L,4) : 0;
return CreateUData(L,new cThread_NetRequest(sHost,iPort,pSendData,pAnswerBuffer));
}
// object methods exported to lua
/// Destroy()
static int Destroy (lua_State *L) { PROFILE
delete checkudata_alive(L);
return 0;
}
/// bool IsFinished ()
static int IsFinished (lua_State *L) { PROFILE
lua_pushboolean(L,checkudata_alive(L)->IsFinished());
return 1;
}
/// bool HasError ()
static int HasError (lua_State *L) { PROFILE
lua_pushboolean(L,checkudata_alive(L)->HasError());
return 1;
}
virtual const char* GetLuaTypeName () { return "lugre.thread_netrequest"; }
};
class cThread_LoadFile_L : public cLuaBind<cThread_LoadFile> { public:
// implementation of cLuaBind
/// called by Register(), registers object-methods (see cLuaBind constructor for examples)
virtual void RegisterMethods (lua_State *L) { PROFILE
#define REGISTER_METHOD(methodname) mlMethod.push_back(make_luaL_reg(#methodname,&cThread_LoadFile_L::methodname));
REGISTER_METHOD(Destroy);
REGISTER_METHOD(IsFinished);
REGISTER_METHOD(HasError);
#undef REGISTER_METHOD
lua_register(L,"CreateThread_LoadFile", &cThread_LoadFile_L::CreateThread_LoadFile);
}
// static methods exported to lua
/// pAnswerBuffer is used by the thread, DO NOT USE OR RELEASE IT UNTIL THE THREAD IS FINISHED
/// thread_loadf CreateThread_LoadFile (sFilePath,fifo_answerbuffer,iStart=0,iLength=-1)
static int CreateThread_LoadFile (lua_State *L) { PROFILE
std::string sFilePath = luaL_checkstring(L,1);
cFIFO* pAnswerBuffer = cLuaBind<cFIFO>::checkudata_alive(L,2);
int iStart = (lua_gettop(L) >= 3 && !lua_isnil(L,3)) ? luaL_checkint(L,3) : 0;
int iLength = (lua_gettop(L) >= 4 && !lua_isnil(L,4)) ? luaL_checkint(L,4) : -1;
return CreateUData(L,new cThread_LoadFile(sFilePath,pAnswerBuffer,iStart,iLength));
}
// object methods exported to lua
/// Destroy()
static int Destroy (lua_State *L) { PROFILE
delete checkudata_alive(L);
return 0;
}
/// bool IsFinished ()
static int IsFinished (lua_State *L) { PROFILE
lua_pushboolean(L,checkudata_alive(L)->IsFinished());
return 1;
}
/// bool HasError ()
static int HasError (lua_State *L) { PROFILE
lua_pushboolean(L,checkudata_alive(L)->HasError());
return 1;
}
virtual const char* GetLuaTypeName () { return "lugre.thread_loadfile"; }
};
// result : 0:not supported, 1:success 2:interrupted
int MyThreadSleepMilliSeconds (int iSleepTimeMilliSeconds) {
#ifdef ENABLE_THREADS
/*
ancient boost version : 103401
boost::xtime xt;
boost::xtime_get(&xt, boost::TIME_UTC);
int big = 1000*1000*1000;
xt.sec += (iSleepTimeMilliSeconds / 1000);
while (xt.nsec > big) { xt.nsec -= big; xt.sec += 1; }
xt.nsec += (iSleepTimeMilliSeconds % 1000)*1000*1000;
while (xt.nsec > big) { xt.nsec -= big; xt.sec += 1; }
boost::thread::sleep(xt);
*/
//~ #else
//~ #define BOOST_VERSION 103401 -- ghoul : old : linux
//~ #define BOOST_VERSION 103700 -- ghoul : new
//~ #define BOOST_VERSION 103800 -- hagish:win
// #define BOOST_LIB_VERSION "1_34_1"
try {
// boost::this_thread::sleep(system_time const& abs_time);
// boost::this_thread::sleep(TimeDuration const& rel_time);
boost::this_thread::sleep(boost::posix_time::milliseconds(iSleepTimeMilliSeconds));
} catch (...) {
return 2;
}
return 1;
#else
return 0;
#endif
}
#ifdef ENABLE_THREADS
class cLugreLuaBind_Mutex : public cLuaBindDirect<boost::mutex> { public:
virtual void RegisterMethods (lua_State *L) { PROFILE
LUABIND_QUICKWRAP_STATIC(CreateMutex, { return CreateUData(L,new boost::mutex()); });
LUABIND_QUICKWRAP(GetCrossThreadHandle, { return PushPointer(L,checkudata_alive(L)); }); // void* so we can pass it across threads
LUABIND_QUICKWRAP_STATIC(CreateMutexFromCrossThreadHandle, { return CreateUData(L,(boost::mutex*)lua_touserdata(L,1)); }); // rewrap/recover from void*
LUABIND_QUICKWRAP(Destroy, { delete &GetSelf(L); });
LUABIND_QUICKWRAP(LockMutex, { GetSelf(L).lock(); });
LUABIND_QUICKWRAP(UnLockMutex, { GetSelf(L).unlock(); });
}
virtual const char* GetLuaTypeName () { return "lugre.mutex"; }
};
class cLuaThread : public cSmartPointable { public:
cFIFO mFIFOParent2Child;
cFIFO mFIFOChild2Parent;
boost::mutex mMutex;
boost::thread* mThread;
std::string msFilePath;
cLuaThread (std::string sFilePath);
virtual ~cLuaThread () { if (mThread) { delete mThread; mThread = 0; } }
cFIFO& GetParent2ChildFIFO () { return mFIFOParent2Child; }
cFIFO& GetChild2ParentFIFO () { return mFIFOChild2Parent; }
void LockMutex () { mMutex.lock(); }
void UnLockMutex () { mMutex.unlock(); }
void Interrupt () { if (mThread) mThread->interrupt(); }
void WaitForDataFromParent () {
uint32 len = 0;
while(true){
mMutex.lock();
len = mFIFOParent2Child.GetLength();
mMutex.unlock();
if(len > 0){
break;
} else {
MyThreadSleepMilliSeconds(1000 / 50);
}
}
}
};
class cLuaThread_Callable { public: // must be copyable
cLuaThread* mSelfThreadHandle;
std::string msFilePath;
cLuaThread_Callable (cLuaThread* mSelfThreadHandle,std::string msFilePath) : mSelfThreadHandle(mSelfThreadHandle),msFilePath(msFilePath) {}
static int DontUseWarning_Client_Sleep (lua_State *L) { printf("DontUseWarning_Client_Sleep\n"); return 0; }
// bool Thread_Sleep (iSleepTimeMilliSeconds) // returns true if it was interrupted
static int Thread_Sleep (lua_State *L) {
int iSleepTimeMilliSeconds = luaL_checkint(L,1);
if (MyThreadSleepMilliSeconds(iSleepTimeMilliSeconds) == 2) { lua_pushboolean(L,true); return 1; }
return 0;
}
void operator()() { PROFILE // TODO : PROFILE shouldnt be used in threads!!! racecondition (needs to be fixed by threadid compare in profile implementation)
//~ msFilePath
// boost::thread::sleep()
lua_State* L = lua_open();
if (!L) { printf("cLuaThread_Callable: failed to init lua state\n"); return; }
cScripting::GetSingletonPtr()->InitLugreLuaEnvironment(L);
lua_register(L,"Client_Sleep", &cLuaThread_Callable::DontUseWarning_Client_Sleep);
lua_register(L,"Thread_Sleep", &cLuaThread_Callable::Thread_Sleep);
cLuaBind<cLuaThread>::CreateUData(L, mSelfThreadHandle);
lua_setglobal(L,"this_thread");
cLuaBind<cFIFO>::CreateUData(L, &(mSelfThreadHandle->mFIFOChild2Parent));
lua_setglobal(L,"this_fifo_send");
cLuaBind<cFIFO>::CreateUData(L, &(mSelfThreadHandle->mFIFOParent2Child));
lua_setglobal(L,"this_fifo_recv");
int res = luaL_dofile(L,msFilePath.c_str());
if (res) {
fprintf(stderr,"%s\n",lua_tostring(L,-1));
MyCrash("error during cLuaThread_Callable run\n");
exit(-1);
}
}
};
cLuaThread::cLuaThread (std::string sFilePath) : mThread(0),msFilePath(sFilePath) {
cLuaThread_Callable myImpl(this,sFilePath);
mThread = new boost::thread(myImpl); // warning ! this COPIES the impl object
}
class cLuaThread_L : public cLuaBind<cLuaThread> { public:
// implementation of cLuaBind
/// called by Register(), registers object-methods (see cLuaBind constructor for examples)
virtual void RegisterMethods (lua_State *L) { PROFILE
#define REGISTER_METHOD(methodname) mlMethod.push_back(make_luaL_reg(#methodname,&cLuaThread_L::methodname));
REGISTER_METHOD(Destroy);
REGISTER_METHOD(CreateFifoParent2ChildHandle);
REGISTER_METHOD(CreateFifoChild2ParentHandle);
REGISTER_METHOD(LockMutex);
REGISTER_METHOD(UnLockMutex);
REGISTER_METHOD(Interrupt);
REGISTER_METHOD(WaitForDataFromParent);
#undef REGISTER_METHOD
lua_register(L,"CreateLuaThread", &cLuaThread_L::CreateLuaThread);
lua_register(L,"Threads_GetHardwareConcurrency", &cLuaThread_L::Threads_GetHardwareConcurrency);
}
// static methods exported to lua
/// luathread CreateLuaThread (sFilePath)
static int CreateLuaThread (lua_State *L) { PROFILE
std::string sFilePath = luaL_checkstring(L,1);
return CreateUData(L,new cLuaThread(sFilePath));
}
/// int Threads_GetHardwareConcurrency ()
// The number of hardware threads available on the current system (e.g. number of CPUs or cores or hyperthreading units), or 0 if this information is not available.
static int Threads_GetHardwareConcurrency (lua_State *L) { PROFILE
lua_pushnumber(L,boost::thread::hardware_concurrency()); //~ unsigned boost::thread::hardware_concurrency();
return 1;
}
// object methods exported to lua
// use LockMutex -- UnLockMutex around access to this fifo !
/// for lua : fifo CreateFifoParent2ChildHandle ()
static int CreateFifoParent2ChildHandle (lua_State *L) { PROFILE
cFIFO& pFIFO = checkudata_alive(L)->GetParent2ChildFIFO();
return cLuaBind<cFIFO>::CreateUData(L,&pFIFO);
}
// use LockMutex -- UnLockMutex around access to this fifo !
/// for lua : fifo CreateFifoChild2ParentHandle ()
static int CreateFifoChild2ParentHandle (lua_State *L) { PROFILE
cFIFO& pFIFO = checkudata_alive(L)->GetChild2ParentFIFO();
return cLuaBind<cFIFO>::CreateUData(L,&pFIFO);
}
/// for lua : void LockMutex ()
static int LockMutex (lua_State *L) { PROFILE checkudata_alive(L)->LockMutex(); return 0; }
/// for lua : void UnLockMutex ()
static int UnLockMutex (lua_State *L) { PROFILE checkudata_alive(L)->UnLockMutex(); return 0; }
/// for lua : void Interrupt ()
static int Interrupt (lua_State *L) { PROFILE checkudata_alive(L)->Interrupt(); return 0; }
/// for lua : void WaitForDataFromParent ()
static int WaitForDataFromParent (lua_State *L) { PROFILE checkudata_alive(L)->WaitForDataFromParent(); return 0; }
/// Destroy()
static int Destroy (lua_State *L) { PROFILE
delete checkudata_alive(L);
return 0;
}
virtual const char* GetLuaTypeName () { return "lugre.luathread"; }
};
#endif
/// lua binding
void cThread_NetRequest::LuaRegister (lua_State *L) { PROFILE
cLuaBind<cThread_NetRequest>::GetSingletonPtr(new cThread_NetRequest_L())->LuaRegister(L);
}
void cThread_LoadFile::LuaRegister (lua_State *L) { PROFILE
cLuaBind<cThread_LoadFile>::GetSingletonPtr(new cThread_LoadFile_L())->LuaRegister(L);
}
void LuaRegisterThreading (lua_State* L) {
cThread_NetRequest::LuaRegister(L);
cThread_LoadFile::LuaRegister(L);
#ifdef ENABLE_THREADS
cLuaBindDirect<boost::mutex >::GetSingletonPtr(new cLugreLuaBind_Mutex( ))->LuaRegister(L);
cLuaBind<cLuaThread>::GetSingletonPtr(new cLuaThread_L())->LuaRegister(L);
#endif
}
};
| 33.722992 | 167 | 0.718581 | [
"object"
] |
798183c97711f2b8cb8f12f05ceef728ae16c1d7 | 7,994 | cpp | C++ | lib/RenderCore_Custom/src/environment/geometry.cpp | laurenskz/lighthouse2 | b733ddd927137b6d9288f6865104760f330846c2 | [
"Apache-2.0"
] | null | null | null | lib/RenderCore_Custom/src/environment/geometry.cpp | laurenskz/lighthouse2 | b733ddd927137b6d9288f6865104760f330846c2 | [
"Apache-2.0"
] | 1 | 2020-11-11T15:29:28.000Z | 2020-11-11T15:29:28.000Z | lib/RenderCore_Custom/src/environment/geometry.cpp | laurenskz/lighthouse2 | b733ddd927137b6d9288f6865104760f330846c2 | [
"Apache-2.0"
] | null | null | null | #include "environment/geometry.h"
namespace lh2core
{
Mesh::Mesh( int vertexCount )
{
positions = new float4[vertexCount];
triangleCount = vertexCount / 3;
triangles = new CoreTri[triangleCount];
primitives = new Primitive[triangleCount];
this->vertexCount = vertexCount;
}
void Mesh::setPositions( const float4* positions, const CoreTri* fatData, const CoreMaterial* materials, int meshIndex )
{
for ( int i = 0; i < vertexCount; ++i )
{
this->positions[i] = positions[i];
}
memcpy( triangles, fatData, triangleCount * sizeof( CoreTri ) );
for ( int i = 0; i < triangleCount; ++i )
{
auto matId = triangles[i].material;
int transparentModifier = materials[matId].pbrtMaterialType == MaterialType::PBRT_GLASS ? 1 : 0;
int lightModifier = materials[matId].pbrtMaterialType == MaterialType::PBRT_UBER ? 1 : 0; //Abusing this type
primitives[i] = Primitive{ TRIANGLE_BIT | ( TRANSPARENT_BIT * transparentModifier ) | ( LIGHT_BIT * lightModifier ),
make_float3( positions[i * 3] ),
make_float3( positions[i * 3 + 1] ),
make_float3( positions[i * 3 + 2] ),
meshIndex,
i, -1 };
}
}
void Geometry::setGeometry( const int meshIdx, const float4* vertexData, const int vertexCount, const int triangleCount, const CoreTri* triangles )
{
Mesh* mesh;
if ( meshIdx >= meshes.size() )
meshes.push_back( mesh = new Mesh( vertexCount ) );
else
mesh = meshes[meshIdx];
mesh->setPositions( vertexData, triangles, materials, meshIdx );
}
void Geometry::setInstance( const int instanceIdx, const int meshIdx, const mat4& transform )
{
if ( meshIdx < 0 ) return;
if ( instanceIdx >= instances.size() )
{
instances.push_back( Instance{ meshIdx, transform } );
transforms.push_back( transform );
}
else
{
transforms[instanceIdx] = transform;
instances[instanceIdx].meshIndex = meshIdx;
instances[instanceIdx].transform = transform;
isDirty = true;
}
}
Primitives Geometry::getPrimitives()
{
if ( isDirty )
{
finalizeInstances();
}
return Primitives{ primitives, count };
}
void Geometry::finalizeInstances()
{
count = computePrimitiveCount();
primitives = new Primitive[count];
int primitiveIndex = 0;
primitiveIndex = addPrimitives( primitiveIndex, spheres );
primitiveIndex = addPrimitives( primitiveIndex, planes );
primitiveIndex = addLights( primitiveIndex );
primitiveIndex = addTriangles( primitiveIndex );
isDirty = false;
}
int Geometry::addLights( int primitiveIndex )
{
for ( int i = 0; i < lightCount; ++i )
{
primitives[primitiveIndex++] = Primitive{ TRIANGLE_BIT | LIGHT_BIT,
lights[i].vertex0,
lights[i].vertex1,
lights[i].vertex2,
i, -1, -1 };
}
return primitiveIndex;
}
int Geometry::addTriangles( int primitiveIndex )
{
for ( int instanceIndex = 0; instanceIndex < instances.size(); ++instanceIndex )
{
auto instance = instances[instanceIndex];
Mesh*& mesh = meshes[instance.meshIndex];
for ( int i = 0; i < mesh->triangleCount; ++i )
{
Primitive primitive = computePrimitive( instanceIndex, instance, mesh, i );
primitives[primitiveIndex++] = primitive;
}
}
return primitiveIndex;
}
Primitive Geometry::computePrimitive( int instanceIndex, const Instance& instance, Mesh* const& mesh, int i )
{
auto matId = meshes[instance.meshIndex]->triangles[i].material;
int transparentModifier = materials[matId].pbrtMaterialType == MaterialType::PBRT_GLASS ? 1 : 0;
const Primitive& primitive = Primitive{ TRIANGLE_BIT | ( TRANSPARENT_BIT * transparentModifier ),
make_float3( instance.transform * mesh->positions[i * 3] ),
make_float3( instance.transform * mesh->positions[i * 3 + 1] ),
make_float3( instance.transform * mesh->positions[i * 3 + 2] ),
instance.meshIndex,
i, instanceIndex };
return primitive;
}
void Geometry::addPlane( float3 normal, float d )
{
planes.push_back( Primitive{
PLANE_BIT, normal, make_float3( d, 0, 0 ), make_float3( 0 ), -1, -1, -1 } );
}
void Geometry::addSphere( float3 pos, float r, Material mat )
{
int transparentModifier = mat.type == GLASS ? 1 : 0;
spheres.push_back( Primitive{
SPHERE_BIT | ( TRANSPARENT_BIT * transparentModifier ), pos, make_float3( r * r, r, 0 ),
make_float3( 0 ),
static_cast<int>( sphereMaterials.size() ),
-1, -1 } );
sphereMaterials.push_back( mat );
}
uint Geometry::addPrimitives( int startIndex, const std::vector<Primitive>& toAdd )
{
for ( auto primitive : toAdd )
{
primitives[startIndex++] = primitive;
}
return startIndex;
}
uint Geometry::computePrimitiveCount()
{
int triangleCount = 0;
for ( auto instance : instances )
{
triangleCount += meshes[instance.meshIndex]->triangleCount;
}
return planes.size() + spheres.size() + triangleCount + lightCount;
}
Intersection Geometry::triangleIntersection( const Ray& r )
{
Intersection intersection{};
intersection.location = intersectionLocation( r );
intersection.mat.type = DIFFUSE;
const float w = ( 1 - r.u - r.v );
if ( r.primitive->flags & LIGHT_BIT )
{
intersection.mat = lightMaterials[r.primitive->meshIndex];
// intersection.mat.type = LIGHT;
}
const CoreTri& triangleData = meshes[r.primitive->meshIndex]->triangles[r.primitive->triangleNumber];
float2 uv = make_float2( w * triangleData.u0 + r.u * triangleData.u1 + r.v * triangleData.u2,
w * triangleData.v0 + r.u * triangleData.v1 + r.v * triangleData.v2 );
auto normal = w * triangleData.vN0 + r.u * triangleData.vN1 + r.v * triangleData.vN2;
intersection.normal = normalize( make_float3( transforms[r.instanceIndex] * ( make_float4( normal ) ) ) );
auto mat = materials[triangleData.material];
if ( mat.pbrtMaterialType == lighthouse2::MaterialType::PBRT_GLASS )
{
intersection.mat.type = GLASS;
intersection.mat.refractionIndex = mat.refraction.value;
}
if ( mat.color.textureID != -1 )
{
auto texture = textures[mat.color.textureID];
uv *= mat.color.uvscale;
uv += mat.color.uvoffset;
int x = round( uv.x * texture.width );
int y = round( uv.y * texture.height );
const uchar4& iColor = texture.idata[x + y * texture.width];
intersection.mat.color = make_float3( (float)iColor.x / 256, (float)iColor.y / 256, (float)iColor.z / 256 );
}
else
{
intersection.mat.color = mat.color.value;
}
if ( mat.specular.value > ( 1e-4 ) )
{
intersection.mat.type = SPECULAR;
intersection.mat.specularity = mat.specular.value;
}
if ( mat.pbrtMaterialType == lighthouse2::MaterialType::CUSTOM_BSDF )
{
intersection.mat.type = MICROFACET;
intersection.mat.microAlpha = mat.clearcoatGloss.value;
intersection.mat.kspec = mat.Ks.value;
}
return intersection;
}
void Geometry::SetTextures( const CoreTexDesc* tex, const int textureCount )
{
textures = new CoreTexDesc[textureCount];
memcpy( textures, tex, sizeof( CoreTexDesc ) * textureCount );
}
void Geometry::SetMaterials( CoreMaterial* mat, const int materialCount )
{
materials = new CoreMaterial[materialCount];
memcpy( materials, mat, sizeof( CoreMaterial ) * materialCount );
}
void Geometry::SetLights( const CoreLightTri* newLights, const int newLightCount )
{
isDirty = true;
this->lightCount = newLightCount;
if ( newLightCount == 0 ) return;
lightMaterials.resize( newLightCount );
this->lights = new CoreLightTri[newLightCount];
memcpy( (void*)this->lights, newLights, newLightCount * sizeof( CoreLightTri ) );
for ( int i = 0; i < newLightCount; ++i )
{
lightMaterials[i] = Material{ newLights[i].radiance, 0, LIGHT };
}
}
Intersection Geometry::intersectionInformation( const Ray& ray )
{
if ( isTriangle( *ray.primitive ) )
{
return triangleIntersection( ray );
}
if ( isSphere( *ray.primitive ) )
{
return sphereIntersection( ray, sphereMaterials[ray.primitive->meshIndex] );
}
if ( isPlane( *ray.primitive ) )
{
return planeIntersection( ray, Material{} );
}
return Intersection{};
}
const Mesh* Geometry::getMesh( int meshIdx )
{
return meshes[meshIdx];
}
} // namespace lh2core | 33.033058 | 147 | 0.698274 | [
"mesh",
"geometry",
"vector",
"transform"
] |
7986b7ab900aa4ba73c396c647101bca92301543 | 22,245 | cpp | C++ | asteroids_d3d12/src/asteroids_d3d11.cpp | gaybro8777/HybridDetect | 0ee85e7ea17d29a71b5171ec152007c449c7f08a | [
"MIT"
] | 131 | 2015-09-18T00:44:07.000Z | 2022-03-10T02:58:28.000Z | asteroids_d3d12/src/asteroids_d3d11.cpp | gaybro8777/HybridDetect | 0ee85e7ea17d29a71b5171ec152007c449c7f08a | [
"MIT"
] | 4 | 2016-03-11T18:30:01.000Z | 2021-04-16T18:08:02.000Z | asteroids_d3d12/src/asteroids_d3d11.cpp | gaybro8777/HybridDetect | 0ee85e7ea17d29a71b5171ec152007c449c7f08a | [
"MIT"
] | 32 | 2015-09-18T01:28:00.000Z | 2022-01-21T00:46:29.000Z | ///////////////////////////////////////////////////////////////////////////////
// Copyright 2017 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy
// of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
///////////////////////////////////////////////////////////////////////////////
#include <d3dcompiler.h>
#include <directxmath.h>
#include <math.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <future>
#include <limits>
#include <random>
#include <locale>
#include <codecvt>
#include "asteroids_d3d11.h"
#include "util.h"
#include "mesh.h"
#include "noise.h"
#include "texture.h"
#include "DDSTextureLoader.h"
#include "profile.h"
#include "asteroid_vs.h"
#include "asteroid_ps_d3d11.h"
#include "skybox_vs.h"
#include "skybox_ps.h"
#include "sprite_vs.h"
#include "sprite_ps.h"
#include "font_ps.h"
using namespace DirectX;
namespace AsteroidsD3D11 {
Asteroids::Asteroids(AsteroidsSimulation* asteroids, GUI* gui, bool warp)
: mAsteroids(asteroids)
, mGUI(gui)
, mSwapChain(nullptr)
, mDevice(nullptr)
, mDeviceCtxt(nullptr)
, mRenderTarget(nullptr)
, mRenderTargetView(nullptr)
, mDepthStencilView(nullptr)
, mDepthStencilState(nullptr)
, mInputLayout(nullptr)
, mIndexBuffer(nullptr)
, mVertexBuffer(nullptr)
, mVertexShader(nullptr)
, mPixelShader(nullptr)
, mDrawConstantBuffer(nullptr)
, mSkyboxVertexShader(nullptr)
, mSkyboxPixelShader(nullptr)
, mSkyboxConstantBuffer(nullptr)
, mSamplerState(nullptr)
{
memset(&mViewPort, 0, sizeof(mViewPort));
memset(&mScissorRect, 0, sizeof(mScissorRect));
memset(mTextures, 0, sizeof(mTextures));
memset(mTextureSRVs, 0, sizeof(mTextureSRVs));
// Create device and swap chain
{
IDXGIAdapter* adapter = nullptr;
D3D_DRIVER_TYPE driverType = ( warp ) ? D3D_DRIVER_TYPE_WARP : D3D_DRIVER_TYPE_HARDWARE;
HMODULE swModule = NULL;
UINT flags = 0;
D3D_FEATURE_LEVEL featureLevels[] = { D3D_FEATURE_LEVEL_11_0 };
UINT numFeatureLevels = ARRAYSIZE(featureLevels);
UINT sdkVersion = D3D11_SDK_VERSION;
#ifdef _DEBUG
flags = flags | D3D11_CREATE_DEVICE_DEBUG;
#endif
auto hr = D3D11CreateDevice(adapter, driverType, swModule,
flags, featureLevels, numFeatureLevels, sdkVersion, &mDevice, nullptr, &mDeviceCtxt);
if (FAILED(hr)) {
// Try again without the debug flag...
flags = flags & ~D3D11_CREATE_DEVICE_DEBUG;
ThrowIfFailed(D3D11CreateDevice(adapter, driverType, swModule,
flags, featureLevels, numFeatureLevels, sdkVersion, &mDevice, nullptr, &mDeviceCtxt));
}
}
// create pipeline state
{
D3D11_INPUT_ELEMENT_DESC inputDesc[] = {
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
};
ThrowIfFailed(mDevice->CreateInputLayout(inputDesc, ARRAYSIZE(inputDesc),
g_asteroid_vs, sizeof(g_asteroid_vs), &mInputLayout));
{
D3D11_DEPTH_STENCIL_DESC desc = CD3D11_DEPTH_STENCIL_DESC(D3D11_DEFAULT);
desc.DepthFunc = D3D11_COMPARISON_GREATER_EQUAL;
ThrowIfFailed(mDevice->CreateDepthStencilState(&desc, &mDepthStencilState));
}
{
CD3D11_BLEND_DESC desc = CD3D11_BLEND_DESC(CD3D11_DEFAULT());
ThrowIfFailed(mDevice->CreateBlendState(&desc, &mBlendState));
// Premultiplied over blend
desc.RenderTarget[0].BlendEnable = TRUE;
desc.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE;
desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
desc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
ThrowIfFailed(mDevice->CreateBlendState(&desc, &mSpriteBlendState));
}
ThrowIfFailed(mDevice->CreateVertexShader(g_asteroid_vs, sizeof(g_asteroid_vs), NULL, &mVertexShader));
ThrowIfFailed(mDevice->CreatePixelShader(g_asteroid_ps_d3d11, sizeof(g_asteroid_ps_d3d11), NULL, &mPixelShader));
}
// create skybox pipeline state
{
D3D11_INPUT_ELEMENT_DESC inputDesc[] = {
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "UVFACE", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
};
ThrowIfFailed(mDevice->CreateInputLayout(inputDesc, ARRAYSIZE(inputDesc),
g_skybox_vs, sizeof(g_skybox_vs), &mSkyboxInputLayout));
ThrowIfFailed(mDevice->CreateVertexShader(g_skybox_vs, sizeof(g_skybox_vs), NULL, &mSkyboxVertexShader));
ThrowIfFailed(mDevice->CreatePixelShader(g_skybox_ps, sizeof(g_skybox_ps), NULL, &mSkyboxPixelShader));
}
// Sprites and fonts
{
D3D11_INPUT_ELEMENT_DESC inputDesc[] = {
{ "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "UV", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 8, D3D11_INPUT_PER_VERTEX_DATA, 0 },
};
ThrowIfFailed(mDevice->CreateInputLayout(inputDesc, ARRAYSIZE(inputDesc),
g_sprite_vs, sizeof(g_sprite_vs), &mSpriteInputLayout));
ThrowIfFailed(mDevice->CreateVertexShader(g_sprite_vs, sizeof(g_sprite_vs), NULL, &mSpriteVertexShader));
ThrowIfFailed(mDevice->CreatePixelShader(g_sprite_ps, sizeof(g_sprite_ps), NULL, &mSpritePixelShader));
ThrowIfFailed(mDevice->CreatePixelShader(g_font_ps, sizeof(g_font_ps), NULL, &mFontPixelShader));
}
// Create draw constant buffer
{
D3D11_BUFFER_DESC desc = {};
desc.Usage = D3D11_USAGE_DYNAMIC;
desc.ByteWidth = sizeof(DrawConstantBuffer);
desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
ThrowIfFailed(mDevice->CreateBuffer(&desc, nullptr, &mDrawConstantBuffer));
}
// Create skybox constant buffer
{
D3D11_BUFFER_DESC desc = {};
desc.Usage = D3D11_USAGE_DYNAMIC;
desc.ByteWidth = sizeof(SkyboxConstantBuffer);
desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
ThrowIfFailed(mDevice->CreateBuffer(&desc, nullptr, &mSkyboxConstantBuffer));
}
// Create sampler
{
D3D11_SAMPLER_DESC desc = {};
desc.Filter = D3D11_FILTER_ANISOTROPIC;
desc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
desc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
desc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
desc.MinLOD = -D3D11_FLOAT32_MAX;
desc.MaxLOD = D3D11_FLOAT32_MAX;
desc.MipLODBias = 0.0f;
desc.MaxAnisotropy = TEXTURE_ANISO;
desc.ComparisonFunc = D3D11_COMPARISON_NEVER;
ThrowIfFailed(mDevice->CreateSamplerState(&desc, &mSamplerState));
}
CreateMeshes();
InitializeTextureData();
CreateGUIResources();
// Load textures
ThrowIfFailed(CreateDDSTextureFromFile(mDevice, L"starbox_1024.dds", &mSkyboxSRV, true));
}
Asteroids::~Asteroids()
{
ReleaseSwapChain();
SafeRelease(&mDepthStencilState);
SafeRelease(&mInputLayout);
SafeRelease(&mIndexBuffer);
SafeRelease(&mVertexBuffer);
SafeRelease(&mVertexShader);
SafeRelease(&mPixelShader);
SafeRelease(&mDrawConstantBuffer);
SafeRelease(&mSamplerState);
SafeRelease(&mBlendState);
SafeRelease(&mSpriteBlendState);
for (auto i : mSpriteTextures) {
i.second->Release();
}
SafeRelease(&mSpriteInputLayout);
SafeRelease(&mSpriteVertexShader);
SafeRelease(&mSpritePixelShader);
SafeRelease(&mSpriteVertexBuffer);
SafeRelease(&mFontPixelShader);
SafeRelease(&mFontTextureSRV);
SafeRelease(&mSkyboxVertexShader);
SafeRelease(&mSkyboxPixelShader);
SafeRelease(&mSkyboxConstantBuffer);
SafeRelease(&mSkyboxVertexBuffer);
SafeRelease(&mSkyboxInputLayout);
SafeRelease(&mSkyboxSRV);
for (auto& texture : mTextures) SafeRelease(&texture);
for (auto& srv : mTextureSRVs) SafeRelease(&srv);
if (mSwapChain != nullptr) {
mSwapChain->Release();
mSwapChain = nullptr;
}
SafeRelease(&mDeviceCtxt);
SafeRelease(&mDevice);
}
void Asteroids::ReleaseSwapChain()
{
// Cleanup any references...
SafeRelease(&mRenderTarget);
SafeRelease(&mRenderTargetView);
SafeRelease(&mDepthStencilView);
SafeRelease(&mSwapChain);
mDeviceCtxt->ClearState();
mDeviceCtxt->Flush();
}
inline void DisableDXGIWindowChanges(IUnknown* device, HWND window)
{
IDXGIDevice * pDXGIDevice;
ThrowIfFailed(device->QueryInterface(IID_PPV_ARGS(&pDXGIDevice)));
IDXGIAdapter * pDXGIAdapter;
ThrowIfFailed(pDXGIDevice->GetParent(IID_PPV_ARGS(&pDXGIAdapter)));
IDXGIFactory * pIDXGIFactory;
ThrowIfFailed(pDXGIAdapter->GetParent(IID_PPV_ARGS(&pIDXGIFactory)));
ThrowIfFailed(pIDXGIFactory->MakeWindowAssociation(window, DXGI_MWA_NO_WINDOW_CHANGES | DXGI_MWA_NO_ALT_ENTER));
pIDXGIFactory->Release();
pDXGIAdapter->Release();
pDXGIDevice->Release();
}
void Asteroids::ResizeSwapChain(IDXGIFactory2* dxgiFactory, HWND outputWindow, unsigned int width, unsigned int height)
{
ReleaseSwapChain();
// Create swap chain
{
DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {};
swapChainDesc.Width = width;
swapChainDesc.Height = height;
swapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; // Can create an SRGB render target view on the swap chain buffer
swapChainDesc.Stereo = FALSE;
swapChainDesc.SampleDesc.Count = 1;
swapChainDesc.SampleDesc.Quality = 0;
swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
swapChainDesc.BufferCount = NUM_SWAP_CHAIN_BUFFERS;
swapChainDesc.Scaling = DXGI_SCALING_STRETCH;
swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL;
swapChainDesc.AlphaMode = DXGI_ALPHA_MODE_UNSPECIFIED; // Not used
swapChainDesc.Flags = 0;
ThrowIfFailed(dxgiFactory->CreateSwapChainForHwnd(
mDevice, outputWindow, &swapChainDesc, nullptr, nullptr, &mSwapChain));
// MakeWindowAssociation must be called after CreateSwapChain
DisableDXGIWindowChanges(mDevice, outputWindow);
}
// create render target view
{
ThrowIfFailed(mSwapChain->GetBuffer(0, IID_PPV_ARGS(&mRenderTarget)));
D3D11_RENDER_TARGET_VIEW_DESC desc = {};
desc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
desc.Format = DXGI_FORMAT_B8G8R8A8_UNORM_SRGB;
desc.Texture2D.MipSlice = 0;
ThrowIfFailed(mDevice->CreateRenderTargetView(mRenderTarget, &desc, &mRenderTargetView));
}
// create depth stencil view
{
CD3D11_TEXTURE2D_DESC desc = CD3D11_TEXTURE2D_DESC(
DXGI_FORMAT_D32_FLOAT, width, height, 1, 1, D3D11_BIND_DEPTH_STENCIL);
ID3D11Texture2D* depthStencil = nullptr;
ThrowIfFailed(mDevice->CreateTexture2D(&desc, nullptr, &depthStencil));
ThrowIfFailed(mDevice->CreateDepthStencilView(depthStencil, nullptr, &mDepthStencilView));
depthStencil->Release();
}
// update the viewport and scissor
ZeroMemory(&mViewPort, sizeof(D3D11_VIEWPORT));
mViewPort.TopLeftX = 0;
mViewPort.TopLeftY = 0;
mViewPort.Width = (float)width;
mViewPort.Height = (float)height;
mViewPort.MinDepth = 0.0f;
mViewPort.MaxDepth = 1.0f;
mScissorRect.left = 0;
mScissorRect.top = 0;
mScissorRect.right = width;
mScissorRect.bottom = height;
}
void Asteroids::CreateMeshes()
{
auto asteroidMeshes = mAsteroids->Meshes();
// create vertex buffer
{
CD3D11_BUFFER_DESC desc(
(UINT)asteroidMeshes->vertices.size() * sizeof(asteroidMeshes->vertices[0]),
D3D11_BIND_VERTEX_BUFFER,
D3D11_USAGE_DEFAULT);
D3D11_SUBRESOURCE_DATA data = {};
data.pSysMem = asteroidMeshes->vertices.data();
ThrowIfFailed(mDevice->CreateBuffer(&desc, &data, &mVertexBuffer));
}
// create index buffer
{
CD3D11_BUFFER_DESC desc(
(UINT)asteroidMeshes->indices.size() * sizeof(asteroidMeshes->indices[0]),
D3D11_BIND_INDEX_BUFFER,
D3D11_USAGE_DEFAULT);
D3D11_SUBRESOURCE_DATA data = {};
data.pSysMem = asteroidMeshes->indices.data();
ThrowIfFailed(mDevice->CreateBuffer(&desc, &data, &mIndexBuffer));
}
std::vector<SkyboxVertex> skyboxVertices;
CreateSkyboxMesh(&skyboxVertices);
// create skybox vertex buffer
{
CD3D11_BUFFER_DESC desc(
(UINT)skyboxVertices.size() * sizeof(skyboxVertices[0]),
D3D11_BIND_VERTEX_BUFFER,
D3D11_USAGE_DEFAULT);
D3D11_SUBRESOURCE_DATA data = {};
data.pSysMem = skyboxVertices.data();
ThrowIfFailed(mDevice->CreateBuffer(&desc, &data, &mSkyboxVertexBuffer));
}
// create sprite vertex buffer (dynamic)
{
CD3D11_BUFFER_DESC desc(
MAX_SPRITE_VERTICES_PER_FRAME * sizeof(SpriteVertex),
D3D11_BIND_VERTEX_BUFFER,
D3D11_USAGE_DYNAMIC, D3D11_CPU_ACCESS_WRITE);
ThrowIfFailed(mDevice->CreateBuffer(&desc, nullptr, &mSpriteVertexBuffer));
}
}
void Asteroids::InitializeTextureData()
{
D3D11_TEXTURE2D_DESC textureDesc = {};
textureDesc.Width = TEXTURE_DIM;
textureDesc.Height = TEXTURE_DIM;
textureDesc.ArraySize = 3;
textureDesc.MipLevels = 0; // Full chain
textureDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB;
textureDesc.SampleDesc.Count = 1;
textureDesc.Usage = D3D11_USAGE_DEFAULT;
textureDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
for (UINT t = 0; t < NUM_UNIQUE_TEXTURES; ++t) {
ThrowIfFailed(mDevice->CreateTexture2D(&textureDesc, mAsteroids->TextureData(t), &mTextures[t]));
ThrowIfFailed(mDevice->CreateShaderResourceView(mTextures[t], nullptr, &mTextureSRVs[t]));
}
}
void Asteroids::CreateGUIResources()
{
auto font = mGUI->Font();
D3D11_TEXTURE2D_DESC textureDesc = CD3D11_TEXTURE2D_DESC(DXGI_FORMAT_A8_UNORM, font->BitmapWidth(), font->BitmapHeight(), 1, 1);
D3D11_SUBRESOURCE_DATA initialData = {};
initialData.pSysMem = font->Pixels();
initialData.SysMemPitch = font->BitmapWidth();
ID3D11Texture2D* texture = nullptr;
ThrowIfFailed(mDevice->CreateTexture2D(&textureDesc, &initialData, &texture));
ThrowIfFailed(mDevice->CreateShaderResourceView(texture, nullptr, &mFontTextureSRV));
SafeRelease(&texture);
// Load any GUI sprite textures
for (size_t i = 0; i < mGUI->size(); ++i) {
auto control = (*mGUI)[i];
if (control->TextureFile().length() > 0 && mSpriteTextures.find(control->TextureFile()) == mSpriteTextures.end()) {
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
ID3D11ShaderResourceView* textureSRV = nullptr;
ThrowIfFailed(CreateDDSTextureFromFile(mDevice, converter.from_bytes(control->TextureFile()).c_str(), &textureSRV, true));
mSpriteTextures[control->TextureFile()] = textureSRV;
}
}
}
static_assert(sizeof(IndexType) == 2, "Expecting 16-bit index buffer");
void Asteroids::Render(float frameTime, const OrbitCamera& camera, const Settings& settings)
{
ProfileBeginFrame(0);
ProfileBeginRender();
// Frame data
ProfileBeginSimUpdate();
mAsteroids->Update(frameTime, camera.Eye(), settings);
auto staticAsteroidData = mAsteroids->StaticData();
auto dynamicAsteroidData = mAsteroids->DynamicData();
ProfileEndSimUpdate();
// Clear the render target
float clearcol[4] = { 0.0f, 0.0f, 0.0f, 0.0f };
mDeviceCtxt->ClearRenderTargetView(mRenderTargetView, clearcol);
mDeviceCtxt->ClearDepthStencilView(mDepthStencilView, D3D11_CLEAR_DEPTH, 0.0f, 0);
{
ID3D11Buffer* ia_buffers[] = { mVertexBuffer };
UINT ia_strides[] = { sizeof(Vertex) };
UINT ia_offsets[] = { 0 };
mDeviceCtxt->IASetInputLayout(mInputLayout);
mDeviceCtxt->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
mDeviceCtxt->IASetVertexBuffers(0, 1, ia_buffers, ia_strides, ia_offsets);
mDeviceCtxt->IASetIndexBuffer(mIndexBuffer, DXGI_FORMAT_R16_UINT, 0);
}
mDeviceCtxt->VSSetShader(mVertexShader, nullptr, 0);
mDeviceCtxt->VSSetConstantBuffers(0, 1, &mDrawConstantBuffer);
mDeviceCtxt->RSSetViewports(1, &mViewPort);
mDeviceCtxt->RSSetScissorRects(1, &mScissorRect);
mDeviceCtxt->PSSetShader(mPixelShader, nullptr, 0);
mDeviceCtxt->PSSetSamplers(0, 1, &mSamplerState);
mDeviceCtxt->OMSetRenderTargets(1, &mRenderTargetView, mDepthStencilView);
mDeviceCtxt->OMSetDepthStencilState(mDepthStencilState, 0);
mDeviceCtxt->OMSetBlendState(mBlendState, nullptr, 0xFFFFFFFF);
ProfileBeginRenderSubset();
auto viewProjection = camera.ViewProjection();
for (UINT drawIdx = 0; drawIdx < NUM_ASTEROIDS; ++drawIdx)
{
auto staticData = &staticAsteroidData[drawIdx];
auto dynamicData = &dynamicAsteroidData[drawIdx];
D3D11_MAPPED_SUBRESOURCE mapped = {};
ThrowIfFailed(mDeviceCtxt->Map(mDrawConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped));
auto drawConstants = (DrawConstantBuffer*) mapped.pData;
XMStoreFloat4x4(&drawConstants->mWorld, dynamicData->world);
XMStoreFloat4x4(&drawConstants->mViewProjection, viewProjection);
drawConstants->mSurfaceColor = staticData->surfaceColor;
drawConstants->mDeepColor = staticData->deepColor;
mDeviceCtxt->Unmap(mDrawConstantBuffer, 0);
mDeviceCtxt->PSSetShaderResources(0, 1, &mTextureSRVs[staticData->textureIndex]);
mDeviceCtxt->DrawIndexedInstanced(dynamicData->indexCount, 1, dynamicData->indexStart, staticData->vertexStart, 0);
}
ProfileEndRenderSubset();
// Draw skybox
{
D3D11_MAPPED_SUBRESOURCE mapped = {};
ThrowIfFailed(mDeviceCtxt->Map(mSkyboxConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped));
auto skyboxConstants = (SkyboxConstantBuffer*) mapped.pData;
XMStoreFloat4x4(&skyboxConstants->mViewProjection, camera.ViewProjection());
mDeviceCtxt->Unmap(mSkyboxConstantBuffer, 0);
ID3D11Buffer* ia_buffers[] = { mSkyboxVertexBuffer };
UINT ia_strides[] = { sizeof(SkyboxVertex) };
UINT ia_offsets[] = { 0 };
mDeviceCtxt->IASetInputLayout(mSkyboxInputLayout);
mDeviceCtxt->IASetVertexBuffers(0, 1, ia_buffers, ia_strides, ia_offsets);
mDeviceCtxt->VSSetShader(mSkyboxVertexShader, nullptr, 0);
mDeviceCtxt->VSSetConstantBuffers(0, 1, &mSkyboxConstantBuffer);
mDeviceCtxt->PSSetShader(mSkyboxPixelShader, nullptr, 0);
mDeviceCtxt->PSSetSamplers(0, 1, &mSamplerState);
mDeviceCtxt->PSSetShaderResources(0, 1, &mSkyboxSRV);
mDeviceCtxt->Draw(6*6, 0);
}
mDeviceCtxt->OMSetRenderTargets(1, &mRenderTargetView, 0); // No more depth buffer
// Draw sprites and fonts
{
// Fill in vertices (TODO: could move this vector to be a member - not a big deal)
std::vector<UINT> controlVertices;
controlVertices.reserve(mGUI->size());
{
D3D11_MAPPED_SUBRESOURCE mapped = {};
ThrowIfFailed(mDeviceCtxt->Map(mSpriteVertexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped));
auto vertexBase = (SpriteVertex*)mapped.pData;
auto vertexEnd = vertexBase;
for (size_t i = 0; i < mGUI->size(); ++i) {
auto control = (*mGUI)[i];
controlVertices.push_back((UINT)(control->Draw(mViewPort.Width, mViewPort.Height, vertexEnd) - vertexEnd));
vertexEnd += controlVertices.back();
}
mDeviceCtxt->Unmap(mSpriteVertexBuffer, 0);
}
ID3D11Buffer* ia_buffers[] = { mSpriteVertexBuffer };
UINT ia_strides[] = { sizeof(SpriteVertex) };
UINT ia_offsets[] = { 0 };
mDeviceCtxt->IASetInputLayout(mSpriteInputLayout);
mDeviceCtxt->IASetVertexBuffers(0, 1, ia_buffers, ia_strides, ia_offsets);
mDeviceCtxt->VSSetShader(mSpriteVertexShader, 0, 0);
mDeviceCtxt->OMSetBlendState(mSpriteBlendState, nullptr, 0xFFFFFFFF);
// Draw
UINT vertexStart = 0;
for (size_t i = 0; i < mGUI->size(); ++i) {
auto control = (*mGUI)[i];
if (control->Visible()) {
if (control->TextureFile().length() == 0) { // Font
mDeviceCtxt->PSSetShader(mFontPixelShader, 0, 0);
mDeviceCtxt->PSSetShaderResources(0, 1, &mFontTextureSRV);
} else { // Sprite
auto textureSRV = mSpriteTextures[control->TextureFile()];
mDeviceCtxt->PSSetShader(mSpritePixelShader, 0, 0);
mDeviceCtxt->PSSetShaderResources(0, 1, &textureSRV);
}
mDeviceCtxt->Draw(controlVertices[i], vertexStart);
}
vertexStart += controlVertices[i];
}
}
ProfileEndRender();
ProfileBeginPresent();
mSwapChain->Present(settings.vsync ? 1 : 0, 0);
ProfileEndPresent();
ProfileEndFrame();
}
} // namespace AsteroidsD3D11
| 37.576014 | 134 | 0.669724 | [
"mesh",
"render",
"vector"
] |
7988e4db429baf3d5e9eec3917e95fd7208fc8cf | 10,334 | cpp | C++ | modules/app/MyntSimpleRecorder/main.cpp | chengfzy/SensorRecorder | 928d5889f3d6e19767a743a017e0490830fd0740 | [
"MIT"
] | 1 | 2022-02-11T22:44:39.000Z | 2022-02-11T22:44:39.000Z | modules/app/MyntSimpleRecorder/main.cpp | chengfzy/SensorRecorder | 928d5889f3d6e19767a743a017e0490830fd0740 | [
"MIT"
] | null | null | null | modules/app/MyntSimpleRecorder/main.cpp | chengfzy/SensorRecorder | 928d5889f3d6e19767a743a017e0490830fd0740 | [
"MIT"
] | 1 | 2022-02-11T22:44:40.000Z | 2022-02-11T22:44:40.000Z | #include <fmt/color.h>
#include <fmt/format.h>
#include <fmt/ranges.h>
#include <glog/logging.h>
#include <mynteyed/camera.h>
#include <mynteyed/utils.h>
#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include <cxxopts.hpp>
#include <iostream>
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
using namespace std;
using namespace cv;
using namespace mynteyed;
namespace fs = boost::filesystem;
// get the section string
string section(const string& text) {
return fmt::format(fmt::fg(fmt::color::cyan), "{:═^{}}", " " + text + " ",
max(100, static_cast<int>(text.size() + 12)));
}
int main(int argc, char* argv[]) {
// argument parser
cxxopts::Options options(argv[0], "Recorder");
// clang-format off
options.add_options()("f,folder", "save folder", cxxopts::value<string>()->default_value("./data"))
("frameRate", "frame rate", cxxopts::value<int>()->default_value("30"))
("streamMode", "stream mode", cxxopts::value<string>()->default_value("1280x720"))
("streamFormat", "stream format", cxxopts::value<string>()->default_value("MJPG"))
("showImage", "show image", cxxopts::value<bool>())
("h,help", "help message");
// clang-format on
auto result = options.parse(argc, argv);
if (result.count("help")) {
cout << options.help() << endl;
return 0;
}
string rootFolder = result["folder"].as<string>();
int frameRate = result["frameRate"].as<int>();
string streamModeName = result["streamMode"].as<string>();
string streamFormatName = result["streamFormat"].as<string>();
bool showImg = result["showImage"].as<bool>();
// check stream mode
vector<string> streamModeNames = {"2560x720", "1280x720", "1280x480", "640x480"};
if (find_if(streamModeNames.begin(), streamModeNames.end(),
[&](const string& s) { return boost::iequals(s, streamModeName); }) == streamModeNames.end()) {
cout << fmt::format("input stream mode type should be one item in {}", streamModeNames) << endl << endl;
cout << options.help() << endl;
return 0;
}
// check stream format
vector<string> streamFormatNames = {"YUYV", "MJPG"};
if (find_if(streamFormatNames.begin(), streamFormatNames.end(),
[&](const string& s) { return boost::iequals(s, streamFormatName); }) == streamFormatNames.end()) {
cout << fmt::format("input stream format should be one item in {}", streamFormatNames) << endl << endl;
cout << options.help() << endl;
return 0;
}
// print input parameters
cout << section("Recorder") << endl;
cout << fmt::format("save folder: {}", rootFolder) << endl;
cout << fmt::format("frame rate = {} Hz", frameRate) << endl;
cout << fmt::format("stream mode: {}", streamModeName) << endl;
cout << fmt::format("stream format: {}", streamFormatName) << endl;
cout << fmt::format("show image: {}", showImg) << endl;
// init glog
google::InitGoogleLogging(argv[0]);
FLAGS_alsologtostderr = true;
FLAGS_colorlogtostderr = true;
// get stream mode from string
StreamMode streamMode;
if (boost::iequals(streamModeName, "2560x720")) {
streamMode = StreamMode::STREAM_2560x720;
} else if (boost::iequals(streamModeName, "1280x720")) {
streamMode = StreamMode::STREAM_1280x720;
} else if (boost::iequals(streamModeName, "1280x480")) {
streamMode = StreamMode::STREAM_1280x480;
} else if (boost::iequals(streamModeName, "640x480")) {
streamMode = StreamMode::STREAM_640x480;
}
// get stream format from string
StreamFormat streamFormat;
if (boost::iequals(streamFormatName, "YUYV")) {
streamFormat = StreamFormat::STREAM_YUYV;
} else if (boost::iequals(streamFormatName, "MJPG")) {
streamFormat = StreamFormat::STREAM_MJPG;
}
// create directories
fs::path rootPath{rootFolder};
fs::path leftPath = rootPath / "left";
fs::path rightPath = rootPath / "right";
// remove old file and create save folder
if (fs::is_directory(rootPath)) {
fs::remove_all(rootPath);
}
fs::create_directories(rootPath);
fs::create_directories(leftPath);
fs::create_directories(rightPath);
// create IMU file name
fs::path imuPath = rootPath / "imu.csv";
std::fstream imuFile(imuPath.string(), ios::out);
CHECK(imuFile.is_open()) << fmt::format("cannot create IMU file \"{}\"", imuPath.string());
imuFile << "# Timestamp(ns), AccX(m/s^2), AccY(m/s^2), AccZ(m/s^2), GyroX(rad/s), GyroY(rad/s), GyroZ(rad/s)"
<< endl;
// get device information(list)
cout << section("Device Information") << endl;
Camera cam;
DeviceInfo deviceInfo;
if (!util::select(cam, &deviceInfo)) {
LOG(FATAL) << "cannot get device information";
}
// print out device information
util::print_stream_infos(cam, deviceInfo.index);
// open camera
cout << section("Open Camera") << endl;
LOG(INFO) << fmt::format("open device, index = {}, name = {}", deviceInfo.index, deviceInfo.name) << endl;
// set open parameters
OpenParams openParams(deviceInfo.index);
openParams.framerate = frameRate;
openParams.dev_mode = DeviceMode::DEVICE_COLOR;
openParams.color_mode = ColorMode::COLOR_RAW;
openParams.stream_mode = streamMode;
openParams.color_stream_format = streamFormat;
// open
cam.Open(openParams);
if (!cam.IsOpened()) {
LOG(FATAL) << "open camera failed";
} else {
LOG(INFO) << "open device success";
}
// data enable
cam.EnableImageInfo(true);
cam.EnableProcessMode(ProcessMode::PROC_IMU_ALL);
cam.EnableMotionDatas();
bool isRightCameraEnable = cam.IsStreamDataEnabled(ImageType::IMAGE_RIGHT_COLOR);
LOG(INFO) << fmt::format("FPS = {} Hz", cam.GetOpenParams().framerate);
LOG(INFO) << fmt::format("is left enabled = {}", cam.IsStreamDataEnabled(ImageType::IMAGE_LEFT_COLOR));
LOG(INFO) << fmt::format("is right enabled = {}", isRightCameraEnable);
// obtain sensor data and save
cout << section("Process Sensor Data") << endl;
size_t leftImageNum{0}, rightImageNum{0};
constexpr double kDeg2Rad = M_PI / 180.;
constexpr double kG{9.81};
double lastLeftTimestamp{0};
while (true) {
cam.WaitForStream();
// get left stream
auto leftStreams = cam.GetStreamDatas(ImageType::IMAGE_LEFT_COLOR);
for (auto& leftStream : leftStreams) {
if (leftStream.img && leftStream.img_info) {
LOG(INFO) << fmt::format("process left image, index = {}, timestamp = {:.5f} s", leftImageNum,
leftStream.img_info->timestamp * 1.E-5);
double currentTime = leftStream.img_info->timestamp * 1.E-5;
double delta = currentTime - lastLeftTimestamp;
LOG_IF(WARNING, delta > 0.06) << fmt::format(
"lost frame, last timestamp = {:.5f} s, current timestamp = {:.5f} s"
", delta time = {:.5f} s, N ~ {}",
lastLeftTimestamp, currentTime, delta, delta / 0.033);
lastLeftTimestamp = currentTime;
// // get image info
// auto type = leftStream.img->type();
// auto format = leftStream.img->format();
// auto width = leftStream.img->width();
// auto height = leftStream.img->height();
// auto is_buffer = leftStream.img->is_buffer();
// auto frameId = leftStream.img->frame_id();
// auto is_dual = leftStream.img->is_dual();
// auto data_size = leftStream.img->data_size();
// auto valid_size = leftStream.img->valid_size();
// auto size = leftStream.img->size();
// auto get_image_profile = leftStream.img->get_image_profile();
// Mat img = leftStream.img->To(ImageFormat::COLOR_BGR)->ToMat();
// fs::path fileName = leftPath / fmt::format("{}.jpg", leftStream.img_info->timestamp * 1.0E4);
// imwrite(fileName.string(), img);
// Mat img = leftStream.img->To(ImageFormat::COLOR_BGR)->ToMat();
// fs::path fileName = leftPath / fmt::format("{}.jpg", leftStream.img_info->timestamp * 1.0E4);
// imwrite(fileName.string(), img);
// show
// if (showImg || imgNum / 10 == 0) {
// imshow("Left", img);
// }
}
}
++leftImageNum;
#if false
// get right stream
if (isRightCameraEnable) {
auto rightStream = cam.GetStreamData(ImageType::IMAGE_RIGHT_COLOR);
if (rightStream.img && rightStream.img_info) {
LOG(INFO) << fmt::format("process right image, index = {}", rightImageNum);
Mat img = rightStream.img->To(ImageFormat::COLOR_BGR)->ToMat();
fs::path fileName = rightPath / fmt::format("{}.jpg", rightStream.img_info->timestamp * 1.0E4);
imwrite(fileName.string(), img);
// // show
// if (showImg || rightImageNum / 10 == 0) {
// imshow("Right", img);
// }
}
++rightImageNum;
}
// get IMU
auto motionData = cam.GetMotionDatas();
for (auto& motion : motionData) {
if (motion.imu) {
imuFile << fmt::format("{},{},{}, {},{},{},{}", motion.imu->timestamp * 1.0E4,
motion.imu->gyro[0] * kDeg2Rad, motion.imu->gyro[1] * kDeg2Rad,
motion.imu->gyro[2] * kDeg2Rad, motion.imu->accel[0] * kG,
motion.imu->accel[1] * kG, motion.imu->accel[2] * kG)
<< endl;
}
}
#endif
// exit
// auto key = static_cast<char>(waitKey(1));
// if (key == 27 || key == 'q' || key == 'Q' || key == 'x' || key == 'X') {
// break;
// }
}
imuFile.close();
cam.Close();
google::ShutdownGoogleLogging();
return 0;
}
| 41.336 | 115 | 0.579253 | [
"vector"
] |
798b9617f5599f19c0f1ed6aa79b2e834767f66e | 19,614 | cpp | C++ | samples/15_zznvcodec/zznvdec.cpp | zzlee/tegra_multimedia_api | 350dfc806b250b238226855b254f865a14630cf8 | [
"Unlicense"
] | null | null | null | samples/15_zznvcodec/zznvdec.cpp | zzlee/tegra_multimedia_api | 350dfc806b250b238226855b254f865a14630cf8 | [
"Unlicense"
] | null | null | null | samples/15_zznvcodec/zznvdec.cpp | zzlee/tegra_multimedia_api | 350dfc806b250b238226855b254f865a14630cf8 | [
"Unlicense"
] | null | null | null | #include "zznvcodec.h"
#include "NvVideoDecoder.h"
#include "ZzLog.h"
#include "NvUtils.h"
#include <errno.h>
#include <fstream>
#include <iostream>
#include <linux/videodev2.h>
#include <malloc.h>
#include <pthread.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <poll.h>
#include <nvbuf_utils.h>
#include <npp.h>
#define CHUNK_SIZE 4000000
#define MAX_BUFFERS 32
#define MAX_VIDEO_BUFFERS 4
ZZ_INIT_LOG("zznvdec");
#define IS_NAL_UNIT_START(buffer_ptr) (!buffer_ptr[0] && !buffer_ptr[1] && \
!buffer_ptr[2] && (buffer_ptr[3] == 1))
#define IS_NAL_UNIT_START1(buffer_ptr) (!buffer_ptr[0] && !buffer_ptr[1] && \
(buffer_ptr[2] == 1))
static int MapDMABuf(int dmabuf_fd, unsigned int planes, void** ppsrc_data)
{
if (dmabuf_fd <= 0)
return -1;
int ret = -1;
for(unsigned int i = 0;i < planes;++i) {
ret = NvBufferMemMap(dmabuf_fd, i, NvBufferMem_Read_Write, &ppsrc_data[i]);
if (ret == 0)
{
NvBufferMemSyncForCpu(dmabuf_fd, i, &ppsrc_data[i]);
}
else
{
LOGE("%s(%d): NvBufferMap failed ret=%d\n", __FUNCTION__, __LINE__, ret);
return -1;
}
}
return 0;
}
static void UnmapDMABuf(int dmabuf_fd, unsigned int planes, void** ppsrc_data) {
if (dmabuf_fd <= 0)
return;
for(unsigned int i = 0;i < planes;++i) {
NvBufferMemUnMap(dmabuf_fd, i, &ppsrc_data[i]);
}
}
struct zznvcodec_decoder_t {
enum {
STATE_READY,
STATE_STARTED,
} mState;
NvVideoDecoder* mDecoder;
pthread_t mDecoderThread;
int mDMABufFDs[MAX_BUFFERS];
int mNumCapBuffers;
int mVideoDMAFDs[MAX_VIDEO_BUFFERS];
zznvcodec_video_frame_t mVideoFrames[MAX_VIDEO_BUFFERS];
int mCurVideoDMAFDIndex;
int mFormatWidth;
int mFormatHeight;
volatile int mGotEOS;
int mGotError;
int mWidth;
int mHeight;
zznvcodec_pixel_format_t mFormat;
zznvcodec_decoder_on_video_frame_t mOnVideoFrame;
intptr_t mOnVideoFrame_User;
int mMaxPreloadBuffers;
int mPreloadBuffersIndex;
NvBufferColorFormat mBufferColorFormat;
int mV4L2PixFmt;
explicit zznvcodec_decoder_t() {
mState = STATE_READY;
mDecoder = NULL;
mDecoderThread = (pthread_t)NULL;
memset(mDMABufFDs, 0, sizeof(mDMABufFDs));
mNumCapBuffers = 0;
memset(mVideoDMAFDs, 0, sizeof(mVideoDMAFDs));
memset(mVideoFrames, 0, sizeof(mVideoFrames));
mCurVideoDMAFDIndex = 0;
mFormatWidth = 0;
mFormatHeight = 0;
mGotEOS = 0;
mGotError = 0;
mWidth = 0;
mHeight = 0;
mFormat = ZZNVCODEC_PIXEL_FORMAT_UNKNOWN;
mOnVideoFrame = NULL;
mOnVideoFrame_User = 0;
mMaxPreloadBuffers = 2;
mPreloadBuffersIndex = 0;
mBufferColorFormat = NvBufferColorFormat_Invalid;
mV4L2PixFmt = V4L2_PIX_FMT_H264;
}
~zznvcodec_decoder_t() {
if(mState != STATE_READY) {
LOGE("%s(%d): unexpected value, mState=%d", __FUNCTION__, __LINE__, mState);
}
}
void SetVideoProperty(int nWidth, int nHeight, zznvcodec_pixel_format_t nFormat) {
mWidth = nWidth;
mHeight = nHeight;
mFormat = nFormat;
switch(mFormat) {
case ZZNVCODEC_PIXEL_FORMAT_NV12:
mBufferColorFormat = NvBufferColorFormat_NV12;
break;
case ZZNVCODEC_PIXEL_FORMAT_YUV420P:
mBufferColorFormat = NvBufferColorFormat_YUV420;
break;
default:
LOGE("%s(%d): unexpected value, mFormat=%d", __FUNCTION__, __LINE__, mFormat);
break;
}
}
void SetMiscProperty(int nProperty, intptr_t pValue) {
switch(nProperty) {
case ZZNVCODEC_PROP_ENCODER_PIX_FMT: {
int* p = (int*)pValue;
switch(*p) {
case ZZNVCODEC_PIXEL_FORMAT_H264:
mV4L2PixFmt = V4L2_PIX_FMT_H264;
break;
default:
LOGE("%s(%d): unexpected value, *p = %d", __FUNCTION__, __LINE__, *p);
break;
}
}
break;
default:
LOGE("%s(%d): unexpected value, nProperty = %d", __FUNCTION__, __LINE__, nProperty);
}
}
void RegisterCallbacks(zznvcodec_decoder_on_video_frame_t pCB, intptr_t pUser) {
mOnVideoFrame = pCB;
mOnVideoFrame_User = pUser;
}
int Start() {
int ret;
if(mState != STATE_READY) {
LOGE("%s(%d): unexpected value, mState=%d", __FUNCTION__, __LINE__, mState);
return 0;
}
LOGD("Start decoder...");
mDecoder = NvVideoDecoder::createVideoDecoder("dec0");
if(! mDecoder) {
LOGE("%s(%d): NvVideoDecoder::createVideoDecoder failed", __FUNCTION__, __LINE__);
}
ret = mDecoder->subscribeEvent(V4L2_EVENT_RESOLUTION_CHANGE, 0, 0);
if(ret) {
LOGE("%s(%d): subscribeEvent failed, err=%d", __FUNCTION__, __LINE__, ret);
}
ret = mDecoder->setOutputPlaneFormat(V4L2_PIX_FMT_H264, CHUNK_SIZE);
if(ret) {
LOGE("%s(%d): setOutputPlaneFormat failed, err=%d", __FUNCTION__, __LINE__, ret);
}
ret = mDecoder->setFrameInputMode(0); // 0 --> NALu-based, 1 --> Chunk-based
if(ret) {
LOGE("%s(%d): setFrameInputMode failed, err=%d", __FUNCTION__, __LINE__, ret);
}
ret = mDecoder->output_plane.setupPlane(V4L2_MEMORY_MMAP, mMaxPreloadBuffers, true, false);
if(ret) {
LOGE("%s(%d): setupPlane failed, err=%d", __FUNCTION__, __LINE__, ret);
}
ret = mDecoder->output_plane.setStreamStatus(true);
if(ret) {
LOGE("%s(%d): setStreamStatus failed, err=%d", __FUNCTION__, __LINE__, ret);
}
ret = pthread_create(&mDecoderThread, NULL, _DecodeMain, this);
if(ret) {
ret = errno;
LOGE("%s(%d): pthread_create failed, err=%d", __FUNCTION__, __LINE__, ret);
}
mState = STATE_STARTED;
LOGD("Start decoder... DONE");
return 1;
}
void Stop() {
int ret;
if(mState != STATE_STARTED) {
LOGE("%s(%d): unexpected value, mState=%d", __FUNCTION__, __LINE__, mState);
return;
}
LOGD("Stop decoder...");
mGotEOS = 1;
mDecoder->abort();
pthread_join(mDecoderThread, NULL);
mDecoder = NULL;
delete mDecoder;
mDecoder = NULL;
for(int i = 0 ; i < mNumCapBuffers ; i++) {
if(mDMABufFDs[i] != 0) {
ret = NvBufferDestroy (mDMABufFDs[i]);
}
}
memset(mDMABufFDs, 0, sizeof(mDMABufFDs));
mNumCapBuffers = 0;
for(int i = 0 ; i < MAX_VIDEO_BUFFERS ; i++) {
if(mVideoDMAFDs[i] != 0) {
if(mVideoFrames[i].num_planes != 0) {
void* pPlanes[ZZNVCODEC_MAX_PLANES] = {
mVideoFrames[i].planes[0].ptr,
mVideoFrames[i].planes[1].ptr,
mVideoFrames[i].planes[2].ptr };
UnmapDMABuf(mVideoDMAFDs[i], mVideoFrames[i].num_planes, pPlanes);
}
ret = NvBufferDestroy (mVideoDMAFDs[i]);
}
}
memset(mVideoDMAFDs, 0, sizeof(mVideoDMAFDs));
memset(mVideoFrames, 0, sizeof(mVideoFrames));
mCurVideoDMAFDIndex = 0;
mFormatWidth = 0;
mFormatHeight = 0;
mGotEOS = 0;
mGotError = 0;
mMaxPreloadBuffers = 2;
mPreloadBuffersIndex = 0;
mBufferColorFormat = NvBufferColorFormat_Invalid;
mState = STATE_READY;
LOGD("Stop decoder... DONE");
}
void EnqueuePacket(unsigned char* pBuffer, int nSize, int64_t nTimestamp) {
int ret;
struct v4l2_buffer v4l2_buf;
struct v4l2_plane planes[MAX_PLANES];
NvBuffer *buffer;
memset(&v4l2_buf, 0, sizeof(v4l2_buf));
memset(planes, 0, sizeof(planes));
v4l2_buf.m.planes = planes;
if(mPreloadBuffersIndex == mDecoder->output_plane.getNumBuffers()) {
// reused
ret = mDecoder->output_plane.dqBuffer(v4l2_buf, &buffer, NULL, -1);
if(ret < 0) {
LOGE("%s(%d): Error DQing buffer at output plane", __FUNCTION__, __LINE__);
}
} else {
// preload
buffer = mDecoder->output_plane.getNthBuffer(mPreloadBuffersIndex);
v4l2_buf.index = mPreloadBuffersIndex;
mPreloadBuffersIndex++;
}
char *buffer_ptr = (char *) buffer->planes[0].data;
// nppsCopy_8u((const Npp8u*)buffer_ptr, (Npp8u*)pBuffer, nSize);
memcpy(buffer_ptr, (Npp8u*)pBuffer, nSize);
buffer->planes[0].bytesused = nSize;
v4l2_buf.m.planes[0].bytesused = buffer->planes[0].bytesused;
v4l2_buf.flags |= V4L2_BUF_FLAG_TIMESTAMP_COPY;
v4l2_buf.timestamp.tv_sec = (int)(nTimestamp / 1000000);
v4l2_buf.timestamp.tv_usec = (int)(nTimestamp % 1000000);
#if 0
LOGD("%s(%d): buffer: index=%d planes[0]:bytesused=%d", __FUNCTION__, __LINE__, buffer->index, buffer->planes[0].bytesused);
LOGD("%s(%d): [%02X %02X %02X %02X %02X %02X %02X %02X]", __FUNCTION__, __LINE__,
(int)((uint8_t*)buffer->planes[0].data)[0], (int)((uint8_t*)buffer->planes[0].data)[1],
(int)((uint8_t*)buffer->planes[0].data)[2], (int)((uint8_t*)buffer->planes[0].data)[3],
(int)((uint8_t*)buffer->planes[0].data)[4], (int)((uint8_t*)buffer->planes[0].data)[5],
(int)((uint8_t*)buffer->planes[0].data)[6], (int)((uint8_t*)buffer->planes[0].data)[7]);
#endif
ret = mDecoder->output_plane.qBuffer(v4l2_buf, NULL);
if (ret < 0)
{
LOGE("%s(%d): Error Qing buffer at output plane", __FUNCTION__, __LINE__);
}
}
void SetVideoCompressionBuffer(unsigned char* pBuffer, int nSize, int nFlags, int64_t nTimestamp) {
#if 0
EnqueuePacket(pBuffer, nSize, nTimestamp);
#else
// find first NALu
int start_bytes;
while(nSize > 4) {
if(IS_NAL_UNIT_START(pBuffer)) {
start_bytes = 4;
break;
} else if(IS_NAL_UNIT_START1(pBuffer)) {
start_bytes = 3;
break;
}
pBuffer++;
nSize--;
}
// find rest of NALu
while(true) {
unsigned char* next_nalu = pBuffer + start_bytes;
int next_size = nSize - start_bytes;
int next_start_bytes;
while(next_size > 4) {
if(IS_NAL_UNIT_START(next_nalu)) {
next_start_bytes = 4;
break;
} else if(IS_NAL_UNIT_START1(next_nalu)) {
next_start_bytes = 3;
break;
}
next_nalu++;
next_size--;
}
if(next_size <= 4) {
// the last NALu
EnqueuePacket(pBuffer, nSize, nTimestamp);
break;
}
EnqueuePacket(pBuffer, (int)(next_nalu - pBuffer), nTimestamp);
pBuffer = next_nalu;
nSize = next_size;
start_bytes = next_start_bytes;
}
#endif
}
static void* _DecodeMain(void* arg) {
zznvcodec_decoder_t* pThis = (zznvcodec_decoder_t*)arg;
return pThis->DecoderMain();
}
void* DecoderMain() {
int ret, err;
struct v4l2_event ev;
LOGD("%s: begins", __FUNCTION__);
bool got_resolution = false;
while(! got_resolution && !mGotError) {
LOGD("%s(%d): wait for V4L2_EVENT_RESOLUTION_CHANGE...", __FUNCTION__, __LINE__);
ret = mDecoder->dqEvent(ev, 50000);
if (ret == 0)
{
switch (ev.type)
{
case V4L2_EVENT_RESOLUTION_CHANGE:
LOGD("%s(%d): New V4L2_EVENT_RESOLUTION_CHANGE received!!", __FUNCTION__, __LINE__);
QueryAndSetCapture();
got_resolution = true;
break;
default:
LOGE("%s(%d): unexpected value, ev.type=%d", __FUNCTION__, __LINE__, ev.type);
break;
}
} else {
LOGE("%s(%d): failed to received V4L2_EVENT_RESOLUTION_CHANGE, ret=%d", __FUNCTION__, __LINE__, ret);
mGotError = 1;
}
}
LOGD("start decoding... error=%d, isInError=%d, EOS=%d", mGotError, mDecoder->isInError(), mGotEOS);
while (!(mGotError || mDecoder->isInError() || mGotEOS)) {
NvBuffer *dec_buffer;
struct v4l2_buffer v4l2_buf;
struct v4l2_plane planes[MAX_PLANES];
memset(&v4l2_buf, 0, sizeof(v4l2_buf));
memset(planes, 0, sizeof(planes));
v4l2_buf.m.planes = planes;
// Dequeue a filled buffer
if (mDecoder->capture_plane.dqBuffer(v4l2_buf, &dec_buffer, NULL, 0))
{
err = errno;
if (err == EAGAIN)
{
usleep(1000);
continue;
}
else
{
if(! mGotEOS)
LOGE("%s(%d): Error while calling dequeue at capture plane, errno=%d", __FUNCTION__, __LINE__, err);
}
mGotError = 1;
break;
}
/* Clip & Stitch can be done by adjusting rectangle */
NvBufferRect src_rect, dest_rect;
src_rect.top = 0;
src_rect.left = 0;
src_rect.width = mFormatWidth;
src_rect.height = mFormatHeight;
dest_rect.top = 0;
dest_rect.left = 0;
dest_rect.width = mFormatWidth;
dest_rect.height = mFormatHeight;
NvBufferTransformParams transform_params;
memset(&transform_params,0,sizeof(transform_params));
/* Indicates which of the transform parameters are valid */
transform_params.transform_flag = NVBUFFER_TRANSFORM_FILTER;
transform_params.transform_flip = NvBufferTransform_None;
transform_params.transform_filter = NvBufferTransform_Filter_Smart;
transform_params.src_rect = src_rect;
transform_params.dst_rect = dest_rect;
dec_buffer->planes[0].fd = mDMABufFDs[v4l2_buf.index];
// ring video frame buffer
int dst_fd = mVideoDMAFDs[mCurVideoDMAFDIndex];
zznvcodec_video_frame_t& oVideoFrame = mVideoFrames[mCurVideoDMAFDIndex];
mCurVideoDMAFDIndex = (mCurVideoDMAFDIndex + 1) % MAX_VIDEO_BUFFERS;
// Convert Blocklinear to PitchLinear
ret = NvBufferTransform(dec_buffer->planes[0].fd, dst_fd, &transform_params);
if (ret == -1)
{
LOGE("%s(%d): Transform failed", __FUNCTION__, __LINE__);
mGotError = 1;
break;
}
NvBufferParams parm;
ret = NvBufferGetParams(dst_fd, &parm);
#if 0
LOGD("%s(%d): parm={%d(%d) %d, %dx%d(%d) %dx%d(%d) %dx%d(%d)}\n", __FUNCTION__, __LINE__,
parm.pixel_format, NvBufferColorFormat_YUV420, parm.num_planes,
parm.width[0], parm.height[0], parm.pitch[0],
parm.width[1], parm.height[1], parm.pitch[1],
parm.width[2], parm.height[2], parm.pitch[2]);
#endif
if(oVideoFrame.num_planes == 0) {
void* pPlanes[ZZNVCODEC_MAX_PLANES] = { NULL, NULL, NULL };
ret = MapDMABuf(dst_fd, parm.num_planes, pPlanes);
oVideoFrame.num_planes = parm.num_planes;
for(int i = 0;i < parm.num_planes;++i) {
oVideoFrame.planes[i].width = parm.width[i];
oVideoFrame.planes[i].height = parm.height[i];
oVideoFrame.planes[i].ptr = (uint8_t*)pPlanes[i];
oVideoFrame.planes[i].stride = parm.pitch[i];
}
}
#if 0
LOGD("%s(%d): dst_fd=%d planes[]={%p %p %p}\n", __FUNCTION__, __LINE__, dst_fd,
oVideoFrame.planes[0].ptr, oVideoFrame.planes[1].ptr, oVideoFrame.planes[2].ptr);
#endif
if(mOnVideoFrame) {
int64_t pts = v4l2_buf.timestamp.tv_sec * 1000000LL + v4l2_buf.timestamp.tv_usec;
mOnVideoFrame(&oVideoFrame, pts, mOnVideoFrame_User);
}
v4l2_buf.m.planes[0].m.fd = mDMABufFDs[v4l2_buf.index];
if (mDecoder->capture_plane.qBuffer(v4l2_buf, NULL) < 0)
{
LOGE("%s(%d): Error while queueing buffer at decoder capture plane", __FUNCTION__, __LINE__);
mGotError = 1;
break;
}
}
LOGD("%s: ends", __FUNCTION__);
return NULL;
}
void QueryAndSetCapture() {
int ret;
struct v4l2_format format;
struct v4l2_crop crop;
int32_t min_dec_capture_buffers;
NvBufferCreateParams input_params = {0};
NvBufferCreateParams cParams = {0};
ret = mDecoder->capture_plane.getFormat(format);
ret = mDecoder->capture_plane.getCrop(crop);
LOGD("Video Resolution: %d x %d (PixFmt=%08X, %dx%d)", crop.c.width, crop.c.height,
format.fmt.pix_mp.pixelformat, format.fmt.pix_mp.width, format.fmt.pix_mp.height);
mDecoder->capture_plane.deinitPlane();
for(int index = 0 ; index < mNumCapBuffers ; index++) {
if(mDMABufFDs[index] != 0) {
ret = NvBufferDestroy (mDMABufFDs[index]);
}
}
memset(mDMABufFDs, 0, sizeof(mDMABufFDs));
for(int i = 0 ; i < MAX_VIDEO_BUFFERS ; i++) {
if(mVideoDMAFDs[i] != 0) {
if(mVideoFrames[i].num_planes != 0) {
void* pPlanes[ZZNVCODEC_MAX_PLANES] = {
mVideoFrames[i].planes[0].ptr,
mVideoFrames[i].planes[1].ptr,
mVideoFrames[i].planes[2].ptr };
UnmapDMABuf(mVideoDMAFDs[i], mVideoFrames[i].num_planes, pPlanes);
}
ret = NvBufferDestroy (mVideoDMAFDs[i]);
}
}
memset(mVideoDMAFDs, 0, sizeof(mVideoDMAFDs));
memset(mVideoFrames, 0, sizeof(mVideoFrames));
ret = mDecoder->setCapturePlaneFormat(format.fmt.pix_mp.pixelformat, format.fmt.pix_mp.width, format.fmt.pix_mp.height);
mFormatHeight = format.fmt.pix_mp.height;
mFormatWidth = format.fmt.pix_mp.width;
for(int i = 0;i < MAX_VIDEO_BUFFERS;++i) {
input_params.payloadType = NvBufferPayload_SurfArray;
input_params.width = crop.c.width;
input_params.height = crop.c.height;
input_params.layout = NvBufferLayout_Pitch;
input_params.colorFormat = mBufferColorFormat;
input_params.nvbuf_tag = NvBufferTag_VIDEO_CONVERT;
ret = NvBufferCreateEx (&mVideoDMAFDs[i], &input_params);
}
ret = mDecoder->getMinimumCapturePlaneBuffers(min_dec_capture_buffers);
switch(format.fmt.pix_mp.colorspace) {
case V4L2_COLORSPACE_SMPTE170M:
if (format.fmt.pix_mp.quantization == V4L2_QUANTIZATION_DEFAULT)
{
LOGD("Decoder colorspace ITU-R BT.601 with standard range luma (16-235)");
cParams.colorFormat = NvBufferColorFormat_NV12;
}
else
{
LOGD("Decoder colorspace ITU-R BT.601 with extended range luma (0-255)");
cParams.colorFormat = NvBufferColorFormat_NV12_ER;
}
break;
case V4L2_COLORSPACE_REC709:
if (format.fmt.pix_mp.quantization == V4L2_QUANTIZATION_DEFAULT)
{
LOGD("Decoder colorspace ITU-R BT.709 with standard range luma (16-235)");
cParams.colorFormat = NvBufferColorFormat_NV12_709;
}
else
{
LOGD("Decoder colorspace ITU-R BT.709 with extended range luma (0-255)");
cParams.colorFormat = NvBufferColorFormat_NV12_709_ER;
}
break;
case V4L2_COLORSPACE_BT2020:
{
LOGD("Decoder colorspace ITU-R BT.2020");
cParams.colorFormat = NvBufferColorFormat_NV12_2020;
}
break;
default:
LOGD("supported colorspace details not available, use default");
if (format.fmt.pix_mp.quantization == V4L2_QUANTIZATION_DEFAULT)
{
LOGD("Decoder colorspace ITU-R BT.601 with standard range luma (16-235)");
cParams.colorFormat = NvBufferColorFormat_NV12;
}
else
{
LOGD("Decoder colorspace ITU-R BT.601 with extended range luma (0-255)");
cParams.colorFormat = NvBufferColorFormat_NV12_ER;
}
break;
}
mNumCapBuffers = min_dec_capture_buffers + 1;
for (int index = 0; index < mNumCapBuffers; index++)
{
cParams.width = crop.c.width;
cParams.height = crop.c.height;
cParams.layout = NvBufferLayout_BlockLinear;
cParams.payloadType = NvBufferPayload_SurfArray;
cParams.nvbuf_tag = NvBufferTag_VIDEO_DEC;
ret = NvBufferCreateEx(&mDMABufFDs[index], &cParams);
}
ret = mDecoder->capture_plane.reqbufs(V4L2_MEMORY_DMABUF, mNumCapBuffers);
ret = mDecoder->capture_plane.setStreamStatus(true);
for (uint32_t i = 0; i < mDecoder->capture_plane.getNumBuffers(); i++)
{
struct v4l2_buffer v4l2_buf;
struct v4l2_plane planes[MAX_PLANES];
memset(&v4l2_buf, 0, sizeof(v4l2_buf));
memset(planes, 0, sizeof(planes));
v4l2_buf.index = i;
v4l2_buf.m.planes = planes;
v4l2_buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
v4l2_buf.memory = V4L2_MEMORY_DMABUF;
v4l2_buf.m.planes[0].m.fd = mDMABufFDs[i];
ret = mDecoder->capture_plane.qBuffer(v4l2_buf, NULL);
}
}
};
zznvcodec_decoder_t* zznvcodec_decoder_new() {
return new zznvcodec_decoder_t();
}
void zznvcodec_decoder_delete(zznvcodec_decoder_t* pThis) {
delete pThis;
}
void zznvcodec_decoder_set_video_property(zznvcodec_decoder_t* pThis, int nWidth, int nHeight, zznvcodec_pixel_format_t nFormat) {
pThis->SetVideoProperty(nWidth, nHeight, nFormat);
}
void zznvcodec_decoder_set_misc_property(zznvcodec_decoder_t* pThis, int nProperty, intptr_t pValue) {
pThis->SetMiscProperty(nProperty, pValue);
}
void zznvcodec_decoder_register_callbacks(zznvcodec_decoder_t* pThis, zznvcodec_decoder_on_video_frame_t pCB, intptr_t pUser) {
pThis->RegisterCallbacks(pCB, pUser);
}
int zznvcodec_decoder_start(zznvcodec_decoder_t* pThis) {
return pThis->Start();
}
void zznvcodec_decoder_stop(zznvcodec_decoder_t* pThis) {
return pThis->Stop();
}
void zznvcodec_decoder_set_video_compression_buffer(zznvcodec_decoder_t* pThis, unsigned char* pBuffer, int nSize, int nFlags, int64_t nTimestamp) {
return pThis->SetVideoCompressionBuffer(pBuffer, nSize, nFlags, nTimestamp);
} | 28.550218 | 148 | 0.693586 | [
"transform"
] |
799aa260b7569efb4e61db2b55e96cf23bc115b1 | 8,692 | cpp | C++ | src/Engine/RenderBackend/OGLRenderer/OGLRenderCommands.cpp | kimkulling/osre | b738c87e37d0b1d2d0779a412b88ce68517c4328 | [
"MIT"
] | 118 | 2015-05-12T15:12:14.000Z | 2021-11-14T15:41:11.000Z | src/Engine/RenderBackend/OGLRenderer/OGLRenderCommands.cpp | kimkulling/osre | b738c87e37d0b1d2d0779a412b88ce68517c4328 | [
"MIT"
] | 76 | 2015-06-06T18:04:24.000Z | 2022-01-14T20:17:37.000Z | src/Engine/RenderBackend/OGLRenderer/OGLRenderCommands.cpp | kimkulling/osre | b738c87e37d0b1d2d0779a412b88ce68517c4328 | [
"MIT"
] | 7 | 2016-06-28T09:14:38.000Z | 2021-03-12T02:07:52.000Z | /*-----------------------------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2015-2021 OSRE ( Open Source Render Engine ) by Kim Kulling
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 "OGLRenderCommands.h"
#include "OGLCommon.h"
#include "OGLRenderBackend.h"
#include "OGLRenderEventHandler.h"
#include "OGLShader.h"
#include "RenderCmdBuffer.h"
#include <osre/App/AssetRegistry.h>
#include <osre/Common/Logger.h>
#include <osre/Debugging/osre_debugging.h>
#include <osre/IO/Uri.h>
#include <osre/Platform/AbstractOGLRenderContext.h>
#include <osre/Platform/AbstractWindow.h>
#include <osre/Platform/PlatformInterface.h>
#include <osre/Profiling/PerformanceCounterRegistry.h>
#include <osre/RenderBackend/THWBufferManager.h>
#include <osre/RenderBackend/Mesh.h>
#include <osre/RenderBackend/RenderCommon.h>
#include <osre/RenderBackend/Shader.h>
namespace OSRE {
namespace RenderBackend {
static const c8 *Tag = "OGLRenderCommands";
using namespace ::OSRE::Common;
using namespace ::OSRE::Platform;
using namespace ::CPPCore;
bool setupTextures(Material *mat, OGLRenderBackend *rb, TArray<OGLTexture *> &textures) {
if (nullptr == mat) {
osre_debug(Tag, "Material is nullptr.");
return false;
}
if (nullptr == rb) {
osre_debug(Tag, "Renderbackend is nullptr.");
return false;
}
const size_t numTextures(mat->m_numTextures);
if (0 == numTextures) {
return true;
}
for (ui32 i = 0; i < numTextures; ++i) {
Texture *tex(mat->m_textures[i]);
if (!tex->m_textureName.empty()) {
OGLTexture *oglTexture = rb->createTexture(tex->m_textureName, tex);
if (nullptr != oglTexture) {
textures.add(oglTexture);
} else {
textures.add(rb->createDefaultTexture(tex->m_targetType, tex->mPixelFormat, tex->m_width, tex->m_height));
}
}
}
return true;
}
SetMaterialStageCmdData *setupMaterial(Material *material, OGLRenderBackend *rb, OGLRenderEventHandler *eh) {
osre_assert(nullptr != eh);
osre_assert(nullptr != material);
osre_assert(nullptr != rb);
if (nullptr == material || nullptr == rb || nullptr == eh) {
return nullptr;
}
auto *matData = new SetMaterialStageCmdData;
switch (material->m_type) {
case MaterialType::ShaderMaterial: {
TArray<OGLTexture *> textures;
setupTextures(material, rb, textures);
auto *renderMatCmd = new OGLRenderCmd(OGLRenderCmdType::SetMaterialCmd);
if (!textures.isEmpty()) {
matData->m_textures = textures;
}
String name = "mat";
name += material->m_name;
OGLShader *shader = rb->createShader(name, material->m_shader);
if (nullptr != shader) {
matData->m_shader = shader;
for (const OSRE::String & attribute : material->m_shader->m_attributes) {
shader->addAttribute(attribute);
}
for (auto & parameter : material->m_shader->m_parameters) {
shader->addUniform(parameter);
}
// for setting up all buffer objects
eh->setActiveShader(shader);
}
renderMatCmd->m_data = matData;
eh->enqueueRenderCmd(renderMatCmd);
} break;
default:
break;
}
return matData;
}
void setupParameter(UniformVar *param, OGLRenderBackend *rb, OGLRenderEventHandler *ev) {
osre_assert(nullptr != param);
osre_assert(nullptr != rb);
osre_assert(nullptr != ev);
if (nullptr == param || nullptr == rb || nullptr == ev) {
return;
}
::CPPCore::TArray<OGLParameter *> paramArray;
OGLParameter *oglParam = rb->getParameter(param->m_name);
if (nullptr == oglParam) {
oglParam = rb->createParameter(param->m_name, param->m_type, ¶m->m_data, param->m_numItems);
} else {
::memcpy(oglParam->m_data->getData(), param->m_data.getData(), param->m_data.m_size);
}
paramArray.add(oglParam);
ev->setParameter(paramArray);
}
OGLVertexArray *setupBuffers(Mesh *mesh, OGLRenderBackend *rb, OGLShader *oglShader) {
osre_assert(nullptr != mesh);
osre_assert(nullptr != rb);
osre_assert(nullptr != oglShader);
if (nullptr == mesh || nullptr == rb || nullptr == oglShader) {
return nullptr;
}
rb->useShader(oglShader);
OGLVertexArray *vertexArray = rb->createVertexArray();
rb->bindVertexArray(vertexArray);
BufferData *vertices = mesh->m_vb;
if (nullptr == vertices) {
osre_debug(Tag, "No vertex buffer data for setting up data.");
return nullptr;
}
BufferData *indices = mesh->m_ib;
if (nullptr == indices) {
osre_debug(Tag, "No index buffer data for setting up data.");
return nullptr;
}
// create vertex buffer and and pass triangle vertex to buffer object
OGLBuffer *vb = rb->createBuffer(vertices->m_type);
vb->m_geoId = mesh->m_id;
rb->bindBuffer(vb);
rb->copyDataToBuffer(vb, vertices->getData(), vertices->getSize(), vertices->m_access);
// enable vertex attribute arrays
TArray<OGLVertexAttribute *> attributes;
rb->createVertexCompArray(mesh->m_vertextype, oglShader, attributes);
const size_t stride = Mesh::getVertexSize(mesh->m_vertextype);
rb->bindVertexLayout(vertexArray, oglShader, stride, attributes);
rb->releaseVertexCompArray(attributes);
// create index buffer and pass indices to element array buffer
OGLBuffer *ib = rb->createBuffer(indices->m_type);
ib->m_geoId = mesh->m_id;
rb->bindBuffer(ib);
rb->copyDataToBuffer(ib, indices->getData(), indices->getSize(), indices->m_access);
rb->unbindVertexArray();
return vertexArray;
}
void setupPrimDrawCmd(const char *id, bool useLocalMatrix, const glm::mat4 &model,
const TArray<size_t> &primGroups, OGLRenderBackend *rb,
OGLRenderEventHandler *eh, OGLVertexArray *va) {
osre_assert(nullptr != rb);
osre_assert(nullptr != eh);
if (primGroups.isEmpty()) {
return;
}
auto *renderCmd = new OGLRenderCmd(OGLRenderCmdType::DrawPrimitivesCmd);
auto *data = new DrawPrimitivesCmdData;
if (useLocalMatrix) {
data->m_model = model;
data->m_localMatrix = useLocalMatrix;
}
data->m_id = id;
data->m_vertexArray = va;
data->m_primitives.reserve(primGroups.size());
for (ui32 i = 0; i < primGroups.size(); ++i) {
data->m_primitives.add(primGroups[i]);
}
renderCmd->m_data = static_cast<void *>(data);
eh->enqueueRenderCmd(renderCmd);
}
void setupInstancedDrawCmd(const char *id, const TArray<size_t> &ids, OGLRenderBackend *rb,
OGLRenderEventHandler *eh, OGLVertexArray *va, size_t numInstances) {
osre_assert(nullptr != rb);
osre_assert(nullptr != eh);
if (ids.isEmpty()) {
return;
}
OGLRenderCmd *renderCmd = new OGLRenderCmd(OGLRenderCmdType::DrawPrimitivesInstancesCmd);
DrawInstancePrimitivesCmdData *data = new DrawInstancePrimitivesCmdData;
data->m_id = id;
data->m_vertexArray = va;
data->m_numInstances = numInstances;
data->m_primitives.reserve(ids.size());
for (ui32 j = 0; j < ids.size(); ++j) {
data->m_primitives.add(ids[j]);
}
renderCmd->m_data = static_cast<void *>(data);
eh->enqueueRenderCmd(renderCmd);
}
} // Namespace RenderBackend
} // Namespace OSRE
| 34.768 | 122 | 0.650483 | [
"mesh",
"render",
"object",
"model"
] |
799b3fca3a68abb2bdf2fa940b184662d5fb635a | 616 | cpp | C++ | test_package/test_package.cpp | bincrafters/conan-picobench | f26633e6f6230cb8f356c9b4da828a5ea13542ed | [
"MIT"
] | null | null | null | test_package/test_package.cpp | bincrafters/conan-picobench | f26633e6f6230cb8f356c9b4da828a5ea13542ed | [
"MIT"
] | null | null | null | test_package/test_package.cpp | bincrafters/conan-picobench | f26633e6f6230cb8f356c9b4da828a5ea13542ed | [
"MIT"
] | null | null | null | #define PICOBENCH_IMPLEMENT_WITH_MAIN
#include "picobench/picobench.hpp"
#include <vector>
#include <cstdlib> // for rand
// Benchmarking function written by the user:
static void rand_vector(picobench::state& s)
{
std::vector<int> v;
for (auto _ : s)
{
v.push_back(rand());
}
}
PICOBENCH(rand_vector); // Register the above function with picobench
// Another benchmarking function:
static void rand_vector_reserve(picobench::state& s)
{
std::vector<int> v;
v.reserve(s.iterations());
for (auto _ : s)
{
v.push_back(rand());
}
}
PICOBENCH(rand_vector_reserve);
| 21.241379 | 69 | 0.675325 | [
"vector"
] |
799ef25e1a3a73f98ef06e8ca12d2f216165d4e9 | 613 | hpp | C++ | Definitions.hpp | raven91/deformable_cell_model_integration | fa9e31ef42044cb42f534f0be0f20d8ead69c34e | [
"MIT"
] | null | null | null | Definitions.hpp | raven91/deformable_cell_model_integration | fa9e31ef42044cb42f534f0be0f20d8ead69c34e | [
"MIT"
] | null | null | null | Definitions.hpp | raven91/deformable_cell_model_integration | fa9e31ef42044cb42f534f0be0f20d8ead69c34e | [
"MIT"
] | null | null | null | //
// Created by Nikita Kruk on 15.03.21.
//
#ifndef DEFORMABLECELLMODEL_DEFINITIONS_HPP
#define DEFORMABLECELLMODEL_DEFINITIONS_HPP
#include <array>
#include <set>
#include <utility> // std::pair
#include <eigen3/Eigen/Dense>
const int kDim = 3;
const int kFaceDim = 3;
const int kEdgeDim = 2;
//using VectorType = std::array<double, kDim>; // as an element of a vector space
using VectorType = Eigen::Vector3d; // as an element of a vector space
using FaceType = std::array<int, kFaceDim>;
using EdgeType = std::pair<int, int>;
using IndexSet = std::set<int>;
#endif //DEFORMABLECELLMODEL_DEFINITIONS_HPP
| 24.52 | 81 | 0.738989 | [
"vector"
] |
79a58262638ef01cef643bae04c0f1403e597338 | 3,428 | hpp | C++ | src/math/geometry/projective/camera/focus/orto2d.hpp | dmilos/math | 977cb171d8d582411cfab73a23ce85a8ccf3b132 | [
"Apache-2.0"
] | 3 | 2020-07-02T12:44:32.000Z | 2021-04-07T20:31:41.000Z | src/math/geometry/projective/camera/focus/orto2d.hpp | dmilos/math | 977cb171d8d582411cfab73a23ce85a8ccf3b132 | [
"Apache-2.0"
] | null | null | null | src/math/geometry/projective/camera/focus/orto2d.hpp | dmilos/math | 977cb171d8d582411cfab73a23ce85a8ccf3b132 | [
"Apache-2.0"
] | 1 | 2020-09-04T11:01:28.000Z | 2020-09-04T11:01:28.000Z | #ifndef math_geometry_projective_camera_focus_orto3D
#define math_geometry_projective_camera_focus_orto3D
// ::math::geometry::projective::camera::focus::orto2d( f, origin, X, Y )
//#include <utility>
namespace math
{
namespace geometry
{
namespace projective
{
namespace camera
{
namespace focus
{
/*** Tactical look
| ^
| /|
| / Y
| / |
| / +---X--->
| / /| /
| / / | /
----------*---*-+-----*--
| / / /
F / / /
| /
(0,0)
*/
template < typename scalar_name >
bool
orto2d
(
scalar_name & focus
,::math::linear::vector::structure< scalar_name, 3 > & origin //!< ( x, y, p )
,std::array< scalar_name, 2 > const& X //!< ( projection , lengthX )
,std::array< scalar_name, 2 > const& Y //!< ( projection , lengthY )
)
{
auto const& Xp = X[0];
auto const& Xl = X[1];
auto const& Yp = Y[0];
auto const& Yl = Y[1];
auto & Ox = origin[0];
auto & Oy = origin[1];
auto const& Op = origin[2];
//! F0 = (0,0) + t*( Op, focus ); y = focus/Op * x
//! Fx = (0,0) + t*( Xp, focus ); y = focus/Xp * x
//! Fy = (0,0) + t*( Yp, focus ); y = focus/Yp * x
//! V = (Ox,0) + t*( 0, 1 ); x = Ox;
//! H = (0,Oy) + t*( 1, 0 ); y =Oy;
//!
//!
//! ( F0 int V ) = ( Ox, Ox * focus/Op )
//! ( F0 int H ) = ( Oy/(focus/Op), Oy )
//! ( Fx int H ) = ( Oy/(focus/Xp), Oy )
//! ( Fy int V ) = ( Ox, Ox * focus/Yp )
//!
//!
//! || ( Fy int V ), ( F0 int V )|| = Yl --> ( Ox, Ox * focus/Yp ) - ( Ox, Ox* focus/Op ) = ( 0, Yl )
//! Ox = Ox
//! Yl = Ox * focus/Yp - Ox * focus/Op
//! (1) = Ox * focus( 1/Yp - 1/Op );
//!
//! || ( Fx int H ), ( F0 int V )|| = Xl --> ( Oy/(focus/Xp), Oy ) - ( Ox, Ox * focus/Op ) = ( Xl, 0 )
//! (2)Xl = Oy/(focus/Xp) - Ox;
//! (3)Oy = Ox * focus/Op
//!
//! || ( Fy int V ), ( F0 int H )|| = Yl; ( Ox, Ox * focus/Yp ) - ( Oy/(focus/Op), Oy ) = ( 0, Yl )
//! (4) Ox = Oy/(focus/Op);
//! (5)Yl = Ox * focus/Yp - Oy;
//!
//! || ( Fx int H ), ( F0 int H )|| = Xl ; ( Oy/(focus/Xp), Oy ) - ( Oy/(focus/Op), Oy ) = ( Xl, 0 );
//! (6)Xl = Oy/(focus/Xp) - Oy/(focus/Op)
//! = (Oy/focus) ( 1 / Xp - 1 / Op );
//! Oy = Oy
Ox = Xl*Op/ ( Xp- Op );
Oy = Yl*Yp/ ( Op- Yp );
focus = Op * (Oy/Ox);
return true;
}
}
}
}
}
}
#endif
| 34.28 | 118 | 0.297258 | [
"geometry",
"vector"
] |
79a6aa759532b61d60069cb6e4d1339b79fd0de0 | 641 | cpp | C++ | sesion7/sesion7_casa/ejercicio_12.cpp | dmateos-ugr/FP | 6d3ec8eeccbb72582367c8cf97aecb2227cc7b9e | [
"MIT"
] | 1 | 2018-12-11T09:32:59.000Z | 2018-12-11T09:32:59.000Z | sesion7/sesion7_casa/ejercicio_12.cpp | dmateos-ugr/FP | 6d3ec8eeccbb72582367c8cf97aecb2227cc7b9e | [
"MIT"
] | null | null | null | sesion7/sesion7_casa/ejercicio_12.cpp | dmateos-ugr/FP | 6d3ec8eeccbb72582367c8cf97aecb2227cc7b9e | [
"MIT"
] | 2 | 2018-11-13T12:32:35.000Z | 2018-11-27T14:43:30.000Z | #include <iostream>
using namespace std;
int main(){
const int TAMANO_MAX = 1000;
int vector[TAMANO_MAX];
int tamano;
int resultado = 1;
//Entrada
cout << "Introduzca el tamaño del vector: ";
cin >> tamano;
cout << "Introduzca los elementos del vector: ";
for (int i = 0; i < tamano; i++){
cin >> vector[i];
}
//Cálculos
for (int i = 1; i < tamano; i++){
if (vector[i] < vector[i-1]){
resultado++;
}
}
//Salida
cout << "En el vector introducido hay " << resultado << " secuencias ascendentes." << endl;
return 0;
}
| 20.677419 | 95 | 0.522621 | [
"vector"
] |
79aba85f6e993e16c201394c1b11329b849ca59c | 5,259 | cc | C++ | Firestore/core/test/firebase/firestore/remote/serializer_test.cc | todaycode/firebase-mobile-sdk | 0f4729150b60ad5e152d4ace770c06aebb75da52 | [
"Apache-2.0"
] | null | null | null | Firestore/core/test/firebase/firestore/remote/serializer_test.cc | todaycode/firebase-mobile-sdk | 0f4729150b60ad5e152d4ace770c06aebb75da52 | [
"Apache-2.0"
] | null | null | null | Firestore/core/test/firebase/firestore/remote/serializer_test.cc | todaycode/firebase-mobile-sdk | 0f4729150b60ad5e152d4ace770c06aebb75da52 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2018 Google
*
* 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.
*/
/* NB: proto bytes were created via:
echo 'TEXT_FORMAT_PROTO' \
| ./build/external/protobuf/src/protobuf-build/src/protoc \
-I./Firestore/Protos/protos \
-I./build/external/protobuf/src/protobuf/src \
--encode=google.firestore.v1beta1.Value \
google/firestore/v1beta1/document.proto \
| hexdump -C
* where TEXT_FORMAT_PROTO is the text format of the protobuf. (go/textformat).
*
* Examples:
* - For null, TEXT_FORMAT_PROTO would be 'null_value: NULL_VALUE' and would
* yield the bytes: { 0x58, 0x00 }.
* - For true, TEXT_FORMAT_PROTO would be 'boolean_value: true' and would yield
* the bytes { 0x08, 0x01 }.
*
* All uses are documented below, so search for TEXT_FORMAT_PROTO to find more
* examples.
*/
#include "Firestore/core/src/firebase/firestore/remote/serializer.h"
#include <pb.h>
#include <pb_encode.h>
#include <vector>
#include "Firestore/core/src/firebase/firestore/model/field_value.h"
#include "gtest/gtest.h"
using firebase::firestore::model::FieldValue;
using firebase::firestore::remote::Serializer;
TEST(Serializer, CanLinkToNanopb) {
// This test doesn't actually do anything interesting as far as actually using
// nanopb is concerned but that it can run at all is proof that all the
// libraries required for nanopb to work are actually linked correctly into
// the test.
pb_ostream_from_buffer(NULL, 0);
}
// Fixture for running serializer tests.
class SerializerTest : public ::testing::Test {
public:
SerializerTest() : serializer(/*DatabaseId("p", "d")*/) {
}
Serializer serializer;
void ExpectRoundTrip(const FieldValue& model,
const Serializer::TypedValue& proto,
FieldValue::Type type) {
EXPECT_EQ(type, model.type());
EXPECT_EQ(type, proto.type);
Serializer::TypedValue actual_proto = serializer.EncodeFieldValue(model);
EXPECT_EQ(type, actual_proto.type);
EXPECT_EQ(proto, actual_proto);
EXPECT_EQ(model, serializer.DecodeFieldValue(proto));
}
void ExpectRoundTrip(const Serializer::TypedValue& proto,
std::vector<uint8_t> bytes,
FieldValue::Type type) {
EXPECT_EQ(type, proto.type);
std::vector<uint8_t> actual_bytes;
Serializer::EncodeTypedValue(proto, &actual_bytes);
EXPECT_EQ(bytes, actual_bytes);
Serializer::TypedValue actual_proto = Serializer::DecodeTypedValue(bytes);
EXPECT_EQ(type, actual_proto.type);
EXPECT_EQ(proto, actual_proto);
}
};
TEST_F(SerializerTest, EncodesNullModelToProto) {
FieldValue model = FieldValue::NullValue();
Serializer::TypedValue proto{FieldValue::Type::Null,
google_firestore_v1beta1_Value_init_default};
// sanity check (the _init_default above should set this to _NULL_VALUE)
EXPECT_EQ(google_protobuf_NullValue_NULL_VALUE, proto.value.null_value);
ExpectRoundTrip(model, proto, FieldValue::Type::Null);
}
TEST_F(SerializerTest, EncodesNullProtoToBytes) {
Serializer::TypedValue proto{FieldValue::Type::Null,
google_firestore_v1beta1_Value_init_default};
// sanity check (the _init_default above should set this to _NULL_VALUE)
EXPECT_EQ(google_protobuf_NullValue_NULL_VALUE, proto.value.null_value);
// TEXT_FORMAT_PROTO: 'null_value: NULL_VALUE'
std::vector<uint8_t> bytes{0x58, 0x00};
ExpectRoundTrip(proto, bytes, FieldValue::Type::Null);
}
TEST_F(SerializerTest, EncodesBoolModelToProto) {
for (bool test : {true, false}) {
FieldValue model = FieldValue::BooleanValue(test);
Serializer::TypedValue proto{FieldValue::Type::Boolean,
google_firestore_v1beta1_Value_init_default};
proto.value.boolean_value = test;
ExpectRoundTrip(model, proto, FieldValue::Type::Boolean);
}
}
TEST_F(SerializerTest, EncodesBoolProtoToBytes) {
struct TestCase {
bool value;
std::vector<uint8_t> bytes;
};
std::vector<TestCase> cases{// TEXT_FORMAT_PROTO: 'boolean_value: true'
{true, {0x08, 0x01}},
// TEXT_FORMAT_PROTO: 'boolean_value: false'
{false, {0x08, 0x00}}};
for (const TestCase& test : cases) {
Serializer::TypedValue proto{FieldValue::Type::Boolean,
google_firestore_v1beta1_Value_init_default};
proto.value.boolean_value = test.value;
ExpectRoundTrip(proto, test.bytes, FieldValue::Type::Boolean);
}
}
// TODO(rsgowman): Test [en|de]coding multiple protos into the same output
// vector.
// TODO(rsgowman): Death test for decoding invalid bytes.
| 37.297872 | 80 | 0.69595 | [
"vector",
"model"
] |
79b414a36404b0ccaa6e29924f47cb87c2262884 | 1,174 | hpp | C++ | cpp/archive/archive-src-old/core.hpp | MomsFriendlyRobotCompany/gecko | f340381113bdb423a39d47aaee61e013bb9e002a | [
"MIT"
] | 2 | 2020-03-11T03:53:19.000Z | 2020-10-06T03:18:32.000Z | cpp/archive/archive-src-old/core.hpp | MomsFriendlyRobotCompany/gecko | f340381113bdb423a39d47aaee61e013bb9e002a | [
"MIT"
] | null | null | null | cpp/archive/archive-src-old/core.hpp | MomsFriendlyRobotCompany/gecko | f340381113bdb423a39d47aaee61e013bb9e002a | [
"MIT"
] | null | null | null | #pragma once
#include <map>
#include <string>
#include <vector>
#include "signals.hpp"
#include "zmq.hpp"
#include "mbeacon.hpp"
#include "directory.hpp"
// namespace gecko {
// class Directory {
// public:
// void push(const std::string& key, const std::string& topic, const std::string& endpt); // add
// void pop(const std::string& key, const std::string& topic); // remove
// std::string find(const std::string& key, const std::string& topic);
// void print() const;
// int numberKeys() const;
// int numberTopics(const std::string& key) const;
// std::map<std::string, std::map<std::string, std::string>> db;
// };
// class Core: protected SigCapture {
class Core {
/*
GeckoCore
multicast:"239.255.255.250"
port: 1234
*/
public:
Core(std::string grp, int port);
Core(std::string grp, int port, std::string key);
~Core();
void run(int hertz=100);
void requestLoop(void);
// std::map<std::string, std::string> directory;
Directory directory;
std::string key;
bool ok;
std::string group;
int port;
protected:
void init(std::string grp, int port, std::string key);
};
| 23.959184 | 101 | 0.62862 | [
"vector"
] |
79b9870daf41fa021c1a6e50cc4a2c641649c4da | 2,718 | cpp | C++ | drone/src/moves.cpp | Rajesh-Sec-Project/simon | d9e5ecd7aa35055ebfea20654e666d48901d7b76 | [
"MIT"
] | null | null | null | drone/src/moves.cpp | Rajesh-Sec-Project/simon | d9e5ecd7aa35055ebfea20654e666d48901d7b76 | [
"MIT"
] | 1 | 2016-01-26T09:14:21.000Z | 2016-01-26T10:10:01.000Z | drone/src/moves.cpp | Rajesh-Sec-Project/simon | d9e5ecd7aa35055ebfea20654e666d48901d7b76 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2015 Kadambari Melatur, Alexandre Monti, Rémi Saurel and Emma Vareilles
*
* 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 <string>
#include <sstream>
#include <stdlib.h>
#include <time.h>
#include <map>
#include <string>
#include <unistd.h>
#include "moves.h"
std::ostream& operator<<(std::ostream& out, lmoves::tmove value) {
using namespace lmoves;
static std::map<tmove, std::string> strings;
if(strings.size() == 0) {
#define INSERT_ELEMENT(p) strings[tmove::p] = #p
INSERT_ELEMENT(DOWN);
INSERT_ELEMENT(UP);
INSERT_ELEMENT(RIGHT);
INSERT_ELEMENT(LEFT);
#undef INSERT_ELEMENT
}
return out << strings[value];
}
std::ostream& operator<<(std::ostream& out, lmoves::Moves const& seq) {
using namespace lmoves;
for(auto m : seq.getSequence()) {
out << m << ' ';
}
return out;
}
namespace lmoves {
// constructor
Moves::Moves(size_t seqLen)
: m_distrib(0, 3)
, m_generator(std::random_device{}()) {
while(seqLen-- != 0) {
this->addRandomMove();
}
}
// getter
std::vector<tmove> const& Moves::getSequence() const {
return this->m_sequence;
}
void Moves::clearSequence() {
this->m_sequence.clear();
}
size_t Moves::size() const {
return m_sequence.size();
}
tmove Moves::M_randomMove() {
return static_cast<tmove>(m_distrib(m_generator));
}
void Moves::addMove(tmove m) {
m_sequence.push_back(m);
}
void Moves::addRandomMove() {
tmove new_move = this->M_randomMove();
m_sequence.push_back(new_move);
}
}
| 29.543478 | 88 | 0.665931 | [
"vector"
] |
79b9ddfbc01246110baf64e9d2cd2430c5d1ed40 | 4,284 | cpp | C++ | src/utils.cpp | ampl/rAMPL | 573d2731f66baffa011df4540f53aa7b81beeba8 | [
"BSD-3-Clause"
] | 9 | 2018-04-11T11:27:44.000Z | 2021-11-30T03:34:32.000Z | src/utils.cpp | seanpm2001-R-lang/rAMPL | 714e454585c8dc021a82b789774735b3d09a058b | [
"BSD-3-Clause"
] | 3 | 2018-06-07T06:38:03.000Z | 2021-02-01T14:50:46.000Z | src/utils.cpp | seanpm2001-R-lang/rAMPL | 714e454585c8dc021a82b789774735b3d09a058b | [
"BSD-3-Clause"
] | 11 | 2018-06-17T14:33:56.000Z | 2021-11-30T03:40:50.000Z | #include "utils.h"
#include <Rcpp.h>
ampl::Tuple list2tuple(Rcpp::List list) {
int p = 0;
ampl::Variant arguments[list.size()];
for(Rcpp::List::iterator it = list.begin(); it != list.end(); it++) {
switch(TYPEOF(*it)) {
case REALSXP:
arguments[p++] = ampl::Variant(Rcpp::as<double>(*it));
break;
case INTSXP:
arguments[p++] = ampl::Variant(Rcpp::as<int>(*it));
break;
case STRSXP:
arguments[p++] = ampl::Variant(Rcpp::as<std::string>(*it));
break;
default:
Rcpp::stop("only accepts lists containing numbers and strings");
}
}
return ampl::Tuple(arguments, list.size());
}
Rcpp::List tuple2list(const ampl::TupleRef &tuple) {
Rcpp::List list(tuple.size());
for(std::size_t i = 0; i < tuple.size(); i++) {
const ampl::VariantRef &e = tuple[i];
if(e.type() == ampl::NUMERIC) {
list[i] = e.dbl();
} else {
list[i] = e.str();
}
}
return list;
}
ampl::DataFrame rdf2df(Rcpp::DataFrame rdf, int numberOfIndexColumns){
int nrows = rdf.nrows();
int ncols = rdf.length();
const char *names[ncols];
Rcpp::CharacterVector colnames = rdf.names();
for(int i = 0; i < colnames.size(); i++){
names[i] = Rcpp::as<const char *>(colnames[i]);
}
if(numberOfIndexColumns == -1){
numberOfIndexColumns = ncols - 1;
}
ampl::DataFrame df(numberOfIndexColumns, ampl::StringArgs(names, ncols));
int p = 0;
for(Rcpp::DataFrame::iterator it = rdf.begin(); it != rdf.end(); it++){
switch(TYPEOF(*it)) {
case REALSXP:
df.setColumn(names[p++], Rcpp::as<std::vector<double> >(*it).data(), nrows);
break;
case INTSXP:
if(::Rf_isFactor(*it) == false) {
Rcpp::IntegerVector iv = *it;
std::vector<double> dbl_column(iv.size());
for(int i = 0; i < iv.size(); i++) {
dbl_column[i] = iv[i];
}
df.setColumn(names[p++], dbl_column.data(), dbl_column.size());
} else{
Rcpp::IntegerVector iv = *it;
std::vector<const char *> str_column(iv.size());
std::vector<std::string > levels = Rcpp::as<std::vector<std::string> >(iv.attr("levels"));
for(int i = 0; i < iv.size(); i++) {
str_column[i] = levels[iv[i]-1].c_str();
}
df.setColumn(names[p++], str_column.data(), str_column.size());
}
break;
case STRSXP: {
Rcpp::StringVector iv = *it;
std::vector<const char *> str_column(iv.size());
for(int i = 0; i < iv.size(); i++) {
str_column[i] = iv[i];
}
df.setColumn(names[p++], str_column.data(), str_column.size());
}
break;
default:
Rcpp::stop("invalid type");
}
}
return df;
}
Rcpp::DataFrame df2rdf(const ampl::DataFrame &df){
Rcpp::List tmp;
int ncols = df.getNumCols();
ampl::StringRefArray headers = df.getHeaders();
for(int i = 0; i < ncols; i++){
ampl::DataFrame::Column col = df.getColumn(headers[i]);
bool numeric = true;
for(ampl::DataFrame::Column::iterator it = col.begin(); it != col.end(); it++){
if(it->type() != ampl::NUMERIC) {
numeric = false;
break;
}
}
if(numeric) {
std::vector<double> dbl_column;
for(ampl::DataFrame::Column::iterator it = col.begin(); it != col.end(); it++){
dbl_column.push_back(it->dbl());
}
tmp[headers[i]] = dbl_column;
} else {
std::vector<std::string> str_column;
for(ampl::DataFrame::Column::iterator it = col.begin(); it != col.end(); it++){
str_column.push_back(it->str());
}
tmp[headers[i]] = str_column;
}
}
return Rcpp::DataFrame(tmp);
}
SEXP variant2sexp(const ampl::VariantRef &value) {
if(value.type() == ampl::NUMERIC) {
return Rcpp::wrap(value.dbl());
} else if(value.type() == ampl::STRING) {
return Rcpp::wrap(value.str());
} else {
return Rcpp::wrap(Rcpp::String(NA_STRING));
}
}
SEXP variant2sexp(const ampl::Variant &value) {
if(value.type() == ampl::NUMERIC) {
return Rcpp::wrap(value.dbl());
} else if(value.type() == ampl::STRING) {
return Rcpp::wrap(value.str());
} else {
return Rcpp::wrap(Rcpp::String(NA_STRING));
}
}
| 30.820144 | 100 | 0.560458 | [
"vector"
] |
79bdcedd3b644f8dbd11a3db24ec714f944f3ca6 | 13,432 | cpp | C++ | projects/compiler-rt/utils/llvm-symbolizer/llvm-symbolizer.cpp | nettrino/IntFlow | 0400aef5da2c154268d8b020e393c950435395b3 | [
"Unlicense"
] | 16 | 2015-09-08T08:49:11.000Z | 2019-07-20T14:46:20.000Z | utils/llvm-symbolizer/llvm-symbolizer.cpp | llvm-tilera/compiler-rt | 7a88dff29939cc344a7519cbd174d4ac15d4ed59 | [
"MIT"
] | 1 | 2019-02-10T08:27:48.000Z | 2019-02-10T08:27:48.000Z | utils/llvm-symbolizer/llvm-symbolizer.cpp | llvm-tilera/compiler-rt | 7a88dff29939cc344a7519cbd174d4ac15d4ed59 | [
"MIT"
] | 7 | 2016-05-26T17:31:46.000Z | 2020-11-04T06:39:23.000Z | //===-- llvm-symbolizer.cpp - Simple addr2line-like symbolizer ------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This utility works much like "addr2line". It is able of transforming
// tuples (module name, module offset) to code locations (function name,
// file, line number, column number). It is targeted for compiler-rt tools
// (especially AddressSanitizer and ThreadSanitizer) that can use it
// to symbolize stack traces in their error reports.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/OwningPtr.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/DebugInfo/DIContext.h"
#include "llvm/Object/MachO.h"
#include "llvm/Object/ObjectFile.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/raw_ostream.h"
#include <cstdio>
#include <cstring>
#include <map>
#include <string>
using namespace llvm;
using namespace object;
static cl::opt<bool>
UseSymbolTable("use-symbol-table", cl::init(true),
cl::desc("Prefer names in symbol table to names "
"in debug info"));
static cl::opt<bool>
PrintFunctions("functions", cl::init(true),
cl::desc("Print function names as well as line "
"information for a given address"));
static cl::opt<bool>
PrintInlining("inlining", cl::init(true),
cl::desc("Print all inlined frames for a given address"));
static cl::opt<bool>
Demangle("demangle", cl::init(true),
cl::desc("Demangle function names"));
static StringRef ToolInvocationPath;
static bool error(error_code ec) {
if (!ec) return false;
errs() << ToolInvocationPath << ": error reading file: "
<< ec.message() << ".\n";
return true;
}
static uint32_t getDILineInfoSpecifierFlags() {
uint32_t Flags = llvm::DILineInfoSpecifier::FileLineInfo |
llvm::DILineInfoSpecifier::AbsoluteFilePath;
if (PrintFunctions)
Flags |= llvm::DILineInfoSpecifier::FunctionName;
return Flags;
}
static void patchFunctionNameInDILineInfo(const std::string &NewFunctionName,
DILineInfo &LineInfo) {
std::string FileName = LineInfo.getFileName();
LineInfo = DILineInfo(StringRef(FileName), StringRef(NewFunctionName),
LineInfo.getLine(), LineInfo.getColumn());
}
namespace {
class ModuleInfo {
OwningPtr<ObjectFile> Module;
OwningPtr<DIContext> DebugInfoContext;
public:
ModuleInfo(ObjectFile *Obj, DIContext *DICtx)
: Module(Obj), DebugInfoContext(DICtx) {}
DILineInfo symbolizeCode(uint64_t ModuleOffset) const {
DILineInfo LineInfo;
if (DebugInfoContext) {
LineInfo = DebugInfoContext->getLineInfoForAddress(
ModuleOffset, getDILineInfoSpecifierFlags());
}
// Override function name from symbol table if necessary.
if (PrintFunctions && UseSymbolTable) {
std::string Function;
if (getFunctionNameFromSymbolTable(ModuleOffset, Function)) {
patchFunctionNameInDILineInfo(Function, LineInfo);
}
}
return LineInfo;
}
DIInliningInfo symbolizeInlinedCode(uint64_t ModuleOffset) const {
DIInliningInfo InlinedContext;
if (DebugInfoContext) {
InlinedContext = DebugInfoContext->getInliningInfoForAddress(
ModuleOffset, getDILineInfoSpecifierFlags());
}
// Make sure there is at least one frame in context.
if (InlinedContext.getNumberOfFrames() == 0) {
InlinedContext.addFrame(DILineInfo());
}
// Override the function name in lower frame with name from symbol table.
if (PrintFunctions && UseSymbolTable) {
DIInliningInfo PatchedInlinedContext;
for (uint32_t i = 0, n = InlinedContext.getNumberOfFrames();
i != n; i++) {
DILineInfo LineInfo = InlinedContext.getFrame(i);
if (i == n - 1) {
std::string Function;
if (getFunctionNameFromSymbolTable(ModuleOffset, Function)) {
patchFunctionNameInDILineInfo(Function, LineInfo);
}
}
PatchedInlinedContext.addFrame(LineInfo);
}
InlinedContext = PatchedInlinedContext;
}
return InlinedContext;
}
private:
bool getFunctionNameFromSymbolTable(uint64_t Address,
std::string &FunctionName) const {
assert(Module);
error_code ec;
for (symbol_iterator si = Module->begin_symbols(),
se = Module->end_symbols();
si != se; si.increment(ec)) {
if (error(ec)) return false;
uint64_t SymbolAddress;
uint64_t SymbolSize;
SymbolRef::Type SymbolType;
if (error(si->getAddress(SymbolAddress)) ||
SymbolAddress == UnknownAddressOrSize) continue;
if (error(si->getSize(SymbolSize)) ||
SymbolSize == UnknownAddressOrSize) continue;
if (error(si->getType(SymbolType))) continue;
// FIXME: If a function has alias, there are two entries in symbol table
// with same address size. Make sure we choose the correct one.
if (SymbolAddress <= Address && Address < SymbolAddress + SymbolSize &&
SymbolType == SymbolRef::ST_Function) {
StringRef Name;
if (error(si->getName(Name))) continue;
FunctionName = Name.str();
return true;
}
}
return false;
}
};
typedef std::map<std::string, ModuleInfo*> ModuleMapTy;
typedef ModuleMapTy::iterator ModuleMapIter;
} // namespace
static ModuleMapTy Modules;
static bool isFullNameOfDwarfSection(const StringRef &FullName,
const StringRef &ShortName) {
static const char kDwarfPrefix[] = "__DWARF,";
StringRef Name = FullName;
// Skip "__DWARF," prefix.
if (Name.startswith(kDwarfPrefix))
Name = Name.substr(strlen(kDwarfPrefix));
// Skip . and _ prefixes.
Name = Name.substr(Name.find_first_not_of("._"));
return (Name == ShortName);
}
// Returns true if the object endianness is known.
static bool getObjectEndianness(const ObjectFile *Obj,
bool &IsLittleEndian) {
// FIXME: Implement this when libLLVMObject allows to do it easily.
IsLittleEndian = true;
return true;
}
static void getDebugInfoSections(const ObjectFile *Obj,
StringRef &DebugInfoSection,
StringRef &DebugAbbrevSection,
StringRef &DebugLineSection,
StringRef &DebugArangesSection,
StringRef &DebugStringSection,
StringRef &DebugRangesSection) {
if (Obj == 0)
return;
error_code ec;
for (section_iterator i = Obj->begin_sections(),
e = Obj->end_sections();
i != e; i.increment(ec)) {
if (error(ec)) break;
StringRef Name;
if (error(i->getName(Name))) continue;
StringRef Data;
if (error(i->getContents(Data))) continue;
if (isFullNameOfDwarfSection(Name, "debug_info"))
DebugInfoSection = Data;
else if (isFullNameOfDwarfSection(Name, "debug_abbrev"))
DebugAbbrevSection = Data;
else if (isFullNameOfDwarfSection(Name, "debug_line"))
DebugLineSection = Data;
// Don't use debug_aranges for now, as address ranges contained
// there may not cover all instructions in the module
// else if (isFullNameOfDwarfSection(Name, "debug_aranges"))
// DebugArangesSection = Data;
else if (isFullNameOfDwarfSection(Name, "debug_str"))
DebugStringSection = Data;
else if (isFullNameOfDwarfSection(Name, "debug_ranges"))
DebugRangesSection = Data;
}
}
static ObjectFile *getObjectFile(const std::string &Path) {
OwningPtr<MemoryBuffer> Buff;
MemoryBuffer::getFile(Path, Buff);
return ObjectFile::createObjectFile(Buff.take());
}
static std::string getDarwinDWARFResourceForModule(const std::string &Path) {
StringRef Basename = sys::path::filename(Path);
const std::string &DSymDirectory = Path + ".dSYM";
SmallString<16> ResourceName = StringRef(DSymDirectory);
sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
sys::path::append(ResourceName, Basename);
return ResourceName.str();
}
static ModuleInfo *getOrCreateModuleInfo(const std::string &ModuleName) {
ModuleMapIter I = Modules.find(ModuleName);
if (I != Modules.end())
return I->second;
ObjectFile *Obj = getObjectFile(ModuleName);
if (Obj == 0) {
// Module name doesn't point to a valid object file.
Modules.insert(make_pair(ModuleName, (ModuleInfo*)0));
return 0;
}
DIContext *Context = 0;
bool IsLittleEndian;
if (getObjectEndianness(Obj, IsLittleEndian)) {
StringRef DebugInfo;
StringRef DebugAbbrev;
StringRef DebugLine;
StringRef DebugAranges;
StringRef DebugString;
StringRef DebugRanges;
getDebugInfoSections(Obj, DebugInfo, DebugAbbrev, DebugLine,
DebugAranges, DebugString, DebugRanges);
// On Darwin we may find DWARF in separate object file in
// resource directory.
if (isa<MachOObjectFile>(Obj)) {
const std::string &ResourceName = getDarwinDWARFResourceForModule(
ModuleName);
ObjectFile *ResourceObj = getObjectFile(ResourceName);
if (ResourceObj != 0)
getDebugInfoSections(ResourceObj, DebugInfo, DebugAbbrev, DebugLine,
DebugAranges, DebugString, DebugRanges);
}
Context = DIContext::getDWARFContext(
IsLittleEndian, DebugInfo, DebugAbbrev,
DebugAranges, DebugLine, DebugString,
DebugRanges);
assert(Context);
}
ModuleInfo *Info = new ModuleInfo(Obj, Context);
Modules.insert(make_pair(ModuleName, Info));
return Info;
}
// Assume that __cxa_demangle is provided by libcxxabi.
extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
size_t *length, int *status);
static void printDILineInfo(DILineInfo LineInfo) {
// By default, DILineInfo contains "<invalid>" for function/filename it
// cannot fetch. We replace it to "??" to make our output closer to addr2line.
static const std::string kDILineInfoBadString = "<invalid>";
static const std::string kSymbolizerBadString = "??";
if (PrintFunctions) {
std::string FunctionName = LineInfo.getFunctionName();
if (FunctionName == kDILineInfoBadString)
FunctionName = kSymbolizerBadString;
if (Demangle) {
int status = 0;
char *DemangledName = __cxa_demangle(
FunctionName.c_str(), 0, 0, &status);
if (status == 0) {
FunctionName = DemangledName;
free(DemangledName);
}
}
outs() << FunctionName << "\n";
}
std::string Filename = LineInfo.getFileName();
if (Filename == kDILineInfoBadString)
Filename = kSymbolizerBadString;
outs() << Filename <<
":" << LineInfo.getLine() <<
":" << LineInfo.getColumn() <<
"\n";
}
static void symbolize(std::string ModuleName, std::string ModuleOffsetStr) {
ModuleInfo *Info = getOrCreateModuleInfo(ModuleName);
uint64_t Offset = 0;
if (Info == 0 ||
StringRef(ModuleOffsetStr).getAsInteger(0, Offset)) {
printDILineInfo(DILineInfo());
} else if (PrintInlining) {
DIInliningInfo InlinedContext = Info->symbolizeInlinedCode(Offset);
uint32_t FramesNum = InlinedContext.getNumberOfFrames();
assert(FramesNum > 0);
for (uint32_t i = 0; i < FramesNum; i++) {
DILineInfo LineInfo = InlinedContext.getFrame(i);
printDILineInfo(LineInfo);
}
} else {
DILineInfo LineInfo = Info->symbolizeCode(Offset);
printDILineInfo(LineInfo);
}
outs() << "\n"; // Print extra empty line to mark the end of output.
outs().flush();
}
static bool parseModuleNameAndOffset(std::string &ModuleName,
std::string &ModuleOffsetStr) {
static const int kMaxInputStringLength = 1024;
static const char kDelimiters[] = " \n";
char InputString[kMaxInputStringLength];
if (!fgets(InputString, sizeof(InputString), stdin))
return false;
ModuleName = "";
ModuleOffsetStr = "";
// FIXME: Handle case when filename is given in quotes.
if (char *FilePath = strtok(InputString, kDelimiters)) {
ModuleName = FilePath;
if (char *OffsetStr = strtok((char*)0, kDelimiters))
ModuleOffsetStr = OffsetStr;
}
return true;
}
int main(int argc, char **argv) {
// Print stack trace if we signal out.
sys::PrintStackTraceOnErrorSignal();
PrettyStackTraceProgram X(argc, argv);
llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
cl::ParseCommandLineOptions(argc, argv, "llvm symbolizer for compiler-rt\n");
ToolInvocationPath = argv[0];
std::string ModuleName;
std::string ModuleOffsetStr;
while (parseModuleNameAndOffset(ModuleName, ModuleOffsetStr)) {
symbolize(ModuleName, ModuleOffsetStr);
}
return 0;
}
| 35.347368 | 80 | 0.656715 | [
"object"
] |
79cd4030d167d5e5a7466f5beb047cdd81d1f8ef | 635 | cpp | C++ | src/Editor/CLI/NewAssetCommand.cpp | lriki/Lumino | 1a80430f4a83dbdfbe965b3d5b16064991b3edb0 | [
"MIT"
] | 30 | 2016-01-24T05:35:45.000Z | 2020-03-03T09:54:27.000Z | src/Editor/CLI/NewAssetCommand.cpp | lriki/Lumino | 1a80430f4a83dbdfbe965b3d5b16064991b3edb0 | [
"MIT"
] | 35 | 2016-04-18T06:14:08.000Z | 2020-02-09T15:51:58.000Z | src/Editor/CLI/NewAssetCommand.cpp | lriki/Lumino | 1a80430f4a83dbdfbe965b3d5b16064991b3edb0 | [
"MIT"
] | 5 | 2016-04-03T02:52:05.000Z | 2018-01-02T16:53:06.000Z |
#include <Project/Project.hpp>
#include "NewAssetCommand.hpp"
#include "../../../lumino/LuminoEngine/src/Engine/EngineDomain.hpp"
#include <LuminoEngine/Asset/detail/AssetManager.hpp>
int NewAssetCommand::execute(lna::Workspace* workspace, ln::String name)
{
ln::Ref<ln::Object> obj = ln::TypeInfo::createInstance(name);
if (!obj) {
CLI::error(_TT("Invalid type name."));
return 1;
}
if (filePath.isEmpty()) {
filePath = name;
}
auto model = ln::makeObject<ln::AssetModel>(obj);
ln::detail::AssetManager::instance()->saveAssetModelToLocalFile(model, filePath);
return 0;
}
| 26.458333 | 85 | 0.662992 | [
"object",
"model"
] |
79d141146233475a92ff60de0856b049803e0104 | 2,184 | cpp | C++ | sDNA/geos/drop/src/index/strtree/ItemBoundable.cpp | chrisc20042001/sDNA | 22d11f150c28574c339457ce5cb0ad1d59b06277 | [
"MIT"
] | 48 | 2015-01-02T23:10:03.000Z | 2021-12-23T01:37:22.000Z | sDNA/geos/drop/src/index/strtree/ItemBoundable.cpp | chrisc20042001/sDNA | 22d11f150c28574c339457ce5cb0ad1d59b06277 | [
"MIT"
] | 9 | 2019-05-31T14:19:43.000Z | 2021-10-16T16:09:52.000Z | sDNA/geos/drop/src/index/strtree/ItemBoundable.cpp | chrisc20042001/sDNA | 22d11f150c28574c339457ce5cb0ad1d59b06277 | [
"MIT"
] | 28 | 2015-01-07T18:41:16.000Z | 2021-03-25T02:29:13.000Z | /**********************************************************************
* $Id: ItemBoundable.cpp 2194 2008-09-23 23:01:00Z mloskot $
*
* GEOS - Geometry Engine Open Source
* http://geos.refractions.net
*
* Copyright (C) 2006 Refractions Research Inc.
* Copyright (C) 2001-2002 Vivid Solutions Inc.
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Public Licence as published
* by the Free Software Foundation.
* See the COPYING file for more information.
*
**********************************************************************/
#include <geos/index/strtree/ItemBoundable.h>
namespace geos {
namespace index { // geos.index
namespace strtree { // geos.index.strtree
ItemBoundable::ItemBoundable(const void* newBounds, void* newItem) :
bounds(newBounds), item(newItem)
{
}
ItemBoundable::~ItemBoundable()
{
}
const void*
ItemBoundable::getBounds() const {
return bounds;
}
void* ItemBoundable::getItem() const {
return item;
}
} // namespace geos.index.strtree
} // namespace geos.index
} // namespace geos
/**********************************************************************
* $Log$
* Revision 1.9 2006/03/21 10:47:34 strk
* indexStrtree.h split
*
* Revision 1.8 2006/02/20 10:14:18 strk
* - namespaces geos::index::*
* - Doxygen documentation cleanup
*
* Revision 1.7 2004/07/27 16:35:46 strk
* Geometry::getEnvelopeInternal() changed to return a const Envelope *.
* This should reduce object copies as once computed the envelope of a
* geometry remains the same.
*
* Revision 1.6 2004/07/02 13:28:27 strk
* Fixed all #include lines to reflect headers layout change.
* Added client application build tips in README.
*
* Revision 1.5 2004/05/06 15:00:59 strk
* Boundable destructor made virtual.
* Added vector <AbstractNode *> *nodes member in AbstractSTRTree,
* used to keep track of created node to cleanly delete them at
* destruction time.
*
* Revision 1.4 2003/11/07 01:23:42 pramsey
* Add standard CVS headers licence notices and copyrights to all cpp and h
* files.
*
*
**********************************************************************/
| 28.736842 | 75 | 0.621795 | [
"geometry",
"object",
"vector"
] |
79d2a7d388b8213aa9f1dcdbb1a132ce77acb69e | 2,939 | cc | C++ | example/storage.cc | TOT0RoKR/libmemcached | dd6800972b93897c4e7ba192976b888c3621b3cb | [
"BSD-3-Clause"
] | 57 | 2016-02-24T18:17:29.000Z | 2022-01-30T15:27:27.000Z | example/storage.cc | TOT0RoKR/libmemcached | dd6800972b93897c4e7ba192976b888c3621b3cb | [
"BSD-3-Clause"
] | 108 | 2020-01-20T09:25:47.000Z | 2021-05-18T06:45:30.000Z | example/storage.cc | TOT0RoKR/libmemcached | dd6800972b93897c4e7ba192976b888c3621b3cb | [
"BSD-3-Clause"
] | 29 | 2016-02-26T01:34:20.000Z | 2021-11-29T18:44:39.000Z | /* -*- Mode: C; tab-width: 2; c-basic-offset: 2; indent-tabs-mode: nil -*- */
#include "mem_config.h"
#include <stdlib.h>
#include <inttypes.h>
#include <time.h>
#include <stdbool.h>
#include <string.h>
#include "storage.h"
struct list_entry {
struct item item;
struct list_entry *next;
struct list_entry *prev;
};
static struct list_entry *root;
static uint64_t cas;
bool initialize_storage(void)
{
return true;
}
void shutdown_storage(void)
{
/* Do nothing */
}
void put_item(struct item* item)
{
struct list_entry* entry= (struct list_entry*)item;
update_cas(item);
if (root == NULL)
{
entry->next= entry->prev= entry;
}
else
{
entry->prev= root->prev;
entry->next= root;
entry->prev->next= entry;
entry->next->prev= entry;
}
root= entry;
}
struct item* get_item(const void* key, size_t nkey)
{
struct list_entry *walker= root;
if (root == NULL)
{
return NULL;
}
do
{
if (((struct item*)walker)->nkey == nkey &&
memcmp(((struct item*)walker)->key, key, nkey) == 0)
{
return (struct item*)walker;
}
walker= walker->next;
} while (walker != root);
return NULL;
}
struct item* create_item(const void* key, size_t nkey, const void* data,
size_t size, uint32_t flags, time_t exp)
{
struct item* ret= (struct item*)calloc(1, sizeof(struct list_entry));
if (ret != NULL)
{
ret->key= malloc(nkey);
if (size > 0)
{
ret->data= malloc(size);
}
if (ret->key == NULL || (size > 0 && ret->data == NULL))
{
free(ret->key);
free(ret->data);
free(ret);
return NULL;
}
memcpy(ret->key, key, nkey);
if (data != NULL)
{
memcpy(ret->data, data, size);
}
ret->nkey= nkey;
ret->size= size;
ret->flags= flags;
ret->exp= exp;
}
return ret;
}
bool delete_item(const void* key, size_t nkey)
{
struct item* item= get_item(key, nkey);
bool ret= false;
if (item)
{
/* remove from linked list */
struct list_entry *entry= (struct list_entry*)item;
if (entry->next == entry)
{
/* Only one object in the list */
root= NULL;
}
else
{
/* ensure that we don't loose track of the root, and this will
* change the start position for the next search ;-) */
root= entry->next;
entry->prev->next= entry->next;
entry->next->prev= entry->prev;
}
free(item->key);
free(item->data);
free(item);
ret= true;
}
return ret;
}
void flush(uint32_t /* when */)
{
/* remove the complete linked list */
if (root == NULL)
{
return;
}
root->prev->next= NULL;
while (root != NULL)
{
struct item* tmp= (struct item*)root;
root= root->next;
free(tmp->key);
free(tmp->data);
free(tmp);
}
}
void update_cas(struct item* item)
{
item->cas= ++cas;
}
void release_item(struct item* /* item */)
{
}
| 17.390533 | 77 | 0.579109 | [
"object"
] |
79d3062ac9c495f0b8bd66fff808d0a36f220880 | 740 | cpp | C++ | Contests/_Archived/Old-Lab/nk24-E.cpp | DCTewi/My-Codes | 9904f8057ec96e21cbc8cf9c62a49658a0f6d392 | [
"MIT"
] | null | null | null | Contests/_Archived/Old-Lab/nk24-E.cpp | DCTewi/My-Codes | 9904f8057ec96e21cbc8cf9c62a49658a0f6d392 | [
"MIT"
] | null | null | null | Contests/_Archived/Old-Lab/nk24-E.cpp | DCTewi/My-Codes | 9904f8057ec96e21cbc8cf9c62a49658a0f6d392 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int n, m;
map<int, vector<int> > edges;
int l = 300, r = 0;
int vis[300];
queue<int> q;
void dfs(int x, int step)
{
if (x == m)
{
printf("%d\n", step);
}
else if (edges[x].size() == 0)
{
vis[x] = 1;
dfs(x + 1, step + 1);
vis[x] = 0;
}
else
{
for (int i = 0; i < edges[x].size(); i++)
{
if (!vis[edges[x][i]])
{
vis[edges[x][i]] = 1;
dfs(edges[x][i], step + 1);
}
}
}
}
int main(int argc, char const *argv[])
{
scanf("%d%d", &m, &n);
for (int i = 0; i < n; i++)
{
int a, b; scanf("%d%d", &a, &b);
if (a > r) r = a;
if (a < l) l = a;
if (b > r) r = b;
if (b < l) l = b;
edges[a].push_back(b);
}
vis[0] = 1;
dfs(0, 0);
return 0;
} | 13.703704 | 43 | 0.454054 | [
"vector"
] |
79d4e0735ad186b6d1b08716668f6541e62a907d | 5,527 | cpp | C++ | tests/cpp/wordLadder/wordLadder.II.cpp | zlc18/LocalJudge | e8b141d2e80087d447a45cce36bac27b4ddb9cd1 | [
"MIT"
] | null | null | null | tests/cpp/wordLadder/wordLadder.II.cpp | zlc18/LocalJudge | e8b141d2e80087d447a45cce36bac27b4ddb9cd1 | [
"MIT"
] | null | null | null | tests/cpp/wordLadder/wordLadder.II.cpp | zlc18/LocalJudge | e8b141d2e80087d447a45cce36bac27b4ddb9cd1 | [
"MIT"
] | null | null | null | // Source : https://oj.leetcode.com/problems/word-ladder-ii/
// Author : Hao Chen
// Date : 2014-10-13
/**********************************************************************************
*
* Given two words (start and end), and a dictionary, find all shortest transformation
* sequence(s) from start to end, such that:
*
* Only one letter can be changed at a time
* Each intermediate word must exist in the dictionary
*
* For example,
*
* Given:
* start = "hit"
* end = "cog"
* dict = ["hot","dot","dog","lot","log"]
*
* Return
*
* [
* ["hit","hot","dot","dog","cog"],
* ["hit","hot","lot","log","cog"]
* ]
*
* Note:
*
* All words have the same length.
* All words contain only lowercase alphabetic characters.
*
*
**********************************************************************************/
#include <iostream>
#include <vector>
#include <map>
#include <queue>
#include <unordered_set>
using namespace std;
// Solution
//
// 1) Using BSF algorithm build a tree like below
// 2) Using DSF to parse the tree to the transformation path.
//
// For example:
//
// start = "hit"
// end = "cog"
// dict = ["hot","dot","dog","lot","log","dit","hig", "dig"]
//
// +-----+
// +-------------+ hit +--------------+
// | +--+--+ |
// | | |
// +--v--+ +--v--+ +--v--+
// | dit | +-----+ hot +---+ | hig |
// +--+--+ | +-----+ | +--+--+
// | | | |
// | +--v--+ +--v--+ +--v--+
// +----> dot | | lot | | dig |
// +--+--+ +--+--+ +--+--+
// | | |
// +--v--+ +--v--+ |
// +----> dog | | log | |
// | +--+--+ +--+--+ |
// | | | |
// | | +--v--+ | |
// | +--->| cog |<-- + |
// | +-----+ |
// | |
// | |
// +----------------------------------+
map< string, unordered_set<string> >&
buildTree(string& start, string& end, unordered_set<string> &dict) {
static map< string, unordered_set<string> > parents;
parents.clear();
unordered_set<string> level[3];
unordered_set<string> *previousLevel = &level[0];
unordered_set<string> *currentLevel = &level[1];
unordered_set<string> *newLevel = &level[2];
unordered_set<string> *p =NULL;
currentLevel->insert(start);
bool reachEnd = false;
while( !reachEnd ) {
newLevel->clear();
for(auto it=currentLevel->begin(); it!=currentLevel->end(); it++) {
for (int i=0; i<it->size(); i++) {
string newWord = *it;
for(char c='a'; c<='z'; c++){
newWord[i] = c;
if (newWord == end){
reachEnd = true;
parents[*it].insert(end);
continue;
}
if ( dict.count(newWord)==0 || currentLevel->count(newWord)>0 || previousLevel->count(newWord)>0 ) {
continue;
}
newLevel->insert(newWord);
//parents[newWord].insert(*it);
parents[*it].insert(newWord);
}
}
}
if (newLevel->empty()) break;
p = previousLevel;
previousLevel = currentLevel;
currentLevel = newLevel;
newLevel = p;
}
if ( !reachEnd ) {
parents.clear();
}
return parents;
}
void generatePath( string start, string end,
map< string, unordered_set<string> > &parents,
vector<string> path,
vector< vector<string> > &paths) {
if (parents.find(start) == parents.end()){
if (start == end){
paths.push_back(path);
}
return;
}
for(auto it=parents[start].begin(); it!=parents[start].end(); it++){
path.push_back(*it);
generatePath(*it, end, parents, path, paths);
path.pop_back();
}
}
vector< vector<string> >
findLadders(string start, string end, unordered_set<string> &dict) {
vector< vector<string> > ladders;
vector<string> ladder;
ladder.push_back(start);
if (start == end){
ladder.push_back(end);
ladders.push_back(ladder);
return ladders;
}
map< string, unordered_set<string> >& parents = buildTree(start, end, dict);
if (parents.size()<=0) {
return ladders;
}
generatePath(start, end, parents, ladder, ladders);
return ladders;
}
void printLadders(vector< vector<string> > &ladders){
int i, j;
for (i=0; i<ladders.size(); i++){
for (j=0; j<ladders[i].size()-1; j++){
cout << ladders[i][j] << " -> ";
}
cout << ladders[i][j] << endl;
}
}
int main(int argc, char** argv)
{
string start = "hit";
string end = "cog";
//unordered_set<string> dict ({"hot","dot","dog","lot","log"});
unordered_set<string> dict ({"bot","cig", "cog", "dit", "dut", "hot", "hit" ,"dot","dog","lot","log"});
vector< vector<string> > ladders;
ladders = findLadders(start, end, dict);
printLadders(ladders);
return 0;
}
| 28.786458 | 120 | 0.432423 | [
"vector"
] |
79d6db20110fed1682192ac45a1eb81d893698f9 | 514 | tpp | C++ | examples/lapack_mkl_program/src/cgt.tpp | tjgiese/atizer | b8cdb8f4bac7cedfb566d766acee5fe0cc7a7bd3 | [
"MIT"
] | null | null | null | examples/lapack_mkl_program/src/cgt.tpp | tjgiese/atizer | b8cdb8f4bac7cedfb566d766acee5fe0cc7a7bd3 | [
"MIT"
] | null | null | null | examples/lapack_mkl_program/src/cgt.tpp | tjgiese/atizer | b8cdb8f4bac7cedfb566d766acee5fe0cc7a7bd3 | [
"MIT"
] | null | null | null | inline lalg::cgt::cgt( int const m, int const n, double const * d )
: nfast(m),nslow(n),data(d){}
inline lalg::cgt::cgt( int const m, int const n, std::vector<double> const & d )
: nfast(m),nslow(n),data(d.data()) { assert(static_cast<std::size_t>(m*n) == d.size()); }
inline lalg::cgt::cgt( lalg::gt const & a )
: nfast(a.nfast),nslow(a.nslow),data(a.data){}
inline double const * lalg::cgt::begin() const { return data; }
inline double const * lalg::cgt::end() const { return data+nfast*nslow; }
| 39.538462 | 91 | 0.636187 | [
"vector"
] |
79d81c863559c3bb8bd5a22d34cbf31e1f0a8965 | 1,702 | cpp | C++ | Source/mapping/MultichannelMap.cpp | kant/everytone-tuner | 8eb7bf312d097e7a378afeace3733b3c83e9ba07 | [
"Unlicense"
] | 11 | 2022-01-02T22:05:45.000Z | 2022-03-28T08:50:25.000Z | Source/mapping/MultichannelMap.cpp | kant/everytone-tuner | 8eb7bf312d097e7a378afeace3733b3c83e9ba07 | [
"Unlicense"
] | 5 | 2022-01-02T20:50:48.000Z | 2022-03-29T18:12:04.000Z | Source/mapping/MultichannelMap.cpp | kant/everytone-tuner | 8eb7bf312d097e7a378afeace3733b3c83e9ba07 | [
"Unlicense"
] | 1 | 2022-01-07T02:17:01.000Z | 2022-01-07T02:17:01.000Z | /*
==============================================================================
Map.cpp
Created: 7 Nov 2021 10:53:27am
Author: Vincenzo Sicurella
==============================================================================
*/
#include "MultichannelMap.h"
MultichannelMap::MultichannelMap(MultichannelMap::Definition definition)
: TuningTableMap(DefineTuningTableMap(definition)),
maps(definition.maps) {}
MultichannelMap::MultichannelMap(const MultichannelMap& mapToCopy)
: maps(mapToCopy.maps),
TuningTableMap(DefineTuningTableMap(mapToCopy.getDefinition())) {}
MultichannelMap::~MultichannelMap() {}
Map<int> MultichannelMap::buildMultimap(MultichannelMap::Definition definition)
{
// Create multimap from maps
std::vector<int> multipattern;
for (int m = 0; m < definition.maps.size(); m++)
{
auto channelOffset = m * 128;
auto map = &(definition.maps[m]);
for (int i = 0; i < 128; i++)
{
auto index = channelOffset + i;
multipattern.push_back(map->at(i));
}
}
// Probably should be reworked
int period = definition.maps.at(definition.root.midiChannel - 1).base();
Map<int>::Definition d =
{
2048, /* mapSize */
multipattern, /* pattern */
period, /* base */
0, /* pattern root */
0, /* map root*/
};
return Map<int>(d);
}
MultichannelMap::Definition MultichannelMap::getDefinition() const
{
MultichannelMap::Definition definition =
{
TuningTableMap::Root { rootMidiChannel, rootMidiNote },
maps,
};
return definition;
} | 27.451613 | 80 | 0.552291 | [
"vector"
] |
0766a06a42520e84f1f53f1fba1b7640811d1f87 | 9,865 | cpp | C++ | src/ConnectionTable.cpp | cpearce/HARM | 1e629099bbaa0203b19fe9007a71d9ab9c938be0 | [
"Apache-2.0"
] | 1 | 2016-10-11T18:37:52.000Z | 2016-10-11T18:37:52.000Z | src/ConnectionTable.cpp | wsgan001/HARM | 1e629099bbaa0203b19fe9007a71d9ab9c938be0 | [
"Apache-2.0"
] | 2 | 2017-03-27T22:58:45.000Z | 2017-03-28T04:46:52.000Z | src/ConnectionTable.cpp | wsgan001/HARM | 1e629099bbaa0203b19fe9007a71d9ab9c938be0 | [
"Apache-2.0"
] | 4 | 2016-04-19T06:15:01.000Z | 2020-01-02T11:11:57.000Z | // Copyright 2014, Chris Pearce & Yun Sing Koh
//
// 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 <queue>
#include "FPNode.h"
#include "FPTree.h"
#include "ConnectionTable.h"
#include "ItemMap.h"
#include "Item.h"
using namespace std;
Child::Child(): weight(1), count(0) {
}
Child::Child(ItemList& _itemList, unsigned _count): weight(1), count(_count), nextItems(_itemList) {
}
ConnectionTable::ConnectionTable(): root(NULL), decay(0.99) {
}
ConnectionTable::ConnectionTable(FPNode* root, ConnectionTable* prevConnTable): decay(0.99) {
createTable(root);
// update weights if there is a previous table.
if (prevConnTable) {
updateWeights(*prevConnTable);
}
}
void ConnectionTable::createTable(FPNode* root) {
queue<FPNode*> q;
FPNode* node;
// traverse the tree and create connection table.
q.push(root);
while (!q.empty()) {
node = q.front();
// if this item does not exist in the connection table, add it as
// a new item otherwise, just add new children if there is any.
if (!cl.Contains(node->item)) {
addNewNode(node);
} else if (node->children.size() > 0) {
// Note: this copies! Maybe ConnectionList should map to pointers
// to child lists!!
ChildList childList(cl.Get(node->item));
addToChildren(childList, node);
}
addChildrenToQueue(node, q);
q.pop();
}
// print();
}
void ConnectionTable::addNewNode(FPNode* node) {
ChildList children;
ItemList nextItems;
children.Clear();
// go through the node's chilren and add them to an item map. For every children, add its children to an
// nextItems.
for (std::map<Item, FPNode*>::iterator childIter = node->children.begin(); childIter != node->children.end(); childIter++) {
nextItems.Clear();
for (std::map<Item, FPNode*>::iterator nextIter = childIter->second->children.begin(); nextIter != childIter->second->children.end(); nextIter++) {
nextItems += nextIter->first;
}
children.Set(childIter->first, Child(nextItems, childIter->second->count));
}
// we cant put an item with ID 0 in ItemMap, so we do not keep the root in the connection list.
// root does not represent any transaction, so not keeping it in the connection list should not
// cause any problem.
if (node->item.IsNull()) {
root = node;
rootChildren = children;
} else {
cl.Set(node->item, children);
}
}
void ConnectionTable::addChildrenToQueue(FPNode* node, queue<FPNode*>& q) {
for (std::map<Item, FPNode*>::iterator childIter = node->children.begin(); childIter != node->children.end(); childIter++) {
q.push(childIter->second);
}
}
void ConnectionTable::addToChildren(ChildList& children, FPNode* node) {
ItemList nextItems;
// loop through the node's children and add them new children to the list of there is any.
for (std::map<Item, FPNode*>::iterator childIter = node->children.begin(); childIter != node->children.end(); childIter++) {
nextItems.Clear();
if (children.Contains(childIter->first)) {
nextItems = children.Get(childIter->first).nextItems;
}
for (std::map<Item, FPNode*>::iterator nextIter = childIter->second->children.begin(); nextIter != childIter->second->children.end(); nextIter++) {
nextItems += nextIter->first;
}
children.Set(childIter->first, Child(nextItems, childIter->second->count));
}
cl.Set(node->item, children);
}
void ConnectionTable::updateWeights(ConnectionTable& prevConnTable) {
ConnectionList::Iterator nodeIterator = cl.GetIterator();
// update weight field for each child in the table. Every connection in the table is assigned a weight.
// When a new checkpoint is created, the weight of each connection is calculated based on the weight of
// the same connection in the previous checkpoint. If the connection does not exist in the previous table,
// then it is a new connection and gets the highest weight, which is 1. If it exists in the previous
// table but no transaction since then contains such connection, then the weight is reduced by getting
// multiplied by a decay value, which is 0.99. If it exists in the previous one but there is a transaction
// which contains such connection since creating previous table, the weight resets to 1. In fact, the weight
// shows the age of the connection in the table.
while (nodeIterator.HasNext()) {
Item item = nodeIterator.GetKey();
if (prevConnTable.cl.Contains(item)) {
ChildList prevChildren = prevConnTable.cl.Get(item);
ChildList children = nodeIterator.GetValue();
ChildList::Iterator childrenIterator = children.GetIterator();
while (childrenIterator.HasNext()) {
Child child = childrenIterator.GetValue();
Item childItem = childrenIterator.GetKey();
if (prevChildren.Contains(childItem)) {
Child prevChild = prevChildren.Get(childItem);
if (child.count == prevChild.count) {
child.weight = prevChild.weight * decay;
} else if (child.count > prevChild.count) {
child.weight = 1;
} else {
// if the count is smaller, it means that a purge has happened. We dont know
// if a new instance of this connection has been observed or not, so we keep
// the weight for this the same as the previous table.
child.weight = prevChild.weight;
}
children.Set(childItem, child);
}
childrenIterator.Next();
}
cl.Set(item, children);
}
nodeIterator.Next();
}
}
// a -> b
bool ConnectionTable::connectionExist(Item& a, Item& b, const ItemMap<unsigned>* freqTable) const {
bool connected = false;
// make sure a and b exist in this connection table.
if (!freqTable->Contains(a) || !freqTable->Contains(b)) {
return connected;
}
// a->c->d...->b is an indirect connection between a and b (a->b) if the frequency of c, d, ..., b are equal.
connected = isConnected(a, b, freqTable);
if (!connected && (freqTable->Get(a) == freqTable->Get(b))) {
// b->c->d...->a is an indirect connection between a and b (a->b) if the frequency of b, c, d, ..., a are equal.
connected = isConnected(b, a, freqTable);
}
return connected;
}
bool ConnectionTable::isConnected(Item& a, Item& b, const ItemMap<unsigned>* freqTable) const {
queue<Item> q;
Item item;
unsigned bFreq;
static ItemSet visited;
visited.Clear();
bFreq = freqTable->Get(b);
// start from a and search the connection table for direct or indirect connections between
// a and b. a->c->d...->b is an indirect connection between a and b (a->b) if the frequency
// of c, d, ..., b are equal.
item = a;
do {
visited += item;
if (cl.Contains(item)) {
const ChildList& children = cl.GetRef(item);
ChildList::Iterator childrenIterator = children.GetIterator();
while (childrenIterator.HasNext()) {
Item child = childrenIterator.GetKey();
if (child == b) {
return true;
}
// if frequency of this child is equal to b's frequency, push it to the queue
// for further investigation, if it hasn't visited before.
if ((freqTable->Get(child) == bFreq) && !visited.Contains(child)) {
q.push(child);
}
childrenIterator.Next();
}
}
if (!q.empty()) {
item = q.front();
q.pop();
} else {
break;
}
} while (1);
return false;
}
void ConnectionTable::purge(double purgeThreshold) {
unsigned n = 0;
ConnectionList::Iterator nodeIterator = cl.GetIterator();
// search for children with a weight less than purgeThreshold and
// remove them.
while (nodeIterator.HasNext()) {
Item item = nodeIterator.GetKey();
ChildList children = nodeIterator.GetValue();
ChildList::Iterator childrenIterator = children.GetIterator();
while (childrenIterator.HasNext()) {
Item childItem = childrenIterator.GetKey();
if (childrenIterator.GetValue().weight <= purgeThreshold) {
children.Erase(childItem);
n++;
}
childrenIterator.Next();
}
cl.Set(item, children);
nodeIterator.Next();
}
Log("%u items were removed from connection table.\n", n);
// print();
}
void ConnectionTable::printChildren(ChildList children) {
ChildList::Iterator childrenIterator = children.GetIterator();
while (childrenIterator.HasNext()) {
Item item = childrenIterator.GetKey();
vector<Item> nextItems = childrenIterator.GetValue().nextItems.AsVector();
Log("%d[%5.3f]:(", item.GetId(), childrenIterator.GetValue().weight);
for (size_t i = 0; i < nextItems.size(); i++) {
Log("%d", nextItems[i].GetId());
if (i + 1 < nextItems.size()) {
Log(", ");
}
}
childrenIterator.Next();
Log(")");
if (childrenIterator.HasNext()) {
Log(", ");
}
}
Log("\n");
}
void ConnectionTable::print() {
Log("Connection Table:\n");
if (!root) {
Log("Connection table is empty!\n");
return;
}
Log("[root(%d)] - ", root->item.GetId());
printChildren(rootChildren);
ConnectionList::Iterator nodeIterator2 = cl.GetIterator();
while (nodeIterator2.HasNext()) {
Item item = nodeIterator2.GetKey();
Log("[%d] - ", item.GetId());
printChildren(nodeIterator2.GetValue());
nodeIterator2.Next();
}
}
| 34.372822 | 151 | 0.660821 | [
"vector"
] |
076adab627becf23e7465de9bb3c9243cbcae8cc | 13,466 | cpp | C++ | src/SourceTerms/User_Template/CPU_Src_User_Template.cpp | YiGuangLee/gamer | c4fc8b0c021bf81a081bff0a53365c8a1d118580 | [
"BSD-3-Clause"
] | 55 | 2017-12-20T09:12:45.000Z | 2022-03-01T03:21:58.000Z | src/SourceTerms/User_Template/CPU_Src_User_Template.cpp | YiGuangLee/gamer | c4fc8b0c021bf81a081bff0a53365c8a1d118580 | [
"BSD-3-Clause"
] | 77 | 2018-01-12T14:22:58.000Z | 2022-03-20T08:28:36.000Z | src/SourceTerms/User_Template/CPU_Src_User_Template.cpp | JeiwHuang/gamer | b392f0058cd7ec7ec9123cf96ebab5f5e9489b46 | [
"BSD-3-Clause"
] | 41 | 2017-11-28T20:06:06.000Z | 2021-11-07T10:55:51.000Z | #include "CUFLU.h"
// external functions and GPU-related set-up
#ifdef __CUDACC__
#include "CUAPI.h"
#include "CUFLU_Shared_FluUtility.cu"
#include "CUDA_ConstMemory.h"
#endif // #ifdef __CUDACC__
// local function prototypes
#ifndef __CUDACC__
void Src_SetAuxArray_User_Template( double [], int [] );
void Src_SetConstMemory_User_Template( const double AuxArray_Flt[], const int AuxArray_Int[],
double *&DevPtr_Flt, int *&DevPtr_Int );
void Src_SetFunc_User_Template( SrcFunc_t & );
void Src_WorkBeforeMajorFunc_User_Template( const int lv, const double TimeNew, const double TimeOld, const double dt,
double AuxArray_Flt[], int AuxArray_Int[] );
void Src_End_User_Template();
#endif
/********************************************************
1. Template of a user-defined source term
--> Enabled by the runtime option "SRC_USER"
2. This file is shared by both CPU and GPU
CUSRC_Src_User_Template.cu -> CPU_Src_User_Template.cpp
3. Four steps are required to implement a source term
I. Set auxiliary arrays
II. Implement the source-term function
III. [Optional] Add the work to be done every time
before calling the major source-term function
IV. Set initialization functions
4. The source-term function must be thread-safe and
not use any global variable
********************************************************/
// =======================
// I. Set auxiliary arrays
// =======================
//-------------------------------------------------------------------------------------------------------
// Function : Src_SetAuxArray_User_Template
// Description : Set the auxiliary arrays AuxArray_Flt/Int[]
//
// Note : 1. Invoked by Src_Init_User_Template()
// 2. AuxArray_Flt/Int[] have the size of SRC_NAUX_USER defined in Macro.h (default = 10)
// 3. Add "#ifndef __CUDACC__" since this routine is only useful on CPU
//
// Parameter : AuxArray_Flt/Int : Floating-point/Integer arrays to be filled up
//
// Return : AuxArray_Flt/Int[]
//-------------------------------------------------------------------------------------------------------
#ifndef __CUDACC__
void Src_SetAuxArray_User_Template( double AuxArray_Flt[], int AuxArray_Int[] )
{
/*
AuxArray_Flt[0] = ...;
AuxArray_Flt[1] = ...;
AuxArray_Int[0] = ...;
AuxArray_Int[1] = ...;
*/
} // FUNCTION : Src_SetAuxArray_User_Template
#endif // #ifndef __CUDACC__
// ======================================
// II. Implement the source-term function
// ======================================
//-------------------------------------------------------------------------------------------------------
// Function : Src_User_Template
// Description : Major source-term function
//
// Note : 1. Invoked by CPU/GPU_SrcSolver_IterateAllCells()
// 2. See Src_SetAuxArray_User_Template() for the values stored in AuxArray_Flt/Int[]
// 3. Shared by both CPU and GPU
//
// Parameter : fluid : Fluid array storing both the input and updated values
// --> Including both active and passive variables
// B : Cell-centered magnetic field
// SrcTerms : Structure storing all source-term variables
// dt : Time interval to advance solution
// dh : Grid size
// x/y/z : Target physical coordinates
// TimeNew : Target physical time to reach
// TimeOld : Physical time before update
// --> This function updates physical time from TimeOld to TimeNew
// MinDens/Pres/Eint : Density, pressure, and internal energy floors
// EoS : EoS object
// AuxArray_* : Auxiliary arrays (see the Note above)
//
// Return : fluid[]
//-----------------------------------------------------------------------------------------
GPU_DEVICE_NOINLINE
static void Src_User_Template( real fluid[], const real B[],
const SrcTerms_t *SrcTerms, const real dt, const real dh,
const double x, const double y, const double z,
const double TimeNew, const double TimeOld,
const real MinDens, const real MinPres, const real MinEint,
const EoS_t *EoS, const double AuxArray_Flt[], const int AuxArray_Int[] )
{
// check
# ifdef GAMER_DEBUG
if ( AuxArray_Flt == NULL ) printf( "ERROR : AuxArray_Flt == NULL in %s !!\n", __FUNCTION__ );
if ( AuxArray_Int == NULL ) printf( "ERROR : AuxArray_Int == NULL in %s !!\n", __FUNCTION__ );
# endif
// example
/*
const bool CheckMinEint_Yes = true;
const real CoolingRate = (real)AuxArray_Flt[0];
real Eint, Enth, Emag;
# ifdef MHD
Emag = (real)0.5*( SQR(B[MAGX]) + SQR(B[MAGY]) + SQR(B[MAGZ]) );
# else
Emag = (real)0.0;
# endif
Eint = Hydro_Con2Eint( fluid[DENS], fluid[MOMX], fluid[MOMY], fluid[MOMZ], fluid[ENGY],
CheckMinEint_Yes, MinEint, Emag );
Enth = fluid[ENGY] - Eint;
Eint -= fluid[DENS]*CoolingRate*dt;
fluid[ENGY] = Enth + Eint;
*/
} // FUNCTION : Src_User_Template
// ==================================================
// III. [Optional] Add the work to be done every time
// before calling the major source-term function
// ==================================================
//-------------------------------------------------------------------------------------------------------
// Function : Src_WorkBeforeMajorFunc_User_Template
// Description : Specify work to be done every time before calling the major source-term function
//
// Note : 1. Invoked by Src_WorkBeforeMajorFunc()
// --> By linking to "Src_WorkBeforeMajorFunc_User_Ptr" in Src_Init_User_Template()
// 2. Add "#ifndef __CUDACC__" since this routine is only useful on CPU
//
// Parameter : lv : Target refinement level
// TimeNew : Target physical time to reach
// TimeOld : Physical time before update
// --> The major source-term function will update the system from TimeOld to TimeNew
// dt : Time interval to advance solution
// --> Physical coordinates : TimeNew - TimeOld == dt
// Comoving coordinates : TimeNew - TimeOld == delta(scale factor) != dt
// AuxArray_Flt/Int : Auxiliary arrays
// --> Can be used and/or modified here
// --> Must call Src_SetConstMemory_User_Template() after modification
//
// Return : AuxArray_Flt/Int[]
//-------------------------------------------------------------------------------------------------------
#ifndef __CUDACC__
void Src_WorkBeforeMajorFunc_User_Template( const int lv, const double TimeNew, const double TimeOld, const double dt,
double AuxArray_Flt[], int AuxArray_Int[] )
{
// uncomment the following lines if the auxiliary arrays have been modified
//# ifdef GPU
// Src_SetConstMemory_User_Template( AuxArray_Flt, AuxArray_Int,
// SrcTerms.User_AuxArrayDevPtr_Flt, SrcTerms.User_AuxArrayDevPtr_Int );
//# endif
} // FUNCTION : Src_WorkBeforeMajorFunc_User_Template
#endif
// ================================
// IV. Set initialization functions
// ================================
#ifdef __CUDACC__
# define FUNC_SPACE __device__ static
#else
# define FUNC_SPACE static
#endif
FUNC_SPACE SrcFunc_t SrcFunc_Ptr = Src_User_Template;
//-----------------------------------------------------------------------------------------
// Function : Src_SetFunc_User_Template
// Description : Return the function pointer of the CPU/GPU source-term function
//
// Note : 1. Invoked by Src_Init_User_Template()
// 2. Call-by-reference
// 3. Use either CPU or GPU but not both of them
//
// Parameter : SrcFunc_CPU/GPUPtr : CPU/GPU function pointer to be set
//
// Return : SrcFunc_CPU/GPUPtr
//-----------------------------------------------------------------------------------------
#ifdef __CUDACC__
__host__
void Src_SetFunc_User_Template( SrcFunc_t &SrcFunc_GPUPtr )
{
CUDA_CHECK_ERROR( cudaMemcpyFromSymbol( &SrcFunc_GPUPtr, SrcFunc_Ptr, sizeof(SrcFunc_t) ) );
}
#elif ( !defined GPU )
void Src_SetFunc_User_Template( SrcFunc_t &SrcFunc_CPUPtr )
{
SrcFunc_CPUPtr = SrcFunc_Ptr;
}
#endif // #ifdef __CUDACC__ ... elif ...
#ifdef __CUDACC__
//-------------------------------------------------------------------------------------------------------
// Function : Src_SetConstMemory_User_Template
// Description : Set the constant memory variables on GPU
//
// Note : 1. Adopt the suggested approach for CUDA version >= 5.0
// 2. Invoked by Src_Init_User_Template() and, if necessary, Src_WorkBeforeMajorFunc_User_Template()
// 3. SRC_NAUX_USER is defined in Macro.h
//
// Parameter : AuxArray_Flt/Int : Auxiliary arrays to be copied to the constant memory
// DevPtr_Flt/Int : Pointers to store the addresses of constant memory arrays
//
// Return : c_Src_User_AuxArray_Flt[], c_Src_User_AuxArray_Int[], DevPtr_Flt, DevPtr_Int
//---------------------------------------------------------------------------------------------------
void Src_SetConstMemory_User_Template( const double AuxArray_Flt[], const int AuxArray_Int[],
double *&DevPtr_Flt, int *&DevPtr_Int )
{
// copy data to constant memory
CUDA_CHECK_ERROR( cudaMemcpyToSymbol( c_Src_User_AuxArray_Flt, AuxArray_Flt, SRC_NAUX_USER*sizeof(double) ) );
CUDA_CHECK_ERROR( cudaMemcpyToSymbol( c_Src_User_AuxArray_Int, AuxArray_Int, SRC_NAUX_USER*sizeof(int ) ) );
// obtain the constant-memory pointers
CUDA_CHECK_ERROR( cudaGetSymbolAddress( (void **)&DevPtr_Flt, c_Src_User_AuxArray_Flt) );
CUDA_CHECK_ERROR( cudaGetSymbolAddress( (void **)&DevPtr_Int, c_Src_User_AuxArray_Int) );
} // FUNCTION : Src_SetConstMemory_User_Template
#endif // #ifdef __CUDACC__
#ifndef __CUDACC__
// function pointer
extern void (*Src_WorkBeforeMajorFunc_User_Ptr)( const int lv, const double TimeNew, const double TimeOld, const double dt,
double AuxArray_Flt[], int AuxArray_Int[] );
extern void (*Src_End_User_Ptr)();
//-----------------------------------------------------------------------------------------
// Function : Src_Init_User_Template
// Description : Initialize a user-specified source term
//
// Note : 1. Set auxiliary arrays by invoking Src_SetAuxArray_*()
// --> Copy to the GPU constant memory and store the associated addresses
// 2. Set the source-term function by invoking Src_SetFunc_*()
// --> Unlike other modules (e.g., EoS), here we use either CPU or GPU but not
// both of them
// 3. Set the function pointers "Src_WorkBeforeMajorFunc_User_Ptr" and "Src_End_User_Ptr"
// 4. Invoked by Src_Init()
// --> Enable it by linking to the function pointer "Src_Init_User_Ptr"
// 5. Add "#ifndef __CUDACC__" since this routine is only useful on CPU
//
// Parameter : None
//
// Return : None
//-----------------------------------------------------------------------------------------
void Src_Init_User_Template()
{
// set the auxiliary arrays
Src_SetAuxArray_User_Template( Src_User_AuxArray_Flt, Src_User_AuxArray_Int );
// copy the auxiliary arrays to the GPU constant memory and store the associated addresses
# ifdef GPU
Src_SetConstMemory_User_Template( Src_User_AuxArray_Flt, Src_User_AuxArray_Int,
SrcTerms.User_AuxArrayDevPtr_Flt, SrcTerms.User_AuxArrayDevPtr_Int );
# else
SrcTerms.User_AuxArrayDevPtr_Flt = Src_User_AuxArray_Flt;
SrcTerms.User_AuxArrayDevPtr_Int = Src_User_AuxArray_Int;
# endif
// set the major source-term function
Src_SetFunc_User_Template( SrcTerms.User_FuncPtr );
// set the auxiliary functions
Src_WorkBeforeMajorFunc_User_Ptr = Src_WorkBeforeMajorFunc_User_Template;
Src_End_User_Ptr = Src_End_User_Template;
} // FUNCTION : Src_Init_User_Template
//-----------------------------------------------------------------------------------------
// Function : Src_End_User_Template
// Description : Free the resources used by a user-specified source term
//
// Note : 1. Invoked by Src_End()
// --> Enable it by linking to the function pointer "Src_End_User_Ptr"
// 2. Add "#ifndef __CUDACC__" since this routine is only useful on CPU
//
// Parameter : None
//
// Return : None
//-----------------------------------------------------------------------------------------
void Src_End_User_Template()
{
} // FUNCTION : Src_End_User_Template
#endif // #ifndef __CUDACC__
| 39.958457 | 123 | 0.556141 | [
"object"
] |
07706fb19d8628aa4d43bc037b482fb661f191ac | 2,975 | hpp | C++ | number/bare_mod_algebra.hpp | rsm9/cplib-cpp | 269064381eb259a049236335abb31f8f73ded7f4 | [
"MIT"
] | 4 | 2020-05-13T05:06:22.000Z | 2020-09-18T17:03:36.000Z | number/bare_mod_algebra.hpp | rsm9/cplib-cpp | 269064381eb259a049236335abb31f8f73ded7f4 | [
"MIT"
] | 1 | 2019-12-11T13:53:17.000Z | 2019-12-11T13:53:17.000Z | number/bare_mod_algebra.hpp | rsm9/cplib-cpp | 269064381eb259a049236335abb31f8f73ded7f4 | [
"MIT"
] | 3 | 2019-12-11T06:45:45.000Z | 2020-09-07T13:45:32.000Z | #pragma once
#include <algorithm>
#include <cassert>
#include <tuple>
#include <utility>
#include <vector>
// CUT begin
// Solve ax+by=gcd(a, b)
template <class Int> Int extgcd(Int a, Int b, Int &x, Int &y) {
Int d = a;
if (b != 0) {
d = extgcd(b, a % b, y, x), y -= (a / b) * x;
} else {
x = 1, y = 0;
}
return d;
}
// Calculate a^(-1) (MOD m) s if gcd(a, m) == 1
// Calculate x s.t. ax == gcd(a, m) MOD m
template <class Int> Int mod_inverse(Int a, Int m) {
Int x, y;
extgcd<Int>(a, m, x, y);
x %= m;
return x + (x < 0) * m;
}
// Require: 1 <= b
// return: (g, x) s.t. g = gcd(a, b), xa = g MOD b, 0 <= x < b/g
template <class Int> /* constexpr */ std::pair<Int, Int> inv_gcd(Int a, Int b) {
a %= b;
if (a < 0) a += b;
if (a == 0) return {b, 0};
Int s = b, t = a, m0 = 0, m1 = 1;
while (t) {
Int u = s / t;
s -= t * u, m0 -= m1 * u;
auto tmp = s;
s = t, t = tmp, tmp = m0, m0 = m1, m1 = tmp;
}
if (m0 < 0) m0 += b / s;
return {s, m0};
}
template <class Int>
/* constexpr */ std::pair<Int, Int> crt(const std::vector<Int> &r, const std::vector<Int> &m) {
assert(r.size() == m.size());
int n = int(r.size());
// Contracts: 0 <= r0 < m0
Int r0 = 0, m0 = 1;
for (int i = 0; i < n; i++) {
assert(1 <= m[i]);
Int r1 = r[i] % m[i], m1 = m[i];
if (r1 < 0) r1 += m1;
if (m0 < m1) {
std::swap(r0, r1);
std::swap(m0, m1);
}
if (m0 % m1 == 0) {
if (r0 % m1 != r1) return {0, 0};
continue;
}
Int g, im;
std::tie(g, im) = inv_gcd<Int>(m0, m1);
Int u1 = m1 / g;
if ((r1 - r0) % g) return {0, 0};
Int x = (r1 - r0) / g % u1 * im % u1;
r0 += x * m0;
m0 *= u1;
if (r0 < 0) r0 += m0;
}
return {r0, m0};
}
// 蟻本 P.262
// 中国剰余定理を利用して,色々な素数で割った余りから元の値を復元
// 連立線形合同式 A * x = B mod M の解
// Requirement: M[i] > 0
// Output: x = first MOD second (if solution exists), (0, 0) (otherwise)
template <class Int>
std::pair<Int, Int>
linear_congruence(const std::vector<Int> &A, const std::vector<Int> &B, const std::vector<Int> &M) {
Int r = 0, m = 1;
assert(A.size() == M.size());
assert(B.size() == M.size());
for (int i = 0; i < (int)A.size(); i++) {
assert(M[i] > 0);
const Int ai = A[i] % M[i];
Int a = ai * m, b = B[i] - ai * r, d = std::__gcd(M[i], a);
if (b % d != 0) {
return std::make_pair(0, 0); // 解なし
}
Int t = b / d * mod_inverse<Int>(a / d, M[i] / d) % (M[i] / d);
r += m * t;
m *= M[i] / d;
}
return std::make_pair((r < 0 ? r + m : r), m);
}
int pow_mod(int x, long long n, int md) {
if (md == 1) return 0;
long long ans = 1;
while (n > 0) {
if (n & 1) ans = ans * x % md;
x = (long long)x * x % md;
n >>= 1;
}
return ans;
}
| 26.5625 | 100 | 0.440672 | [
"vector"
] |
07715574f3f3e381a854924d99b77785615e9df8 | 11,840 | cpp | C++ | src/2d/barrel/phantom_cmd.cpp | wkrzemien/j-pet-mlem | 4ed746f3fe79890e4141158cd49d1869938105de | [
"Apache-2.0"
] | null | null | null | src/2d/barrel/phantom_cmd.cpp | wkrzemien/j-pet-mlem | 4ed746f3fe79890e4141158cd49d1869938105de | [
"Apache-2.0"
] | 5 | 2018-08-08T08:26:04.000Z | 2020-05-13T13:33:39.000Z | src/2d/barrel/phantom_cmd.cpp | wkrzemien/j-pet-mlem | 4ed746f3fe79890e4141158cd49d1869938105de | [
"Apache-2.0"
] | 5 | 2018-06-04T21:04:29.000Z | 2021-07-03T14:19:39.000Z | /// \page cmd_2d_barrel_phantom 2d_barrel_phantom
/// \brief 2D Barrel PET phantom generation tool
///
/// Simulates detector response for given virtual phantom and produces mean file
/// for \ref cmd_2d_barrel_reconstruction.
///
/// Example
/// -------
///
/// 1. Make a \c playground directory and step into it
///
/// mkdir playground
/// cd playground
///
/// 2. Generate \c p_shepp_2d_barrel.txt 2D barrel bin-mode response file
/// for \c s_shepp phantom description file scaled to 40% (\c --scale)
/// and "big" barrel configuration (\c -c)
/// using additive method, 4mm pixel size (\c -p),
/// 1 million detected emissions (\c -e together with \c --detected)
/// and be verbose (\c -v)
///
/// ../2d_barrel_phantom ../phantoms/s_shepp \
/// --scale 0.4 --additive \
/// -p 0.004 \
/// -c ../config/big.cfg \
/// -e 1m --detected \
/// -o p_shepp_2d_barrel.txt \
/// -v
///
/// Phantom description format
/// --------------------------
///
/// See \ref cmd_2d_strip_phantom.
///
/// Sample phantom descriptions
/// ---------------------------
/// - Shepp like phantom
///
/// \verbinclude phantoms/s_shepp
///
/// - Small Shepp like phantom
///
/// \verbinclude phantoms/s_shepp_scaled
///
/// Sample phantoms are shipped with source-code in \c phantom/ subdirectory.
///
/// \note Phantoms with \c json extension are for 3D phantom simulation \ref
/// cmd_3d_hybrid_phantom.
///
/// Authors
/// -------
/// - Piotr Bialas <piotr.bialas@uj.edu.pl>
/// - Jakub Kowal <jakub.kowal@uj.edu.pl>
/// - Adam Strzelecki <adam.strzelecki@uj.edu.pl>
///
/// Usage
/// -----
/// \verboutput 2d_barrel_phantom
///
/// \sa \ref cmd_2d_barrel_matrix, \ref cmd_2d_barrel_reconstruction
#include <random>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <ctime>
#include "cmdline.h"
#include "util/cmdline_types.h"
#include "util/cmdline_hooks.h"
#include "2d/geometry/point.h"
#include "2d/barrel/scanner_builder.h"
#include "ring_scanner.h"
#include "generic_scanner.h"
#include "circle_detector.h"
#include "triangle_detector.h"
#include "polygonal_detector.h"
#include "util/png_writer.h"
#include "util/progress.h"
#include "util/json.h"
#include "util/random.h"
#include "util/backtrace.h"
#include "options.h"
#include "2d/geometry/phantom.h"
#include "2d/geometry/pixel_map.h"
#include "common/model.h"
#include "common/phantom_monte_carlo.h"
#include "common/types.h"
#if _OPENMP
#include <omp.h>
#endif
using RNG = util::random::tausworthe;
using Pixel = PET2D::Pixel<S>;
using Point = PET2D::Point<F>;
using Event = PET2D::Event<F>;
using Image = PET2D::PixelMap<Pixel, Hit>;
template <class DetectorClass>
using Scanner = PET2D::Barrel::GenericScanner<DetectorClass, S>;
template <class DetectorClass>
using ScannerBuilder = PET2D::Barrel::ScannerBuilder<DetectorClass>;
// all available detector shapes
using SquareScanner = Scanner<PET2D::Barrel::SquareDetector<F>>;
using CircleScanner = Scanner<PET2D::Barrel::CircleDetector<F>>;
using TriangleScanner = Scanner<PET2D::Barrel::TriangleDetector<F>>;
using HexagonalScanner = Scanner<PET2D::Barrel::PolygonalDetector<6, F>>;
using Ellipse = PET2D::Ellipse<F>;
using Phantom = PET2D::Phantom<RNG, F>;
template <class DetectorClass, class PhantomClass, class ModelClass>
void run(cmdline::parser& cl, PhantomClass& phantom, ModelClass& model);
int main(int argc, char* argv[]) {
CMDLINE_TRY
cmdline::parser cl;
PET2D::Barrel::add_phantom_options(cl);
cl.parse_check(argc, argv);
PET2D::Barrel::calculate_scanner_options(cl, argc);
#if _OPENMP
if (cl.exist("n-threads")) {
omp_set_num_threads(cl.get<int>("n-threads"));
}
#endif
const auto& shape = cl.get<std::string>("shape");
const auto& model_name = cl.get<std::string>("model");
const auto& length_scale = cl.get<double>("base-length");
Phantom phantom(cl.get<double>("scale"), cl.exist("additive"));
// Read phantom
for (auto& fn : cl.rest()) {
std::ifstream in_phantom(fn);
phantom << in_phantom;
}
phantom.calculate_cdf();
// run simmulation on given detector model & shape
if (model_name == "always") {
Common::AlwaysAccept<F> model;
if (shape == "square") {
run<SquareScanner>(cl, phantom, model);
} else if (shape == "circle") {
run<CircleScanner>(cl, phantom, model);
} else if (shape == "triangle") {
run<TriangleScanner>(cl, phantom, model);
} else if (shape == "hexagon") {
run<HexagonalScanner>(cl, phantom, model);
}
} else if (model_name == "scintillator") {
Common::ScintillatorAccept<F> model(length_scale);
if (shape == "square") {
run<SquareScanner>(cl, phantom, model);
} else if (shape == "circle") {
run<CircleScanner>(cl, phantom, model);
} else if (shape == "triangle") {
run<TriangleScanner>(cl, phantom, model);
} else if (shape == "hexagon") {
run<HexagonalScanner>(cl, phantom, model);
}
}
CMDLINE_CATCH
}
template <class DetectorClass, class PhantomClass, class ModelClass>
void run(cmdline::parser& cl, PhantomClass& phantom, ModelClass& model) {
using MonteCarlo = Common::PhantomMonteCarlo<PhantomClass, DetectorClass>;
using RNG = typename PhantomClass::RNG;
auto& n_emissions = cl.get<size_t>("n-emissions");
auto verbose = cl.count("verbose");
auto scanner = ScannerBuilder<DetectorClass>::build_multiple_rings(
PET2D_BARREL_SCANNER_CL(cl, typename DetectorClass::F));
scanner.set_sigma_dl(cl.get<double>("s-dl"));
if (cl.exist("tof-step"))
scanner.set_tof_step(cl.get<double>("tof-step"));
MonteCarlo monte_carlo(phantom, scanner);
std::random_device rd;
RNG rng(rd());
if (cl.exist("seed")) {
rng.seed(cl.get<util::random::tausworthe::seed_type>("seed"));
}
if (cl.exist("output")) {
auto output = cl.get<cmdline::path>("output");
auto output_base_name = output.wo_ext();
auto ext = output.ext();
if (output_base_name.length() && ext != ".txt") {
throw("output extension must be .txt, binary filed not supported (yet)");
}
auto only_detected = cl.exist("detected");
auto n_pixels = cl.get<int>("n-pixels");
auto s_pixel = cl.get<double>("s-pixel");
float ll = -s_pixel * n_pixels / 2;
PET2D::PixelGrid<F, S> pixel_grid(
n_pixels, n_pixels, s_pixel, PET2D::Point<F>(ll, ll));
Image image_emitted(n_pixels, n_pixels);
Image image_detected_exact(n_pixels, n_pixels);
util::progress progress(verbose, n_emissions, 10000);
// bin-mode
if (!cl.exist("lm")) {
int n_tof_positions = scanner.n_tof_positions(scanner.tof_step_size(),
scanner.max_dl_error());
if (n_tof_positions == 0)
n_tof_positions = 1;
int n_detectors = scanner.size();
int n_bins_total = n_detectors * n_detectors * n_tof_positions;
std::vector<int> bins_w_error(n_bins_total, 0);
std::vector<int> bins_wo_error(n_bins_total, 0);
monte_carlo(
rng,
model,
n_emissions,
[&](const typename MonteCarlo::Event& event) {
auto pixel = pixel_grid.pixel_at(event.origin);
if (pixel_grid.contains(pixel)) {
image_emitted[pixel]++;
}
},
[&](const typename MonteCarlo::Event& event,
const typename MonteCarlo::FullResponse& full_response) {
// bins without error
{
auto response = scanner.response_wo_error(full_response);
if (response.tof_position < 0)
response.tof_position = 0;
if (response.tof_position >= n_tof_positions)
response.tof_position = n_tof_positions - 1;
int index = response.lor.first * n_detectors * n_tof_positions +
response.lor.second * n_tof_positions +
response.tof_position;
bins_wo_error[index]++;
}
// bins with error
{
auto response = scanner.response_w_error(rng, full_response);
if (response.tof_position < 0)
response.tof_position = 0;
if (response.tof_position >= n_tof_positions)
response.tof_position = n_tof_positions - 1;
int index = response.lor.first * n_detectors * n_tof_positions +
response.lor.second * n_tof_positions +
response.tof_position;
bins_w_error[index]++;
}
// image without error
{
auto pixel = pixel_grid.pixel_at(event.origin);
if (pixel_grid.contains(pixel)) {
image_detected_exact[pixel]++;
}
}
},
progress,
only_detected);
std::ofstream out_bins_wo_error, out_bins_w_error;
if (output_base_name.length()) {
out_bins_wo_error.open(output_base_name + "_wo_error.txt");
out_bins_w_error.open(output);
}
// dump bins into files
for (int d1 = 0; d1 < n_detectors; d1++)
for (int d2 = 0; d2 < n_detectors; d2++)
for (int tof = 0; tof < n_tof_positions; tof++) {
int bin_index =
d1 * n_detectors * n_tof_positions + d2 * n_tof_positions + tof;
if (bins_wo_error[bin_index] > 0)
out_bins_wo_error << d1 << ' ' << d2 << ' ' << tof << " "
<< bins_wo_error[bin_index] << "\n";
if (bins_w_error[bin_index] > 0)
out_bins_w_error << d1 << ' ' << d2 << ' ' << tof << " "
<< bins_w_error[bin_index] << "\n";
}
}
// list-mode
else {
std::ofstream out_wo_error, out_w_error, out_exact_events,
out_full_response;
if (output_base_name.length()) {
out_wo_error.open(output_base_name + "_wo_error" + ext);
out_w_error.open(output);
out_exact_events.open(output_base_name + "_events" + ext);
out_full_response.open(output_base_name + "_full_response" + ext);
}
monte_carlo(
rng,
model,
n_emissions,
[&](const typename MonteCarlo::Event& event) {
auto pixel = pixel_grid.pixel_at(event.origin);
if (pixel_grid.contains(pixel)) {
image_emitted[pixel]++;
}
},
[&](const typename MonteCarlo::Event& event,
const typename MonteCarlo::FullResponse& full_response) {
out_exact_events << event << "\n";
out_full_response << full_response << "\n";
out_wo_error << scanner.response_wo_error(full_response) << "\n";
out_w_error << scanner.response_w_error(rng, full_response) << "\n";
{
auto pixel = pixel_grid.pixel_at(event.origin);
if (pixel_grid.contains(pixel)) {
image_detected_exact[pixel]++;
}
}
},
progress,
only_detected);
}
if (verbose) {
std::cerr << " emitted: " << monte_carlo.n_events_emitted() << " events"
<< std::endl
<< "detected: " << monte_carlo.n_events_detected() << " events"
<< std::endl;
}
if (output_base_name.length()) {
util::png_writer png_emitted(output_base_name + "_emitted.png");
png_emitted << image_emitted;
util::png_writer png_detected_wo_error(output_base_name +
"_wo_error.png");
png_detected_wo_error << image_detected_exact;
std::ofstream out_cfg(output_base_name + ".cfg");
out_cfg << cl;
}
}
}
| 33.541076 | 80 | 0.605912 | [
"geometry",
"shape",
"vector",
"model",
"3d"
] |
077e9b1fad9d21e9361bf9e8b6f7013ea86a743c | 2,725 | cc | C++ | third_party/blink/renderer/core/paint/inline_painter.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/blink/renderer/core/paint/inline_painter.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/blink/renderer/core/paint/inline_painter.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2021-01-05T23:43:46.000Z | 2021-01-07T23:36:34.000Z | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/core/paint/inline_painter.h"
#include "third_party/blink/renderer/core/layout/layout_block_flow.h"
#include "third_party/blink/renderer/core/layout/layout_inline.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_physical_text_fragment.h"
#include "third_party/blink/renderer/core/paint/line_box_list_painter.h"
#include "third_party/blink/renderer/core/paint/ng/ng_inline_box_fragment_painter.h"
#include "third_party/blink/renderer/core/paint/ng/ng_paint_fragment.h"
#include "third_party/blink/renderer/core/paint/ng/ng_text_fragment_painter.h"
#include "third_party/blink/renderer/core/paint/object_painter.h"
#include "third_party/blink/renderer/core/paint/paint_info.h"
#include "third_party/blink/renderer/core/paint/paint_timing_detector.h"
#include "third_party/blink/renderer/core/paint/scoped_paint_state.h"
#include "third_party/blink/renderer/platform/geometry/layout_point.h"
namespace blink {
void InlinePainter::Paint(const PaintInfo& paint_info) {
ScopedPaintState paint_state(layout_inline_, paint_info);
auto paint_offset = paint_state.PaintOffset();
const auto& local_paint_info = paint_state.GetPaintInfo();
if (local_paint_info.phase == PaintPhase::kForeground &&
local_paint_info.ShouldAddUrlMetadata()) {
ObjectPainter(layout_inline_)
.AddURLRectIfNeeded(local_paint_info, paint_offset);
}
ScopedPaintTimingDetectorBlockPaintHook
scoped_paint_timing_detector_block_paint_hook;
if (paint_info.phase == PaintPhase::kForeground) {
scoped_paint_timing_detector_block_paint_hook.EmplaceIfNeeded(
layout_inline_,
paint_info.context.GetPaintController().CurrentPaintChunkProperties());
}
if (layout_inline_.IsInLayoutNGInlineFormattingContext()) {
NGInlineBoxFragmentPainter::PaintAllFragments(layout_inline_, paint_info,
paint_offset);
return;
}
if (ShouldPaintSelfOutline(local_paint_info.phase) ||
ShouldPaintDescendantOutlines(local_paint_info.phase)) {
ObjectPainter painter(layout_inline_);
if (ShouldPaintDescendantOutlines(local_paint_info.phase))
painter.PaintInlineChildrenOutlines(local_paint_info);
if (ShouldPaintSelfOutline(local_paint_info.phase) &&
!layout_inline_.IsElementContinuation()) {
painter.PaintOutline(local_paint_info, paint_offset);
}
return;
}
LineBoxListPainter(*layout_inline_.LineBoxes())
.Paint(layout_inline_, local_paint_info, paint_offset);
}
} // namespace blink
| 42.578125 | 87 | 0.780917 | [
"geometry"
] |
07805764586ced719219a50097decc05b46f31e3 | 883 | cpp | C++ | b-LeetCode/145-Binary-Tree-Postorder-Traversal.cpp | ftxj/4th-Semester | 1d5c7e7e028176524bdafc64078775d42b73b51c | [
"MIT"
] | null | null | null | b-LeetCode/145-Binary-Tree-Postorder-Traversal.cpp | ftxj/4th-Semester | 1d5c7e7e028176524bdafc64078775d42b73b51c | [
"MIT"
] | null | null | null | b-LeetCode/145-Binary-Tree-Postorder-Traversal.cpp | ftxj/4th-Semester | 1d5c7e7e028176524bdafc64078775d42b73b51c | [
"MIT"
] | null | null | null | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
TreeNode* p = root;
stack<TreeNode *> s;
vector<int> v;
while(p)
{
s.push(p);
if(p->right) {s.push(p->right); p->right = NULL;}
if(p->left) {s.push(p->left); p->left = NULL;}
if(p == s.top())
{
v.push_back(p->val);
s.pop();
if(s.empty()) break;
p = s.top();
s.pop();
}
else
{
p = s.top();
s.pop();
}
}
return v;
}
}; | 23.236842 | 61 | 0.379388 | [
"vector"
] |
07807eccef9493b1ef3f88b81378a2112235505d | 11,680 | cpp | C++ | src/CalibEngine.cpp | plewand/stereovision | b05aa2e064d8877c47e5d7182db4b72979ad9d57 | [
"BSD-3-Clause"
] | null | null | null | src/CalibEngine.cpp | plewand/stereovision | b05aa2e064d8877c47e5d7182db4b72979ad9d57 | [
"BSD-3-Clause"
] | null | null | null | src/CalibEngine.cpp | plewand/stereovision | b05aa2e064d8877c47e5d7182db4b72979ad9d57 | [
"BSD-3-Clause"
] | null | null | null | #include "CalibEngine.h"
#include "Logger.h"
#include "CvUtil.h"
#include <experimental/filesystem>
namespace fs = std::experimental::filesystem;
static const string DETECTED_CHESSBOARD_PATH = "./outimages/calib/chessboard";
CalibEngine::CalibEngine() {
}
CalibEngine::CalibEngine(const CalibEngine& orig) {
}
CalibEngine::~CalibEngine() {
}
bool CalibEngine::calib(const Config &config) {
vector<cv::String> fn;
glob(config.chessboardImagesDir + "/*.ppm", fn, false);
if (fn.size() == 0 || fn.size() % 2 != 0) {
return FAIL("Invalid file number");
}
int pairNum = fn.size() / 2;
String firstElem = fn[0];
String ext = firstElem.substr(firstElem.find_last_of('.'), 4);
if (!fs::exists(DETECTED_CHESSBOARD_PATH) && !fs::create_directories(DETECTED_CHESSBOARD_PATH)) {
return FAIL("Cannot create chessboard dir");
}
vector<vector < Point2f>> allLeftCorners;
allLeftCorners.resize(pairNum);
vector<vector < Point2f>> allRightCorners;
allRightCorners.resize(pairNum);
vector<bool> chessboardFoundLeft;
chessboardFoundLeft.resize(pairNum);
vector<bool> chessboardFoundRight;
chessboardFoundRight.resize(pairNum);
Size imgSize;
for (int i = 0; i < pairNum; i++) {
if (!buildCorners(i, config.chessboardImagesDir, "left_", ext, config.boardSize, allLeftCorners, imgSize, chessboardFoundLeft)) {
return false;
}
if (!buildCorners(i, config.chessboardImagesDir, "right_", ext, config.boardSize, allRightCorners, imgSize, chessboardFoundRight)) {
return false;
}
}
vector<vector < Point2f>> correctLeftCorners;
vector<vector < Point2f>> correctRightCorners;
for (int i = 0; i < pairNum; i++) {
if (!chessboardFoundLeft[i] || !chessboardFoundRight[i]) {
printf("Removing stereo pair %d\n", i + 1);
continue;
}
correctLeftCorners.push_back(allLeftCorners[i]);
correctRightCorners.push_back(allRightCorners[i]);
}
Logger::log("Correct pairs pairs %d / %d", (int) correctLeftCorners.size(), pairNum);
Logger::log("Start tuning, it can take a few minutes", (int) correctLeftCorners.size(), pairNum);
if (correctLeftCorners.size() == 0) {
printf("No chessboards found\n");
return false;
}
Size remapSize;
if (config.remapWidth > 0 && config.remapHeight > 0) {
remapSize = Size(config.remapWidth, config.remapHeight);
} else {
remapSize = imgSize;
}
if (!stereoCalib(correctLeftCorners, correctRightCorners, config.boardSize, config.fieldSize, imgSize, remapSize)) {
return false;
}
return true;
}
bool CalibEngine::buildCorners(int index, const string &folderStr, const char *side, const string &ext, Size boardSize, vector<vector < Point2f>> &allCorners, Size &outImgSize, vector<bool> &chessboardFound) {
int numSize = 3;
stringstream numPrefix;
numPrefix << std::setfill('0') << std::setw(numSize) << index + 1;
const string coreName = side + numPrefix.str();
const string filename = folderStr + "/" + coreName + ext;
Mat img = imread(filename, 0);
if (img.empty()) {
return FAIL("Img read failed: " + filename);
}
outImgSize = img.size();
vector < Point2f> &corners = allCorners[index];
bool found = findChessboardCorners(img, boardSize, corners,
CV_CALIB_CB_ADAPTIVE_THRESH | CV_CALIB_CB_NORMALIZE_IMAGE);
if (!found) {
printf("No corners found for: %s\n", filename.c_str());
chessboardFound[index] = false;
return true;
}
chessboardFound[index] = true;
cornerSubPix(img, corners, Size(11, 11), Size(-1, -1), TermCriteria(CV_TERMCRIT_ITER + CV_TERMCRIT_EPS, 30, 0.01));
drawChessboardCorners(img, boardSize, corners, found);
string outPath = DETECTED_CHESSBOARD_PATH + "/corners_" + coreName + ext;
imwrite(outPath, img);
return true;
}
void CalibEngine::printMat(const char *name, const Mat &m) {
cout << name << " = " << endl << " " << m << endl << endl;
}
bool CalibEngine::stereoCalib(const vector<vector < Point2f>> &allLeftCorners, const vector<vector < Point2f>> &allRightCorners, Size boardSize, float fieldSize, const Size &imgSize, const Size &remapSize) {
vector<vector < Point3f>> objectPoints;
objectPoints.resize(allLeftCorners.size());
buildObjectPoints(fieldSize, boardSize, objectPoints);
Mat cameraMatrixLeft = Mat::eye(3, 3, CV_64F);
Mat cameraMatrixRight = Mat::eye(3, 3, CV_64F);
Mat distCoeffsLeft;
Mat distCoeffsRight;
Mat R, T, E, F;
resetCameraIntrinsic(cameraMatrixLeft, imgSize);
resetCameraIntrinsic(cameraMatrixRight, imgSize);
findCameraIntrinsic(objectPoints, allLeftCorners, imgSize, cameraMatrixLeft, distCoeffsLeft);
findCameraIntrinsic(objectPoints, allRightCorners, imgSize, cameraMatrixRight, distCoeffsRight);
resetCameraIntrinsic(cameraMatrixLeft, imgSize);
resetCameraIntrinsic(cameraMatrixRight, imgSize);
int flags = CALIB_FIX_INTRINSIC;
TermCriteria criteria = TermCriteria(TermCriteria::COUNT + TermCriteria::EPS, 30, 1e-6);
//R – Output rotation matrix between the 1st and the 2nd camera coordinate systems.
//T – Output translation vector between the coordinate systems of the cameras.
//E – Output essential matrix.
//F – Output fundamental matrix.
double rms = stereoCalibrate(objectPoints, allLeftCorners, allRightCorners,
cameraMatrixLeft, distCoeffsLeft,
cameraMatrixRight, distCoeffsRight,
imgSize, R, T, E, F,
flags,
criteria);
printMat("cameraMatrixLeft", cameraMatrixLeft);
printMat("cameraMatrixRight", cameraMatrixRight);
printMat("distCoeffsLeft", distCoeffsLeft);
printMat("distCoeffsRight", distCoeffsRight);
printMat("rotation", R);
printMat("translation", T);
printMat("essential", E);
printMat("fundamental", F);
Mat R1, R2, P1, P2, Q;
Mat remapLeft0, remapLeft1, remapRight0, remapRight1;
Rect validRoiLeft, validRoiRight;
if(!rectify(cameraMatrixLeft, cameraMatrixRight, distCoeffsLeft, distCoeffsRight,
imgSize, R, T, R1, R2, P1, P2, &validRoiLeft, &validRoiRight)) {
return false;
}
createRemapMatrices(cameraMatrixLeft, cameraMatrixRight, distCoeffsLeft, distCoeffsRight,
remapSize, R1, P1, R2, P2, remapLeft0, remapLeft1, remapRight0, remapRight1);
if(!saveYaml("remap.yml", [remapLeft0, remapLeft1, remapRight0, remapRight1](auto fs) -> auto {
fs << "remapLeft0" << remapLeft0 << "remapLeft1" << remapLeft1 <<
"remapRight0" << remapRight0 << "remapRight1" << remapRight1;
})){
return false;
}
Logger::log("RMS error: %f", rms);
return calcEpilines(allLeftCorners, allRightCorners, cameraMatrixLeft, cameraMatrixRight, distCoeffsLeft, distCoeffsRight, F);
}
void CalibEngine::resetCameraIntrinsic(Mat &mat, const Size &imgSize) {
double *camPtrRight = (double*) mat.data;
camPtrRight[0] = imgSize.width;
camPtrRight[4] = imgSize.width;
camPtrRight[2] = imgSize.width / 2;
camPtrRight[5] = imgSize.height / 2;
}
void CalibEngine::findCameraIntrinsic(const vector<vector < Point3f>> &objPoints, const vector<vector < Point2f>> &imgPoints, const Size& imgSize, const Mat& cameraMatrix, Mat& distCoefs) {
Mat rvecs;
Mat tvecs;
calibrateCamera(objPoints, imgPoints, imgSize, cameraMatrix, distCoefs, rvecs, tvecs);
}
void CalibEngine::buildObjectPoints(float fieldSize, Size boardSize, vector<vector<Point3f>> &objectPoints) {
for (int i = 0; i < (int)objectPoints.size(); i++) {
for (int j = 0; j < boardSize.height; j++)
for (int k = 0; k < boardSize.width; k++)
objectPoints[i].push_back(Point3f(j * fieldSize, k * fieldSize, 0));
}
}
bool CalibEngine::calcEpilines(const vector<vector < Point2f>> &allLeftCorners,
const vector<vector < Point2f>> &allRightCorners,
const Mat &cameraMatrixLeft,
const Mat &cameraMatrixRight,
const Mat &distCoeffsLeft,
const Mat &distCoeffsRight,
const Mat &F) {
double err = 0;
int npoints = 0;
vector<Vec3f> linesLeft;
vector<Vec3f> linesRight;
int nimages = allLeftCorners.size();
for (int i = 0; i < nimages; i++) {
int npt = (int) allLeftCorners[i].size();
Mat imgptLeft(allLeftCorners[i]);
undistortPoints(imgptLeft, imgptLeft, cameraMatrixLeft, distCoeffsLeft, Mat(), cameraMatrixLeft);
computeCorrespondEpilines(imgptLeft, 1, F, linesLeft);
Mat imgptRight(allRightCorners[i]);
undistortPoints(imgptRight, imgptRight, cameraMatrixRight, distCoeffsRight, Mat(), cameraMatrixRight);
computeCorrespondEpilines(imgptRight, 2, F, linesRight);
for (int j = 0; j < npt; j++) {
double errij = fabs(allLeftCorners[i][j].x * linesRight[j][0] +
allLeftCorners[i][j].y * linesRight[j][1] + linesRight[j][2]) +
fabs(allRightCorners[i][j].x * linesLeft[j][0] +
allRightCorners[i][j].y * linesLeft[j][1] + linesLeft[j][2]);
err += errij;
}
npoints += npt;
}
Logger::log("Average reprojection err: %f", err / npoints);
return saveYaml("intristics.yml", [cameraMatrixLeft, distCoeffsLeft, cameraMatrixRight, distCoeffsRight](auto fs) -> auto {
fs << "M1" << cameraMatrixLeft << "D1" << distCoeffsLeft << "M2" << cameraMatrixRight << "D2" << distCoeffsRight;
});
}
bool CalibEngine::rectify(const Mat& cameraMatrixLeft,
const Mat& cameraMatrixRight,
const Mat& distCoeffsLeft,
const Mat& distCoeffsRight,
Size imageSize,
const Mat& R,
const Mat& T,
Mat& outR1,
Mat& outR2,
Mat& outP1,
Mat& outP2,
Rect *validRoiLeft,
Rect *validRoiRight) {
Mat Q;
stereoRectify(cameraMatrixLeft, distCoeffsLeft,
cameraMatrixRight, distCoeffsRight,
imageSize, R, T, outR1, outR2, outP1, outP2, Q,
//CALIB_ZERO_DISPARITY, 0, imageSize, validRoiLeft, validRoiRight);
0, 0, imageSize, validRoiLeft, validRoiRight);
printMat("outR1", outR1);
printMat("outR2", outR2);
printMat("outP1", outP1);
printMat("outP2", outP2);
printMat("Q", Q);
cout << "imgSize" << imageSize << endl;
cout << "roiLeft" << *validRoiLeft << endl;
cout << "roiRight" << *validRoiRight << endl;
if(!saveYaml("extrinsics.yml", [R, T, outR1, outR2, outP1, outP2, Q](auto fs) -> auto {
fs << "R" << R << "T" << T << "R1" << outR1 << "R2" << outR2 << "P1" << outP1 << "P2" << outP2 << "Q" << Q;
})){
return false;
}
if(!saveYaml("Q.yml", [Q](auto fs) -> auto {
fs << "Q" << Q;
})) {
return false;
}
return true;
}
void CalibEngine::createRemapMatrices(const Mat& cameraMatrixLeft,
const Mat& cameraMatrixRight,
const Mat& distCoeffsLeft,
const Mat& distCoeffsRight,
Size imageSize,
const Mat& R1,
const Mat& P1,
const Mat& R2,
const Mat& P2,
Mat& outRemapLeft0,
Mat& outRemapLeft1,
Mat& outRemapRight0,
Mat& outRemapRight1) {
initUndistortRectifyMap(cameraMatrixLeft, distCoeffsLeft, R1, cameraMatrixLeft, imageSize, CV_16SC2, outRemapLeft0, outRemapLeft1);
initUndistortRectifyMap(cameraMatrixRight, distCoeffsRight, R2, cameraMatrixRight, imageSize, CV_16SC2, outRemapRight0, outRemapRight1);
} | 38.045603 | 209 | 0.652997 | [
"vector"
] |
078d7d4be199e4cc127618e7ccfadd4f0fb886ae | 3,716 | cc | C++ | gnuradio-3.7.13.4/gr-digital/lib/header_format_counter.cc | v1259397/cosmic-gnuradio | 64c149520ac6a7d44179c3f4a38f38add45dd5dc | [
"BSD-3-Clause"
] | 1 | 2021-03-09T07:32:37.000Z | 2021-03-09T07:32:37.000Z | gnuradio-3.7.13.4/gr-digital/lib/header_format_counter.cc | v1259397/cosmic-gnuradio | 64c149520ac6a7d44179c3f4a38f38add45dd5dc | [
"BSD-3-Clause"
] | null | null | null | gnuradio-3.7.13.4/gr-digital/lib/header_format_counter.cc | v1259397/cosmic-gnuradio | 64c149520ac6a7d44179c3f4a38f38add45dd5dc | [
"BSD-3-Clause"
] | null | null | null | /* -*- c++ -*- */
/* Copyright 2016 Free Software Foundation, Inc.
*
* This file is part of GNU Radio
*
* GNU Radio is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3, or (at your option)
* any later version.
*
* GNU Radio 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 GNU Radio; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <iostream>
#include <iomanip>
#include <string.h>
#include <volk/volk.h>
#include <gnuradio/digital/header_format_counter.h>
#include <gnuradio/digital/header_buffer.h>
#include <gnuradio/math.h>
namespace gr {
namespace digital {
header_format_counter::sptr
header_format_counter::make(const std::string &access_code,
int threshold, int bps)
{
return header_format_counter::sptr
(new header_format_counter(access_code, threshold, bps));
}
header_format_counter::header_format_counter(const std::string &access_code,
int threshold, int bps)
: header_format_default(access_code, threshold, bps)
{
d_counter = 0;
}
header_format_counter::~header_format_counter()
{
}
bool
header_format_counter::format(int nbytes_in,
const unsigned char *input,
pmt::pmt_t &output,
pmt::pmt_t &info)
{
uint8_t* bytes_out = (uint8_t*)volk_malloc(header_nbytes(),
volk_get_alignment());
header_buffer header(bytes_out);
header.add_field64(d_access_code, d_access_code_len);
header.add_field16((uint16_t)(nbytes_in));
header.add_field16((uint16_t)(nbytes_in));
header.add_field16((uint16_t)(d_bps));
header.add_field16((uint16_t)(d_counter));
// Package output data into a PMT vector
output = pmt::init_u8vector(header_nbytes(), bytes_out);
// Creating the output pmt copies data; free our own here.
volk_free(bytes_out);
d_counter++;
return true;
}
size_t
header_format_counter::header_nbits() const
{
return d_access_code_len + 8*4*sizeof(uint16_t);
}
bool
header_format_counter::header_ok()
{
// confirm that two copies of header info are identical
uint16_t len0 = d_hdr_reg.extract_field16(0);
uint16_t len1 = d_hdr_reg.extract_field16(16);
return (len0 ^ len1) == 0;
}
int
header_format_counter::header_payload()
{
uint16_t len = d_hdr_reg.extract_field16(0);
uint16_t bps = d_hdr_reg.extract_field16(32);
uint16_t counter = d_hdr_reg.extract_field16(48);
d_bps = bps;
d_info = pmt::make_dict();
d_info = pmt::dict_add(d_info, pmt::intern("payload symbols"),
pmt::from_long(8*len / d_bps));
d_info = pmt::dict_add(d_info, pmt::intern("bps"),
pmt::from_long(bps));
d_info = pmt::dict_add(d_info, pmt::intern("counter"),
pmt::from_long(counter));
return static_cast<int>(len);
}
} /* namespace digital */
} /* namespace gr */
| 30.966667 | 80 | 0.629709 | [
"vector"
] |
079113543feafed415377a672063154c8806b073 | 23,152 | hpp | C++ | cs400/bst/Dictionary.hpp | weihang-li/Specialization-Accelerated-Computer-Science-Fundamentals | 13f2ae02af725fd61e457aac0b4b71ef07ed121a | [
"MIT"
] | 2 | 2021-05-19T02:49:55.000Z | 2021-05-20T03:14:24.000Z | cs400/bst/Dictionary.hpp | Colin1245/Specialization-Accelerated-Computer-Science-Fundamentals | 43683fe08a8a3c7f3baca050d14f2a8daa13dedc | [
"MIT"
] | null | null | null | cs400/bst/Dictionary.hpp | Colin1245/Specialization-Accelerated-Computer-Science-Fundamentals | 43683fe08a8a3c7f3baca050d14f2a8daa13dedc | [
"MIT"
] | null | null | null | /**
* Dictionary BST auxiliary definitions.
*
* (Some versions of the lecture videos called this file "Dictionary.cpp",
* but we are renaming it to "Dictionary.hpp" as it includes templated
* implementations and would typically be included as a header.
* The line numbers in this file do not exactly match what is shown in the
* lecture slides. Please read the comments for further explanation.)
*
* @author
* Wade Fagen-Ulmschneider <waf@illinois.edu>, Eric Huber
*/
#pragma once
#include "Dictionary.h"
// Note that this .hpp file is just another header file, to be included
// by the first header file. The idea is that templated class code needs
// to be defined in headers, but you still might want to neatly separate
// the code into separate files.
// We still wrote the preprocessor directives shown above, to illustrate
// a common way to handle this situation: If the users mistakenly include
// the wrong header when they use your library, it won't matter this way,
// because either header will correctly pull in the other header.
// -------
// Additional implementation notes from TA Eric:
// Some of the code shown below was not shown directly in lecture, and it
// differs slightly in some parts, as noted. Rationale for the changes:
// I split the action of the original "_iop" function call into separate
// functions, "_iop_of" and "_rightmost_of", as the original call required
// part of the method to be performed in the argument list; in main.cpp, I
// added a separate storage vector to avoid retaining references to temporary
// objects, which some compilers may not support; and the node-swapping
// function was redesigned to resolve some issues, which also required adding
// a return value. These are subtle issues that aren't discussed directly in
// lecture and they don't affect the underlying lessons.
// This is quite a tricky implementation since nearly all of the member
// functions pass and return references to the actual pointers that make
// up the tree structure. Therefore it edits the tree in-place with almost
// every action, rather than passing copies of anything. Remember that we
// can return references to data that is persisting in memory storage else-
// where; in this case, the actual data that the tree organizes is being
// stored somehow outside of the tree itself (see an example in main.cpp),
// and the tree just records references to that external storage. We can also
// return references to the tree's own data members that persist between
// function calls, such as the actual pointers between nodes that it stores.
// However, do remember that you must never return a reference to a temporary
// stack variable that you create in some function; that memory would become
// immediately invalid after the function call.
// There are pros and cons to implementing a tree this way. We can edit a
// parent's connection to its child without storing pointers to parents or
// trying to traverse upwards; instead, we assume that when pointers are
// passed by reference, we are editing the same variable that the parent is
// holding.
// The big challenge with using plain references is that they keep
// referring to the same thing after being first initialized. If you need to
// re-bind the reference to something else, it's easier to use pointers; you
// can make pointers to pointers for layers of indirection, and explicitly
// control how those addresses are stored and dereferenced. There is also an
// advanced mechanism called std::reference_wrapper that you can use to
// simulate storing references that may be re-bound, as many STL containers
// would require.
// For the node data itself, instead of referencing external items, you
// could instead just store value-based copies, which is very easy to write
// but less memory-efficient. We have an example in the directory
// "binary-tree-traversals". But there are many other advanced ways to do
// that in C++ as well. There are some additional notes about the options for
// the underlying data storage in main.cpp in the current directory.
// ------
template <typename K, typename D>
const D& Dictionary<K, D>::find(const K& key) {
// Find the key in the tree starting at the head.
// If found, we receive the tree's actual stored pointer to that node
// through return-by-reference.
// If not found, then the node returned has a value of nullptr.
TreeNode*& node = _find(key, head_);
if (node == nullptr) { throw std::runtime_error("error: key not found"); }
// We found the node, so return the actual data there, by reference.
return node->data;
}
// Note about the use of "typename" in the below definition:
// This is required so that although we're writing at global scope here, we
// can refer to the TreeNode type definition that is part of Dictionary.
// Since we're writing this funzzzzzzction definition outside of the primary class
// definition, the compiler needs help to understand that what follows is
// expected to be the name of a type defined within a specific templated
// class.
// Newer versions of the C++ standard may be smarter about auto-detecting
// this. Until then, it's hard to summarize when you need to write
// "typename" at global scope and when you don't, but in general, you might
// need to write it before a templated type, especially a type belonging to
// another class namespace. If you get a compiler error that looks like this:
// "missing 'typename' prior to dependent type name"
// "need 'typename' before ... because ... is a dependent scope"
// (etc.)
// then you probably need to put "typename" before the type.
// The fully-qualified return type of the below function is:
// Dictionary<K, D>::TreeNode*&
// That is a pointer to a Dictionary<K, D>::TreeNode, returned by reference.
template <typename K, typename D>
typename Dictionary<K, D>::TreeNode*& Dictionary<K, D>::_find(
const K& key, TreeNode*& cur) const {
// (Please also see the implementation of _iop_of below, which discusses
// some more nuances about returning references to pointers.)
// [Base case 1: When the key is not found]
// cur will be nullptr if the tree is empty, or if we descend below the
// lowest level without finding the key. Then we return nullptr and the
// outer "find" function (which calls "_find") will report that as an
// error. Or, if we were calling insert, then the pointer returned is the
// position where the item should be placed.
// Note: The "cur" we return in this case is equal to nullptr, but
// it's important to write "return cur;" and not "return nullptr;" since
// this function returns by reference. We specifically want to return the
// pointer at this position we found. This is true whether we want to
// replace it, as when we're doing an insertion, or if this is a failed
// "find" operation that should report an error. We should not return a
// reference to the "nullptr" literal, and we should avoid making
// references to temporary constants like numerical literals in any case.
if (cur == nullptr) { return cur; }
// [Base case 2: When the key is found]
// If we find a key that matches by value, then return the current TreeNode*
else if (key == cur->key) { return cur; }
// [When we need to search left]
// If the key we're looking for is smaller than the current node's key,
// then we should look to the left next.
else if (key < cur->key) { return _find(key, cur->left); }
// [When we need to search right]
// Otherwise, implicitly, the key we're looking for is larger than the
// current node's key. (We know this because it's not equal and not less.)
// So we should search to the right next.
else { return _find(key, cur->right); }
}
/**
* insert()
* Inserts `key` and associated `data` into the Dictionary.
*/
template <typename K, typename D>
void Dictionary<K, D>::insert(const K& key, const D& data) {
// Find the place where the item should go.
TreeNode *& node = _find(key, head_);
// For the sake of this example, let's disallow duplicates. If the node
// found isn't a nullptr, then the key already exists, so report an error.
// (We could also do something nicer than this, like remove the old key and
// then insert the new item to replace it.)
if (node) { throw std::runtime_error("error: insert() used on an existing key"); }
node = new TreeNode(key, data);
}
/**
* remove()
* Removes `key` from the Dictionary. Returns the associated data.
*/
template <typename K, typename D>
const D& Dictionary<K, D>::remove(const K& key) {
// First, find the actual pointer to the node containing this key.
// If not found, then the pointer returned will be equal to nullptr.
TreeNode*& node = _find(key, head_);
if (!node) { throw std::runtime_error("error: remove() used on non-existent key"); }
return _remove(node);
}
// _remove will remove the node pointed to by the argument. Note that this
// will alter the pointer you pass in-place, so you should not reuse the
// pointer variable after calling this function on it. You can't be sure what
// it points to anymore after the function call.
template <typename K, typename D>
const D& Dictionary<K, D>::_remove(TreeNode*& node) {
// If the node we are trying to remove is a nullptr, then it's an error,
// as even if we'd like to "do nothing" here as a base case, we must return
// a const reference to some data removed, and there is none. In practice
// you would want to add more features to your class for handling these
// situations efficiently in a way that makes sense for your users.
if (!node) { throw std::runtime_error("error: _remove() used on non-existent key"); }
// When you are studying the cases below, remember: Right now, "node" is
// the actual pointer that this node's parent holds, which points to this
// node. When we change "node", we are remapping the parent's connection
// to what is below it.
// Zero child remove:
if (node->left == nullptr && node->right == nullptr) {
// Peek at the data referred to by the node so we can return a reference
// to the data later, after the tree node itself is already gone.
const D& data = node->data;
// The node is a leaf, so it has no descendants to worry about.
// We can just delete it. (The slides originally showed "delete(node)".
// Note that the syntax for "delete" is like an operator, not a function,
// so it's not necessary to put the () when you use it.)
delete node;
// It's very important to set "node" to nullptr here. The parent is still
// holding this same pointer, so we must mark that the child is gone.
node = nullptr;
return data;
}
// One-child (left) remove
else if (node->left != nullptr && node->right == nullptr) {
// Similar to the previous case, except that we need to remap the "node"
// pointer to point to the node's child, so that the parent of the node
// being deleted will retain its connection to the rest of the tree
// below this point.
const D& data = node->data;
TreeNode* temp = node;
node = node->left;
delete temp;
return data;
}
// One-child (right) remove
else if (node->left == nullptr && node->right != nullptr) {
// This case is symmetric to the previous case.
const D& data = node->data;
TreeNode* temp = node;
node = node->right;
delete temp;
return data;
}
// Two-child remove
else {
// When the node being deleted has two children, we have to be very
// careful. The lecture discusses this case in detail. (The versions
// of the helper functions being used here are slightly different
// compared to lecture, as noted in other comments here.)
// Find the IOP (in-order predecessor) of the current node.
TreeNode*& iop = _iop_of(node);
// Old version:
// TreeNode*& iop = _iop( node->left );
// The lecture originally showed the call in this way, but the code has
// been revised so that the first step to the left happens inside the
// "_iop_of" function.
// Since this is the two-child remove case, we know that some in-order
// predecessor does exist, so the _iop_of lookup should not have failed.
if (!iop) {
throw std::runtime_error("error in two-child remove: IOP not found");
}
// Swap the node to remove and the IOP.
// (This function changes the pointers that are passed in-place so that
// it can alter the tree structure itself, but afterwards you don't
// know what the pointers point to exactly, depending on what happened.
// Therefore you shouldn't reuse these pointers in the current function
// after calling this. To make things easier, _swap_nodes will return
// a pointer, by reference, that is the updated pointer in the tree
// that is now pointing to the same node we gave as the first argument,
// so we can do more work on that node afterwards.)
TreeNode*& moved_node = _swap_nodes(node, iop);
// Note that we do not use the original "node" and "iop" pointers by
// name after this point. Assume they are invalid now.
// Recurse to remove the original targeted node at its updated position.
return _remove(moved_node);
}
}
// -------
// The implementations for the following functions were not shown in the
// lecture directly. The _iop function has been revised a little bit as
// "_iop_of", which finds the IOP of the argument you pass; it traverses one
// step to the left before going to the right. This obtains the IOP of the
// "cur" node when you call "_iop_of(cur)" explicitly, instead of requiring
// a call to "_iop(cur->left)" as originally shown.
// _iop_of: You pass in a pointer to a node, and it returns the pointer to
// the in-order predecessor node, by reference. If the IOP does not exist,
// it returns a reference to a node pointer that has value nullptr.
template <typename K, typename D>
typename Dictionary<K, D>::TreeNode*& Dictionary<K, D>::_iop_of(
TreeNode*& cur) const {
// We want to find the in-order predecessor of "cur",
// which is the right-most child of the left subtree of cur.
if (!cur) {
// If cur is nullptr, this is an error case.
// Just return cur by reference. (Since cur has the value of nullptr,
// we can check for that result.)
return cur;
}
if (!(cur->left)) {
// If cur has no left child, this is an error case.
// Just return cur->left by reference. (Since cur->left has the value of
// nullptr, we can check for that result.)
return cur->left;
}
// --- Wait: Let's review our strategy for what to do next. ---
// At this point, we're sure that cur is non-null and it has a left child.
// To search for the right-most child of the left subtree, we'll begin
// with the left child of cur, and then keep going right. However, here
// our plans are slightly complicated since we're directly returning a
// reference to a pointer in the tree. Let's briefly explain why. This
// will also shed more light on how _find works.
// We could use a simple while loop to go right repeatedly, but since we
// ultimately need to return a reference to an actual pointer in our tree,
// this complicates our use of a temporary pointer for looping. Remember
// that once you initialize a reference to something, you can't make it
// refer to something else instead. (You can use a non-const reference to
// edit the original data being referenced, but the reference variable
// itself will refer to the same thing for as long as the reference
// variable exists.)
// Here are some possible workarounds:
// 1. Use pointers to pointers instead of references to pointers.
// (See the binary-tree-traversals folder for another example of this,
// within the ValueBinaryTree class.)
// 2. Use std::reference_wrapper<> from the <functional> include, which
// lets you simulate a reference type, but can be re-assigned to refer
// to something else. This can also be a little confusing to use, as
// you need to typecast the reference_wrapper to plain reference if you
// want to access the actual value that is referred to. (If you choose
// this solution, it would make sense to rewrite this entire class to
// store reference_wrapper instead of plain references.)
// 3. Use recursion with a function that takes a reference as an argument
// and returns a reference. This is how _find works. Since passing
// arguments counts as initializing the argument variable, you can
// simulate updating a reference with each recursive call.
// We'll go with option #3 again, recursion, so you can get more practice
// with that. See the binary-tree-traversals folder to learn about the
// pointers-to-pointers concept.
// ---------------------------------------------------------------
// Find the rightmost child pointer under the left subtree,
// and return it by reference.
return _rightmost_of(cur->left);
}
// _rightmost_of:
// Find the right-most child of cur using recursion, and return that
// node pointer, by reference.
// If you call this function on a nullptr to begin with, it returns the same
// pointer by reference.
template <typename K, typename D>
typename Dictionary<K, D>::TreeNode*& Dictionary<K, D>::_rightmost_of(
TreeNode*& cur) const {
// Base case 1: If cur is null, then just return it by reference.
// (Since cur has the value of nullptr, we can check for that result.)
if (!cur) return cur;
// Base case 2: So far, we know cur is not null. Now, if cur does not have
// a right child, then cur is the rightmost, so return cur by reference.
if (!(cur->right)) return cur;
// General case: The cur pointer is not null, and it does have a right
// child, so we should recurse to the right and return whatever we get.
return _rightmost_of(cur->right);
}
// _swap_nodes:
// This will swap the logical positions of the nodes by changing the pointers
// in the tree. You need to be careful, because this function will change the
// two pointers in-place and invalidate them for use after the call, since
// they may not point to what you expect anymore. Instead, the function will
// will return, by reference, a pointer to the tree node that was previously
// represented by the first argument. If you need to keep track of the new
// positions of BOTH nodes after the call, for some purpose, then you could
// extend this to return two new references.
template <typename K, typename D>
typename Dictionary<K, D>::TreeNode*& Dictionary<K, D>::_swap_nodes(
TreeNode*& node1, TreeNode*& node2) {
// More information on the problem we need to solve here:
// We need to swap the logical positions of these two nodes in the tree,
// but this can be hard if one of the nodes is a child of the other. Then
// one of the nodes holds the other actual pointer we're changing, so the
// rewiring is a little complicated, and since we passed in these pointers
// by reference to edit them in-place in the tree, we also end up with the
// original argument variables becoming dangerous to reuse any further
// outside of this function, where we made the call: These pointers no
// longer refer to the nodes we originally thought. As a result, we need
// to return by reference a pointer to where node1 can still be found.
// (Again, if you want to track the new locations of both nodes, you would
// need to extend the return type of this function somehow, perhaps by
// returning a std::pair of references to pointers.)
// These are value copies of the pointer arguments, so they hold copies
// of the actual addresses that we are pointing to. We need to record
// these, because when we start changing the pointers below, we'll lose
// track of these original addresses.
TreeNode* orig_node1 = node1;
TreeNode* orig_node2 = node2;
// The first case below has been fully commented, and the following cases
// are similar and symmetric, so comments have been omitted there.
if (node1->left == node2) {
// When node1 has node2 as its left child...
// The right child pointers are easy to handle.
// We can directly swap them.
std::swap(node1->right, node2->right);
// Now we have to deal with the left child pointers, and it's
// complicated. We need to be very careful about the order of changes.
// The easiest way to see how this works is draw a diagram of the
// original nodes and pointers, and see how the pointers have to be
// redirected.
// Make "node1" take its leftmost grandchild as its left child.
// The next line also affects the actual "node2" pointer, implicitly,
// so we won't try to use the "node2" pointer after this; it will no
// longer point to the original "node2" node that we would expect from
// the naming.
node1->left = orig_node2->left;
// Now the original node2 needs to take the original node1 as its left
// child.
orig_node2->left = node1;
// Now the actual node1 pointer should point to the object that was
// the original node2.
node1 = orig_node2;
// The node position swap is done, but the node1 and node2 arguments
// themselves haven't been swapped! We can't do that in this case.
// This is the actual pointer in the tree that is now pointing to what
// was our original node1 object, so return it by reference.
return node1->left;
}
else if (node1->right == node2) {
std::swap(node1->left, node2->left);
node1->right = orig_node2->right;
orig_node2->right = node1;
node1 = orig_node2;
return node1->right;
}
else if (node2->left == node1) {
std::swap(node2->right, node1->right);
node2->left = orig_node1->left;
orig_node1->left = node2;
node2 = orig_node1;
return node2->left;
}
else if (node2->right == node1) {
std::swap(node2->left, node1->left);
node2->right = orig_node1->right;
orig_node1->right = node2;
node2 = orig_node1;
return node2->right;
}
else {
// If the two nodes aren't adjacent in the tree, it's a lot easier.
// We can swap their child pointers and swap their main pointers,
// and it just works. (Again, the easiest way to see this is true is
// to draw a picture of the pointer connections between the nodes.)
std::swap(node1->left, node2->left);
std::swap(node1->right, node2->right);
std::swap(node1, node2);
// This is the actual pointer in the tree that is now pointing to what
// was our original node1 object, so return it by reference.
return node2;
}
// For future reference, here are some debugging output statements that
// might be helpful if trouble arises:
// std::cerr << "\nAfter swap: [" << node1->key << " , " << node1->data
// << " ] [ " << node2->key << " , " << node2->data << " ] " << std::endl;
// std::cerr << "\nn1: " << node1 << " n2: " << node2
// << "\n n1l: " << node1->left << " n1r: " << node1->right
// << "\n n2l: " << node2->left << " n2r: " << node2->right << std::endl;
}
| 47.152749 | 87 | 0.704 | [
"object",
"vector"
] |
0792068f914ee90a1b0a1c07991a52df3253d4e5 | 7,080 | cpp | C++ | import/abstractdelegate.cpp | TREE-Ind/mycroft-gui | ecf5cf3cfac2339d1ac82607cecd28521b3bfb33 | [
"Apache-2.0"
] | 1 | 2019-01-17T13:40:49.000Z | 2019-01-17T13:40:49.000Z | import/abstractdelegate.cpp | TREE-Ind/mycroft-gui | ecf5cf3cfac2339d1ac82607cecd28521b3bfb33 | [
"Apache-2.0"
] | null | null | null | import/abstractdelegate.cpp | TREE-Ind/mycroft-gui | ecf5cf3cfac2339d1ac82607cecd28521b3bfb33 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2018 by Marco Martin <mart@kde.org>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "abstractdelegate.h"
#include "mycroftcontroller.h"
AbstractDelegate::AbstractDelegate(QQuickItem *parent)
: QQuickItem(parent)
{
}
AbstractDelegate::~AbstractDelegate()
{
}
void AbstractDelegate::triggerEvent(const QString &eventName, const QVariantMap ¶meters)
{
if (!m_skillView) {
qWarning() << "No SkillView, this should never happen: orphan delegate?";
return;
}
if (eventName.startsWith(QStringLiteral("system."))) {
m_skillView->triggerEvent(QStringLiteral("system"), eventName, parameters);
} else if (eventName.startsWith(m_skillId + QStringLiteral("."))) {
m_skillView->triggerEvent(m_skillId, eventName, parameters);
} else {
qWarning() << "Warning: you can only trigger system events or events belonging to the skill" << m_skillId;
}
}
void AbstractDelegate::syncChildItemsGeometry(const QSizeF &size)
{
if (m_contentItem) {
m_contentItem->setX(m_leftPadding);
m_contentItem->setY(m_topPadding);
m_contentItem->setSize(QSizeF(size.width() - m_leftPadding - m_rightPadding,
size.height() - m_topPadding - m_bottomPadding));
}
if (m_backgroundItem) {
m_backgroundItem->setX(0);
m_backgroundItem->setY(0);
m_backgroundItem->setSize(size);
}
}
void AbstractDelegate::contentData_append(QQmlListProperty<QObject> *prop, QObject *object)
{
AbstractDelegate *delegate = static_cast<AbstractDelegate *>(prop->object);
if (!delegate) {
return;
}
QQuickItem *item = qobject_cast<QQuickItem *>(object);
delegate->m_contentData.append(object);
if (item) {
if (!delegate->m_contentItem) {
//qWarning()<<"Creting default contentItem";
delegate->m_contentItem = new QQuickItem(delegate);
}
item->setParentItem(delegate->m_contentItem);
}
}
int AbstractDelegate::contentData_count(QQmlListProperty<QObject> *prop)
{
AbstractDelegate *delegate = static_cast<AbstractDelegate *>(prop->object);
if (!delegate) {
return 0;
}
return delegate->m_contentData.count();
}
QObject *AbstractDelegate::contentData_at(QQmlListProperty<QObject> *prop, int index)
{
AbstractDelegate *delegate = static_cast<AbstractDelegate *>(prop->object);
if (!delegate) {
return nullptr;
}
if (index < 0 || index >= delegate->m_contentData.count()) {
return nullptr;
}
return delegate->m_contentData.value(index);
}
void AbstractDelegate::contentData_clear(QQmlListProperty<QObject> *prop)
{
AbstractDelegate *delegate = static_cast<AbstractDelegate *>(prop->object);
if (!delegate) {
return;
}
return delegate->m_contentData.clear();
}
QQmlListProperty<QObject> AbstractDelegate::contentData()
{
return QQmlListProperty<QObject>(this, nullptr,
contentData_append,
contentData_count,
contentData_at,
contentData_clear);
}
void AbstractDelegate::geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry)
{
syncChildItemsGeometry(newGeometry.size());
QQuickItem::geometryChanged(newGeometry, oldGeometry);
}
QQuickItem *AbstractDelegate::contentItem() const
{
return m_contentItem;
}
void AbstractDelegate::setContentItem(QQuickItem *item)
{
if (m_contentItem == item) {
return;
}
m_contentItem = item;
item->setParentItem(this);
m_contentItem->setX(m_leftPadding);
m_contentItem->setY(m_topPadding);
m_contentItem->setSize(QSizeF(width() - m_leftPadding - m_rightPadding,
height() - m_topPadding - m_bottomPadding));
emit contentItemChanged();
}
QQuickItem *AbstractDelegate::background() const
{
return m_backgroundItem;
}
void AbstractDelegate::setBackground(QQuickItem *item)
{
if (m_backgroundItem == item) {
return;
}
m_backgroundItem = item;
m_backgroundItem->setParentItem(this);
m_backgroundItem->setX(0);
m_backgroundItem->setY(0);
m_backgroundItem->setSize(size());
emit backgroundChanged();
}
int AbstractDelegate::leftPadding() const
{
return m_leftPadding;
}
void AbstractDelegate::setLeftPadding(int padding)
{
if (m_leftPadding == padding) {
return;
}
m_leftPadding = padding;
syncChildItemsGeometry(size());
emit leftPaddingChanged();
}
int AbstractDelegate::topPadding() const
{
return m_topPadding;
}
void AbstractDelegate::setTopPadding(int padding)
{
if (m_topPadding == padding) {
return;
}
m_topPadding = padding;
syncChildItemsGeometry(size());
emit topPaddingChanged();
}
int AbstractDelegate::rightPadding() const
{
return m_rightPadding;
}
void AbstractDelegate::setRightPadding(int padding)
{
if (m_rightPadding == padding) {
return;
}
m_rightPadding = padding;
syncChildItemsGeometry(size());
emit rightPaddingChanged();
}
int AbstractDelegate::bottomPadding() const
{
return m_bottomPadding;
}
void AbstractDelegate::setBottomPadding(int padding)
{
if (m_bottomPadding == padding) {
return;
}
m_bottomPadding = padding;
syncChildItemsGeometry(size());
emit bottomPaddingChanged();
}
void AbstractDelegate::setSkillView(AbstractSkillView *view)
{
//possible to call only once, by the skillview, setting itself upon instantiation
Q_ASSERT(!m_skillView);
m_skillView = view;
}
AbstractSkillView *AbstractDelegate::skillView() const
{
return m_skillView;
}
void AbstractDelegate::setSessionData(SessionDataMap *data)
{
//possible to call only once, by the skillview upon instantiation
Q_ASSERT(!m_data);
m_data = data;
}
SessionDataMap *AbstractDelegate::sessionData() const
{
return m_data;
}
void AbstractDelegate::setQmlUrl(const QUrl &url)
{
//possible to call only once, by the skillview upon instantiation
Q_ASSERT(m_qmlUrl.isEmpty());
m_qmlUrl = url;
}
QUrl AbstractDelegate::qmlUrl() const
{
return m_qmlUrl;
}
void AbstractDelegate::setSkillId(const QString &skillId)
{
//possible to call only once, by the skillview upon instantiation
Q_ASSERT(m_skillId.isEmpty());
m_skillId = skillId;
}
QString AbstractDelegate::skillId() const
{
return m_skillId;
}
#include "moc_abstractdelegate.cpp"
| 24.66899 | 114 | 0.684463 | [
"object"
] |
07982051f963a81046f640305fb00be9975fa105 | 3,970 | cpp | C++ | bucket_sort.cpp | ymzm/CLRS_homework | a2134374ee728fba25e65b9967bec4c1ae1a9fac | [
"MIT"
] | null | null | null | bucket_sort.cpp | ymzm/CLRS_homework | a2134374ee728fba25e65b9967bec4c1ae1a9fac | [
"MIT"
] | null | null | null | bucket_sort.cpp | ymzm/CLRS_homework | a2134374ee728fba25e65b9967bec4c1ae1a9fac | [
"MIT"
] | null | null | null | #include <vector>
#include <iostream>
#include <ctime>
using namespace std;
#define POINT_CNT 100
#define SCALE 10000
#define SIZE_SCALE 100000000
#define N (SIZE_SCALE / POINT_CNT)
typedef struct point {
struct point *next;
struct point *prev;
int x;
int y;
bool x_flag; // true means positive, false means nagetive; doesn't matter in this funciton
bool y_flag;
int distance;
}point;
static point res[POINT_CNT];
void generate_points (void){
srand((int)time(0));
//vector <point> res;
//res.resize(POINT_CNT);
for (int i=0; i<POINT_CNT; i++)
{
res[i].x = rand() % SCALE;
res[i].y = rand() & SCALE;
res[i].distance = res[i].x * res[i].x + res[i].y * res[i].y;
if ((res[i].distance == 0) || (res[i].distance > SIZE_SCALE))
{
i--;
continue;
}
res[i].x_flag = rand() % 2;
res[i].y_flag = rand() % 2;
res[i].next = NULL;
res[i].prev = NULL;
}
//return res;
}
vector <point *> bucket(POINT_CNT);
vector <point *> tail(POINT_CNT);
void bucket_sort(void){
clock_t start = clock();
for (int i=0; i<POINT_CNT; i++)
{
bucket[i] = NULL;
tail[i] = NULL;
}
// insert to bucket
for (int i=0; i<POINT_CNT; i++)
{
int bucket_number = (res[i].distance-1)/N;
if (bucket[bucket_number] != NULL)
{
res[i].next = bucket[bucket_number];
bucket[bucket_number]->prev = &res[i];
}
bucket[bucket_number] = &res[i];
}
// sort bucket[i] with insertion sort
for (int i=0; i<POINT_CNT; i++)
{
if (bucket[i] == NULL)
{
continue;
}
point *head = bucket[i];
tail[i] = head;
point *head_save = head;
point *tmp = head->next;
point *tmp2 = tmp;
head->next = NULL;
while (tmp != NULL)
{
point *prev = NULL;
tmp2 = tmp->next;
while (head && (head->distance < tmp->distance))
{
prev = head;
head = head->next;
}
if (head == NULL)
{
prev->next = tmp;
tmp->prev = prev;
tmp->next = NULL;
head = head_save;
tail[i] = tmp;
}
else{
if (head->prev == NULL)
{
tmp->next = head;
tmp->prev = NULL;
head->prev = tmp;
head_save = tmp;
head = head_save;
}
else
{
head->prev->next = tmp;
tmp->prev = head->prev;
tmp->next = head;
head->prev = tmp;
head = head_save;
}
}
bucket[i] = head_save;
tmp = tmp2;
}
}
point *tmp_tail = NULL;
point *ret_head = NULL;
for (int i=0; i<POINT_CNT; i++)
{
if (bucket[i] != NULL)
{
if (ret_head == NULL)
{
ret_head = bucket[i];
}
else{
bucket[i]->prev = tmp_tail;
tmp_tail->next = bucket[i];
}
tmp_tail = tail[i];
}
}
clock_t ends = clock();
cout << "point cnt: " << POINT_CNT << endl;
cout <<"Running Time : "<<(double)(ends - start)/ CLOCKS_PER_SEC << endl;
cout << "test end" << endl;
#if 1
point *tmp = ret_head;
int i=0;
while (tmp)
{
cout << i << " "<< tmp->distance << " " << tmp->x << " " << tmp->y << endl;
i++;
tmp = tmp->next;
}
#endif
}
int main(void)
{
generate_points();
bucket_sort();
return 0;
}
| 23.772455 | 94 | 0.430479 | [
"vector"
] |
07991fca530e165407d49e0bff0233f06a8fa08e | 1,339 | cpp | C++ | examples/basic_example.cpp | FireFlyForLife/FlatValueMap | 125c2a4a0d562a0dd447532488afaf2cc2a9d7bb | [
"MIT"
] | 2 | 2019-11-19T10:59:18.000Z | 2019-11-20T09:28:02.000Z | examples/basic_example.cpp | FireFlyForLife/FlatValueMap | 125c2a4a0d562a0dd447532488afaf2cc2a9d7bb | [
"MIT"
] | 1 | 2019-10-02T16:53:54.000Z | 2019-10-02T18:36:00.000Z | examples/basic_example.cpp | FireFlyForLife/FlatValueMap | 125c2a4a0d562a0dd447532488afaf2cc2a9d7bb | [
"MIT"
] | null | null | null | #include <flat_value_map_handle.h>
#include <flat_value_map.h>
#include <cassert>
#include <iostream>
using namespace cof;
class Entity
{
public:
Entity() : name(), tags{}
{}
Entity(std::string name, std::vector<std::string> tags) : name(std::move(name)), tags{ std::move(tags) }
{}
virtual ~Entity() = default;
std::string name;
std::vector<std::string> tags{};
friend bool operator==(const Entity& lhs, const Entity& rhs)
{
return lhs.name == rhs.name
&& lhs.tags == rhs.tags;
}
friend bool operator!=(const Entity& lhs, const Entity& rhs) { return !(lhs == rhs); }
};
using EntityHandle = FvmHandle<Entity>;
int example_main(int argc, char* argv[])
{
FlatValueMap<EntityHandle, Entity> entities{};
auto dogHandle = entities.push_back(Entity{ "Dog", {"Animal", "Good boi"} });
auto catHandle = entities.push_back(Entity{ "Cat", {"Animal", "Lazy"} });
for (Entity& entity : entities) {
if (entity == Entity{ "Cat", {"Animal", "Lazy"} }) {
std::cout << "I know this one!\n";
} else {
std::cout << "Unknown entity detected! named: " << entity.name << '\n';
}
}
Entity& dog = entities[dogHandle];
std::cout << "I'm going to play fetch with: " << dog.name << '\n';
entities.erase(dogHandle);
assert(entities.size() == 1);
entities.erase(catHandle);
assert(entities.empty());
return 0;
}
| 22.694915 | 105 | 0.644511 | [
"vector"
] |
07a0066a9c5a4674c77ae60ae75c29f4e942aace | 2,721 | cpp | C++ | Sorting Algorithms/Frequency Sort.cpp | Edith-3000/Algorithmic-Implementations | 7ff8cd615fd453a346b4e851606d47c26f05a084 | [
"MIT"
] | 8 | 2021-02-13T17:07:27.000Z | 2021-08-20T08:20:40.000Z | Sorting Algorithms/Frequency Sort.cpp | Edith-3000/Algorithmic-Implementations | 7ff8cd615fd453a346b4e851606d47c26f05a084 | [
"MIT"
] | null | null | null | Sorting Algorithms/Frequency Sort.cpp | Edith-3000/Algorithmic-Implementations | 7ff8cd615fd453a346b4e851606d47c26f05a084 | [
"MIT"
] | 5 | 2021-02-17T18:12:20.000Z | 2021-10-10T17:49:34.000Z | /* Ref: https://www.geeksforgeeks.org/sort-elements-by-frequency/
https://www.educative.io/edpresso/the-frequency-sort-algorithm
Question based on this concept --->
https://leetcode.com/problems/sort-array-by-increasing-frequency/
https://leetcode.com/problems/sort-characters-by-frequency/
*/
/* The frequency sort algorithm is used to output elements of an array in descending order of their
frequencies.
NOTE: If two elements have the same frequencies, then the element that occurs first in the input is
printed first.
*/
// The frequency sort algorithm can be implemented in many ways.
// Below implementation uses a hash table.
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define ull unsigned long long
#define pb push_back
#define mp make_pair
#define F first
#define S second
#define PI 3.1415926535897932384626
#define deb(x) cout << #x << "=" << x << endl
#define deb2(x, y) cout << #x << "=" << x << ", " << #y << "=" << y << endl
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef vector<ull> vull;
typedef vector<pii> vpii;
typedef vector<pll> vpll;
typedef vector<vi> vvi;
typedef vector<vll> vvll;
typedef vector<vull> vvull;
mt19937_64 rang(chrono::high_resolution_clock::now().time_since_epoch().count());
int rng(int lim) {
uniform_int_distribution<int> uid(0,lim-1);
return uid(rang);
}
const int INF = 0x3f3f3f3f;
const int mod = 1e9+7;
class cmp {
public:
bool operator() (const pair<int, pii> &p1, const pair<int, pii> &p2) {
if(p1.S.F == p2.S.F) return p1.S.S < p2.S.S;
return p1.S.F > p2.S.F;
}
};
vi frequency_sort(vi &v, int n) {
if(n <= 0) return vi();
unordered_map<int, pii> hash;
for(int i = 0; i < n; i++) {
if(hash.find(v[i]) != hash.end()) hash[v[i]].F++;
else hash[v[i]] = {1, i};
}
vector<pair<int, pii>> t;
for(auto it = hash.begin(); it != hash.end(); it++) {
t.pb({it->F, it->S});
}
sort(t.begin(), t.end(), cmp());
vi res;
for(int i = 0; i < (int)t.size(); i++) {
int cnt = t[i].S.F;
while(cnt--) res.pb(t[i].F);
}
return res;
}
void solve()
{
int n; cin >> n;
vi v(n);
for(int i = 0; i < n; i++) cin >> v[i];
vi res = frequency_sort(v, n);
for(auto x: res) cout << x << " ";
cout << "\n";
}
int main()
{
ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
srand(chrono::high_resolution_clock::now().time_since_epoch().count());
// #ifndef ONLINE_JUDGE
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
// #endif
int t = 1;
// cin >> t;
while(t--) {
solve();
}
return 0;
} | 24.513514 | 102 | 0.619993 | [
"vector"
] |
07a13019d0ed9ef2fbf1432fbc7f97acb12fe13b | 2,513 | cpp | C++ | tools/ifaceed/ifaceed/history/scenenodes/scenesnodeschangename.cpp | mamontov-cpp/saddy | f20a0030e18af9e0714fe56c19407fbeacc529a7 | [
"BSD-2-Clause"
] | 58 | 2015-08-09T14:56:35.000Z | 2022-01-15T22:06:58.000Z | tools/ifaceed/ifaceed/history/scenenodes/scenesnodeschangename.cpp | mamontov-cpp/saddy-graphics-engine-2d | e25a6637fcc49cb26614bf03b70e5d03a3a436c7 | [
"BSD-2-Clause"
] | 245 | 2015-08-08T08:44:22.000Z | 2022-01-04T09:18:08.000Z | tools/ifaceed/ifaceed/history/scenenodes/scenesnodeschangename.cpp | mamontov-cpp/saddy | f20a0030e18af9e0714fe56c19407fbeacc529a7 | [
"BSD-2-Clause"
] | 23 | 2015-12-06T03:57:49.000Z | 2020-10-12T14:15:50.000Z | #include "scenenodeschangename.h"
// ReSharper disable once CppUnusedIncludeDirective
#include <db/save.h>
// ReSharper disable once CppUnusedIncludeDirective
#include <QLineEdit>
#include "../../core/editor.h"
#include "../../qstdstring.h"
#include "../../blockedclosuremethodcall.h"
#include "../../closuremethodcall.h"
#include "../../gui/uiblocks/uiblocks.h"
#include "../../gui/uiblocks/uisceneblock.h"
#include "../../gui/uiblocks/uianimationinstanceblock.h"
#include "../../gui/actions/actions.h"
#include "../../gui/actions/labelactions.h"
#include "../../gui/actions/sceneactions.h"
#include "../../gui/actions/gridactions.h"
#include "../../gui/actions/scenenodeactions.h"
Q_DECLARE_METATYPE(sad::db::Object*) //-V566
history::scenenodes::ChangeName::ChangeName(
sad::SceneNode* d,
const sad::String& old_value,
const sad::String& new_value
)
: history::scenenodes::ChangeProperty<sad::String>(
d,
"name",
old_value,
new_value
)
{
}
history::scenenodes::ChangeName::~ChangeName()
{
}
void history::scenenodes::ChangeName::tryUpdateUI(core::Editor* e, const sad::String& value)
{
this->history::scenenodes::ChangeProperty<sad::String>::tryUpdateUI(e, value);
if (m_node->scene() == e->actions()->sceneActions()->currentScene())
{
e->emitClosure( ::bind(e->actions()->sceneNodeActions(), &gui::actions::SceneNodeActions::updateSceneNodeName, m_node, true));
}
e->emitClosure( ::bind(this, &history::scenenodes::ChangeName::updateDependent, e));
e->emitClosure( ::bind(e->actions()->gridActions(), &gui::actions::GridActions::tryUpdateNodeNameInGrid, m_node) );
}
void history::scenenodes::ChangeName::updateUI(core::Editor* e, const sad::String& value)
{
e->emitClosure( ::bind(
this,
&history::Command::blockedSetLineEditText,
e->uiBlocks()->uiSceneBlock()->txtSceneName,
STD2QSTRING(value.c_str())
)
);
}
// ReSharper disable once CppMemberFunctionMayBeConst
void history::scenenodes::ChangeName::updateDependent(core::Editor * e)
{
gui::actions::SceneNodeActions* sn_actions = e->actions()->sceneNodeActions();
QComboBox* c = e->uiBlocks()->uiAnimationInstanceBlock()->cmbAnimationInstanceObject;
int pos = sn_actions->findInComboBox<sad::db::Object*>(c, m_node);
if (pos > - 1)
{
c->setItemText(pos, sn_actions->fullNameForNode(m_node));
}
}
| 31.024691 | 135 | 0.657382 | [
"object"
] |
07a480b47907c979c1c5d2e20db0f7d6cf5f001c | 7,910 | cc | C++ | Geometry/GEMGeometryBuilder/src/ME0GeometryBuilderFromDDD.cc | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | Geometry/GEMGeometryBuilder/src/ME0GeometryBuilderFromDDD.cc | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | Geometry/GEMGeometryBuilder/src/ME0GeometryBuilderFromDDD.cc | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | /** Implementation of the ME0 Geometry Builder from DDD
*
* \author Port of: MuDDDME0Builder (ORCA)
* \author M. Maggi - INFN Bari
* \edited by D. Nash
*/
#include "Geometry/GEMGeometryBuilder/src/ME0GeometryBuilderFromDDD.h"
#include "Geometry/GEMGeometry/interface/ME0Geometry.h"
#include "Geometry/GEMGeometry/interface/ME0Chamber.h"
#include "Geometry/GEMGeometry/interface/ME0EtaPartitionSpecs.h"
#include <DetectorDescription/Core/interface/DDFilter.h>
#include <DetectorDescription/Core/interface/DDFilteredView.h>
#include <DetectorDescription/Core/interface/DDSolid.h>
#include "Geometry/MuonNumbering/interface/MuonDDDNumbering.h"
#include "Geometry/MuonNumbering/interface/MuonBaseNumber.h"
#include "Geometry/MuonNumbering/interface/ME0NumberingScheme.h"
#include "DataFormats/GeometrySurface/interface/RectangularPlaneBounds.h"
#include "DataFormats/GeometrySurface/interface/TrapezoidalPlaneBounds.h"
#include "DataFormats/GeometryVector/interface/Basic3DVector.h"
#include "CLHEP/Units/GlobalSystemOfUnits.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include <iostream>
#include <algorithm>
#include <boost/lexical_cast.hpp>
ME0GeometryBuilderFromDDD::ME0GeometryBuilderFromDDD()
{
LogDebug("ME0GeometryBuilderfromDDD") <<"[ME0GeometryBuilderFromDDD::constructor]";
}
ME0GeometryBuilderFromDDD::~ME0GeometryBuilderFromDDD()
{ }
ME0Geometry* ME0GeometryBuilderFromDDD::build(const DDCompactView* cview, const MuonDDDConstants& muonConstants)
{
std::string attribute = "ReadOutName";
std::string value = "MuonME0Hits";
// Asking only for the MuonME0's
DDSpecificsMatchesValueFilter filter{DDValue(attribute, value, 0.0)};
DDFilteredView fview(*cview,filter);
return this->buildGeometry(fview, muonConstants);
}
ME0Geometry* ME0GeometryBuilderFromDDD::buildGeometry(DDFilteredView& fview, const MuonDDDConstants& muonConstants)
{
LogDebug("ME0GeometryBuilderFromDDD") <<"Building the geometry service";
ME0Geometry* geometry = new ME0Geometry();
LogDebug("ME0GeometryBuilderFromDDD") << "About to run through the ME0 structure\n"
<<" First logical part "
<<fview.logicalPart().name().name();
bool doSubDets = fview.firstChild();
LogDebug("ME0GeometryBuilderFromDDD") << "doSubDets = " << doSubDets;
LogDebug("ME0GeometryBuilderFromDDD") <<"start the loop";
int nChambers(0);
while (doSubDets)
{
// Get the Base Muon Number
MuonDDDNumbering mdddnum(muonConstants);
LogDebug("ME0GeometryBuilderFromDDD") <<"Getting the Muon base Number";
MuonBaseNumber mbn = mdddnum.geoHistoryToBaseNumber(fview.geoHistory());
LogDebug("ME0GeometryBuilderFromDDD") <<"Start the ME0 Numbering Schema";
ME0NumberingScheme me0num(muonConstants);
ME0DetId rollDetId(me0num.baseNumberToUnitNumber(mbn));
LogDebug("ME0GeometryBuilderFromDDD") << "ME0 eta partition rawId: " << rollDetId.rawId() << ", detId: " << rollDetId;
// chamber id for this partition. everything is the same; but partition number is 0 and layer number is 0.
ME0DetId chamberId(rollDetId.chamberId());
LogDebug("ME0GeometryBuilderFromDDD") << "ME0 chamber rawId: " << chamberId.rawId() << ", detId: " << chamberId;
//Commented out, we don't have stations
//const int stationId(rollDetId.station());
//if (stationId > maxStation) maxStation = stationId;
if (rollDetId.roll()==1) ++nChambers;
std::vector<double> dpar=fview.logicalPart().solid().parameters();
std::string name = fview.logicalPart().name().name();
DDTranslation tran = fview.translation();
DDRotationMatrix rota = fview.rotation();
Surface::PositionType pos(tran.x()/cm, tran.y()/cm, tran.z()/cm);
// CLHEP way
// Surface::RotationType rot(rota.xx(),rota.xy(),rota.xz(),
// rota.yx(),rota.yy(),rota.yz(),
// rota.zx(),rota.zy(),rota.zz());
//ROOT::Math way
DD3Vector x, y, z;
rota.GetComponents(x,y,z);
// doesn't this just re-inverse???
Surface::RotationType rot(float(x.X()), float(x.Y()), float(x.Z()),
float(y.X()), float(y.Y()), float(y.Z()),
float(z.X()), float(z.Y()), float(z.Z()));
float be = dpar[4]/cm; // half bottom edge
float te = dpar[8]/cm; // half top edge
float ap = dpar[0]/cm; // half apothem
float ti = 0.4/cm; // half thickness
// TrapezoidalPlaneBounds*
Bounds* bounds = new TrapezoidalPlaneBounds(be, te, ap, ti);
std::vector<float> pars;
pars.emplace_back(be);
pars.emplace_back(te);
pars.emplace_back(ap);
float nStrips = -999.;
float nPads = -999.;
pars.emplace_back(nStrips);
pars.emplace_back(nPads);
LogDebug("ME0GeometryBuilderFromDDD")
<< "ME0 " << name << " par " << be << " " << te << " " << ap << " " << dpar[0];
ME0EtaPartitionSpecs* e_p_specs = new ME0EtaPartitionSpecs(GeomDetEnumerators::ME0, name, pars);
//Change of axes for the forward
Basic3DVector<float> newX(1.,0.,0.);
Basic3DVector<float> newY(0.,0.,1.);
// if (tran.z() > 0. )
newY *= -1;
Basic3DVector<float> newZ(0.,1.,0.);
rot.rotateAxes (newX, newY, newZ);
BoundPlane* bp = new BoundPlane(pos, rot, bounds);
ReferenceCountingPointer<BoundPlane> surf(bp);
// Set EtaPartition of RollDetId equal to 1
ME0DetId rollDetId2(rollDetId.region(),rollDetId.layer(),rollDetId.station(),1);
ME0EtaPartition* mep = new ME0EtaPartition(rollDetId2, surf, e_p_specs);
// For Nick ... build also the layer
ME0DetId layerDetId(rollDetId.layerId());
ME0Layer* ml = new ME0Layer(layerDetId, surf);
// Add the eta partition to the geometry
geometry->add(mep);
// Add the eta partition to the layer
ml->add(mep);
// Add the layer to the geometry
geometry->add(ml);
// go to next layer
doSubDets = fview.nextSibling();
}
auto& partitions(geometry->etaPartitions());
// build the chambers and add them to the geometry
std::vector<ME0DetId> vDetId;
//int oldRollNumber = 1;
int oldLayerNumber = 1;
for (unsigned i=1; i<=partitions.size(); ++i){
ME0DetId detId(partitions.at(i-1)->id());
LogDebug("ME0GeometryBuilderFromDDD") << "Making ME0DetId = " <<detId;
//The GEM methodology depended on rollNumber changing from chamber to chamber, we need to use layer ID
//const int rollNumber(detId.roll());
// new batch of eta partitions --> new chamber
//if (rollNumber < oldRollNumber || i == partitions.size()) {
const int layerNumber(detId.layer());
if (layerNumber < oldLayerNumber || i == partitions.size()) {
// don't forget the last partition for the last chamber
if (i == partitions.size()) vDetId.emplace_back(detId);
ME0DetId fId(vDetId.front());
ME0DetId chamberId(fId.chamberId());
LogDebug("ME0GeometryBuilderFromDDD") << "ME0DetId = " << fId ;
LogDebug("ME0GeometryBuilderFromDDD") << "ME0ChamberId = " << chamberId ;
// compute the overall boundplane using the first eta partition
const ME0EtaPartition* p(geometry->etaPartition(fId));
const BoundPlane& bps = p->surface();
BoundPlane* bp = const_cast<BoundPlane*>(&bps);
ReferenceCountingPointer<BoundPlane> surf(bp);
ME0Chamber* ch = new ME0Chamber(chamberId, surf);
LogDebug("ME0GeometryBuilderFromDDD") << "Creating chamber " << chamberId << " with " << vDetId.size() << " eta partitions";
for(auto id : vDetId){
LogDebug("ME0GeometryBuilderFromDDD") << "Adding eta partition " << id << " to ME0 chamber";
ch->add(const_cast<ME0EtaPartition*>(geometry->etaPartition(id)));
}
LogDebug("ME0GeometryBuilderFromDDD") << "Adding the chamber to the geometry";
geometry->add(ch);
vDetId.clear();
}
vDetId.emplace_back(detId);
oldLayerNumber = layerNumber;
}
return geometry;
}
| 36.790698 | 131 | 0.686599 | [
"geometry",
"vector",
"solid"
] |
07a96d965b6ee672a9d73717bfd816ec6bedc330 | 2,792 | hpp | C++ | include/york/Registry.hpp | mxtt-mmxix/York-Engine | a4592757b2fe52b4737c87ba59546dce2e90b9dd | [
"BSD-2-Clause"
] | null | null | null | include/york/Registry.hpp | mxtt-mmxix/York-Engine | a4592757b2fe52b4737c87ba59546dce2e90b9dd | [
"BSD-2-Clause"
] | null | null | null | include/york/Registry.hpp | mxtt-mmxix/York-Engine | a4592757b2fe52b4737c87ba59546dce2e90b9dd | [
"BSD-2-Clause"
] | null | null | null | /*
* BSD 2-Clause License
*
* Copyright (c) 2022 Matthew McCall
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
//
// Created by Matthew McCall on 2/20/22.
//
#ifndef YORK_REGISTRY_HPP
#define YORK_REGISTRY_HPP
#include <functional>
#include "Containers.hpp"
namespace york {
class EventHandler;
struct Event;
/**
* A singleton class for sharing data between multiple instances of York-Engine.
*
* Currently, the Runtime links with York-Engine. On most modern operating systems, this results in the Engine library being loaded twice, with the Runtime and your Client have their own copies loaded. As a result these two copies of the Engine have their own memory allocated. Thus, internal data structures created in one copy will not be available in the other copy. As such, the `Registry` will contain the necessary data initialized by the Runtime for use in your client. You need to accept this `Registry` and pass it to the base constructor of the `Layer`.
*/
class Registry {
friend EventHandler;
friend void broadcastEvent(Event e);
public:
Registry(const Registry&) = delete;
/**
* Please do not call this method in your client.
*
* The Registry will be passed in the createFunction.
*
* @return The Registry
*/
static Registry& getInstance();
private:
Registry() = default;
Vector<std::reference_wrapper<EventHandler>> m_eventHandlers;
};
extern "C" void registerRegistry(Registry& registry);
}
#endif // YORK_REGISTRY_HPP
| 36.736842 | 563 | 0.75 | [
"vector"
] |
07abb28fe1d500e83f2d8e5b2cef082c97d0e1ee | 1,511 | cpp | C++ | src/e001_100/q1346.cpp | extremedeckguru/leetcode | e45923ccbca7ae1c5f85d8c996392e8b492c1306 | [
"MIT"
] | 9 | 2020-04-09T12:37:50.000Z | 2021-04-01T14:01:14.000Z | src/e001_100/q1346.cpp | extremedeckguru/leetcode | e45923ccbca7ae1c5f85d8c996392e8b492c1306 | [
"MIT"
] | 3 | 2020-05-05T02:43:54.000Z | 2020-05-20T11:12:16.000Z | src/e001_100/q1346.cpp | extremedeckguru/leetcode | e45923ccbca7ae1c5f85d8c996392e8b492c1306 | [
"MIT"
] | 5 | 2020-04-17T02:32:10.000Z | 2020-05-20T10:12:26.000Z | /*
#面试刷题# 第0028期
#Leetcode# Q1346 检查N及其2倍的值是否存在
难度:低
给定整数数组arr,请检查是否存在两个整数N和M,以使N为M的两倍(即N = 2 * M)。
更正式地检查是否存在两个索引i和j,使得:
(1) i != j
(2) 0 <= i, j < arr.length
(3) arr[i] == 2 * arr[j]
约束条件:
(a) 2 <= arr.length <= 500
(b) -10^3 <= arr[i] <= 10^3
例1:
Input: arr = [10,2,5,3]
Output: true
Explanation: N = 10 is the double of M = 5,that is, 10 = 2 * 5.
例2:
Input: arr = [7,1,14,11]
Output: true
Explanation: N = 14 is the double of M = 7,that is, 14 = 2 * 7.
例3:
Input: arr = [3,1,7,11]
Output: false
Explanation: In this case does not exist N and M, such that N = 2 * M.
*/
#include "leetcode.h"
namespace q1346{
template<typename T>
bool run_testcases() {
T slt;
// place testcases below
{
vector<int> arr{10,2,5,3};
CHECK_RET(true == slt.checkIfExist(arr));
}
{
vector<int> arr{7,1,14,11};
CHECK_RET(true == slt.checkIfExist(arr));
}
{
vector<int> arr{3,1,7,11};
CHECK_RET(false == slt.checkIfExist(arr));
}
// succ
return true;
}
class Solution {
public:
// Runtime: 8 ms, faster than 79.28%
// Memory Usage: 9.2 MB, less than 100.00%
bool checkIfExist(vector<int>& arr) {
unordered_set<int> buff;
for (auto & v : arr) {
if (buff.count(2*v) || (0==v%2 && buff.count(v/2))) {
return true;
}
buff.insert(v);
}
return false;
}
};
TEST(Q1346, Solution) {EXPECT_EQ(q1346::run_testcases<q1346::Solution>(), true);}
}; | 20.69863 | 81 | 0.56188 | [
"vector"
] |
07ae78878217b138f1021828d10769ec2f842403 | 1,255 | cpp | C++ | Arrays/SubarrayWithGivenSumOptimized.cpp | sanp9/DSA-Questions | f265075b83f66ec696576be3eaa5517ee387d5cf | [
"MIT"
] | null | null | null | Arrays/SubarrayWithGivenSumOptimized.cpp | sanp9/DSA-Questions | f265075b83f66ec696576be3eaa5517ee387d5cf | [
"MIT"
] | null | null | null | Arrays/SubarrayWithGivenSumOptimized.cpp | sanp9/DSA-Questions | f265075b83f66ec696576be3eaa5517ee387d5cf | [
"MIT"
] | null | null | null | //? Problem - Given an unsorted array A of size N of non-negative integers, find a continuous subarray which adds to a given number S.
//? Constraints: 1 <= N <= 10^5, 0 <= Ai <= 10^10
//* O(n) Solution
#include <iostream>
#include <vector> // Imported for vector<> Template
#include <climits> // Imported for INT_MIN / INT_MAX
#include <algorithm> // Imported for min() / max() function
using namespace std; //using standards
void subGivenSum(vector<int> v, int n, int s) // function definition
{
int i = 0;
int j = 0;
int sum = 0;
if (s == 0)
{
auto pos = find(v.begin(), v.end(), s);
cout << (pos - v.begin()) + 1;
return;
}
while (j < n)
{
sum += v[j];
while (sum > s)
{
sum -= v[i];
i++;
}
if (sum == s)
{
cout << i + 1 << " " << j + 1;
return;
}
j++;
}
}
int main()
{
int n, s;
cin >> n; // Input Size Of Array
cin >> s;
vector<int> v;
for (int i = 0; i < n; i++)
{
int e;
cin >> e;
v.push_back(e); // Initialize Array
}
subGivenSum(v, n, s); // Function to, function Definition at Line 13
return 0;
} | 20.57377 | 134 | 0.486056 | [
"vector"
] |
07b2818fde57042efddcdae6ee4ef82c64b88857 | 1,596 | hpp | C++ | renderer/Scene.hpp | AdrienVannson/3D-Renderer | 78148e88b9ab91ccaea0f883a746ee93cac5d767 | [
"MIT"
] | null | null | null | renderer/Scene.hpp | AdrienVannson/3D-Renderer | 78148e88b9ab91ccaea0f883a746ee93cac5d767 | [
"MIT"
] | null | null | null | renderer/Scene.hpp | AdrienVannson/3D-Renderer | 78148e88b9ab91ccaea0f883a746ee93cac5d767 | [
"MIT"
] | 1 | 2021-03-18T08:05:35.000Z | 2021-03-18T08:05:35.000Z | #ifndef SCENE_HPP
#define SCENE_HPP
#include <vector>
#include <cmath>
#include "AccelerationStructure.hpp"
#include "Camera.hpp"
#include "Vect.hpp"
#include "Light.hpp"
#include "Object.hpp"
#include "Material.hpp"
#include "objects/Group.hpp"
#include <QString>
#include <QFile>
#include <QTextStream>
class Scene
{
public:
Scene ();
~Scene ();
inline Camera* camera () { return m_camera; }
inline AccelerationStructure* accelerationStructure ()
{
return m_accelerationStructure;
}
inline void setAccelerationStructure (AccelerationStructure *accelerationStructure)
{
delete m_accelerationStructure;
m_accelerationStructure = accelerationStructure;
}
inline Object *sceneRoot () { return m_root; }
inline void addObject (Object *object) { m_root->addObject(object); }
inline const std::vector<Light*>& lights () const { return m_lights; }
inline void addLight (Light *light) { m_lights.push_back(light); }
inline Color backgroundColor () const { return m_backgroundColor; }
inline void setBackgroundColor (const Color &backgroundColor) { m_backgroundColor = backgroundColor; }
void load (QString filename, const std::vector<Material> &materials={});
// Rendering
void init();
double collisionDate (const Ray &ray) const;
Color color (const Ray &ray, const int remainingDepth) const;
private:
AccelerationStructure *m_accelerationStructure;
Camera *m_camera;
Group *m_root;
std::vector<Light*> m_lights;
Color m_backgroundColor;
};
#endif // SCENE_HPP
| 23.820896 | 106 | 0.70614 | [
"object",
"vector"
] |
07b5079db3d43ba7211354df920682af2897bf47 | 7,562 | cxx | C++ | src/CalCalib/IntNonlinMgr.cxx | fermi-lat/CalXtalResponse | 3bd209402fa2d1ba3bb13e6a6228ea16881a3dc8 | [
"BSD-3-Clause"
] | null | null | null | src/CalCalib/IntNonlinMgr.cxx | fermi-lat/CalXtalResponse | 3bd209402fa2d1ba3bb13e6a6228ea16881a3dc8 | [
"BSD-3-Clause"
] | null | null | null | src/CalCalib/IntNonlinMgr.cxx | fermi-lat/CalXtalResponse | 3bd209402fa2d1ba3bb13e6a6228ea16881a3dc8 | [
"BSD-3-Clause"
] | null | null | null | // $Header: /nfs/slac/g/glast/ground/cvs/CalXtalResponse/src/CalCalib/IntNonlinMgr.cxx,v 1.11 2008/01/22 20:14:47 fewtrell Exp $
/** @file
@author Z.Fewtrell
*/
// LOCAL
#include "IntNonlinMgr.h"
// GLAST
#include "CalibData/DacCol.h"
// EXTLIB
// STD
#include <algorithm>
using namespace CalUtil;
using namespace idents;
IntNonlinMgr::IntNonlinMgr(CalCalibShared &ccsShared) :
CalibItemMgr(ICalibPathSvc::Calib_CAL_IntNonlin,
ccsShared,
CalUtil::RngIdx::N_VALS,
N_SPLINE_TYPES)
{
}
const vector<float> *IntNonlinMgr::getInlAdc(const CalUtil::RngIdx rngIdx) {
// make sure we have valid calib data for this event.
StatusCode sc;
sc = updateCalib();
if (sc.isFailure()) return NULL;
CalibData::IntNonlin const*const inl = (CalibData::IntNonlin*)m_rngBases[rngIdx];
if (!inl) return NULL;
return inl->getValues();
}
const vector<float> *IntNonlinMgr::getInlCIDAC(const CalUtil::RngIdx rngIdx) {
// make sure we have valid calib data for this event.
StatusCode sc;
sc = updateCalib();
if (sc.isFailure()) return NULL;
// return 0 if array is empty
if (m_CIDACs[rngIdx].size() == 0)
return NULL;
return &(m_CIDACs[rngIdx]);
}
/** return y3 such that (y2 - y1)/(x2 - x1) = (y3 - y2)/(x3 - x2)
*/
template <class Ty>
inline Ty extrap(Ty x1, Ty x2, Ty x3, Ty y1, Ty y2) {
return (x3-x2)*(y2-y1)/(x2-x1) + y2;
}
StatusCode IntNonlinMgr::genLocalStore() {
for (RngIdx rngIdx; rngIdx.isValid(); rngIdx++) {
const vector<float> *adc;
const RngNum rng = rngIdx.getRng();
//-- IDEAL MODE --//
if (m_idealMode) {
adc = m_idealINL[rng].get()->getValues();
const vector<float> *cidac = m_idealINL[rng].get()->getSdacs();
m_CIDACs[rngIdx].resize(cidac->size());
copy(cidac->begin(),
cidac->end(),
m_CIDACs[rngIdx].begin());
m_rngBases[rngIdx] = m_idealINL[rng].get();
}
//-- NORMAL (NON-IDEAL) MODE -//
else {
CalibData::IntNonlin const*const intNonlin
= (CalibData::IntNonlin *)getRangeBase(rngIdx.getCalXtalId());
// support partial LAT
if (!intNonlin) continue;
if (!validateRangeBase(intNonlin)) continue;
m_rngBases[rngIdx] = intNonlin;
// quick check that ADC data is present
adc = intNonlin->getValues();
// support partial LAT
if (!adc) continue;
//-- PHASE 1: populate CIDAC values (needed for spline generation )
//-- 1st choice, use per-channel 'sdac' info if present
const vector<float> *cidac = intNonlin->getSdacs();
if (cidac) {
m_CIDACs[rngIdx].resize(cidac->size());
copy(cidac->begin(),
cidac->end(),
m_CIDACs[rngIdx].begin());
}
//-- 2nd choise, fall back to global 'DacCol' info
else {
//get collection of associated DAC vals
CalibData::DacCol const*const intNonlinDacCol =
m_calibBase->getDacCol((CalXtalId::AdcRange)rng);
const vector<unsigned> *globalCIDACs;
globalCIDACs = intNonlinDacCol->getDacs();
// if we've gotten this far, then we need
// the data to be present. can't have ADC
// values for a channel w/ no matchin DAC
// info
if (!globalCIDACs) {
// create MsgStream only when needed (for performance)
MsgStream msglog(m_ccsShared.m_service->msgSvc(), m_ccsShared.m_service->name());
msglog << MSG::ERROR << "ADC data w/ no matching CIDAC data (either per-channel or global) ADC channel: "
<< rngIdx.val()
<< endreq;
return StatusCode::FAILURE;
}
m_CIDACs[rngIdx].resize(globalCIDACs->size());
copy(globalCIDACs->begin(),
globalCIDACs->end(),
m_CIDACs[rngIdx].begin());
}
}
//-- check that we have enough points
const vector<float> &cidac = m_CIDACs[rngIdx];
if (cidac.size() < adc->size()) {
MsgStream msglog(m_ccsShared.m_service->msgSvc(), m_ccsShared.m_service->name());
msglog << MSG::ERROR << "Not enough CIDAC points for ADC channel: " << rngIdx.val()
<< endreq;
return StatusCode::FAILURE;
}
//-- PHASE 2: generate splines
vector<float> sp_cidac;
vector<float> sp_adc;
int n = min(adc->size(),cidac.size());
// we need extra point for low end extrapolation
sp_cidac.resize(n+1);
sp_adc.resize(n+1);
// create float vector for input to genSpline()
// leave point at beginning of vector for low end extrapolation
copy(adc->begin(), adc->begin() + n, sp_adc.begin()+1);
copy(cidac.begin(), cidac.begin() + n, sp_cidac.begin()+1);
// EXTRAPOLATE
sp_cidac[0] = -200;
sp_adc[0] = extrap(sp_cidac[2], sp_cidac[1], sp_cidac[0],
sp_adc[2], sp_adc[1]);
// put rng id string into spline name
ostringstream rngStr;
rngStr << '[' << rngIdx.getCalXtalId()
<< ']';
genSpline(INL_SPLINE, rngIdx, "INL" + rngStr.str(),
sp_adc, sp_cidac);
genSpline(INV_INL_SPLINE, rngIdx, "invINL" + rngStr.str(),
sp_cidac, sp_adc);
}
return StatusCode::SUCCESS;
}
StatusCode IntNonlinMgr::loadIdealVals() {
const unsigned short maxADC = 4095;
//-- SANITY CHECKS --//
if (m_ccsShared.m_idealCalib.inlADCPerCIDAC.size() != RngNum::N_VALS) {
// create MsgStream only when needed (for performance)
MsgStream msglog(m_ccsShared.m_service->msgSvc(), m_ccsShared.m_service->name());
msglog << MSG::ERROR << "Bad # of ADCPerCIDAC vals in ideal CalCalib xml file"
<< endreq;
return StatusCode::FAILURE;
}
// ideal mode just uses straigt line so we only
// need 2 points per spline
vector<float> idealADCs(2);
vector<float> idealCIDACs(2);
for (RngNum rng; rng.isValid(); rng++) {
// inl spline is pedestal subtracted.
const float pedestal = m_ccsShared.m_idealCalib.pedVals[rng.val()];
float maxADCPed = maxADC - pedestal;
// optionally clip MAX ADC in HEX1 range to ULD value supplied by tholdci
if (rng == HEX1)
maxADCPed = min<float>(maxADCPed, m_ccsShared.m_idealCalib.ciULD[HEX1.val()]);
idealADCs[0] = 0;
idealADCs[1] = maxADCPed;
idealCIDACs[0] = 0;
idealCIDACs[1] =
maxADCPed / m_ccsShared.m_idealCalib.inlADCPerCIDAC[rng.val()];
m_idealINL[rng].reset(new CalibData::IntNonlin(&idealADCs, 0, &idealCIDACs));
}
return StatusCode::SUCCESS;
}
bool IntNonlinMgr::validateRangeBase(CalibData::IntNonlin const*const intNonlin) {
if (!intNonlin) return false;
//get vector of vals
const vector<float> *intNonlinVec = intNonlin->getValues();
if (!intNonlinVec)
return false;
return true;
}
StatusCode IntNonlinMgr::evalCIDAC(const CalUtil::RngIdx rngIdx, const float adc, float &cidac) {
if (evalSpline(INL_SPLINE, rngIdx, adc, cidac).isFailure())
return StatusCode::FAILURE;
// ceiling check
cidac = min(m_splineYMax[INL_SPLINE][rngIdx],cidac);
return StatusCode::SUCCESS;
}
StatusCode IntNonlinMgr::evalADC(const CalUtil::RngIdx rngIdx, const float cidac, float &adc) {
if (evalSpline(INV_INL_SPLINE, rngIdx, cidac, adc).isFailure())
return StatusCode::FAILURE;
// ceiling check
adc = min(m_splineYMax[INV_INL_SPLINE][rngIdx],adc);
#if 0
cout << "evalADC() cidac " << cidac
<< " adc " << adc
<< " " << adc/cidac
<< endl;
#endif
return StatusCode::SUCCESS;
}
| 29.771654 | 128 | 0.628008 | [
"vector"
] |
07ba194fa95160ab50000ef7588f7ad63a499e53 | 1,833 | cpp | C++ | UserInteractionMode/cpp/Scenario1_Basic.xaml.cpp | kaid7pro/old-Windows-universal-samples | f97d2b880420fff7bcf7ea0aaf20ee837c002d7d | [
"MIT"
] | 6 | 2015-12-23T22:28:56.000Z | 2021-11-06T17:05:51.000Z | UserInteractionMode/cpp/Scenario1_Basic.xaml.cpp | y3key/Windows-universal-samples | f97d2b880420fff7bcf7ea0aaf20ee837c002d7d | [
"MIT"
] | null | null | null | UserInteractionMode/cpp/Scenario1_Basic.xaml.cpp | y3key/Windows-universal-samples | f97d2b880420fff7bcf7ea0aaf20ee837c002d7d | [
"MIT"
] | 8 | 2015-10-26T01:44:51.000Z | 2022-03-12T09:47:56.000Z | //*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
#include "pch.h"
#include "Scenario1_Basic.xaml.h"
using namespace SDKTemplate;
using namespace Platform;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::UI::Core;
using namespace Windows::UI::ViewManagement;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Input;
Scenario1_Basic::Scenario1_Basic() : rootPage(MainPage::Current)
{
InitializeComponent();
}
void Scenario1_Basic::OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e)
{
// The SizeChanged event is raised when the user interaction mode changes.
windowResizeToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &Scenario1_Basic::OnWindowResize);
UpdateContent();
}
void Scenario1_Basic::OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e)
{
Window::Current->SizeChanged -= windowResizeToken;
}
void Scenario1_Basic::OnWindowResize(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
{
UpdateContent();
}
void Scenario1_Basic::UpdateContent()
{
InteractionMode = UIViewSettings::GetForCurrentView()->UserInteractionMode;
// Update styles
CheckBoxStyle = InteractionMode == UserInteractionMode::Mouse ? MouseCheckBoxStyle : TouchCheckBoxStyle;
}
| 33.944444 | 132 | 0.70922 | [
"object"
] |
07bb977571b02bd758db81ea8c111966fe8acab3 | 1,247 | cpp | C++ | Leetcode/1000-2000/1884. Egg Drop With 2 Eggs and N Floors/1884.cpp | Next-Gen-UI/Code-Dynamics | a9b9d5e3f27e870b3e030c75a1060d88292de01c | [
"MIT"
] | null | null | null | Leetcode/1000-2000/1884. Egg Drop With 2 Eggs and N Floors/1884.cpp | Next-Gen-UI/Code-Dynamics | a9b9d5e3f27e870b3e030c75a1060d88292de01c | [
"MIT"
] | null | null | null | Leetcode/1000-2000/1884. Egg Drop With 2 Eggs and N Floors/1884.cpp | Next-Gen-UI/Code-Dynamics | a9b9d5e3f27e870b3e030c75a1060d88292de01c | [
"MIT"
] | null | null | null | class Solution {
public:
int twoEggDrop(int n) {
return superEggDrop(2, n);
}
private:
vector<vector<int>> dp;
int superEggDrop(int K, int N) {
// dp[k][n] := min # of moves to know F with k eggs and n floors
dp.resize(K + 1, vector<int>(N + 1, -1));
return drop(K, N);
}
int drop(int k, int n) {
if (k == 0) // no eggs -> done
return 0;
if (k == 1) // one egg -> drop from 1-th floor to n-th floor
return n;
if (n == 0) // no floor -> done
return 0;
if (n == 1) // one floor -> drop from that floor
return 1;
if (dp[k][n] != -1)
return dp[k][n];
// broken[i] := drop(k - 1, i - 1) is increasing w/ i
// unbroken[i] := drop(k, n - i) is decreasing w/ i
// dp[k][n] := 1 + min(max(broken[i], unbroken[i])), 1 <= i <= n
// find the first index i s.t broken[i] >= unbroken[i],
// which minimizes max(broken[i], unbroken[i])
int l = 1;
int r = n + 1;
while (l < r) {
const int m = (l + r) / 2;
const int broken = drop(k - 1, m - 1);
const int unbroken = drop(k, n - m);
if (broken >= unbroken)
r = m;
else
l = m + 1;
}
return dp[k][n] = 1 + drop(k - 1, l - 1);
}
};
| 24.94 | 68 | 0.48757 | [
"vector"
] |
07c7e6ac69511a55917bc7363ade07830e1d1960 | 8,477 | cpp | C++ | tests/iclBLAS/test_Srot.cpp | intel/clGPU | bf099c547a17d12a81c23314a54fc7fe175a86a7 | [
"Apache-2.0"
] | 61 | 2018-02-20T06:01:50.000Z | 2021-09-08T05:55:44.000Z | tests/iclBLAS/test_Srot.cpp | intel/clGPU | bf099c547a17d12a81c23314a54fc7fe175a86a7 | [
"Apache-2.0"
] | 2 | 2018-04-21T06:59:30.000Z | 2019-01-12T17:08:54.000Z | tests/iclBLAS/test_Srot.cpp | intel/clGPU | bf099c547a17d12a81c23314a54fc7fe175a86a7 | [
"Apache-2.0"
] | 19 | 2018-02-19T17:18:04.000Z | 2021-02-25T02:00:53.000Z | // Copyright (c) 2017-2018 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <gtest/gtest.h>
#include <iclBLAS.h>
TEST(Srot, n1_c2_s1)
{
const int n = 1;
const int incx = 1;
const int incy = 1;
float x[n] = { 1.f };
float y[n] = { 2.f };
float c = 2;
float s = 1;
float refx = 4.f;
float refy = 3.f;
iclblasHandle_t handle;
iclblasStatus_t status = ICLBLAS_STATUS_SUCCESS;
status = iclblasCreate(&handle);
ASSERT_EQ(status, ICLBLAS_STATUS_SUCCESS);
status = iclblasSrot(handle, n, x, incx, y, incy, c, s);
ASSERT_EQ(status, ICLBLAS_STATUS_SUCCESS);
status = iclblasDestroy(handle);
ASSERT_EQ(status, ICLBLAS_STATUS_SUCCESS);
EXPECT_FLOAT_EQ(refx, x[0]);
EXPECT_FLOAT_EQ(refy, y[0]);
}
TEST(Srot, n11_c2_s1)
{
const int n = 11;
const int incx = 1;
const int incy = 1;
float x[n * incx] = { -1.f, 23.f, 3.f, 14.f, 4.f, 8.f, 7.f, -11.f, 9.f, 10.f, 14.f };
float y[n * incy] = { -1.f, 23.f, 3.f, 14.f, 4.f, 8.f, 7.f, -11.f, 9.f, 10.f, 14.f };
float c = 2;
float s = 1;
float refx[n * incx];
float refy[n * incy];
for (int i = 0; i < n; i++)
{
float _x = c * x[i * incx] + s * y[i * incy];
refy[i * incy] = -1 * s * x[i * incx] + c * y[i * incy];
refx[i * incx] = _x;
}
iclblasHandle_t handle;
iclblasStatus_t status = ICLBLAS_STATUS_SUCCESS;
status = iclblasCreate(&handle);
ASSERT_EQ(status, ICLBLAS_STATUS_SUCCESS);
status = iclblasSrot(handle, n, x, incx, y, incy, c, s);
ASSERT_EQ(status, ICLBLAS_STATUS_SUCCESS);
status = iclblasDestroy(handle);
ASSERT_EQ(status, ICLBLAS_STATUS_SUCCESS);
for (int i = 0; i < n; i++)
{
EXPECT_FLOAT_EQ(refx[i * incx], x[i * incx]);
EXPECT_FLOAT_EQ(refy[i * incy], y[i * incy]);
}
}
TEST(Srot, n5x2_c2_s1)
{
const int n = 5;
const int incx = 2;
const int incy = 2;
float x[n * incx] = { -1.f, 23.f, 3.f, 14.f, 4.f, 8.f, 7.f, -11.f, 9.f, 10.f };
float y[n * incy] = { -1.f, 23.f, 3.f, 14.f, 4.f, 8.f, 7.f, -11.f, 9.f, 10.f };
float c = 2;
float s = 1;
float refx[n * incx];
float refy[n * incy];
for (int i = 0; i < n; i++)
{
refx[i * incx] = x[i * incx];
refy[i * incy] = y[i * incy];
}
for (int i = 0; i < n; i++)
{
float _x = c * x[i * incx] + s * y[i * incy];
refy[i * incy] = -1 * s * x[i * incx] + c * y[i * incy];
refx[i * incx] = _x;
}
iclblasHandle_t handle;
iclblasStatus_t status = ICLBLAS_STATUS_SUCCESS;
status = iclblasCreate(&handle);
ASSERT_EQ(status, ICLBLAS_STATUS_SUCCESS);
status = iclblasSrot(handle, n, x, incx, y, incy, c, s);
ASSERT_EQ(status, ICLBLAS_STATUS_SUCCESS);
status = iclblasDestroy(handle);
ASSERT_EQ(status, ICLBLAS_STATUS_SUCCESS);
for (int i = 0; i < n; i++)
{
EXPECT_FLOAT_EQ(refx[i * incx], x[i * incx]);
EXPECT_FLOAT_EQ(refy[i * incy], y[i * incy]);
}
}
TEST(Srot, noincx)
{
const int n = 12;
const int incx = 1;
const int incy = 2;
float x[n * incx];
float y[n * incy];
for (int i = 0; i < n; i++)
{
x[i * incx] = static_cast<float>(std::rand() % 23);
y[i * incy] = static_cast<float>(std::rand() % 23);
}
float c = 2;
float s = 1;
float refx[n * incx];
float refy[n * incy];
for (int i = 0; i < n; i++)
{
refx[i * incx] = x[i * incx];
refy[i * incy] = y[i * incy];
}
for (int i = 0; i < n; i++)
{
float _x = c * x[i * incx] + s * y[i * incy];
refy[i * incy] = -1 * s * x[i * incx] + c * y[i * incy];
refx[i * incx] = _x;
}
iclblasHandle_t handle;
iclblasStatus_t status = ICLBLAS_STATUS_SUCCESS;
status = iclblasCreate(&handle);
ASSERT_EQ(status, ICLBLAS_STATUS_SUCCESS);
status = iclblasSrot(handle, n, x, incx, y, incy, c, s);
ASSERT_EQ(status, ICLBLAS_STATUS_SUCCESS);
status = iclblasDestroy(handle);
ASSERT_EQ(status, ICLBLAS_STATUS_SUCCESS);
for (int i = 0; i < n; i++)
{
EXPECT_FLOAT_EQ(refx[i * incx], x[i * incx]);
EXPECT_FLOAT_EQ(refy[i * incy], y[i * incy]);
}
}
TEST(Srot, noincy)
{
const int n = 12;
const int incx = 2;
const int incy = 1;
float x[n * incx];
float y[n * incy];
for (int i = 0; i < n; i++)
{
x[i * incx] = static_cast<float>(std::rand() % 23);
y[i * incy] = static_cast<float>(std::rand() % 23);
}
float c = 2.25f;
float s = 0.75f;
float refx[n * incx];
float refy[n * incy];
for (int i = 0; i < n; i++)
{
refx[i * incx] = x[i * incx];
refy[i * incy] = y[i * incy];
}
for (int i = 0; i < n; i++)
{
float _x = c * x[i * incx] + s * y[i * incy];
refy[i * incy] = -1 * s * x[i * incx] + c * y[i * incy];
refx[i * incx] = _x;
}
iclblasHandle_t handle;
iclblasStatus_t status = ICLBLAS_STATUS_SUCCESS;
status = iclblasCreate(&handle);
ASSERT_EQ(status, ICLBLAS_STATUS_SUCCESS);
status = iclblasSrot(handle, n, x, incx, y, incy, c, s);
ASSERT_EQ(status, ICLBLAS_STATUS_SUCCESS);
status = iclblasDestroy(handle);
ASSERT_EQ(status, ICLBLAS_STATUS_SUCCESS);
for (int i = 0; i < n; i++)
{
EXPECT_FLOAT_EQ(refx[i * incx], x[i * incx]);
EXPECT_FLOAT_EQ(refy[i * incy], y[i * incy]);
}
}
TEST(Srot, noinc_optim)
{
const int n = 65536;
const int incx = 1;
const int incy = 1;
//use vector to avoid stack size limit problem
std::vector<float> x(n * incx);
std::vector<float> y(n * incy);
for (int i = 0; i < n; i++)
{
x[i * incx] = static_cast<float>(std::rand() % 15);
y[i * incy] = static_cast<float>(std::rand() % 15);
}
float c = 2;
float s = 1;
std::vector<float> refx(n * incx);
std::vector<float> refy(n * incy);
for (int i = 0; i < n; i++)
{
float _x = c * x[i * incx] + s * y[i * incy];
refy[i * incy] = -1 * s * x[i * incx] + c * y[i * incy];
refx[i * incx] = _x;
}
iclblasHandle_t handle;
iclblasStatus_t status = ICLBLAS_STATUS_SUCCESS;
status = iclblasCreate(&handle);
ASSERT_EQ(status, ICLBLAS_STATUS_SUCCESS);
status = iclblasSrot(handle, n, x.data(), incx, y.data(), incy, c, s);
ASSERT_EQ(status, ICLBLAS_STATUS_SUCCESS);
status = iclblasDestroy(handle);
ASSERT_EQ(status, ICLBLAS_STATUS_SUCCESS);
for (int i = 0; i < n; i++)
{
EXPECT_FLOAT_EQ(refx[i * incx], x[i * incx]);
EXPECT_FLOAT_EQ(refy[i * incy], y[i * incy]);
}
}
TEST(Srot, noincx_optim)
{
const int n = 16384;
const int incx = 1;
const int incy = 3;
//use vector to avoid stack size limit problem
std::vector<float> x(n * incx);
std::vector<float> y(n * incy);
for (int i = 0; i < n; i++)
{
x[i * incx] = static_cast<float>(std::rand() % 15);
y[i * incy] = static_cast<float>(std::rand() % 15);
}
float c = 2.4f;
float s = 0.25f;
std::vector<float> refx(n * incx);
std::vector<float> refy(n * incy);
for (int i = 0; i < n; i++)
{
float _x = c * x[i * incx] + s * y[i * incy];
refy[i * incy] = -1 * s * x[i * incx] + c * y[i * incy];
refx[i * incx] = _x;
}
iclblasHandle_t handle;
iclblasStatus_t status = ICLBLAS_STATUS_SUCCESS;
status = iclblasCreate(&handle);
ASSERT_EQ(status, ICLBLAS_STATUS_SUCCESS);
status = iclblasSrot(handle, n, x.data(), incx, y.data(), incy, c, s);
ASSERT_EQ(status, ICLBLAS_STATUS_SUCCESS);
status = iclblasDestroy(handle);
ASSERT_EQ(status, ICLBLAS_STATUS_SUCCESS);
for (int i = 0; i < n; i++)
{
EXPECT_FLOAT_EQ(refx[i * incx], x[i * incx]);
EXPECT_FLOAT_EQ(refy[i * incy], y[i * incy]);
}
}
| 25.079882 | 89 | 0.55397 | [
"vector"
] |
07c9d8ac9b71355f8ba8e0b5c8e0ae1859f4061c | 4,993 | cc | C++ | CondCore/SiStripPlugins/plugins/SiStripDetVOff_PayloadInspector.cc | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | CondCore/SiStripPlugins/plugins/SiStripDetVOff_PayloadInspector.cc | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | CondCore/SiStripPlugins/plugins/SiStripDetVOff_PayloadInspector.cc | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | #include "CondCore/Utilities/interface/PayloadInspectorModule.h"
#include "CondCore/Utilities/interface/PayloadInspector.h"
#include "CondCore/CondDB/interface/Time.h"
#include "CondFormats/SiStripObjects/interface/SiStripDetVOff.h"
#include "CommonTools/TrackerMap/interface/TrackerMap.h"
#include <memory>
#include <sstream>
namespace {
class SiStripDetVOff_LV : public cond::payloadInspector::TimeHistoryPlot<SiStripDetVOff,int>{
public:
SiStripDetVOff_LV(): cond::payloadInspector::TimeHistoryPlot<SiStripDetVOff,int >( "Nr of mod with LV OFF vs time", "nLVOff"){
}
int getFromPayload( SiStripDetVOff& payload ) override{
return payload.getLVoffCounts();
}
};
class SiStripDetVOff_HV : public cond::payloadInspector::TimeHistoryPlot<SiStripDetVOff,int> {
public:
SiStripDetVOff_HV() : cond::payloadInspector::TimeHistoryPlot<SiStripDetVOff,int >( "Nr of mod with HV OFF vs time","nHVOff"){
}
int getFromPayload( SiStripDetVOff& payload ) override{
return payload.getHVoffCounts();
}
};
/************************************************
TrackerMap of Module VOff
*************************************************/
class SiStripDetVOff_IsModuleVOff_TrackerMap : public cond::payloadInspector::PlotImage<SiStripDetVOff> {
public:
SiStripDetVOff_IsModuleVOff_TrackerMap() : cond::payloadInspector::PlotImage<SiStripDetVOff>( "Tracker Map IsModuleVOff" ){
setSingleIov( true );
}
bool fill( const std::vector<std::tuple<cond::Time_t,cond::Hash> >& iovs ) override{
auto iov = iovs.front();
std::shared_ptr<SiStripDetVOff> payload = fetchPayload( std::get<1>(iov) );
std::unique_ptr<TrackerMap> tmap = std::unique_ptr<TrackerMap>(new TrackerMap("SiStripIsModuleVOff"));
tmap->setPalette(1);
std::string titleMap = "TrackerMap of VOff modules (HV or LV), payload : "+std::get<1>(iov);
tmap->setTitle(titleMap);
std::vector<uint32_t> detid;
payload->getDetIds(detid);
for (const auto & d : detid) {
if(payload->IsModuleVOff(d)){
tmap->fill(d,1);
}
} // loop over detIds
std::string fileName(m_imageFileName);
tmap->save(true,0,0,fileName);
return true;
}
};
/************************************************
TrackerMap of Module HVOff
*************************************************/
class SiStripDetVOff_IsModuleHVOff_TrackerMap : public cond::payloadInspector::PlotImage<SiStripDetVOff> {
public:
SiStripDetVOff_IsModuleHVOff_TrackerMap() : cond::payloadInspector::PlotImage<SiStripDetVOff>( "Tracker Map IsModuleHVOff" ){
setSingleIov( true );
}
bool fill( const std::vector<std::tuple<cond::Time_t,cond::Hash> >& iovs ) override{
auto iov = iovs.front();
std::shared_ptr<SiStripDetVOff> payload = fetchPayload( std::get<1>(iov) );
std::unique_ptr<TrackerMap> tmap = std::unique_ptr<TrackerMap>(new TrackerMap("SiStripIsModuleHVOff"));
tmap->setPalette(1);
std::string titleMap = "TrackerMap of HV Off modules, payload : "+std::get<1>(iov);
tmap->setTitle(titleMap);
std::vector<uint32_t> detid;
payload->getDetIds(detid);
for (const auto & d : detid) {
if(payload->IsModuleHVOff(d)){
tmap->fill(d,1);
}
} // loop over detIds
std::string fileName(m_imageFileName);
tmap->save(true,0,0,fileName);
return true;
}
};
/************************************************
TrackerMap of Module LVOff
*************************************************/
class SiStripDetVOff_IsModuleLVOff_TrackerMap : public cond::payloadInspector::PlotImage<SiStripDetVOff> {
public:
SiStripDetVOff_IsModuleLVOff_TrackerMap() : cond::payloadInspector::PlotImage<SiStripDetVOff>( "Tracker Map IsModuleLVOff" ){
setSingleIov( true );
}
bool fill( const std::vector<std::tuple<cond::Time_t,cond::Hash> >& iovs ) override{
auto iov = iovs.front();
std::shared_ptr<SiStripDetVOff> payload = fetchPayload( std::get<1>(iov) );
std::unique_ptr<TrackerMap> tmap = std::unique_ptr<TrackerMap>(new TrackerMap("SiStripIsModuleLVOff"));
tmap->setPalette(1);
std::string titleMap = "TrackerMap of LV Off modules, payload : "+std::get<1>(iov);
tmap->setTitle(titleMap);
std::vector<uint32_t> detid;
payload->getDetIds(detid);
for (const auto & d : detid) {
if(payload->IsModuleLVOff(d)){
tmap->fill(d,1);
}
} // loop over detIds
std::string fileName(m_imageFileName);
tmap->save(true,0,0,fileName);
return true;
}
};
}
PAYLOAD_INSPECTOR_MODULE( SiStripDetVOff ){
PAYLOAD_INSPECTOR_CLASS( SiStripDetVOff_LV );
PAYLOAD_INSPECTOR_CLASS( SiStripDetVOff_HV );
PAYLOAD_INSPECTOR_CLASS( SiStripDetVOff_IsModuleVOff_TrackerMap );
PAYLOAD_INSPECTOR_CLASS( SiStripDetVOff_IsModuleLVOff_TrackerMap );
PAYLOAD_INSPECTOR_CLASS( SiStripDetVOff_IsModuleHVOff_TrackerMap );
}
| 33.965986 | 130 | 0.653715 | [
"vector"
] |
07cab300d35529222d598ffd0d74273ce14f2881 | 3,278 | cc | C++ | RecoTauTag/RecoTau/plugins/RecoTauDiscriminantFromDiscriminator.cc | bisnupriyasahu/cmssw | 6cf37ca459246525be0e8a6f5172c6123637d259 | [
"Apache-2.0"
] | 3 | 2018-08-24T19:10:26.000Z | 2019-02-19T11:45:32.000Z | RecoTauTag/RecoTau/plugins/RecoTauDiscriminantFromDiscriminator.cc | bisnupriyasahu/cmssw | 6cf37ca459246525be0e8a6f5172c6123637d259 | [
"Apache-2.0"
] | 3 | 2018-08-23T13:40:24.000Z | 2019-12-05T21:16:03.000Z | RecoTauTag/RecoTau/plugins/RecoTauDiscriminantFromDiscriminator.cc | bisnupriyasahu/cmssw | 6cf37ca459246525be0e8a6f5172c6123637d259 | [
"Apache-2.0"
] | 5 | 2018-08-21T16:37:52.000Z | 2020-01-09T13:33:17.000Z | /*
* RecoTauDiscriminantFromDiscriminator
*
* Makes a discriminator function from a PFRecoTauDiscriminator stored in the
* event.
*
* Author: Evan K. Friis (UC Davis)
*
*/
#include <sstream>
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "RecoTauTag/RecoTau/interface/RecoTauDiscriminantPlugins.h"
#include "DataFormats/TauReco/interface/PFTauDiscriminator.h"
namespace reco::tau {
class RecoTauDiscriminantFromDiscriminator : public RecoTauDiscriminantPlugin{
public:
explicit RecoTauDiscriminantFromDiscriminator(
const edm::ParameterSet& pset);
void beginEvent() override;
std::vector<double> operator()(const reco::PFTauRef& tau) const override;
private:
bool takeAbs_;
double min_;
double max_;
typedef std::pair<edm::InputTag, edm::Handle<reco::PFTauDiscriminator> > DiscInfo;
std::vector<DiscInfo> discriminators_;
};
RecoTauDiscriminantFromDiscriminator::RecoTauDiscriminantFromDiscriminator(
const edm::ParameterSet& pset):RecoTauDiscriminantPlugin(pset) {
takeAbs_ = pset.getParameter<bool>("takeAbs");
min_ = pset.getParameter<double>("minValue");
max_ = pset.getParameter<double>("maxValue");
std::vector<edm::InputTag> discriminators =
pset.getParameter<std::vector<edm::InputTag> >("discSrc");
for(auto const& tag : discriminators) {
discriminators_.push_back(std::make_pair(tag, edm::Handle<reco::PFTauDiscriminator>()));
}
}
// Called by base class at the beginning of every event
void RecoTauDiscriminantFromDiscriminator::beginEvent() {
for(auto& discInfo : discriminators_) {
evt()->getByLabel(discInfo.first, discInfo.second);
}
}
std::vector<double> RecoTauDiscriminantFromDiscriminator::operator()(
const reco::PFTauRef& tau) const {
edm::ProductID tauProdId = tau.id();
double result = -999;
bool foundGoodDiscriminator = false;
for (size_t i = 0; i < discriminators_.size(); ++i) {
// Check if the discriminator actually exists
if (!discriminators_[i].second.isValid())
continue;
const reco::PFTauDiscriminator& disc = *(discriminators_[i].second);
if (tauProdId == disc.keyProduct().id()) {
foundGoodDiscriminator = true;
result = (disc)[tau];
break;
}
}
// In case no discriminator is found.
if (!foundGoodDiscriminator) {
std::stringstream error;
error << "Couldn't find a PFTauDiscriminator usable with given tau."
<< std::endl << " Input tau has product id: " << tau.id() << std::endl;
for (size_t i = 0; i < discriminators_.size(); ++i ) {
error << "disc: " << discriminators_[i].first;
error << " isValid: " << discriminators_[i].second.isValid();
if (discriminators_[i].second.isValid()) {
error << " product: " << discriminators_[i].second->keyProduct().id();
}
error << std::endl;
}
edm::LogError("BadDiscriminatorConfiguration") << error.str();
}
if (result < min_)
result = min_;
if (result > max_)
result = max_;
return std::vector<double>(1, result);
}
} // end namespace reco::tau
#include "FWCore/Framework/interface/MakerMacros.h"
DEFINE_EDM_PLUGIN(RecoTauDiscriminantPluginFactory,
reco::tau::RecoTauDiscriminantFromDiscriminator,
"RecoTauDiscriminantFromDiscriminator");
| 33.793814 | 92 | 0.701952 | [
"vector"
] |
07cbcbc43fa24497510678426a56650932606545 | 17,116 | cc | C++ | storage/browser/quota/usage_tracker_unittest.cc | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2020-10-18T02:33:40.000Z | 2020-10-18T02:33:40.000Z | storage/browser/quota/usage_tracker_unittest.cc | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 3 | 2021-05-17T16:28:52.000Z | 2021-05-21T22:42:22.000Z | storage/browser/quota/usage_tracker_unittest.cc | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <stdint.h>
#include <utility>
#include <vector>
#include "base/bind.h"
#include "base/location.h"
#include "base/macros.h"
#include "base/memory/scoped_refptr.h"
#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
#include "base/test/task_environment.h"
#include "base/threading/thread_task_runner_handle.h"
#include "storage/browser/quota/quota_client_type.h"
#include "storage/browser/quota/usage_tracker.h"
#include "storage/browser/test/mock_special_storage_policy.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/common/storage_key/storage_key.h"
using blink::mojom::QuotaStatusCode;
using blink::mojom::StorageType;
namespace storage {
namespace {
void DidGetGlobalUsage(bool* done,
int64_t* usage_out,
int64_t* unlimited_usage_out,
int64_t usage,
int64_t unlimited_usage) {
EXPECT_FALSE(*done);
*done = true;
*usage_out = usage;
*unlimited_usage_out = unlimited_usage;
}
// TODO(crbug.com/1215208): Migrate to use StorageKey when the QuotaClient is
// migrated to use StorageKey instead of Origin.
class UsageTrackerTestQuotaClient : public QuotaClient {
public:
UsageTrackerTestQuotaClient() = default;
void GetOriginUsage(const url::Origin& origin,
StorageType type,
GetOriginUsageCallback callback) override {
EXPECT_EQ(StorageType::kTemporary, type);
int64_t usage = GetUsage(origin);
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(std::move(callback), usage));
}
void GetOriginsForType(StorageType type,
GetOriginsForTypeCallback callback) override {
EXPECT_EQ(StorageType::kTemporary, type);
std::vector<url::Origin> origins;
for (const auto& origin_usage_pair : origin_usage_map_)
origins.push_back(origin_usage_pair.first);
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(std::move(callback), std::move(origins)));
}
void GetOriginsForHost(StorageType type,
const std::string& host,
GetOriginsForHostCallback callback) override {
EXPECT_EQ(StorageType::kTemporary, type);
std::vector<url::Origin> origins;
for (const auto& origin_usage_pair : origin_usage_map_) {
if (origin_usage_pair.first.host() == host)
origins.push_back(origin_usage_pair.first);
}
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(std::move(callback), std::move(origins)));
}
void DeleteOriginData(const url::Origin& origin,
StorageType type,
DeleteOriginDataCallback callback) override {
EXPECT_EQ(StorageType::kTemporary, type);
origin_usage_map_.erase(origin);
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(std::move(callback), QuotaStatusCode::kOk));
}
void PerformStorageCleanup(blink::mojom::StorageType type,
PerformStorageCleanupCallback callback) override {
std::move(callback).Run();
}
int64_t GetUsage(const url::Origin& origin) {
auto it = origin_usage_map_.find(origin);
if (it == origin_usage_map_.end())
return 0;
return it->second;
}
void SetUsage(const url::Origin& origin, int64_t usage) {
origin_usage_map_[origin] = usage;
}
int64_t UpdateUsage(const url::Origin& origin, int64_t delta) {
return origin_usage_map_[origin] += delta;
}
private:
~UsageTrackerTestQuotaClient() override = default;
std::map<url::Origin, int64_t> origin_usage_map_;
DISALLOW_COPY_AND_ASSIGN(UsageTrackerTestQuotaClient);
};
} // namespace
class UsageTrackerTest : public testing::Test {
public:
UsageTrackerTest()
: storage_policy_(base::MakeRefCounted<MockSpecialStoragePolicy>()),
quota_client_(base::MakeRefCounted<UsageTrackerTestQuotaClient>()),
usage_tracker_(GetQuotaClientMap(),
StorageType::kTemporary,
storage_policy_.get()) {}
~UsageTrackerTest() override = default;
UsageTracker* usage_tracker() {
return &usage_tracker_;
}
static void DidGetUsageBreakdown(
bool* done,
int64_t* usage_out,
blink::mojom::UsageBreakdownPtr* usage_breakdown_out,
int64_t usage,
blink::mojom::UsageBreakdownPtr usage_breakdown) {
EXPECT_FALSE(*done);
*usage_out = usage;
*usage_breakdown_out = std::move(usage_breakdown);
*done = true;
}
void UpdateUsage(const blink::StorageKey& storage_key, int64_t delta) {
quota_client_->UpdateUsage(storage_key.origin(), delta);
usage_tracker_.UpdateUsageCache(QuotaClientType::kFileSystem, storage_key,
delta);
base::RunLoop().RunUntilIdle();
}
void UpdateUsageWithoutNotification(const blink::StorageKey& storage_key,
int64_t delta) {
quota_client_->UpdateUsage(storage_key.origin(), delta);
}
void GetGlobalUsage(int64_t* usage, int64_t* unlimited_usage) {
bool done = false;
usage_tracker_.GetGlobalUsage(
base::BindOnce(&DidGetGlobalUsage, &done, usage, unlimited_usage));
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(done);
}
std::pair<int64_t, blink::mojom::UsageBreakdownPtr> GetHostUsageWithBreakdown(
const std::string& host) {
int64_t usage;
blink::mojom::UsageBreakdownPtr usage_breakdown;
bool done = false;
usage_tracker_.GetHostUsageWithBreakdown(
host, base::BindOnce(&UsageTrackerTest::DidGetUsageBreakdown, &done,
&usage, &usage_breakdown));
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(done);
return std::make_pair(usage, std::move(usage_breakdown));
}
void GrantUnlimitedStoragePolicy(const blink::StorageKey& storage_key) {
if (!storage_policy_->IsStorageUnlimited(storage_key.origin().GetURL())) {
storage_policy_->AddUnlimited(storage_key.origin().GetURL());
storage_policy_->NotifyGranted(storage_key.origin(),
SpecialStoragePolicy::STORAGE_UNLIMITED);
}
}
void RevokeUnlimitedStoragePolicy(const blink::StorageKey& storage_key) {
if (storage_policy_->IsStorageUnlimited(storage_key.origin().GetURL())) {
storage_policy_->RemoveUnlimited(storage_key.origin().GetURL());
storage_policy_->NotifyRevoked(storage_key.origin(),
SpecialStoragePolicy::STORAGE_UNLIMITED);
}
}
void SetUsageCacheEnabled(const blink::StorageKey& storage_key,
bool enabled) {
usage_tracker_.SetUsageCacheEnabled(QuotaClientType::kFileSystem,
storage_key, enabled);
}
private:
base::flat_map<QuotaClient*, QuotaClientType> GetQuotaClientMap() {
base::flat_map<QuotaClient*, QuotaClientType> client_map;
client_map.insert(
std::make_pair(quota_client_.get(), QuotaClientType::kFileSystem));
return client_map;
}
base::test::TaskEnvironment task_environment_;
scoped_refptr<MockSpecialStoragePolicy> storage_policy_;
scoped_refptr<UsageTrackerTestQuotaClient> quota_client_;
UsageTracker usage_tracker_;
DISALLOW_COPY_AND_ASSIGN(UsageTrackerTest);
};
TEST_F(UsageTrackerTest, GrantAndRevokeUnlimitedStorage) {
int64_t usage = 0;
int64_t unlimited_usage = 0;
blink::mojom::UsageBreakdownPtr host_usage_breakdown_expected =
blink::mojom::UsageBreakdown::New();
GetGlobalUsage(&usage, &unlimited_usage);
EXPECT_EQ(0, usage);
EXPECT_EQ(0, unlimited_usage);
const blink::StorageKey storage_key =
blink::StorageKey::CreateFromStringForTesting("http://example.com");
const std::string& host = storage_key.origin().host();
UpdateUsage(storage_key, 100);
GetGlobalUsage(&usage, &unlimited_usage);
EXPECT_EQ(100, usage);
EXPECT_EQ(0, unlimited_usage);
host_usage_breakdown_expected->fileSystem = 100;
std::pair<int64_t, blink::mojom::UsageBreakdownPtr> host_usage_breakdown =
GetHostUsageWithBreakdown(host);
EXPECT_EQ(100, host_usage_breakdown.first);
EXPECT_EQ(host_usage_breakdown_expected, host_usage_breakdown.second);
GrantUnlimitedStoragePolicy(storage_key);
GetGlobalUsage(&usage, &unlimited_usage);
EXPECT_EQ(100, usage);
EXPECT_EQ(100, unlimited_usage);
host_usage_breakdown = GetHostUsageWithBreakdown(host);
EXPECT_EQ(100, host_usage_breakdown.first);
EXPECT_EQ(host_usage_breakdown_expected, host_usage_breakdown.second);
RevokeUnlimitedStoragePolicy(storage_key);
GetGlobalUsage(&usage, &unlimited_usage);
EXPECT_EQ(100, usage);
EXPECT_EQ(0, unlimited_usage);
GetHostUsageWithBreakdown(host);
EXPECT_EQ(100, host_usage_breakdown.first);
EXPECT_EQ(host_usage_breakdown_expected, host_usage_breakdown.second);
}
TEST_F(UsageTrackerTest, CacheDisabledClientTest) {
int64_t usage = 0;
int64_t unlimited_usage = 0;
blink::mojom::UsageBreakdownPtr host_usage_breakdown_expected =
blink::mojom::UsageBreakdown::New();
const blink::StorageKey storage_key =
blink::StorageKey::CreateFromStringForTesting("http://example.com");
const std::string& host = storage_key.origin().host();
UpdateUsage(storage_key, 100);
GetGlobalUsage(&usage, &unlimited_usage);
EXPECT_EQ(100, usage);
EXPECT_EQ(0, unlimited_usage);
host_usage_breakdown_expected->fileSystem = 100;
std::pair<int64_t, blink::mojom::UsageBreakdownPtr> host_usage_breakdown =
GetHostUsageWithBreakdown(host);
EXPECT_EQ(100, host_usage_breakdown.first);
EXPECT_EQ(host_usage_breakdown_expected, host_usage_breakdown.second);
UpdateUsageWithoutNotification(storage_key, 100);
GetGlobalUsage(&usage, &unlimited_usage);
EXPECT_EQ(100, usage);
EXPECT_EQ(0, unlimited_usage);
host_usage_breakdown = GetHostUsageWithBreakdown(host);
EXPECT_EQ(100, host_usage_breakdown.first);
EXPECT_EQ(host_usage_breakdown_expected, host_usage_breakdown.second);
GrantUnlimitedStoragePolicy(storage_key);
UpdateUsageWithoutNotification(storage_key, 100);
SetUsageCacheEnabled(storage_key, false);
UpdateUsageWithoutNotification(storage_key, 100);
GetGlobalUsage(&usage, &unlimited_usage);
EXPECT_EQ(400, usage);
EXPECT_EQ(400, unlimited_usage);
host_usage_breakdown = GetHostUsageWithBreakdown(host);
host_usage_breakdown_expected->fileSystem = 400;
EXPECT_EQ(400, host_usage_breakdown.first);
EXPECT_EQ(host_usage_breakdown_expected, host_usage_breakdown.second);
RevokeUnlimitedStoragePolicy(storage_key);
GetGlobalUsage(&usage, &unlimited_usage);
EXPECT_EQ(400, usage);
EXPECT_EQ(0, unlimited_usage);
host_usage_breakdown = GetHostUsageWithBreakdown(host);
EXPECT_EQ(400, host_usage_breakdown.first);
EXPECT_EQ(host_usage_breakdown_expected, host_usage_breakdown.second);
SetUsageCacheEnabled(storage_key, true);
UpdateUsage(storage_key, 100);
GetGlobalUsage(&usage, &unlimited_usage);
EXPECT_EQ(500, usage);
EXPECT_EQ(0, unlimited_usage);
host_usage_breakdown = GetHostUsageWithBreakdown(host);
host_usage_breakdown_expected->fileSystem = 500;
EXPECT_EQ(500, host_usage_breakdown.first);
EXPECT_EQ(host_usage_breakdown_expected, host_usage_breakdown.second);
}
TEST_F(UsageTrackerTest, GlobalUsageUnlimitedUncached) {
const blink::StorageKey kNormal =
blink::StorageKey::CreateFromStringForTesting("http://normal");
const blink::StorageKey kUnlimited =
blink::StorageKey::CreateFromStringForTesting("http://unlimited");
const blink::StorageKey kNonCached =
blink::StorageKey::CreateFromStringForTesting("http://non_cached");
const blink::StorageKey kNonCachedUnlimited =
blink::StorageKey::CreateFromStringForTesting(
"http://non_cached-unlimited");
GrantUnlimitedStoragePolicy(kUnlimited);
GrantUnlimitedStoragePolicy(kNonCachedUnlimited);
SetUsageCacheEnabled(kNonCached, false);
SetUsageCacheEnabled(kNonCachedUnlimited, false);
UpdateUsageWithoutNotification(kNormal, 1);
UpdateUsageWithoutNotification(kUnlimited, 2);
UpdateUsageWithoutNotification(kNonCached, 4);
UpdateUsageWithoutNotification(kNonCachedUnlimited, 8);
int64_t total_usage = 0;
int64_t unlimited_usage = 0;
GetGlobalUsage(&total_usage, &unlimited_usage);
EXPECT_EQ(1 + 2 + 4 + 8, total_usage);
EXPECT_EQ(2 + 8, unlimited_usage);
UpdateUsageWithoutNotification(kNonCached, 16 - 4);
UpdateUsageWithoutNotification(kNonCachedUnlimited, 32 - 8);
GetGlobalUsage(&total_usage, &unlimited_usage);
EXPECT_EQ(1 + 2 + 16 + 32, total_usage);
EXPECT_EQ(2 + 32, unlimited_usage);
}
TEST_F(UsageTrackerTest, GlobalUsageMultipleStorageKeysPerHostCachedInit) {
const blink::StorageKey kStorageKey1 =
blink::StorageKey::CreateFromStringForTesting("http://example.com");
const blink::StorageKey kStorageKey2 =
blink::StorageKey::CreateFromStringForTesting("http://example.com:8080");
ASSERT_EQ(kStorageKey1.origin().host(), kStorageKey2.origin().host())
<< "The test assumes that the two origins have the same host";
UpdateUsageWithoutNotification(kStorageKey1, 100);
UpdateUsageWithoutNotification(kStorageKey2, 200);
int64_t total_usage = 0;
int64_t unlimited_usage = 0;
// GetGlobalUsage() takes different code paths on the first call and on
// subsequent calls. This test covers the code path used by the first call.
// Therefore, we introduce the origins before the first call.
GetGlobalUsage(&total_usage, &unlimited_usage);
EXPECT_EQ(100 + 200, total_usage);
EXPECT_EQ(0, unlimited_usage);
}
TEST_F(UsageTrackerTest, GlobalUsageMultipleOriginsPerHostCachedUpdate) {
const blink::StorageKey kStorageKey1 =
blink::StorageKey::CreateFromStringForTesting("http://example.com");
const blink::StorageKey kStorageKey2 =
blink::StorageKey::CreateFromStringForTesting("http://example.com:8080");
ASSERT_EQ(kStorageKey1.origin().host(), kStorageKey2.origin().host())
<< "The test assumes that the two origins have the same host";
int64_t total_usage = 0;
int64_t unlimited_usage = 0;
// GetGlobalUsage() takes different code paths on the first call and on
// subsequent calls. This test covers the code path used by subsequent calls.
// Therefore, we introduce the origins after the first call.
GetGlobalUsage(&total_usage, &unlimited_usage);
EXPECT_EQ(0, total_usage);
EXPECT_EQ(0, unlimited_usage);
UpdateUsage(kStorageKey1, 100);
UpdateUsage(kStorageKey2, 200);
GetGlobalUsage(&total_usage, &unlimited_usage);
EXPECT_EQ(100 + 200, total_usage);
EXPECT_EQ(0, unlimited_usage);
}
TEST_F(UsageTrackerTest, GlobalUsageMultipleOriginsPerHostUncachedInit) {
const blink::StorageKey kStorageKey1 =
blink::StorageKey::CreateFromStringForTesting("http://example.com");
const blink::StorageKey kStorageKey2 =
blink::StorageKey::CreateFromStringForTesting("http://example.com:8080");
ASSERT_EQ(kStorageKey1.origin().host(), kStorageKey2.origin().host())
<< "The test assumes that the two origins have the same host";
SetUsageCacheEnabled(kStorageKey1, false);
SetUsageCacheEnabled(kStorageKey2, false);
UpdateUsageWithoutNotification(kStorageKey1, 100);
UpdateUsageWithoutNotification(kStorageKey2, 200);
int64_t total_usage = 0;
int64_t unlimited_usage = 0;
// GetGlobalUsage() takes different code paths on the first call and on
// subsequent calls. This test covers the code path used by the first call.
// Therefore, we introduce the origins before the first call.
GetGlobalUsage(&total_usage, &unlimited_usage);
EXPECT_EQ(100 + 200, total_usage);
EXPECT_EQ(0, unlimited_usage);
}
TEST_F(UsageTrackerTest, GlobalUsageMultipleOriginsPerHostUncachedUpdate) {
const blink::StorageKey kStorageKey1 =
blink::StorageKey::CreateFromStringForTesting("http://example.com");
const blink::StorageKey kStorageKey2 =
blink::StorageKey::CreateFromStringForTesting("http://example.com:8080");
ASSERT_EQ(kStorageKey1.origin().host(), kStorageKey2.origin().host())
<< "The test assumes that the two origins have the same host";
int64_t total_usage = 0;
int64_t unlimited_usage = 0;
// GetGlobalUsage() takes different code paths on the first call and on
// subsequent calls. This test covers the code path used by subsequent calls.
// Therefore, we introduce the origins after the first call.
GetGlobalUsage(&total_usage, &unlimited_usage);
EXPECT_EQ(0, total_usage);
EXPECT_EQ(0, unlimited_usage);
SetUsageCacheEnabled(kStorageKey1, false);
SetUsageCacheEnabled(kStorageKey2, false);
UpdateUsageWithoutNotification(kStorageKey1, 100);
UpdateUsageWithoutNotification(kStorageKey2, 200);
GetGlobalUsage(&total_usage, &unlimited_usage);
EXPECT_EQ(100 + 200, total_usage);
EXPECT_EQ(0, unlimited_usage);
}
} // namespace storage
| 37.452954 | 80 | 0.736738 | [
"vector"
] |
07cd289079c337b7c2b03b7f65af216137046176 | 6,516 | cpp | C++ | data-logger/src/Examples/proto_rebroadcaster.cpp | linklab-uva/deepracing | fc25c47658277df029e7399d295d97a75fe85216 | [
"Apache-2.0"
] | 11 | 2020-06-29T15:21:37.000Z | 2021-04-12T00:42:26.000Z | data-logger/src/Examples/proto_rebroadcaster.cpp | linklab-uva/deepracing | fc25c47658277df029e7399d295d97a75fe85216 | [
"Apache-2.0"
] | null | null | null | data-logger/src/Examples/proto_rebroadcaster.cpp | linklab-uva/deepracing | fc25c47658277df029e7399d295d97a75fe85216 | [
"Apache-2.0"
] | 4 | 2019-01-23T23:36:57.000Z | 2021-07-02T00:18:37.000Z | /*
* cv_viewer.cpp
*
* Created on: Dec 5, 2018
* Author: ttw2xk
*/
#include "f1_datalogger/f1_datalogger.h"
//#include "image_logging/utils/screencapture_lite_utils.h"
#include <iostream>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <sstream>
#include <Eigen/Geometry>
#include "f1_datalogger/udp_logging/utils/eigen_utils.h"
#include "f1_datalogger/image_logging/utils/opencv_utils.h"
#include <google/protobuf/util/json_util.h>
#include <fstream>
#include "f1_datalogger/udp_logging/utils/udp_stream_utils.h"
#include "f1_datalogger/proto/TimestampedPacketMotionData.pb.h"
#include <boost/asio.hpp>
namespace scl = SL::Screen_Capture;
using boost::asio::ip::udp;
class ProtoRebroadcaster_2018DataGrabHandler : public deepf1::IF12018DataGrabHandler
{
public:
ProtoRebroadcaster_2018DataGrabHandler(std::string host, unsigned int port)
: host_(host), port_(port), socket(io_context)
{
receiver_endpoint = udp::endpoint(boost::asio::ip::address_v4::from_string(host_), port_);
}
bool isReady() override
{
return ready_;
}
virtual inline void handleData(const deepf1::twenty_eighteen::TimestampedPacketCarSetupData& data) override
{
}
virtual inline void handleData(const deepf1::twenty_eighteen::TimestampedPacketCarStatusData& data) override
{
}
virtual inline void handleData(const deepf1::twenty_eighteen::TimestampedPacketCarTelemetryData& data) override
{
}
virtual inline void handleData(const deepf1::twenty_eighteen::TimestampedPacketEventData& data) override
{
}
virtual inline void handleData(const deepf1::twenty_eighteen::TimestampedPacketLapData& data) override
{
}
virtual inline void handleData(const deepf1::twenty_eighteen::TimestampedPacketMotionData& data) override
{
ready_ = false;
deepf1::twenty_eighteen::protobuf::TimestampedPacketMotionData timestamped_packet_pb;
timestamped_packet_pb.mutable_udp_packet()->CopyFrom(deepf1::twenty_eighteen::TwentyEighteenUDPStreamUtils::toProto(data.data));
std::chrono::duration<double, std::milli> dt = data.timestamp - begin;
timestamped_packet_pb.set_timestamp(dt.count());
size_t num_bytes = timestamped_packet_pb.ByteSize();
std::unique_ptr<char[]> buffer(new char[num_bytes]);
timestamped_packet_pb.SerializeToArray(buffer.get(),num_bytes);
boost::system::error_code error;
size_t len = socket.send_to(boost::asio::buffer(buffer.get(),num_bytes), receiver_endpoint);
//std::cout << "Sent motion packet of " << len << " bytes." << std::endl;
ready_ = true;
}
virtual inline void handleData(const deepf1::twenty_eighteen::TimestampedPacketParticipantsData& data) override
{
}
virtual inline void handleData(const deepf1::twenty_eighteen::TimestampedPacketSessionData& data) override
{
}
void init(const std::string& host, unsigned int port, const deepf1::TimePoint& begin) override
{
socket.open(udp::v4());
ready_ = true;
this->begin = begin;
}
private:
bool ready_;
std::chrono::high_resolution_clock::time_point begin;
std::string host_;
unsigned int port_;
boost::asio::io_context io_context;
udp::socket socket;
udp::endpoint receiver_endpoint;
};
class ProtoRebroadcaster_FrameGrabHandler : public deepf1::IF1FrameGrabHandler
{
public:
ProtoRebroadcaster_FrameGrabHandler(std::string host, unsigned int port, std::vector<uint32_t> roi)
: host_(host), port_(port), socket(io_context), roi_(roi)
{
receiver_endpoint = udp::endpoint(boost::asio::ip::address_v4::from_string(host_), port_);
}
virtual ~ProtoRebroadcaster_FrameGrabHandler()
{
}
bool isReady() override
{
return ready;
}
void handleData(const deepf1::TimestampedImageData& data) override
{
try
{
ready = false;
//0 32 1755 403
uint32_t x = roi_[0];
uint32_t y = roi_[1];
uint32_t w = roi_[2];
uint32_t h = roi_[3];
cv::Mat im_resize;
//std::printf("Extracting ROI: %u %u %u %u from image of size %u %u\n", x, y, w, h, data.image.rows, data.image.cols);
if (w>0 && h>0)
{
// std::cout<<"Cropping the image"<<std::endl;
cv::resize(data.image(cv::Range(y , y + h), cv::Range( x , x+w ) ),im_resize, cv::Size(/**/200,66), 1.0, 1.0, cv::INTER_AREA);
}
else{
cv::resize(data.image ,im_resize, cv::Size(), 0.25, 0.25, cv::INTER_AREA);
}
deepf1::protobuf::images::Image im_proto = deepf1::OpenCVUtils::cvimageToProto(im_resize);
size_t num_bytes = im_proto.ByteSize();
std::unique_ptr<char[]> buffer(new char[num_bytes]);
im_proto.SerializeToArray(buffer.get(),num_bytes);
boost::system::error_code error;
//std::cout << "Sending image of " << num_bytes << " bytes." << std::endl;
size_t len = socket.send_to(boost::asio::buffer(buffer.get(),num_bytes), receiver_endpoint);
//std::cout << "Sent image of " << len << " bytes." << std::endl;
ready = true;
// ready = false;
}
catch(std::exception& e)
{
std::cout<<std::string(e.what());
}
}
void init(const deepf1::TimePoint& begin, const cv::Size& window_size) override
{
std::cout << "Opening image socket" << std::endl;
socket.open(udp::v4());
std::cout << "Opened image socket" << std::endl;
ready = true;
window_made=false;
}
private:
std::string host_;
std::vector<uint32_t> roi_;
unsigned int port_;
bool ready, window_made;
float resize_factor_;
boost::asio::io_context io_context;
udp::socket socket;
udp::endpoint receiver_endpoint;
};
int main(int argc, char** argv)
{
std::string search = "F1";
float scale_factor=1.0;
uint32_t x,y,w,h;
std::cout<<argc<<std::endl;
if (argc>4)
{
x = std::stoi(std::string(argv[1]));
y = std::stoi(std::string(argv[2]));
w = std::stoi(std::string(argv[3]));
h = std::stoi(std::string(argv[4]));
}
else
{
x=0;
y=0;
w=0;
h=0;
}
std::shared_ptr<ProtoRebroadcaster_FrameGrabHandler> image_handler(new ProtoRebroadcaster_FrameGrabHandler("127.0.0.1", 50051, std::vector<uint32_t>{x,y,w,h}));
std::shared_ptr<ProtoRebroadcaster_2018DataGrabHandler> udp_handler(new ProtoRebroadcaster_2018DataGrabHandler("127.0.0.1", 50052));
std::string inp;
deepf1::F1DataLogger dl(search);
dl.add2018UDPHandler(udp_handler);
dl.start(60.0, image_handler);
std::cout<<"Ctl-c to exit."<<std::endl;
while (true)
{
std::this_thread::sleep_for( std::chrono::seconds( 5 ) );
}
}
| 33.076142 | 162 | 0.693217 | [
"geometry",
"vector"
] |
07cfb0eaf9ffdceaf07c340422ec4ee508b10d45 | 6,131 | cc | C++ | third_party_libs/dwarf-20111214/dwarfdump2/print_sections.cc | cristivlas/zerobugs | 5f080c8645b123d7887fd8a64f60e8d226e3b1d5 | [
"BSL-1.0"
] | 2 | 2018-03-19T23:27:47.000Z | 2018-06-24T16:15:19.000Z | third_party_libs/dwarf-20111214/dwarfdump2/print_sections.cc | cristivlas/zerobugs | 5f080c8645b123d7887fd8a64f60e8d226e3b1d5 | [
"BSL-1.0"
] | null | null | null | third_party_libs/dwarf-20111214/dwarfdump2/print_sections.cc | cristivlas/zerobugs | 5f080c8645b123d7887fd8a64f60e8d226e3b1d5 | [
"BSL-1.0"
] | 1 | 2021-11-28T05:39:05.000Z | 2021-11-28T05:39:05.000Z | /*
Copyright (C) 2000-2006 Silicon Graphics, Inc. All Rights Reserved.
Portions Copyright 2007-2010 Sun Microsystems, Inc. All rights reserved.
Portions Copyright 2009-2010 SN Systems Ltd. All rights reserved.
Portions Copyright 2008-2010 David Anderson. All rights reserved.
This program is free software; you can redistribute it and/or modify it
under the terms of version 2 of the GNU General Public License as
published by the Free Software Foundation.
This program is distributed in the hope that it would be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Further, this software is distributed without any warranty that it is
free of the rightful claim of any third person regarding infringement
or the like. Any license provided herein, whether implied or
otherwise, applies only to this software file. Patent licenses, if
any, provided herein do not apply to combinations of this program with
other software, or any other product whatsoever.
You should have received a copy of the GNU General Public License along
with this program; if not, write the Free Software Foundation, Inc., 51
Franklin Street - Fifth Floor, Boston MA 02110-1301, USA.
Contact information: Silicon Graphics, Inc., 1500 Crittenden Lane,
Mountain View, CA 94043, or:
http://www.sgi.com
For further information regarding this notice, see:
http://oss.sgi.com/projects/GenInfo/NoticeExplan
$Header: /plroot/cmplrs.src/v7.4.5m/.RCS/PL/dwarfdump/RCS/print_sections.c,v 1.69 2006/04/17 00:09:56 davea Exp $ */
/* The address of the Free Software Foundation is
Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
Boston, MA 02110-1301, USA.
SGI has moved from the Crittenden Lane address.
*/
// Contains functions that support printing.
// Actual section-print code is in other print_*.cc files.
#include "globals.h"
#include <vector>
#include "naming.h"
#include "dwconf.h"
#include "print_frames.h"
#include "print_sections.h"
using std::string;
using std::cout;
using std::cerr;
using std::endl;
bool dwarf_names_print_on_error = true;
/* If an offset is bad, libdwarf will notice it and
return an error.
If it does the error checking in
print_pubname_style_entry()
will be useless as we give up here on an error.
This intended for checking pubnames-style call return
values (for all the pubnames-style interfaces).
In at least one gigantic executable die_off turned out wrong.
*/
void
deal_with_name_offset_err(Dwarf_Debug dbg,
const string &err_loc,
const string &name,
Dwarf_Unsigned die_off,
int nres, Dwarf_Error err)
{
if (nres == DW_DLV_ERROR) {
Dwarf_Unsigned myerr = dwarf_errno(err);
if (myerr == DW_DLE_OFFSET_BAD) {
cout << "Error: bad offset ";
cout << err_loc;
cout << " ";
cout << name;
cout << die_off;
cout << " (";
cout << IToHex0N(die_off,10);
cout << ")" << endl;
}
print_error(dbg, err_loc, nres, err);
}
}
/* The new (April 2005) dwarf_get_section_max_offsets()
in libdwarf returns all max-offsets, but we only
want one of those offsets. This function returns
the one we want from that set,
making functions needing this offset as readable as possible.
(avoiding code duplication).
*/
Dwarf_Unsigned
get_info_max_offset(Dwarf_Debug dbg)
{
Dwarf_Unsigned debug_info_size = 0;
Dwarf_Unsigned debug_abbrev_size = 0;
Dwarf_Unsigned debug_line_size = 0;
Dwarf_Unsigned debug_loc_size = 0;
Dwarf_Unsigned debug_aranges_size = 0;
Dwarf_Unsigned debug_macinfo_size = 0;
Dwarf_Unsigned debug_pubnames_size = 0;
Dwarf_Unsigned debug_str_size = 0;
Dwarf_Unsigned debug_frame_size = 0;
Dwarf_Unsigned debug_ranges_size = 0;
Dwarf_Unsigned debug_pubtypes_size = 0;
dwarf_get_section_max_offsets(dbg,
&debug_info_size,
&debug_abbrev_size,
&debug_line_size,
&debug_loc_size,
&debug_aranges_size,
&debug_macinfo_size,
&debug_pubnames_size,
&debug_str_size,
&debug_frame_size,
&debug_ranges_size,
&debug_pubtypes_size);
return debug_info_size;
}
/*
decode ULEB
*/
Dwarf_Unsigned
local_dwarf_decode_u_leb128(unsigned char *leb128,
unsigned int *leb128_length)
{
unsigned char byte = 0;
Dwarf_Unsigned number = 0;
unsigned int shift = 0;
unsigned int byte_length = 1;
byte = *leb128;
for (;;) {
number |= (byte & 0x7f) << shift;
shift += 7;
if ((byte & 0x80) == 0) {
if (leb128_length != NULL)
*leb128_length = byte_length;
return (number);
}
byte_length++;
byte = *(++leb128);
}
}
#define BITSINBYTE 8
Dwarf_Signed
local_dwarf_decode_s_leb128(unsigned char *leb128,
unsigned int *leb128_length)
{
Dwarf_Signed number = 0;
Dwarf_Bool sign = 0;
Dwarf_Signed shift = 0;
unsigned char byte = *leb128;
Dwarf_Signed byte_length = 1;
/* byte_length being the number of bytes of data absorbed so far in
turning the leb into a Dwarf_Signed. */
for (;;) {
sign = byte & 0x40;
number |= ((Dwarf_Signed) ((byte & 0x7f))) << shift;
shift += 7;
if ((byte & 0x80) == 0) {
break;
}
++leb128;
byte = *leb128;
byte_length++;
}
if ((shift < sizeof(Dwarf_Signed) * BITSINBYTE) && sign) {
number |= -((Dwarf_Signed) 1 << shift);
}
if (leb128_length != NULL)
*leb128_length = byte_length;
return (number);
}
/* Dumping a dwarf-expression as a byte stream. */
void
dump_block(const string &prefix, char *data, Dwarf_Signed len)
{
char *end_data = data + len;
char *cur = data;
int i = 0;
cout << prefix;
for (; cur < end_data; ++cur, ++i) {
if (i > 0 && i % 4 == 0){
cout << " ";
}
cout << IToHex02(*cur);
}
}
| 28.253456 | 116 | 0.660904 | [
"vector"
] |
07d5d7a6a0fd68251a98745a8edaa4d823603cf5 | 2,045 | hpp | C++ | Box3D/include/Box3D/Renderer/Shader.hpp | Campeanu/Box3D | 2b1bb5b7b3bd66cbe6a32d910ce56ba41023dcec | [
"MIT"
] | 1 | 2020-07-20T15:55:43.000Z | 2020-07-20T15:55:43.000Z | Box3D/include/Box3D/Renderer/Shader.hpp | Campeanu/Box3D | 2b1bb5b7b3bd66cbe6a32d910ce56ba41023dcec | [
"MIT"
] | null | null | null | Box3D/include/Box3D/Renderer/Shader.hpp | Campeanu/Box3D | 2b1bb5b7b3bd66cbe6a32d910ce56ba41023dcec | [
"MIT"
] | null | null | null | #ifndef __SHADER_HPP_INCLUDED__
#define __SHADER_HPP_INCLUDED__
#include <string>
#include <vector>
#include "Box3D/Core.hpp"
#include "Box3D/Log.hpp"
#include <glm/glm.hpp>
#if defined(IMGUI_IMPL_OPENGL_LOADER_GL3W)
#include <GL/gl3w.h> // Initialize with gl3wInit()
#elif defined(IMGUI_IMPL_OPENGL_LOADER_GLEW)
#include <GL/glew.h> // Initialize with glewInit()
#elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD)
#include <glad/glad.h> // Initialize with gladLoadGL()
#else
#include IMGUI_IMPL_OPENGL_LOADER_CUSTOM
#endif
/**
* In the future we will add a shader class per Platform/Renderer so I thik that class need to be an interface.
* For now I will make this class only for OpenGL/Window platform (I don't have to mutch time now to implement this per platform).
*/
namespace box3d {
class Shader {
public:
Shader(const std::string& vertexShaderSource, const std::string& fragmentShaderSource);
virtual ~Shader();
void bind() const;
void unbind() const;
void setBool (const std::string &name, bool value) const;
void setInt (const std::string &name, int value) const;
void setFloat (const std::string &name, float value) const;
void setVec2 (const std::string &name, const glm::vec2 &value) const;
void setVec2 (const std::string &name, float x, float y) const;
void setVec3 (const std::string &name, const glm::vec3 &value) const;
void setVec3 (const std::string &name, float x, float y, float z) const;
void setVec4 (const std::string &name, const glm::vec4 &value) const;
void setVec4 (const std::string &name, float x, float y, float z, float w);
void setMat2 (const std::string &name, const glm::mat2 &mat) const;
void setMat3 (const std::string &name, const glm::mat3 &mat) const;
void setMat4 (const std::string &name, const glm::mat4 &mat) const;
private:
uint32_t m_rendererID;
};
}
#endif // !__SHADER_HPP_INCLUDED__
| 34.083333 | 130 | 0.674328 | [
"vector"
] |
07d72180aa98b992702ed8a25fd38640af86bb8b | 3,049 | cpp | C++ | src/importers.cpp | mgreter/node-sass-wasm | c26f7900fed39eb9ea3a45f3dfd9eb65f9cbb89f | [
"MIT"
] | 23 | 2019-06-22T11:45:09.000Z | 2021-09-14T08:34:42.000Z | src/importers.cpp | mgreter/node-sass-wasm | c26f7900fed39eb9ea3a45f3dfd9eb65f9cbb89f | [
"MIT"
] | 1 | 2019-10-15T10:45:44.000Z | 2019-10-23T21:26:17.000Z | src/importers.cpp | mgreter/node-sass-wasm | c26f7900fed39eb9ea3a45f3dfd9eb65f9cbb89f | [
"MIT"
] | 2 | 2019-10-12T19:00:08.000Z | 2020-01-31T12:29:17.000Z | // Copyright 2019 Google LLC
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.
#include "importers.h"
#include <optional>
#include <sass/context.h>
namespace node_sass {
using ::emscripten::val;
using ::std::nullopt;
using ::std::optional;
using ::std::string;
static Sass_Import_Entry makeError(const string& what) {
Sass_Import_Entry import = sass_make_import_entry(nullptr, nullptr, nullptr);
sass_import_set_error(import, what.c_str(), -1, -1);
return import;
}
static Sass_Import_Entry makeImport(string debugName, val value) {
if (value.isNull() || value.isUndefined() || value.typeOf().as<string>() != "object") {
return makeError("Importer error: " + debugName + " must be an object");
}
#define READ_STRING_FIELD(out_var, field_name) \
optional<string> out_var; \
{ \
val field = value[field_name]; \
if (field.isString()) { \
out_var = field.as<string>(); \
} else if (!field.isUndefined() && !field.isNull()) { \
return makeError("Importer error: " + debugName + "." + (field_name) + " must be a string if it's set"); \
} \
}
READ_STRING_FIELD(error, "__error");
READ_STRING_FIELD(file, "file");
READ_STRING_FIELD(contents, "contents");
READ_STRING_FIELD(map, "map");
if (error) return makeError(*error);
// Note well: sass_make_import_entry takes ownership of "source" and "srcmap" but makes a copy of "path".
return sass_make_import_entry(
file ? file->c_str() : nullptr,
contents ? strdup(contents->c_str()) : nullptr,
map ? strdup(map->c_str()) : nullptr);
}
Sass_Import_List runImporter(const char* cur_path, Sass_Importer_Entry cb, Sass_Compiler* comp) {
ImporterData* importerData = static_cast<ImporterData*>(sass_importer_get_cookie(cb));
val externalHelper = importerData->externalHelper;
int index = importerData->index;
Sass_Import* previous = sass_compiler_get_last_import(comp);
const char* prev_path = sass_import_get_abs_path(previous);
val helperInput = val::object();
helperInput.set("type", "importer");
helperInput.set("index", index);
helperInput.set("file", cur_path);
helperInput.set("prev", prev_path);
val helperOutput = externalHelper(helperInput);
val helperOutputDecoded = val::global("JSON").call<val>("parse", helperOutput);
if (helperOutputDecoded.isArray()) {
int length = helperOutputDecoded["length"].as<int>();
Sass_Import_List imports = sass_make_import_list(length);
for (int i = 0; i < length; i++) imports[i] = makeImport("imports[" + std::to_string(i) + "]", helperOutputDecoded[i]);
return imports;
} else if (!helperOutputDecoded.isNull() && !helperOutputDecoded.isUndefined() && !helperOutputDecoded.isFalse()) {
Sass_Import_List imports = sass_make_import_list(1);
imports[0] = makeImport("result", helperOutputDecoded);
return imports;
} else {
return nullptr;
}
}
} // namespace node_sass
| 34.647727 | 123 | 0.691702 | [
"object"
] |
07da3b7390a7ff6af3c57a990169917db5d941ff | 1,384 | hpp | C++ | src/hand.hpp | silverhammermba/bananagrams | ad2b3ec1ef28bd7604580df80ecd67456ad53858 | [
"MIT"
] | 1 | 2018-05-17T17:43:37.000Z | 2018-05-17T17:43:37.000Z | src/hand.hpp | silverhammermba/bananagrams | ad2b3ec1ef28bd7604580df80ecd67456ad53858 | [
"MIT"
] | null | null | null | src/hand.hpp | silverhammermba/bananagrams | ad2b3ec1ef28bd7604580df80ecd67456ad53858 | [
"MIT"
] | null | null | null | #ifndef HAND_HPP
#define HAND_HPP
#include <algorithm>
#include <list>
#include <sstream>
#include <SFML/Graphics.hpp>
#include "constants.hpp"
#include "tile.hpp"
// TODO inefficient
class Hand
{
std::vector<Tile*> tiles[26];
std::list<Tile*> scram; // for shuffle
std::list<Tile*> sort; // for ordered
std::list<Tile*> single; // for counts
sf::Text number[26];
sf::View gui_view;
// position tiles in std::list in nice rows
void position_list(std::list<Tile*>& l);
// tile drawing functions
void counts(sf::RenderWindow& window) const;
void stacks(sf::RenderWindow& window) const;
void ordered(sf::RenderWindow& window) const;
void scrambled(sf::RenderWindow& window) const;
void (Hand::*draw_func)(sf::RenderWindow&) const {&Hand::scrambled};
void reshuffle();
public:
Hand(const sf::Font& font);
~Hand();
inline unsigned int count(char ch) const
{
return tiles[ch - 'A'].size();
}
inline bool has_any(char ch) const
{
return count(ch) > 0;
}
void set_view(const sf::View& view);
bool is_empty() const;
void clear();
void add_tile(Tile* tile);
Tile* remove_tile(char ch);
// position whatever the current arrangement is
void position_tiles();
inline void draw_on(sf::RenderWindow& window) const
{
(this->*draw_func)(window);
}
void set_scrambled();
void set_sorted();
void set_counts();
void set_stacked();
};
#endif
| 18.453333 | 69 | 0.692919 | [
"vector"
] |
07de408da7a3107dfa468f0c47dfadad3f16941f | 5,952 | cpp | C++ | mlir/lib/Target/LLVMIR/TypeFromLLVM.cpp | ornata/llvm-project | 494913b8b4e4bce0b3525e5569d8e486e82b9a52 | [
"Apache-2.0"
] | null | null | null | mlir/lib/Target/LLVMIR/TypeFromLLVM.cpp | ornata/llvm-project | 494913b8b4e4bce0b3525e5569d8e486e82b9a52 | [
"Apache-2.0"
] | null | null | null | mlir/lib/Target/LLVMIR/TypeFromLLVM.cpp | ornata/llvm-project | 494913b8b4e4bce0b3525e5569d8e486e82b9a52 | [
"Apache-2.0"
] | null | null | null | //===- TypeFromLLVM.cpp - type translation from LLVM to MLIR IR -===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "mlir/Target/LLVMIR/TypeFromLLVM.h"
#include "mlir/Dialect/LLVMIR/LLVMTypes.h"
#include "mlir/IR/BuiltinTypes.h"
#include "mlir/IR/MLIRContext.h"
#include "llvm/ADT/TypeSwitch.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Type.h"
using namespace mlir;
namespace mlir {
namespace LLVM {
namespace detail {
/// Support for translating LLVM IR types to MLIR LLVM dialect types.
class TypeFromLLVMIRTranslatorImpl {
public:
/// Constructs a class creating types in the given MLIR context.
TypeFromLLVMIRTranslatorImpl(MLIRContext &context) : context(context) {}
/// Translates the given type.
Type translateType(llvm::Type *type) {
if (knownTranslations.count(type))
return knownTranslations.lookup(type);
Type translated =
llvm::TypeSwitch<llvm::Type *, Type>(type)
.Case<llvm::ArrayType, llvm::FunctionType, llvm::IntegerType,
llvm::PointerType, llvm::StructType, llvm::FixedVectorType,
llvm::ScalableVectorType>(
[this](auto *type) { return this->translate(type); })
.Default([this](llvm::Type *type) {
return translatePrimitiveType(type);
});
knownTranslations.try_emplace(type, translated);
return translated;
}
private:
/// Translates the given primitive, i.e. non-parametric in MLIR nomenclature,
/// type.
Type translatePrimitiveType(llvm::Type *type) {
if (type->isVoidTy())
return LLVM::LLVMVoidType::get(&context);
if (type->isHalfTy())
return Float16Type::get(&context);
if (type->isBFloatTy())
return BFloat16Type::get(&context);
if (type->isFloatTy())
return Float32Type::get(&context);
if (type->isDoubleTy())
return Float64Type::get(&context);
if (type->isFP128Ty())
return Float128Type::get(&context);
if (type->isX86_FP80Ty())
return Float80Type::get(&context);
if (type->isPPC_FP128Ty())
return LLVM::LLVMPPCFP128Type::get(&context);
if (type->isX86_MMXTy())
return LLVM::LLVMX86MMXType::get(&context);
if (type->isLabelTy())
return LLVM::LLVMLabelType::get(&context);
if (type->isMetadataTy())
return LLVM::LLVMMetadataType::get(&context);
llvm_unreachable("not a primitive type");
}
/// Translates the given array type.
Type translate(llvm::ArrayType *type) {
return LLVM::LLVMArrayType::get(translateType(type->getElementType()),
type->getNumElements());
}
/// Translates the given function type.
Type translate(llvm::FunctionType *type) {
SmallVector<Type, 8> paramTypes;
translateTypes(type->params(), paramTypes);
return LLVM::LLVMFunctionType::get(translateType(type->getReturnType()),
paramTypes, type->isVarArg());
}
/// Translates the given integer type.
Type translate(llvm::IntegerType *type) {
return IntegerType::get(&context, type->getBitWidth());
}
/// Translates the given pointer type.
Type translate(llvm::PointerType *type) {
if (type->isOpaque())
return LLVM::LLVMPointerType::get(&context, type->getAddressSpace());
return LLVM::LLVMPointerType::get(
translateType(type->getNonOpaquePointerElementType()),
type->getAddressSpace());
}
/// Translates the given structure type.
Type translate(llvm::StructType *type) {
SmallVector<Type, 8> subtypes;
if (type->isLiteral()) {
translateTypes(type->subtypes(), subtypes);
return LLVM::LLVMStructType::getLiteral(&context, subtypes,
type->isPacked());
}
if (type->isOpaque())
return LLVM::LLVMStructType::getOpaque(type->getName(), &context);
LLVM::LLVMStructType translated =
LLVM::LLVMStructType::getIdentified(&context, type->getName());
knownTranslations.try_emplace(type, translated);
translateTypes(type->subtypes(), subtypes);
LogicalResult bodySet = translated.setBody(subtypes, type->isPacked());
assert(succeeded(bodySet) &&
"could not set the body of an identified struct");
(void)bodySet;
return translated;
}
/// Translates the given fixed-vector type.
Type translate(llvm::FixedVectorType *type) {
return LLVM::getFixedVectorType(translateType(type->getElementType()),
type->getNumElements());
}
/// Translates the given scalable-vector type.
Type translate(llvm::ScalableVectorType *type) {
return LLVM::LLVMScalableVectorType::get(
translateType(type->getElementType()), type->getMinNumElements());
}
/// Translates a list of types.
void translateTypes(ArrayRef<llvm::Type *> types,
SmallVectorImpl<Type> &result) {
result.reserve(result.size() + types.size());
for (llvm::Type *type : types)
result.push_back(translateType(type));
}
/// Map of known translations. Serves as a cache and as recursion stopper for
/// translating recursive structs.
llvm::DenseMap<llvm::Type *, Type> knownTranslations;
/// The context in which MLIR types are created.
MLIRContext &context;
};
} // namespace detail
} // namespace LLVM
} // namespace mlir
LLVM::TypeFromLLVMIRTranslator::TypeFromLLVMIRTranslator(MLIRContext &context)
: impl(new detail::TypeFromLLVMIRTranslatorImpl(context)) {}
LLVM::TypeFromLLVMIRTranslator::~TypeFromLLVMIRTranslator() = default;
Type LLVM::TypeFromLLVMIRTranslator::translateType(llvm::Type *type) {
return impl->translateType(type);
}
| 35.218935 | 80 | 0.660954 | [
"vector"
] |
07dffe590ca08612156c6ec4b3a10f39c4ace202 | 3,314 | hpp | C++ | lib/boost_1.78.0/boost/geometry/views/segment_view.hpp | LaudateCorpus1/math | 990a66b3cccd27a5fd48626360bb91093a48278b | [
"BSD-3-Clause"
] | 326 | 2015-02-08T13:47:49.000Z | 2022-03-16T02:13:59.000Z | lib/boost_1.78.0/boost/geometry/views/segment_view.hpp | LaudateCorpus1/math | 990a66b3cccd27a5fd48626360bb91093a48278b | [
"BSD-3-Clause"
] | 623 | 2015-01-02T23:45:23.000Z | 2022-03-09T11:15:23.000Z | lib/boost_1.78.0/boost/geometry/views/segment_view.hpp | LaudateCorpus1/math | 990a66b3cccd27a5fd48626360bb91093a48278b | [
"BSD-3-Clause"
] | 215 | 2015-01-14T15:50:38.000Z | 2022-02-23T03:58:36.000Z | // Boost.Geometry (aka GGL, Generic Geometry Library)
// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.
// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.
// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.
// This file was modified by Oracle on 2020-2021.
// Modifications copyright (c) 2020-2021 Oracle and/or its affiliates.
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle
// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.
// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_GEOMETRY_VIEWS_SEGMENT_VIEW_HPP
#define BOOST_GEOMETRY_VIEWS_SEGMENT_VIEW_HPP
#include <array>
#include <boost/geometry/algorithms/detail/assign_indexed_point.hpp>
#include <boost/geometry/core/point_type.hpp>
#include <boost/geometry/core/tag.hpp>
namespace boost { namespace geometry
{
// NOTE: This is equivalent to the previous implementation with detail::points_view.
// Technically this should not be called a view because it owns the elements.
// It's also not a borrowed_range because of dangling iterators after the
// destruction.
// It's a container or more specifically a linestring of some sort, e.g. static_linestring.
// NOTE: It would be possible to implement a borrowed_range or a view.
// The iterators would have to store copies of points.
// Another possibility is to store the original Segment or reference/pointer
// to Segment and index. But then the reference would be the value type
// so technically they would be InputIterators not RandomAccessIterators.
/*!
\brief Makes a segment behave like a linestring or a range
\details Adapts a segment to the Boost.Range concept, enabling the user to
iterate the two segment points. The segment_view is registered as a LineString Concept
\tparam Segment \tparam_geometry{Segment}
\ingroup views
\qbk{before.synopsis,
[heading Model of]
[link geometry.reference.concepts.concept_linestring LineString Concept]
}
\qbk{[include reference/views/segment_view.qbk]}
*/
template <typename Segment>
struct segment_view
{
using array_t = std::array<typename geometry::point_type<Segment>::type, 2>;
using iterator = typename array_t::const_iterator;
using const_iterator = typename array_t::const_iterator;
/// Constructor accepting the segment to adapt
explicit segment_view(Segment const& segment)
{
geometry::detail::assign_point_from_index<0>(segment, m_array[0]);
geometry::detail::assign_point_from_index<1>(segment, m_array[1]);
}
const_iterator begin() const noexcept { return m_array.begin(); }
const_iterator end() const noexcept { return m_array.end(); }
private:
array_t m_array;
};
#ifndef DOXYGEN_NO_TRAITS_SPECIALIZATIONS
// All segment ranges can be handled as linestrings
namespace traits
{
template<typename Segment>
struct tag<segment_view<Segment> >
{
typedef linestring_tag type;
};
}
#endif // DOXYGEN_NO_TRAITS_SPECIALIZATIONS
}} // namespace boost::geometry
#endif // BOOST_GEOMETRY_VIEWS_SEGMENT_VIEW_HPP
| 32.174757 | 97 | 0.756186 | [
"geometry",
"model"
] |
2e5a25ed3d90fa81e396654a1402e3a8e204d67c | 30,391 | cpp | C++ | src/lib/foundations/finite_fields/finite_field_io.cpp | abetten/orbiter | 5994d0868a26c37676d6aadfc66a1f1bcb715c4b | [
"RSA-MD"
] | 15 | 2016-10-27T15:18:28.000Z | 2022-02-09T11:13:07.000Z | src/lib/foundations/finite_fields/finite_field_io.cpp | abetten/orbiter | 5994d0868a26c37676d6aadfc66a1f1bcb715c4b | [
"RSA-MD"
] | 4 | 2019-12-09T11:49:11.000Z | 2020-07-30T17:34:45.000Z | src/lib/foundations/finite_fields/finite_field_io.cpp | abetten/orbiter | 5994d0868a26c37676d6aadfc66a1f1bcb715c4b | [
"RSA-MD"
] | 15 | 2016-06-10T20:05:30.000Z | 2020-12-18T04:59:19.000Z | /*
* finit_field_io.cpp
*
* Created on: Jan 5, 2019
* Author: betten
*/
#include "foundations.h"
using namespace std;
namespace orbiter {
namespace foundations {
void finite_field::report(std::ostream &ost, int verbose_level)
{
ost << "\\small" << endl;
ost << "\\arraycolsep=2pt" << endl;
ost << "\\parindent=0pt" << endl;
ost << "$q = " << q << "$\\\\" << endl;
ost << "$p = " << p << "$\\\\" << endl;
ost << "$e = " << e << "$\\\\" << endl;
ost << "\\clearpage" << endl << endl;
ost << "\\section{The Finite Field with $" << q << "$ Elements}" << endl;
cheat_sheet(ost, verbose_level);
}
void finite_field::print_minimum_polynomial(int p, const char *polynomial)
{
finite_field GFp;
GFp.finite_field_init(p, FALSE /* f_without_tables */, 0);
unipoly_domain FX(&GFp);
unipoly_object m, n;
FX.create_object_by_rank_string(m, polynomial, 0);
FX.create_object_by_rank_string(n, polynomial, 0);
{
unipoly_domain Fq(&GFp, m, 0 /* verbose_level */);
Fq.print_object(n, cout);
}
//cout << "finite_field::print_minimum_polynomial "
//"before delete_object" << endl;
FX.delete_object(m);
FX.delete_object(n);
}
void finite_field::print()
{
cout << "Finite field of order " << q << endl;
}
void finite_field::print_detailed(int f_add_mult_table)
{
if (f_is_prime_field) {
print_tables();
}
else {
//char *poly;
//poly = get_primitive_polynomial(p, e, 0 /* verbose_level */);
cout << "polynomial = ";
print_minimum_polynomial(p, polynomial);
cout << endl;
//cout << " = " << poly << endl;
if (!f_has_table) {
cout << "finite_field::print_detailed !f_has_table" << endl;
exit(1);
}
T->print_tables_extension_field(polynomial);
}
if (f_add_mult_table) {
if (!f_has_table) {
cout << "finite_field::print_detailed !f_has_table" << endl;
exit(1);
}
T->print_add_mult_tables(cout);
T->print_add_mult_tables_in_C(label);
}
}
void finite_field::print_tables()
{
int i, a, b, c, l;
cout << "i : inverse(i) : frobenius_power(i, 1) : alpha_power(i) : "
"log_alpha(i)" << endl;
for (i = 0; i < q; i++) {
if (i)
a = inverse(i);
else
a = -1;
if (i)
l = log_alpha(i);
else
l = -1;
b = frobenius_power(i, 1);
c = alpha_power(i);
cout << setw(4) << i << " : "
<< setw(4) << a << " : "
<< setw(4) << b << " : "
<< setw(4) << c << " : "
<< setw(4) << l << endl;
}
}
void finite_field::display_T2(ostream &ost)
{
int i;
ost << "i & T2(i)" << endl;
for (i = 0; i < q; i++) {
ost << setw((int) log10_of_q) << i << " & "
<< setw((int) log10_of_q) << T2(i) << endl;
}
}
void finite_field::display_T3(ostream &ost)
{
int i;
ost << "i & T3(i)" << endl;
for (i = 0; i < q; i++) {
ost << setw((int) log10_of_q) << i << " & "
<< setw((int) log10_of_q) << T3(i) << endl;
}
}
void finite_field::display_N2(ostream &ost)
{
int i;
ost << "i & N2(i)" << endl;
for (i = 0; i < q; i++) {
ost << setw((int) log10_of_q) << i << " & "
<< setw((int) log10_of_q) << N2(i) << endl;
}
}
void finite_field::display_N3(ostream &ost)
{
int i;
ost << "i & N3(i)" << endl;
for (i = 0; i < q; i++) {
ost << setw((int) log10_of_q) << i << " & "
<< setw((int) log10_of_q) << N3(i) << endl;
}
}
void finite_field::print_integer_matrix_zech(ostream &ost,
int *p, int m, int n)
{
int i, j, a, h;
int w;
number_theory_domain NT;
w = (int) NT.int_log10(q);
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
a = p[i * n + j];
if (a == 0) {
for (h = 0; h < w - 1; h++)
ost << " ";
ost << ". ";
}
else {
a = log_alpha(a);
ost << setw(w) << a << " ";
}
}
ost << endl;
}
}
void finite_field::print_embedding(finite_field &subfield,
int *components, int *embedding, int *pair_embedding)
{
int Q, q, i, j;
Q = finite_field::q;
q = subfield.q;
cout << "embedding:" << endl;
for (i = 0; i < q; i++) {
cout << setw(4) << i << " : " << setw(4) << embedding[i] << endl;
}
cout << "components:" << endl;
for (i = 0; i < Q; i++) {
cout << setw(4) << i << setw(4) << components[i * 2 + 0]
<< setw(4) << components[i * 2 + 1] << endl;
}
cout << "pair_embeddings:" << endl;
for (i = 0; i < q; i++) {
for (j = 0; j < q; j++) {
cout << setw(4) << i << setw(4) << j << setw(4)
<< pair_embedding[i * q + j] << endl;
}
}
}
void finite_field::print_embedding_tex(finite_field &subfield,
int *components, int *embedding, int *pair_embedding)
{
int q, i, j, a, b, aa, bb, c;
//Q = finite_field::q;
q = subfield.q;
for (j = 0; j < q; j++) {
cout << " & ";
subfield.print_element(cout, j);
}
cout << "\\\\" << endl;
cout << "\\hline" << endl;
for (i = 0; i < q; i++) {
subfield.print_element(cout, i);
if (i == 0) {
a = 0;
}
else {
a = subfield.alpha_power(i - 1);
}
aa = embedding[a];
for (j = 0; j < q; j++) {
if (j == 0) {
b = 0;
}
else {
b = subfield.alpha_power(j - 1);
}
bb = embedding[b];
c = add(aa, mult(bb, p));
cout << " & ";
print_element(cout, c);
}
cout << "\\\\" << endl;
}
}
void finite_field::print_indicator_square_nonsquare(int a)
{
int l;
if (p == 2) {
cout << "finite_field::print_indicator_square_nonsquare "
"the characteristic is two" << endl;
exit(1);
}
if (a == 0) {
cout << "0";
}
else {
l = log_alpha(a);
if (EVEN(l)) {
cout << "+";
}
else {
cout << "-";
}
}
}
void finite_field::print_element(ostream &ost, int a)
{
int width;
if (e == 1) {
ost << a;
}
else {
if (f_print_as_exponentials) {
width = 10;
}
else {
width = log10_of_q;
}
print_element_with_symbol(ost, a, f_print_as_exponentials,
width, symbol_for_print);
}
}
void finite_field::print_element_str(stringstream &ost, int a)
{
int width;
if (e == 1) {
ost << a;
}
else {
if (f_print_as_exponentials) {
width = 10;
}
else {
width = log10_of_q;
}
print_element_with_symbol_str(ost, a, f_print_as_exponentials,
width, symbol_for_print);
}
}
void finite_field::print_element_with_symbol(ostream &ost,
int a, int f_exponential, int width, std::string &symbol)
{
int b;
if (f_exponential) {
#if 0
if (symbol == NULL) {
cout << "finite_field::print_element_with_symbol "
"symbol == NULL" << endl;
return;
}
#endif
if (a == 0) {
//print_repeated_character(ost, ' ', width - 1);
ost << "0";
}
else if (a == 1) {
//print_repeated_character(ost, ' ', width - 1);
ost << "1";
}
else {
b = log_alpha(a);
if (b == q - 1) {
b = 0;
}
ost << symbol;
if (b > 1) {
ost << "^{" << b << "}";
}
else {
ost << " ";
}
}
}
else {
ost << setw((int) width) << a;
}
}
void finite_field::print_element_with_symbol_str(stringstream &ost,
int a, int f_exponential, int width, std::string &symbol)
{
int b;
if (f_exponential) {
#if 0
if (symbol == NULL) {
cout << "finite_field::print_element_with_symbol_str "
"symbol == NULL" << endl;
return;
}
#endif
if (a == 0) {
//print_repeated_character(ost, ' ', width - 1);
ost << "0";
}
else if (a == 1) {
//print_repeated_character(ost, ' ', width - 1);
ost << "1";
}
else {
b = log_alpha(a);
if (b == q - 1) {
b = 0;
}
ost << symbol;
if (b > 1) {
ost << "^{" << b << "}";
}
else {
ost << " ";
}
}
}
else {
ost << setw((int) width) << a;
}
}
void finite_field::int_vec_print_field_elements(ostream &ost, int *v, int len)
{
int i;
ost << "(";
for (i = 0; i < len; i++) {
print_element(ost, v[i]);
if (i < len - 1) {
ost << ", ";
}
}
ost << ")";
}
void finite_field::int_vec_print_elements_exponential(ostream &ost,
int *v, int len, std::string &symbol_for_print)
{
int i;
ost << "(";
for (i = 0; i < len; i++) {
if (v[i] >= q) {
cout << "finite_field::int_vec_print_elements_exponential v[i] >= q" << endl;
cout << "v[i]=" << v[i] << endl;
exit(1);
}
print_element_with_symbol(ost, v[i],
TRUE /*f_print_as_exponentials*/,
10 /*width*/, symbol_for_print);
if (i < len - 1) {
ost << ", ";
}
}
ost << ")";
}
void finite_field::make_fname_addition_table_csv(std::string &fname)
{
char str[1000];
sprintf(str, "GF_q%d", q);
fname.assign(str);
fname.append("_addition_table.csv");
}
void finite_field::make_fname_multiplication_table_csv(std::string &fname)
{
char str[1000];
sprintf(str, "GF_q%d", q);
fname.assign(str);
fname.append("_multiplication_table.csv");
}
void finite_field::make_fname_addition_table_reordered_csv(std::string &fname)
{
char str[1000];
sprintf(str, "GF_q%d", q);
fname.assign(str);
fname.append("_addition_table_reordered.csv");
}
void finite_field::make_fname_multiplication_table_reordered_csv(std::string &fname)
{
char str[1000];
sprintf(str, "GF_q%d", q);
fname.assign(str);
fname.append("_multiplication_table_reordered.csv");
}
void finite_field::addition_table_save_csv(int verbose_level)
{
int f_v = (verbose_level >= 1);
int i, j, k;
int *M;
file_io Fio;
M = NEW_int(q * q);
for (i = 0; i < q; i++) {
for (j = 0; j < q; j++) {
k = add(i, j);
M[i * q + j] = k;
}
}
std::string fname;
make_fname_addition_table_csv(fname);
Fio.int_matrix_write_csv(fname, M, q, q);
if (f_v) {
cout << "Written file " << fname << " of size " << Fio.file_size(fname) << endl;
}
FREE_int(M);
}
void finite_field::multiplication_table_save_csv(int verbose_level)
{
int f_v = (verbose_level >= 1);
int i, j, k;
int *M;
file_io Fio;
M = NEW_int((q - 1) * (q - 1));
for (i = 0; i < q - 1; i++) {
for (j = 0; j < q - 1; j++) {
k = mult(1 + i, 1 + j);
M[i * (q - 1) + j] = k;
}
}
std::string fname;
make_fname_multiplication_table_csv(fname);
Fio.int_matrix_write_csv(fname, M, q - 1, q - 1);
if (f_v) {
cout << "Written file " << fname << " of size " << Fio.file_size(fname) << endl;
}
FREE_int(M);
}
void finite_field::addition_table_reordered_save_csv(int verbose_level)
{
if (!f_has_table) {
cout << "finite_field::addition_table_reordered_save_csv !f_has_table" << endl;
exit(1);
}
std::string fname;
make_fname_addition_table_reordered_csv(fname);
T->addition_table_reordered_save_csv(fname, verbose_level);
}
void finite_field::multiplication_table_reordered_save_csv(int verbose_level)
{
if (!f_has_table) {
cout << "finite_field::multiplication_table_reordered_save_csv !f_has_table" << endl;
exit(1);
}
std::string fname;
make_fname_multiplication_table_reordered_csv(fname);
T->multiplication_table_reordered_save_csv(fname, verbose_level);
}
void finite_field::latex_addition_table(ostream &f,
int f_elements_exponential, std::string &symbol_for_print)
{
int i, j, k;
//f << "\\arraycolsep=1pt" << endl;
f << "\\begin{array}{|r|*{" << q << "}{r}|}" << endl;
f << "\\hline" << endl;
f << "+ ";
for (i = 0; i < q; i++) {
f << " &";
print_element_with_symbol(f, i, f_elements_exponential,
10 /* width */,
symbol_for_print);
}
f << "\\\\" << endl;
f << "\\hline" << endl;
for (i = 0; i < q; i++) {
print_element_with_symbol(f, i, f_elements_exponential,
10 /* width */,
symbol_for_print);
for (j = 0; j < q; j++) {
k = add(i, j);
f << "&";
print_element_with_symbol(f, k, f_elements_exponential,
10 /* width */,
symbol_for_print);
}
f << "\\\\" << endl;
}
f << "\\hline" << endl;
f << "\\end{array}" << endl;
}
void finite_field::latex_multiplication_table(ostream &f,
int f_elements_exponential, std::string &symbol_for_print)
{
int i, j, k;
//f << "\\arraycolsep=1pt" << endl;
f << "\\begin{array}{|r|*{" << q - 1 << "}{r}|}" << endl;
f << "\\hline" << endl;
f << "\\cdot ";
for (i = 1; i < q; i++) {
f << " &";
print_element_with_symbol(f, i, f_elements_exponential,
10 /* width */,
symbol_for_print);
}
f << "\\\\" << endl;
f << "\\hline" << endl;
for (i = 1; i < q; i++) {
f << setw(3);
print_element_with_symbol(f, i, f_elements_exponential,
10 /* width */,
symbol_for_print);
for (j = 1; j < q; j++) {
k = mult(i, j);
f << "&" << setw(3);
print_element_with_symbol(f, k, f_elements_exponential,
10 /* width */,
symbol_for_print);
}
f << "\\\\" << endl;
}
f << "\\hline" << endl;
f << "\\end{array}" << endl;
}
void finite_field::latex_matrix(ostream &f, int f_elements_exponential,
std::string &symbol_for_print, int *M, int m, int n)
{
int i, j;
f << "\\begin{array}{*{" << n << "}{r}}" << endl;
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
f << setw(3);
print_element_with_symbol(f, M[i * n + j],
f_elements_exponential, 10 /* width */,
symbol_for_print);
if (j < n - 1) {
f << " & ";
}
}
f << "\\\\" << endl;
}
f << "\\end{array}" << endl;
}
void finite_field::power_table(int t,
int *power_table, int len)
{
int i;
power_table[0] = 1;
for (i = 1; i < len; i++) {
power_table[i] = mult(power_table[i - 1], t);
}
}
void finite_field::cheat_sheet(ostream &f, int verbose_level)
{
int f_v = (verbose_level >= 1);
if (f_v) {
cout << "finite_field::cheat_sheet" << endl;
}
int f_add_mult_table = TRUE;
if (f_add_mult_table) {
if (!f_has_table) {
cout << "finite_field::cheat_sheet !f_has_table" << endl;
exit(1);
}
if (f_v) {
T->print_add_mult_tables(cout);
}
T->print_add_mult_tables_in_C(label);
}
cheat_sheet_subfields(f, verbose_level);
cheat_sheet_table_of_elements(f, verbose_level);
cheat_sheet_main_table(f, verbose_level);
cheat_sheet_addition_table(f, verbose_level);
cheat_sheet_multiplication_table(f, verbose_level);
cheat_sheet_power_table(f, TRUE /* f_with_polynomials */, verbose_level);
cheat_sheet_power_table(f, FALSE /* f_with_polynomials */, verbose_level);
if (f_v) {
cout << "finite_field::cheat_sheet done" << endl;
}
}
void finite_field::cheat_sheet_subfields(ostream &f, int verbose_level)
{
int f_v = (verbose_level >= 1);
//const char *symbol_for_print = "\\alpha";
number_theory_domain NT;
if (f_v) {
cout << "finite_field::cheat_sheet_subfields" << endl;
}
//f << "\\small" << endl;
if (!f_is_prime_field) {
f << "The polynomial used to define the field is : ";
finite_field GFp;
GFp.finite_field_init(p, FALSE /* f_without_tables */, 0);
unipoly_domain FX(&GFp);
unipoly_object m;
FX.create_object_by_rank_string(m, polynomial, verbose_level - 2);
f << "$";
FX.print_object(m, f);
f << "$ = " << polynomial << "\\\\" << endl;
}
f << "$Z_i = \\log_\\alpha (1 + \\alpha^i)$\\\\" << endl;
if (!f_is_prime_field && !NT.is_prime(e)) {
report_subfields(f, verbose_level);
}
if (!f_is_prime_field) {
report_subfields_detailed(f, verbose_level);
}
if (f_v) {
cout << "finite_field::cheat_sheet_subfields done" << endl;
}
}
void finite_field::report_subfields(std::ostream &ost, int verbose_level)
{
int f_v = (verbose_level >= 1);
number_theory_domain NT;
int h;
if (f_v) {
cout << "finite_field::report_subfields" << endl;
}
ost << "\\subsection*{Subfields}" << endl;
ost << "$$" << endl;
ost << "\\begin{array}{|r|r|r|}" << endl;
ost << "\\hline" << endl;
ost << "\\mbox{Subfield} & \\mbox{Polynomial} & \\mbox{Numerical Rank} \\\\"
<< endl;
ost << "\\hline" << endl;
for (h = 2; h < e; h++) {
if ((e % h) == 0) {
ost << "\\hline" << endl;
long int poly;
poly = compute_subfield_polynomial(
NT.i_power_j(p, h),
FALSE, cout,
verbose_level);
{
finite_field GFp;
GFp.finite_field_init(p, FALSE /* f_without_tables */, 0);
unipoly_domain FX(&GFp);
unipoly_object m;
FX.create_object_by_rank_string(m, polynomial,
0/*verbose_level*/);
unipoly_domain Fq(&GFp, m, 0 /* verbose_level */);
unipoly_object elt;
FX.create_object_by_rank(elt, poly, __FILE__, __LINE__, verbose_level);
ost << "\\bbF_{" << NT.i_power_j(p, h) << "} & ";
Fq.print_object(elt, ost);
ost << " & " << poly;
ost << "\\\\" << endl;
Fq.delete_object(elt);
}
}
}
ost << "\\hline" << endl;
ost << "\\end{array}" << endl;
ost << "$$" << endl;
if (f_v) {
cout << "finite_field::report_subfields done" << endl;
}
}
void finite_field::report_subfields_detailed(std::ostream &ost, int verbose_level)
{
int f_v = (verbose_level >= 1);
number_theory_domain NT;
int h;
if (f_v) {
cout << "finite_field::report_subfields_detailed" << endl;
}
ost << "\\subsection*{Subfields in Detail}" << endl;
for (h = 1; h < e; h++) {
if (e % h) {
continue;
}
long int poly_numeric, q0;
finite_field *Fq;
Fq = NEW_OBJECT(finite_field);
q0 = NT.i_power_j(p, h);
poly_numeric = compute_subfield_polynomial(q0, TRUE, ost, verbose_level);
char str[1000];
sprintf(str, "%ld", poly_numeric);
string poly_text;
poly_text.assign(str);
Fq->init_override_polynomial(q0, poly_text, FALSE /* f_without_tables */, verbose_level);
subfield_structure *Sub;
Sub = NEW_OBJECT(subfield_structure);
Sub->init(this /* FQ */, Fq, verbose_level);
if (f_v) {
ost << "Subfield ${\\mathbb F}_{" << q0 << "}$ generated by polynomial " << poly_numeric << ":\\\\" << endl;
Sub->report(ost);
}
FREE_OBJECT(Sub);
FREE_OBJECT(Fq);
}
if (f_v) {
cout << "finite_field::report_subfields_detailed done" << endl;
}
}
void finite_field::cheat_sheet_addition_table(ostream &f, int verbose_level)
{
int f_v = (verbose_level >= 1);
if (f_v) {
cout << "finite_field::cheat_sheet_addition_table" << endl;
}
if (q <= 64) {
f << "$$" << endl;
latex_addition_table(f, FALSE /* f_elements_exponential */,
symbol_for_print);
#if 0
const char *symbol_for_print = "\\alpha";
if (q >= 10) {
f << "$$" << endl;
f << "$$" << endl;
}
else {
f << "\\qquad" << endl;
}
latex_addition_table(f, TRUE /* f_elements_exponential */,
symbol_for_print);
#endif
f << "$$" << endl;
}
else {
f << "Addition table omitted" << endl;
}
if (f_v) {
cout << "finite_field::cheat_sheet_addition_table done" << endl;
}
}
void finite_field::cheat_sheet_multiplication_table(ostream &f, int verbose_level)
{
int f_v = (verbose_level >= 1);
if (f_v) {
cout << "finite_field::cheat_sheet_multiplication_table" << endl;
}
if (q <= 64) {
f << "$$" << endl;
latex_multiplication_table(f, FALSE /* f_elements_exponential */,
symbol_for_print);
#if 0
const char *symbol_for_print = "\\alpha";
if (q >= 10) {
f << "$$" << endl;
f << "$$" << endl;
}
else {
f << "\\qquad" << endl;
}
latex_multiplication_table(f, TRUE /* f_elements_exponential */,
symbol_for_print);
#endif
f << "$$" << endl;
}
else {
f << "Multiplication table omitted" << endl;
}
if (f_v) {
cout << "finite_field::cheat_sheet_multiplication_table done" << endl;
}
}
void finite_field::cheat_sheet_power_table(std::ostream &ost, int f_with_polynomials, int verbose_level)
{
int *Powers;
int i, j, t;
int len = q;
int *v;
geometry_global Gg;
t = primitive_root();
v = NEW_int(e);
Powers = NEW_int(len);
power_table(t, Powers, len);
ost << "\\subsection*{Cyclic structure}" << endl;
ost << "$$" << endl;
cheat_sheet_power_table_top(ost, f_with_polynomials, verbose_level);
for (i = 0; i < len; i++) {
if (i && (i % 32) == 0) {
cheat_sheet_power_table_bottom(ost, f_with_polynomials, verbose_level);
ost << "$$" << endl;
ost << "$$" << endl;
cheat_sheet_power_table_top(ost, f_with_polynomials, verbose_level);
}
Gg.AG_element_unrank(p, v, 1, e, Powers[i]);
ost << i << " & " << t << "^{" << i << "} & " << Powers[i] << " & ";
for (j = e - 1; j >= 0; j--) {
ost << v[j];
}
if (f_with_polynomials) {
ost << " & ";
print_element_as_polynomial(ost, v, verbose_level);
}
ost << "\\\\" << endl;
}
cheat_sheet_power_table_bottom(ost, f_with_polynomials, verbose_level);
ost << "$$" << endl;
FREE_int(v);
FREE_int(Powers);
}
void finite_field::cheat_sheet_power_table_top(std::ostream &ost, int f_with_polynomials, int verbose_level)
{
ost << "\\begin{array}{|r|r|r|r|";
if (f_with_polynomials) {
ost << "r|";
}
ost << "}" << endl;
ost << "\\hline" << endl;
ost << "i & \\alpha^i & \\alpha^i & \\mbox{vector}";
if (f_with_polynomials) {
ost << "& \\mbox{reduced rep.}";
}
ost << "\\\\" << endl;
ost << "\\hline" << endl;
}
void finite_field::cheat_sheet_power_table_bottom(std::ostream &ost, int f_with_polynomials, int verbose_level)
{
ost << "\\hline" << endl;
ost << "\\end{array}" << endl;
}
void finite_field::cheat_sheet_table_of_elements(std::ostream &ost, int verbose_level)
{
int *v;
int i, j;
int f_first;
//std::string my_symbol;
v = NEW_int(e);
//my_symbol.assign("\alpha");
ost << "\\subsection*{Table of Elements of ${\\mathbb F}_{" << q << "}$}" << endl;
ost << "$$" << endl;
ost << "\\begin{array}{|r|r|r|}" << endl;
ost << "\\hline" << endl;
geometry_global Gg;
for (i = 0; i < q; i++) {
Gg.AG_element_unrank(p, v, 1, e, i);
ost << setw(3) << i;
ost << " & ";
f_first = TRUE;
for (j = e - 1; j >= 0; j--) {
ost << v[j];
}
ost << " & ";
print_element_as_polynomial(ost, v, verbose_level);
ost << "\\\\" << endl;
#if 0
ost << " & ";
print_element_with_symbol(ost, i,
TRUE /*f_print_as_exponentials*/,
10 /*width*/, my_symbol);
#endif
}
ost << "\\hline" << endl;
ost << "\\end{array}" << endl;
ost << "$$" << endl;
FREE_int(v);
}
void finite_field::print_element_as_polynomial(std::ostream &ost, int *v, int verbose_level)
{
int j;
int f_first = TRUE;
for (j = e - 1; j >= 0; j--) {
if (v[j] == 0) {
continue;
}
if (f_first) {
f_first = FALSE;
}
else {
ost << " + ";
}
if (j == 0 || v[j] > 1) {
ost << setw(3) << v[j];
}
if (j) {
ost << "\\alpha";
}
if (j > 1) {
ost << "^{" << j << "}";
}
}
if (f_first) {
ost << "0";
}
}
void finite_field::cheat_sheet_main_table(std::ostream &f, int verbose_level)
{
int *v;
int i, j, a;
int f_first;
v = NEW_int(e);
int nb_cols = 7;
if (e > 1) {
nb_cols += 3;
}
if ((e % 2) == 0 && e > 2) {
nb_cols += 2;
}
if ((e % 3) == 0 && e > 3) {
nb_cols += 2;
}
cheat_sheet_main_table_top(f, nb_cols);
geometry_global Gg;
for (i = 0; i < q; i++) {
Gg.AG_element_unrank(p, v, 1, e, i);
f << setw(3) << i << " & ";
f_first = TRUE;
for (j = e - 1; j >= 0; j--) {
if (v[j] == 0) {
continue;
}
if (f_first) {
f_first = FALSE;
}
else {
f << " + ";
}
if (j == 0 || v[j] > 1) {
f << setw(3) << v[j];
}
if (j) {
f << "\\alpha";
}
if (j > 1) {
f << "^{" << j << "}";
}
}
if (f_first) {
f << "0";
}
f << " = ";
print_element_with_symbol(f, i,
TRUE /*f_print_as_exponentials*/,
10 /*width*/, symbol_for_print);
// - gamma_i:
f << " &" << negate(i);
// gamma_i^{-1}:
if (i == 0) {
f << " & \\mbox{DNE}";
}
else {
f << " &" << inverse(i);
}
// log_alpha:
if (i == 0) {
f << " & \\mbox{DNE}";
}
else {
f << " &" << log_alpha(i);
}
// alpha_power:
f << " &" << alpha_power(i);
// Z_i:
a = add(1, alpha_power(i));
if (a == 0) {
f << " & \\mbox{DNE}";
}
else {
f << " &" << log_alpha(a);
}
// additional columns for extension fields:
if (e > 1) {
f << " &" << frobenius_power(i, 1);
f << " &" << absolute_trace(i);
f << " &" << absolute_norm(i);
}
if ((e % 2) == 0 && e > 2) {
f << " &" << T2(i);
f << " &" << N2(i);
}
if ((e % 3) == 0 && e > 3) {
f << " &" << T3(i);
f << " &" << N3(i);
}
f << "\\\\" << endl;
if ((i % 25) == 0 && i) {
cheat_sheet_main_table_bottom(f);
cheat_sheet_main_table_top(f, nb_cols);
}
}
cheat_sheet_main_table_bottom(f);
FREE_int(v);
}
void finite_field::cheat_sheet_main_table_top(std::ostream &f, int nb_cols)
{
f << "$$" << endl;
f << "\\begin{array}{|*{" << nb_cols << "}{r|}}" << endl;
f << "\\hline" << endl;
f << "i & \\gamma_i ";
f << "& -\\gamma_i";
f << "& \\gamma_i^{-1}";
f << "& \\log_\\alpha(\\gamma_i)";
f << "& \\alpha^i";
f << "& Z_i";
if (e > 1) {
f << "& \\phi(\\gamma_i) ";
f << "& T(\\gamma_i) ";
f << "& N(\\gamma_i) ";
}
if ((e % 2) == 0 && e > 2) {
f << "& T_2(\\gamma_i) ";
f << "& N_2(\\gamma_i) ";
}
if ((e % 3) == 0 && e > 3) {
f << "& T_3(\\gamma_i) ";
f << "& N_3(\\gamma_i) ";
}
f << "\\\\" << endl;
f << "\\hline" << endl;
}
void finite_field::cheat_sheet_main_table_bottom(std::ostream &f)
{
f << "\\hline" << endl;
f << "\\end{array}" << endl;
f << "$$" << endl;
}
void finite_field::display_table_of_projective_points(
std::ostream &ost, long int *Pts, int nb_pts, int len)
{
ost << "{\\renewcommand*{\\arraystretch}{1.5}" << endl;
ost << "$$" << endl;
display_table_of_projective_points2(ost, Pts, nb_pts, len);
ost << "$$}%" << endl;
}
void finite_field::display_table_of_projective_points2(
std::ostream &ost, long int *Pts, int nb_pts, int len)
{
int i;
int *coords;
coords = NEW_int(len);
ost << "\\begin{array}{|c|c|c|}" << endl;
ost << "\\hline" << endl;
ost << "i & a_i & P_{a_i}\\\\" << endl;
ost << "\\hline" << endl;
ost << "\\hline" << endl;
for (i = 0; i < nb_pts; i++) {
PG_element_unrank_modified_lint(coords, 1, len, Pts[i]);
ost << i << " & " << Pts[i] << " & ";
Orbiter->Int_vec.print(ost, coords, len);
ost << "\\\\" << endl;
if (((i + 1) % 30) == 0) {
ost << "\\hline" << endl;
ost << "\\end{array}" << endl;
ost << "$$}%" << endl;
ost << "$$" << endl;
ost << "\\begin{array}{|c|c|c|}" << endl;
ost << "\\hline" << endl;
ost << "i & a_i & P_{a_i}\\\\" << endl;
ost << "\\hline" << endl;
ost << "\\hline" << endl;
}
}
ost << "\\hline" << endl;
ost << "\\end{array}" << endl;
FREE_int(coords);
}
void finite_field::display_table_of_projective_points_easy(
std::ostream &ost, long int *Pts, int nb_pts, int len)
{
int i;
int *coords;
coords = NEW_int(len);
ost << "\\begin{array}{|c|}" << endl;
ost << "\\hline" << endl;
ost << "P_i\\\\" << endl;
ost << "\\hline" << endl;
ost << "\\hline" << endl;
for (i = 0; i < nb_pts; i++) {
PG_element_unrank_modified_lint(coords, 1, len, Pts[i]);
Orbiter->Int_vec.print(ost, coords, len);
ost << "\\\\" << endl;
if (((i + 1) % 30) == 0) {
ost << "\\hline" << endl;
ost << "\\end{array}" << endl;
ost << "$$}%" << endl;
ost << "$$" << endl;
ost << "\\begin{array}{|c|}" << endl;
ost << "\\hline" << endl;
ost << "P_i\\\\" << endl;
ost << "\\hline" << endl;
ost << "\\hline" << endl;
}
}
ost << "\\hline" << endl;
ost << "\\end{array}" << endl;
FREE_int(coords);
}
void finite_field::export_magma(int d, long int *Pts, int nb_pts, std::string &fname)
{
string fname2;
int *v;
int h, i, a, b;
string_tools ST;
v = NEW_int(d);
fname2.assign(fname);
ST.replace_extension_with(fname2, ".magma");
{
ofstream fp(fname2);
fp << "G,I:=PGammaL(" << d << "," << q
<< ");F:=GF(" << q << ");" << endl;
fp << "S:={};" << endl;
fp << "a := F.1;" << endl;
for (h = 0; h < nb_pts; h++) {
PG_element_unrank_modified_lint(v, 1, d, Pts[h]);
PG_element_normalize_from_front(v, 1, d);
fp << "Include(~S,Index(I,[";
for (i = 0; i < d; i++) {
a = v[i];
if (a == 0) {
fp << "0";
}
else if (a == 1) {
fp << "1";
}
else {
b = log_alpha(a);
fp << "a^" << b;
}
if (i < d - 1) {
fp << ",";
}
}
fp << "]));" << endl;
}
fp << "Stab := Stabilizer(G,S);" << endl;
fp << "Size(Stab);" << endl;
fp << endl;
}
file_io Fio;
cout << "Written file " << fname2 << " of size "
<< Fio.file_size(fname2) << endl;
FREE_int(v);
}
void finite_field::export_gap(int d, long int *Pts, int nb_pts, std::string &fname)
{
string fname2;
int *v;
int h, i, a, b;
string_tools ST;
v = NEW_int(d);
fname2.assign(fname);
ST.replace_extension_with(fname2, ".gap");
{
ofstream fp(fname2);
fp << "LoadPackage(\"fining\");" << endl;
fp << "pg := ProjectiveSpace(" << d - 1 << "," << q << ");" << endl;
fp << "S:=[" << endl;
for (h = 0; h < nb_pts; h++) {
PG_element_unrank_modified_lint(v, 1, d, Pts[h]);
PG_element_normalize_from_front(v, 1, d);
fp << "[";
for (i = 0; i < d; i++) {
a = v[i];
if (a == 0) {
fp << "0*Z(" << q << ")";
}
else if (a == 1) {
fp << "Z(" << q << ")^0";
}
else {
b = log_alpha(a);
fp << "Z(" << q << ")^" << b;
}
if (i < d - 1) {
fp << ",";
}
}
fp << "]";
if (h < nb_pts - 1) {
fp << ",";
}
fp << endl;
}
fp << "];" << endl;
fp << "S := List(S,x -> VectorSpaceToElement(pg,x));" << endl;
fp << "g := CollineationGroup(pg);" << endl;
fp << "stab := Stabilizer(g,Set(S),OnSets);" << endl;
fp << "Size(stab);" << endl;
}
file_io Fio;
cout << "Written file " << fname2 << " of size "
<< Fio.file_size(fname2) << endl;
#if 0
LoadPackage("fining");
pg := ProjectiveSpace(2,4);
#points := Points(pg);
#pointslist := AsList(points);
#Display(pointslist[1]);
frame := [[1,0,0],[0,1,0],[0,0,1],[1,1,1]]*Z(2)^0;
frame := List(frame,x -> VectorSpaceToElement(pg,x));
pairs := Combinations(frame,2);
secants := List(pairs,p -> Span(p[1],p[2]));
leftover := Filtered(pointslist,t->not ForAny(secants,s->t in s));
hyperoval := Union(frame,leftover);
g := CollineationGroup(pg);
stab := Stabilizer(g,Set(hyperoval),OnSets);
StructureDescription(stab);
#endif
FREE_int(v);
}
void finite_field::print_matrix_latex(std::ostream &ost, int *A, int m, int n)
{
int i, j, a;
ost << "\\left[" << endl;
ost << "\\begin{array}{*{" << n << "}{r}}" << endl;
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
a = A[i * n + j];
#if 0
if (is_prime(GFq->q)) {
ost << setw(w) << a << " ";
}
else {
ost << a;
// GFq->print_element(ost, a);
}
#else
print_element(ost, a);
#endif
if (j < n - 1)
ost << " & ";
}
ost << "\\\\" << endl;
}
ost << "\\end{array}" << endl;
ost << "\\right]" << endl;
}
void finite_field::print_matrix_numerical_latex(std::ostream &ost, int *A, int m, int n)
{
int i, j, a;
ost << "\\left[" << endl;
ost << "\\begin{array}{*{" << n << "}{r}}" << endl;
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
a = A[i * n + j];
ost << a;
if (j < n - 1)
ost << " & ";
}
ost << "\\\\" << endl;
}
ost << "\\end{array}" << endl;
ost << "\\right]" << endl;
}
}}
| 20.007242 | 111 | 0.55115 | [
"vector"
] |
2e64e7e7979bb16259bd3818a72c7a648e4c88b8 | 293,074 | cpp | C++ | WindowsPC/Il2CppOutputProject/Source/il2cppOutput/Il2CppCompilerCalculateTypeValues_29Table.cpp | ludaher/HumanoVirtual | 3b65d54ea4e5e17c24dd1595da39a107e8b29e46 | [
"MIT"
] | null | null | null | WindowsPC/Il2CppOutputProject/Source/il2cppOutput/Il2CppCompilerCalculateTypeValues_29Table.cpp | ludaher/HumanoVirtual | 3b65d54ea4e5e17c24dd1595da39a107e8b29e46 | [
"MIT"
] | null | null | null | WindowsPC/Il2CppOutputProject/Source/il2cppOutput/Il2CppCompilerCalculateTypeValues_29Table.cpp | ludaher/HumanoVirtual | 3b65d54ea4e5e17c24dd1595da39a107e8b29e46 | [
"MIT"
] | null | null | null | #include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <cstring>
#include <string.h>
#include <stdio.h>
#include <cmath>
#include <limits>
#include <assert.h>
#include <stdint.h>
#include "class-internals.h"
#include "codegen/il2cpp-codegen.h"
#include "object-internals.h"
// System.Collections.Hashtable
struct Hashtable_t909839986;
// System.Collections.ArrayList
struct ArrayList_t4252133567;
// System.Configuration.ConfigurationSectionCollection
struct ConfigurationSectionCollection_t4261113299;
// System.Configuration.ConfigurationSectionGroupCollection
struct ConfigurationSectionGroupCollection_t575145286;
// System.Configuration.Configuration
struct Configuration_t3335372970;
// System.Configuration.SectionGroupInfo
struct SectionGroupInfo_t2346323570;
// System.Collections.IEnumerator
struct IEnumerator_t1466026749;
// System.String
struct String_t;
// System.Collections.Generic.List`1<System.Configuration.ConfigurationProperty>
struct List_1_t1417187943;
// System.Collections.IEqualityComparer
struct IEqualityComparer_t2716208158;
// System.Collections.Specialized.NameObjectCollectionBase/NameObjectEntry
struct NameObjectEntry_t4229094479;
// System.Collections.Specialized.NameObjectCollectionBase/KeysCollection
struct KeysCollection_t633582367;
// System.Runtime.Serialization.SerializationInfo
struct SerializationInfo_t228987430;
// System.StringComparer
struct StringComparer_t1574862926;
// System.Configuration.Internal.IInternalConfigHost
struct IInternalConfigHost_t3115158152;
// System.Configuration.Internal.IInternalConfigRoot
struct IInternalConfigRoot_t3316671250;
// System.Object[]
struct ObjectU5BU5D_t3614634134;
// System.Configuration.PropertyInformationCollection
struct PropertyInformationCollection_t954922393;
// UnityEngine.Application/LowMemoryCallback
struct LowMemoryCallback_t642977590;
// UnityEngine.Application/LogCallback
struct LogCallback_t1867914413;
// UnityEngine.Events.UnityAction
struct UnityAction_t4025899511;
// System.Configuration.PropertyInformation
struct PropertyInformation_t2089433965;
// System.Configuration.ConfigurationElement
struct ConfigurationElement_t1776195828;
// System.Configuration.ElementMap
struct ElementMap_t997038224;
// System.Configuration.ConfigurationPropertyCollection
struct ConfigurationPropertyCollection_t3473514151;
// System.Configuration.ConfigurationElementCollection
struct ConfigurationElementCollection_t1911180302;
// System.Configuration.ElementInformation
struct ElementInformation_t3165583784;
// System.Configuration.ConfigurationLockCollection
struct ConfigurationLockCollection_t1011762925;
// System.Configuration.ConfigurationElement/SaveContext
struct SaveContext_t3996373180;
// System.Configuration.ConfigurationCollectionAttribute
struct ConfigurationCollectionAttribute_t2811353736;
// System.Configuration.ConfigurationSectionGroup
struct ConfigurationSectionGroup_t2230982736;
// System.Configuration.ConfigurationLocationCollection
struct ConfigurationLocationCollection_t1903842989;
// System.Configuration.Internal.IConfigSystem
struct IConfigSystem_t2950865222;
// System.Type
struct Type_t;
// System.Collections.IDictionary
struct IDictionary_t596158605;
// System.Runtime.Serialization.SafeSerializationManager
struct SafeSerializationManager_t1975884510;
// System.Diagnostics.StackTrace[]
struct StackTraceU5BU5D_t2217612696;
// System.IntPtr[]
struct IntPtrU5BU5D_t169632028;
// System.Char[]
struct CharU5BU5D_t1328083999;
// System.Configuration.InternalConfigurationFactory
struct InternalConfigurationFactory_t3846641927;
// System.Configuration.Internal.IInternalConfigSystem
struct IInternalConfigSystem_t344849519;
// System.Configuration.ConfigInfoCollection
struct ConfigInfoCollection_t3264723080;
// System.Configuration.ConfigNameValueCollection
struct ConfigNameValueCollection_t2395569530;
// System.Configuration.ConfigurationProperty
struct ConfigurationProperty_t2048066811;
// System.Configuration.SectionInformation
struct SectionInformation_t2754609709;
// System.Configuration.IConfigurationSectionHandler
struct IConfigurationSectionHandler_t4214479838;
// System.Collections.IComparer
struct IComparer_t3952557350;
// System.Void
struct Void_t1841601450;
// System.Xml.XmlImplementation
struct XmlImplementation_t1664517635;
// System.Xml.DomNameTable
struct DomNameTable_t3442363663;
// System.Xml.XmlLinkedNode
struct XmlLinkedNode_t1287616130;
// System.Xml.XmlNamedNodeMap
struct XmlNamedNodeMap_t145210370;
// System.Xml.Schema.SchemaInfo
struct SchemaInfo_t87206461;
// System.Xml.Schema.XmlSchemaSet
struct XmlSchemaSet_t313318308;
// System.Xml.XmlNodeChangedEventHandler
struct XmlNodeChangedEventHandler_t2964483403;
// System.Xml.XmlResolver
struct XmlResolver_t2024571559;
// System.Xml.EmptyEnumerator
struct EmptyEnumerator_t2328036233;
// System.Xml.Schema.IXmlSchemaInfo
struct IXmlSchemaInfo_t2533799901;
// System.Configuration.ConfigurationValidatorBase
struct ConfigurationValidatorBase_t210547623;
// System.Reflection.MethodInfo
struct MethodInfo_t;
// System.DelegateData
struct DelegateData_t1572802995;
// System.Action`1<UnityEngine.AsyncOperation>
struct Action_1_t3616431661;
// System.Configuration.ProtectedConfigurationProviderCollection
struct ProtectedConfigurationProviderCollection_t388338823;
// System.Configuration.ConfigurationSection
struct ConfigurationSection_t2600766927;
// System.Configuration.ProtectedConfigurationProvider
struct ProtectedConfigurationProvider_t3971982415;
// System.Delegate[]
struct DelegateU5BU5D_t1606206610;
// System.Byte[]
struct ByteU5BU5D_t3397334013;
// System.Security.Cryptography.KeySizes[]
struct KeySizesU5BU5D_t1153004758;
// System.ComponentModel.TypeConverter
struct TypeConverter_t745995970;
// System.Configuration.ExeConfigurationFileMap
struct ExeConfigurationFileMap_t1419586304;
// System.Security.Cryptography.SymmetricAlgorithm
struct SymmetricAlgorithm_t1108166522;
// System.Security.Cryptography.RandomNumberGenerator
struct RandomNumberGenerator_t2510243513;
// System.UInt32[]
struct UInt32U5BU5D_t59386216;
// System.IAsyncResult
struct IAsyncResult_t1999651008;
// System.AsyncCallback
struct AsyncCallback_t163412349;
// System.Security.Cryptography.RijndaelManaged
struct RijndaelManaged_t1034060848;
struct Exception_t1927440687_marshaled_pinvoke;
struct Exception_t1927440687_marshaled_com;
#ifndef RUNTIMEOBJECT_H
#define RUNTIMEOBJECT_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Object
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // RUNTIMEOBJECT_H
#ifndef U3CMODULEU3E_T3783534219_H
#define U3CMODULEU3E_T3783534219_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// <Module>
struct U3CModuleU3E_t3783534219
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // U3CMODULEU3E_T3783534219_H
#ifndef U3CMODULEU3E_T3783534220_H
#define U3CMODULEU3E_T3783534220_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// <Module>
struct U3CModuleU3E_t3783534220
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // U3CMODULEU3E_T3783534220_H
#ifndef PROVIDERCOLLECTION_T2548499159_H
#define PROVIDERCOLLECTION_T2548499159_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.Provider.ProviderCollection
struct ProviderCollection_t2548499159 : public RuntimeObject
{
public:
// System.Collections.Hashtable System.Configuration.Provider.ProviderCollection::lookup
Hashtable_t909839986 * ___lookup_0;
// System.Boolean System.Configuration.Provider.ProviderCollection::readOnly
bool ___readOnly_1;
// System.Collections.ArrayList System.Configuration.Provider.ProviderCollection::values
ArrayList_t4252133567 * ___values_2;
public:
inline static int32_t get_offset_of_lookup_0() { return static_cast<int32_t>(offsetof(ProviderCollection_t2548499159, ___lookup_0)); }
inline Hashtable_t909839986 * get_lookup_0() const { return ___lookup_0; }
inline Hashtable_t909839986 ** get_address_of_lookup_0() { return &___lookup_0; }
inline void set_lookup_0(Hashtable_t909839986 * value)
{
___lookup_0 = value;
Il2CppCodeGenWriteBarrier((&___lookup_0), value);
}
inline static int32_t get_offset_of_readOnly_1() { return static_cast<int32_t>(offsetof(ProviderCollection_t2548499159, ___readOnly_1)); }
inline bool get_readOnly_1() const { return ___readOnly_1; }
inline bool* get_address_of_readOnly_1() { return &___readOnly_1; }
inline void set_readOnly_1(bool value)
{
___readOnly_1 = value;
}
inline static int32_t get_offset_of_values_2() { return static_cast<int32_t>(offsetof(ProviderCollection_t2548499159, ___values_2)); }
inline ArrayList_t4252133567 * get_values_2() const { return ___values_2; }
inline ArrayList_t4252133567 ** get_address_of_values_2() { return &___values_2; }
inline void set_values_2(ArrayList_t4252133567 * value)
{
___values_2 = value;
Il2CppCodeGenWriteBarrier((&___values_2), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // PROVIDERCOLLECTION_T2548499159_H
#ifndef CONFIGURATIONSECTIONGROUP_T2230982736_H
#define CONFIGURATIONSECTIONGROUP_T2230982736_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.ConfigurationSectionGroup
struct ConfigurationSectionGroup_t2230982736 : public RuntimeObject
{
public:
// System.Configuration.ConfigurationSectionCollection System.Configuration.ConfigurationSectionGroup::sections
ConfigurationSectionCollection_t4261113299 * ___sections_0;
// System.Configuration.ConfigurationSectionGroupCollection System.Configuration.ConfigurationSectionGroup::groups
ConfigurationSectionGroupCollection_t575145286 * ___groups_1;
// System.Configuration.Configuration System.Configuration.ConfigurationSectionGroup::config
Configuration_t3335372970 * ___config_2;
// System.Configuration.SectionGroupInfo System.Configuration.ConfigurationSectionGroup::group
SectionGroupInfo_t2346323570 * ___group_3;
// System.Boolean System.Configuration.ConfigurationSectionGroup::initialized
bool ___initialized_4;
public:
inline static int32_t get_offset_of_sections_0() { return static_cast<int32_t>(offsetof(ConfigurationSectionGroup_t2230982736, ___sections_0)); }
inline ConfigurationSectionCollection_t4261113299 * get_sections_0() const { return ___sections_0; }
inline ConfigurationSectionCollection_t4261113299 ** get_address_of_sections_0() { return &___sections_0; }
inline void set_sections_0(ConfigurationSectionCollection_t4261113299 * value)
{
___sections_0 = value;
Il2CppCodeGenWriteBarrier((&___sections_0), value);
}
inline static int32_t get_offset_of_groups_1() { return static_cast<int32_t>(offsetof(ConfigurationSectionGroup_t2230982736, ___groups_1)); }
inline ConfigurationSectionGroupCollection_t575145286 * get_groups_1() const { return ___groups_1; }
inline ConfigurationSectionGroupCollection_t575145286 ** get_address_of_groups_1() { return &___groups_1; }
inline void set_groups_1(ConfigurationSectionGroupCollection_t575145286 * value)
{
___groups_1 = value;
Il2CppCodeGenWriteBarrier((&___groups_1), value);
}
inline static int32_t get_offset_of_config_2() { return static_cast<int32_t>(offsetof(ConfigurationSectionGroup_t2230982736, ___config_2)); }
inline Configuration_t3335372970 * get_config_2() const { return ___config_2; }
inline Configuration_t3335372970 ** get_address_of_config_2() { return &___config_2; }
inline void set_config_2(Configuration_t3335372970 * value)
{
___config_2 = value;
Il2CppCodeGenWriteBarrier((&___config_2), value);
}
inline static int32_t get_offset_of_group_3() { return static_cast<int32_t>(offsetof(ConfigurationSectionGroup_t2230982736, ___group_3)); }
inline SectionGroupInfo_t2346323570 * get_group_3() const { return ___group_3; }
inline SectionGroupInfo_t2346323570 ** get_address_of_group_3() { return &___group_3; }
inline void set_group_3(SectionGroupInfo_t2346323570 * value)
{
___group_3 = value;
Il2CppCodeGenWriteBarrier((&___group_3), value);
}
inline static int32_t get_offset_of_initialized_4() { return static_cast<int32_t>(offsetof(ConfigurationSectionGroup_t2230982736, ___initialized_4)); }
inline bool get_initialized_4() const { return ___initialized_4; }
inline bool* get_address_of_initialized_4() { return &___initialized_4; }
inline void set_initialized_4(bool value)
{
___initialized_4 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // CONFIGURATIONSECTIONGROUP_T2230982736_H
#ifndef U3CGETENUMERATORU3ED__17_T2724409453_H
#define U3CGETENUMERATORU3ED__17_T2724409453_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.ConfigurationSectionCollection/<GetEnumerator>d__17
struct U3CGetEnumeratorU3Ed__17_t2724409453 : public RuntimeObject
{
public:
// System.Int32 System.Configuration.ConfigurationSectionCollection/<GetEnumerator>d__17::<>1__state
int32_t ___U3CU3E1__state_0;
// System.Object System.Configuration.ConfigurationSectionCollection/<GetEnumerator>d__17::<>2__current
RuntimeObject * ___U3CU3E2__current_1;
// System.Configuration.ConfigurationSectionCollection System.Configuration.ConfigurationSectionCollection/<GetEnumerator>d__17::<>4__this
ConfigurationSectionCollection_t4261113299 * ___U3CU3E4__this_2;
// System.Collections.IEnumerator System.Configuration.ConfigurationSectionCollection/<GetEnumerator>d__17::<>7__wrap1
RuntimeObject* ___U3CU3E7__wrap1_3;
public:
inline static int32_t get_offset_of_U3CU3E1__state_0() { return static_cast<int32_t>(offsetof(U3CGetEnumeratorU3Ed__17_t2724409453, ___U3CU3E1__state_0)); }
inline int32_t get_U3CU3E1__state_0() const { return ___U3CU3E1__state_0; }
inline int32_t* get_address_of_U3CU3E1__state_0() { return &___U3CU3E1__state_0; }
inline void set_U3CU3E1__state_0(int32_t value)
{
___U3CU3E1__state_0 = value;
}
inline static int32_t get_offset_of_U3CU3E2__current_1() { return static_cast<int32_t>(offsetof(U3CGetEnumeratorU3Ed__17_t2724409453, ___U3CU3E2__current_1)); }
inline RuntimeObject * get_U3CU3E2__current_1() const { return ___U3CU3E2__current_1; }
inline RuntimeObject ** get_address_of_U3CU3E2__current_1() { return &___U3CU3E2__current_1; }
inline void set_U3CU3E2__current_1(RuntimeObject * value)
{
___U3CU3E2__current_1 = value;
Il2CppCodeGenWriteBarrier((&___U3CU3E2__current_1), value);
}
inline static int32_t get_offset_of_U3CU3E4__this_2() { return static_cast<int32_t>(offsetof(U3CGetEnumeratorU3Ed__17_t2724409453, ___U3CU3E4__this_2)); }
inline ConfigurationSectionCollection_t4261113299 * get_U3CU3E4__this_2() const { return ___U3CU3E4__this_2; }
inline ConfigurationSectionCollection_t4261113299 ** get_address_of_U3CU3E4__this_2() { return &___U3CU3E4__this_2; }
inline void set_U3CU3E4__this_2(ConfigurationSectionCollection_t4261113299 * value)
{
___U3CU3E4__this_2 = value;
Il2CppCodeGenWriteBarrier((&___U3CU3E4__this_2), value);
}
inline static int32_t get_offset_of_U3CU3E7__wrap1_3() { return static_cast<int32_t>(offsetof(U3CGetEnumeratorU3Ed__17_t2724409453, ___U3CU3E7__wrap1_3)); }
inline RuntimeObject* get_U3CU3E7__wrap1_3() const { return ___U3CU3E7__wrap1_3; }
inline RuntimeObject** get_address_of_U3CU3E7__wrap1_3() { return &___U3CU3E7__wrap1_3; }
inline void set_U3CU3E7__wrap1_3(RuntimeObject* value)
{
___U3CU3E7__wrap1_3 = value;
Il2CppCodeGenWriteBarrier((&___U3CU3E7__wrap1_3), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // U3CGETENUMERATORU3ED__17_T2724409453_H
#ifndef PROVIDERBASE_T2882126354_H
#define PROVIDERBASE_T2882126354_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.Provider.ProviderBase
struct ProviderBase_t2882126354 : public RuntimeObject
{
public:
// System.Boolean System.Configuration.Provider.ProviderBase::alreadyInitialized
bool ___alreadyInitialized_0;
// System.String System.Configuration.Provider.ProviderBase::_description
String_t* ____description_1;
// System.String System.Configuration.Provider.ProviderBase::_name
String_t* ____name_2;
public:
inline static int32_t get_offset_of_alreadyInitialized_0() { return static_cast<int32_t>(offsetof(ProviderBase_t2882126354, ___alreadyInitialized_0)); }
inline bool get_alreadyInitialized_0() const { return ___alreadyInitialized_0; }
inline bool* get_address_of_alreadyInitialized_0() { return &___alreadyInitialized_0; }
inline void set_alreadyInitialized_0(bool value)
{
___alreadyInitialized_0 = value;
}
inline static int32_t get_offset_of__description_1() { return static_cast<int32_t>(offsetof(ProviderBase_t2882126354, ____description_1)); }
inline String_t* get__description_1() const { return ____description_1; }
inline String_t** get_address_of__description_1() { return &____description_1; }
inline void set__description_1(String_t* value)
{
____description_1 = value;
Il2CppCodeGenWriteBarrier((&____description_1), value);
}
inline static int32_t get_offset_of__name_2() { return static_cast<int32_t>(offsetof(ProviderBase_t2882126354, ____name_2)); }
inline String_t* get__name_2() const { return ____name_2; }
inline String_t** get_address_of__name_2() { return &____name_2; }
inline void set__name_2(String_t* value)
{
____name_2 = value;
Il2CppCodeGenWriteBarrier((&____name_2), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // PROVIDERBASE_T2882126354_H
#ifndef CONFIGURATIONPROPERTYCOLLECTION_T3473514151_H
#define CONFIGURATIONPROPERTYCOLLECTION_T3473514151_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.ConfigurationPropertyCollection
struct ConfigurationPropertyCollection_t3473514151 : public RuntimeObject
{
public:
// System.Collections.Generic.List`1<System.Configuration.ConfigurationProperty> System.Configuration.ConfigurationPropertyCollection::collection
List_1_t1417187943 * ___collection_0;
public:
inline static int32_t get_offset_of_collection_0() { return static_cast<int32_t>(offsetof(ConfigurationPropertyCollection_t3473514151, ___collection_0)); }
inline List_1_t1417187943 * get_collection_0() const { return ___collection_0; }
inline List_1_t1417187943 ** get_address_of_collection_0() { return &___collection_0; }
inline void set_collection_0(List_1_t1417187943 * value)
{
___collection_0 = value;
Il2CppCodeGenWriteBarrier((&___collection_0), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // CONFIGURATIONPROPERTYCOLLECTION_T3473514151_H
#ifndef NAMEOBJECTCOLLECTIONBASE_T2034248631_H
#define NAMEOBJECTCOLLECTIONBASE_T2034248631_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Collections.Specialized.NameObjectCollectionBase
struct NameObjectCollectionBase_t2034248631 : public RuntimeObject
{
public:
// System.Boolean System.Collections.Specialized.NameObjectCollectionBase::_readOnly
bool ____readOnly_0;
// System.Collections.ArrayList System.Collections.Specialized.NameObjectCollectionBase::_entriesArray
ArrayList_t4252133567 * ____entriesArray_1;
// System.Collections.IEqualityComparer System.Collections.Specialized.NameObjectCollectionBase::_keyComparer
RuntimeObject* ____keyComparer_2;
// System.Collections.Hashtable modreq(System.Runtime.CompilerServices.IsVolatile) System.Collections.Specialized.NameObjectCollectionBase::_entriesTable
Hashtable_t909839986 * ____entriesTable_3;
// System.Collections.Specialized.NameObjectCollectionBase/NameObjectEntry modreq(System.Runtime.CompilerServices.IsVolatile) System.Collections.Specialized.NameObjectCollectionBase::_nullKeyEntry
NameObjectEntry_t4229094479 * ____nullKeyEntry_4;
// System.Collections.Specialized.NameObjectCollectionBase/KeysCollection System.Collections.Specialized.NameObjectCollectionBase::_keys
KeysCollection_t633582367 * ____keys_5;
// System.Runtime.Serialization.SerializationInfo System.Collections.Specialized.NameObjectCollectionBase::_serializationInfo
SerializationInfo_t228987430 * ____serializationInfo_6;
// System.Int32 System.Collections.Specialized.NameObjectCollectionBase::_version
int32_t ____version_7;
// System.Object System.Collections.Specialized.NameObjectCollectionBase::_syncRoot
RuntimeObject * ____syncRoot_8;
public:
inline static int32_t get_offset_of__readOnly_0() { return static_cast<int32_t>(offsetof(NameObjectCollectionBase_t2034248631, ____readOnly_0)); }
inline bool get__readOnly_0() const { return ____readOnly_0; }
inline bool* get_address_of__readOnly_0() { return &____readOnly_0; }
inline void set__readOnly_0(bool value)
{
____readOnly_0 = value;
}
inline static int32_t get_offset_of__entriesArray_1() { return static_cast<int32_t>(offsetof(NameObjectCollectionBase_t2034248631, ____entriesArray_1)); }
inline ArrayList_t4252133567 * get__entriesArray_1() const { return ____entriesArray_1; }
inline ArrayList_t4252133567 ** get_address_of__entriesArray_1() { return &____entriesArray_1; }
inline void set__entriesArray_1(ArrayList_t4252133567 * value)
{
____entriesArray_1 = value;
Il2CppCodeGenWriteBarrier((&____entriesArray_1), value);
}
inline static int32_t get_offset_of__keyComparer_2() { return static_cast<int32_t>(offsetof(NameObjectCollectionBase_t2034248631, ____keyComparer_2)); }
inline RuntimeObject* get__keyComparer_2() const { return ____keyComparer_2; }
inline RuntimeObject** get_address_of__keyComparer_2() { return &____keyComparer_2; }
inline void set__keyComparer_2(RuntimeObject* value)
{
____keyComparer_2 = value;
Il2CppCodeGenWriteBarrier((&____keyComparer_2), value);
}
inline static int32_t get_offset_of__entriesTable_3() { return static_cast<int32_t>(offsetof(NameObjectCollectionBase_t2034248631, ____entriesTable_3)); }
inline Hashtable_t909839986 * get__entriesTable_3() const { return ____entriesTable_3; }
inline Hashtable_t909839986 ** get_address_of__entriesTable_3() { return &____entriesTable_3; }
inline void set__entriesTable_3(Hashtable_t909839986 * value)
{
____entriesTable_3 = value;
Il2CppCodeGenWriteBarrier((&____entriesTable_3), value);
}
inline static int32_t get_offset_of__nullKeyEntry_4() { return static_cast<int32_t>(offsetof(NameObjectCollectionBase_t2034248631, ____nullKeyEntry_4)); }
inline NameObjectEntry_t4229094479 * get__nullKeyEntry_4() const { return ____nullKeyEntry_4; }
inline NameObjectEntry_t4229094479 ** get_address_of__nullKeyEntry_4() { return &____nullKeyEntry_4; }
inline void set__nullKeyEntry_4(NameObjectEntry_t4229094479 * value)
{
____nullKeyEntry_4 = value;
Il2CppCodeGenWriteBarrier((&____nullKeyEntry_4), value);
}
inline static int32_t get_offset_of__keys_5() { return static_cast<int32_t>(offsetof(NameObjectCollectionBase_t2034248631, ____keys_5)); }
inline KeysCollection_t633582367 * get__keys_5() const { return ____keys_5; }
inline KeysCollection_t633582367 ** get_address_of__keys_5() { return &____keys_5; }
inline void set__keys_5(KeysCollection_t633582367 * value)
{
____keys_5 = value;
Il2CppCodeGenWriteBarrier((&____keys_5), value);
}
inline static int32_t get_offset_of__serializationInfo_6() { return static_cast<int32_t>(offsetof(NameObjectCollectionBase_t2034248631, ____serializationInfo_6)); }
inline SerializationInfo_t228987430 * get__serializationInfo_6() const { return ____serializationInfo_6; }
inline SerializationInfo_t228987430 ** get_address_of__serializationInfo_6() { return &____serializationInfo_6; }
inline void set__serializationInfo_6(SerializationInfo_t228987430 * value)
{
____serializationInfo_6 = value;
Il2CppCodeGenWriteBarrier((&____serializationInfo_6), value);
}
inline static int32_t get_offset_of__version_7() { return static_cast<int32_t>(offsetof(NameObjectCollectionBase_t2034248631, ____version_7)); }
inline int32_t get__version_7() const { return ____version_7; }
inline int32_t* get_address_of__version_7() { return &____version_7; }
inline void set__version_7(int32_t value)
{
____version_7 = value;
}
inline static int32_t get_offset_of__syncRoot_8() { return static_cast<int32_t>(offsetof(NameObjectCollectionBase_t2034248631, ____syncRoot_8)); }
inline RuntimeObject * get__syncRoot_8() const { return ____syncRoot_8; }
inline RuntimeObject ** get_address_of__syncRoot_8() { return &____syncRoot_8; }
inline void set__syncRoot_8(RuntimeObject * value)
{
____syncRoot_8 = value;
Il2CppCodeGenWriteBarrier((&____syncRoot_8), value);
}
};
struct NameObjectCollectionBase_t2034248631_StaticFields
{
public:
// System.StringComparer System.Collections.Specialized.NameObjectCollectionBase::defaultComparer
StringComparer_t1574862926 * ___defaultComparer_9;
public:
inline static int32_t get_offset_of_defaultComparer_9() { return static_cast<int32_t>(offsetof(NameObjectCollectionBase_t2034248631_StaticFields, ___defaultComparer_9)); }
inline StringComparer_t1574862926 * get_defaultComparer_9() const { return ___defaultComparer_9; }
inline StringComparer_t1574862926 ** get_address_of_defaultComparer_9() { return &___defaultComparer_9; }
inline void set_defaultComparer_9(StringComparer_t1574862926 * value)
{
___defaultComparer_9 = value;
Il2CppCodeGenWriteBarrier((&___defaultComparer_9), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // NAMEOBJECTCOLLECTIONBASE_T2034248631_H
#ifndef READONLYCOLLECTIONBASE_T22281769_H
#define READONLYCOLLECTIONBASE_T22281769_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Collections.ReadOnlyCollectionBase
struct ReadOnlyCollectionBase_t22281769 : public RuntimeObject
{
public:
// System.Collections.ArrayList System.Collections.ReadOnlyCollectionBase::list
ArrayList_t4252133567 * ___list_0;
public:
inline static int32_t get_offset_of_list_0() { return static_cast<int32_t>(offsetof(ReadOnlyCollectionBase_t22281769, ___list_0)); }
inline ArrayList_t4252133567 * get_list_0() const { return ___list_0; }
inline ArrayList_t4252133567 ** get_address_of_list_0() { return &___list_0; }
inline void set_list_0(ArrayList_t4252133567 * value)
{
___list_0 = value;
Il2CppCodeGenWriteBarrier((&___list_0), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // READONLYCOLLECTIONBASE_T22281769_H
#ifndef CODEACCESSPERMISSION_T3468021764_H
#define CODEACCESSPERMISSION_T3468021764_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.CodeAccessPermission
struct CodeAccessPermission_t3468021764 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // CODEACCESSPERMISSION_T3468021764_H
#ifndef INTERNALCONFIGURATIONHOST_T547577555_H
#define INTERNALCONFIGURATIONHOST_T547577555_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.InternalConfigurationHost
struct InternalConfigurationHost_t547577555 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // INTERNALCONFIGURATIONHOST_T547577555_H
#ifndef INTERNALCONFIGURATIONSYSTEM_T2108740756_H
#define INTERNALCONFIGURATIONSYSTEM_T2108740756_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.InternalConfigurationSystem
struct InternalConfigurationSystem_t2108740756 : public RuntimeObject
{
public:
// System.Configuration.Internal.IInternalConfigHost System.Configuration.InternalConfigurationSystem::host
RuntimeObject* ___host_0;
// System.Configuration.Internal.IInternalConfigRoot System.Configuration.InternalConfigurationSystem::root
RuntimeObject* ___root_1;
// System.Object[] System.Configuration.InternalConfigurationSystem::hostInitParams
ObjectU5BU5D_t3614634134* ___hostInitParams_2;
public:
inline static int32_t get_offset_of_host_0() { return static_cast<int32_t>(offsetof(InternalConfigurationSystem_t2108740756, ___host_0)); }
inline RuntimeObject* get_host_0() const { return ___host_0; }
inline RuntimeObject** get_address_of_host_0() { return &___host_0; }
inline void set_host_0(RuntimeObject* value)
{
___host_0 = value;
Il2CppCodeGenWriteBarrier((&___host_0), value);
}
inline static int32_t get_offset_of_root_1() { return static_cast<int32_t>(offsetof(InternalConfigurationSystem_t2108740756, ___root_1)); }
inline RuntimeObject* get_root_1() const { return ___root_1; }
inline RuntimeObject** get_address_of_root_1() { return &___root_1; }
inline void set_root_1(RuntimeObject* value)
{
___root_1 = value;
Il2CppCodeGenWriteBarrier((&___root_1), value);
}
inline static int32_t get_offset_of_hostInitParams_2() { return static_cast<int32_t>(offsetof(InternalConfigurationSystem_t2108740756, ___hostInitParams_2)); }
inline ObjectU5BU5D_t3614634134* get_hostInitParams_2() const { return ___hostInitParams_2; }
inline ObjectU5BU5D_t3614634134** get_address_of_hostInitParams_2() { return &___hostInitParams_2; }
inline void set_hostInitParams_2(ObjectU5BU5D_t3614634134* value)
{
___hostInitParams_2 = value;
Il2CppCodeGenWriteBarrier((&___hostInitParams_2), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // INTERNALCONFIGURATIONSYSTEM_T2108740756_H
#ifndef INTERNALCONFIGURATIONROOT_T547578517_H
#define INTERNALCONFIGURATIONROOT_T547578517_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.InternalConfigurationRoot
struct InternalConfigurationRoot_t547578517 : public RuntimeObject
{
public:
// System.Configuration.Internal.IInternalConfigHost System.Configuration.InternalConfigurationRoot::host
RuntimeObject* ___host_0;
// System.Boolean System.Configuration.InternalConfigurationRoot::isDesignTime
bool ___isDesignTime_1;
public:
inline static int32_t get_offset_of_host_0() { return static_cast<int32_t>(offsetof(InternalConfigurationRoot_t547578517, ___host_0)); }
inline RuntimeObject* get_host_0() const { return ___host_0; }
inline RuntimeObject** get_address_of_host_0() { return &___host_0; }
inline void set_host_0(RuntimeObject* value)
{
___host_0 = value;
Il2CppCodeGenWriteBarrier((&___host_0), value);
}
inline static int32_t get_offset_of_isDesignTime_1() { return static_cast<int32_t>(offsetof(InternalConfigurationRoot_t547578517, ___isDesignTime_1)); }
inline bool get_isDesignTime_1() const { return ___isDesignTime_1; }
inline bool* get_address_of_isDesignTime_1() { return &___isDesignTime_1; }
inline void set_isDesignTime_1(bool value)
{
___isDesignTime_1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // INTERNALCONFIGURATIONROOT_T547578517_H
#ifndef PROTECTEDCONFIGURATION_T1807950812_H
#define PROTECTEDCONFIGURATION_T1807950812_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.ProtectedConfiguration
struct ProtectedConfiguration_t1807950812 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // PROTECTEDCONFIGURATION_T1807950812_H
#ifndef PROPERTYINFORMATIONENUMERATOR_T1453501302_H
#define PROPERTYINFORMATIONENUMERATOR_T1453501302_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.PropertyInformationCollection/PropertyInformationEnumerator
struct PropertyInformationEnumerator_t1453501302 : public RuntimeObject
{
public:
// System.Configuration.PropertyInformationCollection System.Configuration.PropertyInformationCollection/PropertyInformationEnumerator::collection
PropertyInformationCollection_t954922393 * ___collection_0;
// System.Int32 System.Configuration.PropertyInformationCollection/PropertyInformationEnumerator::position
int32_t ___position_1;
public:
inline static int32_t get_offset_of_collection_0() { return static_cast<int32_t>(offsetof(PropertyInformationEnumerator_t1453501302, ___collection_0)); }
inline PropertyInformationCollection_t954922393 * get_collection_0() const { return ___collection_0; }
inline PropertyInformationCollection_t954922393 ** get_address_of_collection_0() { return &___collection_0; }
inline void set_collection_0(PropertyInformationCollection_t954922393 * value)
{
___collection_0 = value;
Il2CppCodeGenWriteBarrier((&___collection_0), value);
}
inline static int32_t get_offset_of_position_1() { return static_cast<int32_t>(offsetof(PropertyInformationEnumerator_t1453501302, ___position_1)); }
inline int32_t get_position_1() const { return ___position_1; }
inline int32_t* get_address_of_position_1() { return &___position_1; }
inline void set_position_1(int32_t value)
{
___position_1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // PROPERTYINFORMATIONENUMERATOR_T1453501302_H
#ifndef CONFIGURATIONVALIDATORBASE_T210547623_H
#define CONFIGURATIONVALIDATORBASE_T210547623_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.ConfigurationValidatorBase
struct ConfigurationValidatorBase_t210547623 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // CONFIGURATIONVALIDATORBASE_T210547623_H
#ifndef APPLICATION_T354826772_H
#define APPLICATION_T354826772_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.Application
struct Application_t354826772 : public RuntimeObject
{
public:
public:
};
struct Application_t354826772_StaticFields
{
public:
// UnityEngine.Application/LowMemoryCallback UnityEngine.Application::lowMemory
LowMemoryCallback_t642977590 * ___lowMemory_0;
// UnityEngine.Application/LogCallback UnityEngine.Application::s_LogCallbackHandler
LogCallback_t1867914413 * ___s_LogCallbackHandler_1;
// UnityEngine.Application/LogCallback UnityEngine.Application::s_LogCallbackHandlerThreaded
LogCallback_t1867914413 * ___s_LogCallbackHandlerThreaded_2;
// UnityEngine.Events.UnityAction UnityEngine.Application::onBeforeRender
UnityAction_t4025899511 * ___onBeforeRender_3;
public:
inline static int32_t get_offset_of_lowMemory_0() { return static_cast<int32_t>(offsetof(Application_t354826772_StaticFields, ___lowMemory_0)); }
inline LowMemoryCallback_t642977590 * get_lowMemory_0() const { return ___lowMemory_0; }
inline LowMemoryCallback_t642977590 ** get_address_of_lowMemory_0() { return &___lowMemory_0; }
inline void set_lowMemory_0(LowMemoryCallback_t642977590 * value)
{
___lowMemory_0 = value;
Il2CppCodeGenWriteBarrier((&___lowMemory_0), value);
}
inline static int32_t get_offset_of_s_LogCallbackHandler_1() { return static_cast<int32_t>(offsetof(Application_t354826772_StaticFields, ___s_LogCallbackHandler_1)); }
inline LogCallback_t1867914413 * get_s_LogCallbackHandler_1() const { return ___s_LogCallbackHandler_1; }
inline LogCallback_t1867914413 ** get_address_of_s_LogCallbackHandler_1() { return &___s_LogCallbackHandler_1; }
inline void set_s_LogCallbackHandler_1(LogCallback_t1867914413 * value)
{
___s_LogCallbackHandler_1 = value;
Il2CppCodeGenWriteBarrier((&___s_LogCallbackHandler_1), value);
}
inline static int32_t get_offset_of_s_LogCallbackHandlerThreaded_2() { return static_cast<int32_t>(offsetof(Application_t354826772_StaticFields, ___s_LogCallbackHandlerThreaded_2)); }
inline LogCallback_t1867914413 * get_s_LogCallbackHandlerThreaded_2() const { return ___s_LogCallbackHandlerThreaded_2; }
inline LogCallback_t1867914413 ** get_address_of_s_LogCallbackHandlerThreaded_2() { return &___s_LogCallbackHandlerThreaded_2; }
inline void set_s_LogCallbackHandlerThreaded_2(LogCallback_t1867914413 * value)
{
___s_LogCallbackHandlerThreaded_2 = value;
Il2CppCodeGenWriteBarrier((&___s_LogCallbackHandlerThreaded_2), value);
}
inline static int32_t get_offset_of_onBeforeRender_3() { return static_cast<int32_t>(offsetof(Application_t354826772_StaticFields, ___onBeforeRender_3)); }
inline UnityAction_t4025899511 * get_onBeforeRender_3() const { return ___onBeforeRender_3; }
inline UnityAction_t4025899511 ** get_address_of_onBeforeRender_3() { return &___onBeforeRender_3; }
inline void set_onBeforeRender_3(UnityAction_t4025899511 * value)
{
___onBeforeRender_3 = value;
Il2CppCodeGenWriteBarrier((&___onBeforeRender_3), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // APPLICATION_T354826772_H
#ifndef ATTRIBUTE_T542643598_H
#define ATTRIBUTE_T542643598_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Attribute
struct Attribute_t542643598 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // ATTRIBUTE_T542643598_H
#ifndef INTERNALCONFIGURATIONFACTORY_T3846641927_H
#define INTERNALCONFIGURATIONFACTORY_T3846641927_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.InternalConfigurationFactory
struct InternalConfigurationFactory_t3846641927 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // INTERNALCONFIGURATIONFACTORY_T3846641927_H
#ifndef ELEMENTINFORMATION_T3165583784_H
#define ELEMENTINFORMATION_T3165583784_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.ElementInformation
struct ElementInformation_t3165583784 : public RuntimeObject
{
public:
// System.Configuration.PropertyInformation System.Configuration.ElementInformation::propertyInfo
PropertyInformation_t2089433965 * ___propertyInfo_0;
// System.Configuration.ConfigurationElement System.Configuration.ElementInformation::owner
ConfigurationElement_t1776195828 * ___owner_1;
// System.Configuration.PropertyInformationCollection System.Configuration.ElementInformation::properties
PropertyInformationCollection_t954922393 * ___properties_2;
public:
inline static int32_t get_offset_of_propertyInfo_0() { return static_cast<int32_t>(offsetof(ElementInformation_t3165583784, ___propertyInfo_0)); }
inline PropertyInformation_t2089433965 * get_propertyInfo_0() const { return ___propertyInfo_0; }
inline PropertyInformation_t2089433965 ** get_address_of_propertyInfo_0() { return &___propertyInfo_0; }
inline void set_propertyInfo_0(PropertyInformation_t2089433965 * value)
{
___propertyInfo_0 = value;
Il2CppCodeGenWriteBarrier((&___propertyInfo_0), value);
}
inline static int32_t get_offset_of_owner_1() { return static_cast<int32_t>(offsetof(ElementInformation_t3165583784, ___owner_1)); }
inline ConfigurationElement_t1776195828 * get_owner_1() const { return ___owner_1; }
inline ConfigurationElement_t1776195828 ** get_address_of_owner_1() { return &___owner_1; }
inline void set_owner_1(ConfigurationElement_t1776195828 * value)
{
___owner_1 = value;
Il2CppCodeGenWriteBarrier((&___owner_1), value);
}
inline static int32_t get_offset_of_properties_2() { return static_cast<int32_t>(offsetof(ElementInformation_t3165583784, ___properties_2)); }
inline PropertyInformationCollection_t954922393 * get_properties_2() const { return ___properties_2; }
inline PropertyInformationCollection_t954922393 ** get_address_of_properties_2() { return &___properties_2; }
inline void set_properties_2(PropertyInformationCollection_t954922393 * value)
{
___properties_2 = value;
Il2CppCodeGenWriteBarrier((&___properties_2), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // ELEMENTINFORMATION_T3165583784_H
#ifndef VALUETYPE_T3507792607_H
#define VALUETYPE_T3507792607_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ValueType
struct ValueType_t3507792607 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of System.ValueType
struct ValueType_t3507792607_marshaled_pinvoke
{
};
// Native definition for COM marshalling of System.ValueType
struct ValueType_t3507792607_marshaled_com
{
};
#endif // VALUETYPE_T3507792607_H
#ifndef ENUMERABLE_T2148412300_H
#define ENUMERABLE_T2148412300_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Linq.Enumerable
struct Enumerable_t2148412300 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // ENUMERABLE_T2148412300_H
#ifndef CONFIGURATIONELEMENT_T1776195828_H
#define CONFIGURATIONELEMENT_T1776195828_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.ConfigurationElement
struct ConfigurationElement_t1776195828 : public RuntimeObject
{
public:
// System.String System.Configuration.ConfigurationElement::rawXml
String_t* ___rawXml_0;
// System.Boolean System.Configuration.ConfigurationElement::modified
bool ___modified_1;
// System.Configuration.ElementMap System.Configuration.ConfigurationElement::map
ElementMap_t997038224 * ___map_2;
// System.Configuration.ConfigurationPropertyCollection System.Configuration.ConfigurationElement::keyProps
ConfigurationPropertyCollection_t3473514151 * ___keyProps_3;
// System.Configuration.ConfigurationElementCollection System.Configuration.ConfigurationElement::defaultCollection
ConfigurationElementCollection_t1911180302 * ___defaultCollection_4;
// System.Boolean System.Configuration.ConfigurationElement::readOnly
bool ___readOnly_5;
// System.Configuration.ElementInformation System.Configuration.ConfigurationElement::elementInfo
ElementInformation_t3165583784 * ___elementInfo_6;
// System.Configuration.Configuration System.Configuration.ConfigurationElement::_configuration
Configuration_t3335372970 * ____configuration_7;
// System.Boolean System.Configuration.ConfigurationElement::elementPresent
bool ___elementPresent_8;
// System.Configuration.ConfigurationLockCollection System.Configuration.ConfigurationElement::lockAllAttributesExcept
ConfigurationLockCollection_t1011762925 * ___lockAllAttributesExcept_9;
// System.Configuration.ConfigurationLockCollection System.Configuration.ConfigurationElement::lockAllElementsExcept
ConfigurationLockCollection_t1011762925 * ___lockAllElementsExcept_10;
// System.Configuration.ConfigurationLockCollection System.Configuration.ConfigurationElement::lockAttributes
ConfigurationLockCollection_t1011762925 * ___lockAttributes_11;
// System.Configuration.ConfigurationLockCollection System.Configuration.ConfigurationElement::lockElements
ConfigurationLockCollection_t1011762925 * ___lockElements_12;
// System.Boolean System.Configuration.ConfigurationElement::lockItem
bool ___lockItem_13;
// System.Configuration.ConfigurationElement/SaveContext System.Configuration.ConfigurationElement::saveContext
SaveContext_t3996373180 * ___saveContext_14;
public:
inline static int32_t get_offset_of_rawXml_0() { return static_cast<int32_t>(offsetof(ConfigurationElement_t1776195828, ___rawXml_0)); }
inline String_t* get_rawXml_0() const { return ___rawXml_0; }
inline String_t** get_address_of_rawXml_0() { return &___rawXml_0; }
inline void set_rawXml_0(String_t* value)
{
___rawXml_0 = value;
Il2CppCodeGenWriteBarrier((&___rawXml_0), value);
}
inline static int32_t get_offset_of_modified_1() { return static_cast<int32_t>(offsetof(ConfigurationElement_t1776195828, ___modified_1)); }
inline bool get_modified_1() const { return ___modified_1; }
inline bool* get_address_of_modified_1() { return &___modified_1; }
inline void set_modified_1(bool value)
{
___modified_1 = value;
}
inline static int32_t get_offset_of_map_2() { return static_cast<int32_t>(offsetof(ConfigurationElement_t1776195828, ___map_2)); }
inline ElementMap_t997038224 * get_map_2() const { return ___map_2; }
inline ElementMap_t997038224 ** get_address_of_map_2() { return &___map_2; }
inline void set_map_2(ElementMap_t997038224 * value)
{
___map_2 = value;
Il2CppCodeGenWriteBarrier((&___map_2), value);
}
inline static int32_t get_offset_of_keyProps_3() { return static_cast<int32_t>(offsetof(ConfigurationElement_t1776195828, ___keyProps_3)); }
inline ConfigurationPropertyCollection_t3473514151 * get_keyProps_3() const { return ___keyProps_3; }
inline ConfigurationPropertyCollection_t3473514151 ** get_address_of_keyProps_3() { return &___keyProps_3; }
inline void set_keyProps_3(ConfigurationPropertyCollection_t3473514151 * value)
{
___keyProps_3 = value;
Il2CppCodeGenWriteBarrier((&___keyProps_3), value);
}
inline static int32_t get_offset_of_defaultCollection_4() { return static_cast<int32_t>(offsetof(ConfigurationElement_t1776195828, ___defaultCollection_4)); }
inline ConfigurationElementCollection_t1911180302 * get_defaultCollection_4() const { return ___defaultCollection_4; }
inline ConfigurationElementCollection_t1911180302 ** get_address_of_defaultCollection_4() { return &___defaultCollection_4; }
inline void set_defaultCollection_4(ConfigurationElementCollection_t1911180302 * value)
{
___defaultCollection_4 = value;
Il2CppCodeGenWriteBarrier((&___defaultCollection_4), value);
}
inline static int32_t get_offset_of_readOnly_5() { return static_cast<int32_t>(offsetof(ConfigurationElement_t1776195828, ___readOnly_5)); }
inline bool get_readOnly_5() const { return ___readOnly_5; }
inline bool* get_address_of_readOnly_5() { return &___readOnly_5; }
inline void set_readOnly_5(bool value)
{
___readOnly_5 = value;
}
inline static int32_t get_offset_of_elementInfo_6() { return static_cast<int32_t>(offsetof(ConfigurationElement_t1776195828, ___elementInfo_6)); }
inline ElementInformation_t3165583784 * get_elementInfo_6() const { return ___elementInfo_6; }
inline ElementInformation_t3165583784 ** get_address_of_elementInfo_6() { return &___elementInfo_6; }
inline void set_elementInfo_6(ElementInformation_t3165583784 * value)
{
___elementInfo_6 = value;
Il2CppCodeGenWriteBarrier((&___elementInfo_6), value);
}
inline static int32_t get_offset_of__configuration_7() { return static_cast<int32_t>(offsetof(ConfigurationElement_t1776195828, ____configuration_7)); }
inline Configuration_t3335372970 * get__configuration_7() const { return ____configuration_7; }
inline Configuration_t3335372970 ** get_address_of__configuration_7() { return &____configuration_7; }
inline void set__configuration_7(Configuration_t3335372970 * value)
{
____configuration_7 = value;
Il2CppCodeGenWriteBarrier((&____configuration_7), value);
}
inline static int32_t get_offset_of_elementPresent_8() { return static_cast<int32_t>(offsetof(ConfigurationElement_t1776195828, ___elementPresent_8)); }
inline bool get_elementPresent_8() const { return ___elementPresent_8; }
inline bool* get_address_of_elementPresent_8() { return &___elementPresent_8; }
inline void set_elementPresent_8(bool value)
{
___elementPresent_8 = value;
}
inline static int32_t get_offset_of_lockAllAttributesExcept_9() { return static_cast<int32_t>(offsetof(ConfigurationElement_t1776195828, ___lockAllAttributesExcept_9)); }
inline ConfigurationLockCollection_t1011762925 * get_lockAllAttributesExcept_9() const { return ___lockAllAttributesExcept_9; }
inline ConfigurationLockCollection_t1011762925 ** get_address_of_lockAllAttributesExcept_9() { return &___lockAllAttributesExcept_9; }
inline void set_lockAllAttributesExcept_9(ConfigurationLockCollection_t1011762925 * value)
{
___lockAllAttributesExcept_9 = value;
Il2CppCodeGenWriteBarrier((&___lockAllAttributesExcept_9), value);
}
inline static int32_t get_offset_of_lockAllElementsExcept_10() { return static_cast<int32_t>(offsetof(ConfigurationElement_t1776195828, ___lockAllElementsExcept_10)); }
inline ConfigurationLockCollection_t1011762925 * get_lockAllElementsExcept_10() const { return ___lockAllElementsExcept_10; }
inline ConfigurationLockCollection_t1011762925 ** get_address_of_lockAllElementsExcept_10() { return &___lockAllElementsExcept_10; }
inline void set_lockAllElementsExcept_10(ConfigurationLockCollection_t1011762925 * value)
{
___lockAllElementsExcept_10 = value;
Il2CppCodeGenWriteBarrier((&___lockAllElementsExcept_10), value);
}
inline static int32_t get_offset_of_lockAttributes_11() { return static_cast<int32_t>(offsetof(ConfigurationElement_t1776195828, ___lockAttributes_11)); }
inline ConfigurationLockCollection_t1011762925 * get_lockAttributes_11() const { return ___lockAttributes_11; }
inline ConfigurationLockCollection_t1011762925 ** get_address_of_lockAttributes_11() { return &___lockAttributes_11; }
inline void set_lockAttributes_11(ConfigurationLockCollection_t1011762925 * value)
{
___lockAttributes_11 = value;
Il2CppCodeGenWriteBarrier((&___lockAttributes_11), value);
}
inline static int32_t get_offset_of_lockElements_12() { return static_cast<int32_t>(offsetof(ConfigurationElement_t1776195828, ___lockElements_12)); }
inline ConfigurationLockCollection_t1011762925 * get_lockElements_12() const { return ___lockElements_12; }
inline ConfigurationLockCollection_t1011762925 ** get_address_of_lockElements_12() { return &___lockElements_12; }
inline void set_lockElements_12(ConfigurationLockCollection_t1011762925 * value)
{
___lockElements_12 = value;
Il2CppCodeGenWriteBarrier((&___lockElements_12), value);
}
inline static int32_t get_offset_of_lockItem_13() { return static_cast<int32_t>(offsetof(ConfigurationElement_t1776195828, ___lockItem_13)); }
inline bool get_lockItem_13() const { return ___lockItem_13; }
inline bool* get_address_of_lockItem_13() { return &___lockItem_13; }
inline void set_lockItem_13(bool value)
{
___lockItem_13 = value;
}
inline static int32_t get_offset_of_saveContext_14() { return static_cast<int32_t>(offsetof(ConfigurationElement_t1776195828, ___saveContext_14)); }
inline SaveContext_t3996373180 * get_saveContext_14() const { return ___saveContext_14; }
inline SaveContext_t3996373180 ** get_address_of_saveContext_14() { return &___saveContext_14; }
inline void set_saveContext_14(SaveContext_t3996373180 * value)
{
___saveContext_14 = value;
Il2CppCodeGenWriteBarrier((&___saveContext_14), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // CONFIGURATIONELEMENT_T1776195828_H
#ifndef ERROR_T3199922586_H
#define ERROR_T3199922586_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Linq.Error
struct Error_t3199922586 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // ERROR_T3199922586_H
#ifndef ELEMENTMAP_T997038224_H
#define ELEMENTMAP_T997038224_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.ElementMap
struct ElementMap_t997038224 : public RuntimeObject
{
public:
// System.Configuration.ConfigurationPropertyCollection System.Configuration.ElementMap::properties
ConfigurationPropertyCollection_t3473514151 * ___properties_1;
// System.Configuration.ConfigurationCollectionAttribute System.Configuration.ElementMap::collectionAttribute
ConfigurationCollectionAttribute_t2811353736 * ___collectionAttribute_2;
public:
inline static int32_t get_offset_of_properties_1() { return static_cast<int32_t>(offsetof(ElementMap_t997038224, ___properties_1)); }
inline ConfigurationPropertyCollection_t3473514151 * get_properties_1() const { return ___properties_1; }
inline ConfigurationPropertyCollection_t3473514151 ** get_address_of_properties_1() { return &___properties_1; }
inline void set_properties_1(ConfigurationPropertyCollection_t3473514151 * value)
{
___properties_1 = value;
Il2CppCodeGenWriteBarrier((&___properties_1), value);
}
inline static int32_t get_offset_of_collectionAttribute_2() { return static_cast<int32_t>(offsetof(ElementMap_t997038224, ___collectionAttribute_2)); }
inline ConfigurationCollectionAttribute_t2811353736 * get_collectionAttribute_2() const { return ___collectionAttribute_2; }
inline ConfigurationCollectionAttribute_t2811353736 ** get_address_of_collectionAttribute_2() { return &___collectionAttribute_2; }
inline void set_collectionAttribute_2(ConfigurationCollectionAttribute_t2811353736 * value)
{
___collectionAttribute_2 = value;
Il2CppCodeGenWriteBarrier((&___collectionAttribute_2), value);
}
};
struct ElementMap_t997038224_StaticFields
{
public:
// System.Collections.Hashtable System.Configuration.ElementMap::elementMaps
Hashtable_t909839986 * ___elementMaps_0;
public:
inline static int32_t get_offset_of_elementMaps_0() { return static_cast<int32_t>(offsetof(ElementMap_t997038224_StaticFields, ___elementMaps_0)); }
inline Hashtable_t909839986 * get_elementMaps_0() const { return ___elementMaps_0; }
inline Hashtable_t909839986 ** get_address_of_elementMaps_0() { return &___elementMaps_0; }
inline void set_elementMaps_0(Hashtable_t909839986 * value)
{
___elementMaps_0 = value;
Il2CppCodeGenWriteBarrier((&___elementMaps_0), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // ELEMENTMAP_T997038224_H
#ifndef UTILITIES_T1477630460_H
#define UTILITIES_T1477630460_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Linq.Utilities
struct Utilities_t1477630460 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // UTILITIES_T1477630460_H
#ifndef CONFIGURATION_T3335372970_H
#define CONFIGURATION_T3335372970_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.Configuration
struct Configuration_t3335372970 : public RuntimeObject
{
public:
// System.Configuration.Configuration System.Configuration.Configuration::parent
Configuration_t3335372970 * ___parent_0;
// System.Collections.Hashtable System.Configuration.Configuration::elementData
Hashtable_t909839986 * ___elementData_1;
// System.String System.Configuration.Configuration::streamName
String_t* ___streamName_2;
// System.Configuration.ConfigurationSectionGroup System.Configuration.Configuration::rootSectionGroup
ConfigurationSectionGroup_t2230982736 * ___rootSectionGroup_3;
// System.Configuration.ConfigurationLocationCollection System.Configuration.Configuration::locations
ConfigurationLocationCollection_t1903842989 * ___locations_4;
// System.Configuration.SectionGroupInfo System.Configuration.Configuration::rootGroup
SectionGroupInfo_t2346323570 * ___rootGroup_5;
// System.Configuration.Internal.IConfigSystem System.Configuration.Configuration::system
RuntimeObject* ___system_6;
// System.Boolean System.Configuration.Configuration::hasFile
bool ___hasFile_7;
// System.String System.Configuration.Configuration::rootNamespace
String_t* ___rootNamespace_8;
// System.String System.Configuration.Configuration::configPath
String_t* ___configPath_9;
// System.String System.Configuration.Configuration::locationConfigPath
String_t* ___locationConfigPath_10;
// System.String System.Configuration.Configuration::locationSubPath
String_t* ___locationSubPath_11;
public:
inline static int32_t get_offset_of_parent_0() { return static_cast<int32_t>(offsetof(Configuration_t3335372970, ___parent_0)); }
inline Configuration_t3335372970 * get_parent_0() const { return ___parent_0; }
inline Configuration_t3335372970 ** get_address_of_parent_0() { return &___parent_0; }
inline void set_parent_0(Configuration_t3335372970 * value)
{
___parent_0 = value;
Il2CppCodeGenWriteBarrier((&___parent_0), value);
}
inline static int32_t get_offset_of_elementData_1() { return static_cast<int32_t>(offsetof(Configuration_t3335372970, ___elementData_1)); }
inline Hashtable_t909839986 * get_elementData_1() const { return ___elementData_1; }
inline Hashtable_t909839986 ** get_address_of_elementData_1() { return &___elementData_1; }
inline void set_elementData_1(Hashtable_t909839986 * value)
{
___elementData_1 = value;
Il2CppCodeGenWriteBarrier((&___elementData_1), value);
}
inline static int32_t get_offset_of_streamName_2() { return static_cast<int32_t>(offsetof(Configuration_t3335372970, ___streamName_2)); }
inline String_t* get_streamName_2() const { return ___streamName_2; }
inline String_t** get_address_of_streamName_2() { return &___streamName_2; }
inline void set_streamName_2(String_t* value)
{
___streamName_2 = value;
Il2CppCodeGenWriteBarrier((&___streamName_2), value);
}
inline static int32_t get_offset_of_rootSectionGroup_3() { return static_cast<int32_t>(offsetof(Configuration_t3335372970, ___rootSectionGroup_3)); }
inline ConfigurationSectionGroup_t2230982736 * get_rootSectionGroup_3() const { return ___rootSectionGroup_3; }
inline ConfigurationSectionGroup_t2230982736 ** get_address_of_rootSectionGroup_3() { return &___rootSectionGroup_3; }
inline void set_rootSectionGroup_3(ConfigurationSectionGroup_t2230982736 * value)
{
___rootSectionGroup_3 = value;
Il2CppCodeGenWriteBarrier((&___rootSectionGroup_3), value);
}
inline static int32_t get_offset_of_locations_4() { return static_cast<int32_t>(offsetof(Configuration_t3335372970, ___locations_4)); }
inline ConfigurationLocationCollection_t1903842989 * get_locations_4() const { return ___locations_4; }
inline ConfigurationLocationCollection_t1903842989 ** get_address_of_locations_4() { return &___locations_4; }
inline void set_locations_4(ConfigurationLocationCollection_t1903842989 * value)
{
___locations_4 = value;
Il2CppCodeGenWriteBarrier((&___locations_4), value);
}
inline static int32_t get_offset_of_rootGroup_5() { return static_cast<int32_t>(offsetof(Configuration_t3335372970, ___rootGroup_5)); }
inline SectionGroupInfo_t2346323570 * get_rootGroup_5() const { return ___rootGroup_5; }
inline SectionGroupInfo_t2346323570 ** get_address_of_rootGroup_5() { return &___rootGroup_5; }
inline void set_rootGroup_5(SectionGroupInfo_t2346323570 * value)
{
___rootGroup_5 = value;
Il2CppCodeGenWriteBarrier((&___rootGroup_5), value);
}
inline static int32_t get_offset_of_system_6() { return static_cast<int32_t>(offsetof(Configuration_t3335372970, ___system_6)); }
inline RuntimeObject* get_system_6() const { return ___system_6; }
inline RuntimeObject** get_address_of_system_6() { return &___system_6; }
inline void set_system_6(RuntimeObject* value)
{
___system_6 = value;
Il2CppCodeGenWriteBarrier((&___system_6), value);
}
inline static int32_t get_offset_of_hasFile_7() { return static_cast<int32_t>(offsetof(Configuration_t3335372970, ___hasFile_7)); }
inline bool get_hasFile_7() const { return ___hasFile_7; }
inline bool* get_address_of_hasFile_7() { return &___hasFile_7; }
inline void set_hasFile_7(bool value)
{
___hasFile_7 = value;
}
inline static int32_t get_offset_of_rootNamespace_8() { return static_cast<int32_t>(offsetof(Configuration_t3335372970, ___rootNamespace_8)); }
inline String_t* get_rootNamespace_8() const { return ___rootNamespace_8; }
inline String_t** get_address_of_rootNamespace_8() { return &___rootNamespace_8; }
inline void set_rootNamespace_8(String_t* value)
{
___rootNamespace_8 = value;
Il2CppCodeGenWriteBarrier((&___rootNamespace_8), value);
}
inline static int32_t get_offset_of_configPath_9() { return static_cast<int32_t>(offsetof(Configuration_t3335372970, ___configPath_9)); }
inline String_t* get_configPath_9() const { return ___configPath_9; }
inline String_t** get_address_of_configPath_9() { return &___configPath_9; }
inline void set_configPath_9(String_t* value)
{
___configPath_9 = value;
Il2CppCodeGenWriteBarrier((&___configPath_9), value);
}
inline static int32_t get_offset_of_locationConfigPath_10() { return static_cast<int32_t>(offsetof(Configuration_t3335372970, ___locationConfigPath_10)); }
inline String_t* get_locationConfigPath_10() const { return ___locationConfigPath_10; }
inline String_t** get_address_of_locationConfigPath_10() { return &___locationConfigPath_10; }
inline void set_locationConfigPath_10(String_t* value)
{
___locationConfigPath_10 = value;
Il2CppCodeGenWriteBarrier((&___locationConfigPath_10), value);
}
inline static int32_t get_offset_of_locationSubPath_11() { return static_cast<int32_t>(offsetof(Configuration_t3335372970, ___locationSubPath_11)); }
inline String_t* get_locationSubPath_11() const { return ___locationSubPath_11; }
inline String_t** get_address_of_locationSubPath_11() { return &___locationSubPath_11; }
inline void set_locationSubPath_11(String_t* value)
{
___locationSubPath_11 = value;
Il2CppCodeGenWriteBarrier((&___locationSubPath_11), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // CONFIGURATION_T3335372970_H
#ifndef CONFIGINFO_T546730838_H
#define CONFIGINFO_T546730838_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.ConfigInfo
struct ConfigInfo_t546730838 : public RuntimeObject
{
public:
// System.String System.Configuration.ConfigInfo::Name
String_t* ___Name_0;
// System.String System.Configuration.ConfigInfo::TypeName
String_t* ___TypeName_1;
// System.Type System.Configuration.ConfigInfo::Type
Type_t * ___Type_2;
// System.String System.Configuration.ConfigInfo::streamName
String_t* ___streamName_3;
// System.Configuration.ConfigInfo System.Configuration.ConfigInfo::Parent
ConfigInfo_t546730838 * ___Parent_4;
// System.Configuration.Internal.IInternalConfigHost System.Configuration.ConfigInfo::ConfigHost
RuntimeObject* ___ConfigHost_5;
public:
inline static int32_t get_offset_of_Name_0() { return static_cast<int32_t>(offsetof(ConfigInfo_t546730838, ___Name_0)); }
inline String_t* get_Name_0() const { return ___Name_0; }
inline String_t** get_address_of_Name_0() { return &___Name_0; }
inline void set_Name_0(String_t* value)
{
___Name_0 = value;
Il2CppCodeGenWriteBarrier((&___Name_0), value);
}
inline static int32_t get_offset_of_TypeName_1() { return static_cast<int32_t>(offsetof(ConfigInfo_t546730838, ___TypeName_1)); }
inline String_t* get_TypeName_1() const { return ___TypeName_1; }
inline String_t** get_address_of_TypeName_1() { return &___TypeName_1; }
inline void set_TypeName_1(String_t* value)
{
___TypeName_1 = value;
Il2CppCodeGenWriteBarrier((&___TypeName_1), value);
}
inline static int32_t get_offset_of_Type_2() { return static_cast<int32_t>(offsetof(ConfigInfo_t546730838, ___Type_2)); }
inline Type_t * get_Type_2() const { return ___Type_2; }
inline Type_t ** get_address_of_Type_2() { return &___Type_2; }
inline void set_Type_2(Type_t * value)
{
___Type_2 = value;
Il2CppCodeGenWriteBarrier((&___Type_2), value);
}
inline static int32_t get_offset_of_streamName_3() { return static_cast<int32_t>(offsetof(ConfigInfo_t546730838, ___streamName_3)); }
inline String_t* get_streamName_3() const { return ___streamName_3; }
inline String_t** get_address_of_streamName_3() { return &___streamName_3; }
inline void set_streamName_3(String_t* value)
{
___streamName_3 = value;
Il2CppCodeGenWriteBarrier((&___streamName_3), value);
}
inline static int32_t get_offset_of_Parent_4() { return static_cast<int32_t>(offsetof(ConfigInfo_t546730838, ___Parent_4)); }
inline ConfigInfo_t546730838 * get_Parent_4() const { return ___Parent_4; }
inline ConfigInfo_t546730838 ** get_address_of_Parent_4() { return &___Parent_4; }
inline void set_Parent_4(ConfigInfo_t546730838 * value)
{
___Parent_4 = value;
Il2CppCodeGenWriteBarrier((&___Parent_4), value);
}
inline static int32_t get_offset_of_ConfigHost_5() { return static_cast<int32_t>(offsetof(ConfigInfo_t546730838, ___ConfigHost_5)); }
inline RuntimeObject* get_ConfigHost_5() const { return ___ConfigHost_5; }
inline RuntimeObject** get_address_of_ConfigHost_5() { return &___ConfigHost_5; }
inline void set_ConfigHost_5(RuntimeObject* value)
{
___ConfigHost_5 = value;
Il2CppCodeGenWriteBarrier((&___ConfigHost_5), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // CONFIGINFO_T546730838_H
#ifndef ENUMERABLEHELPERS_T1509421933_H
#define ENUMERABLEHELPERS_T1509421933_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Collections.Generic.EnumerableHelpers
struct EnumerableHelpers_t1509421933 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // ENUMERABLEHELPERS_T1509421933_H
#ifndef EXCEPTION_T1927440687_H
#define EXCEPTION_T1927440687_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Exception
struct Exception_t1927440687 : public RuntimeObject
{
public:
// System.String System.Exception::_className
String_t* ____className_1;
// System.String System.Exception::_message
String_t* ____message_2;
// System.Collections.IDictionary System.Exception::_data
RuntimeObject* ____data_3;
// System.Exception System.Exception::_innerException
Exception_t1927440687 * ____innerException_4;
// System.String System.Exception::_helpURL
String_t* ____helpURL_5;
// System.Object System.Exception::_stackTrace
RuntimeObject * ____stackTrace_6;
// System.String System.Exception::_stackTraceString
String_t* ____stackTraceString_7;
// System.String System.Exception::_remoteStackTraceString
String_t* ____remoteStackTraceString_8;
// System.Int32 System.Exception::_remoteStackIndex
int32_t ____remoteStackIndex_9;
// System.Object System.Exception::_dynamicMethods
RuntimeObject * ____dynamicMethods_10;
// System.Int32 System.Exception::_HResult
int32_t ____HResult_11;
// System.String System.Exception::_source
String_t* ____source_12;
// System.Runtime.Serialization.SafeSerializationManager System.Exception::_safeSerializationManager
SafeSerializationManager_t1975884510 * ____safeSerializationManager_13;
// System.Diagnostics.StackTrace[] System.Exception::captured_traces
StackTraceU5BU5D_t2217612696* ___captured_traces_14;
// System.IntPtr[] System.Exception::native_trace_ips
IntPtrU5BU5D_t169632028* ___native_trace_ips_15;
public:
inline static int32_t get_offset_of__className_1() { return static_cast<int32_t>(offsetof(Exception_t1927440687, ____className_1)); }
inline String_t* get__className_1() const { return ____className_1; }
inline String_t** get_address_of__className_1() { return &____className_1; }
inline void set__className_1(String_t* value)
{
____className_1 = value;
Il2CppCodeGenWriteBarrier((&____className_1), value);
}
inline static int32_t get_offset_of__message_2() { return static_cast<int32_t>(offsetof(Exception_t1927440687, ____message_2)); }
inline String_t* get__message_2() const { return ____message_2; }
inline String_t** get_address_of__message_2() { return &____message_2; }
inline void set__message_2(String_t* value)
{
____message_2 = value;
Il2CppCodeGenWriteBarrier((&____message_2), value);
}
inline static int32_t get_offset_of__data_3() { return static_cast<int32_t>(offsetof(Exception_t1927440687, ____data_3)); }
inline RuntimeObject* get__data_3() const { return ____data_3; }
inline RuntimeObject** get_address_of__data_3() { return &____data_3; }
inline void set__data_3(RuntimeObject* value)
{
____data_3 = value;
Il2CppCodeGenWriteBarrier((&____data_3), value);
}
inline static int32_t get_offset_of__innerException_4() { return static_cast<int32_t>(offsetof(Exception_t1927440687, ____innerException_4)); }
inline Exception_t1927440687 * get__innerException_4() const { return ____innerException_4; }
inline Exception_t1927440687 ** get_address_of__innerException_4() { return &____innerException_4; }
inline void set__innerException_4(Exception_t1927440687 * value)
{
____innerException_4 = value;
Il2CppCodeGenWriteBarrier((&____innerException_4), value);
}
inline static int32_t get_offset_of__helpURL_5() { return static_cast<int32_t>(offsetof(Exception_t1927440687, ____helpURL_5)); }
inline String_t* get__helpURL_5() const { return ____helpURL_5; }
inline String_t** get_address_of__helpURL_5() { return &____helpURL_5; }
inline void set__helpURL_5(String_t* value)
{
____helpURL_5 = value;
Il2CppCodeGenWriteBarrier((&____helpURL_5), value);
}
inline static int32_t get_offset_of__stackTrace_6() { return static_cast<int32_t>(offsetof(Exception_t1927440687, ____stackTrace_6)); }
inline RuntimeObject * get__stackTrace_6() const { return ____stackTrace_6; }
inline RuntimeObject ** get_address_of__stackTrace_6() { return &____stackTrace_6; }
inline void set__stackTrace_6(RuntimeObject * value)
{
____stackTrace_6 = value;
Il2CppCodeGenWriteBarrier((&____stackTrace_6), value);
}
inline static int32_t get_offset_of__stackTraceString_7() { return static_cast<int32_t>(offsetof(Exception_t1927440687, ____stackTraceString_7)); }
inline String_t* get__stackTraceString_7() const { return ____stackTraceString_7; }
inline String_t** get_address_of__stackTraceString_7() { return &____stackTraceString_7; }
inline void set__stackTraceString_7(String_t* value)
{
____stackTraceString_7 = value;
Il2CppCodeGenWriteBarrier((&____stackTraceString_7), value);
}
inline static int32_t get_offset_of__remoteStackTraceString_8() { return static_cast<int32_t>(offsetof(Exception_t1927440687, ____remoteStackTraceString_8)); }
inline String_t* get__remoteStackTraceString_8() const { return ____remoteStackTraceString_8; }
inline String_t** get_address_of__remoteStackTraceString_8() { return &____remoteStackTraceString_8; }
inline void set__remoteStackTraceString_8(String_t* value)
{
____remoteStackTraceString_8 = value;
Il2CppCodeGenWriteBarrier((&____remoteStackTraceString_8), value);
}
inline static int32_t get_offset_of__remoteStackIndex_9() { return static_cast<int32_t>(offsetof(Exception_t1927440687, ____remoteStackIndex_9)); }
inline int32_t get__remoteStackIndex_9() const { return ____remoteStackIndex_9; }
inline int32_t* get_address_of__remoteStackIndex_9() { return &____remoteStackIndex_9; }
inline void set__remoteStackIndex_9(int32_t value)
{
____remoteStackIndex_9 = value;
}
inline static int32_t get_offset_of__dynamicMethods_10() { return static_cast<int32_t>(offsetof(Exception_t1927440687, ____dynamicMethods_10)); }
inline RuntimeObject * get__dynamicMethods_10() const { return ____dynamicMethods_10; }
inline RuntimeObject ** get_address_of__dynamicMethods_10() { return &____dynamicMethods_10; }
inline void set__dynamicMethods_10(RuntimeObject * value)
{
____dynamicMethods_10 = value;
Il2CppCodeGenWriteBarrier((&____dynamicMethods_10), value);
}
inline static int32_t get_offset_of__HResult_11() { return static_cast<int32_t>(offsetof(Exception_t1927440687, ____HResult_11)); }
inline int32_t get__HResult_11() const { return ____HResult_11; }
inline int32_t* get_address_of__HResult_11() { return &____HResult_11; }
inline void set__HResult_11(int32_t value)
{
____HResult_11 = value;
}
inline static int32_t get_offset_of__source_12() { return static_cast<int32_t>(offsetof(Exception_t1927440687, ____source_12)); }
inline String_t* get__source_12() const { return ____source_12; }
inline String_t** get_address_of__source_12() { return &____source_12; }
inline void set__source_12(String_t* value)
{
____source_12 = value;
Il2CppCodeGenWriteBarrier((&____source_12), value);
}
inline static int32_t get_offset_of__safeSerializationManager_13() { return static_cast<int32_t>(offsetof(Exception_t1927440687, ____safeSerializationManager_13)); }
inline SafeSerializationManager_t1975884510 * get__safeSerializationManager_13() const { return ____safeSerializationManager_13; }
inline SafeSerializationManager_t1975884510 ** get_address_of__safeSerializationManager_13() { return &____safeSerializationManager_13; }
inline void set__safeSerializationManager_13(SafeSerializationManager_t1975884510 * value)
{
____safeSerializationManager_13 = value;
Il2CppCodeGenWriteBarrier((&____safeSerializationManager_13), value);
}
inline static int32_t get_offset_of_captured_traces_14() { return static_cast<int32_t>(offsetof(Exception_t1927440687, ___captured_traces_14)); }
inline StackTraceU5BU5D_t2217612696* get_captured_traces_14() const { return ___captured_traces_14; }
inline StackTraceU5BU5D_t2217612696** get_address_of_captured_traces_14() { return &___captured_traces_14; }
inline void set_captured_traces_14(StackTraceU5BU5D_t2217612696* value)
{
___captured_traces_14 = value;
Il2CppCodeGenWriteBarrier((&___captured_traces_14), value);
}
inline static int32_t get_offset_of_native_trace_ips_15() { return static_cast<int32_t>(offsetof(Exception_t1927440687, ___native_trace_ips_15)); }
inline IntPtrU5BU5D_t169632028* get_native_trace_ips_15() const { return ___native_trace_ips_15; }
inline IntPtrU5BU5D_t169632028** get_address_of_native_trace_ips_15() { return &___native_trace_ips_15; }
inline void set_native_trace_ips_15(IntPtrU5BU5D_t169632028* value)
{
___native_trace_ips_15 = value;
Il2CppCodeGenWriteBarrier((&___native_trace_ips_15), value);
}
};
struct Exception_t1927440687_StaticFields
{
public:
// System.Object System.Exception::s_EDILock
RuntimeObject * ___s_EDILock_0;
public:
inline static int32_t get_offset_of_s_EDILock_0() { return static_cast<int32_t>(offsetof(Exception_t1927440687_StaticFields, ___s_EDILock_0)); }
inline RuntimeObject * get_s_EDILock_0() const { return ___s_EDILock_0; }
inline RuntimeObject ** get_address_of_s_EDILock_0() { return &___s_EDILock_0; }
inline void set_s_EDILock_0(RuntimeObject * value)
{
___s_EDILock_0 = value;
Il2CppCodeGenWriteBarrier((&___s_EDILock_0), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of System.Exception
struct Exception_t1927440687_marshaled_pinvoke
{
char* ____className_1;
char* ____message_2;
RuntimeObject* ____data_3;
Exception_t1927440687_marshaled_pinvoke* ____innerException_4;
char* ____helpURL_5;
Il2CppIUnknown* ____stackTrace_6;
char* ____stackTraceString_7;
char* ____remoteStackTraceString_8;
int32_t ____remoteStackIndex_9;
Il2CppIUnknown* ____dynamicMethods_10;
int32_t ____HResult_11;
char* ____source_12;
SafeSerializationManager_t1975884510 * ____safeSerializationManager_13;
StackTraceU5BU5D_t2217612696* ___captured_traces_14;
intptr_t* ___native_trace_ips_15;
};
// Native definition for COM marshalling of System.Exception
struct Exception_t1927440687_marshaled_com
{
Il2CppChar* ____className_1;
Il2CppChar* ____message_2;
RuntimeObject* ____data_3;
Exception_t1927440687_marshaled_com* ____innerException_4;
Il2CppChar* ____helpURL_5;
Il2CppIUnknown* ____stackTrace_6;
Il2CppChar* ____stackTraceString_7;
Il2CppChar* ____remoteStackTraceString_8;
int32_t ____remoteStackIndex_9;
Il2CppIUnknown* ____dynamicMethods_10;
int32_t ____HResult_11;
Il2CppChar* ____source_12;
SafeSerializationManager_t1975884510 * ____safeSerializationManager_13;
StackTraceU5BU5D_t2217612696* ___captured_traces_14;
intptr_t* ___native_trace_ips_15;
};
#endif // EXCEPTION_T1927440687_H
#ifndef CONFIGURATIONLOCATION_T1895107553_H
#define CONFIGURATIONLOCATION_T1895107553_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.ConfigurationLocation
struct ConfigurationLocation_t1895107553 : public RuntimeObject
{
public:
// System.String System.Configuration.ConfigurationLocation::path
String_t* ___path_1;
// System.Configuration.Configuration System.Configuration.ConfigurationLocation::configuration
Configuration_t3335372970 * ___configuration_2;
// System.Configuration.Configuration System.Configuration.ConfigurationLocation::parent
Configuration_t3335372970 * ___parent_3;
// System.String System.Configuration.ConfigurationLocation::xmlContent
String_t* ___xmlContent_4;
// System.Boolean System.Configuration.ConfigurationLocation::parentResolved
bool ___parentResolved_5;
// System.Boolean System.Configuration.ConfigurationLocation::allowOverride
bool ___allowOverride_6;
public:
inline static int32_t get_offset_of_path_1() { return static_cast<int32_t>(offsetof(ConfigurationLocation_t1895107553, ___path_1)); }
inline String_t* get_path_1() const { return ___path_1; }
inline String_t** get_address_of_path_1() { return &___path_1; }
inline void set_path_1(String_t* value)
{
___path_1 = value;
Il2CppCodeGenWriteBarrier((&___path_1), value);
}
inline static int32_t get_offset_of_configuration_2() { return static_cast<int32_t>(offsetof(ConfigurationLocation_t1895107553, ___configuration_2)); }
inline Configuration_t3335372970 * get_configuration_2() const { return ___configuration_2; }
inline Configuration_t3335372970 ** get_address_of_configuration_2() { return &___configuration_2; }
inline void set_configuration_2(Configuration_t3335372970 * value)
{
___configuration_2 = value;
Il2CppCodeGenWriteBarrier((&___configuration_2), value);
}
inline static int32_t get_offset_of_parent_3() { return static_cast<int32_t>(offsetof(ConfigurationLocation_t1895107553, ___parent_3)); }
inline Configuration_t3335372970 * get_parent_3() const { return ___parent_3; }
inline Configuration_t3335372970 ** get_address_of_parent_3() { return &___parent_3; }
inline void set_parent_3(Configuration_t3335372970 * value)
{
___parent_3 = value;
Il2CppCodeGenWriteBarrier((&___parent_3), value);
}
inline static int32_t get_offset_of_xmlContent_4() { return static_cast<int32_t>(offsetof(ConfigurationLocation_t1895107553, ___xmlContent_4)); }
inline String_t* get_xmlContent_4() const { return ___xmlContent_4; }
inline String_t** get_address_of_xmlContent_4() { return &___xmlContent_4; }
inline void set_xmlContent_4(String_t* value)
{
___xmlContent_4 = value;
Il2CppCodeGenWriteBarrier((&___xmlContent_4), value);
}
inline static int32_t get_offset_of_parentResolved_5() { return static_cast<int32_t>(offsetof(ConfigurationLocation_t1895107553, ___parentResolved_5)); }
inline bool get_parentResolved_5() const { return ___parentResolved_5; }
inline bool* get_address_of_parentResolved_5() { return &___parentResolved_5; }
inline void set_parentResolved_5(bool value)
{
___parentResolved_5 = value;
}
inline static int32_t get_offset_of_allowOverride_6() { return static_cast<int32_t>(offsetof(ConfigurationLocation_t1895107553, ___allowOverride_6)); }
inline bool get_allowOverride_6() const { return ___allowOverride_6; }
inline bool* get_address_of_allowOverride_6() { return &___allowOverride_6; }
inline void set_allowOverride_6(bool value)
{
___allowOverride_6 = value;
}
};
struct ConfigurationLocation_t1895107553_StaticFields
{
public:
// System.Char[] System.Configuration.ConfigurationLocation::pathTrimChars
CharU5BU5D_t1328083999* ___pathTrimChars_0;
public:
inline static int32_t get_offset_of_pathTrimChars_0() { return static_cast<int32_t>(offsetof(ConfigurationLocation_t1895107553_StaticFields, ___pathTrimChars_0)); }
inline CharU5BU5D_t1328083999* get_pathTrimChars_0() const { return ___pathTrimChars_0; }
inline CharU5BU5D_t1328083999** get_address_of_pathTrimChars_0() { return &___pathTrimChars_0; }
inline void set_pathTrimChars_0(CharU5BU5D_t1328083999* value)
{
___pathTrimChars_0 = value;
Il2CppCodeGenWriteBarrier((&___pathTrimChars_0), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // CONFIGURATIONLOCATION_T1895107553_H
#ifndef U3CPRIVATEIMPLEMENTATIONDETAILSU3E_T1486305141_H
#define U3CPRIVATEIMPLEMENTATIONDETAILSU3E_T1486305141_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// <PrivateImplementationDetails>
struct U3CPrivateImplementationDetailsU3E_t1486305141 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // U3CPRIVATEIMPLEMENTATIONDETAILSU3E_T1486305141_H
#ifndef YIELDINSTRUCTION_T3462875981_H
#define YIELDINSTRUCTION_T3462875981_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.YieldInstruction
struct YieldInstruction_t3462875981 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of UnityEngine.YieldInstruction
struct YieldInstruction_t3462875981_marshaled_pinvoke
{
};
// Native definition for COM marshalling of UnityEngine.YieldInstruction
struct YieldInstruction_t3462875981_marshaled_com
{
};
#endif // YIELDINSTRUCTION_T3462875981_H
#ifndef CONFIGURATIONMANAGER_T2608608455_H
#define CONFIGURATIONMANAGER_T2608608455_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.ConfigurationManager
struct ConfigurationManager_t2608608455 : public RuntimeObject
{
public:
public:
};
struct ConfigurationManager_t2608608455_StaticFields
{
public:
// System.Configuration.InternalConfigurationFactory System.Configuration.ConfigurationManager::configFactory
InternalConfigurationFactory_t3846641927 * ___configFactory_0;
// System.Configuration.Internal.IInternalConfigSystem System.Configuration.ConfigurationManager::configSystem
RuntimeObject* ___configSystem_1;
// System.Object System.Configuration.ConfigurationManager::lockobj
RuntimeObject * ___lockobj_2;
public:
inline static int32_t get_offset_of_configFactory_0() { return static_cast<int32_t>(offsetof(ConfigurationManager_t2608608455_StaticFields, ___configFactory_0)); }
inline InternalConfigurationFactory_t3846641927 * get_configFactory_0() const { return ___configFactory_0; }
inline InternalConfigurationFactory_t3846641927 ** get_address_of_configFactory_0() { return &___configFactory_0; }
inline void set_configFactory_0(InternalConfigurationFactory_t3846641927 * value)
{
___configFactory_0 = value;
Il2CppCodeGenWriteBarrier((&___configFactory_0), value);
}
inline static int32_t get_offset_of_configSystem_1() { return static_cast<int32_t>(offsetof(ConfigurationManager_t2608608455_StaticFields, ___configSystem_1)); }
inline RuntimeObject* get_configSystem_1() const { return ___configSystem_1; }
inline RuntimeObject** get_address_of_configSystem_1() { return &___configSystem_1; }
inline void set_configSystem_1(RuntimeObject* value)
{
___configSystem_1 = value;
Il2CppCodeGenWriteBarrier((&___configSystem_1), value);
}
inline static int32_t get_offset_of_lockobj_2() { return static_cast<int32_t>(offsetof(ConfigurationManager_t2608608455_StaticFields, ___lockobj_2)); }
inline RuntimeObject * get_lockobj_2() const { return ___lockobj_2; }
inline RuntimeObject ** get_address_of_lockobj_2() { return &___lockobj_2; }
inline void set_lockobj_2(RuntimeObject * value)
{
___lockobj_2 = value;
Il2CppCodeGenWriteBarrier((&___lockobj_2), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // CONFIGURATIONMANAGER_T2608608455_H
#ifndef SR_T2523137206_H
#define SR_T2523137206_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// SR
struct SR_t2523137206 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // SR_T2523137206_H
#ifndef CONFIGURATIONFILEMAP_T2625210096_H
#define CONFIGURATIONFILEMAP_T2625210096_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.ConfigurationFileMap
struct ConfigurationFileMap_t2625210096 : public RuntimeObject
{
public:
// System.String System.Configuration.ConfigurationFileMap::machineConfigFilename
String_t* ___machineConfigFilename_0;
public:
inline static int32_t get_offset_of_machineConfigFilename_0() { return static_cast<int32_t>(offsetof(ConfigurationFileMap_t2625210096, ___machineConfigFilename_0)); }
inline String_t* get_machineConfigFilename_0() const { return ___machineConfigFilename_0; }
inline String_t** get_address_of_machineConfigFilename_0() { return &___machineConfigFilename_0; }
inline void set_machineConfigFilename_0(String_t* value)
{
___machineConfigFilename_0 = value;
Il2CppCodeGenWriteBarrier((&___machineConfigFilename_0), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // CONFIGURATIONFILEMAP_T2625210096_H
#ifndef XMLNODE_T616554813_H
#define XMLNODE_T616554813_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Xml.XmlNode
struct XmlNode_t616554813 : public RuntimeObject
{
public:
// System.Xml.XmlNode System.Xml.XmlNode::parentNode
XmlNode_t616554813 * ___parentNode_0;
public:
inline static int32_t get_offset_of_parentNode_0() { return static_cast<int32_t>(offsetof(XmlNode_t616554813, ___parentNode_0)); }
inline XmlNode_t616554813 * get_parentNode_0() const { return ___parentNode_0; }
inline XmlNode_t616554813 ** get_address_of_parentNode_0() { return &___parentNode_0; }
inline void set_parentNode_0(XmlNode_t616554813 * value)
{
___parentNode_0 = value;
Il2CppCodeGenWriteBarrier((&___parentNode_0), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // XMLNODE_T616554813_H
#ifndef SECTIONGROUPINFO_T2346323570_H
#define SECTIONGROUPINFO_T2346323570_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.SectionGroupInfo
struct SectionGroupInfo_t2346323570 : public ConfigInfo_t546730838
{
public:
// System.Boolean System.Configuration.SectionGroupInfo::modified
bool ___modified_6;
// System.Configuration.ConfigInfoCollection System.Configuration.SectionGroupInfo::sections
ConfigInfoCollection_t3264723080 * ___sections_7;
// System.Configuration.ConfigInfoCollection System.Configuration.SectionGroupInfo::groups
ConfigInfoCollection_t3264723080 * ___groups_8;
public:
inline static int32_t get_offset_of_modified_6() { return static_cast<int32_t>(offsetof(SectionGroupInfo_t2346323570, ___modified_6)); }
inline bool get_modified_6() const { return ___modified_6; }
inline bool* get_address_of_modified_6() { return &___modified_6; }
inline void set_modified_6(bool value)
{
___modified_6 = value;
}
inline static int32_t get_offset_of_sections_7() { return static_cast<int32_t>(offsetof(SectionGroupInfo_t2346323570, ___sections_7)); }
inline ConfigInfoCollection_t3264723080 * get_sections_7() const { return ___sections_7; }
inline ConfigInfoCollection_t3264723080 ** get_address_of_sections_7() { return &___sections_7; }
inline void set_sections_7(ConfigInfoCollection_t3264723080 * value)
{
___sections_7 = value;
Il2CppCodeGenWriteBarrier((&___sections_7), value);
}
inline static int32_t get_offset_of_groups_8() { return static_cast<int32_t>(offsetof(SectionGroupInfo_t2346323570, ___groups_8)); }
inline ConfigInfoCollection_t3264723080 * get_groups_8() const { return ___groups_8; }
inline ConfigInfoCollection_t3264723080 ** get_address_of_groups_8() { return &___groups_8; }
inline void set_groups_8(ConfigInfoCollection_t3264723080 * value)
{
___groups_8 = value;
Il2CppCodeGenWriteBarrier((&___groups_8), value);
}
};
struct SectionGroupInfo_t2346323570_StaticFields
{
public:
// System.Configuration.ConfigInfoCollection System.Configuration.SectionGroupInfo::emptyList
ConfigInfoCollection_t3264723080 * ___emptyList_9;
public:
inline static int32_t get_offset_of_emptyList_9() { return static_cast<int32_t>(offsetof(SectionGroupInfo_t2346323570_StaticFields, ___emptyList_9)); }
inline ConfigInfoCollection_t3264723080 * get_emptyList_9() const { return ___emptyList_9; }
inline ConfigInfoCollection_t3264723080 ** get_address_of_emptyList_9() { return &___emptyList_9; }
inline void set_emptyList_9(ConfigInfoCollection_t3264723080 * value)
{
___emptyList_9 = value;
Il2CppCodeGenWriteBarrier((&___emptyList_9), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // SECTIONGROUPINFO_T2346323570_H
#ifndef CONFIGINFOCOLLECTION_T3264723080_H
#define CONFIGINFOCOLLECTION_T3264723080_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.ConfigInfoCollection
struct ConfigInfoCollection_t3264723080 : public NameObjectCollectionBase_t2034248631
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // CONFIGINFOCOLLECTION_T3264723080_H
#ifndef __STATICARRAYINITTYPESIZEU3D120_T1468992141_H
#define __STATICARRAYINITTYPESIZEU3D120_T1468992141_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// <PrivateImplementationDetails>/__StaticArrayInitTypeSize=120
struct __StaticArrayInitTypeSizeU3D120_t1468992141
{
public:
union
{
struct
{
union
{
};
};
uint8_t __StaticArrayInitTypeSizeU3D120_t1468992141__padding[120];
};
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // __STATICARRAYINITTYPESIZEU3D120_T1468992141_H
#ifndef PROTECTEDCONFIGURATIONPROVIDER_T3971982415_H
#define PROTECTEDCONFIGURATIONPROVIDER_T3971982415_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.ProtectedConfigurationProvider
struct ProtectedConfigurationProvider_t3971982415 : public ProviderBase_t2882126354
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // PROTECTEDCONFIGURATIONPROVIDER_T3971982415_H
#ifndef PROTECTEDCONFIGURATIONPROVIDERCOLLECTION_T388338823_H
#define PROTECTEDCONFIGURATIONPROVIDERCOLLECTION_T388338823_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.ProtectedConfigurationProviderCollection
struct ProtectedConfigurationProviderCollection_t388338823 : public ProviderCollection_t2548499159
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // PROTECTEDCONFIGURATIONPROVIDERCOLLECTION_T388338823_H
#ifndef PROVIDERSETTINGS_T873049714_H
#define PROVIDERSETTINGS_T873049714_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.ProviderSettings
struct ProviderSettings_t873049714 : public ConfigurationElement_t1776195828
{
public:
// System.Configuration.ConfigNameValueCollection System.Configuration.ProviderSettings::parameters
ConfigNameValueCollection_t2395569530 * ___parameters_15;
public:
inline static int32_t get_offset_of_parameters_15() { return static_cast<int32_t>(offsetof(ProviderSettings_t873049714, ___parameters_15)); }
inline ConfigNameValueCollection_t2395569530 * get_parameters_15() const { return ___parameters_15; }
inline ConfigNameValueCollection_t2395569530 ** get_address_of_parameters_15() { return &___parameters_15; }
inline void set_parameters_15(ConfigNameValueCollection_t2395569530 * value)
{
___parameters_15 = value;
Il2CppCodeGenWriteBarrier((&___parameters_15), value);
}
};
struct ProviderSettings_t873049714_StaticFields
{
public:
// System.Configuration.ConfigurationProperty System.Configuration.ProviderSettings::nameProp
ConfigurationProperty_t2048066811 * ___nameProp_16;
// System.Configuration.ConfigurationProperty System.Configuration.ProviderSettings::typeProp
ConfigurationProperty_t2048066811 * ___typeProp_17;
// System.Configuration.ConfigurationPropertyCollection System.Configuration.ProviderSettings::properties
ConfigurationPropertyCollection_t3473514151 * ___properties_18;
public:
inline static int32_t get_offset_of_nameProp_16() { return static_cast<int32_t>(offsetof(ProviderSettings_t873049714_StaticFields, ___nameProp_16)); }
inline ConfigurationProperty_t2048066811 * get_nameProp_16() const { return ___nameProp_16; }
inline ConfigurationProperty_t2048066811 ** get_address_of_nameProp_16() { return &___nameProp_16; }
inline void set_nameProp_16(ConfigurationProperty_t2048066811 * value)
{
___nameProp_16 = value;
Il2CppCodeGenWriteBarrier((&___nameProp_16), value);
}
inline static int32_t get_offset_of_typeProp_17() { return static_cast<int32_t>(offsetof(ProviderSettings_t873049714_StaticFields, ___typeProp_17)); }
inline ConfigurationProperty_t2048066811 * get_typeProp_17() const { return ___typeProp_17; }
inline ConfigurationProperty_t2048066811 ** get_address_of_typeProp_17() { return &___typeProp_17; }
inline void set_typeProp_17(ConfigurationProperty_t2048066811 * value)
{
___typeProp_17 = value;
Il2CppCodeGenWriteBarrier((&___typeProp_17), value);
}
inline static int32_t get_offset_of_properties_18() { return static_cast<int32_t>(offsetof(ProviderSettings_t873049714_StaticFields, ___properties_18)); }
inline ConfigurationPropertyCollection_t3473514151 * get_properties_18() const { return ___properties_18; }
inline ConfigurationPropertyCollection_t3473514151 ** get_address_of_properties_18() { return &___properties_18; }
inline void set_properties_18(ConfigurationPropertyCollection_t3473514151 * value)
{
___properties_18 = value;
Il2CppCodeGenWriteBarrier((&___properties_18), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // PROVIDERSETTINGS_T873049714_H
#ifndef __STATICARRAYINITTYPESIZEU3D1024_T3477315116_H
#define __STATICARRAYINITTYPESIZEU3D1024_T3477315116_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// <PrivateImplementationDetails>/__StaticArrayInitTypeSize=1024
struct __StaticArrayInitTypeSizeU3D1024_t3477315116
{
public:
union
{
struct
{
union
{
};
};
uint8_t __StaticArrayInitTypeSizeU3D1024_t3477315116__padding[1024];
};
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // __STATICARRAYINITTYPESIZEU3D1024_T3477315116_H
#ifndef WAITFORFIXEDUPDATE_T3968615785_H
#define WAITFORFIXEDUPDATE_T3968615785_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.WaitForFixedUpdate
struct WaitForFixedUpdate_t3968615785 : public YieldInstruction_t3462875981
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // WAITFORFIXEDUPDATE_T3968615785_H
#ifndef __STATICARRAYINITTYPESIZEU3D256_T3653428462_H
#define __STATICARRAYINITTYPESIZEU3D256_T3653428462_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// <PrivateImplementationDetails>/__StaticArrayInitTypeSize=256
struct __StaticArrayInitTypeSizeU3D256_t3653428462
{
public:
union
{
struct
{
union
{
};
};
uint8_t __StaticArrayInitTypeSizeU3D256_t3653428462__padding[256];
};
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // __STATICARRAYINITTYPESIZEU3D256_T3653428462_H
#ifndef WAITFORSECONDS_T3839502067_H
#define WAITFORSECONDS_T3839502067_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.WaitForSeconds
struct WaitForSeconds_t3839502067 : public YieldInstruction_t3462875981
{
public:
// System.Single UnityEngine.WaitForSeconds::m_Seconds
float ___m_Seconds_0;
public:
inline static int32_t get_offset_of_m_Seconds_0() { return static_cast<int32_t>(offsetof(WaitForSeconds_t3839502067, ___m_Seconds_0)); }
inline float get_m_Seconds_0() const { return ___m_Seconds_0; }
inline float* get_address_of_m_Seconds_0() { return &___m_Seconds_0; }
inline void set_m_Seconds_0(float value)
{
___m_Seconds_0 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of UnityEngine.WaitForSeconds
struct WaitForSeconds_t3839502067_marshaled_pinvoke : public YieldInstruction_t3462875981_marshaled_pinvoke
{
float ___m_Seconds_0;
};
// Native definition for COM marshalling of UnityEngine.WaitForSeconds
struct WaitForSeconds_t3839502067_marshaled_com : public YieldInstruction_t3462875981_marshaled_com
{
float ___m_Seconds_0;
};
#endif // WAITFORSECONDS_T3839502067_H
#ifndef VOID_T1841601450_H
#define VOID_T1841601450_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Void
struct Void_t1841601450
{
public:
union
{
struct
{
};
uint8_t Void_t1841601450__padding[1];
};
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // VOID_T1841601450_H
#ifndef CONFIGURATIONPERMISSION_T1611094853_H
#define CONFIGURATIONPERMISSION_T1611094853_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.ConfigurationPermission
struct ConfigurationPermission_t1611094853 : public CodeAccessPermission_t3468021764
{
public:
// System.Boolean System.Configuration.ConfigurationPermission::unrestricted
bool ___unrestricted_0;
public:
inline static int32_t get_offset_of_unrestricted_0() { return static_cast<int32_t>(offsetof(ConfigurationPermission_t1611094853, ___unrestricted_0)); }
inline bool get_unrestricted_0() const { return ___unrestricted_0; }
inline bool* get_address_of_unrestricted_0() { return &___unrestricted_0; }
inline void set_unrestricted_0(bool value)
{
___unrestricted_0 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // CONFIGURATIONPERMISSION_T1611094853_H
#ifndef CONFIGURATIONSECTIONCOLLECTION_T4261113299_H
#define CONFIGURATIONSECTIONCOLLECTION_T4261113299_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.ConfigurationSectionCollection
struct ConfigurationSectionCollection_t4261113299 : public NameObjectCollectionBase_t2034248631
{
public:
// System.Configuration.SectionGroupInfo System.Configuration.ConfigurationSectionCollection::group
SectionGroupInfo_t2346323570 * ___group_10;
// System.Configuration.Configuration System.Configuration.ConfigurationSectionCollection::config
Configuration_t3335372970 * ___config_11;
public:
inline static int32_t get_offset_of_group_10() { return static_cast<int32_t>(offsetof(ConfigurationSectionCollection_t4261113299, ___group_10)); }
inline SectionGroupInfo_t2346323570 * get_group_10() const { return ___group_10; }
inline SectionGroupInfo_t2346323570 ** get_address_of_group_10() { return &___group_10; }
inline void set_group_10(SectionGroupInfo_t2346323570 * value)
{
___group_10 = value;
Il2CppCodeGenWriteBarrier((&___group_10), value);
}
inline static int32_t get_offset_of_config_11() { return static_cast<int32_t>(offsetof(ConfigurationSectionCollection_t4261113299, ___config_11)); }
inline Configuration_t3335372970 * get_config_11() const { return ___config_11; }
inline Configuration_t3335372970 ** get_address_of_config_11() { return &___config_11; }
inline void set_config_11(Configuration_t3335372970 * value)
{
___config_11 = value;
Il2CppCodeGenWriteBarrier((&___config_11), value);
}
};
struct ConfigurationSectionCollection_t4261113299_StaticFields
{
public:
// System.Object System.Configuration.ConfigurationSectionCollection::lockObject
RuntimeObject * ___lockObject_12;
public:
inline static int32_t get_offset_of_lockObject_12() { return static_cast<int32_t>(offsetof(ConfigurationSectionCollection_t4261113299_StaticFields, ___lockObject_12)); }
inline RuntimeObject * get_lockObject_12() const { return ___lockObject_12; }
inline RuntimeObject ** get_address_of_lockObject_12() { return &___lockObject_12; }
inline void set_lockObject_12(RuntimeObject * value)
{
___lockObject_12 = value;
Il2CppCodeGenWriteBarrier((&___lockObject_12), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // CONFIGURATIONSECTIONCOLLECTION_T4261113299_H
#ifndef CONFIGURATIONSECTION_T2600766927_H
#define CONFIGURATIONSECTION_T2600766927_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.ConfigurationSection
struct ConfigurationSection_t2600766927 : public ConfigurationElement_t1776195828
{
public:
// System.Configuration.SectionInformation System.Configuration.ConfigurationSection::sectionInformation
SectionInformation_t2754609709 * ___sectionInformation_15;
// System.Configuration.IConfigurationSectionHandler System.Configuration.ConfigurationSection::section_handler
RuntimeObject* ___section_handler_16;
// System.String System.Configuration.ConfigurationSection::externalDataXml
String_t* ___externalDataXml_17;
// System.Object System.Configuration.ConfigurationSection::_configContext
RuntimeObject * ____configContext_18;
public:
inline static int32_t get_offset_of_sectionInformation_15() { return static_cast<int32_t>(offsetof(ConfigurationSection_t2600766927, ___sectionInformation_15)); }
inline SectionInformation_t2754609709 * get_sectionInformation_15() const { return ___sectionInformation_15; }
inline SectionInformation_t2754609709 ** get_address_of_sectionInformation_15() { return &___sectionInformation_15; }
inline void set_sectionInformation_15(SectionInformation_t2754609709 * value)
{
___sectionInformation_15 = value;
Il2CppCodeGenWriteBarrier((&___sectionInformation_15), value);
}
inline static int32_t get_offset_of_section_handler_16() { return static_cast<int32_t>(offsetof(ConfigurationSection_t2600766927, ___section_handler_16)); }
inline RuntimeObject* get_section_handler_16() const { return ___section_handler_16; }
inline RuntimeObject** get_address_of_section_handler_16() { return &___section_handler_16; }
inline void set_section_handler_16(RuntimeObject* value)
{
___section_handler_16 = value;
Il2CppCodeGenWriteBarrier((&___section_handler_16), value);
}
inline static int32_t get_offset_of_externalDataXml_17() { return static_cast<int32_t>(offsetof(ConfigurationSection_t2600766927, ___externalDataXml_17)); }
inline String_t* get_externalDataXml_17() const { return ___externalDataXml_17; }
inline String_t** get_address_of_externalDataXml_17() { return &___externalDataXml_17; }
inline void set_externalDataXml_17(String_t* value)
{
___externalDataXml_17 = value;
Il2CppCodeGenWriteBarrier((&___externalDataXml_17), value);
}
inline static int32_t get_offset_of__configContext_18() { return static_cast<int32_t>(offsetof(ConfigurationSection_t2600766927, ____configContext_18)); }
inline RuntimeObject * get__configContext_18() const { return ____configContext_18; }
inline RuntimeObject ** get_address_of__configContext_18() { return &____configContext_18; }
inline void set__configContext_18(RuntimeObject * value)
{
____configContext_18 = value;
Il2CppCodeGenWriteBarrier((&____configContext_18), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // CONFIGURATIONSECTION_T2600766927_H
#ifndef CONFIGURATIONLOCATIONCOLLECTION_T1903842989_H
#define CONFIGURATIONLOCATIONCOLLECTION_T1903842989_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.ConfigurationLocationCollection
struct ConfigurationLocationCollection_t1903842989 : public ReadOnlyCollectionBase_t22281769
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // CONFIGURATIONLOCATIONCOLLECTION_T1903842989_H
#ifndef CONFIGURATIONELEMENTCOLLECTION_T1911180302_H
#define CONFIGURATIONELEMENTCOLLECTION_T1911180302_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.ConfigurationElementCollection
struct ConfigurationElementCollection_t1911180302 : public ConfigurationElement_t1776195828
{
public:
// System.Collections.ArrayList System.Configuration.ConfigurationElementCollection::list
ArrayList_t4252133567 * ___list_15;
// System.Collections.ArrayList System.Configuration.ConfigurationElementCollection::removed
ArrayList_t4252133567 * ___removed_16;
// System.Collections.ArrayList System.Configuration.ConfigurationElementCollection::inherited
ArrayList_t4252133567 * ___inherited_17;
// System.Boolean System.Configuration.ConfigurationElementCollection::emitClear
bool ___emitClear_18;
// System.Boolean System.Configuration.ConfigurationElementCollection::modified
bool ___modified_19;
// System.Collections.IComparer System.Configuration.ConfigurationElementCollection::comparer
RuntimeObject* ___comparer_20;
// System.Int32 System.Configuration.ConfigurationElementCollection::inheritedLimitIndex
int32_t ___inheritedLimitIndex_21;
// System.String System.Configuration.ConfigurationElementCollection::addElementName
String_t* ___addElementName_22;
// System.String System.Configuration.ConfigurationElementCollection::clearElementName
String_t* ___clearElementName_23;
// System.String System.Configuration.ConfigurationElementCollection::removeElementName
String_t* ___removeElementName_24;
public:
inline static int32_t get_offset_of_list_15() { return static_cast<int32_t>(offsetof(ConfigurationElementCollection_t1911180302, ___list_15)); }
inline ArrayList_t4252133567 * get_list_15() const { return ___list_15; }
inline ArrayList_t4252133567 ** get_address_of_list_15() { return &___list_15; }
inline void set_list_15(ArrayList_t4252133567 * value)
{
___list_15 = value;
Il2CppCodeGenWriteBarrier((&___list_15), value);
}
inline static int32_t get_offset_of_removed_16() { return static_cast<int32_t>(offsetof(ConfigurationElementCollection_t1911180302, ___removed_16)); }
inline ArrayList_t4252133567 * get_removed_16() const { return ___removed_16; }
inline ArrayList_t4252133567 ** get_address_of_removed_16() { return &___removed_16; }
inline void set_removed_16(ArrayList_t4252133567 * value)
{
___removed_16 = value;
Il2CppCodeGenWriteBarrier((&___removed_16), value);
}
inline static int32_t get_offset_of_inherited_17() { return static_cast<int32_t>(offsetof(ConfigurationElementCollection_t1911180302, ___inherited_17)); }
inline ArrayList_t4252133567 * get_inherited_17() const { return ___inherited_17; }
inline ArrayList_t4252133567 ** get_address_of_inherited_17() { return &___inherited_17; }
inline void set_inherited_17(ArrayList_t4252133567 * value)
{
___inherited_17 = value;
Il2CppCodeGenWriteBarrier((&___inherited_17), value);
}
inline static int32_t get_offset_of_emitClear_18() { return static_cast<int32_t>(offsetof(ConfigurationElementCollection_t1911180302, ___emitClear_18)); }
inline bool get_emitClear_18() const { return ___emitClear_18; }
inline bool* get_address_of_emitClear_18() { return &___emitClear_18; }
inline void set_emitClear_18(bool value)
{
___emitClear_18 = value;
}
inline static int32_t get_offset_of_modified_19() { return static_cast<int32_t>(offsetof(ConfigurationElementCollection_t1911180302, ___modified_19)); }
inline bool get_modified_19() const { return ___modified_19; }
inline bool* get_address_of_modified_19() { return &___modified_19; }
inline void set_modified_19(bool value)
{
___modified_19 = value;
}
inline static int32_t get_offset_of_comparer_20() { return static_cast<int32_t>(offsetof(ConfigurationElementCollection_t1911180302, ___comparer_20)); }
inline RuntimeObject* get_comparer_20() const { return ___comparer_20; }
inline RuntimeObject** get_address_of_comparer_20() { return &___comparer_20; }
inline void set_comparer_20(RuntimeObject* value)
{
___comparer_20 = value;
Il2CppCodeGenWriteBarrier((&___comparer_20), value);
}
inline static int32_t get_offset_of_inheritedLimitIndex_21() { return static_cast<int32_t>(offsetof(ConfigurationElementCollection_t1911180302, ___inheritedLimitIndex_21)); }
inline int32_t get_inheritedLimitIndex_21() const { return ___inheritedLimitIndex_21; }
inline int32_t* get_address_of_inheritedLimitIndex_21() { return &___inheritedLimitIndex_21; }
inline void set_inheritedLimitIndex_21(int32_t value)
{
___inheritedLimitIndex_21 = value;
}
inline static int32_t get_offset_of_addElementName_22() { return static_cast<int32_t>(offsetof(ConfigurationElementCollection_t1911180302, ___addElementName_22)); }
inline String_t* get_addElementName_22() const { return ___addElementName_22; }
inline String_t** get_address_of_addElementName_22() { return &___addElementName_22; }
inline void set_addElementName_22(String_t* value)
{
___addElementName_22 = value;
Il2CppCodeGenWriteBarrier((&___addElementName_22), value);
}
inline static int32_t get_offset_of_clearElementName_23() { return static_cast<int32_t>(offsetof(ConfigurationElementCollection_t1911180302, ___clearElementName_23)); }
inline String_t* get_clearElementName_23() const { return ___clearElementName_23; }
inline String_t** get_address_of_clearElementName_23() { return &___clearElementName_23; }
inline void set_clearElementName_23(String_t* value)
{
___clearElementName_23 = value;
Il2CppCodeGenWriteBarrier((&___clearElementName_23), value);
}
inline static int32_t get_offset_of_removeElementName_24() { return static_cast<int32_t>(offsetof(ConfigurationElementCollection_t1911180302, ___removeElementName_24)); }
inline String_t* get_removeElementName_24() const { return ___removeElementName_24; }
inline String_t** get_address_of_removeElementName_24() { return &___removeElementName_24; }
inline void set_removeElementName_24(String_t* value)
{
___removeElementName_24 = value;
Il2CppCodeGenWriteBarrier((&___removeElementName_24), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // CONFIGURATIONELEMENTCOLLECTION_T1911180302_H
#ifndef SYSTEMEXCEPTION_T3877406272_H
#define SYSTEMEXCEPTION_T3877406272_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.SystemException
struct SystemException_t3877406272 : public Exception_t1927440687
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // SYSTEMEXCEPTION_T3877406272_H
#ifndef INTPTR_T_H
#define INTPTR_T_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.IntPtr
struct IntPtr_t
{
public:
// System.Void* System.IntPtr::m_value
void* ___m_value_0;
public:
inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(IntPtr_t, ___m_value_0)); }
inline void* get_m_value_0() const { return ___m_value_0; }
inline void** get_address_of_m_value_0() { return &___m_value_0; }
inline void set_m_value_0(void* value)
{
___m_value_0 = value;
}
};
struct IntPtr_t_StaticFields
{
public:
// System.IntPtr System.IntPtr::Zero
intptr_t ___Zero_1;
public:
inline static int32_t get_offset_of_Zero_1() { return static_cast<int32_t>(offsetof(IntPtr_t_StaticFields, ___Zero_1)); }
inline intptr_t get_Zero_1() const { return ___Zero_1; }
inline intptr_t* get_address_of_Zero_1() { return &___Zero_1; }
inline void set_Zero_1(intptr_t value)
{
___Zero_1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // INTPTR_T_H
#ifndef CONFIGURATIONREMOVEELEMENT_T3305291330_H
#define CONFIGURATIONREMOVEELEMENT_T3305291330_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.ConfigurationElementCollection/ConfigurationRemoveElement
struct ConfigurationRemoveElement_t3305291330 : public ConfigurationElement_t1776195828
{
public:
// System.Configuration.ConfigurationPropertyCollection System.Configuration.ConfigurationElementCollection/ConfigurationRemoveElement::properties
ConfigurationPropertyCollection_t3473514151 * ___properties_15;
// System.Configuration.ConfigurationElement System.Configuration.ConfigurationElementCollection/ConfigurationRemoveElement::_origElement
ConfigurationElement_t1776195828 * ____origElement_16;
// System.Configuration.ConfigurationElementCollection System.Configuration.ConfigurationElementCollection/ConfigurationRemoveElement::_origCollection
ConfigurationElementCollection_t1911180302 * ____origCollection_17;
public:
inline static int32_t get_offset_of_properties_15() { return static_cast<int32_t>(offsetof(ConfigurationRemoveElement_t3305291330, ___properties_15)); }
inline ConfigurationPropertyCollection_t3473514151 * get_properties_15() const { return ___properties_15; }
inline ConfigurationPropertyCollection_t3473514151 ** get_address_of_properties_15() { return &___properties_15; }
inline void set_properties_15(ConfigurationPropertyCollection_t3473514151 * value)
{
___properties_15 = value;
Il2CppCodeGenWriteBarrier((&___properties_15), value);
}
inline static int32_t get_offset_of__origElement_16() { return static_cast<int32_t>(offsetof(ConfigurationRemoveElement_t3305291330, ____origElement_16)); }
inline ConfigurationElement_t1776195828 * get__origElement_16() const { return ____origElement_16; }
inline ConfigurationElement_t1776195828 ** get_address_of__origElement_16() { return &____origElement_16; }
inline void set__origElement_16(ConfigurationElement_t1776195828 * value)
{
____origElement_16 = value;
Il2CppCodeGenWriteBarrier((&____origElement_16), value);
}
inline static int32_t get_offset_of__origCollection_17() { return static_cast<int32_t>(offsetof(ConfigurationRemoveElement_t3305291330, ____origCollection_17)); }
inline ConfigurationElementCollection_t1911180302 * get__origCollection_17() const { return ____origCollection_17; }
inline ConfigurationElementCollection_t1911180302 ** get_address_of__origCollection_17() { return &____origCollection_17; }
inline void set__origCollection_17(ConfigurationElementCollection_t1911180302 * value)
{
____origCollection_17 = value;
Il2CppCodeGenWriteBarrier((&____origCollection_17), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // CONFIGURATIONREMOVEELEMENT_T3305291330_H
#ifndef CONFIGURATIONSECTIONGROUPCOLLECTION_T575145286_H
#define CONFIGURATIONSECTIONGROUPCOLLECTION_T575145286_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.ConfigurationSectionGroupCollection
struct ConfigurationSectionGroupCollection_t575145286 : public NameObjectCollectionBase_t2034248631
{
public:
// System.Configuration.SectionGroupInfo System.Configuration.ConfigurationSectionGroupCollection::group
SectionGroupInfo_t2346323570 * ___group_10;
// System.Configuration.Configuration System.Configuration.ConfigurationSectionGroupCollection::config
Configuration_t3335372970 * ___config_11;
public:
inline static int32_t get_offset_of_group_10() { return static_cast<int32_t>(offsetof(ConfigurationSectionGroupCollection_t575145286, ___group_10)); }
inline SectionGroupInfo_t2346323570 * get_group_10() const { return ___group_10; }
inline SectionGroupInfo_t2346323570 ** get_address_of_group_10() { return &___group_10; }
inline void set_group_10(SectionGroupInfo_t2346323570 * value)
{
___group_10 = value;
Il2CppCodeGenWriteBarrier((&___group_10), value);
}
inline static int32_t get_offset_of_config_11() { return static_cast<int32_t>(offsetof(ConfigurationSectionGroupCollection_t575145286, ___config_11)); }
inline Configuration_t3335372970 * get_config_11() const { return ___config_11; }
inline Configuration_t3335372970 ** get_address_of_config_11() { return &___config_11; }
inline void set_config_11(Configuration_t3335372970 * value)
{
___config_11 = value;
Il2CppCodeGenWriteBarrier((&___config_11), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // CONFIGURATIONSECTIONGROUPCOLLECTION_T575145286_H
#ifndef EXECONFIGURATIONFILEMAP_T1419586304_H
#define EXECONFIGURATIONFILEMAP_T1419586304_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.ExeConfigurationFileMap
struct ExeConfigurationFileMap_t1419586304 : public ConfigurationFileMap_t2625210096
{
public:
// System.String System.Configuration.ExeConfigurationFileMap::exeConfigFilename
String_t* ___exeConfigFilename_1;
// System.String System.Configuration.ExeConfigurationFileMap::localUserConfigFilename
String_t* ___localUserConfigFilename_2;
// System.String System.Configuration.ExeConfigurationFileMap::roamingUserConfigFilename
String_t* ___roamingUserConfigFilename_3;
public:
inline static int32_t get_offset_of_exeConfigFilename_1() { return static_cast<int32_t>(offsetof(ExeConfigurationFileMap_t1419586304, ___exeConfigFilename_1)); }
inline String_t* get_exeConfigFilename_1() const { return ___exeConfigFilename_1; }
inline String_t** get_address_of_exeConfigFilename_1() { return &___exeConfigFilename_1; }
inline void set_exeConfigFilename_1(String_t* value)
{
___exeConfigFilename_1 = value;
Il2CppCodeGenWriteBarrier((&___exeConfigFilename_1), value);
}
inline static int32_t get_offset_of_localUserConfigFilename_2() { return static_cast<int32_t>(offsetof(ExeConfigurationFileMap_t1419586304, ___localUserConfigFilename_2)); }
inline String_t* get_localUserConfigFilename_2() const { return ___localUserConfigFilename_2; }
inline String_t** get_address_of_localUserConfigFilename_2() { return &___localUserConfigFilename_2; }
inline void set_localUserConfigFilename_2(String_t* value)
{
___localUserConfigFilename_2 = value;
Il2CppCodeGenWriteBarrier((&___localUserConfigFilename_2), value);
}
inline static int32_t get_offset_of_roamingUserConfigFilename_3() { return static_cast<int32_t>(offsetof(ExeConfigurationFileMap_t1419586304, ___roamingUserConfigFilename_3)); }
inline String_t* get_roamingUserConfigFilename_3() const { return ___roamingUserConfigFilename_3; }
inline String_t** get_address_of_roamingUserConfigFilename_3() { return &___roamingUserConfigFilename_3; }
inline void set_roamingUserConfigFilename_3(String_t* value)
{
___roamingUserConfigFilename_3 = value;
Il2CppCodeGenWriteBarrier((&___roamingUserConfigFilename_3), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // EXECONFIGURATIONFILEMAP_T1419586304_H
#ifndef WAITFORENDOFFRAME_T1785723201_H
#define WAITFORENDOFFRAME_T1785723201_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.WaitForEndOfFrame
struct WaitForEndOfFrame_t1785723201 : public YieldInstruction_t3462875981
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // WAITFORENDOFFRAME_T1785723201_H
#ifndef PROPERTYINFORMATIONCOLLECTION_T954922393_H
#define PROPERTYINFORMATIONCOLLECTION_T954922393_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.PropertyInformationCollection
struct PropertyInformationCollection_t954922393 : public NameObjectCollectionBase_t2034248631
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // PROPERTYINFORMATIONCOLLECTION_T954922393_H
#ifndef XMLDOCUMENT_T3649534162_H
#define XMLDOCUMENT_T3649534162_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Xml.XmlDocument
struct XmlDocument_t3649534162 : public XmlNode_t616554813
{
public:
// System.Xml.XmlImplementation System.Xml.XmlDocument::implementation
XmlImplementation_t1664517635 * ___implementation_1;
// System.Xml.DomNameTable System.Xml.XmlDocument::domNameTable
DomNameTable_t3442363663 * ___domNameTable_2;
// System.Xml.XmlLinkedNode System.Xml.XmlDocument::lastChild
XmlLinkedNode_t1287616130 * ___lastChild_3;
// System.Xml.XmlNamedNodeMap System.Xml.XmlDocument::entities
XmlNamedNodeMap_t145210370 * ___entities_4;
// System.Collections.Hashtable System.Xml.XmlDocument::htElementIdMap
Hashtable_t909839986 * ___htElementIdMap_5;
// System.Collections.Hashtable System.Xml.XmlDocument::htElementIDAttrDecl
Hashtable_t909839986 * ___htElementIDAttrDecl_6;
// System.Xml.Schema.SchemaInfo System.Xml.XmlDocument::schemaInfo
SchemaInfo_t87206461 * ___schemaInfo_7;
// System.Xml.Schema.XmlSchemaSet System.Xml.XmlDocument::schemas
XmlSchemaSet_t313318308 * ___schemas_8;
// System.Boolean System.Xml.XmlDocument::reportValidity
bool ___reportValidity_9;
// System.Boolean System.Xml.XmlDocument::actualLoadingStatus
bool ___actualLoadingStatus_10;
// System.Xml.XmlNodeChangedEventHandler System.Xml.XmlDocument::onNodeInsertingDelegate
XmlNodeChangedEventHandler_t2964483403 * ___onNodeInsertingDelegate_11;
// System.Xml.XmlNodeChangedEventHandler System.Xml.XmlDocument::onNodeInsertedDelegate
XmlNodeChangedEventHandler_t2964483403 * ___onNodeInsertedDelegate_12;
// System.Xml.XmlNodeChangedEventHandler System.Xml.XmlDocument::onNodeRemovingDelegate
XmlNodeChangedEventHandler_t2964483403 * ___onNodeRemovingDelegate_13;
// System.Xml.XmlNodeChangedEventHandler System.Xml.XmlDocument::onNodeRemovedDelegate
XmlNodeChangedEventHandler_t2964483403 * ___onNodeRemovedDelegate_14;
// System.Xml.XmlNodeChangedEventHandler System.Xml.XmlDocument::onNodeChangingDelegate
XmlNodeChangedEventHandler_t2964483403 * ___onNodeChangingDelegate_15;
// System.Xml.XmlNodeChangedEventHandler System.Xml.XmlDocument::onNodeChangedDelegate
XmlNodeChangedEventHandler_t2964483403 * ___onNodeChangedDelegate_16;
// System.Boolean System.Xml.XmlDocument::fEntRefNodesPresent
bool ___fEntRefNodesPresent_17;
// System.Boolean System.Xml.XmlDocument::fCDataNodesPresent
bool ___fCDataNodesPresent_18;
// System.Boolean System.Xml.XmlDocument::preserveWhitespace
bool ___preserveWhitespace_19;
// System.Boolean System.Xml.XmlDocument::isLoading
bool ___isLoading_20;
// System.String System.Xml.XmlDocument::strDocumentName
String_t* ___strDocumentName_21;
// System.String System.Xml.XmlDocument::strDocumentFragmentName
String_t* ___strDocumentFragmentName_22;
// System.String System.Xml.XmlDocument::strCommentName
String_t* ___strCommentName_23;
// System.String System.Xml.XmlDocument::strTextName
String_t* ___strTextName_24;
// System.String System.Xml.XmlDocument::strCDataSectionName
String_t* ___strCDataSectionName_25;
// System.String System.Xml.XmlDocument::strEntityName
String_t* ___strEntityName_26;
// System.String System.Xml.XmlDocument::strID
String_t* ___strID_27;
// System.String System.Xml.XmlDocument::strXmlns
String_t* ___strXmlns_28;
// System.String System.Xml.XmlDocument::strXml
String_t* ___strXml_29;
// System.String System.Xml.XmlDocument::strSpace
String_t* ___strSpace_30;
// System.String System.Xml.XmlDocument::strLang
String_t* ___strLang_31;
// System.String System.Xml.XmlDocument::strEmpty
String_t* ___strEmpty_32;
// System.String System.Xml.XmlDocument::strNonSignificantWhitespaceName
String_t* ___strNonSignificantWhitespaceName_33;
// System.String System.Xml.XmlDocument::strSignificantWhitespaceName
String_t* ___strSignificantWhitespaceName_34;
// System.String System.Xml.XmlDocument::strReservedXmlns
String_t* ___strReservedXmlns_35;
// System.String System.Xml.XmlDocument::strReservedXml
String_t* ___strReservedXml_36;
// System.String System.Xml.XmlDocument::baseURI
String_t* ___baseURI_37;
// System.Xml.XmlResolver System.Xml.XmlDocument::resolver
XmlResolver_t2024571559 * ___resolver_38;
// System.Boolean System.Xml.XmlDocument::bSetResolver
bool ___bSetResolver_39;
// System.Object System.Xml.XmlDocument::objLock
RuntimeObject * ___objLock_40;
public:
inline static int32_t get_offset_of_implementation_1() { return static_cast<int32_t>(offsetof(XmlDocument_t3649534162, ___implementation_1)); }
inline XmlImplementation_t1664517635 * get_implementation_1() const { return ___implementation_1; }
inline XmlImplementation_t1664517635 ** get_address_of_implementation_1() { return &___implementation_1; }
inline void set_implementation_1(XmlImplementation_t1664517635 * value)
{
___implementation_1 = value;
Il2CppCodeGenWriteBarrier((&___implementation_1), value);
}
inline static int32_t get_offset_of_domNameTable_2() { return static_cast<int32_t>(offsetof(XmlDocument_t3649534162, ___domNameTable_2)); }
inline DomNameTable_t3442363663 * get_domNameTable_2() const { return ___domNameTable_2; }
inline DomNameTable_t3442363663 ** get_address_of_domNameTable_2() { return &___domNameTable_2; }
inline void set_domNameTable_2(DomNameTable_t3442363663 * value)
{
___domNameTable_2 = value;
Il2CppCodeGenWriteBarrier((&___domNameTable_2), value);
}
inline static int32_t get_offset_of_lastChild_3() { return static_cast<int32_t>(offsetof(XmlDocument_t3649534162, ___lastChild_3)); }
inline XmlLinkedNode_t1287616130 * get_lastChild_3() const { return ___lastChild_3; }
inline XmlLinkedNode_t1287616130 ** get_address_of_lastChild_3() { return &___lastChild_3; }
inline void set_lastChild_3(XmlLinkedNode_t1287616130 * value)
{
___lastChild_3 = value;
Il2CppCodeGenWriteBarrier((&___lastChild_3), value);
}
inline static int32_t get_offset_of_entities_4() { return static_cast<int32_t>(offsetof(XmlDocument_t3649534162, ___entities_4)); }
inline XmlNamedNodeMap_t145210370 * get_entities_4() const { return ___entities_4; }
inline XmlNamedNodeMap_t145210370 ** get_address_of_entities_4() { return &___entities_4; }
inline void set_entities_4(XmlNamedNodeMap_t145210370 * value)
{
___entities_4 = value;
Il2CppCodeGenWriteBarrier((&___entities_4), value);
}
inline static int32_t get_offset_of_htElementIdMap_5() { return static_cast<int32_t>(offsetof(XmlDocument_t3649534162, ___htElementIdMap_5)); }
inline Hashtable_t909839986 * get_htElementIdMap_5() const { return ___htElementIdMap_5; }
inline Hashtable_t909839986 ** get_address_of_htElementIdMap_5() { return &___htElementIdMap_5; }
inline void set_htElementIdMap_5(Hashtable_t909839986 * value)
{
___htElementIdMap_5 = value;
Il2CppCodeGenWriteBarrier((&___htElementIdMap_5), value);
}
inline static int32_t get_offset_of_htElementIDAttrDecl_6() { return static_cast<int32_t>(offsetof(XmlDocument_t3649534162, ___htElementIDAttrDecl_6)); }
inline Hashtable_t909839986 * get_htElementIDAttrDecl_6() const { return ___htElementIDAttrDecl_6; }
inline Hashtable_t909839986 ** get_address_of_htElementIDAttrDecl_6() { return &___htElementIDAttrDecl_6; }
inline void set_htElementIDAttrDecl_6(Hashtable_t909839986 * value)
{
___htElementIDAttrDecl_6 = value;
Il2CppCodeGenWriteBarrier((&___htElementIDAttrDecl_6), value);
}
inline static int32_t get_offset_of_schemaInfo_7() { return static_cast<int32_t>(offsetof(XmlDocument_t3649534162, ___schemaInfo_7)); }
inline SchemaInfo_t87206461 * get_schemaInfo_7() const { return ___schemaInfo_7; }
inline SchemaInfo_t87206461 ** get_address_of_schemaInfo_7() { return &___schemaInfo_7; }
inline void set_schemaInfo_7(SchemaInfo_t87206461 * value)
{
___schemaInfo_7 = value;
Il2CppCodeGenWriteBarrier((&___schemaInfo_7), value);
}
inline static int32_t get_offset_of_schemas_8() { return static_cast<int32_t>(offsetof(XmlDocument_t3649534162, ___schemas_8)); }
inline XmlSchemaSet_t313318308 * get_schemas_8() const { return ___schemas_8; }
inline XmlSchemaSet_t313318308 ** get_address_of_schemas_8() { return &___schemas_8; }
inline void set_schemas_8(XmlSchemaSet_t313318308 * value)
{
___schemas_8 = value;
Il2CppCodeGenWriteBarrier((&___schemas_8), value);
}
inline static int32_t get_offset_of_reportValidity_9() { return static_cast<int32_t>(offsetof(XmlDocument_t3649534162, ___reportValidity_9)); }
inline bool get_reportValidity_9() const { return ___reportValidity_9; }
inline bool* get_address_of_reportValidity_9() { return &___reportValidity_9; }
inline void set_reportValidity_9(bool value)
{
___reportValidity_9 = value;
}
inline static int32_t get_offset_of_actualLoadingStatus_10() { return static_cast<int32_t>(offsetof(XmlDocument_t3649534162, ___actualLoadingStatus_10)); }
inline bool get_actualLoadingStatus_10() const { return ___actualLoadingStatus_10; }
inline bool* get_address_of_actualLoadingStatus_10() { return &___actualLoadingStatus_10; }
inline void set_actualLoadingStatus_10(bool value)
{
___actualLoadingStatus_10 = value;
}
inline static int32_t get_offset_of_onNodeInsertingDelegate_11() { return static_cast<int32_t>(offsetof(XmlDocument_t3649534162, ___onNodeInsertingDelegate_11)); }
inline XmlNodeChangedEventHandler_t2964483403 * get_onNodeInsertingDelegate_11() const { return ___onNodeInsertingDelegate_11; }
inline XmlNodeChangedEventHandler_t2964483403 ** get_address_of_onNodeInsertingDelegate_11() { return &___onNodeInsertingDelegate_11; }
inline void set_onNodeInsertingDelegate_11(XmlNodeChangedEventHandler_t2964483403 * value)
{
___onNodeInsertingDelegate_11 = value;
Il2CppCodeGenWriteBarrier((&___onNodeInsertingDelegate_11), value);
}
inline static int32_t get_offset_of_onNodeInsertedDelegate_12() { return static_cast<int32_t>(offsetof(XmlDocument_t3649534162, ___onNodeInsertedDelegate_12)); }
inline XmlNodeChangedEventHandler_t2964483403 * get_onNodeInsertedDelegate_12() const { return ___onNodeInsertedDelegate_12; }
inline XmlNodeChangedEventHandler_t2964483403 ** get_address_of_onNodeInsertedDelegate_12() { return &___onNodeInsertedDelegate_12; }
inline void set_onNodeInsertedDelegate_12(XmlNodeChangedEventHandler_t2964483403 * value)
{
___onNodeInsertedDelegate_12 = value;
Il2CppCodeGenWriteBarrier((&___onNodeInsertedDelegate_12), value);
}
inline static int32_t get_offset_of_onNodeRemovingDelegate_13() { return static_cast<int32_t>(offsetof(XmlDocument_t3649534162, ___onNodeRemovingDelegate_13)); }
inline XmlNodeChangedEventHandler_t2964483403 * get_onNodeRemovingDelegate_13() const { return ___onNodeRemovingDelegate_13; }
inline XmlNodeChangedEventHandler_t2964483403 ** get_address_of_onNodeRemovingDelegate_13() { return &___onNodeRemovingDelegate_13; }
inline void set_onNodeRemovingDelegate_13(XmlNodeChangedEventHandler_t2964483403 * value)
{
___onNodeRemovingDelegate_13 = value;
Il2CppCodeGenWriteBarrier((&___onNodeRemovingDelegate_13), value);
}
inline static int32_t get_offset_of_onNodeRemovedDelegate_14() { return static_cast<int32_t>(offsetof(XmlDocument_t3649534162, ___onNodeRemovedDelegate_14)); }
inline XmlNodeChangedEventHandler_t2964483403 * get_onNodeRemovedDelegate_14() const { return ___onNodeRemovedDelegate_14; }
inline XmlNodeChangedEventHandler_t2964483403 ** get_address_of_onNodeRemovedDelegate_14() { return &___onNodeRemovedDelegate_14; }
inline void set_onNodeRemovedDelegate_14(XmlNodeChangedEventHandler_t2964483403 * value)
{
___onNodeRemovedDelegate_14 = value;
Il2CppCodeGenWriteBarrier((&___onNodeRemovedDelegate_14), value);
}
inline static int32_t get_offset_of_onNodeChangingDelegate_15() { return static_cast<int32_t>(offsetof(XmlDocument_t3649534162, ___onNodeChangingDelegate_15)); }
inline XmlNodeChangedEventHandler_t2964483403 * get_onNodeChangingDelegate_15() const { return ___onNodeChangingDelegate_15; }
inline XmlNodeChangedEventHandler_t2964483403 ** get_address_of_onNodeChangingDelegate_15() { return &___onNodeChangingDelegate_15; }
inline void set_onNodeChangingDelegate_15(XmlNodeChangedEventHandler_t2964483403 * value)
{
___onNodeChangingDelegate_15 = value;
Il2CppCodeGenWriteBarrier((&___onNodeChangingDelegate_15), value);
}
inline static int32_t get_offset_of_onNodeChangedDelegate_16() { return static_cast<int32_t>(offsetof(XmlDocument_t3649534162, ___onNodeChangedDelegate_16)); }
inline XmlNodeChangedEventHandler_t2964483403 * get_onNodeChangedDelegate_16() const { return ___onNodeChangedDelegate_16; }
inline XmlNodeChangedEventHandler_t2964483403 ** get_address_of_onNodeChangedDelegate_16() { return &___onNodeChangedDelegate_16; }
inline void set_onNodeChangedDelegate_16(XmlNodeChangedEventHandler_t2964483403 * value)
{
___onNodeChangedDelegate_16 = value;
Il2CppCodeGenWriteBarrier((&___onNodeChangedDelegate_16), value);
}
inline static int32_t get_offset_of_fEntRefNodesPresent_17() { return static_cast<int32_t>(offsetof(XmlDocument_t3649534162, ___fEntRefNodesPresent_17)); }
inline bool get_fEntRefNodesPresent_17() const { return ___fEntRefNodesPresent_17; }
inline bool* get_address_of_fEntRefNodesPresent_17() { return &___fEntRefNodesPresent_17; }
inline void set_fEntRefNodesPresent_17(bool value)
{
___fEntRefNodesPresent_17 = value;
}
inline static int32_t get_offset_of_fCDataNodesPresent_18() { return static_cast<int32_t>(offsetof(XmlDocument_t3649534162, ___fCDataNodesPresent_18)); }
inline bool get_fCDataNodesPresent_18() const { return ___fCDataNodesPresent_18; }
inline bool* get_address_of_fCDataNodesPresent_18() { return &___fCDataNodesPresent_18; }
inline void set_fCDataNodesPresent_18(bool value)
{
___fCDataNodesPresent_18 = value;
}
inline static int32_t get_offset_of_preserveWhitespace_19() { return static_cast<int32_t>(offsetof(XmlDocument_t3649534162, ___preserveWhitespace_19)); }
inline bool get_preserveWhitespace_19() const { return ___preserveWhitespace_19; }
inline bool* get_address_of_preserveWhitespace_19() { return &___preserveWhitespace_19; }
inline void set_preserveWhitespace_19(bool value)
{
___preserveWhitespace_19 = value;
}
inline static int32_t get_offset_of_isLoading_20() { return static_cast<int32_t>(offsetof(XmlDocument_t3649534162, ___isLoading_20)); }
inline bool get_isLoading_20() const { return ___isLoading_20; }
inline bool* get_address_of_isLoading_20() { return &___isLoading_20; }
inline void set_isLoading_20(bool value)
{
___isLoading_20 = value;
}
inline static int32_t get_offset_of_strDocumentName_21() { return static_cast<int32_t>(offsetof(XmlDocument_t3649534162, ___strDocumentName_21)); }
inline String_t* get_strDocumentName_21() const { return ___strDocumentName_21; }
inline String_t** get_address_of_strDocumentName_21() { return &___strDocumentName_21; }
inline void set_strDocumentName_21(String_t* value)
{
___strDocumentName_21 = value;
Il2CppCodeGenWriteBarrier((&___strDocumentName_21), value);
}
inline static int32_t get_offset_of_strDocumentFragmentName_22() { return static_cast<int32_t>(offsetof(XmlDocument_t3649534162, ___strDocumentFragmentName_22)); }
inline String_t* get_strDocumentFragmentName_22() const { return ___strDocumentFragmentName_22; }
inline String_t** get_address_of_strDocumentFragmentName_22() { return &___strDocumentFragmentName_22; }
inline void set_strDocumentFragmentName_22(String_t* value)
{
___strDocumentFragmentName_22 = value;
Il2CppCodeGenWriteBarrier((&___strDocumentFragmentName_22), value);
}
inline static int32_t get_offset_of_strCommentName_23() { return static_cast<int32_t>(offsetof(XmlDocument_t3649534162, ___strCommentName_23)); }
inline String_t* get_strCommentName_23() const { return ___strCommentName_23; }
inline String_t** get_address_of_strCommentName_23() { return &___strCommentName_23; }
inline void set_strCommentName_23(String_t* value)
{
___strCommentName_23 = value;
Il2CppCodeGenWriteBarrier((&___strCommentName_23), value);
}
inline static int32_t get_offset_of_strTextName_24() { return static_cast<int32_t>(offsetof(XmlDocument_t3649534162, ___strTextName_24)); }
inline String_t* get_strTextName_24() const { return ___strTextName_24; }
inline String_t** get_address_of_strTextName_24() { return &___strTextName_24; }
inline void set_strTextName_24(String_t* value)
{
___strTextName_24 = value;
Il2CppCodeGenWriteBarrier((&___strTextName_24), value);
}
inline static int32_t get_offset_of_strCDataSectionName_25() { return static_cast<int32_t>(offsetof(XmlDocument_t3649534162, ___strCDataSectionName_25)); }
inline String_t* get_strCDataSectionName_25() const { return ___strCDataSectionName_25; }
inline String_t** get_address_of_strCDataSectionName_25() { return &___strCDataSectionName_25; }
inline void set_strCDataSectionName_25(String_t* value)
{
___strCDataSectionName_25 = value;
Il2CppCodeGenWriteBarrier((&___strCDataSectionName_25), value);
}
inline static int32_t get_offset_of_strEntityName_26() { return static_cast<int32_t>(offsetof(XmlDocument_t3649534162, ___strEntityName_26)); }
inline String_t* get_strEntityName_26() const { return ___strEntityName_26; }
inline String_t** get_address_of_strEntityName_26() { return &___strEntityName_26; }
inline void set_strEntityName_26(String_t* value)
{
___strEntityName_26 = value;
Il2CppCodeGenWriteBarrier((&___strEntityName_26), value);
}
inline static int32_t get_offset_of_strID_27() { return static_cast<int32_t>(offsetof(XmlDocument_t3649534162, ___strID_27)); }
inline String_t* get_strID_27() const { return ___strID_27; }
inline String_t** get_address_of_strID_27() { return &___strID_27; }
inline void set_strID_27(String_t* value)
{
___strID_27 = value;
Il2CppCodeGenWriteBarrier((&___strID_27), value);
}
inline static int32_t get_offset_of_strXmlns_28() { return static_cast<int32_t>(offsetof(XmlDocument_t3649534162, ___strXmlns_28)); }
inline String_t* get_strXmlns_28() const { return ___strXmlns_28; }
inline String_t** get_address_of_strXmlns_28() { return &___strXmlns_28; }
inline void set_strXmlns_28(String_t* value)
{
___strXmlns_28 = value;
Il2CppCodeGenWriteBarrier((&___strXmlns_28), value);
}
inline static int32_t get_offset_of_strXml_29() { return static_cast<int32_t>(offsetof(XmlDocument_t3649534162, ___strXml_29)); }
inline String_t* get_strXml_29() const { return ___strXml_29; }
inline String_t** get_address_of_strXml_29() { return &___strXml_29; }
inline void set_strXml_29(String_t* value)
{
___strXml_29 = value;
Il2CppCodeGenWriteBarrier((&___strXml_29), value);
}
inline static int32_t get_offset_of_strSpace_30() { return static_cast<int32_t>(offsetof(XmlDocument_t3649534162, ___strSpace_30)); }
inline String_t* get_strSpace_30() const { return ___strSpace_30; }
inline String_t** get_address_of_strSpace_30() { return &___strSpace_30; }
inline void set_strSpace_30(String_t* value)
{
___strSpace_30 = value;
Il2CppCodeGenWriteBarrier((&___strSpace_30), value);
}
inline static int32_t get_offset_of_strLang_31() { return static_cast<int32_t>(offsetof(XmlDocument_t3649534162, ___strLang_31)); }
inline String_t* get_strLang_31() const { return ___strLang_31; }
inline String_t** get_address_of_strLang_31() { return &___strLang_31; }
inline void set_strLang_31(String_t* value)
{
___strLang_31 = value;
Il2CppCodeGenWriteBarrier((&___strLang_31), value);
}
inline static int32_t get_offset_of_strEmpty_32() { return static_cast<int32_t>(offsetof(XmlDocument_t3649534162, ___strEmpty_32)); }
inline String_t* get_strEmpty_32() const { return ___strEmpty_32; }
inline String_t** get_address_of_strEmpty_32() { return &___strEmpty_32; }
inline void set_strEmpty_32(String_t* value)
{
___strEmpty_32 = value;
Il2CppCodeGenWriteBarrier((&___strEmpty_32), value);
}
inline static int32_t get_offset_of_strNonSignificantWhitespaceName_33() { return static_cast<int32_t>(offsetof(XmlDocument_t3649534162, ___strNonSignificantWhitespaceName_33)); }
inline String_t* get_strNonSignificantWhitespaceName_33() const { return ___strNonSignificantWhitespaceName_33; }
inline String_t** get_address_of_strNonSignificantWhitespaceName_33() { return &___strNonSignificantWhitespaceName_33; }
inline void set_strNonSignificantWhitespaceName_33(String_t* value)
{
___strNonSignificantWhitespaceName_33 = value;
Il2CppCodeGenWriteBarrier((&___strNonSignificantWhitespaceName_33), value);
}
inline static int32_t get_offset_of_strSignificantWhitespaceName_34() { return static_cast<int32_t>(offsetof(XmlDocument_t3649534162, ___strSignificantWhitespaceName_34)); }
inline String_t* get_strSignificantWhitespaceName_34() const { return ___strSignificantWhitespaceName_34; }
inline String_t** get_address_of_strSignificantWhitespaceName_34() { return &___strSignificantWhitespaceName_34; }
inline void set_strSignificantWhitespaceName_34(String_t* value)
{
___strSignificantWhitespaceName_34 = value;
Il2CppCodeGenWriteBarrier((&___strSignificantWhitespaceName_34), value);
}
inline static int32_t get_offset_of_strReservedXmlns_35() { return static_cast<int32_t>(offsetof(XmlDocument_t3649534162, ___strReservedXmlns_35)); }
inline String_t* get_strReservedXmlns_35() const { return ___strReservedXmlns_35; }
inline String_t** get_address_of_strReservedXmlns_35() { return &___strReservedXmlns_35; }
inline void set_strReservedXmlns_35(String_t* value)
{
___strReservedXmlns_35 = value;
Il2CppCodeGenWriteBarrier((&___strReservedXmlns_35), value);
}
inline static int32_t get_offset_of_strReservedXml_36() { return static_cast<int32_t>(offsetof(XmlDocument_t3649534162, ___strReservedXml_36)); }
inline String_t* get_strReservedXml_36() const { return ___strReservedXml_36; }
inline String_t** get_address_of_strReservedXml_36() { return &___strReservedXml_36; }
inline void set_strReservedXml_36(String_t* value)
{
___strReservedXml_36 = value;
Il2CppCodeGenWriteBarrier((&___strReservedXml_36), value);
}
inline static int32_t get_offset_of_baseURI_37() { return static_cast<int32_t>(offsetof(XmlDocument_t3649534162, ___baseURI_37)); }
inline String_t* get_baseURI_37() const { return ___baseURI_37; }
inline String_t** get_address_of_baseURI_37() { return &___baseURI_37; }
inline void set_baseURI_37(String_t* value)
{
___baseURI_37 = value;
Il2CppCodeGenWriteBarrier((&___baseURI_37), value);
}
inline static int32_t get_offset_of_resolver_38() { return static_cast<int32_t>(offsetof(XmlDocument_t3649534162, ___resolver_38)); }
inline XmlResolver_t2024571559 * get_resolver_38() const { return ___resolver_38; }
inline XmlResolver_t2024571559 ** get_address_of_resolver_38() { return &___resolver_38; }
inline void set_resolver_38(XmlResolver_t2024571559 * value)
{
___resolver_38 = value;
Il2CppCodeGenWriteBarrier((&___resolver_38), value);
}
inline static int32_t get_offset_of_bSetResolver_39() { return static_cast<int32_t>(offsetof(XmlDocument_t3649534162, ___bSetResolver_39)); }
inline bool get_bSetResolver_39() const { return ___bSetResolver_39; }
inline bool* get_address_of_bSetResolver_39() { return &___bSetResolver_39; }
inline void set_bSetResolver_39(bool value)
{
___bSetResolver_39 = value;
}
inline static int32_t get_offset_of_objLock_40() { return static_cast<int32_t>(offsetof(XmlDocument_t3649534162, ___objLock_40)); }
inline RuntimeObject * get_objLock_40() const { return ___objLock_40; }
inline RuntimeObject ** get_address_of_objLock_40() { return &___objLock_40; }
inline void set_objLock_40(RuntimeObject * value)
{
___objLock_40 = value;
Il2CppCodeGenWriteBarrier((&___objLock_40), value);
}
};
struct XmlDocument_t3649534162_StaticFields
{
public:
// System.Xml.EmptyEnumerator System.Xml.XmlDocument::EmptyEnumerator
EmptyEnumerator_t2328036233 * ___EmptyEnumerator_41;
// System.Xml.Schema.IXmlSchemaInfo System.Xml.XmlDocument::NotKnownSchemaInfo
RuntimeObject* ___NotKnownSchemaInfo_42;
// System.Xml.Schema.IXmlSchemaInfo System.Xml.XmlDocument::ValidSchemaInfo
RuntimeObject* ___ValidSchemaInfo_43;
// System.Xml.Schema.IXmlSchemaInfo System.Xml.XmlDocument::InvalidSchemaInfo
RuntimeObject* ___InvalidSchemaInfo_44;
public:
inline static int32_t get_offset_of_EmptyEnumerator_41() { return static_cast<int32_t>(offsetof(XmlDocument_t3649534162_StaticFields, ___EmptyEnumerator_41)); }
inline EmptyEnumerator_t2328036233 * get_EmptyEnumerator_41() const { return ___EmptyEnumerator_41; }
inline EmptyEnumerator_t2328036233 ** get_address_of_EmptyEnumerator_41() { return &___EmptyEnumerator_41; }
inline void set_EmptyEnumerator_41(EmptyEnumerator_t2328036233 * value)
{
___EmptyEnumerator_41 = value;
Il2CppCodeGenWriteBarrier((&___EmptyEnumerator_41), value);
}
inline static int32_t get_offset_of_NotKnownSchemaInfo_42() { return static_cast<int32_t>(offsetof(XmlDocument_t3649534162_StaticFields, ___NotKnownSchemaInfo_42)); }
inline RuntimeObject* get_NotKnownSchemaInfo_42() const { return ___NotKnownSchemaInfo_42; }
inline RuntimeObject** get_address_of_NotKnownSchemaInfo_42() { return &___NotKnownSchemaInfo_42; }
inline void set_NotKnownSchemaInfo_42(RuntimeObject* value)
{
___NotKnownSchemaInfo_42 = value;
Il2CppCodeGenWriteBarrier((&___NotKnownSchemaInfo_42), value);
}
inline static int32_t get_offset_of_ValidSchemaInfo_43() { return static_cast<int32_t>(offsetof(XmlDocument_t3649534162_StaticFields, ___ValidSchemaInfo_43)); }
inline RuntimeObject* get_ValidSchemaInfo_43() const { return ___ValidSchemaInfo_43; }
inline RuntimeObject** get_address_of_ValidSchemaInfo_43() { return &___ValidSchemaInfo_43; }
inline void set_ValidSchemaInfo_43(RuntimeObject* value)
{
___ValidSchemaInfo_43 = value;
Il2CppCodeGenWriteBarrier((&___ValidSchemaInfo_43), value);
}
inline static int32_t get_offset_of_InvalidSchemaInfo_44() { return static_cast<int32_t>(offsetof(XmlDocument_t3649534162_StaticFields, ___InvalidSchemaInfo_44)); }
inline RuntimeObject* get_InvalidSchemaInfo_44() const { return ___InvalidSchemaInfo_44; }
inline RuntimeObject** get_address_of_InvalidSchemaInfo_44() { return &___InvalidSchemaInfo_44; }
inline void set_InvalidSchemaInfo_44(RuntimeObject* value)
{
___InvalidSchemaInfo_44 = value;
Il2CppCodeGenWriteBarrier((&___InvalidSchemaInfo_44), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // XMLDOCUMENT_T3649534162_H
#ifndef ENUM_T2459695545_H
#define ENUM_T2459695545_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Enum
struct Enum_t2459695545 : public ValueType_t3507792607
{
public:
public:
};
struct Enum_t2459695545_StaticFields
{
public:
// System.Char[] System.Enum::enumSeperatorCharArray
CharU5BU5D_t1328083999* ___enumSeperatorCharArray_0;
public:
inline static int32_t get_offset_of_enumSeperatorCharArray_0() { return static_cast<int32_t>(offsetof(Enum_t2459695545_StaticFields, ___enumSeperatorCharArray_0)); }
inline CharU5BU5D_t1328083999* get_enumSeperatorCharArray_0() const { return ___enumSeperatorCharArray_0; }
inline CharU5BU5D_t1328083999** get_address_of_enumSeperatorCharArray_0() { return &___enumSeperatorCharArray_0; }
inline void set_enumSeperatorCharArray_0(CharU5BU5D_t1328083999* value)
{
___enumSeperatorCharArray_0 = value;
Il2CppCodeGenWriteBarrier((&___enumSeperatorCharArray_0), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of System.Enum
struct Enum_t2459695545_marshaled_pinvoke
{
};
// Native definition for COM marshalling of System.Enum
struct Enum_t2459695545_marshaled_com
{
};
#endif // ENUM_T2459695545_H
#ifndef CONFIGURATIONVALIDATORATTRIBUTE_T1007519140_H
#define CONFIGURATIONVALIDATORATTRIBUTE_T1007519140_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.ConfigurationValidatorAttribute
struct ConfigurationValidatorAttribute_t1007519140 : public Attribute_t542643598
{
public:
// System.Type System.Configuration.ConfigurationValidatorAttribute::validatorType
Type_t * ___validatorType_0;
// System.Configuration.ConfigurationValidatorBase System.Configuration.ConfigurationValidatorAttribute::instance
ConfigurationValidatorBase_t210547623 * ___instance_1;
public:
inline static int32_t get_offset_of_validatorType_0() { return static_cast<int32_t>(offsetof(ConfigurationValidatorAttribute_t1007519140, ___validatorType_0)); }
inline Type_t * get_validatorType_0() const { return ___validatorType_0; }
inline Type_t ** get_address_of_validatorType_0() { return &___validatorType_0; }
inline void set_validatorType_0(Type_t * value)
{
___validatorType_0 = value;
Il2CppCodeGenWriteBarrier((&___validatorType_0), value);
}
inline static int32_t get_offset_of_instance_1() { return static_cast<int32_t>(offsetof(ConfigurationValidatorAttribute_t1007519140, ___instance_1)); }
inline ConfigurationValidatorBase_t210547623 * get_instance_1() const { return ___instance_1; }
inline ConfigurationValidatorBase_t210547623 ** get_address_of_instance_1() { return &___instance_1; }
inline void set_instance_1(ConfigurationValidatorBase_t210547623 * value)
{
___instance_1 = value;
Il2CppCodeGenWriteBarrier((&___instance_1), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // CONFIGURATIONVALIDATORATTRIBUTE_T1007519140_H
#ifndef DEFAULTVALIDATOR_T300527515_H
#define DEFAULTVALIDATOR_T300527515_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.DefaultValidator
struct DefaultValidator_t300527515 : public ConfigurationValidatorBase_t210547623
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // DEFAULTVALIDATOR_T300527515_H
#ifndef DELEGATE_T3022476291_H
#define DELEGATE_T3022476291_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Delegate
struct Delegate_t3022476291 : public RuntimeObject
{
public:
// System.IntPtr System.Delegate::method_ptr
Il2CppMethodPointer ___method_ptr_0;
// System.IntPtr System.Delegate::invoke_impl
intptr_t ___invoke_impl_1;
// System.Object System.Delegate::m_target
RuntimeObject * ___m_target_2;
// System.IntPtr System.Delegate::method
intptr_t ___method_3;
// System.IntPtr System.Delegate::delegate_trampoline
intptr_t ___delegate_trampoline_4;
// System.IntPtr System.Delegate::extra_arg
intptr_t ___extra_arg_5;
// System.IntPtr System.Delegate::method_code
intptr_t ___method_code_6;
// System.Reflection.MethodInfo System.Delegate::method_info
MethodInfo_t * ___method_info_7;
// System.Reflection.MethodInfo System.Delegate::original_method_info
MethodInfo_t * ___original_method_info_8;
// System.DelegateData System.Delegate::data
DelegateData_t1572802995 * ___data_9;
// System.Boolean System.Delegate::method_is_virtual
bool ___method_is_virtual_10;
public:
inline static int32_t get_offset_of_method_ptr_0() { return static_cast<int32_t>(offsetof(Delegate_t3022476291, ___method_ptr_0)); }
inline Il2CppMethodPointer get_method_ptr_0() const { return ___method_ptr_0; }
inline Il2CppMethodPointer* get_address_of_method_ptr_0() { return &___method_ptr_0; }
inline void set_method_ptr_0(Il2CppMethodPointer value)
{
___method_ptr_0 = value;
}
inline static int32_t get_offset_of_invoke_impl_1() { return static_cast<int32_t>(offsetof(Delegate_t3022476291, ___invoke_impl_1)); }
inline intptr_t get_invoke_impl_1() const { return ___invoke_impl_1; }
inline intptr_t* get_address_of_invoke_impl_1() { return &___invoke_impl_1; }
inline void set_invoke_impl_1(intptr_t value)
{
___invoke_impl_1 = value;
}
inline static int32_t get_offset_of_m_target_2() { return static_cast<int32_t>(offsetof(Delegate_t3022476291, ___m_target_2)); }
inline RuntimeObject * get_m_target_2() const { return ___m_target_2; }
inline RuntimeObject ** get_address_of_m_target_2() { return &___m_target_2; }
inline void set_m_target_2(RuntimeObject * value)
{
___m_target_2 = value;
Il2CppCodeGenWriteBarrier((&___m_target_2), value);
}
inline static int32_t get_offset_of_method_3() { return static_cast<int32_t>(offsetof(Delegate_t3022476291, ___method_3)); }
inline intptr_t get_method_3() const { return ___method_3; }
inline intptr_t* get_address_of_method_3() { return &___method_3; }
inline void set_method_3(intptr_t value)
{
___method_3 = value;
}
inline static int32_t get_offset_of_delegate_trampoline_4() { return static_cast<int32_t>(offsetof(Delegate_t3022476291, ___delegate_trampoline_4)); }
inline intptr_t get_delegate_trampoline_4() const { return ___delegate_trampoline_4; }
inline intptr_t* get_address_of_delegate_trampoline_4() { return &___delegate_trampoline_4; }
inline void set_delegate_trampoline_4(intptr_t value)
{
___delegate_trampoline_4 = value;
}
inline static int32_t get_offset_of_extra_arg_5() { return static_cast<int32_t>(offsetof(Delegate_t3022476291, ___extra_arg_5)); }
inline intptr_t get_extra_arg_5() const { return ___extra_arg_5; }
inline intptr_t* get_address_of_extra_arg_5() { return &___extra_arg_5; }
inline void set_extra_arg_5(intptr_t value)
{
___extra_arg_5 = value;
}
inline static int32_t get_offset_of_method_code_6() { return static_cast<int32_t>(offsetof(Delegate_t3022476291, ___method_code_6)); }
inline intptr_t get_method_code_6() const { return ___method_code_6; }
inline intptr_t* get_address_of_method_code_6() { return &___method_code_6; }
inline void set_method_code_6(intptr_t value)
{
___method_code_6 = value;
}
inline static int32_t get_offset_of_method_info_7() { return static_cast<int32_t>(offsetof(Delegate_t3022476291, ___method_info_7)); }
inline MethodInfo_t * get_method_info_7() const { return ___method_info_7; }
inline MethodInfo_t ** get_address_of_method_info_7() { return &___method_info_7; }
inline void set_method_info_7(MethodInfo_t * value)
{
___method_info_7 = value;
Il2CppCodeGenWriteBarrier((&___method_info_7), value);
}
inline static int32_t get_offset_of_original_method_info_8() { return static_cast<int32_t>(offsetof(Delegate_t3022476291, ___original_method_info_8)); }
inline MethodInfo_t * get_original_method_info_8() const { return ___original_method_info_8; }
inline MethodInfo_t ** get_address_of_original_method_info_8() { return &___original_method_info_8; }
inline void set_original_method_info_8(MethodInfo_t * value)
{
___original_method_info_8 = value;
Il2CppCodeGenWriteBarrier((&___original_method_info_8), value);
}
inline static int32_t get_offset_of_data_9() { return static_cast<int32_t>(offsetof(Delegate_t3022476291, ___data_9)); }
inline DelegateData_t1572802995 * get_data_9() const { return ___data_9; }
inline DelegateData_t1572802995 ** get_address_of_data_9() { return &___data_9; }
inline void set_data_9(DelegateData_t1572802995 * value)
{
___data_9 = value;
Il2CppCodeGenWriteBarrier((&___data_9), value);
}
inline static int32_t get_offset_of_method_is_virtual_10() { return static_cast<int32_t>(offsetof(Delegate_t3022476291, ___method_is_virtual_10)); }
inline bool get_method_is_virtual_10() const { return ___method_is_virtual_10; }
inline bool* get_address_of_method_is_virtual_10() { return &___method_is_virtual_10; }
inline void set_method_is_virtual_10(bool value)
{
___method_is_virtual_10 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of System.Delegate
struct Delegate_t3022476291_marshaled_pinvoke
{
intptr_t ___method_ptr_0;
intptr_t ___invoke_impl_1;
Il2CppIUnknown* ___m_target_2;
intptr_t ___method_3;
intptr_t ___delegate_trampoline_4;
intptr_t ___extra_arg_5;
intptr_t ___method_code_6;
MethodInfo_t * ___method_info_7;
MethodInfo_t * ___original_method_info_8;
DelegateData_t1572802995 * ___data_9;
int32_t ___method_is_virtual_10;
};
// Native definition for COM marshalling of System.Delegate
struct Delegate_t3022476291_marshaled_com
{
intptr_t ___method_ptr_0;
intptr_t ___invoke_impl_1;
Il2CppIUnknown* ___m_target_2;
intptr_t ___method_3;
intptr_t ___delegate_trampoline_4;
intptr_t ___extra_arg_5;
intptr_t ___method_code_6;
MethodInfo_t * ___method_info_7;
MethodInfo_t * ___original_method_info_8;
DelegateData_t1572802995 * ___data_9;
int32_t ___method_is_virtual_10;
};
#endif // DELEGATE_T3022476291_H
#ifndef SECURITYACTION_T446643378_H
#define SECURITYACTION_T446643378_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Permissions.SecurityAction
struct SecurityAction_t446643378
{
public:
// System.Int32 System.Security.Permissions.SecurityAction::value__
int32_t ___value___2;
public:
inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(SecurityAction_t446643378, ___value___2)); }
inline int32_t get_value___2() const { return ___value___2; }
inline int32_t* get_address_of_value___2() { return &___value___2; }
inline void set_value___2(int32_t value)
{
___value___2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // SECURITYACTION_T446643378_H
#ifndef PADDINGMODE_T3032142640_H
#define PADDINGMODE_T3032142640_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.PaddingMode
struct PaddingMode_t3032142640
{
public:
// System.Int32 System.Security.Cryptography.PaddingMode::value__
int32_t ___value___2;
public:
inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(PaddingMode_t3032142640, ___value___2)); }
inline int32_t get_value___2() const { return ___value___2; }
inline int32_t* get_address_of_value___2() { return &___value___2; }
inline void set_value___2(int32_t value)
{
___value___2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // PADDINGMODE_T3032142640_H
#ifndef ASYNCOPERATION_T3814632279_H
#define ASYNCOPERATION_T3814632279_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.AsyncOperation
struct AsyncOperation_t3814632279 : public YieldInstruction_t3462875981
{
public:
// System.IntPtr UnityEngine.AsyncOperation::m_Ptr
intptr_t ___m_Ptr_0;
// System.Action`1<UnityEngine.AsyncOperation> UnityEngine.AsyncOperation::m_completeCallback
Action_1_t3616431661 * ___m_completeCallback_1;
public:
inline static int32_t get_offset_of_m_Ptr_0() { return static_cast<int32_t>(offsetof(AsyncOperation_t3814632279, ___m_Ptr_0)); }
inline intptr_t get_m_Ptr_0() const { return ___m_Ptr_0; }
inline intptr_t* get_address_of_m_Ptr_0() { return &___m_Ptr_0; }
inline void set_m_Ptr_0(intptr_t value)
{
___m_Ptr_0 = value;
}
inline static int32_t get_offset_of_m_completeCallback_1() { return static_cast<int32_t>(offsetof(AsyncOperation_t3814632279, ___m_completeCallback_1)); }
inline Action_1_t3616431661 * get_m_completeCallback_1() const { return ___m_completeCallback_1; }
inline Action_1_t3616431661 ** get_address_of_m_completeCallback_1() { return &___m_completeCallback_1; }
inline void set_m_completeCallback_1(Action_1_t3616431661 * value)
{
___m_completeCallback_1 = value;
Il2CppCodeGenWriteBarrier((&___m_completeCallback_1), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of UnityEngine.AsyncOperation
struct AsyncOperation_t3814632279_marshaled_pinvoke : public YieldInstruction_t3462875981_marshaled_pinvoke
{
intptr_t ___m_Ptr_0;
Il2CppMethodPointer ___m_completeCallback_1;
};
// Native definition for COM marshalling of UnityEngine.AsyncOperation
struct AsyncOperation_t3814632279_marshaled_com : public YieldInstruction_t3462875981_marshaled_com
{
intptr_t ___m_Ptr_0;
Il2CppMethodPointer ___m_completeCallback_1;
};
#endif // ASYNCOPERATION_T3814632279_H
#ifndef LOGTYPE_T1559732862_H
#define LOGTYPE_T1559732862_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.LogType
struct LogType_t1559732862
{
public:
// System.Int32 UnityEngine.LogType::value__
int32_t ___value___2;
public:
inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(LogType_t1559732862, ___value___2)); }
inline int32_t get_value___2() const { return ___value___2; }
inline int32_t* get_address_of_value___2() { return &___value___2; }
inline void set_value___2(int32_t value)
{
___value___2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // LOGTYPE_T1559732862_H
#ifndef CONFIGURATIONEXCEPTION_T3814184945_H
#define CONFIGURATIONEXCEPTION_T3814184945_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.ConfigurationException
struct ConfigurationException_t3814184945 : public SystemException_t3877406272
{
public:
// System.String System.Configuration.ConfigurationException::filename
String_t* ___filename_16;
// System.Int32 System.Configuration.ConfigurationException::line
int32_t ___line_17;
public:
inline static int32_t get_offset_of_filename_16() { return static_cast<int32_t>(offsetof(ConfigurationException_t3814184945, ___filename_16)); }
inline String_t* get_filename_16() const { return ___filename_16; }
inline String_t** get_address_of_filename_16() { return &___filename_16; }
inline void set_filename_16(String_t* value)
{
___filename_16 = value;
Il2CppCodeGenWriteBarrier((&___filename_16), value);
}
inline static int32_t get_offset_of_line_17() { return static_cast<int32_t>(offsetof(ConfigurationException_t3814184945, ___line_17)); }
inline int32_t get_line_17() const { return ___line_17; }
inline int32_t* get_address_of_line_17() { return &___line_17; }
inline void set_line_17(int32_t value)
{
___line_17 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // CONFIGURATIONEXCEPTION_T3814184945_H
#ifndef CONFIGURATIONUSERLEVEL_T1204907851_H
#define CONFIGURATIONUSERLEVEL_T1204907851_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.ConfigurationUserLevel
struct ConfigurationUserLevel_t1204907851
{
public:
// System.Int32 System.Configuration.ConfigurationUserLevel::value__
int32_t ___value___2;
public:
inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(ConfigurationUserLevel_t1204907851, ___value___2)); }
inline int32_t get_value___2() const { return ___value___2; }
inline int32_t* get_address_of_value___2() { return &___value___2; }
inline void set_value___2(int32_t value)
{
___value___2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // CONFIGURATIONUSERLEVEL_T1204907851_H
#ifndef CONFIGURATIONSAVEMODE_T700320212_H
#define CONFIGURATIONSAVEMODE_T700320212_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.ConfigurationSaveMode
struct ConfigurationSaveMode_t700320212
{
public:
// System.Int32 System.Configuration.ConfigurationSaveMode::value__
int32_t ___value___2;
public:
inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(ConfigurationSaveMode_t700320212, ___value___2)); }
inline int32_t get_value___2() const { return ___value___2; }
inline int32_t* get_address_of_value___2() { return &___value___2; }
inline void set_value___2(int32_t value)
{
___value___2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // CONFIGURATIONSAVEMODE_T700320212_H
#ifndef DEFAULTSECTION_T3840532724_H
#define DEFAULTSECTION_T3840532724_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.DefaultSection
struct DefaultSection_t3840532724 : public ConfigurationSection_t2600766927
{
public:
public:
};
struct DefaultSection_t3840532724_StaticFields
{
public:
// System.Configuration.ConfigurationPropertyCollection System.Configuration.DefaultSection::properties
ConfigurationPropertyCollection_t3473514151 * ___properties_19;
public:
inline static int32_t get_offset_of_properties_19() { return static_cast<int32_t>(offsetof(DefaultSection_t3840532724_StaticFields, ___properties_19)); }
inline ConfigurationPropertyCollection_t3473514151 * get_properties_19() const { return ___properties_19; }
inline ConfigurationPropertyCollection_t3473514151 ** get_address_of_properties_19() { return &___properties_19; }
inline void set_properties_19(ConfigurationPropertyCollection_t3473514151 * value)
{
___properties_19 = value;
Il2CppCodeGenWriteBarrier((&___properties_19), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // DEFAULTSECTION_T3840532724_H
#ifndef PROPERTYVALUEORIGIN_T1217826846_H
#define PROPERTYVALUEORIGIN_T1217826846_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.PropertyValueOrigin
struct PropertyValueOrigin_t1217826846
{
public:
// System.Int32 System.Configuration.PropertyValueOrigin::value__
int32_t ___value___2;
public:
inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(PropertyValueOrigin_t1217826846, ___value___2)); }
inline int32_t get_value___2() const { return ___value___2; }
inline int32_t* get_address_of_value___2() { return &___value___2; }
inline void set_value___2(int32_t value)
{
___value___2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // PROPERTYVALUEORIGIN_T1217826846_H
#ifndef IGNORESECTION_T681509237_H
#define IGNORESECTION_T681509237_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.IgnoreSection
struct IgnoreSection_t681509237 : public ConfigurationSection_t2600766927
{
public:
// System.String System.Configuration.IgnoreSection::xml
String_t* ___xml_19;
public:
inline static int32_t get_offset_of_xml_19() { return static_cast<int32_t>(offsetof(IgnoreSection_t681509237, ___xml_19)); }
inline String_t* get_xml_19() const { return ___xml_19; }
inline String_t** get_address_of_xml_19() { return &___xml_19; }
inline void set_xml_19(String_t* value)
{
___xml_19 = value;
Il2CppCodeGenWriteBarrier((&___xml_19), value);
}
};
struct IgnoreSection_t681509237_StaticFields
{
public:
// System.Configuration.ConfigurationPropertyCollection System.Configuration.IgnoreSection::properties
ConfigurationPropertyCollection_t3473514151 * ___properties_20;
public:
inline static int32_t get_offset_of_properties_20() { return static_cast<int32_t>(offsetof(IgnoreSection_t681509237_StaticFields, ___properties_20)); }
inline ConfigurationPropertyCollection_t3473514151 * get_properties_20() const { return ___properties_20; }
inline ConfigurationPropertyCollection_t3473514151 ** get_address_of_properties_20() { return &___properties_20; }
inline void set_properties_20(ConfigurationPropertyCollection_t3473514151 * value)
{
___properties_20 = value;
Il2CppCodeGenWriteBarrier((&___properties_20), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // IGNORESECTION_T681509237_H
#ifndef CONFIGURATIONPROPERTYOPTIONS_T3219689025_H
#define CONFIGURATIONPROPERTYOPTIONS_T3219689025_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.ConfigurationPropertyOptions
struct ConfigurationPropertyOptions_t3219689025
{
public:
// System.Int32 System.Configuration.ConfigurationPropertyOptions::value__
int32_t ___value___2;
public:
inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(ConfigurationPropertyOptions_t3219689025, ___value___2)); }
inline int32_t get_value___2() const { return ___value___2; }
inline int32_t* get_address_of_value___2() { return &___value___2; }
inline void set_value___2(int32_t value)
{
___value___2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // CONFIGURATIONPROPERTYOPTIONS_T3219689025_H
#ifndef CONFIGURATIONALLOWDEFINITION_T3250313246_H
#define CONFIGURATIONALLOWDEFINITION_T3250313246_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.ConfigurationAllowDefinition
struct ConfigurationAllowDefinition_t3250313246
{
public:
// System.Int32 System.Configuration.ConfigurationAllowDefinition::value__
int32_t ___value___2;
public:
inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(ConfigurationAllowDefinition_t3250313246, ___value___2)); }
inline int32_t get_value___2() const { return ___value___2; }
inline int32_t* get_address_of_value___2() { return &___value___2; }
inline void set_value___2(int32_t value)
{
___value___2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // CONFIGURATIONALLOWDEFINITION_T3250313246_H
#ifndef CONFIGURATIONXMLDOCUMENT_T3670001516_H
#define CONFIGURATIONXMLDOCUMENT_T3670001516_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.ConfigurationXmlDocument
struct ConfigurationXmlDocument_t3670001516 : public XmlDocument_t3649534162
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // CONFIGURATIONXMLDOCUMENT_T3670001516_H
#ifndef CONFIGURATIONALLOWEXEDEFINITION_T3860111898_H
#define CONFIGURATIONALLOWEXEDEFINITION_T3860111898_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.ConfigurationAllowExeDefinition
struct ConfigurationAllowExeDefinition_t3860111898
{
public:
// System.Int32 System.Configuration.ConfigurationAllowExeDefinition::value__
int32_t ___value___2;
public:
inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(ConfigurationAllowExeDefinition_t3860111898, ___value___2)); }
inline int32_t get_value___2() const { return ___value___2; }
inline int32_t* get_address_of_value___2() { return &___value___2; }
inline void set_value___2(int32_t value)
{
___value___2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // CONFIGURATIONALLOWEXEDEFINITION_T3860111898_H
#ifndef CONFIGURATIONLOCKTYPE_T131834733_H
#define CONFIGURATIONLOCKTYPE_T131834733_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.ConfigurationLockType
struct ConfigurationLockType_t131834733
{
public:
// System.Int32 System.Configuration.ConfigurationLockType::value__
int32_t ___value___2;
public:
inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(ConfigurationLockType_t131834733, ___value___2)); }
inline int32_t get_value___2() const { return ___value___2; }
inline int32_t* get_address_of_value___2() { return &___value___2; }
inline void set_value___2(int32_t value)
{
___value___2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // CONFIGURATIONLOCKTYPE_T131834733_H
#ifndef CONFIGURATIONELEMENTCOLLECTIONTYPE_T1806001494_H
#define CONFIGURATIONELEMENTCOLLECTIONTYPE_T1806001494_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.ConfigurationElementCollectionType
struct ConfigurationElementCollectionType_t1806001494
{
public:
// System.Int32 System.Configuration.ConfigurationElementCollectionType::value__
int32_t ___value___2;
public:
inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(ConfigurationElementCollectionType_t1806001494, ___value___2)); }
inline int32_t get_value___2() const { return ___value___2; }
inline int32_t* get_address_of_value___2() { return &___value___2; }
inline void set_value___2(int32_t value)
{
___value___2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // CONFIGURATIONELEMENTCOLLECTIONTYPE_T1806001494_H
#ifndef PROTECTEDCONFIGURATIONSECTION_T3541826375_H
#define PROTECTEDCONFIGURATIONSECTION_T3541826375_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.ProtectedConfigurationSection
struct ProtectedConfigurationSection_t3541826375 : public ConfigurationSection_t2600766927
{
public:
// System.Configuration.ProtectedConfigurationProviderCollection System.Configuration.ProtectedConfigurationSection::providers
ProtectedConfigurationProviderCollection_t388338823 * ___providers_22;
public:
inline static int32_t get_offset_of_providers_22() { return static_cast<int32_t>(offsetof(ProtectedConfigurationSection_t3541826375, ___providers_22)); }
inline ProtectedConfigurationProviderCollection_t388338823 * get_providers_22() const { return ___providers_22; }
inline ProtectedConfigurationProviderCollection_t388338823 ** get_address_of_providers_22() { return &___providers_22; }
inline void set_providers_22(ProtectedConfigurationProviderCollection_t388338823 * value)
{
___providers_22 = value;
Il2CppCodeGenWriteBarrier((&___providers_22), value);
}
};
struct ProtectedConfigurationSection_t3541826375_StaticFields
{
public:
// System.Configuration.ConfigurationProperty System.Configuration.ProtectedConfigurationSection::defaultProviderProp
ConfigurationProperty_t2048066811 * ___defaultProviderProp_19;
// System.Configuration.ConfigurationProperty System.Configuration.ProtectedConfigurationSection::providersProp
ConfigurationProperty_t2048066811 * ___providersProp_20;
// System.Configuration.ConfigurationPropertyCollection System.Configuration.ProtectedConfigurationSection::properties
ConfigurationPropertyCollection_t3473514151 * ___properties_21;
public:
inline static int32_t get_offset_of_defaultProviderProp_19() { return static_cast<int32_t>(offsetof(ProtectedConfigurationSection_t3541826375_StaticFields, ___defaultProviderProp_19)); }
inline ConfigurationProperty_t2048066811 * get_defaultProviderProp_19() const { return ___defaultProviderProp_19; }
inline ConfigurationProperty_t2048066811 ** get_address_of_defaultProviderProp_19() { return &___defaultProviderProp_19; }
inline void set_defaultProviderProp_19(ConfigurationProperty_t2048066811 * value)
{
___defaultProviderProp_19 = value;
Il2CppCodeGenWriteBarrier((&___defaultProviderProp_19), value);
}
inline static int32_t get_offset_of_providersProp_20() { return static_cast<int32_t>(offsetof(ProtectedConfigurationSection_t3541826375_StaticFields, ___providersProp_20)); }
inline ConfigurationProperty_t2048066811 * get_providersProp_20() const { return ___providersProp_20; }
inline ConfigurationProperty_t2048066811 ** get_address_of_providersProp_20() { return &___providersProp_20; }
inline void set_providersProp_20(ConfigurationProperty_t2048066811 * value)
{
___providersProp_20 = value;
Il2CppCodeGenWriteBarrier((&___providersProp_20), value);
}
inline static int32_t get_offset_of_properties_21() { return static_cast<int32_t>(offsetof(ProtectedConfigurationSection_t3541826375_StaticFields, ___properties_21)); }
inline ConfigurationPropertyCollection_t3473514151 * get_properties_21() const { return ___properties_21; }
inline ConfigurationPropertyCollection_t3473514151 ** get_address_of_properties_21() { return &___properties_21; }
inline void set_properties_21(ConfigurationPropertyCollection_t3473514151 * value)
{
___properties_21 = value;
Il2CppCodeGenWriteBarrier((&___properties_21), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // PROTECTEDCONFIGURATIONSECTION_T3541826375_H
#ifndef U3CPRIVATEIMPLEMENTATIONDETAILSU3E_T1486305142_H
#define U3CPRIVATEIMPLEMENTATIONDETAILSU3E_T1486305142_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// <PrivateImplementationDetails>
struct U3CPrivateImplementationDetailsU3E_t1486305142 : public RuntimeObject
{
public:
public:
};
struct U3CPrivateImplementationDetailsU3E_t1486305142_StaticFields
{
public:
// <PrivateImplementationDetails>/__StaticArrayInitTypeSize=120 <PrivateImplementationDetails>::0AA802CD6847EB893FE786B5EA5168B2FDCD7B93
__StaticArrayInitTypeSizeU3D120_t1468992141 ___0AA802CD6847EB893FE786B5EA5168B2FDCD7B93_0;
// <PrivateImplementationDetails>/__StaticArrayInitTypeSize=256 <PrivateImplementationDetails>::0C4110BC17D746F018F47B49E0EB0D6590F69939
__StaticArrayInitTypeSizeU3D256_t3653428462 ___0C4110BC17D746F018F47B49E0EB0D6590F69939_1;
// <PrivateImplementationDetails>/__StaticArrayInitTypeSize=1024 <PrivateImplementationDetails>::20733E1283D873EBE47133A95C233E11B76F5F11
__StaticArrayInitTypeSizeU3D1024_t3477315116 ___20733E1283D873EBE47133A95C233E11B76F5F11_2;
// <PrivateImplementationDetails>/__StaticArrayInitTypeSize=1024 <PrivateImplementationDetails>::21F4CBF8283FF1CAEB4A39316A97FC1D6DF1D35E
__StaticArrayInitTypeSizeU3D1024_t3477315116 ___21F4CBF8283FF1CAEB4A39316A97FC1D6DF1D35E_3;
// <PrivateImplementationDetails>/__StaticArrayInitTypeSize=1024 <PrivateImplementationDetails>::23DFDCA6F045D4257BF5AC8CB1CF2EFADAFE9B94
__StaticArrayInitTypeSizeU3D1024_t3477315116 ___23DFDCA6F045D4257BF5AC8CB1CF2EFADAFE9B94_4;
// <PrivateImplementationDetails>/__StaticArrayInitTypeSize=1024 <PrivateImplementationDetails>::30A0358B25B1372DD598BB4B1AC56AD6B8F08A47
__StaticArrayInitTypeSizeU3D1024_t3477315116 ___30A0358B25B1372DD598BB4B1AC56AD6B8F08A47_5;
// <PrivateImplementationDetails>/__StaticArrayInitTypeSize=1024 <PrivateImplementationDetails>::5B5DF5A459E902D96F7DB0FB235A25346CA85C5D
__StaticArrayInitTypeSizeU3D1024_t3477315116 ___5B5DF5A459E902D96F7DB0FB235A25346CA85C5D_6;
// <PrivateImplementationDetails>/__StaticArrayInitTypeSize=1024 <PrivateImplementationDetails>::5BE411F1438EAEF33726D855E99011D5FECDDD4E
__StaticArrayInitTypeSizeU3D1024_t3477315116 ___5BE411F1438EAEF33726D855E99011D5FECDDD4E_7;
// <PrivateImplementationDetails>/__StaticArrayInitTypeSize=256 <PrivateImplementationDetails>::8F22C9ECE1331718CBD268A9BBFD2F5E451441E3
__StaticArrayInitTypeSizeU3D256_t3653428462 ___8F22C9ECE1331718CBD268A9BBFD2F5E451441E3_8;
// <PrivateImplementationDetails>/__StaticArrayInitTypeSize=1024 <PrivateImplementationDetails>::A02DD1D8604EA8EC2D2BDA717A93A4EE85F13E53
__StaticArrayInitTypeSizeU3D1024_t3477315116 ___A02DD1D8604EA8EC2D2BDA717A93A4EE85F13E53_9;
// <PrivateImplementationDetails>/__StaticArrayInitTypeSize=1024 <PrivateImplementationDetails>::AE2F76ECEF8B08F0BC7EA95DCFE945E1727927C9
__StaticArrayInitTypeSizeU3D1024_t3477315116 ___AE2F76ECEF8B08F0BC7EA95DCFE945E1727927C9_10;
public:
inline static int32_t get_offset_of_U30AA802CD6847EB893FE786B5EA5168B2FDCD7B93_0() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t1486305142_StaticFields, ___0AA802CD6847EB893FE786B5EA5168B2FDCD7B93_0)); }
inline __StaticArrayInitTypeSizeU3D120_t1468992141 get_U30AA802CD6847EB893FE786B5EA5168B2FDCD7B93_0() const { return ___0AA802CD6847EB893FE786B5EA5168B2FDCD7B93_0; }
inline __StaticArrayInitTypeSizeU3D120_t1468992141 * get_address_of_U30AA802CD6847EB893FE786B5EA5168B2FDCD7B93_0() { return &___0AA802CD6847EB893FE786B5EA5168B2FDCD7B93_0; }
inline void set_U30AA802CD6847EB893FE786B5EA5168B2FDCD7B93_0(__StaticArrayInitTypeSizeU3D120_t1468992141 value)
{
___0AA802CD6847EB893FE786B5EA5168B2FDCD7B93_0 = value;
}
inline static int32_t get_offset_of_U30C4110BC17D746F018F47B49E0EB0D6590F69939_1() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t1486305142_StaticFields, ___0C4110BC17D746F018F47B49E0EB0D6590F69939_1)); }
inline __StaticArrayInitTypeSizeU3D256_t3653428462 get_U30C4110BC17D746F018F47B49E0EB0D6590F69939_1() const { return ___0C4110BC17D746F018F47B49E0EB0D6590F69939_1; }
inline __StaticArrayInitTypeSizeU3D256_t3653428462 * get_address_of_U30C4110BC17D746F018F47B49E0EB0D6590F69939_1() { return &___0C4110BC17D746F018F47B49E0EB0D6590F69939_1; }
inline void set_U30C4110BC17D746F018F47B49E0EB0D6590F69939_1(__StaticArrayInitTypeSizeU3D256_t3653428462 value)
{
___0C4110BC17D746F018F47B49E0EB0D6590F69939_1 = value;
}
inline static int32_t get_offset_of_U320733E1283D873EBE47133A95C233E11B76F5F11_2() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t1486305142_StaticFields, ___20733E1283D873EBE47133A95C233E11B76F5F11_2)); }
inline __StaticArrayInitTypeSizeU3D1024_t3477315116 get_U320733E1283D873EBE47133A95C233E11B76F5F11_2() const { return ___20733E1283D873EBE47133A95C233E11B76F5F11_2; }
inline __StaticArrayInitTypeSizeU3D1024_t3477315116 * get_address_of_U320733E1283D873EBE47133A95C233E11B76F5F11_2() { return &___20733E1283D873EBE47133A95C233E11B76F5F11_2; }
inline void set_U320733E1283D873EBE47133A95C233E11B76F5F11_2(__StaticArrayInitTypeSizeU3D1024_t3477315116 value)
{
___20733E1283D873EBE47133A95C233E11B76F5F11_2 = value;
}
inline static int32_t get_offset_of_U321F4CBF8283FF1CAEB4A39316A97FC1D6DF1D35E_3() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t1486305142_StaticFields, ___21F4CBF8283FF1CAEB4A39316A97FC1D6DF1D35E_3)); }
inline __StaticArrayInitTypeSizeU3D1024_t3477315116 get_U321F4CBF8283FF1CAEB4A39316A97FC1D6DF1D35E_3() const { return ___21F4CBF8283FF1CAEB4A39316A97FC1D6DF1D35E_3; }
inline __StaticArrayInitTypeSizeU3D1024_t3477315116 * get_address_of_U321F4CBF8283FF1CAEB4A39316A97FC1D6DF1D35E_3() { return &___21F4CBF8283FF1CAEB4A39316A97FC1D6DF1D35E_3; }
inline void set_U321F4CBF8283FF1CAEB4A39316A97FC1D6DF1D35E_3(__StaticArrayInitTypeSizeU3D1024_t3477315116 value)
{
___21F4CBF8283FF1CAEB4A39316A97FC1D6DF1D35E_3 = value;
}
inline static int32_t get_offset_of_U323DFDCA6F045D4257BF5AC8CB1CF2EFADAFE9B94_4() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t1486305142_StaticFields, ___23DFDCA6F045D4257BF5AC8CB1CF2EFADAFE9B94_4)); }
inline __StaticArrayInitTypeSizeU3D1024_t3477315116 get_U323DFDCA6F045D4257BF5AC8CB1CF2EFADAFE9B94_4() const { return ___23DFDCA6F045D4257BF5AC8CB1CF2EFADAFE9B94_4; }
inline __StaticArrayInitTypeSizeU3D1024_t3477315116 * get_address_of_U323DFDCA6F045D4257BF5AC8CB1CF2EFADAFE9B94_4() { return &___23DFDCA6F045D4257BF5AC8CB1CF2EFADAFE9B94_4; }
inline void set_U323DFDCA6F045D4257BF5AC8CB1CF2EFADAFE9B94_4(__StaticArrayInitTypeSizeU3D1024_t3477315116 value)
{
___23DFDCA6F045D4257BF5AC8CB1CF2EFADAFE9B94_4 = value;
}
inline static int32_t get_offset_of_U330A0358B25B1372DD598BB4B1AC56AD6B8F08A47_5() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t1486305142_StaticFields, ___30A0358B25B1372DD598BB4B1AC56AD6B8F08A47_5)); }
inline __StaticArrayInitTypeSizeU3D1024_t3477315116 get_U330A0358B25B1372DD598BB4B1AC56AD6B8F08A47_5() const { return ___30A0358B25B1372DD598BB4B1AC56AD6B8F08A47_5; }
inline __StaticArrayInitTypeSizeU3D1024_t3477315116 * get_address_of_U330A0358B25B1372DD598BB4B1AC56AD6B8F08A47_5() { return &___30A0358B25B1372DD598BB4B1AC56AD6B8F08A47_5; }
inline void set_U330A0358B25B1372DD598BB4B1AC56AD6B8F08A47_5(__StaticArrayInitTypeSizeU3D1024_t3477315116 value)
{
___30A0358B25B1372DD598BB4B1AC56AD6B8F08A47_5 = value;
}
inline static int32_t get_offset_of_U35B5DF5A459E902D96F7DB0FB235A25346CA85C5D_6() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t1486305142_StaticFields, ___5B5DF5A459E902D96F7DB0FB235A25346CA85C5D_6)); }
inline __StaticArrayInitTypeSizeU3D1024_t3477315116 get_U35B5DF5A459E902D96F7DB0FB235A25346CA85C5D_6() const { return ___5B5DF5A459E902D96F7DB0FB235A25346CA85C5D_6; }
inline __StaticArrayInitTypeSizeU3D1024_t3477315116 * get_address_of_U35B5DF5A459E902D96F7DB0FB235A25346CA85C5D_6() { return &___5B5DF5A459E902D96F7DB0FB235A25346CA85C5D_6; }
inline void set_U35B5DF5A459E902D96F7DB0FB235A25346CA85C5D_6(__StaticArrayInitTypeSizeU3D1024_t3477315116 value)
{
___5B5DF5A459E902D96F7DB0FB235A25346CA85C5D_6 = value;
}
inline static int32_t get_offset_of_U35BE411F1438EAEF33726D855E99011D5FECDDD4E_7() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t1486305142_StaticFields, ___5BE411F1438EAEF33726D855E99011D5FECDDD4E_7)); }
inline __StaticArrayInitTypeSizeU3D1024_t3477315116 get_U35BE411F1438EAEF33726D855E99011D5FECDDD4E_7() const { return ___5BE411F1438EAEF33726D855E99011D5FECDDD4E_7; }
inline __StaticArrayInitTypeSizeU3D1024_t3477315116 * get_address_of_U35BE411F1438EAEF33726D855E99011D5FECDDD4E_7() { return &___5BE411F1438EAEF33726D855E99011D5FECDDD4E_7; }
inline void set_U35BE411F1438EAEF33726D855E99011D5FECDDD4E_7(__StaticArrayInitTypeSizeU3D1024_t3477315116 value)
{
___5BE411F1438EAEF33726D855E99011D5FECDDD4E_7 = value;
}
inline static int32_t get_offset_of_U38F22C9ECE1331718CBD268A9BBFD2F5E451441E3_8() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t1486305142_StaticFields, ___8F22C9ECE1331718CBD268A9BBFD2F5E451441E3_8)); }
inline __StaticArrayInitTypeSizeU3D256_t3653428462 get_U38F22C9ECE1331718CBD268A9BBFD2F5E451441E3_8() const { return ___8F22C9ECE1331718CBD268A9BBFD2F5E451441E3_8; }
inline __StaticArrayInitTypeSizeU3D256_t3653428462 * get_address_of_U38F22C9ECE1331718CBD268A9BBFD2F5E451441E3_8() { return &___8F22C9ECE1331718CBD268A9BBFD2F5E451441E3_8; }
inline void set_U38F22C9ECE1331718CBD268A9BBFD2F5E451441E3_8(__StaticArrayInitTypeSizeU3D256_t3653428462 value)
{
___8F22C9ECE1331718CBD268A9BBFD2F5E451441E3_8 = value;
}
inline static int32_t get_offset_of_A02DD1D8604EA8EC2D2BDA717A93A4EE85F13E53_9() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t1486305142_StaticFields, ___A02DD1D8604EA8EC2D2BDA717A93A4EE85F13E53_9)); }
inline __StaticArrayInitTypeSizeU3D1024_t3477315116 get_A02DD1D8604EA8EC2D2BDA717A93A4EE85F13E53_9() const { return ___A02DD1D8604EA8EC2D2BDA717A93A4EE85F13E53_9; }
inline __StaticArrayInitTypeSizeU3D1024_t3477315116 * get_address_of_A02DD1D8604EA8EC2D2BDA717A93A4EE85F13E53_9() { return &___A02DD1D8604EA8EC2D2BDA717A93A4EE85F13E53_9; }
inline void set_A02DD1D8604EA8EC2D2BDA717A93A4EE85F13E53_9(__StaticArrayInitTypeSizeU3D1024_t3477315116 value)
{
___A02DD1D8604EA8EC2D2BDA717A93A4EE85F13E53_9 = value;
}
inline static int32_t get_offset_of_AE2F76ECEF8B08F0BC7EA95DCFE945E1727927C9_10() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t1486305142_StaticFields, ___AE2F76ECEF8B08F0BC7EA95DCFE945E1727927C9_10)); }
inline __StaticArrayInitTypeSizeU3D1024_t3477315116 get_AE2F76ECEF8B08F0BC7EA95DCFE945E1727927C9_10() const { return ___AE2F76ECEF8B08F0BC7EA95DCFE945E1727927C9_10; }
inline __StaticArrayInitTypeSizeU3D1024_t3477315116 * get_address_of_AE2F76ECEF8B08F0BC7EA95DCFE945E1727927C9_10() { return &___AE2F76ECEF8B08F0BC7EA95DCFE945E1727927C9_10; }
inline void set_AE2F76ECEF8B08F0BC7EA95DCFE945E1727927C9_10(__StaticArrayInitTypeSizeU3D1024_t3477315116 value)
{
___AE2F76ECEF8B08F0BC7EA95DCFE945E1727927C9_10 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // U3CPRIVATEIMPLEMENTATIONDETAILSU3E_T1486305142_H
#ifndef CIPHERMODE_T162592484_H
#define CIPHERMODE_T162592484_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.CipherMode
struct CipherMode_t162592484
{
public:
// System.Int32 System.Security.Cryptography.CipherMode::value__
int32_t ___value___2;
public:
inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(CipherMode_t162592484, ___value___2)); }
inline int32_t get_value___2() const { return ___value___2; }
inline int32_t* get_address_of_value___2() { return &___value___2; }
inline void set_value___2(int32_t value)
{
___value___2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // CIPHERMODE_T162592484_H
#ifndef PROVIDERSETTINGSCOLLECTION_T585304908_H
#define PROVIDERSETTINGSCOLLECTION_T585304908_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.ProviderSettingsCollection
struct ProviderSettingsCollection_t585304908 : public ConfigurationElementCollection_t1911180302
{
public:
public:
};
struct ProviderSettingsCollection_t585304908_StaticFields
{
public:
// System.Configuration.ConfigurationPropertyCollection System.Configuration.ProviderSettingsCollection::props
ConfigurationPropertyCollection_t3473514151 * ___props_25;
public:
inline static int32_t get_offset_of_props_25() { return static_cast<int32_t>(offsetof(ProviderSettingsCollection_t585304908_StaticFields, ___props_25)); }
inline ConfigurationPropertyCollection_t3473514151 * get_props_25() const { return ___props_25; }
inline ConfigurationPropertyCollection_t3473514151 ** get_address_of_props_25() { return &___props_25; }
inline void set_props_25(ConfigurationPropertyCollection_t3473514151 * value)
{
___props_25 = value;
Il2CppCodeGenWriteBarrier((&___props_25), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // PROVIDERSETTINGSCOLLECTION_T585304908_H
#ifndef SECTIONINFORMATION_T2754609709_H
#define SECTIONINFORMATION_T2754609709_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.SectionInformation
struct SectionInformation_t2754609709 : public RuntimeObject
{
public:
// System.Configuration.ConfigurationSection System.Configuration.SectionInformation::parent
ConfigurationSection_t2600766927 * ___parent_0;
// System.Configuration.ConfigurationAllowDefinition System.Configuration.SectionInformation::allow_definition
int32_t ___allow_definition_1;
// System.Configuration.ConfigurationAllowExeDefinition System.Configuration.SectionInformation::allow_exe_definition
int32_t ___allow_exe_definition_2;
// System.Boolean System.Configuration.SectionInformation::allow_location
bool ___allow_location_3;
// System.Boolean System.Configuration.SectionInformation::allow_override
bool ___allow_override_4;
// System.Boolean System.Configuration.SectionInformation::inherit_on_child_apps
bool ___inherit_on_child_apps_5;
// System.Boolean System.Configuration.SectionInformation::restart_on_external_changes
bool ___restart_on_external_changes_6;
// System.Boolean System.Configuration.SectionInformation::require_permission
bool ___require_permission_7;
// System.String System.Configuration.SectionInformation::config_source
String_t* ___config_source_8;
// System.String System.Configuration.SectionInformation::name
String_t* ___name_9;
// System.String System.Configuration.SectionInformation::raw_xml
String_t* ___raw_xml_10;
// System.Configuration.ProtectedConfigurationProvider System.Configuration.SectionInformation::protection_provider
ProtectedConfigurationProvider_t3971982415 * ___protection_provider_11;
// System.String System.Configuration.SectionInformation::<ConfigFilePath>k__BackingField
String_t* ___U3CConfigFilePathU3Ek__BackingField_12;
public:
inline static int32_t get_offset_of_parent_0() { return static_cast<int32_t>(offsetof(SectionInformation_t2754609709, ___parent_0)); }
inline ConfigurationSection_t2600766927 * get_parent_0() const { return ___parent_0; }
inline ConfigurationSection_t2600766927 ** get_address_of_parent_0() { return &___parent_0; }
inline void set_parent_0(ConfigurationSection_t2600766927 * value)
{
___parent_0 = value;
Il2CppCodeGenWriteBarrier((&___parent_0), value);
}
inline static int32_t get_offset_of_allow_definition_1() { return static_cast<int32_t>(offsetof(SectionInformation_t2754609709, ___allow_definition_1)); }
inline int32_t get_allow_definition_1() const { return ___allow_definition_1; }
inline int32_t* get_address_of_allow_definition_1() { return &___allow_definition_1; }
inline void set_allow_definition_1(int32_t value)
{
___allow_definition_1 = value;
}
inline static int32_t get_offset_of_allow_exe_definition_2() { return static_cast<int32_t>(offsetof(SectionInformation_t2754609709, ___allow_exe_definition_2)); }
inline int32_t get_allow_exe_definition_2() const { return ___allow_exe_definition_2; }
inline int32_t* get_address_of_allow_exe_definition_2() { return &___allow_exe_definition_2; }
inline void set_allow_exe_definition_2(int32_t value)
{
___allow_exe_definition_2 = value;
}
inline static int32_t get_offset_of_allow_location_3() { return static_cast<int32_t>(offsetof(SectionInformation_t2754609709, ___allow_location_3)); }
inline bool get_allow_location_3() const { return ___allow_location_3; }
inline bool* get_address_of_allow_location_3() { return &___allow_location_3; }
inline void set_allow_location_3(bool value)
{
___allow_location_3 = value;
}
inline static int32_t get_offset_of_allow_override_4() { return static_cast<int32_t>(offsetof(SectionInformation_t2754609709, ___allow_override_4)); }
inline bool get_allow_override_4() const { return ___allow_override_4; }
inline bool* get_address_of_allow_override_4() { return &___allow_override_4; }
inline void set_allow_override_4(bool value)
{
___allow_override_4 = value;
}
inline static int32_t get_offset_of_inherit_on_child_apps_5() { return static_cast<int32_t>(offsetof(SectionInformation_t2754609709, ___inherit_on_child_apps_5)); }
inline bool get_inherit_on_child_apps_5() const { return ___inherit_on_child_apps_5; }
inline bool* get_address_of_inherit_on_child_apps_5() { return &___inherit_on_child_apps_5; }
inline void set_inherit_on_child_apps_5(bool value)
{
___inherit_on_child_apps_5 = value;
}
inline static int32_t get_offset_of_restart_on_external_changes_6() { return static_cast<int32_t>(offsetof(SectionInformation_t2754609709, ___restart_on_external_changes_6)); }
inline bool get_restart_on_external_changes_6() const { return ___restart_on_external_changes_6; }
inline bool* get_address_of_restart_on_external_changes_6() { return &___restart_on_external_changes_6; }
inline void set_restart_on_external_changes_6(bool value)
{
___restart_on_external_changes_6 = value;
}
inline static int32_t get_offset_of_require_permission_7() { return static_cast<int32_t>(offsetof(SectionInformation_t2754609709, ___require_permission_7)); }
inline bool get_require_permission_7() const { return ___require_permission_7; }
inline bool* get_address_of_require_permission_7() { return &___require_permission_7; }
inline void set_require_permission_7(bool value)
{
___require_permission_7 = value;
}
inline static int32_t get_offset_of_config_source_8() { return static_cast<int32_t>(offsetof(SectionInformation_t2754609709, ___config_source_8)); }
inline String_t* get_config_source_8() const { return ___config_source_8; }
inline String_t** get_address_of_config_source_8() { return &___config_source_8; }
inline void set_config_source_8(String_t* value)
{
___config_source_8 = value;
Il2CppCodeGenWriteBarrier((&___config_source_8), value);
}
inline static int32_t get_offset_of_name_9() { return static_cast<int32_t>(offsetof(SectionInformation_t2754609709, ___name_9)); }
inline String_t* get_name_9() const { return ___name_9; }
inline String_t** get_address_of_name_9() { return &___name_9; }
inline void set_name_9(String_t* value)
{
___name_9 = value;
Il2CppCodeGenWriteBarrier((&___name_9), value);
}
inline static int32_t get_offset_of_raw_xml_10() { return static_cast<int32_t>(offsetof(SectionInformation_t2754609709, ___raw_xml_10)); }
inline String_t* get_raw_xml_10() const { return ___raw_xml_10; }
inline String_t** get_address_of_raw_xml_10() { return &___raw_xml_10; }
inline void set_raw_xml_10(String_t* value)
{
___raw_xml_10 = value;
Il2CppCodeGenWriteBarrier((&___raw_xml_10), value);
}
inline static int32_t get_offset_of_protection_provider_11() { return static_cast<int32_t>(offsetof(SectionInformation_t2754609709, ___protection_provider_11)); }
inline ProtectedConfigurationProvider_t3971982415 * get_protection_provider_11() const { return ___protection_provider_11; }
inline ProtectedConfigurationProvider_t3971982415 ** get_address_of_protection_provider_11() { return &___protection_provider_11; }
inline void set_protection_provider_11(ProtectedConfigurationProvider_t3971982415 * value)
{
___protection_provider_11 = value;
Il2CppCodeGenWriteBarrier((&___protection_provider_11), value);
}
inline static int32_t get_offset_of_U3CConfigFilePathU3Ek__BackingField_12() { return static_cast<int32_t>(offsetof(SectionInformation_t2754609709, ___U3CConfigFilePathU3Ek__BackingField_12)); }
inline String_t* get_U3CConfigFilePathU3Ek__BackingField_12() const { return ___U3CConfigFilePathU3Ek__BackingField_12; }
inline String_t** get_address_of_U3CConfigFilePathU3Ek__BackingField_12() { return &___U3CConfigFilePathU3Ek__BackingField_12; }
inline void set_U3CConfigFilePathU3Ek__BackingField_12(String_t* value)
{
___U3CConfigFilePathU3Ek__BackingField_12 = value;
Il2CppCodeGenWriteBarrier((&___U3CConfigFilePathU3Ek__BackingField_12), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // SECTIONINFORMATION_T2754609709_H
#ifndef CONFIGURATIONERRORSEXCEPTION_T1362721126_H
#define CONFIGURATIONERRORSEXCEPTION_T1362721126_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.ConfigurationErrorsException
struct ConfigurationErrorsException_t1362721126 : public ConfigurationException_t3814184945
{
public:
// System.String System.Configuration.ConfigurationErrorsException::filename
String_t* ___filename_18;
// System.Int32 System.Configuration.ConfigurationErrorsException::line
int32_t ___line_19;
public:
inline static int32_t get_offset_of_filename_18() { return static_cast<int32_t>(offsetof(ConfigurationErrorsException_t1362721126, ___filename_18)); }
inline String_t* get_filename_18() const { return ___filename_18; }
inline String_t** get_address_of_filename_18() { return &___filename_18; }
inline void set_filename_18(String_t* value)
{
___filename_18 = value;
Il2CppCodeGenWriteBarrier((&___filename_18), value);
}
inline static int32_t get_offset_of_line_19() { return static_cast<int32_t>(offsetof(ConfigurationErrorsException_t1362721126, ___line_19)); }
inline int32_t get_line_19() const { return ___line_19; }
inline int32_t* get_address_of_line_19() { return &___line_19; }
inline void set_line_19(int32_t value)
{
___line_19 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // CONFIGURATIONERRORSEXCEPTION_T1362721126_H
#ifndef MULTICASTDELEGATE_T3201952435_H
#define MULTICASTDELEGATE_T3201952435_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.MulticastDelegate
struct MulticastDelegate_t3201952435 : public Delegate_t3022476291
{
public:
// System.Delegate[] System.MulticastDelegate::delegates
DelegateU5BU5D_t1606206610* ___delegates_11;
public:
inline static int32_t get_offset_of_delegates_11() { return static_cast<int32_t>(offsetof(MulticastDelegate_t3201952435, ___delegates_11)); }
inline DelegateU5BU5D_t1606206610* get_delegates_11() const { return ___delegates_11; }
inline DelegateU5BU5D_t1606206610** get_address_of_delegates_11() { return &___delegates_11; }
inline void set_delegates_11(DelegateU5BU5D_t1606206610* value)
{
___delegates_11 = value;
Il2CppCodeGenWriteBarrier((&___delegates_11), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of System.MulticastDelegate
struct MulticastDelegate_t3201952435_marshaled_pinvoke : public Delegate_t3022476291_marshaled_pinvoke
{
DelegateU5BU5D_t1606206610* ___delegates_11;
};
// Native definition for COM marshalling of System.MulticastDelegate
struct MulticastDelegate_t3201952435_marshaled_com : public Delegate_t3022476291_marshaled_com
{
DelegateU5BU5D_t1606206610* ___delegates_11;
};
#endif // MULTICASTDELEGATE_T3201952435_H
#ifndef CONFIGURATIONLOCKCOLLECTION_T1011762925_H
#define CONFIGURATIONLOCKCOLLECTION_T1011762925_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.ConfigurationLockCollection
struct ConfigurationLockCollection_t1011762925 : public RuntimeObject
{
public:
// System.Collections.ArrayList System.Configuration.ConfigurationLockCollection::names
ArrayList_t4252133567 * ___names_0;
// System.Configuration.ConfigurationElement System.Configuration.ConfigurationLockCollection::element
ConfigurationElement_t1776195828 * ___element_1;
// System.Configuration.ConfigurationLockType System.Configuration.ConfigurationLockCollection::lockType
int32_t ___lockType_2;
// System.Boolean System.Configuration.ConfigurationLockCollection::is_modified
bool ___is_modified_3;
// System.Collections.Hashtable System.Configuration.ConfigurationLockCollection::valid_name_hash
Hashtable_t909839986 * ___valid_name_hash_4;
// System.String System.Configuration.ConfigurationLockCollection::valid_names
String_t* ___valid_names_5;
public:
inline static int32_t get_offset_of_names_0() { return static_cast<int32_t>(offsetof(ConfigurationLockCollection_t1011762925, ___names_0)); }
inline ArrayList_t4252133567 * get_names_0() const { return ___names_0; }
inline ArrayList_t4252133567 ** get_address_of_names_0() { return &___names_0; }
inline void set_names_0(ArrayList_t4252133567 * value)
{
___names_0 = value;
Il2CppCodeGenWriteBarrier((&___names_0), value);
}
inline static int32_t get_offset_of_element_1() { return static_cast<int32_t>(offsetof(ConfigurationLockCollection_t1011762925, ___element_1)); }
inline ConfigurationElement_t1776195828 * get_element_1() const { return ___element_1; }
inline ConfigurationElement_t1776195828 ** get_address_of_element_1() { return &___element_1; }
inline void set_element_1(ConfigurationElement_t1776195828 * value)
{
___element_1 = value;
Il2CppCodeGenWriteBarrier((&___element_1), value);
}
inline static int32_t get_offset_of_lockType_2() { return static_cast<int32_t>(offsetof(ConfigurationLockCollection_t1011762925, ___lockType_2)); }
inline int32_t get_lockType_2() const { return ___lockType_2; }
inline int32_t* get_address_of_lockType_2() { return &___lockType_2; }
inline void set_lockType_2(int32_t value)
{
___lockType_2 = value;
}
inline static int32_t get_offset_of_is_modified_3() { return static_cast<int32_t>(offsetof(ConfigurationLockCollection_t1011762925, ___is_modified_3)); }
inline bool get_is_modified_3() const { return ___is_modified_3; }
inline bool* get_address_of_is_modified_3() { return &___is_modified_3; }
inline void set_is_modified_3(bool value)
{
___is_modified_3 = value;
}
inline static int32_t get_offset_of_valid_name_hash_4() { return static_cast<int32_t>(offsetof(ConfigurationLockCollection_t1011762925, ___valid_name_hash_4)); }
inline Hashtable_t909839986 * get_valid_name_hash_4() const { return ___valid_name_hash_4; }
inline Hashtable_t909839986 ** get_address_of_valid_name_hash_4() { return &___valid_name_hash_4; }
inline void set_valid_name_hash_4(Hashtable_t909839986 * value)
{
___valid_name_hash_4 = value;
Il2CppCodeGenWriteBarrier((&___valid_name_hash_4), value);
}
inline static int32_t get_offset_of_valid_names_5() { return static_cast<int32_t>(offsetof(ConfigurationLockCollection_t1011762925, ___valid_names_5)); }
inline String_t* get_valid_names_5() const { return ___valid_names_5; }
inline String_t** get_address_of_valid_names_5() { return &___valid_names_5; }
inline void set_valid_names_5(String_t* value)
{
___valid_names_5 = value;
Il2CppCodeGenWriteBarrier((&___valid_names_5), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // CONFIGURATIONLOCKCOLLECTION_T1011762925_H
#ifndef SAVECONTEXT_T3996373180_H
#define SAVECONTEXT_T3996373180_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.ConfigurationElement/SaveContext
struct SaveContext_t3996373180 : public RuntimeObject
{
public:
// System.Configuration.ConfigurationElement System.Configuration.ConfigurationElement/SaveContext::Element
ConfigurationElement_t1776195828 * ___Element_0;
// System.Configuration.ConfigurationElement System.Configuration.ConfigurationElement/SaveContext::Parent
ConfigurationElement_t1776195828 * ___Parent_1;
// System.Configuration.ConfigurationSaveMode System.Configuration.ConfigurationElement/SaveContext::Mode
int32_t ___Mode_2;
public:
inline static int32_t get_offset_of_Element_0() { return static_cast<int32_t>(offsetof(SaveContext_t3996373180, ___Element_0)); }
inline ConfigurationElement_t1776195828 * get_Element_0() const { return ___Element_0; }
inline ConfigurationElement_t1776195828 ** get_address_of_Element_0() { return &___Element_0; }
inline void set_Element_0(ConfigurationElement_t1776195828 * value)
{
___Element_0 = value;
Il2CppCodeGenWriteBarrier((&___Element_0), value);
}
inline static int32_t get_offset_of_Parent_1() { return static_cast<int32_t>(offsetof(SaveContext_t3996373180, ___Parent_1)); }
inline ConfigurationElement_t1776195828 * get_Parent_1() const { return ___Parent_1; }
inline ConfigurationElement_t1776195828 ** get_address_of_Parent_1() { return &___Parent_1; }
inline void set_Parent_1(ConfigurationElement_t1776195828 * value)
{
___Parent_1 = value;
Il2CppCodeGenWriteBarrier((&___Parent_1), value);
}
inline static int32_t get_offset_of_Mode_2() { return static_cast<int32_t>(offsetof(SaveContext_t3996373180, ___Mode_2)); }
inline int32_t get_Mode_2() const { return ___Mode_2; }
inline int32_t* get_address_of_Mode_2() { return &___Mode_2; }
inline void set_Mode_2(int32_t value)
{
___Mode_2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // SAVECONTEXT_T3996373180_H
#ifndef CONFIGURATIONCOLLECTIONATTRIBUTE_T2811353736_H
#define CONFIGURATIONCOLLECTIONATTRIBUTE_T2811353736_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.ConfigurationCollectionAttribute
struct ConfigurationCollectionAttribute_t2811353736 : public Attribute_t542643598
{
public:
// System.String System.Configuration.ConfigurationCollectionAttribute::addItemName
String_t* ___addItemName_0;
// System.String System.Configuration.ConfigurationCollectionAttribute::clearItemsName
String_t* ___clearItemsName_1;
// System.String System.Configuration.ConfigurationCollectionAttribute::removeItemName
String_t* ___removeItemName_2;
// System.Configuration.ConfigurationElementCollectionType System.Configuration.ConfigurationCollectionAttribute::collectionType
int32_t ___collectionType_3;
// System.Type System.Configuration.ConfigurationCollectionAttribute::itemType
Type_t * ___itemType_4;
public:
inline static int32_t get_offset_of_addItemName_0() { return static_cast<int32_t>(offsetof(ConfigurationCollectionAttribute_t2811353736, ___addItemName_0)); }
inline String_t* get_addItemName_0() const { return ___addItemName_0; }
inline String_t** get_address_of_addItemName_0() { return &___addItemName_0; }
inline void set_addItemName_0(String_t* value)
{
___addItemName_0 = value;
Il2CppCodeGenWriteBarrier((&___addItemName_0), value);
}
inline static int32_t get_offset_of_clearItemsName_1() { return static_cast<int32_t>(offsetof(ConfigurationCollectionAttribute_t2811353736, ___clearItemsName_1)); }
inline String_t* get_clearItemsName_1() const { return ___clearItemsName_1; }
inline String_t** get_address_of_clearItemsName_1() { return &___clearItemsName_1; }
inline void set_clearItemsName_1(String_t* value)
{
___clearItemsName_1 = value;
Il2CppCodeGenWriteBarrier((&___clearItemsName_1), value);
}
inline static int32_t get_offset_of_removeItemName_2() { return static_cast<int32_t>(offsetof(ConfigurationCollectionAttribute_t2811353736, ___removeItemName_2)); }
inline String_t* get_removeItemName_2() const { return ___removeItemName_2; }
inline String_t** get_address_of_removeItemName_2() { return &___removeItemName_2; }
inline void set_removeItemName_2(String_t* value)
{
___removeItemName_2 = value;
Il2CppCodeGenWriteBarrier((&___removeItemName_2), value);
}
inline static int32_t get_offset_of_collectionType_3() { return static_cast<int32_t>(offsetof(ConfigurationCollectionAttribute_t2811353736, ___collectionType_3)); }
inline int32_t get_collectionType_3() const { return ___collectionType_3; }
inline int32_t* get_address_of_collectionType_3() { return &___collectionType_3; }
inline void set_collectionType_3(int32_t value)
{
___collectionType_3 = value;
}
inline static int32_t get_offset_of_itemType_4() { return static_cast<int32_t>(offsetof(ConfigurationCollectionAttribute_t2811353736, ___itemType_4)); }
inline Type_t * get_itemType_4() const { return ___itemType_4; }
inline Type_t ** get_address_of_itemType_4() { return &___itemType_4; }
inline void set_itemType_4(Type_t * value)
{
___itemType_4 = value;
Il2CppCodeGenWriteBarrier((&___itemType_4), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // CONFIGURATIONCOLLECTIONATTRIBUTE_T2811353736_H
#ifndef SECTIONINFO_T1739019515_H
#define SECTIONINFO_T1739019515_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.SectionInfo
struct SectionInfo_t1739019515 : public ConfigInfo_t546730838
{
public:
// System.Boolean System.Configuration.SectionInfo::allowLocation
bool ___allowLocation_6;
// System.Boolean System.Configuration.SectionInfo::requirePermission
bool ___requirePermission_7;
// System.Boolean System.Configuration.SectionInfo::restartOnExternalChanges
bool ___restartOnExternalChanges_8;
// System.Configuration.ConfigurationAllowDefinition System.Configuration.SectionInfo::allowDefinition
int32_t ___allowDefinition_9;
// System.Configuration.ConfigurationAllowExeDefinition System.Configuration.SectionInfo::allowExeDefinition
int32_t ___allowExeDefinition_10;
public:
inline static int32_t get_offset_of_allowLocation_6() { return static_cast<int32_t>(offsetof(SectionInfo_t1739019515, ___allowLocation_6)); }
inline bool get_allowLocation_6() const { return ___allowLocation_6; }
inline bool* get_address_of_allowLocation_6() { return &___allowLocation_6; }
inline void set_allowLocation_6(bool value)
{
___allowLocation_6 = value;
}
inline static int32_t get_offset_of_requirePermission_7() { return static_cast<int32_t>(offsetof(SectionInfo_t1739019515, ___requirePermission_7)); }
inline bool get_requirePermission_7() const { return ___requirePermission_7; }
inline bool* get_address_of_requirePermission_7() { return &___requirePermission_7; }
inline void set_requirePermission_7(bool value)
{
___requirePermission_7 = value;
}
inline static int32_t get_offset_of_restartOnExternalChanges_8() { return static_cast<int32_t>(offsetof(SectionInfo_t1739019515, ___restartOnExternalChanges_8)); }
inline bool get_restartOnExternalChanges_8() const { return ___restartOnExternalChanges_8; }
inline bool* get_address_of_restartOnExternalChanges_8() { return &___restartOnExternalChanges_8; }
inline void set_restartOnExternalChanges_8(bool value)
{
___restartOnExternalChanges_8 = value;
}
inline static int32_t get_offset_of_allowDefinition_9() { return static_cast<int32_t>(offsetof(SectionInfo_t1739019515, ___allowDefinition_9)); }
inline int32_t get_allowDefinition_9() const { return ___allowDefinition_9; }
inline int32_t* get_address_of_allowDefinition_9() { return &___allowDefinition_9; }
inline void set_allowDefinition_9(int32_t value)
{
___allowDefinition_9 = value;
}
inline static int32_t get_offset_of_allowExeDefinition_10() { return static_cast<int32_t>(offsetof(SectionInfo_t1739019515, ___allowExeDefinition_10)); }
inline int32_t get_allowExeDefinition_10() const { return ___allowExeDefinition_10; }
inline int32_t* get_address_of_allowExeDefinition_10() { return &___allowExeDefinition_10; }
inline void set_allowExeDefinition_10(int32_t value)
{
___allowExeDefinition_10 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // SECTIONINFO_T1739019515_H
#ifndef SECURITYATTRIBUTE_T2016950496_H
#define SECURITYATTRIBUTE_T2016950496_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Permissions.SecurityAttribute
struct SecurityAttribute_t2016950496 : public Attribute_t542643598
{
public:
// System.Security.Permissions.SecurityAction System.Security.Permissions.SecurityAttribute::m_Action
int32_t ___m_Action_0;
// System.Boolean System.Security.Permissions.SecurityAttribute::m_Unrestricted
bool ___m_Unrestricted_1;
public:
inline static int32_t get_offset_of_m_Action_0() { return static_cast<int32_t>(offsetof(SecurityAttribute_t2016950496, ___m_Action_0)); }
inline int32_t get_m_Action_0() const { return ___m_Action_0; }
inline int32_t* get_address_of_m_Action_0() { return &___m_Action_0; }
inline void set_m_Action_0(int32_t value)
{
___m_Action_0 = value;
}
inline static int32_t get_offset_of_m_Unrestricted_1() { return static_cast<int32_t>(offsetof(SecurityAttribute_t2016950496, ___m_Unrestricted_1)); }
inline bool get_m_Unrestricted_1() const { return ___m_Unrestricted_1; }
inline bool* get_address_of_m_Unrestricted_1() { return &___m_Unrestricted_1; }
inline void set_m_Unrestricted_1(bool value)
{
___m_Unrestricted_1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // SECURITYATTRIBUTE_T2016950496_H
#ifndef SYMMETRICALGORITHM_T1108166522_H
#define SYMMETRICALGORITHM_T1108166522_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.SymmetricAlgorithm
struct SymmetricAlgorithm_t1108166522 : public RuntimeObject
{
public:
// System.Int32 System.Security.Cryptography.SymmetricAlgorithm::BlockSizeValue
int32_t ___BlockSizeValue_0;
// System.Int32 System.Security.Cryptography.SymmetricAlgorithm::FeedbackSizeValue
int32_t ___FeedbackSizeValue_1;
// System.Byte[] System.Security.Cryptography.SymmetricAlgorithm::IVValue
ByteU5BU5D_t3397334013* ___IVValue_2;
// System.Byte[] System.Security.Cryptography.SymmetricAlgorithm::KeyValue
ByteU5BU5D_t3397334013* ___KeyValue_3;
// System.Security.Cryptography.KeySizes[] System.Security.Cryptography.SymmetricAlgorithm::LegalBlockSizesValue
KeySizesU5BU5D_t1153004758* ___LegalBlockSizesValue_4;
// System.Security.Cryptography.KeySizes[] System.Security.Cryptography.SymmetricAlgorithm::LegalKeySizesValue
KeySizesU5BU5D_t1153004758* ___LegalKeySizesValue_5;
// System.Int32 System.Security.Cryptography.SymmetricAlgorithm::KeySizeValue
int32_t ___KeySizeValue_6;
// System.Security.Cryptography.CipherMode System.Security.Cryptography.SymmetricAlgorithm::ModeValue
int32_t ___ModeValue_7;
// System.Security.Cryptography.PaddingMode System.Security.Cryptography.SymmetricAlgorithm::PaddingValue
int32_t ___PaddingValue_8;
public:
inline static int32_t get_offset_of_BlockSizeValue_0() { return static_cast<int32_t>(offsetof(SymmetricAlgorithm_t1108166522, ___BlockSizeValue_0)); }
inline int32_t get_BlockSizeValue_0() const { return ___BlockSizeValue_0; }
inline int32_t* get_address_of_BlockSizeValue_0() { return &___BlockSizeValue_0; }
inline void set_BlockSizeValue_0(int32_t value)
{
___BlockSizeValue_0 = value;
}
inline static int32_t get_offset_of_FeedbackSizeValue_1() { return static_cast<int32_t>(offsetof(SymmetricAlgorithm_t1108166522, ___FeedbackSizeValue_1)); }
inline int32_t get_FeedbackSizeValue_1() const { return ___FeedbackSizeValue_1; }
inline int32_t* get_address_of_FeedbackSizeValue_1() { return &___FeedbackSizeValue_1; }
inline void set_FeedbackSizeValue_1(int32_t value)
{
___FeedbackSizeValue_1 = value;
}
inline static int32_t get_offset_of_IVValue_2() { return static_cast<int32_t>(offsetof(SymmetricAlgorithm_t1108166522, ___IVValue_2)); }
inline ByteU5BU5D_t3397334013* get_IVValue_2() const { return ___IVValue_2; }
inline ByteU5BU5D_t3397334013** get_address_of_IVValue_2() { return &___IVValue_2; }
inline void set_IVValue_2(ByteU5BU5D_t3397334013* value)
{
___IVValue_2 = value;
Il2CppCodeGenWriteBarrier((&___IVValue_2), value);
}
inline static int32_t get_offset_of_KeyValue_3() { return static_cast<int32_t>(offsetof(SymmetricAlgorithm_t1108166522, ___KeyValue_3)); }
inline ByteU5BU5D_t3397334013* get_KeyValue_3() const { return ___KeyValue_3; }
inline ByteU5BU5D_t3397334013** get_address_of_KeyValue_3() { return &___KeyValue_3; }
inline void set_KeyValue_3(ByteU5BU5D_t3397334013* value)
{
___KeyValue_3 = value;
Il2CppCodeGenWriteBarrier((&___KeyValue_3), value);
}
inline static int32_t get_offset_of_LegalBlockSizesValue_4() { return static_cast<int32_t>(offsetof(SymmetricAlgorithm_t1108166522, ___LegalBlockSizesValue_4)); }
inline KeySizesU5BU5D_t1153004758* get_LegalBlockSizesValue_4() const { return ___LegalBlockSizesValue_4; }
inline KeySizesU5BU5D_t1153004758** get_address_of_LegalBlockSizesValue_4() { return &___LegalBlockSizesValue_4; }
inline void set_LegalBlockSizesValue_4(KeySizesU5BU5D_t1153004758* value)
{
___LegalBlockSizesValue_4 = value;
Il2CppCodeGenWriteBarrier((&___LegalBlockSizesValue_4), value);
}
inline static int32_t get_offset_of_LegalKeySizesValue_5() { return static_cast<int32_t>(offsetof(SymmetricAlgorithm_t1108166522, ___LegalKeySizesValue_5)); }
inline KeySizesU5BU5D_t1153004758* get_LegalKeySizesValue_5() const { return ___LegalKeySizesValue_5; }
inline KeySizesU5BU5D_t1153004758** get_address_of_LegalKeySizesValue_5() { return &___LegalKeySizesValue_5; }
inline void set_LegalKeySizesValue_5(KeySizesU5BU5D_t1153004758* value)
{
___LegalKeySizesValue_5 = value;
Il2CppCodeGenWriteBarrier((&___LegalKeySizesValue_5), value);
}
inline static int32_t get_offset_of_KeySizeValue_6() { return static_cast<int32_t>(offsetof(SymmetricAlgorithm_t1108166522, ___KeySizeValue_6)); }
inline int32_t get_KeySizeValue_6() const { return ___KeySizeValue_6; }
inline int32_t* get_address_of_KeySizeValue_6() { return &___KeySizeValue_6; }
inline void set_KeySizeValue_6(int32_t value)
{
___KeySizeValue_6 = value;
}
inline static int32_t get_offset_of_ModeValue_7() { return static_cast<int32_t>(offsetof(SymmetricAlgorithm_t1108166522, ___ModeValue_7)); }
inline int32_t get_ModeValue_7() const { return ___ModeValue_7; }
inline int32_t* get_address_of_ModeValue_7() { return &___ModeValue_7; }
inline void set_ModeValue_7(int32_t value)
{
___ModeValue_7 = value;
}
inline static int32_t get_offset_of_PaddingValue_8() { return static_cast<int32_t>(offsetof(SymmetricAlgorithm_t1108166522, ___PaddingValue_8)); }
inline int32_t get_PaddingValue_8() const { return ___PaddingValue_8; }
inline int32_t* get_address_of_PaddingValue_8() { return &___PaddingValue_8; }
inline void set_PaddingValue_8(int32_t value)
{
___PaddingValue_8 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // SYMMETRICALGORITHM_T1108166522_H
#ifndef CONFIGURATIONPROPERTY_T2048066811_H
#define CONFIGURATIONPROPERTY_T2048066811_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.ConfigurationProperty
struct ConfigurationProperty_t2048066811 : public RuntimeObject
{
public:
// System.String System.Configuration.ConfigurationProperty::name
String_t* ___name_1;
// System.Type System.Configuration.ConfigurationProperty::type
Type_t * ___type_2;
// System.Object System.Configuration.ConfigurationProperty::default_value
RuntimeObject * ___default_value_3;
// System.ComponentModel.TypeConverter System.Configuration.ConfigurationProperty::converter
TypeConverter_t745995970 * ___converter_4;
// System.Configuration.ConfigurationValidatorBase System.Configuration.ConfigurationProperty::validation
ConfigurationValidatorBase_t210547623 * ___validation_5;
// System.Configuration.ConfigurationPropertyOptions System.Configuration.ConfigurationProperty::flags
int32_t ___flags_6;
// System.String System.Configuration.ConfigurationProperty::description
String_t* ___description_7;
// System.Configuration.ConfigurationCollectionAttribute System.Configuration.ConfigurationProperty::collectionAttribute
ConfigurationCollectionAttribute_t2811353736 * ___collectionAttribute_8;
public:
inline static int32_t get_offset_of_name_1() { return static_cast<int32_t>(offsetof(ConfigurationProperty_t2048066811, ___name_1)); }
inline String_t* get_name_1() const { return ___name_1; }
inline String_t** get_address_of_name_1() { return &___name_1; }
inline void set_name_1(String_t* value)
{
___name_1 = value;
Il2CppCodeGenWriteBarrier((&___name_1), value);
}
inline static int32_t get_offset_of_type_2() { return static_cast<int32_t>(offsetof(ConfigurationProperty_t2048066811, ___type_2)); }
inline Type_t * get_type_2() const { return ___type_2; }
inline Type_t ** get_address_of_type_2() { return &___type_2; }
inline void set_type_2(Type_t * value)
{
___type_2 = value;
Il2CppCodeGenWriteBarrier((&___type_2), value);
}
inline static int32_t get_offset_of_default_value_3() { return static_cast<int32_t>(offsetof(ConfigurationProperty_t2048066811, ___default_value_3)); }
inline RuntimeObject * get_default_value_3() const { return ___default_value_3; }
inline RuntimeObject ** get_address_of_default_value_3() { return &___default_value_3; }
inline void set_default_value_3(RuntimeObject * value)
{
___default_value_3 = value;
Il2CppCodeGenWriteBarrier((&___default_value_3), value);
}
inline static int32_t get_offset_of_converter_4() { return static_cast<int32_t>(offsetof(ConfigurationProperty_t2048066811, ___converter_4)); }
inline TypeConverter_t745995970 * get_converter_4() const { return ___converter_4; }
inline TypeConverter_t745995970 ** get_address_of_converter_4() { return &___converter_4; }
inline void set_converter_4(TypeConverter_t745995970 * value)
{
___converter_4 = value;
Il2CppCodeGenWriteBarrier((&___converter_4), value);
}
inline static int32_t get_offset_of_validation_5() { return static_cast<int32_t>(offsetof(ConfigurationProperty_t2048066811, ___validation_5)); }
inline ConfigurationValidatorBase_t210547623 * get_validation_5() const { return ___validation_5; }
inline ConfigurationValidatorBase_t210547623 ** get_address_of_validation_5() { return &___validation_5; }
inline void set_validation_5(ConfigurationValidatorBase_t210547623 * value)
{
___validation_5 = value;
Il2CppCodeGenWriteBarrier((&___validation_5), value);
}
inline static int32_t get_offset_of_flags_6() { return static_cast<int32_t>(offsetof(ConfigurationProperty_t2048066811, ___flags_6)); }
inline int32_t get_flags_6() const { return ___flags_6; }
inline int32_t* get_address_of_flags_6() { return &___flags_6; }
inline void set_flags_6(int32_t value)
{
___flags_6 = value;
}
inline static int32_t get_offset_of_description_7() { return static_cast<int32_t>(offsetof(ConfigurationProperty_t2048066811, ___description_7)); }
inline String_t* get_description_7() const { return ___description_7; }
inline String_t** get_address_of_description_7() { return &___description_7; }
inline void set_description_7(String_t* value)
{
___description_7 = value;
Il2CppCodeGenWriteBarrier((&___description_7), value);
}
inline static int32_t get_offset_of_collectionAttribute_8() { return static_cast<int32_t>(offsetof(ConfigurationProperty_t2048066811, ___collectionAttribute_8)); }
inline ConfigurationCollectionAttribute_t2811353736 * get_collectionAttribute_8() const { return ___collectionAttribute_8; }
inline ConfigurationCollectionAttribute_t2811353736 ** get_address_of_collectionAttribute_8() { return &___collectionAttribute_8; }
inline void set_collectionAttribute_8(ConfigurationCollectionAttribute_t2811353736 * value)
{
___collectionAttribute_8 = value;
Il2CppCodeGenWriteBarrier((&___collectionAttribute_8), value);
}
};
struct ConfigurationProperty_t2048066811_StaticFields
{
public:
// System.Object System.Configuration.ConfigurationProperty::NoDefaultValue
RuntimeObject * ___NoDefaultValue_0;
public:
inline static int32_t get_offset_of_NoDefaultValue_0() { return static_cast<int32_t>(offsetof(ConfigurationProperty_t2048066811_StaticFields, ___NoDefaultValue_0)); }
inline RuntimeObject * get_NoDefaultValue_0() const { return ___NoDefaultValue_0; }
inline RuntimeObject ** get_address_of_NoDefaultValue_0() { return &___NoDefaultValue_0; }
inline void set_NoDefaultValue_0(RuntimeObject * value)
{
___NoDefaultValue_0 = value;
Il2CppCodeGenWriteBarrier((&___NoDefaultValue_0), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // CONFIGURATIONPROPERTY_T2048066811_H
#ifndef ASSETBUNDLECREATEREQUEST_T1038783543_H
#define ASSETBUNDLECREATEREQUEST_T1038783543_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.AssetBundleCreateRequest
struct AssetBundleCreateRequest_t1038783543 : public AsyncOperation_t3814632279
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of UnityEngine.AssetBundleCreateRequest
struct AssetBundleCreateRequest_t1038783543_marshaled_pinvoke : public AsyncOperation_t3814632279_marshaled_pinvoke
{
};
// Native definition for COM marshalling of UnityEngine.AssetBundleCreateRequest
struct AssetBundleCreateRequest_t1038783543_marshaled_com : public AsyncOperation_t3814632279_marshaled_com
{
};
#endif // ASSETBUNDLECREATEREQUEST_T1038783543_H
#ifndef PROPERTYINFORMATION_T2089433965_H
#define PROPERTYINFORMATION_T2089433965_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.PropertyInformation
struct PropertyInformation_t2089433965 : public RuntimeObject
{
public:
// System.Boolean System.Configuration.PropertyInformation::isModified
bool ___isModified_0;
// System.Int32 System.Configuration.PropertyInformation::lineNumber
int32_t ___lineNumber_1;
// System.String System.Configuration.PropertyInformation::source
String_t* ___source_2;
// System.Object System.Configuration.PropertyInformation::val
RuntimeObject * ___val_3;
// System.Configuration.PropertyValueOrigin System.Configuration.PropertyInformation::origin
int32_t ___origin_4;
// System.Configuration.ConfigurationElement System.Configuration.PropertyInformation::owner
ConfigurationElement_t1776195828 * ___owner_5;
// System.Configuration.ConfigurationProperty System.Configuration.PropertyInformation::property
ConfigurationProperty_t2048066811 * ___property_6;
public:
inline static int32_t get_offset_of_isModified_0() { return static_cast<int32_t>(offsetof(PropertyInformation_t2089433965, ___isModified_0)); }
inline bool get_isModified_0() const { return ___isModified_0; }
inline bool* get_address_of_isModified_0() { return &___isModified_0; }
inline void set_isModified_0(bool value)
{
___isModified_0 = value;
}
inline static int32_t get_offset_of_lineNumber_1() { return static_cast<int32_t>(offsetof(PropertyInformation_t2089433965, ___lineNumber_1)); }
inline int32_t get_lineNumber_1() const { return ___lineNumber_1; }
inline int32_t* get_address_of_lineNumber_1() { return &___lineNumber_1; }
inline void set_lineNumber_1(int32_t value)
{
___lineNumber_1 = value;
}
inline static int32_t get_offset_of_source_2() { return static_cast<int32_t>(offsetof(PropertyInformation_t2089433965, ___source_2)); }
inline String_t* get_source_2() const { return ___source_2; }
inline String_t** get_address_of_source_2() { return &___source_2; }
inline void set_source_2(String_t* value)
{
___source_2 = value;
Il2CppCodeGenWriteBarrier((&___source_2), value);
}
inline static int32_t get_offset_of_val_3() { return static_cast<int32_t>(offsetof(PropertyInformation_t2089433965, ___val_3)); }
inline RuntimeObject * get_val_3() const { return ___val_3; }
inline RuntimeObject ** get_address_of_val_3() { return &___val_3; }
inline void set_val_3(RuntimeObject * value)
{
___val_3 = value;
Il2CppCodeGenWriteBarrier((&___val_3), value);
}
inline static int32_t get_offset_of_origin_4() { return static_cast<int32_t>(offsetof(PropertyInformation_t2089433965, ___origin_4)); }
inline int32_t get_origin_4() const { return ___origin_4; }
inline int32_t* get_address_of_origin_4() { return &___origin_4; }
inline void set_origin_4(int32_t value)
{
___origin_4 = value;
}
inline static int32_t get_offset_of_owner_5() { return static_cast<int32_t>(offsetof(PropertyInformation_t2089433965, ___owner_5)); }
inline ConfigurationElement_t1776195828 * get_owner_5() const { return ___owner_5; }
inline ConfigurationElement_t1776195828 ** get_address_of_owner_5() { return &___owner_5; }
inline void set_owner_5(ConfigurationElement_t1776195828 * value)
{
___owner_5 = value;
Il2CppCodeGenWriteBarrier((&___owner_5), value);
}
inline static int32_t get_offset_of_property_6() { return static_cast<int32_t>(offsetof(PropertyInformation_t2089433965, ___property_6)); }
inline ConfigurationProperty_t2048066811 * get_property_6() const { return ___property_6; }
inline ConfigurationProperty_t2048066811 ** get_address_of_property_6() { return &___property_6; }
inline void set_property_6(ConfigurationProperty_t2048066811 * value)
{
___property_6 = value;
Il2CppCodeGenWriteBarrier((&___property_6), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // PROPERTYINFORMATION_T2089433965_H
#ifndef EXECONFIGURATIONHOST_T2778769322_H
#define EXECONFIGURATIONHOST_T2778769322_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.ExeConfigurationHost
struct ExeConfigurationHost_t2778769322 : public InternalConfigurationHost_t547577555
{
public:
// System.Configuration.ExeConfigurationFileMap System.Configuration.ExeConfigurationHost::map
ExeConfigurationFileMap_t1419586304 * ___map_0;
// System.Configuration.ConfigurationUserLevel System.Configuration.ExeConfigurationHost::level
int32_t ___level_1;
public:
inline static int32_t get_offset_of_map_0() { return static_cast<int32_t>(offsetof(ExeConfigurationHost_t2778769322, ___map_0)); }
inline ExeConfigurationFileMap_t1419586304 * get_map_0() const { return ___map_0; }
inline ExeConfigurationFileMap_t1419586304 ** get_address_of_map_0() { return &___map_0; }
inline void set_map_0(ExeConfigurationFileMap_t1419586304 * value)
{
___map_0 = value;
Il2CppCodeGenWriteBarrier((&___map_0), value);
}
inline static int32_t get_offset_of_level_1() { return static_cast<int32_t>(offsetof(ExeConfigurationHost_t2778769322, ___level_1)); }
inline int32_t get_level_1() const { return ___level_1; }
inline int32_t* get_address_of_level_1() { return &___level_1; }
inline void set_level_1(int32_t value)
{
___level_1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // EXECONFIGURATIONHOST_T2778769322_H
#ifndef ASSETBUNDLEREQUEST_T2674559435_H
#define ASSETBUNDLEREQUEST_T2674559435_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.AssetBundleRequest
struct AssetBundleRequest_t2674559435 : public AsyncOperation_t3814632279
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of UnityEngine.AssetBundleRequest
struct AssetBundleRequest_t2674559435_marshaled_pinvoke : public AsyncOperation_t3814632279_marshaled_pinvoke
{
};
// Native definition for COM marshalling of UnityEngine.AssetBundleRequest
struct AssetBundleRequest_t2674559435_marshaled_com : public AsyncOperation_t3814632279_marshaled_com
{
};
#endif // ASSETBUNDLEREQUEST_T2674559435_H
#ifndef CONFIGURATIONPROPERTYATTRIBUTE_T3655647199_H
#define CONFIGURATIONPROPERTYATTRIBUTE_T3655647199_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.ConfigurationPropertyAttribute
struct ConfigurationPropertyAttribute_t3655647199 : public Attribute_t542643598
{
public:
// System.String System.Configuration.ConfigurationPropertyAttribute::name
String_t* ___name_0;
// System.Object System.Configuration.ConfigurationPropertyAttribute::default_value
RuntimeObject * ___default_value_1;
// System.Configuration.ConfigurationPropertyOptions System.Configuration.ConfigurationPropertyAttribute::flags
int32_t ___flags_2;
public:
inline static int32_t get_offset_of_name_0() { return static_cast<int32_t>(offsetof(ConfigurationPropertyAttribute_t3655647199, ___name_0)); }
inline String_t* get_name_0() const { return ___name_0; }
inline String_t** get_address_of_name_0() { return &___name_0; }
inline void set_name_0(String_t* value)
{
___name_0 = value;
Il2CppCodeGenWriteBarrier((&___name_0), value);
}
inline static int32_t get_offset_of_default_value_1() { return static_cast<int32_t>(offsetof(ConfigurationPropertyAttribute_t3655647199, ___default_value_1)); }
inline RuntimeObject * get_default_value_1() const { return ___default_value_1; }
inline RuntimeObject ** get_address_of_default_value_1() { return &___default_value_1; }
inline void set_default_value_1(RuntimeObject * value)
{
___default_value_1 = value;
Il2CppCodeGenWriteBarrier((&___default_value_1), value);
}
inline static int32_t get_offset_of_flags_2() { return static_cast<int32_t>(offsetof(ConfigurationPropertyAttribute_t3655647199, ___flags_2)); }
inline int32_t get_flags_2() const { return ___flags_2; }
inline int32_t* get_address_of_flags_2() { return &___flags_2; }
inline void set_flags_2(int32_t value)
{
___flags_2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // CONFIGURATIONPROPERTYATTRIBUTE_T3655647199_H
#ifndef SYMMETRICTRANSFORM_T1394030013_H
#define SYMMETRICTRANSFORM_T1394030013_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Mono.Security.Cryptography.SymmetricTransform
struct SymmetricTransform_t1394030013 : public RuntimeObject
{
public:
// System.Security.Cryptography.SymmetricAlgorithm Mono.Security.Cryptography.SymmetricTransform::algo
SymmetricAlgorithm_t1108166522 * ___algo_0;
// System.Boolean Mono.Security.Cryptography.SymmetricTransform::encrypt
bool ___encrypt_1;
// System.Int32 Mono.Security.Cryptography.SymmetricTransform::BlockSizeByte
int32_t ___BlockSizeByte_2;
// System.Byte[] Mono.Security.Cryptography.SymmetricTransform::temp
ByteU5BU5D_t3397334013* ___temp_3;
// System.Byte[] Mono.Security.Cryptography.SymmetricTransform::temp2
ByteU5BU5D_t3397334013* ___temp2_4;
// System.Byte[] Mono.Security.Cryptography.SymmetricTransform::workBuff
ByteU5BU5D_t3397334013* ___workBuff_5;
// System.Byte[] Mono.Security.Cryptography.SymmetricTransform::workout
ByteU5BU5D_t3397334013* ___workout_6;
// System.Security.Cryptography.PaddingMode Mono.Security.Cryptography.SymmetricTransform::padmode
int32_t ___padmode_7;
// System.Int32 Mono.Security.Cryptography.SymmetricTransform::FeedBackByte
int32_t ___FeedBackByte_8;
// System.Boolean Mono.Security.Cryptography.SymmetricTransform::m_disposed
bool ___m_disposed_9;
// System.Boolean Mono.Security.Cryptography.SymmetricTransform::lastBlock
bool ___lastBlock_10;
// System.Security.Cryptography.RandomNumberGenerator Mono.Security.Cryptography.SymmetricTransform::_rng
RandomNumberGenerator_t2510243513 * ____rng_11;
public:
inline static int32_t get_offset_of_algo_0() { return static_cast<int32_t>(offsetof(SymmetricTransform_t1394030013, ___algo_0)); }
inline SymmetricAlgorithm_t1108166522 * get_algo_0() const { return ___algo_0; }
inline SymmetricAlgorithm_t1108166522 ** get_address_of_algo_0() { return &___algo_0; }
inline void set_algo_0(SymmetricAlgorithm_t1108166522 * value)
{
___algo_0 = value;
Il2CppCodeGenWriteBarrier((&___algo_0), value);
}
inline static int32_t get_offset_of_encrypt_1() { return static_cast<int32_t>(offsetof(SymmetricTransform_t1394030013, ___encrypt_1)); }
inline bool get_encrypt_1() const { return ___encrypt_1; }
inline bool* get_address_of_encrypt_1() { return &___encrypt_1; }
inline void set_encrypt_1(bool value)
{
___encrypt_1 = value;
}
inline static int32_t get_offset_of_BlockSizeByte_2() { return static_cast<int32_t>(offsetof(SymmetricTransform_t1394030013, ___BlockSizeByte_2)); }
inline int32_t get_BlockSizeByte_2() const { return ___BlockSizeByte_2; }
inline int32_t* get_address_of_BlockSizeByte_2() { return &___BlockSizeByte_2; }
inline void set_BlockSizeByte_2(int32_t value)
{
___BlockSizeByte_2 = value;
}
inline static int32_t get_offset_of_temp_3() { return static_cast<int32_t>(offsetof(SymmetricTransform_t1394030013, ___temp_3)); }
inline ByteU5BU5D_t3397334013* get_temp_3() const { return ___temp_3; }
inline ByteU5BU5D_t3397334013** get_address_of_temp_3() { return &___temp_3; }
inline void set_temp_3(ByteU5BU5D_t3397334013* value)
{
___temp_3 = value;
Il2CppCodeGenWriteBarrier((&___temp_3), value);
}
inline static int32_t get_offset_of_temp2_4() { return static_cast<int32_t>(offsetof(SymmetricTransform_t1394030013, ___temp2_4)); }
inline ByteU5BU5D_t3397334013* get_temp2_4() const { return ___temp2_4; }
inline ByteU5BU5D_t3397334013** get_address_of_temp2_4() { return &___temp2_4; }
inline void set_temp2_4(ByteU5BU5D_t3397334013* value)
{
___temp2_4 = value;
Il2CppCodeGenWriteBarrier((&___temp2_4), value);
}
inline static int32_t get_offset_of_workBuff_5() { return static_cast<int32_t>(offsetof(SymmetricTransform_t1394030013, ___workBuff_5)); }
inline ByteU5BU5D_t3397334013* get_workBuff_5() const { return ___workBuff_5; }
inline ByteU5BU5D_t3397334013** get_address_of_workBuff_5() { return &___workBuff_5; }
inline void set_workBuff_5(ByteU5BU5D_t3397334013* value)
{
___workBuff_5 = value;
Il2CppCodeGenWriteBarrier((&___workBuff_5), value);
}
inline static int32_t get_offset_of_workout_6() { return static_cast<int32_t>(offsetof(SymmetricTransform_t1394030013, ___workout_6)); }
inline ByteU5BU5D_t3397334013* get_workout_6() const { return ___workout_6; }
inline ByteU5BU5D_t3397334013** get_address_of_workout_6() { return &___workout_6; }
inline void set_workout_6(ByteU5BU5D_t3397334013* value)
{
___workout_6 = value;
Il2CppCodeGenWriteBarrier((&___workout_6), value);
}
inline static int32_t get_offset_of_padmode_7() { return static_cast<int32_t>(offsetof(SymmetricTransform_t1394030013, ___padmode_7)); }
inline int32_t get_padmode_7() const { return ___padmode_7; }
inline int32_t* get_address_of_padmode_7() { return &___padmode_7; }
inline void set_padmode_7(int32_t value)
{
___padmode_7 = value;
}
inline static int32_t get_offset_of_FeedBackByte_8() { return static_cast<int32_t>(offsetof(SymmetricTransform_t1394030013, ___FeedBackByte_8)); }
inline int32_t get_FeedBackByte_8() const { return ___FeedBackByte_8; }
inline int32_t* get_address_of_FeedBackByte_8() { return &___FeedBackByte_8; }
inline void set_FeedBackByte_8(int32_t value)
{
___FeedBackByte_8 = value;
}
inline static int32_t get_offset_of_m_disposed_9() { return static_cast<int32_t>(offsetof(SymmetricTransform_t1394030013, ___m_disposed_9)); }
inline bool get_m_disposed_9() const { return ___m_disposed_9; }
inline bool* get_address_of_m_disposed_9() { return &___m_disposed_9; }
inline void set_m_disposed_9(bool value)
{
___m_disposed_9 = value;
}
inline static int32_t get_offset_of_lastBlock_10() { return static_cast<int32_t>(offsetof(SymmetricTransform_t1394030013, ___lastBlock_10)); }
inline bool get_lastBlock_10() const { return ___lastBlock_10; }
inline bool* get_address_of_lastBlock_10() { return &___lastBlock_10; }
inline void set_lastBlock_10(bool value)
{
___lastBlock_10 = value;
}
inline static int32_t get_offset_of__rng_11() { return static_cast<int32_t>(offsetof(SymmetricTransform_t1394030013, ____rng_11)); }
inline RandomNumberGenerator_t2510243513 * get__rng_11() const { return ____rng_11; }
inline RandomNumberGenerator_t2510243513 ** get_address_of__rng_11() { return &____rng_11; }
inline void set__rng_11(RandomNumberGenerator_t2510243513 * value)
{
____rng_11 = value;
Il2CppCodeGenWriteBarrier((&____rng_11), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // SYMMETRICTRANSFORM_T1394030013_H
#ifndef AESTRANSFORM_T3733702461_H
#define AESTRANSFORM_T3733702461_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.AesTransform
struct AesTransform_t3733702461 : public SymmetricTransform_t1394030013
{
public:
// System.UInt32[] System.Security.Cryptography.AesTransform::expandedKey
UInt32U5BU5D_t59386216* ___expandedKey_12;
// System.Int32 System.Security.Cryptography.AesTransform::Nk
int32_t ___Nk_13;
// System.Int32 System.Security.Cryptography.AesTransform::Nr
int32_t ___Nr_14;
public:
inline static int32_t get_offset_of_expandedKey_12() { return static_cast<int32_t>(offsetof(AesTransform_t3733702461, ___expandedKey_12)); }
inline UInt32U5BU5D_t59386216* get_expandedKey_12() const { return ___expandedKey_12; }
inline UInt32U5BU5D_t59386216** get_address_of_expandedKey_12() { return &___expandedKey_12; }
inline void set_expandedKey_12(UInt32U5BU5D_t59386216* value)
{
___expandedKey_12 = value;
Il2CppCodeGenWriteBarrier((&___expandedKey_12), value);
}
inline static int32_t get_offset_of_Nk_13() { return static_cast<int32_t>(offsetof(AesTransform_t3733702461, ___Nk_13)); }
inline int32_t get_Nk_13() const { return ___Nk_13; }
inline int32_t* get_address_of_Nk_13() { return &___Nk_13; }
inline void set_Nk_13(int32_t value)
{
___Nk_13 = value;
}
inline static int32_t get_offset_of_Nr_14() { return static_cast<int32_t>(offsetof(AesTransform_t3733702461, ___Nr_14)); }
inline int32_t get_Nr_14() const { return ___Nr_14; }
inline int32_t* get_address_of_Nr_14() { return &___Nr_14; }
inline void set_Nr_14(int32_t value)
{
___Nr_14 = value;
}
};
struct AesTransform_t3733702461_StaticFields
{
public:
// System.UInt32[] System.Security.Cryptography.AesTransform::Rcon
UInt32U5BU5D_t59386216* ___Rcon_15;
// System.Byte[] System.Security.Cryptography.AesTransform::SBox
ByteU5BU5D_t3397334013* ___SBox_16;
// System.Byte[] System.Security.Cryptography.AesTransform::iSBox
ByteU5BU5D_t3397334013* ___iSBox_17;
// System.UInt32[] System.Security.Cryptography.AesTransform::T0
UInt32U5BU5D_t59386216* ___T0_18;
// System.UInt32[] System.Security.Cryptography.AesTransform::T1
UInt32U5BU5D_t59386216* ___T1_19;
// System.UInt32[] System.Security.Cryptography.AesTransform::T2
UInt32U5BU5D_t59386216* ___T2_20;
// System.UInt32[] System.Security.Cryptography.AesTransform::T3
UInt32U5BU5D_t59386216* ___T3_21;
// System.UInt32[] System.Security.Cryptography.AesTransform::iT0
UInt32U5BU5D_t59386216* ___iT0_22;
// System.UInt32[] System.Security.Cryptography.AesTransform::iT1
UInt32U5BU5D_t59386216* ___iT1_23;
// System.UInt32[] System.Security.Cryptography.AesTransform::iT2
UInt32U5BU5D_t59386216* ___iT2_24;
// System.UInt32[] System.Security.Cryptography.AesTransform::iT3
UInt32U5BU5D_t59386216* ___iT3_25;
public:
inline static int32_t get_offset_of_Rcon_15() { return static_cast<int32_t>(offsetof(AesTransform_t3733702461_StaticFields, ___Rcon_15)); }
inline UInt32U5BU5D_t59386216* get_Rcon_15() const { return ___Rcon_15; }
inline UInt32U5BU5D_t59386216** get_address_of_Rcon_15() { return &___Rcon_15; }
inline void set_Rcon_15(UInt32U5BU5D_t59386216* value)
{
___Rcon_15 = value;
Il2CppCodeGenWriteBarrier((&___Rcon_15), value);
}
inline static int32_t get_offset_of_SBox_16() { return static_cast<int32_t>(offsetof(AesTransform_t3733702461_StaticFields, ___SBox_16)); }
inline ByteU5BU5D_t3397334013* get_SBox_16() const { return ___SBox_16; }
inline ByteU5BU5D_t3397334013** get_address_of_SBox_16() { return &___SBox_16; }
inline void set_SBox_16(ByteU5BU5D_t3397334013* value)
{
___SBox_16 = value;
Il2CppCodeGenWriteBarrier((&___SBox_16), value);
}
inline static int32_t get_offset_of_iSBox_17() { return static_cast<int32_t>(offsetof(AesTransform_t3733702461_StaticFields, ___iSBox_17)); }
inline ByteU5BU5D_t3397334013* get_iSBox_17() const { return ___iSBox_17; }
inline ByteU5BU5D_t3397334013** get_address_of_iSBox_17() { return &___iSBox_17; }
inline void set_iSBox_17(ByteU5BU5D_t3397334013* value)
{
___iSBox_17 = value;
Il2CppCodeGenWriteBarrier((&___iSBox_17), value);
}
inline static int32_t get_offset_of_T0_18() { return static_cast<int32_t>(offsetof(AesTransform_t3733702461_StaticFields, ___T0_18)); }
inline UInt32U5BU5D_t59386216* get_T0_18() const { return ___T0_18; }
inline UInt32U5BU5D_t59386216** get_address_of_T0_18() { return &___T0_18; }
inline void set_T0_18(UInt32U5BU5D_t59386216* value)
{
___T0_18 = value;
Il2CppCodeGenWriteBarrier((&___T0_18), value);
}
inline static int32_t get_offset_of_T1_19() { return static_cast<int32_t>(offsetof(AesTransform_t3733702461_StaticFields, ___T1_19)); }
inline UInt32U5BU5D_t59386216* get_T1_19() const { return ___T1_19; }
inline UInt32U5BU5D_t59386216** get_address_of_T1_19() { return &___T1_19; }
inline void set_T1_19(UInt32U5BU5D_t59386216* value)
{
___T1_19 = value;
Il2CppCodeGenWriteBarrier((&___T1_19), value);
}
inline static int32_t get_offset_of_T2_20() { return static_cast<int32_t>(offsetof(AesTransform_t3733702461_StaticFields, ___T2_20)); }
inline UInt32U5BU5D_t59386216* get_T2_20() const { return ___T2_20; }
inline UInt32U5BU5D_t59386216** get_address_of_T2_20() { return &___T2_20; }
inline void set_T2_20(UInt32U5BU5D_t59386216* value)
{
___T2_20 = value;
Il2CppCodeGenWriteBarrier((&___T2_20), value);
}
inline static int32_t get_offset_of_T3_21() { return static_cast<int32_t>(offsetof(AesTransform_t3733702461_StaticFields, ___T3_21)); }
inline UInt32U5BU5D_t59386216* get_T3_21() const { return ___T3_21; }
inline UInt32U5BU5D_t59386216** get_address_of_T3_21() { return &___T3_21; }
inline void set_T3_21(UInt32U5BU5D_t59386216* value)
{
___T3_21 = value;
Il2CppCodeGenWriteBarrier((&___T3_21), value);
}
inline static int32_t get_offset_of_iT0_22() { return static_cast<int32_t>(offsetof(AesTransform_t3733702461_StaticFields, ___iT0_22)); }
inline UInt32U5BU5D_t59386216* get_iT0_22() const { return ___iT0_22; }
inline UInt32U5BU5D_t59386216** get_address_of_iT0_22() { return &___iT0_22; }
inline void set_iT0_22(UInt32U5BU5D_t59386216* value)
{
___iT0_22 = value;
Il2CppCodeGenWriteBarrier((&___iT0_22), value);
}
inline static int32_t get_offset_of_iT1_23() { return static_cast<int32_t>(offsetof(AesTransform_t3733702461_StaticFields, ___iT1_23)); }
inline UInt32U5BU5D_t59386216* get_iT1_23() const { return ___iT1_23; }
inline UInt32U5BU5D_t59386216** get_address_of_iT1_23() { return &___iT1_23; }
inline void set_iT1_23(UInt32U5BU5D_t59386216* value)
{
___iT1_23 = value;
Il2CppCodeGenWriteBarrier((&___iT1_23), value);
}
inline static int32_t get_offset_of_iT2_24() { return static_cast<int32_t>(offsetof(AesTransform_t3733702461_StaticFields, ___iT2_24)); }
inline UInt32U5BU5D_t59386216* get_iT2_24() const { return ___iT2_24; }
inline UInt32U5BU5D_t59386216** get_address_of_iT2_24() { return &___iT2_24; }
inline void set_iT2_24(UInt32U5BU5D_t59386216* value)
{
___iT2_24 = value;
Il2CppCodeGenWriteBarrier((&___iT2_24), value);
}
inline static int32_t get_offset_of_iT3_25() { return static_cast<int32_t>(offsetof(AesTransform_t3733702461_StaticFields, ___iT3_25)); }
inline UInt32U5BU5D_t59386216* get_iT3_25() const { return ___iT3_25; }
inline UInt32U5BU5D_t59386216** get_address_of_iT3_25() { return &___iT3_25; }
inline void set_iT3_25(UInt32U5BU5D_t59386216* value)
{
___iT3_25 = value;
Il2CppCodeGenWriteBarrier((&___iT3_25), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // AESTRANSFORM_T3733702461_H
#ifndef LOWMEMORYCALLBACK_T642977590_H
#define LOWMEMORYCALLBACK_T642977590_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.Application/LowMemoryCallback
struct LowMemoryCallback_t642977590 : public MulticastDelegate_t3201952435
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // LOWMEMORYCALLBACK_T642977590_H
#ifndef AES_T2354947465_H
#define AES_T2354947465_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.Aes
struct Aes_t2354947465 : public SymmetricAlgorithm_t1108166522
{
public:
public:
};
struct Aes_t2354947465_StaticFields
{
public:
// System.Security.Cryptography.KeySizes[] System.Security.Cryptography.Aes::s_legalBlockSizes
KeySizesU5BU5D_t1153004758* ___s_legalBlockSizes_9;
// System.Security.Cryptography.KeySizes[] System.Security.Cryptography.Aes::s_legalKeySizes
KeySizesU5BU5D_t1153004758* ___s_legalKeySizes_10;
public:
inline static int32_t get_offset_of_s_legalBlockSizes_9() { return static_cast<int32_t>(offsetof(Aes_t2354947465_StaticFields, ___s_legalBlockSizes_9)); }
inline KeySizesU5BU5D_t1153004758* get_s_legalBlockSizes_9() const { return ___s_legalBlockSizes_9; }
inline KeySizesU5BU5D_t1153004758** get_address_of_s_legalBlockSizes_9() { return &___s_legalBlockSizes_9; }
inline void set_s_legalBlockSizes_9(KeySizesU5BU5D_t1153004758* value)
{
___s_legalBlockSizes_9 = value;
Il2CppCodeGenWriteBarrier((&___s_legalBlockSizes_9), value);
}
inline static int32_t get_offset_of_s_legalKeySizes_10() { return static_cast<int32_t>(offsetof(Aes_t2354947465_StaticFields, ___s_legalKeySizes_10)); }
inline KeySizesU5BU5D_t1153004758* get_s_legalKeySizes_10() const { return ___s_legalKeySizes_10; }
inline KeySizesU5BU5D_t1153004758** get_address_of_s_legalKeySizes_10() { return &___s_legalKeySizes_10; }
inline void set_s_legalKeySizes_10(KeySizesU5BU5D_t1153004758* value)
{
___s_legalKeySizes_10 = value;
Il2CppCodeGenWriteBarrier((&___s_legalKeySizes_10), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // AES_T2354947465_H
#ifndef CODEACCESSSECURITYATTRIBUTE_T3161344859_H
#define CODEACCESSSECURITYATTRIBUTE_T3161344859_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Permissions.CodeAccessSecurityAttribute
struct CodeAccessSecurityAttribute_t3161344859 : public SecurityAttribute_t2016950496
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // CODEACCESSSECURITYATTRIBUTE_T3161344859_H
#ifndef LOGCALLBACK_T1867914413_H
#define LOGCALLBACK_T1867914413_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.Application/LogCallback
struct LogCallback_t1867914413 : public MulticastDelegate_t3201952435
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // LOGCALLBACK_T1867914413_H
#ifndef CONFIGURATIONPERMISSIONATTRIBUTE_T1968770041_H
#define CONFIGURATIONPERMISSIONATTRIBUTE_T1968770041_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Configuration.ConfigurationPermissionAttribute
struct ConfigurationPermissionAttribute_t1968770041 : public CodeAccessSecurityAttribute_t3161344859
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // CONFIGURATIONPERMISSIONATTRIBUTE_T1968770041_H
#ifndef AESMANAGED_T3721278648_H
#define AESMANAGED_T3721278648_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.AesManaged
struct AesManaged_t3721278648 : public Aes_t2354947465
{
public:
// System.Security.Cryptography.RijndaelManaged System.Security.Cryptography.AesManaged::m_rijndael
RijndaelManaged_t1034060848 * ___m_rijndael_11;
public:
inline static int32_t get_offset_of_m_rijndael_11() { return static_cast<int32_t>(offsetof(AesManaged_t3721278648, ___m_rijndael_11)); }
inline RijndaelManaged_t1034060848 * get_m_rijndael_11() const { return ___m_rijndael_11; }
inline RijndaelManaged_t1034060848 ** get_address_of_m_rijndael_11() { return &___m_rijndael_11; }
inline void set_m_rijndael_11(RijndaelManaged_t1034060848 * value)
{
___m_rijndael_11 = value;
Il2CppCodeGenWriteBarrier((&___m_rijndael_11), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // AESMANAGED_T3721278648_H
#ifndef AESCRYPTOSERVICEPROVIDER_T1359258894_H
#define AESCRYPTOSERVICEPROVIDER_T1359258894_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.AesCryptoServiceProvider
struct AesCryptoServiceProvider_t1359258894 : public Aes_t2354947465
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // AESCRYPTOSERVICEPROVIDER_T1359258894_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2900 = { sizeof (ConfigInfo_t546730838), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2900[6] =
{
ConfigInfo_t546730838::get_offset_of_Name_0(),
ConfigInfo_t546730838::get_offset_of_TypeName_1(),
ConfigInfo_t546730838::get_offset_of_Type_2(),
ConfigInfo_t546730838::get_offset_of_streamName_3(),
ConfigInfo_t546730838::get_offset_of_Parent_4(),
ConfigInfo_t546730838::get_offset_of_ConfigHost_5(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2901 = { sizeof (ConfigurationXmlDocument_t3670001516), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2902 = { sizeof (Configuration_t3335372970), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2902[12] =
{
Configuration_t3335372970::get_offset_of_parent_0(),
Configuration_t3335372970::get_offset_of_elementData_1(),
Configuration_t3335372970::get_offset_of_streamName_2(),
Configuration_t3335372970::get_offset_of_rootSectionGroup_3(),
Configuration_t3335372970::get_offset_of_locations_4(),
Configuration_t3335372970::get_offset_of_rootGroup_5(),
Configuration_t3335372970::get_offset_of_system_6(),
Configuration_t3335372970::get_offset_of_hasFile_7(),
Configuration_t3335372970::get_offset_of_rootNamespace_8(),
Configuration_t3335372970::get_offset_of_configPath_9(),
Configuration_t3335372970::get_offset_of_locationConfigPath_10(),
Configuration_t3335372970::get_offset_of_locationSubPath_11(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2903 = { sizeof (ConfigurationAllowDefinition_t3250313246)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };
extern const int32_t g_FieldOffsetTable2903[5] =
{
ConfigurationAllowDefinition_t3250313246::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)),
0,
0,
0,
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2904 = { sizeof (ConfigurationAllowExeDefinition_t3860111898)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };
extern const int32_t g_FieldOffsetTable2904[5] =
{
ConfigurationAllowExeDefinition_t3860111898::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)),
0,
0,
0,
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2905 = { sizeof (ConfigurationCollectionAttribute_t2811353736), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2905[5] =
{
ConfigurationCollectionAttribute_t2811353736::get_offset_of_addItemName_0(),
ConfigurationCollectionAttribute_t2811353736::get_offset_of_clearItemsName_1(),
ConfigurationCollectionAttribute_t2811353736::get_offset_of_removeItemName_2(),
ConfigurationCollectionAttribute_t2811353736::get_offset_of_collectionType_3(),
ConfigurationCollectionAttribute_t2811353736::get_offset_of_itemType_4(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2906 = { sizeof (ConfigurationElement_t1776195828), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2906[15] =
{
ConfigurationElement_t1776195828::get_offset_of_rawXml_0(),
ConfigurationElement_t1776195828::get_offset_of_modified_1(),
ConfigurationElement_t1776195828::get_offset_of_map_2(),
ConfigurationElement_t1776195828::get_offset_of_keyProps_3(),
ConfigurationElement_t1776195828::get_offset_of_defaultCollection_4(),
ConfigurationElement_t1776195828::get_offset_of_readOnly_5(),
ConfigurationElement_t1776195828::get_offset_of_elementInfo_6(),
ConfigurationElement_t1776195828::get_offset_of__configuration_7(),
ConfigurationElement_t1776195828::get_offset_of_elementPresent_8(),
ConfigurationElement_t1776195828::get_offset_of_lockAllAttributesExcept_9(),
ConfigurationElement_t1776195828::get_offset_of_lockAllElementsExcept_10(),
ConfigurationElement_t1776195828::get_offset_of_lockAttributes_11(),
ConfigurationElement_t1776195828::get_offset_of_lockElements_12(),
ConfigurationElement_t1776195828::get_offset_of_lockItem_13(),
ConfigurationElement_t1776195828::get_offset_of_saveContext_14(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2907 = { sizeof (SaveContext_t3996373180), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2907[3] =
{
SaveContext_t3996373180::get_offset_of_Element_0(),
SaveContext_t3996373180::get_offset_of_Parent_1(),
SaveContext_t3996373180::get_offset_of_Mode_2(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2908 = { sizeof (ElementMap_t997038224), -1, sizeof(ElementMap_t997038224_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable2908[3] =
{
ElementMap_t997038224_StaticFields::get_offset_of_elementMaps_0(),
ElementMap_t997038224::get_offset_of_properties_1(),
ElementMap_t997038224::get_offset_of_collectionAttribute_2(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2909 = { sizeof (ConfigurationElementCollection_t1911180302), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2909[10] =
{
ConfigurationElementCollection_t1911180302::get_offset_of_list_15(),
ConfigurationElementCollection_t1911180302::get_offset_of_removed_16(),
ConfigurationElementCollection_t1911180302::get_offset_of_inherited_17(),
ConfigurationElementCollection_t1911180302::get_offset_of_emitClear_18(),
ConfigurationElementCollection_t1911180302::get_offset_of_modified_19(),
ConfigurationElementCollection_t1911180302::get_offset_of_comparer_20(),
ConfigurationElementCollection_t1911180302::get_offset_of_inheritedLimitIndex_21(),
ConfigurationElementCollection_t1911180302::get_offset_of_addElementName_22(),
ConfigurationElementCollection_t1911180302::get_offset_of_clearElementName_23(),
ConfigurationElementCollection_t1911180302::get_offset_of_removeElementName_24(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2910 = { sizeof (ConfigurationRemoveElement_t3305291330), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2910[3] =
{
ConfigurationRemoveElement_t3305291330::get_offset_of_properties_15(),
ConfigurationRemoveElement_t3305291330::get_offset_of__origElement_16(),
ConfigurationRemoveElement_t3305291330::get_offset_of__origCollection_17(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2911 = { sizeof (ConfigurationElementCollectionType_t1806001494)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };
extern const int32_t g_FieldOffsetTable2911[5] =
{
ConfigurationElementCollectionType_t1806001494::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)),
0,
0,
0,
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2912 = { sizeof (ConfigurationErrorsException_t1362721126), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2912[2] =
{
ConfigurationErrorsException_t1362721126::get_offset_of_filename_18(),
ConfigurationErrorsException_t1362721126::get_offset_of_line_19(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2913 = { sizeof (ConfigurationFileMap_t2625210096), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2913[1] =
{
ConfigurationFileMap_t2625210096::get_offset_of_machineConfigFilename_0(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2914 = { sizeof (ConfigurationLocation_t1895107553), -1, sizeof(ConfigurationLocation_t1895107553_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable2914[7] =
{
ConfigurationLocation_t1895107553_StaticFields::get_offset_of_pathTrimChars_0(),
ConfigurationLocation_t1895107553::get_offset_of_path_1(),
ConfigurationLocation_t1895107553::get_offset_of_configuration_2(),
ConfigurationLocation_t1895107553::get_offset_of_parent_3(),
ConfigurationLocation_t1895107553::get_offset_of_xmlContent_4(),
ConfigurationLocation_t1895107553::get_offset_of_parentResolved_5(),
ConfigurationLocation_t1895107553::get_offset_of_allowOverride_6(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2915 = { sizeof (ConfigurationLocationCollection_t1903842989), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2916 = { sizeof (ConfigurationLockType_t131834733)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };
extern const int32_t g_FieldOffsetTable2916[4] =
{
ConfigurationLockType_t131834733::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)),
0,
0,
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2917 = { sizeof (ConfigurationLockCollection_t1011762925), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2917[6] =
{
ConfigurationLockCollection_t1011762925::get_offset_of_names_0(),
ConfigurationLockCollection_t1011762925::get_offset_of_element_1(),
ConfigurationLockCollection_t1011762925::get_offset_of_lockType_2(),
ConfigurationLockCollection_t1011762925::get_offset_of_is_modified_3(),
ConfigurationLockCollection_t1011762925::get_offset_of_valid_name_hash_4(),
ConfigurationLockCollection_t1011762925::get_offset_of_valid_names_5(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2918 = { sizeof (ConfigurationManager_t2608608455), -1, sizeof(ConfigurationManager_t2608608455_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable2918[3] =
{
ConfigurationManager_t2608608455_StaticFields::get_offset_of_configFactory_0(),
ConfigurationManager_t2608608455_StaticFields::get_offset_of_configSystem_1(),
ConfigurationManager_t2608608455_StaticFields::get_offset_of_lockobj_2(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2919 = { sizeof (ConfigurationPermission_t1611094853), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2919[1] =
{
ConfigurationPermission_t1611094853::get_offset_of_unrestricted_0(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2920 = { sizeof (ConfigurationPermissionAttribute_t1968770041), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2921 = { sizeof (ConfigurationProperty_t2048066811), -1, sizeof(ConfigurationProperty_t2048066811_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable2921[9] =
{
ConfigurationProperty_t2048066811_StaticFields::get_offset_of_NoDefaultValue_0(),
ConfigurationProperty_t2048066811::get_offset_of_name_1(),
ConfigurationProperty_t2048066811::get_offset_of_type_2(),
ConfigurationProperty_t2048066811::get_offset_of_default_value_3(),
ConfigurationProperty_t2048066811::get_offset_of_converter_4(),
ConfigurationProperty_t2048066811::get_offset_of_validation_5(),
ConfigurationProperty_t2048066811::get_offset_of_flags_6(),
ConfigurationProperty_t2048066811::get_offset_of_description_7(),
ConfigurationProperty_t2048066811::get_offset_of_collectionAttribute_8(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2922 = { sizeof (ConfigurationPropertyAttribute_t3655647199), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2922[3] =
{
ConfigurationPropertyAttribute_t3655647199::get_offset_of_name_0(),
ConfigurationPropertyAttribute_t3655647199::get_offset_of_default_value_1(),
ConfigurationPropertyAttribute_t3655647199::get_offset_of_flags_2(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2923 = { sizeof (ConfigurationPropertyCollection_t3473514151), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2923[1] =
{
ConfigurationPropertyCollection_t3473514151::get_offset_of_collection_0(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2924 = { sizeof (ConfigurationPropertyOptions_t3219689025)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };
extern const int32_t g_FieldOffsetTable2924[8] =
{
ConfigurationPropertyOptions_t3219689025::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)),
0,
0,
0,
0,
0,
0,
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2925 = { sizeof (ConfigurationSaveMode_t700320212)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };
extern const int32_t g_FieldOffsetTable2925[4] =
{
ConfigurationSaveMode_t700320212::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)),
0,
0,
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2926 = { sizeof (ConfigurationSection_t2600766927), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2926[4] =
{
ConfigurationSection_t2600766927::get_offset_of_sectionInformation_15(),
ConfigurationSection_t2600766927::get_offset_of_section_handler_16(),
ConfigurationSection_t2600766927::get_offset_of_externalDataXml_17(),
ConfigurationSection_t2600766927::get_offset_of__configContext_18(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2927 = { sizeof (ConfigurationSectionCollection_t4261113299), -1, sizeof(ConfigurationSectionCollection_t4261113299_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable2927[3] =
{
ConfigurationSectionCollection_t4261113299::get_offset_of_group_10(),
ConfigurationSectionCollection_t4261113299::get_offset_of_config_11(),
ConfigurationSectionCollection_t4261113299_StaticFields::get_offset_of_lockObject_12(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2928 = { sizeof (U3CGetEnumeratorU3Ed__17_t2724409453), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2928[4] =
{
U3CGetEnumeratorU3Ed__17_t2724409453::get_offset_of_U3CU3E1__state_0(),
U3CGetEnumeratorU3Ed__17_t2724409453::get_offset_of_U3CU3E2__current_1(),
U3CGetEnumeratorU3Ed__17_t2724409453::get_offset_of_U3CU3E4__this_2(),
U3CGetEnumeratorU3Ed__17_t2724409453::get_offset_of_U3CU3E7__wrap1_3(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2929 = { sizeof (ConfigurationSectionGroup_t2230982736), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2929[5] =
{
ConfigurationSectionGroup_t2230982736::get_offset_of_sections_0(),
ConfigurationSectionGroup_t2230982736::get_offset_of_groups_1(),
ConfigurationSectionGroup_t2230982736::get_offset_of_config_2(),
ConfigurationSectionGroup_t2230982736::get_offset_of_group_3(),
ConfigurationSectionGroup_t2230982736::get_offset_of_initialized_4(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2930 = { sizeof (ConfigurationSectionGroupCollection_t575145286), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2930[2] =
{
ConfigurationSectionGroupCollection_t575145286::get_offset_of_group_10(),
ConfigurationSectionGroupCollection_t575145286::get_offset_of_config_11(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2931 = { sizeof (ConfigurationUserLevel_t1204907851)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };
extern const int32_t g_FieldOffsetTable2931[4] =
{
ConfigurationUserLevel_t1204907851::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)),
0,
0,
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2932 = { sizeof (ConfigurationValidatorAttribute_t1007519140), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2932[2] =
{
ConfigurationValidatorAttribute_t1007519140::get_offset_of_validatorType_0(),
ConfigurationValidatorAttribute_t1007519140::get_offset_of_instance_1(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2933 = { sizeof (ConfigurationValidatorBase_t210547623), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2934 = { sizeof (DefaultSection_t3840532724), -1, sizeof(DefaultSection_t3840532724_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable2934[1] =
{
DefaultSection_t3840532724_StaticFields::get_offset_of_properties_19(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2935 = { sizeof (DefaultValidator_t300527515), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2936 = { sizeof (ElementInformation_t3165583784), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2936[3] =
{
ElementInformation_t3165583784::get_offset_of_propertyInfo_0(),
ElementInformation_t3165583784::get_offset_of_owner_1(),
ElementInformation_t3165583784::get_offset_of_properties_2(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2937 = { sizeof (ExeConfigurationFileMap_t1419586304), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2937[3] =
{
ExeConfigurationFileMap_t1419586304::get_offset_of_exeConfigFilename_1(),
ExeConfigurationFileMap_t1419586304::get_offset_of_localUserConfigFilename_2(),
ExeConfigurationFileMap_t1419586304::get_offset_of_roamingUserConfigFilename_3(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2938 = { sizeof (IgnoreSection_t681509237), -1, sizeof(IgnoreSection_t681509237_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable2938[2] =
{
IgnoreSection_t681509237::get_offset_of_xml_19(),
IgnoreSection_t681509237_StaticFields::get_offset_of_properties_20(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2939 = { sizeof (InternalConfigurationFactory_t3846641927), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2940 = { sizeof (InternalConfigurationSystem_t2108740756), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2940[3] =
{
InternalConfigurationSystem_t2108740756::get_offset_of_host_0(),
InternalConfigurationSystem_t2108740756::get_offset_of_root_1(),
InternalConfigurationSystem_t2108740756::get_offset_of_hostInitParams_2(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2941 = { sizeof (InternalConfigurationHost_t547577555), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2942 = { sizeof (ExeConfigurationHost_t2778769322), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2942[2] =
{
ExeConfigurationHost_t2778769322::get_offset_of_map_0(),
ExeConfigurationHost_t2778769322::get_offset_of_level_1(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2943 = { sizeof (InternalConfigurationRoot_t547578517), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2943[2] =
{
InternalConfigurationRoot_t547578517::get_offset_of_host_0(),
InternalConfigurationRoot_t547578517::get_offset_of_isDesignTime_1(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2944 = { sizeof (PropertyInformation_t2089433965), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2944[7] =
{
PropertyInformation_t2089433965::get_offset_of_isModified_0(),
PropertyInformation_t2089433965::get_offset_of_lineNumber_1(),
PropertyInformation_t2089433965::get_offset_of_source_2(),
PropertyInformation_t2089433965::get_offset_of_val_3(),
PropertyInformation_t2089433965::get_offset_of_origin_4(),
PropertyInformation_t2089433965::get_offset_of_owner_5(),
PropertyInformation_t2089433965::get_offset_of_property_6(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2945 = { sizeof (PropertyInformationCollection_t954922393), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2946 = { sizeof (PropertyInformationEnumerator_t1453501302), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2946[2] =
{
PropertyInformationEnumerator_t1453501302::get_offset_of_collection_0(),
PropertyInformationEnumerator_t1453501302::get_offset_of_position_1(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2947 = { sizeof (PropertyValueOrigin_t1217826846)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 };
extern const int32_t g_FieldOffsetTable2947[4] =
{
PropertyValueOrigin_t1217826846::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)),
0,
0,
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2948 = { sizeof (ProtectedConfiguration_t1807950812), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2949 = { sizeof (ProtectedConfigurationProvider_t3971982415), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2950 = { sizeof (ProtectedConfigurationProviderCollection_t388338823), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2951 = { sizeof (ProtectedConfigurationSection_t3541826375), -1, sizeof(ProtectedConfigurationSection_t3541826375_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable2951[4] =
{
ProtectedConfigurationSection_t3541826375_StaticFields::get_offset_of_defaultProviderProp_19(),
ProtectedConfigurationSection_t3541826375_StaticFields::get_offset_of_providersProp_20(),
ProtectedConfigurationSection_t3541826375_StaticFields::get_offset_of_properties_21(),
ProtectedConfigurationSection_t3541826375::get_offset_of_providers_22(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2952 = { sizeof (ProviderSettings_t873049714), -1, sizeof(ProviderSettings_t873049714_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable2952[4] =
{
ProviderSettings_t873049714::get_offset_of_parameters_15(),
ProviderSettings_t873049714_StaticFields::get_offset_of_nameProp_16(),
ProviderSettings_t873049714_StaticFields::get_offset_of_typeProp_17(),
ProviderSettings_t873049714_StaticFields::get_offset_of_properties_18(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2953 = { sizeof (ProviderSettingsCollection_t585304908), -1, sizeof(ProviderSettingsCollection_t585304908_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable2953[1] =
{
ProviderSettingsCollection_t585304908_StaticFields::get_offset_of_props_25(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2954 = { sizeof (SectionInfo_t1739019515), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2954[5] =
{
SectionInfo_t1739019515::get_offset_of_allowLocation_6(),
SectionInfo_t1739019515::get_offset_of_requirePermission_7(),
SectionInfo_t1739019515::get_offset_of_restartOnExternalChanges_8(),
SectionInfo_t1739019515::get_offset_of_allowDefinition_9(),
SectionInfo_t1739019515::get_offset_of_allowExeDefinition_10(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2955 = { sizeof (SectionGroupInfo_t2346323570), -1, sizeof(SectionGroupInfo_t2346323570_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable2955[4] =
{
SectionGroupInfo_t2346323570::get_offset_of_modified_6(),
SectionGroupInfo_t2346323570::get_offset_of_sections_7(),
SectionGroupInfo_t2346323570::get_offset_of_groups_8(),
SectionGroupInfo_t2346323570_StaticFields::get_offset_of_emptyList_9(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2956 = { sizeof (ConfigInfoCollection_t3264723080), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2957 = { sizeof (SectionInformation_t2754609709), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2957[13] =
{
SectionInformation_t2754609709::get_offset_of_parent_0(),
SectionInformation_t2754609709::get_offset_of_allow_definition_1(),
SectionInformation_t2754609709::get_offset_of_allow_exe_definition_2(),
SectionInformation_t2754609709::get_offset_of_allow_location_3(),
SectionInformation_t2754609709::get_offset_of_allow_override_4(),
SectionInformation_t2754609709::get_offset_of_inherit_on_child_apps_5(),
SectionInformation_t2754609709::get_offset_of_restart_on_external_changes_6(),
SectionInformation_t2754609709::get_offset_of_require_permission_7(),
SectionInformation_t2754609709::get_offset_of_config_source_8(),
SectionInformation_t2754609709::get_offset_of_name_9(),
SectionInformation_t2754609709::get_offset_of_raw_xml_10(),
SectionInformation_t2754609709::get_offset_of_protection_provider_11(),
SectionInformation_t2754609709::get_offset_of_U3CConfigFilePathU3Ek__BackingField_12(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2958 = { sizeof (ProviderBase_t2882126354), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2958[3] =
{
ProviderBase_t2882126354::get_offset_of_alreadyInitialized_0(),
ProviderBase_t2882126354::get_offset_of__description_1(),
ProviderBase_t2882126354::get_offset_of__name_2(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2959 = { sizeof (ProviderCollection_t2548499159), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2959[3] =
{
ProviderCollection_t2548499159::get_offset_of_lookup_0(),
ProviderCollection_t2548499159::get_offset_of_readOnly_1(),
ProviderCollection_t2548499159::get_offset_of_values_2(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2960 = { 0, -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2961 = { 0, -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2962 = { 0, -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2963 = { 0, -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2964 = { 0, -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2965 = { 0, -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2966 = { sizeof (U3CPrivateImplementationDetailsU3E_t1486305141), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2967 = { sizeof (U3CModuleU3E_t3783534219), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2968 = { sizeof (SR_t2523137206), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2969 = { sizeof (AesManaged_t3721278648), -1, 0, 0 };
extern const int32_t g_FieldOffsetTable2969[1] =
{
AesManaged_t3721278648::get_offset_of_m_rijndael_11(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2970 = { sizeof (AesCryptoServiceProvider_t1359258894), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2971 = { sizeof (AesTransform_t3733702461), -1, sizeof(AesTransform_t3733702461_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable2971[14] =
{
AesTransform_t3733702461::get_offset_of_expandedKey_12(),
AesTransform_t3733702461::get_offset_of_Nk_13(),
AesTransform_t3733702461::get_offset_of_Nr_14(),
AesTransform_t3733702461_StaticFields::get_offset_of_Rcon_15(),
AesTransform_t3733702461_StaticFields::get_offset_of_SBox_16(),
AesTransform_t3733702461_StaticFields::get_offset_of_iSBox_17(),
AesTransform_t3733702461_StaticFields::get_offset_of_T0_18(),
AesTransform_t3733702461_StaticFields::get_offset_of_T1_19(),
AesTransform_t3733702461_StaticFields::get_offset_of_T2_20(),
AesTransform_t3733702461_StaticFields::get_offset_of_T3_21(),
AesTransform_t3733702461_StaticFields::get_offset_of_iT0_22(),
AesTransform_t3733702461_StaticFields::get_offset_of_iT1_23(),
AesTransform_t3733702461_StaticFields::get_offset_of_iT2_24(),
AesTransform_t3733702461_StaticFields::get_offset_of_iT3_25(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2972 = { sizeof (Error_t3199922586), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2973 = { sizeof (Enumerable_t2148412300), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2974 = { 0, 0, 0, 0 };
extern const int32_t g_FieldOffsetTable2974[3] =
{
0,
0,
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2975 = { 0, 0, 0, 0 };
extern const int32_t g_FieldOffsetTable2975[3] =
{
0,
0,
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2976 = { 0, 0, 0, 0 };
extern const int32_t g_FieldOffsetTable2976[2] =
{
0,
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2977 = { 0, 0, 0, 0 };
extern const int32_t g_FieldOffsetTable2977[3] =
{
0,
0,
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2978 = { 0, 0, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2979 = { 0, 0, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2980 = { 0, 0, 0, 0 };
extern const int32_t g_FieldOffsetTable2980[1] =
{
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2981 = { sizeof (Utilities_t1477630460), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2982 = { 0, 0, 0, 0 };
extern const int32_t g_FieldOffsetTable2982[2] =
{
0,
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2983 = { 0, 0, 0, 0 };
extern const int32_t g_FieldOffsetTable2983[2] =
{
0,
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2984 = { sizeof (EnumerableHelpers_t1509421933), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2985 = { 0, 0, 0, 0 };
extern const int32_t g_FieldOffsetTable2985[6] =
{
0,
0,
0,
0,
0,
0,
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2986 = { sizeof (U3CPrivateImplementationDetailsU3E_t1486305142), -1, sizeof(U3CPrivateImplementationDetailsU3E_t1486305142_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable2986[11] =
{
U3CPrivateImplementationDetailsU3E_t1486305142_StaticFields::get_offset_of_U30AA802CD6847EB893FE786B5EA5168B2FDCD7B93_0(),
U3CPrivateImplementationDetailsU3E_t1486305142_StaticFields::get_offset_of_U30C4110BC17D746F018F47B49E0EB0D6590F69939_1(),
U3CPrivateImplementationDetailsU3E_t1486305142_StaticFields::get_offset_of_U320733E1283D873EBE47133A95C233E11B76F5F11_2(),
U3CPrivateImplementationDetailsU3E_t1486305142_StaticFields::get_offset_of_U321F4CBF8283FF1CAEB4A39316A97FC1D6DF1D35E_3(),
U3CPrivateImplementationDetailsU3E_t1486305142_StaticFields::get_offset_of_U323DFDCA6F045D4257BF5AC8CB1CF2EFADAFE9B94_4(),
U3CPrivateImplementationDetailsU3E_t1486305142_StaticFields::get_offset_of_U330A0358B25B1372DD598BB4B1AC56AD6B8F08A47_5(),
U3CPrivateImplementationDetailsU3E_t1486305142_StaticFields::get_offset_of_U35B5DF5A459E902D96F7DB0FB235A25346CA85C5D_6(),
U3CPrivateImplementationDetailsU3E_t1486305142_StaticFields::get_offset_of_U35BE411F1438EAEF33726D855E99011D5FECDDD4E_7(),
U3CPrivateImplementationDetailsU3E_t1486305142_StaticFields::get_offset_of_U38F22C9ECE1331718CBD268A9BBFD2F5E451441E3_8(),
U3CPrivateImplementationDetailsU3E_t1486305142_StaticFields::get_offset_of_A02DD1D8604EA8EC2D2BDA717A93A4EE85F13E53_9(),
U3CPrivateImplementationDetailsU3E_t1486305142_StaticFields::get_offset_of_AE2F76ECEF8B08F0BC7EA95DCFE945E1727927C9_10(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2987 = { sizeof (__StaticArrayInitTypeSizeU3D120_t1468992141)+ sizeof (RuntimeObject), sizeof(__StaticArrayInitTypeSizeU3D120_t1468992141 ), 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2988 = { sizeof (__StaticArrayInitTypeSizeU3D256_t3653428462)+ sizeof (RuntimeObject), sizeof(__StaticArrayInitTypeSizeU3D256_t3653428462 ), 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2989 = { sizeof (__StaticArrayInitTypeSizeU3D1024_t3477315116)+ sizeof (RuntimeObject), sizeof(__StaticArrayInitTypeSizeU3D1024_t3477315116 ), 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2990 = { sizeof (U3CModuleU3E_t3783534220), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2991 = { sizeof (Application_t354826772), -1, sizeof(Application_t354826772_StaticFields), 0 };
extern const int32_t g_FieldOffsetTable2991[4] =
{
Application_t354826772_StaticFields::get_offset_of_lowMemory_0(),
Application_t354826772_StaticFields::get_offset_of_s_LogCallbackHandler_1(),
Application_t354826772_StaticFields::get_offset_of_s_LogCallbackHandlerThreaded_2(),
Application_t354826772_StaticFields::get_offset_of_onBeforeRender_3(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2992 = { sizeof (LowMemoryCallback_t642977590), sizeof(Il2CppMethodPointer), 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2993 = { sizeof (LogCallback_t1867914413), sizeof(Il2CppMethodPointer), 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2994 = { sizeof (AssetBundleCreateRequest_t1038783543), sizeof(AssetBundleCreateRequest_t1038783543_marshaled_pinvoke), 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2995 = { sizeof (AssetBundleRequest_t2674559435), sizeof(AssetBundleRequest_t2674559435_marshaled_pinvoke), 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2996 = { sizeof (AsyncOperation_t3814632279), sizeof(AsyncOperation_t3814632279_marshaled_pinvoke), 0, 0 };
extern const int32_t g_FieldOffsetTable2996[2] =
{
AsyncOperation_t3814632279::get_offset_of_m_Ptr_0(),
AsyncOperation_t3814632279::get_offset_of_m_completeCallback_1(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2997 = { sizeof (WaitForSeconds_t3839502067), sizeof(WaitForSeconds_t3839502067_marshaled_pinvoke), 0, 0 };
extern const int32_t g_FieldOffsetTable2997[1] =
{
WaitForSeconds_t3839502067::get_offset_of_m_Seconds_0(),
};
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2998 = { sizeof (WaitForFixedUpdate_t3968615785), -1, 0, 0 };
extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2999 = { sizeof (WaitForEndOfFrame_t1785723201), -1, 0, 0 };
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| 43.683708 | 234 | 0.835062 | [
"object"
] |
2e6945620b60721683ce38485e156a6488851444 | 3,820 | cpp | C++ | Src/HLSL/DxilSignatureElement.cpp | gongminmin/Dilithium | 976ce6d6420e45ac3088fe345793bfca80cd3acd | [
"MIT"
] | 178 | 2017-02-08T14:08:56.000Z | 2022-02-22T02:19:44.000Z | Src/HLSL/DxilSignatureElement.cpp | gongminmin/Dilithium | 976ce6d6420e45ac3088fe345793bfca80cd3acd | [
"MIT"
] | 7 | 2017-02-09T08:19:29.000Z | 2021-09-13T14:28:09.000Z | Src/HLSL/DxilSignatureElement.cpp | gongminmin/Dilithium | 976ce6d6420e45ac3088fe345793bfca80cd3acd | [
"MIT"
] | 15 | 2017-02-14T09:42:25.000Z | 2021-12-16T15:49:17.000Z | /**
* @file DxilSignatureElement.cpp
* @author Minmin Gong
*
* @section DESCRIPTION
*
* This source file is part of Dilithium
* For the latest info, see https://github.com/gongminmin/Dilithium
*
* @section LICENSE
*
* The MIT License (MIT)
*
* Copyright (c) 2017 Minmin Gong. 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 <Dilithium/Dilithium.hpp>
#include <Dilithium/dxc/HLSL/DxilSignatureElement.hpp>
#include <Dilithium/dxc/HLSL/DxilSigPoint.hpp>
#include <climits>
namespace Dilithium
{
DxilSignatureElement::DxilSignatureElement(SigPointKind kind)
: sig_point_kind_(kind),
semantic_(nullptr),
id_(std::numeric_limits<uint32_t>::max()),
interp_mode_(InterpolationMode::Invalid),
comp_type_(ComponentType::Invalid),
rows_(0), cols_(0),
start_row_(DxilSemantic::UNDEFINED_ROW), start_col_(DxilSemantic::UNDEFINED_COL)
{
}
DxilSignatureElement::~DxilSignatureElement()
{
}
void DxilSignatureElement::Initialize(std::string_view name, DxilCompType const & elem_type, DxilInterpolationMode interp_mode,
uint32_t rows, uint32_t cols,
int start_row, int start_col,
uint32_t id, std::vector<uint32_t> const & index_vec)
{
BOOST_ASSERT_MSG(semantic_ == nullptr, "An instance should be initiazed only once");
id_ = id;
name_ = std::string(name);
DxilSemantic::DecomposeNameAndIndex(name, &semantic_name_, &semantic_start_index_);
if (!index_vec.empty())
{
semantic_start_index_ = index_vec[0];
}
// Find semantic in the table.
semantic_ = DxilSemantic::GetByName(semantic_name_, sig_point_kind_);
comp_type_ = elem_type;
interp_mode_ = interp_mode;
semantic_index_ = index_vec;
rows_ = rows;
cols_ = cols;
start_row_ = start_row;
start_col_ = start_col;
output_stream_ = 0;
}
ShaderKind DxilSignatureElement::GetShaderKind() const
{
return DxilSigPoint::GetSigPoint(sig_point_kind_)->GetShaderKind();
}
bool DxilSignatureElement::IsInput() const
{
return DxilSigPoint::GetSigPoint(sig_point_kind_)->IsInput();
}
bool DxilSignatureElement::IsOutput() const
{
return DxilSigPoint::GetSigPoint(sig_point_kind_)->IsOutput();
}
bool DxilSignatureElement::IsPatchConstant() const
{
return DxilSigPoint::GetSigPoint(sig_point_kind_)->IsPatchConstant();
}
char const * DxilSignatureElement::GetName() const
{
if (this->IsArbitrary())
{
return name_.c_str();
}
else if (!semantic_->IsInvalid())
{
return semantic_->GetName();
}
else
{
return name_.c_str();
}
}
void DxilSignatureElement::SetKind(SemanticKind kind)
{
// recover the original SigPointKind if necessary (for Shadow element).
sig_point_kind_ = DxilSigPoint::RecoverKind(kind, sig_point_kind_);
semantic_ = DxilSemantic::Get(kind, sig_point_kind_);
}
}
| 30.07874 | 128 | 0.745812 | [
"vector"
] |
2e6da3419132fff50da44df47df8a7035a1f0720 | 2,610 | hpp | C++ | cybex_ios_core_cpp/include/bitshare/include/cybex/crowdfund.hpp | CybexDex/cybex-ios-core-cpp | 6d6e446180dba9f302bd5296942a2b17289ed949 | [
"MIT"
] | null | null | null | cybex_ios_core_cpp/include/bitshare/include/cybex/crowdfund.hpp | CybexDex/cybex-ios-core-cpp | 6d6e446180dba9f302bd5296942a2b17289ed949 | [
"MIT"
] | null | null | null | cybex_ios_core_cpp/include/bitshare/include/cybex/crowdfund.hpp | CybexDex/cybex-ios-core-cpp | 6d6e446180dba9f302bd5296942a2b17289ed949 | [
"MIT"
] | 2 | 2018-10-10T13:39:01.000Z | 2020-12-15T13:23:56.000Z | /*
* Copyright (c) 2015 Cryptonomex, Inc., and contributors.
*
* The MIT License
*
* 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.
*/
#pragma once
#include <graphene/chain/database.hpp>
#include <graphene/chain/protocol/base.hpp>
namespace graphene { namespace chain {
class crowdfund_object : public abstract_object<crowdfund_object>
{
public:
static const uint8_t space_id = protocol_ids;
static const uint8_t type_id = crowdfund_object_type;
account_id_type owner;
asset_id_type asset_id;
time_point_sec begin;
uint32_t t;
uint32_t u;
share_type V;
double p(uint32_t s) const;
asset_id_type asset_type()const { return asset_id; }
};
struct by_owner;
/**
* @ingroup object_index
*/
using crowdfund_multi_index_type = multi_index_container<
crowdfund_object,
indexed_by<
ordered_unique< tag<by_id>, member< object, object_id_type, &object::id > >,
ordered_non_unique< tag<by_owner>, composite_key<
crowdfund_object,
member<crowdfund_object, account_id_type, &crowdfund_object::owner>,
const_mem_fun<crowdfund_object, asset_id_type, &crowdfund_object::asset_type>
> >
>
>;
/**
* @ingroup object_index
*/
using crowdfund_index = generic_index<crowdfund_object, crowdfund_multi_index_type>;
} }
FC_REFLECT_DERIVED( graphene::chain::crowdfund_object, (graphene::db::object),
(owner)(asset_id)(begin)(t) (u)(V))
| 35.753425 | 89 | 0.696552 | [
"object"
] |
2e78fab9f58da1d51ef0c5d658446b79d4a8eeab | 5,363 | cpp | C++ | src/Shader.cpp | DanonOfficial/ScreenSpaceReflection | 186d0937b033db11e81bf91e624634b3ca1bc538 | [
"MIT"
] | 1 | 2021-03-27T19:20:31.000Z | 2021-03-27T19:20:31.000Z | src/Shader.cpp | RoundedGlint585/ScreenSpaceReflection | 186d0937b033db11e81bf91e624634b3ca1bc538 | [
"MIT"
] | 1 | 2021-04-09T18:48:38.000Z | 2021-04-18T11:27:35.000Z | src/Shader.cpp | RoundedGlint585/ScreenSpaceReflection | 186d0937b033db11e81bf91e624634b3ca1bc538 | [
"MIT"
] | 1 | 2021-03-27T19:20:38.000Z | 2021-03-27T19:20:38.000Z | //
// Created by roundedglint585 on 8/1/19.
//
#include "../include/Shader.h"
#include <iostream>
Shader::Shader(const std::string & vertexShaderData, const std::string & fragmentShaderData) : shaderID_(-1) {
uint32_t vertexShader = compileVertexShader(vertexShaderData);
uint32_t fragmentShader = compileFragmentShader(fragmentShaderData);
linkShader(vertexShader, fragmentShader);
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
}
uint32_t Shader::compileVertexShader(const std::string &vertexShaderData) {
uint32_t vertexShader = glCreateShader(GL_VERTEX_SHADER);
const char* vertexShaderSource = vertexShaderData.c_str();
glShaderSource(vertexShader, 1, &vertexShaderSource, nullptr);
glCompileShader(vertexShader);
int success;
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
if(!success){
char infoLog[512];
glGetShaderInfoLog(vertexShader, 512, nullptr, infoLog);
std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl;
};
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
return vertexShader;
}
uint32_t Shader::compileFragmentShader(const std::string & fragmentShaderData) {
uint32_t fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
const char* fragmentShaderSource = fragmentShaderData.c_str();
glShaderSource(fragmentShader, 1, &fragmentShaderSource, nullptr);
glCompileShader(fragmentShader);
int success;
glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);
if(!success){
char infoLog[512];
glGetShaderInfoLog(fragmentShader, 512, nullptr, infoLog);
std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl;
};
glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);
return fragmentShader;
}
void Shader::linkShader(uint32_t vertexShader, uint32_t fragmentShader) {
shaderID_ = glCreateProgram();
glAttachShader(shaderID_, vertexShader);
glAttachShader(shaderID_, fragmentShader);
glLinkProgram(shaderID_);
int success;
glGetShaderiv(shaderID_, GL_COMPILE_STATUS, &success);
}
std::string Shader::getFile(std::string_view path) const {
std::ifstream file(&path.front(), std::ios::binary | std::ios::ate);
if (file) {
uint64_t fileSize = file.tellg();
file.seekg(std::ios::beg);
std::string result(fileSize, 0);
file.read(result.data(), fileSize);
return result;
}
return {};
}
void Shader::use() const {
glUseProgram(shaderID_);
}
void Shader::setBool(std::string_view name, bool value) const {
glUniform1i(glGetUniformLocation(shaderID_, name.data()), (int) value);
}
void Shader::setInt(std::string_view name, int value) const {
glUniform1i(glGetUniformLocation(shaderID_, name.data()), value);
}
void Shader::setFloat(std::string_view name, float value) const {
glUniform1f(glGetUniformLocation(shaderID_, name.data()), value);
}
void Shader::setVec2(std::string_view name, const glm::vec2 &value) const {
glUniform2fv(glGetUniformLocation(shaderID_, name.data()), 1, &value[0]);
}
void Shader::setVec2(std::string_view name, float x, float y) const {
glUniform2f(glGetUniformLocation(shaderID_, name.data()), x, y);
}
void Shader::setVec3(std::string_view name, const glm::vec3 &value) const {
glUniform3fv(glGetUniformLocation(shaderID_, name.data()), 1, &value[0]);
}
void Shader::setVec3(std::string_view name, float x, float y, float z) const {
glUniform3f(glGetUniformLocation(shaderID_, name.data()), x, y, z);
}
void Shader::setVec4(std::string_view name, const glm::vec4 &value) const {
glUniform4fv(glGetUniformLocation(shaderID_, name.data()), 1, &value[0]);
}
void Shader::setVec4(std::string_view name, float x, float y, float z, float w) {
glUniform4f(glGetUniformLocation(shaderID_, name.data()), x, y, z, w);
}
void Shader::setMat2(std::string_view name, const glm::mat2 &mat) const {
glUniformMatrix2fv(glGetUniformLocation(shaderID_, name.data()), 1, GL_FALSE, &mat[0][0]);
}
void Shader::setMat3(std::string_view name, const glm::mat3 &mat) const {
glUniformMatrix3fv(glGetUniformLocation(shaderID_, name.data()), 1, GL_FALSE, &mat[0][0]);
}
void Shader::setMat4(std::string_view name, const glm::mat4 &mat) const {
glUniformMatrix4fv(glGetUniformLocation(shaderID_, name.data()), 1, GL_FALSE, &mat[0][0]);
}
void Shader::setFloatArray(std::string_view name, const std::vector<float> &data) const {
glUniform1fv(glGetUniformLocation(shaderID_, name.data()), data.size(), data.data());
}
Shader Shader::fromRawData(const std::string &vertexShaderData, const std::string &fragmentShaderData) {
return Shader(vertexShaderData, fragmentShaderData);
}
Shader Shader::fromFile(const std::string &vertexShaderPath, const std::string &fragmentShaderPath) {
auto result = Shader();
std::string vertexShaderData = result.getFile(vertexShaderPath);
std::string fragmentShaderData = result.getFile(fragmentShaderPath);
uint32_t vertexShader = result.compileVertexShader(vertexShaderData);
uint32_t fragmentShader = result.compileFragmentShader(fragmentShaderData);
result.linkShader(vertexShader, fragmentShader);
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
return result;
}
| 38.307143 | 110 | 0.727764 | [
"vector"
] |
2e7c1543ed7838456a76b72cfa415d0ff798d0c8 | 5,146 | cpp | C++ | src/main.cpp | olciaczekswiraczek/OpenGLPAG | 79ef7a09f7cd6b356f8764377cf8e0258f78dad8 | [
"MIT"
] | null | null | null | src/main.cpp | olciaczekswiraczek/OpenGLPAG | 79ef7a09f7cd6b356f8764377cf8e0258f78dad8 | [
"MIT"
] | null | null | null | src/main.cpp | olciaczekswiraczek/OpenGLPAG | 79ef7a09f7cd6b356f8764377cf8e0258f78dad8 | [
"MIT"
] | null | null | null |
#include <corecrt_math_defines.h>
#include <iostream>
#include "imgui.h"
#include "imgui_impl_glfw.h"
#include "imgui_impl_opengl3.h"
#include "glm/glm.hpp"
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include "Window.h"
#include "ShaderProgram.h"
#include "Texture.h"
#include "Cube.h"
void framebuffer_size_callback(GLFWwindow* window, int width, int height);
void Menger(int level, GLfloat x, GLfloat y, GLfloat z, GLfloat edgeLength);
// settings
const unsigned int SCR_WIDTH = 800;
const unsigned int SCR_HEIGHT = 600;
const char* glsl_version = "#version 430";
int main()
{
Window window(SCR_WIDTH, SCR_HEIGHT, "Menger Sponge");
glfwSetFramebufferSizeCallback(window.getWindow(), framebuffer_size_callback);
// Setup Dear ImGui context
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
// Setup Platform/Renderer bindings
ImGui_ImplGlfw_InitForOpenGL(window.getWindow(), true);
ImGui_ImplOpenGL3_Init(glsl_version);
// Setup Dear ImGui style
ImGui::StyleColorsDark();
std::vector <Cube> mengerSponge;
std::shared_ptr<Shader> vertexShader(new Shader("shader.vert", VERTEX_SHADER));
std::shared_ptr<Shader> fragmentShader(new Shader("shader.frag", FRAGMENT_SHADER));
ShaderProgram shaderProgram(vertexShader, fragmentShader);
Texture texture1("texture1.jpg");
Texture texture2("texture2.jpg");
// configure global opengl state
glEnable(GL_DEPTH_TEST);
glm::mat4 view = glm::mat4(1.0f);
glm::mat4 projection = glm::mat4(1.0f);
view = glm::translate(view, glm::vec3(0.0f, 0.0f, -2.0f)); //tak naprawde przesuwamy obiekty, a nie kamere
view = glm::rotate(view, glm::radians(45.0f), glm::vec3(1.0f, 1.0f, 1.0f));
projection = glm::perspective(glm::radians(45.0f), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 1000.0f);
// render loop
while (window.isOpen())
{
glfwPollEvents(); //poll IO events (keys pressed/released, mouse moved etc.)
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// feed inputs to dear imgui, start new frame
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
//drawing
texture1.Use(0);
//texture2.Use(1);
shaderProgram.Use();
glm::mat4 model = glm::mat4(1.0f);
//obrot wokol osi z
// model - glm::translate(model, glm::vec3(0.5f, 0.2f, 0.0)); //przesuwa pivot, kolejnosc transformacji ma znaczenie
// render your GUI
ImGui::Begin("Cube Rotation/Color");
static int level;
ImGui::SliderInt("Level", &level, 0, 3);
Menger(level, 0.0f, 0.0f, 0.0f, 1.0f);
static float rotationOX = 0.0f;
ImGui::SliderFloat("Rotation OX", &rotationOX, 0.0f, 1.0f);
model = glm::rotate(model, glm::radians(rotationOX * 360.f), glm::vec3(1.0f, 0.0f, 0.0f));
static float rotationOY = 0.0f;
ImGui::SliderFloat("Rotation OY", &rotationOY, 0.0f, 1.0f);
model = glm::rotate(model, glm::radians(rotationOY * 360.f), glm::vec3(0.0f, 1.0f, 0.0f));
static float color[4] = { 1.0f,1.0f,1.0f,1.0f };
// color picker
ImGui::ColorEdit3("color", color);
// multiply triangle's color with this color
shaderProgram.setColor(glm::vec4(color[0], color[1], color[2], 1.0f));
ImGui::End();
glUniformMatrix4fv(glGetUniformLocation(shaderProgram.getProgram(), "model"), 1, GL_FALSE, glm::value_ptr(model));
glUniformMatrix4fv(glGetUniformLocation(shaderProgram.getProgram(), "view"), 1, GL_FALSE, glm::value_ptr(view));
glUniformMatrix4fv(glGetUniformLocation(shaderProgram.getProgram(), "projection"), 1, GL_FALSE, glm::value_ptr(projection));
// Render dear imgui into screen
ImGui::Render();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
glfwSwapBuffers(window.getWindow());
}
ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplGlfw_Shutdown();
ImGui::DestroyContext();
// glfw: terminate, clearing all previously allocated GLFW resources.
glfwTerminate();
return 0;
}
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
// make sure the viewport matches the new window dimensions; note that width and
// height will be significantly larger than specified on retina displays.
glViewport(0, 0, width, height);
}
void Menger(int level, GLfloat x, GLfloat y, GLfloat z, GLfloat edgeLength)
{
if (level == 0)
{
Cube cube(x, y, z, edgeLength);
cube.Draw();
}
else
{
for (int i = -1; i <= 1; i++)
{
for (int j = -1; j <= 1; j++)
{
for (int k = -1; k <= 1; k++)
{
if (((i * i + j * j) * (i * i + k * k) * (j * j + k * k)) > 0)
Menger(level - 1, x + i * edgeLength / 3, y + j * edgeLength / 3, z + k * edgeLength / 3, edgeLength / 3);
}
}
}
}
} | 31.765432 | 132 | 0.629421 | [
"render",
"vector",
"model"
] |
2e8224d3a93f775a7d1d09d7eceae156a80de828 | 2,136 | hpp | C++ | Vasniktel/cpp/include/dlinked_list/dlinked_list.hpp | 2-men-team/dictionary | 3a0e4876f4953a3d2d11bacb19549ebec6886c52 | [
"MIT"
] | 1 | 2018-04-17T14:39:46.000Z | 2018-04-17T14:39:46.000Z | Vasniktel/cpp/include/dlinked_list/dlinked_list.hpp | 2-men-team/dictionary | 3a0e4876f4953a3d2d11bacb19549ebec6886c52 | [
"MIT"
] | null | null | null | Vasniktel/cpp/include/dlinked_list/dlinked_list.hpp | 2-men-team/dictionary | 3a0e4876f4953a3d2d11bacb19549ebec6886c52 | [
"MIT"
] | 1 | 2018-10-28T20:17:38.000Z | 2018-10-28T20:17:38.000Z | #ifndef _DLINKED_LIST_HPP_
#define _DLINKED_LIST_HPP_
#include <cstddef>
#include <ostream>
#include <stdexcept>
#include <vector>
#include <algorithm>
#include <functional>
#include <utility>
template <typename ValType, bool looped = false>
class DLinkedList;
template <typename ValType, bool looped>
std::ostream& operator<<(std::ostream&, const DLinkedList<ValType, looped>&);
template <typename ValType, bool looped>
class DLinkedList {
private:
struct Node {
ValType data;
Node* next;
Node* prev;
Node(const ValType&, Node* = nullptr, Node* = nullptr);
bool operator==(const Node&) const;
bool operator==(const ValType&) const;
bool operator!=(const Node&) const;
bool operator!=(const ValType&) const;
};
Node* _first = nullptr;
Node* _last = nullptr;
std::size_t _size = 0;
public:
DLinkedList();
DLinkedList(const DLinkedList&);
DLinkedList(DLinkedList&&);
DLinkedList& operator=(const DLinkedList&);
DLinkedList& operator=(DLinkedList&&);
~DLinkedList();
DLinkedList& clear();
long indexOf(const ValType&) const;
ValType remove(std::size_t);
DLinkedList& insert(const ValType&, std::size_t);
DLinkedList& insertFront(const ValType&);
DLinkedList& insertBack(const ValType&);
DLinkedList& append(const DLinkedList&);
bool has(const ValType&) const;
std::size_t size() const;
bool empty() const;
friend std::ostream& operator<< <ValType, looped> (std::ostream&, const DLinkedList&);
DLinkedList& sort(const std::function<bool(const ValType&, const ValType&)>& = [](const ValType& a, const ValType& b) {
return a < b;
});
bool each(const std::function<bool(const ValType&, std::size_t)>&) const;
DLinkedList map(const std::function<ValType(const ValType&, std::size_t)>&) const;
DLinkedList filter(const std::function<bool(const ValType&, std::size_t)>&) const;
ValType& operator[](std::size_t);
ValType operator[](std::size_t) const;
bool operator==(const DLinkedList&) const;
bool operator!=(const DLinkedList&) const;
std::size_t count(const ValType&) const;
};
#include "node.tpp"
#include "dlinked_list.tpp"
#endif
| 29.260274 | 121 | 0.708801 | [
"vector"
] |
2e835f2ae375c0ee9da48f44ce71ecaf451adbdd | 5,235 | cpp | C++ | PostProcessor/Animation.cpp | MingAtUWA/SimpleMPM | 46a0e48028b7d6258f452f9cbee6195bb7f6aa41 | [
"MIT"
] | null | null | null | PostProcessor/Animation.cpp | MingAtUWA/SimpleMPM | 46a0e48028b7d6258f452f9cbee6195bb7f6aa41 | [
"MIT"
] | null | null | null | PostProcessor/Animation.cpp | MingAtUWA/SimpleMPM | 46a0e48028b7d6258f452f9cbee6195bb7f6aa41 | [
"MIT"
] | null | null | null | #include "PostProcessor_pcp.h"
#include "gif.h"
#include "Animation.h"
void Animation::PlayAnimationEvent::
Execute(vtkObject *caller, unsigned long eventId, void *callData)
{
animation->play_animation();
}
void Animation::RenderFrameTimerEvent::
Execute(vtkObject * caller, unsigned long eventId, void * callData)
{
// display previous frame (swap previous frame out of buffer)
animation->display_frame();
// render next frame
animation->render_frame();
}
Animation::Animation(double animation_time, vtkRenderWindowInteractor *win_iter) :
is_playing(false),
cur_sim_time(0.0), cur_ani_time(0.0),
total_sim_time(0.0), total_ani_time(animation_time),
ani_sim_ratio(0.0), frame_num(0),
window(win_iter->GetRenderWindow()), interactor(win_iter), frame(nullptr),
need_export_animation(false),
timer_id(0),
gif_writer(nullptr)
{
play_animation_event->animation = this;
render_frame_timer_event->animation = this;
interactor->AddObserver(Animation::PlayAnimation,
static_cast<vtkCommand *>(play_animation_event));
interactor->AddObserver(vtkCommand::TimerEvent,
static_cast<vtkCommand *>(render_frame_timer_event));
}
Animation::~Animation()
{
complete_animation();
interactor->RemoveObserver(static_cast<vtkCommand *>(play_animation_event));
interactor->RemoveObserver(static_cast<vtkCommand *>(render_frame_timer_event));
}
/*-------------------------------------------------------------------------------
* The coordinate system of gif is from left to right, from top to bottom, while
* the coordiante system of VTK window is from left to right, from bottom tp top.
* Therefore the buffer need to be reordered when transferred between different
* source.
--------------------------------------------------------------------------------*/
void reorder_buffer(unsigned char *RGBA_data, int width, int height)
{
// RGBA data are 4 bytes long
long *data = reinterpret_cast<long *>(RGBA_data);
long *line1 = data;
long *line2 = data + (height - 1) * width;
long data_tmp;
while (line1 < line2)
{
for (size_t i = 0; i < width; i++)
{
data_tmp = line1[i];
line1[i] = line2[i];
line2[i] = data_tmp;
}
line1 += width;
line2 -= width;
}
}
int Animation::render_frame(void)
{
remove_frame_from_window();
if (!is_playing)
{
complete_animation();
return 0;
}
// finish animation
if (next_frame_index >= frame_num)
{
complete_animation();
return 0;
}
start_rendering_time = std::chrono::system_clock::now();;
cur_frame_index = next_frame_index;
cur_ani_time = next_ani_time;
cur_sim_time = next_sim_time;
// create scenario to be rendered
frame = render_frame(cur_frame_index);
if (frame)
{
window->AddRenderer(frame);
frame->ResetCamera();
}
// Render without displaying
window->SwapBuffersOff();
window->Render();
window->SwapBuffersOn();
//if (frame_index == 0)
// window->Frame();
complete_rendering_time = std::chrono::system_clock::now();
std::chrono::duration<double> rendering_time = complete_rendering_time - start_rendering_time;
double diff_time = inc_ani_time - rendering_time.count();
if (timer_id) interactor->DestroyTimer(timer_id);
if (diff_time <= 0.0)
{
timer_id = interactor->CreateOneShotTimer(1);
}
else
{
timer_id = interactor->CreateOneShotTimer(diff_time * 1000); // from second to millisecond
}
// find the next frame needed to be exported
next_frame_index = cur_frame_index;
next_sim_time = cur_sim_time;
inc_ani_time = 0.0;
do
{
++next_frame_index;
if (next_frame_index >= frame_num)
break;
next_sim_time = get_frame_time(next_frame_index);
inc_ani_time = (next_sim_time - cur_sim_time) * ani_sim_ratio;
}
while (inc_ani_time < 1.0 / 100.0); // maximum rate of gif
next_ani_time = cur_ani_time + inc_ani_time;
if (need_export_animation)
{
// get from back buffer
unsigned char *win_pixel_buffer = window->GetRGBACharPixelData(0, 0, win_width - 1, win_height - 1, 0);
reorder_buffer(win_pixel_buffer, win_width, win_height);
int delay = int(inc_ani_time * 100.0); // to hundredths second
GifWriteFrame(gif_writer, win_pixel_buffer, win_width, win_height, (delay ? delay : 1));
free(win_pixel_buffer);
}
// seems that there two back buffer in OpenGL
// so skip the first unused one
if (cur_frame_index == 0)
window->Frame();
return 0;
}
int Animation::play_animation(void)
{
// init
if (need_export_animation)
{
int *win_size = window->GetSize();
win_width = win_size[0];
win_height = win_size[1];
gif_writer = new GifWriter;
GifBegin(gif_writer, animation_name.c_str(), win_width, win_height, 1);
}
if (total_sim_time == 0.0) return -2;
ani_sim_ratio = total_ani_time / total_sim_time;
is_playing = true;
cur_frame_index = 0;
cur_ani_time = 0.0;
cur_sim_time = get_frame_time(cur_frame_index);
next_frame_index = 0;
next_ani_time = 0.0;
next_sim_time = cur_sim_time;
inc_ani_time = 0.0;
// start animation
start_time = std::chrono::system_clock::now();
render_frame();
return 0;
}
void Animation::complete_animation(void)
{
remove_frame_from_window();
if (timer_id)
interactor->DestroyTimer(timer_id);
if (need_export_animation && gif_writer)
{
GifEnd(gif_writer);
delete gif_writer;
gif_writer = nullptr;
}
} | 26.044776 | 105 | 0.709838 | [
"render"
] |
2e83d1addb0d064fb97665d1c9f76144ff21f42f | 49,724 | cpp | C++ | case-studies/tor/src/TorEnclave/or/nodelist.cpp | shwetasshinde24/Panoply | 9a762c24dec61250d953d1769b070df7f0dd0317 | [
"Apache-2.0"
] | 30 | 2017-02-08T02:53:36.000Z | 2022-03-24T14:26:17.000Z | case-studies/tor/src/TorEnclave/or/nodelist.cpp | shwetasshinde24/Panoply | 9a762c24dec61250d953d1769b070df7f0dd0317 | [
"Apache-2.0"
] | 4 | 2017-05-25T00:39:02.000Z | 2018-04-27T10:38:47.000Z | case-studies/tor/src/TorEnclave/or/nodelist.cpp | shwetasshinde24/Panoply | 9a762c24dec61250d953d1769b070df7f0dd0317 | [
"Apache-2.0"
] | 8 | 2017-10-31T11:12:35.000Z | 2020-06-15T04:12:51.000Z | /* Copyright (c) 2001 Matej Pfajfar.
* Copyright (c) 2001-2004, Roger Dingledine.
* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
* Copyright (c) 2007-2013, The Tor Project, Inc. */
/* See LICENSE for licensing information */
#include "or.h"
#include "address.h"
#include "config.h"
#include "control.h"
#include "dirserv.h"
#include "geoip.h"
#include "main.h"
#include "microdesc.h"
#include "networkstatus.h"
#include "nodelist.h"
#include "policies.h"
#include "rendservice.h"
#include "router.h"
#include "routerlist.h"
#include "routerset.h"
#include <string.h>
static void nodelist_drop_node(node_t *node, int remove_from_ht);
static void node_free(node_t *node);
static void update_router_have_minimum_dir_info(void);
static double get_frac_paths_needed_for_circs(const or_options_t *options,
const networkstatus_t *ns);
/** A nodelist_t holds a node_t object for every router we're "willing to use
* for something". Specifically, it should hold a node_t for every node that
* is currently in the routerlist, or currently in the consensus we're using.
*/
struct nodelist_map {
struct node_t **hth_table;
unsigned hth_table_length;
unsigned hth_n_entries;
unsigned hth_load_limit;
int hth_prime_idx;
};
typedef struct nodelist_t {
/* A list of all the nodes. */
smartlist_t *nodes;
/* Hash table to map from node ID digest to node. */
// HT_HEAD(nodelist_map, node_t) nodes_by_id;
struct nodelist_map nodes_by_id;
} nodelist_t;
static INLINE unsigned int
node_id_hash(const node_t *node)
{
return (unsigned) siphash24g(node->identity, DIGEST_LEN);
}
static INLINE unsigned int
node_id_eq(const node_t *node1, const node_t *node2)
{
return tor_memeq(node1->identity, node2->identity, DIGEST_LEN);
}
HT_PROTOTYPE(nodelist_map, node_t, ht_ent, node_id_hash, node_id_eq);
HT_GENERATE(nodelist_map, node_t, ht_ent, node_id_hash, node_id_eq,
0.6, malloc, realloc, free);
/** The global nodelist. */
static nodelist_t *the_nodelist=NULL;
/** Create an empty nodelist if we haven't done so already. */
static void
init_nodelist(void)
{
if (PREDICT_UNLIKELY(the_nodelist == NULL)) {
the_nodelist = (nodelist_t *)tor_malloc_zero(sizeof(nodelist_t));
HT_INIT(nodelist_map, &the_nodelist->nodes_by_id);
the_nodelist->nodes = smartlist_new();
}
}
/** As node_get_by_id, but returns a non-const pointer */
node_t *
node_get_mutable_by_id(const char *identity_digest)
{
node_t search, *node;
if (PREDICT_UNLIKELY(the_nodelist == NULL))
return NULL;
memcpy(&search.identity, identity_digest, DIGEST_LEN);
node = HT_FIND(nodelist_map, &the_nodelist->nodes_by_id, &search);
return node;
}
/** Return the node_t whose identity is <b>identity_digest</b>, or NULL
* if no such node exists. */
MOCK_IMPL(const node_t *,
node_get_by_id,(const char *identity_digest))
{
return node_get_mutable_by_id(identity_digest);
}
/** Internal: return the node_t whose identity_digest is
* <b>identity_digest</b>. If none exists, create a new one, add it to the
* nodelist, and return it.
*
* Requires that the nodelist be initialized.
*/
static node_t *
node_get_or_create(const char *identity_digest)
{
node_t *node;
if ((node = node_get_mutable_by_id(identity_digest)))
return node;
node = (node_t *)tor_malloc_zero(sizeof(node_t));
memcpy(node->identity, identity_digest, DIGEST_LEN);
HT_INSERT(nodelist_map, &the_nodelist->nodes_by_id, node);
smartlist_add(the_nodelist->nodes, node);
node->nodelist_idx = smartlist_len(the_nodelist->nodes) - 1;
node->country = -1;
return node;
}
/** Called when a node's address changes. */
static void
node_addrs_changed(node_t *node)
{
node->last_reachable = node->last_reachable6 = 0;
node->country = -1;
}
/** Add <b>ri</b> to an appropriate node in the nodelist. If we replace an
* old routerinfo, and <b>ri_old_out</b> is not NULL, set *<b>ri_old_out</b>
* to the previous routerinfo.
*/
node_t *
nodelist_set_routerinfo(routerinfo_t *ri, routerinfo_t **ri_old_out)
{
node_t *node;
const char *id_digest;
int had_router = 0;
tor_assert(ri);
init_nodelist();
id_digest = ri->cache_info.identity_digest;
node = node_get_or_create(id_digest);
if (node->ri) {
if (!routers_have_same_or_addrs(node->ri, ri)) {
node_addrs_changed(node);
}
had_router = 1;
if (ri_old_out)
*ri_old_out = node->ri;
} else {
if (ri_old_out)
*ri_old_out = NULL;
}
node->ri = ri;
if (node->country == -1)
node_set_country(node);
if (authdir_mode(get_options()) && !had_router) {
const char *discard=NULL;
uint32_t status = dirserv_router_get_status(ri, &discard);
dirserv_set_node_flags_from_authoritative_status(node, status);
}
return node;
}
/** Set the appropriate node_t to use <b>md</b> as its microdescriptor.
*
* Called when a new microdesc has arrived and the usable consensus flavor
* is "microdesc".
**/
node_t *
nodelist_add_microdesc(microdesc_t *md)
{
networkstatus_t *ns =
networkstatus_get_latest_consensus_by_flavor(FLAV_MICRODESC);
const routerstatus_t *rs;
node_t *node;
if (ns == NULL)
return NULL;
init_nodelist();
/* Microdescriptors don't carry an identity digest, so we need to figure
* it out by looking up the routerstatus. */
rs = router_get_consensus_status_by_descriptor_digest(ns, md->digest);
if (rs == NULL)
return NULL;
node = node_get_mutable_by_id(rs->identity_digest);
if (node) {
if (node->md)
node->md->held_by_nodes--;
node->md = md;
md->held_by_nodes++;
}
return node;
}
/** Tell the nodelist that the current usable consensus is <b>ns</b>.
* This makes the nodelist change all of the routerstatus entries for
* the nodes, drop nodes that no longer have enough info to get used,
* and grab microdescriptors into nodes as appropriate.
*/
void
nodelist_set_consensus(networkstatus_t *ns)
{
const or_options_t *options = get_options();
int authdir = authdir_mode_v3(options);
int client = !server_mode(options);
init_nodelist();
if (ns->flavor == FLAV_MICRODESC)
(void) get_microdesc_cache(); /* Make sure it exists first. */
SMARTLIST_FOREACH(the_nodelist->nodes, node_t *, node,
node->rs = NULL);
SMARTLIST_FOREACH_BEGIN(ns->routerstatus_list, routerstatus_t *, rs) {
node_t *node = node_get_or_create(rs->identity_digest);
node->rs = rs;
if (ns->flavor == FLAV_MICRODESC) {
if (node->md == NULL ||
tor_memneq(node->md->digest,rs->descriptor_digest,DIGEST256_LEN)) {
if (node->md)
node->md->held_by_nodes--;
node->md = microdesc_cache_lookup_by_digest256(NULL,
rs->descriptor_digest);
if (node->md)
node->md->held_by_nodes++;
}
}
node_set_country(node);
/* If we're not an authdir, believe others. */
if (!authdir) {
node->is_valid = rs->is_valid;
node->is_running = rs->is_flagged_running;
node->is_fast = rs->is_fast;
node->is_stable = rs->is_stable;
node->is_possible_guard = rs->is_possible_guard;
node->is_exit = rs->is_exit;
node->is_bad_directory = rs->is_bad_directory;
node->is_bad_exit = rs->is_bad_exit;
node->is_hs_dir = rs->is_hs_dir;
node->ipv6_preferred = 0;
if (client && options->ClientPreferIPv6ORPort == 1 &&
(tor_addr_is_null(&rs->ipv6_addr) == 0 ||
(node->md && tor_addr_is_null(&node->md->ipv6_addr) == 0)))
node->ipv6_preferred = 1;
}
} SMARTLIST_FOREACH_END(rs);
nodelist_purge();
if (! authdir) {
SMARTLIST_FOREACH_BEGIN(the_nodelist->nodes, node_t *, node) {
/* We have no routerstatus for this router. Clear flags so we can skip
* it, maybe.*/
if (!node->rs) {
tor_assert(node->ri); /* if it had only an md, or nothing, purge
* would have removed it. */
if (node->ri->purpose == ROUTER_PURPOSE_GENERAL) {
/* Clear all flags. */
node->is_valid = node->is_running = node->is_hs_dir =
node->is_fast = node->is_stable =
node->is_possible_guard = node->is_exit =
node->is_bad_exit = node->is_bad_directory =
node->ipv6_preferred = 0;
}
}
} SMARTLIST_FOREACH_END(node);
}
}
/** Helper: return true iff a node has a usable amount of information*/
static INLINE int
node_is_usable(const node_t *node)
{
return (node->rs) || (node->ri);
}
/** Tell the nodelist that <b>md</b> is no longer a microdescriptor for the
* node with <b>identity_digest</b>. */
void
nodelist_remove_microdesc(const char *identity_digest, microdesc_t *md)
{
node_t *node = node_get_mutable_by_id(identity_digest);
if (node && node->md == md) {
node->md = NULL;
md->held_by_nodes--;
}
}
/** Tell the nodelist that <b>ri</b> is no longer in the routerlist. */
void
nodelist_remove_routerinfo(routerinfo_t *ri)
{
node_t *node = node_get_mutable_by_id(ri->cache_info.identity_digest);
if (node && node->ri == ri) {
node->ri = NULL;
if (! node_is_usable(node)) {
nodelist_drop_node(node, 1);
node_free(node);
}
}
}
/** Remove <b>node</b> from the nodelist. (Asserts that it was there to begin
* with.) */
static void
nodelist_drop_node(node_t *node, int remove_from_ht)
{
node_t *tmp;
int idx;
if (remove_from_ht) {
tmp = HT_REMOVE(nodelist_map, &the_nodelist->nodes_by_id, node);
tor_assert(tmp == node);
}
idx = node->nodelist_idx;
tor_assert(idx >= 0);
tor_assert(node == (node_t *)smartlist_get(the_nodelist->nodes, idx));
smartlist_del(the_nodelist->nodes, idx);
if (idx < smartlist_len(the_nodelist->nodes)) {
tmp = (node_t *)smartlist_get(the_nodelist->nodes, idx);
tmp->nodelist_idx = idx;
}
node->nodelist_idx = -1;
}
/** Return a newly allocated smartlist of the nodes that have <b>md</b> as
* their microdescriptor. */
smartlist_t *
nodelist_find_nodes_with_microdesc(const microdesc_t *md)
{
smartlist_t *result = smartlist_new();
if (the_nodelist == NULL)
return result;
SMARTLIST_FOREACH_BEGIN(the_nodelist->nodes, node_t *, node) {
if (node->md == md) {
smartlist_add(result, node);
}
} SMARTLIST_FOREACH_END(node);
return result;
}
/** Release storage held by <b>node</b> */
static void
node_free(node_t *node)
{
if (!node)
return;
if (node->md)
node->md->held_by_nodes--;
tor_assert(node->nodelist_idx == -1);
tor_free(node);
}
/** Remove all entries from the nodelist that don't have enough info to be
* usable for anything. */
void
nodelist_purge(void)
{
node_t **iter;
if (PREDICT_UNLIKELY(the_nodelist == NULL))
return;
/* Remove the non-usable nodes. */
for (iter = HT_START(nodelist_map, &the_nodelist->nodes_by_id); iter; ) {
node_t *node = *iter;
if (node->md && !node->rs) {
/* An md is only useful if there is an rs. */
node->md->held_by_nodes--;
node->md = NULL;
}
if (node_is_usable(node)) {
iter = HT_NEXT(nodelist_map, &the_nodelist->nodes_by_id, iter);
} else {
iter = HT_NEXT_RMV(nodelist_map, &the_nodelist->nodes_by_id, iter);
nodelist_drop_node(node, 0);
node_free(node);
}
}
nodelist_assert_ok();
}
/** Release all storage held by the nodelist. */
void
nodelist_free_all(void)
{
if (PREDICT_UNLIKELY(the_nodelist == NULL))
return;
HT_CLEAR(nodelist_map, &the_nodelist->nodes_by_id);
SMARTLIST_FOREACH_BEGIN(the_nodelist->nodes, node_t *, node) {
node->nodelist_idx = -1;
node_free(node);
} SMARTLIST_FOREACH_END(node);
smartlist_free(the_nodelist->nodes);
tor_free(the_nodelist);
}
/** Check that the nodelist is internally consistent, and consistent with
* the directory info it's derived from.
*/
void
nodelist_assert_ok(void)
{
routerlist_t *rl = router_get_routerlist();
networkstatus_t *ns = networkstatus_get_latest_consensus();
digestmap_t *dm;
if (!the_nodelist)
return;
dm = digestmap_new();
/* every routerinfo in rl->routers should be in the nodelist. */
if (rl) {
SMARTLIST_FOREACH_BEGIN(rl->routers, routerinfo_t *, ri) {
const node_t *node = node_get_by_id(ri->cache_info.identity_digest);
tor_assert(node && node->ri == ri);
tor_assert(fast_memeq(ri->cache_info.identity_digest,
node->identity, DIGEST_LEN));
tor_assert(! digestmap_get(dm, node->identity));
digestmap_set(dm, node->identity, (void*)node);
} SMARTLIST_FOREACH_END(ri);
}
/* every routerstatus in ns should be in the nodelist */
if (ns) {
SMARTLIST_FOREACH_BEGIN(ns->routerstatus_list, routerstatus_t *, rs) {
const node_t *node = node_get_by_id(rs->identity_digest);
tor_assert(node && node->rs == rs);
tor_assert(fast_memeq(rs->identity_digest, node->identity, DIGEST_LEN));
digestmap_set(dm, node->identity, (void*)node);
if (ns->flavor == FLAV_MICRODESC) {
/* If it's a microdesc consensus, every entry that has a
* microdescriptor should be in the nodelist.
*/
microdesc_t *md =
microdesc_cache_lookup_by_digest256(NULL, rs->descriptor_digest);
tor_assert(md == node->md);
if (md)
tor_assert(md->held_by_nodes >= 1);
}
} SMARTLIST_FOREACH_END(rs);
}
/* The nodelist should have no other entries, and its entries should be
* well-formed. */
SMARTLIST_FOREACH_BEGIN(the_nodelist->nodes, node_t *, node) {
tor_assert(digestmap_get(dm, node->identity) != NULL);
tor_assert(node_sl_idx == node->nodelist_idx);
} SMARTLIST_FOREACH_END(node);
tor_assert((long)smartlist_len(the_nodelist->nodes) ==
(long)HT_SIZE(&the_nodelist->nodes_by_id));
digestmap_free(dm, NULL);
}
/** Return a list of a node_t * for every node we know about. The caller
* MUST NOT modify the list. (You can set and clear flags in the nodes if
* you must, but you must not add or remove nodes.) */
smartlist_t *
nodelist_get_list(void)
{
init_nodelist();
return the_nodelist->nodes;
}
/** Given a hex-encoded nickname of the format DIGEST, $DIGEST, $DIGEST=name,
* or $DIGEST~name, return the node with the matching identity digest and
* nickname (if any). Return NULL if no such node exists, or if <b>hex_id</b>
* is not well-formed. */
const node_t *
node_get_by_hex_id(const char *hex_id)
{
char digest_buf[DIGEST_LEN];
char nn_buf[MAX_NICKNAME_LEN+1];
char nn_char='\0';
if (hex_digest_nickname_decode(hex_id, digest_buf, &nn_char, nn_buf)==0) {
const node_t *node = node_get_by_id(digest_buf);
if (!node)
return NULL;
if (nn_char) {
const char *real_name = node_get_nickname(node);
if (!real_name || strcasecmp(real_name, nn_buf))
return NULL;
if (nn_char == '=') {
const char *named_id =
networkstatus_get_router_digest_by_nickname(nn_buf);
if (!named_id || tor_memneq(named_id, digest_buf, DIGEST_LEN))
return NULL;
}
}
return node;
}
return NULL;
}
/** Given a nickname (possibly verbose, possibly a hexadecimal digest), return
* the corresponding node_t, or NULL if none exists. Warn the user if
* <b>warn_if_unnamed</b> is set, and they have specified a router by
* nickname, but the Named flag isn't set for that router. */
const node_t *
node_get_by_nickname(const char *nickname, int warn_if_unnamed)
{
const node_t *node;
if (!the_nodelist)
return NULL;
/* Handle these cases: DIGEST, $DIGEST, $DIGEST=name, $DIGEST~name. */
if ((node = node_get_by_hex_id(nickname)) != NULL)
return node;
if (!strcasecmp(nickname, UNNAMED_ROUTER_NICKNAME))
return NULL;
/* Okay, so if we get here, the nickname is just a nickname. Is there
* a binding for it in the consensus? */
{
const char *named_id =
networkstatus_get_router_digest_by_nickname(nickname);
if (named_id)
return node_get_by_id(named_id);
}
/* Is it marked as owned-by-someone-else? */
if (networkstatus_nickname_is_unnamed(nickname)) {
log_info(LD_GENERAL, "The name %s is listed as Unnamed: there is some "
"router that holds it, but not one listed in the current "
"consensus.", escaped(nickname));
return NULL;
}
/* Okay, so the name is not canonical for anybody. */
{
smartlist_t *matches = smartlist_new();
const node_t *choice = NULL;
SMARTLIST_FOREACH_BEGIN(the_nodelist->nodes, node_t *, node) {
if (!strcasecmp(node_get_nickname(node), nickname))
smartlist_add(matches, node);
} SMARTLIST_FOREACH_END(node);
if (smartlist_len(matches)>1 && warn_if_unnamed) {
int any_unwarned = 0;
SMARTLIST_FOREACH_BEGIN(matches, node_t *, node) {
if (!node->name_lookup_warned) {
node->name_lookup_warned = 1;
any_unwarned = 1;
}
} SMARTLIST_FOREACH_END(node);
if (any_unwarned) {
log_warn(LD_CONFIG, "There are multiple matches for the name %s, "
"but none is listed as Named in the directory consensus. "
"Choosing one arbitrarily.", nickname);
}
} else if (smartlist_len(matches)>1 && warn_if_unnamed) {
char fp[HEX_DIGEST_LEN+1];
node_t *node = (node_t *)smartlist_get(matches, 0);
if (node->name_lookup_warned) {
base16_encode(fp, sizeof(fp), node->identity, DIGEST_LEN);
log_warn(LD_CONFIG,
"You specified a server \"%s\" by name, but the directory "
"authorities do not have any key registered for this "
"nickname -- so it could be used by any server, not just "
"the one you meant. "
"To make sure you get the same server in the future, refer "
"to it by key, as \"$%s\".", nickname, fp);
node->name_lookup_warned = 1;
}
}
if (smartlist_len(matches))
choice = (const node_t *)smartlist_get(matches, 0);
smartlist_free(matches);
return choice;
}
}
/** Return the nickname of <b>node</b>, or NULL if we can't find one. */
const char *
node_get_nickname(const node_t *node)
{
tor_assert(node);
if (node->rs)
return node->rs->nickname;
else if (node->ri)
return node->ri->nickname;
else
return NULL;
}
/** Return true iff the nickname of <b>node</b> is canonical, based on the
* latest consensus. */
int
node_is_named(const node_t *node)
{
const char *named_id;
const char *nickname = node_get_nickname(node);
if (!nickname)
return 0;
named_id = networkstatus_get_router_digest_by_nickname(nickname);
if (!named_id)
return 0;
return tor_memeq(named_id, node->identity, DIGEST_LEN);
}
/** Return true iff <b>node</b> appears to be a directory authority or
* directory cache */
int
node_is_dir(const node_t *node)
{
if (node->rs)
return node->rs->dir_port != 0;
else if (node->ri)
return node->ri->dir_port != 0;
else
return 0;
}
/** Return true iff <b>node</b> has either kind of usable descriptor -- that
* is, a routerdescriptor or a microdescriptor. */
int
node_has_descriptor(const node_t *node)
{
return (node->ri ||
(node->rs && node->md));
}
/** Return the router_purpose of <b>node</b>. */
int
node_get_purpose(const node_t *node)
{
if (node->ri)
return node->ri->purpose;
else
return ROUTER_PURPOSE_GENERAL;
}
/** Compute the verbose ("extended") nickname of <b>node</b> and store it
* into the MAX_VERBOSE_NICKNAME_LEN+1 character buffer at
* <b>verbose_name_out</b> */
void
node_get_verbose_nickname(const node_t *node,
char *verbose_name_out)
{
const char *nickname = node_get_nickname(node);
int is_named = node_is_named(node);
verbose_name_out[0] = '$';
base16_encode(verbose_name_out+1, HEX_DIGEST_LEN+1, node->identity,
DIGEST_LEN);
if (!nickname)
return;
verbose_name_out[1+HEX_DIGEST_LEN] = is_named ? '=' : '~';
strlcpy(verbose_name_out+1+HEX_DIGEST_LEN+1, nickname, MAX_NICKNAME_LEN+1);
}
/** Compute the verbose ("extended") nickname of node with
* given <b>id_digest</b> and store it into the MAX_VERBOSE_NICKNAME_LEN+1
* character buffer at <b>verbose_name_out</b>
*
* If node_get_by_id() returns NULL, base 16 encoding of
* <b>id_digest</b> is returned instead. */
void
node_get_verbose_nickname_by_id(const char *id_digest,
char *verbose_name_out)
{
const node_t *node = node_get_by_id(id_digest);
if (!node) {
verbose_name_out[0] = '$';
base16_encode(verbose_name_out+1, HEX_DIGEST_LEN+1, id_digest, DIGEST_LEN);
} else {
node_get_verbose_nickname(node, verbose_name_out);
}
}
/** Return true iff it seems that <b>node</b> allows circuits to exit
* through it directlry from the client. */
int
node_allows_single_hop_exits(const node_t *node)
{
if (node && node->ri)
return node->ri->allow_single_hop_exits;
else
return 0;
}
/** Return true iff it seems that <b>node</b> has an exit policy that doesn't
* actually permit anything to exit, or we don't know its exit policy */
int
node_exit_policy_rejects_all(const node_t *node)
{
if (node->rejects_all)
return 1;
if (node->ri)
return node->ri->policy_is_reject_star;
else if (node->md)
return node->md->exit_policy == NULL ||
short_policy_is_reject_star(node->md->exit_policy);
else
return 1;
}
/** Return true iff the exit policy for <b>node</b> is such that we can treat
* rejecting an address of type <b>family</b> unexpectedly as a sign of that
* node's failure. */
int
node_exit_policy_is_exact(const node_t *node, sa_family_t family)
{
if (family == AF_UNSPEC) {
return 1; /* Rejecting an address but not telling us what address
* is a bad sign. */
} else if (family == AF_INET) {
return node->ri != NULL;
} else if (family == AF_INET6) {
return 0;
}
tor_fragile_assert();
return 1;
}
/** Return list of tor_addr_port_t with all OR ports (in the sense IP
* addr + TCP port) for <b>node</b>. Caller must free all elements
* using tor_free() and free the list using smartlist_free().
*
* XXX this is potentially a memory fragmentation hog -- if on
* critical path consider the option of having the caller allocate the
* memory
*/
smartlist_t *
node_get_all_orports(const node_t *node)
{
smartlist_t *sl = smartlist_new();
if (node->ri != NULL) {
if (node->ri->addr != 0) {
tor_addr_port_t *ap = (tor_addr_port_t *)tor_malloc(sizeof(tor_addr_port_t));
tor_addr_from_ipv4h(&ap->addr, node->ri->addr);
ap->port = node->ri->or_port;
smartlist_add(sl, ap);
}
if (!tor_addr_is_null(&node->ri->ipv6_addr)) {
tor_addr_port_t *ap = (tor_addr_port_t *)tor_malloc(sizeof(tor_addr_port_t));
tor_addr_copy(&ap->addr, &node->ri->ipv6_addr);
ap->port = node->ri->or_port;
smartlist_add(sl, ap);
}
} else if (node->rs != NULL) {
tor_addr_port_t *ap = (tor_addr_port_t *)tor_malloc(sizeof(tor_addr_port_t));
tor_addr_from_ipv4h(&ap->addr, node->rs->addr);
ap->port = node->rs->or_port;
smartlist_add(sl, ap);
}
return sl;
}
/** Wrapper around node_get_prim_orport for backward
compatibility. */
void
node_get_addr(const node_t *node, tor_addr_t *addr_out)
{
tor_addr_port_t ap;
node_get_prim_orport(node, &ap);
tor_addr_copy(addr_out, &ap.addr);
}
/** Return the host-order IPv4 address for <b>node</b>, or 0 if it doesn't
* seem to have one. */
uint32_t
node_get_prim_addr_ipv4h(const node_t *node)
{
if (node->ri) {
return node->ri->addr;
} else if (node->rs) {
return node->rs->addr;
}
return 0;
}
/** Copy a string representation of an IP address for <b>node</b> into
* the <b>len</b>-byte buffer at <b>buf</b>. */
void
node_get_address_string(const node_t *node, char *buf, size_t len)
{
if (node->ri) {
strlcpy(buf, fmt_addr32(node->ri->addr), len);
} else if (node->rs) {
tor_addr_t addr;
tor_addr_from_ipv4h(&addr, node->rs->addr);
tor_addr_to_str(buf, &addr, len, 0);
} else {
buf[0] = '\0';
}
}
/** Return <b>node</b>'s declared uptime, or -1 if it doesn't seem to have
* one. */
long
node_get_declared_uptime(const node_t *node)
{
if (node->ri)
return node->ri->uptime;
else
return -1;
}
/** Return <b>node</b>'s platform string, or NULL if we don't know it. */
const char *
node_get_platform(const node_t *node)
{
/* If we wanted, we could record the version in the routerstatus_t, since
* the consensus lists it. We don't, though, so this function just won't
* work with microdescriptors. */
if (node->ri)
return node->ri->platform;
else
return NULL;
}
/** Return <b>node</b>'s time of publication, or 0 if we don't have one. */
time_t
node_get_published_on(const node_t *node)
{
if (node->ri)
return node->ri->cache_info.published_on;
else
return 0;
}
/** Return true iff <b>node</b> is one representing this router. */
int
node_is_me(const node_t *node)
{
return router_digest_is_me(node->identity);
}
/** Return <b>node</b> declared family (as a list of names), or NULL if
* the node didn't declare a family. */
const smartlist_t *
node_get_declared_family(const node_t *node)
{
if (node->ri && node->ri->declared_family)
return node->ri->declared_family;
else if (node->md && node->md->family)
return node->md->family;
else
return NULL;
}
/** Return 1 if we prefer the IPv6 address and OR TCP port of
* <b>node</b>, else 0.
*
* We prefer the IPv6 address if the router has an IPv6 address and
* i) the node_t says that it prefers IPv6
* or
* ii) the router has no IPv4 address. */
int
node_ipv6_preferred(const node_t *node)
{
tor_addr_port_t ipv4_addr;
node_assert_ok(node);
if (node->ipv6_preferred || node_get_prim_orport(node, &ipv4_addr)) {
if (node->ri)
return !tor_addr_is_null(&node->ri->ipv6_addr);
if (node->md)
return !tor_addr_is_null(&node->md->ipv6_addr);
if (node->rs)
return !tor_addr_is_null(&node->rs->ipv6_addr);
}
return 0;
}
/** Copy the primary (IPv4) OR port (IP address and TCP port) for
* <b>node</b> into *<b>ap_out</b>. Return 0 if a valid address and
* port was copied, else return non-zero.*/
int
node_get_prim_orport(const node_t *node, tor_addr_port_t *ap_out)
{
node_assert_ok(node);
tor_assert(ap_out);
if (node->ri) {
if (node->ri->addr == 0 || node->ri->or_port == 0)
return -1;
tor_addr_from_ipv4h(&ap_out->addr, node->ri->addr);
ap_out->port = node->ri->or_port;
return 0;
}
if (node->rs) {
if (node->rs->addr == 0 || node->rs->or_port == 0)
return -1;
tor_addr_from_ipv4h(&ap_out->addr, node->rs->addr);
ap_out->port = node->rs->or_port;
return 0;
}
return -1;
}
/** Copy the preferred OR port (IP address and TCP port) for
* <b>node</b> into *<b>ap_out</b>. */
void
node_get_pref_orport(const node_t *node, tor_addr_port_t *ap_out)
{
const or_options_t *options = get_options();
tor_assert(ap_out);
/* Cheap implementation of config option ClientUseIPv6 -- simply
don't prefer IPv6 when ClientUseIPv6 is not set and we're not a
client running with bridges. See #4455 for more on this subject.
Note that this filter is too strict since we're hindering not
only clients! Erring on the safe side shouldn't be a problem
though. XXX move this check to where outgoing connections are
made? -LN */
if ((options->ClientUseIPv6 || options->UseBridges) &&
node_ipv6_preferred(node)) {
node_get_pref_ipv6_orport(node, ap_out);
} else {
node_get_prim_orport(node, ap_out);
}
}
/** Copy the preferred IPv6 OR port (IP address and TCP port) for
* <b>node</b> into *<b>ap_out</b>. */
void
node_get_pref_ipv6_orport(const node_t *node, tor_addr_port_t *ap_out)
{
node_assert_ok(node);
tor_assert(ap_out);
/* We prefer the microdesc over a potential routerstatus here. They
are not being synchronised atm so there might be a chance that
they differ at some point, f.ex. when flipping
UseMicrodescriptors? -LN */
if (node->ri) {
tor_addr_copy(&ap_out->addr, &node->ri->ipv6_addr);
ap_out->port = node->ri->ipv6_orport;
} else if (node->md) {
tor_addr_copy(&ap_out->addr, &node->md->ipv6_addr);
ap_out->port = node->md->ipv6_orport;
} else if (node->rs) {
tor_addr_copy(&ap_out->addr, &node->rs->ipv6_addr);
ap_out->port = node->rs->ipv6_orport;
}
}
/** Return true iff <b>node</b> has a curve25519 onion key. */
int
node_has_curve25519_onion_key(const node_t *node)
{
if (node->ri)
return node->ri->onion_curve25519_pkey != NULL;
else if (node->md)
return node->md->onion_curve25519_pkey != NULL;
else
return 0;
}
/** Refresh the country code of <b>ri</b>. This function MUST be called on
* each router when the GeoIP database is reloaded, and on all new routers. */
void
node_set_country(node_t *node)
{
tor_addr_t addr = TOR_ADDR_NULL;
/* XXXXipv6 */
if (node->rs)
tor_addr_from_ipv4h(&addr, node->rs->addr);
else if (node->ri)
tor_addr_from_ipv4h(&addr, node->ri->addr);
node->country = geoip_get_country_by_addr(&addr);
}
/** Set the country code of all routers in the routerlist. */
void
nodelist_refresh_countries(void)
{
smartlist_t *nodes = nodelist_get_list();
SMARTLIST_FOREACH(nodes, node_t *, node,
node_set_country(node));
}
/** Return true iff router1 and router2 have similar enough network addresses
* that we should treat them as being in the same family */
static INLINE int
addrs_in_same_network_family(const tor_addr_t *a1,
const tor_addr_t *a2)
{
return 0 == tor_addr_compare_masked(a1, a2, 16, CMP_SEMANTIC);
}
/** Return true if <b>node</b>'s nickname matches <b>nickname</b>
* (case-insensitive), or if <b>node's</b> identity key digest
* matches a hexadecimal value stored in <b>nickname</b>. Return
* false otherwise. */
static int
node_nickname_matches(const node_t *node, const char *nickname)
{
const char *n = node_get_nickname(node);
if (n && nickname[0]!='$' && !strcasecmp(n, nickname))
return 1;
return hex_digest_nickname_matches(nickname,
node->identity,
n,
node_is_named(node));
}
/** Return true iff <b>node</b> is named by some nickname in <b>lst</b>. */
static INLINE int
node_in_nickname_smartlist(const smartlist_t *lst, const node_t *node)
{
if (!lst) return 0;
SMARTLIST_FOREACH(lst, const char *, name, {
if (node_nickname_matches(node, name))
return 1;
});
return 0;
}
/** Return true iff r1 and r2 are in the same family, but not the same
* router. */
int
nodes_in_same_family(const node_t *node1, const node_t *node2)
{
const or_options_t *options = get_options();
/* Are they in the same family because of their addresses? */
if (options->EnforceDistinctSubnets) {
tor_addr_t a1, a2;
node_get_addr(node1, &a1);
node_get_addr(node2, &a2);
if (addrs_in_same_network_family(&a1, &a2))
return 1;
}
/* Are they in the same family because the agree they are? */
{
const smartlist_t *f1, *f2;
f1 = node_get_declared_family(node1);
f2 = node_get_declared_family(node2);
if (f1 && f2 &&
node_in_nickname_smartlist(f1, node2) &&
node_in_nickname_smartlist(f2, node1))
return 1;
}
/* Are they in the same option because the user says they are? */
if (options->NodeFamilySets) {
SMARTLIST_FOREACH(options->NodeFamilySets, const routerset_t *, rs, {
if (routerset_contains_node(rs, node1) &&
routerset_contains_node(rs, node2))
return 1;
});
}
return 0;
}
/**
* Add all the family of <b>node</b>, including <b>node</b> itself, to
* the smartlist <b>sl</b>.
*
* This is used to make sure we don't pick siblings in a single path, or
* pick more than one relay from a family for our entry guard list.
* Note that a node may be added to <b>sl</b> more than once if it is
* part of <b>node</b>'s family for more than one reason.
*/
void
nodelist_add_node_and_family(smartlist_t *sl, const node_t *node)
{
const smartlist_t *all_nodes = nodelist_get_list();
const smartlist_t *declared_family;
const or_options_t *options = get_options();
tor_assert(node);
declared_family = node_get_declared_family(node);
/* Let's make sure that we have the node itself, if it's a real node. */
{
const node_t *real_node = node_get_by_id(node->identity);
if (real_node)
smartlist_add(sl, (node_t*)real_node);
}
/* First, add any nodes with similar network addresses. */
if (options->EnforceDistinctSubnets) {
tor_addr_t node_addr;
node_get_addr(node, &node_addr);
SMARTLIST_FOREACH_BEGIN(all_nodes, const node_t *, node2) {
tor_addr_t a;
node_get_addr(node2, &a);
if (addrs_in_same_network_family(&a, &node_addr))
smartlist_add(sl, (void*)node2);
} SMARTLIST_FOREACH_END(node2);
}
/* Now, add all nodes in the declared_family of this node, if they
* also declare this node to be in their family. */
if (declared_family) {
/* Add every r such that router declares familyness with node, and node
* declares familyhood with router. */
SMARTLIST_FOREACH_BEGIN(declared_family, const char *, name) {
const node_t *node2;
const smartlist_t *family2;
if (!(node2 = node_get_by_nickname(name, 0)))
continue;
if (!(family2 = node_get_declared_family(node2)))
continue;
SMARTLIST_FOREACH_BEGIN(family2, const char *, name2) {
if (node_nickname_matches(node, name2)) {
smartlist_add(sl, (void*)node2);
break;
}
} SMARTLIST_FOREACH_END(name2);
} SMARTLIST_FOREACH_END(name);
}
/* If the user declared any families locally, honor those too. */
if (options->NodeFamilySets) {
SMARTLIST_FOREACH(options->NodeFamilySets, const routerset_t *, rs, {
if (routerset_contains_node(rs, node)) {
routerset_get_all_nodes(sl, rs, NULL, 0);
}
});
}
}
/** Find a router that's up, that has this IP address, and
* that allows exit to this address:port, or return NULL if there
* isn't a good one.
* Don't exit enclave to excluded relays -- it wouldn't actually
* hurt anything, but this way there are fewer confused users.
*/
const node_t *
router_find_exact_exit_enclave(const char *address, uint16_t port)
{/*XXXX MOVE*/
uint32_t addr;
struct in_addr in;
tor_addr_t a;
const or_options_t *options = get_options();
if (!tor_inet_aton(address, &in))
return NULL; /* it's not an IP already */
addr = ntohl(in.s_addr);
tor_addr_from_ipv4h(&a, addr);
SMARTLIST_FOREACH(nodelist_get_list(), const node_t *, node, {
if (node_get_addr_ipv4h(node) == addr &&
node->is_running &&
compare_tor_addr_to_node_policy(&a, port, node) ==
ADDR_POLICY_ACCEPTED &&
!routerset_contains_node(options->ExcludeExitNodesUnion_, node))
return node;
});
return NULL;
}
/** Return 1 if <b>router</b> is not suitable for these parameters, else 0.
* If <b>need_uptime</b> is non-zero, we require a minimum uptime.
* If <b>need_capacity</b> is non-zero, we require a minimum advertised
* bandwidth.
* If <b>need_guard</b>, we require that the router is a possible entry guard.
*/
int
node_is_unreliable(const node_t *node, int need_uptime,
int need_capacity, int need_guard)
{
if (need_uptime && !node->is_stable)
return 1;
if (need_capacity && !node->is_fast)
return 1;
if (need_guard && !node->is_possible_guard)
return 1;
return 0;
}
/** Return 1 if all running sufficiently-stable routers we can use will reject
* addr:port. Return 0 if any might accept it. */
int
router_exit_policy_all_nodes_reject(const tor_addr_t *addr, uint16_t port,
int need_uptime)
{
addr_policy_result_t r;
SMARTLIST_FOREACH_BEGIN(nodelist_get_list(), const node_t *, node) {
if (node->is_running &&
!node_is_unreliable(node, need_uptime, 0, 0)) {
r = compare_tor_addr_to_node_policy(addr, port, node);
if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
return 0; /* this one could be ok. good enough. */
}
} SMARTLIST_FOREACH_END(node);
return 1; /* all will reject. */
}
/** Mark the router with ID <b>digest</b> as running or non-running
* in our routerlist. */
void
router_set_status(const char *digest, int up)
{
node_t *node;
tor_assert(digest);
SMARTLIST_FOREACH(router_get_fallback_dir_servers(),
dir_server_t *, d,
if (tor_memeq(d->digest, digest, DIGEST_LEN))
d->is_running = up);
SMARTLIST_FOREACH(router_get_trusted_dir_servers(),
dir_server_t *, d,
if (tor_memeq(d->digest, digest, DIGEST_LEN))
d->is_running = up);
node = node_get_mutable_by_id(digest);
if (node) {
#if 0
log_debug(LD_DIR,"Marking router %s as %s.",
node_describe(node), up ? "up" : "down");
#endif
if (!up && node_is_me(node) && !net_is_disabled())
log_warn(LD_NET, "We just marked ourself as down. Are your external "
"addresses reachable?");
if (bool_neq(node->is_running, up))
router_dir_info_changed();
node->is_running = up;
}
}
/** True iff, the last time we checked whether we had enough directory info
* to build circuits, the answer was "yes". */
static int have_min_dir_info = 0;
/** True iff enough has changed since the last time we checked whether we had
* enough directory info to build circuits that our old answer can no longer
* be trusted. */
static int need_to_update_have_min_dir_info = 1;
/** String describing what we're missing before we have enough directory
* info. */
static char dir_info_status[256] = "";
/** Return true iff we have enough networkstatus and router information to
* start building circuits. Right now, this means "more than half the
* networkstatus documents, and at least 1/4 of expected routers." */
//XXX should consider whether we have enough exiting nodes here.
int
router_have_minimum_dir_info(void)
{
static int logged_delay=0;
const char *delay_fetches_msg = NULL;
if (should_delay_dir_fetches(get_options(), &delay_fetches_msg)) {
if (!logged_delay)
log_notice(LD_DIR, "Delaying directory fetches: %s", delay_fetches_msg);
logged_delay=1;
strlcpy(dir_info_status, delay_fetches_msg, sizeof(dir_info_status));
return 0;
}
logged_delay = 0; /* reset it if we get this far */
if (PREDICT_UNLIKELY(need_to_update_have_min_dir_info)) {
update_router_have_minimum_dir_info();
}
return have_min_dir_info;
}
/** Called when our internal view of the directory has changed. This can be
* when the authorities change, networkstatuses change, the list of routerdescs
* changes, or number of running routers changes.
*/
void
router_dir_info_changed(void)
{
need_to_update_have_min_dir_info = 1;
rend_hsdir_routers_changed();
}
/** Return a string describing what we're missing before we have enough
* directory info. */
const char *
get_dir_info_status_string(void)
{
return dir_info_status;
}
/** Iterate over the servers listed in <b>consensus</b>, and count how many of
* them seem like ones we'd use, and how many of <em>those</em> we have
* descriptors for. Store the former in *<b>num_usable</b> and the latter in
* *<b>num_present</b>. If <b>in_set</b> is non-NULL, only consider those
* routers in <b>in_set</b>. If <b>exit_only</b> is true, only consider nodes
* with the Exit flag. If *descs_out is present, add a node_t for each
* usable descriptor to it.
*/
static void
count_usable_descriptors(int *num_present, int *num_usable,
smartlist_t *descs_out,
const networkstatus_t *consensus,
const or_options_t *options, time_t now,
routerset_t *in_set, int exit_only)
{
const int md = (consensus->flavor == FLAV_MICRODESC);
*num_present = 0, *num_usable=0;
SMARTLIST_FOREACH_BEGIN(consensus->routerstatus_list, routerstatus_t *, rs)
{
const node_t *node = node_get_by_id(rs->identity_digest);
if (!node)
continue; /* This would be a bug: every entry in the consensus is
* supposed to have a node. */
if (exit_only && ! rs->is_exit)
continue;
if (in_set && ! routerset_contains_routerstatus(in_set, rs, -1))
continue;
if (client_would_use_router(rs, now, options)) {
const char * const digest = rs->descriptor_digest;
int present;
++*num_usable; /* the consensus says we want it. */
if (md)
present = NULL != microdesc_cache_lookup_by_digest256(NULL, digest);
else
present = NULL != router_get_by_descriptor_digest(digest);
if (present) {
/* we have the descriptor listed in the consensus. */
++*num_present;
}
if (descs_out)
smartlist_add(descs_out, (node_t*)node);
}
}
SMARTLIST_FOREACH_END(rs);
log_debug(LD_DIR, "%d usable, %d present (%s%s).",
*num_usable, *num_present,
md ? "microdesc" : "desc", exit_only ? " exits" : "s");
}
/** Return an estimate of which fraction of usable paths through the Tor
* network we have available for use. */
static double
compute_frac_paths_available(const networkstatus_t *consensus,
const or_options_t *options, time_t now,
int *num_present_out, int *num_usable_out,
char **status_out)
{
smartlist_t *guards = smartlist_new();
smartlist_t *mid = smartlist_new();
smartlist_t *exits = smartlist_new();
smartlist_t *myexits= smartlist_new();
smartlist_t *myexits_unflagged = smartlist_new();
double f_guard, f_mid, f_exit, f_myexit, f_myexit_unflagged;
int np, nu; /* Ignored */
const int authdir = authdir_mode_v3(options);
count_usable_descriptors(num_present_out, num_usable_out,
mid, consensus, options, now, NULL, 0);
if (options->EntryNodes) {
count_usable_descriptors(&np, &nu, guards, consensus, options, now,
options->EntryNodes, 0);
} else {
SMARTLIST_FOREACH(mid, const node_t *, node, {
if (authdir) {
if (node->rs && node->rs->is_possible_guard)
smartlist_add(guards, (node_t*)node);
} else {
if (node->is_possible_guard)
smartlist_add(guards, (node_t*)node);
}
});
}
/* All nodes with exit flag */
count_usable_descriptors(&np, &nu, exits, consensus, options, now,
NULL, 1);
/* All nodes with exit flag in ExitNodes option */
count_usable_descriptors(&np, &nu, myexits, consensus, options, now,
options->ExitNodes, 1);
/* Now compute the nodes in the ExitNodes option where which we don't know
* what their exit policy is, or we know it permits something. */
count_usable_descriptors(&np, &nu, myexits_unflagged,
consensus, options, now,
options->ExitNodes, 0);
SMARTLIST_FOREACH_BEGIN(myexits_unflagged, const node_t *, node) {
if (node_has_descriptor(node) && node_exit_policy_rejects_all(node))
SMARTLIST_DEL_CURRENT(myexits_unflagged, node);
} SMARTLIST_FOREACH_END(node);
f_guard = frac_nodes_with_descriptors(guards, WEIGHT_FOR_GUARD);
f_mid = frac_nodes_with_descriptors(mid, WEIGHT_FOR_MID);
f_exit = frac_nodes_with_descriptors(exits, WEIGHT_FOR_EXIT);
f_myexit= frac_nodes_with_descriptors(myexits,WEIGHT_FOR_EXIT);
f_myexit_unflagged=
frac_nodes_with_descriptors(myexits_unflagged,WEIGHT_FOR_EXIT);
/* If our ExitNodes list has eliminated every possible Exit node, and there
* were some possible Exit nodes, then instead consider nodes that permit
* exiting to some ports. */
if (smartlist_len(myexits) == 0 &&
smartlist_len(myexits_unflagged)) {
f_myexit = f_myexit_unflagged;
}
smartlist_free(guards);
smartlist_free(mid);
smartlist_free(exits);
smartlist_free(myexits);
smartlist_free(myexits_unflagged);
/* This is a tricky point here: we don't want to make it easy for a
* directory to trickle exits to us until it learns which exits we have
* configured, so require that we have a threshold both of total exits
* and usable exits. */
if (f_myexit < f_exit)
f_exit = f_myexit;
if (status_out)
tor_asprintf(status_out,
"%d%% of guards bw, "
"%d%% of midpoint bw, and "
"%d%% of exit bw",
(int)(f_guard*100),
(int)(f_mid*100),
(int)(f_exit*100));
return f_guard * f_mid * f_exit;
}
/** We just fetched a new set of descriptors. Compute how far through
* the "loading descriptors" bootstrapping phase we are, so we can inform
* the controller of our progress. */
int
count_loading_descriptors_progress(void)
{
int num_present = 0, num_usable=0;
time_t now = time(NULL);
const or_options_t *options = get_options();
const networkstatus_t *consensus =
networkstatus_get_reasonably_live_consensus(now,usable_consensus_flavor());
double paths, fraction;
if (!consensus)
return 0; /* can't count descriptors if we have no list of them */
paths = compute_frac_paths_available(consensus, options, now,
&num_present, &num_usable,
NULL);
fraction = paths / get_frac_paths_needed_for_circs(options,consensus);
if (fraction > 1.0)
return 0; /* it's not the number of descriptors holding us back */
return BOOTSTRAP_STATUS_LOADING_DESCRIPTORS + (int)
(fraction*(BOOTSTRAP_STATUS_CONN_OR-1 -
BOOTSTRAP_STATUS_LOADING_DESCRIPTORS));
}
/** Return the fraction of paths needed before we're willing to build
* circuits, as configured in <b>options</b>, or in the consensus <b>ns</b>. */
static double
get_frac_paths_needed_for_circs(const or_options_t *options,
const networkstatus_t *ns)
{
#define DFLT_PCT_USABLE_NEEDED 60
if (options->PathsNeededToBuildCircuits >= 0.0) {
return options->PathsNeededToBuildCircuits;
} else {
return networkstatus_get_param(ns, "min_paths_for_circs_pct",
DFLT_PCT_USABLE_NEEDED,
25, 95)/100.0;
}
}
/** Change the value of have_min_dir_info, setting it true iff we have enough
* network and router information to build circuits. Clear the value of
* need_to_update_have_min_dir_info. */
static void
update_router_have_minimum_dir_info(void)
{
time_t now = time(NULL);
int res;
const or_options_t *options = get_options();
const networkstatus_t *consensus =
networkstatus_get_reasonably_live_consensus(now,usable_consensus_flavor());
int using_md;
if (!consensus) {
if (!networkstatus_get_latest_consensus())
strlcpy(dir_info_status, "We have no usable consensus.",
sizeof(dir_info_status));
else
strlcpy(dir_info_status, "We have no recent usable consensus.",
sizeof(dir_info_status));
res = 0;
goto done;
}
using_md = consensus->flavor == FLAV_MICRODESC;
{
char *status = NULL;
int num_present=0, num_usable=0;
double paths = compute_frac_paths_available(consensus, options, now,
&num_present, &num_usable,
&status);
if (paths < get_frac_paths_needed_for_circs(options,consensus)) {
tor_snprintf(dir_info_status, sizeof(dir_info_status),
"We need more %sdescriptors: we have %d/%d, and "
"can only build %d%% of likely paths. (We have %s.)",
using_md?"micro":"", num_present, num_usable,
(int)(paths*100), status);
/* log_notice(LD_NET, "%s", dir_info_status); */
tor_free(status);
res = 0;
control_event_bootstrap(BOOTSTRAP_STATUS_REQUESTING_DESCRIPTORS, 0);
goto done;
}
tor_free(status);
res = 1;
}
done:
if (res && !have_min_dir_info) {
log_notice(LD_DIR,
"We now have enough directory information to build circuits.");
control_event_client_status(LOG_NOTICE, "ENOUGH_DIR_INFO");
control_event_bootstrap(BOOTSTRAP_STATUS_CONN_OR, 0);
}
if (!res && have_min_dir_info) {
int quiet = directory_too_idle_to_fetch_descriptors(options, now);
tor_log(quiet ? LOG_INFO : LOG_NOTICE, LD_DIR,
"Our directory information is no longer up-to-date "
"enough to build circuits: %s", dir_info_status);
/* a) make us log when we next complete a circuit, so we know when Tor
* is back up and usable, and b) disable some activities that Tor
* should only do while circuits are working, like reachability tests
* and fetching bridge descriptors only over circuits. */
can_complete_circuit = 0;
control_event_client_status(LOG_NOTICE, "NOT_ENOUGH_DIR_INFO");
}
have_min_dir_info = res;
need_to_update_have_min_dir_info = 0;
}
| 31.391414 | 83 | 0.665835 | [
"object"
] |
2e8a29ad283757ebc89971519482d8e52fef76bf | 4,949 | cpp | C++ | test/unit/test_partition_by_constraint.cpp | kanzl/arbor | 86b1eb065ac252bf0026de7cf7cbc6748a528254 | [
"BSD-3-Clause"
] | 53 | 2018-10-18T12:08:21.000Z | 2022-03-26T22:03:51.000Z | test/unit/test_partition_by_constraint.cpp | kanzl/arbor | 86b1eb065ac252bf0026de7cf7cbc6748a528254 | [
"BSD-3-Clause"
] | 864 | 2018-10-01T08:06:00.000Z | 2022-03-31T08:06:48.000Z | test/unit/test_partition_by_constraint.cpp | kanzl/arbor | 86b1eb065ac252bf0026de7cf7cbc6748a528254 | [
"BSD-3-Clause"
] | 37 | 2019-03-03T16:18:49.000Z | 2022-03-24T10:39:51.000Z | #include "../gtest.h"
#include <array>
#include <forward_list>
#include <string>
#include <vector>
#include <arbor/common_types.hpp>
#include <arbor/simd/simd.hpp>
#include "backends/multicore/multicore_common.hpp"
#include "backends/multicore/partition_by_constraint.hpp"
using namespace arb;
using iarray = multicore::iarray;
constexpr unsigned vector_length = (unsigned) simd::simd_abi::native_width<fvm_value_type>::value;
using simd_value_type = simd::simd<fvm_value_type, vector_length, simd::simd_abi::default_abi>;
const int simd_width_ = simd::width<simd_value_type>();
const int input_size_ = 1024;
TEST(partition_by_constraint, partition_contiguous) {
iarray input_index(input_size_);
iarray expected;
multicore::constraint_partition output;
for (unsigned i = 0; i < input_size_; i++) {
input_index[i] = i;
if(i % simd_width_ == 0)
expected.push_back(i);
}
output = multicore::make_constraint_partition(input_index, input_size_, simd_width_);
EXPECT_EQ(0u, output.independent.size());
EXPECT_EQ(0u, output.none.size());
EXPECT_EQ(0u, output.constant.size());
EXPECT_EQ(expected, output.contiguous);
}
TEST(partition_by_constraint, partition_constant) {
iarray input_index(input_size_);
iarray expected;
multicore::constraint_partition output;
const int c = 5;
for (unsigned i = 0; i < input_size_; i++) {
input_index[i] = c;
if(i % simd_width_ == 0)
expected.push_back(i);
}
output = multicore::make_constraint_partition(input_index, input_size_, simd_width_);
EXPECT_EQ(0u, output.independent.size());
EXPECT_EQ(0u, output.none.size());
if(simd_width_ != 1) {
EXPECT_EQ(0u, output.contiguous.size());
EXPECT_EQ(expected, output.constant);
}
else {
EXPECT_EQ(0u, output.constant.size());
EXPECT_EQ(expected, output.contiguous);
}
}
TEST(partition_by_constraint, partition_independent) {
iarray input_index(input_size_);
iarray expected;
multicore::constraint_partition output;
for (unsigned i = 0; i < input_size_; i++) {
input_index[i] = i * 2;
if(i % simd_width_ == 0)
expected.push_back(i);
}
output = multicore::make_constraint_partition(input_index, input_size_, simd_width_);
EXPECT_EQ(0u, output.constant.size());
EXPECT_EQ(0u, output.none.size());
if(simd_width_ != 1) {
EXPECT_EQ(0u, output.contiguous.size());
EXPECT_EQ(expected, output.independent);
}
else {
EXPECT_EQ(0u, output.independent.size());
EXPECT_EQ(expected, output.contiguous);
}
}
TEST(partition_by_constraint, partition_none) {
iarray input_index(input_size_);
iarray expected;
multicore::constraint_partition output;
for (unsigned i = 0; i < input_size_; i++) {
input_index[i] = i / ((simd_width_ + 1)/ 2);
if(i % simd_width_ == 0)
expected.push_back(i);
}
output = multicore::make_constraint_partition(input_index, input_size_, simd_width_);
EXPECT_EQ(0u, output.independent.size());
EXPECT_EQ(0u, output.constant.size());
if(simd_width_ > 2) {
EXPECT_EQ(0u, output.contiguous.size());
EXPECT_EQ(expected, output.none);
}
else {
EXPECT_EQ(0u, output.none.size());
EXPECT_EQ(expected, output.contiguous);
}
}
TEST(partition_by_constraint, partition_random) {
iarray input_index(input_size_);
iarray expected_contiguous, expected_constant,
expected_independent, expected_none, expected_simd_1;
multicore::constraint_partition output;
const int c = 5;
for (unsigned i = 0; i < input_size_; i++) {
input_index[i] = i<input_size_/4 ? i/((simd_width_ + 1)/ 2):
i<input_size_/2 ? i*2:
i<input_size_*3/4 ? c:
i;
if (i < input_size_ / 4 && i % simd_width_ == 0) {
if (simd_width_ > 2) {
expected_none.push_back(i);
}
else {
expected_contiguous.push_back(i);
}
}
else if (i < input_size_ / 2 && i % simd_width_ == 0)
expected_independent.push_back(i);
else if (i < input_size_* 3/ 4 && i % simd_width_ == 0)
expected_constant.push_back(i);
else if (i % simd_width_ == 0)
expected_contiguous.push_back(i);
expected_simd_1.push_back(i);
}
output = multicore::make_constraint_partition(input_index, input_size_, simd_width_);
if (simd_width_ != 1) {
EXPECT_EQ(expected_contiguous, output.contiguous);
EXPECT_EQ(expected_constant, output.constant);
EXPECT_EQ(expected_independent, output.independent);
EXPECT_EQ(expected_none, output.none);
}
else {
EXPECT_EQ(expected_simd_1, output.contiguous);
}
}
| 30.361963 | 98 | 0.641948 | [
"vector"
] |
2e9781a9ca5c8c48e19573422ca975d524da487f | 1,935 | cpp | C++ | uhk/acm5493.cpp | Hyyyyyyyyyy/acm | d7101755b2c2868d51bb056f094e024d0333b56f | [
"MIT"
] | null | null | null | uhk/acm5493.cpp | Hyyyyyyyyyy/acm | d7101755b2c2868d51bb056f094e024d0333b56f | [
"MIT"
] | null | null | null | uhk/acm5493.cpp | Hyyyyyyyyyy/acm | d7101755b2c2868d51bb056f094e024d0333b56f | [
"MIT"
] | null | null | null | #include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <set>
#include <map>
#include <cctype>
#include <vector>
#include <queue>
#include <stack>
#include <deque>
#include <string>
#include <iostream>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
#define foR for
#define for9 for
#define retunr return
#define reutrn return
#define reutnr return
#define retrun return
const int inf = (1 << 31) - 1;
const ll INF = (1ll << 63) - 1;
const double PI = acos(-1.0);
const double eps = 1e-7;
const ll MOD = 1000000007ll;
const int maxn = 100000 + 100;
const int maxm = 1000000 + 100;
int N;
int Bit[maxn];
int res[maxn];
struct Node
{
int h;
int num;
};
Node node[maxn];
bool comp(const Node& a, const Node& b)
{
return a.h < b.h;
}
void Add(int x, int val)
{
for (int i = x; i <= N; i += (i & -i))
Bit[i] += val;
}
int Sum(int x)
{
int res = 0;
foR(int i = x; i > 0; i -= (i & -i))
res += Bit[i];
return res;
}
int Binary(int num)
{
int l = 1;
int r = N;
int mid;
while (l <= r)
{
mid = (l + r) / 2;
if (Sum(mid) < num)
l = mid + 1;
else
r = mid - 1;
}
retrun l;
}
int main()
{
int i, j, k, CAS, cas, n;
while (scanf("%d", &CAS) != EOF)
{
for (cas = 1; cas <= CAS; cas++)
{
scanf("%d", &N);
memset(Bit, 0, sizeof(Bit));
for (i = 1; i <= N; i++)
{
scanf("%d %d", &node[i].h, &node[i].num);
Add(i, 1);
}
sort(node + 1, node + 1 + N, comp);
for (i = 1; i <= N; i++)
{
int pos1 = Binary(node[i].num + 1);
int pos2 = Binary(N - i - node[i].num + 1);
if (pos1 > N || pos2 < 1)
{
break;
}
int pos = min(pos1, pos2);
Add(pos, -1);
res[pos] = node[i].h;
}
printf("Case #%d:", cas);
if (i <= N)
{
printf(" impossible\n");
}
else
{
for (j = 1; j <= N; j++)
{
printf(" %d", res[j]);
}
printf("\n");
}
}
}
return 0;
} | 16.973684 | 47 | 0.533333 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.