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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d5c1211393ea9b33ab9990caf024545f7763778f | 10,073 | cpp | C++ | src/levels/level2.cpp | TomSavas/ScrewGeometry | 396a6302220de2fcd7f9a947b5c5a508c28ded69 | [
"MIT"
] | null | null | null | src/levels/level2.cpp | TomSavas/ScrewGeometry | 396a6302220de2fcd7f9a947b5c5a508c28ded69 | [
"MIT"
] | null | null | null | src/levels/level2.cpp | TomSavas/ScrewGeometry | 396a6302220de2fcd7f9a947b5c5a508c28ded69 | [
"MIT"
] | null | null | null | #include "levels/level2.h"
#include <utility>
#include "GLFW/glfw3.h"
#include "OBJ_Loader.h"
#include "game_objects/camera.h"
#include "game_objects/portal.h"
#include "components/model.h"
#include "components/transform.h"
#include "components/player_controller.h"
#include "components/portal_camera_controller.h"
#include "game.h"
#include "renderer/single_color_texture.h"
#include "renderer/framebuffer.h"
#include "renderer/renderbuffer.h"
Framebuffer *RenderTarget(glm::ivec2 size)
{
Framebuffer *fb = new Framebuffer();
fb->Bind();
Texture *tex = new Texture(size);
tex->Load();
tex->Bind();
fb->SetRenderTexture(tex);
Renderbuffer *depthStencilTarget = new Renderbuffer(size, GL_DEPTH24_STENCIL8);
depthStencilTarget->Bind();
fb->SetDepthStencilTarget(depthStencilTarget);
fb->CheckComplete();
fb->Unbind();
return fb;
}
Level2::~Level2()
{
}
void Level2::Load()
{
objl::Loader loader;
loader.LoadFile("../assets/models/cube.obj");
Texture *orangeTexture = new Texture("../assets/textures/dev_orange_256.jpeg", true, glm::vec2(10.f, 10.f));
//Texture *orangeTexture = new SingleColorTexture(255, 0, 0);
Texture *greyTexture = new Texture("../assets/textures/dev_grey_256.jpeg", true, glm::vec2(10.f, 10.f));
Model orangeCubeModel(loader.LoadedMeshes[0], *orangeTexture);
Model greyCubeModel(loader.LoadedMeshes[0], *greyTexture);
// light
unsigned char lightColor[3] = { 255, 255, 255 };
Texture *lightTexture = new SingleColorTexture(lightColor[0], lightColor[1], lightColor[2]);
DrawableGameObject *light = new DrawableGameObject("light");
light->GetComponent<Transform>()->position = glm::vec3(0.f, 3.f, 0.f);
light->GetComponent<Transform>()->scale = glm::vec3(0.25f);
light->AddComponent<Model>(Model(loader.LoadedMeshes[0], *lightTexture));
//light->AddComponent<PointLight>(PointLight(lightColor[0], lightColor[1], lightColor[2]));
objects.insert(std::make_pair(light->Name(), light));
// ground
DrawableGameObject *ground = new DrawableGameObject("ground");
ground->GetComponent<Transform>()->scale = glm::vec3(10, 0.01f, 10);
ground->AddComponent<Model>(greyCubeModel);
objects.insert(std::make_pair(ground->Name(), ground));
// tunnel
DrawableGameObject *leftWall = new DrawableGameObject("leftTunnelWall");
leftWall->GetComponent<Transform>()->position.x = 5.f;
leftWall->GetComponent<Transform>()->position.y = 1.f;
leftWall->GetComponent<Transform>()->scale = glm::vec3(0.25f, 1.f, 5.f);
leftWall->AddComponent<Model>(orangeCubeModel);
objects.insert(std::make_pair(leftWall->Name(), leftWall));
DrawableGameObject *rightWall = new DrawableGameObject("rightTunnelWall");
rightWall->GetComponent<Transform>()->position.x = 3.f;
rightWall->GetComponent<Transform>()->position.y = 1.f;
rightWall->GetComponent<Transform>()->scale = glm::vec3(0.25f, 1.f, 5.f);
rightWall->AddComponent<Model>(orangeCubeModel);
objects.insert(std::make_pair(rightWall->Name(), rightWall));
DrawableGameObject *topWall = new DrawableGameObject("topTunnelWall");
topWall->GetComponent<Transform>()->position.x = 4.f;
topWall->GetComponent<Transform>()->position.y = 1.75f;
topWall->GetComponent<Transform>()->scale = glm::vec3(.75f, 0.25f, 5.f);
topWall->AddComponent<Model>(orangeCubeModel);
objects.insert(std::make_pair(topWall->Name(), topWall));
// doorway
DrawableGameObject *leftBeam = new DrawableGameObject("leftDoorwayBeam");
leftBeam->GetComponent<Transform>()->position = glm::vec3(-5.f, 1.f, -3.f);
leftBeam->GetComponent<Transform>()->scale = glm::vec3(0.25f, 1.f, 0.25f);
leftBeam->AddComponent<Model>(orangeCubeModel);
objects.insert(std::make_pair(leftBeam->Name(), leftBeam));
DrawableGameObject *rightBeam = new DrawableGameObject("rightDoorwayBeam");
rightBeam->GetComponent<Transform>()->position = glm::vec3(-3.f, 1.f, -3.f);
rightBeam->GetComponent<Transform>()->scale = glm::vec3(0.25f, 1.f, 0.25f);
rightBeam->AddComponent<Model>(orangeCubeModel);
objects.insert(std::make_pair(rightBeam->Name(), rightBeam));
DrawableGameObject *topBeam = new DrawableGameObject("topDoorwayBeam");
topBeam->GetComponent<Transform>()->position = glm::vec3(-4.f, 1.75f, -3.f);
topBeam->GetComponent<Transform>()->scale = glm::vec3(.75f, 0.25f, 0.25f);
topBeam->AddComponent<Model>(orangeCubeModel);
objects.insert(std::make_pair(topBeam->Name(), topBeam));
//Framebuffer *fb = new Framebuffer();
//fb->Bind();
//glm::ivec2 renderTargetSize(800, 600);
//Texture *renderTarget = new Texture(renderTargetSize);
//renderTarget->Load();
//fb->SetRenderTexture(renderTarget);
//Renderbuffer *depthStencilTarget = new Renderbuffer(renderTargetSize, GL_DEPTH24_STENCIL8);
//depthStencilTarget->Bind();
//fb->SetDepthStencilTarget(depthStencilTarget);
//fb->CheckComplete();
//fb->Unbind();
//ShaderProgram *portalShader = new ShaderProgram("../src/shaders/default.vert", "../src/shaders/portal.frag");
//DrawableGameObject *doorwayPortal = new DrawableGameObject("doorwayPortal", *portalShader);
//doorwayPortal->GetComponent<Transform>()->position = glm::vec3(-4.f, .75f, -3.f);
//doorwayPortal->GetComponent<Transform>()->scale = glm::vec3(1.5f, 1.5f, 1.f);
//doorwayPortal->AddComponent<Framebuffer>(fb);
//doorwayPortal->AddComponent<Model>(Model::Quad(glm::vec3(1), *renderTarget));
// //doorwayPortal->AddComponent<Model>(Model::Quad(glm::vec3(1), Texture::DefaultTexture()));
//objects.insert(std::make_pair(doorwayPortal->Name(), doorwayPortal));
// portal
DrawableGameObject *targetPortalLeftBeam = new DrawableGameObject("targetPortalLeftBeam");
targetPortalLeftBeam->GetComponent<Transform>()->position = glm::vec3(-5.f, 1.f, 5.f);
targetPortalLeftBeam->GetComponent<Transform>()->scale = glm::vec3(0.25f, 1.f, 0.25f);
targetPortalLeftBeam->AddComponent<Model>(orangeCubeModel);
objects.insert(std::make_pair(targetPortalLeftBeam->Name(), targetPortalLeftBeam));
DrawableGameObject *targetPortalRightBeam = new DrawableGameObject("targetPortalRightBeam");
targetPortalRightBeam->GetComponent<Transform>()->position = glm::vec3(-3.f, 1.f, 5.f);
targetPortalRightBeam->GetComponent<Transform>()->scale = glm::vec3(0.25f, 1.f, 0.25f);
targetPortalRightBeam->AddComponent<Model>(orangeCubeModel);
objects.insert(std::make_pair(targetPortalRightBeam->Name(), targetPortalRightBeam));
DrawableGameObject *targetPortalTopBeam = new DrawableGameObject("targetPortalTopBeam");
targetPortalTopBeam->GetComponent<Transform>()->position = glm::vec3(-4.f, 1.75f, 5.f);
targetPortalTopBeam->GetComponent<Transform>()->scale = glm::vec3(.75f, 0.25f, 0.25f);
targetPortalTopBeam->AddComponent<Model>(orangeCubeModel);
objects.insert(std::make_pair(targetPortalTopBeam->Name(), targetPortalTopBeam));
//DrawableGameObject *portalTarget = new DrawableGameObject("portalTarget");
//portalTarget->GetComponent<Transform>()->position = glm::vec3(-4.f, .75f, 5.f);
//portalTarget->GetComponent<Transform>()->scale = glm::vec3(1.5f, 1.5f, 1.f);
//portalTarget->AddComponent<Model>(Model::Quad(glm::vec3(1), *(new SingleColorTexture(0, 255, 0))));
// //doorwayPortal->AddComponent<Model>(Model::Quad(glm::vec3(1), Texture::DefaultTexture()));
//objects.insert(std::make_pair(portalTarget->Name(), portalTarget));
DrawableGameObject *player = new DrawableGameObject("player");
player->GetComponent<Transform>()->position = glm::vec3(2.f, 1.f, 0);
player->GetComponent<Transform>()->scale = glm::vec3(0.3f, 1.f, 0.3f);
player->AddComponent<PlayerController>();
player->AddComponent<Model>(new Model(loader.LoadedMeshes[0], SingleColorTexture::DefaultTexture()));
player->AddComponent<Camera>(new Camera());
//DrawableGameObject *portalCamera = new DrawableGameObject("portalCamera");
//portalCamera->GetComponent<Transform>()->position = glm::vec3(2.f, 1.f, 0);
//portalCamera->GetComponent<Transform>()->scale = glm::vec3(0.1f);
//portalCamera->AddComponent<Model>(new Model(loader.LoadedMeshes[0], SingleColorTexture::DefaultTexture()));
//portalCamera->AddComponent<Camera>(new Camera());
//portalCamera->AddComponent<PortalCameraController>(new PortalCameraController(player->GetComponent<Transform>(), doorwayPortal->GetComponent<Transform>(), portalTarget->GetComponent<Transform>()->position));
//objects.insert(std::make_pair(portalCamera->Name(), portalCamera));
// portals
Portal *portal0 = new Portal("portal0", player, RenderTarget(glm::ivec2(800, 600)));
portal0->GetComponent<Transform>()->position = glm::vec3(2.749f, .75f, 3.f);
portal0->GetComponent<Transform>()->scale = glm::vec3(1.5f, 1.5f, 1.f);
portal0->GetComponent<Transform>()->rotation = glm::quat_cast(glm::eulerAngleY(-glm::pi<float>() / 2.f));
//portal0->AddComponent<Framebuffer>(fb);
Portal *portal1 = new Portal("portal1", player, RenderTarget(glm::ivec2(800, 600)));
portal1->GetComponent<Transform>()->position = glm::vec3(-4.f, .75f, -3.f);
portal1->GetComponent<Transform>()->scale = glm::vec3(1.5f, 1.5f, 1.f);
//portal1->AddComponent<Framebuffer>(fb);
//objects.insert(std::make_pair("portalCamera1", reinterpret_cast<DrawableGameObject*>(portal1->RemoteCamera())));
//objects.insert(std::make_pair("portalCamera0", reinterpret_cast<DrawableGameObject*>(portal0->RemoteCamera())));
portal0->AttachPortal(portal1);
portal1->AttachPortal(portal0);
objects.insert(std::make_pair(portal0->Name(), portal0));
objects.insert(std::make_pair(portal1->Name(), portal1));
portals.push_back(portal0);
portals.push_back(portal1);
// TODO: update player after the portals, otherwise we have stuttering
objects.insert(std::make_pair(player->Name(), player));
} | 49.377451 | 213 | 0.704457 | [
"model",
"transform"
] |
d5c17404235f0c64168927d78dd2581f36d184cd | 18,030 | cpp | C++ | modules/dnn/src/op_webnn.cpp | yash112-lang/opencv | be38d4ea932bc3a0d06845ed1a2de84acc2a09de | [
"Apache-2.0"
] | 2 | 2022-03-26T11:12:18.000Z | 2022-03-30T13:07:32.000Z | modules/dnn/src/op_webnn.cpp | yash112-lang/opencv | be38d4ea932bc3a0d06845ed1a2de84acc2a09de | [
"Apache-2.0"
] | null | null | null | modules/dnn/src/op_webnn.cpp | yash112-lang/opencv | be38d4ea932bc3a0d06845ed1a2de84acc2a09de | [
"Apache-2.0"
] | 1 | 2020-12-13T22:09:12.000Z | 2020-12-13T22:09:12.000Z | // This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
#include "precomp.hpp"
#include <fstream>
#include "op_webnn.hpp"
#include <opencv2/core/utils/configuration.private.hpp>
#include <opencv2/core/utils/logger.hpp>
#include "opencv2/core/utils/filesystem.hpp"
#include "opencv2/core/utils/filesystem.private.hpp"
#include <opencv2/dnn/shape_utils.hpp>
#include "net_impl.hpp"
namespace cv { namespace dnn {
#ifdef HAVE_WEBNN
CV__DNN_INLINE_NS_BEGIN
void Net::Impl::addWebnnOutputs(LayerData &ld)
{
CV_TRACE_FUNCTION();
Ptr<WebnnNet> layerNet;
auto it = ld.backendNodes.find(preferableBackend);
if (it != ld.backendNodes.end())
{
Ptr<BackendNode> node = it->second;
if (!node.empty())
{
Ptr<WebnnBackendNode> webnnNode = node.dynamicCast<WebnnBackendNode>();
CV_Assert(!webnnNode.empty()); CV_Assert(!webnnNode->net.empty());
layerNet = webnnNode->net;
}
}
for (int i = 0; i < ld.inputBlobsId.size(); ++i)
{
LayerData &inpLd = layers[ld.inputBlobsId[i].lid];
Ptr<BackendNode> inpNode = inpLd.backendNodes[preferableBackend];
if (!inpNode.empty())
{
Ptr<WebnnBackendNode> webnnInpNode = inpNode.dynamicCast<WebnnBackendNode>();
CV_Assert(!webnnInpNode.empty()); CV_Assert(!webnnInpNode->net.empty());
if (layerNet != webnnInpNode->net)
{
webnnInpNode->net->addOutput(webnnInpNode->name);
webnnInpNode->net->setUnconnectedNodes(webnnInpNode);
}
}
}
}
void Net::Impl::initWebnnBackend(const std::vector<LayerPin>& blobsToKeep_)
{
CV_TRACE_FUNCTION();
CV_Assert_N(preferableBackend == DNN_BACKEND_WEBNN, haveWebnn());
Ptr<WebnnNet> net;
for (MapIdToLayerData::iterator it = layers.begin(); it != layers.end(); ++it)
{
LayerData &ld = it->second;
if (ld.id == 0)
{
CV_Assert((netInputLayer->outNames.empty() && ld.outputBlobsWrappers.size() == 1) ||
(netInputLayer->outNames.size() == ld.outputBlobsWrappers.size()));
for (int i = 0; i < ld.outputBlobsWrappers.size(); ++i)
{
Ptr<WebnnBackendWrapper> wrapper = ld.outputBlobsWrappers[i].dynamicCast<WebnnBackendWrapper>();
std::string outputName = netInputLayer->outNames.empty() ? ld.name : netInputLayer->outNames[i];
outputName = ld.outputBlobsWrappers.size() > 1 ? (outputName + "." + std::to_string(i)) : outputName;
wrapper->name = outputName;
}
}
else
{
for (int i = 0; i < ld.outputBlobsWrappers.size(); ++i)
{
Ptr<WebnnBackendWrapper> wrapper = ld.outputBlobsWrappers[i].dynamicCast<WebnnBackendWrapper>();
std::string outputName = ld.outputBlobsWrappers.size() > 1 ? (ld.name + "." + std::to_string(i)) : ld.name;
wrapper->name = outputName;
}
}
}
// Build WebNN networks from sets of layers that support this
// backend. Split a whole model on several WebNN networks if
// some of layers are not implemented.
for (MapIdToLayerData::iterator it = layers.begin(); it != layers.end(); ++it)
{
LayerData &ld = it->second;
if (ld.id == 0 && ld.skip)
continue;
bool fused = ld.skip;
Ptr<Layer> layer = ld.layerInstance;
if (!fused && !layer->supportBackend(preferableBackend))
{
// For test use. when not using WebNN, the test case will fail
// with the following code.
CV_LOG_WARNING(NULL, "Layer " + ld.type + " name " + ld.name + " is unsupported by WebNN backend.");
addWebnnOutputs(ld);
net = Ptr<WebnnNet>();
layer->preferableTarget = DNN_TARGET_CPU;
for (int i = 0; i < ld.inputBlobsId.size(); ++i)
{
LayerData &inpLd = layers[ld.inputBlobsId[i].lid];
Ptr<BackendNode> inpNode = inpLd.backendNodes[preferableBackend];
if (!inpNode.empty()) {
Ptr<WebnnBackendNode> webnnNode = inpNode.dynamicCast<WebnnBackendNode>();
CV_Assert(!webnnNode.empty());
webnnNode->net->setUnconnectedNodes(webnnNode);
}
}
continue;
}
ld.skip = true; // Initially skip all WebNN supported layers.
// Create a new network if one of inputs from different WebNN graph.
std::vector<Ptr<BackendNode>> inputNodes;
for (int i = 0; i < ld.inputBlobsId.size(); ++i)
{
// Layer_Test_ROIPooling.Accuracy has 2 inputs inpLD = 0, 0 -> has 4 inputNodes (input, rois, input, rois)
if (inputNodes.size() == ld.inputBlobsId.size()) {
break;
}
LayerData &inpLd = layers[ld.inputBlobsId[i].lid];
Ptr<BackendNode> inpNode = inpLd.backendNodes[preferableBackend];
if (!inpNode.empty())
{
Ptr<WebnnBackendNode> webnnInpNode = inpNode.dynamicCast<WebnnBackendNode>();
CV_Assert(!webnnInpNode.empty()); CV_Assert(!webnnInpNode->net.empty());
if (webnnInpNode->net == net && !fused) {
inputNodes.push_back(inpNode);
continue;
}
}
if (net.empty()) {
net = Ptr<WebnnNet>(new WebnnNet());
}
if (!fused) {
std::vector<std::string> inputNames;
std::vector<cv::Mat> inputs;
auto curr_pos = inpLd.consumers.begin();
auto compare = [&ld] (const LayerPin& lp) { return lp.lid == ld.id; };
auto cons = curr_pos;
while ((cons = std::find_if(curr_pos, inpLd.consumers.end(), compare)) !=
inpLd.consumers.end()) {
int cons_inp = cons->oid;
Ptr<WebnnBackendWrapper> inpWrapper = inpLd.outputBlobsWrappers[cons_inp].
dynamicCast<WebnnBackendWrapper>();
CV_Assert(!inpWrapper.empty());
auto iter = std::find(inputNames.begin(), inputNames.end(),
inpWrapper->name);
if (iter == inputNames.end()) {
inputNames.push_back(inpWrapper->name);
inputs.push_back(inpLd.outputBlobs[cons_inp]);
}
curr_pos = cons + 1;
}
auto inps = net->setInputs(inputs, inputNames);
for (auto& inp : inps) {
WebnnBackendNode* node = new WebnnBackendNode(inp);
node->net = net;
inputNodes.emplace_back(Ptr<BackendNode>(node));
}
}
}
Ptr<BackendNode> node;
if (!net.empty())
{
if (fused)
{
bool inPlace = ld.inputBlobsId.size() == 1 && ld.outputBlobs.size() == 1 &&
ld.inputBlobs[0]->data == ld.outputBlobs[0].data;
CV_Assert(inPlace);
node = layers[ld.inputBlobsId[0].lid].backendNodes[preferableBackend];
ld.inputBlobsWrappers = layers[ld.inputBlobsId[0].lid].inputBlobsWrappers;
}
}
else {
net = Ptr<WebnnNet>(new WebnnNet());
}
if (!fused)
{
CV_Assert(ld.inputBlobsId.size() == inputNodes.size());
for (int i = 0; i < ld.inputBlobsId.size(); ++i)
{
int lid = ld.inputBlobsId[i].lid;
int oid = ld.inputBlobsId[i].oid;
if (oid == 0 || lid == 0)
continue;
auto webnnInpNode = inputNodes[i].dynamicCast<WebnnBackendNode>();
inputNodes[i] = Ptr<BackendNode>(new WebnnBackendNode(webnnInpNode->operand));
}
if (layer->supportBackend(preferableBackend))
{
if (ld.type == "Const") {
ml::Operand fake_operand;
Ptr<WebnnBackendNode> fake_input_node = Ptr<WebnnBackendNode>(new WebnnBackendNode(fake_operand));
fake_input_node->net = net;
inputNodes.push_back(fake_input_node);
}
node = layer->initWebnn(ld.inputBlobsWrappers, inputNodes);
for (int i = 0; i < ld.outputBlobsWrappers.size(); ++i)
{
Ptr<WebnnBackendWrapper> wrapper = ld.outputBlobsWrappers[i].dynamicCast<WebnnBackendWrapper>();
node.dynamicCast<WebnnBackendNode>()->name = wrapper->name;
}
}
else
{
continue;
}
}
else if (node.empty())
continue;
ld.backendNodes[preferableBackend] = node;
Ptr<WebnnBackendNode> webnnNode = node.dynamicCast<WebnnBackendNode>();
CV_Assert(!webnnNode.empty());
webnnNode->net = net;
if (ld.consumers.empty()) {
// TF EAST_text_detection
webnnNode->net->setUnconnectedNodes(webnnNode);
}
for (const auto& pin : blobsToKeep_)
{
if (pin.lid == ld.id)
{
webnnNode->net->addOutput(webnnNode->name);
break;
}
}
net->addBlobs(ld.inputBlobsWrappers);
net->addBlobs(ld.outputBlobsWrappers);
addWebnnOutputs(ld);
}
// Initialize all networks.
for (MapIdToLayerData::reverse_iterator it = layers.rbegin(); it != layers.rend(); ++it)
{
LayerData &ld = it->second;
auto iter = ld.backendNodes.find(preferableBackend);
if (iter == ld.backendNodes.end())
continue;
Ptr<BackendNode>& node = iter->second;
if (node.empty())
continue;
Ptr<WebnnBackendNode> webnnNode = node.dynamicCast<WebnnBackendNode>();
if (webnnNode.empty())
continue;
CV_Assert(!webnnNode->net.empty());
if (!webnnNode->net->isInitialized())
{
webnnNode->net->setUnconnectedNodes(webnnNode);
webnnNode->net->createNet((Target)preferableTarget);
ld.skip = false;
}
}
}
CV__DNN_INLINE_NS_END
namespace webnn {
ml::Operand BuildConstant(const ml::GraphBuilder& builder,
const std::vector<int32_t>& dimensions,
const void* value,
size_t size,
ml::OperandType type) {
ml::OperandDescriptor desc;
desc.type = type;
desc.dimensions = dimensions.data();
desc.dimensionsCount = (uint32_t)dimensions.size();
ml::ArrayBufferView resource;
resource.buffer = const_cast<void*>(value);
resource.byteLength = size;
return builder.Constant(&desc, &resource);
}
}
static std::string kDefaultInpLayerName = "opencv_webnn_empty_inp_layer_name";
static std::vector<Ptr<WebnnBackendWrapper> >
webnnWrappers(const std::vector<Ptr<BackendWrapper> >& ptrs)
{
std::vector<Ptr<WebnnBackendWrapper> > wrappers(ptrs.size());
for (int i = 0; i < ptrs.size(); ++i)
{
CV_Assert(!ptrs[i].empty());
wrappers[i] = ptrs[i].dynamicCast<WebnnBackendWrapper>();
CV_Assert(!wrappers[i].empty());
}
return wrappers;
}
// WebnnNet
WebnnNet::WebnnNet()
{
hasNetOwner = false;
device_name = "CPU";
#ifdef __EMSCRIPTEN__
context = ml::Context(emscripten_webnn_create_context());
#else
WebnnProcTable backendProcs = webnn_native::GetProcs();
webnnProcSetProcs(&backendProcs);
context = ml::Context(webnn_native::CreateContext());
#endif
builder = ::ml::CreateGraphBuilder(context);
namedOperands = ::ml::CreateNamedOperands();
}
void WebnnNet::addOutput(const std::string& name)
{
requestedOutputs.push_back(name);
}
void WebnnNet::createNet(Target targetId) {
init(targetId);
}
void WebnnNet::init(Target targetId)
{
switch (targetId)
{
case DNN_TARGET_CPU:
device_name = "CPU";
break;
case DNN_TARGET_OPENCL:
device_name = "GPU";
break;
default:
CV_Error(Error::StsNotImplemented, "Unknown target");
};
graph = builder.Build(namedOperands);
CV_Assert(graph!=nullptr);
isInit = true;
}
std::vector<ml::Operand> WebnnNet::setInputs(const std::vector<cv::Mat>& inputs,
const std::vector<std::string>& names) {
CV_Assert_N(inputs.size() == names.size());
std::vector<ml::Operand> current_inp;
for (size_t i = 0; i < inputs.size(); i++)
{
auto& m = inputs[i];
std::vector<int32_t> dimensions = webnn::getShape(m);
ml::OperandDescriptor descriptor;
descriptor.dimensions = dimensions.data();
descriptor.dimensionsCount = dimensions.size();
if (m.type() == CV_32F)
{
descriptor.type = ml::OperandType::Float32;
}
else
{
CV_Error(Error::StsNotImplemented, format("Unsupported data type %s", typeToString(m.type()).c_str()));
}
ml::Operand inputOperand = builder.Input(names[i].c_str(), &descriptor);
current_inp.push_back(std::move(inputOperand));
}
inputNames = names;
return current_inp;
}
void WebnnNet::setUnconnectedNodes(Ptr<WebnnBackendNode>& node) {
outputNames.push_back(node->name);
namedOperands.Set(outputNames.back().c_str(), node->operand);
}
bool WebnnNet::isInitialized()
{
return isInit;
}
void WebnnNet::reset()
{
allBlobs.clear();
isInit = false;
}
void WebnnNet::addBlobs(const std::vector<cv::Ptr<BackendWrapper> >& ptrs)
{
auto wrappers = webnnWrappers(ptrs);
for (const auto& wrapper : wrappers)
{
std::string name = wrapper->name;
name = name.empty() ? kDefaultInpLayerName : name;
allBlobs.insert({name, wrapper});
}
}
void WebnnNet::forward(const std::vector<Ptr<BackendWrapper> >& outBlobsWrappers, bool isAsync)
{
CV_LOG_DEBUG(NULL, "WebnnNet::forward(" << (isAsync ? "async" : "sync") << ")");
ml::NamedInputs named_inputs = ::ml::CreateNamedInputs();
std::vector<ml::Input> inputs(inputNames.size());
for (int i = 0; i < inputNames.size(); ++i) {
const std::string& name = inputNames[i];
ml::Input& input = inputs[i];
auto blobIt = allBlobs.find(name);
CV_Assert(blobIt != allBlobs.end());
const Ptr<WebnnBackendWrapper> wrapper = blobIt->second;
input.resource.buffer = wrapper->host->data;
input.resource.byteLength = wrapper->size;
named_inputs.Set(name.c_str(), &input);
}
std::vector<Ptr<WebnnBackendWrapper> > outs = webnnWrappers(outBlobsWrappers);
ml::NamedOutputs named_outputs = ::ml::CreateNamedOutputs();
std::vector<ml::ArrayBufferView> outputs(outs.size());
for (int i = 0; i < outs.size(); ++i) {
const std::string& name = outs[i]->name;
ml::ArrayBufferView& output = outputs[i];
output.buffer = outs[i]->host->data;
// std::cout<<"host data size: "<<outs[i]->host->total()*outs[i]->host->elemSize()<<std::endl;
output.byteLength = outs[i]->size;
// std::cout<<"outs[i]->size: "<< outs[i]->size << std::endl;
named_outputs.Set(name.c_str(), &output);
}
ml::ComputeGraphStatus status = graph.Compute(named_inputs, named_outputs);
if (status != ::ml::ComputeGraphStatus::Success) {
CV_Error(Error::StsAssert, format("Failed to compute: %d", int(status)));
}
}
// WebnnBackendNode
WebnnBackendNode::WebnnBackendNode(ml::Operand&& _operand)
: BackendNode(DNN_BACKEND_WEBNN), operand(std::move(_operand)) {}
WebnnBackendNode::WebnnBackendNode(ml::Operand& _operand)
: BackendNode(DNN_BACKEND_WEBNN), operand(_operand) {}
// WebnnBackendWrapper
WebnnBackendWrapper::WebnnBackendWrapper(int targetId, cv::Mat& m)
: BackendWrapper(DNN_BACKEND_WEBNN, targetId)
{
size = m.total() * m.elemSize();
// buffer.reset(new char[size]);
// std::memcpy(buffer.get(), m.data, size);
// dimensions = getShape<int32_t>(m);
// descriptor.dimensions = dimensions.data();
// descriptor.dimensionsCount = dimensions.size();
if (m.type() == CV_32F)
{
descriptor.type = ml::OperandType::Float32;
}
else
{
CV_Error(Error::StsNotImplemented, format("Unsupported data type %s", typeToString(m.type()).c_str()));
}
host = &m;
}
WebnnBackendWrapper::~WebnnBackendWrapper()
{
// nothing
}
void WebnnBackendWrapper::copyToHost()
{
CV_LOG_DEBUG(NULL, "WebnnBackendWrapper::copyToHost()");
//CV_Error(Error::StsNotImplemented, "");
}
void WebnnBackendWrapper::setHostDirty()
{
CV_LOG_DEBUG(NULL, "WebnnBackendWrapper::setHostDirty()");
//CV_Error(Error::StsNotImplemented, "");
}
void forwardWebnn(const std::vector<Ptr<BackendWrapper> >& outBlobsWrappers,
Ptr<BackendNode>& node, bool isAsync)
{
CV_Assert(!node.empty());
Ptr<WebnnBackendNode> webnnNode = node.dynamicCast<WebnnBackendNode>();
CV_Assert(!webnnNode.empty());
webnnNode->net->forward(outBlobsWrappers, isAsync);
}
#else
void forwardWebnn(const std::vector<Ptr<BackendWrapper> >& outBlobsWrappers,
Ptr<BackendNode>& operand, bool isAsync)
{
CV_Assert(false && "WebNN is not enabled in this OpenCV build");
}
#endif
}
} | 34.606526 | 123 | 0.577981 | [
"vector",
"model"
] |
d5c50f7bd30fefe5270a82d8e57dacb8938dfed6 | 1,380 | hpp | C++ | util/combinatorics.hpp | silentWatcher3/Ludo-The_Game | 03576725241fe89dfd7cc74110971877663086b0 | [
"MIT"
] | 16 | 2020-05-27T10:12:42.000Z | 2020-11-25T10:46:37.000Z | util/combinatorics.hpp | silentWatcher3/Ludo-The_Game | 03576725241fe89dfd7cc74110971877663086b0 | [
"MIT"
] | 20 | 2020-05-27T10:15:34.000Z | 2020-10-29T14:02:06.000Z | util/combinatorics.hpp | silentWatcher3/Ludo-The_Game | 03576725241fe89dfd7cc74110971877663086b0 | [
"MIT"
] | 15 | 2020-05-27T10:27:27.000Z | 2020-10-19T16:11:11.000Z | #pragma once
#include <vector>
namespace util
{
/*@brief Returns true if `num` can be written as a sum of some elements of the vector v; Else returns false*/
template <typename T = int>
bool isSum(T num, const std::vector<T> &v);
template <typename T = int>
std::vector<T> isSumOfElements(T num, const std::vector<T> &v);
} // namespace util
//DEFINITIONS
template <typename T>
bool util::isSum(T num, const std::vector<T> &v)
{
auto total = 1 << v.size();
T sum;
for (auto i = 0; i < total; ++i)
{
sum = 0;
for (auto j = 0; j < v.size(); ++j)
{
if (i & 1 << j)
{ //Cheching if the jth bit is set
sum += v[j];
}
}
if (num == sum)
return true;
}
return false;
}
template <typename T>
std::vector<T> util::isSumOfElements(T num, const std::vector<T> &v)
{
auto sum = 0;
auto total = 1 << v.size();
std::vector<T> elements;
for (int i = 0; i < total; ++i)
{
for (size_t j = 0; j < v.size(); ++j)
{
if (i & 1 << j)
{ //Cheching if the jth bit is set
elements.push_back(v[j]);
sum += v[j];
}
}
if (num == sum)
return elements;
sum = 0;
elements.clear();
}
return {};
}
| 21.904762 | 113 | 0.478986 | [
"vector"
] |
d5c5db5b2e95b554315df7b17a95c86d5458900b | 3,762 | cpp | C++ | tests/ka/test_algorithm.cpp | Maelic/libqi | 0a92452be48376004e5e5ebfe2bd0683725d033e | [
"BSD-3-Clause"
] | null | null | null | tests/ka/test_algorithm.cpp | Maelic/libqi | 0a92452be48376004e5e5ebfe2bd0683725d033e | [
"BSD-3-Clause"
] | null | null | null | tests/ka/test_algorithm.cpp | Maelic/libqi | 0a92452be48376004e5e5ebfe2bd0683725d033e | [
"BSD-3-Clause"
] | null | null | null | #include <gtest/gtest.h>
#include <ka/algorithm.hpp>
#include <string>
#include <vector>
#include <deque>
#include <list>
#include <forward_list>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <boost/container/static_vector.hpp>
#include <boost/container/small_vector.hpp>
#include <boost/container/slist.hpp>
#include <boost/container/flat_set.hpp>
#include <boost/container/flat_map.hpp>
template<typename T>
struct EraseIfSequence : testing::Test {
};
using sequences = testing::Types<
std::string, std::vector<int>, std::deque<int>, std::list<int>,
std::forward_list<int>, boost::container::static_vector<int, 9>,
boost::container::small_vector<int, 9>, boost::container::slist<int>>;
TYPED_TEST_SUITE(EraseIfSequence, sequences);
struct even_t {
/// Arithmetic N
template<typename N>
bool operator()(N n) const {
return n % N{2} == N{0};
}
};
TYPED_TEST(EraseIfSequence, SequencesEmpty) {
using S = TypeParam;
S s;
ka::erase_if(s, even_t{});
EXPECT_EQ(S{}, s);
}
TYPED_TEST(EraseIfSequence, SequencesPredicateAlwaysFalse) {
using S = TypeParam;
S s{1, 3, 5};
ka::erase_if(s, even_t{});
EXPECT_EQ((S{1, 3, 5}), s);
}
TYPED_TEST(EraseIfSequence, SequencesPredicateAlwaysTrue) {
using S = TypeParam;
S s{4, 6, 8, 10};
ka::erase_if(s, even_t{});
EXPECT_EQ(S{}, s);
}
TYPED_TEST(EraseIfSequence, SequencesStandardCase) {
using S = TypeParam;
S s{1, 4, 6, 8, 3};
ka::erase_if(s, even_t{});
EXPECT_EQ((S{1, 3}), s);
}
template<typename T>
struct EraseIfAssociativeSequence : testing::Test {};
using associative_sequences = testing::Types<
std::map<int, char>, std::multimap<int, char>, std::unordered_map<int, char>,
boost::container::flat_map<int, char>, boost::container::flat_multimap<int, char>>;
TYPED_TEST_SUITE(EraseIfAssociativeSequence, associative_sequences);
struct even_key_t {
/// Pair<Arithmetic, _> T
template<typename T>
bool operator()(T const& pair) const {
using N = decltype(pair.first);
return pair.first % N{2} == N{0};
}
};
TYPED_TEST(EraseIfAssociativeSequence, AssociativeSequencesEmpty) {
using S = TypeParam;
S s;
ka::erase_if(s, even_key_t{});
EXPECT_EQ(S{}, s);
}
TYPED_TEST(EraseIfAssociativeSequence, AssociativeSequencesPredicateAlwaysFalse) {
using S = TypeParam;
S s{{1, 'a'}, {3, 'c'}, {5, 'e'}};
ka::erase_if(s, even_key_t{});
EXPECT_EQ((S{{1, 'a'}, {3, 'c'}, {5, 'e'}}), s);
}
TYPED_TEST(EraseIfAssociativeSequence, AssociativeSequencesPredicateAlwaysTrue) {
using S = TypeParam;
S s{{4, 'd'}, {6, 'f'}, {8, 'h'}, {10, 'j'}};
ka::erase_if(s, even_key_t{});
EXPECT_EQ(S{}, s);
}
TYPED_TEST(EraseIfAssociativeSequence, AssociativeSequencesStandardCase) {
using S = TypeParam;
S s{{1, 'a'}, {4, 'd'}, {6, 'f'}, {8, 'h'}, {3, 'c'}};
ka::erase_if(s, even_key_t{});
EXPECT_EQ((S{{1, 'a'}, {3, 'c'}}), s);
}
template<typename T>
struct EraseIfSet : testing::Test {};
using sets = testing::Types<
std::set<int>, std::multiset<int>, std::unordered_set<int>,
boost::container::flat_set<int>, boost::container::flat_multiset<int>>;
TYPED_TEST_SUITE(EraseIfSet, sets);
TYPED_TEST(EraseIfSet, SetsEmpty) {
using S = TypeParam;
S s;
ka::erase_if(s, even_t{});
EXPECT_EQ(S{}, s);
}
TYPED_TEST(EraseIfSet, SetsPredicateAlwaysFalse) {
using S = TypeParam;
S s{1, 3, 5, 3};
ka::erase_if(s, even_t{});
EXPECT_EQ((S{1, 3, 5, 3}), s);
}
TYPED_TEST(EraseIfSet, SetsPredicateAlwaysTrue) {
using S = TypeParam;
S s{4, 6, 8, 4, 10, 6};
ka::erase_if(s, even_t{});
EXPECT_EQ(S{}, s);
}
TYPED_TEST(EraseIfSet, SetsPredicateStandardCase) {
using S = TypeParam;
S s{1, 4, 1, 6, 6, 8, 3, 8, 3};
ka::erase_if(s, even_t{});
EXPECT_EQ((S{1, 1, 3, 3}), s);
}
| 25.591837 | 85 | 0.669591 | [
"vector"
] |
d5c70145e4383154ef81adfe5b6f7ebcfce0adf2 | 938 | cpp | C++ | cuda/src/gridding.cpp | duducheng/torch-points-kernels | aed9cf56ca61fe34b4880159951760e5dcb3a1db | [
"MIT"
] | 52 | 2020-04-14T14:55:18.000Z | 2021-07-19T12:36:22.000Z | cuda/src/gridding.cpp | duducheng/torch-points-kernels | aed9cf56ca61fe34b4880159951760e5dcb3a1db | [
"MIT"
] | 32 | 2020-04-21T10:43:22.000Z | 2021-07-29T12:27:28.000Z | cuda/src/gridding.cpp | duducheng/torch-points-kernels | aed9cf56ca61fe34b4880159951760e5dcb3a1db | [
"MIT"
] | 12 | 2020-06-03T03:14:33.000Z | 2021-07-25T21:50:31.000Z | #include "gridding.h"
#include "utils.h"
std::vector<torch::Tensor> gridding(float min_x, float max_x, float min_y, float max_y, float min_z,
float max_z, torch::Tensor ptcloud)
{
CHECK_CUDA(ptcloud);
CHECK_CONTIGUOUS(ptcloud);
cudaStream_t stream = at::cuda::getCurrentCUDAStream();
return gridding_kernel_warpper(min_x, max_x, min_y, max_y, min_z, max_z, ptcloud, stream);
}
torch::Tensor gridding_grad(torch::Tensor grid_pt_weights, torch::Tensor grid_pt_indexes,
torch::Tensor grad_grid)
{
CHECK_CUDA(grid_pt_weights);
CHECK_CONTIGUOUS(grid_pt_weights);
CHECK_CUDA(grid_pt_indexes);
CHECK_CONTIGUOUS(grid_pt_indexes);
CHECK_CUDA(grad_grid);
CHECK_CONTIGUOUS(grad_grid);
cudaStream_t stream = at::cuda::getCurrentCUDAStream();
return gridding_grad_kernel_warpper(grid_pt_weights, grid_pt_indexes, grad_grid, stream);
}
| 34.740741 | 100 | 0.710021 | [
"vector"
] |
d5c776d11678d35c2b5fdc881b12de4a59a786e6 | 1,257 | cpp | C++ | examples/console_reflection/main.cpp | dtmoodie/MetaObject | 8238d143d578ff9c0c6506e7e627eca15e42369e | [
"MIT"
] | 2 | 2017-10-26T04:41:49.000Z | 2018-02-09T05:12:19.000Z | examples/console_reflection/main.cpp | dtmoodie/MetaObject | 8238d143d578ff9c0c6506e7e627eca15e42369e | [
"MIT"
] | null | null | null | examples/console_reflection/main.cpp | dtmoodie/MetaObject | 8238d143d578ff9c0c6506e7e627eca15e42369e | [
"MIT"
] | 3 | 2017-01-08T21:09:48.000Z | 2018-02-10T04:27:32.000Z | #include "obj.hpp"
int main()
{
/*!
* \brief factory is a pointer to the global object factory
*/
std::shared_ptr<SystemTable> table = SystemTable::instance();
std::shared_ptr<mo::MetaObjectFactory> factory = mo::MetaObjectFactory::instance();
// call the inlined register translation unit function to register ConcreteImplementation
// to the global object registry
factory->registerTranslationUnit();
// Get a list of objects that inherit from ExampleInterface
auto constructors = factory->getConstructors(ExampleInterface::getHash());
// Print static object info
for (IObjectConstructor* constructor : constructors)
{
const IObjectInfo* info = constructor->GetObjectInfo();
if (const ExampleInterfaceInfo* interface_info = dynamic_cast<const ExampleInterfaceInfo*>(info))
{
interface_info->PrintHelp();
}
// Print reflection info
std::cout << info->Print() << std::endl;
}
// Construct an object
mo::IMetaObject* obj = factory->create("ConcreteImplementation");
if (ExampleInterface* interface_object = dynamic_cast<ExampleInterface*>(obj))
{
interface_object->foo();
}
delete obj;
return 0;
}
| 31.425 | 105 | 0.672235 | [
"object"
] |
d5c94966b2713e0fd4a28bdee6e5b0827edbfb86 | 15,557 | cpp | C++ | src/penguinv/penguinv.cpp | vrozin/penguinV | 9349e3d8aa50a114ab192795cdff9c2ef5f57509 | [
"BSD-3-Clause"
] | null | null | null | src/penguinv/penguinv.cpp | vrozin/penguinV | 9349e3d8aa50a114ab192795cdff9c2ef5f57509 | [
"BSD-3-Clause"
] | null | null | null | src/penguinv/penguinv.cpp | vrozin/penguinV | 9349e3d8aa50a114ab192795cdff9c2ef5f57509 | [
"BSD-3-Clause"
] | null | null | null | #include "penguinv.h"
#include "../image_function_helper.h"
namespace
{
struct ReferenceOwner
{
explicit ReferenceOwner( PenguinV_Image::Image & data_ )
: data( data_ )
{
}
PenguinV_Image::Image & data;
};
struct ConstReferenceOwner
{
explicit ConstReferenceOwner( const PenguinV_Image::Image & data_ )
: data( data_ )
{
}
const PenguinV_Image::Image & data;
};
class ImageManager
{
public:
explicit ImageManager( uint8_t requiredType )
: _registrator( ImageTypeManager::instance() )
, _type( requiredType )
{
}
~ImageManager()
{
for ( std::vector<ConstReferenceOwner *>::iterator data = _input.begin(); data != _input.end(); ++data )
delete *data;
for ( size_t i = 0u; i < _output.size(); ++i ) {
_restore( _outputClone[i], _output[i]->data );
delete _output[i];
}
}
const PenguinV_Image::Image & operator ()( const PenguinV_Image::Image & image )
{
if ( image.type() != _type ) {
_inputClone.push_back( _clone( image ) );
return _inputClone.back();
}
else {
return image;
}
}
PenguinV_Image::Image & operator ()( PenguinV_Image::Image & image )
{
if ( image.type() != _type ) {
_output.push_back( new ReferenceOwner( image ) );
_outputClone.push_back( _clone( image ) );
return _outputClone.back();
}
else {
return image;
}
}
private:
ImageTypeManager & _registrator;
std::vector< ConstReferenceOwner * > _input;
std::vector< ReferenceOwner * > _output;
std::vector< PenguinV_Image::Image > _inputClone;
std::vector< PenguinV_Image::Image > _outputClone;
uint8_t _type;
PenguinV_Image::Image _clone( const PenguinV_Image::Image & in )
{
PenguinV_Image::Image temp = _registrator.image( _type ).generate( in.width(), in.height(), in.colorCount() );
_registrator.convert( in.type(), _type )( in, temp );
return temp;
}
void _restore( const PenguinV_Image::Image & in, PenguinV_Image::Image & out )
{
_registrator.convert( in.type(), out.type() )( in, out );
}
};
template <typename _T>
void verifyFunction(_T func, const char * functionName)
{
if ( func == nullptr ) {
const std::string error( std::string("Function ") + std::string(functionName) + std::string(" is not defined") );
throw imageException(error.data());
}
}
#define initialize( image, func_ ) \
ImageTypeManager & registrator = ImageTypeManager::instance(); \
auto func = registrator.functionTable( image.type() ).func_; \
uint8_t imageType = image.type(); \
if ( func == nullptr && registrator.isIntertypeConversionEnabled() ) { \
const std::vector< uint8_t > & types = registrator.imageTypes(); \
for ( std::vector< uint8_t >::const_iterator type = types.cbegin(); type != types.cend(); ++type ) { \
auto funcTemp = registrator.functionTable( *type ).func_; \
if ( funcTemp != nullptr ) { \
func = funcTemp; \
imageType = *type; \
break; \
} \
} \
} \
verifyFunction( func, #func_ ); \
ImageManager manager( imageType );
}
namespace penguinV
{
void AbsoluteDifference( const Image & in1, uint32_t startX1, uint32_t startY1, const Image & in2, uint32_t startX2, uint32_t startY2,
Image & out, uint32_t startXOut, uint32_t startYOut, uint32_t width, uint32_t height )
{
initialize( in1, AbsoluteDifference )
func( manager(in1), startX1, startY1, manager(in2), startX2, startY2, manager(out), startXOut, startYOut, width, height );
}
void Accumulate( const Image & image, uint32_t x, uint32_t y, uint32_t width, uint32_t height, std::vector < uint32_t > & result )
{
initialize( image, Accumulate )
func( image, x, y, width, height, result );
}
void BitwiseAnd( const Image & in1, uint32_t startX1, uint32_t startY1, const Image & in2, uint32_t startX2, uint32_t startY2,
Image & out, uint32_t startXOut, uint32_t startYOut, uint32_t width, uint32_t height )
{
initialize( in1, BitwiseAnd )
func( in1, startX1, startY1, in2, startX2, startY2, out, startXOut, startYOut, width, height );
}
void BitwiseOr( const Image & in1, uint32_t startX1, uint32_t startY1, const Image & in2, uint32_t startX2, uint32_t startY2,
Image & out, uint32_t startXOut, uint32_t startYOut, uint32_t width, uint32_t height )
{
initialize( in1, BitwiseOr )
func( in1, startX1, startY1, in2, startX2, startY2, out, startXOut, startYOut, width, height );
}
void BitwiseXor( const Image & in1, uint32_t startX1, uint32_t startY1, const Image & in2, uint32_t startX2, uint32_t startY2,
Image & out, uint32_t startXOut, uint32_t startYOut, uint32_t width, uint32_t height )
{
initialize( in1, BitwiseXor )
func( in1, startX1, startY1, in2, startX2, startY2, out, startXOut, startYOut, width, height );
}
void ConvertToGrayScale( const Image & in, uint32_t startXIn, uint32_t startYIn, Image & out, uint32_t startXOut, uint32_t startYOut,
uint32_t width, uint32_t height )
{
initialize( in, ConvertToGrayScale )
func( manager(in), startXIn, startYIn, manager(out), startXOut, startYOut, width, height );
}
void ConvertToRgb( const Image & in, uint32_t startXIn, uint32_t startYIn, Image & out, uint32_t startXOut, uint32_t startYOut,
uint32_t width, uint32_t height )
{
initialize( in, ConvertToRgb )
func( in, startXIn, startYIn, out, startXOut, startYOut, width, height );
}
void Copy( const Image & in, uint32_t startXIn, uint32_t startYIn, Image & out, uint32_t startXOut, uint32_t startYOut,
uint32_t width, uint32_t height )
{
initialize( in, Copy )
func( in, startXIn, startYIn, out, startXOut, startYOut, width, height );
}
void ExtractChannel( const Image & in, uint32_t startXIn, uint32_t startYIn, Image & out, uint32_t startXOut,
uint32_t startYOut, uint32_t width, uint32_t height, uint8_t channelId )
{
initialize( in, ExtractChannel )
func( in, startXIn, startYIn, out, startXOut, startYOut, width, height, channelId );
}
void Fill( Image & image, uint32_t x, uint32_t y, uint32_t width, uint32_t height, uint8_t value )
{
initialize( image, Fill )
func( image, x, y, width, height, value );
}
void Flip( const Image & in, uint32_t startXIn, uint32_t startYIn, Image & out, uint32_t startXOut, uint32_t startYOut,
uint32_t width, uint32_t height, bool horizontal, bool vertical )
{
initialize( in, Flip )
func( in, startXIn, startYIn, out, startXOut, startYOut, width, height, horizontal, vertical );
}
void GammaCorrection( const Image & in, uint32_t startXIn, uint32_t startYIn, Image & out, uint32_t startXOut, uint32_t startYOut,
uint32_t width, uint32_t height, double a, double gamma )
{
initialize( in, GammaCorrection )
func( in, startXIn, startYIn, out, startXOut, startYOut, width, height, a, gamma );
}
uint8_t GetPixel( const Image & image, uint32_t x, uint32_t y )
{
initialize( image, GetPixel );
return func( image, x, y );
}
uint8_t GetThreshold( const std::vector < uint32_t > & histogram )
{
return Image_Function_Helper::GetThreshold( histogram );
}
void Histogram( const Image & image, uint32_t x, uint32_t y, uint32_t width, uint32_t height,
std::vector < uint32_t > & histogram )
{
initialize( image, Histogram )
func( manager(image), x, y, width, height, histogram );
}
void Invert( const Image & in, uint32_t startXIn, uint32_t startYIn, Image & out, uint32_t startXOut, uint32_t startYOut,
uint32_t width, uint32_t height )
{
initialize( in, Invert )
func( in, startXIn, startYIn, out, startXOut, startYOut, width, height );
}
bool IsEqual( const Image & in1, uint32_t startX1, uint32_t startY1, const Image & in2, uint32_t startX2, uint32_t startY2,
uint32_t width, uint32_t height )
{
initialize( in1, IsEqual );
return func( in1, startX1, startY1, in2, startX2, startY2, width, height );
}
void LookupTable ( const Image & in, uint32_t startXIn, uint32_t startYIn, Image & out, uint32_t startXOut, uint32_t startYOut,
uint32_t width, uint32_t height, const std::vector < uint8_t > & table )
{
initialize( in, LookupTable )
func( in, startXIn, startYIn, out, startXOut, startYOut, width, height, table );
}
void Maximum( const Image & in1, uint32_t startX1, uint32_t startY1, const Image & in2, uint32_t startX2, uint32_t startY2,
Image & out, uint32_t startXOut, uint32_t startYOut, uint32_t width, uint32_t height )
{
initialize( in1, Maximum )
func( in1, startX1, startY1, in2, startX2, startY2, out, startXOut, startYOut, width, height );
}
void Merge( const Image & in1, uint32_t startXIn1, uint32_t startYIn1, const Image & in2, uint32_t startXIn2, uint32_t startYIn2,
const Image & in3, uint32_t startXIn3, uint32_t startYIn3, Image & out, uint32_t startXOut, uint32_t startYOut,
uint32_t width, uint32_t height )
{
initialize( in1, Merge )
func( in1, startXIn1, startYIn1, in2, startXIn2, startYIn2, in3, startXIn3, startYIn3,
out, startXOut, startYOut, width, height );
}
void Minimum( const Image & in1, uint32_t startX1, uint32_t startY1, const Image & in2, uint32_t startX2, uint32_t startY2,
Image & out, uint32_t startXOut, uint32_t startYOut, uint32_t width, uint32_t height )
{
initialize( in1, Minimum )
func( in1, startX1, startY1, in2, startX2, startY2, out, startXOut, startYOut, width, height );
}
void Normalize( const Image & in, uint32_t startXIn, uint32_t startYIn, Image & out, uint32_t startXOut, uint32_t startYOut,
uint32_t width, uint32_t height )
{
initialize( in, Normalize )
func( in, startXIn, startYIn, out, startXOut, startYOut, width, height );
}
void ProjectionProfile( const Image & image, uint32_t x, uint32_t y, uint32_t width, uint32_t height, bool horizontal,
std::vector < uint32_t > & projection )
{
initialize( image, ProjectionProfile )
func( image, x, y, width, height, horizontal, projection );
}
void Resize( const Image & in, uint32_t startXIn, uint32_t startYIn, uint32_t widthIn, uint32_t heightIn,
Image & out, uint32_t startXOut, uint32_t startYOut, uint32_t widthOut, uint32_t heightOut )
{
initialize( in, Resize )
func( in, startXIn, startYIn, widthIn, heightIn, out, startXOut, startYOut, widthOut, heightOut );
}
void RgbToBgr( const Image & in, uint32_t startXIn, uint32_t startYIn, Image & out, uint32_t startXOut, uint32_t startYOut,
uint32_t width, uint32_t height )
{
initialize( in, RgbToBgr )
func( in, startXIn, startYIn, out, startXOut, startYOut, width, height );
}
void SetPixel( Image & image, uint32_t x, uint32_t y, uint8_t value )
{
initialize( image, SetPixel )
func( image, x, y, value );
}
void SetPixel( Image & image, const std::vector < uint32_t > & X, const std::vector < uint32_t > & Y, uint8_t value )
{
initialize( image, SetPixel2 )
func( image, X, Y, value );
}
void Split( const Image & in, uint32_t startXIn, uint32_t startYIn, Image & out1, uint32_t startXOut1, uint32_t startYOut1,
Image & out2, uint32_t startXOut2, uint32_t startYOut2, Image & out3, uint32_t startXOut3, uint32_t startYOut3,
uint32_t width, uint32_t height )
{
initialize( in, Split )
func( in, startXIn, startYIn, out1, startXOut1, startYOut1, out2, startXOut2, startYOut2,
out3, startXOut3, startYOut3, width, height );
}
void Subtract( const Image & in1, uint32_t startX1, uint32_t startY1, const Image & in2, uint32_t startX2, uint32_t startY2,
Image & out, uint32_t startXOut, uint32_t startYOut, uint32_t width, uint32_t height )
{
initialize( in1, Subtract )
func( in1, startX1, startY1, in2, startX2, startY2, out, startXOut, startYOut, width, height );
}
uint32_t Sum( const Image & image, uint32_t x, uint32_t y, uint32_t width, uint32_t height )
{
initialize( image, Sum );
return func( image, x, y, width, height );
}
void Threshold( const Image & in, uint32_t startXIn, uint32_t startYIn, Image & out, uint32_t startXOut, uint32_t startYOut,
uint32_t width, uint32_t height, uint8_t threshold )
{
initialize( in, Threshold )
func( manager(in), startXIn, startYIn, manager(out), startXOut, startYOut, width, height, threshold );
}
void Threshold( const Image & in, uint32_t startXIn, uint32_t startYIn, Image & out, uint32_t startXOut, uint32_t startYOut,
uint32_t width, uint32_t height, uint8_t minThreshold, uint8_t maxThreshold )
{
initialize( in, Threshold2 )
func( in, startXIn, startYIn, out, startXOut, startYOut, width, height, minThreshold, maxThreshold );
}
void Transpose( const Image & in, uint32_t startXIn, uint32_t startYIn, Image & out, uint32_t startXOut, uint32_t startYOut,
uint32_t width, uint32_t height )
{
initialize( in, Transpose )
func( in, startXIn, startYIn, out, startXOut, startYOut, width, height );
}
}
| 45.092754 | 138 | 0.577296 | [
"vector"
] |
d5cd3b8d3f29f45cb1101149f75b073489b38906 | 15,316 | cpp | C++ | src/trunk/libs/seiscomp3/datamodel/config.cpp | damb/seiscomp3 | 560a8f7ae43737ae7826fb1ffca76a9f601cf9dc | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 94 | 2015-02-04T13:57:34.000Z | 2021-11-01T15:10:06.000Z | src/trunk/libs/seiscomp3/datamodel/config.cpp | damb/seiscomp3 | 560a8f7ae43737ae7826fb1ffca76a9f601cf9dc | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 233 | 2015-01-28T15:16:46.000Z | 2021-08-23T11:31:37.000Z | src/trunk/libs/seiscomp3/datamodel/config.cpp | damb/seiscomp3 | 560a8f7ae43737ae7826fb1ffca76a9f601cf9dc | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 95 | 2015-02-13T15:53:30.000Z | 2021-11-02T14:54:54.000Z | /***************************************************************************
* Copyright (C) by GFZ Potsdam *
* *
* You can redistribute and/or modify this program under the *
* terms of the SeisComP Public 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 *
* SeisComP Public License for more details. *
***************************************************************************/
#define SEISCOMP_COMPONENT DataModel
#include <seiscomp3/datamodel/config.h>
#include <seiscomp3/datamodel/parameterset.h>
#include <seiscomp3/datamodel/configmodule.h>
#include <algorithm>
#include <seiscomp3/datamodel/metadata.h>
#include <seiscomp3/logging/log.h>
namespace Seiscomp {
namespace DataModel {
IMPLEMENT_SC_CLASS_DERIVED(Config, PublicObject, "Config");
Config::MetaObject::MetaObject(const Core::RTTI* rtti) : Seiscomp::Core::MetaObject(rtti) {
addProperty(arrayObjectProperty("parameterSet", "ParameterSet", &Config::parameterSetCount, &Config::parameterSet, static_cast<bool (Config::*)(ParameterSet*)>(&Config::add), &Config::removeParameterSet, static_cast<bool (Config::*)(ParameterSet*)>(&Config::remove)));
addProperty(arrayObjectProperty("module", "ConfigModule", &Config::configModuleCount, &Config::configModule, static_cast<bool (Config::*)(ConfigModule*)>(&Config::add), &Config::removeConfigModule, static_cast<bool (Config::*)(ConfigModule*)>(&Config::remove)));
}
IMPLEMENT_METAOBJECT(Config)
Config::Config(): PublicObject("Config") {
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Config::Config(const Config& other)
: PublicObject() {
*this = other;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Config::~Config() {
std::for_each(_parameterSets.begin(), _parameterSets.end(),
std::compose1(std::bind2nd(std::mem_fun(&ParameterSet::setParent),
(PublicObject*)NULL),
std::mem_fun_ref(&ParameterSetPtr::get)));
std::for_each(_configModules.begin(), _configModules.end(),
std::compose1(std::bind2nd(std::mem_fun(&ConfigModule::setParent),
(PublicObject*)NULL),
std::mem_fun_ref(&ConfigModulePtr::get)));
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
bool Config::operator==(const Config& rhs) const {
return true;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
bool Config::operator!=(const Config& rhs) const {
return !operator==(rhs);
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
bool Config::equal(const Config& other) const {
return *this == other;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Config& Config::operator=(const Config& other) {
PublicObject::operator=(other);
return *this;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
bool Config::assign(Object* other) {
Config* otherConfig = Config::Cast(other);
if ( other == NULL )
return false;
*this = *otherConfig;
return true;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
bool Config::attachTo(PublicObject* parent) {
return false;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
bool Config::detachFrom(PublicObject* object) {
return false;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
bool Config::detach() {
return false;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Object* Config::clone() const {
Config* clonee = new Config();
*clonee = *this;
return clonee;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
bool Config::updateChild(Object* child) {
ParameterSet* parameterSetChild = ParameterSet::Cast(child);
if ( parameterSetChild != NULL ) {
ParameterSet* parameterSetElement
= ParameterSet::Cast(PublicObject::Find(parameterSetChild->publicID()));
if ( parameterSetElement && parameterSetElement->parent() == this ) {
*parameterSetElement = *parameterSetChild;
parameterSetElement->update();
return true;
}
return false;
}
ConfigModule* configModuleChild = ConfigModule::Cast(child);
if ( configModuleChild != NULL ) {
ConfigModule* configModuleElement
= ConfigModule::Cast(PublicObject::Find(configModuleChild->publicID()));
if ( configModuleElement && configModuleElement->parent() == this ) {
*configModuleElement = *configModuleChild;
configModuleElement->update();
return true;
}
return false;
}
return false;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
void Config::accept(Visitor* visitor) {
for ( std::vector<ParameterSetPtr>::iterator it = _parameterSets.begin(); it != _parameterSets.end(); ++it )
(*it)->accept(visitor);
for ( std::vector<ConfigModulePtr>::iterator it = _configModules.begin(); it != _configModules.end(); ++it )
(*it)->accept(visitor);
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
size_t Config::parameterSetCount() const {
return _parameterSets.size();
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
ParameterSet* Config::parameterSet(size_t i) const {
return _parameterSets[i].get();
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
ParameterSet* Config::findParameterSet(const std::string& publicID) const {
for ( std::vector<ParameterSetPtr>::const_iterator it = _parameterSets.begin(); it != _parameterSets.end(); ++it )
if ( (*it)->publicID() == publicID )
return (*it).get();
return NULL;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
bool Config::add(ParameterSet* parameterSet) {
if ( parameterSet == NULL )
return false;
// Element has already a parent
if ( parameterSet->parent() != NULL ) {
SEISCOMP_ERROR("Config::add(ParameterSet*) -> element has already a parent");
return false;
}
if ( PublicObject::IsRegistrationEnabled() ) {
ParameterSet* parameterSetCached = ParameterSet::Find(parameterSet->publicID());
if ( parameterSetCached ) {
if ( parameterSetCached->parent() ) {
if ( parameterSetCached->parent() == this )
SEISCOMP_ERROR("Config::add(ParameterSet*) -> element with same publicID has been added already");
else
SEISCOMP_ERROR("Config::add(ParameterSet*) -> element with same publicID has been added already to another object");
return false;
}
else
parameterSet = parameterSetCached;
}
}
// Add the element
_parameterSets.push_back(parameterSet);
parameterSet->setParent(this);
// Create the notifiers
if ( Notifier::IsEnabled() ) {
NotifierCreator nc(OP_ADD);
parameterSet->accept(&nc);
}
// Notify registered observers
childAdded(parameterSet);
return true;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
bool Config::remove(ParameterSet* parameterSet) {
if ( parameterSet == NULL )
return false;
if ( parameterSet->parent() != this ) {
SEISCOMP_ERROR("Config::remove(ParameterSet*) -> element has another parent");
return false;
}
std::vector<ParameterSetPtr>::iterator it;
it = std::find(_parameterSets.begin(), _parameterSets.end(), parameterSet);
// Element has not been found
if ( it == _parameterSets.end() ) {
SEISCOMP_ERROR("Config::remove(ParameterSet*) -> child object has not been found although the parent pointer matches???");
return false;
}
// Create the notifiers
if ( Notifier::IsEnabled() ) {
NotifierCreator nc(OP_REMOVE);
(*it)->accept(&nc);
}
(*it)->setParent(NULL);
childRemoved((*it).get());
_parameterSets.erase(it);
return true;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
bool Config::removeParameterSet(size_t i) {
// index out of bounds
if ( i >= _parameterSets.size() )
return false;
// Create the notifiers
if ( Notifier::IsEnabled() ) {
NotifierCreator nc(OP_REMOVE);
_parameterSets[i]->accept(&nc);
}
_parameterSets[i]->setParent(NULL);
childRemoved(_parameterSets[i].get());
_parameterSets.erase(_parameterSets.begin() + i);
return true;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
size_t Config::configModuleCount() const {
return _configModules.size();
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
ConfigModule* Config::configModule(size_t i) const {
return _configModules[i].get();
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
ConfigModule* Config::findConfigModule(const std::string& publicID) const {
for ( std::vector<ConfigModulePtr>::const_iterator it = _configModules.begin(); it != _configModules.end(); ++it )
if ( (*it)->publicID() == publicID )
return (*it).get();
return NULL;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
bool Config::add(ConfigModule* configModule) {
if ( configModule == NULL )
return false;
// Element has already a parent
if ( configModule->parent() != NULL ) {
SEISCOMP_ERROR("Config::add(ConfigModule*) -> element has already a parent");
return false;
}
if ( PublicObject::IsRegistrationEnabled() ) {
ConfigModule* configModuleCached = ConfigModule::Find(configModule->publicID());
if ( configModuleCached ) {
if ( configModuleCached->parent() ) {
if ( configModuleCached->parent() == this )
SEISCOMP_ERROR("Config::add(ConfigModule*) -> element with same publicID has been added already");
else
SEISCOMP_ERROR("Config::add(ConfigModule*) -> element with same publicID has been added already to another object");
return false;
}
else
configModule = configModuleCached;
}
}
// Add the element
_configModules.push_back(configModule);
configModule->setParent(this);
// Create the notifiers
if ( Notifier::IsEnabled() ) {
NotifierCreator nc(OP_ADD);
configModule->accept(&nc);
}
// Notify registered observers
childAdded(configModule);
return true;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
bool Config::remove(ConfigModule* configModule) {
if ( configModule == NULL )
return false;
if ( configModule->parent() != this ) {
SEISCOMP_ERROR("Config::remove(ConfigModule*) -> element has another parent");
return false;
}
std::vector<ConfigModulePtr>::iterator it;
it = std::find(_configModules.begin(), _configModules.end(), configModule);
// Element has not been found
if ( it == _configModules.end() ) {
SEISCOMP_ERROR("Config::remove(ConfigModule*) -> child object has not been found although the parent pointer matches???");
return false;
}
// Create the notifiers
if ( Notifier::IsEnabled() ) {
NotifierCreator nc(OP_REMOVE);
(*it)->accept(&nc);
}
(*it)->setParent(NULL);
childRemoved((*it).get());
_configModules.erase(it);
return true;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
bool Config::removeConfigModule(size_t i) {
// index out of bounds
if ( i >= _configModules.size() )
return false;
// Create the notifiers
if ( Notifier::IsEnabled() ) {
NotifierCreator nc(OP_REMOVE);
_configModules[i]->accept(&nc);
}
_configModules[i]->setParent(NULL);
childRemoved(_configModules[i].get());
_configModules.erase(_configModules.begin() + i);
return true;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
void Config::serialize(Archive& ar) {
// Do not read/write if the archive's version is higher than
// currently supported
if ( ar.isHigherVersion<0,11>() ) {
SEISCOMP_ERROR("Archive version %d.%d too high: Config skipped",
ar.versionMajor(), ar.versionMinor());
ar.setValidity(false);
return;
}
if ( ar.hint() & Archive::IGNORE_CHILDS ) return;
ar & NAMED_OBJECT_HINT("parameterSet",
Seiscomp::Core::Generic::containerMember(_parameterSets,
Seiscomp::Core::Generic::bindMemberFunction<ParameterSet>(static_cast<bool (Config::*)(ParameterSet*)>(&Config::add), this)),
Archive::STATIC_TYPE);
ar & NAMED_OBJECT_HINT("module",
Seiscomp::Core::Generic::containerMember(_configModules,
Seiscomp::Core::Generic::bindMemberFunction<ConfigModule>(static_cast<bool (Config::*)(ConfigModule*)>(&Config::add), this)),
Archive::STATIC_TYPE);
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
}
}
| 30.031373 | 269 | 0.47643 | [
"object",
"vector"
] |
d5d3f6d09929133e2657ba9833601ac2869f9bc1 | 2,381 | hpp | C++ | doc/quickbook/oglplus/quickref/string/ref.hpp | matus-chochlik/oglplus | 76dd964e590967ff13ddff8945e9dcf355e0c952 | [
"BSL-1.0"
] | 364 | 2015-01-01T09:38:23.000Z | 2022-03-22T05:32:00.000Z | doc/quickbook/oglplus/quickref/string/ref.hpp | matus-chochlik/oglplus | 76dd964e590967ff13ddff8945e9dcf355e0c952 | [
"BSL-1.0"
] | 55 | 2015-01-06T16:42:55.000Z | 2020-07-09T04:21:41.000Z | doc/quickbook/oglplus/quickref/string/ref.hpp | matus-chochlik/oglplus | 76dd964e590967ff13ddff8945e9dcf355e0c952 | [
"BSL-1.0"
] | 57 | 2015-01-07T18:35:49.000Z | 2022-03-22T05:32:04.000Z | /*
* Copyright 2014-2019 Matus Chochlik. 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)
*/
//[oglplus_string_ref
class StrCRef {
public:
StrCRef() noexcept; /*<
Constructs a reference to an empty string.
>*/
StrCRef(const GLchar* cstr) noexcept; /*<
Constructs a reference to a C-string.
>*/
StrCRef(const GLchar* cstr, size_t size) noexcept; /*<
Constructs a reference to a C-string with a specific size.
>*/
template <size_t N>
StrCRef(const GLchar (&cary)[N]) noexcept; /*<
Constructs a reference to a character array with a known size.
>*/
StrCRef(const __String& sstr) noexcept; /*<
Constructs a reference to a string stored inside of a __String.
>*/
StrCRef(const std::vector<GLchar>& cvec) noexcept; /*<
Constructs a reference to a string stored inside of a [^std::vector].
>*/
template <size_t N>
StrCRef(const std::array<GLchar, N>& cvec) noexcept; /*<
Constructs a reference to a string stored inside of a [^std::array].
>*/
size_t size() const noexcept; /*<
Returns the lenght of the string, not counting any terminating
characters.
>*/
bool empty() const noexcept; /*<
Returns true if the referenced string is empty.
>*/
using iterator = const GLchar*; /*<
Iterator types.
>*/
using const_iterator = iterator;
const_iterator begin() const noexcept;
const_iterator end() const noexcept;
bool is_nts() const noexcept; /*<
Returns true if the string is null-terminated
>*/
const GLchar* c_str() const noexcept; /*<
Returns a const pointer to the referenced character string.
This function may be called only if the string stored inside
is null-terminated.
>*/
__String str() const; /*<
Returns the referenced character string as a __String.
>*/
friend bool operator==(const StrCRef& a, const StrCRef& b); /*<
Comparison operators.
>*/
friend bool operator==(const StrCRef& a, const Char* b);
friend bool operator==(const Char* a, const StrCRef& b);
friend bool operator!=(const StrCRef& a, const StrCRef& b);
friend bool operator!=(const StrCRef& a, const Char* b);
friend bool operator!=(const Char* a, const StrCRef& b);
};
//]
| 29.395062 | 73 | 0.659807 | [
"vector"
] |
d5dfd7884cdd4bd1ab78c5ea36bb517d0b494e6c | 31,859 | cpp | C++ | renderer/renderingcontext.cpp | ip-gpu/MathForGameDevelopers | e5a9d5e4a6777b278b704f9c363d599f84186fd4 | [
"BSD-4-Clause"
] | 520 | 2015-01-02T00:27:58.000Z | 2022-03-29T10:53:01.000Z | renderer/renderingcontext.cpp | ip-gpu/MathForGameDevelopers | e5a9d5e4a6777b278b704f9c363d599f84186fd4 | [
"BSD-4-Clause"
] | 8 | 2015-01-04T21:58:42.000Z | 2021-04-02T22:51:45.000Z | renderer/renderingcontext.cpp | ip-gpu/MathForGameDevelopers | e5a9d5e4a6777b278b704f9c363d599f84186fd4 | [
"BSD-4-Clause"
] | 111 | 2015-01-18T22:12:30.000Z | 2022-03-24T09:04:17.000Z | /*
Copyright (c) 2012, Lunar Workshop, Inc.
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. All advertising materials mentioning features or use of this software must display the following acknowledgement:
This product includes software developed by Lunar Workshop, Inc.
4. Neither the name of the Lunar Workshop 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 LUNAR WORKSHOP INC ''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 LUNAR WORKSHOP 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 "renderingcontext.h"
#include <string.h>
#include <GL3/gl3w.h>
#if defined(__APPLE__)
#include <OpenGL/glu.h>
#else
#include <GL/glu.h>
#endif
#include <common.h>
#include <renderer/shaders.h>
#include <renderer/application.h>
#include <renderer/renderer.h>
#define BUFFER_OFFSET(i) ((char *)NULL + (i))
using namespace std;
vector<float> CRenderingContext::s_dynamic_verts;
vector<CRenderingContext::CRenderContext> CRenderingContext::s_aContexts;
CRenderingContext::CRenderingContext(CRenderer* pRenderer, bool bInherit)
{
m_pRenderer = pRenderer;
m_clrRender = ::Color(255, 255, 255, 255);
s_aContexts.push_back(CRenderContext());
if (bInherit && s_aContexts.size() > 1)
{
CRenderContext& oLastContext = s_aContexts[s_aContexts.size()-2];
CRenderContext& oThisContext = GetContext();
oThisContext.m_mProjection = oLastContext.m_mProjection;
oThisContext.m_mView = oLastContext.m_mView;
oThisContext.m_mTransformations = oLastContext.m_mTransformations;
strncpy(oThisContext.m_szProgram, oLastContext.m_szProgram, PROGRAM_LEN);
oThisContext.m_pShader = oLastContext.m_pShader;
oThisContext.m_iViewportX = oLastContext.m_iViewportX;
oThisContext.m_iViewportY = oLastContext.m_iViewportY;
oThisContext.m_iViewportWidth = oLastContext.m_iViewportWidth;
oThisContext.m_iViewportHeight = oLastContext.m_iViewportHeight;
oThisContext.m_eBlend = oLastContext.m_eBlend;
oThisContext.m_flAlpha = oLastContext.m_flAlpha;
oThisContext.m_bDepthMask = oLastContext.m_bDepthMask;
oThisContext.m_bDepthTest = oLastContext.m_bDepthTest;
oThisContext.m_eDepthFunction = oLastContext.m_eDepthFunction;
oThisContext.m_bCull = oLastContext.m_bCull;
oThisContext.m_bWinding = oLastContext.m_bWinding;
m_pShader = oThisContext.m_pShader;
if (m_pShader)
m_iProgram = m_pShader->m_iProgram;
else
m_iProgram = 0;
}
else
{
m_pShader = NULL;
BindTexture(0);
UseProgram("");
SetViewport(0, 0, Application()->GetWindowWidth(), Application()->GetWindowHeight());
SetBlend(BLEND_NONE);
SetAlpha(1);
SetDepthMask(true);
SetDepthTest(true);
SetDepthFunction(DF_LESS);
SetBackCulling(true);
SetWinding(true);
}
}
CRenderingContext::~CRenderingContext()
{
s_aContexts.pop_back();
if (s_aContexts.size())
{
CRenderContext& oContext = GetContext();
UseProgram(oContext.m_pShader);
if (*oContext.m_szProgram)
{
oContext.m_bProjectionUpdated = false;
oContext.m_bViewUpdated = false;
oContext.m_bTransformUpdated = false;
}
SetViewport(oContext.m_iViewportX, oContext.m_iViewportY, oContext.m_iViewportWidth, oContext.m_iViewportHeight);
SetBlend(oContext.m_eBlend);
SetAlpha(oContext.m_flAlpha);
SetDepthMask(oContext.m_bDepthMask);
SetDepthTest(oContext.m_bDepthTest);
SetDepthFunction(oContext.m_eDepthFunction);
SetBackCulling(oContext.m_bCull);
SetWinding(oContext.m_bWinding);
}
else
{
GLCall(glActiveTexture(GL_TEXTURE0));
GLCall(glBindTexture(GL_TEXTURE_2D, 0));
GLCall(glBindFramebuffer(GL_FRAMEBUFFER, 0));
if (m_pRenderer)
GLCall(glViewport(0, 0, (GLsizei)m_pRenderer->m_iWidth, (GLsizei)m_pRenderer->m_iHeight));
else
GLCall(glViewport(0, 0, (GLsizei)Application()->GetWindowWidth(), (GLsizei)Application()->GetWindowHeight()));
GLCall(glUseProgram(0));
GLCall(glDisablei(GL_BLEND, 0));
GLCall(glDepthMask(true));
GLCall(glEnable(GL_DEPTH_TEST));
GLCall(glEnable(GL_CULL_FACE));
GLCall(glDepthFunc(GL_LESS));
GLCall(glFrontFace(GL_CCW));
}
}
void CRenderingContext::SetProjection(const Matrix4x4& m)
{
CRenderContext& oContext = GetContext();
oContext.m_mProjection = m;
GetContext().m_bProjectionUpdated = false;
}
void CRenderingContext::SetView(const Matrix4x4& m)
{
CRenderContext& oContext = GetContext();
oContext.m_mView = m;
oContext.m_bViewUpdated = false;
}
void CRenderingContext::SetPosition(const Vector& vecPosition)
{
CRenderContext& oContext = GetContext();
oContext.m_mTransformations.SetTranslation(vecPosition);
oContext.m_bTransformUpdated = false;
}
void CRenderingContext::Transform(const Matrix4x4& m)
{
CRenderContext& oContext = GetContext();
oContext.m_mTransformations *= m;
oContext.m_bTransformUpdated = false;
}
void CRenderingContext::Translate(const Vector& vecTranslate)
{
CRenderContext& oContext = GetContext();
oContext.m_mTransformations.AddTranslation(vecTranslate);
oContext.m_bTransformUpdated = false;
}
void CRenderingContext::Rotate(float flAngle, Vector vecAxis)
{
Matrix4x4 mRotation;
mRotation.SetRotation(flAngle, vecAxis);
CRenderContext& oContext = GetContext();
oContext.m_mTransformations *= mRotation;
oContext.m_bTransformUpdated = false;
}
void CRenderingContext::Scale(float flX, float flY, float flZ)
{
CRenderContext& oContext = GetContext();
oContext.m_mTransformations.AddScale(Vector(flX, flY, flZ));
oContext.m_bTransformUpdated = false;
}
void CRenderingContext::ResetTransformations()
{
CRenderContext& oContext = GetContext();
oContext.m_mTransformations.Identity();
oContext.m_bTransformUpdated = false;
}
void CRenderingContext::LoadTransform(const Matrix4x4& m)
{
CRenderContext& oContext = GetContext();
oContext.m_mTransformations = m;
oContext.m_bTransformUpdated = false;
}
void CRenderingContext::SetViewport(int x, int y, int w, int h)
{
CRenderContext& oContext = GetContext();
oContext.m_iViewportX = x;
oContext.m_iViewportY = y;
oContext.m_iViewportWidth = w;
oContext.m_iViewportHeight = h;
}
void CRenderingContext::SetBlend(blendtype_t eBlend)
{
if (eBlend)
{
GLCall(glEnablei(GL_BLEND, 0));
if (eBlend == BLEND_ALPHA)
GLCall(glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA));
else if (eBlend == BLEND_ADDITIVE)
GLCall(glBlendFunc(GL_SRC_ALPHA, GL_ONE));
else if (eBlend == BLEND_BOTH)
GLCall(glBlendFunc(GL_ONE, GL_ONE));
}
else
GLCall(glDisablei(GL_BLEND, 0));
GetContext().m_eBlend = eBlend;
}
void CRenderingContext::SetDepthMask(bool bDepthMask)
{
GLCall(glDepthMask(bDepthMask));
GetContext().m_bDepthMask = bDepthMask;
}
void CRenderingContext::SetDepthTest(bool bDepthTest)
{
if (bDepthTest)
GLCall(glEnable(GL_DEPTH_TEST));
else
GLCall(glDisable(GL_DEPTH_TEST));
GetContext().m_bDepthTest = bDepthTest;
}
void CRenderingContext::SetDepthFunction(depth_function_t eDepthFunction)
{
if (eDepthFunction == DF_LEQUAL)
GLCall(glDepthFunc(GL_LEQUAL));
else if (eDepthFunction == DF_LESS)
GLCall(glDepthFunc(GL_LESS));
GetContext().m_eDepthFunction = eDepthFunction;
}
void CRenderingContext::SetBackCulling(bool bCull)
{
if (bCull)
GLCall(glEnable(GL_CULL_FACE));
else
GLCall(glDisable(GL_CULL_FACE));
GetContext().m_bCull = bCull;
}
void CRenderingContext::SetWinding(bool bWinding)
{
GetContext().m_bWinding = bWinding;
GLCall(glFrontFace(bWinding?GL_CCW:GL_CW));
}
void CRenderingContext::ClearColor(const ::Color& clrClear)
{
GLCall(glClearColor((float)(clrClear.r())/255, (float)(clrClear.g())/255, (float)(clrClear.b())/255, (float)(clrClear.a())/255));
GLCall(glClear(GL_COLOR_BUFFER_BIT));
}
void CRenderingContext::ClearDepth()
{
GLCall(glClear(GL_DEPTH_BUFFER_BIT));
}
void CRenderingContext::RenderWireBox(const Vector& vecMins, const Vector& vecMaxs)
{
BeginRenderLineLoop();
Vertex(vecMaxs);
Vertex(Vector(vecMins.x, vecMaxs.y, vecMaxs.z));
Vertex(Vector(vecMins.x, vecMaxs.y, vecMins.z));
Vertex(Vector(vecMaxs.x, vecMaxs.y, vecMins.z));
Vertex(vecMaxs);
Vertex(Vector(vecMaxs.x, vecMins.y, vecMaxs.z));
Vertex(Vector(vecMins.x, vecMins.y, vecMaxs.z));
Vertex(Vector(vecMins.x, vecMins.y, vecMins.z));
Vertex(Vector(vecMaxs.x, vecMins.y, vecMins.z));
Vertex(Vector(vecMaxs.x, vecMins.y, vecMaxs.z));
EndRender();
BeginRenderLines();
Vertex(Vector(vecMins.x, vecMaxs.y, vecMaxs.z));
Vertex(Vector(vecMins.x, vecMins.y, vecMaxs.z));
EndRender();
BeginRenderLines();
Vertex(Vector(vecMins.x, vecMaxs.y, vecMins.z));
Vertex(Vector(vecMins.x, vecMins.y, vecMins.z));
EndRender();
BeginRenderLines();
Vertex(Vector(vecMaxs.x, vecMaxs.y, vecMins.z));
Vertex(Vector(vecMaxs.x, vecMins.y, vecMins.z));
EndRender();
}
void CRenderingContext::RenderBox(const Vector& vecMins, const Vector& vecMaxs)
{
Vector vecForward(vecMaxs.x - vecMins.x, 0, 0);
Vector vecUp(0, vecMaxs.y - vecMins.y, 0);
Vector vecRight(0, 0, vecMaxs.z - vecMins.z);
// The back face
BeginRenderTris();
Normal(Vector(-1, 0, 0));
TexCoord(0.0f, 0.0f);
Vertex(vecMins);
TexCoord(1.0f, 0.0f);
Vertex(vecMins + vecRight);
TexCoord(1.0f, 1.0f);
Vertex(vecMins + vecRight + vecUp);
TexCoord(0.0f, 0.0f);
Vertex(vecMins);
TexCoord(1.0f, 1.0f);
Vertex(vecMins + vecRight + vecUp);
TexCoord(0.0f, 1.0f);
Vertex(vecMins + vecUp);
// The left face
Normal(Vector(0, 0, -1));
TexCoord(0.0f, 0.0f);
Vertex(vecMins);
TexCoord(0.0f, 1.0f);
Vertex(vecMins + vecUp);
TexCoord(1.0f, 1.0f);
Vertex(vecMins + vecUp + vecForward);
TexCoord(0.0f, 0.0f);
Vertex(vecMins);
TexCoord(1.0f, 1.0f);
Vertex(vecMins + vecUp + vecForward);
TexCoord(1.0f, 0.0f);
Vertex(vecMins + vecForward);
// The bottom face
Normal(Vector(0, -1, 0));
TexCoord(0.0f, 0.0f);
Vertex(vecMins);
TexCoord(1.0f, 0.0f);
Vertex(vecMins + vecForward);
TexCoord(1.0f, 1.0f);
Vertex(vecMins + vecForward + vecRight);
TexCoord(0.0f, 0.0f);
Vertex(vecMins);
TexCoord(1.0f, 1.0f);
Vertex(vecMins + vecForward + vecRight);
TexCoord(0.0f, 1.0f);
Vertex(vecMins + vecRight);
// The top face
Normal(Vector(0, 1, 0));
TexCoord(0.0f, 1.0f);
Vertex(vecMins + vecRight + vecUp + vecForward);
TexCoord(0.0f, 0.0f);
Vertex(vecMins + vecUp + vecForward);
TexCoord(1.0f, 0.0f);
Vertex(vecMins + vecUp);
TexCoord(0.0f, 1.0f);
Vertex(vecMins + vecRight + vecUp + vecForward);
TexCoord(1.0f, 0.0f);
Vertex(vecMins + vecUp);
TexCoord(1.0f, 1.0f);
Vertex(vecMins + vecRight + vecUp);
// The right face
Normal(Vector(0, 0, 1));
TexCoord(0.0f, 1.0f);
Vertex(vecMins + vecRight + vecUp + vecForward);
TexCoord(1.0f, 1.0f);
Vertex(vecMins + vecRight + vecUp);
TexCoord(1.0f, 0.0f);
Vertex(vecMins + vecRight);
TexCoord(0.0f, 1.0f);
Vertex(vecMins + vecRight + vecUp + vecForward);
TexCoord(1.0f, 0.0f);
Vertex(vecMins + vecRight);
TexCoord(0.0f, 0.0f);
Vertex(vecMins + vecForward + vecRight);
// The front face
Normal(Vector(1, 0, 0));
TexCoord(0.0f, 1.0f);
Vertex(vecMins + vecRight + vecUp + vecForward);
TexCoord(0.0f, 0.0f);
Vertex(vecMins + vecForward + vecRight);
TexCoord(1.0f, 0.0f);
Vertex(vecMins + vecForward);
TexCoord(0.0f, 1.0f);
Vertex(vecMins + vecRight + vecUp + vecForward);
TexCoord(1.0f, 0.0f);
Vertex(vecMins + vecForward);
TexCoord(1.0f, 1.0f);
Vertex(vecMins + vecForward + vecUp);
EndRender();
}
void CRenderingContext::RenderBillboard(size_t iTexture, float flRadius, Vector vecUp, Vector vecRight)
{
vecUp = vecUp * flRadius;
vecRight = vecRight * flRadius;
BindTexture(iTexture);
// The up and right vectors form an orthogonal basis for the plane that the billboarded sprite is in.
// That means we can use combinations of these two vectors to find the four vertices of the sprite.
// http://youtu.be/puOTwCrEm7Q
// Pass the vertices of the billboarded sprite into the renderer in counter-clockwise order.
BeginRenderTriFan();
TexCoord(0.0f, 0.0f);
Vertex(-vecUp - vecRight);
TexCoord(1.0f, 0.0f);
Vertex(-vecUp + vecRight);
TexCoord(1.0f, 1.0f);
Vertex(vecUp + vecRight);
TexCoord(0.0f, 1.0f);
Vertex(vecUp - vecRight);
EndRender();
}
void CRenderingContext::UseProgram(const char* pszProgram)
{
CRenderContext& oContext = GetContext();
strncpy(oContext.m_szProgram, pszProgram, PROGRAM_LEN);
oContext.m_pShader = m_pShader = CShaderLibrary::GetShader(pszProgram);
UseProgram(m_pShader);
}
void CRenderingContext::UseProgram(class CShader* pShader)
{
CRenderContext& oContext = GetContext();
oContext.m_pShader = m_pShader = pShader;
if (!m_pShader)
{
oContext.m_szProgram[0] = '\0';
m_iProgram = 0;
GLCall(glUseProgram(0));
return;
}
strncpy(oContext.m_szProgram, pShader->m_sName.c_str(), PROGRAM_LEN);
m_iProgram = m_pShader->m_iProgram;
GLCall(glUseProgram((GLuint)m_pShader->m_iProgram));
oContext.m_bProjectionUpdated = false;
oContext.m_bViewUpdated = false;
}
void CRenderingContext::SetUniform(const char* pszName, int iValue)
{
int iUniform = glGetUniformLocation((GLuint)m_iProgram, pszName);
GLCall(glUniform1i(iUniform, iValue));
}
void CRenderingContext::SetUniform(const char* pszName, float flValue)
{
int iUniform = glGetUniformLocation((GLuint)m_iProgram, pszName);
TAssert(iUniform > 0);
GLCall(glUniform1f(iUniform, flValue));
}
void CRenderingContext::SetUniform(const char* pszName, const Vector& vecValue)
{
int iUniform = glGetUniformLocation((GLuint)m_iProgram, pszName);
TAssert(iUniform > 0);
GLCall(glUniform3fv(iUniform, 1, &vecValue.x));
}
void CRenderingContext::SetUniform(const char* pszName, const Vector4D& vecValue)
{
int iUniform = glGetUniformLocation((GLuint)m_iProgram, pszName);
TAssert(iUniform > 0);
GLCall(glUniform4fv(iUniform, 1, vecValue));
}
void CRenderingContext::SetUniform(const char* pszName, const ::Color& clrValue)
{
Vector4D vecValue(clrValue); // Convert it to a vector so it's a 0-1 value and not a 0-255 value
int iUniform = glGetUniformLocation((GLuint)m_iProgram, pszName);
TAssert(iUniform > 0);
GLCall(glUniform4fv(iUniform, 1, &vecValue.x));
}
void CRenderingContext::SetUniform(const char* pszName, const Matrix4x4& mValue)
{
int iUniform = glGetUniformLocation((GLuint)m_iProgram, pszName);
TAssert(iUniform > 0);
GLCall(glUniformMatrix4fv(iUniform, 1, false, mValue));
}
void CRenderingContext::SetUniform(const char* pszName, size_t iSize, const float* aflValues)
{
int iUniform = glGetUniformLocation((GLuint)m_iProgram, pszName);
TAssert(iUniform > 0);
GLCall(glUniform1fv(iUniform, iSize, aflValues));
}
void CRenderingContext::BindTexture(size_t iTexture, int iChannel, bool bMultisample)
{
GLCall(glActiveTexture(GL_TEXTURE0+iChannel));
if (bMultisample)
GLCall(glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, (GLuint)iTexture));
else
GLCall(glBindTexture(GL_TEXTURE_2D, (GLuint)iTexture));
}
void CRenderingContext::SetColor(const ::Color& c)
{
m_clrRender = c;
}
void CRenderingContext::BeginRenderTris()
{
s_dynamic_verts.clear();
m_num_verts = 0;
m_bTexCoord = false;
m_bNormal = false;
m_bTangents = false;
m_iDrawMode = GL_TRIANGLES;
}
void CRenderingContext::BeginRenderTriFan()
{
s_dynamic_verts.clear();
m_num_verts = 0;
m_bTexCoord = false;
m_bNormal = false;
m_bTangents = false;
m_iDrawMode = GL_TRIANGLE_FAN;
}
void CRenderingContext::BeginRenderTriStrip()
{
s_dynamic_verts.clear();
m_num_verts = 0;
m_bTexCoord = false;
m_bNormal = false;
m_bTangents = false;
m_iDrawMode = GL_TRIANGLE_STRIP;
}
void CRenderingContext::BeginRenderLines()
{
s_dynamic_verts.clear();
m_num_verts = 0;
m_bTexCoord = false;
m_bNormal = false;
m_bTangents = false;
m_iDrawMode = GL_LINES;
}
void CRenderingContext::BeginRenderLineLoop()
{
s_dynamic_verts.clear();
m_num_verts = 0;
m_bTexCoord = false;
m_bNormal = false;
m_bTangents = false;
m_iDrawMode = GL_LINE_LOOP;
}
void CRenderingContext::BeginRenderLineStrip()
{
s_dynamic_verts.clear();
m_num_verts = 0;
m_bTexCoord = false;
m_bNormal = false;
m_bTangents = false;
m_iDrawMode = GL_LINE_STRIP;
}
void CRenderingContext::BeginRenderDebugLines()
{
BeginRenderLines();
}
void CRenderingContext::BeginRenderPoints(float flSize)
{
s_dynamic_verts.clear();
m_num_verts = 0;
m_bTexCoord = false;
m_bNormal = false;
m_bTangents = false;
GLCall(glPointSize( flSize ));
m_iDrawMode = GL_POINTS;
}
void CRenderingContext::TexCoord(float s, float t, int iChannel)
{
m_texcoords = Vector2D(s, t);
m_bTexCoord = true;
}
void CRenderingContext::TexCoord(const Vector2D& v, int iChannel)
{
m_texcoords = v;
m_bTexCoord = true;
}
void CRenderingContext::TexCoord(const Vector& v, int iChannel)
{
m_texcoords = v;
m_bTexCoord = true;
}
void CRenderingContext::Normal(const Vector& v)
{
m_normal = v;
m_bNormal = true;
}
void CRenderingContext::Tangent(const Vector& v)
{
TAssert(m_bNormal);
m_tangent = v;
m_bTangents = true;
}
void CRenderingContext::Bitangent(const Vector& v)
{
TAssert(m_bNormal);
m_bitangent = v;
m_bTangents = true;
}
void CRenderingContext::Vertex(const Vector& v)
{
m_num_verts++;
s_dynamic_verts.push_back(v.x);
s_dynamic_verts.push_back(v.y);
s_dynamic_verts.push_back(v.z);
if (m_bTexCoord)
{
s_dynamic_verts.push_back(m_texcoords.x);
s_dynamic_verts.push_back(m_texcoords.y);
}
if (m_bNormal)
{
s_dynamic_verts.push_back(m_normal.x);
s_dynamic_verts.push_back(m_normal.y);
s_dynamic_verts.push_back(m_normal.z);
}
if (m_bTangents)
{
s_dynamic_verts.push_back(m_tangent.x);
s_dynamic_verts.push_back(m_tangent.y);
s_dynamic_verts.push_back(m_tangent.z);
s_dynamic_verts.push_back(m_bitangent.x);
s_dynamic_verts.push_back(m_bitangent.y);
s_dynamic_verts.push_back(m_bitangent.z);
}
}
void CRenderingContext::EndRender()
{
if (!m_pShader)
{
UseProgram("model");
if (!m_pShader)
return;
}
CRenderContext& oContext = GetContext();
if (!oContext.m_bProjectionUpdated)
SetUniform("mProjection", oContext.m_mProjection);
if (!oContext.m_bViewUpdated)
SetUniform("mView", oContext.m_mView);
if (!oContext.m_bTransformUpdated)
SetUniform("mGlobal", oContext.m_mTransformations);
oContext.m_bProjectionUpdated = oContext.m_bViewUpdated = oContext.m_bTransformUpdated = true;
GLCall(glBindVertexArray(m_pRenderer->m_default_vao));
GLCall(glBindBuffer(GL_ARRAY_BUFFER, m_pRenderer->m_dynamic_mesh_vbo));
GLCall(glBufferData(GL_ARRAY_BUFFER, GLsizeiptr((size_t)s_dynamic_verts.size() * sizeof(float)), s_dynamic_verts.data(), GL_STATIC_DRAW));
int stride = 3 * sizeof(float);
int position_offset = 0;
int texcoord_offset = stride;
int normal_offset = stride;
int tangent_offset = stride;
int bitangent_offset = stride;
if (m_bTexCoord)
{
int uv_size = 2 * sizeof(float);
stride += uv_size;
normal_offset += uv_size;
tangent_offset += uv_size;
bitangent_offset += uv_size;
}
if (m_bNormal)
{
int normal_size = 3 * sizeof(float);
stride += normal_size;
tangent_offset += normal_size;
bitangent_offset += normal_size;
}
if (m_bTangents)
{
int tangents_size = 6 * sizeof(float);
stride += tangents_size;
bitangent_offset += 3 * sizeof(float);
}
if (m_bTexCoord)
{
for (size_t i = 0; i < MAX_TEXTURE_CHANNELS; i++)
{
if (m_pShader->m_aiTexCoordAttributes[i] != ~0)
{
GLCall(glEnableVertexAttribArray(m_pShader->m_aiTexCoordAttributes[i]));
GLCall(glVertexAttribPointer(m_pShader->m_aiTexCoordAttributes[i], 2, GL_FLOAT, false, stride, BUFFER_OFFSET(texcoord_offset)));
}
}
}
if (m_bNormal && m_pShader->m_iNormalAttribute != ~0)
{
GLCall(glEnableVertexAttribArray(m_pShader->m_iNormalAttribute));
GLCall(glVertexAttribPointer(m_pShader->m_iNormalAttribute, 3, GL_FLOAT, false, stride, BUFFER_OFFSET(normal_offset)));
}
if (m_bTangents && m_pShader->m_iTangentAttribute != ~0 && m_pShader->m_iBitangentAttribute != ~0)
{
GLCall(glEnableVertexAttribArray(m_pShader->m_iTangentAttribute));
GLCall(glVertexAttribPointer(m_pShader->m_iTangentAttribute, 3, GL_FLOAT, false, stride, BUFFER_OFFSET(tangent_offset)));
GLCall(glEnableVertexAttribArray(m_pShader->m_iBitangentAttribute));
GLCall(glVertexAttribPointer(m_pShader->m_iBitangentAttribute, 3, GL_FLOAT, false, stride, BUFFER_OFFSET(bitangent_offset)));
}
GLCall(glEnableVertexAttribArray(m_pShader->m_iPositionAttribute));
GLCall(glVertexAttribPointer(m_pShader->m_iPositionAttribute, 3, GL_FLOAT, false, stride, BUFFER_OFFSET(0)));
GLCall(glDrawArrays(m_iDrawMode, 0, m_num_verts));
GLCall(glDisableVertexAttribArray(m_pShader->m_iPositionAttribute));
for (size_t i = 0; i < MAX_TEXTURE_CHANNELS; i++)
{
if (m_pShader->m_aiTexCoordAttributes[i] != ~0)
GLCall(glDisableVertexAttribArray(m_pShader->m_aiTexCoordAttributes[i]));
}
if (m_pShader->m_iNormalAttribute != ~0)
GLCall(glDisableVertexAttribArray(m_pShader->m_iNormalAttribute));
if (m_pShader->m_iTangentAttribute != ~0)
GLCall(glDisableVertexAttribArray(m_pShader->m_iTangentAttribute));
if (m_pShader->m_iBitangentAttribute != ~0)
GLCall(glDisableVertexAttribArray(m_pShader->m_iBitangentAttribute));
if (m_pShader->m_iColorAttribute != ~0)
GLCall(glDisableVertexAttribArray(m_pShader->m_iColorAttribute));
}
void CRenderingContext::CreateVBO(size_t& iVBO, size_t& iVBOSize)
{
TAssert(m_pRenderer);
if (!m_pRenderer)
return;
TAssert(s_dynamic_verts.size());
if (!s_dynamic_verts.size())
return;
iVBOSize = (size_t)s_dynamic_verts.size() * sizeof(s_dynamic_verts[0]);
iVBO = m_pRenderer->LoadVertexDataIntoGL(iVBOSize, s_dynamic_verts.data());
}
void CRenderingContext::BeginRenderVertexArray(size_t iBuffer)
{
if (iBuffer)
GLCall(glBindBuffer(GL_ARRAY_BUFFER, iBuffer));
}
#define BUFFER_OFFSET(i) ((char *)NULL + (i))
void CRenderingContext::SetPositionBuffer(float* pflBuffer, size_t iStride)
{
TAssert(m_pShader->m_iPositionAttribute != ~0);
GLCall(glEnableVertexAttribArray(m_pShader->m_iPositionAttribute));
GLCall(glVertexAttribPointer(m_pShader->m_iPositionAttribute, 3, GL_FLOAT, false, iStride, pflBuffer));
}
void CRenderingContext::SetPositionBuffer(size_t iOffset, size_t iStride)
{
TAssert(iOffset%4 == 0); // Should be multiples of four because it's offsets in bytes and we're always working with floats or doubles
TAssert(m_pShader->m_iPositionAttribute != ~0);
GLCall(glEnableVertexAttribArray(m_pShader->m_iPositionAttribute));
GLCall(glVertexAttribPointer(m_pShader->m_iPositionAttribute, 3, GL_FLOAT, false, iStride, BUFFER_OFFSET(iOffset)));
}
void CRenderingContext::SetNormalsBuffer(float* pflBuffer, size_t iStride)
{
if (m_pShader->m_iNormalAttribute == ~0)
return;
GLCall(glEnableVertexAttribArray(m_pShader->m_iNormalAttribute));
GLCall(glVertexAttribPointer(m_pShader->m_iNormalAttribute, 3, GL_FLOAT, false, iStride, pflBuffer));
}
void CRenderingContext::SetNormalsBuffer(size_t iOffset, size_t iStride)
{
if (m_pShader->m_iNormalAttribute == ~0)
return;
TAssert(iOffset%4 == 0); // Should be multiples of four because it's offsets in bytes and we're always working with floats or doubles
GLCall(glEnableVertexAttribArray(m_pShader->m_iNormalAttribute));
GLCall(glVertexAttribPointer(m_pShader->m_iNormalAttribute, 3, GL_FLOAT, false, iStride, BUFFER_OFFSET(iOffset)));
}
void CRenderingContext::SetTangentsBuffer(float* pflBuffer, size_t iStride)
{
if (m_pShader->m_iTangentAttribute == ~0)
return;
GLCall(glEnableVertexAttribArray(m_pShader->m_iTangentAttribute));
GLCall(glVertexAttribPointer(m_pShader->m_iTangentAttribute, 3, GL_FLOAT, false, iStride, pflBuffer));
}
void CRenderingContext::SetTangentsBuffer(size_t iOffset, size_t iStride)
{
if (m_pShader->m_iTangentAttribute == ~0)
return;
TAssert(iOffset%4 == 0); // Should be multiples of four because it's offsets in bytes and we're always working with floats or doubles
GLCall(glEnableVertexAttribArray(m_pShader->m_iTangentAttribute));
GLCall(glVertexAttribPointer(m_pShader->m_iTangentAttribute, 3, GL_FLOAT, false, iStride, BUFFER_OFFSET(iOffset)));
}
void CRenderingContext::SetBitangentsBuffer(float* pflBuffer, size_t iStride)
{
if (m_pShader->m_iBitangentAttribute == ~0)
return;
GLCall(glEnableVertexAttribArray(m_pShader->m_iBitangentAttribute));
GLCall(glVertexAttribPointer(m_pShader->m_iBitangentAttribute, 3, GL_FLOAT, false, iStride, pflBuffer));
}
void CRenderingContext::SetBitangentsBuffer(size_t iOffset, size_t iStride)
{
if (m_pShader->m_iBitangentAttribute == ~0)
return;
TAssert(iOffset%4 == 0); // Should be multiples of four because it's offsets in bytes and we're always working with floats or doubles
GLCall(glEnableVertexAttribArray(m_pShader->m_iBitangentAttribute));
GLCall(glVertexAttribPointer(m_pShader->m_iBitangentAttribute, 3, GL_FLOAT, false, iStride, BUFFER_OFFSET(iOffset)));
}
void CRenderingContext::SetTexCoordBuffer(float* pflBuffer, size_t iStride, size_t iChannel)
{
TAssert(iChannel >= 0 && iChannel < MAX_TEXTURE_CHANNELS);
if (m_pShader->m_aiTexCoordAttributes[iChannel] == ~0)
return;
GLCall(glEnableVertexAttribArray(m_pShader->m_aiTexCoordAttributes[iChannel]));
GLCall(glVertexAttribPointer(m_pShader->m_aiTexCoordAttributes[iChannel], 2, GL_FLOAT, false, iStride, pflBuffer));
}
void CRenderingContext::SetTexCoordBuffer(size_t iOffset, size_t iStride, size_t iChannel)
{
TAssert(iChannel >= 0 && iChannel < MAX_TEXTURE_CHANNELS);
if (m_pShader->m_aiTexCoordAttributes[iChannel] == ~0)
return;
TAssert(iOffset%4 == 0); // Should be multiples of four because it's offsets in bytes and we're always working with floats or doubles
GLCall(glEnableVertexAttribArray(m_pShader->m_aiTexCoordAttributes[iChannel]));
GLCall(glVertexAttribPointer(m_pShader->m_aiTexCoordAttributes[iChannel], 2, GL_FLOAT, false, iStride, BUFFER_OFFSET(iOffset)));
}
void CRenderingContext::SetCustomIntBuffer(const char* pszName, size_t iSize, size_t iOffset, size_t iStride)
{
int iAttribute = glGetAttribLocation(m_iProgram, pszName);
TAssert(iAttribute != ~0);
if (iAttribute == ~0)
return;
TAssert(iOffset%4 == 0); // Should be multiples of four because it's offsets in bytes and we're always working with floats or doubles
GLCall(glEnableVertexAttribArray(iAttribute));
GLCall(glVertexAttribIPointer(iAttribute, iSize, GL_INT, iStride, BUFFER_OFFSET(iOffset)));
}
void CRenderingContext::EndRenderVertexArray(size_t iVertices, bool bWireframe)
{
CRenderContext& oContext = GetContext();
if (!oContext.m_bProjectionUpdated)
SetUniform("mProjection", oContext.m_mProjection);
if (!oContext.m_bViewUpdated)
SetUniform("mView", oContext.m_mView);
if (!oContext.m_bTransformUpdated)
SetUniform("mGlobal", oContext.m_mTransformations);
oContext.m_bProjectionUpdated = oContext.m_bViewUpdated = oContext.m_bTransformUpdated = true;
if (bWireframe)
{
GLCall(glLineWidth(1));
GLCall(glDrawArrays(GL_LINES, 0, iVertices));
}
else
GLCall(glDrawArrays(GL_TRIANGLES, 0, iVertices));
GLCall(glDisableVertexAttribArray(m_pShader->m_iPositionAttribute));
for (size_t i = 0; i < MAX_TEXTURE_CHANNELS; i++)
{
if (m_pShader->m_aiTexCoordAttributes[i] != ~0)
GLCall(glDisableVertexAttribArray(m_pShader->m_aiTexCoordAttributes[i]));
}
if (m_pShader->m_iNormalAttribute != ~0)
GLCall(glDisableVertexAttribArray(m_pShader->m_iNormalAttribute));
if (m_pShader->m_iTangentAttribute != ~0)
GLCall(glDisableVertexAttribArray(m_pShader->m_iTangentAttribute));
if (m_pShader->m_iBitangentAttribute != ~0)
GLCall(glDisableVertexAttribArray(m_pShader->m_iBitangentAttribute));
if (m_pShader->m_iColorAttribute != ~0)
GLCall(glDisableVertexAttribArray(m_pShader->m_iColorAttribute));
GLCall(glBindBuffer(GL_ARRAY_BUFFER, 0));
}
void CRenderingContext::EndRenderVertexArrayTriangles(size_t iTriangles, int* piIndices)
{
CRenderContext& oContext = GetContext();
if (!oContext.m_bProjectionUpdated)
SetUniform("mProjection", oContext.m_mProjection);
if (!oContext.m_bViewUpdated)
SetUniform("mView", oContext.m_mView);
if (!oContext.m_bTransformUpdated)
SetUniform("mGlobal", oContext.m_mTransformations);
oContext.m_bProjectionUpdated = oContext.m_bViewUpdated = oContext.m_bTransformUpdated = true;
GLCall(glDrawElements(GL_TRIANGLES, iTriangles*3, GL_UNSIGNED_INT, piIndices));
GLCall(glDisableVertexAttribArray(m_pShader->m_iPositionAttribute));
for (size_t i = 0; i < MAX_TEXTURE_CHANNELS; i++)
{
if (m_pShader->m_aiTexCoordAttributes[i] != ~0)
GLCall(glDisableVertexAttribArray(m_pShader->m_aiTexCoordAttributes[i]));
}
if (m_pShader->m_iNormalAttribute != ~0)
GLCall(glDisableVertexAttribArray(m_pShader->m_iNormalAttribute));
if (m_pShader->m_iTangentAttribute != ~0)
GLCall(glDisableVertexAttribArray(m_pShader->m_iTangentAttribute));
if (m_pShader->m_iBitangentAttribute != ~0)
GLCall(glDisableVertexAttribArray(m_pShader->m_iBitangentAttribute));
if (m_pShader->m_iColorAttribute != ~0)
GLCall(glDisableVertexAttribArray(m_pShader->m_iColorAttribute));
GLCall(glBindBuffer(GL_ARRAY_BUFFER, 0));
}
void CRenderingContext::EndRenderVertexArrayIndexed(size_t iBuffer, size_t iVertices)
{
CRenderContext& oContext = GetContext();
if (!oContext.m_bProjectionUpdated)
SetUniform("mProjection", oContext.m_mProjection);
if (!oContext.m_bViewUpdated)
SetUniform("mView", oContext.m_mView);
if (!oContext.m_bTransformUpdated)
SetUniform("mGlobal", oContext.m_mTransformations);
oContext.m_bProjectionUpdated = oContext.m_bViewUpdated = oContext.m_bTransformUpdated = true;
GLCall(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, iBuffer));
bool bWireframe = false;
GLCall(glDrawElements(bWireframe?GL_LINES:GL_TRIANGLES, iVertices, GL_UNSIGNED_INT, nullptr));
GLCall(glDisableVertexAttribArray(m_pShader->m_iPositionAttribute));
for (size_t i = 0; i < MAX_TEXTURE_CHANNELS; i++)
{
if (m_pShader->m_aiTexCoordAttributes[i] != ~0)
GLCall(glDisableVertexAttribArray(m_pShader->m_aiTexCoordAttributes[i]));
}
if (m_pShader->m_iNormalAttribute != ~0)
GLCall(glDisableVertexAttribArray(m_pShader->m_iNormalAttribute));
if (m_pShader->m_iTangentAttribute != ~0)
GLCall(glDisableVertexAttribArray(m_pShader->m_iTangentAttribute));
if (m_pShader->m_iBitangentAttribute != ~0)
GLCall(glDisableVertexAttribArray(m_pShader->m_iBitangentAttribute));
if (m_pShader->m_iColorAttribute != ~0)
GLCall(glDisableVertexAttribArray(m_pShader->m_iColorAttribute));
GLCall(glBindBuffer(GL_ARRAY_BUFFER, 0));
GLCall(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0));
}
void CRenderingContext::ReadPixels(size_t x, size_t y, size_t w, size_t h, Vector4D* pvecPixels)
{
GLCall(glReadPixels(x, y, w, h, GL_RGBA, GL_FLOAT, pvecPixels));
}
void CRenderingContext::Finish()
{
GLCall(glFinish());
}
CRenderingContext::CRenderContext::CRenderContext()
{
m_bProjectionUpdated = false;
m_bViewUpdated = false;
m_bTransformUpdated = false;
}
| 29.20165 | 205 | 0.760256 | [
"vector",
"model",
"transform"
] |
d5e45b5638074d40c59a0042345d17baa6f97e03 | 9,016 | cpp | C++ | src/test_application/activescenes/redstone_osp.cpp | Capital-Asterisk/redstone-osp | 3f86cf6f9d26f596f3b7f8ee9d66743ac8c82db6 | [
"MIT"
] | null | null | null | src/test_application/activescenes/redstone_osp.cpp | Capital-Asterisk/redstone-osp | 3f86cf6f9d26f596f3b7f8ee9d66743ac8c82db6 | [
"MIT"
] | null | null | null | src/test_application/activescenes/redstone_osp.cpp | Capital-Asterisk/redstone-osp | 3f86cf6f9d26f596f3b7f8ee9d66743ac8c82db6 | [
"MIT"
] | null | null | null | #include "redstone_osp.h"
#include <osp/logging.h>
namespace testapp::redstone
{
/**
* @brief Main block-related update function
*
* @param rScene
* @param blkChanges
*/
void update_blocks(RedstoneScene& rScene, ArrayView< std::pair<ChunkId, ChkBlkPlacements_t> > blkChanges)
{
// clear previous frame's block type updates
for (TmpChkBlkTypeUpd &rBlkTypeUpd : rScene.m_blkTypeUpdates)
{
rBlkTypeUpd.m_changed.reset();
rBlkTypeUpd.m_perType.clear();
}
// Update block IDs
// * Modifies each chunk's BlkTypeId buffers
// * Writes modified chunks
// * Writes per-blocktype added/removed changes: rScene.m_blkTypeUpdates
world_update_block_ids(rScene, blkChanges);
// clear notify slots
for (TmpChkNotify &rNotify : rScene.m_chkNotify)
{
rNotify.m_notifyTypes.clear();
// clear bitsets
for (HierBitset_t &rBitset : rNotify.m_notifySlots)
{
rBitset.reset();
}
}
// Notify subscribers
for (std::size_t chkIdI = 0; chkIdI < rScene.m_blkTypeUpdates.size(); ++ chkIdI)
{
if (rScene.m_blkTypeUpdates[chkIdI].m_changed.count() != 0)
{
TmpExtNotify dummy; // not yet implemented
chunk_notify_subscribers(
rScene.m_chunks.m_connect[chkIdI],
rScene.m_blkTypeUpdates[chkIdI].m_changed, rScene.m_chunks.m_blkTypes[chkIdI], rScene.m_chkNotify[chkIdI], dummy);
}
}
// Log blocks to notify
for (TmpChkNotify const &rNotify : rScene.m_chkNotify)
{
for (HierBitset_t const &rBitset : rNotify.m_notifySlots)
{
if (rBitset.size() == 0)
{
continue;
}
for (int const blkSubscriber : rBitset)
{
OSP_LOG_TRACE("Notify: {}", blkSubscriber);
}
}
}
// Accumolate subscription changes
TmpUpdPublish_t updPub;
TmpUpdSubscribe_t updSub(rScene.m_chunks.m_ids.capacity());
for (std::size_t chunkId : rScene.m_chunks.m_dirty)
{
TmpChkBlkTypeUpd const& blkTypeUpd = rScene.m_blkTypeUpdates[chunkId];
if (auto it = blkTypeUpd.m_perType.find(g_blkTypeIds.id_of("dust"));
it != blkTypeUpd.m_perType.end())
{
chunk_subscribe_dusts(it->second, ChunkId(chunkId), index_to_pos(chunkId), updPub, updSub[chunkId]);
}
}
// TODO: allocate chunks allowed to subscribe to not-yet-loaded chunks
// Apply publish changes
// 1 element for each chunk changed
for (std::size_t i = 0; i < updPub.size(); ++i)
{
Vector3i const pos = updPub.key(i);
TmpChkUpdPublish &rChkUpdConnect = updPub.value(i);
auto found = rScene.m_chunks.m_coordToChunk.find(ChunkCoord_t{pos.x(), pos.y(), pos.z()});
if (found == rScene.m_chunks.m_coordToChunk.end())
{
continue; // just skip non existent chunks for now
}
using PublishTo = TmpChkUpdPublish::PublishTo;
std::sort(rChkUpdConnect.m_changes.begin(), rChkUpdConnect.m_changes.end(),
[] (PublishTo const& lhs, PublishTo const& rhs)
{
return lhs.m_pubBlk < rhs.m_pubBlk;
});
ChkConnect::MultiMap_t &rBlkPublish = rScene.m_chunks.m_connect.at(std::size_t(found->second)).m_blkPublish;
// Intention is to have a thread for each chunk do this.
// Multiple TmpChkUpdPublish can be passed to this thread and
// iterated all at once
using it_t = TmpChkUpdPublish::Vec_t::iterator;
using pair_t = std::pair<it_t, it_t>;
auto its = std::array
{
pair_t(rChkUpdConnect.m_changes.begin(),
rChkUpdConnect.m_changes.end())
};
std::size_t const totalChanges = rChkUpdConnect.m_changes.size();
if (std::size_t const sizeReq
= lgrn::div_ceil(rBlkPublish.data_size() + totalChanges, gc_chunkSize) * gc_chunkSize;
rBlkPublish.data_capacity() < sizeReq)
{
rBlkPublish.data_reserve(sizeReq);
}
std::vector<BlkConnect> tmpConnect;
ChkBlkId currBlk = lgrn::id_null<ChkBlkId>();
auto flush = [&tmpConnect, &currBlk, &rBlkPublish] () -> void
{
if (tmpConnect.empty()) [[unlikely]]
{
return;
}
uint16_t const currBlkI = uint16_t(currBlk);
if (rBlkPublish.contains(currBlkI))
{
// erase existing subscribers
auto span = rBlkPublish[currBlkI];
tmpConnect.insert(tmpConnect.end(), span.begin(), span.end());
rBlkPublish.erase(currBlkI);
}
rBlkPublish.emplace(currBlkI, tmpConnect.begin(), tmpConnect.end());
OSP_LOG_TRACE("Block {} publishes to:", currBlk);
for (auto const fish : tmpConnect)
{
OSP_LOG_TRACE("* {}", fish.m_block);
}
tmpConnect.clear();
};
funnel_each(its.begin(), its.end(),
[] (pair_t const& lhs, pair_t const& rhs) -> bool
{
return lhs.first->m_pubBlk < rhs.first->m_pubBlk;
},
[&tmpConnect, &currBlk, flush] (it_t pubIt)
{
if (currBlk != pubIt->m_pubBlk)
{
flush();
currBlk = pubIt->m_pubBlk;
}
if (currBlk == pubIt->m_pubBlk)
{
tmpConnect.emplace_back(BlkConnect{pubIt->m_subChunk, pubIt->m_subBlk});
}
});
flush();
rBlkPublish.pack();
}
}
//-----------------------------------------------------------------------------
void chunk_subscribe_dusts(ChkBlkChanges const& dustBlkUpd, ChunkId chunkId, Vector3i chunkPos, TmpUpdPublish_t& rUpdPublish, TmpChkUpdSubscribe& rUpdChkSubscribe)
{
if (dustBlkUpd.m_added.count() == 0)
{
return;
}
using PublishTo = TmpChkUpdPublish::PublishTo;
using SubscribeToItn = TmpChkUpdSubscribe::SubscribeToItn;
using SubscribeToExt = TmpChkUpdSubscribe::SubscribeToExt;
std::array<Vector3i, 12> sc_subToOffsets
{{
{ 1, -1, 0}, { 1, 0, 0}, { 1, 1, 0},
{-1, -1, 0}, {-1, 0, 0}, {-1, 1, 0},
{ 0, -1, 1}, { 0, 0, 1}, { 0, 1, 1},
{ 0, -1, -1}, { 0, 0, -1}, { 0, 1, -1}
}};
std::size_t const ownChunkPubIdx = rUpdPublish.find_assure(chunkPos);
for (std::size_t subBlkId : dustBlkUpd.m_added)
{
Vector3i const subBlkPos = index_to_pos(subBlkId);
for (Vector3i const offset : sc_subToOffsets)
{
DiffBlk const diff = inter_chunk_pos(subBlkPos + offset);
ChkBlkId const pubBlkId = chunk_block_id(diff.m_pos);
PublishTo const pub{pubBlkId, ChkBlkId(subBlkId), chunkId};
if (diff.m_chunkDelta.isZero())
{
// subscribe to own chunk (common case)
rUpdPublish.value(ownChunkPubIdx).m_changes.emplace_back(pub);
rUpdChkSubscribe.m_changesItn.emplace_back(SubscribeToItn{ChkBlkId(subBlkId), pubBlkId});
}
else
{
// subscribe to neighbouring chunk
Vector3i const neighbourPos = chunkPos + diff.m_chunkDelta;
rUpdPublish[neighbourPos].m_changes.emplace_back(pub);
}
}
}
}
void chunk_connect_dusts(
BlkTypeId type,
ChunkId chkId,
HierBitset_t const& notify,
ACtxVxLoadedChunks const& chunks,
ACtxVxRsDusts const& dusts,
ACtxVxRsDusts::ChkDust_t &rChkDust)
{
}
//-----------------------------------------------------------------------------
void world_update_block_ids(
RedstoneScene& rScene,
ArrayView< std::pair<ChunkId, ChkBlkPlacements_t> > chunkUpd)
{
using namespace osp::active;
for (auto const& [chunkId, blkPlace] : chunkUpd)
{
// Clear block added and removed queues
for (auto & [blkTypeId, blkTypeUpd]
: rScene.m_blkTypeUpdates.at(size_t(chunkId)).m_perType)
{
blkTypeUpd.m_added.reset();
blkTypeUpd.m_removed.reset();
}
// Update all block IDs and write type changes
for (auto const& [newBlkTypeId, rPlace] : blkPlace)
{
chunk_assign_block_ids(
newBlkTypeId, rPlace,
rScene.m_chunks.m_blkTypes.at(size_t(chunkId)),
rScene.m_blkTypeUpdates.at(size_t(chunkId)));
}
HierBitset_t& rNotify = rScene.m_chkNotify.at(size_t(chunkId)).m_notifySlots.at(0);
rNotify.reset(); // Clear notify queues too
// just set all chunks dirty for now lol
rScene.m_chunks.m_dirty.set(size_t(chunkId));
}
}
} // namespace testapp::redstone
| 32.431655 | 163 | 0.57043 | [
"vector"
] |
d5f398a8962b8de7dfc2b72a169bb5148f67070c | 11,917 | cpp | C++ | src/LercLib/Lerc1Decode/CntZImage.cpp | zakjan/lerc | 3f523fee2b5764f2029e035c41a2325b6360a29d | [
"Apache-2.0"
] | 157 | 2015-12-17T22:21:39.000Z | 2021-12-18T09:01:30.000Z | src/LercLib/Lerc1Decode/CntZImage.cpp | zakjan/lerc | 3f523fee2b5764f2029e035c41a2325b6360a29d | [
"Apache-2.0"
] | 71 | 2015-12-18T02:29:05.000Z | 2022-03-12T01:24:39.000Z | src/LercLib/Lerc1Decode/CntZImage.cpp | zakjan/lerc | 3f523fee2b5764f2029e035c41a2325b6360a29d | [
"Apache-2.0"
] | 55 | 2015-12-18T00:54:07.000Z | 2021-12-28T19:52:26.000Z | /*
Copyright 2015 Esri
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.
A local copy of the license and additional notices are located with the
source distribution at:
http://github.com/Esri/lerc/
Contributors: Thomas Maurer
*/
#include <cstring>
#include <algorithm>
#include "CntZImage.h"
#include "BitStuffer.h"
#include "../BitMask.h"
#include "../RLE.h"
using namespace std;
using namespace LercNS;
// -------------------------------------------------------------------------- ;
CntZImage::CntZImage()
{
type_ = CNT_Z;
m_bDecoderCanIgnoreMask = false;
memset(&m_infoFromComputeNumBytes, 0, sizeof(m_infoFromComputeNumBytes));
};
// -------------------------------------------------------------------------- ;
bool CntZImage::resizeFill0(int width, int height)
{
if (!resize(width, height))
return false;
memset(getData(), 0, width * height * sizeof(CntZ));
return true;
}
// -------------------------------------------------------------------------- ;
unsigned int CntZImage::computeNumBytesNeededToReadHeader(bool onlyZPart)
{
CntZImage zImg;
unsigned int cnt = (unsigned int)zImg.getTypeString().length(); // "CntZImage ", 10 bytes
cnt += 4 * sizeof(int); // version, type, width, height
cnt += 1 * sizeof(double); // maxZError
if (!onlyZPart)
cnt += 3 * sizeof(int) + sizeof(float); // cnt part
cnt += 3 * sizeof(int) + sizeof(float); // z part
cnt += 1;
return cnt;
}
// -------------------------------------------------------------------------- ;
bool CntZImage::read(Byte** ppByte, double maxZError, bool onlyHeader, bool onlyZPart)
{
if (!ppByte || !*ppByte)
return false;
size_t len = getTypeString().length();
string typeStr(len, '0');
memcpy(&typeStr[0], *ppByte, len);
*ppByte += len;
if (typeStr != getTypeString())
return false;
int version = 0, type = 0, width = 0, height = 0;
double maxZErrorInFile = 0;
Byte* ptr = *ppByte;
memcpy(&version, ptr, sizeof(int)); ptr += sizeof(int);
memcpy(&type, ptr, sizeof(int)); ptr += sizeof(int);
memcpy(&height, ptr, sizeof(int)); ptr += sizeof(int);
memcpy(&width, ptr, sizeof(int)); ptr += sizeof(int);
memcpy(&maxZErrorInFile, ptr, sizeof(double)); ptr += sizeof(double);
*ppByte = ptr;
SWAP_4(version);
SWAP_4(type);
SWAP_4(height);
SWAP_4(width);
SWAP_8(maxZErrorInFile);
if (version != 11 || type != type_)
return false;
if (width > 20000 || height > 20000)
return false;
if (maxZErrorInFile > maxZError)
return false;
if (onlyHeader)
return true;
if (!onlyZPart && !resizeFill0(width, height)) // init with (0,0), used below
return false;
m_bDecoderCanIgnoreMask = false;
for (int iPart = 0; iPart < 2; iPart++)
{
bool zPart = iPart ? true : false; // first cnt part, then z part
if (!zPart && onlyZPart)
continue;
int numTilesVert = 0, numTilesHori = 0, numBytes = 0;
float maxValInImg = 0;
Byte* ptr = *ppByte;
memcpy(&numTilesVert, ptr, sizeof(int)); ptr += sizeof(int);
memcpy(&numTilesHori, ptr, sizeof(int)); ptr += sizeof(int);
memcpy(&numBytes, ptr, sizeof(int)); ptr += sizeof(int);
memcpy(&maxValInImg, ptr, sizeof(float)); ptr += sizeof(float);
*ppByte = ptr;
Byte* bArr = ptr;
SWAP_4(numTilesVert);
SWAP_4(numTilesHori);
SWAP_4(numBytes);
SWAP_4(maxValInImg);
if (!zPart && numTilesVert == 0 && numTilesHori == 0) // no tiling for this cnt part
{
if (numBytes == 0) // cnt part is const
{
CntZ* dstPtr = getData();
for (int i = 0; i < height_; i++)
for (int j = 0; j < width_; j++)
{
dstPtr->cnt = maxValInImg;
dstPtr++;
}
if (maxValInImg > 0)
m_bDecoderCanIgnoreMask = true;
}
if (numBytes > 0) // cnt part is binary mask, use fast RLE class
{
// decompress to bit mask
BitMask bitMask(width_, height_);
RLE rle;
if (!rle.decompress(bArr, width_ * height_ * 2, (Byte*)bitMask.Bits(), bitMask.Size()))
return false;
CntZ* dstPtr = getData();
for (int k = 0, i = 0; i < height_; i++)
for (int j = 0; j < width_; j++, k++, dstPtr++)
dstPtr->cnt = bitMask.IsValid(k) ? 1.0f : 0.0f;
}
}
else if (!readTiles(zPart, maxZErrorInFile, numTilesVert, numTilesHori, maxValInImg, bArr))
return false;
*ppByte += numBytes;
}
m_tmpDataVec.clear();
return true;
}
// -------------------------------------------------------------------------- ;
bool CntZImage::readTiles(bool zPart, double maxZErrorInFile, int numTilesVert, int numTilesHori,
float maxValInImg, Byte* bArr)
{
Byte* ptr = bArr;
for (int iTile = 0; iTile <= numTilesVert; iTile++)
{
int tileH = height_ / numTilesVert;
int i0 = iTile * tileH;
if (iTile == numTilesVert)
tileH = height_ % numTilesVert;
if (tileH == 0)
continue;
for (int jTile = 0; jTile <= numTilesHori; jTile++)
{
int tileW = width_ / numTilesHori;
int j0 = jTile * tileW;
if (jTile == numTilesHori)
tileW = width_ % numTilesHori;
if (tileW == 0)
continue;
bool rv = zPart ? readZTile( &ptr, i0, i0 + tileH, j0, j0 + tileW, maxZErrorInFile, maxValInImg) :
readCntTile(&ptr, i0, i0 + tileH, j0, j0 + tileW);
if (!rv)
return false;
}
}
return true;
}
// -------------------------------------------------------------------------- ;
bool CntZImage::readCntTile(Byte** ppByte, int i0, int i1, int j0, int j1)
{
Byte* ptr = *ppByte;
int numPixel = (i1 - i0) * (j1 - j0);
Byte comprFlag = *ptr++;
if (comprFlag == 2) // entire tile is constant 0 (invalid)
{ // here we depend on resizeFill0()
*ppByte = ptr;
return true;
}
if (comprFlag == 3 || comprFlag == 4) // entire tile is constant -1 (invalid) or 1 (valid)
{
CntZ cz1m = {-1, 0};
CntZ cz1p = { 1, 0};
CntZ cz1 = (comprFlag == 3) ? cz1m : cz1p;
for (int i = i0; i < i1; i++)
{
CntZ* dstPtr = getData() + i * width_ + j0;
for (int j = j0; j < j1; j++)
*dstPtr++ = cz1;
}
*ppByte = ptr;
return true;
}
if ((comprFlag & 63) > 4)
return false;
if (comprFlag == 0)
{
// read cnt's as flt arr uncompressed
const float* srcPtr = (const float*)ptr;
for (int i = i0; i < i1; i++)
{
CntZ* dstPtr = getData() + i * width_ + j0;
for (int j = j0; j < j1; j++)
{
dstPtr->cnt = *srcPtr++;
SWAP_4(dstPtr->cnt);
dstPtr++;
}
}
ptr += numPixel * sizeof(float);
}
else
{
// read cnt's as int arr bit stuffed
int bits67 = comprFlag >> 6;
int n = (bits67 == 0) ? 4 : 3 - bits67;
float offset = 0;
if (!readFlt(&ptr, offset, n))
return false;
vector<unsigned int>& dataVec = m_tmpDataVec;
BitStuffer bitStuffer;
if (!bitStuffer.read(&ptr, dataVec))
return false;
unsigned int* srcPtr = &dataVec[0];
for (int i = i0; i < i1; i++)
{
CntZ* dstPtr = getData() + i * width_ + j0;
for (int j = j0; j < j1; j++)
{
dstPtr->cnt = offset + (float)(*srcPtr++);
dstPtr++;
}
}
}
*ppByte = ptr;
return true;
}
// -------------------------------------------------------------------------- ;
bool CntZImage::readZTile(Byte** ppByte, int i0, int i1, int j0, int j1, double maxZErrorInFile, float maxZInImg)
{
Byte* ptr = *ppByte;
int numPixel = 0;
Byte comprFlag = *ptr++;
int bits67 = comprFlag >> 6;
comprFlag &= 63;
if (comprFlag == 2) // entire zTile is constant 0 (if valid or invalid doesn't matter)
{
for (int i = i0; i < i1; i++)
{
CntZ* dstPtr = getData() + i * width_ + j0;
for (int j = j0; j < j1; j++)
{
if (dstPtr->cnt > 0)
dstPtr->z = 0;
dstPtr++;
}
}
*ppByte = ptr;
return true;
}
if (comprFlag > 3)
return false;
if (comprFlag == 0)
{
// read z's as flt arr uncompressed
const float* srcPtr = (const float*)ptr;
for (int i = i0; i < i1; i++)
{
CntZ* dstPtr = getData() + i * width_ + j0;
for (int j = j0; j < j1; j++)
{
if (dstPtr->cnt > 0)
{
dstPtr->z = *srcPtr++;
SWAP_4(dstPtr->z);
numPixel++;
}
dstPtr++;
}
}
ptr += numPixel * sizeof(float);
}
else
{
// read z's as int arr bit stuffed
int n = (bits67 == 0) ? 4 : 3 - bits67;
float offset = 0;
if (!readFlt(&ptr, offset, n))
return false;
if (comprFlag == 3)
{
for (int i = i0; i < i1; i++)
{
CntZ* dstPtr = getData() + i * width_ + j0;
for (int j = j0; j < j1; j++)
{
if (dstPtr->cnt > 0)
dstPtr->z = offset;
dstPtr++;
}
}
}
else
{
vector<unsigned int>& dataVec = m_tmpDataVec;
BitStuffer bitStuffer;
if (!bitStuffer.read(&ptr, dataVec))
return false;
double invScale = 2 * maxZErrorInFile;
unsigned int* srcPtr = &dataVec[0];
if (m_bDecoderCanIgnoreMask)
{
for (int i = i0; i < i1; i++)
{
CntZ* dstPtr = getData() + i * width_ + j0;
for (int j = j0; j < j1; j++)
{
float z = (float)(offset + *srcPtr++ * invScale);
dstPtr->z = std::min(z, maxZInImg); // make sure we stay in the orig range
dstPtr++;
}
}
}
else
{
for (int i = i0; i < i1; i++)
{
CntZ* dstPtr = getData() + i * width_ + j0;
for (int j = j0; j < j1; j++)
{
if (dstPtr->cnt > 0)
{
float z = (float)(offset + *srcPtr++ * invScale);
dstPtr->z = std::min(z, maxZInImg); // make sure we stay in the orig range
}
dstPtr++;
}
}
}
}
}
*ppByte = ptr;
return true;
}
// -------------------------------------------------------------------------- ;
int CntZImage::numBytesFlt(float z)
{
short s = (short)z;
char c = (char)s;
return ((float)c == z) ? 1 : ((float)s == z) ? 2 : 4;
}
// -------------------------------------------------------------------------- ;
bool CntZImage::readFlt(Byte** ppByte, float& z, int numBytes)
{
Byte* ptr = *ppByte;
if (numBytes == 1)
{
char c = *((char*)ptr);
z = c;
}
else if (numBytes == 2)
{
short s;
memcpy(&s, ptr, sizeof(short));
SWAP_2(s);
z = s;
}
else if (numBytes == 4)
{
memcpy(&z, ptr, sizeof(float));
SWAP_4(z);
}
else
return false;
*ppByte = ptr + numBytes;
return true;
}
// -------------------------------------------------------------------------- ;
| 25.355319 | 114 | 0.492406 | [
"vector"
] |
d5f5dfef9a091d9d4b381d75da6e1cecb7546bfc | 4,631 | cxx | C++ | main.cxx | James-N-M/60-340-Genetic-Algorithm-Project | fecde260fe0c6beb52e0b4154b9d194e36ef2f4a | [
"MIT"
] | null | null | null | main.cxx | James-N-M/60-340-Genetic-Algorithm-Project | fecde260fe0c6beb52e0b4154b9d194e36ef2f4a | [
"MIT"
] | null | null | null | main.cxx | James-N-M/60-340-Genetic-Algorithm-Project | fecde260fe0c6beb52e0b4154b9d194e36ef2f4a | [
"MIT"
] | null | null | null | //------------------------------------------------------------------------------
//
// This program runs a genetic algorithm for computing task/machine
// schedules. It is mainly for testing the GA routine on subsequently
// larger and larger pool sizes to see how it compares when run
// serially vs multithreaded.
//
//------------------------------------------------------------------------------
#include "types.hxx"
#include "ga.hxx"
#include "program_options.hxx"
#include <random>
#include <chrono>
#include <iostream>
#include <thread>
//------------------------------------------------------------------------------
int main(int argc, char* argv[])
{
using namespace std;
// 1. Create an object of type cs340::program_options. Call it args.
// Pass into the constructor argc and argv as parameters.
//
// TODO: Read and examine the program_options.hxx header file.
// TODO: Read the documentation about Boost.ProgramOptions here:
// http://www.boost.org/doc/libs/1_63_0/doc/html/program_options.html
// TODO: The program options code has been provided to you. Notice
// how it simplifies processing command line arguments.
/* TODO: WRITE CODE HERE */
cs340::program_options args{argc, argv};
// 2. Set up the random number generator. Create an object of type
// std::seed_seq. Pass in as parameters an iterator pointing to the
// first element of args.seeds, and an iterator pointing to one
// past the end of the elements of args.seeds.
//
// Once done, create an object of type cs340::random_generator. Call it
// engine. Pass in your seed sequence as the only parameter to engine's
// unary constructor.
//
// TODO: Read about std::seed_seq in the course textbooks.
// TODO: Read about random numbers (e.g., <random>) in the course textbooks.
/* TODO: WRITE CODE HERE */
std::seed_seq seed(args.seeds.begin(), args.seeds.end());
cs340::random_generator engine(seed);
// 3. Create an object of type cs340::simulation_parameters. Call it
// params. Pass in as arguments (in this exact order) to the constructor:
//
// 1. The number of generations
// 2. The min pool size
// 3. The number of threads.
//
// See the program_options.hxx for the correct member variables of your
// args object.
/* TODO: WRITE CODE HERE */
cs340::simulation_parameters params{args.generations, args.min_pool_size, args.threads};
// 4. Create a matrix object by calling the function
// cs340::create_random_matrix. Pass in the correct parameters
// (see types.hxx and types.cxx) for the interface. Use the value
// 30 for the time_max parameter.
/* TODO: WRITE CODE HERE */
auto const matrix = cs340::create_random_matrix(args.tasks, args.machines, 30, engine);
cout << "Pool\tResult\tTime (s)\n";
for ( ;
params.pool_size <= args.max_pool_size;
params.pool_size += args.pool_size_step
)
{
// TODO: Read about <chrono> and related time facilities in your
// course textbooks.
// 5. Do the following, in order:
//
// a. Get the current CPU time. use std::chrono::high_resolution_clock.
//
// b. Call the function cs340::run_simulation. Check the header files
// to make sure you are passing the correct arguments! Store the
// return value of the function in a variable called result.
//
// c. Get the current CPU time the same way you did in step 5a.
//
// NOTE: Later you will be subtracting the values obtained in steps
// 5a and 5c to determine the total elapsed time of the
// simulation.
/* TODO: WRITE CODE HERE */
auto start = std::chrono::high_resolution_clock::now();
auto result = cs340::run_simulation(matrix, params, engine);
auto end = std::chrono::high_resolution_clock::now();
// 6. Output to standard out the following:
//
// i. params.pool_size
// 11. the score of the variable result
// iii. the number of seconds the simulation took to run.
//
// For (iii), first compute a variable of type chrono::duration<double>
// representing the difference between the stop time and the start time.
// Then call .count() on it to get the number of seconds it represents.
//
// Each field output should be separated by a tab character.
// The entire output should be flushed via std::endl.
/* TODO: WRITE CODE HERE */
std::chrono::duration<double> diff = end-start;
std::cout << params.pool_size << "\t" << result.score(matrix) << "\t" << diff.count() << std::endl;
}
}
//------------------------------------------------------------------------------
| 37.959016 | 102 | 0.637443 | [
"object"
] |
d5f60d0fee39983bda0b3b2897af509bd8795336 | 1,774 | cpp | C++ | Desen/main.cpp | rusucosmin/Cplusplus | 0e95cd01d20b22404aa4166c71d5a9e834a5a21b | [
"MIT"
] | 11 | 2015-08-29T13:41:22.000Z | 2020-01-08T20:34:06.000Z | Desen/main.cpp | rusucosmin/Cplusplus | 0e95cd01d20b22404aa4166c71d5a9e834a5a21b | [
"MIT"
] | null | null | null | Desen/main.cpp | rusucosmin/Cplusplus | 0e95cd01d20b22404aa4166c71d5a9e834a5a21b | [
"MIT"
] | 5 | 2016-01-20T18:17:01.000Z | 2019-10-30T11:57:15.000Z | #include <iostream>
#include <fstream>
#include <math.h>
#include <iomanip>
#include <vector>
#include <algorithm>
using namespace std;
ifstream fin("desen.in");
ofstream fout("desen.out");
const int maxn = 1005;
int n, father[maxn];
double dp[maxn][maxn];
vector <pair<int, int> > points;
inline double _dist(pair<int, int> a, pair<int, int> b) {
return sqrt((double)(a.first - b.first) * (a.first - b.first) + (double)(a.second - b.second) * (a.second - b.second));
}
inline int _find(int x) {
if(father[x] != x)
father[x] = _find(father[x]);
return father[x];
}
int main() {
fin >> n;
for(int i = 0 ; i < n ; ++ i) {
int x, y;
fin >> x >> y;
points.push_back(make_pair(x, y));
}
fout << fixed << setprecision(6);
for(int i = 0 ; i < n ; ++ i)
for(int j = 0 ; j < n ; ++ j)
dp[i][j] = dp[j][i] = _dist(points[i], points[j]);
fout << 0.0 << '\n' << dp[0][1] << '\n';
vector <pair<double, pair<int, int> > > apm;
apm.push_back(make_pair(dp[0][1], make_pair(0, 1)));
for(int i = 2 ; i < n ; ++ i) {
for(int j = 0 ; j < i ; ++ j)
apm.push_back(make_pair(dp[i][j], make_pair(i, j)));
sort(apm.begin(), apm.end());
vector <pair<double, pair<int, int> > > newapm;
for(int node = 0 ; node <= i ; ++ node)
father[node] = node;
double ans = 0;
for(int e = 0 ; e < apm.size() ; ++ e) {
int tx = _find(apm[e].second.first);
int ty = _find(apm[e].second.second);
if(tx == ty)
continue;
ans += apm[e].first;
father[tx] = ty;
newapm.push_back(apm[e]);
}
apm = newapm;
fout << ans << '\n';
}
}
| 28.15873 | 123 | 0.494927 | [
"vector"
] |
d5f8d78aabf55182af6b843a69e9ab8c3da3f867 | 588 | hpp | C++ | src/al_wrap/objects/al_Object.hpp | inobelar/al_wrap | 7643d6d5cf47bd23adb8342bbe62af7b69aabc94 | [
"MIT"
] | null | null | null | src/al_wrap/objects/al_Object.hpp | inobelar/al_wrap | 7643d6d5cf47bd23adb8342bbe62af7b69aabc94 | [
"MIT"
] | null | null | null | src/al_wrap/objects/al_Object.hpp | inobelar/al_wrap | 7643d6d5cf47bd23adb8342bbe62af7b69aabc94 | [
"MIT"
] | null | null | null | #pragma once
namespace al {
class Object
{
public:
using id_t = unsigned int; // Aka ALuint
protected:
id_t _id;
public:
Object();
virtual ~Object();
// -------------------------------------------------------------------------
// Moveable
Object(Object &&) = default;
Object& operator = (Object &&) = default;
// Non-copyable
Object(const Object &) = delete;
Object& operator = (const Object &) = delete;
// -------------------------------------------------------------------------
id_t getId() const;
};
} // namespace al
| 16.333333 | 80 | 0.428571 | [
"object"
] |
9101795ed033fa0b490648cdd9b0bc753d7aaa92 | 10,830 | cpp | C++ | Sources/Graphics/Renderer/WorldRenderer.cpp | carloshgsilva/VoxelEngine | 5ba308d3573805437124f32d407306776c1d66d6 | [
"MIT"
] | 1 | 2022-01-20T15:53:31.000Z | 2022-01-20T15:53:31.000Z | Sources/Graphics/Renderer/WorldRenderer.cpp | carloshgsilva/VoxelEngine | 5ba308d3573805437124f32d407306776c1d66d6 | [
"MIT"
] | null | null | null | Sources/Graphics/Renderer/WorldRenderer.cpp | carloshgsilva/VoxelEngine | 5ba308d3573805437124f32d407306776c1d66d6 | [
"MIT"
] | null | null | null | #include "WorldRenderer.h"
#include "World/World.h"
#include "World/Components.h"
#include "World/Systems/CameraSystem.h"
#include "World/Systems/ShadowVoxSystem.h"
#include "Core/Engine.h"
#include "Core/Input.h"
#include "Graphics/Graphics.h"
#include "Profiler/Profiler.h"
#include "GLFW/glfw3.h"
#include "Editor/Importer/AssetImporter.h"
#include "Graphics/Pipelines/GeometrySkyPipeline.h"
#include "Graphics/Pipelines/GeometryVoxelPipeline.h"
#include "Graphics/Pipelines/LightAmbientPipeline.h"
#include "Graphics/Pipelines/LightPointPipeline.h"
#include "Graphics/Pipelines/LightSpotPipeline.h"
#include "Graphics/Pipelines/LightTAAPipeline.h"
#include "Graphics/Pipelines/LightReflectionPipeline.h"
#include "Graphics/Pipelines/LightBloomStep.h"
#include "Graphics/Pipelines/LightBlur.h"
#include "Graphics/Pipelines/OutlineVoxelPipeline.h"
#include "Graphics/Pipelines/ComposePipeline.h"
#include "Graphics/Pipelines/ComposeTAAPipeline.h"
#include "Graphics/Pipelines/ColorWorldPipeline.h"
constexpr bool ENABLE_UPSAMPLING = false;
const int BLOOM_MIP_COUNT = 5;
//TimeStamp Points
const int TS_GBUFFER = 0;
const int TS_OUTLINE = 1;
const int TS_LIGHTS = 2;
const int TS_LIGHTS_TAA = 3;
const int TS_REFLECTION = 4;
const int TS_COMPOSE = 5;
const int TS_COMPOSE_TAA = 6;
const int TS_TOTAL = 7;
struct RenderCmds {
std::vector<OutlineVoxelPipeline::Cmd> outline;
std::vector<GeometryVoxelPipeline::Cmd> voxel;
void Clear() {
outline.clear();
voxel.clear();
}
};
WorldRenderer::WorldRenderer() {
//Create Initial Framebuffers
RecreateFramebuffer(320, 240); //Small Initial buffer allocation
Cmds = new RenderCmds();
_BlueNoise = Assets::Load("default/LDR_RGBA_0.png");
_DefaultSkyBox = Assets::Load("default/immenstadter_horn_4k.hdr");
_ViewBuffer = Buffer::Create(sizeof(ViewData), BufferUsage::Storage, MemoryType::CPU_TO_GPU);
}
void WorldRenderer::CmdOutline(const glm::mat4& matrix, Image& vox, glm::vec3 color) {
OutlineVoxelPipeline::Cmd c;
c.WorldMatrix = matrix;
c.VolumeRID = vox.getRID();
c.Color = color;
Cmds->outline.push_back(c);
}
void WorldRenderer::CmdVoxel(const glm::mat4& matrix, const glm::mat4& lastMatrix, Image& vox, int palleteIndex, int id) {
GeometryVoxelPipeline::Cmd c;
c.WorldMatrix = matrix;
c.LastWorldMatrix = lastMatrix;
c.VolumeRID = vox.getRID();
c.PalleteIndex = palleteIndex;
Cmds->voxel.push_back(c);
}
void WorldRenderer::RecreateFramebuffer(int32 Width, int32 Height) {
if (Width <= 1)Width = 1;
if (Height <= 1)Height = 1;
if (ENABLE_UPSAMPLING) {
Width /= 2;
Height /= 2;
}
_Bloom1Buffer.clear();
_Bloom2Buffer.clear();
//Geometry
_GeometryBuffer = Framebuffer::Create(Passes::Geometry(), Width, Height);
//Outline
_OutlineBuffer = Framebuffer::Create(Passes::Outline(), Width, Height);
//Light
_LastLightBuffer = Framebuffer::Create(Passes::Light(), Width, Height);
_CurrentLightBuffer = Framebuffer::Create(Passes::Light(), Width, Height);
_TAALightBuffer = Framebuffer::Create(Passes::Light(), Width, Height);
_ReflectionBuffer = Framebuffer::Create(Passes::Light(), Width, Height);
_BloomStepBuffer = Framebuffer::Create(Passes::Light(), Width >> 1, Height >> 1); // second mip
for (int i = 0; i < BLOOM_MIP_COUNT; i++) {
int mip = 2 + i; // third mip
int w = std::max(Width >> mip, 1);
int h = std::max(Height >> mip, 1);
_Bloom1Buffer.push_back(Framebuffer::Create(Passes::Light(), w, h));
_Bloom2Buffer.push_back(Framebuffer::Create(Passes::Light(), w, h));
}
if (ENABLE_UPSAMPLING) {
Width *= 2;
Height *= 2;
}
//Compose
_LastComposeBuffer = Framebuffer::Create(Passes::Color(), Width, Height);
_CurrentComposeBuffer = Framebuffer::Create(Passes::Color(), Width, Height);
_TAAComposeBuffer = Framebuffer::Create(Passes::Color(), Width, Height);
//Present
_ColorBuffer = Framebuffer::Create(Passes::Color(), Width, Height);
}
double lastReloadShaders = 0.0f;
void WorldRenderer::DrawWorld(DeltaTime dt, CmdBuffer& cmd, View& view, World& world) {
PROFILE_FUNC();
//////////////////
// Swap Buffers //
//////////////////
_LastLightBuffer.state.swap(_TAALightBuffer.state);
_LastComposeBuffer.state.swap(_TAAComposeBuffer.state);
// Crtl to reload shaders
if (Input::IsKeyPressed(Key::LeftControl) && (glfwGetTime()-lastReloadShaders) > 1.0) {
lastReloadShaders = glfwGetTime();
//TODO: It is a memory leak
GeometryVoxelPipeline::Get() = GeometryVoxelPipeline();
GeometrySkyPipeline::Get() = GeometrySkyPipeline();
OutlineVoxelPipeline::Get() = OutlineVoxelPipeline();
LightAmbientPipeline::Get() = LightAmbientPipeline();
LightPointPipeline::Get() = LightPointPipeline();
LightSpotPipeline::Get() = LightSpotPipeline();
LightTAAPipeline::Get() = LightTAAPipeline();
LightBloomStepPipeline::Get() = LightBloomStepPipeline();
LightBlurPipeline::Get() = LightBlurPipeline();
LightReflectionPipeline::Get() = LightReflectionPipeline();
ComposePipeline::Get() = ComposePipeline();
ComposeTAAPipeline::Get() = ComposeTAAPipeline();
ColorWorldPipeline::Get() = ColorWorldPipeline();
//Rest VoxSlot
world.GetRegistry().view<VoxRenderer>().each([](const entt::entity e, VoxRenderer& vr) {
vr.VoxSlot = -1;
});
}
////////////
// Render //
////////////
glm::vec2 OFFSETS[16] = {
glm::vec2(0.5000, 0.3333),
glm::vec2(0.2500, 0.6667),
glm::vec2(0.7500, 0.1111),
glm::vec2(0.1250, 0.4444),
glm::vec2(0.6250, 0.7778),
glm::vec2(0.3750, 0.2222),
glm::vec2(0.8750, 0.5556),
glm::vec2(0.0625, 0.8889),
glm::vec2(0.5625, 0.0370),
glm::vec2(0.3125, 0.3704),
glm::vec2(0.8125, 0.7037),
glm::vec2(0.1875, 0.1481),
glm::vec2(0.6875, 0.4815),
glm::vec2(0.4375, 0.8148),
glm::vec2(0.9375, 0.2593),
glm::vec2(0.0313, 0.5926)
};
ViewData viewData;
{
viewData.LastViewMatrix = _LastView.ViewMatrix;
viewData.ViewMatrix = view.ViewMatrix;
viewData.InverseViewMatrix = glm::inverse(view.ViewMatrix);
viewData.ProjectionMatrix = view.ProjectionMatrix;
viewData.InverseProjectionMatrix = glm::inverse(view.ProjectionMatrix);
viewData.Res = glm::vec2(view.Width, view.Height) * (ENABLE_UPSAMPLING ? 0.5f : 1.0f);
viewData.iRes = 1.0f / viewData.Res;
viewData.CameraPosition = view.Position;
viewData.Jitter = OFFSETS[_Frame%16];
viewData.Frame = _Frame;
viewData.ColorTextureRID = _GeometryBuffer.getAttachment(Passes::Geometry_Color).getRID();
viewData.DepthTextureRID = _GeometryBuffer.getAttachment(Passes::Geometry_Depth).getRID();
viewData.PalleteColorRID = PalleteCache::GetColorTexture().getRID();
viewData.PalleteMaterialRID = PalleteCache::GetMaterialTexture().getRID();
_ViewBuffer.update(&viewData, sizeof(ViewData));
}
//Build Voxel Cmds
{
PROFILE_SCOPE("Build Voxel Cmds");
world.GetRegistry().group<VoxRenderer>(entt::get_t<Transform>()).each([&](const entt::entity e, VoxRenderer& v, Transform& t) {
if (v.Vox.IsValid() && v.Pallete.IsValid()) {
glm::mat4 mat = t.WorldMatrix;
mat = glm::translate(mat, -v.Pivot);
glm::mat4 last_mat = t.PreviousWorldMatrix;
last_mat = glm::translate(last_mat, -v.Pivot);
CmdVoxel(mat, last_mat, v.Vox->GetImage(), v.Pallete->GetPalleteIndex());
}
});
}
cmd.timestamp("GBuffer", [&] {
//G-Buffer
cmd.use(_GeometryBuffer, [&] {
GeometrySkyPipeline::Get().Use(cmd, _ViewBuffer, viewData.Res);
GeometryVoxelPipeline::Get().Use(cmd, _ViewBuffer, viewData.Res, _BlueNoise->GetImage(), Cmds->voxel);
});
});
cmd.timestamp("Outline", [&] {
//Outline
cmd.use(_OutlineBuffer, [&] {
OutlineVoxelPipeline::Get().Use(cmd, _ViewBuffer, _GeometryBuffer, Cmds->outline);
});
});
cmd.timestamp("Lights", [&] {
//Lights
cmd.use(_CurrentLightBuffer, [&] {
LightAmbientPipeline::Get().Use(cmd, _ViewBuffer, _GeometryBuffer, world.ShadowVox->GetVolumeImage(), _BlueNoise->GetImage(), _DefaultSkyBox->GetSkyBox());
LightPointPipeline::Get().Use(cmd, _ViewBuffer, _GeometryBuffer, world.ShadowVox->GetVolumeImage(), _BlueNoise->GetImage(), _Frame, [&](LightPointPipeline& P) {
world.GetRegistry().view<const Transform, const Light>().each([&](const entt::entity e, const Transform& t, const Light& l) {
PROFILE_SCOPE("DrawPointLight()");
if (l.LightType == Light::Type::Point) {
P.DrawLight(t.WorldMatrix[3], l.Range, l.Color * l.Intensity, l.Attenuation);
}
});
});
LightSpotPipeline::Get().Use(cmd, _ViewBuffer, _GeometryBuffer, world.ShadowVox->GetVolumeImage(), _BlueNoise->GetImage(), _Frame, [&](LightSpotPipeline& P) {
world.GetRegistry().view<const Transform, const Light>().each([&](const entt::entity e, const Transform& t, const Light& l) {
PROFILE_SCOPE("DrawSpotLight()");
if (l.LightType == Light::Type::Spot) {
P.DrawLight(t.WorldMatrix[3], l.Range, l.Color * l.Intensity, l.Attenuation, t.WorldMatrix[2], l.Angle, l.AngleAttenuation);
}
});
});
});
});
cmd.timestamp("LightTAA", [&] {
//Light TAA
cmd.use(_TAALightBuffer, [&] {
LightTAAPipeline::Get().Use(cmd, _ViewBuffer, _BlueNoise->GetImage(), _LastLightBuffer, _CurrentLightBuffer, _GeometryBuffer);
});
});
cmd.timestamp("Reflection", [&] {
//Reflection
cmd.use(_ReflectionBuffer, [&] {
LightReflectionPipeline::Get().Use(cmd, _ViewBuffer, _TAALightBuffer.getAttachment(0), _GeometryBuffer, world.ShadowVox->GetVolumeImage(), _DefaultSkyBox->GetSkyBox(), _BlueNoise->GetImage());
});
});
cmd.timestamp("Bloom", [&] {
cmd.use(_BloomStepBuffer, [&] {
LightBloomStepPipeline::Get().Use(cmd, _CurrentLightBuffer.getAttachment(0));
});
for (int i = 0; i < BLOOM_MIP_COUNT; i++) {
cmd.use(_Bloom1Buffer[i], [&] {
LightBlurPipeline::Get().Use(cmd, (i == 0 ? _BloomStepBuffer : _Bloom2Buffer[i-1]).getAttachment(0), true); // use the step for the first input
});
cmd.use(_Bloom2Buffer[i], [&] {
LightBlurPipeline::Get().Use(cmd, _Bloom1Buffer[i].getAttachment(0), false);
});
}
});
cmd.timestamp("Compose", [&] {
//Compose
cmd.use(_CurrentComposeBuffer, [&] {
ComposePipeline::Get().Use(cmd, _ViewBuffer, _GeometryBuffer, _TAALightBuffer, _ReflectionBuffer, _Bloom2Buffer);
});
});
cmd.timestamp("ComposeTAA", [&] {
//Compose TAA
cmd.use(_TAAComposeBuffer, [&] {
ComposeTAAPipeline::Get().Use(cmd, _ViewBuffer, _LastComposeBuffer, _CurrentComposeBuffer, _GeometryBuffer);
});
});
cmd.timestamp("Color", [&] {
//Color (final world color)
cmd.use(_ColorBuffer, [&] {
ColorWorldPipeline::Get().Use(cmd, _TAAComposeBuffer.getAttachment(0), _OutlineBuffer);
//ColorWorldPipeline::Get().Use(cmd, _GeometryBuffer.getAttachment(Passes::Geometry_Color), _OutlineBuffer);
});
});
_LastView = view;
_Frame++;
if (_Frame > 16 * 100)_Frame = 0;
Cmds->Clear();
}
Image& WorldRenderer::GetCurrentColorImage() {
return _ColorBuffer.getAttachment(0);
}
| 33.738318 | 195 | 0.705263 | [
"geometry",
"render",
"vector",
"transform"
] |
9107f8b3d6f335e58c6e27309815733c5f9354c6 | 3,872 | cpp | C++ | src/pipeline_factory.cpp | wxthss82/openvino_model_server | 93541522d301163a130751e4b4d3d9c40d869f2b | [
"Apache-2.0"
] | null | null | null | src/pipeline_factory.cpp | wxthss82/openvino_model_server | 93541522d301163a130751e4b4d3d9c40d869f2b | [
"Apache-2.0"
] | null | null | null | src/pipeline_factory.cpp | wxthss82/openvino_model_server | 93541522d301163a130751e4b4d3d9c40d869f2b | [
"Apache-2.0"
] | null | null | null | //*****************************************************************************
// Copyright 2020 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
#include "pipeline_factory.hpp"
#include "logging.hpp"
#include "prediction_service_utils.hpp"
namespace ovms {
Status PipelineFactory::createDefinition(const std::string& pipelineName,
const std::vector<NodeInfo>& nodeInfos,
const pipeline_connections_t& connections,
ModelManager& manager) {
if (definitionExists(pipelineName)) {
SPDLOG_LOGGER_WARN(modelmanager_logger, "Two pipelines with the same name: {} defined in config file. Ignoring the second definition", pipelineName);
return StatusCode::PIPELINE_DEFINITION_ALREADY_EXIST;
}
std::unique_ptr<PipelineDefinition> pipelineDefinition = std::make_unique<PipelineDefinition>(pipelineName, nodeInfos, connections);
pipelineDefinition->makeSubscriptions(manager);
Status validationResult = pipelineDefinition->validate(manager);
if (!validationResult.ok()) {
pipelineDefinition->resetSubscriptions(manager);
SPDLOG_LOGGER_ERROR(modelmanager_logger, "Loading pipeline definition: {} failed: {}", pipelineName, validationResult.string());
return validationResult;
}
std::unique_lock lock(definitionsMtx);
definitions[pipelineName] = std::move(pipelineDefinition);
SPDLOG_LOGGER_INFO(modelmanager_logger, "Loading pipeline definition: {} succeeded", pipelineName);
return StatusCode::OK;
}
Status PipelineFactory::create(std::unique_ptr<Pipeline>& pipeline,
const std::string& name,
const tensorflow::serving::PredictRequest* request,
tensorflow::serving::PredictResponse* response,
ModelManager& manager) const {
if (!definitionExists(name)) {
SPDLOG_LOGGER_INFO(dag_executor_logger, "Pipeline with requested name: {} does not exist", name);
return StatusCode::PIPELINE_DEFINITION_NAME_MISSING;
}
std::shared_lock lock(definitionsMtx);
auto& definition = *definitions.at(name);
lock.unlock();
return definition.create(pipeline, request, response, manager);
}
Status PipelineFactory::reloadDefinition(const std::string& pipelineName,
const std::vector<NodeInfo>&& nodeInfos,
const pipeline_connections_t&& connections,
ModelManager& manager) {
auto pd = findDefinitionByName(pipelineName);
if (pd == nullptr) {
SPDLOG_LOGGER_ERROR(modelmanager_logger, "Requested to reload pipeline definition but it does not exist: {}", pipelineName);
return StatusCode::UNKNOWN_ERROR;
}
return pd->reload(manager, std::move(nodeInfos), std::move(connections));
}
void PipelineFactory::revalidatePipelines(ModelManager& manager) {
for (auto& [name, definition] : definitions) {
if (definition->getStatus().isRevalidationRequired()) {
auto validationResult = definition->validate(manager);
if (!validationResult.ok()) {
SPDLOG_LOGGER_ERROR(modelmanager_logger, "Revalidation pipeline definition: {} failed: {}", name, validationResult.string());
} else {
SPDLOG_LOGGER_DEBUG(modelmanager_logger, "Revalidation of pipeline: {} succeeded", name);
}
}
}
}
} // namespace ovms
| 44 | 157 | 0.695506 | [
"vector"
] |
51051ee46a575802e37c91f74332d9be21f9dad6 | 3,492 | cc | C++ | tce/src/applibs/ImplementationTester/ImplementationSimulator.cc | kanishkan/tce | 430e764b4d43f46bd1dc754aeb1d5632fc742110 | [
"MIT"
] | 74 | 2015-10-22T15:34:10.000Z | 2022-03-25T07:57:23.000Z | tce/src/applibs/ImplementationTester/ImplementationSimulator.cc | kanishkan/tce | 430e764b4d43f46bd1dc754aeb1d5632fc742110 | [
"MIT"
] | 79 | 2015-11-19T09:23:08.000Z | 2022-01-12T14:15:16.000Z | tce/src/applibs/ImplementationTester/ImplementationSimulator.cc | kanishkan/tce | 430e764b4d43f46bd1dc754aeb1d5632fc742110 | [
"MIT"
] | 38 | 2015-11-17T10:12:23.000Z | 2022-03-25T07:57:24.000Z | /*
Copyright (c) 2002-2010 Tampere University.
This file is part of TTA-Based Codesign Environment (TCE).
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 ImplementationSimulator.cc
*
* Implementation of ImplementationSimulator
*
* @author Otto Esko 2010 (otto.esko-no.spam-tut.fi)
* @note rating: red
*/
#include <string>
#include <vector>
#include "ImplementationSimulator.hh"
#include "FileSystem.hh"
using std::string;
using std::vector;
ImplementationSimulator::ImplementationSimulator(
std::string tbFile,
std::vector<std::string> hdlFiles,
bool verbose,
bool leaveDirty):
tbFile_(tbFile),
hdlFiles_(hdlFiles), baseDir_(""), workDir_(""), oldCwd_(""),
verbose_(verbose), leaveDirty_(leaveDirty) {
baseDir_ = FileSystem::directoryOfPath(tbFile);
oldCwd_ = FileSystem::currentWorkingDir();
}
ImplementationSimulator::~ImplementationSimulator() {
if (!workDir_.empty() && FileSystem::fileExists(workDir_)) {
if (!leaveDirty_) {
FileSystem::removeFileOrDirectory(workDir_);
}
}
if (!oldCwd_.empty()) {
FileSystem::changeWorkingDir(oldCwd_);
}
}
std::string ImplementationSimulator::createWorkDir() {
string work = baseDir_ + FileSystem::DIRECTORY_SEPARATOR + "work";
if (!FileSystem::createDirectory(work)) {
work = "";
}
workDir_ = work;
return workDir_;
}
void ImplementationSimulator::setWorkDir(std::string dir) {
workDir_ = dir;
}
std::string ImplementationSimulator::workDir() const {
return workDir_;
}
std::string ImplementationSimulator::tbDirectory() const {
return baseDir_;
}
std::string ImplementationSimulator::tbFile() const {
return tbFile_;
}
int ImplementationSimulator::hdlFileCount() const {
return hdlFiles_.size();
}
std::string ImplementationSimulator::file(int index) const {
return hdlFiles_.at(index);
}
bool ImplementationSimulator::verbose() {
return verbose_;
}
void
ImplementationSimulator::parseErrorMessages(
std::vector<std::string>& inputMsg, std::vector<std::string>& errors) {
string tag = "TCE Assert";
for (unsigned int i = 0; i < inputMsg.size(); i++) {
string::size_type loc = inputMsg.at(i).find(tag, 0);
if (loc != string::npos) {
string errorMsg = FileSystem::fileOfPath(tbFile_) + ": "
+ inputMsg.at(i);
errors.push_back(errorMsg);
}
}
}
| 30.103448 | 78 | 0.697595 | [
"vector"
] |
5105c78f27d8759071e827831bde53d931f96aa0 | 14,548 | cc | C++ | DAQ/src/StrawAndCaloDigisFromFragments_module.cc | bonventre/Offline | 77db9d6368f27ab9401c690c2c2a4257ade6c231 | [
"Apache-2.0"
] | null | null | null | DAQ/src/StrawAndCaloDigisFromFragments_module.cc | bonventre/Offline | 77db9d6368f27ab9401c690c2c2a4257ade6c231 | [
"Apache-2.0"
] | 1 | 2019-11-22T14:45:51.000Z | 2019-11-22T14:50:03.000Z | DAQ/src/StrawAndCaloDigisFromFragments_module.cc | bonventre/Offline | 77db9d6368f27ab9401c690c2c2a4257ade6c231 | [
"Apache-2.0"
] | 2 | 2019-10-14T17:46:58.000Z | 2020-03-30T21:05:15.000Z | // ======================================================================
//
// StrawAndCaloDigisFromFragments_plugin: Add tracker/cal data products to the event
//
// ======================================================================
#include "art/Framework/Core/EDProducer.h"
#include "art/Framework/Principal/Event.h"
#include "art/Framework/Core/ModuleMacros.h"
#include "art/Framework/Services/Registry/ServiceHandle.h"
#include "fhiclcpp/ParameterSet.h"
#include "art/Framework/Principal/Handle.h"
#include "mu2e-artdaq-core/Overlays/ArtFragmentReader.hh"
#include <artdaq-core/Data/Fragment.hh>
#include "DataProducts/inc/TrkTypes.hh"
#include "RecoDataProducts/inc/StrawDigiCollection.hh"
#include "RecoDataProducts/inc/CaloDigiCollection.hh"
#include <iostream>
#include <string>
#include <memory>
namespace art {
class StrawAndCaloDigisFromFragments;
}
using art::StrawAndCaloDigisFromFragments;
// ======================================================================
class art::StrawAndCaloDigisFromFragments
: public EDProducer
{
public:
using EventNumber_t = art::EventNumber_t;
using adc_t = mu2e::ArtFragmentReader::adc_t;
// --- C'tor/d'tor:
explicit StrawAndCaloDigisFromFragments(fhicl::ParameterSet const& pset);
virtual ~StrawAndCaloDigisFromFragments() { }
// --- Production:
virtual void produce( Event & );
private:
int diagLevel_;
int parseCAL_;
int parseTRK_;
art::InputTag trkFragmentsTag_;
art::InputTag caloFragmentsTag_;
}; // StrawAndCaloDigisFromFragments
// ======================================================================
StrawAndCaloDigisFromFragments::StrawAndCaloDigisFromFragments(fhicl::ParameterSet const& pset)
: EDProducer(pset)
, diagLevel_(pset.get<int>("diagLevel",0))
, parseCAL_(pset.get<int>("parseCAL",1))
, parseTRK_(pset.get<int>("parseTRK",1))
, trkFragmentsTag_(pset.get<art::InputTag>("trkTag","daq:trk"))
, caloFragmentsTag_(pset.get<art::InputTag>("caloTag","daq:calo"))
{
produces<EventNumber_t>();
produces<mu2e::StrawDigiCollection>();
produces<mu2e::CaloDigiCollection>();
}
// ----------------------------------------------------------------------
void
StrawAndCaloDigisFromFragments::
produce( Event & event )
{
art::EventNumber_t eventNumber = event.event();
auto trkFragments = event.getValidHandle<artdaq::Fragments>(trkFragmentsTag_);
auto calFragments = event.getValidHandle<artdaq::Fragments>(caloFragmentsTag_);
size_t numTrkFrags = trkFragments->size();
size_t numCalFrags = calFragments->size();
if( diagLevel_ > 1 ) {
std::cout << std::dec << "Producer: Run " << event.run() << ", subrun " << event.subRun()
<< ", event " << eventNumber << " has " << std::endl;
std::cout << trkFragments->size() << " TRK fragments, and ";
std::cout << calFragments->size() << " CAL fragments." << std::endl;
size_t totalSize = 0;
for(size_t idx = 0; idx < trkFragments->size(); ++idx) {
auto size = ((*trkFragments)[idx]).size() * sizeof(artdaq::RawDataType);
totalSize += size;
// std::cout << "\tTRK Fragment " << idx << " has size " << size << std::endl;
}
for(size_t idx = 0; idx < calFragments->size(); ++idx) {
auto size = ((*calFragments)[idx]).size() * sizeof(artdaq::RawDataType);
totalSize += size;
// std::cout << "\tCAL Fragment " << idx << " has size " << size << std::endl;
}
std::cout << "\tTotal Size: " << (int)totalSize << " bytes." << std::endl;
}
// Collection of StrawDigis for the event
std::unique_ptr<mu2e::StrawDigiCollection> straw_digis(new mu2e::StrawDigiCollection);
// Collection of CaloDigis for the event
std::unique_ptr<mu2e::CaloDigiCollection> calo_digis(new mu2e::CaloDigiCollection);
std::string curMode = "TRK";
// Loop over the TRK and CAL fragments
for (size_t idx = 0; idx < numTrkFrags+numCalFrags; ++idx) {
auto curHandle = trkFragments;
size_t curIdx = idx;
if(idx>=numTrkFrags) {
curIdx = idx-numTrkFrags;
curHandle = calFragments;
}
const auto& fragment((*curHandle)[curIdx]);
mu2e::ArtFragmentReader cc(fragment);
if( diagLevel_ > 1 ) {
std::cout << std::endl;
std::cout << "ArtFragmentReader: ";
std::cout << "\tBlock Count: " << std::dec << cc.block_count() << std::endl;
std::cout << "\tByte Count: " << cc.byte_count() << std::endl;
std::cout << std::endl;
std::cout << "\t" << "====== Example Block Sizes ======" << std::endl;
for(size_t i=0; i<10; i++) {
if(i <cc.block_count()) {
std::cout << "\t" << i << "\t" << cc.blockIndexBytes(i) << "\t" << cc.blockSizeBytes(i) << std::endl;
}
}
std::cout << "\t" << "=========================" << std::endl;
}
std::string mode_;
for(size_t curBlockIdx=0; curBlockIdx<cc.block_count(); curBlockIdx++) {
size_t blockStartBytes = cc.blockIndexBytes(curBlockIdx);
size_t blockEndBytes = cc.blockEndBytes(curBlockIdx);
if( diagLevel_ > 1 ) {
std::cout << "BLOCKSTARTEND: " << blockStartBytes << " " << blockEndBytes << " " << cc.blockSizeBytes(curBlockIdx)<< std::endl;
std::cout << "IndexComparison: " << cc.blockIndexBytes(0)+16*(0+3*curBlockIdx) << "\t";
std::cout << cc.blockIndexBytes(curBlockIdx)+16*(0+3*0) << std::endl;
}
adc_t const *pos = reinterpret_cast<adc_t const *>(cc.dataAtBytes(blockStartBytes));
if( diagLevel_ > 1 ) {
// Print binary contents the first 3 packets starting at the current position
// In the case of the tracker simulation, this will be the whole tracker
// DataBlock. In the case of the calorimeter, the number of data packets
// following the header packet is variable.
cc.printPacketAtByte(cc.blockIndexBytes(0)+16*(0+3*curBlockIdx));
cc.printPacketAtByte(cc.blockIndexBytes(0)+16*(1+3*curBlockIdx));
cc.printPacketAtByte(cc.blockIndexBytes(0)+16*(2+3*curBlockIdx));
// Print out decimal values of 16 bit chunks of packet data
for(int i=7; i>=0; i--) {
std::cout << (adc_t) *(pos+i);
std::cout << " ";
}
std::cout << std::endl;
}
adc_t rocID = cc.DBH_ROCID(pos);
adc_t valid = cc.DBH_Valid(pos);
adc_t packetCount = cc.DBH_PacketCount(pos);
uint32_t timestampLow = cc.DBH_TimestampLow(pos);
uint32_t timestampMedium = cc.DBH_TimestampMedium(pos);
size_t timestamp = timestampLow | (timestampMedium<<16);
adc_t EVBMode = cc.DBH_EVBMode(pos);
adc_t sysID = cc.DBH_SubsystemID(pos);
adc_t dtcID = cc.DBH_DTCID(pos);
eventNumber = timestamp;
if(sysID==0) {
mode_ = "TRK";
} else if(sysID==1) {
mode_ = "CAL";
}
// Parse phyiscs information from TRK packets
if(mode_ == "TRK" && packetCount>0 && parseTRK_>0) {
// Create the StrawDigi data products
mu2e::StrawId sid(cc.DBT_StrawIndex(pos));
mu2e::TrkTypes::TDCValues tdc = {cc.DBT_TDC0(pos) , cc.DBT_TDC1(pos)};
mu2e::TrkTypes::TOTValues tot = {cc.DBT_TOT0(pos) , cc.DBT_TOT1(pos)};
// ///////////////////////////////////////////////////////////////////////////
// // NOTE: Because the tracker code in offline has not been updated to
// // use 15 samples, it is necessary to add an extra sample in order to
// // initialize an ADCWaveform that can be passed to the StrawDigi
// // constructor. This means that the digis produced by StrawAndCaloDigisFromFragments
// // will differ from those processed in offline so the filter performance
// // will be different. This is only temporary.
// std::array<adc_t,15> const & shortWaveform = cc.DBT_Waveform(pos);
// mu2e::TrkTypes::ADCWaveform wf;
// for(size_t i=0; i<15; i++) {
// wf[i] = shortWaveform[i];
// }
// wf[15] = 0;
// ///////////////////////////////////////////////////////////////////////////
mu2e::TrkTypes::ADCWaveform wf = cc.DBT_Waveform(pos);
adc_t flags = cc.DBT_Flags(pos);
// Fill the StrawDigiCollection
straw_digis->emplace_back(sid, tdc, tot, wf);
if( diagLevel_ > 1 ) {
std::cout << "MAKEDIGI: " << sid.asUint16() << " " << tdc[0] << " " << tdc[1] << " "
<< tot[0] << " " << tot[1] << " ";
for(size_t i=0; i<mu2e::TrkTypes::NADC; i++) {
std::cout << wf[i];
if(i<mu2e::TrkTypes::NADC-1) {
std::cout << " ";
}
}
std::cout << std::endl;
std::cout << "timestamp: " << timestamp << std::endl;
std::cout << "sysID: " << sysID << std::endl;
std::cout << "dtcID: " << dtcID << std::endl;
std::cout << "rocID: " << rocID << std::endl;
std::cout << "packetCount: " << packetCount << std::endl;
std::cout << "valid: " << valid << std::endl;
std::cout << "EVB mode: " << EVBMode << std::endl;
for(int i=7; i>=0; i--) {
std::cout << (adc_t) *(pos+8+i);
std::cout << " ";
}
std::cout << std::endl;
for(int i=7; i>=0; i--) {
std::cout << (adc_t) *(pos+8*2+i);
std::cout << " ";
}
std::cout << std::endl;
std::cout << "strawIdx: " << sid.asUint16() << std::endl;
std::cout << "TDC0: " << tdc[0] << std::endl;
std::cout << "TDC1: " << tdc[1] << std::endl;
std::cout << "TOT0: " << tot[0] << std::endl;
std::cout << "TOT1: " << tot[1] << std::endl;
std::cout << "Waveform: {";
for(size_t i=0; i<mu2e::TrkTypes::NADC; i++) {
std::cout << wf[i];
if(i<mu2e::TrkTypes::NADC-1) {
std::cout << ",";
}
}
std::cout << "}" << std::endl;
std::cout << "FPGA Flags: ";
for(size_t i=8; i<16; i++) {
if( ((0x0001<<(15-i)) & flags) > 0) {
std::cout << "1";
} else {
std::cout << "0";
}
}
std::cout << std::endl;
std::cout << "LOOP: " << eventNumber << " " << curBlockIdx << " " << "(" << timestamp << ")" << std::endl;
// Text format: timestamp strawidx tdc0 tdc1 nsamples sample0-11
// Example: 1 1113 36978 36829 12 1423 1390 1411 1354 2373 2392 2342 2254 1909 1611 1525 1438
std::cout << "GREPMETRK: " << timestamp << " ";
std::cout << sid.asUint16() << " ";
std::cout << tdc[0] << " ";
std::cout << tdc[1] << " ";
std::cout << tot[0] << " ";
std::cout << tot[1] << " ";
std::cout << wf.size() << " ";
for(size_t i=0; i<mu2e::TrkTypes::NADC; i++) {
std::cout << wf[i];
if(i<mu2e::TrkTypes::NADC-1) {
std::cout << " ";
}
}
std::cout << std::endl;
} // End debug output
} else if(mode_ == "CAL" && packetCount>0 && parseCAL_>0) { // Parse phyiscs information from CAL packets
for(size_t hitIdx = 0; hitIdx<cc.DBC_NumHits(pos); hitIdx++) {
// Fill the CaloDigiCollection
std::vector<int> cwf = cc.DBC_Waveform(pos,hitIdx);
// IMPORTANT NOTE: As described in CaloPacketProducer_module.cc, we don't have a final
// mapping yet so for the moment, the BoardID field (described in docdb 4914) is just a
// placeholder. Because we still need to know which crystal a hit belongs to, we are
// temporarily storing the 4-bit apdID and 12-bit crystalID in the Reserved DIRAC A slot.
// Also, note that until we have an actual map, channel index does not actually correspond
// to the physical readout channel on a ROC.
calo_digis->emplace_back(
((cc.DBC_DIRACOutputB(pos,hitIdx) & 0x0FFF)*2 +
(cc.DBC_DIRACOutputB(pos,hitIdx)>>12)),
cc.DBC_Time(pos,hitIdx),
cwf
);
if( diagLevel_ > 1 ) {
// Until we have the final mapping, the BoardID is just a placeholder
// adc_t BoardId = cc.DBC_BoardID(pos,channelIdx);
// As noted above, until we have the final mapping, the crystal ID and apdID
// will be temporarily stored in the Reserved DIRAC A slot.
adc_t crystalID = cc.DBC_DIRACOutputB(pos,hitIdx) & 0x0FFF;
adc_t apdID = cc.DBC_DIRACOutputB(pos,hitIdx) >> 12;
adc_t time = cc.DBC_Time(pos,hitIdx);
adc_t numSamples = cc.DBC_NumSamples(pos,hitIdx);
//adc_t peakIdx = cc.DBC_PeakSampleIdx(pos,hitIdx);
std::cout << "timestamp: " << timestamp << std::endl;
std::cout << "sysID: " << sysID << std::endl;
std::cout << "dtcID: " << dtcID << std::endl;
std::cout << "rocID: " << rocID << std::endl;
std::cout << "packetCount: " << packetCount << std::endl;
std::cout << "valid: " << valid << std::endl;
std::cout << "EVB mode: " << EVBMode << std::endl;
for(int i=7; i>=0; i--) {
std::cout << (adc_t) *(pos+8+i);
std::cout << " ";
}
std::cout << std::endl;
for(int i=7; i>=0; i--) {
std::cout << (adc_t) *(pos+8*2+i);
std::cout << " ";
}
std::cout << std::endl;
std::cout << "Crystal ID: " << crystalID << std::endl;
std::cout << "APD ID: " << apdID << std::endl;
std::cout << "Time: " << time << std::endl;
std::cout << "NumSamples: " << numSamples << std::endl;
std::cout << "Waveform: {";
for(size_t i=0; i<cwf.size(); i++) {
std::cout << cwf[i];
if(i<cwf.size()-1) {
std::cout << ",";
}
}
std::cout << "}" << std::endl;
// Text format: timestamp crystalID roID time nsamples samples...
// Example: 1 201 402 660 18 0 0 0 0 1 17 51 81 91 83 68 60 58 52 42 33 23 16
std::cout << "GREPMECAL: " << timestamp << " ";
std::cout << crystalID << " ";
std::cout << apdID << " ";
std::cout << time << " ";
std::cout << cwf.size() << " ";
for(size_t i=0; i<cwf.size(); i++) {
std::cout << cwf[i];
if(i<cwf.size()-1) {
std::cout << " ";
}
}
std::cout << std::endl;
} // End debug output
} // End loop over readout channels in DataBlock
} // End Cal Mode
} // End loop over DataBlocks within fragment
} // Close loop over fragments
// } // Close loop over the TRK and CAL collections
if( diagLevel_ > 0 ) {
std::cout << "mu2e::StrawAndCaloDigisFromFragments::produce exiting eventNumber=" << (int)(event.event()) << " / timestamp=" << (int)eventNumber <<std::endl;
}
event.put(std::unique_ptr<EventNumber_t>(new EventNumber_t( eventNumber )));
// Store the straw digis and calo digis in the event
event.put(std::move(straw_digis));
event.put(std::move(calo_digis));
} // produce()
// ======================================================================
DEFINE_ART_MODULE(StrawAndCaloDigisFromFragments)
// ======================================================================
| 34.803828 | 161 | 0.571213 | [
"vector"
] |
510ed889ecd0862ddf3d8564fa7c6747030d2851 | 299 | cpp | C++ | source/GLRenderer/materials/ClipspaceWireframeMaterial.cpp | GPUPeople/cuRE | ccba6a29bba4445300cbb630befe57e31f0d80cb | [
"MIT"
] | 55 | 2018-07-11T23:40:06.000Z | 2022-03-18T05:34:44.000Z | source/GLRenderer/materials/ClipspaceWireframeMaterial.cpp | GPUPeople/cuRE | ccba6a29bba4445300cbb630befe57e31f0d80cb | [
"MIT"
] | 1 | 2018-09-10T09:57:47.000Z | 2018-09-10T09:57:47.000Z | source/GLRenderer/materials/ClipspaceWireframeMaterial.cpp | GPUPeople/cuRE | ccba6a29bba4445300cbb630befe57e31f0d80cb | [
"MIT"
] | 13 | 2018-08-16T17:00:36.000Z | 2022-01-17T08:33:57.000Z |
#include "GLRenderer/shaders/ClipspaceShader.h"
#include "ClipspaceMaterial.h"
namespace GLRenderer
{
ClipspaceMaterial::ClipspaceMaterial(const ClipspaceShader& shader)
: shader(shader)
{
}
void ClipspaceMaterial::draw(const ::Geometry* geometry) const
{
shader.draw(geometry);
}
}
| 14.95 | 68 | 0.752508 | [
"geometry"
] |
5110758001fb9f88de1c8e23b3637ff9e7f4f89d | 2,337 | cpp | C++ | testbrevno.cpp | phma/mitobrevno | 30526eac54d0d619abd165b803b143347f4ade9d | [
"Apache-2.0"
] | null | null | null | testbrevno.cpp | phma/mitobrevno | 30526eac54d0d619abd165b803b143347f4ade9d | [
"Apache-2.0"
] | null | null | null | testbrevno.cpp | phma/mitobrevno | 30526eac54d0d619abd165b803b143347f4ade9d | [
"Apache-2.0"
] | null | null | null | /******************************************************/
/* */
/* testbrevno.cpp - main program for testing */
/* */
/******************************************************/
/* Copyright 2020 Pierre Abbat.
* This file is part of Mitobrevno.
*
* 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 <iostream>
#include <fstream>
#include "mitobrevno.h"
#include "roundup.h"
#include "itree.h"
#define tassert(x) testfail|=(!(x))
using namespace std;
bool testfail=false;
vector<string> args;
void testroundUp()
{
array<unsigned long,2> result;
result=roundUp(342739564245);
cout<<result[1]<<"×"<<result[0]<<'='<<result[0]*result[1]<<endl;
}
void testitree()
{
int n,i,j,s;
int count[4];
IntervalTree itree0(0,987);
Interval iv;
for (i=0;i<4;i++)
count[i]=0;
for (n=18;n<20;n++)
{
IntervalTree itree(0,n);
for (i=n;i>=0;i--)
{
for (j=0;j<=i;j++)
{
s=itree.subtree(j,i);
cout<<s<<' ';
count[s]++;
}
cout<<endl;
}
}
for (i=0;i<4;i++)
tassert(count[i]==100);
iv.start=512;
iv.end=729;
itree0.insert(iv);
}
bool shoulddo(string testname)
{
int i;
bool ret,listTests=false;
if (testfail)
{
cout<<"failed before "<<testname<<endl;
//sleep(2);
}
ret=args.size()==0;
for (i=0;i<args.size();i++)
{
if (testname==args[i])
ret=true;
if (args[i]=="-l")
listTests=true;
}
if (listTests)
cout<<testname<<endl;
return ret;
}
int main(int argc, char *argv[])
{
int i;
for (i=1;i<argc;i++)
args.push_back(argv[i]);
if (shoulddo("roundup"))
testroundUp();
if (shoulddo("itree"))
testitree();
cout<<"\nTest "<<(testfail?"failed":"passed")<<endl;
return testfail;
}
| 22.257143 | 75 | 0.562259 | [
"vector"
] |
5111361e37572dd23599ceb70134dbfc5e1fe505 | 652 | cpp | C++ | LeetCode/#34.cpp | ksdkamesh99/Code-Monker | 0105d50185796539d4c2328892c9c117cb62ba55 | [
"MIT"
] | 3 | 2020-06-29T15:37:26.000Z | 2020-12-02T09:14:13.000Z | LeetCode/#34.cpp | ksdkamesh99/Code-Monker | 0105d50185796539d4c2328892c9c117cb62ba55 | [
"MIT"
] | null | null | null | LeetCode/#34.cpp | ksdkamesh99/Code-Monker | 0105d50185796539d4c2328892c9c117cb62ba55 | [
"MIT"
] | 1 | 2021-02-23T23:31:54.000Z | 2021-02-23T23:31:54.000Z | class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int l=-1;
int u=-1;
if(!nums.empty()){
l=lower_bound(nums.begin(),nums.end(),target)-nums.begin();
u=upper_bound(nums.begin(),nums.end(),target)-nums.begin();
if(l<nums.size() && u<=nums.size() && nums[l]==target){
l=l;
u=u-1;
}
else{
l=-1;
u=-1;
}
}
vector<int>v;
v.push_back(l);
v.push_back(u);
return v;
}
}; | 23.285714 | 71 | 0.384969 | [
"vector"
] |
5113a518ef5ff067092ece5a9ab883341e8dff17 | 455 | cpp | C++ | CodeForces/Complete/600-699/682A-AlyonaAndNumbers.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 36 | 2019-12-27T08:23:08.000Z | 2022-01-24T20:35:47.000Z | CodeForces/Complete/600-699/682A-AlyonaAndNumbers.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 10 | 2019-11-13T02:55:18.000Z | 2021-10-13T23:28:09.000Z | CodeForces/Complete/600-699/682A-AlyonaAndNumbers.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 53 | 2020-08-15T11:08:40.000Z | 2021-10-09T15:51:38.000Z | #include <cstdio>
#include <vector>
const int D = 5;
int main(){
long n, m; scanf("%ld %ld\n", &n, &m);
std::vector<long long> a(D);
std::vector<long long> b(D);
a[0] = n / D; b[0] = m / D;
for(int p = 1; p < D; p++){
a[p] = (n / D) + (n % D >= p);
b[p] = (m / D) + (m % D >= p);
}
long long res(0);
for(int p = 0; p < D; p++){res += a[p] * b[(D - p) % D];}
printf("%lld\n", res);
return 0;
}
| 18.958333 | 61 | 0.404396 | [
"vector"
] |
51144614a5df89952b95377afac17fbdcbbf581e | 1,726 | cpp | C++ | sdrs/src/v1/model/ExtendReplicationRequestBody.cpp | huaweicloud/huaweicloud-sdk-cpp-v3 | d3b5e07b0ee8367d1c7f6dad17be0212166d959c | [
"Apache-2.0"
] | 5 | 2021-03-03T08:23:43.000Z | 2022-02-16T02:16:39.000Z | sdrs/src/v1/model/ExtendReplicationRequestBody.cpp | ChenwxJay/huaweicloud-sdk-cpp-v3 | f821ec6d269b50203e0c1638571ee1349c503c41 | [
"Apache-2.0"
] | null | null | null | sdrs/src/v1/model/ExtendReplicationRequestBody.cpp | ChenwxJay/huaweicloud-sdk-cpp-v3 | f821ec6d269b50203e0c1638571ee1349c503c41 | [
"Apache-2.0"
] | 7 | 2021-02-26T13:53:35.000Z | 2022-03-18T02:36:43.000Z |
#include "huaweicloud/sdrs/v1/model/ExtendReplicationRequestBody.h"
namespace HuaweiCloud {
namespace Sdk {
namespace Sdrs {
namespace V1 {
namespace Model {
ExtendReplicationRequestBody::ExtendReplicationRequestBody()
{
extendReplicationIsSet_ = false;
}
ExtendReplicationRequestBody::~ExtendReplicationRequestBody() = default;
void ExtendReplicationRequestBody::validate()
{
}
web::json::value ExtendReplicationRequestBody::toJson() const
{
web::json::value val = web::json::value::object();
if(extendReplicationIsSet_) {
val[utility::conversions::to_string_t("extend-replication")] = ModelBase::toJson(extendReplication_);
}
return val;
}
bool ExtendReplicationRequestBody::fromJson(const web::json::value& val)
{
bool ok = true;
if(val.has_field(utility::conversions::to_string_t("extend-replication"))) {
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("extend-replication"));
if(!fieldValue.is_null())
{
ExtendReplicationRequestParams refVal;
ok &= ModelBase::fromJson(fieldValue, refVal);
setExtendReplication(refVal);
}
}
return ok;
}
ExtendReplicationRequestParams ExtendReplicationRequestBody::getExtendReplication() const
{
return extendReplication_;
}
void ExtendReplicationRequestBody::setExtendReplication(const ExtendReplicationRequestParams& value)
{
extendReplication_ = value;
extendReplicationIsSet_ = true;
}
bool ExtendReplicationRequestBody::extendReplicationIsSet() const
{
return extendReplicationIsSet_;
}
void ExtendReplicationRequestBody::unsetextendReplication()
{
extendReplicationIsSet_ = false;
}
}
}
}
}
}
| 21.308642 | 109 | 0.733488 | [
"object",
"model"
] |
511a606901306f36f915ffd78ce2ac71e0dc027c | 1,353 | cpp | C++ | nsgaII/nsgaII_test.cpp | alfjesus3/Basics_Math_and_Dynamic_Systems | 6c9338f393d9f6576e4138d21212c6197c846036 | [
"MIT"
] | null | null | null | nsgaII/nsgaII_test.cpp | alfjesus3/Basics_Math_and_Dynamic_Systems | 6c9338f393d9f6576e4138d21212c6197c846036 | [
"MIT"
] | null | null | null | nsgaII/nsgaII_test.cpp | alfjesus3/Basics_Math_and_Dynamic_Systems | 6c9338f393d9f6576e4138d21212c6197c846036 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstdlib>
#include <cassert>
#include "nsgaII_test.h"
#include "nsgaII.h"
int testIndividualCreation(int length_indiv, float min_val, float max_val){
std::cout << "The Indiv uses the parameters "<< length_indiv << ", " << min_val << " and " << max_val << std::endl;
Individual indivTest(length_indiv, min_val, max_val);
std::vector<float> genome = indivTest.get_Genome();
if (genome.size() != length_indiv){
std::cout << "Something went wrong with the Individual creation ..." << std::endl;
return -1;
}
for (int i=0; i < genome.size(); i++)
std::cout << genome[i] << std::endl;
}
int testPopulationCreation(int pop_size, int length_indiv, float min_val, float max_val){
std::cout << "The Popul given parameters are "<< pop_size << ", " << length_indiv << ", " << min_val << " and " << max_val << std::endl;
std::vector<Individual> popul; // More flexible than an array
popul.reserve(pop_size);
for (int i=0; i < pop_size; i++)
popul[i] = Individual(length_indiv, min_val, max_val);
for (int i=0; i < pop_size; i++){
std::cout << "Checking Indiv" << i << std::endl;
std::vector<float> tmp_genome = popul[i].get_Genome();
assert(tmp_genome.size() == length_indiv);
}
} | 37.583333 | 141 | 0.604582 | [
"vector"
] |
511d096ee82a03fa13946dda5e5c3ac833b80fae | 2,142 | cpp | C++ | test/test_full_mesh.cpp | SCOREC/pumi-pic | e6a7a59cff180f2bf3426e5c5fdfd9e8a70f4dc2 | [
"BSD-3-Clause"
] | 16 | 2019-05-02T08:33:11.000Z | 2022-03-25T12:13:42.000Z | test/test_full_mesh.cpp | SCOREC/pumi-pic | e6a7a59cff180f2bf3426e5c5fdfd9e8a70f4dc2 | [
"BSD-3-Clause"
] | 63 | 2019-01-10T21:58:36.000Z | 2021-12-22T21:27:29.000Z | test/test_full_mesh.cpp | SCOREC/pumi-pic | e6a7a59cff180f2bf3426e5c5fdfd9e8a70f4dc2 | [
"BSD-3-Clause"
] | 11 | 2019-04-10T19:01:42.000Z | 2021-06-25T00:26:47.000Z | #include <fstream>
#include <Omega_h_file.hpp>
#include <Omega_h_for.hpp>
#include <pumipic_mesh.hpp>
int main(int argc, char** argv) {
pumipic::Library pic_lib(&argc, &argv);
Omega_h::Library& lib = pic_lib.omega_h_lib();
int rank;
MPI_Comm_rank(MPI_COMM_WORLD,&rank);
if (argc != 3) {
if (!rank)
fprintf(stderr, "Usage: %s <mesh> <partition filename>\n", argv[0]);
MPI_Finalize();
return EXIT_FAILURE;
}
int comm_size;
MPI_Comm_size(MPI_COMM_WORLD, &comm_size);
//**********Load the mesh in serial everywhere*************//
Omega_h::Mesh mesh = Omega_h::read_mesh_file(argv[1], lib.self());
int dim = mesh.dim();
int ne = mesh.nents(dim);
if (rank == 0)
printf("Mesh loaded with <v e f r> %d %d %d %d\n", mesh.nverts(), mesh.nedges(),
mesh.nfaces(), mesh.nelems());
//********* Load the partition vector ***********//
pumipic::Input input(mesh, argv[2], pumipic::Input::FULL, pumipic::Input::FULL);
pumipic::Mesh picparts(input);
for (int i = 0; i <= mesh.dim(); ++i) {
if (mesh.nents(i) != picparts.mesh()->nents(i)) {
fprintf(stderr, "Entity counts do not match on process %d for dimension %d (%d != %d)\n",
rank, i, mesh.nents(i), picparts.mesh()->nents(i));
return EXIT_FAILURE;
}
}
//Test the global tag to be converted to global_serial
Omega_h::TagBase const* new_tag = picparts->get_tagbase(dim, "global_serial");
Omega_h::GOs global_old = mesh.get_array<Omega_h::GO>(dim, "global");
Omega_h::GOs global_new = picparts->get_array<Omega_h::GO>(dim, "global_serial");
Omega_h::Write<Omega_h::LO> fails(1,0);
auto checkGlobals = OMEGA_H_LAMBDA(const Omega_h::LO ent) {
if (global_old[ent] != global_new[ent]) {
printf("global ids do not match on entity %d [%ld != %ld]", ent, global_old[ent],
global_old[ent]);
fails[0] = 1;
}
};
Omega_h::parallel_for(mesh.nelems(), checkGlobals, "checkGlobals");
char vtk_name[100];
sprintf(vtk_name, "picpart%d", rank);
Omega_h::vtk::write_parallel(vtk_name, picparts.mesh(), dim);
return Omega_h::HostWrite<Omega_h::LO>(fails)[0];
}
| 33.46875 | 95 | 0.634921 | [
"mesh",
"vector"
] |
511e3a4eea06840784121f38fe15e9fb34a02554 | 9,272 | cc | C++ | src/wtf/fuzzer_test_tlv_server.cc | JohnPMerrill/wtf | ec8646bf5b6be8d23be63596463cfaf0beaa3815 | [
"MIT"
] | null | null | null | src/wtf/fuzzer_test_tlv_server.cc | JohnPMerrill/wtf | ec8646bf5b6be8d23be63596463cfaf0beaa3815 | [
"MIT"
] | null | null | null | src/wtf/fuzzer_test_tlv_server.cc | JohnPMerrill/wtf | ec8646bf5b6be8d23be63596463cfaf0beaa3815 | [
"MIT"
] | null | null | null | // written by y0ny0ns0n
#include "backend.h"
#include "targets.h"
#include "utils.h"
#include "mutator.h"
#include "crash_detection_umode.h"
#include <fmt/format.h>
namespace fs = std::filesystem;
using namespace std;
#define FIELD_SIZEOF(t, f) (sizeof(((t*)0)->f))
/*
test_tlv_server source code:
https://gist.github.com/y0ny0ns0n/389654ff9eb2b1541367de2b365c8210
*/
namespace test_tlv_server {
std::unique_ptr<LibfuzzerMutator_t> Mutator_ = NULL;
vector<pair<uint8_t *, uint32_t> *> Testcases_;
size_t Testcase_CurIdx;
size_t Testcase_LastIdx;
uint64_t MaxTestcaseCount = 100;
uint64_t SingleTestcaseMaxSize = 0x3FF;
uint64_t g_Rsp, g_Rip, g_Rax, g_Rbx, g_Rcx, g_Rdx, g_Rsi, g_Rdi,
g_R8, g_R9, g_R10, g_R11, g_R12, g_R13, g_R14, g_R15;
#pragma pack(push, 1)
typedef struct COMMON_PACKET_HEADER {
uint32_t CommandId;
uint32_t BodySize;
} COMMON_PACKET_HEADER;
#pragma pack(pop)
void Save64bitRegs() {
g_Rsp = g_Backend->Rsp();
g_Rip = g_Backend->Rip();
g_Rax = g_Backend->Rax();
g_Rbx = g_Backend->Rbx();
g_Rcx = g_Backend->Rcx();
g_Rdx = g_Backend->Rdx();
g_Rsi = g_Backend->Rsi();
g_Rdi = g_Backend->Rdi();
g_R8 = g_Backend->R8();
g_R9 = g_Backend->R9();
g_R10 = g_Backend->R10();
g_R11 = g_Backend->R11();
g_R12 = g_Backend->R12();
g_R13 = g_Backend->R13();
g_R14 = g_Backend->R14();
g_R15 = g_Backend->R15();
}
void Restore64bitRegs() {
g_Backend->Rsp(g_Rsp);
g_Backend->Rip(g_Rip);
g_Backend->Rax(g_Rax);
g_Backend->Rbx(g_Rbx);
g_Backend->Rcx(g_Rcx);
g_Backend->Rdx(g_Rdx);
g_Backend->Rsi(g_Rsi);
g_Backend->Rdi(g_Rdi);
g_Backend->R8(g_R8);
g_Backend->R9(g_R9);
g_Backend->R10(g_R10);
g_Backend->R11(g_R11);
g_Backend->R12(g_R12);
g_Backend->R13(g_R13);
g_Backend->R14(g_R14);
g_Backend->R15(g_R15);
}
constexpr bool LoggingOn = false;
template <typename... Args_t>
void DebugPrint(const char *Format, const Args_t &...args) {
if constexpr (LoggingOn) {
fmt::print("test_tlv_server: ");
fmt::print(Format, args...);
}
}
bool InsertTestcase(const uint8_t *Buffer, const size_t BufferSize) {
DebugPrint("InsertTestcase: called\n");
// initializing testcase vector
for(int i = 0; i < Testcases_.size(); i++) {
free(Testcases_.at(i)->first); // free testcase_ptr
free(Testcases_.at(i)); // free testcase
}
Testcases_.clear();
Testcase_CurIdx = 0;
size_t idx = 0;
uint32_t testcase_size = 0;
uint8_t * testcase_ptr = NULL;
pair<uint8_t *, uint32_t> *testcase = NULL;
Testcase_LastIdx = 0;
while(idx < BufferSize) {
testcase_size = *((uint32_t *)&Buffer[idx]);
idx += 4;
// +1 for pad
testcase_ptr = (uint8_t *)calloc(1, testcase_size + 1);
memcpy(testcase_ptr, &Buffer[idx], testcase_size);
idx += testcase_size;
testcase = new pair<uint8_t *, uint32_t>();
testcase->first = testcase_ptr;
testcase->second = testcase_size;
Testcases_.push_back(testcase);
Testcase_LastIdx += 1;
}
return true;
}
bool Init(const Options_t &Opts, const CpuState_t &) {
//
// return addr = rip + 5
//
// 0033:00007ff7`9d821894 e867f7ffff call test_tlv_server!process_packet (00007ff7`9d821000) <- take a snapshot on here
// 0033:00007ff7`9d821899 488b4c2438 mov rcx, qword ptr [rsp+38h]
const Gva_t Rip = Gva_t(g_Backend->Rip());
const Gva_t AfterCall = Rip + Gva_t(5);
DebugPrint("Init: Rip = {:#x}, AfterCall = {:#x}\n", Rip.U64(), AfterCall.U64());
Save64bitRegs();
if (!g_Backend->SetBreakpoint(AfterCall, [](Backend_t *Backend) {
Restore64bitRegs();
DebugPrint("Aftercall reached, now go back!\n");
})) {
DebugPrint("Failed to SetBreakpoint AfterCall\n");
return false;
}
//
// NOP the calls to DbgPrintEx.
//
if (!g_Backend->SetBreakpoint("nt!DbgPrintEx", [](Backend_t *Backend) {
const Gva_t FormatPtr = Backend->GetArgGva(2);
const std::string &Format = Backend->VirtReadString(FormatPtr);
DebugPrint("DbgPrintEx: {}", Format);
Backend->SimulateReturnFromFunction(0);
})) {
DebugPrint("Failed to SetBreakpoint DbgPrintEx\n");
return false;
}
//
// Make ExGenRandom deterministic. <- have to edit based on ntoskrnl version
//
// kd> u nt!ExGenRandom+0xfb l1
// nt!ExGenRandom+0xfb:
// fffff800`6125073b 0fc7f2 rdrand edx
const Gva_t ExGenRandom = Gva_t(g_Dbg.GetSymbol("nt!ExGenRandom") + 0xfb);
if (!g_Backend->SetBreakpoint(ExGenRandom, [](Backend_t *Backend) {
DebugPrint("Hit ExGenRandom!\n");
Backend->Rdx(Backend->Rdrand());
})) {
return false;
}
if(!g_Backend->SetBreakpoint("test_tlv_server!process_packet", [](Backend_t *Backend) {
if(Testcase_CurIdx == Testcase_LastIdx) {
DebugPrint("No more testcases. goto next round\n");
Backend->Stop(Ok_t());
}
else {
DebugPrint("process packet called\n");
uint8_t *testcase_ptr = Testcases_.at(Testcase_CurIdx)->first;
uint32_t testcase_size = Testcases_.at(Testcase_CurIdx)->second;
Gva_t PacketBuf = Backend->GetArgGva(0);
DebugPrint("Testcase_CurIdx = {}, testcase_size = {}\n", Testcase_CurIdx, testcase_size);
if(testcase_size > FIELD_SIZEOF(COMMON_PACKET_HEADER, CommandId)) {
COMMON_PACKET_HEADER *hdr = (COMMON_PACKET_HEADER *)testcase_ptr;
// 1 = Alloc, 2 = Edit, 3 = delete
hdr->CommandId = (hdr->CommandId % 3) + 1;
hdr->BodySize = testcase_size - sizeof(COMMON_PACKET_HEADER);
}
Backend->VirtWriteDirty(PacketBuf, testcase_ptr, testcase_size);
Backend->Rdx(testcase_size);
Testcase_CurIdx += 1;
}
})) {
DebugPrint("Failed to SetBreakpoint process_packet\n");
return false;
}
if (!g_Backend->SetBreakpoint("test_tlv_server!printf", [](Backend_t *Backend) {
const Gva_t FormatPtr = Backend->GetArgGva(0);
const std::string &Format = Backend->VirtReadString(FormatPtr);
DebugPrint("printf: {}", Format);
Backend->SimulateReturnFromFunction(0);
})) {
DebugPrint("Failed to SetBreakpoint printf\n");
return false;
}
if (!g_Backend->SetBreakpoint("ntdll!RtlEnterCriticalSection", [](Backend_t *Backend) {
Backend->SimulateReturnFromFunction(0);
})) {
DebugPrint("Failed to SetBreakpoint RtlEnterCriticalSection\n");
return false;
}
SetupUsermodeCrashDetectionHooks();
return true;
}
bool Restore() { return true; }
size_t CustomMutate(uint8_t *Data, const size_t DataLen, const size_t MaxSize, std::mt19937_64 Rng_) {
vector<pair<uint8_t*, uint32_t>> mutated_testcases;
size_t idx = 0;
uint32_t testcase_size = 0;
uint8_t *testcase_ptr = NULL;
if(Mutator_ == NULL) {
DebugPrint("CustomMutate: allocating new Mutator\n");
Mutator_ = std::make_unique<LibfuzzerMutator_t>(Rng_);
}
while(idx < DataLen) {
/**************************************************************
multi input testcase layout
+-----------------------------------+
| |
| size of 1th testcase( 4 bytes ) |
| |
+-----------------------------------+
| |
| 1th testcase( x bytes ) |
| |
+-----------------------------------+
.
.
.
+-----------------------------------+
| |
| size of Nth testcase( 4 bytes ) |
| |
+-----------------------------------+
| |
| Nth testcase( y bytes ) |
| |
+-----------------------------------+
**************************************************************/
testcase_size = *((uint32_t *)&Data[idx]);
idx += 4;
testcase_ptr = (uint8_t *)calloc(1, SingleTestcaseMaxSize);
memcpy(testcase_ptr, &Data[idx], testcase_size);
idx += testcase_size;
testcase_size = Mutator_->Mutate(testcase_ptr, testcase_size, SingleTestcaseMaxSize);
mutated_testcases.push_back(make_pair(testcase_ptr, testcase_size));
}
// initializing output buffer
memset(Data, 0, DataLen);
idx = 0;
for(int i = 0; i < mutated_testcases.size(); i++) {
testcase_ptr = mutated_testcases.at(i).first;
testcase_size = mutated_testcases.at(i).second;
*((uint32_t *)&Data[idx]) = testcase_size;
idx += 4;
memcpy(&Data[idx], testcase_ptr, testcase_size);
idx += testcase_size;
free(testcase_ptr);
}
mutated_testcases.clear();
return idx;
}
void PostMutate(Testcase_t *testcase) {
DebugPrint("PostMutate called\n");
if(Mutator_ != NULL) {
Mutator_->SetCrossOverWith(*testcase);
}
}
//
// Register the target.
//
Target_t test_tlv_server("test_tlv_server", Init, InsertTestcase, Restore, CustomMutate, PostMutate);
} // namespace test_tlv_server
| 28.617284 | 130 | 0.592968 | [
"vector"
] |
511e88c19bc8d3c12d0c7b45d9be370161134918 | 5,879 | cpp | C++ | FEBioMix/FEPoroTraction.cpp | Scriptkiddi/FEBioStudio | b4cafde6b2761c9184e7e66451a9555b81a8a3dc | [
"MIT"
] | null | null | null | FEBioMix/FEPoroTraction.cpp | Scriptkiddi/FEBioStudio | b4cafde6b2761c9184e7e66451a9555b81a8a3dc | [
"MIT"
] | null | null | null | FEBioMix/FEPoroTraction.cpp | Scriptkiddi/FEBioStudio | b4cafde6b2761c9184e7e66451a9555b81a8a3dc | [
"MIT"
] | null | null | null | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
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 "stdafx.h"
#include "FEPoroTraction.h"
#include "FECore/FEModel.h"
#include <FECore/FELinearSystem.h>
//-----------------------------------------------------------------------------
BEGIN_FECORE_CLASS(FEPoroNormalTraction, FESurfaceLoad)
ADD_PARAMETER(m_traction , "traction" );
ADD_PARAMETER(m_blinear , "linear" );
ADD_PARAMETER(m_bshellb , "shell_bottom");
ADD_PARAMETER(m_beffective, "effective");
END_FECORE_CLASS();
//-----------------------------------------------------------------------------
//! constructor
FEPoroNormalTraction::FEPoroNormalTraction(FEModel* pfem) : FESurfaceLoad(pfem)
{
m_traction = 1.0;
m_blinear = false;
m_bshellb = false;
m_beffective = false;
}
//-----------------------------------------------------------------------------
//! allocate storage
void FEPoroNormalTraction::SetSurface(FESurface* ps)
{
FESurfaceLoad::SetSurface(ps);
m_traction.SetItemList(ps->GetFacetSet());
}
//-----------------------------------------------------------------------------
bool FEPoroNormalTraction::Init()
{
FEModel* fem = GetFEModel();
m_dof.Clear();
if (m_bshellb == false)
{
m_dof.AddDof("x");
m_dof.AddDof("y");
m_dof.AddDof("z");
if (m_dof.AddDof("p") == false) m_dof.AddDof(-1);
}
else
{
m_dof.AddDof(fem->GetDOFIndex("sx"));
m_dof.AddDof(fem->GetDOFIndex("sy"));
m_dof.AddDof(fem->GetDOFIndex("sz"));
if (m_dof.AddDof("q") == false) m_dof.AddDof(-1);
}
return FESurfaceLoad::Init();
}
//-----------------------------------------------------------------------------
void FEPoroNormalTraction::StiffnessMatrix(FELinearSystem& LS, const FETimeInfo& tp)
{
if (m_blinear) return;
m_psurf->SetShellBottom(m_bshellb);
bool bsymm = LS.IsSymmetric();
FEPoroNormalTraction* traction = this;
m_psurf->LoadStiffness(LS, m_dof, m_dof, [=](FESurfaceMaterialPoint& mp, const FESurfaceDofShape& dof_a, const FESurfaceDofShape& dof_b, matrix& Kab) {
double H_i = dof_a.shape;
double Gr_i = dof_a.shape_deriv_r;
double Gs_i = dof_a.shape_deriv_s;
double H_j = dof_b.shape;
double Gr_j = dof_b.shape_deriv_r;
double Gs_j = dof_b.shape_deriv_s;
// traction at integration point
double tr = traction->Traction(mp);
if (traction->m_bshellb) tr = -tr;
// calculate stiffness component
Kab.zero();
if (!bsymm) {
// non-symmetric
vec3d kab = (mp.dxs*Gr_j - mp.dxr*Gs_j)*H_i * tr;
Kab[0][0] = 0;
Kab[0][1] = -kab.z;
Kab[0][2] = kab.y;
Kab[1][0] = kab.z;
Kab[1][1] = 0;
Kab[1][2] = -kab.x;
Kab[2][0] = -kab.y;
Kab[2][1] = kab.x;
Kab[2][2] = 0;
// if prescribed traction is effective, add stiffness component
if (traction->m_beffective)
{
vec3d kab = (mp.dxr ^ mp.dxs)* H_i * H_j;
Kab[0][3] = kab.x;
Kab[1][3] = kab.y;
Kab[2][3] = kab.z;
}
}
else {
// symmetric
vec3d kab = ((mp.dxs*Gr_j - mp.dxr*Gs_j)*H_i - (mp.dxs*Gr_i - mp.dxr*Gs_i)*H_j)*0.5 * tr;
Kab[0][0] = 0;
Kab[0][1] = -kab.z;
Kab[0][2] = kab.y;
Kab[1][0] = kab.z;
Kab[1][1] = 0;
Kab[1][2] = -kab.x;
Kab[2][0] = -kab.y;
Kab[2][1] = kab.x;
Kab[2][2] = 0;
// if prescribed traction is effective, add stiffness component
if (traction->m_beffective)
{
vec3d kab = (mp.dxr ^ mp.dxs) * 0.5*H_i * H_j;
Kab[0][3] = kab.x;
Kab[1][3] = kab.y;
Kab[2][3] = kab.z;
// TODO: This is not symmetric!
Kab[0][3] = kab.x;
Kab[1][3] = kab.y;
Kab[2][3] = kab.z;
}
}
});
}
//-----------------------------------------------------------------------------
double FEPoroNormalTraction::Traction(FESurfaceMaterialPoint& mp)
{
FESurfaceElement& el = *mp.SurfaceElement();
// calculate nodal normal tractions
double tr = m_traction(mp);
// if the prescribed traction is effective, evaluate the total traction
if (m_beffective)
{
// fluid pressure
tr -= m_psurf->Evaluate(mp, m_dof[3]);
}
return tr;
}
//-----------------------------------------------------------------------------
void FEPoroNormalTraction::LoadVector(FEGlobalVector& R, const FETimeInfo& tp)
{
m_psurf->SetShellBottom(m_bshellb);
FEPoroNormalTraction* traction = this;
m_psurf->LoadVector(R, m_dof, m_blinear, [=](FESurfaceMaterialPoint& mp, const FESurfaceDofShape& dof_a, vector<double>& fa) {
// traction at integration points
double tr = traction->Traction(mp);
if (traction->m_bshellb) tr = -tr;
// force vector
vec3d f = (mp.dxr ^ mp.dxs)*tr;
double H = dof_a.shape;
fa[0] = H * f.x;
fa[1] = H * f.y;
fa[2] = H * f.z;
fa[3] = 0.0;
});
}
| 28.129187 | 152 | 0.608267 | [
"shape",
"vector"
] |
511ebe9ffea16ca2802cd3033b8ffe67c045b434 | 6,063 | cpp | C++ | Allocator/PagedLinearAllocator.cpp | AzCopey/ICMemory | f0c903ef80611f1bb8f3efe02e65a59f9633a2f5 | [
"MIT"
] | 1 | 2016-02-01T13:52:54.000Z | 2016-02-01T13:52:54.000Z | Allocator/PagedLinearAllocator.cpp | AzCopey/ICMemory | f0c903ef80611f1bb8f3efe02e65a59f9633a2f5 | [
"MIT"
] | null | null | null | Allocator/PagedLinearAllocator.cpp | AzCopey/ICMemory | f0c903ef80611f1bb8f3efe02e65a59f9633a2f5 | [
"MIT"
] | null | null | null | // Created by Ian Copland on 2016-05-12
//
// The MIT License(MIT)
//
// Copyright(c) 2016 Ian Copland
//
// 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 "PagedLinearAllocator.h"
#include <cassert>
namespace IC
{
//------------------------------------------------------------------------------
PagedLinearAllocator::PagedLinearAllocator(std::size_t pageSize) noexcept
: m_pageSize(pageSize), m_freeStoreLinearAllocators()
{
m_freeStoreLinearAllocators.push_back(std::unique_ptr<LinearAllocator>(new LinearAllocator(m_pageSize)));
}
//------------------------------------------------------------------------------
PagedLinearAllocator::PagedLinearAllocator(IAllocator& parentAllocator, std::size_t pageSize) noexcept
: m_pageSize(pageSize), m_parentAllocator(&parentAllocator), m_parentAllocatorLinearAllocators(MakeVector<UniquePtr<LinearAllocator>>(*m_parentAllocator))
{
m_parentAllocatorLinearAllocators.push_back(MakeUnique<LinearAllocator>(*m_parentAllocator, *m_parentAllocator, m_pageSize));
}
//------------------------------------------------------------------------------
std::size_t PagedLinearAllocator::GetNumPages() const noexcept
{
if (m_parentAllocator)
{
return m_parentAllocatorLinearAllocators.size();
}
else
{
return m_freeStoreLinearAllocators.size();
}
}
//------------------------------------------------------------------------------
void* PagedLinearAllocator::Allocate(std::size_t allocationSize) noexcept
{
assert(allocationSize <= GetMaxAllocationSize());
if (m_parentAllocator)
{
for (const auto& blockAllocator : m_parentAllocatorLinearAllocators)
{
if (blockAllocator->GetFreeSpace() >= allocationSize)
{
return blockAllocator->Allocate(allocationSize);
}
}
m_parentAllocatorLinearAllocators.push_back(MakeUnique<LinearAllocator>(*m_parentAllocator, *m_parentAllocator, m_pageSize));
return m_parentAllocatorLinearAllocators.back()->Allocate(allocationSize);
}
else
{
for (const auto& blockAllocator : m_freeStoreLinearAllocators)
{
if (blockAllocator->GetFreeSpace() >= allocationSize)
{
return blockAllocator->Allocate(allocationSize);
}
}
m_freeStoreLinearAllocators.push_back(std::unique_ptr<LinearAllocator>(new LinearAllocator(m_pageSize)));
return m_freeStoreLinearAllocators.back()->Allocate(allocationSize);
}
}
//------------------------------------------------------------------------------
void PagedLinearAllocator::Deallocate(void* pointer) noexcept
{
if (m_parentAllocator)
{
for (const auto& blockAllocator : m_parentAllocatorLinearAllocators)
{
if (blockAllocator->Contains(pointer))
{
return blockAllocator->Deallocate(pointer);
}
}
}
else
{
for (const auto& blockAllocator : m_freeStoreLinearAllocators)
{
if (blockAllocator->Contains(pointer))
{
return blockAllocator->Deallocate(pointer);
}
}
}
assert(false);
}
//------------------------------------------------------------------------------
void PagedLinearAllocator::Reset() noexcept
{
if (m_parentAllocator)
{
for (auto& allocator : m_parentAllocatorLinearAllocators)
{
allocator->Reset();
}
}
else
{
for (auto& allocator : m_freeStoreLinearAllocators)
{
allocator->Reset();
}
}
}
//------------------------------------------------------------------------------
void PagedLinearAllocator::ResetAndShrink() noexcept
{
Reset();
if (m_parentAllocator)
{
while (m_parentAllocatorLinearAllocators.size() > 1)
{
m_parentAllocatorLinearAllocators.erase(m_parentAllocatorLinearAllocators.begin() + 1);
}
}
else
{
while (m_freeStoreLinearAllocators.size() > 1)
{
m_freeStoreLinearAllocators.erase(m_freeStoreLinearAllocators.begin() + 1);
}
}
}
//------------------------------------------------------------------------------
PagedLinearAllocator::~PagedLinearAllocator() noexcept
{
Reset();
if (m_parentAllocator)
{
m_parentAllocatorLinearAllocators.~vector();
}
else
{
m_freeStoreLinearAllocators.~vector();
}
}
} | 35.25 | 162 | 0.549728 | [
"vector"
] |
512382ea383ee5f129bfafb0336d18369cf0d25b | 3,463 | cxx | C++ | gui/moc_QvisPostableWindow.cxx | ahota/visit_ospray | d80b2e18ff5654d04bfb56ae4d6f42e45f87c9b9 | [
"BSD-3-Clause"
] | null | null | null | gui/moc_QvisPostableWindow.cxx | ahota/visit_ospray | d80b2e18ff5654d04bfb56ae4d6f42e45f87c9b9 | [
"BSD-3-Clause"
] | null | null | null | gui/moc_QvisPostableWindow.cxx | ahota/visit_ospray | d80b2e18ff5654d04bfb56ae4d6f42e45f87c9b9 | [
"BSD-3-Clause"
] | null | null | null | /****************************************************************************
** Meta object code from reading C++ file 'QvisPostableWindow.h'
**
** Created: Wed Nov 4 16:17:57 2015
** by: The Qt Meta Object Compiler version 63 (Qt 4.8.3)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "QvisPostableWindow.h"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'QvisPostableWindow.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 63
#error "This file was generated using the moc from 4.8.3. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
static const uint qt_meta_data_QvisPostableWindow[] = {
// content:
6, // revision
0, // classname
0, 0, // classinfo
7, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: signature, parameters, type, tag, flags
19, 27, 27, 27, 0x0a,
28, 27, 27, 27, 0x0a,
35, 27, 27, 27, 0x0a,
42, 27, 27, 27, 0x0a,
49, 60, 27, 27, 0x0a,
73, 27, 27, 27, 0x0a,
82, 27, 27, 27, 0x0a,
0 // eod
};
static const char qt_meta_stringdata_QvisPostableWindow[] = {
"QvisPostableWindow\0raise()\0\0show()\0"
"hide()\0post()\0post(bool)\0avoid_scroll\0"
"unpost()\0help()\0"
};
void QvisPostableWindow::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
Q_ASSERT(staticMetaObject.cast(_o));
QvisPostableWindow *_t = static_cast<QvisPostableWindow *>(_o);
switch (_id) {
case 0: _t->raise(); break;
case 1: _t->show(); break;
case 2: _t->hide(); break;
case 3: _t->post(); break;
case 4: _t->post((*reinterpret_cast< bool(*)>(_a[1]))); break;
case 5: _t->unpost(); break;
case 6: _t->help(); break;
default: ;
}
}
}
const QMetaObjectExtraData QvisPostableWindow::staticMetaObjectExtraData = {
0, qt_static_metacall
};
const QMetaObject QvisPostableWindow::staticMetaObject = {
{ &QvisWindowBase::staticMetaObject, qt_meta_stringdata_QvisPostableWindow,
qt_meta_data_QvisPostableWindow, &staticMetaObjectExtraData }
};
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &QvisPostableWindow::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION
const QMetaObject *QvisPostableWindow::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}
void *QvisPostableWindow::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_QvisPostableWindow))
return static_cast<void*>(const_cast< QvisPostableWindow*>(this));
return QvisWindowBase::qt_metacast(_clname);
}
int QvisPostableWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QvisWindowBase::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 7)
qt_static_metacall(this, _c, _id, _a);
_id -= 7;
}
return _id;
}
QT_END_MOC_NAMESPACE
| 32.064815 | 98 | 0.60901 | [
"object"
] |
512a8f7e6f0d473fe4a5ca1f3aa6a5bd48d471f4 | 12,567 | cc | C++ | components/sync_driver/non_ui_model_type_controller_unittest.cc | maidiHaitai/haitaibrowser | a232a56bcfb177913a14210e7733e0ea83a6b18d | [
"BSD-3-Clause"
] | 1 | 2020-09-15T08:43:34.000Z | 2020-09-15T08:43:34.000Z | components/sync_driver/non_ui_model_type_controller_unittest.cc | maidiHaitai/haitaibrowser | a232a56bcfb177913a14210e7733e0ea83a6b18d | [
"BSD-3-Clause"
] | null | null | null | components/sync_driver/non_ui_model_type_controller_unittest.cc | maidiHaitai/haitaibrowser | a232a56bcfb177913a14210e7733e0ea83a6b18d | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/sync_driver/non_ui_model_type_controller.h"
#include <memory>
#include <utility>
#include "base/bind.h"
#include "base/callback.h"
#include "base/logging.h"
#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h"
#include "base/memory/weak_ptr.h"
#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "base/sequenced_task_runner.h"
#include "base/test/test_simple_task_runner.h"
#include "base/threading/thread.h"
#include "components/sync_driver/backend_data_type_configurer.h"
#include "components/sync_driver/fake_sync_client.h"
#include "sync/api/fake_model_type_service.h"
#include "sync/engine/commit_queue.h"
#include "sync/internal_api/public/activation_context.h"
#include "sync/internal_api/public/shared_model_type_processor.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace sync_driver_v2 {
namespace {
// Test controller derived from NonUIModelTypeController.
class TestNonUIModelTypeController : public NonUIModelTypeController {
public:
TestNonUIModelTypeController(
const scoped_refptr<base::SingleThreadTaskRunner>& ui_thread,
const scoped_refptr<base::TaskRunner>& model_task_runner,
const base::Closure& error_callback,
syncer::ModelType model_type,
sync_driver::SyncClient* sync_client)
: NonUIModelTypeController(ui_thread,
error_callback,
model_type,
sync_client),
model_task_runner_(model_task_runner) {}
bool RunOnModelThread(const tracked_objects::Location& from_here,
const base::Closure& task) override {
DCHECK(model_task_runner_);
return model_task_runner_->PostTask(from_here, task);
}
private:
~TestNonUIModelTypeController() override {}
scoped_refptr<base::TaskRunner> model_task_runner_;
};
// A no-op instance of CommitQueue.
class NullCommitQueue : public syncer_v2::CommitQueue {
public:
NullCommitQueue() {}
~NullCommitQueue() override {}
void EnqueueForCommit(const syncer_v2::CommitRequestDataList& list) override {
NOTREACHED() << "Not implemented.";
}
};
// A class that pretends to be the sync backend.
class MockSyncBackend {
public:
void Connect(
syncer::ModelType type,
std::unique_ptr<syncer_v2::ActivationContext> activation_context) {
enabled_types_.Put(type);
activation_context->type_processor->ConnectSync(
base::WrapUnique(new NullCommitQueue()));
}
void Disconnect(syncer::ModelType type) {
DCHECK(enabled_types_.Has(type));
enabled_types_.Remove(type);
}
private:
syncer::ModelTypeSet enabled_types_;
};
// Fake implementation of BackendDataTypeConfigurer that pretends to be Sync
// backend.
class MockBackendDataTypeConfigurer
: public sync_driver::BackendDataTypeConfigurer {
public:
MockBackendDataTypeConfigurer(
MockSyncBackend* backend,
const scoped_refptr<base::TaskRunner>& sync_task_runner)
: backend_(backend), sync_task_runner_(sync_task_runner) {}
~MockBackendDataTypeConfigurer() override {}
syncer::ModelTypeSet ConfigureDataTypes(
syncer::ConfigureReason reason,
const DataTypeConfigStateMap& config_state_map,
const base::Callback<void(syncer::ModelTypeSet, syncer::ModelTypeSet)>&
ready_task,
const base::Callback<void()>& retry_callback) override {
NOTREACHED() << "Not implemented.";
return syncer::ModelTypeSet();
}
void ActivateDirectoryDataType(
syncer::ModelType type,
syncer::ModelSafeGroup group,
sync_driver::ChangeProcessor* change_processor) override {
NOTREACHED() << "Not implemented.";
}
void DeactivateDirectoryDataType(syncer::ModelType type) override {
NOTREACHED() << "Not implemented.";
}
void ActivateNonBlockingDataType(syncer::ModelType type,
std::unique_ptr<syncer_v2::ActivationContext>
activation_context) override {
// Post on Sync thread just like the real implementation does.
sync_task_runner_->PostTask(
FROM_HERE,
base::Bind(&MockSyncBackend::Connect, base::Unretained(backend_), type,
base::Passed(std::move(activation_context))));
}
void DeactivateNonBlockingDataType(syncer::ModelType type) override {
sync_task_runner_->PostTask(FROM_HERE,
base::Bind(&MockSyncBackend::Disconnect,
base::Unretained(backend_), type));
}
private:
MockSyncBackend* backend_;
scoped_refptr<base::TaskRunner> sync_task_runner_;
};
} // namespace
class NonUIModelTypeControllerTest : public testing::Test,
public sync_driver::FakeSyncClient {
public:
NonUIModelTypeControllerTest()
: auto_run_tasks_(true),
load_models_callback_called_(false),
association_callback_called_(false),
model_thread_("modelthread"),
sync_thread_runner_(new base::TestSimpleTaskRunner()),
configurer_(&backend_, sync_thread_runner_) {}
~NonUIModelTypeControllerTest() override {}
void SetUp() override {
model_thread_.Start();
model_thread_runner_ = model_thread_.task_runner();
InitializeModelTypeService();
controller_ = new TestNonUIModelTypeController(
ui_loop_.task_runner(), model_thread_runner_, base::Closure(),
syncer::DICTIONARY, this);
}
void TearDown() override {
ClearModelTypeService();
controller_ = NULL;
RunQueuedUIThreadTasks();
}
syncer_v2::ModelTypeService* GetModelTypeServiceForType(
syncer::ModelType type) override {
return service_.get();
}
protected:
std::unique_ptr<syncer_v2::ModelTypeChangeProcessor> CreateProcessor(
syncer::ModelType type,
syncer_v2::ModelTypeService* service) {
std::unique_ptr<syncer_v2::SharedModelTypeProcessor> processor =
base::WrapUnique(
new syncer_v2::SharedModelTypeProcessor(type, service));
type_processor_ = processor.get();
return std::move(processor);
}
void InitializeModelTypeService() {
if (!model_thread_runner_ ||
model_thread_runner_->BelongsToCurrentThread()) {
service_.reset(new syncer_v2::FakeModelTypeService(
base::Bind(&NonUIModelTypeControllerTest::CreateProcessor,
base::Unretained(this))));
} else {
model_thread_runner_->PostTask(
FROM_HERE,
base::Bind(&NonUIModelTypeControllerTest::InitializeModelTypeService,
base::Unretained(this)));
RunQueuedModelThreadTasks();
}
}
void ClearModelTypeService() {
if (!model_thread_runner_ ||
model_thread_runner_->BelongsToCurrentThread()) {
service_.reset();
} else {
model_thread_runner_->PostTask(
FROM_HERE,
base::Bind(&NonUIModelTypeControllerTest::ClearModelTypeService,
base::Unretained(this)));
RunQueuedModelThreadTasks();
}
}
void ExpectProcessorConnected(bool isConnected) {
if (model_thread_runner_->BelongsToCurrentThread()) {
DCHECK(type_processor_);
EXPECT_EQ(isConnected, type_processor_->IsConnected());
} else {
model_thread_runner_->PostTask(
FROM_HERE,
base::Bind(&NonUIModelTypeControllerTest::ExpectProcessorConnected,
base::Unretained(this), isConnected));
RunQueuedModelThreadTasks();
}
}
void OnMetadataLoaded() {
if (model_thread_runner_->BelongsToCurrentThread()) {
if (!type_processor_->IsAllowingChanges()) {
type_processor_->OnMetadataLoaded(
syncer::SyncError(),
base::WrapUnique(new syncer_v2::MetadataBatch()));
}
} else {
model_thread_runner_->PostTask(
FROM_HERE, base::Bind(&NonUIModelTypeControllerTest::OnMetadataLoaded,
base::Unretained(this)));
}
}
void LoadModels() {
controller_->LoadModels(base::Bind(
&NonUIModelTypeControllerTest::LoadModelsDone, base::Unretained(this)));
OnMetadataLoaded();
if (auto_run_tasks_) {
RunAllTasks();
}
}
void RegisterWithBackend() {
controller_->RegisterWithBackend(&configurer_);
if (auto_run_tasks_) {
RunAllTasks();
}
}
void StartAssociating() {
controller_->StartAssociating(
base::Bind(&NonUIModelTypeControllerTest::AssociationDone,
base::Unretained(this)));
// The callback is expected to be promptly called.
EXPECT_TRUE(association_callback_called_);
}
void DeactivateDataTypeAndStop() {
controller_->DeactivateDataType(&configurer_);
controller_->Stop();
if (auto_run_tasks_) {
RunAllTasks();
}
}
// These threads can ping-pong for a bit so we run the model thread twice.
void RunAllTasks() {
RunQueuedModelThreadTasks();
RunQueuedUIThreadTasks();
RunQueuedSyncThreadTasks();
RunQueuedModelThreadTasks();
}
// Runs any tasks posted on UI thread.
void RunQueuedUIThreadTasks() { ui_loop_.RunUntilIdle(); }
// Runs any tasks posted on model thread.
void RunQueuedModelThreadTasks() {
base::RunLoop run_loop;
model_thread_runner_->PostTaskAndReply(
FROM_HERE, base::Bind(&base::DoNothing),
base::Bind(&base::RunLoop::Quit, base::Unretained(&run_loop)));
run_loop.Run();
}
// Processes any pending connect or disconnect requests and sends
// responses synchronously.
void RunQueuedSyncThreadTasks() { sync_thread_runner_->RunUntilIdle(); }
void SetAutoRunTasks(bool auto_run_tasks) {
auto_run_tasks_ = auto_run_tasks;
}
void LoadModelsDone(syncer::ModelType type, syncer::SyncError error) {
load_models_callback_called_ = true;
load_models_error_ = error;
}
void AssociationDone(sync_driver::DataTypeController::ConfigureResult result,
const syncer::SyncMergeResult& local_merge_result,
const syncer::SyncMergeResult& syncer_merge_result) {
EXPECT_EQ(sync_driver::DataTypeController::OK, result);
association_callback_called_ = true;
}
syncer_v2::SharedModelTypeProcessor* type_processor_;
scoped_refptr<TestNonUIModelTypeController> controller_;
bool auto_run_tasks_;
bool load_models_callback_called_;
syncer::SyncError load_models_error_;
bool association_callback_called_;
base::MessageLoopForUI ui_loop_;
base::Thread model_thread_;
scoped_refptr<base::SingleThreadTaskRunner> model_thread_runner_;
scoped_refptr<base::TestSimpleTaskRunner> sync_thread_runner_;
MockSyncBackend backend_;
MockBackendDataTypeConfigurer configurer_;
std::unique_ptr<syncer_v2::FakeModelTypeService> service_;
};
TEST_F(NonUIModelTypeControllerTest, InitialState) {
EXPECT_EQ(syncer::DICTIONARY, controller_->type());
EXPECT_EQ(sync_driver::DataTypeController::NOT_RUNNING, controller_->state());
}
TEST_F(NonUIModelTypeControllerTest, LoadModelsOnBackendThread) {
SetAutoRunTasks(false);
LoadModels();
EXPECT_EQ(sync_driver::DataTypeController::MODEL_STARTING,
controller_->state());
RunAllTasks();
EXPECT_EQ(sync_driver::DataTypeController::MODEL_LOADED,
controller_->state());
EXPECT_TRUE(load_models_callback_called_);
EXPECT_FALSE(load_models_error_.IsSet());
ExpectProcessorConnected(false);
}
TEST_F(NonUIModelTypeControllerTest, LoadModelsTwice) {
LoadModels();
SetAutoRunTasks(false);
LoadModels();
EXPECT_EQ(sync_driver::DataTypeController::MODEL_LOADED,
controller_->state());
// The second LoadModels call should set the error.
EXPECT_TRUE(load_models_error_.IsSet());
}
TEST_F(NonUIModelTypeControllerTest, ActivateDataTypeOnBackendThread) {
LoadModels();
EXPECT_EQ(sync_driver::DataTypeController::MODEL_LOADED,
controller_->state());
RegisterWithBackend();
ExpectProcessorConnected(true);
StartAssociating();
EXPECT_EQ(sync_driver::DataTypeController::RUNNING, controller_->state());
}
TEST_F(NonUIModelTypeControllerTest, Stop) {
LoadModels();
RegisterWithBackend();
ExpectProcessorConnected(true);
StartAssociating();
DeactivateDataTypeAndStop();
EXPECT_EQ(sync_driver::DataTypeController::NOT_RUNNING, controller_->state());
}
} // namespace sync_driver_v2
| 32.641558 | 80 | 0.709159 | [
"model"
] |
512c3b1a163677cb5e15e5df30d854571fe5bf4b | 9,497 | cc | C++ | FastSimulation/CaloGeometryTools/src/CrystalPad.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-24T19:10:26.000Z | 2019-02-19T11:45:32.000Z | FastSimulation/CaloGeometryTools/src/CrystalPad.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-23T13:40:24.000Z | 2019-12-05T21:16:03.000Z | FastSimulation/CaloGeometryTools/src/CrystalPad.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 5 | 2018-08-21T16:37:52.000Z | 2020-01-09T13:33:17.000Z | #include "FastSimulation/CaloGeometryTools/interface/CrystalPad.h"
#include <iostream>
std::vector<CLHEP::Hep2Vector> CrystalPad::aVector(4);
CrystalPad::CrystalPad(const CrystalPad& right)
{
corners_ = right.corners_;
dir_ = right.dir_;
number_ = right.number_;
survivalProbability_ = right.survivalProbability_;
center_ = right.center_;
epsilon_ = right.epsilon_;
dummy_ = right.dummy_;
}
CrystalPad&
CrystalPad::operator = (const CrystalPad& right ) {
if (this != &right) { // don't copy into yourself
corners_ = right.corners_;
dir_ = right.dir_;
number_ = right.number_;
survivalProbability_ = right.survivalProbability_;
center_ = right.center_;
epsilon_ = right.epsilon_;
dummy_ = right.dummy_;
}
return *this;
}
CrystalPad::CrystalPad(unsigned number,
const std::vector<CLHEP::Hep2Vector>& corners)
:
corners_(corners),
dir_(aVector),
number_(number),
survivalProbability_(1.),
center_(0.,0.),
epsilon_(0.001)
{
// std::cout << " Hello " << std::endl;
if(corners.size()!=4)
{
std::cout << " Try to construct a quadrilateral with " << corners.size() << " points ! " << std::endl;
dummy_=true;
}
else
{
dummy_=false;
// Set explicity the z to 0 !
for(unsigned ic=0; ic<4;++ic)
{
dir_[ic] = (corners[(ic+1)%4]-corners[ic]).unit();
center_+=corners_[ic];
}
center_*=0.25;
}
// std::cout << " End of 1 constructor " << std::endl;
// std::cout << " Ncorners " << corners_.size() << std::endl;
// std::cout << " Ndirs " << dir_.size() << std::endl;
}
CrystalPad::CrystalPad(unsigned number, int onEcal,
const std::vector<XYZPoint>& corners,
const XYZPoint& origin,
const XYZVector& vec1,
const XYZVector& vec2)
:
corners_(aVector),
dir_(aVector),
number_(number),
survivalProbability_(1.),
center_(0.,0.),
epsilon_(0.001)
{
// std::cout << " We are in the 2nd constructor " << std::endl;
if(corners.size()!=4)
{
std::cout << " Try to construct a quadrilateral with " << corners.size() << " points ! " << std::endl;
dummy_=true;
}
else
{
dummy_=false;
double sign=(onEcal==1) ? -1.: 1.;
// the good one in the central
trans_=Transform3D((Point)origin,
(Point)(origin+vec1),
(Point)(origin+vec2),
Point(0.,0.,0.),
Point(0.,0.,sign),
Point(0.,1.,0.));
trans_.GetDecomposition(rotation_,translation_);
// std::cout << " Constructor 2; input corners " << std::endl;
for(unsigned ic=0;ic<4;++ic)
{
// std::cout << corners[ic]<< " " ;
XYZPoint corner = rotation_(corners[ic])+translation_;
// std::cout << corner << std::endl ;
corners_[ic] = CLHEP::Hep2Vector(corner.X(),corner.Y());
center_+=corners_[ic];
}
for(unsigned ic=0;ic<4;++ic)
{
dir_[ic] = (corners_[(ic+1)%4]-corners_[ic]).unit();
}
center_*=0.25;
}
// std::cout << " End of 2 constructor " << std::endl;
// std::cout << " Corners(constructor) " ;
// std::cout << corners_[0] << std::endl;
// std::cout << corners_[1] << std::endl;
// std::cout << corners_[2] << std::endl;
// std::cout << corners_[3] << std::endl;
}
CrystalPad::CrystalPad(unsigned number,
const std::vector<XYZPoint>& corners,
const Transform3D & trans,double scaf,bool bothdirections)
:
corners_(aVector),
dir_(aVector),
number_(number),
survivalProbability_(1.),
center_(0.,0.),
epsilon_(0.001),
yscalefactor_(scaf)
{
// std::cout << " We are in the 2nd constructor " << std::endl;
if(corners.size()!=4)
{
std::cout << " Try to construct a quadrilateral with " << corners.size() << " points ! " << std::endl;
dummy_=true;
}
else
{
dummy_=false;
// the good one in the central
trans_=trans;
// std::cout << " Constructor 2; input corners " << std::endl;
trans_.GetDecomposition(rotation_,translation_);
for(unsigned ic=0;ic<4;++ic)
{
XYZPoint corner=rotation_(corners[ic])+translation_;
// std::cout << corner << std::endl ;
double xscalefactor=(bothdirections) ? yscalefactor_:1.;
corners_[ic] = CLHEP::Hep2Vector(corner.X()*xscalefactor,corner.Y()*yscalefactor_);
center_+=corners_[ic];
}
for(unsigned ic=0;ic<4;++ic)
{
dir_[ic] = (corners_[(ic+1)%4]-corners_[ic]).unit();
}
center_*=0.25;
}
}
bool
CrystalPad::inside(const CLHEP::Hep2Vector & ppoint,bool debug) const
{
// std::cout << "Inside " << ppoint <<std::endl;
// std::cout << "Corners " << corners_.size() << std::endl;
// std::cout << corners_[0] << std::endl;
// std::cout << corners_[1] << std::endl;
// std::cout << corners_[2] << std::endl;
// std::cout << corners_[3] << std::endl;
// std::cout << " Got the 2D point " << std::endl;
CLHEP::Hep2Vector pv0(ppoint-corners_[0]);
CLHEP::Hep2Vector pv2(ppoint-corners_[2]);
CLHEP::Hep2Vector n1(pv0-(pv0*dir_[0])*dir_[0]);
CLHEP::Hep2Vector n2(pv2-(pv2*dir_[2])*dir_[2]);
// double N1(n1.mag());
// double N2(n2.mag());
double r1(n1*n2);
bool inside1(r1<=0.);
if (!inside1) return false;
// if(debug)
// {
// std::cout << n1 << std::endl;
// std::cout << n2 << std::endl;
// std::cout << r1 << std::endl;
// std::cout << inside1 << std::endl;
// }
// bool close1=(N1<epsilon_||N2<epsilon_);
//
// if(!close1&&!inside1) return false;
// std::cout << " First calculation " << std::endl;
CLHEP::Hep2Vector pv1(ppoint-corners_[1]);
CLHEP::Hep2Vector pv3(ppoint-corners_[3]);
CLHEP::Hep2Vector n3(pv1-(pv1*dir_[1])*dir_[1]);
CLHEP::Hep2Vector n4(pv3-(pv3*dir_[3])*dir_[3]);
// double N3(n3.mag());
// double N4(n4.mag());
// bool close2=(N3<epsilon_||N4<epsilon_);
double r2(n3*n4);
bool inside2(r2<=0.);
// // std::cout << " pv1 & pv3 " << pv1.mag() << " " << pv3.mag() << std::endl;
// // double tmp=(pv1-(pv1*dir_[1])*dir_[1])*(pv3-(pv3*dir_[3])*dir_[3]);
// // std::cout << " Computed tmp " << tmp << std::endl;
// if(debug)
// {
// std::cout << n3 << std::endl;
// std::cout << n4 << std::endl;
// std::cout << r2 << std::endl;
// std::cout << inside2 << std::endl;
// }
// if(!close2&&!inside2) return false;
// std::cout << " Second calculation " << std::endl;
// std::cout << " True " << std::endl;
// return (!close1&&!close2||(close2&&inside1||close1&&inside2));
return inside2;
}
/*
bool
CrystalPad::globalinside(XYZPoint point) const
{
// std::cout << " Global inside " << std::endl;
// std::cout << point << " " ;
ROOT::Math::Rotation3D r;
XYZVector t;
point = rotation_(point)+translation_;
// std::cout << point << std::endl;
// print();
CLHEP::Hep2Vector ppoint(point.X(),point.Y());
bool result=inside(ppoint);
// std::cout << " Result " << result << std::endl;
return result;
}
*/
void CrystalPad::print() const
{
std::cout << " Corners " << std::endl;
std::cout << corners_[0] << std::endl;
std::cout << corners_[1] << std::endl;
std::cout << corners_[2] << std::endl;
std::cout << corners_[3] << std::endl;
}
/*
CLHEP::Hep2Vector
CrystalPad::localPoint(XYZPoint point) const
{
point = rotation_(point)+translation_;
return CLHEP::Hep2Vector(point.X(),point.Y());
}
*/
CLHEP::Hep2Vector& CrystalPad::edge(unsigned iside,int n)
{
return corners_[(iside+n)%4];
}
CLHEP::Hep2Vector & CrystalPad::edge(CaloDirection dir)
{
switch(dir)
{
case NORTHWEST:
return corners_[0];
break;
case NORTHEAST:
return corners_[1];
break;
case SOUTHEAST:
return corners_[2];
break;
case SOUTHWEST:
return corners_[3];
break;
default:
{
std::cout << " Serious problem in CrystalPad ! " << dir << std::endl;
return corners_[0];
}
}
return corners_[0];
}
void
CrystalPad::extrems(double &xmin,double& xmax,double &ymin, double& ymax) const
{
xmin=ymin=999;
xmax=ymax=-999;
for(unsigned ic=0;ic<4;++ic)
{
if(corners_[ic].x()<xmin) xmin=corners_[ic].x();
if(corners_[ic].x()>xmax) xmax=corners_[ic].x();
if(corners_[ic].y()<ymin) ymin=corners_[ic].y();
if(corners_[ic].y()>ymax) ymax=corners_[ic].y();
}
}
void
CrystalPad::resetCorners() {
// Find the centre-of-gravity of the Quad (after re-organization)
center_ = CLHEP::Hep2Vector(0.,0.);
for(unsigned ic=0;ic<4;++ic) center_ += corners_[ic];
center_ *= 0.25;
// Rescale the corners to allow for some inaccuracies in
// in the inside test
for(unsigned ic=0;ic<4;++ic)
corners_[ic] += 0.001 * (corners_[ic] - center_) ;
}
std::ostream & operator << (std::ostream& ost, CrystalPad & quad)
{
ost << " Number " << quad.getNumber() << std::endl ;
ost << NORTHWEST << quad.edge(NORTHWEST) << std::endl;
ost << NORTHEAST << quad.edge(NORTHEAST) << std::endl;
ost << SOUTHEAST << quad.edge(SOUTHEAST) << std::endl;
ost << SOUTHWEST << quad.edge(SOUTHWEST) << std::endl;
return ost;
}
void
CrystalPad::getDrawingCoordinates(std::vector<float> &x, std::vector<float>&y) const
{
x.clear();
y.clear();
x.push_back(corners_[0].x());
x.push_back(corners_[1].x());
x.push_back(corners_[2].x());
x.push_back(corners_[3].x());
x.push_back(corners_[0].x());
y.push_back(corners_[0].y());
y.push_back(corners_[1].y());
y.push_back(corners_[2].y());
y.push_back(corners_[3].y());
y.push_back(corners_[0].y());
}
| 27.134286 | 113 | 0.593872 | [
"vector"
] |
513bb9a88d9b7f6d3cb758f79e79c70068f94e5c | 1,620 | cpp | C++ | verify/verify-unit-test/set-function.test.cpp | NachiaVivias/library | 73091ddbb00bc59328509c8f6e662fea2b772994 | [
"CC0-1.0"
] | 69 | 2020-11-06T05:21:42.000Z | 2022-03-29T03:38:35.000Z | verify/verify-unit-test/set-function.test.cpp | NachiaVivias/library | 73091ddbb00bc59328509c8f6e662fea2b772994 | [
"CC0-1.0"
] | 21 | 2020-07-25T04:47:12.000Z | 2022-02-01T14:39:29.000Z | verify/verify-unit-test/set-function.test.cpp | NachiaVivias/library | 73091ddbb00bc59328509c8f6e662fea2b772994 | [
"CC0-1.0"
] | 9 | 2020-11-06T11:55:10.000Z | 2022-03-20T04:45:31.000Z | #define PROBLEM "https://judge.yosupo.jp/problem/aplusb"
#include "../../template/template.hpp"
using namespace Nyaan;
#include "../../misc/rng.hpp"
#include "../../modint/montgomery-modint.hpp"
#include "../../set-function/and-convolution.hpp"
#include "../../set-function/or-convolution.hpp"
#include "../../set-function/xor-convolution.hpp"
using mint = LazyMontgomeryModInt<998244353>;
template <typename T>
void test(int n) {
assert((n & (n - 1)) == 0);
vector<T> a(n), b(n), c(n);
rep(i, n) {
a[i] = rng() & 0xFFFF;
b[i] = rng() & 0xFFFF;
}
{
auto d = a;
subset_zeta_transform(d);
subset_mobius_transform(d);
assert(a == d && "subset");
}
{
auto d = a;
superset_zeta_transform(d);
superset_mobius_transform(d);
assert(a == d && "superset");
}
{
auto d = a;
walsh_hadamard_transform(d);
walsh_hadamard_transform(d, true);
assert(a == d && "hadamard");
}
// and convolution
{
auto d = and_convolution(a, b);
fill(all(c), 0);
rep(i, n) rep(j, n) c[i & j] += a[i] * b[j];
assert(c == d && "and");
}
// or convolution
{
auto d = or_convolution(a, b);
fill(all(c), 0);
rep(i, n) rep(j, n) c[i | j] += a[i] * b[j];
assert(c == d && "or");
}
// xor convolution
{
auto d = xor_convolution(a, b);
fill(all(c), 0);
rep(i, n) rep(j, n) c[i ^ j] += a[i] * b[j];
assert(c == d && "xor");
}
}
void Nyaan::solve() {
for (int i = 1; i <= 1024; i *= 2) {
test<ll>(i);
test<mint>(i);
}
cerr << "ok" << endl;
int a, b;
cin >> a >> b;
cout << a + b << endl;
}
| 20 | 56 | 0.533333 | [
"vector"
] |
513d945d1a74a6529ca4f07b417abb241865f0ae | 5,894 | hpp | C++ | include/pstore/support/inherit_const.hpp | paulhuggett/pstore2 | a0c663d10a2e2713fdf39ecdae1f9c1e96041f5c | [
"Apache-2.0"
] | 11 | 2018-02-02T21:24:49.000Z | 2020-12-11T04:06:03.000Z | include/pstore/support/inherit_const.hpp | SNSystems/pstore | 74e9dd960245d6bfc125af03ed964d8ad660a62d | [
"Apache-2.0"
] | 63 | 2018-02-05T17:24:59.000Z | 2022-03-22T17:26:28.000Z | include/pstore/support/inherit_const.hpp | paulhuggett/pstore | 067be94d87c87fce524c8d76c6f47c347d8f1853 | [
"Apache-2.0"
] | 5 | 2020-01-13T22:47:11.000Z | 2021-05-14T09:31:15.000Z | //===- include/pstore/support/inherit_const.hpp -----------*- mode: C++ -*-===//
//* _ _ _ _ _ *
//* (_)_ __ | |__ ___ _ __(_) |_ ___ ___ _ __ ___| |_ *
//* | | '_ \| '_ \ / _ \ '__| | __| / __/ _ \| '_ \/ __| __| *
//* | | | | | | | | __/ | | | |_ | (_| (_) | | | \__ \ |_ *
//* |_|_| |_|_| |_|\___|_| |_|\__| \___\___/|_| |_|___/\__| *
//* *
//===----------------------------------------------------------------------===//
//
// Part of the pstore project, under the Apache License v2.0 with LLVM Exceptions.
// See https://github.com/SNSystems/pstore/blob/master/LICENSE.txt for license
// information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
/// \file inherit_const.hpp
/// \brief A utility template intended to simplify the writing of the const- and non-const variants
/// of member functions.
///
/// It's not uncommon for a class to supply const- and non-const variants of the same member
/// function where the constness of the return type changes according to the constness of the
/// function itself. For example, std::vector<> has:
///
/// reference operator[] (size_type pos);
/// const_reference operator[] (size_type pos) const;
///
/// Often the implementation of these two functions is identical: the constness is the only thing
/// changing. This encourages us to want to share the implementation because duplicating code is
/// almost always to be avoided. Writers typically adopt one of three solutions:
///
/// 1. Just duplicate the code and move on. For trivial one liners this is a perfectly good
/// solution. For anything more complex however, there's a risk that future changes will modify the
/// implementations and that they'll begin to diverge with time, which can result in new bugs being
/// introduced.
///
/// reference operator[] (size_type pos) {
/// return base_ + pos;
/// }
/// const_reference operator[] (size_type pos) const {
/// return base_ + pos;
/// }
///
/// 2. Write one of the functions in terms of the other and use const_cast<> to silence the compiler
/// errors. An attractive options since duplication is avoided completely. However, using
/// const_cast<> is potentially dangerous because by using it the code is really lying to the
/// compiler: the underlying data may be truly read-only even if the types no longer are. This can
/// be a new source of bugs.
///
/// reference operator[] (size_type pos) {
/// auto const * cthis = this;
/// return const_cast<reference> cthis->operator[] (pos);
/// }
/// const_reference operator[] (size_type pos) const {
/// return base_ + pos;
/// }
///
/// 3. Use macros to past the repeated implementation into the code. Happily, for most writers of
/// C++, this isn't really considered a viable option.
///
/// #define OPERATOR_INDEX(p) (base_ + (p))
/// reference operator[] (size_type pos) {
/// return OPERATOR_INDEX(pos);
/// }
/// const_reference operator[] (size_type pos) const {
/// return OPERATOR_INDEX(pos);
/// }
/// #undef OPERATOR_INDEX
///
/// The utility here is intended to resolve some of these concerns. For true one-liner member
/// functions it is very likely overkill, but can be useful for implementations that are just
/// fractionally more complex. In the example below I've added an assertion to the shared
/// implementation.
///
/// class vector {
/// public:
/// ...
/// reference operator[] (size_type pos) {
/// return index_impl (*this, pos);
/// }
/// const_reference operator[] (size_type pos) const {
/// return index_impl (*this, pos);
/// }
/// ...
/// private:
/// template <typename Vector, typename ResultType = typename inherit_const<Vector,
/// reference>::type>
/// static ResultType index_impl (Vector & v, size_type pos) {
/// PSTORE_ASSERT (pos < v.size ());
/// return v.base_ + pos;
/// }
/// };
#ifndef PSTORE_SUPPORT_INHERIT_CONST_HPP
#define PSTORE_SUPPORT_INHERIT_CONST_HPP
#include <type_traits>
namespace pstore {
/// Provides a member typedef inherit_const::type, which is defined as \p R const if
/// \p T is a const type and \p R if \p T is non-const.
///
/// \tparam T A type whose constness will determine the constness of
/// inherit_const::type.
/// \tparam R The result type.
/// \tparam RC The const-result type.
template <typename T, typename R, typename RC = R const>
struct inherit_const {
/// If \p T is const, \p R const otherwise \p R.
using type =
typename std::conditional<std::is_const<typename std::remove_reference<T>::type>::value,
RC, R>::type;
};
} // namespace pstore
static_assert (std::is_same<typename pstore::inherit_const<int, bool>::type, bool>::value,
"int -> bool");
static_assert (
std::is_same<typename pstore::inherit_const<int const, bool>::type, bool const>::value,
"int const -> bool const");
static_assert (std::is_same<typename pstore::inherit_const<int &, bool>::type, bool>::value,
"int& -> bool");
static_assert (
std::is_same<typename pstore::inherit_const<int const &, bool>::type, bool const>::value,
"int const & -> bool const");
static_assert (std::is_same<typename pstore::inherit_const<int &&, bool>::type, bool>::value,
"int && -> bool");
static_assert (
std::is_same<typename pstore::inherit_const<int const &&, bool>::type, bool const>::value,
"int const && -> bool const");
#endif // PSTORE_SUPPORT_INHERIT_CONST_HPP
| 43.985075 | 100 | 0.602816 | [
"vector"
] |
513e0b725af5bb6ca8e627f26d60e4a0da565727 | 3,911 | hh | C++ | neb/inc/com/centreon/engine/configuration/servicegroup.hh | sdelafond/centreon-broker | 21178d98ed8a061ca71317d23c2026dbc4edaca2 | [
"Apache-2.0"
] | null | null | null | neb/inc/com/centreon/engine/configuration/servicegroup.hh | sdelafond/centreon-broker | 21178d98ed8a061ca71317d23c2026dbc4edaca2 | [
"Apache-2.0"
] | null | null | null | neb/inc/com/centreon/engine/configuration/servicegroup.hh | sdelafond/centreon-broker | 21178d98ed8a061ca71317d23c2026dbc4edaca2 | [
"Apache-2.0"
] | null | null | null | /*
** Copyright 2011-2013,2017 Centreon
**
** This file is part of Centreon Engine.
**
** Centreon Engine is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon Engine 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 Centreon Engine. If not, see
** <http://www.gnu.org/licenses/>.
*/
#ifndef CCE_CONFIGURATION_SERVICEGROUP_HH
# define CCE_CONFIGURATION_SERVICEGROUP_HH
# include <set>
# include <utility>
# include "com/centreon/engine/configuration/group.hh"
# include "com/centreon/engine/configuration/object.hh"
# include "com/centreon/engine/opt.hh"
# include "com/centreon/engine/namespace.hh"
typedef std::set<std::pair<std::string, std::string> > set_pair_string;
CCE_BEGIN()
namespace configuration {
class servicegroup : public object {
public:
typedef std::string key_type;
servicegroup(key_type const& key = "");
servicegroup(servicegroup const& right);
~servicegroup() throw () override;
servicegroup& operator=(servicegroup const& right);
bool operator==(
servicegroup const& right) const throw ();
bool operator!=(
servicegroup const& right) const throw ();
bool operator<(
servicegroup const& right) const throw();
void check_validity() const override;
key_type const& key() const throw ();
void merge(object const& obj) override;
bool parse(char const* key, char const* value) override;
std::string const& action_url() const throw ();
std::string const& alias() const throw ();
set_pair_string& members() throw ();
set_pair_string const& members() const throw ();
std::string const& notes() const throw ();
std::string const& notes_url() const throw ();
unsigned int servicegroup_id() const throw();
set_string& servicegroup_members() throw ();
set_string const& servicegroup_members() const throw ();
std::string const& servicegroup_name() const throw ();
private:
typedef bool (*setter_func)(servicegroup&, char const*);
bool _set_action_url(std::string const& value);
bool _set_alias(std::string const& value);
bool _set_members(std::string const& value);
bool _set_notes(std::string const& value);
bool _set_notes_url(std::string const& value);
bool _set_servicegroup_id(unsigned int value);
bool _set_servicegroup_members(std::string const& value);
bool _set_servicegroup_name(std::string const& value);
std::string _action_url;
std::string _alias;
group<set_pair_string> _members;
std::string _notes;
std::string _notes_url;
unsigned int _servicegroup_id;
group<set_string> _servicegroup_members;
std::string _servicegroup_name;
static std::unordered_map<std::string, setter_func> const _setters;
};
typedef std::shared_ptr<servicegroup> servicegroup_ptr;
typedef std::set<servicegroup> set_servicegroup;
}
CCE_END()
#endif // !CCE_CONFIGURATION_SERVICEGROUP_HH
| 41.168421 | 80 | 0.608029 | [
"object"
] |
514097cf0697c9404036201591347901c30d5675 | 4,231 | cpp | C++ | smn/src/obnsmn_event.cpp | sduerr85/OpenBuildNet | 126feb4d17558e7bfe1e2e6f081bbfbf1514496f | [
"MIT"
] | null | null | null | smn/src/obnsmn_event.cpp | sduerr85/OpenBuildNet | 126feb4d17558e7bfe1e2e6f081bbfbf1514496f | [
"MIT"
] | null | null | null | smn/src/obnsmn_event.cpp | sduerr85/OpenBuildNet | 126feb4d17558e7bfe1e2e6f081bbfbf1514496f | [
"MIT"
] | null | null | null | /* -*- mode: C++; indent-tabs-mode: nil; -*- */
/** \file
* \brief Implement the event objects in the Global Clock.
*
* This file is part of the openBuildNet simulation framework
* (OBN-Sim) developed at EPFL.
*
* \author Truong X. Nghiem (xuan.nghiem@epfl.ch)
*/
#include <obnsmn_gc.h>
#include <obnsmn_report.h>
bool OBNsmn::GCThread::gc_waitfor_process_ACK(const OBNSimMsg::N2SMN& msg, int ID) {
OBNSimMsg::N2SMN::MSGTYPE type = msg.msgtype();
std::lock_guard<std::mutex> lock(gc_waitfor_mutex);
if (gc_waitfor_status == GC_WAITFOR_RESULT_ERROR) { return true; }
if (gc_waitfor_status != GC_WAITFOR_RESULT_ACTIVE || gc_waitfor_type != type) {
report_warning(0, "Unexpected ACK received from node " + std::to_string(ID) + " with type " + std::to_string(type) +
" expecting type " + std::to_string(gc_waitfor_type));
return true;
}
if (gc_waitfor_predicate && !gc_waitfor_predicate(msg)) {
// Invalid ACK messasge
gc_waitfor_status = GC_WAITFOR_RESULT_ERROR;
mWakeupCondition.notify_all();
return true;
}
// This ACK message has been checked -> check it in the bit array
if (!gc_waitfor_bits[ID]) {
gc_waitfor_bits[ID] = true;
gc_waitfor_num--;
}
if (gc_waitfor_num == 0) {
gc_waitfor_status = GC_WAITFOR_RESULT_DONE;
mWakeupCondition.notify_all();
}
return true;
}
/** Except for ACK messages, this method dynamically create a new node event object from an N2SMN message and push it to the queue.
This method should be used to convert an N2SMN message to a node event because it also checks for the validity of the message and assigns a suitable category.
\param msg The N2SMN message object.
\param defaultID The default ID of the node that sent the message, to be used only if it's not included in the message itself or if the ID is overridden.
\param overrideID true if the message's ID is always overridden by defaultID; false if defaultID is only used if the message does not contain an ID.
\return true if successful.
*/
bool OBNsmn::GCThread::pushNodeEvent(const OBNSimMsg::N2SMN& msg, int defaultID, bool overrideID) {
int ID = overrideID?defaultID:(msg.has_id()?msg.id():defaultID);
bool hasID = msg.has_id() || overrideID;
OBNSimMsg::N2SMN::MSGTYPE type = msg.msgtype();
bool isNotSysMsg = static_cast<uint16_t>(type) >= 0x0100; // Not a system management message
// If this is not a system management message (i.e. if type >= 0x0100),
// check that the ID is valid, otherwise it may cause security problem
if (isNotSysMsg && (!hasID || ID > maxID || ID < 0)) {
report_warning(0, "Received message (type: " + std::to_string(type) + ") with an invalid ID (" + std::to_string(ID) + ").");
return false;
}
OBNsmn::SMNNodeEvent::EventCategory cat = OBNsmn::SMNNodeEvent::EVT_SYS;
if (isNotSysMsg) {
// In the switch-case, put the more frequent/typical cases first, to improve performance
switch (type) {
case OBNSimMsg::N2SMN::SIM_Y_ACK:
case OBNSimMsg::N2SMN::SIM_X_ACK:
case OBNSimMsg::N2SMN::SIM_INIT_ACK:
// pushEvent(new SMNNodeEvent(type, OBNsmn::SMNNodeEvent::EVT_ACK, ID));
// return true;
// Process wait-for here
return gc_waitfor_process_ACK(msg, ID);
// case OBNSimMsg::N2SMN::SIM_INIT_ACK:
// cat = OBNsmn::SMNNodeEvent::EVT_ACK;
// break;
default:
cat = OBNsmn::SMNNodeEvent::EVT_SIM;
}
}
// For complex events with attached data
OBNsmn::SMNNodeEvent* pe = new OBNsmn::SMNNodeEvent(type, cat, ID, hasID);
if (msg.has_data()) {
OBNSimMsg::MSGDATA data = msg.data();
if (data.has_b()) {
pe->has_b = 1;
pe->b = data.b();
}
if (data.has_t()) {
pe->has_t = 1;
pe->t = data.t();
}
if (data.has_i()) {
pe->has_i = 1;
pe->i = data.i();
}
}
pushEvent(pe);
return true;
}
| 38.816514 | 159 | 0.619239 | [
"object"
] |
514424cd7d15493c4636f4470daeddf64c858436 | 312 | cpp | C++ | source/render/material.cpp | biomorphs/lean | b28dac32b3aea0f0cf65e396a265c7b99aeb1fb0 | [
"MIT"
] | 1 | 2021-06-15T04:38:49.000Z | 2021-06-15T04:38:49.000Z | source/render/material.cpp | biomorphs/lean | b28dac32b3aea0f0cf65e396a265c7b99aeb1fb0 | [
"MIT"
] | null | null | null | source/render/material.cpp | biomorphs/lean | b28dac32b3aea0f0cf65e396a265c7b99aeb1fb0 | [
"MIT"
] | null | null | null | #include "material.h"
#include "core/string_hashing.h"
namespace Render
{
Material::Material()
{
}
Material::~Material()
{
}
void Material::SetSampler(std::string name, uint32_t handle)
{
const uint32_t hash = Core::StringHashing::GetHash(name.c_str());
m_samplers[hash] = { name, handle };
}
} | 14.857143 | 67 | 0.679487 | [
"render"
] |
51514ed22b17b88fddf0cfd231572867378971bd | 717 | cpp | C++ | Cpp/Kattis/DataStructure/bank.cpp | kchevali/OnlineJudge | c1d1894078fa45eef05c8785aba29758d9adf0c6 | [
"MIT"
] | null | null | null | Cpp/Kattis/DataStructure/bank.cpp | kchevali/OnlineJudge | c1d1894078fa45eef05c8785aba29758d9adf0c6 | [
"MIT"
] | null | null | null | Cpp/Kattis/DataStructure/bank.cpp | kchevali/OnlineJudge | c1d1894078fa45eef05c8785aba29758d9adf0c6 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
typedef long long l;
typedef pair<l, l> ll;
typedef priority_queue<ll, vector<ll>, less<ll>> pqll; // max first
int main() {
l n, t, money, endTime, x = 0;
cin >> n >> t;
l times[t];
memset(times, 0, sizeof times);
pqll q;
for (l i = 0; i < n; i++) {
cin >> money >> endTime;
q.push(make_pair(money, endTime));
}
while (!q.empty()) {
tie(money, endTime) = q.top();
q.pop();
l minIndex = -1, minValue = money;
for (l i = endTime; i >= 0; i--)
if (times[i] < minValue) minValue = times[minIndex = i];
if (minIndex == -1) continue;
x += money - times[minIndex];
times[minIndex] = money;
}
cout << x << "\n";
} | 24.724138 | 68 | 0.556485 | [
"vector"
] |
5153106d44054f5ee72fb4f5de88d9129565092c | 6,288 | cpp | C++ | 3rdparty/meshlab-master/src/meshlabplugins/edit_align/align/align_parameter.cpp | HoEmpire/slambook2 | 96d360f32aa5d8b5c5dcbbf9ee7ba865e84409f4 | [
"MIT"
] | 4 | 2016-03-30T14:31:52.000Z | 2019-02-02T05:01:32.000Z | graphics/meshlab/src/meshlabplugins/edit_align/align/align_parameter.cpp | hlzz/dotfiles | 0591f71230c919c827ba569099eb3b75897e163e | [
"BSD-3-Clause"
] | null | null | null | graphics/meshlab/src/meshlabplugins/edit_align/align/align_parameter.cpp | hlzz/dotfiles | 0591f71230c919c827ba569099eb3b75897e163e | [
"BSD-3-Clause"
] | null | null | null | /****************************************************************************
* VCGLib o o *
* Visual and Computer Graphics Library o o *
* _ O _ *
* Copyright(C) 2004 \/)\/ *
* Visual Computing Lab /\/| *
* ISTI - Italian National Research Council | *
* \ *
* 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; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License (http://www.gnu.org/licenses/gpl.txt) *
* for more details. *
* *
****************************************************************************/
#include "align_parameter.h"
using namespace vcg;
AlignParameter::AlignParameter(){}
// given a RichParameterSet get back the alignment parameter (dual of the buildParemeterSet)
void AlignParameter::RichParameterSetToAlignPairParam(const RichParameterSet &rps , AlignPair::Param &app)
{
app.SampleNum =rps.getInt( "SampleNum");
app.MinDistAbs =rps.getFloat("MinDistAbs");
app.TrgDistAbs =rps.getFloat("TrgDistAbs");
app.MaxIterNum =rps.getInt( "MaxIterNum");
app.SampleMode =rps.getBool( "SampleMode")?AlignPair::Param::SMNormalEqualized : AlignPair::Param::SMRandom;
app.ReduceFactorPerc=rps.getFloat("ReduceFactorPerc");
app.PassHiFilter =rps.getFloat("PassHiFilter");
app.MatchMode =rps.getBool( "MatchMode")? AlignPair::Param::MMRigid : AlignPair::Param::MMSimilarity;
}
// given an alignment parameter builds the corresponding RichParameterSet (dual of the retrieveParemeterSet)
void AlignParameter::AlignPairParamToRichParameterSet(const AlignPair::Param &app, RichParameterSet &rps)
{
rps.clear();
rps.addParam(new RichInt("SampleNum",app.SampleNum,"Sample Number","Number of samples that we try to choose at each ICP iteration"));
rps.addParam(new RichFloat("MinDistAbs",app.MinDistAbs,"Minimal Starting Distance","For all the chosen sample on one mesh we consider for ICP only the samples nearer than this value."
"If MSD is too large outliers could be included, if it is too small convergence will be very slow. "
"A good guess is needed here, suggested values are in the range of 10-100 times of the device scanning error."
"This value is also dynamically changed by the 'Reduce Distance Factor'"));
rps.addParam(new RichFloat("TrgDistAbs",app.TrgDistAbs,"Target Distance","When 50% of the chosen samples are below this distance we consider the two mesh aligned. Usually it should be a value lower than the error of the scanning device. "));
rps.addParam(new RichInt("MaxIterNum",app.MaxIterNum,"Max Iteration Num","The maximum number of iteration that the ICP is allowed to perform."));
rps.addParam(new RichBool("SampleMode",app.SampleMode == AlignPair::Param::SMNormalEqualized,"Normal Equalized Sampling","if true (default) the sample points of icp are choosen with a distribution uniform with respect to the normals of the surface. Otherwise they are distributed in a spatially uniform way."));
rps.addParam(new RichFloat("ReduceFactorPerc",app.ReduceFactorPerc,"MSD Reduce Factor","At each ICP iteration the Minimal Starting Distance is reduced to be 5 times the <Reduce Factor> percentile of the sample distances (e.g. if RF is 0.9 the new Minimal Starting Distance is 5 times the value <X> such that 90% of the sample lies at a distance lower than <X>."));
rps.addParam(new RichFloat("PassHiFilter",app.PassHiFilter,"Sample Cut High","At each ICP iteration all the sample that are farther than the <cuth high> percentile are discarded ( In practice we use only the <cut high> best results )."));
rps.addParam(new RichBool("MatchMode",app.MatchMode == AlignPair::Param::MMRigid,"Rigid matching","If true the ICP is cosntrained to perform matching only throug roto-translations (no scaling allowed). If false a more relaxed transformation matrix is allowed (scaling and shearing can appear)."));
}
void AlignParameter::RichParameterSetToMeshTreeParam(const RichParameterSet &fps , MeshTree::Param &mtp)
{
mtp.arcThreshold=fps.getFloat("arcThreshold");
mtp.OGSize = fps.getInt("OGSize");
mtp.recalcThreshold = fps.getFloat("recalcThreshold");
}
void AlignParameter::MeshTreeParamToRichParameterSet(const MeshTree::Param &mtp, RichParameterSet &rps)
{
rps.clear();
rps.addParam(new RichInt("OGSize",mtp.OGSize,"Occupancy Grid Size","To compute the overlap between range maps we discretize them into voxel and count them (both for area and overlap); This parameter affect the resolution of the voxelization process. Using a too fine voxelization can "));
rps.addParam(new RichFloat("arcThreshold",mtp.arcThreshold,"Arc Area Thr.","We run ICP on every pair of mesh with a relative overlap greather than this threshold. The relative overlap is computed as overlapArea / min(area1,area2)"));
rps.addParam(new RichFloat("recalcThreshold",mtp.recalcThreshold,"Recalc Fraction","Every time we start process we discard the <recalc> fraction of all the arcs in order to recompute them and hopefully improve the final result. It corresponds to iteratively recalc the bad arcs."));
}
| 82.736842 | 366 | 0.637087 | [
"mesh"
] |
5153f28d67533d90a7df3f3c88353f509449983f | 5,338 | cpp | C++ | examples/subscriber.cpp | jgriffiths/autobahn-cpp | 781686678d9606e77ad12cf79ba85aadf4e3d63d | [
"BSL-1.0"
] | 187 | 2015-10-16T11:48:25.000Z | 2022-02-08T04:45:30.000Z | examples/subscriber.cpp | jgriffiths/autobahn-cpp | 781686678d9606e77ad12cf79ba85aadf4e3d63d | [
"BSL-1.0"
] | 170 | 2015-10-11T19:34:40.000Z | 2022-03-31T18:31:43.000Z | examples/subscriber.cpp | jgriffiths/autobahn-cpp | 781686678d9606e77ad12cf79ba85aadf4e3d63d | [
"BSL-1.0"
] | 96 | 2015-10-24T05:06:57.000Z | 2022-02-06T03:02:09.000Z | ///////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) Crossbar.io Technologies GmbH and contributors
//
// Boost Software License - Version 1.0 - August 17th, 2003
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
///////////////////////////////////////////////////////////////////////////////
#include "parameters.hpp"
#include <autobahn/autobahn.hpp>
#include <boost/asio.hpp>
#include <iostream>
#include <memory>
#include <tuple>
void on_topic1(const autobahn::wamp_event& event)
{
std::cerr << "received event: " << event->argument<std::string>(0) << std::endl;
}
int main(int argc, char** argv)
{
std::cerr << "Boost: " << BOOST_VERSION << std::endl;
try {
auto parameters = get_parameters(argc, argv);
std::cerr << "Connecting to realm: " << parameters->realm() << std::endl;
boost::asio::io_service io;
bool debug = parameters->debug();
auto transport = std::make_shared<autobahn::wamp_tcp_transport>(
io, parameters->rawsocket_endpoint(), debug);
// create a WAMP session that talks WAMP-RawSocket over TCP
//
auto session = std::make_shared<autobahn::wamp_session>(io, debug);
transport->attach(std::static_pointer_cast<autobahn::wamp_transport_handler>(session));
// Make sure the continuation futures we use do not run out of scope prematurely.
// Since we are only using one thread here this can cause the io service to block
// as a future generated by a continuation will block waiting for its promise to be
// fulfilled when it goes out of scope. This would prevent the session from receiving
// responses from the router.
boost::future<void> connect_future;
boost::future<void> start_future;
boost::future<void> join_future;
boost::future<void> subscribe_future;
connect_future = transport->connect().then([&](boost::future<void> connected) {
try {
connected.get();
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
io.stop();
return;
}
std::cerr << "transport connected" << std::endl;
start_future = session->start().then([&](boost::future<void> started) {
try {
started.get();
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
io.stop();
return;
}
std::cerr << "session started" << std::endl;
join_future = session->join(parameters->realm()).then([&](boost::future<uint64_t> joined) {
try {
std::cerr << "joined realm: " << joined.get() << std::endl;
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
io.stop();
return;
}
subscribe_future = session->subscribe("com.examples.subscriptions.topic1", &on_topic1).then([&] (boost::future<autobahn::wamp_subscription> subscribed)
{
try {
std::cerr << "subscribed to topic: " << subscribed.get().id() << std::endl;
}
catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
io.stop();
return;
}
});
});
});
});
std::cerr << "starting io service" << std::endl;
io.run();
std::cerr << "stopped io service" << std::endl;
}
catch (std::exception& e) {
std::cerr << "exception: " << e.what() << std::endl;
return 1;
}
return 0;
}
| 39.835821 | 171 | 0.558262 | [
"object"
] |
51541d6d12bd8b39df593acc1f4e16331ed30041 | 2,516 | cpp | C++ | ScreenShot/FlameShot/utilitypanel.cpp | YIXINSHUWU/QtScreenShot | 8dda54fb1a1568f26466a0a2e866db05a36d5e54 | [
"Apache-2.0"
] | null | null | null | ScreenShot/FlameShot/utilitypanel.cpp | YIXINSHUWU/QtScreenShot | 8dda54fb1a1568f26466a0a2e866db05a36d5e54 | [
"Apache-2.0"
] | null | null | null | ScreenShot/FlameShot/utilitypanel.cpp | YIXINSHUWU/QtScreenShot | 8dda54fb1a1568f26466a0a2e866db05a36d5e54 | [
"Apache-2.0"
] | null | null | null |
#include "utilitypanel.h"
#include <QPropertyAnimation>
#include <QVBoxLayout>
#include <QTimer>
#include <QScrollArea>
#include <QWheelEvent>
UtilityPanel::UtilityPanel(QWidget *parent) : QWidget(parent) {
initInternalPanel();
setAttribute(Qt::WA_TransparentForMouseEvents);
setCursor(Qt::ArrowCursor);
m_showAnimation = new QPropertyAnimation(m_internalPanel, "geometry", this);
m_showAnimation->setEasingCurve(QEasingCurve::InOutQuad);
m_showAnimation->setDuration(300);
m_hideAnimation = new QPropertyAnimation(m_internalPanel, "geometry", this);
m_hideAnimation->setEasingCurve(QEasingCurve::InOutQuad);
m_hideAnimation->setDuration(300);
connect(m_hideAnimation, &QPropertyAnimation::finished,
m_internalPanel, &QWidget::hide);
}
QWidget *UtilityPanel::toolWidget() const {
return m_toolWidget;
}
void UtilityPanel::addToolWidget(QWidget *w) {
if (m_toolWidget) {
m_toolWidget->deleteLater();
}
if (w) {
m_toolWidget = w;
m_upLayout->addWidget(w);
}
}
void UtilityPanel::clearToolWidget() {
if (m_toolWidget) {
m_toolWidget->deleteLater();
}
}
void UtilityPanel::pushWidget(QWidget *w) {
m_layout->addWidget(w);
}
void UtilityPanel::toggle() {
if (m_internalPanel->isHidden()) {
setAttribute(Qt::WA_TransparentForMouseEvents, false);
m_showAnimation->setStartValue(QRect(-width(), 0, 0, height()));
m_showAnimation->setEndValue(QRect(0, 0, width(), height()));
m_internalPanel->show();
m_showAnimation->start();
} else {
setAttribute(Qt::WA_TransparentForMouseEvents);
m_hideAnimation->setStartValue(QRect(0, 0, width(), height()));
m_hideAnimation->setEndValue(QRect(-width(), 0, 0, height()));
m_hideAnimation->start();
}
}
void UtilityPanel::initInternalPanel() {
m_internalPanel = new QScrollArea(this);
m_internalPanel->setAttribute(Qt::WA_NoMousePropagation);
QWidget *widget = new QWidget();
m_internalPanel->setWidget(widget);
m_internalPanel->setWidgetResizable(true);
m_layout = new QVBoxLayout();
m_upLayout = new QVBoxLayout();
m_layout->addLayout(m_upLayout);
widget->setLayout(m_layout);
QColor bgColor = palette().background().color();
bgColor.setAlphaF(0.0);
m_internalPanel->setStyleSheet(QStringLiteral("QScrollArea {background-color: %1}")
.arg(bgColor.name()));
m_internalPanel->hide();
}
| 29.952381 | 87 | 0.683227 | [
"geometry"
] |
51541de57cd2ce0a9d1c8d3a6013ffa00428fd0f | 7,293 | hpp | C++ | inference-engine/src/mkldnn_plugin/utils/bfloat16.hpp | tkrupa-intel/openvino | 8c0ff5d9065486d23901a9c27debd303661f465f | [
"Apache-2.0"
] | 1 | 2022-01-19T15:36:45.000Z | 2022-01-19T15:36:45.000Z | inference-engine/src/mkldnn_plugin/utils/bfloat16.hpp | tkrupa-intel/openvino | 8c0ff5d9065486d23901a9c27debd303661f465f | [
"Apache-2.0"
] | 22 | 2021-02-03T12:41:51.000Z | 2022-02-21T13:04:48.000Z | inference-engine/src/mkldnn_plugin/utils/bfloat16.hpp | tkrupa-intel/openvino | 8c0ff5d9065486d23901a9c27debd303661f465f | [
"Apache-2.0"
] | null | null | null | // Copyright (C) 2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#pragma once
#include <cmath>
#include <limits>
#include "nodes/common/emitter.h"
/**
* The bfloat16_t class can be used as an arithmetic type. All arithmetic operations goes through conversion to the float data type.
*/
#define BFLOAT16_ROUND_MODE_TO_NEAREST_EVEN
namespace MKLDNNPlugin {
class bfloat16_t {
public:
constexpr bfloat16_t()
: m_value{0}
{
}
bfloat16_t(float value) noexcept
: m_value{
#if defined BFLOAT16_ROUND_MODE_TO_NEAREST
round_to_nearest(value)
#elif defined BFLOAT16_ROUND_MODE_TO_NEAREST_EVEN
round_to_nearest_even(value)
#elif defined BFLOAT16_ROUND_MODE_TRUNCATE
truncate(value)
#else
#error \
"ROUNDING_MODE must be one of BFLOAT16_ROUND_MODE_TO_NEAREST, BFLOAT16_ROUND_MODE_TO_NEAREST_EVEN, or BFLOAT16_ROUND_MODE_TRUNCATE"
#endif
}
{
}
operator float() const {
return F32{uint32_t(m_value) << 16}.vfloat;
}
static constexpr bfloat16_t from_bits(uint16_t bits) { return bfloat16_t(bits, true); }
uint16_t to_bits() const { return m_value; }
static inline uint16_t round_to_nearest_even(float x) {
return static_cast<uint16_t>((F32(x).vint + ((F32(x).vint & 0x00010000) >> 1)) >> 16);
}
static inline uint16_t round_to_nearest(float x) {
return static_cast<uint16_t>((F32(x).vint + 0x8000) >> 16);
}
static inline uint16_t truncate(float x) { return static_cast<uint16_t>((F32(x).vint) >> 16); }
private:
constexpr bfloat16_t(uint16_t x, bool)
: m_value{x}
{
}
union alignas(16) F32 {
F32(float val)
: vfloat{val} {
}
F32(uint32_t val)
: vint{val} {
}
float vfloat;
uint32_t vint;
};
uint16_t m_value;
};
class jit_emu_vcvtneps2bf16 : public jit_emitter {
public:
jit_emu_vcvtneps2bf16(mkldnn::impl::cpu::x64::jit_generator* host, mkldnn::impl::cpu::x64::cpu_isa_t host_isa, const MKLDNNNode* node,
InferenceEngine::Precision exec_prc = InferenceEngine::Precision::BF16) : jit_emitter(host, host_isa, node, exec_prc) {
prepare_table();
};
size_t get_inputs_num() { return 1; };
private:
void emit_impl(const std::vector<size_t>& in_vec_idxs, const std::vector<size_t>& out_vec_idxs,
const std::vector<size_t>& pool_vec_idxs, const std::vector<size_t>& pool_gpr_idxs) {
if (host_isa_ == mkldnn::impl::cpu::x64::cpu_isa_t::avx512_common) {
Xbyak::Zmm in = Xbyak::Zmm(in_vec_idxs[0]);
Xbyak::Ymm out = Xbyak::Ymm(out_vec_idxs[0]);
Xbyak::Zmm aux = Xbyak::Zmm(aux_vec_idxs[0]);
Xbyak::Zmm aux1 = Xbyak::Zmm(aux_vec_idxs[1]);
h->uni_vpsrld(aux, in, 16);
h->vpandd(aux, aux, table_val("one"));
h->uni_vmovups(aux1, table_val("even"));
h->uni_vpaddd(aux, aux1, aux);
h->uni_vpaddd(aux, in, aux);
h->vfixupimmps(aux, in, table_val("selector"), 0);
h->vpsrad(aux, aux, 16);
h->vpmovdw(out, aux);
} else {
assert(!"unsupported isa");
}
};
inline int encode_fixup_selector(int input, int output) {
return ((output) << (4 * (input)));
}
void register_table_entries() {
enum {
fixup_input_code_qnan_ = 0,
fixup_input_code_snan_ = 1,
fixup_input_code_ninf_ = 4,
fixup_input_code_pinf_ = 5,
fixup_output_code_copy_input_ = 1,
fixup_output_code_qnan_input_ = 2,
};
const int selector_int32 =
/* qnan input to qnan output (presenrving input bits 0..21) */
encode_fixup_selector(fixup_input_code_snan_, fixup_output_code_qnan_input_) |
/* snan input to qnan output (presenrving input bits 0..21) */
encode_fixup_selector(fixup_input_code_qnan_, fixup_output_code_qnan_input_) |
/* neg inf input copied to output */
encode_fixup_selector(fixup_input_code_ninf_, fixup_output_code_copy_input_) |
/* pos inf input copied to output */
encode_fixup_selector(fixup_input_code_pinf_, fixup_output_code_copy_input_);
push_arg_entry_of("one", 0x00000001, true);
push_arg_entry_of("even", 0x00007fff, true);
push_arg_entry_of("selector", selector_int32, true);
}
size_t aux_vecs_count() const { return 2; }
};
} // namespace MKLDNNPlugin
/**
* std::numeric_limits overloaded for better compatibility with template metaprogramming.
* For example, to make the following template work:
* template <typename T>
* void someFunction() {
* ...
* T maxValue = std::numeric_limits<T>::max();
* ...
* }
*/
namespace std {
template <>
class numeric_limits<MKLDNNPlugin::bfloat16_t> {
public:
static constexpr bool is_specialized = true;
static constexpr MKLDNNPlugin::bfloat16_t min() noexcept {
return MKLDNNPlugin::bfloat16_t::from_bits(0x007F);
}
static constexpr MKLDNNPlugin::bfloat16_t max() noexcept {
return MKLDNNPlugin::bfloat16_t::from_bits(0x7F7F);
}
static constexpr MKLDNNPlugin::bfloat16_t lowest() noexcept {
return MKLDNNPlugin::bfloat16_t::from_bits(0xFF7F);
}
static constexpr int digits = 7;
static constexpr int digits10 = 2;
static constexpr bool is_signed = true;
static constexpr bool is_integer = false;
static constexpr bool is_exact = false;
static constexpr int radix = 2;
static constexpr MKLDNNPlugin::bfloat16_t epsilon() noexcept {
return MKLDNNPlugin::bfloat16_t::from_bits(0x3C00);
}
static constexpr MKLDNNPlugin::bfloat16_t round_error() noexcept {
return MKLDNNPlugin::bfloat16_t::from_bits(0x3F00);
}
static constexpr int min_exponent = -125;
static constexpr int min_exponent10 = -37;
static constexpr int max_exponent = 128;
static constexpr int max_exponent10 = 38;
static constexpr bool has_infinity = true;
static constexpr bool has_quiet_NaN = true;
static constexpr bool has_signaling_NaN = true;
static constexpr float_denorm_style has_denorm = denorm_absent;
static constexpr bool has_denorm_loss = false;
static constexpr MKLDNNPlugin::bfloat16_t infinity() noexcept {
return MKLDNNPlugin::bfloat16_t::from_bits(0x7F80);
}
static constexpr MKLDNNPlugin::bfloat16_t quiet_NaN() noexcept {
return MKLDNNPlugin::bfloat16_t::from_bits(0x7FC0);
}
static constexpr MKLDNNPlugin::bfloat16_t signaling_NaN() noexcept {
return MKLDNNPlugin::bfloat16_t::from_bits(0x7FC0);
}
static constexpr MKLDNNPlugin::bfloat16_t denorm_min() noexcept {
return MKLDNNPlugin::bfloat16_t::from_bits(0);
}
static constexpr bool is_iec559 = false;
static constexpr bool is_bounded = false;
static constexpr bool is_modulo = false;
static constexpr bool traps = false;
static constexpr bool tinyness_before = false;
static constexpr float_round_style round_style = round_to_nearest;
};
} // namespace std
| 35.231884 | 138 | 0.658988 | [
"vector"
] |
5158394d1ba54e96098f99a4375e906e42f38f4f | 612 | cpp | C++ | codility/odd_occurance_in_array.cpp | Anil8753/DS-Algo | 4bb6699460f01e119e3de835661734bfb6666773 | [
"MIT"
] | null | null | null | codility/odd_occurance_in_array.cpp | Anil8753/DS-Algo | 4bb6699460f01e119e3de835661734bfb6666773 | [
"MIT"
] | null | null | null | codility/odd_occurance_in_array.cpp | Anil8753/DS-Algo | 4bb6699460f01e119e3de835661734bfb6666773 | [
"MIT"
] | null | null | null |
#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
int solution(vector<int> &A)
{
std::unordered_map<int, int> table;
for (const auto &n : A)
{
table[n] = table[n] + 1;
}
for (const auto &pair : table)
{
const int count = pair.second;
if (count % 2)
{
return pair.first;
}
}
return 0;
}
int main()
{
std::vector<int> v = {1,
1,
2,
2,
3};
std::cout << solution(v);
return 0;
} | 17.485714 | 39 | 0.428105 | [
"vector"
] |
515a8969e724a5c45e4d5210cfa47462a065b901 | 6,710 | cpp | C++ | src/common/transformations/src/transformations/common_optimizations/shuffle_channels_fusion.cpp | ytorzuk-altran/openvino | 68d460a3bb578a738ba0e4d0e1f2e321afa73ab0 | [
"Apache-2.0"
] | 1 | 2020-05-25T17:10:22.000Z | 2020-05-25T17:10:22.000Z | inference-engine/src/transformations/src/transformations/common_optimizations/shuffle_channels_fusion.cpp | thomas-yanxin/openvino | 031e998a15ec738c64cc2379d7f30fb73087c272 | [
"Apache-2.0"
] | 55 | 2020-11-16T09:55:29.000Z | 2022-03-28T13:18:15.000Z | inference-engine/src/transformations/src/transformations/common_optimizations/shuffle_channels_fusion.cpp | thomas-yanxin/openvino | 031e998a15ec738c64cc2379d7f30fb73087c272 | [
"Apache-2.0"
] | 4 | 2021-09-29T20:44:49.000Z | 2021-10-20T13:02:12.000Z | // Copyright (C) 2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "transformations/common_optimizations/shuffle_channels_fusion.hpp"
#include "itt.hpp"
#include <memory>
#include <vector>
#include <ngraph/opsets/opset6.hpp>
#include <ngraph/pattern/op/wrap_type.hpp>
#include <ngraph/rt_info.hpp>
namespace {
bool check_shapes(const ngraph::Shape& shape_input, const ngraph::Shape& shape_reshape_before,
const ngraph::AxisVector& transpose_constant_values, const ngraph::Shape& shape_reshape_after) {
// x: [N, C, H, W]
bool is_transformation_valid = (shape_input.size() == 4);
// x'= reshape(x, [N, group, C / group, H * W]) or reshape(x, [N, group, C / group, H, W])
bool is_reshape_before_valid = (shape_reshape_before.size() == 4 || shape_reshape_before.size() == 5);
if (is_reshape_before_valid) {
size_t group = shape_reshape_before[1];
ngraph::Shape expected_reshape_before = { shape_input[0], group, shape_input[1] / group };
if (shape_reshape_before.size() == 4) {
expected_reshape_before.push_back(shape_input[2] * shape_input[3]);
} else {
expected_reshape_before.push_back(shape_input[2]);
expected_reshape_before.push_back(shape_input[3]);
}
is_reshape_before_valid &= (expected_reshape_before == shape_reshape_before);
}
// x''= transpose(x', [0, 2, 1, 3]) or transpose(x', [0, 2, 1, 3, 4])
bool is_transpose_valid = (transpose_constant_values.size() == 4 || transpose_constant_values.size() == 5);
if (is_transpose_valid) {
ngraph::AxisVector expected_transpose_values{ 0, 2, 1, 3 };
if (transpose_constant_values.size() == 5) {
expected_transpose_values.push_back(4);
}
is_transpose_valid &= (expected_transpose_values == transpose_constant_values);
}
// y = reshape(x'', [N, C, H, W])
bool is_reshape_after_valid = (shape_input == shape_reshape_after);
is_transformation_valid &= is_reshape_before_valid & is_transpose_valid & is_reshape_after_valid;
return is_transformation_valid;
}
} // namespace
NGRAPH_RTTI_DEFINITION(ngraph::pass::ShuffleChannelsFusion, "ShuffleChannelsFusion", 0);
ngraph::pass::ShuffleChannelsFusion::ShuffleChannelsFusion(const bool reshape_constants_check) {
MATCHER_SCOPE(ShuffleChannelsFusion);
auto has_static_4d_shape = [](const Output<Node>& output) {
return pattern::has_static_shape()(output) && pattern::rank_equals(4)(output);
};
auto input = ngraph::pattern::any_input(has_static_4d_shape);
auto reshape_before_const_pattern = ngraph::pattern::wrap_type<ngraph::opset6::Constant>();
auto transpose_const_pattern = ngraph::pattern::wrap_type<ngraph::opset6::Constant>();
auto reshape_after_const_pattern = ngraph::pattern::wrap_type<ngraph::opset6::Constant>();
auto has_static_shape_and_single_consumer = [](const Output<Node>& output) {
return pattern::has_static_shape()(output) && pattern::consumers_count(1)(output);
};
auto reshape_before_pattern = ngraph::pattern::wrap_type<ngraph::opset6::Reshape>({input, reshape_before_const_pattern},
has_static_shape_and_single_consumer);
auto transpose_pattern = ngraph::pattern::wrap_type<ngraph::opset6::Transpose>({reshape_before_pattern, transpose_const_pattern},
has_static_shape_and_single_consumer);
auto reshape_after_pattern = ngraph::pattern::wrap_type<ngraph::opset6::Reshape>({transpose_pattern, reshape_after_const_pattern},
pattern::has_static_shape());
ngraph::matcher_pass_callback callback = [=](pattern::Matcher& m) {
const auto& pattern_map = m.get_pattern_value_map();
auto data = pattern_map.at(input);
auto reshape_before = std::dynamic_pointer_cast<ngraph::opset6::Reshape>(pattern_map.at(reshape_before_pattern).get_node_shared_ptr());
auto transpose = std::dynamic_pointer_cast<ngraph::opset6::Transpose>(pattern_map.at(transpose_pattern).get_node_shared_ptr());
auto reshape_after = std::dynamic_pointer_cast<ngraph::opset6::Reshape>(pattern_map.at(reshape_after_pattern).get_node_shared_ptr());
if (!reshape_after || !transpose || !reshape_after)
return false;
if (reshape_constants_check) {
auto reshape_before_constant = std::dynamic_pointer_cast<ngraph::opset6::Constant>(
pattern_map.at(reshape_before_const_pattern).get_node_shared_ptr());
auto reshape_after_constant = std::dynamic_pointer_cast<ngraph::opset6::Constant>(
pattern_map.at(reshape_after_const_pattern).get_node_shared_ptr());
if (!reshape_before_constant || !reshape_after_constant)
return false;
const auto& reshape_before_values = reshape_before_constant->cast_vector<int64_t>();
const auto& reshape_after_values = reshape_after_constant->cast_vector<int64_t>();
if (std::any_of(reshape_before_values.cbegin(), reshape_before_values.cend(), [](const int64_t& value) { return value == -1; }) ||
std::any_of(reshape_after_values.cbegin(), reshape_after_values.cend(), [](const int64_t& value) { return value == -1; })) {
return false;
}
}
auto shape_input = reshape_before->get_input_shape(0);
auto shape_reshape_before = reshape_before->get_output_shape(0);
auto shape_reshape_after = reshape_after->get_output_shape(0);
auto transpose_constant = std::dynamic_pointer_cast<ngraph::opset6::Constant>(pattern_map.at(transpose_const_pattern).get_node_shared_ptr());
auto transpose_constant_values = transpose_constant->get_axis_vector_val();
if (!check_shapes(shape_input, shape_reshape_before, transpose_constant_values, shape_reshape_after))
return false;
int64_t axis = 1ul;
int64_t group = shape_reshape_before[1];
auto shuffle_shannels = std::make_shared<ngraph::opset6::ShuffleChannels>(data, axis, group);
shuffle_shannels->set_friendly_name(reshape_after->get_friendly_name());
ngraph::copy_runtime_info({ reshape_before, transpose, reshape_after }, shuffle_shannels);
ngraph::replace_node(reshape_after, shuffle_shannels);
return true;
};
auto m = std::make_shared<ngraph::pattern::Matcher>(reshape_after_pattern, matcher_name);
register_matcher(m, callback);
}
| 51.615385 | 149 | 0.683905 | [
"shape",
"vector"
] |
515e80b43f90cdb8ad779ad56c3c99307c6e6b57 | 5,232 | hpp | C++ | src/feature_based_method/libImage/image_io.hpp | pariasm/estadeo-seq | 2198df08b50cc7f4fc1fdbf43387eb166e3627ac | [
"BSD-2-Clause"
] | null | null | null | src/feature_based_method/libImage/image_io.hpp | pariasm/estadeo-seq | 2198df08b50cc7f4fc1fdbf43387eb166e3627ac | [
"BSD-2-Clause"
] | null | null | null | src/feature_based_method/libImage/image_io.hpp | pariasm/estadeo-seq | 2198df08b50cc7f4fc1fdbf43387eb166e3627ac | [
"BSD-2-Clause"
] | null | null | null | // Copyright (c) 2007-2011 libmv authors.
//
// 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 LIBS_IMAGE_IMAGE_IMAGE_IO_H
#define LIBS_IMAGE_IMAGE_IMAGE_IO_H
#include "libImage/image.hpp"
#include "libImage/image_converter.hpp"
#include "libImage/pixelTypes.hpp"
#include <vector>
namespace libs {
typedef unsigned char uchar;
typedef Image<uchar> ByteImage;
enum Format {
Pnm, Png, Jpg, Unknown
};
Format GetFormat(const char *c);
/// Try to load the given file in the image<T> image.
template<class T>
int ReadImage(const char *, Image<T> *);
/// Open an png image with unsigned char as memory target.
/// The memory point must be null as input.
int ReadImage(const char *, std::vector<unsigned char> *, int * w, int * h, int * depth);
int ReadPng(const char *, std::vector<unsigned char> *, int * w, int * h, int * depth);
int ReadPngStream(FILE *, std::vector<unsigned char> *, int * w, int * h, int * depth);
template<class T>
int WriteImage(const char *, const Image<T> &);
int WriteImage(const char *, const std::vector<unsigned char> & array, int w, int h, int depth);
int WritePng(const char *, const std::vector<unsigned char> & array, int w, int h, int depth);
int WritePngStream(FILE *, const std::vector<unsigned char> & array, int w, int h, int depth);
template<class T>
int WriteJpg(const char *, const Image<T> &, int quality=90);
int WriteJpg(const char *, const std::vector<unsigned char> & array, int w, int h, int depth, int quality=90);
int WriteJpgStream(FILE *, const std::vector<unsigned char> & array, int w, int h, int depth, int quality=90);
/// Open a jpg image with unsigned char as memory target.
/// The memory point must be null as input.
int ReadJpg(const char *, std::vector<unsigned char> *, int * w, int * h, int * depth);
int ReadJpgStream(FILE *, std::vector<unsigned char> *, int * w, int * h, int * depth);
int ReadPnm(const char *, std::vector<unsigned char> *, int * w, int * h, int * depth);
int ReadPnmStream(FILE *, std::vector<unsigned char> *, int * w, int * h, int * depth);
int WritePnm(const char *, const std::vector<unsigned char> & array, int w, int h, int depth);
int WritePnmStream(FILE *, const std::vector<unsigned char> & array, int w, int h, int depth);
template<>
inline int ReadImage(const char * path, Image<unsigned char> * im)
{
std::vector<unsigned char> ptr;
int w, h, depth;
int res = ReadImage(path, &ptr, &w, &h, &depth);
if (res == 1) {
if(depth == 1)
{
(*im) = Image<unsigned char>(w, h, &ptr[0]);
} else if(depth == 3)
{
Image<RGBColor> color(w, h, (const RGBColor*) &ptr[0]);
convertImage(color, im);
} else
res = 0; // Do not know how to convert to gray
}
return res;
}
template<>
inline int ReadImage(const char * path, Image<RGBColor> * im)
{
std::vector<unsigned char> ptr;
int w, h, depth;
int res = ReadImage(path, &ptr, &w, &h, &depth);
if (res == 1) {
if(depth == 3)
{
(*im) = Image<RGBColor>(w, h, (const RGBColor*) &ptr[0]);
} else if(depth == 1)
{
Image<unsigned char> gray(w, h, &ptr[0]);
convertImage(gray, im);
} else
res = 0; // Do not know how to convert to color
}
return res;
}
//--------
//-- Image Writing
//--------
template<class T>
int WriteImage(const char * filename, const Image<T> & im)
{
const unsigned char * ptr = (unsigned char*)(im.data());
int depth = sizeof( T ) / sizeof(unsigned char);
std::vector<unsigned char> array( ptr , ptr + im.Width()*im.Height()*depth );
const int w = static_cast<int>( im.Width() );
const int h = static_cast<int>( im.Height());
int res = WriteImage(filename, array, w, h, depth);
return res;
}
template<class T>
int WriteJpg(const char * filename, const Image<T> & im, int quality)
{
const unsigned char * ptr = (unsigned char*)(im.data());
const int w = static_cast<int>( im.Width() );
const int h = static_cast<int>( im.Height());
const int depth = sizeof( T ) / sizeof(unsigned char);
std::vector<unsigned char> array( ptr , ptr + w*h*depth );
int res = WriteJpg(filename, array, w, h, depth, quality);
return res;
}
} // namespace libs
#endif // LIBS_IMAGE_IMAGE_IMAGE_IO_H
| 33.754839 | 110 | 0.675076 | [
"vector"
] |
516154effcf8ea1a78095a43d40bacc59777cb7d | 14,430 | cpp | C++ | example.cpp | ivere27/SimpleCertificateManager | 23534547e9d2ac220a8db7492a6e14f9dba75ec8 | [
"MIT"
] | 6 | 2018-01-05T03:30:58.000Z | 2021-03-08T01:00:08.000Z | example.cpp | ivere27/SimpleCertificateManager | 23534547e9d2ac220a8db7492a6e14f9dba75ec8 | [
"MIT"
] | null | null | null | example.cpp | ivere27/SimpleCertificateManager | 23534547e9d2ac220a8db7492a6e14f9dba75ec8 | [
"MIT"
] | 3 | 2018-10-01T07:44:31.000Z | 2020-12-10T11:13:21.000Z | #include <iostream>
#include <fstream>
#include <vector>
#include "SimpleCertificateManager.hpp"
using namespace std;
using namespace certificate;
std::string get_file_contents(const char *filename)
{
std::ifstream in(filename, std::ios::in | std::ios::binary);
if (in) {
std::string contents;
in.seekg(0, std::ios::end);
contents.resize(in.tellg());
in.seekg(0, std::ios::beg);
in.read(&contents[0], contents.size());
in.close();
return (contents);
}
throw (errno);
}
int main() {
#ifdef TEST_BRUTEFORCE_PASSPHRASE_PEM
try {
string pem = Key(2048, "aes256", "zz").getPrivateKeyString(); // passphrase 'zz'
vector<string> elements;
for (char i = 'a';i <='z';i++)
elements.push_back(string(1, i));
int start = pow(elements.size(),1); // 2 length
int end = start + pow(elements.size(),2) - 1; // 2 length
string passphrase = Key().bruteforcePassphrase(pem,
FORMAT_PEM,
elements,
start,
end);
if (!passphrase.empty())
cout << "found! " << passphrase << endl;
} catch(std::exception const& e) {
cout << e.what();
}
return 0;
#endif //TEST_BRUTEFORCE_PASSPHRASE_PEM
#ifdef TEST_BRUTEFORCE_PASSPHRASE_PKCS12
try {
string pkcs12 = Key(2048, "aes256").getPkcs12("zz"); // passphrase 'zz'
vector<string> elements;
for (char i = 'a';i <='z';i++)
elements.push_back(string(1, i));
int start = pow(elements.size(),1); // 2 length
int end = start + pow(elements.size(),2) - 1; // 2 length
string passphrase = Key().bruteforcePassphrase(pkcs12,
FORMAT_PKCS12,
elements,
start,
end);
if (!passphrase.empty())
cout << "found! " << passphrase << endl;
} catch(std::exception const& e) {
cout << e.what();
}
return 0;
#endif //TEST_BRUTEFORCE_PASSPHRASE_PEM
#ifdef TEST_LOAD_CERTIFICATE_DER
// ./openssl x509 -outform der -in rootca.crt -out rootca.crt.der
try {
Key key = Key();
key.loadCertificate(get_file_contents("rootca.crt.der"), FORMAT_DER);
cout << key.getCertificatePrint() << endl;
cout << key.getCertificateKeyIdentifier() << endl;
cout << key.getPublicKeyIdentifier() << endl;
cout << "length : " << key.length() << endl;
ofstream certCrt("rootca.crt.der2");
certCrt << key.getCertificateEncoded();
certCrt.close();
} catch(std::exception const& e) {
cout << e.what();
}
return 0;
#endif // TEST_LOAD_CERTIFICATE_DER
#ifdef TEST_LOAD_PRIVATE_KEY_DER
// ./openssl rsa -in rootca.key -out rootca.der -outform DER
try {
Key key = Key(get_file_contents("rootca.der"), "", FORMAT_DER);
cout << key.getPrivateKeyString() << endl;
cout << key.getPrivateKeyPrint() << endl;
cout << key.getPrivateKeyIdentifier() << endl;
ofstream certCrt("rootca.der2");
certCrt << key.getPrivateKeyEncoded();
certCrt.close();
} catch(std::exception const& e) {
cout << e.what();
}
return 0;
#endif
#ifdef TEST_LOAD_PKCS12
// ./openssl pkcs12 -export -in rootca.crt -inkey rootca.key -out root.p12
// ./openssl pkcs12 -export -in cert.crt -inkey cert.key -certfile rootca.crt -out file.p12
try {
Key key = Key(get_file_contents("file.p12"), "", FORMAT_PKCS12);
cout << key.getPrivateKeyString() << endl;
cout << key.getPrivateKeyPrint() << endl;
cout << key.getPrivateKeyIdentifier() << endl;
cout << key.getCertificateString() << endl;
cout << key.getCertificatePrint() << endl;
cout << key.getCertificateIdentifier() << endl;
cout << key.getCertificateKeyIdentifier() << endl;
// add another certificate
key.addCertificateAuthority(get_file_contents("GoogleInternetAuthorityG2.crt"));
cout << key.getCertificateAuthoritiesString() << endl;
// openssl pkcs12 -info -in temp.p12
string pkcs12 = key.getPkcs12("dory");
ofstream p12file("temp.p12");
p12file << pkcs12;
p12file.close();
} catch(std::exception const& e) {
cout << e.what();
}
return 0;
#endif // TEST_LOAD_PKCS12
#ifdef TEST_PRIVATE_KEY_PASSPHRASE
try {
Key key = Key(2048, "aes256", "dory");
string pem = key.getPrivateKeyString();
cout << pem << endl;
cout << key.getPrivateKeyIdentifier() << endl;
Key key2 = Key(pem.c_str(), "dory");
cout << key2.getPrivateKeyIdentifier() << endl;
key2.resetPrivateKeyPassphrase();
cout << key2.getPrivateKeyString() << endl;
cout << key2.getPrivateKeyIdentifier() << endl;
key2.resetPrivateKeyPassphrase("aes256", "dory");
cout << key2.getPrivateKeyString() << endl;
cout << key2.getPrivateKeyIdentifier() << endl;
} catch(std::exception const& e) {
cout << e.what();
}
return 0;
#endif // TEST_PRIVATE_KEY_PASSPHRASE
#ifdef TEST_PRIVATE_KEY_IDENTIFIER_FILE
try {
Key key = Key(get_file_contents("rootca.key"), "dory");
cout << key.getPrivateKeyString() << endl;
cout << key.getPrivateKeyPrint() << endl;
cout << key.getPrivateKeyIdentifier() << endl;
} catch(std::exception const& e) {
cout << e.what();
}
return 0;
#endif // TEST_PRIVATE_KEY_IDENTIFIER_FILE
#ifdef TEST_PRIVATE_KEY_IDENTIFIER
// openssl pkcs8 -in rootca.key -inform PEM -outform DER -topk8 -nocrypt | openssl sha1 -c
try {
Key key = Key(2048, "aes256", "dory");
cout << key.getPrivateKeyString() << endl;
cout << key.getPrivateKeyIdentifier() << endl;
} catch(std::exception const& e) {
cout << e.what();
}
return 0;
#endif
#ifdef TEST_CERTIFICATE_KEY_IDENTIFIER
try {
Key key = Key();
key.loadCertificate(get_file_contents("test.crt"));
cout << key.getCertificatePrint() << endl;
cout << key.getCertificateKeyIdentifier() << endl;
cout << key.getPublicKeyIdentifier() << endl;
cout << "length : " << key.length() << endl;
cout << "subject : " << key.getCertificateSubject() << endl;
cout << "issuer : " << key.getCertificateIssuer() << endl;
} catch(std::exception const& e) {
cout << e.what();
}
return 0;
#endif // TEST_CERTIFICATE_KEY_IDENTIFIER
#ifdef TEST_KEY_PRINT
try {
Key key = Key(2048); // 2048 bit
cout << key.getPrivateKeyPrint() << endl;
cout << key.getPublicKeyPrint() << endl;
const char* digest = "sha256"; // sha256
const char* countryName = "US"; // 2 chars
const char* stateOrProvinceName = "ROOT-ST";
const char* localityName = "ROOT-L";
const char* organizationName = "ROOT-O";
const char* organizationalUnitName = "ROOT-OU";
const char* commonName = "www.example.com";
const char* emailAddress = "dory@example.com";
string subject;
subject += "/C=" ; subject += countryName;
subject += "/ST="; subject += stateOrProvinceName;
subject += "/L=" ; subject += localityName;
subject += "/O=" ; subject += organizationName;
subject += "/OU="; subject += organizationalUnitName;
subject += "/CN="; subject += commonName;
subject += "/emailAddress="; subject += emailAddress;
key.genRequest(subject, digest);
string request = key.getRequestString();
cout << key.getRequestPrint() << endl;
key.signRequest("", "0", 365, digest);
cout << key.getCertificatePrint() << endl;
} catch(std::exception const& e) {
cout << e.what();
}
return 0;
#endif
#ifdef TEST_EMPTY_SUBJECT_NAME
try {
Key key = Key(512);
cout << key.getPrivateKeyPrint() << endl;
cout << key.getPublicKeyPrint() << endl;
key.genRequest();
string request = key.getRequestString();
cout << key.getRequestPrint() << endl;
key.signRequest();
cout << key.getCertificatePrint() << endl;
} catch(std::exception const& e) {
cout << e.what();
}
return 0;
#endif
#ifdef TEST_LOAD_PUBLIC_KEY
try {
Key key = Key(2048); // 2048 bit
cout << key.getPublicKeyPrint() << endl;
cout << key.getPublicKeyIdentifier() << endl;
Key test = Key();
test.loadPublicKey(key.getPublicKeyString());
cout << test.getPublicKeyPrint() << endl;
cout << test.getPublicKeyIdentifier() << endl;
cout << "length : " << test.length() << endl;
} catch(std::exception const& e) {
cout << e.what();
}
return 0;
#endif
#ifdef TEST_LOAD_REQUEST
try {
string rootPrivate, rootPublic, rootRequest, rootCertificate;
Key root = Key(512);
rootPrivate = root.getPrivateKeyString();
rootPublic = root.getPublicKeyString();
const char* digest = "sha256";
const char* countryName = "US";
const char* stateOrProvinceName = "ROOT-ST";
const char* localityName = "ROOT-L";
const char* organizationName = "ROOT-O";
const char* organizationalUnitName = "ROOT-OU";
const char* commonName = "www.example.com";
const char* emailAddress = "dory@example.com";
string subject;
subject += "/C=" ; subject += countryName;
subject += "/ST="; subject += stateOrProvinceName;
subject += "/L=" ; subject += localityName;
subject += "/O=" ; subject += organizationName;
subject += "/OU="; subject += organizationalUnitName;
subject += "/CN="; subject += commonName;
subject += "/emailAddress="; subject += emailAddress;
root.genRequest(subject, digest);
rootRequest = root.getRequestString();
cout << root.getRequestPrint() << endl;
cout << "length : " << root.length() << endl;
Key key2 = Key("");
key2.loadRequest(rootRequest);
cout << key2.getRequestPrint() << endl;
cout << "length : " << key2.length() << endl;
} catch(std::exception const& e) {
cout << e.what();
}
return 0;
#endif
string rootPrivate, rootPublic, rootRequest, rootCertificate;
// generate new root certificate
try {
Key root = Key(2048); // 2048 bit
rootPrivate = root.getPrivateKeyString();
rootPublic = root.getPublicKeyString();
const char* digest = "sha256"; // sha256
const char* countryName = "US"; // 2 chars
const char* stateOrProvinceName = "ROOT-ST";
const char* localityName = "ROOT-L";
const char* organizationName = "ROOT-O";
const char* organizationalUnitName = "ROOT-OU";
const char* commonName = "www.example.com - 한中に";
const char* emailAddress = "dory@example.com";
string subject;
subject += "/C=" ; subject += countryName;
subject += "/ST="; subject += stateOrProvinceName;
subject += "/L=" ; subject += localityName;
subject += "/O=" ; subject += organizationName;
subject += "/OU="; subject += organizationalUnitName;
subject += "/CN="; subject += commonName;
subject += "/emailAddress="; subject += emailAddress;
root.genRequest(subject, digest);
rootRequest = root.getRequestString();
// ROOTCA(self-signed). csr: null, serial : 0, days : 365, digest : sha256
rootCertificate = root.signRequest("", "0", 365, digest);
cout << root.getCertificatePrint() << endl;
cout << "Certificate Identifier : " << root.getCertificateIdentifier() << endl;
} catch(std::exception const& e) {
cout << e.what();
}
// load root from string and sign a cert.
string certPrivate, certPublic, certRequest, certCertificate;
try {
Key root = Key(rootPrivate);
root.loadCertificate(rootCertificate);
Key cert = Key(2048); // new key
certPrivate = cert.getPrivateKeyString();
certPublic = cert.getPublicKeyString();
string digest = "sha256"; // sha256
const char* countryName = "US"; // 2 chars
const char* stateOrProvinceName = "CERT-ST";
const char* localityName = "CERT-L";
const char* organizationName = "CERT-O";
const char* organizationalUnitName = "CERT-OU";
const char* commonName = "www.example.org";
const char* emailAddress = "dorydory@example.com";
string subject;
subject += "/C=" ; subject += countryName;
subject += "/ST="; subject += stateOrProvinceName;
subject += "/L=" ; subject += localityName;
subject += "/O=" ; subject += organizationName;
subject += "/OU="; subject += organizationalUnitName;
subject += "/CN="; subject += commonName;
subject += "/emailAddress="; subject += emailAddress;
cert.genRequest(subject, digest);
certRequest = cert.getRequestString();
cout << cert.getRequestPrint() << endl;
cout << "subject : " << cert.getRequestSubject() << endl;
// signed by root. digest : sha512, serial : 1, days : 7
certCertificate = root.signRequest(certRequest, "1", 7, digest);
cert.loadCertificate(certCertificate);
cout << cert.getCertificatePrint() << endl;
cout << "subject : " << cert.getCertificateSubject() << endl;
cout << "issuer : " << cert.getCertificateIssuer() << endl;
} catch(std::exception const& e) {
cout << e.what();
}
// create a new csr by existing certificate.
string otherRequest, otherCertificate;
try {
Key root = Key(rootPrivate);
root.loadCertificate(rootCertificate);
Key other = Key(2048);
otherRequest = other.getRequestByCertificate(certCertificate);
cout << other.getRequestPrint() << endl;
// signed by root. digest : sha512, serial : 2, days : 14
otherCertificate = root.signRequest(otherRequest, "2", 14, "sha512");
} catch(std::exception const& e) {
cout << e.what();
}
// check by $ openssl x509 -in cert.crt -text -noout
// verify by $ openssl verify -CAfile root.crt cert.crt other.crt
cout << rootCertificate << endl;
cout << certCertificate << endl;
cout << otherCertificate << endl;
// check by $ openssl req -in other.csr -noout -text
cout << otherRequest <<endl;
// create files
ofstream rootcaKey("rootca.key");
rootcaKey << rootPrivate;
rootcaKey.close();
ofstream rootcaCrt("rootca.crt");
rootcaCrt << rootCertificate;
rootcaCrt.close();
ofstream certKey("cert.key");
certKey << certPrivate;
certKey.close();
ofstream certCrt("cert.crt");
certCrt << certCertificate;
certCrt.close();
return 0;
} | 31.995565 | 94 | 0.616424 | [
"vector"
] |
5169e31ef2eed229e7d8a2dc97c95196657c06e9 | 29,008 | cpp | C++ | DK/DKFramework/DKCanvas.cpp | arkiny/DKGL | a93516c9aff1cec04d93ee2cf3cb6bf15b513dfc | [
"BSD-3-Clause"
] | 33 | 2015-11-24T08:40:48.000Z | 2022-03-16T14:54:12.000Z | DK/DKFramework/DKCanvas.cpp | arkiny/DKGL | a93516c9aff1cec04d93ee2cf3cb6bf15b513dfc | [
"BSD-3-Clause"
] | 3 | 2021-04-11T04:08:04.000Z | 2021-04-13T12:01:04.000Z | DK/DKFramework/DKCanvas.cpp | arkiny/DKGL | a93516c9aff1cec04d93ee2cf3cb6bf15b513dfc | [
"BSD-3-Clause"
] | 10 | 2015-11-24T02:27:53.000Z | 2022-01-05T18:29:09.000Z | //
// File: DKCanvas.cpp
// Author: Hongtae Kim (tiff2766@gmail.com)
//
// Copyright (c) 2004-2020 Hongtae Kim. All rights reserved.
//
#include "DKCanvas.h"
#include "DKMath.h"
#include "DKAffineTransform2.h"
using namespace DKFramework;
const float DKCanvas::minimumScaleFactor = 0.000001f;
DKCanvas::DKCanvas(DKCommandBuffer* cb, DKTexture* color, DKTexture* depth)
: commandBuffer(cb)
, colorAttachment(color)
, depthAttachment(depth)
, viewport(0, 0, 1, 1)
, contentBounds(0, 0, 1, 1)
, contentTransform(DKMatrix3::identity)
, screenTransform(DKMatrix3::identity)
{
}
DKCanvas::~DKCanvas()
{
}
const DKRect& DKCanvas::Viewport() const
{
return viewport;
}
void DKCanvas::SetViewport(const DKRect& rc)
{
viewport = rc;
this->UpdateTransform();
}
const DKRect& DKCanvas::ContentBounds() const
{
return contentBounds;
}
void DKCanvas::SetContentBounds(const DKRect& rc)
{
DKASSERT_DEBUG(rc.size.width > 0.0 && rc.size.height > 0.0);
this->contentBounds.origin = rc.origin;
this->contentBounds.size.width = Max(rc.size.width, minimumScaleFactor);
this->contentBounds.size.height = Max(rc.size.height, minimumScaleFactor);
this->UpdateTransform();
}
const DKMatrix3& DKCanvas::ContentTransform() const
{
return contentTransform;
}
void DKCanvas::SetContentTransform(const DKMatrix3& tm)
{
this->contentTransform = tm;
this->UpdateTransform();
}
void DKCanvas::UpdateTransform()
{
const DKPoint& viewportOffset = this->viewport.origin;
const DKPoint& contentOffset = this->contentBounds.origin;
const DKSize& contentScale = this->contentBounds.size;
DKASSERT_DEBUG(contentScale.width > 0.0 && contentScale.height > 0.0);
DKMatrix3 targetOrient = this->TargetOrientation();
DKMatrix3 offset = DKAffineTransform2(-contentOffset.Vector()).Matrix3();
DKLinearTransform2 s(1.0f / contentScale.width, 1.0f / contentScale.height);
this->screenTransform = this->contentTransform * offset * DKAffineTransform2(s).Multiply(targetOrient).Matrix3();
}
void DKCanvas::DrawTriangles(const DKPoint* verts,
size_t numVerts,
const DKColor& color)
{
if (numVerts > 2)
{
DKArray<ColoredVertex> vertices;
vertices.Reserve(numVerts);
for (size_t i = 0; i < numVerts; ++i)
{
vertices.Add(ColoredVertex{ verts[i], color });
}
DrawTriangles(vertices, vertices.Count());
}
}
void DKCanvas::DrawLineStrip(const DKPoint* points,
size_t numPoints,
const DKColor& color)
{
if (numPoints > 1)
{
DKArray<DKPoint> lines;
lines.Reserve(numPoints * 2);
for (int i = 0; (i + 1) < numPoints; ++i)
{
DKPoint v0 = points[i].Vector().Transform(screenTransform);
DKPoint v1 = points[i + 1].Vector().Transform(screenTransform);
lines.Add(v0);
lines.Add(v1);
}
this->DrawLines(lines, lines.Count(), color);
}
}
void DKCanvas::DrawTriangleStrip(const DKPoint* verts,
size_t numVerts,
const DKColor& color)
{
if (numVerts > 2)
{
DKArray<ColoredVertex> pts;
pts.Reserve(numVerts * 3);
for (size_t i = 0; (i + 2) < numVerts; ++i)
{
if (i & 1)
{
pts.Add({ verts[i + 1], color });
pts.Add({ verts[i], color });
}
else
{
pts.Add({ verts[i], color });
pts.Add({ verts[i + 1], color });
}
pts.Add({ verts[i + 2], color });
}
this->DrawTriangles(pts, pts.Count());
}
}
void DKCanvas::DrawTriangleStrip(const ColoredVertex* verts,
size_t numVerts)
{
if (numVerts > 2)
{
DKArray<ColoredVertex> pts;
pts.Reserve(numVerts * 3);
for (size_t i = 0; (i + 2) < numVerts; ++i)
{
if (i & 1)
{
pts.Add(verts[i + 1]);
pts.Add(verts[i]);
}
else
{
pts.Add(verts[i]);
pts.Add(verts[i + 1]);
}
pts.Add(verts[i + 2]);
}
this->DrawTriangles(pts, pts.Count());
}
}
void DKCanvas::DrawTriangleStrip(const TexturedVertex* verts,
size_t numVerts,
const DKTexture* texture)
{
if (numVerts > 2 && texture)
{
DKArray<TexturedVertex> pts;
pts.Reserve(numVerts * 3);
for (size_t i = 0; (i + 2) < numVerts; ++i)
{
if (i & 1)
{
pts.Add(verts[i + 1]);
pts.Add(verts[i]);
}
else
{
pts.Add(verts[i]);
pts.Add(verts[i + 1]);
}
pts.Add(verts[i + 2]);
}
this->DrawTriangles(pts, pts.Count(), texture);
}
}
void DKCanvas::DrawQuad(const DKPoint& lt,
const DKPoint& rt,
const DKPoint& lb,
const DKPoint& rb,
const DKColor& color)
{
if (IsDrawable())
{
const DKVector2 tpos[4] = {
lt.Vector().Transform(this->contentTransform), // left-top
rt.Vector().Transform(this->contentTransform), // right-top
lb.Vector().Transform(this->contentTransform), // left-bottom
rb.Vector().Transform(this->contentTransform), // right-bottom
};
bool t1 = this->contentBounds.IntersectTriangle(tpos[0], tpos[2], tpos[1]);
bool t2 = this->contentBounds.IntersectTriangle(tpos[1], tpos[2], tpos[3]);
if (t1 && t2)
{
const DKPoint vf[6] = { lt, lb, rt, rt, lb, rb };
DrawTriangles(vf, 6, color);
}
else if (t1)
{
const DKPoint vf[3] = { lt, lb, rt };
DrawTriangles(vf, 3, color);
}
else if (t2)
{
const DKPoint vf[3] = { rt, lb, rb };
DrawTriangles(vf, 3, color);
}
}
}
void DKCanvas::DrawQuad(const TexturedVertex& lt,
const TexturedVertex& rt,
const TexturedVertex& lb,
const TexturedVertex& rb,
const DKTexture* texture)
{
if (IsDrawable() && texture)
{
const DKVector2 tpos[4] = {
lt.position.Vector().Transform(this->contentTransform), // left-top
rt.position.Vector().Transform(this->contentTransform), // right-top
lb.position.Vector().Transform(this->contentTransform), // left-bottom
rb.position.Vector().Transform(this->contentTransform), // right-bottom
};
bool t1 = this->contentBounds.IntersectTriangle(tpos[0], tpos[2], tpos[1]);
bool t2 = this->contentBounds.IntersectTriangle(tpos[1], tpos[2], tpos[3]);
if (t1 && t2)
{
const TexturedVertex vf[6] = { lt, lb, rt, rt, lb, rb };
DrawTriangles(vf, 6, texture);
}
else if (t1)
{
const TexturedVertex vf[3] = { lt, lb, rt };
DrawTriangles(vf, 3, texture);
}
else if (t2)
{
const TexturedVertex vf[3] = { rt, lb, rb };
DrawTriangles(vf, 3, texture);
}
}
}
void DKCanvas::DrawRect(const DKRect& posRect, const DKMatrix3& posTM, const DKColor& color)
{
if (IsDrawable() && posRect.IsValid())
{
const DKVector2 pos[4] = {
DKVector2(posRect.origin.x, posRect.origin.y).Transform(posTM), // left-top
DKVector2(posRect.origin.x + posRect.size.width, posRect.origin.y).Transform(posTM), // right-top
DKVector2(posRect.origin.x, posRect.origin.y + posRect.size.height).Transform(posTM), // left-bottom
DKVector2(posRect.origin.x + posRect.size.width, posRect.origin.y + posRect.size.height).Transform(posTM), // right-bottom
};
const DKVector2 tpos[4] = {
DKVector2(pos[0]).Transform(this->contentTransform),
DKVector2(pos[1]).Transform(this->contentTransform),
DKVector2(pos[2]).Transform(this->contentTransform),
DKVector2(pos[3]).Transform(this->contentTransform),
};
bool t1 = this->contentBounds.IntersectTriangle(tpos[0], tpos[2], tpos[1]);
bool t2 = this->contentBounds.IntersectTriangle(tpos[1], tpos[2], tpos[3]);
if (t1 && t2)
{
const DKPoint vf[6] = { pos[0], pos[2], pos[1], pos[1], pos[2], pos[3] };
DrawTriangles(vf, 6, color);
}
else if (t1)
{
const DKPoint vf[3] = { pos[0], pos[2],pos[1] };
DrawTriangles(vf, 3, color);
}
else if (t2)
{
const DKPoint vf[3] = { pos[1], pos[2], pos[3] };
DrawTriangles(vf, 3, color);
}
}
}
void DKCanvas::DrawRect(const DKRect& posRect, const DKMatrix3& posTM,
const DKRect& texRect, const DKMatrix3& texTM,
const DKTexture* texture,
const DKColor& color)
{
if (IsDrawable() && texture && posRect.IsValid())
{
const DKVector2 pos[4] = {
DKVector2(posRect.origin.x, posRect.origin.y).Transform(posTM), // left-top
DKVector2(posRect.origin.x + posRect.size.width, posRect.origin.y).Transform(posTM), // right-top
DKVector2(posRect.origin.x, posRect.origin.y + posRect.size.height).Transform(posTM), // left-bottom
DKVector2(posRect.origin.x + posRect.size.width, posRect.origin.y + posRect.size.height).Transform(posTM), // right-bottom
};
const DKVector2 tex[4] = {
DKVector2(texRect.origin.x, texRect.origin.y).Transform(texTM), // left-top
DKVector2(texRect.origin.x + texRect.size.width, texRect.origin.y).Transform(texTM), // right-top
DKVector2(texRect.origin.x, texRect.origin.y + texRect.size.height).Transform(texTM), // left-bottom
DKVector2(texRect.origin.x + texRect.size.width, texRect.origin.y + texRect.size.height).Transform(texTM), // right-bottom
};
const DKVector2 tpos[4] = {
DKVector2(pos[0]).Transform(this->contentTransform),
DKVector2(pos[1]).Transform(this->contentTransform),
DKVector2(pos[2]).Transform(this->contentTransform),
DKVector2(pos[3]).Transform(this->contentTransform),
};
bool t1 = this->contentBounds.IntersectTriangle(tpos[0], tpos[2], tpos[1]);
bool t2 = this->contentBounds.IntersectTriangle(tpos[1], tpos[2], tpos[3]);
if (t1 && t2)
{
const TexturedVertex vf[6] = {
{ pos[0], tex[0], color },
{ pos[2], tex[2], color },
{ pos[1], tex[1], color },
{ pos[1], tex[1], color },
{ pos[2], tex[2], color },
{ pos[3], tex[3], color }
};
DrawTriangles(vf, 6, texture);
}
else if (t1)
{
const TexturedVertex vf[3] = {
{ pos[0], tex[0], color },
{ pos[2], tex[2], color },
{ pos[1], tex[1], color }
};
DrawTriangles(vf, 3, texture);
}
else if (t2)
{
const TexturedVertex vf[3] = {
{ pos[1], tex[1], color },
{ pos[2], tex[2], color },
{ pos[3], tex[3], color }
};
DrawTriangles(vf, 3, texture);
}
}
}
void DKCanvas::DrawEllipseLine(const DKRect& bounds,
const DKMatrix3& tm,
const DKColor& color)
{
if (IsDrawable() && bounds.IsValid())
{
const DKVector2 pos[4] = {
DKVector2(bounds.origin.x, bounds.origin.y).Transform(tm), // left-top
DKVector2(bounds.origin.x + bounds.size.width, bounds.origin.y).Transform(tm), // right-top
DKVector2(bounds.origin.x, bounds.origin.y + bounds.size.height).Transform(tm), // left-bottom
DKVector2(bounds.origin.x + bounds.size.width, bounds.origin.y + bounds.size.height).Transform(tm), // right-bottom
};
const DKVector2 tpos[4] = {
DKVector2(pos[0]).Transform(this->contentTransform),
DKVector2(pos[1]).Transform(this->contentTransform),
DKVector2(pos[2]).Transform(this->contentTransform),
DKVector2(pos[3]).Transform(this->contentTransform),
};
bool t1 = this->contentBounds.IntersectTriangle(tpos[0], tpos[2], tpos[1]);
bool t2 = this->contentBounds.IntersectTriangle(tpos[1], tpos[2], tpos[3]);
if (t1 || t2)
{
float circleW = Max((tpos[0] - tpos[1]).Length(), (tpos[2] - tpos[3]).Length());
float circleH = Max((tpos[0] - tpos[2]).Length(), (tpos[1] - tpos[3]).Length());
const int numSegments = LineSegmentsCircumference(Min(circleW, circleH) * 0.5f);
DKArray<DKPoint> lines;
lines.Resize(numSegments + 1);
const DKVector2 center = bounds.Center().Vector();
const DKVector2 radius = bounds.size.Vector() * 0.5f;
const DKVector2 radiusSq = { radius.x * radius.x, radius.y * radius.y };
// formula: X^2 / A^2 + Y^2 / B^2 = 1
// A = bounds.width/2, B = bounds.height/2
// generate outline polygon!
for (int i = 0; i < numSegments; ++i)
{
// x = a*sin(t)
// y = b*cos(t)
// where 0 <= t < 2*PI
float t = (DKGL_PI * 2.0f) * (float(i) / float(numSegments));
DKVector2 p = { radius.x * sinf(t), radius.y * cosf(t) };
lines[i] = DKVector2(p + center).Transform(tm);
}
lines[numSegments] = lines.Value(0);
DrawLines(lines, lines.Count(), color);
}
}
}
void DKCanvas::DrawEllipse(const DKRect& bounds, const DKMatrix3& tm, const DKColor& color)
{
if (IsDrawable() && bounds.IsValid())
{
const DKVector2 pos[4] = {
DKVector2(bounds.origin.x, bounds.origin.y).Transform(tm), // left-top
DKVector2(bounds.origin.x + bounds.size.width, bounds.origin.y).Transform(tm), // right-top
DKVector2(bounds.origin.x, bounds.origin.y + bounds.size.height).Transform(tm), // left-bottom
DKVector2(bounds.origin.x + bounds.size.width, bounds.origin.y + bounds.size.height).Transform(tm), // right-bottom
};
const DKVector2 tpos[4] = {
DKVector2(pos[0]).Transform(this->contentTransform),
DKVector2(pos[1]).Transform(this->contentTransform),
DKVector2(pos[2]).Transform(this->contentTransform),
DKVector2(pos[3]).Transform(this->contentTransform),
};
bool t1 = this->contentBounds.IntersectTriangle(tpos[0], tpos[2], tpos[1]);
bool t2 = this->contentBounds.IntersectTriangle(tpos[1], tpos[2], tpos[3]);
if (t1 || t2)
{
float circleW = Max((tpos[0] - tpos[1]).Length(), (tpos[2] - tpos[3]).Length());
float circleH = Max((tpos[0] - tpos[2]).Length(), (tpos[1] - tpos[3]).Length());
const int numSegments = LineSegmentsCircumference(Min(circleW, circleH) * 0.5f);
DKArray<DKPoint> triangleVertices;
triangleVertices.Resize(numSegments * 3);
const DKVector2 center = bounds.Center().Vector();
const DKVector2 radius = bounds.size.Vector() * 0.5f;
const DKVector2 radiusSq = { radius.x * radius.x, radius.y * radius.y };
DKVector2 lastVertex = DKVector2(center.x, center.y + radius.y).Transform(tm);
DKVector2 transCenter = DKVector2(center).Transform(tm);
// formula: X^2 / A^2 + Y^2 / B^2 = 1
// A = bounds.width/2, B = bounds.height/2
// generate outline polygon!
for (int i = 0; (i + 1) < numSegments; ++i)
{
// x = a*sin(t)
// y = b*cos(t)
// where 0 <= t < 2*PI
float t = (DKGL_PI * 2.0f) * (float(i) / float(numSegments));
DKVector2 p = { radius.x * sinf(t), radius.y * cosf(t) };
DKVector2 vertex = DKVector2(p + center).Transform(tm);
triangleVertices[i * 3] = vertex;
triangleVertices[i * 3 + 1] = lastVertex;
triangleVertices[i * 3 + 2] = transCenter;
lastVertex = vertex;
}
triangleVertices[numSegments * 3 - 3] = triangleVertices[1];
triangleVertices[numSegments * 3 - 2] = lastVertex;
triangleVertices[numSegments * 3 - 1] = transCenter;
DrawTriangles(triangleVertices, triangleVertices.Count(), color);
}
}
}
void DKCanvas::DrawEllipse(const DKRect& bounds,
const DKMatrix3& tm,
const DKRect& texBounds,
const DKMatrix3& texTm,
const DKTexture* texture,
const DKColor& color)
{
if (IsDrawable() && texture && bounds.IsValid())
{
const DKVector2 pos[4] = {
DKVector2(bounds.origin.x, bounds.origin.y).Transform(tm), // left-top
DKVector2(bounds.origin.x + bounds.size.width, bounds.origin.y).Transform(tm), // right-top
DKVector2(bounds.origin.x, bounds.origin.y + bounds.size.height).Transform(tm), // left-bottom
DKVector2(bounds.origin.x + bounds.size.width, bounds.origin.y + bounds.size.height).Transform(tm), // right-bottom
};
const DKVector2 tpos[4] = {
DKVector2(pos[0]).Transform(this->contentTransform),
DKVector2(pos[1]).Transform(this->contentTransform),
DKVector2(pos[2]).Transform(this->contentTransform),
DKVector2(pos[3]).Transform(this->contentTransform),
};
bool t1 = this->contentBounds.IntersectTriangle(tpos[0], tpos[2], tpos[1]);
bool t2 = this->contentBounds.IntersectTriangle(tpos[1], tpos[2], tpos[3]);
if (t1 || t2)
{
float circleW = Max((tpos[0] - tpos[1]).Length(), (tpos[2] - tpos[3]).Length());
float circleH = Max((tpos[0] - tpos[2]).Length(), (tpos[1] - tpos[3]).Length());
const int numSegments = LineSegmentsCircumference(Min(circleW, circleH) * 0.5f);
DKArray<TexturedVertex> triangleVertices;
triangleVertices.Resize(numSegments * 3);
const DKVector2 center = bounds.Center().Vector();
const DKVector2 texCenter = texBounds.Center().Vector();
const DKVector2 radius = bounds.size.Vector() * 0.5f;
const DKVector2 radiusSq = { radius.x * radius.x, radius.y * radius.y };
TexturedVertex lastVertex = {
DKVector2(center.x, center.y + radius.y).Transform(tm),
DKVector2(texCenter.x, texCenter.y + texBounds.size.height * (radius.y / bounds.size.height)).Transform(texTm),
color
};
TexturedVertex transCenter = {
DKVector2(center).Transform(tm),
DKVector2(texCenter).Transform(texTm),
color
};
// formula: X^2 / A^2 + Y^2 / B^2 = 1
// A = bounds.width/2, B = bounds.height/2
// generate outline polygon!
for (int i = 0; (i + 1) < numSegments; ++i)
{
// x = a*sin(t)
// y = b*cos(t)
// where 0 <= t < 2*PI
float t = (DKGL_PI * 2.0f) * (float(i) / float(numSegments));
DKVector2 p = DKVector2(radius.x * sinf(t), radius.y * cosf(t)) + center;
DKVector2 uv = texBounds.origin.Vector() + texBounds.size.Vector() * ((p - bounds.origin.Vector()) / bounds.size.Vector());
TexturedVertex vertex = {
DKVector2(p).Transform(tm),
DKVector2(uv).Transform(texTm),
color
};
triangleVertices[i * 3] = vertex;
triangleVertices[i * 3 + 1] = lastVertex;
triangleVertices[i * 3 + 2] = transCenter;
lastVertex = vertex;
}
triangleVertices[numSegments * 3 - 3] = triangleVertices[1];
triangleVertices[numSegments * 3 - 2] = lastVertex;
triangleVertices[numSegments * 3 - 1] = transCenter;
DrawTriangles(triangleVertices, triangleVertices.Count(), texture);
}
}
}
void DKCanvas::DrawText(const DKRect& bounds,
const DKMatrix3& transform,
const DKString& text,
const DKFont* font,
const DKColor& color)
{
if (!IsDrawable() || !bounds.IsValid())
return;
size_t textLen = text.Length();
if (font == nullptr || !font->IsValid() || textLen == 0)
return;
struct Quad
{
TexturedVertex lt, rt, lb, rb;
const DKTexture* texture;
};
DKArray<Quad> quads;
quads.Reserve(textLen);
DKPoint bboxMin(0, 0);
DKPoint bboxMax(0, 0);
float offset = 0; // accumulated text width (pixel)
for (size_t i = 0; i < textLen; ++i)
{
// get glyph info from font object
const DKFont::GlyphData* glyph = font->GlyphDataForChar(text[i]);
if (glyph == nullptr)
continue;
DKPoint posMin(offset + glyph->position.x, -glyph->position.y);
DKPoint posMax(offset + glyph->position.x + glyph->frame.size.width, glyph->frame.size.height - glyph->position.y);
if (bboxMin.x > posMin.x) bboxMin.x = posMin.x;
if (bboxMin.y > posMin.y) bboxMin.y = posMin.y;
if (bboxMax.x < posMax.x) bboxMax.x = posMax.x;
if (bboxMax.y < posMax.y) bboxMax.y = posMax.y;
if (glyph->texture)
{
uint32_t textureWidth = glyph->texture->Width();
uint32_t textureHeight = glyph->texture->Height();
if (textureWidth > 0 && textureHeight > 0)
{
float invW = 1.0f / static_cast<float>(textureWidth);
float invH = 1.0f / static_cast<float>(textureHeight);
DKPoint uvMin(glyph->frame.origin.x * invW, glyph->frame.origin.y * invH);
DKPoint uvMax((glyph->frame.origin.x + glyph->frame.size.width) * invW,
(glyph->frame.origin.y + glyph->frame.size.height) * invH);
const Quad q =
{
TexturedVertex { DKVector2(posMin.x, posMin.y), DKVector2(uvMin.x, uvMin.y), color }, // lt
TexturedVertex { DKVector2(posMax.x, posMin.y), DKVector2(uvMax.x, uvMin.y), color }, // rt
TexturedVertex { DKVector2(posMin.x, posMax.y), DKVector2(uvMin.x, uvMax.y), color }, // lb
TexturedVertex { DKVector2(posMax.x, posMax.y), DKVector2(uvMax.x, uvMax.y), color }, // rb
glyph->texture,
};
quads.Add(q);
}
}
offset += glyph->advance.width + font->KernAdvance(text[i], text[i + 1]).x; // text[i+1] can be null.
}
if (quads.Count() == 0)
return;
const float width = bboxMax.x - bboxMin.x;
const float height = bboxMax.y - bboxMin.y;
if (width <= 0.0f || height <= 0.0f)
return;
// sort by texture order
quads.Sort([](const Quad& lhs, const Quad& rhs)
{
return reinterpret_cast<uintptr_t>(lhs.texture) > reinterpret_cast<uintptr_t>(rhs.texture);
});
// calculate transform matrix
DKAffineTransform2 trans;
trans.Translate(-bboxMin.x, -bboxMin.y); // move origin
trans *= DKLinearTransform2().Scale(1.0f / width, 1.0f / height); // normalize size
trans *= DKLinearTransform2().Scale(bounds.size.width, bounds.size.height); // scale to bounds
trans.Translate(bounds.origin.x, bounds.origin.y); // move to bounds origin
DKMatrix3 matrix = trans.Matrix3();
matrix *= transform; // user transform
const DKTexture* lastTexture = nullptr;
DKArray<TexturedVertex> triangles;
triangles.Reserve(quads.Count() * 6);
for (Quad& q : quads)
{
if (q.texture != lastTexture)
{
if (triangles.Count() > 0)
DrawTriangles(triangles, triangles.Count(), lastTexture);
triangles.Clear();
lastTexture = q.texture;
}
TexturedVertex vf[6] = {
TexturedVertex { q.lt.position.Vector().Transform(matrix), q.lt.texcoord, color },
TexturedVertex { q.lb.position.Vector().Transform(matrix), q.lb.texcoord, color },
TexturedVertex { q.rt.position.Vector().Transform(matrix), q.rt.texcoord, color },
TexturedVertex { q.rt.position.Vector().Transform(matrix), q.rt.texcoord, color },
TexturedVertex { q.lb.position.Vector().Transform(matrix), q.lb.texcoord, color },
TexturedVertex { q.rb.position.Vector().Transform(matrix), q.rb.texcoord, color },
};
triangles.Add(vf, 6);
}
if (triangles.Count() > 0)
DrawTriangles(triangles, triangles.Count(), lastTexture);
}
void DKCanvas::DrawText(const DKPoint& baselineBegin,
const DKPoint& baselineEnd,
const DKString& text,
const DKFont* font,
const DKColor& color)
{
if (IsDrawable() == false)
return;
if (font == nullptr || !font->IsValid() || text.Length() == 0)
return;
if ((baselineEnd.Vector() - baselineBegin.Vector()).Length() < FLT_EPSILON)
return;
// font size, screen size in pixel units
const float lineHeight = font->LineHeight();
const float lineWidth = font->LineWidth(text);
const DKRect textBounds = font->Bounds(text);
const DKSize& viewportSize = this->viewport.size;
const DKSize& contentScale = this->contentBounds.size;
// change local-coords to pixel-coords
const DKSize scaleToScreen = DKSize(viewportSize.width / contentScale.width, viewportSize.height / contentScale.height);
const DKVector2 baselinePixelBegin = DKVector2(baselineBegin.x * scaleToScreen.width, baselineBegin.y * scaleToScreen.height);
const DKVector2 baselinePixelEnd = DKVector2(baselineEnd.x * scaleToScreen.width, baselineEnd.y * scaleToScreen.height);
const float scale = (baselinePixelEnd - baselinePixelBegin).Length();
const DKVector2 baselinePixelDir = (baselinePixelEnd - baselinePixelBegin).Normalize();
const float angle = acosf(baselinePixelDir.x) * ((baselinePixelDir.y < 0) ? -1.0f : 1.0f);
// calculate transform (matrix)
DKAffineTransform2 transform(
DKLinearTransform2()
.Scale(scale / lineWidth) // scale
.Rotate(angle) // rotate
.Scale(1.0f / viewportSize.width, 1.0f / viewportSize.height) // normalize (0~1)
.Scale(contentScale.width, contentScale.height) // apply contentScale
, baselineBegin.Vector());
DrawText(textBounds, transform.Matrix3(), text, font, color);
}
uint32_t DKCanvas::LineSegmentsCircumference(float radius) const
{
float circleAreaPoints = radius * radius * static_cast<float>(DKGL_PI);
float contentArea = contentBounds.size.width * contentBounds.size.height;
float resolutionArea = viewport.size.width * viewport.size.height;
float areaRatio = resolutionArea / contentArea;
float circleAreaPixels = circleAreaPoints * areaRatio;
float r2 = sqrtf(circleAreaPixels * static_cast<float>(DKGL_MATH_1_PI));
float circumference = r2 * static_cast<float>(DKGL_PI) * 2.0f;
constexpr uint32_t minSegments = 4;
constexpr uint32_t maxSegments = 90;
uint32_t numSegments = Clamp(static_cast<uint32_t>(circumference * 0.25f),
minSegments,
maxSegments);
return numSegments;
}
| 39.041723 | 139 | 0.548228 | [
"object",
"vector",
"transform"
] |
516f0d52a1fb708db51e2532c48b55c32d6d3e35 | 2,973 | cpp | C++ | Examples/To do/Image synthesis/RayTracer2010Cpp/RayTracer2010Cpp/camera.cpp | dotnuttx/Alter-Native | 9282c7d48a4baae1ea6fd9b102bc6f55ba0e6e95 | [
"MIT"
] | 119 | 2015-01-09T14:02:17.000Z | 2022-03-09T14:24:21.000Z | Examples/To do/Image synthesis/RayTracer2010Cpp/RayTracer2010Cpp/camera.cpp | dotnuttx/Alter-Native | 9282c7d48a4baae1ea6fd9b102bc6f55ba0e6e95 | [
"MIT"
] | 12 | 2016-01-15T11:33:32.000Z | 2021-06-08T04:57:07.000Z | Examples/To do/Image synthesis/RayTracer2010Cpp/RayTracer2010Cpp/camera.cpp | dotnuttx/Alter-Native | 9282c7d48a4baae1ea6fd9b102bc6f55ba0e6e95 | [
"MIT"
] | 43 | 2015-01-14T10:59:51.000Z | 2022-01-10T23:46:06.000Z | #include "camera.h"
#include "ray.h"
#include "scene.h"
#include "shader.h"
#include "random.h"
#include <cmath>
#include <limits>
#include "FreeImagePlus.h"
static unsigned char clamp(double v)
{
int i = (int)(v * 256);
if (i < 0)
i = 0;
else if (i > 255)
i = 255;
return i;
}
Camera::Camera()
{
pos = 0;
orient = Quaternion::makeIdentity();
width = 600, height = 400;
fov_y = 70;
subsamples = 2;
focal_length = 1;
aperture = 0;
}
void Camera::replaceFilm()
{
film.resize(width, height);
for (int i = 0; i < width*height; i++)
film.data[i] = 0;
}
void Camera::expose(Scene *scene)
{
// get the orientation of the camera
matrix4f rotmat;
orient.quat2Matrix(rotmat);
vect3d rt(rotmat.m[0], rotmat.m[1], rotmat.m[2]);
vect3d up(rotmat.m[4], rotmat.m[5], rotmat.m[6]);
vect3d fwd(rotmat.m[8], rotmat.m[9], rotmat.m[10]);
//printf("fwd (%f, %f, %f)\n", fwd[0], fwd[1], fwd[2]);
//printf("up (%f, %f, %f)\n", up[0], up[1], up[2]);
//printf("rt (%f, %f, %f)\n", rt[0], rt[1], rt[2]);
vect3d unit_rt = rt;
vect3d unit_up = up;
// convert the orientation to a 3D screen
double aspect = (double)width / (double)height;
double h = tan(fov_y * pi / 360.0);
up *= h * 2 * focal_length;
rt *= aspect * h * 2 * focal_length;
fwd *= -focal_length;
// 2D screen conversions
vect3d dx = rt / width;
vect3d dy = up / height;
vect3d corner = fwd - rt * .5 - up * .5;
// expose each pixel
Ray r;
r.scene = scene;
double subsample_res = 1.0 / subsamples;
for (int j = 0; j < height; j++)
{
for (int i = 0; i < width; i++)
{
vect3d color = 0;
for (int jj = 0; jj < subsamples; jj++)
{
for (int ii = 0; ii < subsamples; ii++)
{
// depth of field offset
vect2d dof2d;
rand_mt_in_sphere(dof2d);
vect3d dof = (unit_rt * dof2d[0] + unit_up * dof2d[1]) * aperture;
// set ray properties
r.pos = pos + dof;
r.hit_dist = double_max_value;
r.color = 0;
r.hit_object = 0;
r.dir = corner - dof + dx * (i + (ii+rand_mt_real2()) * subsample_res) + dy * (j + (jj+rand_mt_real2()) * subsample_res);
r.dir.normalize();
// trace the ray
scene->trace(r);
if (r.hit_object)
{
r.hit_object->shader->colorize(r);
color += r.color;
}
else
{
color += scene->background_color;
}
}
}
color *= subsample_res * subsample_res;
film(i,j) += color;
}
}
}
fipImage *Camera::create_image()
{
fipImage *bmp = new fipImage(FIT_BITMAP, width, height, 24);
for (int j = 0; j < height; j++)
{
vect3ub *scanline = (vect3ub*)bmp->getScanLine(j/*height - j - 1*/);
for (int i = 0; i < width; i++)
{
vect3f &color = film(i,j);
// gamma correct the color
double brightness = color.length() / 1.7320508075688772;
color /= sqrt(brightness);
// store the color
scanline[i][2] = clamp(color[0]);
scanline[i][1] = clamp(color[1]);
scanline[i][0] = clamp(color[2]);
}
}
return bmp;
}
| 20.645833 | 126 | 0.581904 | [
"3d"
] |
5171ee5655d74eb77150b9c4e09e042b97ab564f | 93,505 | cpp | C++ | export/windows/obj/src/lime/math/_Matrix4/Matrix4_Impl_.cpp | arturspon/zombie-killer | 07848c5006916e9079537a3d703ffe3740afaa5a | [
"MIT"
] | null | null | null | export/windows/obj/src/lime/math/_Matrix4/Matrix4_Impl_.cpp | arturspon/zombie-killer | 07848c5006916e9079537a3d703ffe3740afaa5a | [
"MIT"
] | null | null | null | export/windows/obj/src/lime/math/_Matrix4/Matrix4_Impl_.cpp | arturspon/zombie-killer | 07848c5006916e9079537a3d703ffe3740afaa5a | [
"MIT"
] | 1 | 2021-07-16T22:57:01.000Z | 2021-07-16T22:57:01.000Z | // Generated by Haxe 4.0.0-rc.2+77068e10c
#include <hxcpp.h>
#ifndef INCLUDED_95f339a1d026d52c
#define INCLUDED_95f339a1d026d52c
#include "hxMath.h"
#endif
#ifndef INCLUDED_haxe_io_Bytes
#include <haxe/io/Bytes.h>
#endif
#ifndef INCLUDED_lime_math_Matrix3
#include <lime/math/Matrix3.h>
#endif
#ifndef INCLUDED_lime_math_Vector4
#include <lime/math/Vector4.h>
#endif
#ifndef INCLUDED_lime_math__Matrix4_Matrix4_Impl_
#include <lime/math/_Matrix4/Matrix4_Impl_.h>
#endif
#ifndef INCLUDED_lime_utils_ArrayBufferView
#include <lime/utils/ArrayBufferView.h>
#endif
#ifndef INCLUDED_lime_utils_Log
#include <lime/utils/Log.h>
#endif
HX_LOCAL_STACK_FRAME(_hx_pos_a8b6e1b1a7c59cb4_27__new,"lime.math._Matrix4.Matrix4_Impl_","_new",0x84b003e9,"lime.math._Matrix4.Matrix4_Impl_._new","lime/math/Matrix4.hx",27,0xeb65dbd8)
HX_LOCAL_STACK_FRAME(_hx_pos_a8b6e1b1a7c59cb4_44_append,"lime.math._Matrix4.Matrix4_Impl_","append",0x0e638262,"lime.math._Matrix4.Matrix4_Impl_.append","lime/math/Matrix4.hx",44,0xeb65dbd8)
HX_LOCAL_STACK_FRAME(_hx_pos_a8b6e1b1a7c59cb4_75_appendRotation,"lime.math._Matrix4.Matrix4_Impl_","appendRotation",0xe357adc0,"lime.math._Matrix4.Matrix4_Impl_.appendRotation","lime/math/Matrix4.hx",75,0xeb65dbd8)
HX_LOCAL_STACK_FRAME(_hx_pos_a8b6e1b1a7c59cb4_95_appendScale,"lime.math._Matrix4.Matrix4_Impl_","appendScale",0x8a9ad8c8,"lime.math._Matrix4.Matrix4_Impl_.appendScale","lime/math/Matrix4.hx",95,0xeb65dbd8)
HX_LOCAL_STACK_FRAME(_hx_pos_a8b6e1b1a7c59cb4_107_appendTranslation,"lime.math._Matrix4.Matrix4_Impl_","appendTranslation",0xe6447daf,"lime.math._Matrix4.Matrix4_Impl_.appendTranslation","lime/math/Matrix4.hx",107,0xeb65dbd8)
HX_LOCAL_STACK_FRAME(_hx_pos_a8b6e1b1a7c59cb4_119_clone,"lime.math._Matrix4.Matrix4_Impl_","clone",0xe1a2dbd5,"lime.math._Matrix4.Matrix4_Impl_.clone","lime/math/Matrix4.hx",119,0xeb65dbd8)
HX_LOCAL_STACK_FRAME(_hx_pos_a8b6e1b1a7c59cb4_129_copyColumnFrom,"lime.math._Matrix4.Matrix4_Impl_","copyColumnFrom",0x5224fffd,"lime.math._Matrix4.Matrix4_Impl_.copyColumnFrom","lime/math/Matrix4.hx",129,0xeb65dbd8)
HX_LOCAL_STACK_FRAME(_hx_pos_a8b6e1b1a7c59cb4_167_copyColumnTo,"lime.math._Matrix4.Matrix4_Impl_","copyColumnTo",0xcc64e54e,"lime.math._Matrix4.Matrix4_Impl_.copyColumnTo","lime/math/Matrix4.hx",167,0xeb65dbd8)
HX_LOCAL_STACK_FRAME(_hx_pos_a8b6e1b1a7c59cb4_204_copyFrom,"lime.math._Matrix4.Matrix4_Impl_","copyFrom",0xc27fde47,"lime.math._Matrix4.Matrix4_Impl_.copyFrom","lime/math/Matrix4.hx",204,0xeb65dbd8)
HX_LOCAL_STACK_FRAME(_hx_pos_a8b6e1b1a7c59cb4_214_copyRowFrom,"lime.math._Matrix4.Matrix4_Impl_","copyRowFrom",0xc4e0b7e7,"lime.math._Matrix4.Matrix4_Impl_.copyRowFrom","lime/math/Matrix4.hx",214,0xeb65dbd8)
HX_LOCAL_STACK_FRAME(_hx_pos_a8b6e1b1a7c59cb4_252_copyRowTo,"lime.math._Matrix4.Matrix4_Impl_","copyRowTo",0x543beeb8,"lime.math._Matrix4.Matrix4_Impl_.copyRowTo","lime/math/Matrix4.hx",252,0xeb65dbd8)
HX_LOCAL_STACK_FRAME(_hx_pos_a8b6e1b1a7c59cb4_293_create2D,"lime.math._Matrix4.Matrix4_Impl_","create2D",0x26131c56,"lime.math._Matrix4.Matrix4_Impl_.create2D","lime/math/Matrix4.hx",293,0xeb65dbd8)
HX_LOCAL_STACK_FRAME(_hx_pos_a8b6e1b1a7c59cb4_325_createOrtho,"lime.math._Matrix4.Matrix4_Impl_","createOrtho",0x33fdc114,"lime.math._Matrix4.Matrix4_Impl_.createOrtho","lime/math/Matrix4.hx",325,0xeb65dbd8)
HX_LOCAL_STACK_FRAME(_hx_pos_a8b6e1b1a7c59cb4_455_deltaTransformVector,"lime.math._Matrix4.Matrix4_Impl_","deltaTransformVector",0x66f080bf,"lime.math._Matrix4.Matrix4_Impl_.deltaTransformVector","lime/math/Matrix4.hx",455,0xeb65dbd8)
HX_LOCAL_STACK_FRAME(_hx_pos_a8b6e1b1a7c59cb4_465_fromMatrix3,"lime.math._Matrix4.Matrix4_Impl_","fromMatrix3",0x00fd1900,"lime.math._Matrix4.Matrix4_Impl_.fromMatrix3","lime/math/Matrix4.hx",465,0xeb65dbd8)
HX_LOCAL_STACK_FRAME(_hx_pos_a8b6e1b1a7c59cb4_475_identity,"lime.math._Matrix4.Matrix4_Impl_","identity",0xb34e17c6,"lime.math._Matrix4.Matrix4_Impl_.identity","lime/math/Matrix4.hx",475,0xeb65dbd8)
HX_LOCAL_STACK_FRAME(_hx_pos_a8b6e1b1a7c59cb4_503_interpolate,"lime.math._Matrix4.Matrix4_Impl_","interpolate",0xf4884739,"lime.math._Matrix4.Matrix4_Impl_.interpolate","lime/math/Matrix4.hx",503,0xeb65dbd8)
HX_LOCAL_STACK_FRAME(_hx_pos_a8b6e1b1a7c59cb4_521_interpolateTo,"lime.math._Matrix4.Matrix4_Impl_","interpolateTo",0x5c939114,"lime.math._Matrix4.Matrix4_Impl_.interpolateTo","lime/math/Matrix4.hx",521,0xeb65dbd8)
HX_LOCAL_STACK_FRAME(_hx_pos_a8b6e1b1a7c59cb4_532_invert,"lime.math._Matrix4.Matrix4_Impl_","invert",0x1e68879e,"lime.math._Matrix4.Matrix4_Impl_.invert","lime/math/Matrix4.hx",532,0xeb65dbd8)
HX_LOCAL_STACK_FRAME(_hx_pos_a8b6e1b1a7c59cb4_585_pointAt,"lime.math._Matrix4.Matrix4_Impl_","pointAt",0x903e77db,"lime.math._Matrix4.Matrix4_Impl_.pointAt","lime/math/Matrix4.hx",585,0xeb65dbd8)
HX_LOCAL_STACK_FRAME(_hx_pos_a8b6e1b1a7c59cb4_652_prepend,"lime.math._Matrix4.Matrix4_Impl_","prepend",0x76fd6d86,"lime.math._Matrix4.Matrix4_Impl_.prepend","lime/math/Matrix4.hx",652,0xeb65dbd8)
HX_LOCAL_STACK_FRAME(_hx_pos_a8b6e1b1a7c59cb4_683_prependRotation,"lime.math._Matrix4.Matrix4_Impl_","prependRotation",0x52475ce4,"lime.math._Matrix4.Matrix4_Impl_.prependRotation","lime/math/Matrix4.hx",683,0xeb65dbd8)
HX_LOCAL_STACK_FRAME(_hx_pos_a8b6e1b1a7c59cb4_703_prependScale,"lime.math._Matrix4.Matrix4_Impl_","prependScale",0x9a060b24,"lime.math._Matrix4.Matrix4_Impl_.prependScale","lime/math/Matrix4.hx",703,0xeb65dbd8)
HX_LOCAL_STACK_FRAME(_hx_pos_a8b6e1b1a7c59cb4_715_prependTranslation,"lime.math._Matrix4.Matrix4_Impl_","prependTranslation",0xfad7dd0b,"lime.math._Matrix4.Matrix4_Impl_.prependTranslation","lime/math/Matrix4.hx",715,0xeb65dbd8)
HX_LOCAL_STACK_FRAME(_hx_pos_a8b6e1b1a7c59cb4_809_transformVector,"lime.math._Matrix4.Matrix4_Impl_","transformVector",0x3cbf39c7,"lime.math._Matrix4.Matrix4_Impl_.transformVector","lime/math/Matrix4.hx",809,0xeb65dbd8)
HX_LOCAL_STACK_FRAME(_hx_pos_a8b6e1b1a7c59cb4_825_transformVectors,"lime.math._Matrix4.Matrix4_Impl_","transformVectors",0xea9354cc,"lime.math._Matrix4.Matrix4_Impl_.transformVectors","lime/math/Matrix4.hx",825,0xeb65dbd8)
HX_LOCAL_STACK_FRAME(_hx_pos_a8b6e1b1a7c59cb4_847_transpose,"lime.math._Matrix4.Matrix4_Impl_","transpose",0x2d08b4f1,"lime.math._Matrix4.Matrix4_Impl_.transpose","lime/math/Matrix4.hx",847,0xeb65dbd8)
HX_LOCAL_STACK_FRAME(_hx_pos_a8b6e1b1a7c59cb4_857___getAxisRotation,"lime.math._Matrix4.Matrix4_Impl_","__getAxisRotation",0x8b4b420d,"lime.math._Matrix4.Matrix4_Impl_.__getAxisRotation","lime/math/Matrix4.hx",857,0xeb65dbd8)
HX_LOCAL_STACK_FRAME(_hx_pos_a8b6e1b1a7c59cb4_887___swap,"lime.math._Matrix4.Matrix4_Impl_","__swap",0x79e62e3b,"lime.math._Matrix4.Matrix4_Impl_.__swap","lime/math/Matrix4.hx",887,0xeb65dbd8)
HX_LOCAL_STACK_FRAME(_hx_pos_a8b6e1b1a7c59cb4_896_get_determinant,"lime.math._Matrix4.Matrix4_Impl_","get_determinant",0x5d0323a4,"lime.math._Matrix4.Matrix4_Impl_.get_determinant","lime/math/Matrix4.hx",896,0xeb65dbd8)
HX_LOCAL_STACK_FRAME(_hx_pos_a8b6e1b1a7c59cb4_906_get_position,"lime.math._Matrix4.Matrix4_Impl_","get_position",0x55830b3a,"lime.math._Matrix4.Matrix4_Impl_.get_position","lime/math/Matrix4.hx",906,0xeb65dbd8)
HX_LOCAL_STACK_FRAME(_hx_pos_a8b6e1b1a7c59cb4_910_set_position,"lime.math._Matrix4.Matrix4_Impl_","set_position",0x6a7c2eae,"lime.math._Matrix4.Matrix4_Impl_.set_position","lime/math/Matrix4.hx",910,0xeb65dbd8)
HX_LOCAL_STACK_FRAME(_hx_pos_a8b6e1b1a7c59cb4_919_get,"lime.math._Matrix4.Matrix4_Impl_","get",0x10b0bb0e,"lime.math._Matrix4.Matrix4_Impl_.get","lime/math/Matrix4.hx",919,0xeb65dbd8)
HX_LOCAL_STACK_FRAME(_hx_pos_a8b6e1b1a7c59cb4_923_set,"lime.math._Matrix4.Matrix4_Impl_","set",0x10b9d61a,"lime.math._Matrix4.Matrix4_Impl_.set","lime/math/Matrix4.hx",923,0xeb65dbd8)
HX_LOCAL_STACK_FRAME(_hx_pos_a8b6e1b1a7c59cb4_11_boot,"lime.math._Matrix4.Matrix4_Impl_","boot",0x86ac72ba,"lime.math._Matrix4.Matrix4_Impl_.boot","lime/math/Matrix4.hx",11,0xeb65dbd8)
static const Float _hx_array_data_cbf9fee6_38[] = {
1.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,1.0,
};
namespace lime{
namespace math{
namespace _Matrix4{
void Matrix4_Impl__obj::__construct() { }
Dynamic Matrix4_Impl__obj::__CreateEmpty() { return new Matrix4_Impl__obj; }
void *Matrix4_Impl__obj::_hx_vtable = 0;
Dynamic Matrix4_Impl__obj::__Create(hx::DynamicArray inArgs)
{
hx::ObjectPtr< Matrix4_Impl__obj > _hx_result = new Matrix4_Impl__obj();
_hx_result->__construct();
return _hx_result;
}
bool Matrix4_Impl__obj::_hx_isInstanceOf(int inClassId) {
return inClassId==(int)0x00000001 || inClassId==(int)0x71ea7962;
}
::Array< Float > Matrix4_Impl__obj::_hx___identity;
::lime::utils::ArrayBufferView Matrix4_Impl__obj::_new( ::lime::utils::ArrayBufferView data){
HX_GC_STACKFRAME(&_hx_pos_a8b6e1b1a7c59cb4_27__new)
HXDLIN( 27) ::lime::utils::ArrayBufferView this1;
HXLINE( 29) bool _hx_tmp;
HXDLIN( 29) if (hx::IsNotNull( data )) {
HXLINE( 29) _hx_tmp = (data->length == 16);
}
else {
HXLINE( 29) _hx_tmp = false;
}
HXDLIN( 29) if (_hx_tmp) {
HXLINE( 31) this1 = data;
}
else {
HXLINE( 35) ::cpp::VirtualArray array = ::lime::math::_Matrix4::Matrix4_Impl__obj::_hx___identity;
HXDLIN( 35) ::lime::utils::ArrayBufferView this2;
HXDLIN( 35) if (hx::IsNotNull( array )) {
HXLINE( 35) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,8);
HXDLIN( 35) _this->byteOffset = 0;
HXDLIN( 35) _this->length = array->get_length();
HXDLIN( 35) _this->byteLength = (_this->length * _this->bytesPerElement);
HXDLIN( 35) ::haxe::io::Bytes this3 = ::haxe::io::Bytes_obj::alloc(_this->byteLength);
HXDLIN( 35) _this->buffer = this3;
HXDLIN( 35) _this->copyFromArray(array,null());
HXDLIN( 35) this2 = _this;
}
else {
HXLINE( 35) HX_STACK_DO_THROW(HX_("Invalid constructor arguments for Float32Array",8e,c1,f4,d4));
}
HXDLIN( 35) this1 = this2;
}
HXLINE( 27) return this1;
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(Matrix4_Impl__obj,_new,return )
void Matrix4_Impl__obj::append( ::lime::utils::ArrayBufferView this1, ::lime::utils::ArrayBufferView lhs){
HX_STACKFRAME(&_hx_pos_a8b6e1b1a7c59cb4_44_append)
HXLINE( 45) Float m111 = ::__hxcpp_memory_get_float(this1->buffer->b,this1->byteOffset);
HXDLIN( 45) Float m121 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 16));
HXDLIN( 45) Float m131 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 32));
HXDLIN( 45) Float m141 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 48));
HXDLIN( 45) Float m112 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 4));
HXDLIN( 45) Float m122 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 20));
HXDLIN( 45) Float m132 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 36));
HXDLIN( 45) Float m142 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 52));
HXDLIN( 45) Float m113 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 8));
HXDLIN( 45) Float m123 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 24));
HXDLIN( 45) Float m133 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 40));
HXDLIN( 45) Float m143 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 56));
HXDLIN( 45) Float m114 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 12));
HXDLIN( 45) Float m124 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 28));
HXDLIN( 45) Float m134 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 44));
HXDLIN( 45) Float m144 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 60));
HXDLIN( 45) Float m211 = ::lime::math::_Matrix4::Matrix4_Impl__obj::get(lhs,0);
HXDLIN( 45) Float m221 = ::lime::math::_Matrix4::Matrix4_Impl__obj::get(lhs,4);
HXDLIN( 45) Float m231 = ::lime::math::_Matrix4::Matrix4_Impl__obj::get(lhs,8);
HXDLIN( 45) Float m241 = ::lime::math::_Matrix4::Matrix4_Impl__obj::get(lhs,12);
HXDLIN( 45) Float m212 = ::lime::math::_Matrix4::Matrix4_Impl__obj::get(lhs,1);
HXDLIN( 45) Float m222 = ::lime::math::_Matrix4::Matrix4_Impl__obj::get(lhs,5);
HXDLIN( 45) Float m232 = ::lime::math::_Matrix4::Matrix4_Impl__obj::get(lhs,9);
HXDLIN( 45) Float m242 = ::lime::math::_Matrix4::Matrix4_Impl__obj::get(lhs,13);
HXDLIN( 45) Float m213 = ::lime::math::_Matrix4::Matrix4_Impl__obj::get(lhs,2);
HXDLIN( 45) Float m223 = ::lime::math::_Matrix4::Matrix4_Impl__obj::get(lhs,6);
HXDLIN( 45) Float m233 = ::lime::math::_Matrix4::Matrix4_Impl__obj::get(lhs,10);
HXDLIN( 45) Float m243 = ::lime::math::_Matrix4::Matrix4_Impl__obj::get(lhs,14);
HXDLIN( 45) Float m214 = ::lime::math::_Matrix4::Matrix4_Impl__obj::get(lhs,3);
HXDLIN( 45) Float m224 = ::lime::math::_Matrix4::Matrix4_Impl__obj::get(lhs,7);
HXDLIN( 45) Float m234 = ::lime::math::_Matrix4::Matrix4_Impl__obj::get(lhs,11);
HXDLIN( 45) Float m244 = ::lime::math::_Matrix4::Matrix4_Impl__obj::get(lhs,15);
HXLINE( 47) {
HXLINE( 47) Float val = ((((m111 * m211) + (m112 * m221)) + (m113 * m231)) + (m114 * m241));
HXDLIN( 47) ::__hxcpp_memory_set_float(this1->buffer->b,this1->byteOffset,val);
}
HXLINE( 48) {
HXLINE( 48) Float val1 = ((((m111 * m212) + (m112 * m222)) + (m113 * m232)) + (m114 * m242));
HXDLIN( 48) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 4),val1);
}
HXLINE( 49) {
HXLINE( 49) Float val2 = ((((m111 * m213) + (m112 * m223)) + (m113 * m233)) + (m114 * m243));
HXDLIN( 49) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 8),val2);
}
HXLINE( 50) {
HXLINE( 50) Float val3 = ((((m111 * m214) + (m112 * m224)) + (m113 * m234)) + (m114 * m244));
HXDLIN( 50) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 12),val3);
}
HXLINE( 52) {
HXLINE( 52) Float val4 = ((((m121 * m211) + (m122 * m221)) + (m123 * m231)) + (m124 * m241));
HXDLIN( 52) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 16),val4);
}
HXLINE( 53) {
HXLINE( 53) Float val5 = ((((m121 * m212) + (m122 * m222)) + (m123 * m232)) + (m124 * m242));
HXDLIN( 53) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 20),val5);
}
HXLINE( 54) {
HXLINE( 54) Float val6 = ((((m121 * m213) + (m122 * m223)) + (m123 * m233)) + (m124 * m243));
HXDLIN( 54) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 24),val6);
}
HXLINE( 55) {
HXLINE( 55) Float val7 = ((((m121 * m214) + (m122 * m224)) + (m123 * m234)) + (m124 * m244));
HXDLIN( 55) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 28),val7);
}
HXLINE( 57) {
HXLINE( 57) Float val8 = ((((m131 * m211) + (m132 * m221)) + (m133 * m231)) + (m134 * m241));
HXDLIN( 57) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 32),val8);
}
HXLINE( 58) {
HXLINE( 58) Float val9 = ((((m131 * m212) + (m132 * m222)) + (m133 * m232)) + (m134 * m242));
HXDLIN( 58) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 36),val9);
}
HXLINE( 59) {
HXLINE( 59) Float val10 = ((((m131 * m213) + (m132 * m223)) + (m133 * m233)) + (m134 * m243));
HXDLIN( 59) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 40),val10);
}
HXLINE( 60) {
HXLINE( 60) Float val11 = ((((m131 * m214) + (m132 * m224)) + (m133 * m234)) + (m134 * m244));
HXDLIN( 60) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 44),val11);
}
HXLINE( 62) {
HXLINE( 62) Float val12 = ((((m141 * m211) + (m142 * m221)) + (m143 * m231)) + (m144 * m241));
HXDLIN( 62) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 48),val12);
}
HXLINE( 63) {
HXLINE( 63) Float val13 = ((((m141 * m212) + (m142 * m222)) + (m143 * m232)) + (m144 * m242));
HXDLIN( 63) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 52),val13);
}
HXLINE( 64) {
HXLINE( 64) Float val14 = ((((m141 * m213) + (m142 * m223)) + (m143 * m233)) + (m144 * m243));
HXDLIN( 64) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 56),val14);
}
HXLINE( 65) {
HXLINE( 65) Float val15 = ((((m141 * m214) + (m142 * m224)) + (m143 * m234)) + (m144 * m244));
HXDLIN( 65) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 60),val15);
}
}
STATIC_HX_DEFINE_DYNAMIC_FUNC2(Matrix4_Impl__obj,append,(void))
void Matrix4_Impl__obj::appendRotation( ::lime::utils::ArrayBufferView this1,Float degrees, ::lime::math::Vector4 axis, ::lime::math::Vector4 pivotPoint){
HX_STACKFRAME(&_hx_pos_a8b6e1b1a7c59cb4_75_appendRotation)
HXLINE( 76) ::lime::utils::ArrayBufferView m = ::lime::math::_Matrix4::Matrix4_Impl__obj::_hx___getAxisRotation(this1,axis->x,axis->y,axis->z,degrees);
HXLINE( 78) if (hx::IsNotNull( pivotPoint )) {
HXLINE( 80) ::lime::math::Vector4 p = pivotPoint;
HXLINE( 81) ::lime::math::_Matrix4::Matrix4_Impl__obj::appendTranslation(m,p->x,p->y,p->z);
}
HXLINE( 84) ::lime::math::_Matrix4::Matrix4_Impl__obj::append(this1,m);
}
STATIC_HX_DEFINE_DYNAMIC_FUNC4(Matrix4_Impl__obj,appendRotation,(void))
void Matrix4_Impl__obj::appendScale( ::lime::utils::ArrayBufferView this1,Float xScale,Float yScale,Float zScale){
HX_GC_STACKFRAME(&_hx_pos_a8b6e1b1a7c59cb4_95_appendScale)
HXDLIN( 95) ::cpp::VirtualArray array = ::Array_obj< Float >::__new(16)->init(0,xScale)->init(1,((Float)0.0))->init(2,((Float)0.0))->init(3,((Float)0.0))->init(4,((Float)0.0))->init(5,yScale)->init(6,((Float)0.0))->init(7,((Float)0.0))->init(8,((Float)0.0))->init(9,((Float)0.0))->init(10,zScale)->init(11,((Float)0.0))->init(12,((Float)0.0))->init(13,((Float)0.0))->init(14,((Float)0.0))->init(15,((Float)1.0));
HXDLIN( 95) ::lime::utils::ArrayBufferView this2;
HXDLIN( 95) if (hx::IsNotNull( array )) {
HXDLIN( 95) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,8);
HXDLIN( 95) _this->byteOffset = 0;
HXDLIN( 95) _this->length = array->get_length();
HXDLIN( 95) _this->byteLength = (_this->length * _this->bytesPerElement);
HXDLIN( 95) ::haxe::io::Bytes this3 = ::haxe::io::Bytes_obj::alloc(_this->byteLength);
HXDLIN( 95) _this->buffer = this3;
HXDLIN( 95) _this->copyFromArray(array,null());
HXDLIN( 95) this2 = _this;
}
else {
HXDLIN( 95) HX_STACK_DO_THROW(HX_("Invalid constructor arguments for Float32Array",8e,c1,f4,d4));
}
HXDLIN( 95) ::lime::math::_Matrix4::Matrix4_Impl__obj::append(this1,::lime::math::_Matrix4::Matrix4_Impl__obj::_new(this2));
}
STATIC_HX_DEFINE_DYNAMIC_FUNC4(Matrix4_Impl__obj,appendScale,(void))
void Matrix4_Impl__obj::appendTranslation( ::lime::utils::ArrayBufferView this1,Float x,Float y,Float z){
HX_STACKFRAME(&_hx_pos_a8b6e1b1a7c59cb4_107_appendTranslation)
HXLINE( 108) {
HXLINE( 108) Float val = ( ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 48)) + x);
HXDLIN( 108) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 48),val);
}
HXLINE( 109) {
HXLINE( 109) Float val1 = ( ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 52)) + y);
HXDLIN( 109) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 52),val1);
}
HXLINE( 110) {
HXLINE( 110) Float val2 = ( ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 56)) + z);
HXDLIN( 110) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 56),val2);
}
}
STATIC_HX_DEFINE_DYNAMIC_FUNC4(Matrix4_Impl__obj,appendTranslation,(void))
::lime::utils::ArrayBufferView Matrix4_Impl__obj::clone( ::lime::utils::ArrayBufferView this1){
HX_GC_STACKFRAME(&_hx_pos_a8b6e1b1a7c59cb4_119_clone)
HXDLIN( 119) ::lime::utils::ArrayBufferView this2;
HXDLIN( 119) if (hx::IsNotNull( this1 )) {
HXDLIN( 119) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,8);
HXDLIN( 119) ::haxe::io::Bytes srcData = this1->buffer;
HXDLIN( 119) int srcLength = this1->length;
HXDLIN( 119) int srcByteOffset = this1->byteOffset;
HXDLIN( 119) int srcElementSize = this1->bytesPerElement;
HXDLIN( 119) int elementSize = _this->bytesPerElement;
HXDLIN( 119) if ((this1->type == _this->type)) {
HXDLIN( 119) int srcLength1 = srcData->length;
HXDLIN( 119) int cloneLength = (srcLength1 - srcByteOffset);
HXDLIN( 119) ::haxe::io::Bytes this3 = ::haxe::io::Bytes_obj::alloc(cloneLength);
HXDLIN( 119) _this->buffer = this3;
HXDLIN( 119) _this->buffer->blit(0,srcData,srcByteOffset,cloneLength);
}
else {
HXDLIN( 119) HX_STACK_DO_THROW(HX_("unimplemented",09,2f,74,b4));
}
HXDLIN( 119) _this->byteLength = (_this->bytesPerElement * srcLength);
HXDLIN( 119) _this->byteOffset = 0;
HXDLIN( 119) _this->length = srcLength;
HXDLIN( 119) this2 = _this;
}
else {
HXDLIN( 119) HX_STACK_DO_THROW(HX_("Invalid constructor arguments for Float32Array",8e,c1,f4,d4));
}
HXDLIN( 119) return ::lime::math::_Matrix4::Matrix4_Impl__obj::_new(this2);
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(Matrix4_Impl__obj,clone,return )
void Matrix4_Impl__obj::copyColumnFrom( ::lime::utils::ArrayBufferView this1,int column, ::lime::math::Vector4 vector){
HX_STACKFRAME(&_hx_pos_a8b6e1b1a7c59cb4_129_copyColumnFrom)
HXDLIN( 129) switch((int)(column)){
case (int)0: {
HXLINE( 132) {
HXLINE( 132) Float val = vector->x;
HXDLIN( 132) ::__hxcpp_memory_set_float(this1->buffer->b,this1->byteOffset,val);
}
HXLINE( 133) {
HXLINE( 133) Float val1 = vector->y;
HXDLIN( 133) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 4),val1);
}
HXLINE( 134) {
HXLINE( 134) Float val2 = vector->z;
HXDLIN( 134) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 8),val2);
}
HXLINE( 135) {
HXLINE( 135) Float val3 = vector->w;
HXDLIN( 135) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 12),val3);
}
}
break;
case (int)1: {
HXLINE( 138) {
HXLINE( 138) Float val4 = vector->x;
HXDLIN( 138) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 16),val4);
}
HXLINE( 139) {
HXLINE( 139) Float val5 = vector->y;
HXDLIN( 139) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 20),val5);
}
HXLINE( 140) {
HXLINE( 140) Float val6 = vector->z;
HXDLIN( 140) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 24),val6);
}
HXLINE( 141) {
HXLINE( 141) Float val7 = vector->w;
HXDLIN( 141) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 28),val7);
}
}
break;
case (int)2: {
HXLINE( 144) {
HXLINE( 144) Float val8 = vector->x;
HXDLIN( 144) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 32),val8);
}
HXLINE( 145) {
HXLINE( 145) Float val9 = vector->y;
HXDLIN( 145) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 36),val9);
}
HXLINE( 146) {
HXLINE( 146) Float val10 = vector->z;
HXDLIN( 146) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 40),val10);
}
HXLINE( 147) {
HXLINE( 147) Float val11 = vector->w;
HXDLIN( 147) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 44),val11);
}
}
break;
case (int)3: {
HXLINE( 150) {
HXLINE( 150) Float val12 = vector->x;
HXDLIN( 150) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 48),val12);
}
HXLINE( 151) {
HXLINE( 151) Float val13 = vector->y;
HXDLIN( 151) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 52),val13);
}
HXLINE( 152) {
HXLINE( 152) Float val14 = vector->z;
HXDLIN( 152) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 56),val14);
}
HXLINE( 153) {
HXLINE( 153) Float val15 = vector->w;
HXDLIN( 153) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 60),val15);
}
}
break;
default:{
HXLINE( 156) ::lime::utils::Log_obj::error(((HX_("Column ",6a,d4,aa,c0) + column) + HX_(" out of bounds [0, ..., 3]",2f,8b,46,17)),hx::SourceInfo(HX_("lime/math/Matrix4.hx",d8,db,65,eb),156,HX_("lime.math._Matrix4.Matrix4_Impl_",e6,fe,f9,cb),HX_("copyColumnFrom",75,97,b5,3a)));
}
}
}
STATIC_HX_DEFINE_DYNAMIC_FUNC3(Matrix4_Impl__obj,copyColumnFrom,(void))
void Matrix4_Impl__obj::copyColumnTo( ::lime::utils::ArrayBufferView this1,int column, ::lime::math::Vector4 vector){
HX_STACKFRAME(&_hx_pos_a8b6e1b1a7c59cb4_167_copyColumnTo)
HXDLIN( 167) switch((int)(column)){
case (int)0: {
HXLINE( 170) vector->x = ::__hxcpp_memory_get_float(this1->buffer->b,this1->byteOffset);
HXLINE( 171) vector->y = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 4));
HXLINE( 172) vector->z = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 8));
HXLINE( 173) vector->w = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 12));
}
break;
case (int)1: {
HXLINE( 176) vector->x = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 16));
HXLINE( 177) vector->y = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 20));
HXLINE( 178) vector->z = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 24));
HXLINE( 179) vector->w = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 28));
}
break;
case (int)2: {
HXLINE( 182) vector->x = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 32));
HXLINE( 183) vector->y = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 36));
HXLINE( 184) vector->z = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 40));
HXLINE( 185) vector->w = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 44));
}
break;
case (int)3: {
HXLINE( 188) vector->x = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 48));
HXLINE( 189) vector->y = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 52));
HXLINE( 190) vector->z = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 56));
HXLINE( 191) vector->w = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 60));
}
break;
default:{
HXLINE( 194) ::lime::utils::Log_obj::error(((HX_("Column ",6a,d4,aa,c0) + column) + HX_(" out of bounds [0, ..., 3]",2f,8b,46,17)),hx::SourceInfo(HX_("lime/math/Matrix4.hx",d8,db,65,eb),194,HX_("lime.math._Matrix4.Matrix4_Impl_",e6,fe,f9,cb),HX_("copyColumnTo",c6,2e,f6,f6)));
}
}
}
STATIC_HX_DEFINE_DYNAMIC_FUNC3(Matrix4_Impl__obj,copyColumnTo,(void))
void Matrix4_Impl__obj::copyFrom( ::lime::utils::ArrayBufferView this1, ::lime::utils::ArrayBufferView other){
HX_STACKFRAME(&_hx_pos_a8b6e1b1a7c59cb4_204_copyFrom)
HXDLIN( 204) int offset = 0;
HXDLIN( 204) if (hx::IsNotNull( other )) {
HXDLIN( 204) this1->buffer->blit((offset * this1->bytesPerElement),other->buffer,other->byteOffset,other->byteLength);
}
else {
HXDLIN( 204) HX_STACK_DO_THROW(HX_("Invalid .set call. either view, or array must be not-null.",64,ba,b7,6c));
}
}
STATIC_HX_DEFINE_DYNAMIC_FUNC2(Matrix4_Impl__obj,copyFrom,(void))
void Matrix4_Impl__obj::copyRowFrom( ::lime::utils::ArrayBufferView this1,int row, ::lime::math::Vector4 vector){
HX_STACKFRAME(&_hx_pos_a8b6e1b1a7c59cb4_214_copyRowFrom)
HXDLIN( 214) switch((int)(row)){
case (int)0: {
HXLINE( 217) {
HXLINE( 217) Float val = vector->x;
HXDLIN( 217) ::__hxcpp_memory_set_float(this1->buffer->b,this1->byteOffset,val);
}
HXLINE( 218) {
HXLINE( 218) Float val1 = vector->y;
HXDLIN( 218) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 16),val1);
}
HXLINE( 219) {
HXLINE( 219) Float val2 = vector->z;
HXDLIN( 219) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 32),val2);
}
HXLINE( 220) {
HXLINE( 220) Float val3 = vector->w;
HXDLIN( 220) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 48),val3);
}
}
break;
case (int)1: {
HXLINE( 223) {
HXLINE( 223) Float val4 = vector->x;
HXDLIN( 223) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 4),val4);
}
HXLINE( 224) {
HXLINE( 224) Float val5 = vector->y;
HXDLIN( 224) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 20),val5);
}
HXLINE( 225) {
HXLINE( 225) Float val6 = vector->z;
HXDLIN( 225) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 36),val6);
}
HXLINE( 226) {
HXLINE( 226) Float val7 = vector->w;
HXDLIN( 226) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 52),val7);
}
}
break;
case (int)2: {
HXLINE( 229) {
HXLINE( 229) Float val8 = vector->x;
HXDLIN( 229) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 8),val8);
}
HXLINE( 230) {
HXLINE( 230) Float val9 = vector->y;
HXDLIN( 230) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 24),val9);
}
HXLINE( 231) {
HXLINE( 231) Float val10 = vector->z;
HXDLIN( 231) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 40),val10);
}
HXLINE( 232) {
HXLINE( 232) Float val11 = vector->w;
HXDLIN( 232) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 56),val11);
}
}
break;
case (int)3: {
HXLINE( 235) {
HXLINE( 235) Float val12 = vector->x;
HXDLIN( 235) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 12),val12);
}
HXLINE( 236) {
HXLINE( 236) Float val13 = vector->y;
HXDLIN( 236) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 28),val13);
}
HXLINE( 237) {
HXLINE( 237) Float val14 = vector->z;
HXDLIN( 237) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 44),val14);
}
HXLINE( 238) {
HXLINE( 238) Float val15 = vector->w;
HXDLIN( 238) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 60),val15);
}
}
break;
default:{
HXLINE( 241) ::lime::utils::Log_obj::error(((HX_("Row ",e6,20,88,36) + row) + HX_(" out of bounds [0, ..., 3]",2f,8b,46,17)),hx::SourceInfo(HX_("lime/math/Matrix4.hx",d8,db,65,eb),241,HX_("lime.math._Matrix4.Matrix4_Impl_",e6,fe,f9,cb),HX_("copyRowFrom",6f,45,8b,ef)));
}
}
}
STATIC_HX_DEFINE_DYNAMIC_FUNC3(Matrix4_Impl__obj,copyRowFrom,(void))
void Matrix4_Impl__obj::copyRowTo( ::lime::utils::ArrayBufferView this1,int row, ::lime::math::Vector4 vector){
HX_STACKFRAME(&_hx_pos_a8b6e1b1a7c59cb4_252_copyRowTo)
HXDLIN( 252) switch((int)(row)){
case (int)0: {
HXLINE( 255) vector->x = ::__hxcpp_memory_get_float(this1->buffer->b,this1->byteOffset);
HXLINE( 256) vector->y = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 16));
HXLINE( 257) vector->z = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 32));
HXLINE( 258) vector->w = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 48));
}
break;
case (int)1: {
HXLINE( 261) vector->x = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 4));
HXLINE( 262) vector->y = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 20));
HXLINE( 263) vector->z = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 36));
HXLINE( 264) vector->w = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 52));
}
break;
case (int)2: {
HXLINE( 267) vector->x = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 8));
HXLINE( 268) vector->y = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 24));
HXLINE( 269) vector->z = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 40));
HXLINE( 270) vector->w = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 56));
}
break;
case (int)3: {
HXLINE( 273) vector->x = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 12));
HXLINE( 274) vector->y = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 28));
HXLINE( 275) vector->z = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 44));
HXLINE( 276) vector->w = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 60));
}
break;
default:{
HXLINE( 279) ::lime::utils::Log_obj::error(((HX_("Row ",e6,20,88,36) + row) + HX_(" out of bounds [0, ..., 3]",2f,8b,46,17)),hx::SourceInfo(HX_("lime/math/Matrix4.hx",d8,db,65,eb),279,HX_("lime.math._Matrix4.Matrix4_Impl_",e6,fe,f9,cb),HX_("copyRowTo",40,8a,62,73)));
}
}
}
STATIC_HX_DEFINE_DYNAMIC_FUNC3(Matrix4_Impl__obj,copyRowTo,(void))
void Matrix4_Impl__obj::create2D( ::lime::utils::ArrayBufferView this1,Float a,Float b,Float c,Float d,hx::Null< Float > __o_tx,hx::Null< Float > __o_ty){
Float tx = __o_tx.Default(0);
Float ty = __o_ty.Default(0);
HX_STACKFRAME(&_hx_pos_a8b6e1b1a7c59cb4_293_create2D)
HXLINE( 294) ::__hxcpp_memory_set_float(this1->buffer->b,this1->byteOffset,a);
HXLINE( 295) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 4),b);
HXLINE( 296) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 8),0);
HXLINE( 297) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 12),0);
HXLINE( 299) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 16),c);
HXLINE( 300) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 20),d);
HXLINE( 301) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 24),0);
HXLINE( 302) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 28),0);
HXLINE( 304) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 32),0);
HXLINE( 305) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 36),0);
HXLINE( 306) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 40),1);
HXLINE( 307) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 44),0);
HXLINE( 309) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 48),tx);
HXLINE( 310) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 52),ty);
HXLINE( 311) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 56),0);
HXLINE( 312) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 60),1);
}
STATIC_HX_DEFINE_DYNAMIC_FUNC7(Matrix4_Impl__obj,create2D,(void))
void Matrix4_Impl__obj::createOrtho( ::lime::utils::ArrayBufferView this1,Float left,Float right,Float bottom,Float top,Float zNear,Float zFar){
HX_STACKFRAME(&_hx_pos_a8b6e1b1a7c59cb4_325_createOrtho)
HXLINE( 326) Float sx = (((Float)1.0) / (right - left));
HXLINE( 327) Float sy = (((Float)1.0) / (top - bottom));
HXLINE( 328) Float sz = (((Float)1.0) / (zFar - zNear));
HXLINE( 330) {
HXLINE( 330) Float val = (( (Float)(2) ) * sx);
HXDLIN( 330) ::__hxcpp_memory_set_float(this1->buffer->b,this1->byteOffset,val);
}
HXLINE( 331) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 4),0);
HXLINE( 332) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 8),0);
HXLINE( 333) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 12),0);
HXLINE( 335) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 16),0);
HXLINE( 336) {
HXLINE( 336) Float val1 = (( (Float)(2) ) * sy);
HXDLIN( 336) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 20),val1);
}
HXLINE( 337) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 24),0);
HXLINE( 338) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 28),0);
HXLINE( 340) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 32),0);
HXLINE( 341) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 36),0);
HXLINE( 342) {
HXLINE( 342) Float val2 = (( (Float)(-2) ) * sz);
HXDLIN( 342) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 40),val2);
}
HXLINE( 343) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 44),0);
HXLINE( 345) {
HXLINE( 345) Float val3 = (-((left + right)) * sx);
HXDLIN( 345) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 48),val3);
}
HXLINE( 346) {
HXLINE( 346) Float val4 = (-((bottom + top)) * sy);
HXDLIN( 346) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 52),val4);
}
HXLINE( 347) {
HXLINE( 347) Float val5 = (-((zNear + zFar)) * sz);
HXDLIN( 347) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 56),val5);
}
HXLINE( 348) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 60),1);
}
STATIC_HX_DEFINE_DYNAMIC_FUNC7(Matrix4_Impl__obj,createOrtho,(void))
::lime::math::Vector4 Matrix4_Impl__obj::deltaTransformVector( ::lime::utils::ArrayBufferView this1, ::lime::math::Vector4 v, ::lime::math::Vector4 result){
HX_GC_STACKFRAME(&_hx_pos_a8b6e1b1a7c59cb4_455_deltaTransformVector)
HXLINE( 456) if (hx::IsNull( result )) {
HXLINE( 456) result = ::lime::math::Vector4_obj::__alloc( HX_CTX ,null(),null(),null(),null());
}
HXLINE( 457) Float x = v->x;
HXDLIN( 457) Float y = v->y;
HXDLIN( 457) Float z = v->z;
HXLINE( 458) Float _hx_tmp = (x * ::__hxcpp_memory_get_float(this1->buffer->b,this1->byteOffset));
HXDLIN( 458) Float _hx_tmp1 = (_hx_tmp + (y * ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 16))));
HXDLIN( 458) Float _hx_tmp2 = (_hx_tmp1 + (z * ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 32))));
HXDLIN( 458) result->x = (_hx_tmp2 + ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 12)));
HXLINE( 459) Float _hx_tmp3 = (x * ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 4)));
HXDLIN( 459) Float _hx_tmp4 = (_hx_tmp3 + (y * ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 20))));
HXDLIN( 459) Float _hx_tmp5 = (_hx_tmp4 + (z * ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 36))));
HXDLIN( 459) result->y = (_hx_tmp5 + ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 28)));
HXLINE( 460) Float _hx_tmp6 = (x * ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 8)));
HXDLIN( 460) Float _hx_tmp7 = (_hx_tmp6 + (y * ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 24))));
HXDLIN( 460) Float _hx_tmp8 = (_hx_tmp7 + (z * ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 40))));
HXDLIN( 460) result->z = (_hx_tmp8 + ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 44)));
HXLINE( 461) return result;
}
STATIC_HX_DEFINE_DYNAMIC_FUNC3(Matrix4_Impl__obj,deltaTransformVector,return )
::lime::utils::ArrayBufferView Matrix4_Impl__obj::fromMatrix3( ::lime::math::Matrix3 matrix3){
HX_STACKFRAME(&_hx_pos_a8b6e1b1a7c59cb4_465_fromMatrix3)
HXLINE( 466) ::lime::utils::ArrayBufferView mat = ::lime::math::_Matrix4::Matrix4_Impl__obj::_new(null());
HXLINE( 467) ::lime::math::_Matrix4::Matrix4_Impl__obj::create2D(mat,matrix3->a,matrix3->b,matrix3->c,matrix3->d,matrix3->tx,matrix3->ty);
HXLINE( 468) return mat;
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(Matrix4_Impl__obj,fromMatrix3,return )
void Matrix4_Impl__obj::identity( ::lime::utils::ArrayBufferView this1){
HX_STACKFRAME(&_hx_pos_a8b6e1b1a7c59cb4_475_identity)
HXLINE( 476) ::__hxcpp_memory_set_float(this1->buffer->b,this1->byteOffset,1);
HXLINE( 477) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 4),0);
HXLINE( 478) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 8),0);
HXLINE( 479) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 12),0);
HXLINE( 480) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 16),0);
HXLINE( 481) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 20),1);
HXLINE( 482) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 24),0);
HXLINE( 483) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 28),0);
HXLINE( 484) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 32),0);
HXLINE( 485) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 36),0);
HXLINE( 486) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 40),1);
HXLINE( 487) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 44),0);
HXLINE( 488) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 48),0);
HXLINE( 489) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 52),0);
HXLINE( 490) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 56),0);
HXLINE( 491) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 60),1);
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(Matrix4_Impl__obj,identity,(void))
::lime::utils::ArrayBufferView Matrix4_Impl__obj::interpolate( ::lime::utils::ArrayBufferView thisMat, ::lime::utils::ArrayBufferView toMat,Float percent, ::lime::utils::ArrayBufferView result){
HX_STACKFRAME(&_hx_pos_a8b6e1b1a7c59cb4_503_interpolate)
HXLINE( 504) if (hx::IsNull( result )) {
HXLINE( 504) result = ::lime::math::_Matrix4::Matrix4_Impl__obj::_new(null());
}
HXLINE( 506) {
HXLINE( 506) int _g = 0;
HXDLIN( 506) while((_g < 16)){
HXLINE( 506) _g = (_g + 1);
HXDLIN( 506) int i = (_g - 1);
HXLINE( 508) Float _hx_tmp = ::lime::math::_Matrix4::Matrix4_Impl__obj::get(thisMat,i);
HXDLIN( 508) Float _hx_tmp1 = ::lime::math::_Matrix4::Matrix4_Impl__obj::get(toMat,i);
HXDLIN( 508) ::lime::math::_Matrix4::Matrix4_Impl__obj::set(result,i,(_hx_tmp + ((_hx_tmp1 - ::lime::math::_Matrix4::Matrix4_Impl__obj::get(thisMat,i)) * percent)));
}
}
HXLINE( 511) return result;
}
STATIC_HX_DEFINE_DYNAMIC_FUNC4(Matrix4_Impl__obj,interpolate,return )
void Matrix4_Impl__obj::interpolateTo( ::lime::utils::ArrayBufferView this1, ::lime::utils::ArrayBufferView toMat,Float percent){
HX_STACKFRAME(&_hx_pos_a8b6e1b1a7c59cb4_521_interpolateTo)
HXDLIN( 521) int _g = 0;
HXDLIN( 521) while((_g < 16)){
HXDLIN( 521) _g = (_g + 1);
HXDLIN( 521) int i = (_g - 1);
HXLINE( 523) {
HXLINE( 523) Float val = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + (i * 4)));
HXDLIN( 523) Float val1 = ::lime::math::_Matrix4::Matrix4_Impl__obj::get(toMat,i);
HXDLIN( 523) Float val2 = (val + ((val1 - ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + (i * 4)))) * percent));
HXDLIN( 523) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + (i * 4)),val2);
}
}
}
STATIC_HX_DEFINE_DYNAMIC_FUNC3(Matrix4_Impl__obj,interpolateTo,(void))
bool Matrix4_Impl__obj::invert( ::lime::utils::ArrayBufferView this1){
HX_STACKFRAME(&_hx_pos_a8b6e1b1a7c59cb4_532_invert)
HXLINE( 533) Float d = ::lime::math::_Matrix4::Matrix4_Impl__obj::get_determinant(this1);
HXLINE( 534) bool invertable = (::Math_obj::abs(d) > ((Float)0.00000000001));
HXLINE( 536) if (invertable) {
HXLINE( 538) d = (( (Float)(1) ) / d);
HXLINE( 540) Float m11 = ::__hxcpp_memory_get_float(this1->buffer->b,this1->byteOffset);
HXLINE( 541) Float m21 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 16));
HXLINE( 542) Float m31 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 32));
HXLINE( 543) Float m41 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 48));
HXLINE( 544) Float m12 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 4));
HXLINE( 545) Float m22 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 20));
HXLINE( 546) Float m32 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 36));
HXLINE( 547) Float m42 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 52));
HXLINE( 548) Float m13 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 8));
HXLINE( 549) Float m23 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 24));
HXLINE( 550) Float m33 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 40));
HXLINE( 551) Float m43 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 56));
HXLINE( 552) Float m14 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 12));
HXLINE( 553) Float m24 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 28));
HXLINE( 554) Float m34 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 44));
HXLINE( 555) Float m44 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 60));
HXLINE( 557) {
HXLINE( 557) Float val = (d * (((m22 * ((m33 * m44) - (m43 * m34))) - (m32 * ((m23 * m44) - (m43 * m24)))) + (m42 * ((m23 * m34) - (m33 * m24)))));
HXDLIN( 557) ::__hxcpp_memory_set_float(this1->buffer->b,this1->byteOffset,val);
}
HXLINE( 558) {
HXLINE( 558) Float val1 = (-(d) * (((m12 * ((m33 * m44) - (m43 * m34))) - (m32 * ((m13 * m44) - (m43 * m14)))) + (m42 * ((m13 * m34) - (m33 * m14)))));
HXDLIN( 558) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 4),val1);
}
HXLINE( 559) {
HXLINE( 559) Float val2 = (d * (((m12 * ((m23 * m44) - (m43 * m24))) - (m22 * ((m13 * m44) - (m43 * m14)))) + (m42 * ((m13 * m24) - (m23 * m14)))));
HXDLIN( 559) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 8),val2);
}
HXLINE( 560) {
HXLINE( 560) Float val3 = (-(d) * (((m12 * ((m23 * m34) - (m33 * m24))) - (m22 * ((m13 * m34) - (m33 * m14)))) + (m32 * ((m13 * m24) - (m23 * m14)))));
HXDLIN( 560) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 12),val3);
}
HXLINE( 561) {
HXLINE( 561) Float val4 = (-(d) * (((m21 * ((m33 * m44) - (m43 * m34))) - (m31 * ((m23 * m44) - (m43 * m24)))) + (m41 * ((m23 * m34) - (m33 * m24)))));
HXDLIN( 561) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 16),val4);
}
HXLINE( 562) {
HXLINE( 562) Float val5 = (d * (((m11 * ((m33 * m44) - (m43 * m34))) - (m31 * ((m13 * m44) - (m43 * m14)))) + (m41 * ((m13 * m34) - (m33 * m14)))));
HXDLIN( 562) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 20),val5);
}
HXLINE( 563) {
HXLINE( 563) Float val6 = (-(d) * (((m11 * ((m23 * m44) - (m43 * m24))) - (m21 * ((m13 * m44) - (m43 * m14)))) + (m41 * ((m13 * m24) - (m23 * m14)))));
HXDLIN( 563) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 24),val6);
}
HXLINE( 564) {
HXLINE( 564) Float val7 = (d * (((m11 * ((m23 * m34) - (m33 * m24))) - (m21 * ((m13 * m34) - (m33 * m14)))) + (m31 * ((m13 * m24) - (m23 * m14)))));
HXDLIN( 564) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 28),val7);
}
HXLINE( 565) {
HXLINE( 565) Float val8 = (d * (((m21 * ((m32 * m44) - (m42 * m34))) - (m31 * ((m22 * m44) - (m42 * m24)))) + (m41 * ((m22 * m34) - (m32 * m24)))));
HXDLIN( 565) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 32),val8);
}
HXLINE( 566) {
HXLINE( 566) Float val9 = (-(d) * (((m11 * ((m32 * m44) - (m42 * m34))) - (m31 * ((m12 * m44) - (m42 * m14)))) + (m41 * ((m12 * m34) - (m32 * m14)))));
HXDLIN( 566) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 36),val9);
}
HXLINE( 567) {
HXLINE( 567) Float val10 = (d * (((m11 * ((m22 * m44) - (m42 * m24))) - (m21 * ((m12 * m44) - (m42 * m14)))) + (m41 * ((m12 * m24) - (m22 * m14)))));
HXDLIN( 567) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 40),val10);
}
HXLINE( 568) {
HXLINE( 568) Float val11 = (-(d) * (((m11 * ((m22 * m34) - (m32 * m24))) - (m21 * ((m12 * m34) - (m32 * m14)))) + (m31 * ((m12 * m24) - (m22 * m14)))));
HXDLIN( 568) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 44),val11);
}
HXLINE( 569) {
HXLINE( 569) Float val12 = (-(d) * (((m21 * ((m32 * m43) - (m42 * m33))) - (m31 * ((m22 * m43) - (m42 * m23)))) + (m41 * ((m22 * m33) - (m32 * m23)))));
HXDLIN( 569) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 48),val12);
}
HXLINE( 570) {
HXLINE( 570) Float val13 = (d * (((m11 * ((m32 * m43) - (m42 * m33))) - (m31 * ((m12 * m43) - (m42 * m13)))) + (m41 * ((m12 * m33) - (m32 * m13)))));
HXDLIN( 570) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 52),val13);
}
HXLINE( 571) {
HXLINE( 571) Float val14 = (-(d) * (((m11 * ((m22 * m43) - (m42 * m23))) - (m21 * ((m12 * m43) - (m42 * m13)))) + (m41 * ((m12 * m23) - (m22 * m13)))));
HXDLIN( 571) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 56),val14);
}
HXLINE( 572) {
HXLINE( 572) Float val15 = (d * (((m11 * ((m22 * m33) - (m32 * m23))) - (m21 * ((m12 * m33) - (m32 * m13)))) + (m31 * ((m12 * m23) - (m22 * m13)))));
HXDLIN( 572) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 60),val15);
}
}
HXLINE( 575) return invertable;
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(Matrix4_Impl__obj,invert,return )
void Matrix4_Impl__obj::pointAt( ::lime::utils::ArrayBufferView this1, ::lime::math::Vector4 pos, ::lime::math::Vector4 at, ::lime::math::Vector4 up){
HX_GC_STACKFRAME(&_hx_pos_a8b6e1b1a7c59cb4_585_pointAt)
HXLINE( 588) if (hx::IsNull( at )) {
HXLINE( 590) at = ::lime::math::Vector4_obj::__alloc( HX_CTX ,0,0,1,null());
}
HXLINE( 593) if (hx::IsNull( up )) {
HXLINE( 595) up = ::lime::math::Vector4_obj::__alloc( HX_CTX ,0,1,0,null());
}
HXLINE( 598) ::lime::math::Vector4 result = null();
HXDLIN( 598) if (hx::IsNull( result )) {
HXLINE( 598) result = ::lime::math::Vector4_obj::__alloc( HX_CTX ,null(),null(),null(),null());
}
HXDLIN( 598) {
HXLINE( 598) result->x = (pos->x - at->x);
HXDLIN( 598) result->y = (pos->y - at->y);
HXDLIN( 598) result->z = (pos->z - at->z);
}
HXDLIN( 598) ::lime::math::Vector4 dir = result;
HXLINE( 599) ::lime::math::Vector4 vup = ::lime::math::Vector4_obj::__alloc( HX_CTX ,up->x,up->y,up->z,up->w);
HXLINE( 602) {
HXLINE( 602) Float l = ::Math_obj::sqrt((((dir->x * dir->x) + (dir->y * dir->y)) + (dir->z * dir->z)));
HXDLIN( 602) if ((l != 0)) {
HXLINE( 602) ::lime::math::Vector4 dir1 = dir;
HXDLIN( 602) dir1->x = (dir1->x / l);
HXDLIN( 602) ::lime::math::Vector4 dir2 = dir;
HXDLIN( 602) dir2->y = (dir2->y / l);
HXDLIN( 602) ::lime::math::Vector4 dir3 = dir;
HXDLIN( 602) dir3->z = (dir3->z / l);
}
}
HXLINE( 603) {
HXLINE( 603) Float l1 = ::Math_obj::sqrt((((vup->x * vup->x) + (vup->y * vup->y)) + (vup->z * vup->z)));
HXDLIN( 603) if ((l1 != 0)) {
HXLINE( 603) ::lime::math::Vector4 vup1 = vup;
HXDLIN( 603) vup1->x = (vup1->x / l1);
HXDLIN( 603) ::lime::math::Vector4 vup2 = vup;
HXDLIN( 603) vup2->y = (vup2->y / l1);
HXDLIN( 603) ::lime::math::Vector4 vup3 = vup;
HXDLIN( 603) vup3->z = (vup3->z / l1);
}
}
HXLINE( 605) ::lime::math::Vector4 dir21 = ::lime::math::Vector4_obj::__alloc( HX_CTX ,dir->x,dir->y,dir->z,dir->w);
HXLINE( 606) {
HXLINE( 606) Float s = (((vup->x * dir->x) + (vup->y * dir->y)) + (vup->z * dir->z));
HXDLIN( 606) ::lime::math::Vector4 dir22 = dir21;
HXDLIN( 606) dir22->x = (dir22->x * s);
HXDLIN( 606) ::lime::math::Vector4 dir23 = dir21;
HXDLIN( 606) dir23->y = (dir23->y * s);
HXDLIN( 606) ::lime::math::Vector4 dir24 = dir21;
HXDLIN( 606) dir24->z = (dir24->z * s);
}
HXLINE( 608) ::lime::math::Vector4 result1 = null();
HXDLIN( 608) if (hx::IsNull( result1 )) {
HXLINE( 608) result1 = ::lime::math::Vector4_obj::__alloc( HX_CTX ,null(),null(),null(),null());
}
HXDLIN( 608) {
HXLINE( 608) result1->x = (vup->x - dir21->x);
HXDLIN( 608) result1->y = (vup->y - dir21->y);
HXDLIN( 608) result1->z = (vup->z - dir21->z);
}
HXDLIN( 608) vup = result1;
HXLINE( 610) if ((::Math_obj::sqrt((((vup->x * vup->x) + (vup->y * vup->y)) + (vup->z * vup->z))) > 0)) {
HXLINE( 612) Float l2 = ::Math_obj::sqrt((((vup->x * vup->x) + (vup->y * vup->y)) + (vup->z * vup->z)));
HXDLIN( 612) if ((l2 != 0)) {
HXLINE( 612) ::lime::math::Vector4 vup4 = vup;
HXDLIN( 612) vup4->x = (vup4->x / l2);
HXDLIN( 612) ::lime::math::Vector4 vup5 = vup;
HXDLIN( 612) vup5->y = (vup5->y / l2);
HXDLIN( 612) ::lime::math::Vector4 vup6 = vup;
HXDLIN( 612) vup6->z = (vup6->z / l2);
}
}
else {
HXLINE( 616) if ((dir->x != 0)) {
HXLINE( 618) vup = ::lime::math::Vector4_obj::__alloc( HX_CTX ,-(dir->y),dir->x,0,null());
}
else {
HXLINE( 622) vup = ::lime::math::Vector4_obj::__alloc( HX_CTX ,1,0,0,null());
}
}
HXLINE( 626) ::lime::math::Vector4 result2 = null();
HXDLIN( 626) if (hx::IsNull( result2 )) {
HXLINE( 626) result2 = ::lime::math::Vector4_obj::__alloc( HX_CTX ,null(),null(),null(),null());
}
HXDLIN( 626) {
HXLINE( 626) Float ya = ((vup->z * dir->x) - (vup->x * dir->z));
HXDLIN( 626) Float za = ((vup->x * dir->y) - (vup->y * dir->x));
HXDLIN( 626) result2->x = ((vup->y * dir->z) - (vup->z * dir->y));
HXDLIN( 626) result2->y = ya;
HXDLIN( 626) result2->z = za;
}
HXDLIN( 626) result2->w = ( (Float)(1) );
HXLINE( 600) ::lime::math::Vector4 right = result2;
HXLINE( 627) {
HXLINE( 627) Float l3 = ::Math_obj::sqrt((((right->x * right->x) + (right->y * right->y)) + (right->z * right->z)));
HXDLIN( 627) if ((l3 != 0)) {
HXLINE( 627) ::lime::math::Vector4 right1 = right;
HXDLIN( 627) right1->x = (right1->x / l3);
HXDLIN( 627) ::lime::math::Vector4 right2 = right;
HXDLIN( 627) right2->y = (right2->y / l3);
HXDLIN( 627) ::lime::math::Vector4 right3 = right;
HXDLIN( 627) right3->z = (right3->z / l3);
}
}
HXLINE( 629) {
HXLINE( 629) Float val = right->x;
HXDLIN( 629) ::__hxcpp_memory_set_float(this1->buffer->b,this1->byteOffset,val);
}
HXLINE( 630) {
HXLINE( 630) Float val1 = right->y;
HXDLIN( 630) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 16),val1);
}
HXLINE( 631) {
HXLINE( 631) Float val2 = right->z;
HXDLIN( 631) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 32),val2);
}
HXLINE( 632) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 48),((Float)0.0));
HXLINE( 633) {
HXLINE( 633) Float val3 = vup->x;
HXDLIN( 633) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 4),val3);
}
HXLINE( 634) {
HXLINE( 634) Float val4 = vup->y;
HXDLIN( 634) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 20),val4);
}
HXLINE( 635) {
HXLINE( 635) Float val5 = vup->z;
HXDLIN( 635) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 36),val5);
}
HXLINE( 636) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 52),((Float)0.0));
HXLINE( 637) {
HXLINE( 637) Float val6 = dir->x;
HXDLIN( 637) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 8),val6);
}
HXLINE( 638) {
HXLINE( 638) Float val7 = dir->y;
HXDLIN( 638) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 24),val7);
}
HXLINE( 639) {
HXLINE( 639) Float val8 = dir->z;
HXDLIN( 639) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 40),val8);
}
HXLINE( 640) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 56),((Float)0.0));
HXLINE( 641) {
HXLINE( 641) Float val9 = pos->x;
HXDLIN( 641) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 12),val9);
}
HXLINE( 642) {
HXLINE( 642) Float val10 = pos->y;
HXDLIN( 642) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 28),val10);
}
HXLINE( 643) {
HXLINE( 643) Float val11 = pos->z;
HXDLIN( 643) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 44),val11);
}
HXLINE( 644) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 60),((Float)1.0));
}
STATIC_HX_DEFINE_DYNAMIC_FUNC4(Matrix4_Impl__obj,pointAt,(void))
void Matrix4_Impl__obj::prepend( ::lime::utils::ArrayBufferView this1, ::lime::utils::ArrayBufferView rhs){
HX_STACKFRAME(&_hx_pos_a8b6e1b1a7c59cb4_652_prepend)
HXLINE( 653) Float m111 = ::lime::math::_Matrix4::Matrix4_Impl__obj::get(rhs,0);
HXDLIN( 653) Float m121 = ::lime::math::_Matrix4::Matrix4_Impl__obj::get(rhs,4);
HXDLIN( 653) Float m131 = ::lime::math::_Matrix4::Matrix4_Impl__obj::get(rhs,8);
HXDLIN( 653) Float m141 = ::lime::math::_Matrix4::Matrix4_Impl__obj::get(rhs,12);
HXDLIN( 653) Float m112 = ::lime::math::_Matrix4::Matrix4_Impl__obj::get(rhs,1);
HXDLIN( 653) Float m122 = ::lime::math::_Matrix4::Matrix4_Impl__obj::get(rhs,5);
HXDLIN( 653) Float m132 = ::lime::math::_Matrix4::Matrix4_Impl__obj::get(rhs,9);
HXDLIN( 653) Float m142 = ::lime::math::_Matrix4::Matrix4_Impl__obj::get(rhs,13);
HXDLIN( 653) Float m113 = ::lime::math::_Matrix4::Matrix4_Impl__obj::get(rhs,2);
HXDLIN( 653) Float m123 = ::lime::math::_Matrix4::Matrix4_Impl__obj::get(rhs,6);
HXDLIN( 653) Float m133 = ::lime::math::_Matrix4::Matrix4_Impl__obj::get(rhs,10);
HXDLIN( 653) Float m143 = ::lime::math::_Matrix4::Matrix4_Impl__obj::get(rhs,14);
HXDLIN( 653) Float m114 = ::lime::math::_Matrix4::Matrix4_Impl__obj::get(rhs,3);
HXDLIN( 653) Float m124 = ::lime::math::_Matrix4::Matrix4_Impl__obj::get(rhs,7);
HXDLIN( 653) Float m134 = ::lime::math::_Matrix4::Matrix4_Impl__obj::get(rhs,11);
HXDLIN( 653) Float m144 = ::lime::math::_Matrix4::Matrix4_Impl__obj::get(rhs,15);
HXDLIN( 653) Float m211 = ::__hxcpp_memory_get_float(this1->buffer->b,this1->byteOffset);
HXDLIN( 653) Float m221 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 16));
HXDLIN( 653) Float m231 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 32));
HXDLIN( 653) Float m241 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 48));
HXDLIN( 653) Float m212 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 4));
HXDLIN( 653) Float m222 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 20));
HXDLIN( 653) Float m232 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 36));
HXDLIN( 653) Float m242 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 52));
HXDLIN( 653) Float m213 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 8));
HXDLIN( 653) Float m223 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 24));
HXDLIN( 653) Float m233 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 40));
HXDLIN( 653) Float m243 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 56));
HXDLIN( 653) Float m214 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 12));
HXDLIN( 653) Float m224 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 28));
HXDLIN( 653) Float m234 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 44));
HXDLIN( 653) Float m244 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 60));
HXLINE( 655) {
HXLINE( 655) Float val = ((((m111 * m211) + (m112 * m221)) + (m113 * m231)) + (m114 * m241));
HXDLIN( 655) ::__hxcpp_memory_set_float(this1->buffer->b,this1->byteOffset,val);
}
HXLINE( 656) {
HXLINE( 656) Float val1 = ((((m111 * m212) + (m112 * m222)) + (m113 * m232)) + (m114 * m242));
HXDLIN( 656) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 4),val1);
}
HXLINE( 657) {
HXLINE( 657) Float val2 = ((((m111 * m213) + (m112 * m223)) + (m113 * m233)) + (m114 * m243));
HXDLIN( 657) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 8),val2);
}
HXLINE( 658) {
HXLINE( 658) Float val3 = ((((m111 * m214) + (m112 * m224)) + (m113 * m234)) + (m114 * m244));
HXDLIN( 658) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 12),val3);
}
HXLINE( 660) {
HXLINE( 660) Float val4 = ((((m121 * m211) + (m122 * m221)) + (m123 * m231)) + (m124 * m241));
HXDLIN( 660) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 16),val4);
}
HXLINE( 661) {
HXLINE( 661) Float val5 = ((((m121 * m212) + (m122 * m222)) + (m123 * m232)) + (m124 * m242));
HXDLIN( 661) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 20),val5);
}
HXLINE( 662) {
HXLINE( 662) Float val6 = ((((m121 * m213) + (m122 * m223)) + (m123 * m233)) + (m124 * m243));
HXDLIN( 662) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 24),val6);
}
HXLINE( 663) {
HXLINE( 663) Float val7 = ((((m121 * m214) + (m122 * m224)) + (m123 * m234)) + (m124 * m244));
HXDLIN( 663) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 28),val7);
}
HXLINE( 665) {
HXLINE( 665) Float val8 = ((((m131 * m211) + (m132 * m221)) + (m133 * m231)) + (m134 * m241));
HXDLIN( 665) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 32),val8);
}
HXLINE( 666) {
HXLINE( 666) Float val9 = ((((m131 * m212) + (m132 * m222)) + (m133 * m232)) + (m134 * m242));
HXDLIN( 666) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 36),val9);
}
HXLINE( 667) {
HXLINE( 667) Float val10 = ((((m131 * m213) + (m132 * m223)) + (m133 * m233)) + (m134 * m243));
HXDLIN( 667) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 40),val10);
}
HXLINE( 668) {
HXLINE( 668) Float val11 = ((((m131 * m214) + (m132 * m224)) + (m133 * m234)) + (m134 * m244));
HXDLIN( 668) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 44),val11);
}
HXLINE( 670) {
HXLINE( 670) Float val12 = ((((m141 * m211) + (m142 * m221)) + (m143 * m231)) + (m144 * m241));
HXDLIN( 670) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 48),val12);
}
HXLINE( 671) {
HXLINE( 671) Float val13 = ((((m141 * m212) + (m142 * m222)) + (m143 * m232)) + (m144 * m242));
HXDLIN( 671) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 52),val13);
}
HXLINE( 672) {
HXLINE( 672) Float val14 = ((((m141 * m213) + (m142 * m223)) + (m143 * m233)) + (m144 * m243));
HXDLIN( 672) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 56),val14);
}
HXLINE( 673) {
HXLINE( 673) Float val15 = ((((m141 * m214) + (m142 * m224)) + (m143 * m234)) + (m144 * m244));
HXDLIN( 673) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 60),val15);
}
}
STATIC_HX_DEFINE_DYNAMIC_FUNC2(Matrix4_Impl__obj,prepend,(void))
void Matrix4_Impl__obj::prependRotation( ::lime::utils::ArrayBufferView this1,Float degrees, ::lime::math::Vector4 axis, ::lime::math::Vector4 pivotPoint){
HX_STACKFRAME(&_hx_pos_a8b6e1b1a7c59cb4_683_prependRotation)
HXLINE( 684) ::lime::utils::ArrayBufferView m = ::lime::math::_Matrix4::Matrix4_Impl__obj::_hx___getAxisRotation(this1,axis->x,axis->y,axis->z,degrees);
HXLINE( 686) if (hx::IsNotNull( pivotPoint )) {
HXLINE( 688) ::lime::math::Vector4 p = pivotPoint;
HXLINE( 689) ::lime::math::_Matrix4::Matrix4_Impl__obj::appendTranslation(m,p->x,p->y,p->z);
}
HXLINE( 692) ::lime::math::_Matrix4::Matrix4_Impl__obj::prepend(this1,m);
}
STATIC_HX_DEFINE_DYNAMIC_FUNC4(Matrix4_Impl__obj,prependRotation,(void))
void Matrix4_Impl__obj::prependScale( ::lime::utils::ArrayBufferView this1,Float xScale,Float yScale,Float zScale){
HX_GC_STACKFRAME(&_hx_pos_a8b6e1b1a7c59cb4_703_prependScale)
HXDLIN( 703) ::cpp::VirtualArray array = ::Array_obj< Float >::__new(16)->init(0,xScale)->init(1,((Float)0.0))->init(2,((Float)0.0))->init(3,((Float)0.0))->init(4,((Float)0.0))->init(5,yScale)->init(6,((Float)0.0))->init(7,((Float)0.0))->init(8,((Float)0.0))->init(9,((Float)0.0))->init(10,zScale)->init(11,((Float)0.0))->init(12,((Float)0.0))->init(13,((Float)0.0))->init(14,((Float)0.0))->init(15,((Float)1.0));
HXDLIN( 703) ::lime::utils::ArrayBufferView this2;
HXDLIN( 703) if (hx::IsNotNull( array )) {
HXDLIN( 703) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,8);
HXDLIN( 703) _this->byteOffset = 0;
HXDLIN( 703) _this->length = array->get_length();
HXDLIN( 703) _this->byteLength = (_this->length * _this->bytesPerElement);
HXDLIN( 703) ::haxe::io::Bytes this3 = ::haxe::io::Bytes_obj::alloc(_this->byteLength);
HXDLIN( 703) _this->buffer = this3;
HXDLIN( 703) _this->copyFromArray(array,null());
HXDLIN( 703) this2 = _this;
}
else {
HXDLIN( 703) HX_STACK_DO_THROW(HX_("Invalid constructor arguments for Float32Array",8e,c1,f4,d4));
}
HXDLIN( 703) ::lime::math::_Matrix4::Matrix4_Impl__obj::prepend(this1,::lime::math::_Matrix4::Matrix4_Impl__obj::_new(this2));
}
STATIC_HX_DEFINE_DYNAMIC_FUNC4(Matrix4_Impl__obj,prependScale,(void))
void Matrix4_Impl__obj::prependTranslation( ::lime::utils::ArrayBufferView this1,Float x,Float y,Float z){
HX_GC_STACKFRAME(&_hx_pos_a8b6e1b1a7c59cb4_715_prependTranslation)
HXLINE( 716) ::lime::utils::ArrayBufferView m = ::lime::math::_Matrix4::Matrix4_Impl__obj::_new(null());
HXLINE( 717) ::lime::math::_Matrix4::Matrix4_Impl__obj::set_position(m, ::lime::math::Vector4_obj::__alloc( HX_CTX ,x,y,z,null()));
HXLINE( 718) ::lime::math::_Matrix4::Matrix4_Impl__obj::prepend(this1,m);
}
STATIC_HX_DEFINE_DYNAMIC_FUNC4(Matrix4_Impl__obj,prependTranslation,(void))
::lime::math::Vector4 Matrix4_Impl__obj::transformVector( ::lime::utils::ArrayBufferView this1, ::lime::math::Vector4 v, ::lime::math::Vector4 result){
HX_GC_STACKFRAME(&_hx_pos_a8b6e1b1a7c59cb4_809_transformVector)
HXLINE( 810) if (hx::IsNull( result )) {
HXLINE( 810) result = ::lime::math::Vector4_obj::__alloc( HX_CTX ,null(),null(),null(),null());
}
HXLINE( 811) Float x = v->x;
HXDLIN( 811) Float y = v->y;
HXDLIN( 811) Float z = v->z;
HXLINE( 812) Float _hx_tmp = (x * ::__hxcpp_memory_get_float(this1->buffer->b,this1->byteOffset));
HXDLIN( 812) Float _hx_tmp1 = (_hx_tmp + (y * ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 16))));
HXDLIN( 812) Float _hx_tmp2 = (_hx_tmp1 + (z * ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 32))));
HXDLIN( 812) result->x = (_hx_tmp2 + ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 48)));
HXLINE( 813) Float _hx_tmp3 = (x * ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 4)));
HXDLIN( 813) Float _hx_tmp4 = (_hx_tmp3 + (y * ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 20))));
HXDLIN( 813) Float _hx_tmp5 = (_hx_tmp4 + (z * ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 36))));
HXDLIN( 813) result->y = (_hx_tmp5 + ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 52)));
HXLINE( 814) Float _hx_tmp6 = (x * ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 8)));
HXDLIN( 814) Float _hx_tmp7 = (_hx_tmp6 + (y * ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 24))));
HXDLIN( 814) Float _hx_tmp8 = (_hx_tmp7 + (z * ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 40))));
HXDLIN( 814) result->z = (_hx_tmp8 + ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 56)));
HXLINE( 815) Float _hx_tmp9 = (x * ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 12)));
HXDLIN( 815) Float _hx_tmp10 = (_hx_tmp9 + (y * ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 28))));
HXDLIN( 815) Float _hx_tmp11 = (_hx_tmp10 + (z * ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 44))));
HXDLIN( 815) result->w = (_hx_tmp11 + ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 60)));
HXLINE( 816) return result;
}
STATIC_HX_DEFINE_DYNAMIC_FUNC3(Matrix4_Impl__obj,transformVector,return )
void Matrix4_Impl__obj::transformVectors( ::lime::utils::ArrayBufferView this1, ::lime::utils::ArrayBufferView ain, ::lime::utils::ArrayBufferView aout){
HX_STACKFRAME(&_hx_pos_a8b6e1b1a7c59cb4_825_transformVectors)
HXLINE( 826) int i = 0;
HXLINE( 827) Float x;
HXDLIN( 827) Float y;
HXDLIN( 827) Float z;
HXLINE( 829) while(((i + 3) <= ain->length)){
HXLINE( 831) x = ::__hxcpp_memory_get_float(ain->buffer->b,(ain->byteOffset + (i * 4)));
HXLINE( 832) y = ::__hxcpp_memory_get_float(ain->buffer->b,(ain->byteOffset + ((i + 1) * 4)));
HXLINE( 833) z = ::__hxcpp_memory_get_float(ain->buffer->b,(ain->byteOffset + ((i + 2) * 4)));
HXLINE( 835) {
HXLINE( 835) Float val = (x * ::__hxcpp_memory_get_float(this1->buffer->b,this1->byteOffset));
HXDLIN( 835) Float val1 = (val + (y * ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 16))));
HXDLIN( 835) Float val2 = (val1 + (z * ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 32))));
HXDLIN( 835) Float val3 = (val2 + ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 48)));
HXDLIN( 835) ::__hxcpp_memory_set_float(aout->buffer->b,(aout->byteOffset + (i * 4)),val3);
}
HXLINE( 836) {
HXLINE( 836) Float val4 = (x * ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 4)));
HXDLIN( 836) Float val5 = (val4 + (y * ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 20))));
HXDLIN( 836) Float val6 = (val5 + (z * ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 36))));
HXDLIN( 836) Float val7 = (val6 + ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 52)));
HXDLIN( 836) ::__hxcpp_memory_set_float(aout->buffer->b,(aout->byteOffset + ((i + 1) * 4)),val7);
}
HXLINE( 837) {
HXLINE( 837) Float val8 = (x * ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 8)));
HXDLIN( 837) Float val9 = (val8 + (y * ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 24))));
HXDLIN( 837) Float val10 = (val9 + (z * ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 40))));
HXDLIN( 837) Float val11 = (val10 + ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 56)));
HXDLIN( 837) ::__hxcpp_memory_set_float(aout->buffer->b,(aout->byteOffset + ((i + 2) * 4)),val11);
}
HXLINE( 839) i = (i + 3);
}
}
STATIC_HX_DEFINE_DYNAMIC_FUNC3(Matrix4_Impl__obj,transformVectors,(void))
void Matrix4_Impl__obj::transpose( ::lime::utils::ArrayBufferView this1){
HX_STACKFRAME(&_hx_pos_a8b6e1b1a7c59cb4_847_transpose)
HXLINE( 848) {
HXLINE( 848) Float temp = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 4));
HXDLIN( 848) {
HXLINE( 848) Float val = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 16));
HXDLIN( 848) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 4),val);
}
HXDLIN( 848) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 16),temp);
}
HXLINE( 849) {
HXLINE( 849) Float temp1 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 8));
HXDLIN( 849) {
HXLINE( 849) Float val1 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 32));
HXDLIN( 849) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 8),val1);
}
HXDLIN( 849) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 32),temp1);
}
HXLINE( 850) {
HXLINE( 850) Float temp2 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 12));
HXDLIN( 850) {
HXLINE( 850) Float val2 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 48));
HXDLIN( 850) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 12),val2);
}
HXDLIN( 850) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 48),temp2);
}
HXLINE( 851) {
HXLINE( 851) Float temp3 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 24));
HXDLIN( 851) {
HXLINE( 851) Float val3 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 36));
HXDLIN( 851) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 24),val3);
}
HXDLIN( 851) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 36),temp3);
}
HXLINE( 852) {
HXLINE( 852) Float temp4 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 28));
HXDLIN( 852) {
HXLINE( 852) Float val4 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 52));
HXDLIN( 852) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 28),val4);
}
HXDLIN( 852) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 52),temp4);
}
HXLINE( 853) {
HXLINE( 853) Float temp5 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 44));
HXDLIN( 853) {
HXLINE( 853) Float val5 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 56));
HXDLIN( 853) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 44),val5);
}
HXDLIN( 853) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 56),temp5);
}
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(Matrix4_Impl__obj,transpose,(void))
::lime::utils::ArrayBufferView Matrix4_Impl__obj::_hx___getAxisRotation( ::lime::utils::ArrayBufferView this1,Float x,Float y,Float z,Float degrees){
HX_GC_STACKFRAME(&_hx_pos_a8b6e1b1a7c59cb4_857___getAxisRotation)
HXLINE( 858) ::lime::utils::ArrayBufferView m = ::lime::math::_Matrix4::Matrix4_Impl__obj::_new(null());
HXLINE( 860) ::lime::math::Vector4 a1 = ::lime::math::Vector4_obj::__alloc( HX_CTX ,x,y,z,null());
HXLINE( 861) Float rad = (-(degrees) * (::Math_obj::PI / ( (Float)(180) )));
HXLINE( 862) Float c = ::Math_obj::cos(rad);
HXLINE( 863) Float s = ::Math_obj::sin(rad);
HXLINE( 864) Float t = (((Float)1.0) - c);
HXLINE( 866) ::lime::math::_Matrix4::Matrix4_Impl__obj::set(m,0,(c + ((a1->x * a1->x) * t)));
HXLINE( 867) ::lime::math::_Matrix4::Matrix4_Impl__obj::set(m,5,(c + ((a1->y * a1->y) * t)));
HXLINE( 868) ::lime::math::_Matrix4::Matrix4_Impl__obj::set(m,10,(c + ((a1->z * a1->z) * t)));
HXLINE( 870) Float tmp1 = ((a1->x * a1->y) * t);
HXLINE( 871) Float tmp2 = (a1->z * s);
HXLINE( 872) ::lime::math::_Matrix4::Matrix4_Impl__obj::set(m,4,(tmp1 + tmp2));
HXLINE( 873) ::lime::math::_Matrix4::Matrix4_Impl__obj::set(m,1,(tmp1 - tmp2));
HXLINE( 874) tmp1 = ((a1->x * a1->z) * t);
HXLINE( 875) tmp2 = (a1->y * s);
HXLINE( 876) ::lime::math::_Matrix4::Matrix4_Impl__obj::set(m,8,(tmp1 - tmp2));
HXLINE( 877) ::lime::math::_Matrix4::Matrix4_Impl__obj::set(m,2,(tmp1 + tmp2));
HXLINE( 878) tmp1 = ((a1->y * a1->z) * t);
HXLINE( 879) tmp2 = (a1->x * s);
HXLINE( 880) ::lime::math::_Matrix4::Matrix4_Impl__obj::set(m,9,(tmp1 + tmp2));
HXLINE( 881) ::lime::math::_Matrix4::Matrix4_Impl__obj::set(m,6,(tmp1 - tmp2));
HXLINE( 883) return m;
}
STATIC_HX_DEFINE_DYNAMIC_FUNC5(Matrix4_Impl__obj,_hx___getAxisRotation,return )
void Matrix4_Impl__obj::_hx___swap( ::lime::utils::ArrayBufferView this1,int a,int b){
HX_STACKFRAME(&_hx_pos_a8b6e1b1a7c59cb4_887___swap)
HXLINE( 888) Float temp = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + (a * 4)));
HXLINE( 889) {
HXLINE( 889) Float val = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + (b * 4)));
HXDLIN( 889) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + (a * 4)),val);
}
HXLINE( 890) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + (b * 4)),temp);
}
STATIC_HX_DEFINE_DYNAMIC_FUNC3(Matrix4_Impl__obj,_hx___swap,(void))
Float Matrix4_Impl__obj::get_determinant( ::lime::utils::ArrayBufferView this1){
HX_STACKFRAME(&_hx_pos_a8b6e1b1a7c59cb4_896_get_determinant)
HXDLIN( 896) Float _hx_tmp = ::__hxcpp_memory_get_float(this1->buffer->b,this1->byteOffset);
HXDLIN( 896) Float _hx_tmp1 = (_hx_tmp * ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 20)));
HXDLIN( 896) Float _hx_tmp2 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 16));
HXDLIN( 896) Float _hx_tmp3 = (_hx_tmp1 - (_hx_tmp2 * ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 4))));
HXDLIN( 896) Float _hx_tmp4 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 40));
HXDLIN( 896) Float _hx_tmp5 = (_hx_tmp4 * ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 60)));
HXDLIN( 896) Float _hx_tmp6 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 56));
HXDLIN( 896) Float _hx_tmp7 = (_hx_tmp3 * (_hx_tmp5 - (_hx_tmp6 * ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 44)))));
HXLINE( 897) Float _hx_tmp8 = ::__hxcpp_memory_get_float(this1->buffer->b,this1->byteOffset);
HXDLIN( 897) Float _hx_tmp9 = (_hx_tmp8 * ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 36)));
HXDLIN( 897) Float _hx_tmp10 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 32));
HXDLIN( 897) Float _hx_tmp11 = (_hx_tmp9 - (_hx_tmp10 * ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 4))));
HXDLIN( 897) Float _hx_tmp12 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 24));
HXDLIN( 897) Float _hx_tmp13 = (_hx_tmp12 * ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 60)));
HXDLIN( 897) Float _hx_tmp14 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 56));
HXLINE( 896) Float _hx_tmp15 = (_hx_tmp7 - (_hx_tmp11 * (_hx_tmp13 - (_hx_tmp14 * ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 28))))));
HXLINE( 898) Float _hx_tmp16 = ::__hxcpp_memory_get_float(this1->buffer->b,this1->byteOffset);
HXDLIN( 898) Float _hx_tmp17 = (_hx_tmp16 * ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 52)));
HXDLIN( 898) Float _hx_tmp18 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 48));
HXDLIN( 898) Float _hx_tmp19 = (_hx_tmp17 - (_hx_tmp18 * ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 4))));
HXDLIN( 898) Float _hx_tmp20 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 24));
HXDLIN( 898) Float _hx_tmp21 = (_hx_tmp20 * ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 44)));
HXDLIN( 898) Float _hx_tmp22 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 40));
HXLINE( 896) Float _hx_tmp23 = (_hx_tmp15 + (_hx_tmp19 * (_hx_tmp21 - (_hx_tmp22 * ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 28))))));
HXLINE( 899) Float _hx_tmp24 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 16));
HXDLIN( 899) Float _hx_tmp25 = (_hx_tmp24 * ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 36)));
HXDLIN( 899) Float _hx_tmp26 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 32));
HXDLIN( 899) Float _hx_tmp27 = (_hx_tmp25 - (_hx_tmp26 * ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 20))));
HXDLIN( 899) Float _hx_tmp28 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 8));
HXDLIN( 899) Float _hx_tmp29 = (_hx_tmp28 * ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 60)));
HXDLIN( 899) Float _hx_tmp30 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 56));
HXLINE( 896) Float _hx_tmp31 = (_hx_tmp23 + (_hx_tmp27 * (_hx_tmp29 - (_hx_tmp30 * ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 12))))));
HXLINE( 900) Float _hx_tmp32 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 16));
HXDLIN( 900) Float _hx_tmp33 = (_hx_tmp32 * ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 52)));
HXDLIN( 900) Float _hx_tmp34 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 48));
HXDLIN( 900) Float _hx_tmp35 = (_hx_tmp33 - (_hx_tmp34 * ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 20))));
HXDLIN( 900) Float _hx_tmp36 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 8));
HXDLIN( 900) Float _hx_tmp37 = (_hx_tmp36 * ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 44)));
HXDLIN( 900) Float _hx_tmp38 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 40));
HXLINE( 896) Float _hx_tmp39 = (_hx_tmp31 - (_hx_tmp35 * (_hx_tmp37 - (_hx_tmp38 * ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 12))))));
HXLINE( 901) Float _hx_tmp40 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 32));
HXDLIN( 901) Float _hx_tmp41 = (_hx_tmp40 * ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 52)));
HXDLIN( 901) Float _hx_tmp42 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 48));
HXDLIN( 901) Float _hx_tmp43 = (_hx_tmp41 - (_hx_tmp42 * ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 36))));
HXDLIN( 901) Float _hx_tmp44 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 8));
HXDLIN( 901) Float _hx_tmp45 = (_hx_tmp44 * ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 28)));
HXDLIN( 901) Float _hx_tmp46 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 24));
HXLINE( 896) return (_hx_tmp39 + (_hx_tmp43 * (_hx_tmp45 - (_hx_tmp46 * ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 12))))));
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(Matrix4_Impl__obj,get_determinant,return )
::lime::math::Vector4 Matrix4_Impl__obj::get_position( ::lime::utils::ArrayBufferView this1){
HX_GC_STACKFRAME(&_hx_pos_a8b6e1b1a7c59cb4_906_get_position)
HXDLIN( 906) Float _hx_tmp = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 48));
HXDLIN( 906) Float _hx_tmp1 = ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 52));
HXDLIN( 906) return ::lime::math::Vector4_obj::__alloc( HX_CTX ,_hx_tmp,_hx_tmp1, ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + 56)),null());
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(Matrix4_Impl__obj,get_position,return )
::lime::math::Vector4 Matrix4_Impl__obj::set_position( ::lime::utils::ArrayBufferView this1, ::lime::math::Vector4 val){
HX_STACKFRAME(&_hx_pos_a8b6e1b1a7c59cb4_910_set_position)
HXLINE( 911) {
HXLINE( 911) Float val1 = val->x;
HXDLIN( 911) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 48),val1);
}
HXLINE( 912) {
HXLINE( 912) Float val2 = val->y;
HXDLIN( 912) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 52),val2);
}
HXLINE( 913) {
HXLINE( 913) Float val3 = val->z;
HXDLIN( 913) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + 56),val3);
}
HXLINE( 914) return val;
}
STATIC_HX_DEFINE_DYNAMIC_FUNC2(Matrix4_Impl__obj,set_position,return )
Float Matrix4_Impl__obj::get( ::lime::utils::ArrayBufferView this1,int index){
HX_STACKFRAME(&_hx_pos_a8b6e1b1a7c59cb4_919_get)
HXDLIN( 919) return ::__hxcpp_memory_get_float(this1->buffer->b,(this1->byteOffset + (index * 4)));
}
STATIC_HX_DEFINE_DYNAMIC_FUNC2(Matrix4_Impl__obj,get,return )
Float Matrix4_Impl__obj::set( ::lime::utils::ArrayBufferView this1,int index,Float value){
HX_STACKFRAME(&_hx_pos_a8b6e1b1a7c59cb4_923_set)
HXLINE( 924) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + (index * 4)),value);
HXLINE( 925) return value;
}
STATIC_HX_DEFINE_DYNAMIC_FUNC3(Matrix4_Impl__obj,set,return )
Matrix4_Impl__obj::Matrix4_Impl__obj()
{
}
bool Matrix4_Impl__obj::__GetStatic(const ::String &inName, Dynamic &outValue, hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 3:
if (HX_FIELD_EQ(inName,"get") ) { outValue = get_dyn(); return true; }
if (HX_FIELD_EQ(inName,"set") ) { outValue = set_dyn(); return true; }
break;
case 4:
if (HX_FIELD_EQ(inName,"_new") ) { outValue = _new_dyn(); return true; }
break;
case 5:
if (HX_FIELD_EQ(inName,"clone") ) { outValue = clone_dyn(); return true; }
break;
case 6:
if (HX_FIELD_EQ(inName,"append") ) { outValue = append_dyn(); return true; }
if (HX_FIELD_EQ(inName,"invert") ) { outValue = invert_dyn(); return true; }
if (HX_FIELD_EQ(inName,"__swap") ) { outValue = _hx___swap_dyn(); return true; }
break;
case 7:
if (HX_FIELD_EQ(inName,"pointAt") ) { outValue = pointAt_dyn(); return true; }
if (HX_FIELD_EQ(inName,"prepend") ) { outValue = prepend_dyn(); return true; }
break;
case 8:
if (HX_FIELD_EQ(inName,"copyFrom") ) { outValue = copyFrom_dyn(); return true; }
if (HX_FIELD_EQ(inName,"create2D") ) { outValue = create2D_dyn(); return true; }
if (HX_FIELD_EQ(inName,"identity") ) { outValue = identity_dyn(); return true; }
break;
case 9:
if (HX_FIELD_EQ(inName,"copyRowTo") ) { outValue = copyRowTo_dyn(); return true; }
if (HX_FIELD_EQ(inName,"transpose") ) { outValue = transpose_dyn(); return true; }
break;
case 11:
if (HX_FIELD_EQ(inName,"appendScale") ) { outValue = appendScale_dyn(); return true; }
if (HX_FIELD_EQ(inName,"copyRowFrom") ) { outValue = copyRowFrom_dyn(); return true; }
if (HX_FIELD_EQ(inName,"createOrtho") ) { outValue = createOrtho_dyn(); return true; }
if (HX_FIELD_EQ(inName,"fromMatrix3") ) { outValue = fromMatrix3_dyn(); return true; }
if (HX_FIELD_EQ(inName,"interpolate") ) { outValue = interpolate_dyn(); return true; }
break;
case 12:
if (HX_FIELD_EQ(inName,"copyColumnTo") ) { outValue = copyColumnTo_dyn(); return true; }
if (HX_FIELD_EQ(inName,"prependScale") ) { outValue = prependScale_dyn(); return true; }
if (HX_FIELD_EQ(inName,"get_position") ) { outValue = get_position_dyn(); return true; }
if (HX_FIELD_EQ(inName,"set_position") ) { outValue = set_position_dyn(); return true; }
break;
case 13:
if (HX_FIELD_EQ(inName,"interpolateTo") ) { outValue = interpolateTo_dyn(); return true; }
break;
case 14:
if (HX_FIELD_EQ(inName,"appendRotation") ) { outValue = appendRotation_dyn(); return true; }
if (HX_FIELD_EQ(inName,"copyColumnFrom") ) { outValue = copyColumnFrom_dyn(); return true; }
break;
case 15:
if (HX_FIELD_EQ(inName,"prependRotation") ) { outValue = prependRotation_dyn(); return true; }
if (HX_FIELD_EQ(inName,"transformVector") ) { outValue = transformVector_dyn(); return true; }
if (HX_FIELD_EQ(inName,"get_determinant") ) { outValue = get_determinant_dyn(); return true; }
break;
case 16:
if (HX_FIELD_EQ(inName,"transformVectors") ) { outValue = transformVectors_dyn(); return true; }
break;
case 17:
if (HX_FIELD_EQ(inName,"appendTranslation") ) { outValue = appendTranslation_dyn(); return true; }
if (HX_FIELD_EQ(inName,"__getAxisRotation") ) { outValue = _hx___getAxisRotation_dyn(); return true; }
break;
case 18:
if (HX_FIELD_EQ(inName,"prependTranslation") ) { outValue = prependTranslation_dyn(); return true; }
break;
case 20:
if (HX_FIELD_EQ(inName,"deltaTransformVector") ) { outValue = deltaTransformVector_dyn(); return true; }
}
return false;
}
#ifdef HXCPP_SCRIPTABLE
static hx::StorageInfo *Matrix4_Impl__obj_sMemberStorageInfo = 0;
static hx::StaticInfo Matrix4_Impl__obj_sStaticStorageInfo[] = {
{hx::fsObject /* ::Array< Float > */ ,(void *) &Matrix4_Impl__obj::_hx___identity,HX_("__identity",5e,b8,67,5c)},
{ hx::fsUnknown, 0, null()}
};
#endif
static void Matrix4_Impl__obj_sMarkStatics(HX_MARK_PARAMS) {
HX_MARK_MEMBER_NAME(Matrix4_Impl__obj::_hx___identity,"__identity");
};
#ifdef HXCPP_VISIT_ALLOCS
static void Matrix4_Impl__obj_sVisitStatics(HX_VISIT_PARAMS) {
HX_VISIT_MEMBER_NAME(Matrix4_Impl__obj::_hx___identity,"__identity");
};
#endif
hx::Class Matrix4_Impl__obj::__mClass;
static ::String Matrix4_Impl__obj_sStaticFields[] = {
HX_("__identity",5e,b8,67,5c),
HX_("_new",61,15,1f,3f),
HX_("append",da,e1,d3,8f),
HX_("appendRotation",38,45,e8,cb),
HX_("appendScale",50,66,45,b5),
HX_("appendTranslation",37,e1,3d,d6),
HX_("clone",5d,13,63,48),
HX_("copyColumnFrom",75,97,b5,3a),
HX_("copyColumnTo",c6,2e,f6,f6),
HX_("copyFrom",bf,0b,61,c8),
HX_("copyRowFrom",6f,45,8b,ef),
HX_("copyRowTo",40,8a,62,73),
HX_("create2D",ce,49,f4,2b),
HX_("createOrtho",9c,4e,a8,5e),
HX_("deltaTransformVector",37,02,9c,c2),
HX_("fromMatrix3",88,a6,a7,2b),
HX_("identity",3e,45,2f,b9),
HX_("interpolate",c1,d4,32,1f),
HX_("interpolateTo",9c,90,22,71),
HX_("invert",16,e7,d8,9f),
HX_("pointAt",63,a1,21,51),
HX_("prepend",0e,97,e0,37),
HX_("prependRotation",6c,4e,3b,e8),
HX_("prependScale",9c,54,97,c4),
HX_("prependTranslation",83,90,15,05),
HX_("transformVector",4f,2b,b3,d2),
HX_("transformVectors",44,ba,12,8a),
HX_("transpose",79,50,2f,4c),
HX_("__getAxisRotation",95,a5,44,7b),
HX_("__swap",b3,8d,56,fb),
HX_("get_determinant",2c,15,f7,f2),
HX_("get_position",b2,54,14,80),
HX_("set_position",26,78,0d,95),
HX_("get",96,80,4e,00),
HX_("set",a2,9b,57,00),
::String(null())
};
void Matrix4_Impl__obj::__register()
{
Matrix4_Impl__obj _hx_dummy;
Matrix4_Impl__obj::_hx_vtable = *(void **)&_hx_dummy;
hx::Static(__mClass) = new hx::Class_obj();
__mClass->mName = HX_("lime.math._Matrix4.Matrix4_Impl_",e6,fe,f9,cb);
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &Matrix4_Impl__obj::__GetStatic;
__mClass->mSetStaticField = &hx::Class_obj::SetNoStaticField;
__mClass->mMarkFunc = Matrix4_Impl__obj_sMarkStatics;
__mClass->mStatics = hx::Class_obj::dupFunctions(Matrix4_Impl__obj_sStaticFields);
__mClass->mMembers = hx::Class_obj::dupFunctions(0 /* sMemberFields */);
__mClass->mCanCast = hx::TCanCast< Matrix4_Impl__obj >;
#ifdef HXCPP_VISIT_ALLOCS
__mClass->mVisitFunc = Matrix4_Impl__obj_sVisitStatics;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = Matrix4_Impl__obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = Matrix4_Impl__obj_sStaticStorageInfo;
#endif
hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
void Matrix4_Impl__obj::__boot()
{
{
HX_STACKFRAME(&_hx_pos_a8b6e1b1a7c59cb4_11_boot)
HXDLIN( 11) _hx___identity = ::Array_obj< Float >::fromData( _hx_array_data_cbf9fee6_38,16);
}
}
} // end namespace lime
} // end namespace math
} // end namespace _Matrix4
| 58.477173 | 414 | 0.662478 | [
"vector",
"3d"
] |
51724537a5ebc0d892c3e3e767797b63df5d7b34 | 32,220 | hpp | C++ | include/astro/orbitalElementConversions.hpp | srikarad07/astro | e7beea121e26780ba3dcbde058271ffe03699d76 | [
"MIT"
] | null | null | null | include/astro/orbitalElementConversions.hpp | srikarad07/astro | e7beea121e26780ba3dcbde058271ffe03699d76 | [
"MIT"
] | null | null | null | include/astro/orbitalElementConversions.hpp | srikarad07/astro | e7beea121e26780ba3dcbde058271ffe03699d76 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2014-2016 Kartik Kumar, Dinamica Srl (me@kartikkumar.com)
* Copyright (c) 2014-2016 Marko Jankovic, DFKI GmbH
* Copyright (c) 2014-2016 Natalia Ortiz, University of Southampton
* Copyright (c) 2014-2016 Juan Romero, University of Strathclyde
* Distributed under the MIT License.
* See accompanying file LICENSE.md or copy at http://opensource.org/licenses/MIT
*/
#ifndef ASTRO_ORBITAL_ELEMENT_CONVERSIONS_HPP
#define ASTRO_ORBITAL_ELEMENT_CONVERSIONS_HPP
#include <algorithm>
#include <cmath>
#include <limits>
#include <stdexcept>
#include <vector>
#include <sml/sml.hpp>
#include "astro/stateVectorIndices.hpp"
namespace astro
{
//! Convert Cartesian elements to Keplerian elements.
/*!
* Converts a given set of Cartesian elements (position, velocity) to classical (osculating)
* Keplerian elements. See Chobotov (2006) for a full derivation of the conversion.
*
* The tolerance is given a default value. It should not be changed unless required for specific
* scenarios. Below this tolerance value for eccentricity and inclination, the orbit is considered
* to be a limit case. Essentially, special solutions are then used for parabolic, circular
* inclined, non-circular equatorial, and circular equatorial orbits. These special solutions are
* required because of singularities in the classical Keplerian elements. If high precision is
* required near these singularities, users are encouraged to consider using other elements, such
* as Modified Equinoctial Elements (MEE). It should be noted that MEE also suffer from
* singularities, but not for zero eccentricity and inclination.
*
* WARNING: If eccentricity is 1.0 within tolerance, keplerianElements( 0 ) = semi-latus rectum,
* since the orbit is parabolic.
* WARNING: If eccentricity is 0.0 within tolerance, argument of periapsis is set to 0.0, since the
* orbit is circular.
* WARNING: If inclination is 0.0 within tolerance, longitude of ascending node is set to 0.0, since
* since the orbit is equatorial.
*
* @tparam Real Real type
* @tparam Vector Vector type
* @param cartesianElements Vector containing Cartesian elements <br>
* N.B.: Order of elements is important! <br>
* cartesianElements( 0 ) = x-position coordinate [m] <br>
* cartesianElements( 1 ) = y-position coordinate [m] <br>
* cartesianElements( 2 ) = z-position coordinate [m] <br>
* cartesianElements( 3 ) = x-velocity coordinate [m/s] <br>
* cartesianElements( 4 ) = y-velocity coordinate [m/s] <br>
* cartesianElements( 5 ) = z-velocity coordinate [m/s]
* @param gravitationalParameter Gravitational parameter of central body [m^3 s^-2]
* @param tolerance Tolerance used to check for limit cases
* (eccentricity, inclination)
* @return Converted vector of Keplerian elements <br>
* N.B.: Order of elements is important! <br>
* keplerianElements( 0 ) = semiMajorAxis [m] <br>
* keplerianElements( 1 ) = eccentricity [-] <br>
* keplerianElements( 2 ) = inclination [rad] <br>
* keplerianElements( 3 ) = argument of periapsis [rad] <br>
* keplerianElements( 4 ) = longitude of ascending node [rad] <br>
* keplerianElements( 5 ) = true anomaly [rad]
*/
template< typename Real, typename Vector6 >
Vector6 convertCartesianToKeplerianElements(
const Vector6& cartesianElements,
const Real gravitationalParameter,
const Real tolerance = 10.0 * std::numeric_limits< Real >::epsilon( ) )
{
// Check that the Cartesian elements vector contains exactly 6 elemenets and otherwise throw
// and error.
if ( cartesianElements.size( ) != 6 )
{
throw std::runtime_error(
"ERROR: Cartesian elements vector has more or less than 6 elements!" );
}
Vector6 keplerianElements = cartesianElements;
// Set position and velocity vectors.
std::vector< Real > position( 3 );
position[ xPositionIndex ] = cartesianElements[ xPositionIndex ];
position[ yPositionIndex ] = cartesianElements[ yPositionIndex ];
position[ zPositionIndex ] = cartesianElements[ zPositionIndex ];
std::vector< Real > velocity( 3 );
velocity[ 0 ] = cartesianElements[ xVelocityIndex ];
velocity[ 1 ] = cartesianElements[ yVelocityIndex ];
velocity[ 2 ] = cartesianElements[ zVelocityIndex ];
// Compute orbital angular momentum vector.
const std::vector< Real > angularMomentum( sml::cross( position, velocity ) );
// Compute semi-latus rectum.
const Real semiLatusRectum
= sml::squaredNorm< Real >( angularMomentum ) / gravitationalParameter;
// Compute unit vector to ascending node.
std::vector< Real > ascendingNodeUnitVector
= sml::normalize< Real >(
sml::cross( sml::getZUnitVector< std::vector< Real > >( ),
sml::normalize< Real >( angularMomentum ) ) );
// Compute eccentricity vector.
std::vector< Real > eccentricityVector
= sml::add( sml::multiply( sml::cross( velocity, angularMomentum ),
1.0 / gravitationalParameter ),
sml::multiply( sml::normalize< Real >( position ), -1.0 ) );
// Store eccentricity.
keplerianElements[ eccentricityIndex ] = sml::norm< Real >( eccentricityVector );
// Compute and store semi-major axis.
// Check if orbit is parabolic. If it is, store the semi-latus rectum instead of the
// semi-major axis.
if ( std::fabs( keplerianElements[ eccentricityIndex ] - 1.0 ) < tolerance )
{
keplerianElements[ semiLatusRectumIndex ] = semiLatusRectum;
}
// Else the orbit is either elliptical or hyperbolic, so store the semi-major axis.
else
{
keplerianElements[ semiMajorAxisIndex ]
= semiLatusRectum / ( 1.0 - keplerianElements[ eccentricityIndex ]
* keplerianElements[ eccentricityIndex ] );
}
// Compute and store inclination.
keplerianElements[ inclinationIndex ]
= std::acos( angularMomentum[ zPositionIndex ] / sml::norm< Real >( angularMomentum ) );
// Compute and store longitude of ascending node.
// Define the quadrant condition for the argument of perigee.
Real argumentOfPeriapsisQuandrantCondition = eccentricityVector[ zPositionIndex ];
// Check if the orbit is equatorial. If it is, set the vector to the line of nodes to the
// x-axis.
if ( std::fabs( keplerianElements[ inclinationIndex ] ) < tolerance )
{
ascendingNodeUnitVector = sml::getXUnitVector< std::vector< Real > >( );
// If the orbit is equatorial, eccentricityVector_z is zero, therefore the quadrant
// condition is taken to be the y-component, eccentricityVector_y.
argumentOfPeriapsisQuandrantCondition = eccentricityVector[ yPositionIndex ];
}
// Compute and store the resulting longitude of ascending node.
keplerianElements[ longitudeOfAscendingNodeIndex ]
= std::acos( ascendingNodeUnitVector[ xPositionIndex ] );
// Check if the quandrant is correct.
if ( ascendingNodeUnitVector[ yPositionIndex ] < 0.0 )
{
keplerianElements[ longitudeOfAscendingNodeIndex ]
= 2.0 * sml::SML_PI - keplerianElements[ longitudeOfAscendingNodeIndex ];
}
// Compute and store argument of periapsis.
// Define the quadrant condition for the true anomaly.
Real trueAnomalyQuandrantCondition = sml::dot< Real >( position, velocity );
// Check if the orbit is circular. If it is, set the eccentricity vector to unit vector
// pointing to the ascending node, i.e. set the argument of periapsis to zero.
if ( std::fabs( keplerianElements[ eccentricityIndex ] ) < tolerance )
{
eccentricityVector = ascendingNodeUnitVector;
keplerianElements[ argumentOfPeriapsisIndex ] = 0.0;
// Check if orbit is also equatorial and set true anomaly quandrant check condition
// accordingly.
if ( ascendingNodeUnitVector == sml::getXUnitVector< std::vector< Real > >( ) )
{
// If the orbit is circular, dot( position, velocity ) = 0, therefore this value
// cannot be used as a quadrant condition. Moreover, if the orbit is equatorial,
// position_z is also zero and therefore the quadrant condition is taken to be the
// y-component, position_y.
trueAnomalyQuandrantCondition = position[ yPositionIndex ];
}
else
{
// If the orbit is circular, dot( position, velocity ) = 0, therefore the quadrant
// condition is taken to be the z-component of the position, position_z.
trueAnomalyQuandrantCondition = position[ zPositionIndex ];
}
}
// Else, compute the argument of periapsis as the angle between the eccentricity vector and
// the unit vector to the ascending node.
else
{
keplerianElements[ argumentOfPeriapsisIndex ]
= std::acos( sml::dot< Real >( sml::normalize< Real >( eccentricityVector ),
ascendingNodeUnitVector ) );
// Check if the quadrant is correct.
if ( argumentOfPeriapsisQuandrantCondition < 0.0 )
{
keplerianElements[ argumentOfPeriapsisIndex ]
= 2.0 * sml::SML_PI - keplerianElements[ argumentOfPeriapsisIndex ];
}
}
// Compute dot-product of position and eccentricity vectors.
Real dotProductPositionAndEccentricityVectors
= sml::dot< Real >( sml::normalize< Real >( position ),
sml::normalize< Real >( eccentricityVector ) );
// Check if the dot-product is one of the limiting cases: 0.0 or 1.0
// (within prescribed tolerance).
if ( std::fabs( 1.0 - dotProductPositionAndEccentricityVectors ) < tolerance )
{
dotProductPositionAndEccentricityVectors = 1.0;
}
if ( std::fabs( dotProductPositionAndEccentricityVectors ) < tolerance )
{
dotProductPositionAndEccentricityVectors = 0.0;
}
// Compute and store true anomaly.
keplerianElements[ trueAnomalyIndex ] = std::acos( dotProductPositionAndEccentricityVectors );
// Check if the quandrant is correct.
if ( trueAnomalyQuandrantCondition < 0.0 )
{
keplerianElements[ trueAnomalyIndex ]
= 2.0 * sml::SML_PI - keplerianElements[ trueAnomalyIndex ];
}
return keplerianElements;
}
//! Convert Keplerian elements to Cartesian elements.
/*!
* Converts a given set of Keplerian (osculating) elements to Cartesian elements (position,
* velocity). See Chobotov (2006) for a full derivation of the conversion.
*
* WARNING: If eccentricity is 1.0 within tolerance, the user should provide
* keplerianElements( 0 ) = semi-latus rectum, since the orbit is parabolic.
*
* @tparam Real Real type
* @tparam Vector Vector type
* @param keplerianElements Vector containing Keplerian elemenets <br>
* N.B.: Order of elements is important! <br>
* keplerianElements( 0 ) = semiMajorAxis [m] <br>
* keplerianElements( 1 ) = eccentricity [-] <br>
* keplerianElements( 2 ) = inclination [rad] <br>
* keplerianElements( 3 ) = argument of periapsis [rad] <br>
* keplerianElements( 4 ) = longitude of [rad]
* ascending node [rad] <br>
* keplerianElements( 5 ) = true anomaly [rad]
* @param gravitationalParameter Gravitational parameter of central body [m^3 s^-2]
* @param tolerance Tolerance used to check for limit case of eccentricity
* @return Converted vector of Cartesian elements <br>
* N.B.: Order of elements is important! <br>
* cartesianElements( 0 ) = x-position coordinate [m] <br>
* cartesianElements( 1 ) = y-position coordinate [m] <br>
* cartesianElements( 2 ) = z-position coordinate [m] <br>
* cartesianElements( 3 ) = x-velocity coordinate [m/s] <br>
* cartesianElements( 4 ) = y-velocity coordinate [m/s] <br>
* cartesianElements( 5 ) = z-velocity coordinate [m/s]
*/
template< typename Real, typename Vector6 >
Vector6 convertKeplerianToCartesianElements(
const Vector6& keplerianElements, const Real gravitationalParameter,
const Real tolerance = 10.0 * std::numeric_limits< Real >::epsilon( ) )
{
Vector6 cartesianElements = keplerianElements;
const Real semiMajorAxis = keplerianElements[ semiMajorAxisIndex ];
const Real eccentricity = keplerianElements[ eccentricityIndex ];
const Real inclination = keplerianElements[ inclinationIndex ];
const Real argumentOfPeriapsis = keplerianElements[ argumentOfPeriapsisIndex ];
const Real longitudeOfAscendingNode = keplerianElements[ longitudeOfAscendingNodeIndex ];
const Real trueAnomaly = keplerianElements[ trueAnomalyIndex ];
// Pre-compute sines and cosines of angles for efficient computation.
const Real cosineOfInclination = std::cos( inclination );
const Real sineOfInclination = std::sin( inclination );
const Real cosineOfArgumentOfPeriapsis = std::cos( argumentOfPeriapsis );
const Real sineOfArgumentOfPeriapsis = std::sin( argumentOfPeriapsis );
const Real cosineOfLongitudeOfAscendingNode = std::cos( longitudeOfAscendingNode );
const Real sineOfLongitudeOfAscendingNode = std::sin( longitudeOfAscendingNode );
const Real cosineOfTrueAnomaly = std::cos( trueAnomaly );
const Real sineOfTrueAnomaly = std::sin( trueAnomaly );
// Compute semi-latus rectum in the case the orbit is not a parabola.
Real semiLatusRectum = 0.0;
if ( std::fabs( eccentricity - 1.0 ) > tolerance )
{
semiLatusRectum = semiMajorAxis * ( 1.0 - eccentricity * eccentricity );
}
// Else set the semi-latus rectum as the first element in the vector of Keplerian elements.
else
{
semiLatusRectum = keplerianElements[ 0 ];
}
// Compute the magnitude of the orbital radius, measured from the focal point.
const Real radiusMagnitude = semiLatusRectum / ( 1.0 + eccentricity * cosineOfTrueAnomaly );
// Define position and velocity in the perifocal coordinate system.
const Real xPositionPerifocal = radiusMagnitude * cosineOfTrueAnomaly;
const Real yPositionPerifocal = radiusMagnitude * sineOfTrueAnomaly;
const Real xVelocityPerifocal
= -std::sqrt( gravitationalParameter / semiLatusRectum ) * sineOfTrueAnomaly;
const Real yVelocityPerifocal
= std::sqrt( gravitationalParameter / semiLatusRectum )
* ( eccentricity + cosineOfTrueAnomaly );
// Compute scalar components of rotation matrix to rotate from periforcal to Earth-Centered
// Inertial (ECI) frame.
const Real rotationMatrixComponent11
= ( cosineOfLongitudeOfAscendingNode * cosineOfArgumentOfPeriapsis
- sineOfLongitudeOfAscendingNode * sineOfArgumentOfPeriapsis * cosineOfInclination );
const Real rotationMatrixComponent12
= ( -cosineOfLongitudeOfAscendingNode * sineOfArgumentOfPeriapsis
-sineOfLongitudeOfAscendingNode * cosineOfArgumentOfPeriapsis * cosineOfInclination );
const Real rotationMatrixComponent21
= ( sineOfLongitudeOfAscendingNode * cosineOfArgumentOfPeriapsis
+ cosineOfLongitudeOfAscendingNode * sineOfArgumentOfPeriapsis * cosineOfInclination );
const Real rotationMatrixComponent22
= ( -sineOfLongitudeOfAscendingNode * sineOfArgumentOfPeriapsis
+ cosineOfLongitudeOfAscendingNode * cosineOfArgumentOfPeriapsis * cosineOfInclination );
const Real rotationMatrixComponent31 = ( sineOfArgumentOfPeriapsis * sineOfInclination );
const Real rotationMatrixComponent32 = ( cosineOfArgumentOfPeriapsis * sineOfInclination );
// Compute Cartesian position and velocities.
cartesianElements[ xPositionIndex ] = rotationMatrixComponent11 * xPositionPerifocal
+ rotationMatrixComponent12 * yPositionPerifocal;
cartesianElements[ yPositionIndex ] = rotationMatrixComponent21 * xPositionPerifocal
+ rotationMatrixComponent22 * yPositionPerifocal;
cartesianElements[ zPositionIndex ] = rotationMatrixComponent31 * xPositionPerifocal
+ rotationMatrixComponent32 * yPositionPerifocal;
cartesianElements[ xVelocityIndex ] = rotationMatrixComponent11 * xVelocityPerifocal
+ rotationMatrixComponent12 * yVelocityPerifocal;
cartesianElements[ yVelocityIndex ] = rotationMatrixComponent21 * xVelocityPerifocal
+ rotationMatrixComponent22 * yVelocityPerifocal;
cartesianElements[ zVelocityIndex ] = rotationMatrixComponent31 * xVelocityPerifocal
+ rotationMatrixComponent32 * yVelocityPerifocal;
return cartesianElements;
}
//! Convert true anomaly to elliptical eccentric anomaly.
/*!
* Converts true anomaly to eccentric anomaly for elliptical orbits (0 <= eccentricity < 1.0).
*
* This implementation performs a check on the eccentricity and throws an error if it is
* non-elliptical, i.e., eccentricity < 0.0 and eccentricity >= 1.0.
*
* The equations used can be found in (Chobotov, 2002).
*
* @tparam Real Real type
* @param trueAnomaly True anomaly [rad]
* @param eccentricity Eccentricity [-]
* @return Elliptical eccentric anomaly [rad]
*/
template< typename Real >
Real convertTrueAnomalyToEllipticalEccentricAnomaly( const Real trueAnomaly,
const Real eccentricity )
{
if ( eccentricity >= 1.0 || eccentricity < 0.0 )
{
throw std::runtime_error( "ERROR: Eccentricity is non-elliptical!" );
}
// Compute sine and cosine of eccentric anomaly.
const Real sineOfEccentricAnomaly
= std::sqrt( 1.0 - std::pow( eccentricity, 2.0 ) )
* std::sin( trueAnomaly ) / ( 1.0 + eccentricity * std::cos( trueAnomaly ) );
const Real cosineOfEccentricAnomaly
= ( eccentricity + std::cos( trueAnomaly ) )
/ ( 1.0 + eccentricity * std::cos( trueAnomaly ) );
// Return elliptical eccentric anomaly.
return std::atan2( sineOfEccentricAnomaly, cosineOfEccentricAnomaly );
}
//! Convert true anomaly to hyperbolic eccentric anomaly.
/*!
* Converts true anomaly to hyperbolic eccentric anomaly for hyperbolic orbits
* (eccentricity > 1.0).
*
* This implementation performs a check on the eccentricity and throws an error if it is
* non-hyperbolic, i.e., eccentricity >= 1.0.
*
* The equations used can be found in (Chobotov, 2002).
*
* @tparam Real Real type
* @param trueAnomaly True anomaly [rad]
* @param eccentricity Eccentricity [-]
* @return Hyperbolic eccentric anomaly [rad]
*/
template< typename Real >
Real convertTrueAnomalyToHyperbolicEccentricAnomaly( const Real trueAnomaly,
const Real eccentricity )
{
if ( eccentricity <= 1.0 )
{
throw std::runtime_error( "ERROR: Eccentricity is non-hyperbolic!" );
}
// Compute hyperbolic sine and hyperbolic cosine of hyperbolic eccentric anomaly.
const Real hyperbolicSineOfHyperbolicEccentricAnomaly
= std::sqrt( std::pow( eccentricity, 2.0 ) - 1.0 )
* std::sin( trueAnomaly ) / ( 1.0 + std::cos( trueAnomaly ) );
const Real hyperbolicCosineOfHyperbolicEccentricAnomaly
= ( std::cos( trueAnomaly ) + eccentricity ) / ( 1.0 + std::cos( trueAnomaly ) );
// Return hyperbolic eccentric anomaly.
// The inverse hyperbolic tangent is computed here manually, since the atanh() function is not
// available in older C++ compilers.
const Real angle
= hyperbolicSineOfHyperbolicEccentricAnomaly
/ hyperbolicCosineOfHyperbolicEccentricAnomaly;
return 0.5 * ( std::log( 1.0 + angle ) - std::log( 1.0 - angle ) );
}
//! Convert true anomaly to eccentric anomaly.
/*!
* Converts true anomaly to eccentric anomaly for elliptical and hyperbolic orbits
* (eccentricity < 1.0 && eccentricity > 1.0). This function is essentially a wrapper for
* functions that treat each case. It should be used in cases where the eccentricity of the orbit
* is not known a priori.
*
* This implementation performs a check on the eccentricity and throws an error for
* eccentricity < 0.0 and parabolic orbits, which have not been implemented.
*
* The equations used can be found in (Chobotov, 2002).
*
* @sa convertTrueAnomalyToEllipticalEccentricAnomaly,
* convertTrueAnomalyToHyperbolicEccentricAnomaly
* @tparam Real Real type
* @param trueAnomaly True anomaly [rad]
* @param eccentricity Eccentricity [-]
* @return Eccentric anomaly [rad]
*/
template< typename Real >
Real convertTrueAnomalyToEccentricAnomaly( const Real trueAnomaly, const Real eccentricity )
{
Real eccentricAnomaly = 0.0;
// Check if eccentricity is invalid and throw an error if true.
if ( eccentricity < 0.0 )
{
throw std::runtime_error( "ERROR: Eccentricity is negative!" );
}
// Check if orbit is parabolic and throw an error if true.
else if ( std::fabs( eccentricity - 1.0 ) < std::numeric_limits< Real >::epsilon( ) )
{
throw std::runtime_error( "ERROR: Parabolic orbits have not been implemented!" );
}
// Check if orbit is elliptical and compute eccentric anomaly.
else if ( eccentricity >= 0.0 && eccentricity < 1.0 )
{
eccentricAnomaly
= convertTrueAnomalyToEllipticalEccentricAnomaly( trueAnomaly, eccentricity );
}
// Check if orbit is hyperbolic and compute eccentric anomaly.
else if ( eccentricity > 1.0 )
{
eccentricAnomaly
= convertTrueAnomalyToHyperbolicEccentricAnomaly( trueAnomaly, eccentricity );
}
return eccentricAnomaly;
}
//! Convert elliptical eccentric anomaly to mean anomaly.
/*!
* Converts eccentric anomaly to mean anomaly for elliptical orbits (0 <= eccentricity < 1.0).
*
* This implementation performs a check on the eccentricity and throws an error if it is
* non-elliptical, i.e., eccentricity < 0.0 and eccentricity >= 1.0.
*
* The equations used can be found in (Chobotov, 2002).
*
* @tparam Real Real type
* @param ellipticalEccentricAnomaly Elliptical eccentric anomaly [rad]
* @param eccentricity Eccentricity [-]
* @return Mean anomaly [rad]
*/
template< typename Real >
Real convertEllipticalEccentricAnomalyToMeanAnomaly( const Real ellipticalEccentricAnomaly,
const Real eccentricity )
{
if ( eccentricity >= 1.0 || eccentricity < 0.0 )
{
throw std::runtime_error( "ERROR: Eccentricity is non-elliptical!" );
}
return ellipticalEccentricAnomaly - eccentricity * std::sin( ellipticalEccentricAnomaly );
}
//! Convert hyperbolic eccentric anomaly to mean anomaly.
/*!
* Converts hyperbolic eccentric anomaly to mean anomaly for hyperbolic orbits
* (eccentricity > 1.0).
*
* This implementation performs a check on the eccentricity and throws an error if it is
* non-hyperbolic, i.e., eccentricity >= 1.0.
*
* The equations used can be found in (Chobotov, 2002).
*
* @tparam Real Real type
* @param hyperbolicEccentricAnomaly Hyperbolic eccentric anomaly [rad]
* @param eccentricity Eccentricity [-]
* @return Mean anomaly [rad]
*/
template< typename Real >
Real convertHyperbolicEccentricAnomalyToMeanAnomaly(
const Real hyperbolicEccentricAnomaly, const Real eccentricity )
{
if ( eccentricity <= 1.0 )
{
throw std::runtime_error( "ERROR: Eccentricity is non-hyperbolic!" );
}
return eccentricity * std::sinh( hyperbolicEccentricAnomaly ) - hyperbolicEccentricAnomaly;
}
//! Convert eccentric anomaly to mean anomaly.
/*!
* Converts eccentric anomaly to mean anomaly for elliptical and hyperbolic orbits
* (eccentricity < 1.0 && eccentricity > 1.0). This function is essentially a wrapper for
* functions that treat each case. It should be used in cases where the eccentricity of the orbit
* is not known a priori.
*
* Currently, this implementation performs a check on the eccentricity and throws an error for
* eccentricity < 0.0 and parabolic orbits, which have not been implemented.
*
* The equations used can be found in (Chobotov, 2002).
*
* @sa convertEllipticalEccentricAnomalyToMeanAnomaly,
* convertHyperbolicEccentricAnomalyToMeanAnomaly
* @tparam Real Real type
* @param eccentricity Eccentricity [-]
* @param eccentricAnomaly Eccentric anomaly [rad]
* @return Mean anomaly [rad]
*/
template< typename Real >
Real convertEccentricAnomalyToMeanAnomaly( const Real eccentricAnomaly, const Real eccentricity )
{
Real meanAnomaly = 0.0;
// Check if eccentricity is invalid and throw an error if true.
if ( eccentricity < 0.0 )
{
throw std::runtime_error( "ERROR: Eccentricity is negative!" );
}
// Check if orbit is parabolic and throw an error if true.
else if ( std::fabs( eccentricity - 1.0 ) < std::numeric_limits< Real >::epsilon( ) )
{
throw std::runtime_error( "ERROR: Parabolic orbits have not been implemented!" );
}
// Check if orbit is elliptical and compute mean anomaly.
else if ( eccentricity >= 0.0 && eccentricity < 1.0 )
{
meanAnomaly
= convertEllipticalEccentricAnomalyToMeanAnomaly( eccentricAnomaly, eccentricity );
}
// Check if orbit is hyperbolic and compute mean anomaly.
else if ( eccentricity > 1.0 )
{
meanAnomaly
= convertHyperbolicEccentricAnomalyToMeanAnomaly( eccentricAnomaly, eccentricity );
}
return meanAnomaly;
}
//! Convert elliptical eccentric anomaly to true anomaly.
/*!
* Converts eccentric anomaly to true anomaly for elliptical orbits (0 <= eccentricity < 1.0).
* The equations used can be found in (Chobotov, 2002).
*
* @tparam Real Real type
* @param ellipticEccentricAnomaly Elliptical eccentric anomaly [rad]
* @param eccentricity Eccentricity [-]
* @return True anomaly [rad]
*/
template< typename Real >
Real convertEllipticalEccentricAnomalyToTrueAnomaly( const Real ellipticEccentricAnomaly,
const Real eccentricity )
{
const Real sineOfTrueAnomaly = std::sqrt( 1.0 - eccentricity * eccentricity )
* std::sin( ellipticEccentricAnomaly )
/ ( 1.0 - eccentricity * std::cos( ellipticEccentricAnomaly ) );
const Real cosineOfTrueAnomaly
= ( std::cos( ellipticEccentricAnomaly ) - eccentricity )
/ ( 1.0 - eccentricity * std::cos( ellipticEccentricAnomaly ) );
return std::atan2( sineOfTrueAnomaly, cosineOfTrueAnomaly );
}
//! Convert hyperbolic eccentric anomaly to true anomaly.
/*!
* Converts hyperbolic eccentric anomaly to true anomaly for hyperbolic orbits
* (eccentricity > 1.0). The equations used can be found in (Chobotov, 2002).
*
* @tparam Real Real type
* @param hyperbolicEccentricAnomaly Hyperbolic eccentric anomaly [rad]
* @param eccentricity Eccentricity [-]
* @return True anomaly [rad]
*/
template< typename Real >
Real convertHyperbolicEccentricAnomalyToTrueAnomaly( const Real hyperbolicEccentricAnomaly,
const Real eccentricity )
{
const Real sineOfTrueAnomaly
= std::sqrt( eccentricity * eccentricity - 1.0 )
* std::sinh( hyperbolicEccentricAnomaly )
/ ( eccentricity * std::cosh( hyperbolicEccentricAnomaly ) - 1.0 );
const Real cosineOfTrueAnomaly
= ( eccentricity - std::cosh( hyperbolicEccentricAnomaly ) )
/ ( eccentricity * std::cosh( hyperbolicEccentricAnomaly ) - 1.0 );
return std::atan2( sineOfTrueAnomaly, cosineOfTrueAnomaly );
}
//! Convert eccentric anomaly to true anomaly.
/*!
* Converts eccentric anomaly to true anomaly for elliptical and hyperbolic orbits
* (eccentricity < 1.0 && eccentricity > 1.0). This function is essentially a wrapper for
* functions that treat each case. It should be used in cases where the eccentricity of the orbit
* is not known a priori.
*
* Currently, this implementation performs a check on the eccentricity and throws an error for
* eccentricity < 0.0 and parabolic orbits, which have not been implemented.
*
* The equations used can be found in (Chobotov, 2002).
*
* @sa convertEllipticalEccentricAnomalyToTrueAnomaly,
* convertHyperbolicEccentricAnomalyToTrueAnomaly
* @tparam Real Real type
* @param eccentricAnomaly Eccentric anomaly [rad]
* @param eccentricity Eccentricity [-]
* @return True anomaly [rad]
*/
template< typename Real >
Real convertEccentricAnomalyToTrueAnomaly( const Real eccentricAnomaly, const Real eccentricity )
{
Real trueAnomaly = 0.0;
// Check if eccentricity is invalid and throw an error if true.
if ( eccentricity < 0.0 )
{
throw std::runtime_error( "ERROR: Eccentricity is negative!" );
}
// Check if orbit is parabolic and throw an error if true.
else if ( std::fabs( eccentricity - 1.0 ) < std::numeric_limits< Real >::epsilon( ) )
{
throw std::runtime_error( "ERROR: Parabolic orbits have not been implemented!" );
}
// Check if orbit is elliptical and compute true anomaly.
else if ( eccentricity < 1.0 )
{
trueAnomaly = convertEllipticalEccentricAnomalyToTrueAnomaly( eccentricAnomaly,
eccentricity );
}
else if ( eccentricity > 1.0 )
{
trueAnomaly = convertHyperbolicEccentricAnomalyToTrueAnomaly( eccentricAnomaly,
eccentricity );
}
return trueAnomaly;
}
} // namespace astro
#endif // ASTRO_ORBITAL_ELEMENT_CONVERSIONS_HPP
/*!
* References
* Chobotov, V.A. Orbital Mechanics, Third Edition, AIAA Education Series, VA, 2002.
*/
| 45.572843 | 103 | 0.643079 | [
"vector"
] |
5172a29aeb67710a0d12074ed8430a08197784ee | 1,336 | cc | C++ | bounce/socket.cc | zhangyu0310/bounce | ca6b2d693ffda1a28a1d7b1564468f02d53f2afa | [
"MIT"
] | 17 | 2018-12-09T15:39:45.000Z | 2022-03-15T03:27:28.000Z | bounce/socket.cc | shanliner/bounce | 7876df0ff92a621629fecd455957bb8a040af29c | [
"MIT"
] | 8 | 2019-01-08T09:50:57.000Z | 2019-05-07T14:49:39.000Z | bounce/socket.cc | shanliner/bounce | 7876df0ff92a621629fecd455957bb8a040af29c | [
"MIT"
] | 7 | 2018-12-26T14:33:27.000Z | 2020-06-27T06:58:41.000Z | /*
* Copyright (C) 2018 poppinzhang.
*
* Written by poppinzhang with C++11 <poppinzhang@tencent.com>
*
* This file is some function implementation of Socket.
* A socket object is a encapsulation of file descriptor.
*
* Distributed under the MIT License (http://opensource.org/licenses/MIT)
*/
#include <bounce/socket.h>
#include <bounce/logger.h>
#include <bounce/sockaddr.h>
// The size 5 is a recommended value.
static const int LISTEN_SIZE = 5;
void bounce::Socket::bind(const SockAddress& addr) {
if (::bind(fd_, addr.constInetAddr(), addr.size()) != 0) {
Logger::get("bounce_file_log")->critical(
"file:{}, line:{}, function:{} bind failed. errno is {}",
FILENAME(__FILE__), __LINE__, __FUNCTION__, errno);
exit(1);
}
}
void bounce::Socket::listen() {
if (::listen(fd_, LISTEN_SIZE) != 0) {
Logger::get("bounce_file_log")->critical(
"file:{}, line:{}, function:{} listen failed. errno is {}",
FILENAME(__FILE__), __LINE__, __FUNCTION__, errno);
exit(1);
}
}
int bounce::Socket::accept(SockAddress* addr) {
socklen_t len = addr->size();
int fd = ::accept4(fd_, addr->inetAddr(), &len, SOCK_NONBLOCK);
if (fd < 0) {
Logger::get("bounce_file_log")->error(
"file:{}, line:{}, function:{} accept fd < 0. errno is {}",
FILENAME(__FILE__), __LINE__, __FUNCTION__, errno);
}
return fd;
} | 28.425532 | 72 | 0.667665 | [
"object"
] |
5179ad96b3cc55c98d513884b889f3045489cf5a | 30,048 | cpp | C++ | framework/demuxer/play_list/SegmentTracker.cpp | aliyun/CicadaPlayer | 9d2b515a52403034a6e764e30fd0c9508edec889 | [
"MIT"
] | 38 | 2019-12-16T14:31:00.000Z | 2020-01-11T03:01:26.000Z | framework/demuxer/play_list/SegmentTracker.cpp | aliyun/CicadaPlayer | 9d2b515a52403034a6e764e30fd0c9508edec889 | [
"MIT"
] | 11 | 2020-01-07T06:32:11.000Z | 2020-01-13T03:52:37.000Z | framework/demuxer/play_list/SegmentTracker.cpp | aliyun/CicadaPlayer | 9d2b515a52403034a6e764e30fd0c9508edec889 | [
"MIT"
] | 14 | 2019-12-30T01:19:04.000Z | 2020-01-11T02:12:35.000Z | //
// Created by moqi on 2018/4/28.
//
#define LOG_TAG "SegmentTracker"
#include "SegmentTracker.h"
#include "AdaptationSet.h"
#include "Helper.h"
#include "HlsParser.h"
#include "Period.h"
#include "Representation.h"
#include "SegmentList.h"
#include "data_source/dataSourcePrototype.h"
#include "playList_demuxer.h"
#include "utils/errors/framework_error.h"
#include "utils/frame_work_log.h"
#include "utils/timer.h"
#include <algorithm>
#include <cassert>
#include <utility>
#define IS_LIVE (mRep && mRep->b_live)
namespace Cicada {
SegmentTracker::SegmentTracker(Representation *rep, const IDataSource::SourceConfig &sourceConfig)
: mRep(rep), mSourceConfig(sourceConfig)
{
mCanBlockReload = mRep->mCanBlockReload;
if (mCanBlockReload && mTargetDuration > 0) {
mSourceConfig.connect_time_out_ms = 3 * mTargetDuration;
}
mCanSkipUntil = mRep->mCanSkipUntil;
mThread = NEW_AF_THREAD(threadFunction);
}
SegmentTracker::~SegmentTracker()
{
{
std::unique_lock<std::mutex> locker(mSegMutex);
mStopLoading = true;
mNeedUpdate = true;
}
mSegCondition.notify_all();
delete mThread;
std::unique_lock<std::recursive_mutex> locker(mMutex);
if (playListOwnedByMe) {
delete mPPlayList;
}
if (mPDataSource) {
mPDataSource->Interrupt(true);
mPDataSource->Close();
delete mPDataSource;
}
}
std::shared_ptr<segment> SegmentTracker::getCurSegment(bool force)
{
std::unique_lock<std::recursive_mutex> locker(mMutex);
if (mPreloadSegment) {
return mPreloadSegment;
}
shared_ptr<segment> seg = nullptr;
if (mRep->GetSegmentList()) {
seg = mRep->GetSegmentList()->getSegmentByNumber(mCurSegNum, force);
}
if (seg) {
mCurSegNum = seg->getSequenceNumber();
}
return seg;
}
std::shared_ptr<segment> SegmentTracker::getNextSegment()
{
std::unique_lock<std::recursive_mutex> locker(mMutex);
shared_ptr<segment> seg = nullptr;
mCurSegNum++;
if (mRep->GetSegmentList()) {
seg = mRep->GetSegmentList()->getSegmentByNumber(mCurSegNum, true);
}
if (seg) {
mCurSegNum = seg->getSequenceNumber();
mPreloadSegment = nullptr;
} else {
mCurSegNum--;
}
return seg;
}
int SegmentTracker::GetRemainSegmentCount()
{
std::unique_lock<std::recursive_mutex> locker(mMutex);
int count = -1;
if (mRep->GetSegmentList()) {
count = mRep->GetSegmentList()->getRemainSegmentAfterNumber(mCurSegNum);
}
return count;
}
void SegmentTracker::MoveToLiveStartSegment(const int64_t liveStartIndex)
{
SegmentList *segList = mRep->GetSegmentList();
if (segList == nullptr) {
AF_LOGW("SegmentTracker::MoveToLiveStartSegment, segmentList is empty");
return;
}
auto segments = segList->getSegments();
if (segList->hasLHLSSegments()) {
if (mRep->mPartHoldBack > 0.0) {
double duration = 0.0;
bool isFindPart = false;
for (auto iter = segments.rbegin(); iter != segments.rend(); iter++) {
const vector<SegmentPart> &segmentParts = (*iter)->getSegmentParts();
if (segmentParts.size() > 0) {
for (int i = segmentParts.size() - 1; i >= 0; i--) {
duration += segmentParts[i].duration / 1000000.0f;
if (duration >= mRep->mPartHoldBack) {
(*iter)->moveToNearestIndependentPart(i);
isFindPart = true;
setCurSegNum((*iter)->getSequenceNumber());
std::string segUrl = (*iter)->getDownloadUrl();
AF_LOGI("SegmentTracker::MoveToLiveStartSegment, segUrl=%s", segUrl.c_str());
break;
}
}
if (isFindPart) {
break;
}
} else {
duration += (*iter)->duration / 1000000.0f;
if (duration >= mRep->mPartHoldBack) {
isFindPart = true;
setCurSegNum((*iter)->getSequenceNumber());
std::string segUrl = (*iter)->getDownloadUrl();
AF_LOGI("SegmentTracker::MoveToLiveStartSegment, segUrl=%s", segUrl.c_str());
break;
}
}
}
if (!isFindPart) {
// use first independent part
auto iter = segments.front();
iter->moveToNearestIndependentPart(0);
setCurSegNum(iter->getSequenceNumber());
std::string segUrl = iter->getDownloadUrl();
AF_LOGI("SegmentTracker::MoveToLiveStartSegment, segUrl=%s", segUrl.c_str());
}
} else {
// playlist has no PART-HOLD-BACK, use liveStartIndex , liveStartIndex is partial segment index
if (liveStartIndex >= 0) {
int offset = liveStartIndex;
bool isFindPart = false;
for (auto iter = segments.begin(); iter != segments.end(); iter++) {
const vector<SegmentPart> &segmentParts = (*iter)->getSegmentParts();
if (offset >= segmentParts.size()) {
offset -= segmentParts.size();
} else {
(*iter)->moveToNearestIndependentPart(offset);
isFindPart = true;
setCurSegNum((*iter)->getSequenceNumber());
std::string segUrl = (*iter)->getDownloadUrl();
AF_LOGI("SegmentTracker::MoveToLiveStartSegment, segUrl=%s", segUrl.c_str());
break;
}
}
if (!isFindPart) {
// use last independent part
auto iter = segments.back();
iter->moveToNearestIndependentPart(iter->getSegmentParts().size() - 1);
setCurSegNum(iter->getSequenceNumber());
std::string segUrl = iter->getDownloadUrl();
AF_LOGI("SegmentTracker::MoveToLiveStartSegment, segUrl=%s", segUrl.c_str());
}
} else {
int offset = -liveStartIndex - 1;
bool isFindPart = false;
for (auto iter = segments.rbegin(); iter != segments.rend(); iter++) {
const vector<SegmentPart> &segmentParts = (*iter)->getSegmentParts();
if (offset >= segmentParts.size()) {
offset -= segmentParts.size();
} else {
(*iter)->moveToNearestIndependentPart(segmentParts.size() - 1 - offset);
isFindPart = true;
setCurSegNum((*iter)->getSequenceNumber());
std::string segUrl = (*iter)->getDownloadUrl();
AF_LOGI("SegmentTracker::MoveToLiveStartSegment, segUrl=%s", segUrl.c_str());
break;
}
}
if (!isFindPart) {
// use first independent part
auto iter = segments.front();
iter->moveToNearestIndependentPart(0);
setCurSegNum(iter->getSequenceNumber());
std::string segUrl = iter->getDownloadUrl();
AF_LOGI("SegmentTracker::MoveToLiveStartSegment, segUrl=%s", segUrl.c_str());
}
}
}
} else {
uint64_t curNum = 0;
if (mRep->mHoldBack > 0.0) {
double duration = 0.0;
bool isFind = false;
for (auto iter = segments.rbegin(); iter != segments.rend(); iter++) {
duration += (*iter)->duration / 1000000.0f;
if (duration >= mRep->mHoldBack) {
isFind = true;
curNum = (*iter)->getSequenceNumber();
setCurSegNum(curNum);
AF_LOGI("SegmentTracker::MoveToLiveStartSegment, seg num=%llu", curNum);
break;
}
}
if (!isFind) {
// use first segment
auto iter = segments.front();
curNum = iter->getSequenceNumber();
setCurSegNum(curNum);
AF_LOGI("SegmentTracker::MoveToLiveStartSegment, seg num=%llu", curNum);
}
} else {
// playlist has no HOLD-BACK, use liveStartIndex , liveStartIndex is segment index
if (liveStartIndex >= 0) {
curNum = std::min(getFirstSegNum() + liveStartIndex, getLastSegNum());
} else {
int64_t targetSegNum = ((int64_t) getLastSegNum()) + liveStartIndex + 1;
if (targetSegNum < 0) {
targetSegNum = 0;
}
curNum = std::max((uint64_t) targetSegNum, getFirstSegNum());
}
setCurSegNum(curNum);
AF_LOGI("SegmentTracker::MoveToLiveStartSegment, seg num=%llu", curNum);
}
}
}
int SegmentTracker::loadPlayList(bool noSkip)
{
int ret;
string uri;
bool useSkip = false;
if (!mRep) {
return -EINVAL;
}
{
std::unique_lock<std::recursive_mutex> locker(mMutex);
if (mLocation.empty()) {
uri = Helper::combinePaths(mRep->getPlaylist()->getPlaylistUrl(), mRep->getPlaylistUrl());
} else {
uri = mLocation;
}
if (mCanBlockReload && mCurrentMsn >= 0) {
if (uri.find('?') == std::string::npos) {
uri += "?";
} else {
uri += "&";
}
uri += "_HLS_msn=";
uri += std::to_string(mCurrentMsn);
uri += "&_HLS_part=";
uri += std::to_string(mCurrentPart);
} else if (!mCurrentRenditions.empty()) {
std::string playListUrl = mRep->getPlaylistUrl();
for (auto &it : mCurrentRenditions) {
if (it.uri == playListUrl && mCurSegNum >= it.lastMsn && mCurSegNum < it.lastMsn + 3) {
if (uri.find('?') == std::string::npos) {
uri += "?";
} else {
uri += "&";
}
uri += "_HLS_msn=";
uri += std::to_string(mCurSegNum);
AF_LOGD("[llhls] use rendition report to load playlist");
break;
}
}
mCurrentRenditions.clear();
}
if (!noSkip && mCanSkipUntil > 0.0 && af_getsteady_ms() - mLastPlaylistUpdateTime < mCanSkipUntil * 0.5 * 1000) {
if (uri.find('?') == std::string::npos) {
uri += "?";
} else {
uri += "&";
}
uri += "_HLS_skip=YES";
useSkip = true;
}
}
AF_LOGD("loadPlayList uri is [%s]\n", uri.c_str());
if (mRep->mPlayListType == playList_demuxer::playList_type_hls) {
mLoadingPlaylist = true;
if (mExtDataSource) {
ret = mExtDataSource->Open(uri);
} else {
if (mPDataSource == nullptr) {
{
std::unique_lock<std::recursive_mutex> locker(mMutex);
mPDataSource = dataSourcePrototype::create(uri, mOpts);
mPDataSource->Set_config(mSourceConfig);
mPDataSource->Interrupt(mInterrupted);
}
ret = mPDataSource->Open(0);
} else {
ret = mPDataSource->Open(uri);
}
}
mLoadingPlaylist = false;
AF_LOGD("loadPlayList ret is %d\n", ret);
if (ret < 0) {
AF_LOGE("open url error %s\n", framework_err2_string(ret));
if (ret == gen_framework_http_errno(404)) {
if (mReloadErrorStartTime == INT64_MIN) {
mReloadErrorStartTime = af_getsteady_ms();
} else {
if (af_getsteady_ms() - mReloadErrorStartTime > mSourceConfig.low_speed_time_ms) {
return -EIO;
}
}
}
return ret;
} else {
mReloadErrorStartTime = INT64_MIN;
}
if (mLocation.empty()) {
std::string location("location");
if (mExtDataSource) {
mLocation = mExtDataSource->GetOption(location);
} else {
assert(mPDataSource);
mLocation = mPDataSource->GetOption(location);
}
}
auto *parser = new HlsParser(uri.c_str());
if (mExtDataSource) {
parser->setDataSourceIO(new dataSourceIO(mExtDataSource));
} else {
parser->setDataSourceIO(new dataSourceIO(mPDataSource));
}
playList *pPlayList = parser->parse(uri);
// mPPlayList->dump();
// mediaPlayList only have one Representation
if (pPlayList != nullptr) {
std::unique_lock<std::recursive_mutex> locker(mMutex);
Representation *rep = (*(*(*pPlayList->GetPeriods().begin())->GetAdaptSets().begin())->getRepresentations().begin());
SegmentList *sList = rep->GetSegmentList();
SegmentList *pList = mRep->GetSegmentList();
mTargetDuration = rep->targetDuration;
mPartTargetDuration = rep->partTargetDuration;
// sList->print();
//live stream should always keeps the new lists.
if (pList) {
if (useSkip) {
uint64_t oldLastSegNum = pList->getLastSeqNum();
uint64_t newFirstSegNum = sList->getFirstSeqNum();
if (newFirstSegNum > oldLastSegNum + 1) {
mNeedReloadWithoutSkip = true;
delete pPlayList;
delete parser;
return 0;
}
}
pList->merge(sList);
} else {
mRep->SetSegmentList(sList);
}
mRep->mCanBlockReload = rep->mCanBlockReload;
mCanBlockReload = rep->mCanBlockReload;
SegmentList *currentSegList = mRep->GetSegmentList();
if (mCanBlockReload) {
auto lastSeg = currentSegList->getSegmentByNumber(currentSegList->getLastSeqNum(), false);
bool bHasUnusedParts;
mCurrentMsn = lastSeg->getSequenceNumber();
if (lastSeg->isDownloadComplete(bHasUnusedParts)) {
mCurrentMsn++;
mCurrentPart = 0;
} else {
mCurrentPart = lastSeg->getSegmentParts().size();
}
}
if (mRep->mPreloadHint.used) {
if (mPreloadSegment && currentSegList->getLastSeqNum() >= mPreloadSegment->getSequenceNumber()) {
mPreloadSegment = nullptr;
}
if (rep->mPreloadHint.uri != mRep->mPreloadHint.uri && !currentSegList->containPartialSegment(mRep->mPreloadHint.uri)) {
// TODO: cancel preload
}
uint64_t preloadSegNum;
if (currentSegList->findPartialSegment(mRep->mPreloadHint.uri, preloadSegNum)) {
if (mCurSegNum < preloadSegNum) {
mCurSegNum = preloadSegNum;
AF_LOGD("[lhls] move to preload segment, segNum=%llu, uri=%s", mCurSegNum, mRep->mPreloadHint.uri.c_str());
}
mRep->mPreloadHint.used = false;
}
auto curSeg = getCurSegment(false);
if (curSeg) {
curSeg->moveToPreloadSegment(mRep->mPreloadHint.uri);
}
}
if (!mRep->mPreloadHint.used && mRep->mPreloadHint.uri != rep->mPreloadHint.uri) {
mRep->mPreloadHint = rep->mPreloadHint;
}
rep->SetSegmentList(nullptr);
mRep->mRenditionReport = rep->mRenditionReport;
mRep->mCanSkipUntil = rep->mCanSkipUntil;
mCanSkipUntil = rep->mCanSkipUntil;
// update is live
mRep->b_live = rep->b_live;
if (pPlayList->getDuration() > 0 && mPDataSource) {
mPDataSource->Close();
delete mPDataSource;
mPDataSource = nullptr;
}
if (mPPlayList == nullptr) { //save the first playList
mPPlayList = pPlayList;
playListOwnedByMe = true;
} else {
delete pPlayList;
}
mLastPlaylistUpdateTime = af_getsteady_ms();
} else {
delete parser;
return -EAGAIN;
}
// mRep->mStreamType = rep->mStreamType;
// TODO save parser
delete parser;
return 0;
}
return 0;
}
int SegmentTracker::init()
{
int ret = 0;
if (!mInited) {
SegmentList *list = nullptr;
{
std::unique_lock<std::recursive_mutex> locker(mMutex);
list = mRep->GetSegmentList();
}
if (list == nullptr) { //masterPlayList
ret = loadPlayList();
mLastLoadTime = af_gettime_relative();
mCanBlockReload = mRep->mCanBlockReload;
if (mCanBlockReload && mTargetDuration > 0) {
mSourceConfig.connect_time_out_ms = 3 * mTargetDuration;
}
mCanSkipUntil = mRep->mCanSkipUntil;
if (ret < 0) {
AF_LOGE("loadPlayList error %d\n", ret);
return ret;
}
} else {
std::unique_lock<std::recursive_mutex> locker(mMutex);
mPPlayList = mRep->getPlaylist();
playListOwnedByMe = false;
}
if (mRep != nullptr && mRep->GetSegmentList() != nullptr) {
mRealtime = mRep->GetSegmentList()->hasLHLSSegments();
}
if (IS_LIVE) {
mThread->start();
}
mInited = true;
} else if (isLive()) {
ret = loadPlayList();
if (ret < 0) {
AF_LOGE("loadPlayList error %d\n", ret);
return ret;
}
mCanBlockReload = mRep->mCanBlockReload;
if (mCanBlockReload && mTargetDuration > 0) {
mSourceConfig.connect_time_out_ms = 3 * mTargetDuration;
}
mCanSkipUntil = mRep->mCanSkipUntil;
}
// start from a num
if (mCurSegNum == 0) {
std::unique_lock<std::recursive_mutex> locker(mMutex);
mCurSegNum = mRep->GetSegmentList()->getFirstSeqNum();
}
if (mCurSegPos > 0) {
AF_LOGD("%d mCurSegNum = %llu , mCurSegPos = %llu \n", __LINE__, mCurSegNum,
mCurSegPos);
mCurSegNum = mRep->GetSegmentList()->getFirstSeqNum() + mCurSegPos;
AF_LOGD("%d mCurSegNum = %llu\n", __LINE__, mCurSegNum);
mCurSegPos = 0;
}
return ret;
}
int SegmentTracker::getStreamType() const
{
return mRep->mStreamType;
}
const string SegmentTracker::getBaseUri()
{
std::unique_lock<std::recursive_mutex> locker(mMutex);
return Helper::combinePaths(mRep->getPlaylist()->getPlaylistUrl(),
mRep->getBaseUrl());
}
void SegmentTracker::print()
{
AF_LOGD("playList url is %s\n", mRep->getPlaylistUrl().c_str());
AF_LOGD("BaseUrl url is %s\n", mRep->getBaseUrl().c_str());
AF_LOGD("getPlaylist()->getPlaylistUrl url is %s\n",
mRep->getPlaylist()->getPlaylistUrl().c_str());
mRep->GetSegmentList()->print();
}
int SegmentTracker::getStreamInfo(int *width, int *height, uint64_t *bandwidth,
std::string &language)
{
return mRep->getStreamInfo(width, height, bandwidth, language);
}
string SegmentTracker::getDescriptionInfo()
{
return mRep->getAdaptationSet()->getDescription();
}
bool SegmentTracker::getSegmentNumberByTime(uint64_t &time, uint64_t &num)
{
std::unique_lock<std::recursive_mutex> locker(mMutex);
if (mRep->GetSegmentList()) {
return mRep->GetSegmentList()->getSegmentNumberByTime(time, num);
}
return false;
}
int64_t SegmentTracker::getDuration()
{
std::unique_lock<std::recursive_mutex> locker(mMutex);
if (mPPlayList) {
return mPPlayList->getDuration();
}
return INT64_MIN;
}
int SegmentTracker::reLoadPlayList()
{
// AF_TRACE;
if (IS_LIVE) {
if (mCanBlockReload) {
std::unique_lock<std::mutex> locker(mSegMutex);
if (!mLoadingPlaylist) {
mNeedUpdate = true;
mSegCondition.notify_all();
}
} else {
int64_t time = af_gettime_relative();
// AF_LOGD("mTargetDuration is %lld", (int64_t)mTargetDuration);
int64_t reloadInterval = 0;
if (mPartTargetDuration > 0) {
// lhls reload interval is 2 times part target duration
reloadInterval = mPartTargetDuration * 2;
} else {
// hls reload interval is half target dutaion
reloadInterval = mTargetDuration / 2;
}
if (time - mLastLoadTime > reloadInterval) {
std::unique_lock<std::mutex> locker(mSegMutex);
mNeedUpdate = true;
mSegCondition.notify_all();
mLastLoadTime = time;
}
}
return mPlayListStatus;
}
return 0;
}
uint64_t SegmentTracker::getSegSize()
{
std::unique_lock<std::recursive_mutex> locker(mMutex);
return mRep->GetSegmentList()->getSegments().size();
}
int SegmentTracker::threadFunction()
{
// TODO: stop when eos
while (!mStopLoading) {
{
std::unique_lock<std::mutex> locker(mSegMutex);
mSegCondition.wait(locker, [this]() {
return mNeedUpdate.load();
});
}
if (!mStopLoading) {
mPlayListStatus = loadPlayList();
if (mNeedReloadWithoutSkip) {
mPlayListStatus = loadPlayList(true);
mNeedReloadWithoutSkip = false;
}
if (!mRealtime && mRep != nullptr && mRep->GetSegmentList() != nullptr)
{
mRealtime = mRep->GetSegmentList()->hasLHLSSegments();
}
mNeedUpdate = false;
}
}
return 0;
}
void SegmentTracker::interrupt(int inter)
{
std::unique_lock<std::recursive_mutex> locker(mMutex);
mInterrupted = inter;
if (mExtDataSource) {
mExtDataSource->Interrupt(inter);
}
if (mPDataSource) {
mPDataSource->Interrupt(inter);
}
mCurrentMsn = -1;
mCurrentPart = -1;
mCanBlockReload = false;
mCanSkipUntil = false;
}
bool SegmentTracker::isInited()
{
return mInited;
}
bool SegmentTracker::isLive()
{
return IS_LIVE;
}
string SegmentTracker::getPlayListUri()
{
std::unique_lock<std::recursive_mutex> locker(mMutex);
return Helper::combinePaths(mRep->getPlaylist()->getPlaylistUrl(),
mRep->getPlaylistUrl());
}
uint64_t SegmentTracker::getCurSegPosition()
{
if (isInited()) {
uint64_t firstSegNum = getFirstSegNum();
uint64_t curSegNum = getCurSegNum();
uint64_t position = curSegNum - firstSegNum - 1;
AF_LOGD("1206, getCurSegPosition <--- targetSegNum %llu , firstSegNum = %llu ,curSegNum = %llu \n", position, firstSegNum, curSegNum);
return position;
} else {
AF_LOGD("1206, getCurSegPosition %llu\n", mCurSegPos);
return mCurSegPos;
}
};
void SegmentTracker::setCurSegPosition(uint64_t position)
{
mCurSegPos = 0;
if (isInited()) {
uint64_t targetSegNum = getFirstSegNum() + position;
AF_LOGD("1206, setCurSegPosition --> targetSegNum %llu\n", targetSegNum);
setCurSegNum(targetSegNum);
} else {
mCurSegPos = position;
AF_LOGD("1206, setCurSegPosition %llu\n", mCurSegPos);
}
mSeeked = true;
}
uint64_t SegmentTracker::getFirstSegNum()
{
return mRep->GetSegmentList()->getFirstSeqNum();
}
uint64_t SegmentTracker::getLastSegNum()
{
return mRep->GetSegmentList()->getLastSeqNum();
}
int64_t SegmentTracker::getTargetDuration()
{
if (mRep->GetSegmentList() != nullptr) {
return mRep->GetSegmentList()->getTargetDuration();
} else {
return mRep->targetDuration;
}
}
vector<mediaSegmentListEntry> SegmentTracker::getSegmentList()
{
vector<mediaSegmentListEntry> ret;
std::unique_lock<std::recursive_mutex> locker(mMutex);
if (mRep->GetSegmentList()) {
auto segments = mRep->GetSegmentList()->getSegments();
for (auto it = segments.begin(); it != segments.end(); it++) {
std::string uri = Helper::combinePaths(getBaseUri(), (*it)->getDownloadUrl());
ret.push_back(mediaSegmentListEntry(uri, (*it)->duration));
}
}
return ret;
}
bool SegmentTracker::hasPreloadSegment()
{
std::unique_lock<std::recursive_mutex> locker(mMutex);
if (mRep && mRep->mPreloadHint.isPartialSegment && !mRep->mPreloadHint.uri.empty() && !mRep->mPreloadHint.used) {
return true;
}
return false;
}
void SegmentTracker::usePreloadSegment(std::string &uri, int64_t &rangeStart, int64_t &rangeEnd)
{
assert(mRep);
std::unique_lock<std::recursive_mutex> locker(mMutex);
mRep->mPreloadHint.used = true;
uri = mRep->mPreloadHint.uri;
rangeStart = mRep->mPreloadHint.rangeStart;
rangeEnd = mRep->mPreloadHint.rangeEnd;
}
std::shared_ptr<segment> SegmentTracker::usePreloadSegment()
{
assert(mRep);
std::unique_lock<std::recursive_mutex> locker(mMutex);
mRep->mPreloadHint.used = true;
mPreloadSegment = std::make_shared<segment>(0);
mPreloadSegment->sequence = mCurSegNum + 1;
mPreloadSegment->setSourceUrl("");
auto lastSeg = mRep->GetSegmentList()->getSegments().back();
if (lastSeg->startTime != UINT64_MAX) {
mPreloadSegment->startTime = lastSeg->startTime + lastSeg->duration;
}
if (lastSeg->utcTime >= 0) {
mPreloadSegment->utcTime = lastSeg->utcTime + lastSeg->duration;
}
SegmentPart part;
part.uri = mRep->mPreloadHint.uri;
mPreloadSegment->updateParts({part});
return mPreloadSegment;
}
void SegmentTracker::setExtDataSource(IDataSource *source)
{
std::unique_lock<std::recursive_mutex> locker(mMutex);
mExtDataSource = source;
}
void SegmentTracker::setRenditionInfo(const std::vector<RenditionReport> &renditions)
{
mCurrentRenditions = renditions;
}
std::vector<RenditionReport> SegmentTracker::getRenditionInfo()
{
return mRep->mRenditionReport;
}
}
| 36.95941 | 146 | 0.496739 | [
"vector"
] |
517a86dd2ed3e54f6cbc53527ce6ffd44a3e8458 | 8,263 | hpp | C++ | framework/include/minko/render/Pass.hpp | undeadinu/minko | 9171805751fb3a50c6fcab0b78892cdd4253ee11 | [
"BSD-3-Clause"
] | 478 | 2015-01-04T16:59:53.000Z | 2022-03-07T20:28:07.000Z | framework/include/minko/render/Pass.hpp | undeadinu/minko | 9171805751fb3a50c6fcab0b78892cdd4253ee11 | [
"BSD-3-Clause"
] | 83 | 2015-01-15T21:45:06.000Z | 2021-11-08T11:01:48.000Z | framework/include/minko/render/Pass.hpp | undeadinu/minko | 9171805751fb3a50c6fcab0b78892cdd4253ee11 | [
"BSD-3-Clause"
] | 175 | 2015-01-04T03:30:39.000Z | 2020-01-27T17:08:14.000Z | /*
Copyright (c) 2014 Aerys
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#pragma once
#include "minko/Common.hpp"
#include "minko/render/Blending.hpp"
#include "minko/render/CompareMode.hpp"
#include "minko/render/TriangleCulling.hpp"
#include "minko/render/ProgramSignature.hpp"
#include "minko/render/Program.hpp"
#include "minko/render/States.hpp"
#include "minko/render/VertexAttribute.hpp"
#include "minko/Flyweight.hpp"
namespace minko
{
namespace render
{
class Pass :
public std::enable_shared_from_this<Pass>
{
public:
typedef std::shared_ptr<Pass> Ptr;
private:
typedef std::shared_ptr<Program> ProgramPtr;
typedef std::shared_ptr<VertexBuffer> VertexBufferPtr;
typedef std::unordered_map<std::string, SamplerState> SamplerStatesMap;
typedef std::unordered_map<ProgramSignature*, ProgramPtr> SignatureToProgramMap;
typedef std::function<void(ProgramPtr)> ProgramFunc;
typedef std::unordered_map<std::string, ProgramFunc> ProgramFuncMap;
typedef std::unordered_map<std::string, data::MacroBinding> MacroBindingsMap;
private:
const std::string _name;
bool _isForward;
ProgramPtr _programTemplate;
data::BindingMap _attributeBindings;
data::BindingMap _uniformBindings;
data::BindingMap _stateBindings;
data::MacroBindingMap _macroBindings;
States _states;
SignatureToProgramMap _signatureToProgram;
ProgramFuncMap _uniformFunctions;
ProgramFuncMap _attributeFunctions;
ProgramFuncMap _macroFunctions;
public:
~Pass()
{
for (auto& signatureAndProgram : _signatureToProgram)
delete signatureAndProgram.first;
}
inline static
Ptr
create(const std::string& name,
bool isForward,
std::shared_ptr<render::Program> program,
const data::BindingMap& attributeBindings,
const data::BindingMap& uniformBindings,
const data::BindingMap& stateBindings,
const data::MacroBindingMap& macroBindings)
{
return std::shared_ptr<Pass>(new Pass(
name,
isForward,
program,
attributeBindings,
uniformBindings,
stateBindings,
macroBindings
));
}
inline static
Ptr
create(Ptr pass, bool deepCopy = false)
{
auto p = create(
pass->_name,
pass->_isForward,
deepCopy ? Program::create(pass->_programTemplate, deepCopy) : pass->_programTemplate,
pass->_attributeBindings,
pass->_uniformBindings,
pass->_stateBindings,
pass->_macroBindings
);
for (auto& signatureProgram : pass->_signatureToProgram)
p->_signatureToProgram[new ProgramSignature(*signatureProgram.first)] = signatureProgram.second;
p->_uniformFunctions = pass->_uniformFunctions;
p->_attributeFunctions = pass->_attributeFunctions;
p->_macroFunctions = pass->_macroFunctions;
if (pass->_programTemplate->isReady())
{
for (auto& nameAndFunc : p->_uniformFunctions)
nameAndFunc.second(pass->_programTemplate);
for (auto& nameAndFunc : p->_attributeFunctions)
nameAndFunc.second(pass->_programTemplate);
for (auto& nameAndFunc : p->_macroFunctions)
nameAndFunc.second(pass->_programTemplate);
}
return p;
}
inline
const std::string&
name()
{
return _name;
}
inline
bool
isForward() const
{
return _isForward;
}
inline
std::shared_ptr<Program>
program()
{
return _programTemplate;
}
inline
data::BindingMap&
attributeBindings()
{
return _attributeBindings;
}
inline
data::BindingMap&
uniformBindings()
{
return _uniformBindings;
}
inline
data::BindingMap&
stateBindings()
{
return _stateBindings;
}
inline
data::MacroBindingMap&
macroBindings()
{
return _macroBindings;
}
inline
States&
states()
{
return _states;
}
std::pair<std::shared_ptr<Program>, const ProgramSignature*>
selectProgram(const EffectVariables& translatedPropertyNames,
const data::Store& targetData,
const data::Store& rendererData,
const data::Store& rootData);
template <typename... T>
void
setUniform(const std::string& name, const T&... values)
{
_uniformFunctions[name] = [=](std::shared_ptr<Program> program)
{
setUniformOnProgram<T...>(program, name, values...);
};
if (_programTemplate->isReady())
_programTemplate->setUniform(name, values...);
for (auto signatureAndProgram : _signatureToProgram)
signatureAndProgram.second->setUniform(name, values...);
}
inline
void
setAttribute(const std::string& name, const VertexAttribute& attribute)
{
_attributeFunctions[name] = [=](std::shared_ptr<Program> program)
{
setVertexAttributeOnProgram(program, name, attribute);
};
if (_programTemplate->isReady())
_programTemplate->setAttribute(name, attribute);
for (auto signatureAndProgram : _signatureToProgram)
signatureAndProgram.second->setAttribute(name, attribute);
}
inline
void
define(const std::string& macroName)
{
_macroFunctions[macroName] = [=](std::shared_ptr<Program> program)
{
defineOnProgram(program, macroName);
};
_programTemplate->define(macroName);
}
template <typename T>
inline
void
define(const std::string& macroName, T macroValue)
{
_macroFunctions[macroName] = [=](std::shared_ptr<Program> program)
{
defineOnProgramWithValue(program, macroName, macroValue);
};
_programTemplate->define(macroName, macroValue);
}
private:
Pass(const std::string& name,
bool isForward,
std::shared_ptr<render::Program> program,
const data::BindingMap& attributeBindings,
const data::BindingMap& uniformBindings,
const data::BindingMap& stateBindings,
const data::MacroBindingMap& macroBindings);
template <typename... T>
static
void
setUniformOnProgram(std::shared_ptr<Program> program, const std::string& name, const T&... values)
{
program->setUniform(name, values...);
}
static
void
setVertexAttributeOnProgram(std::shared_ptr<Program> program, const std::string& name, const VertexAttribute& attribute)
{
program->setAttribute(name, attribute);
}
static
void
defineOnProgram(std::shared_ptr<Program> program, const std::string& macroName)
{
program->define(macroName);
}
template <typename T>
static
void
defineOnProgramWithValue(std::shared_ptr<Program> program, const std::string& macroName, T value)
{
program->define(macroName, value);
}
ProgramPtr
finalizeProgram(ProgramPtr program);
};
}
}
| 28.591696 | 132 | 0.654242 | [
"render"
] |
517e0374f67cc2bf471b6428e9a750a9060b172a | 1,479 | hh | C++ | src/captain/CaptPMTBuilder.hh | andrewmogan/edep-sim | 4e9923ccba8b2f65f47b72cbb41ed683f19f1123 | [
"MIT"
] | 15 | 2017-04-25T14:20:22.000Z | 2022-03-15T19:39:43.000Z | src/captain/CaptPMTBuilder.hh | andrewmogan/edep-sim | 4e9923ccba8b2f65f47b72cbb41ed683f19f1123 | [
"MIT"
] | 24 | 2017-11-08T21:16:48.000Z | 2022-03-04T13:33:18.000Z | src/captain/CaptPMTBuilder.hh | andrewmogan/edep-sim | 4e9923ccba8b2f65f47b72cbb41ed683f19f1123 | [
"MIT"
] | 20 | 2017-11-09T15:41:46.000Z | 2022-01-25T20:52:32.000Z | #ifndef CaptPMTBuilder_hh_Seen
#define CaptPMTBuilder_hh_Seen
#include "EDepSimBuilder.hh"
class G4LogicalVolume;
/// Construct an unrotated PMT. In the local coordinate system, the
/// PMT points along the positive Z direction.
class CaptPMTBuilder : public EDepSim::Builder {
public:
CaptPMTBuilder(G4String name, EDepSim::Builder* parent)
: EDepSim::Builder(name,parent) {Init();};
virtual ~CaptPMTBuilder();
/// Construct and return a G4 volume for the object. This is a pure
/// virtual function, which means it must be implemented by the inheriting
/// classes. This returns an unplaced logical volume which faces along
/// the Z axis.
virtual G4LogicalVolume *GetPiece(void);
/// Get or set the length of the base. The base length measures from the
/// face of the photocathode to the back of the PMT.
/// @{
void SetBaseLength(double v) {fBaseLength = v;}
double GetBaseLength() const {return fBaseLength;}
/// @}
/// Set the size of the PMT.
/// @{
void SetSize(double v) {fSize = v;}
double GetSize() const {return fSize;}
/// @}
/// Set that the PMT is round
void SetRound(bool v) {fRoundPMT = v;}
bool IsRound() const {return fRoundPMT;}
private:
void Init(void);
/// The size of the PMT.
double fSize;
/// The length of the PMT base.
double fBaseLength;
/// Flag that the PMT is round (not square).
bool fRoundPMT;
};
#endif
| 27.90566 | 78 | 0.663962 | [
"object"
] |
517f761b61268d2c664f74bdb338ffb79f8841f8 | 8,488 | cc | C++ | lite/kernels/cuda/transpose_compute_test.cc | hcj5206/Paddle-Lite | eed7a506cef5d2ba6a076a34e4f51d3b5f60cddd | [
"Apache-2.0"
] | null | null | null | lite/kernels/cuda/transpose_compute_test.cc | hcj5206/Paddle-Lite | eed7a506cef5d2ba6a076a34e4f51d3b5f60cddd | [
"Apache-2.0"
] | null | null | null | lite/kernels/cuda/transpose_compute_test.cc | hcj5206/Paddle-Lite | eed7a506cef5d2ba6a076a34e4f51d3b5f60cddd | [
"Apache-2.0"
] | 1 | 2020-02-13T10:45:37.000Z | 2020-02-13T10:45:37.000Z | // Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "lite/kernels/cuda/transpose_compute.h"
#include <gtest/gtest.h>
#include <memory>
#include <utility>
#include <vector>
namespace paddle {
namespace lite {
namespace kernels {
namespace cuda {
namespace {
#define IN(n, c, h, w) \
input_data[w + h * input_w + c * input_h * input_w + \
n * input_c * input_h * input_w]
#define OUT(n, c, h, w) \
output_data[w + h * output_w + c * output_h * output_w + \
n * output_c * output_h * output_w]
void nchw2nhwc_ref(lite::Tensor* input,
lite::Tensor* output,
const std::vector<int> axies) {
auto* input_data = input->data<float>();
auto* output_data = output->mutable_data<float>();
int input_n = input->dims()[0];
int input_c = input->dims()[1];
int input_h = input->dims()[2];
int input_w = input->dims()[3];
int output_c = output->dims()[1];
int output_h = output->dims()[2];
int output_w = output->dims()[3];
for (int n = 0; n < input_n; ++n) {
for (int c = 0; c < input_c; ++c) {
for (int h = 0; h < input_h; ++h) {
for (int w = 0; w < input_w; ++w) {
OUT(n, h, w, c) = IN(n, c, h, w);
}
}
}
}
}
#undef IN
#undef OUT
#define IN(n, h, w, c) \
input_data[c + w * input_c + h * input_w * input_c + \
n * input_h * input_w * input_c]
#define OUT(n, h, w, c) \
output_data[c + w * output_c + h * output_w * output_c + \
n * output_h * output_w * output_c]
void nhwc2nchw_ref(lite::Tensor* input,
lite::Tensor* output,
const std::vector<int> axies) {
auto* input_data = input->data<float>();
auto* output_data = output->mutable_data<float>();
int input_n = input->dims()[0];
int input_h = input->dims()[1];
int input_w = input->dims()[2];
int input_c = input->dims()[3];
int output_h = output->dims()[1];
int output_w = output->dims()[2];
int output_c = output->dims()[3];
for (int n = 0; n < input_n; ++n) {
for (int c = 0; c < input_c; ++c) {
for (int h = 0; h < input_h; ++h) {
for (int w = 0; w < input_w; ++w) {
OUT(n, c, h, w) = IN(n, h, w, c);
}
}
}
}
}
void transpose_ref(lite::Tensor* input,
lite::Tensor* output,
const std::vector<int> axes) {
auto* input_data = input->data<float>();
auto* output_data = output->mutable_data<float>();
int ndim = input->dims().size();
auto dims = input->dims();
std::vector<int> strides(ndim, 0);
std::vector<int> buf(ndim, 0);
int cur_stride = 1;
for (int i = ndim - 1; i >= 0; --i) {
buf[i] = cur_stride;
cur_stride *= dims[i];
}
for (int i = 0; i < ndim; ++i) {
strides[i] = buf[axes[i]];
}
auto y_dims = output->dims();
int size = input->dims().production();
for (int i = 0; i < size; ++i) {
int idx = 0;
int v = i;
for (int j = ndim - 1; j >= 0; --j) {
idx += v % y_dims[j] * strides[j];
v /= y_dims[j];
}
output_data[i] = input_data[idx];
}
}
} // namespace
TEST(transpose_nchw, normal) {
TransposeCompute transpose_kernel;
std::unique_ptr<KernelContext> ctx(new KernelContext);
auto& context = ctx->As<CUDAContext>();
operators::TransposeParam param;
lite::Tensor x, x_cpu, x_ref;
lite::Tensor out, out_cpu, out_ref;
int N = 5, C = 6, H = 7, W = 8;
std::vector<int> axes({0, 2, 3, 1});
x.Resize({N, C, H, W});
out.Resize({N, H, W, C});
x_cpu.Resize({N, C, H, W});
out_cpu.Resize({N, H, W, C});
x_ref.Resize({N, C, H, W});
out_ref.Resize({N, H, W, C});
auto* x_cpu_data = x_cpu.mutable_data<float>();
auto* out_cpu_data = out_cpu.mutable_data<float>();
auto* x_ref_data = x_ref.mutable_data<float>();
for (int i = 0; i < x_cpu.numel(); ++i) {
x_cpu_data[i] = i + 1;
x_ref_data[i] = i + 1;
}
x.Assign<float, lite::DDim, TARGET(kCUDA)>(x_cpu_data, x_cpu.dims());
param.x = &x;
param.output = &out;
param.axis = axes;
transpose_kernel.SetParam(param);
cudaStream_t stream;
cudaStreamCreate(&stream);
context.SetExecStream(stream);
transpose_kernel.SetContext(std::move(ctx));
transpose_kernel.Launch();
cudaDeviceSynchronize();
auto* out_data = out.mutable_data<float>(TARGET(kCUDA));
CopySync<TARGET(kCUDA)>(
out_cpu_data, out_data, sizeof(float) * out.numel(), IoDirection::DtoH);
nchw2nhwc_ref(&x_ref, &out_ref, axes);
auto* out_ref_data = out_ref.mutable_data<float>();
// transpose_ref(&x_ref, &out_ref, axes);
for (int i = 0; i < out.numel(); i++) {
EXPECT_NEAR(out_cpu_data[i], out_ref_data[i], 1e-5);
}
}
TEST(transpose_nhwc, normal) {
TransposeCompute transpose_kernel;
std::unique_ptr<KernelContext> ctx(new KernelContext);
auto& context = ctx->As<CUDAContext>();
operators::TransposeParam param;
lite::Tensor x, x_cpu, x_ref;
lite::Tensor out, out_cpu, out_ref;
int N = 5, C = 6, H = 7, W = 8;
std::vector<int> axes({0, 3, 1, 2});
x.Resize({N, H, W, C});
out.Resize({N, C, H, W});
x_cpu.Resize({N, H, W, C});
out_cpu.Resize({N, C, H, W});
x_ref.Resize({N, H, W, C});
out_ref.Resize({N, C, H, W});
auto* x_cpu_data = x_cpu.mutable_data<float>();
auto* out_cpu_data = out_cpu.mutable_data<float>();
auto* x_ref_data = x_ref.mutable_data<float>();
for (int i = 0; i < x_cpu.numel(); ++i) {
x_cpu_data[i] = i + 1;
x_ref_data[i] = i + 1;
}
x.Assign<float, lite::DDim, TARGET(kCUDA)>(x_cpu_data, x_cpu.dims());
param.x = &x;
param.output = &out;
param.axis = axes;
transpose_kernel.SetParam(param);
cudaStream_t stream;
cudaStreamCreate(&stream);
context.SetExecStream(stream);
transpose_kernel.SetContext(std::move(ctx));
transpose_kernel.Launch();
cudaDeviceSynchronize();
auto* out_data = out.mutable_data<float>(TARGET(kCUDA));
CopySync<TARGET(kCUDA)>(
out_cpu_data, out_data, sizeof(float) * out.numel(), IoDirection::DtoH);
nhwc2nchw_ref(&x_ref, &out_ref, axes);
// transpose_ref(&x_ref, &out_ref, axes);
auto* out_ref_data = out_ref.mutable_data<float>();
for (int i = 0; i < out.numel(); i++) {
EXPECT_NEAR(out_cpu_data[i], out_ref_data[i], 1e-5);
}
}
TEST(transpose, normal) {
TransposeCompute transpose_kernel;
std::unique_ptr<KernelContext> ctx(new KernelContext);
auto& context = ctx->As<CUDAContext>();
operators::TransposeParam param;
lite::Tensor x, x_cpu, x_ref;
lite::Tensor out, out_cpu, out_ref;
int C = 6, H = 7, W = 8;
std::vector<int> axes({2, 0, 1});
x.Resize({C, H, W});
out.Resize({W, C, H});
x_cpu.Resize({C, H, W});
out_cpu.Resize({W, C, H});
x_ref.Resize({C, H, W});
out_ref.Resize({W, C, H});
auto* x_cpu_data = x_cpu.mutable_data<float>();
auto* out_cpu_data = out_cpu.mutable_data<float>();
auto* x_ref_data = x_ref.mutable_data<float>();
for (int i = 0; i < x_cpu.numel(); ++i) {
x_cpu_data[i] = i + 1;
x_ref_data[i] = i + 1;
}
x.Assign<float, lite::DDim, TARGET(kCUDA)>(x_cpu_data, x_cpu.dims());
param.x = &x;
param.output = &out;
param.axis = axes;
transpose_kernel.SetParam(param);
cudaStream_t stream;
cudaStreamCreate(&stream);
context.SetExecStream(stream);
transpose_kernel.SetContext(std::move(ctx));
transpose_kernel.Launch();
cudaDeviceSynchronize();
auto* out_data = out.mutable_data<float>(TARGET(kCUDA));
CopySync<TARGET(kCUDA)>(
out_cpu_data, out_data, sizeof(float) * out.numel(), IoDirection::DtoH);
transpose_ref(&x_ref, &out_ref, axes);
auto* out_ref_data = out_ref.mutable_data<float>();
for (int i = 0; i < out.numel(); i++) {
EXPECT_NEAR(out_cpu_data[i], out_ref_data[i], 1e-5);
}
}
} // namespace cuda
} // namespace kernels
} // namespace lite
} // namespace paddle
| 29.678322 | 78 | 0.607681 | [
"vector"
] |
5182355171f292b9df20852ebaf1d2727258470d | 335 | hpp | C++ | utf8_unicode.hpp | schiffma/distlib | 5688cffc1284bff8894ba29d5270afb5116b7869 | [
"MIT"
] | 11 | 2021-07-08T14:18:02.000Z | 2022-02-24T12:29:06.000Z | utf8_unicode.hpp | schiffma/distlib | 5688cffc1284bff8894ba29d5270afb5116b7869 | [
"MIT"
] | null | null | null | utf8_unicode.hpp | schiffma/distlib | 5688cffc1284bff8894ba29d5270afb5116b7869 | [
"MIT"
] | null | null | null | #ifndef UTF8_UNICODE_HPP
#define UTF8_UNICODE_HPP
#include <string>
#include <vector>
std::vector<std::string> utf8_split(const std::string &str);
int utf8_length(const std::string &str);
std::string vect2str(const std::vector<std::string> &v);
std::vector<std::string> slice(std::vector<std::string> const &v, int m, int n);
#endif | 27.916667 | 80 | 0.737313 | [
"vector"
] |
51826f26e32c37a9f4c953a7bb21704583ab46fb | 1,607 | cpp | C++ | csapex_vision/src/set_color.cpp | AdrianZw/csapex_core_plugins | 1b23c90af7e552c3fc37c7dda589d751d2aae97f | [
"BSD-3-Clause"
] | 2 | 2016-09-02T15:33:22.000Z | 2019-05-06T22:09:33.000Z | csapex_vision/src/set_color.cpp | AdrianZw/csapex_core_plugins | 1b23c90af7e552c3fc37c7dda589d751d2aae97f | [
"BSD-3-Clause"
] | 1 | 2021-02-14T19:53:30.000Z | 2021-02-14T19:53:30.000Z | csapex_vision/src/set_color.cpp | AdrianZw/csapex_core_plugins | 1b23c90af7e552c3fc37c7dda589d751d2aae97f | [
"BSD-3-Clause"
] | 6 | 2016-10-12T00:55:23.000Z | 2021-02-10T17:49:25.000Z | /// HEADER
#include "set_color.h"
/// PROJECT
#include <csapex/model/node_modifier.h>
#include <csapex/msg/io.h>
#include <csapex/param/parameter_factory.h>
#include <csapex/param/range_parameter.h>
#include <csapex/utility/register_apex_plugin.h>
#include <csapex_opencv/cv_mat_message.h>
CSAPEX_REGISTER_CLASS(csapex::SetColor, csapex::Node)
using namespace csapex;
using namespace csapex::connection_types;
SetColor::SetColor()
{
}
void SetColor::process()
{
CvMatMessage::ConstPtr in = msg::getMessage<CvMatMessage>(input_);
CvMatMessage::ConstPtr in_mask = msg::getMessage<CvMatMessage>(input_mask_);
CvMatMessage::Ptr out(new CvMatMessage(in->getEncoding(), in->frame_id, in->stamp_micro_seconds));
if (in->value.type() != CV_8UC3)
throw std::runtime_error("Need 3 channel color image!");
if (in_mask->value.type() != CV_8UC1)
throw std::runtime_error("Need 1 channel uchar mask!");
const std::vector<int>& c = readParameter<std::vector<int>>("color");
cv::Vec3b color(c[2], c[1], c[0]);
out->value = in->value.clone();
out->value.setTo(color, in_mask->value);
msg::publish(output_, out);
}
void SetColor::setup(NodeModifier& node_modifier)
{
input_ = node_modifier.addInput<CvMatMessage>("Image");
input_mask_ = node_modifier.addInput<CvMatMessage>("Mask");
output_ = node_modifier.addOutput<CvMatMessage>("Colored");
}
void SetColor::setupParameters(Parameterizable& parameters)
{
addParameter(csapex::param::factory::declareColorParameter("color", csapex::param::ParameterDescription("Color to set."), 0, 0, 0));
}
| 30.903846 | 136 | 0.719353 | [
"vector",
"model"
] |
3d633186865793f1d3fa00464ed4a70699a91f85 | 2,030 | cpp | C++ | King.cpp | Faz0lek/Chess | 9a840353dbccb3e539789e08fdbc73d74d753630 | [
"MIT"
] | null | null | null | King.cpp | Faz0lek/Chess | 9a840353dbccb3e539789e08fdbc73d74d753630 | [
"MIT"
] | null | null | null | King.cpp | Faz0lek/Chess | 9a840353dbccb3e539789e08fdbc73d74d753630 | [
"MIT"
] | null | null | null | #include "King.h"
King::King(std::string StartingTile, char team) : ChessPiece(StartingTile, team)
{
this->PieceTexture.loadFromFile(team == 'W' ? "Images/WhiteKing.png" : "Images/BlackKing.png");
this->PieceSprite.setTexture(this->PieceTexture);
}
bool King::IsLegalMove(const std::vector <std::vector <Tile>>& Tiles, const int x, const int y)
{
int thisx = (this->OccupantOf->TileRectangle.left - 45) / 70;
int thisy = (this->OccupantOf->TileRectangle.top - 45) / 70;
bool IsAttacking = false;
if (thisy == y) // CASTLING
{
if (thisx == x - 2 && Tiles[x + 1][y].Occupant != nullptr) // CASTLING DOPRAVA
{
if (!this->HasMoved && !Tiles[x + 1][y].Occupant->HasMoved)
{
this->IsCastling = 1;
for (int i = 0; i < 2; i++)
{
if (Tiles[x - i][y].Occupant != nullptr)
{
this->IsCastling = 0;
}
}
}
}
else if (thisx == x + 2 && Tiles[x - 2][y].Occupant != nullptr) // CASTLING DOLEVA
{
if (!this->HasMoved && !Tiles[x - 2][y].Occupant->HasMoved)
{
this->IsCastling = -2;
for (int i = 0; i < 2; i++)
{
if (Tiles[x + i][y].Occupant != nullptr)
{
this->IsCastling = 0;
}
}
if (Tiles[x - 1][y].Occupant != nullptr)
this->IsCastling = 0;
}
}
}
if (Tiles[x][y].Occupant != nullptr) // POHYB NA OBSAZENE POLE
{
if (this->team == Tiles[x][y].Occupant->team) // POKUS O POHYB NA POLE OBSAZENE FIGURKOU STEJNE BARVY
{
return false;
}
else // SEBRANI FIGURKY
{
IsAttacking = true;
}
}
if ((abs(this->PieceSprite.getPosition().x - Tiles[x][y].TileRectangle.left) == 70 || abs(this->PieceSprite.getPosition().x - Tiles[x][y].TileRectangle.left) == 0) && (abs(this->PieceSprite.getPosition().y - Tiles[x][y].TileRectangle.top) == 70 || abs(this->PieceSprite.getPosition().y - Tiles[x][y].TileRectangle.top) == 0))
{
if (IsAttacking)
Tiles[x][y].Occupant->PieceSprite.setPosition(-100, -100);
return true;
}
return false;
} | 29.42029 | 327 | 0.580788 | [
"vector"
] |
3d6c138f5e9cbcaa4357c276dd68afb4bea7e97c | 9,264 | cc | C++ | modules/localization/msf/local_tool/map_creation/lossless_map_to_lossy_map.cc | DavidSplit/apollo-3.0 | 9f82838e857e4c9146952946cbc34b9f35098deb | [
"Apache-2.0"
] | 6 | 2019-10-11T07:57:49.000Z | 2022-02-23T15:23:41.000Z | modules/localization/msf/local_tool/map_creation/lossless_map_to_lossy_map.cc | DavidSplit/apollo-3.0 | 9f82838e857e4c9146952946cbc34b9f35098deb | [
"Apache-2.0"
] | null | null | null | modules/localization/msf/local_tool/map_creation/lossless_map_to_lossy_map.cc | DavidSplit/apollo-3.0 | 9f82838e857e4c9146952946cbc34b9f35098deb | [
"Apache-2.0"
] | 12 | 2019-10-11T07:57:49.000Z | 2022-03-16T05:13:00.000Z | /******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
* Modifications Copyright (c) 2018 LG Electronics, Inc. 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 <boost/filesystem.hpp>
#include <boost/program_options.hpp>
#include "modules/localization/msf/local_map/lossless_map/lossless_map.h"
#include "modules/localization/msf/local_map/lossless_map/lossless_map_config.h"
#include "modules/localization/msf/local_map/lossless_map/lossless_map_matrix.h"
#include "modules/localization/msf/local_map/lossless_map/lossless_map_pool.h"
#include "modules/localization/msf/local_map/lossy_map/lossy_map_2d.h"
#include "modules/localization/msf/local_map/lossy_map/lossy_map_config_2d.h"
#include "modules/localization/msf/local_map/lossy_map/lossy_map_matrix_2d.h"
#include "modules/localization/msf/local_map/lossy_map/lossy_map_node_2d.h"
#include "modules/localization/msf/local_map/lossy_map/lossy_map_pool_2d.h"
namespace apollo {
namespace localization {
namespace msf {
typedef LossyMap2D LossyMap;
typedef LossyMapNode2D LossyMapNode;
typedef LossyMapNodePool2D LossyMapNodePool;
typedef LossyMapMatrix2D LossyMapMatrix;
typedef LossyMapConfig2D LossyMapConfig;
MapNodeIndex GetMapIndexFromMapFolder(const std::string& map_folder) {
MapNodeIndex index;
char buf[100];
sscanf(map_folder.c_str(), "/%03u/%05s/%02d/%08u/%08u", &index.resolution_id_,
buf, &index.zone_id_, &index.m_, &index.n_);
std::string zone = buf;
// std::cout << zone << std::endl;
if (zone == "south") {
index.zone_id_ = -index.zone_id_;
}
std::cout << index << std::endl;
return index;
}
bool GetAllMapIndex(const std::string& src_map_folder,
const std::string& dst_map_folder,
std::list<MapNodeIndex>* buf) {
std::string src_map_path = src_map_folder + "/map";
std::string dst_map_path = dst_map_folder + "/map";
boost::filesystem::path src_map_path_boost(src_map_path);
boost::filesystem::path dst_map_path_boost(dst_map_path);
if (!boost::filesystem::exists(dst_map_path)) {
boost::filesystem::create_directory(dst_map_path_boost);
}
// push path of map's index to list
buf->clear();
// std::deque<std::string> map_bin_path;
boost::filesystem::recursive_directory_iterator end_iter;
boost::filesystem::recursive_directory_iterator iter(src_map_path_boost);
for (; iter != end_iter; ++iter) {
if (!boost::filesystem::is_directory(*iter)) {
if (iter->path().extension() == "") {
// map_bin_path.push_back(iter->path().string());
std::string tmp = iter->path().string();
tmp = tmp.substr(src_map_path.length(), tmp.length());
buf->push_back(GetMapIndexFromMapFolder(tmp));
}
} else {
std::string tmp = iter->path().string();
tmp = tmp.substr(src_map_path.length(), tmp.length());
tmp = dst_map_path + tmp;
boost::filesystem::path p(tmp);
if (!boost::filesystem::exists(p)) {
boost::filesystem::create_directory(p);
}
}
}
return true;
}
} // namespace msf
} // namespace localization
} // namespace apollo
using apollo::localization::msf::LosslessMap;
using apollo::localization::msf::LosslessMapConfig;
using apollo::localization::msf::LosslessMapMatrix;
using apollo::localization::msf::LosslessMapNode;
using apollo::localization::msf::LosslessMapNodePool;
using apollo::localization::msf::LossyMap;
using apollo::localization::msf::LossyMapConfig;
using apollo::localization::msf::LossyMapMatrix;
using apollo::localization::msf::LossyMapNode;
using apollo::localization::msf::LossyMapNodePool;
using apollo::localization::msf::MapNodeIndex;
int main(int argc, char** argv) {
boost::program_options::options_description boost_desc("Allowed options");
boost_desc.add_options()("help", "produce help message")(
"srcdir", boost::program_options::value<std::string>(),
"provide the data base dir")("dstdir",
boost::program_options::value<std::string>(),
"provide the lossy map destination dir");
boost::program_options::variables_map boost_args;
boost::program_options::store(
boost::program_options::parse_command_line(argc, argv, boost_desc),
boost_args);
boost::program_options::notify(boost_args);
if (boost_args.count("help") || !boost_args.count("srcdir") ||
!boost_args.count("dstdir")) {
std::cout << boost_desc << std::endl;
return 0;
}
const std::string src_path = boost_args["srcdir"].as<std::string>();
const std::string dst_path = boost_args["dstdir"].as<std::string>();
std::string src_map_folder = src_path + "/";
LosslessMapConfig lossless_config("lossless_map");
LosslessMapNodePool lossless_map_node_pool(25, 8);
lossless_map_node_pool.Initial(&lossless_config);
LosslessMap lossless_map(&lossless_config);
lossless_map.InitThreadPool(1, 6);
lossless_map.InitMapNodeCaches(12, 24);
lossless_map.AttachMapNodePool(&lossless_map_node_pool);
if (!lossless_map.SetMapFolderPath(src_map_folder)) {
std::cerr << "Reflectance map folder is invalid!" << std::endl;
return -1;
}
// create lossy map
std::string dst_map_folder = dst_path + "/lossy_map/";
if (!boost::filesystem::exists(dst_map_folder)) {
boost::filesystem::create_directory(dst_map_folder);
}
std::list<MapNodeIndex> buf;
GetAllMapIndex(src_map_folder, dst_map_folder, &buf);
std::cout << "index size: " << buf.size() << std::endl;
LosslessMapConfig config_transform_lossy("lossless_map");
config_transform_lossy.Load(src_map_folder + "config.xml");
config_transform_lossy.map_version_ = "lossy_map";
config_transform_lossy.Save(dst_map_folder + "config.xml");
std::cout << "lossy map directory structure has built." << std::endl;
LossyMapConfig lossy_config("lossy_map");
LossyMapNodePool lossy_map_node_pool(25, 8);
lossy_map_node_pool.Initial(&lossy_config);
LossyMap lossy_map(&lossy_config);
lossy_map.InitThreadPool(1, 6);
lossy_map.InitMapNodeCaches(12, 24);
lossy_map.AttachMapNodePool(&lossy_map_node_pool);
if (!lossy_map.SetMapFolderPath(dst_map_folder)) {
std::cout << "lossy_map config xml not exist" << std::endl;
}
int index = 0;
auto itr = buf.begin();
for (; itr != buf.end(); ++itr, ++index) {
// int single_alt = 0;
// int double_alt = 0;
// float delta_alt_max = 0.0;
// float delta_alt_min = 100.0;
// int delta_alt_minus_num = 0;
// float alt_max = 0.0;
// float alt_min = 100.0;
LosslessMapNode* lossless_node =
static_cast<LosslessMapNode*>(lossless_map.GetMapNodeSafe(*itr));
if (lossless_node == NULL) {
std::cerr << "index: " << index << " is a NULL pointer!" << std::endl;
continue;
}
LosslessMapMatrix& lossless_matrix =
static_cast<LosslessMapMatrix&>(lossless_node->GetMapCellMatrix());
LossyMapNode* lossy_node =
static_cast<LossyMapNode*>(lossy_map.GetMapNodeSafe(*itr));
LossyMapMatrix& lossy_matrix =
static_cast<LossyMapMatrix&>(lossy_node->GetMapCellMatrix());
int rows = lossless_config.map_node_size_y_;
int cols = lossless_config.map_node_size_x_;
for (int row = 0; row < rows; ++row) {
for (int col = 0; col < cols; ++col) {
float intensity = lossless_node->GetValue(row, col);
float intensity_var = lossless_node->GetVar(row, col);
unsigned int count = lossless_node->GetCount(row, col);
// Read altitude
float altitude_ground = 0.0;
float altitude_avg = 0.0;
bool is_ground_useful = false;
std::vector<float> layer_alts;
std::vector<unsigned int> layer_counts;
lossless_matrix.GetMapCell(row, col).GetCount(&layer_counts);
lossless_matrix.GetMapCell(row, col).GetAlt(&layer_alts);
if (layer_counts.size() == 0 || layer_alts.size() == 0) {
altitude_avg = lossless_node->GetAlt(row, col);
is_ground_useful = false;
} else {
altitude_avg = lossless_node->GetAlt(row, col);
altitude_ground = layer_alts[0];
is_ground_useful = true;
}
lossy_matrix[row][col].intensity = intensity;
lossy_matrix[row][col].intensity_var = intensity_var;
lossy_matrix[row][col].count = count;
lossy_matrix[row][col].altitude = altitude_avg;
lossy_matrix[row][col].altitude_ground = altitude_ground;
lossy_matrix[row][col].is_ground_useful = is_ground_useful;
}
}
lossy_node->SetIsChanged(true);
}
return 0;
}
| 38.92437 | 80 | 0.688687 | [
"vector"
] |
3d6cd71aefa635a3874f23d4e7b0fdf047d10427 | 9,943 | cpp | C++ | test/test_decode.cpp | zhengfish/bencode.hpp | 064c1a1b7d4d149569d774e84a705b83db08db4e | [
"BSD-3-Clause"
] | 19 | 2016-09-18T01:58:41.000Z | 2021-12-16T02:10:12.000Z | test/test_decode.cpp | zhengfish/bencode.hpp | 064c1a1b7d4d149569d774e84a705b83db08db4e | [
"BSD-3-Clause"
] | 1 | 2018-04-11T13:42:24.000Z | 2018-06-03T02:53:03.000Z | test/test_decode.cpp | zhengfish/bencode.hpp | 064c1a1b7d4d149569d774e84a705b83db08db4e | [
"BSD-3-Clause"
] | 12 | 2016-07-02T00:18:00.000Z | 2022-03-29T13:05:50.000Z | #include <mettle.hpp>
using namespace mettle;
#include "bencode.hpp"
struct at_eof : matcher_tag {
bool operator ()(const std::string &) const {
return true;
}
template<typename Char, typename Traits>
bool operator ()(const std::basic_ios<Char, Traits> &ss) const {
return ss.eof();
}
std::string desc() const {
return "at eof";
}
};
suite<> test_decode("test decoder", [](auto &_) {
subsuite<
bencode::data, bencode::boost_data
>(_, "decoding", type_only, [](auto &_) {
using DataType = fixture_type_t<decltype(_)>;
using boost::get;
using std::get;
subsuite<
const char *, std::string, std::istringstream
>(_, "decoding from", type_only, [](auto &_) {
using Fixture = fixture_type_t<decltype(_)>;
_.test("integer", []() {
Fixture pos("i42e");
auto pos_value = bencode::basic_decode<DataType>(pos);
expect(pos, at_eof());
expect(get<typename DataType::integer>(pos_value), equal_to(42));
Fixture neg("i-42e");
auto neg_value = bencode::basic_decode<DataType>(neg);
expect(neg, at_eof());
expect(get<typename DataType::integer>(neg_value), equal_to(-42));
});
_.test("string", []() {
Fixture data("4:spam");
auto value = bencode::basic_decode<DataType>(data);
expect(data, at_eof());
expect(get<typename DataType::string>(value), equal_to("spam"));
});
_.test("list", []() {
Fixture data("li42ee");
auto value = bencode::basic_decode<DataType>(data);
auto list = get<typename DataType::list>(value);
expect(data, at_eof());
expect(get<typename DataType::integer>(list[0]), equal_to(42));
});
_.test("dict", []() {
Fixture data("d4:spami42ee");
auto value = bencode::basic_decode<DataType>(data);
auto dict = get<typename DataType::dict>(value);
expect(data, at_eof());
expect(get<typename DataType::integer>(dict["spam"]), equal_to(42));
});
_.test("nested", []() {
Fixture data("d"
"3:one" "i1e"
"5:three" "l" "d" "3:bar" "i0e" "3:foo" "i0e" "e" "e"
"3:two" "l" "i3e" "3:foo" "i4e" "e"
"e");
auto value = bencode::basic_decode<DataType>(data);
expect(data, at_eof());
auto dict = get<typename DataType::dict>(value);
expect(get<typename DataType::integer>(dict["one"]), equal_to(1));
expect(get<typename DataType::string>(
get<typename DataType::list>(dict["two"])[1]
), equal_to("foo"));
expect(get<typename DataType::integer>(
get<typename DataType::dict>(
get<typename DataType::list>(dict["three"])[0]
)["foo"]
), equal_to(0));
});
});
});
subsuite<>(_, "decode successive objects", [](auto &_) {
_.test("from string", []() {
std::string data("i42e4:goat");
auto begin = data.begin(), end = data.end();
auto first = bencode::decode(begin, end);
expect(std::get<bencode::integer>(first), equal_to(42));
auto second = bencode::decode(begin, end);
expect(std::get<bencode::string>(second), equal_to("goat"));
});
_.test("from stream", []() {
std::stringstream data("i42e4:goat");
auto first = bencode::decode(data);
expect(std::get<bencode::integer>(first), equal_to(42));
expect(data, is_not(at_eof()));
auto second = bencode::decode(data);
expect(std::get<bencode::string>(second), equal_to("goat"));
expect(data, at_eof());
});
});
subsuite<
bencode::data_view, bencode::boost_data_view
>(_, "decoding (view)", type_only, [](auto &_) {
using DataType = fixture_type_t<decltype(_)>;
using boost::get;
using std::get;
_.test("integer", []() {
std::string pos("i42e");
auto pos_value = bencode::basic_decode<DataType>(pos);
expect(get<typename DataType::integer>(pos_value), equal_to(42));
std::string neg("i-42e");
auto neg_value = bencode::basic_decode<DataType>(neg);
expect(get<typename DataType::integer>(neg_value), equal_to(-42));
});
_.test("string", []() {
std::string data("4:spam");
auto in_range = all(
greater_equal(data.data()),
less_equal(data.data() + data.size())
);
auto value = bencode::basic_decode<DataType>(data);
auto str = get<typename DataType::string>(value);
expect(&*str.begin(), in_range);
expect(&*str.end(), in_range);
expect(str, equal_to("spam"));
});
_.test("list", []() {
std::string data("li42ee");
auto value = bencode::basic_decode<DataType>(data);
auto list = get<typename DataType::list>(value);
expect(get<typename DataType::integer>(list[0]), equal_to(42));
});
_.test("dict", []() {
std::string data("d4:spami42ee");
auto in_range = all(
greater_equal(data.data()),
less_equal(data.data() + data.size())
);
auto value = bencode::basic_decode<DataType>(data);
auto dict = get<typename DataType::dict>(value);
auto str = dict.find("spam")->first;
expect(&*str.begin(), in_range);
expect(&*str.end(), in_range);
expect(str, equal_to("spam"));
expect(get<typename DataType::integer>(dict["spam"]), equal_to(42));
});
_.test("nested", []() {
std::string data("d"
"3:one" "i1e"
"5:three" "l" "d" "3:bar" "i0e" "3:foo" "i0e" "e" "e"
"3:two" "l" "i3e" "3:foo" "i4e" "e"
"e");
auto value = bencode::basic_decode<DataType>(data);
auto dict = get<typename DataType::dict>(value);
expect(get<typename DataType::integer>(dict["one"]), equal_to(1));
expect(get<typename DataType::string>(
get<typename DataType::list>(dict["two"])[1]
), equal_to("foo"));
expect(get<typename DataType::integer>(
get<typename DataType::dict>(
get<typename DataType::list>(dict["three"])[0]
)["foo"]
), equal_to(0));
});
});
subsuite<>(_, "decoding integers", [](auto &_) {
using udata = bencode::basic_data<
std::variant, unsigned long long, std::string, std::vector,
bencode::map_proxy
>;
_.test("max value", []() {
auto value = bencode::decode("i9223372036854775807e");
expect(std::get<bencode::integer>(value),
equal_to(9223372036854775807LL));
});
_.test("overflow", []() {
expect([]() { bencode::decode("i9223372036854775808e"); },
thrown<std::invalid_argument>("integer overflow"));
expect([]() { bencode::decode("i9323372036854775807e"); },
thrown<std::invalid_argument>("integer overflow"));
expect([]() { bencode::decode("i92233720368547758070e"); },
thrown<std::invalid_argument>("integer overflow"));
});
_.test("min value", []() {
auto value = bencode::decode("i-9223372036854775808e");
expect(std::get<bencode::integer>(value),
equal_to(-9223372036854775807LL - 1));
});
_.test("underflow", []() {
expect([]() { bencode::decode("i-9223372036854775809e"); },
thrown<std::invalid_argument>("integer underflow"));
expect([]() { bencode::decode("i-9323372036854775808e"); },
thrown<std::invalid_argument>("integer underflow"));
expect([]() { bencode::decode("i-92233720368547758080e"); },
thrown<std::invalid_argument>("integer underflow"));
});
_.test("max value (unsigned)", []() {
auto value = bencode::basic_decode<udata>("i18446744073709551615e");
expect(std::get<udata::integer>(value),
equal_to(18446744073709551615ULL));
});
_.test("overflow (unsigned)", []() {
expect([]() { bencode::basic_decode<udata>("i18446744073709551616e"); },
thrown<std::invalid_argument>("integer overflow"));
expect([]() { bencode::basic_decode<udata>("i19446744073709551615e"); },
thrown<std::invalid_argument>("integer overflow"));
expect([]() { bencode::basic_decode<udata>("i184467440737095516150e"); },
thrown<std::invalid_argument>("integer overflow"));
});
_.test("negative value (unsigned)", []() {
expect([]() { bencode::basic_decode<udata>("i-42e"); },
thrown<std::invalid_argument>("expected unsigned integer"));
});
});
subsuite<>(_, "error handling", [](auto &_) {
_.test("unexpected type", []() {
expect([]() { bencode::decode("x"); },
thrown<std::invalid_argument>("unexpected type"));
});
_.test("unexpected end of string", []() {
auto eos = thrown<std::invalid_argument>("unexpected end of string");
expect([]() { bencode::decode(""); }, eos);
expect([]() { bencode::decode("i123"); }, eos);
expect([]() { bencode::decode("3"); }, eos);
expect([]() { bencode::decode("3:as"); }, eos);
expect([]() { bencode::decode("l"); }, eos);
expect([]() { bencode::decode("li1e"); }, eos);
expect([]() { bencode::decode("d"); }, eos);
expect([]() { bencode::decode("d1:a"); }, eos);
expect([]() { bencode::decode("d1:ai1e"); }, eos);
});
_.test("expected 'e'", []() {
expect([]() { bencode::decode("i123i"); },
thrown<std::invalid_argument>("expected 'e'"));
});
_.test("expected ':'", []() {
expect([]() { bencode::decode("1abc"); },
thrown<std::invalid_argument>("expected ':'"));
});
_.test("expected string token", []() {
expect([]() { bencode::decode("di123ee"); },
thrown<std::invalid_argument>("expected string token"));
});
_.test("duplicated key", []() {
expect([]() { bencode::decode("d3:fooi1e3:fooi1ee"); },
thrown<std::invalid_argument>("duplicated key in dict: foo"));
});
});
});
| 33.478114 | 79 | 0.566932 | [
"vector"
] |
3d72a6ad6d61bda69a0fe20eab7e4fe8c3d4d981 | 6,353 | cpp | C++ | Main.cpp | pl2526/PSCAcoustic | eaf127f0bd6aa9bdf4a051b4390966e86fdf6751 | [
"MIT"
] | null | null | null | Main.cpp | pl2526/PSCAcoustic | eaf127f0bd6aa9bdf4a051b4390966e86fdf6751 | [
"MIT"
] | null | null | null | Main.cpp | pl2526/PSCAcoustic | eaf127f0bd6aa9bdf4a051b4390966e86fdf6751 | [
"MIT"
] | null | null | null | #ifndef MAIN_CPP
#define MAIN_CPP
/*
* MAIN.h
* PSC
*
* Copyright 2014 Pierre-David Letourneau
*
* 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.
*
* Overstructure.
*/
#include <vector>
#include <complex>
#include <iostream>
#include "Coordinates.h"
#include "IncWave.h"
#include "Scatterer.h"
#include "Distributions.h"
#include "PSCEnv.h"
#include "Imaging.h"
#include "Solver.h"
#include "Finalize.h"
int main(int argc,char **args)
{
int Proc_Idx = 0;
// PSC environment for fast algorithm
PSC_Env PSC_env(EPS);
// Linear solver
Solver solver;
// Global indexing
Indexing Index(LMAX); // TODO: Should not have different instances of Index
// Display relevant information concerning the problem
cout << endl << endl;
cout << "LMAX : " << LMAX << endl;
cout << "RTOL : " << RTOL << endl;
cout << "MAXITS : " << MAXITS << endl;
cout << "OMEGA : " << OMEGA << endl;
cout << "C_OUT : " << C_OUT << endl;
cout << "C : " << C << endl;
cout << "K_OUT : " << K_OUT << endl;
cout << "K : " << K << endl;
cout << "NScat : " << NScat << endl;
cout << "RADIUS : " << RADIUS << endl;
cout << "nLevels : " << nLevels << endl;
cout << "EPS : " << EPS << endl;
cout << endl;
// *** Parameters ***
int P = 20; // Number of simulations to carry out
// *** File names ***
std::string filename("../AcousticOutputFiles/Homogenization check/HomogenizationCheck_D_PHI=0,05_N=8000_");
std::string image_filename("../AcousticOutputFiles/Homogenization check/HomogenizationCheck_D_PHI=0,05_N=8000_image_");
// *** Image parameters ***
bool produce_image = true;
int M = 65; // Number of pixels: 2*M+1 from -M to M
double L = 0.5; // size of image [-L,L]x[-L,L]
// *** Source parameters ***
std::string src_type("PlaneWave");
Pvec src_wv(0., 0., std::abs(K_OUT)*1., Pvec::Cartesian); // Plane wave, eave vector
// *** Scatterer cluster parameters ***
Pvec center(0.,0.,0.,Pvec::Cartesian);
double d_min = 0.002 * 2*PI/std::abs(K_OUT);
double R = 0.4;
// ---- Computations -----
double kappa = RHO / RHO_OUT;
for( int p = 0; p < P; p++ ){
Proc_Idx = p;
std::vector< std::vector<complex > > RHS(NScat, std::vector<complex >(Index.size()));
std::vector< std::vector<complex> > u(NScat, std::vector<complex>(Index.size()));
std::vector< std::vector<complex> > u_in(NScat, std::vector<complex>(Index.size()));
// *** Construct scatterers ***
cout << "***Building scatterers..." << endl;
std::vector<Scatterer> ScL;
std::vector<Pvec> scat_loc = RandSpherical(R, RADIUS, d_min, center, NScat);
assert(scat_loc.size() == NScat);
for( int i = 0; i < NScat; i++ ){
Scatterer scatterer(RADIUS, K, K_OUT, RHO, scat_loc[i]);
ScL.push_back(scatterer);
}
//ScL = ScatInit( NScat, K, K_OUT);
cout << "***Building scatterers: done" << endl << endl;
// *** Construct PSC environment ***
cout << "***Constructing environment..." << endl;
PSC_env.Construct(nLevels, RADIUS, K, K_OUT, ScL);
cout << "***Constructing environment: done" << endl << endl;
// *** Initialization of source ***
PlaneWave* IW = new PlaneWave(1., src_wv);
//SphericalWave* IW = new SphericalWave(K_OUT, 1., src_wv);
// *** Initialization of right-hand side ***
cout << "***Initializing right-hand side..." << endl;
solver.RHSInit(IW, ScL, RHS);
cout << "***Initializing right-hand side: done" << endl;
// *** Solve linear system ***
cout << " ***Solving linear system..." << endl;
double res = 1e10, rel_res = 1e10, cond;
int Niter;
solver.Solve(PSC_env, ScL, RHS, u, res, rel_res, cond, Niter);
cout << " ***Solving linear system: done" << endl;
// *** Compute field inside scatterers ***
PSC_env.getTransfer()->execute(u, u_in);
for( int n = 0; n < NScat; n++ ){
std::vector<complex> u_src(Index.size());
Pvec p = ScL[n].getLocation();
IW->Translate(p, u_src);
for( int i = 0; i < (int) Index.size(); i++ )
u_in[n][i] += u_src[i];
}
for( int n = 0; n < NScat; n++ ){
for( int i = 0; i < (int) Index.size(); i++ ){
int l = Index(i,0);
complex T_coeff = -K_OUT * RADIUS*RADIUS * CI * ( K_OUT*Amos_sf_hankel_l_prime(l, K_OUT*RADIUS) * Amos_sf_bessel_jl(l, K*RADIUS)
- K/kappa * Amos_sf_hankel_1(l, K_OUT*RADIUS) * Amos_sf_bessel_jl_prime(l, K*RADIUS) );
u_in[n][i] = u_in[n][i] / T_coeff;// Scatterer::Mie_in(K, K_OUT, RADIUS, RHO, RHO_OUT, l, 0);
}
}
// *** Write information about problem to file ***
cout << " ***Writing to file..." << endl;
Write_Info(Proc_Idx, src_type, res, rel_res, cond, Niter, filename);
Write_Source(Proc_Idx, IW, IncWave::Pt, filename);
Write_Location(Proc_Idx, ScL, filename);
Write_Solution( Proc_Idx, Index, u, filename);
cout << " ***Writing to file: done" << endl << endl;
// *** Produce image ***
if( produce_image ){
std::vector< std::vector<complex> >* u_in_ptr; u_in_ptr = &u_in;
Imaging(ScL, IW, image_filename, u, Proc_Idx, M, L, u_in_ptr, K_OUT, K);
}
// Destroy environment
PSC_env.Destruct();
}
return 0;
}
#endif
| 29.826291 | 129 | 0.616087 | [
"vector"
] |
3d7344a62b44f55900a5d52967d5f020e08d074f | 805 | cpp | C++ | 150-Evaluate-Reverse-Polish-Notation/solution.cpp | johnhany/leetcode | 453a86ac16360e44893262e04f77fd350d1e80f2 | [
"Apache-2.0"
] | 3 | 2019-05-27T06:47:32.000Z | 2020-12-22T05:57:10.000Z | 150-Evaluate-Reverse-Polish-Notation/solution.cpp | johnhany/leetcode | 453a86ac16360e44893262e04f77fd350d1e80f2 | [
"Apache-2.0"
] | null | null | null | 150-Evaluate-Reverse-Polish-Notation/solution.cpp | johnhany/leetcode | 453a86ac16360e44893262e04f77fd350d1e80f2 | [
"Apache-2.0"
] | 5 | 2020-04-01T10:26:04.000Z | 2022-02-05T18:21:01.000Z | #include "solution.hpp"
static auto x = []() {
// turn off sync
std::ios::sync_with_stdio(false);
// untie in/out streams
cin.tie(NULL);
return 0;
}();
int Solution::evalRPN(vector<string>& tokens) {
if (tokens.size() == 1)
return stoi(tokens[0]);
int a, b, x = 0;
stack<int> nums;
set<string> operators{"+", "-", "*", "/"};
while (x < tokens.size()) {
if (operators.find(tokens[x]) == operators.end()) {
nums.push(stoi(tokens[x]));
} else {
b = nums.top();
nums.pop();
a = nums.top();
nums.pop();
if (tokens[x] == "+") {
nums.push(a + b);
} else if (tokens[x] == "-") {
nums.push(a - b);
} else if (tokens[x] == "*") {
nums.push(a * b);
} else {
nums.push(a / b);
}
}
x++;
}
return nums.top();
}
| 20.641026 | 54 | 0.495652 | [
"vector"
] |
3d75097fda2ae23734cfc7cac5354302d5250a5b | 977 | hpp | C++ | include/config_parser.hpp | Reisyukaku/EdiZon | 859e23d32220627828e26dff2ef0535e69fad54f | [
"MIT"
] | 1 | 2019-01-20T14:56:37.000Z | 2019-01-20T14:56:37.000Z | include/config_parser.hpp | Reisyukaku/EdiZon | 859e23d32220627828e26dff2ef0535e69fad54f | [
"MIT"
] | null | null | null | include/config_parser.hpp | Reisyukaku/EdiZon | 859e23d32220627828e26dff2ef0535e69fad54f | [
"MIT"
] | null | null | null | #pragma once
#include <string>
#include <unordered_map>
#include <vector>
#include "widget.hpp"
#include "types.h"
#include "json.hpp"
#define CONFIG_ROOT "/EdiZon/editor/"
using json = nlohmann::json;
class ScriptParser;
class ConfigParser {
public:
ConfigParser() = delete;
static s8 hasConfig(u64 titleId);
static s8 loadConfigFile(u64 titleId, std::string filepath);
static void unloadConfigFile();
static void createWidgets(WidgetItems &widgets, ScriptParser &scriptParser);
static inline std::unordered_map<u64, bool> g_editableTitles;
static inline std::unordered_map<u64, bool> g_betaTitles;
template<typename T>
static inline T getOptionalValue(json j, std::string key, T elseVal) {
return j.find(key) != j.end() ? j[key].get<T>() : elseVal;
}
static inline json& getConfigFile() {
return m_configFile;
}
private:
static inline json m_configFile;
static inline u8 m_useInsteadTries;
};
| 22.72093 | 80 | 0.70522 | [
"vector"
] |
3d7aca3eb4160b0af437508d67d607fe99f28369 | 21,900 | cc | C++ | mkldpy/deconv.cc | mingxiaoh/chainer-v3 | 815ff00f5eaf7944d6e8a75662ff64a2fe046a4d | [
"BSD-3-Clause"
] | null | null | null | mkldpy/deconv.cc | mingxiaoh/chainer-v3 | 815ff00f5eaf7944d6e8a75662ff64a2fe046a4d | [
"BSD-3-Clause"
] | null | null | null | mkldpy/deconv.cc | mingxiaoh/chainer-v3 | 815ff00f5eaf7944d6e8a75662ff64a2fe046a4d | [
"BSD-3-Clause"
] | null | null | null | /*
*COPYRIGHT
*All modification made by Intel Corporation: © 2017 Intel Corporation.
*Copyright (c) 2015 Preferred Infrastructure, Inc.
*Copyright (c) 2015 Preferred Networks, Inc.
*
*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.
*
*
*######################################################################
*# The CuPy is designed based on NumPy's API.
*# CuPy's source code and documents contain the original NumPy ones.
*######################################################################
*Copyright (c) 2005-2016, NumPy Developers.
*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 NumPy Developers nor the names of any
* 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 <glog/logging.h>
#include <iostream>
#include "common.h"
#include "mkldnn.hpp"
#include "deconv.h"
#include "utils.h"
using namespace mkldnn;
extern engine cpu_engine;
template<typename T>
DeConvolution2D<T>::DeConvolution2D()
{
fwd_stream_.reset(new stream(stream::kind::eager));
bwd_weights_stream_.reset(new stream(stream::kind::eager));
bwd_data_stream_.reset(new stream(stream::kind::eager));
}
template<typename T>
DeConvolution2D<T>::~DeConvolution2D()
{
}
template<typename T>
void DeConvolution2D<T>::forward_setup(T* x, int x_d1, int x_d2, int x_d3, int x_d4,
T* W, int W_d1, int W_d2, int W_d3, int W_d4,
T* b, int b_d1,
T* y, int y_d1, int y_d2, int y_d3, int y_d4,
int s1, int s2,
int pl1, int pl2,
int pr1, int pr2)
{
LOG(INFO) << "DeConvolution forward_setup";
/*
LOG(INFO) << "x =(" << x_d1 << "," << x_d2 << "," << x_d3 << "," << x_d4 << ")";
LOG(INFO) << "W =(" << W_d1 << "," << W_d2 << "," << W_d3 << "," << W_d4 << ")";
//LOG(INFO) << "b =(" << b_d1 << ")";
LOG(INFO) << "y =(" << y_d1 << "," << y_d2 << "," << y_d3 << "," << y_d4 << ")";
*/
/*
* DeConvolution fwd --> Convolution bwd data
*/
src_tz_ = {x_d1, x_d2, x_d3, x_d4};
weights_tz_ = {W_d1, W_d2, W_d3, W_d4};
dst_tz_ = {y_d1, y_d2, y_d3, y_d4};
strides_ = {s1, s2};
bias_tz_ = {b_d1};
padding_l_ = {pl1, pl2};
padding_r_ = {pr1, pr2};
/* create memory for user data */
user_src_mem_.reset(new memory({{{src_tz_}, memory_data_type<T>(),
memory::format::nchw}, cpu_engine}, dummy));
user_weights_mem_.reset(new memory({{{weights_tz_},
memory_data_type<T>(), memory::format::oihw}, cpu_engine}, dummy));
/* in current design, output is also allocated in python part */
user_dst_mem_.reset(new memory({{{dst_tz_}, memory_data_type<T>(),
memory::format::nchw}, cpu_engine}, dummy));
/* create memory descriptors for convolution data w/ no specified format */
src_md_.reset(new memory::desc({src_tz_}, memory_data_type<T>(),
memory::format::any));
weights_md_.reset(new memory::desc({weights_tz_},
memory_data_type<T>(), memory::format::any));
dst_md_.reset(new memory::desc({dst_tz_}, memory_data_type<T>(),
memory::format::any));
if ( b != NULL ) {
bias_md_.reset(new memory::desc({bias_tz_}, memory_data_type<T>(),
memory::format::any));
}
/* create a deconvolution */
/*
* convolution bwd data need convolution fwd as hint, so create convolution fwd here which will be used as deconvolution bwd data
*/
fwd_desc_.reset(new convolution_forward::desc(prop_kind::forward,
convolution_direct, *dst_md_, *weights_md_,
*src_md_, strides_, padding_l_,padding_r_, padding_kind::zero));
fwd_pd_.reset(new convolution_forward::primitive_desc(*fwd_desc_,cpu_engine));
/*
* use convolution bwd data to implement deconvolution fwd
* data backward conv prim desc (gX = gy * W) ==> deconv: y = x * W
* for data backward conv, no need b/gb
* src_md: gx ==> deconv: y
* weigths_md: W ==> deconv: W
* dst_md: gy ==> deconv: x
* */
bwd_data_desc_.reset(new convolution_backward_data::desc(
convolution_direct, *dst_md_, *weights_md_,
*src_md_, strides_, padding_l_, padding_r_, padding_kind::zero));
bwd_data_pd_.reset(new convolution_backward_data::primitive_desc(
*bwd_data_desc_, cpu_engine, *fwd_pd_));
/* create reorders between user and data if it is needed and
* add it to net before convolution */
// deconvolution fwd's x is gy in convolution bwd data
src_mem_ = user_src_mem_;
if (memory::primitive_desc(bwd_data_pd_.get()->diff_dst_primitive_desc())
!= user_src_mem_.get()->get_primitive_desc()) {
LOG(INFO) << "fwd reorder src dim";
src_mem_.reset(new memory(bwd_data_pd_.get()->diff_dst_primitive_desc()));
deconv_reorder_src_ = reorder(*user_src_mem_,*src_mem_);
fwd_reorder_deconv_src_ = true;
}
// deconvolution fwd's w is w in convolution bwd data
weights_mem_ = user_weights_mem_;
if (memory::primitive_desc(bwd_data_pd_.get()->weights_primitive_desc())
!= user_weights_mem_.get()->get_primitive_desc()) {
LOG(INFO) << "fwd reorder W";
weights_mem_.reset(new memory(bwd_data_pd_.get()->weights_primitive_desc()));
deconv_reorder_weights_ = reorder(*user_weights_mem_, *weights_mem_);
fwd_reorder_deconv_weights_ = true;
}
// deconvolution fwd's y is gx in convolution bwd data
dst_mem_ = user_dst_mem_;
if (memory::primitive_desc(bwd_data_pd_.get()->diff_src_primitive_desc())
!= user_dst_mem_.get()->get_primitive_desc()) {
LOG(INFO) << "fwd reorder y";
dst_mem_.reset(new memory(bwd_data_pd_.get()->diff_src_primitive_desc()));
deconv_reorder_dst_ = reorder(*dst_mem_, *user_dst_mem_);
fwd_reorder_deconv_dst_ = true;
}
/* create deconvolution primitive and add it to net */
deconv_bwd_data_.reset(new convolution_backward_data(
*bwd_data_pd_, *src_mem_, *weights_mem_, *dst_mem_));
//put all primitives into fwd_stream_
if (fwd_reorder_deconv_src_){
fwd_primitives_.push_back(deconv_reorder_src_);
}
if (fwd_reorder_deconv_weights_){
fwd_primitives_.push_back(deconv_reorder_weights_);
}
fwd_primitives_.push_back(*deconv_bwd_data_);
if (fwd_reorder_deconv_dst_){
fwd_primitives_.push_back(deconv_reorder_dst_);
}
return;
}
template<typename T>
int DeConvolution2D<T>::forward(T* x, int x_d1, int x_d2, int x_d3, int x_d4,
T* W, int W_d1, int W_d2, int W_d3, int W_d4,
T* b, int b_d1,
T* y, int y_d1, int y_d2, int y_d3, int y_d4,
int s1, int s2,
int pl1, int pl2,
int pr1, int pr2)
{
LOG(INFO) << "DeConvolution forward" << b;
if (deconv_bwd_data_ == NULL) {
forward_setup(x, x_d1, x_d2, x_d3, x_d4,
W, W_d1, W_d2, W_d3, W_d4,
b, b_d1,
y, y_d1, y_d2, y_d3, y_d4,
s1, s2,
pl1, pl2,
pr1, pr2);
}
//LOG(INFO) << "conv_fwd_:" << conv_fwd_;
//LOG(INFO) << "x=" << x << "; x_size=" << x_d1*x_d2*x_d3*x_d4*4;
user_src_mem_->set_data_handle(x);
user_weights_mem_->set_data_handle(W);
user_dst_mem_->set_data_handle(y);
if (fwd_first_run_) {
fwd_stream_->submit(fwd_primitives_).wait();
fwd_first_run_ = false;
} else {
fwd_stream_->rerun().wait();
}
return 0;
}
template<typename T>
int DeConvolution2D<T>::forward(T* x, int x_d1, int x_d2, int x_d3, int x_d4,
T* W, int W_d1, int W_d2, int W_d3, int W_d4,
T* y, int y_d1, int y_d2, int y_d3, int y_d4,
int s1, int s2,
int pl1, int pl2,
int pr1, int pr2)
{
LOG(INFO) << "DeConvolution forward without bias";
// LOG(INFO) << conv_fwd_;
forward(x, x_d1, x_d2, x_d3, x_d4,
W, W_d1, W_d2, W_d3, W_d4,
NULL, -1,
y, y_d1, y_d2, y_d3, y_d4,
s1, s2,
pl1, pl2,
pr1, pr2);
return 0;
}
template<typename T>
void DeConvolution2D<T>::backward_setup( T* x, int x_d1, int x_d2, int x_d3, int x_d4,
T* W, int W_d1, int W_d2, int W_d3, int W_d4,
T* b, int b_d1,
T* gy, int gy_d1, int gy_d2, int gy_d3, int gy_d4,
T* gW, int gW_d1, int gW_d2, int gW_d3, int gW_d4,
T* gx, int gx_d1, int gx_d2, int gx_d3, int gx_d4,
T* gb, int gb_d1)
{
LOG(INFO) << "DeConvolution backward_setup";
#if 1
/* create user format memory*/
user_bwd_src_mem_.reset(new memory({{{ src_tz_ }, memory_data_type<T>(),
memory::format::nchw }, cpu_engine }, dummy)); //x
user_bwd_weights_mem_.reset(new memory({{{ weights_tz_ }, memory_data_type<T>(),
memory::format::oihw }, cpu_engine }, dummy)); //W
user_bwd_diff_dst_mem_.reset(new memory({{{ dst_tz_ }, memory_data_type<T>(),
memory::format::nchw }, cpu_engine }, dummy)); //gy
user_bwd_diff_weights_mem_.reset(new memory({{{ weights_tz_ }, memory_data_type<T>(),
memory::format::oihw }, cpu_engine }, dummy)); //gW
user_bwd_diff_src_mem_.reset(new memory({{{ src_tz_ }, memory_data_type<T>(),
memory::format::nchw }, cpu_engine }, dummy)); //gx
if ( b != NULL ) {
user_bwd_diff_bias_mem_.reset(new memory({{{ bias_tz_}, memory_data_type<T>(),
memory::format::x,}, cpu_engine}, dummy)); //gB
}
/*
* create backward deconvolution operator desc
* memory desc can be shared between forward and backward, since they have same shape
* */
if ( b != NULL) {
/*
* weight backward deconv desc (gW = gy * X)
* src_md: x == convolution_backward_weights
* weigths_md: gW
* bias_md: gb
* dst_md: gy == convolution backward src
* */
bwd_weights_desc_.reset(new convolution_backward_weights::desc(
convolution_direct, *dst_md_, *weights_md_,
*bias_md_, *src_md_, strides_, padding_l_, padding_r_, padding_kind::zero));
} else {
/*
* weight backward deconv prim desc (gW = gy * X)
* src_md: x == convolution backward weights
* weigths_md: gW
* dst_md: gy == convolution backward src
* */
bwd_weights_desc_.reset(new convolution_backward_weights::desc(
convolution_direct, *dst_md_, *weights_md_,
*src_md_, strides_, padding_l_, padding_r_, padding_kind::zero));
}
/*
* For deconv backward:
* deconv backward weight == conv backward weight
* deconv backward data == conv forward
* */
bwd_weights_pd_.reset(new convolution_backward_weights::primitive_desc(
*bwd_weights_desc_, cpu_engine, *fwd_pd_));
/*
* for best performance convolution backward might choose different memory format for src and diffsrc
* than the memory formats preferred by forward convolution for src and dst respectively
* create reorder primitive for src from forward convolution to the format chosen by backward convolution */
/* user_bwd_src_mem_ ==> x */
bwd_src_mem_ = user_bwd_src_mem_;
if (memory::primitive_desc(bwd_weights_pd_.get()->diff_dst_primitive_desc())
!= user_bwd_src_mem_.get()->get_primitive_desc()) {
LOG(INFO) << "bwd reorder x";
bwd_src_mem_.reset(new memory(bwd_weights_pd_.get()->diff_dst_primitive_desc()));
deconv_bwd_reorder_src_ = reorder(*user_bwd_src_mem_, *bwd_src_mem_);
bwd_reorder_src_ = true;
}
/* user_bwd_diff_dst_weights_mem_ ==> gy for gW*/
bwd_diff_dst_weights_mem_ = user_bwd_diff_dst_mem_;
if (memory::primitive_desc(bwd_weights_pd_.get()->src_primitive_desc())
!= user_bwd_diff_dst_mem_.get()->get_primitive_desc()) {
LOG(INFO) << "bwd reorder gy";
bwd_diff_dst_weights_mem_.reset(new memory(bwd_weights_pd_.get()->src_primitive_desc()));
deconv_bwd_reorder_dst_weights_ = reorder(*user_bwd_diff_dst_mem_, *bwd_diff_dst_weights_mem_);
bwd_reorder_diff_dst_weights_ = true;
}
/* user_bwd_diff_weights_mem_ ==> gW */
bwd_diff_weights_mem_ = user_bwd_diff_weights_mem_;
if (memory::primitive_desc(bwd_weights_pd_.get()->diff_weights_primitive_desc())
!= user_bwd_diff_weights_mem_.get()->get_primitive_desc()) {
LOG(INFO) << "bwd reorder gW";
bwd_diff_weights_mem_.reset(new memory(bwd_weights_pd_.get()->diff_weights_primitive_desc()));
deconv_bwd_reorder_diff_weights_ = reorder(*bwd_diff_weights_mem_, *user_bwd_diff_weights_mem_);
bwd_reorder_diff_weights_ = true;
}
/* create weight deconv bwd prim */
if (b != NULL) {
/*
* create deconvolution backward primitive (gW = gy * X)
* src_mem: x ==> convolution backward diff dst
* diff_dst_mem: gy ==> convolution backward src
* diff_weights_mem: gW
* diff_bias_mem: gb
* */
deconv_bwd_weights_.reset( new convolution_backward_weights(
*bwd_weights_pd_, *bwd_diff_dst_weights_mem_, *bwd_src_mem_,
*bwd_diff_weights_mem_, *user_bwd_diff_bias_mem_));
} else {
/*
* create deconvolution backward primitive (gW = gy * x)
* src_mem: x
* diff_dst_mem: gy
* diff_weights_mem: gW
* */
deconv_bwd_weights_.reset( new convolution_backward_weights(
*bwd_weights_pd_, *bwd_diff_dst_weights_mem_,
*bwd_src_mem_, *bwd_diff_weights_mem_));
}
/*
* create weight deconv bwd stream (gW = gy * X)
*
* reorder_x -> reorder_gy -> weight_conv_bwd -> reoder_gW
*
*/
if (bwd_reorder_src_) {
bwd_weights_primitives_.push_back(deconv_bwd_reorder_src_);
}
if (bwd_reorder_diff_dst_weights_) {
bwd_weights_primitives_.push_back(deconv_bwd_reorder_dst_weights_);
}
bwd_weights_primitives_.push_back(*deconv_bwd_weights_);
if (bwd_reorder_diff_weights_) {
bwd_weights_primitives_.push_back(deconv_bwd_reorder_diff_weights_);
}
/*
* DeConvolution backward data == conv fwd
* conv fwd pd has already been created in forward_setup
*/
fwd_desc_.reset(new convolution_forward::desc(prop_kind::forward,
convolution_direct, *dst_md_, *weights_md_,
*src_md_, strides_, padding_l_,padding_r_, padding_kind::zero));
fwd_pd_.reset(new convolution_forward::primitive_desc(*fwd_desc_,cpu_engine));
//reorder gy
bwd_diff_dst_data_mem_ = user_bwd_diff_dst_mem_;
if (memory::primitive_desc(fwd_pd_.get()->src_primitive_desc())
!= user_bwd_diff_dst_mem_.get()->get_primitive_desc()) {
LOG(INFO) << "bwd data reorder gy dim";
bwd_diff_dst_data_mem_.reset(new memory(fwd_pd_.get()->src_primitive_desc()));
deconv_bwd_reorder_dst_data_ = reorder(*user_bwd_diff_dst_mem_, *bwd_diff_dst_data_mem_);
bwd_reorder_diff_dst_data_ = true;
}
//reorder W
bwd_weights_mem_ = user_bwd_weights_mem_;
if (memory::primitive_desc(fwd_pd_.get()->weights_primitive_desc())
!= user_bwd_weights_mem_.get()->get_primitive_desc()) {
LOG(INFO) << "bwd data reorder W dim";
bwd_weights_mem_.reset(new memory(fwd_pd_.get()->weights_primitive_desc()));
deconv_bwd_reorder_weights_ = reorder(*user_bwd_weights_mem_, *bwd_weights_mem_);
bwd_reorder_weights_ = true;
}
//reorder gx
bwd_diff_src_mem_ = user_bwd_diff_src_mem_;
if (memory::primitive_desc(fwd_pd_.get()->dst_primitive_desc())
!= user_bwd_diff_src_mem_.get()->get_primitive_desc()) {
LOG(INFO) << "bwd data reorder gx dim";
bwd_diff_src_mem_.reset(new memory(fwd_pd_.get()->dst_primitive_desc()));
deconv_bwd_reorder_diff_src_ = reorder( *bwd_diff_src_mem_, *user_bwd_diff_src_mem_);
bwd_reorder_diff_src_ = true;
}
//create conv fwd primitive for deconvolution backward data
deconv_fwd_.reset(new convolution_forward(*fwd_pd_, *bwd_diff_dst_data_mem_,
*bwd_weights_mem_, *bwd_diff_src_mem_));
/*
* create data conv bwd stream (gX = gy * W)
*
* reorder_W -> reorder_gy -> data_conv_bwd -> reorder_gX
*
*/
if (bwd_reorder_weights_) {
bwd_data_primitives_.push_back(deconv_bwd_reorder_weights_);
}
if (bwd_reorder_diff_dst_data_) {
bwd_data_primitives_.push_back(deconv_bwd_reorder_dst_data_);
}
bwd_data_primitives_.push_back(*deconv_fwd_);
if (bwd_reorder_diff_src_) {
bwd_data_primitives_.push_back(deconv_bwd_reorder_diff_src_);
}
#endif
return;
}
template<typename T>
int DeConvolution2D<T>::backward( T* x, int x_d1, int x_d2, int x_d3, int x_d4,
T* W, int W_d1, int W_d2, int W_d3, int W_d4,
T* b, int b_d1,
T* gy, int gy_d1, int gy_d2, int gy_d3, int gy_d4,
T* gW, int gW_d1, int gW_d2, int gW_d3, int gW_d4,
T* gx, int gx_d1, int gx_d2, int gx_d3, int gx_d4,
T* gb, int gb_d1,
bool first_layer)
{
#if 1
LOG(INFO) << "DeConvolution backward with bias " << b;
if (deconv_bwd_weights_ == NULL) {
backward_setup(x, x_d1, x_d2, x_d3, x_d4,
W, W_d1, W_d2, W_d3, W_d4,
b, b_d1,
gy, gy_d1, gy_d2, gy_d3, gy_d4,
gW, gW_d1, gW_d2, gW_d3, gW_d4,
gx, gx_d1, gx_d2, gx_d3, gx_d4,
gb, gb_d1);
}
user_bwd_src_mem_->set_data_handle(x); //x
user_bwd_weights_mem_->set_data_handle(W); //W
user_bwd_diff_src_mem_->set_data_handle(gx); //gx
user_bwd_diff_weights_mem_->set_data_handle(gW); //gW
user_bwd_diff_dst_mem_->set_data_handle(gy); //gy
if (b!=NULL) {
user_bwd_diff_bias_mem_->set_data_handle(gb); //gb
}
if (bwd_first_run_) {
bwd_weights_stream_->submit(bwd_weights_primitives_).wait();
if (!first_layer)//first layer will no need to do backward data
bwd_data_stream_->submit(bwd_data_primitives_).wait();
bwd_first_run_ = false;
} else {
bwd_weights_stream_->rerun().wait();
if (!first_layer)
bwd_data_stream_->rerun().wait();
}
#endif
return 0;
}
template<typename T>
int DeConvolution2D<T>::backward( T* x, int x_d1, int x_d2, int x_d3, int x_d4,
T* W, int W_d1, int W_d2, int W_d3, int W_d4,
T* gy, int gy_d1, int gy_d2, int gy_d3, int gy_d4,
T* gW, int gW_d1, int gW_d2, int gW_d3, int gW_d4,
T* gx, int gx_d1, int gx_d2, int gx_d3, int gx_d4,
bool first_layer)
{
#if 1
LOG(INFO) << "Convolution backward without bias";
backward(x, x_d1, x_d2, x_d3, x_d4,
W, W_d1, W_d2, W_d3, W_d4,
NULL, -1,
gy, gy_d1, gy_d2, gy_d3, gy_d4,
gW, gW_d1, gW_d2, gW_d3, gW_d4,
gx, gx_d1, gx_d2, gx_d3, gx_d4,
NULL, -1,
first_layer);
#endif
return 0;
}
template class DeConvolution2D<float>;
// vim: et ts=4 sw=4 cindent cino^=l0,\:0,N-s
| 40.782123 | 133 | 0.637854 | [
"shape"
] |
3d80ff906a14e00df8ab2dfee3189c803b17720c | 1,401 | cpp | C++ | Engine/Source/Editor/UnrealEd/Private/Fbx/FbxSkeletalMeshImportData.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | 1 | 2022-01-29T18:36:12.000Z | 2022-01-29T18:36:12.000Z | Engine/Source/Editor/UnrealEd/Private/Fbx/FbxSkeletalMeshImportData.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | Engine/Source/Editor/UnrealEd/Private/Fbx/FbxSkeletalMeshImportData.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "Factories/FbxSkeletalMeshImportData.h"
#include "Engine/SkeletalMesh.h"
UFbxSkeletalMeshImportData::UFbxSkeletalMeshImportData(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
, bImportMeshesInBoneHierarchy(true)
{
bTransformVertexToAbsolute = true;
bBakePivotInVertex = false;
}
UFbxSkeletalMeshImportData* UFbxSkeletalMeshImportData::GetImportDataForSkeletalMesh(USkeletalMesh* SkeletalMesh, UFbxSkeletalMeshImportData* TemplateForCreation)
{
check(SkeletalMesh);
UFbxSkeletalMeshImportData* ImportData = Cast<UFbxSkeletalMeshImportData>(SkeletalMesh->AssetImportData);
if ( !ImportData )
{
ImportData = NewObject<UFbxSkeletalMeshImportData>(SkeletalMesh, NAME_None, RF_NoFlags, TemplateForCreation);
// Try to preserve the source file data if possible
if ( SkeletalMesh->AssetImportData != NULL )
{
ImportData->SourceData = SkeletalMesh->AssetImportData->SourceData;
}
SkeletalMesh->AssetImportData = ImportData;
}
return ImportData;
}
bool UFbxSkeletalMeshImportData::CanEditChange(const UProperty* InProperty) const
{
bool bMutable = Super::CanEditChange(InProperty);
UObject* Outer = GetOuter();
if(Outer && bMutable)
{
// Let the FbxImportUi object handle the editability of our properties
bMutable = Outer->CanEditChange(InProperty);
}
return bMutable;
}
| 30.456522 | 162 | 0.798001 | [
"object"
] |
3d8480fd91405c387c9163ed70a05b6ae58ca672 | 2,766 | hpp | C++ | REDSI_1160929_1161573/boost_1_67_0/libs/spirit/example/qi/iter_pos.hpp | Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo | eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8 | [
"MIT"
] | 32 | 2019-02-27T06:57:07.000Z | 2021-08-29T10:56:19.000Z | REDSI_1160929_1161573/boost_1_67_0/libs/spirit/example/qi/iter_pos.hpp | Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo | eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8 | [
"MIT"
] | 1 | 2019-03-04T11:21:00.000Z | 2019-05-24T01:36:31.000Z | REDSI_1160929_1161573/boost_1_67_0/libs/spirit/example/qi/iter_pos.hpp | Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo | eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8 | [
"MIT"
] | 5 | 2019-08-20T13:45:04.000Z | 2022-03-01T18:23:49.000Z | // Copyright (c) 2001-2010 Hartmut Kaiser
//
// 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)
#if !defined(ITER_POS_NOV_20_2009_1245PM)
#define ITER_POS_NOV_20_2009_1245PM
#include <boost/spirit/include/qi_parse.hpp>
///////////////////////////////////////////////////////////////////////////////
// definition the place holder
namespace custom_parser
{
BOOST_SPIRIT_TERMINAL(iter_pos)
}
///////////////////////////////////////////////////////////////////////////////
// implementation the enabler
namespace boost { namespace spirit
{
// We want custom_parser::iter_pos to be usable as a terminal only,
// and only for parser expressions (qi::domain).
template <>
struct use_terminal<qi::domain, custom_parser::tag::iter_pos>
: mpl::true_
{};
}}
///////////////////////////////////////////////////////////////////////////////
// implementation of the parser
namespace custom_parser
{
struct iter_pos_parser
: boost::spirit::qi::primitive_parser<iter_pos_parser>
{
// Define the attribute type exposed by this parser component
template <typename Context, typename Iterator>
struct attribute
{
typedef Iterator type;
};
// This function is called during the actual parsing process
template <typename Iterator, typename Context
, typename Skipper, typename Attribute>
bool parse(Iterator& first, Iterator const& last
, Context&, Skipper const& skipper, Attribute& attr) const
{
boost::spirit::qi::skip_over(first, last, skipper);
boost::spirit::traits::assign_to(first, attr);
return true;
}
// This function is called during error handling to create
// a human readable string for the error context.
template <typename Context>
boost::spirit::info what(Context&) const
{
return boost::spirit::info("iter_pos");
}
};
}
///////////////////////////////////////////////////////////////////////////////
// instantiation of the parser
namespace boost { namespace spirit { namespace qi
{
// This is the factory function object invoked in order to create
// an instance of our iter_pos_parser.
template <typename Modifiers>
struct make_primitive<custom_parser::tag::iter_pos, Modifiers>
{
typedef custom_parser::iter_pos_parser result_type;
result_type operator()(unused_type, unused_type) const
{
return result_type();
}
};
}}}
#endif
| 32.928571 | 82 | 0.564714 | [
"object"
] |
3d8f5037b5c771617b653ad464a4433092e91bd8 | 5,060 | cpp | C++ | clang/test/Driver/sycl-offload-nvptx.cpp | mgehre-xlx/sycl | 2086745509ef4bc298d7bbec402a123dae68f25e | [
"Apache-2.0"
] | 61 | 2019-04-12T18:49:57.000Z | 2022-03-19T22:23:16.000Z | clang/test/Driver/sycl-offload-nvptx.cpp | mgehre-xlx/sycl | 2086745509ef4bc298d7bbec402a123dae68f25e | [
"Apache-2.0"
] | 127 | 2019-04-09T00:55:50.000Z | 2022-03-21T15:35:41.000Z | clang/test/Driver/sycl-offload-nvptx.cpp | mgehre-xlx/sycl | 2086745509ef4bc298d7bbec402a123dae68f25e | [
"Apache-2.0"
] | 10 | 2019-04-02T18:25:40.000Z | 2022-02-15T07:11:37.000Z | /// Tests specific to `-fsycl-targets=nvptx64-nvidia-nvcl-sycldevice`
// REQUIRES: clang-driver
// UNSUPPORTED: system-windows
/// Check action graph.
// RUN: %clangxx -### -std=c++11 -target x86_64-unknown-linux-gnu -fsycl \
// RUN: -fsycl-targets=nvptx64-nvidia-cuda --cuda-path=%S/Inputs/CUDA/usr/local/cuda \
// RUN: -fsycl-libspirv-path=%S/Inputs/SYCL/libspirv.bc %s 2>&1 \
// RUN: | FileCheck -check-prefix=CHK-ACTIONS %s
// CHK-ACTIONS: "-cc1" "-triple" "nvptx64-nvidia-cuda" "-aux-triple" "x86_64-unknown-linux-gnu"{{.*}} "-fsycl-is-device"{{.*}} "-Wno-sycl-strict"{{.*}} "-sycl-std=2020" {{.*}} "-emit-llvm-bc" {{.*}} "-internal-isystem" "{{.*}}bin{{[/\\]+}}..{{[/\\]+}}include{{[/\\]+}}sycl"{{.*}} "-mlink-builtin-bitcode" "{{.*}}libspirv.bc"{{.*}} "-mlink-builtin-bitcode" "{{.*}}libdevice{{.*}}.10.bc"{{.*}} "-target-feature" "+ptx42"{{.*}} "-target-sdk-version=[[CUDA_VERSION:[0-9.]+]]"{{.*}} "-target-cpu" "sm_50"{{.*}} "-std=c++11"{{.*}}
// CHK-ACTIONS: sycl-post-link{{.*}} "-split=auto"
// CHK-ACTIONS: file-table-tform" "-extract=Code" "-drop_titles"
// CHK-ACTIONS: llvm-foreach" {{.*}} "--" "{{.*}}clang-{{[0-9]+}}"
// CHK-ACTIONS: llvm-foreach" {{.*}} "--" "{{.*}}ptxas"
// CHK-ACTIONS: llvm-foreach" {{.*}} "--" "{{.*}}fatbinary"
// CHK-ACTIONS: file-table-tform" "-replace=Code,Code"
// CHK-ACTIONS-NOT: "-mllvm -sycl-opt"
// CHK-ACTIONS: clang-offload-wrapper"{{.*}} "-host=x86_64-unknown-linux-gnu" "-target=nvptx64" "-kind=sycl"{{.*}}
/// Check phases w/out specifying a compute capability.
// RUN: %clangxx -ccc-print-phases -std=c++11 -target x86_64-unknown-linux-gnu -fsycl \
// RUN: -fsycl-targets=nvptx64-nvidia-cuda %s 2>&1 \
// RUN: | FileCheck -check-prefix=CHK-PHASES-NO-CC %s
// CHK-PHASES-NO-CC: 0: input, "{{.*}}", c++, (host-sycl)
// CHK-PHASES-NO-CC: 1: append-footer, {0}, c++, (host-sycl)
// CHK-PHASES-NO-CC: 2: preprocessor, {1}, c++-cpp-output, (host-sycl)
// CHK-PHASES-NO-CC: 3: input, "{{.*}}", c++, (device-sycl, sm_50)
// CHK-PHASES-NO-CC: 4: preprocessor, {3}, c++-cpp-output, (device-sycl, sm_50)
// CHK-PHASES-NO-CC: 5: compiler, {4}, ir, (device-sycl, sm_50)
// CHK-PHASES-NO-CC: 6: offload, "host-sycl (x86_64-unknown-linux-gnu)" {2}, "device-sycl (nvptx64-nvidia-cuda:sm_50)" {5}, c++-cpp-output
// CHK-PHASES-NO-CC: 7: compiler, {6}, ir, (host-sycl)
// CHK-PHASES-NO-CC: 8: backend, {7}, assembler, (host-sycl)
// CHK-PHASES-NO-CC: 9: assembler, {8}, object, (host-sycl)
// CHK-PHASES-NO-CC: 10: linker, {9}, image, (host-sycl)
// CHK-PHASES-NO-CC: 11: linker, {5}, ir, (device-sycl, sm_50)
// CHK-PHASES-NO-CC: 12: sycl-post-link, {11}, ir, (device-sycl, sm_50)
// CHK-PHASES-NO-CC: 13: file-table-tform, {12}, ir, (device-sycl, sm_50)
// CHK-PHASES-NO-CC: 14: backend, {13}, assembler, (device-sycl, sm_50)
// CHK-PHASES-NO-CC: 15: assembler, {14}, object, (device-sycl, sm_50)
// CHK-PHASES-NO-CC: 16: linker, {14, 15}, cuda-fatbin, (device-sycl, sm_50)
// CHK-PHASES-NO-CC: 17: foreach, {13, 16}, cuda-fatbin, (device-sycl, sm_50)
// CHK-PHASES-NO-CC: 18: file-table-tform, {12, 17}, tempfiletable, (device-sycl, sm_50)
// CHK-PHASES-NO-CC: 19: clang-offload-wrapper, {18}, object, (device-sycl, sm_50)
// CHK-PHASES-NO-CC: 20: offload, "host-sycl (x86_64-unknown-linux-gnu)" {10}, "device-sycl (nvptx64-nvidia-cuda:sm_50)" {19}, image
/// Check phases specifying a compute capability.
// RUN: %clangxx -ccc-print-phases -std=c++11 -target x86_64-unknown-linux-gnu -fsycl \
// RUN: -fsycl-targets=nvptx64-nvidia-cuda \
N.)
// RUN: -Xsycl-target-backend "--cuda-gpu-arch=sm_35" %s 2>&1 \
// RUN: | FileCheck -check-prefix=CHK-PHASES %s
// CHK-PHASES: 0: input, "{{.*}}", c++, (host-sycl)
// CHK-PHASES: 1: append-footer, {0}, c++, (host-sycl)
// CHK-PHASES: 2: preprocessor, {1}, c++-cpp-output, (host-sycl)
// CHK-PHASES: 3: input, "{{.*}}", c++, (device-sycl, sm_35)
// CHK-PHASES: 4: preprocessor, {3}, c++-cpp-output, (device-sycl, sm_35)
// CHK-PHASES: 5: compiler, {4}, ir, (device-sycl, sm_35)
// CHK-PHASES: 6: offload, "host-sycl (x86_64-unknown-linux-gnu)" {2}, "device-sycl (nvptx64-nvidia-cuda:sm_35)" {5}, c++-cpp-output
// CHK-PHASES: 7: compiler, {6}, ir, (host-sycl)
// CHK-PHASES: 8: backend, {7}, assembler, (host-sycl)
// CHK-PHASES: 9: assembler, {8}, object, (host-sycl)
// CHK-PHASES: 10: linker, {9}, image, (host-sycl)
// CHK-PHASES: 11: linker, {5}, ir, (device-sycl, sm_35)
// CHK-PHASES: 12: sycl-post-link, {11}, ir, (device-sycl, sm_35)
// CHK-PHASES: 13: file-table-tform, {12}, ir, (device-sycl, sm_35)
// CHK-PHASES: 14: backend, {13}, assembler, (device-sycl, sm_35)
// CHK-PHASES: 15: assembler, {14}, object, (device-sycl, sm_35)
// CHK-PHASES: 16: linker, {14, 15}, cuda-fatbin, (device-sycl, sm_35)
// CHK-PHASES: 17: foreach, {13, 16}, cuda-fatbin, (device-sycl, sm_35)
// CHK-PHASES: 18: file-table-tform, {12, 17}, tempfiletable, (device-sycl, sm_35)
// CHK-PHASES: 19: clang-offload-wrapper, {18}, object, (device-sycl, sm_35)
// CHK-PHASES: 20: offload, "host-sycl (x86_64-unknown-linux-gnu)" {10}, "device-sycl (nvptx64-nvidia-cuda:sm_35)" {19}, image
| 67.466667 | 524 | 0.632609 | [
"object"
] |
3d94812590b6978dc9d5cc0e2acb085d1ed9e88c | 677 | cpp | C++ | NowCoder/CodingInterviews/PrintLevel.cpp | cnsteven/online-judge | 60ee841a97e2bc0dc9c7b23fe5daa186898ab8b7 | [
"MIT"
] | 1 | 2019-05-04T10:28:32.000Z | 2019-05-04T10:28:32.000Z | NowCoder/CodingInterviews/PrintLevel.cpp | cnsteven/online-judge | 60ee841a97e2bc0dc9c7b23fe5daa186898ab8b7 | [
"MIT"
] | null | null | null | NowCoder/CodingInterviews/PrintLevel.cpp | cnsteven/online-judge | 60ee841a97e2bc0dc9c7b23fe5daa186898ab8b7 | [
"MIT"
] | 3 | 2020-12-31T04:36:38.000Z | 2021-07-25T07:39:31.000Z | #include "main.h"
class Solution {
public:
vector<vector<int>> Print(TreeNode *pRoot) {
if (pRoot == nullptr)
return {};
vector<vector<int>> res;
queue<TreeNode *> q;
q.push(pRoot);
while (!q.empty()) {
int size = q.size();
vector<int> level;
while (size--) {
auto t = q.front();
level.push_back(t->val);
if (t->left)
q.push(t->left);
if (t->right)
q.push(t->right);
q.pop();
}
res.push_back(level);
}
return res;
}
}; | 25.074074 | 48 | 0.394387 | [
"vector"
] |
3d95ff2b44f8bde0006c45ca09ebc5670723368c | 17,272 | cpp | C++ | Sources/Elastos/Frameworks/Droid/Base/Services/Server/src/elastos/droid/server/connectivity/PacManager.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 7 | 2017-07-13T10:34:54.000Z | 2021-04-16T05:40:35.000Z | Sources/Elastos/Frameworks/Droid/Base/Services/Server/src/elastos/droid/server/connectivity/PacManager.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | null | null | null | Sources/Elastos/Frameworks/Droid/Base/Services/Server/src/elastos/droid/server/connectivity/PacManager.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 9 | 2017-07-13T12:33:20.000Z | 2021-06-19T02:46:48.000Z | //=========================================================================
// Copyright (C) 2012 The Elastos Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//=========================================================================
#include <elastos/droid/server/connectivity/PacManager.h>
#include <elastos/droid/server/IoThread.h>
#include <elastos/droid/os/SystemClock.h>
#include <elastos/core/AutoLock.h>
#include <elastos/core/StringUtils.h>
#include <elastos/core/StringBuilder.h>
#include <elastos/utility/logging/Logger.h>
#include <Elastos.Droid.App.h>
#include <Elastos.Droid.Net.h>
#include <Elastos.Droid.Os.h>
#include <Elastos.Droid.Content.h>
#include <Elastos.Droid.Provider.h>
#include <Elastos.CoreLibrary.Libcore.h>
#include <Elastos.CoreLibrary.IO.h>
#include <Elastos.CoreLibrary.Net.h>
#include <elastos/core/AutoLock.h>
using Elastos::Core::AutoLock;
using Elastos::Droid::Os::IMessage;
using Elastos::Droid::Os::IServiceManager;
using Elastos::Droid::Os::CServiceManager;
using Elastos::Droid::Os::SystemClock;
using Elastos::Droid::Os::ISystemProperties;
using Elastos::Droid::Os::CSystemProperties;
using Elastos::Droid::Net::IUriHelper;
using Elastos::Droid::Net::CUriHelper;
using Elastos::Droid::Net::CProxyInfo;
// using Elastos::Droid::Net::IIProxyCallback;
// using Elastos::Droid::Net::IIProxyPortListener;
using Elastos::Droid::App::IPendingIntentHelper;
using Elastos::Droid::App::CPendingIntentHelper;
using Elastos::Droid::Content::CIntent;
using Elastos::Droid::Content::CIntentFilter;
using Elastos::Droid::Content::EIID_IServiceConnection;
using Elastos::Droid::Provider::ISettingsGlobal;
using Elastos::Droid::Provider::CSettingsGlobal;
using Elastos::Droid::Server::IoThread;
using Elastos::Core::StringBuilder;
using Elastos::Core::StringUtils;
using Elastos::Utility::Logging::Logger;
using Elastos::Net::CURL;
using Elastos::Net::IProxyHelper;
using Elastos::Net::CProxyHelper;
using Elastos::IO::IInputStream;
using Libcore::IO::IStreams;
using Libcore::IO::CStreams;
namespace Elastos {
namespace Droid {
namespace Server {
namespace Connectivity {
const String PacManager::PAC_PACKAGE("com.android.pacprocessor");
const String PacManager::PAC_SERVICE("com.android.pacprocessor.PacService");
const String PacManager::PAC_SERVICE_NAME("com.android.net.IProxyService");
const String PacManager::PROXY_PACKAGE("com.android.proxyhandler");
const String PacManager::PROXY_SERVICE("com.android.proxyhandler.ProxyService");
const String PacManager::TAG("PacManager");
const String PacManager::ACTION_PAC_REFRESH("android.net.proxy.PAC_REFRESH");
const String PacManager::DEFAULT_DELAYS("8 32 120 14400 43200");
const Int32 PacManager::DELAY_1 = 0;
const Int32 PacManager::DELAY_4 = 3;
const Int32 PacManager::DELAY_LONG = 4;
/** Keep these values up-to-date with ProxyService.java */
const String PacManager::KEY_PROXY("keyProxy");
//============================================================================
// PacManager::PacDownloaderRunnable
//============================================================================
PacManager::PacDownloaderRunnable::PacDownloaderRunnable(
/* [in] */ PacManager* host)
: mHost(host)
{}
ECode PacManager::PacDownloaderRunnable::Run()
{
String file;
Object& lockObj = mHost->mProxyLock;
{ AutoLock syncLock(lockObj);
AutoPtr<IUriHelper> helper;
CUriHelper::AcquireSingleton((IUriHelper**)&helper);
AutoPtr<IUri> emptyUri;
helper->GetEMPTY((IUri**)&emptyUri);
if (Object::Equals(emptyUri, mHost->mPacUrl)) return NOERROR;
ECode ec = mHost->Get(mHost->mPacUrl, &file);
if (ec == (ECode)E_IO_EXCEPTION) {
file = String(NULL);
Logger::W("PacManager", "Failed to load PAC file: IOException");
}
}
if (file != NULL) {
Object& lockObj = mHost->mProxyLock;
{ AutoLock syncLock(lockObj);
if (!file.Equals(mHost->mCurrentPac)) {
mHost->SetCurrentProxyScript(file);
}
}
mHost->mHasDownloaded = TRUE;
mHost->SendProxyIfNeeded();
mHost->LongSchedule();
}
else {
mHost->Reschedule();
}
return NOERROR;
}
//============================================================================
// PacManager::PacRefreshIntentReceiver
//============================================================================
PacManager::PacRefreshIntentReceiver::PacRefreshIntentReceiver(
/* [in] */ PacManager* host)
: mHost(host)
{}
ECode PacManager::PacRefreshIntentReceiver::OnReceive(
/* [in] */ IContext* context,
/* [in] */ IIntent* intent)
{
Boolean bval;
IoThread::GetHandler()->Post(mHost->mPacDownloader, &bval);
return NOERROR;
}
//============================================================================
// PacManager::ServiceConnection
//============================================================================
CAR_INTERFACE_IMPL(PacManager::ServiceConnection, Object, IServiceConnection)
PacManager::ServiceConnection::ServiceConnection(
/* [in] */ PacManager* host)
: mHost(host)
{}
ECode PacManager::ServiceConnection::OnServiceDisconnected(
/* [in] */ IComponentName* component)
{
Object& lockObj = mHost->mProxyLock;
{ AutoLock syncLock(lockObj);
assert(0 && "TODO");
// mHost->mProxyService = NULL;
}
return NOERROR;
}
ECode PacManager::ServiceConnection::OnServiceConnected(
/* [in] */ IComponentName* component,
/* [in] */ IBinder* binder)
{
Object& lockObj = mHost->mProxyLock;
{ AutoLock syncLock(lockObj);
Logger::D("PacManager::ServiceConnection", "Adding service %s %s",
PacManager::PAC_SERVICE_NAME.string(), TO_CSTR(binder));
AutoPtr<IServiceManager> srvMrg;
CServiceManager::AcquireSingleton((IServiceManager**)&srvMrg);
srvMrg->AddService(PacManager::PAC_SERVICE_NAME, binder);
assert(0 && "TODO");
// mHost->mProxyService = IIProxyService::Probe(binder);
// if (mHost->mProxyService == NULL) {
// Logger::E("PacManager::ServiceConnection", "No proxy service");
// }
// else {
// ECode ec = mHost->mProxyService->StartPacSystem();
// if (ec == (ECode)E_REMOTE_EXCEPTION) {
// Logger::E("PacManager::ServiceConnection", "Unable to reach ProxyService - PAC will not be started");
// }
// Boolean bval;
// IoThread::GetHandler()->Post(mHost->mPacDownloader, &bval);
// }
}
return NOERROR;
}
//============================================================================
// PacManager::ProxyConnection
//============================================================================
CAR_INTERFACE_IMPL(PacManager::ProxyConnection, Object, IServiceConnection)
PacManager::ProxyConnection::ProxyConnection(
/* [in] */ PacManager* host)
: mHost(host)
{}
ECode PacManager::ProxyConnection::OnServiceDisconnected(
/* [in] */ IComponentName* component)
{
return NOERROR;
}
ECode PacManager::ProxyConnection::OnServiceConnected(
/* [in] */ IComponentName* component,
/* [in] */ IBinder* binder)
{
assert(0 && "TODO");
// AutoPtr<IIProxyCallback> callbackService = IIProxyCallback::Probe(binder);
// if (callbackService.Get() != NULL) {
// callbackService.getProxyPort(new IProxyPortListener.Stub() {
// //@Override
// public CARAPI SetProxyPort(
// /* [in] */ Int32 port)
// {
// if (mLastPort != -1) {
// // Always need to send if port changed
// mHost->mHasSentBroadcast = FALSE;
// }
// mLastPort = port;
// if (port != -1) {
// Logger::D("PacManager::ProxyConnection", "Local proxy is bound on %d", port);
// mHost->SendProxyIfNeeded();
// } else {
// Logger::E(TAG, "Received invalid port from Local Proxy,"
// " PAC will not be operational");
// }
// }
// });
// }
return NOERROR;
}
//============================================================================
// PacManager
//============================================================================
PacManager::PacManager(
/* [in] */ IContext* context,
/* [in] */ IHandler* handler,
/* [in] */ Int32 proxyMessage)
: mCurrentDelay(0)
, mLastPort(0)
, mHasSentBroadcast(0)
, mHasDownloaded(0)
, mProxyMessage(0)
{
mContext = context;
mLastPort = -1;
AutoPtr<IUriHelper> helper;
CUriHelper::AcquireSingleton((IUriHelper**)&helper);
AutoPtr<IUri> emptyUri;
helper->GetEMPTY((IUri**)&emptyUri);
mPacUrl = emptyUri;
AutoPtr<IPendingIntentHelper> piHelper;
CPendingIntentHelper::AcquireSingleton((IPendingIntentHelper**)&piHelper);
AutoPtr<IIntent> intent;
CIntent::New(ACTION_PAC_REFRESH, (IIntent**)&intent);
piHelper->GetBroadcast(context, 0, intent, 0, (IPendingIntent**)&mPacRefreshIntent);
AutoPtr<IBroadcastReceiver> receiver = new PacRefreshIntentReceiver(this);
AutoPtr<IIntentFilter> filter;
CIntentFilter::New(ACTION_PAC_REFRESH, (IIntentFilter**)&filter);
AutoPtr<IIntent> stickyIntent;
context->RegisterReceiver(receiver, filter, (IIntent**)&stickyIntent);
mConnectivityHandler = handler;
mProxyMessage = proxyMessage;
}
AutoPtr<IAlarmManager> PacManager::GetAlarmManager()
{
if (mAlarmManager == NULL) {
AutoPtr<IInterface> obj;
mContext->GetSystemService(IContext::ALARM_SERVICE, (IInterface**)&obj);
mAlarmManager = IAlarmManager::Probe(obj);
}
return mAlarmManager;
}
Boolean PacManager::SetCurrentProxyScriptUrl(
/* [in] */ IProxyInfo* proxy)
{
AutoLock lock(this);
AutoPtr<IUriHelper> helper;
CUriHelper::AcquireSingleton((IUriHelper**)&helper);
AutoPtr<IUri> emptyUri;
helper->GetEMPTY((IUri**)&emptyUri);
AutoPtr<IUri> pacFileUri;
proxy->GetPacFileUrl((IUri**)&pacFileUri);
if (!Object::Equals(emptyUri, pacFileUri)) {
Int32 port;
if (Object::Equals(pacFileUri, mPacUrl) && (proxy->GetPort(&port), port) > 0) {
// Allow to send broadcast, nothing to do.
return FALSE;
}
{ AutoLock syncLock(mProxyLock);
mPacUrl = NULL;
proxy->GetPacFileUrl((IUri**)&mPacUrl);
}
mCurrentDelay = DELAY_1;
mHasSentBroadcast = FALSE;
mHasDownloaded = FALSE;
GetAlarmManager()->Cancel(mPacRefreshIntent);
Bind();
return TRUE;
}
else {
GetAlarmManager()->Cancel(mPacRefreshIntent);
{ AutoLock syncLock(mProxyLock);
mPacUrl = emptyUri;
mCurrentPac = NULL;
assert(0 && "TODO");
// if (mProxyService != NULL) {
// ECode ec = mProxyService->StopPacSystem();
// if (ec == (ECode)E_REMOTE_EXCEPTION) {
// Logger::W(TAG, "Failed to stop PAC service");
// }
// Unbind();
// }
}
}
return FALSE;
}
ECode PacManager::Get(
/* [in] */ IUri* pacUri,
/* [out] */ String* result)
{
VALIDATE_NOT_NULL(result)
*result = String(NULL);
String str = Object::ToString(pacUri);
AutoPtr<IURL> url;
CURL::New(str, (IURL**)&url);
AutoPtr<IURLConnection> urlConnection;
AutoPtr<IProxyHelper> helper;
CProxyHelper::AcquireSingleton((IProxyHelper**)&helper);
AutoPtr<Elastos::Net::IProxy> noProxy;
helper->GetNO_PROXY((Elastos::Net::IProxy**)&noProxy);
FAIL_RETURN(url->OpenConnection(noProxy, (IURLConnection**)&urlConnection))
AutoPtr<IInputStream> is;
urlConnection->GetInputStream((IInputStream**)&is);
AutoPtr<IStreams> streams;
CStreams::AcquireSingleton((IStreams**)&streams);
AutoPtr< ArrayOf<Byte> > bytes;
streams->ReadFully(is, (ArrayOf<Byte>**)&bytes);
String readStr(*bytes);
*result = readStr;
return NOERROR;
}
Int32 PacManager::GetNextDelay(
/* [in] */ Int32 currentDelay)
{
if (++currentDelay > DELAY_4) {
return DELAY_4;
}
return currentDelay;
}
void PacManager::LongSchedule()
{
mCurrentDelay = DELAY_1;
SetDownloadIn(DELAY_LONG);
}
void PacManager::Reschedule()
{
mCurrentDelay = GetNextDelay(mCurrentDelay);
SetDownloadIn(mCurrentDelay);
}
String PacManager::GetPacChangeDelay()
{
AutoPtr<IContentResolver> cr;
mContext->GetContentResolver((IContentResolver**)&cr);
/** Check system properties for the default value then use secure settings value, if any. */
AutoPtr<ISystemProperties> sysProp;
CSystemProperties::AcquireSingleton((ISystemProperties**)&sysProp);
StringBuilder sb("conn.");
sb += ISettingsGlobal::PAC_CHANGE_DELAY;
String defaultDelay;
sysProp->Get(sb.ToString(), DEFAULT_DELAYS, &defaultDelay);
AutoPtr<ISettingsGlobal> sg;
CSettingsGlobal::AcquireSingleton((ISettingsGlobal**)&sg);
String val;
sg->GetString(cr, ISettingsGlobal::PAC_CHANGE_DELAY, &val);
return (val.IsNull()) ? defaultDelay : val;
}
Int64 PacManager::GetDownloadDelay(
/* [in] */ Int32 delayIndex)
{
String delay = GetPacChangeDelay();
AutoPtr<ArrayOf<String> > list;
StringUtils::Split(delay, " ", (ArrayOf<String>**)&list);
if (delayIndex < list->GetLength()) {
String str = (*list)[delayIndex];
return StringUtils::ParseInt64(str);
}
return 0;
}
void PacManager::SetDownloadIn(
/* [in] */ Int32 delayIndex)
{
Int64 delay = GetDownloadDelay(delayIndex);
Int64 timeTillTrigger = 1000 * delay + SystemClock::GetElapsedRealtime();
GetAlarmManager()->Set(IAlarmManager::ELAPSED_REALTIME, timeTillTrigger, mPacRefreshIntent);
}
Boolean PacManager::SetCurrentProxyScript(
/* [in] */ const String& script)
{
assert(0 && "TODO");
// if (mProxyService == NULL) {
// Logger::E(TAG, "SetCurrentProxyScript: no proxy service");
// return FALSE;
// }
// // try {
// ECode ec = mProxyService->SetPacFile(script);
// if (ec == (ECode)E_REMOTE_EXCEPTION) {
// Logger::E(TAG, "Unable to set PAC file");
// return FALSE;
// }
mCurrentPac = script;
return TRUE;
}
void PacManager::Bind()
{
if (mContext == NULL) {
Logger::E(TAG, "No context for binding");
return;
}
AutoPtr<IIntent> intent;
CIntent::New((IIntent**)&intent);
intent->SetClassName(PAC_PACKAGE, PAC_SERVICE);
// Already bound no need to Bind again.
if ((mProxyConnection != NULL) && (mConnection != NULL)) {
if (mLastPort != -1) {
AutoPtr<IProxyInfo> info;
CProxyInfo::New(mPacUrl, mLastPort, (IProxyInfo**)&info);
SendPacBroadcast(info);
} else {
Logger::E(TAG, "Received invalid port from Local Proxy,"
" PAC will not be operational");
}
return;
}
Boolean bval;
mConnection = new ServiceConnection(this);
mContext->BindService(intent, mConnection,
IContext::BIND_AUTO_CREATE | IContext::BIND_NOT_FOREGROUND | IContext::BIND_NOT_VISIBLE, &bval);
AutoPtr<IIntent> proxyIntent;
CIntent::New((IIntent**)&proxyIntent);
proxyIntent->SetClassName(PROXY_PACKAGE, PROXY_SERVICE);
mProxyConnection = new ServiceConnection(this);
mContext->BindService(proxyIntent, mProxyConnection,
IContext::BIND_AUTO_CREATE | IContext::BIND_NOT_FOREGROUND | IContext::BIND_NOT_VISIBLE, &bval);
}
void PacManager::Unbind()
{
if (mConnection != NULL) {
mContext->UnbindService(mConnection);
mConnection = NULL;
}
if (mProxyConnection != NULL) {
mContext->UnbindService(mProxyConnection);
mProxyConnection = NULL;
}
assert(0 && "TODO");
// mProxyService = NULL;
mLastPort = -1;
}
void PacManager::SendPacBroadcast(
/* [in] */ IProxyInfo* proxy)
{
AutoPtr<IMessage> msg;
mConnectivityHandler->ObtainMessage(mProxyMessage, proxy, (IMessage**)&msg);
Boolean bval;
mConnectivityHandler->SendMessage(msg, &bval);
}
void PacManager::SendProxyIfNeeded()
{
AutoLock lock(this);
if (!mHasDownloaded || (mLastPort == -1)) {
return;
}
if (!mHasSentBroadcast) {
AutoPtr<IProxyInfo> info;
CProxyInfo::New(mPacUrl, mLastPort, (IProxyInfo**)&info);
SendPacBroadcast(info);
mHasSentBroadcast = TRUE;
}
}
} // Connectivity
} // Server
} // Droid
} // Elastos
| 32.774194 | 120 | 0.616779 | [
"object"
] |
3d989dbe54fe1ecef0846c8ed788457bd2243c9b | 225 | cpp | C++ | AtCoder/abc205/a/main.cpp | H-Tatsuhiro/Com_Pro-Cpp | fd79f7821a76b11f4a6f83bbb26a034db577a877 | [
"MIT"
] | null | null | null | AtCoder/abc205/a/main.cpp | H-Tatsuhiro/Com_Pro-Cpp | fd79f7821a76b11f4a6f83bbb26a034db577a877 | [
"MIT"
] | 1 | 2021-10-19T08:47:23.000Z | 2022-03-07T05:23:56.000Z | AtCoder/abc205/a/main.cpp | H-Tatsuhiro/Com_Pro-Cpp | fd79f7821a76b11f4a6f83bbb26a034db577a877 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cmath>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
long double a, b; cin >> a >> b;
long double ans = ((b * 1.0) / 100) * a * 1.0;
cout << ans << endl;
}
| 20.454545 | 50 | 0.577778 | [
"vector"
] |
3d9df380c1b9c9ea20919f3af9c8c6ddebdb98e7 | 14,665 | cpp | C++ | Server/Servers/NavigatorServer/src/OneSearchBinaryResult.cpp | wayfinder/Wayfinder-Server | a688546589f246ee12a8a167a568a9c4c4ef8151 | [
"BSD-3-Clause"
] | 4 | 2015-08-17T20:12:22.000Z | 2020-05-30T19:53:26.000Z | Server/Servers/NavigatorServer/src/OneSearchBinaryResult.cpp | wayfinder/Wayfinder-Server | a688546589f246ee12a8a167a568a9c4c4ef8151 | [
"BSD-3-Clause"
] | null | null | null | Server/Servers/NavigatorServer/src/OneSearchBinaryResult.cpp | wayfinder/Wayfinder-Server | a688546589f246ee12a8a167a568a9c4c4ef8151 | [
"BSD-3-Clause"
] | null | null | null | /*
Copyright (c) 1999 - 2010, Vodafone Group Services Ltd
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 Vodafone Group Services Ltd 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 "OneSearchBinaryResult.h"
#include "STLUtility.h"
#include "STLStringUtility.h"
#include "SearchParserHandler.h"
#include "SearchMatch.h"
#include "ItemInfoPacket.h"
#include "NavSearchHandler.h"
#include "ItemDetailEnums.h"
namespace {
/**
* Class for holding info about a Area
*/
class Area {
public:
Area() {};
Area( const MC2String& idStr) : id( idStr) {};
int16 type;
MC2String name;
MC2String id;
bool operator==( const MC2String& other ) const{
return id == other;
}
bool operator<( const Area& other ) const {
return id < other.id;
}
};
// Gets the size of the fixed
int32 getMatchTableFixedFieldsSize() {
return sizeof( int32 ) + // nameIndex
sizeof( int32 ) + // idIndex
sizeof( int32 ) + // locationIndex
sizeof( int32 ) + // lat
sizeof( int32 ) + // lon
sizeof( int8 ) + // type
sizeof( int16 ) + // subtype
sizeof( int32 ) + // categoryImageIndex
sizeof( int32 ) + // providerImageIndex
sizeof( int32 ) + // brandImageIndex
sizeof( int8 ) + // flags
sizeof( int8 ) + // nbrCategories
sizeof( int8 ) + // nbrAreas
sizeof( int8 ); // nbrInfoItems
}
/**
* Get the name for the match, companies have street name in name.
*/
MC2String getMatchName( const VanillaMatch& match ) {
MC2String name( match.getName() );
if ( match.getType() == SEARCH_COMPANIES ) {
const VanillaCompanyMatch& poi =
static_cast< const VanillaCompanyMatch& >( match );
if ( ! poi.getCleanCompanyName().empty() ) {
name = poi.getCleanCompanyName();
}
}
return name;
}
/**
* Gets all strings and puts them in the stringMap, setting all indexes to zero.
* Adds areas to the map and calculates size of item info table and matches
* table.
*/
void getStringsAreasAndSizes( map<MC2String, int32>& stringMap,
map<Area, int32>& areas,
int32& nbrItemInfos,
int32& matchTableSize,
SearchParserHandler& searchHandler,
ResultVector::const_iterator matchesBegin,
ResultVector::const_iterator matchesEnd ) {
nbrItemInfos = 0;
matchTableSize = 0;
for( ResultVector::const_iterator it = matchesBegin;
it != matchesEnd; ++it ) {
const VanillaMatch* match = *it;
// Add main strings
stringMap[ getMatchName( *match ) ] = 0;
stringMap[ match->matchToString() ] = 0;
stringMap[ match->getLocationName() ] = 0;
stringMap[ searchHandler.getCategoryImageName( *match ) ] = 0;
stringMap[ searchHandler.getProviderImageName( *match ) ] = 0;
stringMap[ searchHandler.getBrandImageName( *match ) ] = 0;
matchTableSize += getMatchTableFixedFieldsSize();
// Get category list size
if ( match->getType() == SEARCH_COMPANIES ) {
const VanillaCompanyMatch& poi =
static_cast< const VanillaCompanyMatch& >( *match );
matchTableSize += poi.getCategories().size() * 4;
}
// Add string for areas
for ( uint32 i = 0 ; i < match->getNbrRegions() ; ++i ) {
VanillaRegionMatch* regMatch = match->getRegion( i );
if ( regMatch->getType() ) {
Area a;
a.type = regMatch->getType();
a.id = MC2String( regMatch->matchToString() );
a.name = regMatch->getName();
stringMap[ a.id ] = 0;
stringMap[ a.name ] = 0;
areas[ a ] = 0;
matchTableSize += 4;
}
}
// Add strings for item info
ItemInfoData::ItemInfoEntryCont::const_iterator it;
ItemInfoData::ItemInfoEntryCont::const_iterator endIt =
match->getItemInfos().end();
for ( it = match->getItemInfos().begin() ; it != endIt ; ++it ) {
stringMap[ it->getKey() ] = 0;
stringMap[ it->getVal() ] = 0;
nbrItemInfos++;
matchTableSize += 4;
}
}
}
/**
* Calculates the size of the string table, given all the strings.
*/
int calcStringTableSize( const map<MC2String, int32>& stringMap ) {
int totalStringLength = 0;
// Sum up the sizes of all strings
for ( map<MC2String, int32>::const_iterator itr = stringMap.begin();
itr != stringMap.end(); ++itr) {
totalStringLength += (*itr).first.size();
}
// Each string has 3 bytes for length indicator + zero terminator
return stringMap.size()*3 + totalStringLength;
}
/**
* Creates the string table and sets the indexes to each string
* in the string map.
*/
void writeStringTable( map<MC2String, int32>& stringMap,
DataBuffer* stringTable ) {
for ( map<MC2String, int32>::iterator itr = stringMap.begin();
itr != stringMap.end(); ++itr) {
// The position should be the position of the string, not of the
// length indicator
(*itr).second = stringTable->getCurrentOffset() + sizeof( uint16 );
// Write length indicator
stringTable->writeNextBAShort( (*itr).first.size() );
// Write string content
stringTable->writeNextString( (*itr).first.c_str() );
}
}
/**
* Given a string, this function returns its index into the string table.
* Since the stringMap should contain all strings, there's a bug somewhere
* if the string isn't available, so we assert false.
*/
int32 getStringIndex( const map<MC2String, int32>& stringMap,
const MC2String& str ) {
map<MC2String, int32>::const_iterator itr = stringMap.find( str );
if ( itr == stringMap.end() ) {
// Should never happen
MC2_ASSERT( false );
return 0;
}
else {
return (*itr).second;
}
}
/**
* Creates the Area table and sets the indexes to correct values
*/
void writeAreaTable( map<Area, int32>& areaMap,
const map<MC2String, int32>& stringMap,
DataBuffer* areaTable ) {
for ( map<Area, int32>::iterator itr = areaMap.begin();
itr != areaMap.end(); ++itr) {
// Set index pos
(*itr).second = areaTable->getCurrentOffset();
// Write type
areaTable->writeNextBAShort( NavSearchHandler::mc2TypeToNavRegionType(
(*itr).first.type ) );
// Write name index
areaTable->writeNextBALong( getStringIndex( stringMap,
(*itr).first.name ) );
// Write id index
areaTable->writeNextBALong( getStringIndex( stringMap,
(*itr).first.id ) );
}
}
/**
* Get index for area with id str
*/
int32 getAreaIndex( const map<Area, int32>& areaMap,
const MC2String& str ) {
map<Area, int32>::const_iterator itr = areaMap.find( str );
if ( itr == areaMap.end() ) {
// Should never happen
MC2_ASSERT( false );
return 0;
}
else {
return (*itr).second;
}
}
typedef vector<uint16> Categories;
/**
* Create the matchesTable and itemInfoTable
*/
void writeDataTables( const map<MC2String, int32>& stringMap,
const map<Area, int32>& areas,
SearchParserHandler& searchHandler,
ResultVector::const_iterator matchesBegin,
ResultVector::const_iterator matchesEnd,
OneSearchUtils::BinarySearchResult* format) {
DataBuffer* matchBuffer = format->m_matchesTable.get();
DataBuffer* itemInfoBuffer = format->m_infoItemTable.get();
for( ResultVector::const_iterator it = matchesBegin;
it != matchesEnd; ++it ) {
const VanillaMatch& match = *(*it);
// Write name and id indexes
matchBuffer->writeNextBALong( getStringIndex( stringMap,
getMatchName( match ) ) );
matchBuffer->writeNextBALong( getStringIndex( stringMap,
match.matchToString() ) );
// Write location
matchBuffer->writeNextBALong( getStringIndex( stringMap,
match.getLocationName() ) );
matchBuffer->writeNextBALong( match.getCoords().lat );
matchBuffer->writeNextBALong( match.getCoords().lon );
// Write match type and sub type
matchBuffer->writeNextBAByte(
NavSearchHandler::mc2TypeToNavItemType( match.getType() ) );
matchBuffer->writeNextBAShort(
NavSearchHandler::mc2ItemTypeToNavSubType(
ItemTypes::itemType( match.getItemSubtype() ) ) );
// Write the icons
matchBuffer->writeNextBALong(
getStringIndex( stringMap,
searchHandler.getCategoryImageName( match ) ) );
matchBuffer->writeNextBALong(
getStringIndex( stringMap,
searchHandler.getProviderImageName( match ) ) );
matchBuffer->writeNextBALong(
getStringIndex( stringMap,
searchHandler.getBrandImageName( match ) ) );
// Write flags
// Aditional info is currently the only flag
matchBuffer->writeNextBAByte( match.getAdditionalInfoExists() );
// Get this hits categories count
int32 hitCatCount = 0;
if ( match.getType() == SEARCH_COMPANIES ) {
const VanillaCompanyMatch& poi =
static_cast< const VanillaCompanyMatch& >( match );
hitCatCount = poi.getCategories().size();
}
// Write number of categories
matchBuffer->writeNextBAByte( hitCatCount );
// Write number of areas
matchBuffer->writeNextBAByte( match.getNbrRegions() );
// Write number of info fields
matchBuffer->writeNextBAByte( match.getItemInfos().size() );
// Write the categories
if ( match.getType() == SEARCH_COMPANIES ) {
const VanillaCompanyMatch& poi =
static_cast< const VanillaCompanyMatch& >( match );
const Categories& ids = poi.getCategories();
for( Categories::const_iterator it = ids.begin();
it!= ids.end(); ++it ) {
matchBuffer->writeNextBALong( *it );
}
}
// Write the area offsets in match buffer
for ( uint32 i = 0 ; i < match.getNbrRegions() ; ++i ) {
matchBuffer->writeNextBALong(
getAreaIndex( areas, match.getRegion( i )->matchToString() ) );
}
// Write the detail infos
ItemInfoData::ItemInfoEntryCont::const_iterator it;
ItemInfoData::ItemInfoEntryCont::const_iterator endIt =
match.getItemInfos().end();
for ( it = match.getItemInfos().begin() ; it != endIt ; ++it ) {
// Write offset into match buffer
matchBuffer->writeNextBALong( itemInfoBuffer->getCurrentOffset() );
// Write data into item info buffer
itemInfoBuffer->writeNextBAShort(
ItemDetailEnums::poiInfoToPoiDetail( it->getInfoType() ) );
itemInfoBuffer->writeNextBAByte(
ItemDetailEnums::getContentTypeForPoiInfo( it->getInfoType() ) );
itemInfoBuffer->writeNextBALong(
getStringIndex( stringMap, it->getKey() ) );
itemInfoBuffer->writeNextBALong(
getStringIndex( stringMap, it->getVal() ) );
}
}
}
}
namespace OneSearchUtils {
void serializeResults( ResultVector::const_iterator matchesBegin,
ResultVector::const_iterator matchesEnd,
SearchParserHandler& searchHandler,
BinarySearchResult* format) {
map<MC2String, int32> stringMap;
map<Area, int32> areas;
int32 nbrOfItemInfos = 0;
int32 matchTableSize = 0;
// Get string table and other data
getStringsAreasAndSizes( stringMap, areas, nbrOfItemInfos, matchTableSize,
searchHandler, matchesBegin, matchesEnd );
// Write down the string table
int stringTableSize = calcStringTableSize( stringMap );
format->m_stringTable.reset( new DataBuffer( stringTableSize ) );
writeStringTable( stringMap, format->m_stringTable.get() );
// Write the area table
const uint32 areaTableSize = areas.size() *
( sizeof( int16 ) + 2 * sizeof( uint32 ) );
format->m_areaTable.reset( new DataBuffer( areaTableSize, true ) );
writeAreaTable( areas, stringMap, format->m_areaTable.get() );
// Write matches and info field tables
const uint32 infoItemTableSize = nbrOfItemInfos *
( sizeof( int16 ) + sizeof( int8 ) + 2 * sizeof( int32 ) );
format->m_infoItemTable.reset( new DataBuffer( infoItemTableSize, true ) );
format->m_matchesTable.reset( new DataBuffer( matchTableSize ) );
writeDataTables( stringMap, areas, searchHandler, matchesBegin, matchesEnd,
format );
// Reset the buffers
format->m_stringTable->reset();
format->m_areaTable->reset();
format->m_infoItemTable->reset();
format->m_matchesTable->reset();
}
}
| 35.768293 | 755 | 0.621752 | [
"vector"
] |
3da8aee40c278f0f1129c4bd258ba83b91a7f4cd | 4,747 | cpp | C++ | examples/neural_net.cpp | PetterS/spii | 98c5847223d7c3febea5a1aac6f4978dfef207ec | [
"BSD-2-Clause"
] | 35 | 2015-03-03T16:21:40.000Z | 2020-09-16T08:02:12.000Z | examples/neural_net.cpp | nashdingsheng/spii | 3130d0dc43af8ae79d1fdf315a8b5fc05fe00321 | [
"BSD-2-Clause"
] | 2 | 2015-07-16T14:41:55.000Z | 2018-04-09T19:27:22.000Z | examples/neural_net.cpp | nashdingsheng/spii | 3130d0dc43af8ae79d1fdf315a8b5fc05fe00321 | [
"BSD-2-Clause"
] | 11 | 2015-09-21T23:09:37.000Z | 2021-07-24T20:20:30.000Z | // Petter Strandmark 2013.
//
// Trains a small artificial neural network using L-BFGS.
// Learns the xor function from two inputs to one output
// variable.
//
// This example illustrates how functions of matrices can
// be optimized using automatic differentiations.
#include <iostream>
#include <random>
#include <stdexcept>
#include <spii/auto_diff_term.h>
#include <spii/constrained_function.h>
#include <spii/solver.h>
template<typename R, int rows>
void sigmoid_inplace(Eigen::Matrix<R, rows, 1>& v)
{
using std::exp;
for (int i = 0; i < rows; ++i) {
v[i] = 1.0 / (1.0 + exp(-v[i]));
}
}
template<typename R, int n_input, int n_hidden, int n_output>
Eigen::Matrix<R, n_output, 1> neural_network_classify(const Eigen::Matrix<double, n_input, 1>& input,
const R* const W1_data,
const R* const W2_data)
{
Eigen::Map<const Eigen::Matrix<R, n_hidden, n_input>> W1(W1_data);
Eigen::Map<const Eigen::Matrix<R, n_output, n_hidden>> W2(W2_data);
Eigen::Matrix<R, n_input, 1> input_R;
// input.cast<R>() does not work on GCC 4.8.2...
for (int i = 0; i < n_input; ++i) {
input_R(i) = input(i);
}
Eigen::Matrix<R, n_hidden, 1> hidden = W1 * input_R;
sigmoid_inplace(hidden);
Eigen::Matrix<R, n_output, 1> output = W2 * hidden;
sigmoid_inplace(output);
return output;
}
template<int n_input, int n_hidden, int n_output>
class NeuralNetQuadraticLoss
{
public:
NeuralNetQuadraticLoss(const Eigen::Matrix<double, n_input, 1>& input_,
const Eigen::Matrix<double, n_output, 1>& desired_output_)
: input{input_},
desired_output{desired_output_}
{ }
template<typename R>
R operator()(const R* const W1_data, const R* const W2_data) const
{
// Classify the input using the neural network given
// as input to this function.
auto output = neural_network_classify<R, n_input, n_hidden, n_output>(input, W1_data, W2_data);
// Compute the squared error.
R squared_sum = 0.0;
for (int i = 0; i < n_output; ++i) {
auto delta = output[i] - R(desired_output[i]);
squared_sum += delta*delta;
}
return squared_sum;
}
private:
const Eigen::Matrix<double, n_input, 1> input;
const Eigen::Matrix<double, n_output, 1> desired_output;
};
// Number of nodes in the three-layer network.
const int n_input = 2;
const int n_hidden = 4;
const int n_output = 1;
int main_function()
{
using namespace spii;
using namespace std;
vector<double> W1(n_hidden * n_input, 1.0);
vector<double> W2(n_output * n_hidden, 0.0);
std::mt19937_64 engine;
std::normal_distribution<double> rand(0.0, 1.0);
for (auto& w: W1) {
w = rand(engine);
}
for (auto& w : W2) {
w = rand(engine);
}
Function function;
Eigen::Matrix<double, n_input, 1> input;
Eigen::Matrix<double, n_output, 1> output;
typedef NeuralNetQuadraticLoss<n_input, n_hidden, n_output> NeuralNet;
typedef AutoDiffTerm<NeuralNet, n_hidden * n_input, n_output * n_hidden> NeuralNetTerm;
vector<vector<double>> training = {
{0, 0, 0},
{0, 1, 1}, // {input1, input2, output1}
{1, 0, 1},
{1, 1, 0},
};
for (const auto& example: training) {
for (double eps1 = -0.1; eps1 <= 0.1; eps1 += 0.02) {
for (double eps2 = -0.1; eps2 <= 0.1; eps2 += 0.02) {
// Do not traing on exactly on (0, 0), ... (1, 1)
// Only on slight permutations.
if (eps1 == 0 && eps2 == 0)
continue;
input[0] = example[0] + eps1;
input[1] = example[1] + eps2;
//input[2] = 1.0;
output[0] = example[2];
auto term = make_shared<NeuralNetTerm>(input, output);
function.add_term(term, W1.data(), W2.data());
}
}
}
cout << "Using " << function.get_number_of_terms() << " training examples." << endl;
LBFGSSolver solver;
solver.maximum_iterations = 300;
SolverResults results;
solver.solve(function, &results);
cout << results << endl << endl;
// Show the resulting matrices.
Eigen::Map<const Eigen::Matrix<double, n_hidden, n_input>> W1_m(W1.data());
Eigen::Map<const Eigen::Matrix<double, n_output, n_hidden>> W2_m(W2.data());
cout << "Input --> hidden:" << endl << W1_m << endl << endl;
cout << "Hidden --> output:" << endl << W2_m << endl << endl;
auto test = training;
test.push_back({0.5, 0.5});
// Print a few classifications results.
for (const auto& example : test) {
input[0] = example[0];
input[1] = example[1];
output = neural_network_classify<double, n_input, n_hidden, n_output>(input, W1.data(), W2.data());
cout << "(" << input[0] << ", " << input[1] << ") --> " << output[0] << endl;
}
return 0;
}
int main()
{
try {
return main_function();
}
catch (std::exception& e) {
std::cerr << "Exception: " << e.what() << std::endl;
}
}
| 27.760234 | 101 | 0.641247 | [
"vector"
] |
3daab25b0ae3b7285e87eb27169f993e3e49550b | 1,316 | cpp | C++ | src/Scene.cpp | Dav-v/Rha | 77fa838ea0830bd1f335349dd88d0a7005b4a921 | [
"Apache-2.0"
] | null | null | null | src/Scene.cpp | Dav-v/Rha | 77fa838ea0830bd1f335349dd88d0a7005b4a921 | [
"Apache-2.0"
] | null | null | null | src/Scene.cpp | Dav-v/Rha | 77fa838ea0830bd1f335349dd88d0a7005b4a921 | [
"Apache-2.0"
] | null | null | null | /*
* Author: Davide Viero - dviero42@gmail.com
* Rha raytracer
* 2019
* License: see LICENSE file
*
*/
#include "scene.h"
Scene::Scene(
float near,
float left,
float right,
float bottom,
float top,
glm::vec3 background,
glm::vec3 ambient,
std::vector<SceneObject *> objects,
std::vector<Light *> lights,
unsigned int rX,
unsigned int rY,
std::string outputFile
)
{
this->near = near;
this->left = left;
this->right = right;
this->bottom = bottom;
this->top = top;
this->background = background;
this->ambient = ambient;
this->objects = objects;
this->lights = lights;
this->rX = rX;
this->rY = rY;
this->outputFile = outputFile;
}
float Scene::getNear()
{
return near;
}
float Scene::getLeft()
{
return left;
}
float Scene::getRight()
{
return right;
}
float Scene::getBottom()
{
return bottom;
}
float Scene::getTop()
{
return top;
}
glm::vec3 Scene::getBackground()
{
return background;
}
glm::vec3 Scene::getAmbient()
{
return ambient;
}
std::vector<SceneObject *> Scene::getObjects()
{
return objects;
}
std::vector<Light *> Scene::getLights()
{
return lights;
}
unsigned int Scene::getRX()
{
return rX;
}
unsigned int Scene::getRY()
{
return rY;
}
std::string Scene::getOutFile()
{
return outputFile;
} | 14.954545 | 46 | 0.641337 | [
"vector"
] |
3daae607723be21fedf12b9f44bf4b33eedf607c | 77,878 | cpp | C++ | jni/wprint/plugins/genPCLm/src/genPCLm.cpp | ibevilinc/WFDSPrintPlugin | 63426e7c6d7c038585bf9a8d5661655af28f8e40 | [
"Apache-2.0"
] | 5 | 2015-03-25T11:50:49.000Z | 2020-08-25T09:52:27.000Z | jni/wprint/plugins/genPCLm/src/genPCLm.cpp | ibevilinc/WFDSPrintPlugin | 63426e7c6d7c038585bf9a8d5661655af28f8e40 | [
"Apache-2.0"
] | 1 | 2015-03-25T06:27:27.000Z | 2015-03-25T11:20:00.000Z | jni/wprint/plugins/genPCLm/src/genPCLm.cpp | ibevilinc/WFDSPrintPlugin | 63426e7c6d7c038585bf9a8d5661655af28f8e40 | [
"Apache-2.0"
] | 8 | 2015-02-21T10:48:53.000Z | 2021-11-26T06:59:23.000Z | /*
(c) Copyright 2013 Hewlett-Packard Development Company, L.P.
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.
*/
/*
(c) Copyright 2013 Hewlett-Packard Development Company, L.P.
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.
*/
/**********************************************************************************************
* File: genPCLm.c
*
* Author(s): Steve Claiborne
*
* To Do: Status
* - Error generation
* - Backside duplex flip/mirror capability
* - Opportunity to scale input image to device resolution
* - Support Adobe RGB color space
* - Skip white strips
*
*==== COMPLETED TASKS ===========================================================
* - Generate output file name to reflect media and input params 12/20/2010
* - Support 300 device resolution 12/17/2010
* - Support 1200 device resolution 12/17/2010
* - Media size support 12/17/2010
* - Other compression technologies: delta, taos 11/17/2010
* - zlib 11/17/2010
* - RLE (Hi) 12/13/2010
* - Margin support N/A?
* - Strip height programmability 11/18/2010
* - Multiple pages 11/23/2010
* - Source image scaling 11/09/2010
* - Debug option 11/09/2010
* - Add comment job ticket 12/02/2010
* - Added grayscale 12/20/2010
* - Scaled source width to full-width of media 12/17/2010
* - Implemented PCLmGen OO Interface 02/10/2011
* - AdobeRGB 02/01/2011
* - Support odd-page duplex for InkJet 02/01/2011
* - JPEG markers to reflect resolution 02/16/2011
* - JPEG markers for strip height are stuck at 16 02/16/2011
* - KidsArray, xRefTable, KidsString, pOutBuffer are static sized 02/23/2011
* - Rewrite the logic for handling the **bufPtr 02/24/2011
* - Support short-edge duplex 03/04/2011
* - Need to implement error handling correctly 03/04/2011
* - Fixed adobeRGB multi-job issue 03/08/2011
* - Color convert crash fix 03/08/2011
* - Added abilty to pass debug setting to genPCLm 03/08/2011
* - Added top-margin capabilities to shift image right and down 04/12/2011
* - Add ability to use PNG as input 04/01/2011
**********************************************************************************
* - eliminate the flate_colorspace.bin file
* - Change compression types intra-page
* - Assert that CS does not change
* - Change CS type on page boundaries
* - Implement the media*Offset functionality
* - Leftover lines in a strip are not supported
* - Need to implement debug -> logfile
*
*==== Log of issues / defects ==================================================
* 0.54: programmable strip height 11/23/2010
* 0.53: run-time crash of large source images 11/17/2010
* switched to getopt for parsing 11/17/2010
* 0.55: Add multi-page support 11/23/2010
* 0.56: Fixing /Length issue & removed leading comment 11/29/2010
* 0.57: Fixing scaling and image position issues 12/01/2010
* 0.58: Fixing white space at bottom of page 12/01/2010
* 0.58: Fixing floating point error by switching to dev coordinates 12/02/2010
* 0.59: Added comment job-ticket 12/03/2010
* 0.60: Fixed xref issues that caused performance degradation 12/08/2010
* Added support for -h 0 (generates 1 strip) 12/08/2010
* Added JPEG compression into JFIF header 12/08/2010
* 0.63 Fixed media-padding issue for mediaHeight 12/20/2010
* Fixed media-padding issue for non-600 resolutions 12/20/2010
* 0.65 Added ability to inject blank page for duplex 02/02/2011
*
* Known Issues:
* - Can't convert large images to PDF Fixed 11/18(0.53)
* - 1200 dpi images are rendered to PDF at 600 dpi Fixed 12/17(0.61)
*
**********************************************************************************************/
/**********************************************************************************************
* JPEG image pointers:
* - myImageBuffer: allocated source image buffer
* - destBuffer: current buffer pointer for put_scanline_someplace
*
**********************************************************************************************/
/**********************************************************************************************
* zlib parameters
* compress2 (dest, destLen, source, sourceLen)
* Compresses the source buffer into the destination buffer. sourceLen is the byte
* length of the source buffer. Upon entry, destLen is the total size of the
* destination buffer, which must be at least 0.1% larger than sourceLen plus
* 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
* compress returns Z_OK if success, Z_MEM_ERROR if there was not enough
* memory, Z_BUF_ERROR if there was not enough room in the output buffer,
* Z_STREAM_ERROR if the level parameter is invalid.
* #define Z_OK 0
* #define Z_STREAM_END 1
* #define Z_NEED_DICT 2
* #define Z_ERRNO (-1)
* #define Z_STREAM_ERROR (-2)
* #define Z_DATA_ERROR (-3)
* #define Z_MEM_ERROR (-4)
* #define Z_BUF_ERROR (-5)
* #define Z_VERSION_ERROR (-6)
*
**********************************************************************************************/
#define STAND_ALLONE
#include "PCLmGenerator.h"
#include "media.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <assert.h>
#include <math.h>
#include <zlib.h>
#include <unistd.h>
#include "common_defines.h"
#include "genPCLm.h"
#include "ctype.h"
#include "genPCLm_proto.h"
#include "flate_colorspace.h"
#include "myrle.h"
int RLEEncodeImage(ubyte *inFile, ubyte *outFile, int destSize);
/*
Defines
*/
#define STRIP_HEIGHT 16
#define JPEG_QUALITY 100
#define XREF_SIZE 10000
#define TEMP_BUFF_SIZE 10000000
#define DEFAULT_OUTBUFF_SIZE 64*5120*3*10
#define COMPRESSION_PAD 1024*1000
#define STANDARD_SCALE_FOR_PDF 72.0
#define KID_STRING_SIZE 1000
#define CATALOG_OBJ_NUMBER 1
#define PAGES_OBJ_NUMBER 2
/*
Local Variables
*/
static PCLmSUserSettingsType PCLmSSettings;
/*
Defines
*/
#define rgb_2_gray(r,g,b) (ubyte)(0.299*(double)r+0.587*(double)g+0.114*(double)b)
// Note: this is required for debugging
boolean writeOutputFile(int numBytes, ubyte *ptr);
/********************************************* Helper Routines **************************
Function: shiftStripByLeftMargin
Purpose: To shift the strip image right in the strip buffer by leftMargin pixels
Assumptions: The strip buffer was allocated large enough to handle the shift; if not
then the image data on the right will get clipped.
Details:
We allocate a full strip (height and width), but then only copy numLinesThisCall from the original buffer
to the newly allocated buffer. This pads the strips for JPEG processing.
*/
ubyte *shiftStripByLeftMargin(ubyte *ptrToStrip,sint32 currSourceWidth,sint32 currStripHeight, sint32 numLinesThisCall,
sint32 currMediaWidth, sint32 leftMargin, colorSpaceDisposition destColorSpace)
{
ubyte *fromPtr=ptrToStrip, *toPtr, *newStrip;
sint32 scanLineWidth;
assert(currSourceWidth+(2*leftMargin)<=currMediaWidth);
// writeOutputFile(currSourceWidth*3*numLinesThisCall, ptrToStrip);
if(destColorSpace==grayScale)
{
scanLineWidth=currMediaWidth;
// Allocate a full strip
newStrip=(ubyte*)malloc(scanLineWidth*currStripHeight);
memset(newStrip,0xff,scanLineWidth*currStripHeight);
for(int i=0;i<numLinesThisCall;i++)
{
toPtr=newStrip+leftMargin+(i*currMediaWidth);
fromPtr=ptrToStrip+(i*currSourceWidth);
memcpy(toPtr,fromPtr,currSourceWidth);
}
}
else
{
scanLineWidth=currMediaWidth*3;
sint32 srcScanlineWidth=currSourceWidth*3;
sint32 shiftAmount=leftMargin*3;
newStrip=(ubyte*)malloc(scanLineWidth*currStripHeight);
memset(newStrip,0xff,scanLineWidth*currStripHeight);
for(int i=0;i<numLinesThisCall;i++)
{
toPtr=newStrip+shiftAmount+(i*scanLineWidth);
fromPtr=ptrToStrip+(i*srcScanlineWidth);
memcpy(toPtr,fromPtr,srcScanlineWidth);
// memset(toPtr,0xe0,srcScanlineWidth);
}
}
return(newStrip);
}
#ifdef SUPPORT_WHITE_STRIPS
bool PCLmGenerator::isWhiteStrip(void *pInBuffer, int inBufferSize)
{
uint32 *ptr=(uint32*)pInBuffer;
for(int i=0;i<inBufferSize/4;i++,ptr++)
{
if(*ptr!=0xffffffff)
return(false);
}
return(true);
}
#endif
void PCLmGenerator::Cleanup(void)
{
if(allocatedOutputBuffer)
{
free(allocatedOutputBuffer);
allocatedOutputBuffer = NULL;
currOutBuffSize = 0;
}
if(leftoverScanlineBuffer)
{
free(leftoverScanlineBuffer);
leftoverScanlineBuffer=NULL;
}
if(scratchBuffer)
{
free(scratchBuffer);
scratchBuffer = NULL;
}
if(xRefTable)
{
free(xRefTable);
xRefTable=NULL;
}
if(KidsArray)
{
free(KidsArray);
KidsArray=NULL;
}
}
int PCLmGenerator::errorOutAndCleanUp()
{
Cleanup();
jobOpen=job_errored;
return(genericFailure);
}
static sint32 startXRef=0;
static sint32 endXRef=0;
/***************************************************************
* Warning: don't muck with this unless you understand what is going on. This function attempst to
* fix the xref table, based upon the strips getting inserted in reverse order (on the backside
* page). It does the following:
* 1) Calculates the new object reference size (using tmpArray)
* 2) Adds 2 to the object size to componsate for the offset
* 3) Reorders the Image FileBody and the ImageTrasformation, as these are actually 1 PDF object
* 4) Frees the tmp array
**************************************************************/
void PCLmGenerator::fixXRef()
{
if(!startXRef || !mirrorBackside)
return;
if(currDuplexDisposition==duplex_longEdge && !(pageCount%2) && mirrorBackside)
{
assert(startXRef);
sint32 start=startXRef;
sint32 end=endXRef-1;
sint32 aSize=endXRef-startXRef-1;
sint32 *tmpArray=(sint32*)malloc(aSize*20);
sint32 xRefI=startXRef;
for(int i=0;i<aSize+1;i++,xRefI++)
{
*(tmpArray+i)=xRefTable[xRefI+1]-xRefTable[xRefI];
//printf("size=%d: %d - %d\n",*(tmpArray+i),xRefTable[xRefI+1],xRefTable[xRefI]);
}
//printf("second time\n");
// Reorder header and image sizes
for(int i=0;i<aSize+1;i+=2,xRefI++)
{
sint32 t=*(tmpArray+i);
*(tmpArray+i)=*(tmpArray+i+1);
*(tmpArray+i+1)=t;
}
// for(int i=0;i<aSize+1;i++,xRefI++)
// printf("size=%d\n",*(tmpArray+i));
// printf("endXRef=%d\n",endXRef);
// for(int ii=startXRef;ii<endXRef+1;ii++)
// printf("xRefTable[%d]=%d \n",ii,xRefTable[ii]);
xRefI=aSize;
// printf("start=%d, end=%d\n",start+1, end);
for(int i=start+1, j=aSize; i<end+2;i++, start++, xRefI--, j--)
{
// printf("xRefTable[%d]=%d, *tmpArray=%d, summed=%d\n",i-1,xRefTable[i-1],*(tmpArray+j),
// xRefTable[i-1] + *tmpArray);
xRefTable[i]=(xRefTable[i-1] + *(tmpArray+j));
}
// printf("start=%d, end=%d\n",startXRef+2, endXRef);
for(int i=startXRef+2; i<endXRef;i++)
{
// printf("i=%d\n",i);
xRefTable[i]+=2;
}
// printf("After\n");
// for(int ii=startXRef;ii<endXRef+1;ii++)
// printf("xRefTable[%d]=%d\n",ii,xRefTable[ii]);
//for(int i=startXRef; i<j/2;i++,j--)
//
// Now reorder, so that image0 is first in the xref table
sint32 k=endXRef-1;
// sint32 j=k;
int i;
sint32 lSize=(endXRef-startXRef)/2;
// printf("endXRef=%d, startXRef=%d, lSize=%d\n",endXRef, startXRef, lSize);
// printf("switching order, aSize=%d, start=%d, end=%d\n",j, startXRef, endXRef-1);
// printf("startXRef+(j/2)+1=%d\n",startXRef+(j/2));
for(i=startXRef; i<startXRef+lSize;i++,k--)
{
// printf("SJC: i=%d, k=%d\n",i,k);
sint32 t=xRefTable[i];
xRefTable[i]=xRefTable[k];
xRefTable[k]=t;
}
free(tmpArray);
}
//printf("Finally\n");
//for(int ii=startXRef;ii<endXRef+1;ii++)
// printf("xRefTable[%d]=%d\n",ii,xRefTable[ii]);
startXRef=0;
}
bool PCLmGenerator::addXRef(sint32 xRefObj)
{
#define XREF_ARRAY_SIZE 100
if(!xRefTable)
{
xRefTable=(sint32*)malloc(XREF_ARRAY_SIZE*sizeof(sint32));
assert(xRefTable);
xRefTable[0]=0;
xRefIndex++;
}
xRefTable[xRefIndex]=xRefObj;
xRefIndex++;
if(!(xRefIndex%XREF_ARRAY_SIZE))
{
xRefTable=(sint32*)realloc(xRefTable,(((xRefIndex+XREF_ARRAY_SIZE)*sizeof(sint32))));
if(DebugIt)
printf("Realloc xRef: 0x%lx\n",(unsigned long int)xRefTable);
}
return(true);
}
bool PCLmGenerator::addKids(sint32 kidObj)
{
#define KID_ARRAY_SIZE 20
if(!KidsArray)
{
KidsArray=(sint32*)malloc(KID_ARRAY_SIZE*sizeof(sint32));
assert(KidsArray);
}
KidsArray[numKids]=kidObj;
numKids++;
if(!(numKids%KID_ARRAY_SIZE))
{
KidsArray=(sint32*)realloc(KidsArray,((numKids+KID_ARRAY_SIZE)*sizeof(sint32)));
}
return(true);
}
boolean writeOutputFile(int numBytes, ubyte *ptr)
{
FILE *outputFile;
char outFileName[20];
static int fileCntr=0;
sprintf(outFileName,"outfile_%04d",fileCntr);
fileCntr++;
// Open output PDF file
if (!(outputFile = fopen (outFileName, "w")))
{
fprintf (stderr, "Could not open the output file out - %s.\n", "t.pdf");
exit (-1);
}
fwrite(ptr,numBytes,1,outputFile);
fclose(outputFile);
return(true);
}
void PCLmGenerator::initOutBuff(char *buff, sint32 size)
{
currBuffPtr=outBuffPtr=buff;
outBuffSize=size;
totalBytesWrittenToCurrBuff=0;
memset(buff,0,size);
}
void PCLmGenerator::writeStr2OutBuff(char *str)
{
sint32 strSize=strlen(str);
// Make sure we have enough room for the copy
char *maxSize=currBuffPtr+strSize;
assert(maxSize-outBuffPtr < outBuffSize);
memcpy(currBuffPtr,str,strSize);
currBuffPtr+=strSize;
totalBytesWrittenToCurrBuff+=strSize;
totalBytesWrittenToPCLmFile+=strSize;
}
void PCLmGenerator::write2Buff(ubyte *buff, int buffSize)
{
char *maxSize=currBuffPtr+buffSize;
if(maxSize-outBuffPtr > outBuffSize)
{
printf("outBuffSize too small: %ld, %d\n",maxSize-outBuffPtr,outBuffSize);
assert(0);
}
memcpy(currBuffPtr,buff,buffSize);
currBuffPtr+=buffSize;
totalBytesWrittenToCurrBuff+=buffSize;
totalBytesWrittenToPCLmFile+=buffSize;
}
int PCLmGenerator::statOutputFileSize()
{
addXRef(totalBytesWrittenToPCLmFile);
return(1);
}
void PCLmGenerator::writePDFGrammarTrailer(int imageWidth, int imageHeight)
{
int i;
char KidsString[KID_STRING_SIZE];
if(DebugIt2)
{
fprintf(stderr, "imageWidth=%d\n",imageWidth);
fprintf(stderr, "imageHeight=%d\n",imageHeight);
}
sprintf(pOutStr,"%%============= PCLm: FileBody: Object 1 - Catalog\n"); writeStr2OutBuff(pOutStr);
statOutputFileSize();
sprintf(pOutStr,"%d 0 obj\n", CATALOG_OBJ_NUMBER); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"<<\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"/Type /Catalog\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"/Pages %d 0 R\n",PAGES_OBJ_NUMBER); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,">>\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"endobj\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"%%============= PCLm: FileBody: Object 2 - page tree \n"); writeStr2OutBuff(pOutStr);
statOutputFileSize();
sprintf(pOutStr,"%d 0 obj\n", PAGES_OBJ_NUMBER); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"<<\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"/Count %d\n",numKids); writeStr2OutBuff(pOutStr);
// Define the Kids for this document as an indirect array
sprintf(KidsString,"/Kids [ ");writeStr2OutBuff(KidsString);
for(i=0;i<numKids;i++)
{
//spot=strlen(KidsString);
sprintf(KidsString,"%d 0 R ",KidsArray[i]);
writeStr2OutBuff(KidsString);
}
sprintf(KidsString,"]\n");
writeStr2OutBuff(KidsString);
sprintf(pOutStr,"/Type /Pages\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,">>\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"endobj\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"%%============= PCLm: cross-reference section: object 0, 6 entries\n"); writeStr2OutBuff(pOutStr);
statOutputFileSize();
// Fix up the xref table for backside duplex
fixXRef();
xRefStart=xRefIndex-1;
infoObj=xRefIndex;
sprintf(pOutStr,"xref\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"0 %d\n",1); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"0000000000 65535 f\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"%d %d\n",PAGES_OBJ_NUMBER+1,xRefIndex-4); writeStr2OutBuff(pOutStr);
for(i=1;i<xRefIndex-3;i++)
{
sprintf(pOutStr,"%010d %05d n\n",xRefTable[i],0); writeStr2OutBuff(pOutStr);
}
#ifdef PIECEINFO_SUPPORTED
// HP PieceInfo Structure
sprintf(pOutStr,"9996 0 obj\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"<</HPDefine1 1\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"/Private 9997 0 R>>\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"9997 0 obj\n"); writeStr2OutBuff(pOutStr);
#endif
//sprintf(pOutStr,"<</AIMetaData 32 0 R/AIPDFPrivateData1 33 0 R/AIPDFPrivateData10 34 0\n");
// Now add the catalog and page object
sprintf(pOutStr,"%d 2\n",CATALOG_OBJ_NUMBER); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"%010d %05d n\n",xRefTable[xRefIndex-3],0); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"%010d %05d n\n",xRefTable[xRefIndex-2],0); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"%%============= PCLm: File Trailer\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"trailer\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"<<\n"); writeStr2OutBuff(pOutStr);
// sprintf(pOutStr,"/Info %d 0\n", infoObj); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"/Size %d\n", xRefIndex-1); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"/Root %d 0 R\n",CATALOG_OBJ_NUMBER); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,">>\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"startxref\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"%d\n",xRefTable[xRefStart]); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"%%%%EOF\n"); writeStr2OutBuff(pOutStr);
}
bool PCLmGenerator::injectAdobeRGBCS()
{
if(adobeRGBCS_firstTime)
{
// We need to inject the ICC object for AdobeRGB
sprintf(pOutStr,"%%============= PCLm: ICC Profile\n"); writeStr2OutBuff(pOutStr);
statOutputFileSize();
sprintf(pOutStr,"%d 0 obj\n", objCounter); objCounter++; writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"[/ICCBased %d 0 R]\n",objCounter); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"endobj\n"); writeStr2OutBuff(pOutStr);
statOutputFileSize();
sprintf(pOutStr,"%d 0 obj\n", objCounter); objCounter++; writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"<<\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"/N 3\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"/Alternate /DeviceRGB\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"/Length %u\n",ADOBE_RGB_SIZE+1); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"/Filter /FlateDecode\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,">>\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"stream\n"); writeStr2OutBuff(pOutStr);
#ifdef STAND_ALLONE
#define ADOBE_RGB_SIZE 284
FILE *inFile;
if (!(inFile = fopen ("flate_colorspace.bin", "rb")))
{
fprintf(stderr, "can't open %s\n", "flate_colorspace.bin");
return 0;
}
ubyte *buffIn=(unsigned char *)malloc(ADOBE_RGB_SIZE);
assert(buffIn);
sint32 bytesRead=fread( buffIn, 1, ADOBE_RGB_SIZE, inFile );
assert(bytesRead==ADOBE_RGB_SIZE);
fclose(inFile);
write2Buff(buffIn,bytesRead);
if(buffIn)
{
free(buffIn);
buffIn=NULL;
}
#else
write2Buff(flateBuffer,ADOBE_RGB_SIZE);
#endif // STEVECODE
sprintf(pOutStr,"\nendstream\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"endobj\n"); writeStr2OutBuff(pOutStr);
}
adobeRGBCS_firstTime=false;
return(true);
}
/****************************************************************************************
* Function: colorConvertSource
* Purpose: to convert an image from one color space to another.
* Limitations:
* - Currently, only supports RGB->GRAY
*****************************************************************************************/
bool PCLmGenerator::colorConvertSource(colorSpaceDisposition srcCS, colorSpaceDisposition dstCS, ubyte *strip, sint32 stripWidth, sint32 stripHeight)
{
if(srcCS==deviceRGB && dstCS==grayScale)
{
// Do an inplace conversion from RGB -> 8 bpp gray
ubyte *srcPtr=strip;
ubyte *dstPtr=strip;
for(int h=0;h<stripHeight;h++)
{
for(int w=0;w<stripWidth;w++,dstPtr++,srcPtr+=3)
{
//*dstPtr=(ubyte)((0.299*((double)r))+(0.587*((double)g)+0.114)*((double)b));
*dstPtr=(ubyte)rgb_2_gray(*srcPtr,*(srcPtr+1),*(srcPtr+2));
}
}
dstNumComponents=1;
// sourceColorSpace=grayScale; // We don't want to change this, as we are only changing the
// current strip.
}
else
assert(1);
//writeOutputFile(stripWidth*stripHeight, strip);
return(true);
}
int PCLmGenerator::injectRLEStrip(ubyte *RLEBuffer, int numBytes, int imageWidth, int imageHeight, colorSpaceDisposition destColorSpace, bool whiteStrip)
{
//unsigned char c;
char fileStr[25];
static int stripCount=0;
bool printedImageTransform=false;
if(DebugIt2)
{
printf("Injecting RLE compression stream into PDF\n");
printf(" numBytes=%d, imageWidth=%d, imageHeight=%d\n",numBytes,imageWidth,imageHeight);
sprintf(fileStr,"rleFile.%d",stripCount);
stripCount++;
write2Buff(RLEBuffer,numBytes);
}
if(currDuplexDisposition==duplex_longEdge && !(pageCount%2) && mirrorBackside)
{
if(!startXRef)
startXRef=xRefIndex;
injectImageTransform();
printedImageTransform=true;
}
if(destColorSpace==adobeRGB)
{
injectAdobeRGBCS();
}
// Inject LZ compressed image into PDF file
sprintf(pOutStr,"%%============= PCLm: FileBody: Strip Stream: RLE Image \n"); writeStr2OutBuff(pOutStr);
statOutputFileSize();
if(currDuplexDisposition==duplex_longEdge && !(pageCount%2) && mirrorBackside)
{
sprintf(pOutStr,"%d 0 obj\n", objCounter-1); objCounter++; writeStr2OutBuff(pOutStr);
}
else
{
sprintf(pOutStr,"%d 0 obj\n", objCounter); objCounter++; writeStr2OutBuff(pOutStr);
}
sprintf(pOutStr,"<<\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"/Width %d\n", imageWidth); writeStr2OutBuff(pOutStr);
if(destColorSpace==deviceRGB)
{
sprintf(pOutStr,"/ColorSpace /DeviceRGB\n"); writeStr2OutBuff(pOutStr);
}
else if(destColorSpace==adobeRGB)
{
sprintf(pOutStr,"/ColorSpace 5 0 R\n"); writeStr2OutBuff(pOutStr);
}
else
{
sprintf(pOutStr,"/ColorSpace /DeviceGray\n"); writeStr2OutBuff(pOutStr);
}
sprintf(pOutStr,"/Height %d\n", imageHeight); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"/Filter /RunLengthDecode\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"/Subtype /Image\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"/Length %d\n",numBytes); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"/Type /XObject\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"/BitsPerComponent 8\n"); writeStr2OutBuff(pOutStr);
#ifdef SUPPORT_WHITE_STRIPS
if(whiteStrip)
{
sprintf(pOutStr,"/Name /WhiteStrip\n"); writeStr2OutBuff(pOutStr);
}
else
{
sprintf(pOutStr,"/Name /ColorStrip\n"); writeStr2OutBuff(pOutStr);
}
#endif
sprintf(pOutStr,">>\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"stream\n"); writeStr2OutBuff(pOutStr);
// Write the zlib compressed strip to the PDF output file
write2Buff(RLEBuffer,numBytes);
sprintf(pOutStr,"\nendstream\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"endobj\n"); writeStr2OutBuff(pOutStr);
if(!printedImageTransform)
injectImageTransform();
endXRef=xRefIndex;
return(1);
}
int PCLmGenerator::injectLZStrip(ubyte *LZBuffer, int numBytes, int imageWidth, int imageHeight, colorSpaceDisposition destColorSpace, bool whiteStrip)
{
//unsigned char c;
bool printedImageTransform=false;
if(DebugIt2)
{
printf("Injecting LZ compression stream into PDF\n");
printf(" numBytes=%d, imageWidth=%d, imageHeight=%d\n",numBytes,imageWidth,imageHeight);
}
if(currDuplexDisposition==duplex_longEdge && !(pageCount%2) && mirrorBackside)
{
if(!startXRef)
startXRef=xRefIndex;
injectImageTransform();
printedImageTransform=true;
}
if(destColorSpace==adobeRGB)
{
injectAdobeRGBCS();
}
// Inject LZ compressed image into PDF file
sprintf(pOutStr,"%%============= PCLm: FileBody: Strip Stream: zlib Image \n"); writeStr2OutBuff(pOutStr);
statOutputFileSize();
if(currDuplexDisposition==duplex_longEdge && !(pageCount%2) && mirrorBackside)
{
sprintf(pOutStr,"%d 0 obj\n", objCounter-1); objCounter++; writeStr2OutBuff(pOutStr);
}
else
{
sprintf(pOutStr,"%d 0 obj\n", objCounter); objCounter++; writeStr2OutBuff(pOutStr);
}
sprintf(pOutStr,"<<\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"/Width %d\n", imageWidth); writeStr2OutBuff(pOutStr);
if(destColorSpace==deviceRGB)
{
sprintf(pOutStr,"/ColorSpace /DeviceRGB\n"); writeStr2OutBuff(pOutStr);
}
else if(destColorSpace==adobeRGB)
{
sprintf(pOutStr,"/ColorSpace 5 0 R\n"); writeStr2OutBuff(pOutStr);
}
else
{
sprintf(pOutStr,"/ColorSpace /DeviceGray\n"); writeStr2OutBuff(pOutStr);
}
sprintf(pOutStr,"/Height %d\n", imageHeight); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"/Filter /FlateDecode\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"/Subtype /Image\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"/Length %d\n",numBytes); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"/Type /XObject\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"/BitsPerComponent 8\n"); writeStr2OutBuff(pOutStr);
#ifdef SUPPORT_WHITE_STRIPS
if(whiteStrip)
{
sprintf(pOutStr,"/Name /WhiteStrip\n"); writeStr2OutBuff(pOutStr);
}
else
{
sprintf(pOutStr,"/Name /ColorStrip\n"); writeStr2OutBuff(pOutStr);
}
#endif
sprintf(pOutStr,">>\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"stream\n"); writeStr2OutBuff(pOutStr);
// Write the zlib compressed strip to the PDF output file
write2Buff(LZBuffer,numBytes);
sprintf(pOutStr,"\nendstream\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"endobj\n"); writeStr2OutBuff(pOutStr);
if(!printedImageTransform)
injectImageTransform();
endXRef=xRefIndex;
return(1);
}
void PCLmGenerator::injectImageTransform()
{
char str[512];
int strLength;
sprintf(str,"q /image Do Q\n");
strLength=strlen(str);
// Output image transformation information
sprintf(pOutStr,"%%============= PCLm: Object - Image Transformation \n"); writeStr2OutBuff(pOutStr);
statOutputFileSize();
if(currDuplexDisposition==duplex_longEdge && !(pageCount%2) && mirrorBackside)
{
sprintf(pOutStr,"%d 0 obj\n", objCounter+1); objCounter++; writeStr2OutBuff(pOutStr);
}
else
{
sprintf(pOutStr,"%d 0 obj\n", objCounter); objCounter++; writeStr2OutBuff(pOutStr);
}
sprintf(pOutStr,"<<\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"/Length %d\n",strLength); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,">>\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"stream\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"%s",str); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"endstream\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"endobj\n"); writeStr2OutBuff(pOutStr);
}
int PCLmGenerator::injectJPEG(char *jpeg_Buff, int imageWidth, int imageHeight, int numCompBytes, colorSpaceDisposition destColorSpace, bool whiteStrip)
{
// int fd, bytesRead;
int strLength;
char str[512];
bool printedImageTransform=false;
if(currDuplexDisposition==duplex_longEdge && !(pageCount%2) && mirrorBackside)
{
if(!startXRef)
startXRef=xRefIndex;
injectImageTransform();
printedImageTransform=true;
}
if(DebugIt2)
{
printf("Injecting jpegBuff into PDF\n");
}
yPosition+=imageHeight;
if(destColorSpace==adobeRGB)
{
injectAdobeRGBCS();
}
// Inject PDF JPEG into output file
sprintf(pOutStr,"%%============= PCLm: FileBody: Strip Stream: jpeg Image \n"); writeStr2OutBuff(pOutStr);
statOutputFileSize();
if(currDuplexDisposition==duplex_longEdge && !(pageCount%2) && mirrorBackside)
{
//printf("frontside, oc=%d\n",objCounter);sprintf(pOutStr,"%d 0 obj\n", objCounter);
//objCounter++; writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"%d 0 obj\n", objCounter-1); objCounter++;
writeStr2OutBuff(pOutStr);
}
else
{
sprintf(pOutStr,"%d 0 obj\n", objCounter); objCounter++;
writeStr2OutBuff(pOutStr);
}
sprintf(pOutStr,"<<\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"/Width %d\n", imageWidth); writeStr2OutBuff(pOutStr);
if(destColorSpace==deviceRGB)
{
sprintf(pOutStr,"/ColorSpace /DeviceRGB\n"); writeStr2OutBuff(pOutStr);
}
else if(destColorSpace==adobeRGB)
{
sprintf(pOutStr,"/ColorSpace 5 0 R\n"); writeStr2OutBuff(pOutStr);
}
else
{
sprintf(pOutStr,"/ColorSpace /DeviceGray\n"); writeStr2OutBuff(pOutStr);
}
sprintf(pOutStr,"/Height %d\n", imageHeight); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"/Filter /DCTDecode\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"/Subtype /Image\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"/Length %d\n",numCompBytes); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"/Type /XObject\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"/BitsPerComponent 8\n"); writeStr2OutBuff(pOutStr);
#ifdef SUPPORT_WHITE_STRIPS
if(whiteStrip)
{
sprintf(pOutStr,"/Name /WhiteStrip\n"); writeStr2OutBuff(pOutStr);
}
else
{
sprintf(pOutStr,"/Name /ColorStrip\n"); writeStr2OutBuff(pOutStr);
}
#endif
sprintf(pOutStr,">>\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"stream\n"); writeStr2OutBuff(pOutStr);
// Inject JPEG image into stream
//fd = open(jpeg_filename, O_RDWR);
//if(fd==-1)
//{
// fprintf (stderr, "Could not open the image file %s.\n", jpeg_filename);
// exit(-1);
//}
//inPtr=(unsigned char *)malloc(fileSize);
//bytesRead=read(fd, inPtr, fileSize);
//write(stdout, inPtr, bytesRead);
write2Buff((ubyte*)jpeg_Buff,numCompBytes);
sprintf(pOutStr,"\nendstream\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"endobj\n"); writeStr2OutBuff(pOutStr);
sprintf(str,"q /image Do Q\n");
strLength=strlen(str);
if(!printedImageTransform)
injectImageTransform();
endXRef=xRefIndex;
return(1);
}
void writeStr2Buff(char *buffer,char *str)
{
int buffSize;
char *buffPos;
buffSize=strlen(buffer)+strlen(str);
if(buffSize>TEMP_BUFF_SIZE)
assert(0);
buffSize=strlen(buffer);
buffPos=buffer+buffSize;
sprintf(buffPos,"%s",str);
buffSize=strlen(buffer);
if(buffSize>TEMP_BUFF_SIZE)
{
printf("tempBuff size exceeded: buffSize=%d\n",buffSize);
assert(0);
}
}
/**********************************************************************************************
* Function: writePDFGrammarPage
* Purpose: to generate the PDF page construct(s), which includes the image information.
* Implementation: the /Length definition is required for PDF, so we write the stream to a RAM buffer
* first, then calculate the Buffer size, insert the PDF /Length construct, then write the
* buffer to the PDF file. I used the RAM buffer instead of a temporary file, as a driver
* implementation won't be able to use a disk file.
***********************************************************************************************/
void PCLmGenerator::writePDFGrammarPage(int imageWidth, int imageHeight, int numStrips, colorSpaceDisposition destColorSpace)
{
int i, imageRef=objCounter+2, buffSize;
int yAnchor;
char str[512];
char *tempBuffer;
int startImageIndex=0;
int numLinesLeft = 0;
if(destColorSpace==adobeRGB && 1 == pageCount)
{
imageRef+=2; // Add 2 for AdobeRGB
}
tempBuffer=(char *)malloc(TEMP_BUFF_SIZE);
assert(tempBuffer);
if(DebugIt2)
printf("Allocated %d bytes for tempBuffer\n",TEMP_BUFF_SIZE);
memset(tempBuffer,0x0,TEMP_BUFF_SIZE);
sprintf(pOutStr,"%%============= PCLm: FileBody: Object 3 - page object\n"); writeStr2OutBuff(pOutStr);
statOutputFileSize();
sprintf(pOutStr,"%d 0 obj\n", objCounter); writeStr2OutBuff(pOutStr);
addKids(objCounter);
objCounter++;
sprintf(pOutStr,"<<\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"/Type /Page\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"/Parent %d 0 R\n",PAGES_OBJ_NUMBER); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"/Resources <<\n"); writeStr2OutBuff(pOutStr);
// sprintf(pOutStr,"/ProcSet [ /PDF /ImageC ]\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"/XObject <<\n"); writeStr2OutBuff(pOutStr);
if(topMarginInPix)
{
for(i=0;i<numFullInjectedStrips;i++,startImageIndex++)
{
sprintf(str,"/Image%d %d 0 R\n",startImageIndex,imageRef);
sprintf(pOutStr,"%s",str); writeStr2OutBuff(pOutStr);
imageRef+=2;
}
if(numPartialScanlinesToInject)
{
sprintf(str,"/Image%d %d 0 R\n",startImageIndex,imageRef);
sprintf(pOutStr,"%s",str); writeStr2OutBuff(pOutStr);
imageRef+=2;
startImageIndex++;
}
}
for(i=startImageIndex;i<numStrips+startImageIndex;i++)
{
sprintf(str,"/Image%d %d 0 R\n",i,imageRef);
// sprintf(pOutStr,"/ImageA 4 0 R /ImageB 6 0 R >>\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"%s",str); writeStr2OutBuff(pOutStr);
imageRef+=2;
}
sprintf(pOutStr,">>\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,">>\n"); writeStr2OutBuff(pOutStr);
if(currMediaOrientationDisposition==landscapeOrientation)
{
pageOrigin=mediaWidth;
sprintf(pOutStr,"/MediaBox [ 0 0 %d %d ]\n", mediaHeight, mediaWidth); writeStr2OutBuff(pOutStr);
}
else
{
pageOrigin=mediaHeight;
sprintf(pOutStr,"/MediaBox [ 0 0 %d %d ]\n", mediaWidth, mediaHeight); writeStr2OutBuff(pOutStr);
}
sprintf(pOutStr,"/Contents [ %d 0 R ]\n",objCounter); writeStr2OutBuff(pOutStr);
#ifdef PIECEINFO_SUPPORTED
sprintf(pOutStr,"/PieceInfo <</HPAddition %d 0 R >> \n",9997); writeStr2OutBuff(pOutStr);
#endif
sprintf(pOutStr,">>\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"endobj\n"); writeStr2OutBuff(pOutStr);
// Create the FileBody stream first, so we know the Length of the stream
if(reverseOrder)
{
yAnchor=0;
}
else
{
yAnchor=(int)((pageOrigin*STANDARD_SCALE)+0.99); // Round up
}
// Setup the CTM so that we can send device-resolution coordinates
sprintf(pOutStr,"%%Image Transformation Matrix: width, skewX, skewY, height, xAnchor, yAnchor\n"); writeStr2OutBuff(pOutStr);
sprintf(str,"%f 0 0 %f 0 0 cm\n",STANDARD_SCALE_FOR_PDF/currRenderResolutionInteger,STANDARD_SCALE_FOR_PDF/currRenderResolutionInteger);
writeStr2Buff(tempBuffer,str);
startImageIndex=0;
if(topMarginInPix)
{
for(i=0;i<numFullInjectedStrips;i++)
{
if(reverseOrder)
yAnchor+=numFullScanlinesToInject;
else
yAnchor-=numFullScanlinesToInject;
sprintf(str,"/P <</MCID 0>> BDC q\n");
writeStr2Buff(tempBuffer,str);
sprintf(str,"%%Image Transformation Matrix: width, skewX, skewY, height, xAnchor, yAnchor\n");
writeStr2Buff(tempBuffer,str);
sprintf(str,"%d 0 0 %d 0 %d cm\n",imageWidth*scaleFactor,numFullScanlinesToInject*scaleFactor,yAnchor*scaleFactor);
writeStr2Buff(tempBuffer,str);
sprintf(str,"/Image%d Do Q\n",startImageIndex);
writeStr2Buff(tempBuffer,str);
startImageIndex++;
}
if(numPartialScanlinesToInject)
{
if(reverseOrder)
yAnchor+=numPartialScanlinesToInject;
else
yAnchor-=numPartialScanlinesToInject;
sprintf(str,"/P <</MCID 0>> BDC q\n");
writeStr2Buff(tempBuffer,str);
sprintf(str,"%%Image Transformation Matrix: width, skewX, skewY, height, xAnchor, yAnchor\n");
writeStr2Buff(tempBuffer,str);
sprintf(str,"%d 0 0 %d 0 %d cm\n",imageWidth*scaleFactor,numPartialScanlinesToInject*scaleFactor,yAnchor*scaleFactor);
writeStr2Buff(tempBuffer,str);
sprintf(str,"/Image%d Do Q\n",startImageIndex);
writeStr2Buff(tempBuffer,str);
startImageIndex++;
}
}
for(i=startImageIndex;i<numStrips+startImageIndex;i++)
{
//last strip may have less lines than currStripHeight. So update yAnchor using left over lines
if(i == (numStrips+startImageIndex-1))
{
numLinesLeft = currSourceHeight - ((numStrips-1) * currStripHeight);
if(reverseOrder)
yAnchor+=numLinesLeft;
else
yAnchor-=numLinesLeft;
}
else
{
if(reverseOrder)
yAnchor+=currStripHeight;
else
yAnchor-=currStripHeight;
}
sprintf(str,"/P <</MCID 0>> BDC q\n");
writeStr2Buff(tempBuffer,str);
sprintf(str,"%%Image Transformation Matrix: width, skewX, skewY, height, xAnchor, yAnchor\n");
writeStr2Buff(tempBuffer,str);
if(i == (numStrips+startImageIndex-1)) //last strip may have less lines than currStripHeight
{
sprintf(str,"%d 0 0 %d 0 %d cm\n",imageWidth*scaleFactor,numLinesLeft*scaleFactor,yAnchor*scaleFactor);
writeStr2Buff(tempBuffer,str);
}
else if(yAnchor<0)
{
sint32 newH=currStripHeight+yAnchor;
sprintf(str,"%d 0 0 %d 0 %d cm\n",imageWidth*scaleFactor,newH*scaleFactor,0*scaleFactor);
writeStr2Buff(tempBuffer,str);
}
else
{
sprintf(str,"%d 0 0 %d 0 %d cm\n",imageWidth*scaleFactor,currStripHeight*scaleFactor,yAnchor*scaleFactor);
writeStr2Buff(tempBuffer,str);
}
sprintf(str,"/Image%d Do Q\n",i);
writeStr2Buff(tempBuffer,str);
}
// Resulting buffer size
buffSize=strlen(tempBuffer);
sprintf(pOutStr,"%%============= PCLm: FileBody: Page Content Stream object\n"); writeStr2OutBuff(pOutStr);
statOutputFileSize();
sprintf(pOutStr,"%d 0 obj\n",objCounter); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"<<\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"/Length %d\n",buffSize); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,">>\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"stream\n"); writeStr2OutBuff(pOutStr);
// Now write the FileBody stream
write2Buff((ubyte*)tempBuffer,buffSize);
sprintf(pOutStr,"endstream\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"endobj\n"); writeStr2OutBuff(pOutStr);
objCounter++;
if(tempBuffer)
{
free(tempBuffer);
tempBuffer=NULL;
}
}
/****************************************************************************************
* Function: prepImageForBacksideDuplex
* Purpose: To mirror the source image in preperation for backside duplex support
* Limitations:
* -
*****************************************************************************************/
boolean prepImageForBacksideDuplex(ubyte *imagePtr, sint32 imageHeight, sint32 imageWidth, sint32 numComponents)
{
sint32 numBytes=imageHeight*imageWidth*numComponents;
ubyte *head, *tail, t0, t1, t2;
if(numComponents==3)
{
for(head=imagePtr,tail=imagePtr+numBytes-1;tail>head;)
{
t0=*head;
t1=*(head+1);
t2=*(head+2);
*head= *(tail-2);
*(head+1)=*(tail-1);
*(head+2)=*(tail-0);
*tail= t2;
*(tail-1)=t1;
*(tail-2)=t0;
head+=3;
tail-=3;
}
}
else
{
for(head=imagePtr,tail=imagePtr+numBytes;tail>head;)
{
t0=*head;
*head=*tail;
*tail=t0;
head++;
tail--;
}
}
//origTail++;
return(true);
}
bool PCLmGenerator::getInputBinString(jobInputBin bin, char *returnStr)
{
memset(returnStr,0,sizeof(returnStr));
switch (bin)
{
case alternate: strcpy(returnStr,"alternate"); break;
case alternate_roll: strcpy(returnStr,"alternate_roll"); break;
case auto_select: strcpy(returnStr,"auto_select"); break;
case bottom: strcpy(returnStr,"bottom"); break;
case center: strcpy(returnStr,"center"); break;
case disc: strcpy(returnStr,"disc"); break;
case envelope: strcpy(returnStr,"envelope"); break;
case hagaki: strcpy(returnStr,"hagaki"); break;
case large_capacity: strcpy(returnStr,"large_capacity"); break;
case left: strcpy(returnStr,"left"); break;
case main_tray: strcpy(returnStr,"main_tray"); break;
case main_roll: strcpy(returnStr,"main_roll"); break;
case manual: strcpy(returnStr,"manual"); break;
case middle: strcpy(returnStr,"middle"); break;
case photo: strcpy(returnStr,"photo"); break;
case rear: strcpy(returnStr,"rear"); break;
case right: strcpy(returnStr,"right"); break;
case side: strcpy(returnStr,"side"); break;
case top: strcpy(returnStr,"top"); break;
case tray_1: strcpy(returnStr,"tray_1"); break;
case tray_2: strcpy(returnStr,"tray_2"); break;
case tray_3: strcpy(returnStr,"tray_3"); break;
case tray_4: strcpy(returnStr,"tray_4"); break;
case tray_5: strcpy(returnStr,"tray_5"); break;
case tray_N: strcpy(returnStr,"tray_N"); break;
default: assert(0); break;
}
return(true);
}
bool PCLmGenerator::getOutputBin(jobOutputBin bin, char *returnStr)
{
memset(returnStr,0,sizeof(returnStr));
switch(bin)
{
case top_output: strcpy(returnStr,"top_output"); break;
case middle_output: strcpy(returnStr,"middle_output"); break;
case bottom_output: strcpy(returnStr,"bottom_output"); break;
case side_output: strcpy(returnStr,"side_output"); break;
case center_output: strcpy(returnStr,"center_output"); break;
case rear_output: strcpy(returnStr,"rear_output"); break;
case face_up: strcpy(returnStr,"face_up"); break;
case face_down: strcpy(returnStr,"face_down"); break;
case large_capacity_output: strcpy(returnStr,"large_capacity_output"); break;
case stacker_N: strcpy(returnStr,"stacker_N"); break;
case mailbox_N: strcpy(returnStr,"mailbox_N"); break;
case tray_1_output: strcpy(returnStr,"tray_1_output"); break;
case tray_2_output: strcpy(returnStr,"tray_2_output"); break;
case tray_3_output: strcpy(returnStr,"tray_3_output"); break;
case tray_4_output: strcpy(returnStr,"tray_4_output"); break;
default: assert(0); break;
}
return(true);
}
void PCLmGenerator::writeJobTicket()
{
// Write JobTicket
char inputBin[256];
char outputBin[256];
if(!m_pPCLmSSettings)
return;
getInputBinString(m_pPCLmSSettings->userInputBin,&inputBin[0]);
getOutputBin(m_pPCLmSSettings->userOutputBin, &outputBin[0]);
strcpy(inputBin, inputBin);
strcpy(outputBin, outputBin);
sprintf(pOutStr,"%% genPCLm (Ver: %f)\n",PCLM_Ver); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"%%============= Job Ticket =============\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"%% PCLmS-Job-Ticket\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"%% job-ticket-version: 0.1\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"%% epcl-version: 1.01\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"%% JobSection\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"%% job-id: xxx\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"%% MediaHandlingSection\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"%% media-size-name: %s\n",currMediaName); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"%% media-type: %s\n",m_pPCLmSSettings->userMediaType); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"%% media-source: %s\n",inputBin); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"%% sides: xxx\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"%% finishings: xxx\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"%% output-bin: %s\n",outputBin); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"%% RenderingSection\n"); writeStr2OutBuff(pOutStr);
if(currCompressionDisposition==compressDCT)
{
sprintf(pOutStr,"%% pclm-compression-method: JPEG\n"); writeStr2OutBuff(pOutStr);
}
else if(currCompressionDisposition==compressFlate)
{
sprintf(pOutStr,"%% pclm-compression-method: FLATE\n"); writeStr2OutBuff(pOutStr);
}
else
{
sprintf(pOutStr,"%% pclm-compression-method: RLE\n"); writeStr2OutBuff(pOutStr);
}
sprintf(pOutStr,"%% strip-height: %d\n",currStripHeight); writeStr2OutBuff(pOutStr);
if(destColorSpace==deviceRGB)
{
sprintf(pOutStr,"%% print-color-mode: deviceRGB\n"); writeStr2OutBuff(pOutStr);
}
else if(destColorSpace==adobeRGB)
{
sprintf(pOutStr,"%% print-color-mode: adobeRGB\n"); writeStr2OutBuff(pOutStr);
}
else if(destColorSpace==grayScale)
{
sprintf(pOutStr,"%% print-color-mode: gray\n"); writeStr2OutBuff(pOutStr);
}
sprintf(pOutStr,"%% print-quality: %d\n",m_pPCLmSSettings->userPageQuality); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"%% printer-resolution: %d\n",currRenderResolutionInteger); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"%% print-content-optimized: xxx\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"%% orientation-requested: %d\n",m_pPCLmSSettings->userOrientation); writeStr2OutBuff(pOutStr);
if(PCLmSSettings.userCopies==0)
PCLmSSettings.userCopies=1;
sprintf(pOutStr,"%% copies: %d\n",m_pPCLmSSettings->userCopies); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"%% pclm-raster-back-side: xxx\n"); writeStr2OutBuff(pOutStr);
if(currRenderResolutionInteger)
{
sprintf(pOutStr,"%% margins-pre-applied: TRUE\n"); writeStr2OutBuff(pOutStr);
}
else
{
sprintf(pOutStr,"%% margins-pre-applied: FALSE\n"); writeStr2OutBuff(pOutStr);
}
sprintf(pOutStr,"%% PCLmS-Job-Ticket-End\n"); writeStr2OutBuff(pOutStr);
}
void PCLmGenerator::writePDFGrammarHeader()
{
// sprintf(pOutStr,"%%============= PCLm: File Header \n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"%%PDF-1.7\n"); writeStr2OutBuff(pOutStr);
sprintf(pOutStr,"%%PCLm 1.0\n"); writeStr2OutBuff(pOutStr);
}
int PCLmGenerator::RLEEncodeImage(ubyte *in, ubyte *out, int inLength)
{
// Overview
// compress input by identifying repeating bytes (not sequences)
// Compression ratio good for grayscale images, not great on RGB
// Output:
// 1-127: literal run
// 128: end of compression block
// 129-256: repeating byte sequence
//
ubyte *imgPtr=in;
ubyte *endPtr=in+inLength;
ubyte *origOut=out;
ubyte c;
sint32 cnt=0;
while(imgPtr<endPtr)
{
c=*imgPtr++;
cnt=1;
// Figure out how many repeating bytes are in the image
while(*imgPtr==c && cnt<inLength )
{
if(imgPtr>endPtr)
break;
cnt++;
imgPtr++;
}
// If cnt > 1, then output repeating byte specification
// The syntax is "byte-count repeateByte", where byte-count is
// 257-byte-count.
// Since the cnt value is a byte, if the repeateCnt is > 128
// then we need to put out multiple repeat-blocks
// Referred to as method 1, range is 128-256
if(cnt>1)
{
// Handle the repeat blocks of greater than 128 bytes
while(cnt>128)
{ // block of 128 repeating bytes
*out++=129; // i.e. 257-129==128
*out++=c;
cnt-=128;
}
// Now handle the repeats that are < 128
if(cnt)
{
*out++=(257-cnt); // i.e. cnt==2: 257-255=2
*out++=c;
}
}
// If cnt==1, then this is a literal run - no repeating bytes found.
// The syntax is "byte-count literal-run", where byte-count is < 128 and
// literal-run is the non-repeating bytes of the input stream.
// Referred to as method 2, range is 0-127
else
{
ubyte *start, *p;
sint32 i;
start=(imgPtr-1); // The first byte of the literal run
// Now find the end of the literal run
for(cnt=1,p=start;*p!=*imgPtr;p++,imgPtr++,cnt++)
if(imgPtr>=endPtr) break;
if(!(imgPtr==endPtr))
imgPtr--; // imgPtr incremented 1 too many
cnt--;
// Blocks of literal bytes can't exceed 128 bytes, so output multiple
// literal-run blocks if > 128
while(cnt>128)
{
*out++=127;
for(i=0;i<128;i++)
*out++=*start++;
cnt-=128;
}
// Now output the leftover literal run
*out++=cnt-1;
for(i=0;i<cnt;i++)
*out++=*start++;
}
}
// Now, write the end-of-compression marker (byte 128) into the output stream
*out++=128;
// Return the compressed size
return((int)(out-origOut));
}
/* PCLmGenerator Constructor
*
* /desc
* /param
* /return
*/
PCLmGenerator::PCLmGenerator()
{
strcpy(currMediaName,"LETTER");
currDuplexDisposition=simplex;
currColorSpaceDisposition=deviceRGB;
currDebugDisposition=debugOn;
currCompressionDisposition=compressDCT;
currMediaOrientationDisposition=portraitOrientation;
currRenderResolution=res600;
currStripHeight=STRIP_HEIGHT;
// Default media h/w to letter specification
mediaWidthInPixels=0;
mediaHeightInPixels=0;
mediaWidth=612;
mediaHeight=792;
destColorSpace=deviceRGB;
sourceColorSpace=deviceRGB;
scaleFactor=1;
genExtraPage=false;
jobOpen=job_closed;
scratchBuffer=NULL;
pageCount=0;
currRenderResolutionInteger=600;
STANDARD_SCALE=(float)currRenderResolutionInteger/(float)STANDARD_SCALE_FOR_PDF;
yPosition=0;
infoObj=0;
numKids=0;
// XRefTable storage
xRefIndex=0;
DebugIt=0;
DebugIt2=0;
objCounter=PAGES_OBJ_NUMBER+1;
totalBytesWrittenToPCLmFile=0;
// Initialize first index in xRefTable
xRefTable=NULL;
KidsArray=NULL;
// Initialize the output Buffer
allocatedOutputBuffer=NULL;
// Initialize the leftover scanline logic
leftoverScanlineBuffer=0;
adobeRGBCS_firstTime=true;
mirrorBackside=true;
topMarginInPix=0;
leftMarginInPix=0;
m_pPCLmSSettings = NULL;
}
/* PCLmGenerator Destructor
*
* /desc
* /param
* /return
*/
PCLmGenerator::~PCLmGenerator()
{
Cleanup();
}
/* StartJob
*
* /desc
* /param
* /return
*/
#ifdef STANDALONE
int PCLmGenerator::StartJob(void **pOutBuffer, int *iOutBufferSize, bool debug)
#else
int PCLmGenerator::StartJob(void **pOutBuffer, int *iOutBufferSize)
#endif
{
DebugIt=debug;
DebugIt2=debug;
if(DebugIt)
printf("genPCLm::StartJob\n");
// Allocate the output buffer; we don't know much at this point, so make the output buffer size
// the worst case dimensions; when we get a startPage, we will resize it appropriately
outBuffSize=DEFAULT_OUTBUFF_SIZE;
*iOutBufferSize=outBuffSize;
*pOutBuffer=(ubyte*)malloc(outBuffSize); // This multipliy by 10 needs to be removed...
if(NULL == *pOutBuffer)
{
return(errorOutAndCleanUp());
}
currOutBuffSize=outBuffSize;
if(DebugIt2)
printf("Allocated %d for myOutBufferSize\n",outBuffSize);
if(NULL==*pOutBuffer)
{
return(errorOutAndCleanUp());
}
allocatedOutputBuffer=*pOutBuffer;
initOutBuff((char*)*pOutBuffer,outBuffSize);
writePDFGrammarHeader();
*iOutBufferSize=totalBytesWrittenToCurrBuff;
jobOpen=job_open;
return(success);
}
/* EndJob
*
* /desc
* /param
* /return
*/
int PCLmGenerator::EndJob(void **pOutBuffer, int *iOutBufferSize)
{
int result;
if(DebugIt)
printf("genPCLm::EndJob\n");
if(NULL==allocatedOutputBuffer)
{
return(errorOutAndCleanUp());
}
*pOutBuffer = allocatedOutputBuffer;
initOutBuff((char*)*pOutBuffer,outBuffSize);
// Write PDF trailer
writePDFGrammarTrailer(currSourceWidth, currSourceHeight);
if(!DebugIt && (currCompressionDisposition==compressDCT))
{
result=remove("jpeg_chunk.jpg");
}
*iOutBufferSize=totalBytesWrittenToCurrBuff;
jobOpen=job_closed;
if(xRefTable)
{
free(xRefTable);
xRefTable=NULL;
}
if(KidsArray)
{
free(KidsArray);
KidsArray=NULL;
}
return(success);
}
/* PCLmSStartPage
* *
* * /desc
* * /param
* * /return
* */
int PCLmGenerator::StartPage(PCLmSSetup *PCLmSPageContent, bool generatePCLmS, void **pOutBuffer, int *iOutBufferSize)
{
m_pPCLmSSettings=PCLmSPageContent->PCLmSUserSettings;
return(StartPage(PCLmSPageContent->PCLmPageContent,pOutBuffer,iOutBufferSize));
}
/* StartPage
*
* /desc
* /param
* /return
*/
int PCLmGenerator::StartPage(PCLmPageSetup *PCLmPageContent, void **pOutBuffer, int *iOutBufferSize)
{
int numImageStrips;
// Save the resolution information
currRenderResolution=PCLmPageContent->destinationResolution;
*pOutBuffer = allocatedOutputBuffer;
if(currRenderResolution==res300)
currRenderResolutionInteger=300;
else if(currRenderResolution==res600)
currRenderResolutionInteger=600;
else if(currRenderResolution==res1200)
currRenderResolutionInteger=1200;
else
assert(0);
// Recalculate STANDARD_SCALE to reflect the job resolution
STANDARD_SCALE=(float)currRenderResolutionInteger/(float)STANDARD_SCALE_FOR_PDF;
// Media and source sizes are in 72 DPI; convert media information to native resolutions:
// Add 0.5 to force rounding
// Use the values set by the caller
currSourceWidth = PCLmPageContent->SourceWidthPixels;
currSourceHeight = PCLmPageContent->SourceHeightPixels;
// Save off the media information
mediaWidth=(int)(PCLmPageContent->mediaWidth);
mediaHeight=(int)(PCLmPageContent->mediaHeight);
// Use the values set by the caller
mediaWidthInPixels = PCLmPageContent->mediaWidthInPixels;
mediaHeightInPixels= PCLmPageContent->mediaHeightInPixels;
topMarginInPix=(int)(((PCLmPageContent->mediaHeightOffset/STANDARD_SCALE_FOR_PDF)*currRenderResolutionInteger)+0.50);
leftMarginInPix=(int)(((PCLmPageContent->mediaWidthOffset/STANDARD_SCALE_FOR_PDF)*currRenderResolutionInteger)+0.50);
currCompressionDisposition=PCLmPageContent->compTypeRequested;
if(DebugIt)
{
printf("genPCLm::StartPage\n");
printf(" mediaName=%s\n", PCLmPageContent->mediaSizeName);
printf(" clientLocale=%s\n",PCLmPageContent->mediaSizeName);
printf(" mediaHeight=%f\n", PCLmPageContent->mediaHeight);
printf(" mediaWidth=%f\n", PCLmPageContent->mediaWidth);
printf(" topMargin=%d\n", topMarginInPix);
printf(" leftMargin=%d\n", leftMarginInPix);
printf(" topLeftMargin=%f,%f\n",PCLmPageContent->mediaWidthOffset,PCLmPageContent->mediaHeightOffset);
printf(" sourceHeight=%f\n",PCLmPageContent->sourceHeight);
printf(" sourceWidth=%f\n", PCLmPageContent->sourceWidth);
printf(" stripHeight=%d\n", PCLmPageContent->stripHeight);
printf(" scaleFactor=%d\n", PCLmPageContent->scaleFactor);
printf(" genExtraPage=%d\n",PCLmPageContent->genExtraPage);
if(PCLmPageContent->colorContent==color_content)
printf(" colorContent=color_content\n");
else if(PCLmPageContent->colorContent==gray_content)
printf(" colorContent=gray_content\n");
else
printf(" colorContent=unknown_content\n");
if(PCLmPageContent->pageOrigin==top_left)
printf(" pageOrigin=top_left\n");
else
printf(" pageOrigin=bottom_right\n");
if(PCLmPageContent->compTypeRequested==compressRLE)
printf("compTypeRequested=RLE\n");
else if(PCLmPageContent->compTypeRequested==compressDCT)
printf("compTypeRequested=DCT\n");
else if(PCLmPageContent->compTypeRequested==compressFlate)
printf("compTypeRequested=Flate\n");
else if(PCLmPageContent->compTypeRequested==compressDefault)
printf("compTypeRequested=Flate\n");
else if(PCLmPageContent->compTypeRequested==compressNone)
printf("compTypeRequested=None\n");
if(PCLmPageContent->dstColorSpaceSpefication==deviceRGB)
printf("colorSpaceSpefication=deviceRGB\n");
else if(PCLmPageContent->dstColorSpaceSpefication==adobeRGB)
printf("colorSpaceSpefication=adobeRGB\n");
else if(PCLmPageContent->dstColorSpaceSpefication==grayScale)
printf("colorSpaceSpefication=grayScale\n");
if(PCLmPageContent->destinationResolution==res300)
printf("destinationResolution Requested=300 DPI\n");
else if(PCLmPageContent->destinationResolution==res600)
printf("destinationResolution Requested=600 DPI\n");
else if(PCLmPageContent->destinationResolution==res1200)
printf("destinationResolution Requested=1200 DPI\n");
if(PCLmPageContent->duplexDisposition==simplex)
printf("duplex disposition=Simplex\n");
else if(PCLmPageContent->duplexDisposition==duplex_longEdge)
printf("duplex disposition=Duplex_longEdge\n");
else if(PCLmPageContent->duplexDisposition==duplex_shortEdge)
printf("duplex disposition=Duplex_shortEdge\n");
}
if(strlen(PCLmPageContent->mediaSizeName))
strcpy(currMediaName,PCLmPageContent->mediaSizeName);
currStripHeight=PCLmPageContent->stripHeight;
if(!currStripHeight)
{
numImageStrips=1;
currStripHeight=currSourceHeight;
}
else
{
float numImageStripsReal=ceil((float)currSourceHeight/(float)currStripHeight); // Need to know how many strips will be inserted into PDF file
numImageStrips=(int)numImageStripsReal;
//if(topMarginInPix) // We will inject an extra image for the topMargin offset
// numImageStrips++;
}
if(PCLmPageContent->srcColorSpaceSpefication==grayScale)
srcNumComponents=1;
else
srcNumComponents=3;
if(PCLmPageContent->dstColorSpaceSpefication==grayScale)
dstNumComponents=1;
else
dstNumComponents=3;
currDuplexDisposition=PCLmPageContent->duplexDisposition;
destColorSpace=PCLmPageContent->dstColorSpaceSpefication;
// Calculate how large the output buffer needs to be based upon the page specifications
int tmp_outBuffSize=mediaWidthInPixels*currStripHeight*dstNumComponents;
if(tmp_outBuffSize>currOutBuffSize)
{
*pOutBuffer=realloc(*pOutBuffer,tmp_outBuffSize); // Realloc the pOutBuffer to the correct size
if(*pOutBuffer==NULL) //realloc failed and prev buffer not freed
{
return errorOutAndCleanUp();
}
outBuffSize=currOutBuffSize=tmp_outBuffSize;
allocatedOutputBuffer=*pOutBuffer;
if(NULL==allocatedOutputBuffer)
{
return(errorOutAndCleanUp());
}
if(DebugIt2)
printf("pOutBuffer: allocated %d bytes at 0x%lx\n",tmp_outBuffSize, (long int)*pOutBuffer);
}
initOutBuff((char*)*pOutBuffer,outBuffSize);
if(DebugIt2)
printf("Allocated %d for myOutBufferSize\n",outBuffSize);
if(DebugIt)
printf("numImageStrips=%d\n",numImageStrips);
// Keep track of the page count
pageCount++;
// If we are on a backside and doing duplex, prep for reverse strip order
if(currDuplexDisposition==duplex_longEdge && !(pageCount%2) && mirrorBackside)
{
if(DebugIt2)
printf("genPCLm.cpp: setting reverseOrder\n");
reverseOrder=true;
}
else
reverseOrder=false;
// Calculate the number of injected strips, if any
if(topMarginInPix)
{
if(topMarginInPix<=currStripHeight)
{
numFullInjectedStrips=1;
numFullScanlinesToInject=topMarginInPix;
numPartialScanlinesToInject=0;
}
else
{
numFullInjectedStrips=topMarginInPix/currStripHeight;
numFullScanlinesToInject=currStripHeight;
numPartialScanlinesToInject=topMarginInPix - (numFullInjectedStrips*currStripHeight);
}
}
writeJobTicket();
writePDFGrammarPage(mediaWidthInPixels, mediaHeightInPixels, numImageStrips, destColorSpace);
*iOutBufferSize=totalBytesWrittenToCurrBuff;
if(!scratchBuffer)
{
// We need to pad the scratchBuffer size to allow for compression expansion (RLE can create
// compressed segments that are slightly larger than the source.
scratchBuffer=(ubyte*)malloc(currStripHeight*mediaWidthInPixels*srcNumComponents*2);
if(!scratchBuffer)
return(errorOutAndCleanUp());
if(DebugIt2)
printf("scrachBuffer: Allocated %d bytes at 0x%lx\n",currStripHeight*currSourceWidth*srcNumComponents, (long int) scratchBuffer);
}
mirrorBackside=PCLmPageContent->mirrorBackside;
firstStrip=true;
return(success);
}
/* EndPage
*
* /desc
* /param
* /return
*/
int PCLmGenerator::EndPage(void **pOutBuffer, int *iOutBufferSize)
{
*pOutBuffer = allocatedOutputBuffer;
initOutBuff((char*)*pOutBuffer,outBuffSize);
*iOutBufferSize=totalBytesWrittenToCurrBuff;
// Free up the scratchbuffer at endpage, to allow the next page to be declared with a different
// size.
if(scratchBuffer)
{
free(scratchBuffer);
scratchBuffer=NULL;
}
return(success);
}
/* SkipLines
*
* /desc
* /param
* /return
*/
int PCLmGenerator::SkipLines(int iSkipLines)
{
return(success);
}
/* Encapsulate
*
* /desc
* /param
* /return
*/
int PCLmGenerator::Encapsulate(void *pInBuffer, int inBufferSize, int thisHeight, void **pOutBuffer, int *iOutBufferSize)
{
int result=0, numCompBytes;
int scanlineWidth=mediaWidthInPixels*srcNumComponents;
// int numLinesThisCall=inBufferSize/(currSourceWidth*srcNumComponents);
int numLinesThisCall=thisHeight;
void *savedInBufferPtr=NULL;
void *tmpBuffer=NULL;
void *localInBuffer;
ubyte *newStripPtr=NULL;
// writeOutputFile(currSourceWidth*3*currStripHeight, (ubyte*)pInBuffer);
if(leftoverScanlineBuffer)
{
ubyte *whereAreWe;
sint32 scanlinesThisTime;
// The leftover scanlines have already been processed (color-converted and flipped), so justscanlineWidth
// put them into the output buffer.
// Allocate a temporary buffer to copy leftover and new data into
tmpBuffer=malloc(scanlineWidth*currStripHeight);
if(!tmpBuffer)
return(errorOutAndCleanUp());
// Copy leftover scanlines into tmpBuffer
memcpy(tmpBuffer,leftoverScanlineBuffer,scanlineWidth*numLeftoverScanlines);
whereAreWe=(ubyte*)tmpBuffer+(scanlineWidth*numLeftoverScanlines);
scanlinesThisTime=currStripHeight-numLeftoverScanlines;
// Copy enough scanlines from the real inBuffer to fill out the tmpBuffer
memcpy(whereAreWe,pInBuffer,scanlinesThisTime*scanlineWidth);
// Now copy the remaining scanlines from pInBuffer to the leftoverBuffer
if(DebugIt)
printf("Leftover scanlines: numLinesThisCall=%d, currStripHeight=%d\n",numLinesThisCall,currStripHeight);
numLeftoverScanlines=thisHeight-scanlinesThisTime;
assert(leftoverScanlineBuffer);
whereAreWe=(ubyte*)pInBuffer+(scanlineWidth*numLeftoverScanlines);
memcpy(leftoverScanlineBuffer,whereAreWe,scanlineWidth*numLeftoverScanlines);
numLinesThisCall=thisHeight=currStripHeight;
savedInBufferPtr=pInBuffer;
localInBuffer=tmpBuffer;
}
else
localInBuffer=pInBuffer;
if(thisHeight > currStripHeight)
{
// Copy raw raster into leftoverScanlineBuffer
ubyte *ptr;
if(DebugIt)
printf("Leftover scanlines: numLinesThisCall=%d, currStripHeight=%d\n",numLinesThisCall,currStripHeight);
numLeftoverScanlines=thisHeight-currStripHeight;
leftoverScanlineBuffer=malloc(scanlineWidth*numLeftoverScanlines);
if(!leftoverScanlineBuffer)
return(errorOutAndCleanUp());
ptr=(ubyte *)localInBuffer+scanlineWidth*numLeftoverScanlines;
memcpy(leftoverScanlineBuffer,ptr,scanlineWidth*numLeftoverScanlines);
thisHeight=currStripHeight;
}
if(NULL==allocatedOutputBuffer)
{
return(errorOutAndCleanUp());
}
*pOutBuffer = allocatedOutputBuffer;
initOutBuff((char*)*pOutBuffer,outBuffSize);
if(currDuplexDisposition==duplex_longEdge && !(pageCount%2))
{
if(mirrorBackside)
prepImageForBacksideDuplex((ubyte*)localInBuffer, numLinesThisCall, currSourceWidth, srcNumComponents);
}
if(destColorSpace==grayScale && (sourceColorSpace==deviceRGB || sourceColorSpace==adobeRGB))
{
colorConvertSource(sourceColorSpace, grayScale, (ubyte*)localInBuffer, currSourceWidth, numLinesThisCall);
// Adjust the scanline width accordingly
scanlineWidth = mediaWidthInPixels * dstNumComponents;
}
if(leftMarginInPix)
{
newStripPtr=shiftStripByLeftMargin((ubyte*)localInBuffer, currSourceWidth, currStripHeight, numLinesThisCall, mediaWidthInPixels, leftMarginInPix, destColorSpace);
// newStripPtr=shiftStripByLeftMargin((ubyte*)localInBuffer, currSourceWidth, currStripHeight, mediaWidthInPixels, leftMarginInPix, destColorSpace);
#if 0
if(sourceColorSpace==grayScale)
writeOutputFile(currStripHeight*mediaWidthInPixels,(ubyte*)newStripPtr);
else
writeOutputFile(3*currStripHeight*mediaWidthInPixels,(ubyte*)newStripPtr);
#endif
}
#ifdef SUPPORT_WHITE_STRIPS
bool whiteStrip=isWhiteStrip(pInBuffer, thisHeight*currSourceWidth*srcNumComponents);
if(DebugIt2)
{
if(whiteStrip)
printf("Found white strip\n");
else
printf("Found non-white strip\n");
}
#else
bool whiteStrip=false;
#endif
if(currCompressionDisposition==compressDCT)
{
if(firstStrip && topMarginInPix)
{
ubyte whitePt=0xff;
ubyte *tmpStrip=(ubyte*)malloc(scanlineWidth*topMarginInPix);
memset(tmpStrip,whitePt,scanlineWidth*topMarginInPix);
for(sint32 stripCntr=0; stripCntr<numFullInjectedStrips;stripCntr++)
{
write_JPEG_Buff (scratchBuffer, JPEG_QUALITY, mediaWidthInPixels, (sint32)numFullScanlinesToInject, (JSAMPLE*)tmpStrip, currRenderResolutionInteger, destColorSpace, &numCompBytes);
injectJPEG((char*)scratchBuffer, mediaWidthInPixels, (sint32)numFullScanlinesToInject, numCompBytes, destColorSpace, true /*white*/ );
}
if(numPartialScanlinesToInject)
{
// Handle the leftover strip
write_JPEG_Buff (scratchBuffer, JPEG_QUALITY, mediaWidthInPixels, numPartialScanlinesToInject, (JSAMPLE*)tmpStrip, currRenderResolutionInteger, destColorSpace, &numCompBytes);
injectJPEG((char*)scratchBuffer, mediaWidthInPixels, numPartialScanlinesToInject, numCompBytes, destColorSpace, true /*white*/ );
}
free(tmpStrip);
firstStrip=false;
}
/*The "if 1" block below pads the incoming buffer from numLinesThisCall to strip_height assuming that it has
* that much extra space. Also "else" block after this "if 1" block was used before; when for
* JPEG also, there was no padding to strip_height. Retaining it just in case, in future, the padding
* has to be removed*/
#if 1
// We are always going to compress the full strip height, even though the image may be less;
// this allows the compressed images to be symetric
if(numLinesThisCall<currStripHeight)
{
sint32 numLeftoverBytes=(currStripHeight-numLinesThisCall)*currSourceWidth*3;
sint32 numImagedBytes =numLinesThisCall*currSourceWidth*3;
// End-of-page: we have to white-out the unused section of the source image
memset((ubyte*)localInBuffer+numImagedBytes, 0xff, numLeftoverBytes);
}
if(newStripPtr)
{
write_JPEG_Buff (scratchBuffer, JPEG_QUALITY, mediaWidthInPixels, currStripHeight, (JSAMPLE*)newStripPtr, currRenderResolutionInteger, destColorSpace, &numCompBytes);
free(newStripPtr);
}
else
{
write_JPEG_Buff (scratchBuffer, JPEG_QUALITY, mediaWidthInPixels, currStripHeight, (JSAMPLE*)localInBuffer, currRenderResolutionInteger, destColorSpace, &numCompBytes);
}
if(DebugIt2)
writeOutputFile(numCompBytes, scratchBuffer);
injectJPEG((char*)scratchBuffer, mediaWidthInPixels, currStripHeight, numCompBytes, destColorSpace, whiteStrip );
#else
if(newStripPtr)
{
write_JPEG_Buff (scratchBuffer, JPEG_QUALITY, mediaWidthInPixels, numLinesThisCall, (JSAMPLE*)newStripPtr, currRenderResolutionInteger, destColorSpace, &numCompBytes);
free(newStripPtr);
}
else
write_JPEG_Buff (scratchBuffer, JPEG_QUALITY, mediaWidthInPixels, numLinesThisCall, (JSAMPLE*)localInBuffer, currRenderResolutionInteger, destColorSpace, &numCompBytes);
if(DebugIt2)
writeOutputFile(numCompBytes, scratchBuffer);
injectJPEG((char*)scratchBuffer, mediaWidthInPixels, numLinesThisCall, numCompBytes, destColorSpace, whiteStrip );
#endif
}
else if(currCompressionDisposition==compressFlate)
{
uint32 len=numLinesThisCall*scanlineWidth;
uLongf destSize=len;
if(firstStrip && topMarginInPix)
{
ubyte whitePt=0xff;
// We need to inject a blank image-strip with a height==topMarginInPix
ubyte *tmpStrip=(ubyte*)malloc(scanlineWidth*topMarginInPix);
uLongf tmpDestSize=destSize;
memset(tmpStrip,whitePt,scanlineWidth*topMarginInPix);
for(sint32 stripCntr=0; stripCntr<numFullInjectedStrips;stripCntr++)
{
result=compress((Bytef*)scratchBuffer,&tmpDestSize, (const Bytef*)tmpStrip, scanlineWidth*numFullScanlinesToInject);
injectLZStrip((ubyte*)scratchBuffer, tmpDestSize, mediaWidthInPixels, numFullScanlinesToInject, destColorSpace, true /*white*/ );
}
if(numPartialScanlinesToInject)
{
result=compress((Bytef*)scratchBuffer,&tmpDestSize, (const Bytef*)tmpStrip, scanlineWidth*numPartialScanlinesToInject);
injectLZStrip((ubyte*)scratchBuffer, tmpDestSize, mediaWidthInPixels, numPartialScanlinesToInject, destColorSpace, true /*white*/ );
}
free(tmpStrip);
firstStrip=false;
}
if(newStripPtr)
{
result=compress((Bytef*)scratchBuffer,&destSize,(const Bytef*)newStripPtr,scanlineWidth*numLinesThisCall);
if(DebugIt2)
writeOutputFile(destSize, scratchBuffer);
if(DebugIt2)
{
printf("Allocated zlib dest buffer of size %d\n",numLinesThisCall*scanlineWidth);
printf("zlib compression return result=%d, compSize=%d\n",result,(int)destSize);
}
free(newStripPtr);
}
else
{
// Dump the source data
// writeOutputFile(scanlineWidth*numLinesThisCall, (ubyte *)localInBuffer);
result=compress((Bytef*)scratchBuffer, &destSize, (const Bytef*)localInBuffer, scanlineWidth*numLinesThisCall);
if(DebugIt2)
writeOutputFile(destSize, scratchBuffer);
if(DebugIt2)
{
printf("Allocated zlib dest buffer of size %d\n",numLinesThisCall*scanlineWidth);
printf("zlib compression return result=%d, compSize=%d\n",result,(int)destSize);
}
}
injectLZStrip(scratchBuffer,destSize, mediaWidthInPixels, numLinesThisCall, destColorSpace, whiteStrip);
}
else if(currCompressionDisposition==compressRLE)
{
#ifdef RLE_SUPPORTED
int compSize;
if(firstStrip && topMarginInPix)
{
ubyte whitePt=0xff;
// We need to inject a blank image-strip with a height==topMarginInPix
ubyte *tmpStrip=(ubyte*)malloc(scanlineWidth*topMarginInPix);
memset(tmpStrip,whitePt,scanlineWidth*topMarginInPix);
for(sint32 stripCntr=0; stripCntr<numFullInjectedStrips;stripCntr++)
{
compSize=RLEEncodeImage((ubyte*)tmpStrip, scratchBuffer, scanlineWidth*numFullScanlinesToInject);
injectRLEStrip((ubyte*)scratchBuffer, compSize, mediaWidthInPixels, numFullScanlinesToInject, destColorSpace, true /*white*/);
}
if(numPartialScanlinesToInject)
{
compSize=RLEEncodeImage((ubyte*)tmpStrip, scratchBuffer, scanlineWidth*numPartialScanlinesToInject);
injectRLEStrip((ubyte*)scratchBuffer, compSize, mediaWidthInPixels, numPartialScanlinesToInject, destColorSpace, true /*white*/);
}
free(tmpStrip);
firstStrip=false;
}
if(newStripPtr)
{
compSize=RLEEncodeImage((ubyte*)newStripPtr, scratchBuffer, scanlineWidth*numLinesThisCall);
free(newStripPtr);
}
else
compSize=RLEEncodeImage((ubyte*)localInBuffer, scratchBuffer, scanlineWidth*numLinesThisCall);
if(DebugIt2)
{
printf("Allocated rle dest buffer of size %d\n",numLinesThisCall*scanlineWidth);
printf("rle compression return size=%d=%d\n",result,(int)compSize);
}
injectRLEStrip(scratchBuffer, compSize, mediaWidthInPixels, numLinesThisCall, destColorSpace, whiteStrip);
#else
assert(0);
#endif
}
else
assert(0);
*iOutBufferSize=totalBytesWrittenToCurrBuff;
if(savedInBufferPtr)
pInBuffer=savedInBufferPtr;
if(tmpBuffer)
free(tmpBuffer);
return(success);
}
int PCLmGenerator::get_pclm_media_dimensions(const char *mediaRequested, PCLmPageSetup *myPageInfo)
{
int mediaNumEntries=sizeof(MasterMediaSizeTable)/sizeof(struct MediaSizeTableElement);
int i=0;
int result = 99;
int iRenderResolutionInteger = 0;
if(myPageInfo->destinationResolution==res300)
iRenderResolutionInteger=300;
else if(myPageInfo->destinationResolution==res600)
iRenderResolutionInteger=600;
else if(myPageInfo->destinationResolution==res1200)
iRenderResolutionInteger=1200;
else
assert(0);
do
{
if(myPageInfo == NULL)
{
continue;
}
for(i=0; i<mediaNumEntries; i++)
{
if(strcasecmp(mediaRequested,MasterMediaSizeTable[i].PCL6Name)==0)
{
myPageInfo->mediaWidth = floorf(_MI_TO_POINTS(MasterMediaSizeTable[i].WidthInInches));
myPageInfo->mediaHeight = floorf(_MI_TO_POINTS(MasterMediaSizeTable[i].HeightInInches));
myPageInfo->mediaWidthInPixels = floorf(_MI_TO_PIXELS(MasterMediaSizeTable[i].WidthInInches, iRenderResolutionInteger));
myPageInfo->mediaHeightInPixels = floorf(_MI_TO_PIXELS(MasterMediaSizeTable[i].HeightInInches, iRenderResolutionInteger));
result = i;
if(DebugIt){
printf("PCLmGenerator get_pclm_media_size(): match found: %s, %s\n", mediaRequested, MasterMediaSizeTable[i].PCL6Name);
printf("PCLmGenerator Calculated mediaWidth=%f\n",myPageInfo->mediaWidth);
printf("PCLmGenerator Calculated mediaHeight=%f\n",myPageInfo->mediaHeight);
}
break; // we found a match, so break out of loop
}
}
}
while(0);
if (i == mediaNumEntries)
{
// media size not found, defaulting to letter
printf("PCLmGenerator get_pclm_media_size(): media size, %s, NOT FOUND, setting to letter", mediaRequested);
result = get_pclm_media_dimensions("LETTER", myPageInfo);
}
return(result);
}
/* FreeBuffer
*
* /desc
* /param
* /return
*/
void PCLmGenerator::FreeBuffer(void *pBuffer)
{
if(jobOpen==job_closed && pBuffer)
{
if(pBuffer==allocatedOutputBuffer)
{
allocatedOutputBuffer=NULL;
}
free(pBuffer);
}
pBuffer=NULL;
}
| 33.424034 | 191 | 0.666453 | [
"object"
] |
3dadd111f86dc0d2b4605fd20f4eb784815bea6b | 11,335 | hpp | C++ | include/poplin/Norms.hpp | giantchen2012/poplibs | 2bc6b6f3d40863c928b935b5da88f40ddd77078e | [
"MIT"
] | 1 | 2021-02-23T05:58:24.000Z | 2021-02-23T05:58:24.000Z | include/poplin/Norms.hpp | giantchen2012/poplibs | 2bc6b6f3d40863c928b935b5da88f40ddd77078e | [
"MIT"
] | null | null | null | include/poplin/Norms.hpp | giantchen2012/poplibs | 2bc6b6f3d40863c928b935b5da88f40ddd77078e | [
"MIT"
] | null | null | null | // Copyright (c) 2019 Graphcore Ltd. All rights reserved.
/** \file
*
* Functions to support normalising values in a tensor.
*
*/
#ifndef poplin_Norms_hpp
#define poplin_Norms_hpp
#include <poplar/Graph.hpp>
#include <poplar/Program.hpp>
#include <tuple>
namespace poplin {
// Note that the functionality here should move to popnn once operations on
// broadcasting some of the dimensions is added. Currently these operations are
// optimised for tensors produced by convolutions/matrix multiplications.
// (see T6054)
/// Create and map the per-channel multiplicative gamma parameter tensor used
/// for normalisation in convolution layers.
/// \param graph The graph with the activations and gamma tensor.
/// \param acts The activations tensor has shape `[N][C][..F..]`
/// where:
/// - `N` is the batch size
/// - `C` is the number of channels
/// - `..F..` is dimensions of a N-dimensional field.
/// \param type The type of the output tensor.
/// \param debugContext Optional debug information.
/// \returns Gamma vector of dimension `C`.
poplar::Tensor createNormGamma(poplar::Graph &graph, const poplar::Tensor &acts,
const poplar::Type &type,
const poplar::DebugContext &debugContext = {});
/// Create and map the per-channel multiplicative gamma parameter tensor used
/// for normalisation in convolution layers.
/// \param graph The graph with the activations and gamma tensor.
/// \param acts The activations tensor has shape `[N][C][..F..]`
/// where:
/// - `N` is the batch size
/// - `C` is the number of channels
/// - `..F..` is dimensions of a N-dimensional field.
/// \param debugContext Optional debug information.
/// \returns Gamma vector of dimension `C`.
poplar::Tensor createNormGamma(poplar::Graph &graph, const poplar::Tensor &acts,
const poplar::DebugContext &debugContext = {});
/// Create and map the per-channel additive beta parameter tensor used for
/// normalisation in convolution layers.
/// \param graph The graph with the activations and beta tensor.
/// \param acts The activations tensor has shape `[N][C][..F..]`
/// where:
/// - `N` is the batch size
/// - `C` is the number of channels
/// - `..F..` is dimensions of a N-dimensional field
/// \param type The type of the output tensor.
/// \param debugContext Optional debug information.
/// \returns Beta vector of dimension `C`.
poplar::Tensor createNormBeta(poplar::Graph &graph, const poplar::Tensor &acts,
const poplar::Type &type,
const poplar::DebugContext &debugContext = {});
/// Create and map the per-channel additive beta parameter tensor used for
/// normalisation in convolution layers.
/// \param graph The graph with the activations and beta tensor.
/// \param acts The activations tensor has shape `[N][C][..F..]`
/// where:
/// - `N` is the batch size
/// - `C` is the number of channels
/// - `..F..` is dimensions of a N-dimensional field
/// \param debugContext Optional debug information.
/// \returns Beta vector of dimension `C`.
poplar::Tensor createNormBeta(poplar::Graph &graph, const poplar::Tensor &acts,
const poplar::DebugContext &debugContext = {});
/// Creates a tensor pair of normalisation parameters (gamma, beta).
/// \param graph The graph with the activations and beta/gamma
/// tensors.
/// \param acts The activations tensor has shape `[N][C][..F..]`
/// where:
/// - `N` is the batch size
/// - `C` is the number of channels
/// - `..F..` is dimensions of a N-dimensional field
/// \param debugContext Optional debug information.
/// \returns A pair of vectors of dimension `C`.
std::pair<poplar::Tensor, poplar::Tensor>
createNormParams(poplar::Graph &graph, const poplar::Tensor &acts,
const poplar::DebugContext &debugContext = {});
/// Compute the normalisation statistics from the activations tensor. The
/// activations tensor is of shape `[N][C][..F..]`. The mean and inverse
/// standard
/// deviation is computed over dimensions `{[N] [..F..]}` and vectors of
/// length `C` are returned as estimates.
///
/// The input activations tensor must be rearranged such that statistics are
/// computed for `C` channels.
/// \param graph The graph in which the computation is performed.
/// \param actsUngrouped The activation with shape `[N][C][..F..]`
/// where:
/// - `N` is the batch size
/// - `C` is the number of channels
/// - `..F..` is dimensions of a N-dimensional field.
/// \param eps The epsilon added to the variance to avoid divide by
/// zero.
/// \param prog A program sequence that the code to
/// perform the normalisation will be appended to.
/// \param unbiasedVarEstimate
/// Compute unbiased variance estimate.
/// \param stableAlgo If true, computes the mean first and subtracts
/// the activations by it before computing the variance.
/// The implementation with this flag set to true is
// slower than when set to false.
/// \param partialsType Poplar type used for partials.
/// \param debugContext Optional debug information.
///
/// \returns A vector pair with mean and inverse standard deviation.
std::pair<poplar::Tensor, poplar::Tensor>
normStatistics(poplar::Graph &graph, const poplar::Tensor &actsUngrouped,
float eps, poplar::program::Sequence &prog,
bool unbiasedVarEstimate, bool stableAlgo = false,
const poplar::Type &partialsType = poplar::FLOAT,
const poplar::DebugContext &debugContext = {});
/// Compute the whitened activations using the supplied mean and inverse
/// standard deviation.
///
/// The input activations undergo a prior rearrangement such that `C`
/// is the size of the statistics \p mean and \p iStdDev tensors.
/// \param graph The graph which the computation is in.
/// \param acts The activations tensor of shape [N][C][..F..].
/// \param mean Mean of the activations with dimension C.
/// \param iStdDev Inverse standard deviation with dimension C.
/// \param prog A program sequence that the code to
/// perform the normalisation will be appended to.
/// \param debugContext Optional debug information.
///
/// \returns Whitened activations.
poplar::Tensor normWhiten(poplar::Graph &graph, const poplar::Tensor &acts,
const poplar::Tensor &mean,
const poplar::Tensor &iStdDev,
poplar::program::Sequence &prog,
const poplar::DebugContext &debugContext = {});
/// Computes the normalised output from whitened activations.
/// \param graph The graph to which the normalisaton operation is added.
/// \param actsWhitened Whitened activations.
/// \param gamma Per-channel multiplicative normalisation parameter.
/// \param beta Per-channel additive normalisation parameter.
/// \param prog A program sequence that the code to
/// perform the normalisation will be appended to.
/// \param debugContext Optional debug information.
poplar::Tensor normalise(poplar::Graph &graph,
const poplar::Tensor &actsWhitened,
const poplar::Tensor &gamma,
const poplar::Tensor &beta,
poplar::program::Sequence &prog,
const poplar::DebugContext &debugContext = {});
/// Compute gradients with respect to parameters required for parameter update.
/// \param graph The graph to which the normalisaton operation is added.
/// \param actsWhitened Whitened activations.
/// \param gradsIn Input gradients to the normalisation layer.
/// \param prog A program sequence that the code to
/// perform the normalisation will be appended to.
/// \param partialsType The intermediate type kept in the computation.
/// \param debugContext Optional debug information.
std::pair<poplar::Tensor, poplar::Tensor>
normParamGradients(poplar::Graph &graph, const poplar::Tensor &actsWhitened,
const poplar::Tensor &gradsIn,
poplar::program::Sequence &prog,
const poplar::Type &partialsType = poplar::FLOAT,
const poplar::DebugContext &debugContext = {});
/// Propagate the gradients through the normalisation layer.
/// \param graph The graph to which the normalisaton operation is added.
/// \param gradsIn Input gradients to the normalisation layer.
/// \param gamma Multiplicative parameter used in the normalisation.
/// \param prog A program sequence that the code to
/// perform the normalisation will be appended to.
/// \param debugContext Optional debug information.
poplar::Tensor normGradients(poplar::Graph &graph,
const poplar::Tensor &gradsIn,
const poplar::Tensor &gamma,
poplar::program::Sequence &prog,
const poplar::DebugContext &debugContext = {});
/// Propagate the gradients through the norm statistics layer. The input to the
/// layer is the output gradients from the normalisation layer. The whitened
/// activations and the input gradients must have undergone a prior
/// rearrangement such that the channel dimension has the same elements as
/// \p invStdDev.
/// \param graph The graph to which the normalisaton operation is added.
/// \param actsWhitened Forward whitened activations.
/// \param gradsIn Input gradients to the normalisation layer.
/// \param invStdDev Inverse standard deviation from norm statistics.
/// \param prog A program sequence that the code to
/// perform the normalisation will be appended to.
/// \param debugContext Optional debug information.
poplar::Tensor normStatisticsGradients(
poplar::Graph &graph, const poplar::Tensor &actsWhitened,
const poplar::Tensor &gradsIn, const poplar::Tensor &invStdDev,
poplar::program::Sequence &prog,
const poplar::Type &partialsType = poplar::FLOAT,
const poplar::DebugContext &debugContext = {});
} // namespace poplin
#endif // poplin_Norms_hpp
| 53.720379 | 80 | 0.608028 | [
"shape",
"vector"
] |
3db492bcd0bd0234d4548e1ad87fa90cfd9981d5 | 4,809 | cpp | C++ | swap.cpp | ibaned/omega_h_v1 | 9ab9efca33d66e4411f87206a7bd1534cec116e4 | [
"MIT"
] | null | null | null | swap.cpp | ibaned/omega_h_v1 | 9ab9efca33d66e4411f87206a7bd1534cec116e4 | [
"MIT"
] | null | null | null | swap.cpp | ibaned/omega_h_v1 | 9ab9efca33d66e4411f87206a7bd1534cec116e4 | [
"MIT"
] | null | null | null | #include "swap.hpp"
#include <cassert>
#include <cstdio>
#include "arrays.hpp"
#include "comm.hpp"
#include "doubles.hpp"
#include "ghost_mesh.hpp"
#include "indset.hpp"
#include "inherit.hpp"
#include "ints.hpp"
#include "loop.hpp"
#include "mark.hpp"
#include "mesh.hpp"
#include "parallel_mesh.hpp"
#include "parallel_modify.hpp"
#include "quality.hpp"
#include "swap_conserve.hpp"
#include "swap_fit.hpp"
#include "swap_qualities.hpp"
#include "swap_topology.hpp"
#include "tables.hpp"
namespace omega_h {
static void swap_ents(
struct mesh* m,
struct mesh* m_out,
unsigned ent_dim,
unsigned const* indset,
unsigned const* ring_sizes)
{
unsigned nedges = mesh_count(m, 1);
unsigned* gen_offset_of_edges = get_swap_topology_offsets(
ent_dim, nedges, indset, ring_sizes);
unsigned ngen_ents = array_at(gen_offset_of_edges, nedges);
unsigned* verts_of_gen_ents = mesh_swap_topology(m, ent_dim,
indset, gen_offset_of_edges);
unsigned* old_ents = mesh_mark_up(m, 1, ent_dim, indset);
unsigned nents = mesh_count(m, ent_dim);
unsigned* same_ents = uints_negate(old_ents, nents);
loop_free(old_ents);
unsigned* same_ent_offsets = uints_exscan(same_ents, nents);
loop_free(same_ents);
unsigned const* verts_of_ents = mesh_ask_down(m, ent_dim, 0);
unsigned nents_out;
unsigned* verts_of_ents_out;
concat_verts_of_ents(ent_dim, nents, ngen_ents, verts_of_ents,
same_ent_offsets, verts_of_gen_ents,
&nents_out, &verts_of_ents_out);
loop_free(verts_of_gen_ents);
mesh_set_ents(m_out, ent_dim, nents_out, verts_of_ents_out);
if (mesh_get_rep(m) == MESH_FULL) {
unsigned ndoms[4];
unsigned* prods_of_doms_offsets[4];
setup_swap(m, ent_dim, gen_offset_of_edges, same_ent_offsets,
ndoms, prods_of_doms_offsets);
inherit_class(m, m_out, ent_dim, ndoms, prods_of_doms_offsets);
}
if (mesh_is_parallel(m))
inherit_globals(m, m_out, ent_dim, same_ent_offsets);
if (ent_dim == mesh_dim(m)) {
swap_conserve(m, m_out, gen_offset_of_edges, same_ent_offsets);
swap_fit(m, m_out, gen_offset_of_edges, same_ent_offsets);
}
loop_free(gen_offset_of_edges);
loop_free(same_ent_offsets);
}
static void swap_interior(
struct mesh* m)
{
unsigned const* indset = mesh_find_tag(m, 1, "indset")->d.u32;
unsigned nedges = mesh_count(m, 1);
unsigned long total = comm_add_ulong(uints_sum(indset, nedges));
unsigned const* ring_sizes = mesh_find_tag(m, 1, "ring_size")->d.u32;
unsigned elem_dim = mesh_dim(m);
/* vertex handling */
unsigned nverts = mesh_count(m, 0);
struct mesh* m_out = new_mesh(elem_dim, mesh_get_rep(m), mesh_is_parallel(m));
mesh_set_ents(m_out, 0, nverts, 0);
if (mesh_is_parallel(m))
mesh_tag_globals(m, 0);
copy_tags(mesh_tags(m, 0), mesh_tags(m_out, 0), nverts);
if (mesh_is_parallel(m))
mesh_parallel_from_tags(m_out, 0);
/* end vertex handling */
if (mesh_get_rep(m) == MESH_REDUCED)
swap_ents(m, m_out, mesh_dim(m), indset, ring_sizes);
else
for (unsigned d = 1; d <= mesh_dim(m); ++d)
swap_ents(m, m_out, d, indset, ring_sizes);
if (!comm_rank())
printf("swapped %10lu %s\n", total, get_ent_name(1, total));
overwrite_mesh(m, m_out);
}
static unsigned swap_common(
struct mesh* m,
unsigned* candidates)
{
unsigned nedges = mesh_count(m, 1);
if (!comm_max_uint(uints_max(candidates, nedges))) {
loop_free(candidates);
return 0;
}
mesh_unmark_boundary(m, 1, candidates);
if (!comm_max_uint(uints_max(candidates, nedges))) {
loop_free(candidates);
return 0;
}
double* edge_quals;
unsigned* ring_sizes;
mesh_swap_qualities(m, candidates, &edge_quals, &ring_sizes);
mesh_conform_array(m, 1, 1, &candidates);
mesh_conform_array(m, 1, 1, &edge_quals);
mesh_conform_array(m, 1, 1, &ring_sizes);
if (!comm_max_uint(uints_max(candidates, nedges))) {
loop_free(candidates);
loop_free(edge_quals);
loop_free(ring_sizes);
return 0;
}
unsigned* indset = mesh_find_indset(m, 1, candidates, edge_quals);
loop_free(candidates);
loop_free(edge_quals);
mesh_add_tag(m, 1, TAG_U32, "indset", 1, indset);
mesh_add_tag(m, 1, TAG_U32, "ring_size", 1, ring_sizes);
if (mesh_is_parallel(m)) {
set_own_ranks_by_indset(m, 1);
unghost_mesh(m);
}
swap_interior(m);
return 1;
}
unsigned swap_slivers(
struct mesh* m,
double good_qual,
unsigned nlayers)
{
assert(mesh_dim(m) == 3);
if (mesh_is_parallel(m)) {
assert(mesh_get_rep(m) == MESH_FULL);
mesh_ensure_ghosting(m, 1);
}
unsigned elem_dim = mesh_dim(m);
unsigned* slivers = mesh_mark_slivers(m, good_qual, nlayers);
unsigned* candidates = mesh_mark_down(m, elem_dim, 1, slivers);
loop_free(slivers);
unsigned ret = swap_common(m, candidates);
return ret;
}
}
| 30.630573 | 80 | 0.713454 | [
"mesh"
] |
3db69c5765323f0aa0d5d46d8b2a697025d61363 | 1,462 | cc | C++ | tests/iohal/test_sparse_pmem.cc | MarkMankins/libosi | 2d67ed8066098bc798a53c06dffb5ba257d89bde | [
"BSD-3-Clause"
] | 3 | 2021-02-23T09:13:07.000Z | 2021-08-13T14:15:06.000Z | tests/iohal/test_sparse_pmem.cc | MarkMankins/libosi | 2d67ed8066098bc798a53c06dffb5ba257d89bde | [
"BSD-3-Clause"
] | 3 | 2021-12-02T17:51:48.000Z | 2022-03-04T20:02:32.000Z | tests/iohal/test_sparse_pmem.cc | MarkMankins/libosi | 2d67ed8066098bc798a53c06dffb5ba257d89bde | [
"BSD-3-Clause"
] | 2 | 2021-12-07T00:42:31.000Z | 2022-03-04T15:42:12.000Z | #include "sparse_pmem.h"
#include "gtest/gtest.h"
// Sanity check that the object can be included, allocated, and freed
TEST(SparsePmemTest, PmemAllocate)
{
struct PhysicalMemory* pmem = createSparsePhysicalMemory(2048);
ASSERT_TRUE(pmem != nullptr) << "Could not allocate physical memory object!";
pmem->free(pmem);
}
TEST(SparsePmemTest, PmemSparseRead)
{
uint8_t target_data[8] = {0x12, 0x43, 0x99, 0xa1, 0x00, 0xb2, 0x00, 0x00};
// Initialize physical memory with some data
struct PhysicalMemory* pmem = createSparsePhysicalMemory(2048 * 1024);
auto spm = (SparsePhysicalMemory*)pmem->opaque;
spm->set_range(1024, target_data, 6);
// Read it back out
uint8_t output_data[8] = {0};
ASSERT_TRUE(pmem->read(pmem, 1024, output_data, 8))
<< "Failed to read physical memory";
// Make sure it matches
bool failed = false;
for (size_t ix = 0; ix < 8; ++ix) {
failed = failed | (target_data[ix] != output_data[ix]);
}
ASSERT_TRUE(!failed) << "Failed to read data back out";
pmem->free(pmem);
}
TEST(SparsePmemTest, PmemOOBRead)
{
size_t max_addr = 2048 * 1024;
struct PhysicalMemory* pmem = createSparsePhysicalMemory(max_addr);
// Read it back out
uint8_t* output_data = (uint8_t*)calloc(1, 0x10);
ASSERT_TRUE(!pmem->read(pmem, max_addr - 0x8, output_data, 16))
<< "Failed to read physical memory";
free(output_data);
pmem->free(pmem);
}
| 30.458333 | 81 | 0.671683 | [
"object"
] |
3dc358ce154921061631aa64b958940901f5d701 | 23,755 | cc | C++ | hyperion/synthesis/FFT.cc | mpokorny/legms | 8ea5d1899ac5e2658ebe481b706430474685bb2d | [
"Apache-2.0"
] | 2 | 2021-02-03T00:40:55.000Z | 2021-02-03T13:30:31.000Z | hyperion/synthesis/FFT.cc | mpokorny/legms | 8ea5d1899ac5e2658ebe481b706430474685bb2d | [
"Apache-2.0"
] | null | null | null | hyperion/synthesis/FFT.cc | mpokorny/legms | 8ea5d1899ac5e2658ebe481b706430474685bb2d | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2020 Associated Universities, Inc. Washington DC, USA.
*
* 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 <hyperion/synthesis/FFT.h>
#include <hyperion/utility.h>
#include <mappers/default_mapper.h>
#include <limits>
using namespace hyperion;
using namespace hyperion::synthesis;
using namespace Legion;
Mutex hyperion::synthesis::fftw_mutex;
Mutex hyperion::synthesis::fftwf_mutex;
#if !HAVE_CXX17
const size_t Mutex::default_count;
const constexpr char* FFT::in_place_task_name;
const constexpr char* FFT::create_plan_task_name;
const constexpr char* FFT::execute_fft_task_name;
const constexpr char* FFT::destroy_plan_task_name;
const constexpr char* FFT::rotate_arrays_task_name;
#endif
TaskID FFT::in_place_task_id;
TaskID FFT::create_plan_task_id;
TaskID FFT::execute_fft_task_id;
TaskID FFT::destroy_plan_task_id;
TaskID FFT::rotate_arrays_task_id;
struct Params {
std::vector<int> n;
std::vector<int> nembed;
int dist;
int stride;
int howmany;
void* buffer;
};
/**
* check for matching values in first n dimensions of to points
*/
template <unsigned N>
static bool
prefixes_match(const Point<N>& p0, const Point<N>& p1, int n) {
if (n >= 0) {
for (size_t i = 0; i < std::min(static_cast<unsigned>(n), N); ++i)
if (p0[i] != p1[i])
return false;
}
return true;
}
/**
* get parameters for FFTW or cuFFT for an array of type T, rank array_rank in
* a field fid of a region with rank N
*/
template <typename F, int N>
static Params
get_paramsN(
Runtime* rt,
const RegionRequirement& req,
const PhysicalRegion& region,
const FieldID& fid,
unsigned array_rank) {
assert(array_rank > 0);
Params result;
Rect<N> rect(rt->get_index_space_domain(req.region.get_index_space()));
Rect<N> region_rect(region);
result.howmany = 1;
for (size_t i = 0; i < N; ++i) {
auto len = rect.hi[i] - rect.lo[i] + 1;
if (i < N - array_rank) {
result.howmany *= len;
} else {
result.n.push_back(len);
result.nembed.push_back(region_rect.hi[i] - region_rect.lo[i] + 1);
}
}
const FieldAccessor<
READ_ONLY,
F,
N,
coord_t,
AffineAccessor<F, N, coord_t>,
HYPERION_CHECK_BOUNDS> acc(region, fid);
PointInRectIterator<N> pir(rect, false);
Point<N> pt0 = *pir;
const F* f0 = acc.ptr(*pir);
result.buffer = const_cast<F*>(f0);
pir++;
if (pir() && prefixes_match<N>(pt0, *pir, N - array_rank)) {
result.stride = acc.ptr(*pir) - f0;
pir++;
while (pir() && prefixes_match<N>(pt0, *pir, N - array_rank))
pir++;
if (pir())
result.dist = acc.ptr(*pir) - f0;
else
result.dist = 0;
} else {
result.stride = 0;
result.dist = 0;
}
return result;
}
/**
* get parameters for FFTW or cuFFT for an array of type T, rank array_rank in
* a field fid of a region with variable rank
*/
template <typename F>
static Params
get_params(
Runtime* rt,
const RegionRequirement& req,
const PhysicalRegion& region,
const FieldID& fid,
unsigned array_rank) {
switch (req.region.get_index_space().get_dim()) {
#define GET_PARAMSN(N) \
case N: { \
return get_paramsN<F, N>(rt, req, region, fid, array_rank); \
break; \
}
HYPERION_FOREACH_N(GET_PARAMSN);
default:
assert(false);
return Params();
break;
}
}
/**
* coordinate the computation of an FFT through sub-tasks that create a plan,
* execute the plan, and finally destroy the plan
*/
static void
in_place(
const Task* task,
const std::vector<PhysicalRegion>& regions,
Context ctx,
Runtime* rt,
bool enable_inlined_planner_subtasks) {
auto same_req = task->regions[0];
same_req.tag = Mapping::DefaultMapper::MappingTags::SAME_ADDRESS_SPACE;
// create the FFT plan
const FFT::Args& args = *static_cast<const FFT::Args*>(task->args);
TaskLauncher
plan_creator(FFT::create_plan_task_id, TaskArgument(&args, sizeof(args)));
plan_creator.add_region_requirement(same_req);
plan_creator.enable_inlining = enable_inlined_planner_subtasks;
auto plan = rt->execute_task(ctx, plan_creator);
// if args.rotate_in is true, then rotate the array half-sections
if (args.rotate_in) {
TaskLauncher rotator(
FFT::rotate_arrays_task_id,
TaskArgument(&args.desc, sizeof(args.desc)));
rotator.add_region_requirement(task->regions[0]);
rt->execute_task(ctx, rotator);
}
// execute the FFT plan, dependency on plan future for sequencing
TaskLauncher executor(
FFT::execute_fft_task_id,
TaskArgument(
&enable_inlined_planner_subtasks,
sizeof(enable_inlined_planner_subtasks)));
executor.add_region_requirement(same_req);
executor.add_future(plan);
auto rc = rt->execute_task(ctx, executor);
// destroy the FFT plan, use dependency on rc future for sequencing, and
// supply the plan in a future for convenience
if (!enable_inlined_planner_subtasks) {
TaskLauncher plan_destroyer(FFT::destroy_plan_task_id, TaskArgument());
plan_destroyer.add_future(plan);
plan_destroyer.add_future(rc);
rt->execute_task(ctx, plan_destroyer);
}
// if args.rotate_out is true, then rotate the array half-sections
if (args.rotate_out) {
TaskLauncher rotator(
FFT::rotate_arrays_task_id,
TaskArgument(&args.desc, sizeof(args.desc)));
rotator.add_region_requirement(task->regions[0]);
rt->execute_task(ctx, rotator);
}
}
void
FFT::fftw_in_place(
const Task* task,
const std::vector<PhysicalRegion>& regions,
Context ctx,
Runtime* rt) {
in_place(task, regions, ctx, rt, false);
}
#ifdef HYPERION_USE_CUDA
void
FFT::cufft_in_place(
const Task* task,
const std::vector<PhysicalRegion>& regions,
Context ctx,
Runtime* rt) {
in_place(task, regions, ctx, rt, false);
}
#endif
FFT::Plan
FFT::fftw_create_plan(
const Task* task,
const std::vector<PhysicalRegion>& regions,
Context ctx,
Runtime* rt) {
const Args& args = *static_cast<const Args*>(task->args);
assert(args.desc.transform == Type::C2C);
Plan result;
result.desc = args.desc;
if (args.desc.precision == Precision::SINGLE) {
auto params =
get_params<complex<float>>(
rt,
task->regions[0],
regions[0],
args.fid,
args.desc.rank);
result.buffer = params.buffer;
fftwf_mutex.lock(ctx, rt);
if (args.seconds >= 0)
fftwf_set_timelimit(args.seconds);
// when creating a plan, if FFTW does not yet have wisdom for that plan, it
// will overwrite the array; thus when necessary, create a similar plan
// initially with a different buffer
auto make_plan =
[¶ms, &args](fftwf_complex* buffer, unsigned flags) {
return
fftwf_plan_many_dft(
params.n.size(), params.n.data(), params.howmany,
buffer, params.nembed.data(), params.stride, params.dist,
buffer, params.nembed.data(), params.stride, params.dist,
args.desc.sign,
flags);
};
result.handle.fftwf =
make_plan(
static_cast<fftwf_complex*>(params.buffer),
args.flags | FFTW_WISDOM_ONLY);
if (result.handle.fftwf == NULL && (args.flags & FFTW_WISDOM_ONLY) == 0) {
// no existing wisdom for plan, and caller accepts generation of new plan
std::cout << "new FFTWF plan" << std::endl;
auto buff = fftwf_alloc_complex(params.howmany * params.dist);
auto p = make_plan(buff, args.flags);
::fftwf_destroy_plan(p);
fftwf_free(buff);
result.handle.fftwf =
make_plan(
static_cast<fftwf_complex*>(params.buffer),
args.flags | FFTW_WISDOM_ONLY);
assert(result.handle.fftwf != NULL);
}
fftwf_mutex.unlock();
} else {
auto params =
get_params<complex<double>>(
rt,
task->regions[0],
regions[0],
args.fid,
args.desc.rank);
result.buffer = params.buffer;
fftw_mutex.lock(ctx, rt);
if (args.seconds >= 0)
fftw_set_timelimit(args.seconds);
// when creating a plan, if FFTW does not yet have wisdom for that plan, it
// will overwrite the array; thus when necessary, create a similar plan
// initially with a different buffer
auto make_plan =
[¶ms, &args](fftw_complex* buffer, unsigned flags) {
return
fftw_plan_many_dft(
params.n.size(), params.n.data(), params.howmany,
buffer, params.nembed.data(), params.stride, params.dist,
buffer, params.nembed.data(), params.stride, params.dist,
args.desc.sign,
flags);
};
result.handle.fftw =
make_plan(
static_cast<fftw_complex*>(result.buffer),
args.flags | FFTW_WISDOM_ONLY);
if (result.handle.fftw == NULL && (args.flags & FFTW_WISDOM_ONLY) == 0) {
std::cout << "new FFTW plan" << std::endl;
auto buff = fftw_alloc_complex(params.howmany * params.dist);
auto p = make_plan(buff, args.flags);
::fftw_destroy_plan(p);
fftw_free(buff);
result.handle.fftw =
make_plan(
static_cast<fftw_complex*>(result.buffer),
args.flags | FFTW_WISDOM_ONLY);
assert(result.handle.fftw != NULL);
}
fftw_mutex.unlock();
}
#undef DESC
return result;
}
#ifdef HYPERION_USE_CUDA
FFT::Plan
FFT::cufft_create_plan(
const Task* task,
const std::vector<PhysicalRegion>& regions,
Context ctx,
Runtime* rt) {
const Args& args = *static_cast<const Args*>(task->args);
assert(args.desc.transform == Type::C2C);
Plan result;
result.desc = args.desc;
if (args.desc.precision == Precision::SINGLE) {
auto params =
get_params<complex<float>>(
rt,
task->regions[0],
regions[0],
args.fid,
args.desc.rank);
result.buffer = params.buffer;
auto rc =
cufftPlanMany(
&result.handle.cufft, params.n.size(), params.n.data(),
params.nembed.data(), params.stride, params.dist,
params.nembed.data(), params.stride, params.dist,
CUFFT_C2C,
params.howmany);
if (rc != CUFFT_SUCCESS)
result.handle.cufft = 0;
} else {
auto params =
get_params<complex<double>>(
rt,
task->regions[0],
regions[0],
args.fid,
args.desc.rank);
result.buffer = params.buffer;
auto rc =
cufftPlanMany(
&result.handle.cufft, params.n.size(), params.n.data(),
params.nembed.data(), params.stride, params.dist,
params.nembed.data(), params.stride, params.dist,
CUFFT_Z2Z,
params.howmany);
if (rc != CUFFT_SUCCESS)
result.handle.cufft = 0;
}
#undef DESC
return result;
}
#endif
int
FFT::fftw_execute(
const Task* task,
const std::vector<PhysicalRegion>& regions,
Context ctx,
Runtime* rt) {
auto plan = task->futures[0].get_result<Plan>();
int result;
if (plan.desc.precision == Precision::SINGLE) {
if (plan.handle.fftwf != NULL) {
::fftwf_execute(plan.handle.fftwf);
result = 0;
} else {
auto lr = task->regions[0].region;
complex<float> nan(
std::numeric_limits<float>::quiet_NaN(),
std::numeric_limits<float>::quiet_NaN());
rt->fill_field(ctx, lr, lr, task->regions[0].instance_fields[0], nan);
result = 1;
}
} else {
if (plan.handle.fftw != NULL) {
::fftw_execute(plan.handle.fftw);
result = 0;
} else {
auto lr = task->regions[0].region;
complex<double> nan(
std::numeric_limits<double>::quiet_NaN(),
std::numeric_limits<double>::quiet_NaN());
rt->fill_field(ctx, lr, lr, task->regions[0].instance_fields[0], nan);
result = 1;
}
}
if (*static_cast<bool*>(task->args))
fftw_destroy_plan(task, regions, ctx, rt);
return result;
}
#ifdef HYPERION_USE_CUDA
int
FFT::cufft_execute(
const Task* task,
const std::vector<PhysicalRegion>& regions,
Context ctx,
Runtime* rt) {
auto plan = task->futures[0].get_result<Plan>();
int result;
if (plan.handle.cufft != 0) {
if (plan.desc.precision == Precision::SINGLE)
result =
cufftExecC2C(
plan.handle.cufft,
static_cast<cufftComplex*>(plan.buffer),
static_cast<cufftComplex*>(plan.buffer),
plan.desc.sign);
else
result =
cufftExecZ2Z(
plan.handle.cufft,
static_cast<cufftDoubleComplex*>(plan.buffer),
static_cast<cufftDoubleComplex*>(plan.buffer),
plan.desc.sign);
} else {
result = -1;
}
if (*static_cast<bool*>(task->args))
cufft_destroy_plan(task, regions, ctx, rt);
return result;
}
#endif
void
FFT::fftw_destroy_plan(
const Task* task,
const std::vector<PhysicalRegion>&,
Context ctx,
Runtime* rt) {
auto plan = task->futures[0].get_result<Plan>();
if (plan.desc.precision == Precision::SINGLE) {
if (plan.handle.fftwf != NULL) {
fftwf_mutex.lock(ctx, rt);
::fftwf_destroy_plan(plan.handle.fftwf);
fftwf_mutex.unlock();
}
} else {
if (plan.handle.fftw != NULL) {
fftw_mutex.lock(ctx, rt);
::fftw_destroy_plan(plan.handle.fftw);
fftw_mutex.unlock();
}
}
}
#ifdef HYPERION_USE_CUDA
void
FFT::cufft_destroy_plan(
const Task* task,
const std::vector<PhysicalRegion>&,
Context,
Runtime*) {
auto plan = task->futures[0].get_result<Plan>();
if (plan.handle.cufft != 0)
cufftDestroy(plan.handle.cufft);
}
#endif
template <typename T>
void
rotate_1d_array(T* array, long n0, T* scratch) {
const long shift = n0 / 2 + 1;
for (long i = 0; i < n0; ++i)
scratch[i] = array[(i + shift) % n0];
for (long i = 0; i < n0; ++i)
array[i] = scratch[i];
}
template <typename T>
void
rotate_2d_array(T* array, long n0, long n1, T* scratch) {
std::array<long, 2> shift{n0 / 2 + 1, n1 / 2 + 1};
for (long i = 0; i < n0; ++i) {
auto i1 = (i + shift[0]) % n0;
for (long j = 0; j < n1; ++j)
scratch[i * n1 + j] = array[i1 * n1 + (j + shift[1]) % n1];
}
for (long i = 0; i < n0; ++i)
for (long j = 0; j < n1; ++j)
array[i * n1 + j] = scratch[i * n1 + j];
}
template <typename T>
void
rotate_3d_array(T* array, long n0, long n1, long n2, T* scratch) {
std::array<long, 3>
shift{n0 / 2 + 1, n1 / 2 + 1, n2 / 2 + 1};
for (long i = 0; i < n0; ++i) {
auto i1 = (i + shift[0]) % n0;
for (long j = 0; j < n1; ++j) {
auto j1 = (j + shift[1]) % n1;
for (long k = 0; k < n2; ++k)
scratch[(i * n1 + j) * n2 + k] =
array[(i1 * n1 + j1) * n2 + (k + shift[2]) % n2];
}
}
for (long i = 0; i < n0; ++i)
for (long j = 0; j < n1; ++j)
for (long k = 0; k < n2; ++k)
array[(i * n1 + j) * n2 + k] = scratch[(i * n1 + j) * n2 + k];
}
template <typename T, int N>
static void
rotate_arrays(
Context ctx,
Runtime* rt,
const FFT::Desc& desc,
const RegionRequirement& req,
const PhysicalRegion& region) {
// N.B: we're assuming that the array axes of the region are not partitioned
const FieldAccessor<
LEGION_READ_WRITE,
T,
N,
coord_t,
AffineAccessor<T, N, coord_t>,
HYPERION_CHECK_BOUNDS> acc(region, *req.privilege_fields.begin());
assert(0 < desc.rank && desc.rank <= 3);
Point<N> array_pt;
for (size_t i = 0; i < N; ++i)
array_pt[i] = -1;
Rect<N> rect(rt->get_index_space_domain(req.region.get_index_space()));
std::vector<ptrdiff_t> array_dim;
size_t array_size = 1;
for (size_t i = desc.rank; i > 0; --i) {
array_dim.push_back(rect.hi[N - i] - rect.lo[N - i] + 1);
array_size *= static_cast<size_t>(array_dim.back());
}
// TODO: c++20: use make_unique_for_overwrite
auto scratch = std::make_unique<T[]>(array_size);
for (PointInRectIterator<N> pir(rect, false); pir(); pir++) {
// each of the iterator values in the outer N - desc.rank dimensions names
// a single array to rotate
if (!prefixes_match<N>(array_pt, *pir, N - desc.rank)) {
// save the indices for the current array
for (size_t i = 0; i < N; ++i)
array_pt[i] = pir[i];
switch (desc.rank) {
case 1: {
rotate_1d_array(acc.ptr(*pir), array_dim[0], scratch.get());
break;
}
case 2: {
rotate_2d_array(
acc.ptr(*pir),
array_dim[0],
array_dim[1],
scratch.get());
break;
}
case 3: {
rotate_3d_array(
acc.ptr(*pir),
array_dim[0],
array_dim[1],
array_dim[2],
scratch.get());
break;
}
default:
assert(false);
break;
}
}
}
}
void
FFT::rotate_arrays_task(
const Task* task,
const std::vector<PhysicalRegion>& regions,
Context ctx,
Runtime* rt) {
const Desc& desc = *static_cast<const Desc*>(task->args);
assert(desc.transform == FFT::Type::C2C);
switch (task->regions[0].region.get_dim()) {
#define ROTATE_ARRAYS(N) \
case N: \
switch (desc.precision) { \
case FFT::Precision::SINGLE: \
::rotate_arrays<complex<float>, N>( \
ctx, rt, desc, task->regions[0], regions[0]); \
break; \
case FFT::Precision::DOUBLE: \
::rotate_arrays<complex<double>, N>( \
ctx, rt, desc, task->regions[0], regions[0]); \
break; \
} \
break;
HYPERION_FOREACH_N(ROTATE_ARRAYS);
#undef ROTATE_ARRAYS
default:
assert(false);
break;
}
}
void
FFT::preregister_tasks() {
LayoutConstraintRegistrar
fftw_constraints(FieldSpace::NO_SPACE, "FFT::fftw_constraints");
add_soa_right_ordering_constraint(fftw_constraints);
fftw_constraints.add_constraint(
SpecializedConstraint(LEGION_AFFINE_SPECIALIZE));
auto fftw_layout_id = Runtime::preregister_layout(fftw_constraints);
#ifdef HYPERION_USE_CUDA
LayoutConstraintRegistrar
cufft_constraints(FieldSpace::NO_SPACE, "FFT::cufft_constraints");
add_soa_right_ordering_constraint(cufft_constraints);
cufft_constraints.add_constraint(
SpecializedConstraint(LEGION_AFFINE_SPECIALIZE));
auto cufft_layout_id = Runtime::preregister_layout(cufft_constraints);
#endif
//
// in_place_task
//
{
in_place_task_id = Runtime::generate_static_task_id();
// fftw variant
//
// FIXME: remove assumption that FFTW is using OpenMP
{
TaskVariantRegistrar
registrar(in_place_task_id, in_place_task_name);
registrar.add_constraint(ProcessorConstraint(Processor::OMP_PROC));
registrar.set_inner();
registrar.add_layout_constraint_set(0, fftw_layout_id);
Runtime::preregister_task_variant<fftw_in_place>(
registrar,
in_place_task_name);
}
#ifdef HYPERION_USE_CUDA
// cufft variant
{
TaskVariantRegistrar
registrar(in_place_task_id, in_place_task_name);
registrar.add_constraint(ProcessorConstraint(Processor::TOC_PROC));
registrar.set_inner();
registrar.add_layout_constraint_set(0, cufft_layout_id);
Runtime::preregister_task_variant<cufft_in_place>(
registrar,
in_place_task_name);
}
#endif
}
//
// create_plan_task
//
{
create_plan_task_id = Runtime::generate_static_task_id();
// fftw variant
//
// FIXME: remove assumption that FFTW is using OpenMP
{
TaskVariantRegistrar
registrar(create_plan_task_id, create_plan_task_name);
registrar.add_constraint(ProcessorConstraint(Processor::OMP_PROC));
registrar.set_leaf();
registrar.add_layout_constraint_set(0, fftw_layout_id);
Runtime::preregister_task_variant<Plan, fftw_create_plan>(
registrar,
create_plan_task_name);
}
#ifdef HYPERION_USE_CUDA
// cufft variant
{
TaskVariantRegistrar
registrar(create_plan_task_id, create_plan_task_name);
registrar.add_constraint(ProcessorConstraint(Processor::TOC_PROC));
registrar.set_leaf();
registrar.add_layout_constraint_set(0, cufft_layout_id);
Runtime::preregister_task_variant<Plan, cufft_create_plan>(
registrar,
create_plan_task_name);
}
#endif
}
//
// execute_fft_task
//
{
execute_fft_task_id = Runtime::generate_static_task_id();
// fftw variant
//
// FIXME: remove assumption that FFTW is using OpenMP
{
TaskVariantRegistrar
registrar(execute_fft_task_id, execute_fft_task_name);
registrar.add_constraint(ProcessorConstraint(Processor::OMP_PROC));
registrar.set_leaf();
//registrar.set_idempotent();
registrar.add_layout_constraint_set(0, fftw_layout_id);
Runtime::preregister_task_variant<int, fftw_execute>(
registrar,
execute_fft_task_name);
}
#ifdef HYPERION_USE_CUDA
// cufft variant
{
TaskVariantRegistrar
registrar(execute_fft_task_id, execute_fft_task_name);
registrar.add_constraint(ProcessorConstraint(Processor::TOC_PROC));
registrar.set_leaf();
//registrar.set_idempotent();
registrar.add_layout_constraint_set(0, cufft_layout_id);
Runtime::preregister_task_variant<int, cufft_execute>(
registrar,
execute_fft_task_name);
}
#endif
}
//
// destroy_plan_task
//
{
destroy_plan_task_id = Runtime::generate_static_task_id();
// fftw variant
//
// FIXME: remove assumption that FFTW is using OpenMP
{
TaskVariantRegistrar
registrar(destroy_plan_task_id, destroy_plan_task_name);
registrar.add_constraint(ProcessorConstraint(Processor::OMP_PROC));
registrar.set_leaf();
registrar.add_layout_constraint_set(0, fftw_layout_id);
Runtime::preregister_task_variant<fftw_destroy_plan>(
registrar,
destroy_plan_task_name);
}
#ifdef HYPERION_USE_CUDA
// cufft variant
{
TaskVariantRegistrar
registrar(destroy_plan_task_id, destroy_plan_task_name);
registrar.add_constraint(ProcessorConstraint(Processor::TOC_PROC));
registrar.set_leaf();
registrar.add_layout_constraint_set(0, cufft_layout_id);
Runtime::preregister_task_variant<cufft_destroy_plan>(
registrar,
destroy_plan_task_name);
}
#endif
}
//
// rotate_arrays_task
//
{
rotate_arrays_task_id = Runtime::generate_static_task_id();
// have only a CPU variant at this time
{
TaskVariantRegistrar
registrar(rotate_arrays_task_id, rotate_arrays_task_name);
registrar.add_constraint(ProcessorConstraint(Processor::LOC_PROC));
registrar.set_leaf();
registrar.add_layout_constraint_set(0, fftw_layout_id);
Runtime::preregister_task_variant<rotate_arrays_task>(
registrar,
rotate_arrays_task_name);
}
}
}
// Local Variables:
// mode: c++
// c-basic-offset: 2
// fill-column: 80
// indent-tabs-mode: nil
// End:
| 28.75908 | 79 | 0.637845 | [
"vector",
"transform"
] |
3dc850d20ff6a2549b9c0528efc89fca227a3629 | 79,326 | cpp | C++ | third_party/rsyn/src/tool/qpdp/IncrementalTimingDrivenQP.cpp | boenset/FastRoute4-lefdef | dd29747029fe0e4837da8696153998d5dd91aa89 | [
"BSD-3-Clause"
] | 1 | 2019-09-25T01:29:45.000Z | 2019-09-25T01:29:45.000Z | third_party/rsyn/src/tool/qpdp/IncrementalTimingDrivenQP.cpp | wjx-1999/FastRoute4-lefdef | f9e0a28e42376cd673eae288fa19af60c1cd390e | [
"BSD-3-Clause"
] | null | null | null | third_party/rsyn/src/tool/qpdp/IncrementalTimingDrivenQP.cpp | wjx-1999/FastRoute4-lefdef | f9e0a28e42376cd673eae288fa19af60c1cd390e | [
"BSD-3-Clause"
] | null | null | null | /* Copyright 2014-2018 Rsyn
*
* 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 <limits>
#include <thread>
#include "session/Session.h"
#include "tool/library/LibraryCharacterizer.h"
#include "tool/routing/RoutingEstimator.h"
#include "iccad15/Infrastructure.h"
#include "IncrementalTimingDrivenQP.h"
#include "util/FloatingPoint.h"
#include "util/AsciiProgressBar.h"
#include "util/Environment.h"
#include "util/StreamStateSaver.h"
namespace ICCAD15 {
void IncrementalTimingDrivenQP::setSession(Rsyn::Session ptr) {
session = ptr;
infra = session.getService("ufrgs.ispd16.infra");
timer = session.getService("rsyn.timer");
routingEstimator = session.getService("rsyn.routingEstimator");
libc = session.getService("rsyn.libraryCharacterizer");
design = session.getDesign();
module = design.getTopModule();
mapCellToIndex = design.createAttribute();
delayRatio = design.createAttribute();
phDesign = session.getPhysicalDesign();
for (Rsyn::Instance instance : module.allInstances()) {
Rsyn::Cell cell = instance.asCell(); // TODO: hack, assuming
// that the instance is a
// cell
mapCellToIndex[cell] = -1;
delayRatio[cell] = 1.0;
}
} // end method
// -----------------------------------------------------------------------------
void IncrementalTimingDrivenQP::refreshCellsDelayRatio() {
// Ignore for now...
return;
// for (Rsyn::Instance instance : design.allCells()) {
// Rsyn::Cell cell = instance.asCell(); // TODO: hack,
// assuming that the instance is a cell
// delayRatio[ cell ] = computeCellDelayRatio( cell );
// } // end for
} // end method
// -----------------------------------------------------------------------------
void IncrementalTimingDrivenQP::buildMapping() {
mapIndexToCell.clear();
mapIndexToCell.resize(movable.size());
int index = 0;
for (Rsyn::Cell cell : movable) {
mapCellToIndex[cell] = index;
mapIndexToCell[index] = cell;
index++;
} // end for
} // end method
// -----------------------------------------------------------------------------
void IncrementalTimingDrivenQP::copyCellsLocationFromSessionToLinearSystem() {
Stepwatch watch(
"[Quadratic Placement] Copying positions to Linear System.");
const int numMovableElements = movable.size();
px.clear();
py.clear();
px.assign(numMovableElements, 0);
py.assign(numMovableElements, 0);
for (Rsyn::Instance instance : module.allInstances()) {
Rsyn::Cell cell = instance.asCell(); // TODO: hack, assuming
// that the instance is a
// cell
const int index = mapCellToIndex[cell];
if (index < 0) continue;
Rsyn::PhysicalCell phCell = phDesign.getPhysicalCell(cell);
const DBUxy cellPos = phCell.getPosition();
px[index] = cellPos[X];
py[index] = cellPos[Y];
} // end for
} // end method
// -----------------------------------------------------------------------------
void IncrementalTimingDrivenQP::copyCellsLocationFromLinearSystemToSession() {
Stepwatch watch("[Quadratic Placement] Copying positions to design.");
std::vector<Rsyn::Timer::PathHop> path;
timer->queryTopCriticalPath(Rsyn::LATE, path);
const double pathLengthBefore = infra->computePathManhattanLength(path);
AsciiProgressBar progressBar(mapIndexToCell.size());
const bool moveTentatively = false;
// double minDisplacement = 4 * session.getRows()[0].height();
double minDisplacement = 4 * phDesign.getRowHeight();
std::cout << "[Quadratic Placement] minDisplacement = "
<< minDisplacement << "\n";
initialPositions.assign(mapIndexToCell.size(),
DBUxy(std::numeric_limits<DBU>::quiet_NaN(),
std::numeric_limits<DBU>::quiet_NaN()));
std::vector<std::tuple<Number, Rsyn::Cell, int>> orderedCells;
for (Rsyn::Instance instance : module.allInstances()) {
Rsyn::Cell cell = instance.asCell(); // TODO: hack, assuming
// that the instance is a
// cell
const int index = mapCellToIndex[cell];
if (index < 0) continue;
const Number slack = timer->getCellWorstSlack(cell, Rsyn::LATE);
Rsyn::PhysicalCell phCell = phDesign.getPhysicalCell(cell);
const double x = px[index];
const double y = py[index];
const double2 newPos(x, y);
const double2 oldPos = double2(phCell.getPosition());
if (oldPos.approximatelyEqual(newPos, minDisplacement)) {
continue;
} // enf if
// double2 displacement = newPos - oldPos;
// displacement.abs();
// displacement.x = -displacement.x;
// displacement.y = -displacement.y;
orderedCells.push_back(std::make_tuple(slack, cell, index));
}
std::sort(orderedCells.begin(), orderedCells.end());
double averageDisplacement = 0.0;
int numMoved = 0;
for (const std::tuple<Number, Rsyn::Cell, int>& e : orderedCells) {
Rsyn::Cell cell = std::get<1>(e);
const int index = std::get<2>(e);
Rsyn::PhysicalCell phCell = phDesign.getPhysicalCell(cell);
const double x = px[index];
const double y = py[index];
const double2 newPos(x, y);
const DBUxy oldPos = phCell.getPosition();
initialPositions[index] = oldPos;
if (moveTentatively) {
infra->moveCellTowards(cell, newPos.convertToDbu(),
legMode, 0.1);
} else {
if (!infra->moveCell(cell, newPos.convertToDbu(),
legMode, true)) {
if (!infra->moveCell(cell, oldPos, legMode,
true)) {
if (!infra->moveCell(
cell, oldPos,
LegalizationMethod::
LEG_MIN_LINEAR_DISPLACEMENT,
true)) {
std::cout
<< "[WARNING]: "
"Legalization error at "
<< __FILE__ << ": "
<< __LINE__ << "\n";
} // end if
} // end if
} // end if
} // end if
Rsyn::PhysicalCell phCell2 = phDesign.getPhysicalCell(cell);
const double2 cellPos = double2(phCell2.getPosition());
averageDisplacement += std::abs(x - cellPos[X]);
averageDisplacement += std::abs(y - cellPos[Y]);
numMoved++;
progressBar.progress();
if (debugMode) {
std::cout << "x=(" << cellPos[X] << ", " << x << ") "
<< "y=(" << cellPos[Y] << ", " << y << ")\n";
} // end if
} // end for
averageDisplacement /= numMoved;
// averageDisplacement /= session.getRows()[0].height();
averageDisplacement /= (double)phDesign.getRowHeight();
cout << "\n\tAverage legalization disp = " << averageDisplacement
<< " rows\n";
timer->updatePath(path);
infra->computePathManhattanLength(path);
const double pathLengthAfter = infra->computePathManhattanLength(path);
if (averageDisplacement) {
std::cout << "**** Path "
<< path.front().getPin().getFullName();
std::cout << " -> " << path.back().getPin().getFullName()
<< " ****\n";
std::cout << " Length before: " << pathLengthBefore << "\n";
std::cout << " Length now: " << pathLengthAfter << "\n";
std::cout << " Change (%): ";
std::cout << std::fixed;
std::cout << std::setprecision(2);
std::cout << 100 * pathLengthAfter / pathLengthBefore << "\n";
} // end if
progressBar.progress();
std::cout << "\n";
} // end method
// -----------------------------------------------------------------------------
void IncrementalTimingDrivenQP::
copyCellsLocationFromLinearSystemToSessionOptimized() {
Stepwatch watch("[Quadratic Placement] Copying positions to design.");
AsciiProgressBar progressBar(mapIndexToCell.size());
double minDisplacement = 4 * phDesign.getRowHeight();
std::cout << "[Quadratic Placement] minDisplacement = "
<< minDisplacement << "\n";
initialPositions.assign(mapIndexToCell.size(),
DBUxy(std::numeric_limits<DBU>::quiet_NaN(),
std::numeric_limits<DBU>::quiet_NaN()));
std::vector<std::tuple<Number, Rsyn::Cell, int>> orderedCells;
for (Rsyn::Instance instance : module.allInstances()) {
Rsyn::Cell cell = instance.asCell(); // TODO: hack, assuming
// that the instance is a
// cell
const int index = mapCellToIndex[cell];
if (index < 0) continue;
const Number slack = timer->getCellWorstSlack(cell, Rsyn::LATE);
Rsyn::PhysicalCell phCell = phDesign.getPhysicalCell(cell);
const double x = px[index];
const double y = py[index];
const double2 newPos(x, y);
const double2 oldPos = double2(phCell.getPosition());
if (oldPos.approximatelyEqual(newPos, minDisplacement)) {
continue;
} // enf if
orderedCells.push_back(std::make_tuple(slack, cell, index));
}
std::sort(orderedCells.begin(), orderedCells.end());
double averageDisplacement = 0.0;
int numMoved = 0;
for (const std::tuple<Number, Rsyn::Cell, int>& e : orderedCells) {
const Number slack = std::get<0>(e);
Rsyn::Cell cell = std::get<1>(e);
const int index = std::get<2>(e);
Rsyn::PhysicalCell phCell = phDesign.getPhysicalCell(cell);
const double x = px[index];
const double y = py[index];
double2 newPos(x, y);
const DBUxy oldPos = phCell.getPosition();
initialPositions[index] = oldPos;
if (!infra->moveCell(cell, newPos.convertToDbu(), legMode,
true)) {
if (!infra->moveCell(cell, oldPos, legMode, true)) {
if (!infra->moveCell(
cell, oldPos,
LegalizationMethod::
LEG_MIN_LINEAR_DISPLACEMENT,
true)) {
std::cout << "[WARNING]: Legalization "
"error at "
<< __FILE__ << ": "
<< __LINE__ << "\n";
} // end if
} // end if
} // end if
Rsyn::PhysicalCell phCell2 = phDesign.getPhysicalCell(cell);
const double2 cellPos = double2(phCell2.getPosition());
averageDisplacement += std::abs(x - cellPos[X]);
averageDisplacement += std::abs(y - cellPos[Y]);
numMoved++;
progressBar.progress();
if (debugMode) {
std::cout << "x=(" << cellPos[X] << ", " << x << ") "
<< "y=(" << cellPos[Y] << ", " << y << ")\n";
} // end if
} // end for
averageDisplacement /= numMoved;
averageDisplacement /= (double)phDesign.getRowHeight();
cout << "\n\tAverage legalization disp = " << averageDisplacement
<< " rows\n";
const bool debugPathImprovement = true;
if (debugPathImprovement) {
std::cout << "\"debugPathImprovement\" enabled. It will cause "
"performance loss..\n";
timer->updateTimingIncremental();
if (averageDisplacement) {
std::vector<Rsyn::Timer::PathHop> path;
timer->queryTopCriticalPath(Rsyn::LATE, path);
// Rsyn::Pin endpoint =
// design.findPinByName("A2_B4_C2_D17_o724686:d");
// timer->queryTopCriticalPathsFromEndpoint(Rsyn::LATE,
// endpoint, 1, path );
const double pathLength =
infra->computePathManhattanLength(path);
infra->reportPathManhattanLengthBySegment(path);
std::cout << "**** Path "
<< path.front().getPin().getFullName();
std::cout << " -> "
<< path.back().getPin().getFullName()
<< " ****\n";
std::cout << " Length : " << pathLength << "\n";
} // end if
}
progressBar.progress();
std::cout << "\n";
}
// -----------------------------------------------------------------------------
void IncrementalTimingDrivenQP::neutralizeSystem() {
Stepwatch watch("[Quadratic Placement] Neutralizing system");
::Mul(a, px, bx);
::Mul(a, py, by);
} // end method
// -----------------------------------------------------------------------------
void IncrementalTimingDrivenQP::neutralizeSystemWithSpreadingForces() {
Stepwatch watch("[Quadratic Placement] Neutralizing system");
for (int i = 0; i < a.GetDimension(); i++) a.AddDiagonalElement(i, .1);
std::vector<double> nx(px.size(), 0.0);
std::vector<double> ny(py.size(), 0.0);
::Mul(a, px, nx);
::Mul(a, py, ny);
std::vector<double> fx(px.size(), 0.0);
std::vector<double> fy(py.size(), 0.0);
::Sub(nx, bx, fx);
::Sub(ny, by, fy);
::Add(fx, bx, bx);
::Add(fy, by, by);
}
// -----------------------------------------------------------------------------
void generateRetentionForces(std::vector<double>& fx, std::vector<double>& fy) {
}
// -----------------------------------------------------------------------------
void IncrementalTimingDrivenQP::addAnchor(const Rsyn::Cell c, const DBUxy pos,
const double w) {
const int index = mapCellToIndex[c];
if (index < 0) return;
fw[index] += w;
fx[index] += w * pos.x;
fy[index] += w * pos.y;
} // end method
// -----------------------------------------------------------------------------
void IncrementalTimingDrivenQP::runQuadraticPlacement(
const std::set<Rsyn::Cell>& movable,
const LegalizationMethod legalizationMethod,
const bool roolbackOnMaxDisplacementViolation) {
std::cout << "Deprecated..." << std::endl;
return;
// Compute retention forces.
//::Sub(nx, bx0, fx);
//::Sub(ny, by0, fy);
// Add the retention forces to the stressed linear system.
//::Add(bx1, fx, bx1);
//::Add(by1, fy, by1);
// Solve 'not' stressed linear system.
std::thread tx([&]() { SolveByConjugateGradient(a, bx, px, 1000); });
std::thread ty([&]() { SolveByConjugateGradient(a, by, py, 1000); });
tx.join();
ty.join();
} // end method
// -----------------------------------------------------------------------------
/* Remove all spreading forces from the system. */
void IncrementalTimingDrivenQP::removeAnchors() {
fw.clear();
fx.clear();
fy.clear();
fw.assign(mapIndexToCell.size(), 0);
fx.assign(mapIndexToCell.size(), 0);
fy.assign(mapIndexToCell.size(), 0);
} // end method
// -----------------------------------------------------------------------------
void IncrementalTimingDrivenQP::buildLinearSystem(const bool stress) {
Stepwatch watch("[Quadratic Placement] Building Linear system");
// Clear fixed forces vector
bx.clear();
by.clear();
bx.assign(mapIndexToCell.size(), 0);
by.assign(mapIndexToCell.size(), 0);
// Clear anchors
removeAnchors();
// Define the nets that connect at least one movable element.
std::set<Rsyn::Net> nset;
for (Rsyn::Instance instance : module.allInstances()) {
Rsyn::Cell cell = instance.asCell(); // TODO: hack, assuming
// that the instance is a
// cell
if (mapCellToIndex[cell] < 0) continue;
for (Rsyn::Pin pin : cell.allPins()) {
Rsyn::Net net = pin.getNet();
if (net) {
if (net == timer->getClockNet()) continue;
Rsyn::Pin driver = net.getAnyDriver();
Rsyn::Instance instance = driver.getInstance();
if (driver && instance.isLCB()) continue;
nset.insert(net);
} // end if
} // end for
} // end for
for (Rsyn::Net net : nset) {
Rsyn::Pin driver = net.getAnyDriver();
double R = 1;
if (enableRC) {
const double driverResistance =
driver
? libc->getCellMaxDriverResistance(
driver.getInstance(), Rsyn::LATE)
: 1;
R = 0.1 * driverResistance; // * loadCapacitance;
}
R = std::max(R, minimumResistance);
for (Rsyn::Pin pin0 : net.allPins()) {
Rsyn::Cell cell0 = pin0.getInstance().asCell();
const int index0 = mapCellToIndex[cell0];
if (index0 == -1) continue;
for (Rsyn::Pin pin1 : net.allPins()) {
if (pin0 == pin1) continue;
Rsyn::Cell cell1 = pin1.getInstance().asCell();
const int index1 = mapCellToIndex[cell1];
if ((index0 != -1 && index1 != -1) &&
index0 >= index1)
continue;
double weight =
R * double(1) /
std::max(1, (net.getNumPins() - 1));
if (stress) {
weight *= 1 +
timer->getNetCriticality(
net, Rsyn::LATE);
} // end if
if (index0 != -1 && index1 != -1) {
// add movable-to-movable connection
dscp.AddElement(index0, index1,
-weight);
dscp.AddElement(index1, index0,
-weight);
dscp.AddDiagonalElement(index0, weight);
dscp.AddDiagonalElement(index1, weight);
} else if (index0 != -1) {
// add movable-to-fixed connection
const DBUxy pos1 =
phDesign.getPinPosition(pin1);
bx[index0] += weight * pos1.x;
by[index0] += weight * pos1.y;
dscp.AddDiagonalElement(index0, weight);
} else if (index1 != -1) {
// add fixed-to-movable connection
const DBUxy pos0 =
phDesign.getPinPosition(pin0);
bx[index1] += weight * pos0.x;
by[index1] += weight * pos0.y;
dscp.AddDiagonalElement(index1, weight);
} // end if
} // end for
} // end for
} // end for
a.Reset();
#ifdef DEBUG
a.Initialize(dscp, true);
#else
a.Initialize(dscp, false);
#endif
dscp.Clear();
} // end method
// -----------------------------------------------------------------------------
void IncrementalTimingDrivenQP::solveLinearSystem(bool spreadingForces) {
Stepwatch watch("[Quadratic Placement] Solving Linear System.");
// Creates local variables for the system...
SquareCompressedRowMatrix& a = this->a;
std::vector<double>& bx = this->bx;
std::vector<double>& by = this->by;
// Add spreading forces to the system if enabled...
if (spreadingForces) {
for (int i = 0; i < bx.size(); i++) {
a.AddDiagonalElement(i, fw[i]);
bx[i] += fx[i];
by[i] += fy[i];
} // end for
} // end if
// Solves linear system...
// SquareCompressedRowMatrix u, l;
// Cholesky( a, u, l );
// SolveByConjugateGradientWithPCond(a, bx, px, 1000, 1e-5, u, l);
// SolveByConjugateGradientWithPCond(a, by, py, 1000, 1e-5, u, l);
std::thread tx([&]() {
::SolveByConjugateGradientWithDiagonalPreConditioner(a, bx, px,
1000);
});
std::thread ty([&]() {
::SolveByConjugateGradientWithDiagonalPreConditioner(a, by, py,
1000);
});
tx.join();
ty.join();
}
// -----------------------------------------------------------------------------
bool IncrementalTimingDrivenQP::canBeSetAsMovable(
Rsyn::Cell cell, const bool considerCriticalCellsAsFixed) {
Rsyn::PhysicalCell physicalCell = phDesign.getPhysicalCell(cell);
return !cell.isPort() && !cell.isFixed() && !cell.isSequential() &&
!cell.isLCB() && !cell.isMacroBlock() &&
!(considerCriticalCellsAsFixed &&
timer->getCellCriticality(cell, Rsyn::LATE) > 0);
} // end method
// -----------------------------------------------------------------------------
void IncrementalTimingDrivenQP::markAsMovableAllNonFixedCells(
const bool considerCriticalCellsAsFixed) {
movable.clear();
for (Rsyn::Instance instance : module.allInstances()) {
Rsyn::Cell cell = instance.asCell(); // TODO: hack, assuming
// that the instance is a
// cell
if (canBeSetAsMovable(cell, considerCriticalCellsAsFixed)) {
movable.insert(cell);
} // end if
} // end for
} // end for
// -----------------------------------------------------------------------------
void IncrementalTimingDrivenQP::markAsMovableAllNonFixedCriticalCells() {
movable.clear();
for (Rsyn::Instance instance : module.allInstances()) {
Rsyn::Cell cell = instance.asCell(); // TODO: hack, assuming
// that the instance is a
// cell
if (canBeSetAsMovable(cell, false) &&
timer->getCellCriticality(cell, Rsyn::LATE) > 0) {
movable.insert(cell);
} // end if
} // end for
} // end for
// -----------------------------------------------------------------------------
void IncrementalTimingDrivenQP::
markAsMovableAllNonFixedNonCriticalCellsDrivenByCriticalNets() {
movable.clear();
for (Rsyn::Instance instance : module.allInstances()) {
Rsyn::Cell cell = instance.asCell(); // TODO: hack, assuming
// that the instance is a
// cell
if (canBeSetAsMovable(cell, false) &&
FloatingPoint::approximatelyZero(
timer->getCellCriticality(cell, Rsyn::LATE))) {
// Check if its driven by a critical net.
bool drivenByCriticalNet = false;
for (Rsyn::Pin pin : cell.allPins(Rsyn::IN)) {
Rsyn::Net net = pin.getNet();
if (net &&
timer->getNetCriticality(net, Rsyn::LATE) >
0) {
drivenByCriticalNet = true;
break;
} // end if
} // end for
if (drivenByCriticalNet) movable.insert(cell);
} // end if
} // end for
} // end for
// -----------------------------------------------------------------------------
void IncrementalTimingDrivenQP::
markAsMovableAllNonFixedCriticalCellsAndTheirSinks() {
movable.clear();
for (Rsyn::Instance instance : module.allInstances()) {
Rsyn::Cell currentCell =
instance.asCell(); // TODO: hack, assuming that the
// instance is a cell
if (timer->getCellCriticality(currentCell, Rsyn::LATE) > 0) {
for (Rsyn::Pin driver :
currentCell.allPins(Rsyn::OUT)) {
Rsyn::Net net = driver.getNet();
if (net) {
for (Rsyn::Pin pin : net.allPins()) {
Rsyn::Cell cell =
pin.getInstance().asCell();
if (canBeSetAsMovable(cell,
false)) {
movable.insert(cell);
} // end if
} // end for
} // end if
} // end for
} // end if
} // end for
} // end for
// -----------------------------------------------------------------------------
void IncrementalTimingDrivenQP::
markAsMovableAllNonFixedCriticalCellsAndTheirNeighbors() {
movable.clear();
for (Rsyn::Instance instance : module.allInstances()) {
Rsyn::Cell currentCell =
instance.asCell(); // TODO: hack, assuming that the
// instance is a cell
if (timer->getCellCriticality(currentCell, Rsyn::LATE) > 0) {
for (Rsyn::Pin cellPin : currentCell.allPins()) {
Rsyn::Net net = cellPin.getNet();
if (net) {
for (Rsyn::Pin netPin : net.allPins()) {
Rsyn::Cell cell =
netPin.getInstance()
.asCell();
if (canBeSetAsMovable(cell,
false)) {
movable.insert(cell);
} // end if
} // end for
} // end if
} // end for
} // end if
} // end for
} // end for
// -----------------------------------------------------------------------------
void IncrementalTimingDrivenQP::markAsMovableAllNonFixedCellsInTopCriticalPaths(
const int numPaths) {
movable.clear();
std::vector<std::vector<Rsyn::Timer::PathHop>> paths;
timer->queryTopCriticalPaths(Rsyn::LATE, numPaths, paths);
const int actualNumPaths = paths.size();
for (int i = 0; i < actualNumPaths; i++) {
std::vector<Rsyn::Timer::PathHop>& path = paths[i];
for (const Rsyn::Timer::PathHop& hop : path) {
Rsyn::Cell cell = hop.getInstance().asCell();
if (canBeSetAsMovable(cell, false)) {
movable.insert(cell);
} // end if
} // end for
} // end for
} // end for
// -----------------------------------------------------------------------------
void IncrementalTimingDrivenQP::
markAsMovableAllNonFixedCellsInTopCriticalPathsAndTheirNeighbors(
const int numPaths) {
movable.clear();
std::vector<std::vector<Rsyn::Timer::PathHop>> paths;
timer->queryTopCriticalPaths(Rsyn::LATE, numPaths, paths);
const int actualNumPaths = paths.size();
for (int i = 0; i < actualNumPaths; i++) {
std::vector<Rsyn::Timer::PathHop>& path = paths[i];
for (const Rsyn::Timer::PathHop& hop : path) {
Rsyn::Cell currentCell = hop.getInstance().asCell();
for (Rsyn::Pin cellPin : currentCell.allPins()) {
Rsyn::Net net = cellPin.getNet();
if (net) {
for (Rsyn::Pin netPin : net.allPins()) {
Rsyn::Cell cell =
netPin.getInstance()
.asCell();
if (canBeSetAsMovable(cell,
false)) {
movable.insert(cell);
} // end if
} // end for
} // end if
} // end for
} // end for
} // end for
} // end for
// -----------------------------------------------------------------------------
void IncrementalTimingDrivenQP::runCriticalPathSmoothing() {
std::cout << "Deprecated..." << std::endl;
return;
const int N = 300;
std::vector<std::vector<Rsyn::Timer::PathHop>> paths;
timer->queryTopCriticalPaths(Rsyn::LATE, N, paths);
// timer->queryTopCriticalPathFromTopCriticalEndpoints(Rsyn::LATE, N,
// paths);
const int numPaths = paths.size();
if (numPaths > 0) {
StreamStateSaver sss(std::cout);
markAsMovableAllNonFixedCellsInTopCriticalPathsAndTheirNeighbors(
numPaths);
// markAsMovableCellsInTopCriticalPaths(numPaths);
// markAsMovableAllNonFixedCellsInTopCriticalPathsAndTheirNeighbors(numPaths);
// markAsMovableAllNonFixedCells();
// markAsMovableAllNonFixedCriticalCellsAndTheirSinks();
// markAsMovableAllNonFixedCriticalCellsAndTheirNeighbors();
std::cout << "Quadratic placement smoothing...\n";
buildMapping();
runQuadraticPlacement(movable, LEG_NEAREST_WHITESPACE, true);
timer->updateTimingIncremental();
infra->updateQualityScore();
std::cout << "Quadratic placement smoothing... Done\n";
for (int i = 0; i < numPaths; i++) {
std::vector<Rsyn::Timer::PathHop>& path = paths[i];
const double oldSlack = path.back().getSlack();
timer->updatePath(path);
const double newSlack = path.back().getSlack();
std::cout << std::setw(10) << oldSlack << " "
<< std::setw(10) << newSlack << std::setw(10)
<< (100 * (1 - newSlack / oldSlack)) << "%\n";
} // end for
sss.restore();
infra->reportDigest();
} else {
std::cout << "No critical path to be fixed.\n";
} // end else
} // end method
// -----------------------------------------------------------------------------
void IncrementalTimingDrivenQP::generateLoadAnchors() {
Stepwatch watch("[Quadratic Placement] Generating anchors.");
criticalNets.clear();
// for ( Rsyn::Cell cell : design.allCells() ) {
// if( !canBeSetAsMovable( cell, true ) )
// continue;
//
// DBUxy target =
// session.getCellBounds( cell ).lower();
//
// addAnchor( cell, target, 0.5 );
// }
for (Rsyn::Net net : module.allNets()) {
double criticality = timer->getNetCriticality(net, Rsyn::LATE);
if (criticality > 0) {
Rsyn::Cell driver =
net.getAnyDriver().getInstance().asCell();
double slack = timer->getCellWorstNegativeSlack(
driver, Rsyn::LATE);
criticalNets.push_back(std::make_pair(slack, net));
} // end if
} // end for
std::sort(criticalNets.begin(), criticalNets.end());
int violations = 0;
int total = 0;
for (auto& it : criticalNets) {
Rsyn::Net net = std::get<1>(it);
Rsyn::Pin dPin = net.getAnyDriver();
double criticality = timer->getPinCriticality(dPin, Rsyn::LATE);
Rsyn::PhysicalCell phCell = phDesign.getPhysicalCell(dPin);
DBUxy target = phCell.getCenter();
for (Rsyn::Pin pin : net.allPins(Rsyn::IN)) {
if (timer->getPinCriticality(pin, Rsyn::LATE) > 0)
continue;
Rsyn::Cell cell = pin.getInstance().asCell();
if (!canBeSetAsMovable(cell, true)) continue;
total++;
addAnchor(cell, target, 1);
} // end for
} // end for
}
// -----------------------------------------------------------------------------
double IncrementalTimingDrivenQP::estimatePathSize(
std::vector<Rsyn::Timer::PathHop>& pathHops) {
double size = 0.0;
const int numHops = pathHops.size();
for (int i = 4; i < numHops - 1; i++) {
const Rsyn::Pin currPin = pathHops[i].getPin();
const Rsyn::Cell currCell = currPin.getInstance().asCell();
const Rsyn::Pin nextPin = pathHops[i + 1].getPin();
const Rsyn::Cell nextCell = nextPin.getInstance().asCell();
// PhysicalPin pCurrPin = session.getPhysicalPin( currPin );
// PhysicalCell pCurrCell = session.getPhysicalCell( currCell );
// PhysicalPin pNextPin = session.getPhysicalPin( nextPin );
// PhysicalCell pNextCell = session.getPhysicalCell( nextCell );
// DBUxy currPinPosition = pCurrCell.lower() +
// pCurrPin.displacement;
// DBUxy nextPinPosition = pNextCell.lower() +
// pNextPin.displacement;
DBUxy currPinPosition = phDesign.getPinPosition(currPin);
DBUxy nextPinPosition = phDesign.getPinPosition(nextPin);
size += std::abs(currPinPosition.x - nextPinPosition.x) +
std::abs(currPinPosition.y - nextPinPosition.y);
} // end for
return size;
} // end method
// -----------------------------------------------------------------------------
double IncrementalTimingDrivenQP::pathAvailableArea(
std::vector<Rsyn::Timer::PathHop>& pathHops) {
DBU minX = std::numeric_limits<DBU>::max();
DBU maxX = -std::numeric_limits<DBU>::max();
DBU minY = std::numeric_limits<DBU>::max();
DBU maxY = -std::numeric_limits<DBU>::max();
for (int i = 0; i < pathHops.size(); i++) {
// const PhysicalPin pin = session.getPhysicalPin(
// pathHops[i].getPin() );
// const PhysicalCell cell = session.getPhysicalCell(
// pathHops[i].getPin() );
// const double2 pinPos = cell.lower() + pin.displacement;
const DBUxy pinPos =
phDesign.getPinPosition(pathHops[i].getPin());
minX = std::min(minX, pinPos.x);
maxX = std::max(maxX, pinPos.x);
minY = std::min(minY, pinPos.y);
maxY = std::max(maxY, pinPos.y);
} // end for
Bounds pathBB(minX, minY, maxX, maxY);
double totalArea = pathBB.computeArea();
double blockedArea = 0.0;
for (Rsyn::Instance instance : module.allInstances()) {
Rsyn::Cell cell = instance.asCell(); // TODO: hack, assuming
// that the instance is a
// cell
PhysicalCell pCell = phDesign.getPhysicalCell(cell);
if (!cell.isMacroBlock()) continue;
blockedArea += pCell.getBounds().overlapArea(pathBB);
}
return 1 - blockedArea / totalArea;
} // end method
// -----------------------------------------------------------------------------
void IncrementalTimingDrivenQP::generateStraighteningForces_DEPRECATED(
const bool enableCriticality) {
std::vector<std::vector<Rsyn::Timer::PathHop>> paths;
std::vector<std::vector<Rsyn::Timer::PathHop>> paths2;
const Number slackThresshold = -alpha * timer->getClockPeriod();
timer->queryTopCriticalPaths(Rsyn::LATE, maxNumPaths, paths,
slackThresshold);
std::cout << "[Quadratic Placement] #Paths " << paths.size() << "\n";
const int numCriticalEndPoints =
timer->getNumCriticalEndpoints(Rsyn::LATE);
timer->queryTopCriticalPathFromTopCriticalEndpoints(
Rsyn::LATE, numCriticalEndPoints, paths2);
// paths.insert( paths.end(), paths2.begin(), paths2.end() );
std::set<std::pair<Rsyn::Cell, Rsyn::Cell>> connections;
for (int i = 0; i < paths.size(); i++) {
auto& criticalPathHops = paths[i];
if (criticalPathHops.size() < 10) continue;
double criticality = 1;
if (enableCriticality)
criticality = criticalPathHops[0].getSlack() /
timer->getWns(Rsyn::LATE);
for (int i = 4; i < criticalPathHops.size() - 2; i += 2) {
const Rsyn::Timer::PathHop& hop = criticalPathHops[i];
const Rsyn::Cell currCell =
hop.getPin().getInstance().asCell();
const Rsyn::Cell nextCell =
hop.getNextPin().getInstance().asCell();
const bool connectionExists =
connections.find(std::make_pair(
currCell, nextCell)) != connections.end();
if (connectionExists) continue;
double RC = 1;
if (enableRC) {
const double driverResistance =
libc->getCellMaxDriverResistance(
currCell, Rsyn::LATE);
const double loadCapacitance =
routingEstimator
->getRCTree(hop.getPin().getNet())
.getLumpedCap()
.getMax();
RC = 0.1 *
driverResistance; // * loadCapacitance;
}
RC = std::max(RC, minimumResistance);
const bool currIsMovable =
canBeSetAsMovable(currCell, false);
const bool nextIsMovable =
canBeSetAsMovable(nextCell, false);
if (!currIsMovable && nextIsMovable) {
/*...*/
const int index = mapCellToIndex[nextCell];
// const PhysicalCell pCell =
// session.getPhysicalCell( currCell );
// const PhysicalPin pPin =
// session.getPhysicalPin( hop.getPin() );
const DBUxy pinPos =
phDesign.getPinPosition(hop.getPin());
a.AddDiagonalElement(index, RC * 5);
// bx[ index ] += RC * 5 * (pCell.lower().x +
// pPin.dx);
// by[ index ] += RC * 5 * (pCell.lower().y +
// pPin.dy);
bx[index] += RC * 5 * (pinPos[X]);
by[index] += RC * 5 * (pinPos[Y]);
continue;
} else if (currIsMovable && !nextIsMovable) {
const int index = mapCellToIndex[currCell];
// const PhysicalCell pCell =
// session.getPhysicalCell( nextCell );
// const PhysicalPin pPin =
// session.getPhysicalPin( hop.getNextPin() );
const DBUxy pinPos =
phDesign.getPinPosition(hop.getNextPin());
a.AddDiagonalElement(index, RC * 5);
// bx[ index ] += RC * 5 * (pCell.lower().x +
// pPin.dx);
// by[ index ] += RC * 5 * (pCell.lower().y +
// pPin.dy);
bx[index] += RC * 5 * (pinPos[X]);
by[index] += RC * 5 * (pinPos[Y]);
continue;
} else if (!currIsMovable && !nextIsMovable)
continue;
connections.insert(std::make_pair(currCell, nextCell));
const int index1 = mapCellToIndex[currCell];
const int index2 = mapCellToIndex[nextCell];
const double weight = RC * 5 * (1 + criticality);
a.AddElement(std::max(index1, index2),
std::min(index1, index2), -weight);
a.AddElement(std::min(index1, index2),
std::max(index1, index2), -weight);
a.AddDiagonalElement(index1, weight);
a.AddDiagonalElement(index2, weight);
} // end for
} // end for
} // end method
// -----------------------------------------------------------------------------
void IncrementalTimingDrivenQP::generateStraighteningForcesTopCriticalPaths() {
std::vector<Rsyn::Pin> topCriticalEndPoints;
timer->queryTopCriticalEndpoints(
Rsyn::LATE, timer->getNumCriticalEndpoints(Rsyn::LATE),
topCriticalEndPoints, 0.01f * timer->getWns(Rsyn::LATE));
std::map<std::pair<Rsyn::Pin, Rsyn::Pin>, double> edges;
for (int i = 0; i < topCriticalEndPoints.size(); i++) {
std::vector<std::vector<Rsyn::Timer::PathHop>> criticalPaths;
timer->queryTopCriticalPathsFromEndpoint(
Rsyn::LATE, topCriticalEndPoints[i], 500, criticalPaths);
for (int j = 0; j < criticalPaths.size(); j++) {
const std::vector<Rsyn::Timer::PathHop>& path =
criticalPaths[j];
const Number pathCriticality =
path.back().getSlack() / timer->getWns(Rsyn::LATE);
for (int k = 0; k < path.size() - 1; k++) {
const Rsyn::Timer::PathHop& hop = path[k];
if (hop.getPin().getDirection() == Rsyn::IN)
continue;
const Rsyn::Cell currCell =
hop.getInstance().asCell();
const double driverResistance =
libc->getCellMaxDriverResistance(
currCell, Rsyn::LATE);
const double R = std::max(
0.1 * driverResistance, minimumResistance);
const double weight =
5 * R * (1 + pathCriticality);
const std::pair<Rsyn::Pin, Rsyn::Pin> key(
hop.getPin(), hop.getNextPin());
const auto edge = edges.find(key);
if (edge != edges.end())
edge->second =
std::max(edge->second, weight);
else
edges.emplace(key, weight);
} // end for
} // end for
} // end for
for (const auto& edge : edges) {
const Rsyn::Pin p0 = edge.first.first;
const Rsyn::Pin p1 = edge.first.second;
const double weight = edge.second;
const int index0 = mapCellToIndex[p0.getInstance()];
const int index1 = mapCellToIndex[p1.getInstance()];
if (index0 != -1 && index1 != -1) {
// add movable-to-movable connection
a.AddElement(index0, index1, -weight);
a.AddElement(index1, index0, -weight);
a.AddDiagonalElement(index0, weight);
a.AddDiagonalElement(index1, weight);
} else if (index0 != -1) {
// add movable-to-fixed connection
const DBUxy pos1 = phDesign.getPinPosition(p1);
bx[index0] += weight * pos1.x;
by[index0] += weight * pos1.y;
a.AddDiagonalElement(index0, weight);
} else if (index1 != -1) {
// add fixed-to-movable connection
const DBUxy pos0 = phDesign.getPinPosition(p0);
bx[index1] += weight * pos0.x;
by[index1] += weight * pos0.y;
a.AddDiagonalElement(index1, weight);
} // end if
} // end for
} // end method
// -----------------------------------------------------------------------------
void IncrementalTimingDrivenQP::generateStraighteningForces(const bool stress) {
Stepwatch watch(__func__);
fx.clear();
fy.clear();
fw.clear();
fx.assign(mapIndexToCell.size(), 0.0);
fy.assign(mapIndexToCell.size(), 0.0);
fw.assign(mapIndexToCell.size(), 0.0);
for (Rsyn::Net net : module.allNets()) {
Rsyn::Pin driver = net.getAnyDriver();
if (!driver) {
std::cout << "[WARNING] Net without a driver.\n";
continue;
}
Rsyn::Cell driverCell =
net.getAnyDriver().getInstance().asCell();
const Number driverCriticality =
timer->getSmoothedCriticality(driver, Rsyn::LATE);
if (driverCriticality > beta) continue;
if (driverCriticality < alpha ||
FloatingPoint::approximatelyEqual(driverCriticality, alpha))
continue;
const bool driverIsMovable =
canBeSetAsMovable(driverCell, false);
bool enableRC = true;
double R = 1;
if (enableRC) {
if (!libc) {
std::cout << "No libc specified! Aborting..."
<< std::endl;
exit(1);
}
double driverResistance =
libc->getCellMaxDriverResistance(driverCell,
Rsyn::LATE);
R = 0.1 * driverResistance; // e * loadCapacitance;
} // end if
R = std::max(R, 0.01);
for (Rsyn::Pin pin : net.allPins(Rsyn::IN)) {
const Number pinCriticality =
timer->getSmoothedCriticality(pin, Rsyn::LATE);
// const Number pinCriticality =
// timer->getCellCentrality(pin.getCell(), Rsyn::LATE );
const Number pinCentrality =
timer->getPinCentrality(pin, Rsyn::LATE);
if (pinCriticality < alpha ||
FloatingPoint::approximatelyEqual(pinCriticality,
alpha))
continue;
if (pinCriticality > beta) continue;
double weight = // 10 * RC;
5 * R * (1 + pinCriticality);
// 10 * RC * ( 1 + 0.5 * pinCriticality );
// RC * ( 1 + 3 * pinCentrality + 6 * pinCriticality );
// RC * ( 1 + 0.2 * std::exp( std::pow( pinCentrality,
// 3) - 1 ) );
// RC * ( 0.7 + 0.3 * pinCentrality );
// RC * ( 0.3 * pinCentrality + 0.7 * pinCriticality );
if (stress) weight *= R;
Rsyn::Cell cell = pin.getInstance().asCell();
if (!cell) {
std::cout << "[WARNING] Pin without a cell.\n";
continue;
} // end if
const bool cellIsMovable =
canBeSetAsMovable(cell, false);
if (driverIsMovable && !cellIsMovable) {
const int index = mapCellToIndex[driverCell];
// const PhysicalCell pCell =
// session.getPhysicalCell( cell );
// const PhysicalPin pPin =
// session.getPhysicalPin( pin );
const DBUxy pinPos =
phDesign.getPinPosition(pin);
fw[index] += weight;
// fx[ index ] += weight * ( pCell.lower().x +
// pPin.dx );
// fy[ index ] += weight * ( pCell.lower().y +
// pPin.dy );
fx[index] += weight * (pinPos[X]);
fy[index] += weight * (pinPos[Y]);
continue;
} else if (!driverIsMovable && cellIsMovable) {
const int index = mapCellToIndex[cell];
// const PhysicalCell pCell =
// session.getPhysicalCell( driverCell );
// const PhysicalPin pPin =
// session.getPhysicalPin( design.getDriver( net
// ) );
const DBUxy pinPos =
phDesign.getPinPosition(net.getAnyDriver());
fw[index] += weight;
// fx[ index ] += weight * ( pCell.lower().x +
// pPin.dx );
// fy[ index ] += weight * ( pCell.lower().y +
// pPin.dy );
fx[index] += weight * (pinPos[X]);
fy[index] += weight * (pinPos[Y]);
continue;
} else if (!driverIsMovable && !cellIsMovable)
continue;
const int index1 = mapCellToIndex[driverCell];
const int index2 = mapCellToIndex[cell];
try {
a.AddElement(std::max(index1, index2),
std::min(index1, index2), -weight);
a.AddElement(std::min(index1, index2),
std::max(index1, index2), -weight);
} catch (exception& e) {
std::cout << "Exception at line: " << __LINE__
<< std::endl;
} // end try-catch
a.AddDiagonalElement(index1, weight);
a.AddDiagonalElement(index2, weight);
} // end for
} // end for
} // end method
// -----------------------------------------------------------------------------
void IncrementalTimingDrivenQP::generateStraighteningForces_ELMORE() {
Stepwatch watch(__func__);
fx.clear();
fy.clear();
fw.clear();
fx.assign(mapIndexToCell.size(), 0.0);
fy.assign(mapIndexToCell.size(), 0.0);
fw.assign(mapIndexToCell.size(), 0.0);
const double Cwire = routingEstimator->getLocalWireCapPerUnitLength();
const double Rwire = routingEstimator->getLocalWireResPerUnitLength();
for (Rsyn::Net net : module.allNets()) {
Rsyn::Pin driver = net.getAnyDriver();
Rsyn::Cell driverCell =
net.getAnyDriver().getInstance().asCell();
if (!driverCell) {
std::cout << "[WARNING] Net without a driver.\n";
continue;
} // end if
const Number driverCriticality =
timer->getSmoothedCriticality(driver, Rsyn::LATE);
if (driverCriticality > beta) continue;
if (driverCriticality < alpha) //||
// FloatingPoint::approximatelyEqual(driverCriticality,
// alpha ) )
continue;
const bool driverIsMovable =
canBeSetAsMovable(driverCell, false);
double Rdrive =
libc->getCellMaxDriverResistance(driverCell, Rsyn::LATE);
Rdrive = std::max(Rdrive, 0.01);
DBUxy driverPos = phDesign.getPinPosition(driver);
for (Rsyn::Pin pin : net.allPins(Rsyn::IN)) {
const Number pinCriticality =
timer->getPinCriticality(pin, Rsyn::LATE);
// const Number pinCriticality =
// timer->getCellCentrality(pin.getCell(), Rsyn::LATE );
const Number pinCentrality =
timer->getPinCentrality(pin, Rsyn::LATE);
if (pinCriticality < alpha &&
!FloatingPoint::approximatelyEqual(pinCriticality,
alpha))
continue;
if (pinCriticality > beta) continue;
double Cload = timer->getPinInputCapacitance(pin);
DBUxy sinkPos = phDesign.getPinPosition(pin);
double l = (sinkPos - driverPos).norm();
double n = std::max(1, net.getNumPins() - 1);
double weight = Rwire * Cwire / (2 * n * n) +
Rwire * Cload / (n * l);
weight *=
1e11 * Rdrive * 0.1; // * ( 1 + pinCriticality );
Rsyn::Cell cell = pin.getInstance().asCell();
if (!cell) {
std::cout << "[WARNING] Pin without a cell.\n";
continue;
} // end if
const bool cellIsMovable =
canBeSetAsMovable(cell, false);
if (driverIsMovable && !cellIsMovable) {
const int index = mapCellToIndex[driverCell];
// const PhysicalCell pCell =
// session.getPhysicalCell( cell );
// const PhysicalPin pPin =
// session.getPhysicalPin( pin );
const DBUxy pinPos =
phDesign.getPinPosition(pin);
fw[index] += weight;
// fx[ index ] += weight * ( pCell.lower().x +
// pPin.dx );
// fy[ index ] += weight * ( pCell.lower().y +
// pPin.dy );
fx[index] += weight * (pinPos[X]);
fy[index] += weight * (pinPos[Y]);
continue;
} else if (!driverIsMovable && cellIsMovable) {
const int index = mapCellToIndex[cell];
// const PhysicalCell pCell =
// session.getPhysicalCell( driverCell );
// const PhysicalPin pPin =
// session.getPhysicalPin( net.getDriver() );
const DBUxy pinPos =
phDesign.getPinPosition(net.getAnyDriver());
fw[index] += weight;
// fx[ index ] += weight * ( pCell.lower().x +
// pPin.dx );
// fy[ index ] += weight * ( pCell.lower().y +
// pPin.dy );
fx[index] += weight * (pinPos[X]);
fy[index] += weight * (pinPos[Y]);
continue;
} else if (!driverIsMovable && !cellIsMovable)
continue;
const int index1 = mapCellToIndex[driverCell];
const int index2 = mapCellToIndex[cell];
try {
a.AddElement(std::max(index1, index2),
std::min(index1, index2), -weight);
a.AddElement(std::min(index1, index2),
std::max(index1, index2), -weight);
} catch (exception& e) {
std::cout << "Exception at line: " << __LINE__
<< std::endl;
} // end try-catch
a.AddDiagonalElement(index1, weight);
a.AddDiagonalElement(index2, weight);
} // end for
} // end for
} // end method
// -----------------------------------------------------------------------------
void IncrementalTimingDrivenQP::runNetLoadReduction(bool withAnchors) {
markAsMovableAllNonFixedCells(true);
buildMapping();
copyCellsLocationFromSessionToLinearSystem();
buildLinearSystem(false);
if (withAnchors)
neutralizeSystemWithSpreadingForces();
else
neutralizeSystem();
generateLoadAnchors();
solveLinearSystem();
copyCellsLocationFromLinearSystemToSession();
timer->updateTimingIncremental();
} // end method
// -----------------------------------------------------------------------------
void IncrementalTimingDrivenQP::runNetLoadReductionIteration() {
// removeAnchors();
generateLoadAnchors();
solveLinearSystem();
copyCellsLocationFromLinearSystemToSession();
timer->updateTimingIncremental();
}
// -----------------------------------------------------------------------------
void IncrementalTimingDrivenQP::runNeutralizeSystemWithSpreadingForces() {
markAsMovableAllNonFixedCells(false);
buildMapping();
copyCellsLocationFromSessionToLinearSystem();
buildLinearSystem(false);
neutralizeSystemWithSpreadingForces();
solveLinearSystem();
copyCellsLocationFromLinearSystemToSession();
timer->updateTimingIncremental();
}
// -----------------------------------------------------------------------------
void IncrementalTimingDrivenQP::computeAnchorPositions(std::vector<double>& x,
std::vector<double>& y) {
markAsMovableAllNonFixedCells(false);
buildMapping();
copyCellsLocationFromSessionToLinearSystem();
buildLinearSystem(false);
const double anchorWeight = 1;
for (int i = 0; i < a.GetDimension(); i++)
a.AddDiagonalElement(i, anchorWeight);
std::vector<double> nx(px.size(), 0.0);
std::vector<double> ny(py.size(), 0.0);
::Mul(a, px, nx);
::Mul(a, py, ny);
x.assign(px.size(), 0.0);
y.assign(py.size(), 0.0);
////////////////////////////////////////////////////////////////////////////
// std::vector<double> resultx( px.size(), 0.0 );
// std::vector<double> resulty( py.size(), 0.0 );
//
// std::vector<double> diffx( px.size(), 0.0 );
// std::vector<double> diffy( py.size(), 0.0 );
//
// ::SolveByConjugateGradient(a, nx, resultx);
// ::SolveByConjugateGradient(a, ny, resulty);
//
// ::Sub(px, resultx, diffx);
// ::Sub(py, resulty, diffy);
//
// std::cout << "normx: " << ::Norm(diffx);
// std::cout << "normy: " << ::Norm(diffy);
////////////////////////////////////////////////////////////////////////////
::Sub(nx, bx, x);
::Sub(ny, by, y);
::Div(x, anchorWeight, x);
::Div(y, anchorWeight, y);
// Histogram
const int numElements = px.size();
Rsyn::PhysicalModule phModule = phDesign.getPhysicalModule(module);
const Bounds& coreBounds = phModule.getBounds();
const Number range = coreBounds.computeSemiperimeter() * 0.01f;
std::vector<int> histogram;
for (int i = 0; i < numElements; i++) {
const double distance =
std::abs(px[i] - x[i]) + std::abs(py[i] - y[i]);
const int slot = (int)std::floor(distance / range);
if (slot >= histogram.size()) {
histogram.resize(slot + 1, 0);
} // end if
histogram[slot]++;
} // end for
std::cout << "Histogram:\n ";
for (int i = 0; i < histogram.size(); i++) {
std::cout << (i * range) << " " << histogram[i] << "\n";
} // end for
} // end method
// -----------------------------------------------------------------------------
void IncrementalTimingDrivenQP::runQuadraticPlacementStraighteningMultiplePaths(
const int N) {
std::cout << "Not implemented yet..." << std::endl;
} // end method
// -----------------------------------------------------------------------------
void IncrementalTimingDrivenQP::
runQuadraticPlacementStraighteningSinglePathAndSideCells(const int N) {
std::cout << "Not implemented yet..." << std::endl;
} // end method
// -----------------------------------------------------------------------------
void IncrementalTimingDrivenQP::runPathStraighteningFlow(const bool stress) {
Stepwatch qp("QP");
markAsMovableAllNonFixedCells(false);
buildMapping();
copyCellsLocationFromSessionToLinearSystem();
buildLinearSystem(false);
// copyCellsLocationFromSessionToLinearSystem();
neutralizeSystemWithSpreadingForces();
// Add Straightening forces...
// generateStraighteningForces( true );
generateStraighteningForces(stress);
solveLinearSystem();
// removeCellsFromBlockedAreas();
// solveLinearSystem();
copyCellsLocationFromLinearSystemToSession();
qp.finish();
Stepwatch watchTimer("timer");
timer->updateTimingIncremental();
watchTimer.finish();
}
// -----------------------------------------------------------------------------
void IncrementalTimingDrivenQP::runPathStraighteningFlow_UNDER_TEST() {
Stepwatch qp("QP");
markAsMovableAllNonFixedCells(false);
buildMapping();
copyCellsLocationFromSessionToLinearSystem();
buildLinearSystem(false);
// copyCellsLocationFromSessionToLinearSystem();
neutralizeSystemWithSpreadingForces();
// Add Straightening forces...
generateStraighteningForcesTopCriticalPaths();
solveLinearSystem();
// removeCellsFromBlockedAreas();
// solveLinearSystem();
copyCellsLocationFromLinearSystemToSession();
qp.finish();
Stepwatch watchTimer("timer");
timer->updateTimingIncremental();
watchTimer.finish();
}
// -----------------------------------------------------------------------------
void IncrementalTimingDrivenQP::runPathStraighteningFlow_ELMORE() {
Stepwatch qp("QP");
markAsMovableAllNonFixedCells(false);
buildMapping();
copyCellsLocationFromSessionToLinearSystem();
buildLinearSystem(false);
// copyCellsLocationFromSessionToLinearSystem();
neutralizeSystemWithSpreadingForces();
// Add Straightening forces...
generateStraighteningForces_ELMORE();
solveLinearSystem();
// removeCellsFromBlockedAreas();
// solveLinearSystem();
copyCellsLocationFromLinearSystemToSessionOptimized();
qp.finish();
Stepwatch watchTimer("timer");
timer->updateTimingIncremental();
watchTimer.finish();
} // end method
// -----------------------------------------------------------------------------
void IncrementalTimingDrivenQP::runNetWeighteningFlow() {
Stepwatch qp("QP");
markAsMovableAllNonFixedCells(false);
buildMapping();
copyCellsLocationFromSessionToLinearSystem();
buildLinearSystem(false);
neutralizeSystemWithSpreadingForces();
// Generate net weights
generateNetWeights();
solveLinearSystem();
copyCellsLocationFromLinearSystemToSession();
qp.finish();
refreshCellsDelayRatio();
Stepwatch watchTimer("timer");
timer->updateTimingIncremental();
watchTimer.finish();
} // end method
// -----------------------------------------------------------------------------
void IncrementalTimingDrivenQP::generateNetWeights() {
for (Rsyn::Net net : module.allNets()) {
Rsyn::Pin driver = net.getAnyDriver();
if (!driver) continue;
double driverCriticallity =
timer->getPinCriticality(driver, Rsyn::LATE);
if (driverCriticallity < alpha) continue;
double R = 1;
double enableRC = true;
if (enableRC) {
Rsyn::Cell driverCell = driver.getInstance().asCell();
double driverResistance =
libc->getCellMaxDriverResistance(driverCell,
Rsyn::LATE);
R = 0.1 * driverResistance; // e * loadCapacitance;
}
R = std::max(R, 0.01);
// double C = 1;
// C = std::max( timer->getNetPinLoad( net
//)[Rsyn::RISE],
// timer->getNetPinLoad( net
//)[Rsyn::FALL] );
// C = std::max( C, 0.01);
//
for (Rsyn::Pin pin0 : net.allPins()) {
Rsyn::Cell cell0 = pin0.getInstance().asCell();
const int index0 = mapCellToIndex[cell0];
if (index0 == -1) continue;
for (Rsyn::Pin pin1 : net.allPins()) {
if (pin0 == pin1) continue;
Rsyn::Cell cell1 = pin1.getInstance().asCell();
const int index1 = mapCellToIndex[cell1];
if ((index0 != -1 && index1 != -1) &&
index0 >= index1)
continue;
double weight =
R * 5 * (1 + driverCriticallity) /
std::max(1, (net.getNumPins() - 1));
if (index0 != -1 && index1 != -1) {
// add movable-to-movable connection
a.AddElement(index0, index1, -weight);
a.AddElement(index1, index0, -weight);
a.AddDiagonalElement(index0, weight);
a.AddDiagonalElement(index1, weight);
} else if (index0 != -1) {
// add movable-to-fixed connection
const DBUxy pos1 =
phDesign.getPinPosition(pin1);
bx[index0] += weight * pos1.x;
by[index0] += weight * pos1.y;
a.AddDiagonalElement(index0, weight);
} else if (index1 != -1) {
// add fixed-to-movable connection
const DBUxy pos0 =
phDesign.getPinPosition(pin0);
bx[index1] += weight * pos0.x;
by[index1] += weight * pos0.y;
a.AddDiagonalElement(index1, weight);
} // end if
} // end for
} // end for
} // end for
} // end method
// -----------------------------------------------------------------------------
// void IncrementalTimingDrivenQP::doNoHarm() {
// for( auto& netInfo : criticalNets ) {
// Rsyn::Net net = std::get<1>( netInfo );
// Rsyn::Pin driver = net.getDriver();
// double initialSlack = std::get<0>( netInfo );
// double currentSlack = timer->getPinWorstNegativeSlack( driver,
// Rsyn::LATE );
//
// if( initialSlack > currentSlack ) {
// for( auto pin : net.allPins(Rsyn::IN) ) {
//// auto cell = pin.getCell();
// session.moveCell( pin.getInstance().asCell(),
// //session.getPhysicalCell( pin.getCell()
//).initialPos,
// session.getInitialCellPosition(
// pin.getInstance() ),
// LegalizationMethod::LEG_NONE);
// }
// }
// }
//} // end method
// -----------------------------------------------------------------------------
bool IncrementalTimingDrivenQP::run(const Rsyn::Json& params) {
this->session = session;
libc = session.getService("rsyn.libraryCharacterizer");
timer = session.getService("rsyn.timer");
design = session.getDesign();
module = design.getTopModule();
routingEstimator = session.getService("rsyn.routingEstimator");
mapCellToIndex = design.createAttribute();
delayRatio = design.createAttribute();
infra = session.getService("ufrgs.ispd16.infra");
phDesign = session.getPhysicalDesign();
for (Rsyn::Instance instance : module.allInstances()) {
Rsyn::Cell cell = instance.asCell(); // TODO: hack, assuming
// that the instance is a
// cell
mapCellToIndex[cell] = -1;
delayRatio[cell] = 1.0;
}
alpha = params.value("alpha", 0.0f);
beta = params.value("beta", 1.0f);
const std::string legModeName =
params.value("legMode", "NEAREST_WHITESPACE");
if (legModeName == "NEAREST_WHITESPACE")
legMode = LegalizationMethod::LEG_NEAREST_WHITESPACE;
else if (legModeName == "EXACT_LOCATION")
legMode = LegalizationMethod::LEG_EXACT_LOCATION;
else if (legModeName == "MIN_LINEAR_DISPLACEMENT")
legMode = LegalizationMethod::LEG_MIN_LINEAR_DISPLACEMENT;
else if (legModeName == "NONE")
legMode = LegalizationMethod::LEG_NONE;
else
std::cout << "Invalid legalization method " << legModeName
<< "."
<< " Assuming default value.\n";
if (params.count("flow") && params["flow"] == "default") {
runPathStraighteningFlow();
} else if (params["flow"] == "netWeighting") {
runNetWeighteningFlow();
} else if (params["flow"] == "elmore") {
runPathStraighteningFlow_ELMORE();
} else {
std::cout << " Warning, invalid QP flow '" << params["flow"]
<< "'.";
std::cout << " Skipping QP...";
return false;
} // end if
return true;
} // end method
} // end namespace
| 41.728564 | 94 | 0.429973 | [
"vector"
] |
3dc8770d55d59d5d648a6289225972492fe997fb | 2,256 | cpp | C++ | src/scenepic/image.cpp | microsoft/scenepic | e3fd2c6312fa670a92b7888962b6812c262c6759 | [
"MIT"
] | 28 | 2021-10-05T08:51:26.000Z | 2022-03-18T11:19:23.000Z | src/scenepic/image.cpp | microsoft/scenepic | e3fd2c6312fa670a92b7888962b6812c262c6759 | [
"MIT"
] | 17 | 2021-10-05T11:36:17.000Z | 2022-02-10T13:33:43.000Z | src/scenepic/image.cpp | microsoft/scenepic | e3fd2c6312fa670a92b7888962b6812c262c6759 | [
"MIT"
] | 2 | 2021-12-12T16:42:51.000Z | 2022-02-23T11:50:14.000Z | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#include "image.h"
#include "base64.h"
#include "util.h"
#include <algorithm>
#include <cctype>
#include <exception>
#include <fstream>
namespace
{
bool end_with(const std::string& value, const std::string& ending)
{
if (value.size() < ending.size())
{
return false;
}
if (value.compare(value.size() - ending.size(), ending.size(), ending) == 0)
{
return true;
}
return false;
}
} // namespace
namespace scenepic
{
Image::Image(const std::string& image_id)
: m_image_id(image_id), m_data(), m_ext("None")
{}
void Image::load(const std::string& path)
{
std::ifstream ifs(path, std::ios::binary | std::ios::ate);
std::ifstream::pos_type pos = ifs.tellg();
m_data = std::vector<unsigned char>(static_cast<std::size_t>(pos));
ifs.seekg(0, std::ios::beg);
ifs.read(reinterpret_cast<char*>(m_data.data()), pos);
std::string name = path;
std::transform(name.begin(), name.end(), name.begin(), [](unsigned char c) {
return std::tolower(c);
});
if (end_with(name, "png"))
{
m_ext = "png";
}
else if (end_with(name, "jpeg") || end_with(name, "jpg"))
{
m_ext = "jpg";
}
else
{
throw std::invalid_argument("Not a path to a JPG or PNG image");
}
}
JsonValue Image::to_json() const
{
JsonValue obj;
obj["CommandType"] = "DefineImage";
obj["ImageId"] = m_image_id;
obj["Type"] = m_ext;
obj["Data"] =
base64_encode(m_data.data(), static_cast<unsigned int>(m_data.size()));
return obj;
}
const std::string& Image::image_id() const
{
return m_image_id;
}
const std::vector<std::uint8_t>& Image::data() const
{
return m_data;
}
std::vector<std::uint8_t>& Image::data()
{
return m_data;
}
Image& Image::data(const std::vector<std::uint8_t>& value)
{
m_data = value;
return *this;
}
const std::string& Image::ext() const
{
return m_ext;
}
Image& Image::ext(const std::string& value)
{
m_ext = value;
return *this;
}
std::string Image::to_string() const
{
return this->to_json().to_string();
}
} // namespace scenepic | 19.448276 | 80 | 0.598848 | [
"vector",
"transform"
] |
3dc945b86724640fe246d7667592eaac893c12f8 | 4,270 | cpp | C++ | 4/4_5.cpp | pietroblandizzi/cracking-the-coding-interview | fdd91cff35a4420909eceda60060f380b3ed74e4 | [
"MIT"
] | null | null | null | 4/4_5.cpp | pietroblandizzi/cracking-the-coding-interview | fdd91cff35a4420909eceda60060f380b3ed74e4 | [
"MIT"
] | null | null | null | 4/4_5.cpp | pietroblandizzi/cracking-the-coding-interview | fdd91cff35a4420909eceda60060f380b3ed74e4 | [
"MIT"
] | null | null | null | /*****************************************************************************
Copyright (c) [2017] [Blandizzi Pietro]
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 <iostream>
#include<vector>
using std::vector;
//simple BT
class NodeBT
{
public:
int data;
NodeBT* left;
NodeBT* right;
};
bool isSmaller (NodeBT*, int );
NodeBT* utilityCreate (vector<int>& v, int start,int end)
{
if (end < start)
return nullptr;
NodeBT* n = new NodeBT;
// divide the array in two
int middle = (start+end)/2;
n->data = v[middle];
n->left = utilityCreate (v,start, middle-1);
n->right = utilityCreate (v,middle+1, end);
return n;
}
/** My solution is maybe a bit complicate
It check for each subtree is a BST
checking if left < n < data and then
compute the max value in the left three
and check if it is bigger than it
and the same with the min value of the right
and check if it is smaller than it
**
Some int suggest to flip the logic
we can check if curr is always big then left
and always smaller then right
**/
/***** first solution****/
int biggestLeft (NodeBT* n)
{
if (n == nullptr)
return INT_MIN;
return std::max (n->data,biggestLeft(n->left));
}
int smallestRight (NodeBT* n)
{
if (n == nullptr)
return INT_MAX;
return std::min (n->data, smallestRight(n->right));
}
NodeBT* buildMinHeightBST (vector<int>& v)
{
return utilityCreate(v,0,v.size()-1);
}
// idea from the solution we do an in-order traversal and check
bool checkBST (NodeBT* n, int& prev)
{
if (n == nullptr)
return true;
//go left
if (!checkBST(n->left, prev))
return false;
//check the current
if (prev != INT_MIN && n->data <= prev)
return false;
prev = n->data;
//go right
if (!checkBST(n->right,prev))
return false;
return true;
}
//with min and max
bool checkBSTV2 (NodeBT* n, int& r_min, int& r_max)
{
if (n == nullptr)
return true;
if (n->data <= r_min || n->data > r_max )
return false;
bool left = checkBSTV2 (n->left, r_min, n->data);
bool right = checkBSTV2 (n->right,n->data,r_max);
return left && right;
}
//preorder
void printBSTPreOrd (NodeBT* root)
{
if (root != nullptr) {
std::cout << root->data << std::endl;
printBSTPreOrd (root->left);
printBSTPreOrd (root->right);
}
return;
}
void printBSTInOrd (NodeBT* root)
{
if (root != nullptr) {
printBSTInOrd (root->left);
std::cout << root->data << std::endl;
printBSTInOrd (root->right);
}
return;
}
// i will use the exercise 2 to create easily a BST
int main()
{
//Create the three
vector<int> v = {1,2,3,4,5,6,7,8,9,10};
NodeBT* root =buildMinHeightBST (v);
int d = INT_MIN;
if (checkBST(root,d))
std::cout << "yes" << std::endl;
else
std::cout << "no" << std::endl;
int r_min = INT_MIN;
int r_max = INT_MAX;
if (checkBSTV2(root,r_min,r_max))
std::cout << "yes" << std::endl;
else
std::cout << "no" << std::endl;
printBSTPreOrd(root);
std::cout<< "root " << root->right->data ;
return 0;
}
| 23.206522 | 82 | 0.623653 | [
"vector"
] |
3de07e3228478dd41f74a7a5f8596348aa464120 | 10,078 | cpp | C++ | src/TwoChQSz/TwoChQSz.cpp | lgds/NRG_USP | ff66846e92498aa429cce6fc5793bec23ad03eb4 | [
"MIT"
] | 3 | 2015-09-21T20:58:45.000Z | 2019-03-20T01:21:41.000Z | src/TwoChQSz/TwoChQSz.cpp | lgds/NRG_USP | ff66846e92498aa429cce6fc5793bec23ad03eb4 | [
"MIT"
] | null | null | null | src/TwoChQSz/TwoChQSz.cpp | lgds/NRG_USP | ff66846e92498aa429cce6fc5793bec23ad03eb4 | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/io.hpp>
#include <vector>
#include <cmath>
#include "NRGclasses.hpp"
#include "NRGfunctions.hpp"
#include "TwoChQSz.hpp"
#ifndef pi
#define pi 3.141592653589793238462643383279502884197169
#endif
bool AeqB(CNRGbasisarray *pAeigCut, int ibl1,int ibl2){
return (ibl1==ibl2);
}
double AtimesB(CNRGbasisarray *pAeig, CNRGbasisarray *pSingleSite,
int ibl1,int ibl2){
return((double)ibl1*ibl2);
}
int main (){
CNRGarray Aeig(2);
CNRGbasisarray AeigCut(2);
CNRGbasisarray Abasis(2);
CNRGbasisarray SingleSite(2);
// STL vector
CNRGmatrix Qm1fNQ[2];
CNRGmatrix MQQp1;
double U,ed,Gamma1,Gamma2;
vector<double> Params;
double Lambda;
double HalfLambdaFactor;
double Dband=1.0;
int calcdens;
double DN=0.0;
double TM=0.0;
double betabar=0.727;
double Temp=0.0;
double Sus=0.0;
//vector<double> SuscepChain;
char arqSus[32],arqname[32];
double chi_m1,chi_N[2];
double daux[4];
int Nsites,Nsitesmax=2;
int Ncutoff=700;
int UpdateBefCut=0;
int auxIn;
// outstream
ofstream OutFile;
// instream
ifstream InFile;
int ii,jj,i1,i2;
// STL iterator:
vector<double>::iterator diter;
// Test
CNRGmatrix HN;
HN.CheckForMatEl=AeqB;
HN.CalcMatEl=AtimesB;
if (HN.CheckForMatEl(&Abasis,2,2)) cout << "TRUE!" << endl;
else cout << "FALSE!" << endl;
cout << HN.CalcMatEl(&Abasis,&SingleSite,3,4) << endl;
exit(0);
/// ///
/// Begin code ///
/// ///
U=0.5;
ed=-0.5*U;
Gamma1=0.0282691;
Gamma2=0.0;
Lambda=2.5;
// Steps: Input parameters
InFile.open("nrg_input_TwoChAnderson.dat");
if (InFile.is_open())
{
InFile >> Nsitesmax;
InFile >> Ncutoff;
InFile >> U;
InFile >> Gamma1;
InFile >> Gamma2;
InFile >> ed;
InFile >> Lambda;
InFile >> Dband;
InFile >> auxIn;
InFile >> UpdateBefCut;
InFile >> calcdens;
}
else cout << "can't open nrg_input_TwoChAnderson.dat" << endl;
InFile.close();
///////////////////////////
///////////////////////////
if (calcdens==2)
{
//SuscepChain.clear();
strcpy(arqSus,"SuscepImp_25_726.dat");
strcpy(arqname,"SuscepChain.dat");
InFile.open(arqname);
if (InFile.fail())
{
cout << "Can't find " << arqname << endl;
strcpy(arqSus,"SuscepChain.dat");
calcdens=3;
}
///////////////////////
// else
// {
// while (!InFile.eof())
// {
// InFile >> Temp >> daux[0] >> daux[0] >> Sus;
// SuscepChain.push_back(Sus);
// }
// SuscepChain.pop_back();
// if (SuscepChain.size()<Nsitesmax-1)
// {
// cout << "Nsuscep = " << SuscepChain.size() << " Nsitesmax = " << Nsitesmax << endl;
// cout << " Longer SuscepChain needed! Doing it all over..." << endl;
// SuscepChain.clear();
// strcpy(arqSus,"SuscepChain.dat");
// calcdens=3;
// }
// }
// InFile.close();
//////////////////////////
}
if (calcdens==3)
{
strcpy(arqSus,"SuscepChain.dat");
U=0.0;ed=0.0;Gamma1=0.0;Gamma2=0.0;
}
///////////////////////////
///////////////////////////
HalfLambdaFactor=0.5*(1.0+(1.0/Lambda));
chi_m1=sqrt(2.0*Gamma1/pi)/(sqrt(Lambda)*HalfLambdaFactor);
double U_tilde=0.5*U/HalfLambdaFactor;
double ed_tilde=ed/HalfLambdaFactor;
double Gamma1_tilde=Gamma1*(2.0/pi)/(HalfLambdaFactor*HalfLambdaFactor);
double Gamma2_tilde=Gamma2*(2.0/pi)/(HalfLambdaFactor*HalfLambdaFactor);
OutFile.open("NRG_in.txt");
OutFile << "Begin NRG 2-ch calculation" << endl;
OutFile << " Nsitesmax = " << Nsitesmax-1 << endl;
OutFile << " Ncutoff = " << Ncutoff << endl;
OutFile << " U = " << U << endl;
OutFile << " Gamma1 = " << Gamma1 << endl;
OutFile << " Gamma2 = " << Gamma2 << endl;
OutFile << " ed = " << ed << endl;
OutFile << " Lambda = " << Lambda << endl;
OutFile << " Dband = " << Dband << endl;
OutFile << " UpdateBefCut = " << UpdateBefCut << endl;
OutFile << " calcdens = " << calcdens << endl;
OutFile << "=================================" << endl;
OutFile << "U~ = " << U_tilde << endl;
OutFile << "ed~ = " << ed_tilde << endl;
OutFile << "Gamma1~ = " << Gamma1_tilde<< endl;
OutFile << "Gamma2~ = " << Gamma2_tilde<< endl;
OutFile << "=================================" << endl;
OutFile.close();
// Define H0 (impurity + 1s site)
// Output:
// Aeig,
// fd_{1sigma} and fd_{2sigma} matrix elements
//
// Set single site (use pointers in the subroutines!!)
TwoChQSz_SetSingleSite(&SingleSite);
Params.push_back(U_tilde/sqrt(Lambda));
Params.push_back(ed_tilde/sqrt(Lambda));
Params.push_back(sqrt(Gamma1_tilde/Lambda));
Params.push_back(sqrt(Gamma2_tilde/Lambda));
Nsites=0;
DN=HalfLambdaFactor*pow(Lambda,(-(Nsites-1)/2.0) );
TM=DN/betabar;
cout << "DN = " << DN << "TM = " << TM << endl;
//TwoChQSz_SetH0Anderson(Params,&SingleSite,&Aeig,Qm1fNQ);
TwoChQSz_SetH0Anderson(Params,&SingleSite,&Aeig,&Abasis);
Aeig.PrintEn();
// Calculate Susceptibility
if ( (calcdens==2)||(calcdens==3) )
{
TM=DN/betabar;
Params.clear();
Params.push_back(betabar);
Sus=CalcSuscep(Params,&Aeig,1,false);
double Sus0=0.0;
int nlines=0;
if (calcdens==2)
{
InFile.open("SuscepChain.dat");
InFile.clear();
InFile.seekg(0, ios::beg); // rewind
if (InFile.fail())
{
cout << "Can't open SuscepChain.dat"<< endl;
}
else
{
while ( (!InFile.eof())&&(nlines<=Nsites) )
{
InFile >> daux[0] >> daux[0] >> daux[0] >> Sus0;
nlines++;
}
}
InFile.close();
}
//if (calcdens==2) Sus0=SuscepChain[Nsites];
else Sus-=1.0/8.0; // exclude dot site in the chain.
if (Nsites==0) OutFile.open(arqSus);
else OutFile.open(arqSus,ofstream::app);
OutFile.precision(20);
OutFile << scientific << TM << " " << Sus << " " << Sus0 << " " << Sus-Sus0 << endl;
OutFile.close();
}
TwoChQSz_UpdateQm1fQ(&SingleSite,&Aeig,&Abasis,Qm1fNQ);
// Check Matrix
for (int ich=1;ich<=2;ich++)
{
cout << " Printing Qm1fQ channel: " << ich << endl;
for (int ibl=0; ibl<Qm1fNQ[ich-1].NumMatBlocks();ibl++)
{
Qm1fNQ[ich-1].PrintMatBlock(ibl);
}
}
// Loop on Nsites: start from Nsites=0 (imp+1)
//
Nsites=1;
while (Nsites<=Nsitesmax)
{
DN=HalfLambdaFactor*pow(Lambda,(-(Nsites-1)/2.0) );
TM=DN/betabar;
cout << "DN = " << DN << "TM = " << TM << endl;
// 0 - Update chi_N, eps_N
daux[0]=(double)( 1.0-pow(Lambda,(-Nsites)) );
daux[1]=(double)sqrt( 1.0-pow(Lambda,-(2*Nsites-1)) );
daux[2]=(double)sqrt( 1.0-pow(Lambda,-(2*Nsites+1)) );
daux[3]=0.5*(1.0+(1.0/Lambda))*(double)sqrt(Lambda);
chi_N[0]=daux[0]/(daux[1]*daux[2]);
chi_N[1]=daux[0]/(daux[1]*daux[2]);
cout << "chi_N = " << chi_N[0] << " " << chi_N[1] << endl;
cout << "Nsites = " << Nsites << endl;
cout << "BEG Eig Nshell = " << Aeig.Nshell << endl;
// 1 - Eliminate states and Build Abasis
cout << "Cutting states..." << endl;
AeigCut.CNRGbasisarray::ClearAll();
AeigCut=CutStates(&Aeig, Ncutoff);
cout << "... done cutting states." << endl;
// Calculate new matrix elements using the CUT basis:
// update Qm1fNQ, Qm1cdQ, etc.
if ( (UpdateBefCut==0)&&(Nsites>1) )
{
cout << "Updating matrices after cutting... " << endl;
TwoChQSz_UpdateMatrixAfterCutting(&SingleSite,
&AeigCut, &Abasis, Qm1fNQ, &MQQp1);
cout << "... done updating matrices. " << endl;
}
//Q1Q2Sz_BuildBasis(&AeigCut,&Abasis,&SingleSite,UpdateBefCut);
// doesnt work
QSz_BuildBasis(&AeigCut,&Abasis,&SingleSite,UpdateBefCut);
cout << "No blocks = " << Abasis.NumBlocks() << endl;
cout << "No states = " << Abasis.Nstates() << endl;
//Abasis.PrintAll();
// 2 - Build and diagonalize H_N+1
Params.clear();
Params.push_back(chi_N[0]);
Params.push_back(chi_N[1]);
Params.push_back(Lambda);
cout << "Diagonalizing HN... " << endl;
TwoChQSz_DiagHN(Params,&Abasis,&SingleSite,Qm1fNQ,&Aeig);
Aeig.PrintEn();
cout << "..done diagonalizing HN. " << endl;
// 3 - Update Qm1f1NQ, Qm1f2Q, Qm1cdQ, etc.
if ( (UpdateBefCut==1)&&(Nsites<Nsitesmax) )
{
cout << "Updating matrices before cutting... " << endl;
TwoChQSz_UpdateQm1fQ(&SingleSite,&Aeig,&Abasis,Qm1fNQ);
cout << "... done updating matrices. " << endl;
}
// Calculate Susceptibility
if ( (calcdens==2)||(calcdens==3) )
{
TM=DN/betabar;
Params.clear();
Params.push_back(betabar);
Sus=CalcSuscep(Params,&Aeig,1,false);
double Sus0=0.0;
int nlines=0;
// Gets SuscepChain iteration by iteration
if (calcdens==2)
{
InFile.open("SuscepChain.dat");
InFile.clear();
InFile.seekg(0, ios::beg); // rewind
if (InFile.fail())
{
cout << "Can't find " << arqname << endl;
}
else
{
while ( (!InFile.eof())&&(nlines<=Nsites) )
{
InFile >> daux[0] >> daux[0] >> daux[0] >> Sus0;
nlines++;
}
}
InFile.close();
}
//if (calcdens==2) Sus0=SuscepChain[Nsites];
else Sus-=1.0/8.0; // exclude dot site in the chain.
if (Nsites==0) OutFile.open(arqSus);
else OutFile.open(arqSus,ofstream::app);
OutFile.precision(20);
OutFile << scientific << TM << " " << Sus << " " << Sus0 << " " << Sus-Sus0 << endl;
OutFile.close();
}
// 4 - Update Nsites
Nsites++;
}
cout << "=== Calculation Finished! ==== "<< endl;
OutFile.open("NRG_end.txt");
OutFile << "END NRG calculation" << endl;
OutFile.close();
cout << "Calling destructors " << endl;
}
//END code
| 23.437209 | 93 | 0.563306 | [
"vector"
] |
3de103b5651d124a8066880daf947abc2f6f867d | 210 | cpp | C++ | CPhysics/DifferentialSolver/EulerImplSysSolver.cpp | glensand/CPhysics | dca21414275a0fc9b0725e843de0f346c1529f4a | [
"MIT"
] | 1 | 2019-10-18T16:53:11.000Z | 2019-10-18T16:53:11.000Z | CPhysics/DifferentialSolver/EulerImplSysSolver.cpp | glensand/CPhysics | dca21414275a0fc9b0725e843de0f346c1529f4a | [
"MIT"
] | 29 | 2019-09-26T04:08:58.000Z | 2020-06-17T03:04:02.000Z | CPhysics/DifferentialSolver/EulerImplSysSolver.cpp | glensand/CPhysics | dca21414275a0fc9b0725e843de0f346c1529f4a | [
"MIT"
] | null | null | null | #include "EulerImplSysSolver.h"
namespace CPhysics
{
IDifferentialSystemSolver::ReturnType EulerImplSysSolver::Solve(const Params* params) const
{
std::vector<std::vector<Real>> res{};
return res;
}
} | 13.125 | 91 | 0.747619 | [
"vector"
] |
3de520b7ec163c21d641086013998e9e46c0c9bf | 16,809 | cpp | C++ | test/VectorTests.cpp | DNKpp/Simple-Vector | 522adc19150a0284d4b7e5a1112a3b219b030559 | [
"BSL-1.0"
] | null | null | null | test/VectorTests.cpp | DNKpp/Simple-Vector | 522adc19150a0284d4b7e5a1112a3b219b030559 | [
"BSL-1.0"
] | 2 | 2021-06-06T19:21:11.000Z | 2022-02-17T18:06:23.000Z | test/VectorTests.cpp | DNKpp/Simple-Vector | 522adc19150a0284d4b7e5a1112a3b219b030559 | [
"BSL-1.0"
] | null | null | null | // Copyright Dominic Koepke 2021 - 2021.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// https://www.boost.org/LICENSE_1_0.txt)
#include <catch2/catch.hpp>
#include "Simple-Vector/Generators.hpp"
#include "Simple-Vector/Vector.hpp"
#include <ranges>
using namespace sl::vec;
namespace
{
template <class TValueType, std::size_t VDims>
constexpr Vector<TValueType, VDims> make_iota_vector(TValueType begin = {}) noexcept
{
if constexpr (std::integral<TValueType>)
{
return Vector<TValueType, VDims>{ gen::iota{ begin } };
}
else
{
return static_cast<Vector<TValueType, VDims>>(Vector<int, VDims>{ gen::iota{ static_cast<int>(begin) } });
}
}
template <std::ranges::borrowed_range TRange>
class approx_range_matcher final : public Catch::MatcherBase<std::remove_cvref_t<TRange>>
{
public:
using range_type = std::remove_cvref_t<TRange>;
using view_type = std::views::all_t<TRange>;
explicit approx_range_matcher(const range_type& range) :
m_View{ range }
{
}
bool match(const range_type& other) const override
{
return std::ranges::equal
(
m_View,
other,
[](const auto& lhs, const auto& rhs)
{
constexpr auto inf = std::numeric_limits<std::ranges::range_value_t<range_type>>::infinity();
if (lhs == inf || rhs == inf)
{
return lhs == rhs;
}
return (lhs - rhs) == Approx(0);
}
);
}
[[nodiscard]]
std::string describe() const override
{
return "Approx equals: " + Catch::rangeToString(m_View);
}
private:
view_type m_View;
};
template <std::ranges::borrowed_range TRange>
auto approx_range(TRange&& range)
{
return approx_range_matcher<TRange>{ range };
}
}
#pragma warning(disable: 26444)
TEMPLATE_TEST_CASE
(
"vector_value_t should yield the same result as value_type of Vector.",
"[vector][traits]",
int,
float,
const int&,
const int,
int&&
)
#pragma warning(default: 26444)
{
using vector_t = Vector<TestType, 1>;
REQUIRE(std::same_as<typename vector_t::value_type, vector_value_t<vector_t>>);
}
#pragma warning(disable: 26444)
TEMPLATE_TEST_CASE_SIG
(
"vector_dims_v should yield the same result as dimensions of Vector.",
"[vector][traits]",
((std::size_t VDims), VDims),
(1),
(2),
(3)
)
#pragma warning(default: 26444)
{
using vector_t = Vector<int, VDims>;
REQUIRE(vector_t::dimensions == VDims);
REQUIRE(vector_t::dimensions == vector_dims_v<vector_t>);
}
TEST_CASE("Vector types should be default constructible with zeros", "[Vector][construction]")
{
constexpr Vector<int, 3> vec;
REQUIRE(std::cmp_equal(vec.dimensions, 3));
REQUIRE(std::cmp_equal(vec[0], 0));
REQUIRE(std::cmp_equal(vec[1], 0));
REQUIRE(std::cmp_equal(vec[2], 0));
}
TEST_CASE("Vector types should be constructible via generator", "[vector][construction]")
{
constexpr int value = 42;
constexpr Vector<int, 3> vec{ gen::fill{ value } };
REQUIRE(std::ranges::all_of(vec, [](auto val) { return val == value; }));
}
#pragma warning(disable: 26444)
TEMPLATE_PRODUCT_TEST_CASE
(
"Vector types should be explicitly convertible between different value_types.",
"[vector][construction]",
std::tuple,
((Vector<int, 3>, Vector<std::size_t, 3>),
(Vector<std::size_t, 5>, Vector<int, 5>))
)
#pragma warning(default: 26444)
{
using Source_t = std::tuple_element_t<0, TestType>;
using Target_t = std::tuple_element_t<1, TestType>;
constexpr auto result = static_cast<Target_t>(Source_t{ gen::iota{ 1 } });
REQUIRE(result == Target_t{ gen::iota{ 1 } });
}
#if __cpp_nontype_template_args >= 201911L
// well, clang sucks
#pragma warning(disable: 26444)
TEMPLATE_TEST_CASE_SIG
(
"Vector types should be explicitly convertible between different dimension sizes.",
"[vector][construction]",
((std::size_t VSourceDims, std::size_t VTargetDims, auto VExpectedRange), VSourceDims, VTargetDims, VExpectedRange),
(3, 2, std::to_array({ 1, 2 })),
(3, 5, std::to_array({ 1, 2, 3, 0, 0 }))
)
#pragma warning(default: 26444)
{
using SourceVector_t = Vector<int, VSourceDims>;
using TargetVector_t = Vector<int, VTargetDims>;
constexpr auto result = static_cast<TargetVector_t>(SourceVector_t{ gen::iota{ 1 } });
REQUIRE(std::ranges::equal(result, VExpectedRange));
}
#endif
#pragma warning(disable: 26444)
#if __cpp_nontype_template_args < 201911L
TEMPLATE_TEST_CASE_SIG
(
"Vector types should be constructible by direct initialization",
"[Vector][construction]",
((auto... V), V...),
(1, 2, 3)
)
#else
TEMPLATE_TEST_CASE_SIG
(
"Vector types should be constructible by direct initialization",
"[Vector][construction]",
((auto... V), V...),
(1, 2, 3),
(4, 3, 2.f, 1.)
)
#endif
#pragma warning(default: 26444)
{
constexpr Vector vec{ V... };
REQUIRE(std::cmp_equal(vec.dimensions, sizeof...(V)));
}
TEST_CASE("Vector types should be iteratable", "[Vector][iteration]")
{
constexpr std::size_t dims = 5;
auto vec = make_iota_vector<int, 5>(1);
REQUIRE(std::cmp_equal(dims, std::ranges::distance(vec)));
REQUIRE(std::cmp_equal(vec[0], 1));
REQUIRE(std::cmp_equal(vec[1], 2));
REQUIRE(std::cmp_equal(vec[2], 3));
REQUIRE(std::cmp_equal(vec[3], 4));
REQUIRE(std::cmp_equal(vec[4], 5));
REQUIRE(std::equal(std::begin(vec), std::end(vec), std::begin(std::as_const(vec)), std::end(std::as_const(vec))));
REQUIRE(std::equal(std::begin(vec), std::end(vec), std::cbegin(vec), std::cend(vec)));
}
TEST_CASE("Vector types should be reverse iteratable", "[Vector][iteration]")
{
auto vec = make_iota_vector<int, 5>(1);
REQUIRE(std::cmp_equal(*std::rbegin(vec), 5));
REQUIRE(std::cmp_equal(*(std::rbegin(vec) + 1), 4));
REQUIRE(std::cmp_equal(*(std::rbegin(vec) + 2), 3));
REQUIRE(std::cmp_equal(*(std::rbegin(vec) + 3), 2));
REQUIRE(std::cmp_equal(*(std::rbegin(vec) + 4), 1));
REQUIRE(std::equal(std::rbegin(vec), std::rend(vec), std::rbegin(std::as_const(vec)), std::rend(std::as_const(vec))));
REQUIRE(std::equal(std::rbegin(vec), std::rend(vec), std::crbegin(vec), std::crend(vec)));
}
namespace
{
template <class T>
concept has_y_function = requires(T t)
{
{ t.y() };
};
template <class T>
concept has_z_function = requires(T t)
{
{ t.z() };
};
}
TEST_CASE("Vector has x member function", "[Vector]")
{
auto vec = make_iota_vector<int, 3>(1);
REQUIRE(vec.x() == 1);
REQUIRE(std::as_const(vec).x() == 1);
}
#pragma warning(disable: 26444)
TEMPLATE_TEST_CASE_SIG
(
"Vector has y member function",
"[Vector]",
((std::size_t VDims), VDims),
(1),
(2),
(3)
)
#pragma warning(default: 26444)
{
auto vec = make_iota_vector<int, VDims>(1);
using Vector_t = decltype(vec);
if constexpr (has_y_function<Vector_t>)
{
REQUIRE(std::cmp_less_equal(2, Vector_t::dimensions));
REQUIRE(vec.y() == 2);
REQUIRE(std::as_const(vec).y() == 2);
}
}
#pragma warning(disable: 26444)
TEMPLATE_TEST_CASE_SIG
(
"Vector has z member function",
"[Vector]",
((std::size_t VDims), VDims),
(2),
(3),
(4)
)
#pragma warning(default: 26444)
{
auto vec = make_iota_vector<int, VDims>(1);
using Vector_t = decltype(vec);
if constexpr (has_z_function<Vector_t>)
{
REQUIRE(std::cmp_less_equal(3, Vector_t::dimensions));
REQUIRE(std::as_const(vec).z() == 3);
}
}
TEST_CASE("Vector should be equality comparable.", "[vector]")
{
constexpr std::size_t dims = 2;
const auto [firstBegin, secBegin, expected] = GENERATE
(
table<int,
int,
bool>({
{ 1, 1, true},
{ 1, 0, false},
{ -2, -2, true},
{ -4, 4, false}
})
);
const auto vec1 = make_iota_vector<int, dims>(firstBegin);
const auto vec2 = make_iota_vector<int, dims>(secBegin);
const auto eqResult = vec1 == vec2;
const auto neqResult = vec1 != vec2;
REQUIRE(eqResult == expected);
REQUIRE(neqResult != expected);
}
#pragma warning(disable: 26444)
TEMPLATE_TEST_CASE_SIG
(
"Vector should be addable with types equally or convertible to its value_type.",
"[vector][arithmetic]",
((class T, std::size_t VDims), T, VDims),
(int, 1),
(int, 2),
(int, 3),
(unsigned int, 4),
(unsigned int, 5),
(unsigned int, 6),
(float, 7),
(float, 8),
(float, 9)
)
#pragma warning(default: 26444)
{
const Vector vec = make_iota_vector<int, VDims>(1);
const auto value = GENERATE(as<T>{}, 0, 1, 5, -1, -2);
const Vector sum = vec + value;
REQUIRE
(
std::ranges::equal
(
std::ranges::transform_view{ vec, [value](auto v){ return v + static_cast<int>(value); } },
sum
)
);
}
#pragma warning(disable: 26444)
TEMPLATE_TEST_CASE_SIG
(
"Vector should be subtractable with types equally or convertible to its value_type.",
"[vector][arithmetic]",
((class T, std::size_t VDims), T, VDims),
(int, 1),
(int, 2),
(int, 3),
(unsigned int, 4),
(unsigned int, 5),
(unsigned int, 6),
(float, 7),
(float, 8),
(float, 9)
)
#pragma warning(default: 26444)
{
const Vector vec = make_iota_vector<int, VDims>(1);
const auto value = GENERATE(as<T>{}, 0, 1, 5, -1, -2);
const Vector diff = vec - value;
REQUIRE(diff + value == vec);
}
#pragma warning(disable: 26444)
TEMPLATE_TEST_CASE_SIG
(
"Vector should be commutatively multiplyable with types equally or convertible to its value_type.",
"[vector][arithmetic]",
((class T, std::size_t VDims), T, VDims),
(int, 1),
(int, 2),
(int, 3),
(unsigned int, 4),
(unsigned int, 5),
(unsigned int, 6),
(float, 7),
(float, 8),
(float, 9)
)
#pragma warning(default: 26444)
{
const Vector vec = make_iota_vector<int, VDims>(1);
auto value = GENERATE(as<T>{}, 0, 1, 5, -1, -2);
const Vector product = vec * value;
const Vector commutativeProduct = value * vec;
REQUIRE
(
std::ranges::equal
(
std::ranges::transform_view{ vec, [value](auto v){ return static_cast<int>(v * value); } },
product
)
);
REQUIRE(product == commutativeProduct);
}
#pragma warning(disable: 26444)
TEMPLATE_TEST_CASE_SIG
(
"Vector should be dividable with types equally or convertible to its value_type.",
"[vector][arithmetic]",
((class T, std::size_t VDims), T, VDims),
(int, 1),
(int, 2),
(int, 3),
(unsigned int, 4),
(unsigned int, 5),
(unsigned int, 6),
(float, 7),
(float, 8),
(float, 9)
)
#pragma warning(default: 26444)
{
const Vector vec = make_iota_vector<int, VDims>(1);
const auto value = GENERATE(as<T>{}, 1, 5, -1, -2);
const Vector fraction = vec / value;
REQUIRE
(
std::ranges::equal
(
fraction,
std::ranges::transform_view{ vec, [value](auto v){ return static_cast<int>(v / value); } }
)
);
}
#pragma warning(disable: 26444)
TEMPLATE_TEST_CASE_SIG
(
"Vector should be modable with types equally or convertible to its value_type.",
"[vector][arithmetic]",
((class T, std::size_t VDims), T, VDims),
(int, 1),
(int, 2),
(int, 3),
(unsigned int, 4),
(unsigned int, 5),
(unsigned int, 6),
(float, 7),
(float, 8),
(float, 9)
)
#pragma warning(default: 26444)
{
const Vector vec = make_iota_vector<int, VDims>(1);
const auto value = GENERATE(as<T>{}, 1, 5, -1, -2);
const Vector remainder = vec % value;
REQUIRE
(
std::ranges::equal
(
remainder,
std::views::transform(vec, [value](auto v){ return v % static_cast<int>(value); })
)
);
}
#pragma warning(disable: 26444)
TEMPLATE_TEST_CASE_SIG
(
"Vector should be addable by Vectors, whichs value_types are equally or convertible to the targets value_type.",
"[vector][arithmetic]",
((class T, std::size_t VDims), T, VDims),
(int, 1),
(int, 2),
(int, 3),
(unsigned int, 4),
(unsigned int, 5),
(unsigned int, 6),
(float, 7),
(float, 8),
(float, 9)
)
#pragma warning(default: 26444)
{
const auto vec1 = make_iota_vector<int, VDims>(1);
const auto vec2 = make_iota_vector<T, VDims>(1);
const Vector sum = vec1 + vec2;
REQUIRE(sum == 2 * vec1);
}
#pragma warning(disable: 26444)
TEMPLATE_TEST_CASE_SIG
(
"Vector should be subtractable by Vectors, whichs value_types are equally or convertible to the targets value_type.",
"[vector][arithmetic]",
((class T, std::size_t VDims), T, VDims),
(int, 1),
(int, 2),
(int, 3),
(unsigned int, 4),
(unsigned int, 5),
(unsigned int, 6),
(float, 7),
(float, 8),
(float, 9)
)
#pragma warning(default: 26444)
{
const auto vec1 = make_iota_vector<int, VDims>(1);
const auto vec2 = make_iota_vector<T, VDims>(1);
const Vector sub = vec1 - vec2;
REQUIRE(sub == Vector<int, VDims>{});
}
#pragma warning(disable: 26444)
TEMPLATE_TEST_CASE_SIG
(
"length_squared should calculate the squared length of given vectors",
"[vector][algorithm]",
((std::size_t VDims, int VExpected), VDims, VExpected),
(1, 1),
(2, 5),
(3, 14)
)
#pragma warning(default: 26444)
{
const auto vec = make_iota_vector<int, VDims>(1);
auto squaredLength = sl::vec::length_squared(vec);
REQUIRE(VExpected == squaredLength);
}
#pragma warning(disable: 26444)
TEMPLATE_TEST_CASE_SIG
(
"length should calculate the length of given vectors",
"[vector][algorithm]",
((std::size_t VDims, int VExpectedSq), VDims, VExpectedSq),
(1, 1),
(2, 5),
(3, 14)
)
#pragma warning(default: 26444)
{
const auto vec = make_iota_vector<int, VDims>(1);
const auto length = sl::vec::length(vec);
REQUIRE(length == Approx(std::sqrt(VExpectedSq)));
}
#pragma warning(disable: 26444)
TEMPLATE_TEST_CASE_SIG
(
"dot_product should calculate the dot product of the two given vectors",
"[vector][algorithm]",
((class TOther, std::size_t VDims, int VExpected), TOther, VDims, VExpected),
(int, 1, 2),
(int, 2, 8),
(int, 3, 20),
(float, 1, 2),
(float, 2, 8),
(float, 3, 20)
)
#pragma warning(default: 26444)
{
const auto vec1 = make_iota_vector<int, VDims>(1);
const auto vec2 = make_iota_vector<TOther, VDims>(2);
int dotProd = sl::vec::dot_product(vec1, vec2);
REQUIRE(dotProd == VExpected);
}
#pragma warning(disable: 26444)
TEMPLATE_TEST_CASE_SIG
(
"normalized should scale vectors to length of 1.",
"[vector][algorithm]",
((std::size_t VDims), VDims),
(1),
(2),
(3)
)
#pragma warning(default: 26444)
{
const auto iotaBegin = GENERATE(as<float>{}, 1, 3, 10);
const auto vec = make_iota_vector<float, VDims>(iotaBegin);
const auto normalizedVec = normalized(vec);
REQUIRE(sl::vec::length(normalizedVec) == Approx(1));
}
#if __cpp_nontype_template_args >= 201911L
// well, clang sucks
#pragma warning(disable: 26444)
TEMPLATE_TEST_CASE_SIG
(
"projected should project vector1 onto vector2",
"[vector][algorithm]",
((auto VSource, auto VTarget, auto VExpected), VSource, VTarget, VExpected),
(std::to_array({ 1. }), std::to_array({ 1. }), std::to_array({ 1. })),
(std::to_array({ 1. }), std::to_array({ -1. }), std::to_array({ 1. })),
(std::to_array({ 1., 1. }), std::to_array({ 2., 0. }), std::to_array({ 1., 0. })),
(std::to_array({ 1., 1. }), std::to_array({ -2., 0. }), std::to_array({ 1., 0. })),
(std::to_array({ 1., 4. }), std::to_array({ 2., 1. }), std::to_array({ 12./5., 6./5. })),
(std::to_array({ 3., 0. }), std::to_array({ 0., 3. }), std::to_array({ 0., 0. })),
(std::to_array({ 1., 0., 0. }), std::to_array({ 1., 0., 0. }), std::to_array({ 1., 0., 0. })),
(std::to_array({ 1., 1., 1. }), std::to_array({ 0., 5., 5. }), std::to_array({ 0., 1., 1. }))
)
#pragma warning(default: 26444)
{
constexpr auto dims = std::size(VSource);
using Vector_t = Vector<double, dims>;
constexpr Vector_t source{ gen::range{ VSource }};
constexpr Vector_t target{ gen::range{ VTarget }};
constexpr Vector_t expected{ gen::range{ VExpected }};
const auto projectedVec = projected(source, target);
REQUIRE_THAT(projectedVec, approx_range(expected));
}
#endif
#if __cpp_nontype_template_args >= 201911L
// well, clang sucks
#pragma warning(disable: 26444)
TEMPLATE_TEST_CASE_SIG
(
"lerp should interpolate between vector1 and vector2",
"[vector][algorithm]",
((auto VBegin, auto VEnd, auto VLerpValue, auto VExpected), VBegin, VEnd, VLerpValue, VExpected),
(std::to_array({ 1. }), std::to_array({ 2 }), 1., std::to_array({ 2. })),
(std::to_array({ 1., 2., 3. }), std::to_array({ 3., 2., 1. }), 0.5, std::to_array({ 2., 2., 2. }))
)
#pragma warning(default: 26444)
{
constexpr auto dims = std::size(VBegin);
using Vector_t = Vector<double, dims>;
constexpr Vector_t begin{ gen::range{ VBegin }};
constexpr Vector_t end{ gen::range{ VEnd }};
constexpr Vector_t expected{ gen::range{ VExpected }};
constexpr auto lerpedVec = lerp(begin, end, VLerpValue);
REQUIRE_THAT(lerpedVec, approx_range(expected));
}
#endif
TEST_CASE("inversed should compute the inverse of each element", "[vector][algorithm]")
{
const auto [src, expected] = GENERATE
(
table<Vector<double,
3>,
Vector<double,
3>>({
{ Vector{ 1., 1., 1. }, Vector{ 1., 1., 1. } },
{ Vector{ 1., 2., 3. }, Vector{ 1., 0.5, 1./3. } },
{ Vector{ 1., 2., 0. }, Vector{ 1., 0.5, std::numeric_limits<double>::infinity() } }
})
);
const auto inversedVec = inversed(src);
REQUIRE_THAT(inversedVec, approx_range(expected));
}
| 24.646628 | 119 | 0.665298 | [
"vector",
"transform"
] |
3decdf5bcf2e0768fdfc60b59072ca0f2320b659 | 2,095 | hpp | C++ | Sprites.hpp | JurajX/Snake | dc27d400c04dbcc113259c96d074885a7e100b9b | [
"Unlicense"
] | null | null | null | Sprites.hpp | JurajX/Snake | dc27d400c04dbcc113259c96d074885a7e100b9b | [
"Unlicense"
] | null | null | null | Sprites.hpp | JurajX/Snake | dc27d400c04dbcc113259c96d074885a7e100b9b | [
"Unlicense"
] | null | null | null | //
// Sprites.hpp
// Snake
//
// Created by X on 16.05.18.
//
#ifndef Sprites_hpp
#define Sprites_hpp
#include "SDL.h"
#include "SDL_image.h"
#include <vector>
#include <map>
#include <string>
//-------------------- Helper structures
// Note that (in the integer representation) neither direction nor sum of any two directions
// are equal. Keep this in mind, it will become useful in Snake::LoadImages().
enum class Direction :int { UP=1, DOWN=2, RIGHT=4, LEFT=7 };
struct Part {
SDL_Point pt;
Direction front;
int FrontToInt() const;
int BackToInt() const;
};
//-------------------- Snake class
class Snake {
public:
Snake(SDL_Point playground_dimensions,
int tile_size,
Uint32 pixel_format=SDL_PIXELFORMAT_RGBA32);
Snake(const Snake&) = delete;
Snake& operator=(const Snake&) = delete;
Snake(Snake&&) = delete;
Snake& operator=(Snake&&) = delete;
~Snake();
void LoadImages();
void SetNewDirection(Direction direction);
int Update(SDL_Point pellet_top_left);
void BlitOnPlayground(SDL_Surface *playground_surface);
bool ColidesWithPoint(SDL_Point position) const;
bool SelfColision() const;
private:
std::map<int, SDL_Surface*> mHeadSurfaces;
std::map<int, SDL_Surface*> mBodySurfaces;
std::vector<Part> mBodyParts;
Direction mDirection;
SDL_Point mPlaygroundDims;
int mTileSize;
};
//-------------------- Pellet class
class Pellet {
public:
Pellet(SDL_Point playground_dimensions,
int tile_size,
Uint32 pixel_format=SDL_PIXELFORMAT_RGBA32);
Pellet(const Pellet&) = delete;
Pellet& operator=(const Pellet&) = delete;
Pellet(Pellet&&) = delete;
Pellet& operator=(Pellet&&) = delete;
~Pellet();
void LoadImages();
void MoveRandomly();
SDL_Point GetTopLeft() const;
void BlitOnPlayground(SDL_Surface *playground_surface) const;
private:
SDL_Point mTopLeft;
int mTileSize;
SDL_Point mPlaygroundDims;
std::vector<SDL_Surface*> mSurfaces;
int mSurfaceIndex;
};
#endif /* Sprites_hpp */
| 22.771739 | 92 | 0.664439 | [
"vector"
] |
3df5134b520f17fb4c915eb4be7f7041a659facd | 6,519 | cpp | C++ | ROVER/src/noisy/led.cpp | majitaki/arliss2019_tadpole | 22c2f976dfb91d345a6be878a45bcd361247943b | [
"MIT"
] | null | null | null | ROVER/src/noisy/led.cpp | majitaki/arliss2019_tadpole | 22c2f976dfb91d345a6be878a45bcd361247943b | [
"MIT"
] | null | null | null | ROVER/src/noisy/led.cpp | majitaki/arliss2019_tadpole | 22c2f976dfb91d345a6be878a45bcd361247943b | [
"MIT"
] | null | null | null | #include <wiringPiI2C.h>
#include <wiringPi.h>
#include <softPwm.h>
#include <time.h>
#include <string.h>
#include <fstream>
#include <sstream>
#include <unistd.h>
#include <stdlib.h>
#define _USE_MATH_DEFINES
#include <math.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <stdarg.h>
#include <wiringSerial.h>
#include <iostream>
#include <iomanip>
#include <ctime>
#include <sstream>
#include <tuple>
#include "../rover_util/utils.h"
#include "./led.h"
LED gLED;
bool LED::onInit(const struct timespec& time)
{
pinMode(PIN_LED_R, OUTPUT);
pinMode(PIN_LED_G, OUTPUT);
pinMode(PIN_LED_B, OUTPUT);
softPwmCreate(PIN_LED_R, 0, 256);
softPwmCreate(PIN_LED_G, 0, 256);
softPwmCreate(PIN_LED_B, 0, 256);
digitalWrite(PIN_LED_R, LOW);
digitalWrite(PIN_LED_G, LOW);
digitalWrite(PIN_LED_B, LOW);
mLastUpdateTime1 = mLastUpdateTime2 = time;
r = g = b = t = s = u = v = p = d = 0;
rbw = bnk = hf = false;
error_brink();
return true;
}
void LED::onClean()
{
digitalWrite(PIN_LED_R, LOW);
digitalWrite(PIN_LED_G, LOW);
digitalWrite(PIN_LED_B, LOW);
rbw = false;
}
bool LED::onCommand(const std::vector<std::string>& args)
{
switch (args.size())
{
case 1:
Debug::print(LOG_PRINT, "(R,G,B)=(%d,%d,%d)\r\n", r, g, b);
if (bnk)
Debug::print(LOG_PRINT, "Brink=true (%f,%f)\r\n", u, v);
else
Debug::print(LOG_PRINT, "Brink=false\r\n");
if (rbw)
Debug::print(LOG_PRINT, "Rainbow=true (%f)\r\n", s);
else
Debug::print(LOG_PRINT, "Rainbow=false\r\n");
if (hf)
Debug::print(LOG_PRINT, "HSV=true (%f)\r\n", p);
else
Debug::print(LOG_PRINT, "HSV=false\r\n");
Debug::print(LOG_PRINT, "led : Show led status\r\nled s : Stop lightning LED\r\nled test : = led 255 255 255\r\nled rainbow [seconds] : Rainbow w/ [seconds]\r\nled rainbow s : Stop rainbow\r\nled brink s : Stop brinking\r\nled brink [seconds] : Brink w/ [seconds]\r\nled brink [sec1] [sec2] : Brink w/ sec1 on / sec2 off\r\nled hsv [sec] : hsv w/ [sec]\r\nled hsv s : stop hsv\r\nled [R] [G] [B] : Light LED w/ RGB in 256 steps (0-255)\r\n");
return true;
break;
case 2:
if (args[1].compare("s") == 0)
{
clearLED();
return true;
}
else if (args[1].compare("test") == 0)
{
setColor(255, 255, 255);
return true;
}
break;
case 3:
if (args[1].compare("rainbow") == 0)
{
if (args[2].compare("s") == 0)
{
stopRainbow();
Debug::print(LOG_PRINT, "stop rainbow\r\n");
return true;
}
else
{
rainbow(atof(args[2].c_str()));
Debug::print(LOG_PRINT, "rainbow(%f)\r\n", s);
return true;
}
}
else if (args[1].compare("brink") == 0)
{
if (args[2].compare("s") == 0)
{
stopBrink();
Debug::print(LOG_PRINT, "stop brink\r\n");
return true;
}
else
{
brink(atof(args[2].c_str()));
Debug::print(LOG_PRINT, "brink(%f)\r\n", u);
return true;
}
}
else if (args[1].compare("hsv") == 0)
{
if (args[2].compare("s") == 0)
{
stopHSV();
Debug::print(LOG_PRINT, "stop hsv\r\n");
return true;
}
else
{
startHSV(atof(args[2].c_str()));
Debug::print(LOG_PRINT, "hsv(%f)\r\n", atof(args[2].c_str()));
return true;
}
}
break;
case 4:
if (args[1].compare("brink") == 0)
{
brink(atof(args[2].c_str()), atof(args[3].c_str()));
Debug::print(LOG_PRINT, "brink(%f,%f)\r\n", u, v);
return true;
}
else
{
r = (int)atof(args[1].c_str());
if (r>255)
r = 255;
g = (int)atof(args[2].c_str());
if (g>255)
g = 255;
b = (int)atof(args[3].c_str());
if (b>255)
b = 255;
reflect();
return true;
}
break;
}
Debug::print(LOG_PRINT, "led : Show led status\r\nled s : Stop lightning LED\r\nled test : = led 255 255 255\r\nled rainbow [seconds] : Rainbow w/ [seconds]\r\nled rainbow s : Stop rainbow\r\nled brink s : Stop brinking\r\nled brink [seconds] : Brink w/ [seconds]\r\nled brink [sec1] [sec2] : Brink w/ sec1 on / sec2 off\r\nled hsv [sec] : hsv w/ [sec]\r\nled hsv s : stop hsv\r\nled [R] [G] [B] : Light LED w/ RGB in 256 steps (0-255)\r\n");
return false;
}
void LED::reflect()
{
softPwmWrite(PIN_LED_R, r);
softPwmWrite(PIN_LED_G, g);
softPwmWrite(PIN_LED_B, b);
}
void LED::setColor(int x)
{
r = (x >> 16) & 255;
g = (x >> 8) & 255;
b = x & 255;
reflect();
}
void LED::setColor(int c1, int c2, int c3)
{
r = (c1>255 ? 255 : c1);
g = (c2>255 ? 255 : c2);
b = (c3>255 ? 255 : c3);
reflect();
}
void LED::turnOff()
{
softPwmWrite(PIN_LED_R, 0);
softPwmWrite(PIN_LED_G, 0);
softPwmWrite(PIN_LED_B, 0);
}
void LED::onUpdate(const struct timespec& time)
{
if (hf)
{
if (Time::dt(time, mLastUpdateTime1)<p)
;
else
{
hsv((float)d);
d += 0.01;
if (d>1.0)
d = 0;
mLastUpdateTime1 = time;
}
}
else if (rbw)
{
if (Time::dt(time, mLastUpdateTime1)<s)
;
else
{
setColor(((t >> 2) & 1) * 255, ((t >> 1) & 1) * 255, (t & 1) * 255);
t++;
if (t == 8)
t = 1;
mLastUpdateTime1 = time;
}
}
if (bnk)
{
if (Time::dt(time, mLastUpdateTime2)<u)
reflect();
else if (Time::dt(time, mLastUpdateTime2)<u + v)
turnOff();
else
mLastUpdateTime2 = time;
}
}
void LED::rainbow(double x)
{
s = x;
rbw = true;
hf = false;
}
void LED::stopRainbow()
{
rbw = false;
}
void LED::startHSV(double x)
{
p = x;
d = 0;
hf = true;
rbw = false;
}
void LED::stopHSV()
{
hf = false;
}
void LED::brink(double x)
{
u = v = x;
bnk = true;
}
void LED::brink(double x, double y)
{
u = x;
v = y;
bnk = true;
}
void LED::stopBrink()
{
bnk = false;
}
void LED::hsv(float h)
{
float s_ = 1.0f, v_ = 1.0f, r_, g_, b_;
r_ = g_ = b_ = v_;
h *= 6.0f;
int i = (int)h;
float f = h - (float)i;
switch (i)
{
default:
case 0:
g_ *= 1 - s_ * (1 - f);
b_ *= 1 - s_;
break;
case 1:
r_ *= 1 - s_ * f;
b_ *= 1 - s_;
break;
case 2:
r_ *= 1 - s_;
b_ *= 1 - s_ * (1 - f);
break;
case 3:
r_ *= 1 - s_;
g_ *= 1 - s_ * f;
break;
case 4:
r_ *= 1 - s_ * (1 - f);
g_ *= 1 - s_;
break;
case 5:
g_ *= 1 - s_;
b_ *= 1 - s_ * f;
break;
}
setColor((int)(r_ * 256), (int)(g_ * 256), (int)(b_ * 255));
}
void LED::clearLED()
{
stopBrink();
stopRainbow();
stopHSV();
turnOff();
}
void LED::error_brink()
{
if (fails.empty()) {
setColor(255, 255, 255);
}
//for (auto itr = fails.begin(); itr != fails.end(); ++itr) {
//}
}
void LED::add_error(int r, int g, int b)
{
//fails.add()
}
LED::LED()
{
setName("led");
setPriority(TASK_PRIORITY_ACTUATOR, TASK_INTERVAL_ACTUATOR);
}
LED::~LED()
{
}
| 18.57265 | 444 | 0.57877 | [
"vector"
] |
3df5a0e37e8152ef1a93daa7671423c6ef4803a5 | 5,906 | cc | C++ | Client.cc | kcirick/simplewm | a3d5fc153dc9dce95d6b632f686c0eb99d090b19 | [
"MIT"
] | 30 | 2016-09-13T10:55:37.000Z | 2021-11-14T20:31:50.000Z | Client.cc | kcirick/simplewm | a3d5fc153dc9dce95d6b632f686c0eb99d090b19 | [
"MIT"
] | null | null | null | Client.cc | kcirick/simplewm | a3d5fc153dc9dce95d6b632f686c0eb99d090b19 | [
"MIT"
] | 3 | 2021-04-04T12:35:26.000Z | 2022-02-13T20:47:25.000Z | #include "Globals.hh"
#include "Configuration.hh"
#include "XScreen.hh"
#include "Client.hh"
//--- Constructor and destructor -----------------------------------------
Client::Client(XScreen* screen, Window win) : g_xscreen(screen), window(win) {
say(DEBUG, "Client::Client() constructor");
iconified = false;
marked = false;
urgent = false;
fixed = false;
initGeometry();
XSelectInput(g_xscreen->getDisplay(), window, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
g_xscreen->grabButtons(window, CONTEXT_CLIENT);
g_xscreen->initEWMHClient(window);
g_xscreen->setEWMHDesktop(window, g_xscreen->getCurrentTagIndex());
// map window
XMoveResizeWindow(g_xscreen->getDisplay(), window, geom.x, geom.y, geom.width, geom.height);
XMapWindow(g_xscreen->getDisplay(), window);
}
Client::~Client(){ }
//------------------------------------------------------------------------
void Client::initGeometry(){
XWindowAttributes attr;
XGetWindowAttributes(g_xscreen->getDisplay(), window, &attr);
Window dw;
int x, y, di;
uint dui;
XQueryPointer(g_xscreen->getDisplay(), g_xscreen->getRoot(), &dw, &dw, &x, &y, &di, &di, &dui);
geom.x = x-(attr.width/2);
geom.y = y-(attr.height/2);
geom.width=attr.width;
geom.height=attr.height;
// Fix spilling of the window outside the screen
int border_width = g_xscreen->getBorderWidth();
int spill_x = geom.x+geom.width - g_xscreen->getWidth();
int spill_y = geom.y+geom.height - g_xscreen->getHeight();
if(spill_x > 0) geom.x -= spill_x+border_width;
if(spill_y > 0) geom.y -= spill_y+border_width;
if(geom.x < 0) geom.x = border_width;
if(geom.y < 0) geom.y = border_width;
// create border
unsigned int frame_pixel = (g_xscreen->getBorderColour(UNFOCUSED)).pixel;
XWindowChanges wc;
wc.border_width = border_width;
XConfigureWindow(g_xscreen->getDisplay(), window, CWBorderWidth, &wc);
XSetWindowBorder(g_xscreen->getDisplay(), window, frame_pixel);
}
void Client::updateGeometry(Geometry this_geom) {
geom = this_geom;
XMoveResizeWindow(g_xscreen->getDisplay(), window, geom.x, geom.y, geom.width, geom.height);
// not necessary?
send_config();
}
void Client::updateBorderColour(bool current) {
Display *display = g_xscreen->getDisplay();
XColor frame_colour = g_xscreen->getBorderColour(UNFOCUSED);
if(fixed) frame_colour = g_xscreen->getBorderColour(FIXED);
if(marked) frame_colour = g_xscreen->getBorderColour(MARKED);
if(current && !iconified) {
if(!(marked || fixed)){
frame_colour = g_xscreen->getBorderColour(FOCUSED);
}
}
XSetWindowBorder(display, window, frame_colour.pixel);
}
void Client::send_config() {
XConfigureEvent ce;
ce.type = ConfigureNotify;
ce.event = window;
ce.window = window;
ce.x = geom.x;
ce.y = geom.y;
ce.width = geom.width;
ce.height = geom.height;
ce.border_width = 0;
ce.above = None;
ce.override_redirect = False;
XSendEvent(g_xscreen->getDisplay(), window, False, StructureNotifyMask, (XEvent *)&ce);
}
void Client::kill(bool force_kill) {
int i,n,found=0;
Atom * protocols;
if(!force_kill && XGetWMProtocols(g_xscreen->getDisplay(), window, &protocols, &n)){
for(i=0; i<n; i++)
if(protocols[i]==g_xscreen->getAtom(WM_DELETE_WINDOW))
found++;
XFree(protocols);
}
if(found){
XEvent ev;
ev.type = ClientMessage;
ev.xclient.window = window;
ev.xclient.message_type = g_xscreen->getAtom(WM_PROTOCOLS);
ev.xclient.format = 32;
ev.xclient.data.l[0] = g_xscreen->getAtom(WM_DELETE_WINDOW);
ev.xclient.data.l[1] = CurrentTime;
XSendEvent(g_xscreen->getDisplay(), window, False, NoEventMask, &ev);
} else
XKillClient(g_xscreen->getDisplay(), window);
}
void Client::dragMove() {
say(DEBUG, "Client::dragMove()");
Display* display = g_xscreen->getDisplay();
Window root_win = g_xscreen->getRoot();
if(XGrabPointer(display, root_win, False, ButtonPressMask|ButtonReleaseMask|PointerMotionMask, GrabModeAsync, GrabModeAsync,
None, g_xscreen->move_curs, CurrentTime)!=GrabSuccess)
return;
XEvent ev;
int old_cx = geom.x;
int old_cy = geom.y;
Window dw;
int x, y, di;
uint dui;
XQueryPointer(display, root_win, &dw, &dw, &x, &y, &di, &di, &dui);
for (;;) {
XMaskEvent(display, ButtonReleaseMask|PointerMotionMask, &ev);
switch (ev.type) {
case MotionNotify:
if (ev.xmotion.root != root_win) break;
geom.x = old_cx + (ev.xmotion.x - x) + 2;
geom.y = old_cy + (ev.xmotion.y - y) + 2;
XMoveWindow(display, window, geom.x, geom.y);
break;
case ButtonRelease:
XUngrabPointer(display, CurrentTime);
updateGeometry(geom);
return;
default: break;
}
}
}
void Client::dragResize() {
say(DEBUG, "Client::dragResize()");
Display* display = g_xscreen->getDisplay();
Window root_win = g_xscreen->getRoot();
if(XGrabPointer(display, root_win, False, ButtonPressMask|ButtonReleaseMask|PointerMotionMask, GrabModeAsync, GrabModeAsync,
None, g_xscreen->resize_curs, CurrentTime)!=GrabSuccess)
return;
XEvent ev;
int old_cx = geom.x;
int old_cy = geom.y;
XWarpPointer(display, None, window, 0, 0, 0, 0, geom.width, geom.height);
for (;;) {
g_xscreen->drawOutline(geom); /* clear */
XMaskEvent(display, ButtonReleaseMask|PointerMotionMask, &ev);
g_xscreen->drawOutline(geom);
switch (ev.type) {
case MotionNotify:
if (ev.xmotion.root != root_win)
break;
geom.width = ev.xmotion.x - old_cx;
geom.height = ev.xmotion.y - old_cy;
break;
case ButtonRelease:
XUngrabPointer(display, CurrentTime);
updateGeometry(geom);
return;
default: break;
}
}
}
| 29.093596 | 128 | 0.653742 | [
"geometry"
] |
3df6422974bfcbb5d601e5b61165c23f63370968 | 8,271 | cpp | C++ | torch/csrc/jit/passes/onnx/fixup_onnx_loop.cpp | wenhaopeter/read_pytorch_code | 491f989cd918cf08874dd4f671fb7f0142a0bc4f | [
"Intel",
"X11"
] | null | null | null | torch/csrc/jit/passes/onnx/fixup_onnx_loop.cpp | wenhaopeter/read_pytorch_code | 491f989cd918cf08874dd4f671fb7f0142a0bc4f | [
"Intel",
"X11"
] | null | null | null | torch/csrc/jit/passes/onnx/fixup_onnx_loop.cpp | wenhaopeter/read_pytorch_code | 491f989cd918cf08874dd4f671fb7f0142a0bc4f | [
"Intel",
"X11"
] | null | null | null | #include <torch/csrc/jit/passes/onnx/fixup_onnx_loop.h>
#include <torch/csrc/jit/passes/dead_code_elimination.h>
#include <torch/csrc/jit/passes/onnx/peephole.h>
namespace torch {
namespace jit {
namespace onnx {
using namespace ::c10::onnx;
}
Node* CreateCastToBoolNode(Value* val, Graph* graph) {
Node* cast_node = graph->create(onnx::Cast);
cast_node->addInput(val);
cast_node->i_(attr::to, /*Bool*/ 9);
return cast_node;
}
Node* InsertCastForCond(Value* cond_val, Graph* graph, Node* consumer_node) {
// prev: cond_val -> consumer_node
// after: cond_val -> cast -> consumer_node
// NOTE: The cast is required because operators like PyTorch Greater/Less
// return tensor in type torch.uint8. However the type for condition
// input in ONNX Loop must be bool.
Node* cast_node = CreateCastToBoolNode(cond_val, graph);
cast_node->insertBefore(consumer_node);
consumer_node->replaceInputWith(cond_val, cast_node->output());
return cast_node;
}
bool IsCondCastRequired(Value* cond_val) {
const auto& type = cond_val->type();
if (auto tt = type->cast<TensorType>()) {
if (auto scalar_type = tt->scalarType()) {
return *scalar_type != c10::kBool;
}
}
return !type->isSubtypeOf(BoolType::get());
}
void FixupONNXLoops(Block* block) {
for (auto* node : block->nodes()) {
if (node->kind() == ::c10::onnx::Loop) {
auto* loop_node = node;
auto* graph = loop_node->owningGraph();
// add cast to condition input outside the loop.
Value* cond_val = loop_node->inputs()[1];
if (IsCondCastRequired(cond_val))
InsertCastForCond(cond_val, graph, loop_node);
// Setup Loop input cond and i.
TORCH_INTERNAL_ASSERT(loop_node->blocks().size() == 1);
auto* sub_block = loop_node->blocks()[0];
Value* cond = sub_block->insertInput(1, "cond");
cond->setType(BoolType::create());
Value* i = sub_block->inputs()[0];
i->setType(TensorType::fromNumberType(IntType::get()));
// add cast to condition input inside the loop.
Value* next_cond_val = sub_block->outputs()[0];
if (IsCondCastRequired(next_cond_val))
InsertCastForCond(next_cond_val, graph, sub_block->return_node());
}
for (Block* block : node->blocks()) {
FixupONNXLoops(block);
}
}
}
namespace {
bool IsErasableSequence(const Node* loop_node, size_t i) {
AT_ASSERT(loop_node->blocks().size() == 1);
auto* sub_block = loop_node->blocks()[0];
auto* out_node = sub_block->outputs()[i - 1]->node();
auto* in_val = sub_block->inputs()[i];
if (out_node->kind() != ::c10::onnx::SequenceInsert) {
return false;
}
if (out_node->inputs().size() == 3) {
// Non-default insert position is not supported.
return false;
}
if (out_node->input(0) != in_val) {
// Only SequenceInsert that applies on loop-carried sequence is supported.
return false;
}
const auto seq_node_kind = loop_node->inputs()[i]->node()->kind();
if (seq_node_kind != ::c10::onnx::SequenceEmpty) {
// Initial sequence must be empty.
return false;
}
if (out_node->output()->uses().size() != 1) {
// The sequence is not supported to be used elsewhere.
return false;
}
return true;
}
} // anonymous namespace
// ONNX::Loop does not support Sequence type as loop-carried dependencies. Only
// tensors are supported. This pass converts Sequence loop-carried dependencies
// to scan_outputs. In opset 11, only the below pattern is supported.
//
// PTIR graph:
// ...
// %res.1 : Tensor[] = prim::ListConstruct()
// %res : Tensor[] = prim::Loop(%11, %22, %res.1)
// block0(%i.1 : Tensor, %res.6 : Tensor[]):
// ...
// %res.3 : Tensor[] = aten::append(%res.6, %17)
// -> (%22, %res.3)
// return (%res.3)
//
// ONNX graph:
// ...
// %res : Tensor = onnx::Loop(%11, %22)
// block0(%i.1 : Tensor):
// ...
// -> (%22, %17)
// %res_seq : Tensor[] = onnx::SplitToSequence[keepdims=0](%res)
// return (%res_seq)
void ConvertSequenceDependencies(Block* block) {
for (auto* node : block->nodes()) {
for (Block* block : node->blocks()) {
ConvertSequenceDependencies(block);
}
if (node->kind() == ::c10::onnx::Loop) {
auto* loop_node = node;
auto* graph = loop_node->owningGraph();
AT_ASSERT(loop_node->blocks().size() == 1);
auto* sub_block = loop_node->blocks()[0];
std::vector<size_t> idx_to_remove;
// loop sub-block inputs are (iter, cond, loop-carried dependencies)
// loop sub-block outputs are ( cond, loop-carried dependencies, scan
// outputs) loop inputs are (iter, cond, loop-carried
// dependencies) loop outputs are ( loop-carried
// dependencies, scan outputs)
for (size_t i = 2; i < sub_block->inputs().size(); ++i) {
if (IsErasableSequence(loop_node, i)) {
auto* seq_node = sub_block->outputs()[i - 1]->node();
// Replace sequence output with the inserted element.
auto inserted_value = seq_node->input(1);
sub_block->return_node()->replaceInputWith(
seq_node->output(), inserted_value);
// Split the added scan_output back to expected tensor sequence.
auto loop_output = loop_node->output(i - 2);
Node* split_node =
loop_node->owningGraph()->create(onnx::SplitToSequence);
loop_output->replaceAllUsesWith(split_node->output());
split_node->i_(attr::keepdims, 0);
split_node->addInput(loop_output);
split_node->insertAfter(loop_node);
split_node->output()->copyMetadata(loop_output);
// Update loop output metadata.
loop_output->copyMetadata(inserted_value);
loop_output->setType(c10::unshapedType(loop_output->type()));
// The node that produces sequence should be safe to remove now.
seq_node->destroy();
idx_to_remove.push_back(i);
}
}
for (size_t i = 0; i < idx_to_remove.size(); ++i) {
size_t idx = idx_to_remove[i] - i;
sub_block->eraseInput(idx);
loop_node->removeInput(idx);
// Swap output order. Move all scan outputs to the back.
sub_block->return_node()->addInput(
sub_block->return_node()->inputs().at(idx - 1));
sub_block->return_node()->removeInput(idx - 1);
auto loop_out = loop_node->addOutput();
loop_out->copyMetadata(loop_node->outputs().at(idx - 2));
loop_node->outputs().at(idx - 2)->replaceAllUsesWith(loop_out);
loop_node->eraseOutput(idx - 2);
}
}
}
}
static void FuseSequenceSplitConcat(Block* b) {
for (auto it = b->nodes().begin(), end = b->nodes().end(); it != end; ++it) {
for (auto* child_block : it->blocks()) {
FuseSequenceSplitConcat(child_block);
}
if (it->kind() == onnx::ConcatFromSequence &&
it->input()->node()->kind() == onnx::SplitToSequence) {
if (it->input()->uses().size() > 1) {
continue;
}
auto split_node = it->input()->node();
auto concat_node = *it;
const auto split_axis =
split_node->hasAttribute(attr::axis) ? split_node->i(attr::axis) : 0;
const auto split_keepdims = split_node->hasAttribute(attr::keepdims)
? split_node->i(attr::keepdims)
: 1;
const auto concat_axis = concat_node->i(attr::axis);
const auto concat_new_axis = concat_node->hasAttribute(attr::new_axis)
? concat_node->i(attr::new_axis)
: 0;
const bool has_input_split = split_node->inputs().size() == 2;
if (has_input_split) {
continue;
}
if (split_keepdims == concat_new_axis) {
continue;
}
if (split_axis != concat_axis) {
continue;
}
concat_node->output()->replaceAllUsesWith(split_node->input());
}
}
}
void FixupONNXLoops(std::shared_ptr<Graph>& graph) {
FixupONNXLoops(graph->block());
ConvertSequenceDependencies(graph->block());
FuseSequenceSplitConcat(graph->block());
EliminateDeadCode(
graph->block(),
true,
DCESideEffectPolicy::ALLOW_DELETING_NODES_WITH_SIDE_EFFECTS);
}
} // namespace jit
} // namespace torch
| 32.6917 | 80 | 0.623987 | [
"vector"
] |
3df83c1f2e51740214369277c575113d6b59d363 | 7,391 | cpp | C++ | OgreMain/src/Compositor/Pass/PassDepthCopy/OgreCompositorPassDepthCopy.cpp | jondo2010/ogre | c1e836d453b2bca0d4e2eb6a32424fe967092b52 | [
"MIT"
] | null | null | null | OgreMain/src/Compositor/Pass/PassDepthCopy/OgreCompositorPassDepthCopy.cpp | jondo2010/ogre | c1e836d453b2bca0d4e2eb6a32424fe967092b52 | [
"MIT"
] | null | null | null | OgreMain/src/Compositor/Pass/PassDepthCopy/OgreCompositorPassDepthCopy.cpp | jondo2010/ogre | c1e836d453b2bca0d4e2eb6a32424fe967092b52 | [
"MIT"
] | null | null | null | /*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2014 Torus Knot Software Ltd
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 "OgreStableHeaders.h"
#include "Compositor/Pass/PassDepthCopy/OgreCompositorPassDepthCopy.h"
#include "Compositor/Pass/PassDepthCopy/OgreCompositorPassDepthCopyDef.h"
#include "Compositor/OgreCompositorNodeDef.h"
#include "Compositor/OgreCompositorNode.h"
#include "Compositor/OgreCompositorWorkspace.h"
#include "Compositor/OgreCompositorWorkspaceListener.h"
#include "OgreDepthBuffer.h"
#include "OgreRenderTarget.h"
#include "OgreRenderSystem.h"
namespace Ogre
{
void CompositorPassDepthCopyDef::setDepthTextureCopy( const String &srcTextureName,
const String &dstTextureName )
{
if( srcTextureName.find( "global_" ) == 0 )
{
mParentNodeDef->addTextureSourceName( srcTextureName, 0,
TextureDefinitionBase::TEXTURE_GLOBAL );
}
if( dstTextureName.find( "global_" ) == 0 )
{
mParentNodeDef->addTextureSourceName( dstTextureName, 0,
TextureDefinitionBase::TEXTURE_GLOBAL );
}
mSrcDepthTextureName = srcTextureName;
mDstDepthTextureName = dstTextureName;
}
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
CompositorPassDepthCopy::CompositorPassDepthCopy( const CompositorPassDepthCopyDef *definition,
const CompositorChannel &target,
CompositorNode *parentNode ) :
CompositorPass( definition, target, parentNode ),
mDefinition( definition ),
mCopyFailed( false )
{
}
//-----------------------------------------------------------------------------------
void CompositorPassDepthCopy::execute( const Camera *lodCamera )
{
//Execute a limited number of times?
if( mNumPassesLeft != std::numeric_limits<uint32>::max() )
{
if( !mNumPassesLeft )
return;
--mNumPassesLeft;
}
//Call beginUpdate if we're the first to use this RT
if( mDefinition->mBeginRtUpdate )
mTarget->_beginUpdate();
//Fire the listener in case it wants to change anything
CompositorWorkspaceListener *listener = mParentNode->getWorkspace()->getListener();
if( listener )
listener->passPreExecute( this );
executeResourceTransitions();
//Should we retrieve every update, or cache the return values
//and listen to notifyRecreated and family of funtions?
const CompositorChannel *srcChannel = mParentNode->_getDefinedTexture(
mDefinition->mSrcDepthTextureName );
const CompositorChannel *dstChannel = mParentNode->_getDefinedTexture(
mDefinition->mDstDepthTextureName );
DepthBuffer *srcDepthBuffer = srcChannel->target->getDepthBuffer();
DepthBuffer *dstDepthBuffer = dstChannel->target->getDepthBuffer();
if( !mCopyFailed )
{
mCopyFailed = !srcDepthBuffer->copyTo( dstDepthBuffer );
}
if( mCopyFailed && srcDepthBuffer != dstDepthBuffer &&
mDefinition->mAliasDepthBufferOnCopyFailure )
{
dstChannel->target->attachDepthBuffer( srcDepthBuffer, false );
}
if( listener )
listener->passPosExecute( this );
//Call endUpdate if we're the last pass in a row to use this RT
if( mDefinition->mEndRtUpdate )
mTarget->_endUpdate();
}
//-----------------------------------------------------------------------------------
void CompositorPassDepthCopy::_placeBarriersAndEmulateUavExecution( BoundUav boundUavs[64],
ResourceAccessMap &uavsAccess,
ResourceLayoutMap &resourcesLayout )
{
RenderSystem *renderSystem = mParentNode->getRenderSystem();
const RenderSystemCapabilities *caps = renderSystem->getCapabilities();
const bool explicitApi = caps->hasCapability( RSC_EXPLICIT_API );
if( !explicitApi )
return;
OGRE_EXCEPT( Exception::ERR_NOT_IMPLEMENTED, "D3D12/Vulkan/Mantle Stub",
"CompositorPassDepthCopy::_placeBarriersAndEmulateUavExecution" );
/*{
const CompositorChannel *srcChannel = mParentNode->_getDefinedTexture(
mDefinition->mSrcDepthTextureName );
//Check <anything> -> CopySrc
ResourceLayoutMap::iterator currentLayout = resourcesLayout.find(
srcChannel->target->getDepthBuffer() );
if( currentLayout->second != ResourceLayout::CopySrc )
{
addResourceTransition( currentLayout,
ResourceLayout::CopySrc,
ReadBarrier::? ); //Likely 0
}
const CompositorChannel *dstChannel = mParentNode->_getDefinedTexture(
mDefinition->mDstDepthTextureName );
//Check <anything> -> CopyDst
currentLayout = resourcesLayout.find( dstChannel->target->getDepthBuffer() );
if( currentLayout->second != ResourceLayout::CopyDst )
{
addResourceTransition( currentLayout,
ResourceLayout::CopyDst,
ReadBarrier::? ); //Likely 0
}
}*/
//Do not use base class functionality at all.
//CompositorPass::_placeBarriersAndEmulateUavExecution();
}
}
| 44.257485 | 108 | 0.571776 | [
"object"
] |
ad063233155a7992f7c45f7db24b3687ee48acc0 | 4,660 | cpp | C++ | LeetCode/C++/General/Medium/SumRootToLeafNumbers/main.cpp | busebd12/InterviewPreparation | e68c41f16f7790e44b10a229548186e13edb5998 | [
"MIT"
] | null | null | null | LeetCode/C++/General/Medium/SumRootToLeafNumbers/main.cpp | busebd12/InterviewPreparation | e68c41f16f7790e44b10a229548186e13edb5998 | [
"MIT"
] | null | null | null | LeetCode/C++/General/Medium/SumRootToLeafNumbers/main.cpp | busebd12/InterviewPreparation | e68c41f16f7790e44b10a229548186e13edb5998 | [
"MIT"
] | null | null | null | #include "../TreeNode.h"
#include <cmath>
#include <iostream>
#include <stack>
#include <utility>
#include <vector>
/*
* Solutions:
*
* 1. Recursive pre-order traversal, building each root-to-leaf path as we go.
* When we reach the end of a path, we sum up the path and add that sum to our
* overall sum, result.
*
* Time complexity: O(n^2) [where n is the number of nodes in the binary tree]
*
* Space complexity average case: O(h + ph) [where h is the height of the binary tree and p is the number of root-to-leaf paths]
* Space complexity worse case: O(n + pn) [where n is the height of the binary tree and p is the number of root-to-lear paths]
*
* 2. Iterative version of the first solution.
*
* Time complexity: O(n^2) [where n is the number of nodes in the binary tree]
*
* Space complexity average case: O(h + ph) [where h is the height of the binary tree and p is the number of root-to-leaf paths]
* Space complexity worse case: O(n + pn) [where n is the height of the binary tree and p is the number of root-to-lear paths]
*
*
* 3. Instead of building each path, we just maintain the sum of the path(s) as we traverse the tree. When we reach the end
* of a root-to-leaf path, we add it to the overall sum, result.
*
* Time complexity: O(n) [where n is the number of nodes in the binary tree]
*
* Space complexity average case: O(h) [where h is the height of the binary tree]
* Space complexity worse case: O(n) [where n is the height of the binary tree]
*/
void preOrderTraversal(TreeNode* root, std::vector<int> path, int & result)
{
if(root==nullptr)
{
return;
}
path.emplace_back(root->val);
if(root->right==nullptr && root->left==nullptr)
{
int sum=0;
int power=int(path.size()-1);
for(auto & number : path)
{
int value=number * static_cast<int>(std::pow(10, power));
sum+=value;
power--;
}
result+=sum;
}
preOrderTraversal(root->left, path, result);
preOrderTraversal(root->right, path, result);
}
int sumNumbers(TreeNode* root)
{
int result=0;
if(root==nullptr)
{
return result;
}
std::vector<int> path;
preOrderTraversal(root, path, result);
return result;
}
int sumNumbers(TreeNode* root)
{
int result=0;
if(root==nullptr)
{
return result;
}
std::stack<std::pair<TreeNode*, std::vector<int>>> stk;
stk.push(std::make_pair(root, std::vector<int>()));
while(!stk.empty())
{
auto element=stk.top();
stk.pop();
element.second.emplace_back(element.first->val);
if(element.first->left==nullptr && element.first->right==nullptr)
{
int sum=0;
int power=int(element.second.size()-1);
for(auto & number : element.second)
{
int value=number * static_cast<int>(std::pow(10, power));
sum+=value;
power--;
}
result+=sum;
}
if(element.first->right!=nullptr)
{
stk.push(std::make_pair(element.first->right, element.second));
}
if(element.first->left!=nullptr)
{
stk.push(std::make_pair(element.first->left, element.second));
}
}
return result;
}
void preOrderTraversal(TreeNode* root, int sum, int & result)
{
if(root==nullptr)
{
return;
}
sum=sum*10 + root->val;
if(root->right==nullptr && root->left==nullptr)
{
result+=sum;
}
preOrderTraversal(root->left, sum, result);
preOrderTraversal(root->right, sum, result);
}
int sumNumbers(TreeNode* root)
{
int result=0;
if(root==nullptr)
{
return result;
}
int sum=0;
preOrderTraversal(root, sum, result);
return result;
}
int sumNumbers(TreeNode* root)
{
int result=0;
if(root==nullptr)
{
return result;
}
std::stack<std::pair<TreeNode*, int>> stk;
stk.push(std::make_pair(root, 0));
while(!stk.empty())
{
auto element=stk.top();
stk.pop();
element.second=element.second*10 + element.first->val;
if(element.first->left==nullptr && element.first->right==nullptr)
{
result+=element.second;
}
if(element.first->right!=nullptr)
{
stk.push(std::make_pair(element.first->right, element.second));
}
if(element.first->left!=nullptr)
{
stk.push(std::make_pair(element.first->left, element.second));
}
}
return result;
} | 22.085308 | 128 | 0.58927 | [
"vector"
] |
ad096be4fa10c60db80ed464996c77b562cf8923 | 3,821 | cpp | C++ | isis/src/clipper/objs/ClipperWacFcCamera/ClipperWacFcCamera.cpp | robotprogrammer22/ISIS3 | 8a2ec4bb3c91969c81d75c681051a1fe77028788 | [
"CC0-1.0"
] | null | null | null | isis/src/clipper/objs/ClipperWacFcCamera/ClipperWacFcCamera.cpp | robotprogrammer22/ISIS3 | 8a2ec4bb3c91969c81d75c681051a1fe77028788 | [
"CC0-1.0"
] | null | null | null | isis/src/clipper/objs/ClipperWacFcCamera/ClipperWacFcCamera.cpp | robotprogrammer22/ISIS3 | 8a2ec4bb3c91969c81d75c681051a1fe77028788 | [
"CC0-1.0"
] | null | null | null | /**
* @file
*
* Unless noted otherwise, the portions of Isis written by the USGS are public
* domain. See individual third-party library and package descriptions for
* intellectual property information,user agreements, and related information.
*
* Although Isis has been used by the USGS, no warranty, expressed or implied,
* is made by the USGS as to the accuracy and functioning of such software
* and related material nor shall the fact of distribution constitute any such
* warranty, and no responsibility is assumed by the USGS in connection
* therewith.
*
* For additional information, launch
* $ISISROOT/doc//documents/Disclaimers/Disclaimers.html in a browser or see
* the Privacy & Disclaimers page on the Isis website,
* http://isis.astrogeology.usgs.gov, and the USGS privacy and disclaimers on
* http://www.usgs.gov/privacy.html.
*/
#include "ClipperWacFcCamera.h"
#include <QString>
#include "CameraDetectorMap.h"
#include "CameraDistortionMap.h"
#include "CameraFocalPlaneMap.h"
#include "CameraGroundMap.h"
#include "CameraSkyMap.h"
#include "IString.h"
#include "iTime.h"
#include "NaifStatus.h"
using namespace std;
namespace Isis {
/**
* Constructs a Clipper wide angle framing camera object.
*
* @param lab Pvl label from a Clipper wide angle framing camera image.
*
* @author Stuart Sides and Summer Stapleton-Greig
*
* @internal
*/
ClipperWacFcCamera::ClipperWacFcCamera(Cube &cube) : FramingCamera(cube) {
m_spacecraftNameLong = "Europa Clipper";
m_spacecraftNameShort = "Clipper";
m_instrumentNameLong = "Europa Imaging System Framing Wide Angle Camera";
m_instrumentNameShort = "EIS-FWAC";
NaifStatus::CheckErrors();
SetFocalLength();
SetPixelPitch();
// Set up detector map, focal plane map, and distortion map
new CameraDetectorMap(this);
new CameraFocalPlaneMap(this, naifIkCode());
new CameraDistortionMap(this);
// Setup the ground and sky map
new CameraGroundMap(this);
new CameraSkyMap(this);
Pvl &lab = *cube.label();
PvlGroup &inst = lab.findGroup("Instrument", Pvl::Traverse);
QString startTime = inst["StartTime"];
iTime etStart(startTime);
// double exposureDuration = (double)inst["ExposureDuration"] / 1000.0;
// pair<iTime, iTime> startStop = ShutterOpenCloseTimes(et, exposureDuration);
setTime(etStart.Et()); // Set the time explicitly for now to prevent segfault
// Internalize all the NAIF SPICE information into memory.
LoadCache();
NaifStatus::CheckErrors();
}
/**
* Returns the shutter open and close times. The LORRI camera doesn't use a shutter to start and
* end an observation, but this function is being used to get the observation start and end times,
* so we will simulate a shutter.
*
* @param exposureDuration ExposureDuration keyword value from the labels,
* converted to seconds.
* @param time The StartTime keyword value from the labels, converted to
* ephemeris time.
*
* @return @b pair < @b iTime, @b iTime > The first value is the shutter
* open time and the second is the shutter close time.
*
*/
pair<iTime, iTime> ClipperWacFcCamera::ShutterOpenCloseTimes(double time,
double exposureDuration) {
return FramingCamera::ShutterOpenCloseTimes(time - exposureDuration / 2.0, exposureDuration);
}
}
/**
* This is the function that is called in order to instantiate a ClipperWacFcCamera
* object.
*
* @param lab Cube labels
*
* @return Isis::Camera* ClipperWacFcCamera
* @internal
*/
extern "C" Isis::Camera *ClipperWacFcCameraPlugin(Isis::Cube &cube) {
return new Isis::ClipperWacFcCamera(cube);
}
| 33.226087 | 100 | 0.696938 | [
"object"
] |
ad15ed2c728070686708942c8f2278b061eec51a | 36,891 | cc | C++ | content/browser/dom_storage/local_storage_context_mojo.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/browser/dom_storage/local_storage_context_mojo.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/browser/dom_storage/local_storage_context_mojo.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/dom_storage/local_storage_context_mojo.h"
#include <inttypes.h>
#include <cctype> // for std::isalnum
#include "base/memory/ptr_util.h"
#include "base/metrics/histogram_functions.h"
#include "base/metrics/histogram_macros.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "base/sys_info.h"
#include "base/trace_event/memory_dump_manager.h"
#include "components/leveldb/public/cpp/util.h"
#include "components/leveldb/public/interfaces/leveldb.mojom.h"
#include "content/browser/dom_storage/dom_storage_area.h"
#include "content/browser/dom_storage/dom_storage_database.h"
#include "content/browser/dom_storage/dom_storage_task_runner.h"
#include "content/browser/dom_storage/local_storage_database.pb.h"
#include "content/browser/leveldb_wrapper_impl.h"
#include "content/common/dom_storage/dom_storage_types.h"
#include "content/public/browser/local_storage_usage_info.h"
#include "services/file/public/interfaces/constants.mojom.h"
#include "services/service_manager/public/cpp/connector.h"
#include "sql/connection.h"
#include "storage/browser/quota/special_storage_policy.h"
#include "third_party/leveldatabase/env_chromium.h"
namespace content {
// LevelDB database schema
// =======================
//
// Version 1 (in sorted order):
// key: "VERSION"
// value: "1"
//
// key: "META:" + <url::Origin 'origin'>
// value: <LocalStorageOriginMetaData serialized as a string>
//
// key: "_" + <url::Origin> 'origin'> + '\x00' + <script controlled key>
// value: <script controlled value>
namespace {
const char kVersionKey[] = "VERSION";
const char kOriginSeparator = '\x00';
const char kDataPrefix[] = "_";
const uint8_t kMetaPrefix[] = {'M', 'E', 'T', 'A', ':'};
const int64_t kMinSchemaVersion = 1;
const int64_t kCurrentSchemaVersion = 1;
// After this many consecutive commit errors we'll throw away the entire
// database.
const int kCommitErrorThreshold = 8;
// Use a smaller block cache on android. Because of the extra caching done in
// LevelDBWrapperImpl the block cache isn't particularly useful, but it still
// provides some benefit with speeding up compaction. And since this is a once
// per profile overhead, the overhead should be fairly minimal on desktop.
#if defined(OS_ANDROID)
const size_t kMaxBlockCacheSize = 100 * 1024;
#else
const size_t kMaxBlockCacheSize = 2 * 1024 * 1024;
#endif
// Limits on the cache size and number of areas in memory, over which the areas
// are purged.
#if defined(OS_ANDROID)
const unsigned kMaxStorageAreaCount = 10;
const size_t kMaxCacheSize = 2 * 1024 * 1024;
#else
const unsigned kMaxStorageAreaCount = 50;
const size_t kMaxCacheSize = 20 * 1024 * 1024;
#endif
std::vector<uint8_t> CreateMetaDataKey(const url::Origin& origin) {
auto serialized_origin = leveldb::StdStringToUint8Vector(origin.Serialize());
std::vector<uint8_t> key;
key.reserve(arraysize(kMetaPrefix) + serialized_origin.size());
key.insert(key.end(), kMetaPrefix, kMetaPrefix + arraysize(kMetaPrefix));
key.insert(key.end(), serialized_origin.begin(), serialized_origin.end());
return key;
}
void NoOpSuccess(bool success) {}
void NoOpDatabaseError(leveldb::mojom::DatabaseError error) {}
void MigrateStorageHelper(
base::FilePath db_path,
const scoped_refptr<base::SingleThreadTaskRunner> reply_task_runner,
base::Callback<void(std::unique_ptr<LevelDBWrapperImpl::ValueMap>)>
callback) {
DOMStorageDatabase db(db_path);
DOMStorageValuesMap map;
db.ReadAllValues(&map);
auto values = base::MakeUnique<LevelDBWrapperImpl::ValueMap>();
for (const auto& it : map) {
(*values)[LocalStorageContextMojo::MigrateString(it.first)] =
LocalStorageContextMojo::MigrateString(it.second.string());
}
reply_task_runner->PostTask(FROM_HERE,
base::Bind(callback, base::Passed(&values)));
}
// Helper to convert from OnceCallback to Callback.
void CallMigrationCalback(LevelDBWrapperImpl::ValueMapCallback callback,
std::unique_ptr<LevelDBWrapperImpl::ValueMap> data) {
std::move(callback).Run(std::move(data));
}
void AddDeleteOriginOperations(
std::vector<leveldb::mojom::BatchedOperationPtr>* operations,
const url::Origin& origin) {
leveldb::mojom::BatchedOperationPtr item =
leveldb::mojom::BatchedOperation::New();
item->type = leveldb::mojom::BatchOperationType::DELETE_PREFIXED_KEY;
item->key = leveldb::StdStringToUint8Vector(kDataPrefix + origin.Serialize() +
kOriginSeparator);
operations->push_back(std::move(item));
item = leveldb::mojom::BatchedOperation::New();
item->type = leveldb::mojom::BatchOperationType::DELETE_KEY;
item->key = CreateMetaDataKey(origin);
operations->push_back(std::move(item));
}
enum class CachePurgeReason {
NotNeeded,
SizeLimitExceeded,
AreaCountLimitExceeded,
InactiveOnLowEndDevice,
AggressivePurgeTriggered
};
void RecordCachePurgedHistogram(CachePurgeReason reason,
size_t purged_size_kib) {
UMA_HISTOGRAM_COUNTS_100000("LocalStorageContext.CachePurgedInKB",
purged_size_kib);
switch (reason) {
case CachePurgeReason::SizeLimitExceeded:
UMA_HISTOGRAM_COUNTS_100000(
"LocalStorageContext.CachePurgedInKB.SizeLimitExceeded",
purged_size_kib);
break;
case CachePurgeReason::AreaCountLimitExceeded:
UMA_HISTOGRAM_COUNTS_100000(
"LocalStorageContext.CachePurgedInKB.AreaCountLimitExceeded",
purged_size_kib);
break;
case CachePurgeReason::InactiveOnLowEndDevice:
UMA_HISTOGRAM_COUNTS_100000(
"LocalStorageContext.CachePurgedInKB.InactiveOnLowEndDevice",
purged_size_kib);
break;
case CachePurgeReason::AggressivePurgeTriggered:
UMA_HISTOGRAM_COUNTS_100000(
"LocalStorageContext.CachePurgedInKB.AggressivePurgeTriggered",
purged_size_kib);
break;
case CachePurgeReason::NotNeeded:
NOTREACHED();
break;
}
}
} // namespace
class LocalStorageContextMojo::LevelDBWrapperHolder
: public LevelDBWrapperImpl::Delegate {
public:
LevelDBWrapperHolder(LocalStorageContextMojo* context,
const url::Origin& origin)
: context_(context), origin_(origin) {
// Delay for a moment after a value is set in anticipation
// of other values being set, so changes are batched.
const int kCommitDefaultDelaySecs = 5;
// To avoid excessive IO we apply limits to the amount of data being written
// and the frequency of writes.
const int kMaxBytesPerHour = kPerStorageAreaQuota;
const int kMaxCommitsPerHour = 60;
level_db_wrapper_ = base::MakeUnique<LevelDBWrapperImpl>(
context_->database_.get(),
kDataPrefix + origin_.Serialize() + kOriginSeparator,
kPerStorageAreaQuota + kPerStorageAreaOverQuotaAllowance,
base::TimeDelta::FromSeconds(kCommitDefaultDelaySecs), kMaxBytesPerHour,
kMaxCommitsPerHour, this);
level_db_wrapper_ptr_ = level_db_wrapper_.get();
}
LevelDBWrapperImpl* level_db_wrapper() { return level_db_wrapper_ptr_; }
void OnNoBindings() override {
has_bindings_ = false;
// Don't delete ourselves, but do schedule an immediate commit. Possible
// deletion will happen under memory pressure or when another localstorage
// area is opened.
level_db_wrapper()->ScheduleImmediateCommit();
}
std::vector<leveldb::mojom::BatchedOperationPtr> PrepareToCommit() override {
std::vector<leveldb::mojom::BatchedOperationPtr> operations;
// Write schema version if not already done so before.
if (!context_->database_initialized_) {
leveldb::mojom::BatchedOperationPtr item =
leveldb::mojom::BatchedOperation::New();
item->type = leveldb::mojom::BatchOperationType::PUT_KEY;
item->key = leveldb::StdStringToUint8Vector(kVersionKey);
item->value = leveldb::StdStringToUint8Vector(
base::Int64ToString(kCurrentSchemaVersion));
operations.push_back(std::move(item));
context_->database_initialized_ = true;
}
leveldb::mojom::BatchedOperationPtr item =
leveldb::mojom::BatchedOperation::New();
item->type = leveldb::mojom::BatchOperationType::PUT_KEY;
item->key = CreateMetaDataKey(origin_);
if (level_db_wrapper()->empty()) {
item->type = leveldb::mojom::BatchOperationType::DELETE_KEY;
} else {
item->type = leveldb::mojom::BatchOperationType::PUT_KEY;
LocalStorageOriginMetaData data;
data.set_last_modified(base::Time::Now().ToInternalValue());
data.set_size_bytes(level_db_wrapper()->bytes_used());
item->value = leveldb::StdStringToUint8Vector(data.SerializeAsString());
}
operations.push_back(std::move(item));
return operations;
}
void DidCommit(leveldb::mojom::DatabaseError error) override {
UMA_HISTOGRAM_ENUMERATION("LocalStorageContext.CommitResult",
leveldb::GetLevelDBStatusUMAValue(error),
leveldb_env::LEVELDB_STATUS_MAX);
// Delete any old database that might still exist if we successfully wrote
// data to LevelDB, and our LevelDB is actually disk backed.
if (error == leveldb::mojom::DatabaseError::OK && !deleted_old_data_ &&
!context_->subdirectory_.empty() && context_->task_runner_ &&
!context_->old_localstorage_path_.empty()) {
deleted_old_data_ = true;
context_->task_runner_->PostShutdownBlockingTask(
FROM_HERE, DOMStorageTaskRunner::PRIMARY_SEQUENCE,
base::Bind(base::IgnoreResult(&sql::Connection::Delete),
sql_db_path()));
}
context_->OnCommitResult(error);
}
void MigrateData(LevelDBWrapperImpl::ValueMapCallback callback) override {
if (context_->task_runner_ && !context_->old_localstorage_path_.empty()) {
context_->task_runner_->PostShutdownBlockingTask(
FROM_HERE, DOMStorageTaskRunner::PRIMARY_SEQUENCE,
base::Bind(
&MigrateStorageHelper, sql_db_path(),
base::ThreadTaskRunnerHandle::Get(),
base::Bind(&CallMigrationCalback, base::Passed(&callback))));
return;
}
std::move(callback).Run(nullptr);
}
void OnMapLoaded(leveldb::mojom::DatabaseError error) override {
if (error != leveldb::mojom::DatabaseError::OK)
UMA_HISTOGRAM_ENUMERATION("LocalStorageContext.MapLoadError",
leveldb::GetLevelDBStatusUMAValue(error),
leveldb_env::LEVELDB_STATUS_MAX);
}
void Bind(mojom::LevelDBWrapperRequest request) {
has_bindings_ = true;
level_db_wrapper()->Bind(std::move(request));
}
bool has_bindings() const { return has_bindings_; }
private:
base::FilePath sql_db_path() const {
if (context_->old_localstorage_path_.empty())
return base::FilePath();
return context_->old_localstorage_path_.Append(
DOMStorageArea::DatabaseFileNameFromOrigin(origin_.GetURL()));
}
LocalStorageContextMojo* context_;
url::Origin origin_;
std::unique_ptr<LevelDBWrapperImpl> level_db_wrapper_;
// Holds the same value as |level_db_wrapper_|. The reason for this is that
// during destruction of the LevelDBWrapperImpl instance we might still get
// called and need access to the LevelDBWrapperImpl instance. The unique_ptr
// could already be null, but this field should still be valid.
LevelDBWrapperImpl* level_db_wrapper_ptr_;
bool deleted_old_data_ = false;
bool has_bindings_ = false;
};
LocalStorageContextMojo::LocalStorageContextMojo(
scoped_refptr<base::SingleThreadTaskRunner> task_runner,
service_manager::Connector* connector,
scoped_refptr<DOMStorageTaskRunner> legacy_task_runner,
const base::FilePath& old_localstorage_path,
const base::FilePath& subdirectory,
scoped_refptr<storage::SpecialStoragePolicy> special_storage_policy)
: connector_(connector ? connector->Clone() : nullptr),
subdirectory_(subdirectory),
special_storage_policy_(std::move(special_storage_policy)),
memory_dump_id_(base::StringPrintf("LocalStorage/0x%" PRIXPTR,
reinterpret_cast<uintptr_t>(this))),
task_runner_(std::move(legacy_task_runner)),
old_localstorage_path_(old_localstorage_path),
is_low_end_device_(base::SysInfo::IsLowEndDevice()),
weak_ptr_factory_(this) {
base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
this, "LocalStorage", task_runner);
}
void LocalStorageContextMojo::OpenLocalStorage(
const url::Origin& origin,
mojom::LevelDBWrapperRequest request) {
RunWhenConnected(base::BindOnce(&LocalStorageContextMojo::BindLocalStorage,
weak_ptr_factory_.GetWeakPtr(), origin,
std::move(request)));
}
void LocalStorageContextMojo::GetStorageUsage(
GetStorageUsageCallback callback) {
RunWhenConnected(
base::BindOnce(&LocalStorageContextMojo::RetrieveStorageUsage,
weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}
void LocalStorageContextMojo::DeleteStorage(const url::Origin& origin) {
if (connection_state_ != CONNECTION_FINISHED) {
RunWhenConnected(base::BindOnce(&LocalStorageContextMojo::DeleteStorage,
weak_ptr_factory_.GetWeakPtr(), origin));
return;
}
auto found = level_db_wrappers_.find(origin);
if (found != level_db_wrappers_.end()) {
// Renderer process expects |source| to always be two newline separated
// strings.
found->second->level_db_wrapper()->DeleteAll("\n",
base::Bind(&NoOpSuccess));
found->second->level_db_wrapper()->ScheduleImmediateCommit();
} else if (database_) {
std::vector<leveldb::mojom::BatchedOperationPtr> operations;
AddDeleteOriginOperations(&operations, origin);
database_->Write(std::move(operations), base::Bind(&NoOpDatabaseError));
}
}
void LocalStorageContextMojo::DeleteStorageForPhysicalOrigin(
const url::Origin& origin) {
GetStorageUsage(base::BindOnce(
&LocalStorageContextMojo::OnGotStorageUsageForDeletePhysicalOrigin,
weak_ptr_factory_.GetWeakPtr(), origin));
}
void LocalStorageContextMojo::Flush() {
if (connection_state_ != CONNECTION_FINISHED) {
RunWhenConnected(base::BindOnce(&LocalStorageContextMojo::Flush,
weak_ptr_factory_.GetWeakPtr()));
return;
}
for (const auto& it : level_db_wrappers_)
it.second->level_db_wrapper()->ScheduleImmediateCommit();
}
void LocalStorageContextMojo::FlushOriginForTesting(const url::Origin& origin) {
if (connection_state_ != CONNECTION_FINISHED)
return;
const auto& it = level_db_wrappers_.find(origin);
if (it == level_db_wrappers_.end())
return;
it->second->level_db_wrapper()->ScheduleImmediateCommit();
}
void LocalStorageContextMojo::ShutdownAndDelete() {
DCHECK_NE(connection_state_, CONNECTION_SHUTDOWN);
// Nothing to do if no connection to the database was ever finished.
if (connection_state_ != CONNECTION_FINISHED) {
connection_state_ = CONNECTION_SHUTDOWN;
OnShutdownComplete(leveldb::mojom::DatabaseError::OK);
return;
}
connection_state_ = CONNECTION_SHUTDOWN;
// Flush any uncommitted data.
for (const auto& it : level_db_wrappers_)
it.second->level_db_wrapper()->ScheduleImmediateCommit();
// Respect the content policy settings about what to
// keep and what to discard.
if (force_keep_session_state_) {
OnShutdownComplete(leveldb::mojom::DatabaseError::OK);
return; // Keep everything.
}
bool has_session_only_origins =
special_storage_policy_.get() &&
special_storage_policy_->HasSessionOnlyOrigins();
if (has_session_only_origins) {
RetrieveStorageUsage(
base::BindOnce(&LocalStorageContextMojo::OnGotStorageUsageForShutdown,
base::Unretained(this)));
} else {
OnShutdownComplete(leveldb::mojom::DatabaseError::OK);
}
}
void LocalStorageContextMojo::PurgeMemory() {
size_t total_cache_size, unused_wrapper_count;
GetStatistics(&total_cache_size, &unused_wrapper_count);
for (auto it = level_db_wrappers_.begin(); it != level_db_wrappers_.end();) {
if (it->second->has_bindings()) {
it->second->level_db_wrapper()->PurgeMemory();
++it;
} else {
it = level_db_wrappers_.erase(it);
}
}
// Track the size of cache purged.
size_t final_total_cache_size;
GetStatistics(&final_total_cache_size, &unused_wrapper_count);
size_t purged_size_kib = (total_cache_size - final_total_cache_size) / 1024;
RecordCachePurgedHistogram(CachePurgeReason::AggressivePurgeTriggered,
purged_size_kib);
}
void LocalStorageContextMojo::PurgeUnusedWrappersIfNeeded() {
size_t total_cache_size, unused_wrapper_count;
GetStatistics(&total_cache_size, &unused_wrapper_count);
// Nothing to purge.
if (!unused_wrapper_count)
return;
CachePurgeReason purge_reason = CachePurgeReason::NotNeeded;
if (total_cache_size > kMaxCacheSize)
purge_reason = CachePurgeReason::SizeLimitExceeded;
else if (level_db_wrappers_.size() > kMaxStorageAreaCount)
purge_reason = CachePurgeReason::AreaCountLimitExceeded;
else if (is_low_end_device_)
purge_reason = CachePurgeReason::InactiveOnLowEndDevice;
if (purge_reason == CachePurgeReason::NotNeeded)
return;
for (auto it = level_db_wrappers_.begin(); it != level_db_wrappers_.end();) {
if (it->second->has_bindings())
++it;
else
it = level_db_wrappers_.erase(it);
}
// Track the size of cache purged.
size_t final_total_cache_size;
GetStatistics(&final_total_cache_size, &unused_wrapper_count);
size_t purged_size_kib = (total_cache_size - final_total_cache_size) / 1024;
RecordCachePurgedHistogram(purge_reason, purged_size_kib);
}
void LocalStorageContextMojo::SetDatabaseForTesting(
leveldb::mojom::LevelDBDatabaseAssociatedPtr database) {
DCHECK_EQ(connection_state_, NO_CONNECTION);
connection_state_ = CONNECTION_IN_PROGRESS;
database_ = std::move(database);
OnDatabaseOpened(true, leveldb::mojom::DatabaseError::OK);
}
bool LocalStorageContextMojo::OnMemoryDump(
const base::trace_event::MemoryDumpArgs& args,
base::trace_event::ProcessMemoryDump* pmd) {
if (connection_state_ != CONNECTION_FINISHED)
return true;
std::string context_name =
base::StringPrintf("dom_storage/localstorage_0x%" PRIXPTR,
reinterpret_cast<uintptr_t>(this));
// Account for leveldb memory usage, which actually lives in the file service.
auto* global_dump = pmd->CreateSharedGlobalAllocatorDump(memory_dump_id_);
// The size of the leveldb dump will be added by the leveldb service.
auto* leveldb_mad = pmd->CreateAllocatorDump(context_name + "/leveldb");
// Specifies that the current context is responsible for keeping memory alive.
int kImportance = 2;
pmd->AddOwnershipEdge(leveldb_mad->guid(), global_dump->guid(), kImportance);
if (args.level_of_detail ==
base::trace_event::MemoryDumpLevelOfDetail::BACKGROUND) {
size_t total_cache_size, unused_wrapper_count;
GetStatistics(&total_cache_size, &unused_wrapper_count);
auto* mad = pmd->CreateAllocatorDump(context_name + "/cache_size");
mad->AddScalar(base::trace_event::MemoryAllocatorDump::kNameSize,
base::trace_event::MemoryAllocatorDump::kUnitsBytes,
total_cache_size);
mad->AddScalar("total_areas",
base::trace_event::MemoryAllocatorDump::kUnitsObjects,
level_db_wrappers_.size());
return true;
}
for (const auto& it : level_db_wrappers_) {
// Limit the url length to 50 and strip special characters.
std::string url = it.first.Serialize().substr(0, 50);
for (size_t index = 0; index < url.size(); ++index) {
if (!std::isalnum(url[index]))
url[index] = '_';
}
std::string wrapper_dump_name = base::StringPrintf(
"%s/%s/0x%" PRIXPTR, context_name.c_str(), url.c_str(),
reinterpret_cast<uintptr_t>(it.second->level_db_wrapper()));
it.second->level_db_wrapper()->OnMemoryDump(wrapper_dump_name, pmd);
}
return true;
}
// static
std::vector<uint8_t> LocalStorageContextMojo::MigrateString(
const base::string16& input) {
static const uint8_t kUTF16Format = 0;
const uint8_t* data = reinterpret_cast<const uint8_t*>(input.data());
std::vector<uint8_t> result;
result.reserve(input.size() * sizeof(base::char16) + 1);
result.push_back(kUTF16Format);
result.insert(result.end(), data, data + input.size() * sizeof(base::char16));
return result;
}
LocalStorageContextMojo::~LocalStorageContextMojo() {
DCHECK_EQ(connection_state_, CONNECTION_SHUTDOWN);
base::trace_event::MemoryDumpManager::GetInstance()->UnregisterDumpProvider(
this);
}
void LocalStorageContextMojo::RunWhenConnected(base::OnceClosure callback) {
DCHECK_NE(connection_state_, CONNECTION_SHUTDOWN);
// If we don't have a filesystem_connection_, we'll need to establish one.
if (connection_state_ == NO_CONNECTION) {
connection_state_ = CONNECTION_IN_PROGRESS;
InitiateConnection();
}
if (connection_state_ == CONNECTION_IN_PROGRESS) {
// Queue this OpenLocalStorage call for when we have a level db pointer.
on_database_opened_callbacks_.push_back(std::move(callback));
return;
}
std::move(callback).Run();
}
void LocalStorageContextMojo::InitiateConnection(bool in_memory_only) {
DCHECK_EQ(connection_state_, CONNECTION_IN_PROGRESS);
// Unit tests might not always have a Connector, use in-memory only if that
// happens.
if (!connector_) {
OnDatabaseOpened(false, leveldb::mojom::DatabaseError::OK);
return;
}
if (!subdirectory_.empty() && !in_memory_only) {
// We were given a subdirectory to write to. Get it and use a disk backed
// database.
connector_->BindInterface(file::mojom::kServiceName, &file_system_);
file_system_->GetSubDirectory(
subdirectory_.AsUTF8Unsafe(), MakeRequest(&directory_),
base::Bind(&LocalStorageContextMojo::OnDirectoryOpened,
weak_ptr_factory_.GetWeakPtr()));
} else {
// We were not given a subdirectory. Use a memory backed database.
connector_->BindInterface(file::mojom::kServiceName, &leveldb_service_);
leveldb_service_->OpenInMemory(
memory_dump_id_, MakeRequest(&database_),
base::Bind(&LocalStorageContextMojo::OnDatabaseOpened,
weak_ptr_factory_.GetWeakPtr(), true));
}
}
void LocalStorageContextMojo::OnDirectoryOpened(
filesystem::mojom::FileError err) {
if (err != filesystem::mojom::FileError::OK) {
// We failed to open the directory; continue with startup so that we create
// the |level_db_wrappers_|.
UMA_HISTOGRAM_ENUMERATION("LocalStorageContext.DirectoryOpenError",
-static_cast<base::File::Error>(err),
-base::File::FILE_ERROR_MAX);
LogDatabaseOpenResult(OpenResult::DIRECTORY_OPEN_FAILED);
OnDatabaseOpened(false, leveldb::mojom::DatabaseError::OK);
return;
}
// Now that we have a directory, connect to the LevelDB service and get our
// database.
connector_->BindInterface(file::mojom::kServiceName, &leveldb_service_);
// We might still need to use the directory, so create a clone.
filesystem::mojom::DirectoryPtr directory_clone;
directory_->Clone(MakeRequest(&directory_clone));
auto options = leveldb::mojom::OpenOptions::New();
options->create_if_missing = true;
options->max_open_files = 0; // use minimum
// Default write_buffer_size is 4 MB but that might leave a 3.999
// memory allocation in RAM from a log file recovery.
options->write_buffer_size = 64 * 1024;
// Default block_cache_size is 8 MB, but we don't really want to cache that
// much data, so instead set it to a lower value. LevelDBWrapperImpl takes
// care of almost all the actual block caching we care about.
options->block_cache_size = kMaxBlockCacheSize;
leveldb_service_->OpenWithOptions(
std::move(options), std::move(directory_clone), "leveldb",
memory_dump_id_, MakeRequest(&database_),
base::Bind(&LocalStorageContextMojo::OnDatabaseOpened,
weak_ptr_factory_.GetWeakPtr(), false));
}
void LocalStorageContextMojo::OnDatabaseOpened(
bool in_memory,
leveldb::mojom::DatabaseError status) {
if (status != leveldb::mojom::DatabaseError::OK) {
UMA_HISTOGRAM_ENUMERATION("LocalStorageContext.DatabaseOpenError",
leveldb::GetLevelDBStatusUMAValue(status),
leveldb_env::LEVELDB_STATUS_MAX);
if (in_memory) {
UMA_HISTOGRAM_ENUMERATION("LocalStorageContext.DatabaseOpenError.Memory",
leveldb::GetLevelDBStatusUMAValue(status),
leveldb_env::LEVELDB_STATUS_MAX);
} else {
UMA_HISTOGRAM_ENUMERATION("LocalStorageContext.DatabaseOpenError.Disk",
leveldb::GetLevelDBStatusUMAValue(status),
leveldb_env::LEVELDB_STATUS_MAX);
}
LogDatabaseOpenResult(OpenResult::DATABASE_OPEN_FAILED);
// If we failed to open the database, try to delete and recreate the
// database, or ultimately fallback to an in-memory database.
DeleteAndRecreateDatabase("LocalStorageContext.OpenResultAfterOpenFailed");
return;
}
// Verify DB schema version.
if (database_) {
database_->Get(leveldb::StdStringToUint8Vector(kVersionKey),
base::Bind(&LocalStorageContextMojo::OnGotDatabaseVersion,
weak_ptr_factory_.GetWeakPtr()));
return;
}
OnConnectionFinished();
}
void LocalStorageContextMojo::OnGotDatabaseVersion(
leveldb::mojom::DatabaseError status,
const std::vector<uint8_t>& value) {
if (status == leveldb::mojom::DatabaseError::NOT_FOUND) {
// New database, nothing more to do. Current version will get written
// when first data is committed.
} else if (status == leveldb::mojom::DatabaseError::OK) {
// Existing database, check if version number matches current schema
// version.
int64_t db_version;
if (!base::StringToInt64(leveldb::Uint8VectorToStdString(value),
&db_version) ||
db_version < kMinSchemaVersion || db_version > kCurrentSchemaVersion) {
LogDatabaseOpenResult(OpenResult::INVALID_VERSION);
DeleteAndRecreateDatabase(
"LocalStorageContext.OpenResultAfterInvalidVersion");
return;
}
database_initialized_ = true;
} else {
// Other read error. Possibly database corruption.
UMA_HISTOGRAM_ENUMERATION("LocalStorageContext.ReadVersionError",
leveldb::GetLevelDBStatusUMAValue(status),
leveldb_env::LEVELDB_STATUS_MAX);
LogDatabaseOpenResult(OpenResult::VERSION_READ_ERROR);
DeleteAndRecreateDatabase(
"LocalStorageContext.OpenResultAfterReadVersionError");
return;
}
OnConnectionFinished();
}
void LocalStorageContextMojo::OnConnectionFinished() {
DCHECK_EQ(connection_state_, CONNECTION_IN_PROGRESS);
if (!database_) {
directory_.reset();
file_system_.reset();
leveldb_service_.reset();
}
// If connection was opened successfully, reset tried_to_recreate_during_open_
// to enable recreating the database on future errors.
if (database_)
tried_to_recreate_during_open_ = false;
open_result_histogram_ = nullptr;
// |database_| should be known to either be valid or invalid by now. Run our
// delayed bindings.
connection_state_ = CONNECTION_FINISHED;
for (size_t i = 0; i < on_database_opened_callbacks_.size(); ++i)
std::move(on_database_opened_callbacks_[i]).Run();
on_database_opened_callbacks_.clear();
}
void LocalStorageContextMojo::DeleteAndRecreateDatabase(
const char* histogram_name) {
// We're about to set database_ to null, so delete and LevelDBWrappers
// that might still be using the old database.
level_db_wrappers_.clear();
// Reset state to be in process of connecting. This will cause requests for
// LevelDBWrappers to be queued until the connection is complete.
connection_state_ = CONNECTION_IN_PROGRESS;
commit_error_count_ = 0;
database_ = nullptr;
open_result_histogram_ = histogram_name;
bool recreate_in_memory = false;
// If tried to recreate database on disk already, try again but this time
// in memory.
if (tried_to_recreate_during_open_ && !subdirectory_.empty()) {
recreate_in_memory = true;
} else if (tried_to_recreate_during_open_) {
// Give up completely, run without any database.
OnConnectionFinished();
return;
}
tried_to_recreate_during_open_ = true;
// Unit tests might not have a bound file_service_, in which case there is
// nothing to retry.
if (!file_system_.is_bound()) {
OnConnectionFinished();
return;
}
// Destroy database, and try again.
if (directory_.is_bound()) {
leveldb_service_->Destroy(
std::move(directory_), "leveldb",
base::Bind(&LocalStorageContextMojo::OnDBDestroyed,
weak_ptr_factory_.GetWeakPtr(), recreate_in_memory));
} else {
// No directory, so nothing to destroy. Retrying to recreate will probably
// fail, but try anyway.
InitiateConnection(recreate_in_memory);
}
}
void LocalStorageContextMojo::OnDBDestroyed(
bool recreate_in_memory,
leveldb::mojom::DatabaseError status) {
UMA_HISTOGRAM_ENUMERATION("LocalStorageContext.DestroyDBResult",
leveldb::GetLevelDBStatusUMAValue(status),
leveldb_env::LEVELDB_STATUS_MAX);
// We're essentially ignoring the status here. Even if destroying failed we
// still want to go ahead and try to recreate.
InitiateConnection(recreate_in_memory);
}
// The (possibly delayed) implementation of OpenLocalStorage(). Can be called
// directly from that function, or through |on_database_open_callbacks_|.
void LocalStorageContextMojo::BindLocalStorage(
const url::Origin& origin,
mojom::LevelDBWrapperRequest request) {
GetOrCreateDBWrapper(origin)->Bind(std::move(request));
}
LocalStorageContextMojo::LevelDBWrapperHolder*
LocalStorageContextMojo::GetOrCreateDBWrapper(const url::Origin& origin) {
DCHECK_EQ(connection_state_, CONNECTION_FINISHED);
auto found = level_db_wrappers_.find(origin);
if (found != level_db_wrappers_.end()) {
return found->second.get();
}
size_t total_cache_size, unused_wrapper_count;
GetStatistics(&total_cache_size, &unused_wrapper_count);
// Track the total localStorage cache size.
UMA_HISTOGRAM_COUNTS_100000("LocalStorageContext.CacheSizeInKB",
total_cache_size / 1024);
PurgeUnusedWrappersIfNeeded();
auto holder = base::MakeUnique<LevelDBWrapperHolder>(this, origin);
LevelDBWrapperHolder* holder_ptr = holder.get();
level_db_wrappers_[origin] = std::move(holder);
return holder_ptr;
}
void LocalStorageContextMojo::RetrieveStorageUsage(
GetStorageUsageCallback callback) {
if (!database_) {
// If for whatever reason no leveldb database is available, no storage is
// used, so return an array only containing the current leveldb wrappers.
std::vector<LocalStorageUsageInfo> result;
base::Time now = base::Time::Now();
for (const auto& it : level_db_wrappers_) {
LocalStorageUsageInfo info;
info.origin = it.first.GetURL();
info.last_modified = now;
result.push_back(std::move(info));
}
std::move(callback).Run(std::move(result));
return;
}
database_->GetPrefixed(
std::vector<uint8_t>(kMetaPrefix, kMetaPrefix + arraysize(kMetaPrefix)),
base::Bind(&LocalStorageContextMojo::OnGotMetaData,
weak_ptr_factory_.GetWeakPtr(), base::Passed(&callback)));
}
void LocalStorageContextMojo::OnGotMetaData(
GetStorageUsageCallback callback,
leveldb::mojom::DatabaseError status,
std::vector<leveldb::mojom::KeyValuePtr> data) {
std::vector<LocalStorageUsageInfo> result;
std::set<url::Origin> origins;
for (const auto& row : data) {
DCHECK_GT(row->key.size(), arraysize(kMetaPrefix));
LocalStorageUsageInfo info;
info.origin = GURL(leveldb::Uint8VectorToStdString(row->key).substr(
arraysize(kMetaPrefix)));
origins.insert(url::Origin(info.origin));
if (!info.origin.is_valid()) {
// TODO(mek): Deal with database corruption.
continue;
}
LocalStorageOriginMetaData data;
if (!data.ParseFromArray(row->value.data(), row->value.size())) {
// TODO(mek): Deal with database corruption.
continue;
}
info.data_size = data.size_bytes();
info.last_modified = base::Time::FromInternalValue(data.last_modified());
result.push_back(std::move(info));
}
// Add any origins for which LevelDBWrappers exist, but which haven't
// committed any data to disk yet.
base::Time now = base::Time::Now();
for (const auto& it : level_db_wrappers_) {
if (origins.find(it.first) != origins.end())
continue;
LocalStorageUsageInfo info;
info.origin = it.first.GetURL();
info.last_modified = now;
result.push_back(std::move(info));
}
std::move(callback).Run(std::move(result));
}
void LocalStorageContextMojo::OnGotStorageUsageForDeletePhysicalOrigin(
const url::Origin& origin,
std::vector<LocalStorageUsageInfo> usage) {
for (const auto& info : usage) {
url::Origin origin_candidate(info.origin);
if (!origin_candidate.IsSameOriginWith(origin) &&
origin_candidate.IsSamePhysicalOriginWith(origin))
DeleteStorage(origin_candidate);
}
DeleteStorage(origin);
}
void LocalStorageContextMojo::OnGotStorageUsageForShutdown(
std::vector<LocalStorageUsageInfo> usage) {
std::vector<leveldb::mojom::BatchedOperationPtr> operations;
for (const auto& info : usage) {
if (special_storage_policy_->IsStorageProtected(info.origin))
continue;
if (!special_storage_policy_->IsStorageSessionOnly(info.origin))
continue;
AddDeleteOriginOperations(&operations, url::Origin(info.origin));
}
if (!operations.empty()) {
database_->Write(std::move(operations),
base::Bind(&LocalStorageContextMojo::OnShutdownComplete,
base::Unretained(this)));
} else {
OnShutdownComplete(leveldb::mojom::DatabaseError::OK);
}
}
void LocalStorageContextMojo::OnShutdownComplete(
leveldb::mojom::DatabaseError error) {
delete this;
}
void LocalStorageContextMojo::GetStatistics(size_t* total_cache_size,
size_t* unused_wrapper_count) {
*total_cache_size = 0;
*unused_wrapper_count = 0;
for (const auto& it : level_db_wrappers_) {
*total_cache_size += it.second->level_db_wrapper()->bytes_used();
if (!it.second->has_bindings())
(*unused_wrapper_count)++;
}
}
void LocalStorageContextMojo::OnCommitResult(
leveldb::mojom::DatabaseError error) {
DCHECK_EQ(connection_state_, CONNECTION_FINISHED);
if (error == leveldb::mojom::DatabaseError::OK) {
commit_error_count_ = 0;
return;
}
commit_error_count_++;
if (commit_error_count_ > kCommitErrorThreshold) {
if (tried_to_recover_from_commit_errors_) {
// We already tried to recover from a high commit error rate before, but
// are still having problems: there isn't really anything left to try, so
// just ignore errors.
return;
}
tried_to_recover_from_commit_errors_ = true;
// Deleting LevelDBWrappers in here could cause more commits (and commit
// errors), but those commits won't reach OnCommitResult because the wrapper
// will have been deleted before the commit finishes.
DeleteAndRecreateDatabase(
"LocalStorageContext.OpenResultAfterCommitErrors");
}
}
void LocalStorageContextMojo::LogDatabaseOpenResult(OpenResult result) {
if (result != OpenResult::SUCCESS) {
UMA_HISTOGRAM_ENUMERATION("LocalStorageContext.OpenError", result,
OpenResult::MAX);
}
if (open_result_histogram_) {
base::UmaHistogramEnumeration(open_result_histogram_, result,
OpenResult::MAX);
}
}
} // namespace content
| 38.229016 | 80 | 0.712016 | [
"vector"
] |
ad16b144d5216cf6923684a891e993a1f47e648a | 763 | cpp | C++ | mcrouter/routes/McRouteHandleProvider-FailoverRoute.cpp | kiaplayer/mcrouter | c54233f1cd57dc9f541bdbff7ff485775ff289fc | [
"MIT"
] | 2,205 | 2015-01-03T02:56:53.000Z | 2022-03-31T09:24:08.000Z | mcrouter/routes/McRouteHandleProvider-FailoverRoute.cpp | kiaplayer/mcrouter | c54233f1cd57dc9f541bdbff7ff485775ff289fc | [
"MIT"
] | 327 | 2015-01-07T00:59:57.000Z | 2022-03-31T16:03:58.000Z | mcrouter/routes/McRouteHandleProvider-FailoverRoute.cpp | kiaplayer/mcrouter | c54233f1cd57dc9f541bdbff7ff485775ff289fc | [
"MIT"
] | 479 | 2015-01-07T02:06:42.000Z | 2022-03-24T11:44:31.000Z | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "mcrouter/routes/McRouteHandleProvider.h"
#include <mcrouter/routes/FailoverRoute.h>
namespace facebook {
namespace memcache {
namespace mcrouter {
template MemcacheRouterInfo::RouteHandlePtr
makeFailoverRouteWithFailoverErrorSettings<
MemcacheRouterInfo,
FailoverRoute,
FailoverErrorsSettings>(
const folly::dynamic& json,
std::vector<MemcacheRouterInfo::RouteHandlePtr> children,
FailoverErrorsSettings failoverErrors,
const folly::dynamic* jFailoverPolicy);
} // namespace mcrouter
} // namespace memcache
} // namespace facebook
| 26.310345 | 66 | 0.769332 | [
"vector"
] |
ad1df801c3d6c628214f03cf596caa2bc9d6d872 | 21,755 | cpp | C++ | wrap/tests/expected/geometry_wrapper.cpp | sdmiller/gtsam_pcl | 1e607bd75090d35e325a8fb37a6c5afe630f1207 | [
"BSD-3-Clause"
] | 11 | 2015-02-04T16:41:47.000Z | 2021-12-10T07:02:44.000Z | wrap/tests/expected/geometry_wrapper.cpp | sdmiller/gtsam_pcl | 1e607bd75090d35e325a8fb37a6c5afe630f1207 | [
"BSD-3-Clause"
] | null | null | null | wrap/tests/expected/geometry_wrapper.cpp | sdmiller/gtsam_pcl | 1e607bd75090d35e325a8fb37a6c5afe630f1207 | [
"BSD-3-Clause"
] | 6 | 2015-09-10T12:06:08.000Z | 2021-12-10T07:02:48.000Z | #include <wrap/matlab.h>
#include <map>
#include <boost/foreach.hpp>
#include <folder/path/to/Test.h>
typedef std::set<boost::shared_ptr<Point2>*> Collector_Point2;
static Collector_Point2 collector_Point2;
typedef std::set<boost::shared_ptr<Point3>*> Collector_Point3;
static Collector_Point3 collector_Point3;
typedef std::set<boost::shared_ptr<Test>*> Collector_Test;
static Collector_Test collector_Test;
void _deleteAllObjects()
{
mstream mout;
std::streambuf *outbuf = std::cout.rdbuf(&mout);
bool anyDeleted = false;
{ for(Collector_Point2::iterator iter = collector_Point2.begin();
iter != collector_Point2.end(); ) {
delete *iter;
collector_Point2.erase(iter++);
anyDeleted = true;
} }
{ for(Collector_Point3::iterator iter = collector_Point3.begin();
iter != collector_Point3.end(); ) {
delete *iter;
collector_Point3.erase(iter++);
anyDeleted = true;
} }
{ for(Collector_Test::iterator iter = collector_Test.begin();
iter != collector_Test.end(); ) {
delete *iter;
collector_Test.erase(iter++);
anyDeleted = true;
} }
if(anyDeleted)
cout <<
"WARNING: Wrap modules with variables in the workspace have been reloaded due to\n"
"calling destructors, call 'clear all' again if you plan to now recompile a wrap\n"
"module, so that your recompiled module is used instead of the old one." << endl;
std::cout.rdbuf(outbuf);
}
void _geometry_RTTIRegister() {
const mxArray *alreadyCreated = mexGetVariablePtr("global", "gtsam_geometry_rttiRegistry_created");
if(!alreadyCreated) {
std::map<std::string, std::string> types;
mxArray *registry = mexGetVariable("global", "gtsamwrap_rttiRegistry");
if(!registry)
registry = mxCreateStructMatrix(1, 1, 0, NULL);
typedef std::pair<std::string, std::string> StringPair;
BOOST_FOREACH(const StringPair& rtti_matlab, types) {
int fieldId = mxAddField(registry, rtti_matlab.first.c_str());
if(fieldId < 0)
mexErrMsgTxt("gtsam wrap: Error indexing RTTI types, inheritance will not work correctly");
mxArray *matlabName = mxCreateString(rtti_matlab.second.c_str());
mxSetFieldByNumber(registry, 0, fieldId, matlabName);
}
if(mexPutVariable("global", "gtsamwrap_rttiRegistry", registry) != 0)
mexErrMsgTxt("gtsam wrap: Error indexing RTTI types, inheritance will not work correctly");
mxDestroyArray(registry);
mxArray *newAlreadyCreated = mxCreateNumericMatrix(0, 0, mxINT8_CLASS, mxREAL);
if(mexPutVariable("global", "gtsam_geometry_rttiRegistry_created", newAlreadyCreated) != 0)
mexErrMsgTxt("gtsam wrap: Error indexing RTTI types, inheritance will not work correctly");
mxDestroyArray(newAlreadyCreated);
}
}
void Point2_collectorInsertAndMakeBase_0(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
mexAtExit(&_deleteAllObjects);
typedef boost::shared_ptr<Point2> Shared;
Shared *self = *reinterpret_cast<Shared**> (mxGetData(in[0]));
collector_Point2.insert(self);
}
void Point2_constructor_1(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
mexAtExit(&_deleteAllObjects);
typedef boost::shared_ptr<Point2> Shared;
Shared *self = new Shared(new Point2());
collector_Point2.insert(self);
out[0] = mxCreateNumericMatrix(1, 1, mxUINT32OR64_CLASS, mxREAL);
*reinterpret_cast<Shared**> (mxGetData(out[0])) = self;
}
void Point2_constructor_2(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
mexAtExit(&_deleteAllObjects);
typedef boost::shared_ptr<Point2> Shared;
double x = unwrap< double >(in[0]);
double y = unwrap< double >(in[1]);
Shared *self = new Shared(new Point2(x,y));
collector_Point2.insert(self);
out[0] = mxCreateNumericMatrix(1, 1, mxUINT32OR64_CLASS, mxREAL);
*reinterpret_cast<Shared**> (mxGetData(out[0])) = self;
}
void Point2_deconstructor_3(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<Point2> Shared;
checkArguments("delete_Point2",nargout,nargin,1);
Shared *self = *reinterpret_cast<Shared**>(mxGetData(in[0]));
Collector_Point2::iterator item;
item = collector_Point2.find(self);
if(item != collector_Point2.end()) {
delete self;
collector_Point2.erase(item);
}
}
void Point2_argChar_4(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<Point2> Shared;
checkArguments("argChar",nargout,nargin-1,1);
Shared obj = unwrap_shared_ptr<Point2>(in[0], "ptr_Point2");
char a = unwrap< char >(in[1]);
obj->argChar(a);
}
void Point2_argUChar_5(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<Point2> Shared;
checkArguments("argUChar",nargout,nargin-1,1);
Shared obj = unwrap_shared_ptr<Point2>(in[0], "ptr_Point2");
unsigned char a = unwrap< unsigned char >(in[1]);
obj->argUChar(a);
}
void Point2_dim_6(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<Point2> Shared;
checkArguments("dim",nargout,nargin-1,0);
Shared obj = unwrap_shared_ptr<Point2>(in[0], "ptr_Point2");
out[0] = wrap< int >(obj->dim());
}
void Point2_returnChar_7(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<Point2> Shared;
checkArguments("returnChar",nargout,nargin-1,0);
Shared obj = unwrap_shared_ptr<Point2>(in[0], "ptr_Point2");
out[0] = wrap< char >(obj->returnChar());
}
void Point2_vectorConfusion_8(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<VectorNotEigen> SharedVectorNotEigen;
typedef boost::shared_ptr<Point2> Shared;
checkArguments("vectorConfusion",nargout,nargin-1,0);
Shared obj = unwrap_shared_ptr<Point2>(in[0], "ptr_Point2");
out[0] = wrap_shared_ptr(SharedVectorNotEigen(new VectorNotEigen(obj->vectorConfusion())),"VectorNotEigen", false);
}
void Point2_x_9(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<Point2> Shared;
checkArguments("x",nargout,nargin-1,0);
Shared obj = unwrap_shared_ptr<Point2>(in[0], "ptr_Point2");
out[0] = wrap< double >(obj->x());
}
void Point2_y_10(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<Point2> Shared;
checkArguments("y",nargout,nargin-1,0);
Shared obj = unwrap_shared_ptr<Point2>(in[0], "ptr_Point2");
out[0] = wrap< double >(obj->y());
}
void Point3_collectorInsertAndMakeBase_11(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
mexAtExit(&_deleteAllObjects);
typedef boost::shared_ptr<Point3> Shared;
Shared *self = *reinterpret_cast<Shared**> (mxGetData(in[0]));
collector_Point3.insert(self);
}
void Point3_constructor_12(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
mexAtExit(&_deleteAllObjects);
typedef boost::shared_ptr<Point3> Shared;
double x = unwrap< double >(in[0]);
double y = unwrap< double >(in[1]);
double z = unwrap< double >(in[2]);
Shared *self = new Shared(new Point3(x,y,z));
collector_Point3.insert(self);
out[0] = mxCreateNumericMatrix(1, 1, mxUINT32OR64_CLASS, mxREAL);
*reinterpret_cast<Shared**> (mxGetData(out[0])) = self;
}
void Point3_deconstructor_13(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<Point3> Shared;
checkArguments("delete_Point3",nargout,nargin,1);
Shared *self = *reinterpret_cast<Shared**>(mxGetData(in[0]));
Collector_Point3::iterator item;
item = collector_Point3.find(self);
if(item != collector_Point3.end()) {
delete self;
collector_Point3.erase(item);
}
}
void Point3_norm_14(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<Point3> Shared;
checkArguments("norm",nargout,nargin-1,0);
Shared obj = unwrap_shared_ptr<Point3>(in[0], "ptr_Point3");
out[0] = wrap< double >(obj->norm());
}
void Point3_StaticFunctionRet_15(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<Point3> SharedPoint3;
typedef boost::shared_ptr<Point3> Shared;
checkArguments("Point3.StaticFunctionRet",nargout,nargin,1);
double z = unwrap< double >(in[0]);
out[0] = wrap_shared_ptr(SharedPoint3(new Point3(Point3::StaticFunctionRet(z))),"Point3", false);
}
void Point3_staticFunction_16(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<Point3> Shared;
checkArguments("Point3.staticFunction",nargout,nargin,0);
out[0] = wrap< double >(Point3::staticFunction());
}
void Test_collectorInsertAndMakeBase_17(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
mexAtExit(&_deleteAllObjects);
typedef boost::shared_ptr<Test> Shared;
Shared *self = *reinterpret_cast<Shared**> (mxGetData(in[0]));
collector_Test.insert(self);
}
void Test_constructor_18(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
mexAtExit(&_deleteAllObjects);
typedef boost::shared_ptr<Test> Shared;
Shared *self = new Shared(new Test());
collector_Test.insert(self);
out[0] = mxCreateNumericMatrix(1, 1, mxUINT32OR64_CLASS, mxREAL);
*reinterpret_cast<Shared**> (mxGetData(out[0])) = self;
}
void Test_constructor_19(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
mexAtExit(&_deleteAllObjects);
typedef boost::shared_ptr<Test> Shared;
double a = unwrap< double >(in[0]);
Matrix b = unwrap< Matrix >(in[1]);
Shared *self = new Shared(new Test(a,b));
collector_Test.insert(self);
out[0] = mxCreateNumericMatrix(1, 1, mxUINT32OR64_CLASS, mxREAL);
*reinterpret_cast<Shared**> (mxGetData(out[0])) = self;
}
void Test_deconstructor_20(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<Test> Shared;
checkArguments("delete_Test",nargout,nargin,1);
Shared *self = *reinterpret_cast<Shared**>(mxGetData(in[0]));
Collector_Test::iterator item;
item = collector_Test.find(self);
if(item != collector_Test.end()) {
delete self;
collector_Test.erase(item);
}
}
void Test_arg_EigenConstRef_21(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<Test> Shared;
checkArguments("arg_EigenConstRef",nargout,nargin-1,1);
Shared obj = unwrap_shared_ptr<Test>(in[0], "ptr_Test");
Matrix& value = *unwrap_shared_ptr< Matrix >(in[1], "ptr_Matrix");
obj->arg_EigenConstRef(value);
}
void Test_create_MixedPtrs_22(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<Test> SharedTest;
typedef boost::shared_ptr<Test> SharedTest;
typedef boost::shared_ptr<Test> Shared;
checkArguments("create_MixedPtrs",nargout,nargin-1,0);
Shared obj = unwrap_shared_ptr<Test>(in[0], "ptr_Test");
pair< Test, SharedTest > pairResult = obj->create_MixedPtrs();
out[0] = wrap_shared_ptr(SharedTest(new Test(pairResult.first)),"Test", false);
out[1] = wrap_shared_ptr(pairResult.second,"Test", false);
}
void Test_create_ptrs_23(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<Test> SharedTest;
typedef boost::shared_ptr<Test> SharedTest;
typedef boost::shared_ptr<Test> Shared;
checkArguments("create_ptrs",nargout,nargin-1,0);
Shared obj = unwrap_shared_ptr<Test>(in[0], "ptr_Test");
pair< SharedTest, SharedTest > pairResult = obj->create_ptrs();
out[0] = wrap_shared_ptr(pairResult.first,"Test", false);
out[1] = wrap_shared_ptr(pairResult.second,"Test", false);
}
void Test_print_24(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<Test> Shared;
checkArguments("print",nargout,nargin-1,0);
Shared obj = unwrap_shared_ptr<Test>(in[0], "ptr_Test");
obj->print();
}
void Test_return_Point2Ptr_25(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<Point2> SharedPoint2;
typedef boost::shared_ptr<Test> Shared;
checkArguments("return_Point2Ptr",nargout,nargin-1,1);
Shared obj = unwrap_shared_ptr<Test>(in[0], "ptr_Test");
bool value = unwrap< bool >(in[1]);
out[0] = wrap_shared_ptr(obj->return_Point2Ptr(value),"Point2", false);
}
void Test_return_Test_26(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<Test> SharedTest;
typedef boost::shared_ptr<Test> Shared;
checkArguments("return_Test",nargout,nargin-1,1);
Shared obj = unwrap_shared_ptr<Test>(in[0], "ptr_Test");
boost::shared_ptr<Test> value = unwrap_shared_ptr< Test >(in[1], "ptr_Test");
out[0] = wrap_shared_ptr(SharedTest(new Test(obj->return_Test(value))),"Test", false);
}
void Test_return_TestPtr_27(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<Test> SharedTest;
typedef boost::shared_ptr<Test> Shared;
checkArguments("return_TestPtr",nargout,nargin-1,1);
Shared obj = unwrap_shared_ptr<Test>(in[0], "ptr_Test");
boost::shared_ptr<Test> value = unwrap_shared_ptr< Test >(in[1], "ptr_Test");
out[0] = wrap_shared_ptr(obj->return_TestPtr(value),"Test", false);
}
void Test_return_bool_28(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<Test> Shared;
checkArguments("return_bool",nargout,nargin-1,1);
Shared obj = unwrap_shared_ptr<Test>(in[0], "ptr_Test");
bool value = unwrap< bool >(in[1]);
out[0] = wrap< bool >(obj->return_bool(value));
}
void Test_return_double_29(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<Test> Shared;
checkArguments("return_double",nargout,nargin-1,1);
Shared obj = unwrap_shared_ptr<Test>(in[0], "ptr_Test");
double value = unwrap< double >(in[1]);
out[0] = wrap< double >(obj->return_double(value));
}
void Test_return_field_30(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<Test> Shared;
checkArguments("return_field",nargout,nargin-1,1);
Shared obj = unwrap_shared_ptr<Test>(in[0], "ptr_Test");
Test& t = *unwrap_shared_ptr< Test >(in[1], "ptr_Test");
out[0] = wrap< bool >(obj->return_field(t));
}
void Test_return_int_31(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<Test> Shared;
checkArguments("return_int",nargout,nargin-1,1);
Shared obj = unwrap_shared_ptr<Test>(in[0], "ptr_Test");
int value = unwrap< int >(in[1]);
out[0] = wrap< int >(obj->return_int(value));
}
void Test_return_matrix1_32(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<Test> Shared;
checkArguments("return_matrix1",nargout,nargin-1,1);
Shared obj = unwrap_shared_ptr<Test>(in[0], "ptr_Test");
Matrix value = unwrap< Matrix >(in[1]);
out[0] = wrap< Matrix >(obj->return_matrix1(value));
}
void Test_return_matrix2_33(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<Test> Shared;
checkArguments("return_matrix2",nargout,nargin-1,1);
Shared obj = unwrap_shared_ptr<Test>(in[0], "ptr_Test");
Matrix value = unwrap< Matrix >(in[1]);
out[0] = wrap< Matrix >(obj->return_matrix2(value));
}
void Test_return_pair_34(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<Test> Shared;
checkArguments("return_pair",nargout,nargin-1,2);
Shared obj = unwrap_shared_ptr<Test>(in[0], "ptr_Test");
Vector v = unwrap< Vector >(in[1]);
Matrix A = unwrap< Matrix >(in[2]);
pair< Vector, Matrix > pairResult = obj->return_pair(v,A);
out[0] = wrap< Vector >(pairResult.first);
out[1] = wrap< Matrix >(pairResult.second);
}
void Test_return_ptrs_35(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<Test> SharedTest;
typedef boost::shared_ptr<Test> SharedTest;
typedef boost::shared_ptr<Test> Shared;
checkArguments("return_ptrs",nargout,nargin-1,2);
Shared obj = unwrap_shared_ptr<Test>(in[0], "ptr_Test");
boost::shared_ptr<Test> p1 = unwrap_shared_ptr< Test >(in[1], "ptr_Test");
boost::shared_ptr<Test> p2 = unwrap_shared_ptr< Test >(in[2], "ptr_Test");
pair< SharedTest, SharedTest > pairResult = obj->return_ptrs(p1,p2);
out[0] = wrap_shared_ptr(pairResult.first,"Test", false);
out[1] = wrap_shared_ptr(pairResult.second,"Test", false);
}
void Test_return_size_t_36(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<Test> Shared;
checkArguments("return_size_t",nargout,nargin-1,1);
Shared obj = unwrap_shared_ptr<Test>(in[0], "ptr_Test");
size_t value = unwrap< size_t >(in[1]);
out[0] = wrap< size_t >(obj->return_size_t(value));
}
void Test_return_string_37(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<Test> Shared;
checkArguments("return_string",nargout,nargin-1,1);
Shared obj = unwrap_shared_ptr<Test>(in[0], "ptr_Test");
string value = unwrap< string >(in[1]);
out[0] = wrap< string >(obj->return_string(value));
}
void Test_return_vector1_38(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<Test> Shared;
checkArguments("return_vector1",nargout,nargin-1,1);
Shared obj = unwrap_shared_ptr<Test>(in[0], "ptr_Test");
Vector value = unwrap< Vector >(in[1]);
out[0] = wrap< Vector >(obj->return_vector1(value));
}
void Test_return_vector2_39(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
typedef boost::shared_ptr<Test> Shared;
checkArguments("return_vector2",nargout,nargin-1,1);
Shared obj = unwrap_shared_ptr<Test>(in[0], "ptr_Test");
Vector value = unwrap< Vector >(in[1]);
out[0] = wrap< Vector >(obj->return_vector2(value));
}
void aGlobalFunction_40(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
checkArguments("aGlobalFunction",nargout,nargin,0);
out[0] = wrap< Vector >(aGlobalFunction());
}
void mexFunction(int nargout, mxArray *out[], int nargin, const mxArray *in[])
{
mstream mout;
std::streambuf *outbuf = std::cout.rdbuf(&mout);
_geometry_RTTIRegister();
int id = unwrap<int>(in[0]);
try {
switch(id) {
case 0:
Point2_collectorInsertAndMakeBase_0(nargout, out, nargin-1, in+1);
break;
case 1:
Point2_constructor_1(nargout, out, nargin-1, in+1);
break;
case 2:
Point2_constructor_2(nargout, out, nargin-1, in+1);
break;
case 3:
Point2_deconstructor_3(nargout, out, nargin-1, in+1);
break;
case 4:
Point2_argChar_4(nargout, out, nargin-1, in+1);
break;
case 5:
Point2_argUChar_5(nargout, out, nargin-1, in+1);
break;
case 6:
Point2_dim_6(nargout, out, nargin-1, in+1);
break;
case 7:
Point2_returnChar_7(nargout, out, nargin-1, in+1);
break;
case 8:
Point2_vectorConfusion_8(nargout, out, nargin-1, in+1);
break;
case 9:
Point2_x_9(nargout, out, nargin-1, in+1);
break;
case 10:
Point2_y_10(nargout, out, nargin-1, in+1);
break;
case 11:
Point3_collectorInsertAndMakeBase_11(nargout, out, nargin-1, in+1);
break;
case 12:
Point3_constructor_12(nargout, out, nargin-1, in+1);
break;
case 13:
Point3_deconstructor_13(nargout, out, nargin-1, in+1);
break;
case 14:
Point3_norm_14(nargout, out, nargin-1, in+1);
break;
case 15:
Point3_StaticFunctionRet_15(nargout, out, nargin-1, in+1);
break;
case 16:
Point3_staticFunction_16(nargout, out, nargin-1, in+1);
break;
case 17:
Test_collectorInsertAndMakeBase_17(nargout, out, nargin-1, in+1);
break;
case 18:
Test_constructor_18(nargout, out, nargin-1, in+1);
break;
case 19:
Test_constructor_19(nargout, out, nargin-1, in+1);
break;
case 20:
Test_deconstructor_20(nargout, out, nargin-1, in+1);
break;
case 21:
Test_arg_EigenConstRef_21(nargout, out, nargin-1, in+1);
break;
case 22:
Test_create_MixedPtrs_22(nargout, out, nargin-1, in+1);
break;
case 23:
Test_create_ptrs_23(nargout, out, nargin-1, in+1);
break;
case 24:
Test_print_24(nargout, out, nargin-1, in+1);
break;
case 25:
Test_return_Point2Ptr_25(nargout, out, nargin-1, in+1);
break;
case 26:
Test_return_Test_26(nargout, out, nargin-1, in+1);
break;
case 27:
Test_return_TestPtr_27(nargout, out, nargin-1, in+1);
break;
case 28:
Test_return_bool_28(nargout, out, nargin-1, in+1);
break;
case 29:
Test_return_double_29(nargout, out, nargin-1, in+1);
break;
case 30:
Test_return_field_30(nargout, out, nargin-1, in+1);
break;
case 31:
Test_return_int_31(nargout, out, nargin-1, in+1);
break;
case 32:
Test_return_matrix1_32(nargout, out, nargin-1, in+1);
break;
case 33:
Test_return_matrix2_33(nargout, out, nargin-1, in+1);
break;
case 34:
Test_return_pair_34(nargout, out, nargin-1, in+1);
break;
case 35:
Test_return_ptrs_35(nargout, out, nargin-1, in+1);
break;
case 36:
Test_return_size_t_36(nargout, out, nargin-1, in+1);
break;
case 37:
Test_return_string_37(nargout, out, nargin-1, in+1);
break;
case 38:
Test_return_vector1_38(nargout, out, nargin-1, in+1);
break;
case 39:
Test_return_vector2_39(nargout, out, nargin-1, in+1);
break;
case 40:
aGlobalFunction_40(nargout, out, nargin-1, in+1);
break;
}
} catch(const std::exception& e) {
mexErrMsgTxt(("Exception from gtsam:\n" + std::string(e.what()) + "\n").c_str());
}
std::cout.rdbuf(outbuf);
}
| 35.145396 | 117 | 0.697219 | [
"vector"
] |
ad230896047767d9d94456c692b42f6fe4d67759 | 13,648 | cpp | C++ | src/graphics/backend/csm.cpp | NotAPenguin0/Andromeda | 69ac0e448dbc7d5ba8f5915177f333bd8cd1a1b4 | [
"MIT"
] | 7 | 2020-04-28T11:01:55.000Z | 2022-02-22T09:59:33.000Z | src/graphics/backend/csm.cpp | NotAPenguin0/Andromeda | 69ac0e448dbc7d5ba8f5915177f333bd8cd1a1b4 | [
"MIT"
] | 2 | 2021-09-03T12:58:06.000Z | 2021-09-20T20:07:33.000Z | src/graphics/backend/csm.cpp | NotAPenguin0/Andromeda | 69ac0e448dbc7d5ba8f5915177f333bd8cd1a1b4 | [
"MIT"
] | 1 | 2021-09-03T12:56:25.000Z | 2021-09-03T12:56:25.000Z | #include <andromeda/graphics/backend/csm.hpp>
#include <andromeda/graphics/backend/mesh_draw.hpp>
#include <andromeda/graphics/backend/debug_geometry.hpp>
#define GLM_FORCE_DEPTH_ZERO_TO_ONE
#include <glm/gtc/matrix_transform.hpp>
namespace andromeda::gfx::backend {
bool CascadedShadowMapping::is_shadow_caster(gpu::DirectionalLight const& light) {
return light.direction_shadow.w >= 0;
}
// Only meaningful if is_shadow_caster(light) == true
uint32_t CascadedShadowMapping::get_light_index(gpu::DirectionalLight const& light) {
return static_cast<uint32_t>(light.direction_shadow.w);
}
VkSampler CascadedShadowMapping::create_sampler(gfx::Context& ctx) {
VkSamplerCreateInfo info{};
info.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
info.magFilter = VK_FILTER_LINEAR;
info.minFilter = VK_FILTER_LINEAR;
info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
info.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
info.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
info.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
info.mipLodBias = 0.0f;
info.maxAnisotropy = 1.0f;
info.minLod = 0.0f;
info.maxLod = 1.0f;
info.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE;
info.compareEnable = true;
info.compareOp = VK_COMPARE_OP_LESS;
return ctx.create_sampler(info);
}
void CascadedShadowMapping::free(gfx::Context& ctx) {
for (auto& vp: viewport_data) {
for (auto& map: vp.maps) {
// Skip empty shadow maps
if (map.attachment.empty()) { continue; }
for (auto& cascade: map.cascades) {
ctx.destroy_image_view(cascade.view);
}
ctx.destroy_image_view(map.full_view);
}
}
}
void CascadedShadowMapping::create_pipeline(gfx::Context& ctx) {
ph::PipelineCreateInfo pci = ph::PipelineBuilder::create(ctx, "shadow")
.add_shader("data/shaders/shadow.vert.spv", "main", ph::ShaderStage::Vertex)
.add_vertex_input(0)
// Note that not all these attributes will be used, but they are specified because the vertex size is deduced from them
.add_vertex_attribute(0, 0, VK_FORMAT_R32G32B32_SFLOAT) // iPos
.add_vertex_attribute(0, 1, VK_FORMAT_R32G32B32_SFLOAT) // iNormal
.add_vertex_attribute(0, 2, VK_FORMAT_R32G32B32_SFLOAT) // iTangent
.add_vertex_attribute(0, 3, VK_FORMAT_R32G32_SFLOAT) // iUV
.add_dynamic_state(VK_DYNAMIC_STATE_SCISSOR)
.add_dynamic_state(VK_DYNAMIC_STATE_VIEWPORT)
.set_depth_test(true)
.set_depth_write(true)
.set_depth_clamp(true)
.set_depth_op(VK_COMPARE_OP_LESS_OR_EQUAL)
.set_cull_mode(VK_CULL_MODE_BACK_BIT)
.reflect()
.get();
ctx.create_named_pipeline(std::move(pci));
}
std::vector<ph::Pass> CascadedShadowMapping::build_shadow_map_passes(gfx::Context& ctx, ph::InFlightContext& ifc, gfx::Viewport const& viewport,
gfx::SceneDescription const& scene, ph::BufferSlice transforms) {
std::vector<ph::Pass> passes;
passes.reserve(ANDROMEDA_MAX_SHADOWING_DIRECTIONAL_LIGHTS * ANDROMEDA_SHADOW_CASCADE_COUNT);
for (auto const& dir_light: scene.get_directional_lights()) {
// Skip lights that are not shadow casters
if (!is_shadow_caster(dir_light)) { continue; }
uint32_t const light_index = get_light_index(dir_light);
// Request a shadowmap for this light and viewport.
CascadeMap& shadow_map = request_shadow_map(ctx, viewport, light_index);
// Calculate projection matrices for all cascades.
calculate_cascade_splits(shadow_map, viewport, scene.get_camera_info(viewport), dir_light);
// Write projection matrices to a buffer that we can use in the shader
ph::TypedBufferSlice<glm::mat4> light_pvs = ifc.allocate_scratch_ubo<glm::mat4>(ANDROMEDA_SHADOW_CASCADE_COUNT * sizeof(glm::mat4));
for (uint32_t c = 0; c < ANDROMEDA_SHADOW_CASCADE_COUNT; ++c) {
light_pvs.data[c] = shadow_map.cascades[c].light_proj_view;
}
// Start building passes, one for each cascade
for (uint32_t c = 0; c < ANDROMEDA_SHADOW_CASCADE_COUNT; ++c) {
std::string pass_name = fmt::vformat("shadow [L{}][C{}]", fmt::make_format_args(light_index, c));
auto builder = ph::PassBuilder::create(pass_name);
Cascade& cascade = shadow_map.cascades[c];
builder.add_depth_attachment(shadow_map.attachment, cascade.view, ph::LoadOp::Clear, {.depth_stencil = {1.0, 0}});
builder.execute([&ctx, &scene, transforms, c, light_pvs](ph::CommandBuffer& cmd) {
cmd.auto_viewport_scissor();
cmd.bind_pipeline("shadow");
VkDescriptorSet set = ph::DescriptorBuilder::create(ctx, cmd.get_bound_pipeline())
.add_uniform_buffer("light", light_pvs)
.add_storage_buffer("transforms", transforms)
.get();
cmd.bind_descriptor_set(set);
// Push current cascade index to shader
cmd.push_constants(ph::ShaderStage::Vertex, 0, sizeof(uint32_t), &c);
// Render scene from light POV.
for_each_ready_mesh(scene, [&cmd](auto const& draw, auto const& mesh, auto index) {
// Skip draws that don't cast shadows
if (!draw.occluder) { return; }
// Push transform index to shader and draw
cmd.push_constants(ph::ShaderStage::Vertex, sizeof(uint32_t), sizeof(uint32_t), &index);
bind_and_draw(cmd, mesh);
});
});
passes.push_back(builder.get());
}
}
return passes;
}
void CascadedShadowMapping::register_attachment_dependencies(gfx::Viewport const& viewport, ph::PassBuilder& builder) {
auto const& vp = viewport_data[viewport.index()];
for (CascadeMap const& shadow_map: vp.maps) {
// Skip unused shadow maps
if (shadow_map.attachment.empty()) { continue; }
// Since the render graph will always synchronize entire images, we can get away with only registering
// one dependency for each cascade map, for any cascade layer.
builder.sample_attachment(shadow_map.attachment, shadow_map.cascades[0].view, ph::PipelineStage::FragmentShader);
}
}
std::vector<std::string_view> CascadedShadowMapping::get_debug_attachments(const gfx::Viewport& viewport) {
std::vector<std::string_view> result;
for (auto const& map: viewport_data[viewport.index()].maps) {
if (map.attachment.empty()) { continue; }
result.push_back(map.attachment);
}
return result;
}
ph::ImageView CascadedShadowMapping::get_shadow_map(gfx::Viewport const& viewport, gpu::DirectionalLight const& light) {
CascadeMap& map = viewport_data[viewport.index()].maps[get_light_index(light)];
assert(!map.attachment.empty() && "No shadow map created for this light");
return map.full_view;
}
float CascadedShadowMapping::get_split_depth(gfx::Viewport const& viewport, gpu::DirectionalLight const& light, uint32_t const cascade) {
CascadeMap& map = viewport_data[viewport.index()].maps[get_light_index(light)];
assert(!map.attachment.empty() && "No shadow map created for this light");
return map.cascades[cascade].depth_split;
}
glm::mat4 CascadedShadowMapping::get_cascade_matrix(gfx::Viewport const& viewport, gpu::DirectionalLight const& light, uint32_t const cascade) {
CascadeMap& map = viewport_data[viewport.index()].maps[get_light_index(light)];
assert(!map.attachment.empty() && "No shadow map created for this light");
return map.cascades[cascade].light_proj_view;
}
auto CascadedShadowMapping::request_shadow_map(gfx::Context& ctx, gfx::Viewport const& viewport, uint32_t light_index) -> CascadeMap& {
assert(light_index < ANDROMEDA_MAX_SHADOWING_DIRECTIONAL_LIGHTS && "Light index out of range.");
ViewportShadowMap& vp = viewport_data[viewport.index()];
CascadeMap& map = vp.maps[light_index];
// If the attachment string is not empty this map was created before, and we can simply return it
if (!map.attachment.empty()) {
return map;
}
// Create attachment and ImageViews for cascades.
map.attachment = gfx::Viewport::local_string(viewport, fmt::vformat("Cascaded Shadow Map [L{}]", fmt::make_format_args(light_index)));
ctx.create_attachment(map.attachment, {ANDROMEDA_SHADOW_RESOLUTION, ANDROMEDA_SHADOW_RESOLUTION},
VK_FORMAT_D32_SFLOAT, VK_SAMPLE_COUNT_1_BIT, ANDROMEDA_SHADOW_CASCADE_COUNT, ph::ImageType::DepthStencilAttachment);
// Now create an ImageView for each of the cascades individually
ph::Attachment attachment = ctx.get_attachment(map.attachment);
for (uint32_t i = 0; i < ANDROMEDA_SHADOW_CASCADE_COUNT; ++i) {
Cascade& cascade = map.cascades[i];
// Create image view to mip level 0 of the i-th layer of this image.
cascade.view = ctx.create_image_view(*attachment.image, 0, i, ph::ImageAspect::Depth);
ctx.name_object(cascade.view, fmt::vformat("CSM Cascade [L{}][C{}]", fmt::make_format_args(light_index, i)));
}
map.full_view = ctx.create_image_view(*attachment.image, ph::ImageAspect::Depth);
ctx.name_object(map.full_view, fmt::vformat("CSM Cascade [L{}][Full]", fmt::make_format_args(light_index)));
return map;
}
namespace {
constexpr glm::vec4 base_frustum_corners[8]{
glm::vec4(-1.0f, 1.0f, -1.0f, 1.0f),
glm::vec4(1.0f, 1.0f, -1.0f, 1.0f),
glm::vec4(1.0f, -1.0f, -1.0f, 1.0f),
glm::vec4(-1.0f, -1.0f, -1.0f, 1.0f),
glm::vec4(-1.0f, 1.0f, 1.0f, 1.0f),
glm::vec4(1.0f, 1.0f, 1.0f, 1.0f),
glm::vec4(1.0f, -1.0f, 1.0f, 1.0f),
glm::vec4(-1.0f, -1.0f, 1.0f, 1.0f),
};
}
void CascadedShadowMapping::calculate_cascade_splits(CascadeMap& shadow_map, gfx::Viewport const& viewport, gfx::SceneDescription::CameraInfo const& camera, gpu::DirectionalLight const& light) {
std::array<float, ANDROMEDA_SHADOW_CASCADE_COUNT> splits{};
float const near = camera.near;
float const far = camera.far;
float const clip_range = far - near;
float const z_min = near;
float const z_max = near + clip_range;
float const z_range = z_max - z_min;
float const z_ratio = z_max / z_min;
// Calculate split depths based on view camera frustum
// Based on method presented in https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch10.html
for (uint32_t c = 0; c < ANDROMEDA_SHADOW_CASCADE_COUNT; c++) {
float const p = (c + 1) / static_cast<float>(ANDROMEDA_SHADOW_CASCADE_COUNT);
float const log = z_min * std::pow(z_ratio, p);
float const uniform = z_min + z_range * p;
float const d = cascade_split_lambda * (log - uniform) + uniform;
splits[c] = (d - near) / clip_range;
}
// Project frustum to world space
glm::mat4 cam_inverse = glm::inverse(camera.proj_view);
// cam_inverse[1][1] *= -1;
// Compute orthographic projection matrix for each cascade
float last_split = 0.0f;
for (uint32_t c = 0; c < ANDROMEDA_SHADOW_CASCADE_COUNT; ++c) {
float const split = splits[c];
// Projected frustum (Camera -> Worldspace)
std::array<glm::vec3, 8> frustum{};
for (uint32_t f = 0; f < frustum.size(); ++f) {
glm::vec4 const corner_inverse = cam_inverse * base_frustum_corners[f];
frustum[f] = corner_inverse / corner_inverse.w;
}
// Move frustum to match cascade split
for (uint32_t f = 0; f < frustum.size() / 2; ++f) {
glm::vec3 const distance = frustum[f + 4] - frustum[f];
// Move the far corner to the new split distance
frustum[f + 4] = frustum[f] + (distance * split);
// Move the close corner to the old split distance
frustum[f] = frustum[f] + (distance * last_split);
}
// Compute center of frustum by averaging together all points
glm::vec3 frustum_center = glm::vec3(0.0f);
for (auto const& corner: frustum) {
frustum_center += corner;
frustum_center /= static_cast<float>(frustum.size());
}
// Compute radius of bounding sphere. We do this by finding the largest distance
// between the center and each of the points.
float radius = 0.0f;
for (auto const& corner: frustum) {
float const distance = glm::length(corner - frustum_center);
radius = std::max(radius, distance);
}
// Round radius
radius = std::ceil(radius * 16.0f) / 16.0f;
glm::vec3 const max_extents = glm::vec3(radius);
glm::vec3 const min_extents = -max_extents;
glm::vec3 const light_dir = glm::vec3(light.direction_shadow.x, light.direction_shadow.y, light.direction_shadow.z);
glm::mat4 light_view = glm::lookAt(frustum_center - light_dir * -min_extents.z, frustum_center, glm::vec3(0, 1, 0));
glm::mat4 light_proj = glm::ortho(min_extents.x, max_extents.x, min_extents.y, max_extents.y, 0.0f, max_extents.z - min_extents.z);
// Store split distance and matrix in cascade structure
shadow_map.cascades[c].depth_split = (near + split * clip_range) * -1.0f;
shadow_map.cascades[c].light_proj_view = light_proj * light_view;
// Store last split value, so we can correctly build the frustum for next iteration
last_split = split;
}
}
} | 46.580205 | 194 | 0.669402 | [
"mesh",
"render",
"vector",
"transform"
] |
ad25ae0bea0961ea8b86f2fe34b1a71d4b2e031a | 1,198 | hpp | C++ | lib/src/frand_cache.hpp | WojciechMigda/tsetlini | 537f6b4c30c40b07a747006c0878276298c0318e | [
"MIT"
] | 1 | 2018-11-29T08:41:44.000Z | 2018-11-29T08:41:44.000Z | lib/src/frand_cache.hpp | WojciechMigda/TsetlinMachineToolkit | 537f6b4c30c40b07a747006c0878276298c0318e | [
"MIT"
] | null | null | null | lib/src/frand_cache.hpp | WojciechMigda/TsetlinMachineToolkit | 537f6b4c30c40b07a747006c0878276298c0318e | [
"MIT"
] | null | null | null | #pragma once
#ifndef LIB_SRC_FRAND_CACHE_HPP_
#define LIB_SRC_FRAND_CACHE_HPP_
#include "tsetlini_types.hpp"
#include "aligned_allocator.hpp"
#include "assume_aligned.hpp"
#include <vector>
#include <algorithm>
namespace Tsetlini
{
template<int alignment=alignment, typename ValueType=float>
struct frand_cache
{
using value_type = ValueType;
explicit frand_cache(int sz) :
m_pos(sz),
m_fcache(sz)
{
}
frand_cache()
: m_pos(0)
, m_fcache(0)
{
}
template<typename TPRNG>
inline
void refill(TPRNG & frng)
{
value_type * fcache_p = assume_aligned<alignment>(m_fcache.data());
for (auto it = 0u; it < std::min<unsigned int>(m_pos, m_fcache.size()); ++it)
{
fcache_p[it] = frng();
}
m_pos = 0;
}
inline
value_type next()
{
value_type * fcache_p = assume_aligned<alignment>(m_fcache.data());
return fcache_p[m_pos++];
}
inline
value_type operator()()
{
return next();
}
unsigned int m_pos;
aligned_vector<value_type> m_fcache;
};
} // namespace Tsetlini
#endif /* LIB_SRC_FRAND_CACHE_HPP_ */
| 17.617647 | 85 | 0.616027 | [
"vector"
] |
ad2674bc1edf29358d846cde5eafac197a6e2fb0 | 3,618 | cpp | C++ | markerServer/build-untitled-Desktop_Qt_5_7_1_MinGW_32bit-Debug/debug/moc_client.cpp | vasyllll95/MarkerServer | fb256b5468fabdd787c365e1632f202752209fa7 | [
"MIT"
] | 1 | 2017-03-17T21:01:41.000Z | 2017-03-17T21:01:41.000Z | markerServer/build-untitled-Desktop_Qt_5_7_1_MinGW_32bit-Debug/debug/moc_client.cpp | vasyllll95/MarkerServer | fb256b5468fabdd787c365e1632f202752209fa7 | [
"MIT"
] | null | null | null | markerServer/build-untitled-Desktop_Qt_5_7_1_MinGW_32bit-Debug/debug/moc_client.cpp | vasyllll95/MarkerServer | fb256b5468fabdd787c365e1632f202752209fa7 | [
"MIT"
] | null | null | null | /****************************************************************************
** Meta object code from reading C++ file 'client.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.7.1)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../untitled/client.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'client.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.7.1. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
struct qt_meta_stringdata_client_t {
QByteArrayData data[6];
char stringdata0[46];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_client_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_client_t qt_meta_stringdata_client = {
{
QT_MOC_LITERAL(0, 0, 6), // "client"
QT_MOC_LITERAL(1, 7, 7), // "ReadAll"
QT_MOC_LITERAL(2, 15, 0), // ""
QT_MOC_LITERAL(3, 16, 12), // "SendResponce"
QT_MOC_LITERAL(4, 29, 8), // "responce"
QT_MOC_LITERAL(5, 38, 7) // "addBody"
},
"client\0ReadAll\0\0SendResponce\0responce\0"
"addBody"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_client[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
2, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: name, argc, parameters, tag, flags
1, 0, 24, 2, 0x0a /* Public */,
3, 2, 25, 2, 0x0a /* Public */,
// slots: parameters
QMetaType::Void,
QMetaType::Void, QMetaType::QString, QMetaType::QByteArray, 4, 5,
0 // eod
};
void client::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
client *_t = static_cast<client *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->ReadAll(); break;
case 1: _t->SendResponce((*reinterpret_cast< QString(*)>(_a[1])),(*reinterpret_cast< QByteArray(*)>(_a[2]))); break;
default: ;
}
}
}
const QMetaObject client::staticMetaObject = {
{ &QObject::staticMetaObject, qt_meta_stringdata_client.data,
qt_meta_data_client, qt_static_metacall, Q_NULLPTR, Q_NULLPTR}
};
const QMetaObject *client::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *client::qt_metacast(const char *_clname)
{
if (!_clname) return Q_NULLPTR;
if (!strcmp(_clname, qt_meta_stringdata_client.stringdata0))
return static_cast<void*>(const_cast< client*>(this));
return QObject::qt_metacast(_clname);
}
int client::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QObject::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 2)
qt_static_metacall(this, _c, _id, _a);
_id -= 2;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 2)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 2;
}
return _id;
}
QT_END_MOC_NAMESPACE
| 30.661017 | 124 | 0.607794 | [
"object"
] |
ad278f373e4463bf2d8ab6f4690521e89ae08fc4 | 3,555 | cpp | C++ | Sources/XML/XML/xpath_object.cpp | ValtoFrameworks/ClanLib | 2d6b59386ce275742653b354a1daab42cab7cb3e | [
"Linux-OpenIB"
] | null | null | null | Sources/XML/XML/xpath_object.cpp | ValtoFrameworks/ClanLib | 2d6b59386ce275742653b354a1daab42cab7cb3e | [
"Linux-OpenIB"
] | null | null | null | Sources/XML/XML/xpath_object.cpp | ValtoFrameworks/ClanLib | 2d6b59386ce275742653b354a1daab42cab7cb3e | [
"Linux-OpenIB"
] | null | null | null | /*
** ClanLib SDK
** Copyright (c) 1997-2016 The ClanLib Team
**
** 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.
**
** Note: Some of the libraries ClanLib may link to may have additional
** requirements or restrictions.
**
** File Author(s):
**
** Magnus Norddahl
** Thomas Gottschalk Larsen
*/
#include "XML/precomp.h"
#include "API/XML/xpath_object.h"
#include "API/XML/dom_node.h"
namespace clan
{
class XPathObject_Impl
{
public:
XPathObject_Impl()
: type(XPathObject::type_null), boolean(false), number(0.0)
{
}
XPathObject::Type type;
std::vector<DomNode> node_set;
bool boolean;
double number;
std::string string;
};
XPathObject::XPathObject()
: impl(std::make_shared<XPathObject_Impl>())
{
impl->type = XPathObject::type_null;
}
XPathObject::XPathObject(bool value)
: impl(std::make_shared<XPathObject_Impl>())
{
set_boolean(value);
}
XPathObject::XPathObject(double value)
: impl(std::make_shared<XPathObject_Impl>())
{
set_number(value);
}
XPathObject::XPathObject(size_t value)
: impl(std::make_shared<XPathObject_Impl>())
{
set_number(value);
}
XPathObject::XPathObject(const std::string &value)
: impl(std::make_shared<XPathObject_Impl>())
{
set_string(value);
}
XPathObject::XPathObject(const std::vector<DomNode> &value)
: impl(std::make_shared<XPathObject_Impl>())
{
set_node_set(value);
}
XPathObject::Type XPathObject::get_type() const
{
return impl->type;
}
bool XPathObject::is_null() const
{
return impl->type == type_null;
}
std::vector<DomNode> XPathObject::get_node_set() const
{
if (impl->type == type_node_set)
return impl->node_set;
else
return std::vector<DomNode>();
}
bool XPathObject::get_boolean() const
{
if (impl->type == type_boolean)
return impl->boolean;
else
return false;
}
double XPathObject::get_number() const
{
if (impl->type == type_number)
return impl->number;
else
return 0.0;
}
std::string XPathObject::get_string() const
{
if (impl->type == type_string)
return impl->string;
else
return std::string();
}
void XPathObject::set_null()
{
impl->type = type_null;
impl->node_set.clear();
}
void XPathObject::set_node_set(const std::vector<DomNode> &node_set)
{
impl->type = type_node_set;
impl->node_set = node_set;
}
void XPathObject::set_boolean(bool value)
{
impl->type = type_boolean;
impl->boolean = value;
impl->node_set.clear();
}
void XPathObject::set_number(double value)
{
impl->type = type_number;
impl->number = value;
impl->node_set.clear();
}
void XPathObject::set_string(const std::string &str)
{
impl->type = type_string;
impl->string = str;
impl->node_set.clear();
}
}
| 21.944444 | 78 | 0.697046 | [
"vector"
] |
ad2e862fb170c3684bdb182759c8d231f518aebf | 14,299 | cpp | C++ | day20/main.cpp | bashbaug/adventofcode_2020 | d1a18a034503744bc322168f1d77ea436125079d | [
"Unlicense"
] | null | null | null | day20/main.cpp | bashbaug/adventofcode_2020 | d1a18a034503744bc322168f1d77ea436125079d | [
"Unlicense"
] | null | null | null | day20/main.cpp | bashbaug/adventofcode_2020 | d1a18a034503744bc322168f1d77ea436125079d | [
"Unlicense"
] | null | null | null | #include <algorithm>
#include <cinttypes>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
struct Tile {
Tile(int num) : Used(false), Num(num), Dim(0), Matches(0) {}
const char& get(int row, int col) const
{
return Data.at(row * Dim + col);
}
char& get(int row, int col)
{
return Data.at(row * Dim + col);
}
void addRow(const std::string& rowdata)
{
if (Dim == 0) {
Dim = (int)rowdata.length();
} else {
if (Dim != rowdata.length()) {
printf("Row data mismatch? Had %d, got %d.\n", Dim, (int)rowdata.length());
}
}
Data += rowdata;
}
std::string getEdge(int num) const
{
// 0 = top, 1 = right, 2 = bottom, 3 = left
std::string ret;
if (num % 4 == 0) {
ret = Data.substr(0, Dim);
} else if (num % 4 == 1) {
for (int c = 0; c < Dim; c++) {
ret += get(c, Dim - 1);
}
} else if (num % 4 == 2) {
ret = Data.substr((Dim - 1) * Dim, Dim);
} else if (num % 4 == 3) {
for (int c = 0; c < Dim; c++) {
ret += get(c, 0);
}
}
if (num >= 4) {
std::reverse(ret.begin(), ret.end());
}
return ret;
}
bool matches(const Tile& othertile, int& outindex) const
{
if (Num == othertile.Num) {
printf("Tile %d trivially matches tile %d - BUT IS THIS WHAT YOU WANTED TO DO?\n", Num, othertile.Num);
return true;
}
for (int e = 0; e < 4; e++) {
std::string edge = getEdge(e);
for (int oe = 0; oe < 8; oe++) {
std::string other = othertile.getEdge(oe);
if (edge == other) {
printf("Tile %d matches tile %d.\n", Num, othertile.Num);
outindex = oe;
return true;
}
}
}
return false;
}
void print() const
{
printf("\n\nTile %d\n", Num);
for (int row = 0; row < Dim; row++) {
printf(" %s\n", Data.substr(row * Dim, Dim).c_str());
}
}
void printedges() const
{
printf("Tile %d edges\n", Num);
for (int edge = 0; edge < 8; edge++) {
printf(" %d: %s\n", edge, getEdge(edge).c_str());
}
}
void flipV()
{
std::string newData;
for (int row = 0; row < Dim; row++) {
for (int col = 0; col < Dim; col++) {
newData += get(Dim - row - 1, col);
}
}
Data = newData;
}
void flipH()
{
std::string newData;
for (int row = 0; row < Dim; row++) {
for (int col = 0; col < Dim; col++) {
newData += get(row, Dim - col - 1);
}
}
Data = newData;
}
void rotateR()
{
std::string newData;
for (int row = 0; row < Dim; row++) {
for (int col = 0; col < Dim; col++) {
newData += get(Dim - col - 1, row);
}
}
Data = newData;
}
void rotateL()
{
std::string newData;
for (int row = 0; row < Dim; row++) {
for (int col = 0; col < Dim; col++) {
newData += get(col, Dim - row - 1);
}
}
Data = newData;
}
void transpose()
{
std::string newData;
for (int row = 0; row < Dim; row++) {
for (int col = 0; col < Dim; col++) {
newData += get(col, row);
}
}
Data = newData;
}
std::string Data;
bool Used;
int Num;
int Dim;
int Matches;
};
int findnext(std::vector<Tile>& tiles, int left, int above, const std::vector<int>& search)
{
for (auto index : search) {
Tile& othertile = tiles[index];
if (othertile.Used == true) continue;
bool found = true;
if (left >= 0) {
const Tile& lefttile = tiles[left];
int outindex;
found &= lefttile.matches(othertile, outindex);
if (found) {
printf("Before Left Adjustment (out index is %d)...\n", outindex);
othertile.print();
switch(outindex) {
case 0: othertile.flipH(); othertile.rotateL(); break; // top
case 4: othertile.rotateL(); break; // top reversed
case 1: othertile.flipH(); break; // right
case 5: othertile.flipV(); othertile.flipH(); break; // right reversed
case 2: othertile.rotateR(); break; // bottom
case 6: othertile.flipH(); othertile.rotateR(); break; // bottom reversed
case 3: break; // left
case 7: othertile.flipV(); break; // left reversed
default: printf("Unknown out index %d!\n", outindex);
}
printf("After...\n"); othertile.print();
int test;
lefttile.matches(othertile, test);
if (test != 3) {
printf("Bad left alignment! outindex was %d, test is %d\n", outindex, test);
}
}
}
if (above >= 0) {
const Tile& abovetile = tiles[above];
int outindex;
found &= abovetile.matches(othertile, outindex);
if (found) {
printf("Before Top Adjustment (out index is %d)...\n", outindex);
printf("Above Tile:\n");
abovetile.print();
printf("This Tile:\n");
othertile.print();
switch(outindex) {
case 0: break; // top
case 4: othertile.flipH(); break; // top reversed
case 1: othertile.rotateL(); break; // right
case 5: othertile.flipV(); othertile.rotateL(); break; // right reversed
case 2: othertile.flipV(); break; // bottom
case 6: othertile.flipH(); othertile.flipV(); break; // bottom reversed
case 3: othertile.flipV(); othertile.rotateR(); break; // left
case 7: othertile.rotateR(); break; // left reversed
default: printf("Unknown out index %d!\n", outindex);
}
printf("After...\n");
othertile.print();
int test;
abovetile.matches(othertile, test);
if (test != 0) {
printf("Bad top alignment! left index is %d, outindex was %d, test is %d\n", left, outindex, test);
}
}
}
if (found) {
return index;
}
}
printf("I didn't find it??\n");
return -1;
}
void stitch(const std::vector<Tile>& tiles, const std::vector<int>& sequence, int tiledim, Tile& outtile)
{
std::string megarow;
for (int tr = 0; tr < tiledim; tr++) {
for (int r = 0; r < tiles[0].Dim; r++) {
megarow = "";
for (int tc = 0; tc < tiledim; tc++) {
int tile = sequence[tr * tiledim + tc];
for (int c = 0; c < tiles[0].Dim; c++) {
char value = tiles[tile].get(r, c);
putchar(value);
if (c != 0 && c != tiles[0].Dim - 1) {
megarow += tiles[tile].get(r, c);
}
}
putchar(' ');
}
printf("\n");
if (r != 0 && r != tiles[0].Dim - 1) {
outtile.addRow(megarow);
}
}
printf("\n");
}
}
bool findmonster(const Tile& image, const std::vector<std::string>& pattern, int ir, int ic)
{
for (int pr = 0; pr < pattern.size(); pr++) {
for (int pc = 0; pc < pattern[pr].length(); pc++) {
if (pattern[pr].at(pc) == '#' && image.get(ir + pr, ic + pc) != '#') {
return false;
}
}
}
return true;
}
int countmonsters(const Tile& image, const std::vector<std::string>& pattern)
{
int count = 0;
for (int r = 0; r < image.Dim - pattern.size(); r++) {
for (int c = 0; c < image.Dim - pattern[0].length(); c++ ) {
bool found = findmonster(image, pattern, r, c);
if (found) {
printf("Found a monster at row: %d, col: %d\n", r, c);
count++;
}
}
}
return count;
}
int main(int argc, char** argv)
{
std::ifstream is(argv[1]);
std::string str;
std::vector<Tile> tiles;
while (std::getline(is, str)) {
int num = 0;
std::sscanf(str.c_str(), "Tile %d:", &num);
Tile tile(num);
while (std::getline(is, str)) {
if (str.empty()) break;
tile.addRow(str);
}
tiles.push_back(tile);
}
printf("Found %d tiles.\n", (int)tiles.size());
for (const auto& tile : tiles) {
tile.print();
tile.printedges();
}
for (int t = 0; t < tiles.size(); t++) {
for (int ot = t + 1; ot < tiles.size(); ot++) {
if (t == ot) continue;
int outindex;
if (tiles[t].matches(tiles[ot], outindex)) {
tiles[t].Matches++;
tiles[ot].Matches++;
}
}
}
std::vector<int> corners;
std::vector<int> edges;
std::vector<int> middles;
uint64_t product = 1;
int others = 0;
for (int t = 0; t < tiles.size(); t++) {
printf("Tile %d (%d) has %d matches.\n", t, tiles[t].Num, tiles[t].Matches);
if (tiles[t].Matches == 2) {
printf("\t --> Found corner tile %d (%d)?\n", t, tiles[t].Num);
corners.push_back(t);
product *= tiles[t].Num;
} else if (tiles[t].Matches == 3) {
edges.push_back(t);
} else if (tiles[t].Matches == 4) {
middles.push_back(t);
} else {
others++;
}
}
int tiledim = (int)edges.size() / 4 + 2;
std::vector<int> sequence;
// This is a hack!
// If we didn't want to do this hack we could instead track used edges
// and orient with an edge on the right and bottom.
if (tiledim == 3) {
// sample input
tiles[corners[0]].flipV();
} else if (tiledim == 12) {
// actual input
tiles[corners[0]].transpose();
}
{
// Start with an arbitrary corner tile:
sequence.push_back(corners[0]);
tiles[corners[0]].Used = true;
for (int t = 0; t < edges.size() / 4; t++) {
int left = sequence.back();
int next = findnext(tiles, left, -1, edges);
sequence.push_back(next);
tiles[next].Used = true;
}
// Find the ending corner tile:
{
int left = sequence.back();
int next = findnext(tiles, left, -1, corners);
sequence.push_back(next);
tiles[next].Used = true;
}
for (int r = 0; r < edges.size() / 4; r++) {
// Find the first edge tile.
{
int above = sequence[sequence.size() - tiledim];
int next = findnext(tiles, -1, above, edges);
sequence.push_back(next);
tiles[next].Used = true;
}
for (int t = 0; t < edges.size() / 4; t++) {
int left = sequence.back();
int above = sequence[sequence.size() - tiledim];
int next = findnext(tiles, left, above, middles);
sequence.push_back(next);
tiles[next].Used = true;
}
// Find the ending edge tile.
{
int left = sequence.back();
int above = sequence[sequence.size() - tiledim];
int next = findnext(tiles, left, above, edges);
sequence.push_back(next);
tiles[next].Used = true;
}
}
// Find the last row corner tile.
{
int above = sequence[sequence.size() - tiledim];
int next = findnext(tiles, -1, above, corners);
sequence.push_back(next);
tiles[next].Used = true;
}
for (int t = 0; t < edges.size() / 4; t++) {
int left = sequence.back();
int above = sequence[sequence.size() - tiledim];
int next = findnext(tiles, left, above, edges);
sequence.push_back(next);
tiles[next].Used = true;
}
// Find the ending corner tile:
{
int left = sequence.back();
int above = sequence[sequence.size() - tiledim];
int next = findnext(tiles, left, above, corners);
sequence.push_back(next);
tiles[next].Used = true;
}
}
for (int i = 0; i < sequence.size(); i++) {
if (i % tiledim == 0) {
printf("\n");
}
printf("%4d ", tiles[sequence[i]].Num);
}
printf("\n\nStitched image:\n\n");
Tile outtile(9999999);
stitch(tiles, sequence, (int)edges.size() / 4 + 2, outtile);
printf("Output tile:\n");
outtile.print();
std::vector<std::string> monster;
monster.push_back(" # ");
monster.push_back("# ## ## ###");
monster.push_back(" # # # # # # ");
int count = 0;
count += countmonsters(outtile, monster);
printf("Original orientation: Found %d monsters.\n", count);
outtile.transpose();
count += countmonsters(outtile, monster);
printf("Transpose: Found %d monsters.\n", count);
int water = 0;
for (const auto c : outtile.Data) {
if (c == '#') ++water;
}
printf("\n\nFound %d corners, %d edges, %d, middles, and %d others.\n", (int)corners.size(), (int)edges.size(), (int)middles.size(), others);
printf("Product of corner tiles = %" PRIu64 "\n", product);
printf("Found %d water. Subtract %d x 15 == %d\n", water, count, water - count * 15);
return 0;
}
| 30.230444 | 145 | 0.458004 | [
"vector"
] |
ad366fea06e4d9dca541881e287051b408e45ffc | 2,300 | hpp | C++ | source/headers/Protocol/Handshake.hpp | IshaySela/PubSub | d25a90458c4fb178dc3c8eb8a0f204d0c4347043 | [
"MIT"
] | null | null | null | source/headers/Protocol/Handshake.hpp | IshaySela/PubSub | d25a90458c4fb178dc3c8eb8a0f204d0c4347043 | [
"MIT"
] | null | null | null | source/headers/Protocol/Handshake.hpp | IshaySela/PubSub | d25a90458c4fb178dc3c8eb8a0f204d0c4347043 | [
"MIT"
] | null | null | null | #ifndef HANDSHAKE
#define HANDSHAKE
#include "../json.hpp"
#include "ClientType.hpp"
#define HEADER_NAME_CLIENT_TYPE "ClientType"
#define HEADER_NAME_AUTHENTICATION_SECRET "AuthSecret"
#define HEADER_NAME_SHOULD_ENCRYPT "Encrypt"
#define HEADER_NAME_ENCRYPTION_STRING "EncryptionString"
using Json = nlohmann::json;
namespace PubSub
{
namespace Protocol
{
/**
* @brief The handshake class wrapps the json object recived from the client, and creates simple ways to access the headers information.
* <a href="0_handshake.json" target="_blank">implements /Schema/0_handshake.json</a>
*/
class Handshake
{
public:
Handshake(const std::string &raw);
Handshake(const char *raw);
/**
* @brief Chek if the json object is valid.
*@returns boolean. true if the json contains all required keys, false otherwise.
*/
bool validHeaders();
bool getShouldEncrypt() const;
std::string getAuthenticationSecret() const;
std::string getEncryptionString() const;
ClientType getClientType() const;
template <typename T>
T get(const char* headerName);
/**
*Create a handshake class, and throw runtime error if the json is not validate.
*/
static Handshake createAndThrow(const std::string &json);
static Handshake createAndThrow(const char *json);
private:
Json json; ///< The raw json object of the class.
bool shouldEncrypt;
ClientType clientType;
std::string authenticationSecret;
std::string encryptionString;
/**
* @brief Set all default headers to their default values (if they do not exists in the json)
*/
void setDefaultHeadersForJson();
/**
* @brief Get all of the headers from the json into their variables.
*/
void setHeadersFromJson();
};
template <typename T>
T Handshake::get(const char* headerName)
{
return this->json[headerName].get<T>();
}
} // namespace Protocol
} // namespace PubSub
#endif | 30.666667 | 143 | 0.600435 | [
"object"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.