hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7a08d9381f44ca79b1933dcaba4489bc0af73e2b | 16,905 | cpp | C++ | src/VkRenderPass.cpp | HumpaLumpa007/LowPolyEngine | 800cfa84f6113424a2643a4a99fe214195e45cd5 | [
"MIT"
] | 6 | 2017-11-20T15:10:17.000Z | 2018-03-07T14:59:25.000Z | src/VkRenderPass.cpp | ClemensGerstung/LowPolyEngine | 800cfa84f6113424a2643a4a99fe214195e45cd5 | [
"MIT"
] | null | null | null | src/VkRenderPass.cpp | ClemensGerstung/LowPolyEngine | 800cfa84f6113424a2643a4a99fe214195e45cd5 | [
"MIT"
] | 1 | 2021-03-03T12:09:42.000Z | 2021-03-03T12:09:42.000Z | #include "VkRenderPass.h"
lpe::rendering::Attachment::Attachment(const vk::ImageView& imageView,
uint32_t index,
vk::ImageLayout layout,
const vk::AttachmentDescriptionFlags& flags,
vk::Format format,
vk::SampleCountFlagBits samples,
vk::AttachmentLoadOp loadOp,
vk::AttachmentStoreOp storeOp,
vk::AttachmentLoadOp stencilLoadOp,
vk::AttachmentStoreOp stencilStoreOp,
vk::ImageLayout initialLayout,
vk::ImageLayout finalLayout)
: ImageView(imageView),
Index(index),
Layout(layout),
Flags(flags),
Format(format),
Samples(samples),
LoadOp(loadOp),
StoreOp(storeOp),
StencilLoadOp(stencilLoadOp),
StencilStoreOp(stencilStoreOp),
InitialLayout(initialLayout),
FinalLayout(finalLayout)
{
}
vk::AttachmentReference lpe::rendering::Attachment::GetAttachmentReference() const
{
return { Index, Layout };
}
vk::AttachmentDescription lpe::rendering::Attachment::GetAttachmentDescription() const
{
return { Flags, Format, Samples, LoadOp, StoreOp, StencilLoadOp, StencilStoreOp, InitialLayout, FinalLayout };
}
lpe::rendering::Attachment::operator bool() const
{
return ImageView && Flags;
}
bool lpe::rendering::Attachment::operator!() const
{
return !(ImageView && Flags);
}
lpe::rendering::SubpassParameters::SubpassParameters(const std::vector<uint32_t>& inputAttachmentIndices,
const std::vector<uint32_t>& colorAttachmentIndices,
const std::vector<uint32_t>& resolveAttachmentIndices,
const std::vector<uint32_t>& preserveAttachmentIndices,
uint32_t depthAttachmentIndex,
vk::PipelineBindPoint bindPoint)
: InputAttachmentIndices(inputAttachmentIndices),
ColorAttachmentIndices(colorAttachmentIndices),
ResolveAttachmentIndices(resolveAttachmentIndices),
PreserveAttachmentIndices(preserveAttachmentIndices),
DepthAttachmentIndex(depthAttachmentIndex),
BindPoint(bindPoint)
{
}
lpe::rendering::SubpassParameters::SubpassParameters(const SubpassParameters& other)
: InputAttachmentIndices(other.InputAttachmentIndices),
ColorAttachmentIndices(other.ColorAttachmentIndices),
ResolveAttachmentIndices(other.ResolveAttachmentIndices),
PreserveAttachmentIndices(other.PreserveAttachmentIndices),
DepthAttachmentIndex(other.DepthAttachmentIndex),
BindPoint(other.BindPoint)
{
}
lpe::rendering::SubpassParameters::SubpassParameters(SubpassParameters&& other) noexcept
: InputAttachmentIndices(std::move(other.InputAttachmentIndices)),
ColorAttachmentIndices(std::move(other.ColorAttachmentIndices)),
ResolveAttachmentIndices(std::move(other.ResolveAttachmentIndices)),
PreserveAttachmentIndices(std::move(other.PreserveAttachmentIndices)),
DepthAttachmentIndex(other.DepthAttachmentIndex),
BindPoint(other.BindPoint)
{
}
lpe::rendering::SubpassParameters& lpe::rendering::SubpassParameters::operator=(const SubpassParameters& other)
{
if (this == &other) return *this;
InputAttachmentIndices = other.InputAttachmentIndices;
ColorAttachmentIndices = other.ColorAttachmentIndices;
ResolveAttachmentIndices = other.ResolveAttachmentIndices;
PreserveAttachmentIndices = other.PreserveAttachmentIndices;
DepthAttachmentIndex = other.DepthAttachmentIndex;
BindPoint = other.BindPoint;
return *this;
}
lpe::rendering::SubpassParameters& lpe::rendering::SubpassParameters::operator=(SubpassParameters&& other) noexcept
{
if (this == &other) return *this;
InputAttachmentIndices = std::move(other.InputAttachmentIndices);
ColorAttachmentIndices = std::move(other.ColorAttachmentIndices);
ResolveAttachmentIndices = std::move(other.ResolveAttachmentIndices);
PreserveAttachmentIndices = std::move(other.PreserveAttachmentIndices);
DepthAttachmentIndex = other.DepthAttachmentIndex;
BindPoint = other.BindPoint;
return *this;
}
void lpe::rendering::RenderPass::FillAttachments(std::vector<vk::AttachmentReference>& attachments,
const std::vector<uint32_t>& indices)
{
for (auto&& inputIndex : indices)
{
auto attachment = this->attachments[inputIndex];
if (attachment.Index != inputIndex)
{
auto iterator = std::find_if(std::begin(this->attachments),
std::end(this->attachments),
[index = inputIndex](const Attachment& attachment)
{
return attachment.Index == index;
});
if (iterator != std::end(this->attachments))
{
attachment = *iterator;
}
}
attachments.emplace_back(attachment.GetAttachmentReference());
}
}
lpe::rendering::RenderPass::RenderPass()
{
subpassDependencies = {};
attachments = {};
subpasses = {};
renderPass = nullptr;
currentFrameBuffer = nullptr;
currentCmdBuffer = nullptr;
state = RenderPassState::Creating;
}
lpe::rendering::RenderPass::RenderPass(const RenderPass& other)
{
this->operator=(other);
}
lpe::rendering::RenderPass::RenderPass(RenderPass&& other) noexcept
{
this->operator=(std::move(other));
}
lpe::rendering::RenderPass& lpe::rendering::RenderPass::operator=(const RenderPass& other)
{
this->subpassDependencies = { other.subpassDependencies };
this->attachments = { other.attachments };
this->subpasses = { other.subpasses };
this->renderPass = other.renderPass;
this->currentFrameBuffer = other.currentFrameBuffer;
this->currentCmdBuffer = other.currentCmdBuffer;
this->state = other.state;
return *this;
}
lpe::rendering::RenderPass& lpe::rendering::RenderPass::operator=(RenderPass&& other) noexcept
{
this->subpassDependencies = std::move(other.subpassDependencies);
this->attachments = std::move(other.attachments);
this->subpasses = std::move(other.subpasses);
this->renderPass = other.renderPass;
this->currentFrameBuffer = other.currentFrameBuffer;
this->currentCmdBuffer = other.currentCmdBuffer;
this->state = other.state;
return *this;
}
void lpe::rendering::RenderPass::AddAttachment(const vk::ImageView& view,
uint32_t index,
vk::ImageLayout layout,
const vk::AttachmentDescriptionFlags& flags,
vk::Format format,
vk::SampleCountFlagBits samples,
vk::AttachmentLoadOp loadOp,
vk::AttachmentStoreOp storeOp,
vk::AttachmentLoadOp stencilLoadOp,
vk::AttachmentStoreOp stencilStoreOp,
vk::ImageLayout initialLayout,
vk::ImageLayout finalLayout)
{
attachments.emplace_back(view,
index,
layout,
flags,
format,
samples,
loadOp,
storeOp,
stencilLoadOp,
stencilStoreOp,
initialLayout,
finalLayout);
}
void lpe::rendering::RenderPass::AddAttachment(const Attachment& attachment)
{
attachments.push_back(attachment);
}
void lpe::rendering::RenderPass::AddAttachment(Attachment&& attachment)
{
attachments.push_back(attachment);
}
void lpe::rendering::RenderPass::AddSubpass(vk::PipelineBindPoint bindPoint,
std::vector<uint32_t> inputAttachments,
std::vector<uint32_t> colorAttachments,
std::vector<uint32_t> resolveAttachments,
uint32_t depthAttachment,
std::vector<uint32_t> preserveAttachments)
{
subpasses.emplace_back(inputAttachments,
colorAttachments,
resolveAttachments,
preserveAttachments,
depthAttachment,
bindPoint);
}
void lpe::rendering::RenderPass::AddSubpass(const SubpassParameters& attachment)
{
subpasses.push_back(attachment);
}
void lpe::rendering::RenderPass::AddSubpass(SubpassParameters&& attachment)
{
subpasses.push_back(attachment);
}
void lpe::rendering::RenderPass::AddSubpassDependency(uint32_t srcSubpass,
uint32_t dstSubpass,
vk::PipelineStageFlags srcStageMask,
vk::PipelineStageFlags dstStageMask,
vk::AccessFlags srcAccessMask,
vk::AccessFlags dstAccessMask,
vk::DependencyFlags dependencyFlags)
{
subpassDependencies.emplace_back(srcSubpass,
dstSubpass,
srcStageMask,
dstStageMask,
srcAccessMask,
dstAccessMask,
dependencyFlags);
}
const vk::RenderPass& lpe::rendering::RenderPass::Create(vk::Device device)
{
assert(state == RenderPassState::Creating);
std::vector<vk::AttachmentReference> inputAttachments;
std::vector<vk::AttachmentReference> colorAttachments;
std::vector<vk::AttachmentReference> resolveAttachments;
vk::AttachmentReference depthAttachment;
std::vector<vk::SubpassDescription> subpassDescriptions;
std::vector<vk::AttachmentDescription> attachmentDescriptions;
attachmentDescriptions.resize(attachments.size());
for (auto&& subpass : subpasses)
{
inputAttachments.clear();
colorAttachments.clear();
resolveAttachments.clear();
depthAttachment = VK_NULL_HANDLE;
auto attachment = attachments[subpass.DepthAttachmentIndex];
if (attachment.Index != subpass.DepthAttachmentIndex)
{
auto iterator = std::find_if(std::begin(attachments),
std::end(attachments),
[index = subpass.DepthAttachmentIndex](const Attachment& attachment)
{
return attachment.Index == index;
});
if (iterator != std::end(attachments))
{
attachment = *iterator;
}
}
depthAttachment = attachment.GetAttachmentReference();
FillAttachments(inputAttachments,
subpass.InputAttachmentIndices);
FillAttachments(colorAttachments,
subpass.ColorAttachmentIndices);
FillAttachments(resolveAttachments,
subpass.ResolveAttachmentIndices);
subpassDescriptions.emplace_back(vk::SubpassDescriptionFlags(),
subpass.BindPoint,
static_cast<uint32_t>(inputAttachments.size()),
inputAttachments.data(),
static_cast<uint32_t>(colorAttachments.size()),
colorAttachments.data(),
resolveAttachments.data(),
&depthAttachment,
static_cast<uint32_t>(subpass.PreserveAttachmentIndices.size()),
subpass.PreserveAttachmentIndices.data());
}
for (uint32_t i = 0; i < attachments.size(); ++i)
{
auto attachment = attachments[i];
if (attachment.Index != i)
{
auto iterator = std::find_if(std::begin(this->attachments),
std::end(this->attachments),
[index = i](const Attachment& attachment)
{
return attachment.Index == index;
});
if (iterator != std::end(this->attachments))
{
attachment = *iterator;
}
}
attachmentDescriptions[i] = attachment.GetAttachmentDescription();
}
vk::RenderPassCreateInfo createInfo =
{
{},
static_cast<uint32_t>(attachmentDescriptions.size()),
attachmentDescriptions.data(),
static_cast<uint32_t>(subpassDescriptions.size()),
subpassDescriptions.data(),
static_cast<uint32_t>(subpassDependencies.size()),
subpassDependencies.data()
};
auto result = device.createRenderPass(&createInfo,
nullptr,
&renderPass);
assert(result == vk::Result::eSuccess);
state = RenderPassState::Created;
return renderPass;
}
const vk::Framebuffer& lpe::rendering::RenderPass::CreateFrameBuffer(vk::Device device,
uint32_t width,
uint32_t height,
uint32_t layers)
{
assert(state == RenderPassState::Created && renderPass);
std::vector<vk::ImageView> views;
views.resize(attachments.size());
for (uint32_t i = 0; i < attachments.size(); ++i)
{
auto attachment = attachments[i];
if (attachment.Index != i)
{
auto iterator = std::find_if(std::begin(this->attachments),
std::end(this->attachments),
[index = i](const Attachment& attachment)
{
return attachment.Index == index;
});
if (iterator != std::end(this->attachments))
{
attachment = *iterator;
}
}
views[i] = attachment.ImageView;
}
vk::FramebufferCreateInfo createInfo =
{
{},
renderPass,
static_cast<uint32_t>(views.size()),
views.data(),
width,
height,
layers
};
auto result = device.createFramebuffer(&createInfo,
nullptr,
¤tFrameBuffer);
assert(result == vk::Result::eSuccess);
return currentFrameBuffer;
}
void lpe::rendering::RenderPass::Begin(vk::CommandBuffer cmdBuffer,
vk::Rect2D renderArea,
std::vector<vk::ClearValue> clearValues,
vk::SubpassContents contents)
{
assert((state == RenderPassState::Created || state == RenderPassState::Ended) && currentFrameBuffer && renderPass);
vk::RenderPassBeginInfo beginInfo =
{
renderPass,
currentFrameBuffer,
renderArea,
static_cast<uint32_t>(clearValues.size()),
clearValues.data()
};
cmdBuffer.beginRenderPass(&beginInfo,
contents);
currentCmdBuffer = cmdBuffer;
state = RenderPassState::Recording;
}
void lpe::rendering::RenderPass::NextSubpass(vk::SubpassContents contents)
{
assert(state == RenderPassState::Recording && currentFrameBuffer && renderPass && currentCmdBuffer);
currentCmdBuffer.nextSubpass(contents);
}
void lpe::rendering::RenderPass::End(vk::Device device)
{
assert(state == RenderPassState::Recording && currentCmdBuffer && currentFrameBuffer);
currentCmdBuffer.endRenderPass();
device.destroyFramebuffer(currentFrameBuffer,
nullptr);
currentFrameBuffer = nullptr;
currentCmdBuffer = nullptr;
state = RenderPassState::Ended;
}
void lpe::rendering::RenderPass::Destroy(vk::Device device)
{
assert(state == RenderPassState::Ended && renderPass);
if (currentFrameBuffer)
{
device.destroyFramebuffer(currentFrameBuffer,
nullptr);
currentFrameBuffer = nullptr;
}
device.destroyRenderPass(renderPass,
nullptr);
renderPass = nullptr;
}
| 35.664557 | 117 | 0.577048 | [
"vector"
] |
7a09eaca4652c76372fa29107e0e185b21d765f3 | 4,337 | cc | C++ | src/support.cc | TerenceWangh/leetcode | a6287d3928fb7114c39a430d149879ca8fa71020 | [
"MIT"
] | 3 | 2018-12-06T10:49:01.000Z | 2020-12-15T18:30:09.000Z | src/support.cc | TerenceWangh/leetcode | a6287d3928fb7114c39a430d149879ca8fa71020 | [
"MIT"
] | null | null | null | src/support.cc | TerenceWangh/leetcode | a6287d3928fb7114c39a430d149879ca8fa71020 | [
"MIT"
] | null | null | null | #include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
#include <queue>
#include "support.h"
using std::string;
using std::stringstream;
using std::vector;
int stringToInteger(string input)
{
return stoi(input);
}
double stringToDouble(string input)
{
return stod(input);
}
void trimLeftTrailingSpaces(string &input)
{
input.erase(input.begin(), find_if(input.begin(), input.end(), [](int ch) {
return !isspace(ch);
}));
}
void trimRightTrailingSpaces(string &input)
{
input.erase(find_if(input.rbegin(), input.rend(), [](int ch) {
return !isspace(ch);
}).base(),
input.end());
}
vector<int> stringToIntegerVector(const string &input)
{
vector<int> output;
string copied(input);
trimLeftTrailingSpaces(copied);
trimRightTrailingSpaces(copied);
copied = copied.substr(1, copied.length() - 2);
stringstream ss;
ss.str(copied);
string item;
char delim = ',';
while (getline(ss, item, delim))
{
output.push_back(stoi(item));
}
return output;
}
void printList(ListNode *l)
{
while (l)
{
std::cout << l->val;
if (l->next)
std::cout << "->";
l = l->next;
}
}
ListNode *stringToListNode(const string &input)
{
vector<int> list = stringToIntegerVector(input);
ListNode *dummyRoot = new ListNode(0);
ListNode *ptr = dummyRoot;
for (int item : list)
{
ptr->next = new ListNode(item);
ptr = ptr->next;
}
ptr = dummyRoot->next;
delete dummyRoot;
return ptr;
}
string listNodeToString(ListNode *node)
{
if (node == nullptr)
{
return "[]";
}
string result;
while (node)
{
result += std::to_string(node->val) + ", ";
node = node->next;
}
return "[" + result.substr(0, result.length() - 2) + "]";
}
void freeList(ListNode *root)
{
ListNode *tmp;
while (root)
{
tmp = root;
root = root->next;
delete tmp;
}
}
bool compare_fn(std::vector<int> &v1, std::vector<int> &v2)
{
for (unsigned i = 0; i < v1.size() && i < v2.size(); i++)
{
if (v1[i] < v2[i])
return true;
if (v1[i] > v2[i])
return false;
}
return v1.size() < v2.size();
}
std::string treeNodeToString(TreeNode *root)
{
if (root == nullptr)
return "[]";
string output = "";
std::queue<TreeNode *> q;
q.push(root);
while (!q.empty())
{
TreeNode *node = q.front();
q.pop();
if (node == nullptr)
{
output += "null, ";
continue;
}
output += std::to_string(node->val) + ", ";
q.push(node->left);
q.push(node->right);
}
return "[" + output.substr(0, output.length() - 2) + "]";
}
TreeNode *stringToTreeNode(string input)
{
trimLeftTrailingSpaces(input);
trimRightTrailingSpaces(input);
input = input.substr(1, input.length() - 2);
if (!input.size())
return nullptr;
string item;
stringstream ss;
ss.str(input);
getline(ss, item, ',');
TreeNode *root = new TreeNode(stoi(item));
std::queue<TreeNode *> nodeQueue;
nodeQueue.push(root);
while (true)
{
TreeNode *node = nodeQueue.front();
nodeQueue.pop();
if (!getline(ss, item, ','))
{
break;
}
trimLeftTrailingSpaces(item);
if (item != "null")
{
int leftNumber = stoi(item);
node->left = new TreeNode(leftNumber);
nodeQueue.push(node->left);
}
if (!getline(ss, item, ','))
{
break;
}
trimLeftTrailingSpaces(item);
if (item != "null")
{
int rightNumber = stoi(item);
node->right = new TreeNode(rightNumber);
nodeQueue.push(node->right);
}
}
return root;
}
void prettyPrintTree(TreeNode *node, string prefix = "", bool isLeft = true)
{
if (node == nullptr)
{
std::cout << "Empty tree";
return;
}
if (node->right)
{
prettyPrintTree(node->right, prefix + (isLeft ? "│ " : " "), false);
}
std::cout << prefix + (isLeft ? "└── " : "┌── ") + std::to_string(node->val);
std::cout << std::endl;
if (node->left)
prettyPrintTree(node->left, prefix + (isLeft ? " " : "│ "), true);
}
| 19.624434 | 80 | 0.551533 | [
"vector"
] |
7a134d9895640a2cb0ea334a8b7e07509de9728c | 989 | cpp | C++ | the-skyline-problem-test.cpp | cfriedt/leetcode | ad15031b407b895f12704897eb81042d7d56d07d | [
"MIT"
] | 1 | 2021-01-20T16:04:54.000Z | 2021-01-20T16:04:54.000Z | the-skyline-problem-test.cpp | cfriedt/leetcode | ad15031b407b895f12704897eb81042d7d56d07d | [
"MIT"
] | 293 | 2018-11-29T14:54:29.000Z | 2021-01-29T16:07:26.000Z | the-skyline-problem-test.cpp | cfriedt/leetcode | ad15031b407b895f12704897eb81042d7d56d07d | [
"MIT"
] | 1 | 2020-11-10T10:49:12.000Z | 2020-11-10T10:49:12.000Z | /*
* Copyright (c) 2021, Christopher Friedt
*
* SPDX-License-Identifier: MIT
*/
#include <gtest/gtest.h>
#include "the-skyline-problem.cpp"
using namespace std;
TEST(TheSkylineProblem, 2_9_10__3_7_15__5_12_12__15_20_10__19_24_8) {
vector<vector<int>> buildings = {
{2, 9, 10}, {3, 7, 15}, {5, 12, 12}, {15, 20, 10}, {19, 24, 8}};
vector<vector<int>> expected = {{2, 10}, {3, 15}, {7, 12}, {12, 0},
{15, 10}, {20, 8}, {24, 0}};
EXPECT_EQ(expected, Solution().getSkyline(buildings));
}
TEST(TheSkylineProblem, 0_2_3__2_5_3) {
vector<vector<int>> buildings = {{0, 2, 3}, {2, 5, 3}};
vector<vector<int>> expected = {{0, 3}, {5, 0}};
EXPECT_EQ(expected, Solution().getSkyline(buildings));
}
#if 0
TEST(TheSkylineProblem, 0_2147483647_2147483647) {
vector<vector<int>> buildings = {{0, 2147483647, 2147483647}};
vector<vector<int>> expected = {{2147483647, 0}};
EXPECT_EQ(expected, Solution().getSkyline(buildings));
}
#endif
| 29.088235 | 70 | 0.632963 | [
"vector"
] |
7a238de9cddf489b83a149fbeabb63be8a83c503 | 2,093 | cpp | C++ | net.ssa/AlexRR_Editor/UI_RControl.cpp | ixray-team/xray-vss-archive | b245c8601dcefb505b4b51f58142da6769d4dc92 | [
"Linux-OpenIB"
] | 1 | 2022-03-26T17:00:19.000Z | 2022-03-26T17:00:19.000Z | AlexRR_Editor/UI_RControl.cpp | ixray-team/xray-vss-archive | b245c8601dcefb505b4b51f58142da6769d4dc92 | [
"Linux-OpenIB"
] | null | null | null | AlexRR_Editor/UI_RControl.cpp | ixray-team/xray-vss-archive | b245c8601dcefb505b4b51f58142da6769d4dc92 | [
"Linux-OpenIB"
] | 1 | 2022-03-26T17:00:21.000Z | 2022-03-26T17:00:21.000Z | //----------------------------------------------------
// file: UI_RControl.cpp
//----------------------------------------------------
#include "Pch.h"
#pragma hdrstop
#include "NetDeviceLog.h"
#include "UI_Main.h"
//----------------------------------------------------
UI_RControl::UI_RControl()
:UI_ViewControl()
{
m_SaveTransform.identity();
m_RCenter.set( 0, 0, 0 );
}
UI_RControl::~UI_RControl(){
}
//----------------------------------------------------
void UI_RControl::MouseStartMove(){
m_SaveTransform.set( UI.m_Camera );
m_RCenter.set( UI.pivot() );
}
void UI_RControl::MouseEndMove(){
}
void UI_RControl::MouseMove(){
float kr = 0.0005f;
if( m_Accelerated )
kr *= 5.f;
if( m_Alternate ){
IMatrix rmatrix;
if( m_RelMove.x ){
IVector vr;
vr.set( 0, 1, 0 );
rmatrix.r( m_RelMove.x * kr, vr );
//rmatrix.r( m_RelMove.x * kr, UI.m_Camera.j );
UI.m_Camera.c.sub( m_RCenter );
rmatrix.transform( UI.m_Camera.c );
UI.m_Camera.c.add( m_RCenter );
rmatrix.transform( UI.m_Camera.i );
rmatrix.transform( UI.m_Camera.j );
rmatrix.transform( UI.m_Camera.k ); }
if( m_RelMove.y ){
rmatrix.r( m_RelMove.y * kr, UI.m_Camera.i );
UI.m_Camera.c.sub( m_RCenter );
rmatrix.transform( UI.m_Camera.c );
UI.m_Camera.c.add( m_RCenter );
rmatrix.transform( UI.m_Camera.i );
rmatrix.transform( UI.m_Camera.j );
rmatrix.transform( UI.m_Camera.k ); }
} else {
IMatrix rmatrix;
if( m_RelMove.x ){
IVector vr;
vr.set( 0, 1, 0 );
rmatrix.r( m_RelMove.x * kr, vr );
//rmatrix.r( m_RelMove.x * kr, UI.m_Camera.j );
rmatrix.transform( UI.m_Camera.i );
rmatrix.transform( UI.m_Camera.j );
rmatrix.transform( UI.m_Camera.k ); }
if( m_RelMove.y ){
rmatrix.r( m_RelMove.y * kr, UI.m_Camera.i );
rmatrix.transform( UI.m_Camera.i );
rmatrix.transform( UI.m_Camera.j );
rmatrix.transform( UI.m_Camera.k ); }
}
UI.Redraw();
}
//----------------------------------------------------
| 22.031579 | 55 | 0.52795 | [
"transform"
] |
7a239233b0abd491116a79fbd7a448c53f8e2adc | 7,006 | cpp | C++ | MonoNative.Tests/mscorlib/System/Diagnostics/SymbolStore/mscorlib_System_Diagnostics_SymbolStore_ISymbolWriter_Fixture.cpp | brunolauze/MonoNative | 959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66 | [
"BSD-2-Clause"
] | 7 | 2015-03-10T03:36:16.000Z | 2021-11-05T01:16:58.000Z | MonoNative.Tests/mscorlib/System/Diagnostics/SymbolStore/mscorlib_System_Diagnostics_SymbolStore_ISymbolWriter_Fixture.cpp | brunolauze/MonoNative | 959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66 | [
"BSD-2-Clause"
] | 1 | 2020-06-23T10:02:33.000Z | 2020-06-24T02:05:47.000Z | MonoNative.Tests/mscorlib/System/Diagnostics/SymbolStore/mscorlib_System_Diagnostics_SymbolStore_ISymbolWriter_Fixture.cpp | brunolauze/MonoNative | 959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66 | [
"BSD-2-Clause"
] | null | null | null | // Mono Native Fixture
// Assembly: mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
// Namespace: System.Diagnostics.SymbolStore
// Name: ISymbolWriter
// C++ Typed Name: mscorlib::System::Diagnostics::SymbolStore::ISymbolWriter
#include <gtest/gtest.h>
#include <mscorlib/System/Diagnostics/SymbolStore/mscorlib_System_Diagnostics_SymbolStore_ISymbolWriter.h>
#include <mscorlib/System/Diagnostics/SymbolStore/mscorlib_System_Diagnostics_SymbolStore_ISymbolDocumentWriter.h>
#include <mscorlib/System/mscorlib_System_String.h>
#include <mscorlib/System/mscorlib_System_Guid.h>
#include <mscorlib/System/Diagnostics/SymbolStore/mscorlib_System_Diagnostics_SymbolStore_SymbolToken.h>
#include <mscorlib/System/mscorlib_System_Byte.h>
namespace mscorlib
{
namespace System
{
namespace Diagnostics
{
namespace SymbolStore
{
//Public Methods Tests
// Method Close
// Signature:
TEST(mscorlib_System_Diagnostics_SymbolStore_ISymbolWriter_Fixture,Close_Test)
{
}
// Method CloseMethod
// Signature:
TEST(mscorlib_System_Diagnostics_SymbolStore_ISymbolWriter_Fixture,CloseMethod_Test)
{
}
// Method CloseNamespace
// Signature:
TEST(mscorlib_System_Diagnostics_SymbolStore_ISymbolWriter_Fixture,CloseNamespace_Test)
{
}
// Method CloseScope
// Signature: mscorlib::System::Int32 endOffset
TEST(mscorlib_System_Diagnostics_SymbolStore_ISymbolWriter_Fixture,CloseScope_Test)
{
}
// Method DefineDocument
// Signature: mscorlib::System::String url, mscorlib::System::Guid language, mscorlib::System::Guid languageVendor, mscorlib::System::Guid documentType
TEST(mscorlib_System_Diagnostics_SymbolStore_ISymbolWriter_Fixture,DefineDocument_Test)
{
}
// Method DefineField
// Signature: mscorlib::System::Diagnostics::SymbolStore::SymbolToken parent, mscorlib::System::String name, mscorlib::System::Reflection::FieldAttributes::__ENUM__ attributes, std::vector<mscorlib::System::Byte*> signature, mscorlib::System::Diagnostics::SymbolStore::SymAddressKind::__ENUM__ addrKind, mscorlib::System::Int32 addr1, mscorlib::System::Int32 addr2, mscorlib::System::Int32 addr3
TEST(mscorlib_System_Diagnostics_SymbolStore_ISymbolWriter_Fixture,DefineField_Test)
{
}
// Method DefineGlobalVariable
// Signature: mscorlib::System::String name, mscorlib::System::Reflection::FieldAttributes::__ENUM__ attributes, std::vector<mscorlib::System::Byte*> signature, mscorlib::System::Diagnostics::SymbolStore::SymAddressKind::__ENUM__ addrKind, mscorlib::System::Int32 addr1, mscorlib::System::Int32 addr2, mscorlib::System::Int32 addr3
TEST(mscorlib_System_Diagnostics_SymbolStore_ISymbolWriter_Fixture,DefineGlobalVariable_Test)
{
}
// Method DefineLocalVariable
// Signature: mscorlib::System::String name, mscorlib::System::Reflection::FieldAttributes::__ENUM__ attributes, std::vector<mscorlib::System::Byte*> signature, mscorlib::System::Diagnostics::SymbolStore::SymAddressKind::__ENUM__ addrKind, mscorlib::System::Int32 addr1, mscorlib::System::Int32 addr2, mscorlib::System::Int32 addr3, mscorlib::System::Int32 startOffset, mscorlib::System::Int32 endOffset
TEST(mscorlib_System_Diagnostics_SymbolStore_ISymbolWriter_Fixture,DefineLocalVariable_Test)
{
}
// Method DefineParameter
// Signature: mscorlib::System::String name, mscorlib::System::Reflection::ParameterAttributes::__ENUM__ attributes, mscorlib::System::Int32 sequence, mscorlib::System::Diagnostics::SymbolStore::SymAddressKind::__ENUM__ addrKind, mscorlib::System::Int32 addr1, mscorlib::System::Int32 addr2, mscorlib::System::Int32 addr3
TEST(mscorlib_System_Diagnostics_SymbolStore_ISymbolWriter_Fixture,DefineParameter_Test)
{
}
// Method DefineSequencePoints
// Signature: mscorlib::System::Diagnostics::SymbolStore::ISymbolDocumentWriter document, std::vector<mscorlib::System::Int32*> offsets, std::vector<mscorlib::System::Int32*> lines, std::vector<mscorlib::System::Int32*> columns, std::vector<mscorlib::System::Int32*> endLines, std::vector<mscorlib::System::Int32*> endColumns
TEST(mscorlib_System_Diagnostics_SymbolStore_ISymbolWriter_Fixture,DefineSequencePoints_Test)
{
}
// Method Initialize
// Signature: mscorlib::System::IntPtr emitter, mscorlib::System::String filename, mscorlib::System::Boolean fFullBuild
TEST(mscorlib_System_Diagnostics_SymbolStore_ISymbolWriter_Fixture,Initialize_Test)
{
}
// Method OpenMethod
// Signature: mscorlib::System::Diagnostics::SymbolStore::SymbolToken method
TEST(mscorlib_System_Diagnostics_SymbolStore_ISymbolWriter_Fixture,OpenMethod_Test)
{
}
// Method OpenNamespace
// Signature: mscorlib::System::String name
TEST(mscorlib_System_Diagnostics_SymbolStore_ISymbolWriter_Fixture,OpenNamespace_Test)
{
}
// Method OpenScope
// Signature: mscorlib::System::Int32 startOffset
TEST(mscorlib_System_Diagnostics_SymbolStore_ISymbolWriter_Fixture,OpenScope_Test)
{
}
// Method SetMethodSourceRange
// Signature: mscorlib::System::Diagnostics::SymbolStore::ISymbolDocumentWriter startDoc, mscorlib::System::Int32 startLine, mscorlib::System::Int32 startColumn, mscorlib::System::Diagnostics::SymbolStore::ISymbolDocumentWriter endDoc, mscorlib::System::Int32 endLine, mscorlib::System::Int32 endColumn
TEST(mscorlib_System_Diagnostics_SymbolStore_ISymbolWriter_Fixture,SetMethodSourceRange_Test)
{
}
// Method SetScopeRange
// Signature: mscorlib::System::Int32 scopeID, mscorlib::System::Int32 startOffset, mscorlib::System::Int32 endOffset
TEST(mscorlib_System_Diagnostics_SymbolStore_ISymbolWriter_Fixture,SetScopeRange_Test)
{
}
// Method SetSymAttribute
// Signature: mscorlib::System::Diagnostics::SymbolStore::SymbolToken parent, mscorlib::System::String name, std::vector<mscorlib::System::Byte*> data
TEST(mscorlib_System_Diagnostics_SymbolStore_ISymbolWriter_Fixture,SetSymAttribute_Test)
{
}
// Method SetUnderlyingWriter
// Signature: mscorlib::System::IntPtr underlyingWriter
TEST(mscorlib_System_Diagnostics_SymbolStore_ISymbolWriter_Fixture,SetUnderlyingWriter_Test)
{
}
// Method SetUserEntryPoint
// Signature: mscorlib::System::Diagnostics::SymbolStore::SymbolToken entryMethod
TEST(mscorlib_System_Diagnostics_SymbolStore_ISymbolWriter_Fixture,SetUserEntryPoint_Test)
{
}
// Method UsingNamespace
// Signature: mscorlib::System::String fullName
TEST(mscorlib_System_Diagnostics_SymbolStore_ISymbolWriter_Fixture,UsingNamespace_Test)
{
}
}
}
}
}
| 36.113402 | 408 | 0.748787 | [
"vector"
] |
7a2b538961f79db615da2cd956d8b1a4d8043ecc | 701 | cpp | C++ | leetcode_0044_字符串_动态规划.cpp | xiaoxiaoxiang-Wang/01-leetcode | 5a9426dd70c3dd6725444783aaa8cefc27196779 | [
"MIT"
] | null | null | null | leetcode_0044_字符串_动态规划.cpp | xiaoxiaoxiang-Wang/01-leetcode | 5a9426dd70c3dd6725444783aaa8cefc27196779 | [
"MIT"
] | null | null | null | leetcode_0044_字符串_动态规划.cpp | xiaoxiaoxiang-Wang/01-leetcode | 5a9426dd70c3dd6725444783aaa8cefc27196779 | [
"MIT"
] | null | null | null | class Solution {
public:
bool isMatch(string s, string p) {
int m = s.length();
int n = p.length();
vector<vector<bool>> dp(m+1,vector<bool>(n+1));
// dp[i][j]表示s的前i个字符和p的前j个字符是否匹配
dp[0][0] = true;
for (int i=1; i<=n; i++) {
if(p[i-1]=='*') {
dp[0][i] = true;
} else {
break;
}
}
for(int i=1;i<=m;i++) {
for(int j=1;j<=n;j++) {
if((p[j-1]=='*'&&(dp[i-1][j]||dp[i][j-1]||dp[i-1][j-1]))||
(dp[i-1][j-1]&&(p[j-1]=='?'||s[i-1]==p[j-1]))){
dp[i][j]=true;
}
}
}
return dp[m][n];
}
}; | 26.961538 | 74 | 0.342368 | [
"vector"
] |
7a3134604ff9a39126a5387b6400e70bdbe4784c | 20,907 | cc | C++ | src/live.cc | AnthonyBrunasso/test_games | 31354d2bf95aae9a880e7292bc78ad8577b3f09c | [
"MIT"
] | null | null | null | src/live.cc | AnthonyBrunasso/test_games | 31354d2bf95aae9a880e7292bc78ad8577b3f09c | [
"MIT"
] | null | null | null | src/live.cc | AnthonyBrunasso/test_games | 31354d2bf95aae9a880e7292bc78ad8577b3f09c | [
"MIT"
] | 2 | 2019-11-12T23:15:18.000Z | 2020-01-15T17:49:27.000Z | // Singleplayer game template.
#define SINGLE_PLAYER
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <queue>
#include <functional>
#include <optional>
#include "math/math.cc"
#include "renderer/renderer.cc"
#include "renderer/camera.cc"
#include "renderer/imui.cc"
#include "animation/fsm.cc"
#define WIN_ATTACH_DEBUGGER 0
#define DEBUG_PHYSICS 0
#define DEBUG_UI 0
#define PLATFORMER_CAMERA 1
static b8 kRenderCharacterAabb = false;
static b8 kRenderGrid = false;
static b8 kRenderGridFill = false;
static b8 kDebugImui = false;
struct State {
// Game and render updates per second
u64 framerate = 60;
// Calculated available microseconds per game_update
u64 frame_target_usec;
// Estimate of gime passed since game start.
u64 game_time_usec = 0;
// Estimated frames per second.
r32 frames_per_second = 0;
// (optional) yield unused cpu time to the system
b8 sleep_on_loop = true;
// Number of times the game has been updated.
u64 game_updates = 0;
// Parameters window::Create will be called with.
window::CreateInfo window_create_info;
// Id to music.
u32 music_id;
// Game clock.
platform::Clock game_clock;
};
static State kGameState;
static Stats kGameStats;
namespace std {
template <>
struct hash<v2i>
{
std::size_t
operator()(const v2i& grid) const
{
// Arbitrarily large prime numbers
const size_t h1 = 0x8da6b343;
const size_t h2 = 0xd8163841;
return grid.x * h1 + grid.y * h2;
}
};
}
#include "live/components.cc"
#include "live/constants.cc"
#include "live/sim.cc"
static char kUIBuffer[64];
enum DebugUIState {
kDiagnosticsViewer,
kEntityViewer,
kDebugViewer,
};
void
SetFramerate(u64 fr)
{
kGameState.framerate = fr;
kGameState.frame_target_usec = 1000.f * 1000.f / kGameState.framerate;
}
void
DebugUIRenderDiagnostics()
{
v2f screen = window::GetWindowSize();
static r32 right_align = 130.f;
imui::TextOptions debug_options;
debug_options.color = imui::kWhite;
debug_options.highlight_color = imui::kRed;
imui::SameLine();
imui::Width(right_align);
imui::Text("Frame Time");
snprintf(kUIBuffer, sizeof(kUIBuffer), "%04.02fus [%02.02f%%]",
StatsMean(&kGameStats), 100.f * StatsUnbiasedRsDev(&kGameStats));
imui::Text(kUIBuffer);
imui::NewLine();
imui::SameLine();
imui::Width(right_align);
imui::Text("Game Time");
snprintf(kUIBuffer, sizeof(kUIBuffer), "%04.02fs",
(r64)kGameState.game_time_usec / 1e6);
imui::Text(kUIBuffer);
imui::NewLine();
imui::SameLine();
imui::Width(right_align);
imui::Text("AVG FPS");
snprintf(kUIBuffer, sizeof(kUIBuffer), "%04.02ff/s",
(r64)kGameState.game_updates /
((r64)kGameState.game_time_usec / 1e6));
imui::Text(kUIBuffer);
imui::NewLine();
imui::SameLine();
imui::Width(right_align);
imui::Text("Window Size");
snprintf(kUIBuffer, sizeof(kUIBuffer), "%.0fx%.0f", screen.x, screen.y);
imui::Text(kUIBuffer);
imui::NewLine();
imui::SameLine();
imui::Width(right_align);
imui::Text("Camera Pos");
v3f cpos = rgg::CameraPosition();
snprintf(kUIBuffer, sizeof(kUIBuffer), "(%.0f, %.0f, %.0f)", cpos.x, cpos.y, cpos.z);
imui::Text(kUIBuffer);
imui::NewLine();
imui::SameLine();
imui::Width(right_align);
imui::Text("Cursor World");
v2f wpos = rgg::CameraRayFromMouseToWorld(window::GetCursorPosition(), 1.f).xy();
snprintf(kUIBuffer, sizeof(kUIBuffer), "(%.0f, %.0f)", wpos.x, wpos.y);
imui::Text(kUIBuffer);
imui::NewLine();
v2i gpos;
if (live::GridXYFromPos(wpos, &gpos)) {
imui::SameLine();
imui::Width(right_align);
imui::Text("Cursor Grid");
snprintf(kUIBuffer, sizeof(kUIBuffer), "(%i, %i)", gpos.x, gpos.y);
imui::Text(kUIBuffer);
imui::NewLine();
}
imui::SameLine();
imui::Width(right_align);
imui::Text("Game Speed");
if (imui::Text("120 ", debug_options).clicked) {
SetFramerate(120);
}
if (imui::Text("60 ", debug_options).clicked) {
SetFramerate(60);
}
if (imui::Text("30 ", debug_options).clicked) {
SetFramerate(30);
}
if (imui::Text("10 ", debug_options).clicked) {
SetFramerate(10);
}
if (imui::Text("5 ", debug_options).clicked) {
SetFramerate(5);
}
imui::NewLine();
Rectf swb = live::ScreenBounds();
imui::Width(right_align);
imui::Text("World Screen");
snprintf(kUIBuffer, sizeof(kUIBuffer), "(%.2f, %.2f, %.2f, %.2f)", swb.x, swb.y, swb.width, swb.height);
imui::Text(kUIBuffer);
imui::NewLine();
}
void
DebugUIRenderEntity()
{
static r32 right_align = 130.f;
// TODO: Current grid
live::Grid* grid = live::GridGet(1);
v2f wpos = rgg::CameraRayFromMouseToWorld(window::GetCursorPosition(), 1.f).xy();
v2i gpos;
if (live::GridXYFromPos(wpos, &gpos)) {
live::Cell* cell = grid->Get(gpos);
assert(cell != nullptr);
imui::SameLine();
imui::Width(right_align);
imui::Text("Cursor Grid");
snprintf(kUIBuffer, sizeof(kUIBuffer), "(%i, %i)", gpos.x, gpos.y);
imui::Text(kUIBuffer);
imui::NewLine();
for (u32 entity_id : cell->entity_ids) {
ecs::Entity* entity = ecs::FindEntity(entity_id);
assert(entity != nullptr);
imui::SameLine();
snprintf(kUIBuffer, sizeof(kUIBuffer), "Entity(%u)", entity_id);
imui::Text(kUIBuffer);
imui::NewLine();
for (u64 i = 0; i < ecs::kComponentCount; ++i) {
ecs::TypeId type_id = (ecs::TypeId)i;
if (entity->Has(type_id)) {
snprintf(kUIBuffer, sizeof(kUIBuffer), " %s", ecs::TypeName(type_id));
imui::Text(kUIBuffer);
switch (type_id)
{
case ecs::kPhysicsComponent: {
ecs::PhysicsComponent* physics = ecs::GetPhysicsComponent(entity);
snprintf(kUIBuffer, sizeof(kUIBuffer), " pos: %.2f, %.2f", physics->pos.x, physics->pos.y);
imui::Text(kUIBuffer);
snprintf(kUIBuffer, sizeof(kUIBuffer), " bounds: %.2f, %.2f", physics->bounds.x, physics->bounds.y);
imui::Text(kUIBuffer);
snprintf(kUIBuffer, sizeof(kUIBuffer), " grid: %u", physics->grid_id);
imui::Text(kUIBuffer);
} break;
case ecs::kResourceComponent: {
ecs::ResourceComponent* resource = ecs::GetResourceComponent(entity);
snprintf(kUIBuffer, sizeof(kUIBuffer), " resource: %s", ecs::ResourceName(resource->resource_type));
imui::Text(kUIBuffer);
} break;
case ecs::kHarvestComponent: {
} break;
case ecs::kCharacterComponent: {
} break;
case ecs::kDeathComponent: {
} break;
case ecs::kBuildComponent: {
} break;
case ecs::kStructureComponent: {
} break;
case ecs::kOrderComponent: {
} break;
case ecs::kPickupComponent: {
} break;
case ecs::kZoneComponent: {
ecs::ZoneComponent* zone = ecs::GetZoneComponent(entity);
snprintf(kUIBuffer, sizeof(kUIBuffer), " resource_mask: %u", zone->resource_mask);
imui::Text(kUIBuffer);
snprintf(kUIBuffer, sizeof(kUIBuffer), " zone_start: %i, %i", zone->zone_start.x, zone->zone_start.y);
imui::Text(kUIBuffer);
snprintf(kUIBuffer, sizeof(kUIBuffer), " zone_end: %i, %i", zone->zone_end.x, zone->zone_end.y);
imui::Text(kUIBuffer);
int i = 0;
for (const ecs::ZoneCell& zone_cell : zone->zone_cells) {
snprintf(kUIBuffer, sizeof(kUIBuffer), " cell(%i): %i, %i", i++, zone_cell.grid_pos.x, zone_cell.grid_pos.y);
imui::Text(kUIBuffer);
snprintf(kUIBuffer, sizeof(kUIBuffer), " reserved: %i", zone_cell.reserved);
imui::Text(kUIBuffer);
}
} break;
case ecs::kCarryComponent: {
} break;
}
}
}
}
}
}
void
DebugUIRenderDebug()
{
static r32 right_align = 160.f;
imui::SameLine();
imui::Width(right_align);
imui::Text("Render AABB");
imui::Checkbox(16.f, 16.f, &kRenderCharacterAabb);
imui::NewLine();
imui::SameLine();
imui::Width(right_align);
imui::Text("Render Grid");
imui::Checkbox(16.f, 16.f, &kRenderGrid);
imui::NewLine();
imui::SameLine();
imui::Width(right_align);
imui::Text("Render Grid Fill");
imui::Checkbox(16.f, 16.f, &kRenderGridFill);
imui::NewLine();
imui::SameLine();
imui::Width(right_align);
imui::Text("Debug IMUI");
imui::Checkbox(16.f, 16.f, &kDebugImui);
imui::NewLine();
}
void
DebugUI()
{
v2f screen = window::GetWindowSize();
{
static b8 enable_debug = false;
static v2f diagnostics_pos(3.f, screen.y);
static DebugUIState debug_ui_state = kDiagnosticsViewer;
static r32 right_align = 125.f;
static v4f unused_color = v4f(.8f, .8f, .8f, 1.f);
imui::PaneOptions options;
options.max_width = 315.f;
imui::Begin("Debug", imui::kEveryoneTag, options, &diagnostics_pos,
&enable_debug);
imui::TextOptions debug_options;
debug_options.highlight_color = imui::kRed;
imui::SameLine();
imui::Width(right_align);
debug_options.color = debug_ui_state == kDiagnosticsViewer ? imui::kRed : unused_color;
if (imui::Text("Diag", debug_options).clicked) {
debug_ui_state = kDiagnosticsViewer;
}
imui::Width(right_align);
debug_options.color = debug_ui_state == kEntityViewer ? imui::kRed : unused_color;
if (imui::Text("Entity", debug_options).clicked) {
debug_ui_state = kEntityViewer;
}
debug_options.color = debug_ui_state == kDebugViewer ? imui::kRed : unused_color;
if (imui::Text("Debug", debug_options).clicked) {
debug_ui_state = kDebugViewer;
}
imui::NewLine();
imui::HorizontalLine(v4f(1.f, 1.f, 1.f, .4f));
imui::Space(imui::kVertical, 5);
switch (debug_ui_state) {
case kDiagnosticsViewer:
DebugUIRenderDiagnostics();
break;
case kEntityViewer:
DebugUIRenderEntity();
break;
case kDebugViewer:
DebugUIRenderDebug();
break;
}
imui::End();
}
}
void
GameInitialize(const v2f& dims)
{
/*rgg::GetObserver()->projection =
math::Ortho(dims.x, 0.f, dims.y, 0.f, -1.f, 1.f);
rgg::Camera camera;
camera.position = v3f(950.f, 600.f, 0.f);
camera.dir = v3f(0.f, 0.f, -1.f);
camera.up = v3f(0.f, 1.f, 0.f);
camera.viewport = dims;
camera.mode = rgg::kCameraOverhead;
rgg::CameraInit(camera);*/
rgg::GetObserver()->projection = math::Perspective(67.f, dims.x / dims.y, .1f, 1000.f);
rgg::Camera camera;
camera.position = v3f(50.f, 50.f, 400.f);
camera.dir = v3f(0.f, 0.f, -1.f);
camera.up = v3f(0.f, 1.f, 0.f);
camera.mode = rgg::kCameraBrowser;
camera.viewport = dims;
camera.speed = v3f(1.f, 1.f, .1f);
rgg::CameraInit(camera);
// I don't think we need depth testing for a 2d game?
//glDisable(GL_DEPTH_TEST);
//glEnable(GL_BLEND);
//glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
live::AssetLoadAll();
live::SimInitialize();
}
bool
GameUpdate()
{
rgg::CameraUpdate();
rgg::GetObserver()->view = rgg::CameraView();
//Print4x4Matrix(rgg::GetObserver()->view);
live::SimUpdate();
return true;
}
void
GameRender(v2f dims)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glClearColor(.1f, .1f, .13f, 1.f);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_ALWAYS);
//glDisable(GL_BLEND);
//glEnable(GL_BLEND);
//glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
DebugUI();
//live::InteractionRenderEntityViewer();
live::InteractionRenderOrderOptions();
live::InteractionRenderResourceCounts();
live::Grid* grid = live::GridGet(1);
if (kRenderGridFill) {
for (live::Cell& cell : grid->storage) {
if (!cell.entity_ids.empty()) {
rgg::RenderRectangle(cell.rect(), v4f(.2f, .2f, .2f, .8f));
}
}
}
rgg::Texture* terrain_texture = rgg::GetTexture(live::kAssets.terrain_texture_id);
rgg::Texture* character_texture = rgg::GetTexture(live::kAssets.character_texture_id);
Rectf sbounds = live::ScreenBounds();
{
assert(terrain_texture);
for (const live::Cell& cell : grid->storage) {
if (!math::IsContainedInRect(cell.rect(), sbounds) && !math::IntersectRect(cell.rect(), sbounds))
continue;
if (cell.pos == v2i(0, 0)) {
live::AssetTerrainRender(terrain_texture, live::GridPosFromXY(cell.pos), live::TerrainAsset::kDirtBottomLeft);
} else if (cell.pos.y == 0) {
live::AssetTerrainRender(terrain_texture, live::GridPosFromXY(cell.pos), live::TerrainAsset::kDirtBottomMiddle);
} else if (cell.pos.x == 0) {
live::AssetTerrainRender(terrain_texture, live::GridPosFromXY(cell.pos), live::TerrainAsset::kDirtMiddleLeft);
} else {
live::AssetTerrainRender(terrain_texture, live::GridPosFromXY(cell.pos), live::TerrainAsset::kDirtMiddleMiddle);
}
}
}
{
ECS_ITR2(itr, kPhysicsComponent, kZoneComponent);
while (itr.Next()) {
PhysicsComponent* physics = itr.c.physics;
rgg::RenderRectangle(physics->rect(), v4f(0.1f, 0.1f, 0.4f, 0.8f));
}
}
{
ECS_ITR3(itr, kPhysicsComponent, kHarvestComponent, kResourceComponent);
while (itr.Next()) {
PhysicsComponent* physics = itr.c.physics;
ResourceComponent* resource = itr.c.resource;
if (!math::IsContainedInRect(physics->rect(), sbounds) && !math::IntersectRect(physics->rect(), sbounds))
continue;
switch (resource->resource_type) {
case kLumber:
//rgg::RenderRectangle(physics->rect(), v4f(0.f, 1.f, 0.f, 1.f));
live::AssetTerrainRender(terrain_texture, physics->pos, live::TerrainAsset::kTree);
break;
case kStone:
rgg::RenderRectangle(physics->rect(), v4f(.5f, .5f, .5f, 1.f));
break;
case kResourceTypeCount:
default:
assert(!"Can't render resource type");
}
}
}
glDisable(GL_BLEND);
{
ECS_ITR2(itr, kPhysicsComponent, kBuildComponent);
while (itr.Next()) {
PhysicsComponent* physics = itr.c.physics;
BuildComponent* build = itr.c.build;
switch (build->structure_type) {
case kWall:
rgg::RenderLineRectangle(physics->rect(), v4f(1.f, 1.f, 1.f, 1.f));
break;
case kStructureTypeCount:
default:
assert(!"Can't render build component");
}
}
}
{
ECS_ITR2(itr, kPhysicsComponent, kStructureComponent);
while (itr.Next()) {
PhysicsComponent* physics = itr.c.physics;
StructureComponent* structure = itr.c.structure;
switch (structure->structure_type) {
case kWall:
rgg::RenderRectangle(physics->rect(), v4f(.64f, .45f, .28f, 1.f));
break;
case kStructureTypeCount:
default:
assert(!"Can't render structure component");
}
}
}
{
ECS_ITR2(itr, kPhysicsComponent, kCharacterComponent);
while (itr.Next()) {
PhysicsComponent* character = itr.c.physics;
r32 half_width = character->rect().width / 2.f;
/*
std::vector<v2i> grids = live::GridGetIntersectingCellPos(character);
for (v2i grid : grids) {
v2f grid_pos = live::GridPosFromXY(grid);
rgg::RenderRectangle(Rectf(grid_pos, live::CellDims()), v4f(.2f, .6f, .2f, .8f));
}*/
//live::AssetCharacterRender(character_texture, character->pos, live::CharacterAsset::kVillager);
rgg::RenderCircle(character->pos + v2f(half_width, half_width),
character->rect().width / 2.f, v4f(1.f, 0.f, 0.f, 1.f));
if (kRenderCharacterAabb) {
rgg::RenderLineRectangle(character->rect(), v4f(1.f, 0.f, 0.f, 1.f));
}
//v2f grid_pos;
//if (live::GridClampPos(character->pos, &grid_pos)) {
// rgg::RenderRectangle(Rectf(grid_pos, live::CellDims()), v4f(.2f, .2f, .2f, .8f));
//}
}
}
{
ECS_ITR2(itr, kPhysicsComponent, kResourceComponent);
while (itr.Next()) {
// The resource should not be rendered if this is a tree for instance.
if (GetHarvestComponent(itr.e)) continue;
PhysicsComponent* physics = itr.c.physics;
ResourceComponent* resource = itr.c.resource;
Rectf rect = physics->rect();
switch (resource->resource_type) {
case kLumber:
rgg::RenderTriangle(rect.Center(), rect.width / 2.f, v4f(.1f, .5f, .1f, 1.f));
break;
case kStone:
rgg::RenderTriangle(rect.Center(), rect.width / 2.f, v4f(.5f, .5f, .5f, 1.f));
break;
case kResourceTypeCount:
default:
assert(!"Can't render resource type");
}
}
}
glEnable(GL_BLEND);
if (kRenderGrid) {
// TODO: Implement an active grid which is the current view I think.
live::Grid* grid = live::GridGet(1);
r32 grid_width = grid->width * live::kCellWidth;
r32 grid_height = grid->height * live::kCellHeight;
for (s32 x = 0; x < grid->width; ++x) {
v2f start(x * live::kCellWidth, 0);
v2f end(x * live::kCellWidth, grid_height);
rgg::RenderLine(start, end, v4f(1.f, 1.f, 1.f, .15f));
}
for (s32 y = 0; y < grid->height; ++y) {
v2f start(0, y * live::kCellHeight);
v2f end(grid_width, y * live::kCellHeight);
rgg::RenderLine(start, end, v4f(1.f, 1.f, 1.f, .15f));
}
}
live::InteractionRender();
rgg::DebugRenderWorldPrimitives();
rgg::DebugRenderUIPrimitives();
if (kDebugImui) {
static v2f debug_imui(500.f, 500.f);
static b8 show = true;
imui::DebugPane("Debug IMUI", imui::kEveryoneTag, &debug_imui, &show);
}
imui::Render(imui::kEveryoneTag);
window::SwapBuffers();
}
void
ProcessPlatformEvent(const PlatformEvent& event) {
rgg::CameraUpdateEvent(event);
switch(event.type) {
case KEY_DOWN: {
switch (event.key) {
case KEY_ESC: {
exit(1);
} break;
case KEY_ARROW_UP: {
rgg::CameraMove(v2f(0.f, live::kCameraSpeed));
} break;
case KEY_ARROW_RIGHT: {
rgg::CameraMove(v2f(live::kCameraSpeed, 0.f));
} break;
case KEY_ARROW_DOWN: {
rgg::CameraMove(v2f(0.f, -live::kCameraSpeed));
} break;
case KEY_ARROW_LEFT: {
rgg::CameraMove(v2f(-live::kCameraSpeed, 0.f));
} break;
}
} break;
case MOUSE_DOWN: {
if (event.button == BUTTON_LEFT) {
imui::MouseDown(event.position, event.button, imui::kEveryoneTag);
}
} break;
case MOUSE_UP: {
imui::MouseUp(event.position, event.button, imui::kEveryoneTag);
} break;
default: break;
}
live::InteractionProcessPlatformEvent(event);
}
s32
main(s32 argc, char** argv)
{
#ifdef _WIN32
#if WIN_ATTACH_DEBUGGER
while (!IsDebuggerPresent()) {};
#endif
#endif
if (!memory::Initialize(MiB(64))) {
return 1;
}
kGameState.window_create_info.window_width = live::kScreenWidth;
kGameState.window_create_info.window_height = live::kScreenHeight;
if (!window::Create("Game", kGameState.window_create_info)) {
return 1;
}
if (!rgg::Initialize()) {
return 1;
}
const v2f dims = window::GetWindowSize();
GameInitialize(dims);
// main thread affinity set to core 0
if (platform::thread_affinity_count() > 1) {
platform::thread_affinity_usecore(0);
printf("Game thread may run on %d cores\n",
platform::thread_affinity_count());
}
// Reset State
StatsInit(&kGameStats);
kGameState.game_updates = 0;
SetFramerate(kGameState.framerate);
printf("Client target usec %lu\n", kGameState.frame_target_usec);
// If vsync is enabled, force the clock_init to align with clock_sync
// TODO: We should also enforce framerate is equal to refresh rate
window::SwapBuffers();
while (1) {
platform::ClockStart(&kGameState.game_clock);
imui::ResetTag(imui::kEveryoneTag);
rgg::DebugReset();
if (window::ShouldClose()) break;
const v2f cursor = window::GetCursorPosition();
imui::MousePosition(cursor, imui::kEveryoneTag);
PlatformEvent event;
while (window::PollEvent(&event)) {
ProcessPlatformEvent(event);
}
GameUpdate();
GameRender(dims);
const u64 elapsed_usec = platform::ClockEnd(&kGameState.game_clock);
StatsAdd(elapsed_usec, &kGameStats);
if (kGameState.frame_target_usec > elapsed_usec) {
u64 wait_usec = kGameState.frame_target_usec - elapsed_usec;
platform::Clock wait_clock;
platform::ClockStart(&wait_clock);
while (platform::ClockEnd(&wait_clock) < wait_usec) {}
}
kGameState.game_time_usec += platform::ClockEnd(&kGameState.game_clock);
kGameState.game_updates++;
}
return 0;
}
| 30.212428 | 128 | 0.630028 | [
"render",
"vector"
] |
7a32a83674649b956674bb82384129d8c8b8ea53 | 8,660 | hpp | C++ | include/lemon/select.hpp | frodofine/lemon | f874857cb8f1851313257b25681ad2a254ada8dc | [
"BSD-3-Clause"
] | 43 | 2018-07-21T22:08:48.000Z | 2022-03-23T22:19:02.000Z | include/lemon/select.hpp | frodofine/lemon | f874857cb8f1851313257b25681ad2a254ada8dc | [
"BSD-3-Clause"
] | 22 | 2018-08-01T19:13:11.000Z | 2020-06-02T17:04:03.000Z | include/lemon/select.hpp | frodofine/lemon | f874857cb8f1851313257b25681ad2a254ada8dc | [
"BSD-3-Clause"
] | 9 | 2018-07-21T19:13:55.000Z | 2020-12-22T09:12:43.000Z | #ifndef LEMON_SELECT_HPP
#define LEMON_SELECT_HPP
#include <vector>
#include <unordered_set>
#include <string>
#include <cstdint>
#include "lemon/external/gaurd.hpp"
LEMON_EXTERNAL_FILE_PUSH
#include <chemfiles/Frame.hpp>
LEMON_EXTERNAL_FILE_POP
#include "lemon/constants.hpp"
#include "lemon/residue_name.hpp"
namespace lemon {
//! Functions to select various residue based on a given criterion
namespace select {
//! Select small molecules in a given frame
//!
//! Use this function to find small molecules in a given `frame`. A small
//! molecule is defined as an entity that has a given [chemical composition]
//! (http://mmcif.wwpdb.org/dictionaries/mmcif_pdbx_v50.dic/Items/_chem_comp.type.html).
//! Also, the selected entity must have a specified number of atoms (default
//! 10), so that common residues such as water and metal ions are not selected.
//! \param [in] frame The entry containing molecules of interest.
//! \param [in] types A set of `std::string` containing the accepted chemical
//! chemical composition. Defaults are *NON-POLYMER*, *OTHER*, *PEPTIDE-LIKE*
//! \param [in] min_heavy_atoms The minimum number of non-hydrogen atoms for a
//! residue to be classed as a small molecule.
//! \return The selected residue locations
template <typename Container = std::vector<uint64_t>>
inline Container small_molecules(
const chemfiles::Frame& frame,
const std::unordered_set<std::string>& types = small_molecule_types,
size_t min_heavy_atoms = 10) {
using chemfiles::Property;
Container selection;
const auto& residues = frame.topology().residues();
for (size_t selected_residue = 0; selected_residue < residues.size();
++selected_residue) {
const auto& residue = residues[selected_residue];
// Quick check, filters out many ions and small molecules before more
// expensive checks.
// For example, water
if (residue.size() < min_heavy_atoms) {
continue;
}
auto composition_type =
residue.get<Property::STRING>("composition_type").value_or("");
if (!types.count(composition_type)) {
continue;
}
auto num_heavy_atoms = std::count_if(
std::begin(residue), std::end(residue), [&frame](size_t index) {
return *(frame[index].atomic_number()) != 1;
});
if (static_cast<size_t>(num_heavy_atoms) < min_heavy_atoms) {
continue;
}
selection.insert(selection.end(), selected_residue);
}
return selection;
}
//! Select metal ions in a given frame
//!
//! This function populates the residue IDs of metal ions. We define a metal ion
//! as a residue with a single, positively charged ion.
//! \param [in] frame The entry containing metal ions of interest.
//! \return The selected residue locations
template <typename Container = std::vector<uint64_t>>
inline Container metal_ions(const chemfiles::Frame& frame) {
const auto& residues = frame.topology().residues();
Container selection;
for (size_t selected_residue = 0; selected_residue < residues.size();
++selected_residue) {
const auto& residue = residues[selected_residue];
if (residue.size() == 1 && frame[*residue.begin()].charge() > 0.0) {
selection.insert(selection.end(), selected_residue);
}
}
return selection;
}
//! Select nucleic acid residues in a given frame
//!
//! This function populates the residue IDs of nucleic acid residues.
//! We define a nucleic acid as a residue with a chemical composition
//! containing the *RNA* or *DNA* substring.
//! \param [in] frame The entry containing nucleic acid residues.
//! \return The selected residue locations
template <typename Container = std::vector<uint64_t>>
inline Container nucleic_acids(const chemfiles::Frame& frame) {
using chemfiles::Property;
const auto& residues = frame.topology().residues();
Container selection;
for (size_t selected_residue = 0; selected_residue < residues.size();
++selected_residue) {
const chemfiles::Residue& residue = residues[selected_residue];
auto comp_type =
residue.get<Property::STRING>("composition_type").value_or("");
if (comp_type.find("DNA") == std::string::npos &&
comp_type.find("RNA") == std::string::npos) {
continue;
}
selection.insert(selection.end(), selected_residue);
}
return selection;
}
//! Select peptide residues in a given frame
//!
//! This function populates the residue IDs of peptide residues.
//! We define a peptided as a residue with a chemical composition
//! containing the *PEPTIDE* substring which is not *PEPTIDE-LIKE*.
//! \param [in] frame The entry containing peptide residues.
//! \return The selected residue locations
template <typename Container = std::vector<uint64_t>>
inline Container peptides(const chemfiles::Frame& frame) {
using chemfiles::Property;
const auto& residues = frame.topology().residues();
Container selection;
for (size_t selected_residue = 0; selected_residue < residues.size();
++selected_residue) {
const chemfiles::Residue& residue = residues[selected_residue];
auto comp_type =
residue.get<Property::STRING>("composition_type").value_or("");
if (comp_type.find("PEPTIDE") == std::string::npos ||
comp_type == "PEPTIDE-LIKE") {
continue;
}
selection.insert(selection.end(), selected_residue);
}
return selection;
}
//! Select residues with a given name in a given frame
//!
//! This function populates the residue IDs of peptides matching a given name
//! set.
//! \param [in] frame The entry containing residues of interest.
//! \param [in] resnis The set of residue IDs of interest.
//! \return The selected residue locations
template <typename Container = std::vector<uint64_t>>
inline Container residue_ids(const chemfiles::Frame& frame,
const std::set<uint64_t>& resis) {
const auto& residues = frame.topology().residues();
Container selection;
for (size_t selected_residue = 0; selected_residue < residues.size();
++selected_residue) {
const auto& residue_id = residues[selected_residue].id();
if (!residue_id) {
continue;
}
if (resis.count({*residue_id}) == 0) {
continue;
}
selection.insert(selection.end(), selected_residue);
}
return selection;
}
//! Select residues with a given name in a given frame
//!
//! This function returns a set of residue locations within a given name set
//! \param [in] frame The entry containing residues of interest.
//! \param [in] resnames The set of residue names of interest.
//! \return The selected residue locations
template <typename Container = std::vector<uint64_t>>
inline Container specific_residues(const chemfiles::Frame& frame,
const ResidueNameSet& resnames) {
const auto& residues = frame.topology().residues();
Container selection;
for (size_t selected_residue = 0; selected_residue < residues.size();
++selected_residue) {
const auto& residue = residues[selected_residue];
if (resnames.count({residue.name()}) == 0) {
continue;
}
selection.insert(selection.end(), selected_residue);
}
return selection;
}
//! Select residues with a property
//!
//! This function returns the residue locations of residues with a property
//! \param [in] frame The entry containing residues of interest.
//! \param [in] property_name The name of the property to select
//! \param [in] property the property of interest
//! \return The selected residue locations
template <typename Container = std::vector<uint64_t>>
inline Container residue_property(const chemfiles::Frame& frame,
const std::string& property_name,
const chemfiles::Property& property) {
const auto& residues = frame.topology().residues();
Container selection;
for (size_t selected_residue = 0; selected_residue < residues.size();
++selected_residue) {
const auto& residue = residues[selected_residue];
const auto res_prop = residue.get(property_name);
if (!res_prop) {
continue;
}
if (*res_prop == property) {
selection.insert(selection.end(), selected_residue);
}
}
return selection;
}
} // namespace select
} // namespace lemon
#endif
| 32.80303 | 88 | 0.667552 | [
"vector"
] |
7a338fe051ce27081ce702c0dcd2fe52a8b9ac58 | 40,198 | cxx | C++ | src/PatRec/TreeBased/TreeBasedTool.cxx | fermi-lat/TkrRecon | 9174a0ab1310038d3956ab4dcc26e06b8a845daf | [
"BSD-3-Clause"
] | null | null | null | src/PatRec/TreeBased/TreeBasedTool.cxx | fermi-lat/TkrRecon | 9174a0ab1310038d3956ab4dcc26e06b8a845daf | [
"BSD-3-Clause"
] | null | null | null | src/PatRec/TreeBased/TreeBasedTool.cxx | fermi-lat/TkrRecon | 9174a0ab1310038d3956ab4dcc26e06b8a845daf | [
"BSD-3-Clause"
] | null | null | null | /**
* @class TreeBasedTool
*
* @brief Implements a Gaudi Tool for find track candidates. This method uses a four step method:
* 1) X-Y Clusters are combined to form sets of 3-D "TkrPoints"
* 2) Vectors are formed between pairs of "TkrPoints"
* 3) "Tracks" are formed by linking Vectors which share the same end points
* 4) Track candidates are extracted from the combinations above
*
* *** PARENTAL ADVISORY ***
* This tool uses both recursion and function pointers
* It should not be read without the proper supervision!
*
* @author The Tracking Software Group
*
* File and Version Information:
* $Header: /nfs/slac/g/glast/ground/cvs/GlastRelease-scons/TkrRecon/src/PatRec/TreeBased/TreeBasedTool.cxx,v 1.57 2013/06/12 16:15:38 usher Exp $
*/
#include "GaudiKernel/ToolFactory.h"
#include "GaudiKernel/SmartDataPtr.h"
#include "GaudiKernel/GaudiException.h"
#include "GaudiKernel/IChronoStatSvc.h"
#include "src/PatRec/PatRecBaseTool.h"
#include "Event/TopLevel/EventModel.h"
#include "Event/Recon/TkrRecon/TkrTree.h"
#include "Event/Recon/TkrRecon/TkrTrack.h"
#include "Event/Recon/TkrRecon/TkrEventParams.h"
#include "Event/Recon/CalRecon/CalEventEnergy.h"
#include "Event/Recon/CalRecon/CalClusterMap.h"
#include "GlastSvc/GlastDetSvc/IGlastDetSvc.h"
#include "TkrRecon/Track/ITkrFitTool.h"
#include "TkrRecon/Track/IFindTrackHitsTool.h"
#include "src/Track/TkrControl.h"
#include "../VectorLinks/ITkrVecPointsBuilder.h"
#include "../VectorLinks/ITkrVecPointLinksBuilder.h"
#include "TkrVecNodesBuilder.h"
#include "TkrTreeBuilder.h"
#include "ITkrTreeTrackFinder.h"
#include "TreeCalClusterAssociator.h"
//Exception handler
#include "Utilities/TkrException.h"
#include <errno.h>
#include <math.h>
//typedef std::vector<Event::TkrVecPoint*> VecPointVec;
//typedef Event::TkrVecPointsLinkPtrVec VecPointsLinkVec;
class TreeBasedTool : public PatRecBaseTool
{
public:
/// Standard Gaudi Tool interface constructor
TreeBasedTool(const std::string& type, const std::string& name, const IInterface* parent);
virtual ~TreeBasedTool();
/// @brief Intialization of the tool
StatusCode initialize();
/// @brief start of event processing
StatusCode start();
/// @brief First Pass method to build trees
StatusCode firstPass();
/// @brief Secon Pass method to extract tracks
StatusCode secondPass();
/// @brief Finalize method for outputting run statistics
StatusCode finalize();
private:
///*** PRIVATE METHODS ***
/// Get the event energy
double getEventEnergy();
Event::TreeClusterRelationVec buildTreeRelVec(Event::ClusterToRelationMap* clusToRelationMap,
Event::TreeToRelationMap* treeToRelationMap,
Event::TkrTreeCol* treeCol,
Event::CalClusterVec* calClusters);
/// Assign track energy and run first fit
void setTrackEnergy(double eventEnergy, Event::TkrTrackCol* tdsTracks);
/// for clearing the clusters we own
void clearClusterCol();
///*** PRIVATE DATA MEMBERS ***
/// The track fit code
ITkrFitTool* m_trackFitTool;
/// Used for finding leading hits on tracks
IFindTrackHitsTool* m_findHitsTool;
/// Services for hit arbitration
IGlastDetSvc* m_glastDetSvc;
/// Points builder tool
ITkrVecPointsBuilder* m_pointsBuilder;
/// Link builder tool
ITkrVecPointsLinkBuilder* m_linkBuilder;
/// For extracting tracks from trees
ITkrTreeTrackFinder* m_tkrTrackFinder;
/// For keeping track of Tree/Cluster associations
TreeCalClusterAssociator* m_treeClusterAssociator;
/// Minimum energy
double m_minEnergy;
double m_fracEneFirstTrack;
/// Set a scale factor for the "refError" if getting from the tracker filter
/// between the reference point and the projection of the candidate link
double m_minRefError;
double m_minAngError;
/// Control for merging clusters
bool m_mergeClusters;
int m_nClusToMerge;
int m_stripGap;
/// Maximum number of trees to return
int m_maxTrees;
/// Let's keep track of event timing
IChronoStatSvc* m_chronoSvc;
bool m_doTiming;
std::string m_toolTag;
IChronoStatSvc::ChronoTime m_toolTime;
std::string m_toolLinkTag;
IChronoStatSvc::ChronoTime m_linkTime;
std::string m_toolNodeTag;
IChronoStatSvc::ChronoTime m_nodeTime;
std::string m_toolBuildTag;
IChronoStatSvc::ChronoTime m_buildTime;
/// This places a hard cut on the number of vector points in a given event
size_t m_maxNumVecPoints;
/// In case we want to turn off track-cluster association
bool m_associateClusters;
bool m_reorderTrees;
/// In the event we create fake TkrClusters, keep track of them here
Event::TkrClusterCol* m_clusterCol;
};
//static ToolFactory<TreeBasedTool> s_factory;
//const IToolFactory& TreeBasedToolFactory = s_factory;
DECLARE_TOOL_FACTORY(TreeBasedTool);
//
// Class constructor, no initialization here
//
TreeBasedTool::TreeBasedTool(const std::string& type, const std::string& name, const IInterface* parent) :
PatRecBaseTool(type, name, parent)
{
declareProperty("MinEnergy", m_minEnergy = 30.);
declareProperty("FracEneFirstTrack", m_fracEneFirstTrack = 0.80);
declareProperty("MinimumRefError", m_minRefError = 50.);
declareProperty("MinimumAngError", m_minAngError = M_PI/16.);
declareProperty("MergeClusters", m_mergeClusters = false);
declareProperty("NumClustersToMerge", m_nClusToMerge = 3);
declareProperty("MergeStripGap", m_stripGap = 8);
declareProperty("MaxNumTrees", m_maxTrees = 10);
declareProperty("DoToolTiming", m_doTiming = true);
declareProperty("MaxNumVecPoints", m_maxNumVecPoints = 10000);
declareProperty("AssociateClusters", m_associateClusters = true);
declareProperty("ReorderTrees", m_reorderTrees = true);
m_clusterCol = 0;
m_treeClusterAssociator = 0;
m_toolTag = this->name();
if (m_toolTag.find(".") < m_toolTag.size())
{
m_toolTag = m_toolTag.substr(m_toolTag.find(".")+1,m_toolTag.size());
}
m_toolLinkTag = m_toolTag + "_link";
m_toolNodeTag = m_toolTag + "_node";
m_toolBuildTag = m_toolTag + "_build";
return;
}
TreeBasedTool::~TreeBasedTool()
{
if (m_clusterCol) delete m_clusterCol;
return;
}
//
// Initialization of the tool here
//
StatusCode TreeBasedTool::initialize()
{
PatRecBaseTool::initialize();
StatusCode sc = StatusCode::SUCCESS;
if( (sc = toolSvc()->retrieveTool("KalmanTrackFitTool", "KalmanTrackFitTool", m_trackFitTool)).isFailure() )
{
throw GaudiException("ToolSvc could not find KalmanTrackFitTool", name(), sc);
}
if( (sc = toolSvc()->retrieveTool("FindTrackHitsTool", "FindTrackHitsTool", m_findHitsTool)).isFailure() )
{
throw GaudiException("ToolSvc could not find FindTrackHitsTool", name(), sc);
}
if( (sc = toolSvc()->retrieveTool("TkrVecPointsBuilderTool", "TkrVecPointsBuilderTool", m_pointsBuilder)).isFailure() )
{
throw GaudiException("ToolSvc could not find TkrVecPointsBuilderTool", name(), sc);
}
if( (sc = toolSvc()->retrieveTool("TkrVecLinkBuilderTool", "TkrVecLinkBuilderTool", m_linkBuilder)).isFailure() )
{
throw GaudiException("ToolSvc could not find TkrVecLinkBuilderTool", name(), sc);
}
if( (sc = toolSvc()->retrieveTool("TkrTreeTrackFinderTool", "TkrTreeTrackFinderTool", m_tkrTrackFinder)).isFailure() )
{
throw GaudiException("ToolSvc could not find TkrTreeTrackFinderTool", name(), sc);
}
// Get the Glast Det Service
if( serviceLocator() )
{
IService* iService = 0;
if ((sc = serviceLocator()->getService("GlastDetSvc", iService, true)).isFailure())
{
throw GaudiException("Service [GlastDetSvc] not found", name(), sc);
}
m_glastDetSvc = dynamic_cast<IGlastDetSvc*>(iService);
if ((sc = serviceLocator()->getService("ChronoStatSvc", iService, true)).isFailure())
{
throw GaudiException("Service [ChronoSvc] not found", name(), sc);
}
m_chronoSvc = dynamic_cast<IChronoStatSvc*>(iService);
}
// Create and clear a Cluster collection
m_clusterCol = new Event::TkrClusterCol();
m_clusterCol->clear();
return sc;
}
StatusCode TreeBasedTool::start()
{
if (m_doTiming)
{
m_toolTime = 0;
m_linkTime = 0;
m_nodeTime = 0;
m_buildTime = 0;
m_chronoSvc->chronoStart(m_toolTag);
m_chronoSvc->chronoStop(m_toolTag);
m_chronoSvc->chronoStart(m_toolLinkTag);
m_chronoSvc->chronoStop(m_toolLinkTag);
m_chronoSvc->chronoStart(m_toolNodeTag);
m_chronoSvc->chronoStop(m_toolNodeTag);
m_chronoSvc->chronoStart(m_toolBuildTag);
m_chronoSvc->chronoStop(m_toolBuildTag);
}
return StatusCode::SUCCESS;
}
//
// Method called externally to drives the finding of the
// pattern candidate tracks
//
StatusCode TreeBasedTool::firstPass()
{
// Always believe in success
StatusCode sc = StatusCode::SUCCESS;
// Zap any TkrClusters we may have created on a previous pass
if (!m_clusterCol->empty()) clearClusterCol();
// Zap the Tree Cluster associator if created on a previous pass
if (m_treeClusterAssociator)
{
delete m_treeClusterAssociator;
m_treeClusterAssociator = 0;
}
SmartDataPtr<Event::TkrTrackMap> tdsTrackMap(m_dataSvc, EventModel::TkrRecon::TkrTrackMap);
// We are not meant to be able to get here without a track collection in the TDS
Event::TkrTrackCol* tdsTracks = (*tdsTrackMap)[EventModel::TkrRecon::TkrTrackCol];
// Set the event energy
double eventEnergy = getEventEnergy();
// STEP ONE: Check to be sure the TkrVecPoints exist
Event::TkrVecPointCol* tkrVecPointCol =
SmartDataPtr<Event::TkrVecPointCol>(m_dataSvc, EventModel::TkrRecon::TkrVecPointCol);
// If requested, start the tool timing
if (m_doTiming)
{
m_toolTime = 0;
m_linkTime = 0;
m_nodeTime = 0;
m_buildTime = 0;
m_chronoSvc->chronoStart(m_toolTag);
}
// If they dont exist then we make them here
if (!tkrVecPointCol)
{
// Put this here for now
int numLyrsToSkip = 3;
// Re-recover the vector point collection
tkrVecPointCol = m_pointsBuilder->buildTkrVecPoints(numLyrsToSkip);
if (!tkrVecPointCol) return StatusCode::FAILURE;
}
// Place a temporary cut here to prevent out of control events
if (!tkrVecPointCol || tkrVecPointCol->size() > m_maxNumVecPoints) return sc;
try
{
// Checking timing of link building
if (m_doTiming) m_chronoSvc->chronoStart(m_toolLinkTag);
// STEP TWO: Associate (link) adjacent pairs of VecPoints and store away
// We need to give the link building code a reference point/axis and energy
// By default we'll use the values in TkrEventParams so we'll initialize those first
Event::TkrEventParams* tkrEventParams =
SmartDataPtr<Event::TkrEventParams>(m_dataSvc,EventModel::TkrRecon::TkrEventParams);
Point refPoint = tkrEventParams->getEventPosition();
Vector refAxis = tkrEventParams->getEventAxis();
double energy = tkrEventParams->getEventEnergy();
double refError = std::max(tkrEventParams->getTransRms(), m_minRefError);
double angError = m_minAngError;
// This axis comes from cal so make sure it is pointing into the tracker!
if (tkrEventParams->getEventEnergy() > 20.)
{
refPoint = tkrEventParams->getEventPosition();
double arcLen = (m_tkrGeom->gettkrZBot() - refPoint.z()) / refAxis.z();
Point tkrBotPos = refPoint + arcLen * refAxis;
// Are we outside the fiducial area already?
if (std::fabs(tkrBotPos.x()) > 0.5 * m_tkrGeom->calXWidth() || tkrBotPos.y() > 0.5 * m_tkrGeom->calYWidth())
{
static Point top(0., 0., 1000.);
Vector newAxis = top - refPoint;
refAxis = newAxis.unit();
}
}
// If the energy is zero then there is no axis so set to point "up"
else refAxis = Vector(0.,0.,1.);
// However, if we have reconstructed a nice axis from the Hough Filter we will use that instead
// Look up in TDS to see if such axis exists
Event::TkrFilterParamsCol* tkrFilterParamsCol =
SmartDataPtr<Event::TkrFilterParamsCol>(m_dataSvc,EventModel::TkrRecon::TkrFilterParamsCol);
// If there is a collection and there is an entry at the head of the list, use this for the event axis
if (tkrFilterParamsCol && !tkrFilterParamsCol->empty() && tkrFilterParamsCol->front()->getChiSquare() > 0.)
{
Event::TkrFilterParams* filterParams = tkrFilterParamsCol->front();
// First lets check the angle between the above reference axis and the filter
double cosAxesAng = filterParams->getEventAxis().dot(refAxis);
refPoint = filterParams->getEventPosition();
refAxis = filterParams->getEventAxis();
energy = filterParams->getEventEnergy();
refError = std::max(3. * filterParams->getTransRms(), m_minRefError);
angError = std::max(acos(std::max(-1., std::min(1., cosAxesAng))), m_minAngError);
}
// Having said the above regarding refError, it is observed that once the number of vector
// points gets above 2000 that the number of links can "explode". Add in a bit of a safety factor
// here to improve performance for these high occupancy events
if (tkrVecPointCol->size() > 2000.)
{
double sclFctrInc = 0.001 * double(tkrVecPointCol->size()) - 2.;
refError *= 1. / (1. + sclFctrInc);
}
Event::TkrVecPointsLinkInfo* tkrVecPointsLinkInfo = m_linkBuilder->getAllLayerLinks(refPoint, refAxis, refError, angError, energy);
int numVecPointsLinks = tkrVecPointsLinkInfo->getTkrVecPointsLinkCol()->size();
if (m_doTiming) m_chronoSvc->chronoStop(m_toolLinkTag);
if (numVecPointsLinks > 1)
{
// STEP THREE: build the node trees
try
{
if (m_doTiming) m_chronoSvc->chronoStart(m_toolNodeTag);
TkrVecNodesBuilder tkrNodesBldr(m_dataSvc, m_tkrGeom, energy);
tkrNodesBldr.buildTrackElements();
if (m_doTiming)
{
m_chronoSvc->chronoStop(m_toolNodeTag);
m_chronoSvc->chronoStart(m_toolBuildTag);
}
// STEP FOUR: build the naked trees including getting their axis parameters
try
{
TkrTreeBuilder tkrTreeBldr(tkrNodesBldr, m_dataSvc, m_tkrGeom);
if (Event::TkrTreeCol* treeCol = tkrTreeBldr.buildTrees())
{
// STEP FIVE: If requested, associated Trees to Clusters using Tree Axis
if (m_associateClusters)
{
// Recover the cal cluster collection from the TDS
SmartDataPtr<Event::CalClusterMap> calClusterMap(m_dataSvc, EventModel::CalRecon::CalClusterMap);
// Now set up the track - cluster associator
m_treeClusterAssociator = new TreeCalClusterAssociator(calClusterMap, m_dataSvc, m_tkrGeom);
// Make a pass through the trees to do the association
// This pass should result in an association map between trees and relation objects which is in the
// same order as the collection in the TDS
try
{
for(Event::TkrTreeCol::iterator treeItr = treeCol->begin(); treeItr != treeCol->end(); treeItr++)
{
Event::TkrTree* tree = *treeItr;
m_treeClusterAssociator->associateTreeToClusters(tree);
}
}
catch(TkrException& e)
{
throw e;
}
catch(...)
{
throw(TkrException("Unknown exception encountered in TkrVecNode and TkrTree building "));
}
// Ok, for right now our last step is going to be to go through and reorder the trees, which we do through the
// back door using this method...
if (m_reorderTrees)
{
// Recover the Cal Cluster Vec
Event::CalClusterVec calClusterVec;
if (calClusterMap) calClusterVec = calClusterMap->getRawClusterVec();
Event::TreeClusterRelationVec treeRelVec = buildTreeRelVec(m_treeClusterAssociator->getClusterToRelationMap(),
m_treeClusterAssociator->getTreeToRelationMap(),
treeCol,
&calClusterVec);
}
// The final step in the process of creating relations is to make relations of the best/first Tree
// to the uber and uber2 clusters. This is done in a special method of the associator
if (!treeCol->empty()) m_treeClusterAssociator->associateTreeToUbers(*treeCol->begin());
}
}
if (m_doTiming) m_chronoSvc->chronoStop(m_toolBuildTag);
}
catch(TkrException& e)
{
throw e;
}
catch(...)
{
throw(TkrException("Unknown exception encountered in TkrVecNode and TkrTree building "));
}
}
catch(TkrException& e)
{
throw e;
}
catch(...)
{
throw(TkrException("Unknown exception encountered in TkrVecNode and TkrTree building "));
}
// Finally, set the track energies and do a first fit
setTrackEnergy(eventEnergy, tdsTracks);
}
}
catch(TkrException& e)
{
if (m_doTiming)
{
m_chronoSvc->chronoStop(m_toolTag);
m_chronoSvc->chronoStop(m_toolLinkTag);
m_chronoSvc->chronoStop(m_toolNodeTag);
m_chronoSvc->chronoStop(m_toolBuildTag);
}
throw e;
}
catch(...)
{
if (m_doTiming)
{
m_chronoSvc->chronoStop(m_toolTag);
m_chronoSvc->chronoStop(m_toolLinkTag);
m_chronoSvc->chronoStop(m_toolNodeTag);
m_chronoSvc->chronoStop(m_toolBuildTag);
}
throw(TkrException("Unknown exception encountered in TkrVecLink building "));
}
// Make sure timer is shut down
if (m_doTiming)
{
m_chronoSvc->chronoStop(m_toolTag);
m_chronoSvc->chronoStop(m_toolLinkTag);
m_chronoSvc->chronoStop(m_toolNodeTag);
m_chronoSvc->chronoStop(m_toolBuildTag);
m_toolTime = m_chronoSvc->chronoDelta(m_toolTag,IChronoStatSvc::USER);
m_linkTime = m_chronoSvc->chronoDelta(m_toolLinkTag, IChronoStatSvc::USER);
m_nodeTime = m_chronoSvc->chronoDelta(m_toolNodeTag, IChronoStatSvc::USER);
m_buildTime = m_chronoSvc->chronoDelta(m_toolBuildTag, IChronoStatSvc::USER);
float toolDelta = static_cast<float>(m_toolTime)*0.000001;
float linkDelta = static_cast<float>(m_linkTime)*0.000001;
float nodeDelta = static_cast<float>(m_nodeTime)*0.000001;
float buildDelta = static_cast<float>(m_buildTime)*0.000001;
MsgStream log(msgSvc(), name());
log << MSG::DEBUG << " total tool time: " << toolDelta << " sec\n"
<< " link time: " << linkDelta << " sec\n"
<< " node time: " << nodeDelta << " sec\n"
<< " build time: " << buildDelta << " sec\n"
<< endreq ;
}
return sc;
}
//
// Method called externally to drives the finding of the
// pattern candidate tracks
//
StatusCode TreeBasedTool::secondPass()
{
// Always believe in success
StatusCode sc = StatusCode::SUCCESS;
// Recover the forest
Event::TkrTreeCol* treeCol = SmartDataPtr<Event::TkrTreeCol>(m_dataSvc,"/Event/TkrRecon/TkrTreeCol");
// No forest, no work
if (!treeCol || treeCol->empty()) return sc;
// Recover the tds track collection in the TDS
Event::TkrTrackMap* tdsTrackMap = SmartDataPtr<Event::TkrTrackMap>(m_dataSvc, EventModel::TkrRecon::TkrTrackMap);
// We are not meant to be able to get here without a track collection in the TDS
Event::TkrTrackCol* tdsTracks = (*tdsTrackMap)[EventModel::TkrRecon::TkrTrackCol];
// Recover the cal energy map from the TDS
Event::CalEventEnergyMap* calEnergyMap = SmartDataPtr<Event::CalEventEnergyMap>(m_dataSvc,EventModel::CalRecon::CalEventEnergyMap);
// Basic plan is to loop through the tree collection, sending each Tree to the track finder
// The energy that we assign each Tree, and whether there is an associated cluster, will depend
// on the existence of a Tree/Cluster relation
// We will also remove Trees which don't return tracks "on the fly"
int treeIdx = 0;
while(treeIdx < int(treeCol->size()))
{
Event::TkrTree* tree = (*treeCol)[treeIdx];
Event::CalCluster* cluster = 0;
double energy = treeIdx == 0 ? getEventEnergy() : m_minEnergy;
// If the tree to relation map exists then try to recover the relation between this Tree and a Cluster
if (m_treeClusterAssociator && m_treeClusterAssociator->getTreeToRelationMap() && m_treeClusterAssociator->getClusterToRelationMap())
{
Event::TreeClusterRelationVec* treeClusVec = m_treeClusterAssociator->getTreeToRelationVec(tree);
// The association was performed, but was there an actual association?
if (treeClusVec && !treeClusVec->empty())
{
cluster = treeClusVec->front()->getCluster();
// Ok, this probably "can't happen" but let's be paranoid just in case
if (cluster)
{
// We actually want the recon'd energy from this cluster, look it up here
Event::CalEventEnergyMap::iterator calEnergyItr = calEnergyMap->find(cluster);
// If the energy was recon'd then this will find it
if (calEnergyItr != calEnergyMap->end())
{
// The "best" energy will be returned by the CalEventEnergy's params method
energy = calEnergyItr->second.front()->getParams().getEnergy();
}
}
}
}
// Ok, all of that nonsense is out of the way, now find the tracks!
// To account for exceptions being thrown we need to make sure to catch them here
int numTracks = 0;
// Encase in a try-catch block
try
{
// Ok, all of that nonsense is out of the way, now find the tracks!
numTracks = m_tkrTrackFinder->findTracks(tree, energy, cluster);
}
// If an exception occurred in handling then make sure to catch here
catch(TkrException&)
{
// In this case we have a failure in track fitting, most likely, which we will deem to be non-fatal
// Set the number of tracks returned to the size of the Tree
numTracks = int(tree->size());
}
// Otherwise
catch(...)
{
// This is an unknown failure... we should zap the Tree Col from this Tree forward
while(treeIdx < int(treeCol->size()))
{
tree = (*treeCol)[treeIdx];
delete tree;
}
// And then pass the exception up to a higher authority
throw(TkrException("Exception encountered in the Second Pass of Tree Building "));
}
// If we found tracks then add them to the TDS collection
if (numTracks > 0)
{
// Loop over the tracks and give ownership to the TDS
for(Event::TkrTrackVec::iterator treeTrkItr = tree->begin(); treeTrkItr != tree->end(); treeTrkItr++)
{
tdsTracks->push_back(*treeTrkItr);
}
// Note that if we are successful then we want to move on to the next tree in the collection
treeIdx++;
}
// Otherwise, we zap the Tree and its relations
// And note that in this case we do NOT want to increment the tree index
else
{
// Make sure any relations are dealt with
if (m_treeClusterAssociator) m_treeClusterAssociator->removeTreeClusterRelations(tree);
// Now delete the tree (which should automatically remove it from the Tree Collection
delete tree;
}
}
return sc;
}
StatusCode TreeBasedTool::finalize()
{
StatusCode sc = StatusCode::SUCCESS;
if (m_doTiming) m_chronoSvc->chronoPrint(m_toolTag);
return sc;
}
void TreeBasedTool::clearClusterCol()
{
int numClusters = m_clusterCol->size();
m_clusterCol->clear();
return;
}
//
// Sets the event energy
//
double TreeBasedTool::getEventEnergy()
{
double energy = m_minEnergy;
// Recover pointer to Cal Cluster info
Event::TkrEventParams* tkrEventParams =
SmartDataPtr<Event::TkrEventParams>(m_dataSvc,EventModel::TkrRecon::TkrEventParams);
//If clusters, then retrieve estimate for the energy & centroid
if (tkrEventParams)
{
energy = std::max(tkrEventParams->getEventEnergy(), m_minEnergy);
}
return energy;
}
/// Assigns energy to tracks
void TreeBasedTool::setTrackEnergy(double eventEnergy, Event::TkrTrackCol* tdsTracks)
{
// Nothing to do here if no tracks
if (tdsTracks->empty()) return;
// How many tracks do we have?
int numTracks = tdsTracks->size();
// Fraction of event energy to first track
double fracEnergy = numTracks > 1 ? m_fracEneFirstTrack : 1.;
for (Event::TkrTrackCol::iterator trackItr = tdsTracks->begin(); trackItr != tdsTracks->end(); trackItr++)
{
Event::TkrTrack* track = *trackItr;
// Set the track energy
track->setInitialEnergy(fracEnergy * eventEnergy);
if (StatusCode sc = m_trackFitTool->doTrackFit(track) != StatusCode::SUCCESS)
{
}
// See if we can add leading hits
// int numAdded = m_findHitsTool->addLeadingHits(track);
// If added, then we need to refit?
// if (numAdded > 0)
// {
// if (StatusCode sc = m_trackFitTool->doTrackFit(track) != StatusCode::SUCCESS)
// {
// }
// }
// Reset the energy stuff for subsequent tracks
if (trackItr == tdsTracks->begin() && numTracks > 1)
{
eventEnergy -= fracEnergy * eventEnergy;
fracEnergy = 1. / (numTracks - 1);
}
}
// Ok, now that we are fit, re-sort one more time...
// std::sort(tdsTracks->begin(), tdsTracks->end(), CompareTkrTracks());
return;
}
class SortTreeClusterRelationsByLength
{
public:
SortTreeClusterRelationsByLength() {};
~SortTreeClusterRelationsByLength() {};
const bool operator()(const Event::TreeClusterRelation* left,
const Event::TreeClusterRelation* right) const
{
// Try sorting simply by closest DOCA or angle
//int leftNumBiLayers = left->getTree()->getHeadNode()->getBestNumBiLayers();
//int rightNumBiLayers = right->getTree()->getHeadNode()->getBestNumBiLayers();
//if (leftNumBiLayers > rightNumBiLayers) return true;
const Event::TkrVecNode* leftNode = left->getTree()->getHeadNode();
const Event::TkrVecNode* rightNode = right->getTree()->getHeadNode();
double sclFactor = double(rightNode->getBestNumBiLayers()) / double(leftNode->getBestNumBiLayers());
double leftRmsAngle = leftNode->getBestRmsAngle() * sclFactor * sclFactor;
double rightRmsAngle = rightNode->getBestRmsAngle() / (sclFactor * sclFactor);
if (leftRmsAngle < rightRmsAngle) return true;
return false;
}
};
class SortTreeClusterRelationsByDist
{
public:
SortTreeClusterRelationsByDist() {};
~SortTreeClusterRelationsByDist() {};
const bool operator()(const Event::TreeClusterRelation* left,
const Event::TreeClusterRelation* right) const
{
// Form a "blended" doca/angle to cluster
double leftDocaByAngle = left->getTreeClusDoca() / std::max(0.0001,std::fabs(left->getTreeClusCosAngle()));
double rightDocaByAngle = right->getTreeClusDoca() / std::max(0.0001,std::fabs(right->getTreeClusCosAngle()));
// Try sorting simply by closest DOCA or angle
if (leftDocaByAngle < rightDocaByAngle)
{
return true;
}
return false;
}
};
Event::TreeClusterRelationVec TreeBasedTool::buildTreeRelVec(Event::ClusterToRelationMap* clusToRelationMap,
Event::TreeToRelationMap* treeToRelationMap,
Event::TkrTreeCol* treeCol,
Event::CalClusterVec* calClusterVec)
{
// The goal of this method is to return a vector of Tree to Cluster relations. The general order of this
// vector is going to be by Cal Cluster and, for trees sharing clusters, sorted by proximity to cluster parameters.
// Tacked onto the end of the list will be any trees which were not originally associated to a cluster (can happen!)
Event::TreeClusterRelationVec treeRelVec;
treeRelVec.clear();
// Note that we must protect against the case where there are no clusters
// in the TDS colletion!
try
{
if (m_reorderTrees && calClusterVec && !calClusterVec->empty())
{
// The Cal cluster ordering should reflect the output of the classification tree where the first
// cluster is thought to be "the" gamma cluster. Loop through clusters in order and do the
// tree ordering
// We first need to set the end condition...
for(Event::CalClusterVec::iterator clusItr = calClusterVec->begin(); clusItr != calClusterVec->end(); clusItr++)
{
// Cluster pointer
Event::CalCluster* cluster = *clusItr;
// Retrieve the vector of tree associations for this cluster
Event::ClusterToRelationMap::iterator clusToRelationItr = clusToRelationMap->find(cluster);
if (clusToRelationItr != clusToRelationMap->end())
{
Event::TreeClusterRelationVec* relVec = &clusToRelationItr->second;
// If more than one tree associated to this cluster then we need to so some reordering
if (relVec && relVec->size() > 1)
{
// First we are going to put the vector into order by length
std::sort(relVec->begin(), relVec->end(), SortTreeClusterRelationsByLength());
// Now take the length of the first/longest Tree and look down the list to find the point
// where the length is less by less than 3 bilayers.
int bestTreeLength = relVec->front()->getTree()->getHeadNode()->getBestNumBiLayers();
// Set the iterator to the "last" element to sort
Event::TreeClusterRelationVec::iterator lastItr = relVec->end();
// Ok, this search only makes sense if the best Tree length is more than 5 bilayers
if (bestTreeLength > 5)
{
// Get the best rms angle for comparison below
double bestRmsAngle = relVec->front()->getTree()->getHeadNode()->getBestRmsAngle();
// Set a loop iterator
Event::TreeClusterRelationVec::iterator loopItr = relVec->begin();
// Reset the lastItr
lastItr = relVec->begin();
// Go through the list of relations looking for the point at which the length changes
while(loopItr != relVec->end())
{
Event::TreeClusterRelation* rel = *loopItr;
double calTransRms = rel->getCluster()->getMomParams().getTransRms();
double treeCalDoca = rel->getTreeClusDoca() / std::max(0.0001, rel->getTreeClusCosAngle());
int treeLength = rel->getTree()->getHeadNode()->getBestNumBiLayers();
int deltaLen = bestTreeLength - treeLength;
// This test meant to cut off any more searching after remaining trees get to be too short
if (deltaLen > 6 || (deltaLen > 2 && treeCalDoca > 3. * calTransRms)) break;
// Only increment the "last" if the other tree is relatively "straight"
if (rel->getTree()->getHeadNode()->getBestRmsAngle() < 7.5 * bestRmsAngle) lastItr = loopItr + 1;
loopItr++;
}
}
// Ok, now sort this mini list by proximity to the Cal Cluster
std::sort(relVec->begin(), lastItr, SortTreeClusterRelationsByDist());
}
// Now keep track of the results
for(Event::TreeClusterRelationVec::iterator relVecItr = relVec->begin();
relVecItr != relVec->end();
relVecItr++)
{
if ((*relVecItr)->getTree()) treeRelVec.push_back(*relVecItr);
}
}
}
// Don't forget the remaining trees
// Note that to preserve order we MUST loop over the input tree collection
for(Event::TkrTreeCol::iterator treeItr = treeCol->begin();
treeItr != treeCol->end();
treeItr++)
{
Event::TreeToRelationMap::iterator treeMapItr = treeToRelationMap->find(*treeItr);
// Should **always** be an entry here
if (treeMapItr == treeToRelationMap->end())
{
throw(TkrException("No Tree to cal cluster relation found!!"));
}
Event::TreeClusterRelation* treeClusRel = treeMapItr->second.front();
if (!treeClusRel->getCluster() && treeClusRel->getTree()) treeRelVec.push_back(treeClusRel);
}
}
// Otherwise, we simply use the results of the association
else
{
for(Event::TkrTreeCol::iterator treeItr = treeCol->begin(); treeItr != treeCol->end(); treeItr++)
{
Event::TkrTree* tree = *treeItr;
Event::TreeToRelationMap::iterator treeToRelationItr = treeToRelationMap->find(tree);
if (treeToRelationItr != treeToRelationMap->end())
{
Event::TreeClusterRelationVec& relVec = treeToRelationItr->second;
// A tree can be related to one cluster, simply grab the front/only one here
if (relVec.front()->getTree()) treeRelVec.push_back(relVec.front());
}
}
}
}
catch(TkrException& e)
{
throw e;
}
catch(...)
{
throw(TkrException("Unknown exception encountered in TkrVecNode and TkrTree building "));
}
try
{
// Ok, now the big step... we want to clear the current tree collection in the TDS - without deleting the trees -
// so we can reorder it according to the above associations
// To do this we need to make sure that Gaudi doesn't delete the tree and in order to do that we need to set the
// parent to zero and call the erase method handing it an iterator to the object in question... Seems contorted but
// this does the job.
int nTrees = treeCol->size();
while(nTrees--)
{
// If the tree is not empty then we don't want to delete it
// if (!treeCol->front()->empty()) treeCol->front()->setParent(0);
treeCol->front()->setParent(0);
// Ok, erase this tree (temporarily) from the collection
treeCol->erase(treeCol->begin());
}
// Now we gotta put the trees back in to the collection
// But if we have more than our limit of Trees then we are only going to keep the best ones
// Remember that treeRelVec is a local vector so we can loop through it without having to worry about
// deleting any of its members
for(Event::TreeClusterRelationVec::iterator relVecItr = treeRelVec.begin(); relVecItr != treeRelVec.end(); relVecItr++)
{
Event::TkrTree* tree = (*relVecItr)->getTree();
// If less than max then keep the tree
if (nTrees++ < m_maxTrees) treeCol->push_back(tree);
// Otherwise, we need to delete it while also making sure to zap previous knowledge of its existence
else
{
// First get rid of the Tree/Cluster relation
if (m_treeClusterAssociator) m_treeClusterAssociator->removeTreeClusterRelations(tree);
// Now delete the Tree
delete tree;
}
}
}
catch(TkrException& e)
{
throw e;
}
catch(...)
{
throw(TkrException("Unknown exception encountered in TkrVecNode and TkrTree building "));
}
return treeRelVec;
}
| 39.48723 | 151 | 0.58881 | [
"object",
"vector"
] |
7a376a1c398c359806312e423a2c9ce2b5161ce9 | 463 | cxx | C++ | Algorithms/Strings/two-strings.cxx | will-crawford/HackerRank | 74965480ee6a51603eb320e5982b0943fdaf1302 | [
"MIT"
] | null | null | null | Algorithms/Strings/two-strings.cxx | will-crawford/HackerRank | 74965480ee6a51603eb320e5982b0943fdaf1302 | [
"MIT"
] | null | null | null | Algorithms/Strings/two-strings.cxx | will-crawford/HackerRank | 74965480ee6a51603eb320e5982b0943fdaf1302 | [
"MIT"
] | null | null | null | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int32_t bits_from ( istream &is ) {
int32_t result = 0; char c; while ( is.get(c) && c != '\n' ) result |= 1 << ( c - 'a' ); return result;
}
int main() {
int p; cin >> p; cin >> ws; while ( --p >= 0 ) {
int32_t a = bits_from (cin), b = bits_from (cin);
cout << ( ( a & b ) ? "YES" : "NO" ) << endl;
}
return 0;
}
| 24.368421 | 107 | 0.531317 | [
"vector"
] |
7a3b824e6d577e850e7eed444dbee40bf8495986 | 7,228 | cpp | C++ | indra/test/llscriptresource_tut.cpp | humbletim/archived-casviewer | 3b51b1baae7e7cebf1c7dca62d9c02751709ee57 | [
"Unlicense"
] | null | null | null | indra/test/llscriptresource_tut.cpp | humbletim/archived-casviewer | 3b51b1baae7e7cebf1c7dca62d9c02751709ee57 | [
"Unlicense"
] | null | null | null | indra/test/llscriptresource_tut.cpp | humbletim/archived-casviewer | 3b51b1baae7e7cebf1c7dca62d9c02751709ee57 | [
"Unlicense"
] | null | null | null | /**
* @file llscriptresource_tut.cpp
* @brief Test LLScriptResource
*
* $LicenseInfo:firstyear=2008&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2010, Linden Research, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License only.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
//#include <tut/tut.h>
#include "linden_common.h"
#include "lltut.h"
#include "llscriptresource.h"
#include "llscriptresourceconsumer.h"
#include "llscriptresourcepool.h"
class TestConsumer : public LLScriptResourceConsumer
{
public:
TestConsumer()
: mUsedURLs(0)
{ }
// LLScriptResourceConsumer interface:
S32 getUsedPublicURLs() const
{
return mUsedURLs;
}
// Test details:
S32 mUsedURLs;
};
namespace tut
{
class LLScriptResourceTestData
{
};
typedef test_group<LLScriptResourceTestData> LLScriptResourceTestGroup;
typedef LLScriptResourceTestGroup::object LLScriptResourceTestObject;
LLScriptResourceTestGroup scriptResourceTestGroup("scriptResource");
template<> template<>
void LLScriptResourceTestObject::test<1>()
{
LLScriptResource resource;
U32 total = 42;
resource.setTotal(total);
ensure_equals("Verify set/get total", resource.getTotal(), total);
ensure_equals("Verify all resources are initially available",resource.getAvailable(),total);
// Requesting too many, releasing non-allocated
ensure("Request total + 1 resources should fail",!resource.request(total + 1));
ensure_equals("Verify all resources available after failed request",resource.getAvailable(),total);
ensure("Releasing resources when none allocated should fail",!resource.release());
ensure_equals("All resources should be available after failed release",resource.getAvailable(),total);
ensure("Request one resource", resource.request());
ensure_equals("Verify available resources after successful request",resource.getAvailable(),total - 1);
// Is this right? Or should we release all used resources if we try to release more than are currently used?
ensure("Release more resources than allocated",!resource.release(2));
ensure_equals("Verify resource availability after failed release",resource.getAvailable(),total - 1);
ensure("Release a resource",resource.release());
ensure_equals("Verify all resources available after successful release",resource.getAvailable(),total);
}
template<> template<>
void LLScriptResourceTestObject::test<2>()
{
LLScriptResource resource;
U32 total = 42;
resource.setTotal(total);
S32 resources_to_request = 30;
ensure("Get multiple resources resources",resource.request(resources_to_request));
ensure_equals("Verify available resources is correct after request of multiple resources",resource.getAvailable(), total - resources_to_request);
S32 resources_to_release = (resources_to_request / 2);
ensure("Release some resources",resource.release(resources_to_release));
S32 expected_available = (total - resources_to_request + resources_to_release);
ensure_equals("Verify available resources after release of some resources",resource.getAvailable(), expected_available);
resources_to_release = (resources_to_request - resources_to_release);
ensure("Release remaining resources",resource.release(resources_to_release));
ensure_equals("Verify available resources after release of remaining resources",resource.getAvailable(), total);
}
template<> template<>
void LLScriptResourceTestObject::test<3>()
{
LLScriptResource resource;
U32 total = 42;
resource.setTotal(total);
ensure("Request all resources",resource.request(total));
U32 low_total = 10;
ensure("Release all resources",resource.release(total));
ensure_equals("Verify all resources available after releasing",resource.getAvailable(),total);
resource.setTotal(low_total);
ensure_equals("Verify low total resources are available after set",resource.getAvailable(),low_total);
}
template<> template<>
void LLScriptResourceTestObject::test<4>()
{
S32 big_resource_total = 100;
S32 small_resource_total = 10;
LLScriptResourcePool big_pool;
big_pool.getPublicURLResource().setTotal(big_resource_total);
LLScriptResourcePool small_pool;
small_pool.getPublicURLResource().setTotal(small_resource_total);
TestConsumer consumer;
LLScriptResourcePool& initial_pool = consumer.getScriptResourcePool();
ensure("Initial resource pool is 'null'.", (&initial_pool == &LLScriptResourcePool::null));
consumer.switchScriptResourcePools(big_pool);
LLScriptResourcePool& get_pool = consumer.getScriptResourcePool();
ensure("Get resource that was set.", (&big_pool == &get_pool));
ensure_equals("No public urls in use yet.", consumer.getUsedPublicURLs(),0);
S32 request_urls = 5;
consumer.mUsedURLs = request_urls;
consumer.getScriptResourcePool().getPublicURLResource().request(request_urls);
ensure_equals("Available urls on big_pool is 5 less than total.",
big_pool.getPublicURLResource().getAvailable(), big_resource_total - request_urls);
ensure("Switching from big pool to small pool",
consumer.switchScriptResourcePools(small_pool));
ensure_equals("All resources available to big pool again",
big_pool.getPublicURLResource().getAvailable(), big_resource_total);
ensure_equals("Available urls on small pool is 5 less than total.",
small_pool.getPublicURLResource().getAvailable(), small_resource_total - request_urls);
ensure("Switching from small pool to big pool",
consumer.switchScriptResourcePools(big_pool));
consumer.getScriptResourcePool().getPublicURLResource().release(request_urls);
request_urls = 50; // Too many for the small_pool
consumer.mUsedURLs = request_urls;
consumer.getScriptResourcePool().getPublicURLResource().request(request_urls);
// Verify big pool has them
ensure_equals("Available urls on big pool is 50 less than total.",
big_pool.getPublicURLResource().getAvailable(), big_resource_total - request_urls);
// Verify can't switch to small_pool
ensure("Switching to small pool with too many resources",
!consumer.switchScriptResourcePools(small_pool));
// Verify big pool still accounting for used resources
ensure_equals("Available urls on big_pool is still 50 less than total.",
big_pool.getPublicURLResource().getAvailable(), big_resource_total - request_urls);
// Verify small pool still has all resources available.
ensure_equals("All resources in small pool are still available.",
small_pool.getPublicURLResource().getAvailable(), small_resource_total);
}
}
| 36.321608 | 147 | 0.770476 | [
"object"
] |
7a40e447feb77263c718c129a78fd9fbb8ee2010 | 642 | cpp | C++ | C++/0797-All-Paths-From-Source-to-Target/soln-1.cpp | wyaadarsh/LeetCode-Solutions | 3719f5cb059eefd66b83eb8ae990652f4b7fd124 | [
"MIT"
] | 5 | 2020-07-24T17:48:59.000Z | 2020-12-21T05:56:00.000Z | C++/0797-All-Paths-From-Source-to-Target/soln-1.cpp | zhangyaqi1989/LeetCode-Solutions | 2655a1ffc8678ad1de6c24295071308a18c5dc6e | [
"MIT"
] | null | null | null | C++/0797-All-Paths-From-Source-to-Target/soln-1.cpp | zhangyaqi1989/LeetCode-Solutions | 2655a1ffc8678ad1de6c24295071308a18c5dc6e | [
"MIT"
] | 2 | 2020-07-24T17:49:01.000Z | 2020-08-31T19:57:35.000Z | class Solution {
public:
vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
vector<int> path = {0};
vector<vector<int>> ans;
dfs(graph, path, ans);
return ans;
}
void dfs(vector<vector<int>>& graph, vector<int> & path, vector<vector<int>>& ans) {
if (path.back() == graph.size() - 1) {
ans.push_back(path);
} else {
int node = path.back();
for(int nei : graph[node]) {
path.push_back(nei);
dfs(graph, path, ans);
path.pop_back();
}
}
}
};
| 25.68 | 88 | 0.47352 | [
"vector"
] |
7a422c4526888af6aa87a15c134a478a9f56829f | 24,723 | cc | C++ | Translator_file/examples/step-20/step-20.cc | jiaqiwang969/deal.ii-course-practice | 0da5ad1537d8152549d8a0e4de5872efe7619c8a | [
"MIT"
] | null | null | null | Translator_file/examples/step-20/step-20.cc | jiaqiwang969/deal.ii-course-practice | 0da5ad1537d8152549d8a0e4de5872efe7619c8a | [
"MIT"
] | null | null | null | Translator_file/examples/step-20/step-20.cc | jiaqiwang969/deal.ii-course-practice | 0da5ad1537d8152549d8a0e4de5872efe7619c8a | [
"MIT"
] | null | null | null |
/* ---------------------------------------------------------------------
*
* Copyright (C) 2005 - 2021 by the deal.II authors
*
* This file is part of the deal.II library.
*
* The deal.II library is free software; you can use it, redistribute
* it, and/or modify it under the terms of the GNU Lesser General
* Public License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* The full text of the license can be found in the file LICENSE.md at
* the top level directory of deal.II.
*
* ---------------------------------------------------------------------
*/
// @sect3{Include files}
// 由于这个程序只是对 step-4 的改编,所以在头文件方面没有太多的新东西。在deal.II中,我们通常按照base-lac-grid-dofs-fe-numerics的顺序列出包含文件,然后是C++标准包含文件。
#include <deal.II/base/quadrature_lib.h>
#include <deal.II/base/logstream.h>
#include <deal.II/base/function.h>
#include <deal.II/lac/block_vector.h>
#include <deal.II/lac/full_matrix.h>
#include <deal.II/lac/block_sparse_matrix.h>
#include <deal.II/lac/solver_cg.h>
#include <deal.II/lac/precondition.h>
// 唯一值得关注的两个新头文件是LinearOperator和PackagedOperation类的文件。
#include <deal.II/lac/linear_operator.h>
#include <deal.II/lac/packaged_operation.h>
#include <deal.II/grid/tria.h>
#include <deal.II/grid/grid_generator.h>
#include <deal.II/dofs/dof_handler.h>
#include <deal.II/dofs/dof_renumbering.h>
#include <deal.II/dofs/dof_tools.h>
#include <deal.II/fe/fe_dgq.h>
#include <deal.II/fe/fe_system.h>
#include <deal.II/fe/fe_values.h>
#include <deal.II/numerics/vector_tools.h>
#include <deal.II/numerics/matrix_tools.h>
#include <deal.II/numerics/data_out.h>
#include <fstream>
#include <iostream>
// 这是唯一重要的新标题,即声明Raviart-Thomas有限元的标题。
#include <deal.II/fe/fe_raviart_thomas.h>
// 最后,作为本程序中的一项奖励,我们将使用一个张量系数。由于它可能具有空间依赖性,我们认为它是一个张量值的函数。下面的include文件提供了 <code>TensorFunction</code> 类,提供了这样的功能。
#include <deal.II/base/tensor_function.h>
// 最后一步和以前所有的程序一样。我们把所有与这个程序相关的代码放到一个命名空间中。(这个想法在 step-7 中首次提出) 。
namespace Step20
{
using namespace dealii;
// @sect3{The <code>MixedLaplaceProblem</code> class template}
// 同样,由于这是对 step-6 的改编,主类与该教程程序中的主类几乎相同。就成员函数而言,主要区别在于构造函数将Raviart-Thomas元素的度数作为参数(并且有一个相应的成员变量来存储这个值),并且增加了 <code>compute_error</code> 函数,在这个函数中,不出意外,我们将计算精确解和数值解之间的差异,以确定我们计算的收敛性。
template <int dim>
class MixedLaplaceProblem
{
public:
MixedLaplaceProblem(const unsigned int degree);
void run();
private:
void make_grid_and_dofs();
void assemble_system();
void solve();
void compute_errors() const;
void output_results() const;
const unsigned int degree;
Triangulation<dim> triangulation;
FESystem<dim> fe;
DoFHandler<dim> dof_handler;
// 第二个区别是疏散模式、系统矩阵、解和右手向量现在被封锁了。这意味着什么,人们可以用这些对象做什么,在本程序的介绍中已经解释过了,下面我们在解释这个问题的线性求解器和预处理器时也会进一步解释。
BlockSparsityPattern sparsity_pattern;
BlockSparseMatrix<double> system_matrix;
BlockVector<double> solution;
BlockVector<double> system_rhs;
};
// @sect3{Right hand side, boundary values, and exact solution}
// 我们的下一个任务是定义我们问题的右手边(即原始拉普拉斯方程中压力的标量右手边),压力的边界值,以及一个描述压力和精确解的速度的函数,以便以后计算误差。请注意,这些函数分别有一个、一个和 <code>dim+1</code> 个分量,我们将分量的数量传递给 <code>Function@<dim@></code> 基类。对于精确解,我们只声明实际一次性返回整个解向量(即其中的所有成分)的函数。下面是各自的声明。
namespace PrescribedSolution
{
constexpr double alpha = 0.3;
constexpr double beta = 1;
template <int dim>
class RightHandSide : public Function<dim>
{
public:
RightHandSide()
: Function<dim>(1)
{}
virtual double value(const Point<dim> & p,
const unsigned int component = 0) const override;
};
template <int dim>
class PressureBoundaryValues : public Function<dim>
{
public:
PressureBoundaryValues()
: Function<dim>(1)
{}
virtual double value(const Point<dim> & p,
const unsigned int component = 0) const override;
};
template <int dim>
class ExactSolution : public Function<dim>
{
public:
ExactSolution()
: Function<dim>(dim + 1)
{}
virtual void vector_value(const Point<dim> &p,
Vector<double> & value) const override;
};
// 然后我们还必须定义这些各自的函数,当然了。鉴于我们在介绍中讨论了解决方案应该是怎样的,下面的计算应该是很简单的。
template <int dim>
double RightHandSide<dim>::value(const Point<dim> & /*p*/,
const unsigned int /*component*/) const
{
return 0;
}
template <int dim>
double
PressureBoundaryValues<dim>::value(const Point<dim> &p,
const unsigned int /*component*/) const
{
return -(alpha * p[0] * p[1] * p[1] / 2 + beta * p[0] -
alpha * p[0] * p[0] * p[0] / 6);
}
template <int dim>
void ExactSolution<dim>::vector_value(const Point<dim> &p,
Vector<double> & values) const
{
Assert(values.size() == dim + 1,
ExcDimensionMismatch(values.size(), dim + 1));
values(0) = alpha * p[1] * p[1] / 2 + beta - alpha * p[0] * p[0] / 2;
values(1) = alpha * p[0] * p[1];
values(2) = -(alpha * p[0] * p[1] * p[1] / 2 + beta * p[0] -
alpha * p[0] * p[0] * p[0] / 6);
}
// @sect3{The inverse permeability tensor}
// 除了其他方程数据外,我们还想使用渗透性张量,或者更好的是--因为这是在弱形式中出现的全部内容--渗透性张量的逆, <code>KInverse</code> 。对于验证解的精确性和确定收敛顺序的目的来说,这个张量的作用大于帮助。因此,我们将简单地把它设置为同一矩阵。
// 然而,在现实生活中的多孔介质流动模拟中,空间变化的渗透率张量是不可缺少的,我们想利用这个机会来展示使用张量值函数的技术。
// 可能不足为奇,deal.II也有一个基类,不仅适用于标量和一般的矢量值函数( <code>Function</code> 基类),也适用于返回固定维度和等级的张量的函数, <code>TensorFunction</code> 模板。在这里,所考虑的函数返回一个dim-by-dim矩阵,即一个等级为2、维度为 <code>dim</code> 的张量。然后我们适当地选择基类的模板参数。
// <code>TensorFunction</code> 类提供的接口本质上等同于 <code>Function</code> 类。特别是,存在一个 <code>value_list</code> 函数,它接收一个评估函数的点的列表,并在第二个参数中返回函数的值,一个张量的列表。
template <int dim>
class KInverse : public TensorFunction<2, dim>
{
public:
KInverse()
: TensorFunction<2, dim>()
{}
virtual void
value_list(const std::vector<Point<dim>> &points,
std::vector<Tensor<2, dim>> & values) const override;
};
// 实现起来就不那么有趣了。和以前的例子一样,我们在类的开头添加一个检查,以确保输入和输出参数的大小是相同的(关于这个技术的讨论见 step-5 )。然后我们在所有的评估点上循环,对于每一个评估点,将输出张量设置为身份矩阵。
// 在函数的顶部有一个奇怪的地方(`(void)point;`语句),值得讨论。我们放到输出`values`数组中的值实际上并不取决于函数被评估的坐标`points`数组。换句话说,`points'参数实际上是不用的,如果我们想的话,可以不给它起名字。但是我们想用`points`对象来检查`values`对象是否有正确的大小。问题是,在发布模式下,`AssertDimension`被定义为一个宏,扩展为空;然后编译器会抱怨`points`对象没有使用。消除这个警告的习惯方法是有一个评估(读取)变量的语句,但实际上不做任何事情:这就是`(void)points;`所做的:它从`points`中读取,然后将读取的结果转换为`void`,也就是什么都没有。换句话说,这句话是完全没有意义的,除了向编译器解释是的,这个变量事实上是被使用的,即使是在发布模式下。(在调试模式下,`AssertDimension`宏会扩展为从变量中读出的东西,所以在调试模式下,这个有趣的语句是没有必要的)。
template <int dim>
void KInverse<dim>::value_list(const std::vector<Point<dim>> &points,
std::vector<Tensor<2, dim>> & values) const
{
(void)points;
AssertDimension(points.size(), values.size());
for (auto &value : values)
value = unit_symmetric_tensor<dim>();
}
} // namespace PrescribedSolution
// @sect3{MixedLaplaceProblem class implementation}
// @sect4{MixedLaplaceProblem::MixedLaplaceProblem}
// 在这个类的构造函数中,我们首先存储传入的关于我们将使用的有限元的度数的值(例如,度数为0,意味着使用RT(0)和DG(0)),然后构造属于介绍中描述的空间 $X_h$ 的向量值的元素。构造函数的其余部分与早期的教程程序一样。
// 这里唯一值得描述的是,这个变量所属的 <code>fe</code> variable. The <code>FESystem</code> 类的构造函数调用有很多不同的构造函数,它们都是指将较简单的元素绑定在一起,成为一个较大的元素。在目前的情况下,我们想把一个RT(度)元素与一个DQ(度)元素结合起来。这样做的 <code>FESystem</code> 构造函数要求我们首先指定第一个基本元素(给定程度的 <code>FE_RaviartThomas</code> 对象),然后指定这个基本元素的副本数量,然后类似地指定 <code>FE_DGQ</code> 元素的种类和数量。注意Raviart-Thomas元素已经有 <code>dim</code> 个矢量分量,所以耦合元素将有 <code>dim+1</code> 个矢量分量,其中第一个 <code>dim</code> 个对应于速度变量,最后一个对应于压力。
// 我们从基本元素中构建这个元素的方式与我们在 step-8 中的方式也值得比较:在那里,我们将其构建为 <code>fe (FE_Q@<dim@>(1), dim)</code> ,即我们简单地使用 <code>dim</code> copies of the <code>FE_Q(1)</code> 元素,每个坐标方向上的位移都有一份。
template <int dim>
MixedLaplaceProblem<dim>::MixedLaplaceProblem(const unsigned int degree)
: degree(degree)
, fe(FE_RaviartThomas<dim>(degree), 1, FE_DGQ<dim>(degree), 1)
, dof_handler(triangulation)
{}
// @sect4{MixedLaplaceProblem::make_grid_and_dofs}
// 接下来的函数开始于众所周知的函数调用,创建和细化一个网格,然后将自由度与之关联。
template <int dim>
void MixedLaplaceProblem<dim>::make_grid_and_dofs()
{
GridGenerator::hyper_cube(triangulation, -1, 1);
triangulation.refine_global(5);
dof_handler.distribute_dofs(fe);
// 然而,接下来事情就变得不同了。正如介绍中提到的,我们要将矩阵细分为对应于速度和压力这两种不同的变量的块。为此,我们首先要确保与速度和压力相对应的指数不会混在一起。首先是所有速度自由度,然后是所有压力自由度。这样一来,全局矩阵就很好地分离成一个 $2 \times 2$ 系统。为了达到这个目的,我们必须根据自由度的矢量分量对其重新编号,这个操作已经很方便地实现了。
DoFRenumbering::component_wise(dof_handler);
// 接下来,我们要弄清楚这些块的大小,以便我们可以分配适当的空间量。为此,我们调用了 DoFTools::count_dofs_per_fe_component() 函数,该函数计算了某个向量分量的形状函数非零的数量。我们有 <code>dim+1</code> 个向量分量, DoFTools::count_dofs_per_fe_component() 将计算有多少个形状函数属于这些分量中的每个。
// 这里有一个问题。正如该函数的文档所描述的,它 <i>wants</i> 将 $x$ -速度形状函数的数量放入 <code>dofs_per_component[0]</code> 中,将 $y$ -速度形状函数的数量放入 <code>dofs_per_component[1]</code> 中(以及类似的3d),并将压力形状函数的数量放入 <code>dofs_per_component[dim]</code> 中 。但是,Raviart-Thomas元素的特殊性在于它是非 @ref GlossPrimitive "原始 "的,也就是说,对于Raviart-Thomas元素,所有的速度形状函数在所有分量中都是非零。换句话说,该函数不能区分 $x$ 和 $y$ 速度函数,因为<i>is</i>没有这种区分。因此,它将速度的总体数量放入 <code>dofs_per_component[c]</code> , $0\le c\le \text{dim}$ 中的每一个。另一方面,压力变量的数量等于在dim-th分量中不为零的形状函数的数量。
// 利用这些知识,我们可以从 <code>dofs_per_component</code> 的第一个 <code>dim</code> 元素中的任何一个得到速度形状函数的数量,然后用下面这个来初始化向量和矩阵块的大小,以及创建输出。
// @note 如果你觉得这个概念难以理解,你可以考虑用函数 DoFTools::count_dofs_per_fe_block() 来代替,就像我们在 step-22 的相应代码中做的那样。你可能还想阅读一下术语表中 @ref GlossBlock "块 "和 @ref GlossComponent "组件 "的区别。
const std::vector<types::global_dof_index> dofs_per_component =
DoFTools::count_dofs_per_fe_component(dof_handler);
const unsigned int n_u = dofs_per_component[0],
n_p = dofs_per_component[dim];
std::cout << "Number of active cells: " << triangulation.n_active_cells()
<< std::endl
<< "Total number of cells: " << triangulation.n_cells()
<< std::endl
<< "Number of degrees of freedom: " << dof_handler.n_dofs()
<< " (" << n_u << '+' << n_p << ')' << std::endl;
// 下一个任务是为我们将要创建的矩阵分配一个稀疏模式。我们使用与前面步骤一样的压缩稀疏模式,但是由于 <code>system_matrix</code> 是一个块状矩阵,我们使用 <code>BlockDynamicSparsityPattern</code> 类,而不仅仅是 <code>DynamicSparsityPattern</code> 。这种块状稀疏模式在 $2 \times 2$ 模式下有四个块。块的大小取决于 <code>n_u</code> and <code>n_p</code> ,它持有速度和压力变量的数量。在第二步中,我们必须指示块系统更新它所管理的块的大小的知识;这发生在 <code>dsp.collect_sizes ()</code> 的调用中。
BlockDynamicSparsityPattern dsp(2, 2);
dsp.block(0, 0).reinit(n_u, n_u);
dsp.block(1, 0).reinit(n_p, n_u);
dsp.block(0, 1).reinit(n_u, n_p);
dsp.block(1, 1).reinit(n_p, n_p);
dsp.collect_sizes();
DoFTools::make_sparsity_pattern(dof_handler, dsp);
// 我们以与非区块版本相同的方式使用压缩的区块稀疏模式,以创建稀疏模式,然后创建系统矩阵。
sparsity_pattern.copy_from(dsp);
system_matrix.reinit(sparsity_pattern);
// 然后,我们必须以与块压缩稀疏度模式完全相同的方式调整解决方案和右侧向量的大小。
solution.reinit(2);
solution.block(0).reinit(n_u);
solution.block(1).reinit(n_p);
solution.collect_sizes();
system_rhs.reinit(2);
system_rhs.block(0).reinit(n_u);
system_rhs.block(1).reinit(n_p);
system_rhs.collect_sizes();
}
// @sect4{MixedLaplaceProblem::assemble_system}
// 同样地,组装线性系统的函数在这个例子的介绍中已经讨论过很多了。在它的顶部,发生的是所有常见的步骤,此外,我们不仅为单元项分配正交和 <code>FEValues</code> 对象,而且还为面项分配。之后,我们为变量定义通常的缩写,并为本地矩阵和右手贡献分配空间,以及保存当前单元的全局自由度数的数组。
template <int dim>
void MixedLaplaceProblem<dim>::assemble_system()
{
QGauss<dim> quadrature_formula(degree + 2);
QGauss<dim - 1> face_quadrature_formula(degree + 2);
FEValues<dim> fe_values(fe,
quadrature_formula,
update_values | update_gradients |
update_quadrature_points | update_JxW_values);
FEFaceValues<dim> fe_face_values(fe,
face_quadrature_formula,
update_values | update_normal_vectors |
update_quadrature_points |
update_JxW_values);
const unsigned int dofs_per_cell = fe.n_dofs_per_cell();
const unsigned int n_q_points = quadrature_formula.size();
const unsigned int n_face_q_points = face_quadrature_formula.size();
FullMatrix<double> local_matrix(dofs_per_cell, dofs_per_cell);
Vector<double> local_rhs(dofs_per_cell);
std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell);
// 下一步是声明代表方程中源项、压力边界值和系数的对象。除了这些代表连续函数的对象外,我们还需要数组来保存它们在各个单元格(或面,对于边界值)的正交点的值。请注意,在系数的情况下,数组必须是矩阵的一种。
const PrescribedSolution::RightHandSide<dim> right_hand_side;
const PrescribedSolution::PressureBoundaryValues<dim>
pressure_boundary_values;
const PrescribedSolution::KInverse<dim> k_inverse;
std::vector<double> rhs_values(n_q_points);
std::vector<double> boundary_values(n_face_q_points);
std::vector<Tensor<2, dim>> k_inverse_values(n_q_points);
// 最后,我们需要几个提取器,用来获取矢量值形状函数的速度和压力成分。它们的功能和使用在 @ref vector_valued报告中有详细描述。基本上,我们将把它们作为下面FEValues对象的下标:FEValues对象描述了形状函数的所有矢量分量,而在订阅后,它将只指速度(一组从零分量开始的 <code>dim</code> 分量)或压力(位于 <code>dim</code> 位置的标量分量)。
const FEValuesExtractors::Vector velocities(0);
const FEValuesExtractors::Scalar pressure(dim);
// 有了这些,我们就可以继续对所有单元进行循环。这个循环的主体已经在介绍中讨论过了,这里就不再做任何评论了。
for (const auto &cell : dof_handler.active_cell_iterators())
{
fe_values.reinit(cell);
local_matrix = 0;
local_rhs = 0;
right_hand_side.value_list(fe_values.get_quadrature_points(),
rhs_values);
k_inverse.value_list(fe_values.get_quadrature_points(),
k_inverse_values);
for (unsigned int q = 0; q < n_q_points; ++q)
for (unsigned int i = 0; i < dofs_per_cell; ++i)
{
const Tensor<1, dim> phi_i_u = fe_values[velocities].value(i, q);
const double div_phi_i_u = fe_values[velocities].divergence(i, q);
const double phi_i_p = fe_values[pressure].value(i, q);
for (unsigned int j = 0; j < dofs_per_cell; ++j)
{
const Tensor<1, dim> phi_j_u =
fe_values[velocities].value(j, q);
const double div_phi_j_u =
fe_values[velocities].divergence(j, q);
const double phi_j_p = fe_values[pressure].value(j, q);
local_matrix(i, j) +=
(phi_i_u * k_inverse_values[q] * phi_j_u //
- phi_i_p * div_phi_j_u //
- div_phi_i_u * phi_j_p) //
* fe_values.JxW(q);
}
local_rhs(i) += -phi_i_p * rhs_values[q] * fe_values.JxW(q);
}
for (const auto &face : cell->face_iterators())
if (face->at_boundary())
{
fe_face_values.reinit(cell, face);
pressure_boundary_values.value_list(
fe_face_values.get_quadrature_points(), boundary_values);
for (unsigned int q = 0; q < n_face_q_points; ++q)
for (unsigned int i = 0; i < dofs_per_cell; ++i)
local_rhs(i) += -(fe_face_values[velocities].value(i, q) * //
fe_face_values.normal_vector(q) * //
boundary_values[q] * //
fe_face_values.JxW(q));
}
// 循环所有单元的最后一步是将局部贡献转移到全局矩阵和右手向量中。请注意,我们使用的接口与之前的例子完全相同,尽管我们现在使用的是块状矩阵和向量,而不是常规的。换句话说,对于外界来说,块对象具有与矩阵和向量相同的接口,但它们还允许访问单个块。
cell->get_dof_indices(local_dof_indices);
for (unsigned int i = 0; i < dofs_per_cell; ++i)
for (unsigned int j = 0; j < dofs_per_cell; ++j)
system_matrix.add(local_dof_indices[i],
local_dof_indices[j],
local_matrix(i, j));
for (unsigned int i = 0; i < dofs_per_cell; ++i)
system_rhs(local_dof_indices[i]) += local_rhs(i);
}
}
// @sect3{Implementation of linear solvers and preconditioners}
// 我们在这个例子中使用的线性求解器和预处理器已经在介绍中进行了详细的讨论。因此,我们在这里不再讨论我们的方法的原理,而只是对剩下的一些实现方面进行评论。
// @sect4{MixedLaplace::solve}
// 正如在介绍中所概述的那样,求解函数基本上由两个步骤组成。首先,我们必须形成涉及舒尔补数的第一个方程,并求解压力(解决方案的第一部分)。然后,我们可以从第二个方程(解的第0部分)中重构速度。
template <int dim>
void MixedLaplaceProblem<dim>::solve()
{
// 作为第一步,我们声明对矩阵的所有块状成分、右手边和我们将需要的解向量的引用。
const auto &M = system_matrix.block(0, 0);
const auto &B = system_matrix.block(0, 1);
const auto &F = system_rhs.block(0);
const auto &G = system_rhs.block(1);
auto &U = solution.block(0);
auto &P = solution.block(1);
// 然后,我们将创建相应的LinearOperator对象并创建 <code>op_M_inv</code> 运算器。
const auto op_M = linear_operator(M);
const auto op_B = linear_operator(B);
ReductionControl reduction_control_M(2000, 1.0e-18, 1.0e-10);
SolverCG<Vector<double>> solver_M(reduction_control_M);
PreconditionJacobi<SparseMatrix<double>> preconditioner_M;
preconditioner_M.initialize(M);
const auto op_M_inv = inverse_operator(op_M, solver_M, preconditioner_M);
// 这样我们就可以声明舒尔补数 <code>op_S</code> 和近似舒尔补数 <code>op_aS</code> 。
const auto op_S = transpose_operator(op_B) * op_M_inv * op_B;
const auto op_aS =
transpose_operator(op_B) * linear_operator(preconditioner_M) * op_B;
// 我们现在从 <code>op_aS</code> 中创建一个预处理程序,应用固定数量的30次(便宜的)CG迭代。
IterationNumberControl iteration_number_control_aS(30, 1.e-18);
SolverCG<Vector<double>> solver_aS(iteration_number_control_aS);
const auto preconditioner_S =
inverse_operator(op_aS, solver_aS, PreconditionIdentity());
// 现在来看看第一个方程。它的右边是 $B^TM^{-1}F-G$ ,这就是我们在前几行计算的结果。然后我们用CG求解器和我们刚刚声明的预处理程序来解决第一个方程。
const auto schur_rhs = transpose_operator(op_B) * op_M_inv * F - G;
SolverControl solver_control_S(2000, 1.e-12);
SolverCG<Vector<double>> solver_S(solver_control_S);
const auto op_S_inv = inverse_operator(op_S, solver_S, preconditioner_S);
P = op_S_inv * schur_rhs;
std::cout << solver_control_S.last_step()
<< " CG Schur complement iterations to obtain convergence."
<< std::endl;
// 得到压力后,我们可以计算速度。方程为 $MU=-BP+F$ ,我们通过首先计算右手边,然后与代表质量矩阵逆的对象相乘来解决这个问题。
U = op_M_inv * (F - op_B * P);
}
// @sect3{MixedLaplaceProblem class implementation (continued)}
// @sect4{MixedLaplace::compute_errors}
// 在我们处理完线性求解器和预处理器之后,我们继续实现我们的主类。特别是,下一个任务是计算我们数值解的误差,包括压力和速度。
// 为了计算解的误差,我们已经在 step-7 和 step-11 中介绍了 <code>VectorTools::integrate_difference</code> 函数。然而,在那里我们只处理了标量解,而在这里我们有一个矢量值的解,其组成部分甚至表示不同的量,并且可能有不同的收敛阶数(由于所使用的有限元的选择,这里不是这种情况,但在混合有限元应用中经常出现这种情况)。因此,我们要做的是 "掩盖 "我们感兴趣的成分。这很容易做到: <code>VectorTools::integrate_difference</code> 函数将一个指向权重函数的指针作为其参数之一(该参数默认为空指针,意味着单位权重)。我们要做的是传递一个函数对象,在我们感兴趣的成分中等于1,而在其他成分中等于0。例如,为了计算压力误差,我们应该传入一个函数,该函数在分量 <code>dim</code> 中代表单位值的常数向量,而对于速度,常数向量在第一个 <code>dim</code> 分量中应该是1,而在压力的位置是0。
// 在deal.II中, <code>ComponentSelectFunction</code> 正是这样做的:它想知道它要表示的函数应该有多少个向量分量(在我们的例子中,这将是 <code>dim+1</code> ,用于联合速度-压力空间),哪个个体或范围的分量应该等于1。因此,我们在函数的开头定义了两个这样的掩码,接下来是一个代表精确解的对象和一个向量,我们将在其中存储由 <code>integrate_difference</code> 计算的单元误差。
template <int dim>
void MixedLaplaceProblem<dim>::compute_errors() const
{
const ComponentSelectFunction<dim> pressure_mask(dim, dim + 1);
const ComponentSelectFunction<dim> velocity_mask(std::make_pair(0, dim),
dim + 1);
PrescribedSolution::ExactSolution<dim> exact_solution;
Vector<double> cellwise_errors(triangulation.n_active_cells());
// 正如在 step-7 中已经讨论过的那样,我们必须认识到,不可能精确地整合误差。我们所能做的就是用正交法对这个积分进行近似。这实际上在这里提出了一个小小的转折:如果我们像人们可能倾向于做的那样天真地选择一个 <code>QGauss@<dim@>(degree+1)</code> 类型的对象(这就是我们用于积分线性系统的对象),就会发现误差非常小,根本不遵循预期的收敛曲线。现在的情况是,对于这里使用的混合有限元,高斯点恰好是超收敛点,其中的点误差要比其他地方小得多(而且收敛的阶数更高)。因此,这些点不是特别好的积分点。为了避免这个问题,我们只需使用梯形法则,并在每个坐标方向上迭代 <code>degree+2</code> 次(同样如 step-7 中的解释)。
QTrapezoid<1> q_trapez;
QIterated<dim> quadrature(q_trapez, degree + 2);
// 有了这个,我们就可以让库计算出误差并将其输出到屏幕上。
VectorTools::integrate_difference(dof_handler,
solution,
exact_solution,
cellwise_errors,
quadrature,
VectorTools::L2_norm,
&pressure_mask);
const double p_l2_error =
VectorTools::compute_global_error(triangulation,
cellwise_errors,
VectorTools::L2_norm);
VectorTools::integrate_difference(dof_handler,
solution,
exact_solution,
cellwise_errors,
quadrature,
VectorTools::L2_norm,
&velocity_mask);
const double u_l2_error =
VectorTools::compute_global_error(triangulation,
cellwise_errors,
VectorTools::L2_norm);
std::cout << "Errors: ||e_p||_L2 = " << p_l2_error
<< ", ||e_u||_L2 = " << u_l2_error << std::endl;
}
// @sect4{MixedLaplace::output_results}
// 最后一个有趣的函数是我们生成图形输出的函数。请注意,所有的速度分量都得到相同的解名 "u"。再加上使用 DataComponentInterpretation::component_is_part_of_vector ,这将导致 DataOut<dim>::write_vtu() 生成各个速度分量的矢量表示,更多信息请参见 step-22 或 @ref VVOutput 模块中的 "生成图形输出 "部分。最后,对于高阶元素来说,在图形输出中每个单元只显示一个双线性四边形似乎不合适。因此,我们生成大小为(度数+1)x(度数+1)的斑块来捕捉解决方案的全部信息内容。有关这方面的更多信息,请参见 step-7 的教程程序。
template <int dim>
void MixedLaplaceProblem<dim>::output_results() const
{
std::vector<std::string> solution_names(dim, "u");
solution_names.emplace_back("p");
std::vector<DataComponentInterpretation::DataComponentInterpretation>
interpretation(dim,
DataComponentInterpretation::component_is_part_of_vector);
interpretation.push_back(DataComponentInterpretation::component_is_scalar);
DataOut<dim> data_out;
data_out.add_data_vector(dof_handler,
solution,
solution_names,
interpretation);
data_out.build_patches(degree + 1);
std::ofstream output("solution.vtu");
data_out.write_vtu(output);
}
// @sect4{MixedLaplace::run}
// 这是我们主类的最后一个函数。它唯一的工作是按照自然顺序调用其他函数。
template <int dim>
void MixedLaplaceProblem<dim>::run()
{
make_grid_and_dofs();
assemble_system();
solve();
compute_errors();
output_results();
}
} // namespace Step20
// @sect3{The <code>main</code> function}
// 我们从 step-6 而不是 step-4 那里偷来的主函数。它几乎等同于 step-6 中的函数(当然,除了改变的类名),唯一的例外是我们将有限元空间的度数传递给混合拉普拉斯问题的构造函数(这里,我们使用零阶元素)。
int main()
{
try
{
using namespace Step20;
const unsigned int fe_degree = 0;
MixedLaplaceProblem<2> mixed_laplace_problem(fe_degree);
mixed_laplace_problem.run();
}
catch (std::exception &exc)
{
std::cerr << std::endl
<< std::endl
<< "----------------------------------------------------"
<< std::endl;
std::cerr << "Exception on processing: " << std::endl
<< exc.what() << std::endl
<< "Aborting!" << std::endl
<< "----------------------------------------------------"
<< std::endl;
return 1;
}
catch (...)
{
std::cerr << std::endl
<< std::endl
<< "----------------------------------------------------"
<< std::endl;
std::cerr << "Unknown exception!" << std::endl
<< "Aborting!" << std::endl
<< "----------------------------------------------------"
<< std::endl;
return 1;
}
return 0;
}
| 40.397059 | 489 | 0.632812 | [
"vector"
] |
7a4487296be45c0c46119225d48eda99b2664ca2 | 3,599 | cpp | C++ | VEngine/Renderer/Object3dInfoFactory.cpp | achlubek/venginenative | ec1d10171b050d3f750f8e60c62575b7f08fe578 | [
"MIT"
] | 169 | 2016-04-03T08:43:31.000Z | 2021-07-08T15:44:13.000Z | VEngine/Renderer/Object3dInfoFactory.cpp | achlubek/venginenative | ec1d10171b050d3f750f8e60c62575b7f08fe578 | [
"MIT"
] | 5 | 2016-11-29T21:43:49.000Z | 2017-10-09T15:48:39.000Z | VEngine/Renderer/Object3dInfoFactory.cpp | achlubek/venginenative | ec1d10171b050d3f750f8e60c62575b7f08fe578 | [
"MIT"
] | 9 | 2016-05-23T15:54:49.000Z | 2020-07-15T03:39:55.000Z | #include "stdafx.h"
#include "Object3dInfoFactory.h"
#include "Object3dInfo.h"
#include "../FileSystem/Media.h"
namespace VEngine
{
namespace Renderer
{
using namespace VEngine::FileSystem;
using namespace VEngine::Renderer::Internal;
Object3dInfoFactory::Object3dInfoFactory(VulkanDevice* device, FileSystem::MediaInterface* media)
: device(device), media(media)
{
unsigned char bytes[288] = {
0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x80, 0xBF, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x80, 0xBF,
0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x80, 0x3F,
0x00, 0x00, 0x80, 0xBF, 0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x80, 0xBF,
0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x80, 0x3F,
0x00, 0x00, 0x80, 0xBF, 0x00, 0x00, 0x80, 0xBF, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x80, 0xBF,
0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x80, 0x3F,
0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x80, 0xBF, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x80, 0xBF,
0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x80, 0x3F,
0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x80, 0xBF,
0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x80, 0x3F,
0x00, 0x00, 0x80, 0xBF, 0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x80, 0xBF,
0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x80, 0x3F
};
int bytescount = 288;
GLfloat * floats = (GLfloat*)bytes;
int floatsCount = bytescount / 4;
std::vector<GLfloat> flo(floats, floats + floatsCount);
fullScreenQuad = build(flo);
}
Object3dInfoFactory::~Object3dInfoFactory()
{
}
Object3dInfoInterface * Object3dInfoFactory::build(std::string mediakey)
{
unsigned char* bytes;
int bytescount = media->readBinary(mediakey, &bytes);
float * floats = (float*)bytes;
int floatsCount = bytescount / 4;
std::vector<float> flo(floats, floats + floatsCount);
return build(flo);
}
Object3dInfoInterface * Object3dInfoFactory::build(std::vector<float> rawData)
{
return new Object3dInfo(device, rawData);
}
Object3dInfoInterface * Object3dInfoFactory::getFullScreenQuad()
{
return fullScreenQuad;
}
}
} | 46.74026 | 105 | 0.563768 | [
"vector"
] |
7a4bf9fcd63f307b1ded112156ccd0e083f899ae | 69,253 | cpp | C++ | SGPLibraryCode/modules/sgp_render/opengl/sgp_OpenGLWorldSystemManager.cpp | phoenixzz/VoronoiMapGen | 5afd852f8bb0212baba9d849178eb135f62df903 | [
"MIT"
] | 11 | 2017-03-03T03:31:15.000Z | 2019-03-01T17:09:12.000Z | SGPLibraryCode/modules/sgp_render/opengl/sgp_OpenGLWorldSystemManager.cpp | phoenixzz/VoronoiMapGen | 5afd852f8bb0212baba9d849178eb135f62df903 | [
"MIT"
] | null | null | null | SGPLibraryCode/modules/sgp_render/opengl/sgp_OpenGLWorldSystemManager.cpp | phoenixzz/VoronoiMapGen | 5afd852f8bb0212baba9d849178eb135f62df903 | [
"MIT"
] | 2 | 2017-03-03T03:31:17.000Z | 2021-05-27T21:50:43.000Z |
COpenGLWorldSystemManager::COpenGLWorldSystemManager(COpenGLRenderDevice* pRenderDevice, Logger* pLogger)
: m_pRenderDevice(pRenderDevice), m_pLogger(pLogger),
m_pWorldMap(NULL), m_pTerrain(NULL), m_pSkydome(NULL), m_pWorldSun(NULL), m_pWater(NULL), m_pGrass(NULL),
m_pWorldMapRawMemoryAddress(NULL)
{
m_VisibleSceneObjectArray.ensureStorageAllocated(INIT_SCENEOBJECTARRAYSIZE);
m_VisibleChunkArray.ensureStorageAllocated(SGPTS_LARGE*SGPTS_LARGE / 3);
m_WaterMirrorVisibleChunkArray.ensureStorageAllocated(SGPTS_LARGE*SGPTS_LARGE / 3);
}
COpenGLWorldSystemManager::~COpenGLWorldSystemManager()
{
if( m_pTerrain )
delete m_pTerrain;
m_pTerrain = NULL;
if( m_pSkydome )
delete m_pSkydome;
m_pSkydome = NULL;
if( m_pWorldSun )
delete m_pWorldSun;
m_pWorldSun = NULL;
if( m_pWater )
delete m_pWater;
m_pWater = NULL;
if( m_pGrass )
delete m_pGrass;
m_pGrass = NULL;
if( m_pWorldMapRawMemoryAddress )
delete [] m_pWorldMapRawMemoryAddress;
m_pWorldMapRawMemoryAddress = NULL;
}
void COpenGLWorldSystemManager::createTerrain( SGP_TERRAIN_SIZE terrainsize, bool bUsePerlinNoise, uint16 maxTerrainHeight )
{
// Create Terrain
m_pTerrain = new CSGPTerrain();
m_pTerrain->InitializeCreateHeightmap( terrainsize, bUsePerlinNoise, maxTerrainHeight );
m_pTerrain->CreateLODHeights();
m_pTerrain->UpdateBoundingBox();
// Create VB/IB render resource for Terrain
initializeTerrainRenderer(false);
}
void COpenGLWorldSystemManager::createSkydome( const String& skydomeMF1FileName )
{
// Create Skydome
m_pSkydome = new CSGPSkyDome();
m_pSkydome->m_MF1FileName = skydomeMF1FileName;
// load MF1 SkyDome static mesh
m_pSkydome->m_SkydomeMF1ModelResourceID = m_pRenderDevice->GetModelManager()->registerModel(skydomeMF1FileName, false);
if( m_pSkydome->m_SkydomeMF1ModelResourceID == 0xFFFFFFFF )
{
m_pLogger->writeToLog(String("Unable to load SkyDome MF1 File : ") + skydomeMF1FileName, ELL_ERROR);
return;
}
m_pSkydome->m_bUpdateModel = true;
}
void COpenGLWorldSystemManager::releaseSkydome()
{
if( m_pSkydome )
{
// unregister Skydome MF1 Model and Textures
if( m_pSkydome->m_SkydomeMF1ModelResourceID != 0xFFFFFFFF )
{
m_pRenderDevice->GetModelManager()->unRegisterModelByID(m_pSkydome->m_SkydomeMF1ModelResourceID);
m_pRenderDevice->getOpenGLSkydomeRenderer()->resetSkydomeStaticBuffer();
for( int i=0; i<m_pSkydome->m_nSkydomeTextureID.size(); i++ )
m_pRenderDevice->GetTextureManager()->unRegisterTextureByID( m_pSkydome->m_nSkydomeTextureID[i] );
}
}
}
void COpenGLWorldSystemManager::createWorldSun()
{
m_pWorldSun = new CSGPWorldSun();
}
void COpenGLWorldSystemManager::setWorldSunPosition( float fSunPosition )
{
if( m_pWorldSun )
{
m_pWorldSun->m_fSunPosition = fSunPosition;
m_pWorldSun->updateSunDirection();
// Compute thetaS dependencies
if( m_pSkydome )
{
Vector3D vecZenith( 0.0f, 1.0f, 0.0f );
float thetaS = acosf( m_pWorldSun->getSunDirection() * vecZenith );
m_pSkydome->GetScatter().computeAttenuation(thetaS);
}
}
}
void COpenGLWorldSystemManager::setSkydomeTexture( const String& SkyDomeColudTextureName, const String& SkyDomeNoiseTextureName )
{
if( m_pSkydome )
{
m_pSkydome->m_cloudTextureFileName = SkyDomeColudTextureName;
m_pSkydome->m_noiseTextureFileName = SkyDomeNoiseTextureName;
for( int i=0; i<m_pSkydome->m_nSkydomeTextureID.size(); i++ )
{
if( m_pSkydome->m_nSkydomeTextureID[i] != 0 )
m_pRenderDevice->GetTextureManager()->unRegisterTextureByID( m_pSkydome->m_nSkydomeTextureID[i] );
}
m_pSkydome->m_nSkydomeTextureID.clearQuick();
m_pSkydome->m_nSkydomeTextureID.add( m_pRenderDevice->GetTextureManager()->registerTexture( SkyDomeColudTextureName ) );
m_pSkydome->m_nSkydomeTextureID.add( m_pRenderDevice->GetTextureManager()->registerTexture( SkyDomeNoiseTextureName ) );
m_pRenderDevice->getOpenGLSkydomeRenderer()->updateSkydomeMaterialSkin(m_pSkydome);
}
}
ISGPObject* COpenGLWorldSystemManager::createObject( const String& MF1FileNameStr, const String& SceneObjectName,
const Vector3D& vPos, const Vector3D& vRotationXYZ,
float fScale, float fAlpha )
{
ISGPObject* pSceneObject = new ISGPObject();
strcpy( pSceneObject->m_MF1FileName, MF1FileNameStr.toUTF8().getAddress() );
strcpy( pSceneObject->m_SceneObjectName, SceneObjectName.toUTF8().getAddress() );
pSceneObject->m_fPosition[0] = vPos.x;
pSceneObject->m_fPosition[1] = vPos.y;
pSceneObject->m_fPosition[2] = vPos.z;
pSceneObject->m_fRotationXYZ[0] = vRotationXYZ.x;
pSceneObject->m_fRotationXYZ[1] = vRotationXYZ.y;
pSceneObject->m_fRotationXYZ[2] = vRotationXYZ.z;
pSceneObject->m_fScale = fScale;
pSceneObject->m_fAlpha = fAlpha;
return pSceneObject;
}
void COpenGLWorldSystemManager::addSceneObject( ISGPObject* obj, uint32 ConfigIndex )
{
// if have exist
if( m_SenceObjectArray.contains(obj) )
return;
// Found empty Scene object ID
int iSceneID = m_SenceObjectArray.indexOf(NULL);
if( iSceneID == -1 )
{
iSceneID = m_SenceObjectArray.size();
m_SenceObjectArray.add(obj);
}
else
{
m_SenceObjectArray.set(iSceneID, obj);
}
obj->m_iSceneID = iSceneID;
obj->m_iConfigIndex = ConfigIndex;
// create mesh instance and add it to map data struct
CStaticMeshInstance *pStaticModel = new CStaticMeshInstance(m_pRenderDevice);
pStaticModel->changeModel( String(obj->getMF1FileName()), obj->m_iConfigIndex );
pStaticModel->setPosition( obj->m_fPosition[0], obj->m_fPosition[1], obj->m_fPosition[2] );
pStaticModel->setRotationXYZ( obj->m_fRotationXYZ[0], obj->m_fRotationXYZ[1], obj->m_fRotationXYZ[2] );
pStaticModel->setScale( obj->m_fScale );
pStaticModel->setInstanceAlpha( obj->m_fAlpha ); // set Alpha
m_SceneIDToInstanceMap.set(iSceneID, pStaticModel);
// Register object lightmap texture
pStaticModel->registerLightmapTexture( getWorldName(), String(obj->getSceneObjectName())+String(".dds") );
}
bool COpenGLWorldSystemManager::refreshSceneObject( ISGPObject* obj )
{
// Load Static Mesh Resource
CStaticMeshInstance* pStaticModel = m_SceneIDToInstanceMap[obj->getSceneObjectID()];
if( pStaticModel->getMF1ModelResourceID() == 0xFFFFFFFF )
return false;
obj->setTriangleCount( pStaticModel->getMeshTriangleCount() );
obj->setBoundingBox( pStaticModel->getInstanceOBBox() );
// Finding scene object in which terrain chunks
Array<int> TerrainChunkIndex;
const OBBox& ObjBoundingBoxOBB = obj->getBoundingBox();
AABBox ObjBoundingBoxAABB;
ObjBoundingBoxAABB.Construct(&ObjBoundingBoxOBB);
for( int i=0; i<m_pTerrain->m_TerrainChunks.size(); i++ )
{
AABBox chunkAABB = m_pTerrain->m_TerrainChunks[i]->m_BoundingBox;
chunkAABB += Vector3D(chunkAABB.vcMax.x, ObjBoundingBoxAABB.vcMax.y, chunkAABB.vcMax.z);
chunkAABB += Vector3D(chunkAABB.vcMin.x, ObjBoundingBoxAABB.vcMin.y, chunkAABB.vcMin.z);
if( OBBox(&chunkAABB).Intersects(ObjBoundingBoxOBB) )
TerrainChunkIndex.add(i);
}
// delete old data
if( (obj->m_iObjectInChunkIndexNum > 0) && obj->m_pObjectInChunkIndex )
{
delete [] obj->m_pObjectInChunkIndex;
obj->m_pObjectInChunkIndex = NULL;
obj->m_iObjectInChunkIndexNum = 0;
}
// Create new data
obj->m_iObjectInChunkIndexNum = TerrainChunkIndex.size();
if( obj->m_iObjectInChunkIndexNum > 0 )
obj->m_pObjectInChunkIndex = new int32 [obj->m_iObjectInChunkIndexNum];
else
obj->m_pObjectInChunkIndex = NULL;
for( uint32 j=0; j<obj->m_iObjectInChunkIndexNum; j++ )
obj->m_pObjectInChunkIndex[j] = TerrainChunkIndex.getUnchecked(j);
/////////////////////////////////////////////////////////////////////////
// Add obj to terrain chunk
for( uint32 i=0; i<obj->getObjectInChunkNum(); i++ )
{
m_pTerrain->AddSceneObject( obj, obj->getObjectInChunkIndex(i) );
}
return true;
}
void COpenGLWorldSystemManager::deleteSceneObject( ISGPObject* obj )
{
int iSceneID = m_SenceObjectArray.indexOf(obj);
// if not have exist
if( iSceneID == -1 )
return;
else
{
CStaticMeshInstance* pInstance = m_SceneIDToInstanceMap[iSceneID];
pInstance->destroyModel();
delete pInstance;
pInstance = NULL;
m_SceneIDToInstanceMap.remove(iSceneID);
m_SenceObjectArray.set(iSceneID, NULL);
}
}
bool COpenGLWorldSystemManager::flushSceneObject( ISGPObject* pObjArray, uint32 iObjNum, bool bRemove )
{
jassert( m_pTerrain );
bool bAllSceneObjectFlushed = true;
if( bRemove )
{
// delete scene object
for( uint32 i=0; i<iObjNum; i++ )
{
for( uint32 j=0; j<pObjArray[i].getObjectInChunkNum(); j++ )
{
m_pTerrain->RemoveSceneObject( &pObjArray[i], pObjArray[i].getObjectInChunkIndex(j) );
}
}
}
else
{
// add scene object or change scene object position
for( uint32 i=0; i<iObjNum; i++ )
{
if( pObjArray[i].m_bRefreshed )
{
Array<int32> TerrainChunkIndex;
CStaticMeshInstance* pInst = getMeshInstanceBySceneID(pObjArray[i].getSceneObjectID());
Matrix4x4 ModelMatrix;
ModelMatrix.Identity();
ModelMatrix._11 = ModelMatrix._22 = ModelMatrix._33 = pInst->getScale();
Matrix4x4 matTemp;
Quaternion qRotation;
qRotation.MakeFromEuler(pInst->getRotationXYZ().x, pInst->getRotationXYZ().y, pInst->getRotationXYZ().z);
//Convert the quaternion to a rotation matrix
qRotation.GetMatrix(&matTemp);
ModelMatrix = ModelMatrix * matTemp;
ModelMatrix.SetTranslation( pInst->getPosition() );
// Update Instance OOBB boundingbox
OBBox ObjBoundingBoxOBB;
ObjBoundingBoxOBB.DeTransform( pInst->getStaticMeshOBBox(), ModelMatrix );
pObjArray[i].setBoundingBox( ObjBoundingBoxOBB );
AABBox ObjBoundingBoxAABB;
ObjBoundingBoxAABB.Construct(&ObjBoundingBoxOBB);
for( int32 j =0; j<m_pTerrain->m_TerrainChunks.size(); j++ )
{
AABBox chunkAABB = m_pTerrain->m_TerrainChunks[j]->m_BoundingBox;
chunkAABB += Vector3D(chunkAABB.vcMax.x, ObjBoundingBoxAABB.vcMax.y, chunkAABB.vcMax.z);
chunkAABB += Vector3D(chunkAABB.vcMin.x, ObjBoundingBoxAABB.vcMin.y, chunkAABB.vcMin.z);
if( OBBox(&chunkAABB).Intersects(ObjBoundingBoxOBB) )
TerrainChunkIndex.add(j);
}
Array<int32> oldTerrainChunkIndex = Array<int32>(pObjArray[i].m_pObjectInChunkIndex, pObjArray[i].m_iObjectInChunkIndexNum);
Array<int32> oldTerrainChunkIndex1 = oldTerrainChunkIndex;
if( TerrainChunkIndex == oldTerrainChunkIndex )
continue;
// delete old data
if( (pObjArray[i].m_iObjectInChunkIndexNum > 0) && pObjArray[i].m_pObjectInChunkIndex )
{
delete [] pObjArray[i].m_pObjectInChunkIndex;
pObjArray[i].m_pObjectInChunkIndex = NULL;
pObjArray[i].m_iObjectInChunkIndexNum = 0;
}
// Create new data
pObjArray[i].m_iObjectInChunkIndexNum = TerrainChunkIndex.size();
if( pObjArray[i].m_iObjectInChunkIndexNum > 0 )
pObjArray[i].m_pObjectInChunkIndex = new int32 [pObjArray[i].m_iObjectInChunkIndexNum];
else
pObjArray[i].m_pObjectInChunkIndex = NULL;
for( uint32 j=0; j<pObjArray[i].m_iObjectInChunkIndexNum; j++ )
pObjArray[i].m_pObjectInChunkIndex[j] = TerrainChunkIndex.getUnchecked(j);
/////////////////////////////////////////////////////////////////////////
oldTerrainChunkIndex.removeValuesIn(TerrainChunkIndex);
// Remove obj from terrain chunk
for( int k=0; k<oldTerrainChunkIndex.size(); k++ )
{
m_pTerrain->RemoveSceneObject( &pObjArray[i], oldTerrainChunkIndex.getUnchecked(k) );
}
TerrainChunkIndex.removeValuesIn(oldTerrainChunkIndex1);
// Add obj to terrain chunk
for( int k=0; k<TerrainChunkIndex.size(); k++ )
{
m_pTerrain->AddSceneObject( &pObjArray[i], TerrainChunkIndex.getUnchecked(k) );
}
}
else
bAllSceneObjectFlushed = false;
}
}
return bAllSceneObjectFlushed;
}
void COpenGLWorldSystemManager::initializeQuadTree()
{
// First Release QuadTree then Create Quadtree
m_QuadTree.Shutdown();
m_QuadTree.InitializeFromTerrain(m_pTerrain);
}
void COpenGLWorldSystemManager::initializeCollisionSet()
{
m_CollisionTree.release();
if( m_pTerrain )
{
for( uint32 j=0; j<m_pTerrain->GetTerrainChunkSize(); j++ )
for( uint32 i=0; i<m_pTerrain->GetTerrainChunkSize(); i++ )
m_pTerrain->m_TerrainChunks[j * m_pTerrain->GetTerrainChunkSize() + i]->AddTriangleCollisionSet(m_CollisionTree);
}
Array<ISGPObject*> BuildingObjectArray;
getAllSceneBuilding(BuildingObjectArray);
ISGPObject** pEnd = BuildingObjectArray.end();
for( ISGPObject** pBegin = BuildingObjectArray.begin(); pBegin < pEnd; pBegin++ )
{
if( *pBegin )
{
if( !(*pBegin)->m_bCastShadow )
continue;
CStaticMeshInstance *pInstance = m_SceneIDToInstanceMap[(*pBegin)->getSceneObjectID()];
Matrix4x4 modelMatrix = pInstance->getModelMatrix();
CMF1FileResource *pMF1Res = m_pRenderDevice->GetModelManager()->getModelByID(pInstance->getMF1ModelResourceID());
CSGPModelMF1 *pMF1Model = (pMF1Res != NULL) ? pMF1Res->pModelMF1 : NULL;
jassert( pMF1Model );
for( uint32 i=0; i<pMF1Model->m_Header.m_iNumMeshes; i++ )
{
for( uint32 j=0; j<pMF1Model->m_pLOD0Meshes[i].m_iNumIndices; j += 3 )
{
Vector3D v0(
pMF1Model->m_pLOD0Meshes[i].m_pVertex[ pMF1Model->m_pLOD0Meshes[i].m_pIndices[j ] ].vPos[0],
pMF1Model->m_pLOD0Meshes[i].m_pVertex[ pMF1Model->m_pLOD0Meshes[i].m_pIndices[j ] ].vPos[1],
pMF1Model->m_pLOD0Meshes[i].m_pVertex[ pMF1Model->m_pLOD0Meshes[i].m_pIndices[j ] ].vPos[2] );
Vector3D v1(
pMF1Model->m_pLOD0Meshes[i].m_pVertex[ pMF1Model->m_pLOD0Meshes[i].m_pIndices[j+1] ].vPos[0],
pMF1Model->m_pLOD0Meshes[i].m_pVertex[ pMF1Model->m_pLOD0Meshes[i].m_pIndices[j+1] ].vPos[1],
pMF1Model->m_pLOD0Meshes[i].m_pVertex[ pMF1Model->m_pLOD0Meshes[i].m_pIndices[j+1] ].vPos[2] );
Vector3D v2(
pMF1Model->m_pLOD0Meshes[i].m_pVertex[ pMF1Model->m_pLOD0Meshes[i].m_pIndices[j+2] ].vPos[0],
pMF1Model->m_pLOD0Meshes[i].m_pVertex[ pMF1Model->m_pLOD0Meshes[i].m_pIndices[j+2] ].vPos[1],
pMF1Model->m_pLOD0Meshes[i].m_pVertex[ pMF1Model->m_pLOD0Meshes[i].m_pIndices[j+2] ].vPos[2] );
v0 = v0 * modelMatrix;
v1 = v1 * modelMatrix;
v2 = v2 * modelMatrix;
m_CollisionTree.addTriangle(v0, v1, v2, NULL);
m_CollisionTree.addTriangle(v0, v2, v1, NULL);
}
}
}
}
m_pLogger->writeToLog(String("Start building Collision Tree..."), ELL_INFORMATION);
m_CollisionTree.build(3, 1, 50);
m_pLogger->writeToLog(String("Finish building Collision Tree..."), ELL_INFORMATION);
}
float COpenGLWorldSystemManager::getTerrainHeight(float positionX, float positionZ)
{
if( m_pTerrain )
return m_pTerrain->GetTerrainHeight(positionX, positionZ);
return 0;
}
float COpenGLWorldSystemManager::getRealTerrainHeight(float positionX, float positionZ)
{
if( m_pTerrain )
return m_pTerrain->GetRealTerrainHeight(positionX, positionZ);
return 0;
}
Vector3D COpenGLWorldSystemManager::getTerrainNormal(float positionX, float positionZ)
{
if( m_pTerrain )
return m_pTerrain->GetTerrainNormal(positionX, positionZ);
return Vector3D(0,0,0);
}
void COpenGLWorldSystemManager::saveWorldToFile(const String& WorkingDir, const String& WorldMapFileName)
{
strcpy( m_pWorldMap->m_Header.m_cFilename, WorldMapFileName.toUTF8().getAddress() );
// Copy SceneObject data from m_SenceObjectArray in world to m_pWorldMap
m_pWorldMap->m_Header.m_iSceneObjectNum = 0;
for( int i=0; i<getSenceObjectCount(); i++ )
{
ISGPObject* pObj = getSceneObjectBySceneID(i);
if( pObj )
m_pWorldMap->m_Header.m_iSceneObjectNum++;
}
if( m_pWorldMap->m_Header.m_iSceneObjectNum > 0 )
m_pWorldMap->m_pSceneObject = new ISGPObject [m_pWorldMap->m_Header.m_iSceneObjectNum];
int idx = 0;
for( int i=0; i<getSenceObjectCount(); i++ )
{
ISGPObject* pObj = getSceneObjectBySceneID(i);
if( pObj )
m_pWorldMap->m_pSceneObject[idx++].Clone(pObj);
}
// Copy LightObject data from m_LightObjectArray in world to m_pWorldMap
m_pWorldMap->m_Header.m_iLightObjectNum = 0;
for( int i=0; i<m_LightObjectArray.size(); ++i)
{
ISGPLightObject* pLightObj = m_LightObjectArray[i];
if(pLightObj)
m_pWorldMap->m_Header.m_iLightObjectNum++;
}
if( m_pWorldMap->m_Header.m_iLightObjectNum > 0 )
m_pWorldMap->m_pLightObject = new ISGPLightObject [m_pWorldMap->m_Header.m_iLightObjectNum];
idx = 0;
for( int i=0; i<m_LightObjectArray.size(); i++ )
{
ISGPLightObject* pLightObj = m_LightObjectArray[i];
if( pLightObj )
m_pWorldMap->m_pLightObject[idx++].Clone(pLightObj);
}
// HeightMap from terrain
memcpy( m_pWorldMap->m_pTerrainHeightMap, m_pTerrain->GetHeightMap(), sizeof(uint16) * m_pTerrain->GetVertexCount() );
// Normal data from terrain chunk
m_pTerrain->SaveNormalTable(m_pWorldMap->m_pTerrainNormal, m_pWorldMap->m_pTerrainTangent, m_pWorldMap->m_pTerrainBinormal);
// Water data
if( m_pWater && (m_pWater->m_TerrainWaterChunks.size() > 0) )
{
m_pWorldMap->m_WaterSettingData.m_bHaveWater = true;
m_pWorldMap->m_WaterSettingData.m_fWaterHeight = m_pWater->m_fWaterHeight;
strcpy( m_pWorldMap->m_WaterSettingData.m_WaterWaveTextureName, m_pWater->m_WaterWaveTextureName.toUTF8().getAddress() );
// save Water Parameter
m_pWorldMap->m_WaterSettingData.m_vWaterSurfaceColor[0] = m_pWater->m_vWaterSurfaceColor.x;
m_pWorldMap->m_WaterSettingData.m_vWaterSurfaceColor[1] = m_pWater->m_vWaterSurfaceColor.y;
m_pWorldMap->m_WaterSettingData.m_vWaterSurfaceColor[2] = m_pWater->m_vWaterSurfaceColor.z;
m_pWorldMap->m_WaterSettingData.m_fRefractionBumpScale = m_pWater->m_fRefractionBumpScale;
m_pWorldMap->m_WaterSettingData.m_fReflectionBumpScale = m_pWater->m_fReflectionBumpScale;
m_pWorldMap->m_WaterSettingData.m_fFresnelBias = m_pWater->m_fFresnelBias;
m_pWorldMap->m_WaterSettingData.m_fFresnelPow = m_pWater->m_fFresnelPow;
m_pWorldMap->m_WaterSettingData.m_fWaterDepthScale = m_pWater->m_fWaterDepthScale;
m_pWorldMap->m_WaterSettingData.m_fWaterBlendScale = m_pWater->m_fWaterBlendScale;
m_pWorldMap->m_WaterSettingData.m_vWaveDir[0] = m_pWater->m_vWaveDir.x;
m_pWorldMap->m_WaterSettingData.m_vWaveDir[1] = m_pWater->m_vWaveDir.y;
m_pWorldMap->m_WaterSettingData.m_fWaveSpeed = m_pWater->m_fWaveSpeed;
m_pWorldMap->m_WaterSettingData.m_fWaveRate = m_pWater->m_fWaveRate;
m_pWorldMap->m_WaterSettingData.m_fWaterSunSpecularPower = m_pWater->m_fWaterSunSpecularPower;
memset(m_pWorldMap->m_WaterSettingData.m_pWaterChunkIndex, -1, sizeof(int32) * m_pWorldMap->m_Header.m_iChunkNumber);
for( int i=0; i<m_pWater->m_TerrainWaterChunks.size(); i++ )
m_pWorldMap->m_WaterSettingData.m_pWaterChunkIndex[ m_pWater->m_TerrainWaterChunks[i]->GetTerrainChunkIndex() ] = m_pWater->m_TerrainWaterChunks[i]->GetTerrainChunkIndex();
}
else
{
m_pWorldMap->m_WaterSettingData.m_bHaveWater = false;
memset(m_pWorldMap->m_WaterSettingData.m_pWaterChunkIndex, -1, sizeof(int32) * m_pWorldMap->m_Header.m_iChunkNumber);
}
// Grass data
if( m_pGrass )
{
strcpy( m_pWorldMap->m_GrassData.m_GrassTextureName, m_pGrass->GetGrassTextureName().toUTF8().getAddress() );
m_pWorldMap->m_GrassData.m_TextureAtlas[0] = m_pGrass->m_fTextureAtlasNbX;
m_pWorldMap->m_GrassData.m_TextureAtlas[1] = m_pGrass->m_fTextureAtlasNbY;
m_pWorldMap->m_GrassData.m_fGrassFarFadingStart = CSGPWorldConfig::getInstance()->m_fGrassFarFadingStart;
m_pWorldMap->m_GrassData.m_fGrassFarFadingEnd = CSGPWorldConfig::getInstance()->m_fGrassFarFadingEnd;
m_pWorldMap->m_GrassData.m_nChunkGrassClusterNum = m_pTerrain->GetTerrainChunkSize() * m_pTerrain->GetTerrainChunkSize();
// save Grass Parameter
m_pWorldMap->m_GrassData.m_vWindDirectionAndStrength[0] = m_pGrass->m_vWindDirectionAndStrength.x;
m_pWorldMap->m_GrassData.m_vWindDirectionAndStrength[1] = m_pGrass->m_vWindDirectionAndStrength.y;
m_pWorldMap->m_GrassData.m_vWindDirectionAndStrength[2] = m_pGrass->m_vWindDirectionAndStrength.z;
m_pWorldMap->m_GrassData.m_vWindDirectionAndStrength[3] = m_pGrass->m_vWindDirectionAndStrength.w;
m_pWorldMap->m_GrassData.m_fGrassPeriod = m_pGrass->m_fGrassPeriod;
}
// Skydome data
if( m_pSkydome )
{
m_pWorldMap->m_SkydomeData.m_bHaveSkydome = true;
strcpy( m_pWorldMap->m_SkydomeData.m_SkydomeMF1FileName, m_pSkydome->m_MF1FileName.toUTF8().getAddress() );
strcpy( m_pWorldMap->m_SkydomeData.m_CloudTextureFileName, m_pSkydome->m_cloudTextureFileName.toUTF8().getAddress() );
strcpy( m_pWorldMap->m_SkydomeData.m_NoiseTextureFileName, m_pSkydome->m_noiseTextureFileName.toUTF8().getAddress() );
// save Skydome Parameter
m_pWorldMap->m_SkydomeData.m_coludMoveSpeed_x = m_pSkydome->m_coludMoveSpeed_x;
m_pWorldMap->m_SkydomeData.m_coludMoveSpeed_z = m_pSkydome->m_coludMoveSpeed_z;
m_pWorldMap->m_SkydomeData.m_coludNoiseScale = m_pSkydome->m_coludNoiseScale;
m_pWorldMap->m_SkydomeData.m_coludBrightness = m_pSkydome->m_coludBrightness;
m_pWorldMap->m_SkydomeData.m_scale = m_pSkydome->GetScale();
// save Skydome atmosphere Parameter
CSGPHoffmanPreethemScatter& scatter = m_pSkydome->GetScatter();
m_pWorldMap->m_SkydomeData.m_fHGgFunction = scatter.m_fHGgFunction;
m_pWorldMap->m_SkydomeData.m_fInscatteringMultiplier = scatter.m_fInscatteringMultiplier;
m_pWorldMap->m_SkydomeData.m_fBetaRayMultiplier = scatter.m_fBetaRayMultiplier;
m_pWorldMap->m_SkydomeData.m_fBetaMieMultiplier = scatter.m_fBetaMieMultiplier;
m_pWorldMap->m_SkydomeData.m_fSunIntensity = scatter.m_fSunIntensity;
m_pWorldMap->m_SkydomeData.m_fTurbitity = scatter.m_fTurbitity;
if( m_pWorldSun )
m_pWorldMap->m_SkydomeData.m_fSunPosition = m_pWorldSun->m_fSunPosition;
}
else
m_pWorldMap->m_SkydomeData.m_bHaveSkydome = false;
// set CSGPWorldConfig Parameter
m_pWorldMap->m_WorldConfigTag.m_bUsingQuadTree = CSGPWorldConfig::getInstance()->m_bUsingQuadTree;
m_pWorldMap->m_WorldConfigTag.m_bVisibleCull = CSGPWorldConfig::getInstance()->m_bVisibleCull;
m_pWorldMap->m_WorldConfigTag.m_bUsingTerrainLOD = CSGPWorldConfig::getInstance()->m_bUsingTerrainLOD;
m_pWorldMap->m_WorldConfigTag.m_bPostFog = CSGPWorldConfig::getInstance()->m_bPostFog;
m_pWorldMap->m_WorldConfigTag.m_bDOF = CSGPWorldConfig::getInstance()->m_bDOF;
m_pWorldMap->SaveWorldMap( WorkingDir, WorldMapFileName );
// release allocated Object and LightObject memory
if( m_pWorldMap->m_Header.m_iSceneObjectNum > 0 )
{
if( m_pWorldMap->m_pSceneObject!=NULL )
{
delete [] m_pWorldMap->m_pSceneObject;
m_pWorldMap->m_pSceneObject = NULL;
}
}
if( m_pWorldMap->m_Header.m_iLightObjectNum > 0 )
{
if( m_pWorldMap->m_pLightObject!=NULL )
{
delete [] m_pWorldMap->m_pLightObject;
m_pWorldMap->m_pLightObject = NULL;
}
}
}
void COpenGLWorldSystemManager::loadWorldFromFile(const String& WorkingDir, const String& WorldMapFileName, bool bLoadObjs)
{
m_pWorldMapRawMemoryAddress = CSGPWorldMap::LoadWorldMap(m_pWorldMap, WorkingDir, WorldMapFileName);
setWorldName( File::getCurrentWorkingDirectory().getChildFile(String(m_pWorldMap->m_Header.m_cFilename)).getFileNameWithoutExtension() );
// World Sun
createWorldSun();
// Skydome
if( m_pWorldMap->m_SkydomeData.m_bHaveSkydome )
{
createSkydome( String(m_pWorldMap->m_SkydomeData.m_SkydomeMF1FileName) );
setSkydomeTexture( String(m_pWorldMap->m_SkydomeData.m_CloudTextureFileName), String(m_pWorldMap->m_SkydomeData.m_NoiseTextureFileName) );
// set Skydome Parameter
m_pSkydome->m_coludMoveSpeed_x = m_pWorldMap->m_SkydomeData.m_coludMoveSpeed_x;
m_pSkydome->m_coludMoveSpeed_z = m_pWorldMap->m_SkydomeData.m_coludMoveSpeed_z;
m_pSkydome->m_coludNoiseScale = m_pWorldMap->m_SkydomeData.m_coludNoiseScale;
m_pSkydome->m_coludBrightness = m_pWorldMap->m_SkydomeData.m_coludBrightness;
m_pSkydome->SetScale(m_pWorldMap->m_SkydomeData.m_scale);
// set Skydome atmosphere Parameter
CSGPHoffmanPreethemScatter& scatter = m_pSkydome->GetScatter();
scatter.m_fHGgFunction = m_pWorldMap->m_SkydomeData.m_fHGgFunction;
scatter.m_fInscatteringMultiplier = m_pWorldMap->m_SkydomeData.m_fInscatteringMultiplier;
scatter.m_fBetaRayMultiplier = m_pWorldMap->m_SkydomeData.m_fBetaRayMultiplier;
scatter.m_fBetaMieMultiplier = m_pWorldMap->m_SkydomeData.m_fBetaMieMultiplier;
scatter.m_fSunIntensity = m_pWorldMap->m_SkydomeData.m_fSunIntensity;
scatter.m_fTurbitity = m_pWorldMap->m_SkydomeData.m_fTurbitity;
scatter.calculateScatteringConstants();
setWorldSunPosition(m_pWorldMap->m_SkydomeData.m_fSunPosition);
}
// Load terrain data and OpenGL Resource
m_pTerrain = new CSGPTerrain();
// Load height map
m_pTerrain->LoadCreateHeightmap( static_cast<SGP_TERRAIN_SIZE>(m_pWorldMap->m_Header.m_iTerrainSize), m_pWorldMap->m_pTerrainHeightMap, m_pWorldMap->m_Header.m_iTerrainMaxHeight );
m_pTerrain->CreateLODHeights();
m_pTerrain->UpdateBoundingBox();
// Load normal
m_pTerrain->LoadCreateNormalTable(m_pWorldMap->m_pTerrainNormal, m_pWorldMap->m_pTerrainTangent, m_pWorldMap->m_pTerrainBinormal);
// Create VB/IB render resource for Terrain
initializeTerrainRenderer(true);
// Create Scene Object Array in World
if( bLoadObjs )
{
for( uint32 i=0; i<m_pWorldMap->m_Header.m_iSceneObjectNum; i++ )
{
ISGPObject* pObj = &(m_pWorldMap->m_pSceneObject[i]);
if( pObj->getSceneObjectID() == (uint32)m_SenceObjectArray.size() )
{
m_SenceObjectArray.add(pObj);
continue;
}
while( pObj->getSceneObjectID() != (uint32)m_SenceObjectArray.size() )
{
m_SenceObjectArray.add(NULL);
}
m_SenceObjectArray.add(pObj);
}
ISGPObject** pEnd = m_SenceObjectArray.end();
for( ISGPObject** pBegin = m_SenceObjectArray.begin(); pBegin < pEnd; pBegin++ )
{
ISGPObject* obj = (*pBegin);
if( !obj )
continue;
// create mesh instance and add it to map data struct
CStaticMeshInstance *pStaticModel = new CStaticMeshInstance(m_pRenderDevice);
pStaticModel->changeModel( String(obj->getMF1FileName()), obj->m_iConfigIndex );
pStaticModel->setPosition( obj->m_fPosition[0], obj->m_fPosition[1], obj->m_fPosition[2] );
pStaticModel->setRotationXYZ( obj->m_fRotationXYZ[0], obj->m_fRotationXYZ[1], obj->m_fRotationXYZ[2] );
pStaticModel->setScale( obj->m_fScale );
pStaticModel->setInstanceAlpha( obj->m_fAlpha );
m_SceneIDToInstanceMap.set(obj->getSceneObjectID(), pStaticModel);
// add to terrain chunk
for( uint32 i=0; i<obj->getObjectInChunkNum(); i++ )
{
m_pTerrain->AddSceneObject( obj, obj->getObjectInChunkIndex(i) );
}
// Register object lightmap texture
pStaticModel->registerLightmapTexture( getWorldName(), String(obj->getSceneObjectName())+String(".dds") );
}
}
// Create water for World
if( m_pWorldMap->m_WaterSettingData.m_bHaveWater )
{
createWater( m_pWorldMap->m_WaterSettingData.m_fWaterHeight, String(m_pWorldMap->m_WaterSettingData.m_WaterWaveTextureName) );
// set Water Parameter
m_pWater->m_vWaterSurfaceColor.x = m_pWorldMap->m_WaterSettingData.m_vWaterSurfaceColor[0];
m_pWater->m_vWaterSurfaceColor.y = m_pWorldMap->m_WaterSettingData.m_vWaterSurfaceColor[1];
m_pWater->m_vWaterSurfaceColor.z = m_pWorldMap->m_WaterSettingData.m_vWaterSurfaceColor[2];
m_pWater->m_fRefractionBumpScale = m_pWorldMap->m_WaterSettingData.m_fRefractionBumpScale;
m_pWater->m_fReflectionBumpScale = m_pWorldMap->m_WaterSettingData.m_fReflectionBumpScale;
m_pWater->m_fFresnelBias = m_pWorldMap->m_WaterSettingData.m_fFresnelBias;
m_pWater->m_fFresnelPow = m_pWorldMap->m_WaterSettingData.m_fFresnelPow;
m_pWater->m_fWaterDepthScale = m_pWorldMap->m_WaterSettingData.m_fWaterDepthScale;
m_pWater->m_fWaterBlendScale = m_pWorldMap->m_WaterSettingData.m_fWaterBlendScale;
m_pWater->m_vWaveDir.x = m_pWorldMap->m_WaterSettingData.m_vWaveDir[0];
m_pWater->m_vWaveDir.y = m_pWorldMap->m_WaterSettingData.m_vWaveDir[1];
m_pWater->m_fWaveSpeed = m_pWorldMap->m_WaterSettingData.m_fWaveSpeed;
m_pWater->m_fWaveRate = m_pWorldMap->m_WaterSettingData.m_fWaveRate;
m_pWater->m_fWaterSunSpecularPower = m_pWorldMap->m_WaterSettingData.m_fWaterSunSpecularPower;
for( uint32 i=0; i<m_pWorldMap->m_Header.m_iChunkNumber; i++ )
{
if( m_pWorldMap->m_WaterSettingData.m_pWaterChunkIndex[i] != -1 )
addWaterChunk( m_pWorldMap->m_WaterSettingData.m_pWaterChunkIndex[i] );
}
}
// recreate Frame Buffer Object
m_pRenderDevice->recreateRenderToFrameBuffer(m_pRenderDevice->getViewPort().Width, m_pRenderDevice->getViewPort().Height, false);
// Create grass for World
if( m_pWorldMap->m_GrassData.m_nChunkGrassClusterNum > 0 )
{
createGrass( String(m_pWorldMap->m_GrassData.m_GrassTextureName), m_pWorldMap->m_GrassData.m_TextureAtlas[0], m_pWorldMap->m_GrassData.m_TextureAtlas[1] );
// set Grass Parameter
m_pGrass->m_vWindDirectionAndStrength.x = m_pWorldMap->m_GrassData.m_vWindDirectionAndStrength[0];
m_pGrass->m_vWindDirectionAndStrength.y = m_pWorldMap->m_GrassData.m_vWindDirectionAndStrength[1];
m_pGrass->m_vWindDirectionAndStrength.z = m_pWorldMap->m_GrassData.m_vWindDirectionAndStrength[2];
m_pGrass->m_vWindDirectionAndStrength.w = m_pWorldMap->m_GrassData.m_vWindDirectionAndStrength[3];
m_pGrass->m_fGrassPeriod = m_pWorldMap->m_GrassData.m_fGrassPeriod;
CSGPWorldConfig::getInstance()->m_fGrassFarFadingStart = m_pWorldMap->m_GrassData.m_fGrassFarFadingStart;
CSGPWorldConfig::getInstance()->m_fGrassFarFadingEnd = m_pWorldMap->m_GrassData.m_fGrassFarFadingEnd;
for( uint32 i=0; i<m_pWorldMap->m_GrassData.m_nChunkGrassClusterNum; i++ )
{
if( m_pWorldMap->m_GrassData.m_ppChunkGrassCluster[i] == NULL )
continue;
CSGPTerrainChunk* pGrassTerrainChunk = m_pTerrain->m_TerrainChunks[ m_pWorldMap->m_GrassData.m_ppChunkGrassCluster[i]->m_nChunkIndex ];
m_pGrass->m_TerrainGrassChunks.add( pGrassTerrainChunk );
pGrassTerrainChunk->SetChunkGrassCluster(
m_pWorldMap->m_GrassData.m_ppChunkGrassCluster[i]->m_GrassLayerData,
SGPTT_TILENUM * SGPTGD_GRASS_DIMISION * SGPTT_TILENUM * SGPTGD_GRASS_DIMISION );
}
}
// set CSGPWorldConfig Parameter
CSGPWorldConfig::getInstance()->m_bUsingQuadTree = m_pWorldMap->m_WorldConfigTag.m_bUsingQuadTree;
CSGPWorldConfig::getInstance()->m_bVisibleCull = m_pWorldMap->m_WorldConfigTag.m_bVisibleCull;
CSGPWorldConfig::getInstance()->m_bUsingTerrainLOD = m_pWorldMap->m_WorldConfigTag.m_bUsingTerrainLOD;
CSGPWorldConfig::getInstance()->m_bPostFog = m_pWorldMap->m_WorldConfigTag.m_bPostFog;
CSGPWorldConfig::getInstance()->m_bDOF = m_pWorldMap->m_WorldConfigTag.m_bDOF;
}
void COpenGLWorldSystemManager::loadObjectToWorldForEditor(ISGPObject* pObjArray, uint32 count)
{
for( uint32 i=0; i<count; i++)
{
ISGPObject* pObj = &(pObjArray[i]);
if( pObj->getSceneObjectID() == (uint32)m_SenceObjectArray.size() )
{
m_SenceObjectArray.add(pObj);
continue;
}
while( pObj->getSceneObjectID() != (uint32)m_SenceObjectArray.size() )
{
m_SenceObjectArray.add(NULL);
}
m_SenceObjectArray.add(pObj);
}
for( uint32 i=0; i<count ;i++ )
{
ISGPObject* obj = &(pObjArray[i]);
// create mesh instance and add it to map data struct
CStaticMeshInstance *pStaticModel = new CStaticMeshInstance(m_pRenderDevice);
pStaticModel->changeModel( String(obj->getMF1FileName()), obj->m_iConfigIndex );
pStaticModel->setPosition( obj->m_fPosition[0], obj->m_fPosition[1], obj->m_fPosition[2] );
pStaticModel->setRotationXYZ( obj->m_fRotationXYZ[0], obj->m_fRotationXYZ[1], obj->m_fRotationXYZ[2] );
pStaticModel->setScale( obj->m_fScale );
pStaticModel->setInstanceAlpha(obj->m_fAlpha); // set Alpha
m_SceneIDToInstanceMap.set(obj->getSceneObjectID(), pStaticModel);
// add to terrain chunk
for( uint32 i=0; i<obj->getObjectInChunkNum(); i++ )
{
m_pTerrain->AddSceneObject( obj, obj->getObjectInChunkIndex(i) );
}
// Register object lightmap texture
pStaticModel->registerLightmapTexture( getWorldName(), String(obj->getSceneObjectName())+String(".dds") );
}
}
void COpenGLWorldSystemManager::updateWorld(float fDeltaTimeInSecond)
{
// update all scene object firstly
ISGPObject** pEnd = m_SenceObjectArray.end();
for( ISGPObject** pBegin = m_SenceObjectArray.begin(); pBegin < pEnd; pBegin++ )
{
if( *pBegin )
{
m_SceneIDToInstanceMap[(*pBegin)->getSceneObjectID()]->setVisible(false);
m_SceneIDToInstanceMap[(*pBegin)->getSceneObjectID()]->update(fDeltaTimeInSecond);
}
// unloaded scene object need be Refreshed
if( (*pBegin) && !(*pBegin)->m_bRefreshed )
(*pBegin)->m_bRefreshed = refreshSceneObject( *pBegin );
}
// update Camera View Frustum
Frustum ViewFrustum;
ViewFrustum.setFrom( m_pRenderDevice->getOpenGLCamera()->m_mViewProjMatrix );
// QUADTREE Cull and get visible terrain chunks
m_VisibleChunkArray.clearQuick();
m_QuadTree.GetVisibleTerrainChunk(m_QuadTree.GetRootNode(), ViewFrustum, m_VisibleChunkArray);
// Update water
m_pRenderDevice->getOpenGLWaterRenderer()->update(fDeltaTimeInSecond, m_pWater);
// update water mirrored visible terrain chunks
if( needRenderWater() )
{
Frustum MirroredViewFrustum;
MirroredViewFrustum.setFrom( m_pRenderDevice->getOpenGLWaterRenderer()->m_MirrorViewMatrix * m_pRenderDevice->getOpenGLCamera()->m_mProjMatrix );
m_WaterMirrorVisibleChunkArray.clearQuick();
m_QuadTree.GetVisibleTerrainChunk(m_QuadTree.GetRootNode(), MirroredViewFrustum, m_WaterMirrorVisibleChunkArray);
// Appends mirrored view seeing terrain chunk at the end of m_VisibleChunkArray as long as the new terrain chunk doesn't already contain it
CSGPTerrainChunk** pEnd = m_WaterMirrorVisibleChunkArray.end();
for( CSGPTerrainChunk** pBegin = m_WaterMirrorVisibleChunkArray.begin(); pBegin < pEnd; pBegin++ )
{
m_VisibleChunkArray.addIfNotAlreadyThere( *pBegin );
}
}
// Update every Visible terrain chunk
if( m_VisibleChunkArray.size() > 0 )
{
CSGPTerrainChunk** pEnd = m_VisibleChunkArray.end();
for( CSGPTerrainChunk** pBegin = m_VisibleChunkArray.begin(); pBegin < pEnd; pBegin++ )
{
m_pRenderDevice->getOpenGLTerrainRenderer()->updateChunkLODInfo( (*pBegin)->GetTerrainChunkIndex(), (*pBegin)->GetChunkCenter() );
}
}
// Update Sky dome
Vector4D CamPos;
m_pRenderDevice->getCamreaPosition( &CamPos );
m_pRenderDevice->getOpenGLSkydomeRenderer()->update(fDeltaTimeInSecond, m_pSkydome, CamPos);
// Update Grass
m_pRenderDevice->getOpenGLGrassRenderer()->update(fDeltaTimeInSecond, CamPos, ViewFrustum, m_pGrass);
// get all visible Scene Object and update
m_VisibleSceneObjectArray.clearQuick();
getVisibleSceneObjectArray(ViewFrustum, m_VisibleChunkArray, m_VisibleSceneObjectArray);
ISGPObject** pVisibleObjEnd = m_VisibleSceneObjectArray.end();
for( ISGPObject** pVisibleObjBegin = m_VisibleSceneObjectArray.begin(); pVisibleObjBegin < pVisibleObjEnd; pVisibleObjBegin++ )
{
m_SceneIDToInstanceMap[(*pVisibleObjBegin)->getSceneObjectID()]->setVisible(true);
m_SceneIDToInstanceMap[(*pVisibleObjBegin)->getSceneObjectID()]->update(fDeltaTimeInSecond);
}
}
void COpenGLWorldSystemManager::shutdownWorld()
{
m_QuadTree.Shutdown();
releaseTerrainRenderer();
releaseSkydome();
m_pRenderDevice->getOpenGLWaterRenderer()->releaseWaterWaveTexture();
m_pRenderDevice->getOpenGLGrassRenderer()->releaseGrassTexture();
HashMap<uint32, CStaticMeshInstance*>::Iterator i (m_SceneIDToInstanceMap);
while( i.next() )
{
CStaticMeshInstance* pInstance = i.getValue();
pInstance->destroyModel();
delete pInstance;
pInstance = NULL;
}
m_SceneIDToInstanceMap.clear();
m_SenceObjectArray.clear();
m_LightObjectArray.clear();
if( m_pTerrain )
delete m_pTerrain;
m_pTerrain = NULL;
if( m_pSkydome )
delete m_pSkydome;
m_pSkydome = NULL;
if( m_pWorldSun )
delete m_pWorldSun;
m_pWorldSun = NULL;
if( m_pWater )
delete m_pWater;
m_pWater = NULL;
if( m_pGrass )
delete m_pGrass;
m_pGrass = NULL;
if( m_pWorldMapRawMemoryAddress )
delete [] m_pWorldMapRawMemoryAddress;
m_pWorldMapRawMemoryAddress = NULL;
}
void COpenGLWorldSystemManager::renderWorld()
{
// Render Terrain Chunks
if( m_VisibleChunkArray.size() > 0 )
{
CSGPTerrainChunk** pEnd = m_VisibleChunkArray.end();
for( CSGPTerrainChunk** pBegin = m_VisibleChunkArray.begin(); pBegin < pEnd; pBegin++ )
{
m_pRenderDevice->getOpenGLTerrainRenderer()->renderTerrainChunk( (*pBegin)->GetTerrainChunkIndex() );
}
}
// Render Skydome
if( m_pSkydome )
m_pRenderDevice->getOpenGLSkydomeRenderer()->render( m_pSkydome );
// Render Grass
if( m_pGrass )
m_pRenderDevice->getOpenGLGrassRenderer()->render( m_pGrass );
// Render Water
if( m_pWater && needRenderWater() )
m_pRenderDevice->getOpenGLWaterRenderer()->render( m_pWater );
// Render Scene object
if( m_VisibleSceneObjectArray.size() > 0 )
{
ISGPObject** pEnd = m_VisibleSceneObjectArray.end();
for( ISGPObject** pBegin = m_VisibleSceneObjectArray.begin(); pBegin < pEnd; pBegin++ )
{
m_SceneIDToInstanceMap[(*pBegin)->getSceneObjectID()]->render();
}
}
}
void COpenGLWorldSystemManager::createWater( float fWaterHeight, const String& WaterWaveTextureName )
{
CSGPWorldConfig::getInstance()->m_bHavingWaterInWorld = true;
CSGPWorldConfig::getInstance()->m_bPostFog = true;
m_pWater = new CSGPWater(fWaterHeight);
m_pWater->m_WaterWaveTextureName = WaterWaveTextureName;
m_pRenderDevice->getOpenGLWaterRenderer()->createWaterWaveTexture( WaterWaveTextureName );
}
void COpenGLWorldSystemManager::addWaterChunk( int32 terrainChunkIndex )
{
if( m_pWater && m_pTerrain )
{
if( terrainChunkIndex < m_pTerrain->m_TerrainChunks.size() )
{
// Update chunk AABBox when terrain chunk having water
if( m_pWater->m_fWaterHeight > m_pTerrain->m_TerrainChunks[terrainChunkIndex]->m_BoundingBox.vcMax.y )
{
m_pTerrain->m_TerrainChunks[terrainChunkIndex]->m_BoundingBox +=
Vector3D( m_pTerrain->m_TerrainChunks[terrainChunkIndex]->m_BoundingBox.vcMax.x,
m_pWater->m_fWaterHeight,
m_pTerrain->m_TerrainChunks[terrainChunkIndex]->m_BoundingBox.vcMax.z );
}
// if WaterHeight below terrain chunk's whole boundingbox, skip this chunk
if( m_pWater->m_fWaterHeight >= m_pTerrain->m_TerrainChunks[terrainChunkIndex]->m_BoundingBox.vcMin.y )
m_pWater->m_TerrainWaterChunks.add( m_pTerrain->m_TerrainChunks[terrainChunkIndex] );
}
}
}
bool COpenGLWorldSystemManager::needRenderWater()
{
return m_pRenderDevice->getOpenGLWaterRenderer()->needRenderWater();
}
bool COpenGLWorldSystemManager::isTerrainChunkVisible(CSGPTerrainChunk* pChunk)
{
return m_VisibleChunkArray.contains( pChunk );
}
void COpenGLWorldSystemManager::createGrass(const String& grassTextureName, uint16 TexAtlasX, uint16 TexAtlasY)
{
m_pGrass = new CSGPGrass();
m_pGrass->SetGrassTextureName( grassTextureName );
m_pGrass->SetAtlasDimensions(TexAtlasX, TexAtlasY);
m_pRenderDevice->getOpenGLGrassRenderer()->initializeFromGrass(m_pGrass);
}
void COpenGLWorldSystemManager::setGrassCluster(float fPosX, float fPosZ, const SGPGrassCluster& ClusterData)
{
if( m_pTerrain && m_pGrass )
{
uint32 nChunkIndex = m_pTerrain->GetChunkIndex(fPosX, fPosZ);
if( nChunkIndex != 0xFFFFFFFF )
{
if( m_pGrass->m_TerrainGrassChunks.contains(m_pTerrain->m_TerrainChunks[nChunkIndex]) )
m_pTerrain->SetTerrainGrassLayerData(fPosX, fPosZ, ClusterData);
else
{
SGPWorldMapGrassTag::SGPWorldMapChunkGrassClusterTag* pNewGrassClusterData = new SGPWorldMapGrassTag::SGPWorldMapChunkGrassClusterTag();
memset(pNewGrassClusterData, 0, sizeof(SGPWorldMapGrassTag::SGPWorldMapChunkGrassClusterTag));
pNewGrassClusterData->m_nChunkIndex = nChunkIndex;
m_pWorldMap->m_GrassData.m_ppChunkGrassCluster[nChunkIndex] = pNewGrassClusterData;
m_pGrass->m_TerrainGrassChunks.add( m_pTerrain->m_TerrainChunks[nChunkIndex] );
m_pTerrain->m_TerrainChunks[nChunkIndex]->SetChunkGrassCluster(pNewGrassClusterData->m_GrassLayerData, SGPTT_TILENUM * SGPTGD_GRASS_DIMISION * SGPTT_TILENUM * SGPTGD_GRASS_DIMISION);
setGrassCluster(fPosX, fPosZ, ClusterData);
}
}
}
}
void COpenGLWorldSystemManager::getAllSceneBuilding(Array<ISGPObject*>& BuildingObjectArray)
{
ISGPObject** pEnd = m_SenceObjectArray.end();
for( ISGPObject** pBegin = m_SenceObjectArray.begin(); pBegin < pEnd; pBegin++ )
{
if( *pBegin && (*pBegin)->getSceneObjectType() == SGPOT_Building )
BuildingObjectArray.add( (*pBegin) );
}
}
ISGPObject* COpenGLWorldSystemManager::getSceneObjectByName(const char* pSceneObjectNameStr)
{
ISGPObject** pEnd = m_SenceObjectArray.end();
for( ISGPObject** pBegin = m_SenceObjectArray.begin(); pBegin < pEnd; pBegin++ )
{
if( *pBegin && (strcmp( (*pBegin)->m_SceneObjectName, pSceneObjectNameStr ) == 0) )
return *pBegin;
}
return NULL;
}
void COpenGLWorldSystemManager::getAllSceneObjectByName(const char* pSceneObjectNameStr, Array<ISGPObject*>& SceneObjectArray)
{
ISGPObject** pEnd = m_SenceObjectArray.end();
for( ISGPObject** pBegin = m_SenceObjectArray.begin(); pBegin < pEnd; pBegin++ )
{
if( *pBegin && (strcmp( (*pBegin)->m_SceneObjectName, pSceneObjectNameStr ) == 0) )
SceneObjectArray.add( *pBegin );
}
}
ISGPObject* COpenGLWorldSystemManager::getSceneObjectBySceneID( uint32 nSceneObjectID )
{
return m_SenceObjectArray[nSceneObjectID];
}
CStaticMeshInstance* COpenGLWorldSystemManager::getMeshInstanceBySceneID( uint32 nSceneObjectID )
{
return m_SceneIDToInstanceMap[nSceneObjectID];
}
//==============================================================================
// Editor Interface Function
//==============================================================================
bool COpenGLWorldSystemManager::setHeightMap(uint32 index_x, uint32 index_z, uint16 iHeight)
{
jassert( m_pTerrain );
if( index_x > m_pTerrain->GetTerrainChunkSize()*SGPTT_TILENUM )
return false;
if( index_z > m_pTerrain->GetTerrainChunkSize()*SGPTT_TILENUM )
return false;
uint32 heightmap_index = index_z * (m_pTerrain->GetTerrainChunkSize()*SGPTT_TILENUM+1) + index_x;
if( m_pTerrain->GetHeightMap()[heightmap_index] == iHeight )
return false;
m_pTerrain->SetHeightMap(heightmap_index, iHeight);
if( iHeight > m_pTerrain->GetTerrainMaxHeight() )
m_pTerrain->SetTerrainMaxHeight(iHeight);
return true;
}
void COpenGLWorldSystemManager::flushTerrainHeight(uint32* pChunkIndex, uint32 ichunkNum)
{
jassert( m_pTerrain );
for( uint32 i=0; i<ichunkNum; i++ )
m_pTerrain->m_TerrainChunks[pChunkIndex[i]]->FlushTerrainChunkHeight();
for( uint32 i=0; i<ichunkNum; i++ )
{
// Terrain VBO update
m_pRenderDevice->getOpenGLTerrainRenderer()->flushChunkVBO( pChunkIndex[i] );
CSGPTerrainChunk* pTerrainChunk = m_pTerrain->m_TerrainChunks[pChunkIndex[i]];
// water update
if( m_pWater && m_pWater->m_TerrainWaterChunks.contains( pTerrainChunk ) )
{
if( m_pWater->m_fWaterHeight > pTerrainChunk->m_BoundingBox.vcMax.y )
{
pTerrainChunk->m_BoundingBox +=
Vector3D( pTerrainChunk->m_BoundingBox.vcMax.x,
m_pWater->m_fWaterHeight,
pTerrainChunk->m_BoundingBox.vcMax.z );
}
}
// grass update
for( uint32 j=0; j<pTerrainChunk->GetGrassClusterDataCount(); j++ )
{
const SGPGrassCluster& GrassData = pTerrainChunk->GetGrassClusterData()[j];
if( GrassData.nData == 0 )
continue;
SGPGrassCluster newGrassData = GrassData;
newGrassData.fPositionY = getRealTerrainHeight(newGrassData.fPositionX, newGrassData.fPositionZ);
Vector3D terrainNorm = m_pTerrain->GetTerrainNormal(newGrassData.fPositionX, newGrassData.fPositionZ);
newGrassData.nPackedNormal = (uint32((terrainNorm.x * 0.5f + 0.5f) * 255) << 24) +
(uint32((terrainNorm.y * 0.5f + 0.5f) * 255) << 16) +
(uint32((terrainNorm.z * 0.5f + 0.5f) * 255) << 8);
m_pTerrain->SetTerrainGrassLayerData(GrassData.fPositionX, GrassData.fPositionZ, newGrassData);
}
}
}
void COpenGLWorldSystemManager::flushTerrainNormal(uint32* pChunkIndex, uint32 ichunkNum)
{
if( !pChunkIndex || (ichunkNum <= 0) )
return;
// normal update
m_pTerrain->CreateNormalTable();
for( uint32 i=0; i<ichunkNum; i++ )
{
// Terrain VBO update
m_pRenderDevice->getOpenGLTerrainRenderer()->flushChunkVBO( pChunkIndex[i] );
// grass normal update
for( uint32 j=0; j<m_pTerrain->m_TerrainChunks[i]->GetGrassClusterDataCount(); j++ )
{
const SGPGrassCluster& GrassData = m_pTerrain->m_TerrainChunks[i]->GetGrassClusterData()[j];
if( GrassData.nData == 0 )
continue;
SGPGrassCluster newGrassData = GrassData;
Vector3D terrainNorm = m_pTerrain->GetTerrainNormal(newGrassData.fPositionX, newGrassData.fPositionZ);
newGrassData.nPackedNormal = (uint32((terrainNorm.x * 0.5f + 0.5f) * 255) << 24) +
(uint32((terrainNorm.y * 0.5f + 0.5f) * 255) << 16) +
(uint32((terrainNorm.z * 0.5f + 0.5f) * 255) << 8);
m_pTerrain->SetTerrainGrassLayerData(GrassData.fPositionX, GrassData.fPositionZ, newGrassData);
}
}
}
void COpenGLWorldSystemManager::createNewWorld(CSGPWorldMap* &pWorldMap, const char* WorldName, SGP_TERRAIN_SIZE terrainsize, bool bUsePerlinNoise, uint16 maxTerrainHeight, const String& Diffuse0TextureName)
{
setWorldName( String(WorldName) );
m_pWorldMap = pWorldMap;
// HEADER
m_pWorldMap->m_Header.m_iTerrainSize = terrainsize;
m_pWorldMap->m_Header.m_iTerrainMaxHeight = maxTerrainHeight;
m_pWorldMap->m_Header.m_iChunkTextureNameNum = 1;
m_pWorldMap->m_Header.m_iChunkNumber = terrainsize * terrainsize;
m_pWorldMap->m_Header.m_iSceneObjectNum = 0;
m_pWorldMap->m_Header.m_iLightObjectNum = 0;
m_pWorldMap->m_Header.m_iChunkColorminiMapSize = terrainsize * SGPTT_TILENUM;
m_pWorldMap->m_Header.m_iChunkAlphaTextureSize = terrainsize * SGPTT_TILENUM * SGPTBD_BLENDTEXTURE_DIMISION;
m_pWorldMap->m_Header.m_iHeightMapOffset = 0;
m_pWorldMap->m_Header.m_iChunkTextureNameOffset = 0;
m_pWorldMap->m_Header.m_iChunkTextureIndexOffset = 0;
m_pWorldMap->m_Header.m_iChunkColorminiMapTextureOffset = 0;
m_pWorldMap->m_Header.m_iChunkAlphaTextureOffset = 0;
m_pWorldMap->m_Header.m_iSceneObjectOffset = 0;
m_pWorldMap->m_Header.m_iLightObjectOffset = 0;
m_pWorldMap->m_Header.m_iHeaderSize = sizeof(SGPWorldMapHeader);
// WATER DATA
m_pWorldMap->m_WaterSettingData.m_bHaveWater = false;
m_pWorldMap->m_WaterSettingData.m_pWaterChunkIndex = new int32 [terrainsize * terrainsize];
memset(m_pWorldMap->m_WaterSettingData.m_pWaterChunkIndex, -1, sizeof(int32) * terrainsize * terrainsize);
// GRASS DATA
m_pWorldMap->m_GrassData.m_nChunkGrassClusterNum = 0;
m_pWorldMap->m_GrassData.m_ppChunkGrassCluster = new SGPWorldMapGrassTag::SGPWorldMapChunkGrassClusterTag* [terrainsize * terrainsize];
memset(m_pWorldMap->m_GrassData.m_ppChunkGrassCluster, 0, sizeof(SGPWorldMapGrassTag::SGPWorldMapChunkGrassClusterTag*) * terrainsize * terrainsize);
// CHUNK TEXTURE
m_pWorldMap->m_pChunkTextureNames = new SGPWorldMapChunkTextureNameTag [m_pWorldMap->m_Header.m_iChunkTextureNameNum];
strcpy( m_pWorldMap->m_pChunkTextureNames[0].m_ChunkTextureFileName, Diffuse0TextureName.toUTF8().getAddress() );
m_pWorldMap->m_pChunkTextureIndex = new SGPWorldMapChunkTextureIndexTag [m_pWorldMap->m_Header.m_iChunkNumber];
for( uint32 i=0; i<m_pWorldMap->m_Header.m_iChunkNumber; i++ )
{
m_pWorldMap->m_pChunkTextureIndex[i].m_ChunkTextureIndex[eChunk_Diffuse0Texture] = 0;
}
// Raw DATA
m_pWorldMap->m_pTerrainHeightMap = new uint16 [(terrainsize*SGPTT_TILENUM + 1) * (terrainsize*SGPTT_TILENUM + 1)];
memset(m_pWorldMap->m_pTerrainHeightMap, 0, sizeof(uint16) * (terrainsize*SGPTT_TILENUM + 1) * (terrainsize*SGPTT_TILENUM + 1));
m_pWorldMap->m_pTerrainNormal = new float [(terrainsize * SGPTT_TILENUM + 1) * (terrainsize * SGPTT_TILENUM + 1) * 3];
memset(m_pWorldMap->m_pTerrainNormal, 0, sizeof(float) * (terrainsize*SGPTT_TILENUM + 1) * (terrainsize*SGPTT_TILENUM + 1) * 3);
m_pWorldMap->m_pTerrainTangent = new float [(terrainsize * SGPTT_TILENUM + 1) * (terrainsize * SGPTT_TILENUM + 1) * 3];
memset(m_pWorldMap->m_pTerrainTangent, 0, sizeof(float) * (terrainsize*SGPTT_TILENUM + 1) * (terrainsize*SGPTT_TILENUM + 1) * 3);
m_pWorldMap->m_pTerrainBinormal = new float [(terrainsize * SGPTT_TILENUM + 1) * (terrainsize * SGPTT_TILENUM + 1) * 3];
memset(m_pWorldMap->m_pTerrainBinormal, 0, sizeof(float) * (terrainsize*SGPTT_TILENUM + 1) * (terrainsize*SGPTT_TILENUM + 1) * 3);
// TEXTURE DATA
m_pWorldMap->m_WorldChunkAlphaTextureData = new uint32 [m_pWorldMap->m_Header.m_iChunkAlphaTextureSize * m_pWorldMap->m_Header.m_iChunkAlphaTextureSize];
memset(m_pWorldMap->m_WorldChunkAlphaTextureData, (uint32)0xFF000000, sizeof(uint32) * m_pWorldMap->m_Header.m_iChunkAlphaTextureSize * m_pWorldMap->m_Header.m_iChunkAlphaTextureSize);
m_pWorldMap->m_WorldChunkColorMiniMapTextureData = new uint32 [m_pWorldMap->m_Header.m_iChunkColorminiMapSize * m_pWorldMap->m_Header.m_iChunkColorminiMapSize];
memset(m_pWorldMap->m_WorldChunkColorMiniMapTextureData, (uint32)0xFF000000, sizeof(uint32) * m_pWorldMap->m_Header.m_iChunkColorminiMapSize * m_pWorldMap->m_Header.m_iChunkColorminiMapSize);
// Create terrain and OpenGL Resource
createTerrain(terrainsize, bUsePerlinNoise, maxTerrainHeight);
}
void COpenGLWorldSystemManager::editTerrainChunkBlendTexture(uint32 SrcX, uint32 SrcZ, uint32 width, uint32 height, uint32* pAlphaBlendData)
{
m_pRenderDevice->getOpenGLTerrainRenderer()->updateBlendTexture(SrcX, SrcZ, width, height, pAlphaBlendData);
}
void COpenGLWorldSystemManager::setTerrainChunkLayerTexture(uint32 ChunkIndex, ESGPTerrainChunkTexture nLayer, const String& TextureName)
{
m_pRenderDevice->getOpenGLTerrainRenderer()->updateTerrainChunkLayerTexture(ChunkIndex, nLayer, TextureName);
}
uint32* COpenGLWorldSystemManager::flushTerrainChunkColorMinimapTexture(uint32* pChunkIndex, uint32 ichunkNum)
{
return m_pRenderDevice->getOpenGLTerrainRenderer()->updateColorMinimapTexture(pChunkIndex, ichunkNum);
}
void COpenGLWorldSystemManager::addWaterChunkForEditor( int32 *pChunkIndex, uint32 ChunkIndexNum )
{
if( pChunkIndex && m_pWater && m_pTerrain )
{
for( uint32 idx = 0; idx < ChunkIndexNum; idx++ )
{
if( pChunkIndex[idx] < m_pTerrain->m_TerrainChunks.size() )
{
// Update chunk AABBox when terrain chunk having water
if( m_pWater->m_fWaterHeight > m_pTerrain->m_TerrainChunks[pChunkIndex[idx]]->m_BoundingBox.vcMax.y )
{
m_pTerrain->m_TerrainChunks[pChunkIndex[idx]]->m_BoundingBox +=
Vector3D( m_pTerrain->m_TerrainChunks[pChunkIndex[idx]]->m_BoundingBox.vcMax.x,
m_pWater->m_fWaterHeight,
m_pTerrain->m_TerrainChunks[pChunkIndex[idx]]->m_BoundingBox.vcMax.z );
}
// if WaterHeight below terrain chunk's whole boundingbox, skip this chunk
if( m_pWater->m_fWaterHeight >= m_pTerrain->m_TerrainChunks[pChunkIndex[idx]]->m_BoundingBox.vcMin.y )
m_pWater->m_TerrainWaterChunks.addIfNotAlreadyThere( m_pTerrain->m_TerrainChunks[pChunkIndex[idx]] );
}
}
}
// recreate Frame Buffer Object
m_pRenderDevice->recreateRenderToFrameBuffer(m_pRenderDevice->getViewPort().Width, m_pRenderDevice->getViewPort().Height, false);
}
void COpenGLWorldSystemManager::removeWaterChunkForEditor( int32 *pChunkIndex, uint32 ChunkIndexNum )
{
if( pChunkIndex && m_pWater && m_pTerrain )
{
for( uint32 idx = 0; idx < ChunkIndexNum; idx++ )
{
if( pChunkIndex[idx] < m_pTerrain->m_TerrainChunks.size() )
{
m_pWater->m_TerrainWaterChunks.removeAllInstancesOf( m_pTerrain->m_TerrainChunks[pChunkIndex[idx]] );
m_pTerrain->m_TerrainChunks[pChunkIndex[idx]]->UpdateAABB();
}
}
}
if( m_pWater->m_TerrainWaterChunks.size() == 0 )
{
m_pRenderDevice->getOpenGLWaterRenderer()->releaseWaterWaveTexture();
if( m_pWater )
delete m_pWater;
m_pWater = NULL;
CSGPWorldConfig::getInstance()->m_bHavingWaterInWorld = false;
}
// recreate Frame Buffer Object
m_pRenderDevice->recreateRenderToFrameBuffer(m_pRenderDevice->getViewPort().Width, m_pRenderDevice->getViewPort().Height, false);
}
ISGPLightObject* COpenGLWorldSystemManager::createLightObject( const String& LightName,
SGP_LIGHT_TYPE nLightType, const Vector3D& vPos , const Vector3D& vDirection,
float fLightSize, float fRange, const Colour& DiffuseColor )
{
ISGPLightObject* pLightObject = new ISGPLightObject();
strcpy( pLightObject->m_SceneObjectName, LightName.toUTF8().getAddress() );
pLightObject->m_iLightType = nLightType;
pLightObject->m_fPosition[0] = vPos.x;
pLightObject->m_fPosition[1] = vPos.y;
pLightObject->m_fPosition[2] = vPos.z;
pLightObject->m_fDirection[0] = vDirection.x;
pLightObject->m_fDirection[1] = vDirection.y;
pLightObject->m_fDirection[2] = vDirection.z;
pLightObject->m_fLightSize = fLightSize;
pLightObject->m_fRange = fRange;
pLightObject->m_fDiffuseColor[0] = DiffuseColor.getFloatRed();
pLightObject->m_fDiffuseColor[1] = DiffuseColor.getFloatGreen();
pLightObject->m_fDiffuseColor[2] = DiffuseColor.getFloatBlue();
return pLightObject;
}
void COpenGLWorldSystemManager::addLightObject( ISGPLightObject* lightobj )
{
// if have exist
if( m_LightObjectArray.contains(lightobj) )
return;
// Found empty Light object ID
int iLightID = m_LightObjectArray.indexOf(NULL);
if( iLightID == -1 )
{
iLightID = m_LightObjectArray.size();
m_LightObjectArray.add(lightobj);
}
else
{
m_LightObjectArray.set(iLightID, lightobj);
}
lightobj->m_iLightID = iLightID;
}
void COpenGLWorldSystemManager::deleteLightObject( ISGPLightObject* lightobj )
{
int iLightID = m_LightObjectArray.indexOf(lightobj);
if(iLightID != -1)
{
m_LightObjectArray.set(iLightID, NULL);
}
}
uint32* COpenGLWorldSystemManager::updateTerrainLightmapTexture( float &fProgress, Random* pRandom )
{
if( !m_pWorldMap || !m_pTerrain )
return NULL;
// Create Sample direction
Vector3D *samples = new Vector3D [CSGPLightMapGenConfig::getInstance()->m_iLightMap_Sample_Count];
for(uint32 x = 0; x < CSGPLightMapGenConfig::getInstance()->m_iLightMap_Sample_Count; x++)
{
Vector3D v;
do {
v.x = pRandom->nextInt(65536)/65535.0f * 2.0f - 1.0f;
v.y = pRandom->nextInt(65536)/65535.0f * 2.0f - 1.0f;
v.z = pRandom->nextInt(65536)/65535.0f * 2.0f - 1.0f;
} while (v * v > 1.0f);
samples[x] = v;
}
// Create lightmap Image in memory
uint32 LMTexWidth = m_pTerrain->GetTerrainChunkSize() * SGPTT_TILENUM * SGPTLD_LIGHTMAPTEXTURE_DIMISION;
uint32 LMTexHeight = m_pTerrain->GetTerrainChunkSize() * SGPTT_TILENUM * SGPTLD_LIGHTMAPTEXTURE_DIMISION;
uint32 *lMap = new uint32 [LMTexWidth * LMTexHeight];
memset(lMap, 0, LMTexWidth * LMTexHeight * sizeof(uint32));
float du = m_pTerrain->GetTerrainWidth() / (LMTexWidth - 1);
float dv = m_pTerrain->GetTerrainWidth() / (LMTexHeight - 1);
float fLightColorRGB[3] = {0.0f};
float fLightDistensy = 0.0f;
Vector3D samplePos;
Vector3D sampleNormal;
Vector3D vertexPos;
Vector3D lightPos;
Vector3D lightVec;
Vector3D lightVecNor;
// Pass 1, illuminate using the main light
for(uint32 t = 0; t < LMTexHeight; t++)
{
for(uint32 s = 0; s < LMTexWidth; s++)
{
samplePos.Set( s * du, getRealTerrainHeight(s*du, m_pTerrain->GetTerrainWidth()-t*dv), m_pTerrain->GetTerrainWidth() - t * dv );
sampleNormal = getTerrainNormal(s*du, m_pTerrain->GetTerrainWidth()-t*dv);
fLightColorRGB[0] = fLightColorRGB[1] = fLightColorRGB[2] = 0.0f;
ISGPLightObject** pEnd = m_LightObjectArray.end();
for( ISGPLightObject** pBegin = m_LightObjectArray.begin(); pBegin < pEnd; pBegin++ )
{
fLightDistensy = 0.0f;
vertexPos = samplePos;
lightPos.Set( (*pBegin)->m_fPosition[0], (*pBegin)->m_fPosition[1], (*pBegin)->m_fPosition[2] );
lightVec = lightPos - vertexPos;
float fdistance = lightVec.GetLength();
if( fdistance >= (*pBegin)->m_fRange )
continue;
float atten = 1.0f / ( (*pBegin)->m_fAttenuation0 +
(*pBegin)->m_fAttenuation1 * fdistance +
(*pBegin)->m_fAttenuation2 * fdistance * fdistance );
lightVecNor = lightVec;
lightVecNor.Normalize();
float diffuse = lightVecNor * sampleNormal;
if( diffuse > 0 )
{
//m_CollisionTree.pushSphere(vertexPos, CSGPLightMapGenConfig::getInstance()->m_fLightMap_Collision_Offset);
vertexPos += sampleNormal * CSGPLightMapGenConfig::getInstance()->m_fLightMap_Collision_Offset;
for(uint32 k = 0; k < CSGPLightMapGenConfig::getInstance()->m_iLightMap_Sample_Count; k++)
{
if( !m_CollisionTree.intersect( lightPos + samples[k] * (*pBegin)->m_fLightSize, vertexPos ) )
fLightDistensy += 1.0f / CSGPLightMapGenConfig::getInstance()->m_iLightMap_Sample_Count;
}
fLightColorRGB[0] += (*pBegin)->m_fDiffuseColor[0] * atten * fLightDistensy * diffuse;
fLightColorRGB[1] += (*pBegin)->m_fDiffuseColor[1] * atten * fLightDistensy * diffuse;
fLightColorRGB[2] += (*pBegin)->m_fDiffuseColor[2] * atten * fLightDistensy * diffuse;
}
}
lMap[t * LMTexWidth + s] = 0xFF000000 +
((uint32)(255.0f * fLightColorRGB[0]) << 16) +
((uint32)(255.0f * fLightColorRGB[1]) << 8) +
(uint32)(255.0f * fLightColorRGB[2]);
fProgress = float(t * LMTexWidth + s) / float(LMTexHeight * LMTexWidth) * 0.5f;
}
// m_pLogger->writeToLog(String("illuminate Terrain...")+String(fProgress), ELL_INFORMATION);
}
// Pass 2, indirect lumination (AO)
Vector3D v;
for(uint32 t = 0; t < LMTexHeight; t++)
{
for(uint32 s = 0; s < LMTexWidth; s++)
{
samplePos.Set( s * du, getRealTerrainHeight(s*du, m_pTerrain->GetTerrainWidth()-t*dv), m_pTerrain->GetTerrainWidth() - t * dv );
sampleNormal = getTerrainNormal(s*du, m_pTerrain->GetTerrainWidth()-t*dv);
//m_CollisionTree.pushSphere(samplePos, CSGPLightMapGenConfig::getInstance()->m_fLightMap_Collision_Offset);
samplePos += sampleNormal * CSGPLightMapGenConfig::getInstance()->m_fLightMap_Collision_Offset;
for(uint32 x = 0; x < CSGPLightMapGenConfig::getInstance()->m_iLightMap_Sample_Count; x++)
{
do {
v.x = pRandom->nextInt(65536)/65535.0f * 2.0f - 1.0f;
v.y = pRandom->nextInt(65536)/65535.0f * 2.0f - 1.0f;
v.z = pRandom->nextInt(65536)/65535.0f * 2.0f - 1.0f;
} while ((v * v > 1.0f) || (sampleNormal * v < 0));
samples[x] = v * CSGPLightMapGenConfig::getInstance()->m_fLightMap_AO_Distance;
}
float AO = 0.0f;
for(uint32 k = 0; k < CSGPLightMapGenConfig::getInstance()->m_iLightMap_Sample_Count; k++)
{
if( !m_CollisionTree.intersect(samplePos, samplePos + samples[k]) )
AO += 1.0f / CSGPLightMapGenConfig::getInstance()->m_iLightMap_Sample_Count;
}
lMap[t * LMTexWidth + s] = (lMap[t * LMTexWidth + s] & 0x00FFFFFF) + ((uint32)(AO * 255.0f) << 24);
fProgress = 0.5f + float(t * LMTexWidth + s) / float(LMTexHeight * LMTexWidth) * 0.5f;
}
// m_pLogger->writeToLog(String("illuminate Terrain...")+String(fProgress), ELL_INFORMATION);
}
// m_pRenderDevice->getOpenGLTerrainRenderer()->updateLightmapTexture(LMTexWidth, LMTexHeight, lMap);
/* delete [] lMap;
lMap = NULL;*/
delete [] samples;
samples = NULL;
return lMap;
}
uint32* COpenGLWorldSystemManager::updateSceneObjectLightmapTexture( float &fProgress, ISGPObject* pSceneObj, uint32 nLMTexWidth, uint32 nLMTexHeight, Random* pRandom )
{
if( !m_pWorldMap || !m_pTerrain || !pSceneObj )
return NULL;
// Create Sample direction
Vector3D *samples = new Vector3D [CSGPLightMapGenConfig::getInstance()->m_iLightMap_Sample_Count];
Vector3D *samples2 = new Vector3D [CSGPLightMapGenConfig::getInstance()->m_iLightMap_Sample_Count];
for(uint32 x = 0; x < CSGPLightMapGenConfig::getInstance()->m_iLightMap_Sample_Count; x++)
{
Vector3D v;
do {
v.x = pRandom->nextInt(65536)/65535.0f * 2.0f - 1.0f;
v.y = pRandom->nextInt(65536)/65535.0f * 2.0f - 1.0f;
v.z = pRandom->nextInt(65536)/65535.0f * 2.0f - 1.0f;
} while (v * v > 1.0f);
samples[x] = v;
}
// Create lightmap Image in memory
uint32 *lMap = new uint32 [nLMTexWidth * nLMTexHeight];
memset(lMap, 0, nLMTexWidth * nLMTexHeight * sizeof(uint32));
float du = 1.0f / (nLMTexWidth - 1);
float dv = 1.0f / (nLMTexHeight - 1);
float fLightColorRGB[3] = {0.0f};
float fLightDistensy = 0.0f;
Vector3D samplePos;
Vector3D sampleNormal;
Vector3D vertexPos;
Vector3D lightPos;
Vector3D lightVec;
Vector3D lightVecNor;
CStaticMeshInstance *pInstance = m_SceneIDToInstanceMap[pSceneObj->getSceneObjectID()];
Matrix4x4 modelMatrix = pInstance->getModelMatrix();
CMF1FileResource *pMF1Res = m_pRenderDevice->GetModelManager()->getModelByID(pInstance->getMF1ModelResourceID());
CSGPModelMF1 *pMF1Model = (pMF1Res != NULL) ? pMF1Res->pModelMF1 : NULL;
jassert( pMF1Model );
Vector4D SunColor = m_pRenderDevice->getOpenGLSkydomeRenderer()->getSunColorAndIntensity();
Array<ISGPLightObject*> LightObjectArray;
getAllIlluminatedLight(LightObjectArray, pSceneObj);
for(uint32 t = 0; t < nLMTexHeight; t++)
{
for(uint32 s = 0; s < nLMTexWidth; s++)
{
if( pMF1Model->GetMeshPointFromSecondTexCoord( samplePos, sampleNormal, Vector2D(s * du, t * dv), modelMatrix ) )
{
// Pass 1, illuminate using the main light
fLightColorRGB[0] = fLightColorRGB[1] = fLightColorRGB[2] = 0.0f;
ISGPLightObject** pEnd = LightObjectArray.end();
for( ISGPLightObject** pBegin = LightObjectArray.begin(); pBegin < pEnd; pBegin++ )
{
fLightDistensy = 0.0f;
vertexPos = samplePos;
lightPos.Set( (*pBegin)->m_fPosition[0], (*pBegin)->m_fPosition[1], (*pBegin)->m_fPosition[2] );
lightVec = lightPos - vertexPos;
float fdistance = lightVec.GetLength();
if( fdistance >= (*pBegin)->m_fRange )
continue;
float atten = 1.0f / ( (*pBegin)->m_fAttenuation0 +
(*pBegin)->m_fAttenuation1 * fdistance +
(*pBegin)->m_fAttenuation2 * fdistance * fdistance );
lightVecNor = lightVec;
lightVecNor.Normalize();
float diffuse = lightVecNor * sampleNormal;
if( diffuse > 0 )
{
//m_CollisionTree.pushSphere(vertexPos, CSGPLightMapGenConfig::getInstance()->m_fLightMap_Collision_Offset);
vertexPos += sampleNormal * CSGPLightMapGenConfig::getInstance()->m_fLightMap_Collision_Offset;
for(uint32 k = 0; k < CSGPLightMapGenConfig::getInstance()->m_iLightMap_Sample_Count; k++)
{
if( !m_CollisionTree.intersect( lightPos + samples[k] * (*pBegin)->m_fLightSize, vertexPos ) )
fLightDistensy += 1.0f / CSGPLightMapGenConfig::getInstance()->m_iLightMap_Sample_Count;
}
fLightColorRGB[0] += (*pBegin)->m_fDiffuseColor[0] * atten * fLightDistensy * diffuse;
fLightColorRGB[1] += (*pBegin)->m_fDiffuseColor[1] * atten * fLightDistensy * diffuse;
fLightColorRGB[2] += (*pBegin)->m_fDiffuseColor[2] * atten * fLightDistensy * diffuse;
}
}
// Global Sun Direction Light
lightVecNor = m_pRenderDevice->GetWorldSystemManager()->getWorldSun()->getNormalizedSunDirection();
float diffuse = lightVecNor * sampleNormal;
if( diffuse > 0 )
{
fLightColorRGB[0] += SunColor.x * diffuse;
fLightColorRGB[1] += SunColor.y * diffuse;
fLightColorRGB[2] += SunColor.z * diffuse;
}
fLightColorRGB[0] = jlimit(0.0f, 1.0f, fLightColorRGB[0]);
fLightColorRGB[1] = jlimit(0.0f, 1.0f, fLightColorRGB[1]);
fLightColorRGB[2] = jlimit(0.0f, 1.0f, fLightColorRGB[2]);
lMap[t * nLMTexWidth + s] = 0xFF000000 +
((uint32)(255.0f * fLightColorRGB[0]) << 16) +
((uint32)(255.0f * fLightColorRGB[1]) << 8) +
(uint32)(255.0f * fLightColorRGB[2]);
// Pass 2, indirect lumination (AO)
vertexPos = samplePos;
//m_CollisionTree.pushSphere(vertexPos, CSGPLightMapGenConfig::getInstance()->m_fLightMap_Collision_Offset);
vertexPos += sampleNormal * CSGPLightMapGenConfig::getInstance()->m_fLightMap_Collision_Offset;
for(uint32 x = 0; x < CSGPLightMapGenConfig::getInstance()->m_iLightMap_Sample_Count; x++)
{
Vector3D v;
do {
v.x = pRandom->nextInt(65536)/65535.0f * 2.0f - 1.0f;
v.y = pRandom->nextInt(65536)/65535.0f * 2.0f - 1.0f;
v.z = pRandom->nextInt(65536)/65535.0f * 2.0f - 1.0f;
} while ((v * v > 1.0f) || (sampleNormal * v < 0));
samples2[x] = v * CSGPLightMapGenConfig::getInstance()->m_fLightMap_AO_Distance;
}
float AO = 0.0f;
for(uint32 k = 0; k < CSGPLightMapGenConfig::getInstance()->m_iLightMap_Sample_Count; k++)
{
if( !m_CollisionTree.intersect(vertexPos, vertexPos + samples2[k]) )
AO += 1.0f / CSGPLightMapGenConfig::getInstance()->m_iLightMap_Sample_Count;
}
lMap[t * nLMTexWidth + s] = (lMap[t * nLMTexWidth + s] & 0x00FFFFFF) + ((uint32)(AO * 255.0f) << 24);
}
fProgress = float(t * nLMTexWidth + s) / float(nLMTexHeight * nLMTexWidth);
}
// m_pLogger->writeToLog(String("illuminate Object ")+String(pSceneObj->getSceneObjectName())+String(fProgress), ELL_INFORMATION);
}
// pInstance->updateLightmapTexture(nLMTexWidth, nLMTexHeight, lMap);
/* delete [] lMap;
lMap = NULL;*/
delete [] samples;
samples = NULL;
delete [] samples2;
samples2 = NULL;
return lMap;
}
void COpenGLWorldSystemManager::getAllIlluminatedLight(Array<ISGPLightObject*>& LightObjectArray, ISGPObject* pSceneObj)
{
jassert(pSceneObj);
ISGPLightObject** pEnd = m_LightObjectArray.end();
for( ISGPLightObject** pBegin = m_LightObjectArray.begin(); pBegin < pEnd; pBegin++ )
{
const OBBox& boundingbox = pSceneObj->getBoundingBox();
AABBox lightBox( Vector3D( (*pBegin)->m_fPosition[0] - (*pBegin)->m_fRange, (*pBegin)->m_fPosition[1] - (*pBegin)->m_fRange, (*pBegin)->m_fPosition[2] - (*pBegin)->m_fRange ),
Vector3D( (*pBegin)->m_fPosition[0] + (*pBegin)->m_fRange, (*pBegin)->m_fPosition[1] + (*pBegin)->m_fRange, (*pBegin)->m_fPosition[2] + (*pBegin)->m_fRange ) );
if( OBBox( &lightBox ).Intersects(boundingbox) )
LightObjectArray.add( *pBegin );
}
}
//==============================================================================
//==============================================================================
void COpenGLWorldSystemManager::initializeTerrainRenderer(bool bLoadFromMap)
{
// set terrain size
m_pRenderDevice->getOpenGLTerrainRenderer()->setTerrainSize( m_pTerrain->GetTerrainChunkSize() );
// Create terrain Chunk VAO
for( uint32 j=0; j<m_pTerrain->GetTerrainChunkSize(); j++ )
{
for( uint32 i=0; i<m_pTerrain->GetTerrainChunkSize(); i++ )
{
m_pRenderDevice->getOpenGLTerrainRenderer()->createChunkVBO(j * m_pTerrain->GetTerrainChunkSize() + i);
m_pRenderDevice->getOpenGLTerrainRenderer()->createChunkTextureFromWorldMap(m_pWorldMap, j * m_pTerrain->GetTerrainChunkSize() + i);
}
}
// Register terrain alphablend texture
m_pRenderDevice->getOpenGLTerrainRenderer()->registerBlendTexture(m_pWorldMap, String(L"Blendmap-")+getWorldName(), m_pTerrain->GetTerrainChunkSize());
// Register terrain mini colormap texture
if( !bLoadFromMap )
{
uint32* pMinimapData = getWorldMap()->m_WorldChunkColorMiniMapTextureData;
for( uint32 row = 0; row < m_pTerrain->GetTerrainChunkSize(); row++ )
for( uint32 col = 0; col < m_pTerrain->GetTerrainChunkSize(); col++ )
m_pRenderDevice->getOpenGLTerrainRenderer()->generateChunkColorMinimapData(pMinimapData, m_pTerrain->GetTerrainChunkSize(), row, col);
}
m_pRenderDevice->getOpenGLTerrainRenderer()->registerColorMinimapTexture(m_pWorldMap, String(L"ColorMinimap-")+getWorldName(), m_pTerrain->GetTerrainChunkSize());
// Register terrain lightmap texture
m_pRenderDevice->getOpenGLTerrainRenderer()->registerLightmapTexture(getWorldName(), String(L"TerrainLightmap.dds"));
}
void COpenGLWorldSystemManager::releaseTerrainRenderer()
{
// unRegister terrain alphablend texture
m_pRenderDevice->getOpenGLTerrainRenderer()->unregisterBlendTexture(String(L"Blendmap-")+getWorldName());
// unRegister terrain mini colormap texture
m_pRenderDevice->getOpenGLTerrainRenderer()->unRegisterColorMinimapTexture(String(L"ColorMinimap-")+getWorldName());
// unRegister terrain lightmap texture
m_pRenderDevice->getOpenGLTerrainRenderer()->unregisterLightmapTexture();
// Release Chunk VAO
if( m_pTerrain )
{
for( uint32 j=0; j<m_pTerrain->GetTerrainChunkSize(); j++ )
{
for( uint32 i=0; i<m_pTerrain->GetTerrainChunkSize(); i++ )
m_pRenderDevice->getOpenGLTerrainRenderer()->releaseChunkVBO(j * m_pTerrain->GetTerrainChunkSize() + i);
}
}
}
void COpenGLWorldSystemManager::getVisibleSceneObjectArray(const Frustum& ViewFrustum, const Array<CSGPTerrainChunk*>& VisibleChunkArray, Array<ISGPObject*>& VisibleSceneObjectArray)
{
Frustum MirroredViewFrustum;
if( needRenderWater() )
{
MirroredViewFrustum.setFrom( m_pRenderDevice->getOpenGLWaterRenderer()->m_MirrorViewMatrix * m_pRenderDevice->getOpenGLCamera()->m_mProjMatrix );
}
CSGPTerrainChunk** pEnd = VisibleChunkArray.end();
for( CSGPTerrainChunk** pBegin = VisibleChunkArray.begin(); pBegin < pEnd; pBegin++ )
{
const Array<ISGPObject*>& chunkObjArray = (*pBegin)->GetTerrainChunkObject();
ISGPObject** pObjEnd = chunkObjArray.end();
for( ISGPObject** pObjBegin = chunkObjArray.begin(); pObjBegin < pObjEnd; pObjBegin++ )
{
AABBox objAABB;
objAABB.Construct( &((*pObjBegin)->getBoundingBox()) );
if( objAABB.Intersects(ViewFrustum) )
VisibleSceneObjectArray.addIfNotAlreadyThere(*pObjBegin);
if( needRenderWater() && objAABB.Intersects(MirroredViewFrustum) )
VisibleSceneObjectArray.addIfNotAlreadyThere(*pObjBegin);
}
}
}
| 38.261326 | 207 | 0.747751 | [
"mesh",
"render",
"object",
"model"
] |
7a538656210fd9966be7b9e921f5a96d61c90159 | 3,654 | cpp | C++ | source/radeon_gpu_analyzer_gui/rg_settings_model_base.cpp | clayne/RGA | 7ed370e00b635c5b558d4af4eb050e2a38f77e53 | [
"MIT"
] | 97 | 2020-03-12T01:47:49.000Z | 2022-03-16T02:29:04.000Z | source/radeon_gpu_analyzer_gui/rg_settings_model_base.cpp | clayne/RGA | 7ed370e00b635c5b558d4af4eb050e2a38f77e53 | [
"MIT"
] | 34 | 2020-03-10T16:38:48.000Z | 2022-03-19T04:05:04.000Z | source/radeon_gpu_analyzer_gui/rg_settings_model_base.cpp | clayne/RGA | 7ed370e00b635c5b558d4af4eb050e2a38f77e53 | [
"MIT"
] | 14 | 2020-03-13T00:50:23.000Z | 2022-01-31T09:06:54.000Z | // C++.
#include <cassert>
#include <sstream>
// Local.
#include "radeon_gpu_analyzer_gui/rg_utils.h"
#include "radeon_gpu_analyzer_gui/qt/rg_settings_model_base.h"
#include "radeon_gpu_analyzer_gui/rg_data_types.h"
#include "radeon_gpu_analyzer_gui/rg_string_constants.h"
RgSettingsModelBase::RgSettingsModelBase(unsigned int model_count) :
ModelViewMapper(model_count) {}
void RgSettingsModelBase::RevertPendingChanges()
{
// Clear the map of pending changes to the settings.
pending_values_.clear();
// After submitting the user's pending changes, the interface has no changes pending.
SetHasPendingChanges(false);
// Reset the build settings to the current settings, which will update the UI.
InitializeModelValues();
}
bool RgSettingsModelBase::HasPendingChanges() const
{
return has_pending_changes_;
}
void RgSettingsModelBase::InitializeModelValues()
{
// Initialize the model values.
InitializeModelValuesImpl();
// Since the model data has just been initialized for the first time, it is in a "dirty" state.
// Reset the model's pending changes so that the Build Settings aren't displayed
SetHasPendingChanges(false);
}
void RgSettingsModelBase::SetHasPendingChanges(bool has_pending_changes)
{
// Only confirm the state change if it's different from the current state.
if (has_pending_changes_ != has_pending_changes)
{
has_pending_changes_ = has_pending_changes;
// Emit a signal that the dirtiness of the model has changed.
emit PendingChangesStateChanged(has_pending_changes);
}
}
void RgSettingsModelBase::SubmitPendingChanges()
{
// Step through each control and update the displayed value if necessary.
uint32_t model_count = GetModelCount();
for (uint32_t control_index = 0; control_index < model_count; ++control_index)
{
auto control_value = pending_values_.find(control_index);
if (control_value != pending_values_.end())
{
UpdateModelValue(control_index, control_value->second, true);
}
}
// After submitting the changes, clear all of the user's pending changes.
RevertPendingChanges();
}
bool RgSettingsModelBase::GetHasPendingChanges() const
{
bool has_pending_changes = false;
// Step through the initial values, and compare to pending values.
auto initial_values_start_iter = initial_values_.begin();
auto initial_values_end_iter = initial_values_.end();
for (auto initial_values_iter = initial_values_start_iter; initial_values_iter != initial_values_end_iter; ++initial_values_iter)
{
// Extract the initial value for the control.
int model_index = initial_values_iter->first;
const QVariant& initial_value = initial_values_iter->second;
// Attempt to find a pending value for the control.
auto pending_value_iter = pending_values_.find(model_index);
if (pending_value_iter != pending_values_.end())
{
const QVariant& pending_value = pending_value_iter->second;
// If the original and pending values match, there is no pending change.
if (initial_value != pending_value)
{
has_pending_changes = true;
break;
}
}
}
return has_pending_changes;
}
bool RgSettingsModelBase::GetPendingValue(int control, QVariant& value) const
{
bool ret = false;
auto pending_value_iter = pending_values_.find(control);
if (pending_value_iter != pending_values_.end())
{
ret = true;
value = pending_value_iter->second;
}
return ret;
}
| 32.052632 | 133 | 0.711549 | [
"model"
] |
7a54788f3f5767c3c2a9f871065c6242bb63cc4c | 9,308 | cpp | C++ | src/gui/CustomGetDlg.cpp | jtilander/niftyp4win | 457e2973e3b5c109d76138c5032c486f18276910 | [
"BSD-2-Clause"
] | 3 | 2016-09-09T01:57:01.000Z | 2021-05-14T22:38:32.000Z | src/gui/CustomGetDlg.cpp | jtilander/niftyp4win | 457e2973e3b5c109d76138c5032c486f18276910 | [
"BSD-2-Clause"
] | null | null | null | src/gui/CustomGetDlg.cpp | jtilander/niftyp4win | 457e2973e3b5c109d76138c5032c486f18276910 | [
"BSD-2-Clause"
] | null | null | null | // CustomGetDlg.cpp : implementation file
//
#include "stdafx.h"
#include "p4win.h"
#include "CustomGetDlg.h"
#include "MainFrm.h"
#include "p4api\P4Command.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CCustomGetDlg dialog
CCustomGetDlg::CCustomGetDlg(CWnd* pParent /*=NULL*/)
: CDialog(CCustomGetDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CCustomGetDlg)
m_LabelText = _T("");
m_RevText = _T("");
m_Radio = -1;
m_Only = m_Force = FALSE;
m_DepotWnd = pParent->m_hWnd;
//}}AFX_DATA_INIT
m_IsMinimized = FALSE;
m_NbrSel = -1;
}
CCustomGetDlg::~CCustomGetDlg()
{
}
void CCustomGetDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CCustomGetDlg)
DDX_Text(pDX, IDC_EDITLABEL, m_LabelText);
DDV_MaxChars(pDX, m_LabelText, 128);
DDX_Text(pDX, IDC_REVNBR, m_RevText);
DDV_MaxChars(pDX, m_RevText, 8);
DDX_Radio(pDX, IDC_ISREVNBR, m_Radio);
DDX_Control(pDX, IDC_COMBO, m_TypeCombo);
DDX_Check(pDX, IDC_CHECKONLY, m_Only);
DDX_Check(pDX, IDC_FORCE_RESYNC, m_Force);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CCustomGetDlg, CDialog)
//{{AFX_MSG_MAP(CCustomGetDlg)
ON_BN_CLICKED(IDGETPREVIEW, OnGetpreview)
ON_BN_CLICKED(IDGET, OnGet)
ON_BN_CLICKED(IDC_ISREVNBR, OnRadioClick)
ON_BN_CLICKED(IDC_ISSYMBOL, OnRadioClick)
ON_BN_CLICKED(IDC_BROWSE, OnBrowse)
ON_CBN_SELCHANGE(IDC_COMBO, OnComboValueChg)
ON_WM_SIZE()
ON_WM_DESTROY()
ON_WM_SYSCOMMAND()
//}}AFX_MSG_MAP
ON_MESSAGE(WM_BROWSECALLBACK1, OnBrowseCallBack)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CCustomGetDlg message handlers
BOOL CCustomGetDlg::OnInitDialog()
{
CDialog::OnInitDialog();
MainFrame()->SetModelessWnd(this);
GetDlgItem(IDC_DATELABEL)->ShowWindow(SW_HIDE);
m_TypeCombo.AddString(LoadStringResource(IDS_COMBO_CHGNBR));
m_TypeCombo.AddString(LoadStringResource(IDS_COMBO_LABEL));
m_TypeCombo.AddString(LoadStringResource(IDS_COMBO_DATE));
m_TypeCombo.AddString(LoadStringResource(IDS_COMBO_CLIENT));
m_TypeCombo.SetCurSel(0);
int init = GET_P4REGPTR()->GetSyncDlgFlag();
if (init >= 0)
{
if (!init)
m_Radio = 0;
else
{
m_Radio = 1;
m_TypeCombo.SetCurSel(init - 1);
}
}
UpdateData(FALSE);
OnRadioClick();
ShowWindow(SW_SHOW);
return FALSE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
void CCustomGetDlg::OnGetpreview()
{
UpdateData(TRUE);
switch(m_Radio)
{
case 0:
m_RevText.TrimLeft(_T(" #"));
if(m_RevText.GetLength() == 0 || m_RevText.FindOneOf(_T("#@")) != -1)
{
AfxMessageBox(IDS_REVISION_NUMBER_IS_INVALID, MB_ICONEXCLAMATION);
return;
}
if (m_RevText == _T("0"))
m_RevText = _T("none");
else if (!_istdigit(m_RevText[0]) && m_RevText != _T("none")
&& m_RevText != _T("head") && m_RevText != _T("have"))
{
AfxMessageBox(IDS_REVISION_NUMBER_IS_INVALID, MB_ICONEXCLAMATION);
return;
}
m_LabelText= _T("#") + m_RevText;
if (m_RevText != _T("none") && m_NbrSel > 1
&& IDYES != AfxMessageBox(IDS_SYNC_MULTIFILES_TO_REVNBR,
MB_ICONQUESTION|MB_YESNO|MB_DEFBUTTON2))
return;
GET_P4REGPTR()->SetSyncDlgFlag(0);
break;
case 1:
m_LabelText.TrimLeft(_T(" @"));
m_LabelText.TrimRight();
if (m_LabelText.GetLength() == 0 || (m_Only && (m_LabelText.FindOneOf(_T("#@")) != -1)))
{
if (m_LabelText != _T("#none"))
{
GotoDlgCtrl(GetDlgItem(IDC_EDITLABEL));
AfxMessageBox(IDS_CHGLABDATCLI_IS_INVALID, MB_ICONEXCLAMATION);
return;
}
}
if (m_LabelText.GetAt(0) != _T('#'))
{
m_LabelText = _T("@") + m_LabelText;
if (m_Only)
{
if ((m_LabelText.Find(_T('/')) != -1)
&& (m_LabelText.Find(_T(':')) == -1))
m_LabelText = m_LabelText + _T(":00:00:00,") + m_LabelText + _T(":23:59:59");
else
m_LabelText += _T(",") + m_LabelText;
}
}
GET_P4REGPTR()->SetSyncDlgFlag(1 + m_TypeCombo.GetCurSel());
break;
}
::PostMessage(m_DepotWnd, WM_DOCUSTOMGET,
m_Force ? (WPARAM)IDGETFORCEPREVIEW : (WPARAM)IDGETPREVIEW,
(LPARAM)((LPCTSTR)m_LabelText));
}
void CCustomGetDlg::OnGet()
{
UpdateData(TRUE);
switch(m_Radio)
{
case 0:
m_RevText.TrimLeft(_T(" #"));
if(m_RevText.GetLength() == 0 || m_RevText.FindOneOf(_T("#@")) != -1)
{
AfxMessageBox(IDS_REVISION_NUMBER_IS_INVALID, MB_ICONEXCLAMATION);
return;
}
if (m_RevText == _T("0"))
m_RevText = _T("none");
else if (!_istdigit(m_RevText[0]) && m_RevText != _T("none")
&& m_RevText != _T("head") && m_RevText != _T("have"))
{
AfxMessageBox(IDS_REVISION_NUMBER_IS_INVALID, MB_ICONEXCLAMATION);
return;
}
m_LabelText= _T("#") + m_RevText;
if (m_RevText != _T("none") && m_NbrSel > 1
&& IDYES != AfxMessageBox(IDS_SYNC_MULTIFILES_TO_REVNBR,
MB_ICONQUESTION|MB_YESNO|MB_DEFBUTTON2))
return;
GET_P4REGPTR()->SetSyncDlgFlag(0);
break;
case 1:
m_LabelText.TrimLeft(_T(" @"));
m_LabelText.TrimRight();
if (m_LabelText.GetLength() == 0 || (m_Only && (m_LabelText.FindOneOf(_T("#@")) != -1)))
{
if (m_LabelText != _T("#none"))
{
GotoDlgCtrl(GetDlgItem(IDC_EDITLABEL));
AfxMessageBox(IDS_CHGLABDATCLI_IS_INVALID, MB_ICONEXCLAMATION);
return;
}
}
if (m_LabelText.GetAt(0) != _T('#'))
{
m_LabelText = _T("@") + m_LabelText;
if (m_Only)
{
if ((m_LabelText.Find(_T('/')) != -1)
&& (m_LabelText.Find(_T(':')) == -1))
m_LabelText = m_LabelText + _T(":00:00:00,") + m_LabelText + _T(":23:59:59");
else
m_LabelText += _T(",") + m_LabelText;
}
}
GET_P4REGPTR()->SetSyncDlgFlag(1 + m_TypeCombo.GetCurSel());
break;
}
::PostMessage(m_DepotWnd, WM_DOCUSTOMGET,
m_Force ? (WPARAM)IDGETFORCE : (WPARAM)IDGET, (LPARAM)((LPCTSTR)m_LabelText));
}
void CCustomGetDlg::OnCancel()
{
::PostMessage(m_DepotWnd, WM_DOCUSTOMGET, (WPARAM)IDCANCEL, (LPARAM)0);
}
// This signals the closing of a modeless dialog
// to MainFrame which will delete the 'this' object
void CCustomGetDlg::OnDestroy()
{
::PostMessage(MainFrame()->m_hWnd, WM_P4DLGDESTROY, 0, (LPARAM)this);
}
void CCustomGetDlg::OnRadioClick()
{
UpdateData(TRUE);
GetDlgItem(IDGET)->EnableWindow( TRUE );
GetDlgItem(IDGETPREVIEW)->EnableWindow( TRUE );
GetDlgItem(IDC_EDITLABEL)->EnableWindow( FALSE );
GetDlgItem(IDC_REVNBR)->EnableWindow( FALSE );
GetDlgItem(IDC_COMBO)->EnableWindow( FALSE );
GetDlgItem(IDC_CHECKONLY)->EnableWindow( FALSE );
switch(m_Radio)
{
case 0:
GetDlgItem(IDC_REVNBR)->EnableWindow( TRUE );
GotoDlgCtrl(GetDlgItem(IDC_REVNBR));
break;
case 1:
GetDlgItem(IDC_EDITLABEL)->EnableWindow( TRUE );
GetDlgItem(IDC_COMBO)->EnableWindow( TRUE );
GetDlgItem(IDC_CHECKONLY)->EnableWindow( TRUE );
OnComboValueChg();
GotoDlgCtrl(GetDlgItem(IDC_COMBO));
break;
default:
break;
}
}
void CCustomGetDlg::OnComboValueChg()
{
switch(m_TypeCombo.GetCurSel())
{
default:
case COMBO_CHGNBR:
GetDlgItem(IDC_BROWSE)->EnableWindow( TRUE );
GetDlgItem(IDC_DATELABEL)->ShowWindow(SW_HIDE);
GetDlgItem(IDC_CHECKONLY)->SetWindowText(LoadStringResource(IDS_SYNCONLYCHG));
break;
case COMBO_LABEL:
GetDlgItem(IDC_BROWSE)->EnableWindow( TRUE );
GetDlgItem(IDC_DATELABEL)->ShowWindow(SW_HIDE);
GetDlgItem(IDC_CHECKONLY)->SetWindowText(LoadStringResource(IDS_SYNCONLYLABEL));
break;
case COMBO_CLIENT:
GetDlgItem(IDC_BROWSE)->EnableWindow( TRUE );
GetDlgItem(IDC_DATELABEL)->ShowWindow(SW_HIDE);
GetDlgItem(IDC_CHECKONLY)->SetWindowText(LoadStringResource(IDS_SYNCONLYCLIENT));
break;
case COMBO_DATE:
GetDlgItem(IDC_BROWSE)->EnableWindow( FALSE );
GetDlgItem(IDC_DATELABEL)->ShowWindow(SW_SHOW);
GetDlgItem(IDC_CHECKONLY)->SetWindowText(LoadStringResource(IDS_SYNCONLYDATE));
break;
}
}
void CCustomGetDlg::OnBrowse()
{
HWND hWnd;
switch(m_TypeCombo.GetCurSel())
{
case COMBO_CLIENT:
hWnd = MainFrame()->ClientWnd();
break;
case COMBO_LABEL:
hWnd = MainFrame()->LabelWnd();
break;
case COMBO_CHGNBR:
hWnd = MainFrame()->OldChgsWnd();
break;
default:
hWnd = 0;
break;
}
::SendMessage(hWnd, WM_FETCHOBJECTLIST, (WPARAM)(this->m_hWnd), WM_BROWSECALLBACK1);
GotoDlgCtrl(GetDlgItem(IDC_EDITLABEL));
}
LRESULT CCustomGetDlg::OnBrowseCallBack(WPARAM wParam, LPARAM lParam)
{
UpdateData(TRUE);
CString *str = (CString *)lParam;
m_LabelText = *str;
UpdateData(FALSE);
GotoDlgCtrl(GetDlgItem(IDC_EDITLABEL));
return 0;
}
void CCustomGetDlg::OnSize(UINT nType, int cx, int cy)
{
CDialog::OnSize(nType, cx, cy);
if (nType == SIZE_MINIMIZED)
{
m_IsMinimized = TRUE;
return;
}
else if (m_IsMinimized)
{
m_IsMinimized = FALSE;
return;
}
}
void CCustomGetDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
switch(nID)
{
case SC_MINIMIZE:
GetDesktopWindow()->ArrangeIconicWindows();
break;
}
CDialog::OnSysCommand(nID, lParam);
}
| 26.443182 | 91 | 0.662226 | [
"object"
] |
7a5b6bf87f467801762adceda55915964dcc5df6 | 3,468 | cpp | C++ | misc/siggraphasia2019_loc/mlsmpm_ref/MPM/Simulator.cpp | amix2115/taichi | 55eb9affe84b711c0344c0365456d6f99b9316c0 | [
"MIT"
] | 3 | 2020-01-08T02:58:51.000Z | 2020-10-28T07:01:58.000Z | misc/siggraphasia2019_loc/mlsmpm_ref/MPM/Simulator.cpp | amix2115/taichi | 55eb9affe84b711c0344c0365456d6f99b9316c0 | [
"MIT"
] | 1 | 2020-07-21T05:51:19.000Z | 2020-10-08T01:31:15.000Z | misc/siggraphasia2019_loc/mlsmpm_ref/MPM/Simulator.cpp | amix2115/taichi | 55eb9affe84b711c0344c0365456d6f99b9316c0 | [
"MIT"
] | 1 | 2020-03-25T16:37:00.000Z | 2020-03-25T16:37:00.000Z | #include "Simulator.h"
#include "../Particle/ParticleDomain.cuh"
#include "../Grid/GridDomain.cuh"
#include "../DomainTransform/DomainTransformer.cuh"
#include <System/Log/Logger.hpp>
#include <stdio.h>
#include <stdlib.h>
namespace mn {
MPMSimulator::MPMSimulator()
: _frameRate(48.f), _currentFrame(0), _currentTime(0) {
}
MPMSimulator::~MPMSimulator() {
checkCudaErrors(cudaFree(d_keyTable));
checkCudaErrors(cudaFree(d_valTable));
checkCudaErrors(cudaFree(d_masks));
checkCudaErrors(cudaFree(d_maxVelSquared));
checkCudaErrors(cudaFree(d_memTrunk));
}
void MPMSimulator::buildModel(std::vector<T> &hmass,
std::vector<std::array<T, Dim>> &hpos,
std::vector<std::array<T, Dim>> &hvel,
const int materialType,
const T youngsModulus,
const T poissonRatio,
const T density,
const T volume,
int idx) {
{
auto geometry = std::make_unique<Particles>(_numParticle, _tableSize);
auto material = std::make_unique<ElasticMaterialDynamics>(
materialType, youngsModulus, poissonRatio, density, volume);
h_models.emplace_back(
std::make_unique<Model>(std::move(geometry), std::move(material)));
printf("\n\tFinish Particles initializing\n");
}
auto &geometry = refGeometryPtr(idx);
geometry->initialize(hmass.data(), (const T *)hpos.data(),
(const T *)hvel.data(), d_masks, h_masks.data(),
d_keyTable, d_valTable, d_memTrunk);
}
void MPMSimulator::buildGrid(const int width,
const int height,
const int depth,
const T dc) {
auto &grid = refGridPtr();
grid = std::make_unique<SPGrid>(width, height, depth, dc);
grid->initialize(d_masks, h_masks.data());
printf("\n\tFinish SPGrid initializing\n");
}
void MPMSimulator::buildTransformer(const int gridVolume) {
auto &transformer = refTransformerPtr();
transformer = std::make_unique<DomainTransformer<TEST_STRUCT<T>>>(
_numParticle, gridVolume);
transformer->initialize(d_masks, refGeometryPtr(0)->d_offsets, _tableSize,
d_keyTable, d_valTable);
printf("\n\tFinish Transformer initializing\n");
Logger::blankLine<TimerType::GPU>();
}
void MPMSimulator::writePartio(const std::string &filename) {
Partio::ParticlesDataMutable *parts = Partio::create();
Partio::ParticleAttribute posH =
parts->addAttribute("position", Partio::VECTOR, 3);
Partio::ParticleAttribute velH =
parts->addAttribute("velocity", Partio::VECTOR, 3);
Partio::ParticleAttribute indexH =
parts->addAttribute("index", Partio::INT, 1);
Partio::ParticleAttribute typeH = parts->addAttribute("type", Partio::INT, 1);
for (unsigned int i = 0; i < h_pos.size(); ++i) {
int idx = parts->addParticle();
float *p = parts->dataWrite<float>(posH, idx);
float *v = parts->dataWrite<float>(velH, idx);
int *index = parts->dataWrite<int>(indexH, idx);
int *type = parts->dataWrite<int>(typeH, idx);
for (int k = 0; k < 3; k++)
p[k] = h_pos[i][k];
for (int k = 0; k < 3; k++)
v[k] = h_vel[i][k];
index[0] = h_indices[i];
type[0] = 1;
}
Partio::write(filename.c_str(), *parts);
parts->release();
}
} // namespace mn
| 40.8 | 80 | 0.617935 | [
"geometry",
"vector",
"model"
] |
7a5ed6404067eb0b548129a69070182ad7860c97 | 960 | cpp | C++ | tutorial/verify.cpp | axell-corp/TFHEpp-1 | 6e489396575d2d6cf830af5b1153e8ab3d22f9c6 | [
"Apache-2.0"
] | 33 | 2020-01-29T08:43:37.000Z | 2022-03-29T03:06:12.000Z | tutorial/verify.cpp | axell-corp/TFHEpp-1 | 6e489396575d2d6cf830af5b1153e8ab3d22f9c6 | [
"Apache-2.0"
] | 6 | 2020-01-17T12:40:40.000Z | 2022-03-24T12:47:23.000Z | tutorial/verify.cpp | axell-corp/TFHEpp-1 | 6e489396575d2d6cf830af5b1153e8ab3d22f9c6 | [
"Apache-2.0"
] | 12 | 2020-05-10T19:10:43.000Z | 2022-01-10T05:12:33.000Z | #include <cereal/archives/portable_binary.hpp>
#include <cereal/types/vector.hpp>
#include <fstream>
#include <iostream>
#include <tfhe++.hpp>
int main()
{
// reads the cloud key from file
TFHEpp::SecretKey sk;
{
std::ifstream ifs{"secret.key", std::ios::binary};
cereal::PortableBinaryInputArchive ar(ifs);
sk.serialize(ar);
};
// read the 2 ciphertexts of the result
std::vector<TFHEpp::TLWE<TFHEpp::lvl0param>> result;
{
std::ifstream ifs{"result.data", std::ios::binary};
cereal::PortableBinaryInputArchive ar(ifs);
ar(result);
};
// decrypt and print plaintext answer
std::vector<uint8_t> p = bootsSymDecrypt(result, sk);
if (p[0])
std::cout << "Equall!" << std::endl;
else {
if (p[1])
std::cout << "Client is the millionaire!" << std::endl;
else
std::cout << "Cloud is the millionaire!" << std::endl;
}
} | 28.235294 | 67 | 0.59375 | [
"vector"
] |
7a6ddda7cd7e86414695aa36d769f44d289a696e | 1,685 | cc | C++ | drds/src/model/DescribeMyCatDbListRequest.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | null | null | null | drds/src/model/DescribeMyCatDbListRequest.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | null | null | null | drds/src/model/DescribeMyCatDbListRequest.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | 1 | 2020-11-27T09:13:12.000Z | 2020-11-27T09:13:12.000Z | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/drds/model/DescribeMyCatDbListRequest.h>
using AlibabaCloud::Drds::Model::DescribeMyCatDbListRequest;
DescribeMyCatDbListRequest::DescribeMyCatDbListRequest() :
RpcServiceRequest("drds", "2019-01-23", "DescribeMyCatDbList")
{
setMethod(HttpRequest::Method::Post);
}
DescribeMyCatDbListRequest::~DescribeMyCatDbListRequest()
{}
std::string DescribeMyCatDbListRequest::getSchemaUrl()const
{
return schemaUrl_;
}
void DescribeMyCatDbListRequest::setSchemaUrl(const std::string& schemaUrl)
{
schemaUrl_ = schemaUrl;
setParameter("SchemaUrl", schemaUrl);
}
std::string DescribeMyCatDbListRequest::getRegionId()const
{
return regionId_;
}
void DescribeMyCatDbListRequest::setRegionId(const std::string& regionId)
{
regionId_ = regionId;
setParameter("RegionId", regionId);
}
std::string DescribeMyCatDbListRequest::getRuleUrl()const
{
return ruleUrl_;
}
void DescribeMyCatDbListRequest::setRuleUrl(const std::string& ruleUrl)
{
ruleUrl_ = ruleUrl;
setParameter("RuleUrl", ruleUrl);
}
| 26.746032 | 76 | 0.75549 | [
"model"
] |
7a718ebed18027c3d9a2702cf9aec5dc43c0ff69 | 5,862 | hpp | C++ | src/Headers/Extensions/ProcessExtensions.hpp | BerkanYildiz/EasyNT | 60441e098cae9a28174d1eb9c119742ff15a8d2a | [
"MIT"
] | 5 | 2021-06-17T03:01:11.000Z | 2022-02-07T03:47:46.000Z | src/Headers/Extensions/ProcessExtensions.hpp | BerkanYildiz/EasyNT | 60441e098cae9a28174d1eb9c119742ff15a8d2a | [
"MIT"
] | null | null | null | src/Headers/Extensions/ProcessExtensions.hpp | BerkanYildiz/EasyNT | 60441e098cae9a28174d1eb9c119742ff15a8d2a | [
"MIT"
] | 1 | 2021-07-23T11:59:34.000Z | 2021-07-23T11:59:34.000Z | #pragma once
EXTERN_C NTSYSAPI NTSTATUS NTAPI ZwQuerySystemInformation(
IN SYSTEM_INFORMATION_CLASS SystemInformationClass,
OUT PVOID SystemInformation,
IN ULONG SystemInformationLength,
OUT PULONG ReturnLength OPTIONAL
);
EXTERN_C NTKERNELAPI NTSTATUS ZwQueryInformationProcess(
_In_ HANDLE ProcessHandle,
_In_ PROCESSINFOCLASS ProcessInformationClass,
_Out_ PVOID ProcessInformation,
_In_ ULONG ProcessInformationLength,
_Out_opt_ PULONG ReturnLength
);
EXTERN_C NTKERNELAPI PPEB NTAPI PsGetProcessPeb(
IN PEPROCESS Process
);
#define PROCESS_TERMINATE 0x0001
#define PROCESS_CREATE_THREAD 0x0002
#define PROCESS_SET_SESSIONID 0x0004
#define PROCESS_VM_OPERATION 0x0008
#define PROCESS_VM_READ 0x0010
#define PROCESS_VM_WRITE 0x0020
#define PROCESS_CREATE_PROCESS 0x0080
#define PROCESS_SET_QUOTA 0x0100
#define PROCESS_SET_INFORMATION 0x0200
#define PROCESS_QUERY_INFORMATION 0x0400
#define PROCESS_SET_PORT 0x0800
#define PROCESS_SUSPEND_RESUME 0x0800
#define PROCESS_QUERY_LIMITED_INFORMATION 0x1000
/// <summary>
/// Gets every processes information on the system.
/// </summary>
/// <param name="OutProcessEntries">The process entries.</param>
/// <param name="OutNumberOfProcessEntries">The number of entries in the buffer.</param>
NTSTATUS PsGetProcesses(OUT SYSTEM_PROCESS_INFORMATION** OutProcessEntries, OPTIONAL OUT ULONG* OutNumberOfProcessEntries = nullptr);
/// <summary>
/// Gets every processes information on the system matching a certain image file name.
/// </summary>
/// <param name="InProcessName">The process image filename.</param>
/// <param name="OutProcessEntries">The process entries.</param>
/// <param name="OutNumberOfProcessEntries">The number of entries in the buffer.</param>
NTSTATUS PsGetProcesses(UNICODE_STRING InProcessName, OUT SYSTEM_PROCESS_INFORMATION** OutProcessEntries, OPTIONAL OUT ULONG* OutNumberOfProcessEntries = nullptr);
/// <summary>
/// Gets every processes information on the system matching a certain image file name.
/// </summary>
/// <param name="InProcessName">The process image filename.</param>
/// <param name="OutProcessEntries">The process entries.</param>
/// <param name="OutNumberOfProcessEntries">The number of entries in the buffer.</param>
NTSTATUS PsGetProcesses(CONST WCHAR* InProcessName, OUT SYSTEM_PROCESS_INFORMATION** OutProcessEntries, OPTIONAL OUT ULONG* OutNumberOfProcessEntries = nullptr);
/// <summary>
/// Gets every processes information on the system matching a certain image file name.
/// </summary>
/// <param name="InProcessName">The process image filename.</param>
/// <param name="OutProcessEntries">The process entries.</param>
/// <param name="OutNumberOfProcessEntries">The number of entries in the buffer.</param>
NTSTATUS PsGetProcesses(CONST CHAR* InProcessName, OUT SYSTEM_PROCESS_INFORMATION** OutProcessEntries, OPTIONAL OUT ULONG* OutNumberOfProcessEntries = nullptr);
/// <summary>
/// Gets information about the process with the given filename.
/// </summary>
/// <param name="InProcessName">The process image filename.</param>
/// <param name="OutProcessInformation">The returned process information.</param>
NTSTATUS PsGetProcessInformation(UNICODE_STRING InProcessName, OUT SYSTEM_PROCESS_INFORMATION* OutProcessInformation);
/// <summary>
/// Gets information about the process with the given filename.
/// </summary>
/// <param name="InProcessName">The process image filename.</param>
/// <param name="OutProcessInformation">The returned process information.</param>
NTSTATUS PsGetProcessInformation(CONST WCHAR* InProcessName, OUT SYSTEM_PROCESS_INFORMATION* OutProcessInformation);
/// <summary>
/// Gets information about the process with the given filename.
/// </summary>
/// <param name="InProcessName">The process image filename.</param>
/// <param name="OutProcessInformation">The returned process information.</param>
NTSTATUS PsGetProcessInformation(CONST CHAR* InProcessName, OUT SYSTEM_PROCESS_INFORMATION* OutProcessInformation);
/// <summary>
/// Gets information about the process with the given process id.
/// </summary>
/// <param name="InProcessId">The process identifier.</param>
/// <param name="OutProcessInformation">The returned process information.</param>
NTSTATUS PsGetProcessInformation(CONST HANDLE InProcessId, OUT SYSTEM_PROCESS_INFORMATION* OutProcessInformation);
/// <summary>
/// Gets information about the process with the given process object.
/// </summary>
/// <param name="InProcess">The process object.</param>
/// <param name="OutProcessInformation">The returned process information.</param>
NTSTATUS PsGetProcessInformation(CONST PEPROCESS InProcess, OUT SYSTEM_PROCESS_INFORMATION* OutProcessInformation);
/// <summary>
/// Gets the image file path of the given process.
/// </summary>
/// <param name="InProcess">The process object.</param>
/// <param name="OutProcessName">The process image file path.</param>
NTSTATUS PsGetProcessImageFilePath(CONST PEPROCESS InProcess, OUT WCHAR** OutProcessName);
/// <summary>
/// Gets the image filename of the given process.
/// </summary>
/// <param name="InProcess">The process object.</param>
/// <param name="OutProcessName">The process image filename.</param>
NTSTATUS PsGetProcessImageFileName(CONST PEPROCESS InProcess, OUT WCHAR** OutProcessName);
/// <summary>
/// Terminates a process by its object with the given exit status.
/// </summary>
/// <param name="InProcess">The process object.</param>
/// <param name="InExitStatus">The exist status.</param>
NTSTATUS PsTerminateProcess(CONST PEPROCESS InProcess, NTSTATUS InExitStatus = STATUS_SUCCESS);
/// <summary>
/// Gets a value indicating whether the specified process is terminating.
/// </summary>
/// <param name="InProcess">The process.</param>
BOOLEAN PsProcessIsTerminating(CONST PEPROCESS InProcess);
| 45.796875 | 163 | 0.778574 | [
"object"
] |
7a773e8a8a3c6be1c3139a6c18b7d74230231c4f | 1,923 | cpp | C++ | Regression C++/VifRegression.cpp | KingJMS1/EEInformation | 887d2ac11e57e12360f62ce378a51ca74f628c87 | [
"MIT"
] | null | null | null | Regression C++/VifRegression.cpp | KingJMS1/EEInformation | 887d2ac11e57e12360f62ce378a51ca74f628c87 | [
"MIT"
] | null | null | null | Regression C++/VifRegression.cpp | KingJMS1/EEInformation | 887d2ac11e57e12360f62ce378a51ca74f628c87 | [
"MIT"
] | null | null | null | #include <Python.h>
#include "Reg.h"
static PyObject *VifRegression_regress(PyObject *self, PyObject *args) {
PyObject *xs;
PyObject *ys;
int m;
MatrixXd finalVals;
vector<int> finalVars;
if (!PyArg_ParseTuple(args, "iOO", &m, &xs, &ys)) {
return NULL;
}
if(!(PyList_Check(xs) && PyList_Check(ys))) {
printf("YOU MUST PASS TWO LISTS INTO THIS FUNCTION.");
return NULL;
}
MatrixXd xMatrix(PyList_Size(xs), PyList_Size(PyList_GetItem(xs, 0)));
VectorXd yMatrix(PyList_Size(ys));
Regresser a;
for(int i = 0; i < PyList_Size(xs); i++) {
PyObject *row = PyList_GetItem(xs, i);
for(int j = 0; j < PyList_Size(row); j++) {
xMatrix(i, j) = PyFloat_AsDouble(PyList_GetItem(row, j));
}
yMatrix(i) = PyFloat_AsDouble(PyList_GetItem(ys, i));
}
a.vifSelect(m, xMatrix, yMatrix, finalVals, finalVars);
PyObject *toRet = PyTuple_New(2);
PyObject *valList = PyList_New(finalVals.size());
PyObject *indexList = PyList_New(finalVars.size());
for(int i = 0; i < finalVals.size(); i++) {
PyList_SetItem(valList, i, PyFloat_FromDouble(finalVals(i)));
if(i >= 1) {
PyList_SetItem(indexList, i-1, PyFloat_FromDouble(finalVars.at(i-1)));
}
}
PyTuple_SetItem(toRet, 0, valList);
PyTuple_SetItem(toRet, 1, indexList);
return toRet;
}
static PyMethodDef VifRegressionMethods[] = {
{"regress", VifRegression_regress, METH_VARARGS, "Does a Vif Regression, takes int m, 2dlist xs, 1dlist ys"},
{NULL, NULL, 0, NULL}
};
static struct PyModuleDef VifRegression_definition = {
PyModuleDef_HEAD_INIT,
"VifRegression",
"A module to do a Vif Regression",
-1,
VifRegressionMethods
};
PyMODINIT_FUNC PyInit_VifRegression(void) {
Py_Initialize();
return PyModule_Create(&VifRegression_definition);
} | 30.046875 | 113 | 0.634945 | [
"vector"
] |
7a7ce71cee7d7a63643ca5b7ed8be7fd1eb2d309 | 828 | cpp | C++ | 630.cpp | BYOUINZAKA/LeetCodeNotes | 48e1b4522c1f769eeec4944cfbd57abf1281d09a | [
"MIT"
] | null | null | null | 630.cpp | BYOUINZAKA/LeetCodeNotes | 48e1b4522c1f769eeec4944cfbd57abf1281d09a | [
"MIT"
] | null | null | null | 630.cpp | BYOUINZAKA/LeetCodeNotes | 48e1b4522c1f769eeec4944cfbd57abf1281d09a | [
"MIT"
] | null | null | null | /*
* @Author: Hata
* @Date: 2020-05-11 13:59:17
* @LastEditors: Hata
* @LastEditTime: 2020-05-11 14:11:50
* @FilePath: \LeetCode\630.cpp
* @Description: https://leetcode-cn.com/problems/course-schedule-iii/
*/
#include <bits/stdc++.h>
class Solution
{
public:
int scheduleCourse(std::vector<std::vector<int>> &courses)
{
std::sort(courses.begin(), courses.end(), [](const auto &a, const auto &b) {
return a.back() < b.back();
});
std::priority_queue<int> queue;
int day = 0;
for (auto &&pair : courses)
{
queue.push(pair.front());
day += pair.front();
if (day > pair.back())
{
day -= queue.top();
queue.pop();
}
}
return queue.size();
}
}; | 24.352941 | 84 | 0.503623 | [
"vector"
] |
7a8095c72f4d349a26b0e14435c44dedd502634d | 1,500 | hpp | C++ | src/Builtins/Arithmetic/ArithmeticEvaluators.hpp | pawel-jarosz/nastya-lisp | 813a58523b741e00c8c27980fe658b546e9ff38c | [
"MIT"
] | 1 | 2021-03-12T13:39:17.000Z | 2021-03-12T13:39:17.000Z | src/Builtins/Arithmetic/ArithmeticEvaluators.hpp | pawel-jarosz/nastya-lisp | 813a58523b741e00c8c27980fe658b546e9ff38c | [
"MIT"
] | null | null | null | src/Builtins/Arithmetic/ArithmeticEvaluators.hpp | pawel-jarosz/nastya-lisp | 813a58523b741e00c8c27980fe658b546e9ff38c | [
"MIT"
] | null | null | null | //
// Created by caedus on 23.01.2021.
//
#pragma once
#include "Runtime/GenericEvaluatorFactory.hpp"
#include "Runtime/GenericEvaluator.hpp"
namespace nastya::builtins::arithmetic {
class AddEvaluator : public runtime::GenericEvaluator
, public runtime::GenericEvaluatorFactory<AddEvaluator>
{
public:
AddEvaluator() : runtime::GenericEvaluator{"+"} {}
typesystem::ObjectStorage evaluate(runtime::IMemory& memory, const typesystem::ObjectStorage& object) const override;
};
class SubtractionEvaluator : public runtime::GenericEvaluator
, public runtime::GenericEvaluatorFactory<SubtractionEvaluator>
{
public:
SubtractionEvaluator() : runtime::GenericEvaluator{"-"} {}
typesystem::ObjectStorage evaluate(runtime::IMemory& memory, const typesystem::ObjectStorage& object) const override;
};
class MultiplyEvaluator : public runtime::GenericEvaluator
, public runtime::GenericEvaluatorFactory<MultiplyEvaluator>
{
public:
MultiplyEvaluator() : runtime::GenericEvaluator{"*"} {}
typesystem::ObjectStorage evaluate(runtime::IMemory& memory, const typesystem::ObjectStorage& object) const override;
};
class DivisionEvaluator : public runtime::GenericEvaluator
, public runtime::GenericEvaluatorFactory<DivisionEvaluator>
{
public:
DivisionEvaluator() : runtime::GenericEvaluator{"/"} {}
typesystem::ObjectStorage evaluate(runtime::IMemory& memory, const typesystem::ObjectStorage& object) const override;
};
} | 34.090909 | 121 | 0.751333 | [
"object"
] |
7a8384623e0ad814f51ec5d2a8a3d07516a64d4a | 2,089 | hpp | C++ | parser/parser.hpp | maruthgoyal/sp | 582b58c568bafb6fe36e17f05cf4a9c4387d30d9 | [
"MIT"
] | 12 | 2017-10-05T14:49:22.000Z | 2018-07-29T12:42:14.000Z | parser/parser.hpp | maruthgoyal/bork | 582b58c568bafb6fe36e17f05cf4a9c4387d30d9 | [
"MIT"
] | null | null | null | parser/parser.hpp | maruthgoyal/bork | 582b58c568bafb6fe36e17f05cf4a9c4387d30d9 | [
"MIT"
] | null | null | null | /*
Copyright (c) 2017 Maruth Goyal
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 _USERS_MARUTHGOYAL_SP_PARSER_PARSER_HPP_
#define _USERS_MARUTHGOYAL_SP_PARSER_PARSER_HPP_
#include <string>
#include <vector>
namespace parser {
class thing;
class token;
class expression;
enum class type;
parser::thing *parse(std::string);
} // namespace parser
enum class parser::type {
TOKEN, EXPRESSION, EVALED
};
class parser::thing {
public:
type t;
};
class parser::token : public parser::thing {
std::string content;
public:
explicit token(const std::string &s) {
content.assign(s);
t = parser::type::TOKEN;
}
std::string get_content() {
return content;
}
void set_content(std::string s) {
content = s;
}
};
class parser::expression : public parser::thing {
public:
std::vector<parser::thing *> things;
expression() {
t = parser::type::EXPRESSION;
}
bool insert_thing(thing *t) {
if (t!=NULL) {
things.push_back(t);
return true;
}
return false;
}
};
#endif // _USERS_MARUTHGOYAL_SP_PARSER_PARSER_HPP_
| 20.086538 | 78 | 0.732408 | [
"vector"
] |
1866908069de7ed76bc7f2c162984b53aff14dfd | 24,915 | cpp | C++ | lib/runtime/Exe.cpp | rohitmaurya-png/Infinity-Programing-Langauge | 396dae993e174d190a2b58031eb0ec51fd10cc97 | [
"MIT"
] | null | null | null | lib/runtime/Exe.cpp | rohitmaurya-png/Infinity-Programing-Langauge | 396dae993e174d190a2b58031eb0ec51fd10cc97 | [
"MIT"
] | null | null | null | lib/runtime/Exe.cpp | rohitmaurya-png/Infinity-Programing-Langauge | 396dae993e174d190a2b58031eb0ec51fd10cc97 | [
"MIT"
] | null | null | null | //
//Created by Rohit Maurya 2/15/2020.
//
#include <cstdlib>
#include "Exe.h"
#include "../util/File.h"
#include "../util/KeyPair.h"
#include "symbols/Method.h"
#include "Manifest.h"
#include "symbols/Field.h"
#include "symbols/ClassObject.h"
#include "symbols/Object.h"
#include "../util/zip/zlib.h"
#include "main.h"
#include "VirtualMachine.h"
runtime::String tmpStr;
string exeErrorMessage;
uInt currentPos = 0;
bool validateAuthenticity(File::buffer& exe);
native_string& getString(File::buffer& exe, Int length = -1);
Int parseInt(File::buffer& exe);
int32_t geti32(File::buffer& exe);
Symbol* getSymbol(File::buffer& buffer);
void parseSourceFile(SourceFile &sourceFile, native_string &data);
int Process_Exe(std::string &exe)
{
File::buffer buffer;
Int processedFlags=0, currentFlag;
if(!File::exists(exe.c_str())){
exeErrorMessage = "file `" + exe + "` doesnt exist!\n";
return FILE_DOES_NOT_EXIST;
}
File::read_alltext(exe.c_str(), buffer);
if(buffer.empty()) {
exeErrorMessage = "file `" + exe + "` is empty.\n";
return EMPTY_FILE;
}
if(!validateAuthenticity(buffer)) {
exeErrorMessage = "file `" + exe + "` could not be ran.\n";
return FILE_NOT_AUTHENTIC;
}
if(buffer.at(currentPos++) != manif){
exeErrorMessage = "file `" + exe + "` may be corrupt";
return CORRUPT_MANIFEST;
}
for (;;) {
currentFlag = buffer.at(currentPos++);
processedFlags++;
switch (currentFlag) {
case 0x0:
case 0x0a:
case 0x0d:
case eoh:
processedFlags--;
break;
case 0x2:
vm.manifest.application = getString(buffer);
break;
case 0x4:
vm.manifest.version = getString(buffer);
break;
case 0x5:
vm.manifest.debug = buffer.at(currentPos++) == '1';
break;
case 0x6:
vm.manifest.entryMethod = geti32(buffer);
break;
case 0x7:
vm.manifest.methods = geti32(buffer);
break;
case 0x8:
vm.manifest.classes = geti32(buffer);
break;
case 0x9:
vm.manifest.fvers = parseInt(buffer);
break;
case 0x0c:
vm.manifest.strings = geti32(buffer);
break;
case 0x0e:
vm.manifest.target = parseInt(buffer);
break;
case 0x0f:
vm.manifest.sourceFiles = geti32(buffer);
break;
case 0x1b:
vm.manifest.threadLocals = geti32(buffer);
break;
case 0x1c:
vm.manifest.constants = geti32(buffer);
break;
default: {
exeErrorMessage = "file `" + exe + "` may be corrupt.\n";
return CORRUPT_MANIFEST;
}
}
if(currentFlag == eoh) {
if(processedFlags != HEADER_SIZE)
return CORRUPT_MANIFEST;
else if(vm.manifest.target > BUILD_VERS)
return UNSUPPORTED_BUILD_VERSION;
if(!(vm.manifest.fvers >= min_file_vers && vm.manifest.fvers <= file_vers)) {
stringstream err;
err << "unsupported file version of: " << vm.manifest.fvers << ". infinity supports file versions from `"
<< min_file_vers << "-" << file_vers << "` that can be processed. Are you possibly targeting the incorrect virtual machine?";
exeErrorMessage = err.str();
return UNSUPPORTED_FILE_VERS;
}
break;
}
}
if(buffer.at(currentPos++) != ssymbol){
exeErrorMessage = "file `" + exe + "` may be corrupt";
return CORRUPT_FILE;
}
/* Symbol section */
const Int nativeSymbolCount = 14;
uInt sourceFilesCreated=0;
uInt itemsProcessed=0;
uInt functionPointersProcessed=0;
vm.classes =(ClassObject*)malloc(sizeof(ClassObject)*vm.manifest.classes);
vm.methods = (Method*)malloc(sizeof(Method)*vm.manifest.methods);
vm.strings = (runtime::String*)malloc(sizeof(runtime::String)*(vm.manifest.strings)); // TODO: create "" string from compiler as the 0'th element
vm.constants = (double*)malloc(sizeof(double)*(vm.manifest.constants));
vm.staticHeap = (Object*)calloc(vm.manifest.classes, sizeof(Object));
vm.metaData.init();
vm.nativeSymbols = (Symbol*)malloc(sizeof(Symbol)*nativeSymbolCount);
vm.manifest.functionPointers = geti32(buffer);
vm.funcPtrSymbols = (Method*)malloc(sizeof(Method)*vm.manifest.functionPointers);
for(Int i = 0; i < nativeSymbolCount; i++) {
vm.nativeSymbols[i].init();
vm.nativeSymbols[i].type = (DataType)i;
}
if(vm.classes == NULL || vm.methods == NULL || vm.staticHeap == NULL
|| vm.strings == NULL || vm.constants == NULL) {
exeErrorMessage = "Failed to allocate memory for the program.";
return OUT_OF_MEMORY;
}
for (;;) {
currentFlag = buffer.at(currentPos++);
switch (currentFlag) {
case 0x0:
case 0x0a:
case 0x0d:
break;
case data_symbol: {
if(functionPointersProcessed >= vm.manifest.functionPointers) {
exeErrorMessage = "file `" + exe + "` may be corrupt";
return CORRUPT_FILE;
}
Method &method = vm.funcPtrSymbols[functionPointersProcessed++];
method.init();
method.fnType = fn_ptr;
Int paramSize = geti32(buffer);
if(paramSize > 0) {
method.params = (Param *) malloc(sizeof(Param) * paramSize);
for (Int i = 0; i < paramSize; i++) {
method.params[i].utype =
getSymbol(buffer);
method.params[i].isArray = buffer.at(currentPos++) == '1';
if(method.params[i].utype == NULL)
return CORRUPT_FILE;
}
}
method.utype = getSymbol(buffer);
method.arrayUtype = buffer.at(currentPos++) == '1';
if(method.utype == NULL)
return CORRUPT_FILE;
break;
}
case data_class: {
Int address = geti32(buffer);
if(address >= vm.manifest.classes || address < 0) {
exeErrorMessage = "file `" + exe + "` may be corrupt";
return CORRUPT_FILE;
}
ClassObject* klass = &vm.classes[address];
klass->init();
klass->address = address;
address = geti32(buffer);
if(address != -1) klass->owner = &vm.classes[address];
address = geti32(buffer);
if(address != -1) klass->super = &vm.classes[address];
klass->guid = geti32(buffer);
klass->name = getString(buffer);
klass->fullName = getString(buffer);
klass->staticFields = geti32(buffer);
klass->instanceFields = geti32(buffer);
klass->totalFieldCount = klass->staticFields + klass->instanceFields;
klass->methodCount = geti32(buffer);
klass->interfaceCount = geti32(buffer);
if(klass->totalFieldCount > 0)
klass->fields = (Field*)malloc(sizeof(Field)*klass->totalFieldCount);
if(klass->methodCount > 0)
klass->methods = (Method**)malloc(sizeof(Method**)*klass->methodCount);
if(klass->interfaceCount > 0)
klass->interfaces = (ClassObject**)malloc(sizeof(ClassObject**)*klass->interfaceCount);
itemsProcessed=0;
if(klass->totalFieldCount != 0) {
for( ;; ) {
if(buffer.at(currentPos) == data_field) {
if(itemsProcessed >= klass->totalFieldCount) {
exeErrorMessage = "file `" + exe + "` may be corrupt";
return CORRUPT_FILE;
}
currentPos++;
Field *field = &klass->fields[itemsProcessed++];
field->init();
field->name = getString(buffer);
field->fullName = getString(buffer);
field->address = geti32(buffer);
field->type = (DataType) geti32(buffer);
field->guid = geti32(buffer);
field->flags = geti32(buffer);
field->isArray = buffer.at(currentPos++) == '1';
field->threadLocal = buffer.at(currentPos++) == '1';
field->utype = getSymbol(buffer);
field->owner = &vm.classes[geti32(buffer)];
if(field->utype == NULL)
return CORRUPT_FILE;
} else if(buffer.at(currentPos) == 0x0 || buffer.at(currentPos) == 0x0a || buffer.at(currentPos) == 0x0d){ /* ignore */ }
else
break;
currentPos++;
}
if(itemsProcessed != klass->totalFieldCount) {
exeErrorMessage = "Failed to process all class fields in executable.";
return CORRUPT_FILE;
}
}
itemsProcessed = 0;
if(klass->methodCount != 0) {
for( ;; ) {
if(buffer.at(currentPos) == data_method) {
if(itemsProcessed >= klass->methodCount) {
exeErrorMessage = "file `" + exe + "` may be corrupt";
return CORRUPT_FILE;
}
currentPos++;
klass->methods[itemsProcessed++] = &vm.methods[geti32(buffer)];
} else if(buffer.at(currentPos) == 0x0 || buffer.at(currentPos) == 0x0a || buffer.at(currentPos) == 0x0d){ /* ignore */ }
else
break;
currentPos++;
}
if(itemsProcessed != klass->methodCount) {
exeErrorMessage = "Failed to process all class methods in executable.";
return CORRUPT_FILE;
}
}
itemsProcessed = 0;
if(klass->interfaceCount != 0) {
for( ;; ) {
if(buffer.at(currentPos) == data_interface) {
if(itemsProcessed >= klass->interfaceCount) {
exeErrorMessage = "file `" + exe + "` may be corrupt";
return CORRUPT_FILE;
}
currentPos++;
klass->interfaces[itemsProcessed++] = &vm.classes[geti32(buffer)];
} else if(buffer.at(currentPos) == 0x0 || buffer.at(currentPos) == 0x0a || buffer.at(currentPos) == 0x0d){ /* ignore */ }
else
break;
currentPos++;
}
if(itemsProcessed != klass->interfaceCount) {
exeErrorMessage = "Failed to process all interfaces in executable.";
return CORRUPT_FILE;
}
}
break;
}
case eos:
break;
default: {
exeErrorMessage = "file `" + exe + "` may be corrupt";
return CORRUPT_FILE;
}
}
if(currentFlag == eos) {
break;
}
}
/* String section */
itemsProcessed=0;
if(buffer.at(currentPos++) != sstring) {
exeErrorMessage = "file `" + exe + "` may be corrupt";
return CORRUPT_FILE;
}
for (;;) {
currentFlag = buffer.at(currentPos++);
switch (currentFlag) {
case 0x0:
case 0x0a:
case 0x0d:
break;
case data_string: {
if(itemsProcessed >= vm.manifest.strings) {
exeErrorMessage = "file `" + exe + "` may be corrupt";
return CORRUPT_FILE;
}
vm.strings[itemsProcessed].init();
vm.strings[itemsProcessed++] = getString(buffer, geti32(buffer));
break;
}
case eos:
break;
default: {
exeErrorMessage = "file `" + exe + "` may be corrupt";
return CORRUPT_FILE;
}
}
if (currentFlag == eos) {
if (itemsProcessed != vm.manifest.strings) {
exeErrorMessage = "Failed to process all strings in executable.";
return CORRUPT_FILE;
}
break;
}
}
/* Constants section */
itemsProcessed=0;
if(buffer.at(currentPos++) != sconst) {
exeErrorMessage = "file `" + exe + "` may be corrupt";
return CORRUPT_FILE;
}
for (;;) {
currentFlag = buffer.at(currentPos++);
switch (currentFlag) {
case 0x0:
case 0x0a:
case 0x0d:
break;
case data_const: {
if(itemsProcessed >= vm.manifest.constants) {
exeErrorMessage = "file `" + exe + "` may be corrupt";
return CORRUPT_FILE;
}
vm.constants[itemsProcessed++] = std::strtod(getString(buffer).str().c_str(), NULL);
break;
}
case eos:
break;
default: {
exeErrorMessage = "file `" + exe + "` may be corrupt";
return CORRUPT_FILE;
}
}
if (currentFlag == eos) {
if (itemsProcessed != vm.manifest.constants) {
exeErrorMessage = "Failed to process all constants in executable.";
return CORRUPT_FILE;
}
break;
}
}
if(buffer.at(currentPos) == data_compress) {
currentPos++;
// restructure buffer
stringstream buf, __outbuf__;
for(uInt i = currentPos; i < buffer.size(); i++) {
__outbuf__ << buffer.at(i);
}
Zlib zlib;
Zlib::AUTO_CLEAN=(true);
zlib.Decompress_Buffer2Buffer(__outbuf__.str(), buf);
buffer.end();
buffer << buf.str(); buf.str("");
currentPos = 0;
}
if(buffer.at(currentPos++) != sdata) {
exeErrorMessage = "file `" + exe + "` may be corrupt";
return CORRUPT_FILE;
}
/* Data section */
itemsProcessed = 0;
for (;;) {
currentFlag = buffer.at(currentPos++);
switch (currentFlag) {
case 0x0:
case 0x0a:
case 0x0d:
break;
case data_method: {
if(itemsProcessed >= vm.manifest.methods) {
exeErrorMessage = "file `" + exe + "` may be corrupt";
return CORRUPT_FILE;
}
Method* method = &vm.methods[itemsProcessed++];
method->init();
method->address = geti32(buffer);
method->guid = geti32(buffer);
method->name = getString(buffer);
method->fullName = getString(buffer);
method->sourceFile = geti32(buffer);
method->owner = &vm.classes[geti32(buffer)];
method->fnType = (function_type)geti32(buffer);
method->stackSize = geti32(buffer);
method->cacheSize = geti32(buffer);
method->flags = geti32(buffer);
method->nativeFunc = ((method->flags >> 9) & 1u);
method->delegateAddress = geti32(buffer);
method->fpOffset = geti32(buffer);
method->spOffset = geti32(buffer);
method->frameStackOffset = geti32(buffer);
method->utype = getSymbol(buffer);
method->arrayUtype = buffer.at(currentPos++) == '1';
Int paramSize = geti32(buffer);
method->paramSize = paramSize;
if(method->utype == NULL)
return CORRUPT_FILE;
if(paramSize > 0) {
method->params = (Param *) malloc(sizeof(Param) * paramSize);
for (Int i = 0; i < paramSize; i++) {
method->params[i].utype =
getSymbol(buffer);
method->params[i].isArray =
buffer.at(currentPos++) == '1';
if (method->params[i].utype == NULL)
return CORRUPT_FILE;
}
}
// if(c_options.jit) {
// if(method->address==316) method->isjit = true;
// if(method->address==7) method->isjit = true;
// }
long len = geti32(buffer);
for(Int i = 0; i < len; i++) {
Int pc = geti32(buffer);
Int line = geti32(buffer);
method->lineTable
.add(LineData(pc, line));
}
len = geti32(buffer);
for(Int i = 0; i < len; i++) {
TryCatchData &tryCatchData = method->tryCatchTable.__new();
tryCatchData.init();
tryCatchData.try_start_pc= geti32(buffer);
tryCatchData.try_end_pc= geti32(buffer);
tryCatchData.block_start_pc= geti32(buffer);
tryCatchData.block_end_pc= geti32(buffer);
Int caughtExceptions = geti32(buffer);
for(Int j =0; j < caughtExceptions; j++) {
CatchData &catchData = tryCatchData.catchTable.__new();
catchData.handler_pc = geti32(buffer);
catchData.localFieldAddress = geti32(buffer);
catchData.caughtException = &vm.classes[geti32(buffer)];
}
if(buffer.at(currentPos++) == 1) {
tryCatchData.finallyData = (FinallyData*)malloc(sizeof(FinallyData));
tryCatchData.finallyData->start_pc = geti32(buffer);
tryCatchData.finallyData->end_pc = geti32(buffer);
tryCatchData.finallyData->exception_object_field_address = geti32(buffer);
}
}
break;
}
case data_byte:
break;
default: {
exeErrorMessage = "file `" + exe + "` may be corrupt";
return CORRUPT_FILE;
}
}
if(currentFlag == data_byte) {
if(itemsProcessed != vm.manifest.methods)
throw std::runtime_error("data section may be corrupt");
currentPos--;
break;
}
}
itemsProcessed=0;
for (;;) {
currentFlag = buffer.at(currentPos++);
switch (currentFlag) {
case 0x0:
case 0x0a:
case 0x0d:
break;
case data_byte: {
if(itemsProcessed >= vm.manifest.methods) {
exeErrorMessage = "file `" + exe + "` may be corrupt";
return CORRUPT_FILE;
}
Method* method = &vm.methods[itemsProcessed++];
if(method->cacheSize > 0) {
method->bytecode = (opcode_instr*)malloc(sizeof(opcode_instr)*method->cacheSize);
for(int64_t i = 0; i < method->cacheSize; i++) {
method->bytecode[i] = geti32(buffer);
}
} else if(method->fnType != fn_delegate) {
exeErrorMessage = "method `" + method->fullName.str() + "` is missing bytecode";
return CORRUPT_FILE;
}
break;
}
case eos:
break;
default: {
exeErrorMessage = "file `" + exe + "` may be corrupt";
return CORRUPT_FILE;
}
}
if(currentFlag == eos) {
break;
}
}
if(buffer.at(currentPos++) != smeta) {
exeErrorMessage = "file `" + exe + "` may be corrupt";
return CORRUPT_FILE;
}
/* Meta Data Section */
for(;;) {
currentFlag = buffer.at(currentPos++);
switch (currentFlag) {
case 0x0:
case 0x0a:
case 0x0d:
break;
case data_file: {
SourceFile &sourceFile = vm.metaData.files.__new();
sourceFile.init();
sourceFile.name = getString(buffer);
if(vm.manifest.debug) {
String sourceFileData(getString(buffer, geti32(buffer)));
parseSourceFile(sourceFile, sourceFileData);
}
break;
}
case eos:
break;
default: {
exeErrorMessage = "file `" + exe + "` may be corrupt";
return CORRUPT_FILE;
}
}
if(currentFlag == eos) {
break;
}
}
buffer.end();
return 0;
}
void parseSourceFile(SourceFile &sourceFile, native_string &data) {
native_string line;
for(unsigned int i = 0; i < data.len; i++) {
if(data.chars[i] == '\n')
{
sourceFile.lines.__new().init();
sourceFile.lines.last() = line;
line.free();
} else {
line += data.chars[i];
}
}
sourceFile.lines.__new().init();
sourceFile.lines.last() = line;
line.free();
}
Symbol* getSymbol(File::buffer& buffer) {
DataType type = (DataType)geti32(buffer);
if((type >= _INT8 && type <= _UINT64)
|| type == VAR || type == OBJECT
|| type == NIL) {
return &vm.nativeSymbols[type];
} else if(type == CLASS) {
return &vm.classes[geti32(buffer)];
} else if(type == FNPTR) {
return &vm.funcPtrSymbols[geti32(buffer)];
} else {
exeErrorMessage = "invalid type found in symbol table";
return NULL;
}
}
int32_t geti32(File::buffer& exe) {
int32_t i32 =SET_i32(
exe.at(currentPos), exe.at(currentPos + 1),
exe.at(currentPos + 2), exe.at(currentPos + 3)
); currentPos+=EXE_BYTE_CHUNK;
return i32;
}
native_string& getString(File::buffer& exe, Int length) {
tmpStr.free();
if(length != -1) {
for (; length > 0; length--) {
tmpStr += exe.at(currentPos);
currentPos++;
}
} else {
while (exe.at(currentPos++) != nil) {
tmpStr += exe.at(currentPos - 1);
}
}
return tmpStr;
}
Int parseInt(File::buffer& exe) {
#if _ARCH_BITS == 32
return strtol(getString(exe).c_str(), NULL, 0);
#else
return strtoll(getString(exe).str().c_str(), NULL, 0);
#endif
}
native_string& string_forward(File::buffer& str, size_t begin, size_t end) {
tmpStr.free();
if(begin >= str.size() || end >= str.size())
throw std::invalid_argument("unexpected end of stream");
size_t it=0;
for(size_t i = begin; it++ < end; i++)
tmpStr +=str.at(i);
return tmpStr;
}
bool validateAuthenticity(File::buffer& exe) {
if(exe.at(currentPos++) == file_sig && string_forward(exe, currentPos, 3) == "SEF") {
currentPos += 3 + zoffset;
/* Check file's digital signature */
if(exe.at(currentPos++) == digi_sig1 && exe.at(currentPos++) == digi_sig2
&& exe.at(currentPos++) == digi_sig3) {
return true;
}
}
return false;
}
| 33.760163 | 149 | 0.476942 | [
"object"
] |
186cdab9bb21a7a8062fa824418f5bcf0550c915 | 9,702 | cpp | C++ | Src/Trainer.cpp | Arutsuyo/Smash.io | f251733c98aa024a2f018cdca90f390364930832 | [
"MIT"
] | null | null | null | Src/Trainer.cpp | Arutsuyo/Smash.io | f251733c98aa024a2f018cdca90f390364930832 | [
"MIT"
] | null | null | null | Src/Trainer.cpp | Arutsuyo/Smash.io | f251733c98aa024a2f018cdca90f390364930832 | [
"MIT"
] | 3 | 2021-11-05T23:19:58.000Z | 2021-11-05T23:21:08.000Z | #include "Trainer.h"
#include <fstream>
#include <signal.h>
#include <stdio.h>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#define FILENM "TRNR"
std::vector<int> Trainer::killpids;
Trainer* Trainer::_inst = NULL;
bool Trainer::term;
Config* Trainer::cfg;
// ISO locations, will step through
std::string Trainer::_ssbmisoLocs[] = {
"/mnt/f/Program Files/Dolphin-x64/iso/ssbm.gcm",
"/mnt/c/Program Files/Dolphin-x64/iso/ssbm.gcm",
"/mnt/c/User/Nara/Desktop/Dolphin-x64/iso/ssbm.gcm",
"/mnt/c/Users/aruts/OneDrive/UO/CIS 472/Project/ssbm.gcm",
"/home/zach/Desktop/CIS472/ssbm.gcm"
};
unsigned int Trainer::_isoidx = -1;
int Trainer::memoryCount = 0;
std::string Trainer::ssbmOverride = "";
// To be filled out in main
std::string Trainer::userDir = "";
std::string Trainer::dolphinDefaultUser = "";
std::string Trainer::PythonCommand = "python.exe";
std::string Trainer::modelName = "ssbm";
int Trainer::predictionType = LOAD_MODEL;
// Used for tracking events in the threads
std::mutex Trainer::mut;
std::condition_variable Trainer::cv;
unsigned Trainer::Concurent = 1;
VsType Trainer::vs = VsType::Self;
/* Helper Functions */
bool file_exists(const char* path)
{
if (FILE * file = fopen(path, "r")) {
fclose(file);
return true;
}
else {
return false;
}
}
// https://stackoverflow.com/q/18100097/2939859
bool dir_exists(const char* path)
{
struct stat info;
if (stat(path, &info) != 0)
{
fprintf(stderr, "%s:%d\t%s: %s\n", FILENM, __LINE__,
"--ERROR:stat", strerror(errno));
return false;
}
else if (S_ISDIR(info.st_mode))
return true;
else
return false;
}
void sigint_handle(int val)
{
if (val != SIGINT)
return;
printf("%s:%d\tReceived SIGINT, closing trainer\n", FILENM, __LINE__);
Trainer::term = true;
Trainer::_inst->KillDolphinHandles();
}
bool createSigIntAction()
{
// Create signal action
struct sigaction sa;
sa.sa_flags = 0;
sa.sa_handler = sigint_handle;
sigemptyset(&sa.sa_mask);
if (sigaction(SIGINT, &sa, NULL) == -1)
{
fprintf(stderr, "%s:%d: %s: %s\n", FILENM, __LINE__,
"--ERROR:sigaction", strerror(errno));
return false;
}
printf("%s:%d\tSignal Handler Created\n", FILENM, __LINE__);
return true;
}
void Trainer::KillDolphinHandles()
{
for (unsigned int i = 0; i < _Dhandles.size(); i++)
_Dhandles[i]->running = false;
}
void Trainer::GetVersionNumber(std::string& parsed)
{
char version[32];
std::fstream fs;
fs.open("Version/version.txt", std::fstream::in);
if (fs.fail())
{
fprintf(stderr, "%s:%d --Error: Version/version.txt is missing.\n", FILENM, __LINE__);
exit(EXIT_FAILURE);
}
fs.getline(version, 32);
fs.close();
Trainer::modelName = parsed + version;
printf("%s:%d\tUsing Model: %s\n", FILENM, __LINE__, modelName.c_str());
}
void Trainer::runTraining()
{
if (!GenerationManager::Initialize(modelName))
{
fprintf(stderr, "%s:%d --Error: Couldn't initialize GenerationManager\n", FILENM, __LINE__);
exit(EXIT_FAILURE);
}
//exit(EXIT_SUCCESS);
printf("%s:%d\tInitializing Training.\n", FILENM, __LINE__);
createSigIntAction();
switch (vs)
{
case Self:
printf("%s:%d\tPlaying vs Self\n", FILENM, __LINE__);
break;
case CPU:
printf("%s:%d\tPlaying vs CPU\n", FILENM, __LINE__);
break;
case Human:
printf("%s:%d\tPlaying vs Human\n", FILENM, __LINE__);
break;
default:
break;
}
unsigned int numCreate = vs == VsType::Human ? 1 : Concurent;
//int numCreate = 1;
printf("%s:%d\tRunning %d Instance%s\n", FILENM, __LINE__, numCreate, numCreate > 1 ? "s" : "");
// Cycle user folders to allow controllers to close completely.
unsigned int usernum = 0;
printf("%s:%d\tEntering Management Loop\n", FILENM, __LINE__);
printf("%s:%d\t--Stop the Trainer with CTRL+C\n", FILENM, __LINE__);
while (!term)
{
cv.notify_all();
std::unique_lock<std::mutex> lk(mut);
bool readyToCull = GenerationManager::GenerationReady();
while (!readyToCull && _Dhandles.size() < numCreate)
{
printf("%s:%d\tCreating Handler %lu\n", FILENM, __LINE__, _Dhandles.size());
DolphinHandle* dh = new DolphinHandle(vs);
_Dhandles.push_back(dh);
}
for (unsigned int i = 0; i < _Dhandles.size(); i++)
{
DolphinHandle* dh = _Dhandles[i];
if (!dh->started && !readyToCull)
{
lk.unlock();
cv.notify_all();
printf("%s:%d\tStarting(0) Dolphin Instance %d\n", FILENM, __LINE__, i);
if (!dh->StartDolphin(usernum++))
{
printf("%s:%d\t--ERROR: Dolphin Failed to start(0)\n", FILENM, __LINE__);
term = true;
break;
}
printf("%s:%d\tDolphin Instance %d Started(0)\n", FILENM, __LINE__, i);
cv.notify_all();
lk.lock();
}
}
if (term)
break;
printf("%s:%d\tChecking if running\n", FILENM, __LINE__);
for (unsigned int i = 0; i < _Dhandles.size(); i++)
{
DolphinHandle* dh = _Dhandles[i];
// Check if the match finished
if (!dh->running && dh->started)
{
printf("%s:%d\tDolphin Instance %d stopped\n", FILENM, __LINE__, i);
if (dh->safeclose)
printf("%s:%d\tDolphin Instance Closed safely\n", FILENM, __LINE__);
else
{
fprintf(stderr, "%s:%d\t--ERROR:Dolphin failed to close safely\n", FILENM, __LINE__);
term = true;
break;
}
dh->~DolphinHandle();
// Remove the handler, calling the destructor
_Dhandles.erase(_Dhandles.begin() + i);
if (!readyToCull)
{
// push a new one
DolphinHandle* dh = new DolphinHandle(vs);
lk.unlock();
cv.notify_all();
printf("%s:%d\tStarting(1) Dolphin Instance %d\n", FILENM, __LINE__, i);
if (!dh->StartDolphin(usernum++))
{
fprintf(stderr, "%s:%d\t--ERROR:Dolphin Failed to start(1)", FILENM, __LINE__);
term = true;
break;
}
printf("%s:%d\tDolphin Instance %d Started(1)\n", FILENM, __LINE__, i);
_Dhandles.push_back(dh);
cv.notify_all();
lk.lock();
}
}
}
if (term)
break;
if (readyToCull && !_Dhandles.size())
{
term = !GenerationManager::CullTheWeak();
// We can now load the new model!
if (predictionType == NEW_MODEL)
predictionType = LOAD_MODEL;
// Purge the old, in with the new
char buff[256];
memset(buff, 0, 256);
sprintf(buff, "rm -rf %s/ssbm*", Trainer::userDir.c_str());
system(buff);
}
printf("%s:%d\tWaiting for notification\n", FILENM, __LINE__);
// Lock the mutex and wait for the condition variable
cv.wait_for(lk, std::chrono::seconds(5));
}
}
Trainer::Trainer()
{
if (ssbmOverride.size())
{
if (!file_exists(ssbmOverride.c_str()))
{
fprintf(stderr, "%s:%d: %s\n", FILENM, __LINE__,
"--ERROR:GCM not found");
exit(EXIT_FAILURE);
}
else
{
printf("%s:%d\tUsing GCM:\n\t%s\n", FILENM, __LINE__,
ssbmOverride.c_str());
}
}
else
{
size_t n = sizeof(_ssbmisoLocs) / sizeof(_ssbmisoLocs[0]);
printf("%s:%d\tChecking %lu Locations\n", FILENM, __LINE__, n);
do {
_isoidx++;
if (_isoidx == n)
{
fprintf(stderr, "%s:%d: %s\n", FILENM, __LINE__,
"--ERROR:GCM not found");
exit(EXIT_FAILURE);
}
printf("%s:%d\tTesting for GCM:\n\t%s\n", FILENM, __LINE__, _ssbmisoLocs[_isoidx].c_str());
} while (!file_exists(_ssbmisoLocs[_isoidx].c_str()));
printf("%s:%d\tGCM Found: %s\n", FILENM, __LINE__, _ssbmisoLocs[_isoidx].c_str());
}
if (!cfg)
{
printf("%s:%d\tCreating Config\n", FILENM, __LINE__);
cfg = new Config(vs);
memoryCount = cfg->getMemlocationLines();
}
initialized = true;
_inst = this;
}
Trainer::~Trainer()
{
printf("%s:%d\tDestroying Trainer\n", FILENM, __LINE__);
if (cfg)
cfg->~Config();
printf("%s:%d\tClosing Handles\n", FILENM, __LINE__);
// Call each destructor
while (_Dhandles.size() > 0)
{
DolphinHandle* dh = _Dhandles[0];
dh->~DolphinHandle();
_Dhandles.pop_back();
}
}
| 29.852308 | 106 | 0.520614 | [
"vector",
"model"
] |
186d1830c690a19c219220f79060ffcb85087cdd | 15,692 | hpp | C++ | Plugins/AIOUSB/AIOUSB/deprecated/classlib/AnalogInputSubsystem.hpp | networkmodeling/RCVW | 0cd801c5b06824ea295594e227e78eef71d671cc | [
"Apache-2.0"
] | 1 | 2021-06-04T23:44:01.000Z | 2021-06-04T23:44:01.000Z | Plugins/AIOUSB/AIOUSB/deprecated/classlib/AnalogInputSubsystem.hpp | networkmodeling/RCVW | 0cd801c5b06824ea295594e227e78eef71d671cc | [
"Apache-2.0"
] | null | null | null | Plugins/AIOUSB/AIOUSB/deprecated/classlib/AnalogInputSubsystem.hpp | networkmodeling/RCVW | 0cd801c5b06824ea295594e227e78eef71d671cc | [
"Apache-2.0"
] | 2 | 2021-04-30T22:04:57.000Z | 2021-05-01T19:05:47.000Z | /*
* $RCSfile: AnalogInputSubsystem.hpp,v $
* $Revision: 1.26 $
* $Date: 2010/01/19 17:14:47 $
* jEdit:tabSize=4:indentSize=4:collapseFolds=1:
*
* class AnalogInputSubsystem declarations
*/
#if ! defined( AnalogInputSubsystem_hpp )
#define AnalogInputSubsystem_hpp
#include <AI16_InputRange.hpp>
#include <AI16_DataSet.hpp>
#include <DeviceSubsystem.hpp>
namespace AIOUSB {
class AI16_DataSet;
/**
* Class AnalogInputSubsystem represents the analog input subsystem of a device. One accesses
* this analog input subsystem through its parent object, typically through a method such as
* <i>adc() (see USB_AI16_Family::adc())</i>.
*/
class AnalogInputSubsystem : public DeviceSubsystem {
friend class USB_AI16_Family;
public:
/*
* A/D calibration modes; if ground or reference mode is selected, only one A/D
* sample may be taken at a time; that means, one channel and no oversampling;
* attempting to read more than one channel or use an oversample setting of more
* than zero will result in a timeout error
*/
/** Selects normal measurement mode <i>(see setCalMode( int calMode ))</i>. */
static const int CAL_MODE_NORMAL = 0; // normal measurement
/** Selects ground calibration mode <i>(see setCalMode( int calMode ))</i>. */
static const int CAL_MODE_GROUND = 1; // measure ground
/** Selects reference (full scale) calibration mode <i>(see setCalMode( int calMode ))</i>. */
static const int CAL_MODE_REFERENCE = 3; // measure reference
/*
* A/D trigger and counter bits
*/
/** If set, counter 0 is externally triggered <i>(see setTriggerMode( int triggerMode ))</i>. */
static const int TRIG_MODE_CTR0_EXT = 0x10; // 1 == counter 0 externally triggered
/** If set, the A/D is triggered by the falling edge of its trigger source, otherwise it's triggered by the rising edge <i>(see setTriggerMode( int triggerMode ))</i>. */
static const int TRIG_MODE_FALLING_EDGE = 0x08; // 1 == triggered by falling edge
/** If set, each trigger will cause the A/D to scan all the channels, otherwise the A/D will read a single channel with each trigger <i>(see setTriggerMode( int triggerMode ))</i>. */
static const int TRIG_MODE_SCAN = 0x04; // 1 == scan all channels, 0==single channel
/** If set, the A/D is triggered by an external pin on the board <i>(see setTriggerMode( int triggerMode ))</i>. */
static const int TRIG_MODE_EXTERNAL = 0x02; // 1 == triggered by external pin on board
/** If set, the A/D is triggered by counter 2 <i>(see setTriggerMode( int triggerMode ))</i>. */
static const int TRIG_MODE_TIMER = 0x01; // 1 == triggered by counter 2
/*
* range codes passed to setRange(); these values are defined by the device and must not be changed
*/
/** Unipolar, 0-10 volt range <i>(see setRange( int channel, int range ))</i>. */
static const int RANGE_0_10V = 0; // 0-10V
/** Bipolar, -10 to +10 volt range <i>(see setRange( int channel, int range ))</i>. */
static const int RANGE_10V = 1; // +/-10V
/** Unipolar, 0-5 volt range <i>(see setRange( int channel, int range ))</i>. */
static const int RANGE_0_5V = 2; // 0-5V
/** Bipolar, -5 to +5 volt range <i>(see setRange( int channel, int range ))</i>. */
static const int RANGE_5V = 3; // +/-5V
/** Unipolar, 0-2 volt range <i>(see setRange( int channel, int range ))</i>. */
static const int RANGE_0_2V = 4; // 0-2V
/** Bipolar, -2 to +2 volt range <i>(see setRange( int channel, int range ))</i>. */
static const int RANGE_2V = 5; // +/-2V
/** Unipolar, 0-1 volt range <i>(see setRange( int channel, int range ))</i>. */
static const int RANGE_0_1V = 6; // 0-1V
/** Bipolar, -1 to +1 volt range <i>(see setRange( int channel, int range ))</i>. */
static const int RANGE_1V = 7; // +/-1V
/** Minimum number of counts A/D can read. */
static const int MIN_COUNTS = 0;
/** Maximum number of counts A/D can read. */
static const int MAX_COUNTS = 0xffff;
/** Number of 16-bit words in an A/D calibration table (65,536 16-bit words). */
static const int CAL_TABLE_WORDS = 64 * 1024;
protected:
static const char RANGE_TEXT[][ 10 ];
protected:
/*
* register indexes
*/
static const int NUM_CONFIG_REGISTERS = 20; // number of "registers" (bytes) in config. block
static const int NUM_MUX_CONFIG_REGISTERS = 21; // number of "registers" (bytes) in config. block when MUX installed
static const int NUM_GAIN_CODE_REGISTERS = 16; // number of gain code (range) registers in config. block
static const int REG_GAIN_CODE = 0; // gain code (range) for A/D channel 0 (one of RANGE_* settings above)
// gain codes for channels 1-15 occupy configuration block indexes 1-15
static const int REG_CAL_MODE = 16; // calibration mode (one of CAL_MODE_* settings below)
static const int REG_TRIG_MODE = 17; // trigger mode (one of TRIG_MODE_* settings below)
static const int REG_START_END = 18; // start and end channels for scan (bits 7-4 contain end channel, bits 3-0 contain start channel)
static const int REG_OVERSAMPLE = 19; // oversample setting (0-255 samples in addition to single sample)
static const int REG_MUX_START_END = 20; // MUX start and end channels for scan (bits 7-4 contain end channel MS-nibble, bits 3-0 contain start channel MS-nibble)
static const int DIFFERENTIAL_MODE = 8; // OR with range to enable differential mode for channels 0-7
static const int MAX_OVERSAMPLE = 0xff;
static const int TRIG_MODE_VALID_MASK = (
TRIG_MODE_CTR0_EXT
| TRIG_MODE_FALLING_EDGE
| TRIG_MODE_SCAN
| TRIG_MODE_EXTERNAL
| TRIG_MODE_TIMER );
static const int AUTO_CAL_UNKNOWN = 0;
static const int AUTO_CAL_NOT_PRESENT = 1;
static const int AUTO_CAL_PRESENT = 2;
static const int MAX_CHANNELS = 128; // maximum number of channels supported by this software
int numChannels; // number of A/D channels
int numMUXChannels; // number of MUXed A/D channels
int channelsPerGroup; // number of A/D channels in each config. group (1, 4 or 8 depending on model)
int configBlockSize; // size of configuration block (bytes)
int autoCalFeature; // cached A/D auto. cal. feature
AI16_InputRange *inputRange; // range for each channel group
bool *differentialMode; // differential mode for each channel group
int calMode; // calibration mode (CAL_MODE_*)
int triggerMode; // trigger mode (TRIG_MODE_*)
int startChannel; // starting channel for scans
int endChannel; // ending channel for scans
int overSample; // over-samples
unsigned short *readBulkBuffer; // buffer used during bulk read procedure
int readBulkSamplesRequested; // total number of samples requested during bulk read procedure
int readBulkSamplesRetrieved; // number of samples retrieved so far during bulk read procedure
bool autoConfig; // true == automatically send modified configuration to device
public:
AnalogInputSubsystem &setScanRange( int startChannel, int numChannels );
AnalogInputSubsystem( USBDeviceBase &parent );
virtual ~AnalogInputSubsystem();
public:
/*
* properties
*/
virtual std::ostream &print( std::ostream &out );
/**
* Gets the number of primary analog input channels.
* @return Number of channels, numbered 0 to n-1.
*/
int getNumChannels() const {
return numChannels;
} // getNumChannels()
/**
* Gets the number of analog input channels available through an optional multiplexer.
* @return Number of channels, numbered 0 to n-1.
*/
int getNumMUXChannels() const {
return numMUXChannels;
} // getNumMUXChannels()
/**
* Gets the number of analog input channels in each configuration group (1, 4 or 8 depending on the device model).
* @return The number of channels per group.
*/
int getChannelsPerGroup() {
return channelsPerGroup;
} // getChannelsPerGroup()
bool isAutoCalPresent( bool force );
static std::string getRangeText( int range );
/*
* configuration
*/
/**
* Tells whether the modified configuration will be automatically sent to the device.
* @return <i>True</i> indicates that the modified configuration will be automatically sent to the device,
* <i>false</i> indicates that you will have to explicitly call <i>writeConfig()</i>
* to send the configuration to the device.
* @see setAutoConfig( bool autoConfig )
*/
bool isAutoConfig() const {
return autoConfig;
} // isAutoConfig()
/**
* Enables or disables automatically sending the modified configuration to the device. Normally, it's desirable
* to send the modified configuration to the device immediately. However, in order to reduce the amount of
* communication with the device while setting multiple properties, this automatic sending mechanism can be
* disabled and the configuration can be sent by explicitly calling <i>writeConfig()</i>
* once all the properties have been set, like so:
* <pre>device.adc()
* .setAutoConfig( false )
* .setCalMode( AnalogInputSubsystem::CAL_MODE_NORMAL )
* .setTriggerMode( AnalogInputSubsystem::TRIG_MODE_SCAN | AnalogInputSubsystem::TRIG_MODE_TIMER )
* .setOverSample( 50 )
* .writeConfig()
* .setAutoConfig( true );</pre>
* <i>Remember to call setAutoConfig( true ) after configuring the properties, otherwise all subsequent
* configuration changes will have to be explicitly sent to the device by calling writeConfig().</i>
* @param autoConfig <i>True</i> enables automatically sending modified configuration, <i>false</i> disables it.
* @return This subsystem, useful for chaining together multiple operations.
*/
AnalogInputSubsystem &setAutoConfig( bool autoConfig ) {
this->autoConfig = autoConfig;
return *this;
} // isAutoConfig()
AnalogInputSubsystem &readConfig();
AnalogInputSubsystem &writeConfig();
bool isDiscardFirstSample() const;
AnalogInputSubsystem &setDiscardFirstSample( bool discard );
/**
* Gets the current calibration mode.
* @return Current calibration mode (<i>AnalogInputSubsystem::CAL_MODE_NORMAL</i>,
* <i>AnalogInputSubsystem::CAL_MODE_GROUND</i> or <i>AnalogInputSubsystem::CAL_MODE_REFERENCE</i>).
* @see setCalMode( int calMode )
*/
int getCalMode() const {
return calMode;
} // getCalMode()
AnalogInputSubsystem &setCalMode( int calMode );
/**
* Gets the current trigger mode.
* @return Current trigger mode (bitwise OR of <i>TRIG_MODE_CTR0_EXT</i>, <i>TRIG_MODE_FALLING_EDGE</i>,
* <i>TRIG_MODE_SCAN</i>, <i>TRIG_MODE_EXTERNAL</i> or <i>TRIG_MODE_TIMER</i>).
* @see setTriggerMode( int triggerMode )
*/
int getTriggerMode() const {
return triggerMode;
} // getTriggerMode()
AnalogInputSubsystem &setTriggerMode( int triggerMode );
int getRange( int channel ) const;
IntArray getRange( int startChannel, int numChannels ) const;
AnalogInputSubsystem &setRange( int channel, int range );
AnalogInputSubsystem &setRange( int startChannel, const IntArray &range );
bool isDifferentialMode( int channel ) const;
BoolArray isDifferentialMode( int startChannel, int numChannels ) const;
AnalogInputSubsystem &setDifferentialMode( int channel, bool differentialMode );
AnalogInputSubsystem &setDifferentialMode( int startChannel, const BoolArray &differentialMode );
AnalogInputSubsystem &setRangeAndDiffMode( int channel, int range, bool differentialMode );
AnalogInputSubsystem &setRangeAndDiffMode( int startChannel, const IntArray &range, const BoolArray &differentialMode );
AnalogInputSubsystem &setRangeAndDiffMode( int range, bool differentialMode );
/**
* Gets the current number of over-samples.
* @return Current number of over-samples (0-255).
* @see setOverSample( int oversample )
*/
int getOverSample() const {
return overSample;
} // getOverSample()
AnalogInputSubsystem &setOverSample( int overSample );
AnalogInputSubsystem &setCalibrationTable( const std::string &fileName );
AnalogInputSubsystem &setCalibrationTable( const UShortArray &calTable );
/**
* Gets the current streaming block size.
* @return The current streaming block size. The value returned may not be the same as the value passed to
* <i>setStreamingBlockSize( int blockSize )</i> because that value is rounded up to a whole multiple of 512.
* @throws OperationFailedException
*/
int getStreamingBlockSize() {
return parent->getStreamingBlockSize();
} // getStreamingBlockSize()
/**
* Sets the streaming block size.
* @param blockSize the streaming block size you wish to set. This will be rounded up to the
* next multiple of 512.
* @return This subsystem, useful for chaining together multiple operations.
* @throws IllegalArgumentException
* @throws OperationFailedException
*/
AnalogInputSubsystem &setStreamingBlockSize( int blockSize ) {
parent->setStreamingBlockSize( blockSize );
return *this;
} // setStreamingBlockSize()
/**
* Gets the current clock frequency for timer-driven bulk reads <i>(see setClock( double clockHz ))</i>.
* @return The current frequency at which to take the samples (in Hertz).
*/
double getClock() {
return parent->getMiscClock();
} // getClock()
/**
* Sets the clock frequency for timer-driven bulk reads <i>(see getClock() and
* readBulkStart( int startChannel, int numChannels, int numSamples ))</i>.
* @param clockHz the frequency at which to take the samples (in Hertz).
* @return This subsystem, useful for chaining together multiple operations.
*/
AnalogInputSubsystem &setClock( double clockHz ) {
parent->setMiscClock( clockHz );
return *this;
} // setClock()
/*
* operations
*/
UShortArray calibrate( bool autoCal, bool returnCalTable, const std::string &saveFileName );
UShortArray calibrate( const DoubleArray &points, bool returnCalTable, const std::string &saveFileName );
AI16_DataSet *read( int startChannel, int numChannels );
unsigned short readCounts( int channel );
UShortArray readCounts( int startChannel, int numChannels );
double readVolts( int channel );
DoubleArray readVolts( int startChannel, int numChannels );
AnalogInputSubsystem &readBulkStart( int startChannel, int numChannels, int numSamples );
int readBulkSamplesAvailable();
UShortArray readBulkNext( int numSamples );
/**
* Clears the streaming FIFO, using one of several different methods.
* @param method the method to use when clearing the FIFO. May be one of:
* <i>USBDeviceBase::CLEAR_FIFO_METHOD_IMMEDIATE
* USBDeviceBase::CLEAR_FIFO_METHOD_AUTO
* USBDeviceBase::CLEAR_FIFO_METHOD_IMMEDIATE_AND_ABORT
* USBDeviceBase::CLEAR_FIFO_METHOD_WAIT</i>
* @return This subsystem, useful for chaining together multiple operations.
*/
AnalogInputSubsystem &clearFIFO( FIFO_Method method ) {
parent->clearFIFO( method );
return *this;
} // clearFIFO()
/*
* utilities
*/
double countsToVolts( int channel, unsigned short counts ) const;
DoubleArray countsToVolts( int startChannel, const UShortArray &counts ) const;
unsigned short voltsToCounts( int channel, double volts ) const;
UShortArray voltsToCounts( int startChannel, const DoubleArray &volts ) const;
}; // class AnalogInputSubsystem
} // namespace AIOUSB
#endif
/* end of file */
| 41.294737 | 185 | 0.701122 | [
"object",
"model"
] |
1870db6e1dc609c6df332d9a514e5e38557c3561 | 19,431 | cpp | C++ | src/drift_diff_fcts.cpp | giorgiopaulon/LDDMM | 2a59ca7fb81226c9fba03f07835fc6827193e897 | [
"MIT"
] | 2 | 2021-11-13T00:26:06.000Z | 2021-11-15T00:19:52.000Z | src/drift_diff_fcts.cpp | giorgiopaulon/LDDMM | 2a59ca7fb81226c9fba03f07835fc6827193e897 | [
"MIT"
] | null | null | null | src/drift_diff_fcts.cpp | giorgiopaulon/LDDMM | 2a59ca7fb81226c9fba03f07835fc6827193e897 | [
"MIT"
] | 1 | 2021-11-13T00:26:21.000Z | 2021-11-13T00:26:21.000Z |
#include <RcppArmadillo.h>
#include <progress.hpp>
#include <R_ext/Utils.h>
#include <RcppArmadilloExtensions/sample.h>
#include <math.h>
#include <rgen.h>
// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::depends(RcppProgress)]]
// [[Rcpp::depends(rgen)]]
// [[Rcpp::plugins(cpp11)]]
double dinvgaussian_cpp(arma::vec tau, arma::vec mu, arma::vec lambda,
arma::vec delta, bool log){
double out;
out = arma::accu(0.5 * (arma::log(lambda) - std::log(2.0 * arma::datum::pi)) -
3.0/2.0 * arma::log(tau - delta) -
lambda % arma::square(tau - delta - mu) / (2.0 * arma::square(mu) % (tau - delta)));
return(out);
}
double pinvgaussian_cpp(arma::vec tau, arma::vec mu, arma::vec lambda,
arma::vec delta, bool log){
double out;
out = arma::accu(arma::log(arma::abs(
1.0 -
arma::normcdf( arma::sqrt(lambda / (tau - delta)) % ((tau - delta) / mu - 1.0) ) -
arma::exp( 2.0 * lambda / mu +
arma::log(arma::normcdf( - arma::sqrt(lambda / (tau - delta)) % ((tau - delta) / mu + 1.0) )))
)));
return(out);
}
//' Log-likelihood computation
//'
//' Compute the log-likelihood for the drift-diffusion model, including the
//' censored data contribution.
//'
//' @param tau vector of size n containing the response times
//' @param mu matrix of size (n x d1) containing the drift parameters
//' corresponding to the n response times for each possible d1 decision
//' @param b matrix of size (n x d1) containing the boundary parameters
//' corresponding to the n response times for each possible d1 decision
//' @param delta vector of size n containing the offset parameters corresponding
//' to the n response times
//' @param cens vector of size n containing censoring indicators (1 censored, 0
//' not censored) corresponding to the n response times
//' @param D (n x 2) matrix whose first column has the n input stimuli, and whose second column has the n decision categories
//' @param log should the results be returned on the log scale?
// [[Rcpp::export]]
double log_likelihood(arma::vec tau, arma::mat mu, arma::mat b,
arma::vec delta, arma::uvec cens, arma::umat D,
bool log){
unsigned int d_1 = mu.n_cols;
arma::uvec one_to_d = arma::regspace<arma::uvec>(0, d_1 - 1);
arma::uvec idx_cens = arma::find(cens == 1);
arma::uvec idx_noncens = arma::find(cens == 0);
arma::uvec idx_nsupp = arma::find(tau <= delta);
arma::uvec yprime;
arma::uvec idx_succ;
arma::vec out(d_1*(d_1 + 1), arma::fill::zeros);
out -= arma::datum::inf;
unsigned int pos = 0;
// Computation is done on the log scale to prevent underflow/overflow
if (idx_nsupp.n_elem == 0){
for (unsigned int y_temp = 0; y_temp < d_1; y_temp++){
idx_succ = arma::find( (D.col(1) == (y_temp + 1)) && (cens == 0) );
if (idx_succ.n_elem > 0){
out(pos) = dinvgaussian_cpp(tau.elem(idx_succ), b.submat(idx_succ, arma::regspace<arma::uvec>(y_temp, y_temp))/mu.submat(idx_succ, arma::regspace<arma::uvec>(y_temp, y_temp)),
arma::square(b.submat(idx_succ, arma::regspace<arma::uvec>(y_temp, y_temp))), delta.elem(idx_succ), true);
}
else{
out(pos) = 0.0;
}
pos += 1;
yprime = one_to_d.elem(arma::find(one_to_d != y_temp));
for (unsigned int j = 0; j < d_1 - 1; j++){
if (idx_succ.n_elem > 0){
out(pos) = pinvgaussian_cpp(tau.elem(idx_succ), b.submat(idx_succ, arma::regspace<arma::uvec>(yprime(j), yprime(j)))/mu.submat(idx_succ, arma::regspace<arma::uvec>(yprime(j), yprime(j))),
arma::square(b.submat(idx_succ, arma::regspace<arma::uvec>(yprime(j), yprime(j)))), delta.elem(idx_succ), true);
}
else{
out(pos) = 0.0;
}
pos += 1;
}
}
if (idx_cens.n_elem > 0){
for (unsigned int y_temp = 0; y_temp < d_1; y_temp++){
out(pos) = pinvgaussian_cpp(tau.elem(idx_cens), b.submat(idx_cens, arma::regspace<arma::uvec>(y_temp, y_temp))/mu.submat(idx_cens, arma::regspace<arma::uvec>(y_temp, y_temp)),
arma::square(b.submat(idx_cens, arma::regspace<arma::uvec>(y_temp, y_temp))), delta.elem(idx_cens), true);;
pos += 1;
}
}
else{
for (unsigned int y_temp = 0; y_temp < d_1; y_temp++){
out(pos) = 0.0;
pos += 1;
}
}
}
if (out.has_nan()){
out.zeros();
out -= arma::datum::inf;
}
if (log){
return (arma::accu(out));
}
else{
return (exp(arma::accu(out)));
}
}
// Count Frequencies
//
// Analogous of the table function in R: computes the counts of the elements
// of an integer valued vector.
//
// @param x input vector of length n
// @param K maximum value that x can have (the support of x is /{1, ..., K/})
// @return vector of counts for every category
// [[Rcpp::export]]
arma::uvec table_int(arma::uvec x, unsigned int K){
unsigned int n = x.n_elem;
arma::uvec count(K, arma::fill::zeros); // here we consider that x has values in {1, ..., max(x)}
for (unsigned int i = 0; i < n; i++){
count[x[i] - 1] += 1;
}
return (count);
}
// Stable Sum of the Rows of a Matrix
//
// Sums the rows of a matrix defined on the log scale, returns the vector on
// the log scale.
//
// @param Q input matrix (with unnormalized log probabilities on the rows)
// @return vector with the sums (on the log scale)
// [[Rcpp::export]]
arma::vec sum_rows_log(arma::mat Q){
unsigned int S = Q.n_cols;
arma::vec out(S, arma::fill::zeros);
double m_star;
for (unsigned hh = 0; hh < S; hh++){
m_star = max(Q.row(hh));
if (m_star != - arma::datum::inf){
out(hh) = m_star + log(arma::accu(exp(Q.row(hh) - m_star)));
}
else{
out(hh) = - arma::datum::inf;
}
}
return (out);
}
// Stable Normalization
//
// Normalize a vector on the log scale with the log-sum-exp trick.
//
// @param x vector (on the log-scale) to be normalized
// @return normalized vector on the exponentiated scale
// [[Rcpp::export]]
arma::vec normalise_log(arma::vec x){
unsigned int n = x.n_elem;
double c = x.max();
x -= c;
arma::vec out(n);
out = arma::exp(x)/arma::accu(arma::exp(x));
return (out);
}
// Dirichlet Distribution
//
// Samples from the Dirichlet distribution.
//
// @param deltas vector of scale parameters
// @return one sample from the Dirichlet distribution
// [[Rcpp::export]]
arma::vec rdirichlet(arma::vec deltas){
arma::vec out = rgen::rdirichlet(deltas);
return (out);
}
// Count the Clustering Assignments
//
// Given the cluster memberships over time, count the clustering assignments
// to update the transition matrix.
//
// @param z matrix with cluster membership labels over time
// @param M max number of clusters
// @return count the transitions between states and return it into a (M x M)
// matrix
// [[Rcpp::export]]
arma::umat count_assign(arma::umat z, unsigned int M){
unsigned int d_1 = z.n_rows;
unsigned int K = z.n_cols;
arma::umat count(M, M, arma::fill::zeros);
for (unsigned int i = 0; i < d_1; i++){
for (unsigned int j = 1; j < K; j++){
count(z(i,j-1) - 1,z(i,j) - 1) += 1;
}
}
return (count);
}
// Random effects sampling
//
// Sample the random effect parameters for the drift parameters using
// Metropolis Hastings
//
// @param tau vector of size n containing the response times
// @param D (n x 2) matrix whose first column has the n input stimuli, and whose second column has the n decision categories
// @param cens vector of size n containing censoring indicators (1 censored, 0
// not censored) corresponding to the n response times
// @param beta_u_old old random effects spline coefficients
// @param delta_dat vector of size n containing the offset parameters corresponding
// to the n response times
// @param b_dat matrix of size (n x d1) containing the boundary parameters
// corresponding to the n response times for each possible d1 decision
// @param B_beta_dat old random effects spline coefficients expanded on the B Spline bases
// @param mu_dat_old matrix of size (n x d1) containing the old drift parameters
// corresponding to the n response times for each possible d1 decision
// @param B expansion of the blocks on the spline basis
// @param P smoothness inducing matrix (first order differences)
// @param ind vector denoting the individuals
// @param time vector denoting the time index
// @param sigma2_us smoothness parameter for the random effects
// @param sigma2_ua variance parameter for the random effects
// @param sd_beta_u standard deviation for the random walk proposal
// @param acc_beta_u acceptance rate for the random effects spline coefficients
// @return new random effects spline coefficients
// [[Rcpp::export]]
Rcpp::List sample_reff_mu(arma::vec tau, arma::umat D, arma::uvec cens,
arma::mat beta_u_old,
arma::vec delta_dat, arma::mat b_dat,
arma::mat B_beta_dat, arma::mat mu_dat_old,
arma::mat B, arma::mat P, arma::uvec ind,
arma::uvec time, double sigma2_us,
double sigma2_ua, arma::mat sd_beta_u,
arma::mat acc_beta_u){
arma::uvec un_ind = arma::unique(ind);
unsigned int n_ind = un_ind.n_elem;
unsigned int J = B.n_cols;
unsigned int n = tau.n_elem;
unsigned int d_1 = b_dat.n_cols;
arma::mat beta_u_prop(n_ind, J, arma::fill::zeros);
arma::mat B_beta_u_dat(n, d_1, arma::fill::zeros);
arma::mat B_beta_u_prop_dat, mu_dat_prop, temp;
arma::uvec idx_it, idx_i;
double l_u, alpha_acc, logpost_prop, logpost_old, logpr_prop, logpr_old;
for (unsigned int i = 1; i <= n_ind; i++){
for (unsigned int k = 0; k < J; k++){
// Propose new value
beta_u_prop.row(i-1) = beta_u_old.row(i-1);
beta_u_prop(i - 1,k) = beta_u_old(i - 1,k) + sd_beta_u(i - 1,k) * arma::randn();
if (k == 0){ // only data at t = 1 influence the first coefficient
idx_it = arma::find( (ind == i) && (time == 1) );
logpr_prop = - 0.5 * ( std::pow(beta_u_prop(i - 1,k), 2.0) / sigma2_ua +
std::pow(beta_u_prop(i - 1,k + 1) - beta_u_prop(i - 1,k), 2.0) / sigma2_us);
logpr_old = - 0.5 * ( std::pow(beta_u_old(i - 1,k), 2.0) / sigma2_ua +
std::pow(beta_u_old(i - 1,k + 1) - beta_u_old(i - 1,k), 2.0) / sigma2_us);
}
else if (k == (J - 1)){ // only data at t = T influence the last coefficient
idx_it = arma::find( (ind == i) && (time == (J - 1)) );
logpr_prop = - 0.5 * ( std::pow(beta_u_prop(i - 1,k), 2.0) / sigma2_ua +
std::pow(beta_u_prop(i - 1,k) - beta_u_prop(i - 1,k - 1), 2.0) / sigma2_us);
logpr_old = - 0.5 * ( std::pow(beta_u_old(i - 1,k), 2.0) / sigma2_ua +
std::pow(beta_u_old(i - 1,k) - beta_u_old(i - 1,k - 1), 2.0) / sigma2_us);
}
else { // data at t = {k-1,k} influence the kth coefficient
idx_it = arma::find( (ind == i) && ((time == k) || (time == k+1)) );
logpr_prop = - 0.5 * ( std::pow(beta_u_prop(i - 1,k), 2.0) / sigma2_ua +
std::pow(beta_u_prop(i - 1,k + 1) - beta_u_prop(i - 1,k), 2.0) / sigma2_us +
std::pow(beta_u_prop(i - 1,k) - beta_u_prop(i - 1,k - 1), 2.0) / sigma2_us);
logpr_old = - 0.5 * ( std::pow(beta_u_old(i - 1,k), 2.0) / sigma2_ua +
std::pow(beta_u_old(i - 1,k + 1) - beta_u_old(i - 1,k), 2.0) / sigma2_us +
std::pow(beta_u_old(i - 1,k) - beta_u_old(i - 1,k - 1), 2.0) / sigma2_us);
}
// Compute the implied \mu
B_beta_u_prop_dat = B.rows(idx_it) * beta_u_prop.row(i-1).t();
temp = B_beta_dat.rows(idx_it);
temp.each_col() += B_beta_u_prop_dat;
mu_dat_prop = arma::exp(temp);
// Evaluate log posterior
logpost_prop = log_likelihood(tau.elem(idx_it),
mu_dat_prop,
b_dat.rows(idx_it),
delta_dat.elem(idx_it),
cens.elem(idx_it),
D.rows(idx_it), true) +
logpr_prop;
logpost_old = log_likelihood(tau.elem(idx_it),
mu_dat_old.rows(idx_it),
b_dat.rows(idx_it),
delta_dat.elem(idx_it),
cens.elem(idx_it),
D.rows(idx_it), true) +
logpr_old;
// Acceptance rate
alpha_acc = logpost_prop - logpost_old;
l_u = std::log(arma::randu());
if (l_u < alpha_acc){
beta_u_old(i - 1,k) = beta_u_prop(i - 1,k);
mu_dat_old.rows(idx_it) = mu_dat_prop;
acc_beta_u(i - 1,k) += 1;
}
}
idx_i = arma::find(ind == i);
for (unsigned j = 0; j < d_1; j++){
B_beta_u_dat.submat(idx_i, arma::regspace<arma::uvec>(j, j)) = B.rows(idx_i) * beta_u_old.row(i-1).t();
}
}
return Rcpp::List::create(
Rcpp::Named("B_beta_u_dat")=B_beta_u_dat,
Rcpp::Named("beta_u_old")=beta_u_old,
Rcpp::Named("acc_beta_u")=acc_beta_u
);
}
// Random effects sampling
//
// Sample the random effect parameters for the boundary parameters using
// Metropolis Hastings
//
// @param tau vector of size n containing the response times
// @param D (n x 2) matrix whose first column has the n input stimuli, and whose second column has the n decision categories
// @param cens vector of size n containing censoring indicators (1 censored, 0
// not censored) corresponding to the n response times
// @param beta_u_old old random effects spline coefficients
// @param delta_dat vector of size n containing the offset parameters corresponding
// to the n response times
// @param B_beta_dat old random effects spline coefficients expanded on the B Spline bases
// @param b_dat_old matrix of size (n x d1) containing the old boundary parameters
// corresponding to the n response times for each possible d1 decision
// @param mu_dat matrix of size (n x d1) containing the drift parameters
// corresponding to the n response times for each possible d1 decision
// @param B expansion of the blocks on the spline basis
// @param P smoothness inducing matrix (first order differences)
// @param ind vector denoting the individuals
// @param time vector denoting the time index
// @param sigma2_us smoothness parameter for the random effects
// @param sigma2_ua variance parameter for the random effects
// @param sd_beta_u standard deviation for the random walk proposal
// @param acc_beta_u acceptance rate for the random effects spline coefficients
// @return new random effects spline coefficients
// [[Rcpp::export]]
Rcpp::List sample_reff_b(arma::vec tau, arma::umat D, arma::uvec cens,
arma::mat beta_u_old,
arma::vec delta_dat, arma::mat B_beta_dat,
arma::mat b_dat_old, arma::mat mu_dat, arma::mat B,
arma::mat P, arma::uvec ind, arma::uvec time,
double sigma2_us, double sigma2_ua, arma::mat sd_beta_u,
arma::mat acc_beta_u){
arma::uvec un_ind = arma::unique(ind);
unsigned int n_ind = un_ind.n_elem;
unsigned int J = B.n_cols;
unsigned int n = tau.n_elem;
unsigned int d_1 = mu_dat.n_cols;
arma::mat beta_u_prop(n_ind, J, arma::fill::zeros);
arma::mat B_beta_u_dat(n, d_1, arma::fill::zeros);
arma::mat B_beta_u_prop_dat, b_dat_prop, temp;
arma::uvec idx_it, idx_i;
double l_u, alpha_acc, logpost_prop, logpost_old, logpr_prop, logpr_old;
for (unsigned int i = 1; i <= n_ind; i++){
for (unsigned int k = 0; k < J; k++){
// Propose new value
beta_u_prop.row(i-1) = beta_u_old.row(i-1);
beta_u_prop(i - 1,k) = beta_u_old(i - 1,k) + sd_beta_u(i - 1,k) * arma::randn();
if (k == 0){ // only data at t = 1 influence the first coefficient
idx_it = arma::find( (ind == i) && (time == 1) );
logpr_prop = - 0.5 * ( std::pow(beta_u_prop(i - 1,k), 2.0) / sigma2_ua +
std::pow(beta_u_prop(i - 1,k + 1) - beta_u_prop(i - 1,k), 2.0) / sigma2_us);
logpr_old = - 0.5 * ( std::pow(beta_u_old(i - 1,k), 2.0) / sigma2_ua +
std::pow(beta_u_old(i - 1,k + 1) - beta_u_old(i - 1,k), 2.0) / sigma2_us);
}
else if (k == (J - 1)){ // only data at t = T influence the last coefficient
idx_it = arma::find( (ind == i) && (time == (J - 1)) );
logpr_prop = - 0.5 * ( std::pow(beta_u_prop(i - 1,k), 2.0) / sigma2_ua +
std::pow(beta_u_prop(i - 1,k) - beta_u_prop(i - 1,k - 1), 2.0) / sigma2_us);
logpr_old = - 0.5 * ( std::pow(beta_u_old(i - 1,k), 2.0) / sigma2_ua +
std::pow(beta_u_old(i - 1,k) - beta_u_old(i - 1,k - 1), 2.0) / sigma2_us);
}
else { // data at t = {k-1,k} influence the kth coefficient
idx_it = arma::find( (ind == i) && ((time == k) || (time == k+1)) );
logpr_prop = - 0.5 * ( std::pow(beta_u_prop(i - 1,k), 2.0) / sigma2_ua +
std::pow(beta_u_prop(i - 1,k + 1) - beta_u_prop(i - 1,k), 2.0) / sigma2_us +
std::pow(beta_u_prop(i - 1,k) - beta_u_prop(i - 1,k - 1), 2.0) / sigma2_us);
logpr_old = - 0.5 * ( std::pow(beta_u_old(i - 1,k), 2.0) / sigma2_ua +
std::pow(beta_u_old(i - 1,k + 1) - beta_u_old(i - 1,k), 2.0) / sigma2_us +
std::pow(beta_u_old(i - 1,k) - beta_u_old(i - 1,k - 1), 2.0) / sigma2_us);
}
// Compute the implied \mu
B_beta_u_prop_dat = B.rows(idx_it) * beta_u_prop.row(i-1).t();
temp = B_beta_dat.rows(idx_it);
temp.each_col() += B_beta_u_prop_dat;
b_dat_prop = arma::exp(temp);
// Evaluate log posterior
logpost_prop = log_likelihood(tau.elem(idx_it),
mu_dat.rows(idx_it),
b_dat_prop,
delta_dat.elem(idx_it),
cens.elem(idx_it),
D.rows(idx_it), true) +
logpr_prop;
logpost_old = log_likelihood(tau.elem(idx_it),
mu_dat.rows(idx_it),
b_dat_old.rows(idx_it),
delta_dat.elem(idx_it),
cens.elem(idx_it),
D.rows(idx_it), true) +
logpr_old;
alpha_acc = logpost_prop - logpost_old;
l_u = std::log(arma::randu());
if (l_u < alpha_acc){
beta_u_old(i - 1,k) = beta_u_prop(i - 1,k);
b_dat_old.rows(idx_it) = b_dat_prop;
acc_beta_u(i - 1,k) += 1;
}
}
idx_i = arma::find(ind == i);
for (unsigned j = 0; j < d_1; j++){
B_beta_u_dat.submat(idx_i, arma::regspace<arma::uvec>(j, j)) = B.rows(idx_i) * beta_u_old.row(i-1).t();
}
}
return Rcpp::List::create(
Rcpp::Named("B_beta_u_dat")=B_beta_u_dat,
Rcpp::Named("beta_u_old")=beta_u_old,
Rcpp::Named("acc_beta_u")=acc_beta_u
);
}
| 40.146694 | 198 | 0.590088 | [
"vector",
"model"
] |
187516909bd69b4637bf57ab9c4f59c9fb66e745 | 5,426 | cpp | C++ | src/Pathname.cpp | AnantaYudica/single_source | f95f0b2454efc48511d540c3c90ae39b087e102f | [
"MIT"
] | null | null | null | src/Pathname.cpp | AnantaYudica/single_source | f95f0b2454efc48511d540c3c90ae39b087e102f | [
"MIT"
] | null | null | null | src/Pathname.cpp | AnantaYudica/single_source | f95f0b2454efc48511d540c3c90ae39b087e102f | [
"MIT"
] | null | null | null | #include "Pathname.h"
#include <stack>
#include <utility>
using namespace std;
const string Pathname::ms_norm_conj_dir_str("/");
const string Pathname::ms_parent_dir_str("../");
const regex Pathname::ms_rep_conj_dir_regex("\\\\");
const regex Pathname::ms_dir_filename_regex("(.*[\\/\\\\])*(.*)");
const regex Pathname::ms_file_extname_regex("(.*)(\\..*)");
const regex Pathname::ms_search_dir_regex("([^\\/]*\\/)");
void Pathname::Normalize(string & pathname)
{
pathname = regex_replace(pathname, ms_rep_conj_dir_regex,
ms_norm_conj_dir_str);
vector<string> name_split;
ptrdiff_t diff = 0;
cmatch rslt;
pair<const char *, const char *> m_last_suffix;
while (regex_search(pathname.c_str() + diff, rslt, ms_search_dir_regex) &&
rslt.size() > 1)
{
name_split.push_back(rslt[1].str());
diff = rslt.suffix().first - pathname.c_str();
m_last_suffix.first = rslt.suffix().first;
m_last_suffix.second = rslt.suffix().second;
}
stack<string> name_stack;
string filename = string(m_last_suffix.first, m_last_suffix.second);
size_t count_skip = 0;
for(auto it = name_split.rbegin(); it != name_split.rend(); ++it)
{
if (it->compare(ms_parent_dir_str) == 0)
++count_skip;
else
{
if (count_skip != 0)
--count_skip;
else
name_stack.push(std::move(*it));
}
}
while(!name_stack.empty())
{
pathname.append(name_stack.top());
name_stack.pop();
}
pathname.append(filename);
}
void Pathname::DirFileExtname(const string & pathname,
IntervalType & dirname_strpos, IntervalType& filename_strpos,
IntervalType & extname_strpos)
{
smatch s_rslt;
cmatch c_rslt;
ptrdiff_t diff = 0;
if (regex_match(pathname, s_rslt, ms_dir_filename_regex) &&
s_rslt.size() > 2)
{
dirname_strpos.Begin(s_rslt[1].first);
dirname_strpos.End(s_rslt[1].second);
diff = s_rslt[2].first - pathname.begin();
}
else
{
dirname_strpos.Begin(pathname.begin());
dirname_strpos.End(pathname.end());
}
if (regex_match(pathname.c_str() + diff, c_rslt, ms_file_extname_regex) &&
c_rslt.size() > 2)
{
filename_strpos.Begin(pathname.begin() +
(c_rslt[1].first - pathname.c_str()));
filename_strpos.End(pathname.begin() +
(c_rslt[1].second - pathname.c_str()));
extname_strpos.Begin(pathname.begin() +
(c_rslt[2].first - pathname.c_str()));
extname_strpos.End(pathname.begin() +
(c_rslt[2].second - pathname.c_str()));
}
else
{
filename_strpos.Begin(pathname.end());
filename_strpos.End(pathname.end());
extname_strpos.Begin(pathname.end());
extname_strpos.End(pathname.end());
}
}
Pathname::Pathname() :
m_pathname_str("")
{
DirFileExtname(m_pathname_str, m_dirname_strpos,
m_filename_strpos, m_extname_strpos);
}
Pathname::Pathname(string pathname_str) :
m_pathname_str(std::move(pathname_str))
{
DirFileExtname(m_pathname_str, m_dirname_strpos,
m_filename_strpos, m_extname_strpos);
}
Pathname::Pathname(const Pathname & cpy) :
m_pathname_str(cpy.m_pathname_str)
{
DirFileExtname(m_pathname_str, m_dirname_strpos, m_filename_strpos,
m_extname_strpos);
}
Pathname::Pathname(Pathname && mov) :
m_pathname_str(std::move(mov.m_pathname_str)),
m_dirname_strpos(std::move(mov.m_dirname_strpos)),
m_filename_strpos(std::move(mov.m_filename_strpos)),
m_extname_strpos(std::move(mov.m_extname_strpos))
{}
Pathname & Pathname::operator=(const Pathname & cpy)
{
m_pathname_str = cpy.m_pathname_str;
DirFileExtname(m_pathname_str, m_dirname_strpos, m_filename_strpos,
m_extname_strpos);
return *this;
}
Pathname & Pathname::operator=(Pathname && mov)
{
m_pathname_str = std::move(mov.m_pathname_str);
m_dirname_strpos = std::move(mov.m_dirname_strpos);
m_filename_strpos = std::move(mov.m_filename_strpos);
m_extname_strpos = std::move(mov.m_extname_strpos);
return *this;
}
bool Pathname::operator==(const Pathname & pathname) const
{
return m_pathname_str.compare(pathname.m_pathname_str) == 0;
}
bool Pathname::operator!=(const Pathname & pathname) const
{
return !operator==(pathname);
}
string Pathname::String() const
{
return m_pathname_str;
}
string Pathname::DirectoryString() const
{
return string(m_dirname_strpos.Begin(), m_dirname_strpos.End());
}
string Pathname::FileString() const
{
return string(m_filename_strpos.Begin(), m_extname_strpos.End());
}
string Pathname::NameString() const
{
return string(m_filename_strpos.Begin(), m_filename_strpos.End());
}
std::string Pathname::ExtensionString() const
{
return string(m_extname_strpos.Begin(), m_extname_strpos.End());
}
bool Pathname::IsFile() const
{
return m_filename_strpos.Begin() != m_filename_strpos.End() ||
m_extname_strpos.Begin() != m_extname_strpos.End();
}
bool Pathname::IsDirectory() const
{
return m_dirname_strpos.Begin() != m_dirname_strpos.End() &&
m_filename_strpos.Begin() == m_filename_strpos.End() &&
m_extname_strpos.Begin() == m_extname_strpos.End();
}
Pathname::operator bool() const
{
return !m_pathname_str.empty();
}
| 27.543147 | 79 | 0.661998 | [
"vector"
] |
187bf7d215d7373beb9c3444e3d72c5368e90484 | 788 | cpp | C++ | src/Lab07-Vectors/TwoDArrayUsingVector.cpp | AGithub457/CompsciSpring2018 | 5663b7aeafd68e96c98036416abe7a9060fb3560 | [
"MIT"
] | null | null | null | src/Lab07-Vectors/TwoDArrayUsingVector.cpp | AGithub457/CompsciSpring2018 | 5663b7aeafd68e96c98036416abe7a9060fb3560 | [
"MIT"
] | null | null | null | src/Lab07-Vectors/TwoDArrayUsingVector.cpp | AGithub457/CompsciSpring2018 | 5663b7aeafd68e96c98036416abe7a9060fb3560 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
int sum(const vector<vector<int> > &array) {
int total = 0;
for (int row = 0; row < array.size(); row++) {
for (int column = 0; column < array[row].size(); column++) {
total += array[row][column];
}
}
return total;
}
int main() {
vector<vector<int> > array(4); // four rows
for (int i = 0; i < 4; i++)
array[i] = vector<int>(3);
array[0][0] = 1;
array[0][1] = 2;
array[0][2] = 3;
array[1][0] = 4;
array[1][1] = 5;
array[1][2] = 6;
array[2][0] = 7;
array[2][1] = 8;
array[2][2] = 9;
array[3][0] = 10;
array[3][1] = 11;
array[3][2] = 12;
cout << "Sum of all elements is " << sum(array) << endl;
return 0;
}
| 19.7 | 68 | 0.482234 | [
"vector"
] |
187ea95b5cf98c3b318853829e30deaf58c8ad03 | 11,898 | cpp | C++ | src/interface_generator.cpp | kpengk/Mercury | 68350b917eabc0b14f2887b706f80f42de420440 | [
"MIT"
] | null | null | null | src/interface_generator.cpp | kpengk/Mercury | 68350b917eabc0b14f2887b706f80f42de420440 | [
"MIT"
] | null | null | null | src/interface_generator.cpp | kpengk/Mercury | 68350b917eabc0b14f2887b706f80f42de420440 | [
"MIT"
] | null | null | null | #include "interface_generator.h"
#include <unordered_map>
#include <filesystem>
#include <fstream>
#include <regex>
#include <set>
#include <clang/Tooling/Tooling.h>
#include <inja/inja.hpp>
#include <nlohmann/json.hpp>
#include "analysis_action.h"
#include "uuid.hpp"
namespace glasssix::ymer
{
namespace
{
static std::string replace_regex(std::string_view str, std::string_view old_value, std::string_view new_value)
{
const std::regex reg_str(old_value.data());
return std::regex_replace(str.data(), reg_str, new_value.data());
}
static void replace_text(std::string& str, std::string_view old_value, std::string_view new_value)
{
for (std::string::size_type pos{ 0 }; pos != std::string::npos; pos += new_value.length()) {
if ((pos = str.find(old_value, pos)) != std::string::npos)
str.replace(pos, old_value.length(), new_value);
else
break;
}
}
static bool is_base_type(std::string_view type)
{
static std::set<std::string> base_type{
u8"int8", u8"int16", u8"int32", u8"int64", u8"int",
u8"uint8", u8"uint16", u8"uint32", u8"uint64",
u8"float", u8"double", u8"_Bool", u8"bool", u8"char"
};
return base_type.find(type.data()) != base_type.cend();
}
static std::string read_file(std::string_view file, bool* ok = nullptr)
{
std::ifstream ifs(file.data());
if (!ifs.is_open())
{
fprintf(stderr, u8"\033[31mOpen file error. [%s].\n\033[0m", file.data());
if (ok)
*ok = false;
return std::string();
}
ifs.seekg(0, std::ios::end);
const size_t len = ifs.tellg();
ifs.seekg(0, std::ios::beg);
std::string buffer(len, ' ');
ifs.read(buffer.data(), len);
ifs.close();
if (ok)
*ok = true;
return buffer;
}
static bool generate_code_file(std::string_view code_file_name, std::string_view template_code, const nlohmann::json& obj)
{
std::ofstream ofs(code_file_name.data());
if (!ofs.is_open())
{
fprintf(stderr, u8"open output file error. [%s].\n", code_file_name.data());
return false;
}
try
{
inja::render_to(ofs, template_code, obj);
}
catch (const std::exception& e)
{
fprintf(stderr, u8"\033[31mGenerate code error, exception: %s.\n\033[0m", e.what());
ofs.close();
return false;
}
ofs.close();
return true;
}
static std::vector<std::string> depend_header(const std::string& code)
{
static const std::regex pattern(R"(#\s*include\s*[<"]\s*([\w/\\]+)[\.]?[hpxc]*\s*[>"])");
std::vector<std::string> result;
std::smatch match_result;
auto iter_start = code.cbegin();
auto iter_end = code.cend();
while (regex_search(iter_start, iter_end, match_result, pattern))
{
assert(match_result.size() == 2);
result.push_back(match_result.str(1));
iter_start = match_result[0].second;
}
return result;
}
}
class interface_generator::impl
{
public:
bool load_field_map(std::string_view file_name)
{
field_mapping_.clear();
std::ifstream ifs(file_name.data());
if (!ifs.is_open())
{
return false;
}
nlohmann::json field_json;
ifs >> field_json;
ifs.close();
if (field_json.empty())
{
return false;
}
if (!field_json.contains(u8"field_map"))
{
return false;
}
field_json.at(u8"field_map").get_to(field_mapping_);
return true;
}
bool load_predefined(std::string_view file_name)
{
predefined_file_ = file_name;
bool ok{};
read_file(file_name, &ok);
return ok;
}
bool load_template(std::string_view interface_file, std::string_view impl_file, std::string_view func_file)
{
template_code_ = read_file(interface_file);
impl_template_code_ = read_file(impl_file);
func_template_code_ = read_file(func_file);
return !(template_code_.empty() || impl_template_code_.empty() || func_template_code_.empty());
}
void set_include_path(std::vector<std::string> dirs)
{
run_args_.clear();
for (std::string_view path : dirs)
{
run_args_.push_back(std::string(u8"-I").append(path));
}
}
std::string_view set_output_path(std::string_view path)
{
if (path.empty())
path = "./";
auto syspath = std::filesystem::path(path);
if (!std::filesystem::exists(syspath))
{
std::filesystem::create_directories(syspath);
}
std::string str_path = std::filesystem::absolute(syspath).string();
if (const char last = *(--str_path.end()); last != '\\' && last != '/')
{
#ifdef _WIN32
str_path.push_back('\\');
#else
str_path.push_back('/');
#endif // WIN32_
}
output_path_ = str_path;
return output_path_;
}
bool run_file(std::string_view file_name)
{
// read file
bool ok;
std::string code = read_file(file_name, &ok);
if (!ok)
{
return false;
}
return run_code(code);
}
bool run_code(std::string_view code)
{
interface_json_.clear();
std::vector<ymer::interface_decl> all_class_info;
if (code.empty() || !analysis(code, all_class_info) || all_class_info.empty())
{
return false;
}
auto decl = --all_class_info.end();
if (decl->functions.empty() && decl->fields.empty())
{
return false;
}
// Interface fields to function
for (const param_decl& field : decl->fields)
{
if (field.attr == 0)//set
{
function_decl fun_decl;
fun_decl.func_name = u8"set_" + field.name;
fun_decl.is_const_func = false;
fun_decl.return_type = u8"void";
fun_decl.return_void = true;
fun_decl.params = { field };
decl->functions.push_back(fun_decl);
}
else if (field.attr == 1)//get
{
function_decl fun_decl;
fun_decl.func_name = u8"get_" + field.name;
fun_decl.is_const_func = true;
fun_decl.return_type = field.type;
fun_decl.return_void = false;
decl->functions.push_back(fun_decl);
}
else if (field.attr == 2)//set-get
{
function_decl set_fun_decl;
set_fun_decl.func_name = u8"set_" + field.name;
set_fun_decl.is_const_func = false;
set_fun_decl.return_type = u8"void";
set_fun_decl.return_void = true;
param_decl param = field;
param.attr = 0;
set_fun_decl.params = { param };
decl->functions.push_back(set_fun_decl);
function_decl get_fun_decl;
get_fun_decl.func_name = u8"get_" + field.name;
get_fun_decl.is_const_func = true;
get_fun_decl.return_type = field.type;
get_fun_decl.return_void = false;
decl->functions.push_back(get_fun_decl);
}
}
return generator(*decl);
}
std::vector<std::string> function_signature()
{
if (interface_json_.empty())
{
return std::vector<std::string>();
}
std::string func_interface;
try
{
func_interface = inja::render(func_template_code_, interface_json_);
}
catch (const std::exception& e)
{
fprintf(stderr, u8"\033[31mGenerate code error, exception: %s.\n\033[0m", e.what());
return std::vector<std::string>();
}
if (func_interface.empty())
return std::vector<std::string>();
std::vector<std::string> funcs;
for (std::string::size_type pos{ 0 }; pos != std::string::npos;) {
auto idx = func_interface.find('\n', pos);
if (idx != std::string::npos)
funcs.push_back(func_interface.substr(pos, idx - pos));
else
break;
pos = idx + 1;
}
return funcs;
}
bool analysis(std::string_view code, std::vector<ymer::interface_decl>& result)
{
const auto& header = depend_header(code.data());
// pretreatment
std::string whole_code = "#include \"" + predefined_file_ + "\"\n" + code.data();
static const std::array<std::string, 5> attributes{ u8"in", u8"out", u8"inout", u8"set", u8"get" };
for (std::string_view attr : attributes)
{
char old_str[64]{};
char new_str[64]{};
sprintf_s(old_str, sizeof(old_str), u8"\\[\\s*\\[\\s*%s\\s*\\]\\s*\\]", attr.data());
sprintf_s(new_str, sizeof(new_str), u8"__attribute__((annotate(\"%s\")))", attr.data());
whole_code = replace_regex(whole_code, old_str, new_str);
}
// run
const bool ret = clang::tooling::runToolOnCodeWithArgs(std::make_unique<ymer::analysis_action>(result), whole_code.c_str(), run_args_);
if (ret)
{
(--result.end())->depend_class = header;
}
return ret;
}
bool generator(const interface_decl& decl)
{
// Transfer interface parameters to JSON
interface_json_ = to_json(decl);
const std::string code_file_name = output_path_ + decl.class_name + ".hpp";
bool ret = generate_code_file(code_file_name, template_code_, interface_json_);
const std::string code_impl_file_name = output_path_ + decl.class_name + "_impl.hpp";
ret &= generate_code_file(code_impl_file_name, impl_template_code_, interface_json_);
return ret;
}
std::string to_std_type(const std::string& type) const
{
std::string result = type;
replace_text(result, "struct ", "");
const auto iter = field_mapping_.find(type);
if (iter != field_mapping_.end())
{
result = iter->second;
}
else
{
for (const auto& field : field_mapping_)
{
replace_text(result, field.first, field.second);
}
}
return result;
}
nlohmann::json to_json(const interface_decl& decl)
{
nlohmann::json interface_json;
interface_json[u8"depend_class"] = decl.depend_class;
interface_json[u8"package_name"] = decl.package_name;
interface_json[u8"class_name"] = decl.class_name;
interface_json[u8"guid"] = glasssix::uuid::generate();
nlohmann::json all_func_json = nlohmann::json::array();;
for (const auto& func_decl : decl.functions)
{
nlohmann::json func_json;
func_json[u8"func_name"] = func_decl.func_name;
func_json[u8"return_type"] = to_std_type(func_decl.return_type);
func_json[u8"is_const_func"] = func_decl.is_const_func;
func_json[u8"return_void"] = func_decl.return_void;
nlohmann::json all_param_json = nlohmann::json::array();
for (const auto& param : func_decl.params)
{
nlohmann::json param_json;
param_json[u8"attr"] = param.attr;
param_json[u8"type"] = to_std_type(param.type);
param_json[u8"base_type"] = is_base_type(param.type);
param_json[u8"name"] = param.name;
all_param_json.push_back(param_json);
}
func_json[u8"params"] = all_param_json;
all_func_json.push_back(func_json);
}
interface_json[u8"functions"] = all_func_json;
return interface_json;
}
private:
std::string predefined_file_;
std::string template_code_;
std::string impl_template_code_;
std::string func_template_code_;
std::string output_path_;
std::vector<std::string> run_args_;
std::unordered_map<std::string, std::string> field_mapping_;
nlohmann::json interface_json_;
};
interface_generator::interface_generator()
:impl_(std::make_unique<impl>())
{
}
interface_generator::~interface_generator()
{
}
bool interface_generator::load_field_map(std::string_view file_name)
{
return impl_->load_field_map(file_name);
}
bool interface_generator::load_predefined(std::string_view file_name)
{
return impl_->load_predefined(file_name);
}
bool interface_generator::load_template(std::string_view interface_file, std::string_view impl_file, std::string_view func_file)
{
return impl_->load_template(interface_file, impl_file, func_file);
}
void interface_generator::set_include_path(std::vector<std::string> dirs)
{
impl_->set_include_path(dirs);
}
std::string_view interface_generator::set_output_path(std::string_view path)
{
return impl_->set_output_path(path);
}
bool interface_generator::run_file(std::string_view file_name)
{
return impl_->run_file(file_name);
}
bool interface_generator::run_code(std::string_view code)
{
return impl_->run_code(code);
}
std::vector<std::string> interface_generator::function_signature()
{
return impl_->function_signature();
}
}
| 25.314894 | 138 | 0.664818 | [
"render",
"vector"
] |
188d99cace0d922208f8cbc6be02df01e7a2e41e | 15,551 | cpp | C++ | src/desktop-view.cpp | dingjingmaster/desktop-view | 88b6de026b8b1693c77c61835e92eee29cdc6876 | [
"MIT"
] | null | null | null | src/desktop-view.cpp | dingjingmaster/desktop-view | 88b6de026b8b1693c77c61835e92eee29cdc6876 | [
"MIT"
] | null | null | null | src/desktop-view.cpp | dingjingmaster/desktop-view | 88b6de026b8b1693c77c61835e92eee29cdc6876 | [
"MIT"
] | null | null | null | #include "desktop-view.h"
#include <QRect>
#include "private/qabstractitemview_p.h"
#include <QtWidgets/private/qtwidgetsglobal_p.h>
#include <QApplication>
#include <QPaintEvent>
#include <QPainter>
#include <QDropEvent>
#include <QDebug>
#define SCREEN_ID 1000
#define RELATED_GRID_POSITION 1001
#define ICONVIEW_PADDING 5
#define INVALID_POS QPoint(-1, -1)
DesktopView::DesktopView(QWidget *parent) : QAbstractItemView(parent)
{
m_rubberBand = new QRubberBand(QRubberBand::Rectangle, this);
setDragDropMode(QAbstractItemView::DragDrop);
setDragEnabled(true);
setSelectionMode(QAbstractItemView::ExtendedSelection);
// init grid size
setIconSize(QSize(64, 64));
setWindowFlag(Qt::FramelessWindowHint);
QIcon::setThemeName("ukui-icon-theme-default");
for (auto qscreen : qApp->screens()) {
auto screen = new Screen(qscreen, m_gridSize, this);
addScreen(screen);
}
}
Screen *DesktopView::getScreen(int screenId)
{
if (m_screens.count() > screenId) {
return m_screens.at(screenId);
} else {
return nullptr;
}
}
void DesktopView::addScreen(Screen *screen)
{
connect(screen, &Screen::screenVisibleChanged, this, [=](bool visible){
if (!visible) {
removeScreen(screen);
}
});
m_screens<<screen;
}
void DesktopView::swapScreen(Screen *screen1, Screen *screen2)
{
// primary screen should alwayls be the header of list.
if (!screen1 || !screen2) {
qCritical()<<"invalide screen arguments";
return;
}
auto s1 = screen1->getScreen();
auto s2 = screen2->getScreen();
screen1->rebindScreen(s2);
screen2->rebindScreen(s1);
// list操作
int index1 = m_screens.indexOf(screen1);
int index2 = m_screens.indexOf(screen2);
m_screens.replace(index1, screen2);
m_screens.replace(index2, screen1);
this->handleScreenChanged(screen1);
this->handleScreenChanged(screen2);
}
void DesktopView::removeScreen(Screen *screen)
{
if (!screen) {
qCritical()<<"invalid screen id";
return;
}
this->handleScreenChanged(screen);
}
void DesktopView::setGridSize(QSize size)
{
m_gridSize = size;
for (auto screen : m_screens) {
screen->onScreenGridSizeChanged(size);
}
for (auto screen : m_screens) {
//越界图标重排
handleScreenChanged(screen);
}
}
QRect DesktopView::visualRect(const QModelIndex &index) const
{
auto rect = QRect(0, 0, m_gridSize.width(), m_gridSize.height());
// FIXME: uri
auto uri = getIndexUri(index);
auto pos = m_itemsPosesCached.value(uri);
rect.translate(pos);
return rect.adjusted(ICONVIEW_PADDING, ICONVIEW_PADDING, -ICONVIEW_PADDING, -ICONVIEW_PADDING);
}
QModelIndex DesktopView::indexAt(const QPoint &point) const
{
QList<QRect> visualRects;
for (int row = 0; row < model()->rowCount(); row++) {
auto index = model()->index(row, 0);
visualRects<<visualRect(index);
}
for (auto rect : visualRects) {
if (rect.contains(point)) {
int row = visualRects.indexOf(rect);
return model()->index(row, 0);
}
}
return QModelIndex();
}
QModelIndex DesktopView::findIndexByUri(const QString &uri) const
{
if (model()) {
for (int row = 0; row < model()->rowCount(); row++) {
//FIXME:
auto index = model()->index(row, 0);
auto indexUri = getIndexUri(index);
if (indexUri == uri) {
return index;
}
}
}
return QModelIndex();
}
QString DesktopView::getIndexUri(const QModelIndex &index) const
{
return index.data(Qt::UserRole).toString();
}
bool DesktopView::trySetIndexToPos(const QModelIndex &index, const QPoint &pos)
{
for (auto screen : m_screens) {
if (!screen->isValidScreen()) {
continue;
}
if (screen->setItemWithGlobalPos(getIndexUri(index), pos)) {
//清空其它屏幕关于此index的gridPos?
for (auto screen : m_screens) {
screen->makeItemGridPosInvalid(getIndexUri(index));
}
//效率?
screen->setItemWithGlobalPos(getIndexUri(index), pos);
m_itemsPosesCached.insert(getIndexUri(index), screen->getItemGlobalPosition(getIndexUri(index)));
return true;
} else {
//不改变位置
}
}
return false;
}
bool DesktopView::isIndexOverlapped(const QModelIndex &index)
{
return isItemOverlapped(getIndexUri(index));
}
bool DesktopView::isItemOverlapped(const QString &uri)
{
auto itemPos = m_itemsPosesCached.value(uri);
QStringList overrlappedItems;
for (auto item : m_items) {
if (m_itemsPosesCached.value(item) == itemPos) {
overrlappedItems<<item;
if (overrlappedItems.count() > 2) {
break;
}
}
}
overrlappedItems.removeOne(uri);
if (!overrlappedItems.isEmpty()) {
return true;
} else {
return false;
}
}
void DesktopView::_saveItemsPoses()
{
this->saveItemsPositions();
}
void DesktopView::paintEvent(QPaintEvent *event)
{
qDebug()<<"paint evnet";
QPainter p(viewport());
if (!event->rect().isEmpty()) {
// update one index only, used for dataChanged
} else {
// update all indexes, fixme: more effective?
}
// test
for (auto item : m_items) {
auto index = findIndexByUri(item);
QStyleOptionViewItem opt = viewOptions();
opt.text = index.data().toString();
opt.icon = qvariant_cast<QIcon>(index.data(Qt::DecorationRole));
opt.rect = visualRect(index);
opt.state |= QStyle::State_Enabled;
if (selectedIndexes().contains(index)) {
opt.state |= QStyle::State_Selected;
}
qApp->style()->drawControl(QStyle::CE_ItemViewItem, &opt, &p, this);
}
}
void DesktopView::dropEvent(QDropEvent *event)
{
// 有bug
//计算全体偏移量,验证越界和重叠图标,重新排序
if (event->source() == this) {
QPoint offset = event->pos() - m_dragStartPos;
QHash<QModelIndex, QPoint> indexesPoses;
auto indexes = selectedIndexes();
QStringList itemsNeedBeRelayouted;
for (auto index : indexes) {
//清空屏幕关于此index的gridPos
for (auto screen : m_screens) {
screen->makeItemGridPosInvalid(getIndexUri(index));
}
}
for (auto index : indexes) {
bool successed = false;
auto sourceRect = visualRect(index);
sourceRect.adjust(-ICONVIEW_PADDING, -ICONVIEW_PADDING, ICONVIEW_PADDING, ICONVIEW_PADDING);
sourceRect.translate(offset);
indexesPoses.insert(index, sourceRect.center());
for (auto screen : m_screens) {
if (!screen->isValidScreen()) {
continue;
}
if (screen->setItemWithGlobalPos(getIndexUri(index), sourceRect.center())) {
successed = true;
//效率?
screen->setItemWithGlobalPos(getIndexUri(index), sourceRect.center());
screen->setItemMetaInfoGridPos(getIndexUri(index), screen->itemGridPos(getIndexUri(index)));
setItemPosMetaInfo(getIndexUri(index), screen->itemGridPos(getIndexUri(index)), m_screens.indexOf(screen));
//覆盖原有index的位置
m_itemsPosesCached.insert(getIndexUri(index), screen->getItemGlobalPosition(getIndexUri(index)));
//TODO: 设置metainfo的位置
} else {
//不改变位置
}
}
if (!successed) {
//排列失败,这个元素被列为浮动元素
itemsNeedBeRelayouted<<getIndexUri(index);
}
}
relayoutItems(itemsNeedBeRelayouted);
} else {
}
viewport()->update();
}
void DesktopView::startDrag(Qt::DropActions supportedActions)
{
QAbstractItemView::startDrag(supportedActions);
}
void DesktopView::mousePressEvent(QMouseEvent *event)
{
QAbstractItemView::mousePressEvent(event);
m_dragStartPos = event->pos();
qDebug()<<m_dragStartPos;
}
void DesktopView::mouseMoveEvent(QMouseEvent *event)
{
QAbstractItemView::mouseMoveEvent(event);
if (!indexAt(m_dragStartPos).isValid() && event->buttons() & Qt::LeftButton) {
if (m_rubberBand->size().width() > 100 && m_rubberBand->height() > 100) {
m_rubberBand->setVisible(true);
}
setSelection(m_rubberBand->geometry(), QItemSelectionModel::Select|QItemSelectionModel::Deselect);
} else {
m_rubberBand->setVisible(false);
}
m_rubberBand->setGeometry(QRect(m_dragStartPos, event->pos()).normalized());
}
void DesktopView::mouseReleaseEvent(QMouseEvent *event)
{
QAbstractItemView::mouseReleaseEvent(event);
m_rubberBand->hide();
}
QStyleOptionViewItem DesktopView::viewOptions() const
{
QStyleOptionViewItem item;
item.decorationAlignment = Qt::AlignHCenter|Qt::AlignBottom;
item.decorationSize = iconSize();
item.decorationPosition = QStyleOptionViewItem::Position::Top;
item.displayAlignment = Qt::AlignHCenter|Qt::AlignTop;
item.features = QStyleOptionViewItem::HasDecoration|QStyleOptionViewItem::HasDisplay|QStyleOptionViewItem::WrapText;
item.font = qApp->font();
item.fontMetrics = qApp->fontMetrics();
return item;
}
void DesktopView::setSelection(const QRect &rect, QItemSelectionModel::SelectionFlags command)
{
qDebug()<<"set selection";
// FIXME:
if (m_rubberBand->isVisible()) {
for (int row = 0; row < model()->rowCount(); row++) {
auto index = model()->index(row, 0);
auto indexRect = visualRect(index);
if (rect.intersects(indexRect)) {
selectionModel()->select(index, QItemSelectionModel::Select);
} else {
selectionModel()->select(index, QItemSelectionModel::Deselect);
}
}
} else {
auto index = indexAt(rect.topLeft());
selectionModel()->select(index, command);
}
}
QRegion DesktopView::visualRegionForSelection(const QItemSelection &selection) const
{
QRegion visualRegion;
for (auto index : selection.indexes()) {
visualRegion += visualRect(index);
}
return visualRegion;
}
void DesktopView::setItemPosMetaInfo(const QString &uri, const QPoint &gridPos, int screenId)
{
// FIXME:
}
void DesktopView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles)
{
auto string = topLeft.data().toString();
Q_UNUSED(bottomRight)
Q_UNUSED(roles)
auto demageRect = visualRect(topLeft);
viewport()->update(demageRect);
}
void DesktopView::rowsInserted(const QModelIndex &parent, int start, int end)
{
for (int i = start; i <= end ; i++) {
auto index = model()->index(i, 0);
m_items.append(getIndexUri(index));
// FIXME: check if index has metainfo postion
if (false) {
} else {
// add index to float items.
m_floatItems<<getIndexUri(index);
for (auto screen : m_screens) {
// fixme: improve layout speed with cached position
auto gridPos = screen->placeItem(getIndexUri(index));
if (gridPos.x() >= 0) {
m_itemsPosesCached.insert(getIndexUri(index), screen->getItemGlobalPosition(getIndexUri(index)));
break;
}
}
}
}
viewport()->update();
}
void DesktopView::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end)
{
Q_UNUSED(end)
auto indexAboutToBeRemoved = model()->index(start, 0);
m_itemsPosesCached.remove(getIndexUri(indexAboutToBeRemoved));
m_items.removeOne(getIndexUri(indexAboutToBeRemoved));
m_floatItems.removeOne(getIndexUri(indexAboutToBeRemoved));
for (auto screen : m_screens) {
screen->makeItemGridPosInvalid(getIndexUri(indexAboutToBeRemoved));
}
// 重排浮动元素
relayoutItems(m_floatItems);
viewport()->update();
}
void DesktopView::saveItemsPositions()
{
//非越界元素的确认,越界元素不应该保存位置
QStringList itemOnAllScreen;
for (auto screen : m_screens) {
itemOnAllScreen<<screen->getItemsVisibleOnScreen();
}
for (auto item : itemOnAllScreen) {
//检查当前位置是否有重叠,如果有,则不确认
bool isOverlapped = isItemOverlapped(item);
if (!isOverlapped) {
//从浮动元素中排除
m_floatItems.removeOne(item);
//设置metainfo
auto screen = getItemScreen(item);
if (screen) {
int screenId = m_screens.indexOf(screen, 0);
QPoint gridPos = screen->itemGridPos(item);
screen->setItemMetaInfoGridPos(item, gridPos);
setItemPosMetaInfo(item, gridPos, screenId);
}
}
}
}
void DesktopView::handleScreenChanged(Screen *screen)
{
QStringList itemsNeedBeRelayouted = screen->getAllItemsOnScreen();
// 优先排列界内的有metainfo的图标
auto itemsMetaGridPosOnScreen = screen->getItemMetaGridPosVisibleOnScreen();
for (auto uri : itemsMetaGridPosOnScreen) {
itemsNeedBeRelayouted.removeOne(uri);
auto gridPos = screen->getItemMetaInfoGridPos(uri);
m_itemsPosesCached.insert(uri, screen->globalPositionFromGridPos(gridPos));
}
// sort?
relayoutItems(itemsNeedBeRelayouted);
// if (!screen->isValidScreen()) {
// // 对越界图标进行重排,但是不记录位置
// auto items = screen->getAllItemsOnScreen();
// itemsNeedBeRelayouted<<items;
// } else {
// // 更新屏幕内图标的位置
// auto items = screen->getItemsVisibleOnScreen();
// for (auto item : items) {
// auto pos = screen->getItemGlobalPosition(item);
// m_itemsPosesCached.insert(item, pos);
// }
// // 对越界图标进行重排,但是不记录位置
// items = screen->getItemsOutOfScreen();
// itemsNeedBeRelayouted<<items;
// relayoutItems(items);
// }
viewport()->update();
}
void DesktopView::handleGridSizeChanged()
{
// 保持index相对的grid位置不变,对越界图标进行处理
for (auto screen : m_screens) {
screen->onScreenGridSizeChanged(m_gridSize);
// 更新屏幕内图标的位置
// 记录越界图标
handleScreenChanged(screen);
}
// 重排越界图标
viewport()->update();
}
void DesktopView::relayoutItems(const QStringList &uris)
{
for (auto uri : uris) {
for (auto screen : m_screens) {
screen->makeItemGridPosInvalid(uri);
}
}
for (auto uri : uris) {
for (auto screen : m_screens) {
QPoint currentGridPos = QPoint();
// fixme: improve layout speed with cached position
currentGridPos = screen->placeItem(uri, currentGridPos);
if (currentGridPos != INVALID_POS) {
m_itemsPosesCached.insert(uri, screen->getItemGlobalPosition(uri));
break;
} else {
// FIXME:
// no place to place items
m_itemsPosesCached.remove(uri);
}
}
}
}
Screen *DesktopView::getItemScreen(const QString &uri)
{
auto itemPos = m_itemsPosesCached.value(uri);
for (auto screen : m_screens) {
if (screen->isValidScreen()) {
if (screen->getGeometry().contains(itemPos))
return screen;
}
}
// should not happend
return nullptr;
}
| 29.06729 | 127 | 0.61996 | [
"geometry",
"model"
] |
189b2aacd6996e3276539a5d0e0c05f47f8b3627 | 369 | hpp | C++ | src/Design/Components/Structural_Component.hpp | MattMarti/Lambda-Trajectory-Sim | 4155f103120bd49221776cc3b825b104f36817f2 | [
"MIT"
] | null | null | null | src/Design/Components/Structural_Component.hpp | MattMarti/Lambda-Trajectory-Sim | 4155f103120bd49221776cc3b825b104f36817f2 | [
"MIT"
] | null | null | null | src/Design/Components/Structural_Component.hpp | MattMarti/Lambda-Trajectory-Sim | 4155f103120bd49221776cc3b825b104f36817f2 | [
"MIT"
] | null | null | null | #ifndef LAMBDA_TRAJECTORY_SIM_SRC_ROCKET_COMPONENTS_STRUCTURAL_COMPONENT_HPP
#define LAMBDA_TRAJECTORY_SIM_SRC_ROCKET_COMPONENTS_STRUCTURAL_COMPONENT_HPP
#include "Design/Components/Component.hpp"
/*
Structural_Component.h
A structural component with specific shape and density
*/
class Structural_Component : public Component {
Structural_Component();
};
#endif | 26.357143 | 76 | 0.856369 | [
"shape"
] |
18a13a8d93aaa8f53af4dcf5ac8ec8e6d77f3952 | 287 | hpp | C++ | src/Tools/Converter/MatrixToString.hpp | NaokiTakahashi12/OpenHumanoidController | ce8da0cabc8bbeec86f16a36b9ba5e6a16c4a67d | [
"MIT"
] | 1 | 2019-09-23T06:21:47.000Z | 2019-09-23T06:21:47.000Z | src/Tools/Converter/MatrixToString.hpp | NaokiTakahashi12/hc-early | ce8da0cabc8bbeec86f16a36b9ba5e6a16c4a67d | [
"MIT"
] | 12 | 2019-07-30T00:17:09.000Z | 2019-12-09T23:00:43.000Z | src/Tools/Converter/MatrixToString.hpp | NaokiTakahashi12/OpenHumanoidController | ce8da0cabc8bbeec86f16a36b9ba5e6a16c4a67d | [
"MIT"
] | null | null | null |
#pragma once
#include <string>
#include <Eigen/Dense>
namespace Tools {
namespace Converter {
template <typename T>
std::string matrix_to_string(Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> &matrix);
template <typename T>
std::string matrix_to_string(T &vector);
}
}
| 15.944444 | 89 | 0.714286 | [
"vector"
] |
18a8517e0b55dcbe2ea2c815e7fc4d518457397b | 969 | cpp | C++ | packages/motionPlanning/src/types/cForbiddenAreaType.cpp | Falcons-Robocup/code | 2281a8569e7f11cbd3238b7cc7341c09e2e16249 | [
"Apache-2.0"
] | 2 | 2021-01-15T13:27:19.000Z | 2021-08-04T08:40:52.000Z | packages/motionPlanning/src/types/cForbiddenAreaType.cpp | Falcons-Robocup/code | 2281a8569e7f11cbd3238b7cc7341c09e2e16249 | [
"Apache-2.0"
] | null | null | null | packages/motionPlanning/src/types/cForbiddenAreaType.cpp | Falcons-Robocup/code | 2281a8569e7f11cbd3238b7cc7341c09e2e16249 | [
"Apache-2.0"
] | 5 | 2018-05-01T10:39:31.000Z | 2022-03-25T03:02:35.000Z | // Copyright 2017 Jan Feitsma (Falcons)
// SPDX-License-Identifier: Apache-2.0
/*
* cForbiddenAreaType.cpp
*
* Created on: Dec 3, 2017
* Author: Jan Feitsma
*/
#include "int/types/cForbiddenAreaType.hpp"
#include <string>
cForbiddenAreaType::cForbiddenAreaType(std::vector<Point2D> const &points)
{
_points = points;
calcHash();
}
std::string cForbiddenAreaType::getHash() const
{
return _hash;
}
std::vector<Point2D> cForbiddenAreaType::getPoints() const
{
return _points;
}
void cForbiddenAreaType::calcHash()
{
_hash = "";
for (auto p = _points.begin(); p != _points.end(); ++p)
{
char buf[64] = {0};
sprintf(buf, "%7.2f %7.2f", p->x, p->y);
_hash += buf;
}
}
bool cForbiddenAreaType::operator==(cForbiddenAreaType const &other) const
{
return _hash == other.getHash();
}
bool cForbiddenAreaType::operator<(cForbiddenAreaType const &other) const
{
return _hash < other.getHash();
}
| 19.38 | 74 | 0.654283 | [
"vector"
] |
18aed56adcaaf8da19b19be3a1365dc7e5ac8189 | 18,192 | cpp | C++ | driver/host/NovenaLMS6.cpp | bujigr/mmap_fpga | e36ca7edb97091b7e5019a175c06b4fc96367a75 | [
"CC-BY-3.0"
] | 34 | 2015-01-26T19:34:21.000Z | 2021-11-17T10:45:22.000Z | driver/host/NovenaLMS6.cpp | bujigr/mmap_fpga | e36ca7edb97091b7e5019a175c06b4fc96367a75 | [
"CC-BY-3.0"
] | 22 | 2015-02-07T01:39:50.000Z | 2017-09-09T15:48:41.000Z | driver/host/NovenaLMS6.cpp | bujigr/mmap_fpga | e36ca7edb97091b7e5019a175c06b4fc96367a75 | [
"CC-BY-3.0"
] | 16 | 2015-01-13T16:44:11.000Z | 2022-01-04T22:01:50.000Z | ////////////////////////////////////////////////////////////////////////
// SoapySDR module for Novena-RF SDR
//
// Copyright (c) 2015-2015 Lime Microsystems
// Copyright (c) 2015-2015 Andrew "bunnie" Huang
// SPDX-License-Identifier: Apache-2.0
// http://www.apache.org/licenses/LICENSE-2.0
////////////////////////////////////////////////////////////////////////
#include "NovenaRF.hpp"
#include "LMS6002_MainControl.h"
#include "lms6/CompoundOperations.h"
#include "lms6/Algorithms.h"
#include "MessageLog.h"
#include <sys/stat.h>
#include <pthread.h>
#include <fstream>
/***********************************************************************
* Log handler from the lms suite
**********************************************************************/
class SignalHandlerLogger : public SignalHandler
{
public:
SignalHandlerLogger(void)
{
return;
}
void HandleMessage(const LMS_Message &msg)
{
switch (msg.type)
{
case MSG_ERROR: SoapySDR::log(SOAPY_SDR_ERROR, msg.text); break;
case MSG_WARNING: SoapySDR::log(SOAPY_SDR_WARNING, msg.text); break;
default: SoapySDR::log(SOAPY_SDR_INFO, msg.text); break;
}
}
};
static SignalHandlerLogger myLogger;
/***********************************************************************
* handler for interfacing with LMS6 registers from unix fifo
**********************************************************************/
#define NOVENA_RF_CMD_PATH "/tmp/novena_rf_cmd"
#define NOVENA_RF_OUT_PATH "/tmp/novena_rf_out"
static pthread_t fifoAccessThread;
void *fifoAccessHandler(void *arg)
{
auto regMap = reinterpret_cast<lms6::RegistersMap *>(arg);
mkfifo(NOVENA_RF_CMD_PATH, S_IWUSR | S_IRUSR);
mkfifo(NOVENA_RF_OUT_PATH, S_IWUSR | S_IRUSR);
while (true)
{
//read cmd fifo
std::ifstream cmdFile(NOVENA_RF_CMD_PATH);
std::string line;
std::getline(cmdFile, line);
if (line.empty()) continue;
if (line == "exit") break;
//parse command
std::string adrStr, valStr;
std::stringstream ss(line);
std::getline(ss, adrStr, ' ');
std::getline(ss, valStr, ' ');
const long adr = (adrStr.substr(0, 2) == "0x")?strtol(adrStr.c_str(), nullptr, 16):strtol(adrStr.c_str(), nullptr, 10);
const long val = (valStr.substr(0, 2) == "0x")?strtol(valStr.c_str(), nullptr, 16):strtol(valStr.c_str(), nullptr, 10);
//perform write it value specified
if (not valStr.empty()) regMap->SetRegisterValue(adr, val);
//perform a read and output to the result
const int out = regMap->GetRegisterValue(adr, true/*from chip*/);
std::ofstream outFile(NOVENA_RF_OUT_PATH);
outFile << std::hex << "0x" << out << std::endl;
}
return nullptr;
}
/***********************************************************************
* Setup and tear-down hooks
* Initialize everything on the lms6 for runtime usage.
* Configurable parameters are in the sections below.
**********************************************************************/
void NovenaRF::initRFIC(void)
{
_calLPFCoreOnce = 0;
auto ser = new ConnectionManager();
ser->RegisterForNotifications(&myLogger);
ser->Open();
//separate logger - enable to console
//MessageLog::getInstance()->SetConsoleFilter(LOG_ALL, true);
//main control owns the connection manager
_lms6ctrl = new lms6::LMS6002_MainControl(ser);
_lms6ctrl->ResetChip(LMS_RST_PULSE);
_lms6ctrl->NewProject();
SoapySDR::logf(SOAPY_SDR_INFO, "LMS6002: ver=0x%x, rev=0x%x",
_lms6ctrl->GetParam(lms6::VER), _lms6ctrl->GetParam(lms6::REV));
_lms6ctrl->SetReferenceFrequency(this->getMasterClockRate()/1e6, true/*Rx*/);
_lms6ctrl->SetReferenceFrequency(this->getMasterClockRate()/1e6, false/*Tx*/);
_lms6ctrl->SetParam(lms6::STXEN, 1); //enable transmitter
_lms6ctrl->SetParam(lms6::SRXEN, 1); //enable receiver
//enable all the things
_lms6ctrl->SetParam(lms6::EN_TOP, 1);
_lms6ctrl->SetParam(lms6::EN_RXPLL, 1);
_lms6ctrl->SetParam(lms6::EN_TXPLL, 1);
_lms6ctrl->SetParam(lms6::EN_ADC_DAC, 1);
_lms6ctrl->SetParam(lms6::EN_TXRF, 1);
_lms6ctrl->SetParam(lms6::EN_RXFE, 1);
_lms6ctrl->SetParam(lms6::EN_RXLPF, 1);
_lms6ctrl->SetParam(lms6::EN_TXLPF, 1);
_lms6ctrl->SetParam(lms6::EN_RXVGA2, 1);
lms6::CompoundOperations(_lms6ctrl).CustSet_RxVGA2PowerON();
lms6::CompoundOperations(_lms6ctrl).CustSet_LNAPowerON();
lms6::CompoundOperations(_lms6ctrl).CustSet_RxLpfPowerON();
lms6::CompoundOperations(_lms6ctrl).CustSet_RxFePowerON();
//bypass LPF by default with large BW
this->setBandwidth(SOAPY_SDR_TX, 0, 30.0e6);
this->setBandwidth(SOAPY_SDR_RX, 0, 30.0e6);
//initialize to minimal gain settings
SoapySDR::Device::setGain(SOAPY_SDR_TX, 0, 0.0);
SoapySDR::Device::setGain(SOAPY_SDR_RX, 0, 0.0);
//initialize antenna to broadband
this->setAntenna(SOAPY_SDR_TX, 0, "BB");
this->setAntenna(SOAPY_SDR_RX, 0, "BB");
//set expected interface mode
_lms6ctrl->SetParam(lms6::MISC_CTRL_9, 0); //rx fsync polarity
_lms6ctrl->SetParam(lms6::MISC_CTRL_8, 1); //rx interleave mode (swap for std::complex host format)
_lms6ctrl->SetParam(lms6::MISC_CTRL_6, 1); //tx fsync polarity (tx needs this swap for an unknown reason)
_lms6ctrl->SetParam(lms6::MISC_CTRL_5, 1); //tx interleave mode (swap for std::complex host format)
//start the register handler thread
if (pthread_create(&fifoAccessThread, nullptr, fifoAccessHandler, _lms6ctrl->getRegistersMap()) != 0)
{
SoapySDR::log(SOAPY_SDR_ERROR, "Error creating fifo access thread");
}
}
void NovenaRF::exitRFIC(void)
{
//stop the register handler thread
std::ofstream cmdFile(NOVENA_RF_CMD_PATH);
cmdFile << "exit" << std::endl;
cmdFile.close();
pthread_join(fifoAccessThread, nullptr);
//_lms6ctrl->SaveToFile("/tmp/lms6.txt", false);
_lms6ctrl->SetParam(lms6::STXEN, 0); //disable transmitter
_lms6ctrl->SetParam(lms6::SRXEN, 0); //disable receiver
lms6::CompoundOperations(_lms6ctrl).CustSet_RxVGA2PowerOFF();
lms6::CompoundOperations(_lms6ctrl).CustSet_LNAPowerOFF();
lms6::CompoundOperations(_lms6ctrl).CustSet_RxLpfPowerOFF();
lms6::CompoundOperations(_lms6ctrl).CustSet_RxFePowerOFF();
delete _lms6ctrl;
_lms6ctrl = nullptr;
}
/*******************************************************************
* Gain API
*
* Available amplification/attenuation elements are listed in order
* from RF to BB for the default gain distribution algorithm.
*
* Gains are passed in as dB and clipped and scaled into integer values
* for the specific registers to which they apply.
******************************************************************/
std::vector<std::string> NovenaRF::listGains(const int direction, const size_t channel) const
{
std::vector<std::string> gains;
if (direction == SOAPY_SDR_TX)
{
//ordering RF to BB
gains.push_back("VGA2");
gains.push_back("VGA1");
}
if (direction == SOAPY_SDR_RX)
{
//ordering RF to BB
gains.push_back("LNA");
gains.push_back("VGA1");
gains.push_back("VGA2");
}
return gains;
}
#define MinMaxClip(minimum, maximum, value) \
std::max(minimum, std::min(maximum, value))
void NovenaRF::setGain(const int direction, const size_t channel, const std::string &name, const double value)
{
if (direction == SOAPY_SDR_TX and name == "VGA1")
{
const double regVal(MinMaxClip(-35.0, -4.0, value));
_lms6ctrl->SetParam(lms6::VGA1GAIN, lrint(regVal+35.0));
}
if (direction == SOAPY_SDR_TX and name == "VGA2")
{
const double regVal(MinMaxClip(0.0, 25.0, value));
_lms6ctrl->SetParam(lms6::VGA2GAIN_TXVGA2, lrint(regVal));
}
if (direction == SOAPY_SDR_RX and name == "VGA2")
{
const double regVal(MinMaxClip(0.0, 30.0, value));
_lms6ctrl->SetParam(lms6::VGA2GAIN_RXVGA2, lrint(regVal/3.0));
}
if (direction == SOAPY_SDR_RX and name == "VGA1")
{
const double regVal(MinMaxClip(0.0, 30.0, value));
_lms6ctrl->SetParam(lms6::RFB_TIA_RXFE, regVal*4);
}
if (direction == SOAPY_SDR_RX and name == "LNA")
{
const double regVal(MinMaxClip(0.0, 6.0, value));
_lms6ctrl->SetParam(lms6::G_LNA_RXFE, 2 | lrint(regVal/6.0));
}
}
double NovenaRF::getGain(const int direction, const size_t channel, const std::string &name) const
{
if (direction == SOAPY_SDR_TX and name == "VGA1")
{
return _lms6ctrl->GetParam(lms6::VGA1GAIN) - 35.0;
}
if (direction == SOAPY_SDR_TX and name == "VGA2")
{
return _lms6ctrl->GetParam(lms6::VGA2GAIN_TXVGA2);
}
if (direction == SOAPY_SDR_RX and name == "VGA2")
{
return _lms6ctrl->GetParam(lms6::VGA2GAIN_RXVGA2)*3.0;
}
if (direction == SOAPY_SDR_RX and name == "VGA1")
{
return _lms6ctrl->GetParam(lms6::RFB_TIA_RXFE)/4.0;
}
if (direction == SOAPY_SDR_RX and name == "LNA")
{
return (_lms6ctrl->GetParam(lms6::G_LNA_RXFE) & 0x1)*6.0;
}
return SoapySDR::Device::getGain(direction, channel, name);
}
SoapySDR::Range NovenaRF::getGainRange(const int direction, const size_t channel, const std::string &name) const
{
if (direction == SOAPY_SDR_TX and name == "VGA1") return SoapySDR::Range(-35.0, -4.0);
if (direction == SOAPY_SDR_TX and name == "VGA2") return SoapySDR::Range(0.0, 25.0);
if (direction == SOAPY_SDR_RX and name == "VGA2") return SoapySDR::Range(0.0, 30.0);
if (direction == SOAPY_SDR_RX and name == "VGA1") return SoapySDR::Range(0.0, 30.0);
if (direction == SOAPY_SDR_RX and name == "LNA") return SoapySDR::Range(0.0, 6.0);
return SoapySDR::Device::getGainRange(direction, channel, name);
}
/*******************************************************************
* Frequency API
*
* The LO is tuned to the specified frequency in Hz
* and then the calibration algorithm is applied.
* Error in tuning the LO is compensated in the CORDIC
* through the default tuning algorithm.
******************************************************************/
void NovenaRF::setRfFrequency(const int direction, const size_t channel, const double frequency, const SoapySDR::Kwargs &)
{
double realFreq, fVco;
unsigned Nint, Nfrac, iVco;
int divider;
_lms6ctrl->SetFrequency(direction == SOAPY_SDR_RX, frequency/1e6, realFreq, Nint, Nfrac, iVco, fVco, divider);
_lms6ctrl->Tune(direction == SOAPY_SDR_RX);
SoapySDR::logf(SOAPY_SDR_TRACE, "NovenaRF: %sTune(%f MHz), actual = %f MHz", (direction==SOAPY_SDR_TX)?"TX":"RX", frequency/1e6, realFreq);
//SoapySDR::logf(SOAPY_SDR_TRACE, "fVco=%f, Nint=%d, Nfrac=%d, iVco=%d, divider=%d", fVco, Nint, Nfrac, iVco, divider);
//save gain values
std::map<std::string, double> save;
for (const auto &name : this->listGains(direction, channel))
{
save[name] = this->getGain(direction, channel, name);
}
//apply gain
if (direction == SOAPY_SDR_RX)
{
auto r = SoapySDR::Device::getGainRange(direction, channel);
SoapySDR::Device::setGain(direction, channel, r.maximum());
}
if (direction == SOAPY_SDR_TX)
{
this->setGain(direction, channel, "VGA1", -10);
this->setGain(direction, channel, "VGA2", 25);
}
//perform cal with adc off
_lms6ctrl->SetParam(lms6::EN_ADC_DAC, 0);
if (_calLPFCoreOnce++ == 0) lms6::Algorithms(_lms6ctrl).CalibrateLPFCore();
if (direction == SOAPY_SDR_TX) lms6::Algorithms(_lms6ctrl).CalibrateTx();
if (direction == SOAPY_SDR_RX) lms6::Algorithms(_lms6ctrl).CalibrateRx();
_lms6ctrl->SetParam(lms6::EN_ADC_DAC, 1);
//restore gain values
for (const auto &pair : save)
{
this->setGain(direction, channel, pair.first, pair.second);
}
}
void NovenaRF::setFrequency(const int direction, const size_t channel, const std::string &name, const double frequency, const SoapySDR::Kwargs &args)
{
//printf("setFrequency %s %f MHz\n", name.c_str(), frequency/1e6);
if (name == "RF")
{
return this->setRfFrequency(direction, channel, frequency, args);
}
if (name == "BB")
{
//set the cordic rate
const double cordicFreq = frequency;
const double dspRate = LMS_CLOCK_RATE/2;
uint32_t cordicWord = int32_t(cordicFreq*(1 << 31)/dspRate);
uint32_t scaledWord = -2*int32_t(cordicWord);
if (direction == SOAPY_SDR_RX)
{
this->writeRegister(REG_DECIM_CORDIC_PHASE_LO, scaledWord & 0xffff);
this->writeRegister(REG_DECIM_CORDIC_PHASE_HI, scaledWord >> 16);
}
if (direction == SOAPY_SDR_TX)
{
this->writeRegister(REG_INTERP_CORDIC_PHASE_LO, scaledWord & 0xffff);
this->writeRegister(REG_INTERP_CORDIC_PHASE_HI, scaledWord >> 16);
}
_cachedCordics[direction][channel] = (cordicWord*dspRate)/double(1 << 31);
return;
}
return SoapySDR::Device::setFrequency(direction, channel, name, frequency);
}
double NovenaRF::getFrequency(const int direction, const size_t channel, const std::string &name) const
{
if (name == "RF")
{
return _lms6ctrl->GetFrequency(direction == SOAPY_SDR_RX)*1e6;
}
if (name == "BB")
{
return _cachedCordics.at(direction).at(channel);
}
return SoapySDR::Device::getFrequency(direction, channel, name);
}
SoapySDR::RangeList NovenaRF::getFrequencyRange(const int direction, const size_t channel, const std::string &name) const
{
if (name == "RF")
{
return SoapySDR::RangeList(1, SoapySDR::Range(0.3e9, 3.8e9));
}
if (name == "BB")
{
const double dspRate = LMS_CLOCK_RATE/2;
return SoapySDR::RangeList(1, SoapySDR::Range(-dspRate/2, dspRate/2));
}
return SoapySDR::Device::getFrequencyRange(direction, channel, name);
}
std::vector<std::string> NovenaRF::listFrequencies(const int direction, const size_t channel) const
{
//order RF to BB for default tuning algorithm
std::vector<std::string> comps;
comps.push_back("RF");
comps.push_back("BB");
return comps;
}
/*******************************************************************
* Bandwidth filters API
******************************************************************/
void NovenaRF::setBandwidth(const int direction, const size_t channel, const double bw)
{
//map the requested frequency to the next greatest bandwidth setting
const auto bws = this->listBandwidths(direction, channel);
long val = 0;
while (val < 0xf)
{
if (bw >= bws.at(val)) break;
val++;
}
//bypass when BW is larger than max filter
const bool bypass = (bw/2.0 > 14e6);
if (direction == SOAPY_SDR_TX and bypass) lms6::CompoundOperations(_lms6ctrl).CustSet_BypassTxLpfON();
if (direction == SOAPY_SDR_TX and not bypass) lms6::CompoundOperations(_lms6ctrl).CustSet_BypassTxLpfOFF();
if (direction == SOAPY_SDR_RX and bypass) lms6::CompoundOperations(_lms6ctrl).CustSet_BypassRxLpfON();
if (direction == SOAPY_SDR_RX and not bypass) lms6::CompoundOperations(_lms6ctrl).CustSet_BypassRxLpfOFF();
//write the setting
const auto reg = (direction == SOAPY_SDR_RX)?lms6::BWC_LPF_RXLPF:lms6::BWC_LPF_TXLPF;
_lms6ctrl->SetParam(reg, val);
}
double NovenaRF::getBandwidth(const int direction, const size_t channel) const
{
const auto reg = (direction == SOAPY_SDR_RX)?lms6::BWC_LPF_RXLPF:lms6::BWC_LPF_TXLPF;
long val = _lms6ctrl->GetParam(reg);
return this->listBandwidths(direction, channel).at(val & 0xf);
}
std::vector<double> NovenaRF::listBandwidths(const int direction, const size_t channel) const
{
std::vector<double> bws;
bws.push_back(14e6);
bws.push_back(10e6);
bws.push_back(7e6);
bws.push_back(6e6);
bws.push_back(5e6);
bws.push_back(4.375e6);
bws.push_back(3.5e6);
bws.push_back(3e6);
bws.push_back(2.75e6);
bws.push_back(2.5e6);
bws.push_back(1.92e6);
bws.push_back(1.5e6);
bws.push_back(1.375e6);
bws.push_back(1.25e6);
bws.push_back(0.875e6);
bws.push_back(0.75e6);
for (auto &bw : bws) bw *= 2; //convert to complex width in Hz
return bws;
}
/*******************************************************************
* Antenna API
******************************************************************/
std::vector<std::string> NovenaRF::listAntennas(const int direction, const size_t channel) const
{
std::vector<std::string> ants;
if (direction == SOAPY_SDR_TX)
{
//1: High band output (1500 - 3800 MHz)
//2: Broadband output
ants.push_back("HB");
ants.push_back("BB");
}
if (direction == SOAPY_SDR_RX)
{
//1: Low band input (300 - 2200 MHz)
//2: High band input (1500-3800MHz)
//3: Broadband input
ants.push_back("LB");
ants.push_back("HB");
ants.push_back("BB");
}
return ants;
}
void NovenaRF::setAntenna(const int direction, const size_t channel, const std::string &name)
{
if (direction == SOAPY_SDR_TX)
{
if (name == "HB") _lms6ctrl->SetParam(lms6::PA_EN, 1);
else _lms6ctrl->SetParam(lms6::PA_EN, 2);
}
else
{
if (name == "LB") _lms6ctrl->SetParam(lms6::LNASEL_RXFE, 1);
else if (name == "HB") _lms6ctrl->SetParam(lms6::LNASEL_RXFE, 2);
else _lms6ctrl->SetParam(lms6::LNASEL_RXFE, 3);
}
}
std::string NovenaRF::getAntenna(const int direction, const size_t channel) const
{
if (direction == SOAPY_SDR_TX)
{
switch (_lms6ctrl->GetParam(lms6::PA_EN))
{
case 1: return "HB";
default: return "BB";
}
}
if (direction == SOAPY_SDR_RX)
{
switch (_lms6ctrl->GetParam(lms6::LNASEL_RXFE))
{
case 1: return "LB";
case 2: return "HB";
default: return "BB";
}
}
return SoapySDR::Device::getAntenna(direction, channel);
}
| 35.952569 | 149 | 0.619613 | [
"vector"
] |
18ba8b2e9876b09129b215b8d396c7be6c41a0b0 | 279 | cpp | C++ | old/AtCoder/abc084/C.cpp | not522/Competitive-Programming | be4a7d25caf5acbb70783b12899474a56c34dedb | [
"Unlicense"
] | 7 | 2018-04-14T14:55:51.000Z | 2022-01-31T10:49:49.000Z | old/AtCoder/abc084/C.cpp | not522/Competitive-Programming | be4a7d25caf5acbb70783b12899474a56c34dedb | [
"Unlicense"
] | 5 | 2018-04-14T14:28:49.000Z | 2019-05-11T02:22:10.000Z | old/AtCoder/abc084/C.cpp | not522/Competitive-Programming | be4a7d25caf5acbb70783b12899474a56c34dedb | [
"Unlicense"
] | null | null | null | #include "template.hpp"
int main() {
int n;
cin >> n;
vector<int> t(n);
for (int i = 0; i < n - 1; ++i) {
int c, s, f;
cin >> c >> s >> f;
for (int j = 0; j <= i; ++j) {
for (chmax(t[j], s); t[j] % f; ++t[j]);
t[j] += c;
}
}
cout << t;
}
| 16.411765 | 45 | 0.369176 | [
"vector"
] |
18cbc1309432cde893a33a6496f75660700bdbe4 | 51,816 | cpp | C++ | krust/public-api/vulkan-utils.cpp | ahcox/krust | c4c349b3432d086466a13aef61ab220d8c43bcbb | [
"MIT"
] | 4 | 2016-05-09T08:22:52.000Z | 2019-12-07T16:19:50.000Z | krust/public-api/vulkan-utils.cpp | ahcox/krust | c4c349b3432d086466a13aef61ab220d8c43bcbb | [
"MIT"
] | null | null | null | krust/public-api/vulkan-utils.cpp | ahcox/krust | c4c349b3432d086466a13aef61ab220d8c43bcbb | [
"MIT"
] | null | null | null | // Copyright (c) 2016 Andrew Helge Cox
//
// 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.
/// @file Utility code for Vulkan.
/// @todo Commit functions with dedicated error handling to use the Krust deferred error handling mechanism or move them to their own file of weakly-coupled helpers (these came from krust-io and were written when there was an idea that someone might want to use krust-io without krust core. E.g. EnumeratePhysicalDevices().
// Compilation unit header:
#include "vulkan-utils.h"
// Internal includes:
#include "krust/public-api/logging.h"
#include "krust/public-api/krust-assertions.h"
#include "krust/public-api/vulkan_struct_init.h"
#include "krust/public-api/vulkan-objects.h"
#include "krust/internal/krust-internal.h"
// External includes:
#include <algorithm>
#include <cstring>
namespace Krust
{
VkImageCreateInfo CreateDepthImageInfo(const uint32_t presentQueueFamily, const VkFormat depthFormat, const uint32_t width, const uint32_t height)
{
KRUST_ASSERT2(IsDepthFormat(depthFormat), "Format not usable for a depth buffer.");
auto info = ImageCreateInfo();
info.flags = 0,
info.imageType = VK_IMAGE_TYPE_2D,
info.format = depthFormat,
info.extent.width = width,
info.extent.height = height,
info.extent.depth = 1,
info.mipLevels = 1,
info.arrayLayers = 1,
info.samples = VK_SAMPLE_COUNT_1_BIT,
info.tiling = VK_IMAGE_TILING_OPTIMAL,
info.usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT,
info.sharingMode = VK_SHARING_MODE_EXCLUSIVE,
info.queueFamilyIndexCount = 1,
info.pQueueFamilyIndices = &presentQueueFamily,
info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; // But I want to get into: VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
return info;
}
VkImageView CreateDepthImageView(VkDevice device, VkImage image, const VkFormat format)
{
auto viewInfo = ImageViewCreateInfo();
viewInfo.flags = 0, //< No flags needed [Could set VK_IMAGE_VIEW_CREATE_READ_ONLY_DEPTH_BIT or VK_IMAGE_VIEW_CREATE_READ_ONLY_STENCIL_BIT for read-only depth buffer.]
viewInfo.image = image,
viewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D,
viewInfo.format = format,
viewInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY,
viewInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY,
viewInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY,
viewInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY,
viewInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_STENCIL_BIT | VK_IMAGE_ASPECT_DEPTH_BIT,
viewInfo.subresourceRange.baseMipLevel = 0,
viewInfo.subresourceRange.levelCount = 1,
viewInfo.subresourceRange.baseArrayLayer = 0,
viewInfo.subresourceRange.layerCount = 1;
VkImageView imageView;
const VkResult result = vkCreateImageView(device, &viewInfo, Krust::Internal::sAllocator, &imageView);
if(result != VK_SUCCESS)
{
KRUST_LOG_ERROR << "Failed to create image view for depth buffer. Error: " << result << endlog;
imageView = 0;
}
return imageView;
}
VkResult ApplyImageBarrierBlocking(
Krust::Device& device, VkImage image, VkQueue queue, Krust::CommandPool& pool,
const VkImageMemoryBarrier& barrier)
{
auto commandBuffer = CommandBuffer::New(pool, VK_COMMAND_BUFFER_LEVEL_PRIMARY);
auto commandBufferInheritanceInfo = CommandBufferInheritanceInfo();
commandBufferInheritanceInfo.renderPass = nullptr,
commandBufferInheritanceInfo.subpass = 0,
commandBufferInheritanceInfo.framebuffer = nullptr,
commandBufferInheritanceInfo.occlusionQueryEnable = VK_FALSE,
commandBufferInheritanceInfo.queryFlags = 0,
commandBufferInheritanceInfo.pipelineStatistics = 0;
auto bufferBeginInfo = CommandBufferBeginInfo(
VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT,
&commandBufferInheritanceInfo);
const VkResult beginBufferResult = vkBeginCommandBuffer(
*commandBuffer,
&bufferBeginInfo);
if(VK_SUCCESS != beginBufferResult)
{
KRUST_LOG_ERROR << "Failed to begin command buffer. Error: " << beginBufferResult << Krust::endlog;
return beginBufferResult;
}
vkCmdPipelineBarrier(
*commandBuffer,
VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
0, // VkDependencyFlags
0, nullptr,
0, nullptr,
1, &barrier);
VK_CALL_RET_RES(vkEndCommandBuffer, *commandBuffer);
// Submit the buffer and then wait for it to complete:
constexpr VkPipelineStageFlags pipelineFlags = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
auto submitInfo = SubmitInfo(
0, nullptr,
&pipelineFlags,
1, commandBuffer->GetVkCommandBufferAddress(),
0, nullptr);
// Execute command buffer on main queue:
FencePtr fence {Fence::New(device, 0)};
VK_CALL(vkQueueSubmit, queue, 1, &submitInfo, *fence);
const VkResult fenceWaitResult = vkWaitForFences(device, 1, fence->GetVkFenceAddress(), true, 1000000000); // Wait one second.
if(VK_SUCCESS != fenceWaitResult)
{
KRUST_LOG_ERROR << "Wait for queue submit of image memory barrier did not succeed: " << fenceWaitResult << Krust::endlog;
return fenceWaitResult;
}
return VK_SUCCESS;
}
ConditionalValue<uint32_t>
FindFirstMemoryTypeWithProperties(const VkPhysicalDeviceMemoryProperties& memoryProperties, const uint32_t candidateTypeBitset, const VkMemoryPropertyFlags properties)
{
const uint32_t count = std::min(uint32_t(VK_MAX_MEMORY_TYPES), memoryProperties.memoryTypeCount);
for(uint32_t memoryType = 0; memoryType < count; ++memoryType)
{
// Check whether the memory type is in the bitset of allowable options:
if(candidateTypeBitset & (1u << memoryType))
{
// Check whether all the requested properties are set for the memory type:
if((memoryProperties.memoryTypes[memoryType].propertyFlags & properties) == properties)
{
return ConditionalValue<uint32_t>(memoryType, true);
}
}
}
KRUST_LOG_WARN << "No suitable memory type found with the requested properties (" << properties << ") among the allowed types in the flag set (" << candidateTypeBitset << ")." << endlog;
return ConditionalValue<uint32_t>(0, false);
}
ConditionalValue<uint32_t>
FindMemoryTypeMatchingProperties(const VkPhysicalDeviceMemoryProperties& memoryProperties, const uint32_t candidateTypeBitset, const VkMemoryPropertyFlags properties)
{
const uint32_t count = std::min(uint32_t(VK_MAX_MEMORY_TYPES), memoryProperties.memoryTypeCount);
for(uint32_t memoryType = 0; memoryType < count; ++memoryType)
{
// Check whether the memory type is in the bitset of allowable options:
if(candidateTypeBitset & (1u << memoryType))
{
// Check whether all the requested properties are set for the memory type:
if(memoryProperties.memoryTypes[memoryType].propertyFlags == properties)
{
return ConditionalValue<uint32_t>(memoryType, true);
}
}
}
KRUST_LOG_WARN << "No suitable memory type found with the requested properties (" << properties << ") among the allowed types in the flag set (" << candidateTypeBitset << ")." << endlog;
return ConditionalValue<uint32_t>(0, false);
}
bool IsDepthFormat(const VkFormat format)
{
// Use this to find out the new number if the assert below fires:
// KRUST_SHOW_UINT_AS_WARNING(VK_FORMAT_RANGE_SIZE);
// Vulkan headers have started shipping withotu these useful extra enumernats:
// KRUST_COMPILE_ASSERT(VK_FORMAT_RANGE_SIZE == 185, "Number of formats changed. Check if any are depth ones.");
// Note, a depth format could be added while a non-depth one was removed and not
// trigger the assert above.
bool isDepth = false;
if(format == VK_FORMAT_D16_UNORM ||
format == VK_FORMAT_X8_D24_UNORM_PACK32 ||
format == VK_FORMAT_D32_SFLOAT ||
format == VK_FORMAT_D16_UNORM_S8_UINT ||
format == VK_FORMAT_D24_UNORM_S8_UINT ||
format == VK_FORMAT_D32_SFLOAT_S8_UINT)
{
isDepth = true;
}
return isDepth;
}
void LogResultError(const char* message, VkResult result)
{
KRUST_LOG_ERROR << message << " Result: " << ResultToString(result) << "." << endlog;
}
const char* ResultToString(const VkResult result)
{
const char *string = "<<Unknown Result Code>>";
// Recreate with %s/\(VK_.*\) = .*,$/case \1: { string = "\1"; break; }/
switch (result) {
case VK_SUCCESS: { string = "VK_SUCCESS"; break; }
case VK_NOT_READY: { string = "VK_NOT_READY"; break; }
case VK_TIMEOUT: { string = "VK_TIMEOUT"; break; }
case VK_EVENT_SET: { string = "VK_EVENT_SET"; break; }
case VK_EVENT_RESET: { string = "VK_EVENT_RESET"; break; }
case VK_INCOMPLETE: { string = "VK_INCOMPLETE"; break; }
case VK_ERROR_OUT_OF_HOST_MEMORY: { string = "VK_ERROR_OUT_OF_HOST_MEMORY"; break; }
case VK_ERROR_OUT_OF_DEVICE_MEMORY: { string = "VK_ERROR_OUT_OF_DEVICE_MEMORY"; break; }
case VK_ERROR_INITIALIZATION_FAILED: { string = "VK_ERROR_INITIALIZATION_FAILED"; break; }
case VK_ERROR_DEVICE_LOST: { string = "VK_ERROR_DEVICE_LOST"; break; }
case VK_ERROR_MEMORY_MAP_FAILED: { string = "VK_ERROR_MEMORY_MAP_FAILED"; break; }
case VK_ERROR_LAYER_NOT_PRESENT: { string = "VK_ERROR_LAYER_NOT_PRESENT"; break; }
case VK_ERROR_EXTENSION_NOT_PRESENT: { string = "VK_ERROR_EXTENSION_NOT_PRESENT"; break; }
case VK_ERROR_FEATURE_NOT_PRESENT: { string = "VK_ERROR_FEATURE_NOT_PRESENT"; break; }
case VK_ERROR_INCOMPATIBLE_DRIVER: { string = "VK_ERROR_INCOMPATIBLE_DRIVER"; break; }
case VK_ERROR_TOO_MANY_OBJECTS: { string = "VK_ERROR_TOO_MANY_OBJECTS"; break; }
case VK_ERROR_FORMAT_NOT_SUPPORTED: { string = "VK_ERROR_FORMAT_NOT_SUPPORTED"; break; }
case VK_ERROR_FRAGMENTED_POOL: { string = "VK_ERROR_FRAGMENTED_POOL"; break; }
case VK_ERROR_UNKNOWN: { string = "VK_ERROR_UNKNOWN"; break; }
case VK_ERROR_OUT_OF_POOL_MEMORY: { string = "VK_ERROR_OUT_OF_POOL_MEMORY"; break; }
case VK_ERROR_INVALID_EXTERNAL_HANDLE: { string = "VK_ERROR_INVALID_EXTERNAL_HANDLE"; break; }
case VK_ERROR_FRAGMENTATION: { string = "VK_ERROR_FRAGMENTATION"; break; }
case VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS: { string = "VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS"; break; }
case VK_ERROR_SURFACE_LOST_KHR: { string = "VK_ERROR_SURFACE_LOST_KHR"; break; }
case VK_ERROR_NATIVE_WINDOW_IN_USE_KHR: { string = "VK_ERROR_NATIVE_WINDOW_IN_USE_KHR"; break; }
case VK_SUBOPTIMAL_KHR: { string = "VK_SUBOPTIMAL_KHR"; break; }
case VK_ERROR_OUT_OF_DATE_KHR: { string = "VK_ERROR_OUT_OF_DATE_KHR"; break; }
case VK_ERROR_INCOMPATIBLE_DISPLAY_KHR: { string = "VK_ERROR_INCOMPATIBLE_DISPLAY_KHR"; break; }
case VK_ERROR_VALIDATION_FAILED_EXT: { string = "VK_ERROR_VALIDATION_FAILED_EXT"; break; }
case VK_ERROR_INVALID_SHADER_NV: { string = "VK_ERROR_INVALID_SHADER_NV"; break; }
case VK_ERROR_INVALID_DRM_FORMAT_MODIFIER_PLANE_LAYOUT_EXT: { string = "VK_ERROR_INVALID_DRM_FORMAT_MODIFIER_PLANE_LAYOUT_EXT"; break; }
case VK_ERROR_NOT_PERMITTED_EXT: { string = "VK_ERROR_NOT_PERMITTED_EXT"; break; }
case VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT: { string = "VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT"; break; }
case VK_THREAD_IDLE_KHR: { string = "VK_THREAD_IDLE_KHR"; break; }
case VK_THREAD_DONE_KHR: { string = "VK_THREAD_DONE_KHR"; break; }
case VK_OPERATION_DEFERRED_KHR: { string = "VK_OPERATION_DEFERRED_KHR"; break; }
case VK_OPERATION_NOT_DEFERRED_KHR: { string = "VK_OPERATION_NOT_DEFERRED_KHR"; break; }
case VK_PIPELINE_COMPILE_REQUIRED_EXT: { string = "VK_PIPELINE_COMPILE_REQUIRED_EXT"; break; }
// case VK_RESULT_RANGE_SIZE: { string = "VK_RESULT_RANGE_SIZE"; break; }
case VK_RESULT_MAX_ENUM: { string = "VK_RESULT_MAX_ENUM"; break; }
};
return string;
}
int SortMetric(const VkPresentModeKHR mode, const bool tearingAllowed)
{
/// @todo Revise code that chooses a present mode. Maybe force app to have a list from best to worst it knows about.
// The modes are enumerated from best to worst, with the caveat that the first
// will tear. Therefore we use their values as the metric but penalize the tearing
// mode if tearing is not allowed.
int sortKey = mode;
if(!tearingAllowed && (mode == VK_PRESENT_MODE_IMMEDIATE_KHR))
{
sortKey += 128;
}
return sortKey;
}
const char* SurfaceTransformToString(const VkSurfaceTransformFlagsKHR transform)
{
const char* text = "<<<UNKNOWN VK_SURFACE_TRANSFORM>>>";
switch(transform)
{
case VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR: { text = "VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR"; break; }
case VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR: { text = "VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR"; break; }
case VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR: { text = "VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR"; break; }
case VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR: { text = "VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR"; break; }
case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR: { text = "VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR"; break; }
case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR: { text = "VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR"; break; }
case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR: { text = "VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR"; break; }
case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR: { text = "VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR"; break; }
case VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR: { text = "VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR"; break; }
};
return text;
}
void BuildFences(
Krust::Device& device,
const VkFenceCreateFlags flags,
const size_t numSwapChainImageViews,
std::vector<FencePtr>& outSwapChainFences)
{
outSwapChainFences.resize(numSwapChainImageViews);
for(unsigned i = 0; i < numSwapChainImageViews; ++i)
{
outSwapChainFences[i] = Fence::New(device, flags);
}
}
bool BuildFramebuffersForSwapChain(
Krust::Device& device,
const std::vector<VkImageView>& swapChainImageViews,
const VkImageView depthBufferView,
const uint32_t surfaceWidth, const uint32_t surfaceHeight,
const VkFormat colorFormat,
const VkFormat depthFormat,
const VkSampleCountFlagBits colorSamples,
std::vector<VkRenderPass>& outRenderPasses,
std::vector<VkFramebuffer>& outSwapChainFramebuffers,
std::vector<FencePtr>& outSwapChainFences)
{
// Create RenderPass per swap chain image:
VkAttachmentDescription attachments[2];
attachments[0].flags = 0,
attachments[0].format = colorFormat,
attachments[0].samples = colorSamples,
attachments[0].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR,
attachments[0].storeOp = VK_ATTACHMENT_STORE_OP_STORE,
attachments[0].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE,
attachments[0].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE,
attachments[0].initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
attachments[0].finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
attachments[1].flags = 0,
attachments[1].format = depthFormat,
attachments[1].samples = colorSamples,
attachments[1].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR,
attachments[1].storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE,
attachments[1].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE,
attachments[1].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE,
attachments[1].initialLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
attachments[1].finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
VkAttachmentReference subpassColorAttachment;
subpassColorAttachment.attachment = 0,
subpassColorAttachment.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
VkAttachmentReference depthStencilAttachment;
depthStencilAttachment.attachment = 1,
depthStencilAttachment.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
VkSubpassDescription subpass;
subpass.flags = 0,
subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS,
// Which of the two attachments of the RenderPass will be read at the start of
// the Subpass. Since we do a clear at the start, we read zero of them.
subpass.inputAttachmentCount = 0,
subpass.pInputAttachments = nullptr,
subpass.colorAttachmentCount = 1,
subpass.pColorAttachments = &subpassColorAttachment,
// Attachments to resolve multisample color into be we are not doing AA:
subpass.pResolveAttachments = nullptr,
subpass.pDepthStencilAttachment = &depthStencilAttachment,
// Non-modified attachments which must be preserved:
subpass.preserveAttachmentCount = 0,
subpass.pPreserveAttachments = nullptr;
auto renderPassInfo = RenderPassCreateInfo();
renderPassInfo.flags = 0,
renderPassInfo.attachmentCount = 2, // Depth and color.
renderPassInfo.pAttachments = attachments,
renderPassInfo.subpassCount = 1,
renderPassInfo.pSubpasses = &subpass,
// List of subpass pairs where the execution of flagged stages of the second
// must wait for flagged stages of the first to complete,
// but there is only one subpass so that is irrelevant:
renderPassInfo.dependencyCount = 0,
renderPassInfo.pDependencies = nullptr;
KRUST_ASSERT1(outRenderPasses.size() == 0, "Double init of primary view renderpasses.");
for(unsigned i = 0; i < swapChainImageViews.size(); ++i)
{
VkRenderPass renderPass;
VK_CALL_RET(vkCreateRenderPass, device, &renderPassInfo, Krust::Internal::sAllocator, &renderPass);
outRenderPasses.push_back(renderPass);
}
// Create a FrameBuffer object for each image in the swapchain that we are
// going to be presenting to the screen:
// Populate the second attachment as our depth buffer:
VkImageView colorDepthViews[2];
colorDepthViews[1] = depthBufferView;
outSwapChainFramebuffers.resize(swapChainImageViews.size());
auto framebufferInfo = FramebufferCreateInfo();
framebufferInfo.flags = 0,
framebufferInfo.renderPass = nullptr, // Init this inside loop below.
framebufferInfo.attachmentCount = 2,
framebufferInfo.pAttachments = colorDepthViews,
framebufferInfo.width = surfaceWidth,
framebufferInfo.height = surfaceHeight,
framebufferInfo.layers = 1;
for(unsigned i = 0; i < outSwapChainFramebuffers.size(); ++i)
{
framebufferInfo.renderPass = outRenderPasses[i];
colorDepthViews[0] = swapChainImageViews[i]; // Reset color buffer, but share depth.
VK_CALL_RET(vkCreateFramebuffer, device, &framebufferInfo, Krust::Internal::sAllocator, &outSwapChainFramebuffers[i]);
}
BuildFences(device, VK_FENCE_CREATE_SIGNALED_BIT, swapChainImageViews.size(), outSwapChainFences);
return true;
}
const char* FormatToString(const VkFormat format)
{
const char *string = "<<Unknown Format>>";
// Recreate contents with: %s/\(VK_FORMAT.*\) = .*,$/case \1: { string = "\1"; break; }/
switch (format) {
case VK_FORMAT_UNDEFINED: { string = "VK_FORMAT_UNDEFINED"; break; }
case VK_FORMAT_R4G4_UNORM_PACK8: { string = "VK_FORMAT_R4G4_UNORM_PACK8"; break; }
case VK_FORMAT_R4G4B4A4_UNORM_PACK16: { string = "VK_FORMAT_R4G4B4A4_UNORM_PACK16"; break; }
case VK_FORMAT_B4G4R4A4_UNORM_PACK16: { string = "VK_FORMAT_B4G4R4A4_UNORM_PACK16"; break; }
case VK_FORMAT_R5G6B5_UNORM_PACK16: { string = "VK_FORMAT_R5G6B5_UNORM_PACK16"; break; }
case VK_FORMAT_B5G6R5_UNORM_PACK16: { string = "VK_FORMAT_B5G6R5_UNORM_PACK16"; break; }
case VK_FORMAT_R5G5B5A1_UNORM_PACK16: { string = "VK_FORMAT_R5G5B5A1_UNORM_PACK16"; break; }
case VK_FORMAT_B5G5R5A1_UNORM_PACK16: { string = "VK_FORMAT_B5G5R5A1_UNORM_PACK16"; break; }
case VK_FORMAT_A1R5G5B5_UNORM_PACK16: { string = "VK_FORMAT_A1R5G5B5_UNORM_PACK16"; break; }
case VK_FORMAT_R8_UNORM: { string = "VK_FORMAT_R8_UNORM"; break; }
case VK_FORMAT_R8_SNORM: { string = "VK_FORMAT_R8_SNORM"; break; }
case VK_FORMAT_R8_USCALED: { string = "VK_FORMAT_R8_USCALED"; break; }
case VK_FORMAT_R8_SSCALED: { string = "VK_FORMAT_R8_SSCALED"; break; }
case VK_FORMAT_R8_UINT: { string = "VK_FORMAT_R8_UINT"; break; }
case VK_FORMAT_R8_SINT: { string = "VK_FORMAT_R8_SINT"; break; }
case VK_FORMAT_R8_SRGB: { string = "VK_FORMAT_R8_SRGB"; break; }
case VK_FORMAT_R8G8_UNORM: { string = "VK_FORMAT_R8G8_UNORM"; break; }
case VK_FORMAT_R8G8_SNORM: { string = "VK_FORMAT_R8G8_SNORM"; break; }
case VK_FORMAT_R8G8_USCALED: { string = "VK_FORMAT_R8G8_USCALED"; break; }
case VK_FORMAT_R8G8_SSCALED: { string = "VK_FORMAT_R8G8_SSCALED"; break; }
case VK_FORMAT_R8G8_UINT: { string = "VK_FORMAT_R8G8_UINT"; break; }
case VK_FORMAT_R8G8_SINT: { string = "VK_FORMAT_R8G8_SINT"; break; }
case VK_FORMAT_R8G8_SRGB: { string = "VK_FORMAT_R8G8_SRGB"; break; }
case VK_FORMAT_R8G8B8_UNORM: { string = "VK_FORMAT_R8G8B8_UNORM"; break; }
case VK_FORMAT_R8G8B8_SNORM: { string = "VK_FORMAT_R8G8B8_SNORM"; break; }
case VK_FORMAT_R8G8B8_USCALED: { string = "VK_FORMAT_R8G8B8_USCALED"; break; }
case VK_FORMAT_R8G8B8_SSCALED: { string = "VK_FORMAT_R8G8B8_SSCALED"; break; }
case VK_FORMAT_R8G8B8_UINT: { string = "VK_FORMAT_R8G8B8_UINT"; break; }
case VK_FORMAT_R8G8B8_SINT: { string = "VK_FORMAT_R8G8B8_SINT"; break; }
case VK_FORMAT_R8G8B8_SRGB: { string = "VK_FORMAT_R8G8B8_SRGB"; break; }
case VK_FORMAT_B8G8R8_UNORM: { string = "VK_FORMAT_B8G8R8_UNORM"; break; }
case VK_FORMAT_B8G8R8_SNORM: { string = "VK_FORMAT_B8G8R8_SNORM"; break; }
case VK_FORMAT_B8G8R8_USCALED: { string = "VK_FORMAT_B8G8R8_USCALED"; break; }
case VK_FORMAT_B8G8R8_SSCALED: { string = "VK_FORMAT_B8G8R8_SSCALED"; break; }
case VK_FORMAT_B8G8R8_UINT: { string = "VK_FORMAT_B8G8R8_UINT"; break; }
case VK_FORMAT_B8G8R8_SINT: { string = "VK_FORMAT_B8G8R8_SINT"; break; }
case VK_FORMAT_B8G8R8_SRGB: { string = "VK_FORMAT_B8G8R8_SRGB"; break; }
case VK_FORMAT_R8G8B8A8_UNORM: { string = "VK_FORMAT_R8G8B8A8_UNORM"; break; }
case VK_FORMAT_R8G8B8A8_SNORM: { string = "VK_FORMAT_R8G8B8A8_SNORM"; break; }
case VK_FORMAT_R8G8B8A8_USCALED: { string = "VK_FORMAT_R8G8B8A8_USCALED"; break; }
case VK_FORMAT_R8G8B8A8_SSCALED: { string = "VK_FORMAT_R8G8B8A8_SSCALED"; break; }
case VK_FORMAT_R8G8B8A8_UINT: { string = "VK_FORMAT_R8G8B8A8_UINT"; break; }
case VK_FORMAT_R8G8B8A8_SINT: { string = "VK_FORMAT_R8G8B8A8_SINT"; break; }
case VK_FORMAT_R8G8B8A8_SRGB: { string = "VK_FORMAT_R8G8B8A8_SRGB"; break; }
case VK_FORMAT_B8G8R8A8_UNORM: { string = "VK_FORMAT_B8G8R8A8_UNORM"; break; }
case VK_FORMAT_B8G8R8A8_SNORM: { string = "VK_FORMAT_B8G8R8A8_SNORM"; break; }
case VK_FORMAT_B8G8R8A8_USCALED: { string = "VK_FORMAT_B8G8R8A8_USCALED"; break; }
case VK_FORMAT_B8G8R8A8_SSCALED: { string = "VK_FORMAT_B8G8R8A8_SSCALED"; break; }
case VK_FORMAT_B8G8R8A8_UINT: { string = "VK_FORMAT_B8G8R8A8_UINT"; break; }
case VK_FORMAT_B8G8R8A8_SINT: { string = "VK_FORMAT_B8G8R8A8_SINT"; break; }
case VK_FORMAT_B8G8R8A8_SRGB: { string = "VK_FORMAT_B8G8R8A8_SRGB"; break; }
case VK_FORMAT_A8B8G8R8_UNORM_PACK32: { string = "VK_FORMAT_A8B8G8R8_UNORM_PACK32"; break; }
case VK_FORMAT_A8B8G8R8_SNORM_PACK32: { string = "VK_FORMAT_A8B8G8R8_SNORM_PACK32"; break; }
case VK_FORMAT_A8B8G8R8_USCALED_PACK32: { string = "VK_FORMAT_A8B8G8R8_USCALED_PACK32"; break; }
case VK_FORMAT_A8B8G8R8_SSCALED_PACK32: { string = "VK_FORMAT_A8B8G8R8_SSCALED_PACK32"; break; }
case VK_FORMAT_A8B8G8R8_UINT_PACK32: { string = "VK_FORMAT_A8B8G8R8_UINT_PACK32"; break; }
case VK_FORMAT_A8B8G8R8_SINT_PACK32: { string = "VK_FORMAT_A8B8G8R8_SINT_PACK32"; break; }
case VK_FORMAT_A8B8G8R8_SRGB_PACK32: { string = "VK_FORMAT_A8B8G8R8_SRGB_PACK32"; break; }
case VK_FORMAT_A2R10G10B10_UNORM_PACK32: { string = "VK_FORMAT_A2R10G10B10_UNORM_PACK32"; break; }
case VK_FORMAT_A2R10G10B10_SNORM_PACK32: { string = "VK_FORMAT_A2R10G10B10_SNORM_PACK32"; break; }
case VK_FORMAT_A2R10G10B10_USCALED_PACK32: { string = "VK_FORMAT_A2R10G10B10_USCALED_PACK32"; break; }
case VK_FORMAT_A2R10G10B10_SSCALED_PACK32: { string = "VK_FORMAT_A2R10G10B10_SSCALED_PACK32"; break; }
case VK_FORMAT_A2R10G10B10_UINT_PACK32: { string = "VK_FORMAT_A2R10G10B10_UINT_PACK32"; break; }
case VK_FORMAT_A2R10G10B10_SINT_PACK32: { string = "VK_FORMAT_A2R10G10B10_SINT_PACK32"; break; }
case VK_FORMAT_A2B10G10R10_UNORM_PACK32: { string = "VK_FORMAT_A2B10G10R10_UNORM_PACK32"; break; }
case VK_FORMAT_A2B10G10R10_SNORM_PACK32: { string = "VK_FORMAT_A2B10G10R10_SNORM_PACK32"; break; }
case VK_FORMAT_A2B10G10R10_USCALED_PACK32: { string = "VK_FORMAT_A2B10G10R10_USCALED_PACK32"; break; }
case VK_FORMAT_A2B10G10R10_SSCALED_PACK32: { string = "VK_FORMAT_A2B10G10R10_SSCALED_PACK32"; break; }
case VK_FORMAT_A2B10G10R10_UINT_PACK32: { string = "VK_FORMAT_A2B10G10R10_UINT_PACK32"; break; }
case VK_FORMAT_A2B10G10R10_SINT_PACK32: { string = "VK_FORMAT_A2B10G10R10_SINT_PACK32"; break; }
case VK_FORMAT_R16_UNORM: { string = "VK_FORMAT_R16_UNORM"; break; }
case VK_FORMAT_R16_SNORM: { string = "VK_FORMAT_R16_SNORM"; break; }
case VK_FORMAT_R16_USCALED: { string = "VK_FORMAT_R16_USCALED"; break; }
case VK_FORMAT_R16_SSCALED: { string = "VK_FORMAT_R16_SSCALED"; break; }
case VK_FORMAT_R16_UINT: { string = "VK_FORMAT_R16_UINT"; break; }
case VK_FORMAT_R16_SINT: { string = "VK_FORMAT_R16_SINT"; break; }
case VK_FORMAT_R16_SFLOAT: { string = "VK_FORMAT_R16_SFLOAT"; break; }
case VK_FORMAT_R16G16_UNORM: { string = "VK_FORMAT_R16G16_UNORM"; break; }
case VK_FORMAT_R16G16_SNORM: { string = "VK_FORMAT_R16G16_SNORM"; break; }
case VK_FORMAT_R16G16_USCALED: { string = "VK_FORMAT_R16G16_USCALED"; break; }
case VK_FORMAT_R16G16_SSCALED: { string = "VK_FORMAT_R16G16_SSCALED"; break; }
case VK_FORMAT_R16G16_UINT: { string = "VK_FORMAT_R16G16_UINT"; break; }
case VK_FORMAT_R16G16_SINT: { string = "VK_FORMAT_R16G16_SINT"; break; }
case VK_FORMAT_R16G16_SFLOAT: { string = "VK_FORMAT_R16G16_SFLOAT"; break; }
case VK_FORMAT_R16G16B16_UNORM: { string = "VK_FORMAT_R16G16B16_UNORM"; break; }
case VK_FORMAT_R16G16B16_SNORM: { string = "VK_FORMAT_R16G16B16_SNORM"; break; }
case VK_FORMAT_R16G16B16_USCALED: { string = "VK_FORMAT_R16G16B16_USCALED"; break; }
case VK_FORMAT_R16G16B16_SSCALED: { string = "VK_FORMAT_R16G16B16_SSCALED"; break; }
case VK_FORMAT_R16G16B16_UINT: { string = "VK_FORMAT_R16G16B16_UINT"; break; }
case VK_FORMAT_R16G16B16_SINT: { string = "VK_FORMAT_R16G16B16_SINT"; break; }
case VK_FORMAT_R16G16B16_SFLOAT: { string = "VK_FORMAT_R16G16B16_SFLOAT"; break; }
case VK_FORMAT_R16G16B16A16_UNORM: { string = "VK_FORMAT_R16G16B16A16_UNORM"; break; }
case VK_FORMAT_R16G16B16A16_SNORM: { string = "VK_FORMAT_R16G16B16A16_SNORM"; break; }
case VK_FORMAT_R16G16B16A16_USCALED: { string = "VK_FORMAT_R16G16B16A16_USCALED"; break; }
case VK_FORMAT_R16G16B16A16_SSCALED: { string = "VK_FORMAT_R16G16B16A16_SSCALED"; break; }
case VK_FORMAT_R16G16B16A16_UINT: { string = "VK_FORMAT_R16G16B16A16_UINT"; break; }
case VK_FORMAT_R16G16B16A16_SINT: { string = "VK_FORMAT_R16G16B16A16_SINT"; break; }
case VK_FORMAT_R16G16B16A16_SFLOAT: { string = "VK_FORMAT_R16G16B16A16_SFLOAT"; break; }
case VK_FORMAT_R32_UINT: { string = "VK_FORMAT_R32_UINT"; break; }
case VK_FORMAT_R32_SINT: { string = "VK_FORMAT_R32_SINT"; break; }
case VK_FORMAT_R32_SFLOAT: { string = "VK_FORMAT_R32_SFLOAT"; break; }
case VK_FORMAT_R32G32_UINT: { string = "VK_FORMAT_R32G32_UINT"; break; }
case VK_FORMAT_R32G32_SINT: { string = "VK_FORMAT_R32G32_SINT"; break; }
case VK_FORMAT_R32G32_SFLOAT: { string = "VK_FORMAT_R32G32_SFLOAT"; break; }
case VK_FORMAT_R32G32B32_UINT: { string = "VK_FORMAT_R32G32B32_UINT"; break; }
case VK_FORMAT_R32G32B32_SINT: { string = "VK_FORMAT_R32G32B32_SINT"; break; }
case VK_FORMAT_R32G32B32_SFLOAT: { string = "VK_FORMAT_R32G32B32_SFLOAT"; break; }
case VK_FORMAT_R32G32B32A32_UINT: { string = "VK_FORMAT_R32G32B32A32_UINT"; break; }
case VK_FORMAT_R32G32B32A32_SINT: { string = "VK_FORMAT_R32G32B32A32_SINT"; break; }
case VK_FORMAT_R32G32B32A32_SFLOAT: { string = "VK_FORMAT_R32G32B32A32_SFLOAT"; break; }
case VK_FORMAT_R64_UINT: { string = "VK_FORMAT_R64_UINT"; break; }
case VK_FORMAT_R64_SINT: { string = "VK_FORMAT_R64_SINT"; break; }
case VK_FORMAT_R64_SFLOAT: { string = "VK_FORMAT_R64_SFLOAT"; break; }
case VK_FORMAT_R64G64_UINT: { string = "VK_FORMAT_R64G64_UINT"; break; }
case VK_FORMAT_R64G64_SINT: { string = "VK_FORMAT_R64G64_SINT"; break; }
case VK_FORMAT_R64G64_SFLOAT: { string = "VK_FORMAT_R64G64_SFLOAT"; break; }
case VK_FORMAT_R64G64B64_UINT: { string = "VK_FORMAT_R64G64B64_UINT"; break; }
case VK_FORMAT_R64G64B64_SINT: { string = "VK_FORMAT_R64G64B64_SINT"; break; }
case VK_FORMAT_R64G64B64_SFLOAT: { string = "VK_FORMAT_R64G64B64_SFLOAT"; break; }
case VK_FORMAT_R64G64B64A64_UINT: { string = "VK_FORMAT_R64G64B64A64_UINT"; break; }
case VK_FORMAT_R64G64B64A64_SINT: { string = "VK_FORMAT_R64G64B64A64_SINT"; break; }
case VK_FORMAT_R64G64B64A64_SFLOAT: { string = "VK_FORMAT_R64G64B64A64_SFLOAT"; break; }
case VK_FORMAT_B10G11R11_UFLOAT_PACK32: { string = "VK_FORMAT_B10G11R11_UFLOAT_PACK32"; break; }
case VK_FORMAT_E5B9G9R9_UFLOAT_PACK32: { string = "VK_FORMAT_E5B9G9R9_UFLOAT_PACK32"; break; }
case VK_FORMAT_D16_UNORM: { string = "VK_FORMAT_D16_UNORM"; break; }
case VK_FORMAT_X8_D24_UNORM_PACK32: { string = "VK_FORMAT_X8_D24_UNORM_PACK32"; break; }
case VK_FORMAT_D32_SFLOAT: { string = "VK_FORMAT_D32_SFLOAT"; break; }
case VK_FORMAT_S8_UINT: { string = "VK_FORMAT_S8_UINT"; break; }
case VK_FORMAT_D16_UNORM_S8_UINT: { string = "VK_FORMAT_D16_UNORM_S8_UINT"; break; }
case VK_FORMAT_D24_UNORM_S8_UINT: { string = "VK_FORMAT_D24_UNORM_S8_UINT"; break; }
case VK_FORMAT_D32_SFLOAT_S8_UINT: { string = "VK_FORMAT_D32_SFLOAT_S8_UINT"; break; }
case VK_FORMAT_BC1_RGB_UNORM_BLOCK: { string = "VK_FORMAT_BC1_RGB_UNORM_BLOCK"; break; }
case VK_FORMAT_BC1_RGB_SRGB_BLOCK: { string = "VK_FORMAT_BC1_RGB_SRGB_BLOCK"; break; }
case VK_FORMAT_BC1_RGBA_UNORM_BLOCK: { string = "VK_FORMAT_BC1_RGBA_UNORM_BLOCK"; break; }
case VK_FORMAT_BC1_RGBA_SRGB_BLOCK: { string = "VK_FORMAT_BC1_RGBA_SRGB_BLOCK"; break; }
case VK_FORMAT_BC2_UNORM_BLOCK: { string = "VK_FORMAT_BC2_UNORM_BLOCK"; break; }
case VK_FORMAT_BC2_SRGB_BLOCK: { string = "VK_FORMAT_BC2_SRGB_BLOCK"; break; }
case VK_FORMAT_BC3_UNORM_BLOCK: { string = "VK_FORMAT_BC3_UNORM_BLOCK"; break; }
case VK_FORMAT_BC3_SRGB_BLOCK: { string = "VK_FORMAT_BC3_SRGB_BLOCK"; break; }
case VK_FORMAT_BC4_UNORM_BLOCK: { string = "VK_FORMAT_BC4_UNORM_BLOCK"; break; }
case VK_FORMAT_BC4_SNORM_BLOCK: { string = "VK_FORMAT_BC4_SNORM_BLOCK"; break; }
case VK_FORMAT_BC5_UNORM_BLOCK: { string = "VK_FORMAT_BC5_UNORM_BLOCK"; break; }
case VK_FORMAT_BC5_SNORM_BLOCK: { string = "VK_FORMAT_BC5_SNORM_BLOCK"; break; }
case VK_FORMAT_BC6H_UFLOAT_BLOCK: { string = "VK_FORMAT_BC6H_UFLOAT_BLOCK"; break; }
case VK_FORMAT_BC6H_SFLOAT_BLOCK: { string = "VK_FORMAT_BC6H_SFLOAT_BLOCK"; break; }
case VK_FORMAT_BC7_UNORM_BLOCK: { string = "VK_FORMAT_BC7_UNORM_BLOCK"; break; }
case VK_FORMAT_BC7_SRGB_BLOCK: { string = "VK_FORMAT_BC7_SRGB_BLOCK"; break; }
case VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK: { string = "VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK"; break; }
case VK_FORMAT_ETC2_R8G8B8_SRGB_BLOCK: { string = "VK_FORMAT_ETC2_R8G8B8_SRGB_BLOCK"; break; }
case VK_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK: { string = "VK_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK"; break; }
case VK_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK: { string = "VK_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK"; break; }
case VK_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK: { string = "VK_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK"; break; }
case VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK: { string = "VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK"; break; }
case VK_FORMAT_EAC_R11_UNORM_BLOCK: { string = "VK_FORMAT_EAC_R11_UNORM_BLOCK"; break; }
case VK_FORMAT_EAC_R11_SNORM_BLOCK: { string = "VK_FORMAT_EAC_R11_SNORM_BLOCK"; break; }
case VK_FORMAT_EAC_R11G11_UNORM_BLOCK: { string = "VK_FORMAT_EAC_R11G11_UNORM_BLOCK"; break; }
case VK_FORMAT_EAC_R11G11_SNORM_BLOCK: { string = "VK_FORMAT_EAC_R11G11_SNORM_BLOCK"; break; }
case VK_FORMAT_ASTC_4x4_UNORM_BLOCK: { string = "VK_FORMAT_ASTC_4x4_UNORM_BLOCK"; break; }
case VK_FORMAT_ASTC_4x4_SRGB_BLOCK: { string = "VK_FORMAT_ASTC_4x4_SRGB_BLOCK"; break; }
case VK_FORMAT_ASTC_5x4_UNORM_BLOCK: { string = "VK_FORMAT_ASTC_5x4_UNORM_BLOCK"; break; }
case VK_FORMAT_ASTC_5x4_SRGB_BLOCK: { string = "VK_FORMAT_ASTC_5x4_SRGB_BLOCK"; break; }
case VK_FORMAT_ASTC_5x5_UNORM_BLOCK: { string = "VK_FORMAT_ASTC_5x5_UNORM_BLOCK"; break; }
case VK_FORMAT_ASTC_5x5_SRGB_BLOCK: { string = "VK_FORMAT_ASTC_5x5_SRGB_BLOCK"; break; }
case VK_FORMAT_ASTC_6x5_UNORM_BLOCK: { string = "VK_FORMAT_ASTC_6x5_UNORM_BLOCK"; break; }
case VK_FORMAT_ASTC_6x5_SRGB_BLOCK: { string = "VK_FORMAT_ASTC_6x5_SRGB_BLOCK"; break; }
case VK_FORMAT_ASTC_6x6_UNORM_BLOCK: { string = "VK_FORMAT_ASTC_6x6_UNORM_BLOCK"; break; }
case VK_FORMAT_ASTC_6x6_SRGB_BLOCK: { string = "VK_FORMAT_ASTC_6x6_SRGB_BLOCK"; break; }
case VK_FORMAT_ASTC_8x5_UNORM_BLOCK: { string = "VK_FORMAT_ASTC_8x5_UNORM_BLOCK"; break; }
case VK_FORMAT_ASTC_8x5_SRGB_BLOCK: { string = "VK_FORMAT_ASTC_8x5_SRGB_BLOCK"; break; }
case VK_FORMAT_ASTC_8x6_UNORM_BLOCK: { string = "VK_FORMAT_ASTC_8x6_UNORM_BLOCK"; break; }
case VK_FORMAT_ASTC_8x6_SRGB_BLOCK: { string = "VK_FORMAT_ASTC_8x6_SRGB_BLOCK"; break; }
case VK_FORMAT_ASTC_8x8_UNORM_BLOCK: { string = "VK_FORMAT_ASTC_8x8_UNORM_BLOCK"; break; }
case VK_FORMAT_ASTC_8x8_SRGB_BLOCK: { string = "VK_FORMAT_ASTC_8x8_SRGB_BLOCK"; break; }
case VK_FORMAT_ASTC_10x5_UNORM_BLOCK: { string = "VK_FORMAT_ASTC_10x5_UNORM_BLOCK"; break; }
case VK_FORMAT_ASTC_10x5_SRGB_BLOCK: { string = "VK_FORMAT_ASTC_10x5_SRGB_BLOCK"; break; }
case VK_FORMAT_ASTC_10x6_UNORM_BLOCK: { string = "VK_FORMAT_ASTC_10x6_UNORM_BLOCK"; break; }
case VK_FORMAT_ASTC_10x6_SRGB_BLOCK: { string = "VK_FORMAT_ASTC_10x6_SRGB_BLOCK"; break; }
case VK_FORMAT_ASTC_10x8_UNORM_BLOCK: { string = "VK_FORMAT_ASTC_10x8_UNORM_BLOCK"; break; }
case VK_FORMAT_ASTC_10x8_SRGB_BLOCK: { string = "VK_FORMAT_ASTC_10x8_SRGB_BLOCK"; break; }
case VK_FORMAT_ASTC_10x10_UNORM_BLOCK: { string = "VK_FORMAT_ASTC_10x10_UNORM_BLOCK"; break; }
case VK_FORMAT_ASTC_10x10_SRGB_BLOCK: { string = "VK_FORMAT_ASTC_10x10_SRGB_BLOCK"; break; }
case VK_FORMAT_ASTC_12x10_UNORM_BLOCK: { string = "VK_FORMAT_ASTC_12x10_UNORM_BLOCK"; break; }
case VK_FORMAT_ASTC_12x10_SRGB_BLOCK: { string = "VK_FORMAT_ASTC_12x10_SRGB_BLOCK"; break; }
case VK_FORMAT_ASTC_12x12_UNORM_BLOCK: { string = "VK_FORMAT_ASTC_12x12_UNORM_BLOCK"; break; }
case VK_FORMAT_ASTC_12x12_SRGB_BLOCK: { string = "VK_FORMAT_ASTC_12x12_SRGB_BLOCK"; break; }
case VK_FORMAT_G8B8G8R8_422_UNORM: { string = "VK_FORMAT_G8B8G8R8_422_UNORM"; break; }
case VK_FORMAT_B8G8R8G8_422_UNORM: { string = "VK_FORMAT_B8G8R8G8_422_UNORM"; break; }
case VK_FORMAT_G8_B8_R8_3PLANE_420_UNORM: { string = "VK_FORMAT_G8_B8_R8_3PLANE_420_UNORM"; break; }
case VK_FORMAT_G8_B8R8_2PLANE_420_UNORM: { string = "VK_FORMAT_G8_B8R8_2PLANE_420_UNORM"; break; }
case VK_FORMAT_G8_B8_R8_3PLANE_422_UNORM: { string = "VK_FORMAT_G8_B8_R8_3PLANE_422_UNORM"; break; }
case VK_FORMAT_G8_B8R8_2PLANE_422_UNORM: { string = "VK_FORMAT_G8_B8R8_2PLANE_422_UNORM"; break; }
case VK_FORMAT_G8_B8_R8_3PLANE_444_UNORM: { string = "VK_FORMAT_G8_B8_R8_3PLANE_444_UNORM"; break; }
case VK_FORMAT_R10X6_UNORM_PACK16: { string = "VK_FORMAT_R10X6_UNORM_PACK16"; break; }
case VK_FORMAT_R10X6G10X6_UNORM_2PACK16: { string = "VK_FORMAT_R10X6G10X6_UNORM_2PACK16"; break; }
case VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16: { string = "VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16"; break; }
case VK_FORMAT_G10X6B10X6G10X6R10X6_422_UNORM_4PACK16: { string = "VK_FORMAT_G10X6B10X6G10X6R10X6_422_UNORM_4PACK16"; break; }
case VK_FORMAT_B10X6G10X6R10X6G10X6_422_UNORM_4PACK16: { string = "VK_FORMAT_B10X6G10X6R10X6G10X6_422_UNORM_4PACK16"; break; }
case VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_420_UNORM_3PACK16: { string = "VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_420_UNORM_3PACK16"; break; }
case VK_FORMAT_G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16: { string = "VK_FORMAT_G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16"; break; }
case VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_422_UNORM_3PACK16: { string = "VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_422_UNORM_3PACK16"; break; }
case VK_FORMAT_G10X6_B10X6R10X6_2PLANE_422_UNORM_3PACK16: { string = "VK_FORMAT_G10X6_B10X6R10X6_2PLANE_422_UNORM_3PACK16"; break; }
case VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_444_UNORM_3PACK16: { string = "VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_444_UNORM_3PACK16"; break; }
case VK_FORMAT_R12X4_UNORM_PACK16: { string = "VK_FORMAT_R12X4_UNORM_PACK16"; break; }
case VK_FORMAT_R12X4G12X4_UNORM_2PACK16: { string = "VK_FORMAT_R12X4G12X4_UNORM_2PACK16"; break; }
case VK_FORMAT_R12X4G12X4B12X4A12X4_UNORM_4PACK16: { string = "VK_FORMAT_R12X4G12X4B12X4A12X4_UNORM_4PACK16"; break; }
case VK_FORMAT_G12X4B12X4G12X4R12X4_422_UNORM_4PACK16: { string = "VK_FORMAT_G12X4B12X4G12X4R12X4_422_UNORM_4PACK16"; break; }
case VK_FORMAT_B12X4G12X4R12X4G12X4_422_UNORM_4PACK16: { string = "VK_FORMAT_B12X4G12X4R12X4G12X4_422_UNORM_4PACK16"; break; }
case VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_420_UNORM_3PACK16: { string = "VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_420_UNORM_3PACK16"; break; }
case VK_FORMAT_G12X4_B12X4R12X4_2PLANE_420_UNORM_3PACK16: { string = "VK_FORMAT_G12X4_B12X4R12X4_2PLANE_420_UNORM_3PACK16"; break; }
case VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_422_UNORM_3PACK16: { string = "VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_422_UNORM_3PACK16"; break; }
case VK_FORMAT_G12X4_B12X4R12X4_2PLANE_422_UNORM_3PACK16: { string = "VK_FORMAT_G12X4_B12X4R12X4_2PLANE_422_UNORM_3PACK16"; break; }
case VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_444_UNORM_3PACK16: { string = "VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_444_UNORM_3PACK16"; break; }
case VK_FORMAT_G16B16G16R16_422_UNORM: { string = "VK_FORMAT_G16B16G16R16_422_UNORM"; break; }
case VK_FORMAT_B16G16R16G16_422_UNORM: { string = "VK_FORMAT_B16G16R16G16_422_UNORM"; break; }
case VK_FORMAT_G16_B16_R16_3PLANE_420_UNORM: { string = "VK_FORMAT_G16_B16_R16_3PLANE_420_UNORM"; break; }
case VK_FORMAT_G16_B16R16_2PLANE_420_UNORM: { string = "VK_FORMAT_G16_B16R16_2PLANE_420_UNORM"; break; }
case VK_FORMAT_G16_B16_R16_3PLANE_422_UNORM: { string = "VK_FORMAT_G16_B16_R16_3PLANE_422_UNORM"; break; }
case VK_FORMAT_G16_B16R16_2PLANE_422_UNORM: { string = "VK_FORMAT_G16_B16R16_2PLANE_422_UNORM"; break; }
case VK_FORMAT_G16_B16_R16_3PLANE_444_UNORM: { string = "VK_FORMAT_G16_B16_R16_3PLANE_444_UNORM"; break; }
case VK_FORMAT_PVRTC1_2BPP_UNORM_BLOCK_IMG: { string = "VK_FORMAT_PVRTC1_2BPP_UNORM_BLOCK_IMG"; break; }
case VK_FORMAT_PVRTC1_4BPP_UNORM_BLOCK_IMG: { string = "VK_FORMAT_PVRTC1_4BPP_UNORM_BLOCK_IMG"; break; }
case VK_FORMAT_PVRTC2_2BPP_UNORM_BLOCK_IMG: { string = "VK_FORMAT_PVRTC2_2BPP_UNORM_BLOCK_IMG"; break; }
case VK_FORMAT_PVRTC2_4BPP_UNORM_BLOCK_IMG: { string = "VK_FORMAT_PVRTC2_4BPP_UNORM_BLOCK_IMG"; break; }
case VK_FORMAT_PVRTC1_2BPP_SRGB_BLOCK_IMG: { string = "VK_FORMAT_PVRTC1_2BPP_SRGB_BLOCK_IMG"; break; }
case VK_FORMAT_PVRTC1_4BPP_SRGB_BLOCK_IMG: { string = "VK_FORMAT_PVRTC1_4BPP_SRGB_BLOCK_IMG"; break; }
case VK_FORMAT_PVRTC2_2BPP_SRGB_BLOCK_IMG: { string = "VK_FORMAT_PVRTC2_2BPP_SRGB_BLOCK_IMG"; break; }
case VK_FORMAT_PVRTC2_4BPP_SRGB_BLOCK_IMG: { string = "VK_FORMAT_PVRTC2_4BPP_SRGB_BLOCK_IMG"; break; }
case VK_FORMAT_ASTC_4x4_SFLOAT_BLOCK_EXT: { string = "VK_FORMAT_ASTC_4x4_SFLOAT_BLOCK_EXT"; break; }
case VK_FORMAT_ASTC_5x4_SFLOAT_BLOCK_EXT: { string = "VK_FORMAT_ASTC_5x4_SFLOAT_BLOCK_EXT"; break; }
case VK_FORMAT_ASTC_5x5_SFLOAT_BLOCK_EXT: { string = "VK_FORMAT_ASTC_5x5_SFLOAT_BLOCK_EXT"; break; }
case VK_FORMAT_ASTC_6x5_SFLOAT_BLOCK_EXT: { string = "VK_FORMAT_ASTC_6x5_SFLOAT_BLOCK_EXT"; break; }
case VK_FORMAT_ASTC_6x6_SFLOAT_BLOCK_EXT: { string = "VK_FORMAT_ASTC_6x6_SFLOAT_BLOCK_EXT"; break; }
case VK_FORMAT_ASTC_8x5_SFLOAT_BLOCK_EXT: { string = "VK_FORMAT_ASTC_8x5_SFLOAT_BLOCK_EXT"; break; }
case VK_FORMAT_ASTC_8x6_SFLOAT_BLOCK_EXT: { string = "VK_FORMAT_ASTC_8x6_SFLOAT_BLOCK_EXT"; break; }
case VK_FORMAT_ASTC_8x8_SFLOAT_BLOCK_EXT: { string = "VK_FORMAT_ASTC_8x8_SFLOAT_BLOCK_EXT"; break; }
case VK_FORMAT_ASTC_10x5_SFLOAT_BLOCK_EXT: { string = "VK_FORMAT_ASTC_10x5_SFLOAT_BLOCK_EXT"; break; }
case VK_FORMAT_ASTC_10x6_SFLOAT_BLOCK_EXT: { string = "VK_FORMAT_ASTC_10x6_SFLOAT_BLOCK_EXT"; break; }
case VK_FORMAT_ASTC_10x8_SFLOAT_BLOCK_EXT: { string = "VK_FORMAT_ASTC_10x8_SFLOAT_BLOCK_EXT"; break; }
case VK_FORMAT_ASTC_10x10_SFLOAT_BLOCK_EXT: { string = "VK_FORMAT_ASTC_10x10_SFLOAT_BLOCK_EXT"; break; }
case VK_FORMAT_ASTC_12x10_SFLOAT_BLOCK_EXT: { string = "VK_FORMAT_ASTC_12x10_SFLOAT_BLOCK_EXT"; break; }
case VK_FORMAT_ASTC_12x12_SFLOAT_BLOCK_EXT: { string = "VK_FORMAT_ASTC_12x12_SFLOAT_BLOCK_EXT"; break; }
case VK_FORMAT_G8_B8R8_2PLANE_444_UNORM_EXT: { string = "VK_FORMAT_G8_B8R8_2PLANE_444_UNORM_EXT"; break; }
case VK_FORMAT_G10X6_B10X6R10X6_2PLANE_444_UNORM_3PACK16_EXT: { string = "VK_FORMAT_G10X6_B10X6R10X6_2PLANE_444_UNORM_3PACK16_EXT"; break; }
case VK_FORMAT_G12X4_B12X4R12X4_2PLANE_444_UNORM_3PACK16_EXT: { string = "VK_FORMAT_G12X4_B12X4R12X4_2PLANE_444_UNORM_3PACK16_EXT"; break; }
case VK_FORMAT_G16_B16R16_2PLANE_444_UNORM_EXT: { string = "VK_FORMAT_G16_B16R16_2PLANE_444_UNORM_EXT"; break; }
case VK_FORMAT_A4R4G4B4_UNORM_PACK16_EXT: { string = "VK_FORMAT_A4R4G4B4_UNORM_PACK16_EXT"; break; }
case VK_FORMAT_A4B4G4R4_UNORM_PACK16_EXT: { string = "VK_FORMAT_A4B4G4R4_UNORM_PACK16_EXT"; break; }
// Specials (not actually formats):
//case VK_FORMAT_RANGE_SIZE: { string = "VK_FORMAT_RANGE_SIZE"; break; }
case VK_FORMAT_MAX_ENUM: {string = "VK_FORMAT_MAX_ENUM"; break; };
};
return string;
}
const char* KHRColorspaceToString(const VkColorSpaceKHR space)
{
// KRUST_ASSERT2(space <= VK_COLOR_SPACE_END_RANGE_KHR, "Out of range color space.");
const char* string = "<<unkown colorspace>>";
// recreate cases below with: %s/\(VK_.*\) = .*,$/case \1: { string = "\1"; break; }/
switch (space) {
case VK_COLOR_SPACE_SRGB_NONLINEAR_KHR: { string = "VK_COLOR_SPACE_SRGB_NONLINEAR_KHR"; break; }
case VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT: { string = "VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT"; break; }
case VK_COLOR_SPACE_EXTENDED_SRGB_LINEAR_EXT: { string = "VK_COLOR_SPACE_EXTENDED_SRGB_LINEAR_EXT"; break; }
case VK_COLOR_SPACE_DISPLAY_P3_LINEAR_EXT: { string = "VK_COLOR_SPACE_DISPLAY_P3_LINEAR_EXT"; break; }
case VK_COLOR_SPACE_DCI_P3_NONLINEAR_EXT: { string = "VK_COLOR_SPACE_DCI_P3_NONLINEAR_EXT"; break; }
case VK_COLOR_SPACE_BT709_LINEAR_EXT: { string = "VK_COLOR_SPACE_BT709_LINEAR_EXT"; break; }
case VK_COLOR_SPACE_BT709_NONLINEAR_EXT: { string = "VK_COLOR_SPACE_BT709_NONLINEAR_EXT"; break; }
case VK_COLOR_SPACE_BT2020_LINEAR_EXT: { string = "VK_COLOR_SPACE_BT2020_LINEAR_EXT"; break; }
case VK_COLOR_SPACE_HDR10_ST2084_EXT: { string = "VK_COLOR_SPACE_HDR10_ST2084_EXT"; break; }
case VK_COLOR_SPACE_DOLBYVISION_EXT: { string = "VK_COLOR_SPACE_DOLBYVISION_EXT"; break; }
case VK_COLOR_SPACE_HDR10_HLG_EXT: { string = "VK_COLOR_SPACE_HDR10_HLG_EXT"; break; }
case VK_COLOR_SPACE_ADOBERGB_LINEAR_EXT: { string = "VK_COLOR_SPACE_ADOBERGB_LINEAR_EXT"; break; }
case VK_COLOR_SPACE_ADOBERGB_NONLINEAR_EXT: { string = "VK_COLOR_SPACE_ADOBERGB_NONLINEAR_EXT"; break; }
case VK_COLOR_SPACE_PASS_THROUGH_EXT: { string = "VK_COLOR_SPACE_PASS_THROUGH_EXT"; break; }
case VK_COLOR_SPACE_EXTENDED_SRGB_NONLINEAR_EXT: { string = "VK_COLOR_SPACE_EXTENDED_SRGB_NONLINEAR_EXT"; break; }
case VK_COLOR_SPACE_DISPLAY_NATIVE_AMD: { string = "VK_COLOR_SPACE_DISPLAY_NATIVE_AMD"; break; }
// case VK_COLOR_SPACE_RANGE_SIZE_KHR: {string = "<<invalid: VK_COLORSPACE_RANGE_SIZE>>"; break; };
case VK_COLOR_SPACE_MAX_ENUM_KHR: {string = "<<invalid: VK_COLORSPACE_MAX_ENUM>>"; break; };
}
return string;
}
bool FindExtension(const std::vector<VkExtensionProperties> &extensions, const char *const extension) {
KRUST_ASSERT1(extension, "Name of extension to look up is missing.");
for (auto potential : extensions) {
if (strcmp(extension, potential.extensionName) == 0) {
return true;
}
}
KRUST_LOG_WARN << "Failed to find extension \"" << extension << "\"." << endlog;
return false;
}
bool FindLayer(const std::vector<VkLayerProperties> &layers, const char *const layer) {
KRUST_ASSERT1(layer, "Name of extension to look up is missing.");
for (auto potential : layers) {
if (strcmp(layer, potential.layerName) == 0) {
return true;
}
}
KRUST_LOG_WARN << "Failed to find layer \"" << layer << "\"." << endlog;
return false;
}
const char *MessageFlagsToLevel(const VkFlags flags)
{
const char* level = "UNKNOWN";
switch (flags)
{
case VK_DEBUG_REPORT_INFORMATION_BIT_EXT: { level = "INFO"; break; }
case VK_DEBUG_REPORT_WARNING_BIT_EXT: { level = "WARN"; break; }
case VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT: { level = "PERF_WARN"; break; }
case VK_DEBUG_REPORT_ERROR_BIT_EXT: { level = "ERROR"; break; }
case VK_DEBUG_REPORT_DEBUG_BIT_EXT: { level = "DEBUG"; break; }
}
return level;
}
std::vector<VkExtensionProperties>
EnumerateDeviceExtensionProperties(VkPhysicalDevice &gpu,
const char *const name) {
uint32_t count = 0;
std::vector<VkExtensionProperties> properties;
VkResult result = vkEnumerateDeviceExtensionProperties(gpu, name, &count, 0);
if (result == VK_SUCCESS) {
properties.resize(count);
result = vkEnumerateDeviceExtensionProperties(gpu, name, &count, &properties[0]);
if (result != VK_SUCCESS) {
properties.clear();
KRUST_LOG_ERROR << "Error getting physical device extensions: " << ResultToString(result) << endlog;
}
}
return properties;
}
std::vector<VkLayerProperties> EnumerateDeviceLayerProperties(
const VkPhysicalDevice &gpu) {
uint32_t layerCount = 0;
std::vector<VkLayerProperties> layerProperties;
VkResult result = vkEnumerateDeviceLayerProperties(gpu, &layerCount, 0);
if (result == VK_SUCCESS) {
layerProperties.resize(layerCount);
result = vkEnumerateDeviceLayerProperties(gpu, &layerCount, &layerProperties[0]);
if (result != VK_SUCCESS) {
layerProperties.resize(0);
}
}
if (result != VK_SUCCESS) {
KRUST_LOG_ERROR << "Failed to get GPU layer properties. Error: " << ResultToString(result) << endlog;
}
return layerProperties;
}
std::vector<VkQueueFamilyProperties> GetPhysicalDeviceQueueFamilyProperties(const VkPhysicalDevice gpu) {
uint32_t count = 0;
std::vector<VkQueueFamilyProperties> properties;
vkGetPhysicalDeviceQueueFamilyProperties(gpu, &count, 0);
properties.resize(count);
vkGetPhysicalDeviceQueueFamilyProperties(gpu, &count, &properties[0]);
return properties;
}
std::vector<VkExtensionProperties> GetGlobalExtensionProperties(const char *const name) {
VkResult result;
uint32_t extensionCount = 0;
std::vector<VkExtensionProperties> extensionProperties;
// We make the call once to get the size of the array to return and then again to
// actually populate an array:
result = vkEnumerateInstanceExtensionProperties(name, &extensionCount, 0);
if (result) {
KRUST_LOG_ERROR << ": vkGetGlobalExtensionProperties returned " << ResultToString(result) << ".\n";
}
else {
extensionProperties.resize(extensionCount);
result = vkEnumerateInstanceExtensionProperties(name, &extensionCount, &extensionProperties[0]);
KRUST_ASSERT1(extensionCount <= extensionProperties.size(), "Extension count changed.");
if (result) {
extensionProperties.clear();
KRUST_LOG_ERROR << ": vkGetGlobalExtensionProperties returned " << ResultToString(result) << ".\n";
}
}
return extensionProperties;
}
std::vector<VkLayerProperties> EnumerateInstanceLayerProperties() {
VkResult result;
uint32_t layerCount = 0;
std::vector<VkLayerProperties> layerProperties;
// We make the call once to get the size of the array to return and then again to
// actually populate an array:
result = vkEnumerateInstanceLayerProperties(&layerCount, 0);
if (result) {
KRUST_LOG_ERROR << ": vkGetGlobalLayerProperties returned " << ResultToString(result) << ".\n";
}
else {
layerProperties.resize(layerCount);
result = vkEnumerateInstanceLayerProperties(&layerCount, &layerProperties[0]);
KRUST_ASSERT1(layerCount <= layerProperties.size(), "Layer count changed");
if (result) {
layerProperties.clear();
KRUST_LOG_ERROR << ": vkGetGlobalLayerProperties returned " << ResultToString(result) << ".\n";
}
}
return layerProperties;
}
std::vector<VkPhysicalDevice> EnumeratePhysicalDevices(
const VkInstance &instance) {
uint32_t physicalDeviceCount;
std::vector<VkPhysicalDevice> physicalDevices;
// Query for the number of GPUs:
VkResult gpuResult = vkEnumeratePhysicalDevices(instance, &physicalDeviceCount, 0);
if (gpuResult == VK_SUCCESS) {
// Go ahead and get the list of GPUs:
physicalDevices.resize(physicalDeviceCount);
gpuResult = vkEnumeratePhysicalDevices(instance, &physicalDeviceCount, &physicalDevices[0]);
if (gpuResult != VK_SUCCESS) {
physicalDevices.resize(0);
}
}
if (gpuResult != VK_SUCCESS) {
KRUST_LOG_ERROR << "vkEnumeratePhysicalDevices() returned " << ResultToString(gpuResult) << ".\n";
}
return physicalDevices;
}
ScopedImageOwner::ScopedImageOwner(VkDevice dev, VkImage img) : device(dev), image(img)
{
KRUST_ASSERT2(dev || !img, "Need a device so the destroy will work later.");
}
ScopedImageOwner::~ScopedImageOwner()
{
if(image)
{
KRUST_ASSERT2(device, "No device so can't destroy.");
vkDestroyImage(device, image, Krust::Internal::sAllocator);
}
}
ScopedDeviceMemoryOwner::ScopedDeviceMemoryOwner(VkDevice dev,
VkDeviceMemory mem) :
device(dev), memory(mem)
{
KRUST_ASSERT2(dev || !mem, "Need a device so the free will work later.");
}
ScopedDeviceMemoryOwner::~ScopedDeviceMemoryOwner()
{
if(memory)
{
KRUST_ASSERT2(device, "No device so can't free.");
vkFreeMemory(device, memory, Krust::Internal::sAllocator);
}
}
}
| 57.573333 | 325 | 0.767195 | [
"object",
"vector",
"transform"
] |
18cf86e5bf90bc047e954f4c93d867c291ad4629 | 968 | cpp | C++ | src/bublle_sort.cpp | ebayboy/cpp_demos | b01df202c0285bf232900662d336505520d5d24d | [
"Apache-2.0"
] | null | null | null | src/bublle_sort.cpp | ebayboy/cpp_demos | b01df202c0285bf232900662d336505520d5d24d | [
"Apache-2.0"
] | null | null | null | src/bublle_sort.cpp | ebayboy/cpp_demos | b01df202c0285bf232900662d336505520d5d24d | [
"Apache-2.0"
] | null | null | null | /****************************************************************************
@file:bublle_sort.cpp
@author:ebayboy@163.com
@date:2019-11-20 00:39
@version: 1.0
@description: cpp file
@Copyright (c) all right reserved
**************************************************************************/
#include <iostream>
#include <string>
#include <numeric>
#include <vector>
#include <algorithm>
using namespace std;
#define DEBUG
void show_array(int *a, int len)
{
for (int i = 0; i < len; i++)
cout << *(a + i) << " ";
cout << endl;
}
void bubble_sort(int *a, int len)
{
int i, j;
int temp;
for (i = 0; i < len - 1; i++)
{
for (j = 0; j < len - 1 - i; j++)
{
if (a[j] > a[j + 1])
{
//swap
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
}
int main(int argc, char **argv)
{
int a[9] = {3, 1, 5, 4, 6, 2, 7, 9, 8};
show_array((int *)&a, 9);
bubble_sort((int *)&a, 9);
show_array((int *)&a, 9);
return 0;
}
| 16.689655 | 77 | 0.448347 | [
"vector"
] |
18da4f144c09ac88fed2f49c44ff5825175a882e | 2,798 | cpp | C++ | lib/scene/geometry/geometry_aggregate.cpp | b3h47pte/cuda-path-tracing | b874b86f15b4aca18ecd40e9eb962996298f5fa8 | [
"MIT"
] | null | null | null | lib/scene/geometry/geometry_aggregate.cpp | b3h47pte/cuda-path-tracing | b874b86f15b4aca18ecd40e9eb962996298f5fa8 | [
"MIT"
] | null | null | null | lib/scene/geometry/geometry_aggregate.cpp | b3h47pte/cuda-path-tracing | b874b86f15b4aca18ecd40e9eb962996298f5fa8 | [
"MIT"
] | null | null | null | #include "scene/geometry/geometry_aggregate.h"
#include "scene/geometry/triangle.h"
#include <unordered_set>
#include "utilities/eigen_utility.h"
#include "utilities/error.h"
namespace cpt {
GeometryAggregate::GeometryAggregate(
const std::vector<GeometryPtr>& children):
_children(children) {
// Ensure there are no duplicate children.
std::unordered_set<Geometry*> seen;
for (size_t i = 0; i < children.size(); ++i) {
CHECK_AND_THROW_ERROR(seen.find(children[i].get()) == seen.end(), "Geometry aggregate can not have duplicated children (for now).");
seen.insert(children[i].get());
}
}
GeometryAggregatePtr GeometryAggregateBuilder::construct() const {
auto vertex_container = std::make_shared<VertexContainer>();
vertex_container->positions = stl_vector_to_eigen_array(_pos);
vertex_container->uvs = stl_vector_to_eigen_array(_uv);
vertex_container->normals = stl_vector_to_eigen_array(_normals);
std::vector<GeometryPtr> children;
children.reserve(_face_pos_idx.size());
for (size_t i = 0; i < _face_pos_idx.size(); ++i) {
// Do sanitfy check to make sure the face indexes properly.
for (auto j = 0; j < 3; ++j) {
CHECK_AND_THROW_ERROR(
_face_pos_idx[i](j) >= 0 && _face_pos_idx[i](j) < vertex_container->num_positions(),
"Vertex position index out of bound.");
}
for (auto j = 0; j < 2; ++j) {
CHECK_AND_THROW_ERROR(
_face_uv_idx[i](j) >= 0 && _face_uv_idx[i](j) < vertex_container->num_uvs(),
"Vertex UV index out of bound.");
}
for (auto j = 0; j < 3; ++j) {
CHECK_AND_THROW_ERROR(
_face_normal_idx[i](j) >= 0 && _face_normal_idx[i](j) < vertex_container->num_normals(),
"Vertex normal index out of bound.");
}
children.emplace_back(std::make_shared<Triangle>(
vertex_container,
_face_pos_idx[i],
_face_uv_idx[i],
_face_normal_idx[i]));
}
auto geometry = std::make_shared<GeometryAggregate>(children);
return geometry;
}
void GeometryAggregateBuilder::add_vertex_position(const Eigen::Vector3f& pos) {
_pos.push_back(pos);
}
void GeometryAggregateBuilder::add_vertex_uv(const Eigen::Vector2f& uv) {
_uv.push_back(uv);
}
void GeometryAggregateBuilder::add_vertex_normal(const Eigen::Vector3f& normal) {
_normals.push_back(normal);
}
void GeometryAggregateBuilder::add_face(
const Eigen::Vector3i& vertex_indices,
const Eigen::Vector3i& uv_indices,
const Eigen::Vector3i& normal_indices) {
_face_pos_idx.push_back(vertex_indices);
_face_uv_idx.push_back(uv_indices);
_face_normal_idx.push_back(normal_indices);
}
}
| 34.121951 | 140 | 0.660829 | [
"geometry",
"vector"
] |
18dff101df7bb44f56efada3aaa51fb785ec9764 | 10,316 | cpp | C++ | src/state_space/state_publisher.cpp | cogsys-tuebingen/muse_armcl | 63eb0c8d3a1d03d84222acbb5b0c9978065bcc3c | [
"BSD-3-Clause"
] | 5 | 2020-01-19T09:35:28.000Z | 2021-11-04T10:08:24.000Z | src/state_space/state_publisher.cpp | cxdcxd/muse_armcl | 63eb0c8d3a1d03d84222acbb5b0c9978065bcc3c | [
"BSD-3-Clause"
] | null | null | null | src/state_space/state_publisher.cpp | cxdcxd/muse_armcl | 63eb0c8d3a1d03d84222acbb5b0c9978065bcc3c | [
"BSD-3-Clause"
] | 1 | 2019-11-10T23:40:59.000Z | 2019-11-10T23:40:59.000Z | #include <muse_armcl/state_space/state_publisher.h>
#include <muse_armcl/density/sample_density.hpp>
#include <cslibs_mesh_map/mesh_map_tree.h>
#include <cslibs_mesh_map/cslibs_mesh_map_visualization.h>
#include <cslibs_math_3d/linear/pointcloud.hpp>
#include <cslibs_math_ros/sensor_msgs/conversion_3d.hpp>
#include <cslibs_math_ros/geometry_msgs/conversion_3d.hpp>
#include <visualization_msgs/MarkerArray.h>
#include <sensor_msgs/PointCloud2.h>
#include <cslibs_kdl_msgs/ContactMessageArray.h>
namespace muse_armcl {
void StatePublisher::setup(ros::NodeHandle &nh, map_provider_map_t &map_providers)
{
const std::string map_provider_id = nh.param<std::string>("map", ""); /// toplevel parameter
if (map_provider_id == "")
throw std::runtime_error("[UniformSampling]: No map provider was found!");
if (map_providers.find(map_provider_id) == map_providers.end())
throw std::runtime_error("[UniformSampling]: Cannot find map provider '" + map_provider_id + "'!");
map_provider_ = map_providers.at(map_provider_id);
const std::string topic_particles = nh.param<std::string>("topic_particles", "particles");
const std::string topic_contacts = nh.param<std::string>("topic_contacts", "contacts");
const std::string topic_contacts_vis = nh.param<std::string>("topic_contacts_visualization", "contacts_visualization");
contact_marker_r_ = nh.param<double>("contact_marker_r", 0.0);
contact_marker_g_ = nh.param<double>("contact_marker_g", 0.0);
contact_marker_b_ = nh.param<double>("contact_marker_b", 1.0);
contact_marker_scale_x_ = nh.param<double>("contact_marker_scale_x", 0.005 * 1.9);
contact_marker_scale_y_ = nh.param<double>("contact_marker_scale_y", 0.01 * 2.8);
contact_marker_scale_z_ = nh.param<double>("contact_marker_scale_z", 0.01 * 3.3);
no_contact_torque_threshold_ = nh.param<double>("no_contact_threshold", 0.1);
std::string path;
path = nh.param<std::string>("contact_points_file", std::string(""));
if(path != ""){
std::vector<cslibs_kdl::KDLTransformation> labeled_contact_points;
cslibs_kdl::load(path, labeled_contact_points);
labeled_contact_points_.clear();
for(auto p : labeled_contact_points){
std::string name = p.name;
name.erase(0,1);
int label = std::stoi(name);
labeled_contact_points_[label] = p;
}
}
pub_particles_ = nh.advertise<sensor_msgs::PointCloud2>(topic_particles, 10);
pub_contacts_ = nh.advertise<cslibs_kdl_msgs::ContactMessageArray>(topic_contacts, 10);
pub_contacts_vis_ = nh.advertise<visualization_msgs::MarkerArray>(topic_contacts_vis, 1);
}
void StatePublisher::publish(const sample_set_t::ConstPtr &sample_set)
{
publish(sample_set, true);
}
void StatePublisher::publishIntermediate(const sample_set_t::ConstPtr &sample_set)
{
publish(sample_set, false);
}
void StatePublisher::publishConstant(const sample_set_t::ConstPtr &sample_set)
{
publish(sample_set, false);
}
void StatePublisher::publish(const sample_set_t::ConstPtr &sample_set, const bool &publish_contacts)
{
if (!map_provider_)
return;
/// get the map
const muse_smc::StateSpace<StateSpaceDescription>::ConstPtr ss = map_provider_->getStateSpace();
if (!ss->isType<MeshMap>())
return;
const mesh_map_tree_t* map = ss->as<MeshMap>().data();
uint64_t nsecs = static_cast<uint64_t>(sample_set->getStamp().nanoseconds());
const ros::Time stamp = ros::Time().fromNSec(nsecs);
publishSet(sample_set, map, stamp);
if (publish_contacts) {
visualization_msgs::Marker msg;
msg.lifetime = ros::Duration(0.2);
msg.color.a = 0.8;
msg.color.r = contact_marker_r_;
msg.color.g = contact_marker_g_;
msg.color.b = contact_marker_b_;
msg.scale.x = contact_marker_scale_x_;
msg.scale.y = contact_marker_scale_y_;
msg.scale.z = contact_marker_scale_z_;
msg.ns = "contact";
msg.type = visualization_msgs::Marker::ARROW;
msg.action = visualization_msgs::Marker::MODIFY;
msg.points.resize(2);
/// density estimation
ContactPointHistogram::ConstPtr histogram = std::dynamic_pointer_cast<ContactPointHistogram const>(sample_set->getDensity());
if(histogram && !labeled_contact_points_.empty()){
std::vector<std::pair<int,double>> labels;
histogram->getTopLabels(labels);
publishDiscretePoints(labels, stamp, msg);
} else {
publishContacts(sample_set, map, stamp, msg);
}
}
}
void StatePublisher::publishContacts(const typename sample_set_t::ConstPtr & sample_set,
const mesh_map_tree_t* map,
const ros::Time& stamp,
visualization_msgs::Marker& msg)
{
visualization_msgs::MarkerArray markers;
msg.header.stamp = stamp;
msg.id = 0;
SampleDensity::ConstPtr density = std::dynamic_pointer_cast<SampleDensity const>(sample_set->getDensity());
if (!density) {
std::cerr << "[StatePublisher]: Incomaptible sample density estimation!" << "\n";
return;
}
/// publish all detected contacts
std::vector<StateSpaceDescription::sample_t, StateSpaceDescription::sample_t::allocator_t> states;
density->contacts(states);
// std::cout << "[StatePublisher]: number of contacts: " << states.size() << std::endl;
cslibs_kdl_msgs::ContactMessageArray contact_msg;
bool diff_colors = states.size() > 1;
for (const StateSpaceDescription::sample_t& p : states) {
const mesh_map_tree_node_t* p_map = map->getNode(p.state.map_id);
if (p_map && std::fabs(p.state.force) > 1e-3){
cslibs_kdl_msgs::ContactMessage contact;
contact.header.frame_id = p_map->frameId();
contact.header.stamp = stamp;
cslibs_math_3d::Vector3d point = p.state.getPosition(p_map->map);
cslibs_math_3d::Vector3d direction = p.state.getDirection(p_map->map);
contact.location = cslibs_math_ros::geometry_msgs::conversion_3d::toVector3(point);
contact.direction = cslibs_math_ros::geometry_msgs::conversion_3d::toVector3(direction);
contact.force = static_cast<float>(p.state.force);
msg.header.frame_id = p_map->map.frame_id_;
++msg.id;
double fac = 1.0;
if(diff_colors){
fac = p.state.last_update;
msg.color.r *= fac;
msg.color.g *= fac;
msg.color.b *= fac;
}
msg.points[0] = cslibs_math_ros::geometry_msgs::conversion_3d::toPoint(point - direction * 0.2 );
msg.points[1] = cslibs_math_ros::geometry_msgs::conversion_3d::toPoint(point);
markers.markers.push_back(msg);
contact_msg.contacts.push_back(contact);
}
}
pub_contacts_.publish(contact_msg);
pub_contacts_vis_.publish(markers);
}
void StatePublisher::publishSet(const typename sample_set_t::ConstPtr &sample_set,
const mesh_map_tree_t* map,
const ros::Time& stamp)
{
std::shared_ptr<cslibs_math_3d::PointcloudRGB3d> part_cloud(new cslibs_math_3d::PointcloudRGB3d);
/// publish all particles
for (const StateSpaceDescription::sample_t& p : sample_set->getSamples()) {
const mesh_map_tree_node_t* p_map = map->getNode(p.state.map_id);
if (p_map) {
cslibs_math_3d::Transform3d T = map->getTranformToBase(p_map->map.frame_id_);
cslibs_math_3d::Point3d pos = p.state.getPosition(p_map->map);
pos = T * pos;
cslibs_math::color::Color<double> color(cslibs_math::color::interpolateColor<double>(p.state.last_update,0,1.0));
cslibs_math_3d::PointRGB3d point(pos, 0.9f, color);
part_cloud->insert(point);
}
}
sensor_msgs::PointCloud2 cloud;
cslibs_math_ros::sensor_msgs::conversion_3d::from<double>(part_cloud, cloud);
cloud.header.frame_id = map->front()->frameId();
cloud.header.stamp = stamp;
pub_particles_.publish(cloud);
}
void StatePublisher::publishDiscretePoints(const std::vector<std::pair<int, double>>& labels,
const ros::Time& stamp,
visualization_msgs::Marker& msg)
{
cslibs_kdl_msgs::ContactMessageArray contact_msg;
visualization_msgs::MarkerArray markers;
msg.header.stamp = stamp;
for(const std::pair<int, double>& p : labels){
if(p.first <= 0){
std::cerr << "[StatePublisher]: Got label "<< p.first << " clusering failed?? "<< "\n";
continue; // no contact detected?
}
try {
cslibs_kdl_msgs::ContactMessage contact;
const cslibs_kdl::KDLTransformation& t = labeled_contact_points_.at(p.first);
contact.header.frame_id = t.parent;
msg.header.frame_id = t.parent;
contact.header.stamp = stamp;
contact.force = p.second;
contact.location.x = t.frame.p.x();
contact.location.y = t.frame.p.y();
contact.location.z = t.frame.p.z();
KDL::Vector dir = t.frame.M * KDL::Vector(-1,0,0);
contact.direction.x = dir.x();
contact.direction.y = dir.y();
contact.direction.z = dir.z();
geometry_msgs::Point p0;
p0.x = t.frame.p.x();
p0.y = t.frame.p.y();
p0.z = t.frame.p.z();
geometry_msgs::Point p1;
p1.x = t.frame.p.x() - 0.2 * dir.x();
p1.y = t.frame.p.y() - 0.2 * dir.y();
p1.z = t.frame.p.z() - 0.2 * dir.z();
msg.points[0] = p1;
msg.points[1] = p0;
markers.markers.push_back(msg);
contact_msg.contacts.push_back(contact);
} catch (const std::exception &e) {
std::cerr << "[StatePublisher] : label " << p.first << " not found!" << std::endl;
throw e;
}
}
pub_contacts_.publish(contact_msg);
pub_contacts_vis_.publish(markers);
}
}
| 41.429719 | 133 | 0.638329 | [
"vector"
] |
18e0de83d455973d6d5644e086881051bf6fa74e | 15,088 | hpp | C++ | include/polyvec/curve-tracer/curve_objectives.hpp | ShnitzelKiller/polyfit | 51ddc6365a794db1678459140658211cb78f65b1 | [
"MIT"
] | 27 | 2020-08-17T17:25:59.000Z | 2022-03-01T05:49:12.000Z | include/polyvec/curve-tracer/curve_objectives.hpp | ShnitzelKiller/polyfit | 51ddc6365a794db1678459140658211cb78f65b1 | [
"MIT"
] | 4 | 2020-08-26T13:54:59.000Z | 2020-09-21T07:19:22.000Z | include/polyvec/curve-tracer/curve_objectives.hpp | ShnitzelKiller/polyfit | 51ddc6365a794db1678459140658211cb78f65b1 | [
"MIT"
] | 5 | 2020-08-26T23:26:48.000Z | 2021-01-04T09:06:07.000Z | #ifndef DEADLINE_CODE_GLOBFIT_OBJECTIVE_IS_INCLUDED
#define DEADLINE_CODE_GLOBFIT_OBJECTIVE_IS_INCLUDED
// polyvec
#include <polyvec/curve-tracer/curve_parametrizations.hpp>
#include <polyvec/curve-tracer/curve_bezier.hpp>
#include <polyvec/curve-tracer/curve_objective.hpp>
namespace polyvec {
// =============================================================
// Fit Points
// =============================================================
// class GlobFitObjective_FitPointsProject: public GlobFitObjective {
// public:
// using PointWeightFeeder = std::function<void ( int, Eigen::Vector2d&, double& ) >;
//
// void set_points_to_fit ( PointWeightFeeder, const int n_points );
// void get_points_to_fit ( PointWeightFeeder& feeder, int& n_points ) const;
//
// int n_equations();
// GlobFitObjectiveType get_type();
// void compute_objective_and_jacobian ( Eigen::VectorXd& obj, Eigen::MatrixXd& dobj_dcurveparams ) const;
//
// GlobFitObjective_FitPointsProject() = default;
// private:
// PointWeightFeeder _point_feeder = PointWeightFeeder ( nullptr );
// int _n_points_to_fit = 0;
//
// bool _is_all_data_provided();
// };
//
//// =============================================================
//// FIT TANGENTS
//// =============================================================
//
// class GlobFitObjective_FitTangentsProject: public GlobFitObjective {
// public:
// using PointTangentWeightFeeder = std::function<void ( int, Eigen::Vector2d&, Eigen::Vector2d&, double& ) >;
//
// void set_points_to_fit ( PointTangentWeightFeeder, const int n_points );
// void get_points_to_fit ( PointTangentWeightFeeder& feeder, int& n_points ) const;
//
// int n_equations();
// GlobFitObjectiveType get_type();
// void compute_objective_and_jacobian ( Eigen::VectorXd& obj, Eigen::MatrixXd& dobj_dcurveparams ) const;
//
// GlobFitObjective_FitTangentsProject() = default;
// private:
// PointTangentWeightFeeder _tangent_feeder = PointTangentWeightFeeder ( nullptr );
// int _n_points_to_fit = 0;
//
// bool _is_all_data_provided();
// };
// =============================================================
// FIX POSITION
// =============================================================
class GlobFitObjective_FitPointLength : public GlobFitObjective {
public:
void set_params(GlobFitCurveParametrization* curve, const double t_curve, const Eigen::Vector2d& pos);
int n_equations() const;
GlobFitObjectiveType get_type() const;
void compute_objective_and_jacobian ( Eigen::VectorXd& obj, Eigen::MatrixXd& dobj_dcurveparams ) const;
private:
double _t_curve = -1;
Eigen::Vector2d _fixed_pos = Eigen::Vector2d::Constant ( std::numeric_limits<double>::max() );
bool _is_all_data_provided() const;
};
// =============================================================
// FIX TANGENT
// =============================================================
#if 1
class GlobFitObjective_FitTangentLength : public GlobFitObjective {
public:
void set_params(GlobFitCurveParametrization* curve);
void add_tangent(const double t_curve, const Eigen::Vector2d& tangent);
// Default is using the cross product formulation (1 equation)
// Use this to change to the entry-wise difference formultation (2 equations)
bool get_using_cross_product_formulation() const;
void set_using_cross_product_formulation(const bool);
int n_equations() const;
GlobFitObjectiveType get_type() const;
void compute_objective_and_jacobian(Eigen::VectorXd& obj, Eigen::MatrixXd& dobj_dcurveparams) const;
private:
bool _use_cross_product_formulation = true;
std::vector<double> ts;
std::vector<Eigen::Vector2d> tangents;
bool _is_all_data_provided() const;
};
#else
class GlobFitObjective_FitTangentLength : public GlobFitObjective {
public:
void set_t_for_fixed_tangent ( const double t_curve );
void set_fixed_tangent ( const Eigen::Vector2d& );
// Default is using the cross product formulation (1 equation)
// Use this to change to the entry-wise difference formultation (2 equations)
bool get_using_cross_product_formulation();
void set_using_cross_product_formulation ( const bool );
int n_equations();
GlobFitObjectiveType get_type();
void compute_objective_and_jacobian ( Eigen::VectorXd& obj, Eigen::MatrixXd& dobj_dcurveparams ) const;
private:
bool _use_cross_product_formulation = true;
double _t_curve=-1;
Eigen::Vector2d _fixed_tangent = Eigen::Vector2d::Constant ( std::numeric_limits<double>::max() );
bool _is_all_data_provided();
};
#endif
// =============================================================
// SAME POSITION
// =============================================================
class GlobFitObjective_SamePosition : public GlobFitObjective {
public:
void set_params(GlobFitCurveParametrization* curve1, GlobFitCurveParametrization* curve2);
int n_equations() const;
GlobFitObjectiveType get_type() const;
void compute_objective_and_jacobian ( Eigen::VectorXd& obj, Eigen::MatrixXd& dobj_dcurveparams ) const;
private:
bool _is_all_data_provided() const;
};
// =============================================================
// SAME TANGENT
// =============================================================
class GlobFitObjective_SameTangent : public GlobFitObjective {
public:
enum FormulationType { FORMULATION_VECTOR_DIFF=0, FORMULATION_VECTOR_CROSS };
void set_params(GlobFitCurveParametrization* curve1, GlobFitCurveParametrization* curve2);
int n_equations() const;
GlobFitObjectiveType get_type() const;
void compute_objective_and_jacobian ( Eigen::VectorXd& obj, Eigen::MatrixXd& dobj_dcurveparams ) const;
FormulationType get_formulation() const;
void set_formulation(FormulationType);
private:
FormulationType _formulation_type = FORMULATION_VECTOR_CROSS;
bool _is_all_data_provided() const;
};
// =============================================================
// SAME CURVATURE
// =============================================================
class GlobFitObjective_SameCurvature : public GlobFitObjective {
public:
void set_params ( GlobFitCurveParametrization* curve1, const double t1, GlobFitCurveParametrization* curve2, const double t2 );
int n_equations() const;
GlobFitObjectiveType get_type() const;
void compute_objective_and_jacobian ( Eigen::VectorXd& obj, Eigen::MatrixXd& dobj_dcurveparams ) const;
private:
double t1 = -1, t2 = -1;
bool _is_all_data_provided() const;
};
// =============================================================
// BEZIER SMALL DEVIATION FROM INIT
// =============================================================
class GlobFitObjective_BezierFairness : public GlobFitObjective {
public:
// This will make an internal copy, must be called
void set_initial_bezier ( const Eigen::Matrix2Xd& control_points );
void set_target_length ( const double length );
void set_curve(GlobFitCurveParametrization*);
//
// Description of each term.
//
// weight_end_tangent_length_dev:
// prevents the distance from the first control point and the second (also third and fourth)
// one to deviate much from the initial guess.
// weight_end_tangent_angle_dev
// prevents the the angle of the line between the first and second (also fourth and third)
// control points to deviate from the initial value.
// weight_end_points_dev
// prevents the position of the first and last control points to deviate much from their initial values.
// weight_length
// Regularizer on the length
// weight_prevent_control_point_overlap
// thr_prevent_control_point_overlap
// prevents the first and second (also third and fourth) control points to overlap.
// weight_not_too_far_control_points
// If the line passing from the first-second and fourth-third control points intersect on the
// (second-third) control points side, encourages the control points not to get further than
// than that point. This objective can prevent inflection and loops.
void set_sub_weights (
const double weight_end_tangent_length_dev,
const double weight_end_tangent_angle_dev,
const double weight_end_points_dev,
const double weight_length,
const double weight_prevent_control_point_overlap,
const double thr_prevent_control_point_overlap,
const double weight_not_too_far_control_points );
int n_equations() const;
GlobFitObjectiveType get_type() const;
void compute_objective_and_jacobian ( Eigen::VectorXd& obj, Eigen::MatrixXd& dobj_dcurveparams ) const;
private:
bool _is_initial_bezier_set = false;
double _weight_end_tangent_length_dev = -1;
double _weight_end_tangent_angle_dev = -1;
double _weight_end_points_dev = -1;
double _length_target = -1.;
double _weight_length = -1;
double _weight_prevent_control_point_overlap = -1.;
double _thr_prevent_control_point_overlap = 1.;
double _weight_not_too_far_control_points_beg = -1;
double _weight_not_too_far_control_points_end = -1;
BezierCurve _initial_bezier;
bool _is_all_data_provided() const;
};
// =============================================================
// Point should lie on line
// =============================================================
class GlobFitObjective_PointLieOnLine : public GlobFitObjective {
public:
void set_params(GlobFitCurveParametrization* curve, const double t_curve, const Eigen::Vector2d& point, const Eigen::Vector2d& tangent);
int n_equations() const;
GlobFitObjectiveType get_type() const;
void compute_objective_and_jacobian ( Eigen::VectorXd& obj, Eigen::MatrixXd& dobj_dcurveparams ) const;
private:
double _t_curve = -1;
Eigen::Vector2d _line_point = Eigen::Vector2d::Constant ( std::numeric_limits<double>::max() );
Eigen::Vector2d _line_tangent = Eigen::Vector2d::Constant ( std::numeric_limits<double>::max() );
Eigen::Matrix2d _one_minus_ttT = Eigen::Matrix2d::Constant ( std::numeric_limits<double>::max() );
bool _is_all_data_provided() const;
};
// =============================================================
// Curvature Variation Minimization
// =============================================================
class GlobFitObjective_CurvatureVariation : public GlobFitObjective {
public:
void set_params(GlobFitCurveParametrization* curve);
GlobFitObjectiveType get_type() const { return GLOBFIT_OBJECTIVE_CURVATURE_VARIATION; }
int n_equations() const;
void compute_objective_and_jacobian(Eigen::VectorXd& obj, Eigen::MatrixXd& dobj_dcurveparams) const;
private:
int _M; //half number of samples
double _h; //sample spacing
//Calculates the curvature variation at a given position of the curve and fills the gradient
//with respect to the parametrization.
double calculate_curvature_variation(double t, Eigen::Block<Eigen::MatrixXd, 1> gradient) const;
};
// =============================================================
// Regularization
// =============================================================
class GlobFitObjective_Barrier : public GlobFitObjective
{
public:
void set_params(double soft_limit, double hard_limit);
//protected:
template <typename T>
double compute_barrier(double value, const T& value_jacobian, Eigen::MatrixXd& out_barrier_jacobian) const
{
out_barrier_jacobian.resize(1, value_jacobian.cols());
out_barrier_jacobian.setZero();
double residual = value - soft_limit;
if ((residual > 0) != ((hard_limit - soft_limit) > 0))
return 0; //not exceeding the soft limit
else
{
out_barrier_jacobian = 2 * residual * value_jacobian;
return residual * residual;
}
}
//private:
double soft_limit, hard_limit;
};
//Make sure that tangent lengths do not degenerate and no inflection is introduced
class GlobFitObjective_ParameterBound : public GlobFitObjective_Barrier {
public:
// Adds a penalty for parameters exceeding the soft_limit. The penalty is scaled such that it becomes 10,000 when
// the parameter approaches hard_limit
void set_params(GlobFitCurveParametrization* curve, int parameter, double soft_limit, double hard_limit);
GlobFitObjectiveType get_type() const { return GLOBFIT_OBJECTIVE_PARAMETER_BOUND; }
int n_equations() const { return 1; }
void compute_objective_and_jacobian(Eigen::VectorXd& obj, Eigen::MatrixXd& dobj_dcurveparams) const;
//private:
int parameter;
};
class GlobFitObjective_LineRegularization : public GlobFitObjective_Barrier {
public:
void set_params(GlobFitCurveParametrization* curve);
GlobFitObjectiveType get_type() const { return GLOBFIT_OBJECTIVE_LINE_REGULARIZATION; }
int n_equations() const { return 1; }
void compute_objective_and_jacobian(Eigen::VectorXd& obj, Eigen::MatrixXd& dobj_dcurveparams) const;
};
class GlobFitObjective_LineAngle : public GlobFitObjective {
public:
void set_params(GlobFitLineParametrization* line, double angle);
GlobFitObjectiveType get_type() const { return GLOBFIT_OBJECTIVE_LINE_ANGLE; }
int n_equations() const { return 1; }
void compute_objective_and_jacobian(Eigen::VectorXd& obj, Eigen::MatrixXd& dobj_dcurveparams) const;
double angle;
};
// =============================================================
// Regularize the scale and transition only Beziers
// =============================================================
/* class GlobFitObjective_ScaleAndTranslationOnlyRegularizer :
public GlobFitObjective {
public:
void set_sub_weights (
const double weight_for_scale,
const double weight_for_similarity,
const double weight_for_translation);
int n_equations();
GlobFitObjectiveType get_type();
void compute_objective_and_jacobian ( Eigen::VectorXd& obj, Eigen::MatrixXd& dobj_dcurveparams ) const;
private:
double _sqrt_weight_for_scale=-1;
double _sqrt_weight_for_similarity = -1;
double _sqrt_weight_for_translation =-1;
bool _is_all_data_provided();
};*/
} // end of polyvec
#endif // DEADLINE_CODE_GLOBFIT_OBJECTIVE_IS_INCLUDED
| 38.197468 | 138 | 0.633881 | [
"vector"
] |
18e45e287504dd00592181cbdf3263b1a9a32389 | 44,590 | cpp | C++ | unittests/remote.cpp | Toysoft/upscaledb | 4bdf5de12bc484a3ad2a9379d834149746d45b2f | [
"Apache-2.0"
] | 350 | 2015-11-05T00:49:19.000Z | 2022-03-23T16:27:36.000Z | unittests/remote.cpp | Toysoft/upscaledb | 4bdf5de12bc484a3ad2a9379d834149746d45b2f | [
"Apache-2.0"
] | 71 | 2015-11-05T19:26:57.000Z | 2021-08-20T14:52:21.000Z | unittests/remote.cpp | Toysoft/upscaledb | 4bdf5de12bc484a3ad2a9379d834149746d45b2f | [
"Apache-2.0"
] | 55 | 2015-11-04T15:09:16.000Z | 2021-12-23T20:45:24.000Z | /*
* Copyright (C) 2005-2017 Christoph Rupp (chris@crupp.de).
*
* 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.
*
* See the file COPYING for License information.
*/
#ifdef UPS_ENABLE_REMOTE
#include "3rdparty/catch/catch.hpp"
#include "ups/upscaledb_srv.h"
#include "ups/upscaledb_uqi.h"
#include "ups/upscaledb_int.h"
#include "1errorinducer/errorinducer.h"
#include "os.hpp"
using namespace upscaledb;
#define SERVER_URL "ups://localhost:8989/test.db"
struct RemoteFixture {
ups_srv_t *srv;
ups_env_t *senv;
RemoteFixture()
: srv(0) {
ups_srv_config_t cfg;
::memset(&cfg, 0, sizeof(cfg));
cfg.port = 8989;
REQUIRE(0 == ups_env_create(&senv, "test.db", UPS_ENABLE_TRANSACTIONS,
0644, 0));
ups_db_t *db;
REQUIRE(0 == ups_env_create_db(senv, &db, 14,
UPS_ENABLE_DUPLICATE_KEYS, 0));
ups_db_close(db, 0);
REQUIRE(0 == ups_env_create_db(senv, &db, 13,
UPS_ENABLE_DUPLICATE_KEYS, 0));
ups_db_close(db, 0);
REQUIRE(0 == ups_env_create_db(senv, &db, 33,
UPS_RECORD_NUMBER64 | UPS_ENABLE_DUPLICATE_KEYS, 0));
ups_db_close(db, 0);
REQUIRE(0 == ups_env_create_db(senv, &db, 34,
UPS_RECORD_NUMBER32, 0));
ups_db_close(db, 0);
REQUIRE(0 == ups_env_create_db(senv, &db, 55, 0, 0));
ups_db_close(db, 0);
REQUIRE(0 == ups_srv_init(&cfg, &srv));
REQUIRE(0 == ups_srv_add_env(srv, senv, "/test.db"));
}
~RemoteFixture() {
if (srv) {
ups_srv_close(srv);
srv = 0;
}
if (senv) {
REQUIRE(0 == ups_env_close(senv, UPS_AUTO_CLEANUP));
senv = 0;
}
}
void invalidUrlTest() {
ups_env_t *env;
REQUIRE(UPS_NETWORK_ERROR ==
ups_env_create(&env, "ups://localhost:77/test.db", 0, 0664, 0));
}
void invalidPathTest() {
ups_env_t *env;
REQUIRE(UPS_FILE_NOT_FOUND ==
ups_env_create(&env, "ups://localhost:8989/xxxtest.db", 0, 0, 0));
}
void createCloseTest() {
ups_env_t *env;
REQUIRE(0 == ups_env_create(&env, SERVER_URL, 0, 0664, 0));
REQUIRE(UPS_INV_PARAMETER == ups_env_close(0, 0));
REQUIRE(0 == ups_env_close(env, 0));
}
void createCloseOpenCloseTest() {
ups_env_t *env;
REQUIRE(0 == ups_env_create(&env, SERVER_URL, 0, 0664, 0));
REQUIRE(0 == ups_env_close(env, 0));
REQUIRE(0 == ups_env_open(&env, SERVER_URL, 0, 0));
REQUIRE(0 == ups_env_close(env, 0));
}
void getEnvParamsTest() {
ups_env_t *env;
ups_parameter_t params[] = {
{ UPS_PARAM_CACHESIZE, 0 },
{ UPS_PARAM_PAGESIZE, 0 },
{ UPS_PARAM_MAX_DATABASES, 0 },
{ UPS_PARAM_FLAGS, 0 },
{ UPS_PARAM_FILEMODE, 0 },
{ UPS_PARAM_FILENAME, 0 },
{ 0,0 }
};
REQUIRE(0 == ups_env_create(&env, SERVER_URL, 0, 0664, 0));
REQUIRE(0 == ups_env_get_parameters(env, params));
REQUIRE((unsigned)UPS_DEFAULT_CACHE_SIZE == params[0].value);
REQUIRE((uint64_t)(1024 * 16) == params[1].value);
REQUIRE((uint64_t)540 == params[2].value);
REQUIRE((uint64_t)UPS_ENABLE_TRANSACTIONS == params[3].value);
REQUIRE(0644ull == params[4].value);
REQUIRE(0 == ::strcmp("test.db", (char *)params[5].value));
REQUIRE(0 == ups_env_close(env, 0));
}
void getDatabaseNamesTest() {
ups_env_t *env;
uint16_t names[15];
uint32_t max_names = 15;
REQUIRE(0 == ups_env_create(&env, SERVER_URL, 0, 0664, 0));
REQUIRE(0 == ups_env_get_database_names(env, &names[0], &max_names));
REQUIRE(14 == names[0]);
REQUIRE(13 == names[1]);
REQUIRE(33 == names[2]);
REQUIRE(34 == names[3]);
REQUIRE(5u == max_names);
REQUIRE(0 == ups_env_close(env, 0));
}
void envFlushTest() {
ups_env_t *env;
REQUIRE(0 == ups_env_create(&env, SERVER_URL, 0, 0664, 0));
REQUIRE(0 == ups_env_flush(env, 0));
REQUIRE(0 == ups_env_close(env, 0));
}
void renameDbTest() {
ups_env_t *env;
uint16_t names[15];
uint32_t max_names = 15;
REQUIRE(0 == ups_env_create(&env, SERVER_URL, 0, 0664, 0));
REQUIRE(0 == ups_env_rename_db(env, 13, 15, 0));
REQUIRE(0 == ups_env_get_database_names(env, &names[0], &max_names));
REQUIRE(14 == names[0]);
REQUIRE(15 == names[1]);
REQUIRE(33 == names[2]);
REQUIRE(34 == names[3]);
REQUIRE(5u == max_names);
REQUIRE(UPS_DATABASE_NOT_FOUND == ups_env_rename_db(env, 13, 16, 0));
REQUIRE(0 == ups_env_rename_db(env, 15, 13, 0));
REQUIRE(0 == ups_env_get_database_names(env, &names[0], &max_names));
REQUIRE(14 == names[0]);
REQUIRE(13 == names[1]);
REQUIRE(33 == names[2]);
REQUIRE(34 == names[3]);
REQUIRE(5u == max_names);
REQUIRE(0 == ups_env_close(env, 0));
}
void createDbTest() {
ups_env_t *env;
ups_db_t *db;
REQUIRE(0 == ups_env_create(&env, SERVER_URL, 0, 0664, 0));
REQUIRE(0 == ups_env_create_db(env, &db, 22, 0, 0));
REQUIRE(0 == ups_db_close(db, 0));
REQUIRE(0 == ups_env_close(env, 0));
}
void createDbExtendedTest() {
ups_env_t *env;
ups_db_t *db;
ups_parameter_t params[] = {
{ UPS_PARAM_KEYSIZE, 5 },
{ 0,0 }
};
REQUIRE(0 == ups_env_create(&env, SERVER_URL, 0, 0664, 0));
REQUIRE(0 == ups_env_create_db(env, &db, 22, 0, ¶ms[0]));
params[0].value=0;
REQUIRE(0 == ups_db_get_parameters(db, ¶ms[0]));
REQUIRE(5ull == params[0].value);
REQUIRE(0 == ups_db_close(db, 0));
REQUIRE(0 == ups_env_close(env, 0));
}
void openDbTest() {
ups_env_t *env;
ups_db_t *db;
REQUIRE(0 == ups_env_create(&env, SERVER_URL, 0, 0664, 0));
REQUIRE(0 == ups_env_create_db(env, &db, 22, 0, 0));
REQUIRE(0 == ups_db_close(db, 0));
REQUIRE(0 == ups_env_open_db(env, &db, 22, 0, 0));
REQUIRE(0 == ups_db_close(db, 0));
REQUIRE(0 == ups_env_close(env, 0));
}
void eraseDbTest() {
ups_env_t *env;
uint16_t names[15];
uint32_t max_names = 15;
REQUIRE(0 == ups_env_create(&env, SERVER_URL, 0, 0664, 0));
REQUIRE(0 == ups_env_get_database_names(env, &names[0], &max_names));
REQUIRE(14 == names[0]);
REQUIRE(13 == names[1]);
REQUIRE(33 == names[2]);
REQUIRE(34 == names[3]);
REQUIRE(5u == max_names);
REQUIRE(0 == ups_env_erase_db(env, 14, 0));
REQUIRE(0 == ups_env_get_database_names(env, &names[0], &max_names));
REQUIRE(13 == names[0]);
REQUIRE(33 == names[1]);
REQUIRE(34 == names[2]);
REQUIRE(4u == max_names);
REQUIRE(UPS_DATABASE_NOT_FOUND == ups_env_erase_db(env, 14, 0));
REQUIRE(0 == ups_env_close(env, 0));
}
void getDbParamsTest() {
ups_db_t *db;
ups_env_t *env;
ups_parameter_t params[] = {
{ UPS_PARAM_FLAGS, 0 },
{ 0,0 }
};
REQUIRE(0 == ups_env_create(&env, SERVER_URL, 0, 0664, 0));
REQUIRE(0 == ups_env_create_db(env, &db, 22, 0, 0));
REQUIRE(0 == ups_db_get_parameters(db, params));
REQUIRE((uint64_t)UPS_ENABLE_TRANSACTIONS == params[0].value);
REQUIRE(0 == ups_db_close(db, 0));
REQUIRE(0 == ups_env_close(env, 0));
}
void txnBeginCommitTest() {
ups_db_t *db;
ups_env_t *env;
ups_txn_t *txn;
REQUIRE(0 ==
ups_env_create(&env, SERVER_URL, UPS_ENABLE_TRANSACTIONS, 0664, 0));
REQUIRE(0 == ups_env_create_db(env, &db, 22, 0, 0));
REQUIRE(0 == ups_txn_begin(&txn, ups_db_get_env(db), "name", 0, 0));
REQUIRE(0 == ::strcmp("name", ups_txn_get_name(txn)));
REQUIRE(0 == ups_txn_commit(txn, 0));
REQUIRE(0 == ups_env_close(env, UPS_AUTO_CLEANUP));
}
void txnBeginAbortTest() {
ups_db_t *db;
ups_env_t *env;
ups_txn_t *txn;
REQUIRE(0 ==
ups_env_create(&env, SERVER_URL, UPS_ENABLE_TRANSACTIONS, 0664, 0));
REQUIRE(0 == ups_env_create_db(env, &db, 22, 0, 0));
REQUIRE(0 == ups_txn_begin(&txn, ups_db_get_env(db), 0, 0, 0));
REQUIRE(0 == ups_txn_abort(txn, 0));
REQUIRE(0 == ups_env_close(env, UPS_AUTO_CLEANUP));
}
void checkIntegrityTest() {
ups_db_t *db;
ups_env_t *env;
REQUIRE(0 == ups_env_create(&env, SERVER_URL, 0, 0664, 0));
REQUIRE(0 == ups_env_create_db(env, &db, 22, 0, 0));
REQUIRE(0 == ups_db_check_integrity(db, 0));
REQUIRE(0 == ups_env_close(env, UPS_AUTO_CLEANUP));
}
void getKeyCountTest() {
uint64_t keycount;
ups_db_t *db;
ups_env_t *env;
REQUIRE(0 == ups_env_create(&env, SERVER_URL, 0, 0664, 0));
REQUIRE(0 == ups_env_create_db(env, &db, 22, 0, 0));
REQUIRE(0 == ups_db_count(db, 0, 0, &keycount));
REQUIRE(0ull == keycount);
REQUIRE(0 == ups_env_close(env, UPS_AUTO_CLEANUP));
}
void insertFindTest() {
ups_db_t *db;
ups_env_t *env;
uint64_t keycount;
ups_key_t key = ups_make_key((void *)"hello world", 12);
ups_record_t rec = ups_make_record((void *)"hello chris", 12);
ups_record_t rec2 = {0};
REQUIRE(0 == ups_env_create(&env, SERVER_URL, 0, 0664, 0));
REQUIRE(0 == ups_env_create_db(env, &db, 22, 0, 0));
REQUIRE(0 == ups_db_insert(db, 0, &key, &rec, 0));
REQUIRE(0 == ups_db_find(db, 0, &key, &rec2, 0));
REQUIRE(rec.size == rec2.size);
REQUIRE(0 == ::strcmp((char *)rec.data, (char *)rec2.data));
REQUIRE(0 == ups_db_count(db, 0, 0, &keycount));
REQUIRE(1ull == keycount);
REQUIRE(UPS_DUPLICATE_KEY == ups_db_insert(db, 0, &key, &rec, 0));
REQUIRE(0 == ups_db_insert(db, 0, &key, &rec, UPS_OVERWRITE));
memset(&rec2, 0, sizeof(rec2));
REQUIRE(0 == ups_db_find(db, 0, &key, &rec2, 0));
REQUIRE(rec.size == rec2.size);
REQUIRE(0 == ::strcmp((char *)rec.data, (char *)rec2.data));
REQUIRE(0 == ups_env_close(env, UPS_AUTO_CLEANUP));
}
void insertFindBigTest() {
#define BUFSIZE (1024 * 16 + 10)
ups_db_t *db;
ups_env_t *env;
uint64_t keycount;
REQUIRE(0 == ups_env_create(&env, SERVER_URL, 0, 0664, 0));
REQUIRE(0 == ups_env_create_db(env, &db, 22, 0, 0));
std::vector<uint8_t> buffer(BUFSIZE);
ups_key_t key = ups_make_key((void *)"123", 4);
ups_record_t rec = ups_make_record(buffer.data(), (uint32_t)buffer.size());
ups_record_t rec2 = {0};
REQUIRE(0 == ups_db_insert(db, 0, &key, &rec, 0));
REQUIRE(0 == ups_db_count(db, 0, 0, &keycount));
REQUIRE(1ull == keycount);
REQUIRE(0 == ups_db_find(db, 0, &key, &rec2, 0));
REQUIRE(rec.size == rec2.size);
REQUIRE(0 == ::strcmp((char *)rec.data, (char *)rec2.data));
REQUIRE(UPS_DUPLICATE_KEY == ups_db_insert(db, 0, &key, &rec, 0));
REQUIRE(0 == ups_db_insert(db, 0, &key, &rec, UPS_OVERWRITE));
memset(&rec2, 0, sizeof(rec2));
REQUIRE(0 == ups_db_find(db, 0, &key, &rec2, 0));
REQUIRE(rec.size == rec2.size);
REQUIRE(0 == ::strcmp((char *)rec.data, (char *)rec2.data));
REQUIRE(0 == ups_env_close(env, UPS_AUTO_CLEANUP));
}
template<typename RecnoType>
void insertRecnoTest(int dbid) {
ups_db_t *db;
ups_env_t *env;
ups_key_t key = {0};
ups_record_t rec = ups_make_record((void *)"hello chris", 12);
REQUIRE(0 == ups_env_create(&env, SERVER_URL, 0, 0664, 0));
REQUIRE(0 == ups_env_open_db(env, &db, dbid, 0, 0));
REQUIRE(0 == ups_db_insert(db, 0, &key, &rec, 0));
REQUIRE(sizeof(RecnoType) == key.size);
REQUIRE(1ull == *(RecnoType *)key.data);
memset(&key, 0, sizeof(key));
REQUIRE(0 == ups_db_insert(db, 0, &key, &rec, 0));
REQUIRE(sizeof(RecnoType) == key.size);
REQUIRE(2ull == *(RecnoType *)key.data);
REQUIRE(0 == ups_env_close(env, UPS_AUTO_CLEANUP));
}
void insertFindEraseTest() {
ups_db_t *db;
ups_env_t *env;
uint64_t keycount;
ups_key_t key = ups_make_key((void *)"hello world", 12);
ups_record_t rec = ups_make_record((void *)"hello chris", 12);
ups_record_t rec2 = {0};
REQUIRE(0 == ups_env_create(&env, SERVER_URL, 0, 0664, 0));
(void)ups_env_erase_db(env, 33, 0);
REQUIRE(0 == ups_env_create_db(env, &db, 33, 0, 0));
REQUIRE(0 == ups_db_insert(db, 0, &key, &rec, 0));
REQUIRE(0 == ups_db_count(db, 0, 0, &keycount));
REQUIRE(1ull == keycount);
REQUIRE(0 == ups_db_find(db, 0, &key, &rec2, 0));
REQUIRE(rec.size == rec2.size);
REQUIRE(0 == ::strcmp((char *)rec.data, (char *)rec2.data));
REQUIRE(UPS_DUPLICATE_KEY == ups_db_insert(db, 0, &key, &rec, 0));
REQUIRE(0 == ups_db_insert(db, 0, &key, &rec, UPS_OVERWRITE));
memset(&rec2, 0, sizeof(rec2));
REQUIRE(0 == ups_db_find(db, 0, &key, &rec2, 0));
REQUIRE(rec.size == rec2.size);
REQUIRE(0 == ::strcmp((char *)rec.data, (char *)rec2.data));
REQUIRE(0 == ups_db_erase(db, 0, &key, 0));
REQUIRE(UPS_KEY_NOT_FOUND == ups_db_find(db, 0, &key, &rec, 0));
REQUIRE(0 == ups_db_count(db, 0, 0, &keycount));
REQUIRE(0ull == keycount);
REQUIRE(0 == ups_env_close(env, UPS_AUTO_CLEANUP));
}
void insertFindEraseUserallocTest() {
ups_db_t *db;
ups_env_t *env;
uint64_t keycount;
std::vector<uint8_t> buf(1024);
ups_key_t key = ups_make_key((void *)"hello world", 12);
ups_record_t rec = ups_make_record((void *)"hello chris", 12);
ups_record_t rec2 = ups_make_record(buf.data(), (uint32_t)buf.size());
rec2.flags = UPS_RECORD_USER_ALLOC;
REQUIRE(0 == ups_env_create(&env, SERVER_URL, 0, 0664, 0));
ups_env_erase_db(env, 33, 0);
REQUIRE(0 == ups_env_create_db(env, &db, 33, 0, 0));
REQUIRE(0 == ups_db_insert(db, 0, &key, &rec, 0));
REQUIRE(0 == ups_db_count(db, 0, 0, &keycount));
REQUIRE(1ull == keycount);
REQUIRE(0 == ups_db_find(db, 0, &key, &rec2, 0));
REQUIRE(rec.size == rec2.size);
REQUIRE(0 == ::strcmp((char *)rec.data, (char *)rec2.data));
REQUIRE(UPS_DUPLICATE_KEY == ups_db_insert(db, 0, &key, &rec, 0));
REQUIRE(0 == ups_db_insert(db, 0, &key, &rec, UPS_OVERWRITE));
memset(&rec2, 0, sizeof(rec2));
REQUIRE(0 == ups_db_find(db, 0, &key, &rec2, 0));
REQUIRE(rec.size == rec2.size);
REQUIRE(0 == ::strcmp((char *)rec.data, (char *)rec2.data));
REQUIRE(0 == ups_db_erase(db, 0, &key, 0));
REQUIRE(UPS_KEY_NOT_FOUND == ups_db_find(db, 0, &key, &rec, 0));
REQUIRE(0 == ups_db_count(db, 0, 0, &keycount));
REQUIRE(0ull == keycount);
REQUIRE(0 == ups_env_close(env, UPS_AUTO_CLEANUP));
}
template<typename RecnoType>
void insertFindEraseRecnoTest(int dbid) {
ups_db_t *db;
ups_env_t *env;
uint64_t keycount;
RecnoType recno;
ups_key_t key = {0};
ups_record_t rec = ups_make_record((void *)"hello chris", 12);
REQUIRE(0 == ups_env_create(&env, SERVER_URL, 0, 0664, 0));
REQUIRE(0 == ups_env_open_db(env, &db, dbid, 0, 0));
REQUIRE(0 == ups_db_insert(db, 0, &key, &rec, 0));
REQUIRE(0 == ups_db_count(db, 0, 0, &keycount));
REQUIRE(1ull == keycount);
REQUIRE(sizeof(RecnoType) == key.size);
recno = *(RecnoType *)key.data;
REQUIRE(1ull == recno);
ups_record_t rec2 = {0};
REQUIRE(0 == ups_db_find(db, 0, &key, &rec2, 0));
REQUIRE(rec.size == rec2.size);
REQUIRE(0 == ::strcmp((char *)rec.data, (char *)rec2.data));
memset(&key, 0, sizeof(key));
REQUIRE(0 == ups_db_insert(db, 0, &key, &rec, 0));
REQUIRE(0 == ups_db_count(db, 0, 0, &keycount));
REQUIRE(2ull == keycount);
recno = *(RecnoType *)key.data;
REQUIRE(2ull == recno);
memset(&key, 0, sizeof(key));
REQUIRE(0 == ups_db_insert(db, 0, &key, &rec, 0));
REQUIRE(0 == ups_db_count(db, 0, 0, &keycount));
REQUIRE(3ull == keycount);
recno = *(RecnoType *)key.data;
REQUIRE(3ull == recno);
REQUIRE(0 == ups_db_erase(db, 0, &key, 0));
REQUIRE(UPS_KEY_NOT_FOUND == ups_db_find(db, 0, &key, &rec, 0));
REQUIRE(UPS_KEY_NOT_FOUND == ups_db_erase(db, 0, &key, 0));
REQUIRE(0 == ups_db_count(db, 0, 0, &keycount));
REQUIRE(2ull == keycount);
REQUIRE(0 == ups_db_close(db, 0));
REQUIRE(0 == ups_env_close(env, 0));
}
void cursorInsertFindTest() {
ups_db_t *db;
ups_env_t *env;
ups_cursor_t *cursor;
uint64_t keycount;
ups_key_t key = ups_make_key((void *)"hello world", 12);
ups_record_t rec = ups_make_record((void *)"hello chris", 12);
ups_record_t rec2 = {0};
REQUIRE(0 == ups_env_create(&env, SERVER_URL, 0, 0664, 0));
ups_env_erase_db(env, 33, 0);
REQUIRE(0 == ups_env_create_db(env, &db, 33, 0, 0));
REQUIRE(0 == ups_cursor_create(&cursor, db, 0, 0));
REQUIRE(0 == ups_cursor_insert(cursor, &key, &rec, 0));
REQUIRE(0 == ups_db_count(db, 0, 0, &keycount));
REQUIRE(1ull == keycount);
REQUIRE(0 == ups_cursor_find(cursor, &key, &rec2, 0));
REQUIRE(rec.size == rec2.size);
REQUIRE(0 == ::strcmp((char *)rec.data, (char *)rec2.data));
uint32_t size;
REQUIRE(0 == ups_cursor_get_record_size(cursor, &size));
REQUIRE(size == 12);
REQUIRE(UPS_DUPLICATE_KEY ==
ups_cursor_insert(cursor, &key, &rec, 0));
REQUIRE(0 == ups_cursor_insert(cursor, &key, &rec, UPS_OVERWRITE));
memset(&rec2, 0, sizeof(rec2));
REQUIRE(0 == ups_cursor_find(cursor, &key, &rec2, 0));
REQUIRE(rec.size == rec2.size);
REQUIRE(0 == strcmp((char *)rec.data, (char *)rec2.data));
REQUIRE(0 == ups_env_close(env, UPS_AUTO_CLEANUP));
}
template<typename RecnoType>
void cursorInsertRecnoTest(int dbid) {
ups_db_t *db;
ups_env_t *env;
ups_cursor_t *cursor;
ups_key_t key = {0};
ups_record_t rec1 = ups_make_record((void *)"hello1chris", 12);
ups_record_t rec2 = ups_make_record((void *)"hello2chris", 12);
REQUIRE(0 == ups_env_create(&env, SERVER_URL, 0, 0664, 0));
REQUIRE(0 == ups_env_open_db(env, &db, dbid, 0, 0));
REQUIRE(0 == ups_cursor_create(&cursor, db, 0, 0));
REQUIRE(0 == ups_cursor_insert(cursor, &key, &rec1, 0));
REQUIRE(sizeof(RecnoType) == key.size);
REQUIRE(1ull == *(RecnoType *)key.data);
::memset(&key, 0, sizeof(key));
REQUIRE(0 == ups_cursor_insert(cursor, &key, &rec2, 0));
REQUIRE(sizeof(RecnoType) == key.size);
REQUIRE(2ull == *(RecnoType *)key.data);
REQUIRE(0 == ups_env_close(env, UPS_AUTO_CLEANUP));
}
void cursorInsertFindEraseTest() {
ups_db_t *db;
ups_env_t *env;
ups_cursor_t *cursor;
uint64_t keycount;
ups_key_t key = ups_make_key((void *)"hello world", 12);
ups_record_t rec = ups_make_record((void *)"hello chris", 12);
ups_record_t rec2 = {0};
REQUIRE(0 == ups_env_create(&env, SERVER_URL, 0, 0664, 0));
ups_env_erase_db(env, 33, 0);
REQUIRE(0 == ups_env_create_db(env, &db, 33, 0, 0));
REQUIRE(0 == ups_cursor_create(&cursor, db, 0, 0));
REQUIRE(0 == ups_cursor_insert(cursor, &key, &rec, 0));
REQUIRE(0 == ups_db_count(db, 0, 0, &keycount));
REQUIRE(1ull == keycount);
REQUIRE(0 == ups_cursor_find(cursor, &key, &rec2, 0));
REQUIRE(rec.size == rec2.size);
REQUIRE(0 == ::strcmp((char *)rec.data, (char *)rec2.data));
REQUIRE(UPS_DUPLICATE_KEY == ups_cursor_insert(cursor, &key, &rec, 0));
REQUIRE(0 == ups_cursor_insert(cursor, &key, &rec, UPS_OVERWRITE));
::memset(&rec2, 0, sizeof(rec2));
REQUIRE(0 == ups_cursor_find(cursor, &key, &rec2, 0));
REQUIRE(rec.size == rec2.size);
REQUIRE(0 == ::strcmp((char *)rec.data, (char *)rec2.data));
REQUIRE(0 == ups_cursor_find(cursor, &key, 0, 0));
REQUIRE(0 == ups_cursor_erase(cursor, 0));
REQUIRE(UPS_KEY_NOT_FOUND == ups_cursor_find(cursor, &key, 0, 0));
REQUIRE(0 == ups_db_count(db, 0, 0, &keycount));
REQUIRE(0ull == keycount);
REQUIRE(0 == ups_env_close(env, UPS_AUTO_CLEANUP));
}
template<typename RecnoType>
void cursorInsertFindEraseRecnoTest(int dbid) {
ups_db_t *db;
ups_env_t *env;
ups_cursor_t *cursor;
ups_key_t key = {0};
ups_record_t rec2 = {0};
uint64_t keycount;
RecnoType recno;
ups_record_t rec = ups_make_record((void *)"hello chris", 12);
REQUIRE(0 == ups_env_create(&env, SERVER_URL, 0, 0664, 0));
REQUIRE(0 == ups_env_open_db(env, &db, dbid, 0, 0));
REQUIRE(0 == ups_cursor_create(&cursor, db, 0, 0));
REQUIRE(0 == ups_cursor_insert(cursor, &key, &rec, 0));
REQUIRE(0 == ups_db_count(db, 0, 0, &keycount));
REQUIRE(1ull == keycount);
REQUIRE(sizeof(RecnoType) == key.size);
recno = *(RecnoType *)key.data;
REQUIRE(1ull == recno);
REQUIRE(0 == ups_cursor_find(cursor, &key, &rec2, 0));
REQUIRE(rec.size == rec2.size);
REQUIRE(0 == ::strcmp((char *)rec.data, (char *)rec2.data));
::memset(&key, 0, sizeof(key));
REQUIRE(0 == ups_cursor_insert(cursor, &key, &rec, 0));
REQUIRE(0 == ups_db_count(db, 0, 0, &keycount));
REQUIRE(2ull == keycount);
recno = *(RecnoType *)key.data;
REQUIRE(2ull == recno);
::memset(&key, 0, sizeof(key));
REQUIRE(0 == ups_cursor_insert(cursor, &key, &rec, 0));
REQUIRE(0 == ups_db_count(db, 0, 0, &keycount));
REQUIRE(3ull == keycount);
recno = *(RecnoType *)key.data;
REQUIRE(3ull == recno);
REQUIRE(0 == ups_cursor_erase(cursor, 0));
REQUIRE(UPS_KEY_NOT_FOUND == ups_cursor_find(cursor, &key, 0, 0));
REQUIRE(0 == ups_db_count(db, 0, 0, &keycount));
REQUIRE(2ull == keycount);
REQUIRE(0 == ups_env_close(env, UPS_AUTO_CLEANUP));
}
void approxMatchTest() {
ups_db_t *db;
ups_env_t *env;
ups_key_t key = ups_make_key((void *)"k1", 3);
ups_record_t rec = ups_make_record((void *)"r1", 3);
REQUIRE(0 == ups_env_create(&env, SERVER_URL, 0, 0664, 0));
REQUIRE(0 == ups_env_open_db(env, &db, 55, 0, 0));
REQUIRE(0 == ups_db_insert(db, 0, &key, &rec, 0));
key.data = (void *)"k2";
rec.data = (void *)"r2";
REQUIRE(0 == ups_db_insert(db, 0, &key, &rec, 0));
key.data = (void *)"k3";
rec.data = (void *)"r3";
REQUIRE(0 == ups_db_insert(db, 0, &key, &rec, 0));
key.data = (void *)"k2";
REQUIRE(0 == ups_db_find(db, 0, &key, &rec, UPS_FIND_LT_MATCH));
REQUIRE(0 == ::strcmp((char *)key.data, "k1"));
REQUIRE(0 == ::strcmp((char *)rec.data, "r1"));
key.data = (void *)"k2";
REQUIRE(0 == ups_db_find(db, 0, &key, &rec, UPS_FIND_LEQ_MATCH));
REQUIRE(0 == ::strcmp((char *)key.data, "k2"));
REQUIRE(0 == ::strcmp((char *)rec.data, "r2"));
key.data = (void *)"k2";
REQUIRE(0 == ups_db_find(db, 0, &key, &rec, UPS_FIND_GT_MATCH));
REQUIRE(0 == ::strcmp((char *)key.data, "k3"));
REQUIRE(0 == ::strcmp((char *)rec.data, "r3"));
key.data = (void *)"k2";
REQUIRE(0 == ups_db_find(db, 0, &key, &rec, UPS_FIND_GEQ_MATCH));
REQUIRE(0 == ::strcmp((char *)key.data, "k2"));
REQUIRE(0 == ::strcmp((char *)rec.data, "r2"));
REQUIRE(0 == ups_env_close(env, UPS_AUTO_CLEANUP));
}
void cursorApproxMatchTest() {
ups_db_t *db;
ups_env_t *env;
ups_cursor_t *cursor;
ups_key_t key = ups_make_key((void *)"k1", 3);
ups_record_t rec = ups_make_record((void *)"r1", 3);
REQUIRE(0 == ups_env_create(&env, SERVER_URL, 0, 0664, 0));
REQUIRE(0 == ups_env_open_db(env, &db, 55, 0, 0));
REQUIRE(0 == ups_cursor_create(&cursor, db, 0, 0));
REQUIRE(0 == ups_db_insert(db, 0, &key, &rec, UPS_OVERWRITE));
key.data = (void *)"k2";
rec.data = (void *)"r2";
REQUIRE(0 == ups_db_insert(db, 0, &key, &rec, UPS_OVERWRITE));
key.data = (void *)"k3";
rec.data = (void *)"r3";
REQUIRE(0 == ups_db_insert(db, 0, &key, &rec, UPS_OVERWRITE));
key.data = (void *)"k2";
REQUIRE(0 == ups_cursor_find(cursor, &key, &rec, UPS_FIND_LT_MATCH));
REQUIRE(0 == ::strcmp((char *)key.data, "k1"));
REQUIRE(0 == ::strcmp((char *)rec.data, "r1"));
key.data = (void *)"k2";
REQUIRE(0 == ups_cursor_find(cursor, &key, &rec, UPS_FIND_LEQ_MATCH));
REQUIRE(0 == ::strcmp((char *)key.data, "k2"));
REQUIRE(0 == ::strcmp((char *)rec.data, "r2"));
key.data = (void *)"k2";
REQUIRE(0 == ups_cursor_find(cursor, &key, &rec, UPS_FIND_GT_MATCH));
REQUIRE(0 == ::strcmp((char *)key.data, "k3"));
REQUIRE(0 == ::strcmp((char *)rec.data, "r3"));
key.data = (void *)"k2";
REQUIRE(0 == ups_cursor_find(cursor, &key, &rec, UPS_FIND_GEQ_MATCH));
REQUIRE(0 == ::strcmp((char *)key.data, "k2"));
REQUIRE(0 == ::strcmp((char *)rec.data, "r2"));
REQUIRE(0 == ups_env_close(env, UPS_AUTO_CLEANUP));
}
void cursorInsertFindEraseUserallocTest() {
ups_db_t *db;
ups_env_t *env;
ups_key_t key = {};
ups_cursor_t *cursor;
ups_record_t rec = {};
ups_record_t rec2 = {};
uint64_t keycount;
char buf[1024];
key.data = (void *)"hello world";
key.size = 12;
rec.data = (void *)"hello chris";
rec.size = 12;
rec2.data = (void *)buf;
rec2.size = sizeof(buf);
rec2.flags = UPS_RECORD_USER_ALLOC;
REQUIRE(0 == ups_env_create(&env, SERVER_URL, 0, 0664, 0));
ups_env_erase_db(env, 33, 0);
REQUIRE(0 == ups_env_create_db(env, &db, 33, 0, 0));
REQUIRE(0 == ups_cursor_create(&cursor, db, 0, 0));
REQUIRE(0 == ups_cursor_insert(cursor, &key, &rec, 0));
REQUIRE(0 == ups_db_count(db, 0, 0, &keycount));
REQUIRE(1ull == keycount);
REQUIRE(0 == ups_cursor_find(cursor, &key, &rec2, 0));
REQUIRE(rec.size == rec2.size);
REQUIRE(0 == strcmp((char *)rec.data, (char *)rec2.data));
REQUIRE(UPS_DUPLICATE_KEY == ups_cursor_insert(cursor, &key, &rec, 0));
REQUIRE(0 == ups_cursor_insert(cursor, &key, &rec, UPS_OVERWRITE));
memset(&rec2, 0, sizeof(rec2));
REQUIRE(0 == ups_cursor_find(cursor, &key, &rec2, 0));
REQUIRE(rec.size == rec2.size);
REQUIRE(0 == ::strcmp((char *)rec.data, (char *)rec2.data));
REQUIRE(0 == ups_cursor_erase(cursor, 0));
REQUIRE(UPS_KEY_NOT_FOUND == ups_cursor_find(cursor, &key, 0, 0));
REQUIRE(0 == ups_db_count(db, 0, 0, &keycount));
REQUIRE(0ull == keycount);
REQUIRE(0 == ups_env_close(env, UPS_AUTO_CLEANUP));
}
void insertData(ups_cursor_t *cursor, const char *k, const char *data) {
ups_key_t key = ups_make_key((void *)k,
(uint16_t)(k ? ::strlen(k) + 1 : 0));
ups_record_t rec = ups_make_record((void *)data,
(uint32_t)(::strlen(data) + 1));
REQUIRE(0 == ups_cursor_insert(cursor, &key, &rec, UPS_DUPLICATE));
}
void cursorGetDuplicateCountTest() {
ups_db_t *db;
ups_env_t *env;
uint32_t count;
ups_cursor_t *c;
ups_txn_t *txn;
REQUIRE(0 == ups_env_create(&env, SERVER_URL, 0, 0664, 0));
REQUIRE(0 == ups_env_open_db(env, &db, 14, 0, 0));
REQUIRE(0 == ups_txn_begin(&txn, env, 0, 0, 0));
REQUIRE(0 == ups_cursor_create(&c, db, txn, 0));
REQUIRE(UPS_INV_PARAMETER == ups_cursor_get_duplicate_count(0, &count, 0));
REQUIRE(UPS_INV_PARAMETER == ups_cursor_get_duplicate_count(c, 0, 0));
REQUIRE(UPS_CURSOR_IS_NIL == ups_cursor_get_duplicate_count(c, &count, 0));
REQUIRE((uint32_t)0 == count);
insertData(c, 0, "1111111111");
REQUIRE(0 == ups_cursor_get_duplicate_count(c, &count, 0));
REQUIRE((uint32_t)1 == count);
insertData(c, 0, "2222222222");
REQUIRE(0 == ups_cursor_get_duplicate_count(c, &count, 0));
REQUIRE((uint32_t)2 == count);
insertData(c, 0, "3333333333");
REQUIRE(0 == ups_cursor_get_duplicate_count(c, &count, 0));
REQUIRE((uint32_t)3 == count);
REQUIRE(0 == ups_cursor_erase(c, 0));
REQUIRE(UPS_CURSOR_IS_NIL == ups_cursor_get_duplicate_count(c, &count, 0));
ups_key_t key = {0};
REQUIRE(0 == ups_cursor_find(c, &key, 0, 0));
REQUIRE(0 == ups_cursor_get_duplicate_count(c, &count, 0));
REQUIRE((uint32_t)2 == count);
REQUIRE(0 == ups_cursor_close(c));
REQUIRE(0 == ups_txn_commit(txn, 0));
REQUIRE(0 == ups_env_close(env, UPS_AUTO_CLEANUP));
}
void cursorGetDuplicatePositionTest() {
ups_db_t *db;
ups_env_t *env;
ups_cursor_t *c;
ups_txn_t *txn;
uint32_t position = 0;
REQUIRE(0 == ups_env_create(&env, SERVER_URL, 0, 0664, 0));
REQUIRE(0 == ups_env_open_db(env, &db, 14, 0, 0));
REQUIRE(0 == ups_txn_begin(&txn, env, 0, 0, 0));
REQUIRE(0 == ups_cursor_create(&c, db, txn, 0));
REQUIRE(UPS_CURSOR_IS_NIL ==
ups_cursor_get_duplicate_position(c, &position));
REQUIRE((uint32_t)0 == position);
insertData(c, "p", "1111111111");
REQUIRE(0 == ups_cursor_get_duplicate_position(c, &position));
REQUIRE((uint32_t)0 == position);
insertData(c, "p", "2222222222");
REQUIRE(0 == ups_cursor_get_duplicate_position(c, &position));
REQUIRE((uint32_t)1 == position);
insertData(c, "p", "3333333333");
REQUIRE(0 == ups_cursor_get_duplicate_position(c, &position));
REQUIRE((uint32_t)2 == position);
REQUIRE(0 == ups_cursor_erase(c, 0));
REQUIRE(UPS_CURSOR_IS_NIL ==
ups_cursor_get_duplicate_position(c, &position));
REQUIRE(0 == ups_cursor_close(c));
REQUIRE(0 == ups_txn_abort(txn, 0));
REQUIRE(0 == ups_env_close(env, UPS_AUTO_CLEANUP));
}
void cursorOverwriteTest() {
ups_db_t *db;
ups_env_t *env;
ups_cursor_t *cursor;
ups_record_t rec2 = {};
ups_key_t key = ups_make_key((void *)"hello world", 12);
ups_record_t rec = ups_make_record((void *)"hello chris", 12);
REQUIRE(0 == ups_env_create(&env, SERVER_URL, 0, 0664, 0));
REQUIRE(0 == ups_env_open_db(env, &db, 14, 0, 0));
REQUIRE(0 == ups_cursor_create(&cursor, db, 0, 0));
REQUIRE(0 == ups_cursor_insert(cursor, &key, &rec, 0));
REQUIRE(0 == ups_cursor_find(cursor, &key, &rec2, 0));
REQUIRE(rec.size == rec2.size);
REQUIRE(0 == strcmp((char *)rec.data, (char *)rec2.data));
rec.data = (void *)"hello upscaledb";
rec.size = 16;
REQUIRE(0 == ups_cursor_overwrite(cursor, &rec, 0));
REQUIRE(0 == ups_cursor_find(cursor, &key, &rec2, 0));
REQUIRE(rec.size == rec2.size);
REQUIRE(0 == ::strcmp((char *)rec.data, (char *)rec2.data));
REQUIRE(0 == ups_env_close(env, UPS_AUTO_CLEANUP));
}
void cursorMoveTest() {
ups_db_t *db;
ups_env_t *env;
ups_cursor_t *cursor;
ups_key_t key = {}, key2 = {0};
key.size = 5;
ups_record_t rec = {}, rec2 = {0};
rec.size = 5;
REQUIRE(0 == ups_env_create(&env, SERVER_URL, 0, 0664, 0));
ups_env_erase_db(env, 14, 0);
REQUIRE(0 == ups_env_create_db(env, &db, 14, 0, 0));
REQUIRE(0 == ups_cursor_create(&cursor, db, 0, 0));
key.data = (void *)"key1";
rec.data = (void *)"rec1";
REQUIRE(0 == ups_cursor_insert(cursor, &key, &rec, 0));
key.data = (void *)"key2";
rec.data = (void *)"rec2";
REQUIRE(0 == ups_cursor_insert(cursor, &key, &rec, 0));
REQUIRE(0 == ups_cursor_move(cursor, 0, 0, UPS_CURSOR_FIRST));
key.data = (void *)"key1";
rec.data = (void *)"rec1";
REQUIRE(0 == ups_cursor_move(cursor, &key2, &rec2, 0));
REQUIRE(key.size == key2.size);
REQUIRE(0 == ::strcmp((char *)key.data, (char *)key2.data));
REQUIRE(rec.size == rec2.size);
REQUIRE(0 == ::strcmp((char *)rec.data, (char *)rec2.data));
REQUIRE(0 == ups_cursor_move(cursor, &key2, &rec2, UPS_CURSOR_NEXT));
key.data = (void *)"key2";
rec.data = (void *)"rec2";
REQUIRE(key.size == key2.size);
REQUIRE(0 == ::strcmp((char *)key.data, (char *)key2.data));
REQUIRE(rec.size == rec2.size);
REQUIRE(0 == ::strcmp((char *)rec.data, (char *)rec2.data));
REQUIRE(0 == ups_env_close(env, UPS_AUTO_CLEANUP));
}
void openTwiceTest() {
ups_db_t *db1, *db2;
ups_env_t *env;
REQUIRE(0 == ups_env_create(&env, SERVER_URL, 0, 0664, 0));
REQUIRE(0 == ups_env_open_db(env, &db1, 33, 0, 0));
REQUIRE(UPS_DATABASE_ALREADY_OPEN == ups_env_open_db(env, &db2, 33, 0, 0));
REQUIRE(0 == ups_env_close(env, UPS_AUTO_CLEANUP));
}
void cursorCreateTest() {
ups_db_t *db;
ups_env_t *env;
ups_cursor_t *cursor;
REQUIRE(0 == ups_env_create(&env, SERVER_URL, 0, 0664, 0));
REQUIRE(0 == ups_env_open_db(env, &db, 33, 0, 0));
REQUIRE(0 == ups_cursor_create(&cursor, db, 0, 0));
REQUIRE(0 == ups_env_close(env, UPS_AUTO_CLEANUP));
}
void cursorCloneTest() {
ups_db_t *db;
ups_env_t *env;
ups_cursor_t *src, *dest;
REQUIRE(0 == ups_env_create(&env, SERVER_URL, 0, 0664, 0));
REQUIRE(0 == ups_env_open_db(env, &db, 33, 0, 0));
REQUIRE(0 == ups_cursor_create(&src, db, 0, 0));
REQUIRE(0 == ups_cursor_clone(src, &dest));
REQUIRE(0 == ups_cursor_close(src));
REQUIRE(0 == ups_cursor_close(dest));
REQUIRE(0 == ups_db_close(db, 0));
REQUIRE(0 == ups_env_close(env, 0));
}
void autoCleanupCursorsTest() {
ups_env_t *env;
ups_db_t *db[3];
ups_cursor_t *c[5];
REQUIRE(0 == ups_env_create(&env, SERVER_URL, 0, 0664, 0));
for (int i = 0; i < 3; i++)
REQUIRE(0 == ups_env_create_db(env, &db[i], i+1, 0, 0));
for (int i = 0; i < 5; i++)
REQUIRE(0 == ups_cursor_create(&c[i], db[0], 0, 0));
REQUIRE(0 == ups_env_close(env, UPS_AUTO_CLEANUP));
}
void autoAbortTxnTest() {
ups_env_t *env;
ups_txn_t *txn;
ups_db_t *db;
REQUIRE(0 == ups_env_create(&env, SERVER_URL, 0, 0664, 0));
REQUIRE(0 == ups_env_create_db(env, &db, 1, 0, 0));
REQUIRE(0 == ups_txn_begin(&txn, env, 0, 0, 0));
REQUIRE(0 == ups_db_close(db, UPS_TXN_AUTO_ABORT));
REQUIRE(0 == ups_env_close(env, 0));
}
void timeoutTest() {
ups_env_t *env;
ups_parameter_t params[] = {
{ UPS_PARAM_NETWORK_TIMEOUT_SEC, 2 },
{ 0,0 }
};
ErrorInducer::activate(true);
ErrorInducer::add(ErrorInducer::kServerConnect, 1);
REQUIRE(UPS_IO_ERROR == ups_env_create(&env, SERVER_URL, 0,
0664, ¶ms[0]));
}
void uqiTest() {
ups_key_t key = {0};
ups_record_t record = {0};
uint32_t sum = 0;
ups_env_t *env;
REQUIRE(0 == ups_env_create(&env, SERVER_URL, 0, 0664, 0));
ups_db_t *db;
ups_parameter_t params[] = {
{ UPS_PARAM_KEY_TYPE, UPS_TYPE_UINT32 },
{ 0,0 }
};
REQUIRE(0 == ups_env_create_db(env, &db, 22, 0, ¶ms[0]));
// insert a few keys
for (int i = 0; i < 50; i++) {
key.data = &i;
key.size = sizeof(i);
REQUIRE(0 == ups_db_insert(db, 0, &key, &record, 0));
sum += i;
}
uqi_result_t *result;
uint32_t size;
REQUIRE(0 == uqi_select(env, "SUM($key) from database 22", &result));
REQUIRE(uqi_result_get_record_type(result) == UPS_TYPE_UINT64);
REQUIRE(*(uint64_t *)uqi_result_get_record_data(result, &size) == sum);
uqi_result_close(result);
REQUIRE(0 == uqi_select(env, "count($key) from database 22", &result));
REQUIRE(uqi_result_get_record_type(result) == UPS_TYPE_UINT64);
REQUIRE(*(uint64_t *)uqi_result_get_record_data(result, &size) == 50);
uqi_result_close(result);
REQUIRE(0 == ups_env_close(env, 0));
}
void bulkTest() {
ups_env_t *env;
ups_db_t *db;
REQUIRE(0 == ups_env_create(&env, SERVER_URL, 0, 0664, 0));
REQUIRE(0 == ups_env_create_db(env, &db, 1, 0, 0));
std::vector<ups_operation_t> ops;
int i1 = 1;
ups_key_t key1 = ups_make_key(&i1, sizeof(i1));
ups_record_t rec1 = ups_make_record(&i1, sizeof(i1));
ops.push_back({UPS_OP_INSERT, key1, rec1, 0});
int i2 = 2;
ups_key_t key2 = ups_make_key(&i2, sizeof(i2));
ups_record_t rec2 = ups_make_record(&i2, sizeof(i2));
ops.push_back({UPS_OP_INSERT, key2, rec2, 0});
int i3 = 3;
ups_key_t key3 = ups_make_key(&i3, sizeof(i3));
ups_record_t rec3 = ups_make_record(&i3, sizeof(i3));
ops.push_back({UPS_OP_INSERT, key3, rec3, 0});
ups_key_t key4 = ups_make_key(&i2, sizeof(i2));
ups_record_t rec4 = {0};
ops.push_back({UPS_OP_FIND, key4, rec4, 0});
ops.push_back({UPS_OP_ERASE, key4, rec4, 0});
ups_record_t rec5 = {0};
ops.push_back({UPS_OP_FIND, key4, rec5, 0});
REQUIRE(0 == ups_db_bulk_operations(db, 0, ops.data(), ops.size(), 0));
REQUIRE(0 == ops[0].result);
REQUIRE(0 == ops[1].result);
REQUIRE(0 == ops[2].result);
REQUIRE(0 == ops[3].result);
REQUIRE(ops[3].key.size == key4.size);
REQUIRE(0 == ::memcmp(ops[3].key.data, key4.data, key4.size));
REQUIRE(0 == ops[4].result);
REQUIRE(UPS_KEY_NOT_FOUND == ops[5].result);
REQUIRE(0 == ups_db_close(db, 0));
REQUIRE(0 == ups_env_close(env, 0));
}
void bulkUserAllocTest() {
ups_env_t *env;
ups_db_t *db;
REQUIRE(0 == ups_env_create(&env, SERVER_URL, 0, 0664, 0));
REQUIRE(0 == ups_env_create_db(env, &db, 1, 0, 0));
std::vector<ups_operation_t> ops;
int i1 = 99;
ups_key_t key1 = ups_make_key(&i1, sizeof(i1));
ups_record_t rec1 = ups_make_record(&i1, sizeof(i1));
ops.push_back({UPS_OP_INSERT, key1, rec1, 0});
ups_key_t key4 = ups_make_key(&i1, sizeof(i1));
int i4 = 0;
ups_record_t rec4 = ups_make_record(&i4, sizeof(i4));
rec4.flags = UPS_RECORD_USER_ALLOC;
ops.push_back({UPS_OP_FIND, key4, rec4, 0});
REQUIRE(0 == ups_db_bulk_operations(db, 0, ops.data(), ops.size(), 0));
REQUIRE(ops[1].key.size == key4.size);
REQUIRE(i4 == i1);
REQUIRE(0 == ups_db_close(db, 0));
REQUIRE(0 == ups_env_close(env, 0));
}
void bulkApproxMatchingTest() {
ups_env_t *env;
ups_db_t *db;
REQUIRE(0 == ups_env_create(&env, SERVER_URL, 0, 0664, 0));
REQUIRE(0 == ups_env_create_db(env, &db, 1, 0, 0));
std::vector<ups_operation_t> ops;
int i1 = 10;
ups_key_t key1 = ups_make_key(&i1, sizeof(i1));
ups_record_t rec1 = ups_make_record(&i1, sizeof(i1));
ops.push_back({UPS_OP_INSERT, key1, rec1, 0});
int i2 = 20;
ups_key_t key2 = ups_make_key(&i2, sizeof(i2));
ups_record_t rec2 = ups_make_record(&i2, sizeof(i2));
ops.push_back({UPS_OP_INSERT, key2, rec2, 0});
int i3 = 30;
ups_key_t key3 = ups_make_key(&i3, sizeof(i3));
ups_record_t rec3 = ups_make_record(&i3, sizeof(i3));
ops.push_back({UPS_OP_INSERT, key3, rec3, 0});
int i4 = i2;
ups_key_t key4 = ups_make_key(&i4, sizeof(i4));
key4.flags = UPS_KEY_USER_ALLOC;
ups_record_t rec4 = {0};
ops.push_back({UPS_OP_FIND, key4, rec4, UPS_FIND_LT_MATCH});
int i5 = i2;
ups_key_t key5 = ups_make_key(&i5, sizeof(i5));
ups_record_t rec5 = {0};
ops.push_back({UPS_OP_FIND, key5, rec5, UPS_FIND_GT_MATCH});
REQUIRE(0 == ups_db_bulk_operations(db, 0, ops.data(), ops.size(), 0));
REQUIRE(*(int *)ops[3].record.data == i1);
REQUIRE(i4 == i1);
REQUIRE(*(int *)ops[4].key.data == i3);
REQUIRE(0 == ups_db_close(db, 0));
REQUIRE(0 == ups_env_close(env, 0));
}
void bulkNegativeTests() {
ups_env_t *env;
ups_db_t *db;
REQUIRE(0 == ups_env_create(&env, SERVER_URL, 0, 0664, 0));
REQUIRE(0 == ups_env_create_db(env, &db, 1, 0, 0));
std::vector<ups_operation_t> ops;
REQUIRE(UPS_INV_PARAMETER == ups_db_bulk_operations(0, 0,
ops.data(), 0, 0));
REQUIRE(UPS_INV_PARAMETER == ups_db_bulk_operations(db, 0, 0, 0, 0));
int i1 = 10;
ups_key_t key1 = ups_make_key(&i1, sizeof(i1));
ups_record_t rec1 = ups_make_record(&i1, sizeof(i1));
ops.push_back({UPS_OP_INSERT, key1, rec1, 0});
ops.push_back({99, key1, rec1, 0});
REQUIRE(UPS_INV_PARAMETER == ups_db_bulk_operations(db, 0,
ops.data(), 2, 0));
REQUIRE(0 == ups_db_close(db, 0));
REQUIRE(0 == ups_env_close(env, 0));
}
};
TEST_CASE("Remote/invalidUrlTest", "")
{
RemoteFixture f;
f.invalidUrlTest();
}
TEST_CASE("Remote/invalidPathTest", "")
{
RemoteFixture f;
f.invalidPathTest();
}
TEST_CASE("Remote/createCloseTest", "")
{
RemoteFixture f;
f.createCloseTest();
}
TEST_CASE("Remote/createCloseOpenCloseTest", "")
{
RemoteFixture f;
f.createCloseOpenCloseTest();
}
TEST_CASE("Remote/getEnvParamsTest", "")
{
RemoteFixture f;
f.getEnvParamsTest();
}
TEST_CASE("Remote/getDatabaseNamesTest", "")
{
RemoteFixture f;
f.getDatabaseNamesTest();
}
TEST_CASE("Remote/envFlushTest", "")
{
RemoteFixture f;
f.envFlushTest();
}
TEST_CASE("Remote/renameDbTest", "")
{
RemoteFixture f;
f.renameDbTest();
}
TEST_CASE("Remote/createDbTest", "")
{
RemoteFixture f;
f.createDbTest();
}
TEST_CASE("Remote/createDbExtendedTest", "")
{
RemoteFixture f;
f.createDbExtendedTest();
}
TEST_CASE("Remote/openDbTest", "")
{
RemoteFixture f;
f.openDbTest();
}
TEST_CASE("Remote/eraseDbTest", "")
{
RemoteFixture f;
f.eraseDbTest();
}
TEST_CASE("Remote/getDbParamsTest", "")
{
RemoteFixture f;
f.getDbParamsTest();
}
TEST_CASE("Remote/txnBeginCommitTest", "")
{
RemoteFixture f;
f.txnBeginCommitTest();
}
TEST_CASE("Remote/txnBeginAbortTest", "")
{
RemoteFixture f;
f.txnBeginAbortTest();
}
TEST_CASE("Remote/checkIntegrityTest", "")
{
RemoteFixture f;
f.checkIntegrityTest();
}
TEST_CASE("Remote/getKeyCountTest", "")
{
RemoteFixture f;
f.getKeyCountTest();
}
TEST_CASE("Remote/insertFindTest", "")
{
RemoteFixture f;
f.insertFindTest();
}
TEST_CASE("Remote/insertFindBigTest", "")
{
RemoteFixture f;
f.insertFindBigTest();
}
TEST_CASE("Remote/insertRecno64Test", "")
{
RemoteFixture f;
f.insertRecnoTest<uint64_t>(33);
}
TEST_CASE("Remote/insertFindEraseTest", "")
{
RemoteFixture f;
f.insertFindEraseTest();
}
TEST_CASE("Remote/insertFindEraseUserallocTest", "")
{
RemoteFixture f;
f.insertFindEraseUserallocTest();
}
TEST_CASE("Remote/insertFindEraseRecno64Test", "")
{
RemoteFixture f;
f.insertFindEraseRecnoTest<uint64_t>(33);
}
TEST_CASE("Remote/cursorInsertFindTest", "")
{
RemoteFixture f;
f.cursorInsertFindTest();
}
TEST_CASE("Remote/cursorInsertRecno64Test", "")
{
RemoteFixture f;
f.cursorInsertRecnoTest<uint64_t>(33);
}
TEST_CASE("Remote/cursorInsertFindEraseTest", "")
{
RemoteFixture f;
f.cursorInsertFindEraseTest();
}
TEST_CASE("Remote/cursorInsertFindEraseUserallocTest", "")
{
RemoteFixture f;
f.cursorInsertFindEraseUserallocTest();
}
TEST_CASE("Remote/cursorInsertFindEraseRecno64Test", "")
{
RemoteFixture f;
f.cursorInsertFindEraseRecnoTest<uint64_t>(33);
}
TEST_CASE("Remote/cursorGetDuplicateCountTest", "")
{
RemoteFixture f;
f.cursorGetDuplicateCountTest();
}
TEST_CASE("Remote/cursorGetDuplicatePositionTest", "")
{
RemoteFixture f;
f.cursorGetDuplicatePositionTest();
}
TEST_CASE("Remote/cursorOverwriteTest", "")
{
RemoteFixture f;
f.cursorOverwriteTest();
}
TEST_CASE("Remote/cursorMoveTest", "")
{
RemoteFixture f;
f.cursorMoveTest();
}
TEST_CASE("Remote/openTwiceTest", "")
{
RemoteFixture f;
f.openTwiceTest();
}
TEST_CASE("Remote/cursorCreateTest", "")
{
RemoteFixture f;
f.cursorCreateTest();
}
TEST_CASE("Remote/cursorCloneTest", "")
{
RemoteFixture f;
f.cursorCloneTest();
}
TEST_CASE("Remote/autoCleanupCursorsTest", "")
{
RemoteFixture f;
f.autoCleanupCursorsTest();
}
TEST_CASE("Remote/autoAbortTxnTest", "")
{
RemoteFixture f;
f.autoAbortTxnTest();
}
TEST_CASE("Remote/timeoutTest", "")
{
RemoteFixture f;
f.timeoutTest();
}
TEST_CASE("Remote/insertRecno32Test", "")
{
RemoteFixture f;
f.insertRecnoTest<uint32_t>(34);
}
TEST_CASE("Remote/insertFindEraseRecno32Test", "")
{
RemoteFixture f;
f.insertFindEraseRecnoTest<uint32_t>(34);
}
TEST_CASE("Remote/cursorInsertRecno32Test", "")
{
RemoteFixture f;
f.cursorInsertRecnoTest<uint32_t>(34);
}
TEST_CASE("Remote/cursorInsertFindEraseRecno32Test", "")
{
RemoteFixture f;
f.cursorInsertFindEraseRecnoTest<uint32_t>(34);
}
TEST_CASE("Remote/approxMatchTest", "")
{
RemoteFixture f;
f.approxMatchTest();
}
TEST_CASE("Remote/cursorApproxMatchTest", "")
{
RemoteFixture f;
f.cursorApproxMatchTest();
}
TEST_CASE("Remote/uqiTest", "")
{
RemoteFixture f;
f.uqiTest();
}
TEST_CASE("Remote/bulkTest", "")
{
RemoteFixture f;
f.bulkTest();
}
TEST_CASE("Remote/bulkUserAllocTest", "")
{
RemoteFixture f;
f.bulkUserAllocTest();
}
TEST_CASE("Remote/bulkApproxMatchingTest", "")
{
RemoteFixture f;
f.bulkApproxMatchingTest();
}
TEST_CASE("Remote/bulkNegativeTests", "")
{
RemoteFixture f;
f.bulkNegativeTests();
}
#endif // UPS_ENABLE_REMOTE
| 29.39354 | 81 | 0.628818 | [
"vector"
] |
18f26e7356a183e72a5981d2812236a036701744 | 3,952 | cpp | C++ | source/application/PathTracer/raytracing/system/PlatformManager.cpp | compix/Monte-Carlo-Raytracer | f27842c40dd380aee78f1579873341ad6cfe0834 | [
"MIT"
] | 3 | 2018-09-23T03:12:36.000Z | 2021-12-01T08:30:43.000Z | source/application/PathTracer/raytracing/system/PlatformManager.cpp | compix/Monte-Carlo-Raytracer | f27842c40dd380aee78f1579873341ad6cfe0834 | [
"MIT"
] | null | null | null | source/application/PathTracer/raytracing/system/PlatformManager.cpp | compix/Monte-Carlo-Raytracer | f27842c40dd380aee78f1579873341ad6cfe0834 | [
"MIT"
] | 1 | 2018-09-19T01:49:24.000Z | 2018-09-19T01:49:24.000Z | #include "PlatformManager.h"
#include "engine/util/Logger.h"
#include "mutex"
#if defined(_WIN32)
#include <gl/wglew.h>
#elif defined(__unix__)
// TODO
#elif __APPLE__
// TODO
#endif
std::vector<CLWPlatform> PlatformManager::m_platforms;
std::vector<CLWDevice> PlatformManager::m_supportedDevices;
std::unordered_map<int, int> PlatformManager::m_deviceToPlatformMap;
bool PlatformManager::m_initialized = false;
int PlatformManager::m_activeDeviceIdx = -1;
void PlatformManager::init()
{
// Platforms are OpenCL implementations which can vary in version and vendor.
CLWPlatform::CreateAllPlatforms(m_platforms);
if (m_platforms.size() == 0)
{
LOG_ERROR("No OpenCL platforms installed.");
return;
}
// Devices are processors (CPU, GPU...) that support the implementation.
// In this case we are only interested in GPU devices with GL interoperability which
// are stored in m_supportedDevices.
for (int i = 0; i < m_platforms.size(); ++i)
{
for (int d = 0; d < (int)m_platforms[i].GetDeviceCount(); ++d)
{
CLWDevice curDevice = m_platforms[i].GetDevice(d);
if (curDevice.GetType() != CL_DEVICE_TYPE_GPU || !curDevice.HasGlInterop())
{
LOG("Skipped incompatible device: " << curDevice.GetName());
continue;
}
m_supportedDevices.push_back(curDevice);
m_deviceToPlatformMap[static_cast<int>(m_supportedDevices.size()) - 1] = i;
}
}
m_initialized = true;
m_activeDeviceIdx = getBestDeviceIdx();
}
int PlatformManager::getBestDeviceIdx()
{
if (!m_initialized)
{
return INVALID_DEVICE_INDEX;
}
size_t deviceMemSize = 0;
int deviceIdx = INVALID_DEVICE_INDEX;
for (size_t i = 0; i < m_supportedDevices.size(); ++i)
{
if (m_supportedDevices[i].GetGlobalMemSize() > deviceMemSize)
{
deviceIdx = static_cast<int>(i);
deviceMemSize = m_supportedDevices[i].GetGlobalMemSize();
}
}
return deviceIdx;
}
const std::vector<CLWDevice>& PlatformManager::getSupportedDevices()
{
return m_supportedDevices;
}
int PlatformManager::getDeviceIndex(const CLWDevice& device)
{
for (size_t i = 0; i < m_supportedDevices.size(); ++i)
{
if (m_supportedDevices[i].GetID() == device.GetID())
{
return static_cast<int>(i);
}
}
return -1;
}
CLWDevice& PlatformManager::getDevice(int deviceIdx)
{
assert(deviceIdx >= 0 && deviceIdx < m_supportedDevices.size());
return m_supportedDevices[deviceIdx];
}
CLWDevice* PlatformManager::getActiveDevice()
{
if (m_activeDeviceIdx >= 0 && m_activeDeviceIdx < m_supportedDevices.size())
{
return &getDevice(m_activeDeviceIdx);
}
return nullptr;
}
void PlatformManager::setActiveDeviceIdx(int deviceIdx)
{
m_activeDeviceIdx = deviceIdx;
}
int PlatformManager::getActiveDeviceIdx()
{
return m_activeDeviceIdx;
}
CLWPlatform* PlatformManager::getActiveDevicePlatform()
{
int deviceIdx = getActiveDeviceIdx();
if (deviceIdx != INVALID_DEVICE_INDEX)
{
return &m_platforms[m_deviceToPlatformMap[deviceIdx]];
}
return nullptr;
}
CLWContext PlatformManager::createCLContextWithGLInterop()
{
// A context is a set of user defined devices that are available on the platform of the context.
// Each device in the context has a command queue which is used to execute commands, e.g. user defined kernels.
auto platformPtr = getActiveDevicePlatform();
cl_platform_id platform = 0;
if (platformPtr)
platform = *platformPtr;
#if defined(_WIN32)
cl_context_properties props[] =
{
CL_CONTEXT_PLATFORM, (cl_context_properties)platform,
CL_GL_CONTEXT_KHR, (cl_context_properties)wglGetCurrentContext(),
CL_WGL_HDC_KHR, (cl_context_properties)wglGetCurrentDC(),
0
};
#elif defined(__unix__)
cl_context_properties props[] =
{
CL_CONTEXT_PLATFORM, (cl_context_properties)platform,
CL_GL_CONTEXT_KHR, (cl_context_properties)glXGetCurrentContext(),
CL_WGL_HDC_KHR, (cl_context_properties)glXGetCurrentDrawable(),
0
};
#elif __APPLE__
// TODO
#endif
return CLWContext::Create(*getActiveDevice(), props);
}
| 23.52381 | 113 | 0.743168 | [
"vector"
] |
18f29cf8a71859ea112dec326489efacdc33055b | 1,194 | hh | C++ | src/CRKSPH/computeCRKSPHIntegral.hh | jmikeowen/Spheral | 3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4 | [
"BSD-Source-Code",
"BSD-3-Clause-LBNL",
"FSFAP"
] | 22 | 2018-07-31T21:38:22.000Z | 2020-06-29T08:58:33.000Z | src/CRKSPH/computeCRKSPHIntegral.hh | markguozhiming/spheral | bbb982102e61edb8a1d00cf780bfa571835e1b61 | [
"BSD-Source-Code",
"BSD-3-Clause-LBNL",
"FSFAP"
] | 41 | 2020-09-28T23:14:27.000Z | 2022-03-28T17:01:33.000Z | src/CRKSPH/computeCRKSPHIntegral.hh | markguozhiming/spheral | bbb982102e61edb8a1d00cf780bfa571835e1b61 | [
"BSD-Source-Code",
"BSD-3-Clause-LBNL",
"FSFAP"
] | 7 | 2019-12-01T07:00:06.000Z | 2020-09-15T21:12:39.000Z | //---------------------------------Spheral++------------------------------------
// Compute the CRKSPH corrections.
//------------------------------------------------------------------------------
#ifndef __Spheral__computeCRKSPHIntegral__
#define __Spheral__computeCRKSPHIntegral__
namespace Spheral {
// Forward declarations.
template<typename Dimension> class ConnectivityMap;
template<typename Dimension> class TableKernel;
template<typename Dimension, typename DataType> class FieldList;
template<typename Dimension>
std::pair<typename Dimension::Vector,typename Dimension::Vector>
computeCRKSPHIntegral(const ConnectivityMap<Dimension>& connectivityMap,
const TableKernel<Dimension>& W,
const FieldList<Dimension, typename Dimension::Scalar>& weight,
const FieldList<Dimension, typename Dimension::Vector>& position,
const FieldList<Dimension, typename Dimension::SymTensor>& H,
size_t nodeListi, const int i, size_t nodeListj, const int j, int mydim, const int order,
typename Dimension::Vector rmin, typename Dimension::Vector rmax);
}
#endif
| 44.222222 | 112 | 0.622278 | [
"vector"
] |
18f6633fda797704909dbd9a490cea1d9dde20cd | 7,024 | hpp | C++ | crogine/include/crogine/core/App.hpp | fallahn/crogine | f6cf3ade1f4e5de610d52e562bf43e852344bca0 | [
"FTL",
"Zlib"
] | 41 | 2017-08-29T12:14:36.000Z | 2022-02-04T23:49:48.000Z | crogine/include/crogine/core/App.hpp | fallahn/crogine | f6cf3ade1f4e5de610d52e562bf43e852344bca0 | [
"FTL",
"Zlib"
] | 11 | 2017-09-02T15:32:45.000Z | 2021-12-27T13:34:56.000Z | crogine/include/crogine/core/App.hpp | fallahn/crogine | f6cf3ade1f4e5de610d52e562bf43e852344bca0 | [
"FTL",
"Zlib"
] | 5 | 2020-01-25T17:51:45.000Z | 2022-03-01T05:20:30.000Z | /*-----------------------------------------------------------------------
Matt Marchant 2017 - 2021
http://trederia.blogspot.com
crogine - Zlib license.
This software is provided 'as-is', without any express or
implied warranty.In no event will the authors be held
liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute
it freely, subject to the following restrictions :
1. The origin of this software must not be misrepresented;
you must not claim that you wrote the original software.
If you use this software in a product, an acknowledgment
in the product documentation would be appreciated but
is not required.
2. Altered source versions must be plainly marked as such,
and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any
source distribution.
-----------------------------------------------------------------------*/
#pragma once
#include <crogine/Config.hpp>
#include <crogine/core/MessageBus.hpp>
#include <crogine/core/Window.hpp>
#include <crogine/core/Clock.hpp>
#include <crogine/core/Console.hpp>
#include <crogine/core/Keyboard.hpp>
#include <crogine/core/GameController.hpp>
#include <crogine/detail/Types.hpp>
#include <crogine/graphics/Colour.hpp>
#include <vector>
#include <map>
#ifdef CRO_DEBUG_
#define DPRINT(x, y) cro::Console::printStat(x, y)
#else
#define DPRINT(x, y)
#endif //CRO_DEBUG_
namespace cro
{
namespace Detail
{
class SDLResource;
}
class GuiClient;
class HiResTimer;
/*!
\brief Base class for crogine applications.
One instance of this must exist before crogine may be used
*/
class CRO_EXPORT_API App
{
public:
friend class Detail::SDLResource;
/*!
\param windowStyleFlags Style flags with which to create the default window
\see Window
*/
explicit App(std::uint32_t windowStyleFlags = 0);
virtual ~App();
App(const App&) = delete;
App(const App&&) = delete;
App& operator = (const App&) = delete;
App& operator = (const App&&) = delete;
void run();
void setClearColour(Colour);
const Colour& getClearColour() const;
/*!
\brief Use this to properly close down the application
*/
static void quit();
/*!
\brief Returns a reference to the active window
*/
static Window& getWindow();
/*!
\brief Returns a reference to the system message bus
*/
MessageBus& getMessageBus() { return m_messageBus; }
/*!
\brief Returns the path to the current platform's directory
for storing preference files. Before using this the application's
organisation name and app name should be set with setApplicationStrings()
\see setApplicationStrings()
*/
static const std::string& getPreferencePath();
/*!
\brief Resets the frame clock.
This should only be used when a state finishes loading assets for a long time
to prevent the initial delta frame being a large value.
*/
void resetFrameTime();
/*!
\brief Returns a reference to the active App instance
*/
static App& getInstance();
/*!
\brief Returns true if there is a valid instance of this class
*/
static bool isValid();
protected:
virtual void handleEvent(const Event&) = 0;
virtual void handleMessage(const cro::Message&) = 0;
/*!
\brief Used to update the simulation with a fixed timestep of 60Hz
*/
virtual void simulate(float) = 0;
/*!
\brief Renders any drawables
*/
virtual void render() = 0;
/*!
\brief Called on startup after window is created.
Use it to perform initial operations such as setting the
window title, icon or custom loading screen. Return false
from this if custom initialisation fails for some reason
so that the app may safely shut down while calling finalise().
*/
virtual bool initialise() = 0;
/*!
\brief Called before the window is destroyed.
Use this to clean up any resources which rely on the
window's OpenGL context.
*/
virtual void finalise() {};
/*!
\brief Set the organisation name and application name.
These should be set immediately on construction of your application,
as they are used to form the preferences path retrieved with
getPreferencePath(). The application name should be unique to prevent
overwriting settings files used by other crogine applications.
*/
void setApplicationStrings(const std::string& organisation, const std::string& applicationName);
/*!
\brief Saves the current window and AudioMixer settings
*/
void saveSettings();
private:
std::uint32_t m_windowStyleFlags;
Window m_window;
Colour m_clearColour;
HiResTimer* m_frameClock;
bool m_running;
void handleEvents();
MessageBus m_messageBus;
void handleMessages();
static App* m_instance;
struct ControllerInfo final
{
ControllerInfo() = default;
ControllerInfo(SDL_GameController* gc)
: controller(gc) {}
SDL_GameController* controller = nullptr;
SDL_Haptic* haptic = nullptr;
std::int32_t joystickID = -1; //event IDs don't actually match the controllers
};
std::array<ControllerInfo, GameController::MaxControllers> m_controllers = {};
std::map<std::int32_t, SDL_Joystick*> m_joysticks;
std::size_t m_controllerCount;
friend class GameController;
std::vector<std::pair<std::function<void()>, const GuiClient*>> m_statusControls;
std::vector<std::pair<std::function<void()>, const GuiClient*>> m_guiWindows;
void doImGui();
static void addConsoleTab(const std::string&, const std::function<void()>&, const GuiClient*);
static void removeConsoleTab(const GuiClient*);
static void addWindow(const std::function<void()>&, const GuiClient*);
static void removeWindows(const GuiClient*);
friend class GuiClient;
friend class Console;
std::string m_orgString;
std::string m_appString;
std::string m_prefPath;
struct WindowSettings final
{
std::int32_t width = 800;
std::int32_t height = 600;
bool fullscreen = false;
bool vsync = true;
bool useMultisampling = false;
};
WindowSettings loadSettings();
void saveScreenshot();
};
} | 30.406926 | 104 | 0.625142 | [
"render",
"vector"
] |
18f929c96ddaaabbc5fd34b72c61e7df3d10df8e | 880 | cpp | C++ | Windy/source/core/content/container.cpp | Greentwip/windy | 4eb8174f952c5b600ff004827a5c85dbfb013091 | [
"MIT"
] | 1 | 2017-07-13T21:11:55.000Z | 2017-07-13T21:11:55.000Z | Windy/source/core/content/container.cpp | Greentwip/Windy | 4eb8174f952c5b600ff004827a5c85dbfb013091 | [
"MIT"
] | null | null | null | Windy/source/core/content/container.cpp | Greentwip/Windy | 4eb8174f952c5b600ff004827a5c85dbfb013091 | [
"MIT"
] | null | null | null | #include "core/content/container.hpp"
#include "core/content/instance.hpp"
windy::content::container::container() {
}
void windy::content::container::bake() { // required
auto background_layer = std::make_shared<layer>();
auto animation_layer = std::make_shared<layer>();
auto composition_layer = std::make_shared<layer>();
this->add_child(background_layer);
this->add_child(animation_layer);
this->add_child(composition_layer);
}
void windy::content::container::add(std::shared_ptr<instance> instance) {
this->children()[instance->kind()]->add_child(instance);
}
void windy::content::container::remove(std::shared_ptr<instance> instance) {
this->children()[instance->kind()]->remove_child_by_name(instance->name());
}
std::vector<std::shared_ptr<class windy::node> >& windy::content::container::get(layer::kind kind) {
return this->children()[kind]->children();
} | 31.428571 | 100 | 0.735227 | [
"vector"
] |
18feb80ebe1a6b0988838e881daca31911740a0d | 861 | cpp | C++ | devdc87.cpp | vidit1999/coding_problems | b6c9fa7fda37d9424cd11bcd54b385fd8cf1ee0a | [
"BSD-2-Clause"
] | 1 | 2020-02-24T18:28:48.000Z | 2020-02-24T18:28:48.000Z | devdc87.cpp | vidit1999/coding_problems | b6c9fa7fda37d9424cd11bcd54b385fd8cf1ee0a | [
"BSD-2-Clause"
] | null | null | null | devdc87.cpp | vidit1999/coding_problems | b6c9fa7fda37d9424cd11bcd54b385fd8cf1ee0a | [
"BSD-2-Clause"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
/*
The Pony Express was a mail service that operated from 1859-60 in the United States.
It was made completely obsolete by the intercontinental telegraph.
There were a number of stations where a rider would stop to switch to a fresh horse,
or pass the mail bag along to another rider to continue the trek.
stations is an array/list of distances in miles from one station to the next along the route.
Implement a riders function, to return how many riders it would take to get from point A to point B.
Riders will never agree to riding more than 100 miles.
example: stations = [43, 23, 40, 13]
output: 2 riders
*/
int riders(vector<int> stations){
float sum = 0;
for(int i : stations)
sum += i;
return ceil(sum/100);
}
// main function
int main(){
cout << riders({43, 23, 40, 13}) << "\n";
return 0;
} | 26.90625 | 100 | 0.727062 | [
"vector"
] |
bb41ad9bedb541d696a11f257a3226aea48272dd | 7,969 | cpp | C++ | src/main.cpp | Seideman-Group/chiML | 9ace5dccdbc6c173e8383f6a31ff421b4fefffdf | [
"MIT"
] | 1 | 2019-04-27T05:25:27.000Z | 2019-04-27T05:25:27.000Z | src/main.cpp | Seideman-Group/chiML | 9ace5dccdbc6c173e8383f6a31ff421b4fefffdf | [
"MIT"
] | null | null | null | src/main.cpp | Seideman-Group/chiML | 9ace5dccdbc6c173e8383f6a31ff421b4fefffdf | [
"MIT"
] | 2 | 2019-04-03T10:08:21.000Z | 2019-09-30T22:40:28.000Z | // #include <iostream>
// #include "FDTDField.hpp"
// #include "FDTDFieldTE.hpp"
// #include "FDTDFieldTM.hpp"
#include <FDTD_MANAGER/parallelFDTDField.hpp>
// #include <iomanip>
namespace mpi = boost::mpi;
int main(int argc, char const *argv[])
{
// Initialize the boost mpi environment and communicator
mpi::environment env;
std::shared_ptr<mpiInterface> gridComm = std::make_shared<mpiInterface>();
std::clock_t start;
std::string filename;
double duration= 0.0;
if (argc < 2)
{
std::cout << "Provide an input json file" << std::endl;
exit(1);
}
else
{
// Take in the file name and strip out all comments for the parser
filename = argv[1];
if(gridComm->rank() == 0)
stripComments(filename);
else
filename = "stripped_" + filename;
}
gridComm->barrier();
if(gridComm->rank() == 0)
std::cout << "Reading input file " << argv[1] << "..." << std::endl;
//construct the parser and pass it to the inputs
boost::property_tree::ptree propTree;
boost::property_tree::json_parser::read_json(filename,propTree);
parallelProgramInputs IP(propTree, filename);
gridComm->barrier();
if(gridComm->rank() == 0)
boost::filesystem::remove(filename) ;
if(gridComm->rank() == 0)
std::cout << "I TOOK ALL THE INPUT PARAMETERS" << std::endl;
double maxT = IP.tMax();
if(!IP.cplxFields_)
{
parallelFDTDFieldReal FF(IP, gridComm);
if(gridComm->rank() == 0)
std::cout << "made with real fields" << std::endl;
int nSteps = int(std::ceil( IP.tMax_ / (IP.dt_) ) );
start = std::clock();
for(int tt = 0; tt < nSteps; ++tt )
FF.step();
duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;
for(int ii = 0; ii < gridComm->size(); ii ++)
{
gridComm->barrier();
if(gridComm->rank() == ii)
std::cout << gridComm->rank() << "\t" << duration<<std::endl;
}
// Output the final flux for all flux objects, Polarization terms are because of units for continuous boxes defined by the z component (TE off grid is E fields, TM H fields)
for(auto & flux : FF.fluxArr() )
{
// flux->getFlux(FF.EIncd(), FF.HIncd(), FF.H_mnIncd());
flux->getFlux(FF.ExIncd(), FF.EyIncd(), FF.EzIncd(), FF.HxIncd(), FF.HyIncd(), FF.HzIncd(), true);
}
// Power outputs need incident fields for normalization
for(auto & dtc : FF.dtcFreqArr())
{
try
{
std::vector<std::vector<cplx>> incdFields;
if(dtc->type() == DTCTYPE::HPOW)
incdFields = { FF.HxIncd(), FF.HyIncd(), FF.HzIncd() };
else if(dtc->type() == DTCTYPE::EPOW)
incdFields = { FF.ExIncd(), FF.EyIncd(), FF.EzIncd() };
else if(dtc->type() == DTCTYPE::EX || dtc->type() == DTCTYPE::PX)
incdFields = { FF.ExIncd() };
else if(dtc->type() == DTCTYPE::EY || dtc->type() == DTCTYPE::PY)
incdFields = { FF.EyIncd() };
else if(dtc->type() == DTCTYPE::EZ || dtc->type() == DTCTYPE::PZ)
incdFields = { FF.EzIncd() };
else if(dtc->type() == DTCTYPE::HX || dtc->type() == DTCTYPE::MX)
incdFields = { FF.HxIncd() };
else if(dtc->type() == DTCTYPE::HY || dtc->type() == DTCTYPE::MY)
incdFields = { FF.HyIncd() };
else if(dtc->type() == DTCTYPE::HZ || dtc->type() == DTCTYPE::MZ)
incdFields = { FF.HzIncd() };
if(dtc->outputMaps())
dtc->toMap(incdFields, FF.dt());
else
dtc->toFile(incdFields, FF.dt());
}
catch(std::exception& e)
{
if(dtc->outputMaps())
dtc->toMap();
else
dtc->toFile();
}
}
for(auto& dtc : FF.dtcArr())
dtc->toFile();
for(auto& qe : FF.qeArr())
{
if( qe->pAccuulate() )
qe->outputPol();
for(auto& dtcPop: qe->dtcPopArr() )
dtcPop->toFile();
}
// output scaling information
duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;
for(int ii = 0; ii < gridComm->size(); ii ++)
{
gridComm->barrier();
if(gridComm->rank() == ii)
std::cout << gridComm->rank() << "\t" << duration<<std::endl;
}
}
else
{
parallelFDTDFieldCplx FF(IP, gridComm);
if(gridComm->rank() == 0)
std::cout << "made with complex fields" << std::endl;
int nSteps = int(std::ceil( IP.tMax_ / (IP.dt_) ) );
start = std::clock();
for(int tt = 0; tt < nSteps; ++tt )
FF.step();
duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;
for(int ii = 0; ii < gridComm->size(); ii ++)
{
gridComm->barrier();
if(gridComm->rank() == ii)
std::cout << gridComm->rank() << "\t" << duration<<std::endl;
}
// Output the final flux for all flux objects, Polarization terms are because of units for continuous boxes defined by the z component (TE off grid is E fields, TM H fields)
for(auto & flux : FF.fluxArr() )
{
flux->getFlux(FF.ExIncd(), FF.EyIncd(), FF.EzIncd(), FF.HxIncd(), FF.HyIncd(), FF.HzIncd(), true);
}
// Power outputs need incident fields for normalization
for(auto & dtc : FF.dtcFreqArr())
{
try
{
std::vector<std::vector<cplx>> incdFields;
if(dtc->type() == DTCTYPE::HPOW)
incdFields = { FF.HxIncd(), FF.HyIncd(), FF.HzIncd() };
else if(dtc->type() == DTCTYPE::EPOW)
incdFields = { FF.ExIncd(), FF.EyIncd(), FF.EzIncd() };
else if(dtc->type() == DTCTYPE::EX || dtc->type() == DTCTYPE::PX)
incdFields = { FF.ExIncd() };
else if(dtc->type() == DTCTYPE::EY || dtc->type() == DTCTYPE::PY)
incdFields = { FF.EyIncd() };
else if(dtc->type() == DTCTYPE::EZ || dtc->type() == DTCTYPE::PZ)
incdFields = { FF.EzIncd() };
else if(dtc->type() == DTCTYPE::HX || dtc->type() == DTCTYPE::MX)
incdFields = { FF.HxIncd() };
else if(dtc->type() == DTCTYPE::HY || dtc->type() == DTCTYPE::MY)
incdFields = { FF.HyIncd() };
else if(dtc->type() == DTCTYPE::HZ || dtc->type() == DTCTYPE::MZ)
incdFields = { FF.HzIncd() };
if(dtc->outputMaps())
dtc->toMap(incdFields, FF.dt());
else
dtc->toFile(incdFields, FF.dt());
}
catch(std::exception& e)
{
if(dtc->outputMaps())
dtc->toMap();
else
dtc->toFile();
}
}
for(auto& dtc : FF.dtcArr())
dtc->toFile();
for(auto& qe : FF.qeArr())
{
if( qe->pAccuulate() )
qe->outputPol();
for(auto& dtcPop: qe->dtcPopArr() )
dtcPop->toFile();
}
// output scaling information
duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;
for(int ii = 0; ii < gridComm->size(); ii ++)
{
gridComm->barrier();
if(gridComm->rank() == ii)
std::cout << gridComm->rank() << "\t" << duration<<std::endl;
}
}
return 0;
}
| 38.3125 | 181 | 0.477726 | [
"vector"
] |
bb4bc4bc75fb733698b1ab4eba4e35a0de2bd347 | 1,477 | cpp | C++ | src/absyn_tree.cpp | wangnangg/xml_exp | a9ae96e3c398d2285ca583f700e1d1428b163179 | [
"MIT"
] | null | null | null | src/absyn_tree.cpp | wangnangg/xml_exp | a9ae96e3c398d2285ca583f700e1d1428b163179 | [
"MIT"
] | null | null | null | src/absyn_tree.cpp | wangnangg/xml_exp | a9ae96e3c398d2285ca583f700e1d1428b163179 | [
"MIT"
] | null | null | null | #include "absyn_tree.hpp"
#include <cassert>
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
void link(exp* target, const func_env& env)
{
target->visit([&](exp* curr_exp) {
call_exp* calle = dynamic_cast<call_exp*>(curr_exp);
if (calle)
{
calle->link(env[calle->name()]);
}
});
}
size_t arg_index(const std::vector<std::string>& args, const std::string& name)
{
for (size_t i = 0; i < args.size(); i++)
{
if (args[i] == name)
{
return i;
}
}
throw undef_ref(name);
}
void alloc_var(const std::vector<std::string>& formal, exp* body)
{
body->visit([&](exp* curr_exp) {
var_exp* vare = dynamic_cast<var_exp*>(curr_exp);
if (vare)
{
vare->alloc(arg_index(formal, vare->name()));
}
});
}
func_env::func_env(func_map_t func_map) : _func_map(std::move(func_map))
{
for (auto& pair : _func_map)
{
link(pair.second, *this);
}
}
void func_env_crtor::add_func(std::string name,
const std::vector<std::string>& formal, exp* body)
{
body->visit([&](exp* curr_exp) {
var_exp* vare = dynamic_cast<var_exp*>(curr_exp);
if (vare)
{
vare->alloc(arg_index(formal, vare->name()));
}
});
_func_map[std::move(name)] = body;
}
func_env_crtor::operator func_env() const { return func_env(_func_map); }
| 23.822581 | 80 | 0.560596 | [
"vector"
] |
bb4f682d4cc6f006c40b3743803bd50da579fe44 | 1,895 | cpp | C++ | LinkedBlockLife/MenuScene.cpp | NeuroWhAI/LinkedBlockLife | 5fa969c96e3a218741835493b4c2d40519125dc4 | [
"MIT"
] | 3 | 2017-02-18T16:31:46.000Z | 2021-02-14T06:38:28.000Z | LinkedBlockLife/MenuScene.cpp | NeuroWhAI/LinkedBlockLife | 5fa969c96e3a218741835493b4c2d40519125dc4 | [
"MIT"
] | null | null | null | LinkedBlockLife/MenuScene.cpp | NeuroWhAI/LinkedBlockLife | 5fa969c96e3a218741835493b4c2d40519125dc4 | [
"MIT"
] | null | null | null | #include "MenuScene.h"
#include "MainScene.h"
#include "LabScene.h"
MenuScene::MenuScene()
{
}
MenuScene::~MenuScene()
{
}
//###########################################################################
void MenuScene::onInitialize(caDraw::Window& owner)
{
auto winSize = owner.getSize();
m_font = m_pool.createFont(L"DefaultFont");
m_font->loadFromFile("NanumGothic.ttf");
m_font->setCharacterSize(18);
m_panel = caFactory->createPanel();
m_panel->size = static_cast<caDraw::SizeF>(winSize);
m_panel->transform.position = { 0, 0 };
m_toMain = canew<caUI::Button>();
m_toMain->setFont(m_font);
m_toMain->setSize({ 256, 48 });
m_toMain->transform.position = { winSize.width / 2.0f - 128.0f, 256.0f };
m_toMain->setText("Main simulation");
m_toMain->WhenClick = [this](const caUI::TouchEventArgs& args)
{
this->reserveNextScene<MainScene>();
};
m_toLab = canew<caUI::Button>();
m_toLab->setFont(m_font);
m_toLab->setSize({ 256, 48 });
m_toLab->transform.position = { winSize.width / 2.0f - 128.0f, 256.0f + 64.0f };
m_toLab->setText("Lab");
m_toLab->WhenClick = [this](const caUI::TouchEventArgs& args)
{
this->reserveNextScene<LabScene>();
};
m_exit = canew<caUI::Button>();
m_exit->setFont(m_font);
m_exit->setSize({ 256, 48 });
m_exit->transform.position = { winSize.width / 2.0f - 128.0f, 256.0f + 64.0f * 2 };
m_exit->setText("Exit");
m_exit->WhenClick = [this](const caUI::TouchEventArgs& args)
{
this->reserveNextScene(nullptr);
};
m_panel->addControl(m_toMain);
m_panel->addControl(m_toLab);
m_panel->addControl(m_exit);
addPanel(m_panel);
}
void MenuScene::onRelease()
{
}
void MenuScene::onUpdate(caDraw::Window& owner)
{
if (caKeyboard->isKeyDown(caSys::Keys::Escape))
{
reserveNextScene(nullptr);
}
}
void MenuScene::onDrawBack(caDraw::Graphics& g)
{
}
void MenuScene::onDrawFront(caDraw::Graphics& g)
{
}
| 18.762376 | 84 | 0.656464 | [
"transform"
] |
bb59e61041bd16e90970e819abaf3b7690421c0b | 4,965 | cpp | C++ | solid/system/src/memory.cpp | vipalade/solidframe | cff130652127ca9607019b4db508bc67f8bbecff | [
"BSL-1.0"
] | 26 | 2015-08-25T16:07:58.000Z | 2019-07-05T15:21:22.000Z | solid/system/src/memory.cpp | vipalade/solidframe | cff130652127ca9607019b4db508bc67f8bbecff | [
"BSL-1.0"
] | 5 | 2016-10-15T22:55:15.000Z | 2017-09-19T12:41:10.000Z | solid/system/src/memory.cpp | vipalade/solidframe | cff130652127ca9607019b4db508bc67f8bbecff | [
"BSL-1.0"
] | 5 | 2016-09-15T10:34:52.000Z | 2018-10-30T11:46:46.000Z | // solid/system/src/memorycache.cpp
//
// Copyright (c) 2014 Valentin Palade (vipalade @ gmail . com)
//
// This file is part of SolidFrame framework.
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt.
//
#include "solid/system/memory.hpp"
#include <cstdlib>
#ifdef SOLID_ON_WINDOWS
#define NOMINMAX
#include <Windows.h>
#else
#include <unistd.h>
#endif
#ifdef SOLID_ON_LINUX
#include <malloc.h>
#endif
namespace {
size_t getMemorySize();
size_t getMemoryPageSize();
} //namespace
namespace solid {
size_t memory_page_size()
{
return getMemoryPageSize();
}
void* memory_allocate_aligned(size_t _align, size_t _size)
{
#ifdef SOLID_ON_WINDOWS
return nullptr;
#elif defined(SOLID_ON_DARWIN) || defined(SOLID_ON_FREEBSD)
void* retval = 0;
int rv = posix_memalign(&retval, _align, _size);
if (rv == 0) {
return retval;
} else {
return nullptr;
}
#else
return memalign(_align, _size);
#endif
}
void memory_free_aligned(void* _pv)
{
#ifdef SOLID_ON_WINDOWS
#else
free(_pv);
#endif
}
size_t memory_size()
{
return getMemorySize();
}
} //namespace solid
namespace {
/**
* Returns the size of physical memory (RAM) in bytes.
*/
size_t getMemoryPageSize()
{
#ifdef SOLID_ON_WINDOWS
SYSTEM_INFO siSysInfo;
GetSystemInfo(&siSysInfo);
return siSysInfo.dwPageSize;
#else
return static_cast<size_t>(sysconf(_SC_PAGESIZE));
#endif
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
/*
* Author: David Robert Nadeau
* Site: http://NadeauSoftware.com/
* License: Creative Commons Attribution 3.0 Unported License
* http://creativecommons.org/licenses/by/3.0/deed.en_US
*/
#if defined(_WIN32)
#elif defined(__unix__) || defined(__unix) || defined(unix) || (defined(__APPLE__) && defined(__MACH__))
#include <sys/param.h>
#include <sys/types.h>
#include <unistd.h>
#if defined(BSD)
#include <sys/sysctl.h>
#endif
#else
#error "Unable to define getMemorySize( ) for an unknown OS."
#endif
/**
* Returns the size of physical memory (RAM) in bytes.
*/
size_t getMemorySize()
{
#if defined(_WIN32) && (defined(__CYGWIN__) || defined(__CYGWIN32__))
/* Cygwin under Windows. ------------------------------------ */
/* New 64-bit MEMORYSTATUSEX isn't available. Use old 32.bit */
MEMORYSTATUS status;
status.dwLength = sizeof(status);
GlobalMemoryStatus(&status);
return (size_t)status.dwTotalPhys;
#elif defined(_WIN32)
/* Windows. ------------------------------------------------- */
/* Use new 64-bit MEMORYSTATUSEX, not old 32-bit MEMORYSTATUS */
MEMORYSTATUSEX status;
status.dwLength = sizeof(status);
GlobalMemoryStatusEx(&status);
return (size_t)status.ullTotalPhys;
#elif defined(__unix__) || defined(__unix) || defined(unix) || (defined(__APPLE__) && defined(__MACH__))
/* UNIX variants. ------------------------------------------- */
/* Prefer sysctl() over sysconf() except sysctl() HW_REALMEM and HW_PHYSMEM */
#if defined(CTL_HW) && (defined(HW_MEMSIZE) || defined(HW_PHYSMEM64))
int mib[2];
mib[0] = CTL_HW;
#if defined(HW_MEMSIZE)
mib[1] = HW_MEMSIZE; /* OSX. --------------------- */
#elif defined(HW_PHYSMEM64)
mib[1] = HW_PHYSMEM64; /* NetBSD, OpenBSD. --------- */
#endif
int64_t size = 0; /* 64-bit */
size_t len = sizeof(size);
if (sysctl(mib, 2, &size, &len, nullptr, 0) == 0)
return (size_t)size;
return 0L; /* Failed? */
#elif defined(_SC_AIX_REALMEM)
/* AIX. ----------------------------------------------------- */
return (size_t)sysconf(_SC_AIX_REALMEM) * (size_t)1024L;
#elif defined(_SC_PHYS_PAGES) && defined(_SC_PAGESIZE)
/* FreeBSD, Linux, OpenBSD, and Solaris. -------------------- */
return static_cast<size_t>(sysconf(_SC_PHYS_PAGES)) * static_cast<size_t>(sysconf(_SC_PAGESIZE));
#elif defined(_SC_PHYS_PAGES) && defined(_SC_PAGE_SIZE)
/* Legacy. -------------------------------------------------- */
return (size_t)sysconf(_SC_PHYS_PAGES) * (size_t)sysconf(_SC_PAGE_SIZE);
#elif defined(CTL_HW) && (defined(HW_PHYSMEM) || defined(HW_REALMEM))
/* DragonFly BSD, FreeBSD, NetBSD, OpenBSD, and OSX. -------- */
int mib[2];
mib[0] = CTL_HW;
#if defined(HW_REALMEM)
mib[1] = HW_REALMEM; /* FreeBSD. ----------------- */
#elif defined(HW_PYSMEM)
mib[1] = HW_PHYSMEM; /* Others. ------------------ */
#endif
unsigned int size = 0; /* 32-bit */
size_t len = sizeof(size);
if (sysctl(mib, 2, &size, &len, nullptr, 0) == 0)
return (size_t)size;
return 0L; /* Failed? */
#endif /* sysctl and sysconf variants */
#else
return 0L; /* Unknown OS. */
#endif
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
} //namespace
| 27.73743 | 104 | 0.598389 | [
"solid"
] |
bb5b9990c3ba52ac9cddd94960c4436dc89a52bb | 11,859 | cpp | C++ | Test/Space/ModelTest.cpp | Cultrarius/QuestWeaver | 311016e3ec67c74221ef20d4eeff8904d8222135 | [
"Unlicense"
] | 57 | 2016-02-11T09:07:31.000Z | 2022-03-04T02:57:50.000Z | Test/Space/ModelTest.cpp | Cultrarius/QuestWeaver | 311016e3ec67c74221ef20d4eeff8904d8222135 | [
"Unlicense"
] | 1 | 2016-08-27T20:52:31.000Z | 2016-11-28T14:58:24.000Z | Test/Space/ModelTest.cpp | Cultrarius/QuestWeaver | 311016e3ec67c74221ef20d4eeff8904d8222135 | [
"Unlicense"
] | 10 | 2016-08-27T20:06:42.000Z | 2022-02-08T06:13:50.000Z | //
// Created by michael on 27.10.15.
//
#include <World/Space/SpaceWorldModel.h>
#include <World/Space/DeadCivilization.h>
#include <World/Space/Artifact.h>
#include <World/Space/SpaceStation.h>
#include <World/Space/SpaceWreck.h>
#include <World/Space/SpaceShip.h>
#include "../catch.hpp"
#include "../Mock/TestWorldListener.h"
using namespace weave;
using namespace std;
TEST_CASE("Model Actions", "[model]") {
shared_ptr<RandomStream> rs = make_shared<RandomStream>(43);
shared_ptr<TestWorldListener> listener = make_shared<TestWorldListener>();
SpaceWorldModel testModel(rs);
testModel.AddListener(listener);
shared_ptr<WorldEntity> entity = testModel.CreateLocation().GetEntity();
REQUIRE(entity->GetId() == 0);
SECTION("Unknown entity") {
vector<WorldModelAction> actions;
WorldModelAction action(WorldActionType::UPDATE, entity);
actions.push_back(action);
REQUIRE_THROWS_AS(testModel.Execute(actions), ContractFailedException);
}
SECTION("Unknown action type") {
vector<WorldModelAction> actions;
actions.push_back(WorldModelAction(WorldActionType::CREATE, entity));
actions.push_back(WorldModelAction((WorldActionType) 100, entity));
REQUIRE_THROWS_AS(testModel.Execute(actions), ContractFailedException);
}
SECTION("Empty list of actions") {
vector<WorldModelAction> noActions;
testModel.Execute(noActions);
REQUIRE(testModel.GetEntities().size() == 0);
SECTION("Empty listener") {
REQUIRE(listener->calledActions.size() == 0);
}
}
SECTION("CREATE model action") {
vector<WorldModelAction> actions;
WorldModelAction action(WorldActionType::CREATE, entity);
actions.push_back(action);
testModel.Execute(actions);
REQUIRE(testModel.GetEntities().size() == 1);
REQUIRE(entity->GetId() != 0);
SECTION("Single listener action") {
REQUIRE(listener->calledActions.size() == 1);
}
}
SECTION("CREATE twice action") {
vector<WorldModelAction> actions;
WorldModelAction action(WorldActionType::CREATE, entity);
actions.push_back(action);
testModel.Execute(actions);
REQUIRE_THROWS_AS(testModel.Execute(actions), ContractFailedException);
}
SECTION("KEEP known entity") {
vector<WorldModelAction> actions;
WorldModelAction action(WorldActionType::CREATE, entity);
actions.push_back(action);
testModel.Execute(actions);
actions[0] = WorldModelAction(WorldActionType::KEEP, entity);
testModel.Execute(actions);
}
SECTION("KEEP unknown entity without id") {
vector<WorldModelAction> actions;
WorldModelAction action(WorldActionType::KEEP, entity);
actions.push_back(action);
REQUIRE_THROWS_AS(testModel.Execute(actions), ContractFailedException);
}
SECTION("UPDATE unknown entity") {
vector<WorldModelAction> actions;
WorldModelAction action(WorldActionType::UPDATE, entity);
actions.push_back(action);
REQUIRE_THROWS_AS(testModel.Execute(actions), ContractFailedException);
}
SECTION("UPDATE unknown entity with id") {
vector<WorldModelAction> actions;
WorldModelAction action(WorldActionType::CREATE, entity);
actions.push_back(action);
testModel.Execute(actions);
actions[0] = WorldModelAction(WorldActionType::UPDATE, entity);
SpaceWorldModel otherModel(rs);
REQUIRE_THROWS_AS(otherModel.Execute(actions), ContractFailedException);
}
SECTION("create and keep entity") {
vector<WorldModelAction> actions;
WorldModelAction action(WorldActionType::CREATE, entity);
actions.push_back(action);
testModel.Execute(actions);
actions[0] = WorldModelAction(WorldActionType::KEEP, entity);
testModel.Execute(actions);
REQUIRE(testModel.GetEntities().size() == 1);
REQUIRE(entity->GetId() != 0);
}
SECTION("create and delete entity") {
vector<WorldModelAction> actions;
WorldModelAction action(WorldActionType::CREATE, entity);
actions.push_back(action);
testModel.Execute(actions);
actions[0] = WorldModelAction(WorldActionType::DELETE, entity);
testModel.Execute(actions);
REQUIRE(testModel.GetEntities().size() == 0);
REQUIRE(entity->GetId() == 0);
SECTION("Two listener actions") {
REQUIRE(listener->calledActions.size() == 2);
REQUIRE(listener->calledActions[0].GetActionType() == WorldActionType::CREATE);
REQUIRE(listener->calledActions[1].GetActionType() == WorldActionType::DELETE);
}
}
}
TEST_CASE("Metadata", "[model]") {
shared_ptr<RandomStream> rs = make_shared<RandomStream>(44);
SpaceWorldModel testModel(rs);
shared_ptr<WorldEntity> entity = testModel.CreateAgent().GetEntity();
vector<WorldModelAction> actions;
WorldModelAction action(WorldActionType::CREATE, entity);
actions.push_back(action);
testModel.Execute(actions);
SECTION("Empty metadata test") {
MetaData metaData;
REQUIRE(metaData.GetValueNames().size() == 0);
REQUIRE(metaData.GetValue("Test123") == 0);
REQUIRE(!metaData.HasValue("Test123"));
}
SECTION("Metadata set and get test") {
MetaData metaData;
metaData.SetValue("Test123", 42);
metaData.SetValue("Test456", 43);
REQUIRE(metaData.GetValueNames().size() == 2);
REQUIRE(metaData.HasValue("Test123"));
REQUIRE(metaData.HasValue("Test456"));
REQUIRE(metaData.GetValue("Test123") == 42);
REQUIRE(metaData.GetValue("Test456") == 43);
}
SECTION("Empty model metadata") {
SpaceWorldModel emptyModel(rs);
REQUIRE(emptyModel.GetMetaData(2).GetValueNames().size() == 0);
}
SECTION("Empty Metadata") {
MetaData metadata = testModel.GetMetaData(entity->GetId());
REQUIRE(metadata.GetValueNames().size() == 0);
}
SECTION("Get does not create metadata") {
MetaData metadata = testModel.GetMetaData(entity->GetId());
REQUIRE(!metadata.HasValue("Test123"));
metadata.GetValue("Test123");
REQUIRE(!metadata.HasValue("Test123"));
}
SECTION("Edit metadata immutability") {
MetaData metadata = testModel.GetMetaData(entity->GetId());
REQUIRE(!metadata.HasValue("Test123"));
metadata.SetValue("Test123", 137);
REQUIRE(metadata.HasValue("Test123"));
REQUIRE(!testModel.GetMetaData(entity->GetId()).HasValue("Test123"));
}
SECTION("Create metadata entry") {
SpaceWorldModel metaDataModel(rs);
shared_ptr<WorldEntity> metaEntity = testModel.CreateLocation().GetEntity();
MetaData metaData;
metaData.SetValue("Test123", 142);
actions[0] = WorldModelAction(WorldActionType::CREATE, metaEntity, metaData);
metaDataModel.Execute(actions);
MetaData modelData = metaDataModel.GetMetaData(metaEntity->GetId());
REQUIRE(modelData.HasValue("Test123"));
REQUIRE(modelData.GetValue("Test123") == 142);
}
SECTION("delete entity with metadata") {
SpaceWorldModel metaDataModel(rs);
shared_ptr<WorldEntity> metaEntity = testModel.CreateLocation().GetEntity();
MetaData metaData;
metaData.SetValue("Test123", 142);
actions[0] = WorldModelAction(WorldActionType::CREATE, metaEntity, metaData);
metaDataModel.Execute(actions);
ID id = metaEntity->GetId();
REQUIRE(metaDataModel.GetMetaData(id).HasValue("Test123"));
actions[0] = WorldModelAction(WorldActionType::DELETE, metaEntity);
metaDataModel.Execute(actions);
REQUIRE(!metaDataModel.GetEntityById(id));
REQUIRE(metaDataModel.GetMetaData(id).HasValue("Test123"));
}
SECTION("update entity with metadata") {
SpaceWorldModel metaDataModel(rs);
shared_ptr<WorldEntity> metaEntity = testModel.CreateLocation().GetEntity();
MetaData metaData;
metaData.SetValue("Test123", 142);
actions[0] = WorldModelAction(WorldActionType::CREATE, metaEntity, metaData);
metaDataModel.Execute(actions);
ID id = metaEntity->GetId();
REQUIRE(metaDataModel.GetMetaData(id).GetValue("Test123") == 142);
metaData.SetValue("Test123", 191);
actions[0] = WorldModelAction(WorldActionType::UPDATE, metaEntity, metaData);
metaDataModel.Execute(actions);
REQUIRE(metaDataModel.GetMetaData(id).GetValue("Test123") == 191);
}
SECTION("update metadata key addition") {
SpaceWorldModel metaDataModel(rs);
shared_ptr<WorldEntity> metaEntity = testModel.CreateLocation().GetEntity();
MetaData metaData;
metaData.SetValue("Test123", 142);
actions[0] = WorldModelAction(WorldActionType::CREATE, metaEntity, metaData);
metaDataModel.Execute(actions);
ID id = metaEntity->GetId();
REQUIRE(!metaDataModel.GetMetaData(id).HasValue("Test456"));
metaData.SetValue("Test456", 191);
actions[0] = WorldModelAction(WorldActionType::UPDATE, metaEntity, metaData);
metaDataModel.Execute(actions);
REQUIRE(metaDataModel.GetMetaData(id).GetValue("Test123") == 142);
REQUIRE(metaDataModel.GetMetaData(id).GetValue("Test456") == 191);
}
SECTION("empty update must not delete keys") {
SpaceWorldModel metaDataModel(rs);
shared_ptr<WorldEntity> metaEntity = testModel.CreateLocation().GetEntity();
MetaData metaData;
metaData.SetValue("Test123", 142);
actions[0] = WorldModelAction(WorldActionType::CREATE, metaEntity, metaData);
metaDataModel.Execute(actions);
ID id = metaEntity->GetId();
REQUIRE(metaDataModel.GetMetaData(id).GetValue("Test123") == 142);
actions[0] = WorldModelAction(WorldActionType::UPDATE, metaEntity, MetaData());
metaDataModel.Execute(actions);
REQUIRE(metaDataModel.GetMetaData(id).GetValue("Test123") == 142);
}
}
int getTypeCount(vector<WorldModelAction> actions, string type) {
int count = 0;
for (auto action : actions) {
if (action.GetActionType() == WorldActionType::CREATE && action.GetEntity()->GetType() == type) {
count++;
}
}
return count;
}
TEST_CASE("Init world", "[model]") {
shared_ptr<RandomStream> rs = make_shared<RandomStream>(44);
SpaceWorldModel model(rs);
SECTION("Check required entities") {
vector<WorldModelAction> actions = model.InitializeNewWorld();
REQUIRE(actions.size() > 0);
REQUIRE(getTypeCount(actions, SolarSystem::Type) > 0);
REQUIRE(getTypeCount(actions, Planet::Type) > 0);
REQUIRE(getTypeCount(actions, DeadCivilization::Type) > 0);
REQUIRE(getTypeCount(actions, SpaceAgent::Type) > 0);
REQUIRE(getTypeCount(actions, Artifact::Type) > 0);
REQUIRE(getTypeCount(actions, SpaceStation::Type) > 0);
REQUIRE(getTypeCount(actions, SpaceWreck::Type) > 0);
REQUIRE(getTypeCount(actions, SpaceShip::Type) > 0);
}
SECTION("Each agent has at least one ship") {
vector<WorldModelAction> actions = model.InitializeNewWorld();
REQUIRE(actions.size() > 0);
int agents = getTypeCount(actions, SpaceAgent::Type);
set<shared_ptr<SpaceAgent>> owners;
for (auto action : actions) {
if (action.GetEntity()->GetType() == SpaceShip::Type) {
auto ship = dynamic_pointer_cast<SpaceShip>(action.GetEntity());
owners.insert(ship->Owner);
}
}
REQUIRE(agents == owners.size());
}
}
| 39.795302 | 105 | 0.662029 | [
"vector",
"model"
] |
bb63c57ece96d1b87b0c93ca38aad06656803383 | 9,531 | cpp | C++ | src/web/pubchem.cpp | quizzmaster/chemkit | 803e4688b514008c605cb5c7790f7b36e67b68fc | [
"BSD-3-Clause"
] | 34 | 2015-01-24T23:59:41.000Z | 2020-11-12T13:48:01.000Z | src/web/pubchem.cpp | soplwang/chemkit | d62b7912f2d724a05fa8be757f383776fdd5bbcb | [
"BSD-3-Clause"
] | 4 | 2015-12-28T20:29:16.000Z | 2016-01-26T06:48:19.000Z | src/web/pubchem.cpp | soplwang/chemkit | d62b7912f2d724a05fa8be757f383776fdd5bbcb | [
"BSD-3-Clause"
] | 17 | 2015-01-23T14:50:24.000Z | 2021-06-10T15:43:50.000Z | /******************************************************************************
**
** Copyright (C) 2009-2011 Kyle Lutz <kyle.r.lutz@gmail.com>
** All rights reserved.
**
** This file is a part of the chemkit project. For more information
** see <http://www.chemkit.org>.
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions
** are met:
**
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in the
** documentation and/or other materials provided with the distribution.
** * Neither the name of the chemkit project nor the names of its
** contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
******************************************************************************/
#include "pubchem.h"
#include <QtXml>
#include <QtNetwork>
#include "pubchemquery.h"
#include "downloadthread.h"
#include "pubchemquerythread.h"
#include <chemkit/molecule.h>
#include <chemkit/moleculefile.h>
namespace chemkit {
// === PubChemPrivate ====================================================== //
class PubChemPrivate
{
public:
QUrl url;
QString errorString;
};
// === PubChem ============================================================= //
/// \class PubChem pubchem.h chemkit/pubchem.h
/// \ingroup chemkit-web
/// \brief The PubChem class provides access to the %PubChem web
/// API.
// --- Construction and Destruction ---------------------------------------- //
/// Creates a new PubChem object.
PubChem::PubChem()
: d(new PubChemPrivate)
{
d->url = QUrl("http://pubchem.ncbi.nlm.nih.gov/");
}
/// Destroys the PubChem object.
PubChem::~PubChem()
{
delete d;
}
// --- Properties ---------------------------------------------------------- //
/// Sets the url to \p url.
void PubChem::setUrl(const QUrl &url)
{
d->url = url;
}
/// Returns the url.
QUrl PubChem::url() const
{
return d->url;
}
// --- Downloads ----------------------------------------------------------- //
/// Downloads and returns the molecule with the compound ID \p id.
/// If an error occurs a null pointer is returned.
boost::shared_ptr<Molecule> PubChem::downloadMolecule(const QString &id) const
{
QScopedPointer<MoleculeFile> file(downloadFile(id));
if(!file){
return boost::shared_ptr<Molecule>();
}
return file->molecule();
}
/// Downloads and returns the file with the compound ID \p id. If an
/// error occurs \c 0 is returned.
///
/// The ownership of the returned file is passed to the caller.
MoleculeFile* PubChem::downloadFile(const QString &id) const
{
QByteArray data = downloadFileData(id, "sdf");
if(data.isEmpty()){
return 0;
}
std::stringstream buffer(std::string(data.constData(), data.size()));
MoleculeFile *file = new MoleculeFile;
file->read(buffer, "sdf");
return file;
}
/// Downloads and returns the file containing the compounds with ID's
/// in the list \p ids. If an error occurs \c 0 is returned.
///
/// The ownership of the file is passed to the caller.
///
/// For example, to download the file containing %PubChem Compounds
/// 1, 2, 3, 42 and 57:
/// \code
/// QStringList ids;
/// ids << "1" << "2" << "3" << "42" << "57";
/// MoleculeFile *file = pubchem.downloadFile(ids);
/// \endcode
MoleculeFile* PubChem::downloadFile(const QStringList &ids) const
{
QByteArray data = downloadFileData(ids, "sdf");
if(data.isEmpty()){
return 0;
}
std::stringstream buffer(std::string(data.constData(), data.size()));
MoleculeFile *file = new MoleculeFile;
file->read(buffer, "sdf");
return file;
}
/// Downloads and returns the file data for the compound with ID
/// \p id. If an error occurs an empty QByteArray is returned.
QByteArray PubChem::downloadFileData(const QString &id, const QString &format) const
{
Q_UNUSED(format);
QUrl url(QString("%1summary/summary.cgi?cid=%2&disopt=3DDisplaySDF").arg(d->url.toString())
.arg(id));
return DownloadThread::download(url);
}
/// Downloads and returns the file data for the compounds with ID's
/// in the list \p ids. If an error occurs an empty QByteArray is
/// returned.
QByteArray PubChem::downloadFileData(const QStringList &ids, const QString &format) const
{
PubChemQuery query = PubChemQuery::downloadQuery(ids, format);
PubChemQueryThread thread(query);
thread.start();
thread.wait();
// the response contains a URL where the file can be downloaded
QByteArray response = thread.response();
QDomDocument document;
document.setContent(response, false);
QDomNodeList nodes = document.elementsByTagName("PCT-Download-URL_url");
if(nodes.isEmpty()){
return QByteArray();
}
QDomNode node = nodes.at(0);
QDomElement element = node.toElement();
QString url = element.text();
return DownloadThread::download(QUrl(url));
}
// --- Search -------------------------------------------------------------- //
/// Searches the %PubChem database for \p query and returns a list
/// of matching compound IDs. The returned list of ids can be passed
/// to PubChem::downloadFile() to download the molecules.
QStringList PubChem::search(const QString &query) const
{
QString url = "http://www.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pccompound&term=%1";
QByteArray response = DownloadThread::download(QUrl(url.arg(query)));
QDomDocument document;
document.setContent(response, false);
QDomNodeList nodes = document.elementsByTagName("Id");
QStringList ids;
for(int i = 0; i < nodes.size(); i++){
QDomNode node = nodes.item(i);
QDomElement element = node.toElement();
ids.append(element.text());
}
return ids;
}
// --- Standardization ----------------------------------------------------- //
/// Returns a string containing the standardized version of
/// \p formula in \p format. If an error occurs an empty string is
/// returned.
///
/// For example, to standardize a SMILES formula:
/// \code
/// std::string formula = pubchem.standardizeFormula("c3cccc3", "smiles");
/// \endcode
std::string PubChem::standardizeFormula(const std::string &formula, const std::string &format) const
{
return standardizeFormula(formula, format, format);
}
/// Returns a string containing the standardized version of
/// \p formula from \p inputFormat in \p outputFormat. If an error
/// occurs an empty string is returned.
///
/// For example, to convert an InChI string to standardized SMILES:
/// \code
/// std::string formula = pubchem.standardizeFormula("InChI=1/C6H6/c1-2-4-6-5-3-1/h1-6H", "inchi", "smiles");
/// \endcode
std::string PubChem::standardizeFormula(const std::string &formula, const std::string &inputFormat, const std::string &outputFormat) const
{
if(formula.empty()){
return std::string();
}
PubChemQuery query = PubChemQuery::standardizationQuery(formula, inputFormat, outputFormat);
PubChemQueryThread thread(query);
thread.start();
thread.wait();
QByteArray response = thread.response();
QDomDocument document;
document.setContent(response, false);
QDomNodeList nodes = document.elementsByTagName("PCT-Structure_structure_string");
if(nodes.isEmpty()){
return std::string();
}
QDomNode node = nodes.at(0);
QDomElement element = node.toElement();
QByteArray elementText = element.text().toAscii();
std::string standardizedFormula = elementText.constData();
return standardizedFormula;
}
/// Returns a string containing the standardized formula in \p format
/// for the \p molecule. If an error occurs an empty string is
/// returned.
///
/// For example, to get the standardized InChI formula for a
/// molecule:
/// \code
/// std::string formula = pubchem.standardizeFormula(molecule, "inchi");
/// \endcode
std::string PubChem::standardizeFormula(const Molecule *molecule, const std::string &format) const
{
return standardizeFormula(molecule->formula("smiles"), "smiles", format);
}
// --- Error Handling ------------------------------------------------------ //
void PubChem::setErrorString(const QString &error)
{
d->errorString = error;
}
/// Returns a string describing the last error that occurred.
QString PubChem::errorString() const
{
return d->errorString;
}
} // end chemkit namespace
| 32.199324 | 138 | 0.650089 | [
"object"
] |
bb649915ffc251ab99d95503192b266be030ec47 | 785 | hpp | C++ | libs/core/include/fcppt/variant/types_string.hpp | pmiddend/fcppt | 9f437acbb10258e6df6982a550213a05815eb2be | [
"BSL-1.0"
] | null | null | null | libs/core/include/fcppt/variant/types_string.hpp | pmiddend/fcppt | 9f437acbb10258e6df6982a550213a05815eb2be | [
"BSL-1.0"
] | null | null | null | libs/core/include/fcppt/variant/types_string.hpp | pmiddend/fcppt | 9f437acbb10258e6df6982a550213a05815eb2be | [
"BSL-1.0"
] | null | null | null | // Copyright Carl Philipp Reh 2009 - 2018.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef FCPPT_VARIANT_TYPES_STRING_HPP_INCLUDED
#define FCPPT_VARIANT_TYPES_STRING_HPP_INCLUDED
#include <fcppt/string.hpp>
#include <fcppt/metal/sequence_to_string.hpp>
#include <fcppt/variant/types_of.hpp>
namespace fcppt
{
namespace variant
{
/**
\brief Returns the types of a variant as a string
\ingroup fcpptvariant
\tparam Variant Must be an #fcppt::variant::object.
*/
template<
typename Variant
>
inline
fcppt::string
types_string()
{
return
fcppt::metal::sequence_to_string<
fcppt::variant::types_of<
Variant
>
>();
}
}
}
#endif
| 17.065217 | 61 | 0.729936 | [
"object"
] |
bb65a7a4bc76a82d90d4c28424652067204813e6 | 7,994 | cpp | C++ | src/scriptinterface/tcGroupInterface.cpp | dhanin/friendly-bassoon | fafcfd3921805baddc1889dc0ee2fa367ad882f8 | [
"BSD-3-Clause"
] | 2 | 2021-11-17T10:59:38.000Z | 2021-11-17T10:59:45.000Z | src/scriptinterface/tcGroupInterface.cpp | dhanin/nws | 87a3f24a7887d84b9884635064b48d456b4184e2 | [
"BSD-3-Clause"
] | null | null | null | src/scriptinterface/tcGroupInterface.cpp | dhanin/nws | 87a3f24a7887d84b9884635064b48d456b4184e2 | [
"BSD-3-Clause"
] | null | null | null | /**
** @file tcGroupInterface.cpp
*/
/*
** Copyright (c) 2014, GCBLUE PROJECT
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
**
** 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
**
** 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
** documentation and/or other materials provided with the distribution.
**
** 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from
** this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
** NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
** COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
** HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
** IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "stdwx.h" // precompiled header file
#ifndef WX_PRECOMP
#include "wx/wx.h"
#ifdef WIN32
#include "wx/msw/private.h" // for MS Windows specific definitions
#endif // WIN32
#endif
#include "tcGroupInterface.h"
#include "tcPlatformInterface.h"
#include "tcWeaponInterface.h"
#include "tcSimState.h"
#include "network/tcMultiplayerInterface.h"
#include "tcCommandQueue.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
namespace scriptinterface
{
tcSimState* tcGroupInterface::simState = NULL;
tcCommandQueue* tcGroupInterface::mpCommandQueue = 0;
tcScenarioInterface* tcGroupInterface::scenarioInterface = 0;
/**
* @return tcPlatformInterface object for group member <idx>
*/
tcPlatformInterface tcGroupInterface::GetPlatformInterface(int idx)
{
long id = GetUnitId(idx);
tcGameObject* gameObj = simState->GetObject(id);
if (tcPlatformObject* platformObj = dynamic_cast<tcPlatformObject*>(gameObj))
{
return tcPlatformInterface(platformObj);
}
else
{
fprintf(stderr, "tcGroupInterface::GetPlatformInterface - "
"returned NULL or non-platform obj\n");
return tcPlatformInterface();
}
}
/**
* @return tcWeaponInterface object for group member <idx>
*/
tcWeaponInterface tcGroupInterface::GetWeaponInterface(int idx)
{
long id = GetUnitId(idx);
tcGameObject* gameObj = simState->GetObject(id);
if (tcWeaponObject* weaponObj = dynamic_cast<tcWeaponObject*>(gameObj))
{
return tcWeaponInterface(weaponObj);
}
else
{
fprintf(stderr, "tcGroupInterface::GetWeaponInterface - "
"returned NULL or non-weapon obj\n");
return tcWeaponInterface();
}
}
tcScenarioInterface tcGroupInterface::GetScenarioInterface()
{
if (tcGameObject::IsEditMode())
{
return *scenarioInterface;
}
else
{
wxMessageBox("Access to ScenarioInterface blocked not allowed game play. Corrupt script file?", "Warning");
return *scenarioInterface;
}
}
tcStringArray tcGroupInterface::GetTankerList()
{
tcStringArray result;
for (size_t n=0; n<groupUnits.size(); n++)
{
long id_n = groupUnits[n];
tcAirObject* air = dynamic_cast<tcAirObject*>(simState->GetObject(id_n));
if ((air != 0) && (air->IsTanker()))
{
result.AddString(air->mzUnit.c_str());
}
}
return result;
}
/**
*
*/
int tcGroupInterface::GetUnitCount()
{
return (int)groupUnits.size();
}
/**
*
*/
long tcGroupInterface::GetUnitId(int idx) const
{
if ((size_t)idx >= groupUnits.size())
{
return -1;
}
else
{
return groupUnits[idx];
}
}
bool tcGroupInterface::IsPlatform(int idx) const
{
long id = GetUnitId(idx);
const tcGameObject* gameObj = simState->GetObject(id);
const tcPlatformObject* platformObj = dynamic_cast<const tcPlatformObject*>(gameObj);
return (platformObj != 0);
}
bool tcGroupInterface::IsWeapon(int idx) const
{
long id = GetUnitId(idx);
const tcGameObject* gameObj = simState->GetObject(id);
const tcWeaponObject* weaponObj = dynamic_cast<const tcWeaponObject*>(gameObj);
return (weaponObj != 0);
}
/**
*
*/
std::vector<long>& tcGroupInterface::GetUnits()
{
return groupUnits;
}
/**
* Request user input. Python callback function is called after input is
* obtained
*/
void tcGroupInterface::GetUserInput(std::string callback, std::string uitype)
{
if (mpCommandQueue == 0) return;
mpCommandQueue->GetUserInput(callback.c_str(), uitype.c_str(), -1, "");
}
long tcGroupInterface::LookupUnit(const std::string& name)
{
for (size_t n=0; n<groupUnits.size(); n++)
{
long id_n = groupUnits[n];
tcGameObject* gameObj = simState->GetObject(id_n);
if ((gameObj != 0) && (name == gameObj->mzUnit.c_str()))
{
return id_n;
}
}
return -1;
}
int tcGroupInterface::LookupUnitIdx(const std::string& name)
{
for (size_t n=0; n<groupUnits.size(); n++)
{
long id_n = groupUnits[n];
tcGameObject* gameObj = simState->GetObject(id_n);
if ((gameObj != 0) && (name == gameObj->mzUnit.c_str()))
{
return int(n);
}
}
return -1;
}
/**
* Call to remove destroyed unit from group selection
*/
void tcGroupInterface::RemoveUnit(long unit)
{
std::vector<long> remainingUnits;
for (size_t n=0; n<groupUnits.size(); n++)
{
if (groupUnits[n] != unit) remainingUnits.push_back(groupUnits[n]);
}
groupUnits = remainingUnits;
}
/**
*
*/
void tcGroupInterface::SetUnit(long unit)
{
groupUnits.clear();
groupUnits.push_back(unit);
}
/**
*
*/
void tcGroupInterface::SetUnits(const std::vector<long>& units)
{
groupUnits = units;
}
void tcGroupInterface::ReleaseControl()
{
if (groupUnits.size() == 0) return;
using network::tcMultiplayerInterface;
std::vector<long> controlledIds;
for (size_t k=0; k<groupUnits.size(); k++)
{
tcGameObject* gameObj = simState->GetObject(groupUnits[k]);
if ((gameObj != 0) && (gameObj->IsControlled()))
{
controlledIds.push_back(groupUnits[k]);
}
}
tcMultiplayerInterface::Get()->SendControlRelease(controlledIds);
}
void tcGroupInterface::TakeControl()
{
if (groupUnits.size() == 0) return;
using network::tcMultiplayerInterface;
std::vector<long> availableIds;
for (size_t k=0; k<groupUnits.size(); k++)
{
tcGameObject* gameObj = simState->GetObject(groupUnits[k]);
if ((gameObj != 0) && (gameObj->IsAvailable()))
{
availableIds.push_back(groupUnits[k]);
}
}
tcMultiplayerInterface::Get()->SendControlRequest(availableIds);
}
/**
*
*/
tcGroupInterface::tcGroupInterface()
{
if (!simState)
{
simState = tcSimState::Get();
}
groupUnits.clear();
}
tcGroupInterface::~tcGroupInterface()
{
}
}
| 26.382838 | 146 | 0.637978 | [
"object",
"vector"
] |
bb6be60adfdc2f18d64105d1feac39d98c686688 | 9,072 | cpp | C++ | network_core/src/Network.cpp | dymons/network | d54808f3ccfc600fde9f6ef8f2718f2e40c7f9b3 | [
"BSD-3-Clause"
] | null | null | null | network_core/src/Network.cpp | dymons/network | d54808f3ccfc600fde9f6ef8f2718f2e40c7f9b3 | [
"BSD-3-Clause"
] | null | null | null | network_core/src/Network.cpp | dymons/network | d54808f3ccfc600fde9f6ef8f2718f2e40c7f9b3 | [
"BSD-3-Clause"
] | null | null | null | #include "network_core/Network.hpp"
namespace network {
Network::Network(const InputLayer& t_input, const HiddenLayer& t_hidden, const OutputLayer& t_output)
: m_input_layer_(t_input), m_hidden_layer_(t_hidden), m_output_layer_(t_output)
{
// Check for a specific combination Network. If not satisfied, the network will not work correctly.
assert( is_single_layer<decltype(m_input_layer_)>::value);
assert(!is_single_layer<decltype(m_hidden_layer_)>::value);
assert( is_single_layer<decltype(m_output_layer_)>::value);
// Check initialize layers.
if(!m_input_layer_.m_layers || !m_hidden_layer_.m_layers || !m_output_layer_.m_layers) {
throw NotInitializeError("Not initialize layers in Network.");
}
// Create link between back hidden layer and output layer.
if(auto layer_output_ptr_ = std::get_if<OutputLayer::PrimitiveTPtr>(&(*m_output_layer_.m_layers))) {
if(auto layers_hidden_ptr_ = std::get_if<HiddenLayer::LayerImpl>(&(*m_hidden_layer_.m_layers))) {
if(!layer_output_ptr_->get() || layers_hidden_ptr_->empty()) {
throw NotInitializeError("Not initialize output or hidden layer.");
}
(*layer_output_ptr_)->connect(layers_hidden_ptr_->back());
}
}
// Create links between hidden layers.
if(auto layers_hidden_ptr_ = std::get_if<HiddenLayer::LayerImpl>(&(*m_hidden_layer_.m_layers))) {
if(layers_hidden_ptr_->empty() ) {
throw NotInitializeError("Not initialize hidden layer.");
}
const std::size_t size_hidden_layers_ = layers_hidden_ptr_->size() - 1;
for(std::size_t i = 0; i < size_hidden_layers_; ++i) {
layers_hidden_ptr_->at(i+1)->connect(layers_hidden_ptr_->at(i));
}
}
// Create link between input layer and front hidden layer.
if(auto layer_input_ptr_ = std::get_if<InputLayer::PrimitiveTPtr>(&(*m_input_layer_.m_layers))) {
if(auto layers_hidden_ptr_ = std::get_if<HiddenLayer::LayerImpl>(&(*m_hidden_layer_.m_layers))) {
if(!layer_input_ptr_->get() || layers_hidden_ptr_->empty()) {
throw NotInitializeError("Not initialize input or hidden layer.");
}
layers_hidden_ptr_->front()->connect(*layer_input_ptr_);
}
}
}
void Network::setDataset(const std::string& t_dataset) noexcept
{
m_dataset = t_dataset;
}
void Network::setCategorys(const std::vector<std::string>& t_categorys) noexcept
{
m_categorys.clear();
m_categorys.resize(t_categorys.size());
std::copy(t_categorys.begin(), t_categorys.end(), m_categorys.begin());
}
std::vector<std::string> Network::getCategorys() noexcept
{
return m_categorys;
}
void Network::setEpoch(const std::size_t& t_epoch) noexcept
{
m_epoch.emplace(t_epoch);
}
bool Network::education()
{
bool status { true };
if(m_dataset.empty()) {
throw FolderNotFoundError("Could not find dataset folder " + m_dataset);
return (status = false);
}
if(!fs::exists(fs::path(m_dataset))) {
throw FolderNotFoundError("Could not find dataset folder " + m_dataset);
return (status = false);
}
if(!m_epoch || m_categorys.empty()) {
throw NotInitializeError("Network isn't initialize.");
return (status = false);
}
auto buffer = std::make_unique<std::unordered_map<std::string, std::vector<std::string>>>();
// Save image paths to buffer.
for (fs::recursive_directory_iterator it(m_dataset), end; it != end; ++it) {
// Folder is a category.
if(!boost::filesystem::is_regular_file(it->path())) {
// Check that it is among our filters.
auto exist_category_ = std::find_if(m_categorys.begin(), m_categorys.end(),
[folder = it->path().filename().string()](auto& e){return e == folder;}) != m_categorys.end();
if(exist_category_) {
buffer->emplace(it->path().filename().string(), std::vector<std::string>());
}
continue;
} else {
// So the file is checked for contents in the directory.
auto exist_category_ = std::find_if(m_categorys.begin(), m_categorys.end(),
[folder = it->path().parent_path().filename().string()](auto& e){return e == folder;}) != m_categorys.end();
if(!exist_category_) {
continue;
}
}
// Check that the transferred file matches the formats being processed.
const auto exist_extension_ = std::find_if(m_format.begin(), m_format.end(),
[ex = it->path().extension()](auto e){return e == ex;}) != m_format.end();
if (exist_extension_) {
// TODO: Check for the desired image size.
buffer->at(it->path().parent_path().filename().string()).push_back(it->path().filename().string());
}
}
// Get pointers on layers
auto layer_input_ptr_ = std::get_if<InputLayer::PrimitiveTPtr>(&(*m_input_layer_.m_layers));
auto layers_hidden_ptr_ = std::get_if<HiddenLayer::LayerImpl>(&(*m_hidden_layer_.m_layers));
auto layer_output_ptr_ = std::get_if<OutputLayer::PrimitiveTPtr>(&(*m_output_layer_.m_layers));
if(buffer->size() != (*layer_output_ptr_)->size()) {
throw std::out_of_range("");
return (status = false);
}
// Set category for output layer
for(auto&& row : *buffer | boost::adaptors::indexed(0)) {
auto&& [category, collage] = row.value();
(*layer_output_ptr_)->setCategory(static_cast<std::size_t>(row.index()), category);
}
// Education
for(std::size_t i = 0 ; i < (*m_epoch); ++i) {
for(auto&& [category, collage] : *buffer) {
for(auto& image : collage) {
// Get image.
cv::Mat data_input_ = cv::imread(m_dataset + '/' + category + '/' + image);
// Check valid image.
if(data_input_.empty()) { continue; }
if(data_input_.type() != CV_8UC3) { /* TODO: convert */ }
// Supply values to the input layer
for(int r = 0; r < data_input_.rows; ++r) {
for(int c = 0; c < data_input_.cols; ++c) {
(*layer_input_ptr_)->set(static_cast<std::size_t>(c+(r*data_input_.cols)),
static_cast<double>(data_input_.at<unsigned char>(r,c))/255);
}
}
// Direct distribution Network
{
for(const auto& layer : *layers_hidden_ptr_) {
layer.get()->calculate();
}
(*layer_output_ptr_)->calculate();
}
// Back distribution Network
{
// For output layer
(*layer_output_ptr_)->update(category);
// For hidden layer
layers_hidden_ptr_->back()->update(*(*layer_output_ptr_));
const std::size_t size_hidden_layers_ = layers_hidden_ptr_->size() - 1;
for(std::size_t j = size_hidden_layers_; j != 0; --j) {
layers_hidden_ptr_->at(j-1)->update(*layers_hidden_ptr_->at(j));
}
}
// Update weight
{
for(const auto& layer : *layers_hidden_ptr_) {
layer.get()->updateWeight();
}
(*layer_output_ptr_)->updateWeight();
}
}
}
}
return status;
}
std::vector<std::string> Network::perception(const std::string& t_data)
{
std::vector<std::string> category {};
if(!boost::filesystem::exists(t_data)) {
return category;
}
// TODO: Check on correct image.
cv::Mat data_input_ = cv::imread(t_data);
// Check valid image.
if(!data_input_.empty()) {
if(data_input_.type() != CV_8UC3) { /* TODO: convert */ }
// Get pointers on layers
auto layer_input_ptr_ = std::get_if<InputLayer::PrimitiveTPtr>(&(*m_input_layer_.m_layers));
auto layers_hidden_ptr_ = std::get_if<HiddenLayer::LayerImpl>(&(*m_hidden_layer_.m_layers));
auto layer_output_ptr_ = std::get_if<OutputLayer::PrimitiveTPtr>(&(*m_output_layer_.m_layers));
// Supply values to the input layer
for(int r = 0; r < data_input_.rows; ++r) {
for(int c = 0; c < data_input_.cols; ++c) {
(*layer_input_ptr_)->set(static_cast<std::size_t>(c+(r*data_input_.cols)),
static_cast<double>(data_input_.at<unsigned char>(r,c))/255);
}
}
// Direct distribution Network
{
for(const auto& layer : *layers_hidden_ptr_) {
layer.get()->calculate();
}
(*layer_output_ptr_)->calculate();
}
auto max_output_it = std::max_element((*layer_output_ptr_)->begin(), (*layer_output_ptr_)->end(), [](auto&e, auto& o) {
return e->getOutputValue() < o->getOutputValue();
});
if(max_output_it != (*layer_output_ptr_)->end()) {
auto category_from_neuron = max_output_it->get()->getCategory();
if(!category_from_neuron.empty()) {
category.reserve(category_from_neuron.size());
category = category_from_neuron;
category.shrink_to_fit();
}
}
}
return category;
}
} // namespace network | 35.716535 | 125 | 0.617284 | [
"vector"
] |
bb7566775688db2712b4859b4824bd3adee0a090 | 565 | hh | C++ | sample/vs_pa_player.hh | venitech/vs-audio-keyword-detector | a877333b24add632dadc5f1e079f2fbdba7d555b | [
"Apache-2.0"
] | 1 | 2021-09-29T07:50:13.000Z | 2021-09-29T07:50:13.000Z | sample/vs_pa_player.hh | venitech/vs-audio-keyword-detector | a877333b24add632dadc5f1e079f2fbdba7d555b | [
"Apache-2.0"
] | null | null | null | sample/vs_pa_player.hh | venitech/vs-audio-keyword-detector | a877333b24add632dadc5f1e079f2fbdba7d555b | [
"Apache-2.0"
] | null | null | null | #ifndef __VS_PA_PLAYER_H__
#define __VS_PA_PLAYER_H__
#include <pa_util.h>
#include <portaudio.h>
#include <mutex>
#include "pa_safequeue.hh"
class VSPortAudioPlayer {
public:
VSPortAudioPlayer(int device_num);
~VSPortAudioPlayer();
size_t play(std::vector<int16_t>* data);
void AddSamples(std::vector<int16_t> *_samples);
std::vector<int16_t> _samples;
mutable std::mutex _mutex;
private:
bool Init();
private:
PaStream* _pa_stream;
int _device_number;
int _sample_rate;
int _num_channels;
int _bits_per_sample;
};
#endif | 13.452381 | 49 | 0.730973 | [
"vector"
] |
bb7b3c0fcebe80d29b169de141610a2d7e5c613c | 1,134 | cpp | C++ | src/helpers.cpp | unbornchikken/fastcall | 34695df041ee06798cd44da73f60ca075b0f0828 | [
"Apache-2.0"
] | 220 | 2016-10-25T01:42:09.000Z | 2022-03-16T13:21:51.000Z | src/helpers.cpp | unbornchikken/fastcall | 34695df041ee06798cd44da73f60ca075b0f0828 | [
"Apache-2.0"
] | 47 | 2016-11-17T14:33:52.000Z | 2021-11-15T08:38:59.000Z | src/helpers.cpp | unbornchikken/fastcall | 34695df041ee06798cd44da73f60ca075b0f0828 | [
"Apache-2.0"
] | 23 | 2016-12-12T14:39:07.000Z | 2021-11-11T12:14:01.000Z | /*
Copyright 2016 Gábor Mező (gabor.mezo@outlook.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "deps.h"
#include "helpers.h"
using namespace std;
using namespace v8;
using namespace fastcall;
using namespace node;
bool fastcall::InstanceOf(const v8::Local<Object>& obj, v8::Local<Function> ctor)
{
Nan::HandleScope scope;
auto proto = obj;
for (;;) {
if (proto.IsEmpty() || !proto->IsObject()) {
return false;
}
if (GetValue<Function>(proto, "constructor")->Equals(ctor)) {
return true;
}
proto = proto->GetPrototype().As<Object>();
}
return true;
}
| 27.658537 | 81 | 0.69224 | [
"object"
] |
bb7d88ef02e12fbb9680a483b8ace7c1cbed6cab | 12,699 | cpp | C++ | media_softlet/agnostic/common/vp/hal/packet/vp_render_vebox_hvs_kernel.cpp | LhGu/media-driver | e73c1d9a6cb8ff0c619766174cf618863520bf46 | [
"Intel",
"BSD-3-Clause",
"MIT"
] | null | null | null | media_softlet/agnostic/common/vp/hal/packet/vp_render_vebox_hvs_kernel.cpp | LhGu/media-driver | e73c1d9a6cb8ff0c619766174cf618863520bf46 | [
"Intel",
"BSD-3-Clause",
"MIT"
] | null | null | null | media_softlet/agnostic/common/vp/hal/packet/vp_render_vebox_hvs_kernel.cpp | LhGu/media-driver | e73c1d9a6cb8ff0c619766174cf618863520bf46 | [
"Intel",
"BSD-3-Clause",
"MIT"
] | null | null | null | /*
* Copyright (c) 2022, Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
//!
//! \file vp_render_vebox_hvs_kernel.cpp
//! \brief render packet which used in by mediapipline.
//! \details render packet provide the structures and generate the cmd buffer which mediapipline will used.
//!
#include "vp_render_vebox_hvs_kernel.h"
#include "vp_dumper.h"
#include "vp_kernelset.h"
using namespace vp;
#define VP_HVS_KERNEL_NAME "UpdateDNDITable"
VpRenderHVSKernel::VpRenderHVSKernel(PVP_MHWINTERFACE hwInterface, VpKernelID kernelID, uint32_t kernelIndex, PVpAllocator allocator) :
VpRenderKernelObj(hwInterface, kernelID, kernelIndex, VP_HVS_KERNEL_NAME, allocator)
{
m_kernelBinaryID = VP_ADV_KERNEL_BINARY_ID(kernelID);
m_isAdvKernel = true;
}
VpRenderHVSKernel::~VpRenderHVSKernel()
{
// No need to destroy dstArg.pData, which points to the local variable
// in VpDnFilter.
}
MOS_STATUS VpRenderHVSKernel::Init(VpRenderKernel &kernel)
{
VP_FUNC_CALL();
m_kernelSize = kernel.GetKernelSize() + KERNEL_BINARY_PADDING_SIZE;
uint8_t *pKernelBin = (uint8_t *)kernel.GetKernelBinPointer();
VP_RENDER_CHK_NULL_RETURN(pKernelBin);
m_kernelBinary = pKernelBin + kernel.GetKernelBinOffset();
m_kernelArgs = kernel.GetKernelArgs();
return MOS_STATUS_SUCCESS;
}
MOS_STATUS VpRenderHVSKernel::GetWalkerSetting(KERNEL_WALKER_PARAMS &walkerParam, KERNEL_PACKET_RENDER_DATA &renderData)
{
VP_FUNC_CALL();
VP_RENDER_CHK_STATUS_RETURN(VpRenderKernelObj::GetWalkerSetting(m_walkerParam, renderData));
walkerParam = m_walkerParam;
return MOS_STATUS_SUCCESS;
}
// Only for Adv kernels.
MOS_STATUS VpRenderHVSKernel::SetWalkerSetting(KERNEL_THREAD_SPACE &threadSpace, bool bSyncFlag)
{
VP_FUNC_CALL();
MOS_ZeroMemory(&m_walkerParam, sizeof(KERNEL_WALKER_PARAMS));
m_walkerParam.iBlocksX = threadSpace.uWidth;
m_walkerParam.iBlocksY = threadSpace.uHeight;
m_walkerParam.isVerticalPattern = false;
m_walkerParam.bSyncFlag = bSyncFlag;
return MOS_STATUS_SUCCESS;
}
MOS_STATUS VpRenderHVSKernel::SetKernelArgs(KERNEL_ARGS &kernelArgs, VP_PACKET_SHARED_CONTEXT *sharedContext)
{
VP_FUNC_CALL();
auto &hvsParams = sharedContext->hvsParams;
KRN_ARG krnArg = {};
krnArg.uIndex = 1;
krnArg.eArgKind = ARG_KIND_GENERAL;
krnArg.uSize = 2;
krnArg.pData = &hvsParams.Mode;
kernelArgs.push_back(krnArg);
krnArg.uIndex = 2;
krnArg.eArgKind = ARG_KIND_GENERAL;
krnArg.uSize = 2;
krnArg.pData = &hvsParams.Format;
kernelArgs.push_back(krnArg);
krnArg.uIndex = 3;
krnArg.eArgKind = ARG_KIND_GENERAL;
krnArg.uSize = 2;
krnArg.pData = &hvsParams.Width;
kernelArgs.push_back(krnArg);
krnArg.uIndex = 4;
krnArg.eArgKind = ARG_KIND_GENERAL;
krnArg.uSize = 2;
krnArg.pData = &hvsParams.Height;
kernelArgs.push_back(krnArg);
krnArg.uIndex = 5;
krnArg.eArgKind = ARG_KIND_GENERAL;
krnArg.uSize = 4;
krnArg.pData = &hvsParams.dwGlobalNoiseLevel;
kernelArgs.push_back(krnArg);
krnArg.uIndex = 6;
krnArg.eArgKind = ARG_KIND_GENERAL;
krnArg.uSize = 4;
krnArg.pData = &hvsParams.dwGlobalNoiseLevelU;
kernelArgs.push_back(krnArg);
krnArg.uIndex = 7;
krnArg.eArgKind = ARG_KIND_GENERAL;
krnArg.uSize = 4;
krnArg.pData = &hvsParams.dwGlobalNoiseLevelV;
kernelArgs.push_back(krnArg);
krnArg.uIndex = 8;
krnArg.eArgKind = ARG_KIND_GENERAL;
krnArg.uSize = 4;
krnArg.pData = &hvsParams.Sgne_Level;
kernelArgs.push_back(krnArg);
krnArg.uIndex = 9;
krnArg.eArgKind = ARG_KIND_GENERAL;
krnArg.uSize = 4;
krnArg.pData = &hvsParams.Sgne_LevelU;
kernelArgs.push_back(krnArg);
krnArg.uIndex = 10;
krnArg.eArgKind = ARG_KIND_GENERAL;
krnArg.uSize = 4;
krnArg.pData = &hvsParams.Sgne_LevelV;
kernelArgs.push_back(krnArg);
krnArg.uIndex = 11;
krnArg.eArgKind = ARG_KIND_GENERAL;
krnArg.uSize = 4;
krnArg.pData = &hvsParams.Sgne_Count;
kernelArgs.push_back(krnArg);
krnArg.uIndex = 12;
krnArg.eArgKind = ARG_KIND_GENERAL;
krnArg.uSize = 4;
krnArg.pData = &hvsParams.Sgne_Count;
kernelArgs.push_back(krnArg);
krnArg.uIndex = 13;
krnArg.eArgKind = ARG_KIND_GENERAL;
krnArg.uSize = 4;
krnArg.pData = &hvsParams.Sgne_CountV;
kernelArgs.push_back(krnArg);
krnArg.uIndex = 14;
krnArg.eArgKind = ARG_KIND_GENERAL;
krnArg.uSize = 4;
krnArg.pData = &hvsParams.PrevNslvTemporal;
kernelArgs.push_back(krnArg);
krnArg.uIndex = 15;
krnArg.eArgKind = ARG_KIND_GENERAL;
krnArg.uSize = 4;
krnArg.pData = &hvsParams.PrevNslvTemporalU;
kernelArgs.push_back(krnArg);
krnArg.uIndex = 16;
krnArg.eArgKind = ARG_KIND_GENERAL;
krnArg.uSize = 4;
krnArg.pData = &hvsParams.PrevNslvTemporalV;
kernelArgs.push_back(krnArg);
krnArg.uIndex = 17;
krnArg.eArgKind = ARG_KIND_GENERAL;
krnArg.uSize = 2;
krnArg.pData = &hvsParams.QP;
kernelArgs.push_back(krnArg);
krnArg.uIndex = 18;
krnArg.eArgKind = ARG_KIND_GENERAL;
krnArg.uSize = 2;
krnArg.pData = &hvsParams.FirstFrame;
kernelArgs.push_back(krnArg);
krnArg.uIndex = 19;
krnArg.eArgKind = ARG_KIND_GENERAL;
krnArg.uSize = 2;
krnArg.pData = &hvsParams.TgneFirstFrame;
kernelArgs.push_back(krnArg);
krnArg.uIndex = 20;
krnArg.eArgKind = ARG_KIND_GENERAL;
krnArg.uSize = 2;
krnArg.pData = &hvsParams.Fallback;
kernelArgs.push_back(krnArg);
krnArg.uIndex = 21;
krnArg.eArgKind = ARG_KIND_GENERAL;
krnArg.uSize = 2;
krnArg.pData = &hvsParams.EnableChroma;
kernelArgs.push_back(krnArg);
krnArg.uIndex = 22;
krnArg.eArgKind = ARG_KIND_GENERAL;
krnArg.uSize = 2;
krnArg.pData = &hvsParams.EnableTemporalGNE;
kernelArgs.push_back(krnArg);
if (kernelArgs.size() != m_kernelArgs.size())
{
VP_RENDER_ASSERTMESSAGE("The Kernel Arguments is not aligned!");
return MOS_STATUS_INVALID_PARAMETER;
}
for (uint32_t i = 0; i < m_kernelArgs.size(); ++i)
{
if (i >= kernelArgs.size())
{
VP_RENDER_CHK_STATUS_RETURN(MOS_STATUS_INVALID_PARAMETER);
}
KRN_ARG &srcArg = kernelArgs[i];
KRN_ARG &dstArg = m_kernelArgs[i];
if (srcArg.uIndex != dstArg.uIndex ||
srcArg.uSize != dstArg.uSize ||
srcArg.eArgKind != dstArg.eArgKind &&
dstArg.eArgKind != (srcArg.eArgKind & ~SURFACE_MASK) ||
srcArg.pData == nullptr)
{
VP_RENDER_CHK_STATUS_RETURN(MOS_STATUS_INVALID_PARAMETER);
}
dstArg.eArgKind = srcArg.eArgKind;
dstArg.pData = srcArg.pData;
srcArg.pData = nullptr;
}
return MOS_STATUS_SUCCESS;
}
MOS_STATUS VpRenderHVSKernel::GetCurbeState(void *&curbe, uint32_t &curbeLength)
{
VP_FUNC_CALL();
curbeLength = 0;
for (auto arg : m_kernelArgs)
{
curbeLength += arg.uSize;
}
if (sizeof(m_curbe) != curbeLength)
{
VP_RENDER_CHK_STATUS_RETURN(MOS_STATUS_INVALID_PARAMETER);
}
uint8_t *data = (uint8_t *)&m_curbe;
for (auto &arg : m_kernelArgs)
{
if (arg.eArgKind == ARG_KIND_SURFACE)
{
// Resource need be added.
uint32_t *pSurfaceindex = static_cast<uint32_t *>(arg.pData);
auto it = m_surfaceBindingIndex.find((SurfaceType)*pSurfaceindex);
if (it == m_surfaceBindingIndex.end())
{
VP_RENDER_CHK_STATUS_RETURN(MOS_STATUS_INVALID_PARAMETER);
}
*((uint32_t *)(data + arg.uOffsetInPayload)) = it->second;
}
else if (arg.eArgKind == ARG_KIND_GENERAL)
{
MOS_SecureMemcpy(data + arg.uOffsetInPayload, arg.uSize, arg.pData, arg.uSize);
}
else
{
VP_RENDER_CHK_STATUS_RETURN(MOS_STATUS_UNIMPLEMENTED);
}
}
curbe = data;
VP_RENDER_NORMALMESSAGE("HVS Kernel curbelength %d", curbeLength);
return MOS_STATUS_SUCCESS;
}
MOS_STATUS VpRenderHVSKernel::SetupSurfaceState()
{
VP_FUNC_CALL();
VP_RENDER_CHK_NULL_RETURN(m_surfaceGroup);
VP_RENDER_CHK_NULL_RETURN(m_hwInterface);
PRENDERHAL_INTERFACE renderHal = m_hwInterface->m_renderHal;
PMOS_INTERFACE osInterface = m_hwInterface->m_osInterface;
for (auto arg : m_kernelArgs)
{
VP_RENDER_CHK_NULL_RETURN(arg.pData);
if (arg.eArgKind == ARG_KIND_SURFACE)
{
SurfaceType surfType = *(SurfaceType *)arg.pData;
auto it = m_surfaceGroup->find(surfType);
if (m_surfaceGroup->end() == it)
{
VP_RENDER_CHK_STATUS_RETURN(MOS_STATUS_INVALID_PARAMETER);
}
auto surf = it->second;
VP_RENDER_CHK_NULL_RETURN(surf);
VP_RENDER_CHK_NULL_RETURN(surf->osSurface);
uint32_t width = surf->bufferWidth;
uint32_t height = surf->bufferHeight;
KERNEL_SURFACE_STATE_PARAM kernelSurfaceParam = {};
kernelSurfaceParam.surfaceOverwriteParams.updatedSurfaceParams = true;
kernelSurfaceParam.surfaceOverwriteParams.width = surf->bufferWidth;
kernelSurfaceParam.surfaceOverwriteParams.height = 256;
kernelSurfaceParam.surfaceOverwriteParams.pitch = 0;
kernelSurfaceParam.surfaceOverwriteParams.format = Format_A8R8G8B8;
kernelSurfaceParam.surfaceOverwriteParams.tileType = surf->osSurface->TileType;
kernelSurfaceParam.surfaceOverwriteParams.surface_offset = 0;
//kernelSurfaceParam.surfaceOverwriteParams.updatedRenderSurfaces = true;
//kernelSurfaceParam.surfaceOverwriteParams.renderSurfaceParams.Type = renderHal->SurfaceTypeDefault;
//kernelSurfaceParam.surfaceOverwriteParams.renderSurfaceParams.bRenderTarget = true; // true if no need sync for read.
//kernelSurfaceParam.surfaceOverwriteParams.renderSurfaceParams.bWidthInDword_Y = true;
//kernelSurfaceParam.surfaceOverwriteParams.renderSurfaceParams.bWidthInDword_UV = true;
//kernelSurfaceParam.surfaceOverwriteParams.renderSurfaceParams.Boundary = RENDERHAL_SS_BOUNDARY_ORIGINAL;
//kernelSurfaceParam.surfaceOverwriteParams.renderSurfaceParams.bWidth16Align = false;
////set mem object control for cache
//kernelSurfaceParam.surfaceOverwriteParams.renderSurfaceParams.MemObjCtl = (osInterface->pfnCachePolicyGetMemoryObject(
// MOS_MP_RESOURCE_USAGE_DEFAULT,
// osInterface->pfnGetGmmClientContext(osInterface))).DwordValue;
m_surfaceState.insert(std::make_pair(*(SurfaceType *)arg.pData, kernelSurfaceParam));
}
}
return MOS_STATUS_SUCCESS;
}
MOS_STATUS VpRenderHVSKernel::SetKernelConfigs(KERNEL_CONFIGS& kernelConfigs)
{
VP_FUNC_CALL();
auto it = kernelConfigs.find((VpKernelID)kernelHVSCalc);
if (kernelConfigs.end() == it || nullptr == it->second)
{
VP_RENDER_CHK_STATUS_RETURN(MOS_STATUS_INVALID_PARAMETER);
}
PRENDER_DN_HVS_CAL_PARAMS params = (PRENDER_DN_HVS_CAL_PARAMS)it->second;
return MOS_STATUS_SUCCESS;
}
| 34.137097 | 135 | 0.677534 | [
"render",
"object"
] |
bb8b16f3776fe80aad68ec69976e0e28f8c3cb08 | 1,068 | cpp | C++ | Stack/0084_LargestRectangleInHistogram/Solution.cpp | liweiyap/LeetCode_Solutions | a137ddbfb6baa6ddabbea809e89e003760b1f23f | [
"MIT"
] | 1 | 2020-03-08T23:23:38.000Z | 2020-03-08T23:23:38.000Z | Stack/0084_LargestRectangleInHistogram/Solution.cpp | liweiyap/LeetCode_Solutions | a137ddbfb6baa6ddabbea809e89e003760b1f23f | [
"MIT"
] | 1 | 2020-01-27T14:01:43.000Z | 2020-01-27T14:01:43.000Z | Stack/0084_LargestRectangleInHistogram/Solution.cpp | liweiyap/LeetCode_Solutions | a137ddbfb6baa6ddabbea809e89e003760b1f23f | [
"MIT"
] | null | null | null | // Runtime: 16 ms, faster than 52.04% of C++ online submissions for Largest Rectangle in Histogram.
// Memory Usage: 10.8 MB, less than 37.14% of C++ online submissions for Largest Rectangle in Histogram.
#include <stack>
#include <vector>
#include <algorithm>
class Solution
{
public:
int largestRectangleArea(std::vector<int>& heights)
{
int maxArea = 0;
std::stack<std::pair<int,int>> s;
for (int idx = 0; idx < heights.size(); ++idx)
{
int leftWall = idx;
while (!s.empty() && heights[idx] < heights[s.top().first])
{
leftWall = s.top().second;
maxArea = std::max(maxArea, (idx - leftWall) * heights[s.top().first]);
s.pop();
}
s.push(std::make_pair(idx,leftWall));
}
while (!s.empty())
{
maxArea = std::max(maxArea, (static_cast<int>(heights.size()) - s.top().second) * heights[s.top().first]);
s.pop();
}
return maxArea;
}
};
| 29.666667 | 118 | 0.526217 | [
"vector"
] |
bb8ebb623cf20c57df2c3c1eb6e656ff6ec983e5 | 6,317 | cpp | C++ | src/pomdp/src/alpha_policy.cpp | b-adkins/ros_pomdp | 73af687f94fc41c2f60e4ae86702064a25ea59b3 | [
"MIT"
] | 8 | 2016-01-10T04:40:06.000Z | 2019-02-22T07:39:08.000Z | src/pomdp/src/alpha_policy.cpp | b-adkins/ros_pomdp | 73af687f94fc41c2f60e4ae86702064a25ea59b3 | [
"MIT"
] | null | null | null | src/pomdp/src/alpha_policy.cpp | b-adkins/ros_pomdp | 73af687f94fc41c2f60e4ae86702064a25ea59b3 | [
"MIT"
] | 5 | 2016-01-10T04:40:07.000Z | 2021-08-08T12:57:53.000Z | /*
* The MIT License (MIT)
*
* Copyright (c) 2014 Boone "Bea" Adkins
*
* 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.
*/
/**
* @file
*
*
*
* @date Jul 15, 2013
* @author Bea Adkins
*/
#include <algorithm>
#include <boost/filesystem/path.hpp>
#include <iostream>
#include <iterator>
#include <fstream>
#include <string>
#include <sstream>
#include "alpha_policy.h"
#include "assert_rng.h"
#include "assert_type.h"
#include "pomdp.h"
#include "pomdp_io.h"
#include "pretty.h"
#include "feature_space.h"
#include "belief_feature_value.h"
namespace pomdp
{
AlphaPolicy::AlphaPolicy()
{
}
AlphaPolicy::AlphaPolicy(const char* path)
{
AlphaPolicy();
loadFromFile(path);
}
AlphaPolicy::~AlphaPolicy()
{
}
/**
* Loads a policy file.
*
* @return True on success.
*/
bool AlphaPolicy::loadFromFile(const char* path)
{
int action;
double alpha;
std::vector<double> alphas;
std::string line;
bool alpha_line = false; // True for alpha line, false for action line. (Simple state machine.)
// Open file.
std::ifstream policy_file;
policy_file.open(path);
if(!policy_file.good())
{
ROS_ERROR_STREAM("Unable to open file " << path);
return false;
}
// Check Policy has what it needs to read the file.
ROS_ASSERT_MSG(state_space_, "Requires StateSpace to be initialized!");
// Read file.
while(!policy_file.eof())
{
std::getline(policy_file, line);
if(policy_file.fail())
continue;
line = stripComment(line);
if(isBlank(line))
continue; // Skip line
std::stringstream line_ss(line);
// Action line
if(!alpha_line)
{
// Read element from line.
std::string action_str;
line_ss >> action_str;
if(line_ss.fail())
{
ROS_ERROR_STREAM("Invalid action line: '" << line << "'");
return false;
}
// Convert to action.
// Kludgy. @todo Change actions from ints to FeatureValues.
shared_ptr<FeatureValue> action_obj = action_space_->readFeatureValue(action_str);
action = boost::dynamic_pointer_cast<SimpleFeatureValue>(action_obj)->asInt();
if(!action_space_->isValid(SimpleFeatureValue(action)))
{
ROS_ERROR_STREAM("Invalid action: '" << action_str << "'");
return false;
}
actions_.push_back(action);
alpha_line = true;
}
// Alpha line
else if(alpha_line)
{
alphas.clear();
while(line_ss >> alpha)
{
if(line_ss.fail())
{
ROS_ERROR_STREAM("Invalid alpha vector, needs decimal numbers in line: '" << line << "'");
return false;
}
alphas.push_back(alpha);
}
alphas_.push_back(alphas);
alpha_line = false;
}
}
// Fail on empty policy.
if(alphas_[0].size() == 0)
{
ROS_ERROR("Empty alpha line(s) in policy file.");
return false;
}
if(actions_.size() == 0 || alphas_.size() == 0)
{
ROS_ERROR("Empty policy file.");
return false;
}
// Fail if actions-alphas aren't one-to-one.
if(actions_.size() != alphas_.size())
{
ROS_ERROR_STREAM("Mismatch between number of actions (" << actions_.size()
<< ") and number of alpha vectors (" << alphas_.size() << ").");
return false;
}
// Fail if alphas inconsistent in size.
for(int a = 0; a < alphas_.size() - 1; a++)
{
if(alphas_[a].size() != alphas_[a + 1].size())
{
ROS_ERROR("Inconsistently sized alpha vectors:");
ROS_ERROR_STREAM(Pretty::vectorToString(alphas_[a]));
ROS_ERROR_STREAM(Pretty::vectorToString(alphas_[a + 1]));
return false;
}
}
// Fail on mismatched number of states.
unsigned int num_states = alphas_[0].size();
if(num_states != state_space_->getNumValues())
{
ROS_ERROR_STREAM("Number of states read (" << num_states << ") does not match number in");
ROS_ERROR_STREAM(*state_space_);
return false;
}
// Use filename for name
boost::filesystem::path bpath(path);
setName(bpath.stem().string());
is_init_ = true;
return true;
}
/**
* Determines action from belief state.
*
* @param belief_state Vector of probabilities, one for each state.
* @return Action or -1 for failure.
*/
int AlphaPolicy::applyPolicy(const FeatureValue& belief) const
{
if(!isInit())
return -1;
ROS_ASSERT_CMD(actions_.size() > 0, return -1);
ROS_ASSERT_TYPE(belief, BeliefFeatureValue);
// ROS_ASSERT_TYPE_CMD(belief, BeliefState, return -1);
ROS_ASSERT((state_space_->isValid(belief)));
// ROS_ASSERT_CMD((state_space_->isValid(belief)), return -1);
const BeliefFeatureValue& b = dynamic_cast<const BeliefFeatureValue&>(belief);
// Multiply belief state by every alpha vector
std::vector<double> values(actions_.size(), 0.0);
for(int n = 0; n < actions_.size(); n++)
{
for(int s = 0; s < getNumStates(); s++)
{
values[n] += b[s] * alphas_[n][s];
}
}
// Debug printing
ROS_DEBUG_STREAM("Policy '" << getName() << "' values: " << Pretty::vectorToString(values));
// Find highest value and return corresponding action
std::vector<double>::iterator value_max;
value_max = std::max_element(values.begin(), values.end());
int i_a = std::distance(values.begin(), value_max);
return actions_[i_a];
}
} /* namespace pomdp */
| 26.766949 | 100 | 0.658382 | [
"vector"
] |
bb9167dd7a0cc6f648179848710b2bfaa1161518 | 336 | cpp | C++ | graph-measures/features_algorithms/accelerated_graph_features/src/wrappers/WrapperIncludes.cpp | Unknown-Data/QGCN | e074ada31c13b6de6eabba2b2ebce90e88fdfdbf | [
"MIT"
] | 3 | 2021-04-21T16:06:51.000Z | 2022-03-31T12:09:01.000Z | graph-measures/features_algorithms/accelerated_graph_features/src/wrappers/WrapperIncludes.cpp | Unknown-Data/QGCN | e074ada31c13b6de6eabba2b2ebce90e88fdfdbf | [
"MIT"
] | 1 | 2021-02-04T07:48:16.000Z | 2021-02-24T23:01:41.000Z | graph-measures/features_algorithms/accelerated_graph_features/src/wrappers/WrapperIncludes.cpp | Unknown-Data/QGCN | e074ada31c13b6de6eabba2b2ebce90e88fdfdbf | [
"MIT"
] | null | null | null | /*
* WrapperIncludes.cpp
*
* Created on: Nov 20, 2018
* Author: ori
*/
#include "WrapperIncludes.h"
py::list convertVectorOfVectorsTo2DList(vector<vector<unsigned int>*>* vec) {
py::list mainList;
for (auto l : *vec) {
mainList.append(vectorToPythonList<unsigned int>(*l));
}
return mainList;
}
| 16.8 | 78 | 0.633929 | [
"vector"
] |
bb9802ef3df2b9af28086afbcfae443bcd122491 | 9,077 | cpp | C++ | XsGameEngine/src/AssetLoading/Vulkan_Assets/Vulkan_Texture.cpp | XsAndre-L/XsGameEngine-REF | 82bbb6424c9b63e0ccf381bd73c0beabce0da141 | [
"Apache-2.0"
] | null | null | null | XsGameEngine/src/AssetLoading/Vulkan_Assets/Vulkan_Texture.cpp | XsAndre-L/XsGameEngine-REF | 82bbb6424c9b63e0ccf381bd73c0beabce0da141 | [
"Apache-2.0"
] | null | null | null | XsGameEngine/src/AssetLoading/Vulkan_Assets/Vulkan_Texture.cpp | XsAndre-L/XsGameEngine-REF | 82bbb6424c9b63e0ccf381bd73c0beabce0da141 | [
"Apache-2.0"
] | null | null | null | #include "Vulkan_Texture.h"
Vulkan_Texture::Vulkan_Texture(VkPhysicalDevice* physicalDevice,VkDevice* device, VkQueue* graphicsQueue, VkCommandPool* graphicsCommandPool, VkSampler* sampler, VkDescriptorPool* descriptorPool, VkDescriptorSetLayout* samplerSetLayout)
{
PhysicalDevice = physicalDevice;
Device = device;
GraphicsQueue = graphicsQueue;
GraphicsCommandPool = graphicsCommandPool;
TextureSampler = sampler;
SamplerDescriptorPool = descriptorPool;
SamplerSetLayout = samplerSetLayout;
}
int Vulkan_Texture::createTexture(std::string fileName)
{
//Create Texture Image and get its location in array
bool TexSuccess = createTextureImage(fileName);
if (TexSuccess == false) { return 1; }
//Create image view and add to list
textureImageView = createImageView(*Device, textureImage, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_ASPECT_COLOR_BIT, mipLevel);
//textureImageViews.push_back(imageView);
//TODO: Create Descriptor Set Here
int descriptorLoc = createTextureDescriptor(textureImageView);
return 0;
}
bool Vulkan_Texture::createTextureImage(std::string fileName)
{
//Load Image File
int width, height;
VkDeviceSize imageSize;
stbi_uc* imageData = loadTextureFile(fileName, &width, &height, &imageSize);
if (imageData == nullptr) {
return false;
}
//Calculate MipLevels ///busy
mipLevel = static_cast<uint32_t>(std::floor(std::log2(std::max(width, height)))) + 1;
printf("mip levels: %d", mipLevel);
//Create staging buffer to hold loaded data, ready to copy to device
VkBuffer imageStagingBuffer;
VkDeviceMemory imageStagingBufferMemory;
createBuffer(*PhysicalDevice, *Device, imageSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
&imageStagingBuffer, &imageStagingBufferMemory);
//Copy image data to staging buffer
void* data;
vkMapMemory(*Device, imageStagingBufferMemory, 0, imageSize, 0, &data);
memcpy(data, imageData, static_cast<size_t>(imageSize));
vkUnmapMemory(*Device, imageStagingBufferMemory);
//Free original image data
stbi_image_free(imageData);
//Create image to hold final texture
//VkImage texImage;
//VkDeviceMemory texImageMemory;
textureImage = createImage(*PhysicalDevice, *Device, width, height, mipLevel, VK_SAMPLE_COUNT_1_BIT, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_TILING_OPTIMAL,
VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, &textureImageMemory);
//Transfer Texture to a Transfer DST Optimal Layout
transitionImageLayout(*Device, *GraphicsQueue, *GraphicsCommandPool, textureImage,
VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, mipLevel);
//Copy Data To Image
copyImageBuffer(*Device, *GraphicsQueue, *GraphicsCommandPool, imageStagingBuffer, textureImage, width, height);
//Transfer Texture to a shader read only Layout -- when creating mipMaps
//transitionImageLayout(mainDevice.logicalDevice, graphicsQueue, graphicsCommandPool, texImage, ///bussy
// VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, mipLevels[mipLevels.size() - 1]);
generateMipmaps(textureImage, VK_FORMAT_R8G8B8A8_SRGB, width, height, mipLevel);
// Add texture data to vector for reference
//textureImages.push_back(texImage);
//textureImageMemory.push_back(texImageMemory);
//Destroy staging buffers
vkDestroyBuffer(*Device, imageStagingBuffer, nullptr);
vkFreeMemory(*Device, imageStagingBufferMemory, nullptr);
return true;
}
// Generate MipMaps for given texture
void Vulkan_Texture::generateMipmaps(VkImage image, VkFormat imageFormat, int32_t texWidth, int32_t texHeight, uint32_t mipLevels) { ///busy
VkFormatProperties formatProperties;
vkGetPhysicalDeviceFormatProperties(*PhysicalDevice, imageFormat, &formatProperties);
if (!(formatProperties.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT)) {
throw std::runtime_error("texture image format does not support linear blitting!");
}
VkCommandBuffer commandBuffer = beginCommandBuffer(*Device, *GraphicsCommandPool);
VkImageMemoryBarrier barrier{};
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
barrier.image = image;
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
barrier.subresourceRange.baseArrayLayer = 0;
barrier.subresourceRange.layerCount = 1;
barrier.subresourceRange.levelCount = 1;
int32_t mipWidth = texWidth;
int32_t mipHeight = texHeight;
for (uint32_t i = 1; i < mipLevels; i++) {
barrier.subresourceRange.baseMipLevel = i - 1;
barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
vkCmdPipelineBarrier(commandBuffer,
VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0,
0, nullptr,
0, nullptr,
1, &barrier);
VkImageBlit blit{};
blit.srcOffsets[0] = { 0, 0, 0 };
blit.srcOffsets[1] = { mipWidth, mipHeight, 1 };
blit.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
blit.srcSubresource.mipLevel = i - 1;
blit.srcSubresource.baseArrayLayer = 0;
blit.srcSubresource.layerCount = 1;
blit.dstOffsets[0] = { 0, 0, 0 };
blit.dstOffsets[1] = { mipWidth > 1 ? mipWidth / 2 : 1, mipHeight > 1 ? mipHeight / 2 : 1, 1 };
blit.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
blit.dstSubresource.mipLevel = i;
blit.dstSubresource.baseArrayLayer = 0;
blit.dstSubresource.layerCount = 1;
vkCmdBlitImage(commandBuffer,
image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1, &blit,
VK_FILTER_LINEAR);
barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
barrier.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
vkCmdPipelineBarrier(commandBuffer,
VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0,
0, nullptr,
0, nullptr,
1, &barrier);
if (mipWidth > 1) mipWidth /= 2;
if (mipHeight > 1) mipHeight /= 2;
}
barrier.subresourceRange.baseMipLevel = mipLevels - 1;
barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
vkCmdPipelineBarrier(commandBuffer,
VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0,
0, nullptr,
0, nullptr,
1, &barrier);
endAndSubmitCommandBuffer(*Device, *GraphicsCommandPool, *GraphicsQueue, commandBuffer);
}
stbi_uc* Vulkan_Texture::loadTextureFile(std::string fileName, int* width, int* height, VkDeviceSize* imageSize)
{
int channels;
std::string fileLoc = "Textures/" + fileName;
stbi_uc* image = stbi_load(fileLoc.c_str(), width, height, &channels, STBI_rgb_alpha);
if (!image)
{
//printf("Failed to load Texture ( %s )", fileName.c_str());
std::cout << "Failed to load Texture : " << fileName << std::endl;
image = nullptr;
}
//static_cast<uint64_t> because VkDeviceSize [imageSize] is 64bit large
*imageSize = static_cast<uint64_t>(*width) * *height * 4;
return image;
}
int Vulkan_Texture::createTextureDescriptor(VkImageView textureImage)
{
VkDescriptorSet descriptorSet{};
// Descriptor Set Allocation Info
VkDescriptorSetAllocateInfo setAllocInfo{};
setAllocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
setAllocInfo.descriptorPool = *SamplerDescriptorPool;
setAllocInfo.descriptorSetCount = 1;
setAllocInfo.pSetLayouts = SamplerSetLayout;
// Allocate Descriptor Sets
VkResult result = vkAllocateDescriptorSets(*Device, &setAllocInfo, &SamplerDescriptorSet);
if (result != VK_SUCCESS) {
throw std::runtime_error("could not allocate info! -");// + std::to_string(result));
}
VkDescriptorImageInfo imageInfo{};
imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
imageInfo.imageView = textureImage;
imageInfo.sampler = *TextureSampler;
VkWriteDescriptorSet descriptorWrite{};
descriptorWrite.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrite.dstSet = SamplerDescriptorSet;
descriptorWrite.dstBinding = 0;
descriptorWrite.dstArrayElement = 0;
descriptorWrite.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
descriptorWrite.descriptorCount = 1;
descriptorWrite.pImageInfo = &imageInfo;
vkUpdateDescriptorSets(*Device, 1, &descriptorWrite, 0, nullptr);
//samplerDescriptorSets.push_back(descriptorSet);
return 1;//samplerDescriptorSets.size() - 1;
}
void Vulkan_Texture::cleanUpTexture()
{
if (getState()) { return; }
vkDestroyImageView(*Device, textureImageView, nullptr);
vkDestroyImage(*Device, textureImage, nullptr);
vkFreeMemory(*Device, textureImageMemory, nullptr);
DESTROYED = true;
}
| 35.596078 | 236 | 0.791231 | [
"vector"
] |
bba38ae6bdc2310d5fb567ef741cb690ed586677 | 9,974 | hpp | C++ | modules/scene_manager/include/visualization_msgs/msg/interactive_marker_feedback__struct.hpp | Omnirobotic/godot | d50b5d047bbf6c68fc458c1ad097321ca627185d | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | 1 | 2020-05-19T14:33:49.000Z | 2020-05-19T14:33:49.000Z | ros2_mod_ws/install/include/visualization_msgs/msg/interactive_marker_feedback__struct.hpp | mintforpeople/robobo-ros2-ios-port | 1a5650304bd41060925ebba41d6c861d5062bfae | [
"Apache-2.0"
] | 3 | 2019-11-14T12:20:06.000Z | 2020-08-07T13:51:10.000Z | modules/scene_manager/include/visualization_msgs/msg/interactive_marker_feedback__struct.hpp | Omnirobotic/godot | d50b5d047bbf6c68fc458c1ad097321ca627185d | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | null | null | null | // generated from rosidl_generator_cpp/resource/msg__struct.hpp.em
// generated code does not contain a copyright notice
#ifndef VISUALIZATION_MSGS__MSG__INTERACTIVE_MARKER_FEEDBACK__STRUCT_HPP_
#define VISUALIZATION_MSGS__MSG__INTERACTIVE_MARKER_FEEDBACK__STRUCT_HPP_
// Protect against ERROR being predefined on Windows, in case somebody defines a
// constant by that name.
#if defined(_WIN32) && defined(ERROR)
#undef ERROR
#endif
#include <rosidl_generator_cpp/bounded_vector.hpp>
#include <rosidl_generator_cpp/message_initialization.hpp>
#include <algorithm>
#include <array>
#include <memory>
#include <string>
#include <vector>
// include message dependencies
#include "geometry_msgs/msg/point.hpp" // mouse_point
#include "geometry_msgs/msg/pose.hpp" // pose
#include "std_msgs/msg/header.hpp" // header
#ifndef _WIN32
# define DEPRECATED_visualization_msgs_msg_InteractiveMarkerFeedback __attribute__((deprecated))
#else
# define DEPRECATED_visualization_msgs_msg_InteractiveMarkerFeedback __declspec(deprecated)
#endif
namespace visualization_msgs
{
namespace msg
{
// message struct
template<class ContainerAllocator>
struct InteractiveMarkerFeedback_
{
using Type = InteractiveMarkerFeedback_<ContainerAllocator>;
explicit InteractiveMarkerFeedback_(rosidl_generator_cpp::MessageInitialization _init = rosidl_generator_cpp::MessageInitialization::ALL)
: header(_init),
pose(_init),
mouse_point(_init)
{
if (rosidl_generator_cpp::MessageInitialization::ALL == _init ||
rosidl_generator_cpp::MessageInitialization::ZERO == _init)
{
this->client_id = "";
this->marker_name = "";
this->control_name = "";
}
if (rosidl_generator_cpp::MessageInitialization::ALL == _init ||
rosidl_generator_cpp::MessageInitialization::ZERO == _init)
{
this->event_type = 0;
}
if (rosidl_generator_cpp::MessageInitialization::ALL == _init ||
rosidl_generator_cpp::MessageInitialization::ZERO == _init)
{
this->menu_entry_id = 0ul;
}
if (rosidl_generator_cpp::MessageInitialization::ALL == _init ||
rosidl_generator_cpp::MessageInitialization::ZERO == _init)
{
this->mouse_point_valid = false;
}
}
explicit InteractiveMarkerFeedback_(const ContainerAllocator & _alloc, rosidl_generator_cpp::MessageInitialization _init = rosidl_generator_cpp::MessageInitialization::ALL)
: header(_alloc, _init),
client_id(_alloc),
marker_name(_alloc),
control_name(_alloc),
pose(_alloc, _init),
mouse_point(_alloc, _init)
{
if (rosidl_generator_cpp::MessageInitialization::ALL == _init ||
rosidl_generator_cpp::MessageInitialization::ZERO == _init)
{
this->client_id = "";
this->marker_name = "";
this->control_name = "";
}
if (rosidl_generator_cpp::MessageInitialization::ALL == _init ||
rosidl_generator_cpp::MessageInitialization::ZERO == _init)
{
this->event_type = 0;
}
if (rosidl_generator_cpp::MessageInitialization::ALL == _init ||
rosidl_generator_cpp::MessageInitialization::ZERO == _init)
{
this->menu_entry_id = 0ul;
}
if (rosidl_generator_cpp::MessageInitialization::ALL == _init ||
rosidl_generator_cpp::MessageInitialization::ZERO == _init)
{
this->mouse_point_valid = false;
}
}
// field types and members
using _header_type =
std_msgs::msg::Header_<ContainerAllocator>;
_header_type header;
using _client_id_type =
std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other>;
_client_id_type client_id;
using _marker_name_type =
std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other>;
_marker_name_type marker_name;
using _control_name_type =
std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other>;
_control_name_type control_name;
using _event_type_type =
uint8_t;
_event_type_type event_type;
using _pose_type =
geometry_msgs::msg::Pose_<ContainerAllocator>;
_pose_type pose;
using _menu_entry_id_type =
uint32_t;
_menu_entry_id_type menu_entry_id;
using _mouse_point_type =
geometry_msgs::msg::Point_<ContainerAllocator>;
_mouse_point_type mouse_point;
using _mouse_point_valid_type =
bool;
_mouse_point_valid_type mouse_point_valid;
// setters for named parameter idiom
Type * set__header(
const std_msgs::msg::Header_<ContainerAllocator> & _arg)
{
this->header = _arg;
return this;
}
Type * set__client_id(
const std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other> & _arg)
{
this->client_id = _arg;
return this;
}
Type * set__marker_name(
const std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other> & _arg)
{
this->marker_name = _arg;
return this;
}
Type * set__control_name(
const std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other> & _arg)
{
this->control_name = _arg;
return this;
}
Type * set__event_type(
const uint8_t & _arg)
{
this->event_type = _arg;
return this;
}
Type * set__pose(
const geometry_msgs::msg::Pose_<ContainerAllocator> & _arg)
{
this->pose = _arg;
return this;
}
Type * set__menu_entry_id(
const uint32_t & _arg)
{
this->menu_entry_id = _arg;
return this;
}
Type * set__mouse_point(
const geometry_msgs::msg::Point_<ContainerAllocator> & _arg)
{
this->mouse_point = _arg;
return this;
}
Type * set__mouse_point_valid(
const bool & _arg)
{
this->mouse_point_valid = _arg;
return this;
}
// constant declarations
static constexpr uint8_t KEEP_ALIVE =
0u;
static constexpr uint8_t POSE_UPDATE =
1u;
static constexpr uint8_t MENU_SELECT =
2u;
static constexpr uint8_t BUTTON_CLICK =
3u;
static constexpr uint8_t MOUSE_DOWN =
4u;
static constexpr uint8_t MOUSE_UP =
5u;
// pointer types
using RawPtr =
visualization_msgs::msg::InteractiveMarkerFeedback_<ContainerAllocator> *;
using ConstRawPtr =
const visualization_msgs::msg::InteractiveMarkerFeedback_<ContainerAllocator> *;
using SharedPtr =
std::shared_ptr<visualization_msgs::msg::InteractiveMarkerFeedback_<ContainerAllocator>>;
using ConstSharedPtr =
std::shared_ptr<visualization_msgs::msg::InteractiveMarkerFeedback_<ContainerAllocator> const>;
template<typename Deleter = std::default_delete<
visualization_msgs::msg::InteractiveMarkerFeedback_<ContainerAllocator>>>
using UniquePtrWithDeleter =
std::unique_ptr<visualization_msgs::msg::InteractiveMarkerFeedback_<ContainerAllocator>, Deleter>;
using UniquePtr = UniquePtrWithDeleter<>;
template<typename Deleter = std::default_delete<
visualization_msgs::msg::InteractiveMarkerFeedback_<ContainerAllocator>>>
using ConstUniquePtrWithDeleter =
std::unique_ptr<visualization_msgs::msg::InteractiveMarkerFeedback_<ContainerAllocator> const, Deleter>;
using ConstUniquePtr = ConstUniquePtrWithDeleter<>;
using WeakPtr =
std::weak_ptr<visualization_msgs::msg::InteractiveMarkerFeedback_<ContainerAllocator>>;
using ConstWeakPtr =
std::weak_ptr<visualization_msgs::msg::InteractiveMarkerFeedback_<ContainerAllocator> const>;
// pointer types similar to ROS 1, use SharedPtr / ConstSharedPtr instead
// NOTE: Can't use 'using' here because GNU C++ can't parse attributes properly
typedef DEPRECATED_visualization_msgs_msg_InteractiveMarkerFeedback
std::shared_ptr<visualization_msgs::msg::InteractiveMarkerFeedback_<ContainerAllocator>>
Ptr;
typedef DEPRECATED_visualization_msgs_msg_InteractiveMarkerFeedback
std::shared_ptr<visualization_msgs::msg::InteractiveMarkerFeedback_<ContainerAllocator> const>
ConstPtr;
// comparison operators
bool operator==(const InteractiveMarkerFeedback_ & other) const
{
if (this->header != other.header) {
return false;
}
if (this->client_id != other.client_id) {
return false;
}
if (this->marker_name != other.marker_name) {
return false;
}
if (this->control_name != other.control_name) {
return false;
}
if (this->event_type != other.event_type) {
return false;
}
if (this->pose != other.pose) {
return false;
}
if (this->menu_entry_id != other.menu_entry_id) {
return false;
}
if (this->mouse_point != other.mouse_point) {
return false;
}
if (this->mouse_point_valid != other.mouse_point_valid) {
return false;
}
return true;
}
bool operator!=(const InteractiveMarkerFeedback_ & other) const
{
return !this->operator==(other);
}
}; // struct InteractiveMarkerFeedback_
// alias to use template instance with default allocator
using InteractiveMarkerFeedback =
visualization_msgs::msg::InteractiveMarkerFeedback_<std::allocator<void>>;
// constant definitions
template<typename ContainerAllocator>
constexpr uint8_t InteractiveMarkerFeedback_<ContainerAllocator>::KEEP_ALIVE;
template<typename ContainerAllocator>
constexpr uint8_t InteractiveMarkerFeedback_<ContainerAllocator>::POSE_UPDATE;
template<typename ContainerAllocator>
constexpr uint8_t InteractiveMarkerFeedback_<ContainerAllocator>::MENU_SELECT;
template<typename ContainerAllocator>
constexpr uint8_t InteractiveMarkerFeedback_<ContainerAllocator>::BUTTON_CLICK;
template<typename ContainerAllocator>
constexpr uint8_t InteractiveMarkerFeedback_<ContainerAllocator>::MOUSE_DOWN;
template<typename ContainerAllocator>
constexpr uint8_t InteractiveMarkerFeedback_<ContainerAllocator>::MOUSE_UP;
} // namespace msg
} // namespace visualization_msgs
#endif // VISUALIZATION_MSGS__MSG__INTERACTIVE_MARKER_FEEDBACK__STRUCT_HPP_
| 33.02649 | 174 | 0.744135 | [
"vector"
] |
bba4be7317b0a5d668a6f9f606c3d4719eadacad | 830 | hpp | C++ | baseclass/baseclass_headers.hpp | HxHexa/quang-advCG-raytracer | 605f7dfcc9237f331d456646b7653ad0f26c0cc4 | [
"MIT"
] | null | null | null | baseclass/baseclass_headers.hpp | HxHexa/quang-advCG-raytracer | 605f7dfcc9237f331d456646b7653ad0f26c0cc4 | [
"MIT"
] | null | null | null | baseclass/baseclass_headers.hpp | HxHexa/quang-advCG-raytracer | 605f7dfcc9237f331d456646b7653ad0f26c0cc4 | [
"MIT"
] | null | null | null | /* baseclass_headers.hpp - collection of all headers from headers folder
* makes things cleaner
* Quang Tran - 9/6/2019
* */
#ifndef BASECLASS_HEADERS
#define BASECLASS_HEADERS
#include "headers/color.hpp"
#include "headers/tuple.hpp"
#include "headers/ray.hpp"
#include "headers/canvas.hpp"
#include "headers/matrix.hpp"
#include "headers/intersection.hpp"
#include "headers/comps.hpp"
#include "headers/material.hpp"
#include "headers/arealight.hpp"
#include "headers/pattern.hpp"
#include "headers/stripePattern.hpp"
#include "headers/testPattern.hpp"
#include "headers/checkerPattern.hpp"
#include "headers/object.hpp"
#include "headers/sphere.hpp"
#include "headers/plane.hpp"
#include "headers/triangle.hpp"
#include "headers/world.hpp"
#include "headers/camera.hpp"
#include "headers/baseclass_funcs.hpp"
#endif
| 23.055556 | 72 | 0.768675 | [
"object"
] |
bbaffeb43aa88715a079aad270798b29357b5f07 | 4,743 | hh | C++ | Modules/Plexil/src/apps/StandAloneSimulator/Simulator.hh | 5nefarious/icarous | bfd759d88a47d9ee079fe35deaa6cf6d4459dcd8 | [
"Unlicense"
] | 1 | 2020-02-27T03:35:50.000Z | 2020-02-27T03:35:50.000Z | src/apps/StandAloneSimulator/Simulator.hh | morxa/plexil-4 | 890e92aa259881dd944d573d6ec519341782a5f2 | [
"BSD-3-Clause"
] | null | null | null | src/apps/StandAloneSimulator/Simulator.hh | morxa/plexil-4 | 890e92aa259881dd944d573d6ec519341782a5f2 | [
"BSD-3-Clause"
] | null | null | null | /* Copyright (c) 2006-2008, Universities Space Research Association (USRA).
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Universities Space Research Association nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY USRA ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL USRA BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef SIMULATOR_HH
#define SIMULATOR_HH
#include <map>
#include "simdefs.hh"
#include "SimulatorScriptReader.hh"
#include "TimingService.hh"
#include "ThreadMutex.hh"
class ResponseMessageManager;
class ResponseMessage;
class CommRelayBase;
class Simulator
{
public:
Simulator(CommRelayBase* commRelay, ResponseManagerMap& map);
~Simulator();
/**
* @brief Starts a new background thread with the simulator top level loop and returns immediately.
* @note Call only after reading all scripts.
*/
void start();
/**
* @brief Stops the simulator's top level thread. Returns when the thread has rejoined.
*/
void stop();
/**
* @brief The simulator top level loop.
* @note Call only after reading all scripts.
*/
void simulatorTopLevel();
ResponseMessageManager* getResponseMessageManager(const std::string& cmdName) const;
/**
* @brief Schedules a response to the named command.
* @param command The command name to which we are responding.
* @param uniqueId Caller-specified identifier, passed through the simulator to the comm relay.
*/
void scheduleResponseForCommand(const std::string& command,
void* uniqueId = NULL);
/**
* @brief Get the current value of the named state.
* @param stateName The state name to which we are responding.
* @return Pointer to a const ResponseBase object, or NULL.
*/
ResponseMessage* getLookupNowResponse(const std::string& stateName, void* uniqueId) const;
/**
* @brief Schedules a message to be sent after an interval.
* @param delay The delay after which to send the message.
* @param msg The message to be sent.
*/
void scheduleMessage(const timeval& delay, ResponseMessage* msg);
/**
* @brief Schedules a message to be sent at a future time.
* @param time The absolute time at which to send the message.
* @param msg The message to be sent.
*/
void scheduleMessageAbsolute(const timeval& time, ResponseMessage* msg);
private:
// Deliberately not implemented
Simulator();
Simulator(const Simulator&);
Simulator& operator=(const Simulator&);
// Thread function for pthread_create
static void* run(void * this_as_void_ptr);
void handleWakeUp();
void scheduleNextResponse(const timeval& time);
/**
* @brief Constructs a response to the named command.
* @param command The command name to which we are responding.
* @param uniqueId Caller-specified identifier, passed through the simulator to the comm relay.
* @param timeval (Out parameter) The time at which the response will be sent.
* @param type One of MSG_TELEMETRY or MSG_COMMAND.
*/
bool constructNextResponse(const std::string& command,
void* uniqueId,
timeval& time,
int type);
CommRelayBase* m_CommRelay;
TimingService m_TimingService;
PLEXIL::ThreadMutex m_Mutex;
typedef std::multimap<timeval, ResponseMessage*> AgendaMap;
AgendaMap m_Agenda;
ResponseManagerMap& m_CmdToRespMgr;
pthread_t m_SimulatorThread;
bool m_Started;
bool m_Stop;
};
#endif // SIMULATOR_HH
| 35.395522 | 101 | 0.721484 | [
"object"
] |
bbb7cb4fcfdc0cf9caef400e4cbc60e6a8a4ac5d | 684 | cpp | C++ | leetcode2/minimumsizesubarraysum.cpp | WIZARD-CXY/pl | 22b7f5d81804f4e333d3cff6433364ba1a0ac7ef | [
"Apache-2.0"
] | 1 | 2016-01-20T08:26:34.000Z | 2016-01-20T08:26:34.000Z | leetcode2/minimumsizesubarraysum.cpp | WIZARD-CXY/pl | 22b7f5d81804f4e333d3cff6433364ba1a0ac7ef | [
"Apache-2.0"
] | 1 | 2015-10-21T05:38:17.000Z | 2015-11-02T07:42:55.000Z | leetcode2/minimumsizesubarraysum.cpp | WIZARD-CXY/pl | 22b7f5d81804f4e333d3cff6433364ba1a0ac7ef | [
"Apache-2.0"
] | null | null | null | class Solution {
public:
int minSubArrayLen(int s, vector<int>& nums) {
int start=0;
int end=0;
int sum=0;
int res=INT_MAX;
if(nums.size()==0){
return 0;
}
while(end<nums.size()){
sum+=nums[end];
if(sum>=s){
//try to make it smaller
while(sum-nums[start]>=s){
sum-=nums[start];
start++;
}
res=min(end-start+1,res);
}
end++;
}
if(res==INT_MAX){
return 0;
}
return res;
}
}; | 21.375 | 50 | 0.352339 | [
"vector"
] |
c7e1209e11971926293f867813ed2d0b13c1fcae | 425 | cpp | C++ | test/my_leetcode_bfs/tree_moving_time.cpp | zjuMrzhang/leetcode | 35ab78be5b9a2ef0fb35f99c146c2190b2bed148 | [
"MIT"
] | null | null | null | test/my_leetcode_bfs/tree_moving_time.cpp | zjuMrzhang/leetcode | 35ab78be5b9a2ef0fb35f99c146c2190b2bed148 | [
"MIT"
] | null | null | null | test/my_leetcode_bfs/tree_moving_time.cpp | zjuMrzhang/leetcode | 35ab78be5b9a2ef0fb35f99c146c2190b2bed148 | [
"MIT"
] | 1 | 2020-09-30T19:03:01.000Z | 2020-09-30T19:03:01.000Z |
/*
* tree: int val ,vector<TreeNode*> childrens
*/
struct TreeNode{
int val;
vector<TreeNode*> childrens;
}
int timeForLeave(TreeNode* root){
if(root==NULL) return 0;
int m=0;
for(auto t:root->childrens){
m=max(dfs(t),m);
}
return m;
}
int dfs(TreeNode* root){
if(root==NULL) return 0;
int ans=0;
for(auto t:root->childrens){
ans+=dfs(p);
}
return 1+ans;
} | 16.346154 | 45 | 0.569412 | [
"vector"
] |
c7ee9d5d6cf294b97f813e3efa24474375a9b1ff | 1,656 | hh | C++ | PacDetector/PacCylDetector.hh | brownd1978/FastSim | 05f590d72d8e7f71856fd833114a38b84fc7fd48 | [
"Apache-2.0"
] | null | null | null | PacDetector/PacCylDetector.hh | brownd1978/FastSim | 05f590d72d8e7f71856fd833114a38b84fc7fd48 | [
"Apache-2.0"
] | null | null | null | PacDetector/PacCylDetector.hh | brownd1978/FastSim | 05f590d72d8e7f71856fd833114a38b84fc7fd48 | [
"Apache-2.0"
] | null | null | null | /* Class: PacCylDetector
*
* A detector model consisting of a series of concentric cylinders, each with
* the same thickness and single point resolution. */
#ifndef PacCylDetector_HH
#define PacCylDetector_HH
#include "PacGeom/PacDetector.hh"
#include <vector>
#include <set>
class DetElem;
class DetType;
class DetSet;
class PacMeasurement;
class PacCylVoxelSet;
class TrkGeomTraj;
class PacCylDetector : public PacDetector {
public:
// PacCylDetector();
PacCylDetector();
virtual ~PacCylDetector();
// PacDetector interface
virtual const DetSet* detectorModel() const { return _detset; }
virtual const TrkVolume* detectorVolume() const { return _volume;}
virtual void setRandomEngine(HepRandomEngine* engine);
virtual bool findNextInter(const TrkGeomTraj* traj,DetIntersection& dinter) const;
// Specific interface
const std::vector<double>& getRadii() const { return _radii;}
const std::vector<PacCylVoxelSet*>& voxelSets() const { return _cvsets; }
protected:
std::vector<double> _radii;
std::vector<DetElem*> _elements; // ownership of all element objects
std::set<DetType*> _types; // type ownership: REMOVE ME!!!
std::set<PacMeasurement*> _measures; // measurement ownership for this detector
DetSet* _detset; // global set for the entire detector
std::vector<PacCylVoxelSet*> _cvsets; // voxel sets for each volume
std::vector<DetSet*> _volsets; // organization of elements into volumes
TrkVolume* _volume; // tracking volume, defined for the entire active volume
// cache: current voxel set to speed up navigation
mutable const PacCylVoxelSet* _cvset;
};
#endif // PacCylDetector_HH
| 35.234043 | 84 | 0.751208 | [
"vector",
"model"
] |
c7f9d45d70293f9cfcc744771c0ff2cbe0eece93 | 3,557 | cxx | C++ | Testing/Code/Numerics/FEM/itkFEMLinearSystemWrapperItpackTest2.cxx | dtglidden/ITK | ef0c16fee4fac904d6ab706b8f7d438d4062cd96 | [
"BSD-3-Clause"
] | 1 | 2017-07-31T18:41:02.000Z | 2017-07-31T18:41:02.000Z | Testing/Code/Numerics/FEM/itkFEMLinearSystemWrapperItpackTest2.cxx | dtglidden/ITK | ef0c16fee4fac904d6ab706b8f7d438d4062cd96 | [
"BSD-3-Clause"
] | null | null | null | Testing/Code/Numerics/FEM/itkFEMLinearSystemWrapperItpackTest2.cxx | dtglidden/ITK | ef0c16fee4fac904d6ab706b8f7d438d4062cd96 | [
"BSD-3-Clause"
] | null | null | null | /*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkFEMLinearSystemWrapperItpackTest2.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
// disable debug warnings in MS compiler
#ifdef _MSC_VER
#pragma warning(disable: 4786)
#endif
#include "itkFEMLinearSystemWrapperItpack.h"
#include <iostream>
#include <stdlib.h>
/* Testing for linear system wrappers */
int itkFEMLinearSystemWrapperItpackTest2( int argc, char * argv [] )
{
/* loop vars for printing */
unsigned int i;
unsigned int j;
/* declare wrapper */
itk::fem::LinearSystemWrapperItpack it;
/* system parameters */
unsigned int N = 3;
unsigned int nMatrices = 1;
unsigned int nVectors = 1;
unsigned int nSolutions = 1;
/* Set up the system */
it.SetSystemOrder(N);
it.SetNumberOfMatrices(nMatrices);
it.SetNumberOfVectors(nVectors);
it.SetNumberOfSolutions(nSolutions);
/* Set max non zeros in any matrix */
it.SetMaximumNonZeroValuesInMatrix(9);
/* Initialize memory */
for (i=0; i<nMatrices; i++)
{
it.InitializeMatrix(i);
}
for (i=0; i<nVectors; i++)
{
it.InitializeVector(i);
}
for (i=0; i<nSolutions; i++)
{
it.InitializeSolution(i);
}
/* matrix 0
* |11 0 0|
* | 0 22 0|
* | 0 0 33|
*/
it.SetMatrixValue(0,0,11,0);
it.SetMatrixValue(1,1,22,0);
it.SetMatrixValue(2,2,33,0);
/* print matrix 0 */
std::cout << "Matrix 0" << std::endl;
for(i=0; i<N; i++)
{
for (j=0; j<N; j++)
{
std::cout << it.GetMatrixValue(i,j,0) << " ";
}
std::cout << std::endl;
}
std::cout << std::endl;
/* Vector 0 = [1 2 3 ] */
it.SetVectorValue(0,1,0);
it.SetVectorValue(1,2,0);
it.SetVectorValue(2,3,0);
/* print Vector 0 */
std::cout << "Vector 0" << std::endl;
for (i=0; i<N; i++)
{
std::cout << it.GetVectorValue(i,0) << " ";
}
std::cout << std::endl << std::endl;
if( argc > 1 )
{
int method = atoi( argv[1] );
switch( method )
{
case 0:
it.JacobianConjugateGradient();
break;
case 1:
it.JacobianSemiIterative();
break;
case 2:
it.SuccessiveOverrelaxation();
break;
case 3:
it.SymmetricSuccessiveOverrelaxationConjugateGradient();
break;
case 4:
it.SymmetricSuccessiveOverrelaxationSuccessiveOverrelaxation();
break;
case 5:
it.ReducedSystemConjugateGradient();
break;
case 6:
it.ReducedSystemSemiIteration();
break;
}
}
/* solve system */
std::cout << "Solve for x in: Matrix 0 * x = Vector 0" << std::endl;
it.Solve();
std::cout << "Solution 0" << std::endl;
for (i=0; i<N; i++)
{
std::cout << it.GetSolutionValue(i,0) << " ";
}
std::cout << std::endl << std::endl;
/* destroy matrix,vector,solution */
it.DestroyMatrix(0);
it.DestroyVector(0);
it.DestroySolution(0);
std::cout << "Done." << std::endl;
return EXIT_SUCCESS;
}
| 22.371069 | 76 | 0.57661 | [
"vector"
] |
c7fd635caf917aa44704b18773564d7e401af365 | 4,058 | cpp | C++ | tools/Data2Sql/Data2Sql.cpp | FunctionLab/sleipnir | 6f74986ef03cb2df8deee1077ae180391557403a | [
"CC-BY-3.0"
] | 1 | 2021-03-21T23:17:12.000Z | 2021-03-21T23:17:12.000Z | tools/Data2Sql/Data2Sql.cpp | FunctionLab/sleipnir | 6f74986ef03cb2df8deee1077ae180391557403a | [
"CC-BY-3.0"
] | 4 | 2021-03-26T13:56:59.000Z | 2022-03-30T21:38:06.000Z | tools/Data2Sql/Data2Sql.cpp | FunctionLab/sleipnir | 6f74986ef03cb2df8deee1077ae180391557403a | [
"CC-BY-3.0"
] | null | null | null | /*****************************************************************************
* This file is provided under the Creative Commons Attribution 3.0 license.
*
* You are free to share, copy, distribute, transmit, or adapt this work
* PROVIDED THAT you attribute the work to the authors listed below.
* For more information, please see the following web page:
* http://creativecommons.org/licenses/by/3.0/
*
* This file is a component of the Sleipnir library for functional genomics,
* authored by:
* Curtis Huttenhower (chuttenh@princeton.edu)
* Mark Schroeder
* Maria D. Chikina
* Olga G. Troyanskaya (ogt@princeton.edu, primary contact)
*
* If you use this library, the included executable tools, or any related
* code in your work, please cite the following publication:
* Curtis Huttenhower, Mark Schroeder, Maria D. Chikina, and
* Olga G. Troyanskaya.
* "The Sleipnir library for computational functional genomics"
*****************************************************************************/
#include "stdafx.h"
#include "cmdline.h"
int main(int iArgs, char **aszArgs) {
static const size_t c_iBuffer = 1024;
gengetopt_args_info sArgs;
ifstream ifsm;
istream *pistm;
size_t iFile, i, j, iOne, iTwo, iFirst, iSecond, iCount;
float d;
map <string, size_t> mapstriGenes;
map<string, size_t>::const_iterator iterGene;
vector <string> vecstrLine;
char acBuffer[c_iBuffer];
vector <size_t> veciGenes;
if (cmdline_parser(iArgs, aszArgs, &sArgs)) {
cmdline_parser_print_help();
return 1;
}
CMeta Meta(sArgs.verbosity_arg);
if (sArgs.input_arg) {
ifsm.open(sArgs.input_arg);
pistm = &ifsm;
} else
pistm = &cin;
while (!pistm->eof()) {
pistm->getline(acBuffer, c_iBuffer - 1);
acBuffer[c_iBuffer - 1] = 0;
vecstrLine.clear();
CMeta::Tokenize(acBuffer, vecstrLine);
if (vecstrLine.size() != 2) {
cerr << "Ignoring line: " << acBuffer << endl;
continue;
}
mapstriGenes[vecstrLine[1]] = atoi(vecstrLine[0].c_str());
}
if (sArgs.input_arg)
ifsm.close();
for (iCount = iFile = 0; iFile < sArgs.inputs_num; ++iFile) {
CDataPair Dat;
if (sArgs.datasets_flag) {
cout << (iFile + 1) << '\t' << CMeta::Deextension(CMeta::Basename(sArgs.inputs[iFile])) <<
endl;
continue;
}
if (!Dat.Open(sArgs.inputs[iFile], false, !!sArgs.memmap_flag)) {
cerr << "Could not open: " << sArgs.inputs[iFile] << endl;
return 1;
}
veciGenes.resize(Dat.GetGenes());
for (i = 0; i < veciGenes.size(); ++i)
#ifdef _MSC_VER
(size_t)
#endif // _MSC_VER
veciGenes[i] = ((iterGene = mapstriGenes.find(Dat.GetGene(i))) ==
mapstriGenes.end()) ? -1 : iterGene->second;
for (i = 0; i < veciGenes.size(); ++i) {
if (!(i % 100))
cerr << i << '/' << veciGenes.size() << endl;
if ((iOne = veciGenes[i]) == -1)
continue;
for (j = (i + 1); j < veciGenes.size(); ++j)
if (((iTwo = veciGenes[j]) != -1) && !CMeta::IsNaN(d = Dat.Get(i, j))) {
if (iOne < iTwo) {
iFirst = iOne;
iSecond = iTwo;
} else {
iFirst = iTwo;
iSecond = iOne;
}
if (iCount % sArgs.block_arg)
cout << ',';
else
cout << "INSERT INTO " << sArgs.table_arg << " VALUES " << endl;
cout << '(' << (iFile + 1) << ',' << iFirst << ',' << iSecond << ',' <<
Dat.Quantize(d) << ')';
if (!(++iCount % sArgs.block_arg))
cout << ';' << endl;
}
}
}
if (iCount)
cout << ';' << endl;
return 0;
}
| 36.232143 | 102 | 0.5069 | [
"vector"
] |
2a027fdae5269656edcdec904135f7afac5c0d26 | 3,767 | c++ | C++ | test/5/src/main.c++ | maciek-27/Rgp | d28b5522e640e4c7b951f6861d97cbe52b0a35c9 | [
"MIT"
] | null | null | null | test/5/src/main.c++ | maciek-27/Rgp | d28b5522e640e4c7b951f6861d97cbe52b0a35c9 | [
"MIT"
] | null | null | null | test/5/src/main.c++ | maciek-27/Rgp | d28b5522e640e4c7b951f6861d97cbe52b0a35c9 | [
"MIT"
] | null | null | null | #include <iostream>
#include <exception>
#include <signal.h>
#include "netconn.h++"
#include "demo.h++"
#include "main.h++"
#include "manager.h++"
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <set>
#include <cstdlib>
#include <cstring>
pthread_mutex_t startSequenceMutex;
pthread_mutex_t allprogsStackMutex;
using namespace std;
// for set<ProgEntry> underlaying tree.
bool operator<(const ProgEntry& a, const ProgEntry& b) {
// comparing addresses of a and b would be wrong, as they may
// differ while referencing the same Demo class object.
return a.d < b.d;
}
set<ProgEntry> allprogs;
Server s;
static std::pair<int, char **> args;
void starter(std::istream & in, std::ostream & out)
{
Demo prog(in,out);
pthread_mutex_lock(&allprogsStackMutex);// prevent accidental stack
allprogs.insert(ProgEntry(&prog));// data structure destruction
pthread_mutex_unlock(&allprogsStackMutex);
cerr << "Trying to initialize connection" << endl;
try
{
int i = prog.Start(args.first, args.second); // start
cerr << "Connection finished with code " << i <<endl;// result
// on success
}
catch (exception)// exception caught. try to recover by ignoring it.
{
cerr << "Connection finished with exception, but app is fine."
<<endl;
}
pthread_mutex_lock(&allprogsStackMutex);
cerr << "Requesting erase of 1 app out of "<<allprogs.size()<<endl;;
// if ProgEntry exists (not deleted by localInterface func)
if (allprogs.find(ProgEntry(&prog)) != allprogs.end())
allprogs.erase(ProgEntry(&prog));//erase it.
cerr << endl;
pthread_mutex_unlock(&allprogsStackMutex);
return;
}
Manager manager;
void * localInterface(void * arg)
{
std::pair<int, char **>& args = *
reinterpret_cast<std::pair<int, char **> *>(arg);
manager.Start(args.first, args.second);
// as login as manager is running, everything is
// fine. Start shutdown procedure when it stops.
s.Stop();
cerr << "Server stopped correctly. ";
pthread_mutex_lock(&allprogsStackMutex);
cerr << "Requesting " << allprogs.size()<<" client apps to end."<<endl;
allprogs.clear();//stop all instances of program (ProgEntry
//destructor stops associated app)
cerr << endl;
pthread_mutex_unlock(&allprogsStackMutex);
return 0;
}
//used in netconn and other
void err(const char * s)
{
manager.Exit(0);
sleep(3);// make sure, it'll be displayed afted last message
cerr << "\nFatal error occured:" <<s << endl;
exit(1);
}
typedef void (*pfv)();
int port = 5000;
int main (int argc,char ** argv)
{
args.first = argc;
args.second = argv;
if(argc > 1)
{
stringstream ss;
ss<<argv[1];
for(int i = 0;i<argc;i++) {
if(strncmp(argv[i], "-port=", 6) == 0) {
std::string str(argv[i] + 6);
std::stringstream ss(str);
ss >> port;
}
}
}
pthread_t ctl_local;
pthread_mutex_init(&startSequenceMutex,NULL);
pthread_mutex_lock(&startSequenceMutex); // unlocked after
// clearing screen by
// Manager object
pthread_create(&ctl_local, NULL, localInterface, new std::pair<int, char**>(argc, argv));
pthread_mutex_lock(&startSequenceMutex);
pthread_mutex_unlock(&startSequenceMutex);
pthread_mutex_destroy(&startSequenceMutex);
pthread_mutex_init(&allprogsStackMutex,NULL);
cerr << "opening port " << port << endl;
signal(SIGPIPE, SIG_IGN); //disable signal (app has other ways
//of detecting connection errors)
s.Start(port,starter);
pthread_join(ctl_local,NULL);
cerr << "Game over" << endl;
pthread_mutex_destroy(&allprogsStackMutex);
return 0;
}
/*end of main function of program*/
| 26.907143 | 93 | 0.666313 | [
"object"
] |
2a0e9134914d0aae9c9e5fdcc0962a99ae2da4a2 | 3,176 | cpp | C++ | atcoder/arc116/B/main.cpp | Johniel/contests | b692eff913c20e2c1eb4ff0ce3cd4c57900594e0 | [
"Unlicense"
] | null | null | null | atcoder/arc116/B/main.cpp | Johniel/contests | b692eff913c20e2c1eb4ff0ce3cd4c57900594e0 | [
"Unlicense"
] | 19 | 2016-05-04T02:46:31.000Z | 2021-11-27T06:18:33.000Z | atcoder/arc116/B/main.cpp | Johniel/contests | b692eff913c20e2c1eb4ff0ce3cd4c57900594e0 | [
"Unlicense"
] | null | null | null | // atcoder/arc116/B/mani.cpp
// author: @___Johniel
// github: https://github.com/johniel/
#include <bits/stdc++.h>
#define each(i, c) for (auto& i : c)
#define unless(cond) if (!(cond))
using namespace std;
template<typename P, typename Q> ostream& operator << (ostream& os, pair<P, Q> p) { os << "(" << p.first << "," << p.second << ")"; return os; }
template<typename P, typename Q> istream& operator >> (istream& is, pair<P, Q>& p) { is >> p.first >> p.second; return is; }
template<typename T> ostream& operator << (ostream& os, vector<T> v) { os << "("; for (auto& i: v) os << i << ","; os << ")"; return os; }
template<typename T> istream& operator >> (istream& is, vector<T>& v) { for (auto& i: v) is >> i; return is; }
template<typename T> ostream& operator << (ostream& os, set<T> s) { os << "#{"; for (auto& i: s) os << i << ","; os << "}"; return os; }
template<typename K, typename V> ostream& operator << (ostream& os, map<K, V> m) { os << "{"; for (auto& i: m) os << i << ","; os << "}"; return os; }
template<typename T> inline T setmax(T& a, T b) { return a = std::max(a, b); }
template<typename T> inline T setmin(T& a, T b) { return a = std::min(a, b); }
using lli = long long int;
using ull = unsigned long long;
using point = complex<double>;
using str = string;
template<typename T> using vec = vector<T>;
constexpr array<int, 8> di({0, 1, -1, 0, 1, -1, 1, -1});
constexpr array<int, 8> dj({1, 0, 0, -1, 1, -1, -1, 1});
constexpr lli mod = 998244353;
namespace math {
lli extgcd(lli a, lli b, lli& x, lli& y)
{
lli g = a;
x = 1;
y = 0;
if (b != 0) {
g = extgcd(b, a % b, y, x);
y -= (a / b) * x;
}
return g;
}
lli mod_inverse(lli a, lli m)
{
lli x, y;
extgcd(a, m, x, y);
return (m + x % m) % m;
}
// nHm=n+m-1Cm
lli mod_pow(lli n, lli p)
{
if (p == 0) return 1;
if (p == 1) return n;
lli m = mod_pow(n, p / 2);
m *= m;
m %= mod;
if (p % 2) m = (m * n) % mod;
return m;
}
// ai * x = bi (mod mi)
// 蟻本P.261
// x=b(mod m)の(b,m)を返す
pair<lli, lli> liner_congruence(const vector<lli>& A, const vector<lli>& B, const vector<lli>& M)
{
lli x = 0, m = 1;
for (int i = 0; i < A.size(); ++i) {
lli a = A[i] * m;
lli b = B[i] - A[i] * x;
lli d = __gcd(M[i], a);
if (b % d) return make_pair(-1, -1);
lli t = b / d * mod_inverse(a / d, M[i] / d) % (M[i] / d);
x = x + m * t;
m *= M[i] / d;
}
return {x % m, m};
}
};
int main(int argc, char *argv[])
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.setf(ios_base::fixed);
cout.precision(15);
int n;
while (cin >> n) {
vec<lli> a(n);
cin >> a;
sort(a.begin(), a.end());
lli y = 0;
lli w = 1;
for (int i = 1; i < a.size(); ++i) {
(y += a[i] * w) %= mod;
(w *= 2) %= mod;
}
lli x = 0;
for (int i = 0; i + 1 < a.size(); ++i) {
(x += (a[i] * y) % mod) %= mod;
y = (y - a[i + 1] + mod) % mod * math::mod_inverse(2, mod) % mod;
}
for (int i = 0; i < a.size(); ++i) {
x += (a[i] * a[i]) % mod;
x %= mod;
}
cout << x << endl;
}
return 0;
}
| 27.145299 | 150 | 0.494962 | [
"vector"
] |
2a149ba2fc2afd5e9b7bf0eef8ce8be0047d14f2 | 4,001 | cpp | C++ | sources/students.cpp | Denis-Gorbachev/lab-01-parse | 1ba52c06921b52855671098829332d7f609cb332 | [
"MIT"
] | null | null | null | sources/students.cpp | Denis-Gorbachev/lab-01-parse | 1ba52c06921b52855671098829332d7f609cb332 | [
"MIT"
] | null | null | null | sources/students.cpp | Denis-Gorbachev/lab-01-parse | 1ba52c06921b52855671098829332d7f609cb332 | [
"MIT"
] | null | null | null | // Copyright 2021 Denis <denis.gorbachev2002@yandex.ru>
#include <students.hpp>
json get_data(const std::string& jsonPath){
std::ifstream file(jsonPath);
json data;
file >> data;
if (jsonPath.empty())
throw std::runtime_error("File's path is empty");
if (!file)
throw std::runtime_error("File does not exist");
if (!data.at("items").is_array())
throw std::runtime_error("Items in file should be arrays");
if (data.at("items").size() != data.at("_meta").at("count").get<size_t>())
throw std::runtime_error("Count of items is incorrect");
return data;
}
auto get_name(const json& j) -> std::string {
return j.get<std::string>();
}
auto get_debt(const json& j) -> std::any {
if (j.is_null())
return nullptr;
else if (j.is_string())
return j.get<std::string>();
else
return j.get<std::vector<std::string>>();
}
auto get_avg(const json& j) -> std::any {
if (j.is_null())
return nullptr;
else if (j.is_string())
return j.get<std::string>();
else if (j.is_number_float())
return j.get<double>();
else
return j.get<std::size_t>();
}
auto get_group(const json& j) -> std::any {
if (j.is_string())
return j.get<std::string>();
else
return j.get<std::size_t>();
}
void from_json(const json& j, Student & s) {
s.name = get_name(j.at("name"));
s.group = get_group(j.at("group"));
s.avg = get_avg(j.at("avg"));
s.debt = get_debt(j.at("debt"));
}
std::vector<Student> parse_file(json &data){
std::vector<Student> students;
for (auto const& item : data.at("items")) {
Student student;
from_json(item, student);
students.push_back(student);
}
return students;
}
void print(){
std::cout << "|" << " name" << std::setfill(' ') << std::setw(20)
<< "|" << " group" << std::setw(4) << "|" << " avg"
<< std::setw(6) << "|" << " debt" << std::setw(5)
<< "|" << std::endl << "|" << std::setfill('-') << std::setw(25)
<< "|" << std::setw(10) << "|" << std::setw(10) << "|"
<< std::setw(10) << "|" << std::endl;
}
void print(const Student& student, std::ostream& os){
os << "|" << std::setfill(' ') << std::setw(24)
<< std::left << std::any_cast<std::string>(student.name)
<< std::right << "|";
if (student.group.type() == typeid(std::string))
os << std::setw(9) << std::left
<< std::any_cast<std::string>(student.group)
<< std::right << "|";
else
os << std::setw(9) << std::left << std::any_cast<size_t>(student.group)
<< "|";
if ( student.avg.type() == typeid(std::string) )
os << std::setw(9) << std::left
<< std::any_cast<std::string>(student.avg) << "|";
else if (student.avg.type() == typeid(double))
os << std::setw(9) << std::left << std::any_cast<double>(student.avg)
<< "|";
else if (student.avg.type() == typeid(std::size_t))
os << std::setw(9) << std:: left << std::any_cast<size_t>(student.avg)
<< "|";
if (student.debt.type() == typeid(std::nullptr_t))
os << std::setw(9) << std::left << "null" << "|" << std::endl;
else if (student.debt.type() == typeid(std::string))
os << std::setw(9) << std::left
<< std::any_cast<std::string>(student.debt)
<< "|" << std::endl;
else os << std::setw(1) << std::left
<< std::any_cast<std::vector<std::string>>(student.debt).size()
<< std::setw(8) << std::left
<< " items" << std::right << "|" << std::endl;
os << std::right << "|" << std::setfill('-') << std::setw(25)
<< "|" << std::setw(10) << "|" << std::setw(10) << "|"
<< std::setw(10) << "|" << std::endl;
}
void print(std::vector<Student> &students, std::ostream &os) {
print();
for (Student &student : students){
print(student, os);
}
}
| 33.621849 | 79 | 0.52012 | [
"vector"
] |
2a1b93a05577d9166ac1788eaf7bf6c9250d6c02 | 6,652 | cpp | C++ | test/system/system.cpp | jamesmistry/measuro | 6485732a7decd8bd787a0100fefc7b3f708c80bd | [
"MIT"
] | null | null | null | test/system/system.cpp | jamesmistry/measuro | 6485732a7decd8bd787a0100fefc7b3f708c80bd | [
"MIT"
] | null | null | null | test/system/system.cpp | jamesmistry/measuro | 6485732a7decd8bd787a0100fefc7b3f708c80bd | [
"MIT"
] | null | null | null | /*!
* @file system.cpp
*
* Copyright (c) 2017 James Mistry
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <string>
#include <sstream>
#include <thread>
#include <cstddef>
#include <cassert>
#include <exception>
#include <functional>
#include <memory>
#include <atomic>
#include <vector>
#include <iostream>
#include "measuro.hpp"
using namespace measuro;
const std::size_t NUM_CREATED_METRICS = 1000;
const std::size_t NUM_THREADS = 2;
std::atomic<unsigned int> barrier_count;
class Outputter : public JsonRenderer
{
public:
Outputter(std::stringstream & destination)
: JsonRenderer(destination), m_destination(destination)
{
}
virtual void after() noexcept(false) override
{
JsonRenderer::after();
m_records.push_back(m_destination.str());
m_destination.str("");
}
std::vector<std::string> m_records;
private:
std::stringstream & m_destination;
};
struct Metrics
{
Registry reg;
IntHandle test_num_1;
IntHandle test_num_2;
UintHandle test_num_3;
RateOfIntHandle test_rate;
StringHandle test_str;
BoolHandle test_bool;
FloatHandle test_float;
SumOfIntHandle test_sum;
UintThrottle test_num_3_throt;
std::stringstream render_out;
Outputter renderer;
Metrics()
: test_num_1(reg.create_metric(INT::KIND, "TestNum1", "integer(s)",
"Test number metric 1", 0, std::chrono::milliseconds::zero())),
test_num_2(reg.create_metric(INT::KIND, "TestNum2", "integer(s)",
"Test number metric 2", 0, std::chrono::milliseconds::zero())),
test_num_3(reg.create_metric(UINT::KIND, "TestNum3", "integer(s)",
"Test number metric 3", 0, std::chrono::milliseconds::zero())),
test_rate(reg.create_metric(RATE::KIND, INT::KIND, test_num_1, "TestNumRate",
"integers", "Rate of test number 1", std::chrono::milliseconds::zero())),
test_str(reg.create_metric(STR::KIND, "TestStr",
"Test string metric", "val", std::chrono::milliseconds::zero())),
test_bool(reg.create_metric(BOOL::KIND, "TestBool", "Test bool metric", false,
"TRUE", "FALSE", std::chrono::milliseconds::zero())),
test_float(reg.create_metric(FLOAT::KIND, "TestFloat", "Test float metric", "floats",
0.0f, std::chrono::milliseconds::zero())),
test_sum(reg.create_metric(SUM::KIND, INT::KIND, "TestSum", "numbers", "Test sum metric", {test_num_1, test_num_2}, std::chrono::milliseconds::zero())),
test_num_3_throt(reg.create_throttle(test_num_3, std::chrono::milliseconds(1000), 1000)),
renderer(render_out)
{
reg.render_schedule(renderer, std::chrono::seconds(1));
}
};
void work_thread(Metrics & m, std::size_t thread_index)
{
std::stringstream thread_str;
thread_str << "thread" << thread_index;
++barrier_count;
while(barrier_count < NUM_THREADS);
for (std::size_t i=0;i<NUM_CREATED_METRICS;++i)
{
/*
* Create metrics.
*/
std::stringstream name_prefix, description;
name_prefix << "TestMetric" << i << '_' << thread_index << '_';
description << "Metric " << i << ',' << thread_index;
m.reg.create_metric(UINT::KIND, name_prefix.str() + "uint", "unsigned integer(s)", description.str(), 0, std::chrono::milliseconds::zero());
auto int_metric = m.reg.create_metric(INT::KIND, name_prefix.str() + "int", "integer(s)", description.str(), 0, std::chrono::milliseconds::zero());
auto float_metric = m.reg.create_metric(FLOAT::KIND, name_prefix.str() + "float", "float(s)", description.str(), 0, std::chrono::milliseconds::zero());
auto sum_metric = m.reg.create_metric(SUM::KIND, INT::KIND, name_prefix.str() + "sum_int", "sum", description.str(), {int_metric, m.test_num_1}, std::chrono::milliseconds::zero());
m.reg.create_metric(RATE::KIND, SUM::KIND, INT::KIND, sum_metric, name_prefix.str() + "rate_sum_int", "integers", "Rate of test number 1", std::chrono::milliseconds::zero());
/*
* Perform lookups.
*/
assert(m.reg(UINT::KIND, "TestNum3") == m.test_num_3);
assert(m.reg(INT::KIND, "TestNum1") == m.test_num_1);
assert(m.reg(STR::KIND, "TestStr") == m.test_str);
assert(m.reg(FLOAT::KIND, name_prefix.str() + "float") == float_metric);
assert(m.reg(BOOL::KIND, "TestBool") == m.test_bool);
}
std::this_thread::sleep_for (std::chrono::seconds(3 ));
for (std::size_t i=0;i<1000000;++i)
{
auto test_num_1 = m.reg(INT::KIND, "TestNum1");
++(*test_num_1);
auto test_str = m.reg(STR::KIND, "TestStr");
(*test_str) = thread_str.str();
auto test_float = m.reg(FLOAT::KIND, "TestFloat");
(*test_float) = i;
++m.test_num_3_throt;
}
assert(std::uint64_t(*m.test_num_3) < NUM_THREADS * 999999);
if (thread_index == 0)
{
(*m.test_str) = thread_str.str();
}
}
int main(int argc, char * argv[])
{
Metrics m;
std::vector<std::shared_ptr<std::thread> > threads;
barrier_count = 0;
for (std::size_t i=0;i<NUM_THREADS;++i)
{
auto t = std::make_shared<std::thread>(&work_thread, std::ref(m), i);
threads.push_back(t);
}
for (auto thread : threads)
{
thread->join();
}
assert(std::int64_t(*m.reg(INT::KIND, "TestNum1")) == NUM_THREADS * 1000000);
assert(float(*m.reg(FLOAT::KIND, "TestFloat")) == 999999);
for (auto record : m.renderer.m_records)
{
std::cout << record << '\n';
}
return 0;
}
| 34.112821 | 188 | 0.648527 | [
"vector"
] |
2a3c99998081e6aa66a77f6e95205cfcefb6b5a7 | 4,518 | cpp | C++ | src/glfoundation/light.cpp | ChinYing-Li/OpenGL-cart | 2625dfb194a65d6b277f6c3c57602319000bce16 | [
"MIT"
] | 2 | 2021-06-03T03:36:35.000Z | 2021-09-18T07:25:24.000Z | src/glfoundation/light.cpp | ChinYing-Li/OpenGL-cart | 2625dfb194a65d6b277f6c3c57602319000bce16 | [
"MIT"
] | null | null | null | src/glfoundation/light.cpp | ChinYing-Li/OpenGL-cart | 2625dfb194a65d6b277f6c3c57602319000bce16 | [
"MIT"
] | null | null | null | #include <assert.h>
#include <iostream>
#include "light.h"
#include "glfoundation/texturemanager.h"
namespace Cluster{
Light::Light():
m_const_atten(10.0f),
m_linear_atten(10.0f),
m_shadowbuffer(800, 600)
{}
bool Light::
is_enabled()
{
return m_on_state;
}
void Light::
turn_on()
{
m_on_state = true;
return;
}
void Light::
turn_off()
{
m_on_state = false;
return;
}
void Light::
setup_shadowbuffer(unsigned int width, unsigned int height)
{
m_shadowbuffer.create(width, height);
m_shadowbuffer.bind(FrameBuffer::NORMAL);
m_shadowbuffer.disable_color();
m_shadowbuffer.release();
}
Light::Type Light::
get_type() const
{
return m_type;
}
void Light::
set_color(const glm::vec3 new_color)
{
m_color = new_color;
}
void Light::
set_const_attenuation(const float const_atten)
{
m_const_atten = const_atten;
}
void Light::
set_linear_attenuation(const float linear_atten)
{
m_linear_atten = linear_atten;
}
void Light::
set_quadratic_attenuation(const float quad_atten)
{
m_quadratic_atten = quad_atten;
return;
}
void Light::
set_ambient_strength(const glm::vec3 new_amb_strength)
{
m_ambient_strength = new_amb_strength;
}
void Light::
set_shader(int index,
GLuint& shaderID)
{
glUseProgram(shaderID);
glUniform1i(glGetUniformLocation(shaderID, "lights[0].is_enabled"), int(m_on_state));
glUniform1i(glGetUniformLocation(shaderID, "lights[0].is_local"), int(m_is_local));
glUniform1i(glGetUniformLocation(shaderID, "lights[0].is_spotlight"), int(m_is_spotlight));
glUniform3f(glGetUniformLocation(shaderID, "lights[0].color"), m_color.r, m_color.g, m_color.b);
glUniform3f(glGetUniformLocation(shaderID, "lights[0].ambient_strength"), m_ambient_strength.r, m_ambient_strength.g, m_ambient_strength.b);
glUniform1f(glGetUniformLocation(shaderID, "lights[0].constant_atten"), m_const_atten);
glUniform1f(glGetUniformLocation(shaderID, "lights[0].linear_atten"), m_linear_atten);
glUniform1f(glGetUniformLocation(shaderID, "lights[0].quadratic_atten"), m_quadratic_atten);
return;
}
/*
*
*/
SpotLight::
SpotLight():
Light(),
m_type(Type::POINTLIGHT)
{
m_is_local = true;
m_is_spotlight = true;
}
SpotLight::
SpotLight(const glm::vec3 position,
glm::vec3 conedirection,
const float cutoff,
const float exponent):
Light(),
m_cutoff(cutoff),
m_exponent(exponent),
m_position(position),
m_conedirection(conedirection)
{
m_is_local = true;
m_is_spotlight = true;
}
void SpotLight::
set_shader(int index,
GLuint& shaderID)
{
Light::set_shader(index, shaderID);
glUniform3fv(glGetUniformLocation(shaderID, "lights[0].position"), 1, &m_position[0]);
glUniform3fv(glGetUniformLocation(shaderID, "lights[0].cone_direction"), 1, &m_conedirection[0]);
glUniform1f(glGetUniformLocation(shaderID, "lights[0].spot_cos_cutoff"), m_cutoff);
glUniform1f(glGetUniformLocation(shaderID, "lights[0].exponent"), m_exponent);
return;
}
/*
*
*/
PointLight::
PointLight():
Light()
{
m_is_local = true;
}
PointLight::
PointLight(const glm::vec3 position):
Light()
{
m_position = position;
}
void PointLight::
set_shader(int index,
GLuint& shaderID)
{
glUseProgram(shaderID);
Light::set_shader(index, shaderID);
glUniform3fv(glGetUniformLocation(shaderID, "lights[0].position"), 1, &m_position[0]);
}
void PointLight::
setup_shadow_map(const std::vector<int>& dimension)
{
assert (dimension.size() >= 1);
m_shadow_cubemap = std::make_shared<TextureCubemap>(TextureManager::generate_shadow_cubemap(dimension[0]));
}
std::shared_ptr<Texture> PointLight::
get_shadowmap()
{
return m_shadow_cubemap;
}
/*
*
*/
DirectionalLight::
DirectionalLight(const glm::vec3 direction):
Light(),
m_direction(direction)
{}
void DirectionalLight::
set_shader(int index,
GLuint& shaderID)
{
Light::set_shader(index, shaderID);
glUniform3fv(glGetUniformLocation(shaderID, "lights[0].direction"), 1, &m_direction[0]);
}
void DirectionalLight::
set_direction(const glm::vec3 direction)
{
m_direction = direction;
}
void DirectionalLight::
setup_shadow_map(const std::vector<int>& dimension)
{
assert (dimension.size() >= 2);
m_shadow_map = std::make_shared<Texture2D>(TextureManager::generate_shadow_map(dimension[0], dimension[1]));
}
std::shared_ptr<Texture> DirectionalLight::
get_shadowmap()
{
return m_shadow_map;
}
} // namespace Cluster
| 21.211268 | 144 | 0.719124 | [
"vector"
] |
2a3cd6b528cd12bf2fd3a50dc256ab6f7811e091 | 1,393 | hpp | C++ | include/gpcxx/app/normalize.hpp | gchoinka/gpcxx | 143398d8a12cdc39735e6ef50c3f8a44a6e6360f | [
"BSL-1.0"
] | 21 | 2015-05-15T08:01:37.000Z | 2020-11-12T07:28:54.000Z | include/gpcxx/app/normalize.hpp | gchoinka/gpcxx | 143398d8a12cdc39735e6ef50c3f8a44a6e6360f | [
"BSL-1.0"
] | 2 | 2015-03-26T23:48:04.000Z | 2016-02-29T14:16:37.000Z | include/gpcxx/app/normalize.hpp | gchoinka/gpcxx | 143398d8a12cdc39735e6ef50c3f8a44a6e6360f | [
"BSL-1.0"
] | 9 | 2015-02-12T21:39:01.000Z | 2020-10-01T05:14:08.000Z | /*
gpcxx/app/normalize.hpp
Copyright 2013 Karsten Ahnert
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or
copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef GPCXX_APP_NORMALIZE_HPP_DEFINED
#define GPCXX_APP_NORMALIZE_HPP_DEFINED
#include <gpcxx/eval/regression_fitness.hpp>
#include <utility>
#include <cmath>
namespace gpcxx {
template< typename Vector >
std::pair< typename Vector::value_type , typename Vector::value_type >
normalize( Vector &x )
{
typedef typename Vector::value_type value_type;
value_type mean = 0.0 , sq_mean = 0.0;
for( auto d : x )
{
mean += d;
sq_mean += d * d;
}
mean /= double( x.size() );
sq_mean /= double( x.size() );
value_type stdev = std::sqrt( sq_mean - mean * mean );
for( auto &d : x )
{
d = ( d - mean ) / stdev;
}
return std::make_pair( mean , stdev );
}
template< typename Value , size_t Dim , typename Sequence >
std::array< std::pair< Value , Value > , Dim + 1 >
normalize_regression( regression_training_data< Value , Dim , Sequence > & data )
{
std::array< std::pair< Value , Value > , Dim > ret;
ret[0] = normalize( data.y );
for( size_t i=0 ; i<Dim ; ++i )
ret[i+1] = normalize( data.x[i] );
return ret;
}
} // namespace gpcxx
#endif // GPCXX_APP_NORMALIZE_HPP_DEFINED
| 23.216667 | 81 | 0.643934 | [
"vector"
] |
2a41e2e3d8e6783f1dd4dca6630cf18715f305e3 | 2,033 | cpp | C++ | Contrib-Intel/RSD-PSME-RMM/common/agent-framework/src/module/model/trusted_module.cpp | opencomputeproject/Rack-Manager | e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a | [
"MIT"
] | 5 | 2019-11-11T07:57:26.000Z | 2022-03-28T08:26:53.000Z | Contrib-Intel/RSD-PSME-RMM/common/agent-framework/src/module/model/trusted_module.cpp | opencomputeproject/Rack-Manager | e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a | [
"MIT"
] | 3 | 2019-09-05T21:47:07.000Z | 2019-09-17T18:10:45.000Z | Contrib-Intel/RSD-PSME-RMM/common/agent-framework/src/module/model/trusted_module.cpp | opencomputeproject/Rack-Manager | e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a | [
"MIT"
] | 11 | 2019-07-20T00:16:32.000Z | 2022-01-11T14:17:48.000Z | /*!
* @copyright
* Copyright (c) 2017-2019 Intel Corporation
*
* @copyright
* 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
*
* @copyright
* http://www.apache.org/licenses/LICENSE-2.0
*
* @copyright
* 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 <agent-framework/module/constants/compute.hpp>
#include "agent-framework/module/model/trusted_module.hpp"
using namespace agent_framework::model;
const enums::Component TrustedModule::component = enums::Component::TrustedModule;
const enums::CollectionName TrustedModule::collection_name = enums::CollectionName::TrustedModules;
TrustedModule::TrustedModule(const std::string& parent_uuid, enums::Component parent_type) :
Resource{parent_uuid, parent_type} {}
TrustedModule::~TrustedModule() {}
json::Json TrustedModule::to_json() const {
json::Json json = json::Json();
json[literals::Status::STATUS] = get_status().to_json();
json[literals::Oem::OEM] = get_oem().to_json();
json[literals::TrustedModule::INTERFACE_TYPE] = get_interface_type();
json[literals::TrustedModule::FIRMWARE_VERSION] = get_firmware_version();
return json;
}
TrustedModule TrustedModule::from_json(const json::Json& json) {
TrustedModule trusted_module{};
trusted_module.set_status(attribute::Status::from_json(json[literals::Status::STATUS]));
trusted_module.set_oem(attribute::Oem::from_json(json[literals::Oem::OEM]));
trusted_module.set_interface_type(json[literals::TrustedModule::INTERFACE_TYPE]);
trusted_module.set_firmware_version(json[literals::TrustedModule::FIRMWARE_VERSION]);
return trusted_module;
}
| 35.666667 | 99 | 0.753074 | [
"model"
] |
2a44ac48d96505f78aa8b3afa4ba7832eac9ca71 | 1,382 | cpp | C++ | codeforces/global_9/replacemex.cpp | udayan14/Competitive_Coding | 79e23fdeb909b4161a193d88697a4fe5f4fbbdce | [
"MIT"
] | null | null | null | codeforces/global_9/replacemex.cpp | udayan14/Competitive_Coding | 79e23fdeb909b4161a193d88697a4fe5f4fbbdce | [
"MIT"
] | null | null | null | codeforces/global_9/replacemex.cpp | udayan14/Competitive_Coding | 79e23fdeb909b4161a193d88697a4fe5f4fbbdce | [
"MIT"
] | null | null | null | #include<iostream>
#include<cstring>
#include<vector>
using namespace std;
int getmex(int a[], int n){
for(int i=0 ; i<n ; i++){
if(a[i]==0)
return i;
}
return -1;
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin >> t;
while(t--){
int n;
cin >> n;
int a[n];
int mex[n+1];
memset(mex,0,sizeof(mex));
for(int i=0 ; i<n ; i++){
cin >> a[i];
mex[a[i]]++;
}
int curr;
vector<int> output;
while(true){
curr = getmex(mex,n+1);
if(curr==n){
bool flag = false;
for(int i=0 ; i<n ; i++){
if(a[i]!=i)
{
output.push_back(i);
mex[n]++;
mex[a[i]]--;
a[i] = n;
flag = true;
break;
}
}
if(!flag) break;
}
else{
output.push_back(curr);
mex[a[curr]]--;
mex[curr]++;
a[curr] = curr;
}
}
cout << output.size() << "\n";
for(auto i : output)
cout << i+1 << " ";
cout << "\n";
}
}
| 22.290323 | 44 | 0.323444 | [
"vector"
] |
2a52d312e203a16d6d33d88bd7ace521ca28e422 | 4,406 | hpp | C++ | plugin/namer.hpp | timgates42/libcsp | 0135434f56a64697c6087db4cfc8ce91e9f665e8 | [
"MIT"
] | 1 | 2020-04-08T06:35:38.000Z | 2020-04-08T06:35:38.000Z | plugin/namer.hpp | sthagen/libcsp | deaf02da974fb217dca2196f7faecafe9f06a66a | [
"MIT"
] | null | null | null | plugin/namer.hpp | sthagen/libcsp | deaf02da974fb217dca2196f7faecafe9f06a66a | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2020, Yanhui Shi <lime.syh at gmail dot com>
* All rights reserved.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef LIBCSP_PLUGIN_NAMER_HPP
#define LIBCSP_PLUGIN_NAMER_HPP
#include <iostream>
#include <string>
#include <vector>
#include "fs.hpp"
namespace csp {
const std::string csp_proc_prefix = "csp___";
const std::string default_installed_prefix = "/usr/local/";
const std::string subpath_share = "share/libcsp/";
const std::vector<std::string> namer_type_labels = {
"async", "sync", "timer", "other"
};
typedef enum {
NAMER_TYPE_ASYNC,
NAMER_TYPE_SYNC,
NAMER_TYPE_TIMER,
NAMER_TYPE_OTHER
} namer_type_t;
class namer_entity_t {
public:
size_t id;
std::string name;
namer_type_t type;
namer_entity_t() = default;
namer_entity_t(size_t id, std::string name, namer_type_t type):
id(id), name(name), type(type)
{};
};
class namer_t: public filesystem_t {
public:
namer_t(): next_id(0), prefix(csp_proc_prefix) {};
void initialize(bool is_building_libcsp, std::string installed_prefix,
std::string working_dir) {
this->set_working_dir(working_dir);
this->next_id = this->read_session(this->full_path(session_name));
/* If we are building our apps, set the next_id to that stored in session
* file which is in the `share` path. */
if (this->next_id == 0 && !is_building_libcsp) {
if (installed_prefix[installed_prefix.size() - 1] != slash) {
installed_prefix.push_back(slash);
}
this->next_id = this->read_session(
installed_prefix + subpath_share + session_name
);
}
}
int current_id(void) {
return this->next_id - 1;
}
std::string current_name(void) {
return this->latest_name;
}
std::string next_name(std::string fn_name, namer_type_t type) {
this->latest_name = this->format(
namer_entity_t(this->next_id, fn_name, type)
);
this->next_id++;
return this->latest_name;
}
bool is_generated(std::string name) {
for (auto label: namer_type_labels) {
std::string prefix(this->prefix + label);
if (name.substr(0, prefix.size()) == prefix) {
return true;
}
}
return false;
}
bool parse(std::string name, namer_entity_t &entity) {
if (!this->is_generated(name)) {
return false;
}
name = name.substr(this->prefix.size());
for (int i = 0; i < 2; i++) {
auto idx = name.find('_');
if (idx == std::string::npos) {
return false;
}
std::string part = name.substr(0, idx);
if (i == 0) {
bool found = false;
for (int j = 0; j < namer_type_labels.size(); j++) {
if (part == namer_type_labels[j]) {
found = true;
entity.type = (namer_type_t)j;
break;
}
}
if (!found) {
return false;
}
} else {
std::stringstream ss(part);
if (!(ss >> entity.id)) {
return false;
}
}
name = name.substr(idx + 1);
}
entity.name = name;
return true;
}
void save(void) {
auto file = this->open(this->full_path(session_name), std::fstream::out);
if (!file.is_open()) {
std::cerr << err_prefix << "failed to save session info." << std::endl;
exit(EXIT_FAILURE);
}
file << this->next_id;
file.close();
}
private:
std::string format(namer_entity_t entity) {
std::stringstream ss;
ss << this->prefix
<< namer_type_labels[entity.type]
<< "_"
<< entity.id
<< "_"
<< entity.name;
return ss.str();
}
int next_id;
std::string prefix;
std::string latest_name;
} namer;
}
#endif
| 25.468208 | 77 | 0.629823 | [
"vector"
] |
2a54c719d39ea6b165f762bbd58c70c2de4eba5b | 2,310 | cpp | C++ | codedrills/ICPC_practice_3/d.cpp | Shahraaz/CP_S5 | 2cfb5467841d660c1e47cb8338ea692f10ca6e60 | [
"MIT"
] | 3 | 2020-02-08T10:34:16.000Z | 2020-02-09T10:23:19.000Z | codedrills/ICPC_practice_3/d.cpp | Shahraaz/CP_S5 | 2cfb5467841d660c1e47cb8338ea692f10ca6e60 | [
"MIT"
] | null | null | null | codedrills/ICPC_practice_3/d.cpp | Shahraaz/CP_S5 | 2cfb5467841d660c1e47cb8338ea692f10ca6e60 | [
"MIT"
] | 2 | 2020-10-02T19:05:32.000Z | 2021-09-08T07:01:49.000Z | #include <bits/stdc++.h>
using namespace std;
#define ll long long int
#define ff first
#define ss second
#define pb push_back
#define mp make_pair
#define deb(x) cout << #x << " " << x << "\n";
#define MAX 9223372036854775807
#define MIN -9223372036854775807
#define setbits(n) __builtin_popcountll(n)
#define mkunique(a) \
sort(a.begin(), a.end()); \
a.resize(unique(a.begin(), a.end()) - a.begin());
#define print(s) \
for (ll u : s) \
cout << u << " "; \
cout << "\n";
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
const ll mod = 1e9 + 7;
#include "/debug.h"
const int N = 21;
ll w;
vector<ll> a(4);
ll n, m;
vector<vector<ll>> g(N, vector<ll>(N));
ll dp[N][N][N][N];
ll sum(ll x, ll y, ll tx, ll ty)
{
ll ans = g[tx][ty];
db(x, y, tx, ty);
if (x != 0)
ans -= g[x - 1][ty];
if (y != 0)
ans -= g[tx][y - 1];
if (x != 0 && y != 0)
ans += g[x - 1][y - 1];
db(ans);
return ans;
}
ll go(ll x, ll y, ll tx, ll ty)
{
if (x == tx && y == ty)
return a[sum(x, y, tx, ty)];
if (dp[x][y][tx][ty] != -1)
return dp[x][y][tx][ty];
ll ans = mod * mod, lenx = tx - x + 1, leny = ty - y + 1;
if (sum(x, y, tx, ty) < 4)
ans = a[sum(x, y, tx, ty)];
for (ll i = x; i < tx; i++)
ans = min(ans, w * leny + go(x, y, i, ty) + go(x + 1, y, tx, ty));
for (ll i = y; i < ty; i++)
ans = min(ans, w * lenx + go(x, y, tx, i) + go(x, y + 1, tx, ty));
return dp[x][y][tx][ty] = ans;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
ll TT = clock();
cin >> a[0] >> a[1] >> a[2] >> a[3] >> w;
cin >> n >> m;
for (ll i = 0; i < n; i++)
{
for (ll j = 0; j < m; j++)
cin >> g[i][j];
}
for (ll i = 1; i < n; i++)
g[i][0] += g[i - 1][0];
for (ll i = 1; i < m; i++)
g[0][i] += g[0][i - 1];
for (ll i = 1; i < n; i++)
{
for (ll j = 1; j < m; j++)
{
g[i][j] += g[i - 1][j] + g[i][j - 1] - g[i - 1][j - 1];
}
}
memset(dp, -1, sizeof(dp));
cout << go(0, 0, n, m);
cerr << "\n\nTIME: " << (long double)(clock() - TT) / CLOCKS_PER_SEC << " sec\n";
TT = clock();
return 0;
} | 24.83871 | 85 | 0.441126 | [
"vector"
] |
2a5a282bfb5659366dae7eae71a50000f31f2ba9 | 6,288 | cxx | C++ | HLT/TRD/AliHLTTRDOfflineClusterizerComponent.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | null | null | null | HLT/TRD/AliHLTTRDOfflineClusterizerComponent.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 2 | 2016-11-25T08:40:56.000Z | 2019-10-11T12:29:29.000Z | HLT/TRD/AliHLTTRDOfflineClusterizerComponent.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | null | null | null | // $Id$
//**************************************************************************
//* This file is property of and copyright by the ALICE HLT Project *
//* ALICE Experiment at CERN, All rights reserved. *
//* *
//* Primary Authors: *
//* for The ALICE HLT Project. *
//* *
//* Permission to use, copy, modify and distribute this software and its *
//* documentation strictly for non-commercial purposes is hereby granted *
//* without fee, provided that the above copyright notice appears in all *
//* copies and that both the copyright notice and this permission notice *
//* appear in the supporting documentation. The authors make no claims *
//* about the suitability of this software for any purpose. It is *
//* provided "as is" without express or implied warranty. *
//**************************************************************************
/** @file AliHLTTRDOfflineClusterizerComponent.cxx
@author Theodor Rascanu
@date
@brief Processes digits (with MC) and raw data (without MC). For debug purposes only
*/
// see header file for class documentation //
// or //
// refer to README to build package //
// or //
// visit http://web.ift.uib.no/~kjeks/doc/alice-hlt //
#include "AliHLTTRDOfflineClusterizerComponent.h"
#include "AliHLTTRDDefinitions.h"
#include "AliHLTTRDClusterizer.h"
#include "AliHLTTRDUtils.h"
#include "AliCDBManager.h"
#include "TTree.h"
#include "TClonesArray.h"
#include "TObjString.h"
ClassImp(AliHLTTRDOfflineClusterizerComponent)
AliHLTTRDOfflineClusterizerComponent::AliHLTTRDOfflineClusterizerComponent()
:AliHLTTRDClusterizerComponent()
{
// Default constructor
}
AliHLTTRDOfflineClusterizerComponent::~AliHLTTRDOfflineClusterizerComponent()
{
// Destructor
// Work is Done in DoDeInit()
}
AliHLTComponent* AliHLTTRDOfflineClusterizerComponent::Spawn()
{
// Spawn function, return new instance of this class
return new AliHLTTRDOfflineClusterizerComponent;
};
const char* AliHLTTRDOfflineClusterizerComponent::GetComponentID()
{
// Return the component ID const char *
return "TRDOfflineClusterizer"; // The ID of this component
}
void AliHLTTRDOfflineClusterizerComponent::GetInputDataTypes( vector<AliHLTComponent_DataType>& list)
{
// Get the list of input data
list.clear();
AliHLTTRDClusterizerComponent::GetInputDataTypes(list);
list.push_back(AliHLTTRDDefinitions::fgkDigitsDataType);
}
AliHLTComponentDataType AliHLTTRDOfflineClusterizerComponent::GetOutputDataType()
{
// Get the output data type
return kAliHLTMultipleDataType;
}
int AliHLTTRDOfflineClusterizerComponent::GetOutputDataTypes(AliHLTComponentDataTypeList& tgtList)
{
// Get the output data types
tgtList.clear();
AliHLTTRDClusterizerComponent::GetOutputDataTypes(tgtList);
tgtList.push_back(AliHLTTRDDefinitions::fgkHiLvlClusterDataType);
return tgtList.size();
}
void AliHLTTRDOfflineClusterizerComponent::GetOutputDataSize( unsigned long& constBase, double& inputMultiplier )
{
// Get the output data size
AliHLTTRDClusterizerComponent::GetOutputDataSize(constBase, inputMultiplier);
constBase += 500;
inputMultiplier *= 10;
}
int AliHLTTRDOfflineClusterizerComponent::SetParams()
{
int iResult = AliHLTTRDClusterizerComponent::SetParams();
// here we need the coordinate transformation as we want to ship full flavoured clusters
#ifndef HAVE_NOT_ALITRD_CLUSTERIZER_r42837
fClusterizer->SetSkipTransform(kFALSE);
#endif
return iResult;
}
int AliHLTTRDOfflineClusterizerComponent::DoEvent(const AliHLTComponent_EventData& evtData, const AliHLTComponent_BlockData* blocks,
AliHLTComponent_TriggerData& trigData, AliHLTUInt8_t* outputPtr,
AliHLTUInt32_t& size, vector<AliHLTComponent_BlockData>& outputBlocks )
{
if(!IsDataEvent())return 0;
if(!GetFirstInputBlock(AliHLTTRDDefinitions::fgkDigitsDataType))
return AliHLTTRDClusterizerComponent::DoEvent(evtData, blocks, trigData, outputPtr, size, outputBlocks );
AliHLTUInt32_t offset = 0;
for(const TObject *iter = GetFirstInputObject(AliHLTTRDDefinitions::fgkDigitsDataType); iter; iter = GetNextInputObject())
{
AliTRDclusterizer* clusterizer = new AliTRDclusterizer("TRDCclusterizer", "TRDCclusterizer");
clusterizer->SetReconstructor(fReconstructor);
clusterizer->SetUseLabels(kTRUE);
TTree* digitsTree = dynamic_cast<TTree*>(const_cast<TObject*>(iter));
clusterizer->ReadDigits(digitsTree);
clusterizer->MakeClusters();
TClonesArray* clusterArray = clusterizer->RecPoints();
clusterizer->SetClustersOwner(kFALSE);
AliHLTUInt32_t spec = GetSpecification(iter);
if(fHighLevelOutput){
if(fEmulateHLTClusters){
TClonesArray* temp = clusterArray;
clusterArray = new TClonesArray(*temp);
temp->Delete();
delete temp;
AliHLTTRDUtils::EmulateHLTClusters(clusterArray);
}
TObjString strg;
strg.String() += clusterizer->GetNTimeBins();
PushBack(clusterArray, AliHLTTRDDefinitions::fgkHiLvlClusterDataType, spec);
PushBack(&strg, AliHLTTRDDefinitions::fgkHiLvlClusterDataType, spec);
} else {
Int_t nTimeBins = clusterizer->GetNTimeBins();
Int_t addedSize = AliHLTTRDUtils::AddClustersToOutput(clusterArray, outputPtr+offset, nTimeBins);
AliHLTComponentBlockData bd;
FillBlockData( bd );
bd.fOffset = offset;
bd.fSize = addedSize;
bd.fSpecification = spec;
bd.fDataType = AliHLTTRDDefinitions::fgkClusterDataType;
outputBlocks.push_back( bd );
HLTDebug( "BD ptr 0x%x, offset %i, size %i, dataType %s, spec 0x%x ", bd.fPtr, bd.fOffset, bd.fSize, DataType2Text(bd.fDataType).c_str(), bd.fSpecification);
offset += addedSize;
}
clusterArray->Delete();
delete clusterArray;
delete clusterizer;
}
return 0;
}
| 37.652695 | 158 | 0.676845 | [
"vector"
] |
398010bc0d731e9d8f6d0dfeaac9e6fcec9564e9 | 1,443 | cpp | C++ | HackerEarth/CodeMonk/GraphTheoryII/MonkInTheSecretServices.cpp | shiva92/Contests | 720bb3699f774a6ea1f99e888e0cd784e63130c8 | [
"Apache-2.0"
] | null | null | null | HackerEarth/CodeMonk/GraphTheoryII/MonkInTheSecretServices.cpp | shiva92/Contests | 720bb3699f774a6ea1f99e888e0cd784e63130c8 | [
"Apache-2.0"
] | null | null | null | HackerEarth/CodeMonk/GraphTheoryII/MonkInTheSecretServices.cpp | shiva92/Contests | 720bb3699f774a6ea1f99e888e0cd784e63130c8 | [
"Apache-2.0"
] | null | null | null | #include <bits/stdc++.h>
const int mod = 1e9 + 7;
using namespace std;
int t, n, m, x, y, c, s, a, h;
vector< pair<int, int >> v[107];
int d[3][107];
int shortestpath() {
int temp [] = {s, a, h};
for (int ii = 0; ii < 3; ii++) {
for (int i = 0; i <= 100; i++) d[ii][i] = 1e9; d[ii][temp[ii]] = 0;
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> p;
p.push({0, temp[ii]});
while (!p.empty()) {
auto pr = p.top(); p.pop();
if (d[ii][pr.second] < pr.first) continue;
int j = pr.second;
for (int i = 0; i < int(v[j].size()); i++) {
auto u = v[j][i];
if (d[ii][u.first] > (d[ii][j] + u.second)) {
d[ii][u.first] = d[ii][j] + u.second;
p.push({d[ii][u.first], u.first});
}
}
}
}
int res = 0;
for (int i = 1; i <= n; i++) {
if (i != s && i != a && i != h) {
if (res < (d[0][i] + (2 * d[1][i]) + d[2][i]))
res = (d[0][i] + (2 * d[1][i]) + d[2][i]);
}
}
return res;
}
int main() {
#ifndef ONLINE_JUDGE
freopen("/Users/seeva92/Workspace/Contests/1.txt", "r", stdin);
freopen("/Users/seeva92/Workspace/Contests/2.txt", "w", stdout);
#endif
ios::sync_with_stdio(false);
cin.tie(0);
cin >> t;
while (t--) {
cin >> n >> m;
for (int i = 0; i <= 100; i++) { v[i].clear();}
for (int i = 1; i <= m; i++) {
cin >> x >> y >> c;
v[x].push_back({y, c});
v[y].push_back({x, c});
}
cin >> s >> a >> h;
cout << shortestpath() << '\n';
}
}
| 24.05 | 84 | 0.483714 | [
"vector"
] |
398723acecae875a0968061901396167d69d4dd5 | 3,225 | cpp | C++ | desktop/notes/loginwindow.cpp | pyprism/Hiren-Notes-Desktop-Client | 54ad18322f41c567be4db1e0b51e93772da950de | [
"MIT"
] | null | null | null | desktop/notes/loginwindow.cpp | pyprism/Hiren-Notes-Desktop-Client | 54ad18322f41c567be4db1e0b51e93772da950de | [
"MIT"
] | null | null | null | desktop/notes/loginwindow.cpp | pyprism/Hiren-Notes-Desktop-Client | 54ad18322f41c567be4db1e0b51e93772da950de | [
"MIT"
] | null | null | null | #include "loginwindow.h"
#include "ui_loginwindow.h"
#include <QDebug>
#include <QByteArray>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonValue>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QUrl>
#include <QUrlQuery>
#include <QJsonValue>
#include <QJsonObject>
LoginWindow::LoginWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::LoginWindow),
mNetMan(new QNetworkAccessManager(this)),
mNetReply(nullptr),
mDataBuffer(new QByteArray)
{
ui->setupUi(this);
BuildLogin();
}
void LoginWindow::BuildLogin(){
ui->password_lineEdit->setEchoMode(QLineEdit::Password);
ui->encrytion_lineEdit->setEchoMode(QLineEdit::Password);
ui->login_pushButton->setIcon (QIcon(":/new/img/login.svg"));
this->setWindowTitle ("Login");
QSettings settings;
ui->server_lineEdit->setText (QVariant(settings.value ("url")).toString ());
ui->username_lineEdit->setText (QVariant(settings.value ("username")).toString ());
}
LoginWindow::~LoginWindow()
{
delete ui;
}
void LoginWindow::NetworkCleanup (){
mNetReply->deleteLater ();
mNetReply = nullptr;
mDataBuffer->clear ();
}
void LoginWindow::on_login_pushButton_clicked()
{
ui->statusBar->clearMessage();
QSettings settings;
const QString url = ui->server_lineEdit->text ();
const QString username = ui->username_lineEdit->text ();
const QString password = ui->password_lineEdit->text ();
const QString encryption = ui->encrytion_lineEdit->text ();
settings.setValue ("url", url);
settings.setValue ("username", username);
const QUrl URL(url + "/api/auth/");
QNetworkRequest req(URL);
req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
// QUrlQuery urlQuery;
// urlQuery.addQueryItem ("username", username);
// urlQuery.addQueryItem ("password", password);
// QUrl params;
// params.setQuery (urlQuery);
QByteArray postData;
postData.append("username=" + username + "&password=" + password);
mNetReply = mNetMan->post(req, postData);
connect(mNetReply, &QIODevice::readyRead, this, &LoginWindow::OnResponseReadyToRead);
connect(mNetReply, &QNetworkReply::finished, this, &LoginWindow::OnResponseReadFinished);
// connect (reply, &QNetworkReply::readyRead, [reply]() {
// qDebug() << "Ready to read from reply";
// });
// connect (reply, &QNetworkReply::sslErrors, [this] (QList<QSslError> error) {
// qWarning () << "Ssl error: " << error;
// });
}
void LoginWindow::OnResponseReadyToRead()
{
mDataBuffer->append (mNetReply->readAll ());
}
void LoginWindow::OnResponseReadFinished()
{
QJsonDocument doc = QJsonDocument::fromJson (*mDataBuffer);
QJsonObject object = doc.object ();
QJsonValue token = object.value ("token");
QJsonValue err = object.value ("error");
if(token.isUndefined()) {
ui->statusBar->setStyleSheet("color: red");
ui->statusBar->showMessage("Username/Password is not valid");
} else {
QSettings settings;
settings.setValue("token", token.toString());
}
NetworkCleanup();
}
| 27.10084 | 93 | 0.684341 | [
"object"
] |
39885919fcea1eeebd19fa791a894af9325cadd5 | 36,170 | cpp | C++ | common/tcpcl/src/TcpclV3BidirectionalLink.cpp | ewb4/HDTN | a0e577351bd28c3aeb7e656e03a2d93cf84712a0 | [
"NASA-1.3"
] | null | null | null | common/tcpcl/src/TcpclV3BidirectionalLink.cpp | ewb4/HDTN | a0e577351bd28c3aeb7e656e03a2d93cf84712a0 | [
"NASA-1.3"
] | null | null | null | common/tcpcl/src/TcpclV3BidirectionalLink.cpp | ewb4/HDTN | a0e577351bd28c3aeb7e656e03a2d93cf84712a0 | [
"NASA-1.3"
] | null | null | null | #include <string>
#include <iostream>
#include "TcpclV3BidirectionalLink.h"
#include <boost/lexical_cast.hpp>
#include <boost/make_shared.hpp>
#include <boost/make_unique.hpp>
#include "Uri.h"
#include <boost/endian/conversion.hpp>
TcpclV3BidirectionalLink::TcpclV3BidirectionalLink(
const std::string & implementationStringForCout,
const uint64_t shutdownMessageReconnectionDelaySecondsToSend,
const bool deleteSocketAfterShutdown,
const bool contactHeaderMustReply,
const uint16_t desiredKeepAliveIntervalSeconds,
boost::asio::io_service * externalIoServicePtr,
const unsigned int maxUnacked,
const uint64_t maxBundleSizeBytes,
const uint64_t maxFragmentSize,
const uint64_t myNodeId,
const std::string & expectedRemoteEidUriStringIfNotEmpty
) :
M_BASE_IMPLEMENTATION_STRING_FOR_COUT(implementationStringForCout),
M_BASE_SHUTDOWN_MESSAGE_RECONNECTION_DELAY_SECONDS_TO_SEND(shutdownMessageReconnectionDelaySecondsToSend),
M_BASE_DESIRED_KEEPALIVE_INTERVAL_SECONDS(desiredKeepAliveIntervalSeconds),
M_BASE_DELETE_SOCKET_AFTER_SHUTDOWN(deleteSocketAfterShutdown),
M_BASE_CONTACT_HEADER_MUST_REPLY(contactHeaderMustReply),
//ion 3.7.2 source code tcpcli.c line 1199 uses service number 0 for contact header:
//isprintf(eid, sizeof eid, "ipn:" UVAST_FIELDSPEC ".0", getOwnNodeNbr());
M_BASE_THIS_TCPCL_EID_STRING(Uri::GetIpnUriString(myNodeId, 0)),
m_base_keepAliveIntervalSeconds(desiredKeepAliveIntervalSeconds),
m_base_localIoServiceUniquePtr((externalIoServicePtr == NULL) ? boost::make_unique<boost::asio::io_service>() : std::unique_ptr<boost::asio::io_service>()),
m_base_ioServiceRef((externalIoServicePtr == NULL) ? (*m_base_localIoServiceUniquePtr) : (*externalIoServicePtr)),
m_base_noKeepAlivePacketReceivedTimer(m_base_ioServiceRef),
m_base_needToSendKeepAliveMessageTimer(m_base_ioServiceRef),
m_base_sendShutdownMessageTimeoutTimer(m_base_ioServiceRef),
m_base_shutdownCalled(false),
m_base_readyToForward(false), //bundleSource
m_base_sinkIsSafeToDelete(false), //bundleSink
m_base_tcpclShutdownComplete(true), //bundleSource
m_base_useLocalConditionVariableAckReceived(false), //for bundleSource destructor only
m_base_dataReceivedServedAsKeepaliveReceived(false),
m_base_dataSentServedAsKeepaliveSent(false),
m_base_reconnectionDelaySecondsIfNotZero(3), //bundle source only, default 3 unless remote says 0 in shutdown message
M_BASE_MAX_UNACKED_BUNDLES_IN_PIPELINE(maxUnacked), //bundle sink has MAX_UNACKED(maxUnacked + 5),
M_BASE_UNACKED_BUNDLE_CB_SIZE(maxUnacked + 5),
m_base_bytesToAckCb(M_BASE_UNACKED_BUNDLE_CB_SIZE),
m_base_bytesToAckCbVec(M_BASE_UNACKED_BUNDLE_CB_SIZE),
m_base_fragmentBytesToAckCbVec(M_BASE_UNACKED_BUNDLE_CB_SIZE),
m_base_fragmentVectorIndexCbVec(M_BASE_UNACKED_BUNDLE_CB_SIZE),
M_BASE_MAX_FRAGMENT_SIZE(maxFragmentSize),
//stats
m_base_totalBundlesAcked(0),
m_base_totalBytesAcked(0),
m_base_totalBundlesSent(0),
m_base_totalFragmentedAcked(0),
m_base_totalFragmentedSent(0),
m_base_totalBundleBytesSent(0)
{
m_base_tcpclV3RxStateMachine.SetMaxReceiveBundleSizeBytes(maxBundleSizeBytes);
m_base_tcpclV3RxStateMachine.SetContactHeaderReadCallback(boost::bind(&TcpclV3BidirectionalLink::BaseClass_ContactHeaderCallback, this, boost::placeholders::_1, boost::placeholders::_2, boost::placeholders::_3));
m_base_tcpclV3RxStateMachine.SetDataSegmentContentsReadCallback(boost::bind(&TcpclV3BidirectionalLink::BaseClass_DataSegmentCallback, this, boost::placeholders::_1, boost::placeholders::_2, boost::placeholders::_3));
m_base_tcpclV3RxStateMachine.SetAckSegmentReadCallback(boost::bind(&TcpclV3BidirectionalLink::BaseClass_AckCallback, this, boost::placeholders::_1));
m_base_tcpclV3RxStateMachine.SetBundleRefusalCallback(boost::bind(&TcpclV3BidirectionalLink::BaseClass_BundleRefusalCallback, this, boost::placeholders::_1));
m_base_tcpclV3RxStateMachine.SetNextBundleLengthCallback(boost::bind(&TcpclV3BidirectionalLink::BaseClass_NextBundleLengthCallback, this, boost::placeholders::_1));
m_base_tcpclV3RxStateMachine.SetKeepAliveCallback(boost::bind(&TcpclV3BidirectionalLink::BaseClass_KeepAliveCallback, this));
m_base_tcpclV3RxStateMachine.SetShutdownMessageCallback(boost::bind(&TcpclV3BidirectionalLink::BaseClass_ShutdownCallback, this, boost::placeholders::_1, boost::placeholders::_2, boost::placeholders::_3, boost::placeholders::_4));
m_base_handleTcpSendCallback = boost::bind(&TcpclV3BidirectionalLink::BaseClass_HandleTcpSend, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred);
m_base_handleTcpSendShutdownCallback = boost::bind(&TcpclV3BidirectionalLink::BaseClass_HandleTcpSendShutdown, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred);
for (unsigned int i = 0; i < M_BASE_UNACKED_BUNDLE_CB_SIZE; ++i) {
m_base_fragmentBytesToAckCbVec[i].reserve(100);
}
if (expectedRemoteEidUriStringIfNotEmpty.empty()) {
M_BASE_EXPECTED_REMOTE_CONTACT_HEADER_EID_STRING_IF_NOT_EMPTY = "";
}
else {
uint64_t remoteNodeId, remoteServiceId;
if (!Uri::ParseIpnUriString(expectedRemoteEidUriStringIfNotEmpty, remoteNodeId, remoteServiceId)) {
std::cerr << M_BASE_IMPLEMENTATION_STRING_FOR_COUT << ": error in constructor: error parsing remote EID URI string " << expectedRemoteEidUriStringIfNotEmpty
<< " .. TCPCL will fail the Contact Header Callback. Correct the \"nextHopEndpointId\" field in the outducts config." << std::endl;
}
else {
//ion 3.7.2 source code tcpcli.c line 1199 uses service number 0 for contact header:
//isprintf(eid, sizeof eid, "ipn:" UVAST_FIELDSPEC ".0", getOwnNodeNbr());
M_BASE_EXPECTED_REMOTE_CONTACT_HEADER_EID_STRING_IF_NOT_EMPTY = Uri::GetIpnUriString(remoteNodeId, 0);
}
}
}
TcpclV3BidirectionalLink::~TcpclV3BidirectionalLink() {
}
void TcpclV3BidirectionalLink::BaseClass_TryToWaitForAllBundlesToFinishSending() {
boost::mutex localMutex;
boost::mutex::scoped_lock lock(localMutex);
m_base_useLocalConditionVariableAckReceived = true;
std::size_t previousUnacked = std::numeric_limits<std::size_t>::max();
for (unsigned int attempt = 0; attempt < 10; ++attempt) {
const std::size_t numUnacked = Virtual_GetTotalBundlesUnacked();
if (numUnacked) {
std::cout << M_BASE_IMPLEMENTATION_STRING_FOR_COUT << ": notice: destructor waiting on " << numUnacked << " unacked bundles" << std::endl;
std::cout << " acked: " << m_base_totalBundlesAcked << std::endl;
std::cout << " total sent: " << m_base_totalBundlesSent << std::endl;
if (previousUnacked > numUnacked) {
previousUnacked = numUnacked;
attempt = 0;
}
m_base_localConditionVariableAckReceived.timed_wait(lock, boost::posix_time::milliseconds(250)); // call lock.unlock() and blocks the current thread
//thread is now unblocked, and the lock is reacquired by invoking lock.lock()
continue;
}
break;
}
m_base_useLocalConditionVariableAckReceived = false;
}
std::size_t TcpclV3BidirectionalLink::Virtual_GetTotalBundlesAcked() {
return m_base_totalBundlesAcked;
}
std::size_t TcpclV3BidirectionalLink::Virtual_GetTotalBundlesSent() {
return m_base_totalBundlesSent;
}
std::size_t TcpclV3BidirectionalLink::Virtual_GetTotalBundlesUnacked() {
return m_base_totalBundlesSent - m_base_totalBundlesAcked;
}
std::size_t TcpclV3BidirectionalLink::Virtual_GetTotalBundleBytesAcked() {
return m_base_totalBytesAcked;
}
std::size_t TcpclV3BidirectionalLink::Virtual_GetTotalBundleBytesSent() {
return m_base_totalBundleBytesSent;
}
std::size_t TcpclV3BidirectionalLink::Virtual_GetTotalBundleBytesUnacked() {
return m_base_totalBundleBytesSent - m_base_totalBytesAcked;
}
unsigned int TcpclV3BidirectionalLink::Virtual_GetMaxTxBundlesInPipeline() {
return M_BASE_MAX_UNACKED_BUNDLES_IN_PIPELINE;
}
void TcpclV3BidirectionalLink::BaseClass_HandleTcpSend(const boost::system::error_code& error, std::size_t bytes_transferred) {
if (error) {
std::cerr << M_BASE_IMPLEMENTATION_STRING_FOR_COUT << ": error in BaseClass_HandleTcpSend: " << error.message() << std::endl;
BaseClass_DoTcpclShutdown(true, false);
}
else {
Virtual_OnTcpSendSuccessful_CalledFromIoServiceThread();
}
}
void TcpclV3BidirectionalLink::BaseClass_HandleTcpSendShutdown(const boost::system::error_code& error, std::size_t bytes_transferred) {
if (error) {
std::cerr << M_BASE_IMPLEMENTATION_STRING_FOR_COUT << ": error in BaseClass_HandleTcpSendShutdown: " << error.message() << std::endl;
}
else {
m_base_sendShutdownMessageTimeoutTimer.cancel();
}
}
void TcpclV3BidirectionalLink::Virtual_OnTcpSendSuccessful_CalledFromIoServiceThread() {}
void TcpclV3BidirectionalLink::BaseClass_DataSegmentCallback(padded_vector_uint8_t & dataSegmentDataVec, bool isStartFlag, bool isEndFlag) {
uint64_t bytesToAck = 0;
if (isStartFlag && isEndFlag) { //optimization for whole (non-fragmented) data
bytesToAck = dataSegmentDataVec.size(); //grab the size now in case vector gets stolen in m_wholeBundleReadyCallback
Virtual_WholeBundleReady(dataSegmentDataVec);
//std::cout << dataSegmentDataSharedPtr->size() << std::endl;
}
else {
if (isStartFlag) {
m_base_fragmentedBundleRxConcat.resize(0);
}
m_base_fragmentedBundleRxConcat.insert(m_base_fragmentedBundleRxConcat.end(), dataSegmentDataVec.begin(), dataSegmentDataVec.end()); //concatenate
bytesToAck = m_base_fragmentedBundleRxConcat.size();
if (isEndFlag) { //fragmentation complete
Virtual_WholeBundleReady(m_base_fragmentedBundleRxConcat);
}
}
//send ack
if ((static_cast<unsigned int>(CONTACT_HEADER_FLAGS::REQUEST_ACK_OF_BUNDLE_SEGMENTS)) & (static_cast<unsigned int>(m_base_contactHeaderFlags))) {
if (m_base_tcpSocketPtr) {
TcpAsyncSenderElement * el = new TcpAsyncSenderElement();
el->m_underlyingData.resize(1);
Tcpcl::GenerateAckSegment(el->m_underlyingData[0], bytesToAck);
el->m_constBufferVec.emplace_back(boost::asio::buffer(el->m_underlyingData[0])); //only one element so resize not needed
el->m_onSuccessfulSendCallbackByIoServiceThreadPtr = &m_base_handleTcpSendCallback;
m_base_dataSentServedAsKeepaliveSent = true; //sending acks can also be used in lieu of keepalives
m_base_tcpAsyncSenderPtr->AsyncSend_ThreadSafe(el);
}
}
}
void TcpclV3BidirectionalLink::BaseClass_AckCallback(uint64_t totalBytesAcknowledged) {
const unsigned int readIndex = m_base_bytesToAckCb.GetIndexForRead();
if (readIndex == UINT32_MAX) { //empty
std::cerr << M_BASE_IMPLEMENTATION_STRING_FOR_COUT << ": error: AckCallback called with empty queue" << std::endl;
}
else {
std::vector<uint64_t> & currentFragmentBytesVec = m_base_fragmentBytesToAckCbVec[readIndex];
if (currentFragmentBytesVec.size()) { //this was fragmented
uint64_t & fragIdxRef = m_base_fragmentVectorIndexCbVec[readIndex];
const uint64_t expectedFragByteToAck = currentFragmentBytesVec[fragIdxRef++];
if (fragIdxRef == currentFragmentBytesVec.size()) {
currentFragmentBytesVec.resize(0);
}
if (expectedFragByteToAck == totalBytesAcknowledged) {
++m_base_totalFragmentedAcked;
}
else {
std::cerr << M_BASE_IMPLEMENTATION_STRING_FOR_COUT << ": error in BaseClass_AckCallback: wrong fragment bytes acked: expected "
<< expectedFragByteToAck << " but got " << totalBytesAcknowledged << std::endl;
}
}
//now ack the entire bundle
if (currentFragmentBytesVec.empty()) {
if (m_base_bytesToAckCbVec[readIndex] == totalBytesAcknowledged) {
++m_base_totalBundlesAcked;
m_base_totalBytesAcked += m_base_bytesToAckCbVec[readIndex];
m_base_bytesToAckCb.CommitRead();
Virtual_OnSuccessfulWholeBundleAcknowledged();
if (m_base_useLocalConditionVariableAckReceived) {
m_base_localConditionVariableAckReceived.notify_one();
}
}
else {
std::cerr << M_BASE_IMPLEMENTATION_STRING_FOR_COUT << ": error in BaseClass_AckCallback: wrong bytes acked: expected "
<< m_base_bytesToAckCbVec[readIndex] << " but got " << totalBytesAcknowledged << std::endl;
}
}
}
}
void TcpclV3BidirectionalLink::BaseClass_RestartNoKeepaliveReceivedTimer() {
// m_base_keepAliveIntervalSeconds * 2.5 seconds =>
//If no message (KEEPALIVE or other) has been received for at least
//twice the keepalive_interval, then either party MAY terminate the
//session by transmitting a one-byte SHUTDOWN message (as described in
//Table 2) and by closing the TCP connection.
m_base_noKeepAlivePacketReceivedTimer.expires_from_now(boost::posix_time::milliseconds(m_base_keepAliveIntervalSeconds * 2500)); //cancels active timer with cancel flag in callback
m_base_noKeepAlivePacketReceivedTimer.async_wait(boost::bind(&TcpclV3BidirectionalLink::BaseClass_OnNoKeepAlivePacketReceived_TimerExpired, this, boost::asio::placeholders::error));
m_base_dataReceivedServedAsKeepaliveReceived = false;
}
void TcpclV3BidirectionalLink::BaseClass_KeepAliveCallback() {
std::cout << M_BASE_IMPLEMENTATION_STRING_FOR_COUT << ": received keepalive packet\n";
BaseClass_RestartNoKeepaliveReceivedTimer(); //cancels and restarts timer
}
void TcpclV3BidirectionalLink::BaseClass_OnNoKeepAlivePacketReceived_TimerExpired(const boost::system::error_code& e) {
if (e != boost::asio::error::operation_aborted) {
// Timer was not cancelled, take necessary action.
if (m_base_dataReceivedServedAsKeepaliveReceived) {
std::cout << M_BASE_IMPLEMENTATION_STRING_FOR_COUT << ": data received served as keepalive\n";
BaseClass_RestartNoKeepaliveReceivedTimer();
}
else {
std::cout << M_BASE_IMPLEMENTATION_STRING_FOR_COUT << ": shutting down tcpcl session due to inactivity or missing keepalive\n";
BaseClass_DoTcpclShutdown(true, true);
}
}
else {
//std::cout << "timer cancelled\n";
}
}
void TcpclV3BidirectionalLink::BaseClass_RestartNeedToSendKeepAliveMessageTimer() {
//Shift right 1 (divide by 2) if we are omitting sending a keepalive, so for example,
//if our keep alive interval is 10 seconds, but we are omitting sending a keepalive due to a Forward() function call,
//then evaluate if sending a keepalive is necessary 5 seconds from now.
//But if there is no data being sent from us, do not omit keepalives every 10 seconds.
const unsigned int shift = static_cast<unsigned int>(m_base_dataSentServedAsKeepaliveSent);
const unsigned int millisecondMultiplier = 1000u >> shift;
const boost::posix_time::time_duration expiresFromNowDuration = boost::posix_time::milliseconds(m_base_keepAliveIntervalSeconds * millisecondMultiplier);
//std::cout << "try send keepalive in " << expiresFromNowDuration.total_milliseconds() << " millisec\n";
m_base_needToSendKeepAliveMessageTimer.expires_from_now(expiresFromNowDuration);
m_base_needToSendKeepAliveMessageTimer.async_wait(boost::bind(&TcpclV3BidirectionalLink::BaseClass_OnNeedToSendKeepAliveMessage_TimerExpired, this, boost::asio::placeholders::error));
m_base_dataSentServedAsKeepaliveSent = false;
}
void TcpclV3BidirectionalLink::BaseClass_OnNeedToSendKeepAliveMessage_TimerExpired(const boost::system::error_code& e) {
if (e != boost::asio::error::operation_aborted) {
// Timer was not cancelled, take necessary action.
//SEND KEEPALIVE PACKET
if (m_base_tcpSocketPtr) {
if (!m_base_dataSentServedAsKeepaliveSent) {
TcpAsyncSenderElement * el = new TcpAsyncSenderElement();
el->m_underlyingData.resize(1);
Tcpcl::GenerateKeepAliveMessage(el->m_underlyingData[0]);
el->m_constBufferVec.emplace_back(boost::asio::buffer(el->m_underlyingData[0])); //only one element so resize not needed
el->m_onSuccessfulSendCallbackByIoServiceThreadPtr = &m_base_handleTcpSendCallback;
m_base_tcpAsyncSenderPtr->AsyncSend_NotThreadSafe(el); //timer runs in same thread as socket so special thread safety not needed
}
BaseClass_RestartNeedToSendKeepAliveMessageTimer();
}
}
else {
//std::cout << "timer cancelled\n";
}
}
void TcpclV3BidirectionalLink::BaseClass_ShutdownCallback(bool hasReasonCode, SHUTDOWN_REASON_CODES shutdownReasonCode,
bool hasReconnectionDelay, uint64_t reconnectionDelaySeconds)
{
std::cout << M_BASE_IMPLEMENTATION_STRING_FOR_COUT << ": remote has requested shutdown\n";
if (hasReasonCode) {
std::cout << M_BASE_IMPLEMENTATION_STRING_FOR_COUT << " reason provided by remote for shutdown: "
<< ((shutdownReasonCode == SHUTDOWN_REASON_CODES::BUSY) ? "busy" :
(shutdownReasonCode == SHUTDOWN_REASON_CODES::IDLE_TIMEOUT) ? "idle timeout" :
(shutdownReasonCode == SHUTDOWN_REASON_CODES::VERSION_MISMATCH) ? "version mismatch" : "unassigned") << std::endl;
}
if (hasReconnectionDelay) {
m_base_reconnectionDelaySecondsIfNotZero = reconnectionDelaySeconds; //for bundle source only
std::cout << M_BASE_IMPLEMENTATION_STRING_FOR_COUT << ": remote has requested reconnection delay of " << reconnectionDelaySeconds << " seconds" << std::endl;
}
BaseClass_DoTcpclShutdown(false, false);
}
void TcpclV3BidirectionalLink::BaseClass_DoTcpclShutdown(bool sendShutdownMessage, bool reasonWasTimeOut) {
boost::asio::post(m_base_ioServiceRef, boost::bind(&TcpclV3BidirectionalLink::BaseClass_DoHandleSocketShutdown, this, sendShutdownMessage, reasonWasTimeOut));
}
void TcpclV3BidirectionalLink::BaseClass_DoHandleSocketShutdown(bool sendShutdownMessage, bool reasonWasTimeOut) {
if (!m_base_shutdownCalled) {
m_base_shutdownCalled = true;
// Called from post() to keep socket shutdown within io_service thread.
m_base_readyToForward = false;
//if (!m_base_sinkIsSafeToDelete) { this is unnecessary if statement
if (sendShutdownMessage && m_base_tcpAsyncSenderPtr && m_base_tcpSocketPtr) {
std::cout << M_BASE_IMPLEMENTATION_STRING_FOR_COUT << " Sending shutdown packet to cleanly close tcpcl.. " << std::endl;
TcpAsyncSenderElement * el = new TcpAsyncSenderElement();
el->m_underlyingData.resize(1);
//For the requested delay, in seconds, the value 0 SHALL be interpreted as an infinite delay,
//i.e., that the connecting node MUST NOT re - establish the connection.
if (reasonWasTimeOut) {
Tcpcl::GenerateShutdownMessage(el->m_underlyingData[0], true, SHUTDOWN_REASON_CODES::IDLE_TIMEOUT, true, M_BASE_SHUTDOWN_MESSAGE_RECONNECTION_DELAY_SECONDS_TO_SEND);
}
else {
Tcpcl::GenerateShutdownMessage(el->m_underlyingData[0], false, SHUTDOWN_REASON_CODES::UNASSIGNED, true, M_BASE_SHUTDOWN_MESSAGE_RECONNECTION_DELAY_SECONDS_TO_SEND);
}
el->m_constBufferVec.emplace_back(boost::asio::buffer(el->m_underlyingData[0])); //only one element so resize not needed
el->m_onSuccessfulSendCallbackByIoServiceThreadPtr = &m_base_handleTcpSendShutdownCallback;
m_base_tcpAsyncSenderPtr->AsyncSend_NotThreadSafe(el); //HandleSocketShutdown runs in same thread as socket so special thread safety not needed
m_base_sendShutdownMessageTimeoutTimer.expires_from_now(boost::posix_time::seconds(3));
}
else {
m_base_sendShutdownMessageTimeoutTimer.expires_from_now(boost::posix_time::seconds(0));
}
m_base_sendShutdownMessageTimeoutTimer.async_wait(boost::bind(&TcpclV3BidirectionalLink::BaseClass_OnSendShutdownMessageTimeout_TimerExpired, this, boost::asio::placeholders::error));
}
}
void TcpclV3BidirectionalLink::BaseClass_OnSendShutdownMessageTimeout_TimerExpired(const boost::system::error_code& e) {
if (e != boost::asio::error::operation_aborted) {
// Timer was not cancelled, take necessary action.
std::cout << M_BASE_IMPLEMENTATION_STRING_FOR_COUT << " Notice: No TCPCL shutdown message was sent (not required)." << std::endl;
}
else {
//std::cout << "timer cancelled\n";
std::cout << M_BASE_IMPLEMENTATION_STRING_FOR_COUT << " TCPCL shutdown message was sent." << std::endl;
}
//final code to shut down tcp sockets
if (M_BASE_DELETE_SOCKET_AFTER_SHUTDOWN) { //for bundle sink
std::cout << M_BASE_IMPLEMENTATION_STRING_FOR_COUT << " deleting TCP Async Sender" << std::endl;
m_base_tcpAsyncSenderPtr.reset();
}
if (m_base_tcpSocketPtr) {
if (m_base_tcpSocketPtr->is_open()) {
try {
std::cout << M_BASE_IMPLEMENTATION_STRING_FOR_COUT << " shutting down TCP socket.." << std::endl;
m_base_tcpSocketPtr->shutdown(boost::asio::socket_base::shutdown_type::shutdown_both);
}
catch (const boost::system::system_error & e) {
std::cerr << M_BASE_IMPLEMENTATION_STRING_FOR_COUT << " error in BaseClass_OnSendShutdownMessageTimeout_TimerExpired: " << e.what() << std::endl;
}
try {
std::cout << M_BASE_IMPLEMENTATION_STRING_FOR_COUT << " closing TCP socket socket.." << std::endl;
m_base_tcpSocketPtr->close();
}
catch (const boost::system::system_error & e) {
std::cerr << M_BASE_IMPLEMENTATION_STRING_FOR_COUT << " error in BaseClass_OnSendShutdownMessageTimeout_TimerExpired: " << e.what() << std::endl;
}
}
if (M_BASE_DELETE_SOCKET_AFTER_SHUTDOWN) { //for bundle sink
std::cout << M_BASE_IMPLEMENTATION_STRING_FOR_COUT << " deleting TCP Socket" << std::endl;
if (m_base_tcpSocketPtr.use_count() != 1) {
std::cerr << "error m_base_tcpSocketPtr.use_count() != 1" << std::endl;
}
m_base_tcpSocketPtr = boost::shared_ptr<boost::asio::ip::tcp::socket>();
}
else {
//don't delete the tcp socket or async sender because the Forward function is multi-threaded without a mutex to
//increase speed, so prevent a race condition that would cause a null pointer exception
}
}
m_base_needToSendKeepAliveMessageTimer.cancel();
m_base_noKeepAlivePacketReceivedTimer.cancel();
m_base_tcpclV3RxStateMachine.InitRx(); //reset states
m_base_tcpclShutdownComplete = true;
m_base_sinkIsSafeToDelete = true;
Virtual_OnTcpclShutdownComplete_CalledFromIoServiceThread();
}
bool TcpclV3BidirectionalLink::BaseClass_Forward(const uint8_t* bundleData, const std::size_t size) {
std::vector<uint8_t> vec(bundleData, bundleData + size);
return BaseClass_Forward(vec);
}
bool TcpclV3BidirectionalLink::BaseClass_Forward(std::vector<uint8_t> & dataVec) {
static std::unique_ptr<zmq::message_t> nullZmqMessagePtr;
return BaseClass_Forward(nullZmqMessagePtr, dataVec, false);
}
bool TcpclV3BidirectionalLink::BaseClass_Forward(zmq::message_t & dataZmq) {
static std::vector<uint8_t> unusedVecMessage;
std::unique_ptr<zmq::message_t> zmqMessageUniquePtr = boost::make_unique<zmq::message_t>(std::move(dataZmq));
const bool success = BaseClass_Forward(zmqMessageUniquePtr, unusedVecMessage, true);
if (!success) { //if failure
//move message back to param
if (zmqMessageUniquePtr) {
dataZmq = std::move(*zmqMessageUniquePtr);
}
}
return success;
}
bool TcpclV3BidirectionalLink::BaseClass_Forward(std::unique_ptr<zmq::message_t> & zmqMessageUniquePtr, std::vector<uint8_t> & vecMessage, const bool usingZmqData) {
if (!m_base_readyToForward) {
std::cerr << "link not ready to forward yet" << std::endl;
return false;
}
std::size_t dataSize;
const uint8_t * dataToSendPtr;
if (usingZmqData) { //this is zmq data
dataSize = zmqMessageUniquePtr->size();
dataToSendPtr = (const uint8_t *)zmqMessageUniquePtr->data();
}
else { //this is std::vector<uint8_t>
dataSize = vecMessage.size();
dataToSendPtr = vecMessage.data();
}
const unsigned int writeIndex = m_base_bytesToAckCb.GetIndexForWrite(); //don't put this in tcp async write callback
if (writeIndex == UINT32_MAX) { //push check
std::cerr << M_BASE_IMPLEMENTATION_STRING_FOR_COUT << ": Error in BaseClass_Forward.. too many unacked packets" << std::endl;
return false;
}
m_base_dataSentServedAsKeepaliveSent = true;
m_base_bytesToAckCbVec[writeIndex] = dataSize;
++m_base_totalBundlesSent;
m_base_totalBundleBytesSent += dataSize;
std::vector<uint64_t> & currentFragmentBytesVec = m_base_fragmentBytesToAckCbVec[writeIndex];
currentFragmentBytesVec.resize(0); //will be zero size if not fragmented
m_base_fragmentVectorIndexCbVec[writeIndex] = 0; //used by the ack callback
std::vector<TcpAsyncSenderElement*> elements;
if (M_BASE_MAX_FRAGMENT_SIZE && (dataSize > M_BASE_MAX_FRAGMENT_SIZE)) {
const uint64_t reservedSize = (dataSize / M_BASE_MAX_FRAGMENT_SIZE) + 2;
elements.reserve(reservedSize);
currentFragmentBytesVec.reserve(reservedSize);
uint64_t dataIndex = 0;
while (true) {
uint64_t bytesToSend = std::min(dataSize - dataIndex, M_BASE_MAX_FRAGMENT_SIZE);
const bool isStartSegment = (dataIndex == 0);
const bool isEndSegment = ((bytesToSend + dataIndex) == dataSize);
TcpAsyncSenderElement * el = new TcpAsyncSenderElement();
if (usingZmqData) {
el->m_underlyingData.resize(1);
if (isEndSegment) {
el->m_underlyingDataZmq = std::move(zmqMessageUniquePtr);
}
}
else {
el->m_underlyingData.resize(1 + isEndSegment);
if (isEndSegment) {
el->m_underlyingData[1] = std::move(vecMessage);
}
}
Tcpcl::GenerateDataSegmentHeaderOnly(el->m_underlyingData[0], isStartSegment, isEndSegment, bytesToSend);
el->m_constBufferVec.resize(2);
el->m_constBufferVec[0] = boost::asio::buffer(el->m_underlyingData[0]);
el->m_constBufferVec[1] = boost::asio::buffer(dataToSendPtr + dataIndex, bytesToSend);
el->m_onSuccessfulSendCallbackByIoServiceThreadPtr = &m_base_handleTcpSendCallback;
elements.push_back(el);
dataIndex += bytesToSend;
currentFragmentBytesVec.push_back(dataIndex); //bytes to ack must be cumulative of fragments
if (isEndSegment) {
break;
}
}
}
m_base_bytesToAckCb.CommitWrite(); //pushed
//send length if requested
//LENGTH messages MUST NOT be sent unless the corresponding flag bit is
//set in the contact header. If the flag bit is set, LENGTH messages
//MAY be sent at the sender's discretion. LENGTH messages MUST NOT be
//sent unless the next DATA_SEGMENT message has the 'S' bit set to "1"
//(i.e., just before the start of a new bundle).
//TODO:
//A receiver MAY send a BUNDLE_REFUSE message as soon as it receives a
//LENGTH message without waiting for the next DATA_SEGMENT message.
//The sender MUST be prepared for this and MUST associate the refusal
//with the right bundle.
if ((static_cast<unsigned int>(CONTACT_HEADER_FLAGS::REQUEST_SENDING_OF_LENGTH_MESSAGES)) & (static_cast<unsigned int>(m_base_contactHeaderFlags))) {
TcpAsyncSenderElement * el = new TcpAsyncSenderElement();
el->m_underlyingData.resize(1);
Tcpcl::GenerateBundleLength(el->m_underlyingData[0], dataSize);
el->m_constBufferVec.emplace_back(boost::asio::buffer(el->m_underlyingData[0])); //only one element so resize not needed
el->m_onSuccessfulSendCallbackByIoServiceThreadPtr = &m_base_handleTcpSendCallback;
m_base_tcpAsyncSenderPtr->AsyncSend_ThreadSafe(el);
}
if (elements.size()) { //is fragmented
m_base_totalFragmentedSent += elements.size();
for (std::size_t i = 0; i < elements.size(); ++i) {
m_base_tcpAsyncSenderPtr->AsyncSend_ThreadSafe(elements[i]);
}
}
else {
TcpAsyncSenderElement * el = new TcpAsyncSenderElement();
if (usingZmqData) {
el->m_underlyingData.resize(1);
el->m_underlyingDataZmq = std::move(zmqMessageUniquePtr);
}
else {
el->m_underlyingData.resize(2);
el->m_underlyingData[1] = std::move(vecMessage);
}
Tcpcl::GenerateDataSegmentHeaderOnly(el->m_underlyingData[0], true, true, dataSize);
el->m_constBufferVec.resize(2);
el->m_constBufferVec[0] = boost::asio::buffer(el->m_underlyingData[0]);
el->m_constBufferVec[1] = boost::asio::buffer(dataToSendPtr, dataSize);
el->m_onSuccessfulSendCallbackByIoServiceThreadPtr = &m_base_handleTcpSendCallback;
m_base_tcpAsyncSenderPtr->AsyncSend_ThreadSafe(el);
}
return true;
}
void TcpclV3BidirectionalLink::BaseClass_BundleRefusalCallback(BUNDLE_REFUSAL_CODES refusalCode) {
std::cout << M_BASE_IMPLEMENTATION_STRING_FOR_COUT << ": error: BundleRefusalCallback not implemented yet" << std::endl;
}
void TcpclV3BidirectionalLink::BaseClass_NextBundleLengthCallback(uint64_t nextBundleLength) {
if (nextBundleLength > m_base_tcpclV3RxStateMachine.GetMaxReceiveBundleSizeBytes()) {
std::cout << M_BASE_IMPLEMENTATION_STRING_FOR_COUT << ": error: BaseClass_NextBundleLengthCallback received next bundle length of " << nextBundleLength
<< " which is greater than the bundle receive limit of " << m_base_tcpclV3RxStateMachine.GetMaxReceiveBundleSizeBytes() << " bytes" << std::endl;
//todo refuse bundle message?
}
else {
std::cout << "next bundle length\n";
m_base_fragmentedBundleRxConcat.reserve(nextBundleLength); //in case the bundle is fragmented
}
}
void TcpclV3BidirectionalLink::BaseClass_ContactHeaderCallback(CONTACT_HEADER_FLAGS flags, uint16_t keepAliveIntervalSeconds, const std::string & localEid) {
uint64_t remoteNodeId = UINT64_MAX;
uint64_t remoteServiceId = UINT64_MAX;
if (!Uri::ParseIpnUriString(localEid, remoteNodeId, remoteServiceId)) {
std::cerr << M_BASE_IMPLEMENTATION_STRING_FOR_COUT << ": error in BaseClass_ProcessContactHeader: error parsing remote EID URI string " << localEid
<< " .. TCPCL will not receive bundles." << std::endl;
BaseClass_DoTcpclShutdown(false, false);
return;
}
else if (remoteServiceId != 0) {
//ion 3.7.2 source code tcpcli.c line 1199 uses service number 0 for contact header:
//isprintf(eid, sizeof eid, "ipn:" UVAST_FIELDSPEC ".0", getOwnNodeNbr());
std::cerr << M_BASE_IMPLEMENTATION_STRING_FOR_COUT << ": error in BaseClass_ProcessContactHeader: remote EID URI string " << localEid
<< " does not use service number 0.. TCPCL will not receive bundles." << std::endl;
BaseClass_DoTcpclShutdown(false, false);
return;
}
else if ((!M_BASE_EXPECTED_REMOTE_CONTACT_HEADER_EID_STRING_IF_NOT_EMPTY.empty()) && (localEid != M_BASE_EXPECTED_REMOTE_CONTACT_HEADER_EID_STRING_IF_NOT_EMPTY)) {
std::cout << M_BASE_IMPLEMENTATION_STRING_FOR_COUT << ": error in BaseClass_ProcessContactHeader: received wrong contact header back from "
<< localEid << " but expected " << M_BASE_EXPECTED_REMOTE_CONTACT_HEADER_EID_STRING_IF_NOT_EMPTY
<< " .. TCPCL will not forward bundles. Correct the \"nextHopEndpointId\" field in the outducts config." << std::endl;
BaseClass_DoTcpclShutdown(false, false);
return;
}
m_base_tcpclRemoteEidString = localEid;
m_base_tcpclRemoteNodeId = remoteNodeId;
std::cout << M_BASE_IMPLEMENTATION_STRING_FOR_COUT << " received valid contact header from remote with EID " << m_base_tcpclRemoteEidString << std::endl;
m_base_contactHeaderFlags = flags;
//The keepalive_interval parameter is set to the minimum value from
//both contact headers. If one or both contact headers contains the
//value zero, then the keepalive feature (described in Section 5.6)
//is disabled.
if (M_BASE_DESIRED_KEEPALIVE_INTERVAL_SECONDS == 0) {
std::cout << M_BASE_IMPLEMENTATION_STRING_FOR_COUT << " notice: we have disabled the keepalive feature\n";
m_base_keepAliveIntervalSeconds = 0;
}
else if (keepAliveIntervalSeconds == 0) {
std::cout << M_BASE_IMPLEMENTATION_STRING_FOR_COUT << " notice: remote host has disabled the keepalive feature\n";
m_base_keepAliveIntervalSeconds = 0;
}
else if (M_BASE_DESIRED_KEEPALIVE_INTERVAL_SECONDS > keepAliveIntervalSeconds) {
std::cout << M_BASE_IMPLEMENTATION_STRING_FOR_COUT << " notice: remote host has requested a smaller keepalive interval of " << keepAliveIntervalSeconds
<< " seconds than ours of " << M_BASE_DESIRED_KEEPALIVE_INTERVAL_SECONDS << "." << std::endl;
m_base_keepAliveIntervalSeconds = keepAliveIntervalSeconds; //use the remote's smaller one
}
else if (M_BASE_DESIRED_KEEPALIVE_INTERVAL_SECONDS < keepAliveIntervalSeconds) { //bundle source should never enter here as the response should be smaller
std::cout << M_BASE_IMPLEMENTATION_STRING_FOR_COUT << " notice: we have requested a smaller keepalive interval of " << M_BASE_DESIRED_KEEPALIVE_INTERVAL_SECONDS
<< " seconds than the remote host's of " << keepAliveIntervalSeconds << "." << std::endl;
m_base_keepAliveIntervalSeconds = M_BASE_DESIRED_KEEPALIVE_INTERVAL_SECONDS; //use our smaller one
}
else {
m_base_keepAliveIntervalSeconds = M_BASE_DESIRED_KEEPALIVE_INTERVAL_SECONDS; //use
}
if (M_BASE_CONTACT_HEADER_MUST_REPLY) {
//Since TcpclBundleSink was waiting for a contact header, it just got one. Now it's time to reply with a contact header
//use the same keepalive interval
if (m_base_tcpSocketPtr) {
TcpAsyncSenderElement * el = new TcpAsyncSenderElement();
el->m_underlyingData.resize(1);
Tcpcl::GenerateContactHeader(el->m_underlyingData[0], CONTACT_HEADER_FLAGS::REQUEST_ACK_OF_BUNDLE_SEGMENTS, m_base_keepAliveIntervalSeconds, M_BASE_THIS_TCPCL_EID_STRING);
el->m_constBufferVec.emplace_back(boost::asio::buffer(el->m_underlyingData[0])); //only one element so resize not needed
el->m_onSuccessfulSendCallbackByIoServiceThreadPtr = &m_base_handleTcpSendCallback;
m_base_tcpAsyncSenderPtr->AsyncSend_ThreadSafe(el);
}
}
if (m_base_keepAliveIntervalSeconds) { //non-zero
std::cout << M_BASE_IMPLEMENTATION_STRING_FOR_COUT << " using " << m_base_keepAliveIntervalSeconds << " seconds for keepalive\n";
BaseClass_RestartNoKeepaliveReceivedTimer();
BaseClass_RestartNeedToSendKeepAliveMessageTimer();
}
m_base_readyToForward = true;
Virtual_OnContactHeaderCompletedSuccessfully();
}
void TcpclV3BidirectionalLink::Virtual_OnContactHeaderCompletedSuccessfully() {}
| 53.269514 | 234 | 0.719021 | [
"vector"
] |
398cc5f27a7e0dafc0f4c4dad079cfc1321720b0 | 4,998 | cpp | C++ | mysql-dst/mysql-cluster/storage/ndb/nodejs/jones-ndb/impl/src/ndb/BatchImpl_wrapper.cpp | SJTU-IPADS/dst | 897b929a692642cbf295c105d9d6e64090abb673 | [
"Apache-2.0"
] | 9 | 2020-12-17T01:59:13.000Z | 2022-03-30T16:25:08.000Z | mysql-dst/mysql-cluster/ndb/nodejs/jones-ndb/impl/src/ndb/BatchImpl_wrapper.cpp | SJTU-IPADS/dst | 897b929a692642cbf295c105d9d6e64090abb673 | [
"Apache-2.0"
] | 1 | 2021-07-30T12:06:33.000Z | 2021-07-31T10:16:09.000Z | mysql-dst/mysql-cluster/storage/ndb/nodejs/jones-ndb/impl/src/ndb/BatchImpl_wrapper.cpp | SJTU-IPADS/dst | 897b929a692642cbf295c105d9d6e64090abb673 | [
"Apache-2.0"
] | 1 | 2021-08-01T13:47:07.000Z | 2021-08-01T13:47:07.000Z | /*
Copyright (c) 2014, 2016 , Oracle and/or its affiliates. All rights
reserved.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; version 2 of
the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
02110-1301 USA
*/
#include <NdbApi.hpp>
#include "adapter_global.h"
#include "js_wrapper_macros.h"
#include "Record.h"
#include "NdbWrappers.h"
#include "BatchImpl.h"
#include "NativeMethodCall.h"
#include "NdbWrapperErrors.h"
using namespace v8;
V8WrapperFn getOperationError,
tryImmediateStartTransaction,
execute,
executeAsynch,
readBlobResults,
BatchImpl_freeImpl;
class BatchImplEnvelopeClass : public Envelope {
public:
BatchImplEnvelopeClass() : Envelope("BatchImpl") {
addMethod("tryImmediateStartTransaction", tryImmediateStartTransaction);
addMethod("getOperationError", getOperationError);
addMethod("execute", execute);
addMethod("executeAsynch", executeAsynch);
addMethod("readBlobResults", readBlobResults);
addMethod("free", BatchImpl_freeImpl);
}
};
BatchImplEnvelopeClass BatchImplEnvelope;
// CALLER in DBOperationHelper has a HandleScope
Local<Value> BatchImpl_Wrapper(BatchImpl *set) {
Local<Value> jsobj = BatchImplEnvelope.wrap(set);
BatchImplEnvelope.freeFromGC(set, jsobj);
return jsobj;
}
// This version is *not* freed from GC
Local<Object> getWrappedObject(BatchImpl *set) {
return BatchImplEnvelope.wrap(set)->ToObject();
}
Local<Value> BatchImpl_Recycle(Handle<Object> oldWrapper,
BatchImpl * newSet) {
DEBUG_PRINT("BatchImpl *Recycle*");
BatchImpl * oldSet = unwrapPointer<BatchImpl *>(oldWrapper);
assert(oldSet == 0);
assert(newSet != 0);
wrapPointerInObject(newSet, BatchImplEnvelope, oldWrapper);
return oldWrapper;
}
void getOperationError(const Arguments & args) {
DEBUG_MARKER(UDEB_DETAIL);
EscapableHandleScope scope(args.GetIsolate());
BatchImpl * set = unwrapPointer<BatchImpl *>(args.Holder());
int n = args[0]->Int32Value();
const NdbError * err = set->getError(n);
Local<Value> opErrHandle;
if(err == 0) opErrHandle = True(args.GetIsolate());
else if(err->code == 0) opErrHandle = Null(args.GetIsolate());
else opErrHandle = NdbError_Wrapper(*err);
args.GetReturnValue().Set(scope.Escape(opErrHandle));
}
void tryImmediateStartTransaction(const Arguments &args) {
BatchImpl * ctx = unwrapPointer<BatchImpl *>(args.Holder());
args.GetReturnValue().Set((bool) ctx->tryImmediateStartTransaction());
}
/* ASYNC.
*/
/* Execute NdbTransaction.
BatchImpl will close the transaction if exectype is not NoCommit;
in this case, an extra call is made in the js main thread to register the
transaction as closed.
*/
class TxExecuteAndCloseCall :
public NativeMethodCall_3_<int, BatchImpl, int, int, int> {
public:
/* Constructor */
TxExecuteAndCloseCall(const Arguments &args) :
NativeMethodCall_3_<int, BatchImpl, int, int, int>(
& BatchImpl::execute, args)
{
errorHandler = getNdbErrorIfLessThanZero;
}
void doAsyncCallback(Local<Object>);
};
void TxExecuteAndCloseCall::doAsyncCallback(Local<Object> context) {
if(arg0 != NdbTransaction::NoCommit) {
native_obj->registerClosedTransaction();
}
NativeMethodCall_3_<int, BatchImpl, int, int, int>::doAsyncCallback(context);
}
void execute(const Arguments &args) {
EscapableHandleScope scope(args.GetIsolate());
REQUIRE_ARGS_LENGTH(4);
TxExecuteAndCloseCall * ncallptr = new TxExecuteAndCloseCall(args);
ncallptr->runAsync();
args.GetReturnValue().SetUndefined();
}
/* IMMEDIATE.
*/
void executeAsynch(const Arguments &args) {
EscapableHandleScope scope(args.GetIsolate());
typedef NativeMethodCall_4_<int, BatchImpl,
int, int, int, Handle<Function> > MCALL;
MCALL mcall(& BatchImpl::executeAsynch, args);
mcall.run();
args.GetReturnValue().Set(mcall.jsReturnVal());
}
void readBlobResults(const Arguments &args) {
BatchImpl * set = unwrapPointer<BatchImpl *>(args.Holder());
int n = args[0]->Int32Value();
set->getKeyOperation(n)->readBlobResults(args);
// args.GetReturnValue().Set(set->getKeyOperation(n)->readBlobResults());
}
void BatchImpl_freeImpl(const Arguments &args) {
BatchImpl * set = unwrapPointer<BatchImpl *>(args.Holder());
delete set;
set = 0;
wrapPointerInObject(set, BatchImplEnvelope, args.Holder());
args.GetReturnValue().SetUndefined();
}
| 29.928144 | 79 | 0.722889 | [
"object"
] |
3994b799b2994aee2a8f01cd4931bf058e0b89c8 | 3,217 | cpp | C++ | src/backend/cpp/check.cpp | wadymwadim/normandeau | 2995a3293b22df269b88c3486e4f4009a1a5d76f | [
"Xnet",
"X11"
] | null | null | null | src/backend/cpp/check.cpp | wadymwadim/normandeau | 2995a3293b22df269b88c3486e4f4009a1a5d76f | [
"Xnet",
"X11"
] | null | null | null | src/backend/cpp/check.cpp | wadymwadim/normandeau | 2995a3293b22df269b88c3486e4f4009a1a5d76f | [
"Xnet",
"X11"
] | null | null | null | #include <iostream>
#include "check.hpp"
#include "cover.hpp"
#include "equations.hpp"
#include "evaluator.hpp"
template <template <typename> class Trig>
bool equations_positive(const std::vector<std::tuple<EqVec<Trig>, Coeff64, Coeff64>>& eqs, const PointQ& center, const Rational& radius, Evaluator& eval) {
for (const auto& tup : eqs) {
const auto& eq = std::get<0>(tup);
const auto bx = std::get<1>(tup);
const auto by = std::get<2>(tup);
const auto pos = eval.is_positive(eq, bx + by, center, radius);
if (!pos) {
std::cout << "Failure: not positive" << std::endl;
std::cout << "f(x, y) = " << eq << std::endl;
std::cout << "bound = " << (bx + by) << std::endl;
std::cout << "center = " << center << std::endl;
std::cout << "radius = " << radius << std::endl;
return false;
}
}
return true;
}
static bool covers_square(const StableInfo& info, const ClosedRectangleQ& square, const uint32_t bits) {
if (!geometry::subset(square, info.polygon)) {
std::cout << "Failure: square is not a subset of polygon" << std::endl;
return false;
}
Evaluator eval{bits};
const auto center = square.center();
// It's a square, so we can use width or height
const Rational radius = square.width() / 2;
if (!equations_positive(info.sines, center, radius, eval)) {
std::cout << "not all sines positive" << std::endl;
return false;
}
if (!equations_positive(info.cosines, center, radius, eval)) {
std::cout << "not all cosines positive" << std::endl;
return false;
}
return true;
}
// Convert the givin amount of digits to a roughly equivalent amount of bits
static uint32_t digits_to_bits(const uint32_t digits) {
// This is the function that boost uses, and so we'll keep it for now
// log2(10) ~ 1000/301
return (digits * 1000) / 301 + ((digits * 1000) % 301 ? 2 : 1);
}
std::string check_square(const int64_t numerx, const int64_t numery, const int64_t denom, const CodeSequence& code_seq,
const InitialAngles& initial_angles, const std::string& cover_dir) {
const StableInfo code_info{calculate_code_info(CodePair{code_seq, initial_angles})};
const Rational cx = Rational{numerx} / denom;
const Rational cy = Rational{numery} / denom;
const Rational r = Rational{1, 2} / denom;
const Rational x_min = cx - r;
const Rational x_max = cx + r;
const Rational y_min = cy - r;
const Rational y_max = cy + r;
const ClosedRectangleQ square{{x_min, x_max}, {y_min, y_max}};
const auto digits = load_digits(cover_dir);
const auto bits = digits_to_bits(digits);
const auto cover = covers_square(code_info, square, bits);
std::ostringstream oss{};
oss << "Code Sequence = " << code_seq << '\n';
oss << "Initial Angles = " << initial_angles << '\n';
oss << "Center = (" << cx << ", " << cy << ")\n";
oss << "Radius = " << r << '\n';
oss << "Lower Bound = " << static_cast<double>((cx + cy) * r / 1000) << '\n';
oss << "Covered = " << cover << '\n';
return oss.str();
}
| 31.23301 | 155 | 0.60087 | [
"geometry",
"vector"
] |
39a36622bcd2213f23e2d1446dc870bd9e55f632 | 2,312 | cpp | C++ | UVa Online Judge/v8/857.cpp | mjenrungrot/algorithm | e0e8174eb133ba20931c2c7f5c67732e4cb2b703 | [
"MIT"
] | 1 | 2021-12-08T08:58:43.000Z | 2021-12-08T08:58:43.000Z | UVa Online Judge/v8/857.cpp | mjenrungrot/algorithm | e0e8174eb133ba20931c2c7f5c67732e4cb2b703 | [
"MIT"
] | null | null | null | UVa Online Judge/v8/857.cpp | mjenrungrot/algorithm | e0e8174eb133ba20931c2c7f5c67732e4cb2b703 | [
"MIT"
] | null | null | null | /*=============================================================================
# Author: Teerapat Jenrungrot - https://github.com/mjenrungrot/
# FileName: 857.cpp
# Description: UVa Online Judge - 857
=============================================================================*/
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <vector>
using namespace std;
struct data {
data() {}
data(int code, int note, int m, int b, int t)
: code(code), note(note), m(m), b(b), t(t) {}
int code, note, m, b, t;
};
int N, pass[3000], n_del;
int main() {
// freopen("in","r",stdin);
while (scanf("%d", &N) == 1) {
if (N == -1) {
printf("-1\n");
break;
}
memset(pass, 0, sizeof pass);
n_del = 0;
vector<struct data> V1;
for (int i = 1; i <= N; i++) {
int code, note, m, b, t;
scanf("%d %d %d %d %d", &code, ¬e, &m, &b, &t);
if (t <= 29)
t = 0;
else if (t <= 89)
t = 60;
else if (t <= 149)
t = 120;
else if (t <= 209)
t = 180;
else if (t <= 269)
t = 240;
else if (t <= 329)
t = 300;
else if (t <= 389)
t = 360;
else if (t <= 449)
t = 420;
else {
t = 0;
b++;
if (b > 4) b = 1, m++;
}
V1.push_back(data(code, note, m, b, t));
}
for (int i = 0; i < V1.size(); i++) {
for (int j = i + 1; j < V1.size(); j++) {
if (V1[i].code == true and V1[j].code == false and
V1[i].note == V1[j].note and V1[i].m == V1[j].m and
V1[i].b == V1[j].b and V1[i].t == V1[j].t) {
pass[i] = pass[j] = true;
n_del += 2;
break;
}
}
}
printf("%d\n", N - n_del);
for (int i = 0; i < V1.size(); i++) {
if (pass[i]) continue;
printf("%d %d %d %d %d\n", V1[i].code, V1[i].note, V1[i].m, V1[i].b,
V1[i].t);
}
}
return 0;
} | 28.9 | 80 | 0.334343 | [
"vector"
] |
39a475be046c75b20171d8c39e9bddf1efd1224b | 4,414 | cpp | C++ | Solved exams/February exams/February 2017 session 2/Examen.cpp | marcosherreroa/Fundamentos-de-Programacion | 48c5b6c36e11d907776cdf726022c1b62c6cecdc | [
"CC0-1.0"
] | null | null | null | Solved exams/February exams/February 2017 session 2/Examen.cpp | marcosherreroa/Fundamentos-de-Programacion | 48c5b6c36e11d907776cdf726022c1b62c6cecdc | [
"CC0-1.0"
] | null | null | null | Solved exams/February exams/February 2017 session 2/Examen.cpp | marcosherreroa/Fundamentos-de-Programacion | 48c5b6c36e11d907776cdf726022c1b62c6cecdc | [
"CC0-1.0"
] | null | null | null | #include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <iomanip>
const int N_ACC = 10;
enum tOperacion{ COMPRA, VENTA, ACTUALIZACION, FIN, INCORRECTO };
struct tAccion{
std::string nombre;
float precioAccion;
int numAcciones;
};
tOperacion char2operacion(char caracter){
switch (caracter){
case 'C': return COMPRA;
case 'V': return VENTA;
case 'A': return ACTUALIZACION;
case 'X': return FIN;
}
return INCORRECTO;
}
char operacion2char(tOperacion operacion){
switch (operacion){
case COMPRA: return 'C';
case VENTA: return 'V';
case ACTUALIZACION: return 'A';
}
}
std::istream & operator>>(std::istream & flujo, tAccion & accion){
flujo >> accion.nombre >> accion.precioAccion >> accion.numAcciones;
return flujo;
}
std::ostream & operator<<(std::ostream & flujo, tAccion const & accion){
flujo << std::left << std::setw(10) << accion.nombre << std::right << std::setw(10) << accion.numAcciones << std::setw(10) << accion.precioAccion;
return flujo;
}
std::istream & operator>>(std::istream & flujo, tOperacion & operacion){
char caracter = ' ';
flujo >> caracter;
operacion = char2operacion(caracter);
return flujo;
}
std::ostream & operator<<(std::ostream & flujo, tOperacion & operacion){
flujo << operacion2char(operacion);
return flujo;
}
float valortotal(std::vector<tAccion> const & cartera){
float sol = 0;
for (int i = 0; i < N_ACC; ++i){
sol += cartera[i].numAcciones* cartera[i].precioAccion;
}
return sol;
}
int encontrarEmpresa(std::vector<tAccion> const & cartera, std::string const & nombre){
int posicion = -1;
for (int i = 0; posicion==-1 && i < N_ACC; ++i){
if (cartera[i].nombre == nombre) posicion = i;
}
return posicion;
}
bool cargar(std::vector<tAccion> & cartera){
std::ifstream entrada;
int numempresas = 0;
entrada.open("cartera.txt");
if (!entrada.is_open()) return false;
tAccion accion; int numacciones = 0;
entrada >> accion;
while (numacciones < N_ACC && accion.nombre != "#" ) {
cartera[numacciones] = accion;
++numacciones;
entrada >> accion;
}
entrada.close();
if (numacciones != N_ACC) return false;
else return true;
}
void mostrar(std::vector<tAccion> const & cartera){
std::cout<<'\n';
for (int i = 0; i < N_ACC; ++i){
std::cout << cartera[i]<<'\n';
}
std::cout << "Valor total: " << valortotal(cartera)<<"\n\n";
}
bool procesar(std::vector<tAccion> & cartera){
std::ifstream entrada;
entrada.open("semana.txt");
if (!entrada.is_open())return false;
tOperacion operacion; std::string nombre = ""; float numero = 0.0; int posicion = 0;
entrada >> operacion >> nombre >> numero;
while (operacion!=FIN) {
posicion = encontrarEmpresa(cartera, nombre);
if (operacion == INCORRECTO) std::cout << operacion << ' ' << nombre << ' ' << numero << " Error: Operacion no existe\n";
else if (posicion == -1) std::cout << operacion << ' ' << nombre << ' ' << numero << " Error: Empresa no existe\n";
else {
switch (operacion) {
case COMPRA: {
cartera[posicion].numAcciones += numero;
std::cout << operacion << ' ' << nombre << ' ' << numero << " OK\n";
break;
}
case VENTA: {
if (cartera[posicion].numAcciones < numero)std::cout << operacion << ' ' << nombre << ' ' << numero << " Error: No hay suficientes acciones\n";
else {
cartera[posicion].numAcciones -= numero;
std::cout << operacion << ' ' << nombre << ' ' << numero << " OK\n";
}
break;
}
case ACTUALIZACION: {
cartera[posicion].precioAccion = numero;
std::cout << operacion << ' ' << nombre << ' ' << numero << " OK\n";
break;
}
}
}
entrada >> operacion >> nombre >> numero;
}
entrada.close();
return true;
}
bool guardar(std::vector<tAccion> const & cartera) {
std::ofstream salida;
salida.open("cartera.txt");
if (!salida.is_open()) return false;
for (int i = 0; i < N_ACC; ++i) {
salida << cartera[i].nombre << ' ' << cartera[i].precioAccion << ' ' << cartera[i].numAcciones << '\n';
}
salida << "#";
salida.close();
return true;
}
int main() {
std::vector<tAccion> cartera(N_ACC); bool OK = true;
OK = cargar(cartera);
if (!OK)std::cout << "No se ha podido cargar";
else mostrar(cartera);
OK = procesar(cartera);
if (!OK)std::cout << "No se ha podido procesar";
mostrar(cartera);
OK = guardar(cartera);
if (!OK)std::cout << "No se ha podido guardar la cartera";
system("PAUSE");
return 0;
} | 25.662791 | 147 | 0.637744 | [
"vector"
] |
39bd4bded88e4dcc4d534390f9d30956591aef98 | 1,406 | cpp | C++ | src/region.cpp | calincru/Warlight-AI-Challenge-2-Bot | 4d427423db42c24e8d8f124ed6ab0ce85c3e5dff | [
"MIT"
] | 1 | 2015-10-07T16:44:27.000Z | 2015-10-07T16:44:27.000Z | src/region.cpp | calincru/Warlight-AI-Challenge-2-Bot | 4d427423db42c24e8d8f124ed6ab0ce85c3e5dff | [
"MIT"
] | null | null | null | src/region.cpp | calincru/Warlight-AI-Challenge-2-Bot | 4d427423db42c24e8d8f124ed6ab0ce85c3e5dff | [
"MIT"
] | null | null | null | // This program is free software licenced under MIT Licence. You can
// find a copy of this licence in LICENCE.txt in the top directory of
// source code.
//
// Self
#include "region.hpp"
// C++
#include <cassert>
namespace warlightAi {
Region::Region(int id, SuperRegionPtr superRegion)
: m_id(id)
, m_superRegion(superRegion)
, m_armies(NEUTRAL_ARMY_COUNT)
, m_owner(Player::NEUTRAL)
{}
int Region::id() const
{
return m_id;
}
void Region::addNeighbor(RegionPtr neighbor)
{
if (!isNeighbor(neighbor))
m_neighbors.emplace_back(neighbor);
}
bool Region::isNeighbor(RegionPtr region) const
{
for (auto &neigh : m_neighbors)
if (neigh.lock() == region)
return true;
return false;
}
std::vector<RegionPtr> Region::getNeighbors() const
{
std::vector<RegionPtr> neighs;
for (auto &neigh : m_neighbors)
neighs.emplace_back(neigh.lock());
return neighs;
}
void Region::setOwner(warlightAi::Player player)
{
m_owner = player;
}
bool Region::isOwnedBy(warlightAi::Player player) const
{
return m_owner == player;
}
warlightAi::Player Region::getOwner() const
{
return m_owner;
}
void Region::setArmies(int armies)
{
m_armies = armies;
}
int Region::getArmies() const
{
return m_armies;
}
SuperRegionPtr Region::getSuperRegion() const
{
return m_superRegion.lock();
}
} // namespace warlightAi
| 17.146341 | 69 | 0.681366 | [
"vector"
] |
39bd82af68de1a40dbb4cd974c06561e68c5e9bd | 4,520 | cpp | C++ | src/scheduler/FunctionCallClient.cpp | n-krueger/faabric | c95c3baf9406613629e5f382efc0fc8366b22752 | [
"Apache-2.0"
] | null | null | null | src/scheduler/FunctionCallClient.cpp | n-krueger/faabric | c95c3baf9406613629e5f382efc0fc8366b22752 | [
"Apache-2.0"
] | null | null | null | src/scheduler/FunctionCallClient.cpp | n-krueger/faabric | c95c3baf9406613629e5f382efc0fc8366b22752 | [
"Apache-2.0"
] | null | null | null | #include <faabric/proto/faabric.pb.h>
#include <faabric/scheduler/FunctionCallClient.h>
#include <grpcpp/create_channel.h>
#include <grpcpp/security/credentials.h>
#include <faabric/rpc/macros.h>
#include <faabric/util/queue.h>
#include <faabric/util/testing.h>
namespace faabric::scheduler {
// -----------------------------------
// Mocking
// -----------------------------------
static std::vector<std::pair<std::string, faabric::Message>> functionCalls;
static std::vector<std::pair<std::string, faabric::Message>> flushCalls;
static std::vector<std::pair<std::string, faabric::BatchExecuteRequest>>
batchMessages;
static std::vector<std::pair<std::string, faabric::MPIMessage>> mpiMessages;
static std::vector<std::pair<std::string, faabric::ResourceRequest>>
resourceRequests;
static std::unordered_map<std::string,
faabric::util::Queue<faabric::HostResources>>
queuedResourceResponses;
static std::vector<std::pair<std::string, faabric::UnregisterRequest>>
unregisterRequests;
std::vector<std::pair<std::string, faabric::Message>> getFunctionCalls()
{
return functionCalls;
}
std::vector<std::pair<std::string, faabric::Message>> getFlushCalls()
{
return flushCalls;
}
std::vector<std::pair<std::string, faabric::BatchExecuteRequest>>
getBatchRequests()
{
return batchMessages;
}
std::vector<std::pair<std::string, faabric::MPIMessage>> getMPIMessages()
{
return mpiMessages;
}
std::vector<std::pair<std::string, faabric::ResourceRequest>>
getResourceRequests()
{
return resourceRequests;
}
std::vector<std::pair<std::string, faabric::UnregisterRequest>>
getUnregisterRequests()
{
return unregisterRequests;
}
void queueResourceResponse(const std::string& host, faabric::HostResources& res)
{
queuedResourceResponses[host].enqueue(res);
}
void clearMockRequests()
{
functionCalls.clear();
batchMessages.clear();
mpiMessages.clear();
resourceRequests.clear();
unregisterRequests.clear();
for (auto& p : queuedResourceResponses) {
p.second.reset();
}
queuedResourceResponses.clear();
}
// -----------------------------------
// gRPC client
// -----------------------------------
FunctionCallClient::FunctionCallClient(const std::string& hostIn)
: host(hostIn)
, channel(grpc::CreateChannel(host + ":" + std::to_string(FUNCTION_CALL_PORT),
grpc::InsecureChannelCredentials()))
, stub(faabric::FunctionRPCService::NewStub(channel))
{}
void FunctionCallClient::sendFlush()
{
faabric::Message call;
if (faabric::util::isMockMode()) {
flushCalls.emplace_back(host, call);
} else {
ClientContext context;
faabric::FunctionStatusResponse response;
CHECK_RPC("function_flush", stub->Flush(&context, call, &response));
}
}
void FunctionCallClient::sendMPIMessage(
const std::shared_ptr<faabric::MPIMessage> msg)
{
if (faabric::util::isMockMode()) {
mpiMessages.emplace_back(host, *msg);
} else {
ClientContext context;
faabric::FunctionStatusResponse response;
CHECK_RPC("mpi_message", stub->MPICall(&context, *msg, &response));
}
}
faabric::HostResources FunctionCallClient::getResources(
const faabric::ResourceRequest& req)
{
faabric::HostResources response;
if (faabric::util::isMockMode()) {
// Register the request
resourceRequests.emplace_back(host, req);
// See if we have a queued response
if (queuedResourceResponses[host].size() > 0) {
response = queuedResourceResponses[host].dequeue();
}
} else {
ClientContext context;
CHECK_RPC("get_resources",
stub->GetResources(&context, req, &response));
}
return response;
}
void FunctionCallClient::executeFunctions(
const faabric::BatchExecuteRequest& req)
{
if (faabric::util::isMockMode()) {
batchMessages.emplace_back(host, req);
} else {
ClientContext context;
faabric::FunctionStatusResponse response;
CHECK_RPC("exec_funcs",
stub->ExecuteFunctions(&context, req, &response));
}
}
void FunctionCallClient::unregister(const faabric::UnregisterRequest& req)
{
if (faabric::util::isMockMode()) {
unregisterRequests.emplace_back(host, req);
} else {
ClientContext context;
faabric::FunctionStatusResponse response;
CHECK_RPC("unregister", stub->Unregister(&context, req, &response));
}
}
}
| 27.065868 | 80 | 0.664823 | [
"vector"
] |
39c3f4a3b95fedd5dd5d18ebd869b83f64e08b01 | 19,677 | cpp | C++ | rendering.cpp | Dangertech/tictactoe-ncurses | caf238843d2ac5bf79cab1d17569050fb9703165 | [
"Unlicense"
] | 1 | 2021-09-05T08:05:10.000Z | 2021-09-05T08:05:10.000Z | rendering.cpp | Dangertech/tictactoe | caf238843d2ac5bf79cab1d17569050fb9703165 | [
"Unlicense"
] | 10 | 2021-09-05T08:15:41.000Z | 2021-09-25T14:19:06.000Z | rendering.cpp | Dangertech/tictactoe-ncurses | caf238843d2ac5bf79cab1d17569050fb9703165 | [
"Unlicense"
] | null | null | null | #include <ncurses.h>
#include <vector>
#include <string>
#include "vars.h"
#include "rendering.h"
////// START MENU
// Create a struct that holds option properties
struct menu_options
{
std::string description;
// Int if the option should have a value
int display_value;
// Text if the option should have different strings of text
std::vector < std::string > display_text;
int text_loc; // Pointer to the current entry to be displayed
bool error;
};
// Construct a vector with the options
std::vector <menu_options> menu_container =
{
{"Rows", grid_size_y,{}, 0, false},
{"Columns", grid_size_x, {}, 0, false},
{"Pixels needed to win", pixels_needed, {}, 0, false},
{"Gamemode", 0, {"Singleplayer", "Multiplayer"}, 0, false },
{"Player 1's Color", 0, {"Green", "Red", "Blue", "Yellow"}, player_one_color - 1, false },
{"Player 1's Icon", 0, {"X", "O", "+", "-", "~", "@", "$", "#", "%"}, 0, false },
{"Player 2's Color", 0, {"Green", "Red", "Blue", "Yellow"}, player_two_color - 1, false },
{"Player 2's Icon", 0, {"X", "O", "+", "-", "~", "@", "$", "#", "%"}, 1, false },
{"Starting Player", 0, {"You", "Opponent"}, starting_player, false}
};
// Function to render the menu later on with colors and characters
// matching the ones set by the player(s)
void xoxoprint(int line, std::string xoxo_str)
{
int start_x = (max_x/2) - (xoxo_str.length() / 2);
move(line, start_x);
for (int i = 0; i<xoxo_str.length(); i++)
{
int temp_p_one_col = menu_container[4].text_loc + 1;
int temp_p_two_col = menu_container[6].text_loc + 1;
if (xoxo_str[i] == 'X')
{
// Print player_one's color and character
attron(COLOR_PAIR(temp_p_one_col));
addch(menu_container[5].display_text[menu_container[5].text_loc].at(0));
attroff(COLOR_PAIR(temp_p_two_col));
}
else if (xoxo_str[i] == 'O')
{
// Print player_two's color and character
attron(COLOR_PAIR(temp_p_two_col));
addch(menu_container[7].display_text[menu_container[7].text_loc].at(0));
attroff(COLOR_PAIR(temp_p_two_col));
}
else
{
// Print the remaining characters in the color
// of the starting player
if (menu_container[8].text_loc == 0)
attron(COLOR_PAIR(temp_p_one_col));
else if (menu_container[8].text_loc == 1)
attron(COLOR_PAIR(temp_p_two_col));
addch(xoxo_str[i]);
attroff(COLOR_PAIR(temp_p_one_col));
attroff(COLOR_PAIR(temp_p_two_col));
}
}
}
// Make a 'New game' menu
int start_menu()
{
// Create a window that the menu will be displayed on
WINDOW *menu_win;
int window_rows = menu_container.size() + 4, window_columns = 50;
int x_origin = (max_x / 2) - ( window_columns / 2), y_origin = 13;
int y_borders = 2; // Space to be left out before the first entry gets rendered
int dis_val_start = window_columns - 16; // At which column to start rendering the entries
int selected_entry = 0;
menu_win = newwin( window_rows, window_columns, y_origin, x_origin);
//Draw everything until the user confirms with 'Enter'
while (ch != 10 && ch != ' ')
{
switch (ch)
{
case KEY_UP: case 'k': case 'w':
if (selected_entry > 0)
selected_entry--;
break;
case KEY_DOWN: case 'j': case 's':
if (selected_entry < menu_container.size()-1)
selected_entry++;
break;
case KEY_LEFT: case 'h': case 'a':
// If there is no text to be displayed, decrease the value of the int
if (menu_container[selected_entry].display_text.size() == 0)
menu_container[selected_entry].display_value--;
// else, decrease the pointer to the current text entry
else
{
menu_container[selected_entry].text_loc--;
// Wrap around
if (menu_container[selected_entry].text_loc < 0)
menu_container[selected_entry].text_loc = menu_container[selected_entry].display_text.size() - 1;
}
break;
case KEY_RIGHT: case 'l': case 'd':
if (menu_container[selected_entry].display_text.size() == 0)
menu_container[selected_entry].display_value++;
else
{
menu_container[selected_entry].text_loc++;
if (menu_container[selected_entry].text_loc == menu_container[selected_entry].display_text.size())
menu_container[selected_entry].text_loc = 0;
}
break;
case 'q':
return 1;
break;
}
///// ERROR HANDLING
// Make a vector that holds possible error messages
std::vector <std::string> error_msgs;
error_msgs.clear();
// Push errors back into the error vector
//
// Rows and columns
for (int i = 0; i < 2; i++)
{
int val = menu_container[i].display_value;
// I know, this is pretty bad code but it's just a little easter egg
if (val < 2)
{
error_msgs.push_back("Sizes smaller than two are not supported!");
error_msgs.push_back("You may experience crashes and unexpected behaviour!");
}
else if (val > 30 && val < 120)
{
error_msgs.push_back("You need a sufficiently large screen to properly display high grid sizes!");
error_msgs.push_back("You may experience unexpected behaviour!");
}
else if (val > 120 && val < 235)
error_msgs.push_back("I don't think there's a screen that large...");
else if (val > 235 && val < 512)
error_msgs.push_back("Ok, you're bored, right?");
else if (val > 512 && val < 828)
error_msgs.push_back("Are you trying to impress me through your waste of time?");
else if (val > 828 && val < 1021)
error_msgs.push_back("This is getting ridiculous.");
else if (val > 1021 && val < 1372)
error_msgs.push_back("You may run into some performance issues now, btw");
else if (val > 1372 && val < 1845)
error_msgs.push_back("I really don't have time for this.");
else if (val > 1845)
error_msgs.push_back("Don't you have hobbies or something!?");
// Turn error to true in all cases from above
if (val < 2 || val > 30)
menu_container[i].error = true;
}
// pixels_needed
int dis_pix = menu_container[2].display_value;
if (dis_pix > menu_container[0].display_value && dis_pix > menu_container[1].display_value)
{
error_msgs.push_back("A player needs more pixels in a row to win than there are rows and columns.");
error_msgs.push_back("It is impossible to win.");
menu_container[2].error = true;
}
else if (dis_pix > menu_container[0].display_value || dis_pix > menu_container[1].display_value)
{
error_msgs.push_back("The grid size is not large enough in one direction to win.");
error_msgs.push_back("A game might be harder to win.");
menu_container[2].error = true;
}
if (dis_pix < 2)
{
error_msgs.push_back("Pixel streaks lower than 2 may produce unexpected behaviour!");
menu_container[2].error = true;
}
// Pixel color
if (menu_container[4].text_loc == menu_container[6].text_loc)
{
error_msgs.push_back("Having both players with the same color is not recommended");
menu_container[4].error = true;
menu_container[6].error = true;
}
// Player icons
if (menu_container[5].text_loc == menu_container[7].text_loc)
{
error_msgs.push_back("Having both players with the same icons is not recommended");
menu_container[5].error = true;
menu_container[7].error = true;
}
//// Print error messages
erase();
attron( COLOR_PAIR(2) );
for (int i = 0; i < error_msgs.size(); i++)
{
mvprintw( y_origin + window_rows + 2 + i, x_origin + 3, error_msgs[i].c_str() );
}
attroff( COLOR_PAIR(2) );
///// MENU RENDERING
// Erase the entire window in case there was a menu entry with a higher digit count before than the one now
// For example: A value was 10, now the user presses KEY_LEFT,
// but the menu shows 90 although it is nine, because the location of the '0' wasn't redrawn
werase( menu_win );
// Print a box around the menu window
box(menu_win, 1, 0);
// Create a title and some decorations outside of the window
// I swear this looks halfway decent in the actual menu
// xoxoprint converts the string here to the matching color
// and character for each player
// The X's and O's here are just "placeholders"
xoxoprint( 3, " _____ ___ ____ _____ _ ____ _____ ___ _____ ");
xoxoprint( 4, "|XOXXO|OXO/XOXO| |OOXOX|/X\\ /XOOX| |OXXOX/OXO\\|XXOXO|");
xoxoprint( 5, " |O| |X|X| |O| /O_X\\|X| |X||O| |O|OXO| ");
xoxoprint( 6, " |X| |O|X|___ |X|/OXOXX\\O|___ |O||O| |O|O|___ ");
xoxoprint( 7, " |X| |OO\\OOXX| |X/O/ \\O\\OXXO| |X| \\XXO/|OXXOX|");
mvprintw( y_origin-1, x_origin, "Starting a new game:");
mvwprintw(menu_win, window_rows - 1, window_columns - 10, "<Enter>");
// Error message if the terminal is too small
attron(COLOR_PAIR(66));
if (max_y < 25 || max_x < 70)
mvprintw(0, 0, "Terminal too small for tictactoe-ncurses.\n You may experience rendering issues");
attroff(COLOR_PAIR(66));
// Render window contents
for (int i = 0; i < menu_container.size(); i++)
{
if (selected_entry == i)
{
// Render the input indicator
// Compute the position the right indicator has to render on
int digit_size = 1;
// If the display_text vector is empty, and the number should be shown
if (menu_container[i].display_text.size() == 0)
{
if (menu_container[i].display_value > 9 || menu_container[i].display_value < 0)
digit_size = 2;
if (menu_container[i].display_value > 100 || menu_container[i].display_value < -9)
digit_size = 3;
}
else
{
digit_size = menu_container[i].display_text[menu_container[i].text_loc].length();
}
mvwprintw( menu_win, i + y_borders, dis_val_start - 2, "<");
mvwprintw( menu_win, i + y_borders, dis_val_start + 1+ digit_size, ">");
// Activate the standout color pair
wattron( menu_win, A_STANDOUT );
}
// If the current entry is reported erroneous,
// turn off the standout pair and activate the error color pair
if (menu_container[i].error == true)
{
wattroff( menu_win, A_STANDOUT );
wattron( menu_win, COLOR_PAIR(66) );
}
mvwprintw( menu_win, i + y_borders, 2, menu_container[i].description.c_str() );
// If the size of the text vector is empty, show the integer
if (menu_container[i].display_text.size() == 0)
mvwprintw( menu_win, i + y_borders, dis_val_start, "%d", menu_container[i].display_value );
else
// Else, show the text of the current entry
mvwprintw( menu_win, i + y_borders, dis_val_start, menu_container[i].display_text[menu_container[i].text_loc].c_str() );
// Turn the possible color pairs off
wattroff( menu_win, A_STANDOUT );
wattroff( menu_win, COLOR_PAIR(66) );
// Reset error value to check if it is still true on the next while iteration
menu_container[i].error = false;
}
refresh();
wrefresh( menu_win );
ch = getch();
}
// OK, this looks very ugly, but I couldn't find a better solution:
// Assign every real variable the variable in the vector
grid_size_y = menu_container[0].display_value;
grid_size_x = menu_container[1].display_value;
pixels_needed = menu_container[2].display_value;
gamemode = menu_container[3].text_loc;
player_one_color = menu_container[4].text_loc + 1;
player_one_pixel = menu_container[5].display_text[menu_container[5].text_loc].at(0);
player_two_color = menu_container[6].text_loc + 1;
player_two_pixel = menu_container[7].display_text[menu_container[7].text_loc].at(0);
starting_player = menu_container[8].text_loc + 1;
// Delete the window and clear the screen
delwin( menu_win );
erase();
return 0;
}
int win_menu()
{
// Create a new window
WINDOW *menu_win;
// Construction variables
int des_rows = 20, des_cols = 50;
int y_borders = 7, x_borders = 8;
int window_rows, window_columns;
// Determine window sizes
if (max_y > des_rows + y_borders*2)
window_rows = des_rows;
else
window_rows = max_y - y_borders*2;
if (max_x > des_cols + x_borders*2)
window_columns = des_cols;
else
window_columns = max_x - x_borders*2;
int x_origin = (max_x / 2) - ( window_columns / 2), y_origin = y_borders; // Center window horizontally
menu_win = newwin( window_rows, window_columns, y_origin, x_origin);
int selected = 0;
// Input
ch = 0;
while (ch != 10 && ch != ' ')
{
///// PROCESSING INPUT
//
switch (ch)
{
case 113:
delwin(menu_win);
return 0;
break;
case KEY_UP: case 'k':
selected = 0;
break;
case KEY_DOWN: case 'j':
selected = 1;
break;
}
///// RENDERING
// The most basic renderer because there are only two options
werase( menu_win );
if (selected == 0)
{
// "Restart" stands out
// Indicators
mvwprintw( menu_win, window_rows - 6, window_columns / 2 - 5, "<" );
mvwprintw( menu_win, window_rows - 6, window_columns / 2 + 5, ">" );
wattron(menu_win, A_STANDOUT);
mvwprintw( menu_win, window_rows - 6, window_columns / 2 - 3, "Restart" );
wattroff(menu_win, A_STANDOUT);
mvwprintw( menu_win, window_rows - 5, window_columns / 2 - 2, "Quit" );
}
else if (selected == 1)
{
// "Quit" stands out
// Indicators
mvwprintw( menu_win, window_rows - 5, window_columns / 2 - 4, "<" );
mvwprintw( menu_win, window_rows - 5, window_columns / 2 + 3, ">" );
mvwprintw( menu_win, window_rows - 6, window_columns / 2 - 3, "Restart" );
wattron(menu_win, A_STANDOUT);
mvwprintw( menu_win, window_rows - 5, window_columns / 2 - 2, "Quit" );
wattroff(menu_win, A_STANDOUT);
}
// Make an outline box in the color of the current player
int color;
if (current_player == 1)
color = player_one_color;
else if (current_player == 2)
color = player_two_color;
wattron(menu_win, COLOR_PAIR(color));
box(menu_win, 0, 0);
wattroff(menu_win, COLOR_PAIR(color));
// Win message in yellow
wattron(menu_win, COLOR_PAIR(4));
if (gamemode == 0 && current_player == 2)
{
mvwprintw( menu_win, 5, window_columns / 2 - 8, "The computer has won!" );
}
else if (current_player != -1)
{
mvwprintw( menu_win, 5, window_columns / 2 - 8, "Player %d has won!", current_player );
}
else
mvwprintw( menu_win, 5, window_columns / 2 - 14, "The grid is full. It's a tie!" );
wattroff(menu_win, COLOR_PAIR(4));
// Some random deco
wattron( menu_win, COLOR_PAIR(4) );
mvwprintw( menu_win, 0, 0, "/");
mvwprintw( menu_win, 0, window_columns - 1, "\\");
wattroff( menu_win, COLOR_PAIR(4) );
refresh();
wrefresh(menu_win);
// Get input character
ch = getch();
}
if (selected == 0) // 'Restart' selected
{
// erase the menu on the screen, delete the pointer and render the grid to fill spaces that might have been overwritten
werase(menu_win);
wrefresh(menu_win);
delwin(menu_win);
render_grid();
return 1;
}
else if (selected == 1) // 'Quit' selected
return 0;
// An error must have happened
delwin(menu_win);
return -5;
}
void help_text(int start_y, int start_x)
{
// Gamemode
mvprintw(start_y, start_x, "You are playing a ");
attron(A_BOLD);
if (gamemode == 0)
printw("Singleplayer");
else if (gamemode == 1)
printw("Multiplayer");
else
printw("Oopstheremusthavebeenanerrorbecauseihavenofuckingideowhatgamemodeyourein");
attroff(A_BOLD);
printw(" game.\n");
for (int i = 0; i < start_x; i++)
printw(" ");
// Players turn
if (gamemode == 0)
printw("It is your turn. The computer doesn't have to think like you inferior humans.\n\n");
else if (gamemode == 1)
{
printw("It is Player ");
attron(A_BOLD); printw("%d", current_player); attroff(A_BOLD);
printw("'s turn.\n");
}
for (int i = 0; i < start_x; i++)
printw(" ");
// pixels_needed
printw("You need ");
attron(A_BOLD); printw("%d ", pixels_needed); attroff(A_BOLD);
printw("pixels in a row to win.\n");
for (int i = 0; i < start_x; i++)
printw(" ");
// Use the Vi keys [ hjkl ] or [ WASD ] to move the cursor.
printw("Use the Vi keys ");
attron(A_BOLD); printw("[ hjkl ] "); attroff(A_BOLD);
printw("or ");
attron(A_BOLD); printw("[ wasd ] "); attroff(A_BOLD);
printw("to move the cursor.\n");
for (int i = 0; i < start_x; i++)
printw(" ");
// Confirm your choice with [ Space ] or [ Enter ].
printw("Confirm your choice with ");
attron(A_BOLD); printw("[ Space ] "); attroff(A_BOLD);
printw("or ");
attron(A_BOLD); printw("[ Enter ]"); attroff(A_BOLD);
printw(".\n");
for (int i = 0; i < start_x; i++)
printw(" ");
// Quit with [ q ].
printw("Quit with ");
attron(A_BOLD); printw("[ q ]"); attroff(A_BOLD);
printw(".");
}
void render_title(int start_y, int start_x)
{
// Render the title
// If we have ASCII art, here will be ASCII art
move(start_y, start_x);
int middle = ((grid[0].size() * 6) / 2);
for (int i = 0; i < grid[0].size(); i++)
{
printw("======");
}
std::string title = "TIC TAC TOE";
mvprintw(start_y + 1, (middle - (title.length() / 2)) + start_x, "%s\n",title.c_str());
move(start_y + 2, start_x);
for (int i = 0; i < grid[0].size(); i++)
{
printw("======");
}
printw("\n");
}
// Function for drawing a rectangle without requiring to spawn a window
void make_rectangle(int start_y, int start_x, int end_y, int end_x)
{
mvhline(start_y ,start_x, 0, end_x-start_x);
mvhline(end_y, start_x, 0, end_x-start_x);
mvvline(start_y, start_x, 0, end_y-start_y);
mvvline(start_y, end_x, 0, end_y-start_y);
mvaddch(start_y, start_x, ACS_ULCORNER);
mvaddch(end_y, start_x, ACS_LLCORNER);
mvaddch(start_y, end_x, ACS_URCORNER);
mvaddch(end_y, end_x, ACS_LRCORNER);
}
// Function for rendering the grid
void render_grid()
{
render_title(1, 2);
int start_y = 5, start_x = 2;
int y_pos, x_pos;
// Render the actual grid
for (int y = 0; y < grid.size(); y++)
{
move(start_y + y * 2 + 1, start_x + 1);
for (int x = 0; x < grid[0].size(); x++)
{
printw(" ");
// Render selected pixel on the left
if (get_grid_sel(y, x) == true)
printw(">");
else
printw(" ");
// Render pixel value
char this_pixel;
switch (get_grid_val(y, x))
{
case 0:
this_pixel = empty_pixel;
break;
case 1:
attron(COLOR_PAIR(player_one_color));
this_pixel = player_one_pixel;
break;
case 2:
attron(COLOR_PAIR(player_two_color));
this_pixel = player_two_pixel;
break;
default:
this_pixel = unknown_pixel;
}
printw("%c", this_pixel);
attroff(COLOR_PAIR(player_one_color));
attroff(COLOR_PAIR(player_two_color));
// Render selected pixel on the right
if (get_grid_sel(y, x) == true)
printw("<");
else
printw(" ");
// Render separator
if (x != grid[0].size() - 1)
{
printw(" |");
}
}
// Begin a new line and render the break
printw("\n");
if (y != grid.size() - 1)
{
getyx(stdscr, y_pos, x_pos);
move(y_pos, start_x + 1);
for (int x = 0; x < grid[0].size()-1; x++)
printw("------");
// Print one character less on the last x position
printw("-----");
}
// Repeat on a new line
printw("\n");
}
if (current_player == 1)
attron(COLOR_PAIR(player_one_color));
else if (current_player == 2)
attron(COLOR_PAIR(player_two_color));
make_rectangle(start_y, start_x, start_y + grid.size() * 2, start_x + grid[0].size() * 6);
if (current_player == 1)
attron(COLOR_PAIR(player_one_color));
else if (current_player == 2)
attron(COLOR_PAIR(player_two_color));
attroff(COLOR_PAIR(current_player));
mvprintw(start_y + grid.size() * 2, start_x + 2, "Turn: %d/%d", turn, (grid.size() * grid[0].size())/2);
}
// Function for printing completely centered
void mvcprintw( int pos_y, std::string to_print )
{
int length = to_print.length();
mvprintw(pos_y, (max_x / 2) - (length / 2), to_print.c_str());
}
| 31.432907 | 124 | 0.651116 | [
"render",
"vector"
] |
39d5d4863873fc15d439b18088eaf4f9cf9bef0a | 1,124 | cpp | C++ | Geometry/geometry.cpp | xubenhao/VisualAlgorithm | 5fc45d9a4fc58569953fe3d880517adcd2fb0881 | [
"Apache-2.0"
] | 1 | 2021-01-29T02:12:53.000Z | 2021-01-29T02:12:53.000Z | Geometry/geometry.cpp | xubenhao/VisualAlgorithm | 5fc45d9a4fc58569953fe3d880517adcd2fb0881 | [
"Apache-2.0"
] | null | null | null | Geometry/geometry.cpp | xubenhao/VisualAlgorithm | 5fc45d9a4fc58569953fe3d880517adcd2fb0881 | [
"Apache-2.0"
] | null | null | null | // Author : XuBenHao
// Version : 1.0.0
// Mail : xbh370970843@163.com
// Copyright : XuBenHao 2020 - 2030
#include "geometry.h"
namespace NGeometry
{
Geometry::Geometry(QObject* parent)
: QObject(parent)
{
}
Geometry::~Geometry()
{
}
void Geometry::Draw(
NTransform::Transform* pTrans_,
QPainter& painter)
{
Q_UNUSED(pTrans_);
Q_UNUSED(painter);
}
void Geometry::Draw(QPainter& painter)
{
Q_UNUSED(painter);
}
void Geometry::Trans(
NTransform::Transform* pTrans_)
{
Q_UNUSED(pTrans_);
}
Geometry* Geometry::GetTrans(
NTransform::Transform* pTrans_)
{
Q_UNUSED(pTrans_);
return nullptr;
}
Geometry* Geometry::DeepCopy()
{
return nullptr;
}
void Geometry::OutputDebugInfo(QFile& hFile_)
{
QString _str = QString::asprintf(
"This is geometry\n");
QByteArray _nByteArr = _str.toUtf8();
hFile_.write(_nByteArr);
hFile_.flush();
}
}
| 18.129032 | 49 | 0.540925 | [
"geometry",
"transform"
] |
39d9331511aca7d628257229daa3b0be69068436 | 1,223 | cpp | C++ | 1015 KMP/main.cpp | SLAPaper/hihoCoder | 3f64d678c5dd46db36345736eb56880fb2d2c5fe | [
"MIT"
] | null | null | null | 1015 KMP/main.cpp | SLAPaper/hihoCoder | 3f64d678c5dd46db36345736eb56880fb2d2c5fe | [
"MIT"
] | null | null | null | 1015 KMP/main.cpp | SLAPaper/hihoCoder | 3f64d678c5dd46db36345736eb56880fb2d2c5fe | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <string>
using namespace std;
vector<int> getNext(string p)
{
vector<int> next = vector<int>(p.length());
next[0] = -1;
int i = 0;
int j = -1;
int m = p.length();
while (i < m - 1)
{
if (j == -1 || p[i] == p[j])
{
next[++i] = ++j;
}
else
{
j = next[j];
}
}
return next;
}
int kmp_count(string o, string p)
{
int n = o.length();
int m = p.length();
int i = 0;
int j = 0;
int count = 0;
vector<int> next = getNext(p);
while (i < n)
{
if (o[i] == p[j])
{
if (j == m - 1)
{
count += 1;
j = next[j];
}
else
{
++i;
++j;
}
}
else
{
j = next[j];
}
if (j == -1)
{
++i;
j = 0;
}
}
return count;
}
int main()
{
int N;
cin >> N;
for (int i = 0; i < N; ++i)
{
string p, o;
cin >> p >> o;
cout << kmp_count(o, p) << endl;
}
return 0;
}
| 14.22093 | 47 | 0.323794 | [
"vector"
] |
39ed32afc112ae274ac25d92af3543490c375082 | 10,689 | cpp | C++ | 03_opencv_detection/main.cpp | ifding/self-driving-car | fc8bc808d5439686f0ee24a4f0f3b1f5354df6c0 | [
"MIT"
] | 13 | 2018-05-15T16:33:11.000Z | 2019-02-14T06:46:31.000Z | 03_opencv_detection/main.cpp | ifding/autonomous-vehicles | a3dab9c5d66998ea277308b51f6be0049f605558 | [
"MIT"
] | null | null | null | 03_opencv_detection/main.cpp | ifding/autonomous-vehicles | a3dab9c5d66998ea277308b51f6be0049f605558 | [
"MIT"
] | 15 | 2018-05-18T19:19:48.000Z | 2021-11-03T04:36:50.000Z | #include <fstream>
#include <sstream>
#include <mutex>
#include <thread>
#include <queue>
#include <opencv2/dnn.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
using namespace cv;
using namespace dnn;
float confThreshold = 0.4, nmsThreshold = 0.4;
std::vector<std::string> classes;
inline void preprocess(const Mat& frame, Net& net, Size inpSize, float scale,
const Scalar& mean, bool swapRB);
void postprocess(Mat& frame, const std::vector<Mat>& out, Net& net);
void drawPred(int classId, float conf, int left, int top, int right, int bottom, Mat& frame);
template <typename T>
class QueueFPS : public std::queue<T>
{
public:
QueueFPS() : counter(0) {}
void push(const T& entry)
{
std::lock_guard<std::mutex> lock(mutex);
std::queue<T>::push(entry);
counter += 1;
if (counter == 1)
{
// Start counting from a second frame (warmup).
tm.reset();
tm.start();
}
}
T get()
{
std::lock_guard<std::mutex> lock(mutex);
T entry = this->front();
this->pop();
return entry;
}
float getFPS()
{
tm.stop();
double fps = counter / tm.getTimeSec();
tm.start();
return static_cast<float>(fps);
}
void clear()
{
std::lock_guard<std::mutex> lock(mutex);
while (!this->empty())
this->pop();
}
unsigned int counter;
private:
TickMeter tm;
std::mutex mutex;
};
int main(int argc, char** argv)
{
float scale = 1.0;
Scalar mean = Scalar(104, 177, 123);
bool swapRB = false;
int inpWidth = 300;
int inpHeight = 300;
size_t asyncNumReq = 0;
// Open file with classes names.
std::string file = "./input/object_detection_classes_coco.txt";
std::ifstream ifs(file.c_str());
if (!ifs.is_open())
CV_Error(Error::StsError, "File " + file + " not found");
std::string line;
while (std::getline(ifs, line))
{
classes.push_back(line);
}
std::string modelPath = "./input/frozen_inference_graph.pb";
std::string configPath = "./input/ssd_mobilenet_v2_coco_2018_03_29.pbtxt.txt";
std::string framework = "TensorFlow";
// Load a model.
Net net = readNet(modelPath, configPath, framework);
std::vector<String> outNames = net.getUnconnectedOutLayersNames();
// Create a window
static const std::string kWinName = "Object detection in OpenCV";
namedWindow(kWinName, WINDOW_NORMAL);
// Open a video file or an image file or a camera stream.
//VideoCapture cap;
VideoCapture cap("./input/video_1.mp4");
bool process = true;
// Frames capturing thread
QueueFPS<Mat> framesQueue;
std::thread framesThread([&](){
Mat frame;
while (process)
{
cap >> frame;
if (!frame.empty())
framesQueue.push(frame.clone());
else
break;
}
});
// Frames processing thread
QueueFPS<Mat> processedFramesQueue;
QueueFPS<std::vector<Mat> > predictionsQueue;
std::thread processingThread([&](){
std::queue<AsyncArray> futureOutputs;
Mat blob;
while (process)
{
// Get a next frame
Mat frame;
{
if (!framesQueue.empty())
{
frame = framesQueue.get();
if (asyncNumReq)
{
if (futureOutputs.size() == asyncNumReq)
frame = Mat();
}
else
framesQueue.clear(); // Skip the rest of frames
}
}
// Process the frame
if (!frame.empty())
{
preprocess(frame, net, Size(inpWidth, inpHeight), scale, mean, swapRB);
processedFramesQueue.push(frame);
if (asyncNumReq)
{
futureOutputs.push(net.forwardAsync());
}
else
{
std::vector<Mat> outs;
net.forward(outs, outNames);
predictionsQueue.push(outs);
}
}
while (!futureOutputs.empty() &&
futureOutputs.front().wait_for(std::chrono::seconds(0)))
{
AsyncArray async_out = futureOutputs.front();
futureOutputs.pop();
Mat out;
async_out.get(out);
predictionsQueue.push({out});
}
}
});
// Postprocessing and rendering loop
while (waitKey(1) < 0)
{
if (predictionsQueue.empty())
continue;
std::vector<Mat> outs = predictionsQueue.get();
Mat frame = processedFramesQueue.get();
postprocess(frame, outs, net);
if (predictionsQueue.counter > 1)
{
std::string label = format("Camera: %.2f FPS", framesQueue.getFPS());
putText(frame, label, Point(0, 15), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 255, 0));
label = format("Network: %.2f FPS", predictionsQueue.getFPS());
putText(frame, label, Point(0, 30), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 255, 0));
label = format("Skipped frames: %d", framesQueue.counter - predictionsQueue.counter);
putText(frame, label, Point(0, 45), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 255, 0));
}
imshow(kWinName, frame);
}
process = false;
framesThread.join();
processingThread.join();
return 0;
}
inline void preprocess(const Mat& frame, Net& net, Size inpSize, float scale,
const Scalar& mean, bool swapRB)
{
static Mat blob;
// Create a 4D blob from a frame.
if (inpSize.width <= 0) inpSize.width = frame.cols;
if (inpSize.height <= 0) inpSize.height = frame.rows;
blobFromImage(frame, blob, 1.0, inpSize, Scalar(), swapRB, false, CV_8U);
// Run a model.
net.setInput(blob, "", scale, mean);
if (net.getLayer(0)->outputNameToIndex("im_info") != -1) // Faster-RCNN or R-FCN
{
resize(frame, frame, inpSize);
Mat imInfo = (Mat_<float>(1, 3) << inpSize.height, inpSize.width, 1.6f);
net.setInput(imInfo, "im_info");
}
}
void postprocess(Mat& frame, const std::vector<Mat>& outs, Net& net)
{
static std::vector<int> outLayers = net.getUnconnectedOutLayers();
std::vector<int> classIds;
std::vector<float> confidences;
std::vector<Rect> boxes;
// Network produces output blob with a shape 1x1xNx7 where N is a number of
// detections and an every detection is a vector of values
// [batchId, classId, confidence, left, top, right, bottom]
CV_Assert(outs.size() > 0);
for (size_t k = 0; k < outs.size(); k++)
{
float* data = (float*)outs[k].data;
for (size_t i = 0; i < outs[k].total(); i += 7)
{
float confidence = data[i + 2];
if (confidence > confThreshold)
{
int left = (int)data[i + 3];
int top = (int)data[i + 4];
int right = (int)data[i + 5];
int bottom = (int)data[i + 6];
int width = right - left + 1;
int height = bottom - top + 1;
if (width <= 2 || height <= 2)
{
left = (int)(data[i + 3] * frame.cols);
top = (int)(data[i + 4] * frame.rows);
right = (int)(data[i + 5] * frame.cols);
bottom = (int)(data[i + 6] * frame.rows);
width = right - left + 1;
height = bottom - top + 1;
}
classIds.push_back((int)(data[i + 1]) - 1); // Skip 0th background class id.
boxes.push_back(Rect(left, top, width, height));
confidences.push_back(confidence);
}
}
}
// NMS is used inside Region layer only on DNN_BACKEND_OPENCV for another backends we need NMS in sample
// or NMS is required if number of outputs > 1
if (outLayers.size() > 1)
{
std::map<int, std::vector<size_t> > class2indices;
for (size_t i = 0; i < classIds.size(); i++)
{
if (confidences[i] >= confThreshold)
{
class2indices[classIds[i]].push_back(i);
}
}
std::vector<Rect> nmsBoxes;
std::vector<float> nmsConfidences;
std::vector<int> nmsClassIds;
for (auto it = class2indices.begin(); it != class2indices.end(); ++it)
{
std::vector<Rect> localBoxes;
std::vector<float> localConfidences;
std::vector<size_t> classIndices = it->second;
for (size_t i = 0; i < classIndices.size(); i++)
{
localBoxes.push_back(boxes[classIndices[i]]);
localConfidences.push_back(confidences[classIndices[i]]);
}
std::vector<int> nmsIndices;
NMSBoxes(localBoxes, localConfidences, confThreshold, nmsThreshold, nmsIndices);
for (size_t i = 0; i < nmsIndices.size(); i++)
{
size_t idx = nmsIndices[i];
nmsBoxes.push_back(localBoxes[idx]);
nmsConfidences.push_back(localConfidences[idx]);
nmsClassIds.push_back(it->first);
}
}
boxes = nmsBoxes;
classIds = nmsClassIds;
confidences = nmsConfidences;
}
for (size_t idx = 0; idx < boxes.size(); ++idx)
{
Rect box = boxes[idx];
drawPred(classIds[idx], confidences[idx], box.x, box.y,
box.x + box.width, box.y + box.height, frame);
}
}
void drawPred(int classId, float conf, int left, int top, int right, int bottom, Mat& frame)
{
rectangle(frame, Point(left, top), Point(right, bottom), Scalar(0, 255, 0));
std::string label = format("%.2f", conf);
if (!classes.empty())
{
CV_Assert(classId < (int)classes.size());
label = classes[classId] + ": " + label;
}
int baseLine;
Size labelSize = getTextSize(label, FONT_HERSHEY_SIMPLEX, 0.5, 1, &baseLine);
top = max(top, labelSize.height);
rectangle(frame, Point(left, top - labelSize.height),
Point(left + labelSize.width, top + baseLine), Scalar::all(255), FILLED);
putText(frame, label, Point(left, top), FONT_HERSHEY_SIMPLEX, 0.5, Scalar());
}
| 31.072674 | 108 | 0.538404 | [
"object",
"shape",
"vector",
"model"
] |
39f834a9fc5a62a6cda30464fc4c6c0b406b9668 | 13,786 | cpp | C++ | indra/test/llmessagetemplateparser_tut.cpp | SaladDais/LSO2-VM-Performance | d7ec9ad9daa9a2c9e48c5f06cd768606e3e50638 | [
"ISC"
] | 1 | 2022-01-29T07:10:03.000Z | 2022-01-29T07:10:03.000Z | indra/test/llmessagetemplateparser_tut.cpp | bloomsirenix/Firestorm-manikineko | 67e1bb03b2d05ab16ab98097870094a8cc9de2e7 | [
"Unlicense"
] | null | null | null | indra/test/llmessagetemplateparser_tut.cpp | bloomsirenix/Firestorm-manikineko | 67e1bb03b2d05ab16ab98097870094a8cc9de2e7 | [
"Unlicense"
] | 1 | 2021-10-01T22:22:27.000Z | 2021-10-01T22:22:27.000Z | /**
* @file llmessagetemplateparser_tut.cpp
* @date April 2007
* @brief LLMessageTemplateParser unit tests
*
* $LicenseInfo:firstyear=2006&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2010, Linden Research, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License only.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
#include "linden_common.h"
#include "llmessagetemplateparser.h"
#include "lltut.h"
namespace tut
{
struct LLMessageTemplateParserTestData {
LLMessageTemplateParserTestData() : mMessage("unset message")
{
}
~LLMessageTemplateParserTestData()
{
}
void ensure_next(LLTemplateTokenizer & tokens,
std::string value,
U32 line)
{
std::string next = tokens.next();
ensure_equals(mMessage + " token matches", next, value);
ensure_equals(mMessage + " line matches", tokens.line(), line);
}
char * prehash(const char * name)
{
return LLMessageStringTable::getInstance()->getString(name);
}
void ensure_block_attributes(std::string identifier,
const LLMessageTemplate * message,
const char * name,
EMsgBlockType type,
S32 number,
S32 total_size)
{
const LLMessageBlock * block = message->getBlock(prehash(name));
identifier = identifier + ":" + message->mName + ":" + name + " block";
ensure(identifier + " exists", block != NULL);
ensure_equals(identifier + " name", block->mName, prehash(name));
ensure_equals(identifier + " type", block->mType, type);
ensure_equals(identifier + " number", block->mNumber, number);
ensure_equals(identifier + " total size", block->mTotalSize, total_size);
}
void ensure_variable_attributes(std::string identifier,
const LLMessageBlock * block,
const char * name,
EMsgVariableType type,
S32 size)
{
const LLMessageVariable * var = block->getVariable(prehash(name));
identifier = identifier + ":" + block->mName + ":" + name + " variable";
ensure(identifier + " exists", var != NULL);
ensure_equals(
identifier + " name", var->getName(), prehash(name));
ensure_equals(
identifier + " type", var->getType(), type);
ensure_equals(identifier + " size", var->getSize(), size);
}
std::string mMessage;
};
typedef test_group<LLMessageTemplateParserTestData> LLMessageTemplateParserTestGroup;
typedef LLMessageTemplateParserTestGroup::object LLMessageTemplateParserTestObject;
LLMessageTemplateParserTestGroup llMessageTemplateParserTestGroup("LLMessageTemplateParser");
template<> template<>
void LLMessageTemplateParserTestObject::test<1>()
// tests tokenizer constructor and next methods
{
mMessage = "test method 1 walkthrough";
LLTemplateTokenizer tokens("first line\nnext\t line\n\nfourth");
ensure_next(tokens, "first", 1);
ensure_next(tokens, "line", 1);
ensure_next(tokens, "next", 2);
ensure_next(tokens, "line", 2);
ensure_next(tokens, "fourth", 4);
tokens = LLTemplateTokenizer("\n\t{ \t Test1 Fixed \n 523 }\n\n");
ensure(tokens.want("{"));
ensure_next(tokens, "Test1", 2);
ensure_next(tokens, "Fixed", 2);
ensure_next(tokens, "523", 3);
ensure(tokens.want("}"));
tokens = LLTemplateTokenizer("first line\nnext\t line\n\nfourth");
ensure(tokens.want("first"));
ensure_next(tokens, "line", 1);
ensure_next(tokens, "next", 2);
ensure_next(tokens, "line", 2);
ensure(tokens.want("fourth"));
}
template<> template<>
void LLMessageTemplateParserTestObject::test<2>()
// tests tokenizer want method
{
// *NOTE: order matters
LLTemplateTokenizer tokens("first line\nnext\t line\n\nfourth");
ensure_equals("wants first token", tokens.want("first"), true);
ensure_equals("doesn't want blar token", tokens.want("blar"), false);
ensure_equals("wants line token", tokens.want("line"), true);
}
template<> template<>
void LLMessageTemplateParserTestObject::test<3>()
// tests tokenizer eof methods
{
LLTemplateTokenizer tokens("single\n\n");
ensure_equals("is not at eof at beginning", tokens.atEOF(), false);
ensure_equals("doesn't want eof", tokens.wantEOF(), false);
ensure_equals("wants the first token just to consume it",
tokens.want("single"), true);
ensure_equals("is not at eof in middle", tokens.atEOF(), false);
ensure_equals("wants eof", tokens.wantEOF(), true);
ensure_equals("is at eof at end", tokens.atEOF(), true);
}
template<> template<>
void LLMessageTemplateParserTestObject::test<4>()
// tests variable parsing method
{
LLTemplateTokenizer tokens(std::string("{ Test0 \n\t\n U32 \n\n }"));
LLMessageVariable * var = LLTemplateParser::parseVariable(tokens);
ensure("test0 var parsed", var != 0);
ensure_equals("name of variable", std::string(var->getName()), std::string("Test0"));
ensure_equals("type of variable is U32", var->getType(), MVT_U32);
ensure_equals("size of variable", var->getSize(), 4);
delete var;
std::string message_string("\n\t{ \t Test1 Fixed \n 523 }\n\n");
tokens = LLTemplateTokenizer(message_string);
var = LLTemplateParser::parseVariable(tokens);
ensure("test1 var parsed", var != 0);
ensure_equals("name of variable", std::string(var->getName()), std::string("Test1"));
ensure_equals("type of variable is Fixed", var->getType(), MVT_FIXED);
ensure_equals("size of variable", var->getSize(), 523);
delete var;
// *NOTE: the parsers call LL_ERRS() on invalid input, so we can't really
// test that :-(
}
template<> template<>
void LLMessageTemplateParserTestObject::test<5>()
// tests block parsing method
{
LLTemplateTokenizer tokens("{ BlockA Single { VarX F32 } }");
LLMessageBlock * block = LLTemplateParser::parseBlock(tokens);
ensure("blockA block parsed", block != 0);
ensure_equals("name of block", std::string(block->mName), std::string("BlockA"));
ensure_equals("type of block is Single", block->mType, MBT_SINGLE);
ensure_equals("total size of block", block->mTotalSize, 4);
ensure_equals("number of block defaults to 1", block->mNumber, 1);
ensure_equals("variable type of VarX is F32",
block->getVariableType(prehash("VarX")), MVT_F32);
ensure_equals("variable size of VarX",
block->getVariableSize(prehash("VarX")), 4);
delete block;
tokens = LLTemplateTokenizer("{ Stuff Variable { Id LLUUID } }");
block = LLTemplateParser::parseBlock(tokens);
ensure("stuff block parsed", block != 0);
ensure_equals("name of block", std::string(block->mName), std::string("Stuff"));
ensure_equals("type of block is Multiple", block->mType, MBT_VARIABLE);
ensure_equals("total size of block", block->mTotalSize, 16);
ensure_equals("number of block defaults to 1", block->mNumber, 1);
ensure_equals("variable type of Id is LLUUID",
block->getVariableType(prehash("Id")), MVT_LLUUID);
ensure_equals("variable size of Id",
block->getVariableSize(prehash("Id")), 16);
delete block;
tokens = LLTemplateTokenizer("{ Stuff2 Multiple 45 { Shid LLVector3d } }");
block = LLTemplateParser::parseBlock(tokens);
ensure("stuff2 block parsed", block != 0);
ensure_equals("name of block", std::string(block->mName), std::string("Stuff2"));
ensure_equals("type of block is Multiple", block->mType, MBT_MULTIPLE);
ensure_equals("total size of block", block->mTotalSize, 24);
ensure_equals("number of blocks", block->mNumber, 45);
ensure_equals("variable type of Shid is Vector3d",
block->getVariableType(prehash("Shid")), MVT_LLVector3d);
ensure_equals("variable size of Shid",
block->getVariableSize(prehash("Shid")), 24);
delete block;
}
template<> template<>
void LLMessageTemplateParserTestObject::test<6>()
// tests message parsing method on a simple message
{
std::string message_skel(
"{\n"
"TestMessage Low 1 NotTrusted Zerocoded\n"
"// comment \n"
" {\n"
"TestBlock1 Single\n"
" { Test1 U32 }\n"
" }\n"
" {\n"
" NeighborBlock Multiple 4\n"
" { Test0 U32 }\n"
" { Test1 U32 }\n"
" { Test2 U32 }\n"
" }\n"
"}");
LLTemplateTokenizer tokens(message_skel);
LLMessageTemplate * message = LLTemplateParser::parseMessage(tokens);
ensure("simple message parsed", message != 0);
ensure_equals("name of message", std::string(message->mName), std::string("TestMessage"));
ensure_equals("frequency is Low", message->mFrequency, MFT_LOW);
ensure_equals("trust is untrusted", message->mTrust, MT_NOTRUST);
ensure_equals("message number", message->mMessageNumber, (U32)((255 << 24) | (255 << 16) | 1));
ensure_equals("message encoding is zerocoded", message->mEncoding, ME_ZEROCODED);
ensure_equals("message deprecation is notdeprecated", message->mDeprecation, MD_NOTDEPRECATED);
LLMessageBlock * block = message->getBlock(prehash("NonexistantBlock"));
ensure("Nonexistant block does not exist", block == 0);
delete message;
}
template<> template<>
void LLMessageTemplateParserTestObject::test<7>()
// tests message parsing method on a deprecated message
{
std::string message_skel(
"{\n"
"TestMessageDeprecated High 34 Trusted Unencoded Deprecated\n"
" {\n"
"TestBlock2 Single\n"
" { Test2 S32 }\n"
" }\n"
"}");
LLTemplateTokenizer tokens(message_skel);
LLMessageTemplate * message = LLTemplateParser::parseMessage(tokens);
ensure("deprecated message parsed", message != 0);
ensure_equals("name of message", std::string(message->mName), std::string("TestMessageDeprecated"));
ensure_equals("frequency is High", message->mFrequency, MFT_HIGH);
ensure_equals("trust is trusted", message->mTrust, MT_TRUST);
ensure_equals("message number", message->mMessageNumber, (U32)34);
ensure_equals("message encoding is unencoded", message->mEncoding, ME_UNENCODED);
ensure_equals("message deprecation is deprecated", message->mDeprecation, MD_DEPRECATED);
delete message;
}
template<> template<> void LLMessageTemplateParserTestObject::test<8>()
// tests message parsing on RezMultipleAttachmentsFromInv, a possibly-faulty message
{
std::string message_skel(
"{\n\
RezMultipleAttachmentsFromInv Low 452 NotTrusted Zerocoded\n\
{\n\
AgentData Single\n\
{ AgentID LLUUID }\n\
{ SessionID LLUUID }\n\
} \n\
{\n\
HeaderData Single\n\
{ CompoundMsgID LLUUID } // All messages a single \"compound msg\" must have the same id\n\
{ TotalObjects U8 }\n\
{ FirstDetachAll BOOL }\n\
}\n\
{\n\
ObjectData Variable // 1 to 4 of these per packet\n\
{ ItemID LLUUID }\n\
{ OwnerID LLUUID }\n\
{ AttachmentPt U8 } // 0 for default\n\
{ ItemFlags U32 }\n\
{ GroupMask U32 }\n\
{ EveryoneMask U32 }\n\
{ NextOwnerMask U32 }\n\
{ Name Variable 1 }\n\
{ Description Variable 1 }\n\
}\n\
}\n\
");
LLTemplateTokenizer tokens(message_skel);
LLMessageTemplate * message = LLTemplateParser::parseMessage(tokens);
ensure("RezMultipleAttachmentsFromInv message parsed", message != 0);
ensure_equals("name of message", message->mName, prehash("RezMultipleAttachmentsFromInv"));
ensure_equals("frequency is low", message->mFrequency, MFT_LOW);
ensure_equals("trust is not trusted", message->mTrust, MT_NOTRUST);
ensure_equals("message number", message->mMessageNumber, (U32)((255 << 24) | (255 << 16) | 452));
ensure_equals("message encoding is zerocoded", message->mEncoding, ME_ZEROCODED);
ensure_block_attributes(
"RMAFI", message, "AgentData", MBT_SINGLE, 1, 16+16);
LLMessageBlock * block = message->getBlock(prehash("AgentData"));
ensure_variable_attributes("RMAFI",
block, "AgentID", MVT_LLUUID, 16);
ensure_variable_attributes("RMAFI",
block, "SessionID", MVT_LLUUID, 16);
ensure_block_attributes(
"RMAFI", message, "HeaderData", MBT_SINGLE, 1, 16+1+1);
block = message->getBlock(prehash("HeaderData"));
ensure_variable_attributes(
"RMAFI", block, "CompoundMsgID", MVT_LLUUID, 16);
ensure_variable_attributes(
"RMAFI", block, "TotalObjects", MVT_U8, 1);
ensure_variable_attributes(
"RMAFI", block, "FirstDetachAll", MVT_BOOL, 1);
ensure_block_attributes(
"RMAFI", message, "ObjectData", MBT_VARIABLE, 1, -1);
block = message->getBlock(prehash("ObjectData"));
ensure_variable_attributes("RMAFI", block, "ItemID", MVT_LLUUID, 16);
ensure_variable_attributes("RMAFI", block, "OwnerID", MVT_LLUUID, 16);
ensure_variable_attributes("RMAFI", block, "AttachmentPt", MVT_U8, 1);
ensure_variable_attributes("RMAFI", block, "ItemFlags", MVT_U32, 4);
ensure_variable_attributes("RMAFI", block, "GroupMask", MVT_U32, 4);
ensure_variable_attributes("RMAFI", block, "EveryoneMask", MVT_U32, 4);
ensure_variable_attributes("RMAFI", block, "NextOwnerMask", MVT_U32, 4);
ensure_variable_attributes("RMAFI", block, "Name", MVT_VARIABLE, 1);
ensure_variable_attributes("RMAFI", block, "Description", MVT_VARIABLE, 1);
delete message;
}
}
| 37.360434 | 102 | 0.690918 | [
"object"
] |
39f9bd9a5ecd631357071f874efbe505f3cbe6b1 | 1,255 | cpp | C++ | Strings/fully_justify.cpp | aneesh001/InterviewBit | fcbac096fd8e9554a52db10dc9e5a88cb8a83ef3 | [
"MIT"
] | null | null | null | Strings/fully_justify.cpp | aneesh001/InterviewBit | fcbac096fd8e9554a52db10dc9e5a88cb8a83ef3 | [
"MIT"
] | null | null | null | Strings/fully_justify.cpp | aneesh001/InterviewBit | fcbac096fd8e9554a52db10dc9e5a88cb8a83ef3 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
vector<string> fullJustify(vector<string> &A, int B) {
vector<string> ans;
int taken = 0;
while(taken < A.size()) {
int i = taken;
int sum = A[i].size();
while(i + 1 < A.size() && sum + 1 + A[i + 1].size() <= B) {
sum += 1 + A[i + 1].size();
i++;
}
string line;
if(i == A.size() - 1) {
for(int j = taken; j <= i; ++j) {
if(j != taken) {
line += " ";
}
line += A[j];
}
line += string(B - line.size(), ' ');
}
else {
int wc = 0;
int wl = 0;
for(int j = taken; j <= i; ++j) {
wl += A[j].size();
wc++;
}
if(wc == 1) {
line += A[taken];
line += string(B - line.size(), ' ');
}
else {
int sl = (B - wl) / (wc - 1);
int r = (B - wl) % (wc - 1);
for(int j = taken; j <= i; ++j) {
if(j != taken) {
line += string(sl, ' ');
if(r != 0) {
line += " ";
r--;
}
}
line += A[j];
}
}
}
ans.push_back(line);
taken = i + 1;
}
return ans;
}
int main(void) {
int n;
cin >> n;
vector<string> words(n);
for(int i = 0; i < n; ++i) {
cin >> words[i];
}
int l;
cin >> l;
for(string s: fullJustify(words, l)) {
cout << s << endl;
}
return 0;
} | 14.940476 | 61 | 0.422311 | [
"vector"
] |
39fb1ca74aa9ae17196a9c72e57fdd275209ba2e | 910 | cpp | C++ | algorithms/cpp/Problems 101-200/_162_FindPeakElement.cpp | shivamacs/LeetCode | f8f8b4e9872c47fbaaf9196c422f7e04986e6c3a | [
"MIT"
] | null | null | null | algorithms/cpp/Problems 101-200/_162_FindPeakElement.cpp | shivamacs/LeetCode | f8f8b4e9872c47fbaaf9196c422f7e04986e6c3a | [
"MIT"
] | null | null | null | algorithms/cpp/Problems 101-200/_162_FindPeakElement.cpp | shivamacs/LeetCode | f8f8b4e9872c47fbaaf9196c422f7e04986e6c3a | [
"MIT"
] | null | null | null | /* Source - https://leetcode.com/problems/find-peak-element/
Author - Shivam Arora
*/
#include <bits/stdc++.h>
using namespace std;
int findPeakElement(vector<int>& nums) {
int n = nums.size();
int low = 0;
int high = n - 1;
while(low <= high) {
int mid = low + (high - low) / 2;
if((mid == 0 || nums[mid] > nums[mid - 1]) && (mid == n - 1 || nums[mid] > nums[mid + 1]))
return mid;
else if (mid > 0 && nums[mid] < nums[mid - 1])
high = mid - 1;
else if(mid < n - 1 && nums[mid] < nums[mid + 1])
low = mid + 1;
}
return low;
}
int main()
{
int n;
cout<<"Enter the number of elements: ";
cin>>n;
vector<int> nums(n);
cout<<"Enter elements: ";
for(int i = 0; i < n; i++)
cin>>nums[i];
cout<<"Index of peak element: "<<findPeakElement(nums)<<endl;
} | 22.75 | 98 | 0.49011 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.