hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 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 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 48.5k ⌀ | 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 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
32308f50dc46137cef962e49a5b33fa158c1f135 | 223 | cpp | C++ | src/Game/Entities/Dynamic/Inspector.cpp | emmagonz22/DinerDashGameP3 | 687128c1cfd58ffe8639934b67190a3e4c764642 | [
"Apache-2.0"
] | null | null | null | src/Game/Entities/Dynamic/Inspector.cpp | emmagonz22/DinerDashGameP3 | 687128c1cfd58ffe8639934b67190a3e4c764642 | [
"Apache-2.0"
] | null | null | null | src/Game/Entities/Dynamic/Inspector.cpp | emmagonz22/DinerDashGameP3 | 687128c1cfd58ffe8639934b67190a3e4c764642 | [
"Apache-2.0"
] | null | null | null | #include "Inspector.h"
Inspector::Inspector(int x, int y, int width, int height, ofImage sprite, Burger* burger) : Client(x, y,width,height, sprite, burger)
{
//Empty constructor in case of thing wanna que added
}
| 37.166667 | 134 | 0.70852 | emmagonz22 |
323fc673a2d0a679d848fda08f177a948892f9c9 | 931 | cpp | C++ | Array/Missing_Element_XOR.cpp | susantabiswas/placementPrep | 22a7574206ddc63eba89517f7b68a3d2f4d467f5 | [
"MIT"
] | 19 | 2018-12-02T05:59:44.000Z | 2021-07-24T14:11:54.000Z | Array/Missing_Element_XOR.cpp | susantabiswas/placementPrep | 22a7574206ddc63eba89517f7b68a3d2f4d467f5 | [
"MIT"
] | null | null | null | Array/Missing_Element_XOR.cpp | susantabiswas/placementPrep | 22a7574206ddc63eba89517f7b68a3d2f4d467f5 | [
"MIT"
] | 13 | 2019-04-25T16:20:00.000Z | 2021-09-06T19:50:04.000Z | //Find the missing element from a list of 1..n-1 elements
/*Elements are distinct and range from 1 to n.Input has a list of n-1 numbers and the missing number
needs to be found*/
#include<iostream>
using namespace std;
//finds the missing element
/*XOR all the 1..n elements and then XOR the given elements and XOR both the results
since if c is the missing element then when we XOR the results then we get 0^c that is c
As the common elements being getting XOR operation becomes 0*
Array contains n-1 elements .
But it contains distinct elements out of n elements */
int FindMissing(int arr[],int size)
{
int res1=0;
for (int i = 0; i < size; ++i)
{
res1=arr[i]^res1;
}
int res2=0;
//here n=size+1
for (int i = 1; i < size+2; ++i)
{
res2=res2^i;
}
return res1^res2;
}
int main()
{
int arr[]={1, 2, 4, 6, 3, 7, 8};
int size=sizeof(arr)/sizeof(int);
cout<<"Missing element:"<<FindMissing(arr,size);
return 0;
}
| 25.861111 | 100 | 0.691729 | susantabiswas |
32449484973d63f27bcea3d9a61a8f2dac9832e1 | 3,151 | cpp | C++ | oopAsgn4/prob4.cpp | debargham14/Object-Oriented-Programming-Assignment | 25d7c87803e957c16188cac563eb238654c5a87b | [
"MIT"
] | null | null | null | oopAsgn4/prob4.cpp | debargham14/Object-Oriented-Programming-Assignment | 25d7c87803e957c16188cac563eb238654c5a87b | [
"MIT"
] | null | null | null | oopAsgn4/prob4.cpp | debargham14/Object-Oriented-Programming-Assignment | 25d7c87803e957c16188cac563eb238654c5a87b | [
"MIT"
] | null | null | null | #include<iostream>
using namespace std;
//designing the class array to perform the relevant operations
class ARRAY {
int *p;
int size;
public:
//constrcutor to initialise the array
ARRAY(int s = 0) {
if (s == 0) {
size = s;
p = NULL;
}
else {
size = s;
p = new int[size];
for (int i = 0; i < size; i++) p[i] = 0;
}
}
//defining the copy constructor
ARRAY(const ARRAY& a) {
size = a.size;
if (size == 0)
p = NULL;
else {
p = new int[size]; //creating a new array
for (int i = 0; i < size; i++) p[i] = a.p[i];
}
}
//copy constructor to copy an array
ARRAY(int *arr, int n) {
size = n;
if (size == 0)
p = NULL;
else {
p = new int[size]; //creating a new array
for (int i = 0; i < n; i++) p[i] = arr[i];
}
}
//overloading the >> to take the array as input
friend void operator >> (istream &is, ARRAY& a) {
for (int i = 0; i < a.size; i++) is >> a.p[i];
}
//operator << overloaded to display the array
friend ostream& operator << (ostream &os, ARRAY a) {
for (int i = 0; i < a.size; i++) os << a.p[i] << " ";
return os;
}
//operator overloading + to add the two array
void operator = (ARRAY &b) {
size = b.size;
if (size == 0) {
p = NULL;
}
else {
p = new int[size];
for (int i = 0; i < b.size; i++) p[i] = b.p[i];
}
}
//operator overloading + to add the contents of two array
friend ARRAY operator + (ARRAY &a, ARRAY &b) {
ARRAY c(a.size > b.size ? a.size : b.size);
if (a.size < b.size)
{
for (int i = 0; i < a.size; i++) c.p[i] = a.p[i] + b.p[i];
for (int i = a.size; i < b.size; i++) c.p[i] = b.p[i];
}
else {
for (int i = 0; i < b.size; i++) c.p[i] = a.p[i] + b.p[i];
for (int i = b.size; i < a.size; i++) c.p[i] = b.p[i];
}
return c;
}
//operator overloading for [] so that array can be accessed as a[idx] for array being an object of the array class
int& operator [] (int idx) {
return p[idx];
}
//overloadinf the operator * to support multiplication of an array with integers
friend ARRAY operator * (ARRAY &a, int x) {
ARRAY c(a.size);
for (int i = 0; i < a.size; i++) c.p[i] = a.p[i] * x;
return c;
}
friend ARRAY operator * (int x, ARRAY &a) {
ARRAY c(a.size);
for (int i = 0; i < a.size; i++) c.p[i] = a.p[i] * x;
return c;
}
//destructor is used to set the memory free
~ARRAY() {
delete[] p;
}
};
//driver code to implment the above class
int main() {
int n;
cout << "Enter the number of elements of the array :- ";
cin >> n;
ARRAY a(n), b; //initialising the array using copy constructor
cout << "Enter the array :- ";
cin >> a; //taking input of an array
cout << "Your Entered Array is :- ";
cout << a << "\n"; //displaying the array
b = a; //copying an array bytewise
cout << "A check to the copy function :- ";
cout << b << "\n";
ARRAY c = a + b; //adding the contents of two array
c[0] = 1000; // check the [] operator in the ARRAY
cout << "A check to the add function :- ";
cout << c << "\n";
ARRAY d = 5 * c; //multiplying the content of array with constant variable
cout << "A check to the multiply function :- ";
cout << d << "\n";
return 0;
} | 24.811024 | 115 | 0.567122 | debargham14 |
324f495f006ff8d9558d2af4b1301fc9f4fb6fb4 | 2,103 | hpp | C++ | src/centurion/detail/array_utils.hpp | Creeperface01/centurion | e3b674c11849367a18c2d976ce94071108e1590d | [
"MIT"
] | 14 | 2020-05-17T21:38:03.000Z | 2020-11-21T00:16:25.000Z | src/centurion/detail/array_utils.hpp | Creeperface01/centurion | e3b674c11849367a18c2d976ce94071108e1590d | [
"MIT"
] | 70 | 2020-04-26T17:08:52.000Z | 2020-11-21T17:34:03.000Z | src/centurion/detail/array_utils.hpp | Creeperface01/centurion | e3b674c11849367a18c2d976ce94071108e1590d | [
"MIT"
] | null | null | null | /*
* MIT License
*
* Copyright (c) 2019-2022 Albin Johansson
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef CENTURION_DETAIL_ARRAY_UTILS_HPP_
#define CENTURION_DETAIL_ARRAY_UTILS_HPP_
#include <array> // array, to_array
#include <cstddef> // size_t
#include "../common.hpp"
#include "../features.hpp"
/// \cond FALSE
namespace cen::detail {
template <typename T, std::size_t Size>
constexpr void assign(const std::array<T, Size>& array, bounded_array_ref<T, Size> out)
{
std::size_t index = 0;
for (auto&& value : array) {
out[index] = value;
++index;
}
}
template <typename T, std::size_t Size>
[[nodiscard]] constexpr auto to_array(bounded_array_ref<const T, Size> data)
-> std::array<T, Size>
{
#if CENTURION_HAS_FEATURE_TO_ARRAY
return std::to_array(data);
#else
std::array<T, Size> array; // NOLINT
for (std::size_t i = 0; i < Size; ++i) {
array[i] = data[i];
}
return array;
#endif // CENTURION_HAS_FEATURE_TO_ARRAY
}
} // namespace cen::detail
/// \endcond
#endif // CENTURION_DETAIL_ARRAY_UTILS_HPP_
| 30.042857 | 87 | 0.724679 | Creeperface01 |
325336bb7b753fc226e0c24b300a62e7040c8ce4 | 12,210 | cpp | C++ | Core/src/Core/GameObjectManager.cpp | Hukunaa/Condamnation | 04efeb6ee62013a8399695a8294d9bd9e9f0f41d | [
"MIT"
] | null | null | null | Core/src/Core/GameObjectManager.cpp | Hukunaa/Condamnation | 04efeb6ee62013a8399695a8294d9bd9e9f0f41d | [
"MIT"
] | null | null | null | Core/src/Core/GameObjectManager.cpp | Hukunaa/Condamnation | 04efeb6ee62013a8399695a8294d9bd9e9f0f41d | [
"MIT"
] | null | null | null | #include <tinyxml2.h>
#include <Core/GameObjectManager.h>
#include <Components/LightComp.h>
#include <Components/TransformComp.h>
#include <Components/MaterialComp.h>
#include <Components/BoxColliderComp.h>
#include <Components/RigidBodyComp.h>
#include <Components/ModelComp.h>
#include <Rendering/Managers/InputManager.h>
#include <unordered_map>
#include "Components/PlayerComp.h"
static int phase = 0;
Core::GameObjectManager::GameObjectManager(MeshManager& p_modelManager, Rendering::Managers::CameraManager& p_camera)
{
LoadScene(p_modelManager, "DOOM");
Find("Player")->AddComponent<Components::PlayerComp>(p_camera.GetCamera(), 100);
}
void Core::GameObjectManager::Update(const float& p_deltaTime, Rendering::Managers::CameraManager& p_camera)
{
phase += 1;
float frequency = 0.02f;
if (Rendering::Managers::InputManager::GetInstance()->GetKeyDown(Rendering::Managers::InputManager::KeyCode::Mouse1))
{
if(Find("Link") != nullptr )
Find("Link")->GetComponent<Components::RigidBodyComp>()->AddForce({ p_camera.GetCamera()->GetFront().x * 100, p_camera.GetCamera()->GetFront().y * 100 , p_camera.GetCamera()->GetFront().z * 100 });
if(Find("Link2") != nullptr)
Find("Link2")->GetComponent<Components::RigidBodyComp>()->AddForce({ p_camera.GetCamera()->GetFront().x * 100, p_camera.GetCamera()->GetFront().y * 100 , p_camera.GetCamera()->GetFront().z * 100 });
}
Find("Torch1")->GetComponent<Components::LightComp>()->GetLight()->SetColor(sin(frequency * phase), sin(frequency * phase + 2), sin(frequency * phase + 4));
Find("Torch2")->GetComponent<Components::LightComp>()->GetLight()->SetColor(sin(frequency * phase + 2), sin(frequency * phase + 4), sin(frequency * phase + 6));
Find("Torch3")->GetComponent<Components::LightComp>()->GetLight()->SetColor(sin(frequency * phase + 4), sin(frequency * phase + 6), sin(frequency * phase + 8));
Find("Torch4")->GetComponent<Components::LightComp>()->GetLight()->SetColor(sin(frequency * phase + 6), sin(frequency * phase + 8), sin(frequency * phase + 10));
if (Find("Player") != nullptr)
Find("Player")->GetComponent<Components::PlayerComp>()->ProcessKeyInput(*this, p_deltaTime);
m_angle += 0.005f * p_deltaTime;
if (Find("BlueLight") != nullptr)
{
Find("BlueLight")->GetComponent<Components::TransformComp>()->GetTransform()->Rotate(glm::vec3(0, 1, 0) * p_deltaTime);
Find("BlueLight")->GetComponent<Components::TransformComp>()->GetTransform()->Translate(glm::vec3(0.1, 0, 0) * p_deltaTime);
Find("BlueLight")->GetComponent<Components::TransformComp>()->Update();
}
if (Find("OrangeLight") != nullptr)
Find("OrangeLight")->GetComponent<Components::TransformComp>()->Update();
for (auto& gameObject : m_gameObjects)
{
if (gameObject->GetComponent<Components::BoxColliderComp>() != nullptr)
{
gameObject->GetComponent<Components::BoxColliderComp>()->GetCollider()->GetPosVec() = gameObject->GetComponent<Components::TransformComp>()->GetTransform()->GetPosition();
gameObject->GetComponent<Components::BoxColliderComp>()->GetCollider()->GetMat() = gameObject->GetComponent<Components::TransformComp>()->GetTransform()->GetTransMat();
gameObject->GetComponent<Components::BoxColliderComp>()->GetCollider()->UpdateBoundingBox();
}
}
}
int Core::GameObjectManager::SaveScene(const MeshManager& p_modelManager, const std::string& p_sceneName)
{
using namespace tinyxml2;
std::unordered_map<std::string, int> compTypes
{
{"BoxColliderComp", 0},
{"LightComp", 1},
{"MaterialComp", 2},
{"ModelComp", 3},
{"TransformComp", 4},
{"RigidBodyComp", 5}
};
#ifndef XMLCheckResult
#define XMLCheckResult(a_eResult) if (a_eResult != XML_SUCCESS) { std::cerr << "Error while parsing XML [LOADER] Error Type: " << a_eResult << '\n'; return a_eResult; }
#endif
XMLDocument xmlDoc;
XMLNode* root = xmlDoc.NewElement("scene");
xmlDoc.InsertFirstChild(root);
XMLElement* GOList = xmlDoc.NewElement("GameObjectList");
GOList->SetAttribute("count", static_cast<unsigned int>(m_gameObjects.size()));
root->InsertFirstChild(GOList);
for (auto gameObject : m_gameObjects)
{
XMLElement* GOelement = xmlDoc.NewElement("GameObject");
GOelement->SetAttribute("name", gameObject->GetName().c_str());
if (gameObject->GetComponent<Components::ModelComp>() != nullptr)
{
GOelement->SetAttribute("mesh", FindInstanceIteratorInVector(gameObject->GetComponent<Components::ModelComp>()->GetModel()->GetMesh(), p_modelManager.GetMeshes()));
GOelement->SetAttribute("shader", FindInstanceIteratorInVector(gameObject->GetComponent<Components::ModelComp>()->GetModel()->GetShader(), p_modelManager.GetShaders()));
}
GOelement->SetAttribute("tag", gameObject->GetTag().c_str());
XMLElement* ComponentList = xmlDoc.NewElement("ComponentList");
ComponentList->SetAttribute("count", gameObject->GetComponentCount());
for (const auto& component : gameObject->GetComponents())
{
XMLElement* CompElement = xmlDoc.NewElement("Component");
std::string rawClassName = typeid(*component).name();
size_t offset = rawClassName.find_last_of(':');
std::string realName = rawClassName.substr(offset + 1);
CompElement->SetAttribute("type", realName.c_str());
component->Serialize(CompElement, xmlDoc);
ComponentList->InsertEndChild(CompElement);
}
GOelement->InsertFirstChild(ComponentList);
GOList->InsertEndChild(GOelement);
}
XMLError eResult = xmlDoc.SaveFile((p_sceneName + ".xml").c_str());
XMLCheckResult(eResult);
return eResult;
}
int Core::GameObjectManager::LoadScene(const MeshManager& p_modelManager, const std::string& p_sceneName)
{
using namespace tinyxml2;
std::unordered_map<std::string, int> compTypes
{
{"BoxColliderComp", 0},
{"LightComp", 1},
{"MaterialComp", 2},
{"ModelComp", 3},
{"TransformComp", 4},
{"RigidBodyComp", 5}
};
#ifndef XMLCheckResult
#define XMLCheckResult(a_eResult) if (a_eResult != XML_SUCCESS) { std::cerr << "Error while parsing XML [LOADER] Error Type: " << a_eResult << '\n'; return a_eResult; }
#endif
XMLDocument xmlDoc;
XMLError eResult = xmlDoc.LoadFile((p_sceneName + ".xml").c_str());
XMLCheckResult(eResult);
XMLNode* root = xmlDoc.FirstChild();
if (root == nullptr)
return XML_ERROR_FILE_READ_ERROR;
XMLElement* GOList = root->FirstChildElement("GameObjectList");
if (GOList == nullptr)
return XML_ERROR_PARSING_ELEMENT;
XMLElement* GOelement = GOList->FirstChildElement("GameObject");
while (GOelement != nullptr)
{
const char* newGoName = nullptr;
const char* tag = nullptr;
int meshId{0}, shaderId{0};
bool empty{ true };
newGoName = GOelement->Attribute("name");
if (newGoName == nullptr)
return XML_ERROR_PARSING_ATTRIBUTE;
eResult = GOelement->QueryIntAttribute("mesh", &meshId);
if (eResult == XML_SUCCESS)
empty = false;
eResult = GOelement->QueryIntAttribute("shader", &shaderId);
if (eResult == XML_SUCCESS)
empty = false;
tag = GOelement->Attribute("tag");
std::shared_ptr<GameObject> newGo{};
if (!empty)
newGo = std::make_shared<GameObject>(p_modelManager.GetMesh(meshId), p_modelManager.GetShader(shaderId), newGoName);
else if (empty)
newGo = std::make_shared<GameObject>(newGoName);
newGo->SetTag(tag);
XMLElement* ComponentList = GOelement->FirstChildElement("ComponentList");
if (GOelement == nullptr)
return XML_ERROR_PARSING_ELEMENT;
XMLElement* CompElement = ComponentList->FirstChildElement("Component");
while (CompElement != nullptr)
{
const char* attribText = nullptr;
attribText = CompElement->Attribute("type");
if (attribText == nullptr)
return XML_ERROR_PARSING_ATTRIBUTE;
std::string newCompType{attribText};
std::unordered_map<std::string, int>::const_iterator got = compTypes.find(newCompType);
// this line will be triggered by the playerComp, we are not handling it
// for the moment, and we shouldn't pay much attention to it. It is not an error.
if (got == compTypes.end())
std::cout << "component not found\n";
else
{
switch (got->second)
{
case 0: //boxColliderComp
if (newGo->GetComponent<Components::BoxColliderComp>() == nullptr)
newGo->AddComponent<Components::BoxColliderComp>();
newGo->GetComponent<Components::BoxColliderComp>()->Deserialize(CompElement);
break;
case 1: //LightComp
if (newGo->GetComponent<Components::LightComp>() == nullptr)
newGo->AddComponent<Components::LightComp>();
newGo->GetComponent<Components::LightComp>()->Deserialize(CompElement);
break;
case 2: //materialComp
if (newGo->GetComponent<Components::MaterialComp>() == nullptr)
newGo->AddComponent<Components::MaterialComp>();
newGo->GetComponent<Components::MaterialComp>()->Deserialize(CompElement);
break;
case 3: //modelComp
if (newGo->GetComponent<Components::ModelComp>() == nullptr)
newGo->AddComponent<Components::ModelComp>();
break;
case 4: //TransformComp
if (newGo->GetComponent<Components::TransformComp>() == nullptr)
newGo->AddComponent<Components::TransformComp>();
newGo->GetComponent<Components::TransformComp>()->Deserialize(CompElement);
break;
case 5: //TransformComp
if (newGo->GetComponent<Components::RigidBodyComp>() == nullptr)
newGo->AddComponent<Components::RigidBodyComp>(this);
newGo->GetComponent<Components::RigidBodyComp>()->Deserialize(CompElement);
break;
default:
std::cerr <<
"ERROR : something went wrong when trying to load components on the XML loader\n Your component type is non-existent.";
break;
}
}
CompElement = CompElement->NextSiblingElement("Component");
}
GOelement = GOelement->NextSiblingElement("GameObject");
m_gameObjects.push_back(newGo);
}
return EXIT_SUCCESS;
}
std::shared_ptr<Core::GameObject> Core::GameObjectManager::Find(const std::string& p_name)
{
for (auto& m_gameObject : m_gameObjects)
{
if (m_gameObject->GetName() == p_name)
return m_gameObject;
}
std::cout << "Could not find object " << p_name << "in Game Manager\n";
return {};
}
std::vector<std::shared_ptr<Core::GameObject>>& Core::GameObjectManager::GetGameObjects() noexcept
{
return m_gameObjects;
}
void Core::GameObjectManager::RemoveGameObject(std::shared_ptr<GameObject> p_gameObject)
{
for (int i = 0; i < m_gameObjects.size(); ++i)
{
if (*m_gameObjects[i] == *p_gameObject)
{
if (m_gameObjects[i]->GetComponent<Components::TransformComp>()->GetChild() != nullptr)
{
Core::GameObject& tmp = m_gameObjects[i]->GetComponent<Components::TransformComp>()->GetChild()->GetGameObject();
m_gameObjects[i]->GetComponent<Components::TransformComp>()->GetChild()->SetParent();
RemoveGameObject(std::make_shared<GameObject>(tmp));
return;
}
m_gameObjects.erase(m_gameObjects.begin() + i);
return;
}
}
}
| 40.29703 | 206 | 0.634808 | Hukunaa |
325a6205d1eb661c7f53405784f58e121e4906c4 | 93,995 | cpp | C++ | unittest/biunique_map_test.cpp | suomesta/ken3 | edac96489d5b638dc4eff25454fcca1307ca86e9 | [
"MIT"
] | null | null | null | unittest/biunique_map_test.cpp | suomesta/ken3 | edac96489d5b638dc4eff25454fcca1307ca86e9 | [
"MIT"
] | null | null | null | unittest/biunique_map_test.cpp | suomesta/ken3 | edac96489d5b638dc4eff25454fcca1307ca86e9 | [
"MIT"
] | null | null | null | /**
* @file unittest/biunique_map_test.cpp
* @brief Testing ken3::biunique_map using lest.
* @author toda
* @date 2016-11-24
* @version 0.1.0
* @remark the target is C++11 or more
*/
#include <iterator>
#include <tuple>
#include <vector>
#include "ken3/biunique_map.hpp"
#include "unittest/lest.hpp"
namespace {
// type definitions
template <ken3::biunique_map_type TYPE, ken3::biunique_map_policy POLICY>
using tmp_map = ken3::biunique_map<char, int, TYPE, POLICY>;
using map_list = std::tuple<
tmp_map<ken3::biunique_map_type::ordered_no_default, ken3::biunique_map_policy::silence>,
tmp_map<ken3::biunique_map_type::ordered_front_default, ken3::biunique_map_policy::silence>,
tmp_map<ken3::biunique_map_type::ordered_back_default, ken3::biunique_map_policy::silence>,
tmp_map<ken3::biunique_map_type::unordered_no_default, ken3::biunique_map_policy::silence>,
tmp_map<ken3::biunique_map_type::ordered_no_default, ken3::biunique_map_policy::throwing>,
tmp_map<ken3::biunique_map_type::ordered_front_default, ken3::biunique_map_policy::throwing>,
tmp_map<ken3::biunique_map_type::ordered_back_default, ken3::biunique_map_policy::throwing>,
tmp_map<ken3::biunique_map_type::unordered_no_default, ken3::biunique_map_policy::throwing>
>;
/////////////////////////////////////////////////////////////////////////////
/**
* @brief check std::map items are same or not.
* @tparam MAP: std::map.
* @param[in] lhs: left hand side.
* @param[in] rhs: right hand side.
* @return true: same, false: not same.
*/
template <typename MAP>
bool same_map(const MAP& lhs, const typename MAP::map_type& rhs)
{
if (lhs.size() != rhs.size()) {
return false;
}
for (auto i = lhs.cbegin(); i != lhs.cend(); ++i) {
auto j = rhs.find(i->first);
if (j == rhs.end()) {
return false;
}
else if (i->second != j->second) {
return false;
}
}
return true;
}
/////////////////////////////////////////////////////////////////////////////
} // namespace {
const lest::test specification[] =
{
CASE("minimum functions")
{
{
using my_map = std::tuple_element<0, map_list>::type;
my_map bm;
bm.insert('A', 10);
bm.insert('B', 11);
EXPECT(10 == bm.f2s('A'));
EXPECT(11 == bm.f2s('B'));
EXPECT('A' == bm.s2f(10));
EXPECT('B' == bm.s2f(11));
}
{
using my_map = std::tuple_element<1, map_list>::type;
my_map bm;
bm.insert('A', 10);
bm.insert('B', 11);
EXPECT(10 == bm.f2s('A'));
EXPECT(11 == bm.f2s('B'));
EXPECT('A' == bm.s2f(10));
EXPECT('B' == bm.s2f(11));
}
{
using my_map = std::tuple_element<2, map_list>::type;
my_map bm;
bm.insert('A', 10);
bm.insert('B', 11);
EXPECT(10 == bm.f2s('A'));
EXPECT(11 == bm.f2s('B'));
EXPECT('A' == bm.s2f(10));
EXPECT('B' == bm.s2f(11));
}
{
using my_map = std::tuple_element<3, map_list>::type;
my_map bm;
bm.insert('A', 10);
bm.insert('B', 11);
EXPECT(10 == bm.f2s('A'));
EXPECT(11 == bm.f2s('B'));
EXPECT('A' == bm.s2f(10));
EXPECT('B' == bm.s2f(11));
}
{
using my_map = std::tuple_element<4, map_list>::type;
my_map bm;
bm.insert('A', 10);
bm.insert('B', 11);
EXPECT(10 == bm.f2s('A'));
EXPECT(11 == bm.f2s('B'));
EXPECT('A' == bm.s2f(10));
EXPECT('B' == bm.s2f(11));
}
{
using my_map = std::tuple_element<5, map_list>::type;
my_map bm;
bm.insert('A', 10);
bm.insert('B', 11);
EXPECT(10 == bm.f2s('A'));
EXPECT(11 == bm.f2s('B'));
EXPECT('A' == bm.s2f(10));
EXPECT('B' == bm.s2f(11));
}
{
using my_map = std::tuple_element<6, map_list>::type;
my_map bm;
bm.insert('A', 10);
bm.insert('B', 11);
EXPECT(10 == bm.f2s('A'));
EXPECT(11 == bm.f2s('B'));
EXPECT('A' == bm.s2f(10));
EXPECT('B' == bm.s2f(11));
}
{
using my_map = std::tuple_element<7, map_list>::type;
my_map bm;
bm.insert('A', 10);
bm.insert('B', 11);
EXPECT(10 == bm.f2s('A'));
EXPECT(11 == bm.f2s('B'));
EXPECT('A' == bm.s2f(10));
EXPECT('B' == bm.s2f(11));
}
},
CASE("iterator constructor with non-duplex data")
{
{
using my_map = std::tuple_element<0, map_list>::type;
std::vector<typename my_map::value_type> v{{'A', 10}, {'B', 11}};
my_map bm1(v.begin(), v.end());
EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}}));
typename my_map::map_type m{{'A', 10}, {'B', 11}};
my_map bm2(m.begin(), m.end());
EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<1, map_list>::type;
std::vector<typename my_map::value_type> v{{'A', 10}, {'B', 11}};
my_map bm1(v.begin(), v.end());
EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}}));
typename my_map::map_type m{{'A', 10}, {'B', 11}};
my_map bm2(m.begin(), m.end());
EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<2, map_list>::type;
std::vector<typename my_map::value_type> v{{'A', 10}, {'B', 11}};
my_map bm1(v.begin(), v.end());
EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}}));
typename my_map::map_type m{{'A', 10}, {'B', 11}};
my_map bm2(m.begin(), m.end());
EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<3, map_list>::type;
std::vector<typename my_map::value_type> v{{'A', 10}, {'B', 11}};
my_map bm1(v.begin(), v.end());
EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}}));
typename my_map::map_type m{{'A', 10}, {'B', 11}};
my_map bm2(m.begin(), m.end());
EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<4, map_list>::type;
std::vector<typename my_map::value_type> v{{'A', 10}, {'B', 11}};
my_map bm1(v.begin(), v.end());
EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}}));
typename my_map::map_type m{{'A', 10}, {'B', 11}};
my_map bm2(m.begin(), m.end());
EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<5, map_list>::type;
std::vector<typename my_map::value_type> v{{'A', 10}, {'B', 11}};
my_map bm1(v.begin(), v.end());
EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}}));
typename my_map::map_type m{{'A', 10}, {'B', 11}};
my_map bm2(m.begin(), m.end());
EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<6, map_list>::type;
std::vector<typename my_map::value_type> v{{'A', 10}, {'B', 11}};
my_map bm1(v.begin(), v.end());
EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}}));
typename my_map::map_type m{{'A', 10}, {'B', 11}};
my_map bm2(m.begin(), m.end());
EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<7, map_list>::type;
std::vector<typename my_map::value_type> v{{'A', 10}, {'B', 11}};
my_map bm1(v.begin(), v.end());
EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}}));
typename my_map::map_type m{{'A', 10}, {'B', 11}};
my_map bm2(m.begin(), m.end());
EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}}));
}
},
CASE("iterator constructor with duplex data")
{
{
using my_map = std::tuple_element<0, map_list>::type;
std::vector<typename my_map::value_type> v{{'A', 10}, {'B', 11}, {'A', 12}};
my_map bm1(v.begin(), v.end());
EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}}));
std::map<typename my_map::key_type, typename my_map::mapped_type> m{{'A', 10}, {'B', 11}, {'C', 10}}; // need ordered map to get stable result
my_map bm2(m.begin(), m.end());
EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<1, map_list>::type;
std::vector<typename my_map::value_type> v{{'A', 10}, {'B', 11}, {'A', 12}};
my_map bm1(v.begin(), v.end());
EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}}));
std::map<typename my_map::key_type, typename my_map::mapped_type> m{{'A', 10}, {'B', 11}, {'C', 10}}; // need ordered map to get stable result
my_map bm2(m.begin(), m.end());
EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<2, map_list>::type;
std::vector<typename my_map::value_type> v{{'A', 10}, {'B', 11}, {'A', 12}};
my_map bm1(v.begin(), v.end());
EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}}));
std::map<typename my_map::key_type, typename my_map::mapped_type> m{{'A', 10}, {'B', 11}, {'C', 10}}; // need ordered map to get stable result
my_map bm2(m.begin(), m.end());
EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<3, map_list>::type;
std::vector<typename my_map::value_type> v{{'A', 10}, {'B', 11}, {'A', 12}};
my_map bm1(v.begin(), v.end());
EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}}));
std::map<typename my_map::key_type, typename my_map::mapped_type> m{{'A', 10}, {'B', 11}, {'C', 10}}; // need ordered map to get stable result
my_map bm2(m.begin(), m.end());
EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<4, map_list>::type;
std::vector<typename my_map::value_type> v{{'A', 10}, {'B', 11}, {'A', 12}};
EXPECT_THROWS_AS((my_map(v.begin(), v.end())), std::invalid_argument);
std::map<typename my_map::key_type, typename my_map::mapped_type> m{{'A', 10}, {'B', 11}, {'C', 10}}; // need ordered map to get stable result
EXPECT_THROWS_AS((my_map(m.begin(), m.end())), std::invalid_argument);
}
{
using my_map = std::tuple_element<5, map_list>::type;
std::vector<typename my_map::value_type> v{{'A', 10}, {'B', 11}, {'A', 12}};
EXPECT_THROWS_AS((my_map(v.begin(), v.end())), std::invalid_argument);
std::map<typename my_map::key_type, typename my_map::mapped_type> m{{'A', 10}, {'B', 11}, {'C', 10}}; // need ordered map to get stable result
EXPECT_THROWS_AS((my_map(m.begin(), m.end())), std::invalid_argument);
}
{
using my_map = std::tuple_element<6, map_list>::type;
std::vector<typename my_map::value_type> v{{'A', 10}, {'B', 11}, {'A', 12}};
EXPECT_THROWS_AS((my_map(v.begin(), v.end())), std::invalid_argument);
std::map<typename my_map::key_type, typename my_map::mapped_type> m{{'A', 10}, {'B', 11}, {'C', 10}}; // need ordered map to get stable result
EXPECT_THROWS_AS((my_map(m.begin(), m.end())), std::invalid_argument);
}
{
using my_map = std::tuple_element<7, map_list>::type;
std::vector<typename my_map::value_type> v{{'A', 10}, {'B', 11}, {'A', 12}};
EXPECT_THROWS_AS((my_map(v.begin(), v.end())), std::invalid_argument);
std::map<typename my_map::key_type, typename my_map::mapped_type> m{{'A', 10}, {'B', 11}, {'C', 10}}; // need ordered map to get stable result
EXPECT_THROWS_AS((my_map(m.begin(), m.end())), std::invalid_argument);
}
},
CASE("initializer_list constructor with non-duplex data")
{
{
using my_map = std::tuple_element<0, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<1, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<2, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<3, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<4, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<5, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<6, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<7, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
}
},
CASE("initializer_list constructor with duplex data")
{
{
using my_map = std::tuple_element<0, map_list>::type;
my_map bm1{{'A', 10}, {'B', 11}, {'A', 12}};
EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}}));
my_map bm2{{'A', 10}, {'B', 11}, {'C', 10}};
EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<1, map_list>::type;
my_map bm1{{'A', 10}, {'B', 11}, {'A', 12}};
EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}}));
my_map bm2{{'A', 10}, {'B', 11}, {'C', 10}};
EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<2, map_list>::type;
my_map bm1{{'A', 10}, {'B', 11}, {'A', 12}};
EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}}));
my_map bm2{{'A', 10}, {'B', 11}, {'C', 10}};
EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<3, map_list>::type;
my_map bm1{{'A', 10}, {'B', 11}, {'A', 12}};
EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}}));
my_map bm2{{'A', 10}, {'B', 11}, {'C', 10}};
EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<4, map_list>::type;
EXPECT_THROWS_AS((my_map{{'A', 10}, {'B', 11}, {'A', 12}}), std::invalid_argument);
EXPECT_THROWS_AS((my_map{{'A', 10}, {'B', 11}, {'C', 10}}), std::invalid_argument);
}
{
using my_map = std::tuple_element<5, map_list>::type;
EXPECT_THROWS_AS((my_map{{'A', 10}, {'B', 11}, {'A', 12}}), std::invalid_argument);
EXPECT_THROWS_AS((my_map{{'A', 10}, {'B', 11}, {'C', 10}}), std::invalid_argument);
}
{
using my_map = std::tuple_element<6, map_list>::type;
EXPECT_THROWS_AS((my_map{{'A', 10}, {'B', 11}, {'A', 12}}), std::invalid_argument);
EXPECT_THROWS_AS((my_map{{'A', 10}, {'B', 11}, {'C', 10}}), std::invalid_argument);
}
{
using my_map = std::tuple_element<7, map_list>::type;
EXPECT_THROWS_AS((my_map{{'A', 10}, {'B', 11}, {'A', 12}}), std::invalid_argument);
EXPECT_THROWS_AS((my_map{{'A', 10}, {'B', 11}, {'C', 10}}), std::invalid_argument);
}
},
CASE("initializer_list assignment with non-duplex data")
{
{
using my_map = std::tuple_element<0, map_list>::type;
my_map bm;
bm = {{'A', 10}, {'B', 11}};
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<1, map_list>::type;
my_map bm;
bm = {{'A', 10}, {'B', 11}};
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<2, map_list>::type;
my_map bm;
bm = {{'A', 10}, {'B', 11}};
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<3, map_list>::type;
my_map bm;
bm = {{'A', 10}, {'B', 11}};
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<4, map_list>::type;
my_map bm;
bm = {{'A', 10}, {'B', 11}};
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<5, map_list>::type;
my_map bm;
bm = {{'A', 10}, {'B', 11}};
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<6, map_list>::type;
my_map bm;
bm = {{'A', 10}, {'B', 11}};
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<7, map_list>::type;
my_map bm;
bm = {{'A', 10}, {'B', 11}};
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
}
},
CASE("initializer_list assignment with duplex data")
{
{
using my_map = std::tuple_element<0, map_list>::type;
my_map bm1;
bm1 = {{'A', 10}, {'B', 11}, {'A', 12}};
EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}}));
my_map bm2;
bm2 = {{'A', 10}, {'B', 11}, {'C', 10}};
EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<1, map_list>::type;
my_map bm1;
bm1 = {{'A', 10}, {'B', 11}, {'A', 12}};
EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}}));
my_map bm2;
bm2 = {{'A', 10}, {'B', 11}, {'C', 10}};
EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<2, map_list>::type;
my_map bm1;
bm1 = {{'A', 10}, {'B', 11}, {'A', 12}};
EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}}));
my_map bm2;
bm2 = {{'A', 10}, {'B', 11}, {'C', 10}};
EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<3, map_list>::type;
my_map bm1;
bm1 = {{'A', 10}, {'B', 11}, {'A', 12}};
EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}}));
my_map bm2;
bm2 = {{'A', 10}, {'B', 11}, {'C', 10}};
EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<4, map_list>::type;
my_map bm1;
EXPECT_THROWS_AS((bm1 = {{'A', 10}, {'B', 11}, {'A', 12}}), std::invalid_argument);
my_map bm2;
EXPECT_THROWS_AS((bm2 = {{'A', 10}, {'B', 11}, {'C', 10}}), std::invalid_argument);
}
{
using my_map = std::tuple_element<5, map_list>::type;
my_map bm1;
EXPECT_THROWS_AS((bm1 = {{'A', 10}, {'B', 11}, {'A', 12}}), std::invalid_argument);
my_map bm2;
EXPECT_THROWS_AS((bm2 = {{'A', 10}, {'B', 11}, {'C', 10}}), std::invalid_argument);
}
{
using my_map = std::tuple_element<6, map_list>::type;
my_map bm1;
EXPECT_THROWS_AS((bm1 = {{'A', 10}, {'B', 11}, {'A', 12}}), std::invalid_argument);
my_map bm2;
EXPECT_THROWS_AS((bm2 = {{'A', 10}, {'B', 11}, {'C', 10}}), std::invalid_argument);
}
{
using my_map = std::tuple_element<7, map_list>::type;
my_map bm1;
EXPECT_THROWS_AS((bm1 = {{'A', 10}, {'B', 11}, {'A', 12}}), std::invalid_argument);
my_map bm2;
EXPECT_THROWS_AS((bm2 = {{'A', 10}, {'B', 11}, {'C', 10}}), std::invalid_argument);
}
},
CASE("operator==")
{
{
using my_map = std::tuple_element<0, map_list>::type;
my_map bm1{{'A', 10}, {'B', 11}};
my_map bm2{{'A', 10}, {'B', 11}};
my_map bm3{bm1};
my_map bm4{{'A', 11}, {'B', 10}};
my_map bm5;
EXPECT(bm1 == bm2);
EXPECT(bm1 == bm3);
EXPECT(not (bm1 == bm4));
EXPECT(not (bm1 == bm5));
}
{
using my_map = std::tuple_element<1, map_list>::type;
my_map bm1{{'A', 10}, {'B', 11}};
my_map bm2{{'A', 10}, {'B', 11}};
my_map bm3{bm1};
my_map bm4{{'A', 11}, {'B', 10}};
my_map bm5;
EXPECT(bm1 == bm2);
EXPECT(bm1 == bm3);
EXPECT(not (bm1 == bm4));
EXPECT(not (bm1 == bm5));
}
{
using my_map = std::tuple_element<2, map_list>::type;
my_map bm1{{'A', 10}, {'B', 11}};
my_map bm2{{'A', 10}, {'B', 11}};
my_map bm3{bm1};
my_map bm4{{'A', 11}, {'B', 10}};
my_map bm5;
EXPECT(bm1 == bm2);
EXPECT(bm1 == bm3);
EXPECT(not (bm1 == bm4));
EXPECT(not (bm1 == bm5));
}
{
using my_map = std::tuple_element<3, map_list>::type;
my_map bm1{{'A', 10}, {'B', 11}};
my_map bm2{{'A', 10}, {'B', 11}};
my_map bm3{bm1};
my_map bm4{{'A', 11}, {'B', 10}};
my_map bm5;
EXPECT(bm1 == bm2);
EXPECT(bm1 == bm3);
EXPECT(not (bm1 == bm4));
EXPECT(not (bm1 == bm5));
}
{
using my_map = std::tuple_element<4, map_list>::type;
my_map bm1{{'A', 10}, {'B', 11}};
my_map bm2{{'A', 10}, {'B', 11}};
my_map bm3{bm1};
my_map bm4{{'A', 11}, {'B', 10}};
my_map bm5;
EXPECT(bm1 == bm2);
EXPECT(bm1 == bm3);
EXPECT(not (bm1 == bm4));
EXPECT(not (bm1 == bm5));
}
{
using my_map = std::tuple_element<5, map_list>::type;
my_map bm1{{'A', 10}, {'B', 11}};
my_map bm2{{'A', 10}, {'B', 11}};
my_map bm3{bm1};
my_map bm4{{'A', 11}, {'B', 10}};
my_map bm5;
EXPECT(bm1 == bm2);
EXPECT(bm1 == bm3);
EXPECT(not (bm1 == bm4));
EXPECT(not (bm1 == bm5));
}
{
using my_map = std::tuple_element<6, map_list>::type;
my_map bm1{{'A', 10}, {'B', 11}};
my_map bm2{{'A', 10}, {'B', 11}};
my_map bm3{bm1};
my_map bm4{{'A', 11}, {'B', 10}};
my_map bm5;
EXPECT(bm1 == bm2);
EXPECT(bm1 == bm3);
EXPECT(not (bm1 == bm4));
EXPECT(not (bm1 == bm5));
}
{
using my_map = std::tuple_element<7, map_list>::type;
my_map bm1{{'A', 10}, {'B', 11}};
my_map bm2{{'A', 10}, {'B', 11}};
my_map bm3{bm1};
my_map bm4{{'A', 11}, {'B', 10}};
my_map bm5;
EXPECT(bm1 == bm2);
EXPECT(bm1 == bm3);
EXPECT(not (bm1 == bm4));
EXPECT(not (bm1 == bm5));
}
},
CASE("operator!=")
{
{
using my_map = std::tuple_element<0, map_list>::type;
my_map bm1{{'A', 10}, {'B', 11}};
my_map bm2{{'A', 10}, {'B', 11}};
my_map bm3{bm1};
my_map bm4{{'A', 11}, {'B', 10}};
my_map bm5;
EXPECT(not (bm1 != bm2));
EXPECT(not (bm1 != bm3));
EXPECT(bm1 != bm4);
EXPECT(bm1 != bm5);
}
{
using my_map = std::tuple_element<1, map_list>::type;
my_map bm1{{'A', 10}, {'B', 11}};
my_map bm2{{'A', 10}, {'B', 11}};
my_map bm3{bm1};
my_map bm4{{'A', 11}, {'B', 10}};
my_map bm5;
EXPECT(not (bm1 != bm2));
EXPECT(not (bm1 != bm3));
EXPECT(bm1 != bm4);
EXPECT(bm1 != bm5);
}
{
using my_map = std::tuple_element<2, map_list>::type;
my_map bm1{{'A', 10}, {'B', 11}};
my_map bm2{{'A', 10}, {'B', 11}};
my_map bm3{bm1};
my_map bm4{{'A', 11}, {'B', 10}};
my_map bm5;
EXPECT(not (bm1 != bm2));
EXPECT(not (bm1 != bm3));
EXPECT(bm1 != bm4);
EXPECT(bm1 != bm5);
}
{
using my_map = std::tuple_element<3, map_list>::type;
my_map bm1{{'A', 10}, {'B', 11}};
my_map bm2{{'A', 10}, {'B', 11}};
my_map bm3{bm1};
my_map bm4{{'A', 11}, {'B', 10}};
my_map bm5;
EXPECT(not (bm1 != bm2));
EXPECT(not (bm1 != bm3));
EXPECT(bm1 != bm4);
EXPECT(bm1 != bm5);
}
{
using my_map = std::tuple_element<4, map_list>::type;
my_map bm1{{'A', 10}, {'B', 11}};
my_map bm2{{'A', 10}, {'B', 11}};
my_map bm3{bm1};
my_map bm4{{'A', 11}, {'B', 10}};
my_map bm5;
EXPECT(not (bm1 != bm2));
EXPECT(not (bm1 != bm3));
EXPECT(bm1 != bm4);
EXPECT(bm1 != bm5);
}
{
using my_map = std::tuple_element<5, map_list>::type;
my_map bm1{{'A', 10}, {'B', 11}};
my_map bm2{{'A', 10}, {'B', 11}};
my_map bm3{bm1};
my_map bm4{{'A', 11}, {'B', 10}};
my_map bm5;
EXPECT(not (bm1 != bm2));
EXPECT(not (bm1 != bm3));
EXPECT(bm1 != bm4);
EXPECT(bm1 != bm5);
}
{
using my_map = std::tuple_element<6, map_list>::type;
my_map bm1{{'A', 10}, {'B', 11}};
my_map bm2{{'A', 10}, {'B', 11}};
my_map bm3{bm1};
my_map bm4{{'A', 11}, {'B', 10}};
my_map bm5;
EXPECT(not (bm1 != bm2));
EXPECT(not (bm1 != bm3));
EXPECT(bm1 != bm4);
EXPECT(bm1 != bm5);
}
{
using my_map = std::tuple_element<7, map_list>::type;
my_map bm1{{'A', 10}, {'B', 11}};
my_map bm2{{'A', 10}, {'B', 11}};
my_map bm3{bm1};
my_map bm4{{'A', 11}, {'B', 10}};
my_map bm5;
EXPECT(not (bm1 != bm2));
EXPECT(not (bm1 != bm3));
EXPECT(bm1 != bm4);
EXPECT(bm1 != bm5);
}
},
CASE("swap()")
{
{
using my_map = std::tuple_element<0, map_list>::type;
my_map bm1, bm2;
bm1.insert('A', 10);
bm1.insert('B', 11);
bm2.insert('C', 12);
bm1.swap(bm2);
EXPECT(same_map(bm1, {{'C', 12}}));
EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<1, map_list>::type;
my_map bm1, bm2;
bm1.insert('A', 10);
bm1.insert('B', 11);
bm2.insert('C', 12);
bm1.swap(bm2);
EXPECT(same_map(bm1, {{'C', 12}}));
EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<2, map_list>::type;
my_map bm1, bm2;
bm1.insert('A', 10);
bm1.insert('B', 11);
bm2.insert('C', 12);
bm1.swap(bm2);
EXPECT(same_map(bm1, {{'C', 12}}));
EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<3, map_list>::type;
my_map bm1, bm2;
bm1.insert('A', 10);
bm1.insert('B', 11);
bm2.insert('C', 12);
bm1.swap(bm2);
EXPECT(same_map(bm1, {{'C', 12}}));
EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<4, map_list>::type;
my_map bm1, bm2;
bm1.insert('A', 10);
bm1.insert('B', 11);
bm2.insert('C', 12);
bm1.swap(bm2);
EXPECT(same_map(bm1, {{'C', 12}}));
EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<5, map_list>::type;
my_map bm1, bm2;
bm1.insert('A', 10);
bm1.insert('B', 11);
bm2.insert('C', 12);
bm1.swap(bm2);
EXPECT(same_map(bm1, {{'C', 12}}));
EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<6, map_list>::type;
my_map bm1, bm2;
bm1.insert('A', 10);
bm1.insert('B', 11);
bm2.insert('C', 12);
bm1.swap(bm2);
EXPECT(same_map(bm1, {{'C', 12}}));
EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<7, map_list>::type;
my_map bm1, bm2;
bm1.insert('A', 10);
bm1.insert('B', 11);
bm2.insert('C', 12);
bm1.swap(bm2);
EXPECT(same_map(bm1, {{'C', 12}}));
EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}}));
}
},
CASE("size()")
{
{
using my_map = std::tuple_element<0, map_list>::type;
my_map bm;
EXPECT(0UL == bm.size());
bm.insert('A', 10);
EXPECT(1UL == bm.size());
bm.insert('B', 11);
EXPECT(2UL == bm.size());
bm.clear();
EXPECT(0UL == bm.size());
}
{
using my_map = std::tuple_element<1, map_list>::type;
my_map bm;
EXPECT(0UL == bm.size());
bm.insert('A', 10);
EXPECT(1UL == bm.size());
bm.insert('B', 11);
EXPECT(2UL == bm.size());
bm.clear();
EXPECT(0UL == bm.size());
}
{
using my_map = std::tuple_element<2, map_list>::type;
my_map bm;
EXPECT(0UL == bm.size());
bm.insert('A', 10);
EXPECT(1UL == bm.size());
bm.insert('B', 11);
EXPECT(2UL == bm.size());
bm.clear();
EXPECT(0UL == bm.size());
}
{
using my_map = std::tuple_element<3, map_list>::type;
my_map bm;
EXPECT(0UL == bm.size());
bm.insert('A', 10);
EXPECT(1UL == bm.size());
bm.insert('B', 11);
EXPECT(2UL == bm.size());
bm.clear();
EXPECT(0UL == bm.size());
}
{
using my_map = std::tuple_element<4, map_list>::type;
my_map bm;
EXPECT(0UL == bm.size());
bm.insert('A', 10);
EXPECT(1UL == bm.size());
bm.insert('B', 11);
EXPECT(2UL == bm.size());
bm.clear();
EXPECT(0UL == bm.size());
}
{
using my_map = std::tuple_element<5, map_list>::type;
my_map bm;
EXPECT(0UL == bm.size());
bm.insert('A', 10);
EXPECT(1UL == bm.size());
bm.insert('B', 11);
EXPECT(2UL == bm.size());
bm.clear();
EXPECT(0UL == bm.size());
}
{
using my_map = std::tuple_element<6, map_list>::type;
my_map bm;
EXPECT(0UL == bm.size());
bm.insert('A', 10);
EXPECT(1UL == bm.size());
bm.insert('B', 11);
EXPECT(2UL == bm.size());
bm.clear();
EXPECT(0UL == bm.size());
}
{
using my_map = std::tuple_element<7, map_list>::type;
my_map bm;
EXPECT(0UL == bm.size());
bm.insert('A', 10);
EXPECT(1UL == bm.size());
bm.insert('B', 11);
EXPECT(2UL == bm.size());
bm.clear();
EXPECT(0UL == bm.size());
}
},
CASE("empty()")
{
{
using my_map = std::tuple_element<0, map_list>::type;
my_map bm;
EXPECT(bm.empty());
bm.insert('A', 10);
EXPECT(not bm.empty());
bm.insert('B', 11);
EXPECT(not bm.empty());
bm.clear();
EXPECT(bm.empty());
}
{
using my_map = std::tuple_element<1, map_list>::type;
my_map bm;
EXPECT(bm.empty());
bm.insert('A', 10);
EXPECT(not bm.empty());
bm.insert('B', 11);
EXPECT(not bm.empty());
bm.clear();
EXPECT(bm.empty());
}
{
using my_map = std::tuple_element<2, map_list>::type;
my_map bm;
EXPECT(bm.empty());
bm.insert('A', 10);
EXPECT(not bm.empty());
bm.insert('B', 11);
EXPECT(not bm.empty());
bm.clear();
EXPECT(bm.empty());
}
{
using my_map = std::tuple_element<3, map_list>::type;
my_map bm;
EXPECT(bm.empty());
bm.insert('A', 10);
EXPECT(not bm.empty());
bm.insert('B', 11);
EXPECT(not bm.empty());
bm.clear();
EXPECT(bm.empty());
}
{
using my_map = std::tuple_element<4, map_list>::type;
my_map bm;
EXPECT(bm.empty());
bm.insert('A', 10);
EXPECT(not bm.empty());
bm.insert('B', 11);
EXPECT(not bm.empty());
bm.clear();
EXPECT(bm.empty());
}
{
using my_map = std::tuple_element<5, map_list>::type;
my_map bm;
EXPECT(bm.empty());
bm.insert('A', 10);
EXPECT(not bm.empty());
bm.insert('B', 11);
EXPECT(not bm.empty());
bm.clear();
EXPECT(bm.empty());
}
{
using my_map = std::tuple_element<6, map_list>::type;
my_map bm;
EXPECT(bm.empty());
bm.insert('A', 10);
EXPECT(not bm.empty());
bm.insert('B', 11);
EXPECT(not bm.empty());
bm.clear();
EXPECT(bm.empty());
}
{
using my_map = std::tuple_element<7, map_list>::type;
my_map bm;
EXPECT(bm.empty());
bm.insert('A', 10);
EXPECT(not bm.empty());
bm.insert('B', 11);
EXPECT(not bm.empty());
bm.clear();
EXPECT(bm.empty());
}
},
CASE("cbegin()")
{
{
using my_map = std::tuple_element<0, map_list>::type;
my_map bm;
bm.insert('A', 10);
bm.insert('B', 11);
my_map::map_type m{{'A', 10}, {'B', 11}};
EXPECT(m.cbegin()->first == bm.cbegin()->first);
EXPECT(m.cbegin()->second == bm.cbegin()->second);
EXPECT(std::next(m.cbegin(), 1)->first == std::next(bm.cbegin(), 1)->first);
EXPECT(std::next(m.cbegin(), 1)->second == std::next(bm.cbegin(), 1)->second);
}
{
using my_map = std::tuple_element<1, map_list>::type;
my_map bm;
bm.insert('A', 10);
bm.insert('B', 11);
my_map::map_type m{{'A', 10}, {'B', 11}};
EXPECT(m.cbegin()->first == bm.cbegin()->first);
EXPECT(m.cbegin()->second == bm.cbegin()->second);
EXPECT(std::next(m.cbegin(), 1)->first == std::next(bm.cbegin(), 1)->first);
EXPECT(std::next(m.cbegin(), 1)->second == std::next(bm.cbegin(), 1)->second);
}
{
using my_map = std::tuple_element<2, map_list>::type;
my_map bm;
bm.insert('A', 10);
bm.insert('B', 11);
my_map::map_type m{{'A', 10}, {'B', 11}};
EXPECT(m.cbegin()->first == bm.cbegin()->first);
EXPECT(m.cbegin()->second == bm.cbegin()->second);
EXPECT(std::next(m.cbegin(), 1)->first == std::next(bm.cbegin(), 1)->first);
EXPECT(std::next(m.cbegin(), 1)->second == std::next(bm.cbegin(), 1)->second);
}
{
using my_map = std::tuple_element<3, map_list>::type;
my_map bm;
bm.insert('A', 10);
bm.insert('B', 11);
my_map::map_type m{{'A', 10}, {'B', 11}};
EXPECT(m.cbegin()->first == bm.cbegin()->first);
EXPECT(m.cbegin()->second == bm.cbegin()->second);
EXPECT(std::next(m.cbegin(), 1)->first == std::next(bm.cbegin(), 1)->first);
EXPECT(std::next(m.cbegin(), 1)->second == std::next(bm.cbegin(), 1)->second);
}
{
using my_map = std::tuple_element<4, map_list>::type;
my_map bm;
bm.insert('A', 10);
bm.insert('B', 11);
my_map::map_type m{{'A', 10}, {'B', 11}};
EXPECT(m.cbegin()->first == bm.cbegin()->first);
EXPECT(m.cbegin()->second == bm.cbegin()->second);
EXPECT(std::next(m.cbegin(), 1)->first == std::next(bm.cbegin(), 1)->first);
EXPECT(std::next(m.cbegin(), 1)->second == std::next(bm.cbegin(), 1)->second);
}
{
using my_map = std::tuple_element<5, map_list>::type;
my_map bm;
bm.insert('A', 10);
bm.insert('B', 11);
my_map::map_type m{{'A', 10}, {'B', 11}};
EXPECT(m.cbegin()->first == bm.cbegin()->first);
EXPECT(m.cbegin()->second == bm.cbegin()->second);
EXPECT(std::next(m.cbegin(), 1)->first == std::next(bm.cbegin(), 1)->first);
EXPECT(std::next(m.cbegin(), 1)->second == std::next(bm.cbegin(), 1)->second);
}
{
using my_map = std::tuple_element<6, map_list>::type;
my_map bm;
bm.insert('A', 10);
bm.insert('B', 11);
my_map::map_type m{{'A', 10}, {'B', 11}};
EXPECT(m.cbegin()->first == bm.cbegin()->first);
EXPECT(m.cbegin()->second == bm.cbegin()->second);
EXPECT(std::next(m.cbegin(), 1)->first == std::next(bm.cbegin(), 1)->first);
EXPECT(std::next(m.cbegin(), 1)->second == std::next(bm.cbegin(), 1)->second);
}
{
using my_map = std::tuple_element<7, map_list>::type;
my_map bm;
bm.insert('A', 10);
bm.insert('B', 11);
my_map::map_type m{{'A', 10}, {'B', 11}};
EXPECT(m.cbegin()->first == bm.cbegin()->first);
EXPECT(m.cbegin()->second == bm.cbegin()->second);
EXPECT(std::next(m.cbegin(), 1)->first == std::next(bm.cbegin(), 1)->first);
EXPECT(std::next(m.cbegin(), 1)->second == std::next(bm.cbegin(), 1)->second);
}
},
CASE("cend()")
{
{
using my_map = std::tuple_element<0, map_list>::type;
my_map bm;
bm.insert('A', 10);
bm.insert('B', 11);
EXPECT(std::next(bm.cbegin(), 2) == bm.cend());
}
{
using my_map = std::tuple_element<1, map_list>::type;
my_map bm;
bm.insert('A', 10);
bm.insert('B', 11);
EXPECT(std::next(bm.cbegin(), 2) == bm.cend());
}
{
using my_map = std::tuple_element<2, map_list>::type;
my_map bm;
bm.insert('A', 10);
bm.insert('B', 11);
EXPECT(std::next(bm.cbegin(), 2) == bm.cend());
}
{
using my_map = std::tuple_element<3, map_list>::type;
my_map bm;
bm.insert('A', 10);
bm.insert('B', 11);
EXPECT(std::next(bm.cbegin(), 2) == bm.cend());
}
{
using my_map = std::tuple_element<4, map_list>::type;
my_map bm;
bm.insert('A', 10);
bm.insert('B', 11);
EXPECT(std::next(bm.cbegin(), 2) == bm.cend());
}
{
using my_map = std::tuple_element<5, map_list>::type;
my_map bm;
bm.insert('A', 10);
bm.insert('B', 11);
EXPECT(std::next(bm.cbegin(), 2) == bm.cend());
}
{
using my_map = std::tuple_element<6, map_list>::type;
my_map bm;
bm.insert('A', 10);
bm.insert('B', 11);
EXPECT(std::next(bm.cbegin(), 2) == bm.cend());
}
{
using my_map = std::tuple_element<7, map_list>::type;
my_map bm;
bm.insert('A', 10);
bm.insert('B', 11);
EXPECT(std::next(bm.cbegin(), 2) == bm.cend());
}
},
CASE("clear()")
{
{
using my_map = std::tuple_element<0, map_list>::type;
my_map bm;
bm.insert('A', 10);
bm.insert('B', 11);
EXPECT(not bm.empty());
bm.clear();
EXPECT(bm.empty());
}
{
using my_map = std::tuple_element<1, map_list>::type;
my_map bm;
bm.insert('A', 10);
bm.insert('B', 11);
EXPECT(not bm.empty());
bm.clear();
EXPECT(bm.empty());
}
{
using my_map = std::tuple_element<2, map_list>::type;
my_map bm;
bm.insert('A', 10);
bm.insert('B', 11);
EXPECT(not bm.empty());
bm.clear();
EXPECT(bm.empty());
}
{
using my_map = std::tuple_element<3, map_list>::type;
my_map bm;
bm.insert('A', 10);
bm.insert('B', 11);
EXPECT(not bm.empty());
bm.clear();
EXPECT(bm.empty());
}
{
using my_map = std::tuple_element<4, map_list>::type;
my_map bm;
bm.insert('A', 10);
bm.insert('B', 11);
EXPECT(not bm.empty());
bm.clear();
EXPECT(bm.empty());
}
{
using my_map = std::tuple_element<5, map_list>::type;
my_map bm;
bm.insert('A', 10);
bm.insert('B', 11);
EXPECT(not bm.empty());
bm.clear();
EXPECT(bm.empty());
}
{
using my_map = std::tuple_element<6, map_list>::type;
my_map bm;
bm.insert('A', 10);
bm.insert('B', 11);
EXPECT(not bm.empty());
bm.clear();
EXPECT(bm.empty());
}
{
using my_map = std::tuple_element<7, map_list>::type;
my_map bm;
bm.insert('A', 10);
bm.insert('B', 11);
EXPECT(not bm.empty());
bm.clear();
EXPECT(bm.empty());
}
},
CASE("insert() with non-duplex biunique_map")
{
{
using my_map = std::tuple_element<0, map_list>::type;
my_map bm1{{'A', 10}, {'B', 11}};
my_map bm2{{'C', 12}};
bm2.insert(bm1);
EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}, {'C', 12}}));
}
{
using my_map = std::tuple_element<1, map_list>::type;
my_map bm1{{'A', 10}, {'B', 11}};
my_map bm2{{'C', 12}};
bm2.insert(bm1);
EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}, {'C', 12}}));
}
{
using my_map = std::tuple_element<2, map_list>::type;
my_map bm1{{'A', 10}, {'B', 11}};
my_map bm2{{'C', 12}};
bm2.insert(bm1);
EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}, {'C', 12}}));
}
{
using my_map = std::tuple_element<3, map_list>::type;
my_map bm1{{'A', 10}, {'B', 11}};
my_map bm2{{'C', 12}};
bm2.insert(bm1);
EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}, {'C', 12}}));
}
{
using my_map = std::tuple_element<4, map_list>::type;
my_map bm1{{'A', 10}, {'B', 11}};
my_map bm2{{'C', 12}};
bm2.insert(bm1);
EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}, {'C', 12}}));
}
{
using my_map = std::tuple_element<5, map_list>::type;
my_map bm1{{'A', 10}, {'B', 11}};
my_map bm2{{'C', 12}};
bm2.insert(bm1);
EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}, {'C', 12}}));
}
{
using my_map = std::tuple_element<6, map_list>::type;
my_map bm1{{'A', 10}, {'B', 11}};
my_map bm2{{'C', 12}};
bm2.insert(bm1);
EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}, {'C', 12}}));
}
{
using my_map = std::tuple_element<7, map_list>::type;
my_map bm1{{'A', 10}, {'B', 11}};
my_map bm2{{'C', 12}};
bm2.insert(bm1);
EXPECT(same_map(bm2, {{'A', 10}, {'B', 11}, {'C', 12}}));
}
},
CASE("insert() with duplex biunique_map")
{
{
using my_map = std::tuple_element<0, map_list>::type;
my_map bm1{{'A', 10}, {'B', 11}};
my_map bm2{{'C', 12}, {'A', 10}};
my_map bm3{{'D', 13}, {'A', 14}};
my_map bm4{{'E', 14}, {'F', 11}};
bm1.insert(bm2);
EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}, {'C', 12}}));
bm1.insert(bm3);
EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}}));
bm1.insert(bm4);
EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}, {'E', 14}}));
}
{
using my_map = std::tuple_element<1, map_list>::type;
my_map bm1{{'A', 10}, {'B', 11}};
my_map bm2{{'C', 12}, {'A', 10}};
my_map bm3{{'D', 13}, {'A', 14}};
my_map bm4{{'E', 14}, {'F', 11}};
bm1.insert(bm2);
EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}, {'C', 12}}));
bm1.insert(bm3);
EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}}));
bm1.insert(bm4);
EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}, {'E', 14}}));
}
{
using my_map = std::tuple_element<2, map_list>::type;
my_map bm1{{'A', 10}, {'B', 11}};
my_map bm2{{'C', 12}, {'A', 10}};
my_map bm3{{'D', 13}, {'A', 14}};
my_map bm4{{'E', 14}, {'F', 11}};
bm1.insert(bm2);
EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}, {'C', 12}}));
bm1.insert(bm3);
EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}}));
bm1.insert(bm4);
EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}, {'E', 14}}));
}
{
using my_map = std::tuple_element<3, map_list>::type;
my_map bm1{{'A', 10}, {'B', 11}};
my_map bm2{{'C', 12}, {'A', 10}};
my_map bm3{{'D', 13}, {'A', 14}};
my_map bm4{{'E', 14}, {'F', 11}};
bm1.insert(bm2);
EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}, {'C', 12}}));
bm1.insert(bm3);
EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}}));
bm1.insert(bm4);
EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}, {'E', 14}}));
}
{
using my_map = std::tuple_element<4, map_list>::type;
my_map bm1{{'A', 10}, {'B', 11}};
my_map bm2{{'C', 12}, {'A', 10}};
my_map bm3{{'C', 12}, {'A', 13}};
my_map bm4{{'C', 12}, {'D', 10}};
EXPECT_THROWS_AS(bm1.insert(bm2), std::invalid_argument);
EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}}));
EXPECT_THROWS_AS(bm1.insert(bm3), std::invalid_argument);
EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}}));
EXPECT_THROWS_AS(bm1.insert(bm4), std::invalid_argument);
EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<5, map_list>::type;
my_map bm1{{'A', 10}, {'B', 11}};
my_map bm2{{'C', 12}, {'A', 10}};
my_map bm3{{'C', 12}, {'A', 13}};
my_map bm4{{'C', 12}, {'D', 10}};
EXPECT_THROWS_AS(bm1.insert(bm2), std::invalid_argument);
EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}}));
EXPECT_THROWS_AS(bm1.insert(bm3), std::invalid_argument);
EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}}));
EXPECT_THROWS_AS(bm1.insert(bm4), std::invalid_argument);
EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<6, map_list>::type;
my_map bm1{{'A', 10}, {'B', 11}};
my_map bm2{{'C', 12}, {'A', 10}};
my_map bm3{{'C', 12}, {'A', 13}};
my_map bm4{{'C', 12}, {'D', 10}};
EXPECT_THROWS_AS(bm1.insert(bm2), std::invalid_argument);
EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}}));
EXPECT_THROWS_AS(bm1.insert(bm3), std::invalid_argument);
EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}}));
EXPECT_THROWS_AS(bm1.insert(bm4), std::invalid_argument);
EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<7, map_list>::type;
my_map bm1{{'A', 10}, {'B', 11}};
my_map bm2{{'C', 12}, {'A', 10}};
my_map bm3{{'C', 12}, {'A', 13}};
my_map bm4{{'C', 12}, {'D', 10}};
EXPECT_THROWS_AS(bm1.insert(bm2), std::invalid_argument);
EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}}));
EXPECT_THROWS_AS(bm1.insert(bm3), std::invalid_argument);
EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}}));
EXPECT_THROWS_AS(bm1.insert(bm4), std::invalid_argument);
EXPECT(same_map(bm1, {{'A', 10}, {'B', 11}}));
}
},
CASE("insert() with non-duplex initializer_list")
{
{
using my_map = std::tuple_element<0, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
bm.insert({{'C', 12}});
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}}));
}
{
using my_map = std::tuple_element<1, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
bm.insert({{'C', 12}});
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}}));
}
{
using my_map = std::tuple_element<2, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
bm.insert({{'C', 12}});
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}}));
}
{
using my_map = std::tuple_element<3, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
bm.insert({{'C', 12}});
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}}));
}
{
using my_map = std::tuple_element<4, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
bm.insert({{'C', 12}});
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}}));
}
{
using my_map = std::tuple_element<5, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
bm.insert({{'C', 12}});
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}}));
}
{
using my_map = std::tuple_element<6, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
bm.insert({{'C', 12}});
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}}));
}
{
using my_map = std::tuple_element<7, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
bm.insert({{'C', 12}});
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}}));
}
},
CASE("insert() with duplex initializer_list")
{
{
using my_map = std::tuple_element<0, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
bm.insert({{'C', 12}, {'A', 10}});
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}}));
bm.insert({{'D', 13}, {'A', 14}});
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}}));
bm.insert({{'E', 14}, {'F', 11}});
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}, {'E', 14}}));
}
{
using my_map = std::tuple_element<1, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
bm.insert({{'C', 12}, {'A', 10}});
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}}));
bm.insert({{'D', 13}, {'A', 14}});
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}}));
bm.insert({{'E', 14}, {'F', 11}});
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}, {'E', 14}}));
}
{
using my_map = std::tuple_element<2, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
bm.insert({{'C', 12}, {'A', 10}});
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}}));
bm.insert({{'D', 13}, {'A', 14}});
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}}));
bm.insert({{'E', 14}, {'F', 11}});
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}, {'E', 14}}));
}
{
using my_map = std::tuple_element<3, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
bm.insert({{'C', 12}, {'A', 10}});
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}}));
bm.insert({{'D', 13}, {'A', 14}});
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}}));
bm.insert({{'E', 14}, {'F', 11}});
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}, {'E', 14}}));
}
{
using my_map = std::tuple_element<4, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT_THROWS_AS(bm.insert({{'A', 10}, {'C', 12}}), std::invalid_argument);
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
EXPECT_THROWS_AS(bm.insert({{'D', 13}, {'A', 14}}), std::invalid_argument);
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
EXPECT_THROWS_AS(bm.insert({{'E', 14}, {'F', 11}}), std::invalid_argument);
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<5, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT_THROWS_AS(bm.insert({{'A', 10}, {'C', 12}}), std::invalid_argument);
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
EXPECT_THROWS_AS(bm.insert({{'D', 13}, {'A', 14}}), std::invalid_argument);
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
EXPECT_THROWS_AS(bm.insert({{'E', 14}, {'F', 11}}), std::invalid_argument);
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<6, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT_THROWS_AS(bm.insert({{'A', 10}, {'C', 12}}), std::invalid_argument);
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
EXPECT_THROWS_AS(bm.insert({{'D', 13}, {'A', 14}}), std::invalid_argument);
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
EXPECT_THROWS_AS(bm.insert({{'E', 14}, {'F', 11}}), std::invalid_argument);
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<7, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT_THROWS_AS(bm.insert({{'A', 10}, {'C', 12}}), std::invalid_argument);
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
EXPECT_THROWS_AS(bm.insert({{'D', 13}, {'A', 14}}), std::invalid_argument);
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
EXPECT_THROWS_AS(bm.insert({{'E', 14}, {'F', 11}}), std::invalid_argument);
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
}
},
CASE("insert() with non-duplex iterator")
{
{
using my_map = std::tuple_element<0, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
const std::vector<my_map::value_type> v{{'C', 12}, {'D', 13}};
bm.insert(v.cbegin(), v.cend());
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}}));
const my_map::map_type m{{'E', 14}, {'F', 15}};
bm.insert(m.cbegin(), m.cend());
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}, {'E', 14}, {'F', 15}}));
}
{
using my_map = std::tuple_element<1, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
const std::vector<my_map::value_type> v{{'C', 12}, {'D', 13}};
bm.insert(v.cbegin(), v.cend());
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}}));
const my_map::map_type m{{'E', 14}, {'F', 15}};
bm.insert(m.cbegin(), m.cend());
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}, {'E', 14}, {'F', 15}}));
}
{
using my_map = std::tuple_element<2, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
const std::vector<my_map::value_type> v{{'C', 12}, {'D', 13}};
bm.insert(v.cbegin(), v.cend());
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}}));
const my_map::map_type m{{'E', 14}, {'F', 15}};
bm.insert(m.cbegin(), m.cend());
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}, {'E', 14}, {'F', 15}}));
}
{
using my_map = std::tuple_element<3, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
const std::vector<my_map::value_type> v{{'C', 12}, {'D', 13}};
bm.insert(v.cbegin(), v.cend());
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}}));
const my_map::map_type m{{'E', 14}, {'F', 15}};
bm.insert(m.cbegin(), m.cend());
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}, {'E', 14}, {'F', 15}}));
}
{
using my_map = std::tuple_element<4, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
const std::vector<my_map::value_type> v{{'C', 12}, {'D', 13}};
bm.insert(v.cbegin(), v.cend());
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}}));
const my_map::map_type m{{'E', 14}, {'F', 15}};
bm.insert(m.cbegin(), m.cend());
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}, {'E', 14}, {'F', 15}}));
}
{
using my_map = std::tuple_element<5, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
const std::vector<my_map::value_type> v{{'C', 12}, {'D', 13}};
bm.insert(v.cbegin(), v.cend());
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}}));
const my_map::map_type m{{'E', 14}, {'F', 15}};
bm.insert(m.cbegin(), m.cend());
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}, {'E', 14}, {'F', 15}}));
}
{
using my_map = std::tuple_element<6, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
const std::vector<my_map::value_type> v{{'C', 12}, {'D', 13}};
bm.insert(v.cbegin(), v.cend());
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}}));
const my_map::map_type m{{'E', 14}, {'F', 15}};
bm.insert(m.cbegin(), m.cend());
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}, {'E', 14}, {'F', 15}}));
}
{
using my_map = std::tuple_element<7, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
const std::vector<my_map::value_type> v{{'C', 12}, {'D', 13}};
bm.insert(v.cbegin(), v.cend());
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}}));
const my_map::map_type m{{'E', 14}, {'F', 15}};
bm.insert(m.cbegin(), m.cend());
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}, {'E', 14}, {'F', 15}}));
}
},
CASE("insert() with duplex iterator")
{
{
using my_map = std::tuple_element<0, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
const std::vector<my_map::value_type> v{{'C', 10}, {'D', 13}};
bm.insert(v.cbegin(), v.cend());
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'D', 13}}));
const my_map::map_type m{{'E', 14}, {'F', 10}};
bm.insert(m.cbegin(), m.cend());
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'D', 13}, {'E', 14}}));
}
{
using my_map = std::tuple_element<1, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
const std::vector<my_map::value_type> v{{'C', 10}, {'D', 13}};
bm.insert(v.cbegin(), v.cend());
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'D', 13}}));
const my_map::map_type m{{'E', 14}, {'F', 10}};
bm.insert(m.cbegin(), m.cend());
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'D', 13}, {'E', 14}}));
}
{
using my_map = std::tuple_element<2, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
const std::vector<my_map::value_type> v{{'C', 10}, {'D', 13}};
bm.insert(v.cbegin(), v.cend());
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'D', 13}}));
const my_map::map_type m{{'E', 14}, {'F', 10}};
bm.insert(m.cbegin(), m.cend());
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'D', 13}, {'E', 14}}));
}
{
using my_map = std::tuple_element<3, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
const std::vector<my_map::value_type> v{{'C', 10}, {'D', 13}};
bm.insert(v.cbegin(), v.cend());
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'D', 13}}));
const my_map::map_type m{{'E', 14}, {'F', 10}};
bm.insert(m.cbegin(), m.cend());
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'D', 13}, {'E', 14}}));
}
{
using my_map = std::tuple_element<4, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
const std::vector<my_map::value_type> v{{'C', 10}, {'D', 13}};
EXPECT_THROWS_AS(bm.insert(v.cbegin(), v.cend()), std::invalid_argument);
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
const my_map::map_type m{{'E', 14}, {'F', 10}};
EXPECT_THROWS_AS(bm.insert(m.cbegin(), m.cend()), std::invalid_argument);
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<5, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
const std::vector<my_map::value_type> v{{'C', 10}, {'D', 13}};
EXPECT_THROWS_AS(bm.insert(v.cbegin(), v.cend()), std::invalid_argument);
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
const my_map::map_type m{{'E', 14}, {'F', 10}};
EXPECT_THROWS_AS(bm.insert(m.cbegin(), m.cend()), std::invalid_argument);
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<6, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
const std::vector<my_map::value_type> v{{'C', 10}, {'D', 13}};
EXPECT_THROWS_AS(bm.insert(v.cbegin(), v.cend()), std::invalid_argument);
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
const my_map::map_type m{{'E', 14}, {'F', 10}};
EXPECT_THROWS_AS(bm.insert(m.cbegin(), m.cend()), std::invalid_argument);
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<7, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
const std::vector<my_map::value_type> v{{'C', 10}, {'D', 13}};
EXPECT_THROWS_AS(bm.insert(v.cbegin(), v.cend()), std::invalid_argument);
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
const my_map::map_type m{{'E', 14}, {'F', 10}};
EXPECT_THROWS_AS(bm.insert(m.cbegin(), m.cend()), std::invalid_argument);
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
}
},
CASE("insert() with non-duplex pair")
{
{
using my_map = std::tuple_element<0, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
bm.insert(my_map::value_type{'C', 12});
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}}));
}
{
using my_map = std::tuple_element<1, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
bm.insert(my_map::value_type{'C', 12});
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}}));
}
{
using my_map = std::tuple_element<2, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
bm.insert(my_map::value_type{'C', 12});
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}}));
}
{
using my_map = std::tuple_element<3, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
bm.insert(my_map::value_type{'C', 12});
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}}));
}
{
using my_map = std::tuple_element<4, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
bm.insert(my_map::value_type{'C', 12});
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}}));
}
{
using my_map = std::tuple_element<5, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
bm.insert(my_map::value_type{'C', 12});
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}}));
}
{
using my_map = std::tuple_element<6, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
bm.insert(my_map::value_type{'C', 12});
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}}));
}
{
using my_map = std::tuple_element<7, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
bm.insert(my_map::value_type{'C', 12});
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}}));
}
},
CASE("insert() with duplex pair")
{
{
using my_map = std::tuple_element<0, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
bm.insert(my_map::value_type{'A', 12});
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
bm.insert(my_map::value_type{'C', 11});
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<1, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
bm.insert(my_map::value_type{'A', 12});
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
bm.insert(my_map::value_type{'C', 11});
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<2, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
bm.insert(my_map::value_type{'A', 12});
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
bm.insert(my_map::value_type{'C', 11});
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<3, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
bm.insert(my_map::value_type{'A', 12});
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
bm.insert(my_map::value_type{'C', 11});
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<4, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT_THROWS_AS(bm.insert(my_map::value_type{'A', 12}), std::invalid_argument);
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
EXPECT_THROWS_AS(bm.insert(my_map::value_type{'C', 11}), std::invalid_argument);
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<5, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT_THROWS_AS(bm.insert(my_map::value_type{'A', 12}), std::invalid_argument);
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
EXPECT_THROWS_AS(bm.insert(my_map::value_type{'C', 11}), std::invalid_argument);
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<6, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT_THROWS_AS(bm.insert(my_map::value_type{'A', 12}), std::invalid_argument);
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
EXPECT_THROWS_AS(bm.insert(my_map::value_type{'C', 11}), std::invalid_argument);
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<7, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT_THROWS_AS(bm.insert(my_map::value_type{'A', 12}), std::invalid_argument);
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
EXPECT_THROWS_AS(bm.insert(my_map::value_type{'C', 11}), std::invalid_argument);
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
}
},
CASE("insert() with non-duplex f and s")
{
{
using my_map = std::tuple_element<0, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
bm.insert('C', 12);
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}}));
}
{
using my_map = std::tuple_element<1, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
bm.insert('C', 12);
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}}));
}
{
using my_map = std::tuple_element<2, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
bm.insert('C', 12);
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}}));
}
{
using my_map = std::tuple_element<3, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
bm.insert('C', 12);
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}}));
}
{
using my_map = std::tuple_element<4, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
bm.insert('C', 12);
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}}));
}
{
using my_map = std::tuple_element<5, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
bm.insert('C', 12);
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}}));
}
{
using my_map = std::tuple_element<6, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
bm.insert('C', 12);
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}}));
}
{
using my_map = std::tuple_element<7, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
bm.insert('C', 12);
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}, {'C', 12}}));
}
},
CASE("insert() with duplex f and s")
{
{
using my_map = std::tuple_element<0, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
bm.insert('A', 12);
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
bm.insert('C', 11);
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<1, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
bm.insert('A', 12);
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
bm.insert('C', 11);
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<2, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
bm.insert('A', 12);
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
bm.insert('C', 11);
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<3, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
bm.insert('A', 12);
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
bm.insert('C', 11);
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<4, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT_THROWS_AS(bm.insert('A', 12), std::invalid_argument);
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
EXPECT_THROWS_AS(bm.insert('C', 11), std::invalid_argument);
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<5, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT_THROWS_AS(bm.insert('A', 12), std::invalid_argument);
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
EXPECT_THROWS_AS(bm.insert('C', 11), std::invalid_argument);
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<6, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT_THROWS_AS(bm.insert('A', 12), std::invalid_argument);
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
EXPECT_THROWS_AS(bm.insert('C', 11), std::invalid_argument);
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
}
{
using my_map = std::tuple_element<7, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT_THROWS_AS(bm.insert('A', 12), std::invalid_argument);
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
EXPECT_THROWS_AS(bm.insert('C', 11), std::invalid_argument);
EXPECT(same_map(bm, {{'A', 10}, {'B', 11}}));
}
},
CASE("has_f()")
{
{
using my_map = std::tuple_element<0, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT(bm.has_f('A'));
EXPECT(bm.has_f('B'));
EXPECT(not bm.has_f('C'));
}
{
using my_map = std::tuple_element<1, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT(bm.has_f('A'));
EXPECT(bm.has_f('B'));
EXPECT(not bm.has_f('C'));
}
{
using my_map = std::tuple_element<2, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT(bm.has_f('A'));
EXPECT(bm.has_f('B'));
EXPECT(not bm.has_f('C'));
}
{
using my_map = std::tuple_element<3, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT(bm.has_f('A'));
EXPECT(bm.has_f('B'));
EXPECT(not bm.has_f('C'));
}
{
using my_map = std::tuple_element<4, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT(bm.has_f('A'));
EXPECT(bm.has_f('B'));
EXPECT(not bm.has_f('C'));
}
{
using my_map = std::tuple_element<5, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT(bm.has_f('A'));
EXPECT(bm.has_f('B'));
EXPECT(not bm.has_f('C'));
}
{
using my_map = std::tuple_element<6, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT(bm.has_f('A'));
EXPECT(bm.has_f('B'));
EXPECT(not bm.has_f('C'));
}
{
using my_map = std::tuple_element<7, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT(bm.has_f('A'));
EXPECT(bm.has_f('B'));
EXPECT(not bm.has_f('C'));
}
},
CASE("has_s()")
{
{
using my_map = std::tuple_element<0, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT(bm.has_s(10));
EXPECT(bm.has_s(11));
EXPECT(not bm.has_s(12));
}
{
using my_map = std::tuple_element<1, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT(bm.has_s(10));
EXPECT(bm.has_s(11));
EXPECT(not bm.has_s(12));
}
{
using my_map = std::tuple_element<2, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT(bm.has_s(10));
EXPECT(bm.has_s(11));
EXPECT(not bm.has_s(12));
}
{
using my_map = std::tuple_element<3, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT(bm.has_s(10));
EXPECT(bm.has_s(11));
EXPECT(not bm.has_s(12));
}
{
using my_map = std::tuple_element<4, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT(bm.has_s(10));
EXPECT(bm.has_s(11));
EXPECT(not bm.has_s(12));
}
{
using my_map = std::tuple_element<5, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT(bm.has_s(10));
EXPECT(bm.has_s(11));
EXPECT(not bm.has_s(12));
}
{
using my_map = std::tuple_element<6, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT(bm.has_s(10));
EXPECT(bm.has_s(11));
EXPECT(not bm.has_s(12));
}
{
using my_map = std::tuple_element<7, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT(bm.has_s(10));
EXPECT(bm.has_s(11));
EXPECT(not bm.has_s(12));
}
},
CASE("erase_by_f()")
{
{
using my_map = std::tuple_element<0, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT(bm.has_f('A'));
bm.erase_by_f('A');
EXPECT(not bm.has_f('A'));
EXPECT(1UL == bm.size());
bm.erase_by_f('C');
EXPECT(1UL == bm.size());
EXPECT(bm.has_f('B'));
bm.erase_by_f('B');
EXPECT(not bm.has_f('B'));
}
{
using my_map = std::tuple_element<1, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT(bm.has_f('A'));
bm.erase_by_f('A');
EXPECT(not bm.has_f('A'));
EXPECT(1UL == bm.size());
bm.erase_by_f('C');
EXPECT(1UL == bm.size());
EXPECT(bm.has_f('B'));
bm.erase_by_f('B');
EXPECT(not bm.has_f('B'));
}
{
using my_map = std::tuple_element<2, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT(bm.has_f('A'));
bm.erase_by_f('A');
EXPECT(not bm.has_f('A'));
EXPECT(1UL == bm.size());
bm.erase_by_f('C');
EXPECT(1UL == bm.size());
EXPECT(bm.has_f('B'));
bm.erase_by_f('B');
EXPECT(not bm.has_f('B'));
}
{
using my_map = std::tuple_element<3, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT(bm.has_f('A'));
bm.erase_by_f('A');
EXPECT(not bm.has_f('A'));
EXPECT(1UL == bm.size());
bm.erase_by_f('C');
EXPECT(1UL == bm.size());
EXPECT(bm.has_f('B'));
bm.erase_by_f('B');
EXPECT(not bm.has_f('B'));
}
{
using my_map = std::tuple_element<4, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT(bm.has_f('A'));
bm.erase_by_f('A');
EXPECT(not bm.has_f('A'));
EXPECT(1UL == bm.size());
bm.erase_by_f('C');
EXPECT(1UL == bm.size());
EXPECT(bm.has_f('B'));
bm.erase_by_f('B');
EXPECT(not bm.has_f('B'));
}
{
using my_map = std::tuple_element<5, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT(bm.has_f('A'));
bm.erase_by_f('A');
EXPECT(not bm.has_f('A'));
EXPECT(1UL == bm.size());
bm.erase_by_f('C');
EXPECT(1UL == bm.size());
EXPECT(bm.has_f('B'));
bm.erase_by_f('B');
EXPECT(not bm.has_f('B'));
}
{
using my_map = std::tuple_element<6, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT(bm.has_f('A'));
bm.erase_by_f('A');
EXPECT(not bm.has_f('A'));
EXPECT(1UL == bm.size());
bm.erase_by_f('C');
EXPECT(1UL == bm.size());
EXPECT(bm.has_f('B'));
bm.erase_by_f('B');
EXPECT(not bm.has_f('B'));
}
{
using my_map = std::tuple_element<7, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT(bm.has_f('A'));
bm.erase_by_f('A');
EXPECT(not bm.has_f('A'));
EXPECT(1UL == bm.size());
bm.erase_by_f('C');
EXPECT(1UL == bm.size());
EXPECT(bm.has_f('B'));
bm.erase_by_f('B');
EXPECT(not bm.has_f('B'));
}
},
CASE("erase_by_s()")
{
{
using my_map = std::tuple_element<0, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT(bm.has_s(10));
bm.erase_by_s(10);
EXPECT(not bm.has_s(10));
EXPECT(1UL == bm.size());
bm.erase_by_s(12);
EXPECT(1UL == bm.size());
EXPECT(bm.has_s(11));
bm.erase_by_s(11);
EXPECT(not bm.has_s(11));
}
{
using my_map = std::tuple_element<1, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT(bm.has_s(10));
bm.erase_by_s(10);
EXPECT(not bm.has_s(10));
EXPECT(1UL == bm.size());
bm.erase_by_s(12);
EXPECT(1UL == bm.size());
EXPECT(bm.has_s(11));
bm.erase_by_s(11);
EXPECT(not bm.has_s(11));
}
{
using my_map = std::tuple_element<2, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT(bm.has_s(10));
bm.erase_by_s(10);
EXPECT(not bm.has_s(10));
EXPECT(1UL == bm.size());
bm.erase_by_s(12);
EXPECT(1UL == bm.size());
EXPECT(bm.has_s(11));
bm.erase_by_s(11);
EXPECT(not bm.has_s(11));
}
{
using my_map = std::tuple_element<3, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT(bm.has_s(10));
bm.erase_by_s(10);
EXPECT(not bm.has_s(10));
EXPECT(1UL == bm.size());
bm.erase_by_s(12);
EXPECT(1UL == bm.size());
EXPECT(bm.has_s(11));
bm.erase_by_s(11);
EXPECT(not bm.has_s(11));
}
{
using my_map = std::tuple_element<4, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT(bm.has_s(10));
bm.erase_by_s(10);
EXPECT(not bm.has_s(10));
EXPECT(1UL == bm.size());
bm.erase_by_s(12);
EXPECT(1UL == bm.size());
EXPECT(bm.has_s(11));
bm.erase_by_s(11);
EXPECT(not bm.has_s(11));
}
{
using my_map = std::tuple_element<5, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT(bm.has_s(10));
bm.erase_by_s(10);
EXPECT(not bm.has_s(10));
EXPECT(1UL == bm.size());
bm.erase_by_s(12);
EXPECT(1UL == bm.size());
EXPECT(bm.has_s(11));
bm.erase_by_s(11);
EXPECT(not bm.has_s(11));
}
{
using my_map = std::tuple_element<6, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT(bm.has_s(10));
bm.erase_by_s(10);
EXPECT(not bm.has_s(10));
EXPECT(1UL == bm.size());
bm.erase_by_s(12);
EXPECT(1UL == bm.size());
EXPECT(bm.has_s(11));
bm.erase_by_s(11);
EXPECT(not bm.has_s(11));
}
{
using my_map = std::tuple_element<7, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT(bm.has_s(10));
bm.erase_by_s(10);
EXPECT(not bm.has_s(10));
EXPECT(1UL == bm.size());
bm.erase_by_s(12);
EXPECT(1UL == bm.size());
EXPECT(bm.has_s(11));
bm.erase_by_s(11);
EXPECT(not bm.has_s(11));
}
},
CASE("f2s()")
{
{
using my_map = std::tuple_element<0, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT(10 == bm.f2s('A'));
EXPECT(11 == bm.f2s('B'));
EXPECT_THROWS_AS(bm.f2s('C'), std::out_of_range);
bm.clear();
EXPECT_THROWS_AS(bm.f2s('A'), std::out_of_range);
}
{
using my_map = std::tuple_element<1, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT(10 == bm.f2s('A'));
EXPECT(11 == bm.f2s('B'));
EXPECT(10 == bm.f2s('C'));
bm.clear();
EXPECT_THROWS_AS(bm.f2s('A'), std::out_of_range);
}
{
using my_map = std::tuple_element<2, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT(10 == bm.f2s('A'));
EXPECT(11 == bm.f2s('B'));
EXPECT(11 == bm.f2s('C'));
bm.clear();
EXPECT_THROWS_AS(bm.f2s('A'), std::out_of_range);
}
{
using my_map = std::tuple_element<3, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT(10 == bm.f2s('A'));
EXPECT(11 == bm.f2s('B'));
EXPECT_THROWS_AS(bm.f2s('C'), std::out_of_range);
bm.clear();
EXPECT_THROWS_AS(bm.f2s('A'), std::out_of_range);
}
{
using my_map = std::tuple_element<4, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT(10 == bm.f2s('A'));
EXPECT(11 == bm.f2s('B'));
EXPECT_THROWS_AS(bm.f2s('C'), std::out_of_range);
bm.clear();
EXPECT_THROWS_AS(bm.f2s('A'), std::out_of_range);
}
{
using my_map = std::tuple_element<5, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT(10 == bm.f2s('A'));
EXPECT(11 == bm.f2s('B'));
EXPECT(10 == bm.f2s('C'));
bm.clear();
EXPECT_THROWS_AS(bm.f2s('A'), std::out_of_range);
}
{
using my_map = std::tuple_element<6, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT(10 == bm.f2s('A'));
EXPECT(11 == bm.f2s('B'));
EXPECT(11 == bm.f2s('C'));
bm.clear();
EXPECT_THROWS_AS(bm.f2s('A'), std::out_of_range);
}
{
using my_map = std::tuple_element<7, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT(10 == bm.f2s('A'));
EXPECT(11 == bm.f2s('B'));
EXPECT_THROWS_AS(bm.f2s('C'), std::out_of_range);
bm.clear();
EXPECT_THROWS_AS(bm.f2s('A'), std::out_of_range);
}
},
CASE("s2f()")
{
{
using my_map = std::tuple_element<0, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT('A' == bm.s2f(10));
EXPECT('B' == bm.s2f(11));
EXPECT_THROWS_AS(bm.s2f(12), std::out_of_range);
bm.clear();
EXPECT_THROWS_AS(bm.s2f(10), std::out_of_range);
}
{
using my_map = std::tuple_element<1, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT('A' == bm.s2f(10));
EXPECT('B' == bm.s2f(11));
EXPECT('A' == bm.s2f(12));
bm.clear();
EXPECT_THROWS_AS(bm.s2f(10), std::out_of_range);
}
{
using my_map = std::tuple_element<2, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT('A' == bm.s2f(10));
EXPECT('B' == bm.s2f(11));
EXPECT('B' == bm.s2f(12));
bm.clear();
EXPECT_THROWS_AS(bm.s2f(10), std::out_of_range);
}
{
using my_map = std::tuple_element<3, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT('A' == bm.s2f(10));
EXPECT('B' == bm.s2f(11));
EXPECT_THROWS_AS(bm.s2f(12), std::out_of_range);
bm.clear();
EXPECT_THROWS_AS(bm.s2f(10), std::out_of_range);
}
{
using my_map = std::tuple_element<4, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT('A' == bm.s2f(10));
EXPECT('B' == bm.s2f(11));
EXPECT_THROWS_AS(bm.s2f(12), std::out_of_range);
bm.clear();
EXPECT_THROWS_AS(bm.s2f(10), std::out_of_range);
}
{
using my_map = std::tuple_element<5, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT('A' == bm.s2f(10));
EXPECT('B' == bm.s2f(11));
EXPECT('A' == bm.s2f(12));
bm.clear();
EXPECT_THROWS_AS(bm.s2f(10), std::out_of_range);
}
{
using my_map = std::tuple_element<6, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT('A' == bm.s2f(10));
EXPECT('B' == bm.s2f(11));
EXPECT('B' == bm.s2f(12));
bm.clear();
EXPECT_THROWS_AS(bm.s2f(10), std::out_of_range);
}
{
using my_map = std::tuple_element<7, map_list>::type;
my_map bm{{'A', 10}, {'B', 11}};
EXPECT('A' == bm.s2f(10));
EXPECT('B' == bm.s2f(11));
EXPECT_THROWS_AS(bm.s2f(12), std::out_of_range);
bm.clear();
EXPECT_THROWS_AS(bm.s2f(10), std::out_of_range);
}
},
};
int main(int argc, char* argv[])
{
return lest::run(specification, argc, argv);
}
/////////////////////////////////////////////////////////////////////////////
| 35.323187 | 154 | 0.428342 | suomesta |
3265452c988b768445d55f2700259fcd24c36539 | 532 | hpp | C++ | core/include/olreport/tengine_cfg_data.hpp | wangshankun/Tengine_Atlas | b5485039e72b4a624c795ff95d73eb6d719c7706 | [
"Apache-2.0"
] | 25 | 2018-12-09T09:31:56.000Z | 2021-08-12T10:32:19.000Z | core/include/olreport/tengine_cfg_data.hpp | wangshankun/Tengine_Atlas | b5485039e72b4a624c795ff95d73eb6d719c7706 | [
"Apache-2.0"
] | 1 | 2022-03-31T03:33:42.000Z | 2022-03-31T03:33:42.000Z | core/include/olreport/tengine_cfg_data.hpp | wangshankun/Tengine_Atlas | b5485039e72b4a624c795ff95d73eb6d719c7706 | [
"Apache-2.0"
] | 6 | 2018-12-16T01:18:42.000Z | 2019-09-18T07:29:56.000Z | #ifndef __TENGINE_CFG_DATA_HPP__
#define __TENGINE_CFG_DATA_HPP__
#ifndef EXTERN_CFG_REPORT_DAT
#define CFG_REPORT_TIMER 7200 //seconds
#define CFG_TENGINE_KEY "TENGINE_DEP_171_2019"
#define CFG_TENGINE_TOKEN "TENGINE_DEP"
#define CFG_APPID "tengine_others"
#define CFG_APP_KEY "EzsKwQBYpAADva6k"
#define CFG_API_VERSION "TENGINE_DEP_171"
#define CFG_HOST "cloud.openailab.com"
#define CFG_PORT 80
#define CFG_REQ_URL "/oas-cloud/application/ts/others/saveTengineInfo"
#else
#include "extern_cfg_report_dat.hpp"
#endif
#endif
| 23.130435 | 70 | 0.834586 | wangshankun |
326b6347cc3bf49ac4d638cfb6ce752f624bf001 | 1,568 | cpp | C++ | mse.cpp | ArnoGranier/cppCNN | 9573e01eb71a8fdbb6a62812ef02ce0641055277 | [
"MIT"
] | 8 | 2020-01-23T08:26:22.000Z | 2022-02-22T22:50:17.000Z | mse.cpp | ArnoGranier/cppCNN | 9573e01eb71a8fdbb6a62812ef02ce0641055277 | [
"MIT"
] | 1 | 2021-04-11T02:03:48.000Z | 2021-04-11T02:05:15.000Z | mse.cpp | ArnoGranier/cppCNN | 9573e01eb71a8fdbb6a62812ef02ce0641055277 | [
"MIT"
] | null | null | null | #include "mse.hpp"
namespace cppcnn{
double MSE::compute(const vector<double>& prediction,
int8_t expected_int) const
{
double loss=0.0;
// We receive the expected result as an int between 0 and 9 (equivalent to
// a label). The expected activation of the output layer of the network
// is the one-hot encoding of this int. i.e for
// 0 : [1, 0, 0, 0, 0, 0, 0, 0, 0, 0]
// 3 : [0, 0, 0, 1, 0, 0, 0, 0, 0, 0]
// etc..
// Here we compute the one-hot encoding
uint output_layer_size = prediction.size();
vector<double> expected_vector(output_layer_size, 0.0);
expected_vector[expected_int] = 1.0;
// Compute mean squared-error
for (uint it=0;it<output_layer_size;++it){
loss += std::pow(prediction[it]-expected_vector[it], 2);
}
return loss;
}
vector<double> MSE::deriv(const vector<double>& prediction,
int8_t expected_int) const
{
// Here we compute the one-hot encoding
uint output_layer_size = prediction.size();
vector<double> expected_vector(output_layer_size, 0.0);
expected_vector[expected_int] = 1.0;
// Gradient of mean squared errror for vector X and Y is just
// [0.5*(X_i-Y_i) for i in 1..N]
// We can discard the 0.5 because it does not change proportionality
transform(prediction.begin(), prediction.end(),
expected_vector.begin(), expected_vector.begin(),
std::minus<double>());
return expected_vector;
}
} // namespace | 32.666667 | 78 | 0.617347 | ArnoGranier |
3270b3b301028853379f60a7cfd8f8b6c5a9458d | 3,266 | cpp | C++ | Src/HideoutComponent.cpp | 4anotherday/DarkMaze | e032b05641019cf5d69fd5c8bec9949f250c6c3f | [
"MIT"
] | null | null | null | Src/HideoutComponent.cpp | 4anotherday/DarkMaze | e032b05641019cf5d69fd5c8bec9949f250c6c3f | [
"MIT"
] | null | null | null | Src/HideoutComponent.cpp | 4anotherday/DarkMaze | e032b05641019cf5d69fd5c8bec9949f250c6c3f | [
"MIT"
] | null | null | null | #include "HideoutComponent.h"
#include "HealthComponent.h"
#include "ComponentIDs.h"
#include "includeLUA.h"
#include "Transform.h"
#include "PlayerVisibilityComponent.h"
#include "UserComponentsIDs.h"
#include "GameObject.h"
#include "RenderObjectComponent.h"
#include "ColliderComponent.h"
#include "Engine.h"
#include "Logger.h"
ADD_COMPONENT(HideoutComponent)
HideoutComponent::HideoutComponent() :Component(UserComponentId::HideoutComponent), _log(nullptr), _playerTransform(nullptr), _myTransform(nullptr), _visibility(nullptr), _playerName("Player")
, _render(nullptr), _alphaMaterial("Practica1/BushAlpha"), _normalMaterial("Practica1/Bush"), _distance(1) {
}
HideoutComponent::~HideoutComponent()
{
}
void HideoutComponent::awake(luabridge::LuaRef& data)
{
if (LUAFIELDEXIST(PlayerName))
_playerName = GETLUASTRINGFIELD(PlayerName);
if (LUAFIELDEXIST(AlphaMaterial))
_alphaMaterial = GETLUASTRINGFIELD(AlphaMaterial);
if (LUAFIELDEXIST(NormalMaterial))
_normalMaterial = GETLUASTRINGFIELD(NormalMaterial);
}
void HideoutComponent::start()
{
_log = Logger::getInstance();
GameObject* go = Engine::getInstance()->findGameObject(_playerName);
if (go != nullptr)
{
_visibility = static_cast<PlayerVisibilityComponent*>(go->getComponent(UserComponentId::PlayerVisibilityComponent));
if (_visibility == nullptr)
throw "Player doesn't have PlayerVisibilityComponent";
_playerTransform = static_cast<Transform*>(go->getComponent(ComponentId::Transform));
if (_playerTransform == nullptr)
throw "Player doesn't have Transform";
_myTransform = GETCOMPONENT(Transform, ComponentId::Transform);
if (_myTransform == nullptr)
throw "Hideout doesn't have Transform";
SphereColliderComponent* col = GETCOMPONENT(SphereColliderComponent, ComponentId::SphereCollider);
if (col != nullptr)
_distance = 2 * col->getRadius();
else if (_log != nullptr) _log->log("Hideout doesn't have SphereColliderComponent", Logger::Level::WARN);
_render = GETCOMPONENT(RenderObjectComponent, ComponentId::RenderObject);
if (_render == nullptr && _log != nullptr)
_log->log("Hideout doesn't have RenderObjectComponent, transparencies won't work", Logger::Level::WARN);
}
else throw "Player GameObject not found";
}
void HideoutComponent::update()
{
//std::cout << _myTransform->getPosition().getX() << " " << _myTransform->getPosition().getY() << _myTransform->getPosition().getZ() << '\n';
//std::cout << _playerTransform->getPosition().getX() << " " << _playerTransform->getPosition().getY() << _playerTransform->getPosition().getZ() << '\n';
if (!_visibility->getVisible()) {
Vector3 pos(_myTransform->getPosition().getX(), _playerTransform->getPosition().getY(), _myTransform->getPosition().getZ());
float distance = std::abs((pos - _playerTransform->getPosition()).magnitude());
//the second check is to avoid other hideouts setting visible the player
if (distance >= _distance && distance <= 1.1 * _distance) {
_visibility->setVisible(true);
_render->setMaterial(_normalMaterial);
}
}
}
void HideoutComponent::onTrigger(GameObject* other)
{
if (other->getComponent(UserComponentId::PlayerVisibilityComponent) != nullptr) {
_visibility->setVisible(false);
_render->setMaterial(_alphaMaterial);
}
}
| 37.54023 | 192 | 0.748928 | 4anotherday |
327946e7065a6100efe3614c0625ad6f721a0199 | 20,551 | cpp | C++ | graphalgorithms/AStarDelay.cpp | AaronTrip/hog2 | 96616b40f4173959b127011c76f3e649688e1a99 | [
"MIT"
] | 2 | 2021-06-09T13:54:15.000Z | 2021-07-04T13:30:46.000Z | graphalgorithms/AStarDelay.cpp | AaronTrip/hog2 | 96616b40f4173959b127011c76f3e649688e1a99 | [
"MIT"
] | null | null | null | graphalgorithms/AStarDelay.cpp | AaronTrip/hog2 | 96616b40f4173959b127011c76f3e649688e1a99 | [
"MIT"
] | 2 | 2017-04-17T11:08:57.000Z | 2017-04-18T08:28:27.000Z | /*
* AStarDelay.cpp
* hog2
*
* Created by Nathan Sturtevant on 9/27/07.
* Copyright 2007 __MyCompanyName__. All rights reserved.
*
*/
#include <sys/time.h>
#include <math.h>
#include <cstring>
#include "AStarDelay.h"
using namespace AStarDelayUtil;
using namespace GraphSearchConstants;
const static bool verbose = false;//true;
//static unsigned long tickStart;
//
//static unsigned long tickGen;
void AStarDelay::GetPath(GraphEnvironment *_env, Graph* _g, graphState from, graphState to, std::vector<graphState> &thePath)
{
if (!InitializeSearch(_env,_g,from,to,thePath))
return;
struct timeval t0,t1;
gettimeofday(&t0,0);
while(!DoSingleSearchStep(thePath))
{}
gettimeofday(&t1,0);
// double usedtime = t1.tv_sec-t0.tv_sec + (t1.tv_usec-t0.tv_usec)/1000000.0;
//if(thePath.size() > 0)
// printf("\nNodes expanded=%ld, Nodes touched=%ld, Reopenings=%ld.\n",GetNodesExpanded(),GetNodesTouched(),GetNodesReopened());
//printf("Algorithm AStarDelay, time used=%lf sec, N/sec=%lf, solution cost=%lf, solution edges=%d.\n",usedtime, GetNodesExpanded()/usedtime,solutionCost,pathSize);
}
bool AStarDelay::InitializeSearch(GraphEnvironment *_env, Graph* _g, graphState from, graphState to, std::vector<graphState> &thePath)
{
env = _env;
g = _g;
nodesTouched = nodesExpanded = nodesReopened = 0;
metaexpanded = 0;
closedSize = 0;
start = from;
goal = to;
closedList.clear();
openQueue.reset();
delayQueue.reset();
// fQueue.reset();
thePath.clear();
//tickNewExp = tickReExp = tickBPMX = 0;
//nNewExp = nReExp = nBPMX = 0;
//strcpy(algname,"AStarDelay");
if ((from == UINT32_MAX) || (to == UINT32_MAX) || (from == to))
{
thePath.resize(0);
return false;
}
// step (1)
SearchNode first(env->HCost(start, goal), 0, start, start);
openQueue.Add(first);
F = 0;
return true;
}
bool AStarDelay::DoSingleSearchStep(std::vector<graphState> &thePath)
{
static int reopenCount = 0;
SearchNode topNode;
graphState temp;
bool found = false;
// printf("Reopen count: %d. Unique nodes: %ld. Log2 = %f\n",
// reopenCount, nodesExpanded-nodesReopened, log2(nodesExpanded-nodesReopened));
// printf("Delay queue: %d Open queue: %d goal? %s\n",
// delayQueue.size(), openQueue.size(),
// (env->GoalTest(temp = openQueue.top().currNode, goal))?"yes":"no");
// if we are about to open the goal off open, but the delay queue has
// lower costs, go to the delay queue first, no matter if we're allowed to
// or not
if ((delayQueue.size() > 0) && (openQueue.size() > 0) &&
(env->GoalTest(temp = openQueue.top().currNode, goal)) &&
(fless(delayQueue.top().gCost, openQueue.top().fCost)/*!fgreater(delayQueue.top().fCost, openQueue.top().fCost)*/))
{
do { // throw out nodes with higher cost than goal
topNode = delayQueue.Remove();
} while (fgreater(topNode.fCost, openQueue.top().fCost)/*!fless(topNode.fCost, openQueue.top().fCost)*/);
//reopenCount = 0;
nodesReopened++;
found = true;
}
else if ((reopenCount < fDelay(nodesExpanded-nodesReopened)) && (delayQueue.size() > 0) && (openQueue.size() > 0))
{
//SearchNodeCompare cmpkey;
if (fless(delayQueue.top().gCost, openQueue.top().fCost) /*!cmpkey(delayQueue.top() , openQueue.top())*/ )
{
topNode = delayQueue.Remove();
reopenCount++;
nodesReopened++;
}
else {
topNode = openQueue.Remove();
reopenCount = 0;
}
found = true;
}
else if ((reopenCount < fDelay(nodesExpanded-nodesReopened)) && (delayQueue.size() > 0))
{
nodesReopened++;
topNode = delayQueue.Remove();
reopenCount++;
found = true;
}
// else if (fQueue.size() > 0)
// {
// topNode = fQueue.Remove();
// canReopen = true;
// found = true;
// }
else if ((openQueue.size() > 0))
{
F = topNode.fCost;
topNode = openQueue.Remove();
reopenCount = 0;
found = true;
}
if (found)
{
return DoSingleStep(topNode, thePath);
}
else {
thePath.resize(0); // no path found!
closedList.clear();
openQueue.reset();
env = 0;
return true;
}
return false;
}
/* The steps refer to the pseudo codes of the corresponding algorithms */
bool AStarDelay::DoSingleStep(SearchNode &topNode,
std::vector<graphState> &thePath)
{
nodesExpanded += 1;
//if(topNode.rxp)
// nReExp++;
//else
// nNewExp++;
if (verbose)
{
printf("Expanding node %ld , gcost=%lf, h=%lf, f=%lf.\n",
topNode.currNode, topNode.gCost, topNode.fCost-topNode.gCost, topNode.fCost);
}
// unsigned long tickTmp ;//= clock();
// and if there are no lower f-costs on the other open lists...
// otherwise we need to delay this node
if (env->GoalTest(topNode.currNode, goal))
{
//printf("Found path to goal!\n");
closedList[topNode.currNode] = topNode; // this is necessary for ExtractPathToStart()
ExtractPathToStart(topNode.currNode, thePath);
return true;
}
// step (5), computing gi is delayed
neighbors.resize(0);
env->GetSuccessors(topNode.currNode, neighbors);
//tickGen = clock() - tickTmp;
bool doBPMX = false;
int ichild = 0;
_BPMX:
if(bpmxLevel >= 1)
if(doBPMX) {
ReversePropX1(topNode);
// counting supplement
//if(nodesExpanded%2) {
// nodesExpanded += 1;
// if(topNode.rxp)
// nReExp++;
// else
// nNewExp++;
//}
//nodesExpanded += 1; //ichild / (double)neighbors.size();
}
//tickStart = clock();
double minCost = DBL_MAX;
unsigned int x;
for (x = 0,ichild=1; x < neighbors.size(); x++,ichild++)
{
nodesTouched++;
double cost;
if(bpmxLevel >= 1) {
cost = HandleNeighborX(neighbors[x], topNode);
if(cost == 0) {
//if(topNode.rxp) {
// tickReExp += clock() - tickStart + tickGen;
// tickGen = 0;
//}
//else {
// tickNewExp += clock() - tickStart + tickGen;
// tickGen = 0;
//}
doBPMX = true;
goto _BPMX;
}
if (fless(cost, minCost))
minCost = cost;
}
else {
HandleNeighbor(neighbors[x], topNode);
}
}
//if(topNode.rxp) {
// tickReExp += clock() - tickStart + tickGen;
//}
//else {
// tickNewExp += clock() - tickStart + tickGen;
//}
// path max rule (i or ii?) // this is Mero rule (b), min rule -- allen
if(bpmxLevel >= 1)
if (fless(topNode.fCost-topNode.gCost, minCost))
topNode.fCost = topNode.gCost+minCost;
closedList[topNode.currNode] = topNode;
if(bpmxLevel >= 1)
if(fifo.size() > 0) {
Broadcast(1,fifo.size()); // (level, levelcount)
}
return false;
}
// for BPMX
void AStarDelay::ReversePropX1(SearchNode& topNode)
{
//tickStart = clock();
double maxh = topNode.fCost - topNode.gCost;
for(unsigned int x=0;x<neighbors.size();x++)
{
graphState neighbor = neighbors[x];
SearchNode neighborNode = openQueue.find(SearchNode(neighbor));
if(neighborNode.currNode == neighbor) {
maxh = max(maxh, (neighborNode.fCost - neighborNode.gCost) - env->GCost(topNode.currNode,neighbor));
}
else {
neighborNode = delayQueue.find(SearchNode(neighbor));
if(neighborNode.currNode == neighbor) {
maxh = max(maxh, (neighborNode.fCost - neighborNode.gCost) - env->GCost(topNode.currNode, neighbor));
}
else {
NodeLookupTable::iterator iter = closedList.find(neighbor);
if(iter != closedList.end()) {
neighborNode = iter->second;
double oh = maxh;
maxh = max(maxh, (neighborNode.fCost - neighborNode.gCost) - env->GCost(topNode.currNode,neighbor));
if(bpmxLevel > 1 && oh < maxh) {
fifo.push_back(neighbor);
}
}
else {
maxh = max(maxh, env->HCost(neighbor,goal) - env->GCost(topNode.currNode,neighbor));
}
}
}
}
//nBPMX++;
//tickBPMX += clock() - tickStart;
metaexpanded += 1; //
nodesExpanded += 1;
nodesTouched += neighbors.size();
topNode.fCost = maxh + topNode.gCost;
}
// multi level BPMX in *closed* list
/* BPMX can only center around closed nodes, but open nodes can get updated as well*/
// a recursive function
void AStarDelay::Broadcast(int level, int levelcount)
{ // we will only enque the newly updated (neighbor) nodes; or neighbor nodes being able to update others
NodeLookupTable::iterator iter;
SearchNode frontNode;
//tickStart = clock();
for(int i=0;i<levelcount;i++) {
graphState front = fifo.front();
fifo.pop_front();
iter = closedList.find(front);
if(iter == closedList.end()) {
frontNode = delayQueue.find(SearchNode(front));
if(frontNode.currNode != front)
continue;
}
else
frontNode = iter->second;
double frontH = frontNode.fCost - frontNode.gCost;
myneighbors.clear();
env->GetSuccessors(front, myneighbors);
// backward pass
for (unsigned int x = 0; x < myneighbors.size(); x++)
{
graphState neighbor = myneighbors[x];
iter = closedList.find(neighbor);
if(iter != closedList.end()) {
double edgeWeight = env->GCost(front,neighbor);
SearchNode neighborNode = iter->second;
double neighborH = neighborNode.fCost - neighborNode.gCost;
if(fgreater(neighborH - edgeWeight, frontH)) {
frontH = neighborH - edgeWeight;
frontNode.fCost = frontNode.gCost + frontH;
fifo.push_back(neighbor);
}
}
else {
SearchNode neighborNode = openQueue.find(SearchNode(neighbor));
if(neighborNode.currNode == neighbor) {
double edgeWeight = env->GCost(front,neighbor);
double neighborH = neighborNode.fCost - neighborNode.gCost;
if(fgreater(neighborH - edgeWeight, frontH)) {
frontH = neighborH - edgeWeight;
frontNode.fCost = frontNode.gCost + frontH;
}
}
else {
neighborNode = delayQueue.find(SearchNode(neighbor));
if(neighborNode.currNode == neighbor) {
double edgeWeight = env->GCost(front,neighbor);
double neighborH = neighborNode.fCost - neighborNode.gCost;
if(fgreater(neighborH - edgeWeight, frontH)) {
frontH = neighborH - edgeWeight;
frontNode.fCost = frontNode.gCost + frontH;
fifo.push_back(neighbor);
}
}
}
}
}
// store frontNode
closedList[front] = frontNode;
// forward pass
for (unsigned int x = 0; x < myneighbors.size(); x++)
{
graphState neighbor = myneighbors[x];
NodeLookupTable::iterator theIter = closedList.find(neighbor);
if (theIter != closedList.end())
{
double edgeWeight = env->GCost(front,neighbor);
SearchNode neighborNode = theIter->second;
double neighborH = neighborNode.fCost - neighborNode.gCost;
if(fgreater(frontH - edgeWeight, neighborH)) {
neighborNode.fCost = neighborNode.gCost + frontH - edgeWeight; // store neighborNode
closedList[neighbor] = neighborNode;
fifo.push_back(neighbor);
}
}
else {
SearchNode neighborNode = openQueue.find(SearchNode(neighbor));
if(neighborNode.currNode == neighbor) {
double edgeWeight = env->GCost(front,neighbor);
double neighborH = neighborNode.fCost - neighborNode.gCost;
if(fgreater(frontH - edgeWeight, neighborH)) {
neighborNode.fCost = neighborNode.gCost + frontH - edgeWeight;
openQueue.IncreaseKey(neighborNode);
}
}
else {
neighborNode = delayQueue.find(SearchNode(neighbor));
if(neighborNode.currNode == neighbor) {
double edgeWeight = env->GCost(front,neighbor);
double neighborH = neighborNode.fCost - neighborNode.gCost;
if(fgreater(frontH - edgeWeight, neighborH)) {
neighborNode.fCost = neighborNode.gCost + frontH - edgeWeight;
delayQueue.IncreaseKey(neighborNode);
fifo.push_back(neighbor);
}
}
}
}
}
}
//nBPMX += 2;
//tickBPMX += clock() - tickStart;
metaexpanded += 2; //
nodesExpanded += 2;
nodesTouched += 2*levelcount;
level++;
if(level < bpmxLevel && fifo.size() > 0)
Broadcast(level, fifo.size());
}
double AStarDelay::HandleNeighbor(graphState neighbor, SearchNode &topNode)
{
if (openQueue.IsIn(SearchNode(neighbor))) // in OPEN
{
return UpdateOpenNode(neighbor, topNode);
}
else if (closedList.find(neighbor) != closedList.end()) // in CLOSED
{
return UpdateClosedNode(neighbor, topNode);
}
else if (delayQueue.IsIn(SearchNode(neighbor))) // in DELAY
{
return UpdateDelayedNode(neighbor, topNode);
}
// else if (fQueue.IsIn(SearchNode(neighbor))) // in low g-cost!
// {
// return UpdateLowGNode(neighbor, topNode);
// }
else { // not opened yet
return AddNewNode(neighbor, topNode);
}
return 0;
}
double AStarDelay::HandleNeighborX(graphState neighbor, SearchNode &topNode)
{
SearchNode neighborNode;
NodeLookupTable::iterator iter;
double edge = env->GCost(topNode.currNode,neighbor);
double hTop = topNode.fCost - topNode.gCost;
if ((neighborNode = openQueue.find(SearchNode(neighbor))).currNode == neighbor) // in OPEN
{
if(fgreater(neighborNode.fCost - neighborNode.gCost - edge , hTop)) {
return 0;
}
return UpdateOpenNode(neighbor, topNode);
}
else if ((iter = closedList.find(neighbor)) != closedList.end()) // in CLOSED
{
neighborNode = iter->second;
if(fgreater(neighborNode.fCost - neighborNode.gCost - edge , hTop)) {
return 0;
}
return UpdateClosedNode(neighbor, topNode);
}
else if ((neighborNode = delayQueue.find(SearchNode(neighbor))).currNode == neighbor) // in DELAY
{
if(fgreater(neighborNode.fCost - neighborNode.gCost - edge , hTop)) {
return 0;
}
return UpdateDelayedNode(neighbor, topNode);
}
// else if (fQueue.IsIn(SearchNode(neighbor))) // in low g-cost!
// {
// return UpdateLowGNode(neighbor, topNode);
// }
else { // not opened yet
if(fgreater( env->HCost(neighbor,goal) - edge , hTop)) {
return 0;
}
return AddNewNode(neighbor, topNode);
}
return 0;
}
// return edge cost + h cost
double AStarDelay::AddNewNode(graphState neighbor, SearchNode &topNode)
{
graphState topNodeID = topNode.currNode;
double edgeCost = env->GCost(topNodeID,neighbor);
double gcost = topNode.gCost + edgeCost;
double h = max(env->HCost(neighbor,goal), topNode.fCost - topNode.gCost - edgeCost);
double fcost = gcost + h;
SearchNode n(fcost, gcost, neighbor, topNodeID);
n.isGoal = (neighbor == goal);
// if (fless(fcost, F))
// {
// fQueue.Add(n); // nodes with cost < F
// }
// else {
openQueue.Add(n);
// }
return edgeCost+n.fCost-n.gCost;
}
// return edge cost + h cost
double AStarDelay::UpdateOpenNode(graphState neighbor, SearchNode &topNode)
{
// lookup node
SearchNode n;
n = openQueue.find(SearchNode(neighbor));
double edgeCost = env->GCost(topNode.currNode, neighbor);
double oldf = n.fCost;
if(bpmxLevel >= 1)
n.fCost = max(n.fCost , topNode.fCost - topNode.gCost - edgeCost + n.gCost);
if (fless(topNode.gCost+edgeCost, n.gCost))
{
n.fCost -= n.gCost;
n.gCost = topNode.gCost+edgeCost;
n.fCost += n.gCost;
n.prevNode = topNode.currNode;
if(n.fCost < oldf)
openQueue.DecreaseKey(n);
else
openQueue.IncreaseKey(n);
}
else if(n.fCost > oldf)
openQueue.IncreaseKey(n);
// return value for pathmax
return edgeCost+n.fCost-n.gCost;
}
// return edge cost + h cost
double AStarDelay::UpdateClosedNode(graphState neighbor, SearchNode &topNode)
{
// lookup node
SearchNode n = closedList[neighbor];
double edgeCost = env->GCost(topNode.currNode, neighbor);
// check if we should update cost
if (fless(topNode.gCost+edgeCost, n.gCost))
{
double hCost = n.fCost - n.gCost;
n.gCost = topNode.gCost+edgeCost;
// do pathmax here -- update child-h to parent-h - edge cost
if(bpmxLevel >= 1)
hCost = max(topNode.fCost-topNode.gCost-edgeCost, hCost);
n.fCost = n.gCost + hCost;
n.prevNode = topNode.currNode;
// put into delay list if we can open it
closedList.erase(neighbor); // delete from CLOSED
//n.rxp = true;
delayQueue.Add(n); // add to delay list
//openQueue.Add(n);
}
else if(bpmxLevel >= 1)
if (fgreater(topNode.fCost-topNode.gCost-edgeCost, n.fCost-n.gCost)) // pathmax
{
n.fCost = topNode.fCost-topNode.gCost-edgeCost;
n.fCost += n.gCost;
closedList[neighbor] = n;
if(bpmxLevel > 1) {
fifo.push_back(neighbor);
}
}
// return value for pathmax
return edgeCost+n.fCost-n.gCost;
}
// return edge cost + h cost
double AStarDelay::UpdateDelayedNode(graphState neighbor, SearchNode &topNode)
{
// lookup node
SearchNode n;
n = delayQueue.find(SearchNode(neighbor));
double edgeCost = env->GCost(topNode.currNode, neighbor);
double oldf = n.fCost;
if(bpmxLevel >= 1)
n.fCost = max(n.fCost , topNode.fCost - topNode.gCost - edgeCost + n.gCost);
if (fless(topNode.gCost+edgeCost, n.gCost))
{
n.fCost -= n.gCost;
n.gCost = topNode.gCost+edgeCost;
n.fCost += n.gCost;
n.prevNode = topNode.currNode;
//if(n.fCost < oldf)
delayQueue.DecreaseKey(n);
//else
// delayQueue.IncreaseKey(n);
}
else if(n.fCost > oldf)
delayQueue.IncreaseKey(n);
// return value for pathmax
return edgeCost+n.fCost-n.gCost;
}
void AStarDelay::ExtractPathToStart(graphState goalNode, std::vector<graphState> &thePath)
{
SearchNode n;
closedSize = closedList.size();
if (closedList.find(goalNode) != closedList.end())
{
n = closedList[goalNode];
}
else {
n = openQueue.find(SearchNode(goalNode));
}
solutionCost = n.gCost;
do {
//solutionCost += env->GCost(n.prevNode,n.currNode);
thePath.push_back(n.currNode);
n = closedList[n.prevNode];
} while (n.currNode != n.prevNode);
//thePath.push_back(n.currNode);
pathSize = thePath.size();
}
//
//void AStarDelay::OpenGLDraw(int)
//{
// OpenGLDraw();
//}
void AStarDelay::OpenGLDraw() const
{
// //float r,gcost,b;
// double x,y,z;
// SearchNode sn;
// graphState nodeID;
// SearchNode topn;
// char buf[100];
//
// // draw nodes
// node_iterator ni = g->getNodeIter();
// for(node* n = g->nodeIterNext(ni); n; n = g->nodeIterNext(ni))
// {
// x = n->GetLabelF(kXCoordinate);
// y = n->GetLabelF(kYCoordinate);
// z = n->GetLabelF(kZCoordinate);
//
// nodeID = (graphState) n->GetNum();
//
// // if in closed
// NodeLookupTable::iterator hiter;
// if ((hiter = closedList.find(nodeID)) != closedList.end())
// {
// sn = hiter->second;
//
// memset(buf,0,100);
// sprintf(buf,"C %1.0f=%1.0f+%1.0f", sn.fCost, sn.gCost, (sn.fCost - sn.gCost));
// DrawText(x,y,z+0.05,0,0,0,buf);
//
// glColor3f(1,0,0); // red
// }
// // if in open
// else if (openQueue.IsIn(SearchNode(nodeID)))
// {
// sn = openQueue.find(SearchNode(nodeID));
// memset(buf,0,100);
// sprintf(buf,"O %1.0f=%1.0f+%1.0f", sn.fCost, sn.gCost, (sn.fCost - sn.gCost));
// DrawText(x,y,z+0.05,0,0,0,buf);
//
// glColor3f(0,0,1); // blue
// }
//// else if (fQueue.IsIn(SearchNode(nodeID)))
//// {
//// sn = fQueue.find(SearchNode(nodeID));
//// memset(buf,0,100);
//// sprintf(buf,"L %1.0f=%1.0f+%1.0f", sn.fCost, sn.gCost, (sn.fCost - sn.gCost));
//// DrawText(x,y,z+0.05,0,0,0,buf);
////
//// glColor3f(1,1,0); // yellow
//// }
// else if (delayQueue.IsIn(SearchNode(nodeID)))
// {
// sn = delayQueue.find(SearchNode(nodeID));
// memset(buf,0,100);
// sprintf(buf,"D %1.0f=%1.0f+%1.0f", sn.fCost, sn.gCost, (sn.fCost - sn.gCost));
// DrawText(x,y,z+0.05,0,0,0,buf);
//
// glColor3f(1,0,1); // purple
// }
// // neither in open nor closed, white
// else
// {
// glColor3f(1,1,1); // white
// }
// DrawSphere(x,y,z,0.025);
//
// // draw the text info, in black
// //DrawText(x,y,z+0.05,0,0,0,buf);
// }
//
//// draw edges
// edge_iterator ei = g->getEdgeIter();
// for(edge* e = g->edgeIterNext(ei); e; e = g->edgeIterNext(ei))
// {
// DrawEdge(e->getFrom(), e->getTo(), e->GetWeight());
// }
}
void AStarDelay::DrawText(double x, double y, double z, float r, float gg, float b, char* str)
{
//glPushMatrix();
// rotate ?
glPushMatrix();
glColor3f(r,gg,b);
glTranslatef(x,y,z);
glScalef(1.0/(20*120.0), 1.0/(20*120.0), 1);
glRotatef(180, 0.0, 0.0, 1.0);
glRotatef(180, 0.0, 1.0, 0.0);
int i=0;
while(str[i])
{
glutStrokeCharacter(GLUT_STROKE_ROMAN,str[i]);
i++;
}
glPopMatrix();
}
void AStarDelay::DrawEdge(unsigned int from, unsigned int to, double weight)
{
double x1,y1,z1;
double x2,y2,z2;
char buf[100] = {0};
node* nfrom = g->GetNode(from);
node* nto = g->GetNode(to);
x1 = nfrom->GetLabelF(kXCoordinate);
y1 = nfrom->GetLabelF(kYCoordinate);
z1 = nfrom->GetLabelF(kZCoordinate);
x2 = nto->GetLabelF(kXCoordinate);
y2 = nto->GetLabelF(kYCoordinate);
z2 = nto->GetLabelF(kZCoordinate);
// draw line segment
glBegin(GL_LINES);
glColor3f(1,1,0); // yellow
glVertex3f(x1,y1,z1);
glVertex3f(x2,y2,z2);
glEnd();
// draw weight info
sprintf(buf,"%ld",(long)weight);
DrawText((x1+x2)/2, (y1+y2)/2, (z1+z2)/2 + 0.05, 1, 0, 0, buf); // in red
}
| 25.592777 | 165 | 0.655297 | AaronTrip |
327d7915177103e31c46d8dc5f826a0c47939658 | 34,215 | cpp | C++ | ui/widgets/shader_node_view_widget.cpp | ppearson/ImaginePartial | 9871b052f2edeb023e2845578ad69c25c5baf7d2 | [
"Apache-2.0"
] | 1 | 2018-07-10T13:36:38.000Z | 2018-07-10T13:36:38.000Z | ui/widgets/shader_node_view_widget.cpp | ppearson/ImaginePartial | 9871b052f2edeb023e2845578ad69c25c5baf7d2 | [
"Apache-2.0"
] | null | null | null | ui/widgets/shader_node_view_widget.cpp | ppearson/ImaginePartial | 9871b052f2edeb023e2845578ad69c25c5baf7d2 | [
"Apache-2.0"
] | null | null | null | /*
Imagine
Copyright 2016 Peter Pearson.
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 "shader_node_view_widget.h"
#include <QGraphicsScene>
#include <QGraphicsItem>
#include <QPointF>
#include <QGLWidget>
#include <QWheelEvent>
#include <QMenu>
#include <QSignalMapper>
#include <cmath>
#include <set>
#include "shading/shader_node.h"
#include "shading/shader_nodes_collection.h"
#include "shader_node_view_items.h"
#include "shading/shader_op.h"
#include "utils/string_helpers.h"
#include "parameter.h"
namespace Imagine
{
// TODO: this is a bit overly-complex, but by design the GUI stuff is completely segmented from the backing data structures
// so that the GUI part isn't always needed and operates as an additional layer on top of the data structures.
// But it will be possible to reduce the amount of code here eventually.
ShaderNodeViewWidget::ShaderNodeViewWidget(ShaderNodeViewWidgetHost* pHost, QWidget* pParent)
: QGraphicsView(pParent),
m_mouseMode(eMouseNone), m_scale(0.8f), m_selectionType(eSelectionNone), m_pSelectedItem(nullptr),
m_pNodesCollection(nullptr), m_pHost(pHost), m_pInteractionConnectionItem(nullptr), m_selConnectionDragType(eSelConDragNone)
{
// setViewport(new QGLWidget(QGLFormat(QGL::SampleBuffers | QGL::DirectRendering)));
QGLFormat format = QGLFormat::defaultFormat();
format.setDepth(false);
format.setSampleBuffers(true);
setViewport(new QGLWidget(format));
for (unsigned int i = 0; i < 3; i++)
{
m_creationMenuSignalMapper[i] = nullptr;
}
updateCreationMenu();
//
QGraphicsScene* pScene = new QGraphicsScene(this);
pScene->setSceneRect(0, 0, 1600, 1600);
setScene(pScene);
centerOn(400, 400);
setCacheMode(CacheBackground);
setViewportUpdateMode(BoundingRectViewportUpdate);
setViewportUpdateMode(MinimalViewportUpdate);
// setViewportUpdateMode(FullViewportUpdate);
setRenderHint(QPainter::Antialiasing);
// setTransformationAnchor(AnchorViewCenter);
setTransformationAnchor(AnchorUnderMouse);
setMouseTracking(true);
setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
scale(m_scale, m_scale);
setMinimumSize(400, 400);
}
void ShaderNodeViewWidget::updateCreationMenu()
{
// create list of available Ops
std::vector<std::string> aOpNames;
m_pHost->getListOfNodeNames(aOpNames);
std::vector<std::string>::const_iterator itName = aOpNames.begin();
for (; itName != aOpNames.end(); ++itName)
{
const std::string& name = *itName;
std::string category;
std::string itemName;
splitInTwo(name, category, itemName, "/");
// find the category for the menu
std::map<std::string, NodeCreationMenuCategory*>::iterator itFind = m_aMenuCategories.find(category);
NodeCreationMenuCategory* pMenuCat = nullptr;
if (itFind == m_aMenuCategories.end())
{
// we haven't got this one yet, so create a new one
pMenuCat = new NodeCreationMenuCategory();
m_aMenuCategories[category] = pMenuCat;
}
else
{
pMenuCat = (*itFind).second;
}
QAction* pNewAction = new QAction(itemName.c_str(), this);
pMenuCat->nodeItems.emplace_back(NodeCreationMenuItem(category, itemName, pNewAction));
}
m_aMenuCategoriesIndexed.resize(m_aMenuCategories.size());
unsigned int index = 0;
std::map<std::string, NodeCreationMenuCategory*>::iterator itCat = m_aMenuCategories.begin();
for (; itCat != m_aMenuCategories.end(); ++itCat)
{
NodeCreationMenuCategory* pCat = (*itCat).second;
pCat->index = index;
if (index < 3)
{
QSignalMapper* pNewSignalMapper = new QSignalMapper(this);
// TODO: actually, this *could* be done with a single mapping using offset indices...
if (index == 0)
{
QObject::connect(pNewSignalMapper, SIGNAL(mapped(int)), this, SLOT(menuNewNode0(int)));
}
else if (index == 1)
{
QObject::connect(pNewSignalMapper, SIGNAL(mapped(int)), this, SLOT(menuNewNode1(int)));
}
else if (index == 2)
{
QObject::connect(pNewSignalMapper, SIGNAL(mapped(int)), this, SLOT(menuNewNode2(int)));
}
m_aMenuCategoriesIndexed[index] = pCat;
unsigned int menuIndex = 0;
// now set up the mappings for each QAction for each menu item to the signal mapper
std::vector<NodeCreationMenuItem>::iterator itNodeItem = pCat->nodeItems.begin();
for (; itNodeItem != pCat->nodeItems.end(); ++itNodeItem)
{
NodeCreationMenuItem& menuItem = *itNodeItem;
connect(menuItem.pAction, SIGNAL(triggered()), pNewSignalMapper, SLOT(map()));
pNewSignalMapper->setMapping(menuItem.pAction, menuIndex++);
}
m_creationMenuSignalMapper[index] = pNewSignalMapper;
index++;
}
}
}
ShaderNodeViewWidget::~ShaderNodeViewWidget()
{
}
void ShaderNodeViewWidget::createUIItemsFromNodesCollection()
{
if (!m_pNodesCollection)
return;
// clear existing items
QGraphicsScene* pScene = scene();
pScene->clear();
m_pSelectedItem = nullptr;
m_aConnections.clear();
m_aNodes.clear();
// for the moment, use a naive two-pass approach...
std::map<unsigned int, ShaderNodeUI*> aCreatedUINodes;
std::vector<ShaderNode*>& nodesArray = m_pNodesCollection->getNodes();
// create the UI nodes first
std::vector<ShaderNode*>::iterator itNodes = nodesArray.begin();
for (; itNodes != nodesArray.end(); ++itNodes)
{
ShaderNode* pNode = *itNodes;
ShaderNodeUI* pNewUINode = new ShaderNodeUI(pNode);
unsigned int nodeID = pNode->getNodeID();
aCreatedUINodes[nodeID] = pNewUINode;
pScene->addItem(pNewUINode);
m_aNodes.emplace_back(pNewUINode);
}
// then go back and add connections for them
itNodes = nodesArray.begin();
for (; itNodes != nodesArray.end(); ++itNodes)
{
ShaderNode* pNode = *itNodes;
unsigned int thisNodeID = pNode->getNodeID();
std::map<unsigned int, ShaderNodeUI*>::iterator itFindMain = aCreatedUINodes.find(thisNodeID);
if (itFindMain == aCreatedUINodes.end())
{
// something's gone wrong
continue;
}
ShaderNodeUI* pThisUINode = (*itFindMain).second;
// connect all input connections to their source output ports...
const std::vector<ShaderNode::InputShaderPort>& aInputPorts = pNode->getInputPorts();
unsigned int inputIndex = 0;
std::vector<ShaderNode::InputShaderPort>::const_iterator itInputPort = aInputPorts.begin();
for (; itInputPort != aInputPorts.end(); ++itInputPort, inputIndex++)
{
const ShaderNode::InputShaderPort& inputPort = *itInputPort;
if (inputPort.connection.nodeID == ShaderNode::kNodeConnectionNone)
continue;
// otherwise, connect it to the output port on the source node
std::map<unsigned int, ShaderNodeUI*>::iterator itFindConnectionNode = aCreatedUINodes.find(inputPort.connection.nodeID);
if (itFindConnectionNode != aCreatedUINodes.end())
{
ShaderNodeUI* pOutputUINode = (*itFindConnectionNode).second;
ShaderConnectionUI* pConnection = new ShaderConnectionUI(pOutputUINode, pThisUINode);
pConnection->setSourceNodePortIndex(inputPort.connection.portIndex);
pConnection->setDestinationNodePortIndex(inputIndex);
pScene->addItem(pConnection);
m_aConnections.emplace_back(pConnection);
pThisUINode->setInputPortConnectionItem(inputIndex, pConnection);
pOutputUINode->addOutputPortConnectionItem(inputPort.connection.portIndex, pConnection);
}
}
}
}
void ShaderNodeViewWidget::wheelEvent(QWheelEvent* event)
{
return;
float scaleAmount = powf(1.15f, event->delta());
qreal scaleFactor = transform().scale(scaleAmount, scaleAmount).mapRect(QRectF(0, 0, 1, 1)).width();
if (scaleFactor < 0.07 || scaleFactor > 5.0)
return;
if (m_scale * scaleFactor < 0.1f || m_scale * scaleFactor > 10.0f)
return;
m_scale *= scaleFactor;
scale(scaleFactor, scaleFactor);
}
void ShaderNodeViewWidget::mousePressEvent(QMouseEvent* event)
{
m_lastMousePos = getEventPos(event);
m_lastMouseScenePos = mapToScene(event->pos());
if (event->button() == Qt::RightButton)
{
showRightClickMenu(event);
return;
}
QPointF cursorScenePos = mapToScene(event->pos().x(), event->pos().y());
bool selectedSomething = false;
const bool doQuick = false;
if (doQuick)
{
QTransform dummy;
QGraphicsItem* pHitItem = scene()->itemAt(event->pos(), dummy);
// if (pHitItem->)
if (m_pSelectedItem)
{
m_pSelectedItem->setSelected(false);
}
if (pHitItem)
{
m_selectionType = eSelectionNode;
pHitItem->setSelected(true);
m_pSelectedItem = pHitItem;
}
}
else
{
if (m_pSelectedItem)
{
m_pSelectedItem->setSelected(false);
}
// doing it this way (while inefficient as no acceleration structure is used) means we only get
// the Nodes. Using scene.itemAt() returns children of QGraphicsItem object (like the text items)
std::vector<ShaderNodeUI*>::iterator itNodes = m_aNodes.begin();
for (; itNodes != m_aNodes.end(); ++itNodes)
{
ShaderNodeUI* pTestNode = *itNodes;
ShaderNodeUI::SelectionInfo selInfo;
if (pTestNode->doesContain(cursorScenePos, selInfo))
{
if (selInfo.selectionType == ShaderNodeUI::SelectionInfo::eSelectionNode)
{
m_pSelectedItem = pTestNode;
m_pSelectedItem->setSelected(true);
selectedSomething = true;
m_selectionType = eSelectionNode;
}
else if (selInfo.selectionType == ShaderNodeUI::SelectionInfo::eSelectionInputPort)
{
selectedSomething = true;
m_selectionType = eSelectionEdgeInput;
// see if the selected port currently has a connection attached...
if (pTestNode->getInputPortConnectionItem(selInfo.portIndex))
{
// it has, so we need to modify an existing connection
m_selConnectionDragType = eSelConDragExistingInput;
m_pInteractionConnectionItem = pTestNode->getInputPortConnectionItem(selInfo.portIndex);
m_pInteractionConnectionItem->setTempMousePos(cursorScenePos);
m_pInteractionConnectionItem->setDestinationNode(nullptr);
m_pInteractionConnectionItem->setDestinationNodePortIndex(-1);
// set the connection on the node we're disconnecting from to nullptr
pTestNode->setInputPortConnectionItem(selInfo.portIndex, nullptr);
// fix up backing data structure
pTestNode->getActualNode()->setInputPortConnection(selInfo.portIndex, -1, -1);
ShaderNode* pSrcNode = m_pInteractionConnectionItem->getSourceNode()->getActualNode();
pSrcNode->removeOutputPortConnection(m_pInteractionConnectionItem->getSourceNodePortIndex(), pTestNode->getActualNode()->getNodeID(),
selInfo.portIndex);
m_pSelectedItem = m_pInteractionConnectionItem;
}
else
{
// it hasn't, so create a new temporary one...
m_selConnectionDragType = eSelConDragNewInput;
m_pInteractionConnectionItem = new ShaderConnectionUI(nullptr, pTestNode);
m_pInteractionConnectionItem->setTempMousePos(cursorScenePos);
m_pInteractionConnectionItem->setDestinationNodePortIndex(selInfo.portIndex);
m_pSelectedItem = m_pInteractionConnectionItem;
scene()->addItem(m_pInteractionConnectionItem);
}
}
else if (selInfo.selectionType == ShaderNodeUI::SelectionInfo::eSelectionOutputPort)
{
selectedSomething = true;
m_selectionType = eSelectionEdgeOutput;
unsigned int existingOutputConnections = pTestNode->getOutputPortConnectionCount(selInfo.portIndex);
// see if the selected port currently has a connection attached...
if (existingOutputConnections > 0)
{
// if it has, given that we're allowed to have an output port connected to multiple different
// input ports/nodes, allow creating a new one by default, or if shift is held down and only one
// connection exists, drag existing connection.
if (existingOutputConnections == 1 && event->modifiers() & Qt::ShiftModifier)
{
// so modify the existing connection
m_selConnectionDragType = eSelConDragExistingOutput;
m_pInteractionConnectionItem = pTestNode->getSingleOutputPortConnectionItem(selInfo.portIndex);
m_pInteractionConnectionItem->setTempMousePos(cursorScenePos);
m_pInteractionConnectionItem->setSourceNode(nullptr);
m_pInteractionConnectionItem->setSourceNodePortIndex(-1);
// set the connection on the node we're disconnecting from to nullptr
pTestNode->addOutputPortConnectionItem(selInfo.portIndex, nullptr);
m_pSelectedItem = m_pInteractionConnectionItem;
// fix up backing data structure
pTestNode->getActualNode()->removeOutputPortConnection(selInfo.portIndex,
m_pInteractionConnectionItem->getDestinationNode()->getActualNode()->getNodeID(),
m_pInteractionConnectionItem->getDestinationNodePortIndex());
ShaderNode* pDestNode = m_pInteractionConnectionItem->getDestinationNode()->getActualNode();
pDestNode->setInputPortConnection(m_pInteractionConnectionItem->getDestinationNodePortIndex(), -1, -1);
break;
}
}
// otherwise (no connections, or more than one), just create a new connection for dragging
m_selConnectionDragType = eSelConDragNewOutput;
m_pInteractionConnectionItem = new ShaderConnectionUI(pTestNode, nullptr);
m_pInteractionConnectionItem->setTempMousePos(cursorScenePos);
m_pInteractionConnectionItem->setSourceNodePortIndex(selInfo.portIndex);
pTestNode->addOutputPortConnectionItem(selInfo.portIndex, m_pInteractionConnectionItem);
m_pSelectedItem = m_pInteractionConnectionItem;
scene()->addItem(m_pInteractionConnectionItem);
}
break;
}
}
}
if (!selectedSomething)
{
// if we didn't select a node, see if we selected a connection...
// TODO: this isn't really that efficient, might want to have another look at using
// scene()->itemAt(), although that'll involve a lot of re-jigging how things are done...
// build a unique list of connections
std::set<ShaderConnectionUI*> aConnections;
std::vector<ShaderNodeUI*>::iterator itNodes = m_aNodes.begin();
for (; itNodes != m_aNodes.end(); ++itNodes)
{
ShaderNodeUI* pTestNode = *itNodes;
pTestNode->getConnectionItems(aConnections);
}
// the final closest connection info ends up specified in here...
ShaderConnectionUI::SelectionInfo connSelInfo;
float closestConnectionHitDistance = 25.0f;
bool haveConnection = false;
std::set<ShaderConnectionUI*>::iterator itConnection = aConnections.begin();
for (; itConnection != aConnections.end(); ++itConnection)
{
ShaderConnectionUI* pConn = *itConnection;
// ignore connections which aren't fully-connected
if (pConn->getDestinationNode() == nullptr || pConn->getSourceNode() == nullptr)
continue;
if (pConn->didHit(cursorScenePos, connSelInfo, closestConnectionHitDistance))
{
haveConnection = true;
// don't break out, as we want the closest connection...
}
}
if (haveConnection)
{
selectedSomething = true;
m_pInteractionConnectionItem = connSelInfo.pConnection;
m_pInteractionConnectionItem->setTempMousePos(cursorScenePos);
m_pSelectedItem = m_pInteractionConnectionItem;
// so we need to disconnect the connection at the end closest to where it was clicked...
if (connSelInfo.wasSource)
{
m_selectionType = eSelectionEdgeOutput;
// disconnect the output port side (source)
m_selConnectionDragType = eSelConDragExistingOutput;
ShaderNodeUI* pOldSourceNode = m_pInteractionConnectionItem->getSourceNode();
unsigned int oldSourcePortIndex = m_pInteractionConnectionItem->getSourceNodePortIndex();
m_pInteractionConnectionItem->setSourceNode(nullptr);
m_pInteractionConnectionItem->setSourceNodePortIndex(-1);
// set the connection on the node we're disconnecting from to nullptr
pOldSourceNode->removeOutputPortConnectionItem(oldSourcePortIndex, m_pInteractionConnectionItem);
// fix up backing data structure - both source and destination
ShaderNode* pActualSourceNode = pOldSourceNode->getActualNode();
ShaderNode* pActualDestNode = m_pInteractionConnectionItem->getDestinationNode()->getActualNode();
unsigned int destNodePortID = m_pInteractionConnectionItem->getDestinationNodePortIndex();
pActualSourceNode->removeOutputPortConnection(oldSourcePortIndex,
pActualDestNode->getNodeID(), destNodePortID);
pActualDestNode->setInputPortConnection(destNodePortID, -1, -1);
}
else
{
m_selectionType = eSelectionEdgeInput;
// disconnect the input port side (destination)
m_selConnectionDragType = eSelConDragExistingInput;
ShaderNodeUI* pOldDestinationNode = m_pInteractionConnectionItem->getDestinationNode();
unsigned int oldDestinationPortIndex = m_pInteractionConnectionItem->getSourceNodePortIndex();
m_pInteractionConnectionItem->setDestinationNode(nullptr);
m_pInteractionConnectionItem->setDestinationNodePortIndex(-1);
// set the connection on the node we're disconnecting from to nullptr
pOldDestinationNode->setInputPortConnectionItem(oldDestinationPortIndex, nullptr);
// fix up backing data structure - both source and destination
ShaderNode* pActualDestNode = pOldDestinationNode->getActualNode();
ShaderNode* pActualSourceNode = m_pInteractionConnectionItem->getSourceNode()->getActualNode();
unsigned int sourceNodePortID = m_pInteractionConnectionItem->getSourceNodePortIndex();
pActualSourceNode->removeOutputPortConnection(sourceNodePortID,
pActualDestNode->getNodeID(), oldDestinationPortIndex);
pActualDestNode->setInputPortConnection(oldDestinationPortIndex, -1, -1);
}
}
}
if (!selectedSomething && m_pSelectedItem)
{
m_pSelectedItem->setSelected(false);
m_selectionType = eSelectionNone;
m_pSelectedItem = nullptr;
}
if (event->modifiers() & Qt::ALT || event->button() == Qt::MiddleButton)
{
m_mouseMode = eMousePan;
return;
}
if (m_pSelectedItem)
{
m_mouseMode = eMouseDrag;
m_pSelectedItem->setSelected(true);
}
}
void ShaderNodeViewWidget::mouseMoveEvent(QMouseEvent* event)
{
QPointF sceneMousePos = mapToScene(event->pos());
QPointF cursorPosition = getEventPos(event);
if (m_mouseMode == eMouseNone)
{
}
else if (m_mouseMode == eMousePan)
{
// float deltaMoveX =
QPointF deltaMove = mapToScene(event->pos()) - m_lastMouseScenePos;
// QGraphicsView::mouseMoveEvent(event);
translate(deltaMove.rx(), deltaMove.ry());
// update();
}
else if (m_mouseMode == eMouseDrag && m_pSelectedItem)
{
QPointF deltaMove = sceneMousePos - m_lastMouseScenePos;
if (m_selectionType == eSelectionNode)
{
// TODO: is this the most efficient way of doing things?
// build up a cumulative delta during move and do it on mouse release instead?
ShaderNodeUI* pNode = static_cast<ShaderNodeUI*>(m_pSelectedItem);
pNode->movePos(deltaMove.x(), deltaMove.y());
}
else if (m_selectionType == eSelectionEdgeInput)
{
if (m_selConnectionDragType == eSelConDragNewInput || m_selConnectionDragType == eSelConDragExistingInput)
{
ShaderConnectionUI* pConnection = static_cast<ShaderConnectionUI*>(m_pSelectedItem);
QPointF temp = sceneMousePos;
pConnection->publicPrepareGeometryChange();
pConnection->setTempMousePos(temp);
}
}
else if (m_selectionType == eSelectionEdgeOutput)
{
if (m_selConnectionDragType == eSelConDragNewOutput || m_selConnectionDragType == eSelConDragExistingOutput)
{
ShaderConnectionUI* pConnection = static_cast<ShaderConnectionUI*>(m_pSelectedItem);
QPointF temp = sceneMousePos;
pConnection->publicPrepareGeometryChange();
pConnection->setTempMousePos(temp);
}
}
}
m_lastMousePos = getEventPos(event);
m_lastMouseScenePos = sceneMousePos;
QGraphicsView::mousePressEvent(event);
}
void ShaderNodeViewWidget::mouseReleaseEvent(QMouseEvent* event)
{
QPointF cursorScenePos = mapToScene(event->pos().x(), event->pos().y());
if (m_selectionType == eSelectionNone)
return;
bool didConnectNewConnection = false;
bool didReconnectExistingConnection = false;
if (m_selConnectionDragType != eSelConDragNone &&
m_pSelectedItem != nullptr)
{
// we should be currently dragging a connection from a port, so work out what port we might be being
// dropped on on a source node...
// work out where we dropped...
std::vector<ShaderNodeUI*>::iterator itNodes = m_aNodes.begin();
for (; itNodes != m_aNodes.end(); ++itNodes)
{
ShaderNodeUI* pTestNode = *itNodes;
if (!pTestNode->isActive())
continue;
ShaderNodeUI::SelectionInfo selInfo;
if (!pTestNode->doesContain(cursorScenePos, selInfo))
continue;
ShaderPortVariableType existingPortType = ePortTypeAny;
// check we're not trying to connect to the same node which isn't allowed...
if (m_pInteractionConnectionItem)
{
// get hold of currently existing node, which should be the other end of the connection
ShaderNodeUI* pOtherNode = m_pInteractionConnectionItem->getSourceNode();
if (!pOtherNode)
{
pOtherNode = m_pInteractionConnectionItem->getDestinationNode();
}
if (pOtherNode == pTestNode)
continue;
ShaderPortVariableType thisPortType = ePortTypeAny;
if (selInfo.selectionType == ShaderNodeUI::SelectionInfo::eSelectionOutputPort)
{
thisPortType = pTestNode->getActualNode()->getOutputPort(selInfo.portIndex).type;
existingPortType = pOtherNode->getActualNode()->getInputPort(m_pInteractionConnectionItem->getDestinationNodePortIndex()).type;
}
else if (selInfo.selectionType == ShaderNodeUI::SelectionInfo::eSelectionInputPort)
{
thisPortType = pTestNode->getActualNode()->getInputPort(selInfo.portIndex).type;
existingPortType = pOtherNode->getActualNode()->getOutputPort(m_pInteractionConnectionItem->getSourceNodePortIndex()).type;
}
bool enforceConnectionTypes = true;
if (thisPortType == ePortTypeAny || existingPortType == ePortTypeAny)
{
enforceConnectionTypes = false;
}
if (enforceConnectionTypes && existingPortType != thisPortType)
{
continue;
}
}
if (m_selConnectionDragType == eSelConDragNewOutput && selInfo.selectionType == ShaderNodeUI::SelectionInfo::eSelectionInputPort)
{
// we're currently dragging from an output port (src, right side) on the source node, and have been dropped
// onto an input port on the destination (left side)
// see if the selected port currently has a connection attached...
if (pTestNode->getInputPortConnectionItem(selInfo.portIndex))
{
// it has, so we won't do anything for the moment
// TODO: if Shift is held down, swap the connection with the new one?
}
else
{
// it hasn't, so connect the current interactive one which should still be
// connected at the other end...
m_pInteractionConnectionItem->setDestinationNode(pTestNode);
m_pInteractionConnectionItem->setDestinationNodePortIndex(selInfo.portIndex);
// connect to destination
pTestNode->setInputPortConnectionItem(selInfo.portIndex, m_pInteractionConnectionItem);
// connect to source
ShaderNodeUI* pSrcNode = m_pInteractionConnectionItem->getSourceNode();
unsigned int srcNodePortID = m_pInteractionConnectionItem->getSourceNodePortIndex();
pSrcNode->addOutputPortConnectionItem(srcNodePortID, m_pInteractionConnectionItem);
didConnectNewConnection = true;
// leak m_pInteractionConnectionItem for the moment...
// fix up the backing data structure
ShaderNode* pActualSrcNode = pSrcNode->getActualNode();
ShaderNode* pActualDstNode = pTestNode->getActualNode();
pActualSrcNode->addOutputPortConnection(srcNodePortID, pActualDstNode->getNodeID(), selInfo.portIndex);
pActualDstNode->setInputPortConnection(selInfo.portIndex, pActualSrcNode->getNodeID(), srcNodePortID);
}
}
else if (m_selConnectionDragType == eSelConDragExistingInput && selInfo.selectionType == ShaderNodeUI::SelectionInfo::eSelectionInputPort)
{
// we're dragging the input connection (left side of node) from an existing connection to a new one, so we're modifying
// where the new destination of this connection should be
m_pInteractionConnectionItem->setDestinationNode(pTestNode);
m_pInteractionConnectionItem->setDestinationNodePortIndex(selInfo.portIndex);
pTestNode->setInputPortConnectionItem(selInfo.portIndex, m_pInteractionConnectionItem);
ShaderNodeUI* pSrcNode = m_pInteractionConnectionItem->getSourceNode();
unsigned int srcNodePortID = m_pInteractionConnectionItem->getSourceNodePortIndex();
pSrcNode->addOutputPortConnectionItem(srcNodePortID, m_pInteractionConnectionItem);
// alter backing data structure
ShaderNode* pActualSrcNode = pSrcNode->getActualNode();
ShaderNode* pActualDstNode = pTestNode->getActualNode();
pActualSrcNode->addOutputPortConnection(srcNodePortID, pActualDstNode->getNodeID(), selInfo.portIndex);
pActualDstNode->setInputPortConnection(selInfo.portIndex, pActualSrcNode->getNodeID(), srcNodePortID);
didReconnectExistingConnection = true;
}
else if (m_selConnectionDragType == eSelConDragNewInput && selInfo.selectionType == ShaderNodeUI::SelectionInfo::eSelectionOutputPort)
{
// we're currently dragging from an input port (destination, left side) on destination node,
// and have been dropped onto an output port on the source (right side)
// we support multiple connections on output ports
m_pInteractionConnectionItem->setSourceNode(pTestNode);
m_pInteractionConnectionItem->setSourceNodePortIndex(selInfo.portIndex);
// connect source
pTestNode->addOutputPortConnectionItem(selInfo.portIndex, m_pInteractionConnectionItem);
// connect to destination
ShaderNodeUI* pDstNode = m_pInteractionConnectionItem->getDestinationNode();
unsigned int dstNodePortID = m_pInteractionConnectionItem->getDestinationNodePortIndex();
pDstNode->setInputPortConnectionItem(dstNodePortID, m_pInteractionConnectionItem);
didConnectNewConnection = true;
// leak m_pInteractionConnectionItem for the moment...
// fix up the backing data structure
ShaderNode* pActualSrcNode = pTestNode->getActualNode();
ShaderNode* pActualDstNode = pDstNode->getActualNode();
pActualSrcNode->addOutputPortConnection(selInfo.portIndex, pActualDstNode->getNodeID(), dstNodePortID);
pActualDstNode->setInputPortConnection(dstNodePortID, pActualSrcNode->getNodeID(), selInfo.portIndex);
}
else if (m_selConnectionDragType == eSelConDragExistingOutput && selInfo.selectionType == ShaderNodeUI::SelectionInfo::eSelectionOutputPort)
{
// we're dragging the output connection (right side of node) from an existing connection to a new one, so we're modifying
// where the new source of this connection should be
m_pInteractionConnectionItem->setSourceNode(pTestNode);
m_pInteractionConnectionItem->setSourceNodePortIndex(selInfo.portIndex);
pTestNode->addOutputPortConnectionItem(selInfo.portIndex, m_pInteractionConnectionItem);
// connect to destination
ShaderNodeUI* pDstNode = m_pInteractionConnectionItem->getDestinationNode();
unsigned int dstNodePortID = m_pInteractionConnectionItem->getDestinationNodePortIndex();
pDstNode->setInputPortConnectionItem(dstNodePortID, m_pInteractionConnectionItem);
// fix up the backing data structure
ShaderNode* pActualSrcNode = pTestNode->getActualNode();
ShaderNode* pActualDstNode = pDstNode->getActualNode();
pActualSrcNode->addOutputPortConnection(selInfo.portIndex, pActualDstNode->getNodeID(), dstNodePortID);
pActualDstNode->setInputPortConnection(dstNodePortID, pActualSrcNode->getNodeID(), selInfo.portIndex);
didReconnectExistingConnection = true;
}
break;
m_selectionType = eSelectionNone;
}
}
if (m_selectionType != eSelectionNode)
{
m_pSelectedItem = nullptr;
m_selectionType = eSelectionNone;
m_selConnectionDragType = eSelConDragNone;
}
m_mouseMode = eMouseNone;
if (m_pInteractionConnectionItem)
{
m_pInteractionConnectionItem->setSelected(false);
}
// clean up any undropped connections...
// TODO: this is pretty crap...
if (didConnectNewConnection)
{
// m_pIneractionConnectionItem has now been made into a full connection
}
else if (didReconnectExistingConnection)
{
// an existing connection was re-connected to another node/port
}
else
{
// TODO: need to work out what to do with this
// seems really bad having these allocated per-mouse down on ports... - lots of scope for
// memory leaks...
if (m_pInteractionConnectionItem)
{
// this connection is going to be discarded as it's been unconnected (dragged from a port to an empty location)
// we need to change the connection state within the nodes, so they don't think they're connected any more
ShaderNodeUI* pDstNode = m_pInteractionConnectionItem->getDestinationNode();
if (pDstNode)
{
unsigned int originalPortIndex = m_pInteractionConnectionItem->getDestinationNodePortIndex();
pDstNode->setInputPortConnectionItem(originalPortIndex, nullptr);
m_pInteractionConnectionItem->setDestinationNode(nullptr);
}
ShaderNodeUI* pSrcNode = m_pInteractionConnectionItem->getSourceNode();
if (pSrcNode)
{
unsigned int originalPortIndex = m_pInteractionConnectionItem->getSourceNodePortIndex();
pSrcNode->addOutputPortConnectionItem(originalPortIndex, nullptr);
m_pInteractionConnectionItem->setSourceNode(nullptr);
}
// just deleting the object is good enough, as QGraphicsItem's destructor calls
// QGraphicsScene's removeItem() function, so we don't need to do it ourselves..
delete m_pInteractionConnectionItem;
}
}
m_pInteractionConnectionItem = nullptr;
if (didConnectNewConnection || didReconnectExistingConnection)
{
// trigger a re-draw, so any just dropped connections snap into place...
invalidateScene();
}
QGraphicsView::mouseReleaseEvent(event);
}
void ShaderNodeViewWidget::mouseDoubleClickEvent(QMouseEvent* event)
{
m_lastMousePos = getEventPos(event);
m_lastMouseScenePos = mapToScene(event->pos());
QPointF cursorScenePos = mapToScene(event->pos().x(), event->pos().y());
bool selectedSomething = false;
if (m_pSelectedItem)
{
m_pSelectedItem->setSelected(false);
}
ShaderNodeUI* pClickedNode = nullptr;
// doing it this way (while inefficient as no acceleration structure is used) means we only get
// the Nodes. Using scene.itemAt() returns children of QGraphicsItem object (like the text items)
std::vector<ShaderNodeUI*>::iterator itNodes = m_aNodes.begin();
for (; itNodes != m_aNodes.end(); ++itNodes)
{
ShaderNodeUI* pTestNode = *itNodes;
ShaderNodeUI::SelectionInfo selInfo;
if (pTestNode->doesContain(cursorScenePos, selInfo))
{
if (selInfo.selectionType == ShaderNodeUI::SelectionInfo::eSelectionNode)
{
m_pSelectedItem = pTestNode;
m_pSelectedItem->setSelected(true);
selectedSomething = true;
m_selectionType = eSelectionNode;
pClickedNode = pTestNode;
}
}
}
if (!selectedSomething && m_pSelectedItem)
{
m_pSelectedItem->setSelected(false);
m_selectionType = eSelectionNone;
m_pSelectedItem = nullptr;
return;
}
// do stuff with the node that was double-clicked
ShaderNode* pNode = pClickedNode->getActualNode();
ParametersInterface* pNodeParametersInterface = pNode->getOpParametersInterface();
ParametersInterface* pParamInterface = dynamic_cast<ParametersInterface*>(m_pSelectedItem);
if (pNodeParametersInterface)
{
m_pHost->showParametersPanelForOp(pNodeParametersInterface);
}
}
void ShaderNodeViewWidget::showRightClickMenu(QMouseEvent* event)
{
// work out what type of menu we should show
std::vector<std::string> aNodeCategories;
m_pHost->getAllowedCreationCategories(aNodeCategories);
QMenu menu(this);
QMenu* pNewNodeMenu = menu.addMenu("New node...");
std::vector<std::string>::iterator itCats = aNodeCategories.begin();
for (; itCats != aNodeCategories.end(); ++itCats)
{
const std::string& category = *itCats;
std::map<std::string, NodeCreationMenuCategory*>::iterator itFind = m_aMenuCategories.find(category);
if (itFind == m_aMenuCategories.end())
{
continue;
}
NodeCreationMenuCategory* pMenuCat = (*itFind).second;
QMenu* pCatMenu = pNewNodeMenu->addMenu(category.c_str());
std::vector<NodeCreationMenuItem>::iterator itMenu = pMenuCat->nodeItems.begin();
for (; itMenu != pMenuCat->nodeItems.end(); ++itMenu)
{
NodeCreationMenuItem& menuItem = *itMenu;
pCatMenu->addAction(menuItem.pAction);
}
}
menu.addSeparator();
menu.exec(event->globalPos());
}
QPointF ShaderNodeViewWidget::getEventPos(QMouseEvent* event) const
{
#ifdef IMAGINE_QT_5
return event->localPos();
#else
return event->posF();
#endif
}
void ShaderNodeViewWidget::createNewNodeMenu(unsigned int categoryIndex, int menuIndex)
{
NodeCreationMenuCategory* pCat = m_aMenuCategoriesIndexed[categoryIndex];
NodeCreationMenuItem& item = pCat->nodeItems[menuIndex];
ShaderOp* pNewOp = m_pHost->createNewShaderOp(item.category, item.name);
ShaderNode* pNewNode = new ShaderNode(pNewOp);
pNewNode->setName(pNewOp->getOpTypeName());
m_pNodesCollection->addNode(pNewNode);
ShaderNodeUI* pNewUINode = new ShaderNodeUI(pNewNode);
pNewUINode->setCustomPos(m_lastMouseScenePos.rx(), m_lastMouseScenePos.ry());
m_aNodes.emplace_back(pNewUINode);
scene()->addItem(pNewUINode);
}
void ShaderNodeViewWidget::menuNewNode0(int index)
{
createNewNodeMenu(0, index);
}
void ShaderNodeViewWidget::menuNewNode1(int index)
{
createNewNodeMenu(1, index);
}
void ShaderNodeViewWidget::menuNewNode2(int index)
{
createNewNodeMenu(2, index);
}
} // namespace Imagine
| 33.218447 | 143 | 0.747596 | ppearson |
32851497790e9fc8cb3d7034a825f68a172bf513 | 2,043 | cpp | C++ | tests/dsp_scalardelayline_tests.cpp | jontio/JSquelch | 72805d6e08035daca09e6c668c63f46dc66674a2 | [
"MIT"
] | 2 | 2021-07-11T03:36:42.000Z | 2022-03-26T15:04:30.000Z | tests/dsp_scalardelayline_tests.cpp | jontio/JSquelch | 72805d6e08035daca09e6c668c63f46dc66674a2 | [
"MIT"
] | null | null | null | tests/dsp_scalardelayline_tests.cpp | jontio/JSquelch | 72805d6e08035daca09e6c668c63f46dc66674a2 | [
"MIT"
] | null | null | null | #include "../src/dsp/dsp.h"
#include "../src/util/RuntimeError.h"
#include "../src/util/stdio_utils.h"
#include "../src/util/file_utils.h"
#include <QFile>
#include <QDataStream>
#include <iostream>
//important for Qt include cpputest last as it mucks up new and causes compiling to fail
#include "CppUTest/TestHarness.h"
//this unit test is the big one and tests the C++ algo implimentation with
//that of matlab. the output signal and snr are compared
TEST_GROUP(Test_DSP_ScalarDelayLine)
{
const double double_tolerance=0.0000001;
//cpputest does not seem to work for qt accessing io such as qfile qdebug etc
//i get momory leak messages so im turning it off for this unit where i really want qfile
void setup()
{
// MemoryLeakWarningPlugin::turnOffNewDeleteOverloads();
}
void teardown()
{
// MemoryLeakWarningPlugin::turnOnNewDeleteOverloads();
}
};
TEST(Test_DSP_ScalarDelayLine, DoubleDelay2Test)
{
JDsp::ScalarDelayLine<double> delayline(62);
QVector<double> input(62*2);
for(int k=0;k<62;k++)
{
input[k]=k;
input[k+62]=k;
delayline<<input[k];
}
for(int k=0;k<62;k++)
{
DOUBLES_EQUAL(input[k+62],delayline<<input[k],double_tolerance);
}
}
TEST(Test_DSP_ScalarDelayLine, DoubleZeroTest)
{
JDsp::ScalarDelayLine<double> delayline(0);
QVector<double> input(62*2);
for(int k=0;k<62;k++)
{
input[k]=k;
input[k+62]=k;
delayline.update(input[k]);
}
for(int k=0;k<62;k++)
{
delayline.update(input[k]);
DOUBLES_EQUAL(input[k],delayline,double_tolerance);
}
}
TEST(Test_DSP_ScalarDelayLine, DoubleDelayTest)
{
JDsp::ScalarDelayLine<double> delayline(62);
QVector<double> input(62*2);
for(int k=0;k<62;k++)
{
input[k]=k;
input[k+62]=k;
delayline.update(input[k]);
}
for(int k=0;k<62;k++)
{
delayline.update(input[k]);
DOUBLES_EQUAL(input[k+62],delayline,double_tolerance);
}
}
| 24.321429 | 93 | 0.643661 | jontio |
3285d054d851d23edfbcd08c2e2dfb69ae0738f4 | 11,412 | cc | C++ | pkg/oc/varinfo.cc | ViennaNovoFlop/ViennaNovoFlop-dev | f8c4d6c06590a0d9a3890d81e9b0b4dcb7ea9e00 | [
"TCL",
"SWL",
"MIT",
"X11",
"BSD-3-Clause"
] | null | null | null | pkg/oc/varinfo.cc | ViennaNovoFlop/ViennaNovoFlop-dev | f8c4d6c06590a0d9a3890d81e9b0b4dcb7ea9e00 | [
"TCL",
"SWL",
"MIT",
"X11",
"BSD-3-Clause"
] | null | null | null | pkg/oc/varinfo.cc | ViennaNovoFlop/ViennaNovoFlop-dev | f8c4d6c06590a0d9a3890d81e9b0b4dcb7ea9e00 | [
"TCL",
"SWL",
"MIT",
"X11",
"BSD-3-Clause"
] | null | null | null | /* FILE: varinfo.cc -*-Mode: c++-*-
*
* Small program to probe system characteristics.
*
* Last modified on: $Date: 2009-11-06 05:42:23 $
* Last modified by: $Author: donahue $
*
*/
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <limits.h>
#include <math.h>
#include <float.h>
#if defined(__unix) || defined(_AIX)
#include <unistd.h>
#endif /* __unix */
/* End includes */
/****************
#define COMPLEX
#define EXTRALONG
#define EXTRALONGINT
#define EXTRALONGDOUBLE
****************/
#ifdef __cplusplus
# if !defined(EXTRALONGDOUBLE) && !defined(__SUNPRO_CC) && !defined(__sun)
/* Some(?) releases of Sun Forte compiler missing floorl support. */
/* Some(?) g++ installations on Solaris missing floorl support. */
# define EXTRALONGDOUBLE
# endif
#endif
#ifdef EXTRALONG
# ifndef EXTRALONGINT
# define EXTRALONGINT
# endif
# ifndef EXTRALONGDOUBLE
# define EXTRALONGDOUBLE
# endif
#endif
#ifdef EXTRALONGINT
# ifdef _WIN32
typedef __int64 HUGEINT;
# else
typedef long long HUGEINT;
# endif
#endif
#ifdef EXTRALONGDOUBLE
typedef long double HUGEFLOAT;
#endif
/*
* If "EXTRALONG" is defined, then types "long long" and "long double"
* are included. In particular, the second (long double), may be the
* 10 byte IEEE 854 (3.4E-4932 to 3.4E+4932) "double-extended-precision"
* format (as opposed to the 8-byte IEEE 754 "double-precision" format).
* Your system might have <ieee754.h> and <ieee854.h> include files with
* more information.
*
* Some "magic" values for the IEEE formats
*
* Value Internal representation
* (MSB order, hexadecimal)
* 4-byte: 2.015747786E+00 40 01 02 03
* 8-byte: 2.12598231449442521E+00 40 01 02 03 04 05 06 07
* 10-byte: 4.06286812764321414839E+00 40 01 82 03 04 05 06 07 08 09
*
* Note that the third byte in the 10-byte format is '0x82', NOT '0x02'.
* This is because in the IEEE 10-byte format, bit 63 is an explicit
* "integer" or "J-bit" representing the leading bit in the mantissa.
* For normal (as opposed to denormal) numbers this bit must be 1.
* The J-bit is implied to be 1 in the 4- and 8-byte formats. The
* leading byte is 0x40 so that the value has a small exponent; this
* protects against compilers that complain about over- and under-flow
* errors when selecting from among the magic values, in particular
* in the FLOATCONST macro.
* The PrintByteOrder routine masks off the top 4 bits, so we can
* put any values we want in the top 4 bits of each byte, except
* the special value 0x00 which is treated as invalid.
*/
/* Debugging routine */
#ifdef __cplusplus
void DumpBytes(char *buf,int len)
#else
void DumpBytes(buf,len)
char *buf;
int len;
#endif
{
int i;
for(i=0;i<len;i++) printf("%02X ",(unsigned char)buf[i]);
printf("\n");
}
#define FillByteOrder(x,i,l) \
for(i=1,x=0x10;i<l;i++) { x<<=8; x|=(0x10+(unsigned char)i); }
/* IEEE 754 floating point format "magic" strings (Hex 0x1234, 0x12345678) */
#define FLOATCONST(l) (l==4 ? (float)2.015747786 : \
(l==8 ? (float)2.12598231449442521 : \
(float)0.))
#define DOUBLECONST(l) (l==4 ? (double)2.015747786 : \
(l==8 ? (double)2.12598231449442521 : \
(double)0.))
#ifdef EXTRALONGDOUBLE
#define LONGDOUBLECONST(l) (l==4 ? (HUGEFLOAT)2.015747786 : \
(l==8 ? (HUGEFLOAT)2.12598231449442521 : \
(l>8 ? (HUGEFLOAT)4.06286812764321414839L : \
(HUGEFLOAT)0.)))
#endif /* EXTRALONGDOUBLE */
#ifdef __cplusplus
void PrintByteOrder(char *buf,int len)
#else
void PrintByteOrder(buf,len)
char* buf;
int len;
#endif
{
int i,ch;
printf("Byte order: ");
for(i=0;i<len;i++) {
if(buf[i]==0) {
printf("x");
} else {
ch=0x0F & ((unsigned char)buf[i]);
printf("%01X",ch+1);
}
}
}
double DblMachEps()
{
volatile double one;
double eps,epsok,check;
one = 1.0;
eps=1.0;
epsok=2.0;
check=1.0+eps;
while(check>one) {
epsok=eps;
eps/=2.0;
check = 1.0 + eps;
}
return epsok;
}
#ifdef EXTRALONGDOUBLE
HUGEFLOAT LongDblMachEps()
{
volatile HUGEFLOAT eps,epsok,check;
eps=1.0;
epsok=2.0;
check=1.0+eps;
while(check>1.0) {
epsok=eps;
eps/=2.0;
check = 1.0 + eps;
}
return epsok;
}
#endif /* EXTRALONGDOUBLE */
void Usage()
{
fprintf(stderr,"Usage: varinfo [-h|--help]"
" [--skip-atan2] [--skip-underflow]\n");
exit(1);
}
/* Declaration for dummy zero routine. Definition at bottom of file. */
double zero();
#ifdef __cplusplus
int main(int argc,char** argv)
#else
int main(argc,argv)
int argc;
char **argv;
#endif
{
short s;
int i;
long l;
float f;
double d;
#ifdef EXTRALONGINT
HUGEINT ll;
#endif /* EXTRALONGINT */
#ifdef EXTRALONGDOUBLE
HUGEFLOAT ld;
#endif /* EXTRALONGDOUBLE */
#ifdef COMPLEX
__complex__ int ci;
__complex__ double cd;
#endif /* COMPLEX */
size_t st,loop;
int skip_atan2,skip_underflow;
/* Check command line flags */
if(argc>3) Usage();
skip_atan2=0;
skip_underflow=0;
if(argc>1) {
int ia;
for(ia=1;ia<argc;ia++) {
if(strcmp("--skip-atan2",argv[ia])==0) skip_atan2=1;
else if(strcmp("--skip-underflow",argv[ia])==0) skip_underflow=1;
else Usage();
}
}
/* Work length info */
printf("Type char is %2d bytes wide ",(int)sizeof(char));
st=sizeof(char);
if(st!=1) printf("ERROR: char should be 1 byte wide!\n");
else printf("Byte order: 1\n");
printf("\n");
printf("Type short is %2d bytes wide ",(int)sizeof(short));
FillByteOrder(s,loop,sizeof(short));
PrintByteOrder((char *)&s,(int)sizeof(short)); printf("\n");
printf("Type int is %2d bytes wide ",(int)sizeof(int));
FillByteOrder(i,loop,sizeof(int));
PrintByteOrder((char *)&i,(int)sizeof(int)); printf("\n");
printf("Type long is %2d bytes wide ",(int)sizeof(long));
FillByteOrder(l,loop,sizeof(long));
PrintByteOrder((char *)&l,(int)sizeof(long)); printf("\n");
#ifdef EXTRALONGINT
printf("Type HUGEINT is %2d bytes wide ",(int)sizeof(HUGEINT));
FillByteOrder(ll,loop,sizeof(HUGEINT));
PrintByteOrder((char *)&ll,(int)sizeof(HUGEINT)); printf("\n");
#endif /* EXTRALONGINT */
printf("\n");
printf("Type float is %2d bytes wide ",(int)sizeof(float));
f=FLOATCONST(sizeof(float));
PrintByteOrder((char *)&f,(int)sizeof(float)); printf("\n");
printf("Type double is %2d bytes wide ",(int)sizeof(double));
d=DOUBLECONST(sizeof(double));
PrintByteOrder((char *)&d,(int)sizeof(double)); printf("\n");
#ifdef EXTRALONGDOUBLE
printf("Type HUGEFLOAT is %2d bytes wide ",(int)sizeof(HUGEFLOAT));
for(size_t ihf=0;ihf<sizeof(HUGEFLOAT);++ihf) { ((char *)&ld)[ihf]=0; }
ld=LONGDOUBLECONST(sizeof(HUGEFLOAT));
PrintByteOrder((char *)&ld,(int)sizeof(HUGEFLOAT)); printf("\n");
#endif /* EXTRALONGDOUBLE */
printf("\n");
printf("Type void * is %2d bytes wide\n",(int)sizeof(void *));
#ifdef COMPLEX
printf("\n");
printf("Type __complex__ int is %2d bytes wide\n",
sizeof(__complex__ int));
printf("Type __complex__ double is %2d bytes wide\n",
sizeof(__complex__ double));
#endif /* COMPLEX */
/* Byte order info */
printf("\n"); fflush(stdout);
st=sizeof(double);
if(st!=8) {
fprintf(stderr,"Can't test byte order; sizeof(double)!=8\n");
}
else {
union {
double x;
unsigned char c[8];
} bytetest;
double xpattern=1.234;
unsigned char lsbpattern[9],msbpattern[9];
strncpy((char *)lsbpattern,"\130\071\264\310\166\276\363\077",
sizeof(lsbpattern));
strncpy((char *)msbpattern,"\077\363\276\166\310\264\071\130",
sizeof(msbpattern));
/* The bit pattern for 1.234 on a little endian machine (e.g.,
* Intel's x86 series and Digital's AXP) should be
* 58 39 B4 C8 76 BE F3 3F, while on a big endian machine it is
* 3F F3 BE 76 C8 B4 39 58. Examples of big endian machines
* include ones using the MIPS R4000 and R8000 series chips,
* for example SGI's. Note: At least some versions of the Sun
* 'cc' compiler apparently don't grok '\xXX' hex notation. The
* above octal constants are equivalent to the aforementioned
* hex strings.
*/
bytetest.x=xpattern;
#ifdef DEBUG
printf("sizeof(lsbpattern)=%d\n",sizeof(lsbpattern));
printf("lsb pattern="); DumpBytes(lsbpattern,8);
printf("msb pattern="); DumpBytes(msbpattern,8);
printf(" x pattern="); DumpBytes(bytetest.c,8);
#endif /* DEBUG */
/* Floating point format */
if(strncmp((char *)bytetest.c,(char *)lsbpattern,8)==0) {
printf("Floating point format is IEEE in LSB (little endian) order\n");
}
else if(strncmp((char *)bytetest.c,(char *)msbpattern,8)==0) {
printf("Floating point format is IEEE in MSB (big endian) order\n");
}
else {
printf("Floating point format is either unknown"
" or uses an irregular byte order\n");
}
}
/* Additional system-specific information (ANSI) */
printf("\nWidth of clock_t variable: %7lu bytes\n",
(unsigned long)sizeof(clock_t));
#ifdef CLOCKS_PER_SEC
printf( " CLOCKS_PER_SEC: %7lu\n",
(unsigned long)CLOCKS_PER_SEC);
#else
printf( " CLOCKS_PER_SEC: <not defined>\n");
#endif
#ifdef CLK_TCK
printf( " CLK_TCK: %7lu\n",(unsigned long)CLK_TCK);
#else
printf( " CLK_TCK: <not defined>\n");
#endif
printf("\nFLT_EPSILON: %.9g\n",FLT_EPSILON);
printf("SQRT_FLT_EPSILON: %.9g\n",sqrt(FLT_EPSILON));
printf("DBL_EPSILON: %.17g\n",DBL_EPSILON);
printf("SQRT_DBL_EPSILON: %.17g\n",sqrt(DBL_EPSILON));
printf("CUBE_ROOT_DBL_EPSILON: %.17g\n",pow(DBL_EPSILON,1./3.));
#if 0 && defined(LDBL_EPSILON)
printf("LDBL_EPSILON: %.20Lg\n",LDBL_EPSILON);
#endif
#if 0 && defined(EXTRALONGDOUBLE)
printf("\nCalculated Double Epsilon: %.17g\n",DblMachEps());
printf( "Calculated HUGEFLOAT Epsilon: %.20Lg\n",LongDblMachEps());
#else
printf("\nCalculated Double Epsilon: %.17g\n",DblMachEps());
#endif /* EXTRALONGDOUBLE */
printf("\nDBL_MIN: %.17g\n",DBL_MIN);
printf("DBL_MAX: %.17g\n",DBL_MAX);
if(!skip_atan2) {
printf("\nReturn value from atan2(0,0): %g\n",atan2(zero(),zero()));
}
if(!skip_underflow) {
d = -999999.;
errno = 0;
d = exp(d);
if(d!=0.0) {
fprintf(stderr,"\nERROR: UNDERFLOW TEST FAILURE\n\n");
exit(1);
}
if(errno==0) printf("\nErrno not set on underflow\n");
else printf("\nErrno set on underflow to %d\n",errno);
}
#ifdef EXTRALONGDOUBLE
# ifdef NO_FLOORL_CHECK
printf("\nLibrary function floorl assumed bad or missing.\n");
# else
/* Check for bad long double floor and ceil */
ld = -0.253L;
if(floorl(ld) != -1.0L || (ld - floorl(ld)) != 1.0L - 0.253L) {
printf("\nBad floorl. You should set "
"program_compiler_c++_property_bad_wide2int"
" to 1 in the platform oommf/config/platforms/ file.\n");
} else {
printf("\nGood floorl.\n");
}
# endif
#endif /* EXTRALONGDOUBLE */
return 0;
}
/* Dummy routine that returns 0. This is a workaround for aggressive
* compilers that try to resolve away constants at compile-time (or try
* to and fall over with an internal compiler error...)
*/
double zero()
{
return 0.0;
}
| 28.247525 | 77 | 0.640379 | ViennaNovoFlop |
3286b7e617ed6b57216c4d1e94931b07250b85b8 | 1,423 | cpp | C++ | UltraDV/Source/TKeyFrame.cpp | ModeenF/UltraDV | 30474c60880de541b33687c96293766fe0dc4aef | [
"Unlicense"
] | null | null | null | UltraDV/Source/TKeyFrame.cpp | ModeenF/UltraDV | 30474c60880de541b33687c96293766fe0dc4aef | [
"Unlicense"
] | null | null | null | UltraDV/Source/TKeyFrame.cpp | ModeenF/UltraDV | 30474c60880de541b33687c96293766fe0dc4aef | [
"Unlicense"
] | null | null | null | //---------------------------------------------------------------------
//
// File: TKeyFrame.cpp
//
// Author: Mike Ost
//
// Date: 10.23.98
//
// Desc:
//
// TKeyFrame is owned by TCueEffect. It associates a time with a
// TEffectState, as defined by the add-on effects classes. This
// provides a generic interface to key frames, with the details
// of effects states handled elsewhere.
//
//---------------------------------------------------------------------
#include "TKeyFrame.h"
#include "TCueEffect.h"
//---------------------------------------------------------------------
// Create and Destroy
//---------------------------------------------------------------------
//
//
TKeyFrame::TKeyFrame() :
m_time(0),
m_state(0)
{}
TKeyFrame::~TKeyFrame()
{
delete m_state;
}
TKeyFrame::TKeyFrame(const TKeyFrame& rhs) :
m_time(rhs.m_time)
{
if (rhs.m_state)
m_state = rhs.m_state->NewCopy();
else
m_state = rhs.m_state;
}
//---------------------------------------------------------------------
// Comparison operators
//---------------------------------------------------------------------
//
//
bool TKeyFrame::operator<(const TKeyFrame& rhs)
{
if (m_time < rhs.m_time)
return true;
else if (m_time == rhs.m_time && m_state->LessThan(rhs.m_state))
return true;
return false;
}
bool TKeyFrame::operator==(const TKeyFrame& rhs)
{
return m_time == rhs.m_time && m_state->Equals(rhs.m_state);
}
| 21.560606 | 71 | 0.476458 | ModeenF |
3289d2425a82c902390a490c3a280314b8aa1e8f | 9,408 | hpp | C++ | WICWIU_src/Operator/ReShape.hpp | wok1909/WICWIU-OSSLab-Final-Project | ea172614c3106de3a8e203acfac8f0dd4eca7c7c | [
"Apache-2.0"
] | 119 | 2018-05-30T01:16:36.000Z | 2021-11-08T13:01:07.000Z | WICWIU_src/Operator/ReShape.hpp | wok1909/WICWIU-OSSLab-Final-Project | ea172614c3106de3a8e203acfac8f0dd4eca7c7c | [
"Apache-2.0"
] | 24 | 2018-08-05T16:50:42.000Z | 2020-10-28T00:38:48.000Z | WICWIU_src/Operator/ReShape.hpp | wok1909/WICWIU-OSSLab-Final-Project | ea172614c3106de3a8e203acfac8f0dd4eca7c7c | [
"Apache-2.0"
] | 35 | 2018-06-29T17:10:13.000Z | 2021-06-05T04:07:48.000Z | #ifndef RESHAPE_H_
#define RESHAPE_H_ value
#include "../Operator.hpp"
template<typename DTYPE>
class ReShape : public Operator<DTYPE>{
public:
/*!
@brief ReShape의 생성자
@details 파라미터로 받은 pInput, pRowSize, pColSize으로 Alloc한다.
@param pInput ReShape할 Operator.
@param pRowSize ReShape으로 새로 만들어질 Tensor의 rowsize.
@param pColSize ReShape으로 새로 만들어질 Tensor의 colsize.
@paramp pName 사용자가 부여한 Operator의 이름.
@ref int Alloc(Operator<DTYPE> *pInput, int pTimeSize, int pBatchSize, int pChannelSize, int pRowSize, int pColSize)
*/
ReShape(Operator<DTYPE> *pInput, int pRowSize, int pColSize, std::string pName, int pLoadflag = TRUE) : Operator<DTYPE>(pInput, pName, pLoadflag) {
#ifdef __DEBUG__
std::cout << "ReShape::ReShape(Operator *)" << '\n';
#endif // __DEBUG__
this->Alloc(pInput, 0, 0, 0, pRowSize, pColSize);
}
/*!
@brief ReShape의 생성자
@details 파라미터로 받은 pInput, pRowSize, pColSize으로 Alloc한다.
@param pInput ReShape할 Operator.
@param pChannelSize ReShape으로 새로 만들어질 Tensor의 channelsize
@param pRowSize ReShape으로 새로 만들어질 Tensor의 rowsize.
@param pColSize ReShape으로 새로 만들어질 Tensor의 colsize.
@paramp pName 사용자가 부여한 Operator의 이름.
@ref int Alloc(Operator<DTYPE> *pInput, int pTimeSize, int pBatchSize, int pChannelSize, int pRowSize, int pColSize)
*/
ReShape(Operator<DTYPE> *pInput, int pChannelSize, int pRowSize, int pColSize, std::string pName, int pLoadflag = TRUE) : Operator<DTYPE>(pInput, pName, pLoadflag) {
#ifdef __DEBUG__
std::cout << "ReShape::ReShape(Operator *)" << '\n';
#endif // __DEBUG__
this->Alloc(pInput, 0, 0, pChannelSize, pRowSize, pColSize);
}
/*!
@brief ReShape의 생성자
@details 파라미터로 받은 pInput, pRowSize, pColSize으로 Alloc한다.
@param pInput ReShape할 Operator.
@param pBatchSize ReShape으로 새로 만들어질 Tensor의 batchsize.
@param pChannelSize ReShape으로 새로 만들어질 Tensor의 channelsize.
@param pRowSize ReShape으로 새로 만들어질 Tensor의 rowsize.
@param pColSize ReShape으로 새로 만들어질 Tensor의 colsize.
@paramp pName 사용자가 부여한 Operator의 이름.
@ref int Alloc(Operator<DTYPE> *pInput, int pTimeSize, int pBatchSize, int pChannelSize, int pRowSize, int pColSize)
*/
ReShape(Operator<DTYPE> *pInput, int pBatchSize, int pChannelSize, int pRowSize, int pColSize, std::string pName, int pLoadflag = TRUE) : Operator<DTYPE>(pInput, pName, pLoadflag) {
#ifdef __DEBUG__
std::cout << "ReShape::ReShape(Operator *)" << '\n';
#endif // __DEBUG__
this->Alloc(pInput, 0, pBatchSize, pChannelSize, pRowSize, pColSize);
}
/*!
@brief ReShape의 생성자
@details 파라미터로 받은 pInput, pRowSize, pColSize으로 Alloc한다.
@param pInput ReShape할 Operator.
@param pTimeSize ReShape으로 새로 만들어질 Tensor의 timesize.
@param pBatchSize ReShape으로 새로 만들어질 Tensor의 batchsize.
@param pChannelSize ReShape으로 새로 만들어질 Tensor의 channelsize.
@param pRowSize ReShape으로 새로 만들어질 Tensor의 rowsize.
@param pColSize ReShape으로 새로 만들어질 Tensor의 colsize.
@paramp pName 사용자가 부여한 Operator의 이름.
@ref int Alloc(Operator<DTYPE> *pInput, int pTimeSize, int pBatchSize, int pChannelSize, int pRowSize, int pColSize)
*/
ReShape(Operator<DTYPE> *pInput, int pTimeSize, int pBatchSize, int pChannelSize, int pRowSize, int pColSize, std::string pName, int pLoadflag = TRUE) : Operator<DTYPE>(pInput, pName, pLoadflag) {
#ifdef __DEBUG__
std::cout << "ReShape::ReShape(Operator *)" << '\n';
#endif // __DEBUG__
this->Alloc(pInput, pTimeSize, pBatchSize, pChannelSize, pRowSize, pColSize);
}
/*!
@brief ReShape의 소멸자.
@details Delete 매소드를 사용한다.
@ref void Delete()
*/
~ReShape() {
#ifdef __DEBUG__
std::cout << "ReShape::~ReShape()" << '\n';
#endif // __DEBUG__
Delete();
}
/*!
@brief 파라미터로 받은 값들로 Shape의 dim들을 바꾼다.
@details result에 파라미터로 받은 값들로 result의 shape을 바꾸어 넣고,
@details Delta도 마찬가지로 받은 Dimension 정보들로 새로운 Tensor를 생성하여 넣는다,
@param pInput ReShape할 Operator.
@param pTimeSize ReShape으로 새로 만들어질 Tensor의 timesize.
@param pBatchSize ReShape으로 새로 만들어질 Tensor의 batchsize.
@param pChannelSize ReShape으로 새로 만들어질 Tensor의 channelsize.
@param pRowSize ReShape으로 새로 만들어질 Tensor의 rowsize.
@param pColSize ReShape으로 새로 만들어질 Tensor의 colsize.
@return 성공 시 TRUE.
*/
int Alloc(Operator<DTYPE> *pInput, int pTimeSize, int pBatchSize, int pChannelSize, int pRowSize, int pColSize) {
#ifdef __DEBUG__
std::cout << "ReShape::Alloc(Operator *, Operator *)" << '\n';
#endif // __DEBUG__
Shape *pInputShape = pInput->GetResult()->GetShape();
if (pTimeSize == 0) pTimeSize = (*pInputShape)[0];
if (pBatchSize == 0) pBatchSize = (*pInputShape)[1];
if (pChannelSize == 0) pChannelSize = (*pInputShape)[2];
Tensor<DTYPE> *result = new Tensor<DTYPE>(pInput->GetResult());
result->ReShape(pTimeSize, pBatchSize, pChannelSize, pRowSize, pColSize);
this->SetResult(result); // copy data
this->SetDelta(new Tensor<DTYPE>(pTimeSize, pBatchSize, pChannelSize, pRowSize, pColSize));
return TRUE;
}
/*!
@brief Delete 매소드.
@details 별다른 기능은 없다.
*/
void Delete() {}
/*!
@brief ReShape의 ForwardPropagate 매소드
@details input값을 result(새로운 Shape을 갖는 Tensor)에 저장한다.
@param pTime 연산 할 Tensor가 위치한 Time값. default는 0을 사용.
@return 성공 시 TRUE.
*/
int ForwardPropagate(int pTime = 0) {
Tensor<DTYPE> *input = this->GetInput()[0]->GetResult();
Tensor<DTYPE> *result = this->GetResult();
int timesize = result->GetTimeSize();
int batchsize = result->GetBatchSize();
int channelsize = result->GetChannelSize();
int rowsize = result->GetRowSize();
int colsize = result->GetColSize();
Shape *resultTenShape = result->GetShape();
int ti = pTime;
for (int ba = 0; ba < batchsize; ba++) {
for (int ch = 0; ch < channelsize; ch++) {
for (int ro = 0; ro < rowsize; ro++) {
for (int co = 0; co < colsize; co++) {
(*result)[Index5D(resultTenShape, ti, ba, ch, ro, co)]
= (*input)[Index5D(resultTenShape, ti, ba, ch, ro, co)];
}
}
}
}
return TRUE;
}
/*!
@brief ReShape의 BackPropagate 매소드.
@details input_delta에 this_delta값을 더한다.
@param pTime 연산 할 Tensor가 위치한 Time값. default는 0을 사용.
@return 성공 시 TRUE.
*/
int BackPropagate(int pTime = 0) {
Tensor<DTYPE> *this_delta = this->GetDelta();
Tensor<DTYPE> *input_delta = this->GetInput()[0]->GetDelta();
int timesize = this_delta->GetTimeSize();
int batchsize = this_delta->GetBatchSize();
int channelsize = this_delta->GetChannelSize();
int rowsize = this_delta->GetRowSize();
int colsize = this_delta->GetColSize();
Shape *deltaTenShape = this_delta->GetShape();
int ti = pTime;
for (int ba = 0; ba < batchsize; ba++) {
for (int ch = 0; ch < channelsize; ch++) {
for (int ro = 0; ro < rowsize; ro++) {
for (int co = 0; co < colsize; co++) {
(*input_delta)[Index5D(deltaTenShape, ti, ba, ch, ro, co)]
+= (*this_delta)[Index5D(deltaTenShape, ti, ba, ch, ro, co)];
}
}
}
}
return TRUE;
}
#ifdef __CUDNN__
/*!
@brief GPU에서 동작하는 ReShape의 ForwardPropagate 메소드.
@details cudnnAddTensor를 이용해 pDevInput의 값을 pDevResult에 더한다.
@param pTime 연산 할 Tensor가 위치한 Time값.
@return 성공 시 TRUE.
*/
int ForwardPropagateOnGPU(int pTime) {
Tensor<DTYPE> *input = this->GetInput()[0]->GetResult();
Tensor<DTYPE> *result = this->GetResult();
DTYPE *pDevInput = input->GetGPUData();
DTYPE *pDevResult = result->GetGPUData();
cudnnTensorDescriptor_t pDesc = input->GetDescriptor();
float alpha = 1.f;
float beta = 0.f;
checkCUDNN(cudnnAddTensor(this->GetCudnnHandle(),
&alpha, pDesc, pDevInput,
&alpha, pDesc, pDevResult));
// this->ForwardPropagate(pTime);
return TRUE;
}
/*!
@brief GPU에서 동작하는 ReShape의 BackPropagateOnGPU 메소드.
@details cudnnAddTensor를 이용해 pDevDelta의 값을 pDevInputDelta에 더한다.
@param pTime 연산 할 Tensor가 위치한 Time값.
@return 성공 시 TRUE.
*/
int BackPropagateOnGPU(int pTime) {
Tensor<DTYPE> *this_delta = this->GetDelta();
Tensor<DTYPE> *input_delta = this->GetInput()[0]->GetDelta();
DTYPE *pDevDelta = this_delta->GetGPUData();
DTYPE *pDevInputDelta = input_delta->GetGPUData();
cudnnTensorDescriptor_t pDesc = this_delta->GetDescriptor();
float alpha = 1.f;
float beta = 0.f;
checkCUDNN(cudnnAddTensor(this->GetCudnnHandle(),
&alpha, pDesc, pDevDelta,
&alpha, pDesc, pDevInputDelta));
// this->BackPropagate(pTime);
return TRUE;
}
#endif // __CUDNN__
};
#endif // RESHAPE_H_
| 36.045977 | 200 | 0.615434 | wok1909 |
329276ffdf0b38e9ba8e91fcb9a36241b80c91c8 | 42,781 | cpp | C++ | glstate.cpp | prahal/apitrace | e9426dd61586757d23d7dddc85b3076f477e7f07 | [
"MIT"
] | 1 | 2020-06-19T12:34:44.000Z | 2020-06-19T12:34:44.000Z | glstate.cpp | prahal/apitrace | e9426dd61586757d23d7dddc85b3076f477e7f07 | [
"MIT"
] | null | null | null | glstate.cpp | prahal/apitrace | e9426dd61586757d23d7dddc85b3076f477e7f07 | [
"MIT"
] | null | null | null | /**************************************************************************
*
* Copyright 2011 Jose Fonseca
* 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 <string.h>
#include <algorithm>
#include <iostream>
#include <map>
#include <sstream>
#include "image.hpp"
#include "json.hpp"
#include "glproc.hpp"
#include "glsize.hpp"
#include "glstate.hpp"
#ifdef __APPLE__
#include <Carbon/Carbon.h>
#ifdef __cplusplus
extern "C" {
#endif
OSStatus CGSGetSurfaceBounds(CGSConnectionID, CGWindowID, CGSSurfaceID, CGRect *);
#ifdef __cplusplus
}
#endif
#endif /* __APPLE__ */
namespace glstate {
static inline void
resetPixelPackState(void) {
glPushClientAttrib(GL_CLIENT_PIXEL_STORE_BIT);
glPixelStorei(GL_PACK_SWAP_BYTES, GL_FALSE);
glPixelStorei(GL_PACK_LSB_FIRST, GL_FALSE);
glPixelStorei(GL_PACK_ROW_LENGTH, 0);
glPixelStorei(GL_PACK_IMAGE_HEIGHT, 0);
glPixelStorei(GL_PACK_SKIP_ROWS, 0);
glPixelStorei(GL_PACK_SKIP_PIXELS, 0);
glPixelStorei(GL_PACK_SKIP_IMAGES, 0);
glPixelStorei(GL_PACK_ALIGNMENT, 1);
glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
}
static inline void
restorePixelPackState(void) {
glPopClientAttrib();
}
// Mapping from shader type to shader source, used to accumulated the sources
// of different shaders with same type.
typedef std::map<std::string, std::string> ShaderMap;
static void
getShaderSource(ShaderMap &shaderMap, GLuint shader)
{
if (!shader) {
return;
}
GLint shader_type = 0;
glGetShaderiv(shader, GL_SHADER_TYPE, &shader_type);
if (!shader_type) {
return;
}
GLint source_length = 0;
glGetShaderiv(shader, GL_SHADER_SOURCE_LENGTH, &source_length);
if (!source_length) {
return;
}
GLchar *source = new GLchar[source_length];
GLsizei length = 0;
source[0] = 0;
glGetShaderSource(shader, source_length, &length, source);
shaderMap[enumToString(shader_type)] += source;
delete [] source;
}
static void
getShaderObjSource(ShaderMap &shaderMap, GLhandleARB shaderObj)
{
if (!shaderObj) {
return;
}
GLint object_type = 0;
glGetObjectParameterivARB(shaderObj, GL_OBJECT_TYPE_ARB, &object_type);
if (object_type != GL_SHADER_OBJECT_ARB) {
return;
}
GLint shader_type = 0;
glGetObjectParameterivARB(shaderObj, GL_OBJECT_SUBTYPE_ARB, &shader_type);
if (!shader_type) {
return;
}
GLint source_length = 0;
glGetObjectParameterivARB(shaderObj, GL_OBJECT_SHADER_SOURCE_LENGTH_ARB, &source_length);
if (!source_length) {
return;
}
GLcharARB *source = new GLcharARB[source_length];
GLsizei length = 0;
source[0] = 0;
glGetShaderSource(shaderObj, source_length, &length, source);
shaderMap[enumToString(shader_type)] += source;
delete [] source;
}
static inline void
dumpProgram(JSONWriter &json, GLint program)
{
GLint attached_shaders = 0;
glGetProgramiv(program, GL_ATTACHED_SHADERS, &attached_shaders);
if (!attached_shaders) {
return;
}
ShaderMap shaderMap;
GLuint *shaders = new GLuint[attached_shaders];
GLsizei count = 0;
glGetAttachedShaders(program, attached_shaders, &count, shaders);
std::sort(shaders, shaders + count);
for (GLsizei i = 0; i < count; ++ i) {
getShaderSource(shaderMap, shaders[i]);
}
delete [] shaders;
for (ShaderMap::const_iterator it = shaderMap.begin(); it != shaderMap.end(); ++it) {
json.beginMember(it->first);
json.writeString(it->second);
json.endMember();
}
}
static inline void
dumpProgramObj(JSONWriter &json, GLhandleARB programObj)
{
GLint attached_shaders = 0;
glGetObjectParameterivARB(programObj, GL_OBJECT_ATTACHED_OBJECTS_ARB, &attached_shaders);
if (!attached_shaders) {
return;
}
ShaderMap shaderMap;
GLhandleARB *shaderObjs = new GLhandleARB[attached_shaders];
GLsizei count = 0;
glGetAttachedObjectsARB(programObj, attached_shaders, &count, shaderObjs);
std::sort(shaderObjs, shaderObjs + count);
for (GLsizei i = 0; i < count; ++ i) {
getShaderObjSource(shaderMap, shaderObjs[i]);
}
delete [] shaderObjs;
for (ShaderMap::const_iterator it = shaderMap.begin(); it != shaderMap.end(); ++it) {
json.beginMember(it->first);
json.writeString(it->second);
json.endMember();
}
}
/*
* When fetching the uniform name of an array we usually get name[0]
* so we need to cut the trailing "[0]" in order to properly construct
* array names later. Otherwise we endup with stuff like
* uniformArray[0][0],
* uniformArray[0][1],
* instead of
* uniformArray[0],
* uniformArray[1].
*/
static std::string
resolveUniformName(const GLchar *name, GLint size)
{
std::string qualifiedName(name);
if (size > 1) {
std::string::size_type nameLength = qualifiedName.length();
static const char * const arrayStart = "[0]";
static const int arrayStartLen = 3;
if (qualifiedName.rfind(arrayStart) == (nameLength - arrayStartLen)) {
qualifiedName = qualifiedName.substr(0, nameLength - 3);
}
}
return qualifiedName;
}
static void
dumpUniform(JSONWriter &json, GLint program, GLint size, GLenum type, const GLchar *name) {
GLenum elemType;
GLint numElems;
__gl_uniform_size(type, elemType, numElems);
if (elemType == GL_NONE) {
return;
}
GLfloat fvalues[4*4];
GLdouble dvalues[4*4];
GLint ivalues[4*4];
GLuint uivalues[4*4];
GLint i, j;
std::string qualifiedName = resolveUniformName(name, size);
for (i = 0; i < size; ++i) {
std::stringstream ss;
ss << qualifiedName;
if (size > 1) {
ss << '[' << i << ']';
}
std::string elemName = ss.str();
json.beginMember(elemName);
GLint location = glGetUniformLocation(program, elemName.c_str());
if (numElems > 1) {
json.beginArray();
}
switch (elemType) {
case GL_FLOAT:
glGetUniformfv(program, location, fvalues);
for (j = 0; j < numElems; ++j) {
json.writeNumber(fvalues[j]);
}
break;
case GL_DOUBLE:
glGetUniformdv(program, location, dvalues);
for (j = 0; j < numElems; ++j) {
json.writeNumber(dvalues[j]);
}
break;
case GL_INT:
glGetUniformiv(program, location, ivalues);
for (j = 0; j < numElems; ++j) {
json.writeNumber(ivalues[j]);
}
break;
case GL_UNSIGNED_INT:
glGetUniformuiv(program, location, uivalues);
for (j = 0; j < numElems; ++j) {
json.writeNumber(uivalues[j]);
}
break;
case GL_BOOL:
glGetUniformiv(program, location, ivalues);
for (j = 0; j < numElems; ++j) {
json.writeBool(ivalues[j]);
}
break;
default:
assert(0);
break;
}
if (numElems > 1) {
json.endArray();
}
json.endMember();
}
}
static void
dumpUniformARB(JSONWriter &json, GLhandleARB programObj, GLint size, GLenum type, const GLchar *name) {
GLenum elemType;
GLint numElems;
__gl_uniform_size(type, elemType, numElems);
if (elemType == GL_NONE) {
return;
}
GLfloat fvalues[4*4];
GLint ivalues[4*4];
GLint i, j;
std::string qualifiedName = resolveUniformName(name, size);
for (i = 0; i < size; ++i) {
std::stringstream ss;
ss << qualifiedName;
if (size > 1) {
ss << '[' << i << ']';
}
std::string elemName = ss.str();
json.beginMember(elemName);
GLint location = glGetUniformLocationARB(programObj, elemName.c_str());
if (numElems > 1) {
json.beginArray();
}
switch (elemType) {
case GL_DOUBLE:
// glGetUniformdvARB does not exists
case GL_FLOAT:
glGetUniformfvARB(programObj, location, fvalues);
for (j = 0; j < numElems; ++j) {
json.writeNumber(fvalues[j]);
}
break;
case GL_UNSIGNED_INT:
// glGetUniformuivARB does not exists
case GL_INT:
glGetUniformivARB(programObj, location, ivalues);
for (j = 0; j < numElems; ++j) {
json.writeNumber(ivalues[j]);
}
break;
case GL_BOOL:
glGetUniformivARB(programObj, location, ivalues);
for (j = 0; j < numElems; ++j) {
json.writeBool(ivalues[j]);
}
break;
default:
assert(0);
break;
}
if (numElems > 1) {
json.endArray();
}
json.endMember();
}
}
static inline void
dumpProgramUniforms(JSONWriter &json, GLint program)
{
GLint active_uniforms = 0;
glGetProgramiv(program, GL_ACTIVE_UNIFORMS, &active_uniforms);
if (!active_uniforms) {
return;
}
GLint active_uniform_max_length = 0;
glGetProgramiv(program, GL_ACTIVE_UNIFORM_MAX_LENGTH, &active_uniform_max_length);
GLchar *name = new GLchar[active_uniform_max_length];
if (!name) {
return;
}
for (GLint index = 0; index < active_uniforms; ++index) {
GLsizei length = 0;
GLint size = 0;
GLenum type = GL_NONE;
glGetActiveUniform(program, index, active_uniform_max_length, &length, &size, &type, name);
dumpUniform(json, program, size, type, name);
}
delete [] name;
}
static inline void
dumpProgramObjUniforms(JSONWriter &json, GLhandleARB programObj)
{
GLint active_uniforms = 0;
glGetObjectParameterivARB(programObj, GL_OBJECT_ACTIVE_UNIFORMS_ARB, &active_uniforms);
if (!active_uniforms) {
return;
}
GLint active_uniform_max_length = 0;
glGetObjectParameterivARB(programObj, GL_OBJECT_ACTIVE_UNIFORM_MAX_LENGTH_ARB, &active_uniform_max_length);
GLchar *name = new GLchar[active_uniform_max_length];
if (!name) {
return;
}
for (GLint index = 0; index < active_uniforms; ++index) {
GLsizei length = 0;
GLint size = 0;
GLenum type = GL_NONE;
glGetActiveUniformARB(programObj, index, active_uniform_max_length, &length, &size, &type, name);
dumpUniformARB(json, programObj, size, type, name);
}
delete [] name;
}
static inline void
dumpArbProgram(JSONWriter &json, GLenum target)
{
if (!glIsEnabled(target)) {
return;
}
GLint program_length = 0;
glGetProgramivARB(target, GL_PROGRAM_LENGTH_ARB, &program_length);
if (!program_length) {
return;
}
GLchar *source = new GLchar[program_length + 1];
source[0] = 0;
glGetProgramStringARB(target, GL_PROGRAM_STRING_ARB, source);
source[program_length] = 0;
json.beginMember(enumToString(target));
json.writeString(source);
json.endMember();
delete [] source;
}
static inline void
dumpArbProgramUniforms(JSONWriter &json, GLenum target, const char *prefix)
{
if (!glIsEnabled(target)) {
return;
}
GLint program_parameters = 0;
glGetProgramivARB(target, GL_PROGRAM_PARAMETERS_ARB, &program_parameters);
if (!program_parameters) {
return;
}
GLint max_program_local_parameters = 0;
glGetProgramivARB(target, GL_MAX_PROGRAM_LOCAL_PARAMETERS_ARB, &max_program_local_parameters);
for (GLint index = 0; index < max_program_local_parameters; ++index) {
GLdouble params[4] = {0, 0, 0, 0};
glGetProgramLocalParameterdvARB(target, index, params);
if (!params[0] && !params[1] && !params[2] && !params[3]) {
continue;
}
char name[256];
snprintf(name, sizeof name, "%sprogram.local[%i]", prefix, index);
json.beginMember(name);
json.beginArray();
json.writeNumber(params[0]);
json.writeNumber(params[1]);
json.writeNumber(params[2]);
json.writeNumber(params[3]);
json.endArray();
json.endMember();
}
GLint max_program_env_parameters = 0;
glGetProgramivARB(target, GL_MAX_PROGRAM_ENV_PARAMETERS_ARB, &max_program_env_parameters);
for (GLint index = 0; index < max_program_env_parameters; ++index) {
GLdouble params[4] = {0, 0, 0, 0};
glGetProgramEnvParameterdvARB(target, index, params);
if (!params[0] && !params[1] && !params[2] && !params[3]) {
continue;
}
char name[256];
snprintf(name, sizeof name, "%sprogram.env[%i]", prefix, index);
json.beginMember(name);
json.beginArray();
json.writeNumber(params[0]);
json.writeNumber(params[1]);
json.writeNumber(params[2]);
json.writeNumber(params[3]);
json.endArray();
json.endMember();
}
}
static inline void
dumpShadersUniforms(JSONWriter &json)
{
GLint program = 0;
glGetIntegerv(GL_CURRENT_PROGRAM, &program);
GLhandleARB programObj = glGetHandleARB(GL_PROGRAM_OBJECT_ARB);
json.beginMember("shaders");
json.beginObject();
if (program) {
dumpProgram(json, program);
} else if (programObj) {
dumpProgramObj(json, programObj);
} else {
dumpArbProgram(json, GL_FRAGMENT_PROGRAM_ARB);
dumpArbProgram(json, GL_VERTEX_PROGRAM_ARB);
}
json.endObject();
json.endMember(); // shaders
json.beginMember("uniforms");
json.beginObject();
if (program) {
dumpProgramUniforms(json, program);
} else if (programObj) {
dumpProgramObjUniforms(json, programObj);
} else {
dumpArbProgramUniforms(json, GL_FRAGMENT_PROGRAM_ARB, "fp.");
dumpArbProgramUniforms(json, GL_VERTEX_PROGRAM_ARB, "vp.");
}
json.endObject();
json.endMember(); // uniforms
}
static inline void
dumpTextureImage(JSONWriter &json, GLenum target, GLint level)
{
GLint width, height = 1, depth = 1;
GLint format;
glGetTexLevelParameteriv(target, level, GL_TEXTURE_INTERNAL_FORMAT, &format);
width = 0;
glGetTexLevelParameteriv(target, level, GL_TEXTURE_WIDTH, &width);
if (target != GL_TEXTURE_1D) {
height = 0;
glGetTexLevelParameteriv(target, level, GL_TEXTURE_HEIGHT, &height);
if (target == GL_TEXTURE_3D) {
depth = 0;
glGetTexLevelParameteriv(target, level, GL_TEXTURE_DEPTH, &depth);
}
}
if (width <= 0 || height <= 0 || depth <= 0) {
return;
} else {
char label[512];
GLint active_texture = GL_TEXTURE0;
glGetIntegerv(GL_ACTIVE_TEXTURE, &active_texture);
snprintf(label, sizeof label, "%s, %s, level = %d",
enumToString(active_texture), enumToString(target), level);
json.beginMember(label);
json.beginObject();
// Tell the GUI this is no ordinary object, but an image
json.writeStringMember("__class__", "image");
json.writeNumberMember("__width__", width);
json.writeNumberMember("__height__", height);
json.writeNumberMember("__depth__", depth);
json.writeStringMember("__format__", enumToString(format));
// Hardcoded for now, but we could chose types more adequate to the
// texture internal format
json.writeStringMember("__type__", "uint8");
json.writeBoolMember("__normalized__", true);
json.writeNumberMember("__channels__", 4);
GLubyte *pixels = new GLubyte[depth*width*height*4];
resetPixelPackState();
glGetTexImage(target, level, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
restorePixelPackState();
json.beginMember("__data__");
char *pngBuffer;
int pngBufferSize;
image::writePixelsToBuffer(pixels, width, height, 4, true, &pngBuffer, &pngBufferSize);
json.writeBase64(pngBuffer, pngBufferSize);
free(pngBuffer);
json.endMember(); // __data__
delete [] pixels;
json.endObject();
}
}
static inline void
dumpTexture(JSONWriter &json, GLenum target, GLenum binding)
{
GLint texture_binding = 0;
glGetIntegerv(binding, &texture_binding);
if (!glIsEnabled(target) && !texture_binding) {
return;
}
GLint level = 0;
do {
GLint width = 0, height = 0;
glGetTexLevelParameteriv(target, level, GL_TEXTURE_WIDTH, &width);
glGetTexLevelParameteriv(target, level, GL_TEXTURE_HEIGHT, &height);
if (!width || !height) {
break;
}
if (target == GL_TEXTURE_CUBE_MAP) {
for (int face = 0; face < 6; ++face) {
dumpTextureImage(json, GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, level);
}
} else {
dumpTextureImage(json, target, level);
}
++level;
} while(true);
}
static inline void
dumpTextures(JSONWriter &json)
{
json.beginMember("textures");
json.beginObject();
GLint active_texture = GL_TEXTURE0;
glGetIntegerv(GL_ACTIVE_TEXTURE, &active_texture);
GLint max_texture_coords = 0;
glGetIntegerv(GL_MAX_TEXTURE_COORDS, &max_texture_coords);
GLint max_combined_texture_image_units = 0;
glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &max_combined_texture_image_units);
GLint max_units = std::max(max_combined_texture_image_units, max_texture_coords);
for (GLint unit = 0; unit < max_units; ++unit) {
GLenum texture = GL_TEXTURE0 + unit;
glActiveTexture(texture);
dumpTexture(json, GL_TEXTURE_1D, GL_TEXTURE_BINDING_1D);
dumpTexture(json, GL_TEXTURE_2D, GL_TEXTURE_BINDING_2D);
dumpTexture(json, GL_TEXTURE_3D, GL_TEXTURE_BINDING_3D);
dumpTexture(json, GL_TEXTURE_RECTANGLE, GL_TEXTURE_BINDING_RECTANGLE);
dumpTexture(json, GL_TEXTURE_CUBE_MAP, GL_TEXTURE_BINDING_CUBE_MAP);
}
glActiveTexture(active_texture);
json.endObject();
json.endMember(); // textures
}
static bool
getDrawableBounds(GLint *width, GLint *height) {
#if defined(_WIN32)
HDC hDC = wglGetCurrentDC();
if (!hDC) {
return false;
}
HWND hWnd = WindowFromDC(hDC);
RECT rect;
if (!GetClientRect(hWnd, &rect)) {
return false;
}
*width = rect.right - rect.left;
*height = rect.bottom - rect.top;
#elif defined(__APPLE__)
CGLContextObj ctx = CGLGetCurrentContext();
if (ctx == NULL) {
return false;
}
CGSConnectionID cid;
CGSWindowID wid;
CGSSurfaceID sid;
if (CGLGetSurface(ctx, &cid, &wid, &sid) != kCGLNoError) {
return false;
}
CGRect rect;
if (CGSGetSurfaceBounds(cid, wid, sid, &rect) != 0) {
return false;
}
*width = rect.size.width;
*height = rect.size.height;
#else
#if !TRACE_EGL
Display *display;
Drawable drawable;
Window root;
int x, y;
unsigned int w, h, bw, depth;
display = glXGetCurrentDisplay();
if (!display) {
return false;
}
drawable = glXGetCurrentDrawable();
if (drawable == None) {
return false;
}
if (!XGetGeometry(display, drawable, &root, &x, &y, &w, &h, &bw, &depth)) {
return false;
}
*width = w;
*height = h;
#else
return false;
#endif
#endif
return true;
}
static const GLenum texture_bindings[][2] = {
{GL_TEXTURE_1D, GL_TEXTURE_BINDING_1D},
{GL_TEXTURE_2D, GL_TEXTURE_BINDING_2D},
{GL_TEXTURE_3D, GL_TEXTURE_BINDING_3D},
{GL_TEXTURE_RECTANGLE, GL_TEXTURE_BINDING_RECTANGLE},
{GL_TEXTURE_CUBE_MAP, GL_TEXTURE_BINDING_CUBE_MAP}
};
static bool
bindTexture(GLint texture, GLenum &target, GLint &bound_texture)
{
for (unsigned i = 0; i < sizeof(texture_bindings)/sizeof(texture_bindings[0]); ++i) {
target = texture_bindings[i][0];
GLenum binding = texture_bindings[i][1];
while (glGetError() != GL_NO_ERROR)
;
glGetIntegerv(binding, &bound_texture);
glBindTexture(target, texture);
if (glGetError() == GL_NO_ERROR) {
return true;
}
glBindTexture(target, bound_texture);
}
target = GL_NONE;
return false;
}
static bool
getTextureLevelSize(GLint texture, GLint level, GLint *width, GLint *height)
{
*width = 0;
*height = 0;
GLenum target;
GLint bound_texture = 0;
if (!bindTexture(texture, target, bound_texture)) {
return false;
}
glGetTexLevelParameteriv(target, level, GL_TEXTURE_WIDTH, width);
glGetTexLevelParameteriv(target, level, GL_TEXTURE_HEIGHT, height);
glBindTexture(target, bound_texture);
return *width > 0 && *height > 0;
}
static GLenum
getTextureLevelFormat(GLint texture, GLint level)
{
GLenum target;
GLint bound_texture = 0;
if (!bindTexture(texture, target, bound_texture)) {
return GL_NONE;
}
GLint format = GL_NONE;
glGetTexLevelParameteriv(target, level, GL_TEXTURE_INTERNAL_FORMAT, &format);
glBindTexture(target, bound_texture);
return format;
}
static bool
getRenderbufferSize(GLint renderbuffer, GLint *width, GLint *height)
{
GLint bound_renderbuffer = 0;
glGetIntegerv(GL_RENDERBUFFER_BINDING, &bound_renderbuffer);
glBindRenderbuffer(GL_RENDERBUFFER, renderbuffer);
*width = 0;
*height = 0;
glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, width);
glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, height);
glBindRenderbuffer(GL_RENDERBUFFER, bound_renderbuffer);
return *width > 0 && *height > 0;
}
static GLenum
getRenderbufferFormat(GLint renderbuffer)
{
GLint bound_renderbuffer = 0;
glGetIntegerv(GL_RENDERBUFFER_BINDING, &bound_renderbuffer);
glBindRenderbuffer(GL_RENDERBUFFER, renderbuffer);
GLint format = GL_NONE;
glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_INTERNAL_FORMAT, &format);
glBindRenderbuffer(GL_RENDERBUFFER, bound_renderbuffer);
return format;
}
static bool
getFramebufferAttachmentSize(GLenum target, GLenum attachment, GLint *width, GLint *height)
{
GLint object_type = GL_NONE;
glGetFramebufferAttachmentParameteriv(target, attachment,
GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE,
&object_type);
if (object_type == GL_NONE) {
return false;
}
GLint object_name = 0;
glGetFramebufferAttachmentParameteriv(target, attachment,
GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME,
&object_name);
if (object_name == 0) {
return false;
}
if (object_type == GL_RENDERBUFFER) {
return getRenderbufferSize(object_name, width, height);
} else if (object_type == GL_TEXTURE) {
GLint texture_level = 0;
glGetFramebufferAttachmentParameteriv(target, attachment,
GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL,
&texture_level);
return getTextureLevelSize(object_name, texture_level, width, height);
} else {
std::cerr << "warning: unexpected GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE = " << object_type << "\n";
return false;
}
}
static GLint
getFramebufferAttachmentFormat(GLenum target, GLenum attachment)
{
GLint object_type = GL_NONE;
glGetFramebufferAttachmentParameteriv(target, attachment,
GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE,
&object_type);
if (object_type == GL_NONE) {
return GL_NONE;
}
GLint object_name = 0;
glGetFramebufferAttachmentParameteriv(target, attachment,
GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME,
&object_name);
if (object_name == 0) {
return GL_NONE;
}
if (object_type == GL_RENDERBUFFER) {
return getRenderbufferFormat(object_name);
} else if (object_type == GL_TEXTURE) {
GLint texture_level = 0;
glGetFramebufferAttachmentParameteriv(target, attachment,
GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL,
&texture_level);
return getTextureLevelFormat(object_name, texture_level);
} else {
std::cerr << "warning: unexpected GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE = " << object_type << "\n";
return GL_NONE;
}
}
image::Image *
getDrawBufferImage(GLenum format) {
GLint channels = __gl_format_channels(format);
if (channels > 4) {
return NULL;
}
GLint draw_framebuffer = 0;
glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &draw_framebuffer);
GLint draw_buffer = GL_NONE;
GLint width, height;
if (draw_framebuffer) {
glGetIntegerv(GL_DRAW_BUFFER0, &draw_buffer);
if (draw_buffer == GL_NONE) {
return NULL;
}
if (!getFramebufferAttachmentSize(GL_DRAW_FRAMEBUFFER, draw_buffer, &width, &height)) {
return NULL;
}
} else {
glGetIntegerv(GL_DRAW_BUFFER, &draw_buffer);
if (draw_buffer == GL_NONE) {
return NULL;
}
if (!getDrawableBounds(&width, &height)) {
return NULL;
}
}
image::Image *image = new image::Image(width, height, channels, true);
if (!image) {
return NULL;
}
while (glGetError() != GL_NO_ERROR) {}
GLint read_framebuffer = 0;
glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &read_framebuffer);
glBindFramebuffer(GL_READ_FRAMEBUFFER, draw_framebuffer);
GLint read_buffer = 0;
glGetIntegerv(GL_READ_BUFFER, &read_buffer);
glReadBuffer(draw_buffer);
// TODO: reset imaging state too
resetPixelPackState();
glReadPixels(0, 0, width, height, format, GL_UNSIGNED_BYTE, image->pixels);
restorePixelPackState();
glReadBuffer(read_buffer);
glBindFramebuffer(GL_READ_FRAMEBUFFER, read_framebuffer);
GLenum error = glGetError();
if (error != GL_NO_ERROR) {
do {
std::cerr << "warning: " << enumToString(error) << " while getting snapshot\n";
error = glGetError();
} while(error != GL_NO_ERROR);
delete image;
return NULL;
}
return image;
}
/**
* Dump the image of the currently bound read buffer.
*/
static inline void
dumpReadBufferImage(JSONWriter &json, GLint width, GLint height, GLenum format,
GLint internalFormat = GL_NONE)
{
GLint channels = __gl_format_channels(format);
json.beginObject();
// Tell the GUI this is no ordinary object, but an image
json.writeStringMember("__class__", "image");
json.writeNumberMember("__width__", width);
json.writeNumberMember("__height__", height);
json.writeNumberMember("__depth__", 1);
json.writeStringMember("__format__", enumToString(internalFormat));
// Hardcoded for now, but we could chose types more adequate to the
// texture internal format
json.writeStringMember("__type__", "uint8");
json.writeBoolMember("__normalized__", true);
json.writeNumberMember("__channels__", channels);
GLubyte *pixels = new GLubyte[width*height*channels];
// TODO: reset imaging state too
resetPixelPackState();
glReadPixels(0, 0, width, height, format, GL_UNSIGNED_BYTE, pixels);
restorePixelPackState();
json.beginMember("__data__");
char *pngBuffer;
int pngBufferSize;
image::writePixelsToBuffer(pixels, width, height, channels, true, &pngBuffer, &pngBufferSize);
//std::cerr <<" Before = "<<(width * height * channels * sizeof *pixels)
// <<", after = "<<pngBufferSize << ", ratio = " << double(width * height * channels * sizeof *pixels)/pngBufferSize;
json.writeBase64(pngBuffer, pngBufferSize);
free(pngBuffer);
json.endMember(); // __data__
delete [] pixels;
json.endObject();
}
static inline GLuint
downsampledFramebuffer(GLuint oldFbo, GLint drawbuffer,
GLint colorRb, GLint depthRb, GLint stencilRb,
GLuint *rbs, GLint *numRbs)
{
GLuint fbo;
GLint format;
GLint w, h;
*numRbs = 0;
glGenFramebuffers(1, &fbo);
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glBindRenderbuffer(GL_RENDERBUFFER, colorRb);
glGetRenderbufferParameteriv(GL_RENDERBUFFER,
GL_RENDERBUFFER_WIDTH, &w);
glGetRenderbufferParameteriv(GL_RENDERBUFFER,
GL_RENDERBUFFER_HEIGHT, &h);
glGetRenderbufferParameteriv(GL_RENDERBUFFER,
GL_RENDERBUFFER_INTERNAL_FORMAT, &format);
glGenRenderbuffers(1, &rbs[*numRbs]);
glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
glRenderbufferStorage(GL_RENDERBUFFER, format, w, h);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, drawbuffer,
GL_RENDERBUFFER, rbs[*numRbs]);
glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
glDrawBuffer(drawbuffer);
glReadBuffer(drawbuffer);
glBlitFramebuffer(0, 0, w, h, 0, 0, w, h,
GL_COLOR_BUFFER_BIT, GL_NEAREST);
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
++*numRbs;
if (stencilRb == depthRb && stencilRb) {
//combined depth and stencil buffer
glBindRenderbuffer(GL_RENDERBUFFER, depthRb);
glGetRenderbufferParameteriv(GL_RENDERBUFFER,
GL_RENDERBUFFER_WIDTH, &w);
glGetRenderbufferParameteriv(GL_RENDERBUFFER,
GL_RENDERBUFFER_HEIGHT, &h);
glGetRenderbufferParameteriv(GL_RENDERBUFFER,
GL_RENDERBUFFER_INTERNAL_FORMAT, &format);
glGenRenderbuffers(1, &rbs[*numRbs]);
glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
glRenderbufferStorage(GL_RENDERBUFFER, format, w, h);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT,
GL_RENDERBUFFER, rbs[*numRbs]);
glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
glBlitFramebuffer(0, 0, w, h, 0, 0, w, h,
GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT, GL_NEAREST);
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
++*numRbs;
} else {
if (depthRb) {
glBindRenderbuffer(GL_RENDERBUFFER, depthRb);
glGetRenderbufferParameteriv(GL_RENDERBUFFER,
GL_RENDERBUFFER_WIDTH, &w);
glGetRenderbufferParameteriv(GL_RENDERBUFFER,
GL_RENDERBUFFER_HEIGHT, &h);
glGetRenderbufferParameteriv(GL_RENDERBUFFER,
GL_RENDERBUFFER_INTERNAL_FORMAT, &format);
glGenRenderbuffers(1, &rbs[*numRbs]);
glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
glRenderbufferStorage(GL_RENDERBUFFER, format, w, h);
glFramebufferRenderbuffer(GL_FRAMEBUFFER,
GL_DEPTH_ATTACHMENT,
GL_RENDERBUFFER, rbs[*numRbs]);
glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
glDrawBuffer(GL_DEPTH_ATTACHMENT);
glReadBuffer(GL_DEPTH_ATTACHMENT);
glBlitFramebuffer(0, 0, w, h, 0, 0, w, h,
GL_DEPTH_BUFFER_BIT, GL_NEAREST);
++*numRbs;
}
if (stencilRb) {
glBindRenderbuffer(GL_RENDERBUFFER, stencilRb);
glGetRenderbufferParameteriv(GL_RENDERBUFFER,
GL_RENDERBUFFER_WIDTH, &w);
glGetRenderbufferParameteriv(GL_RENDERBUFFER,
GL_RENDERBUFFER_HEIGHT, &h);
glGetRenderbufferParameteriv(GL_RENDERBUFFER,
GL_RENDERBUFFER_INTERNAL_FORMAT, &format);
glGenRenderbuffers(1, &rbs[*numRbs]);
glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
glRenderbufferStorage(GL_RENDERBUFFER, format, w, h);
glFramebufferRenderbuffer(GL_FRAMEBUFFER,
GL_STENCIL_ATTACHMENT,
GL_RENDERBUFFER, rbs[*numRbs]);
glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
glDrawBuffer(GL_STENCIL_ATTACHMENT);
glReadBuffer(GL_STENCIL_ATTACHMENT);
glBlitFramebuffer(0, 0, w, h, 0, 0, w, h,
GL_STENCIL_BUFFER_BIT, GL_NEAREST);
++*numRbs;
}
}
return fbo;
}
/**
* Dump images of current draw drawable/window.
*/
static void
dumpDrawableImages(JSONWriter &json)
{
GLint width, height;
if (!getDrawableBounds(&width, &height)) {
return;
}
GLint draw_buffer = GL_NONE;
glGetIntegerv(GL_DRAW_BUFFER, &draw_buffer);
glReadBuffer(draw_buffer);
if (draw_buffer != GL_NONE) {
GLint read_buffer = GL_NONE;
glGetIntegerv(GL_READ_BUFFER, &read_buffer);
GLint alpha_bits = 0;
glGetIntegerv(GL_ALPHA_BITS, &alpha_bits);
GLenum format = alpha_bits ? GL_RGBA : GL_RGB;
json.beginMember(enumToString(draw_buffer));
dumpReadBufferImage(json, width, height, format);
json.endMember();
glReadBuffer(read_buffer);
}
GLint depth_bits = 0;
glGetIntegerv(GL_DEPTH_BITS, &depth_bits);
if (depth_bits) {
json.beginMember("GL_DEPTH_COMPONENT");
dumpReadBufferImage(json, width, height, GL_DEPTH_COMPONENT);
json.endMember();
}
GLint stencil_bits = 0;
glGetIntegerv(GL_STENCIL_BITS, &stencil_bits);
if (stencil_bits) {
json.beginMember("GL_STENCIL_INDEX");
dumpReadBufferImage(json, width, height, GL_STENCIL_INDEX);
json.endMember();
}
}
/**
* Dump the specified framebuffer attachment.
*
* In the case of a color attachment, it assumes it is already bound for read.
*/
static void
dumpFramebufferAttachment(JSONWriter &json, GLenum target, GLenum attachment, GLenum format)
{
GLint width = 0, height = 0;
if (!getFramebufferAttachmentSize(target, attachment, &width, &height)) {
return;
}
GLint internalFormat = getFramebufferAttachmentFormat(target, attachment);
json.beginMember(enumToString(attachment));
dumpReadBufferImage(json, width, height, format, internalFormat);
json.endMember();
}
static void
dumpFramebufferAttachments(JSONWriter &json, GLenum target)
{
GLint read_framebuffer = 0;
glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &read_framebuffer);
GLint read_buffer = GL_NONE;
glGetIntegerv(GL_READ_BUFFER, &read_buffer);
GLint max_draw_buffers = 1;
glGetIntegerv(GL_MAX_DRAW_BUFFERS, &max_draw_buffers);
GLint max_color_attachments = 0;
glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS, &max_color_attachments);
for (GLint i = 0; i < max_draw_buffers; ++i) {
GLint draw_buffer = GL_NONE;
glGetIntegerv(GL_DRAW_BUFFER0 + i, &draw_buffer);
if (draw_buffer != GL_NONE) {
glReadBuffer(draw_buffer);
GLint attachment;
if (draw_buffer >= GL_COLOR_ATTACHMENT0 && draw_buffer < GL_COLOR_ATTACHMENT0 + max_color_attachments) {
attachment = draw_buffer;
} else {
std::cerr << "warning: unexpected GL_DRAW_BUFFER" << i << " = " << draw_buffer << "\n";
attachment = GL_COLOR_ATTACHMENT0;
}
GLint alpha_size = 0;
glGetFramebufferAttachmentParameteriv(target, attachment,
GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE,
&alpha_size);
GLenum format = alpha_size ? GL_RGBA : GL_RGB;
dumpFramebufferAttachment(json, target, attachment, format);
}
}
glReadBuffer(read_buffer);
dumpFramebufferAttachment(json, target, GL_DEPTH_ATTACHMENT, GL_DEPTH_COMPONENT);
dumpFramebufferAttachment(json, target, GL_STENCIL_ATTACHMENT, GL_STENCIL_INDEX);
glBindFramebuffer(GL_READ_FRAMEBUFFER, read_framebuffer);
}
static void
dumpFramebuffer(JSONWriter &json)
{
json.beginMember("framebuffer");
json.beginObject();
GLint boundDrawFbo = 0, boundReadFbo = 0;
glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &boundDrawFbo);
glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &boundReadFbo);
if (!boundDrawFbo) {
dumpDrawableImages(json);
} else {
GLint colorRb = 0, stencilRb = 0, depthRb = 0;
GLint draw_buffer0 = GL_NONE;
glGetIntegerv(GL_DRAW_BUFFER0, &draw_buffer0);
bool multisample = false;
GLint boundRb = 0;
glGetIntegerv(GL_RENDERBUFFER_BINDING, &boundRb);
GLint object_type;
glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, draw_buffer0, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &object_type);
if (object_type == GL_RENDERBUFFER) {
glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, draw_buffer0, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &colorRb);
glBindRenderbuffer(GL_RENDERBUFFER, colorRb);
GLint samples = 0;
glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_SAMPLES, &samples);
if (samples) {
multisample = true;
}
}
glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &object_type);
if (object_type == GL_RENDERBUFFER) {
glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &depthRb);
glBindRenderbuffer(GL_RENDERBUFFER, depthRb);
GLint samples = 0;
glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_SAMPLES, &samples);
if (samples) {
multisample = true;
}
}
glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &object_type);
if (object_type == GL_RENDERBUFFER) {
glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &stencilRb);
glBindRenderbuffer(GL_RENDERBUFFER, stencilRb);
GLint samples = 0;
glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_SAMPLES, &samples);
if (samples) {
multisample = true;
}
}
glBindRenderbuffer(GL_RENDERBUFFER, boundRb);
GLuint rbs[3];
GLint numRbs = 0;
GLuint fboCopy = 0;
if (multisample) {
// glReadPixels doesnt support multisampled buffers so we need
// to blit the fbo to a temporary one
fboCopy = downsampledFramebuffer(boundDrawFbo, draw_buffer0,
colorRb, depthRb, stencilRb,
rbs, &numRbs);
}
dumpFramebufferAttachments(json, GL_DRAW_FRAMEBUFFER);
if (multisample) {
glBindRenderbuffer(GL_RENDERBUFFER_BINDING, boundRb);
glDeleteRenderbuffers(numRbs, rbs);
glDeleteFramebuffers(1, &fboCopy);
}
glBindFramebuffer(GL_READ_FRAMEBUFFER, boundReadFbo);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, boundDrawFbo);
}
json.endObject();
json.endMember(); // framebuffer
}
static const GLenum bindings[] = {
GL_DRAW_BUFFER,
GL_READ_BUFFER,
GL_PIXEL_PACK_BUFFER_BINDING,
GL_PIXEL_UNPACK_BUFFER_BINDING,
GL_TEXTURE_BINDING_1D,
GL_TEXTURE_BINDING_2D,
GL_TEXTURE_BINDING_3D,
GL_TEXTURE_BINDING_RECTANGLE,
GL_TEXTURE_BINDING_CUBE_MAP,
GL_DRAW_FRAMEBUFFER_BINDING,
GL_READ_FRAMEBUFFER_BINDING,
GL_RENDERBUFFER_BINDING,
GL_DRAW_BUFFER0,
GL_DRAW_BUFFER1,
GL_DRAW_BUFFER2,
GL_DRAW_BUFFER3,
GL_DRAW_BUFFER4,
GL_DRAW_BUFFER5,
GL_DRAW_BUFFER6,
GL_DRAW_BUFFER7,
};
#define NUM_BINDINGS sizeof(bindings)/sizeof(bindings[0])
void dumpCurrentContext(std::ostream &os)
{
JSONWriter json(os);
#ifndef NDEBUG
GLint old_bindings[NUM_BINDINGS];
for (unsigned i = 0; i < NUM_BINDINGS; ++i) {
old_bindings[i] = 0;
glGetIntegerv(bindings[i], &old_bindings[i]);
}
#endif
dumpParameters(json);
dumpShadersUniforms(json);
dumpTextures(json);
dumpFramebuffer(json);
#ifndef NDEBUG
for (unsigned i = 0; i < NUM_BINDINGS; ++i) {
GLint new_binding = 0;
glGetIntegerv(bindings[i], &new_binding);
if (new_binding != old_bindings[i]) {
std::cerr << "warning: " << enumToString(bindings[i]) << " was clobbered\n";
}
}
#endif
}
} /* namespace glstate */
| 29.709028 | 145 | 0.634254 | prahal |
3293ffac38541bdbd5aa838b8b39b45efafd8ca3 | 1,218 | hpp | C++ | Software/STM/APP/Screens/StateAccel.hpp | ProrokWielki/Wooden-Clock | 96226750ab4b679764b0b254d3c3c21deb658252 | [
"MIT"
] | 1 | 2018-12-14T07:05:33.000Z | 2018-12-14T07:05:33.000Z | Software/STM/APP/Screens/StateAccel.hpp | ProrokWielki/Wooden-Clock | 96226750ab4b679764b0b254d3c3c21deb658252 | [
"MIT"
] | null | null | null | Software/STM/APP/Screens/StateAccel.hpp | ProrokWielki/Wooden-Clock | 96226750ab4b679764b0b254d3c3c21deb658252 | [
"MIT"
] | null | null | null | /**
* StataAccel.hpp
*
* Created on: 02-05-2020
* @author: Paweł Warzecha
*/
#ifndef APP_STATEMACHINE_STATES_STATEACCEL_HPP_
#define APP_STATEMACHINE_STATES_STATEACCEL_HPP_
#include <Canvas.hpp>
#include "LSM9DS1/LSM9DS1.hpp"
#include "BSP.hpp"
class StateAccel: public Canvas
{
public:
explicit StateAccel(LSM9DS1 & accel) : accel_(accel), magnet(32, 32, &empty_frame_buffer[0][0])
{
}
void init() override
{
add(&magnet);
validate();
}
virtual void up_date() override
{
static uint8_t old_x = 0;
static uint8_t old_y = 0;
int16_t x = accel_.get_linear_acceleration(Axis::X);
int16_t y = accel_.get_linear_acceleration(Axis::Y);
x = ((-x * 16) >> 14) + 16;
y = ((y * 16) >> 14) + 16;
x = x > 31 ? 31 : x;
y = y > 31 ? 31 : y;
x = x < 0 ? 0 : x;
y = y < 0 ? 0 : y;
empty_frame_buffer[old_y][old_x] = 0;
old_x = x;
old_y = y;
empty_frame_buffer[y][x] = 255;
validate();
}
private:
LSM9DS1 & accel_;
uint8_t empty_frame_buffer[32][32] = {0};
Image magnet;
};
#endif /* APP_STATEMACHINE_STATES_STATENORTH_HPP_ */
| 19.03125 | 99 | 0.569787 | ProrokWielki |
3298f89e4f50077b33b105f16202820fef1bbd25 | 2,554 | cc | C++ | test/limits.cc | root-project/VecCore | 9375eb6005d08b2bca3b0a2b62e90dbe21694176 | [
"Apache-2.0"
] | 56 | 2017-04-12T17:57:33.000Z | 2021-12-18T03:28:24.000Z | test/limits.cc | root-project/VecCore | 9375eb6005d08b2bca3b0a2b62e90dbe21694176 | [
"Apache-2.0"
] | 19 | 2017-05-09T06:40:48.000Z | 2021-11-01T09:54:24.000Z | test/limits.cc | root-project/VecCore | 9375eb6005d08b2bca3b0a2b62e90dbe21694176 | [
"Apache-2.0"
] | 22 | 2017-04-10T13:41:15.000Z | 2021-08-20T09:05:10.000Z | #include "test.h"
template <class T> class NumericLimitsTest : public VectorTypeTest<T> {};
TYPED_TEST_SUITE_P(NumericLimitsTest);
TYPED_TEST_P(NumericLimitsTest, Limits) {
using Scalar_t = typename TestFixture::Scalar_t;
using Vector_t = typename TestFixture::Vector_t;
using vecCore::Get;
using vecCore::NumericLimits;
using vecCore::VectorSize;
size_t N = VectorSize<Vector_t>();
EXPECT_TRUE(NumericLimits<Scalar_t>::Min() ==
Get(NumericLimits<Vector_t>::Min(), 0));
EXPECT_TRUE(NumericLimits<Scalar_t>::Max() ==
Get(NumericLimits<Vector_t>::Max(), 0));
EXPECT_TRUE(NumericLimits<Scalar_t>::Lowest() ==
Get(NumericLimits<Vector_t>::Lowest(), 0));
EXPECT_TRUE(NumericLimits<Scalar_t>::Highest() ==
Get(NumericLimits<Vector_t>::Highest(), 0));
EXPECT_TRUE(NumericLimits<Scalar_t>::Epsilon() ==
Get(NumericLimits<Vector_t>::Epsilon(), 0));
EXPECT_TRUE(NumericLimits<Scalar_t>::Infinity() ==
Get(NumericLimits<Vector_t>::Infinity(), 0));
EXPECT_TRUE(NumericLimits<Scalar_t>::Min() ==
Get(NumericLimits<Vector_t>::Min(), N - 1));
EXPECT_TRUE(NumericLimits<Scalar_t>::Max() ==
Get(NumericLimits<Vector_t>::Max(), N - 1));
EXPECT_TRUE(NumericLimits<Scalar_t>::Lowest() ==
Get(NumericLimits<Vector_t>::Lowest(), N - 1));
EXPECT_TRUE(NumericLimits<Scalar_t>::Highest() ==
Get(NumericLimits<Vector_t>::Highest(), N - 1));
EXPECT_TRUE(NumericLimits<Scalar_t>::Epsilon() ==
Get(NumericLimits<Vector_t>::Epsilon(), N - 1));
EXPECT_TRUE(NumericLimits<Scalar_t>::Infinity() ==
Get(NumericLimits<Vector_t>::Infinity(), N - 1));
}
REGISTER_TYPED_TEST_SUITE_P(NumericLimitsTest, Limits);
#define TEST_BACKEND_P(name, x) \
INSTANTIATE_TYPED_TEST_SUITE_P(name, NumericLimitsTest, \
FloatTypes<vecCore::backend::x>);
#define TEST_BACKEND(x) TEST_BACKEND_P(x, x)
TEST_BACKEND(Scalar);
TEST_BACKEND(ScalarWrapper);
#ifdef VECCORE_ENABLE_VC
TEST_BACKEND(VcScalar);
TEST_BACKEND(VcVector);
TEST_BACKEND_P(VcSimdArray, VcSimdArray<4>);
#endif
#ifdef VECCORE_ENABLE_UMESIMD
TEST_BACKEND(UMESimd);
TEST_BACKEND_P(UMESimdArray, UMESimdArray<4>);
#endif
#ifdef VECCORE_ENABLE_STD_SIMD
TEST_BACKEND_P(SIMDScalar, SIMDScalar);
TEST_BACKEND_P(SIMDVector4, SIMDVector<4>);
TEST_BACKEND_P(SIMDVector8, SIMDVector<8>);
TEST_BACKEND_P(SIMDNative, SIMDNative);
#endif
| 35.472222 | 80 | 0.676586 | root-project |
32993408f853be203f88de88f31cbb638cafb756 | 1,277 | cpp | C++ | Task 3/RSA.cpp | John-Ghaly88/Cryptography_Course | 7045e931c77032024bbebd2305895003a8625467 | [
"MIT"
] | null | null | null | Task 3/RSA.cpp | John-Ghaly88/Cryptography_Course | 7045e931c77032024bbebd2305895003a8625467 | [
"MIT"
] | null | null | null | Task 3/RSA.cpp | John-Ghaly88/Cryptography_Course | 7045e931c77032024bbebd2305895003a8625467 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int gcd(int x, int y)
{
if (x == 0)
return y;
return gcd(y % x, x);
}
int EulerTotient(int x)
{
int r = 1;
for (int i = 2; i < x; i++)
if (gcd(i, x) == 1)
r++;
return r;
}
int main()
{
cout << "Input n | n < 65536" << endl;
int n;
cin >> n;
cout << "Input e (The public encryption key)" << endl;
int e;
cin >> e;
cout << "Input the cipher encrypted text" << endl;
string cipher;
cin >> cipher;
int phi = EulerTotient(n);
int k = 11;
int d = (1 + (k*phi))/e;
//Assuming that the RSA algorithm used for encrypting this cipher text encodes the non-numerical text
//into their corresponding ASCII number and perform the operation C = P^e mod n on this ASCII value
string plain = "";
for (int i = 0; i < cipher.length(); i++) {
if(cipher.at(i) != ' '){
int c = (int) cipher.at(i);
double p = fmod(pow(c,d), n);
plain.push_back((char)p);
}
else
plain.push_back(' ');
}
cout << "The value of d (The private decryption key) is = " << d << endl;
cout << "The plain decrypted text is: " << plain << endl;
return 0;
}
| 22.403509 | 106 | 0.512921 | John-Ghaly88 |
32997875f0e6406feec6fd94326385f6ae80d4c6 | 484 | cpp | C++ | VD_prep/VR_rep_K2016/main.cpp | theroyalcoder/old.HF-ICT-4-SEM-GUI | d97bec83f339807a0054449421fe061ba901ddf3 | [
"MIT"
] | null | null | null | VD_prep/VR_rep_K2016/main.cpp | theroyalcoder/old.HF-ICT-4-SEM-GUI | d97bec83f339807a0054449421fe061ba901ddf3 | [
"MIT"
] | null | null | null | VD_prep/VR_rep_K2016/main.cpp | theroyalcoder/old.HF-ICT-4-SEM-GUI | d97bec83f339807a0054449421fe061ba901ddf3 | [
"MIT"
] | 1 | 2018-05-03T21:46:28.000Z | 2018-05-03T21:46:28.000Z | #include <iostream>
using namespace std;
//Klausur 2015
int crossumRec(unsigned int n, int result) {
return result + (n % 10);
}
int crossum(unsigned int n) {
int result = 0;
int localN = n;
while (localN > 0) {
result = crossumRec(localN, result);
localN /= 10;
}
return result;
}
int main() {
std::cout << "Hello, World!" << std::endl;
cout << crossum(123);
srand(static_cast<unsigned int>(time(nullptr)));
return 0;
}
| 16.689655 | 52 | 0.586777 | theroyalcoder |
329b7301fa019f359ee470e9ed947bfc831d8237 | 15,527 | cc | C++ | source/common/upstream/load_balancer_impl.cc | Sodman/envoy | 9cb135e059ac6af052e5a5aa6c6c279aada1850b | [
"Apache-2.0"
] | null | null | null | source/common/upstream/load_balancer_impl.cc | Sodman/envoy | 9cb135e059ac6af052e5a5aa6c6c279aada1850b | [
"Apache-2.0"
] | null | null | null | source/common/upstream/load_balancer_impl.cc | Sodman/envoy | 9cb135e059ac6af052e5a5aa6c6c279aada1850b | [
"Apache-2.0"
] | 1 | 2020-12-30T17:12:11.000Z | 2020-12-30T17:12:11.000Z | #include "common/upstream/load_balancer_impl.h"
#include <cstdint>
#include <string>
#include <vector>
#include "envoy/runtime/runtime.h"
#include "envoy/stats/stats.h"
#include "envoy/upstream/upstream.h"
#include "common/common/assert.h"
namespace Envoy {
namespace Upstream {
namespace {
const HostSet* bestAvailable(const PrioritySet* priority_set) {
if (priority_set == nullptr) {
return nullptr;
}
// This is used for LoadBalancerBase priority_set_ and local_priority_set_
// which are guaranteed to have at least one host set.
ASSERT(priority_set->hostSetsPerPriority().size() > 0);
for (auto& host_set : priority_set->hostSetsPerPriority()) {
if (!host_set->healthyHosts().empty()) {
return host_set.get();
}
}
return priority_set->hostSetsPerPriority()[0].get();
}
} // namespace
static const std::string RuntimeZoneEnabled = "upstream.zone_routing.enabled";
static const std::string RuntimeMinClusterSize = "upstream.zone_routing.min_cluster_size";
static const std::string RuntimePanicThreshold = "upstream.healthy_panic_threshold";
LoadBalancerBase::LoadBalancerBase(const PrioritySet& priority_set,
const PrioritySet* local_priority_set, ClusterStats& stats,
Runtime::Loader& runtime, Runtime::RandomGenerator& random)
: stats_(stats), runtime_(runtime), random_(random), priority_set_(priority_set),
best_available_host_set_(bestAvailable(&priority_set)),
local_priority_set_(local_priority_set) {
ASSERT(priority_set.hostSetsPerPriority().size() > 0);
resizePerPriorityState();
priority_set_.addMemberUpdateCb([this](uint32_t priority, const std::vector<HostSharedPtr>&,
const std::vector<HostSharedPtr>&) -> void {
// Update the host set to use for picking, based on the new state.
best_available_host_set_ = bestAvailable(&priority_set_);
// Make sure per_priority_state_ is as large as priority_set_.hostSetsPerPriority()
resizePerPriorityState();
// If there's a local priority set, regenerate all routing based on a potential size change to
// the hosts routed to.
if (local_priority_set_) {
regenerateLocalityRoutingStructures(priority);
}
});
if (local_priority_set_) {
// Multiple priorities are unsupported for local priority sets.
// In order to support priorities correctly, one would have to make some assumptions about
// routing (all local Envoys fail over at the same time) and use all priorities when computing
// the locality routing structure.
ASSERT(local_priority_set_->hostSetsPerPriority().size() == 1);
local_priority_set_member_update_cb_handle_ = local_priority_set_->addMemberUpdateCb(
[this](uint32_t priority, const std::vector<HostSharedPtr>&,
const std::vector<HostSharedPtr>&) -> void {
ASSERT(priority == 0);
UNREFERENCED_PARAMETER(priority);
// If the set of local Envoys changes, regenerate routing based on potential changes to
// the set of servers routing to priority_set_.
regenerateLocalityRoutingStructures(bestAvailablePriority());
});
}
}
LoadBalancerBase::~LoadBalancerBase() {
if (local_priority_set_member_update_cb_handle_ != nullptr) {
local_priority_set_member_update_cb_handle_->remove();
}
}
void LoadBalancerBase::regenerateLocalityRoutingStructures(uint32_t priority) {
ASSERT(local_priority_set_);
stats_.lb_recalculate_zone_structures_.inc();
// We are updating based on a change for a priority level in priority_set_, or the latched
// bestAvailablePriority() which is a latched priority for priority_set_.
ASSERT(priority < priority_set_.hostSetsPerPriority().size());
// resizePerPriorityState should ensure these stay in sync.
ASSERT(per_priority_state_.size() == priority_set_.hostSetsPerPriority().size());
// Do not perform any calculations if we cannot perform locality routing based on non runtime
// params.
PerPriorityState& state = *per_priority_state_[priority];
if (earlyExitNonLocalityRouting(priority)) {
state.locality_routing_state_ = LocalityRoutingState::NoLocalityRouting;
return;
}
HostSet& host_set = *priority_set_.hostSetsPerPriority()[priority];
size_t num_localities = host_set.healthyHostsPerLocality().size();
ASSERT(num_localities > 0);
uint64_t local_percentage[num_localities];
calculateLocalityPercentage(localHostSet().healthyHostsPerLocality(), local_percentage);
uint64_t upstream_percentage[num_localities];
calculateLocalityPercentage(host_set.healthyHostsPerLocality(), upstream_percentage);
// If we have lower percent of hosts in the local cluster in the same locality,
// we can push all of the requests directly to upstream cluster in the same locality.
if (upstream_percentage[0] >= local_percentage[0]) {
state.locality_routing_state_ = LocalityRoutingState::LocalityDirect;
return;
}
state.locality_routing_state_ = LocalityRoutingState::LocalityResidual;
// If we cannot route all requests to the same locality, calculate what percentage can be routed.
// For example, if local percentage is 20% and upstream is 10%
// we can route only 50% of requests directly.
state.local_percent_to_route_ = upstream_percentage[0] * 10000 / local_percentage[0];
// Local locality does not have additional capacity (we have already routed what we could).
// Now we need to figure out how much traffic we can route cross locality and to which exact
// locality we should route. Percentage of requests routed cross locality to a specific locality
// needed be proportional to the residual capacity upstream locality has.
//
// residual_capacity contains capacity left in a given locality, we keep accumulating residual
// capacity to make search for sampled value easier.
// For example, if we have the following upstream and local percentage:
// local_percentage: 40000 40000 20000
// upstream_percentage: 25000 50000 25000
// Residual capacity would look like: 0 10000 5000. Now we need to sample proportionally to
// bucket sizes (residual capacity). For simplicity of finding where specific
// sampled value is, we accumulate values in residual capacity. This is what it will look like:
// residual_capacity: 0 10000 15000
// Now to find a locality to route (bucket) we could simply iterate over residual_capacity
// searching where sampled value is placed.
state.residual_capacity_.resize(num_localities);
// Local locality (index 0) does not have residual capacity as we have routed all we could.
state.residual_capacity_[0] = 0;
for (size_t i = 1; i < num_localities; ++i) {
// Only route to the localities that have additional capacity.
if (upstream_percentage[i] > local_percentage[i]) {
state.residual_capacity_[i] =
state.residual_capacity_[i - 1] + upstream_percentage[i] - local_percentage[i];
} else {
// Locality with index "i" does not have residual capacity, but we keep accumulating previous
// values to make search easier on the next step.
state.residual_capacity_[i] = state.residual_capacity_[i - 1];
}
}
};
void LoadBalancerBase::resizePerPriorityState() {
const uint32_t size = priority_set_.hostSetsPerPriority().size();
while (per_priority_state_.size() < size) {
per_priority_state_.push_back(PerPriorityStatePtr{new PerPriorityState});
}
}
bool LoadBalancerBase::earlyExitNonLocalityRouting(uint32_t priority) {
if (priority_set_.hostSetsPerPriority().size() < priority + 1) {
return true;
}
HostSet& host_set = *priority_set_.hostSetsPerPriority()[priority];
if (host_set.healthyHostsPerLocality().size() < 2) {
return true;
}
if (host_set.healthyHostsPerLocality()[0].empty()) {
return true;
}
// Same number of localities should be for local and upstream cluster.
if (host_set.healthyHostsPerLocality().size() !=
localHostSet().healthyHostsPerLocality().size()) {
stats_.lb_zone_number_differs_.inc();
return true;
}
// Do not perform locality routing for small clusters.
uint64_t min_cluster_size = runtime_.snapshot().getInteger(RuntimeMinClusterSize, 6U);
if (host_set.healthyHosts().size() < min_cluster_size) {
stats_.lb_zone_cluster_too_small_.inc();
return true;
}
return false;
}
bool LoadBalancerUtility::isGlobalPanic(const HostSet& host_set, Runtime::Loader& runtime) {
uint64_t global_panic_threshold =
std::min<uint64_t>(100, runtime.snapshot().getInteger(RuntimePanicThreshold, 50));
double healthy_percent = host_set.hosts().size() == 0
? 0
: 100.0 * host_set.healthyHosts().size() / host_set.hosts().size();
// If the % of healthy hosts in the cluster is less than our panic threshold, we use all hosts.
if (healthy_percent < global_panic_threshold) {
return true;
}
return false;
}
void LoadBalancerBase::calculateLocalityPercentage(
const std::vector<std::vector<HostSharedPtr>>& hosts_per_locality, uint64_t* ret) {
uint64_t total_hosts = 0;
for (const auto& locality_hosts : hosts_per_locality) {
total_hosts += locality_hosts.size();
}
size_t i = 0;
for (const auto& locality_hosts : hosts_per_locality) {
ret[i++] = total_hosts > 0 ? 10000ULL * locality_hosts.size() / total_hosts : 0;
}
}
const std::vector<HostSharedPtr>& LoadBalancerBase::tryChooseLocalLocalityHosts() {
PerPriorityState& state = *per_priority_state_[bestAvailablePriority()];
ASSERT(state.locality_routing_state_ != LocalityRoutingState::NoLocalityRouting);
// At this point it's guaranteed to be at least 2 localities.
size_t number_of_localities = best_available_host_set_->healthyHostsPerLocality().size();
ASSERT(number_of_localities >= 2U);
// Try to push all of the requests to the same locality first.
if (state.locality_routing_state_ == LocalityRoutingState::LocalityDirect) {
stats_.lb_zone_routing_all_directly_.inc();
return best_available_host_set_->healthyHostsPerLocality()[0];
}
ASSERT(state.locality_routing_state_ == LocalityRoutingState::LocalityResidual);
// If we cannot route all requests to the same locality, we already calculated how much we can
// push to the local locality, check if we can push to local locality on current iteration.
if (random_.random() % 10000 < state.local_percent_to_route_) {
stats_.lb_zone_routing_sampled_.inc();
return best_available_host_set_->healthyHostsPerLocality()[0];
}
// At this point we must route cross locality as we cannot route to the local locality.
stats_.lb_zone_routing_cross_zone_.inc();
// This is *extremely* unlikely but possible due to rounding errors when calculating
// locality percentages. In this case just select random locality.
if (state.residual_capacity_[number_of_localities - 1] == 0) {
stats_.lb_zone_no_capacity_left_.inc();
return best_available_host_set_
->healthyHostsPerLocality()[random_.random() % number_of_localities];
}
// Random sampling to select specific locality for cross locality traffic based on the additional
// capacity in localities.
uint64_t threshold = random_.random() % state.residual_capacity_[number_of_localities - 1];
// This potentially can be optimized to be O(log(N)) where N is the number of localities.
// Linear scan should be faster for smaller N, in most of the scenarios N will be small.
int i = 0;
while (threshold > state.residual_capacity_[i]) {
i++;
}
return best_available_host_set_->healthyHostsPerLocality()[i];
}
const std::vector<HostSharedPtr>& LoadBalancerBase::hostsToUse() {
ASSERT(best_available_host_set_->healthyHosts().size() <=
best_available_host_set_->hosts().size());
// If the best available priority has insufficient healthy hosts, return all hosts.
if (LoadBalancerUtility::isGlobalPanic(*best_available_host_set_, runtime_)) {
stats_.lb_healthy_panic_.inc();
return best_available_host_set_->hosts();
}
// If we've latched that we can't do priority-based routing, return healthy
// hosts for the best available priority.
if (per_priority_state_[bestAvailablePriority()]->locality_routing_state_ ==
LocalityRoutingState::NoLocalityRouting) {
return best_available_host_set_->healthyHosts();
}
// Determine if the load balancer should do zone based routing for this pick.
if (!runtime_.snapshot().featureEnabled(RuntimeZoneEnabled, 100)) {
return best_available_host_set_->healthyHosts();
}
if (LoadBalancerUtility::isGlobalPanic(localHostSet(), runtime_)) {
stats_.lb_local_cluster_not_ok_.inc();
// If the local Envoy instances are in global panic, do not do locality
// based routing.
return best_available_host_set_->healthyHosts();
}
return tryChooseLocalLocalityHosts();
}
HostConstSharedPtr RoundRobinLoadBalancer::chooseHost(LoadBalancerContext*) {
const std::vector<HostSharedPtr>& hosts_to_use = hostsToUse();
if (hosts_to_use.empty()) {
return nullptr;
}
return hosts_to_use[rr_index_++ % hosts_to_use.size()];
}
LeastRequestLoadBalancer::LeastRequestLoadBalancer(const PrioritySet& priority_set,
const PrioritySet* local_priority_set,
ClusterStats& stats, Runtime::Loader& runtime,
Runtime::RandomGenerator& random)
: LoadBalancerBase(priority_set, local_priority_set, stats, runtime, random) {
priority_set.addMemberUpdateCb([this](uint32_t, const std::vector<HostSharedPtr>&,
const std::vector<HostSharedPtr>& hosts_removed) -> void {
if (last_host_) {
for (const HostSharedPtr& host : hosts_removed) {
if (host == last_host_) {
hits_left_ = 0;
last_host_.reset();
break;
}
}
}
});
}
HostConstSharedPtr LeastRequestLoadBalancer::chooseHost(LoadBalancerContext*) {
bool is_weight_imbalanced = stats_.max_host_weight_.value() != 1;
bool is_weight_enabled = runtime_.snapshot().getInteger("upstream.weight_enabled", 1UL) != 0;
if (is_weight_imbalanced && hits_left_ > 0 && is_weight_enabled) {
--hits_left_;
return last_host_;
} else {
// To avoid hit stale last_host_ when all hosts become weight balanced.
hits_left_ = 0;
last_host_.reset();
}
const std::vector<HostSharedPtr>& hosts_to_use = hostsToUse();
if (hosts_to_use.empty()) {
return nullptr;
}
// Make weighed random if we have hosts with non 1 weights.
if (is_weight_imbalanced & is_weight_enabled) {
last_host_ = hosts_to_use[random_.random() % hosts_to_use.size()];
hits_left_ = last_host_->weight() - 1;
return last_host_;
} else {
HostSharedPtr host1 = hosts_to_use[random_.random() % hosts_to_use.size()];
HostSharedPtr host2 = hosts_to_use[random_.random() % hosts_to_use.size()];
if (host1->stats().rq_active_.value() < host2->stats().rq_active_.value()) {
return host1;
} else {
return host2;
}
}
}
HostConstSharedPtr RandomLoadBalancer::chooseHost(LoadBalancerContext*) {
const std::vector<HostSharedPtr>& hosts_to_use = hostsToUse();
if (hosts_to_use.empty()) {
return nullptr;
}
return hosts_to_use[random_.random() % hosts_to_use.size()];
}
} // namespace Upstream
} // namespace Envoy
| 40.968338 | 99 | 0.724351 | Sodman |
329eae5447f0cd48d1e279aab3660dbbae09d470 | 1,092 | cpp | C++ | src/CubeSystem/CubeManagerInputs.cpp | frc2081/2018-RobotCode | 6eec5af9b42df4bbd9f43ae6bd0cedc8fa7e0019 | [
"MIT"
] | null | null | null | src/CubeSystem/CubeManagerInputs.cpp | frc2081/2018-RobotCode | 6eec5af9b42df4bbd9f43ae6bd0cedc8fa7e0019 | [
"MIT"
] | 5 | 2018-01-18T03:25:07.000Z | 2018-03-16T13:27:53.000Z | src/CubeSystem/CubeManagerInputs.cpp | frc2081/2018-RobotCode | 6eec5af9b42df4bbd9f43ae6bd0cedc8fa7e0019 | [
"MIT"
] | null | null | null | /*
* CubeManagerInputs.cpp
*
* Created on: Feb 2, 2018
* Author: wentzdr
*/
#include <CubeSystem/CubeManagerInputs.h>
CubeManagerInputs::CubeManagerInputs() {
intakeCubeSensor = CubeSensor::NO_CUBE_PRESENT;
shooterCubeSensor = CubeSensor::NO_CUBE_PRESENT;
shooterangleactualvalue = 0;
armHomeSensor = false;
}
CubeManagerInputs::~CubeManagerInputs() {
}
CubeManagerInputs::CubeSensor CubeManagerInputs::getIntakeCubeSensor() {
return intakeCubeSensor;
}
CubeManagerInputs::CubeSensor CubeManagerInputs::getShooterCubeSensor() {
return shooterCubeSensor;
}
double CubeManagerInputs::getShooterAngleActualValue() {
return shooterangleactualvalue;
}
void CubeManagerInputs::updateInputs(IO *Inputs){
if(Inputs->intakecubesensor->Get()) intakeCubeSensor = CubeSensor::NO_CUBE_PRESENT;
else intakeCubeSensor = CubeSensor::CUBE_PRESENT;
if(Inputs->cubechambersensor->Get()) shooterCubeSensor = CubeSensor::NO_CUBE_PRESENT;
else shooterCubeSensor = CubeSensor::CUBE_PRESENT;
armHomeSensor = Inputs->armhomeswitch->Get();
}
| 25.395349 | 87 | 0.757326 | frc2081 |
32a0c7754769a1c3f4cc12714467089ebc1be583 | 4,237 | cpp | C++ | Alien Engine/Alien Engine/ModuleAudio.cpp | OverPowered-Team/Alien-GameEngine | 713a8846a95fdf253d0869bdcad4ecd006b2e166 | [
"MIT"
] | 7 | 2020-02-20T15:11:11.000Z | 2020-05-19T00:29:04.000Z | Alien Engine/Alien Engine/ModuleAudio.cpp | OverPowered-Team/Alien-GameEngine | 713a8846a95fdf253d0869bdcad4ecd006b2e166 | [
"MIT"
] | 125 | 2020-02-29T17:17:31.000Z | 2020-05-06T19:50:01.000Z | Alien Engine/Alien Engine/ModuleAudio.cpp | OverPowered-Team/Alien-GameEngine | 713a8846a95fdf253d0869bdcad4ecd006b2e166 | [
"MIT"
] | 1 | 2020-05-19T00:29:06.000Z | 2020-05-19T00:29:06.000Z | #include "Application.h"
#include "ModuleAudio.h"
#include "ComponentAudioEmitter.h"
#include "Event.h"
#include "mmgr/mmgr.h"
#include "Optick/include/optick.h"
ModuleAudio::ModuleAudio(bool start_enabled) : Module(start_enabled)
{
name = "audio";
}
ModuleAudio::~ModuleAudio()
{}
bool ModuleAudio::Start()
{
// Init wwise and audio banks
bool ret = WwiseT::InitSoundEngine();
default_listener = CreateSoundEmitter("Listener");
SetListener(default_listener);
for (auto i = banks.begin(); i != banks.end(); i++) {
if (!(*i)->loaded) {
WwiseT::LoadBank((std::to_string((*i)->id) + ".bnk").c_str());
(*i)->loaded = true;
}
}
return ret;
}
void ModuleAudio::LoadBanksInfo()
{
auto j = App->LoadJSONFile("Assets/AudioBanks/SoundbanksInfo.json");
auto bank_arr = j->GetArray("SoundBanksInfo.SoundBanks");
bank_arr->GetFirstNode();
for (uint i = 0; i < bank_arr->GetArraySize(); ++i, bank_arr->GetAnotherNode()) {
if (strcmp(bank_arr->GetString("ShortName"), "Init") != 0) {
Bank* b = new Bank();
b->id = std::stoull(bank_arr->GetString("Id"));
b->name = bank_arr->GetString("ShortName");
auto events = bank_arr->GetArray("IncludedEvents");
events->GetFirstNode();
for (uint e = 0; e < events->GetArraySize(); ++e, events->GetAnotherNode()) {
b->events[std::stoull(events->GetString("Id"))] = events->GetString("Name");
}
auto aud = bank_arr->GetArray("IncludedMemoryFiles");
for (uint a = 0; a < aud->GetArraySize(); ++a) {
b->audios[std::stoull(aud->GetString("Id"))] = aud->GetString("ShortName");
}
banks.push_back(b);
}
}
}
update_status ModuleAudio::Update(float dt)
{
OPTICK_EVENT();
return UPDATE_CONTINUE;
}
update_status ModuleAudio::PostUpdate(float dt)
{
OPTICK_EVENT();
if (listener != nullptr)
WwiseT::ProcessAudio();
return UPDATE_CONTINUE;
}
bool ModuleAudio::CleanUp()
{
OPTICK_EVENT();
for (auto i = emitters.begin(); i != emitters.end(); i++)
{
if((*i))
delete* i;
}
emitters.clear();
WwiseT::StopAllEvents();
UnloadAllBanksFromWwise();
for (auto b = banks.begin(); b != banks.end(); b++)
{
if ((*b))
delete* b;
}
banks.clear();
delete default_listener;
default_listener = nullptr;
return WwiseT::CloseSoundEngine();
}
bool ModuleAudio::UnloadAllBanksFromWwise()
{
OPTICK_EVENT();
for (auto it = banks.begin(); it != banks.end(); it++)
{
if ((*it))
{
if ((*it)->loaded) {
WwiseT::UnLoadBank(std::to_string((*it)->id).c_str());
(*it)->loaded = false;
}
}
}
return true;
}
void ModuleAudio::AddBank(Bank* bk)
{
banks.push_back(bk);
}
WwiseT::AudioSource * ModuleAudio::CreateSoundEmitter(const char * name)
{
return WwiseT::CreateAudSource(name);
}
const std::vector<Bank*> ModuleAudio::GetBanks() const
{
return banks;
}
const Bank* ModuleAudio::GetBankByName(const char* name) const
{
Bank* bk = nullptr;
for (int i = 0; i < banks.size(); ++i)
{
if (App->StringCmp(name, App->audio->GetBanks()[i]->name.c_str()))
bk = App->audio->GetBanks()[i];
}
return bk;
}
Bank* ModuleAudio::GetBankByID(const u64& id) const
{
for (auto i = banks.begin(); i != banks.end(); ++i)
{
if ((*i)->id == id)
return *i;
}
return nullptr;
}
const char* ModuleAudio::GetEventNameByID(const u64& id) const
{
for (auto i = banks.begin(); i != banks.end(); ++i)
{
for (auto j = (*i)->events.begin(); j != (*i)->events.end(); ++j)
{
if ((*j).first == id)
return (*j).second.c_str();
}
}
return "";
}
void ModuleAudio::HandleEvent(EventType eventType)
{
switch (eventType)
{
case EventType::ON_PAUSE:
//Pause();
break;
case EventType::ON_STOP:
Stop();
break;
}
}
void ModuleAudio::Play()
{
OPTICK_EVENT();
for (auto iterator = emitters.begin(); iterator != App->audio->emitters.end(); ++iterator)
{
(*iterator)->StartSound();
}
is_playing = true;
}
void ModuleAudio::Stop()
{
WwiseT::StopAllEvents();
}
void ModuleAudio::Pause() const
{
WwiseT::PauseAll();
}
void ModuleAudio::Resume() const
{
WwiseT::ResumeAll();
}
void ModuleAudio::SetListener(WwiseT::AudioSource* new_listener)
{
if (new_listener == nullptr)
listener = default_listener;
else
listener = new_listener;
WwiseT::SetDefaultListener(new_listener->GetID());
}
| 19.892019 | 91 | 0.648808 | OverPowered-Team |
32a4a11ad05be2aba57383316057873d2484b831 | 1,974 | cpp | C++ | src/filter/filterset.cpp | ikitayama/cobi | e9bc4a5675ead1874ad9ffa953de8edb3a763479 | [
"BSD-3-Clause"
] | null | null | null | src/filter/filterset.cpp | ikitayama/cobi | e9bc4a5675ead1874ad9ffa953de8edb3a763479 | [
"BSD-3-Clause"
] | null | null | null | src/filter/filterset.cpp | ikitayama/cobi | e9bc4a5675ead1874ad9ffa953de8edb3a763479 | [
"BSD-3-Clause"
] | 1 | 2018-12-14T02:45:41.000Z | 2018-12-14T02:45:41.000Z | /*****************************************************************************
** Cobi http://www.scalasca.org/ **
*****************************************************************************
** Copyright (c) 2009-2010 **
** Forschungszentrum Juelich, Juelich Supercomputing Centre **
** **
** See the file COPYRIGHT in the base directory for details **
*****************************************************************************/
/**
* @file filterset.cpp
* @author Jan Mussler
* @brief Implementation of filterset class
*
* a filterset is a set of filters, represtens the filters tag containing
* all filters defined in one filter specification
*/
#include "filters.h"
using namespace gi::filter;
FilterSet::FilterSet() {
}
FilterSet::~FilterSet() {
for (mapStringIFilter::iterator i = filters.begin();
i != filters.end();
i++) {
delete (*i).second;
}
filters.clear();
}
void FilterSet::addFilter(std::string aName, IFilter* aFilter) {
filters[aName] = aFilter;
}
set<string> FilterSet::getFilterNames() {
set<string> names;
for (mapStringIFilter::iterator i = filters.begin();
i != filters.end();
i++) {
names.insert(i->first);
}
return names;
}
IFilter* FilterSet::getFilterByName(std::string aName) {
if (filters.find(aName) != filters.end()) {
return filters[aName];
}
throw ex::ReferencingUndefinedFilter();
}
vector<IFilter*> FilterSet::getInstrumentingFilters() {
vector<IFilter*> result;
for (mapStringIFilter::iterator i = filters.begin();
i != filters.end();
i++) {
if ((*i).second->isInstrumenting()) {
result.push_back((*i).second);
}
}
return result;
}
| 28.608696 | 79 | 0.479737 | ikitayama |
32ae93de04e4ee99e86e2c39c1712e06c1835e29 | 10,433 | cpp | C++ | vendor/android-tools/init/util.cpp | dylanh333/android-unmkbootimg | 7c30a58b5bc3d208fbbbbc713717e2aae98df699 | [
"MIT"
] | 3 | 2018-04-01T18:35:29.000Z | 2020-12-18T21:09:53.000Z | vendor/android-tools/init/util.cpp | dylanh333/android-unmkbootimg | 7c30a58b5bc3d208fbbbbc713717e2aae98df699 | [
"MIT"
] | 2 | 2017-04-24T12:29:05.000Z | 2017-05-09T12:27:10.000Z | vendor/android-tools/init/util.cpp | dylanh333/android-unmkbootimg | 7c30a58b5bc3d208fbbbbc713717e2aae98df699 | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2008 The Android Open Source Project
*
* 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 "util.h"
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <pwd.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <time.h>
#include <unistd.h>
#include <thread>
#include <android-base/file.h>
#include <android-base/logging.h>
#include <android-base/properties.h>
#include <android-base/stringprintf.h>
#include <android-base/strings.h>
#include <android-base/unique_fd.h>
#include <cutils/android_reboot.h>
#include <cutils/sockets.h>
#include <selinux/android.h>
#include <selinux/label.h>
#include "init.h"
#include "reboot.h"
using android::base::boot_clock;
static unsigned int do_decode_uid(const char *s)
{
unsigned int v;
if (!s || *s == '\0')
return UINT_MAX;
if (isalpha(s[0])) {
struct passwd* pwd = getpwnam(s);
if (!pwd)
return UINT_MAX;
return pwd->pw_uid;
}
errno = 0;
v = (unsigned int) strtoul(s, 0, 0);
if (errno)
return UINT_MAX;
return v;
}
/*
* decode_uid - decodes and returns the given string, which can be either the
* numeric or name representation, into the integer uid or gid. Returns
* UINT_MAX on error.
*/
unsigned int decode_uid(const char *s) {
unsigned int v = do_decode_uid(s);
if (v == UINT_MAX) {
LOG(ERROR) << "decode_uid: Unable to find UID for '" << s << "'; returning UINT_MAX";
}
return v;
}
/*
* create_socket - creates a Unix domain socket in ANDROID_SOCKET_DIR
* ("/dev/socket") as dictated in init.rc. This socket is inherited by the
* daemon. We communicate the file descriptor's value via the environment
* variable ANDROID_SOCKET_ENV_PREFIX<name> ("ANDROID_SOCKET_foo").
*/
int create_socket(const char *name, int type, mode_t perm, uid_t uid,
gid_t gid, const char *socketcon)
{
if (socketcon) {
if (setsockcreatecon(socketcon) == -1) {
PLOG(ERROR) << "setsockcreatecon(\"" << socketcon << "\") failed";
return -1;
}
}
android::base::unique_fd fd(socket(PF_UNIX, type, 0));
if (fd < 0) {
PLOG(ERROR) << "Failed to open socket '" << name << "'";
return -1;
}
if (socketcon) setsockcreatecon(NULL);
struct sockaddr_un addr;
memset(&addr, 0 , sizeof(addr));
addr.sun_family = AF_UNIX;
snprintf(addr.sun_path, sizeof(addr.sun_path), ANDROID_SOCKET_DIR"/%s",
name);
if ((unlink(addr.sun_path) != 0) && (errno != ENOENT)) {
PLOG(ERROR) << "Failed to unlink old socket '" << name << "'";
return -1;
}
char *filecon = NULL;
if (sehandle) {
if (selabel_lookup(sehandle, &filecon, addr.sun_path, S_IFSOCK) == 0) {
setfscreatecon(filecon);
}
}
int ret = bind(fd, (struct sockaddr *) &addr, sizeof (addr));
int savederrno = errno;
setfscreatecon(NULL);
freecon(filecon);
if (ret) {
errno = savederrno;
PLOG(ERROR) << "Failed to bind socket '" << name << "'";
goto out_unlink;
}
if (lchown(addr.sun_path, uid, gid)) {
PLOG(ERROR) << "Failed to lchown socket '" << addr.sun_path << "'";
goto out_unlink;
}
if (fchmodat(AT_FDCWD, addr.sun_path, perm, AT_SYMLINK_NOFOLLOW)) {
PLOG(ERROR) << "Failed to fchmodat socket '" << addr.sun_path << "'";
goto out_unlink;
}
LOG(INFO) << "Created socket '" << addr.sun_path << "'"
<< ", mode " << std::oct << perm << std::dec
<< ", user " << uid
<< ", group " << gid;
return fd.release();
out_unlink:
unlink(addr.sun_path);
return -1;
}
bool read_file(const std::string& path, std::string* content) {
content->clear();
android::base::unique_fd fd(
TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC)));
if (fd == -1) {
return false;
}
// For security reasons, disallow world-writable
// or group-writable files.
struct stat sb;
if (fstat(fd, &sb) == -1) {
PLOG(ERROR) << "fstat failed for '" << path << "'";
return false;
}
if ((sb.st_mode & (S_IWGRP | S_IWOTH)) != 0) {
LOG(ERROR) << "skipping insecure file '" << path << "'";
return false;
}
return android::base::ReadFdToString(fd, content);
}
bool write_file(const std::string& path, const std::string& content) {
android::base::unique_fd fd(TEMP_FAILURE_RETRY(
open(path.c_str(), O_WRONLY | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0600)));
if (fd == -1) {
PLOG(ERROR) << "write_file: Unable to open '" << path << "'";
return false;
}
bool success = android::base::WriteStringToFd(content, fd);
if (!success) {
PLOG(ERROR) << "write_file: Unable to write to '" << path << "'";
}
return success;
}
int mkdir_recursive(const std::string& path, mode_t mode) {
std::string::size_type slash = 0;
while ((slash = path.find('/', slash + 1)) != std::string::npos) {
auto directory = path.substr(0, slash);
struct stat info;
if (stat(directory.c_str(), &info) != 0) {
auto ret = make_dir(directory.c_str(), mode);
if (ret && errno != EEXIST) return ret;
}
}
auto ret = make_dir(path.c_str(), mode);
if (ret && errno != EEXIST) return ret;
return 0;
}
int wait_for_file(const char* filename, std::chrono::nanoseconds timeout) {
boot_clock::time_point timeout_time = boot_clock::now() + timeout;
while (boot_clock::now() < timeout_time) {
struct stat sb;
if (stat(filename, &sb) != -1) return 0;
std::this_thread::sleep_for(10ms);
}
return -1;
}
void import_kernel_cmdline(bool in_qemu,
const std::function<void(const std::string&, const std::string&, bool)>& fn) {
std::string cmdline;
android::base::ReadFileToString("/proc/cmdline", &cmdline);
for (const auto& entry : android::base::Split(android::base::Trim(cmdline), " ")) {
std::vector<std::string> pieces = android::base::Split(entry, "=");
if (pieces.size() == 2) {
fn(pieces[0], pieces[1], in_qemu);
}
}
}
int make_dir(const char *path, mode_t mode)
{
int rc;
char *secontext = NULL;
if (sehandle) {
selabel_lookup(sehandle, &secontext, path, mode);
setfscreatecon(secontext);
}
rc = mkdir(path, mode);
if (secontext) {
int save_errno = errno;
freecon(secontext);
setfscreatecon(NULL);
errno = save_errno;
}
return rc;
}
int restorecon(const char* pathname, int flags)
{
return selinux_android_restorecon(pathname, flags);
}
/*
* Writes hex_len hex characters (1/2 byte) to hex from bytes.
*/
std::string bytes_to_hex(const uint8_t* bytes, size_t bytes_len) {
std::string hex("0x");
for (size_t i = 0; i < bytes_len; i++)
android::base::StringAppendF(&hex, "%02x", bytes[i]);
return hex;
}
/*
* Returns true is pathname is a directory
*/
bool is_dir(const char* pathname) {
struct stat info;
if (stat(pathname, &info) == -1) {
return false;
}
return S_ISDIR(info.st_mode);
}
bool expand_props(const std::string& src, std::string* dst) {
const char* src_ptr = src.c_str();
if (!dst) {
return false;
}
/* - variables can either be $x.y or ${x.y}, in case they are only part
* of the string.
* - will accept $$ as a literal $.
* - no nested property expansion, i.e. ${foo.${bar}} is not supported,
* bad things will happen
* - ${x.y:-default} will return default value if property empty.
*/
while (*src_ptr) {
const char* c;
c = strchr(src_ptr, '$');
if (!c) {
dst->append(src_ptr);
return true;
}
dst->append(src_ptr, c);
c++;
if (*c == '$') {
dst->push_back(*(c++));
src_ptr = c;
continue;
} else if (*c == '\0') {
return true;
}
std::string prop_name;
std::string def_val;
if (*c == '{') {
c++;
const char* end = strchr(c, '}');
if (!end) {
// failed to find closing brace, abort.
LOG(ERROR) << "unexpected end of string in '" << src << "', looking for }";
return false;
}
prop_name = std::string(c, end);
c = end + 1;
size_t def = prop_name.find(":-");
if (def < prop_name.size()) {
def_val = prop_name.substr(def + 2);
prop_name = prop_name.substr(0, def);
}
} else {
prop_name = c;
LOG(ERROR) << "using deprecated syntax for specifying property '" << c << "', use ${name} instead";
c += prop_name.size();
}
if (prop_name.empty()) {
LOG(ERROR) << "invalid zero-length property name in '" << src << "'";
return false;
}
std::string prop_val = android::base::GetProperty(prop_name, "");
if (prop_val.empty()) {
if (def_val.empty()) {
LOG(ERROR) << "property '" << prop_name << "' doesn't exist while expanding '" << src << "'";
return false;
}
prop_val = def_val;
}
dst->append(prop_val);
src_ptr = c;
}
return true;
}
void panic() {
LOG(ERROR) << "panic: rebooting to bootloader";
DoReboot(ANDROID_RB_RESTART2, "reboot", "bootloader", false);
}
std::ostream& operator<<(std::ostream& os, const Timer& t) {
os << t.duration_s() << " seconds";
return os;
}
| 28.045699 | 111 | 0.571456 | dylanh333 |
32af3355a38b4aaf5e250e11dc330039addb0cf9 | 2,095 | cpp | C++ | powermode.cpp | eddiejames/openpower-occ-control-1 | bc2f68b9a5cabbdedd988ac14e010d651c685601 | [
"Apache-2.0"
] | 1 | 2021-08-10T21:50:06.000Z | 2021-08-10T21:50:06.000Z | powermode.cpp | eddiejames/openpower-occ-control-1 | bc2f68b9a5cabbdedd988ac14e010d651c685601 | [
"Apache-2.0"
] | 1 | 2021-10-19T19:47:53.000Z | 2021-10-19T19:47:53.000Z | powermode.cpp | eddiejames/openpower-occ-control-1 | bc2f68b9a5cabbdedd988ac14e010d651c685601 | [
"Apache-2.0"
] | 2 | 2019-07-16T16:13:01.000Z | 2021-10-20T21:41:02.000Z | #include <fmt/core.h>
#include <phosphor-logging/log.hpp>
#include <powermode.hpp>
#include <xyz/openbmc_project/Control/Power/Mode/server.hpp>
#include <cassert>
#include <regex>
namespace open_power
{
namespace occ
{
namespace powermode
{
using namespace phosphor::logging;
using Mode = sdbusplus::xyz::openbmc_project::Control::Power::server::Mode;
void PowerMode::modeChanged(sdbusplus::message::message& msg)
{
if (!occStatus.occActive())
{
// Nothing to do
return;
}
SysPwrMode pmode = SysPwrMode::NO_CHANGE;
std::map<std::string, std::variant<std::string>> properties{};
std::string interface;
std::string propVal;
msg.read(interface, properties);
const auto modeEntry = properties.find(POWER_MODE_PROP);
if (modeEntry != properties.end())
{
auto modeEntryValue = modeEntry->second;
propVal = std::get<std::string>(modeEntryValue);
pmode = convertStringToMode(propVal);
if (pmode != SysPwrMode::NO_CHANGE)
{
log<level::INFO>(
fmt::format("Power Mode Change Requested: {}", propVal)
.c_str());
// Trigger mode change to OCC
occStatus.sendModeChange();
}
}
return;
}
// Convert PowerMode string to OCC SysPwrMode
SysPwrMode convertStringToMode(const std::string& i_modeString)
{
SysPwrMode pmode = SysPwrMode::NO_CHANGE;
Mode::PowerMode mode = Mode::convertPowerModeFromString(i_modeString);
if (mode == Mode::PowerMode::MaximumPerformance)
{
pmode = SysPwrMode::MAX_PERF;
}
else if (mode == Mode::PowerMode::PowerSaving)
{
pmode = SysPwrMode::POWER_SAVING;
}
else if (mode == Mode::PowerMode::Static)
{
pmode = SysPwrMode::DISABLE;
}
else
{
log<level::ERR>(
fmt::format("convertStringToMode: Invalid Power Mode specified: {}",
i_modeString)
.c_str());
}
return pmode;
}
} // namespace powermode
} // namespace occ
} // namespace open_power
| 23.539326 | 80 | 0.623389 | eddiejames |
32b0095056c444d81f3846253150025d0ec460d9 | 1,673 | hpp | C++ | util/logging.hpp | farlies/rsked | cd2004bed454578f4d2ac25996dc1ced98d4fa58 | [
"Apache-2.0"
] | null | null | null | util/logging.hpp | farlies/rsked | cd2004bed454578f4d2ac25996dc1ced98d4fa58 | [
"Apache-2.0"
] | null | null | null | util/logging.hpp | farlies/rsked | cd2004bed454578f4d2ac25996dc1ced98d4fa58 | [
"Apache-2.0"
] | 1 | 2020-10-04T22:14:55.000Z | 2020-10-04T22:14:55.000Z | #pragma once
/* Logging functions and macros used by all rsked applications.
*/
/* Part of the rsked package.
*
* Copyright 2020 Steven A. Harp
*
* 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.
*
*/
/// Load this before any other boost logging headers
/// must define this to use the shared lib
#define BOOST_LOG_DYN_LINK 1
#include <boost/log/trivial.hpp>
#include <boost/log/sources/severity_logger.hpp>
namespace lt = boost::log::trivial;
using rsked_logger_t=boost::log::sources::severity_logger<lt::severity_level>;
extern rsked_logger_t Lgr; // global log source
#define LOG_DEBUG(_logger) BOOST_LOG_SEV(_logger,lt::debug)
#define LOG_INFO(_logger) BOOST_LOG_SEV(_logger,lt::info)
#define LOG_WARNING(_logger) BOOST_LOG_SEV(_logger,lt::warning)
#define LOG_ERROR(_logger) BOOST_LOG_SEV(_logger,lt::error)
/* Bit flags to pass init_logging to enable FILE and/or CONSOLE backends
* and to enable debug messages.
*/
#define LF_FILE 1
#define LF_CONSOLE 2
#define LF_DEBUG 4
void init_logging(const char* /*appname*/, const char* /* "rsked_%5N.log" */,
int flags=LF_FILE);
void finish_logging();
| 30.981481 | 78 | 0.73162 | farlies |
32b0d7ad2c5ae1910e4a9e345a6279e42bae61d6 | 669 | cpp | C++ | test/forty_two.cpp | vinniefalco/library-template | 8fa8395d917163c29b9ecc21145ba78028b724da | [
"BSL-1.0"
] | 6 | 2020-03-02T22:40:17.000Z | 2020-03-09T20:49:24.000Z | test/forty_two.cpp | vinniefalco/library-template | 8fa8395d917163c29b9ecc21145ba78028b724da | [
"BSL-1.0"
] | 1 | 2020-12-01T20:01:36.000Z | 2020-12-01T20:01:36.000Z | test/forty_two.cpp | vinniefalco/library-template | 8fa8395d917163c29b9ecc21145ba78028b724da | [
"BSL-1.0"
] | 1 | 2020-11-30T22:29:51.000Z | 2020-11-30T22:29:51.000Z | //
// Copyright (c) 2020 Vinnie Falco (vinnie.falco@gmail.com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/vinniefalco/library_template
//
// Test that header file is self-contained.
#include <boost/library_template/forty_two.hpp>
#include "test_suite.hpp"
namespace boost {
namespace library_template {
class forty_two_test
{
public:
void
run()
{
BOOST_TEST(forty_two() == 42);
}
};
TEST_SUITE(forty_two_test, "boost.library_template.forty_two");
} // library_template
} // boost
| 20.90625 | 79 | 0.718984 | vinniefalco |
32b3ed3d609f2e874e79a1eb38b24d97ab1952fe | 839 | cpp | C++ | C/common/string_utils.cpp | ashish-ScaleDB/FogLAMP | fd52bc53f6a10752acdb1c549279dcaa406893a5 | [
"Apache-2.0"
] | 1 | 2020-09-10T11:34:04.000Z | 2020-09-10T11:34:04.000Z | C/common/string_utils.cpp | YashTatkondawar/FogLAMP | 6a3a6d45db9c9f0058110252202826e9859ccfa1 | [
"Apache-2.0"
] | 1 | 2017-09-06T14:05:21.000Z | 2017-09-06T14:05:21.000Z | C/common/string_utils.cpp | YashTatkondawar/FogLAMP | 6a3a6d45db9c9f0058110252202826e9859ccfa1 | [
"Apache-2.0"
] | null | null | null | /*
* FogLAMP utilities functions for handling JSON document
*
* Copyright (c) 2018 Dianomic Systems
*
* Released under the Apache 2.0 Licence
*
* Author: Stefano Simonelli
*/
#include <iostream>
#include <string>
#include "string_utils.h"
using namespace std;
/**
* Search and replace a string
*
* @param out StringToManage string in which apply the search and replacement
* @param StringToSearch string to search and replace
* @param StringToReplace substitution string
*
*/
void StringReplace(std::string& StringToManage,
const std::string& StringToSearch,
const std::string& StringReplacement)
{
if (StringToManage.find(StringToSearch) != string::npos)
{
StringToManage.replace(StringToManage.find(StringToSearch),
StringToSearch.length(),
StringReplacement);
}
}
| 22.675676 | 80 | 0.709178 | ashish-ScaleDB |
32be67a5dc1a4a37e175de639614a6c71929c546 | 2,995 | cpp | C++ | Algorithms/0576.OutOfBoundaryPaths/solution.cpp | stdstring/leetcode | 84e6bade7d6fc1a737eb6796cb4e2565440db5e3 | [
"MIT"
] | null | null | null | Algorithms/0576.OutOfBoundaryPaths/solution.cpp | stdstring/leetcode | 84e6bade7d6fc1a737eb6796cb4e2565440db5e3 | [
"MIT"
] | null | null | null | Algorithms/0576.OutOfBoundaryPaths/solution.cpp | stdstring/leetcode | 84e6bade7d6fc1a737eb6796cb4e2565440db5e3 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <vector>
#include "gtest/gtest.h"
namespace
{
class Solution
{
public:
int findPaths(int m, int n, int N, int i, int j) const
{
if (N == 0)
return 0;
size_t outPathsCount = 0;
const size_t storageSize = static_cast<size_t>(m) * n;
std::vector<size_t> current(storageSize, 0);
// first step
initStorage(m, n, i, j, current, outPathsCount);
if (N == 1)
return static_cast<int>(outPathsCount);
std::vector<size_t> next(storageSize, 0);
for (size_t step = 2; step <= static_cast<size_t>(N); ++step)
{
std::fill(next.begin(), next.end(), 0);
for (size_t index = 0; index < current.size(); ++index)
{
const size_t row = index / n;
const size_t column = index % n;
if (current[index] != 0)
processCell(m, n, row, column, current, next, outPathsCount);
}
std::swap(current, next);
}
return static_cast<int>(outPathsCount);
}
private:
constexpr static size_t ModValue = 1000000007;
void initStorage(size_t m, size_t n, size_t i, size_t j, std::vector<size_t> ¤t, size_t &outPathsCount) const
{
if (i > 0)
current[(i - 1) * n + j] = 1;
else
++outPathsCount;
if (i < (m - 1))
current[(i + 1) * n + j] = 1;
else
++outPathsCount;
if (j > 0)
current[i * n + (j - 1)] = 1;
else
++outPathsCount;
if (j < (n - 1))
current[i * n + (j + 1)] = 1;
else
++outPathsCount;
}
void processCell(size_t m, size_t n, size_t i, size_t j, std::vector<size_t> const ¤t, std::vector<size_t> &next, size_t&outPathsCount) const
{
const size_t currentPathsCount = current[i * n + j];
if (i > 0)
next[(i - 1) * n + j] = (next[(i - 1) * n + j] + currentPathsCount) % ModValue;
else
outPathsCount = (outPathsCount + currentPathsCount) % ModValue;
if (i < (m - 1))
next[(i + 1) * n + j] = (next[(i + 1) * n + j] + currentPathsCount) % ModValue;
else
outPathsCount = (outPathsCount + currentPathsCount) % ModValue;
if (j > 0)
next[i * n + (j - 1)] = (next[i * n + (j - 1)] + currentPathsCount) % ModValue;
else
outPathsCount = (outPathsCount + currentPathsCount) % ModValue;
if (j < (n - 1))
next[i * n + (j + 1)] = (next[i * n + (j + 1)] + currentPathsCount) % ModValue;
else
outPathsCount = (outPathsCount + currentPathsCount) % ModValue;
}
};
}
namespace OutOfBoundaryPathsTask
{
TEST(OutOfBoundaryPathsTaskTests, Examples)
{
const Solution solution;
ASSERT_EQ(6, solution.findPaths(2, 2, 2, 0, 0));
ASSERT_EQ(12, solution.findPaths(1, 3, 3, 0, 1));
}
} | 31.197917 | 151 | 0.52187 | stdstring |
32c39ab5131ad707f6a922aff6697cbd0ace3949 | 2,732 | cpp | C++ | PATA1017.cpp | Geeks-Z/PAT-Advanced-Level-Practice | 6b25d07ae602310215e46c951638b93080b382bf | [
"MIT"
] | null | null | null | PATA1017.cpp | Geeks-Z/PAT-Advanced-Level-Practice | 6b25d07ae602310215e46c951638b93080b382bf | [
"MIT"
] | null | null | null | PATA1017.cpp | Geeks-Z/PAT-Advanced-Level-Practice | 6b25d07ae602310215e46c951638b93080b382bf | [
"MIT"
] | null | null | null | /*
* @Descripttion:
* @version: 1.0
* @Author: Geeks_Z
* @Date: 2021-05-13 10:20:55
* @LastEditors: Geeks_Z
* @LastEditTime: 2021-05-30 21:33:19
*/
#include <cstdio>
#include <iostream>
#include <vector>
using namespace std;
const int MAXN = 501;
const int INF = 100010;
bool vis[MAXN] = {false};
//连接矩阵 起点到该点最短距离 点权 station数量 自行车数量 第二标尺最优值
int G[MAXN][MAXN], dis[MAXN], weight[MAXN], n, minNeed = INF, capacity, minBack = INF;
//最优路径 临时路径
vector<int> path[MAXN], tempPath, bestPath;
void dijkstra(int s)
{
fill(dis, dis + n + 1, INF);
dis[s] = 0;
for (int i = 0; i < n + 1; i++)
{
//找到最小的u
int u = -1, min = INF;
for (int j = 0; j < n + 1; j++)
{
if (vis[j] == false && dis[j] < min)
{
u = j;
min = dis[j];
}
}
if (u == -1)
{
return;
}
vis[u] = true;
for (int v = 0; v < n + 1; v++)
{
if (vis[v] == false && G[u][v] != INF)
{
if (dis[u] + G[u][v] < dis[v])
{
dis[v] = dis[u] + G[u][v];
path[v].clear();
path[v].push_back(u);
}
else if (dis[u] + G[u][v] == dis[v])
{
path[v].push_back(u);
}
}
}
}
}
/**
* @Descripttion: 输出路径
* @param {int} s 起点
* @param {int} v 当前访问的结点
* @return {*}
*/
void DFS(int v)
{
tempPath.push_back(v);
if (v == 0)
{
int need = 0, back = 0;
for (int i = tempPath.size() - 1; i >= 0; i--)
{
int id = tempPath[i];
if (weight[id] > 0)
{
back += weight[id];
}
else
{
//携带的数量能够满足当前station的需求
if (back > (0 - weight[id]))
{
back += weight[id];
}
else
{
//出去目前携带的 还应该携带的
need += ((0 - weight[id]) - back);
back = 0;
}
}
}
if (need < minNeed)
{
minNeed = need;
minBack = back;
bestPath = tempPath;
}
else if (need == minNeed && back < minBack)
{
minBack = back;
bestPath = tempPath;
}
tempPath.pop_back();
return;
}
for (int i = 0; i < path[v].size(); i++)
{
DFS(path[v][i]);
}
tempPath.pop_back();
}
int main()
{
// freopen("input.txt", "r", stdin);
fill(G[0], G[0] + MAXN * MAXN, INF);
int sp, m;
cin >> capacity >> n >> sp >> m;
for (int i = 1; i <= n; i++)
{
scanf("%d", &weight[i]);
weight[i] = weight[i] - capacity / 2;
}
int s1, s2, time;
for (int i = 0; i < m; i++)
{
cin >> s1 >> s2 >> time;
G[s1][s2] = G[s2][s1] = time;
}
dijkstra(0);
DFS(sp);
printf("%d 0", minNeed);
for (int i = bestPath.size() - 2; i >= 0; i--)
printf("->%d", bestPath[i]);
printf(" %d", minBack);
return 0;
} | 18.841379 | 86 | 0.453148 | Geeks-Z |
32c49cffb08f92d04c4f2794fcc658344e531edf | 695 | hpp | C++ | NWNXLib/API/Linux/API/CExoLinkedListTemplatedCERFRes.hpp | acaos/nwnxee-unified | 0e4c318ede64028c1825319f39c012e168e0482c | [
"MIT"
] | 1 | 2019-06-04T04:30:24.000Z | 2019-06-04T04:30:24.000Z | NWNXLib/API/Linux/API/CExoLinkedListTemplatedCERFRes.hpp | presscad/nwnee | 0f36b281524e0b7e9796bcf30f924792bf9b8a38 | [
"MIT"
] | null | null | null | NWNXLib/API/Linux/API/CExoLinkedListTemplatedCERFRes.hpp | presscad/nwnee | 0f36b281524e0b7e9796bcf30f924792bf9b8a38 | [
"MIT"
] | 1 | 2019-10-20T07:54:45.000Z | 2019-10-20T07:54:45.000Z | #pragma once
#include <cstdint>
namespace NWNXLib {
namespace API {
// Forward class declarations (defined in the source file)
struct CExoLinkedListInternal;
struct CExoLinkedListTemplatedCERFRes
{
CExoLinkedListInternal* m_pcExoLinkedListInternal;
// The below are auto generated stubs.
CExoLinkedListTemplatedCERFRes() = default;
CExoLinkedListTemplatedCERFRes(const CExoLinkedListTemplatedCERFRes&) = default;
CExoLinkedListTemplatedCERFRes& operator=(const CExoLinkedListTemplatedCERFRes&) = default;
~CExoLinkedListTemplatedCERFRes();
};
void CExoLinkedListTemplatedCERFRes__CExoLinkedListTemplatedCERFResDtor(CExoLinkedListTemplatedCERFRes* thisPtr);
}
}
| 23.965517 | 113 | 0.811511 | acaos |
32c781b3614915d5dd36d907d45946d4e230d68e | 2,403 | cpp | C++ | NULL Engine/Source/R_Texture.cpp | BarcinoLechiguino/NULL_Engine | f2abecb44bee45b7cbf2d5b53609d79d38ecc5a3 | [
"MIT"
] | 4 | 2020-11-29T12:28:31.000Z | 2021-06-08T17:32:56.000Z | NULL Engine/Source/R_Texture.cpp | BarcinoLechiguino/NULL_Engine | f2abecb44bee45b7cbf2d5b53609d79d38ecc5a3 | [
"MIT"
] | null | null | null | NULL Engine/Source/R_Texture.cpp | BarcinoLechiguino/NULL_Engine | f2abecb44bee45b7cbf2d5b53609d79d38ecc5a3 | [
"MIT"
] | 4 | 2020-11-01T17:06:32.000Z | 2021-01-09T16:58:50.000Z | #include "OpenGL.h"
#include "VariableTypedefs.h"
#include "JSONParser.h"
#include "R_Texture.h"
R_Texture::R_Texture() : Resource(RESOURCE_TYPE::TEXTURE)
{
}
R_Texture::~R_Texture()
{
}
bool R_Texture::CleanUp()
{
bool ret = true;
glDeleteTextures(1, (GLuint*)&tex_data.id);
return ret;
}
bool R_Texture::SaveMeta(ParsonNode& meta_root) const
{
bool ret = true;
ParsonArray contained_array = meta_root.SetArray("ContainedResources");
ParsonNode settings = meta_root.SetNode("ImportSettings");
texture_settings.Save(settings);
return ret;
}
bool R_Texture::LoadMeta(const ParsonNode& meta_root)
{
bool ret = true;
return ret;
}
// --- R_TEXTURE METHODS ---
Texture R_Texture::GetTextureData() const
{
return tex_data;
}
void R_Texture::SetTextureData(uint id, uint width, uint height, uint depth, uint bpp, uint bytes, TEXTURE_FORMAT format, bool compressed)
{
tex_data.id = id;
tex_data.width = width;
tex_data.height = height;
tex_data.depth = depth;
tex_data.bpp = bpp;
tex_data.bytes = bytes;
tex_data.format = format;
tex_data.compressed = compressed;
}
uint R_Texture::GetTextureID() const
{
return tex_data.id;
}
uint R_Texture::GetTextureWidth() const
{
return tex_data.width;
}
uint R_Texture::GetTextureHeight() const
{
return tex_data.height;
}
uint R_Texture::GetTextureDepth() const
{
return tex_data.depth;
}
uint R_Texture::GetTextureBpp() const
{
return tex_data.bpp;
}
uint R_Texture::GetTextureBytes() const
{
return tex_data.bytes;
}
TEXTURE_FORMAT R_Texture::GetTextureFormat() const
{
return tex_data.format;
}
bool R_Texture::TextureIsCompressed() const
{
return tex_data.compressed;
}
const char* R_Texture::GetTextureFormatString() const
{
switch (tex_data.format)
{
case TEXTURE_FORMAT::UNKNOWN: { return "UNKNOWN"; } break;
case TEXTURE_FORMAT::COLOUR_INDEX: { return "COLOUR_INDEX"; } break;
case TEXTURE_FORMAT::RGB: { return "RGB"; } break;
case TEXTURE_FORMAT::RGBA: { return "RGBA"; } break;
case TEXTURE_FORMAT::BGR: { return "BGR"; } break;
case TEXTURE_FORMAT::BGRA: { return "BGRA"; } break;
case TEXTURE_FORMAT::LUMINANCE: { return "LUMINANCE"; } break;
}
return "NONE";
}
// --- TEXTURE STRUCT METHODS ---
Texture::Texture()
{
id = 0;
width = 0;
height = 0;
depth = 0;
bpp = 0;
bytes = 0;
format = TEXTURE_FORMAT::UNKNOWN;
compressed = true;
} | 17.8 | 138 | 0.707033 | BarcinoLechiguino |
32cd67bff30596424078cb678afc661879634df1 | 61 | hpp | C++ | src/boost_metaparse_error_unexpected_end_of_input.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 10 | 2018-03-17T00:58:42.000Z | 2021-07-06T02:48:49.000Z | src/boost_metaparse_error_unexpected_end_of_input.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 2 | 2021-03-26T15:17:35.000Z | 2021-05-20T23:55:08.000Z | src/boost_metaparse_error_unexpected_end_of_input.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 4 | 2019-05-28T21:06:37.000Z | 2021-07-06T03:06:52.000Z | #include <boost/metaparse/error/unexpected_end_of_input.hpp>
| 30.5 | 60 | 0.852459 | miathedev |
32cdd136909d5c3cc58f8a2df095b70277a36735 | 478 | cc | C++ | Code/0152-maximum-product-subarray.cc | SMartQi/Leetcode | 9e35c65a48ba1ecd5436bbe07dd65f993588766b | [
"MIT"
] | 2 | 2019-12-06T14:08:57.000Z | 2020-01-15T15:25:32.000Z | Code/0152-maximum-product-subarray.cc | SMartQi/Leetcode | 9e35c65a48ba1ecd5436bbe07dd65f993588766b | [
"MIT"
] | 1 | 2020-01-15T16:29:16.000Z | 2020-01-26T12:40:13.000Z | Code/0152-maximum-product-subarray.cc | SMartQi/Leetcode | 9e35c65a48ba1ecd5436bbe07dd65f993588766b | [
"MIT"
] | null | null | null | class Solution {
public:
int maxProduct(vector<int>& nums) {
if (nums.size() == 0) {
return 0;
}
int result = nums[0], pos = nums[0], neg = nums[0];
for (int i = 1; i < nums.size(); i++) {
int tmp = pos;
pos = max(nums[i], max(nums[i] * pos, nums[i] * neg));
neg = min(nums[i], min(nums[i] * tmp, nums[i] * neg));
result = max(result, pos);
}
return result;
}
}; | 29.875 | 66 | 0.439331 | SMartQi |
32ce8149e468185aaa18447e4a322920f41b8889 | 941 | cpp | C++ | 126B.cpp | basuki57/Codeforces | 5227c3deecf13d90e5ea45dab0dfc16b44bd028c | [
"MIT"
] | null | null | null | 126B.cpp | basuki57/Codeforces | 5227c3deecf13d90e5ea45dab0dfc16b44bd028c | [
"MIT"
] | null | null | null | 126B.cpp | basuki57/Codeforces | 5227c3deecf13d90e5ea45dab0dfc16b44bd028c | [
"MIT"
] | 2 | 2020-10-03T04:52:14.000Z | 2020-10-03T05:19:12.000Z | //https://codeforces.com/contest/126/problem/B
#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
vector<ll> zfun(string s){
ll n = s.length();
vector<ll> z(n);
for(ll i = 1; i < n; ++i){
ll j = z[i-1];
while(j > 0 && s[i] != s[j]) j = z[j-1];
if(s[i]== s[j])++j;
z[i] = j;
}
return z;
}
void solve(){
string s, t, st;
cin >> s;
t = s; reverse(t.begin(), t.end());
vector<ll> z = zfun(s), rz = zfun(t);
ll indx = -1, n = s.length(), ma = 0;
for(ll i = 0; i < n; i++){
if(z[i] == rz[n-1-(i-(z[i]-1))] && z[i] > ma){
indx = i; ma = z[i];
}
}
if(indx == -1){
cout << "Just a legend" << endl;
return;
}
for(ll i = 0; i < z[indx]; i++) st+=s[i];
cout << st << endl;
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(0);
//int t;cin>>t;while(t--)
solve();
return 0;
}
| 21.386364 | 54 | 0.446334 | basuki57 |
32d06204c27b116774669b99f6e78685736e1171 | 1,578 | cpp | C++ | SYCL/USM/source_kernel_indirect_access.cpp | asidoren-intel/llvm-test-suite | 93d8391573adfc19b759f971e1269a245be4b87a | [
"Apache-2.0"
] | null | null | null | SYCL/USM/source_kernel_indirect_access.cpp | asidoren-intel/llvm-test-suite | 93d8391573adfc19b759f971e1269a245be4b87a | [
"Apache-2.0"
] | null | null | null | SYCL/USM/source_kernel_indirect_access.cpp | asidoren-intel/llvm-test-suite | 93d8391573adfc19b759f971e1269a245be4b87a | [
"Apache-2.0"
] | null | null | null | // RUN: %clangxx -fsycl -fsycl-targets=%sycl_triple %opencl_lib %s -o %t1.out
// RUN: %CPU_RUN_PLACEHOLDER %t1.out
// RUN: %GPU_RUN_PLACEHOLDER %t1.out
// RUN: %ACC_RUN_PLACEHOLDER %t1.out
// REQUIRES: opencl,opencl_icd
#include <CL/cl.h>
#include <CL/sycl.hpp>
using namespace sycl;
static const char *Src = R"(
kernel void test(global ulong *PSrc, global ulong *PDst) {
global int *Src = (global int *) *PSrc;
global int *Dst = (global int *) *PDst;
int Old = *Src, New = Old + 1;
printf("Read %d from %p; write %d to %p\n", Old, Src, New, Dst);
*Dst = New;
}
)";
int main() {
queue Q{};
cl_context Ctx = Q.get_context().get();
cl_program Prog = clCreateProgramWithSource(Ctx, 1, &Src, NULL, NULL);
clBuildProgram(Prog, 0, NULL, NULL, NULL, NULL);
cl_kernel OclKernel = clCreateKernel(Prog, "test", NULL);
cl::sycl::kernel SyclKernel(OclKernel, Q.get_context());
auto POuter = malloc_shared<int *>(1, Q);
auto PInner = malloc_shared<int>(1, Q);
auto QOuter = malloc_shared<int *>(1, Q);
auto QInner = malloc_shared<int>(1, Q);
*PInner = 4;
*POuter = PInner;
*QInner = 0;
*QOuter = QInner;
Q.submit([&](handler &CGH) {
CGH.set_arg(0, POuter);
CGH.set_arg(1, QOuter);
CGH.parallel_for(cl::sycl::range<1>(1), SyclKernel);
}).wait();
assert(*PInner == 4 && "Read value is corrupted");
assert(*QInner == 5 && "Value value is incorrect");
std::cout << "Increment: " << *PInner << " -> " << *QInner << std::endl;
clReleaseKernel(OclKernel);
clReleaseProgram(Prog);
clReleaseContext(Ctx);
}
| 27.206897 | 77 | 0.636248 | asidoren-intel |
32d2a8c84b423fb5fe0febe95ee200a0dd62bb4a | 1,064 | ipp | C++ | coast/mtfoundation/ThreadPools.ipp | zer0infinity/CuteForCoast | 37d933c5fe2e0ce9a801f51b2aa27c7a18098511 | [
"BSD-3-Clause"
] | null | null | null | coast/mtfoundation/ThreadPools.ipp | zer0infinity/CuteForCoast | 37d933c5fe2e0ce9a801f51b2aa27c7a18098511 | [
"BSD-3-Clause"
] | null | null | null | coast/mtfoundation/ThreadPools.ipp | zer0infinity/CuteForCoast | 37d933c5fe2e0ce9a801f51b2aa27c7a18098511 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2007, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland
* All rights reserved.
*
* This library/application is free software; you can redistribute and/or modify it under the terms of
* the license that is included with this library/application in the file license.txt.
*/
#ifndef _ThreadPools_IPP
#define _ThreadPools_IPP
//--- c-modules used -----------------------------------------------------------
template< class WorkerParamType >
bool WorkerPoolManager::Enter( WorkerParamType workload, long lFindWorkerHint )
{
// guard the entry to request handling
// we're doing flow control on the main thread
// causing it to wait for a request thread to
// be available
LockUnlockEntry me(fMutex);
StartTrace1(WorkerPoolManager.Enter, "hint: " << lFindWorkerHint);
bool bEnterSuccess( false );
// find a worker object that can run this request
WorkerThread *hr( FindNextRunnable( lFindWorkerHint ) );
if ( hr != NULL ) {
bEnterSuccess = hr->SetWorking(workload);
}
return bEnterSuccess;
}
#endif
| 32.242424 | 102 | 0.709586 | zer0infinity |
32d6400d5b4faed0e74ecd60a5837859c0850664 | 3,731 | cpp | C++ | libiop/tests/algebra/test_gf256.cpp | pwang00/libiop | 640a627f0e844caf88ac66cc2ab16f1ef3ea3283 | [
"MIT"
] | null | null | null | libiop/tests/algebra/test_gf256.cpp | pwang00/libiop | 640a627f0e844caf88ac66cc2ab16f1ef3ea3283 | [
"MIT"
] | null | null | null | libiop/tests/algebra/test_gf256.cpp | pwang00/libiop | 640a627f0e844caf88ac66cc2ab16f1ef3ea3283 | [
"MIT"
] | null | null | null | #include <gtest/gtest.h>
#include "libiop/algebra/fields/gf256.hpp"
namespace libiop {
gf256 gf256_mul(const uint64_t &a_val_high, const uint64_t &a_val_midh,
const uint64_t &a_val_midl, const uint64_t &a_val_low,
const uint64_t &b_val_high, const uint64_t &b_val_midh,
const uint64_t &b_val_midl, const uint64_t &b_val_low)
{
return gf256(a_val_high, a_val_midh, a_val_midl, a_val_low) *
gf256(b_val_high, b_val_midh, b_val_midl, b_val_low);
}
/* test cases generated by sage/gf256.sage script */
TEST(MultiplicationTest, SageTests) {
EXPECT_EQ(gf256_mul(0xf764a67447957a65LL, 0x897bb93561e04d72LL, 0x0fe9a9f10ea6b3beLL, 0x614becf0f6981970LL, 0xf507be43450e596cLL, 0x7625671a07a1b127LL, 0xb6f0e7fe834a305fLL, 0x5d1bce4867374275LL), gf256(0x7830000656b147bbLL, 0x84aedc89d9eef7d5LL, 0x206521a58a74c76dLL, 0x15b45070f9272694LL));
EXPECT_EQ(gf256_mul(0xb4dab96b1454919dLL, 0x23fad70584b9ff24LL, 0x00a7fced16ffa59bLL, 0x7009d6ea6cbc3723LL, 0x633c9cefc089eb74LL, 0x0fd73239d93bd077LL, 0x5756b56a1d208f91LL, 0xac2c97ebcf121998LL), gf256(0xec433aa096b7c5a3LL, 0xb988c6486912b0ffLL, 0xf4974416b3ec0351LL, 0xa0abd7439b4a90b4LL));
EXPECT_EQ(gf256_mul(0xfae308c406eb08feLL, 0x49bfcd0bd4d96b01LL, 0xf55ab02f9dae69b8LL, 0xc1c42adfa999b078LL, 0x1cf009d26ee1f80fLL, 0xf2e6b1294f40ac62LL, 0x512288f4b06917d3LL, 0xd2c36d17d828d9b4LL), gf256(0xd4c9b1f1b6032f4aLL, 0x5a443906b0fd92f4LL, 0x069ef58da6005ef0LL, 0x81149bf7a2a4e9efLL));
EXPECT_EQ(gf256_mul(0x579c25544b3ba640LL, 0x7766723a1141eddcLL, 0x206901073d267fa5LL, 0x9a2789bfb11c03c4LL, 0x1d5e8949c38296e0LL, 0x224aa1e6e025b316LL, 0x84eb9e2187501666LL, 0xc78b2478a98afb85LL), gf256(0xc92ed4a7f831b22eLL, 0x42d345a89b213da0LL, 0x6ca9b1401b327636LL, 0x81a1d4e28ecb3203LL));
EXPECT_EQ(gf256_mul(0x034858f4f1f7b14bLL, 0x75bee645ed32bf73LL, 0xfaaf7393e729adf5LL, 0xe4e8ae96b691f6d2LL, 0xae8f8592118650dfLL, 0x4105e1bce7fda1a5LL, 0x94659c82eed44ed6LL, 0x0d6f1491ffab6313LL), gf256(0x3c58c4917b50380aLL, 0x155a26d3e04dc3f9LL, 0x0ece08a653d5d785LL, 0xa0491208d489ad20LL));
EXPECT_EQ(gf256_mul(0x22677e786437ded8LL, 0xeab6bb9efffe16f2LL, 0xae333a6c2e525a7eLL, 0x9ded3331f7e20e08LL, 0x724efc0872e555d7LL, 0x13ee2aa2bc56bb9fLL, 0x4b28b4a78b34aed6LL, 0xc9a973387db34f3cLL), gf256(0x31c713050f9fe79fLL, 0x91f3134564072e28LL, 0xbd3b97df5ceaa321LL, 0x85ae031df2087301LL));
EXPECT_EQ(gf256_mul(0xe103fdd38559f718LL, 0xbde830a033005e9dLL, 0x5980393a96b7e262LL, 0xbee979d0d3e73491LL, 0x24d79165090b54bbLL, 0x6be4979855b9f4a1LL, 0x3c84f51267ae0f3eLL, 0x49762387dc75fbcfLL), gf256(0xaf3c148f5a6d62b6LL, 0xcb2caa9c1491eb09LL, 0x9d964ce7c25f9cc4LL, 0xf0774bdc5efd321bLL));
EXPECT_EQ(gf256_mul(0xc8d362a82d40e33dLL, 0x7ebb79ea0539aab6LL, 0xd4cb229a76bbfdf8LL, 0xe1ed007e6b4d18c4LL, 0xc5ff42586ffe84beLL, 0x2fa0d6324909d6bcLL, 0xd059de8a3f216806LL, 0x11ce6283a327c2aeLL), gf256(0x6d8f5131a50a1174LL, 0x3716b1b7b85aa29fLL, 0x786f09fc7add372aLL, 0xd9be899417749c66LL));
EXPECT_EQ(gf256_mul(0xa34a5c6dc2269e92LL, 0xd4926e0f5173ba59LL, 0xad04af41cefd288cLL, 0xd6910fac0958e021LL, 0xb8efe59559134148LL, 0xe2df550b05c8346bLL, 0x471c649050d8df10LL, 0x3c4ddb6e1d7bdf2bLL), gf256(0x31bc02040d35ef67LL, 0xf4df56b7f489a233LL, 0x94a98345cd1c505eLL, 0x9b8880399d5b6f17LL));
EXPECT_EQ(gf256_mul(0x0dd2d419a879877eLL, 0xbbd7c0e1cb89df45LL, 0xb920792cb175a788LL, 0xfe328eb0319d0dd7LL, 0xfdd10984711604a6LL, 0x449e2950c151d1f4LL, 0x06b95b1542038a8aLL, 0xbbc51592da56e2feLL), gf256(0x5eac8a0dfe585d7dLL, 0x8bb81c1be4902348LL, 0xb441d39d98693d34LL, 0x480e988c351ac9f3LL));
}
TEST(InverseTest, SimpleTest) {
const gf256 a = gf256::random_element();
const gf256 a_inv = a.inverse();
EXPECT_EQ(a*a_inv, gf256(1));
}
}
| 95.666667 | 296 | 0.845886 | pwang00 |
32dcdf57ff8a79e18f9c97c82c1e0f33056c689a | 3,011 | hpp | C++ | include/codegen/include/OVR/OpenVR/IVRSystem__GetStringTrackedDeviceProperty.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 1 | 2021-11-12T09:29:31.000Z | 2021-11-12T09:29:31.000Z | include/codegen/include/OVR/OpenVR/IVRSystem__GetStringTrackedDeviceProperty.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | null | null | null | include/codegen/include/OVR/OpenVR/IVRSystem__GetStringTrackedDeviceProperty.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 2 | 2021-10-03T02:14:20.000Z | 2021-11-12T09:29:36.000Z | // Autogenerated from CppHeaderCreator on 7/27/2020 3:10:00 PM
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "utils/typedefs.h"
// Including type: System.MulticastDelegate
#include "System/MulticastDelegate.hpp"
// Including type: OVR.OpenVR.IVRSystem
#include "OVR/OpenVR/IVRSystem.hpp"
#include "utils/il2cpp-utils.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System
namespace System {
// Skipping declaration: IntPtr because it is already included!
// Forward declaring type: IAsyncResult
class IAsyncResult;
// Forward declaring type: AsyncCallback
class AsyncCallback;
}
// Forward declaring namespace: OVR::OpenVR
namespace OVR::OpenVR {
// Forward declaring type: ETrackedDeviceProperty
struct ETrackedDeviceProperty;
// Forward declaring type: ETrackedPropertyError
struct ETrackedPropertyError;
}
// Forward declaring namespace: System::Text
namespace System::Text {
// Forward declaring type: StringBuilder
class StringBuilder;
}
// Completed forward declares
// Type namespace: OVR.OpenVR
namespace OVR::OpenVR {
// Autogenerated type: OVR.OpenVR.IVRSystem/_GetStringTrackedDeviceProperty
class IVRSystem::_GetStringTrackedDeviceProperty : public System::MulticastDelegate {
public:
// public System.Void .ctor(System.Object object, System.IntPtr method)
// Offset: 0x16A6D0C
static IVRSystem::_GetStringTrackedDeviceProperty* New_ctor(::Il2CppObject* object, System::IntPtr method);
// public System.UInt32 Invoke(System.UInt32 unDeviceIndex, OVR.OpenVR.ETrackedDeviceProperty prop, System.Text.StringBuilder pchValue, System.UInt32 unBufferSize, OVR.OpenVR.ETrackedPropertyError pError)
// Offset: 0x16A6D20
uint Invoke(uint unDeviceIndex, OVR::OpenVR::ETrackedDeviceProperty prop, System::Text::StringBuilder* pchValue, uint unBufferSize, OVR::OpenVR::ETrackedPropertyError& pError);
// public System.IAsyncResult BeginInvoke(System.UInt32 unDeviceIndex, OVR.OpenVR.ETrackedDeviceProperty prop, System.Text.StringBuilder pchValue, System.UInt32 unBufferSize, OVR.OpenVR.ETrackedPropertyError pError, System.AsyncCallback callback, System.Object object)
// Offset: 0x16A7004
System::IAsyncResult* BeginInvoke(uint unDeviceIndex, OVR::OpenVR::ETrackedDeviceProperty prop, System::Text::StringBuilder* pchValue, uint unBufferSize, OVR::OpenVR::ETrackedPropertyError& pError, System::AsyncCallback* callback, ::Il2CppObject* object);
// public System.UInt32 EndInvoke(OVR.OpenVR.ETrackedPropertyError pError, System.IAsyncResult result)
// Offset: 0x16A70F0
uint EndInvoke(OVR::OpenVR::ETrackedPropertyError& pError, System::IAsyncResult* result);
}; // OVR.OpenVR.IVRSystem/_GetStringTrackedDeviceProperty
}
DEFINE_IL2CPP_ARG_TYPE(OVR::OpenVR::IVRSystem::_GetStringTrackedDeviceProperty*, "OVR.OpenVR", "IVRSystem/_GetStringTrackedDeviceProperty");
#pragma pack(pop)
| 52.824561 | 272 | 0.771504 | Futuremappermydud |
32dd370c0f9c38cd961a39812a5bbedf9285e81b | 676 | cc | C++ | Code/1659-get-the-maximum-score.cc | SMartQi/Leetcode | 9e35c65a48ba1ecd5436bbe07dd65f993588766b | [
"MIT"
] | 2 | 2019-12-06T14:08:57.000Z | 2020-01-15T15:25:32.000Z | Code/1659-get-the-maximum-score.cc | SMartQi/Leetcode | 9e35c65a48ba1ecd5436bbe07dd65f993588766b | [
"MIT"
] | 1 | 2020-01-15T16:29:16.000Z | 2020-01-26T12:40:13.000Z | Code/1659-get-the-maximum-score.cc | SMartQi/Leetcode | 9e35c65a48ba1ecd5436bbe07dd65f993588766b | [
"MIT"
] | null | null | null | class Solution {
public:
int maxSum(vector<int>& nums1, vector<int>& nums2) {
long long n1 = 0, n2 = 0;
int p = nums1.size() - 1, q = nums2.size() - 1;
while (p >= 0 && q >= 0) {
if (nums1[p] > nums2[q]) {
n1 += nums1[p--];
} else if (nums1[p] < nums2[q]) {
n2 += nums2[q--];
} else {
n2 = n1 = nums1[p] + max(n1, n2);
p--;
q--;
}
}
while (p >= 0) {
n1 += nums1[p--];
}
while (q >= 0) {
n2 += nums2[q--];
}
return max(n1, n2) % 1000000007;
}
}; | 27.04 | 56 | 0.337278 | SMartQi |
77fe6c5d2daaf516cecb61e5772274380ff47193 | 1,278 | cpp | C++ | bindings/python/src/LibraryPhysicsPy/Environment/Magnetic/Dipole.cpp | cowlicks/library-physics | dd314011132430fcf074a9a1633b24471745cf92 | [
"Apache-2.0"
] | null | null | null | bindings/python/src/LibraryPhysicsPy/Environment/Magnetic/Dipole.cpp | cowlicks/library-physics | dd314011132430fcf074a9a1633b24471745cf92 | [
"Apache-2.0"
] | null | null | null | bindings/python/src/LibraryPhysicsPy/Environment/Magnetic/Dipole.cpp | cowlicks/library-physics | dd314011132430fcf074a9a1633b24471745cf92 | [
"Apache-2.0"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @project Library ▸ Physics
/// @file LibraryPhysicsPy/Environment/Magnetic/Dipole.cpp
/// @author Lucas Brémond <lucas@loftorbital.com>
/// @license Apache License 2.0
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <Library/Physics/Environment/Magnetic/Dipole.hpp>
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
inline void LibraryPhysicsPy_Environment_Magnetic_Dipole ( )
{
using namespace boost::python ;
using library::math::obj::Vector3d ;
using library::physics::environment::magnetic::Dipole ;
scope in_Dipole = class_<Dipole>("Dipole", init<const Vector3d&>())
.def("getFieldValueAt", &Dipole::getFieldValueAt)
;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
| 39.9375 | 160 | 0.324726 | cowlicks |
ae045c9a460af1c7b67fd9565e570a701c9257d3 | 171 | cpp | C++ | config_tools/check_cpu.tool.cpp | SamuraiCrow/AmosKittens | e89477b94a28916e4320fa946c18c0d769c710b2 | [
"MIT"
] | 7 | 2018-04-24T22:11:58.000Z | 2021-09-10T22:12:35.000Z | config_tools/check_cpu.tool.cpp | SamuraiCrow/AmosKittens | e89477b94a28916e4320fa946c18c0d769c710b2 | [
"MIT"
] | 36 | 2018-02-24T18:34:18.000Z | 2021-08-08T10:33:29.000Z | config_tools/check_cpu.tool.cpp | SamuraiCrow/AmosKittens | e89477b94a28916e4320fa946c18c0d769c710b2 | [
"MIT"
] | 2 | 2018-10-22T18:47:30.000Z | 2020-09-16T06:10:52.000Z |
#include <stdio.h>
#include <stdlib.h>
int main(int args,char **arg)
{
int value = 1;
if ( *((char *) &value) == 1 )
{
printf("#define __LITTLE_ENDIAN__\n");
}
} | 12.214286 | 40 | 0.578947 | SamuraiCrow |
ae0a3f06fce60ff1b318cb37a140de678f9abca3 | 1,156 | cpp | C++ | Codeforces/1462C.cpp | DT3264/ProgrammingContestsSolutions | a297f2da654c2ca2815b9aa375c2b4ca0052269d | [
"MIT"
] | null | null | null | Codeforces/1462C.cpp | DT3264/ProgrammingContestsSolutions | a297f2da654c2ca2815b9aa375c2b4ca0052269d | [
"MIT"
] | null | null | null | Codeforces/1462C.cpp | DT3264/ProgrammingContestsSolutions | a297f2da654c2ca2815b9aa375c2b4ca0052269d | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
#define y1 yy
#define f first
#define s second
#define ll long long
#define vi vector<int>
#define pii pair<int, int>
#define debug if(printDebug)
#define noDebug if(!printDebug)
using namespace std;
template<class T>
using v=vector<T>;
bool printDebug=false;
int ans[51];
bool used[10];
void test(int pos){
if(pos>9){
int sum=0;
string str;
for(int i=0; i<10; i++){
if(used[i]){
sum+=i;
str+=i+'0';
}
}
if(str.size()==0) return;
int num=stoi(str);
if(sum<=50 && ans[sum]!=-1 && num<ans[sum]) ans[sum]=num;
if(sum<=50 && ans[sum]==-1) ans[sum]=num;
return;
}
used[pos]=false;
test(pos+1);
used[pos]=true;
test(pos+1);
}
int main(){
memset(ans, -1, sizeof(ans));
//printDebug=true;
/*freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);//*/
noDebug ios_base::sync_with_stdio(0);
noDebug cin.tie(0);
test(1);
int cases;
cin >> cases;
while(cases--){
int n;
cin >> n;
cout << ans[n] << "\n";
}
return 0;
}
| 21.407407 | 65 | 0.521626 | DT3264 |
ae0ad4adaed1a74b592b4dca91d9e1528077222c | 2,376 | cpp | C++ | test/istream.cpp | danra/scnlib | 815782badc1b548c21bb151372497e1516bee806 | [
"Apache-2.0"
] | 556 | 2018-11-17T01:49:32.000Z | 2022-03-25T09:35:10.000Z | test/istream.cpp | danra/scnlib | 815782badc1b548c21bb151372497e1516bee806 | [
"Apache-2.0"
] | 51 | 2019-05-09T14:36:53.000Z | 2022-03-19T12:47:12.000Z | test/istream.cpp | danra/scnlib | 815782badc1b548c21bb151372497e1516bee806 | [
"Apache-2.0"
] | 21 | 2019-02-11T19:56:30.000Z | 2022-03-28T02:52:27.000Z | // Copyright 2017 Elias Kosunen
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// This file is a part of scnlib:
// https://github.com/eliaskosunen/scnlib
#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
#include <scn/istream.h>
#include <istream>
#include <sstream>
#include "test.h"
struct my_type {
int value{};
friend std::istream& operator>>(std::istream& is, my_type& val)
{
is >> val.value;
return is;
}
};
TEST_CASE("istream value")
{
my_type val{};
auto ret = scn::scan("123", "{}", val);
CHECK(ret);
CHECK(val.value == 123);
}
TEST_CASE("istream fail")
{
my_type val{};
auto ret = scn::scan("foo", "{}", val);
CHECK(!ret);
CHECK(ret.error().code() == scn::error::invalid_scanned_value);
CHECK(val.value == 0);
}
TEST_CASE("istream eof")
{
my_type val{};
auto ret = scn::scan("", "{}", val);
CHECK(!ret);
CHECK(ret.error().code() == scn::error::end_of_range);
CHECK(val.value == 0);
}
TEST_CASE("istream composite")
{
auto source = std::string{"foo 123 456"};
std::string s;
auto ret = scn::scan_default(source, s);
CHECK(ret);
CHECK(s == "foo");
my_type val{};
ret = scn::scan_default(ret.range(), val);
CHECK(ret);
CHECK(val.value == 123);
int i;
ret = scn::scan_default(ret.range(), i);
CHECK(ret);
CHECK(i == 456);
CHECK(ret.empty());
}
TEST_CASE("istream composite error")
{
auto source = std::string{"123 foo 456"};
int i;
auto ret = scn::scan_default(source, i);
CHECK(ret);
CHECK(i == 123);
my_type val{};
ret = scn::scan_default(ret.range(), val);
CHECK(!ret);
CHECK(ret.error() == scn::error::invalid_scanned_value);
CHECK(val.value == 0);
std::string s;
ret = scn::scan_default(ret.range(), s);
CHECK(ret);
CHECK(s == "foo");
}
| 23.294118 | 75 | 0.621212 | danra |
ae0cf9861d85e17a183690be0bd6bf178259c176 | 44,069 | cpp | C++ | src/ModelSet.cpp | marcussvensson92/inner_conservative_occluder_rasterization | cbf05803d1e7658e95277d093dbae9570a874c59 | [
"MIT"
] | null | null | null | src/ModelSet.cpp | marcussvensson92/inner_conservative_occluder_rasterization | cbf05803d1e7658e95277d093dbae9570a874c59 | [
"MIT"
] | 1 | 2017-09-10T11:58:30.000Z | 2017-09-10T11:58:30.000Z | src/ModelSet.cpp | marcussvensson92/inner_conservative_occluder_rasterization | cbf05803d1e7658e95277d093dbae9570a874c59 | [
"MIT"
] | null | null | null | #include "ModelSet.h"
#include "OcclusionAlgorithm.h"
#include <DDSTextureLoader.h>
#include <fstream>
#include <locale>
#include <codecvt>
CModelSet::CModelSet() :
m_InstanceCount( 0 ),
m_MaterialBuffer( nullptr ),
m_MaterialBufferUpload( nullptr ),
m_WorldMatrixBufferSize( 0 ),
m_WorldMatrixBuffer( nullptr ),
m_WorldMatrixBufferUpload( nullptr ),
m_ModelInstanceCountBufferSize( 0 ),
m_InstanceIndexMappingsBufferSize( 0 ),
m_InstanceModelMappingsBuffer( nullptr ),
m_InstanceModelMappingsBufferUpload( nullptr ),
m_ModelInstanceOffsetBuffer( nullptr ),
m_ModelInstanceOffsetBufferUpload( nullptr ),
m_ModelInstanceCountBuffer( nullptr ),
m_ModelInstanceCountBufferReset( nullptr ),
m_InstanceIndexMappingsBuffer( nullptr ),
m_OutputCommandBufferCounterOffset( 0 ),
m_InputCommandBuffer( nullptr ),
m_InputCommandBufferUpload( nullptr ),
m_OutputCommandBuffer( nullptr ),
m_OutputCommandBufferCounterReset( nullptr )
{
}
void CModelSet::Load( const std::string& directory, const std::string& filename )
{
m_Directory = directory;
m_Filename = filename;
LoadModels();
}
void CModelSet::Save()
{
SaveModels();
}
void CModelSet::Create(
ID3D12Device* device,
ID3D12GraphicsCommandList* command_list,
NGraphics::CDescriptorHeap descriptor_heaps[ D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES ] )
{
m_InstanceCount = 0;
for ( SModel* model : m_Models )
{
m_InstanceCount += static_cast< UINT >( model->m_Instances.size() );
}
CreateMeshes( device, command_list );
CreateTexturesAndMaterials( device, command_list, descriptor_heaps );
CreateWorldMatrixBuffer( device, command_list, descriptor_heaps );
CreateInstanceMappingsBuffers( device, command_list, descriptor_heaps );
CreateCommandBuffers( device, command_list, descriptor_heaps );
CalculateOccludees();
CalculateOccluders();
}
void CModelSet::Destroy()
{
m_InstanceCount = 0;
for ( SModel* model : m_Models )
{
model->m_Mesh.Destroy();
delete model;
}
m_Models.clear();
SAFE_RELEASE( m_MaterialBufferUpload );
SAFE_RELEASE( m_MaterialBuffer );
for ( STexture texture_array : m_Textures )
{
texture_array.m_Resource->Release();
texture_array.m_ResourceUpload->Release();
}
m_Textures.clear();
m_WorldMatrixBufferSize = 0;
SAFE_RELEASE( m_WorldMatrixBuffer );
SAFE_RELEASE_UNMAP( m_WorldMatrixBufferUpload );
m_ModelInstanceCountBufferSize = 0;
m_InstanceIndexMappingsBufferSize = 0;
SAFE_RELEASE( m_InstanceModelMappingsBuffer );
SAFE_RELEASE( m_InstanceModelMappingsBufferUpload );
SAFE_RELEASE( m_ModelInstanceOffsetBuffer );
SAFE_RELEASE( m_ModelInstanceOffsetBufferUpload );
SAFE_RELEASE( m_ModelInstanceCountBuffer );
SAFE_RELEASE( m_ModelInstanceCountBufferReset );
SAFE_RELEASE( m_InstanceIndexMappingsBuffer );
SAFE_RELEASE( m_InstanceIndexMappingsBufferUpload );
m_OutputCommandBufferCounterOffset = 0;
SAFE_RELEASE( m_InputCommandBuffer );
SAFE_RELEASE( m_InputCommandBufferUpload );
SAFE_RELEASE( m_OutputCommandBuffer );
SAFE_RELEASE( m_OutputCommandBufferCounterReset );
}
void CModelSet::UpdateWorldMatrixBuffer( ID3D12GraphicsCommandList* command_list )
{
for ( SModel* model : m_Models )
{
model->m_VisibleInstanceCount = static_cast< UINT >( model->m_Instances.size() );
DirectX::XMFLOAT4X4* mapped_world_matrix_buffer = model->m_MappedWorldMatrixBuffer;
for ( SInstance instance : model->m_Instances )
{
DirectX::XMStoreFloat4x4(
mapped_world_matrix_buffer,
DirectX::XMMatrixTranspose( DirectX::XMLoadFloat4x4( &instance.m_World ) ) );
++mapped_world_matrix_buffer;
}
}
command_list->ResourceBarrier( 1, &CD3DX12_RESOURCE_BARRIER::Transition(
m_WorldMatrixBuffer, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_COPY_DEST ) );
command_list->CopyBufferRegion( m_WorldMatrixBuffer, 0, m_WorldMatrixBufferUpload, 0, m_WorldMatrixBufferSize );
command_list->ResourceBarrier( 1, &CD3DX12_RESOURCE_BARRIER::Transition(
m_WorldMatrixBuffer, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE ) );
}
void CModelSet::UpdateInstanceMappings(
ID3D12GraphicsCommandList* command_list,
COcclusionAlgorithm* occlusion_algorithm,
UINT occludee_offset )
{
UINT* mapped_instance_index_mappings_upload = nullptr;
HR( m_InstanceIndexMappingsBufferUpload->Map( 0, &CD3DX12_RANGE( 0, 0 ), reinterpret_cast< void** >( &mapped_instance_index_mappings_upload ) ) );
UINT instance_index = 0;
for ( SModel* model : m_Models )
{
model->m_VisibleInstanceCount = 0;
for ( SInstance instance : model->m_Instances )
{
if ( occlusion_algorithm->IsOccludeeVisible( occludee_offset + instance_index ) )
{
mapped_instance_index_mappings_upload[ model->m_VisibleInstanceCount++ ] = instance_index;
}
++instance_index;
}
mapped_instance_index_mappings_upload += model->m_Instances.size();
}
m_InstanceIndexMappingsBufferUpload->Unmap( 0, &CD3DX12_RANGE( 0, 0 ) );
command_list->ResourceBarrier( 1, &CD3DX12_RESOURCE_BARRIER::Transition(
m_InstanceIndexMappingsBuffer, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_COPY_DEST ) );
command_list->CopyBufferRegion( m_InstanceIndexMappingsBuffer, 0, m_InstanceIndexMappingsBufferUpload, 0, m_InstanceIndexMappingsBufferSize );
command_list->ResourceBarrier( 1, &CD3DX12_RESOURCE_BARRIER::Transition(
m_InstanceIndexMappingsBuffer, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE ) );
}
void CModelSet::CalculateOccluders()
{
size_t total_occluder_obb_count = 0;
size_t total_occluder_cylinder_count = 0;
for ( SModel* model : m_Models )
{
total_occluder_obb_count += model->m_OccluderObbs.size() * model->m_Instances.size();
total_occluder_cylinder_count += model->m_OccluderCylinders.size() * model->m_Instances.size();
}
m_OccluderObbs.resize( total_occluder_obb_count );
m_OccluderCylinders.resize( total_occluder_cylinder_count );
size_t occluder_obb_index = 0;
size_t occluder_cylinder_index = 0;
for ( SModel* model : m_Models )
{
for ( size_t i = 0; i < model->m_Instances.size(); ++i )
{
DirectX::XMMATRIX instance_world = DirectX::XMLoadFloat4x4( &model->m_Instances[ i ].m_World );
DirectX::XMVECTOR scale, rotation, translation;
DirectX::XMMatrixDecompose( &scale, &rotation, &translation, instance_world );
instance_world =
DirectX::XMMatrixRotationQuaternion( rotation ) *
DirectX::XMMatrixTranslationFromVector( translation );
for ( size_t j = 0; j < model->m_OccluderObbs.size(); ++j )
{
DirectX::XMMATRIX obb_center =
DirectX::XMMatrixScaling(
model->m_OccluderObbs[ j ].m_Extent.x,
model->m_OccluderObbs[ j ].m_Extent.y,
model->m_OccluderObbs[ j ].m_Extent.z ) *
DirectX::XMMatrixRotationX( DirectX::XMConvertToRadians( model->m_OccluderObbs[ j ].m_Rotation.x ) ) *
DirectX::XMMatrixRotationY( DirectX::XMConvertToRadians( model->m_OccluderObbs[ j ].m_Rotation.y ) ) *
DirectX::XMMatrixRotationZ( DirectX::XMConvertToRadians( model->m_OccluderObbs[ j ].m_Rotation.z ) ) *
DirectX::XMMatrixTranslation(
model->m_OccluderObbs[ j ].m_Center.x,
model->m_OccluderObbs[ j ].m_Center.y,
model->m_OccluderObbs[ j ].m_Center.z );
DirectX::XMStoreFloat4x4(
&m_OccluderObbs[ occluder_obb_index++ ],
DirectX::XMMatrixTranspose( DirectX::XMMatrixMultiply( obb_center, instance_world ) ) );
}
for ( size_t j = 0; j < model->m_OccluderCylinders.size(); ++j )
{
DirectX::XMMATRIX cylinder_center =
DirectX::XMMatrixScaling(
model->m_OccluderCylinders[ j ].m_Radius,
model->m_OccluderCylinders[ j ].m_Height,
model->m_OccluderCylinders[ j ].m_Radius ) *
DirectX::XMMatrixRotationX( DirectX::XMConvertToRadians( model->m_OccluderCylinders[ j ].m_Rotation.x ) ) *
DirectX::XMMatrixRotationY( DirectX::XMConvertToRadians( model->m_OccluderCylinders[ j ].m_Rotation.y ) ) *
DirectX::XMMatrixRotationZ( DirectX::XMConvertToRadians( model->m_OccluderCylinders[ j ].m_Rotation.z ) ) *
DirectX::XMMatrixTranslation(
model->m_OccluderCylinders[ j ].m_Center.x,
model->m_OccluderCylinders[ j ].m_Center.y,
model->m_OccluderCylinders[ j ].m_Center.z );
DirectX::XMStoreFloat4x4(
&m_OccluderCylinders[ occluder_cylinder_index++ ],
DirectX::XMMatrixTranspose( DirectX::XMMatrixMultiply( cylinder_center, instance_world ) ) );
}
}
}
}
void CModelSet::CalculateOccludees()
{
m_OccludeeAabbs.resize( m_InstanceCount );
UINT occludee_aabb_index = 0;
for ( SModel* model : m_Models )
{
DirectX::XMVECTOR center = XMLoadFloat3( &model->m_OccludeeBoundingBoxCenter );
DirectX::XMVECTOR extent = XMLoadFloat3( &model->m_OccludeeBoundingBoxExtent );
DirectX::XMVECTOR positions[ 8 ] =
{
DirectX::XMVectorAdd( center, DirectX::XMVectorMultiply( DirectX::XMVectorSet( 1.0f, 1.0f, 1.0f, 0.0f ), extent ) ),
DirectX::XMVectorAdd( center, DirectX::XMVectorMultiply( DirectX::XMVectorSet( 1.0f, 1.0f, -1.0f, 0.0f ), extent ) ),
DirectX::XMVectorAdd( center, DirectX::XMVectorMultiply( DirectX::XMVectorSet( 1.0f, -1.0f, 1.0f, 0.0f ), extent ) ),
DirectX::XMVectorAdd( center, DirectX::XMVectorMultiply( DirectX::XMVectorSet( 1.0f, -1.0f, -1.0f, 0.0f ), extent ) ),
DirectX::XMVectorAdd( center, DirectX::XMVectorMultiply( DirectX::XMVectorSet( -1.0f, 1.0f, 1.0f, 0.0f ), extent ) ),
DirectX::XMVectorAdd( center, DirectX::XMVectorMultiply( DirectX::XMVectorSet( -1.0f, 1.0f, -1.0f, 0.0f ), extent ) ),
DirectX::XMVectorAdd( center, DirectX::XMVectorMultiply( DirectX::XMVectorSet( -1.0f, -1.0f, 1.0f, 0.0f ), extent ) ),
DirectX::XMVectorAdd( center, DirectX::XMVectorMultiply( DirectX::XMVectorSet( -1.0f, -1.0f, -1.0f, 0.0f ), extent ) )
};
for ( SInstance& instance : model->m_Instances )
{
DirectX::XMMATRIX instance_world = DirectX::XMLoadFloat4x4( &instance.m_World );
DirectX::XMVECTOR aabb_min = DirectX::XMVectorSet( FLT_MAX, FLT_MAX, FLT_MAX, 1.0f );
DirectX::XMVECTOR aabb_max = DirectX::XMVectorSet( -FLT_MAX, -FLT_MAX, -FLT_MAX, 1.0f );
for ( UINT i = 0; i < 8; ++i )
{
DirectX::XMVECTOR position = DirectX::XMVector3TransformCoord( positions[ i ], instance_world );
aabb_min = DirectX::XMVectorMin( aabb_min, position );
aabb_max = DirectX::XMVectorMax( aabb_max, position );
}
DirectX::XMStoreFloat3( &instance.m_OccludeeAabbMin, aabb_min );
DirectX::XMStoreFloat3( &instance.m_OccludeeAabbMax, aabb_max );
DirectX::XMStoreFloat3( &m_OccludeeAabbs[ occludee_aabb_index ].m_Center, ( aabb_max + aabb_min ) * 0.5f );
DirectX::XMStoreFloat3( &m_OccludeeAabbs[ occludee_aabb_index ].m_Extent, ( aabb_max - aabb_min ) * 0.5f );
++occludee_aabb_index;
}
}
}
const UINT CModelSet::GetModelCount() const
{
return static_cast< UINT >( m_Models.size() );
}
const UINT CModelSet::GetInstanceCount() const
{
return m_InstanceCount;
}
const UINT CModelSet::GetTextureCount() const
{
return static_cast< UINT >( m_Textures.size() );
}
std::vector< CModelSet::SModel* >* CModelSet::GetModels()
{
return &m_Models;
}
std::vector< DirectX::XMFLOAT4X4 >* CModelSet::GetOccluderObbs()
{
return &m_OccluderObbs;
}
std::vector< DirectX::XMFLOAT4X4 >* CModelSet::GetOccluderCylinders()
{
return &m_OccluderCylinders;
}
std::vector< COccludeeCollection::SAabb >* CModelSet::GetOccludeeAabbs()
{
return &m_OccludeeAabbs;
}
NGraphics::SDescriptorHandle CModelSet::GetMaterialBufferSrv() const
{
return m_MaterialBufferSrv;
}
NGraphics::SDescriptorHandle CModelSet::GetWorldMatrixBufferSrv() const
{
return m_WorldMatrixBufferSrv;
}
NGraphics::SDescriptorHandle CModelSet::GetTexturesSrv() const
{
return m_Textures[ 0 ].m_Handle;
}
NGraphics::SDescriptorHandle CModelSet::GetInstanceModelMappingsBufferSrv() const
{
return m_InstanceModelMappingsBufferSrv;
}
NGraphics::SDescriptorHandle CModelSet::GetModelInstanceOffsetBufferSrv() const
{
return m_ModelInstanceOffsetBufferSrv;
}
NGraphics::SDescriptorHandle CModelSet::GetModelInstanceCountBufferUav() const
{
return m_ModelInstanceCountBufferUav;
}
NGraphics::SDescriptorHandle CModelSet::GetModelInstanceCountBufferSrv() const
{
return m_ModelInstanceCountBufferSrv;
}
NGraphics::SDescriptorHandle CModelSet::GetInstanceIndexMappingsBufferUav() const
{
return m_InstanceIndexMappingsBufferUav;
}
NGraphics::SDescriptorHandle CModelSet::GetInstanceIndexMappingsBufferSrv() const
{
return m_InstanceIndexMappingsBufferSrv;
}
NGraphics::SDescriptorHandle CModelSet::GetInputCommandBufferSrv() const
{
return m_InputCommandBufferSrv;
}
NGraphics::SDescriptorHandle CModelSet::GetOutputCommandBufferUav() const
{
return m_OutputCommandBufferUav;
}
ID3D12Resource* CModelSet::GetModelInstanceCountBuffer() const
{
return m_ModelInstanceCountBuffer;
}
ID3D12Resource* CModelSet::GetModelInstanceCountBufferReset() const
{
return m_ModelInstanceCountBufferReset;
}
ID3D12Resource* CModelSet::GetInstanceIndexMappingsBuffer() const
{
return m_InstanceIndexMappingsBuffer;
}
ID3D12Resource* CModelSet::GetOutputCommandBuffer() const
{
return m_OutputCommandBuffer;
}
ID3D12Resource* CModelSet::GetOutputCommandBufferCounterReset() const
{
return m_OutputCommandBufferCounterReset;
}
const UINT CModelSet::GetModelInstanceCountBufferSize() const
{
return m_ModelInstanceCountBufferSize;
}
const UINT CModelSet::GetOutputCommandBufferCounterOffset() const
{
return m_OutputCommandBufferCounterOffset;
}
void CModelSet::LoadModels()
{
std::fstream file( m_Directory + "/" + m_Filename, std::ios::in | std::ios::binary );
assert( file.is_open() && file.good() );
size_t size;
file.read( reinterpret_cast< char* >( &size ), sizeof( size_t ) );
m_Models.resize( size );
for ( size_t i = 0; i < m_Models.size(); ++i )
{
SModel* model = new SModel;
file.read( reinterpret_cast< char* >( &size ), sizeof( size_t ) );
model->m_Name.resize( size );
file.read( reinterpret_cast< char* >( &model->m_Name[ 0 ] ), size * sizeof( char ) );
file.read( reinterpret_cast< char* >( &size ), sizeof( size_t ) );
model->m_Vertices.resize( size );
file.read( reinterpret_cast< char* >( &model->m_Vertices[ 0 ] ), size * sizeof( SVertex ) );
file.read( reinterpret_cast< char* >( &size ), sizeof( size_t ) );
model->m_Indices.resize( size );
file.read( reinterpret_cast< char* >( &model->m_Indices[ 0 ] ), size * sizeof( UINT ) );
size_t texture_filepath_count;
file.read( reinterpret_cast< char* >( &texture_filepath_count ), sizeof( size_t ) );
for ( size_t j = 0; j < texture_filepath_count; ++j )
{
std::string texture_filepath_key;
std::string texture_filepath_value;
file.read( reinterpret_cast< char* >( &size ), sizeof( size_t ) );
texture_filepath_key.resize( size );
file.read( reinterpret_cast< char* >( &texture_filepath_key[ 0 ] ), size * sizeof( char ) );
file.read( reinterpret_cast< char* >( &size ), sizeof( size_t ) );
texture_filepath_value.resize( size );
file.read( reinterpret_cast< char* >( &texture_filepath_value[ 0 ] ), size * sizeof( char ) );
model->m_TextureFilepathMap[ texture_filepath_key ] = texture_filepath_value;
}
file.read( reinterpret_cast< char* >( &model->m_OccludeeBoundingBoxCenter ), sizeof( DirectX::XMFLOAT3 ) );
file.read( reinterpret_cast< char* >( &model->m_OccludeeBoundingBoxExtent ), sizeof( DirectX::XMFLOAT3 ) );
file.read( reinterpret_cast< char* >( &size ), sizeof( size_t ) );
model->m_OccluderObbs.resize( size );
if ( size > 0 )
{
file.read( reinterpret_cast< char* >( &model->m_OccluderObbs[ 0 ] ), sizeof( SOccluderObb ) * size );
}
file.read( reinterpret_cast< char* >( &size ), sizeof( size_t ) );
model->m_OccluderCylinders.resize( size );
if ( size > 0 )
{
file.read( reinterpret_cast< char* >( &model->m_OccluderCylinders[ 0 ] ), sizeof( SOccluderCylinder ) * size );
}
file.read( reinterpret_cast< char* >( &size ), sizeof( size_t ) );
model->m_Instances.resize( size );
for ( size_t j = 0; j < model->m_Instances.size(); ++j )
{
file.read( reinterpret_cast< char* >( &model->m_Instances[ j ].m_World ), sizeof( DirectX::XMFLOAT4X4 ) );
}
m_Models[ i ] = model;
}
file.close();
}
void CModelSet::SaveModels()
{
std::fstream file( m_Directory + "/" + m_Filename, std::ios::out | std::ios::binary );
size_t size = m_Models.size();
file.write( reinterpret_cast< char* >( &size ), sizeof( size_t ) );
for ( size_t i = 0; i < m_Models.size(); ++i )
{
SModel* model = m_Models[ i ];
size = model->m_Name.size();
file.write( reinterpret_cast< char* >( &size ), sizeof( size_t ) );
file.write( reinterpret_cast< char* >( &model->m_Name[ 0 ] ), model->m_Name.size() * sizeof( char ) );
size = model->m_Vertices.size();
file.write( reinterpret_cast< char* >( &size ), sizeof( size_t ) );
file.write( reinterpret_cast< char* >( &model->m_Vertices[ 0 ] ), model->m_Vertices.size() * sizeof( SVertex ) );
size = model->m_Indices.size();
file.write( reinterpret_cast< char* >( &size ), sizeof( size_t ) );
file.write( reinterpret_cast< char* >( &model->m_Indices[ 0 ] ), model->m_Indices.size() * sizeof( UINT ) );
size = model->m_TextureFilepathMap.size();
file.write( reinterpret_cast< char* >( &size ), sizeof( size_t ) );
for ( std::pair<std::string, std::string> texture_filepath_entry : model->m_TextureFilepathMap )
{
size = texture_filepath_entry.first.size();
file.write( reinterpret_cast< char* >( &size ), sizeof( size_t ) );
file.write( reinterpret_cast< char* >( &texture_filepath_entry.first[ 0 ] ), texture_filepath_entry.first.size() * sizeof( char ) );
size = texture_filepath_entry.second.size();
file.write( reinterpret_cast< char* >( &size ), sizeof( size_t ) );
file.write( reinterpret_cast< char* >( &texture_filepath_entry.second[ 0 ] ), texture_filepath_entry.second.size() * sizeof( char ) );
}
file.write( reinterpret_cast< char* >( &model->m_OccludeeBoundingBoxCenter ), sizeof( DirectX::XMFLOAT3 ) );
file.write( reinterpret_cast< char* >( &model->m_OccludeeBoundingBoxExtent ), sizeof( DirectX::XMFLOAT3 ) );
size = model->m_OccluderObbs.size();
file.write( reinterpret_cast< char* >( &size ), sizeof( size_t ) );
if ( size > 0 )
{
file.write( reinterpret_cast< char* >( &model->m_OccluderObbs[ 0 ] ), sizeof( SOccluderObb ) * size );
}
size = model->m_OccluderCylinders.size();
file.write( reinterpret_cast< char* >( &size ), sizeof( size_t ) );
if ( size > 0 )
{
file.write( reinterpret_cast< char* >( &model->m_OccluderCylinders[ 0 ] ), sizeof( SOccluderCylinder ) * size );
}
size = model->m_Instances.size();
file.write( reinterpret_cast< char* >( &size ), sizeof( size_t ) );
for ( size_t j = 0; j < model->m_Instances.size(); ++j )
{
file.write( reinterpret_cast< char* >( &model->m_Instances[ j ].m_World ), sizeof( DirectX::XMFLOAT4X4 ) );
}
}
file.close();
}
void CModelSet::CreateMeshes(
ID3D12Device* device,
ID3D12GraphicsCommandList* command_list )
{
for ( SModel* model : m_Models )
{
model->m_Mesh.Create( device, command_list,
&model->m_Vertices, &model->m_Indices );
}
}
void CModelSet::CreateTexturesAndMaterials(
ID3D12Device* device,
ID3D12GraphicsCommandList* command_list,
NGraphics::CDescriptorHeap descriptor_heaps[ D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES ] )
{
assert( !m_Models.empty() );
size_t material_texture_count = m_Models[ 0 ]->m_TextureFilepathMap.size();
std::vector< std::wstring > texture_filepaths;
std::vector< UINT > materials;
std::vector< UINT > material_textures( material_texture_count );
for ( SModel* model : m_Models )
{
size_t material_texture_index = 0;
for ( std::pair<std::string, std::string> texture_filepath_entry : model->m_TextureFilepathMap )
{
std::wstring_convert< std::codecvt_utf8_utf16< wchar_t > > converter;
std::wstring texture_filepath = converter.from_bytes( m_Directory + "/" + texture_filepath_entry.second );
bool is_texture_found = false;
for ( size_t i = 0; i < texture_filepaths.size(); ++i )
{
if ( texture_filepaths[ i ] == texture_filepath )
{
material_textures[ material_texture_index++ ] = static_cast< UINT >( i );
is_texture_found = true;
break;
}
}
if ( !is_texture_found )
{
STexture texture;
texture.m_Resource = nullptr;
texture.m_ResourceUpload = nullptr;
texture.m_Handle = descriptor_heaps[ D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV ].GenerateHandle();
CreateDDSTextureFromFile( device, command_list, texture_filepath.c_str(), 0, false,
&texture.m_Resource, &texture.m_ResourceUpload,
texture.m_Handle.m_Cpu, nullptr );
m_Textures.push_back( texture );
texture_filepaths.push_back( texture_filepath );
material_textures[ material_texture_index++ ] = static_cast< UINT >( texture_filepaths.size() - 1 );
}
}
bool is_material_found = false;
UINT material_index = 0;
for ( size_t i = 0; i < materials.size(); i += material_texture_count )
{
is_material_found = true;
for ( size_t j = 0; j < material_texture_count; ++j )
{
if ( materials[ i + j ] != material_textures[ j ] )
{
is_material_found = false;
break;
}
}
if ( is_material_found )
{
break;
}
++material_index;
}
if ( !is_material_found )
{
materials.insert( materials.end(), material_textures.begin(), material_textures.end() );
}
model->m_MaterialIndex = material_index;
}
UINT material_buffer_size = static_cast< UINT >( sizeof( UINT ) * materials.size() );
HR( device->CreateCommittedResource(
&CD3DX12_HEAP_PROPERTIES( D3D12_HEAP_TYPE_DEFAULT ),
D3D12_HEAP_FLAG_NONE,
&CD3DX12_RESOURCE_DESC::Buffer( material_buffer_size ),
D3D12_RESOURCE_STATE_COPY_DEST,
nullptr,
IID_PPV_ARGS( &m_MaterialBuffer ) ) );
HR( device->CreateCommittedResource(
&CD3DX12_HEAP_PROPERTIES( D3D12_HEAP_TYPE_UPLOAD ),
D3D12_HEAP_FLAG_NONE,
&CD3DX12_RESOURCE_DESC::Buffer( material_buffer_size ),
D3D12_RESOURCE_STATE_GENERIC_READ,
nullptr,
IID_PPV_ARGS( &m_MaterialBufferUpload ) ) );
BYTE* mapped_material_buffer_upload = nullptr;
HR( m_MaterialBufferUpload->Map( 0, &CD3DX12_RANGE( 0, 0 ), reinterpret_cast< void** >( &mapped_material_buffer_upload ) ) );
memcpy( mapped_material_buffer_upload, materials.data(), material_buffer_size );
m_MaterialBufferUpload->Unmap( 0, &CD3DX12_RANGE( 0, 0 ) );
command_list->CopyBufferRegion( m_MaterialBuffer, 0, m_MaterialBufferUpload, 0, material_buffer_size );
command_list->ResourceBarrier( 1, &CD3DX12_RESOURCE_BARRIER::Transition(
m_MaterialBuffer, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE ) );
m_MaterialBufferSrv = descriptor_heaps[ D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV ].GenerateHandle();
D3D12_SHADER_RESOURCE_VIEW_DESC srv_desc;
ZeroMemory( &srv_desc, sizeof( srv_desc ) );
srv_desc.Format = DXGI_FORMAT_UNKNOWN;
srv_desc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER;
srv_desc.Buffer.NumElements = static_cast< UINT >( materials.size() / material_texture_count );
srv_desc.Buffer.StructureByteStride = static_cast< UINT >( material_texture_count * sizeof( UINT ) );
srv_desc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_NONE;
srv_desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
device->CreateShaderResourceView( m_MaterialBuffer, &srv_desc, m_MaterialBufferSrv.m_Cpu );
}
void CModelSet::CreateWorldMatrixBuffer(
ID3D12Device* device,
ID3D12GraphicsCommandList* command_list,
NGraphics::CDescriptorHeap descriptor_heaps[ D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES ] )
{
m_WorldMatrixBufferSize = sizeof( DirectX::XMFLOAT4X4 ) * m_InstanceCount;
HR( device->CreateCommittedResource(
&CD3DX12_HEAP_PROPERTIES( D3D12_HEAP_TYPE_DEFAULT ),
D3D12_HEAP_FLAG_NONE,
&CD3DX12_RESOURCE_DESC::Buffer( m_WorldMatrixBufferSize ),
D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE,
nullptr,
IID_PPV_ARGS( &m_WorldMatrixBuffer ) ) );
HR( device->CreateCommittedResource(
&CD3DX12_HEAP_PROPERTIES( D3D12_HEAP_TYPE_UPLOAD ),
D3D12_HEAP_FLAG_NONE,
&CD3DX12_RESOURCE_DESC::Buffer( m_WorldMatrixBufferSize ),
D3D12_RESOURCE_STATE_GENERIC_READ,
nullptr,
IID_PPV_ARGS( &m_WorldMatrixBufferUpload ) ) );
DirectX::XMFLOAT4X4* mapped_world_matrix_buffer_upload = nullptr;
HR( m_WorldMatrixBufferUpload->Map( 0, &CD3DX12_RANGE( 0, 0 ), reinterpret_cast< void** >( &mapped_world_matrix_buffer_upload ) ) );
UINT world_matrix_buffer_offset = 0;
for ( SModel* model : m_Models )
{
model->m_MappedWorldMatrixBuffer = mapped_world_matrix_buffer_upload;
mapped_world_matrix_buffer_upload += static_cast< UINT >( model->m_Instances.size() );
world_matrix_buffer_offset += static_cast< UINT >( model->m_Instances.size() );
}
m_WorldMatrixBufferSrv = descriptor_heaps[ D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV ].GenerateHandle();
D3D12_SHADER_RESOURCE_VIEW_DESC srv_desc;
ZeroMemory( &srv_desc, sizeof( srv_desc ) );
srv_desc.Format = DXGI_FORMAT_UNKNOWN;
srv_desc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER;
srv_desc.Buffer.NumElements = m_InstanceCount;
srv_desc.Buffer.StructureByteStride = sizeof( DirectX::XMFLOAT4X4 );
srv_desc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_NONE;
srv_desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
device->CreateShaderResourceView( m_WorldMatrixBuffer, &srv_desc, m_WorldMatrixBufferSrv.m_Cpu );
UpdateWorldMatrixBuffer( command_list );
}
void CModelSet::CreateInstanceMappingsBuffers(
ID3D12Device* device,
ID3D12GraphicsCommandList* command_list,
NGraphics::CDescriptorHeap descriptor_heaps[ D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES ] )
{
UINT instance_model_mappings_buffer_size = m_InstanceCount * sizeof( UINT );
UINT model_instance_offset_buffer_size = static_cast< UINT >( m_Models.size() ) * sizeof( UINT );
m_ModelInstanceCountBufferSize = static_cast< UINT >( m_Models.size() ) * sizeof( UINT );
m_InstanceIndexMappingsBufferSize = m_InstanceCount * sizeof( UINT );
HR( device->CreateCommittedResource(
&CD3DX12_HEAP_PROPERTIES( D3D12_HEAP_TYPE_DEFAULT ),
D3D12_HEAP_FLAG_NONE,
&CD3DX12_RESOURCE_DESC::Buffer( instance_model_mappings_buffer_size ),
D3D12_RESOURCE_STATE_COPY_DEST,
nullptr,
IID_PPV_ARGS( &m_InstanceModelMappingsBuffer ) ) );
HR( device->CreateCommittedResource(
&CD3DX12_HEAP_PROPERTIES( D3D12_HEAP_TYPE_UPLOAD ),
D3D12_HEAP_FLAG_NONE,
&CD3DX12_RESOURCE_DESC::Buffer( instance_model_mappings_buffer_size ),
D3D12_RESOURCE_STATE_GENERIC_READ,
nullptr,
IID_PPV_ARGS( &m_InstanceModelMappingsBufferUpload ) ) );
HR( device->CreateCommittedResource(
&CD3DX12_HEAP_PROPERTIES( D3D12_HEAP_TYPE_DEFAULT ),
D3D12_HEAP_FLAG_NONE,
&CD3DX12_RESOURCE_DESC::Buffer( model_instance_offset_buffer_size ),
D3D12_RESOURCE_STATE_COPY_DEST,
nullptr,
IID_PPV_ARGS( &m_ModelInstanceOffsetBuffer ) ) );
HR( device->CreateCommittedResource(
&CD3DX12_HEAP_PROPERTIES( D3D12_HEAP_TYPE_UPLOAD ),
D3D12_HEAP_FLAG_NONE,
&CD3DX12_RESOURCE_DESC::Buffer( model_instance_offset_buffer_size ),
D3D12_RESOURCE_STATE_GENERIC_READ,
nullptr,
IID_PPV_ARGS( &m_ModelInstanceOffsetBufferUpload ) ) );
HR( device->CreateCommittedResource(
&CD3DX12_HEAP_PROPERTIES( D3D12_HEAP_TYPE_DEFAULT ),
D3D12_HEAP_FLAG_NONE,
&CD3DX12_RESOURCE_DESC::Buffer( m_ModelInstanceCountBufferSize, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS ),
D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE,
nullptr,
IID_PPV_ARGS( &m_ModelInstanceCountBuffer ) ) );
HR( device->CreateCommittedResource(
&CD3DX12_HEAP_PROPERTIES( D3D12_HEAP_TYPE_UPLOAD ),
D3D12_HEAP_FLAG_NONE,
&CD3DX12_RESOURCE_DESC::Buffer( m_ModelInstanceCountBufferSize ),
D3D12_RESOURCE_STATE_GENERIC_READ,
nullptr,
IID_PPV_ARGS( &m_ModelInstanceCountBufferReset ) ) );
HR( device->CreateCommittedResource(
&CD3DX12_HEAP_PROPERTIES( D3D12_HEAP_TYPE_DEFAULT ),
D3D12_HEAP_FLAG_NONE,
&CD3DX12_RESOURCE_DESC::Buffer( m_InstanceIndexMappingsBufferSize, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS ),
D3D12_RESOURCE_STATE_COPY_DEST,
nullptr,
IID_PPV_ARGS( &m_InstanceIndexMappingsBuffer ) ) );
HR( device->CreateCommittedResource(
&CD3DX12_HEAP_PROPERTIES( D3D12_HEAP_TYPE_UPLOAD ),
D3D12_HEAP_FLAG_NONE,
&CD3DX12_RESOURCE_DESC::Buffer( m_InstanceIndexMappingsBufferSize ),
D3D12_RESOURCE_STATE_GENERIC_READ,
nullptr,
IID_PPV_ARGS( &m_InstanceIndexMappingsBufferUpload ) ) );
UINT* mapped_instance_model_mappings_buffer_upload = nullptr;
UINT* mapped_model_instance_offset_buffer_upload = nullptr;
UINT* mapped_model_instance_count_buffer_reset = nullptr;
UINT* mapped_instance_index_mappings_upload = nullptr;
HR( m_InstanceModelMappingsBufferUpload->Map( 0, &CD3DX12_RANGE( 0, 0 ), reinterpret_cast< void** >( &mapped_instance_model_mappings_buffer_upload ) ) );
HR( m_ModelInstanceOffsetBufferUpload->Map( 0, &CD3DX12_RANGE( 0, 0 ), reinterpret_cast< void** >( &mapped_model_instance_offset_buffer_upload ) ) );
HR( m_ModelInstanceCountBufferReset->Map( 0, &CD3DX12_RANGE( 0, 0 ), reinterpret_cast< void** >( &mapped_model_instance_count_buffer_reset ) ) );
HR( m_InstanceIndexMappingsBufferUpload->Map( 0, &CD3DX12_RANGE( 0, 0 ), reinterpret_cast< void** >( &mapped_instance_index_mappings_upload ) ) );
UINT model_instance_offset = 0;
for ( UINT i = 0; i < static_cast< UINT >( m_Models.size() ); ++i )
{
for ( UINT j = 0; j < static_cast< UINT >( m_Models[ i ]->m_Instances.size() ); ++j )
{
*mapped_instance_model_mappings_buffer_upload = i;
++mapped_instance_model_mappings_buffer_upload;
mapped_instance_index_mappings_upload[ model_instance_offset + j ] = model_instance_offset + j;
}
*mapped_model_instance_offset_buffer_upload = model_instance_offset;
++mapped_model_instance_offset_buffer_upload;
model_instance_offset += static_cast< UINT >( m_Models[ i ]->m_Instances.size() );
}
ZeroMemory( mapped_model_instance_count_buffer_reset, m_ModelInstanceCountBufferSize );
m_InstanceModelMappingsBufferUpload->Unmap( 0, &CD3DX12_RANGE( 0, 0 ) );
m_ModelInstanceOffsetBufferUpload->Unmap( 0, &CD3DX12_RANGE( 0, 0 ) );
m_ModelInstanceCountBufferReset->Unmap( 0, &CD3DX12_RANGE( 0, 0 ) );
m_InstanceIndexMappingsBufferUpload->Unmap( 0, &CD3DX12_RANGE( 0, 0 ) );
command_list->CopyBufferRegion( m_InstanceModelMappingsBuffer, 0, m_InstanceModelMappingsBufferUpload, 0, instance_model_mappings_buffer_size );
command_list->CopyBufferRegion( m_ModelInstanceOffsetBuffer, 0, m_ModelInstanceOffsetBufferUpload, 0, model_instance_offset_buffer_size );
command_list->CopyBufferRegion( m_InstanceIndexMappingsBuffer, 0, m_InstanceIndexMappingsBufferUpload, 0, m_InstanceIndexMappingsBufferSize );
const D3D12_RESOURCE_BARRIER post_copy_barriers[] =
{
CD3DX12_RESOURCE_BARRIER::Transition( m_InstanceModelMappingsBuffer, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE ),
CD3DX12_RESOURCE_BARRIER::Transition( m_ModelInstanceOffsetBuffer, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE ),
CD3DX12_RESOURCE_BARRIER::Transition( m_InstanceIndexMappingsBuffer, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE ),
};
command_list->ResourceBarrier( _countof( post_copy_barriers ), post_copy_barriers );
m_InstanceModelMappingsBufferSrv = descriptor_heaps[ D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV ].GenerateHandle();
m_ModelInstanceOffsetBufferSrv = descriptor_heaps[ D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV ].GenerateHandle();
m_ModelInstanceCountBufferUav = descriptor_heaps[ D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV ].GenerateHandle();
m_InstanceIndexMappingsBufferUav = descriptor_heaps[ D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV ].GenerateHandle();
m_ModelInstanceCountBufferSrv = descriptor_heaps[ D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV ].GenerateHandle();
m_InstanceIndexMappingsBufferSrv = descriptor_heaps[ D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV ].GenerateHandle();
D3D12_SHADER_RESOURCE_VIEW_DESC srv_desc;
D3D12_UNORDERED_ACCESS_VIEW_DESC uav_desc;
ZeroMemory( &srv_desc, sizeof( srv_desc ) );
srv_desc.Format = DXGI_FORMAT_UNKNOWN;
srv_desc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER;
srv_desc.Buffer.NumElements = m_InstanceCount;
srv_desc.Buffer.StructureByteStride = sizeof( UINT );
srv_desc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_NONE;
srv_desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
device->CreateShaderResourceView( m_InstanceModelMappingsBuffer, &srv_desc, m_InstanceModelMappingsBufferSrv.m_Cpu );
ZeroMemory( &srv_desc, sizeof( srv_desc ) );
srv_desc.Format = DXGI_FORMAT_UNKNOWN;
srv_desc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER;
srv_desc.Buffer.NumElements = static_cast< UINT >( m_Models.size() );
srv_desc.Buffer.StructureByteStride = sizeof( UINT );
srv_desc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_NONE;
srv_desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
device->CreateShaderResourceView( m_ModelInstanceOffsetBuffer, &srv_desc, m_ModelInstanceOffsetBufferSrv.m_Cpu );
ZeroMemory( &uav_desc, sizeof( uav_desc ) );
uav_desc.Format = DXGI_FORMAT_UNKNOWN;
uav_desc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
uav_desc.Buffer.NumElements = static_cast< UINT >( m_Models.size() );
uav_desc.Buffer.StructureByteStride = sizeof( UINT );
uav_desc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_NONE;
device->CreateUnorderedAccessView( m_ModelInstanceCountBuffer, nullptr, &uav_desc, m_ModelInstanceCountBufferUav.m_Cpu );
ZeroMemory( &uav_desc, sizeof( uav_desc ) );
uav_desc.Format = DXGI_FORMAT_UNKNOWN;
uav_desc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
uav_desc.Buffer.NumElements = m_InstanceCount;
uav_desc.Buffer.StructureByteStride = sizeof( UINT );
uav_desc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_NONE;
device->CreateUnorderedAccessView( m_InstanceIndexMappingsBuffer, nullptr, &uav_desc, m_InstanceIndexMappingsBufferUav.m_Cpu );
ZeroMemory( &srv_desc, sizeof( srv_desc ) );
srv_desc.Format = DXGI_FORMAT_UNKNOWN;
srv_desc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER;
srv_desc.Buffer.NumElements = static_cast< UINT >( m_Models.size() );
srv_desc.Buffer.StructureByteStride = sizeof( UINT );
srv_desc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_NONE;
srv_desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
device->CreateShaderResourceView( m_ModelInstanceCountBuffer, &srv_desc, m_ModelInstanceCountBufferSrv.m_Cpu );
ZeroMemory( &srv_desc, sizeof( srv_desc ) );
srv_desc.Format = DXGI_FORMAT_UNKNOWN;
srv_desc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER;
srv_desc.Buffer.NumElements = m_InstanceCount;
srv_desc.Buffer.StructureByteStride = sizeof( UINT );
srv_desc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_NONE;
srv_desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
device->CreateShaderResourceView( m_InstanceIndexMappingsBuffer, &srv_desc, m_InstanceIndexMappingsBufferSrv.m_Cpu );
}
void CModelSet::CreateCommandBuffers(
ID3D12Device* device,
ID3D12GraphicsCommandList* command_list,
NGraphics::CDescriptorHeap descriptor_heaps[ D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES ] )
{
UINT input_command_buffer_size = static_cast< UINT >( sizeof( SIndirectCommand ) * m_Models.size() );
HR( device->CreateCommittedResource(
&CD3DX12_HEAP_PROPERTIES( D3D12_HEAP_TYPE_DEFAULT ),
D3D12_HEAP_FLAG_NONE,
&CD3DX12_RESOURCE_DESC::Buffer( input_command_buffer_size ),
D3D12_RESOURCE_STATE_COPY_DEST,
nullptr,
IID_PPV_ARGS( &m_InputCommandBuffer ) ) );
HR( device->CreateCommittedResource(
&CD3DX12_HEAP_PROPERTIES( D3D12_HEAP_TYPE_UPLOAD ),
D3D12_HEAP_FLAG_NONE,
&CD3DX12_RESOURCE_DESC::Buffer( input_command_buffer_size ),
D3D12_RESOURCE_STATE_GENERIC_READ,
nullptr,
IID_PPV_ARGS( &m_InputCommandBufferUpload ) ) );
UINT output_command_buffer_misalignment = input_command_buffer_size % D3D12_UAV_COUNTER_PLACEMENT_ALIGNMENT;
m_OutputCommandBufferCounterOffset = input_command_buffer_size + ( output_command_buffer_misalignment > 0 ? D3D12_UAV_COUNTER_PLACEMENT_ALIGNMENT - output_command_buffer_misalignment : 0 );
UINT output_command_buffer_size = m_OutputCommandBufferCounterOffset + sizeof( UINT );
HR( device->CreateCommittedResource(
&CD3DX12_HEAP_PROPERTIES( D3D12_HEAP_TYPE_DEFAULT ),
D3D12_HEAP_FLAG_NONE,
&CD3DX12_RESOURCE_DESC::Buffer( output_command_buffer_size, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS ),
D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
nullptr,
IID_PPV_ARGS( &m_OutputCommandBuffer ) ) );
HR( device->CreateCommittedResource(
&CD3DX12_HEAP_PROPERTIES( D3D12_HEAP_TYPE_UPLOAD ),
D3D12_HEAP_FLAG_NONE,
&CD3DX12_RESOURCE_DESC::Buffer( sizeof( UINT ) ),
D3D12_RESOURCE_STATE_GENERIC_READ,
nullptr,
IID_PPV_ARGS( &m_OutputCommandBufferCounterReset ) ) );
SIndirectCommand* mapped_input_command_buffer_upload = nullptr;
UINT* mapped_output_command_buffer_counter_reset = nullptr;
HR( m_InputCommandBufferUpload->Map( 0, &CD3DX12_RANGE( 0, 0 ), reinterpret_cast< void** >( &mapped_input_command_buffer_upload ) ) );
HR( m_OutputCommandBufferCounterReset->Map( 0, &CD3DX12_RANGE( 0, 0 ), reinterpret_cast< void** >( &mapped_output_command_buffer_counter_reset ) ) );
UINT instance_offset = 0;
for ( size_t i = 0; i < m_Models.size(); ++i )
{
mapped_input_command_buffer_upload[ i ].m_InstanceOffset = instance_offset;
mapped_input_command_buffer_upload[ i ].m_MaterialIndex = m_Models[ i ]->m_MaterialIndex;
mapped_input_command_buffer_upload[ i ].m_VertexBufferView = m_Models[ i ]->m_Mesh.GetVertexBufferView();
mapped_input_command_buffer_upload[ i ].m_IndexBufferView = m_Models[ i ]->m_Mesh.GetIndexBufferView();
mapped_input_command_buffer_upload[ i ].m_DrawArguments.IndexCountPerInstance = static_cast< UINT >( m_Models[ i ]->m_Indices.size() );
mapped_input_command_buffer_upload[ i ].m_DrawArguments.InstanceCount = static_cast< UINT >( m_Models[ i ]->m_Instances.size() );
mapped_input_command_buffer_upload[ i ].m_DrawArguments.StartIndexLocation = 0;
mapped_input_command_buffer_upload[ i ].m_DrawArguments.BaseVertexLocation = 0;
mapped_input_command_buffer_upload[ i ].m_DrawArguments.StartInstanceLocation = 0;
instance_offset += static_cast< UINT >( m_Models[ i ]->m_Instances.size() );
}
*mapped_output_command_buffer_counter_reset = 0;
m_InputCommandBufferUpload->Unmap( 0, &CD3DX12_RANGE( 0, 0 ) );
m_OutputCommandBufferCounterReset->Unmap( 0, &CD3DX12_RANGE( 0, 0 ) );
command_list->CopyBufferRegion( m_InputCommandBuffer, 0, m_InputCommandBufferUpload, 0, input_command_buffer_size );
command_list->ResourceBarrier( 1, &CD3DX12_RESOURCE_BARRIER::Transition(
m_InputCommandBuffer, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE ) );
m_InputCommandBufferSrv = descriptor_heaps[ D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV ].GenerateHandle();
m_OutputCommandBufferUav = descriptor_heaps[ D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV ].GenerateHandle();
D3D12_SHADER_RESOURCE_VIEW_DESC srv_desc;
D3D12_UNORDERED_ACCESS_VIEW_DESC uav_desc;
ZeroMemory( &srv_desc, sizeof( srv_desc ) );
srv_desc.Format = DXGI_FORMAT_UNKNOWN;
srv_desc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER;
srv_desc.Buffer.NumElements = static_cast< UINT >( m_Models.size() );
srv_desc.Buffer.StructureByteStride = sizeof( SIndirectCommand );
srv_desc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_NONE;
srv_desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
device->CreateShaderResourceView( m_InputCommandBuffer, &srv_desc, m_InputCommandBufferSrv.m_Cpu );
ZeroMemory( &uav_desc, sizeof( uav_desc ) );
uav_desc.Format = DXGI_FORMAT_UNKNOWN;
uav_desc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
uav_desc.Buffer.NumElements = static_cast< UINT >( m_Models.size() );
uav_desc.Buffer.StructureByteStride = sizeof( SIndirectCommand );
uav_desc.Buffer.CounterOffsetInBytes = m_OutputCommandBufferCounterOffset;
uav_desc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_NONE;
device->CreateUnorderedAccessView( m_OutputCommandBuffer, m_OutputCommandBuffer, &uav_desc, m_OutputCommandBufferUav.m_Cpu );
} | 45.85744 | 193 | 0.700992 | marcussvensson92 |
ae0fc2433cb8618561f8767d7d610762b4fcf790 | 2,675 | cc | C++ | legacy/src/game/event.cc | hengruo/RuneSim | f975374c7ce52baf8f226e8485e2e6e155d52cb2 | [
"Apache-2.0"
] | 9 | 2020-04-28T13:47:07.000Z | 2020-10-03T16:05:53.000Z | legacy/src/game/event.cc | hengruo/RuneSim | f975374c7ce52baf8f226e8485e2e6e155d52cb2 | [
"Apache-2.0"
] | null | null | null | legacy/src/game/event.cc | hengruo/RuneSim | f975374c7ce52baf8f226e8485e2e6e155d52cb2 | [
"Apache-2.0"
] | 4 | 2020-04-27T08:13:09.000Z | 2020-06-02T02:48:07.000Z | #include "event.h"
CastEvent::CastEvent(RSID PlayerId, RSID SpellId) : playerId(PlayerId), spellId(SpellId) {}
DeclAttackEvent::DeclAttackEvent(RSID PlayerId, RSID AttackerId, i8 Position)
: playerId(PlayerId), attackerId(AttackerId), position(Position) {}
DeclBlockEvent::DeclBlockEvent(RSID PlayerId, RSID AttackerId, i8 Position)
: playerId(PlayerId), attackerId(AttackerId), position(Position) {}
DieEvent::DieEvent(RSID PlayerId, RSID DeadId) : playerId(PlayerId), deadId(DeadId) {}
DrawCardEvent::DrawCardEvent(RSID PlayerId, RSID IndeckCardId) : playerId(PlayerId), indeckCardId(IndeckCardId) {}
GetCardEvent::GetCardEvent(RSID PlayerId, RSID CardEntityId) : playerId(PlayerId), cardEntityId(CardEntityId) {}
LevelUpEvent::LevelUpEvent(RSID PlayerId, RSID ChampionId) : playerId(PlayerId), championId(ChampionId) {}
NexusStrikeEvent::NexusStrikeEvent(RSID AttackingPlayerId, RSID AttackedNexusId, i64 Damage) : attackingPlayerId(
AttackingPlayerId), attackedNexusId(AttackedNexusId), damage(Damage) {}
PlayEvent::PlayEvent(RSID PlayerId, RSID InhandCardId) : playerId(PlayerId), inhandCardId(InhandCardId) {}
PutSpell::PutSpell(RSID PlayerId, RSID SpellId) : playerId(PlayerId), spellId(SpellId) {}
StartRoundEvent::StartRoundEvent(i32 Round) : round(Round) {}
StrikeEvent::StrikeEvent(RSID PlayerId, RSID StrikerId) : playerId(PlayerId), strikerId(StrikerId) {}
SummonEvent::SummonEvent(RSID PlayerId, RSID SummoneeId) : playerId(PlayerId), summoneeId(SummoneeId) {}
TargetEvent::TargetEvent(RSID PlayerId, RSID TargetedId) : playerId(PlayerId), targetedId(TargetedId) {}
Event::Event(const LevelUpEvent &LevelUp) : levelUp(LevelUp) {}
Event::Event(const AnyEvent &Any) : any(Any) {}
Event::Event(const CastEvent &Cast) : cast(Cast) {}
Event::Event(const DeclAttackEvent &DeclAttack) : declAttack(DeclAttack) {}
Event::Event(const DeclBlockEvent &DeclBlock) : declBlock(DeclBlock) {}
Event::Event(const DieEvent &Die) : die(Die) {}
Event::Event(const DrawCardEvent &DrawCard) : drawCard(DrawCard) {}
Event::Event(const EndRoundEvent &EndRound) : endRound(EndRound) {}
Event::Event(const EnlightenEvent &Enlighten) : enlighten(Enlighten) {}
Event::Event(const GetCardEvent &GetCard) : getCard(GetCard) {}
Event::Event(const NexusStrikeEvent &NexusStrike) : nexusStrike(NexusStrike) {}
Event::Event(const PlayEvent &Play) : play(Play) {}
Event::Event(const PutSpell &PutSpell) : putSpell(PutSpell) {}
Event::Event(const StartRoundEvent &StartRound) : startRound(StartRound) {}
Event::Event(const StrikeEvent &Strike) : strike(Strike) {}
Event::Event(const SummonEvent &Summon) : summon(Summon) {}
Event::Event(const TargetEvent &Target) : target(Target) {}
| 74.305556 | 114 | 0.776075 | hengruo |
ae11b66c536b7876bda8e855c60424e8136d3641 | 10,081 | cpp | C++ | test/type/logic/And.main.cpp | AnantaYudica/basic | dcbf8c9eebb42a4e6a66b3c56ebc3a7e30626950 | [
"MIT"
] | null | null | null | test/type/logic/And.main.cpp | AnantaYudica/basic | dcbf8c9eebb42a4e6a66b3c56ebc3a7e30626950 | [
"MIT"
] | 178 | 2018-08-08T04:04:27.000Z | 2019-12-15T01:47:58.000Z | test/type/logic/And.main.cpp | AnantaYudica/basic | dcbf8c9eebb42a4e6a66b3c56ebc3a7e30626950 | [
"MIT"
] | null | null | null | #include "type/logic/And.h"
#define USING_BASIC_TEST_MEMORY
#include "Test.h"
BASIC_TEST_CONSTRUCT;
#include "test/Base.h"
#include "test/Case.h"
#include "test/Message.h"
#include "test/Variable.h"
#include "test/var/At.h"
#include <typeinfo>
#include <type_traits>
struct CaseVTa {}; // case value and target
struct CaseV {}; // case value
template<typename TAnd, bool TValue>
using VariableTestAnd = basic::test::Variable<
TAnd,
basic::test::type::Value<bool, TValue>,
basic::test::val::Function<const char*(bool&&)>>;
constexpr std::size_t IAnd = 0;
constexpr std::size_t ITypeValValue = 1;
constexpr std::size_t IValFuncBoolToCString = 2;
template<std::size_t I>
using ArgTypeName = basic::test::msg::arg::type::Name<I>;
template<std::size_t I>
using ArgTypeValue = basic::test::msg::arg::type::Value<I>;
template<std::size_t I>
using ArgTypeParamName = basic::test::msg::arg::type::param::Name<I>;
template<std::size_t I, typename... TArgArgs>
using ArgValFunction = basic::test::msg::arg::val::Function<I, TArgArgs...>;
typedef basic::test::msg::Argument<CaseVTa,
ArgTypeName<IAnd>,
ArgValFunction<IValFuncBoolToCString,
ArgTypeValue<ITypeValValue>>> ArgCaseVTa;
typedef basic::test::msg::Base<CaseVTa, char, ArgCaseVTa,
ArgCaseVTa, ArgCaseVTa> MsgBaseCaseVTa;
typedef basic::test::msg::Argument<CaseV,
ArgTypeName<IAnd>,
ArgTypeName<IAnd>> ArgCaseV;
typedef basic::test::msg::Base<CaseV, char, ArgCaseV,
ArgCaseV, ArgCaseV> MsgBaseCaseV;
template<typename TCases, typename... TVars>
class TestAnd :
public MsgBaseCaseVTa,
public MsgBaseCaseV,
public basic::test::Message<BASIC_TEST, TestAnd<TCases, TVars...>>,
public basic::test::Case<TestAnd<TCases, TVars...>, TCases>,
public basic::test::Base<TestAnd<TCases, TVars...>, TVars...>
{
public:
typedef basic::test::Base<TestAnd<TCases, TVars...>, TVars...> BaseType;
typedef basic::test::Message<BASIC_TEST,
TestAnd<TCases, TVars...>> BaseMessageType;
typedef basic::test::Case<TestAnd<TCases, TVars...>,
TCases> BaseCaseType;
protected:
using MsgBaseCaseVTa::SetFormat;
using MsgBaseCaseV::SetFormat;
public:
using MsgBaseCaseVTa::Format;
using MsgBaseCaseV::Format;
using MsgBaseCaseVTa::Argument;
using MsgBaseCaseV::Argument;
public:
using BaseType::Run;
using BaseCaseType::Run;
public:
TestAnd(TVars&... vars) :
BaseType(*this, vars...),
BaseMessageType(*this),
BaseCaseType(*this)
{
basic::test::msg::base::Info info;
basic::test::msg::base::Debug debug;
basic::test::msg::base::Error err;
CaseVTa case_value_and_target;
SetFormat(info, case_value_and_target,
"test compare between %s::value and %s\n");
SetFormat(debug, case_value_and_target,
"test compare between %s::value and %s\n");
SetFormat(err, case_value_and_target,
"error %s::value is not same with %s\n");
CaseV case_value;
SetFormat(info, case_value,
"test compare between %s::value and %s::Value\n");
SetFormat(debug, case_value,
"test compare between %s::value and %s::Value\n");
SetFormat(err, case_value,
"error %s::value is not same with %s::Value\n");
}
template<typename TAnd, bool TValue>
bool Result(const CaseVTa&, VariableTestAnd<TAnd, TValue>& var)
{
return TAnd::value == TValue;
}
template<typename TAnd, bool TValue>
bool Result(const CaseV&, VariableTestAnd<TAnd, TValue>& var)
{
return TAnd::value == TAnd::Value;
}
};
using Cases = basic::test::type::Parameter<CaseVTa, CaseV>;
BASIC_TEST_TYPE_NAME("std::true_type", std::true_type);
BASIC_TEST_TYPE_NAME("std::false_type", std::false_type);
BASIC_TEST_TYPE_NAME("void", void);
#ifdef _WIN32
template<typename TTrue, typename TArg, typename... TArgs>
struct basic::test::type::Name<basic::type::logic::And<TTrue, TArg, TArgs...>>
#else
template<typename... TArgs>
struct basic::test::type::Name<basic::type::logic::And<TArgs...>>
#endif
{
static basic::test::CString<char> CStr()
{
static char _format_cstr[] = "basic::type::logic::And<%s>";
#ifdef _WIN32
const auto& param_cstr = basic::test::type::param::Name<
basic::test::type::Parameter<TTrue, TArg, TArgs...>>::CStr();
#else
const auto& param_cstr = basic::test::type::param::Name<
basic::test::type::Parameter<TArgs...>>::CStr();
#endif
return basic::test::cstr::Format(sizeof(_format_cstr) +
param_cstr.Size(), _format_cstr, *param_cstr);\
}
};
const char* true_cstr = "true";
const char* false_cstr = "false";
const char* BoolToString(bool&& b)
{
return b ? true_cstr : false_cstr;
}
using TDefaultAnd1_1 = basic::type::logic::And<std::true_type, std::false_type>;
using TDefaultAnd1_2 = basic::type::logic::And<std::true_type, std::true_type>;
typedef VariableTestAnd<TDefaultAnd1_1, false> T1Var1;
typedef VariableTestAnd<TDefaultAnd1_2, true> T1Var2;
T1Var1 t1_var1(&BoolToString);
T1Var2 t1_var2(&BoolToString);
REGISTER_TEST(t1, new TestAnd<Cases, T1Var1, T1Var2>(t1_var1,
t1_var2));
using TDefaultAnd2_1 = basic::type::logic::And<std::true_type,
std::false_type, std::false_type>;
using TDefaultAnd2_2 = basic::type::logic::And<std::true_type,
std::false_type, std::true_type>;
using TDefaultAnd2_3 = basic::type::logic::And<std::true_type,
std::true_type, std::false_type>;
using TDefaultAnd2_4 = basic::type::logic::And<std::true_type,
std::true_type, std::true_type>;
typedef VariableTestAnd<TDefaultAnd2_1, false> T2Var1;
typedef VariableTestAnd<TDefaultAnd2_2, false> T2Var2;
typedef VariableTestAnd<TDefaultAnd2_3, false> T2Var3;
typedef VariableTestAnd<TDefaultAnd2_4, true> T2Var4;
T2Var1 t2_var1(&BoolToString);
T2Var2 t2_var2(&BoolToString);
T2Var3 t2_var3(&BoolToString);
T2Var4 t2_var4(&BoolToString);
REGISTER_TEST(t2, new TestAnd<Cases, T2Var1, T2Var2, T2Var3,
T2Var4>(t2_var1, t2_var2, t2_var3, t2_var4));
using TDefaultAnd4_1 = basic::type::logic::And<std::true_type,
std::false_type, std::false_type, std::false_type, std::false_type>;
using TDefaultAnd4_2 = basic::type::logic::And<std::true_type,
std::false_type, std::false_type, std::false_type, std::true_type>;
using TDefaultAnd4_3 = basic::type::logic::And<std::true_type,
std::false_type, std::false_type, std::true_type, std::false_type>;
using TDefaultAnd4_4 = basic::type::logic::And<std::true_type,
std::false_type, std::false_type, std::true_type, std::true_type>;
using TDefaultAnd4_5 = basic::type::logic::And<std::true_type,
std::false_type, std::true_type, std::false_type, std::false_type>;
using TDefaultAnd4_6 = basic::type::logic::And<std::true_type,
std::false_type, std::true_type, std::false_type, std::true_type>;
using TDefaultAnd4_7 = basic::type::logic::And<std::true_type,
std::false_type, std::true_type, std::true_type, std::false_type>;
using TDefaultAnd4_8 = basic::type::logic::And<std::true_type,
std::false_type, std::true_type, std::true_type, std::true_type>;
using TDefaultAnd4_9 = basic::type::logic::And<std::true_type,
std::true_type, std::false_type, std::false_type, std::false_type>;
using TDefaultAnd4_10 = basic::type::logic::And<std::true_type,
std::true_type, std::false_type, std::false_type, std::true_type>;
using TDefaultAnd4_11 = basic::type::logic::And<std::true_type,
std::true_type, std::false_type, std::true_type, std::false_type>;
using TDefaultAnd4_12 = basic::type::logic::And<std::true_type,
std::true_type, std::false_type, std::true_type, std::true_type>;
using TDefaultAnd4_13 = basic::type::logic::And<std::true_type,
std::true_type, std::true_type, std::false_type, std::false_type>;
using TDefaultAnd4_14 = basic::type::logic::And<std::true_type,
std::true_type, std::true_type, std::false_type, std::true_type>;
using TDefaultAnd4_15 = basic::type::logic::And<std::true_type,
std::true_type, std::true_type, std::true_type, std::false_type>;
using TDefaultAnd4_16 = basic::type::logic::And<std::true_type,
std::true_type, std::true_type, std::true_type, std::true_type>;
typedef VariableTestAnd<TDefaultAnd4_1, false> T3Var1;
typedef VariableTestAnd<TDefaultAnd4_2, false> T3Var2;
typedef VariableTestAnd<TDefaultAnd4_3, false> T3Var3;
typedef VariableTestAnd<TDefaultAnd4_4, false> T3Var4;
typedef VariableTestAnd<TDefaultAnd4_5, false> T3Var5;
typedef VariableTestAnd<TDefaultAnd4_6, false> T3Var6;
typedef VariableTestAnd<TDefaultAnd4_7, false> T3Var7;
typedef VariableTestAnd<TDefaultAnd4_8, false> T3Var8;
typedef VariableTestAnd<TDefaultAnd4_9, false> T3Var9;
typedef VariableTestAnd<TDefaultAnd4_10, false> T3Var10;
typedef VariableTestAnd<TDefaultAnd4_11, false> T3Var11;
typedef VariableTestAnd<TDefaultAnd4_12, false> T3Var12;
typedef VariableTestAnd<TDefaultAnd4_13, false> T3Var13;
typedef VariableTestAnd<TDefaultAnd4_14, false> T3Var14;
typedef VariableTestAnd<TDefaultAnd4_15, false> T3Var15;
typedef VariableTestAnd<TDefaultAnd4_16, true> T3Var16;
T3Var1 t3_var1(&BoolToString);
T3Var2 t3_var2(&BoolToString);
T3Var3 t3_var3(&BoolToString);
T3Var4 t3_var4(&BoolToString);
T3Var5 t3_var5(&BoolToString);
T3Var6 t3_var6(&BoolToString);
T3Var7 t3_var7(&BoolToString);
T3Var8 t3_var8(&BoolToString);
T3Var9 t3_var9(&BoolToString);
T3Var10 t3_var10(&BoolToString);
T3Var11 t3_var11(&BoolToString);
T3Var12 t3_var12(&BoolToString);
T3Var13 t3_var13(&BoolToString);
T3Var14 t3_var14(&BoolToString);
T3Var15 t3_var15(&BoolToString);
T3Var16 t3_var16(&BoolToString);
REGISTER_TEST(t3, new TestAnd<Cases, T3Var1, T3Var2, T3Var3, T3Var4, T3Var5,
T3Var6, T3Var7, T3Var8, T3Var9, T3Var10, T3Var11, T3Var12, T3Var13,
T3Var14, T3Var15, T3Var16>(t3_var1, t3_var2, t3_var3, t3_var4, t3_var5,
t3_var6, t3_var7, t3_var8, t3_var9, t3_var10, t3_var11, t3_var12,
t3_var13, t3_var14, t3_var15, t3_var16));
int main()
{
return RUN_TEST();
}
| 37.337037 | 80 | 0.716397 | AnantaYudica |
ae13b2316bf455bd9154221d528693bb9c139d71 | 778 | cpp | C++ | solved/10338 Mischievous Children.cpp | goutomroy/uva.onlinejudge | 5ce09d9e370ad78eabd0fd500ef77ce804e2d0f2 | [
"MIT"
] | null | null | null | solved/10338 Mischievous Children.cpp | goutomroy/uva.onlinejudge | 5ce09d9e370ad78eabd0fd500ef77ce804e2d0f2 | [
"MIT"
] | null | null | null | solved/10338 Mischievous Children.cpp | goutomroy/uva.onlinejudge | 5ce09d9e370ad78eabd0fd500ef77ce804e2d0f2 | [
"MIT"
] | null | null | null | // WRONG ANSWERE
#include<stdio.h>
#include<string.h>
char word[22],nline;
int time[22],len;
void main()
{
int tcase,i,j, k;
double N, fact;
scanf("%d%c",&tcase,&nline);
for(i=0;i<tcase;i++)
{
scanf("%s",word);
scanf("%c",&nline);
len = strlen(word);
if(len==1)
{
printf("Data set %d: 1\n",i+1);
continue;
}
for(j=0;j<20;j++)
time[j] = 1;
for(j=0;j<len;j++)
{
for( k=j+1; k<len; k++ )
{
if( word[j]==NULL)
break;
else if( word[j] == word[k] )
{
time[j]++;
word[k] = NULL;
}
}
}
N=1;
for(k=len;k>1;k--)
N = N*k;
for(j=0;j<len;j++)
{
for(fact = 1;time[j]>1;time[j]--)
fact = fact*time[j];
N = N/fact;
}
printf("Data set %d: %.0lf\n",i+1,N);
}
}
| 11.61194 | 39 | 0.458869 | goutomroy |
ae161ce585be03f44f9691664d2e5dfe6507241a | 6,759 | cpp | C++ | examples/main.cpp | DarkCaster/Micro-AES-Arduino | ebb1cbf89c2c8d971e9ea111eef2299789c56762 | [
"MIT"
] | null | null | null | examples/main.cpp | DarkCaster/Micro-AES-Arduino | ebb1cbf89c2c8d971e9ea111eef2299789c56762 | [
"MIT"
] | null | null | null | examples/main.cpp | DarkCaster/Micro-AES-Arduino | ebb1cbf89c2c8d971e9ea111eef2299789c56762 | [
"MIT"
] | null | null | null | #include <Arduino.h> //dummy arduino.h for compiling arduino code on desktop systems
#include <aes.h>
#include <cstdio>
#define BLKSZ 16
void verify(const uint8_t * const input, const uint8_t * const output, const uint8_t * const test)
{
//verify
bool verifyOk=true;
for(int i=0;i<BLKSZ;++i)
if(*(test+i)!=*(output+i))
{
verifyOk=false;
break;
}
printf("Input data : ");
for(int i=0;i<BLKSZ;++i)
printf("0x%02x ",*(input+i));
printf("<<END\n");
printf("Output data: ");
for(int i=0;i<BLKSZ;++i)
printf("0x%02x ",*(output+i));
printf("<<END\n");
printf("Test data : ");
for(int i=0;i<BLKSZ;++i)
printf("0x%02x ",*(test+i));
printf("<<END\n");
printf(verifyOk?"Verify OK.\n\n":"Verify failed!\n\n");
}
void encrypt128(const uint8_t * const key, const uint8_t * const input, const uint8_t * const output)
{
//copy input block
uint8_t test[BLKSZ];
for(int i=0;i<BLKSZ;++i)
*(test+i)=*(input+i);
//encrypt
aes_128_context_t context;
aes_128_init(&context, key);
aes_128_encrypt(&context, test);
printf("Encrypt AES128 test\n");
verify(input,output,test);
}
void decrypt128(const uint8_t * const key, const uint8_t * const input, const uint8_t * const output)
{
//copy input block
uint8_t test[BLKSZ];
for(int i=0;i<BLKSZ;++i)
*(test+i)=*(input+i);
//encrypt
aes_128_context_t context;
aes_128_init(&context, key);
aes_128_decrypt(&context, test);
printf("Decrypt AES128 test\n");
verify(input,output,test);
}
void encrypt192(const uint8_t * const key, const uint8_t * const input, const uint8_t * const output)
{
//copy input block
uint8_t test[BLKSZ];
for(int i=0;i<BLKSZ;++i)
*(test+i)=*(input+i);
//encrypt
aes_192_context_t context;
aes_192_init(&context, key);
aes_192_encrypt(&context, test);
printf("Encrypt AES192 test\n");
verify(input,output,test);
}
void decrypt192(const uint8_t * const key, const uint8_t * const input, const uint8_t * const output)
{
//copy input block
uint8_t test[BLKSZ];
for(int i=0;i<BLKSZ;++i)
*(test+i)=*(input+i);
//encrypt
aes_192_context_t context;
aes_192_init(&context, key);
aes_192_decrypt(&context, test);
printf("Decrypt AES192 test\n");
verify(input,output,test);
}
void encrypt256(const uint8_t * const key, const uint8_t * const input, const uint8_t * const output)
{
//copy input block
uint8_t test[BLKSZ];
for(int i=0;i<BLKSZ;++i)
*(test+i)=*(input+i);
//encrypt
aes_256_context_t context;
aes_256_init(&context, key);
aes_256_encrypt(&context, test);
printf("Encrypt AES256 test\n");
verify(input,output,test);
}
void decrypt256(const uint8_t * const key, const uint8_t * const input, const uint8_t * const output)
{
//copy input block
uint8_t test[BLKSZ];
for(int i=0;i<BLKSZ;++i)
*(test+i)=*(input+i);
//encrypt
aes_256_context_t context;
aes_256_init(&context, key);
aes_256_decrypt(&context, test);
printf("Decrypt AES256 test\n");
verify(input,output,test);
}
int main()
{
// using test vectors from this document: http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf
//F.1.1
//ECB-AES128.Encrypt
const uint8_t key_128[]={0x2b,0x7e,0x15,0x16,0x28,0xae,0xd2,0xa6,0xab,0xf7,0x15,0x88,0x09,0xcf,0x4f,0x3c};
const uint8_t plaintext1[]={0x6b,0xc1,0xbe,0xe2,0x2e,0x40,0x9f,0x96,0xe9,0x3d,0x7e,0x11,0x73,0x93,0x17,0x2a};
const uint8_t plaintext2[]={0xae,0x2d,0x8a,0x57,0x1e,0x03,0xac,0x9c,0x9e,0xb7,0x6f,0xac,0x45,0xaf,0x8e,0x51};
const uint8_t plaintext3[]={0x30,0xc8,0x1c,0x46,0xa3,0x5c,0xe4,0x11,0xe5,0xfb,0xc1,0x19,0x1a,0x0a,0x52,0xef};
const uint8_t plaintext4[]={0xf6,0x9f,0x24,0x45,0xdf,0x4f,0x9b,0x17,0xad,0x2b,0x41,0x7b,0xe6,0x6c,0x37,0x10};
const uint8_t ciphertext1_128[]={0x3a,0xd7,0x7b,0xb4,0x0d,0x7a,0x36,0x60,0xa8,0x9e,0xca,0xf3,0x24,0x66,0xef,0x97};
const uint8_t ciphertext2_128[]={0xf5,0xd3,0xd5,0x85,0x03,0xb9,0x69,0x9d,0xe7,0x85,0x89,0x5a,0x96,0xfd,0xba,0xaf};
const uint8_t ciphertext3_128[]={0x43,0xb1,0xcd,0x7f,0x59,0x8e,0xce,0x23,0x88,0x1b,0x00,0xe3,0xed,0x03,0x06,0x88};
const uint8_t ciphertext4_128[]={0x7b,0x0c,0x78,0x5e,0x27,0xe8,0xad,0x3f,0x82,0x23,0x20,0x71,0x04,0x72,0x5d,0xd4};
encrypt128(key_128,plaintext1,ciphertext1_128);
encrypt128(key_128,plaintext2,ciphertext2_128);
encrypt128(key_128,plaintext3,ciphertext3_128);
encrypt128(key_128,plaintext4,ciphertext4_128);
decrypt128(key_128,ciphertext1_128,plaintext1);
decrypt128(key_128,ciphertext2_128,plaintext2);
decrypt128(key_128,ciphertext3_128,plaintext3);
decrypt128(key_128,ciphertext4_128,plaintext4);
//F.1.3
//ECB-AES192.Encrypt
const uint8_t key_192[]={0x8e,0x73,0xb0,0xf7,0xda,0x0e,0x64,0x52,0xc8,0x10,0xf3,0x2b,0x80,0x90,0x79,0xe5,0x62,0xf8,0xea,0xd2,0x52,0x2c,0x6b,0x7b};
const uint8_t ciphertext1_192[]={0xbd,0x33,0x4f,0x1d,0x6e,0x45,0xf2,0x5f,0xf7,0x12,0xa2,0x14,0x57,0x1f,0xa5,0xcc};
const uint8_t ciphertext2_192[]={0x97,0x41,0x04,0x84,0x6d,0x0a,0xd3,0xad,0x77,0x34,0xec,0xb3,0xec,0xee,0x4e,0xef};
const uint8_t ciphertext3_192[]={0xef,0x7a,0xfd,0x22,0x70,0xe2,0xe6,0x0a,0xdc,0xe0,0xba,0x2f,0xac,0xe6,0x44,0x4e};
const uint8_t ciphertext4_192[]={0x9a,0x4b,0x41,0xba,0x73,0x8d,0x6c,0x72,0xfb,0x16,0x69,0x16,0x03,0xc1,0x8e,0x0e};
encrypt192(key_192,plaintext1,ciphertext1_192);
encrypt192(key_192,plaintext2,ciphertext2_192);
encrypt192(key_192,plaintext3,ciphertext3_192);
encrypt192(key_192,plaintext4,ciphertext4_192);
decrypt192(key_192,ciphertext1_192,plaintext1);
decrypt192(key_192,ciphertext2_192,plaintext2);
decrypt192(key_192,ciphertext3_192,plaintext3);
decrypt192(key_192,ciphertext4_192,plaintext4);
//F.1.5
//ECB-AES256.Encrypt
const uint8_t key_256[]={0x60,0x3d,0xeb,0x10,0x15,0xca,0x71,0xbe,0x2b,0x73,0xae,0xf0,0x85,0x7d,0x77,0x81,0x1f,0x35,0x2c,0x07,0x3b,0x61,0x08,0xd7,0x2d,0x98,0x10,0xa3,0x09,0x14,0xdf,0xf4};
const uint8_t ciphertext1_256[]={0xf3,0xee,0xd1,0xbd,0xb5,0xd2,0xa0,0x3c,0x06,0x4b,0x5a,0x7e,0x3d,0xb1,0x81,0xf8};
const uint8_t ciphertext2_256[]={0x59,0x1c,0xcb,0x10,0xd4,0x10,0xed,0x26,0xdc,0x5b,0xa7,0x4a,0x31,0x36,0x28,0x70};
const uint8_t ciphertext3_256[]={0xb6,0xed,0x21,0xb9,0x9c,0xa6,0xf4,0xf9,0xf1,0x53,0xe7,0xb1,0xbe,0xaf,0xed,0x1d};
const uint8_t ciphertext4_256[]={0x23,0x30,0x4b,0x7a,0x39,0xf9,0xf3,0xff,0x06,0x7d,0x8d,0x8f,0x9e,0x24,0xec,0xc7};
encrypt256(key_256,plaintext1,ciphertext1_256);
encrypt256(key_256,plaintext2,ciphertext2_256);
encrypt256(key_256,plaintext3,ciphertext3_256);
encrypt256(key_256,plaintext4,ciphertext4_256);
decrypt256(key_256,ciphertext1_256,plaintext1);
decrypt256(key_256,ciphertext2_256,plaintext2);
decrypt256(key_256,ciphertext3_256,plaintext3);
decrypt256(key_256,ciphertext4_256,plaintext4);
return 0;
}
| 37.759777 | 188 | 0.733245 | DarkCaster |
ae16385cc7eca56e94f53701d593e2310f2f8d21 | 970 | cpp | C++ | graph-source-code/230-E/4442480.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | graph-source-code/230-E/4442480.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | graph-source-code/230-E/4442480.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | //Language: GNU C++
#include <iostream>
#include <fstream>
#include <sstream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cctype>
#include <cmath>
#include <ctime>
#include <algorithm>
#include <vector>
#include <queue>
#include <deque>
#include <stack>
#include <set>
#include <map>
#include <complex>
#include <bitset>
#include <iomanip>
#include <utility>
#define xx first
#define yy second
#define ll long long
#define ull unsigned long long
#define pb push_back
#define pp pop_back
#define pii pair<int ,int>
#define vi vector<int>
using namespace std;
const int maxn=1000000+10;
int deg[maxn];
ll n,m;
ll ans;
int main()
{
ios::sync_with_stdio(false);
cin>>n>>m;
for(int i=1;i<=m;i++){
int u,v;
cin>>u>>v;
deg[u]++;deg[v]++;
}
ans=n*(n-1)*(n-2)/6;
ans-=m*(n-2);
for(int i=1;i<=n;i++)ans+=deg[i]*(deg[i]-1)/2;
cout<<ans;
//cin>>n;
} | 18.653846 | 51 | 0.598969 | AmrARaouf |
ae194a06ae06c7f94a886e778f5295ea8d9b2247 | 24,020 | hpp | C++ | engine/generic_list.hpp | iyupeng/kvdk | 35e882bf6adc5e931d57fb07c648d0478b9ea146 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | engine/generic_list.hpp | iyupeng/kvdk | 35e882bf6adc5e931d57fb07c648d0478b9ea146 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | engine/generic_list.hpp | iyupeng/kvdk | 35e882bf6adc5e931d57fb07c648d0478b9ea146 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | /* SPDX-License-Identifier: BSD-3-Clause
* Copyright(c) 2021 Intel Corporation
*/
#pragma once
#include <immintrin.h>
#include <libpmem.h>
#include <x86intrin.h>
#include <array>
#include <atomic>
#include <deque>
#include <iomanip>
#include <iostream>
#include <libpmemobj++/string_view.hpp>
#include <mutex>
#include <random>
#include <stdexcept>
#include <unordered_map>
#include "alias.hpp"
#include "collection.hpp"
#include "data_record.hpp"
#include "macros.hpp"
#include "pmem_allocator/pmem_allocator.hpp"
#include "utils/utils.hpp"
namespace KVDK_NAMESPACE {
constexpr PMemOffsetType NullPMemOffset = kNullPMemOffset;
template <RecordType ListType, RecordType DataType>
class GenericList final : public Collection {
private:
// For offset-address translation
PMEMAllocator* alloc{nullptr};
// Persisted ListType on PMem, contains List name(key) and id(value).
DLRecord* list_record{nullptr};
// First Element in List, nullptr indicates empty List
DLRecord* first{nullptr};
// Last Element in List, nullptr indicates empty List
DLRecord* last{nullptr};
// Size of list
size_t sz{0U};
// Recursive mutex to lock the List
using LockType = std::recursive_mutex;
LockType mu;
public:
class Iterator {
private:
// owner must be initialized with a List
GenericList const* owner;
// curr == nullptr indicates Head() and Tail()
DLRecord* curr{nullptr};
public:
// Always start at Head()/Tail()
// Head() and Tail() is the same state,
// just for convention this state has two names
// Tail() for iterating forward
// Head() for iterating backward
explicit Iterator(GenericList const* o) : owner{o} {
kvdk_assert(owner != nullptr, "Invalid iterator!");
}
Iterator() = delete;
Iterator(Iterator const&) = default;
Iterator(Iterator&&) = default;
Iterator& operator=(Iterator const&) = default;
Iterator& operator=(Iterator&&) = default;
~Iterator() = default;
/// Increment and Decrement operators
Iterator& operator++() {
if (curr == nullptr) {
// Head(), goto Front()
// Front() == Tail() if List is empty.
curr = owner->first;
} else if (curr->next != NullPMemOffset) {
// Not Back(), goto next
curr = owner->addressOf(curr->next);
} else {
// Back(), goto Tail()
curr = nullptr;
}
return *this;
}
Iterator const operator++(int) {
Iterator old{*this};
this->operator++();
return old;
}
Iterator& operator--() {
if (curr == nullptr) {
// Tail(), goto Back()
// Back() == Head() if List is empty.
curr = owner->last;
} else if (curr->prev != NullPMemOffset) {
// Not Front(), goto prev
curr = owner->addressOf(curr->prev);
} else {
// Front(), goto Head()
curr = nullptr;
}
return *this;
}
Iterator const operator--(int) {
Iterator old{*this};
this->operator--();
return old;
}
DLRecord& operator*() { return *curr; }
DLRecord* operator->() { return curr; }
PMemOffsetType Offset() const { return owner->offsetOf(Address()); }
DLRecord* Address() const {
kvdk_assert(curr != nullptr, "Trying to address dummy Iterator Head()!");
return curr;
}
private:
friend bool operator==(Iterator const& lhs, Iterator const& rhs) {
return (lhs.owner == rhs.owner) && (lhs.curr == rhs.curr);
}
friend bool operator!=(Iterator const& lhs, Iterator const& rhs) {
return !(lhs == rhs);
}
};
public:
// Default to an empty list with no name and 0 as id
// Must Init() or Restore() before further use.
GenericList() : Collection{"", CollectionIDType{}} {}
GenericList(GenericList const&) = delete;
GenericList(GenericList&&) = delete;
GenericList& operator=(GenericList const&) = delete;
GenericList& operator=(GenericList&&) = delete;
~GenericList() = default;
// Initialize a List with pmem base address p_base, pre-space space,
// Creation time, List name and id.
void Init(PMEMAllocator* a, SpaceEntry space, TimeStampType timestamp,
StringView const key, CollectionIDType id) {
collection_name_.assign(key.data(), key.size());
collection_id_ = id;
alloc = a;
list_record = DLRecord::PersistDLRecord(
addressOf(space.offset), space.size, timestamp, RecordType::ListRecord,
NullPMemOffset, NullPMemOffset, NullPMemOffset, key, ID2String(id));
}
template <typename ListDeleter>
void Destroy(ListDeleter list_deleter) {
kvdk_assert(sz == 0 && list_record != nullptr && first == nullptr &&
last == nullptr,
"Only initialized empty List can be destroyed!");
list_deleter(list_record);
list_record = nullptr;
alloc = nullptr;
}
bool Valid() const { return (list_record != nullptr); }
// Restore a List with its ListRecord, first and last element and size
// This function is used by GenericListBuilder to restore the List
void Restore(PMEMAllocator* a, DLRecord* list_rec, DLRecord* fi, DLRecord* la,
size_t n) {
auto key = list_rec->Key();
collection_name_.assign(key.data(), key.size());
kvdk_assert(list_rec->Value().size() == sizeof(CollectionIDType), "");
collection_id_ = ExtractID(list_rec->Value());
alloc = a;
list_record = list_rec;
first = fi;
last = la;
sz = n;
}
LockType* Mutex() { return μ }
std::unique_lock<LockType> AcquireLock() {
return std::unique_lock<LockType>(mu);
}
ExpiredTimeType GetExpireTime() const final {
return list_record->GetExpireTime();
}
bool HasExpired() const final {
return TimeUtils::CheckIsExpired(GetExpireTime());
}
Status SetExpireTime(ExpiredTimeType time) final {
list_record->PersistExpireTimeNT(time);
return Status::Ok;
}
size_t Size() const { return sz; }
Iterator Front() { return ++Head(); }
Iterator Back() { return --Tail(); }
Iterator Head() const { return Iterator{this}; }
Iterator Tail() const { return Iterator{this}; }
Iterator Seek(std::int64_t index) {
if (index >= 0) {
auto iter = Front();
while (index != 0 && iter != Tail()) {
++iter;
--index;
}
return iter;
} else {
auto iter = Back();
while (index != -1 && iter != Head()) {
--iter;
++index;
}
return iter;
}
}
template <typename ElemDeleter>
Iterator Erase(Iterator pos, ElemDeleter elem_deleter) {
kvdk_assert(pos != Head(), "Cannot erase Head()");
kvdk_assert(sz >= 1, "Cannot erase from empty List!");
kvdk_assert(ExtractID(pos->Key()) == ID(), "Erase from wrong List!");
Iterator prev{pos};
--prev;
Iterator next{pos};
++next;
if (sz == 1) {
kvdk_assert(prev == Head() && next == Tail(), "Impossible!");
first = nullptr;
last = nullptr;
} else if (prev == Head()) {
// Erase Front()
kvdk_assert(next != Tail(), "");
first = next.Address();
next->PersistPrevNT(NullPMemOffset);
} else if (next == Tail()) {
// Erase Back()
kvdk_assert(prev != Head(), "");
last = prev.Address();
prev->PersistNextNT(NullPMemOffset);
} else {
kvdk_assert(prev != Head() && next != Tail(), "");
// Reverse procedure of emplace_between() between two elements
next->PersistPrevNT(prev.Offset());
prev->PersistNextNT(next.Offset());
}
elem_deleter(pos.Address());
--sz;
return next;
}
template <typename ElemDeleter>
void PopFront(ElemDeleter elem_deleter) {
Erase(Front(), elem_deleter);
}
template <typename ElemDeleter>
void PopBack(ElemDeleter elem_deleter) {
Erase(Back(), elem_deleter);
}
void EmplaceBefore(SpaceEntry space, Iterator pos, TimeStampType timestamp,
StringView const key, StringView const value) {
Iterator prev{pos};
--prev;
Iterator next{pos};
emplace_between(space, prev, next, timestamp, key, value);
++sz;
}
void EmplaceAfter(SpaceEntry space, Iterator pos, TimeStampType timestamp,
StringView const key, StringView const value) {
Iterator prev{pos};
Iterator next{pos};
++next;
emplace_between(space, prev, next, timestamp, key, value);
++sz;
}
void PushFront(SpaceEntry space, TimeStampType timestamp,
StringView const key, StringView const value) {
emplace_between(space, Head(), Front(), timestamp, key, value);
++sz;
}
void PushBack(SpaceEntry space, TimeStampType timestamp, StringView const key,
StringView const value) {
emplace_between(space, Back(), Tail(), timestamp, key, value);
++sz;
}
template <typename ElemDeleter>
void Replace(SpaceEntry space, Iterator pos, TimeStampType timestamp,
StringView const key, StringView const value,
ElemDeleter elem_deleter) {
kvdk_assert(ExtractID(pos->Key()) == ID(), "Wrong List!");
Iterator prev{pos};
--prev;
Iterator next{pos};
++next;
emplace_between(space, prev, next, timestamp, key, value);
elem_deleter(pos.Address());
}
private:
inline DLRecord* addressOf(PMemOffsetType offset) const {
return static_cast<DLRecord*>(alloc->offset2addr_checked(offset));
}
inline PMemOffsetType offsetOf(DLRecord* rec) const {
return alloc->addr2offset_checked(rec);
}
Iterator emplace_between(SpaceEntry space, Iterator prev, Iterator next,
TimeStampType timestamp, StringView const key,
StringView const value) {
kvdk_assert(++Iterator{prev} == next || ++++Iterator{prev} == next,
"Should only insert or replace");
PMemOffsetType prev_off = (prev == Head()) ? NullPMemOffset : prev.Offset();
PMemOffsetType next_off = (next == Tail()) ? NullPMemOffset : next.Offset();
DLRecord* record = DLRecord::PersistDLRecord(
addressOf(space.offset), space.size, timestamp, DataType,
NullPMemOffset, prev_off, next_off, InternalKey(key), value);
if (sz == 0) {
kvdk_assert(prev == Head() && next == Tail(), "Impossible!");
first = record;
last = record;
} else if (prev == Head()) {
// PushFront()
kvdk_assert(next != Tail(), "");
next->PersistPrevNT(space.offset);
first = record;
} else if (next == Tail()) {
// PushBack()
kvdk_assert(prev != Head(), "");
prev->PersistNextNT(space.offset);
last = record;
} else {
// Emplace between two elements on PMem
kvdk_assert(prev != Head() && next != Tail(), "");
prev->PersistNextNT(space.offset);
next->PersistPrevNT(space.offset);
}
return (next == Tail()) ? --next : ++prev;
}
friend std::ostream& operator<<(std::ostream& out, GenericList const& list) {
auto printRecord = [&](DLRecord* record) {
out << "Type:\t" << to_hex(record->entry.meta.type) << "\t"
<< "Prev:\t" << to_hex(record->prev) << "\t"
<< "Offset:\t"
<< to_hex(reinterpret_cast<char*>(record) - list.pmem_base) << "\t"
<< "Next:\t" << to_hex(record->next) << "\t"
<< "ID:\t" << to_hex(Collection::ExtractID(record->Key())) << "\t"
<< "Key: " << Collection::ExtractUserKey(record->Key()) << "\t"
<< "Value: " << record->Value() << "\n";
};
out << "Contents of List:\n";
Iterator iter = list.Head();
for (Iterator iter = list.Head(); iter != list.Tail(); iter++) {
printRecord(iter.record);
}
printRecord(iter.record);
return out;
}
};
template <RecordType ListType, RecordType DataType>
class GenericListBuilder final {
static constexpr size_t NMiddlePoints = 1024;
using List = GenericList<ListType, DataType>;
PMEMAllocator* alloc;
size_t n_worker{0};
std::mutex mu;
std::vector<std::unique_ptr<List>>* rebuilded_lists{nullptr};
// Resevoir for middle points
// Middle points can be used for multi-thread interating through Lists
std::atomic_uint64_t mpoint_cnt{0U};
std::array<DLRecord*, NMiddlePoints> mpoints{};
struct ListPrimer {
DLRecord* list_record{nullptr};
DLRecord* unique{nullptr};
DLRecord* first{nullptr};
DLRecord* last{nullptr};
std::atomic_uint64_t size{0U};
ListPrimer() = default;
ListPrimer(ListPrimer const& other)
: list_record{other.list_record},
unique{other.unique},
first{other.first},
last{other.last},
size{other.size.load()} {}
ListPrimer(ListPrimer&& other) = delete;
ListPrimer& operator=(ListPrimer const&) = delete;
ListPrimer& operator=(ListPrimer&&) = delete;
~ListPrimer() = default;
};
std::vector<ListPrimer> primers{};
RWLock primers_lock;
std::vector<DLRecord*> brokens{};
std::mutex brokens_lock{};
// There are 4 types of DLRecord
// 0. Unique: prev == Null && next == Null
// 1. First: prev == Null && next != Null
// 2. Last: prev != Null && next == Null
// 3. Middle: prev != Null && next != Null
enum class ListRecordType { Unique, First, Last, Middle };
// There are several types of failure during GenericList operations
// 1. PushFront/PushBack/PopFront/PopBack Failure
// Interruption in Pop() after unlink before purge, same as
// Interruption in Push() after persist before link
// For uniformity with 1-elem Pop crash, which cannot be detected
// Discard the node not linked to/unlinked from List
// 2. ReplaceFront/ReplaceBack Failure
// Discard the unlinked node
// 3. Replace Failure
// a. Node not linked from its prev and next purged directly
// b. Node not linked from prev but linked from next is linked from prev
// This node is older
// c. Node linked from prev but not linked from next is saved to broken
// This node is newer
// After all nodes repaired, this node is unlinked from prev and next
// and can be purged
// 4. Insertion/Erase Failure
// a. Node not linked from its prev and next purged directly
// b. Node not linked from prev but linked from next is linked from prev
// c. Node linked from prev but not linked from next is saved to broken
// After all nodes repaired, this node is unlinked from prev and next
// and can be purged
// In conclusion,
// All unsuccessful Emplace/Push/Replace(before fully linked) will rollback
// All unsuccessful Erase/Pop will be finished
// This way, we avoid generating duplicate First/Last elements, which will
// complicate the recovery procedure
public:
explicit GenericListBuilder(PMEMAllocator* a,
std::vector<std::unique_ptr<List>>* lists,
size_t num_worker)
: alloc{a}, rebuilded_lists{lists}, n_worker{num_worker} {
kvdk_assert(lists != nullptr && lists->empty(), "");
kvdk_assert(num_worker != 0, "");
kvdk_assert(rebuilded_lists != nullptr, "Empty input!");
}
void AddListRecord(DLRecord* lrec) {
kvdk_assert(lrec->Value().size() == sizeof(CollectionIDType), "");
CollectionIDType id = Collection::ExtractID(lrec->Value());
maybeResizePrimers(id);
primers_lock.lock_shared();
kvdk_assert(primers.at(id).list_record == nullptr, "");
primers.at(id).list_record = lrec;
primers_lock.unlock_shared();
}
void AddListElem(DLRecord* elem) {
kvdk_assert(elem->entry.meta.type == DataType, "");
switch (typeOf(elem)) {
case ListRecordType::Unique: {
addUniqueElem(elem);
break;
}
case ListRecordType::First: {
addFirstElem(elem);
break;
}
case ListRecordType::Last: {
addLastElem(elem);
break;
}
case ListRecordType::Middle: {
addMiddleElem(elem);
break;
}
}
return;
}
template <typename Func>
void ProcessCachedElems(Func f, void* args) {
f(mpoints, args);
return;
}
void RebuildLists() {
for (auto const& primer : primers) {
if (primer.list_record == nullptr) {
kvdk_assert(primer.first == nullptr, "");
kvdk_assert(primer.last == nullptr, "");
kvdk_assert(primer.unique == nullptr, "");
kvdk_assert(primer.size.load() == 0U, "");
continue;
}
rebuilded_lists->emplace_back(new List{});
switch (primer.size.load()) {
case 0: {
// Empty List
kvdk_assert(primer.first == nullptr, "");
kvdk_assert(primer.last == nullptr, "");
kvdk_assert(primer.unique == nullptr, "");
kvdk_assert(primer.size.load() == 0, "");
rebuilded_lists->back()->Restore(alloc, primer.list_record, nullptr,
nullptr, 0);
break;
}
case 1: {
// 1-elem List
kvdk_assert(primer.first == nullptr, "");
kvdk_assert(primer.last == nullptr, "");
kvdk_assert(primer.unique != nullptr, "");
kvdk_assert(primer.size.load() == 1, "");
rebuilded_lists->back()->Restore(alloc, primer.list_record,
primer.unique, primer.unique, 1);
break;
}
default: {
// k-elem List
kvdk_assert(primer.first != nullptr, "");
kvdk_assert(primer.last != nullptr, "");
kvdk_assert(primer.unique == nullptr, "");
rebuilded_lists->back()->Restore(alloc, primer.list_record,
primer.first, primer.last,
primer.size.load());
break;
}
}
}
}
template <typename ElemDeleter>
void CleanBrokens(ElemDeleter elem_deleter) {
for (DLRecord* elem : brokens) {
switch (typeOf(elem)) {
case ListRecordType::Unique: {
kvdk_assert(false, "Impossible!");
break;
}
case ListRecordType::First: {
kvdk_assert(!isValidFirst(elem), "");
break;
}
case ListRecordType::Last: {
kvdk_assert(!isValidLast(elem), "");
break;
}
case ListRecordType::Middle: {
kvdk_assert(isDiscardedMiddle(elem), "");
break;
}
}
elem_deleter(elem);
}
}
private:
inline DLRecord* addressOf(PMemOffsetType offset) const {
return static_cast<DLRecord*>(alloc->offset2addr_checked(offset));
}
inline PMemOffsetType offsetOf(DLRecord* rec) const {
return alloc->addr2offset_checked(rec);
}
ListRecordType typeOf(DLRecord* elem) {
if (elem->prev == NullPMemOffset) {
if (elem->next == NullPMemOffset) {
return ListRecordType::Unique;
} else {
return ListRecordType::First;
}
} else {
if (elem->next == NullPMemOffset) {
return ListRecordType::Last;
} else {
return ListRecordType::Middle;
}
}
}
void addUniqueElem(DLRecord* elem) {
kvdk_assert(elem->prev == NullPMemOffset && elem->next == NullPMemOffset,
"Not UniqueElem!");
CollectionIDType id = Collection::ExtractID(elem->Key());
maybeResizePrimers(id);
primers_lock.lock_shared();
kvdk_assert(primers.at(id).unique == nullptr, "");
kvdk_assert(primers.at(id).first == nullptr, "");
kvdk_assert(primers.at(id).last == nullptr, "");
primers.at(id).unique = elem;
primers.at(id).size.fetch_add(1U);
primers_lock.unlock_shared();
}
void addFirstElem(DLRecord* elem) {
kvdk_assert(elem->prev == NullPMemOffset && elem->next != NullPMemOffset,
"Not FirstElem!");
if (!isValidFirst(elem)) {
std::lock_guard<std::mutex> guard{brokens_lock};
brokens.push_back(elem);
return;
}
CollectionIDType id = Collection::ExtractID(elem->Key());
maybeResizePrimers(id);
primers_lock.lock_shared();
kvdk_assert(primers.at(id).first == nullptr, "");
kvdk_assert(primers.at(id).unique == nullptr, "");
primers.at(id).first = elem;
primers.at(id).size.fetch_add(1U);
primers_lock.unlock_shared();
}
void addLastElem(DLRecord* elem) {
kvdk_assert(elem->next == NullPMemOffset && elem->prev != NullPMemOffset,
"Not LastElem!");
if (!isValidLast(elem)) {
std::lock_guard<std::mutex> guard{brokens_lock};
brokens.push_back(elem);
return;
}
CollectionIDType id = Collection::ExtractID(elem->Key());
maybeResizePrimers(id);
primers_lock.lock_shared();
kvdk_assert(primers.at(id).last == nullptr, "");
kvdk_assert(primers.at(id).unique == nullptr, "");
primers.at(id).last = elem;
primers.at(id).size.fetch_add(1U);
primers_lock.unlock_shared();
}
// Reservoir algorithm
void addMiddleElem(DLRecord* elem) {
kvdk_assert(elem->prev != NullPMemOffset && elem->next != NullPMemOffset,
"Not MiddleElem!");
if (!maybeTryFixMiddle(elem)) {
std::lock_guard<std::mutex> guard{brokens_lock};
brokens.push_back(elem);
return;
}
CollectionIDType id = Collection::ExtractID(elem->Key());
maybeResizePrimers(id);
primers_lock.lock_shared();
primers.at(id).size.fetch_add(1U);
primers_lock.unlock_shared();
thread_local std::default_random_engine rengine{get_seed()};
auto cnt = mpoint_cnt.fetch_add(1U);
auto pos = cnt % NMiddlePoints;
auto k = cnt / NMiddlePoints;
// k-th point has posibility 1/(k+1) to replace previous point in reservoir
if (std::bernoulli_distribution{1.0 /
static_cast<double>(k + 1)}(rengine)) {
mpoints.at(pos) = elem;
}
return;
}
bool isValidFirst(DLRecord* elem) {
if (addressOf(elem->next)->prev == NullPMemOffset) {
// Interrupted PushFront()/PopFront()
return false;
} else if (addressOf(elem->next)->prev == offsetOf(elem)) {
return true;
} else {
// Interrupted ReplaceFront()
kvdk_assert(addressOf(addressOf(elem->next)->prev)->next == elem->next,
"");
return false;
}
}
bool isValidLast(DLRecord* elem) {
if (addressOf(elem->prev)->next == NullPMemOffset) {
// Interrupted PushBack()/PopBack()
return false;
} else if (addressOf(elem->prev)->next == offsetOf(elem)) {
return true;
} else {
// Interrupted ReplaceBack()
kvdk_assert(addressOf(addressOf(elem->prev)->next)->prev == elem->prev,
"");
return false;
}
}
// Check for discarded Middle
bool isDiscardedMiddle(DLRecord* elem) {
kvdk_assert(typeOf(elem) == ListRecordType::Middle, "Not a middle");
return (offsetOf(elem) != addressOf(elem->prev)->next) &&
(offsetOf(elem) != addressOf(elem->next)->prev);
}
// When false is returned, the node is put in temporary pool
// and processed after all restoration is done
bool maybeTryFixMiddle(DLRecord* elem) {
if (offsetOf(elem) == addressOf(elem->prev)->next) {
if (offsetOf(elem) == addressOf(elem->next)->prev) {
// Normal Middle
return true;
} else {
// Interrupted Replace/Emplace(newer), discard
return false;
}
} else {
if (offsetOf(elem) == addressOf(elem->next)->prev) {
// Interrupted Replace/Emplace(older), repair into List
addressOf(elem->prev)->PersistNextNT(offsetOf(elem));
return true;
} else {
// Un-purged, discard
return false;
}
}
}
void maybeResizePrimers(CollectionIDType id) {
if (id >= primers.size()) {
std::lock_guard<decltype(primers_lock)> guard{primers_lock};
for (size_t i = primers.size(); i < (id + 1) * 3 / 2; i++) {
primers.emplace_back();
}
}
}
};
} // namespace KVDK_NAMESPACE
| 31.154345 | 80 | 0.613197 | iyupeng |
ae236083dd3d4f9d4d431e5a1fd8148244353fc5 | 1,417 | cpp | C++ | Ejercicio03/compset_iteration_01/lib/RequestHandler/test/test.cpp | SmartNetAR/edi3 | 68e28b58e04b728bc48700378b2afe8f16872974 | [
"MIT"
] | null | null | null | Ejercicio03/compset_iteration_01/lib/RequestHandler/test/test.cpp | SmartNetAR/edi3 | 68e28b58e04b728bc48700378b2afe8f16872974 | [
"MIT"
] | null | null | null | Ejercicio03/compset_iteration_01/lib/RequestHandler/test/test.cpp | SmartNetAR/edi3 | 68e28b58e04b728bc48700378b2afe8f16872974 | [
"MIT"
] | null | null | null | /**
* Copyright (c) 2016 Gabriel Ferreira <gabrielinuz@gmail.com>. All rights reserved.
* This file is part of COMPSET.
* Released under the GPL3 license
* https://opensource.org/licenses/GPL-3.0
**/
#include <iostream>
#include <vector>
#include <unordered_map>
#include <string>
#include <compset/ComponentInterface.h>
#include <compset/ComponentFactory.h>
#include <compset/RequestHandlerInterface.h>
typedef std::vector< std::unordered_map<std::string, std::string> > DataType;
typedef std::unordered_map<std::string, std::string> DatumType;
int main()
{
DataType data;
DatumType datum;
ComponentFactory* componentFactoryObject = new ComponentFactory();
componentFactoryObject->setInterfaceName("RequestHandlerInterface");
ComponentInterface* requestHandlerComponent = componentFactoryObject->createFrom("../RequestHandler");
RequestHandlerInterface* requestHandlerObject = ( (RequestHandlerInterface*) requestHandlerComponent->getInstance() );
DatumType requestParameters = requestHandlerObject->getRequestParameters();
data.push_back(requestParameters);
requestHandlerComponent->release();
delete componentFactoryObject;
std::cout << requestParameters["action"] << std::endl;
std::cout << "RESULT:" << std::endl;
std::cout << "\t\tTEST OK!!!!!" << std::endl;
std::cout << "" << std::endl;
std::cout << "" << std::endl;
return 0;
} | 32.204545 | 122 | 0.721948 | SmartNetAR |
ae23abb8b6a210768d8f1f3438cd33e73abbf59c | 61 | hpp | C++ | addons/modules/modules/curator/prep.hpp | Krzyciu/A3CS | b7144fc9089b5ded6e37cc1fad79b1c2879521be | [
"MIT"
] | 1 | 2020-06-07T00:45:49.000Z | 2020-06-07T00:45:49.000Z | addons/modules/modules/curator/prep.hpp | Krzyciu/A3CS | b7144fc9089b5ded6e37cc1fad79b1c2879521be | [
"MIT"
] | 27 | 2020-05-24T11:09:56.000Z | 2020-05-25T12:28:10.000Z | addons/modules/modules/curator/prep.hpp | Krzyciu/A3CS | b7144fc9089b5ded6e37cc1fad79b1c2879521be | [
"MIT"
] | 2 | 2020-05-31T08:52:45.000Z | 2021-04-16T23:16:37.000Z |
PREP_MODULE(curator,module);
PREP_MODULE(curator,validate);
| 15.25 | 30 | 0.819672 | Krzyciu |
ae253bbbba2b1326e6621f9d165fd1fd8ec7ae36 | 264 | cpp | C++ | src/triangle-rasterizer-demo/src/trdDirectionalLight.cpp | frmr/triangle-rasterizer-demo | 963f32435ebae5b7fbe6fa212709bdc3ea66ac36 | [
"MIT"
] | null | null | null | src/triangle-rasterizer-demo/src/trdDirectionalLight.cpp | frmr/triangle-rasterizer-demo | 963f32435ebae5b7fbe6fa212709bdc3ea66ac36 | [
"MIT"
] | null | null | null | src/triangle-rasterizer-demo/src/trdDirectionalLight.cpp | frmr/triangle-rasterizer-demo | 963f32435ebae5b7fbe6fa212709bdc3ea66ac36 | [
"MIT"
] | null | null | null | #include "trdDirectionalLight.hpp"
trd::DirectionalLight::DirectionalLight(const Vector3& color, Vector3 direction) :
Light(color),
m_direction(direction.normalize())
{
}
const tr::QuadVec3& trd::DirectionalLight::getDirection() const
{
return m_direction;
}
| 20.307692 | 82 | 0.772727 | frmr |
ae2c48b1aa5739963134ca4224fbc585db1d1a24 | 981 | hpp | C++ | aboveGroundSpace.hpp | KrisBierma/textBasedStrategyGame | 231b0e9a33d8892edfb3fd85fb64679c8b237540 | [
"MIT"
] | null | null | null | aboveGroundSpace.hpp | KrisBierma/textBasedStrategyGame | 231b0e9a33d8892edfb3fd85fb64679c8b237540 | [
"MIT"
] | null | null | null | aboveGroundSpace.hpp | KrisBierma/textBasedStrategyGame | 231b0e9a33d8892edfb3fd85fb64679c8b237540 | [
"MIT"
] | null | null | null | /********************************************************************
** Program name:The Secret Treasure, A Text-Based Game (Project 5)
** Author: Kris Bierma
** Date: 12/6/19
** Description: AboveGroundSpace class is derived from Space class.
** It overrides the getSpaceType functions, has its own
** setPointers function and inherits everything else
** the base Space class.
********************************************************************/
#include "space.hpp"
#ifndef KBIERMA_ABOVEGROUNDSPACE_HPP
#define KBIERMA_ABOVEGROUNDSPACE_HPP
class AboveGroundSpace : public Space {
private:
Space *down;
public:
AboveGroundSpace(string spaceNameIn, string printSpaceNameIn, string spaceDescrptionIn, string spaceDescriptionAfterDependencyIn);
~AboveGroundSpace() {};
void setPointers(Space *northIn, Space *eastIn, Space *southIn, Space *westIn, Space *downIn);
virtual string getSpaceType();
};
#endif | 39.24 | 134 | 0.618756 | KrisBierma |
ae2f9969a23231b099261429bcf4614bbb48e80c | 769 | cpp | C++ | Luogu/P7947.cpp | Nickel-Angel/Coding-Practice | 6fb70e9c9542323f82a9a8714727cc668ff58567 | [
"MIT"
] | null | null | null | Luogu/P7947.cpp | Nickel-Angel/Coding-Practice | 6fb70e9c9542323f82a9a8714727cc668ff58567 | [
"MIT"
] | 1 | 2021-11-18T15:10:29.000Z | 2021-11-20T07:13:31.000Z | Luogu/P7947.cpp | Nickel-Angel/ACM-and-OI | 79d13fd008c3a1fe9ebf35329aceb1fcb260d5d9 | [
"MIT"
] | null | null | null | /*
* @author Nickel_Angel (1239004072@qq.com)
* @copyright Copyright (c) 2021
*/
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <numeric>
#include <vector>
int n, k;
std::vector<int> ans;
int main()
{
scanf("%d%d", &n, &k);
for (int i = 2, bound = n; i * i <= bound; ++i)
{
while (n % i == 0)
{
n /= i;
ans.push_back(i);
}
if (n == 1)
break;
}
if (n != 1)
ans.push_back(n);
int sum = std::accumulate(ans.begin(), ans.end(), 0);
if (sum > k)
{
puts("-1");
return 0;
}
printf("%d\n", ans.size() + k - sum);
for (int i : ans)
printf("%d ", i);
for (int i = 0; i < k - sum; ++i)
printf("1 ");
} | 18.756098 | 57 | 0.446034 | Nickel-Angel |
ae30af79ea1f3c2125eb94c5fd7f2b5e5aab7fa2 | 1,009 | hpp | C++ | Questless/Questless/src/animation/scene_node.hpp | jonathansharman/questless | bb9ffb2d21cbfde2a71edfecfcbf466479bbbe7d | [
"MIT"
] | 2 | 2020-07-14T12:50:06.000Z | 2020-11-04T02:25:09.000Z | Questless/Questless/src/animation/scene_node.hpp | jonathansharman/questless | bb9ffb2d21cbfde2a71edfecfcbf466479bbbe7d | [
"MIT"
] | null | null | null | Questless/Questless/src/animation/scene_node.hpp | jonathansharman/questless | bb9ffb2d21cbfde2a71edfecfcbf466479bbbe7d | [
"MIT"
] | null | null | null | //! @file
//! @copyright See <a href="LICENSE.txt">LICENSE.txt</a>.
#pragma once
#include "animation.hpp"
#include "utility/reference.hpp"
#include <deque>
namespace ql {
//! An animation with attached child animations. A scene node's transform is composed with its children's transforms.
struct scene_node : animation {
//! The animation to draw at this node.
uptr<animation> node_animation;
//! Children drawn behind this node. Drawn back-to-front, so back_children.back() is the back-most node.
std::deque<uptr<animation>> back_children{};
//! Children drawn in front of this node. Drawn back-to-front, so front_children.front() is the front-most node.
std::deque<uptr<animation>> front_children{};
//! @param node_animation The animation to draw at this node.
scene_node(uptr<animation> node_animation);
private:
auto animation_subupdate(sec elapsed_time) -> void final;
auto animation_subdraw(sf::RenderTarget& target, sf::RenderStates states) const -> void final;
};
}
| 30.575758 | 118 | 0.733399 | jonathansharman |
ae31b3c508e6deebb4beac171151e2d81164be59 | 119,953 | cpp | C++ | src/parser/ds_lexer.cpp | profelis/daScript | eea57f39dec4dd6168ee64c8ae5139cbcf2937bc | [
"BSD-3-Clause"
] | 421 | 2019-08-15T15:40:04.000Z | 2022-03-29T06:59:06.000Z | src/parser/ds_lexer.cpp | profelis/daScript | eea57f39dec4dd6168ee64c8ae5139cbcf2937bc | [
"BSD-3-Clause"
] | 55 | 2019-08-17T13:50:53.000Z | 2022-03-25T17:58:38.000Z | src/parser/ds_lexer.cpp | profelis/daScript | eea57f39dec4dd6168ee64c8ae5139cbcf2937bc | [
"BSD-3-Clause"
] | 58 | 2019-08-22T17:04:13.000Z | 2022-03-25T17:43:28.000Z | #line 1 "ds_lexer.cpp"
#line 3 "ds_lexer.cpp"
#define YY_INT_ALIGNED short int
/* A lexical scanner generated by flex */
#define FLEX_SCANNER
#define YY_FLEX_MAJOR_VERSION 2
#define YY_FLEX_MINOR_VERSION 6
#define YY_FLEX_SUBMINOR_VERSION 4
#if YY_FLEX_SUBMINOR_VERSION > 0
#define FLEX_BETA
#endif
#ifdef yy_create_buffer
#define das_yy_create_buffer_ALREADY_DEFINED
#else
#define yy_create_buffer das_yy_create_buffer
#endif
#ifdef yy_delete_buffer
#define das_yy_delete_buffer_ALREADY_DEFINED
#else
#define yy_delete_buffer das_yy_delete_buffer
#endif
#ifdef yy_scan_buffer
#define das_yy_scan_buffer_ALREADY_DEFINED
#else
#define yy_scan_buffer das_yy_scan_buffer
#endif
#ifdef yy_scan_string
#define das_yy_scan_string_ALREADY_DEFINED
#else
#define yy_scan_string das_yy_scan_string
#endif
#ifdef yy_scan_bytes
#define das_yy_scan_bytes_ALREADY_DEFINED
#else
#define yy_scan_bytes das_yy_scan_bytes
#endif
#ifdef yy_init_buffer
#define das_yy_init_buffer_ALREADY_DEFINED
#else
#define yy_init_buffer das_yy_init_buffer
#endif
#ifdef yy_flush_buffer
#define das_yy_flush_buffer_ALREADY_DEFINED
#else
#define yy_flush_buffer das_yy_flush_buffer
#endif
#ifdef yy_load_buffer_state
#define das_yy_load_buffer_state_ALREADY_DEFINED
#else
#define yy_load_buffer_state das_yy_load_buffer_state
#endif
#ifdef yy_switch_to_buffer
#define das_yy_switch_to_buffer_ALREADY_DEFINED
#else
#define yy_switch_to_buffer das_yy_switch_to_buffer
#endif
#ifdef yypush_buffer_state
#define das_yypush_buffer_state_ALREADY_DEFINED
#else
#define yypush_buffer_state das_yypush_buffer_state
#endif
#ifdef yypop_buffer_state
#define das_yypop_buffer_state_ALREADY_DEFINED
#else
#define yypop_buffer_state das_yypop_buffer_state
#endif
#ifdef yyensure_buffer_stack
#define das_yyensure_buffer_stack_ALREADY_DEFINED
#else
#define yyensure_buffer_stack das_yyensure_buffer_stack
#endif
#ifdef yylex
#define das_yylex_ALREADY_DEFINED
#else
#define yylex das_yylex
#endif
#ifdef yyrestart
#define das_yyrestart_ALREADY_DEFINED
#else
#define yyrestart das_yyrestart
#endif
#ifdef yylex_init
#define das_yylex_init_ALREADY_DEFINED
#else
#define yylex_init das_yylex_init
#endif
#ifdef yylex_init_extra
#define das_yylex_init_extra_ALREADY_DEFINED
#else
#define yylex_init_extra das_yylex_init_extra
#endif
#ifdef yylex_destroy
#define das_yylex_destroy_ALREADY_DEFINED
#else
#define yylex_destroy das_yylex_destroy
#endif
#ifdef yyget_debug
#define das_yyget_debug_ALREADY_DEFINED
#else
#define yyget_debug das_yyget_debug
#endif
#ifdef yyset_debug
#define das_yyset_debug_ALREADY_DEFINED
#else
#define yyset_debug das_yyset_debug
#endif
#ifdef yyget_extra
#define das_yyget_extra_ALREADY_DEFINED
#else
#define yyget_extra das_yyget_extra
#endif
#ifdef yyset_extra
#define das_yyset_extra_ALREADY_DEFINED
#else
#define yyset_extra das_yyset_extra
#endif
#ifdef yyget_in
#define das_yyget_in_ALREADY_DEFINED
#else
#define yyget_in das_yyget_in
#endif
#ifdef yyset_in
#define das_yyset_in_ALREADY_DEFINED
#else
#define yyset_in das_yyset_in
#endif
#ifdef yyget_out
#define das_yyget_out_ALREADY_DEFINED
#else
#define yyget_out das_yyget_out
#endif
#ifdef yyset_out
#define das_yyset_out_ALREADY_DEFINED
#else
#define yyset_out das_yyset_out
#endif
#ifdef yyget_leng
#define das_yyget_leng_ALREADY_DEFINED
#else
#define yyget_leng das_yyget_leng
#endif
#ifdef yyget_text
#define das_yyget_text_ALREADY_DEFINED
#else
#define yyget_text das_yyget_text
#endif
#ifdef yyget_lineno
#define das_yyget_lineno_ALREADY_DEFINED
#else
#define yyget_lineno das_yyget_lineno
#endif
#ifdef yyset_lineno
#define das_yyset_lineno_ALREADY_DEFINED
#else
#define yyset_lineno das_yyset_lineno
#endif
#ifdef yyget_column
#define das_yyget_column_ALREADY_DEFINED
#else
#define yyget_column das_yyget_column
#endif
#ifdef yyset_column
#define das_yyset_column_ALREADY_DEFINED
#else
#define yyset_column das_yyset_column
#endif
#ifdef yywrap
#define das_yywrap_ALREADY_DEFINED
#else
#define yywrap das_yywrap
#endif
#ifdef yyget_lval
#define das_yyget_lval_ALREADY_DEFINED
#else
#define yyget_lval das_yyget_lval
#endif
#ifdef yyset_lval
#define das_yyset_lval_ALREADY_DEFINED
#else
#define yyset_lval das_yyset_lval
#endif
#ifdef yyalloc
#define das_yyalloc_ALREADY_DEFINED
#else
#define yyalloc das_yyalloc
#endif
#ifdef yyrealloc
#define das_yyrealloc_ALREADY_DEFINED
#else
#define yyrealloc das_yyrealloc
#endif
#ifdef yyfree
#define das_yyfree_ALREADY_DEFINED
#else
#define yyfree das_yyfree
#endif
/* First, we deal with platform-specific or compiler-specific issues. */
/* begin standard C headers. */
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
/* end standard C headers. */
/* flex integer type definitions */
#ifndef FLEXINT_H
#define FLEXINT_H
/* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */
#if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
/* C99 says to define __STDC_LIMIT_MACROS before including stdint.h,
* if you want the limit (max/min) macros for int types.
*/
#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS 1
#endif
#include <inttypes.h>
typedef int8_t flex_int8_t;
typedef uint8_t flex_uint8_t;
typedef int16_t flex_int16_t;
typedef uint16_t flex_uint16_t;
typedef int32_t flex_int32_t;
typedef uint32_t flex_uint32_t;
#else
typedef signed char flex_int8_t;
typedef short int flex_int16_t;
typedef int flex_int32_t;
typedef unsigned char flex_uint8_t;
typedef unsigned short int flex_uint16_t;
typedef unsigned int flex_uint32_t;
/* Limits of integral types. */
#ifndef INT8_MIN
#define INT8_MIN (-128)
#endif
#ifndef INT16_MIN
#define INT16_MIN (-32767-1)
#endif
#ifndef INT32_MIN
#define INT32_MIN (-2147483647-1)
#endif
#ifndef INT8_MAX
#define INT8_MAX (127)
#endif
#ifndef INT16_MAX
#define INT16_MAX (32767)
#endif
#ifndef INT32_MAX
#define INT32_MAX (2147483647)
#endif
#ifndef UINT8_MAX
#define UINT8_MAX (255U)
#endif
#ifndef UINT16_MAX
#define UINT16_MAX (65535U)
#endif
#ifndef UINT32_MAX
#define UINT32_MAX (4294967295U)
#endif
#ifndef SIZE_MAX
#define SIZE_MAX (~(size_t)0)
#endif
#endif /* ! C99 */
#endif /* ! FLEXINT_H */
/* begin standard C++ headers. */
/* TODO: this is always defined, so inline it */
#define yyconst const
#if defined(__GNUC__) && __GNUC__ >= 3
#define yynoreturn __attribute__((__noreturn__))
#else
#define yynoreturn
#endif
/* Returned upon end-of-file. */
#define YY_NULL 0
/* Promotes a possibly negative, possibly signed char to an
* integer in range [0..255] for use as an array index.
*/
#define YY_SC_TO_UI(c) ((YY_CHAR) (c))
/* An opaque pointer. */
#ifndef YY_TYPEDEF_YY_SCANNER_T
#define YY_TYPEDEF_YY_SCANNER_T
typedef void* yyscan_t;
#endif
/* For convenience, these vars (plus the bison vars far below)
are macros in the reentrant scanner. */
#define yyin yyg->yyin_r
#define yyout yyg->yyout_r
#define yyextra yyg->yyextra_r
#define yyleng yyg->yyleng_r
#define yytext yyg->yytext_r
#define yylineno (YY_CURRENT_BUFFER_LVALUE->yy_bs_lineno)
#define yycolumn (YY_CURRENT_BUFFER_LVALUE->yy_bs_column)
#define yy_flex_debug yyg->yy_flex_debug_r
/* Enter a start condition. This macro really ought to take a parameter,
* but we do it the disgusting crufty way forced on us by the ()-less
* definition of BEGIN.
*/
#define BEGIN yyg->yy_start = 1 + 2 *
/* Translate the current start state into a value that can be later handed
* to BEGIN to return to the state. The YYSTATE alias is for lex
* compatibility.
*/
#define YY_START ((yyg->yy_start - 1) / 2)
#define YYSTATE YY_START
/* Action number for EOF rule of a given start state. */
#define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1)
/* Special action meaning "start processing a new file". */
#define YY_NEW_FILE yyrestart( yyin , yyscanner )
#define YY_END_OF_BUFFER_CHAR 0
/* Size of default input buffer. */
#ifndef YY_BUF_SIZE
#ifdef __ia64__
/* On IA-64, the buffer size is 16k, not 8k.
* Moreover, YY_BUF_SIZE is 2*YY_READ_BUF_SIZE in the general case.
* Ditto for the __ia64__ case accordingly.
*/
#define YY_BUF_SIZE 32768
#else
#define YY_BUF_SIZE 16384
#endif /* __ia64__ */
#endif
/* The state buf must be large enough to hold one state per character in the main buffer.
*/
#define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type))
#ifndef YY_TYPEDEF_YY_BUFFER_STATE
#define YY_TYPEDEF_YY_BUFFER_STATE
typedef struct yy_buffer_state *YY_BUFFER_STATE;
#endif
#ifndef YY_TYPEDEF_YY_SIZE_T
#define YY_TYPEDEF_YY_SIZE_T
typedef size_t yy_size_t;
#endif
#define EOB_ACT_CONTINUE_SCAN 0
#define EOB_ACT_END_OF_FILE 1
#define EOB_ACT_LAST_MATCH 2
/* Note: We specifically omit the test for yy_rule_can_match_eol because it requires
* access to the local variable yy_act. Since yyless() is a macro, it would break
* existing scanners that call yyless() from OUTSIDE yylex.
* One obvious solution it to make yy_act a global. I tried that, and saw
* a 5% performance hit in a non-yylineno scanner, because yy_act is
* normally declared as a register variable-- so it is not worth it.
*/
#define YY_LESS_LINENO(n) \
do { \
int yyl;\
for ( yyl = n; yyl < yyleng; ++yyl )\
if ( yytext[yyl] == '\n' )\
--yylineno;\
}while(0)
#define YY_LINENO_REWIND_TO(dst) \
do {\
const char *p;\
for ( p = yy_cp-1; p >= (dst); --p)\
if ( *p == '\n' )\
--yylineno;\
}while(0)
/* Return all but the first "n" matched characters back to the input stream. */
#define yyless(n) \
do \
{ \
/* Undo effects of setting up yytext. */ \
int yyless_macro_arg = (n); \
YY_LESS_LINENO(yyless_macro_arg);\
*yy_cp = yyg->yy_hold_char; \
YY_RESTORE_YY_MORE_OFFSET \
yyg->yy_c_buf_p = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \
YY_DO_BEFORE_ACTION; /* set up yytext again */ \
} \
while ( 0 )
#define unput(c) yyunput( c, yyg->yytext_ptr , yyscanner )
#ifndef YY_STRUCT_YY_BUFFER_STATE
#define YY_STRUCT_YY_BUFFER_STATE
struct yy_buffer_state
{
FILE *yy_input_file;
char *yy_ch_buf; /* input buffer */
char *yy_buf_pos; /* current position in input buffer */
/* Size of input buffer in bytes, not including room for EOB
* characters.
*/
int yy_buf_size;
/* Number of characters read into yy_ch_buf, not including EOB
* characters.
*/
int yy_n_chars;
/* Whether we "own" the buffer - i.e., we know we created it,
* and can realloc() it to grow it, and should free() it to
* delete it.
*/
int yy_is_our_buffer;
/* Whether this is an "interactive" input source; if so, and
* if we're using stdio for input, then we want to use getc()
* instead of fread(), to make sure we stop fetching input after
* each newline.
*/
int yy_is_interactive;
/* Whether we're considered to be at the beginning of a line.
* If so, '^' rules will be active on the next match, otherwise
* not.
*/
int yy_at_bol;
int yy_bs_lineno; /**< The line count. */
int yy_bs_column; /**< The column count. */
/* Whether to try to fill the input buffer when we reach the
* end of it.
*/
int yy_fill_buffer;
int yy_buffer_status;
#define YY_BUFFER_NEW 0
#define YY_BUFFER_NORMAL 1
/* When an EOF's been seen but there's still some text to process
* then we mark the buffer as YY_EOF_PENDING, to indicate that we
* shouldn't try reading from the input source any more. We might
* still have a bunch of tokens to match, though, because of
* possible backing-up.
*
* When we actually see the EOF, we change the status to "new"
* (via yyrestart()), so that the user can continue scanning by
* just pointing yyin at a new input file.
*/
#define YY_BUFFER_EOF_PENDING 2
};
#endif /* !YY_STRUCT_YY_BUFFER_STATE */
/* We provide macros for accessing buffer states in case in the
* future we want to put the buffer states in a more general
* "scanner state".
*
* Returns the top of the stack, or NULL.
*/
#define YY_CURRENT_BUFFER ( yyg->yy_buffer_stack \
? yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] \
: NULL)
/* Same as previous macro, but useful when we know that the buffer stack is not
* NULL or when we need an lvalue. For internal use only.
*/
#define YY_CURRENT_BUFFER_LVALUE yyg->yy_buffer_stack[yyg->yy_buffer_stack_top]
void yyrestart ( FILE *input_file , yyscan_t yyscanner );
void yy_switch_to_buffer ( YY_BUFFER_STATE new_buffer , yyscan_t yyscanner );
YY_BUFFER_STATE yy_create_buffer ( FILE *file, int size , yyscan_t yyscanner );
void yy_delete_buffer ( YY_BUFFER_STATE b , yyscan_t yyscanner );
void yy_flush_buffer ( YY_BUFFER_STATE b , yyscan_t yyscanner );
void yypush_buffer_state ( YY_BUFFER_STATE new_buffer , yyscan_t yyscanner );
void yypop_buffer_state ( yyscan_t yyscanner );
static void yyensure_buffer_stack ( yyscan_t yyscanner );
static void yy_load_buffer_state ( yyscan_t yyscanner );
static void yy_init_buffer ( YY_BUFFER_STATE b, FILE *file , yyscan_t yyscanner );
#define YY_FLUSH_BUFFER yy_flush_buffer( YY_CURRENT_BUFFER , yyscanner)
YY_BUFFER_STATE yy_scan_buffer ( char *base, yy_size_t size , yyscan_t yyscanner );
YY_BUFFER_STATE yy_scan_string ( const char *yy_str , yyscan_t yyscanner );
YY_BUFFER_STATE yy_scan_bytes ( const char *bytes, int len , yyscan_t yyscanner );
void *yyalloc ( yy_size_t , yyscan_t yyscanner );
void *yyrealloc ( void *, yy_size_t , yyscan_t yyscanner );
void yyfree ( void * , yyscan_t yyscanner );
#define yy_new_buffer yy_create_buffer
#define yy_set_interactive(is_interactive) \
{ \
if ( ! YY_CURRENT_BUFFER ){ \
yyensure_buffer_stack (yyscanner); \
YY_CURRENT_BUFFER_LVALUE = \
yy_create_buffer( yyin, YY_BUF_SIZE , yyscanner); \
} \
YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \
}
#define yy_set_bol(at_bol) \
{ \
if ( ! YY_CURRENT_BUFFER ){\
yyensure_buffer_stack (yyscanner); \
YY_CURRENT_BUFFER_LVALUE = \
yy_create_buffer( yyin, YY_BUF_SIZE , yyscanner); \
} \
YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \
}
#define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol)
/* Begin user sect3 */
#define das_yywrap(yyscanner) (/*CONSTCOND*/1)
#define YY_SKIP_YYWRAP
typedef flex_uint8_t YY_CHAR;
typedef int yy_state_type;
#define yytext_ptr yytext_r
static yy_state_type yy_get_previous_state ( yyscan_t yyscanner );
static yy_state_type yy_try_NUL_trans ( yy_state_type current_state , yyscan_t yyscanner);
static int yy_get_next_buffer ( yyscan_t yyscanner );
static void yynoreturn yy_fatal_error ( const char* msg , yyscan_t yyscanner );
/* Done after the current pattern has been matched and before the
* corresponding action - sets up yytext.
*/
#define YY_DO_BEFORE_ACTION \
yyg->yytext_ptr = yy_bp; \
yyleng = (int) (yy_cp - yy_bp); \
yyg->yy_hold_char = *yy_cp; \
*yy_cp = '\0'; \
yyg->yy_c_buf_p = yy_cp;
#define YY_NUM_RULES 212
#define YY_END_OF_BUFFER 213
/* This struct is not used in this scanner,
but its presence is necessary. */
struct yy_trans_info
{
flex_int32_t yy_verify;
flex_int32_t yy_nxt;
};
static const flex_int16_t yy_accept[600] =
{ 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
29, 29, 0, 0, 0, 0, 213, 212, 28, 26,
24, 28, 25, 28, 28, 28, 23, 22, 21, 20,
16, 23, 17, 12, 13, 12, 12, 12, 8, 9,
31, 30, 29, 211, 209, 210, 208, 211, 131, 211,
211, 211, 211, 156, 155, 211, 211, 211, 211, 211,
142, 142, 211, 211, 211, 211, 211, 211, 130, 158,
157, 211, 130, 130, 130, 130, 130, 130, 130, 130,
130, 130, 130, 130, 130, 130, 130, 130, 130, 130,
130, 130, 160, 211, 159, 15, 14, 0, 24, 0,
2, 3, 6, 19, 18, 11, 10, 31, 29, 195,
180, 184, 187, 0, 0, 4, 179, 190, 176, 191,
177, 174, 147, 5, 7, 178, 148, 142, 0, 149,
140, 141, 0, 140, 161, 173, 175, 199, 192, 169,
194, 204, 193, 197, 172, 170, 171, 0, 0, 0,
130, 205, 206, 189, 186, 130, 130, 130, 130, 90,
130, 130, 130, 130, 130, 130, 130, 130, 130, 130,
130, 130, 130, 130, 130, 130, 130, 130, 130, 130,
35, 130, 82, 91, 130, 130, 130, 130, 130, 130,
130, 130, 130, 130, 130, 130, 130, 130, 130, 130,
130, 130, 130, 130, 130, 130, 130, 130, 130, 130,
130, 130, 130, 130, 207, 188, 162, 185, 0, 0,
27, 0, 181, 138, 0, 0, 0, 0, 0, 0,
0, 147, 0, 0, 210, 0, 147, 0, 148, 0,
0, 150, 139, 146, 153, 198, 201, 0, 164, 0,
0, 200, 196, 168, 0, 0, 183, 130, 130, 43,
130, 130, 130, 130, 130, 130, 130, 130, 130, 130,
41, 130, 130, 130, 130, 130, 130, 130, 130, 130,
130, 33, 130, 130, 130, 130, 130, 110, 130, 130,
130, 46, 130, 100, 130, 130, 130, 130, 130, 130,
130, 130, 130, 130, 130, 130, 130, 130, 130, 130,
130, 130, 130, 52, 130, 130, 130, 130, 130, 130,
48, 130, 130, 130, 130, 130, 182, 0, 0, 137,
132, 135, 134, 136, 133, 0, 147, 151, 0, 0,
147, 0, 0, 148, 152, 150, 0, 144, 145, 203,
165, 166, 0, 202, 167, 130, 93, 130, 130, 104,
130, 130, 105, 130, 71, 130, 130, 130, 130, 130,
130, 37, 39, 51, 130, 130, 130, 130, 130, 130,
130, 56, 130, 130, 130, 114, 115, 116, 130, 111,
130, 130, 130, 0, 0, 130, 94, 130, 130, 130,
73, 130, 130, 130, 130, 130, 130, 130, 130, 130,
130, 130, 130, 130, 130, 102, 130, 99, 117, 130,
130, 130, 0, 0, 130, 106, 130, 130, 42, 130,
0, 0, 147, 151, 154, 143, 0, 163, 130, 80,
130, 130, 62, 97, 50, 68, 130, 130, 92, 130,
130, 130, 103, 130, 126, 130, 130, 130, 130, 112,
113, 130, 55, 130, 0, 130, 130, 130, 130, 130,
130, 108, 130, 130, 130, 130, 130, 130, 130, 130,
130, 130, 79, 66, 130, 130, 130, 122, 123, 124,
130, 119, 130, 130, 130, 0, 130, 70, 34, 96,
0, 130, 44, 130, 130, 101, 125, 78, 130, 130,
127, 128, 129, 130, 130, 130, 130, 130, 64, 0,
45, 57, 130, 130, 130, 130, 58, 130, 130, 130,
95, 76, 85, 130, 130, 107, 49, 130, 130, 120,
121, 89, 72, 109, 0, 47, 130, 0, 130, 130,
130, 130, 40, 130, 130, 130, 32, 130, 130, 59,
130, 86, 53, 130, 61, 130, 130, 54, 130, 0,
88, 67, 0, 77, 118, 69, 84, 63, 130, 83,
81, 60, 75, 130, 130, 130, 130, 98, 1, 65,
130, 87, 130, 36, 130, 130, 74, 38, 0
} ;
static const YY_CHAR yy_ec[256] =
{ 0,
1, 1, 1, 1, 1, 1, 1, 1, 2, 3,
1, 1, 4, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 5, 6, 7, 8, 9, 10, 11, 12, 13,
14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
24, 25, 26, 27, 26, 28, 26, 29, 1, 30,
31, 32, 33, 34, 35, 35, 35, 35, 36, 37,
38, 38, 38, 38, 38, 39, 38, 38, 38, 38,
38, 38, 38, 38, 40, 38, 38, 41, 38, 38,
42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
52, 53, 54, 55, 56, 38, 57, 58, 59, 60,
61, 62, 63, 64, 65, 66, 67, 68, 69, 70,
71, 38, 72, 73, 74, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1
} ;
static const YY_CHAR yy_meta[75] =
{ 0,
1, 2, 3, 2, 2, 1, 4, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
5, 5, 5, 5, 5, 5, 5, 5, 1, 1,
1, 1, 1, 1, 6, 5, 5, 7, 7, 7,
7, 1, 1, 1, 1, 7, 7, 6, 6, 6,
6, 5, 5, 7, 7, 7, 7, 8, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 1, 1, 1
} ;
static const flex_int16_t yy_base[619] =
{ 0,
0, 0, 0, 8, 15, 22, 27, 29, 985, 984,
32, 36, 94, 0, 983, 982, 984, 989, 989, 48,
989, 52, 57, 45, 963, 28, 989, 989, 989, 989,
989, 2, 989, 989, 989, 989, 962, 966, 989, 989,
0, 989, 975, 989, 989, 989, 989, 948, 989, 56,
947, 158, 934, 989, 989, 44, 154, 155, 153, 168,
181, 22, 57, 164, 58, 140, 177, 196, 0, 142,
989, 166, 178, 167, 188, 163, 180, 196, 180, 200,
164, 915, 195, 23, 207, 216, 217, 213, 225, 225,
135, 919, 902, 247, 989, 989, 989, 288, 989, 277,
989, 989, 255, 989, 989, 989, 989, 0, 968, 989,
989, 941, 989, 959, 270, 989, 989, 989, 989, 989,
989, 989, 259, 989, 294, 989, 273, 265, 321, 989,
989, 249, 0, 917, 989, 989, 989, 162, 989, 348,
989, 989, 989, 284, 989, 989, 989, 327, 896, 336,
0, 989, 989, 989, 937, 902, 915, 917, 900, 898,
896, 895, 899, 898, 906, 892, 908, 895, 269, 887,
298, 886, 890, 893, 890, 888, 884, 887, 886, 879,
0, 882, 258, 0, 891, 269, 876, 890, 871, 881,
204, 886, 872, 880, 886, 874, 306, 885, 884, 883,
307, 881, 293, 867, 866, 867, 861, 875, 876, 859,
866, 309, 855, 868, 989, 989, 989, 888, 352, 364,
989, 367, 989, 989, 906, 905, 904, 903, 902, 901,
367, 989, 859, 378, 989, 379, 360, 398, 989, 858,
379, 406, 989, 396, 989, 879, 989, 435, 989, 445,
889, 989, 877, 989, 440, 834, 989, 840, 841, 0,
856, 836, 841, 848, 850, 841, 850, 831, 831, 293,
0, 843, 842, 844, 839, 839, 831, 357, 824, 840,
839, 0, 836, 833, 823, 825, 824, 449, 817, 828,
830, 476, 811, 0, 819, 812, 819, 810, 808, 804,
813, 816, 808, 808, 800, 799, 807, 800, 799, 796,
385, 803, 808, 0, 801, 806, 791, 808, 807, 794,
480, 802, 788, 793, 795, 791, 989, 466, 448, 989,
989, 989, 989, 989, 989, 480, 488, 989, 455, 505,
989, 795, 526, 534, 989, 989, 794, 989, 282, 989,
989, 989, 843, 989, 989, 781, 0, 773, 784, 0,
786, 784, 0, 783, 0, 774, 772, 781, 770, 782,
776, 0, 0, 0, 783, 776, 779, 772, 763, 762,
763, 0, 770, 758, 797, 0, 0, 0, 798, 0,
774, 763, 769, 515, 799, 760, 0, 769, 755, 751,
0, 766, 757, 760, 743, 744, 753, 744, 755, 754,
739, 748, 743, 752, 749, 0, 748, 405, 515, 746,
733, 743, 561, 776, 747, 0, 742, 741, 0, 741,
784, 551, 572, 989, 989, 989, 787, 989, 741, 0,
736, 735, 0, 0, 0, 0, 726, 733, 0, 732,
717, 732, 0, 723, 474, 724, 731, 728, 726, 0,
0, 710, 0, 727, 771, 721, 706, 711, 714, 703,
718, 0, 715, 714, 701, 700, 678, 677, 671, 666,
643, 623, 0, 0, 636, 569, 601, 0, 0, 0,
602, 0, 574, 558, 571, 619, 561, 0, 0, 0,
0, 570, 0, 561, 551, 0, 0, 0, 561, 545,
0, 0, 0, 554, 548, 557, 559, 549, 0, 605,
989, 0, 546, 541, 554, 550, 0, 526, 525, 536,
0, 0, 0, 524, 539, 0, 0, 531, 517, 0,
0, 578, 0, 0, 566, 989, 502, 560, 498, 494,
492, 468, 0, 464, 461, 452, 0, 431, 422, 0,
427, 0, 0, 405, 0, 400, 401, 0, 401, 599,
989, 0, 452, 0, 0, 0, 0, 0, 382, 0,
0, 0, 0, 353, 347, 352, 355, 0, 989, 0,
334, 0, 211, 0, 147, 40, 0, 0, 989, 630,
638, 646, 654, 662, 670, 678, 686, 694, 698, 706,
710, 718, 722, 726, 732, 740, 748, 756
} ;
static const flex_int16_t yy_def[619] =
{ 0,
600, 600, 601, 601, 602, 602, 603, 603, 604, 604,
605, 605, 599, 13, 606, 606, 599, 599, 599, 599,
599, 599, 599, 599, 599, 599, 599, 599, 599, 599,
599, 599, 599, 599, 599, 599, 599, 599, 599, 599,
607, 599, 599, 599, 599, 599, 599, 599, 599, 599,
599, 599, 608, 599, 599, 599, 599, 599, 599, 599,
599, 61, 599, 599, 599, 599, 599, 599, 609, 599,
599, 599, 609, 609, 609, 609, 609, 609, 609, 609,
609, 609, 609, 609, 609, 609, 609, 609, 609, 609,
609, 609, 599, 599, 599, 599, 599, 599, 599, 599,
599, 599, 610, 599, 599, 599, 599, 607, 599, 599,
599, 599, 599, 599, 599, 599, 599, 599, 599, 599,
599, 599, 611, 599, 612, 599, 613, 61, 599, 599,
599, 599, 614, 599, 599, 599, 599, 599, 599, 599,
599, 599, 599, 599, 599, 599, 599, 599, 599, 599,
609, 599, 599, 599, 599, 609, 609, 609, 609, 609,
609, 609, 609, 609, 609, 609, 609, 609, 609, 609,
609, 609, 609, 609, 609, 609, 609, 609, 609, 609,
609, 609, 609, 609, 609, 609, 609, 609, 609, 609,
609, 609, 609, 609, 609, 609, 609, 609, 609, 609,
609, 609, 609, 609, 609, 609, 609, 609, 609, 609,
609, 609, 609, 609, 599, 599, 599, 599, 599, 610,
599, 610, 599, 599, 599, 599, 599, 599, 599, 599,
599, 599, 599, 612, 599, 612, 613, 599, 599, 599,
599, 599, 599, 614, 599, 599, 599, 599, 599, 599,
599, 599, 599, 599, 599, 599, 599, 609, 609, 609,
609, 609, 609, 609, 609, 609, 609, 609, 609, 609,
609, 609, 609, 609, 609, 609, 609, 609, 609, 609,
609, 609, 609, 609, 609, 609, 609, 609, 609, 609,
609, 609, 609, 609, 609, 609, 609, 609, 609, 609,
609, 609, 609, 609, 609, 609, 609, 609, 609, 609,
609, 609, 609, 609, 609, 609, 609, 609, 609, 609,
609, 609, 609, 609, 609, 609, 599, 599, 610, 599,
599, 599, 599, 599, 599, 599, 599, 599, 612, 599,
599, 599, 599, 599, 599, 599, 599, 599, 599, 599,
599, 599, 615, 599, 599, 609, 609, 609, 609, 609,
609, 609, 609, 609, 609, 609, 609, 609, 609, 609,
609, 609, 609, 609, 609, 609, 609, 609, 609, 609,
609, 609, 609, 609, 609, 609, 609, 609, 609, 609,
609, 609, 609, 599, 599, 609, 609, 609, 609, 609,
609, 609, 609, 609, 609, 609, 609, 609, 609, 609,
609, 609, 609, 609, 609, 609, 609, 609, 609, 609,
609, 609, 599, 599, 609, 609, 609, 609, 609, 609,
599, 599, 599, 599, 599, 599, 615, 599, 609, 609,
609, 609, 609, 609, 609, 609, 609, 609, 609, 609,
609, 609, 609, 609, 609, 609, 609, 609, 609, 609,
609, 609, 609, 609, 616, 609, 609, 609, 609, 609,
609, 609, 609, 609, 609, 609, 609, 609, 609, 609,
609, 609, 609, 609, 609, 609, 609, 609, 609, 609,
609, 609, 609, 609, 609, 617, 609, 609, 609, 609,
618, 609, 609, 609, 609, 609, 609, 609, 609, 609,
609, 609, 609, 609, 609, 609, 609, 609, 609, 616,
599, 609, 609, 609, 609, 609, 609, 609, 609, 609,
609, 609, 609, 609, 609, 609, 609, 609, 609, 609,
609, 609, 609, 609, 617, 599, 609, 618, 609, 609,
609, 609, 609, 609, 609, 609, 609, 609, 609, 609,
609, 609, 609, 609, 609, 609, 609, 609, 609, 599,
599, 609, 599, 609, 609, 609, 609, 609, 609, 609,
609, 609, 609, 609, 609, 609, 609, 609, 599, 609,
609, 609, 609, 609, 609, 609, 609, 609, 0, 599,
599, 599, 599, 599, 599, 599, 599, 599, 599, 599,
599, 599, 599, 599, 599, 599, 599, 599
} ;
static const flex_int16_t yy_nxt[1064] =
{ 0,
599, 20, 21, 22, 23, 599, 599, 24, 104, 20,
21, 22, 23, 599, 25, 24, 28, 29, 30, 26,
599, 31, 25, 28, 29, 30, 599, 26, 31, 35,
36, 35, 36, 42, 18, 18, 43, 42, 18, 18,
43, 37, 102, 37, 105, 599, 38, 103, 38, 98,
99, 98, 98, 98, 99, 98, 98, 32, 98, 99,
98, 98, 599, 116, 32, 100, 100, 100, 100, 100,
100, 100, 100, 104, 117, 104, 100, 100, 100, 100,
100, 100, 100, 100, 191, 135, 33, 136, 141, 142,
192, 599, 598, 33, 44, 45, 46, 47, 47, 48,
49, 50, 44, 51, 52, 53, 54, 55, 56, 57,
44, 58, 59, 60, 61, 62, 62, 62, 62, 62,
62, 62, 63, 64, 65, 66, 67, 68, 69, 69,
69, 69, 69, 69, 69, 70, 44, 71, 72, 69,
44, 73, 74, 75, 76, 77, 78, 79, 69, 80,
69, 81, 82, 83, 84, 85, 69, 86, 87, 88,
89, 90, 91, 69, 92, 93, 94, 95, 112, 118,
143, 144, 120, 123, 123, 123, 123, 123, 123, 123,
123, 137, 124, 152, 119, 121, 122, 125, 113, 212,
213, 246, 247, 138, 139, 145, 154, 148, 126, 127,
148, 128, 128, 128, 128, 128, 128, 128, 128, 146,
155, 186, 597, 153, 169, 187, 129, 130, 147, 131,
132, 133, 162, 170, 163, 149, 156, 164, 157, 150,
165, 179, 129, 130, 158, 166, 140, 171, 134, 172,
180, 159, 160, 174, 161, 167, 189, 132, 168, 173,
133, 175, 181, 176, 193, 296, 177, 221, 182, 183,
202, 190, 178, 196, 184, 185, 596, 197, 198, 297,
194, 199, 210, 195, 222, 200, 203, 216, 217, 204,
206, 224, 201, 205, 207, 211, 208, 243, 209, 98,
99, 98, 98, 219, 231, 232, 235, 100, 100, 100,
100, 100, 100, 100, 100, 599, 243, 287, 238, 239,
231, 232, 225, 236, 252, 253, 233, 290, 226, 218,
436, 271, 227, 288, 238, 239, 272, 291, 148, 228,
240, 148, 273, 229, 599, 230, 241, 255, 241, 436,
255, 242, 242, 242, 242, 242, 242, 242, 242, 248,
249, 250, 248, 275, 310, 303, 149, 367, 368, 313,
323, 304, 276, 314, 324, 256, 221, 251, 305, 221,
311, 306, 328, 328, 328, 328, 328, 328, 328, 328,
235, 235, 336, 222, 336, 595, 329, 337, 337, 337,
337, 337, 337, 337, 337, 340, 341, 236, 339, 242,
242, 242, 242, 242, 242, 242, 242, 594, 375, 593,
592, 340, 341, 343, 376, 343, 591, 342, 344, 344,
344, 344, 344, 344, 344, 344, 242, 242, 242, 242,
242, 242, 242, 242, 348, 349, 250, 249, 250, 250,
413, 255, 346, 351, 255, 590, 250, 249, 250, 250,
221, 414, 586, 348, 251, 485, 587, 235, 346, 589,
486, 588, 349, 347, 251, 585, 584, 329, 352, 256,
385, 386, 387, 388, 339, 389, 390, 394, 583, 394,
394, 423, 431, 423, 423, 582, 328, 328, 328, 328,
328, 328, 328, 328, 581, 395, 511, 512, 513, 424,
337, 337, 337, 337, 337, 337, 337, 337, 337, 337,
337, 337, 337, 337, 337, 337, 394, 580, 394, 394,
432, 579, 432, 578, 232, 433, 433, 433, 433, 433,
433, 433, 433, 577, 395, 425, 487, 488, 489, 490,
232, 491, 492, 576, 575, 233, 344, 344, 344, 344,
344, 344, 344, 344, 344, 344, 344, 344, 344, 344,
344, 344, 423, 574, 423, 423, 573, 572, 546, 569,
239, 433, 433, 433, 433, 433, 433, 433, 433, 570,
424, 570, 570, 568, 567, 566, 239, 565, 564, 563,
571, 240, 433, 433, 433, 433, 433, 433, 433, 433,
570, 562, 570, 570, 561, 560, 559, 521, 341, 558,
557, 571, 556, 555, 554, 553, 552, 551, 550, 549,
547, 546, 544, 543, 341, 542, 541, 540, 539, 342,
18, 18, 18, 18, 18, 18, 18, 18, 19, 19,
19, 19, 19, 19, 19, 19, 27, 27, 27, 27,
27, 27, 27, 27, 34, 34, 34, 34, 34, 34,
34, 34, 39, 39, 39, 39, 39, 39, 39, 39,
41, 41, 41, 41, 41, 41, 41, 41, 96, 96,
96, 96, 96, 96, 96, 96, 108, 538, 537, 108,
108, 108, 108, 108, 114, 114, 536, 114, 114, 114,
114, 114, 151, 151, 151, 151, 220, 220, 220, 220,
220, 220, 220, 220, 123, 535, 534, 123, 234, 234,
234, 234, 234, 234, 234, 234, 237, 533, 532, 237,
244, 244, 437, 437, 437, 437, 437, 437, 437, 437,
520, 520, 520, 520, 520, 520, 520, 520, 545, 545,
545, 545, 545, 545, 545, 545, 548, 548, 548, 531,
548, 548, 548, 548, 530, 529, 528, 527, 526, 525,
524, 523, 522, 521, 519, 518, 517, 516, 515, 514,
510, 509, 508, 507, 506, 505, 504, 503, 502, 438,
501, 500, 499, 498, 497, 496, 495, 494, 493, 484,
483, 482, 481, 480, 479, 478, 477, 476, 475, 474,
473, 472, 471, 470, 469, 468, 467, 466, 465, 464,
463, 462, 461, 460, 459, 458, 457, 456, 455, 454,
453, 452, 451, 450, 449, 448, 447, 446, 445, 444,
443, 442, 441, 440, 439, 438, 435, 434, 430, 429,
428, 427, 426, 422, 421, 420, 419, 418, 417, 416,
415, 412, 411, 410, 409, 408, 407, 406, 405, 404,
403, 402, 401, 400, 399, 398, 397, 396, 393, 392,
391, 384, 383, 382, 381, 380, 379, 378, 377, 374,
373, 372, 371, 370, 369, 366, 365, 364, 363, 362,
361, 360, 359, 358, 357, 356, 355, 354, 353, 350,
345, 338, 335, 334, 333, 332, 331, 330, 327, 326,
325, 322, 321, 320, 319, 318, 317, 316, 315, 312,
309, 308, 307, 302, 301, 300, 299, 298, 295, 294,
293, 292, 289, 286, 285, 284, 283, 282, 281, 280,
279, 278, 277, 274, 270, 269, 268, 267, 266, 265,
264, 263, 262, 261, 260, 259, 258, 257, 254, 245,
224, 223, 109, 215, 214, 188, 115, 111, 110, 109,
107, 106, 101, 599, 97, 97, 40, 40, 17, 599,
599, 599, 599, 599, 599, 599, 599, 599, 599, 599,
599, 599, 599, 599, 599, 599, 599, 599, 599, 599,
599, 599, 599, 599, 599, 599, 599, 599, 599, 599,
599, 599, 599, 599, 599, 599, 599, 599, 599, 599,
599, 599, 599, 599, 599, 599, 599, 599, 599, 599,
599, 599, 599, 599, 599, 599, 599, 599, 599, 599,
599, 599, 599, 599, 599, 599, 599, 599, 599, 599,
599, 599, 599
} ;
static const flex_int16_t yy_chk[1064] =
{ 0,
0, 3, 3, 3, 3, 0, 0, 3, 32, 4,
4, 4, 4, 0, 3, 4, 5, 5, 5, 3,
0, 5, 4, 6, 6, 6, 0, 4, 6, 7,
7, 8, 8, 11, 11, 11, 11, 12, 12, 12,
12, 7, 26, 8, 32, 0, 7, 26, 8, 20,
20, 20, 20, 22, 22, 22, 22, 5, 23, 23,
23, 23, 62, 56, 6, 24, 24, 24, 24, 24,
24, 24, 24, 32, 56, 32, 50, 50, 50, 50,
50, 50, 50, 50, 84, 63, 5, 63, 65, 65,
84, 62, 596, 6, 13, 13, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 52, 57,
66, 66, 58, 59, 59, 59, 59, 59, 59, 59,
59, 64, 60, 70, 57, 58, 58, 60, 52, 91,
91, 138, 138, 64, 64, 67, 72, 68, 60, 61,
68, 61, 61, 61, 61, 61, 61, 61, 61, 67,
72, 81, 595, 70, 76, 81, 61, 61, 67, 61,
61, 61, 74, 76, 74, 68, 73, 74, 73, 68,
74, 79, 61, 61, 73, 75, 64, 77, 61, 77,
79, 73, 73, 78, 73, 75, 83, 61, 75, 77,
61, 78, 80, 78, 85, 191, 78, 103, 80, 80,
88, 83, 78, 86, 80, 80, 593, 86, 87, 191,
85, 87, 90, 85, 103, 87, 88, 94, 94, 88,
89, 115, 87, 88, 89, 90, 89, 132, 89, 98,
98, 98, 98, 100, 123, 123, 125, 100, 100, 100,
100, 100, 100, 100, 100, 128, 132, 183, 127, 127,
123, 123, 115, 125, 144, 144, 123, 186, 115, 94,
349, 169, 115, 183, 127, 127, 169, 186, 148, 115,
127, 148, 169, 115, 128, 115, 129, 150, 129, 349,
150, 129, 129, 129, 129, 129, 129, 129, 129, 140,
140, 140, 140, 171, 201, 197, 148, 270, 270, 203,
212, 197, 171, 203, 212, 150, 220, 140, 197, 222,
201, 197, 219, 219, 219, 219, 219, 219, 219, 219,
234, 236, 231, 220, 231, 591, 222, 231, 231, 231,
231, 231, 231, 231, 231, 237, 237, 234, 236, 241,
241, 241, 241, 241, 241, 241, 241, 587, 278, 586,
585, 237, 237, 238, 278, 238, 584, 237, 238, 238,
238, 238, 238, 238, 238, 238, 242, 242, 242, 242,
242, 242, 242, 242, 244, 244, 248, 248, 248, 248,
311, 255, 242, 248, 255, 579, 250, 250, 250, 250,
329, 311, 567, 244, 248, 418, 567, 339, 242, 573,
418, 569, 244, 242, 250, 566, 564, 329, 248, 255,
288, 288, 288, 288, 339, 288, 288, 292, 561, 292,
292, 321, 328, 321, 321, 559, 328, 328, 328, 328,
328, 328, 328, 328, 558, 292, 455, 455, 455, 321,
336, 336, 336, 336, 336, 336, 336, 336, 337, 337,
337, 337, 337, 337, 337, 337, 394, 556, 394, 394,
340, 555, 340, 554, 337, 340, 340, 340, 340, 340,
340, 340, 340, 552, 394, 321, 419, 419, 419, 419,
337, 419, 419, 551, 550, 337, 343, 343, 343, 343,
343, 343, 343, 343, 344, 344, 344, 344, 344, 344,
344, 344, 423, 549, 423, 423, 548, 547, 545, 539,
344, 432, 432, 432, 432, 432, 432, 432, 432, 542,
423, 542, 542, 538, 535, 534, 344, 530, 529, 528,
542, 344, 433, 433, 433, 433, 433, 433, 433, 433,
570, 526, 570, 570, 525, 524, 523, 520, 433, 518,
517, 570, 516, 515, 514, 510, 509, 505, 504, 502,
497, 496, 495, 494, 433, 493, 491, 487, 486, 433,
600, 600, 600, 600, 600, 600, 600, 600, 601, 601,
601, 601, 601, 601, 601, 601, 602, 602, 602, 602,
602, 602, 602, 602, 603, 603, 603, 603, 603, 603,
603, 603, 604, 604, 604, 604, 604, 604, 604, 604,
605, 605, 605, 605, 605, 605, 605, 605, 606, 606,
606, 606, 606, 606, 606, 606, 607, 485, 482, 607,
607, 607, 607, 607, 608, 608, 481, 608, 608, 608,
608, 608, 609, 609, 609, 609, 610, 610, 610, 610,
610, 610, 610, 610, 611, 480, 479, 611, 612, 612,
612, 612, 612, 612, 612, 612, 613, 478, 477, 613,
614, 614, 615, 615, 615, 615, 615, 615, 615, 615,
616, 616, 616, 616, 616, 616, 616, 616, 617, 617,
617, 617, 617, 617, 617, 617, 618, 618, 618, 476,
618, 618, 618, 618, 475, 474, 473, 471, 470, 469,
468, 467, 466, 465, 464, 462, 459, 458, 457, 456,
454, 452, 451, 450, 448, 447, 442, 441, 439, 437,
431, 430, 428, 427, 425, 424, 422, 421, 420, 417,
415, 414, 413, 412, 411, 410, 409, 408, 407, 406,
405, 404, 403, 402, 400, 399, 398, 396, 395, 393,
392, 391, 389, 385, 384, 383, 381, 380, 379, 378,
377, 376, 375, 371, 370, 369, 368, 367, 366, 364,
362, 361, 359, 358, 356, 353, 347, 342, 326, 325,
324, 323, 322, 320, 319, 318, 317, 316, 315, 313,
312, 310, 309, 308, 307, 306, 305, 304, 303, 302,
301, 300, 299, 298, 297, 296, 295, 293, 291, 290,
289, 287, 286, 285, 284, 283, 281, 280, 279, 277,
276, 275, 274, 273, 272, 269, 268, 267, 266, 265,
264, 263, 262, 261, 259, 258, 256, 253, 251, 246,
240, 233, 230, 229, 228, 227, 226, 225, 218, 214,
213, 211, 210, 209, 208, 207, 206, 205, 204, 202,
200, 199, 198, 196, 195, 194, 193, 192, 190, 189,
188, 187, 185, 182, 180, 179, 178, 177, 176, 175,
174, 173, 172, 170, 168, 167, 166, 165, 164, 163,
162, 161, 160, 159, 158, 157, 156, 155, 149, 134,
114, 112, 109, 93, 92, 82, 53, 51, 48, 43,
38, 37, 25, 17, 16, 15, 10, 9, 599, 599,
599, 599, 599, 599, 599, 599, 599, 599, 599, 599,
599, 599, 599, 599, 599, 599, 599, 599, 599, 599,
599, 599, 599, 599, 599, 599, 599, 599, 599, 599,
599, 599, 599, 599, 599, 599, 599, 599, 599, 599,
599, 599, 599, 599, 599, 599, 599, 599, 599, 599,
599, 599, 599, 599, 599, 599, 599, 599, 599, 599,
599, 599, 599, 599, 599, 599, 599, 599, 599, 599,
599, 599, 599
} ;
/* Table of booleans, true if rule could match eol. */
static const flex_int32_t yy_rule_can_match_eol[213] =
{ 0,
1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0,
0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, };
/* The intent behind this definition is that it'll catch
* any uses of REJECT which flex missed.
*/
#define REJECT reject_used_but_not_detected
#define yymore() yymore_used_but_not_detected
#define YY_MORE_ADJ 0
#define YY_RESTORE_YY_MORE_OFFSET
#line 1 "ds_lexer.lpp"
#line 2 "ds_lexer.lpp"
#include "daScript/misc/platform.h"
#include <inttypes.h>
#include "daScript/ast/ast.h"
#include "parser_state.h"
#include "ds_parser.hpp"
#ifndef SCNi64
#define SCNi64 "lli"
#endif
#ifndef SCNu64
#define SCNu64 "llu"
#endif
#ifndef SCNx64
#define SCNx64 "llx"
#endif
using namespace das;
union DAS_YYSTYPE;
typedef DAS_YYSTYPE YYSTYPE;
#define YY_NO_INPUT
void das_yyfatalerror(DAS_YYLTYPE * lloc, yyscan_t scanner, const string & error, CompilationError cerr = CompilationError::syntax_error);
#define YY_USER_ACTION \
yylloc_param->first_line = yylloc_param->last_line = yylineno; \
yylloc_param->first_column = yyextra->das_yycolumn; \
yylloc_param->last_column = yyextra->das_yycolumn + yyleng - 1; \
YYCOLUMN (yyextra->das_yycolumn += yyleng, "YY_USER_ACTION");
#ifdef FLEX_DEBUG
void YYCOLUMN ( int, const char * comment ) {
printf("%i:%i %s\n", yyextra->das_yycolumn, yylineno, comment ? comment : "");
}
#else
#define YYCOLUMN(expr,comment) ((expr))
#endif
void YYTAB() {
// YYCOLUMN(yyextra->das_yycolumn = (yyextra->das_yycolumn - 1 + yyextra->das_tab_size) & ~(yyextra->das_tab_size-1), "TAB");
}
void YYNEWLINE(yyscan_t yyscanner);
#define YY_DECL int yylex(DAS_YYSTYPE *yylval_param, DAS_YYLTYPE *yylloc_param, yyscan_t yyscanner)
#define YY_EXTRA_TYPE das::DasParserState *
#line 1167 "ds_lexer.cpp"
#define YY_NO_UNISTD_H 1
/* %option debug */
#line 1171 "ds_lexer.cpp"
#define INITIAL 0
#define indent 1
#define strb 2
#define c_comment 3
#define cpp_comment 4
#define include 5
#define normal 6
#define reader 7
#ifndef YY_NO_UNISTD_H
/* Special case for "unistd.h", since it is non-ANSI. We include it way
* down here because we want the user's section 1 to have been scanned first.
* The user has a chance to override it with an option.
*/
#include <unistd.h>
#endif
#ifndef YY_EXTRA_TYPE
#define YY_EXTRA_TYPE void *
#endif
/* Holds the entire state of the reentrant scanner. */
struct yyguts_t
{
/* User-defined. Not touched by flex. */
YY_EXTRA_TYPE yyextra_r;
/* The rest are the same as the globals declared in the non-reentrant scanner. */
FILE *yyin_r, *yyout_r;
size_t yy_buffer_stack_top; /**< index of top of stack. */
size_t yy_buffer_stack_max; /**< capacity of stack. */
YY_BUFFER_STATE * yy_buffer_stack; /**< Stack as an array. */
char yy_hold_char;
int yy_n_chars;
int yyleng_r;
char *yy_c_buf_p;
int yy_init;
int yy_start;
int yy_did_buffer_switch_on_eof;
int yy_start_stack_ptr;
int yy_start_stack_depth;
int *yy_start_stack;
yy_state_type yy_last_accepting_state;
char* yy_last_accepting_cpos;
int yylineno_r;
int yy_flex_debug_r;
char *yytext_r;
int yy_more_flag;
int yy_more_len;
YYSTYPE * yylval_r;
}; /* end struct yyguts_t */
static int yy_init_globals ( yyscan_t yyscanner );
/* This must go here because YYSTYPE and YYLTYPE are included
* from bison output in section 1.*/
# define yylval yyg->yylval_r
int yylex_init (yyscan_t* scanner);
int yylex_init_extra ( YY_EXTRA_TYPE user_defined, yyscan_t* scanner);
/* Accessor methods to globals.
These are made visible to non-reentrant scanners for convenience. */
int yylex_destroy ( yyscan_t yyscanner );
int yyget_debug ( yyscan_t yyscanner );
void yyset_debug ( int debug_flag , yyscan_t yyscanner );
YY_EXTRA_TYPE yyget_extra ( yyscan_t yyscanner );
void yyset_extra ( YY_EXTRA_TYPE user_defined , yyscan_t yyscanner );
FILE *yyget_in ( yyscan_t yyscanner );
void yyset_in ( FILE * _in_str , yyscan_t yyscanner );
FILE *yyget_out ( yyscan_t yyscanner );
void yyset_out ( FILE * _out_str , yyscan_t yyscanner );
int yyget_leng ( yyscan_t yyscanner );
char *yyget_text ( yyscan_t yyscanner );
int yyget_lineno ( yyscan_t yyscanner );
void yyset_lineno ( int _line_number , yyscan_t yyscanner );
int yyget_column ( yyscan_t yyscanner );
void yyset_column ( int _column_no , yyscan_t yyscanner );
YYSTYPE * yyget_lval ( yyscan_t yyscanner );
void yyset_lval ( YYSTYPE * yylval_param , yyscan_t yyscanner );
/* Macros after this point can all be overridden by user definitions in
* section 1.
*/
#ifndef YY_SKIP_YYWRAP
#ifdef __cplusplus
extern "C" int yywrap ( yyscan_t yyscanner );
#else
extern int yywrap ( yyscan_t yyscanner );
#endif
#endif
#ifndef YY_NO_UNPUT
static void yyunput ( int c, char *buf_ptr , yyscan_t yyscanner);
#endif
#ifndef yytext_ptr
static void yy_flex_strncpy ( char *, const char *, int , yyscan_t yyscanner);
#endif
#ifdef YY_NEED_STRLEN
static int yy_flex_strlen ( const char * , yyscan_t yyscanner);
#endif
#ifndef YY_NO_INPUT
#ifdef __cplusplus
static int yyinput ( yyscan_t yyscanner );
#else
static int input ( yyscan_t yyscanner );
#endif
#endif
/* Amount of stuff to slurp up with each read. */
#ifndef YY_READ_BUF_SIZE
#ifdef __ia64__
/* On IA-64, the buffer size is 16k, not 8k */
#define YY_READ_BUF_SIZE 16384
#else
#define YY_READ_BUF_SIZE 8192
#endif /* __ia64__ */
#endif
/* Copy whatever the last rule matched to the standard output. */
#ifndef ECHO
/* This used to be an fputs(), but since the string might contain NUL's,
* we now use fwrite().
*/
#define ECHO do { if (fwrite( yytext, (size_t) yyleng, 1, yyout )) {} } while (0)
#endif
/* Gets input and stuffs it into "buf". number of characters read, or YY_NULL,
* is returned in "result".
*/
#ifndef YY_INPUT
#define YY_INPUT(buf,result,max_size) \
if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \
{ \
int c = '*'; \
int n; \
for ( n = 0; n < max_size && \
(c = getc( yyin )) != EOF && c != '\n'; ++n ) \
buf[n] = (char) c; \
if ( c == '\n' ) \
buf[n++] = (char) c; \
if ( c == EOF && ferror( yyin ) ) \
YY_FATAL_ERROR( "input in flex scanner failed" ); \
result = n; \
} \
else \
{ \
errno=0; \
while ( (result = (int) fread(buf, 1, (yy_size_t) max_size, yyin)) == 0 && ferror(yyin)) \
{ \
if( errno != EINTR) \
{ \
YY_FATAL_ERROR( "input in flex scanner failed" ); \
break; \
} \
errno=0; \
clearerr(yyin); \
} \
}\
\
#endif
/* No semi-colon after return; correct usage is to write "yyterminate();" -
* we don't want an extra ';' after the "return" because that will cause
* some compilers to complain about unreachable statements.
*/
#ifndef yyterminate
#define yyterminate() return YY_NULL
#endif
/* Number of entries by which start-condition stack grows. */
#ifndef YY_START_STACK_INCR
#define YY_START_STACK_INCR 25
#endif
/* Report a fatal error. */
#ifndef YY_FATAL_ERROR
#define YY_FATAL_ERROR(msg) yy_fatal_error( msg , yyscanner)
#endif
/* end tables serialization structures and prototypes */
/* Default declaration of generated scanner - a define so the user can
* easily add parameters.
*/
#ifndef YY_DECL
#define YY_DECL_IS_OURS 1
extern int yylex \
(YYSTYPE * yylval_param , yyscan_t yyscanner);
#define YY_DECL int yylex \
(YYSTYPE * yylval_param , yyscan_t yyscanner)
#endif /* !YY_DECL */
/* Code executed at the beginning of each rule, after yytext and yyleng
* have been set up.
*/
#ifndef YY_USER_ACTION
#define YY_USER_ACTION
#endif
/* Code executed at the end of each rule. */
#ifndef YY_BREAK
#define YY_BREAK /*LINTED*/break;
#endif
#define YY_RULE_SETUP \
YY_USER_ACTION
/** The main scanner function which does all the work.
*/
YY_DECL
{
yy_state_type yy_current_state;
char *yy_cp, *yy_bp;
int yy_act;
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yylval = yylval_param;
if ( !yyg->yy_init )
{
yyg->yy_init = 1;
#ifdef YY_USER_INIT
YY_USER_INIT;
#endif
if ( ! yyg->yy_start )
yyg->yy_start = 1; /* first start state */
if ( ! yyin )
yyin = stdin;
if ( ! yyout )
yyout = stdout;
if ( ! YY_CURRENT_BUFFER ) {
yyensure_buffer_stack (yyscanner);
YY_CURRENT_BUFFER_LVALUE =
yy_create_buffer( yyin, YY_BUF_SIZE , yyscanner);
}
yy_load_buffer_state( yyscanner );
}
{
#line 74 "ds_lexer.lpp"
#line 1455 "ds_lexer.cpp"
while ( /*CONSTCOND*/1 ) /* loops until end-of-file is reached */
{
yy_cp = yyg->yy_c_buf_p;
/* Support of yytext. */
*yy_cp = yyg->yy_hold_char;
/* yy_bp points to the position in yy_ch_buf of the start of
* the current run.
*/
yy_bp = yy_cp;
yy_current_state = yyg->yy_start;
yy_match:
do
{
YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)] ;
if ( yy_accept[yy_current_state] )
{
yyg->yy_last_accepting_state = yy_current_state;
yyg->yy_last_accepting_cpos = yy_cp;
}
while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 600 )
yy_c = yy_meta[yy_c];
}
yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c];
++yy_cp;
}
while ( yy_current_state != 599 );
yy_cp = yyg->yy_last_accepting_cpos;
yy_current_state = yyg->yy_last_accepting_state;
yy_find_action:
yy_act = yy_accept[yy_current_state];
YY_DO_BEFORE_ACTION;
if ( yy_act != YY_END_OF_BUFFER && yy_rule_can_match_eol[yy_act] )
{
int yyl;
for ( yyl = 0; yyl < yyleng; ++yyl )
if ( yytext[yyl] == '\n' )
do{ yylineno++;
yycolumn=0;
}while(0)
;
}
do_action: /* This label is used only to access EOF actions. */
switch ( yy_act )
{ /* beginning of action switch */
case 0: /* must back up */
/* undo the effects of YY_DO_BEFORE_ACTION */
*yy_cp = yyg->yy_hold_char;
yy_cp = yyg->yy_last_accepting_cpos;
yy_current_state = yyg->yy_last_accepting_state;
goto yy_find_action;
case 1:
/* rule 1 can match eol */
YY_RULE_SETUP
#line 76 "ds_lexer.lpp"
{
string txt = yytext;
int lRow, lCol;
char lFile[256];
if ( sscanf ( yytext, "#%i,%i,\"%255s\"#", &lRow, &lCol, lFile )==3 ) {
lFile[strlen(lFile)-2] = 0;
auto cfi = yyextra->g_FileAccessStack.back();
string incFileName = yyextra->g_Access->getIncludeFileName(cfi->name,lFile);
auto info = yyextra->g_Access->getFileInfo(incFileName);
if ( !info ) {
das_yyfatalerror(yylloc_param,yyscanner,"can't open "+incFileName);
} else {
yyextra->g_FileAccessStack.pop_back();
yyextra->g_FileAccessStack.push_back(info);
yylineno = lRow;
YYCOLUMN ( yyextra->das_yycolumn = lCol, "LINE DIRECTIVE");
}
} else {
das_yyfatalerror(yylloc_param,yyscanner,"can't process line directive " + string(yytext),
CompilationError::invalid_line_directive); return LEXER_ERROR;
}
}
YY_BREAK
case 2:
YY_RULE_SETUP
#line 98 "ds_lexer.lpp"
das_yyfatalerror(yylloc_param,yyscanner,"Unexpected */", CompilationError::unexpected_close_comment); return LEXER_ERROR;
YY_BREAK
case 3:
YY_RULE_SETUP
#line 99 "ds_lexer.lpp"
BEGIN(c_comment); yyextra->das_c_style_depth = 1; yyextra->das_in_normal = false;
YY_BREAK
case 4:
YY_RULE_SETUP
#line 100 "ds_lexer.lpp"
das_yyfatalerror(yylloc_param,yyscanner,"Unexpected */", CompilationError::unexpected_close_comment); return LEXER_ERROR;
YY_BREAK
case 5:
YY_RULE_SETUP
#line 101 "ds_lexer.lpp"
BEGIN(c_comment); yyextra->das_c_style_depth = 1; yyextra->das_in_normal = true;
YY_BREAK
case 6:
YY_RULE_SETUP
#line 102 "ds_lexer.lpp"
BEGIN(cpp_comment);
YY_BREAK
case 7:
YY_RULE_SETUP
#line 103 "ds_lexer.lpp"
BEGIN(cpp_comment);
YY_BREAK
case 8:
YY_RULE_SETUP
#line 104 "ds_lexer.lpp"
YY_BREAK
case 9:
/* rule 9 can match eol */
YY_RULE_SETUP
#line 105 "ds_lexer.lpp"
BEGIN(normal); unput('\n');
YY_BREAK
case YY_STATE_EOF(cpp_comment):
#line 106 "ds_lexer.lpp"
BEGIN(normal);
YY_BREAK
case 10:
YY_RULE_SETUP
#line 107 "ds_lexer.lpp"
yyextra->das_c_style_depth ++;
YY_BREAK
case 11:
YY_RULE_SETUP
#line 108 "ds_lexer.lpp"
{
yyextra->das_c_style_depth --;
if ( yyextra->das_c_style_depth==0 ) {
if ( yyextra->das_in_normal ) {
BEGIN(normal);
} else {
BEGIN(indent);
}
}
}
YY_BREAK
case 12:
YY_RULE_SETUP
#line 118 "ds_lexer.lpp"
/* skipping comment body */
YY_BREAK
case 13:
/* rule 13 can match eol */
YY_RULE_SETUP
#line 119 "ds_lexer.lpp"
/* skipping comment eol */
YY_BREAK
case YY_STATE_EOF(c_comment):
#line 120 "ds_lexer.lpp"
{
das_yyfatalerror(yylloc_param,yyscanner,"end of file encountered inside c-style comment", CompilationError::comment_contains_eof);
BEGIN(normal);
}
YY_BREAK
case YY_STATE_EOF(reader):
#line 124 "ds_lexer.lpp"
{
das_yyfatalerror(yylloc_param,yyscanner,"reader constant exceeds file", CompilationError::string_constant_exceeds_file);
BEGIN(normal);
return END_OF_READ;
}
YY_BREAK
case 14:
/* rule 14 can match eol */
YY_RULE_SETUP
#line 129 "ds_lexer.lpp"
{
YYNEWLINE(yyscanner);
yylval_param->ch = yytext[0];
return STRING_CHARACTER;
}
YY_BREAK
case 15:
YY_RULE_SETUP
#line 134 "ds_lexer.lpp"
{
yylval_param->ch = yytext[0];
return STRING_CHARACTER;
}
YY_BREAK
case 16:
YY_RULE_SETUP
#line 138 "ds_lexer.lpp"
{
// assert(nested_sb==0);
BEGIN(normal);
return END_STRING;
}
YY_BREAK
case 17:
YY_RULE_SETUP
#line 143 "ds_lexer.lpp"
{
DAS_ASSERT(yyextra->das_nested_sb==0);
yyextra->das_nested_sb ++;
BEGIN(normal);
return BEGIN_STRING_EXPR;
}
YY_BREAK
case YY_STATE_EOF(strb):
#line 149 "ds_lexer.lpp"
{
das_yyfatalerror(yylloc_param,yyscanner,"string constant exceeds file", CompilationError::string_constant_exceeds_file);
BEGIN(normal);
return END_STRING;
}
YY_BREAK
case 18:
YY_RULE_SETUP
#line 154 "ds_lexer.lpp"
{
return STRING_CHARACTER_ESC;
}
YY_BREAK
case 19:
YY_RULE_SETUP
#line 157 "ds_lexer.lpp"
{
yylval_param->ch = yytext[1];
return STRING_CHARACTER;
}
YY_BREAK
case 20:
YY_RULE_SETUP
#line 161 "ds_lexer.lpp"
/* do exactly nothing */
YY_BREAK
case 21:
/* rule 21 can match eol */
YY_RULE_SETUP
#line 162 "ds_lexer.lpp"
{
yylval_param->ch = *yytext;
YYNEWLINE(yyscanner);
return STRING_CHARACTER;
}
YY_BREAK
case 22:
YY_RULE_SETUP
#line 167 "ds_lexer.lpp"
{
YYTAB();
yylval_param->ch = *yytext;
return STRING_CHARACTER;
}
YY_BREAK
case 23:
YY_RULE_SETUP
#line 172 "ds_lexer.lpp"
{
yylval_param->ch = *yytext;
return STRING_CHARACTER;
}
YY_BREAK
case 24:
/* rule 24 can match eol */
YY_RULE_SETUP
#line 176 "ds_lexer.lpp"
/* skip empty line */ {
yyextra->das_current_line_indent = 0;
YYNEWLINE(yyscanner);
}
YY_BREAK
case 25:
YY_RULE_SETUP
#line 180 "ds_lexer.lpp"
{
yyextra->das_current_line_indent++;
#ifdef FLEX_DEBUG
printf("[ ], indent=%i\n", yyextra->das_current_line_indent);
#endif
}
YY_BREAK
case 26:
YY_RULE_SETUP
#line 186 "ds_lexer.lpp"
{
yyextra->das_current_line_indent = (yyextra->das_current_line_indent + yyextra->das_tab_size) & ~(yyextra->das_tab_size-1);
#ifdef FLEX_DEBUG
printf("\\t, cli=%i\n", yyextra->das_current_line_indent);
#endif
YYTAB();
}
YY_BREAK
case 27:
/* rule 27 can match eol */
YY_RULE_SETUP
#line 193 "ds_lexer.lpp"
{
yyextra->das_current_line_indent = 0;
yyextra->das_need_oxford_comma = true;
YYNEWLINE(yyscanner);
#ifdef FLEX_DEBUG
printf("new line\n");
#endif
}
YY_BREAK
case 28:
YY_RULE_SETUP
#line 201 "ds_lexer.lpp"
{
unput(*yytext);
YYCOLUMN(yyextra->das_yycolumn--, "UNPUT");
if (yyextra->das_current_line_indent > yyextra->das_indent_level*yyextra->das_tab_size ) {
if ( yyextra->das_current_line_indent % yyextra->das_tab_size ) {
#ifdef FLEX_DEBUG
printf("INVALID INDENT at %i, emit {\n", yyextra->das_current_line_indent);
#endif
das_yyfatalerror(yylloc_param,yyscanner,"invalid indentation"); // pretend tab was pressed
yyextra->das_current_line_indent = (yyextra->das_current_line_indent + yyextra->das_tab_size) & ~(yyextra->das_tab_size-1);
}
yyextra->das_indent_level++;
#ifdef FLEX_DEBUG
printf("emit {, cli=%i, indent =%i\n", yyextra->das_current_line_indent, yyextra->das_indent_level);
#endif
return '{';
} else if (yyextra->das_current_line_indent < yyextra->das_indent_level*yyextra->das_tab_size ) {
yyextra->das_indent_level--;
#ifdef FLEX_DEBUG
printf("emit }, cli=%i, indent =%i\n", yyextra->das_current_line_indent, yyextra->das_indent_level);
#endif
return '}';
} else {
BEGIN(normal);
}
}
YY_BREAK
case YY_STATE_EOF(indent):
#line 227 "ds_lexer.lpp"
{
if ( yyextra->g_FileAccessStack.size()==1 ) {
if ( yyextra->das_indent_level ) {
yyextra->das_indent_level--;
unput('\r');
#ifdef FLEX_DEBUG
printf("emit }\n");
#endif
return '}';
} else {
return 0;
}
} else {
yypop_buffer_state(yyscanner);
yyextra->g_FileAccessStack.pop_back();
yylineno = yyextra->das_line_no.back();
yyextra->das_line_no.pop_back();
}
}
YY_BREAK
case 29:
YY_RULE_SETUP
#line 247 "ds_lexer.lpp"
/* eat the whitespace */
YY_BREAK
case 30:
YY_RULE_SETUP
#line 248 "ds_lexer.lpp"
{
YYTAB();
}
YY_BREAK
case 31:
YY_RULE_SETUP
#line 251 "ds_lexer.lpp"
{ /* got the include file name */
auto cfi = yyextra->g_FileAccessStack.back();
string incFileName = yyextra->g_Access->getIncludeFileName(cfi->name,yytext);
auto info = yyextra->g_Access->getFileInfo(incFileName);
if ( !info ) {
das_yyfatalerror(yylloc_param,yyscanner,"can't open "+incFileName);
} else {
if ( yyextra->das_already_include.find(incFileName) == yyextra->das_already_include.end() ) {
yyextra->das_already_include.insert(incFileName);
yyextra->g_FileAccessStack.push_back(info);
yyextra->das_line_no.push_back(yylineno);
yylineno = 1;
yypush_buffer_state(YY_CURRENT_BUFFER, yyscanner);
const char * src = nullptr;
uint32_t len = 0;
info->getSourceAndLength(src, len);
yy_scan_bytes(src, len, yyscanner);
}
}
BEGIN(normal);
}
YY_BREAK
case 32:
YY_RULE_SETUP
#line 273 "ds_lexer.lpp"
BEGIN(include);
YY_BREAK
case 33:
YY_RULE_SETUP
#line 274 "ds_lexer.lpp"
/* yyextra->das_need_oxford_comma = false; */ return DAS_FOR;
YY_BREAK
case 34:
YY_RULE_SETUP
#line 275 "ds_lexer.lpp"
yyextra->das_need_oxford_comma = false; return DAS_WHILE;
YY_BREAK
case 35:
YY_RULE_SETUP
#line 276 "ds_lexer.lpp"
yyextra->das_need_oxford_comma = false; return DAS_IF;
YY_BREAK
case 36:
YY_RULE_SETUP
#line 277 "ds_lexer.lpp"
yyextra->das_need_oxford_comma = false; return DAS_STATIC_IF;
YY_BREAK
case 37:
YY_RULE_SETUP
#line 278 "ds_lexer.lpp"
yyextra->das_need_oxford_comma = false; return DAS_ELIF;
YY_BREAK
case 38:
YY_RULE_SETUP
#line 279 "ds_lexer.lpp"
yyextra->das_need_oxford_comma = false; return DAS_STATIC_ELIF;
YY_BREAK
case 39:
YY_RULE_SETUP
#line 280 "ds_lexer.lpp"
yyextra->das_need_oxford_comma = false; return DAS_ELSE;
YY_BREAK
case 40:
YY_RULE_SETUP
#line 281 "ds_lexer.lpp"
yyextra->das_need_oxford_comma = false; return DAS_FINALLY;
YY_BREAK
case 41:
YY_RULE_SETUP
#line 282 "ds_lexer.lpp"
yyextra->das_need_oxford_comma = false; return DAS_DEF;
YY_BREAK
case 42:
YY_RULE_SETUP
#line 283 "ds_lexer.lpp"
yyextra->das_need_oxford_comma = false; return DAS_WITH;
YY_BREAK
case 43:
YY_RULE_SETUP
#line 284 "ds_lexer.lpp"
return DAS_AKA;
YY_BREAK
case 44:
YY_RULE_SETUP
#line 285 "ds_lexer.lpp"
return DAS_ASSUME;
YY_BREAK
case 45:
/* rule 45 can match eol */
YY_RULE_SETUP
#line 286 "ds_lexer.lpp"
yyextra->das_need_oxford_comma = false; unput('\n'); return DAS_LET;
YY_BREAK
case 46:
YY_RULE_SETUP
#line 287 "ds_lexer.lpp"
return DAS_LET;
YY_BREAK
case 47:
/* rule 47 can match eol */
YY_RULE_SETUP
#line 288 "ds_lexer.lpp"
yyextra->das_need_oxford_comma = false; unput('\n'); return DAS_VAR;
YY_BREAK
case 48:
YY_RULE_SETUP
#line 289 "ds_lexer.lpp"
return DAS_VAR;
YY_BREAK
case 49:
YY_RULE_SETUP
#line 290 "ds_lexer.lpp"
yyextra->das_need_oxford_comma = false; return DAS_STRUCT;
YY_BREAK
case 50:
YY_RULE_SETUP
#line 291 "ds_lexer.lpp"
yyextra->das_need_oxford_comma = false; return DAS_CLASS;
YY_BREAK
case 51:
YY_RULE_SETUP
#line 292 "ds_lexer.lpp"
yyextra->das_need_oxford_comma = false; return DAS_ENUM;
YY_BREAK
case 52:
YY_RULE_SETUP
#line 293 "ds_lexer.lpp"
yyextra->das_need_oxford_comma = false; return DAS_TRY;
YY_BREAK
case 53:
YY_RULE_SETUP
#line 294 "ds_lexer.lpp"
yyextra->das_need_oxford_comma = false; return DAS_CATCH;
YY_BREAK
case 54:
YY_RULE_SETUP
#line 295 "ds_lexer.lpp"
yyextra->das_need_oxford_comma = false; return DAS_TYPEDEF;
YY_BREAK
case 55:
YY_RULE_SETUP
#line 296 "ds_lexer.lpp"
return DAS_LABEL;
YY_BREAK
case 56:
YY_RULE_SETUP
#line 297 "ds_lexer.lpp"
return DAS_GOTO;
YY_BREAK
case 57:
YY_RULE_SETUP
#line 298 "ds_lexer.lpp"
return DAS_MODULE;
YY_BREAK
case 58:
YY_RULE_SETUP
#line 299 "ds_lexer.lpp"
return DAS_PUBLIC;
YY_BREAK
case 59:
YY_RULE_SETUP
#line 300 "ds_lexer.lpp"
return DAS_OPTIONS;
YY_BREAK
case 60:
YY_RULE_SETUP
#line 301 "ds_lexer.lpp"
return DAS_OPERATOR;
YY_BREAK
case 61:
YY_RULE_SETUP
#line 302 "ds_lexer.lpp"
return DAS_REQUIRE;
YY_BREAK
case 62:
YY_RULE_SETUP
#line 303 "ds_lexer.lpp"
return DAS_TBLOCK;
YY_BREAK
case 63:
YY_RULE_SETUP
#line 304 "ds_lexer.lpp"
return DAS_TFUNCTION;
YY_BREAK
case 64:
YY_RULE_SETUP
#line 305 "ds_lexer.lpp"
return DAS_TLAMBDA;
YY_BREAK
case 65:
YY_RULE_SETUP
#line 306 "ds_lexer.lpp"
return DAS_GENERATOR;
YY_BREAK
case 66:
YY_RULE_SETUP
#line 307 "ds_lexer.lpp"
return DAS_TTUPLE;
YY_BREAK
case 67:
YY_RULE_SETUP
#line 308 "ds_lexer.lpp"
return DAS_TVARIANT;
YY_BREAK
case 68:
YY_RULE_SETUP
#line 309 "ds_lexer.lpp"
return DAS_CONST;
YY_BREAK
case 69:
YY_RULE_SETUP
#line 310 "ds_lexer.lpp"
return DAS_CONTINUE;
YY_BREAK
case 70:
YY_RULE_SETUP
#line 311 "ds_lexer.lpp"
return DAS_WHERE;
YY_BREAK
case 71:
YY_RULE_SETUP
#line 312 "ds_lexer.lpp"
return DAS_CAST;
YY_BREAK
case 72:
YY_RULE_SETUP
#line 313 "ds_lexer.lpp"
return DAS_UPCAST;
YY_BREAK
case 73:
YY_RULE_SETUP
#line 314 "ds_lexer.lpp"
return DAS_PASS;
YY_BREAK
case 74:
YY_RULE_SETUP
#line 315 "ds_lexer.lpp"
return DAS_REINTERPRET;
YY_BREAK
case 75:
YY_RULE_SETUP
#line 316 "ds_lexer.lpp"
return DAS_OVERRIDE;
YY_BREAK
case 76:
YY_RULE_SETUP
#line 317 "ds_lexer.lpp"
return DAS_SEALED;
YY_BREAK
case 77:
YY_RULE_SETUP
#line 318 "ds_lexer.lpp"
return DAS_ABSTRACT;
YY_BREAK
case 78:
YY_RULE_SETUP
#line 319 "ds_lexer.lpp"
return DAS_EXPECT;
YY_BREAK
case 79:
YY_RULE_SETUP
#line 320 "ds_lexer.lpp"
return DAS_TABLE;
YY_BREAK
case 80:
YY_RULE_SETUP
#line 321 "ds_lexer.lpp"
return DAS_ARRAY;
YY_BREAK
case 81:
YY_RULE_SETUP
#line 322 "ds_lexer.lpp"
return DAS_ITERATOR;
YY_BREAK
case 82:
YY_RULE_SETUP
#line 323 "ds_lexer.lpp"
return DAS_IN;
YY_BREAK
case 83:
YY_RULE_SETUP
#line 324 "ds_lexer.lpp"
return DAS_IMPLICIT;
YY_BREAK
case 84:
YY_RULE_SETUP
#line 325 "ds_lexer.lpp"
return DAS_EXPLICIT;
YY_BREAK
case 85:
YY_RULE_SETUP
#line 326 "ds_lexer.lpp"
return DAS_SHARED;
YY_BREAK
case 86:
YY_RULE_SETUP
#line 327 "ds_lexer.lpp"
return DAS_PRIVATE;
YY_BREAK
case 87:
YY_RULE_SETUP
#line 328 "ds_lexer.lpp"
return DAS_SMART_PTR;
YY_BREAK
case 88:
YY_RULE_SETUP
#line 329 "ds_lexer.lpp"
{
unput('(');
YYCOLUMN(yyextra->das_yycolumn--, "UNPUT (");
return DAS_UNSAFE;
}
YY_BREAK
case 89:
YY_RULE_SETUP
#line 334 "ds_lexer.lpp"
yyextra->das_need_oxford_comma = false; return DAS_UNSAFE;
YY_BREAK
case 90:
YY_RULE_SETUP
#line 335 "ds_lexer.lpp"
return DAS_AS;
YY_BREAK
case 91:
YY_RULE_SETUP
#line 336 "ds_lexer.lpp"
return DAS_IS;
YY_BREAK
case 92:
YY_RULE_SETUP
#line 337 "ds_lexer.lpp"
return DAS_DEREF;
YY_BREAK
case 93:
YY_RULE_SETUP
#line 338 "ds_lexer.lpp"
return DAS_ADDR;
YY_BREAK
case 94:
YY_RULE_SETUP
#line 339 "ds_lexer.lpp"
return DAS_NULL;
YY_BREAK
case 95:
YY_RULE_SETUP
#line 340 "ds_lexer.lpp"
return DAS_RETURN;
YY_BREAK
case 96:
YY_RULE_SETUP
#line 341 "ds_lexer.lpp"
return DAS_YIELD;
YY_BREAK
case 97:
YY_RULE_SETUP
#line 342 "ds_lexer.lpp"
return DAS_BREAK;
YY_BREAK
case 98:
YY_RULE_SETUP
#line 343 "ds_lexer.lpp"
return DAS_TYPEINFO;
YY_BREAK
case 99:
YY_RULE_SETUP
#line 344 "ds_lexer.lpp"
return DAS_TYPE;
YY_BREAK
case 100:
YY_RULE_SETUP
#line 345 "ds_lexer.lpp"
return DAS_NEWT;
YY_BREAK
case 101:
YY_RULE_SETUP
#line 346 "ds_lexer.lpp"
return DAS_DELETE;
YY_BREAK
case 102:
YY_RULE_SETUP
#line 347 "ds_lexer.lpp"
return DAS_TRUE;
YY_BREAK
case 103:
YY_RULE_SETUP
#line 348 "ds_lexer.lpp"
return DAS_FALSE;
YY_BREAK
case 104:
YY_RULE_SETUP
#line 349 "ds_lexer.lpp"
return DAS_TAUTO;
YY_BREAK
case 105:
YY_RULE_SETUP
#line 350 "ds_lexer.lpp"
return DAS_TBOOL;
YY_BREAK
case 106:
YY_RULE_SETUP
#line 351 "ds_lexer.lpp"
return DAS_TVOID;
YY_BREAK
case 107:
YY_RULE_SETUP
#line 352 "ds_lexer.lpp"
return DAS_TSTRING;
YY_BREAK
case 108:
YY_RULE_SETUP
#line 353 "ds_lexer.lpp"
return DAS_TRANGE;
YY_BREAK
case 109:
YY_RULE_SETUP
#line 354 "ds_lexer.lpp"
return DAS_TURANGE;
YY_BREAK
case 110:
YY_RULE_SETUP
#line 355 "ds_lexer.lpp"
return DAS_TINT;
YY_BREAK
case 111:
YY_RULE_SETUP
#line 356 "ds_lexer.lpp"
return DAS_TINT8;
YY_BREAK
case 112:
YY_RULE_SETUP
#line 357 "ds_lexer.lpp"
return DAS_TINT16;
YY_BREAK
case 113:
YY_RULE_SETUP
#line 358 "ds_lexer.lpp"
return DAS_TINT64;
YY_BREAK
case 114:
YY_RULE_SETUP
#line 359 "ds_lexer.lpp"
return DAS_TINT2;
YY_BREAK
case 115:
YY_RULE_SETUP
#line 360 "ds_lexer.lpp"
return DAS_TINT3;
YY_BREAK
case 116:
YY_RULE_SETUP
#line 361 "ds_lexer.lpp"
return DAS_TINT4;
YY_BREAK
case 117:
YY_RULE_SETUP
#line 362 "ds_lexer.lpp"
return DAS_TUINT;
YY_BREAK
case 118:
YY_RULE_SETUP
#line 363 "ds_lexer.lpp"
return DAS_TBITFIELD;
YY_BREAK
case 119:
YY_RULE_SETUP
#line 364 "ds_lexer.lpp"
return DAS_TUINT8;
YY_BREAK
case 120:
YY_RULE_SETUP
#line 365 "ds_lexer.lpp"
return DAS_TUINT16;
YY_BREAK
case 121:
YY_RULE_SETUP
#line 366 "ds_lexer.lpp"
return DAS_TUINT64;
YY_BREAK
case 122:
YY_RULE_SETUP
#line 367 "ds_lexer.lpp"
return DAS_TUINT2;
YY_BREAK
case 123:
YY_RULE_SETUP
#line 368 "ds_lexer.lpp"
return DAS_TUINT3;
YY_BREAK
case 124:
YY_RULE_SETUP
#line 369 "ds_lexer.lpp"
return DAS_TUINT4;
YY_BREAK
case 125:
YY_RULE_SETUP
#line 370 "ds_lexer.lpp"
return DAS_TDOUBLE;
YY_BREAK
case 126:
YY_RULE_SETUP
#line 371 "ds_lexer.lpp"
return DAS_TFLOAT;
YY_BREAK
case 127:
YY_RULE_SETUP
#line 372 "ds_lexer.lpp"
return DAS_TFLOAT2;
YY_BREAK
case 128:
YY_RULE_SETUP
#line 373 "ds_lexer.lpp"
return DAS_TFLOAT3;
YY_BREAK
case 129:
YY_RULE_SETUP
#line 374 "ds_lexer.lpp"
return DAS_TFLOAT4;
YY_BREAK
case 130:
YY_RULE_SETUP
#line 375 "ds_lexer.lpp"
yylval_param->s = new string(yytext); return NAME; // TODO: track allocations
YY_BREAK
case 131:
YY_RULE_SETUP
#line 376 "ds_lexer.lpp"
{
BEGIN(strb);
return BEGIN_STRING;
}
YY_BREAK
case 132:
YY_RULE_SETUP
#line 380 "ds_lexer.lpp"
yylval_param->i = 8; return INTEGER;
YY_BREAK
case 133:
YY_RULE_SETUP
#line 381 "ds_lexer.lpp"
yylval_param->i = 9; return INTEGER;
YY_BREAK
case 134:
YY_RULE_SETUP
#line 382 "ds_lexer.lpp"
yylval_param->i = 10; return INTEGER;
YY_BREAK
case 135:
YY_RULE_SETUP
#line 383 "ds_lexer.lpp"
yylval_param->i = 12; return INTEGER;
YY_BREAK
case 136:
YY_RULE_SETUP
#line 384 "ds_lexer.lpp"
yylval_param->i = 13; return INTEGER;
YY_BREAK
case 137:
YY_RULE_SETUP
#line 385 "ds_lexer.lpp"
yylval_param->i = '\\'; return INTEGER;
YY_BREAK
case 138:
YY_RULE_SETUP
#line 386 "ds_lexer.lpp"
yylval_param->i = int32_t(yytext[1]); return INTEGER;
YY_BREAK
case 139:
YY_RULE_SETUP
#line 387 "ds_lexer.lpp"
{
char * endtext = nullptr;
yylval_param->ui64 = strtoull(yytext,&endtext,10);
return ( endtext!=(yytext+strlen(yytext)-2) ) ? LEXER_ERROR : UNSIGNED_LONG_INTEGER;
}
YY_BREAK
case 140:
YY_RULE_SETUP
#line 392 "ds_lexer.lpp"
{
char * endtext = nullptr;
yylval_param->i64 = strtoll(yytext,&endtext,10);
return ( endtext!=(yytext+strlen(yytext)-1) ) ? LEXER_ERROR : LONG_INTEGER;
}
YY_BREAK
case 141:
YY_RULE_SETUP
#line 397 "ds_lexer.lpp"
{
char * endtext = nullptr;
uint64_t uint_const = strtoull(yytext,&endtext,10);
if ( endtext!=(yytext+strlen(yytext)-1) ) {
return LEXER_ERROR;
} else {
if ( uint_const>UINT32_MAX ) {
das_yyfatalerror(yylloc_param,yyscanner,"integer constant out of range", CompilationError::integer_constant_out_of_range);
}
yylval_param->ui = uint32_t(uint_const);
return UNSIGNED_INTEGER;
}
}
YY_BREAK
case 142:
YY_RULE_SETUP
#line 410 "ds_lexer.lpp"
{
char * endtext = nullptr;
int64_t int_const = strtoll(yytext,&endtext,10);
if ( endtext!=(yytext+strlen(yytext)) ) {
return LEXER_ERROR;
} else {
if ( int_const<INT32_MIN || int_const>INT32_MAX ) {
das_yyfatalerror(yylloc_param,yyscanner,"integer constant out of range", CompilationError::integer_constant_out_of_range);
}
yylval_param->i = int32_t(int_const);
return INTEGER;
}
}
YY_BREAK
case 143:
YY_RULE_SETUP
#line 424 "ds_lexer.lpp"
return sscanf(yytext, "%" SCNx64, &yylval_param->ui64)!=1 ? LEXER_ERROR : UNSIGNED_LONG_INTEGER;
YY_BREAK
case 144:
YY_RULE_SETUP
#line 425 "ds_lexer.lpp"
return sscanf(yytext, "%" SCNx64, &yylval_param->ui64)!=1 ? LEXER_ERROR : UNSIGNED_LONG_INTEGER;
YY_BREAK
case 145:
YY_RULE_SETUP
#line 427 "ds_lexer.lpp"
{
uint64_t int_const;
if ( sscanf(yytext, "%" SCNx64, &int_const)!=1 ) {
return LEXER_ERROR;
} else {
if ( int_const>UINT32_MAX ) {
das_yyfatalerror(yylloc_param,yyscanner,"integer constant out of range", CompilationError::integer_constant_out_of_range);
}
yylval_param->ui = uint32_t(int_const);
return UNSIGNED_INTEGER;
}
}
YY_BREAK
case 146:
YY_RULE_SETUP
#line 440 "ds_lexer.lpp"
{
uint64_t int_const;
if ( sscanf(yytext, "%" SCNx64, &int_const)!=1 ) {
return LEXER_ERROR;
} else {
if ( int_const>UINT32_MAX ) {
das_yyfatalerror(yylloc_param,yyscanner,"integer constant out of range", CompilationError::integer_constant_out_of_range);
}
yylval_param->ui = uint32_t(int_const);
return UNSIGNED_INTEGER;
}
}
YY_BREAK
case 147:
YY_RULE_SETUP
#line 453 "ds_lexer.lpp"
return sscanf(yytext, "%lf", &yylval_param->fd)!=1 ? LEXER_ERROR : FLOAT;
YY_BREAK
case 148:
YY_RULE_SETUP
#line 454 "ds_lexer.lpp"
return sscanf(yytext, "%lf", &yylval_param->fd)!=1 ? LEXER_ERROR : FLOAT;
YY_BREAK
case 149:
YY_RULE_SETUP
#line 455 "ds_lexer.lpp"
return sscanf(yytext, "%lf", &yylval_param->fd)!=1 ? LEXER_ERROR : FLOAT;
YY_BREAK
case 150:
YY_RULE_SETUP
#line 456 "ds_lexer.lpp"
return sscanf(yytext, "%lf", &yylval_param->fd)!=1 ? LEXER_ERROR : FLOAT;
YY_BREAK
case 151:
YY_RULE_SETUP
#line 458 "ds_lexer.lpp"
return sscanf(yytext, "%lf", &yylval_param->d)!=1 ? LEXER_ERROR : DOUBLE;
YY_BREAK
case 152:
YY_RULE_SETUP
#line 459 "ds_lexer.lpp"
return sscanf(yytext, "%lf", &yylval_param->d)!=1 ? LEXER_ERROR : DOUBLE;
YY_BREAK
case 153:
YY_RULE_SETUP
#line 460 "ds_lexer.lpp"
return sscanf(yytext, "%lf", &yylval_param->d)!=1 ? LEXER_ERROR : DOUBLE;
YY_BREAK
case 154:
YY_RULE_SETUP
#line 461 "ds_lexer.lpp"
return sscanf(yytext, "%lf", &yylval_param->d)!=1 ? LEXER_ERROR : DOUBLE;
YY_BREAK
case 155:
YY_RULE_SETUP
#line 462 "ds_lexer.lpp"
{
if ( !yyextra->das_nested_parentheses ) {
das_yyfatalerror(yylloc_param,yyscanner,"mismatching parentheses", CompilationError::mismatching_parentheses);
return LEXER_ERROR;
}
yyextra->das_nested_parentheses --;
return ')';
}
YY_BREAK
case 156:
YY_RULE_SETUP
#line 470 "ds_lexer.lpp"
{
yyextra->das_nested_parentheses ++;
return '(';
}
YY_BREAK
case 157:
YY_RULE_SETUP
#line 474 "ds_lexer.lpp"
{
if ( !yyextra->das_nested_square_braces ) {
das_yyfatalerror(yylloc_param,yyscanner,"mismatching square braces", CompilationError::mismatching_parentheses);
return LEXER_ERROR;
}
yyextra->das_nested_square_braces --;
return ']';
}
YY_BREAK
case 158:
YY_RULE_SETUP
#line 482 "ds_lexer.lpp"
{
yyextra->das_nested_square_braces ++;
return '[';
}
YY_BREAK
case 159:
YY_RULE_SETUP
#line 486 "ds_lexer.lpp"
{
if ( yyextra->das_nested_sb ) {
yyextra->das_nested_sb --;
if ( !yyextra->das_nested_sb ) {
BEGIN(strb);
return END_STRING_EXPR;
} else {
return '}';
}
} else {
if ( !yyextra->das_nested_curly_braces ) {
das_yyfatalerror(yylloc_param,yyscanner,"mismatching curly braces", CompilationError::mismatching_curly_bracers);
return LEXER_ERROR;
}
yyextra->das_nested_curly_braces --;
return '}';
}
}
YY_BREAK
case 160:
YY_RULE_SETUP
#line 504 "ds_lexer.lpp"
{
if ( yyextra->das_nested_sb ) {
yyextra->das_nested_sb ++;
} else {
yyextra->das_nested_curly_braces ++;
}
return '{';
}
YY_BREAK
case 161:
YY_RULE_SETUP
#line 512 "ds_lexer.lpp"
return COLCOL;
YY_BREAK
case 162:
YY_RULE_SETUP
#line 513 "ds_lexer.lpp"
return RPIPE;
YY_BREAK
case 163:
/* rule 163 can match eol */
YY_RULE_SETUP
#line 514 "ds_lexer.lpp"
yyextra->das_need_oxford_comma = false; unput('\n'); return LBPIPE;
YY_BREAK
case 164:
/* rule 164 can match eol */
YY_RULE_SETUP
#line 515 "ds_lexer.lpp"
yyextra->das_need_oxford_comma = false; unput('\n'); return LBPIPE;
YY_BREAK
case 165:
YY_RULE_SETUP
#line 516 "ds_lexer.lpp"
{
unput('$');
YYCOLUMN(yyextra->das_yycolumn--, "UNPUT $");
if ( yyextra->das_nested_parentheses ) {
return LPIPE;
} else {
yyextra->das_need_oxford_comma = false;
return LBPIPE;
}
}
YY_BREAK
case 166:
YY_RULE_SETUP
#line 526 "ds_lexer.lpp"
{
unput('@');
YYCOLUMN(yyextra->das_yycolumn--, "UNPUT @");
if ( yyextra->das_nested_parentheses ) {
return LPIPE;
} else {
yyextra->das_need_oxford_comma = false;
return LBPIPE;
}
}
YY_BREAK
case 167:
YY_RULE_SETUP
#line 536 "ds_lexer.lpp"
{
unput('@');
unput('@');
YYCOLUMN(yyextra->das_yycolumn-=2, "UNPUT @@");
if ( yyextra->das_nested_parentheses ) {
return LFPIPE;
} else {
yyextra->das_need_oxford_comma = false;
return LFPIPE;
}
}
YY_BREAK
case 168:
YY_RULE_SETUP
#line 547 "ds_lexer.lpp"
{
unput('@');
YYCOLUMN(yyextra->das_yycolumn--, "UNPUT @");
if ( yyextra->das_nested_parentheses ) {
return LAPIPE;
} else {
yyextra->das_need_oxford_comma = false;
return LAPIPE;
}
}
YY_BREAK
case 169:
YY_RULE_SETUP
#line 557 "ds_lexer.lpp"
return LPIPE;
YY_BREAK
case 170:
YY_RULE_SETUP
#line 558 "ds_lexer.lpp"
return QQ;
YY_BREAK
case 171:
YY_RULE_SETUP
#line 559 "ds_lexer.lpp"
{
yyextra->das_nested_square_braces ++;
return QBRA;
}
YY_BREAK
case 172:
YY_RULE_SETUP
#line 563 "ds_lexer.lpp"
return QDOT;
YY_BREAK
case 173:
YY_RULE_SETUP
#line 564 "ds_lexer.lpp"
return CLONEEQU;
YY_BREAK
case 174:
YY_RULE_SETUP
#line 565 "ds_lexer.lpp"
return RARROW;
YY_BREAK
case 175:
YY_RULE_SETUP
#line 566 "ds_lexer.lpp"
return LARROW;
YY_BREAK
case 176:
YY_RULE_SETUP
#line 567 "ds_lexer.lpp"
return ADDEQU;
YY_BREAK
case 177:
YY_RULE_SETUP
#line 568 "ds_lexer.lpp"
return SUBEQU;
YY_BREAK
case 178:
YY_RULE_SETUP
#line 569 "ds_lexer.lpp"
return DIVEQU;
YY_BREAK
case 179:
YY_RULE_SETUP
#line 570 "ds_lexer.lpp"
return MULEQU;
YY_BREAK
case 180:
YY_RULE_SETUP
#line 571 "ds_lexer.lpp"
return MODEQU;
YY_BREAK
case 181:
YY_RULE_SETUP
#line 572 "ds_lexer.lpp"
return ANDANDEQU;
YY_BREAK
case 182:
YY_RULE_SETUP
#line 573 "ds_lexer.lpp"
return OROREQU;
YY_BREAK
case 183:
YY_RULE_SETUP
#line 574 "ds_lexer.lpp"
return XORXOREQU;
YY_BREAK
case 184:
YY_RULE_SETUP
#line 575 "ds_lexer.lpp"
return ANDAND;
YY_BREAK
case 185:
YY_RULE_SETUP
#line 576 "ds_lexer.lpp"
return OROR;
YY_BREAK
case 186:
YY_RULE_SETUP
#line 577 "ds_lexer.lpp"
return XORXOR;
YY_BREAK
case 187:
YY_RULE_SETUP
#line 578 "ds_lexer.lpp"
return ANDEQU;
YY_BREAK
case 188:
YY_RULE_SETUP
#line 579 "ds_lexer.lpp"
return OREQU;
YY_BREAK
case 189:
YY_RULE_SETUP
#line 580 "ds_lexer.lpp"
return XOREQU;
YY_BREAK
case 190:
YY_RULE_SETUP
#line 581 "ds_lexer.lpp"
return ADDADD;
YY_BREAK
case 191:
YY_RULE_SETUP
#line 582 "ds_lexer.lpp"
return SUBSUB;
YY_BREAK
case 192:
YY_RULE_SETUP
#line 583 "ds_lexer.lpp"
return LEEQU;
YY_BREAK
case 193:
YY_RULE_SETUP
#line 584 "ds_lexer.lpp"
return GREQU;
YY_BREAK
case 194:
YY_RULE_SETUP
#line 585 "ds_lexer.lpp"
return EQUEQU;
YY_BREAK
case 195:
YY_RULE_SETUP
#line 586 "ds_lexer.lpp"
return NOTEQU;
YY_BREAK
case 196:
YY_RULE_SETUP
#line 587 "ds_lexer.lpp"
{
if ( yyextra->das_arrow_depth ) {
unput('>');
unput('>');
YYCOLUMN(yyextra->das_yycolumn-=2, "UNPUT");
return '>';
} else {
return ROTR;
}
}
YY_BREAK
case 197:
YY_RULE_SETUP
#line 597 "ds_lexer.lpp"
{
if ( yyextra->das_arrow_depth ) {
unput('>');
YYCOLUMN(yyextra->das_yycolumn--, "UNPUT");
return '>';
} else {
return SHR;
}
}
YY_BREAK
case 198:
YY_RULE_SETUP
#line 606 "ds_lexer.lpp"
return ROTL;
YY_BREAK
case 199:
YY_RULE_SETUP
#line 607 "ds_lexer.lpp"
return SHL;
YY_BREAK
case 200:
YY_RULE_SETUP
#line 608 "ds_lexer.lpp"
return SHREQU;
YY_BREAK
case 201:
YY_RULE_SETUP
#line 609 "ds_lexer.lpp"
return SHLEQU;
YY_BREAK
case 202:
YY_RULE_SETUP
#line 610 "ds_lexer.lpp"
return ROTREQU;
YY_BREAK
case 203:
YY_RULE_SETUP
#line 611 "ds_lexer.lpp"
return ROTLEQU;
YY_BREAK
case 204:
YY_RULE_SETUP
#line 612 "ds_lexer.lpp"
return MAPTO;
YY_BREAK
case 205:
YY_RULE_SETUP
#line 613 "ds_lexer.lpp"
{
yyextra->das_nested_square_braces ++;
yyextra->das_nested_square_braces ++;
return BRABRAB;
}
YY_BREAK
case 206:
YY_RULE_SETUP
#line 618 "ds_lexer.lpp"
{
yyextra->das_nested_square_braces ++;
yyextra->das_nested_curly_braces ++;
return BRACBRB;
}
YY_BREAK
case 207:
YY_RULE_SETUP
#line 623 "ds_lexer.lpp"
{
yyextra->das_nested_curly_braces ++;
yyextra->das_nested_curly_braces ++;
return CBRCBRB;
}
YY_BREAK
case 208:
YY_RULE_SETUP
#line 628 "ds_lexer.lpp"
/* skip white space */
YY_BREAK
case 209:
YY_RULE_SETUP
#line 629 "ds_lexer.lpp"
{
YYTAB();
}
YY_BREAK
case 210:
/* rule 210 can match eol */
YY_RULE_SETUP
#line 632 "ds_lexer.lpp"
{
YYCOLUMN(yyextra->das_yycolumn = 0, "NEW LINE");
if ( !yyextra->das_nested_parentheses && !yyextra->das_nested_curly_braces && !yyextra->das_nested_square_braces ) {
bool ns = ((yyextra->das_current_line_indent!=0) && yyextra->das_need_oxford_comma) || yyextra->das_force_oxford_comma;
#ifdef FLEX_DEBUG
if ( yyextra->das_force_oxford_comma ) printf ( "forcing oxford comma\n");
#endif
yyextra->das_force_oxford_comma = false;
yyextra->das_current_line_indent = 0;
yyextra->das_need_oxford_comma = true;
BEGIN(indent);
if ( ns ) {
#ifdef FLEX_DEBUG
printf("emit ; at EOL\n");
#endif
return ';';
}
}
}
YY_BREAK
case YY_STATE_EOF(normal):
#line 651 "ds_lexer.lpp"
{
if ( yyextra->g_FileAccessStack.size()==1 ) {
YYCOLUMN(yyextra->das_yycolumn = 0,"EOF");
if ( !yyextra->das_nested_parentheses && !yyextra->das_nested_curly_braces && !yyextra->das_nested_square_braces ) {
bool ns = (yyextra->das_current_line_indent!=0) && yyextra->das_need_oxford_comma;
yyextra->das_current_line_indent = 0;
yyextra->das_need_oxford_comma = true;
BEGIN(indent);
if ( ns ) {
#ifdef FLEX_DEBUG
printf("emit ; at EOF\n");
#endif
return ';';
}
} else {
return 0;
}
} else {
yypop_buffer_state(yyscanner);
yyextra->g_FileAccessStack.pop_back();
yylineno = yyextra->das_line_no.back();
yyextra->das_line_no.pop_back();
}
}
YY_BREAK
case 211:
YY_RULE_SETUP
#line 675 "ds_lexer.lpp"
return *yytext;
YY_BREAK
case 212:
YY_RULE_SETUP
#line 677 "ds_lexer.lpp"
ECHO;
YY_BREAK
#line 2992 "ds_lexer.cpp"
case YY_STATE_EOF(INITIAL):
case YY_STATE_EOF(include):
yyterminate();
case YY_END_OF_BUFFER:
{
/* Amount of text matched not including the EOB char. */
int yy_amount_of_matched_text = (int) (yy_cp - yyg->yytext_ptr) - 1;
/* Undo the effects of YY_DO_BEFORE_ACTION. */
*yy_cp = yyg->yy_hold_char;
YY_RESTORE_YY_MORE_OFFSET
if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW )
{
/* We're scanning a new file or input source. It's
* possible that this happened because the user
* just pointed yyin at a new source and called
* yylex(). If so, then we have to assure
* consistency between YY_CURRENT_BUFFER and our
* globals. Here is the right place to do so, because
* this is the first action (other than possibly a
* back-up) that will match for the new input source.
*/
yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin;
YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL;
}
/* Note that here we test for yy_c_buf_p "<=" to the position
* of the first EOB in the buffer, since yy_c_buf_p will
* already have been incremented past the NUL character
* (since all states make transitions on EOB to the
* end-of-buffer state). Contrast this with the test
* in input().
*/
if ( yyg->yy_c_buf_p <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] )
{ /* This was really a NUL. */
yy_state_type yy_next_state;
yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text;
yy_current_state = yy_get_previous_state( yyscanner );
/* Okay, we're now positioned to make the NUL
* transition. We couldn't have
* yy_get_previous_state() go ahead and do it
* for us because it doesn't know how to deal
* with the possibility of jamming (and we don't
* want to build jamming into it because then it
* will run more slowly).
*/
yy_next_state = yy_try_NUL_trans( yy_current_state , yyscanner);
yy_bp = yyg->yytext_ptr + YY_MORE_ADJ;
if ( yy_next_state )
{
/* Consume the NUL. */
yy_cp = ++yyg->yy_c_buf_p;
yy_current_state = yy_next_state;
goto yy_match;
}
else
{
yy_cp = yyg->yy_last_accepting_cpos;
yy_current_state = yyg->yy_last_accepting_state;
goto yy_find_action;
}
}
else switch ( yy_get_next_buffer( yyscanner ) )
{
case EOB_ACT_END_OF_FILE:
{
yyg->yy_did_buffer_switch_on_eof = 0;
if ( yywrap( yyscanner ) )
{
/* Note: because we've taken care in
* yy_get_next_buffer() to have set up
* yytext, we can now set up
* yy_c_buf_p so that if some total
* hoser (like flex itself) wants to
* call the scanner after we return the
* YY_NULL, it'll still work - another
* YY_NULL will get returned.
*/
yyg->yy_c_buf_p = yyg->yytext_ptr + YY_MORE_ADJ;
yy_act = YY_STATE_EOF(YY_START);
goto do_action;
}
else
{
if ( ! yyg->yy_did_buffer_switch_on_eof )
YY_NEW_FILE;
}
break;
}
case EOB_ACT_CONTINUE_SCAN:
yyg->yy_c_buf_p =
yyg->yytext_ptr + yy_amount_of_matched_text;
yy_current_state = yy_get_previous_state( yyscanner );
yy_cp = yyg->yy_c_buf_p;
yy_bp = yyg->yytext_ptr + YY_MORE_ADJ;
goto yy_match;
case EOB_ACT_LAST_MATCH:
yyg->yy_c_buf_p =
&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars];
yy_current_state = yy_get_previous_state( yyscanner );
yy_cp = yyg->yy_c_buf_p;
yy_bp = yyg->yytext_ptr + YY_MORE_ADJ;
goto yy_find_action;
}
break;
}
default:
YY_FATAL_ERROR(
"fatal flex scanner internal error--no action found" );
} /* end of action switch */
} /* end of scanning one token */
} /* end of user's declarations */
} /* end of yylex */
/* yy_get_next_buffer - try to read in a new buffer
*
* Returns a code representing an action:
* EOB_ACT_LAST_MATCH -
* EOB_ACT_CONTINUE_SCAN - continue scanning from current position
* EOB_ACT_END_OF_FILE - end of file
*/
static int yy_get_next_buffer (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf;
char *source = yyg->yytext_ptr;
int number_to_move, i;
int ret_val;
if ( yyg->yy_c_buf_p > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] )
YY_FATAL_ERROR(
"fatal flex scanner internal error--end of buffer missed" );
if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 )
{ /* Don't try to fill the buffer, so this is an EOF. */
if ( yyg->yy_c_buf_p - yyg->yytext_ptr - YY_MORE_ADJ == 1 )
{
/* We matched a single character, the EOB, so
* treat this as a final EOF.
*/
return EOB_ACT_END_OF_FILE;
}
else
{
/* We matched some text prior to the EOB, first
* process it.
*/
return EOB_ACT_LAST_MATCH;
}
}
/* Try to read more data. */
/* First move last chars to start of buffer. */
number_to_move = (int) (yyg->yy_c_buf_p - yyg->yytext_ptr - 1);
for ( i = 0; i < number_to_move; ++i )
*(dest++) = *(source++);
if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING )
/* don't do the read, it's not guaranteed to return an EOF,
* just force an EOF
*/
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars = 0;
else
{
int num_to_read =
YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1;
while ( num_to_read <= 0 )
{ /* Not enough room in the buffer - grow it. */
/* just a shorter name for the current buffer */
YY_BUFFER_STATE b = YY_CURRENT_BUFFER_LVALUE;
int yy_c_buf_p_offset =
(int) (yyg->yy_c_buf_p - b->yy_ch_buf);
if ( b->yy_is_our_buffer )
{
int new_size = b->yy_buf_size * 2;
if ( new_size <= 0 )
b->yy_buf_size += b->yy_buf_size / 8;
else
b->yy_buf_size *= 2;
b->yy_ch_buf = (char *)
/* Include room in for 2 EOB chars. */
yyrealloc( (void *) b->yy_ch_buf,
(yy_size_t) (b->yy_buf_size + 2) , yyscanner );
}
else
/* Can't grow it, we don't own it. */
b->yy_ch_buf = NULL;
if ( ! b->yy_ch_buf )
YY_FATAL_ERROR(
"fatal error - scanner input buffer overflow" );
yyg->yy_c_buf_p = &b->yy_ch_buf[yy_c_buf_p_offset];
num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size -
number_to_move - 1;
}
if ( num_to_read > YY_READ_BUF_SIZE )
num_to_read = YY_READ_BUF_SIZE;
/* Read in more data. */
YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]),
yyg->yy_n_chars, num_to_read );
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars;
}
if ( yyg->yy_n_chars == 0 )
{
if ( number_to_move == YY_MORE_ADJ )
{
ret_val = EOB_ACT_END_OF_FILE;
yyrestart( yyin , yyscanner);
}
else
{
ret_val = EOB_ACT_LAST_MATCH;
YY_CURRENT_BUFFER_LVALUE->yy_buffer_status =
YY_BUFFER_EOF_PENDING;
}
}
else
ret_val = EOB_ACT_CONTINUE_SCAN;
if ((yyg->yy_n_chars + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) {
/* Extend the array by 50%, plus the number we really need. */
int new_size = yyg->yy_n_chars + number_to_move + (yyg->yy_n_chars >> 1);
YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) yyrealloc(
(void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf, (yy_size_t) new_size , yyscanner );
if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf )
YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" );
/* "- 2" to take care of EOB's */
YY_CURRENT_BUFFER_LVALUE->yy_buf_size = (int) (new_size - 2);
}
yyg->yy_n_chars += number_to_move;
YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] = YY_END_OF_BUFFER_CHAR;
YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] = YY_END_OF_BUFFER_CHAR;
yyg->yytext_ptr = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0];
return ret_val;
}
/* yy_get_previous_state - get the state just before the EOB char was reached */
static yy_state_type yy_get_previous_state (yyscan_t yyscanner)
{
yy_state_type yy_current_state;
char *yy_cp;
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yy_current_state = yyg->yy_start;
for ( yy_cp = yyg->yytext_ptr + YY_MORE_ADJ; yy_cp < yyg->yy_c_buf_p; ++yy_cp )
{
YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1);
if ( yy_accept[yy_current_state] )
{
yyg->yy_last_accepting_state = yy_current_state;
yyg->yy_last_accepting_cpos = yy_cp;
}
while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 600 )
yy_c = yy_meta[yy_c];
}
yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c];
}
return yy_current_state;
}
/* yy_try_NUL_trans - try to make a transition on the NUL character
*
* synopsis
* next_state = yy_try_NUL_trans( current_state );
*/
static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state , yyscan_t yyscanner)
{
int yy_is_jam;
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* This var may be unused depending upon options. */
char *yy_cp = yyg->yy_c_buf_p;
YY_CHAR yy_c = 1;
if ( yy_accept[yy_current_state] )
{
yyg->yy_last_accepting_state = yy_current_state;
yyg->yy_last_accepting_cpos = yy_cp;
}
while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 600 )
yy_c = yy_meta[yy_c];
}
yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c];
yy_is_jam = (yy_current_state == 599);
(void)yyg;
return yy_is_jam ? 0 : yy_current_state;
}
#ifndef YY_NO_UNPUT
static void yyunput (int c, char * yy_bp , yyscan_t yyscanner)
{
char *yy_cp;
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yy_cp = yyg->yy_c_buf_p;
/* undo effects of setting up yytext */
*yy_cp = yyg->yy_hold_char;
if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 )
{ /* need to shift things up to make room */
/* +2 for EOB chars. */
int number_to_move = yyg->yy_n_chars + 2;
char *dest = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[
YY_CURRENT_BUFFER_LVALUE->yy_buf_size + 2];
char *source =
&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move];
while ( source > YY_CURRENT_BUFFER_LVALUE->yy_ch_buf )
*--dest = *--source;
yy_cp += (int) (dest - source);
yy_bp += (int) (dest - source);
YY_CURRENT_BUFFER_LVALUE->yy_n_chars =
yyg->yy_n_chars = (int) YY_CURRENT_BUFFER_LVALUE->yy_buf_size;
if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 )
YY_FATAL_ERROR( "flex scanner push-back overflow" );
}
*--yy_cp = (char) c;
if ( c == '\n' ){
--yylineno;
}
yyg->yytext_ptr = yy_bp;
yyg->yy_hold_char = *yy_cp;
yyg->yy_c_buf_p = yy_cp;
}
#endif
#ifndef YY_NO_INPUT
#ifdef __cplusplus
static int yyinput (yyscan_t yyscanner)
#else
static int input (yyscan_t yyscanner)
#endif
{
int c;
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
*yyg->yy_c_buf_p = yyg->yy_hold_char;
if ( *yyg->yy_c_buf_p == YY_END_OF_BUFFER_CHAR )
{
/* yy_c_buf_p now points to the character we want to return.
* If this occurs *before* the EOB characters, then it's a
* valid NUL; if not, then we've hit the end of the buffer.
*/
if ( yyg->yy_c_buf_p < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] )
/* This was really a NUL. */
*yyg->yy_c_buf_p = '\0';
else
{ /* need more input */
int offset = (int) (yyg->yy_c_buf_p - yyg->yytext_ptr);
++yyg->yy_c_buf_p;
switch ( yy_get_next_buffer( yyscanner ) )
{
case EOB_ACT_LAST_MATCH:
/* This happens because yy_g_n_b()
* sees that we've accumulated a
* token and flags that we need to
* try matching the token before
* proceeding. But for input(),
* there's no matching to consider.
* So convert the EOB_ACT_LAST_MATCH
* to EOB_ACT_END_OF_FILE.
*/
/* Reset buffer status. */
yyrestart( yyin , yyscanner);
/*FALLTHROUGH*/
case EOB_ACT_END_OF_FILE:
{
if ( yywrap( yyscanner ) )
return 0;
if ( ! yyg->yy_did_buffer_switch_on_eof )
YY_NEW_FILE;
#ifdef __cplusplus
return yyinput(yyscanner);
#else
return input(yyscanner);
#endif
}
case EOB_ACT_CONTINUE_SCAN:
yyg->yy_c_buf_p = yyg->yytext_ptr + offset;
break;
}
}
}
c = *(unsigned char *) yyg->yy_c_buf_p; /* cast for 8-bit char's */
*yyg->yy_c_buf_p = '\0'; /* preserve yytext */
yyg->yy_hold_char = *++yyg->yy_c_buf_p;
if ( c == '\n' )
do{ yylineno++;
yycolumn=0;
}while(0)
;
return c;
}
#endif /* ifndef YY_NO_INPUT */
/** Immediately switch to a different input stream.
* @param input_file A readable stream.
* @param yyscanner The scanner object.
* @note This function does not reset the start condition to @c INITIAL .
*/
void yyrestart (FILE * input_file , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if ( ! YY_CURRENT_BUFFER ){
yyensure_buffer_stack (yyscanner);
YY_CURRENT_BUFFER_LVALUE =
yy_create_buffer( yyin, YY_BUF_SIZE , yyscanner);
}
yy_init_buffer( YY_CURRENT_BUFFER, input_file , yyscanner);
yy_load_buffer_state( yyscanner );
}
/** Switch to a different input buffer.
* @param new_buffer The new input buffer.
* @param yyscanner The scanner object.
*/
void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
/* TODO. We should be able to replace this entire function body
* with
* yypop_buffer_state();
* yypush_buffer_state(new_buffer);
*/
yyensure_buffer_stack (yyscanner);
if ( YY_CURRENT_BUFFER == new_buffer )
return;
if ( YY_CURRENT_BUFFER )
{
/* Flush out information for old buffer. */
*yyg->yy_c_buf_p = yyg->yy_hold_char;
YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p;
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars;
}
YY_CURRENT_BUFFER_LVALUE = new_buffer;
yy_load_buffer_state( yyscanner );
/* We don't actually know whether we did this switch during
* EOF (yywrap()) processing, but the only time this flag
* is looked at is after yywrap() is called, so it's safe
* to go ahead and always set it.
*/
yyg->yy_did_buffer_switch_on_eof = 1;
}
static void yy_load_buffer_state (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
yyg->yytext_ptr = yyg->yy_c_buf_p = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos;
yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file;
yyg->yy_hold_char = *yyg->yy_c_buf_p;
}
/** Allocate and initialize an input buffer state.
* @param file A readable stream.
* @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE.
* @param yyscanner The scanner object.
* @return the allocated buffer state.
*/
YY_BUFFER_STATE yy_create_buffer (FILE * file, int size , yyscan_t yyscanner)
{
YY_BUFFER_STATE b;
b = (YY_BUFFER_STATE) yyalloc( sizeof( struct yy_buffer_state ) , yyscanner );
if ( ! b )
YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" );
b->yy_buf_size = size;
/* yy_ch_buf has to be 2 characters longer than the size given because
* we need to put in 2 end-of-buffer characters.
*/
b->yy_ch_buf = (char *) yyalloc( (yy_size_t) (b->yy_buf_size + 2) , yyscanner );
if ( ! b->yy_ch_buf )
YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" );
b->yy_is_our_buffer = 1;
yy_init_buffer( b, file , yyscanner);
return b;
}
/** Destroy the buffer.
* @param b a buffer created with yy_create_buffer()
* @param yyscanner The scanner object.
*/
void yy_delete_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if ( ! b )
return;
if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */
YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0;
if ( b->yy_is_our_buffer )
yyfree( (void *) b->yy_ch_buf , yyscanner );
yyfree( (void *) b , yyscanner );
}
/* Initializes or reinitializes a buffer.
* This function is sometimes called more than once on the same buffer,
* such as during a yyrestart() or at EOF.
*/
static void yy_init_buffer (YY_BUFFER_STATE b, FILE * file , yyscan_t yyscanner)
{
int oerrno = errno;
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yy_flush_buffer( b , yyscanner);
b->yy_input_file = file;
b->yy_fill_buffer = 1;
/* If b is the current buffer, then yy_init_buffer was _probably_
* called from yyrestart() or through yy_get_next_buffer.
* In that case, we don't want to reset the lineno or column.
*/
if (b != YY_CURRENT_BUFFER){
b->yy_bs_lineno = 1;
b->yy_bs_column = 0;
}
b->yy_is_interactive = 0;
errno = oerrno;
}
/** Discard all buffered characters. On the next scan, YY_INPUT will be called.
* @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER.
* @param yyscanner The scanner object.
*/
void yy_flush_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if ( ! b )
return;
b->yy_n_chars = 0;
/* We always need two end-of-buffer characters. The first causes
* a transition to the end-of-buffer state. The second causes
* a jam in that state.
*/
b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR;
b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR;
b->yy_buf_pos = &b->yy_ch_buf[0];
b->yy_at_bol = 1;
b->yy_buffer_status = YY_BUFFER_NEW;
if ( b == YY_CURRENT_BUFFER )
yy_load_buffer_state( yyscanner );
}
/** Pushes the new state onto the stack. The new state becomes
* the current state. This function will allocate the stack
* if necessary.
* @param new_buffer The new state.
* @param yyscanner The scanner object.
*/
void yypush_buffer_state (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if (new_buffer == NULL)
return;
yyensure_buffer_stack(yyscanner);
/* This block is copied from yy_switch_to_buffer. */
if ( YY_CURRENT_BUFFER )
{
/* Flush out information for old buffer. */
*yyg->yy_c_buf_p = yyg->yy_hold_char;
YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p;
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars;
}
/* Only push if top exists. Otherwise, replace top. */
if (YY_CURRENT_BUFFER)
yyg->yy_buffer_stack_top++;
YY_CURRENT_BUFFER_LVALUE = new_buffer;
/* copied from yy_switch_to_buffer. */
yy_load_buffer_state( yyscanner );
yyg->yy_did_buffer_switch_on_eof = 1;
}
/** Removes and deletes the top of the stack, if present.
* The next element becomes the new top.
* @param yyscanner The scanner object.
*/
void yypop_buffer_state (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if (!YY_CURRENT_BUFFER)
return;
yy_delete_buffer(YY_CURRENT_BUFFER , yyscanner);
YY_CURRENT_BUFFER_LVALUE = NULL;
if (yyg->yy_buffer_stack_top > 0)
--yyg->yy_buffer_stack_top;
if (YY_CURRENT_BUFFER) {
yy_load_buffer_state( yyscanner );
yyg->yy_did_buffer_switch_on_eof = 1;
}
}
/* Allocates the stack if it does not exist.
* Guarantees space for at least one push.
*/
static void yyensure_buffer_stack (yyscan_t yyscanner)
{
yy_size_t num_to_alloc;
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if (!yyg->yy_buffer_stack) {
/* First allocation is just for 2 elements, since we don't know if this
* scanner will even need a stack. We use 2 instead of 1 to avoid an
* immediate realloc on the next call.
*/
num_to_alloc = 1; /* After all that talk, this was set to 1 anyways... */
yyg->yy_buffer_stack = (struct yy_buffer_state**)yyalloc
(num_to_alloc * sizeof(struct yy_buffer_state*)
, yyscanner);
if ( ! yyg->yy_buffer_stack )
YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" );
memset(yyg->yy_buffer_stack, 0, num_to_alloc * sizeof(struct yy_buffer_state*));
yyg->yy_buffer_stack_max = num_to_alloc;
yyg->yy_buffer_stack_top = 0;
return;
}
if (yyg->yy_buffer_stack_top >= (yyg->yy_buffer_stack_max) - 1){
/* Increase the buffer to prepare for a possible push. */
yy_size_t grow_size = 8 /* arbitrary grow size */;
num_to_alloc = yyg->yy_buffer_stack_max + grow_size;
yyg->yy_buffer_stack = (struct yy_buffer_state**)yyrealloc
(yyg->yy_buffer_stack,
num_to_alloc * sizeof(struct yy_buffer_state*)
, yyscanner);
if ( ! yyg->yy_buffer_stack )
YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" );
/* zero only the new slots.*/
memset(yyg->yy_buffer_stack + yyg->yy_buffer_stack_max, 0, grow_size * sizeof(struct yy_buffer_state*));
yyg->yy_buffer_stack_max = num_to_alloc;
}
}
/** Setup the input buffer state to scan directly from a user-specified character buffer.
* @param base the character buffer
* @param size the size in bytes of the character buffer
* @param yyscanner The scanner object.
* @return the newly allocated buffer state object.
*/
YY_BUFFER_STATE yy_scan_buffer (char * base, yy_size_t size , yyscan_t yyscanner)
{
YY_BUFFER_STATE b;
if ( size < 2 ||
base[size-2] != YY_END_OF_BUFFER_CHAR ||
base[size-1] != YY_END_OF_BUFFER_CHAR )
/* They forgot to leave room for the EOB's. */
return NULL;
b = (YY_BUFFER_STATE) yyalloc( sizeof( struct yy_buffer_state ) , yyscanner );
if ( ! b )
YY_FATAL_ERROR( "out of dynamic memory in yy_scan_buffer()" );
b->yy_buf_size = (int) (size - 2); /* "- 2" to take care of EOB's */
b->yy_buf_pos = b->yy_ch_buf = base;
b->yy_is_our_buffer = 0;
b->yy_input_file = NULL;
b->yy_n_chars = b->yy_buf_size;
b->yy_is_interactive = 0;
b->yy_at_bol = 1;
b->yy_fill_buffer = 0;
b->yy_buffer_status = YY_BUFFER_NEW;
yy_switch_to_buffer( b , yyscanner );
return b;
}
/** Setup the input buffer state to scan a string. The next call to yylex() will
* scan from a @e copy of @a str.
* @param yystr a NUL-terminated string to scan
* @param yyscanner The scanner object.
* @return the newly allocated buffer state object.
* @note If you want to scan bytes that may contain NUL values, then use
* yy_scan_bytes() instead.
*/
YY_BUFFER_STATE yy_scan_string (const char * yystr , yyscan_t yyscanner)
{
return yy_scan_bytes( yystr, (int) strlen(yystr) , yyscanner);
}
/** Setup the input buffer state to scan the given bytes. The next call to yylex() will
* scan from a @e copy of @a bytes.
* @param yybytes the byte buffer to scan
* @param _yybytes_len the number of bytes in the buffer pointed to by @a bytes.
* @param yyscanner The scanner object.
* @return the newly allocated buffer state object.
*/
YY_BUFFER_STATE yy_scan_bytes (const char * yybytes, int _yybytes_len , yyscan_t yyscanner)
{
YY_BUFFER_STATE b;
char *buf;
yy_size_t n;
int i;
/* Get memory for full buffer, including space for trailing EOB's. */
n = (yy_size_t) (_yybytes_len + 2);
buf = (char *) yyalloc( n , yyscanner );
if ( ! buf )
YY_FATAL_ERROR( "out of dynamic memory in yy_scan_bytes()" );
for ( i = 0; i < _yybytes_len; ++i )
buf[i] = yybytes[i];
buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR;
b = yy_scan_buffer( buf, n , yyscanner);
if ( ! b )
YY_FATAL_ERROR( "bad buffer in yy_scan_bytes()" );
/* It's okay to grow etc. this buffer, and we should throw it
* away when we're done.
*/
b->yy_is_our_buffer = 1;
return b;
}
#ifndef YY_EXIT_FAILURE
#define YY_EXIT_FAILURE 2
#endif
static void yynoreturn yy_fatal_error (const char* msg , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
(void)yyg;
fprintf( stderr, "%s\n", msg );
exit( YY_EXIT_FAILURE );
}
/* Redefine yyless() so it works in section 3 code. */
#undef yyless
#define yyless(n) \
do \
{ \
/* Undo effects of setting up yytext. */ \
int yyless_macro_arg = (n); \
YY_LESS_LINENO(yyless_macro_arg);\
yytext[yyleng] = yyg->yy_hold_char; \
yyg->yy_c_buf_p = yytext + yyless_macro_arg; \
yyg->yy_hold_char = *yyg->yy_c_buf_p; \
*yyg->yy_c_buf_p = '\0'; \
yyleng = yyless_macro_arg; \
} \
while ( 0 )
/* Accessor methods (get/set functions) to struct members. */
/** Get the user-defined data for this scanner.
* @param yyscanner The scanner object.
*/
YY_EXTRA_TYPE yyget_extra (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yyextra;
}
/** Get the current line number.
* @param yyscanner The scanner object.
*/
int yyget_lineno (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if (! YY_CURRENT_BUFFER)
return 0;
return yylineno;
}
/** Get the current column number.
* @param yyscanner The scanner object.
*/
int yyget_column (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if (! YY_CURRENT_BUFFER)
return 0;
return yycolumn;
}
/** Get the input stream.
* @param yyscanner The scanner object.
*/
FILE *yyget_in (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yyin;
}
/** Get the output stream.
* @param yyscanner The scanner object.
*/
FILE *yyget_out (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yyout;
}
/** Get the length of the current token.
* @param yyscanner The scanner object.
*/
int yyget_leng (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yyleng;
}
/** Get the current token.
* @param yyscanner The scanner object.
*/
char *yyget_text (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yytext;
}
/** Set the user-defined data. This data is never touched by the scanner.
* @param user_defined The data to be associated with this scanner.
* @param yyscanner The scanner object.
*/
void yyset_extra (YY_EXTRA_TYPE user_defined , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yyextra = user_defined ;
}
/** Set the current line number.
* @param _line_number line number
* @param yyscanner The scanner object.
*/
void yyset_lineno (int _line_number , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
/* lineno is only valid if an input buffer exists. */
if (! YY_CURRENT_BUFFER )
YY_FATAL_ERROR( "yyset_lineno called with no buffer" );
yylineno = _line_number;
}
/** Set the current column.
* @param _column_no column number
* @param yyscanner The scanner object.
*/
void yyset_column (int _column_no , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
/* column is only valid if an input buffer exists. */
if (! YY_CURRENT_BUFFER )
YY_FATAL_ERROR( "yyset_column called with no buffer" );
yycolumn = _column_no;
}
/** Set the input stream. This does not discard the current
* input buffer.
* @param _in_str A readable stream.
* @param yyscanner The scanner object.
* @see yy_switch_to_buffer
*/
void yyset_in (FILE * _in_str , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yyin = _in_str ;
}
void yyset_out (FILE * _out_str , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yyout = _out_str ;
}
int yyget_debug (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yy_flex_debug;
}
void yyset_debug (int _bdebug , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yy_flex_debug = _bdebug ;
}
/* Accessor methods for yylval and yylloc */
YYSTYPE * yyget_lval (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yylval;
}
void yyset_lval (YYSTYPE * yylval_param , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yylval = yylval_param;
}
/* User-visible API */
/* yylex_init is special because it creates the scanner itself, so it is
* the ONLY reentrant function that doesn't take the scanner as the last argument.
* That's why we explicitly handle the declaration, instead of using our macros.
*/
int yylex_init(yyscan_t* ptr_yy_globals)
{
if (ptr_yy_globals == NULL){
errno = EINVAL;
return 1;
}
*ptr_yy_globals = (yyscan_t) yyalloc ( sizeof( struct yyguts_t ), NULL );
if (*ptr_yy_globals == NULL){
errno = ENOMEM;
return 1;
}
/* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */
memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t));
return yy_init_globals ( *ptr_yy_globals );
}
/* yylex_init_extra has the same functionality as yylex_init, but follows the
* convention of taking the scanner as the last argument. Note however, that
* this is a *pointer* to a scanner, as it will be allocated by this call (and
* is the reason, too, why this function also must handle its own declaration).
* The user defined value in the first argument will be available to yyalloc in
* the yyextra field.
*/
int yylex_init_extra( YY_EXTRA_TYPE yy_user_defined, yyscan_t* ptr_yy_globals )
{
struct yyguts_t dummy_yyguts;
yyset_extra (yy_user_defined, &dummy_yyguts);
if (ptr_yy_globals == NULL){
errno = EINVAL;
return 1;
}
*ptr_yy_globals = (yyscan_t) yyalloc ( sizeof( struct yyguts_t ), &dummy_yyguts );
if (*ptr_yy_globals == NULL){
errno = ENOMEM;
return 1;
}
/* By setting to 0xAA, we expose bugs in
yy_init_globals. Leave at 0x00 for releases. */
memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t));
yyset_extra (yy_user_defined, *ptr_yy_globals);
return yy_init_globals ( *ptr_yy_globals );
}
static int yy_init_globals (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
/* Initialization is the same as for the non-reentrant scanner.
* This function is called from yylex_destroy(), so don't allocate here.
*/
yyg->yy_buffer_stack = NULL;
yyg->yy_buffer_stack_top = 0;
yyg->yy_buffer_stack_max = 0;
yyg->yy_c_buf_p = NULL;
yyg->yy_init = 0;
yyg->yy_start = 0;
yyg->yy_start_stack_ptr = 0;
yyg->yy_start_stack_depth = 0;
yyg->yy_start_stack = NULL;
/* Defined in main.c */
#ifdef YY_STDINIT
yyin = stdin;
yyout = stdout;
#else
yyin = NULL;
yyout = NULL;
#endif
/* For future reference: Set errno on error, since we are called by
* yylex_init()
*/
return 0;
}
/* yylex_destroy is for both reentrant and non-reentrant scanners. */
int yylex_destroy (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
/* Pop the buffer stack, destroying each element. */
while(YY_CURRENT_BUFFER){
yy_delete_buffer( YY_CURRENT_BUFFER , yyscanner );
YY_CURRENT_BUFFER_LVALUE = NULL;
yypop_buffer_state(yyscanner);
}
/* Destroy the stack itself. */
yyfree(yyg->yy_buffer_stack , yyscanner);
yyg->yy_buffer_stack = NULL;
/* Destroy the start condition stack. */
yyfree( yyg->yy_start_stack , yyscanner );
yyg->yy_start_stack = NULL;
/* Reset the globals. This is important in a non-reentrant scanner so the next time
* yylex() is called, initialization will occur. */
yy_init_globals( yyscanner);
/* Destroy the main struct (reentrant only). */
yyfree ( yyscanner , yyscanner );
yyscanner = NULL;
return 0;
}
/*
* Internal utility routines.
*/
#ifndef yytext_ptr
static void yy_flex_strncpy (char* s1, const char * s2, int n , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
(void)yyg;
int i;
for ( i = 0; i < n; ++i )
s1[i] = s2[i];
}
#endif
#ifdef YY_NEED_STRLEN
static int yy_flex_strlen (const char * s , yyscan_t yyscanner)
{
int n;
for ( n = 0; s[n]; ++n )
;
return n;
}
#endif
void *yyalloc (yy_size_t size , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
(void)yyg;
return malloc(size);
}
void *yyrealloc (void * ptr, yy_size_t size , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
(void)yyg;
/* The cast to (char *) in the following accommodates both
* implementations that use char* generic pointers, and those
* that use void* generic pointers. It works with the latter
* because both ANSI C and C++ allow castless assignment from
* any pointer type to void*, and deal with argument conversions
* as though doing an assignment.
*/
return realloc(ptr, size);
}
void yyfree (void * ptr , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
(void)yyg;
free( (char *) ptr ); /* see yyrealloc() for (char *) cast */
}
#define YYTABLES_NAME "yytables"
#line 677 "ds_lexer.lpp"
void das_yybegin_reader ( yyscan_t yyscanner ) {
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
BEGIN(reader);
}
void das_yyend_reader ( yyscan_t yyscanner ) {
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
BEGIN(normal);
}
#if DAS_YYDEBUG
extern int das_yydebug;
#endif
void das_yybegin(const char * str, uint32_t len, yyscan_t yyscanner ) {
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yyextra->g_thisStructure = nullptr;
yyextra->das_module_alias.clear();
yyextra->das_already_include.clear();
#if DAS_YYDEBUG
das_yydebug = 0;
#endif
yyextra->das_tab_size = yyextra->das_def_tab_size;
yyextra->das_line_no.clear();
YYCOLUMN(yyextra->das_yycolumn = 0,"YYBEGIN");
yyextra->das_current_line_indent = 0;
yyextra->das_indent_level = 0;
yyextra->das_nested_parentheses = 0;
yyextra->das_nested_curly_braces = 0;
yyextra->das_nested_square_braces = 0;
yyextra->das_nested_sb = 0;
yyextra->das_need_oxford_comma = true;
yyextra->das_force_oxford_comma = false;
yyextra->das_c_style_depth = 0;
yyextra->das_arrow_depth = 0;
yyextra->g_ReaderMacro = nullptr;
yyextra->g_ReaderExpr = nullptr;
BEGIN(normal);
yy_scan_bytes(str, len, yyscanner);
yylineno = 1;
}
void YYNEWLINE ( yyscan_t yyscanner ) {
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
YYCOLUMN(yyextra->das_yycolumn = 0,"NEW LINE");
}
| 28.304153 | 142 | 0.631289 | profelis |
ae321c80dfaadc0e06163c683151a761e76510f2 | 767 | cpp | C++ | union_find/test.cpp | fedom/Algorithms | 94f9c80c7425d4739be8fb67292deb6b8bb78cc2 | [
"MIT"
] | null | null | null | union_find/test.cpp | fedom/Algorithms | 94f9c80c7425d4739be8fb67292deb6b8bb78cc2 | [
"MIT"
] | null | null | null | union_find/test.cpp | fedom/Algorithms | 94f9c80c7425d4739be8fb67292deb6b8bb78cc2 | [
"MIT"
] | null | null | null | #include "quick_find_uf.h"
#include <stdio.h>
#include <time.h>
#include <fstream>
#include <iostream>
int main(int argc, char *argv[]) {
char *file = "tinyUF.txt";
if (argc >= 2) file = argv[1];
std::ifstream ifs(file);
if (ifs.is_open()) {
int total;
ifs >> total;
std::cout << "total:" << total << std::endl;
QuickFindUF uf(total);
time_t a = time(NULL);
while (!ifs.eof()) {
int a;
int b;
ifs >> a;
ifs >> b;
uf.Connect(a, b);
}
time_t d = time(NULL) - a;
std::cout << "uf count:" << uf.Count() << std::endl;
std::cout << "union time : " << d << std::endl;
}
ifs.close();
return 0;
}
| 18.707317 | 60 | 0.461538 | fedom |
ae32bfab82b547009bae83a8b64a52cb93584c57 | 7,730 | cpp | C++ | src/slg/kernels/texture_noise_funcs_kernel.cpp | DavidBluecame/LuxRays | be0f5228b8b65268278a6c6a1c98564ebdc27c05 | [
"Apache-2.0"
] | null | null | null | src/slg/kernels/texture_noise_funcs_kernel.cpp | DavidBluecame/LuxRays | be0f5228b8b65268278a6c6a1c98564ebdc27c05 | [
"Apache-2.0"
] | null | null | null | src/slg/kernels/texture_noise_funcs_kernel.cpp | DavidBluecame/LuxRays | be0f5228b8b65268278a6c6a1c98564ebdc27c05 | [
"Apache-2.0"
] | null | null | null | #include <string>
namespace slg { namespace ocl {
std::string KernelSource_texture_noise_funcs =
"#line 2 \"texture_noise_funcs.cl\"\n"
"\n"
"/***************************************************************************\n"
" * Copyright 1998-2015 by authors (see AUTHORS.txt) *\n"
" * *\n"
" * This file is part of LuxRender. *\n"
" * *\n"
" * Licensed under the Apache License, Version 2.0 (the \"License\"); *\n"
" * you may not use this file except in compliance with the License. *\n"
" * You may obtain a copy of the License at *\n"
" * *\n"
" * http://www.apache.org/licenses/LICENSE-2.0 *\n"
" * *\n"
" * Unless required by applicable law or agreed to in writing, software *\n"
" * distributed under the License is distributed on an \"AS IS\" BASIS, *\n"
" * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.*\n"
" * See the License for the specific language governing permissions and *\n"
" * limitations under the License. *\n"
" ***************************************************************************/\n"
"\n"
"//------------------------------------------------------------------------------\n"
"// Texture utility functions\n"
"//------------------------------------------------------------------------------\n"
"\n"
"// Perlin Noise Data\n"
"#define NOISE_PERM_SIZE 256\n"
"__constant int NoisePerm[2 * NOISE_PERM_SIZE] = {\n"
" 151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96,\n"
" 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142,\n"
" // Rest of noise permutation table\n"
" 8, 99, 37, 240, 21, 10, 23,\n"
" 190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33,\n"
" 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, 48, 27, 166,\n"
" 77, 146, 158, 231, 83, 111, 229, 122, 60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244,\n"
" 102, 143, 54, 65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169, 200, 196,\n"
" 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64, 52, 217, 226, 250, 124, 123,\n"
" 5, 202, 38, 147, 118, 126, 255, 82, 85, 212, 207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42,\n"
" 223, 183, 170, 213, 119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9,\n"
" 129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104, 218, 246, 97, 228,\n"
" 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241, 81, 51, 145, 235, 249, 14, 239, 107,\n"
" 49, 192, 214, 31, 181, 199, 106, 157, 184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254,\n"
" 138, 236, 205, 93, 222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180,\n"
" 151, 160, 137, 91, 90, 15,\n"
" 131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23,\n"
" 190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33,\n"
" 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, 48, 27, 166,\n"
" 77, 146, 158, 231, 83, 111, 229, 122, 60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244,\n"
" 102, 143, 54, 65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169, 200, 196,\n"
" 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64, 52, 217, 226, 250, 124, 123,\n"
" 5, 202, 38, 147, 118, 126, 255, 82, 85, 212, 207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42,\n"
" 223, 183, 170, 213, 119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9,\n"
" 129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104, 218, 246, 97, 228,\n"
" 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241, 81, 51, 145, 235, 249, 14, 239, 107,\n"
" 49, 192, 214, 31, 181, 199, 106, 157, 184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254,\n"
" 138, 236, 205, 93, 222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180\n"
"};\n"
"\n"
"float Grad(int x, int y, int z, float dx, float dy, float dz) {\n"
" const int h = NoisePerm[NoisePerm[NoisePerm[x] + y] + z] & 15;\n"
" const float u = h < 8 || h == 12 || h == 13 ? dx : dy;\n"
" const float v = h < 4 || h == 12 || h == 13 ? dy : dz;\n"
" return ((h & 1) ? -u : u) + ((h & 2) ? -v : v);\n"
"}\n"
"\n"
"float NoiseWeight(float t) {\n"
" const float t3 = t * t * t;\n"
" const float t4 = t3 * t;\n"
" return 6.f * t4 * t - 15.f * t4 + 10.f * t3;\n"
"}\n"
"\n"
"float Noise(float x, float y, float z) {\n"
" // Compute noise cell coordinates and offsets\n"
" int ix = Floor2Int(x);\n"
" int iy = Floor2Int(y);\n"
" int iz = Floor2Int(z);\n"
" const float dx = x - ix, dy = y - iy, dz = z - iz;\n"
" // Compute gradient weights\n"
" ix &= (NOISE_PERM_SIZE - 1);\n"
" iy &= (NOISE_PERM_SIZE - 1);\n"
" iz &= (NOISE_PERM_SIZE - 1);\n"
" const float w000 = Grad(ix, iy, iz, dx, dy, dz);\n"
" const float w100 = Grad(ix + 1, iy, iz, dx - 1, dy, dz);\n"
" const float w010 = Grad(ix, iy + 1, iz, dx, dy - 1, dz);\n"
" const float w110 = Grad(ix + 1, iy + 1, iz, dx - 1, dy - 1, dz);\n"
" const float w001 = Grad(ix, iy, iz + 1, dx, dy, dz - 1);\n"
" const float w101 = Grad(ix + 1, iy, iz + 1, dx - 1, dy, dz - 1);\n"
" const float w011 = Grad(ix, iy + 1, iz + 1, dx, dy - 1, dz - 1);\n"
" const float w111 = Grad(ix + 1, iy + 1, iz + 1, dx - 1, dy - 1, dz - 1);\n"
" // Compute trilinear interpolation of weights\n"
" const float wx = NoiseWeight(dx);\n"
" const float wy = NoiseWeight(dy);\n"
" const float wz = NoiseWeight(dz);\n"
" const float x00 = Lerp(wx, w000, w100);\n"
" const float x10 = Lerp(wx, w010, w110);\n"
" const float x01 = Lerp(wx, w001, w101);\n"
" const float x11 = Lerp(wx, w011, w111);\n"
" const float y0 = Lerp(wy, x00, x10);\n"
" const float y1 = Lerp(wy, x01, x11);\n"
" return Lerp(wz, y0, y1);\n"
"}\n"
"\n"
"float Noise3(const float3 P) {\n"
" return Noise(P.x, P.y, P.z);\n"
"}\n"
"\n"
"float FBm(const float3 P, const float omega, const int maxOctaves) {\n"
" // Compute number of octaves for anti-aliased FBm\n"
" const float foctaves = (float)maxOctaves;\n"
" const int octaves = Floor2Int(foctaves);\n"
" // Compute sum of octaves of noise for FBm\n"
" float sum = 0.f, lambda = 1.f, o = 1.f;\n"
" for (int i = 0; i < octaves; ++i) {\n"
" sum += o * Noise3(lambda * P);\n"
" lambda *= 1.99f;\n"
" o *= omega;\n"
" }\n"
" const float partialOctave = foctaves - (float)octaves;\n"
" sum += o * SmoothStep(.3f, .7f, partialOctave) *\n"
" Noise3(lambda * P);\n"
" return sum;\n"
"}\n"
"\n"
"float Turbulence(const float3 P, const float omega, const int maxOctaves) {\n"
" // Compute number of octaves for anti-aliased FBm\n"
" const float foctaves = (float)maxOctaves;\n"
" const int octaves = Floor2Int(foctaves);\n"
" // Compute sum of octaves of noise for turbulence\n"
" float sum = 0.f, lambda = 1.f, o = 1.f;\n"
" for (int i = 0; i < octaves; ++i) {\n"
" sum += o * fabs(Noise3(lambda * P));\n"
" lambda *= 1.99f;\n"
" o *= omega;\n"
" }\n"
" const float partialOctave = foctaves - (float)(octaves);\n"
" sum += o * SmoothStep(.3f, .7f, partialOctave) *\n"
" fabs(Noise3(lambda * P));\n"
"\n"
" // finally, add in value to account for average value of fabsf(Noise())\n"
" // (~0.2) for the remaining octaves...\n"
" sum += (maxOctaves - foctaves) * 0.2f;\n"
"\n"
" return sum;\n"
"}\n"
; } }
| 52.22973 | 103 | 0.520181 | DavidBluecame |
ae33f2a025285a2f707a6f723ac0a96c58b54f7e | 10,060 | cpp | C++ | LEGACY/src/librapid/array/multiarray_constructors.cpp | NervousNullPtr/librapid | 2a8f4baccf479138097d5b4ee9e6e060ecab55db | [
"MIT"
] | null | null | null | LEGACY/src/librapid/array/multiarray_constructors.cpp | NervousNullPtr/librapid | 2a8f4baccf479138097d5b4ee9e6e060ecab55db | [
"MIT"
] | null | null | null | LEGACY/src/librapid/array/multiarray_constructors.cpp | NervousNullPtr/librapid | 2a8f4baccf479138097d5b4ee9e6e060ecab55db | [
"MIT"
] | null | null | null | #include <librapid/array/multiarray.hpp>
#include <librapid/utils/array_utils.hpp>
namespace librapid {
RawArray validRawArray =
RawArray {(int64_t *)nullptr, Datatype::VALIDNONE, Accelerator::CPU};
#ifdef LIBRAPID_HAS_CUDA
# ifdef LIBRAPID_CUDA_STREAM
cudaStream_t cudaStream;
bool streamCreated = false;
# endif // LIBRAPID_CUDA_STREAM
#endif // LIBRAPID_HAS_CUDA
Array::Array() { initializeCudaStream(); }
Array::Array(const Extent &extent, Datatype dtype, Accelerator location) {
initializeCudaStream();
if (extent.containsAutomatic()) {
throw std::invalid_argument(
"Cannot create an Array from an Extent"
" containing automatic values. "
"Extent was " +
extent.str());
}
constructNew(extent, Stride::fromExtent(extent), dtype, location);
}
Array::Array(const Array &other, Datatype dtype, Accelerator locn) {
// Quick return if possible
if (other.m_references == nullptr) { return; }
if (dtype == Datatype::NONE) { dtype = other.m_dtype; }
if (locn == Accelerator::NONE) { locn = other.m_location; }
if (dtype != other.m_dtype || locn != other.m_location) {
// Must cast other to the correct value
Array tmp = other.clone(dtype, locn);
m_location = tmp.m_location;
m_dtype = tmp.m_dtype;
m_dataStart = tmp.m_dataStart;
m_dataOrigin = tmp.m_dataOrigin;
m_references = tmp.m_references;
m_extent = tmp.m_extent;
m_stride = tmp.m_stride;
m_isScalar = tmp.m_isScalar;
m_isChild = tmp.m_isChild;
increment();
return;
}
m_location = other.m_location;
m_dtype = other.m_dtype;
m_dataStart = other.m_dataStart;
m_dataOrigin = other.m_dataOrigin;
m_references = other.m_references;
m_extent = other.m_extent;
m_stride = other.m_stride;
m_isScalar = other.m_isScalar;
m_isChild = other.m_isChild;
increment();
}
Array::Array(bool val, Datatype dtype, Accelerator locn) {
initializeCudaStream();
constructNew(Extent(1), Stride(1), dtype, locn);
m_isScalar = true;
if (locn == Accelerator::CPU) {
std::visit([&](auto *data) { *data = val; }, m_dataStart);
}
#ifdef LIBRAPID_HAS_CUDA
else {
int64_t tmpVal = val;
RawArray temp = RawArray {m_dataStart, dtype, locn};
rawArrayMemcpy(
temp, {&tmpVal, Datatype::INT64, Accelerator::CPU}, 1);
}
#else
else {
throw std::invalid_argument(
"CUDA support was not enabled, "
"so a value cannot be created on the GPU");
}
#endif // LIBRAPID_HAS_CUDA
}
Array::Array(float val, Datatype dtype, Accelerator locn) {
initializeCudaStream();
constructNew(Extent(1), Stride(1), dtype, locn);
m_isScalar = true;
if (locn == Accelerator::CPU) {
std::visit([&](auto *data) { *data = val; }, m_dataStart);
}
#ifdef LIBRAPID_HAS_CUDA
else {
RawArray temp = RawArray {m_dataStart, dtype, locn};
rawArrayMemcpy(
temp, {&val, Datatype::FLOAT32, Accelerator::CPU}, 1);
}
#else
else {
throw std::invalid_argument(
"CUDA support was not enabled, "
"so a value cannot be created on the GPU");
}
#endif // LIBRAPID_HAS_CUDA
}
Array::Array(double val, Datatype dtype, Accelerator locn) {
initializeCudaStream();
constructNew(Extent(1), Stride(1), dtype, locn);
m_isScalar = true;
if (locn == Accelerator::CPU) {
std::visit([&](auto *data) { *data = val; }, m_dataStart);
}
#ifdef LIBRAPID_HAS_CUDA
else {
RawArray temp = RawArray {m_dataStart, dtype, locn};
rawArrayMemcpy(
temp, {&val, Datatype::FLOAT64, Accelerator::CPU}, 1);
}
#else
else {
throw std::invalid_argument(
"CUDA support was not enabled, "
"so a value cannot be created on the GPU");
}
#endif // LIBRAPID_HAS_CUDA
}
Array &Array::operator=(const Array &other) {
// Quick return if possible
if (this == &other) return *this;
if (other.m_references == nullptr) { return *this; }
if (!m_isChild) {
// If the array is not a child, decrement it and copy the relevant
// data, then increment this
decrement();
m_location = other.m_location;
m_dtype = other.m_dtype;
m_dataStart = other.m_dataStart;
m_dataOrigin = other.m_dataOrigin;
m_references = other.m_references;
m_extent = other.m_extent;
m_stride = other.m_stride;
m_isScalar = other.m_isScalar;
m_isChild = other.m_isChild;
increment();
} else {
// The array is a child, so the data MUST be copied by value, not by
// reference
// Ensure the Arrays have the same extent
if (m_extent != other.m_extent) {
std::string err =
fmt::format("Cannot set child array with {} to {}",
m_extent.str(),
other.m_extent.str());
throw std::invalid_argument(err);
}
if (m_stride.isContiguous() && other.m_stride.isContiguous()) {
// If both arrays are contiguous in memory, copy the data with
// memcpy to speed things up
rawArrayMemcpy(createRaw(), other.createRaw(), m_extent.size());
} else {
applyUnaryOp(*this, other, ops::Copy());
}
// No need to increment as the data was copied directly
}
return *this;
// if (m_references == nullptr) {
// constructNew(
// other.m_extent, other.m_stride, other.m_dtype,
// other.m_location); } else {
// // Array already exists, so check if it must be reallocated
//
// // This condition might be needed? => || m_dtype !=
// other.m_dtype if (!m_isChild && m_extent !=
// other.m_extent)
// {
// // Extents are not equal, so memory can not be safely
// copied decrement();
// constructNew(other.m_extent, other.m_stride,
// other.m_dtype, other.m_location); m_isScalar
// =
// other.m_isScalar; } else { increment();
// }
// }
//
// if (!m_isChild) {
// m_extent = other.m_extent;
// m_stride = other.m_stride;
// }
//
// // Attempt to copy the data from other into *this
// if (m_stride.isContiguous() && other.m_stride.isContiguous()) {
// // auto raw = createRaw();
// rawArrayMemcpy(createRaw(), other.createRaw(),
// m_extent.size()); } else { throw
// std::runtime_error("Haven't gotten to this yet...");
// }
//
// m_isScalar = other.m_isScalar;
// m_dtype = other.m_dtype;
// m_location = other.m_location;
//
// return *this;
}
Array &Array::operator=(bool val) {
if (m_isChild && !m_isScalar) {
throw std::invalid_argument(
"Cannot set an array with more than zero"
" dimensions to a scalar value. Array must"
" have zero dimensions (i.e. scalar)");
}
if (!m_isChild) {
if (m_references != nullptr) { decrement(); }
constructNew(
Extent(1), Stride(1), Datatype::INT64, Accelerator::CPU);
}
int64_t tmpVal = val;
auto raw = createRaw();
rawArrayMemcpy(
raw, RawArray {&tmpVal, Datatype::INT64, Accelerator::CPU}, 1);
m_isScalar = true;
return *this;
}
Array &Array::operator=(float val) {
if (m_isChild && !m_isScalar) {
throw std::invalid_argument(
"Cannot set an array with more than zero"
" dimensions to a scalar value. Array must"
" have zero dimensions (i.e. scalar)");
}
if (!m_isChild) {
if (m_references != nullptr) { decrement(); }
constructNew(
Extent(1), Stride(1), Datatype::FLOAT32, Accelerator::CPU);
}
auto raw = createRaw();
rawArrayMemcpy(
raw, RawArray {&val, Datatype::FLOAT32, Accelerator::CPU}, 1);
m_isScalar = true;
return *this;
}
Array &Array::operator=(double val) {
if (m_isChild && !m_isScalar) {
throw std::invalid_argument(
"Cannot set an array with more than zero"
" dimensions to a scalar value. Array must"
" have zero dimensions (i.e. scalar)");
}
if (!m_isChild) {
if (m_references != nullptr) { decrement(); }
constructNew(
Extent(1), Stride(1), Datatype::FLOAT64, Accelerator::CPU);
}
auto raw = createRaw();
rawArrayMemcpy(
raw, RawArray {&val, Datatype::FLOAT64, Accelerator::CPU}, 1);
m_isScalar = true;
return *this;
}
Array &Array::operator=(Complex<double> val) {
if (m_isChild && !m_isScalar) {
throw std::invalid_argument(
"Cannot set an array with more than zero"
" dimensions to a scalar value. Array must"
" have zero dimensions (i.e. scalar)");
}
if (!m_isChild) {
if (m_references != nullptr) { decrement(); }
constructNew(
Extent(1), Stride(1), Datatype::CFLOAT64, Accelerator::CPU);
}
auto raw = createRaw();
rawArrayMemcpy(
raw, RawArray {&val, Datatype::FLOAT64, Accelerator::CPU}, 1);
m_isScalar = true;
return *this;
}
Array::~Array() { decrement(); }
void Array::constructNew(const Extent &e, const Stride &s,
const Datatype &dtype,
const Accelerator &location) {
// Is scalar if extent is [0]
bool isScalar = (e.ndim() == 1) && (e[0] == 0);
// Construct members
m_location = location;
m_dtype = dtype;
// If array is scalar, allocate "sizeof(dtype)" bytes -- e.size() is 0
auto raw = RawArray {m_dataStart, dtype, location};
m_dataStart = rawArrayMalloc(raw, e.size() + isScalar).data;
m_dataOrigin = m_dataStart;
m_references = new std::atomic<int64_t>(1);
m_extent = e;
m_stride = s;
m_isScalar = isScalar;
m_isChild = false;
}
void Array::constructHollow(const Extent &e, const Stride &s,
const Datatype &dtype,
const Accelerator &location) {
m_extent = e;
m_stride = s;
m_dtype = dtype;
m_location = location;
m_stride.setContiguity(m_stride.checkContiguous(m_extent));
if (ndim() > LIBRAPID_MAX_DIMS) {
throw std::domain_error("Cannot create an array with " +
std::to_string(ndim()) +
" dimensions. The "
"maximum allowed number of dimensions is " +
std::to_string(LIBRAPID_MAX_DIMS));
}
}
Array zerosLike(const Array &other) {
Array res(other.extent(), other.dtype(), other.location());
res.fill(0);
return res;
}
Array onesLike(const Array &other) {
Array res(other.extent(), other.dtype(), other.location());
res.fill(1);
return res;
}
} // namespace librapid | 26.826667 | 75 | 0.647614 | NervousNullPtr |
ae36c8f83d840e914ead13a81dc0fa31d4615f64 | 49 | cpp | C++ | SpaceStationRescueSouls/SpaceStationRescueSouls/src/component/CollisionWorld.cpp | Neversee-Productions/Space-Station-Rescue-Souls | 48621dd8ddf9c6282669b1547ebca0af56ef7fa9 | [
"MIT"
] | 1 | 2020-03-24T04:40:18.000Z | 2020-03-24T04:40:18.000Z | SpaceStationRescueSouls/SpaceStationRescueSouls/src/component/CollisionWorld.cpp | Neversee-Productions/Space-Station-Rescue-Souls | 48621dd8ddf9c6282669b1547ebca0af56ef7fa9 | [
"MIT"
] | null | null | null | SpaceStationRescueSouls/SpaceStationRescueSouls/src/component/CollisionWorld.cpp | Neversee-Productions/Space-Station-Rescue-Souls | 48621dd8ddf9c6282669b1547ebca0af56ef7fa9 | [
"MIT"
] | 1 | 2020-03-24T04:40:19.000Z | 2020-03-24T04:40:19.000Z | #include "stdafx.h"
#include "CollisionWorld.h"
| 16.333333 | 27 | 0.734694 | Neversee-Productions |
ae447a75f3782605d88fb73540042d950f0cd565 | 4,680 | hpp | C++ | common/phonebook.hpp | canaryinthemines/ILLIXR | 1e3d9b2a4c56f6bf311cbeda83171359e285b10e | [
"NCSA",
"MIT"
] | null | null | null | common/phonebook.hpp | canaryinthemines/ILLIXR | 1e3d9b2a4c56f6bf311cbeda83171359e285b10e | [
"NCSA",
"MIT"
] | null | null | null | common/phonebook.hpp | canaryinthemines/ILLIXR | 1e3d9b2a4c56f6bf311cbeda83171359e285b10e | [
"NCSA",
"MIT"
] | null | null | null | #pragma once
#include <typeindex>
#include <stdexcept>
#include <iostream>
#include <cassert>
#include <mutex>
#include <memory>
#include <unordered_map>
namespace ILLIXR {
/**
* @brief A [service locator][1] for ILLIXR.
*
* This will be explained through an exmaple: Suppose one dynamically-loaded plugin, `A_plugin`,
* needs a service, `B_service`, provided by another, `B_plugin`. `A_plugin` cannot statically
* construct a `B_service`, because the implementation `B_plugin` is dynamically
* loaded. However, `B_plugin` can register an implementation of `B_service` when it is loaded,
* and `A_plugin` can lookup that implementation without knowing it.
*
* `B_service.hpp` in `common`:
* \code{.cpp}
* class B_service {
* public:
* virtual void frobnicate(foo data) = 0;
* };
* \endcode
*
* `B_plugin.hpp`:
* \code{.cpp}
* class B_impl : public B_service {
* public:
* virtual void frobnicate(foo data) {
* // ...
* }
* };
* void blah_blah(phonebook* pb) {
* // Expose `this` as the "official" implementation of `B_service` for this run.
* pb->register_impl<B_service>(new B_impl);
* }
* \endcode
*
* `A_plugin.cpp`:
* \code{.cpp}
* #include "B_service.hpp"
* void blah_blah(phonebook* pb) {
* B_service* b = pb->lookup_impl<B_service>();
* b->frobnicate(data);
* }
* \endcode
*
* If the implementation of `B_service` is not known to `A_plugin` (the usual case), `B_service
* should be an [abstract class][2]. In either case `B_service` should be in `common`, so both
* plugins can refer to it.
*
* One could even selectively return a different implementation of `B_service` depending on the
* caller (through the parameters), but we have not encountered the need for that yet.
*
* [1]: https://en.wikipedia.org/wiki/Service_locator_pattern
* [2]: https://en.wikibooks.org/wiki/C%2B%2B_Programming/Classes/Abstract_Classes
*/
class phonebook {
/*
Proof of thread-safety:
- Since all instance members are private, acquiring a lock in each method implies the class is datarace-free.
- Since there is only one lock and this does not call any code containing locks, this is deadlock-free.
- Both of these methods are only used during initialization, so the locks are not contended in steady-state.
However, to write a correct program, one must also check the thread-safety of the elements
inserted into this class by the caller.
*/
public:
/**
* @brief A 'service' that can be registered in the phonebook.
*
* These must be 'destructible', have a virtual destructor that phonebook can call in its
* destructor.
*/
class service {
public:
/**
*/
virtual ~service() { }
};
/**
* @brief Registers an implementation of @p baseclass for future calls to lookup.
*
* Safe to be called from any thread.
*
* The implementation will be owned by phonebook (phonebook calls `delete`).
*/
template <typename specific_service>
void register_impl(std::shared_ptr<specific_service> impl) {
const std::lock_guard<std::mutex> lock{_m_mutex};
const std::type_index type_index = std::type_index(typeid(specific_service));
#ifndef NDEBUG
std::cerr << "Register " << type_index.name() << std::endl;
#endif
assert(_m_registry.count(type_index) == 0);
_m_registry.try_emplace(type_index, impl);
}
/**
* @brief Look up an implementation of @p specific_service, which should be registered first.
*
* Safe to be called from any thread.
*
* Do not call `delete` on the returned object; it is still managed by phonebook.
*
* @throws if an implementation is not already registered.
*/
template <typename specific_service>
std::shared_ptr<specific_service> lookup_impl() const {
const std::lock_guard<std::mutex> lock{_m_mutex};
const std::type_index type_index = std::type_index(typeid(specific_service));
#ifndef NDEBUG
// if this assert fails, and there are no duplicate base classes, ensure the hash_code's are unique.
if (_m_registry.count(type_index) != 1) {
throw std::runtime_error{"Attempted to lookup an unregistered implementation " + std::string{type_index.name()}};
}
#endif
std::shared_ptr<service> this_service = _m_registry.at(type_index);
assert(this_service);
std::shared_ptr<specific_service> this_specific_service = std::dynamic_pointer_cast<specific_service>(this_service);
assert(this_specific_service);
return this_specific_service;
}
private:
std::unordered_map<std::type_index, const std::shared_ptr<service>> _m_registry;
mutable std::mutex _m_mutex;
};
}
| 32.275862 | 119 | 0.693162 | canaryinthemines |
ae492e4348816dbcaed0271fbc78e88ccbe1e4aa | 1,270 | cpp | C++ | MKE/src/MKE/SpriteBatch.cpp | tMario2111/MKE | a5adf18d41f08b35c31e3ddb2679e5cad62da07f | [
"MIT"
] | 3 | 2021-11-03T07:43:07.000Z | 2022-03-10T09:45:15.000Z | MKE/src/MKE/SpriteBatch.cpp | tMario2111/MKE | a5adf18d41f08b35c31e3ddb2679e5cad62da07f | [
"MIT"
] | null | null | null | MKE/src/MKE/SpriteBatch.cpp | tMario2111/MKE | a5adf18d41f08b35c31e3ddb2679e5cad62da07f | [
"MIT"
] | null | null | null | #include "SpriteBatch.h"
namespace mke
{
SpriteBatch::SpriteBatch() :
batch(sf::PrimitiveType::Quads)
{
}
void SpriteBatch::draw(sf::RenderTarget& target, sf::RenderStates states) const
{
target.draw(batch, states);
}
void SpriteBatch::append(const sf::Sprite& sprite)
{
sf::FloatRect texture_rect = static_cast<sf::FloatRect>(sprite.getTextureRect());
sf::Vertex verts[4];
verts[0].texCoords = sf::Vector2f(texture_rect.left, texture_rect.top);
verts[1].texCoords = sf::Vector2f(texture_rect.left + texture_rect.width, texture_rect.top);
verts[2].texCoords = sf::Vector2f(texture_rect.left + texture_rect.width, texture_rect.top + texture_rect.height);
verts[3].texCoords = sf::Vector2f(texture_rect.left, texture_rect.top + texture_rect.height);
verts[0].position = sprite.getTransform().transformPoint(0, 0);
verts[1].position = sprite.getTransform().transformPoint(texture_rect.width, 0);
verts[2].position = sprite.getTransform().transformPoint(texture_rect.width, texture_rect.height);
verts[3].position = sprite.getTransform().transformPoint(0, texture_rect.height);
for (int i = 0; i < 4; i++)
{
verts[i].color = sprite.getColor();
batch.append(verts[i]);
}
}
void SpriteBatch::clear()
{
batch.clear();
}
}
| 31.75 | 116 | 0.722047 | tMario2111 |
ae49617c7348852fdc63f59c7deba2236c460f1b | 2,072 | hpp | C++ | include/upp/impl/cli/value.hpp | tlammi/upp | 480615e11b8dd12b36fee0e78b984e1b5051183d | [
"MIT"
] | null | null | null | include/upp/impl/cli/value.hpp | tlammi/upp | 480615e11b8dd12b36fee0e78b984e1b5051183d | [
"MIT"
] | null | null | null | include/upp/impl/cli/value.hpp | tlammi/upp | 480615e11b8dd12b36fee0e78b984e1b5051183d | [
"MIT"
] | null | null | null | /* SPDX-License-Identifier: MIT */
/* Copyright @ 2020 Toni Lammi */
#pragma once
#include <string>
#include <string_view>
#include <vector>
#include "upp/impl/cli/convert.hpp"
namespace upp {
namespace cli {
class ValueBase {
public:
virtual ~ValueBase() {}
virtual void add_value(const char* str) = 0;
virtual bool full() const = 0;
virtual std::vector<std::pair<std::string_view, std::string_view>>
restrictions() const {
return {};
}
virtual bool support_multiple() const { return false; }
private:
};
template <typename T>
class Value : public ValueBase {
public:
explicit Value(T& data) : data_{data} {}
void add_value(const char* str) {
if (value_set_)
throw ParsingError("Argument specified multiple times");
data_ = converter<T>::convert(str);
value_set_ = true;
}
bool full() const { return value_set_; }
std::vector<std::string_view> help() const { return {}; }
private:
T& data_;
bool value_set_{false};
};
template <typename T>
class Value<std::vector<T>> : public ValueBase {
public:
explicit Value(std::vector<T>& data) : data_{data} {}
void add_value(const char* str) {
data_.emplace_back(converter<T>::convert(str));
}
bool full() const { return false; }
bool support_multiple() const { return true; }
private:
std::vector<T>& data_;
std::string help_{};
};
template <typename T>
class Value<Enum<T>> : public ValueBase {
public:
explicit Value(Enum<T>& data) : data_{data} {}
void add_value(const char* str) {
if (value_set_)
throw ParsingError("Argument specified multiple times");
data_ = converter<Enum<T>>::convert(str);
value_set_ = true;
}
bool full() const { return value_set_; }
std::vector<std::pair<std::string_view, std::string_view>>
restrictions() const {
std::vector<std::pair<std::string_view, std::string_view>> out;
for (const auto& pair : data_) {
out.push_back({pair.str, pair.help});
}
return out;
}
private:
bool value_set_{false};
Enum<T>& data_;
};
} // namespace cli
} // namespace upp | 22.521739 | 68 | 0.665058 | tlammi |
ae49a7c7457f2af902956b3caed120e334f8ab11 | 1,268 | cpp | C++ | coursework2/test/map_gen_disp/map_gen_test.cpp | foundnet/UOE_PS_coursework | eb719fee024806ec03fbec528e9eb42d444f6289 | [
"Apache-2.0"
] | null | null | null | coursework2/test/map_gen_disp/map_gen_test.cpp | foundnet/UOE_PS_coursework | eb719fee024806ec03fbec528e9eb42d444f6289 | [
"Apache-2.0"
] | null | null | null | coursework2/test/map_gen_disp/map_gen_test.cpp | foundnet/UOE_PS_coursework | eb719fee024806ec03fbec528e9eb42d444f6289 | [
"Apache-2.0"
] | null | null | null | #include "../../include/randommap.h"
#include "gtest/gtest.h"
#include <vector>
#include <cmath>
using std::vector;
TEST(mapgenTestSuite, NormalSizeCheck){
vector<vector<double>> map = map_gen(30,20,1.0,10,4);
EXPECT_EQ(map.size(), 200);
EXPECT_EQ(map[0].size(), 300);
}
TEST(mapgenTestSuite, NarrowSizeCheck1){
vector<vector<double>> map = map_gen(1,10,1.0,10,4);
EXPECT_EQ(map.size(), 100);
EXPECT_EQ(map[0].size(), 10);
}
TEST(mapgenTestSuite, NarrowSizeCheck2){
vector<vector<double>> map = map_gen(10,1,1.0,10,4);
EXPECT_EQ(map.size(), 10);
EXPECT_EQ(map[0].size(), 100);
}
TEST(mapgenTestSuite, WhiteNoiseSizeCheck){
vector<vector<double>> map = map_gen(30,20,1.0,1,4);
EXPECT_EQ(map.size(), 20);
EXPECT_EQ(map[0].size(), 30);
}
TEST(mapgenTestSuite, ZeroOctaveThrowCheck){
EXPECT_ANY_THROW(map_gen(30,20,1.0,10,0));
}
TEST(mapgenTestSuite, ZeroSampleThrowCheck){
EXPECT_ANY_THROW(map_gen(30,20,1.0,0,4));
}
TEST(mapgenTestSuite, ZeroSizeThrowCheck1){
EXPECT_ANY_THROW(map_gen(0,20,1.0,10,4));
}
TEST(mapgenTestSuite, ZeroSizeThrowCheck2){
EXPECT_ANY_THROW(map_gen(30,0,1.0,10,4));
}
int main(int argc,char **argv)
{
testing::InitGoogleTest(&argc,argv);
return RUN_ALL_TESTS();
}
| 23.924528 | 57 | 0.685331 | foundnet |
ae4fdbe1785af7f213e21e2bdde416975c9183e6 | 7,878 | cpp | C++ | src/Keyboard.cpp | 00steve/Lapster | 42c11d7bf96694c36f75d938563031cb08951ff1 | [
"Apache-2.0"
] | null | null | null | src/Keyboard.cpp | 00steve/Lapster | 42c11d7bf96694c36f75d938563031cb08951ff1 | [
"Apache-2.0"
] | null | null | null | src/Keyboard.cpp | 00steve/Lapster | 42c11d7bf96694c36f75d938563031cb08951ff1 | [
"Apache-2.0"
] | null | null | null | #include "Keyboard.h"
void Keyboard::Setup(){
timer.TicksPerSecond(2);
valueX = 100;
valueY = 40;
backButton = new Button(Int2(10,10),Int2(90,90),"Back");
delButton = new Button(Int2(410,10),Int2(470,90),"<--");
int keyWidth = 43;
int keyHeight = 50;
int keySpace = 3;
int x = 11;
int y = 100;
qButton = new Button(Int2(x,y),Int2(x+=keyWidth,y+keyHeight),"q"); x += keySpace;
wButton = new Button(Int2(x,y),Int2(x+=keyWidth,y+keyHeight),"w"); x += keySpace;
eButton = new Button(Int2(x,y),Int2(x+=keyWidth,y+keyHeight),"e"); x += keySpace;
rButton = new Button(Int2(x,y),Int2(x+=keyWidth,y+keyHeight),"r"); x += keySpace;
tButton = new Button(Int2(x,y),Int2(x+=keyWidth,y+keyHeight),"t"); x += keySpace;
yButton = new Button(Int2(x,y),Int2(x+=keyWidth,y+keyHeight),"y"); x += keySpace;
uButton = new Button(Int2(x,y),Int2(x+=keyWidth,y+keyHeight),"u"); x += keySpace;
iButton = new Button(Int2(x,y),Int2(x+=keyWidth,y+keyHeight),"i"); x += keySpace;
oButton = new Button(Int2(x,y),Int2(x+=keyWidth,y+keyHeight),"o"); x += keySpace;
pButton = new Button(Int2(x,y),Int2(x+=keyWidth,y+keyHeight),"p"); x += keySpace;
x = 34;
y += keyHeight + keySpace;
aButton = new Button(Int2(x,y),Int2(x+=keyWidth,y+keyHeight),"a"); x += keySpace;
sButton = new Button(Int2(x,y),Int2(x+=keyWidth,y+keyHeight),"s"); x += keySpace;
dButton = new Button(Int2(x,y),Int2(x+=keyWidth,y+keyHeight),"d"); x += keySpace;
fButton = new Button(Int2(x,y),Int2(x+=keyWidth,y+keyHeight),"f"); x += keySpace;
gButton = new Button(Int2(x,y),Int2(x+=keyWidth,y+keyHeight),"g"); x += keySpace;
hButton = new Button(Int2(x,y),Int2(x+=keyWidth,y+keyHeight),"h"); x += keySpace;
jButton = new Button(Int2(x,y),Int2(x+=keyWidth,y+keyHeight),"j"); x += keySpace;
kButton = new Button(Int2(x,y),Int2(x+=keyWidth,y+keyHeight),"k"); x += keySpace;
lButton = new Button(Int2(x,y),Int2(x+=keyWidth,y+keyHeight),"l"); x += keySpace;
x = 57;
y += keyHeight + keySpace;
zButton = new Button(Int2(x,y),Int2(x+=keyWidth,y+keyHeight),"z"); x += keySpace;
xButton = new Button(Int2(x,y),Int2(x+=keyWidth,y+keyHeight),"x"); x += keySpace;
cButton = new Button(Int2(x,y),Int2(x+=keyWidth,y+keyHeight),"c"); x += keySpace;
vButton = new Button(Int2(x,y),Int2(x+=keyWidth,y+keyHeight),"v"); x += keySpace;
bButton = new Button(Int2(x,y),Int2(x+=keyWidth,y+keyHeight),"b"); x += keySpace;
nButton = new Button(Int2(x,y),Int2(x+=keyWidth,y+keyHeight),"n"); x += keySpace;
mButton = new Button(Int2(x,y),Int2(x+=keyWidth,y+keyHeight),"m"); x += keySpace;
x = 80;
y += keyHeight + keySpace;
spaceButton = new Button(Int2(x,y),Int2(x+=keyWidth*4,y+keyHeight),""); x += keySpace;
}
Keyboard::Keyboard(String *value,short maxLength) :
value(value),
blinker(false),
maxLength(maxLength)
{
Setup();
}
Keyboard::~Keyboard(){
delete aButton;
delete bButton;
delete cButton;
delete dButton;
delete eButton;
delete fButton;
delete gButton;
delete hButton;
delete iButton;
delete jButton;
delete kButton;
delete lButton;
delete mButton;
delete nButton;
delete oButton;
delete pButton;
delete qButton;
delete rButton;
delete sButton;
delete tButton;
delete uButton;
delete vButton;
delete wButton;
delete xButton;
delete yButton;
delete zButton;
delete spaceButton;
delete delButton;
delete backButton;
}
void Keyboard::Update(){
if(Button::CheckForScreenPress()){
Serial.println("keyboard press");
if(backButton->Pressing()){
Button::WaitForDepress();
Finished(true);
}
if(delButton->Pressing()){
DrawDel();
*value = value->substring(0,value->length()-1);
}
if(value->length() < maxLength){
if(aButton->Pressing()) {*value += 'a';DrawDel();DrawChars(value->length()-1);}
if(bButton->Pressing()) {*value += 'b';DrawDel();DrawChars(value->length()-1);}
if(cButton->Pressing()) {*value += 'c';DrawDel();DrawChars(value->length()-1);}
if(dButton->Pressing()) {*value += 'd';DrawDel();DrawChars(value->length()-1);}
if(eButton->Pressing()) {*value += 'e';DrawDel();DrawChars(value->length()-1);}
if(fButton->Pressing()) {*value += 'f';DrawDel();DrawChars(value->length()-1);}
if(gButton->Pressing()) {*value += 'g';DrawDel();DrawChars(value->length()-1);}
if(hButton->Pressing()) {*value += 'h';DrawDel();DrawChars(value->length()-1);}
if(iButton->Pressing()) {*value += 'i';DrawDel();DrawChars(value->length()-1);}
if(jButton->Pressing()) {*value += 'j';DrawDel();DrawChars(value->length()-1);}
if(kButton->Pressing()) {*value += 'k';DrawDel();DrawChars(value->length()-1);}
if(lButton->Pressing()) {*value += 'l';DrawDel();DrawChars(value->length()-1);}
if(mButton->Pressing()) {*value += 'm';DrawDel();DrawChars(value->length()-1);}
if(nButton->Pressing()) {*value += 'n';DrawDel();DrawChars(value->length()-1);}
if(oButton->Pressing()) {*value += 'o';DrawDel();DrawChars(value->length()-1);}
if(pButton->Pressing()) {*value += 'p';DrawDel();DrawChars(value->length()-1);}
if(qButton->Pressing()) {*value += 'q';DrawDel();DrawChars(value->length()-1);}
if(rButton->Pressing()) {*value += 'r';DrawDel();DrawChars(value->length()-1);}
if(sButton->Pressing()) {*value += 's';DrawDel();DrawChars(value->length()-1);}
if(tButton->Pressing()) {*value += 't';DrawDel();DrawChars(value->length()-1);}
if(uButton->Pressing()) {*value += 'u';DrawDel();DrawChars(value->length()-1);}
if(vButton->Pressing()) {*value += 'v';DrawDel();DrawChars(value->length()-1);}
if(wButton->Pressing()) {*value += 'w';DrawDel();DrawChars(value->length()-1);}
if(xButton->Pressing()) {*value += 'x';DrawDel();DrawChars(value->length()-1);}
if(yButton->Pressing()) {*value += 'y';DrawDel();DrawChars(value->length()-1);}
if(zButton->Pressing()) {*value += 'z';DrawDel();DrawChars(value->length()-1);}
if(spaceButton->Pressing()) {*value += ' ';DrawDel();DrawChars(value->length()-1);}
Serial.println(*value);
}
}
Draw();
}
void Keyboard::Draw(){
if(timer.Tick()){
blinker = !blinker;
tft.setCursor(valueX+value->length()*25,valueY);
tft.setTextSize(4);
if(blinker){
tft.setTextColor(0xFFFF);
} else {
tft.setTextColor(0x0000);
}
tft.print("_");
tft.setTextSize(2);
}
}
void Keyboard::DrawDel(){
tft.fillRect(valueX+value->length()*25,valueY,25,35,0x0000);
}
void Keyboard::DrawChars(unsigned int startingIndex){
tft.setTextColor(0xFFFF);
tft.setTextSize(4);
while(startingIndex < value->length()){
tft.setCursor(valueX + startingIndex*25,valueY);
tft.print((*value)[startingIndex]);
++startingIndex;
}
}
void Keyboard::Redraw(){
tft.fillScreen(0x0000);
backButton->Draw();
delButton->Draw();
DrawChars(0);
tft.setTextSize(2);
qButton->Draw(); wButton->Draw(); eButton->Draw(); rButton->Draw(); tButton->Draw(); yButton->Draw(); uButton->Draw(); iButton->Draw(); oButton->Draw(); pButton->Draw();
aButton->Draw(); sButton->Draw(); dButton->Draw(); fButton->Draw(); gButton->Draw(); hButton->Draw(); jButton->Draw(); kButton->Draw(); lButton->Draw();
zButton->Draw(); xButton->Draw(); cButton->Draw(); vButton->Draw(); bButton->Draw(); nButton->Draw(); mButton->Draw();
spaceButton->Draw();
}
| 39.19403 | 173 | 0.59114 | 00steve |
ae54d1d37aa672496acb17e53e2c43c2904c6629 | 970 | cpp | C++ | day25/solution.cpp | qwoprocks/Advent-of-Code-2020-Solutions | 65d96f89af013585ac994b8556d003b6455b0de1 | [
"MIT"
] | null | null | null | day25/solution.cpp | qwoprocks/Advent-of-Code-2020-Solutions | 65d96f89af013585ac994b8556d003b6455b0de1 | [
"MIT"
] | null | null | null | day25/solution.cpp | qwoprocks/Advent-of-Code-2020-Solutions | 65d96f89af013585ac994b8556d003b6455b0de1 | [
"MIT"
] | null | null | null | /* Link to problem: https://adventofcode.com/2020/day/25 */
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <set>
using namespace std;
long long part1(long long card_public_key, long long door_public_key) {
long long mod = 20201227;
long long subject_number = 7;
long long card_loop_size = 0;
long long start = 1;
while (start != card_public_key) {
start = (start * subject_number) % mod;
++card_loop_size;
}
long long encryption_key = 1;
for (int i = 0; i < card_loop_size; ++i) {
encryption_key = (encryption_key * door_public_key) % mod;
}
return encryption_key;
}
int main() {
ifstream reader("input.txt");
string line;
getline(reader, line);
long long card_public_key = stoll(line);
getline(reader, line);
long long door_public_key = stoll(line);
cout << "Part 1: " << part1(card_public_key, door_public_key) << endl;
return 0;
}
| 27.714286 | 74 | 0.652577 | qwoprocks |
ae59ce7e42db92d0d43e3bc4b87f979c6e0dd4f6 | 1,058 | hpp | C++ | osl/Construct.hpp | elnormous/OuzelShadingLanguage | d1644bf2bb244adc44223dd8570c1acd51ff39d2 | [
"BSD-2-Clause"
] | 5 | 2018-03-28T10:37:46.000Z | 2022-03-28T13:45:50.000Z | osl/Construct.hpp | elnormous/OuzelShadingLanguage | d1644bf2bb244adc44223dd8570c1acd51ff39d2 | [
"BSD-2-Clause"
] | null | null | null | osl/Construct.hpp | elnormous/OuzelShadingLanguage | d1644bf2bb244adc44223dd8570c1acd51ff39d2 | [
"BSD-2-Clause"
] | null | null | null | //
// OSL
//
#ifndef CONSTRUCT_HPP
#define CONSTRUCT_HPP
namespace ouzel
{
class Construct
{
public:
enum class Kind
{
Declaration,
Statement,
Expression,
Attribute
};
explicit Construct(Kind initKind) noexcept: kind{initKind} {}
virtual ~Construct() = default;
Construct(const Construct&) = delete;
Construct& operator=(const Construct&) = delete;
Construct(Construct&&) = delete;
Construct& operator=(Construct&&) = delete;
const Kind kind;
};
inline std::string toString(Construct::Kind kind)
{
switch (kind)
{
case Construct::Kind::Declaration: return "Declaration";
case Construct::Kind::Statement: return "Statement";
case Construct::Kind::Expression: return "Expression";
case Construct::Kind::Attribute: return "Attribute";
}
throw std::runtime_error("Unknown construct kind");
}
}
#endif // CONSTRUCT_HPP
| 23 | 69 | 0.579395 | elnormous |
ae5a56571b8152aafbb749f31b862d784eabae29 | 302 | hpp | C++ | src/include/Bus/Memory/Memory.hpp | Garoze/Console | d99a08fb88fab4da5ca7c2c2c6d81fb9e5d6cb56 | [
"MIT"
] | null | null | null | src/include/Bus/Memory/Memory.hpp | Garoze/Console | d99a08fb88fab4da5ca7c2c2c6d81fb9e5d6cb56 | [
"MIT"
] | null | null | null | src/include/Bus/Memory/Memory.hpp | Garoze/Console | d99a08fb88fab4da5ca7c2c2c6d81fb9e5d6cb56 | [
"MIT"
] | null | null | null | #pragma once
#include <array>
#include <cstdint>
#define MEMORY_SIZE 64 * 1024
class Memory
{
public:
Memory();
void viewAt(std::uint16_t);
public:
std::uint8_t& operator[](std::uint16_t i)
{
return data[i];
}
private:
std::array<std::uint8_t, MEMORY_SIZE> data;
};
| 13.727273 | 47 | 0.629139 | Garoze |
ae618e182a830a807ee3e2e83c7727dca25dea5c | 2,205 | cpp | C++ | Std/Forward.cpp | asynts/picoos | 5197f86ce1902fc6572cecd10f97ca68109f2f86 | [
"MIT"
] | 1 | 2021-08-24T05:59:32.000Z | 2021-08-24T05:59:32.000Z | Std/Forward.cpp | asynts/picoos | 5197f86ce1902fc6572cecd10f97ca68109f2f86 | [
"MIT"
] | 3 | 2021-03-31T15:36:01.000Z | 2021-04-19T14:17:44.000Z | Std/Forward.cpp | asynts/picoos | 5197f86ce1902fc6572cecd10f97ca68109f2f86 | [
"MIT"
] | null | null | null | #include <Std/Forward.hpp>
#include <Std/Format.hpp>
#include <Std/Lexer.hpp>
#if !defined(TEST) && !defined(KERNEL)
# error "Only KERNEL and TEST are supported"
#endif
#if defined(TEST)
# include <iostream>
# include <cstdlib>
#elif defined(KERNEL)
# include <Kernel/ConsoleDevice.hpp>
# include <Kernel/HandlerMode.hpp>
#endif
namespace Std
{
static void write_output(StringView value)
{
#if defined(TEST)
std::cerr << std::string_view { value.data(), value.size() };
#elif defined(KERNEL)
Kernel::ConsoleFileHandle handle;
// We do not aquire a mutex here, because the system may not work at
// this point.
bool were_interrupts_enabled = Kernel::disable_interrupts();
handle.write(value.bytes());
Kernel::restore_interrupts(were_interrupts_enabled);
#endif
}
static void write_output(usize value)
{
#if defined(TEST)
std::cerr << value;
#elif defined(KERNEL)
Kernel::ConsoleFileHandle handle;
StringBuilder builder;
builder.appendf("{}", value);
// We do not aquire a mutex here, because the system may not work at
// this point.
bool were_interrupts_enabled = Kernel::disable_interrupts();
handle.write(builder.bytes());
Kernel::restore_interrupts(were_interrupts_enabled);
#endif
}
void crash(const char *format, const char *condition, const char *file, usize line)
{
Std::Lexer lexer { format };
while (!lexer.eof()) {
if (lexer.try_consume("%condition")) {
write_output(condition);
continue;
}
if (lexer.try_consume("%file")) {
write_output(file);
continue;
}
if (lexer.try_consume("%line")) {
write_output(line);
continue;
}
write_output(lexer.consume_until('%'));
if (lexer.peek_or_null() != '%')
ASSERT(lexer.eof());
}
write_output("\n");
#if defined(TEST)
std::abort();
#else
asm volatile("bkpt #0");
for(;;)
asm volatile("wfi");
#endif
}
}
| 25.344828 | 87 | 0.582313 | asynts |
ae61fe9c0709ef23779b6f9244b31d0e26f0be26 | 8,667 | hpp | C++ | __unit_tests/gv_framework_unit_test/unit_test_display_animation.hpp | dragonsn/gv_game_engine | dca6c1fb1f8d96e9a244f157a63f8a69da084b0f | [
"MIT"
] | 2 | 2018-12-03T13:17:31.000Z | 2020-04-08T07:00:02.000Z | __unit_tests/gv_framework_unit_test/unit_test_display_animation.hpp | dragonsn/gv_game_engine | dca6c1fb1f8d96e9a244f157a63f8a69da084b0f | [
"MIT"
] | null | null | null | __unit_tests/gv_framework_unit_test/unit_test_display_animation.hpp | dragonsn/gv_game_engine | dca6c1fb1f8d96e9a244f157a63f8a69da084b0f | [
"MIT"
] | null | null | null | namespace unit_test_display_animation
{
void main(gvt_array< gv_string >& args)
{
bool do_compress = false;
if (args.find("compress"))
{
do_compress = true;
}
gv_int idx;
bool do_file = false;
bool do_software_skinning = true;
gv_string file_name;
if (args.find("file", idx))
{
do_file = true;
file_name = args[idx + 1];
}
bool t_pose_only = false;
if (args.find("t_pose", idx))
{
t_pose_only = true;
}
gv_string mod_file_name;
if (args.find("mod", idx))
{
mod_file_name = args[idx + 1];
}
{
gv_unit_test_context_guard context;
sub_test_timer timer("unit_test_importer_exporter_fbx");
double start_time = m_sandbox->get_time_in_seconds();
m_sandbox->register_processor(gv_world::static_class(), gve_event_channel_world);
gv_world* my_world = gvt_cast< gv_world >(m_sandbox->get_event_processor(gve_event_channel_world));
gv_entity* my_camera = m_sandbox->create_object< gv_entity >(gv_id("my_camera"), NULL);
my_camera->add_component(gv_id("gv_com_cam_fps_fly"));
gv_com_camera* camera = m_sandbox->create_object< gv_com_camera >(gv_id("main_camera"), my_camera);
my_camera->add_component(camera);
GVM_POST_EVENT(render_set_camera, render, (pe->camera = camera));
my_world->add_entity(my_camera);
gv_module* pmod = NULL;
if (!do_file)
{
if (mod_file_name.size())
pmod = m_sandbox->load_module(gv_id(*mod_file_name));
else
pmod = m_sandbox->try_load_module(gv_id("wolf"));
}
else
{
pmod = m_sandbox->create_object< gv_module >(gv_id(MOD_WOLF));
gv_model* model = m_sandbox->create_object< gv_model >(pmod);
m_sandbox->import_external_format(model, *file_name);
m_sandbox->export_module(pmod->get_name_id());
}
gvt_object_iterator< gv_skeletal > it(m_sandbox);
gv_skeletal* my_skeletal = NULL;
if (!it.is_empty())
{
my_skeletal = it;
};
if (!my_skeletal)
{
return;
}
GV_ASSERT(my_skeletal);
gv_ani_set* my_animation = NULL;
gvt_object_iterator< gv_ani_set > it_ani(m_sandbox);
if (!it_ani.is_empty())
{
my_animation = it_ani;
if (do_compress)
{
}
}
gv_skeletal_mesh* my_skeletal_mesh = NULL;
gvt_object_iterator< gv_skeletal_mesh > it_skeletal_mesh(m_sandbox);
if (!it_skeletal_mesh.is_empty())
{
my_skeletal_mesh = it_skeletal_mesh;
my_skeletal_mesh->optimize_bones();
}
if (my_skeletal_mesh)
{
gv_entity* my_entity = m_sandbox->create_object< gv_entity >(gv_id("entity"), NULL);
gv_static_mesh* my_static_mesh = my_skeletal_mesh->m_t_pose_mesh;
if (do_software_skinning)
{
gv_com_static_mesh* pmesh0 = m_sandbox->create_object< gv_com_static_mesh >(my_entity);
//gv_texture * my_texture =m_sandbox->create_object<gv_texture>(my_static_mesh);
//gv_string_tmp tex_file_name=FILE_TEX_SNOW_CUBEMAP;
//my_texture->set_file_name(tex_file_name);
//my_static_mesh->m_diffuse_texture=my_texture;
pmesh0->set_resource(my_static_mesh);
pmesh0->set_renderer_id(gve_render_pass_opaque, gv_id("gv_com_wire_frame_renderer"));
//pmesh0->set_renderer_id(gve_render_pass_opaque, gv_id( "gv_com_wire_frame_renderer") );
my_entity->add_component(pmesh0);
}
else
{
gv_com_skeletal_mesh* pmesh0 = m_sandbox->create_object< gv_com_skeletal_mesh >(my_entity);
pmesh0->set_resource(my_skeletal_mesh);
my_entity->add_component(pmesh0);
}
my_world->add_entity(my_entity);
float r = my_static_mesh->get_bsphere().get_radius();
camera->set_fov(60, 1.333f, 0.1f * r, 100 * r);
camera->set_look_at(gv_vector3(0, 1, 5.f) * r, gv_vector3(0, 0, 0));
camera->update_projection_view_matrix();
}
//============>>GO GO GO !!
int loop = 1000;
if (args.size())
args[0] >> loop;
bool quit = false;
gv_float scale_factor = 1.0f;
//if (args.size()>1 ) args[1]>>scale_factor;
gvt_array< gv_vector3 > original_pos;
bool pause = false;
while (loop-- && !quit)
{
static int index_seq = 0;
if (loop == 1)
{
gv_object_event_render_uninit* pe = new gv_object_event_render_uninit;
m_sandbox->post_event(pe, gve_event_channel_render);
}
quit = !m_sandbox->tick();
gvi_debug_renderer* pdebug = gv_global::debug_draw.get();
pdebug->draw_line_3d(gv_vector3(0, 0, 0), gv_vector3(10, 0, 0), gv_color::RED(), gv_color::RED_B());
pdebug->draw_line_3d(gv_vector3(0, 0, 0), gv_vector3(0, 10, 0), gv_color::GREEN(), gv_color::GREEN_B());
pdebug->draw_line_3d(gv_vector3(0, 0, 0), gv_vector3(0, 0, 10), gv_color::BLUE(), gv_color::BLUE_B());
gv_string_tmp info;
if (my_animation)
{
info << " current animation ";
if (index_seq >= my_animation->get_nb_sequence())
{
index_seq = 0;
}
gv_ani_sequence* pseq = my_animation->get_sequence(index_seq);
info << pseq->get_name_id() << "(" << index_seq << "/" << my_animation->get_nb_sequence();
pdebug->draw_string(*info, gv_vector2i(100, 20), gv_color::BLUE_D());
}
{
static bool last_key_down = false;
if (m_sandbox->get_input_manager()->is_key_down(e_key_space) && !last_key_down)
{
index_seq++;
start_time = m_sandbox->get_time_in_seconds();
}
last_key_down = m_sandbox->get_input_manager()->is_key_down(e_key_space);
}
{
static bool last_key_down = false;
if (m_sandbox->get_input_manager()->is_key_down(e_key_p) && !last_key_down)
{
pause = !pause;
}
last_key_down = m_sandbox->get_input_manager()->is_key_down(e_key_p);
}
//======================================================
//ANIMATE THE MESH
my_skeletal->m_root_tm.set_identity();
if (!t_pose_only && my_animation && my_skeletal && !pause)
{
gv_double time = m_sandbox->get_time_in_seconds() - start_time;
gv_ulong frame = (gv_ulong)(time * 30.0);
if (index_seq >= my_animation->get_nb_sequence())
{
index_seq = 0;
}
gv_ani_sequence* pseq = my_animation->get_sequence(index_seq);
if (pseq)
{
int nb_track = pseq->get_track_number();
if (!nb_track)
continue;
gv_float d = pseq->get_duration();
gv_vector3 pos, scale;
gv_quat q;
for (int i = 0; i < nb_track; i++)
{
gv_ani_track* ptrack = pseq->get_track(i);
ptrack->get_trans_rot((float)time, pos, q, scale, true);
pos *= scale_factor;
my_skeletal->set_bone_local_rotation_trans(ptrack->get_name_id(), q, pos, scale);
}
}
my_skeletal->update_world_matrix();
}
//======================================================
//DRAW THE SKELETAL
if (my_skeletal)
{
for (int i = 0; i < my_skeletal->m_bones.size(); i++)
{
gv_bone& bone = my_skeletal->m_bones[i];
if (bone.m_hierachy_depth)
{
gv_bone& father = my_skeletal->m_bones[bone.m_parent_idx];
pdebug->draw_line_3d(bone.m_tm.get_trans(), father.m_tm.get_trans(), gv_color::WHITE(), gv_color::BLACK());
}
}
}
//======================================================
//MORPH THE VERTEX!!
//SIN WAVE MORPH..
/*
if (my_skeletal_mesh)
{
gv_static_mesh * pmesh=my_skeletal_mesh->m_t_pose_mesh;
if (pmesh && pmesh->m_vertex_buffer)
{
gv_vertex_buffer *vb=pmesh->m_vertex_buffer;
if (!original_pos.size()) original_pos=vb->m_raw_pos;
for ( int i=0; i< vb->m_raw_pos.size(); i++)
{
gv_vector3 &v3=vb->m_raw_pos[i];
v3.x=original_pos[i].x+sinf(v3.y+m_sandbox->get_time_in_seconds()*10.f)*0.4f;
}
vb->set_dirty();
}
}
*/
static bool draw_skin = true;
if (!t_pose_only && my_skeletal_mesh && draw_skin)
{
gv_static_mesh* pmesh = my_skeletal_mesh->m_t_pose_mesh;
if (pmesh && pmesh->m_vertex_buffer)
{
gv_vertex_buffer* vb = pmesh->m_vertex_buffer;
if (!original_pos.size())
original_pos = vb->m_raw_pos;
for (int i = 0; i < vb->m_raw_pos.size(); i++)
{
gv_vector3& v3 = vb->m_raw_pos[i];
v3 = 0;
for (int j = 0; j < 4; j++)
{
gv_short bone_index = (gv_short)vb->m_raw_blend_index[i][j];
if (bone_index == -1)
continue;
gv_bone* pbone = NULL;
if (!my_skeletal_mesh->m_bone_mapping.size())
{
pbone = &my_skeletal_mesh->m_skeletal->m_bones[bone_index];
}
else
{
pbone = &my_skeletal_mesh->m_skeletal->m_bones[my_skeletal_mesh->m_bone_inv_mapping[bone_index]];
}
gv_bone& bone = *pbone;
v3 += original_pos[i] * bone.m_matrix_model_to_bone * bone.m_tm * vb->m_raw_blend_weight[i][j];
}
if (v3.is_almost_zero())
{
int c = 1;
}
}
vb->set_dirty();
}
} //draw t-pose
} //loop
} //context
} //main
}
| 30.410526 | 113 | 0.646244 | dragonsn |
ae6e0213ff0c952cb84f840c77cbc1ba9de7d712 | 652 | hh | C++ | MCDataProducts/inc/PointTrajectoryCollection.hh | bonventre/Offline | 77db9d6368f27ab9401c690c2c2a4257ade6c231 | [
"Apache-2.0"
] | null | null | null | MCDataProducts/inc/PointTrajectoryCollection.hh | bonventre/Offline | 77db9d6368f27ab9401c690c2c2a4257ade6c231 | [
"Apache-2.0"
] | 1 | 2019-11-22T14:45:51.000Z | 2019-11-22T14:50:03.000Z | MCDataProducts/inc/PointTrajectoryCollection.hh | bonventre/Offline | 77db9d6368f27ab9401c690c2c2a4257ade6c231 | [
"Apache-2.0"
] | 2 | 2019-10-14T17:46:58.000Z | 2020-03-30T21:05:15.000Z | #ifndef MCDataProducts_PointTrajectoryCollection_hh
#define MCDataProducts_PointTrajectoryCollection_hh
//
// Define a type for a collection of PointTrajectory objects.
// The key is the simulated particle ID (same as for the
// SimParticleCollection).
//
// $Id: PointTrajectoryCollection.hh,v 1.2 2011/05/24 20:03:31 wb Exp $
// $Author: wb $
// $Date: 2011/05/24 20:03:31 $
//
// Original author Rob Kutschke
//
#include "MCDataProducts/inc/PointTrajectory.hh"
#include "cetlib/map_vector.h"
namespace mu2e {
typedef cet::map_vector<mu2e::PointTrajectory> PointTrajectoryCollection;
}
#endif /* MCDataProducts_PointTrajectoryCollection_hh */
| 27.166667 | 76 | 0.769939 | bonventre |
ae70c8b906df8c9483c1f6ccf81413249959cb47 | 4,279 | cpp | C++ | src/Draw/Image.cpp | FishbowlDigital/FBDraw | 4ea6198f01be5f3c9627ca34bff263245bfd3ecc | [
"MIT",
"Unlicense"
] | null | null | null | src/Draw/Image.cpp | FishbowlDigital/FBDraw | 4ea6198f01be5f3c9627ca34bff263245bfd3ecc | [
"MIT",
"Unlicense"
] | null | null | null | src/Draw/Image.cpp | FishbowlDigital/FBDraw | 4ea6198f01be5f3c9627ca34bff263245bfd3ecc | [
"MIT",
"Unlicense"
] | null | null | null | // Image.cpp
// Implementation file for the Image class
//
// Copyright(c) 2017 - 2022 Fishbowl Digital LLC
//
// 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 "Image.h"
#include "Macros.h"
namespace FBDraw
{
// Constructor
Image::Image(int x, int y, int w, int h, color32_t* image, bool hasAlpha /* = true */)
{
m_location = Point(x, y);
m_height = h;
m_width = w;
m_imageBuffer = image;
m_bOwnsBuffer = false;
m_bHasAlpha = hasAlpha;
// Default is Visible
Visible = true;
}
Image::Image(int x, int y, int w, int h, bool hasAlpha /* = true */)
{
m_location = Point(x, y);
m_height = h;
m_width = w;
m_imageBuffer = new color32_t[w * h];
m_bOwnsBuffer = true;
m_bHasAlpha = hasAlpha;
// Default is Visible
Visible = true;
}
Image::~Image()
{
if (m_bOwnsBuffer)
delete m_imageBuffer;
}
void Image::ReplaceBuffer(color32_t* image)
{
ReplaceBuffer(image, m_location, m_width, m_height);
};
void Image::ReplaceBuffer(color32_t* image, int w, int h)
{
ReplaceBuffer(image, m_location, w, h);
}
void Image::ReplaceBuffer(color32_t* image, Point loc, int w, int h)
{
// Clean old buffer?
if (m_bOwnsBuffer)
delete m_imageBuffer;
// Replace
m_imageBuffer = image;
m_location = loc;
m_width = w;
m_height = h;
// Set new ownership state
m_bOwnsBuffer = false; // Don't cleanup this buffer on delete
}
#ifndef WIN32
__attribute__((optimize("unroll-loops")))
#endif
void Image::Render(color32_t* backBuffer, int width, int height)
{
if (m_imageBuffer == NULL)
return;
int iCanvasStart = ((m_location.Y) * width) + m_location.X;
// Copy the image to the backbuffer
if (m_bHasAlpha)
{
ARGB_Color mixBGRA = ARGB_Color{ 0x00, 0x00, 0x00, 0x00 };
for (int iY = 0; iY < m_height; iY++)
{
int iCanvasRowStart = iCanvasStart + (iY * width);
int iImageRowStart = (iY * m_width);
for (int iX = 0; iX < m_width; iX++)
{
// Alpha mix the image pixel and the back buffer
ARGB_Bytes imgColor, backColor, mixColor;
imgColor.U32 = m_imageBuffer[iImageRowStart + iX];
backColor.U32 = backBuffer[iCanvasRowStart + iX];
mixColor.Color.Red = AlphaMix8(backColor.Color.Red, imgColor.Color.Red, imgColor.Color.Alpha);
mixColor.Color.Green = AlphaMix8(backColor.Color.Green, imgColor.Color.Green, imgColor.Color.Alpha);
mixColor.Color.Blue = AlphaMix8(backColor.Color.Blue, imgColor.Color.Blue, imgColor.Color.Alpha);
backBuffer[iCanvasRowStart + iX] = mixColor.U32 | 0xFF000000;
}
}
}
else
{
for (int iY = 0; iY < m_height; iY++)
{
uint32_t* pBackBuffer = &backBuffer[iCanvasStart + (iY * width)];
uint32_t* pImgBuffer = &m_imageBuffer[(iY * m_width)];
for (int iX = 0; iX < m_width; iX++, pBackBuffer++, pImgBuffer++)
{
*pBackBuffer = *pImgBuffer | 0xFF000000;
}
}
}
}
bool Image::HitTest(int x, int y)
{
return x > m_location.X &&
x < (m_location.X+m_width) &&
y > m_location.Y &&
y < (m_location.Y+m_height);
}
}
| 29.715278 | 106 | 0.649918 | FishbowlDigital |
ae72179e0987143289476d0dece7489e65d23ff5 | 3,146 | cpp | C++ | Lab/SavingsFucnctionPotPourri/main.cpp | salazaru/Program-Logic-Using-Cpp | e4fb97f00eb639d523b7ede0661ff1698301f46d | [
"MIT"
] | 1 | 2015-03-06T01:03:54.000Z | 2015-03-06T01:03:54.000Z | Lab/SavingsFucnctionPotPourri/main.cpp | salazaru/Salazar_Uriel_CSC5_43952 | e4fb97f00eb639d523b7ede0661ff1698301f46d | [
"MIT"
] | null | null | null | Lab/SavingsFucnctionPotPourri/main.cpp | salazaru/Salazar_Uriel_CSC5_43952 | e4fb97f00eb639d523b7ede0661ff1698301f46d | [
"MIT"
] | null | null | null | //File: main.cpp
//==========================================================================
//Programmer: Uriel Salazar
//==========================================================================
//Created: April 20, 2015, 8:14 PM
//==========================================================================
//Purpose: Functions
//==========================================================================
//System Libraries
#include <iostream> //Input/Output Library
#include <iomanip> //Parametric Library
using namespace std; //Input/Output Library under standard name space
//User Libraries
//Global Constants
//Function Prototypes
float save1(float, float, int); //Power Function
float save2(float, float, int); //Exponential & Log Function
float save3(float, float, int); //For-Loop
float save4(float, float, int); //Recursive -> Calling itself
float save5(float = 100.0f, float = 0.08f, int = 9); //Defaulted Parameter
void save6(float, float, int);
void save7(float, float, int);
float save1(float, float, float);
//Execution Begins
int main()
{
//Declare Variables
float pv = 100.0f; //Present Value$'s
float ir = 0.08f; //Interest Rate % / yr
int nC = 9; //Number of Compounding Periods
//Output the Inputs
cout << setprecision(2) << showpoint;
cout << "Present Value = $ " << pv <<endl;
cout << "Interest Rate = " << ir * 100 << "%" << endl;
cout << "Number of Compounding Periods = " << nC << "(yrs)";
//Calculate our savings
cout << "Savings Function 1 = $" << save1(pv, ir, nC) << endl;
float nCf = nc;
cout << "Savings Function 2 = $" << save2(pv, ir, nC) << endl;
cout << "Savings Function 3 = $" << save3(pv, ir, nC) << endl;
cout << "Savings Function 4 = $" << save4(pv, ir, nC) << endl;
cout << "Savings Function 5 = $" << save5(pv, ir, nC) << endl;
cout << "Savings Function 5 = $" << save5(pv, ir) << endl;
cout << "Savings Function 5 = $" << save5(pv) << endl;
cout << "Savings Function 5 = $" << save5(pv, ir) << endl;
float fv;
save6(fv, pv, ir, nC);
cout << "Savings Function 6 = $" << fv << endl;
save7 ()
//Exit Program
return 0;
}
//Function for Future Value Calculation
//inputs
// p -> Present Value $'s
// i -> Interest Rate % / Compounding Period
// n -> Compounding Period yr's
//output
// fv -> Future Value $'s
float save1(float p, float i, int n);
{
return p * pow((1 + i), n);
}
float save2(float p, float i, int n);
{
return p * pow((1 + i), n);
}
float save3(float p, float i, int n);
{
return p * pow((1 + i), n);
}
float save4(float p, float i, int n);
{
return p * pow((1 + i), n);
}
float save5(float p, float i, int n);
{
return p * pow((1 + i), n);
}
float save6(float p, float i, int n)
{
if(n <= 0)
{
return p; //1st return
}
return save4(p, i, n - 1) * (1 + i); //2nd Return
}
float save6(float %f, floatp, ) | 30.25 | 79 | 0.494596 | salazaru |
ae756d793d630e0f6314299c9ae32ba2b36cef73 | 2,297 | hpp | C++ | src/geometryhandler.hpp | pannacotta98/DomeDagen | aa5ac6adbc73326e43dfa129eae11c95f7191a1d | [
"BSD-2-Clause"
] | null | null | null | src/geometryhandler.hpp | pannacotta98/DomeDagen | aa5ac6adbc73326e43dfa129eae11c95f7191a1d | [
"BSD-2-Clause"
] | null | null | null | src/geometryhandler.hpp | pannacotta98/DomeDagen | aa5ac6adbc73326e43dfa129eae11c95f7191a1d | [
"BSD-2-Clause"
] | null | null | null | #pragma once
#include "modelmanager.hpp"
//This class is privately inherited to classes needing models and accompanied functionality
//This class is also very unorganized
class GeometryHandler
{
public:
GeometryHandler(const std::string& shaderProgramName, const std::string& objectModelName)
:mShaderProgram{ sgct::ShaderManager::instance().shaderProgram(shaderProgramName) },
mModel{ &ModelManager::instance().getModel(objectModelName) },
mModelSlot{ ModelManager::instance().findModelSpot(objectModelName)} {}
GeometryHandler(const GeometryHandler&) = default;
GeometryHandler(GeometryHandler&&) = default;
GeometryHandler& operator=(const GeometryHandler&) = delete;
GeometryHandler& operator=(GeometryHandler&& src) noexcept
{
std::swap(mTransMatrixLoc, src.mTransMatrixLoc);
std::swap(mMvpMatrixLoc, src.mMvpMatrixLoc);
std::swap(mModel, src.mModel);
std::swap(mModelSlot, src.mModelSlot);
return *this;
}
//Do not remove mModel as this removes the model for all objects
~GeometryHandler() { mModel = nullptr; }
//Get model pointer index
int getModelPointerIndex(){return mModelSlot;}
//Set new model from slot index in ModelManager
void setModelFromInt(const int index)
{mModel = &ModelManager::instance().getModel(index);}
//Shader matrix locations
GLint mTransMatrixLoc = -1;
GLint mMvpMatrixLoc = -1;
GLint mViewMatrixLoc = -1;
GLint mNormalMatrixLoc = -1;
GLint mCameraPosLoc = -1;
//Reference to shader in shader pool
const sgct::ShaderProgram& mShaderProgram;
const sgct::ShaderProgram& getShader() { return mShaderProgram; }
//POINTER to model in model pool (references are not swappable)
//Needs to be swappable for collectible pooling
Model* mModel;
int mModelSlot = -1;
//Render geometry and texture
void renderModel() const { mModel->render(); };
//Set shader data
void setShaderData()
{
mShaderProgram.bind();
mMvpMatrixLoc = glGetUniformLocation(mShaderProgram.id(), "mvp");
mTransMatrixLoc = glGetUniformLocation(mShaderProgram.id(), "transformation");
mViewMatrixLoc = glGetUniformLocation(mShaderProgram.id(), "view");
mCameraPosLoc = glGetUniformLocation(mShaderProgram.id(), "cameraPos");
mNormalMatrixLoc = glGetUniformLocation(mShaderProgram.id(), "normalMatrix");
mShaderProgram.unbind();
}
}; | 33.779412 | 91 | 0.760993 | pannacotta98 |
ae77f859778c1b360c7129fafbae886e03e4078c | 620 | hpp | C++ | include/lol/def/LolPerksPerkSettingResource.hpp | Maufeat/LeagueAPI | be7cb5093aab3f27d95b3c0e1d5700aa50126c47 | [
"BSD-3-Clause"
] | 1 | 2020-07-22T11:14:55.000Z | 2020-07-22T11:14:55.000Z | include/lol/def/LolPerksPerkSettingResource.hpp | Maufeat/LeagueAPI | be7cb5093aab3f27d95b3c0e1d5700aa50126c47 | [
"BSD-3-Clause"
] | null | null | null | include/lol/def/LolPerksPerkSettingResource.hpp | Maufeat/LeagueAPI | be7cb5093aab3f27d95b3c0e1d5700aa50126c47 | [
"BSD-3-Clause"
] | 4 | 2018-12-01T22:48:21.000Z | 2020-07-22T11:14:56.000Z | #pragma once
#include "../base_def.hpp"
namespace lol {
struct LolPerksPerkSettingResource {
std::vector<int32_t> perkIds;
int32_t perkStyle;
int32_t perkSubStyle;
};
inline void to_json(json& j, const LolPerksPerkSettingResource& v) {
j["perkIds"] = v.perkIds;
j["perkStyle"] = v.perkStyle;
j["perkSubStyle"] = v.perkSubStyle;
}
inline void from_json(const json& j, LolPerksPerkSettingResource& v) {
v.perkIds = j.at("perkIds").get<std::vector<int32_t>>();
v.perkStyle = j.at("perkStyle").get<int32_t>();
v.perkSubStyle = j.at("perkSubStyle").get<int32_t>();
}
} | 32.631579 | 72 | 0.664516 | Maufeat |
ae799ce6bc16b48d7fc7ec7e33cd764f247c3cdd | 1,191 | hpp | C++ | include/all_rounder.hpp | tomdodd4598/UCL-PHAS0100-CandamirTilesExample1 | 8a324462d93db49a6a2c88fb382bca110c7ec611 | [
"MIT"
] | null | null | null | include/all_rounder.hpp | tomdodd4598/UCL-PHAS0100-CandamirTilesExample1 | 8a324462d93db49a6a2c88fb382bca110c7ec611 | [
"MIT"
] | null | null | null | include/all_rounder.hpp | tomdodd4598/UCL-PHAS0100-CandamirTilesExample1 | 8a324462d93db49a6a2c88fb382bca110c7ec611 | [
"MIT"
] | null | null | null | #ifndef ALL_ROUNDER_H
#define ALL_ROUNDER_H
#include "cricketer.hpp"
#include <string>
#include <utility>
namespace cricket {
class AllRounder : public Cricketer {
public:
template<typename NAME, typename... EQUIPMENT>
AllRounder(NAME&& name, int batting_runs, int batting_balls, int dismissals, int bowling_runs, int bowling_balls, int wickets, EQUIPMENT&&... equipment)
: Cricketer(std::forward<NAME>(name), std::forward<EQUIPMENT>(equipment)...)
, batting_runs{batting_runs}
, batting_balls{batting_balls}
, dismissals{dismissals}
, bowling_runs{bowling_runs}
, bowling_balls{bowling_balls}
, wickets{wickets}
{}
double get_batting_average() const;
double get_batting_strike_rate() const;
double get_bowling_average() const;
double get_bowling_strike_rate() const;
double get_bowling_economy_rate() const;
virtual std::string to_string() const;
int batting_runs;
int batting_balls;
int dismissals;
int bowling_runs;
int bowling_balls;
int wickets;
};
}
#endif
| 25.891304 | 160 | 0.643157 | tomdodd4598 |
ae7c7a21e5dc5122acab986da6f246109fa47696 | 5,339 | hpp | C++ | src/mge/core/stacktrace.hpp | mge-engine/mge | e7a6253f99dd640a655d9a80b94118d35c7d8139 | [
"MIT"
] | null | null | null | src/mge/core/stacktrace.hpp | mge-engine/mge | e7a6253f99dd640a655d9a80b94118d35c7d8139 | [
"MIT"
] | 91 | 2019-03-09T11:31:29.000Z | 2022-02-27T13:06:06.000Z | src/mge/core/stacktrace.hpp | mge-engine/mge | e7a6253f99dd640a655d9a80b94118d35c7d8139 | [
"MIT"
] | null | null | null | // mge - Modern Game Engine
// Copyright (c) 2021 by Alexander Schroeder
// All rights reserved.
/** @file */
#pragma once
#include "mge/core/dllexport.hpp"
#include "mge/core/string_pool.hpp"
#include <string>
#include <string_view>
#include <vector>
namespace mge {
/**
* @brief A stack backtrace.
*
*/
class MGECORE_EXPORT stacktrace
{
public:
/**
* @brief A frame on the stack backtrace.
*/
class MGECORE_EXPORT frame
{
public:
/**
* @brief Construct a new frame object
*
* @param address address (program counter)
* @param module module name (executable/shared library)
* @param name name of frame (function)
* @param file source code file
* @param line source code line
*/
frame(const void* address,
std::string_view module,
std::string_view name,
std::string_view file,
uint32_t line);
/**
* @brief Copy constructor.
* @param f copied frame
*/
frame(const frame& f) = default;
~frame() = default;
/**
* @brief Assignment.
*
* @return f assigned frame
*/
frame& operator=(const frame& f) = default;
/**
* @brief Get frame address.
*
* @return frame address
*/
const void* address() const noexcept { return m_address; }
/**
* @brief Frame name (method or function name)
*
* @return method or function name
*/
std::string_view name() const noexcept { return m_name; }
/**
* @brief Source file name.
*
* @return source file name
*/
std::string_view source_file() const noexcept
{
return m_source_file;
}
/**
* @brief Source line number.
*
* @return source line number
*/
uint32_t source_line() const noexcept { return m_source_line; }
/**
* @brief Module name (executable or library)
*
* @return module name
*/
std::string_view module() const noexcept { return m_module; }
private:
const void* m_address;
std::string_view m_name;
std::string_view m_source_file;
std::string_view m_module;
uint32_t m_source_line;
};
private:
using frame_vector = std::vector<frame>;
public:
/// stack trace size
using size_type = frame_vector::size_type;
/// iterator on frames
using const_iterator = frame_vector::const_iterator;
/// iterator on frames
using const_reverse_iterator = frame_vector::const_reverse_iterator;
/**
* @brief Construct stacktrace of current thread.
*/
stacktrace();
/**
* @brief Copy constructor.
*
* @param s copied stack trace
*/
stacktrace(const stacktrace& s);
/**
* @brief Destructor.
*
*/
~stacktrace() = default;
/**
* @brief Assignment
*
* @param s assigned stack trace
* @return @c *this
*/
stacktrace& operator=(const stacktrace& s);
/**
* @brief Number of frames.
*
* @return number of frames
*/
size_type size() const;
/**
* @brief Begin of frames.
*
* @return begin of frames
*/
const_iterator begin() const { return m_frames.begin(); }
/**
* @brief Reverse begin of frames.
*
* @return reverse begin of frames
*/
const_reverse_iterator rbegin() const { return m_frames.rbegin(); }
/**
* @brief End of frames.
*
* @return end of frames
*/
const_iterator end() const { return m_frames.end(); }
/**
* @brief Reverse end of frames.
*
* @return reverse end of frames
*/
const_iterator rend() const { return m_frames.end(); }
/**
* @brief Comparison.
*
* @param s compared stack trace
* @return true if adresses match
*/
bool operator==(const stacktrace& s) const;
/**
* @brief Comparison.
*
* @param s compared stack trace
* @return true if adresses do not match
*/
bool operator!=(const stacktrace& s) const;
private:
frame_vector m_frames;
string_pool m_strings;
};
/**
* @brief Dump stack into stream.
*
* @param os output stream
* @param s stack backtrace
* @return @c os
*/
MGECORE_EXPORT std::ostream& operator<<(std::ostream& os,
const stacktrace& s);
} // namespace mge | 27.101523 | 76 | 0.478929 | mge-engine |
ae7d69c4645db3634351dd9d3aa0bfa20558d263 | 1,637 | cpp | C++ | SPOJ/SAMER08F - Feynman.cpp | ravirathee/Competitive-Programming | 20a0bfda9f04ed186e2f475644e44f14f934b533 | [
"Unlicense"
] | 6 | 2018-11-26T02:38:07.000Z | 2021-07-28T00:16:41.000Z | SPOJ/SAMER08F - Feynman.cpp | ravirathee/Competitive-Programming | 20a0bfda9f04ed186e2f475644e44f14f934b533 | [
"Unlicense"
] | 1 | 2021-05-30T09:25:53.000Z | 2021-06-05T08:33:56.000Z | SPOJ/SAMER08F - Feynman.cpp | ravirathee/Competitive-Programming | 20a0bfda9f04ed186e2f475644e44f14f934b533 | [
"Unlicense"
] | 4 | 2020-04-16T07:15:01.000Z | 2020-12-04T06:26:07.000Z | /*SAMER08F - Feynman
no tags
Richard Phillips Feynman was a well known American physicist and a recipient of the Nobel Prize in Physics. He worked in theoretical physics and also pioneered the field of quantum computing. He visited South America for ten months, giving lectures and enjoying life in the tropics. He is also known for his books "Surely You're Joking, Mr. Feynman!" and "What Do You Care What Other People Think?", which include some of his adventures below the equator.
His life-long addiction was solving and making puzzles, locks, and cyphers. Recently, an old farmer in South America, who was a host to the young physicist in 1949, found some papers and notes that is believed to have belonged to Feynman. Among notes about mesons and electromagnetism, there was a napkin where he wrote a simple puzzle: "how many different squares are there in a grid of N ×N squares?".
In the same napkin there was a drawing which is reproduced below, showing that, for N=2, the answer is 5.
subir imagenes
Input
The input contains several test cases. Each test case is composed of a single line, containing only one integer N, representing the number of squares in each side of the grid (1 ≤ N ≤ 100).
The end of input is indicated by a line containing only one zero.
Output
For each test case in the input, your program must print a single line, containing the number of different squares for the corresponding input.
*/
#include <iostream>
inline int solve(int n)
{
return (2*n+1)*(n+1)*(n)/6;
}
int main()
{
for (int n; std::cin >> n && n != 0;)
std::cout << solve(n) << std::endl;
return 0;
}
| 46.771429 | 455 | 0.745877 | ravirathee |
ae7d979107a95215f0032033d14e3830184e3c4b | 1,802 | cpp | C++ | test/src/detail/offset_fetch_request_write_test.cpp | perchits/libkafka-asio | cbdced006d49a4498955a222915c6514b4ac57a7 | [
"MIT"
] | 77 | 2015-04-07T08:14:14.000Z | 2022-02-14T01:07:05.000Z | test/src/detail/offset_fetch_request_write_test.cpp | perchits/libkafka-asio | cbdced006d49a4498955a222915c6514b4ac57a7 | [
"MIT"
] | 28 | 2015-04-07T08:57:41.000Z | 2020-04-19T21:25:22.000Z | test/src/detail/offset_fetch_request_write_test.cpp | perchits/libkafka-asio | cbdced006d49a4498955a222915c6514b4ac57a7 | [
"MIT"
] | 48 | 2015-04-15T05:34:51.000Z | 2022-03-17T11:50:20.000Z | //
// detail/offset_fetch_request_write_test.cpp
// ------------------------------------------
//
// Copyright (c) 2015 Daniel Joos
//
// Distributed under MIT license. (See file LICENSE)
//
#include <gtest/gtest.h>
#include <libkafka_asio/libkafka_asio.h>
#include "StreamTest.h"
using libkafka_asio::OffsetFetchRequest;
class OffsetFetchRequestWriteTest :
public ::testing::Test,
public StreamTest
{
protected:
void SetUp()
{
ResetStream();
}
};
TEST_F(OffsetFetchRequestWriteTest, WriteRequestMessage)
{
OffsetFetchRequest request;
request.set_consumer_group("TestGroup");
request.FetchOffset("Topic1", 0);
request.FetchOffset("Topic1", 1);
request.FetchOffset("Topic2", 1);
libkafka_asio::detail::WriteRequestMessage(request, *stream);
using namespace libkafka_asio::detail;
ASSERT_STREQ("TestGroup", ReadString(*stream).c_str()); // ConsumerGroup
ASSERT_EQ(2, ReadInt32(*stream)); // Topic array size
ASSERT_STREQ("Topic1", ReadString(*stream).c_str()); // TopicName
ASSERT_EQ(2, ReadInt32(*stream)); // Partition array size
ASSERT_EQ(0, ReadInt32(*stream)); // Partition
ASSERT_EQ(1, ReadInt32(*stream)); // Partition
ASSERT_STREQ("Topic2", ReadString(*stream).c_str()); // TopicName
ASSERT_EQ(1, ReadInt32(*stream)); // Partition array size
ASSERT_EQ(1, ReadInt32(*stream)); // Partition
// Nothing else ...
ASSERT_EQ(0, streambuf->size());
}
TEST_F(OffsetFetchRequestWriteTest, WriteRequestMessage_Empty)
{
OffsetFetchRequest request;
libkafka_asio::detail::WriteRequestMessage(request, *stream);
using namespace libkafka_asio::detail;
ASSERT_STREQ("", ReadString(*stream).c_str()); // ConsumerGroup
ASSERT_EQ(0, ReadInt32(*stream)); // Topic array size
// Nothing else ...
ASSERT_EQ(0, streambuf->size());
}
| 28.15625 | 75 | 0.705882 | perchits |
ae7f91eead9906b48fc98847333f879acb97ad62 | 2,102 | cpp | C++ | src/er1controlapp.cpp | sfmabock/Evolution-Robot-1-Driver | 47cf3d54f2b863aea75abb181ae39f1eb5b83232 | [
"MIT"
] | null | null | null | src/er1controlapp.cpp | sfmabock/Evolution-Robot-1-Driver | 47cf3d54f2b863aea75abb181ae39f1eb5b83232 | [
"MIT"
] | null | null | null | src/er1controlapp.cpp | sfmabock/Evolution-Robot-1-Driver | 47cf3d54f2b863aea75abb181ae39f1eb5b83232 | [
"MIT"
] | null | null | null |
#include <iostream>
#include <string>
#include <SDL2/SDL.h>
#include <er1driver/er1driver.hpp>
int main(int argc, char** argv) {
SDL_Event event;
bool done = false;
if (SDL_Init(SDL_INIT_VIDEO)!= 0) {
return -1;
}
SDL_Window *window;
window = SDL_CreateWindow(
"An SDL2 window",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
640,
480,
SDL_WINDOW_OPENGL
);
er1driver::SimpleER1Interface er1;
er1.connect("/dev/serial/by-id/usb-Evolution_Robot_ER1_Control_Module_v1.0_ER1TQEG3-if00-port0");
int currentDown = 0;
while (!done) {
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_KEYDOWN: {
auto code = event.key.keysym.sym;
if (code == SDLK_UP && currentDown != SDLK_UP) {
currentDown = code;
er1.move(er1driver::Direction::Forward);
} else if (code == SDLK_DOWN && currentDown != SDLK_DOWN) {
currentDown = code;
er1.move(er1driver::Direction::Forward);
} else if (code == SDLK_LEFT && currentDown != SDLK_LEFT) {
currentDown = code;
er1.turn(er1driver::Orientation::Left);
} else if (code == SDLK_RIGHT && currentDown != SDLK_RIGHT){
currentDown = code;
er1.turn(er1driver::Orientation::Right);
}
break;
}
case SDL_KEYUP:
auto code = event.key.keysym.sym;
if (code == SDLK_q) {
done = true;
} else if (code == currentDown) {
er1.stop();
}
currentDown = 0;
break;
}
}
}
er1.disconnect();
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
| 28.405405 | 101 | 0.466698 | sfmabock |
ae81ca480c3a78888683d1ea42c464fd35699e3d | 6,376 | cpp | C++ | src/view/configurator.cpp | TiWinDeTea/NinjaClown | fdd48e62466f11036fa0360fad2bcb182d6d3352 | [
"MIT"
] | 2 | 2020-04-10T14:39:00.000Z | 2021-02-11T15:52:16.000Z | src/view/configurator.cpp | TiWinDeTea/NinjaClown | fdd48e62466f11036fa0360fad2bcb182d6d3352 | [
"MIT"
] | 2 | 2019-12-17T08:50:20.000Z | 2020-02-03T09:37:56.000Z | src/view/configurator.cpp | TiWinDeTea/NinjaClown | fdd48e62466f11036fa0360fad2bcb182d6d3352 | [
"MIT"
] | 1 | 2020-08-19T03:06:52.000Z | 2020-08-19T03:06:52.000Z | #include <imgui.h>
#include "utils/resource_manager.hpp"
#include "view/configurator.hpp"
#include "view/imgui_styles.hpp"
// TODO : rendre la classe configurator statique (pas vraiment besoin de l’instancier plusieurs fois)
using lang_info = std::remove_const_t<std::remove_reference_t<
std::invoke_result<decltype(&utils::resource_manager::get_language_list), utils::resource_manager>::type>>::value_type;
namespace {
namespace idx {
enum idx {
general_lang,
command_lang,
gui_lang,
log_lang,
resource_pack,
MAX,
};
}
constexpr const char window_name[] = "##configurator";
std::string display_name(const utils::resource_manager::resource_pack_info &resource_pack, const lang_info &user_lang) {
if (auto it = resource_pack.names_by_shorthand_lang.find(user_lang.map_name); it != resource_pack.names_by_shorthand_lang.end()) {
return it->second;
}
return resource_pack.default_name;
}
std::string display_name(const lang_info &lang) {
std::string ans = lang.name;
if (!lang.shorthand.empty()) {
ans += " (" + lang.variant + ")";
}
return ans;
}
template <typename T>
const T *combo(std::string_view label, const std::vector<T> &choices, const lang_info ¤t_lang, float label_width, float combo_width) {
// int idx = static_cast<int>(std::distance(langs.begin(), std::find(langs.begin(), langs.end(), current_lang)));
const T *selected = nullptr;
ImGui::TextUnformatted(label.data(), label.data() + label.size());
ImGui::SameLine(label_width);
ImGui::PushID(label.data(), label.data() + label.size());
ImGui::SetNextItemWidth(combo_width);
if (ImGui::BeginCombo("##lang_combo", display_name(current_lang).c_str(), ImGuiComboFlags_NoArrowButton)) {
for (const T ¤t : choices) {
bool is_selected = (current == current_lang);
if (ImGui::Selectable(display_name(current).c_str(), is_selected)) {
selected = ¤t;
}
if (is_selected) {
ImGui::SetItemDefaultFocus();
}
}
ImGui::EndCombo();
}
ImGui::PopID();
return selected;
}
} // namespace
void view::configurator::give_control() noexcept {
m_graphics_changed = false;
if (!m_showing) {
if (m_popup_open) {
if (ImGui::BeginPopupModal(window_name, nullptr, ImGuiWindowFlags_NoTitleBar)) {
ImGui::CloseCurrentPopup();
ImGui::EndPopup();
m_popup_open = false;
}
if (m_config_must_be_saved) {
m_resources.save_user_config();
m_config_must_be_saved = false;
}
}
return;
}
if (!m_popup_open) {
ImGui::OpenPopup(window_name);
m_popup_open = true;
m_resources.refresh_language_list();
m_resources.refresh_resource_pack_list();
}
if (!ImGui::BeginPopupModal(window_name, nullptr,
ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize)) {
m_popup_open = false;
m_showing = false;
return;
}
const ImGuiStyle &style = ImGui::GetStyle();
std::array<std::string_view, idx::MAX> labels;
labels[idx::general_lang] = m_resources.gui_text_for("configurator.general_lang");
labels[idx::command_lang] = m_resources.gui_text_for("configurator.command_lang");
labels[idx::gui_lang] = m_resources.gui_text_for("configurator.gui_lang");
labels[idx::log_lang] = m_resources.gui_text_for("configurator.log_lang");
labels[idx::resource_pack] = m_resources.gui_text_for("configurator.resource_pack");
float labels_width{0};
for (const std::string_view str : labels) {
labels_width = std::max(ImGui::CalcTextSize(str.data(), str.data() + str.size()).x, labels_width);
}
labels_width += style.ItemSpacing.x;
// langs
{
const auto &langs = m_resources.get_language_list();
float combo_width{0};
for (const auto &lang : langs) {
combo_width = std::max(ImGui::CalcTextSize(display_name(lang).c_str()).x, combo_width);
}
combo_width += style.ItemInnerSpacing.x;
const lang_info *selection = nullptr;
if (selection = combo(labels[idx::general_lang], langs, m_resources.user_general_lang(), labels_width, combo_width);
selection != nullptr) {
m_resources.set_user_general_lang(*selection);
m_config_must_be_saved = true;
}
if (selection = combo(labels[idx::command_lang], langs, m_resources.user_commands_lang(), labels_width, combo_width);
selection != nullptr) {
m_resources.set_user_command_lang(*selection);
m_config_must_be_saved = true;
}
if (selection = combo(labels[idx::gui_lang], langs, m_resources.user_gui_lang(), labels_width, combo_width); selection != nullptr) {
m_resources.set_user_gui_lang(*selection);
m_config_must_be_saved = true;
}
if (selection = combo(labels[idx::log_lang], langs, m_resources.user_log_lang(), labels_width, combo_width); selection != nullptr) {
m_resources.set_user_log_lang(*selection);
m_config_must_be_saved = true;
}
std::string_view import_lang = m_resources.gui_text_for("configurator.import_lang");
using_style(disabled_button) {
if (ImGui::Button(import_lang.data(), {ImGui::GetContentRegionAvail().x, 0})) {
}
};
}
ImGui::Separator();
// resource pack
{
const std::vector<utils::resource_manager::resource_pack_info> &resource_packs = m_resources.get_resource_pack_list();
ImGui::TextUnformatted(labels[idx::resource_pack].data(), labels[idx::resource_pack].data() + labels[idx::resource_pack].size());
ImGui::SameLine(labels_width);
ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x);
if (ImGui::BeginCombo("##configurator.resource_pack",
display_name(m_resources.user_resource_pack(), m_resources.user_gui_lang()).c_str(),
ImGuiComboFlags_NoArrowButton)) {
for (const auto &res_pack : resource_packs) {
bool is_selected = (res_pack.file == m_resources.user_gui_lang().file);
if (ImGui::Selectable(display_name(res_pack, m_resources.user_gui_lang()).c_str(), is_selected)) {
m_resources.set_user_resource_pack(res_pack);
m_graphics_changed = true;
}
if (is_selected) {
ImGui::SetItemDefaultFocus();
}
}
ImGui::EndCombo();
}
std::string_view import_respack = m_resources.gui_text_for("configurator.import_respack");
using_style(disabled_button) {
if (ImGui::Button(import_respack.data(), {ImGui::GetContentRegionAvail().x, 0})) {
}
};
}
ImGui::EndPopup();
// TODO: bouton pour quitter le menu de configuration
} | 33.557895 | 140 | 0.715809 | TiWinDeTea |
ae84c70c639cb1814285852d0def8c2ee088ce16 | 211,852 | cpp | C++ | packages/data/epdl/test/tstPhotonDataProcessorShellMap.cpp | lkersting/SCR-2123 | 06ae3d92998664a520dc6a271809a5aeffe18f72 | [
"BSD-3-Clause"
] | null | null | null | packages/data/epdl/test/tstPhotonDataProcessorShellMap.cpp | lkersting/SCR-2123 | 06ae3d92998664a520dc6a271809a5aeffe18f72 | [
"BSD-3-Clause"
] | null | null | null | packages/data/epdl/test/tstPhotonDataProcessorShellMap.cpp | lkersting/SCR-2123 | 06ae3d92998664a520dc6a271809a5aeffe18f72 | [
"BSD-3-Clause"
] | null | null | null | //---------------------------------------------------------------------------//
//!
//! \file tstPhotonDataProcessorShellMap.cpp
//! \author Alex Robinson
//! \brief PhotonDataProcessor class electron shell map unit tests.
//!
//---------------------------------------------------------------------------//
// Std Lib Includes
#include <iostream>
// Trilinos Includes
#include <Teuchos_UnitTestHarness.hpp>
#include <Teuchos_Array.hpp>
#include <Teuchos_TwoDArray.hpp>
// FRENSIE Includes
#include "Data_PhotonDataProcessor.hpp"
#include "Utility_UnitTestHarnessExtensions.hpp"
#include "Utility_HDF5FileHandler.hpp"
#include "Utility_Tuple.hpp"
#include "HDF5DataFileNames.hpp"
//---------------------------------------------------------------------------//
// Test File Names.
//---------------------------------------------------------------------------//
std::string epdl_test_file;
std::string eadl_test_file;
std::string compton_test_file_prefix;
//---------------------------------------------------------------------------//
// Testing Structs.
//---------------------------------------------------------------------------//
class TestingPhotonDataProcessor : public Data::PhotonDataProcessor
{
public:
TestingPhotonDataProcessor( const std::string epdl_file_name,
const std::string eadl_file_name,
const std::string compton_file_prefix,
const std::string output_directory )
: Data::PhotonDataProcessor( epdl_file_name,
eadl_file_name,
compton_file_prefix,
output_directory )
{ /* ... */ }
virtual ~TestingPhotonDataProcessor()
{ /* ... */ }
using Data::PhotonDataProcessor::createShellIndexMap;
};
//---------------------------------------------------------------------------//
// Tests.
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=1
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_1 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix,
"" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 1,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=2
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_2 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 2,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=3
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_3 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 3,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=4
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_4 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 4,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=5
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_5 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 5,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 2;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=6
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_6 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 6,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 2;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=7
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_7 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 7,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 2;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=8
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_8 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 8,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 2;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=9
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_9 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 9,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 2;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=10
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_10 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 10,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 2;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=11
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_11 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 11,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 3;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=12
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_12 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 12,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 3;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=13
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_13 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 13,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 4;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=14
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_14 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 14,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 4;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=15
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_15 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 15,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 4;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=16
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_16 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 16,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 4;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=17
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_17 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 17,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 4;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=18
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_18 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 18,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 4;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=19
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_19 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 19,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 5;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=20
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_20 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 20,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 5;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=21
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_21 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 21,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 6;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=22
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_22 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 22,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 6;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=23
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_23 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 23,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 6;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=24
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_24 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 24,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 6;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=25
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_25 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 25,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 6;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=26
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_26 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 26,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 6;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=27
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_27 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 27,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 6;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=28
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_28 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 28,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 6;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=29
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_29 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 29,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 6;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=30
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_30 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 30,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 6;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=31
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_31 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 31,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 7;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=32
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_32 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 32,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 7;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=34
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_34 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 34,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 7;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=35
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_35 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 35,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 7;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=36
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_36 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 36,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=37
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_37 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 37,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 12;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=38
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_38 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 38,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 12;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=39
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_39 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 39,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 13;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=40
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_40 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 40,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 13;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=41
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_41 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 41,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 13;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=42
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_42 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 42,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 14;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=43
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_43 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 43,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 14;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=44
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_44 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 44,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 14;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=45
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_45 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 45,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 14;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=46
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_46 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 46,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=47
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_47 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 47,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 14;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=48
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_48 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 48,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 14;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=49
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_49 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 49,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 29;
data_point.second = 15;
map_true.push_back( data_point );
data_point.first = 30;
data_point.second = 15;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=50
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_50 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 50,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 29;
data_point.second = 15;
map_true.push_back( data_point );
data_point.first = 30;
data_point.second = 15;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=51
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_51 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 51,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 29;
data_point.second = 15;
map_true.push_back( data_point );
data_point.first = 30;
data_point.second = 16;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=52
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_52 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 52,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 29;
data_point.second = 15;
map_true.push_back( data_point );
data_point.first = 30;
data_point.second = 16;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=53
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_53 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 53,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 29;
data_point.second = 15;
map_true.push_back( data_point );
data_point.first = 30;
data_point.second = 16;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=54
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_54 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 54,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 29;
data_point.second = 15;
map_true.push_back( data_point );
data_point.first = 30;
data_point.second = 16;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=55
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_55 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 55,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 29;
data_point.second = 15;
map_true.push_back( data_point );
data_point.first = 30;
data_point.second = 16;
map_true.push_back( data_point );
data_point.first = 41;
data_point.second = 17;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=56
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_56 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 56,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 29;
data_point.second = 15;
map_true.push_back( data_point );
data_point.first = 30;
data_point.second = 16;
map_true.push_back( data_point );
data_point.first = 41;
data_point.second = 17;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=57
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_57 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 57,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 29;
data_point.second = 15;
map_true.push_back( data_point );
data_point.first = 30;
data_point.second = 16;
map_true.push_back( data_point );
data_point.first = 32;
data_point.second = 17;
map_true.push_back( data_point );
data_point.first = 33;
data_point.second = 17;
map_true.push_back( data_point );
data_point.first = 41;
data_point.second = 18;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=58
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_58 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 58,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 24;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 25;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 15;
map_true.push_back( data_point );
data_point.first = 29;
data_point.second = 16;
map_true.push_back( data_point );
data_point.first = 30;
data_point.second = 17;
map_true.push_back( data_point );
data_point.first = 41;
data_point.second = 19;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=59
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_59 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 59,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 24;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 25;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 15;
map_true.push_back( data_point );
data_point.first = 29;
data_point.second = 16;
map_true.push_back( data_point );
data_point.first = 30;
data_point.second = 17;
map_true.push_back( data_point );
data_point.first = 41;
data_point.second = 18;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=60
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_60 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 60,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 24;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 25;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 15;
map_true.push_back( data_point );
data_point.first = 29;
data_point.second = 16;
map_true.push_back( data_point );
data_point.first = 30;
data_point.second = 17;
map_true.push_back( data_point );
data_point.first = 41;
data_point.second = 18;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=61
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_61 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 61,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 24;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 25;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 15;
map_true.push_back( data_point );
data_point.first = 29;
data_point.second = 16;
map_true.push_back( data_point );
data_point.first = 30;
data_point.second = 17;
map_true.push_back( data_point );
data_point.first = 41;
data_point.second = 18;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=62
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_62 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 62,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 24;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 25;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 15;
map_true.push_back( data_point );
data_point.first = 29;
data_point.second = 16;
map_true.push_back( data_point );
data_point.first = 30;
data_point.second = 17;
map_true.push_back( data_point );
data_point.first = 41;
data_point.second = 18;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=63
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_63 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 63,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 24;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 25;
data_point.second = 15;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 16;
map_true.push_back( data_point );
data_point.first = 29;
data_point.second = 17;
map_true.push_back( data_point );
data_point.first = 30;
data_point.second = 18;
map_true.push_back( data_point );
data_point.first = 41;
data_point.second = 19;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=64
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_64 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 64,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 24;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 25;
data_point.second = 15;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 16;
map_true.push_back( data_point );
data_point.first = 29;
data_point.second = 17;
map_true.push_back( data_point );
data_point.first = 30;
data_point.second = 18;
map_true.push_back( data_point );
data_point.first = 32;
data_point.second = 19;
map_true.push_back( data_point );
data_point.first = 33;
data_point.second = 19;
map_true.push_back( data_point );
data_point.first = 41;
data_point.second = 20;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=65
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_65 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 65,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 24;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 25;
data_point.second = 15;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 16;
map_true.push_back( data_point );
data_point.first = 29;
data_point.second = 17;
map_true.push_back( data_point );
data_point.first = 30;
data_point.second = 18;
map_true.push_back( data_point );
data_point.first = 41;
data_point.second = 19;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=66
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_66 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 66,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 24;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 25;
data_point.second = 15;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 16;
map_true.push_back( data_point );
data_point.first = 29;
data_point.second = 17;
map_true.push_back( data_point );
data_point.first = 30;
data_point.second = 18;
map_true.push_back( data_point );
data_point.first = 41;
data_point.second = 19;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=67
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_67 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 67,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 24;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 25;
data_point.second = 15;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 16;
map_true.push_back( data_point );
data_point.first = 29;
data_point.second = 17;
map_true.push_back( data_point );
data_point.first = 30;
data_point.second = 18;
map_true.push_back( data_point );
data_point.first = 41;
data_point.second = 19;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=68
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_68 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 68,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 24;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 25;
data_point.second = 15;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 16;
map_true.push_back( data_point );
data_point.first = 29;
data_point.second = 17;
map_true.push_back( data_point );
data_point.first = 30;
data_point.second = 18;
map_true.push_back( data_point );
data_point.first = 41;
data_point.second = 19;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=69
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_69 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 69,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 24;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 25;
data_point.second = 15;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 16;
map_true.push_back( data_point );
data_point.first = 29;
data_point.second = 17;
map_true.push_back( data_point );
data_point.first = 30;
data_point.second = 18;
map_true.push_back( data_point );
data_point.first = 41;
data_point.second = 19;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=70
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_70 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 70,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 24;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 25;
data_point.second = 15;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 16;
map_true.push_back( data_point );
data_point.first = 29;
data_point.second = 17;
map_true.push_back( data_point );
data_point.first = 30;
data_point.second = 18;
map_true.push_back( data_point );
data_point.first = 41;
data_point.second = 19;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=71
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_71 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 71,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 24;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 25;
data_point.second = 15;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 16;
map_true.push_back( data_point );
data_point.first = 29;
data_point.second = 17;
map_true.push_back( data_point );
data_point.first = 30;
data_point.second = 18;
map_true.push_back( data_point );
data_point.first = 32;
data_point.second = 19;
map_true.push_back( data_point );
data_point.first = 33;
data_point.second = 19;
map_true.push_back( data_point );
data_point.first = 41;
data_point.second = 20;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=72
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_72 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 72,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 24;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 25;
data_point.second = 15;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 16;
map_true.push_back( data_point );
data_point.first = 29;
data_point.second = 17;
map_true.push_back( data_point );
data_point.first = 30;
data_point.second = 18;
map_true.push_back( data_point );
data_point.first = 32;
data_point.second = 19;
map_true.push_back( data_point );
data_point.first = 33;
data_point.second = 19;
map_true.push_back( data_point );
data_point.first = 41;
data_point.second = 20;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=73
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_73 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 73,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 24;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 25;
data_point.second = 15;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 16;
map_true.push_back( data_point );
data_point.first = 29;
data_point.second = 17;
map_true.push_back( data_point );
data_point.first = 30;
data_point.second = 18;
map_true.push_back( data_point );
data_point.first = 32;
data_point.second = 19;
map_true.push_back( data_point );
data_point.first = 33;
data_point.second = 19;
map_true.push_back( data_point );
data_point.first = 41;
data_point.second = 20;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=74
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_74 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 74,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 24;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 25;
data_point.second = 15;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 16;
map_true.push_back( data_point );
data_point.first = 29;
data_point.second = 17;
map_true.push_back( data_point );
data_point.first = 30;
data_point.second = 18;
map_true.push_back( data_point );
data_point.first = 32;
data_point.second = 19;
map_true.push_back( data_point );
data_point.first = 33;
data_point.second = 19;
map_true.push_back( data_point );
data_point.first = 41;
data_point.second = 20;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=75
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_75 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 75,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 24;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 25;
data_point.second = 15;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 16;
map_true.push_back( data_point );
data_point.first = 29;
data_point.second = 17;
map_true.push_back( data_point );
data_point.first = 30;
data_point.second = 18;
map_true.push_back( data_point );
data_point.first = 32;
data_point.second = 19;
map_true.push_back( data_point );
data_point.first = 33;
data_point.second = 20;
map_true.push_back( data_point );
data_point.first = 41;
data_point.second = 21;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=76
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_76 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 76,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 24;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 25;
data_point.second = 15;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 16;
map_true.push_back( data_point );
data_point.first = 29;
data_point.second = 17;
map_true.push_back( data_point );
data_point.first = 30;
data_point.second = 18;
map_true.push_back( data_point );
data_point.first = 32;
data_point.second = 19;
map_true.push_back( data_point );
data_point.first = 33;
data_point.second = 20;
map_true.push_back( data_point );
data_point.first = 41;
data_point.second = 21;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=77
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_77 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 77,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 24;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 25;
data_point.second = 15;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 16;
map_true.push_back( data_point );
data_point.first = 29;
data_point.second = 17;
map_true.push_back( data_point );
data_point.first = 30;
data_point.second = 18;
map_true.push_back( data_point );
data_point.first = 32;
data_point.second = 19;
map_true.push_back( data_point );
data_point.first = 33;
data_point.second = 20;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=78
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_78 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 78,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 24;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 25;
data_point.second = 15;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 16;
map_true.push_back( data_point );
data_point.first = 29;
data_point.second = 17;
map_true.push_back( data_point );
data_point.first = 30;
data_point.second = 18;
map_true.push_back( data_point );
data_point.first = 32;
data_point.second = 19;
map_true.push_back( data_point );
data_point.first = 33;
data_point.second = 20;
map_true.push_back( data_point );
data_point.first = 41;
data_point.second = 21;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=79
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_79 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 79,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 24;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 25;
data_point.second = 15;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 16;
map_true.push_back( data_point );
data_point.first = 29;
data_point.second = 17;
map_true.push_back( data_point );
data_point.first = 30;
data_point.second = 18;
map_true.push_back( data_point );
data_point.first = 32;
data_point.second = 19;
map_true.push_back( data_point );
data_point.first = 33;
data_point.second = 20;
map_true.push_back( data_point );
data_point.first = 41;
data_point.second = 21;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=80
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_80 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 80,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 24;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 25;
data_point.second = 15;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 16;
map_true.push_back( data_point );
data_point.first = 29;
data_point.second = 17;
map_true.push_back( data_point );
data_point.first = 30;
data_point.second = 18;
map_true.push_back( data_point );
data_point.first = 32;
data_point.second = 19;
map_true.push_back( data_point );
data_point.first = 33;
data_point.second = 20;
map_true.push_back( data_point );
data_point.first = 41;
data_point.second = 21;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=81
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_81 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 81,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 24;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 25;
data_point.second = 15;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 16;
map_true.push_back( data_point );
data_point.first = 29;
data_point.second = 17;
map_true.push_back( data_point );
data_point.first = 30;
data_point.second = 18;
map_true.push_back( data_point );
data_point.first = 32;
data_point.second = 19;
map_true.push_back( data_point );
data_point.first = 33;
data_point.second = 20;
map_true.push_back( data_point );
data_point.first = 41;
data_point.second = 21;
map_true.push_back( data_point );
data_point.first = 43;
data_point.second = 22;
map_true.push_back( data_point );
data_point.first = 44;
data_point.second = 22;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=82
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_82 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 82,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 24;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 25;
data_point.second = 15;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 16;
map_true.push_back( data_point );
data_point.first = 29;
data_point.second = 17;
map_true.push_back( data_point );
data_point.first = 30;
data_point.second = 18;
map_true.push_back( data_point );
data_point.first = 32;
data_point.second = 19;
map_true.push_back( data_point );
data_point.first = 33;
data_point.second = 20;
map_true.push_back( data_point );
data_point.first = 41;
data_point.second = 21;
map_true.push_back( data_point );
data_point.first = 43;
data_point.second = 22;
map_true.push_back( data_point );
data_point.first = 44;
data_point.second = 22;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=83
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_83 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 83,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 24;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 25;
data_point.second = 15;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 16;
map_true.push_back( data_point );
data_point.first = 29;
data_point.second = 17;
map_true.push_back( data_point );
data_point.first = 30;
data_point.second = 18;
map_true.push_back( data_point );
data_point.first = 32;
data_point.second = 19;
map_true.push_back( data_point );
data_point.first = 33;
data_point.second = 20;
map_true.push_back( data_point );
data_point.first = 41;
data_point.second = 21;
map_true.push_back( data_point );
data_point.first = 43;
data_point.second = 22;
map_true.push_back( data_point );
data_point.first = 44;
data_point.second = 23;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=84
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_84 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 84,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 24;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 25;
data_point.second = 15;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 16;
map_true.push_back( data_point );
data_point.first = 29;
data_point.second = 17;
map_true.push_back( data_point );
data_point.first = 30;
data_point.second = 18;
map_true.push_back( data_point );
data_point.first = 32;
data_point.second = 19;
map_true.push_back( data_point );
data_point.first = 33;
data_point.second = 20;
map_true.push_back( data_point );
data_point.first = 41;
data_point.second = 21;
map_true.push_back( data_point );
data_point.first = 43;
data_point.second = 22;
map_true.push_back( data_point );
data_point.first = 44;
data_point.second = 23;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=85
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_85 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 85,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 24;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 25;
data_point.second = 15;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 16;
map_true.push_back( data_point );
data_point.first = 29;
data_point.second = 17;
map_true.push_back( data_point );
data_point.first = 30;
data_point.second = 18;
map_true.push_back( data_point );
data_point.first = 32;
data_point.second = 19;
map_true.push_back( data_point );
data_point.first = 33;
data_point.second = 20;
map_true.push_back( data_point );
data_point.first = 41;
data_point.second = 21;
map_true.push_back( data_point );
data_point.first = 43;
data_point.second = 22;
map_true.push_back( data_point );
data_point.first = 44;
data_point.second = 23;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=86
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_86 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 86,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 24;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 25;
data_point.second = 15;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 16;
map_true.push_back( data_point );
data_point.first = 29;
data_point.second = 17;
map_true.push_back( data_point );
data_point.first = 30;
data_point.second = 18;
map_true.push_back( data_point );
data_point.first = 32;
data_point.second = 19;
map_true.push_back( data_point );
data_point.first = 33;
data_point.second = 20;
map_true.push_back( data_point );
data_point.first = 41;
data_point.second = 21;
map_true.push_back( data_point );
data_point.first = 43;
data_point.second = 22;
map_true.push_back( data_point );
data_point.first = 44;
data_point.second = 23;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=87
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_87 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 87,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 24;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 25;
data_point.second = 15;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 16;
map_true.push_back( data_point );
data_point.first = 29;
data_point.second = 17;
map_true.push_back( data_point );
data_point.first = 30;
data_point.second = 18;
map_true.push_back( data_point );
data_point.first = 32;
data_point.second = 19;
map_true.push_back( data_point );
data_point.first = 33;
data_point.second = 20;
map_true.push_back( data_point );
data_point.first = 41;
data_point.second = 21;
map_true.push_back( data_point );
data_point.first = 43;
data_point.second = 22;
map_true.push_back( data_point );
data_point.first = 44;
data_point.second = 23;
map_true.push_back( data_point );
data_point.first = 58;
data_point.second = 24;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=88
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_88 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 88,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 24;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 25;
data_point.second = 15;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 16;
map_true.push_back( data_point );
data_point.first = 29;
data_point.second = 17;
map_true.push_back( data_point );
data_point.first = 30;
data_point.second = 18;
map_true.push_back( data_point );
data_point.first = 32;
data_point.second = 19;
map_true.push_back( data_point );
data_point.first = 33;
data_point.second = 20;
map_true.push_back( data_point );
data_point.first = 41;
data_point.second = 21;
map_true.push_back( data_point );
data_point.first = 43;
data_point.second = 22;
map_true.push_back( data_point );
data_point.first = 44;
data_point.second = 23;
map_true.push_back( data_point );
data_point.first = 58;
data_point.second = 24;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=89
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_89 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 89,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 24;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 25;
data_point.second = 15;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 16;
map_true.push_back( data_point );
data_point.first = 29;
data_point.second = 17;
map_true.push_back( data_point );
data_point.first = 30;
data_point.second = 18;
map_true.push_back( data_point );
data_point.first = 32;
data_point.second = 19;
map_true.push_back( data_point );
data_point.first = 33;
data_point.second = 20;
map_true.push_back( data_point );
data_point.first = 41;
data_point.second = 21;
map_true.push_back( data_point );
data_point.first = 43;
data_point.second = 22;
map_true.push_back( data_point );
data_point.first = 44;
data_point.second = 23;
map_true.push_back( data_point );
data_point.first = 46;
data_point.second = 24;
map_true.push_back( data_point );
data_point.first = 47;
data_point.second = 24;
map_true.push_back( data_point );
data_point.first = 58;
data_point.second = 25;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=90
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_90 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 90,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 24;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 25;
data_point.second = 15;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 16;
map_true.push_back( data_point );
data_point.first = 29;
data_point.second = 17;
map_true.push_back( data_point );
data_point.first = 30;
data_point.second = 18;
map_true.push_back( data_point );
data_point.first = 32;
data_point.second = 19;
map_true.push_back( data_point );
data_point.first = 33;
data_point.second = 20;
map_true.push_back( data_point );
data_point.first = 41;
data_point.second = 21;
map_true.push_back( data_point );
data_point.first = 43;
data_point.second = 22;
map_true.push_back( data_point );
data_point.first = 44;
data_point.second = 23;
map_true.push_back( data_point );
data_point.first = 46;
data_point.second = 24;
map_true.push_back( data_point );
data_point.first = 47;
data_point.second = 24;
map_true.push_back( data_point );
data_point.first = 58;
data_point.second = 25;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=91
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_91 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 91,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 24;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 25;
data_point.second = 15;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 16;
map_true.push_back( data_point );
data_point.first = 29;
data_point.second = 17;
map_true.push_back( data_point );
data_point.first = 30;
data_point.second = 18;
map_true.push_back( data_point );
data_point.first = 32;
data_point.second = 19;
map_true.push_back( data_point );
data_point.first = 33;
data_point.second = 20;
map_true.push_back( data_point );
data_point.first = 35;
data_point.second = 21;
map_true.push_back( data_point );
data_point.first = 36;
data_point.second = 21;
map_true.push_back( data_point );
data_point.first = 41;
data_point.second = 22;
map_true.push_back( data_point );
data_point.first = 43;
data_point.second = 23;
map_true.push_back( data_point );
data_point.first = 44;
data_point.second = 24;
map_true.push_back( data_point );
data_point.first = 46;
data_point.second = 25;
map_true.push_back( data_point );
data_point.first = 47;
data_point.second = 25;
map_true.push_back( data_point );
data_point.first = 58;
data_point.second = 26;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=92
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_92 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 92,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 24;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 25;
data_point.second = 15;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 16;
map_true.push_back( data_point );
data_point.first = 29;
data_point.second = 17;
map_true.push_back( data_point );
data_point.first = 30;
data_point.second = 18;
map_true.push_back( data_point );
data_point.first = 32;
data_point.second = 19;
map_true.push_back( data_point );
data_point.first = 33;
data_point.second = 20;
map_true.push_back( data_point );
data_point.first = 35;
data_point.second = 21;
map_true.push_back( data_point );
data_point.first = 36;
data_point.second = 21;
map_true.push_back( data_point );
data_point.first = 41;
data_point.second = 22;
map_true.push_back( data_point );
data_point.first = 43;
data_point.second = 23;
map_true.push_back( data_point );
data_point.first = 44;
data_point.second = 24;
map_true.push_back( data_point );
data_point.first = 46;
data_point.second = 25;
map_true.push_back( data_point );
data_point.first = 47;
data_point.second = 25;
map_true.push_back( data_point );
data_point.first = 58;
data_point.second = 26;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=93
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_93 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 93,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 24;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 25;
data_point.second = 15;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 16;
map_true.push_back( data_point );
data_point.first = 29;
data_point.second = 17;
map_true.push_back( data_point );
data_point.first = 30;
data_point.second = 18;
map_true.push_back( data_point );
data_point.first = 32;
data_point.second = 19;
map_true.push_back( data_point );
data_point.first = 33;
data_point.second = 20;
map_true.push_back( data_point );
data_point.first = 35;
data_point.second = 21;
map_true.push_back( data_point );
data_point.first = 36;
data_point.second = 21;
map_true.push_back( data_point );
data_point.first = 41;
data_point.second = 22;
map_true.push_back( data_point );
data_point.first = 43;
data_point.second = 23;
map_true.push_back( data_point );
data_point.first = 44;
data_point.second = 24;
map_true.push_back( data_point );
data_point.first = 46;
data_point.second = 25;
map_true.push_back( data_point );
data_point.first = 47;
data_point.second = 25;
map_true.push_back( data_point );
data_point.first = 58;
data_point.second = 26;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=94
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_94 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 94,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 24;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 25;
data_point.second = 15;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 16;
map_true.push_back( data_point );
data_point.first = 29;
data_point.second = 17;
map_true.push_back( data_point );
data_point.first = 30;
data_point.second = 18;
map_true.push_back( data_point );
data_point.first = 32;
data_point.second = 19;
map_true.push_back( data_point );
data_point.first = 33;
data_point.second = 20;
map_true.push_back( data_point );
data_point.first = 35;
data_point.second = 21;
map_true.push_back( data_point );
data_point.first = 36;
data_point.second = 21;
map_true.push_back( data_point );
data_point.first = 41;
data_point.second = 22;
map_true.push_back( data_point );
data_point.first = 43;
data_point.second = 23;
map_true.push_back( data_point );
data_point.first = 44;
data_point.second = 24;
map_true.push_back( data_point );
data_point.first = 58;
data_point.second = 25;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=95
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_95 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 95,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 24;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 25;
data_point.second = 15;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 16;
map_true.push_back( data_point );
data_point.first = 29;
data_point.second = 17;
map_true.push_back( data_point );
data_point.first = 30;
data_point.second = 18;
map_true.push_back( data_point );
data_point.first = 32;
data_point.second = 19;
map_true.push_back( data_point );
data_point.first = 33;
data_point.second = 20;
map_true.push_back( data_point );
data_point.first = 35;
data_point.second = 21;
map_true.push_back( data_point );
data_point.first = 36;
data_point.second = 22;
map_true.push_back( data_point );
data_point.first = 41;
data_point.second = 23;
map_true.push_back( data_point );
data_point.first = 43;
data_point.second = 24;
map_true.push_back( data_point );
data_point.first = 44;
data_point.second = 25;
map_true.push_back( data_point );
data_point.first = 58;
data_point.second = 26;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=96
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_96 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 96,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 24;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 25;
data_point.second = 15;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 16;
map_true.push_back( data_point );
data_point.first = 29;
data_point.second = 17;
map_true.push_back( data_point );
data_point.first = 30;
data_point.second = 18;
map_true.push_back( data_point );
data_point.first = 32;
data_point.second = 19;
map_true.push_back( data_point );
data_point.first = 33;
data_point.second = 20;
map_true.push_back( data_point );
data_point.first = 35;
data_point.second = 21;
map_true.push_back( data_point );
data_point.first = 36;
data_point.second = 22;
map_true.push_back( data_point );
data_point.first = 41;
data_point.second = 23;
map_true.push_back( data_point );
data_point.first = 43;
data_point.second = 24;
map_true.push_back( data_point );
data_point.first = 44;
data_point.second = 25;
map_true.push_back( data_point );
data_point.first = 46;
data_point.second = 26;
map_true.push_back( data_point );
data_point.first = 47;
data_point.second = 26;
map_true.push_back( data_point );
data_point.first = 58;
data_point.second = 27;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=97
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_97 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 97,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 24;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 25;
data_point.second = 15;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 16;
map_true.push_back( data_point );
data_point.first = 29;
data_point.second = 17;
map_true.push_back( data_point );
data_point.first = 30;
data_point.second = 18;
map_true.push_back( data_point );
data_point.first = 32;
data_point.second = 19;
map_true.push_back( data_point );
data_point.first = 33;
data_point.second = 20;
map_true.push_back( data_point );
data_point.first = 35;
data_point.second = 21;
map_true.push_back( data_point );
data_point.first = 36;
data_point.second = 22;
map_true.push_back( data_point );
data_point.first = 41;
data_point.second = 23;
map_true.push_back( data_point );
data_point.first = 43;
data_point.second = 24;
map_true.push_back( data_point );
data_point.first = 44;
data_point.second = 25;
map_true.push_back( data_point );
data_point.first = 46;
data_point.second = 25;
map_true.push_back( data_point );
data_point.first = 47;
data_point.second = 25;
map_true.push_back( data_point );
data_point.first = 58;
data_point.second = 26;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=98
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_98 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 98,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 24;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 25;
data_point.second = 15;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 16;
map_true.push_back( data_point );
data_point.first = 29;
data_point.second = 17;
map_true.push_back( data_point );
data_point.first = 30;
data_point.second = 18;
map_true.push_back( data_point );
data_point.first = 32;
data_point.second = 19;
map_true.push_back( data_point );
data_point.first = 33;
data_point.second = 20;
map_true.push_back( data_point );
data_point.first = 35;
data_point.second = 21;
map_true.push_back( data_point );
data_point.first = 36;
data_point.second = 22;
map_true.push_back( data_point );
data_point.first = 41;
data_point.second = 23;
map_true.push_back( data_point );
data_point.first = 43;
data_point.second = 24;
map_true.push_back( data_point );
data_point.first = 44;
data_point.second = 25;
map_true.push_back( data_point );
data_point.first = 58;
data_point.second = 26;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=99
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_99 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 99,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 24;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 25;
data_point.second = 15;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 16;
map_true.push_back( data_point );
data_point.first = 29;
data_point.second = 17;
map_true.push_back( data_point );
data_point.first = 30;
data_point.second = 18;
map_true.push_back( data_point );
data_point.first = 32;
data_point.second = 19;
map_true.push_back( data_point );
data_point.first = 33;
data_point.second = 20;
map_true.push_back( data_point );
data_point.first = 35;
data_point.second = 21;
map_true.push_back( data_point );
data_point.first = 36;
data_point.second = 22;
map_true.push_back( data_point );
data_point.first = 41;
data_point.second = 23;
map_true.push_back( data_point );
data_point.first = 43;
data_point.second = 24;
map_true.push_back( data_point );
data_point.first = 44;
data_point.second = 25;
map_true.push_back( data_point );
data_point.first = 58;
data_point.second = 26;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// check that the PhotonDataProcessor can create the correct electron shell
// index map for Z=100
TEUCHOS_UNIT_TEST( PhotonDataProcessor, electron_shell_index_map_z_100 )
{
TestingPhotonDataProcessor photon_data_processor( epdl_test_file,
eadl_test_file,
compton_test_file_prefix, "" );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map;
photon_data_processor.createShellIndexMap( 100,
map );
Teuchos::Array<Utility::Pair<unsigned int, unsigned int> > map_true;
Utility::Pair<unsigned int,unsigned int> data_point;
data_point.first = 1;
data_point.second = 0;
map_true.push_back( data_point );
data_point.first = 3;
data_point.second = 1;
map_true.push_back( data_point );
data_point.first = 5;
data_point.second = 2;
map_true.push_back( data_point );
data_point.first = 6;
data_point.second = 3;
map_true.push_back( data_point );
data_point.first = 8;
data_point.second = 4;
map_true.push_back( data_point );
data_point.first = 10;
data_point.second = 5;
map_true.push_back( data_point );
data_point.first = 11;
data_point.second = 6;
map_true.push_back( data_point );
data_point.first = 13;
data_point.second = 7;
map_true.push_back( data_point );
data_point.first = 14;
data_point.second = 8;
map_true.push_back( data_point );
data_point.first = 16;
data_point.second = 9;
map_true.push_back( data_point );
data_point.first = 18;
data_point.second = 10;
map_true.push_back( data_point );
data_point.first = 19;
data_point.second = 11;
map_true.push_back( data_point );
data_point.first = 21;
data_point.second = 12;
map_true.push_back( data_point );
data_point.first = 22;
data_point.second = 13;
map_true.push_back( data_point );
data_point.first = 24;
data_point.second = 14;
map_true.push_back( data_point );
data_point.first = 25;
data_point.second = 15;
map_true.push_back( data_point );
data_point.first = 27;
data_point.second = 16;
map_true.push_back( data_point );
data_point.first = 29;
data_point.second = 17;
map_true.push_back( data_point );
data_point.first = 30;
data_point.second = 18;
map_true.push_back( data_point );
data_point.first = 32;
data_point.second = 19;
map_true.push_back( data_point );
data_point.first = 33;
data_point.second = 20;
map_true.push_back( data_point );
data_point.first = 35;
data_point.second = 21;
map_true.push_back( data_point );
data_point.first = 36;
data_point.second = 22;
map_true.push_back( data_point );
data_point.first = 41;
data_point.second = 23;
map_true.push_back( data_point );
data_point.first = 43;
data_point.second = 24;
map_true.push_back( data_point );
data_point.first = 44;
data_point.second = 25;
map_true.push_back( data_point );
data_point.first = 58;
data_point.second = 26;
map_true.push_back( data_point );
UTILITY_TEST_COMPARE_ARRAYS( map, map_true );
}
//---------------------------------------------------------------------------//
// Custom main function
//---------------------------------------------------------------------------//
int main( int argc, char* argv[] )
{
Teuchos::CommandLineProcessor& clp = Teuchos::UnitTestRepository::getCLP();
clp.setOption( "epdl_test_file",
&epdl_test_file,
"EPDL test file name" );
clp.setOption( "eadl_test_file",
&eadl_test_file,
"EADL test file name" );
clp.setOption( "compton_test_file_prefix",
&compton_test_file_prefix,
"Compton profile test file prefix" );
Teuchos::GlobalMPISession mpiSession( &argc, &argv );
return Teuchos::UnitTestRepository::runUnitTestsFromMain( argc, argv );
}
//---------------------------------------------------------------------------//
// end tstPhotonDataProcessorShellMap.cpp
//---------------------------------------------------------------------------//
| 25.035689 | 79 | 0.686677 | lkersting |
ae87152dbc2fc8a731ff4c6cbd55b802481f00d4 | 2,837 | cpp | C++ | src/io.cpp | sqt/sudoku | b536c663af5b6d6f0c8b8a728e595f3dfde499b5 | [
"BSD-3-Clause"
] | null | null | null | src/io.cpp | sqt/sudoku | b536c663af5b6d6f0c8b8a728e595f3dfde499b5 | [
"BSD-3-Clause"
] | null | null | null | src/io.cpp | sqt/sudoku | b536c663af5b6d6f0c8b8a728e595f3dfde499b5 | [
"BSD-3-Clause"
] | null | null | null | #include <iostream>
#include <cmath>
#include <sstream>
#include "io.hpp"
PuzzleState readPuzzleFromFile(std::ifstream& ifs)
{
PuzzleState result;
EntryState unknown_entry;
for (uint8_t i = 1; i < 10; ++i)
unknown_entry.insert(i);
for (std::string line; std::getline(ifs, line); )
{
if (line.empty() == false)
{
RowState row;
std::stringstream ss(line);
while (ss.good())
{
uint16_t value;
ss >> value;
if (value == 0)
{
row.push_back(unknown_entry);
}
else
{
EntryState entry;
entry.insert(std::min(static_cast<uint8_t>(value), static_cast<uint8_t>(9u)));
row.push_back(entry);
}
}
result.push_back(row);
}
}
return result;
}
PuzzleState readPuzzleFromJSON(const std::string& json)
{
PuzzleState result;
std::vector<size_t> values;
size_t sloc = json.find_first_of("[") + 1;
while (sloc != std::string::npos && sloc < json.size())
{
size_t eloc = json.find_first_of(",]", sloc);
size_t value = std::strtoull(json.substr(sloc, eloc - sloc).data(), NULL, 10);
values.push_back(value);
sloc = eloc + 1;
}
size_t root = static_cast<size_t>(std::sqrt(static_cast<double>(values.size())));
if (root * root != values.size())
{
return result;
}
EntryState unknown_entry;
for (size_t i = 1; i < root + 1; ++i)
unknown_entry.insert(i);
for (size_t i = 0; i < root; ++i)
{
RowState row;
for (size_t j = 0; j < root; ++j)
{
size_t value = values[i * root + j];
if (value != 0)
{
EntryState entry;
entry.insert(value);
row.push_back(entry);
}
else
{
row.push_back(unknown_entry);
}
}
result.push_back(row);
}
return result;
}
void printRow(const RowState& row, std::ostream& os)
{
for (auto j = row.cbegin(); j < row.cend(); ++j)
{
if (j->size() == 0) // Zero Options Remaining (Should Not Happen)
{
os << "- " << std::flush;
}
else if (j->size() == 1)
{
os << static_cast<uint16_t>(*(j->cbegin())) << " " << std::flush;
}
else
{
os << " " << std::flush;
}
}
}
void printJSONRow(const RowState& row, std::ostream& os)
{
for (auto j = row.cbegin(); j < row.cend(); ++j)
{
if (j != row.cbegin())
{
os << ',';
}
if (j->size() == 0) // Zero Options Remaining (Should Not Happen)
{
os << '0';
}
else if (j->size() == 1)
{
os << static_cast<uint16_t>(*(j->cbegin()));
}
else
{
os << ' ';
}
}
}
void printSolution(const PuzzleState& state, std::ostream& os)
{
for (auto i = state.cbegin(); i < state.cend(); ++i)
{
printRow(*i, os);
os << std::endl;
}
}
void printJSONSolution(const PuzzleState& state, std::ostream& os)
{
os << '[';
for (auto i = state.cbegin(); i < state.cend(); ++i)
{
if (i != state.cbegin())
{
os << ',';
}
printJSONRow(*i, os);
}
os << ']' << std::flush;
}
| 17.955696 | 83 | 0.572788 | sqt |
ae88e50ec6eef358fdc5be75c59fd1b69f95f254 | 39,698 | cc | C++ | src/muensterTPCPhysicsList.cc | l-althueser/MuensterTPC-Simulation | 7a086ab330cd5905f3c78c324936cdc36951e9bd | [
"BSD-2-Clause"
] | null | null | null | src/muensterTPCPhysicsList.cc | l-althueser/MuensterTPC-Simulation | 7a086ab330cd5905f3c78c324936cdc36951e9bd | [
"BSD-2-Clause"
] | 2 | 2017-01-24T21:18:46.000Z | 2017-01-27T13:24:48.000Z | src/muensterTPCPhysicsList.cc | l-althueser/MuensterTPC-Simulation | 7a086ab330cd5905f3c78c324936cdc36951e9bd | [
"BSD-2-Clause"
] | 4 | 2017-04-28T12:18:58.000Z | 2019-04-10T21:15:00.000Z | /******************************************************************
* muensterTPCsim
*
* Simulations of the Muenster TPC
*
* @author Lutz Althüser, based on muensterTPC (Levy) and Xenon100
* @date 2015-04-14
* @update 2016-02-16
*
* @comment - ready for G4 V10.02
* - added some festures of the new G4 versions (modular physics lists)
******************************************************************/
#include <G4ProcessManager.hh>
#include <G4ProcessVector.hh>
#include <G4ParticleDefinition.hh>
#include <G4ParticleWithCuts.hh>
#include <G4ParticleTypes.hh>
#include <G4ParticleTable.hh>
#include <G4HadronCaptureProcess.hh>
#include <G4UserLimits.hh>
#include "G4UserSpecialCuts.hh"
#include <G4ios.hh>
#include <globals.hh>
#include "G4SystemOfUnits.hh"
#include "G4PhysicsListHelper.hh"
#include <iomanip>
#include <G4EmStandardPhysics.hh>
#include <G4EmLivermorePhysics.hh>
#include <G4EmPenelopePhysics.hh>
#include "muensterTPCPhysicsList.hh"
#include "muensterTPCPhysicsMessenger.hh"
#include "G4VPhysicsConstructor.hh"
#include "G4HadronPhysicsQGSP_BERT.hh"
#include "G4HadronPhysicsQGSP_BERT_HP.hh"
#include "G4EmExtraPhysics.hh"
#include "G4HadronElasticPhysics.hh"
#include "G4HadronElasticPhysicsHP.hh"
#include "G4StoppingPhysics.hh"
#include "G4IonPhysics.hh"
#include "G4NeutronTrackingCut.hh"
// Constructor /////////////////////////////////////////////////////////////
muensterTPCPhysicsList::muensterTPCPhysicsList():G4VUserPhysicsList() {
defaultCutValue = 1.0 * mm; //
cutForGamma = defaultCutValue;
cutForElectron = defaultCutValue;
cutForPositron = defaultCutValue;
VerboseLevel = 0;
OpVerbLevel = 0;
SetVerboseLevel(VerboseLevel);
m_pMessenger = new muensterTPCPhysicsMessenger(this);
particleList = new G4DecayPhysics("decays");
}
// Destructor //////////////////////////////////////////////////////////////
muensterTPCPhysicsList::~muensterTPCPhysicsList()
{
delete emPhysicsList;
delete particleList;
// delete opPhysicsList;
delete m_pMessenger;
for(size_t i=0; i<hadronPhys.size(); i++) {
delete hadronPhys[i];
}
}
// Construct Particles /////////////////////////////////////////////////////
void muensterTPCPhysicsList::ConstructParticle() {
// In this method, static member functions should be called
// for all particles which you want to use.
// This ensures that objects of these particle types will be
// created in the program.
//if (m_hHadronicModel == "custom"){
//G4cout << "----- ConstructMyBosons" << G4endl;
ConstructMyBosons();
//G4cout << "----- ConstructMyLeptons" << G4endl;
ConstructMyLeptons();
//G4cout << "----- ConstructMyHadrons" << G4endl;
ConstructMyHadrons();
//G4cout << "----- ConstructMyShortLiveds" << G4endl;
ConstructMyShortLiveds();
//} else if (m_hHadronicModel == "QGSP_BERT_HP") {
particleList->ConstructParticle();
//}
}
// construct Bosons://///////////////////////////////////////////////////
void muensterTPCPhysicsList::ConstructMyBosons() {
// pseudo-particles
G4Geantino::GeantinoDefinition();
G4ChargedGeantino::ChargedGeantinoDefinition();
// gamma
G4Gamma::GammaDefinition();
//OpticalPhotons
G4OpticalPhoton::OpticalPhotonDefinition();
}
// construct Leptons://///////////////////////////////////////////////////
void muensterTPCPhysicsList::ConstructMyLeptons() {
// leptons
G4Electron::ElectronDefinition();
G4Positron::PositronDefinition();
G4MuonPlus::MuonPlusDefinition();
G4MuonMinus::MuonMinusDefinition();
G4NeutrinoE::NeutrinoEDefinition();
G4AntiNeutrinoE::AntiNeutrinoEDefinition();
G4NeutrinoMu::NeutrinoMuDefinition();
G4AntiNeutrinoMu::AntiNeutrinoMuDefinition();
}
#include "G4MesonConstructor.hh"
#include "G4BaryonConstructor.hh"
#include "G4IonConstructor.hh"
// construct Hadrons://///////////////////////////////////////////////////
void muensterTPCPhysicsList::ConstructMyHadrons()
{
// mesons
G4MesonConstructor mConstructor;
mConstructor.ConstructParticle();
// baryons
G4BaryonConstructor bConstructor;
bConstructor.ConstructParticle();
// ions
G4IonConstructor iConstructor;
iConstructor.ConstructParticle();
}
// construct Shortliveds://///////////////////////////////////////////////////
// this can be added if necessary
//#include "G4ShortLivedConstructor.hh"
void muensterTPCPhysicsList::ConstructMyShortLiveds()
{
//G4ShortLivedConstructor slConstructor;
//slConstructor.ConstructParticle();
}
// Construct Processes //////////////////////////////////////////////////////
void muensterTPCPhysicsList::ConstructProcess()
{
G4cout <<"MuensterTPCPhysicsList::MuensterTPCPhysicsList() EM physics: "<< m_hEMlowEnergyModel << G4endl;
G4cout <<"MuensterTPCPhysicsList::MuensterTPCPhysicsList() Cerenkov: "<< m_bCerenkov << G4endl;
AddTransportation();
// EM physics
if (m_hEMlowEnergyModel == "emstandard") {
emPhysicsList = new G4EmStandardPhysics();
} else if (m_hEMlowEnergyModel == "emlivermore"){
emPhysicsList = new G4EmLivermorePhysics();
} else if (m_hEMlowEnergyModel == "empenelope"){
emPhysicsList = new G4EmPenelopePhysics();
} else if (m_hEMlowEnergyModel == "old") {
G4cout << "MuensterTPCPhysicsList::ConstructProcess() WARNING: Old version of low energy EM processes ... "<<G4endl;
} else {
G4cout <<"MuensterTPCPhysicsList::MuensterTPCPhysicsList() FATAL: Bad EM physics list chosen: "<<m_hEMlowEnergyModel<<G4endl;
G4String msg = " Available choices are: <emstandard> <emlivermore (default)> <empenelope> <old>";
G4Exception("MuensterTPCPhysicsList::ConstructProcess()","PhysicsList",FatalException,msg);
}
// add the physics processes
if (m_hEMlowEnergyModel != "old"){
emPhysicsList->ConstructProcess();
} else {
ConstructEM(); // obsolete in GEANT4_VERSION > geant4.9.4.p02
}
// construct optical physics...... is there a G4 standard for this one as well?
ConstructOp();
//opPhysicsList = new G4OpticalPhysics();
// opPhysicsList->ConstructProcess();
// construct the Hadronic physics models
hadronPhys.clear();
if (m_hHadronicModel == "custom") {
// custom hadronic physics list
ConstructHad();
} else if (m_hHadronicModel == "QGSP_BERT") {
// implemented QGSP_BERT: is it done in the right way?
// this follows the recipe from examples/extended/hadronic/Hadr01
SetBuilderList1(false);
hadronPhys.push_back( new G4HadronPhysicsQGSP_BERT());
} else if (m_hHadronicModel == "QGSP_BERT_HP") {
// implemented QGSP_BERT_HP: is it done in the right way?
// this follows the recipe from examples/extended/hadronic/Hadr01
SetBuilderList1(true);
hadronPhys.push_back( new G4HadronPhysicsQGSP_BERT_HP());
} else {
G4String msg = "MuensterTPCPhysicsList::MuensterTPCPhysicsList() Available choices for Hadronic Physics are: <custom> <QGSP_BERT> <QGSP_BERT_HP>";
G4Exception("MuensterTPCPhysicsList::ConstructProcess()","PhysicsList",FatalException,msg);
}
// construct processes
for(size_t i=0; i<hadronPhys.size(); i++) {
hadronPhys[i]->ConstructProcess();
}
// some other stuff
if (m_hHadronicModel == "custom"){
ConstructGeneral();
} else if (m_hHadronicModel == "QGSP_BERT_HP" ||
m_hHadronicModel == "QGSP_BERT" ) {
particleList->ConstructProcess();
ConstructGeneral();
}
}
void muensterTPCPhysicsList::SetBuilderList1(G4bool flagHP)
{
hadronPhys.push_back( new G4EmExtraPhysics());
if(flagHP) {
hadronPhys.push_back( new G4HadronElasticPhysicsHP() );
} else {
hadronPhys.push_back( new G4HadronElasticPhysics() );
}
hadronPhys.push_back( new G4StoppingPhysics());
hadronPhys.push_back( new G4IonPhysics());
hadronPhys.push_back( new G4NeutronTrackingCut());
}
// Transportation ///////////////////////////////////////////////////////////
//#include "XeMaxTimeCuts.hh"
//#include "XeMinEkineCuts.hh"
void muensterTPCPhysicsList::AddTransportation()
{
//G4cout << "----- AddTransportation" << G4endl;
G4VUserPhysicsList::AddTransportation();
// theParticleIterator->reset();
// while((*theParticleIterator) ())
// {
// G4ParticleDefinition *particle = theParticleIterator->value();
// G4ProcessManager *pmanager = particle->GetProcessManager();
// G4String particleName = particle->GetParticleName();
// if(particleName == "neutron")
// pmanager->AddDiscreteProcess(new XeMaxTimeCuts());
// pmanager->AddDiscreteProcess(new XeMinEkineCuts());
// }
}
// Electromagnetic Processes ////////////////////////////////////////////////
// all charged particles
// gamma
#include "G4PhotoElectricEffect.hh"
#include "G4LivermorePhotoElectricModel.hh"
#include "G4ComptonScattering.hh"
#include "G4LivermoreComptonModel.hh"
#include "G4GammaConversion.hh"
#include "G4LivermoreGammaConversionModel.hh"
#include "G4RayleighScattering.hh"
#include "G4LivermoreRayleighModel.hh"
// e-
#include "G4eMultipleScattering.hh"
#include "G4eIonisation.hh"
#include "G4LivermoreIonisationModel.hh"
#include "G4eBremsstrahlung.hh"
#include "G4LivermoreBremsstrahlungModel.hh"
// e+
#include "G4eIonisation.hh"
#include "G4eBremsstrahlung.hh"
#include "G4eplusAnnihilation.hh"
// alpha and GenericIon and deuterons, triton, He3:
//muon:
#include "G4MuIonisation.hh"
#include "G4MuBremsstrahlung.hh"
#include "G4MuPairProduction.hh"
#include "G4MuonMinusCapture.hh"
//OTHERS:
#include "G4hIonisation.hh"
#include "G4hMultipleScattering.hh"
#include "G4hBremsstrahlung.hh"
#include "G4ionIonisation.hh"
#include "G4IonParametrisedLossModel.hh"
//em process options to allow msc step-limitation to be switched off
#include "G4EmProcessOptions.hh"
void
muensterTPCPhysicsList::ConstructEM()
{
//G4cout << "----- ConstructEM" << G4endl;
// Is there a fluorcut missing?
// at the end the fluorescence is switched to off (end of this chapter)
//G4double fluorcut = 250 * eV;
//set a finer grid of the physic tables in order to improve precision
//former LowEnergy models have 200 bins up to 100 GeV
G4EmProcessOptions opt;
opt.SetMaxEnergy(100*GeV);
opt.SetDEDXBinning(200);
opt.SetLambdaBinning(200);
theParticleIterator->reset();
while((*theParticleIterator) ())
{
G4ParticleDefinition *particle = theParticleIterator->value();
G4ProcessManager *pmanager = particle->GetProcessManager();
G4String particleName = particle->GetParticleName();
G4String particleType = particle->GetParticleType();
G4double charge = particle->GetPDGCharge();
//the Livermore models are not strictly necessary
if(particleName == "gamma")
{
//gamma
G4RayleighScattering* theRayleigh = new G4RayleighScattering();
//theRayleigh->SetEmModel(new G4LivermoreRayleighModel());
pmanager->AddDiscreteProcess(theRayleigh);
G4PhotoElectricEffect* thePhotoElectricEffect = new G4PhotoElectricEffect();
//thePhotoElectricEffect->SetEmModel(new G4LivermorePhotoElectricModel());
//thePhotoElectricEffect->SetCutForLowEnSecPhotons(fluorcut);
pmanager->AddDiscreteProcess(thePhotoElectricEffect);
G4ComptonScattering* theComptonScattering = new G4ComptonScattering();
//theComptonScattering->SetEmModel(new G4LivermoreComptonModel());
pmanager->AddDiscreteProcess(theComptonScattering);
G4GammaConversion* theGammaConversion = new G4GammaConversion();
//theGammaConversion->SetEmModel(new G4LivermoreGammaConversionModel());
pmanager->AddDiscreteProcess(theGammaConversion);
}
else if(particleName == "e-")
{
//electron
// process ordering: AddProcess(name, at rest, along step, post step)
// -1 = not implemented, then ordering
// Multiple scattering
G4eMultipleScattering* msc = new G4eMultipleScattering();
msc->SetStepLimitType(fUseDistanceToBoundary);
pmanager->AddProcess(msc,-1, 1, 1);
// Ionisation
G4eIonisation* eIonisation = new G4eIonisation();
//eIonisation->SetCutForLowEnSecPhotons(fluorcut);
//eIonisation->SetEmModel(new G4LivermoreIonisationModel());
eIonisation->SetStepFunction(0.2, 100*um); //improved precision in tracking
pmanager->AddProcess(eIonisation,-1, 2, 2);
// Bremsstrahlung
G4eBremsstrahlung* eBremsstrahlung = new G4eBremsstrahlung();
//eBremsstrahlung->SetEmModel(new G4LivermoreBremsstrahlungModel());
//eBremsstrahlung->SetCutForLowEnSecPhotons(fluorcut);
pmanager->AddProcess(eBremsstrahlung, -1,-1, 3);
}
else if(particleName == "e+")
{
//positron
G4eMultipleScattering* msc = new G4eMultipleScattering();
msc->SetStepLimitType(fUseDistanceToBoundary);
pmanager->AddProcess(msc,-1, 1, 1);
// Ionisation
G4eIonisation* eIonisation = new G4eIonisation();
eIonisation->SetStepFunction(0.2, 100*um);
pmanager->AddProcess(eIonisation, -1, 2, 2);
//Bremsstrahlung (use default, no low-energy available)
pmanager->AddProcess(new G4eBremsstrahlung(), -1,-1, 3);
//Annihilation
pmanager->AddProcess(new G4eplusAnnihilation(), 0, -1, 4);
}
else if(particleName == "mu+" || particleName == "mu-")
{
//muon
pmanager->AddProcess(new G4eMultipleScattering,-1, 1, 1);
pmanager->AddProcess(new G4MuIonisation(),-1, 2, 2);
pmanager->AddProcess(new G4MuBremsstrahlung(),-1,-1, 3);
pmanager->AddProcess(new G4MuPairProduction(),-1,-1, 4);
if( particleName == "mu-" )
pmanager->AddProcess(new G4MuonMinusCapture(), 0,-1,-1);
}
// nucleus is not used yet
// (particleType == "nucleus" && charge != 0)
else if (particleName == "proton" ||
particleName == "pi+" ||
particleName == "pi-")
{
//multiple scattering
pmanager->AddProcess(new G4hMultipleScattering, -1, 1, 1);
//ionisation
G4hIonisation* hIonisation = new G4hIonisation();
hIonisation->SetStepFunction(0.2, 50*um);
pmanager->AddProcess(hIonisation,-1, 2, 2);
//bremmstrahlung
pmanager->AddProcess(new G4hBremsstrahlung,-1,-3, 3);
}
else if (particleName == "alpha" ||
particleName == "deuteron" ||
particleName == "triton" ||
particleName == "He3")
{
//multiple scattering
pmanager->AddProcess(new G4hMultipleScattering,-1,1,1);
//ionisation
G4ionIonisation* ionIoni = new G4ionIonisation();
ionIoni->SetStepFunction(0.1, 20*um);
pmanager->AddProcess(ionIoni,-1, 2, 2);
}
else if (particleName == "GenericIon")
{
// OBJECT may be dynamically created as either a GenericIon or nucleus
// G4Nucleus exists and therefore has particle type nucleus
// genericIon:
//multiple scattering
pmanager->AddProcess(new G4hMultipleScattering,-1,1,1);
//ionisation
G4ionIonisation* ionIoni = new G4ionIonisation();
ionIoni->SetEmModel(new G4IonParametrisedLossModel());
ionIoni->SetStepFunction(0.1, 20*um);
pmanager->AddProcess(ionIoni,-1, 2, 2);
}
else if ((!particle->IsShortLived()) &&
(charge != 0.0) &&
(particle->GetParticleName() != "chargedgeantino"))
{
//all others charged particles except geantino
G4hMultipleScattering* aMultipleScattering = new G4hMultipleScattering();
G4hIonisation* ahadronIon = new G4hIonisation();
//multiple scattering
pmanager->AddProcess(aMultipleScattering,-1,1,1);
//ionisation
pmanager->AddProcess(ahadronIon,-1,2,2);
}
}
// turn off msc step-limitation - especially as electron cut 1nm
opt.SetMscStepLimitation(fMinimal);
// switch on fluorescence, PIXE and Auger:
opt.SetFluo(false);
opt.SetPIXE(false);
opt.SetAuger(false);
}
// Optical Processes ////////////////////////////////////////////////////////
#include "G4Scintillation.hh"
#include "G4OpAbsorption.hh"
#include "G4OpRayleigh.hh"
#include "G4OpBoundaryProcess.hh"
#include "G4Cerenkov.hh"
void
muensterTPCPhysicsList::ConstructOp()
{
//G4cout << "----- ConstructOp" << G4endl;
// default scintillation process
G4Scintillation *theScintProcessDef =
new G4Scintillation("Scintillation");
// theScintProcessDef->DumpPhysicsTable();
theScintProcessDef->SetTrackSecondariesFirst(true);
theScintProcessDef->SetScintillationYieldFactor(1.0);
theScintProcessDef->SetScintillationExcitationRatio(0.0);
theScintProcessDef->SetVerboseLevel(OpVerbLevel);
// scintillation process for alpha:
G4Scintillation *theScintProcessAlpha =
new G4Scintillation("Scintillation");
// theScintProcessNuc->DumpPhysicsTable();
theScintProcessAlpha->SetTrackSecondariesFirst(true);
theScintProcessAlpha->SetScintillationYieldFactor(1.1);
theScintProcessAlpha->SetScintillationExcitationRatio(1.0);
theScintProcessAlpha->SetVerboseLevel(OpVerbLevel);
// scintillation process for heavy nuclei
G4Scintillation *theScintProcessNuc =
new G4Scintillation("Scintillation");
// theScintProcessNuc->DumpPhysicsTable();
theScintProcessNuc->SetTrackSecondariesFirst(true);
theScintProcessNuc->SetScintillationYieldFactor(0.2);
theScintProcessNuc->SetScintillationExcitationRatio(1.0);
theScintProcessNuc->SetVerboseLevel(OpVerbLevel);
// add Cerenkov
G4Cerenkov *fCerenkovProcess = new G4Cerenkov("Cerenkov");
if (m_bCerenkov) {
G4cout <<"muensterTPCPhysicsList::ConstructOp() Define Cerenkov .... "<<G4endl;
// the maximum numer of photons per GEANT4 step....
G4double fMaxNumPhotons = 100; // same as in G4OpticalPhysics.cc I think, but no guarantees
// the maximum change in beta=v/c in percent
G4double fMaxBetaChange = 10; // same as in G4OpticalPhysics.cc
// tracks secondaries before continuing with the original particle
G4bool fTrackSecondariesFirst = true; // same as in G4OpticalPhysics.cc
fCerenkovProcess->SetMaxNumPhotonsPerStep(fMaxNumPhotons);
fCerenkovProcess->SetMaxBetaChangePerStep(fMaxBetaChange);
fCerenkovProcess->SetTrackSecondariesFirst(fTrackSecondariesFirst);
} else {
G4cout <<"muensterTPCPhysicsList::ConstructOp() Disable Cerenkov .... "<<G4endl;
}
// optical processes
G4OpAbsorption *theAbsorptionProcess = new G4OpAbsorption();
G4OpRayleigh *theRayleighScatteringProcess = new G4OpRayleigh();
G4OpBoundaryProcess *theBoundaryProcess = new G4OpBoundaryProcess();
//theAbsorptionProcess->DumpPhysicsTable();
//theRayleighScatteringProcess->DumpPhysicsTable();
theAbsorptionProcess->SetVerboseLevel(OpVerbLevel);
theRayleighScatteringProcess->SetVerboseLevel(OpVerbLevel);
theBoundaryProcess->SetVerboseLevel(OpVerbLevel);
//20th Jun 2012 P.Gumplinger (op-V09-05-04)
//remove methods: SetModel/GetModel from G4OpBoundaryProcess class
// -> remove:
//G4OpticalSurfaceModel themodel = unified;
//theBoundaryProcess->SetModel(themodel);
theParticleIterator->reset();
while((*theParticleIterator) ())
{
G4ParticleDefinition *particle = theParticleIterator->value();
G4ProcessManager *pmanager = particle->GetProcessManager();
G4String particleName = particle->GetParticleName();
if(theScintProcessDef->IsApplicable(*particle))
{
// if(particle->GetPDGMass() > 5.0*GeV)
if(particle->GetParticleName() == "GenericIon")
{
pmanager->AddProcess(theScintProcessNuc); // AtRestDiscrete
pmanager->SetProcessOrderingToLast(theScintProcessNuc,
idxAtRest);
pmanager->SetProcessOrderingToLast(theScintProcessNuc,
idxPostStep);
}
else if(particle->GetParticleName() == "alpha")
{
pmanager->AddProcess(theScintProcessAlpha);
pmanager->SetProcessOrderingToLast(theScintProcessAlpha,
idxAtRest);
pmanager->SetProcessOrderingToLast(theScintProcessAlpha,
idxPostStep);
}
else
{
pmanager->AddProcess(theScintProcessDef);
pmanager->SetProcessOrderingToLast(theScintProcessDef,
idxAtRest);
pmanager->SetProcessOrderingToLast(theScintProcessDef,
idxPostStep);
}
}
if(particleName == "opticalphoton")
{
// Step limitation seen as a process
pmanager->AddProcess(new G4UserSpecialCuts(),-1,-1,1);
pmanager->AddDiscreteProcess(theAbsorptionProcess);
pmanager->AddDiscreteProcess(theRayleighScatteringProcess);
pmanager->AddDiscreteProcess(theBoundaryProcess);
}
// ... and give those particles that need it a bit of Cerenkov.... and only if you want to
if(fCerenkovProcess->IsApplicable(*particle) && m_bCerenkov){
pmanager->AddProcess(fCerenkovProcess);
pmanager->SetProcessOrdering(fCerenkovProcess,idxPostStep);
}
}
}
// Hadronic processes ////////////////////////////////////////////////////////
// for more information see: DMXPhysicsList.cc (Geant4.10 example source)
// Elastic processes:
#include "G4HadronElasticProcess.hh"
#include "G4ChipsElasticModel.hh"
#include "G4ElasticHadrNucleusHE.hh"
// Inelastic processes:
#include "G4PionPlusInelasticProcess.hh"
#include "G4PionMinusInelasticProcess.hh"
#include "G4KaonPlusInelasticProcess.hh"
#include "G4KaonZeroSInelasticProcess.hh"
#include "G4KaonZeroLInelasticProcess.hh"
#include "G4KaonMinusInelasticProcess.hh"
#include "G4ProtonInelasticProcess.hh"
#include "G4AntiProtonInelasticProcess.hh"
#include "G4NeutronInelasticProcess.hh"
#include "G4AntiNeutronInelasticProcess.hh"
#include "G4DeuteronInelasticProcess.hh"
#include "G4TritonInelasticProcess.hh"
#include "G4AlphaInelasticProcess.hh"
// High energy FTFP model and Bertini cascade
#include "G4FTFModel.hh"
#include "G4LundStringFragmentation.hh"
#include "G4ExcitedStringDecay.hh"
#include "G4PreCompoundModel.hh"
#include "G4GeneratorPrecompoundInterface.hh"
#include "G4TheoFSGenerator.hh"
#include "G4CascadeInterface.hh"
// Cross sections
#include "G4VCrossSectionDataSet.hh"
#include "G4CrossSectionDataSetRegistry.hh"
#include "G4CrossSectionElastic.hh"
#include "G4BGGPionElasticXS.hh"
#include "G4AntiNuclElastic.hh"
#include "G4CrossSectionInelastic.hh"
#include "G4PiNuclearCrossSection.hh"
#include "G4CrossSectionPairGG.hh"
#include "G4BGGNucleonInelasticXS.hh"
#include "G4ComponentAntiNuclNuclearXS.hh"
//Version check 10.01, 10.01.p01, 10.01.p02, > 10.02
#ifdef G4VERSION_NUMBER <= 1020
#include "G4GGNuclNuclCrossSection.hh"
#else
#include "G4ComponentGGNuclNuclXsc.hh"
#endif
#include "G4HadronElastic.hh"
#include "G4HadronCaptureProcess.hh"
// Neutron high-precision models: <20 MeV
#include "G4NeutronHPElastic.hh"
#include "G4NeutronHPElasticData.hh"
#include "G4NeutronHPCapture.hh"
#include "G4NeutronHPCaptureData.hh"
#include "G4NeutronHPInelastic.hh"
#include "G4NeutronHPInelasticData.hh"
// Stopping processes
#include "G4PiMinusAbsorptionBertini.hh"
#include "G4KaonMinusAbsorptionBertini.hh"
#include "G4AntiProtonAbsorptionFritiof.hh"
void muensterTPCPhysicsList::ConstructHad()
{
//G4cout << "----- ConstructHad" << G4endl;
//Elastic models
const G4double elastic_elimitPi = 1.0*GeV;
G4HadronElastic* elastic_lhep0 = new G4HadronElastic();
G4HadronElastic* elastic_lhep1 = new G4HadronElastic();
elastic_lhep1->SetMaxEnergy( elastic_elimitPi );
G4ChipsElasticModel* elastic_chip = new G4ChipsElasticModel();
G4ElasticHadrNucleusHE* elastic_he = new G4ElasticHadrNucleusHE();
elastic_he->SetMinEnergy( elastic_elimitPi );
// Inelastic scattering
const G4double theFTFMin0 = 0.0*GeV;
const G4double theFTFMin1 = 4.0*GeV;
const G4double theFTFMax = 100.0*TeV;
const G4double theBERTMin0 = 0.0*GeV;
const G4double theBERTMin1 = 19.0*MeV;
const G4double theBERTMax = 5.0*GeV;
const G4double theHPMin = 0.0*GeV;
const G4double theHPMax = 20.0*MeV;
G4FTFModel * theStringModel = new G4FTFModel;
G4ExcitedStringDecay * theStringDecay = new G4ExcitedStringDecay( new G4LundStringFragmentation );
theStringModel->SetFragmentationModel( theStringDecay );
G4PreCompoundModel * thePreEquilib = new G4PreCompoundModel( new G4ExcitationHandler );
G4GeneratorPrecompoundInterface * theCascade = new G4GeneratorPrecompoundInterface( thePreEquilib );
G4TheoFSGenerator * theFTFModel0 = new G4TheoFSGenerator( "FTFP" );
theFTFModel0->SetHighEnergyGenerator( theStringModel );
theFTFModel0->SetTransport( theCascade );
theFTFModel0->SetMinEnergy( theFTFMin0 );
theFTFModel0->SetMaxEnergy( theFTFMax );
G4TheoFSGenerator * theFTFModel1 = new G4TheoFSGenerator( "FTFP" );
theFTFModel1->SetHighEnergyGenerator( theStringModel );
theFTFModel1->SetTransport( theCascade );
theFTFModel1->SetMinEnergy( theFTFMin1 );
theFTFModel1->SetMaxEnergy( theFTFMax );
G4CascadeInterface * theBERTModel0 = new G4CascadeInterface;
theBERTModel0->SetMinEnergy( theBERTMin0 );
theBERTModel0->SetMaxEnergy( theBERTMax );
G4CascadeInterface * theBERTModel1 = new G4CascadeInterface;
theBERTModel1->SetMinEnergy( theBERTMin1 );
theBERTModel1->SetMaxEnergy( theBERTMax );
G4VCrossSectionDataSet * thePiData = new G4CrossSectionPairGG( new G4PiNuclearCrossSection, 91*GeV );
G4VCrossSectionDataSet * theAntiNucleonData = new G4CrossSectionInelastic( new G4ComponentAntiNuclNuclearXS );
//Version check 10.01, 10.01.p01, 10.01.p02, > 10.02
#ifdef G4VERSION_NUMBER <= 1020
G4VCrossSectionDataSet * theGGNuclNuclData = G4CrossSectionDataSetRegistry::Instance()->
GetCrossSectionDataSet(G4ComponentGGNuclNuclXsc::Default_Name());
#else
// name changed to G4ComponentGGNuclNuclXsc due to v10.02
G4ComponentGGNuclNuclXsc* ionElasticXS = new G4ComponentGGNuclNuclXsc;
G4VCrossSectionDataSet* theGGNuclNuclData = new G4CrossSectionElastic(ionElasticXS);
#endif
theParticleIterator->reset();
while ((*theParticleIterator)())
{
G4ParticleDefinition* particle = theParticleIterator->value();
G4ProcessManager* pmanager = particle->GetProcessManager();
G4String particleName = particle->GetParticleName();
if (particleName == "pi+")
{
// Elastic scattering
G4HadronElasticProcess* theElasticProcess = new G4HadronElasticProcess;
theElasticProcess->AddDataSet( new G4BGGPionElasticXS( particle ) );
theElasticProcess->RegisterMe( elastic_lhep1 );
theElasticProcess->RegisterMe( elastic_he );
pmanager->AddDiscreteProcess( theElasticProcess );
//Inelastic scattering
G4PionPlusInelasticProcess* theInelasticProcess =
new G4PionPlusInelasticProcess("inelastic");
theInelasticProcess->AddDataSet( thePiData );
theInelasticProcess->RegisterMe( theFTFModel1 );
theInelasticProcess->RegisterMe( theBERTModel0 );
pmanager->AddDiscreteProcess( theInelasticProcess );
}
else if (particleName == "pi-")
{
// Elastic scattering
G4HadronElasticProcess* theElasticProcess = new G4HadronElasticProcess;
theElasticProcess->AddDataSet( new G4BGGPionElasticXS( particle ) );
theElasticProcess->RegisterMe( elastic_lhep1 );
theElasticProcess->RegisterMe( elastic_he );
pmanager->AddDiscreteProcess( theElasticProcess );
//Inelastic scattering
G4PionMinusInelasticProcess* theInelasticProcess =
new G4PionMinusInelasticProcess("inelastic");
theInelasticProcess->AddDataSet( thePiData );
theInelasticProcess->RegisterMe( theFTFModel1 );
theInelasticProcess->RegisterMe( theBERTModel0 );
pmanager->AddDiscreteProcess( theInelasticProcess );
//Absorption
pmanager->AddRestProcess(new G4PiMinusAbsorptionBertini, ordDefault);
}
else if (particleName == "kaon+")
{
// Elastic scattering
G4HadronElasticProcess* theElasticProcess = new G4HadronElasticProcess;
theElasticProcess->RegisterMe( elastic_lhep0 );
pmanager->AddDiscreteProcess( theElasticProcess );
// Inelastic scattering
G4KaonPlusInelasticProcess* theInelasticProcess =
new G4KaonPlusInelasticProcess("inelastic");
theInelasticProcess->AddDataSet( G4CrossSectionDataSetRegistry::Instance()->
GetCrossSectionDataSet(G4ChipsKaonPlusInelasticXS::Default_Name()));
theInelasticProcess->RegisterMe( theFTFModel1 );
theInelasticProcess->RegisterMe( theBERTModel0 );
pmanager->AddDiscreteProcess( theInelasticProcess );
}
else if (particleName == "kaon0S")
{
// Elastic scattering
G4HadronElasticProcess* theElasticProcess = new G4HadronElasticProcess;
theElasticProcess->RegisterMe( elastic_lhep0 );
pmanager->AddDiscreteProcess( theElasticProcess );
// Inelastic scattering
G4KaonZeroSInelasticProcess* theInelasticProcess =
new G4KaonZeroSInelasticProcess("inelastic");
theInelasticProcess->AddDataSet( G4CrossSectionDataSetRegistry::Instance()->
GetCrossSectionDataSet(G4ChipsKaonZeroInelasticXS::Default_Name()));
theInelasticProcess->RegisterMe( theFTFModel1 );
theInelasticProcess->RegisterMe( theBERTModel0 );
pmanager->AddDiscreteProcess( theInelasticProcess );
}
else if (particleName == "kaon0L")
{
// Elastic scattering
G4HadronElasticProcess* theElasticProcess = new G4HadronElasticProcess;
theElasticProcess->RegisterMe( elastic_lhep0 );
pmanager->AddDiscreteProcess( theElasticProcess );
// Inelastic scattering
G4KaonZeroLInelasticProcess* theInelasticProcess =
new G4KaonZeroLInelasticProcess("inelastic");
theInelasticProcess->AddDataSet( G4CrossSectionDataSetRegistry::Instance()->
GetCrossSectionDataSet(G4ChipsKaonZeroInelasticXS::Default_Name()));
theInelasticProcess->RegisterMe( theFTFModel1 );
theInelasticProcess->RegisterMe( theBERTModel0 );
pmanager->AddDiscreteProcess( theInelasticProcess );
}
else if (particleName == "kaon-")
{
// Elastic scattering
G4HadronElasticProcess* theElasticProcess = new G4HadronElasticProcess;
theElasticProcess->RegisterMe( elastic_lhep0 );
pmanager->AddDiscreteProcess( theElasticProcess );
// Inelastic scattering
G4KaonMinusInelasticProcess* theInelasticProcess =
new G4KaonMinusInelasticProcess("inelastic");
theInelasticProcess->AddDataSet( G4CrossSectionDataSetRegistry::Instance()->
GetCrossSectionDataSet(G4ChipsKaonMinusInelasticXS::Default_Name()));
theInelasticProcess->RegisterMe( theFTFModel1 );
theInelasticProcess->RegisterMe( theBERTModel0 );
pmanager->AddDiscreteProcess( theInelasticProcess );
pmanager->AddRestProcess(new G4KaonMinusAbsorptionBertini, ordDefault);
}
else if (particleName == "proton")
{
// Elastic scattering
G4HadronElasticProcess* theElasticProcess = new G4HadronElasticProcess;
theElasticProcess->AddDataSet(G4CrossSectionDataSetRegistry::Instance()->
GetCrossSectionDataSet(G4ChipsProtonElasticXS::Default_Name()));
theElasticProcess->RegisterMe( elastic_chip );
pmanager->AddDiscreteProcess( theElasticProcess );
// Inelastic scattering
G4ProtonInelasticProcess* theInelasticProcess =
new G4ProtonInelasticProcess("inelastic");
theInelasticProcess->AddDataSet( new G4BGGNucleonInelasticXS( G4Proton::Proton() ) );
theInelasticProcess->RegisterMe( theFTFModel1 );
theInelasticProcess->RegisterMe( theBERTModel0 );
pmanager->AddDiscreteProcess( theInelasticProcess );
}
else if (particleName == "anti_proton")
{
// Elastic scattering
const G4double elastic_elimitAntiNuc = 100.0*MeV;
G4AntiNuclElastic* elastic_anuc = new G4AntiNuclElastic();
elastic_anuc->SetMinEnergy( elastic_elimitAntiNuc );
G4CrossSectionElastic* elastic_anucxs =
new G4CrossSectionElastic( elastic_anuc->GetComponentCrossSection() );
G4HadronElastic* elastic_lhep2 = new G4HadronElastic();
elastic_lhep2->SetMaxEnergy( elastic_elimitAntiNuc );
G4HadronElasticProcess* theElasticProcess = new G4HadronElasticProcess;
theElasticProcess->AddDataSet( elastic_anucxs );
theElasticProcess->RegisterMe( elastic_lhep2 );
theElasticProcess->RegisterMe( elastic_anuc );
pmanager->AddDiscreteProcess( theElasticProcess );
// Inelastic scattering
G4AntiProtonInelasticProcess* theInelasticProcess =
new G4AntiProtonInelasticProcess("inelastic");
theInelasticProcess->AddDataSet( theAntiNucleonData );
theInelasticProcess->RegisterMe( theFTFModel0 );
pmanager->AddDiscreteProcess( theInelasticProcess );
// Absorption
pmanager->AddRestProcess(new G4AntiProtonAbsorptionFritiof, ordDefault);
}
else if (particleName == "neutron")
{
// elastic scattering
G4HadronElasticProcess* theElasticProcess = new G4HadronElasticProcess;
theElasticProcess->AddDataSet(G4CrossSectionDataSetRegistry::Instance()->
GetCrossSectionDataSet(G4ChipsNeutronElasticXS::Default_Name()));
G4HadronElastic* elastic_neutronChipsModel = new G4ChipsElasticModel();
elastic_neutronChipsModel->SetMinEnergy( 19.0*MeV );
theElasticProcess->RegisterMe( elastic_neutronChipsModel );
G4NeutronHPElastic * theElasticNeutronHP = new G4NeutronHPElastic;
theElasticNeutronHP->SetMinEnergy( theHPMin );
theElasticNeutronHP->SetMaxEnergy( theHPMax );
theElasticProcess->RegisterMe( theElasticNeutronHP );
theElasticProcess->AddDataSet( new G4NeutronHPElasticData );
pmanager->AddDiscreteProcess( theElasticProcess );
// inelastic scattering
G4NeutronInelasticProcess* theInelasticProcess =
new G4NeutronInelasticProcess("inelastic");
theInelasticProcess->AddDataSet( new G4BGGNucleonInelasticXS( G4Neutron::Neutron() ) );
theInelasticProcess->RegisterMe( theFTFModel1 );
theInelasticProcess->RegisterMe( theBERTModel1 );
G4NeutronHPInelastic * theNeutronInelasticHPModel = new G4NeutronHPInelastic;
theNeutronInelasticHPModel->SetMinEnergy( theHPMin );
theNeutronInelasticHPModel->SetMaxEnergy( theHPMax );
theInelasticProcess->RegisterMe( theNeutronInelasticHPModel );
theInelasticProcess->AddDataSet( new G4NeutronHPInelasticData );
pmanager->AddDiscreteProcess(theInelasticProcess);
// capture
G4HadronCaptureProcess* theCaptureProcess =
new G4HadronCaptureProcess;
G4NeutronHPCapture * theLENeutronCaptureModel = new G4NeutronHPCapture;
theLENeutronCaptureModel->SetMinEnergy(theHPMin);
theLENeutronCaptureModel->SetMaxEnergy(theHPMax);
theCaptureProcess->RegisterMe(theLENeutronCaptureModel);
theCaptureProcess->AddDataSet( new G4NeutronHPCaptureData);
pmanager->AddDiscreteProcess(theCaptureProcess);
}
else if (particleName == "anti_neutron")
{
// Elastic scattering
G4HadronElasticProcess* theElasticProcess = new G4HadronElasticProcess;
theElasticProcess->RegisterMe( elastic_lhep0 );
pmanager->AddDiscreteProcess( theElasticProcess );
// Inelastic scattering (include annihilation on-fly)
G4AntiNeutronInelasticProcess* theInelasticProcess =
new G4AntiNeutronInelasticProcess("inelastic");
theInelasticProcess->AddDataSet( theAntiNucleonData );
theInelasticProcess->RegisterMe( theFTFModel0 );
pmanager->AddDiscreteProcess( theInelasticProcess );
}
else if (particleName == "deuteron")
{
// Elastic scattering
G4HadronElasticProcess* theElasticProcess = new G4HadronElasticProcess;
theElasticProcess->RegisterMe( elastic_lhep0 );
pmanager->AddDiscreteProcess( theElasticProcess );
// Inelastic scattering
G4DeuteronInelasticProcess* theInelasticProcess =
new G4DeuteronInelasticProcess("inelastic");
theInelasticProcess->AddDataSet( theGGNuclNuclData );
theInelasticProcess->RegisterMe( theFTFModel1 );
theInelasticProcess->RegisterMe( theBERTModel0 );
pmanager->AddDiscreteProcess( theInelasticProcess );
}
else if (particleName == "triton")
{
// Elastic scattering
G4HadronElasticProcess* theElasticProcess = new G4HadronElasticProcess;
theElasticProcess->RegisterMe( elastic_lhep0 );
pmanager->AddDiscreteProcess( theElasticProcess );
// Inelastic scattering
G4TritonInelasticProcess* theInelasticProcess =
new G4TritonInelasticProcess("inelastic");
theInelasticProcess->AddDataSet( theGGNuclNuclData );
theInelasticProcess->RegisterMe( theFTFModel1 );
theInelasticProcess->RegisterMe( theBERTModel0 );
pmanager->AddDiscreteProcess( theInelasticProcess );
}
else if (particleName == "alpha")
{
// Elastic scattering
G4HadronElasticProcess* theElasticProcess = new G4HadronElasticProcess;
theElasticProcess->RegisterMe( elastic_lhep0 );
pmanager->AddDiscreteProcess( theElasticProcess );
// Inelastic scattering
G4AlphaInelasticProcess* theInelasticProcess =
new G4AlphaInelasticProcess("inelastic");
theInelasticProcess->AddDataSet( theGGNuclNuclData );
theInelasticProcess->RegisterMe( theFTFModel1 );
theInelasticProcess->RegisterMe( theBERTModel0 );
pmanager->AddDiscreteProcess( theInelasticProcess );
}
}
}
// Decays ///////////////////////////////////////////////////////////////////
#include "G4Decay.hh"
#include "G4RadioactiveDecay.hh"
#include "G4IonTable.hh"
#include "G4Ions.hh"
void muensterTPCPhysicsList::ConstructGeneral()
{
//G4cout << "----- ConstructGeneral" << G4endl;
// Add Decay Process
G4Decay *theDecayProcess = new G4Decay();
theParticleIterator->reset();
while((*theParticleIterator) ())
{
G4ParticleDefinition *particle = theParticleIterator->value();
G4ProcessManager *pmanager = particle->GetProcessManager();
if(theDecayProcess->IsApplicable(*particle)
&& !particle->IsShortLived())
{
pmanager->AddProcess(theDecayProcess);
// set ordering for PostStepDoIt and AtRestDoIt
pmanager->SetProcessOrdering(theDecayProcess, idxPostStep);
pmanager->SetProcessOrdering(theDecayProcess, idxAtRest);
}
}
// Declare radioactive decay to the GenericIon in the IonTable.
const G4IonTable *theIonTable =
G4ParticleTable::GetParticleTable()->GetIonTable();
G4RadioactiveDecay *theRadioactiveDecay = new G4RadioactiveDecay();
for(G4int i = 0; i < theIonTable->Entries(); i++)
{
G4String particleName =
theIonTable->GetParticle(i)->GetParticleName();
G4String particleType =
theIonTable->GetParticle(i)->GetParticleType();
if(particleName == "GenericIon")
{
G4ProcessManager *pmanager =
theIonTable->GetParticle(i)->GetProcessManager();
pmanager->SetVerboseLevel(VerboseLevel);
pmanager->AddProcess(theRadioactiveDecay);
pmanager->SetProcessOrdering(theRadioactiveDecay, idxPostStep);
pmanager->SetProcessOrdering(theRadioactiveDecay, idxAtRest);
}
}
}
// Cuts /////////////////////////////////////////////////////////////////////
void
muensterTPCPhysicsList::SetCuts()
{
if(verboseLevel > 1)
G4cout << "muensterTPCPhysicsList::SetCuts:";
if(verboseLevel > 0)
{
G4cout << "muensterTPCPhysicsList::SetCuts:";
G4cout << "CutLength : "
<< G4BestUnit(defaultCutValue, "Length") << G4endl;
}
//special for low energy physics
G4double lowlimit = 250 * eV;
G4ProductionCutsTable::GetProductionCutsTable()->SetEnergyRange(lowlimit,
100. * GeV);
// set cut values for gamma at first and for e- second and next for e+,
// because some processes for e+/e- need cut values for gamma
SetCutValue(cutForGamma, "gamma");
SetCutValue(cutForElectron, "e-");
SetCutValue(cutForPositron, "e+");
if(verboseLevel > 0) DumpCutValuesTable();
}
| 37.170412 | 150 | 0.719961 | l-althueser |
ae8ae3cf60187deee3488ff23dcd56ed2c0297ae | 15,125 | cpp | C++ | src/NameResolver.cpp | skylang/sky | 518add25e6a101ca2701b3c6bea977b0e76b340e | [
"MIT"
] | 3 | 2020-07-17T05:10:56.000Z | 2020-08-02T22:13:50.000Z | src/NameResolver.cpp | skylang/sky | 518add25e6a101ca2701b3c6bea977b0e76b340e | [
"MIT"
] | null | null | null | src/NameResolver.cpp | skylang/sky | 518add25e6a101ca2701b3c6bea977b0e76b340e | [
"MIT"
] | null | null | null | // Copyright (c) 2018 Stephan Unverwerth
// This code is licensed under MIT license (See LICENSE for details)
#include "NameResolver.h"
#include "ast/nodes.h"
#include "exceptions.h"
#include "Scope.h"
#include "SourceFile.h"
namespace Sky {
NameResolver::NameResolver(Scope* globals): scope(globals) {
}
int NameResolver::resolveGenerics(ModuleDeclaration& n) {
int numGenerics = 0;
auto oldscope = scope;
scope = new Scope(scope);
for (auto&& imp: n.imports) {
if (imp->all) {
for (auto&& fun: imp->module->functions) {
if (fun->isExported) {
scope->add(fun->name, fun);
}
}
for (auto&& cls: imp->module->classes) {
if (cls->isExported) {
scope->add(cls->_name, cls);
}
}
for (auto&& iface: imp->module->interfaces) {
if (iface->isExported) {
scope->add(iface->_name, iface);
}
}
for (auto&& en: imp->module->enums) {
if (en->isExported) {
scope->add(en->_name, en);
}
}
}
else if (imp->importModule) {
scope->add(imp->parts.back(), imp->module);
}
else {
auto cls = imp->module->getClass(imp->parts.back());
if (cls) {
if (cls->isExported) {
scope->add(cls->_name, cls);
continue;
}
else {
throw Exception(cls->_name + " is not exported.");
}
}
auto en = imp->module->getEnum(imp->parts.back());
if (en) {
if (en->isExported) {
scope->add(en->_name, en);
continue;
}
else {
throw Exception(en->_name + " is not exported.");
}
}
auto funs = imp->module->getFunctions(imp->parts.back());
if (!funs.empty()) {
for (auto&& fun: funs) {
if (fun->isExported) {
scope->add(fun->name, fun);
}
}
}
}
}
for (auto&& fun: n.functions) {
scope->add(fun->name, fun);
}
for (auto&& cls: n.classes) {
scope->add(cls->_name, cls);
}
for (auto&& iface: n.interfaces) {
scope->add(iface->_name, iface);
}
for (auto&& en: n.enums) {
scope->add(en->_name, en);
}
for (auto&& ta: n.typeAliases) {
scope->add(ta->_name, ta);
}
for (auto& cls: n.classes) {
for (auto& gen: cls->reifiedClasses) {
if (!gen->isResolved) {
resolve(*gen);
numGenerics++;
}
}
}
delete scope;
scope = oldscope;
return numGenerics;
}
void NameResolver::resolve(ModuleDeclaration& n) {
auto oldscope = scope;
scope = new Scope(scope);
for (auto& import: n.imports) {
resolve(*import);
}
for (auto&& fun: n.functions) {
scope->add(fun->name, fun);
}
for (auto&& cls: n.classes) {
scope->add(cls->_name, cls);
}
for (auto&& iface: n.interfaces) {
scope->add(iface->_name, iface);
}
for (auto&& en: n.enums) {
scope->add(en->_name, en);
}
for (auto&& ta: n.typeAliases) {
scope->add(ta->_name, ta);
}
for (auto&& fun: n.functions) {
resolve(*fun);
}
for (auto&& iface: n.interfaces) {
resolve(*iface);
}
for (auto&& cls: n.classes) {
resolve(*cls);
}
for (auto&& ta: n.typeAliases) {
resolve(*ta);
}
delete scope;
scope = oldscope;
}
void NameResolver::resolve(ClassDeclaration& n) {
// is generic
if (n.genericParams.size() > 0 && n.genericArguments.empty()) return;
// is reified generic
if (n.genericParams.size() > 0 && n.genericArguments.size() > 0) {
if (n.isResolved) return;
n.isResolved = true;
}
auto oldscope = scope;
scope = new Scope(scope);
for (int i = 0; i < n.genericParams.size(); ++i) {
scope->add(n.genericParams[i]->_name, n.genericArguments[i]);
}
for (auto&& field: n.fields) {
resolve(*field);
}
for (auto&& method: n.methods) {
resolve(*method);
}
delete scope;
scope = oldscope;
}
void NameResolver::resolve(FunctionDeclaration& n) {
auto oldscope = scope;
scope = new Scope(scope);
if (n.returnTypeExpression) visitChild(n.returnTypeExpression);
for (auto& param: n.parameters) {
resolve(*param);
}
visitChildren(n.statements);
std::vector<TypeDeclaration*> parameterTypes;
for (auto&& param: n.parameters) {
parameterTypes.push_back(param->typeExpression->typeValue);
}
n.declarationType = FunctionType::get(n.returnTypeExpression ? n.returnTypeExpression->typeValue : &VoidType::instance, parameterTypes);
delete scope;
scope = oldscope;
}
void NameResolver::resolve(Parameter& n) {
visitChild(n.typeExpression);
n.declarationType = n.typeExpression->typeValue;
scope->add(n.name, &n);
}
void NameResolver::visit(VarDeclaration& n) {
if (n.typeExpression) {
visitChild(n.typeExpression);
n.declarationType = n.typeExpression->typeValue;
}
if (n.initializer) {
visitChild(n.initializer);
}
try {
scope->add(n.name, &n);
}
catch (const DuplicateSymbolException& e) {
error(n, e.what());
}
}
void NameResolver::visit(IsExpression& n) {
visitChild(n.target);
visitChild(n.typeExpression);
}
void NameResolver::visit(UnionTypeExpression& n) {
visitChild(n.base);
visitChild(n.next);
n.type = &TypeType::instance;
n.typeValue = UnionType::get(n.base->typeValue, n.next->typeValue);
}
void NameResolver::visit(IdExpression& n) {
auto symbol = scope->find(n.name);
if (!symbol) {
error(n, "Unresolved symbol '" + n.name + "'.");
return;
}
if (auto td = symbol->node->as<TypeDeclaration>()) {
n.type = &TypeType::instance;
n.typeValue = td;
}
else if (auto var = symbol->node->as<VarDeclaration>()) {
n.node = var;
n.type = var->declarationType;
}
else if (auto par = symbol->node->as<Parameter>()) {
n.node = par;
n.type = par->declarationType;
}
else if (auto fun = symbol->node->as<FunctionDeclaration>()) {
if (symbol->next) {
auto cur = symbol;
while (cur) {
n.candidates.push_back(cur->node->as<FunctionDeclaration>());
cur = cur->next;
}
n.type = &OverloadedFunctionType::instance;
n.node = nullptr;
}
else {
n.node = fun;
n.type = fun->declarationType;
}
}
else {
error(n, "Unhandled symbol kind.");
return;
}
}
void NameResolver::visit(ReturnStatement& n) {
if (n.expression) {
visitChild(n.expression);
}
}
void NameResolver::visit(ExpressionStatement& n) {
visitChild(n.expression);
}
void NameResolver::visit(CallExpression& n) {
visitChild(n.callTarget);
visitChildren(n.arguments);
}
void NameResolver::visit(BlockStatement& n) {
auto oldscope = scope;
scope = new Scope(scope);
visitChildren(n.statements);
delete scope;
scope = oldscope;
}
void NameResolver::visit(BinopExpression& n) {
visitChild(n.left);
visitChild(n.right);
}
void NameResolver::visit(CastExpression& n) {
visitChild(n.sourceExpression);
visitChild(n.targetTypeExpression);
}
void NameResolver::visit(ScopeExpression& n) {
visitChild(n.scopeTarget);
}
void NameResolver::visit(IfStatement& n) {
visitChild(n.condition);
visitChild(n.trueBranch);
if (n.falseBranch) {
visitChild(n.falseBranch);
}
}
void NameResolver::resolve(FieldDeclaration& n) {
visitChild(n.typeExpression);
n.declarationType = n.typeExpression->typeValue;
}
void NameResolver::visit(NewExpression& n) {
visitChild(n.typeExpression);
visitChildren(n.arguments);
}
void NameResolver::visit(AssignExpression& n) {
visitChild(n.left);
visitChild(n.right);
}
void NameResolver::visit(WhileStatement& n) {
visitChild(n.condition);
visitChild(n.body);
}
void NameResolver::visit(PostfixExpression& n) {
visitChild(n.target);
}
void NameResolver::visit(ArrayTypeExpression& n) {
visitChild(n.baseTypeExpression);
n.type = &TypeType::instance;
if (n.baseTypeExpression->typeValue == &InvalidType::instance) {
return;
}
n.typeValue = ArrayType::get(n.baseTypeExpression->typeValue);
}
void NameResolver::resolve(ImportStatement& n) {
if (n.all) {
for (auto&& fun: n.module->functions) {
if (fun->isExported) {
scope->add(fun->name, fun);
}
}
for (auto&& cls: n.module->classes) {
if (cls->isExported) {
scope->add(cls->_name, cls);
}
}
for (auto&& iface: n.module->interfaces) {
if (iface->isExported) {
scope->add(iface->_name, iface);
}
}
for (auto&& en: n.module->enums) {
if (en->isExported) {
scope->add(en->_name, en);
}
}
for (auto&& alias: n.module->typeAliases) {
if (alias->isExported) {
scope->add(alias->_name, alias);
}
}
}
else if (n.importModule) {
scope->add(n.parts.back(), n.module);
}
else {
auto cls = n.module->getClass(n.parts.back());
if (cls) {
if (cls->isExported) {
scope->add(cls->_name, cls);
return;
}
}
auto en = n.module->getEnum(n.parts.back());
if (en) {
if (en->isExported) {
scope->add(en->_name, en);
return;
}
}
auto funs = n.module->getFunctions(n.parts.back());
if (!funs.empty()) {
for (auto&& fun: funs) {
if (fun->isExported) {
scope->add(fun->name, fun);
}
}
return;
}
auto alias = n.module->getAlias(n.parts.back());
if (alias) {
if (alias->isExported) {
scope->add(alias->_name, alias);
return;
}
}
// nothing found
error(n, "Symbol '" + n.parts.back() + "' not found in module '" + n.getBaseName() + "'");
}
}
void NameResolver::visit(UnaryExpression& n) {
visitChild(n.target);
}
void NameResolver::visit(ArrayLitExpression& n) {
visitChildren(n.elements);
}
void NameResolver::visit(MapLitExpression& n) {
visitChildren(n.keys);
visitChildren(n.values);
}
void NameResolver::visit(SubscriptExpression& n) {
visitChildren(n.arguments);
visitChild(n.callTarget);
}
void NameResolver::resolve(InterfaceDeclaration& n) {
for (auto& field: n.fields) {
resolve(*field);
}
for (auto& method: n.methods) {
resolve(*method);
}
}
void NameResolver::visit(NullableTypeExpression& n) {
visitChild(n.baseTypeExpression);
n.type = &TypeType::instance;
n.typeValue = UnionType::get(n.baseTypeExpression->typeValue, &NullType::instance);
}
void NameResolver::visit(GenericReificationExpression& n) {
visitChild(n.baseTypeExpression);
visitChildren(n.genericArguments);
auto cls = n.baseTypeExpression->typeValue->as<ClassDeclaration>();
if (!cls) {
error(n, "Can not reify non-class type '" + n.baseTypeExpression->typeValue->getFullName() + "'.");
return;
}
if (cls->genericParams.empty()) {
error(n, "Can not reify non-generic class '" + n.baseTypeExpression->typeValue->getFullName() + "'.");
return;
}
if (cls->genericParams.size() != n.genericArguments.size()) {
error(n, "Expected " + std::to_string(cls->genericParams.size()) + " type arguments, " + std::to_string(n.genericArguments.size()) + " given.");
return;
}
std::vector<TypeDeclaration*> types;
for (auto&& tex: n.genericArguments) {
types.push_back(tex->typeValue);
}
n.type = &TypeType::instance;
n.typeValue = cls->getReifiedClass(types);
}
void NameResolver::resolve(InterfaceFieldDeclaration& n) {
visitChild(n.typeExpression);
n.declarationType = n.typeExpression->typeValue;
}
void NameResolver::resolve(InterfaceMethodDeclaration& n) {
visitChild(n.returnTypeExpression);
for (auto& param: n.parameters) {
resolve(*param);
}
std::vector<TypeDeclaration*> parameterTypes;
for (auto&& param: n.parameters) {
parameterTypes.push_back(param->typeExpression->typeValue);
}
n.type = FunctionType::get(n.returnTypeExpression ? n.returnTypeExpression->typeValue : &VoidType::instance, parameterTypes);
}
void NameResolver::resolve(TypeAliasDeclaration& n) {
visitChild(n.typeExpression);
}
} | 29.656863 | 156 | 0.489388 | skylang |
ae9a13d3156789aad35cc8543f005084e5810bf1 | 637 | hpp | C++ | mc/util/util.hpp | ShamylZakariya/MarchingCubes | 27f375d5d25df2246095d65c11127aac82a24211 | [
"MIT"
] | 2 | 2019-12-03T05:52:57.000Z | 2021-05-21T18:17:52.000Z | mc/util/util.hpp | ShamylZakariya/MarchingCubes | 27f375d5d25df2246095d65c11127aac82a24211 | [
"MIT"
] | null | null | null | mc/util/util.hpp | ShamylZakariya/MarchingCubes | 27f375d5d25df2246095d65c11127aac82a24211 | [
"MIT"
] | null | null | null | //
// util.h
// MarchingCubes
//
// Created by Shamyl Zakariya on 11/23/19.
// Copyright © 2019 Shamyl Zakariya. All rights reserved.
//
#ifndef mc_util_h
#define mc_util_h
#include <limits>
#include <epoxy/gl.h>
#include <GLFW/glfw3.h>
#define GLM_FORCE_RADIANS
#define GLM_ENABLE_EXPERIMENTAL
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/hash.hpp>
#include <glm/gtx/norm.hpp>
#include "aabb.hpp"
#include "color.hpp"
#include "io.hpp"
#include "lines.hpp"
#include "storage.hpp"
#include "thread_pool.hpp"
#include "unowned_ptr.hpp"
#endif /* mc_util_h */
| 18.2 | 58 | 0.723705 | ShamylZakariya |
ae9b27522e2872325c204e78afd9a852cb3d1b01 | 376 | cpp | C++ | Ch_15_On_the_Importance_of_Sampling/ao_sampler.cpp | BobLChen/ray-tracing-gems | 76f81fc9d575be0ff30665f659341e97d1d434ad | [
"MIT"
] | 2 | 2021-08-19T08:49:25.000Z | 2021-12-25T15:35:35.000Z | Ch_15_On_the_Importance_of_Sampling/ao_sampler.cpp | RobertBeckebans/ray-tracing-gems | 32f067d162041a400f50ae598a7177b2ee6b37a0 | [
"MIT"
] | null | null | null | Ch_15_On_the_Importance_of_Sampling/ao_sampler.cpp | RobertBeckebans/ray-tracing-gems | 32f067d162041a400f50ae598a7177b2ee6b37a0 | [
"MIT"
] | 1 | 2021-08-19T08:49:26.000Z | 2021-08-19T08:49:26.000Z | float ao(float3 p, float3 n, int nSamples) {
float a = 0;
for (int i = 0; i < nSamples; ++i) {
float xi[2] = { rng(), rng() };
float3 dir(sqrt(xi[0]) * cos(2 * Pi * xi[1]),
sqrt(xi[0]) * sin(2 * Pi * xi[1]),
sqrt(1 - xi[0]));
dir = transformToFrame(n, dir);
if (visible(p, dir)) a += 1;
}
return a / nSamples;
}
| 28.923077 | 50 | 0.460106 | BobLChen |
ae9bdb650abb4ef1eb056d8cb4836dfce392d1f8 | 35 | cpp | C++ | Ciao/src/utils/bvh/Bbox.cpp | dfnzhc/Ciao | 751501b69e9d2eb3e9cf53be07def8989e921b92 | [
"MIT"
] | 1 | 2021-07-15T14:19:27.000Z | 2021-07-15T14:19:27.000Z | Ciao/src/utils/bvh/Bbox.cpp | dfnzhc/OpenGL-Renderer | 751501b69e9d2eb3e9cf53be07def8989e921b92 | [
"MIT"
] | null | null | null | Ciao/src/utils/bvh/Bbox.cpp | dfnzhc/OpenGL-Renderer | 751501b69e9d2eb3e9cf53be07def8989e921b92 | [
"MIT"
] | null | null | null | #include "pch.h"
#include "Bbox.h"
| 11.666667 | 17 | 0.657143 | dfnzhc |
ae9ec94361a04c9a5cea2d7fe9666d5b8e2c8df9 | 1,365 | cpp | C++ | LeetCode/34.Find_First_and_Last_Position_of_Element_in_Sorted_Array.cpp | w181496/OJ | 67d1d32770376865eba8a9dd1767e97dae68989a | [
"MIT"
] | 9 | 2017-10-08T16:22:03.000Z | 2021-08-20T09:32:17.000Z | LeetCode/34.Find_First_and_Last_Position_of_Element_in_Sorted_Array.cpp | w181496/OJ | 67d1d32770376865eba8a9dd1767e97dae68989a | [
"MIT"
] | null | null | null | LeetCode/34.Find_First_and_Last_Position_of_Element_in_Sorted_Array.cpp | w181496/OJ | 67d1d32770376865eba8a9dd1767e97dae68989a | [
"MIT"
] | 2 | 2018-01-15T16:35:44.000Z | 2019-03-21T18:30:04.000Z | // 二分搜兩次(左,右)
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int l = 0, r = nums.size() - 1;
vector<int>ans;
while(l <= r) {
int m = (l + r) >> 1;
if(nums[m] == target) {
if(m > 0 && nums[m - 1] == target) {
r = m;
} else {
ans.push_back(m);
break;
}
} else if(nums[m] < target) {
l = m + 1;
} else {
r = m;
}
if(l == r && nums[l] != target) break;
}
if(nums.size() == 0 || l > r || (l == r && nums[l] != target)) {
ans.push_back(-1);
ans.push_back(-1);
return ans;
}
l = 0;
r = nums.size() - 1;
while(l <= r) {
int m = (l + r) >> 1;
if(nums[m] == target) {
if(m < nums.size() - 1 && nums[m + 1] == target) {
l = m + 1;
} else {
ans.push_back(m);
break;
}
} else if(nums[m] < target) {
l = m + 1;
} else {
r = m;
}
if(l == r && nums[l] != target) break;
}
return ans;
}
};
| 27.857143 | 72 | 0.301832 | w181496 |
aea1a9b1eec06c63097cc1170044f0e860f13f35 | 1,800 | cpp | C++ | gloo/gl_wrapper/Framebuffer.cpp | LongerZrLong/gloo | a198ef25a6a6a495be4aaa8182121201cd9eafa1 | [
"MIT"
] | null | null | null | gloo/gl_wrapper/Framebuffer.cpp | LongerZrLong/gloo | a198ef25a6a6a495be4aaa8182121201cd9eafa1 | [
"MIT"
] | null | null | null | gloo/gl_wrapper/Framebuffer.cpp | LongerZrLong/gloo | a198ef25a6a6a495be4aaa8182121201cd9eafa1 | [
"MIT"
] | null | null | null | #include "Framebuffer.h"
#include <stdexcept>
#include "gloo/utils.h"
namespace GLOO {
Framebuffer::Framebuffer()
{
GL_CHECK(glGenFramebuffers(1, &handle_));
}
Framebuffer::~Framebuffer()
{
if (handle_ != GLuint(-1))
GL_CHECK(glDeleteFramebuffers(1, &handle_));
}
Framebuffer::Framebuffer(Framebuffer &&other) noexcept
{
handle_ = other.handle_;
other.handle_ = GLuint(-1);
}
Framebuffer &Framebuffer::operator=(Framebuffer &&other) noexcept
{
handle_ = other.handle_;
other.handle_ = GLuint(-1);
return *this;
}
void Framebuffer::Bind() const
{
GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, handle_));
}
void Framebuffer::Unbind() const
{
GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, 0));
}
void Framebuffer::AssociateTexture(const Texture &texture, GLenum attachment)
{
Bind();
// Make sure you use GL_CHECK to detect potential errors.
GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER,
attachment,
GL_TEXTURE_2D,
texture.GetHandle(),
0));
GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (status != GL_FRAMEBUFFER_COMPLETE)
{
throw std::runtime_error("Incomplete framebuffer!");
}
Unbind();
}
static_assert(std::is_move_constructible<Framebuffer>(), "");
static_assert(std::is_move_assignable<Framebuffer>(), "");
static_assert(!std::is_copy_constructible<Framebuffer>(), "");
static_assert(!std::is_copy_assignable<Framebuffer>(), "");
} // namespace GLOO
| 26.086957 | 81 | 0.579444 | LongerZrLong |
0006e7d41b8c2c9f13cd8badcd7dd5a8f46a92f2 | 1,591 | cpp | C++ | samples/vxSobel3x3Node/vxSobel3x3Node.cpp | HipaccVX/HipaccVX | 0d469748df11c95f916b5a70f0006878f8550e3c | [
"MIT"
] | 1 | 2021-06-08T08:58:54.000Z | 2021-06-08T08:58:54.000Z | samples/vxSobel3x3Node/vxSobel3x3Node.cpp | HipaccVX/HipaccVX | 0d469748df11c95f916b5a70f0006878f8550e3c | [
"MIT"
] | 1 | 2021-11-13T14:55:55.000Z | 2021-11-13T14:55:55.000Z | samples/vxSobel3x3Node/vxSobel3x3Node.cpp | HipaccVX/HipaccVX | 0d469748df11c95f916b5a70f0006878f8550e3c | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "VX/vx.h"
#include "VX/vx_compatibility.h"
#include "hipaVX/domVX_extensions.hpp"
#define GEN_TEST_IMAGE
#ifdef GEN_TEST_IMAGE
#define IMAGE ""
#ifndef WIDTH
#define WIDTH 4032
#endif
#ifndef HEIGHT
#define HEIGHT 3024
#endif
#else
#define IMAGE "img/fuerte_ship.jpg"
#define WIDTH 4032
#define HEIGHT 3024
#endif
int main(int argc, char *argv[]) {
#ifdef HIPAVX_OUTPUT_FILENAME
set_output_filename(HIPAVX_OUTPUT_FILENAME);
#endif
vx_context context = vxCreateContext();
vx_status status = VX_FAILURE;
if (context) {
vx_graph graph = vxCreateGraph(context);
vx_image img[] = {
vxCreateImageFromFile(context, WIDTH, HEIGHT, VX_DF_IMAGE_U8, IMAGE),
vxCreateImage(context, WIDTH, HEIGHT, VX_DF_IMAGE_S16),
vxCreateImage(context, WIDTH, HEIGHT, VX_DF_IMAGE_S16)
};
if (graph) {
vx_node nodes[] = {
vxSobel3x3Node(graph, img[0], img[1], img[2]),
};
}
status = vxVerifyGraph(graph);
if (status == VX_SUCCESS) {
vxWriteImageAfterGraphCompletion(graph, img[1], "./vxSobel3x3Node_1.png");
vxWriteImageAfterGraphCompletion(graph, img[2], "./vxSobel3x3Node_2.png");
status = vxProcessGraph(graph);
} else {
printf("VERIFICATION ERROR: %d\n", status);
}
for (int i = 0; i < 3; i++) vxReleaseImage(&img[i]);
}
vxReleaseContext(&context);
return status;
}
| 24.476923 | 86 | 0.626021 | HipaccVX |
0008e813424aec01d42bb2f95fd4ddb1289151dc | 30,963 | cpp | C++ | Source/System/Math/Algebra/Quaternion.cpp | arian153/Engine-5 | 34f85433bc0a74a7ebe7da350d3f3698de77226e | [
"MIT"
] | 2 | 2020-01-09T07:48:24.000Z | 2020-01-09T07:48:26.000Z | Source/System/Math/Algebra/Quaternion.cpp | arian153/Engine-5 | 34f85433bc0a74a7ebe7da350d3f3698de77226e | [
"MIT"
] | null | null | null | Source/System/Math/Algebra/Quaternion.cpp | arian153/Engine-5 | 34f85433bc0a74a7ebe7da350d3f3698de77226e | [
"MIT"
] | null | null | null |
#include "Quaternion.hpp"
#include "Matrix33.hpp"
#include "Vector3.hpp"
#include "..//Utility/Utility.hpp"
#include <ostream>
#include "../Utility/VectorDef.hpp"
#include <sstream>
namespace Engine5
{
Quaternion::Quaternion(Real r, Real i, Real j, Real k)
: r(r), i(i), j(j), k(k)
{
}
Quaternion::Quaternion(const Vector3& from, const Vector3& to)
{
Set(from, to);
}
Quaternion::Quaternion(const Vector3& vector)
{
Set(vector);
}
Quaternion::Quaternion(const Matrix33& rotation_matrix)
{
Set(rotation_matrix);
}
Quaternion::Quaternion(const AxisRadian& axis_radian)
{
Set(axis_radian);
}
Quaternion::Quaternion(const EulerAngle& euler_angle)
{
Set(euler_angle);
}
Quaternion::Quaternion(const Vector3& axis, Real radian)
{
Set(axis, radian);
}
Quaternion::Quaternion(const Quaternion& rhs)
: r(rhs.r), i(rhs.i), j(rhs.j), k(rhs.k)
{
}
Quaternion::~Quaternion()
{
}
void Quaternion::Set(Real _r, Real _i, Real _j, Real _k)
{
r = _r;
i = _i;
j = _j;
k = _k;
}
void Quaternion::Set(const Vector3& from, const Vector3& to)
{
// get axis of rotation
Vector3 axis = from.CrossProduct(to);
// get scaled cos of angle between vectors and set initial quaternion
Set(from.DotProduct(to), axis.x, axis.y, axis.z);
// quaternion at this point is ||from||*||to||*( cos(theta), r*sin(theta) )
// normalize to remove ||from||*||to|| factor
SetNormalize();
// quaternion at this point is ( cos(theta), r*sin(theta) )
// what we want is ( cos(theta/2), r*sin(theta/2) )
// set up for half angle calculation
r += 1.0f;
// now when we normalize, we'll be dividing by sqrt(2*(1+cos(theta))), which is
// what we want for r*sin(theta) to give us r*sin(theta/2)
// w will become
// 1+cos(theta)
// ----------------------
// sqrt(2*(1+cos(theta)))
// which simplifies to cos(theta/2)
// before we normalize, check if vectors are opposing
if (r <= Math::EPSILON)
{
//rotate pi radians around orthogonal vector take cross product with x axis
if (from.z * from.z > from.x * from.x)
Set(0.0f, 0.0f, from.z, -from.y);
//or take cross product with z axis
else
Set(0.0f, from.y, -from.x, 0.0f);
}
//s = sqrtf(2*(1+cos(theta)))
//Real s = sqrtf(2.0f * r); Real norm = sqrtf(r * r + i * i + j * j + k * k);
//r = s * 0.5f; i = axis.x / s; j = axis.y / s; k = axis.z / s;
//s is equal to norm. so just normalize again to get rotation quaternion.
SetNormalize();
}
void Quaternion::Set(const Vector3& axis, Real radian)
{
// if axis of rotation is zero vector, just set to identity quat
Real length = axis.LengthSquared();
if (Math::IsZero(length) == true)
{
SetIdentity();
return;
}
// take half-angle
Real half_rad = radian * 0.5f;
Real sin_theta = sinf(half_rad);
Real cos_theta = cosf(half_rad);
Real scale = sin_theta / sqrtf(length);
r = cos_theta;
i = scale * axis.x;
j = scale * axis.y;
k = scale * axis.z;
}
void Quaternion::Set(const Vector3& vector)
{
r = 0.0f;
i = vector.x;
j = vector.y;
k = vector.z;
}
void Quaternion::Set(const Matrix33& rotation_matrix)
{
Real trace = rotation_matrix.Trace();
if (trace > 0.0f)
{
Real s = sqrtf(trace + 1.0f);
r = s * 0.5f;
Real multiplier = 0.5f / s;
i = (rotation_matrix(2, 1) - rotation_matrix(1, 2)) * multiplier;
j = (rotation_matrix(0, 2) - rotation_matrix(2, 0)) * multiplier;
k = (rotation_matrix(1, 0) - rotation_matrix(0, 1)) * multiplier;
}
else
{
size_t _i = 0;
if (rotation_matrix(1, 1) > rotation_matrix(0, 0))
{
_i = 1;
}
if (rotation_matrix(2, 2) > rotation_matrix(_i, _i))
{
_i = 2;
}
size_t _j = (_i + 1) % 3;
size_t _k = (_j + 1) % 3;
Real s = sqrtf(rotation_matrix(_i, _i) - rotation_matrix(_j, _j) - rotation_matrix(_k, _k) + 1.0f);
(*this)[_i] = 0.5f * s;
Real multiplier = 0.5f / s;
r = (rotation_matrix(_k, _j) - rotation_matrix(_j, _k)) * multiplier;
(*this)[_j] = (rotation_matrix(_j, _i) + rotation_matrix(_i, _j)) * multiplier;
(*this)[_k] = (rotation_matrix(_k, _i) + rotation_matrix(_i, _k)) * multiplier;
}
}
void Quaternion::Set(const AxisRadian& axis_radian)
{
// if axis of rotation is zero vector, just set to identity quat
Real length = axis_radian.axis.LengthSquared();
if (Math::IsZero(length) == true)
{
SetIdentity();
return;
}
// take half-angle
Real half_rad = axis_radian.radian * 0.5f;
Real sin_theta = sinf(half_rad);
Real cos_theta = cosf(half_rad);
Real scale = sin_theta / sqrtf(length);
r = cos_theta;
i = scale * axis_radian.axis.x;
j = scale * axis_radian.axis.y;
k = scale * axis_radian.axis.z;
}
void Quaternion::Set(const EulerAngle& euler_angle)
{
Real roll = euler_angle.x_rotation * .5f;
Real pitch = euler_angle.y_rotation * .5f;
Real yaw = euler_angle.z_rotation * .5f;
Real cos_roll = cosf(roll);
Real sin_roll = sinf(roll);
Real cos_pitch = cosf(pitch);
Real sin_pitch = sinf(pitch);
Real cos_yaw = cosf(yaw);
Real sin_yaw = sinf(yaw);
r = cos_roll * cos_pitch * cos_yaw + sin_roll * sin_pitch * sin_yaw;
i = sin_roll * cos_pitch * cos_yaw - cos_roll * sin_pitch * sin_yaw;
j = cos_roll * sin_pitch * cos_yaw + sin_roll * cos_pitch * sin_yaw;
k = cos_roll * cos_pitch * sin_yaw - sin_roll * sin_pitch * cos_yaw;
}
void Quaternion::Set(const Quaternion& rhs)
{
r = rhs.r;
i = rhs.i;
j = rhs.j;
k = rhs.k;
}
void Quaternion::SetNormalize()
{
Real d = r * r + i * i + j * j + k * k;
// Check for zero length quaternion,
//and use the no-rotation quaternion in that case.
if (Math::IsZero(d) == true)
{
r = 1.0f;
return;
}
Real multiplier = Math::InvSqrt(d);//1.f / sqrtf(d);
r *= multiplier;
i *= multiplier;
j *= multiplier;
k *= multiplier;
}
void Quaternion::SetClean()
{
if (Math::IsZero(r))
r = 0.0f;
if (Math::IsZero(i))
i = 0.0f;
if (Math::IsZero(j))
j = 0.0f;
if (Math::IsZero(k))
k = 0.0f;
}
void Quaternion::SetZero()
{
r = i = j = k = 0.0f;
}
void Quaternion::SetIdentity()
{
r = 1.0f;
i = j = k = 0.0f;
}
void Quaternion::SetConjugate()
{
i = -i;
j = -j;
k = -k;
}
void Quaternion::SetInverse()
{
Real norm = r * r + i * i + j * j + k * k;
if (Math::IsZero(norm))
{
//E5_ASSERT(false, "inverse the zero quaternion");
return;
}
Real inverse_norm = 1.0f / norm;
r = inverse_norm * r;
i = -inverse_norm * i;
j = -inverse_norm * j;
k = -inverse_norm * k;
}
Real Quaternion::Norm() const
{
return sqrtf(r * r + i * i + j * j + k * k);
}
Real Quaternion::NormSquared() const
{
return (r * r + i * i + j * j + k * k);
}
bool Quaternion::IsZero() const
{
return Math::IsZero(r * r + i * i + j * j + k * k);
}
bool Quaternion::IsUnit() const
{
return Math::IsZero(1.0f - (r * r + i * i + j * j + k * k));
}
bool Quaternion::IsIdentity() const
{
return Math::IsZero(1.0f - r)
&& Math::IsZero(i)
&& Math::IsZero(j)
&& Math::IsZero(k);
}
bool Quaternion::IsEqual(const Quaternion& rhs) const
{
if (Math::IsEqual(r, rhs.r) == false)
return false;
if (Math::IsEqual(i, rhs.i) == false)
return false;
if (Math::IsEqual(j, rhs.j) == false)
return false;
if (Math::IsEqual(k, rhs.k) == false)
return false;
return true;
}
bool Quaternion::IsNotEqual(const Quaternion& rhs) const
{
if (Math::IsEqual(r, rhs.r) == false)
return true;
if (Math::IsEqual(i, rhs.i) == false)
return true;
if (Math::IsEqual(j, rhs.j) == false)
return true;
if (Math::IsEqual(k, rhs.k) == false)
return true;
return false;
}
bool Quaternion::IsLostAxis() const
{
return Math::IsZero(1.0f - r);
}
Vector3 Quaternion::ToVector() const
{
return Vector3(i, j, k);
}
Matrix33 Quaternion::ToMatrix() const
{
Matrix33 result;
if (IsUnit())
{
Real xs = i + i;
Real ys = j + j;
Real zs = k + k;
Real wx = r * xs;
Real wy = r * ys;
Real wz = r * zs;
Real xx = i * xs;
Real xy = i * ys;
Real xz = i * zs;
Real yy = j * ys;
Real yz = j * zs;
Real zz = k * zs;
result.data[0] = 1.0f - (yy + zz);
result.data[1] = xy - wz;
result.data[2] = xz + wy;
result.data[3] = xy + wz;
result.data[4] = 1.0f - (xx + zz);
result.data[5] = yz - wx;
result.data[6] = xz - wy;
result.data[7] = yz + wx;
result.data[8] = 1.0f - (xx + yy);
}
return result;
}
AxisRadian Quaternion::ToAxisRadian() const
{
Real radian = 2.0f * acosf(r);
Real length = sqrtf(1.0f - (r * r));
Vector3 axis = Math::Vector3::Y_AXIS;
if (Math::IsZero(length) == false)
{
length = 1.0f / length;
axis.Set(i * length, j * length, k * length);
}
return AxisRadian(axis, radian);
}
EulerAngle Quaternion::ToEulerAngle() const
{
Real roll = atan2f(2.f * (r * i + j * k), 1.f - (2.f * (i * i + j * j)));
Real pitch;
Real sin_pitch = 2.f * (r * j - k * i);
if (fabsf(sin_pitch) >= 1)
pitch = copysignf(Math::HALF_PI, sin_pitch); // use 90 degrees if out of range
else
pitch = asinf(sin_pitch);
Real yaw = atan2f(2.f * (r * k + i * j), 1.f - (2.f * (j * j + k * k)));
return EulerAngle(roll, pitch, yaw);
}
Quaternion Quaternion::Conjugate() const
{
return Quaternion(r, -i, -j, -k);
}
Quaternion Quaternion::Inverse() const
{
Real norm = r * r + i * i + j * j + k * k;
// if we're the zero quaternion, just return
if (Math::IsZero(norm))
return Quaternion(r, i, j, k);
Real inverse_norm = 1.0f / norm;
return Quaternion(inverse_norm * r, -inverse_norm * i, -inverse_norm * j, -inverse_norm * k);
}
Real Quaternion::DotProduct(const Quaternion& quaternion) const
{
return (r * quaternion.r + i * quaternion.i + j * quaternion.j + k * quaternion.k);
}
Vector3 Quaternion::Rotate(const Vector3& vector) const
{
if (IsUnit() == true)
{
Real v_multiplier = 2.0f * (i * vector.x + j * vector.y + k * vector.z);
Real c_multiplier = 2.0f * r;
Real p_multiplier = c_multiplier * r - 1.0f;
return Vector3(
p_multiplier * vector.x + v_multiplier * i + c_multiplier * (j * vector.z - k * vector.y),
p_multiplier * vector.y + v_multiplier * j + c_multiplier * (k * vector.x - i * vector.z),
p_multiplier * vector.z + v_multiplier * k + c_multiplier * (i * vector.y - j * vector.x));
}
//"Rotate non-unit quaternion"
return Vector3();
}
Vector3 Quaternion::RotateVector(const Vector3& vector) const
{
Quaternion inverse = Inverse();
Quaternion given_vector(0.0f, vector.x, vector.y, vector.z);
//calculate qpq^-1
Quaternion result = ((*this) * given_vector) * inverse;
return Vector3(result.i, result.j, result.k);
}
Quaternion Quaternion::Multiply(const Quaternion& rhs) const
{
return Quaternion(
r * rhs.r - i * rhs.i - j * rhs.j - k * rhs.k,
r * rhs.i + i * rhs.r + j * rhs.k - k * rhs.j,
r * rhs.j + j * rhs.r + k * rhs.i - i * rhs.k,
r * rhs.k + k * rhs.r + i * rhs.j - j * rhs.i);
}
void Quaternion::AddRotation(const Vector3& axis, Real radian)
{
Quaternion quaternion(AxisRadian(axis, radian));
*this = quaternion * (*this);
SetNormalize();
}
void Quaternion::AddRotation(const Quaternion& quaternion)
{
(*this) = quaternion * (*this);
SetNormalize();
}
void Quaternion::AddRadian(Real radian)
{
Real curr_rad = 2.0f * acosf(r);
Real length = sqrtf(1.0f - (r * r));
Vector3 axis = Math::Vector3::Y_AXIS;
Real half_rad = (curr_rad + radian) * 0.5f;
Real sin_theta = sinf(half_rad);
Real cos_theta = cosf(half_rad);
if (Math::IsZero(length) == false)
{
length = 1.0f / length;
axis.Set(i * length, j * length, k * length);
r = cos_theta;
i = sin_theta * axis.x;
j = sin_theta * axis.y;
k = sin_theta * axis.z;
}
}
void Quaternion::ChangeAxis(const Vector3& axis)
{
Real radian = 2.0f * acosf(r);
Real length = sqrtf(1.0f - (r * r));
Real axis_length = axis.LengthSquared();
if (Math::IsZero(length) == false && Math::IsZero(axis_length) == false)
{
Real half_rad = (radian) * 0.5f;
Real sin_theta = sinf(half_rad);
Real cos_theta = cosf(half_rad);
axis_length = 1.0f / axis_length;
Real scale = sin_theta / sqrtf(axis_length);
r = cos_theta;
i = scale * axis.x;
j = scale * axis.y;
k = scale * axis.z;
}
}
Quaternion Quaternion::operator-() const
{
return Quaternion(-r, -i, -j, -k);
}
Quaternion& Quaternion::operator=(const Quaternion& rhs)
{
if (this != &rhs)
{
r = rhs.r;
i = rhs.i;
j = rhs.j;
k = rhs.k;
}
return *this;
}
bool Quaternion::operator==(const Quaternion& rhs) const
{
if (Math::IsEqual(r, rhs.r) == false)
return false;
if (Math::IsEqual(i, rhs.i) == false)
return false;
if (Math::IsEqual(j, rhs.j) == false)
return false;
if (Math::IsEqual(k, rhs.k) == false)
return false;
return true;
}
bool Quaternion::operator!=(const Quaternion& rhs) const
{
if (Math::IsEqual(r, rhs.r) == false)
return true;
if (Math::IsEqual(i, rhs.i) == false)
return true;
if (Math::IsEqual(j, rhs.j) == false)
return true;
if (Math::IsEqual(k, rhs.k) == false)
return true;
return false;
}
Real Quaternion::operator[](size_t _i) const
{
return (&i)[_i];
}
Real& Quaternion::operator[](size_t _i)
{
return (&i)[_i];
}
Quaternion Quaternion::operator*(const Quaternion& rhs) const
{
return Quaternion(
r * rhs.r - i * rhs.i - j * rhs.j - k * rhs.k,
r * rhs.i + i * rhs.r + j * rhs.k - k * rhs.j,
r * rhs.j + j * rhs.r + k * rhs.i - i * rhs.k,
r * rhs.k + k * rhs.r + i * rhs.j - j * rhs.i);
}
Quaternion& Quaternion::operator*=(const Quaternion& rhs)
{
auto q = *this;
r = q.r * rhs.r - q.i * rhs.i - q.j * rhs.j - q.k * rhs.k;
i = q.r * rhs.i + q.i * rhs.r + q.j * rhs.k - q.k * rhs.j;
j = q.r * rhs.j + q.j * rhs.r + q.k * rhs.i - q.i * rhs.k;
k = q.r * rhs.k + q.k * rhs.r + q.i * rhs.j - q.j * rhs.i;
return *this;
}
Quaternion Quaternion::operator*(const Vector3& vector) const
{
return Quaternion(
- i * vector.x - j * vector.y - k * vector.z,
r * vector.x + j * vector.z - k * vector.y,
r * vector.y + k * vector.x - i * vector.z,
r * vector.z + i * vector.y - j * vector.x);
}
Matrix33 Quaternion::operator*(const Matrix33& matrix) const
{
Matrix33 result;
if (IsUnit())
{
result.data[0] = (1.0f - 2.0f * (j * j + k * k)) * matrix.data[0] + 2.0f * (i * j - r * k) * matrix.data[3] + 2.0f * (i * k + r * j) * matrix.data[6];
result.data[1] = (1.0f - 2.0f * (j * j + k * k)) * matrix.data[1] + 2.0f * (i * j - r * k) * matrix.data[4] + 2.0f * (i * k + r * j) * matrix.data[7];
result.data[2] = (1.0f - 2.0f * (j * j + k * k)) * matrix.data[2] + 2.0f * (i * j - r * k) * matrix.data[5] + 2.0f * (i * k + r * j) * matrix.data[8];
result.data[3] = 2.0f * (i * j + r * k) * matrix.data[0] + (1.0f - 2.0f * (i * i + k * k)) * matrix.data[3] + 2.0f * (j * k - r * i) * matrix.data[6];
result.data[4] = 2.0f * (i * j + r * k) * matrix.data[1] + (1.0f - 2.0f * (i * i + k * k)) * matrix.data[4] + 2.0f * (j * k - r * i) * matrix.data[7];
result.data[5] = 2.0f * (i * j + r * k) * matrix.data[2] + (1.0f - 2.0f * (i * i + k * k)) * matrix.data[5] + 2.0f * (j * k - r * i) * matrix.data[8];
result.data[6] = 2.0f * (i * k - r * j) * matrix.data[0] + 2.0f * (j * k + r * i) * matrix.data[3] + (1.0f - 2.0f * (i * i + j * j)) * matrix.data[6];
result.data[7] = 2.0f * (i * k - r * j) * matrix.data[1] + 2.0f * (j * k + r * i) * matrix.data[4] + (1.0f - 2.0f * (i * i + j * j)) * matrix.data[7];
result.data[8] = 2.0f * (i * k - r * j) * matrix.data[2] + 2.0f * (j * k + r * i) * matrix.data[5] + (1.0f - 2.0f * (i * i + j * j)) * matrix.data[8];
}
return result;
}
Quaternion Quaternion::operator+(const Quaternion& rhs) const
{
return Quaternion(r + rhs.r, i + rhs.i, j + rhs.j, k + rhs.k);
}
Quaternion& Quaternion::operator+=(const Quaternion& rhs)
{
r += rhs.r;
i += rhs.i;
j += rhs.j;
k += rhs.k;
return *this;
}
Quaternion Quaternion::operator-(const Quaternion& rhs) const
{
return Quaternion(r - rhs.r, i - rhs.i, j - rhs.j, k - rhs.k);
}
Quaternion& Quaternion::operator-=(const Quaternion& rhs)
{
r -= rhs.r;
i -= rhs.i;
j -= rhs.j;
k -= rhs.k;
return *this;
}
Quaternion Quaternion::operator*(Real scalar) const
{
return Quaternion(r * scalar, i * scalar, j * scalar, k * scalar);
}
Quaternion& Quaternion::operator*=(Real scalar)
{
r *= scalar;
i *= scalar;
j *= scalar;
k *= scalar;
return *this;
}
Quaternion operator*(const Vector3& vector, const Quaternion& quaternion)
{
return Quaternion(
-vector.x * quaternion.i - vector.y * quaternion.j - vector.z * quaternion.k,
+vector.x * quaternion.r + vector.y * quaternion.k - vector.z * quaternion.j,
+vector.y * quaternion.r + vector.z * quaternion.i - vector.x * quaternion.k,
+vector.z * quaternion.r + vector.x * quaternion.j - vector.y * quaternion.i);
}
Matrix33 operator*(const Matrix33& matrix, const Quaternion& quaternion)
{
Matrix33 result;
if (quaternion.IsUnit())
{
result.data[0] = matrix.data[0] * (1.0f - 2.0f * (quaternion.j * quaternion.j + quaternion.k * quaternion.k))
+ 2.0f * matrix.data[1] * (quaternion.i * quaternion.j + quaternion.r * quaternion.k)
+ 2.0f * matrix.data[2] * (quaternion.i * quaternion.k - quaternion.r * quaternion.j);
result.data[1] = matrix.data[1] * (1.0f - 2.0f * (quaternion.i * quaternion.i + quaternion.k * quaternion.k))
+ 2.0f * matrix.data[0] * (quaternion.i * quaternion.j - quaternion.r * quaternion.k)
+ 2.0f * matrix.data[2] * (quaternion.j * quaternion.k + quaternion.r * quaternion.i);
result.data[2] = matrix.data[2] * (1.0f - 2.0f * (quaternion.i * quaternion.i + quaternion.j * quaternion.j))
+ 2.0f * matrix.data[0] * (quaternion.i * quaternion.k + quaternion.r * quaternion.j)
+ 2.0f * matrix.data[1] * (quaternion.j * quaternion.k - quaternion.r * quaternion.i);
result.data[3] = matrix.data[3] * (1.0f - 2.0f * (quaternion.j * quaternion.j + quaternion.k * quaternion.k))
+ 2.0f * matrix.data[4] * (quaternion.i * quaternion.j + quaternion.r * quaternion.k)
+ 2.0f * matrix.data[5] * (quaternion.i * quaternion.k - quaternion.r * quaternion.j);
result.data[4] = matrix.data[4] * (1.0f - 2.0f * (quaternion.i * quaternion.i + quaternion.k * quaternion.k))
+ 2.0f * matrix.data[3] * (quaternion.i * quaternion.j - quaternion.r * quaternion.k)
+ 2.0f * matrix.data[5] * (quaternion.j * quaternion.k + quaternion.r * quaternion.i);
result.data[5] = matrix.data[5] * (1.0f - 2.0f * (quaternion.i * quaternion.i + quaternion.j * quaternion.j))
+ 2.0f * matrix.data[3] * (quaternion.i * quaternion.k + quaternion.r * quaternion.j)
+ 2.0f * matrix.data[4] * (quaternion.j * quaternion.k - quaternion.r * quaternion.i);;
result.data[6] = matrix.data[6] * (1.0f - 2.0f * (quaternion.j * quaternion.j + quaternion.k * quaternion.k))
+ 2.0f * matrix.data[7] * (quaternion.i * quaternion.j + quaternion.r * quaternion.k)
+ 2.0f * matrix.data[8] * (quaternion.i * quaternion.k - quaternion.r * quaternion.j);
result.data[7] = matrix.data[7] * (1.0f - 2.0f * (quaternion.i * quaternion.i + quaternion.k * quaternion.k))
+ 2.0f * matrix.data[6] * (quaternion.i * quaternion.j - quaternion.r * quaternion.k)
+ 2.0f * matrix.data[8] * (quaternion.j * quaternion.k + quaternion.r * quaternion.i);
result.data[8] = matrix.data[8] * (1.0f - 2.0f * (quaternion.i * quaternion.i + quaternion.j * quaternion.j))
+ 2.0f * matrix.data[6] * (quaternion.i * quaternion.k + quaternion.r * quaternion.j)
+ 2.0f * matrix.data[7] * (quaternion.j * quaternion.k - quaternion.r * quaternion.i);
}
return result;
}
Quaternion Quaternion::Identity()
{
return Quaternion();
}
Quaternion Conjugate(const Quaternion& quaternion)
{
return quaternion.Conjugate();
}
Quaternion Inverse(const Quaternion& quaternion)
{
return quaternion.Inverse();
}
Real DotProduct(const Quaternion& quat1, const Quaternion& quat2)
{
return quat1.DotProduct(quat2);
}
Quaternion LinearInterpolation(const Quaternion& start, const Quaternion& end, Real t)
{
Real cos_theta = start.DotProduct(end);
// initialize result
Quaternion result = t * end;
// if "angle" between quaternions is less than 90 degrees
if (cos_theta >= Math::EPSILON)
{
// use standard interpolation
result += (1.0f - t) * start;
}
else
{
// otherwise, take the shorter path
result += (t - 1.0f) * start;
}
return result;
}
Quaternion SphericalLinearInterpolation(const Quaternion& start, const Quaternion& end, Real t)
{
// get cosine of "angle" between quaternions
Real cos_theta = start.DotProduct(end);
Real start_interp, end_interp;
// if "angle" between quaternions is less than 90 degrees
if (cos_theta >= Math::EPSILON)
{
// if angle is greater than zero
if ((1.0f - cos_theta) > Math::EPSILON)
{
// use standard slerp
Real theta = acosf(cos_theta);
Real inv_sin_theta = 1.0f / sinf(theta);
start_interp = sinf((1.0f - t) * theta) * inv_sin_theta;
end_interp = sinf(t * theta) * inv_sin_theta;
}
// angle is close to zero
else
{
// use linear interpolation
start_interp = 1.0f - t;
end_interp = t;
}
}
// otherwise, take the shorter route
else
{
// if angle is less than 180 degrees
if ((1.0f + cos_theta) > Math::EPSILON)
{
// use slerp w/negation of start quaternion
Real theta = acosf(-cos_theta);
Real inv_sin_theta = 1.0f / sinf(theta);
start_interp = sinf((t - 1.0f) * theta) * inv_sin_theta;
end_interp = sinf(t * theta) * inv_sin_theta;
}
// angle is close to 180 degrees
else
{
// use lerp w/negation of start quaternion
start_interp = t - 1.0f;
end_interp = t;
}
}
Quaternion result = start_interp * start + end_interp * end;
return result;
}
Quaternion SwingTwistInterpolation(const Quaternion& start, const Quaternion& end, const Vector3& twist_axis, Real t)
{
Quaternion delta_rotation = end * start.Inverse();
Quaternion swing_full;
Quaternion twist_full;
Vector3 r = Vector3(delta_rotation.i, delta_rotation.j, delta_rotation.k);
// singularity: rotation by 180 degree
if (r.LengthSquared() < Math::EPSILON)
{
Vector3 rotated_twist_axis = delta_rotation.Rotate(twist_axis);
Vector3 swing_axis = twist_axis.CrossProduct(rotated_twist_axis);
if (swing_axis.LengthSquared() > Math::EPSILON)
{
Real swing_radian = Radian(twist_axis, rotated_twist_axis);
swing_full = Quaternion(swing_axis, swing_radian);
}
else
{
// more singularity:
// rotation axis parallel to twist axis
swing_full = Quaternion::Identity(); // no swing
}
// always twist 180 degree on singularity
twist_full = Quaternion(twist_axis, Math::PI);
}
else
{
// meat of swing-twist decomposition
Vector3 p = r.ProjectionTo(twist_axis);
twist_full = Quaternion(delta_rotation.r, p.x, p.y, p.z);
twist_full.SetNormalize();
swing_full = delta_rotation * twist_full.Inverse();
}
Quaternion swing = SphericalLinearInterpolation(Quaternion::Identity(), swing_full, t);
Quaternion twist = SphericalLinearInterpolation(Quaternion::Identity(), twist_full, t);
return twist * swing;
}
Quaternion operator*(Real scalar, const Quaternion& quaternion)
{
return Quaternion(scalar * quaternion.r, scalar * quaternion.i, scalar * quaternion.j, scalar * quaternion.k);
}
std::ostream& operator<<(std::ostream& os, const Quaternion& rhs)
{
if (rhs.IsUnit() == true)
{
Real radian = 2.0f * acosf(rhs.r);
Real length = sqrtf(1.0f - (rhs.r * rhs.r));
Vector3 axis = Math::Vector3::Y_AXIS;
if (Math::IsZero(length) == false)
{
length = 1.0f / length;
axis.Set(rhs.i * length, rhs.j * length, rhs.k * length);
}
Real degree = Math::RadiansToDegrees(radian);
//os << std::setprecision(3);
os << "[cos(" << degree << ") + sin(" << degree << ") * (" << axis.x << "i + " << axis.y << "j + " << axis.z << "k)]";
//os << std::setprecision(std::ios_base::precision);
}
else
{
os << "[" << rhs.r << ", " << rhs.i << ", " << rhs.j << ", " << rhs.k << "]";
}
return os;
}
std::wstringstream& operator<<(std::wstringstream& os, const Quaternion& rhs)
{
if (rhs.IsUnit() == true)
{
Real radian = 2.0f * acosf(rhs.r);
Real length = sqrtf(1.0f - (rhs.r * rhs.r));
Vector3 axis = Math::Vector3::Y_AXIS;
if (Math::IsZero(length) == false)
{
length = 1.0f / length;
axis.Set(rhs.i * length, rhs.j * length, rhs.k * length);
}
Real degree = Math::RadiansToDegrees(radian);
//os << std::setprecision(3);
os << "[cos(" << degree << ") + sin(" << degree << ") * (" << axis.x << "i + " << axis.y << "j + " << axis.z << "k)]";
//os << std::setprecision(std::ios_base::precision);
}
else
{
os << "[" << rhs.r << ", " << rhs.i << ", " << rhs.j << ", " << rhs.k << "]";
}
return os;
}
}
| 36.003488 | 162 | 0.489907 | arian153 |
000b585f9671e7db56d035f0878a003200f77418 | 5,157 | hpp | C++ | Nostra Utils/src/header/nostrautils/core/Version.hpp | Lehks/NostraUtils | ef1b2d492a1358775752a2a7621c714d86bf96b2 | [
"MIT"
] | 10 | 2018-01-07T01:00:11.000Z | 2021-09-16T14:08:45.000Z | NostraUtils/Nostra Utils/src/header/nostrautils/core/Version.hpp | Lehks/NostraEngine | 0d610dcd97ba482fd8f183795140c38728c3a6b3 | [
"MIT"
] | 107 | 2018-04-06T10:15:47.000Z | 2018-09-28T07:13:46.000Z | NostraUtils/Nostra Utils/src/header/nostrautils/core/Version.hpp | Lehks/NostraEngine | 0d610dcd97ba482fd8f183795140c38728c3a6b3 | [
"MIT"
] | null | null | null | #ifndef NOU_CORE_VERSION_HPP
#define NOU_CORE_VERSION_HPP
#include "nostrautils/core/StdIncludes.hpp"
#include "nostrautils/core/Utils.hpp"
/**
\file core/Version.hpp
\author Lukas Reichmann
\version 1.0.0
\since 1.0.0
\brief A file that contains the nostra::utils::core::Version struct.
\see nostra::utils::core::Version
*/
namespace NOU::NOU_CORE
{
/**
\brief A class that wraps around the macros from the StdIncludes.hpp that generate versions
(like NOU_MAKE_VERSION). However, this struct does not have problems with overflowing the single
parts.
*/
struct Version final
{
public:
/**
\brief The type of a version (which also serves as the type for the parts).
*/
using VersionType = decltype(NOU_MAKE_VERSION(0, 0, 0));
private:
/**
\brief The version itself.
*/
VersionType m_version;
public:
/**
\param version The version to import.
\brief Imports a version that was previously created using NOU_MAKE_VERSION.
*/
constexpr Version(VersionType version);
/**
\param major The major part of the version.
\param minor The minor part of the version.
\param patch The patch part of the version.
\brief Constructs a new version.
\details
Constructs a new version. This constructor will clamp the values of the parts to avoid overflows. The
maximum values of the parts are determined by the NOU_VERSION_*_MAX macros.
*/
constexpr Version(VersionType major, VersionType minor, VersionType patch);
/**
\return The full version.
\brief Returns the full version as generated by NOU_MAKE_VERSION.
*/
constexpr VersionType getRaw() const;
/**
\return The major part of the version.
\brief Returns the major part of the version.
*/
constexpr VersionType getMajor() const;
/**
\return The minor part of the version.
\brief Returns the major part of the version.
*/
constexpr VersionType getMinor() const;
/**
\return The patch part of the version.
\brief Returns the major part of the version.
*/
constexpr VersionType getPatch() const;
/**
\param other The version to compare this one to.
\return True, if this version is bigger than \p other, false if not.
\brief Checks if this version is bigger than \p other.
*/
constexpr boolean operator > (const Version &other) const;
/**
\param other The version to compare this one to.
\return True, if this version is bigger than or equal to \p other, false if not.
\brief Checks if this version is bigger than or equal to \p other.
*/
constexpr boolean operator >= (const Version &other) const;
/**
\param other The version to compare this one to.
\return True, if this version is smaller than \p other, false if not.
\brief Checks if this version is smaller than \p other.
*/
constexpr boolean operator < (const Version &other) const;
/**
\param other The version to compare this one to.
\return True, if this version is smaller than or equal to \p other, false if not.
\brief Checks if this version is smaller than or equal to \p other.
*/
constexpr boolean operator <= (const Version &other) const;
/**
\param other The version to compare this one to.
\return True, if this version is equal to \p other, false if not.
\brief Checks if this version is equal to \p other.
*/
constexpr boolean operator == (const Version &other) const;
/**
\param other The version to compare this one to.
\return True, if this version is unequal to \p other, false if not.
\brief Checks if this version is unequal to \p other.
*/
constexpr boolean operator != (const Version &other) const;
};
constexpr Version::Version(VersionType version) :
m_version(version)
{}
constexpr Version::Version(VersionType major, VersionType minor, VersionType patch) :
m_version(NOU_MAKE_VERSION(clamp(major, static_cast<VersionType>(0), NOU_VERSION_MAJOR_MAX),
clamp(minor, static_cast<VersionType>(0), NOU_VERSION_MINOR_MAX),
clamp(patch, static_cast<VersionType>(0), NOU_VERSION_PATCH_MAX)))
{}
constexpr typename Version::VersionType Version::getRaw() const
{
return m_version;
}
constexpr typename Version::VersionType Version::getMajor() const
{
return NOU_VERSION_MAJOR(m_version);
}
constexpr typename Version::VersionType Version::getMinor() const
{
return NOU_VERSION_MINOR(m_version);
}
constexpr typename Version::VersionType Version::getPatch() const
{
return NOU_VERSION_PATCH(m_version);
}
constexpr boolean Version::operator > (const Version &other) const
{
return getRaw() > other.getRaw();
}
constexpr boolean Version::operator >= (const Version &other) const
{
return getRaw() >= other.getRaw();
}
constexpr boolean Version::operator < (const Version &other) const
{
return getRaw() < other.getRaw();
}
constexpr boolean Version::operator <= (const Version &other) const
{
return getRaw() <= other.getRaw();
}
constexpr boolean Version::operator == (const Version &other) const
{
return getRaw() == other.getRaw();
}
constexpr boolean Version::operator != (const Version &other) const
{
return getRaw() != other.getRaw();
}
}
#endif | 25.156098 | 105 | 0.714951 | Lehks |
00117fd642dc8a5d1aa39f6f6dbc0b2e1b1e4695 | 12,157 | cpp | C++ | src/display_module.cpp | oskrs111/diy-co2-monitior | ca72bf613421732216da5af8359749af52bb49c3 | [
"MIT"
] | 8 | 2020-11-03T09:51:59.000Z | 2021-09-20T05:01:42.000Z | src/display_module.cpp | oskrs111/diy-co2-monitior | ca72bf613421732216da5af8359749af52bb49c3 | [
"MIT"
] | 2 | 2020-11-29T08:11:41.000Z | 2021-01-24T19:21:00.000Z | src/display_module.cpp | oskrs111/diy-co2-monitior | ca72bf613421732216da5af8359749af52bb49c3 | [
"MIT"
] | 3 | 2020-11-19T12:06:42.000Z | 2021-02-05T10:31:57.000Z | /*
Copyright 2020 Oscar Sanz Llopis
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 <stdint.h>
#include "module_common.h"
#include "config_module.h"
#include "sensor_module.h"
#include "display_module.h"
#include "display_module_fonts.h"
#include "display_module_icons.h"
#include "SSD1306Wire.h"
#if DEBUG_TRACES_ENABLE && DISPLAY_TRACES_ENABLE
char debug_string[256];
#endif
static struct display_preferences* preferences = 0x00;
static SSD1306Wire display(0x3c, DISPLAY_SDA_PIN, DISPLAY_SCL_PIN);
static struct st_display_data display_data;
static char display_string[64];
static uint16_t *span_average = 0x00;
void display_module_init()
{
preferences = &config_module_get_preferences()->display;
memset(&display_data, 0x00, sizeof(display_data));
display_module_historical_init();
display.init();
display.setI2cAutoInit(true);
display.flipScreenVertically();
display_module_draw_splash();
display_module_set_battery(100);
display_module_set_ipaddress((char*)"000.000");
display_module_set_ppm(0);
display_module_set_warming(0);
display_module_set_reading(0);
display_module_set_calibrating(0);
display_module_set_ble(0);
Serial.write("> display_module_init() => Done!\r\n");
}
void display_module_historical_init()
{
uint16_t t = 0;
span_average = new uint16_t[preferences->average_interval];
for(t = 1; t < (DISPLAY_MODULE_HISTORICAL_SPAN - 1); t++)
{
display_data.historical.historical_values[t].p_next = &display_data.historical.historical_values[t+1];
display_data.historical.historical_values[t].p_prev = &display_data.historical.historical_values[t-1];
display_data.historical.historical_values[t]._pos = t;
display_data.historical.historical_values[t].value = 0x00;
}
display_data.historical.historical_values[0].p_next = &display_data.historical.historical_values[1];
display_data.historical.historical_values[0].p_prev = &display_data.historical.historical_values[(DISPLAY_MODULE_HISTORICAL_SPAN - 1)];
display_data.historical.historical_values[0]._pos = 0;
display_data.historical.historical_values[0].value = 0x00;
display_data.historical.historical_values[(DISPLAY_MODULE_HISTORICAL_SPAN - 1)].p_next = &display_data.historical.historical_values[0];
display_data.historical.historical_values[(DISPLAY_MODULE_HISTORICAL_SPAN - 1)].p_prev = &display_data.historical.historical_values[(DISPLAY_MODULE_HISTORICAL_SPAN - 2)];
display_data.historical.historical_values[(DISPLAY_MODULE_HISTORICAL_SPAN - 1)]._pos = (DISPLAY_MODULE_HISTORICAL_SPAN - 1);
display_data.historical.historical_values[(DISPLAY_MODULE_HISTORICAL_SPAN - 1)].value = 0x00;
display_data.historical.p_ppm_in = &display_data.historical.historical_values[0];
display_data.historical.ppm_length = 0;
display_data.historical.ppm_max = SENSOR_MIN_PPM;
display_data.historical.ppm_min = SENSOR_MAX_PPM;
display_data.historical.ppm_maxd = SENSOR_MAX_PPM;
display_data.historical.ppm_mind = SENSOR_MIN_PPM;
}
void display_module_clear()
{
display.clear();
}
void display_module_update()
{
display.display();
}
void display_module_set_ppm(uint16_t ppm)
{
display_data.ppm = ppm;
display_module_push_historical(ppm);
}
void display_module_set_temperature(float temp)
{
display_data.temperature = temp;
}
void display_module_push_historical(uint16_t ppm)
{
static uint16_t span_average_count = 0;
struct st_ppm_value *p = 0x00;
uint16_t t = 0x00;
if((ppm == SENSOR_MIN_PPM) || (ppm == SENSOR_MAX_PPM))
{
#if DEBUG_TRACES_ENABLE && DISPLAY_TRACES_ENABLE
sprintf(&debug_string[0],"> Skip value= %d\r\n",ppm);
Serial.write(&debug_string[0]);
return;
#endif
}
if(span_average_count < preferences->average_interval)
{
span_average[span_average_count] = ppm;
span_average_count++;
#if DEBUG_TRACES_ENABLE && DISPLAY_TRACES_ENABLE
sprintf(&debug_string[0],"> Push value= %d, cnt= %d\r\n",ppm, span_average_count);
Serial.write(&debug_string[0]);
#endif
}
else
{
display_data.historical.p_ppm_in->value = display_module_get_average(&span_average[0], preferences->average_interval);
#if DEBUG_TRACES_ENABLE && DISPLAY_TRACES_ENABLE
sprintf(&debug_string[0],"> Store value [%04d]= %d, len=%d\r\n",display_data.historical.p_ppm_in->_pos, display_data.historical.p_ppm_in->value, display_data.historical.ppm_length);
Serial.write(&debug_string[0]);
#endif
display_data.historical.p_ppm_in = display_data.historical.p_ppm_in->p_next;
if(display_data.historical.ppm_length < DISPLAY_MODULE_HISTORICAL_SPAN)
{
display_data.historical.ppm_length++;
}
span_average_count = 0;
display_data.historical.ppm_max = SENSOR_MIN_PPM;
display_data.historical.ppm_min = SENSOR_MAX_PPM;
p = display_data.historical.p_ppm_in->p_prev;
for(t = 0; t < DISPLAY_MODULE_HISTORICAL_SPAN; t++)
{
if(p->value != 0)
{
display_module_max_min_update(p->value);
}
p = p->p_prev;
}
}
}
uint16_t display_module_get_average(uint16_t *data, uint16_t length)
{
uint32_t sum = 0;
uint16_t t = 0;
for(t = 0; t < length; t++)
{
sum += data[t];
}
return (uint16_t)(sum/(uint32_t)length);
}
void display_module_set_battery(uint16_t battery)
{
display_data.battery = battery;
}
void display_module_set_ipaddress(char* ipaddress)
{
if(strlen(&ipaddress[0]) < sizeof(display_data.ipaddress))
{
memcpy(&display_data.ipaddress, &ipaddress[0], strlen(&ipaddress[0]));
display_data.ipaddress[strlen(&ipaddress[0])] = 0;
}
display_module_draw_ipaddress();
}
void display_module_draw_splash()
{
display.clear();
display.drawXbm(23,0,logo_image_width,logo_image_height,&logo_image[0]);
display.setFont(ArialMT_Plain_10);
display.drawString(23,54,"diy-co2-monitor");
display.display();
}
void display_module_draw_ppm()
{
char *format = (char*)"%04d";
if(display_data.ppm < 1000)
{
format = (char*)" %03d";
}
sprintf(&display_string[0],&format[0],display_data.ppm);
display.setFont(Roboto_Black_24);
display.drawString(0,0, &display_string[0]);
display.setFont(ArialMT_Plain_10);
display.drawString(60,0,"ppm");
}
void display_module_draw_ppm_graph()
{
#define VERTICAL_START 38
#define VERTICAL_HEIGHT 30
struct st_ppm_value *p = 0x00;
uint16_t t = 0x00;
uint16_t max = display_data.historical.ppm_max;
uint16_t min = display_data.historical.ppm_min;
uint8_t x_pos = 0x00;
uint8_t y_pos = 0x00;
uint8_t step_size = 0x00;
uint8_t length = 0x00;
if(display_data.historical.ppm_length == 0x00)
{
return;
}
if((max - min) < VERTICAL_HEIGHT)
{
max = (((max + min)/2)+VERTICAL_HEIGHT);
min = (((max + min)/2)-VERTICAL_HEIGHT);
}
else
{
max += (VERTICAL_HEIGHT/4);
min -= (VERTICAL_HEIGHT/4);
}
/**< Update the main maxd/mind values in order to show same values in web dashboard*/
display_data.historical.ppm_maxd = max;
display_data.historical.ppm_mind = min;
step_size = ((max - min) / VERTICAL_HEIGHT);
step_size = (step_size == 0x00)?1:step_size;
x_pos = display_data.historical.ppm_length;
p = display_data.historical.p_ppm_in->p_prev;
for(t = display_data.historical.ppm_length; t > 0; t--)
{
length = ((p->value - min)/ step_size);
y_pos = (VERTICAL_START + (VERTICAL_HEIGHT - length));
display.drawVerticalLine(x_pos, y_pos, length);
#if 0
sprintf(&debug_string[0],"> Draw pos=%d, value= %d, x= %d, y= %d, ln= %d, st= %d, max= %d, min= %d\r\n",
p->_pos, p->value, x_pos, y_pos, length, step_size, max, min );
Serial.write(&debug_string[0]);
#endif
p = p->p_prev;
x_pos--;
}
display.drawHorizontalLine(0, 63, 64);
display.drawVerticalLine(0, VERTICAL_START, 32);
display.setFont(ArialMT_Plain_10);
sprintf(&display_string[0],"%d", max);
display.drawString(65,24,&display_string[0]);
sprintf(&display_string[0],"%d", min);
display.drawString(65,54,&display_string[0]);
}
void display_module_max_min_update(uint16_t ppm)
{
if(ppm > display_data.historical.ppm_max)
{
display_data.historical.ppm_max = ppm;
}
if(ppm < display_data.historical.ppm_min)
{
display_data.historical.ppm_min = ppm;
}
#if DEBUG_TRACES_ENABLE && DISPLAY_TRACES_ENABLE
sprintf(&debug_string[0],"> Update M/m ppm= %d, max= %d, min= %d\r\n", ppm, display_data.historical.ppm_max, display_data.historical.ppm_min);
Serial.write(&debug_string[0]);
#endif
}
void display_module_draw_battery()
{
sprintf(&display_string[0],"%d", display_data.ppm);
display.setFont(ArialMT_Plain_10);
display.drawString(104,0,&display_string[0]);
display.drawRect(102, 0, 22, 12);
display.drawRect(124, 2, 4, 8);
}
void display_module_draw_ipaddress()
{
display.setFont(ArialMT_Plain_10);
display.drawString(95,0,&display_data.ipaddress[0]);
display.drawString(89,0,"<");
}
void display_module_set_warming(uint8_t state)
{
if(state > 0 )
{
display.drawCircle(120, 40, 6);
}
else
{
display.fillCircle(120, 40, 6);
}
}
void display_module_set_ble(uint8_t state)
{
display.drawRect(112, 48, 16, 16);
}
void display_module_set_reading(uint8_t state)
{
if(state > 0 )
{
display.drawCircle(120, 57, 6);
}
else
{
display.fillCircle(120, 57, 6);
}
}
void display_module_set_calibrating(uint8_t state)
{
display.drawRect(112, 32, 16, 16);
}
void display_module_defaults(struct display_preferences* preferences)
{
preferences->average_interval = DISPLAY_MODULE_AVERAGE_INTERVAL_DEFAULT;
}
char* display_module_historical_2_json()
{
static char buffer[((DISPLAY_MODULE_HISTORICAL_SPAN * 5) + 64)];
struct st_ppm_value *p = 0x00;
char* j = &buffer[0];
memset(j, 0x00, sizeof(buffer));
j += sprintf(j,"\"historical\":{\"span\":%d, \"interval\":%d, \"max\":%d, \"min\":%d, \"data\":[",
DISPLAY_MODULE_HISTORICAL_SPAN,
DISPLAY_MODULE_AVERAGE_INTERVAL_DEFAULT,
display_data.historical.ppm_maxd,
display_data.historical.ppm_mind);
p = display_data.historical.p_ppm_in->p_prev;
for(uint16_t t = display_data.historical.ppm_length; t > 0; t--)
{
j += sprintf(j,"%d,", p->value);
p = p->p_prev;
}
if(display_data.historical.ppm_length > 0x00) j--; /**< To remove the last ',' */
j += sprintf(j,"]}");
return &buffer[0]; /**< [0] position is the most recent measure */
} | 34.24507 | 189 | 0.681254 | oskrs111 |
00144f6fe0033d2f64866ceca60fcb1b78d5fad7 | 5,672 | hpp | C++ | backend/compiler.hpp | mark-sed/ebe | 6280704e377e55b89aa5125942cc710b5e73209e | [
"MIT"
] | 1 | 2022-02-22T21:42:28.000Z | 2022-02-22T21:42:28.000Z | backend/compiler.hpp | mark-sed/ebe | 6280704e377e55b89aa5125942cc710b5e73209e | [
"MIT"
] | null | null | null | backend/compiler.hpp | mark-sed/ebe | 6280704e377e55b89aa5125942cc710b5e73209e | [
"MIT"
] | null | null | null | /**
* @file compiler.hpp
* @author Marek Sedlacek
* @date July 2021
* @copyright Copyright 2021 Marek Sedlacek. All rights reserved.
*
* @brief Abstract data for all processing units
*
* Every input processing unit should extend processor class
* so that all needed information and methods are present in it.
*/
#ifndef _COMPILER_HPP_
#define _COMPILER_HPP_
#include <iostream>
#include <unistd.h>
#include "exceptions.hpp"
/**
* Namespace holding resources for error and warning handling
*/
namespace Error {
/**
* Namespace for terminal colorization
*/
namespace Colors {
extern const char * NO_COLOR;
extern const char * BLACK;
extern const char * GRAY;
extern const char * RED;
extern const char * LIGHT_RED;
extern const char * GREEN;
extern const char * LIGHT_GREEN;
extern const char * BROWN;
extern const char * YELLOW;
extern const char * BLUE;
extern const char * LIGHT_BLUE;
extern const char * PURPLE;
extern const char * LIGHT_PURPLE;
extern const char * CYAN;
extern const char * LIGHT_CYAN;
extern const char * LIGHT_GRAY;
extern const char * WHITE;
extern const char * RESET;
/**
* Checks if stderr is redirected to a file
* @return true if stderr is redirected
*/
inline bool is_cerr_redirected() {
static bool initialized(false);
static bool is_redir;
if (!initialized) {
initialized = true;
is_redir = ttyname(fileno(stderr)) == nullptr;
}
return is_redir;
}
/**
* Returns passes in color in case the output is not redirected.
* If output is redirected then this returns empty string ("")
* @param color Colors to sanitize
* @return color if output if not redirected otherwise empty string
*/
inline const char *colorize(const char * color) {
// Check if stderr is redirected
if(is_cerr_redirected()) {
return "";
}
return color;
}
/**
* Resets set color to default terminal settings
* @return Colors::RESET if output is not redirected otherwise empty string
*/
inline const char *reset() {
// Check if stderr is redirected
if(is_cerr_redirected()) {
return "";
}
return Colors::RESET;
}
}
/**
* Possible enum codes
* @note When new code is added its string name should be added also to the get_code_name function
*/
enum ErrorCode {
NO_ERROR = 0, ///< When no error occurred but program had to exit (otherwise return code would be for some error 0)
UNKNOWN, ///< Unknown error (shouldn't be really used)
INTERNAL, ///< Internal compiler error (such as unable to allocate memory)
FILE_ACCESS, ///< Problem opening/writing/working with users files (not internal config files)
ARGUMENTS, ///< Problem with user arguments
SYNTACTIC, ///< Syntactical error
SEMANTIC, ///< Semantical error
UNIMPLEMENTED, ///< Problems with instruction
RUNTIME, ///< Runtime errors
VERSION ///< For when the version is not sufficient
};
/**
* Returns name of ErrorCode
* @param code Error code
* @return Error code's name
*/
const char *get_code_name(ErrorCode code);
/**
* Function for when fatal error occurres
* Prints error information passed in and exits with passed in code
* @param code Code of an error that occurred
* @param msg Info message to be printed for the user
* @param exc Exception that might hava accompanied this error or nullptr
* @param exit If true (default), then after the message is printed program exits with code
*/
void error(Error::ErrorCode code, const char *msg, Exception::EbeException *exc=nullptr, bool exit=true);
void error(Error::ErrorCode code, const char *file, long line, long column, const char *msg,
Exception::EbeException *exc=nullptr, bool exit=true);
/**
* Prints warning to std::cerr
* @param msg Message to print
*/
void warning(const char *msg);
/**
* Exits program with passed in code
* @param code Error code to exit with
*/
[[noreturn]] void exit(Error::ErrorCode code);
}
/**
* Base class for all compiler components
* @note Every compilation pass should extend this class
*/
class Compiler {
public:
const char *unit_name; ///< Name of the compilation unit (needed for error printing)
protected:
/**
* Constructor
* @param unit_name Name of unit which extends this class
*/
Compiler(const char *unit_name);
/**
* Prints error to the user and exits
* @param code Error code to exit with
* @param file Name of the file in which this error occurred
* @param line Line at which the error occurred
* @param column Column at which the error occurred
* @param msg Message to be printed to the user
* @param exc Exception that might hava accompanied this error or nullptr
* @param exit If true (default), then after the message is printed program exits with code
*/
void error(Error::ErrorCode code, const char *file, long line, long column, const char *msg,
Exception::EbeException *exc=nullptr, bool exit=true);
};
#endif//_COMPILER_HPP_
| 33.56213 | 124 | 0.618124 | mark-sed |
0018286db252b6fa890c686fde2b3aa074643601 | 3,702 | hpp | C++ | include/parser/ValueMgr.hpp | scribelang/scribe-poc | c1ba4dafbb3b38a5b408e068747a5ed0f3e49e25 | [
"MIT"
] | null | null | null | include/parser/ValueMgr.hpp | scribelang/scribe-poc | c1ba4dafbb3b38a5b408e068747a5ed0f3e49e25 | [
"MIT"
] | null | null | null | include/parser/ValueMgr.hpp | scribelang/scribe-poc | c1ba4dafbb3b38a5b408e068747a5ed0f3e49e25 | [
"MIT"
] | null | null | null | /*
MIT License
Copyright (c) 2021 Scribe Language Repositories
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.
*/
#ifndef PARSER_VALUEMGR_HPP
#define PARSER_VALUEMGR_HPP
#include <string>
#include <unordered_map>
#include <vector>
#include "Value.hpp"
namespace sc
{
namespace parser
{
class RAIIParser;
// typedef bool (*intrinsic_fn_t)(TypeMgr &types, Stmt *stmt);
// #define INTRINSIC(name) bool intrinsic_##name(TypeMgr &types, Stmt *stmt)
// no need to copy unnecessarily - values are immutable
class ValueLayer
{
std::unordered_map<std::string, Value *> vals;
public:
inline bool add(const std::string &name, Value *val)
{
if(vals.find(name) != vals.end()) return false;
vals[name] = val;
return true;
}
inline Value *get(const std::string &name)
{
return vals[name];
}
inline bool has(const std::string &name)
{
return vals.find(name) != vals.end();
}
};
class ValueSrc
{
std::vector<ValueLayer> stack;
public:
inline void pushLayer()
{
stack.push_back({});
}
inline void popLayer()
{
stack.pop_back();
}
inline bool add(const std::string &name, Value *val)
{
return stack.back().add(name, val);
}
inline Value *get(const std::string &name)
{
return stack.back().get(name);
}
inline bool has(const std::string &name)
{
return stack.back().has(name);
}
};
class ValueMgr
{
RAIIParser *parser;
std::unordered_map<std::string, Value *> globals;
std::unordered_map<size_t, ValueSrc> srcs;
std::vector<ValueSrc *> stack;
ValueAllocator vallocator;
public:
ValueMgr(RAIIParser *parser);
inline RAIIParser *getParser()
{
return parser;
}
inline void add_src(const size_t &src_id)
{
if(srcs.find(src_id) == srcs.end()) srcs[src_id] = {};
}
inline void push_src(const size_t &src_id)
{
stack.push_back(&srcs[src_id]);
}
inline void pop_src()
{
stack.pop_back();
}
inline void pushLayer()
{
stack.back()->pushLayer();
}
inline void popLayer()
{
stack.back()->popLayer();
}
// FIXME: enable global
inline bool add_val(const std::string &name, Value *val, const bool &global)
{
return stack.back()->add(name, val);
}
inline Value *get_val(const std::string &name)
{
return stack.back()->get(name);
}
// FIXME: enable top_only and with_globals
inline bool has(const std::string &name, const bool &top_only, const bool &with_globals)
{
return stack.back()->has(name);
}
inline Value *get(const int64_t &idata)
{
return vallocator.get(idata);
}
inline Value *get(const double &fdata)
{
return vallocator.get(fdata);
}
inline Value *get(const std::string &sdata)
{
return vallocator.get(sdata);
}
inline Value *get(const std::vector<Value *> &vdata)
{
return vallocator.get(vdata);
}
inline Value *get(const std::unordered_map<std::string, Value *> &stdata,
const std::vector<std::string> &storder)
{
return vallocator.get(stdata, storder);
}
// this is for unknown and void values
inline Value *get(const Values &type)
{
return vallocator.get(type);
}
inline Value *get(Value *from)
{
return vallocator.get(from);
}
inline std::string getStringFromVec(Value *vec)
{
return parser::getStringFromVec(vec);
}
inline void updateValue(Value *src, Value *newval)
{
return vallocator.updateValue(src, newval);
}
};
} // namespace parser
} // namespace sc
#endif // PARSER_VALUEMGR_HPP | 20.119565 | 89 | 0.697731 | scribelang |
001e703a89d2f94587d933c20950efe2dda20f91 | 56,473 | cpp | C++ | src/tier0/threadtools.cpp | DeadZoneLuna/csso-src | 6c978ea304ee2df3796bc9c0d2916bac550050d5 | [
"Unlicense"
] | 4 | 2021-10-03T05:16:55.000Z | 2021-12-28T16:49:27.000Z | src/tier0/threadtools.cpp | cafeed28/what | 08e51d077f0eae50afe3b592543ffa07538126f5 | [
"Unlicense"
] | null | null | null | src/tier0/threadtools.cpp | cafeed28/what | 08e51d077f0eae50afe3b592543ffa07538126f5 | [
"Unlicense"
] | 3 | 2022-02-02T18:09:58.000Z | 2022-03-06T18:54:39.000Z | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================
#include "pch_tier0.h"
#include "tier1/strtools.h"
#include "tier0/dynfunction.h"
#if defined( _WIN32 ) && !defined( _X360 )
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif
#ifdef _WIN32
#include <process.h>
#ifdef IS_WINDOWS_PC
#include <Mmsystem.h>
#pragma comment(lib, "winmm.lib")
#endif // IS_WINDOWS_PC
#elif defined(POSIX)
#if !defined(OSX)
#include <sys/fcntl.h>
#include <sys/unistd.h>
#define sem_unlink( arg )
#define OS_TO_PTHREAD(x) (x)
#else
#define pthread_yield pthread_yield_np
#include <mach/thread_act.h>
#include <mach/mach.h>
#define OS_TO_PTHREAD(x) pthread_from_mach_thread_np( x )
#endif // !OSX
#ifdef LINUX
#include <dlfcn.h> // RTLD_NEXT
#endif
typedef int (*PTHREAD_START_ROUTINE)(
void *lpThreadParameter
);
typedef PTHREAD_START_ROUTINE LPTHREAD_START_ROUTINE;
#include <sched.h>
#include <exception>
#include <errno.h>
#include <signal.h>
#include <pthread.h>
#include <sys/time.h>
#define GetLastError() errno
typedef void *LPVOID;
#endif
#include "tier0/valve_minmax_off.h"
#include <memory>
#include "tier0/valve_minmax_on.h"
#include "tier0/threadtools.h"
#include "tier0/vcrmode.h"
#ifdef _X360
#include "xbox/xbox_win32stubs.h"
#endif
#include "tier0/vprof_telemetry.h"
// Must be last header...
#include "tier0/memdbgon.h"
#define THREADS_DEBUG 1
// Need to ensure initialized before other clients call in for main thread ID
#ifdef _WIN32
#pragma warning(disable:4073)
#pragma init_seg(lib)
#endif
#ifdef _WIN32
ASSERT_INVARIANT(TT_SIZEOF_CRITICALSECTION == sizeof(CRITICAL_SECTION));
ASSERT_INVARIANT(TT_INFINITE == INFINITE);
#endif
//-----------------------------------------------------------------------------
// Simple thread functions.
// Because _beginthreadex uses stdcall, we need to convert to cdecl
//-----------------------------------------------------------------------------
struct ThreadProcInfo_t
{
ThreadProcInfo_t( ThreadFunc_t pfnThread, void *pParam )
: pfnThread( pfnThread),
pParam( pParam )
{
}
ThreadFunc_t pfnThread;
void * pParam;
};
//---------------------------------------------------------
#ifdef _WIN32
static unsigned __stdcall ThreadProcConvert( void *pParam )
#elif defined(POSIX)
static void *ThreadProcConvert( void *pParam )
#else
#error
#endif
{
ThreadProcInfo_t info = *((ThreadProcInfo_t *)pParam);
delete ((ThreadProcInfo_t *)pParam);
#ifdef _WIN32
return (*info.pfnThread)(info.pParam);
#elif defined(POSIX)
return (void *)(*info.pfnThread)(info.pParam);
#else
#error
#endif
}
//---------------------------------------------------------
ThreadHandle_t CreateSimpleThread( ThreadFunc_t pfnThread, void *pParam, ThreadId_t *pID, unsigned stackSize )
{
#ifdef _WIN32
ThreadId_t idIgnored;
if ( !pID )
pID = &idIgnored;
HANDLE h = VCRHook_CreateThread(NULL, stackSize, (LPTHREAD_START_ROUTINE)ThreadProcConvert, new ThreadProcInfo_t( pfnThread, pParam ), CREATE_SUSPENDED, pID);
if ( h != INVALID_HANDLE_VALUE )
{
Plat_ApplyHardwareDataBreakpointsToNewThread( *pID );
ResumeThread( h );
}
return (ThreadHandle_t)h;
#elif defined(POSIX)
pthread_t tid;
// If we need to create threads that are detached right out of the gate, we would need to do something like this:
// pthread_attr_t attr;
// int rc = pthread_attr_init(&attr);
// rc = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
// ... pthread_create( &tid, &attr, ... ) ...
// rc = pthread_attr_destroy(&attr);
// ... pthread_join will now fail
int ret = pthread_create( &tid, NULL, ThreadProcConvert, new ThreadProcInfo_t( pfnThread, pParam ) );
if ( ret )
{
// There are only PTHREAD_THREADS_MAX number of threads, and we're probably leaking handles if ret == EAGAIN here?
Error( "CreateSimpleThread: pthread_create failed. Someone not calling pthread_detach() or pthread_join. Ret:%d\n", ret );
}
if ( pID )
*pID = (ThreadId_t)tid;
Plat_ApplyHardwareDataBreakpointsToNewThread( (long unsigned int)tid );
return (ThreadHandle_t)tid;
#endif
}
ThreadHandle_t CreateSimpleThread( ThreadFunc_t pfnThread, void *pParam, unsigned stackSize )
{
return CreateSimpleThread( pfnThread, pParam, NULL, stackSize );
}
PLATFORM_INTERFACE void ThreadDetach( ThreadHandle_t hThread )
{
#if defined( POSIX )
// The resources of this thread will be freed immediately when it terminates,
// instead of waiting for another thread to perform PTHREAD_JOIN.
pthread_t tid = ( pthread_t )hThread;
pthread_detach( tid );
#endif
}
bool ReleaseThreadHandle( ThreadHandle_t hThread )
{
#ifdef _WIN32
return ( CloseHandle( hThread ) != 0 );
#else
return true;
#endif
}
//-----------------------------------------------------------------------------
//
// Wrappers for other simple threading operations
//
//-----------------------------------------------------------------------------
void ThreadSleep(unsigned nMilliseconds)
{
#ifdef _WIN32
#ifdef IS_WINDOWS_PC
static bool bInitialized = false;
if ( !bInitialized )
{
bInitialized = true;
// Set the timer resolution to 1 ms (default is 10.0, 15.6, 2.5, 1.0 or
// some other value depending on hardware and software) so that we can
// use Sleep( 1 ) to avoid wasting CPU time without missing our frame
// rate.
timeBeginPeriod( 1 );
}
#endif // IS_WINDOWS_PC
Sleep( nMilliseconds );
#elif defined(POSIX)
usleep( nMilliseconds * 1000 );
#endif
}
//-----------------------------------------------------------------------------
#ifndef ThreadGetCurrentId
uint ThreadGetCurrentId()
{
#ifdef _WIN32
return GetCurrentThreadId();
#elif defined(POSIX)
return (uint)pthread_self();
#endif
}
#endif
//-----------------------------------------------------------------------------
ThreadHandle_t ThreadGetCurrentHandle()
{
#ifdef _WIN32
return (ThreadHandle_t)GetCurrentThread();
#elif defined(POSIX)
return (ThreadHandle_t)pthread_self();
#endif
}
// On PS3, this will return true for zombie threads
bool ThreadIsThreadIdRunning( ThreadId_t uThreadId )
{
#ifdef _WIN32
bool bRunning = true;
HANDLE hThread = ::OpenThread( THREAD_QUERY_INFORMATION , false, uThreadId );
if ( hThread )
{
DWORD dwExitCode;
if( !::GetExitCodeThread( hThread, &dwExitCode ) || dwExitCode != STILL_ACTIVE )
bRunning = false;
CloseHandle( hThread );
}
else
{
bRunning = false;
}
return bRunning;
#elif defined( _PS3 )
// will return CELL_OK for zombie threads
int priority;
return (sys_ppu_thread_get_priority( uThreadId, &priority ) == CELL_OK );
#elif defined(POSIX)
pthread_t thread = OS_TO_PTHREAD(uThreadId);
if ( thread )
{
int iResult = pthread_kill( thread, 0 );
if ( iResult == 0 )
return true;
}
else
{
// We really ought not to be passing NULL in to here
AssertMsg( false, "ThreadIsThreadIdRunning received a null thread ID" );
}
return false;
#endif
}
//-----------------------------------------------------------------------------
int ThreadGetPriority( ThreadHandle_t hThread )
{
if ( !hThread )
{
hThread = ThreadGetCurrentHandle();
}
#ifdef _WIN32
return ::GetThreadPriority( (HANDLE)hThread );
#else
struct sched_param thread_param;
int policy;
pthread_getschedparam( (pthread_t)hThread, &policy, &thread_param );
return thread_param.sched_priority;
#endif
}
//-----------------------------------------------------------------------------
bool ThreadSetPriority( ThreadHandle_t hThread, int priority )
{
if ( !hThread )
{
hThread = ThreadGetCurrentHandle();
}
#ifdef _WIN32
return ( SetThreadPriority(hThread, priority) != 0 );
#elif defined(POSIX)
struct sched_param thread_param;
thread_param.sched_priority = priority;
pthread_setschedparam( (pthread_t)hThread, SCHED_OTHER, &thread_param );
return true;
#endif
}
//-----------------------------------------------------------------------------
void ThreadSetAffinity( ThreadHandle_t hThread, int nAffinityMask )
{
if ( !hThread )
{
hThread = ThreadGetCurrentHandle();
}
#ifdef _WIN32
SetThreadAffinityMask( hThread, nAffinityMask );
#elif defined(POSIX)
// cpu_set_t cpuSet;
// CPU_ZERO( cpuSet );
// for( int i = 0 ; i < 32; i++ )
// if ( nAffinityMask & ( 1 << i ) )
// CPU_SET( cpuSet, i );
// sched_setaffinity( hThread, sizeof( cpuSet ), &cpuSet );
#endif
}
//-----------------------------------------------------------------------------
uint InitMainThread()
{
#ifndef LINUX
// Skip doing the setname on Linux for the main thread. Here is why...
// From Pierre-Loup e-mail about why pthread_setname_np() on the main thread
// in Linux will cause some tools to display "MainThrd" as the executable name:
//
// You have two things in procfs, comm and cmdline. Each of the threads have
// a different `comm`, which is the value you set through pthread_setname_np
// or prctl(PR_SET_NAME). Top can either display cmdline or comm; it
// switched to display comm by default; htop still displays cmdline by
// default. Top -c will output cmdline rather than comm.
//
// If you press 'H' while top is running it will display each thread as a
// separate process, so you will have different entries for MainThrd,
// MatQueue0, etc with their own CPU usage. But when that mode isn't enabled
// it just displays the 'comm' name from the first thread.
ThreadSetDebugName( "MainThrd" );
#endif
#ifdef _WIN32
return ThreadGetCurrentId();
#elif defined(POSIX)
return (uint)pthread_self();
#endif
}
uint g_ThreadMainThreadID = InitMainThread();
bool ThreadInMainThread()
{
return ( ThreadGetCurrentId() == g_ThreadMainThreadID );
}
//-----------------------------------------------------------------------------
void DeclareCurrentThreadIsMainThread()
{
g_ThreadMainThreadID = ThreadGetCurrentId();
}
bool ThreadJoin( ThreadHandle_t hThread, unsigned timeout )
{
// You should really never be calling this with a NULL thread handle. If you
// are then that probably implies a race condition or threading misunderstanding.
Assert( hThread );
if ( !hThread )
{
return false;
}
#ifdef _WIN32
DWORD dwWait = VCRHook_WaitForSingleObject((HANDLE)hThread, timeout);
if ( dwWait == WAIT_TIMEOUT)
return false;
if ( dwWait != WAIT_OBJECT_0 && ( dwWait != WAIT_FAILED && GetLastError() != 0 ) )
{
Assert( 0 );
return false;
}
#elif defined(POSIX)
if ( pthread_join( (pthread_t)hThread, NULL ) != 0 )
return false;
#endif
return true;
}
#ifdef RAD_TELEMETRY_ENABLED
void TelemetryThreadSetDebugName( ThreadId_t id, const char *pszName );
#endif
//-----------------------------------------------------------------------------
void ThreadSetDebugName( ThreadId_t id, const char *pszName )
{
if( !pszName )
return;
#ifdef RAD_TELEMETRY_ENABLED
TelemetryThreadSetDebugName( id, pszName );
#endif
#ifdef _WIN32
if ( Plat_IsInDebugSession() )
{
#define MS_VC_EXCEPTION 0x406d1388
typedef struct tagTHREADNAME_INFO
{
DWORD dwType; // must be 0x1000
LPCSTR szName; // pointer to name (in same addr space)
DWORD dwThreadID; // thread ID (-1 caller thread)
DWORD dwFlags; // reserved for future use, most be zero
} THREADNAME_INFO;
THREADNAME_INFO info;
info.dwType = 0x1000;
info.szName = pszName;
info.dwThreadID = id;
info.dwFlags = 0;
__try
{
RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(DWORD), (ULONG_PTR *)&info);
}
__except (EXCEPTION_CONTINUE_EXECUTION)
{
}
}
#elif defined( _LINUX )
// As of glibc v2.12, we can use pthread_setname_np.
typedef int (pthread_setname_np_func)(pthread_t, const char *);
static pthread_setname_np_func *s_pthread_setname_np_func = (pthread_setname_np_func *)dlsym(RTLD_DEFAULT, "pthread_setname_np");
if ( s_pthread_setname_np_func )
{
if ( id == (uint32)-1 )
id = pthread_self();
/*
pthread_setname_np() in phthread_setname.c has the following code:
#define TASK_COMM_LEN 16
size_t name_len = strlen (name);
if (name_len >= TASK_COMM_LEN)
return ERANGE;
So we need to truncate the threadname to 16 or the call will just fail.
*/
char szThreadName[ 16 ];
strncpy( szThreadName, pszName, ARRAYSIZE( szThreadName ) );
szThreadName[ ARRAYSIZE( szThreadName ) - 1 ] = 0;
(*s_pthread_setname_np_func)( id, szThreadName );
}
#endif
}
//-----------------------------------------------------------------------------
#ifdef _WIN32
ASSERT_INVARIANT( TW_FAILED == WAIT_FAILED );
ASSERT_INVARIANT( TW_TIMEOUT == WAIT_TIMEOUT );
ASSERT_INVARIANT( WAIT_OBJECT_0 == 0 );
int ThreadWaitForObjects( int nEvents, const HANDLE *pHandles, bool bWaitAll, unsigned timeout )
{
return VCRHook_WaitForMultipleObjects( nEvents, pHandles, bWaitAll, timeout );
}
#endif
//-----------------------------------------------------------------------------
// Used to thread LoadLibrary on the 360
//-----------------------------------------------------------------------------
static ThreadedLoadLibraryFunc_t s_ThreadedLoadLibraryFunc = 0;
PLATFORM_INTERFACE void SetThreadedLoadLibraryFunc( ThreadedLoadLibraryFunc_t func )
{
s_ThreadedLoadLibraryFunc = func;
}
PLATFORM_INTERFACE ThreadedLoadLibraryFunc_t GetThreadedLoadLibraryFunc()
{
return s_ThreadedLoadLibraryFunc;
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
CThreadSyncObject::CThreadSyncObject()
#ifdef _WIN32
: m_hSyncObject( NULL ), m_bCreatedHandle(false)
#elif defined(POSIX)
: m_bInitalized( false )
#endif
{
}
//---------------------------------------------------------
CThreadSyncObject::~CThreadSyncObject()
{
#ifdef _WIN32
if ( m_hSyncObject && m_bCreatedHandle )
{
if ( !CloseHandle(m_hSyncObject) )
{
Assert( 0 );
}
}
#elif defined(POSIX)
if ( m_bInitalized )
{
pthread_cond_destroy( &m_Condition );
pthread_mutex_destroy( &m_Mutex );
m_bInitalized = false;
}
#endif
}
//---------------------------------------------------------
bool CThreadSyncObject::operator!() const
{
#ifdef _WIN32
return !m_hSyncObject;
#elif defined(POSIX)
return !m_bInitalized;
#endif
}
//---------------------------------------------------------
void CThreadSyncObject::AssertUseable()
{
#ifdef THREADS_DEBUG
#ifdef _WIN32
AssertMsg( m_hSyncObject, "Thread synchronization object is unuseable" );
#elif defined(POSIX)
AssertMsg( m_bInitalized, "Thread synchronization object is unuseable" );
#endif
#endif
}
//---------------------------------------------------------
bool CThreadSyncObject::Wait( uint32 dwTimeout )
{
#ifdef THREADS_DEBUG
AssertUseable();
#endif
#ifdef _WIN32
return ( VCRHook_WaitForSingleObject( m_hSyncObject, dwTimeout ) == WAIT_OBJECT_0 );
#elif defined(POSIX)
pthread_mutex_lock( &m_Mutex );
bool bRet = false;
if ( m_cSet > 0 )
{
bRet = true;
m_bWakeForEvent = false;
}
else
{
volatile int ret = 0;
while ( !m_bWakeForEvent && ret != ETIMEDOUT )
{
struct timeval tv;
gettimeofday( &tv, NULL );
volatile struct timespec tm;
uint64 actualTimeout = dwTimeout;
if ( dwTimeout == TT_INFINITE && m_bManualReset )
actualTimeout = 10; // just wait 10 msec at most for manual reset events and loop instead
volatile uint64 nNanoSec = (uint64)tv.tv_usec*1000 + (uint64)actualTimeout*1000000;
tm.tv_sec = tv.tv_sec + nNanoSec /1000000000;
tm.tv_nsec = nNanoSec % 1000000000;
do
{
ret = pthread_cond_timedwait( &m_Condition, &m_Mutex, (const timespec *)&tm );
}
while( ret == EINTR );
bRet = ( ret == 0 );
if ( m_bManualReset )
{
if ( m_cSet )
break;
if ( dwTimeout == TT_INFINITE && ret == ETIMEDOUT )
ret = 0; // force the loop to spin back around
}
}
if ( bRet )
m_bWakeForEvent = false;
}
if ( !m_bManualReset && bRet )
m_cSet = 0;
pthread_mutex_unlock( &m_Mutex );
return bRet;
#endif
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
CThreadEvent::CThreadEvent( bool bManualReset )
{
#ifdef _WIN32
m_hSyncObject = CreateEvent( NULL, bManualReset, FALSE, NULL );
m_bCreatedHandle = true;
AssertMsg1(m_hSyncObject, "Failed to create event (error 0x%x)", GetLastError() );
#elif defined( POSIX )
pthread_mutexattr_t Attr;
pthread_mutexattr_init( &Attr );
pthread_mutex_init( &m_Mutex, &Attr );
pthread_mutexattr_destroy( &Attr );
pthread_cond_init( &m_Condition, NULL );
m_bInitalized = true;
m_cSet = 0;
m_bWakeForEvent = false;
m_bManualReset = bManualReset;
#else
#error "Implement me"
#endif
}
#ifdef _WIN32
CThreadEvent::CThreadEvent( HANDLE hHandle )
{
m_hSyncObject = hHandle;
m_bCreatedHandle = false;
AssertMsg(m_hSyncObject, "Null event passed into constructor" );
}
#endif
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
//---------------------------------------------------------
bool CThreadEvent::Set()
{
AssertUseable();
#ifdef _WIN32
return ( SetEvent( m_hSyncObject ) != 0 );
#elif defined(POSIX)
pthread_mutex_lock( &m_Mutex );
m_cSet = 1;
m_bWakeForEvent = true;
int ret = pthread_cond_signal( &m_Condition );
pthread_mutex_unlock( &m_Mutex );
return ret == 0;
#endif
}
//---------------------------------------------------------
bool CThreadEvent::Reset()
{
#ifdef THREADS_DEBUG
AssertUseable();
#endif
#ifdef _WIN32
return ( ResetEvent( m_hSyncObject ) != 0 );
#elif defined(POSIX)
pthread_mutex_lock( &m_Mutex );
m_cSet = 0;
m_bWakeForEvent = false;
pthread_mutex_unlock( &m_Mutex );
return true;
#endif
}
//---------------------------------------------------------
bool CThreadEvent::Check()
{
#ifdef THREADS_DEBUG
AssertUseable();
#endif
return Wait( 0 );
}
bool CThreadEvent::Wait( uint32 dwTimeout )
{
return CThreadSyncObject::Wait( dwTimeout );
}
#ifdef _WIN32
//-----------------------------------------------------------------------------
//
// CThreadSemaphore
//
// To get Posix implementation, try http://www-128.ibm.com/developerworks/eserver/library/es-win32linux-sem.html
//
//-----------------------------------------------------------------------------
CThreadSemaphore::CThreadSemaphore( long initialValue, long maxValue )
{
if ( maxValue )
{
AssertMsg( maxValue > 0, "Invalid max value for semaphore" );
AssertMsg( initialValue >= 0 && initialValue <= maxValue, "Invalid initial value for semaphore" );
m_hSyncObject = CreateSemaphore( NULL, initialValue, maxValue, NULL );
AssertMsg1(m_hSyncObject, "Failed to create semaphore (error 0x%x)", GetLastError());
}
else
{
m_hSyncObject = NULL;
}
}
//---------------------------------------------------------
bool CThreadSemaphore::Release( long releaseCount, long *pPreviousCount )
{
#ifdef THRDTOOL_DEBUG
AssertUseable();
#endif
return ( ReleaseSemaphore( m_hSyncObject, releaseCount, pPreviousCount ) != 0 );
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
CThreadFullMutex::CThreadFullMutex( bool bEstablishInitialOwnership, const char *pszName )
{
m_hSyncObject = CreateMutex( NULL, bEstablishInitialOwnership, pszName );
AssertMsg1( m_hSyncObject, "Failed to create mutex (error 0x%x)", GetLastError() );
}
//---------------------------------------------------------
bool CThreadFullMutex::Release()
{
#ifdef THRDTOOL_DEBUG
AssertUseable();
#endif
return ( ReleaseMutex( m_hSyncObject ) != 0 );
}
#endif
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
CThreadLocalBase::CThreadLocalBase()
{
#ifdef _WIN32
m_index = TlsAlloc();
AssertMsg( m_index != 0xFFFFFFFF, "Bad thread local" );
if ( m_index == 0xFFFFFFFF )
Error( "Out of thread local storage!\n" );
#elif defined(POSIX)
if ( pthread_key_create( &m_index, NULL ) != 0 )
Error( "Out of thread local storage!\n" );
#endif
}
//---------------------------------------------------------
CThreadLocalBase::~CThreadLocalBase()
{
#ifdef _WIN32
if ( m_index != 0xFFFFFFFF )
TlsFree( m_index );
m_index = 0xFFFFFFFF;
#elif defined(POSIX)
pthread_key_delete( m_index );
#endif
}
//---------------------------------------------------------
void * CThreadLocalBase::Get() const
{
#ifdef _WIN32
if ( m_index != 0xFFFFFFFF )
return TlsGetValue( m_index );
AssertMsg( 0, "Bad thread local" );
return NULL;
#elif defined(POSIX)
void *value = pthread_getspecific( m_index );
return value;
#endif
}
//---------------------------------------------------------
void CThreadLocalBase::Set( void *value )
{
#ifdef _WIN32
if (m_index != 0xFFFFFFFF)
TlsSetValue(m_index, value);
else
AssertMsg( 0, "Bad thread local" );
#elif defined(POSIX)
if ( pthread_setspecific( m_index, value ) != 0 )
AssertMsg( 0, "Bad thread local" );
#endif
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
#ifdef _WIN32
#ifdef _X360
#define TO_INTERLOCK_PARAM(p) ((long *)p)
#define TO_INTERLOCK_PTR_PARAM(p) ((void **)p)
#else
#define TO_INTERLOCK_PARAM(p) (p)
#define TO_INTERLOCK_PTR_PARAM(p) (p)
#endif
#ifndef USE_INTRINSIC_INTERLOCKED
long ThreadInterlockedIncrement( long volatile *pDest )
{
Assert( (size_t)pDest % 4 == 0 );
return InterlockedIncrement( TO_INTERLOCK_PARAM(pDest) );
}
long ThreadInterlockedDecrement( long volatile *pDest )
{
Assert( (size_t)pDest % 4 == 0 );
return InterlockedDecrement( TO_INTERLOCK_PARAM(pDest) );
}
long ThreadInterlockedExchange( long volatile *pDest, long value )
{
Assert( (size_t)pDest % 4 == 0 );
return InterlockedExchange( TO_INTERLOCK_PARAM(pDest), value );
}
long ThreadInterlockedExchangeAdd( long volatile *pDest, long value )
{
Assert( (size_t)pDest % 4 == 0 );
return InterlockedExchangeAdd( TO_INTERLOCK_PARAM(pDest), value );
}
long ThreadInterlockedCompareExchange( long volatile *pDest, long value, long comperand )
{
Assert( (size_t)pDest % 4 == 0 );
return InterlockedCompareExchange( TO_INTERLOCK_PARAM(pDest), value, comperand );
}
bool ThreadInterlockedAssignIf( long volatile *pDest, long value, long comperand )
{
Assert( (size_t)pDest % 4 == 0 );
#if !(defined(_WIN64) || defined (_X360))
__asm
{
mov eax,comperand
mov ecx,pDest
mov edx,value
lock cmpxchg [ecx],edx
mov eax,0
setz al
}
#else
return ( InterlockedCompareExchange( TO_INTERLOCK_PARAM(pDest), value, comperand ) == comperand );
#endif
}
#endif
#if !defined( USE_INTRINSIC_INTERLOCKED ) || defined( _WIN64 )
void *ThreadInterlockedExchangePointer( void * volatile *pDest, void *value )
{
Assert( (size_t)pDest % 4 == 0 );
return InterlockedExchangePointer( TO_INTERLOCK_PARAM(pDest), value );
}
void *ThreadInterlockedCompareExchangePointer( void * volatile *pDest, void *value, void *comperand )
{
Assert( (size_t)pDest % 4 == 0 );
return InterlockedCompareExchangePointer( TO_INTERLOCK_PTR_PARAM(pDest), value, comperand );
}
bool ThreadInterlockedAssignPointerIf( void * volatile *pDest, void *value, void *comperand )
{
Assert( (size_t)pDest % 4 == 0 );
#if !(defined(_WIN64) || defined (_X360))
__asm
{
mov eax,comperand
mov ecx,pDest
mov edx,value
lock cmpxchg [ecx],edx
mov eax,0
setz al
}
#else
return ( InterlockedCompareExchangePointer( TO_INTERLOCK_PTR_PARAM(pDest), value, comperand ) == comperand );
#endif
}
#endif
int64 ThreadInterlockedCompareExchange64( int64 volatile *pDest, int64 value, int64 comperand )
{
Assert( (size_t)pDest % 8 == 0 );
#if defined(_WIN64) || defined (_X360)
return InterlockedCompareExchange64( pDest, value, comperand );
#else
__asm
{
lea esi,comperand;
lea edi,value;
mov eax,[esi];
mov edx,4[esi];
mov ebx,[edi];
mov ecx,4[edi];
mov esi,pDest;
lock CMPXCHG8B [esi];
}
#endif
}
bool ThreadInterlockedAssignIf64(volatile int64 *pDest, int64 value, int64 comperand )
{
Assert( (size_t)pDest % 8 == 0 );
#if defined(PLATFORM_WINDOWS_PC32 )
__asm
{
lea esi,comperand;
lea edi,value;
mov eax,[esi];
mov edx,4[esi];
mov ebx,[edi];
mov ecx,4[edi];
mov esi,pDest;
lock CMPXCHG8B [esi];
mov eax,0;
setz al;
}
#else
return ( ThreadInterlockedCompareExchange64( pDest, value, comperand ) == comperand );
#endif
}
#if defined( PLATFORM_64BITS )
#if _MSC_VER < 1500
// This intrinsic isn't supported on VS2005.
extern "C" unsigned char _InterlockedCompareExchange128( int64 volatile * Destination, int64 ExchangeHigh, int64 ExchangeLow, int64 * ComparandResult );
#endif
bool ThreadInterlockedAssignIf128( volatile int128 *pDest, const int128 &value, const int128 &comperand )
{
Assert( ( (size_t)pDest % 16 ) == 0 );
volatile int64 *pDest64 = ( volatile int64 * )pDest;
int64 *pValue64 = ( int64 * )&value;
int64 *pComperand64 = ( int64 * )&comperand;
// Description:
// The CMPXCHG16B instruction compares the 128-bit value in the RDX:RAX and RCX:RBX registers
// with a 128-bit memory location. If the values are equal, the zero flag (ZF) is set,
// and the RCX:RBX value is copied to the memory location.
// Otherwise, the ZF flag is cleared, and the memory value is copied to RDX:RAX.
// _InterlockedCompareExchange128: http://msdn.microsoft.com/en-us/library/bb514094.aspx
return _InterlockedCompareExchange128( pDest64, pValue64[1], pValue64[0], pComperand64 ) == 1;
}
#endif // PLATFORM_64BITS
int64 ThreadInterlockedIncrement64( int64 volatile *pDest )
{
Assert( (size_t)pDest % 8 == 0 );
int64 Old;
do
{
Old = *pDest;
} while (ThreadInterlockedCompareExchange64(pDest, Old + 1, Old) != Old);
return Old + 1;
}
int64 ThreadInterlockedDecrement64( int64 volatile *pDest )
{
Assert( (size_t)pDest % 8 == 0 );
int64 Old;
do
{
Old = *pDest;
} while (ThreadInterlockedCompareExchange64(pDest, Old - 1, Old) != Old);
return Old - 1;
}
int64 ThreadInterlockedExchange64( int64 volatile *pDest, int64 value )
{
Assert( (size_t)pDest % 8 == 0 );
int64 Old;
do
{
Old = *pDest;
} while (ThreadInterlockedCompareExchange64(pDest, value, Old) != Old);
return Old;
}
int64 ThreadInterlockedExchangeAdd64( int64 volatile *pDest, int64 value )
{
Assert( (size_t)pDest % 8 == 0 );
int64 Old;
do
{
Old = *pDest;
} while (ThreadInterlockedCompareExchange64(pDest, Old + value, Old) != Old);
return Old;
}
#elif defined(GNUC)
#ifdef OSX
#include <libkern/OSAtomic.h>
#endif
long ThreadInterlockedIncrement( long volatile *pDest )
{
return __sync_fetch_and_add( pDest, 1 ) + 1;
}
long ThreadInterlockedDecrement( long volatile *pDest )
{
return __sync_fetch_and_sub( pDest, 1 ) - 1;
}
long ThreadInterlockedExchange( long volatile *pDest, long value )
{
return __sync_lock_test_and_set( pDest, value );
}
long ThreadInterlockedExchangeAdd( long volatile *pDest, long value )
{
return __sync_fetch_and_add( pDest, value );
}
long ThreadInterlockedCompareExchange( long volatile *pDest, long value, long comperand )
{
return __sync_val_compare_and_swap( pDest, comperand, value );
}
bool ThreadInterlockedAssignIf( long volatile *pDest, long value, long comperand )
{
return __sync_bool_compare_and_swap( pDest, comperand, value );
}
void *ThreadInterlockedExchangePointer( void * volatile *pDest, void *value )
{
return __sync_lock_test_and_set( pDest, value );
}
void *ThreadInterlockedCompareExchangePointer( void *volatile *pDest, void *value, void *comperand )
{
return __sync_val_compare_and_swap( pDest, comperand, value );
}
bool ThreadInterlockedAssignPointerIf( void * volatile *pDest, void *value, void *comperand )
{
return __sync_bool_compare_and_swap( pDest, comperand, value );
}
int64 ThreadInterlockedCompareExchange64( int64 volatile *pDest, int64 value, int64 comperand )
{
#if defined(OSX)
int64 retVal = *pDest;
if ( OSAtomicCompareAndSwap64( comperand, value, pDest ) )
retVal = *pDest;
return retVal;
#else
return __sync_val_compare_and_swap( pDest, comperand, value );
#endif
}
bool ThreadInterlockedAssignIf64( int64 volatile * pDest, int64 value, int64 comperand )
{
return __sync_bool_compare_and_swap( pDest, comperand, value );
}
int64 ThreadInterlockedExchange64( int64 volatile *pDest, int64 value )
{
Assert( (size_t)pDest % 8 == 0 );
int64 Old;
do
{
Old = *pDest;
} while (ThreadInterlockedCompareExchange64(pDest, value, Old) != Old);
return Old;
}
#else
// This will perform horribly,
#error "Falling back to mutexed interlocked operations, you really don't have intrinsics you can use?"ß
CThreadMutex g_InterlockedMutex;
long ThreadInterlockedIncrement( long volatile *pDest )
{
AUTO_LOCK( g_InterlockedMutex );
return ++(*pDest);
}
long ThreadInterlockedDecrement( long volatile *pDest )
{
AUTO_LOCK( g_InterlockedMutex );
return --(*pDest);
}
long ThreadInterlockedExchange( long volatile *pDest, long value )
{
AUTO_LOCK( g_InterlockedMutex );
long retVal = *pDest;
*pDest = value;
return retVal;
}
void *ThreadInterlockedExchangePointer( void * volatile *pDest, void *value )
{
AUTO_LOCK( g_InterlockedMutex );
void *retVal = *pDest;
*pDest = value;
return retVal;
}
long ThreadInterlockedExchangeAdd( long volatile *pDest, long value )
{
AUTO_LOCK( g_InterlockedMutex );
long retVal = *pDest;
*pDest += value;
return retVal;
}
long ThreadInterlockedCompareExchange( long volatile *pDest, long value, long comperand )
{
AUTO_LOCK( g_InterlockedMutex );
long retVal = *pDest;
if ( *pDest == comperand )
*pDest = value;
return retVal;
}
void *ThreadInterlockedCompareExchangePointer( void * volatile *pDest, void *value, void *comperand )
{
AUTO_LOCK( g_InterlockedMutex );
void *retVal = *pDest;
if ( *pDest == comperand )
*pDest = value;
return retVal;
}
int64 ThreadInterlockedCompareExchange64( int64 volatile *pDest, int64 value, int64 comperand )
{
Assert( (size_t)pDest % 8 == 0 );
AUTO_LOCK( g_InterlockedMutex );
int64 retVal = *pDest;
if ( *pDest == comperand )
*pDest = value;
return retVal;
}
int64 ThreadInterlockedExchange64( int64 volatile *pDest, int64 value )
{
Assert( (size_t)pDest % 8 == 0 );
int64 Old;
do
{
Old = *pDest;
} while (ThreadInterlockedCompareExchange64(pDest, value, Old) != Old);
return Old;
}
bool ThreadInterlockedAssignIf64(volatile int64 *pDest, int64 value, int64 comperand )
{
Assert( (size_t)pDest % 8 == 0 );
return ( ThreadInterlockedCompareExchange64( pDest, value, comperand ) == comperand );
}
bool ThreadInterlockedAssignIf( long volatile *pDest, long value, long comperand )
{
Assert( (size_t)pDest % 4 == 0 );
return ( ThreadInterlockedCompareExchange( pDest, value, comperand ) == comperand );
}
#endif
//-----------------------------------------------------------------------------
#if defined(_WIN32) && defined(THREAD_PROFILER)
void ThreadNotifySyncNoop(void *p) {}
#define MAP_THREAD_PROFILER_CALL( from, to ) \
void from(void *p) \
{ \
static CDynamicFunction<void (*)(void *)> dynFunc( "libittnotify.dll", #to, ThreadNotifySyncNoop ); \
(*dynFunc)(p); \
}
MAP_THREAD_PROFILER_CALL( ThreadNotifySyncPrepare, __itt_notify_sync_prepare );
MAP_THREAD_PROFILER_CALL( ThreadNotifySyncCancel, __itt_notify_sync_cancel );
MAP_THREAD_PROFILER_CALL( ThreadNotifySyncAcquired, __itt_notify_sync_acquired );
MAP_THREAD_PROFILER_CALL( ThreadNotifySyncReleasing, __itt_notify_sync_releasing );
#endif
//-----------------------------------------------------------------------------
//
// CThreadMutex
//
//-----------------------------------------------------------------------------
#ifndef POSIX
CThreadMutex::CThreadMutex()
{
#ifdef THREAD_MUTEX_TRACING_ENABLED
memset( &m_CriticalSection, 0, sizeof(m_CriticalSection) );
#endif
InitializeCriticalSectionAndSpinCount((CRITICAL_SECTION *)&m_CriticalSection, 4000);
#ifdef THREAD_MUTEX_TRACING_SUPPORTED
// These need to be initialized unconditionally in case mixing release & debug object modules
// Lock and unlock may be emitted as COMDATs, in which case may get spurious output
m_currentOwnerID = m_lockCount = 0;
m_bTrace = false;
#endif
}
CThreadMutex::~CThreadMutex()
{
DeleteCriticalSection((CRITICAL_SECTION *)&m_CriticalSection);
}
#endif // !POSIX
#if defined( _WIN32 ) && !defined( _X360 )
typedef BOOL (WINAPI*TryEnterCriticalSectionFunc_t)(LPCRITICAL_SECTION);
static CDynamicFunction<TryEnterCriticalSectionFunc_t> DynTryEnterCriticalSection( "Kernel32.dll", "TryEnterCriticalSection" );
#elif defined( _X360 )
#define DynTryEnterCriticalSection TryEnterCriticalSection
#endif
bool CThreadMutex::TryLock()
{
#if defined( _WIN32 )
#ifdef THREAD_MUTEX_TRACING_ENABLED
uint thisThreadID = ThreadGetCurrentId();
if ( m_bTrace && m_currentOwnerID && ( m_currentOwnerID != thisThreadID ) )
Msg( "Thread %u about to try-wait for lock %p owned by %u\n", ThreadGetCurrentId(), (CRITICAL_SECTION *)&m_CriticalSection, m_currentOwnerID );
#endif
if ( DynTryEnterCriticalSection != NULL )
{
if ( (*DynTryEnterCriticalSection )( (CRITICAL_SECTION *)&m_CriticalSection ) != FALSE )
{
#ifdef THREAD_MUTEX_TRACING_ENABLED
if (m_lockCount == 0)
{
// we now own it for the first time. Set owner information
m_currentOwnerID = thisThreadID;
if ( m_bTrace )
Msg( "Thread %u now owns lock 0x%p\n", m_currentOwnerID, (CRITICAL_SECTION *)&m_CriticalSection );
}
m_lockCount++;
#endif
return true;
}
return false;
}
Lock();
return true;
#elif defined( POSIX )
return pthread_mutex_trylock( &m_Mutex ) == 0;
#else
#error "Implement me!"
return true;
#endif
}
//-----------------------------------------------------------------------------
//
// CThreadFastMutex
//
//-----------------------------------------------------------------------------
#define THREAD_SPIN (8*1024)
void CThreadFastMutex::Lock( const uint32 threadId, unsigned nSpinSleepTime ) volatile
{
int i;
if ( nSpinSleepTime != TT_INFINITE )
{
for ( i = THREAD_SPIN; i != 0; --i )
{
if ( TryLock( threadId ) )
{
return;
}
ThreadPause();
}
for ( i = THREAD_SPIN; i != 0; --i )
{
if ( TryLock( threadId ) )
{
return;
}
ThreadPause();
if ( i % 1024 == 0 )
{
ThreadSleep( 0 );
}
}
#ifdef _WIN32
if ( !nSpinSleepTime && GetThreadPriority( GetCurrentThread() ) > THREAD_PRIORITY_NORMAL )
{
nSpinSleepTime = 1;
}
else
#endif
if ( nSpinSleepTime )
{
for ( i = THREAD_SPIN; i != 0; --i )
{
if ( TryLock( threadId ) )
{
return;
}
ThreadPause();
ThreadSleep( 0 );
}
}
for ( ;; ) // coded as for instead of while to make easy to breakpoint success
{
if ( TryLock( threadId ) )
{
return;
}
ThreadPause();
ThreadSleep( nSpinSleepTime );
}
}
else
{
for ( ;; ) // coded as for instead of while to make easy to breakpoint success
{
if ( TryLock( threadId ) )
{
return;
}
ThreadPause();
}
}
}
//-----------------------------------------------------------------------------
//
// CThreadRWLock
//
//-----------------------------------------------------------------------------
void CThreadRWLock::WaitForRead()
{
m_nPendingReaders++;
do
{
m_mutex.Unlock();
m_CanRead.Wait();
m_mutex.Lock();
}
while (m_nWriters);
m_nPendingReaders--;
}
void CThreadRWLock::LockForWrite()
{
m_mutex.Lock();
bool bWait = ( m_nWriters != 0 || m_nActiveReaders != 0 );
m_nWriters++;
m_CanRead.Reset();
m_mutex.Unlock();
if ( bWait )
{
m_CanWrite.Wait();
}
}
void CThreadRWLock::UnlockWrite()
{
m_mutex.Lock();
m_nWriters--;
if ( m_nWriters == 0)
{
if ( m_nPendingReaders )
{
m_CanRead.Set();
}
}
else
{
m_CanWrite.Set();
}
m_mutex.Unlock();
}
//-----------------------------------------------------------------------------
//
// CThreadSpinRWLock
//
//-----------------------------------------------------------------------------
void CThreadSpinRWLock::SpinLockForWrite( const uint32 threadId )
{
int i;
for ( i = 1000; i != 0; --i )
{
if ( TryLockForWrite( threadId ) )
{
return;
}
ThreadPause();
}
for ( i = 20000; i != 0; --i )
{
if ( TryLockForWrite( threadId ) )
{
return;
}
ThreadPause();
ThreadSleep( 0 );
}
for ( ;; ) // coded as for instead of while to make easy to breakpoint success
{
if ( TryLockForWrite( threadId ) )
{
return;
}
ThreadPause();
ThreadSleep( 1 );
}
}
void CThreadSpinRWLock::LockForRead()
{
int i;
// In order to grab a read lock, the number of readers must not change and no thread can own the write lock
LockInfo_t oldValue;
LockInfo_t newValue;
oldValue.m_nReaders = m_lockInfo.m_nReaders;
oldValue.m_writerId = 0;
newValue.m_nReaders = oldValue.m_nReaders + 1;
newValue.m_writerId = 0;
if( m_nWriters == 0 && AssignIf( newValue, oldValue ) )
return;
ThreadPause();
oldValue.m_nReaders = m_lockInfo.m_nReaders;
newValue.m_nReaders = oldValue.m_nReaders + 1;
for ( i = 1000; i != 0; --i )
{
if( m_nWriters == 0 && AssignIf( newValue, oldValue ) )
return;
ThreadPause();
oldValue.m_nReaders = m_lockInfo.m_nReaders;
newValue.m_nReaders = oldValue.m_nReaders + 1;
}
for ( i = 20000; i != 0; --i )
{
if( m_nWriters == 0 && AssignIf( newValue, oldValue ) )
return;
ThreadPause();
ThreadSleep( 0 );
oldValue.m_nReaders = m_lockInfo.m_nReaders;
newValue.m_nReaders = oldValue.m_nReaders + 1;
}
for ( ;; ) // coded as for instead of while to make easy to breakpoint success
{
if( m_nWriters == 0 && AssignIf( newValue, oldValue ) )
return;
ThreadPause();
ThreadSleep( 1 );
oldValue.m_nReaders = m_lockInfo.m_nReaders;
newValue.m_nReaders = oldValue.m_nReaders + 1;
}
}
void CThreadSpinRWLock::UnlockRead()
{
int i;
Assert( m_lockInfo.m_nReaders > 0 && m_lockInfo.m_writerId == 0 );
LockInfo_t oldValue;
LockInfo_t newValue;
oldValue.m_nReaders = m_lockInfo.m_nReaders;
oldValue.m_writerId = 0;
newValue.m_nReaders = oldValue.m_nReaders - 1;
newValue.m_writerId = 0;
if( AssignIf( newValue, oldValue ) )
return;
ThreadPause();
oldValue.m_nReaders = m_lockInfo.m_nReaders;
newValue.m_nReaders = oldValue.m_nReaders - 1;
for ( i = 500; i != 0; --i )
{
if( AssignIf( newValue, oldValue ) )
return;
ThreadPause();
oldValue.m_nReaders = m_lockInfo.m_nReaders;
newValue.m_nReaders = oldValue.m_nReaders - 1;
}
for ( i = 20000; i != 0; --i )
{
if( AssignIf( newValue, oldValue ) )
return;
ThreadPause();
ThreadSleep( 0 );
oldValue.m_nReaders = m_lockInfo.m_nReaders;
newValue.m_nReaders = oldValue.m_nReaders - 1;
}
for ( ;; ) // coded as for instead of while to make easy to breakpoint success
{
if( AssignIf( newValue, oldValue ) )
return;
ThreadPause();
ThreadSleep( 1 );
oldValue.m_nReaders = m_lockInfo.m_nReaders;
newValue.m_nReaders = oldValue.m_nReaders - 1;
}
}
void CThreadSpinRWLock::UnlockWrite()
{
Assert( m_lockInfo.m_writerId == ThreadGetCurrentId() && m_lockInfo.m_nReaders == 0 );
static const LockInfo_t newValue = { 0, 0 };
#if defined(_X360)
// X360TBD: Serious Perf implications, not yet. __sync();
#endif
ThreadInterlockedExchange64( (int64 *)&m_lockInfo, *((int64 *)&newValue) );
m_nWriters--;
}
//-----------------------------------------------------------------------------
//
// CThread
//
//-----------------------------------------------------------------------------
CThreadLocalPtr<CThread> g_pCurThread;
//---------------------------------------------------------
CThread::CThread()
:
#ifdef _WIN32
m_hThread( NULL ),
#endif
m_threadId( 0 ),
m_result( 0 ),
m_flags( 0 )
{
m_szName[0] = 0;
}
//---------------------------------------------------------
CThread::~CThread()
{
#ifdef _WIN32
if (m_hThread)
#elif defined(POSIX)
if ( m_threadId )
#endif
{
if ( IsAlive() )
{
Msg( "Illegal termination of worker thread! Threads must negotiate an end to the thread before the CThread object is destroyed.\n" );
#ifdef _WIN32
DoNewAssertDialog( __FILE__, __LINE__, "Illegal termination of worker thread! Threads must negotiate an end to the thread before the CThread object is destroyed.\n" );
#endif
if ( GetCurrentCThread() == this )
{
Stop(); // BUGBUG: Alfred - this doesn't make sense, this destructor fires from the hosting thread not the thread itself!!
}
}
#ifdef _WIN32
// Now that the worker thread has exited (which we know because we presumably waited
// on the thread handle for it to exit) we can finally close the thread handle. We
// cannot do this any earlier, and certainly not in CThread::ThreadProc().
CloseHandle( m_hThread );
#endif
}
}
//---------------------------------------------------------
const char *CThread::GetName()
{
AUTO_LOCK( m_Lock );
if ( !m_szName[0] )
{
#ifdef _WIN32
_snprintf( m_szName, sizeof(m_szName) - 1, "Thread(%p/%p)", this, m_hThread );
#elif defined(POSIX)
_snprintf( m_szName, sizeof(m_szName) - 1, "Thread(0x%x/0x%x)", (uint)this, (uint)m_threadId );
#endif
m_szName[sizeof(m_szName) - 1] = 0;
}
return m_szName;
}
//---------------------------------------------------------
void CThread::SetName(const char *pszName)
{
AUTO_LOCK( m_Lock );
strncpy( m_szName, pszName, sizeof(m_szName) - 1 );
m_szName[sizeof(m_szName) - 1] = 0;
}
//---------------------------------------------------------
bool CThread::Start( unsigned nBytesStack )
{
AUTO_LOCK( m_Lock );
if ( IsAlive() )
{
AssertMsg( 0, "Tried to create a thread that has already been created!" );
return false;
}
bool bInitSuccess = false;
CThreadEvent createComplete;
ThreadInit_t init = { this, &createComplete, &bInitSuccess };
#ifdef _WIN32
HANDLE hThread;
m_hThread = hThread = (HANDLE)VCRHook_CreateThread( NULL,
nBytesStack,
(LPTHREAD_START_ROUTINE)GetThreadProc(),
new ThreadInit_t(init),
CREATE_SUSPENDED,
&m_threadId );
if ( !hThread )
{
AssertMsg1( 0, "Failed to create thread (error 0x%x)", GetLastError() );
return false;
}
Plat_ApplyHardwareDataBreakpointsToNewThread( m_threadId );
ResumeThread( hThread );
#elif defined(POSIX)
pthread_attr_t attr;
pthread_attr_init( &attr );
// From http://www.kernel.org/doc/man-pages/online/pages/man3/pthread_attr_setstacksize.3.html
// A thread's stack size is fixed at the time of thread creation. Only the main thread can dynamically grow its stack.
pthread_attr_setstacksize( &attr, MAX( nBytesStack, 1024u*1024 ) );
if ( pthread_create( &m_threadId, &attr, (void *(*)(void *))GetThreadProc(), new ThreadInit_t( init ) ) != 0 )
{
AssertMsg1( 0, "Failed to create thread (error 0x%x)", GetLastError() );
return false;
}
Plat_ApplyHardwareDataBreakpointsToNewThread( (long unsigned int)m_threadId );
bInitSuccess = true;
#endif
#if !defined( OSX )
ThreadSetDebugName( m_threadId, m_szName );
#endif
if ( !WaitForCreateComplete( &createComplete ) )
{
Msg( "Thread failed to initialize\n" );
#ifdef _WIN32
CloseHandle( m_hThread );
m_hThread = NULL;
m_threadId = 0;
#elif defined(POSIX)
m_threadId = 0;
#endif
return false;
}
if ( !bInitSuccess )
{
Msg( "Thread failed to initialize\n" );
#ifdef _WIN32
CloseHandle( m_hThread );
m_hThread = NULL;
m_threadId = 0;
#elif defined(POSIX)
m_threadId = 0;
#endif
return false;
}
#ifdef _WIN32
if ( !m_hThread )
{
Msg( "Thread exited immediately\n" );
}
#endif
#ifdef _WIN32
return !!m_hThread;
#elif defined(POSIX)
return !!m_threadId;
#endif
}
//---------------------------------------------------------
//
// Return true if the thread exists. false otherwise
//
bool CThread::IsAlive()
{
#ifdef _WIN32
DWORD dwExitCode;
return ( m_hThread &&
GetExitCodeThread( m_hThread, &dwExitCode ) &&
dwExitCode == STILL_ACTIVE );
#elif defined(POSIX)
return m_threadId;
#endif
}
//---------------------------------------------------------
bool CThread::Join(unsigned timeout)
{
#ifdef _WIN32
if ( m_hThread )
#elif defined(POSIX)
if ( m_threadId )
#endif
{
AssertMsg(GetCurrentCThread() != this, _T("Thread cannot be joined with self"));
#ifdef _WIN32
return ThreadJoin( (ThreadHandle_t)m_hThread );
#elif defined(POSIX)
return ThreadJoin( (ThreadHandle_t)m_threadId );
#endif
}
return true;
}
//---------------------------------------------------------
#ifdef _WIN32
HANDLE CThread::GetThreadHandle()
{
return m_hThread;
}
#endif
#if defined( _WIN32 ) || defined( LINUX )
//---------------------------------------------------------
uint CThread::GetThreadId()
{
return m_threadId;
}
#endif
//---------------------------------------------------------
int CThread::GetResult()
{
return m_result;
}
//---------------------------------------------------------
//
// Forcibly, abnormally, but relatively cleanly stop the thread
//
void CThread::Stop(int exitCode)
{
if ( !IsAlive() )
return;
if ( GetCurrentCThread() == this )
{
m_result = exitCode;
if ( !( m_flags & SUPPORT_STOP_PROTOCOL ) )
{
OnExit();
g_pCurThread = (int)NULL;
#ifdef _WIN32
CloseHandle( m_hThread );
m_hThread = NULL;
#endif
Cleanup();
}
throw exitCode;
}
else
AssertMsg( 0, "Only thread can stop self: Use a higher-level protocol");
}
//---------------------------------------------------------
int CThread::GetPriority() const
{
#ifdef _WIN32
return GetThreadPriority(m_hThread);
#elif defined(POSIX)
struct sched_param thread_param;
int policy;
pthread_getschedparam( m_threadId, &policy, &thread_param );
return thread_param.sched_priority;
#endif
}
//---------------------------------------------------------
bool CThread::SetPriority(int priority)
{
#ifdef _WIN32
return ThreadSetPriority( (ThreadHandle_t)m_hThread, priority );
#else
return ThreadSetPriority( (ThreadHandle_t)m_threadId, priority );
#endif
}
//---------------------------------------------------------
void CThread::SuspendCooperative()
{
if ( ThreadGetCurrentId() == (ThreadId_t)m_threadId )
{
m_SuspendEventSignal.Set();
m_nSuspendCount = 1;
m_SuspendEvent.Wait();
m_nSuspendCount = 0;
}
else
{
Assert( !"Suspend not called from worker thread, this would be a bug" );
}
}
//---------------------------------------------------------
void CThread::ResumeCooperative()
{
Assert( m_nSuspendCount == 1 );
m_SuspendEvent.Set();
}
void CThread::BWaitForThreadSuspendCooperative()
{
m_SuspendEventSignal.Wait();
}
#ifndef LINUX
//---------------------------------------------------------
unsigned int CThread::Suspend()
{
#ifdef _WIN32
return ( SuspendThread(m_hThread) != 0 );
#elif defined(OSX)
int susCount = m_nSuspendCount++;
while ( thread_suspend( pthread_mach_thread_np(m_threadId) ) != KERN_SUCCESS )
{
};
return ( susCount) != 0;
#else
#error
#endif
}
//---------------------------------------------------------
unsigned int CThread::Resume()
{
#ifdef _WIN32
return ( ResumeThread(m_hThread) != 0 );
#elif defined(OSX)
int susCount = m_nSuspendCount++;
while ( thread_resume( pthread_mach_thread_np(m_threadId) ) != KERN_SUCCESS )
{
};
return ( susCount - 1) != 0;
#else
#error
#endif
}
#endif
//---------------------------------------------------------
bool CThread::Terminate(int exitCode)
{
#ifndef _X360
#ifdef _WIN32
// I hope you know what you're doing!
if (!TerminateThread(m_hThread, exitCode))
return false;
CloseHandle( m_hThread );
m_hThread = NULL;
Cleanup();
#elif defined(POSIX)
pthread_kill( m_threadId, SIGKILL );
Cleanup();
#endif
return true;
#else
AssertMsg( 0, "Cannot terminate a thread on the Xbox!" );
return false;
#endif
}
//---------------------------------------------------------
//
// Get the Thread object that represents the current thread, if any.
// Can return NULL if the current thread was not created using
// CThread
//
CThread *CThread::GetCurrentCThread()
{
return g_pCurThread;
}
//---------------------------------------------------------
//
// Offer a context switch. Under Win32, equivalent to Sleep(0)
//
void CThread::Yield()
{
#ifdef _WIN32
::Sleep(0);
#elif defined(POSIX)
pthread_yield();
#endif
}
//---------------------------------------------------------
//
// This method causes the current thread to yield and not to be
// scheduled for further execution until a certain amount of real
// time has elapsed, more or less.
//
void CThread::Sleep(unsigned duration)
{
#ifdef _WIN32
::Sleep(duration);
#elif defined(POSIX)
usleep( duration * 1000 );
#endif
}
//---------------------------------------------------------
bool CThread::Init()
{
return true;
}
//---------------------------------------------------------
void CThread::OnExit()
{
}
//---------------------------------------------------------
void CThread::Cleanup()
{
m_threadId = 0;
}
//---------------------------------------------------------
bool CThread::WaitForCreateComplete(CThreadEvent * pEvent)
{
// Force serialized thread creation...
if (!pEvent->Wait(60000))
{
AssertMsg( 0, "Probably deadlock or failure waiting for thread to initialize." );
return false;
}
return true;
}
//---------------------------------------------------------
bool CThread::IsThreadRunning()
{
#ifdef _PS3
// ThreadIsThreadIdRunning() doesn't work on PS3 if the thread is in a zombie state
return m_eventTheadExit.Check();
#else
return ThreadIsThreadIdRunning( (ThreadId_t)m_threadId );
#endif
}
//---------------------------------------------------------
CThread::ThreadProc_t CThread::GetThreadProc()
{
return ThreadProc;
}
//---------------------------------------------------------
unsigned __stdcall CThread::ThreadProc(LPVOID pv)
{
std::auto_ptr<ThreadInit_t> pInit((ThreadInit_t *)pv);
#ifdef _X360
// Make sure all threads are consistent w.r.t floating-point math
SetupFPUControlWord();
#endif
CThread *pThread = pInit->pThread;
g_pCurThread = pThread;
g_pCurThread->m_pStackBase = AlignValue( &pThread, 4096 );
pInit->pThread->m_result = -1;
bool bInitSuccess = true;
if ( pInit->pfInitSuccess )
*(pInit->pfInitSuccess) = false;
try
{
bInitSuccess = pInit->pThread->Init();
}
catch (...)
{
pInit->pInitCompleteEvent->Set();
throw;
}
if ( pInit->pfInitSuccess )
*(pInit->pfInitSuccess) = bInitSuccess;
pInit->pInitCompleteEvent->Set();
if (!bInitSuccess)
return 0;
if ( pInit->pThread->m_flags & SUPPORT_STOP_PROTOCOL )
{
try
{
pInit->pThread->m_result = pInit->pThread->Run();
}
catch (...)
{
}
}
else
{
pInit->pThread->m_result = pInit->pThread->Run();
}
pInit->pThread->OnExit();
g_pCurThread = (int)NULL;
pInit->pThread->Cleanup();
return pInit->pThread->m_result;
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
CWorkerThread::CWorkerThread()
: m_EventSend(true), // must be manual-reset for PeekCall()
m_EventComplete(true), // must be manual-reset to handle multiple wait with thread properly
m_Param(0),
m_pParamFunctor(NULL),
m_ReturnVal(0)
{
}
//---------------------------------------------------------
int CWorkerThread::CallWorker(unsigned dw, unsigned timeout, bool fBoostWorkerPriorityToMaster, CFunctor *pParamFunctor)
{
return Call(dw, timeout, fBoostWorkerPriorityToMaster, NULL, pParamFunctor);
}
//---------------------------------------------------------
int CWorkerThread::CallMaster(unsigned dw, unsigned timeout)
{
return Call(dw, timeout, false);
}
//---------------------------------------------------------
CThreadEvent &CWorkerThread::GetCallHandle()
{
return m_EventSend;
}
//---------------------------------------------------------
unsigned CWorkerThread::GetCallParam( CFunctor **ppParamFunctor ) const
{
if( ppParamFunctor )
*ppParamFunctor = m_pParamFunctor;
return m_Param;
}
//---------------------------------------------------------
int CWorkerThread::BoostPriority()
{
int iInitialPriority = GetPriority();
const int iNewPriority = ThreadGetPriority( (ThreadHandle_t)GetThreadID() );
if (iNewPriority > iInitialPriority)
ThreadSetPriority( (ThreadHandle_t)GetThreadID(), iNewPriority);
return iInitialPriority;
}
//---------------------------------------------------------
static uint32 __stdcall DefaultWaitFunc( int nEvents, CThreadEvent * const *pEvents, int bWaitAll, uint32 timeout )
{
return ThreadWaitForEvents( nEvents, pEvents, bWaitAll!=0, timeout );
// return VCRHook_WaitForMultipleObjects( nHandles, (const void **)pHandles, bWaitAll, timeout );
}
int CWorkerThread::Call(unsigned dwParam, unsigned timeout, bool fBoostPriority, WaitFunc_t pfnWait, CFunctor *pParamFunctor)
{
AssertMsg(!m_EventSend.Check(), "Cannot perform call if there's an existing call pending" );
AUTO_LOCK( m_Lock );
if (!IsAlive())
return WTCR_FAIL;
int iInitialPriority = 0;
if (fBoostPriority)
{
iInitialPriority = BoostPriority();
}
// set the parameter, signal the worker thread, wait for the completion to be signaled
m_Param = dwParam;
m_pParamFunctor = pParamFunctor;
m_EventComplete.Reset();
m_EventSend.Set();
WaitForReply( timeout, pfnWait );
// MWD: Investigate why setting thread priorities is killing the 360
#ifndef _X360
if (fBoostPriority)
SetPriority(iInitialPriority);
#endif
return m_ReturnVal;
}
//---------------------------------------------------------
//
// Wait for a request from the client
//
//---------------------------------------------------------
int CWorkerThread::WaitForReply( unsigned timeout )
{
return WaitForReply( timeout, NULL );
}
int CWorkerThread::WaitForReply( unsigned timeout, WaitFunc_t pfnWait )
{
if (!pfnWait)
{
pfnWait = DefaultWaitFunc;
}
#ifdef WIN32
CThreadEvent threadEvent( GetThreadHandle() );
#endif
CThreadEvent *waits[] =
{
#ifdef WIN32
&threadEvent,
#endif
&m_EventComplete
};
unsigned result;
bool bInDebugger = Plat_IsInDebugSession();
do
{
#ifdef WIN32
// Make sure the thread handle hasn't been closed
if ( !GetThreadHandle() )
{
result = WAIT_OBJECT_0 + 1;
break;
}
#endif
result = (*pfnWait)((sizeof(waits) / sizeof(waits[0])), waits, false,
(timeout != TT_INFINITE) ? timeout : 30000);
AssertMsg(timeout != TT_INFINITE || result != WAIT_TIMEOUT, "Possible hung thread, call to thread timed out");
} while ( bInDebugger && ( timeout == TT_INFINITE && result == WAIT_TIMEOUT ) );
if ( result != WAIT_OBJECT_0 + 1 )
{
if (result == WAIT_TIMEOUT)
m_ReturnVal = WTCR_TIMEOUT;
else if (result == WAIT_OBJECT_0)
{
DevMsg( 2, "Thread failed to respond, probably exited\n");
m_EventSend.Reset();
m_ReturnVal = WTCR_TIMEOUT;
}
else
{
m_EventSend.Reset();
m_ReturnVal = WTCR_THREAD_GONE;
}
}
return m_ReturnVal;
}
//---------------------------------------------------------
//
// Wait for a request from the client
//
//---------------------------------------------------------
bool CWorkerThread::WaitForCall(unsigned * pResult)
{
return WaitForCall(TT_INFINITE, pResult);
}
//---------------------------------------------------------
bool CWorkerThread::WaitForCall(unsigned dwTimeout, unsigned * pResult)
{
bool returnVal = m_EventSend.Wait(dwTimeout);
if (pResult)
*pResult = m_Param;
return returnVal;
}
//---------------------------------------------------------
//
// is there a request?
//
bool CWorkerThread::PeekCall(unsigned * pParam, CFunctor **ppParamFunctor)
{
if (!m_EventSend.Check())
{
return false;
}
else
{
if (pParam)
{
*pParam = m_Param;
}
if( ppParamFunctor )
{
*ppParamFunctor = m_pParamFunctor;
}
return true;
}
}
//---------------------------------------------------------
//
// Reply to the request
//
void CWorkerThread::Reply(unsigned dw)
{
m_Param = 0;
m_ReturnVal = dw;
// The request is now complete so PeekCall() should fail from
// now on
//
// This event should be reset BEFORE we signal the client
m_EventSend.Reset();
// Tell the client we're finished
m_EventComplete.Set();
}
//-----------------------------------------------------------------------------
| 23.481497 | 170 | 0.623307 | DeadZoneLuna |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.