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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ff4bab551d6348c46c4d03061fada6720163685d | 1,192 | cpp | C++ | Editor/Wrappers/Objects/AGEGameScene.cpp | alexshpunt/art_gear | 64a2d001570812690fc8845f694f2bfe1d96c3a2 | [
"MIT"
] | null | null | null | Editor/Wrappers/Objects/AGEGameScene.cpp | alexshpunt/art_gear | 64a2d001570812690fc8845f694f2bfe1d96c3a2 | [
"MIT"
] | null | null | null | Editor/Wrappers/Objects/AGEGameScene.cpp | alexshpunt/art_gear | 64a2d001570812690fc8845f694f2bfe1d96c3a2 | [
"MIT"
] | null | null | null | #include "AGEGameScene.h"
#include "AGEGameObject.h"
AGEGameScene::AGEGameScene(const std::string& name)
: m_scene( new AGGameScene( name ) ),
m_name( name )
{}
AGEGameScene::~AGEGameScene(){}
AGEGameObject* AGEGameScene::createObject(const std::string& name)
{
AGEGameObject* gameObject = new AGEGameObject( m_scene->createObject( name ) );
m_objects.push_back( gameObject );
m_objectsByName[ name ] = gameObject;
return gameObject;
}
AGEGameObject* AGEGameScene::copyFrom(AGEGameObject* object)
{
return nullptr;
}
void AGEGameScene::removeObject(AGEGameObject* object)
{
m_objects.remove( object );
m_objectsByName.erase( object->getName() );
}
void AGEGameScene::removeObject(const std::string& name)
{
auto iter = m_objectsByName.find( name );
m_objects.remove( (*iter).second );
m_objectsByName.erase( name );
}
void AGEGameScene::selectObject(AGEGameObject* object)
{
object->setSelected( true );
m_selectedObject = object;
}
AGEGameObject* AGEGameScene::getSelectedObject() const
{
return m_selectedObject;
}
void AGEGameScene::setName(const std::string& name)
{
m_name = name;
}
const std::string& AGEGameScene::getName() const
{
return m_name;
}
| 20.20339 | 80 | 0.741611 | [
"object"
] |
ff5a42c1768682bd095f4bcced5b425219f89750 | 6,681 | cpp | C++ | ViroRenderer/VRODiffuseIrradianceTest.cpp | dthian/virocore | c702528e0e3ffd8324c1597d65a73bc6adf0e11d | [
"MIT"
] | 2 | 2019-10-16T14:30:06.000Z | 2019-10-30T23:14:30.000Z | ViroRenderer/VRODiffuseIrradianceTest.cpp | dthian/virocore | c702528e0e3ffd8324c1597d65a73bc6adf0e11d | [
"MIT"
] | 47 | 2021-09-08T13:03:44.000Z | 2022-03-10T23:21:05.000Z | ViroRenderer/VRODiffuseIrradianceTest.cpp | dthian/virocore | c702528e0e3ffd8324c1597d65a73bc6adf0e11d | [
"MIT"
] | 2 | 2020-08-26T14:50:23.000Z | 2021-01-04T02:21:02.000Z | //
// VRODiffuseIrradianceTest.cpp
// ViroKit
//
// Created by Raj Advani on 1/18/18.
// Copyright © 2018 Viro Media. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#include "VRODiffuseIrradianceTest.h"
#include "VROTestUtil.h"
#include "VROCompress.h"
#include "VROSphere.h"
VRODiffuseIrradianceTest::VRODiffuseIrradianceTest() :
VRORendererTest(VRORendererTestType::PBRDirect) {
_angle = 0;
_textureIndex = 0;
}
VRODiffuseIrradianceTest::~VRODiffuseIrradianceTest() {
}
void VRODiffuseIrradianceTest::build(std::shared_ptr<VRORenderer> renderer,
std::shared_ptr<VROFrameSynchronizer> frameSynchronizer,
std::shared_ptr<VRODriver> driver) {
_sceneController = std::make_shared<VROARSceneController>();
std::shared_ptr<VROScene> scene = _sceneController->getScene();
std::shared_ptr<VROPortal> rootNode = scene->getRootNode();
rootNode->setPosition({0, 0, 0});
nextEnvironment();
VROVector3f lightPositions[] = {
VROVector3f(-10, 10, 10),
VROVector3f( 10, 10, 10),
VROVector3f(-10, -10, 10),
VROVector3f( 10, -10, 10),
};
float intensity = 300;
VROVector3f lightColors[] = {
VROVector3f(1, 1, 1),
VROVector3f(1, 1, 1),
VROVector3f(1, 1, 1),
VROVector3f(1, 1, 1),
};
int rows = 7;
int columns = 7;
float spacing = 2.5;
std::shared_ptr<VRONode> sphereContainerNode = std::make_shared<VRONode>();
// Render an array of spheres, varying roughness and metalness
for (int row = 0; row < rows; ++row) {
float radius = 1;
float metalness = (float) row / (float) rows;
for (int col = 0; col < columns; ++col) {
// Clamp the roughness to [0.05, 1.0] as perfectly smooth surfaces (roughness of 0.0)
// tend to look off on direct lighting
float roughness = VROMathClamp((float) col / (float) columns, 0.05, 1.0);
std::shared_ptr<VROSphere> sphere = VROSphere::createSphere(radius, 20, 20, true);
const std::shared_ptr<VROMaterial> &material = sphere->getMaterials().front();
material->getDiffuse().setColor({ 0.5, 0.5, 0.5, 1.0 });
material->getRoughness().setColor({ roughness, 1.0, 1.0, 1.0 });
material->getMetalness().setColor({ metalness, 1.0, 1.0, 1.0 });
material->getAmbientOcclusion().setColor({ 1.0, 1.0, 1.0, 1.0 });
material->setLightingModel(VROLightingModel::PhysicallyBased);
std::shared_ptr<VRONode> sphereNode = std::make_shared<VRONode>();
sphereNode->setPosition({ (float)(col - (columns / 2)) * spacing,
(float)(row - (rows / 2)) * spacing,
0.0f });
sphereNode->setGeometry(sphere);
sphereContainerNode->addChildNode(sphereNode);
}
}
rootNode->addChildNode(sphereContainerNode);
_eventDelegate = std::make_shared<VROIBLEventDelegate>(scene, this);
_eventDelegate->setEnabledEvent(VROEventDelegate::EventAction::OnClick, true);
sphereContainerNode->setEventDelegate(_eventDelegate);
// Render the light sources as spheres as well
for (unsigned int i = 0; i < sizeof(lightPositions) / sizeof(lightPositions[0]); ++i) {
std::shared_ptr<VROLight> light = std::make_shared<VROLight>(VROLightType::Omni);
light->setColor(lightColors[i]);
light->setPosition(lightPositions[i]);
light->setAttenuationStartDistance(20);
light->setAttenuationEndDistance(30);
light->setIntensity(intensity);
rootNode->addLight(light);
}
std::shared_ptr<VRONodeCamera> camera = std::make_shared<VRONodeCamera>();
std::shared_ptr<VRONode> cameraNode = std::make_shared<VRONode>();
cameraNode->setPosition({ 0, 0, 20 }); // 9 is good for VR, for for Scene we push further back
cameraNode->setCamera(camera);
rootNode->addChildNode(cameraNode);
std::shared_ptr<VROAction> action = VROAction::perpetualPerFrameAction([this] (VRONode *const node, float seconds) {
_angle += .0015;
node->setRotation({ 0, _angle, 0});
return true;
});
//sphereContainerNode->runAction(action);
_pointOfView = cameraNode;
}
void VRODiffuseIrradianceTest::nextEnvironment() {
std::shared_ptr<VROTexture> environment;
if (_textureIndex == 0) {
environment = VROTestUtil::loadRadianceHDRTexture("san_giuseppe_bridge_1k");
} else if (_textureIndex == 1) {
environment = VROTestUtil::loadRadianceHDRTexture("ibl_newport_loft");
} else if (_textureIndex == 2) {
environment = VROTestUtil::loadRadianceHDRTexture("ibl_ridgecrest_road");
} else if (_textureIndex == 3) {
environment = VROTestUtil::loadRadianceHDRTexture("ibl_wooden_door");
} else if (_textureIndex == 4) {
environment = VROTestUtil::loadRadianceHDRTexture("ibl_mans_outside");
}
std::shared_ptr<VROScene> scene = _sceneController->getScene();
scene->getRootNode()->setLightingEnvironment(environment);
scene->getRootNode()->setBackgroundSphere(environment);
_textureIndex = (_textureIndex + 1) % 5;
}
void VROIBLEventDelegate::onClick(int source, std::shared_ptr<VRONode> node, ClickState clickState,
std::vector<float> position) {
if (clickState != Clicked) {
return;
}
_test->nextEnvironment();
}
| 41.496894 | 120 | 0.650651 | [
"render",
"vector"
] |
ff5b1f8c3cd0652b55e99b93af1bacb34bd4cdb1 | 5,100 | cpp | C++ | ImgRef/main.cpp | arttu94/ImgRef | 3b1ac03183302b298f6a4f92aa172f1804f0fe05 | [
"MIT"
] | null | null | null | ImgRef/main.cpp | arttu94/ImgRef | 3b1ac03183302b298f6a4f92aa172f1804f0fe05 | [
"MIT"
] | null | null | null | ImgRef/main.cpp | arttu94/ImgRef | 3b1ac03183302b298f6a4f92aa172f1804f0fe05 | [
"MIT"
] | null | null | null | #include <SDL.h>
#include <SDL_image.h>
#include <stdio.h>
#include "main.h"
const int SCREEN_WIDTH = 400;
const int SCREEN_HEIGHT = 200;
bool Init();
bool LoadMedia(const char* dir);
void Close();
SDL_Texture* LoadTexture(const char* dir);
SDL_Window* window = nullptr;
SDL_Renderer* renderer = nullptr;
SDL_Texture* texture = nullptr;
float WindowOpacity = 1.0f;
bool LockWindow = false;
bool TextureFillWindow = false;
bool Init()
{
bool success = true;
//Initialize SDL
if (SDL_Init(SDL_INIT_VIDEO) < 0)
{
printf("SDL could not initialize! SDL Error: %s\n", SDL_GetError());
success = false;
}
else
{
//Set texture filtering to linear
if (!SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "1"))
{
printf("Warning: Linear texture filtering not enabled!");
}
//Create window
window = SDL_CreateWindow("Reference Image", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN | SDL_WINDOW_ALWAYS_ON_TOP);
if (window == NULL)
{
printf("Window could not be created! SDL Error: %s\n", SDL_GetError());
success = false;
}
else
{
//Create renderer for window
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
if (renderer == NULL)
{
printf("Renderer could not be created! SDL Error: %s\n", SDL_GetError());
success = false;
}
else
{
//Initialize renderer color
SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF);
//Initialize PNG loading
int imgFlags = IMG_INIT_PNG;
if (!(IMG_Init(imgFlags) & imgFlags))
{
printf("SDL_image could not initialize! SDL_image Error: %s\n", IMG_GetError());
success = false;
}
}
}
}
return success;
}
bool LoadMedia(const char* dir)
{
//Loading success flag
bool success = true;
//Load PNG texture
texture = LoadTexture(dir);
if (texture == NULL)
{
printf("Failed to load texture image!\n");
success = false;
}
return success;
}
void Close()
{
//Free loaded image
SDL_DestroyTexture(texture);
texture = NULL;
//Destroy window
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
window = NULL;
renderer = NULL;
//Quit SDL subsystems
IMG_Quit();
SDL_Quit();
}
SDL_Texture* LoadTexture(const char* dir)
{
//The final texture
SDL_Texture* newTexture = NULL;
//Load image at specified path
SDL_Surface* loadedSurface = IMG_Load(dir);
if (loadedSurface == NULL)
{
printf("Unable to load image %s! SDL_image Error: %s\n", dir, IMG_GetError());
}
else
{
//Create texture from surface pixels
newTexture = SDL_CreateTextureFromSurface(renderer, loadedSurface);
if (newTexture == NULL)
{
printf("Unable to create texture from %s! SDL Error: %s\n", dir, SDL_GetError());
}
//Get rid of old loaded surface
SDL_FreeSurface(loadedSurface);
}
return newTexture;
}
int main(int argc, char* args[])
{
SDL_bool done;
SDL_Event event;
char* dropped_filedir;
Init();
const char* tmp = "data/dropfileimage.png";
LoadMedia(tmp);
//SDL_SetWindowOpacity(window, 0.5f);
WindowOpacity = 1.0f;
SDL_EventState(SDL_DROPFILE, SDL_ENABLE);
done = SDL_FALSE;
while (!done)
{
while (!done && SDL_PollEvent(&event))
{
switch (event.type)
{
case (SDL_QUIT):
done = SDL_TRUE;
break;
case (SDL_DROPFILE):
dropped_filedir = event.drop.file;
LoadMedia(dropped_filedir);
SDL_SetWindowResizable(window, SDL_TRUE);
//SDL_QueryTexture(texture, NULL, NULL, &w, &h);
//SDL_SetWindowSize(window, w, h);
SDL_free(dropped_filedir);
break;
case (SDL_MOUSEWHEEL):
if (event.wheel.y > 0) // scroll up
{
if(WindowOpacity < 1.0f)
WindowOpacity += 0.05f;
SDL_SetWindowOpacity(window, WindowOpacity);
}
else if (event.wheel.y < 0) // scroll down
{
if(WindowOpacity > 0.1f)
WindowOpacity -= 0.05f;
SDL_SetWindowOpacity(window, WindowOpacity);
}
break;
case (SDL_KEYDOWN):
if (event.key.keysym.sym == SDLK_ESCAPE)
{
done = SDL_TRUE;
}
else if (event.key.keysym.sym == SDLK_m)
{
SDL_MinimizeWindow(window);
}
else if (event.key.keysym.sym == SDLK_l)
{
LockWindow = !LockWindow;
if (LockWindow)
{
SDL_SetWindowOpacity(window, WindowOpacity);
SDL_SetWindowBordered(window, SDL_FALSE);
}
else
{
SDL_SetWindowOpacity(window, 1.0f);
SDL_SetWindowBordered(window, SDL_TRUE);
}
}
else if (event.key.keysym.sym == SDLK_f)
{
TextureFillWindow = !TextureFillWindow;
}
break;
case SDL_WINDOWEVENT:
switch (event.window.event)
{
case SDL_WINDOWEVENT_ENTER:
break;
case SDL_WINDOWEVENT_LEAVE:
break;
}
break;
default:
break;
}
}
//Clear screen
SDL_RenderClear(renderer);
int w, h;
SDL_QueryTexture(texture, NULL, NULL, &w, &h);
//Render texture to screen
SDL_Rect dstrect = { 0, 0, w, h };
SDL_RenderCopy(renderer, texture, NULL, TextureFillWindow ? &dstrect : NULL);
//Update screen
SDL_RenderPresent(renderer);
}
Close();
return 0;
} | 19.54023 | 171 | 0.663922 | [
"render"
] |
ff5d94f3332cc74a436a9eb5d80d6efd0066ed12 | 2,164 | cpp | C++ | lucida-suite/fd/baseline/surf-fd.cpp | hitokun-s/monalisa | ccb7fbcd294aef02d52c7c22c632d22cc0e9312a | [
"BSD-3-Clause"
] | null | null | null | lucida-suite/fd/baseline/surf-fd.cpp | hitokun-s/monalisa | ccb7fbcd294aef02d52c7c22c632d22cc0e9312a | [
"BSD-3-Clause"
] | null | null | null | lucida-suite/fd/baseline/surf-fd.cpp | hitokun-s/monalisa | ccb7fbcd294aef02d52c7c22c632d22cc0e9312a | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2015, University of Michigan.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
/**
* TODO:
*
* @author: Johann Hauswald
* @contact: jahausw@umich.edu
*/
#include <assert.h>
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
#include <stdio.h>
#include <pthread.h>
#include <time.h>
#include "../../utils/timer.h"
#include "opencv2/core/core.hpp"
#include "opencv2/core/types_c.h"
#include "opencv2/xfeatures2d/nonfree.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/nonfree/gpu.hpp"
#include "opencv2/objdetect/objdetect.hpp"
using namespace cv;
using namespace std;
vector<KeyPoint> keys;
int minHessian = 400;
Ptr<xfeatures2d::SURF> surf = xfeatures2d::SURF::create(minHessian);
int iterations;
vector<KeyPoint> exec_feature(const Mat &img) {
vector<KeyPoint> keypoints;
surf->detect(img, keypoints, Mat());
return keypoints;
}
Mat exec_desc(const Mat &img, vector<KeyPoint> keypoints) {
Mat descriptors;
surf->detectAndCompute(img, Mat(), keypoints, descriptors, true);
return descriptors;
}
int main(int argc, char **argv) {
if (argc < 2) {
fprintf(stderr, "[ERROR] Input file required.\n\n");
fprintf(stderr, "Usage: %s [INPUT FILE]\n\n", argv[0]);
exit(0);
}
cvUseOptimized(1);
// Generate test keys
Mat img = imread(argv[1], CV_LOAD_IMAGE_GRAYSCALE);
if (img.empty()) {
printf("image not found\n");
exit(-1);
}
STATS_INIT("kernel", "feature_description");
PRINT_STAT_STRING("abrv", "fd");
PRINT_STAT_INT("rows", img.rows);
PRINT_STAT_INT("columns", img.cols);
tic();
keys = exec_feature(img);
PRINT_STAT_DOUBLE("fe", toc());
tic();
Mat testDesc = exec_desc(img, keys);
PRINT_STAT_DOUBLE("fd", toc());
STATS_END();
#ifdef TESTING
FILE *f = fopen("../input/surf-fd.baseline", "w");
fprintf(f, "number of descriptors: %d\n", testDesc.size().height);
fclose(f);
#endif
return 0;
}
| 21.64 | 79 | 0.682532 | [
"vector"
] |
ff5f410f11d78c9ba4c5869b7df07b85a9dd4c68 | 2,831 | cpp | C++ | Options.cpp | yoshiikeda/Options-cplusplus | fad727b17b08027be080b3df0df81102b87c4daf | [
"MIT"
] | null | null | null | Options.cpp | yoshiikeda/Options-cplusplus | fad727b17b08027be080b3df0df81102b87c4daf | [
"MIT"
] | null | null | null | Options.cpp | yoshiikeda/Options-cplusplus | fad727b17b08027be080b3df0df81102b87c4daf | [
"MIT"
] | null | null | null | #include <memory>
#include <string>
#include <vector>
#include "Options.h"
Option::Option(std::unique_ptr<const std::string>&& key_,
std::unique_ptr<const std::string>&& value_) noexcept : _key(std::move(key_)),
_value(std::move(value_))
{
// Empty
}
std::unique_ptr<const Option> Option::Create(const char arg_[]) noexcept
{
return Create(std::string(arg_));
}
std::unique_ptr<const Option> Option::Create(const std::string&& arg_) noexcept
{
auto result{std::unique_ptr<const Option>{nullptr}};
if (!arg_.empty())
{
auto key{new std::string{}};
auto value{new std::string{}};
auto valid{true};
std::size_t k{0};
valid = (arg_[k++] == DELIMITER);
if (k < arg_.size() && valid)
{
if (arg_[k] == DELIMITER)
{
++k;
}
else
{
valid = (arg_.size() == 2);
}
while (k < arg_.size() && valid)
{
valid = (arg_[k] != DELIMITER);
if (valid)
{
*key += arg_[k++];
}
}
if (valid)
{
result = std::unique_ptr<const Option>(new Option(std::unique_ptr<const std::string>(key),
std::unique_ptr<const std::string>(value)));
}
}
}
return result;
}
const std::string& Option::Key() const noexcept
{
return *_key;
}
const std::string& Option::Value() const noexcept
{
return *_value;
}
bool Option::Valid() const noexcept
{
return !(_key->empty());
}
void OptionCollection::Parse(const int argc_, const char** argv_)
{
std::vector<std::string> args{};
for (std::size_t k{1}; k < static_cast<std::size_t>(argc_); ++k)
{
args.push_back(std::string(argv_[k]));
}
Parse(std::move(args));
}
void OptionCollection::Parse(const std::vector<std::string>&& args_)
{
bool valid = true;
for (auto&& k{args_.cbegin()}; k != args_.cend() && valid; ++k)
{
auto o{Option::Create(std::move(const_cast<std::string&>(*k)))};
if (o != nullptr && o->Valid())
{
_options.push_back(std::move(o));
}
else
{
valid = false;
}
}
if (!valid)
{
_options.clear();
}
}
std::size_t OptionCollection::Count() const noexcept
{
return _options.size();
}
const Option& OptionCollection::operator [](const std::size_t i_) const
{
return *(_options[i_]);
}
| 22.468254 | 111 | 0.470152 | [
"vector"
] |
ff649c380dffae3055455a582deeb950c682e1b2 | 823 | hpp | C++ | HW3/src/item/ball.hpp | xupei0610/Animation-Planning-in-Games-HW | f66399959127f2a88f174b22302b25e35e1aebb3 | [
"MIT"
] | 4 | 2019-01-23T09:13:33.000Z | 2021-12-03T02:50:01.000Z | HW3/src/item/ball.hpp | xupei0610/Animation-Planning-in-Games-HW | f66399959127f2a88f174b22302b25e35e1aebb3 | [
"MIT"
] | null | null | null | HW3/src/item/ball.hpp | xupei0610/Animation-Planning-in-Games-HW | f66399959127f2a88f174b22302b25e35e1aebb3 | [
"MIT"
] | null | null | null | #ifndef PX_CG_ITEM_BALL_HPP
#define PX_CG_ITEM_BALL_HPP
#include "item.hpp"
namespace px { namespace item
{
class Ball;
} }
class px::item::Ball : public Item
{
private:
static ItemInfo ITEM_INFO;
public:
static Shader *shader;
static void initShader();
static void destroyShader();
public:
struct
{
glm::vec3 ambient;
glm::vec3 diffuse;
glm::vec3 specular;
float shininess;
} color;
static std::shared_ptr<Item> create();
static std::size_t regItem();
bool postRender() const override { return true; }
void init() override;
void render() override;
Ball(glm::vec3 const &pos = glm::vec3(0.f),
float radius = 1.f);
~Ball() override;
protected:
unsigned int vao[1], vbo[2];
private:
int _n_indices;
};
#endif
| 16.795918 | 53 | 0.63305 | [
"render"
] |
ff6875603438ff2d532c73faaa47e209527f0e3d | 1,551 | cc | C++ | Random Codes/trappingRainWater.cc | ChakreshSinghUC/CPPCodes | d82a3f467303566afbfcc927b660b0f7bf7c0432 | [
"MIT"
] | null | null | null | Random Codes/trappingRainWater.cc | ChakreshSinghUC/CPPCodes | d82a3f467303566afbfcc927b660b0f7bf7c0432 | [
"MIT"
] | null | null | null | Random Codes/trappingRainWater.cc | ChakreshSinghUC/CPPCodes | d82a3f467303566afbfcc927b660b0f7bf7c0432 | [
"MIT"
] | null | null | null | /*
Given n non-negative integers representing an elevation map where the width of
each bar is 1, compute how much water it is able to trap after raining.
For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.
*/
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
// int result = 0;
// int len = height.size();
// if (len <= 2)
// return 0;
// int l = 0;
// int w = 1;
// bool leftwall = false;
// int temp = 0;
// while (l + w <= len - 1) {
// while (height[l + w] < height[l] && l + w <= len - 1) {
// temp += height[l + w];
// w++;
// if (l + w > len - 1 && w > 1) {
// w = 1;
// temp = 0;
// l++;
// leftwall = true;
// }
// }
// if (leftwall) {
// result += (max(height[l], height[l + w]) * w) - temp -
// (min(height[l], height[l + w]));
// } else
// result += (min(height[l], height[l + w]) * (w - 1)) - temp;
// leftwall = false;
// l = l + w;
// w = 1;
// temp = 0;
// }
// return result;
// }
int trap(vector<int>& height) {
int l = 0, r = height.size()-1, level = 0, water = 0;
while (l < r) {
int lower = height[height[l] < height[r] ? l++ : r--];
level = max(level, lower);
water += level - lower;
}
return water;
}
};
int main() {
vector<int> height = {4, 2, 3}; //{0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};
Solution obj;
cout << obj.trap(height);
}
| 23.149254 | 78 | 0.448743 | [
"vector"
] |
ff696beb79bda38345227e158960b14e2999ed2d | 1,406 | cc | C++ | chrome/browser/ui/android/tab_model/tab_model_observer.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | chrome/browser/ui/android/tab_model/tab_model_observer.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | chrome/browser/ui/android/tab_model/tab_model_observer.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2018 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 "chrome/browser/ui/android/tab_model/tab_model_observer.h"
#include "chrome/browser/android/tab_android.h"
TabModelObserver::TabModelObserver() {}
TabModelObserver::~TabModelObserver() {}
void TabModelObserver::DidSelectTab(TabAndroid* tab,
TabModel::TabSelectionType type) {}
void TabModelObserver::WillCloseTab(TabAndroid* tab, bool animate) {}
void TabModelObserver::DidCloseTab(int tab_id, bool incognito) {}
void TabModelObserver::WillAddTab(TabAndroid* tab,
TabModel::TabLaunchType type) {}
void TabModelObserver::DidAddTab(TabAndroid* tab,
TabModel::TabLaunchType type) {}
void TabModelObserver::DidMoveTab(TabAndroid* tab,
int new_index,
int old_index) {}
void TabModelObserver::TabPendingClosure(TabAndroid* tab) {}
void TabModelObserver::TabClosureUndone(TabAndroid* tab) {}
void TabModelObserver::TabClosureCommitted(TabAndroid* tab) {}
void TabModelObserver::AllTabsPendingClosure(
const std::vector<TabAndroid*>& tabs) {}
void TabModelObserver::AllTabsClosureCommitted() {}
void TabModelObserver::TabRemoved(TabAndroid* tab) {}
| 33.47619 | 73 | 0.693457 | [
"vector"
] |
ff78f2aadfb031c0f397742b0e4a6163fab570de | 6,415 | hpp | C++ | cpp/include/cudf/detail/stream_compaction.hpp | wbo4958/cudf | b12f24d25815145a573a9d70f8c6140a8ab9d2cb | [
"Apache-2.0"
] | null | null | null | cpp/include/cudf/detail/stream_compaction.hpp | wbo4958/cudf | b12f24d25815145a573a9d70f8c6140a8ab9d2cb | [
"Apache-2.0"
] | null | null | null | cpp/include/cudf/detail/stream_compaction.hpp | wbo4958/cudf | b12f24d25815145a573a9d70f8c6140a8ab9d2cb | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2019, NVIDIA 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.
*/
#pragma once
#include <cudf/column/column_view.hpp>
#include <cudf/stream_compaction.hpp>
#include <cudf/types.hpp>
namespace cudf {
namespace experimental {
namespace detail {
/**
* @brief Filters a table to remove null elements.
*
* Filters the rows of the `input` considering specified columns indicated in
* `keys` for validity / null values.
*
* Given an input table_view, row `i` from the input columns is copied to
* the output if the same row `i` of @p keys has at least @p keep_threshold
* non-null fields.
*
* This operation is stable: the input order is preserved in the output.
*
* Any non-nullable column in the input is treated as all non-null.
*
* @code{.pseudo}
* input {col1: {1, 2, 3, null},
* col2: {4, 5, null, null},
* col3: {7, null, null, null}}
* keys = {0, 1, 2} // All columns
* keep_threshold = 2
*
* output {col1: {1, 2}
* col2: {4, 5}
* col3: {7, null}}
* @endcode
*
* @note if @p input.num_rows() is zero, or @p keys is empty or has no nulls,
* there is no error, and an empty `table` is returned
*
* @param[in] input The input `table_view` to filter.
* @param[in] keys vector of indices representing key columns from `input`
* @param[in] keep_threshold The minimum number of non-null fields in a row
* required to keep the row.
* @param[in] mr Optional, The resource to use for all allocations
* @param[in] stream Optional CUDA stream on which to execute kernels
* @return unique_ptr<table> Table containing all rows of the `input` with at least @p
* keep_threshold non-null fields in @p keys.
*/
std::unique_ptr<experimental::table> drop_nulls(
table_view const& input,
std::vector<size_type> const& keys,
cudf::size_type keep_threshold,
rmm::mr::device_memory_resource* mr = rmm::mr::get_default_resource(),
cudaStream_t stream = 0);
/**
* @brief Filters `input` using `boolean_mask` of boolean values as a mask.
*
* Given an input `table_view` and a mask `column_view`, an element `i` from
* each column_view of the `input` is copied to the corresponding output column
* if the corresponding element `i` in the mask is non-null and `true`.
* This operation is stable: the input order is preserved.
*
* @note if @p input.num_rows() is zero, there is no error, and an empty table
* is returned.
*
* @throws cudf::logic_error if The `input` size and `boolean_mask` size mismatches.
* @throws cudf::logic_error if `boolean_mask` is not `BOOL8` type.
*
* @param[in] input The input table_view to filter
* @param[in] boolean_mask A nullable column_view of type BOOL8 used as
* a mask to filter the `input`.
* @param[in] mr Optional, The resource to use for all allocations
* @param[in] stream Optional CUDA stream on which to execute kernels
* @return unique_ptr<table> Table containing copy of all rows of @p input passing
* the filter defined by @p boolean_mask.
*/
std::unique_ptr<experimental::table> apply_boolean_mask(
table_view const& input,
column_view const& boolean_mask,
rmm::mr::device_memory_resource* mr = rmm::mr::get_default_resource(),
cudaStream_t stream = 0);
/**
* @brief Create a new table without duplicate rows
*
* Given an `input` table_view, each row is copied to output table if the corresponding
* row of `keys` columns is unique, where the definition of unique depends on the value of @p keep:
* - KEEP_FIRST: only the first of a sequence of duplicate rows is copied
* - KEEP_LAST: only the last of a sequence of duplicate rows is copied
* - KEEP_NONE: only unique rows are kept
*
* @throws cudf::logic_error if The `input` row size mismatches with `keys`.
*
* @param[in] input input table_view to copy only unique rows
* @param[in] keys vector of indices representing key columns from `input`
* @param[in] keep keep first entry, last entry, or no entries if duplicates found
* @param[in] nulls_equal flag to denote nulls are equal if null_equality::EQUAL,
* nulls are not equal if null_equality::UNEQUAL
* @param[in] mr Optional, The resource to use for allocation of returned table
* @param[in] stream Optional CUDA stream on which to execute kernels
*
* @return unique_ptr<table> Table with unique rows as per specified `keep`.
*/
std::unique_ptr<experimental::table> drop_duplicates(
table_view const& input,
std::vector<size_type> const& keys,
duplicate_keep_option keep,
null_equality nulls_equal = null_equality::EQUAL,
rmm::mr::device_memory_resource* mr = rmm::mr::get_default_resource(),
cudaStream_t stream = 0);
/**
* @brief Count the unique elements in the column_view
*
* Given an input column_view, number of unique elements in this column_view is returned
*
* If `null_handling` is null_policy::EXCLUDE and `nan_handling` is nan_policy::NAN_IS_NULL, both
* `NaN` and `null` values are ignored. If `null_handling` is null_policy::EXCLUDE and
* `nan_handling` is nan_policy::NAN_IS_VALID, only `null` is ignored, `NaN` is considered in unique
* count.
*
* @param[in] input The column_view whose unique elements will be counted.
* @param[in] null_handling flag to include or ignore `null` while counting
* @param[in] nan_handling flag to consider `NaN==null` or not.
* @param[in] stream Optional CUDA stream on which to execute kernels
*
* @return number of unique elements
*/
cudf::size_type unique_count(column_view const& input,
null_policy null_handling,
nan_policy nan_handling,
cudaStream_t stream = 0);
} // namespace detail
} // namespace experimental
} // namespace cudf
| 41.928105 | 100 | 0.691972 | [
"vector"
] |
ff7cdea114f1832606c7300f45969205c4410f53 | 1,913 | cpp | C++ | src/main.cpp | Fdhvdu/QuantumCircuit | d79a86c0ebc4a7f839efce7b86c953644c4d6f78 | [
"MIT"
] | null | null | null | src/main.cpp | Fdhvdu/QuantumCircuit | d79a86c0ebc4a7f839efce7b86c953644c4d6f78 | [
"MIT"
] | null | null | null | src/main.cpp | Fdhvdu/QuantumCircuit | d79a86c0ebc4a7f839efce7b86c953644c4d6f78 | [
"MIT"
] | null | null | null | #define USE_THREAD
#include<fstream>
#include<memory> //make_unique
#ifdef USE_THREAD
#include<mutex>
#include<thread> //thread::hardware_concurrency()
#endif
#include<utility> //declval
#include<type_traits> //remove_reference
#include<vector>
#include"../../lib/header/tool/CChrono_timer.hpp"
#include"../../lib/header/tool/show.hpp"
#ifdef USE_THREAD
#include"../../ThreadPool/header/CThreadPool.hpp"
#endif
#include"../header/CQCircuit.hpp"
#include"../header/QCFwd.hpp"
#include"../header/CTsaiAlgorithm.hpp"
namespace
{
std::vector<std::remove_reference<decltype(std::declval<ICircuitAlgorithm>().get())>::type::size_type> accu;
std::ofstream ofs{"output.txt"};
#ifdef USE_THREAD
std::mutex accu_mut;
std::mutex ofs_mut;
#endif
void call_and_output(const Func_t &func)
{
using namespace std;
unique_ptr<ICircuitAlgorithm> algorithm{make_unique<nTsaiAlgorithm::CTsaiAlgorithm>()};
algorithm->setFunc(func);
algorithm->create();
auto size{algorithm->get().size()};
if(size)
size=algorithm->get().front().size();
{
#ifdef USE_THREAD
lock_guard<mutex> lock{ofs_mut};
#endif
nTool::show(func.begin(),func.end(),ofs);
ofs<<"gate : "<<size<<endl<<endl;
}
#ifdef USE_THREAD
lock_guard<mutex> lock{accu_mut};
#endif
if(accu.size()<=size)
accu.resize(size+1);
++accu[size];
}
}
int main()
{
using namespace std;
nTool::CChrono_timer timer;
{
#ifdef USE_THREAD
nThread::CThreadPool tp;
#endif
Func_t func{0,1,2,3,4,5,6,7};
timer.start();
do
#ifdef USE_THREAD
tp.add_and_detach(call_and_output,Func_t(func)); //copy func, not reference
#else
call_and_output(func);
#endif
while(next_permutation(func.begin(),func.end()));
}
timer.stop();
ofs<<timer.duration_minutes()<<"\tminutes"<<endl
<<timer.duration_seconds()%60<<"\tseconds"<<endl
<<timer.duration_milliseconds()%1000<<"\tmilliseconds"<<endl;
nTool::show(accu.begin(),accu.end(),ofs);
} | 25.171053 | 109 | 0.711448 | [
"vector"
] |
ff8a38b8b4c0bfbc6137756ddd76cd15cd11792c | 9,554 | cpp | C++ | jvm-packages/xgboost4j-spark/src/native/xgboost4j_spark.cpp | NVIDIA/spark-xgboost | 983159f52784e3d9dfd8e9957c5f8ca18e64f934 | [
"Apache-2.0"
] | 15 | 2020-06-11T02:20:26.000Z | 2022-03-09T07:18:23.000Z | jvm-packages/xgboost4j-spark/src/native/xgboost4j_spark.cpp | NVIDIA/spark-xgboost | 983159f52784e3d9dfd8e9957c5f8ca18e64f934 | [
"Apache-2.0"
] | 4 | 2021-01-20T03:24:23.000Z | 2021-11-01T05:33:38.000Z | jvm-packages/xgboost4j-spark/src/native/xgboost4j_spark.cpp | NVIDIA/spark-xgboost | 983159f52784e3d9dfd8e9957c5f8ca18e64f934 | [
"Apache-2.0"
] | 6 | 2020-06-24T03:28:58.000Z | 2021-10-01T16:04:11.000Z | /*
* Copyright (c) 2019, NVIDIA 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 <cstddef>
#include <cstdint>
#include <stdexcept>
#include <stdlib.h>
#include <string>
#include <vector>
#include <memory>
#include <iostream>
#include <cuda_runtime.h>
#include "xgboost4j_spark_gpu.h"
#include "xgboost4j_spark.h"
#if defined(XGBOOST_USE_RMM) && XGBOOST_USE_RMM == 1
#include "rmm/mr/device/per_device_resource.hpp"
#include "rmm/mr/device/thrust_allocator_adaptor.hpp"
#include "rmm/device_buffer.hpp"
#endif // defined(XGBOOST_USE_RMM) && XGBOOST_USE_RMM == 1
struct gpu_column_data {
long* data_ptr;
long* valid_ptr;
int dtype_size_in_bytes;
long num_row;
};
namespace xgboost {
namespace spark {
/*! \brief utility class to track GPU allocations */
class unique_gpu_ptr {
void* ptr;
const size_t size;
public:
unique_gpu_ptr(unique_gpu_ptr const&) = delete;
unique_gpu_ptr& operator=(unique_gpu_ptr const&) = delete;
unique_gpu_ptr(unique_gpu_ptr&& other) noexcept : ptr(other.ptr), size(other.size) {
other.ptr = nullptr;
}
unique_gpu_ptr(size_t _size) : ptr(nullptr), size(_size) {
#if defined(XGBOOST_USE_RMM) && XGBOOST_USE_RMM == 1
rmm::mr::device_memory_resource *mr = rmm::mr::get_current_device_resource();
try {
ptr = mr->allocate(_size);
} catch (rmm::bad_alloc const& e) {
auto what = std::string("Could not allocate memory from RMM: ") +
(e.what() == nullptr ? "" : e.what());
std::cerr << what << std::endl;
throw std::bad_alloc();
}
#else
cudaError_t status = cudaMalloc(&ptr, _size);
if (status != cudaSuccess) {
throw std::bad_alloc();
}
#endif
}
~unique_gpu_ptr() {
if (ptr != nullptr) {
#if defined(XGBOOST_USE_RMM) && XGBOOST_USE_RMM == 1
rmm::mr::device_memory_resource *mr = rmm::mr::get_current_device_resource();
mr->deallocate(ptr, size);
#else
cudaFree(ptr);
#endif
}
}
void* get() {
return ptr;
}
void* release() {
void* result = ptr;
ptr = nullptr;
return result;
}
};
/*! \brief custom deleter to free malloc allocations */
struct malloc_deleter {
void operator()(void* ptr) const {
free(ptr);
}
};
static unsigned int get_unsaferow_nullset_size(unsigned int num_columns) {
// The nullset size is rounded up to a multiple of 8 bytes.
return ((num_columns + 63) / 64) * 8;
}
static void build_unsafe_row_nullsets(void* unsafe_rows_dptr,
std::vector<gpu_column_data *> const& gdfcols) {
unsigned int num_columns = gdfcols.size();
size_t num_rows = gdfcols[0]->num_row;
// make the array of validity data pointers available on the device
std::vector<uint32_t const*> valid_ptrs(num_columns);
for (int i = 0; i < num_columns; ++i) {
valid_ptrs[i] = reinterpret_cast<const unsigned int *>(gdfcols[i]->valid_ptr);
}
unique_gpu_ptr dev_valid_mem(num_columns * sizeof(*valid_ptrs.data()));
uint32_t** dev_valid_ptrs = reinterpret_cast<uint32_t**>(dev_valid_mem.get());
cudaError_t cuda_status = cudaMemcpy(dev_valid_ptrs, valid_ptrs.data(),
num_columns * sizeof(valid_ptrs[0]), cudaMemcpyHostToDevice);
if (cuda_status != cudaSuccess) {
throw std::runtime_error(cudaGetErrorString(cuda_status));
}
// build the nullsets for each UnsafeRow
cuda_status = xgboost::spark::build_unsaferow_nullsets(
reinterpret_cast<uint64_t*>(unsafe_rows_dptr), dev_valid_ptrs,
num_columns, num_rows);
if (cuda_status != cudaSuccess) {
throw std::runtime_error(cudaGetErrorString(cuda_status));
}
}
/*!
* \brief Transforms a set of cudf columns into an array of Spark UnsafeRow.
* NOTE: Only fixed-length datatypes are supported, as it is assumed
* that every UnsafeRow has the same size.
*
* Spark's UnsafeRow with fixed-length datatypes has the following format:
* null bitset, 8-byte value, [8-byte value, ...]
* where the null bitset is a collection of 64-bit words with each bit
* indicating whether the corresponding field is null.
*/
void* build_unsafe_rows(std::vector<gpu_column_data *> const& gdfcols) {
cudaError_t cuda_status;
unsigned int num_columns = gdfcols.size();
size_t num_rows = gdfcols[0]->num_row;
unsigned int nullset_size = get_unsaferow_nullset_size(num_columns);
unsigned int row_size = nullset_size + num_columns * 8;
size_t unsafe_rows_size = num_rows * row_size;
// allocate GPU memory to hold the resulting UnsafeRow array
unique_gpu_ptr unsafe_rows_devmem(unsafe_rows_size);
uint8_t* unsafe_rows_dptr = static_cast<uint8_t*>(unsafe_rows_devmem.get());
// write each column to the corresponding position in the unsafe rows
for (int i = 0; i < num_columns; ++i) {
// point to the corresponding field in the first UnsafeRow
uint8_t* dest_addr = unsafe_rows_dptr + nullset_size + i * 8;
int dtype_size = gdfcols[i]->dtype_size_in_bytes;
if (dtype_size <= 0) {
throw std::runtime_error("Unsupported column type");
}
cuda_status = xgboost::spark::store_with_stride_async(dest_addr,
gdfcols[i]->data_ptr, num_rows, dtype_size, row_size, 0);
if (cuda_status != cudaSuccess) {
throw std::runtime_error(cudaGetErrorString(cuda_status));
}
}
build_unsafe_row_nullsets(unsafe_rows_dptr, gdfcols);
// copy UnsafeRow results back to host
std::unique_ptr<void, malloc_deleter> unsafe_rows(malloc(unsafe_rows_size));
if (unsafe_rows.get() == nullptr) {
throw std::bad_alloc();
}
// This copy also serves as a synchronization point with the GPU.
cuda_status = cudaMemcpy(unsafe_rows.get(), unsafe_rows_dptr,
unsafe_rows_size, cudaMemcpyDeviceToHost);
if (cuda_status != cudaSuccess) {
throw std::runtime_error(cudaGetErrorString(cuda_status));
}
return unsafe_rows.release();
}
} // namespace spark
} // namespace xgboost
static void throw_java_exception(JNIEnv* env, char const* classname,
char const* msg) {
jclass exClass = env->FindClass(classname);
if (exClass != NULL) {
env->ThrowNew(exClass, msg);
}
}
static void throw_java_exception(JNIEnv* env, char const* msg) {
throw_java_exception(env, "java/lang/RuntimeException", msg);
}
JNIEXPORT jlong JNICALL
Java_ml_dmlc_xgboost4j_java_XGBoostSparkJNI_buildUnsafeRows(JNIEnv * env,
jclass clazz, jlongArray dataPtrs, jlongArray validPtrs, jintArray dTypePtrs, jlong numRows) {
// FIXME, Do we need to check if the size of dataPtrs/validPtrs/dTypePtrs should be same
int num_columns = env->GetArrayLength(dataPtrs);
if (env->ExceptionOccurred()) {
return 0;
}
if (num_columns <= 0) {
throw_java_exception(env, "Invalid number of columns");
return 0;
}
std::vector<gpu_column_data *> gpu_cols;
jlong* data_jlongs = env->GetLongArrayElements(dataPtrs, nullptr);
if (data_jlongs == nullptr) {
throw_java_exception(env, "Failed to get data handles");
return 0;
}
jlong* valid_jlongs = env->GetLongArrayElements(validPtrs, nullptr);
if (valid_jlongs == nullptr) {
throw_java_exception(env, "Failed to get valid handles");
return 0;
}
jint* dtype_jints = env->GetIntArrayElements(dTypePtrs, nullptr);
if (dtype_jints == nullptr) {
throw_java_exception(env, "Failed to get data type sizes");
return 0;
}
for (int i = 0; i < num_columns; ++i) {
gpu_column_data* tmp_column = new gpu_column_data;
tmp_column->data_ptr = reinterpret_cast<long * > (data_jlongs[i]);
tmp_column->valid_ptr = reinterpret_cast<long * > (valid_jlongs[i]);
tmp_column->dtype_size_in_bytes = dtype_jints[i];
tmp_column->num_row = numRows;
gpu_cols.push_back(tmp_column);
}
env->ReleaseLongArrayElements(dataPtrs, data_jlongs, JNI_ABORT);
env->ReleaseLongArrayElements(validPtrs, valid_jlongs, JNI_ABORT);
env->ReleaseIntArrayElements(dTypePtrs, dtype_jints, JNI_ABORT);
void* unsafe_rows = nullptr;
try {
unsafe_rows = xgboost::spark::build_unsafe_rows(gpu_cols);
} catch (std::bad_alloc const& e) {
throw_java_exception(env, "java/lang/OutOfMemoryError",
"Could not allocate native memory");
} catch (std::exception const& e) {
throw_java_exception(env, e.what());
}
for (int i = 0; i < num_columns; i++) {
delete (gpu_cols[i]);
}
gpu_cols.clear();
return reinterpret_cast<jlong>(unsafe_rows);
}
JNIEXPORT jint JNICALL
Java_ml_dmlc_xgboost4j_java_XGBoostSparkJNI_getGpuDevice(JNIEnv * env,
jclass clazz) {
int device_ordinal;
cudaGetDevice(&device_ordinal);
return device_ordinal;
}
JNIEXPORT jint JNICALL
Java_ml_dmlc_xgboost4j_java_XGBoostSparkJNI_allocateGpuDevice(JNIEnv * env,
jclass clazz, jint gpu_id) {
cudaError_t error = cudaSetDevice(gpu_id);
if (error != cudaSuccess) {
throw_java_exception(env, "Error running cudaSetDevice");
}
// initialize a context
error = cudaFree(0);
if (error != cudaSuccess) {
throw_java_exception(env, "Error running cudaFree");
}
return 0;
}
| 32.496599 | 100 | 0.706615 | [
"vector"
] |
ff8b2ff69fba2ccd92218509390f7f2864f18ab5 | 3,725 | cpp | C++ | unreal/src/Material.cpp | ChaosPaladin/l2mapconv-public | 3d2c8074b0e6a9541dfdc55360bc7958f628cc39 | [
"MIT"
] | 42 | 2020-10-31T12:44:52.000Z | 2022-03-06T08:27:24.000Z | unreal/src/Material.cpp | ChaosPaladin/l2mapconv-public | 3d2c8074b0e6a9541dfdc55360bc7958f628cc39 | [
"MIT"
] | 10 | 2020-11-19T00:06:24.000Z | 2021-12-20T18:54:47.000Z | unreal/src/Material.cpp | ChaosPaladin/l2mapconv-public | 3d2c8074b0e6a9541dfdc55360bc7958f628cc39 | [
"MIT"
] | 28 | 2020-09-21T12:59:13.000Z | 2022-03-12T04:53:37.000Z | #include "pch.h"
#include <unreal/Material.h>
#include "MaterialDeserializer.h"
namespace unreal {
auto Modifier::set_property(const Property &property) -> bool {
if (Material::set_property(property)) {
return true;
}
if (property.name == "Material") {
material.from_property(property, archive);
return true;
}
return false;
}
auto FinalBlend::set_property(const Property &property) -> bool {
if (Modifier::set_property(property)) {
return true;
}
if (property.name == "FrameBufferBlending") {
fb_blending = static_cast<FrameBufferBlending>(property.uint8_t_value);
return true;
}
if (property.name == "ZWrite") {
z_write = property.bool_value();
return true;
}
if (property.name == "ZTest") {
z_test = property.bool_value();
return true;
}
if (property.name == "AlphaTest") {
alpha_test = property.bool_value();
return true;
}
if (property.name == "TwoSided") {
two_sided = property.bool_value();
return true;
}
if (property.name == "AlphaRef") {
alpha_ref = property.uint8_t_value;
return true;
}
if (property.name == "TreatAsTwoSided") {
treat_as_two_sided = property.bool_value();
return true;
}
return false;
}
auto BitmapMaterial::set_property(const Property &property) -> bool {
if (RenderedMaterial::set_property(property)) {
return true;
}
if (property.name == "Format") {
format = static_cast<TextureFormat>(property.uint8_t_value);
return true;
}
if (property.name == "UBits") {
u_bits = property.uint8_t_value;
return true;
}
if (property.name == "VBits") {
v_bits = property.uint8_t_value;
return true;
}
if (property.name == "USize") {
u_size = property.int32_t_value;
return true;
}
if (property.name == "VSize") {
v_size = property.int32_t_value;
return true;
}
if (property.name == "UClamp") {
u_clamp = property.int32_t_value;
return true;
}
if (property.name == "VClamp") {
v_clamp = property.int32_t_value;
return true;
}
return false;
}
void Palette::deserialize() {
Object::deserialize();
archive >> colors;
}
auto operator>>(Archive &archive, Mipmap &mipmap) -> Archive & {
archive >> mipmap.unknown >> mipmap.data >> mipmap.u_size >> mipmap.v_size >>
mipmap.u_bits >> mipmap.v_bits;
return archive;
}
void Texture::deserialize() {
BitmapMaterial::deserialize();
MaterialDeserializer deserializer;
deserializer.deserialize(archive);
archive >> mips;
}
auto Texture::set_property(const Property &property) -> bool {
if (BitmapMaterial::set_property(property)) {
return true;
}
if (property.name == "bAlphaTexture") {
alpha_texture = property.bool_value();
return true;
}
if (property.name == "bTwoSided") {
two_sided = property.bool_value();
return true;
}
return false;
}
auto Shader::set_property(const Property &property) -> bool {
if (RenderedMaterial::set_property(property)) {
return true;
}
if (property.name == "Diffuse") {
diffuse.from_property(property, archive);
return true;
}
if (property.name == "OutputBlending") {
output_blending = static_cast<OutputBlending>(property.uint8_t_value);
return true;
}
if (property.name == "AlphaTest") {
alpha_test = property.bool_value();
return true;
}
if (property.name == "AlphaRef") {
alpha_ref = property.uint8_t_value;
return true;
}
if (property.name == "TreatAsTwoSided") {
treat_as_two_sided = property.bool_value();
return true;
}
if (property.name == "TwoSided") {
two_sided = property.bool_value();
return true;
}
return false;
}
} // namespace unreal
| 20.135135 | 79 | 0.653691 | [
"object"
] |
ff8ee4444d96407744c2e5b093cf05a0456d6303 | 14,575 | cpp | C++ | mzgaf2paf.cpp | glennhickey/mzgaf2paf | 06eaa932bf44c7017b4c56775af9dbf801fb3405 | [
"MIT"
] | null | null | null | mzgaf2paf.cpp | glennhickey/mzgaf2paf | 06eaa932bf44c7017b4c56775af9dbf801fb3405 | [
"MIT"
] | 2 | 2021-07-23T14:46:48.000Z | 2022-03-24T12:47:19.000Z | mzgaf2paf.cpp | glennhickey/mzgaf2paf | 06eaa932bf44c7017b4c56775af9dbf801fb3405 | [
"MIT"
] | null | null | null | /**
* mzgaf2paf.hpp: Make base level pairwise alignemnts from minigraph --write-mz output with the object of using them as
* anchors for other graph methods
*/
#include "mzgaf2paf.hpp"
#include "mzgaf.hpp"
#include <limits>
//#define debug
using namespace gafkluge;
using namespace std;
struct MatchBlock {
int64_t query_start;
int64_t query_end;
int64_t target_start;
int64_t target_end; // could just store length instead of ends, but use to sanity check
};
size_t mzgaf2paf(const MzGafRecord& gaf_record,
const GafRecord& parent_record,
ostream& paf_stream,
int64_t min_gap,
int64_t min_match_length,
MZMap& mz_map,
double universal_filter,
QueryCoverage& query_coverage,
int64_t min_overlap_len,
const string& target_prefix) {
// paf coordinates are always on forward strand. but the mz output coordinates for the target
// can apparently be on the reverse strand, so we flip them as needed
int64_t paf_target_start = gaf_record.target_start;
int64_t paf_target_end = gaf_record.target_end;
if (gaf_record.is_reverse) {
paf_target_start = gaf_record.target_length - gaf_record.target_end;
paf_target_end = gaf_record.target_length - gaf_record.target_start;
}
assert(gaf_record.target_mz_offsets.size() == gaf_record.query_mz_offsets.size());
// if we have a mz map, determine the acceptable count for each minimzer to consider "universal"
MZCount* mz_counts = nullptr;
if (universal_filter > 0) {
auto it = mz_map.find(gaf_record.target_name);
assert(it != mz_map.end());
mz_counts = &it->second;
}
TwoBitVec* cov_vec = min_overlap_len > 0 ? &query_coverage[parent_record.query_name] : nullptr;
if (cov_vec && cov_vec->size() == 0) {
assert(parent_record.block_length < min_overlap_len);
cov_vec = nullptr;
}
// turn the offsets vectors into match blocks, applying gap and inconsistency filters
// positions as we move along (relative to gaf_record.query/target_starts)
int64_t query_pos = 0;
int64_t target_pos = 0;
// cigar matches
vector<MatchBlock> matches;
matches.reserve(gaf_record.num_minimizers);
for (size_t i = 0; i < gaf_record.num_minimizers; ++i) {
MatchBlock match = {query_pos, query_pos + gaf_record.kmer_size,
target_pos, target_pos + gaf_record.kmer_size};
// optional universal check
bool universal = true;
if (mz_counts != nullptr) {
// index on forward strand
int64_t mz_idx = !gaf_record.is_reverse ? gaf_record.target_start + target_pos :
gaf_record.target_length - gaf_record.target_start - target_pos - gaf_record.kmer_size;
assert(universal == 1 || (mz_counts->at(mz_idx).first > 0 && mz_counts->at(mz_idx).second > 0));
// proportion of mapped sequences that have this exact minimizer
// todo: this is sample-unaware. so if two sequences in a given sample have this
// minimizer, it's okay as far as the filter's concerned.
// update: this is sample-aware if the samples are different files and u==1
// by way of lowering the numerator in the combine_mz funciton below
float mz_frac = (float)mz_counts->at(mz_idx).first / (float)mz_counts->at(mz_idx).second;
// mz_frac can be > 1 due to 0-offsets in the minigraph mz lists.
universal = mz_frac >= universal_filter && mz_frac <= 1.;
}
// optional mz_overlap check: filter out minimizer if in query region covered more than once,
// or if the query region is covered once and we're too small
if (cov_vec != nullptr) {
// todo: this is all pretty slow (borrowing the per-base code of universal filter)
// may have to switch to interval queries at scale
for (int64_t i = match.query_start; i < match.query_end && universal; ++i) {
size_t coverage = cov_vec->get(gaf_record.query_start + i);
if (coverage > 1 || (coverage == 1 && parent_record.block_length < min_overlap_len)) {
// we hijack the unversal flag, as the filters have the same effect
universal = false;
}
}
}
if (matches.empty()) {
if (universal) {
matches.push_back(match);
}
} else {
// compute the overlap with the previous minimizer
int64_t query_delta = match.query_start - matches.back().query_end;
int64_t target_delta = match.target_start - matches.back().target_end;
if (query_delta == target_delta && query_delta <= 0) {
// extend adjacent minimizers (todo: do we want to always do this or control with option?)
if (universal) {
matches.back().query_end = match.query_end;
matches.back().target_end = match.target_end;
}
} else if (query_delta < 0 || target_delta < 0) {
// drop inconsistent minimizers
// todo: do we want to accept universal minimizers even if inconsistent with non-universal minimizers
// which we'd drop?
matches.pop_back();
} else if (query_delta >= min_gap && target_delta >= min_gap) {
// add if passes gap filter
if (universal) {
// apply length filter
if (min_match_length > 0 && !matches.empty() && matches.back().query_end - matches.back().query_start < min_match_length) {
matches.pop_back();
}
matches.push_back(match);
}
}
}
// advance our position
if (i < gaf_record.num_minimizers - 1) {
query_pos += gaf_record.query_mz_offsets[i];
target_pos += gaf_record.target_mz_offsets[i];
}
}
// apply length filter
if (min_match_length > 0 && !matches.empty() && matches.back().query_end - matches.back().query_start < min_match_length) {
matches.pop_back();
}
// turn our matches into cigar (todo: go straight to string!)
vector<string> cigar;
cigar.reserve(matches.size() * 3 + 2);
// need for output
int64_t total_matches = 0;
// used for sanity checks
int64_t total_deletions = 0;
int64_t total_insertions = 0;
// don't allow cigars to start on indel, as sometimes they can really inflate block
// lengths (big softclips can come when hardmasking centromeres going into minigraph)
int64_t leading_insertions = 0;
int64_t leading_deletions = 0;
if (!matches.empty() && matches[0].query_start > 0) {
total_insertions += matches[0].query_start;
leading_insertions = matches[0].query_start;
}
if (!matches.empty() && matches[0].target_start > 0) {
total_deletions += matches[0].target_start;
leading_deletions = matches[0].target_start;
}
for (size_t i = 0; i < matches.size(); ++i) {
// match
int64_t match_size = matches[i].query_end - matches[i].query_start;
assert(match_size == matches[i].target_end - matches[i].target_start);
cigar.push_back(std::to_string(match_size) + "M");
total_matches += match_size;
if (i < matches.size() - 1) {
// insertion before next match
int64_t insertion_size = matches[i+1].query_start - matches[i].query_end;
assert(insertion_size >= min_gap);
cigar.push_back(std::to_string(insertion_size) + "I");
total_insertions += insertion_size;
// deletion before next match
int64_t deletion_size = matches[i+1].target_start - matches[i].target_end;
assert(deletion_size >= min_gap);
cigar.push_back(std::to_string(deletion_size) + "D");
total_deletions += deletion_size;
}
}
// don't allow cigars to end on indel, as sometimes they can really inflate block
// lengths (big softclips can come when hardmasking centromeres going into minigraph)
int64_t query_length = gaf_record.query_end - gaf_record.query_start;
int64_t leftover_insertions = query_length - (total_insertions + total_matches);
if (leftover_insertions) {
assert(matches.empty() || matches.back().query_end + leftover_insertions == query_length);
}
int64_t target_length = gaf_record.target_end - gaf_record.target_start;
int64_t leftover_deletions = target_length - (total_deletions + total_matches);
if (leftover_deletions) {
assert(matches.empty() || matches.back().target_end + leftover_deletions == target_length);
}
assert(leftover_insertions >= 0 && leftover_deletions >= 0);
if (gaf_record.is_reverse) {
swap(leading_deletions, leftover_deletions);
}
if (!matches.empty()) {
// output the paf columns
paf_stream << parent_record.query_name << "\t"
<< parent_record.query_length << "\t"
<< (gaf_record.query_start + leading_insertions) << "\t"
<< (gaf_record.query_end - leftover_insertions) << "\t"
<< (gaf_record.is_reverse ? "-" : "+") << "\t"
<< target_prefix << gaf_record.target_name << "\t"
<< gaf_record.target_length << "\t"
<< (paf_target_start + leading_deletions) << "\t"
<< (paf_target_end - leftover_deletions) << "\t"
<< total_matches << "\t"
<< (gaf_record.target_end - gaf_record.target_start - leftover_deletions - leading_deletions) << "\t" // fudged
<< parent_record.mapq << "\t" << "cg:Z:";
// and the cigar
if (gaf_record.is_reverse) {
for (vector<string>::reverse_iterator ci = cigar.rbegin(); ci != cigar.rend(); ++ci) {
paf_stream << *ci;
}
} else {
for (vector<string>::iterator ci = cigar.begin(); ci != cigar.end(); ++ci) {
paf_stream << *ci;
}
}
paf_stream << "\n";
}
return total_matches;
}
// update the counts for one mapping of query to target
void update_mz_map(const gafkluge::MzGafRecord& gaf_record,
const gafkluge::GafRecord& parent_record,
MZMap& mz_map,
int64_t min_mapq,
int64_t min_block_len,
int64_t min_node_len,
bool node_based_universal) {
// find our target in the map
MZCount& mz_counts = mz_map[gaf_record.target_name];
// init the count array
if (mz_counts.empty()) {
mz_counts.resize(gaf_record.target_length, make_pair(0, 0));
}
// increment the mapping counts (regardless of thresholds)
int64_t paf_target_start = gaf_record.target_start;
int64_t paf_target_end = gaf_record.target_end;
if (gaf_record.is_reverse) {
paf_target_start = gaf_record.target_length - gaf_record.target_end;
paf_target_end = gaf_record.target_length - gaf_record.target_start;
}
int64_t range_start = paf_target_start;
int64_t range_end = paf_target_end;
if (node_based_universal) {
// todo: if we want to do things node based, we can use a much simpler structure that stores
// one coutn per node. keeping range just to preserve flexibility for now
range_start = 0;
range_end = gaf_record.target_length;
}
for (int64_t i = range_start; i < range_end; ++i) {
++mz_counts[i].second;
}
// increment each minimzer (if the record passes the thresholds)
if (gaf_record.num_minimizers > 0 &&
parent_record.mapq >= min_mapq &&
(parent_record.query_length <= min_block_len || parent_record.block_length >= min_block_len) &&
gaf_record.target_length >= min_node_len) {
int64_t target_pos = gaf_record.target_start;
for (size_t i = 0; i < gaf_record.num_minimizers; ++i) {
int64_t mz_idx = !gaf_record.is_reverse ? target_pos :
gaf_record.target_length - target_pos - gaf_record.kmer_size;
// note, mz_counts.first can be higher than .second because 0-offsets are apparently a thing in the
// minigraph output
++mz_counts[mz_idx].first;
#ifdef debug
cerr << (gaf_record.is_reverse ? "r" : "f") << "-increment i= " << i << " mzi=" << mz_idx << " to="
<< mz_counts[mz_idx].first << "," << mz_counts[mz_idx].second << endl;
#endif
// advance our position
if (i < gaf_record.num_minimizers - 1) {
target_pos += gaf_record.target_mz_offsets[i];
}
}
}
}
void combine_mz_maps(MZMap& map1, MZMap& map2, bool reset_multiple_counts_to_0) {
for (auto& kv : map1) {
MZCount& mz_counts1 = kv.second;
MZCount& mz_counts2 = map2[kv.first];
// init the count array
if (mz_counts2.empty() && !mz_counts1.empty()) {
mz_counts2.resize(mz_counts1.size());
}
// add the counts
for (int64_t i = 0; i < mz_counts1.size(); ++i) {
mz_counts2[i].first += mz_counts1[i].first;
mz_counts2[i].second += mz_counts1[i].second;
if (reset_multiple_counts_to_0 && (mz_counts1[i].first > 1 || mz_counts1[i].second > 1)) {
// this minimizer was covered or was present more than once in the current GAF file
// we set its hits to 0 (if reset_multple flag is set)
mz_counts2[i].first = 0;
}
}
// remove from map1 to keep memory down
mz_counts1.clear();
}
}
void update_query_coverage(const gafkluge::GafRecord& parent_record,
QueryCoverage& query_coverage) {
TwoBitVec& cov_vec = query_coverage[parent_record.query_name];
if (cov_vec.size() == 0) {
cov_vec.resize(parent_record.query_length);
}
bool check = false;
for (size_t i = parent_record.query_start; i < parent_record.query_end; ++i) {
cov_vec.increment(i);
}
}
| 42.246377 | 143 | 0.604871 | [
"object",
"vector"
] |
ff95a444cc5b52d1b3ca2002adcc12b5bdc1e28f | 5,702 | cpp | C++ | examples/code/blend_modes/blend_modes.cpp | brucelevis/pmtech | 927c763224699d685e08761bedeaed38f41f7027 | [
"MIT"
] | null | null | null | examples/code/blend_modes/blend_modes.cpp | brucelevis/pmtech | 927c763224699d685e08761bedeaed38f41f7027 | [
"MIT"
] | null | null | null | examples/code/blend_modes/blend_modes.cpp | brucelevis/pmtech | 927c763224699d685e08761bedeaed38f41f7027 | [
"MIT"
] | null | null | null | #include "camera.h"
#include "debug_render.h"
#include "dev_ui.h"
#include "ecs/ecs_editor.h"
#include "ecs/ecs_resources.h"
#include "ecs/ecs_scene.h"
#include "ecs/ecs_utilities.h"
#include "loader.h"
#include "pmfx.h"
#include "pen.h"
#include "pen_json.h"
#include "pen_string.h"
#include "renderer.h"
#include "str_utilities.h"
#include "timer.h"
#include "file_system.h"
#include "hash.h"
#include "input.h"
using namespace pen;
using namespace put;
using namespace ecs;
namespace
{
void* user_setup(void* params);
loop_t user_update();
void user_shutdown();
}
namespace physics
{
extern void* physics_thread_main(void* params);
}
namespace pen
{
pen_creation_params pen_entry(int argc, char** argv)
{
pen::pen_creation_params p;
p.window_width = 1280;
p.window_height = 720;
p.window_title = "blend_modes";
p.window_sample_count = 4;
p.user_thread_function = user_setup;
p.flags = pen::e_pen_create_flags::renderer;
return p;
}
} // namespace pen
namespace
{
pen::job_thread_params* job_params;
pen::job* p_thread_info;
void blend_mode_ui()
{
bool opened = true;
ImGui::Begin("Blend Modes", &opened, ImGuiWindowFlags_AlwaysAutoResize);
static hash_id rt_ids[] = {
PEN_HASH("rt_no_blend"), PEN_HASH("rt_alpha_blend"), PEN_HASH("rt_additive"), PEN_HASH("rt_premultiplied_alpha"),
PEN_HASH("rt_min"), PEN_HASH("rt_max"), PEN_HASH("rt_subtract"), PEN_HASH("rt_rev_subtract")};
int c = 0;
for (hash_id id : rt_ids)
{
const pmfx::render_target* r = pmfx::get_render_target(id);
if (!r)
continue;
f32 w, h;
pmfx::get_render_target_dimensions(r, w, h);
ImVec2 size(256, 256);
ImGui::Image(IMG(r->handle), size);
if (c != 3)
{
ImGui::SameLine();
c++;
}
else
{
c = 0;
}
}
ImGui::End();
}
void blend_layers(const scene_view& scene_view)
{
static ecs::geometry_resource* quad = ecs::get_geometry_resource(PEN_HASH("full_screen_quad"));
static pmm_renderable& r = quad->renderable[e_pmm_renderable::full_vertex_buffer];
static u32 background_texture = put::load_texture("data/textures/blend_test_bg.dds");
static u32 foreground_texture = put::load_texture("data/textures/blend_test_fg.dds");
u32 wrap_linear = pmfx::get_render_state(PEN_HASH("wrap_linear"), pmfx::e_render_state::sampler);
u32 disable_blend = pmfx::get_render_state(PEN_HASH("disabled"), pmfx::e_render_state::blend);
if (!is_valid(scene_view.pmfx_shader))
return;
if (!pmfx::set_technique_perm(scene_view.pmfx_shader, scene_view.id_technique))
PEN_ASSERT(0);
pen::renderer_set_constant_buffer(scene_view.cb_view, 0, pen::CBUFFER_BIND_VS);
pen::renderer_set_index_buffer(r.index_buffer, r.index_type, 0);
pen::renderer_set_vertex_buffer(r.vertex_buffer, 0, r.vertex_size, 0);
// background
pen::renderer_set_blend_state(disable_blend);
pen::renderer_set_texture(background_texture, wrap_linear, 0, pen::TEXTURE_BIND_PS);
pen::renderer_draw_indexed(r.num_indices, 0, 0, PEN_PT_TRIANGLELIST);
// foreground
pen::renderer_set_blend_state(scene_view.blend_state);
pen::renderer_set_texture(foreground_texture, wrap_linear, 0, pen::TEXTURE_BIND_PS);
pen::renderer_draw_indexed(r.num_indices, 0, 0, PEN_PT_TRIANGLELIST);
}
void* user_setup(void* params)
{
// unpack the params passed to the thread and signal to the engine it ok to proceed
job_params = (pen::job_thread_params*)params;
p_thread_info = job_params->job_info;
pen::semaphore_post(p_thread_info->p_sem_continue, 1);
pen::jobs_create_job(physics::physics_thread_main, 1024 * 10, nullptr, pen::e_thread_start_flags::detached);
put::dev_ui::init();
put::dbg::init();
put::ecs::create_geometry_primitives();
// create view renderers
put::scene_view_renderer svr_main;
svr_main.name = "blend_layers";
svr_main.id_name = PEN_HASH(svr_main.name.c_str());
svr_main.render_function = &blend_layers;
pmfx::register_scene_view_renderer(svr_main);
pmfx::init("data/configs/blend_modes.jsn");
pen_main_loop(user_update);
return PEN_THREAD_OK;
}
void user_shutdown()
{
pen::renderer_new_frame();
ecs::editor_shutdown();
put::pmfx::shutdown();
put::dbg::shutdown();
put::dev_ui::shutdown();
pen::renderer_present();
pen::renderer_consume_cmd_buffer();
pen::semaphore_post(p_thread_info->p_sem_terminated, 1);
}
loop_t user_update()
{
static pen::timer* frame_timer = pen::timer_create();
pen::timer_start(frame_timer);
put::dev_ui::new_frame();
pmfx::render();
pmfx::show_dev_ui();
blend_mode_ui();
put::dev_ui::render();
pen::renderer_present();
pen::renderer_consume_cmd_buffer();
pmfx::poll_for_changes();
put::poll_hot_loader();
// msg from the engine we want to terminate
if (pen::semaphore_try_wait(p_thread_info->p_sem_exit))
{
user_shutdown();
pen_main_loop_exit();
}
pen_main_loop_continue();
}
}
| 28.653266 | 125 | 0.622764 | [
"render"
] |
910bbe61ee880cd237b61e8711195d2bc42beeb2 | 6,315 | hpp | C++ | openstudiocore/src/model/CoilCoolingWaterToAirHeatPumpVariableSpeedEquationFitSpeedData_Impl.hpp | jasondegraw/OpenStudio | 2ab13f6e5e48940929041444e40ad9d36f80f552 | [
"blessing"
] | 1 | 2016-12-29T08:45:03.000Z | 2016-12-29T08:45:03.000Z | openstudiocore/src/model/CoilCoolingWaterToAirHeatPumpVariableSpeedEquationFitSpeedData_Impl.hpp | jasondegraw/OpenStudio | 2ab13f6e5e48940929041444e40ad9d36f80f552 | [
"blessing"
] | null | null | null | openstudiocore/src/model/CoilCoolingWaterToAirHeatPumpVariableSpeedEquationFitSpeedData_Impl.hpp | jasondegraw/OpenStudio | 2ab13f6e5e48940929041444e40ad9d36f80f552 | [
"blessing"
] | null | null | null | /**********************************************************************
* Copyright (c) 2008-2016, Alliance for Sustainable Energy.
* All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**********************************************************************/
#ifndef MODEL_COILCOOLINGWATERTOAIRHEATPUMPVARIABLESPEEDEQUATIONFITSPEEDDATA_IMPL_HPP
#define MODEL_COILCOOLINGWATERTOAIRHEATPUMPVARIABLESPEEDEQUATIONFITSPEEDDATA_IMPL_HPP
#include "ModelAPI.hpp"
#include "ParentObject_Impl.hpp"
namespace openstudio {
namespace model {
class Curve;
namespace detail {
/** CoilCoolingWaterToAirHeatPumpVariableSpeedEquationFitSpeedData_Impl is a ParentObject_Impl that is the implementation class for CoilCoolingWaterToAirHeatPumpVariableSpeedEquationFitSpeedData.*/
class MODEL_API CoilCoolingWaterToAirHeatPumpVariableSpeedEquationFitSpeedData_Impl : public ParentObject_Impl {
public:
/** @name Constructors and Destructors */
//@{
CoilCoolingWaterToAirHeatPumpVariableSpeedEquationFitSpeedData_Impl(const IdfObject& idfObject,
Model_Impl* model,
bool keepHandle);
CoilCoolingWaterToAirHeatPumpVariableSpeedEquationFitSpeedData_Impl(const openstudio::detail::WorkspaceObject_Impl& other,
Model_Impl* model,
bool keepHandle);
CoilCoolingWaterToAirHeatPumpVariableSpeedEquationFitSpeedData_Impl(const CoilCoolingWaterToAirHeatPumpVariableSpeedEquationFitSpeedData_Impl& other,
Model_Impl* model,
bool keepHandle);
virtual ~CoilCoolingWaterToAirHeatPumpVariableSpeedEquationFitSpeedData_Impl() {}
//@}
/** @name Virtual Methods */
//@{
virtual const std::vector<std::string>& outputVariableNames() const override;
virtual IddObjectType iddObjectType() const override;
virtual ModelObject clone(Model model) const override;
virtual std::vector<ModelObject> children() const override;
//@}
/** @name Getters */
//@{
double referenceUnitGrossRatedTotalCoolingCapacity() const;
double referenceUnitGrossRatedSensibleHeatRatio() const;
double referenceUnitGrossRatedCoolingCOP() const;
double referenceUnitRatedAirFlowRate() const;
double referenceUnitRatedWaterFlowRate() const;
Curve totalCoolingCapacityFunctionofTemperatureCurve() const;
Curve totalCoolingCapacityFunctionofAirFlowFractionCurve() const;
Curve totalCoolingCapacityFunctionofWaterFlowFractionCurve() const;
Curve energyInputRatioFunctionofTemperatureCurve() const;
Curve energyInputRatioFunctionofAirFlowFractionCurve() const;
Curve energyInputRatioFunctionofWaterFlowFractionCurve() const;
double referenceUnitWasteHeatFractionofInputPowerAtRatedConditions() const;
Curve wasteHeatFunctionofTemperatureCurve() const;
//@}
/** @name Setters */
//@{
bool setReferenceUnitGrossRatedTotalCoolingCapacity(double referenceUnitGrossRatedTotalCoolingCapacity);
bool setReferenceUnitGrossRatedSensibleHeatRatio(double referenceUnitGrossRatedSensibleHeatRatio);
bool setReferenceUnitGrossRatedCoolingCOP(double referenceUnitGrossRatedCoolingCOP);
bool setReferenceUnitRatedAirFlowRate(double referenceUnitRatedAirFlowRate);
bool setReferenceUnitRatedWaterFlowRate(double referenceUnitRatedWaterFlowRate);
bool setTotalCoolingCapacityFunctionofTemperatureCurve(const Curve& curve);
bool setTotalCoolingCapacityFunctionofAirFlowFractionCurve(const Curve& curve);
bool setTotalCoolingCapacityFunctionofWaterFlowFractionCurve(const Curve& curve);
bool setEnergyInputRatioFunctionofTemperatureCurve(const Curve& curve);
bool setEnergyInputRatioFunctionofAirFlowFractionCurve(const Curve& curve);
bool setEnergyInputRatioFunctionofWaterFlowFractionCurve(const Curve& curve);
bool setReferenceUnitWasteHeatFractionofInputPowerAtRatedConditions(double referenceUnitWasteHeatFractionofInputPowerAtRatedConditions);
bool setWasteHeatFunctionofTemperatureCurve(const Curve& curve);
//@}
/** @name Other */
//@{
//@}
protected:
private:
REGISTER_LOGGER("openstudio.model.CoilCoolingWaterToAirHeatPumpVariableSpeedEquationFitSpeedData");
// Optional getters for use by methods like children() so can remove() if the constructor fails.
// There are other ways for the public versions of these getters to fail--perhaps all required
// objects should be returned as boost::optionals
boost::optional<Curve> optionalTotalCoolingCapacityFunctionofTemperatureCurve() const;
boost::optional<Curve> optionalTotalCoolingCapacityFunctionofAirFlowFractionCurve() const;
boost::optional<Curve> optionalTotalCoolingCapacityFunctionofWaterFlowFractionCurve() const;
boost::optional<Curve> optionalEnergyInputRatioFunctionofTemperatureCurve() const;
boost::optional<Curve> optionalEnergyInputRatioFunctionofAirFlowFractionCurve() const;
boost::optional<Curve> optionalEnergyInputRatioFunctionofWaterFlowFractionCurve() const;
boost::optional<Curve> optionalWasteHeatFunctionofTemperatureCurve() const;
};
} // detail
} // model
} // openstudio
#endif // MODEL_COILCOOLINGWATERTOAIRHEATPUMPVARIABLESPEEDEQUATIONFITSPEEDDATA_IMPL_HPP
| 41.27451 | 199 | 0.731433 | [
"vector",
"model"
] |
9118ba94f1e4a8d759e8d3b55a75c97c53fe0d34 | 64,663 | cpp | C++ | SimTKmath/Geometry/src/ContactTracker.cpp | elen4/simbody | 3ddbc16323afa45b7698c38e07266a7de15e2ad2 | [
"Apache-2.0"
] | 2 | 2020-01-15T05:03:30.000Z | 2021-01-16T06:18:47.000Z | SimTKmath/Geometry/src/ContactTracker.cpp | sohapouya/simbody | 3729532453b22ffa3693962210941184f5617f5b | [
"Apache-2.0"
] | null | null | null | SimTKmath/Geometry/src/ContactTracker.cpp | sohapouya/simbody | 3729532453b22ffa3693962210941184f5617f5b | [
"Apache-2.0"
] | 1 | 2021-09-24T15:20:36.000Z | 2021-09-24T15:20:36.000Z | /* -------------------------------------------------------------------------- *
* Simbody(tm): SimTKmath *
* -------------------------------------------------------------------------- *
* This is part of the SimTK biosimulation toolkit originating from *
* Simbios, the NIH National Center for Physics-Based Simulation of *
* Biological Structures at Stanford, funded under the NIH Roadmap for *
* Medical Research, grant U54 GM072970. See https://simtk.org/home/simbody. *
* *
* Portions copyright (c) 2010-13 Stanford University and the Authors. *
* Authors: Peter Eastman, Michael Sherman *
* Contributors: *
* *
* 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 "SimTKmath.h"
#include <algorithm>
using std::pair; using std::make_pair;
#include <iostream>
using std::cout; using std::endl;
#include <set>
// Define this if you want to see voluminous output from MPR (XenoCollide)
//#define MPR_DEBUG
namespace SimTK {
//==============================================================================
// CONTACT TRACKER
//==============================================================================
//------------------------------------------------------------------------------
// ESTIMATE IMPLICIT PAIR CONTACT USING MPR
//------------------------------------------------------------------------------
// Generate a rough guess at the contact points. Point P is returned in A's
// frame and point Q is in B's frame, but all the work here is done in frame A.
// See Snethen, G. "XenoCollide: Complex Collision Made Simple", Game
// Programming Gems 7, pp.165-178.
//
// Note that we intend to use this on smooth convex objects. That means there
// can be no guarantee about how many iterations this will take to converge; it
// may take a very long time for objects that are just barely touching. On the
// other hand we only need an approximate answer because we're going to polish
// the solution to machine precision using a Newton iteration afterwards.
namespace {
// Given a direction in shape A's frame, calculate the support point of the
// Minkowski difference shape A-B in that direction. To do that we find A's
// support point P in that direction, and B's support point Q in the opposite
// direction; i.e. what would be -B's support in the original direction. Then
// return the vector v=(P-Q) expressed in A's frame.
struct Support {
Support(const ContactGeometry& shapeA, const ContactGeometry& shapeB,
const Transform& X_AB, const UnitVec3& dirInA)
: shapeA(shapeA), shapeB(shapeB), X_AB(X_AB)
{ computeSupport(dirInA); }
// Calculate a new set of supports for the same shapes.
void computeSupport(const UnitVec3& dirInA) {
const UnitVec3 dirInB = ~X_AB.R() * dirInA; // 15 flops
dir = dirInA;
A = shapeA.calcSupportPoint( dirInA); // varies; 40 flops for ellipsoid
B = shapeB.calcSupportPoint(-dirInB); // "
v = A - X_AB*B; // 21 flops
depth = dot(v,dir); // 5 flops
}
Support& operator=(const Support& src) {
dir = src.dir; A = src.A; B = src.B; v = src.v;
return *this;
}
void swap(Support& other) {
std::swap(dir, other.dir);
std::swap(A,other.A); std::swap(B,other.B); std::swap(v,other.v);
}
void getResult(Vec3& pointP_A, Vec3& pointQ_B, UnitVec3& normalInA) const
{ pointP_A = A; pointQ_B = B; normalInA = dir; }
UnitVec3 dir; // A support direction, exp in A
Vec3 A; // support point in direction dir on shapeA, expressed in A
Vec3 B; // support point in direction -dir on shapeB, expressed in B
Vec3 v; // support point A-B in Minkowski difference shape, exp. in A
Real depth; // v . dir (positive when origin is below support plane)
private:
const ContactGeometry& shapeA;
const ContactGeometry& shapeB;
const Transform& X_AB;
};
const Real MPRAccuracy = Real(.05); // 5% of the surface dimensions
const Real SqrtMPRAccuracy = Real(.2236); // roughly sqrt(MPRAccuracy)
}
/*static*/ bool ContactTracker::
estimateConvexImplicitPairContactUsingMPR
(const ContactGeometry& shapeA, const ContactGeometry& shapeB,
const Transform& X_AB,
Vec3& pointP, Vec3& pointQ, UnitVec3& dirInA, int& numIterations)
{
const Rotation& R_AB = X_AB.R();
numIterations = 0;
// Get some cheap, rough scaling information.
// TODO: ideally this would be done using local curvature information.
// A reasonable alternative would be to use the smallest dimension of the
// shape's oriented bounding box.
// We're going to assume the smallest radius is 1/4 of the bounding
// sphere radius.
Vec3 cA, cB; Real rA, rB;
shapeA.getBoundingSphere(cA,rA); shapeB.getBoundingSphere(cB,rB);
const Real lengthScale = Real(0.25)*std::min(rA,rB);
const Real areaScale = Real(1.5)*square(lengthScale); // ~area of octant
// If we determine the depth to within a small fraction of the scale,
// or localize the contact area to a small fraction of the surface area,
// that is good enough and we can stop.
const Real depthGoal = MPRAccuracy*lengthScale;
const Real areaGoal = SqrtMPRAccuracy*areaScale;
#ifdef MPR_DEBUG
printf("\nMPR acc=%g: r=%g, depthGoal=%g areaGoal=%g\n",
MPRAccuracy, std::min(rA,rB), depthGoal, areaGoal);
#endif
// Phase 1: Portal Discovery
// -------------------------
// Compute an interior point v0 that is known to be inside the Minkowski
// difference, and a ray dir1 directed from that point to the origin.
const Vec3 v0 = ( Support(shapeA, shapeB, X_AB, UnitVec3( XAxis)).v
+ Support(shapeA, shapeB, X_AB, UnitVec3(-XAxis)).v)/2;
if (v0 == 0) {
// This is a pathological case: the two objects are directly on top of
// each other with their centers at exactly the same place. Just
// return *some* vaguely plausible contact.
pointP = shapeA.calcSupportPoint( UnitVec3( XAxis));
pointQ = shapeB.calcSupportPoint(~R_AB*UnitVec3(-XAxis)); // in B
dirInA = XAxis;
return true;
}
// Support 1's direction is initially the "origin ray" that points from
// interior point v0 to the origin.
Support s1(shapeA, shapeB, X_AB, UnitVec3(-v0));
// Test for NaN once and get out to avoid getting stuck in loops below.
if (isNaN(s1.depth)) {
pointP = pointQ = NaN;
dirInA = UnitVec3();
return false;
}
if (s1.depth <= 0) { // origin outside 1st support plane
s1.getResult(pointP, pointQ, dirInA);
return false;
}
if (s1.v % v0 == 0) { // v0 perpendicular to support plane; origin inside
s1.getResult(pointP, pointQ, dirInA);
return true;
}
// Find support point perpendicular to plane containing origin, interior
// point v0, and first support v1.
Support s2(shapeA, shapeB, X_AB, UnitVec3(s1.v % v0));
if (s2.depth <= 0) { // origin is outside 2nd support plane
s2.getResult(pointP, pointQ, dirInA);
return false;
}
// Find support perpendicular to plane containing interior point v0 and
// first two support points v1 and v2. Make sure it is on the side that
// is closer to the origin; fix point ordering if necessary.
UnitVec3 d3 = UnitVec3((s1.v-v0)%(s2.v-v0));
if (~d3*v0 > 0) { // oops -- picked the wrong side
s1.swap(s2);
d3 = -d3;
}
Support s3(shapeA, shapeB, X_AB, d3);
if (s3.depth <= 0) { // origin is outside 3rd support plane
s3.getResult(pointP, pointQ, dirInA);
return false;
}
// We now have a candidate portal (triangle v1,v2,v3). We have to refine it
// until the origin ray -v0 intersects the candidate. Check against the
// three planes of the tetrahedron that contain v0. By construction above
// we know the origin is inside the v0,v1,v2 face already.
// We should find a candidate portal very fast, probably in 1 or 2
// iterations. We'll allow an absurdly large number of
// iterations and then abort just to make sure we don't get stuck in an
// infinite loop.
const Real MaxCandidateIters = 100; // should never get anywhere near this
int candidateIters = 0;
while (true) {
++candidateIters;
SimTK_ERRCHK_ALWAYS(candidateIters <= MaxCandidateIters,
"ContactTracker::estimateConvexImplicitPairContactUsingMPR()",
"Unable to find a candidate portal; should never happen.");
if (~v0*(s1.v % s3.v) < -SignificantReal)
s2 = s3; // origin outside v0,v1,v3 face; replace v2
else if (~v0*(s3.v % s2.v) < -SignificantReal)
s1 = s3; // origin outside v0,v2,v3 face; replace v1
else
break;
// Choose new candidate. The keepers are in v1 and v2; get a new v3.
s3.computeSupport(UnitVec3((s1.v-v0) % (s2.v-v0)));
}
// Phase 2: Portal Refinement
// --------------------------
// We have a portal (triangle v1,v2,v3) that the origin ray passes through.
// Now we need to refine v1,v2,v3 until we have portal such that the origin
// is inside the tetrahedron v0,v1,v2,v3.
const int MinTriesToFindSeparatingPlane = 5;
const int MaxTriesToImproveContact = 5;
int triesToFindSeparatingPlane=0, triesToImproveContact=0;
while (true) {
++numIterations;
// Get the normal to the portal, oriented in the general direction of
// the origin ray (i.e., the outward normal).
const Vec3 portalVec = (s2.v-s1.v) % (s3.v-s1.v);
const Real portalArea = portalVec.norm(), ooPortalArea = 1/portalArea;
UnitVec3 portalDir(portalVec*ooPortalArea, true);
if (~portalDir*v0 > 0)
portalDir = -portalDir;
// Any portal vertex is a vector from the origin to the portal plane.
// Dot one of them with the portal outward normal to get the origin
// depth (positive if inside).
const Real depth = ~s1.v*portalDir;
// Find new support in portal direction.
Support s4(shapeA, shapeB, X_AB, portalDir);
if (s4.depth <= 0) { // origin is outside new support plane
s4.getResult(pointP, pointQ, dirInA);
return false;
}
const Real depthChange = std::abs(s4.depth - depth);
bool mustReturn=false, okToReturn=false;
if (depth >= 0) { // We found a contact.
mustReturn = (++triesToImproveContact >= MaxTriesToImproveContact);
okToReturn = true;
} else { // No contact yet.
okToReturn =
(++triesToFindSeparatingPlane >= MinTriesToFindSeparatingPlane);
mustReturn = false;
}
bool accuracyAchieved =
(depthChange <= depthGoal || portalArea <= areaGoal);
#ifdef MPR_DEBUG
printf(" depth=%g, change=%g area=%g changeFrac=%g areaFrac=%g\n",
depth, depthChange, portalArea,
depthChange/depthGoal, portalArea/areaGoal);
printf(" accuracyAchieved=%d okToReturn=%d mustReturn=%d\n",
accuracyAchieved, okToReturn, mustReturn);
#endif
if (mustReturn || (okToReturn && accuracyAchieved)) {
// The origin is inside the portal, so we have an intersection.
// Compute the barycentric coordinates of the origin ray's
// intersection with the portal, and map back to the two surfaces.
const Vec3 origin = v0+v0*(~portalDir*(s1.v-v0)/(~portalDir*v0));
const Real area1 = ~portalDir*((s2.v-origin)%(s3.v-origin));
const Real area2 = ~portalDir*((s3.v-origin)%(s1.v-origin));
const Real u = area1*ooPortalArea;
const Real v = area2*ooPortalArea;
const Real w = 1-u-v;
// Compute the contact points in their own shape's frame.
pointP = u*s1.A + v*s2.A + w*s3.A;
pointQ = u*s1.B + v*s2.B + w*s3.B;
dirInA = portalDir;
return true;
}
// We know the origin ray entered the (v1,v2,v3,v4) tetrahedron via the
// (v1,v2,v3) face (the portal). New portal is the face that it exits.
const Vec3 v4v0 = s4.v % v0;
if (~s1.v * v4v0 > 0) {
if (~s2.v * v4v0 > 0) s1 = s4; // v4,v2,v3 (new portal)
else s3 = s4; // v1,v2,v4
} else {
if (~s3.v * v4v0 > 0) s2 = s4; // v1,v4,v3
else s1 = s4; // v4,v2,v3 again
}
}
}
//------------------------------------------------------------------------------
// REFINE IMPLICIT PAIR
//------------------------------------------------------------------------------
// We have a rough estimate of the contact points. Use Newton iteration to
// refine them. If the surfaces are separated, this will find the points of
// closest approach. If contacting, this will find the points of maximium
// penetration.
// Returns true if the desired accuracy is achieved, regardless of whether the
// surfaces are separated or in contact.
/*static*/ bool ContactTracker::
refineImplicitPair
(const ContactGeometry& shapeA, Vec3& pointP, // in/out (in A)
const ContactGeometry& shapeB, Vec3& pointQ, // in/out (in B)
const Transform& X_AB, Real accuracyRequested,
Real& accuracyAchieved, int& numIterations)
{
// If the initial guess is very bad, or the ellipsoids pathological we
// may have to crawl along for a while at the beginning.
const int MaxSlowIterations = 8;
const int MaxIterations = MaxSlowIterations + 8;
const Real MinStepFrac = Real(1e-6); // if we can't take at least this
// fraction of Newton step, give it up
Vec6 err = findImplicitPairError(shapeA, pointP, shapeB, pointQ, X_AB);
accuracyAchieved = err.norm();
Vector errVec(6, &err[0], true); // share space with err
Mat66 J; // to hold the Jacobian
Matrix JMat(6,6,6,&J(0,0)); // share space with J
Vec6 delta;
Vector deltaVec(6, &delta[0], true); // share space with delta
numIterations = 0;
while ( accuracyAchieved > accuracyRequested
&& numIterations < MaxIterations)
{
++numIterations;
J = calcImplicitPairJacobian(shapeA, pointP, shapeB, pointQ,
X_AB, err);
// Try to use LU factorization; fall back to QTZ if singular.
FactorLU lu(JMat);
if (!lu.isSingular())
lu.solve(errVec, deltaVec); // writes into delta also
else {
FactorQTZ qtz(JMat, SqrtEps);
qtz.solve(errVec, deltaVec); // writes into delta also
}
// Line search for safety in case starting guess bad. Don't accept
// any move that makes things worse.
Real f = 2; // scale back factor
Vec3 oldP = pointP, oldQ = pointQ;
Real oldAccuracyAchieved = accuracyAchieved;
do {
f /= 2;
pointP = oldP - f*delta.getSubVec<3>(0);
pointQ = oldQ - f*delta.getSubVec<3>(3);
err = findImplicitPairError(shapeA, pointP, shapeB, pointQ, X_AB);
accuracyAchieved = err.norm();
} while (accuracyAchieved > oldAccuracyAchieved && f > MinStepFrac);
const bool noProgressMade = (accuracyAchieved > oldAccuracyAchieved);
if (noProgressMade) { // Restore best points and fall through.
pointP = oldP;
pointQ = oldQ;
}
if ( noProgressMade
|| (f < 1 && numIterations >= MaxSlowIterations)) // Too slow.
{
// We don't appear to be getting anywhere. Just project the
// points onto the surfaces and then exit.
bool inside;
UnitVec3 normal;
pointP = shapeA.findNearestPoint(pointP, inside, normal);
pointQ = shapeB.findNearestPoint(pointQ, inside, normal);
err = findImplicitPairError(shapeA, pointP, shapeB, pointQ, X_AB);
accuracyAchieved = err.norm();
break;
}
}
return accuracyAchieved <= accuracyRequested;
}
//------------------------------------------------------------------------------
// FIND IMPLICIT PAIR ERROR
//------------------------------------------------------------------------------
// We're given two implicitly-defined shapes A and B and candidate surface
// contact points P (for A) and Q (for B). There are six equations that real
// contact points should satisfy. Here we return the errors in each of those
// equations; if all six terms are zero these are contact points.
//
// Per profiling, this gets called a lot at runtime, so keep it tight!
/*static*/ Vec6 ContactTracker::
findImplicitPairError
(const ContactGeometry& shapeA, const Vec3& pointP, // in A
const ContactGeometry& shapeB, const Vec3& pointQ, // in B
const Transform& X_AB)
{
// Compute the function value and normal vector for each object.
const Function& fA = shapeA.getImplicitFunction();
const Function& fB = shapeB.getImplicitFunction();
// Avoid some heap allocations by using stack arrays.
Vec3 xData;
Vector x(3, &xData[0], true); // shares space with xdata
int compData; // just one integer
ArrayView_<int> components(&compData, &compData+1);
Vec3 gradA, gradB;
xData = pointP; // writes into Vector x also
for (int i = 0; i < 3; i++) {
components[0] = i;
gradA[i] = fA.calcDerivative(components, x);
}
Real errorA = fA.calcValue(x);
xData = pointQ; // writes into Vector x also
for (int i = 0; i < 3; i++) {
components[0] = i;
gradB[i] = fB.calcDerivative(components, x);
}
Real errorB = fB.calcValue(x);
// Construct a coordinate frame for each object.
// TODO: this needs some work to make sure it is as stable as possible
// so the perpendicularity errors are stable as the solution advances
// and especially as the Jacobian is calculated by perturbation.
UnitVec3 nA(-gradA);
UnitVec3 nB(X_AB.R()*(-gradB));
UnitVec3 uA(std::abs(nA[0])>Real(0.5)? nA%Vec3(0, 1, 0) : nA%Vec3(1, 0, 0));
UnitVec3 uB(std::abs(nB[0])>Real(0.5)? nB%Vec3(0, 1, 0) : nB%Vec3(1, 0, 0));
Vec3 vA = nA%uA; // Already a unit vector, so we don't need to normalize it.
Vec3 vB = nB%uB;
// Compute the error vector. The components indicate, in order, that nA
// must be perpendicular to both tangents of object B, that the separation
// vector should be zero or perpendicular to the tangents of object A, and
// that both points should be on their respective surfaces.
Vec3 delta = pointP-X_AB*pointQ;
return Vec6(~nA*uB, ~nA*vB, ~delta*uA, ~delta*vA, errorA, errorB);
}
//------------------------------------------------------------------------------
// CALC IMPLICIT PAIR JACOBIAN
//------------------------------------------------------------------------------
// Differentiate the findImplicitPairError() with respect to changes in the
// locations of points P and Q in their own surface frames.
/*static*/ Mat66 ContactTracker::calcImplicitPairJacobian
(const ContactGeometry& shapeA, const Vec3& pointP,
const ContactGeometry& shapeB, const Vec3& pointQ,
const Transform& X_AB, const Vec6& err0)
{
Real dt = SqrtEps;
Vec3 d1 = dt*Vec3(1, 0, 0);
Vec3 d2 = dt*Vec3(0, 1, 0);
Vec3 d3 = dt*Vec3(0, 0, 1);
Vec6 err1 = findImplicitPairError(shapeA, pointP+d1, shapeB, pointQ, X_AB)
- err0;
Vec6 err2 = findImplicitPairError(shapeA, pointP+d2, shapeB, pointQ, X_AB)
- err0;
Vec6 err3 = findImplicitPairError(shapeA, pointP+d3, shapeB, pointQ, X_AB)
- err0;
Vec6 err4 = findImplicitPairError(shapeA, pointP, shapeB, pointQ+d1, X_AB)
- err0;
Vec6 err5 = findImplicitPairError(shapeA, pointP, shapeB, pointQ+d2, X_AB)
- err0;
Vec6 err6 = findImplicitPairError(shapeA, pointP, shapeB, pointQ+d3, X_AB)
- err0;
return Mat66(err1, err2, err3, err4, err5, err6) / dt;
// This is a Central Difference derivative (you should use a somewhat
// larger dt in this case). However, I haven't seen any evidence that this
// helps, even for some very eccentric ellipsoids. (sherm 20130408)
//Vec6 err1 = findImplicitPairError(shapeA, pointP+d1, shapeB, pointQ, X_AB)
// - findImplicitPairError(shapeA, pointP-d1, shapeB, pointQ, X_AB);
//Vec6 err2 = findImplicitPairError(shapeA, pointP+d2, shapeB, pointQ, X_AB)
// - findImplicitPairError(shapeA, pointP-d2, shapeB, pointQ, X_AB);
//Vec6 err3 = findImplicitPairError(shapeA, pointP+d3, shapeB, pointQ, X_AB)
// - findImplicitPairError(shapeA, pointP-d3, shapeB, pointQ, X_AB);
//Vec6 err4 = findImplicitPairError(shapeA, pointP, shapeB, pointQ+d1, X_AB)
// - findImplicitPairError(shapeA, pointP, shapeB, pointQ-d1, X_AB);
//Vec6 err5 = findImplicitPairError(shapeA, pointP, shapeB, pointQ+d2, X_AB)
// - findImplicitPairError(shapeA, pointP, shapeB, pointQ-d2, X_AB);
//Vec6 err6 = findImplicitPairError(shapeA, pointP, shapeB, pointQ+d3, X_AB)
// - findImplicitPairError(shapeA, pointP, shapeB, pointQ-d3, X_AB);
//return Mat66(err1, err2, err3, err4, err5, err6) / (2*dt);
}
//==============================================================================
// HALFSPACE-SPHERE CONTACT TRACKER
//==============================================================================
// Cost is 21 flops if no contact, 67 with contact.
bool ContactTracker::HalfSpaceSphere::trackContact
(const Contact& priorStatus,
const Transform& X_GH,
const ContactGeometry& geoHalfSpace,
const Transform& X_GS,
const ContactGeometry& geoSphere,
Real cutoff,
Contact& currentStatus) const
{
SimTK_ASSERT
( geoHalfSpace.getTypeId()==ContactGeometry::HalfSpace::classTypeId()
&& geoSphere.getTypeId()==ContactGeometry::Sphere::classTypeId(),
"ContactTracker::HalfSpaceSphere::trackContact()");
// No need for an expensive dynamic cast here; we know what we have.
const ContactGeometry::Sphere& sphere =
ContactGeometry::Sphere::getAs(geoSphere);
const Rotation R_HG = ~X_GH.R(); // inverse rotation; no flops
// p_HC is vector from H origin to S's center C
const Vec3 p_HC = R_HG*(X_GS.p() - X_GH.p()); // 18 flops
// Calculate depth of sphere center C given that the halfspace occupies
// all of x>0 space.
const Real r = sphere.getRadius();
const Real depth = p_HC[0] + r; // 1 flop
if (depth <= -cutoff) { // 2 flops
currentStatus.clear(); // not touching
return true; // successful return
}
// Calculate the rest of the X_HS transform as required by Contact.
const Transform X_HS(R_HG*X_GS.R(), p_HC); // 45 flops
const UnitVec3 normal_H(Vec3(-1,0,0), true); // 0 flops
const Vec3 origin_H = Vec3(depth/2, p_HC[1], p_HC[2]); // 1 flop
// The surfaces are contacting (or close enough to be interesting).
// The sphere's radius is also the effective radius.
currentStatus = CircularPointContact(priorStatus.getSurface1(), Infinity,
priorStatus.getSurface2(), r,
X_HS, r, depth, origin_H, normal_H);
return true; // success
}
bool ContactTracker::HalfSpaceSphere::predictContact
(const Contact& priorStatus,
const Transform& X_GS1, const SpatialVec& V_GS1, const SpatialVec& A_GS1,
const ContactGeometry& surface1,
const Transform& X_GS2, const SpatialVec& V_GS2, const SpatialVec& A_GS2,
const ContactGeometry& surface2,
Real cutoff,
Real intervalOfInterest,
Contact& predictedStatus) const
{ SimTK_ASSERT_ALWAYS(!"implemented",
"ContactTracker::HalfSpaceSphere::predictContact() not implemented yet.");
return false; }
bool ContactTracker::HalfSpaceSphere::initializeContact
(const Transform& X_GS1, const SpatialVec& V_GS1,
const ContactGeometry& surface1,
const Transform& X_GS2, const SpatialVec& V_GS2,
const ContactGeometry& surface2,
Real cutoff,
Real intervalOfInterest,
Contact& contactStatus) const
{ SimTK_ASSERT_ALWAYS(!"implemented",
"ContactTracker::HalfSpaceSphere::initializeContact() not implemented yet.");
return false; }
//==============================================================================
// HALFSPACE-ELLIPSOID CONTACT TRACKER
//==============================================================================
// Cost is ~135 flops if no contact, ~425 with contact.
// The contact point on the ellipsoid must be the unique point that has its
// outward-facing normal in the opposite direction of the half space normal.
// We can find that point very fast and see how far it is from the half
// space surface. If it is close enough, we'll evaluate the curvatures at
// that point in preparation for generating forces with Hertz theory.
bool ContactTracker::HalfSpaceEllipsoid::trackContact
(const Contact& priorStatus,
const Transform& X_GH,
const ContactGeometry& geoHalfSpace,
const Transform& X_GE,
const ContactGeometry& geoEllipsoid,
Real cutoff,
Contact& currentStatus) const
{
SimTK_ASSERT
( geoHalfSpace.getTypeId()==ContactGeometry::HalfSpace::classTypeId()
&& geoEllipsoid.getTypeId()==ContactGeometry::Ellipsoid::classTypeId(),
"ContactTracker::HalfSpaceEllipsoid::trackContact()");
// No need for an expensive dynamic cast here; we know what we have.
const ContactGeometry::Ellipsoid& ellipsoid =
ContactGeometry::Ellipsoid::getAs(geoEllipsoid);
// Our half space occupies the +x half so the normal is -x.
const Transform X_HE = ~X_GH*X_GE; // 63 flops
// Halfspace normal is -x, so the ellipsoid normal we're looking for is
// in the half space's +x direction.
const UnitVec3& n_E = (~X_HE.R()).x(); // halfspace normal in E
const Vec3 Q_E = ellipsoid.findPointWithThisUnitNormal(n_E); // 40 flops
const Vec3 Q_H = X_HE*Q_E; // Q measured from half space origin (18 flops)
const Real depth = Q_H[0]; // x > 0 is penetrated
if (depth <= -cutoff) { // 2 flops
currentStatus.clear(); // not touching
return true; // successful return
}
// The surfaces are contacting (or close enough to be interesting).
// The ellipsoid's principal curvatures k at the contact point are also
// the curvatures of the contact paraboloid since the half space doesn't
// add anything interesting.
Transform X_EQ; Vec2 k;
ellipsoid.findParaboloidAtPointWithNormal(Q_E, n_E, X_EQ, k); // 220 flops
// We have the contact paraboloid expressed in frame Q but Qz=n_E has the
// wrong sign since we have to express it using the half space normal.
// We have to end up with a right handed frame, so one of x or y has
// to be negated too. (6 flops)
Rotation& R_EQ = X_EQ.updR();
R_EQ.setRotationColFromUnitVecTrustMe(ZAxis, -R_EQ.z()); // changing X_EQ
R_EQ.setRotationColFromUnitVecTrustMe(XAxis, -R_EQ.x());
// Now the frame is pointing in the right direction. Measure and express in
// half plane frame, then shift origin to half way between contact point
// Q on the undeformed ellipsoid and the corresponding contact point P
// on the undeformed half plane surface. It's easier to do this shift
// in H since it is in the -Hx direction.
Transform X_HC = X_HE*X_EQ; X_HC.updP()[0] -= depth/2; // 65 flops
currentStatus = EllipticalPointContact(priorStatus.getSurface1(),
priorStatus.getSurface2(),
X_HE, X_HC, k, depth);
return true; // success
}
bool ContactTracker::HalfSpaceEllipsoid::predictContact
(const Contact& priorStatus,
const Transform& X_GS1, const SpatialVec& V_GS1, const SpatialVec& A_GS1,
const ContactGeometry& surface1,
const Transform& X_GS2, const SpatialVec& V_GS2, const SpatialVec& A_GS2,
const ContactGeometry& surface2,
Real cutoff,
Real intervalOfInterest,
Contact& predictedStatus) const
{ SimTK_ASSERT_ALWAYS(!"implemented",
"ContactTracker::HalfSpaceEllipsoid::predictContact() not implemented yet.");
return false; }
bool ContactTracker::HalfSpaceEllipsoid::initializeContact
(const Transform& X_GS1, const SpatialVec& V_GS1,
const ContactGeometry& surface1,
const Transform& X_GS2, const SpatialVec& V_GS2,
const ContactGeometry& surface2,
Real cutoff,
Real intervalOfInterest,
Contact& contactStatus) const
{ SimTK_ASSERT_ALWAYS(!"implemented",
"ContactTracker::HalfSpaceEllipsoid::initializeContact() not implemented yet.");
return false; }
//==============================================================================
// SPHERE-SPHERE CONTACT TRACKER
//==============================================================================
// Cost is 12 flops if no contact, 139 if contact
bool ContactTracker::SphereSphere::trackContact
(const Contact& priorStatus,
const Transform& X_GS1,
const ContactGeometry& geoSphere1,
const Transform& X_GS2,
const ContactGeometry& geoSphere2,
Real cutoff, // 0 for contact
Contact& currentStatus) const
{
SimTK_ASSERT
( geoSphere1.getTypeId()==ContactGeometry::Sphere::classTypeId()
&& geoSphere2.getTypeId()==ContactGeometry::Sphere::classTypeId(),
"ContactTracker::SphereSphere::trackContact()");
// No need for an expensive dynamic casts here; we know what we have.
const ContactGeometry::Sphere& sphere1 =
ContactGeometry::Sphere::getAs(geoSphere1);
const ContactGeometry::Sphere& sphere2 =
ContactGeometry::Sphere::getAs(geoSphere2);
currentStatus.clear();
// Find the vector from sphere center C1 to C2, expressed in G.
const Vec3 p_12_G = X_GS2.p() - X_GS1.p(); // 3 flops
const Real d2 = p_12_G.normSqr(); // 5 flops
const Real r1 = sphere1.getRadius();
const Real r2 = sphere2.getRadius();
const Real rr = r1 + r2; // 1 flop
// Quick check. If separated we can return nothing, unless we were
// in contact last time in which case we have to return one last
// Contact indicating that contact has been broken and by how much.
if (d2 > square(rr+cutoff)) { // 3 flops
if (!priorStatus.getContactId().isValid())
return true; // successful return: still separated
const Real separation = std::sqrt(d2) - rr; // > cutoff, ~25 flops
const Transform X_S1S2(~X_GS1.R()*X_GS2.R(),
~X_GS1.R()*p_12_G); // 60 flops
currentStatus = BrokenContact(priorStatus.getSurface1(),
priorStatus.getSurface2(),
X_S1S2, separation);
return true;
}
const Real d = std::sqrt(d2); // ~20 flops
if (d < SignificantReal) { // 1 flop
// TODO: If the centers are coincident we should use past information
// to determine the most likely normal. For now just fail.
return false;
}
const Transform X_S1S2(~X_GS1.R()*X_GS2.R(),
~X_GS1.R()*p_12_G);// 60 flops
const Vec3& p_12 = X_S1S2.p(); // center-to-center vector in S1
const Real depth = rr - d; // >0 for penetration (1 flop)
const Real r = r1*r2/rr; // r=r1r2/(r1+r2)=1/(1/r1+1/r2) ~20 flops
const UnitVec3 normal_S1(p_12/d, true); // 1/ + 3* = ~20 flops
const Vec3 origin_S1 = (r1 - depth/2)*normal_S1; // 5 flops
// The surfaces are contacting (or close enough to be interesting).
currentStatus = CircularPointContact(priorStatus.getSurface1(), r1,
priorStatus.getSurface2(), r2,
X_S1S2, r, depth,
origin_S1, normal_S1);
return true; // success
}
bool ContactTracker::SphereSphere::predictContact
(const Contact& priorStatus,
const Transform& X_GS1, const SpatialVec& V_GS1, const SpatialVec& A_GS1,
const ContactGeometry& surface1,
const Transform& X_GS2, const SpatialVec& V_GS2, const SpatialVec& A_GS2,
const ContactGeometry& surface2,
Real cutoff,
Real intervalOfInterest,
Contact& predictedStatus) const
{ SimTK_ASSERT_ALWAYS(!"implemented",
"ContactTracker::SphereSphere::predictContact() not implemented yet.");
return false; }
bool ContactTracker::SphereSphere::initializeContact
(const Transform& X_GS1, const SpatialVec& V_GS1,
const ContactGeometry& surface1,
const Transform& X_GS2, const SpatialVec& V_GS2,
const ContactGeometry& surface2,
Real cutoff,
Real intervalOfInterest,
Contact& contactStatus) const
{ SimTK_ASSERT_ALWAYS(!"implemented",
"ContactTracker::SphereSphere::initializeContact() not implemented yet.");
return false; }
//==============================================================================
// HALFSPACE - TRIANGLE MESH CONTACT TRACKER
//==============================================================================
// Cost is TODO
bool ContactTracker::HalfSpaceTriangleMesh::trackContact
(const Contact& priorStatus,
const Transform& X_GH,
const ContactGeometry& geoHalfSpace,
const Transform& X_GM,
const ContactGeometry& geoMesh,
Real cutoff,
Contact& currentStatus) const
{
SimTK_ASSERT_ALWAYS
( ContactGeometry::HalfSpace::isInstance(geoHalfSpace)
&& ContactGeometry::TriangleMesh::isInstance(geoMesh),
"ContactTracker::HalfSpaceTriangleMesh::trackContact()");
// We can't handle a "proximity" test, only penetration.
SimTK_ASSERT_ALWAYS(cutoff==0,
"ContactTracker::HalfSpaceTriangleMesh::trackContact()");
// No need for an expensive dynamic cast here; we know what we have.
const ContactGeometry::TriangleMesh& mesh =
ContactGeometry::TriangleMesh::getAs(geoMesh);
// Transform giving mesh (S2) frame in the halfspace (S1) frame.
const Transform X_HM = (~X_GH)*X_GM;
// Normal is halfspace -x direction; xdir is first column of R_MH.
// That's a unit vector and -unitvec is also a unit vector so this
// doesn't require normalization.
const UnitVec3 hsNormal_M = -(~X_HM.R()).x();
// Find the height of the halfspace face along the normal, measured
// from the mesh origin.
const Real hsFaceHeight_M = dot((~X_HM).p(), hsNormal_M);
// Now collect all the faces that are all or partially below the
// halfspace surface.
std::set<int> insideFaces;
processBox(mesh, mesh.getOBBTreeNode(), X_HM,
hsNormal_M, hsFaceHeight_M, insideFaces);
if (insideFaces.empty()) {
currentStatus.clear(); // not touching
return true; // successful return
}
currentStatus = TriangleMeshContact(priorStatus.getSurface1(),
priorStatus.getSurface2(),
X_HM,
std::set<int>(), insideFaces);
return true; // success
}
bool ContactTracker::HalfSpaceTriangleMesh::predictContact
(const Contact& priorStatus,
const Transform& X_GS1, const SpatialVec& V_GS1, const SpatialVec& A_GS1,
const ContactGeometry& surface1,
const Transform& X_GS2, const SpatialVec& V_GS2, const SpatialVec& A_GS2,
const ContactGeometry& surface2,
Real cutoff,
Real intervalOfInterest,
Contact& predictedStatus) const
{ SimTK_ASSERT_ALWAYS(!"implemented",
"ContactTracker::HalfSpaceTriangleMesh::predictContact() not implemented yet.");
return false; }
bool ContactTracker::HalfSpaceTriangleMesh::initializeContact
(const Transform& X_GS1, const SpatialVec& V_GS1,
const ContactGeometry& surface1,
const Transform& X_GS2, const SpatialVec& V_GS2,
const ContactGeometry& surface2,
Real cutoff,
Real intervalOfInterest,
Contact& contactStatus) const
{ SimTK_ASSERT_ALWAYS(!"implemented",
"ContactTracker::HalfSpaceTriangleMesh::initializeContact() not implemented yet.");
return false; }
// Check a single OBB and its contents (recursively) against the halfspace,
// appending any penetrating faces to the insideFaces list.
void ContactTracker::HalfSpaceTriangleMesh::processBox
(const ContactGeometry::TriangleMesh& mesh,
const ContactGeometry::TriangleMesh::OBBTreeNode& node,
const Transform& X_HM, const UnitVec3& hsNormal_M, Real hsFaceHeight_M,
std::set<int>& insideFaces) const
{ // First check against the node's bounding box.
const OrientedBoundingBox& bounds = node.getBounds();
const Transform& X_MB = bounds.getTransform(); // box frame in mesh
const Vec3 p_BC = bounds.getSize()/2; // from box origin corner to center
// Express the half space normal in the box frame, then reflect it into
// the first (+,+,+) quadrant where it is the normal of a different
// but symmetric and more convenient half space.
const UnitVec3 octant1hsNormal_B = (~X_MB.R()*hsNormal_M).abs();
// Dot our octant1 radius p_BC with our octant1 normal to get
// the extent of the box from its center in the direction of the octant1
// reflection of the halfspace.
const Real extent = dot(p_BC, octant1hsNormal_B);
// Compute the height of the box center over the mesh origin,
// measured along the real halfspace normal.
const Vec3 boxCenter_M = X_MB*p_BC;
const Real boxCenterHeight_M = dot(boxCenter_M, hsNormal_M);
// Subtract the halfspace surface position to get the height of the
// box center over the halfspace.
const Real boxCenterHeight = boxCenterHeight_M - hsFaceHeight_M;
if (boxCenterHeight >= extent)
return; // no penetration
if (boxCenterHeight <= -extent) {
addAllTriangles(node, insideFaces); // box is entirely in halfspace
return;
}
// Box is partially penetrated into halfspace. If it is not a leaf node,
// check its children.
if (!node.isLeafNode()) {
processBox(mesh, node.getFirstChildNode(), X_HM, hsNormal_M,
hsFaceHeight_M, insideFaces);
processBox(mesh, node.getSecondChildNode(), X_HM, hsNormal_M,
hsFaceHeight_M, insideFaces);
return;
}
// This is a leaf OBB node that is penetrating, so some of its triangles
// may be penetrating.
const Array_<int>& triangles = node.getTriangles();
for (int i = 0; i < (int) triangles.size(); i++) {
for (int vx=0; vx < 3; ++vx) {
const int vertex = mesh.getFaceVertex(triangles[i], vx);
const Vec3& vertexPos = mesh.getVertexPosition(vertex);
const Real vertexHeight_M = dot(vertexPos, hsNormal_M);
if (vertexHeight_M < hsFaceHeight_M) {
insideFaces.insert(triangles[i]);
break; // done with this face
}
}
}
}
void ContactTracker::HalfSpaceTriangleMesh::addAllTriangles
(const ContactGeometry::TriangleMesh::OBBTreeNode& node,
std::set<int>& insideFaces) const
{
if (node.isLeafNode()) {
const Array_<int>& triangles = node.getTriangles();
for (int i = 0; i < (int) triangles.size(); i++)
insideFaces.insert(triangles[i]);
}
else {
addAllTriangles(node.getFirstChildNode(), insideFaces);
addAllTriangles(node.getSecondChildNode(), insideFaces);
}
}
//==============================================================================
// SPHERE - TRIANGLE MESH CONTACT TRACKER
//==============================================================================
// Cost is TODO
bool ContactTracker::SphereTriangleMesh::trackContact
(const Contact& priorStatus,
const Transform& X_GS,
const ContactGeometry& geoSphere,
const Transform& X_GM,
const ContactGeometry& geoMesh,
Real cutoff,
Contact& currentStatus) const
{
SimTK_ASSERT_ALWAYS
( ContactGeometry::Sphere::isInstance(geoSphere)
&& ContactGeometry::TriangleMesh::isInstance(geoMesh),
"ContactTracker::SphereTriangleMesh::trackContact()");
// We can't handle a "proximity" test, only penetration.
SimTK_ASSERT_ALWAYS(cutoff==0,
"ContactTracker::SphereTriangleMesh::trackContact()");
// No need for an expensive dynamic cast here; we know what we have.
const ContactGeometry::Sphere& sphere =
ContactGeometry::Sphere::getAs(geoSphere);
const ContactGeometry::TriangleMesh& mesh =
ContactGeometry::TriangleMesh::getAs(geoMesh);
// Transform giving mesh (M) frame in the sphere (S) frame.
const Transform X_SM = ~X_GS*X_GM;
// Want the sphere center measured and expressed in the mesh frame.
const Vec3 p_MC = (~X_SM).p();
std::set<int> insideFaces;
processBox(mesh, mesh.getOBBTreeNode(), p_MC, square(sphere.getRadius()),
insideFaces);
if (insideFaces.empty()) {
currentStatus.clear(); // not touching
return true; // successful return
}
currentStatus = TriangleMeshContact(priorStatus.getSurface1(),
priorStatus.getSurface2(),
X_SM,
std::set<int>(), insideFaces);
return true; // success
}
// Check a single OBB and its contents (recursively) against the sphere
// whose center location in M and radius squared is given, appending any
// penetrating faces to the insideFaces list.
void ContactTracker::SphereTriangleMesh::processBox
(const ContactGeometry::TriangleMesh& mesh,
const ContactGeometry::TriangleMesh::OBBTreeNode& node,
const Vec3& center_M, Real radius2,
std::set<int>& insideFaces) const
{ // First check against the node's bounding box.
const Vec3 nearest_M = node.getBounds().findNearestPoint(center_M);
if ((nearest_M-center_M).normSqr() >= radius2)
return; // no intersection possible
// Bounding box is penetrating. If it's not a leaf node, check its children.
if (!node.isLeafNode()) {
processBox(mesh, node.getFirstChildNode(), center_M, radius2,
insideFaces);
processBox(mesh, node.getSecondChildNode(), center_M, radius2,
insideFaces);
return;
}
// This is a leaf node that may be penetrating; check the triangles.
const Array_<int>& triangles = node.getTriangles();
for (unsigned i = 0; i < triangles.size(); i++) {
Vec2 uv;
Vec3 nearest_M = mesh.findNearestPointToFace
(center_M, triangles[i], uv);
if ((nearest_M-center_M).normSqr() < radius2)
insideFaces.insert(triangles[i]);
}
}
bool ContactTracker::SphereTriangleMesh::predictContact
(const Contact& priorStatus,
const Transform& X_GS1, const SpatialVec& V_GS1, const SpatialVec& A_GS1,
const ContactGeometry& surface1,
const Transform& X_GS2, const SpatialVec& V_GS2, const SpatialVec& A_GS2,
const ContactGeometry& surface2,
Real cutoff,
Real intervalOfInterest,
Contact& predictedStatus) const
{ SimTK_ASSERT_ALWAYS(!"implemented",
"ContactTracker::SphereTriangleMesh::predictContact() not implemented yet.");
return false; }
bool ContactTracker::SphereTriangleMesh::initializeContact
(const Transform& X_GS1, const SpatialVec& V_GS1,
const ContactGeometry& surface1,
const Transform& X_GS2, const SpatialVec& V_GS2,
const ContactGeometry& surface2,
Real cutoff,
Real intervalOfInterest,
Contact& contactStatus) const
{ SimTK_ASSERT_ALWAYS(!"implemented",
"ContactTracker::SphereTriangleMesh::initializeContact() not implemented yet.");
return false; }
//==============================================================================
// TRIANGLE MESH - TRIANGLE MESH CONTACT TRACKER
//==============================================================================
// Cost is TODO
bool ContactTracker::TriangleMeshTriangleMesh::trackContact
(const Contact& priorStatus,
const Transform& X_GM1,
const ContactGeometry& geoMesh1,
const Transform& X_GM2,
const ContactGeometry& geoMesh2,
Real cutoff,
Contact& currentStatus) const
{
SimTK_ASSERT_ALWAYS
( ContactGeometry::TriangleMesh::isInstance(geoMesh1)
&& ContactGeometry::TriangleMesh::isInstance(geoMesh2),
"ContactTracker::TriangleMeshTriangleMesh::trackContact()");
// We can't handle a "proximity" test, only penetration.
SimTK_ASSERT_ALWAYS(cutoff==0,
"ContactTracker::TriangleMeshTriangleMesh::trackContact()");
// No need for an expensive dynamic cast here; we know what we have.
const ContactGeometry::TriangleMesh& mesh1 =
ContactGeometry::TriangleMesh::getAs(geoMesh1);
const ContactGeometry::TriangleMesh& mesh2 =
ContactGeometry::TriangleMesh::getAs(geoMesh2);
// Transform giving mesh2 (M2) frame in the mesh1 (M1) frame.
const Transform X_M1M2 = ~X_GM1*X_GM2;
std::set<int> insideFaces1, insideFaces2;
// Get M2's bounding box in M1's frame.
const OrientedBoundingBox
mesh2Bounds_M1 = X_M1M2*mesh2.getOBBTreeNode().getBounds();
// Find the faces that are actually intersecting faces on the other
// surface (this doesn't yet include faces that may be completely buried).
findIntersectingFaces(mesh1, mesh2,
mesh1.getOBBTreeNode(), mesh2.getOBBTreeNode(),
mesh2Bounds_M1, X_M1M2, insideFaces1, insideFaces2);
// It should never be the case that one set of faces is empty and the
// other isn't, however it is conceivable that roundoff error could cause
// this to happen so we'll check both lists.
if (insideFaces1.empty() && insideFaces2.empty()) {
currentStatus.clear(); // not touching
return true; // successful return
}
// There was an intersection. We now need to identify every triangle and
// vertex of each mesh that is inside the other mesh. We found the border
// intersections above; now we have to fill in the buried faces.
findBuriedFaces(mesh1, mesh2, ~X_M1M2, insideFaces1);
findBuriedFaces(mesh2, mesh1, X_M1M2, insideFaces2);
currentStatus = TriangleMeshContact(priorStatus.getSurface1(),
priorStatus.getSurface2(),
X_M1M2,
insideFaces1, insideFaces2);
return true; // success
}
void ContactTracker::TriangleMeshTriangleMesh::
findIntersectingFaces
(const ContactGeometry::TriangleMesh& mesh1,
const ContactGeometry::TriangleMesh& mesh2,
const ContactGeometry::TriangleMesh::OBBTreeNode& node1,
const ContactGeometry::TriangleMesh::OBBTreeNode& node2,
const OrientedBoundingBox& node2Bounds_M1,
const Transform& X_M1M2,
std::set<int>& triangles1,
std::set<int>& triangles2) const
{ // See if the bounding boxes intersect.
if (!node1.getBounds().intersectsBox(node2Bounds_M1))
return;
// If either node is not a leaf node, process the children recursively.
if (!node1.isLeafNode()) {
if (!node2.isLeafNode()) {
const OrientedBoundingBox firstChildBounds =
X_M1M2*node2.getFirstChildNode().getBounds();
const OrientedBoundingBox secondChildBounds =
X_M1M2*node2.getSecondChildNode().getBounds();
findIntersectingFaces(mesh1, mesh2, node1.getFirstChildNode(), node2.getFirstChildNode(), firstChildBounds, X_M1M2, triangles1, triangles2);
findIntersectingFaces(mesh1, mesh2, node1.getFirstChildNode(), node2.getSecondChildNode(), secondChildBounds, X_M1M2, triangles1, triangles2);
findIntersectingFaces(mesh1, mesh2, node1.getSecondChildNode(), node2.getFirstChildNode(), firstChildBounds, X_M1M2, triangles1, triangles2);
findIntersectingFaces(mesh1, mesh2, node1.getSecondChildNode(), node2.getSecondChildNode(), secondChildBounds, X_M1M2, triangles1, triangles2);
}
else {
findIntersectingFaces(mesh1, mesh2, node1.getFirstChildNode(), node2, node2Bounds_M1, X_M1M2, triangles1, triangles2);
findIntersectingFaces(mesh1, mesh2, node1.getSecondChildNode(), node2, node2Bounds_M1, X_M1M2, triangles1, triangles2);
}
return;
}
else if (!node2.isLeafNode()) {
const OrientedBoundingBox firstChildBounds =
X_M1M2*node2.getFirstChildNode().getBounds();
const OrientedBoundingBox secondChildBounds =
X_M1M2*node2.getSecondChildNode().getBounds();
findIntersectingFaces(mesh1, mesh2, node1, node2.getFirstChildNode(), firstChildBounds, X_M1M2, triangles1, triangles2);
findIntersectingFaces(mesh1, mesh2, node1, node2.getSecondChildNode(), secondChildBounds, X_M1M2, triangles1, triangles2);
return;
}
// These are both leaf nodes, so check triangles for intersections.
const Array_<int>& node1triangles = node1.getTriangles();
const Array_<int>& node2triangles = node2.getTriangles();
for (unsigned i = 0; i < node2triangles.size(); i++) {
const int face2 = node2triangles[i];
Vec3 a1 = X_M1M2*mesh2.getVertexPosition(mesh2.getFaceVertex(face2, 0));
Vec3 a2 = X_M1M2*mesh2.getVertexPosition(mesh2.getFaceVertex(face2, 1));
Vec3 a3 = X_M1M2*mesh2.getVertexPosition(mesh2.getFaceVertex(face2, 2));
const Geo::Triangle A(a1,a2,a3);
for (unsigned j = 0; j < node1triangles.size(); j++) {
const int face1 = node1triangles[j];
const Vec3& b1 = mesh1.getVertexPosition(mesh1.getFaceVertex(face1, 0));
const Vec3& b2 = mesh1.getVertexPosition(mesh1.getFaceVertex(face1, 1));
const Vec3& b3 = mesh1.getVertexPosition(mesh1.getFaceVertex(face1, 2));
const Geo::Triangle B(b1,b2,b3);
if (A.overlapsTriangle(B))
{ // The triangles intersect.
triangles1.insert(face1);
triangles2.insert(face2);
}
}
}
}
static const int Outside = -1;
static const int Unknown = 0;
static const int Boundary = 1;
static const int Inside = 2;
void ContactTracker::TriangleMeshTriangleMesh::
findBuriedFaces(const ContactGeometry::TriangleMesh& mesh, // M
const ContactGeometry::TriangleMesh& otherMesh, // O
const Transform& X_OM,
std::set<int>& insideFaces) const
{
// Find which faces are inside.
// We're passed in the list of Boundary faces, that is, those faces of
// "mesh" that intersect faces of "otherMesh".
Array_<int> faceType(mesh.getNumFaces(), Unknown);
for (std::set<int>::iterator iter = insideFaces.begin();
iter != insideFaces.end(); ++iter)
faceType[*iter] = Boundary;
for (int i = 0; i < (int) faceType.size(); i++) {
if (faceType[i] == Unknown) {
// Trace a ray from its center to determine whether it is inside.
const Vec3 origin_O = X_OM * mesh.findCentroid(i);
const UnitVec3 direction_O = X_OM.R()* mesh.getFaceNormal(i);
Real distance;
int face;
Vec2 uv;
if ( otherMesh.intersectsRay(origin_O, direction_O, distance,
face, uv)
&& ~direction_O*otherMesh.getFaceNormal(face) > 0)
{
faceType[i] = Inside;
insideFaces.insert(i);
} else
faceType[i] = Outside;
// Recursively mark adjacent inside or outside Faces.
tagFaces(mesh, faceType, insideFaces, i, 0);
}
}
}
//TODO: the following method uses depth-first recursion to iterate through
//unmarked faces. For a large mesh this was observed to produce a stack
//overflow in OpenSim. Here we limit the recursion depth; after we get that
//deep we'll pop back out and do another expensive intersectsRay() test in
//the method above.
static const int MaxRecursionDepth = 500;
void ContactTracker::TriangleMeshTriangleMesh::
tagFaces(const ContactGeometry::TriangleMesh& mesh,
Array_<int>& faceType,
std::set<int>& triangles,
int index,
int depth) const
{
for (int i = 0; i < 3; i++) {
const int edge = mesh.getFaceEdge(index, i);
const int face = (mesh.getEdgeFace(edge, 0) == index
? mesh.getEdgeFace(edge, 1)
: mesh.getEdgeFace(edge, 0));
if (faceType[face] == Unknown) {
faceType[face] = faceType[index];
if (faceType[index] > 0)
triangles.insert(face);
if (depth < MaxRecursionDepth)
tagFaces(mesh, faceType, triangles, face, depth+1);
}
}
}
bool ContactTracker::TriangleMeshTriangleMesh::predictContact
(const Contact& priorStatus,
const Transform& X_GS1, const SpatialVec& V_GS1, const SpatialVec& A_GS1,
const ContactGeometry& surface1,
const Transform& X_GS2, const SpatialVec& V_GS2, const SpatialVec& A_GS2,
const ContactGeometry& surface2,
Real cutoff,
Real intervalOfInterest,
Contact& predictedStatus) const
{ SimTK_ASSERT_ALWAYS(!"implemented",
"ContactTracker::TriangleMeshTriangleMesh::predictContact() not implemented yet.");
return false; }
bool ContactTracker::TriangleMeshTriangleMesh::initializeContact
(const Transform& X_GS1, const SpatialVec& V_GS1,
const ContactGeometry& surface1,
const Transform& X_GS2, const SpatialVec& V_GS2,
const ContactGeometry& surface2,
Real cutoff,
Real intervalOfInterest,
Contact& contactStatus) const
{ SimTK_ASSERT_ALWAYS(!"implemented",
"ContactTracker::TriangleMeshTriangleMesh::initializeContact() not implemented yet.");
return false; }
//==============================================================================
// CONVEX IMPLICIT SURFACE PAIR CONTACT TRACKER
//==============================================================================
// This will return an elliptical point contact.
bool ContactTracker::ConvexImplicitPair::trackContact
(const Contact& priorStatus,
const Transform& X_GA,
const ContactGeometry& shapeA,
const Transform& X_GB,
const ContactGeometry& shapeB,
Real cutoff,
Contact& currentStatus) const
{
SimTK_ASSERT_ALWAYS
( shapeA.isConvex() && shapeA.isSmooth()
&& shapeB.isConvex() && shapeB.isSmooth(),
"ContactTracker::ConvexImplicitPair::trackContact()");
// We'll work in the shape A frame.
const Transform X_AB = ~X_GA*X_GB; // 63 flops
const Rotation& R_AB = X_AB.R();
// 1. Get a rough guess at the contact points P and Q and contact normal.
Vec3 pointP_A, pointQ_B; // on A and B, resp.
UnitVec3 norm_A;
int numMPRIters;
const bool mightBeContact = estimateConvexImplicitPairContactUsingMPR
(shapeA, shapeB, X_AB,
pointP_A, pointQ_B, norm_A, numMPRIters);
#ifdef MPR_DEBUG
std::cout << "MPR: " << (mightBeContact?"MAYBE":"NO") << std::endl;
std::cout << " P=" << X_GA*pointP_A << " Q=" << X_GB*pointQ_B << std::endl;
std::cout << " N=" << X_GA.R()*norm_A << std::endl;
#endif
if (!mightBeContact) {
currentStatus.clear(); // definitely not touching
return true; // successful return
}
// 2. Refine the contact points to near machine precision.
const Real accuracyRequested = SignificantReal;
Real accuracyAchieved; int numNewtonIters;
bool converged = refineImplicitPair(shapeA, pointP_A, shapeB, pointQ_B,
X_AB, accuracyRequested, accuracyAchieved, numNewtonIters);
const Vec3 pointQ_A = X_AB*pointQ_B; // Q on B, measured & expressed in A
// 3. Compute the curvatures and surface normals of the two surfaces at
// P and Q. Once we have the first normal we can check whether there was
// actually any contact and duck out early if not.
Rotation R_AP; Vec2 curvatureP;
shapeA.calcCurvature(pointP_A, curvatureP, R_AP);
// If the surfaces are in contact then the vector from Q on surface B
// (supposedly inside A) to P on surface A (supposedly inside B) should be
// aligned with the outward normal on A.
const Real depth = dot(pointP_A-pointQ_A, R_AP.z());
#ifdef MPR_DEBUG
printf("MPR %2d iters, Newton %2d iters->accuracy=%g depth=%g\n",
numMPRIters, numNewtonIters, accuracyAchieved, depth);
#endif
if (depth <= 0) {
currentStatus.clear(); // not touching
return true; // successful return
}
// The surfaces are in contact.
Rotation R_BQ; Vec2 curvatureQ;
shapeB.calcCurvature(pointQ_B, curvatureQ, R_BQ);
const UnitVec3 maxDirB_A(R_AB*R_BQ.x()); // re-express in A
// 4. Compute the effective contact frame C and corresponding relative
// curvatures.
Transform X_AC; Vec2 curvatureC;
// Define the contact frame origin to be at the midpoint of P and Q.
X_AC.updP() = (pointP_A+pointQ_A)/2;
// Determine the contact frame orientations and composite curvatures.
ContactGeometry::combineParaboloids(R_AP, curvatureP,
maxDirB_A, curvatureQ,
X_AC.updR(), curvatureC);
// 5. Return the elliptical point contact for force generation.
currentStatus = EllipticalPointContact(priorStatus.getSurface1(),
priorStatus.getSurface2(),
X_AB, X_AC, curvatureC, depth);
return true; // success
}
bool ContactTracker::ConvexImplicitPair::predictContact
(const Contact& priorStatus,
const Transform& X_GS1, const SpatialVec& V_GS1, const SpatialVec& A_GS1,
const ContactGeometry& surface1,
const Transform& X_GS2, const SpatialVec& V_GS2, const SpatialVec& A_GS2,
const ContactGeometry& surface2,
Real cutoff,
Real intervalOfInterest,
Contact& predictedStatus) const
{ SimTK_ASSERT_ALWAYS(!"implemented",
"ContactTracker::ConvexImplicitPair::predictContact() not implemented yet.");
return false; }
bool ContactTracker::ConvexImplicitPair::initializeContact
(const Transform& X_GS1, const SpatialVec& V_GS1,
const ContactGeometry& surface1,
const Transform& X_GS2, const SpatialVec& V_GS2,
const ContactGeometry& surface2,
Real cutoff,
Real intervalOfInterest,
Contact& contactStatus) const
{ SimTK_ASSERT_ALWAYS(!"implemented",
"ContactTracker::ConvexImplicitPair::initializeContact() not implemented yet.");
return false; }
//==============================================================================
// GENERAL IMPLICIT SURFACE PAIR CONTACT TRACKER
//==============================================================================
// This will return an elliptical point contact. TODO: should return a set
// of contacts.
//TODO: not implemented yet -- this is just the Convex-convex code here.
bool ContactTracker::GeneralImplicitPair::trackContact
(const Contact& priorStatus,
const Transform& X_GA,
const ContactGeometry& shapeA,
const Transform& X_GB,
const ContactGeometry& shapeB,
Real cutoff,
Contact& currentStatus) const
{
SimTK_ASSERT_ALWAYS
( shapeA.isSmooth() && shapeB.isSmooth(),
"ContactTracker::GeneralImplicitPair::trackContact()");
// TODO: this won't work unless the shapes are actually convex.
return ConvexImplicitPair(shapeA.getTypeId(),shapeB.getTypeId())
.trackContact(priorStatus, X_GA, shapeA, X_GB, shapeB,
cutoff, currentStatus);
}
bool ContactTracker::GeneralImplicitPair::predictContact
(const Contact& priorStatus,
const Transform& X_GS1, const SpatialVec& V_GS1, const SpatialVec& A_GS1,
const ContactGeometry& surface1,
const Transform& X_GS2, const SpatialVec& V_GS2, const SpatialVec& A_GS2,
const ContactGeometry& surface2,
Real cutoff,
Real intervalOfInterest,
Contact& predictedStatus) const
{ SimTK_ASSERT_ALWAYS(!"implemented",
"ContactTracker::GeneralImplicitPair::predictContact() not implemented yet.");
return false; }
bool ContactTracker::GeneralImplicitPair::initializeContact
(const Transform& X_GS1, const SpatialVec& V_GS1,
const ContactGeometry& surface1,
const Transform& X_GS2, const SpatialVec& V_GS2,
const ContactGeometry& surface2,
Real cutoff,
Real intervalOfInterest,
Contact& contactStatus) const
{ SimTK_ASSERT_ALWAYS(!"implemented",
"ContactTracker::GeneralImplicitPair::initializeContact() not implemented yet.");
return false; }
} // namespace SimTK
| 43.691216 | 155 | 0.607828 | [
"mesh",
"object",
"shape",
"vector",
"transform"
] |
911b55ed19fcc19cac972737cfae788aa3efea25 | 1,733 | cpp | C++ | RT3D/RT3D/SDL GL Triangle/Environment.cpp | RichardsonDaniel/BSc-University-Coursework | f66351152826cafd4d0064c26efb7dc9c74f6ce6 | [
"MIT"
] | null | null | null | RT3D/RT3D/SDL GL Triangle/Environment.cpp | RichardsonDaniel/BSc-University-Coursework | f66351152826cafd4d0064c26efb7dc9c74f6ce6 | [
"MIT"
] | null | null | null | RT3D/RT3D/SDL GL Triangle/Environment.cpp | RichardsonDaniel/BSc-University-Coursework | f66351152826cafd4d0064c26efb7dc9c74f6ce6 | [
"MIT"
] | null | null | null | #include "Environment.h"
Environment::Environment(std::string typeName, char *fnameTexture, char *fobj, GLfloat idx, GLfloat idy, GLfloat idz, GLfloat iScaleX, GLfloat iScaleY, GLfloat iScaleZ, GLfloat iRotate, GLuint newShaderProgram)
{
// Set name of object
type = typeName;
// Initialise position data
pos.x = idx;
pos.y = idy;
pos.z = idz;
// Initialise scale data
scale.x = iScaleX;
scale.y = iScaleY;
scale.z = iScaleZ;
rotateAngle = iRotate; // Set rotation
shaderProgram = newShaderProgram; // Set shader program
// Load object data including texture and create mesh
std::vector<GLfloat> verts;
std::vector<GLfloat> norms;
std::vector<GLfloat> tex_coords;
std::vector<GLuint> indices;
rt3d::loadObj(fobj, verts, norms, tex_coords, indices);
GLuint size = indices.size();
meshIndexCount = size;
texture = rt3d::loadBitmap(fnameTexture);
meshObject = rt3d::createMesh(verts.size()/3, verts.data(), nullptr, norms.data(), tex_coords.data(), size, indices.data());
r.setRect(pos.x, pos.y, scale.x, scale.y); // Set up collision rectangle
}
Environment::~Environment(void)
{
}
void Environment::draw(std::stack<glm::mat4> &mvStack)
{
glBindTexture(GL_TEXTURE_2D, texture);
mvStack.push(mvStack.top());
mvStack.top() = glm::rotate(mvStack.top(), rotateAngle, glm::vec3(1.0f, 0.0f, 0.0f));
mvStack.top() = glm::translate(mvStack.top(), glm::vec3(pos.x, pos.y, pos.z));
mvStack.top() = glm::scale(mvStack.top(), glm::vec3(scale.x, scale.y, scale.z));
rt3d::setUniformMatrix4fv(shaderProgram, "modelview", glm::value_ptr(mvStack.top()));
rt3d::drawIndexedMesh(meshObject,meshIndexCount,GL_TRIANGLES);
mvStack.pop();
}
rect Environment::getRect(){ // Return collision rectangle
return r;
} | 30.403509 | 210 | 0.71783 | [
"mesh",
"object",
"vector"
] |
911c613ca272c965239dc30a2fa357a7666236f6 | 950 | cpp | C++ | cpp/src/exercise/e0100/e0083.cpp | ajz34/LeetCodeLearn | 70ff8a3c17199a100819b356735cd9b13ff166a7 | [
"MIT"
] | null | null | null | cpp/src/exercise/e0100/e0083.cpp | ajz34/LeetCodeLearn | 70ff8a3c17199a100819b356735cd9b13ff166a7 | [
"MIT"
] | null | null | null | cpp/src/exercise/e0100/e0083.cpp | ajz34/LeetCodeLearn | 70ff8a3c17199a100819b356735cd9b13ff166a7 | [
"MIT"
] | null | null | null | // https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/
#include "extern.h"
class S0083 {
public:
ListNode* deleteDuplicates(ListNode* head) {
if (!head) return head;
ListNode* post = new ListNode(head->val == 0 ? 1 : 0);
post->next = head;
ListNode* pl = post; ListNode* pr = post->next;
while (pl->next) {
while (pr->next && pl->next->val == pr->next->val) pr = pr->next;
pl->next = pr; pl = pr;
if (pr->next) pr = pr->next;
}
return post->next;
}
};
TEST(e0100, e0083) {
ListNode* head; vector<int> ans;
head = new ListNode(str_to_vec<int>("[1,1,2]"));
ans = str_to_vec<int>("[1,2]");
ASSERT_THAT(S0083().deleteDuplicates(head)->to_vector(), ans);
head = new ListNode(str_to_vec<int>("[1,1,2,3,3]"));
ans = str_to_vec<int>("[1,2,3]");
ASSERT_THAT(S0083().deleteDuplicates(head)->to_vector(), ans);
}
| 31.666667 | 77 | 0.568421 | [
"vector"
] |
9122c376a47dc36d83c3c72230b8279a890896cd | 697 | hpp | C++ | src/mesh/basic_mesh.hpp | dbeurle/neon | 63cd2929a6eaaa0e1654c729cd35a9a52a706962 | [
"MIT"
] | 9 | 2018-07-12T17:06:33.000Z | 2021-11-20T23:13:26.000Z | src/mesh/basic_mesh.hpp | dbeurle/neon | 63cd2929a6eaaa0e1654c729cd35a9a52a706962 | [
"MIT"
] | 119 | 2016-06-22T07:36:04.000Z | 2019-03-10T19:38:12.000Z | src/mesh/basic_mesh.hpp | dbeurle/neon | 63cd2929a6eaaa0e1654c729cd35a9a52a706962 | [
"MIT"
] | 9 | 2017-10-08T16:51:38.000Z | 2021-03-15T08:08:04.000Z |
#pragma once
/// @file
#include "mesh/nodal_coordinates.hpp"
#include "mesh/basic_submesh.hpp"
#include <map>
namespace neon
{
/// basic_mesh is a basic mesh definition, with nodes and associated volume
/// meshes. This container does not define a notion of boundary or volume meshes.
/// It holds nodes and element type collections, defining type and nodal
/// connectivities.
class basic_mesh : public nodal_coordinates
{
public:
basic_mesh(json const& mesh_file);
/// \return mesh matching a specific name
[[nodiscard]] std::vector<basic_submesh> const& meshes(std::string const& name) const;
protected:
std::map<std::string, std::vector<basic_submesh>> meshes_map;
};
}
| 24.034483 | 90 | 0.736011 | [
"mesh",
"vector"
] |
9126aab0459a56bed692ae66a4f847298075340c | 1,089 | cpp | C++ | codes/leetcode/PalindromePartitioning.cpp | smmehrab/problem-solving | 4aeab1673f18d3270ee5fc9b64ed6805eacf4af5 | [
"MIT"
] | null | null | null | codes/leetcode/PalindromePartitioning.cpp | smmehrab/problem-solving | 4aeab1673f18d3270ee5fc9b64ed6805eacf4af5 | [
"MIT"
] | null | null | null | codes/leetcode/PalindromePartitioning.cpp | smmehrab/problem-solving | 4aeab1673f18d3270ee5fc9b64ed6805eacf4af5 | [
"MIT"
] | null | null | null | /*
************************************************
username : smmehrab
fullname : s.m.mehrabul islam
email : mehrab.24csedu.001@gmail.com
institute : university of dhaka, bangladesh
session : 2017-2018
************************************************
*/
class Solution {
private:
int n;
string s;
vector<vector<string>> allPartitionings;
vector<string> partitioning;
vector<vector<bool>> dp;
void solve(int i) {
if(i==n){
allPartitionings.push_back(partitioning);
return ;
}
for(int j=i; j<n; ++j){
if(s[i] == s[j] && (j-i<=2 || dp[i+1][j-1])){
dp[i][j] = true;
partitioning.push_back(s.substr(i, j-i+1));
solve(j+1);
partitioning.pop_back();
}
}
}
public:
vector<vector<string>> partition(string s) {
this->s = s;
this->n = s.size();
this->dp = vector(n, vector<bool>(n, false));
if(n!=0) solve(0);
return allPartitionings;
}
}; | 25.928571 | 59 | 0.455464 | [
"vector"
] |
91314a5bcb7e13f6f89b04453c29571f41cd95b3 | 4,975 | cc | C++ | ash/app_list/app_list_test_api.cc | blueboxd/chromium-legacy | 07223bc94bd97499909c9ed3c3f5769d718fe2e0 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 76 | 2020-09-02T03:05:41.000Z | 2022-03-30T04:40:55.000Z | ash/app_list/app_list_test_api.cc | blueboxd/chromium-legacy | 07223bc94bd97499909c9ed3c3f5769d718fe2e0 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 45 | 2020-09-02T03:21:37.000Z | 2022-03-31T22:19:45.000Z | ash/app_list/app_list_test_api.cc | blueboxd/chromium-legacy | 07223bc94bd97499909c9ed3c3f5769d718fe2e0 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 8 | 2020-07-22T18:49:18.000Z | 2022-02-08T10:27:16.000Z | // Copyright 2020 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 "ash/public/cpp/test/app_list_test_api.h"
#include <string>
#include <vector>
#include "ash/app_list/app_list_controller_impl.h"
#include "ash/app_list/app_list_presenter_impl.h"
#include "ash/app_list/model/app_list_folder_item.h"
#include "ash/app_list/model/app_list_item.h"
#include "ash/app_list/model/app_list_model.h"
#include "ash/app_list/views/app_list_item_view.h"
#include "ash/app_list/views/app_list_main_view.h"
#include "ash/app_list/views/app_list_view.h"
#include "ash/app_list/views/apps_container_view.h"
#include "ash/app_list/views/contents_view.h"
#include "ash/app_list/views/paged_apps_grid_view.h"
#include "ash/shell.h"
#include "ui/views/view_model.h"
namespace ash {
namespace {
PagedAppsGridView* GetAppsGridView() {
AppListView* app_list_view =
Shell::Get()->app_list_controller()->presenter()->GetView();
return AppListView::TestApi(app_list_view).GetRootAppsGridView();
}
AppsContainerView* GetAppsContainerView() {
return Shell::Get()
->app_list_controller()
->presenter()
->GetView()
->app_list_main_view()
->contents_view()
->apps_container_view();
}
AppListModel* GetAppListModel() {
return Shell::Get()->app_list_controller()->GetModel();
}
} // namespace
AppListTestApi::AppListTestApi() = default;
AppListTestApi::~AppListTestApi() = default;
bool AppListTestApi::HasApp(const std::string& app_id) {
return GetAppListModel()->FindItem(app_id);
}
std::vector<std::string> AppListTestApi::GetTopLevelViewIdList() {
std::vector<std::string> id_list;
auto* view_model = GetAppsGridView()->view_model();
for (int i = 0; i < view_model->view_size(); ++i) {
AppListItem* app_list_item = view_model->view_at(i)->item();
if (app_list_item) {
id_list.push_back(app_list_item->id());
}
}
return id_list;
}
std::string AppListTestApi::CreateFolderWithApps(
const std::vector<std::string>& apps) {
// Only create a folder if there are two or more apps.
DCHECK_GE(apps.size(), 2u);
AppListModel* model = GetAppListModel();
// Create a folder using the first two apps, and add the others to the folder
// iteratively.
std::string folder_id = model->MergeItems(apps[0], apps[1]);
// Return early if MergeItems failed.
if (folder_id.empty())
return "";
for (size_t i = 2; i < apps.size(); ++i)
model->MergeItems(folder_id, apps[i]);
return folder_id;
}
std::string AppListTestApi::GetFolderId(const std::string& app_id) {
return GetAppListModel()->FindItem(app_id)->folder_id();
}
std::vector<std::string> AppListTestApi::GetAppIdsInFolder(
const std::string& folder_id) {
AppListItem* folder_item = GetAppListModel()->FindItem(folder_id);
DCHECK(folder_item->is_folder());
AppListItemList* folder_list =
static_cast<AppListFolderItem*>(folder_item)->item_list();
std::vector<std::string> id_list;
for (size_t i = 0; i < folder_list->item_count(); ++i)
id_list.push_back(folder_list->item_at(i)->id());
return id_list;
}
void AppListTestApi::MoveItemToPosition(const std::string& item_id,
const size_t to_index) {
AppListItem* app_item = GetAppListModel()->FindItem(item_id);
const std::string folder_id = app_item->folder_id();
AppListItemList* item_list;
std::vector<std::string> top_level_id_list = GetTopLevelViewIdList();
// The app should be either at the top level or in a folder.
if (folder_id.empty()) {
// The app is at the top level.
item_list = GetAppListModel()->top_level_item_list();
} else {
// The app is in the folder with |folder_id|.
item_list = GetAppListModel()->FindFolderItem(folder_id)->item_list();
}
size_t from_index = 0;
item_list->FindItemIndex(item_id, &from_index);
item_list->MoveItem(from_index, to_index);
}
void AppListTestApi::AddPageBreakItemAfterId(const std::string& item_id) {
auto* model = GetAppListModel();
model->AddPageBreakItemAfter(model->FindItem(item_id));
}
int AppListTestApi::GetTopListItemCount() {
return GetAppListModel()->top_level_item_list()->item_count();
}
PaginationModel* AppListTestApi::GetPaginationModel() {
return GetAppsGridView()->pagination_model();
}
void AppListTestApi::UpdatePagedViewStructure() {
GetAppsGridView()->UpdatePagedViewStructure();
}
views::View* AppListTestApi::GetViewForAppListSort(AppListSortOrder order) {
views::View* sort_button_container =
GetAppsContainerView()->sort_button_container_for_test();
switch (order) {
case AppListSortOrder::kCustom:
NOTREACHED();
return nullptr;
case AppListSortOrder::kNameAlphabetical:
return sort_button_container->children()[0];
case AppListSortOrder::kNameReverseAlphabetical:
return sort_button_container->children()[1];
}
}
} // namespace ash
| 32.305195 | 79 | 0.723618 | [
"vector",
"model"
] |
913a5989729813f109980dde518be79082682ba4 | 2,256 | cpp | C++ | clone-engine/main.cpp | babu-thomas/clone-engine | e430b2ee172447595e6e1f881b93cc982db573f6 | [
"MIT"
] | null | null | null | clone-engine/main.cpp | babu-thomas/clone-engine | e430b2ee172447595e6e1f881b93cc982db573f6 | [
"MIT"
] | null | null | null | clone-engine/main.cpp | babu-thomas/clone-engine | e430b2ee172447595e6e1f881b93cc982db573f6 | [
"MIT"
] | null | null | null | #include <iostream>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include "src/graphics/shader.h"
#include "src/graphics/window.h"
#include "src/graphics/buffers/buffer.h"
#include "src/graphics/buffers/indexbuffer.h"
#include "src/graphics/buffers/vertexarray.h"
#include <vector>
// To enable NVIDIA Graphics card
//extern "C" {
// _declspec(dllexport) unsigned long NvOptimusEnablement = 0x00000001;
//}
int main()
{
using namespace clone;
using namespace graphics;
Window window("Clone Engine!", 800, 600);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
Shader shader(".\\src\\shaders\\basic_shader.vert", ".\\src\\shaders\\basic_shader.frag");
shader.enable();
glm::mat4 ortho = glm::ortho(0.0f, 20.0f, 0.0f, 20.0f);
shader.setUniformMat4("pr_matrix", ortho);
GLfloat vertices[] = {
5.0f, 5.0f, 0.0f,
5.0f, 15.0f, 0.0f,
15.0f, 15.0f, 0.0f,
15.0f, 5.0f, 0.0f
};
GLushort indices[] = {
0, 1, 3,
1, 2, 3
};
GLfloat colors1[] = {
1.0f, 0.0f, 0.0f,
1.0f, 0.0f, 0.0f,
1.0f, 0.0f, 0.0f,
1.0f, 0.0f, 0.0f
};
GLfloat colors2[] = {
0.0f, 1.0f, 0.0f,
0.0f, 1.0f, 0.0f,
0.0f, 1.0f, 0.0f,
0.0f, 1.0f, 0.0f
};
VertexArray sprite1, sprite2;
IndexBuffer ibo(indices, 6);
sprite1.addBuffer(new Buffer(vertices, 4 * 3, 3), 0);
sprite1.addBuffer(new Buffer(colors1, 4 * 3, 3), 1);
sprite2.addBuffer(new Buffer(vertices, 4 * 3, 3), 0);
sprite2.addBuffer(new Buffer(colors2, 4 * 3, 3), 1);
while (!window.closed())
{
window.clear();
glm::mat4 trans;
trans = glm::translate(trans, glm::vec3(5.0f, 5.0f, 0.0f));
glm::mat4 trans2;
trans2 = glm::translate(trans2, glm::vec3(-5.0f, -5.0f, 0.0f));
glm::vec2 mouse = window.getMousePosition();
float light_pos_x = mouse.x * 20 / 800;
float light_pos_y = 20 - mouse.y * 20 / 600;
shader.setUniform2f("light_pos", glm::vec2(light_pos_x, light_pos_y));
sprite1.bind();
ibo.bind();
shader.setUniformMat4("ml_matrix", trans);
glDrawElements(GL_TRIANGLES, ibo.getCount(), GL_UNSIGNED_SHORT, 0);
sprite1.unbind();
sprite2.bind();
ibo.bind();
shader.setUniformMat4("ml_matrix", trans2);
glDrawElements(GL_TRIANGLES, ibo.getCount(), GL_UNSIGNED_SHORT, 0);
sprite2.unbind();
window.update();
}
return 0;
} | 23.5 | 91 | 0.653812 | [
"vector"
] |
914c5066facc2c133b09b04cb6b739207ceb131d | 19,277 | cc | C++ | chrome/browser/prerender/prerender_local_predictor.cc | codenote/chromium-test | 0637af0080f7e80bf7d20b29ce94c5edc817f390 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2018-03-10T13:08:49.000Z | 2018-03-10T13:08:49.000Z | chrome/browser/prerender/prerender_local_predictor.cc | codenote/chromium-test | 0637af0080f7e80bf7d20b29ce94c5edc817f390 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/prerender/prerender_local_predictor.cc | codenote/chromium-test | 0637af0080f7e80bf7d20b29ce94c5edc817f390 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2020-11-04T07:25:45.000Z | 2020-11-04T07:25:45.000Z | // Copyright (c) 2012 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 "chrome/browser/prerender/prerender_local_predictor.h"
#include <ctype.h>
#include <algorithm>
#include <map>
#include <set>
#include <string>
#include <utility>
#include "base/metrics/field_trial.h"
#include "base/metrics/histogram.h"
#include "base/timer.h"
#include "chrome/browser/history/history_database.h"
#include "chrome/browser/history/history_db_task.h"
#include "chrome/browser/history/history_service.h"
#include "chrome/browser/history/history_service_factory.h"
#include "chrome/browser/prerender/prerender_histograms.h"
#include "chrome/browser/prerender/prerender_manager.h"
#include "chrome/browser/profiles/profile.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/common/page_transition_types.h"
#include "crypto/secure_hash.h"
#include "grit/browser_resources.h"
#include "ui/base/resource/resource_bundle.h"
using content::BrowserThread;
using content::PageTransition;
using history::URLID;
namespace prerender {
namespace {
static const size_t kURLHashSize = 5;
// Task to lookup the URL for a given URLID.
class GetURLForURLIDTask : public history::HistoryDBTask {
public:
GetURLForURLIDTask(URLID url_id, base::Callback<void(const GURL&)> callback)
: url_id_(url_id),
success_(false),
callback_(callback),
start_time_(base::Time::Now()) {
}
virtual bool RunOnDBThread(history::HistoryBackend* backend,
history::HistoryDatabase* db) OVERRIDE {
history::URLRow url_row;
success_ = db->GetURLRow(url_id_, &url_row);
if (success_)
url_ = url_row.url();
return true;
}
virtual void DoneRunOnMainThread() OVERRIDE {
if (success_) {
callback_.Run(url_);
UMA_HISTOGRAM_CUSTOM_TIMES("Prerender.LocalPredictorURLLookupTime",
base::Time::Now() - start_time_,
base::TimeDelta::FromMilliseconds(10),
base::TimeDelta::FromSeconds(10),
50);
}
}
private:
virtual ~GetURLForURLIDTask() {}
URLID url_id_;
bool success_;
base::Callback<void(const GURL&)> callback_;
base::Time start_time_;
GURL url_;
DISALLOW_COPY_AND_ASSIGN(GetURLForURLIDTask);
};
// Task to load history from the visit database on startup.
class GetVisitHistoryTask : public history::HistoryDBTask {
public:
GetVisitHistoryTask(PrerenderLocalPredictor* local_predictor,
int max_visits)
: local_predictor_(local_predictor),
max_visits_(max_visits),
visit_history_(new std::vector<history::BriefVisitInfo>) {
}
virtual bool RunOnDBThread(history::HistoryBackend* backend,
history::HistoryDatabase* db) OVERRIDE {
db->GetBriefVisitInfoOfMostRecentVisits(max_visits_, visit_history_.get());
return true;
}
virtual void DoneRunOnMainThread() OVERRIDE {
local_predictor_->OnGetInitialVisitHistory(visit_history_.Pass());
}
private:
virtual ~GetVisitHistoryTask() {}
PrerenderLocalPredictor* local_predictor_;
int max_visits_;
scoped_ptr<std::vector<history::BriefVisitInfo> > visit_history_;
DISALLOW_COPY_AND_ASSIGN(GetVisitHistoryTask);
};
// Maximum visit history to retrieve from the visit database.
const int kMaxVisitHistory = 100 * 1000;
// Visit history size at which to trigger pruning, and number of items to prune.
const int kVisitHistoryPruneThreshold = 120 * 1000;
const int kVisitHistoryPruneAmount = 20 * 1000;
const int kMaxLocalPredictionTimeMs = 300 * 1000;
const int kMinLocalPredictionTimeMs = 500;
bool IsBackForward(PageTransition transition) {
return (transition & content::PAGE_TRANSITION_FORWARD_BACK) != 0;
}
bool IsHomePage(PageTransition transition) {
return (transition & content::PAGE_TRANSITION_HOME_PAGE) != 0;
}
bool IsIntermediateRedirect(PageTransition transition) {
return (transition & content::PAGE_TRANSITION_CHAIN_END) == 0;
}
bool ShouldExcludeTransitionForPrediction(PageTransition transition) {
return IsBackForward(transition) || IsHomePage(transition) ||
IsIntermediateRedirect(transition);
}
base::Time GetCurrentTime() {
return base::Time::Now();
}
bool StrCaseStr(std::string haystack, std::string needle) {
std::transform(haystack.begin(), haystack.end(), haystack.begin(), ::tolower);
std::transform(needle.begin(), needle.end(), needle.begin(), ::tolower);
return haystack.find(needle) != std::string::npos;
}
bool IsExtendedRootURL(const GURL& url) {
const std::string& path = url.path();
return path == "/index.html" || path == "/home.html" ||
path == "/main.html" ||
path == "/index.htm" || path == "/home.htm" || path == "/main.htm" ||
path == "/index.php" || path == "/home.php" || path == "/main.php" ||
path == "/index.asp" || path == "/home.asp" || path == "/main.asp" ||
path == "/index.py" || path == "/home.py" || path == "/main.py" ||
path == "/index.pl" || path == "/home.pl" || path == "/main.pl";
}
bool IsRootPageURL(const GURL& url) {
return (url.path() == "/" || url.path() == "" || IsExtendedRootURL(url)) &&
(!url.has_query()) && (!url.has_ref());
}
int64 URLHashToInt64(const unsigned char* data) {
COMPILE_ASSERT(kURLHashSize < sizeof(int64), url_hash_must_fit_in_int64);
int64 value = 0;
memcpy(&value, data, kURLHashSize);
return value;
}
int64 GetInt64URLHashForURL(const GURL& url) {
COMPILE_ASSERT(kURLHashSize < sizeof(int64), url_hash_must_fit_in_int64);
scoped_ptr<crypto::SecureHash> hash(
crypto::SecureHash::Create(crypto::SecureHash::SHA256));
int64 hash_value = 0;
const char* url_string = url.spec().c_str();
hash->Update(url_string, strlen(url_string));
hash->Finish(&hash_value, kURLHashSize);
return hash_value;
}
} // namespace
struct PrerenderLocalPredictor::PrerenderData {
PrerenderData(URLID url_id, const GURL& url, double priority,
base::Time start_time)
: url_id(url_id),
url(url),
priority(priority),
start_time(start_time) {
}
URLID url_id;
GURL url;
double priority;
// For expiration purposes, this is a synthetic start time consisting either
// of the actual start time, or of the last time the page was re-requested
// for prerendering - 10 seconds (unless the original request came after
// that). This is to emulate the effect of re-prerendering a page that is
// about to expire, because it was re-requested for prerendering a second
// time after the actual prerender being kept around.
base::Time start_time;
// The actual time this page was last requested for prerendering.
base::Time actual_start_time;
private:
DISALLOW_IMPLICIT_CONSTRUCTORS(PrerenderData);
};
PrerenderLocalPredictor::PrerenderLocalPredictor(
PrerenderManager* prerender_manager)
: prerender_manager_(prerender_manager),
is_visit_database_observer_(false) {
RecordEvent(EVENT_CONSTRUCTED);
if (MessageLoop::current()) {
timer_.Start(FROM_HERE,
base::TimeDelta::FromMilliseconds(kInitDelayMs),
this,
&PrerenderLocalPredictor::Init);
RecordEvent(EVENT_INIT_SCHEDULED);
}
static const size_t kChecksumHashSize = 32;
base::RefCountedStaticMemory* url_whitelist_data =
ResourceBundle::GetSharedInstance().LoadDataResourceBytes(
IDR_PRERENDER_URL_WHITELIST);
size_t size = url_whitelist_data->size();
const unsigned char* front = url_whitelist_data->front();
if (size < kChecksumHashSize ||
(size - kChecksumHashSize) % kURLHashSize != 0) {
RecordEvent(EVENT_URL_WHITELIST_ERROR);
return;
}
scoped_ptr<crypto::SecureHash> hash(
crypto::SecureHash::Create(crypto::SecureHash::SHA256));
hash->Update(front + kChecksumHashSize, size - kChecksumHashSize);
char hash_value[kChecksumHashSize];
hash->Finish(hash_value, kChecksumHashSize);
if (memcmp(hash_value, front, kChecksumHashSize)) {
RecordEvent(EVENT_URL_WHITELIST_ERROR);
return;
}
for (const unsigned char* p = front + kChecksumHashSize;
p < front + size;
p += kURLHashSize) {
url_whitelist_.insert(URLHashToInt64(p));
}
RecordEvent(EVENT_URL_WHITELIST_OK);
}
PrerenderLocalPredictor::~PrerenderLocalPredictor() {
Shutdown();
}
void PrerenderLocalPredictor::Shutdown() {
timer_.Stop();
if (is_visit_database_observer_) {
HistoryService* history = GetHistoryIfExists();
CHECK(history);
history->RemoveVisitDatabaseObserver(this);
is_visit_database_observer_ = false;
}
}
void PrerenderLocalPredictor::OnAddVisit(const history::BriefVisitInfo& info) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
RecordEvent(EVENT_ADD_VISIT);
if (!visit_history_.get())
return;
visit_history_->push_back(info);
if (static_cast<int>(visit_history_->size()) > kVisitHistoryPruneThreshold) {
visit_history_->erase(visit_history_->begin(),
visit_history_->begin() + kVisitHistoryPruneAmount);
}
RecordEvent(EVENT_ADD_VISIT_INITIALIZED);
if (current_prerender_.get() &&
current_prerender_->url_id == info.url_id &&
IsPrerenderStillValid(current_prerender_.get())) {
UMA_HISTOGRAM_CUSTOM_TIMES(
"Prerender.LocalPredictorTimeUntilUsed",
GetCurrentTime() - current_prerender_->actual_start_time,
base::TimeDelta::FromMilliseconds(10),
base::TimeDelta::FromMilliseconds(kMaxLocalPredictionTimeMs),
50);
last_swapped_in_prerender_.reset(current_prerender_.release());
RecordEvent(EVENT_ADD_VISIT_PRERENDER_IDENTIFIED);
}
if (ShouldExcludeTransitionForPrediction(info.transition))
return;
RecordEvent(EVENT_ADD_VISIT_RELEVANT_TRANSITION);
base::TimeDelta max_age =
base::TimeDelta::FromMilliseconds(kMaxLocalPredictionTimeMs);
base::TimeDelta min_age =
base::TimeDelta::FromMilliseconds(kMinLocalPredictionTimeMs);
std::set<URLID> next_urls_currently_found;
std::map<URLID, int> next_urls_num_found;
int num_occurrences_of_current_visit = 0;
base::Time last_visited;
URLID best_next_url = 0;
int best_next_url_count = 0;
const std::vector<history::BriefVisitInfo>& visits = *(visit_history_.get());
for (int i = 0; i < static_cast<int>(visits.size()); i++) {
if (!ShouldExcludeTransitionForPrediction(visits[i].transition)) {
if (visits[i].url_id == info.url_id) {
last_visited = visits[i].time;
num_occurrences_of_current_visit++;
next_urls_currently_found.clear();
continue;
}
if (!last_visited.is_null() &&
last_visited > visits[i].time - max_age &&
last_visited < visits[i].time - min_age) {
next_urls_currently_found.insert(visits[i].url_id);
}
}
if (i == static_cast<int>(visits.size()) - 1 ||
visits[i+1].url_id == info.url_id) {
for (std::set<URLID>::iterator it = next_urls_currently_found.begin();
it != next_urls_currently_found.end();
++it) {
std::pair<std::map<URLID, int>::iterator, bool> insert_ret =
next_urls_num_found.insert(std::pair<URLID, int>(*it, 0));
std::map<URLID, int>::iterator num_found_it = insert_ret.first;
num_found_it->second++;
if (num_found_it->second > best_next_url_count) {
best_next_url_count = num_found_it->second;
best_next_url = *it;
}
}
}
}
// Only consider a candidate next page for prerendering if it was viewed
// at least twice, and at least 10% of the time.
if (num_occurrences_of_current_visit > 0 &&
best_next_url_count > 1 &&
best_next_url_count * 10 >= num_occurrences_of_current_visit) {
RecordEvent(EVENT_ADD_VISIT_IDENTIFIED_PRERENDER_CANDIDATE);
double priority = static_cast<double>(best_next_url_count) /
static_cast<double>(num_occurrences_of_current_visit);
if (ShouldReplaceCurrentPrerender(priority)) {
RecordEvent(EVENT_START_URL_LOOKUP);
HistoryService* history = GetHistoryIfExists();
if (history) {
history->ScheduleDBTask(
new GetURLForURLIDTask(
best_next_url,
base::Bind(&PrerenderLocalPredictor::OnLookupURL,
base::Unretained(this),
best_next_url,
priority)),
&history_db_consumer_);
}
}
}
}
void PrerenderLocalPredictor::OnLookupURL(history::URLID url_id,
double priority,
const GURL& url) {
RecordEvent(EVENT_PRERENDER_URL_LOOKUP_RESULT);
base::Time current_time = GetCurrentTime();
if (ShouldReplaceCurrentPrerender(priority)) {
if (IsRootPageURL(url)) {
RecordEvent(EVENT_ADD_VISIT_PRERENDERING);
if (current_prerender_.get() && current_prerender_->url_id == url_id) {
RecordEvent(EVENT_ADD_VISIT_PRERENDERING_EXTENDED);
if (priority > current_prerender_->priority)
current_prerender_->priority = priority;
// If the prerender already existed, we want to extend it. However,
// we do not want to set its start_time to the current time to
// disadvantage PLT computations when the prerender is swapped in.
// So we set the new start time to current_time - 10s (since the vast
// majority of PLTs are < 10s), provided that is not before the actual
// time the prerender was started (so as to not artificially advantage
// the PLT computation).
base::Time simulated_new_start_time =
current_time - base::TimeDelta::FromSeconds(10);
if (simulated_new_start_time > current_prerender_->start_time)
current_prerender_->start_time = simulated_new_start_time;
} else {
current_prerender_.reset(
new PrerenderData(url_id, url, priority, current_time));
}
current_prerender_->actual_start_time = current_time;
} else {
RecordEvent(EVENT_ADD_VISIT_NOT_ROOTPAGE);
}
}
if (url_whitelist_.count(GetInt64URLHashForURL(url)) > 0) {
RecordEvent(EVENT_PRERENDER_URL_LOOKUP_RESULT_ON_WHITELIST);
if (IsRootPageURL(url))
RecordEvent(EVENT_PRERENDER_URL_LOOKUP_RESULT_ON_WHITELIST_ROOT_PAGE);
}
if (IsRootPageURL(url))
RecordEvent(EVENT_PRERENDER_URL_LOOKUP_RESULT_ROOT_PAGE);
if (IsExtendedRootURL(url))
RecordEvent(EVENT_PRERENDER_URL_LOOKUP_RESULT_EXTENDED_ROOT_PAGE);
if (IsRootPageURL(url) && url.SchemeIs("http"))
RecordEvent(EVENT_PRERENDER_URL_LOOKUP_RESULT_ROOT_PAGE_HTTP);
if (url.SchemeIs("http"))
RecordEvent(EVENT_PRERENDER_URL_LOOKUP_RESULT_IS_HTTP);
if (url.has_query())
RecordEvent(EVENT_PRERENDER_URL_LOOKUP_RESULT_HAS_QUERY_STRING);
if (StrCaseStr(url.spec().c_str(), "logout") ||
StrCaseStr(url.spec().c_str(), "signout"))
RecordEvent(EVENT_PRERENDER_URL_LOOKUP_RESULT_CONTAINS_LOGOUT);
if (StrCaseStr(url.spec().c_str(), "login") ||
StrCaseStr(url.spec().c_str(), "signin"))
RecordEvent(EVENT_PRERENDER_URL_LOOKUP_RESULT_CONTAINS_LOGIN);
}
void PrerenderLocalPredictor::OnGetInitialVisitHistory(
scoped_ptr<std::vector<history::BriefVisitInfo> > visit_history) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(!visit_history_.get());
RecordEvent(EVENT_INIT_SUCCEEDED);
// Since the visit history has descending timestamps, we must reverse it.
visit_history_.reset(new std::vector<history::BriefVisitInfo>(
visit_history->rbegin(), visit_history->rend()));
}
HistoryService* PrerenderLocalPredictor::GetHistoryIfExists() const {
Profile* profile = prerender_manager_->profile();
if (!profile)
return NULL;
return HistoryServiceFactory::GetForProfileWithoutCreating(profile);
}
void PrerenderLocalPredictor::Init() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
RecordEvent(EVENT_INIT_STARTED);
HistoryService* history = GetHistoryIfExists();
if (history) {
CHECK(!is_visit_database_observer_);
history->ScheduleDBTask(
new GetVisitHistoryTask(this, kMaxVisitHistory),
&history_db_consumer_);
history->AddVisitDatabaseObserver(this);
is_visit_database_observer_ = true;
} else {
RecordEvent(EVENT_INIT_FAILED_NO_HISTORY);
}
}
void PrerenderLocalPredictor::OnPLTEventForURL(const GURL& url,
base::TimeDelta page_load_time) {
scoped_ptr<PrerenderData> prerender;
if (DoesPrerenderMatchPLTRecord(last_swapped_in_prerender_.get(),
url, page_load_time)) {
prerender.reset(last_swapped_in_prerender_.release());
}
if (DoesPrerenderMatchPLTRecord(current_prerender_.get(),
url, page_load_time)) {
prerender.reset(current_prerender_.release());
}
if (!prerender.get())
return;
if (IsPrerenderStillValid(prerender.get())) {
UMA_HISTOGRAM_CUSTOM_TIMES("Prerender.SimulatedLocalBrowsingBaselinePLT",
page_load_time,
base::TimeDelta::FromMilliseconds(10),
base::TimeDelta::FromSeconds(60),
100);
base::TimeDelta prerender_age = GetCurrentTime() - prerender->start_time;
if (prerender_age > page_load_time) {
base::TimeDelta new_plt;
if (prerender_age < 2 * page_load_time)
new_plt = 2 * page_load_time - prerender_age;
UMA_HISTOGRAM_CUSTOM_TIMES("Prerender.SimulatedLocalBrowsingPLT",
new_plt,
base::TimeDelta::FromMilliseconds(10),
base::TimeDelta::FromSeconds(60),
100);
}
}
}
bool PrerenderLocalPredictor::IsPrerenderStillValid(
PrerenderLocalPredictor::PrerenderData* prerender) const {
return (prerender &&
(prerender->start_time +
base::TimeDelta::FromMilliseconds(kMaxLocalPredictionTimeMs))
> GetCurrentTime());
}
void PrerenderLocalPredictor::RecordEvent(
PrerenderLocalPredictor::Event event) const {
UMA_HISTOGRAM_ENUMERATION(
base::FieldTrial::MakeName("Prerender.LocalPredictorEvent", "Prerender"),
event, PrerenderLocalPredictor::EVENT_MAX_VALUE);
}
bool PrerenderLocalPredictor::DoesPrerenderMatchPLTRecord(
PrerenderData* prerender, const GURL& url, base::TimeDelta plt) const {
if (prerender && prerender->start_time < GetCurrentTime() - plt) {
if (prerender->url.is_empty())
RecordEvent(EVENT_ERROR_NO_PRERENDER_URL_FOR_PLT);
return (prerender->url == url);
} else {
return false;
}
}
bool PrerenderLocalPredictor::ShouldReplaceCurrentPrerender(
double priority) const {
base::TimeDelta max_age =
base::TimeDelta::FromMilliseconds(kMaxLocalPredictionTimeMs);
return (!current_prerender_.get()) ||
current_prerender_->priority < priority ||
current_prerender_->start_time < GetCurrentTime() - max_age;
}
} // namespace prerender
| 37.214286 | 80 | 0.692795 | [
"vector",
"transform"
] |
915562b205f9bbaab63bafcfd095713644ceef5e | 133,551 | cpp | C++ | Library/QHull/io.cpp | GuoxinFang/ReinforcedFDM | bde4d1890de805ce3e626a010866303a2b132b63 | [
"BSD-3-Clause"
] | 43 | 2020-08-31T08:56:48.000Z | 2022-03-29T08:20:28.000Z | ThirdPartyDependence/QHullLib/io.cpp | zhangjiangzhao123/MultiAxis_3DP_MotionPlanning-1 | 7338bd7a1cdf9173d8715032fed29b6a0b2b21a1 | [
"BSD-3-Clause"
] | null | null | null | ThirdPartyDependence/QHullLib/io.cpp | zhangjiangzhao123/MultiAxis_3DP_MotionPlanning-1 | 7338bd7a1cdf9173d8715032fed29b6a0b2b21a1 | [
"BSD-3-Clause"
] | 10 | 2020-08-31T09:52:57.000Z | 2021-11-20T15:47:12.000Z | /*<html><pre> -<a href="qh-io.htm"
>-------------------------------</a><a name="TOP">-</a>
io.c
Input/Output routines of qhull application
see qh-io.htm and io.h
see user.c for qh_errprint and qh_printfacetlist
unix.c calls qh_readpoints and qh_produce_output
unix.c and user.c are the only callers of io.c functions
This allows the user to avoid loading io.o from qhull.a
copyright (c) 1993-2003 The Geometry Center
*/
#include "qhull_a.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/*========= -functions in alphabetical order after qh_produce_output() =====*/
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="produce_output">-</a>
qh_produce_output()
prints out the result of qhull in desired format
if qh.GETarea
computes and prints area and volume
qh.PRINTout[] is an array of output formats
notes:
prints output in qh.PRINTout order
*/
void qh_produce_output(void) {
int i, tempsize= qh_setsize ((setT*)qhmem.tempstack), d_1;
if (qh VORONOI) {
qh_clearcenters (qh_ASvoronoi);
qh_vertexneighbors();
}
if (qh TRIangulate) {
qh_triangulate();
if (qh VERIFYoutput && !qh CHECKfrequently)
qh_checkpolygon (qh facet_list);
}
qh_findgood_all (qh facet_list);
if (qh GETarea)
qh_getarea(qh facet_list);
if (qh KEEParea || qh KEEPmerge || qh KEEPminArea < REALmax/2)
qh_markkeep (qh facet_list);
if (qh PRINTsummary)
qh_printsummary(qh ferr);
else if (qh PRINTout[0] == qh_PRINTnone)
qh_printsummary(qh fout);
for (i= 0; i < qh_PRINTEND; i++)
qh_printfacets (qh fout, qh PRINTout[i], qh facet_list, NULL, !qh_ALL);
qh_allstatistics();
if (qh PRINTprecision && !qh MERGING && (qh JOGGLEmax > REALmax/2 || qh RERUN))
qh_printstats (qh ferr, qhstat precision, NULL);
if (qh VERIFYoutput && (zzval_(Zridge) > 0 || zzval_(Zridgemid) > 0))
qh_printstats (qh ferr, qhstat vridges, NULL);
if (qh PRINTstatistics) {
qh_collectstatistics();
qh_printstatistics(qh ferr, "");
qh_memstatistics (qh ferr);
d_1= sizeof(setT) + (qh hull_dim - 1) * SETelemsize;
fprintf(qh ferr, "\
size in bytes: merge %d ridge %d vertex %d facet %d\n\
normal %d ridge vertices %d facet vertices or neighbors %d\n",
sizeof(mergeT), sizeof(ridgeT),
sizeof(vertexT), sizeof(facetT),
qh normal_size, d_1, d_1 + SETelemsize);
}
if (qh_setsize ((setT*)qhmem.tempstack) != tempsize) {
fprintf (qh ferr, "qhull internal error (qh_produce_output): temporary sets not empty (%d)\n",
qh_setsize ((setT*)qhmem.tempstack));
qh_errexit (qh_ERRqhull, NULL, NULL);
}
} /* produce_output */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="dfacet">-</a>
dfacet( id )
print facet by id, for debugging
*/
void dfacet (unsigned id) {
facetT *facet;
FORALLfacets {
if (facet->id == id) {
qh_printfacet (qh fout, facet);
break;
}
}
} /* dfacet */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="dvertex">-</a>
dvertex( id )
print vertex by id, for debugging
*/
void dvertex (unsigned id) {
vertexT *vertex;
FORALLvertices {
if (vertex->id == id) {
qh_printvertex (qh fout, vertex);
break;
}
}
} /* dvertex */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="compare_vertexpoint">-</a>
qh_compare_vertexpoint( p1, p2 )
used by qsort() to order vertices by point id
*/
int qh_compare_vertexpoint(const void *p1, const void *p2) {
vertexT *a= *((vertexT **)p1), *b= *((vertexT **)p2);
return ((qh_pointid(a->point) > qh_pointid(b->point)?1:-1));
} /* compare_vertexpoint */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="compare_facetarea">-</a>
qh_compare_facetarea( p1, p2 )
used by qsort() to order facets by area
*/
int qh_compare_facetarea(const void *p1, const void *p2) {
facetT *a= *((facetT **)p1), *b= *((facetT **)p2);
if (!a->isarea)
return -1;
if (!b->isarea)
return 1;
if (a->f.area > b->f.area)
return 1;
else if (a->f.area == b->f.area)
return 0;
return -1;
} /* compare_facetarea */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="compare_facetmerge">-</a>
qh_compare_facetmerge( p1, p2 )
used by qsort() to order facets by number of merges
*/
int qh_compare_facetmerge(const void *p1, const void *p2) {
facetT *a= *((facetT **)p1), *b= *((facetT **)p2);
return (a->nummerge - b->nummerge);
} /* compare_facetvisit */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="compare_facetvisit">-</a>
qh_compare_facetvisit( p1, p2 )
used by qsort() to order facets by visit id or id
*/
int qh_compare_facetvisit(const void *p1, const void *p2) {
facetT *a= *((facetT **)p1), *b= *((facetT **)p2);
int i,j;
if (!(i= a->visitid))
i= - a->id; /* do not convert to int */
if (!(j= b->visitid))
j= - b->id;
return (i - j);
} /* compare_facetvisit */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="countfacets">-</a>
qh_countfacets( facetlist, facets, printall,
numfacets, numsimplicial, totneighbors, numridges, numcoplanar, numtricoplanars )
count good facets for printing and set visitid
if allfacets, ignores qh_skipfacet()
notes:
qh_printsummary and qh_countfacets must match counts
returns:
numfacets, numsimplicial, total neighbors, numridges, coplanars
each facet with ->visitid indicating 1-relative position
->visitid==0 indicates not good
notes
numfacets >= numsimplicial
if qh.NEWfacets,
does not count visible facets (matches qh_printafacet)
design:
for all facets on facetlist and in facets set
unless facet is skipped or visible (i.e., will be deleted)
mark facet->visitid
update counts
*/
void qh_countfacets (facetT *facetlist, setT *facets, boolT printall,
int *numfacetsp, int *numsimplicialp, int *totneighborsp, int *numridgesp, int *numcoplanarsp, int *numtricoplanarsp) {
facetT *facet, **facetp;
int numfacets= 0, numsimplicial= 0, numridges= 0, totneighbors= 0, numcoplanars= 0, numtricoplanars= 0;
FORALLfacet_(facetlist) {
if ((facet->visible && qh NEWfacets)
|| (!printall && qh_skipfacet(facet)))
facet->visitid= 0;
else {
facet->visitid= ++numfacets;
totneighbors += qh_setsize (facet->neighbors);
if (facet->simplicial) {
numsimplicial++;
if (facet->keepcentrum && facet->tricoplanar)
numtricoplanars++;
}else
numridges += qh_setsize (facet->ridges);
if (facet->coplanarset)
numcoplanars += qh_setsize (facet->coplanarset);
}
}
FOREACHfacet_(facets) {
if ((facet->visible && qh NEWfacets)
|| (!printall && qh_skipfacet(facet)))
facet->visitid= 0;
else {
facet->visitid= ++numfacets;
totneighbors += qh_setsize (facet->neighbors);
if (facet->simplicial){
numsimplicial++;
if (facet->keepcentrum && facet->tricoplanar)
numtricoplanars++;
}else
numridges += qh_setsize (facet->ridges);
if (facet->coplanarset)
numcoplanars += qh_setsize (facet->coplanarset);
}
}
qh visit_id += numfacets+1;
*numfacetsp= numfacets;
*numsimplicialp= numsimplicial;
*totneighborsp= totneighbors;
*numridgesp= numridges;
*numcoplanarsp= numcoplanars;
*numtricoplanarsp= numtricoplanars;
} /* countfacets */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="detvnorm">-</a>
qh_detvnorm( vertex, vertexA, centers, offset )
compute separating plane of the Voronoi diagram for a pair of input sites
centers= set of facets (i.e., Voronoi vertices)
facet->visitid= 0 iff vertex-at-infinity (i.e., unbounded)
assumes:
qh_ASvoronoi and qh_vertexneighbors() already set
returns:
norm
a pointer into qh.gm_matrix to qh.hull_dim-1 reals
copy the data before reusing qh.gm_matrix
offset
if 'QVn'
sign adjusted so that qh.GOODvertexp is inside
else
sign adjusted so that vertex is inside
qh.gm_matrix= simplex of points from centers relative to first center
notes:
in io.c so that code for 'v Tv' can be removed by removing io.c
returns pointer into qh.gm_matrix to avoid tracking of temporary memory
design:
determine midpoint of input sites
build points as the set of Voronoi vertices
select a simplex from points (if necessary)
include midpoint if the Voronoi region is unbounded
relocate the first vertex of the simplex to the origin
compute the normalized hyperplane through the simplex
orient the hyperplane toward 'QVn' or 'vertex'
if 'Tv' or 'Ts'
if bounded
test that hyperplane is the perpendicular bisector of the input sites
test that Voronoi vertices not in the simplex are still on the hyperplane
free up temporary memory
*/
pointT *qh_detvnorm (vertexT *vertex, vertexT *vertexA, setT *centers, realT *offsetp) {
facetT *facet, **facetp;
int i, k, pointid, pointidA, point_i, point_n;
setT *simplex= NULL;
pointT *point, **pointp, *point0, *midpoint, *normal, *inpoint;
coordT *coord, *gmcoord, *normalp;
setT *points= qh_settemp (qh TEMPsize);
boolT nearzero= False;
boolT unbounded= False;
int numcenters= 0;
int dim= qh hull_dim - 1;
realT dist, offset, angle, zero= 0.0;
midpoint= qh gm_matrix + qh hull_dim * qh hull_dim; /* last row */
for (k= 0; k < dim; k++)
midpoint[k]= (vertex->point[k] + vertexA->point[k])/2;
FOREACHfacet_(centers) {
numcenters++;
if (!facet->visitid)
unbounded= True;
else {
if (!facet->center)
facet->center= qh_facetcenter (facet->vertices);
qh_setappend (&points, facet->center);
}
}
if (numcenters > dim) {
simplex= qh_settemp (qh TEMPsize);
qh_setappend (&simplex, vertex->point);
if (unbounded)
qh_setappend (&simplex, midpoint);
qh_maxsimplex (dim, points, NULL, 0, &simplex);
qh_setdelnth (simplex, 0);
}else if (numcenters == dim) {
if (unbounded)
qh_setappend (&points, midpoint);
simplex= points;
}else {
fprintf(qh ferr, "qh_detvnorm: too few points (%d) to compute separating plane\n", numcenters);
qh_errexit (qh_ERRqhull, NULL, NULL);
}
i= 0;
gmcoord= qh gm_matrix;
point0= SETfirstt_(simplex, pointT);
FOREACHpoint_(simplex) {
if (qh IStracing >= 4)
qh_printmatrix(qh ferr, "qh_detvnorm: Voronoi vertex or midpoint",
&point, 1, dim);
if (point != point0) {
qh gm_row[i++]= gmcoord;
coord= point0;
for (k= dim; k--; )
*(gmcoord++)= *point++ - *coord++;
}
}
qh gm_row[i]= gmcoord; /* does not overlap midpoint, may be used later for qh_areasimplex */
normal= gmcoord;
qh_sethyperplane_gauss (dim, qh gm_row, point0, True,
normal, &offset, &nearzero);
if (qh GOODvertexp == vertexA->point)
inpoint= vertexA->point;
else
inpoint= vertex->point;
zinc_(Zdistio);
dist= qh_distnorm (dim, inpoint, normal, &offset);
if (dist > 0) {
offset= -offset;
normalp= normal;
for (k= dim; k--; ) {
*normalp= -(*normalp);
normalp++;
}
}
if (qh VERIFYoutput || qh PRINTstatistics) {
pointid= qh_pointid (vertex->point);
pointidA= qh_pointid (vertexA->point);
if (!unbounded) {
zinc_(Zdiststat);
dist= qh_distnorm (dim, midpoint, normal, &offset);
if (dist < 0)
dist= -dist;
zzinc_(Zridgemid);
wwmax_(Wridgemidmax, dist);
wwadd_(Wridgemid, dist);
trace4((qh ferr, "qh_detvnorm: points %d %d midpoint dist %2.2g\n",
pointid, pointidA, dist));
for (k= 0; k < dim; k++)
midpoint[k]= vertexA->point[k] - vertex->point[k]; /* overwrites midpoint! */
qh_normalize (midpoint, dim, False);
angle= qh_distnorm (dim, midpoint, normal, &zero); /* qh_detangle uses dim+1 */
if (angle < 0.0)
angle= angle + 1.0;
else
angle= angle - 1.0;
if (angle < 0.0)
angle -= angle;
trace4((qh ferr, "qh_detvnorm: points %d %d angle %2.2g nearzero %d\n",
pointid, pointidA, angle, nearzero));
if (nearzero) {
zzinc_(Zridge0);
wwmax_(Wridge0max, angle);
wwadd_(Wridge0, angle);
}else {
zzinc_(Zridgeok)
wwmax_(Wridgeokmax, angle);
wwadd_(Wridgeok, angle);
}
}
if (simplex != points) {
FOREACHpoint_i_(points) {
if (!qh_setin (simplex, point)) {
facet= SETelemt_(centers, point_i, facetT);
zinc_(Zdiststat);
dist= qh_distnorm (dim, point, normal, &offset);
if (dist < 0)
dist= -dist;
zzinc_(Zridge);
wwmax_(Wridgemax, dist);
wwadd_(Wridge, dist);
trace4((qh ferr, "qh_detvnorm: points %d %d Voronoi vertex %d dist %2.2g\n",
pointid, pointidA, facet->visitid, dist));
}
}
}
}
*offsetp= offset;
if (simplex != points)
qh_settempfree (&simplex);
qh_settempfree (&points);
return normal;
} /* detvnorm */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="detvridge">-</a>
qh_detvridge( vertexA )
determine Voronoi ridge from 'seen' neighbors of vertexA
include one vertex-at-infinite if an !neighbor->visitid
returns:
temporary set of centers (facets, i.e., Voronoi vertices)
sorted by center id
*/
setT *qh_detvridge (vertexT *vertex) {
setT *centers= qh_settemp (qh TEMPsize);
setT *tricenters= qh_settemp (qh TEMPsize);
facetT *neighbor, **neighborp;
boolT firstinf= True;
FOREACHneighbor_(vertex) {
if (neighbor->seen) {
if (neighbor->visitid) {
if (!neighbor->tricoplanar || qh_setunique (&tricenters, neighbor->center))
qh_setappend (¢ers, neighbor);
}else if (firstinf) {
firstinf= False;
qh_setappend (¢ers, neighbor);
}
}
}
qsort (SETaddr_(centers, facetT), qh_setsize (centers),
sizeof (facetT *), qh_compare_facetvisit);
qh_settempfree (&tricenters);
return centers;
} /* detvridge */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="detvridge3">-</a>
qh_detvridge3( atvertex, vertex )
determine 3-d Voronoi ridge from 'seen' neighbors of atvertex and vertex
include one vertex-at-infinite for !neighbor->visitid
assumes all facet->seen2= True
returns:
temporary set of centers (facets, i.e., Voronoi vertices)
listed in adjacency order (not oriented)
all facet->seen2= True
design:
mark all neighbors of atvertex
for each adjacent neighbor of both atvertex and vertex
if neighbor selected
add neighbor to set of Voronoi vertices
*/
setT *qh_detvridge3 (vertexT *atvertex, vertexT *vertex) {
setT *centers= qh_settemp (qh TEMPsize);
setT *tricenters= qh_settemp (qh TEMPsize);
facetT *neighbor, **neighborp, *facet= NULL;
boolT firstinf= True;
FOREACHneighbor_(atvertex)
neighbor->seen2= False;
FOREACHneighbor_(vertex) {
if (!neighbor->seen2) {
facet= neighbor;
break;
}
}
while (facet) {
facet->seen2= True;
if (neighbor->seen) {
if (facet->visitid) {
if (!facet->tricoplanar || qh_setunique (&tricenters, facet->center))
qh_setappend (¢ers, facet);
}else if (firstinf) {
firstinf= False;
qh_setappend (¢ers, facet);
}
}
FOREACHneighbor_(facet) {
if (!neighbor->seen2) {
if (qh_setin (vertex->neighbors, neighbor))
break;
else
neighbor->seen2= True;
}
}
facet= neighbor;
}
if (qh CHECKfrequently) {
FOREACHneighbor_(vertex) {
if (!neighbor->seen2) {
fprintf (stderr, "qh_detvridge3: neigbors of vertex p%d are not connected at facet %d\n",
qh_pointid (vertex->point), neighbor->id);
qh_errexit (qh_ERRqhull, neighbor, NULL);
}
}
}
FOREACHneighbor_(atvertex)
neighbor->seen2= True;
qh_settempfree (&tricenters);
return centers;
} /* detvridge3 */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="eachvoronoi">-</a>
qh_eachvoronoi( fp, printvridge, vertex, visitall, innerouter, inorder )
if visitall,
visit all Voronoi ridges for vertex (i.e., an input site)
else
visit all unvisited Voronoi ridges for vertex
all vertex->seen= False if unvisited
assumes
all facet->seen= False
all facet->seen2= True (for qh_detvridge3)
all facet->visitid == 0 if vertex_at_infinity
== index of Voronoi vertex
>= qh.num_facets if ignored
innerouter:
qh_RIDGEall-- both inner (bounded) and outer (unbounded) ridges
qh_RIDGEinner- only inner
qh_RIDGEouter- only outer
if inorder
orders vertices for 3-d Voronoi diagrams
returns:
number of visited ridges (does not include previously visited ridges)
if printvridge,
calls printvridge( fp, vertex, vertexA, centers)
fp== any pointer (assumes FILE*)
vertex,vertexA= pair of input sites that define a Voronoi ridge
centers= set of facets (i.e., Voronoi vertices)
->visitid == index or 0 if vertex_at_infinity
ordered for 3-d Voronoi diagram
notes:
uses qh.vertex_visit
see:
qh_eachvoronoi_all()
design:
mark selected neighbors of atvertex
for each selected neighbor (either Voronoi vertex or vertex-at-infinity)
for each unvisited vertex
if atvertex and vertex share more than d-1 neighbors
bump totalcount
if printvridge defined
build the set of shared neighbors (i.e., Voronoi vertices)
call printvridge
*/
int qh_eachvoronoi (FILE *fp, printvridgeT printvridge, vertexT *atvertex, boolT visitall, qh_RIDGE innerouter, boolT inorder) {
boolT unbounded;
int count;
facetT *neighbor, **neighborp, *neighborA, **neighborAp;
setT *centers;
setT *tricenters= qh_settemp (qh TEMPsize);
vertexT *vertex, **vertexp;
boolT firstinf;
unsigned int numfacets= (unsigned int)qh num_facets;
int totridges= 0;
qh vertex_visit++;
atvertex->seen= True;
if (visitall) {
FORALLvertices
vertex->seen= False;
}
FOREACHneighbor_(atvertex) {
if (neighbor->visitid < numfacets)
neighbor->seen= True;
}
FOREACHneighbor_(atvertex) {
if (neighbor->seen) {
FOREACHvertex_(neighbor->vertices) {
if (vertex->visitid != qh vertex_visit && !vertex->seen) {
vertex->visitid= qh vertex_visit;
count= 0;
firstinf= True;
qh_settruncate (tricenters, 0);
FOREACHneighborA_(vertex) {
if (neighborA->seen) {
if (neighborA->visitid) {
if (!neighborA->tricoplanar || qh_setunique (&tricenters, neighborA->center))
count++;
}else if (firstinf) {
count++;
firstinf= False;
}
}
}
if (count >= qh hull_dim - 1) { /* e.g., 3 for 3-d Voronoi */
if (firstinf) {
if (innerouter == qh_RIDGEouter)
continue;
unbounded= False;
}else {
if (innerouter == qh_RIDGEinner)
continue;
unbounded= True;
}
totridges++;
trace4((qh ferr, "qh_eachvoronoi: Voronoi ridge of %d vertices between sites %d and %d\n",
count, qh_pointid (atvertex->point), qh_pointid (vertex->point)));
if (printvridge) {
if (inorder && qh hull_dim == 3+1) /* 3-d Voronoi diagram */
centers= qh_detvridge3 (atvertex, vertex);
else
centers= qh_detvridge (vertex);
(*printvridge) (fp, atvertex, vertex, centers, unbounded);
qh_settempfree (¢ers);
}
}
}
}
}
}
FOREACHneighbor_(atvertex)
neighbor->seen= False;
qh_settempfree (&tricenters);
return totridges;
} /* eachvoronoi */
/*-<a href="qh-poly.htm#TOC"
>-------------------------------</a><a name="eachvoronoi_all">-</a>
qh_eachvoronoi_all( fp, printvridge, isupper, innerouter, inorder )
visit all Voronoi ridges
innerouter:
see qh_eachvoronoi()
if inorder
orders vertices for 3-d Voronoi diagrams
returns
total number of ridges
if isupper == facet->upperdelaunay (i.e., a Vornoi vertex)
facet->visitid= Voronoi vertex index (same as 'o' format)
else
facet->visitid= 0
if printvridge,
calls printvridge( fp, vertex, vertexA, centers)
[see qh_eachvoronoi]
notes:
Not used for qhull.exe
same effect as qh_printvdiagram but ridges not sorted by point id
*/
int qh_eachvoronoi_all (FILE *fp, printvridgeT printvridge, boolT isupper, qh_RIDGE innerouter, boolT inorder) {
facetT *facet;
vertexT *vertex;
int numcenters= 1; /* vertex 0 is vertex-at-infinity */
int totridges= 0;
qh_clearcenters (qh_ASvoronoi);
qh_vertexneighbors();
maximize_(qh visit_id, (unsigned) qh num_facets);
FORALLfacets {
facet->visitid= 0;
facet->seen= False;
facet->seen2= True;
}
FORALLfacets {
if (facet->upperdelaunay == isupper)
facet->visitid= numcenters++;
}
FORALLvertices
vertex->seen= False;
FORALLvertices {
if (qh GOODvertex > 0 && qh_pointid(vertex->point)+1 != qh GOODvertex)
continue;
totridges += qh_eachvoronoi (fp, printvridge, vertex,
!qh_ALL, innerouter, inorder);
}
return totridges;
} /* eachvoronoi_all */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="facet2point">-</a>
qh_facet2point( facet, point0, point1, mindist )
return two projected temporary vertices for a 2-d facet
may be non-simplicial
returns:
point0 and point1 oriented and projected to the facet
returns mindist (maximum distance below plane)
*/
void qh_facet2point(facetT *facet, pointT **point0, pointT **point1, realT *mindist) {
vertexT *vertex0, *vertex1;
realT dist;
if (facet->toporient ^ qh_ORIENTclock) {
vertex0= SETfirstt_(facet->vertices, vertexT);
vertex1= SETsecondt_(facet->vertices, vertexT);
}else {
vertex1= SETfirstt_(facet->vertices, vertexT);
vertex0= SETsecondt_(facet->vertices, vertexT);
}
zadd_(Zdistio, 2);
qh_distplane(vertex0->point, facet, &dist);
*mindist= dist;
*point0= qh_projectpoint(vertex0->point, facet, dist);
qh_distplane(vertex1->point, facet, &dist);
minimize_(*mindist, dist);
*point1= qh_projectpoint(vertex1->point, facet, dist);
} /* facet2point */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="facetvertices">-</a>
qh_facetvertices( facetlist, facets, allfacets )
returns temporary set of vertices in a set and/or list of facets
if allfacets, ignores qh_skipfacet()
returns:
vertices with qh.vertex_visit
notes:
optimized for allfacets of facet_list
design:
if allfacets of facet_list
create vertex set from vertex_list
else
for each selected facet in facets or facetlist
append unvisited vertices to vertex set
*/
setT *qh_facetvertices (facetT *facetlist, setT *facets, boolT allfacets) {
setT *vertices;
facetT *facet, **facetp;
vertexT *vertex, **vertexp;
qh vertex_visit++;
if (facetlist == qh facet_list && allfacets && !facets) {
vertices= qh_settemp (qh num_vertices);
FORALLvertices {
vertex->visitid= qh vertex_visit;
qh_setappend (&vertices, vertex);
}
}else {
vertices= qh_settemp (qh TEMPsize);
FORALLfacet_(facetlist) {
if (!allfacets && qh_skipfacet (facet))
continue;
FOREACHvertex_(facet->vertices) {
if (vertex->visitid != qh vertex_visit) {
vertex->visitid= qh vertex_visit;
qh_setappend (&vertices, vertex);
}
}
}
}
FOREACHfacet_(facets) {
if (!allfacets && qh_skipfacet (facet))
continue;
FOREACHvertex_(facet->vertices) {
if (vertex->visitid != qh vertex_visit) {
vertex->visitid= qh vertex_visit;
qh_setappend (&vertices, vertex);
}
}
}
return vertices;
} /* facetvertices */
/*-<a href="qh-geom.htm#TOC"
>-------------------------------</a><a name="geomplanes">-</a>
qh_geomplanes( facet, outerplane, innerplane )
return outer and inner planes for Geomview
qh.PRINTradius is size of vertices and points (includes qh.JOGGLEmax)
notes:
assume precise calculations in io.c with roundoff covered by qh_GEOMepsilon
*/
void qh_geomplanes (facetT *facet, realT *outerplane, realT *innerplane) {
realT radius;
if (qh MERGING || qh JOGGLEmax < REALmax/2) {
qh_outerinner (facet, outerplane, innerplane);
radius= qh PRINTradius;
if (qh JOGGLEmax < REALmax/2)
radius -= qh JOGGLEmax * sqrt ((double)qh hull_dim); /* already accounted for in qh_outerinner() */
*outerplane += radius;
*innerplane -= radius;
if (qh PRINTcoplanar || qh PRINTspheres) {
*outerplane += qh MAXabs_coord * qh_GEOMepsilon;
*innerplane -= qh MAXabs_coord * qh_GEOMepsilon;
}
}else
*innerplane= *outerplane= 0;
} /* geomplanes */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="markkeep">-</a>
qh_markkeep( facetlist )
mark good facets that meet qh.KEEParea, qh.KEEPmerge, and qh.KEEPminArea
ignores visible facets (not part of convex hull)
returns:
may clear facet->good
recomputes qh.num_good
design:
get set of good facets
if qh.KEEParea
sort facets by area
clear facet->good for all but n largest facets
if qh.KEEPmerge
sort facets by merge count
clear facet->good for all but n most merged facets
if qh.KEEPminarea
clear facet->good if area too small
update qh.num_good
*/
void qh_markkeep (facetT *facetlist) {
facetT *facet, **facetp;
setT *facets= qh_settemp (qh num_facets);
int size, count;
trace2((qh ferr, "qh_markkeep: only keep %d largest and/or %d most merged facets and/or min area %.2g\n",
qh KEEParea, qh KEEPmerge, qh KEEPminArea));
FORALLfacet_(facetlist) {
if (!facet->visible && facet->good)
qh_setappend (&facets, facet);
}
size= qh_setsize (facets);
if (qh KEEParea) {
qsort (SETaddr_(facets, facetT), size,
sizeof (facetT *), qh_compare_facetarea);
if ((count= size - qh KEEParea) > 0) {
FOREACHfacet_(facets) {
facet->good= False;
if (--count == 0)
break;
}
}
}
if (qh KEEPmerge) {
qsort (SETaddr_(facets, facetT), size,
sizeof (facetT *), qh_compare_facetmerge);
if ((count= size - qh KEEPmerge) > 0) {
FOREACHfacet_(facets) {
facet->good= False;
if (--count == 0)
break;
}
}
}
if (qh KEEPminArea < REALmax/2) {
FOREACHfacet_(facets) {
if (!facet->isarea || facet->f.area < qh KEEPminArea)
facet->good= False;
}
}
qh_settempfree (&facets);
count= 0;
FORALLfacet_(facetlist) {
if (facet->good)
count++;
}
qh num_good= count;
} /* markkeep */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="markvoronoi">-</a>
qh_markvoronoi( facetlist, facets, printall, islower, numcenters )
mark voronoi vertices for printing by site pairs
returns:
temporary set of vertices indexed by pointid
islower set if printing lower hull (i.e., at least one facet is lower hull)
numcenters= total number of Voronoi vertices
bumps qh.printoutnum for vertex-at-infinity
clears all facet->seen and sets facet->seen2
if selected
facet->visitid= Voronoi vertex id
else if upper hull (or 'Qu' and lower hull)
facet->visitid= 0
else
facet->visitid >= qh num_facets
notes:
ignores qh.ATinfinity, if defined
*/
setT *qh_markvoronoi (facetT *facetlist, setT *facets, boolT printall, boolT *islowerp, int *numcentersp) {
int numcenters=0;
facetT *facet, **facetp;
setT *vertices;
boolT islower= False;
qh printoutnum++;
qh_clearcenters (qh_ASvoronoi); /* in case, qh_printvdiagram2 called by user */
qh_vertexneighbors();
vertices= qh_pointvertex();
if (qh ATinfinity)
SETelem_(vertices, qh num_points-1)= NULL;
qh visit_id++;
maximize_(qh visit_id, (unsigned) qh num_facets);
FORALLfacet_(facetlist) {
if (printall || !qh_skipfacet (facet)) {
if (!facet->upperdelaunay) {
islower= True;
break;
}
}
}
FOREACHfacet_(facets) {
if (printall || !qh_skipfacet (facet)) {
if (!facet->upperdelaunay) {
islower= True;
break;
}
}
}
FORALLfacets {
if (facet->normal && (facet->upperdelaunay == islower))
facet->visitid= 0; /* facetlist or facets may overwrite */
else
facet->visitid= qh visit_id;
facet->seen= False;
facet->seen2= True;
}
numcenters++; /* qh_INFINITE */
FORALLfacet_(facetlist) {
if (printall || !qh_skipfacet (facet))
facet->visitid= numcenters++;
}
FOREACHfacet_(facets) {
if (printall || !qh_skipfacet (facet))
facet->visitid= numcenters++;
}
*islowerp= islower;
*numcentersp= numcenters;
trace2((qh ferr, "qh_markvoronoi: islower %d numcenters %d\n", islower, numcenters));
return vertices;
} /* markvoronoi */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="order_vertexneighbors">-</a>
qh_order_vertexneighbors( vertex )
order facet neighbors of a 2-d or 3-d vertex by adjacency
notes:
does not orient the neighbors
design:
initialize a new neighbor set with the first facet in vertex->neighbors
while vertex->neighbors non-empty
select next neighbor in the previous facet's neighbor set
set vertex->neighbors to the new neighbor set
*/
void qh_order_vertexneighbors(vertexT *vertex) {
setT *newset;
facetT *facet, *neighbor, **neighborp;
trace4((qh ferr, "qh_order_vertexneighbors: order neighbors of v%d for 3-d\n", vertex->id));
newset= qh_settemp (qh_setsize (vertex->neighbors));
facet= (facetT*)qh_setdellast (vertex->neighbors);
qh_setappend (&newset, facet);
while (qh_setsize (vertex->neighbors)) {
FOREACHneighbor_(vertex) {
if (qh_setin (facet->neighbors, neighbor)) {
qh_setdel(vertex->neighbors, neighbor);
qh_setappend (&newset, neighbor);
facet= neighbor;
break;
}
}
if (!neighbor) {
fprintf (qh ferr, "qhull internal error (qh_order_vertexneighbors): no neighbor of v%d for f%d\n",
vertex->id, facet->id);
qh_errexit (qh_ERRqhull, facet, NULL);
}
}
qh_setfree (&vertex->neighbors);
qh_settemppop ();
vertex->neighbors= newset;
} /* order_vertexneighbors */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="printafacet">-</a>
qh_printafacet( fp, format, facet, printall )
print facet to fp in given output format (see qh.PRINTout)
returns:
nop if !printall and qh_skipfacet()
nop if visible facet and NEWfacets and format != PRINTfacets
must match qh_countfacets
notes
preserves qh.visit_id
facet->normal may be null if PREmerge/MERGEexact and STOPcone before merge
see
qh_printbegin() and qh_printend()
design:
test for printing facet
call appropriate routine for format
or output results directly
*/
void qh_printafacet(FILE *fp, int format, facetT *facet, boolT printall) {
realT color[4], offset, dist, outerplane, innerplane;
boolT zerodiv;
coordT *point, *normp, *coordp, **pointp, *feasiblep;
int k;
vertexT *vertex, **vertexp;
facetT *neighbor, **neighborp;
if (!printall && qh_skipfacet (facet))
return;
if (facet->visible && qh NEWfacets && format != qh_PRINTfacets)
return;
qh printoutnum++;
switch (format) {
case qh_PRINTarea:
if (facet->isarea) {
fprintf (fp, qh_REAL_1, facet->f.area);
fprintf (fp, "\n");
}else
fprintf (fp, "0\n");
break;
case qh_PRINTcoplanars:
fprintf (fp, "%d", qh_setsize (facet->coplanarset));
FOREACHpoint_(facet->coplanarset)
fprintf (fp, " %d", qh_pointid (point));
fprintf (fp, "\n");
break;
case qh_PRINTcentrums:
qh_printcenter (fp, format, NULL, facet);
break;
case qh_PRINTfacets:
qh_printfacet (fp, facet);
break;
case qh_PRINTfacets_xridge:
qh_printfacetheader (fp, facet);
break;
case qh_PRINTgeom: /* either 2 , 3, or 4-d by qh_printbegin */
if (!facet->normal)
break;
for (k= qh hull_dim; k--; ) {
color[k]= (facet->normal[k]+1.0)/2.0;
maximize_(color[k], -1.0);
minimize_(color[k], +1.0);
}
qh_projectdim3 (color, color);
if (qh PRINTdim != qh hull_dim)
qh_normalize2 (color, 3, True, NULL, NULL);
if (qh hull_dim <= 2)
qh_printfacet2geom (fp, facet, color);
else if (qh hull_dim == 3) {
if (facet->simplicial)
qh_printfacet3geom_simplicial (fp, facet, color);
else
qh_printfacet3geom_nonsimplicial (fp, facet, color);
}else {
if (facet->simplicial)
qh_printfacet4geom_simplicial (fp, facet, color);
else
qh_printfacet4geom_nonsimplicial (fp, facet, color);
}
break;
case qh_PRINTids:
fprintf (fp, "%d\n", facet->id);
break;
case qh_PRINTincidences:
case qh_PRINToff:
case qh_PRINTtriangles:
if (qh hull_dim == 3 && format != qh_PRINTtriangles)
qh_printfacet3vertex (fp, facet, format);
else if (facet->simplicial || qh hull_dim == 2 || format == qh_PRINToff)
qh_printfacetNvertex_simplicial (fp, facet, format);
else
qh_printfacetNvertex_nonsimplicial (fp, facet, qh printoutvar++, format);
break;
case qh_PRINTinner:
qh_outerinner (facet, NULL, &innerplane);
offset= facet->offset - innerplane;
goto LABELprintnorm;
break; /* prevent warning */
case qh_PRINTmerges:
fprintf (fp, "%d\n", facet->nummerge);
break;
case qh_PRINTnormals:
offset= facet->offset;
goto LABELprintnorm;
break; /* prevent warning */
case qh_PRINTouter:
qh_outerinner (facet, &outerplane, NULL);
offset= facet->offset - outerplane;
LABELprintnorm:
if (!facet->normal) {
fprintf (fp, "no normal for facet f%d\n", facet->id);
break;
}
if (qh CDDoutput) {
fprintf (fp, qh_REAL_1, -offset);
for (k=0; k < qh hull_dim; k++)
fprintf (fp, qh_REAL_1, -facet->normal[k]);
}else {
for (k=0; k < qh hull_dim; k++)
fprintf (fp, qh_REAL_1, facet->normal[k]);
fprintf (fp, qh_REAL_1, offset);
}
fprintf (fp, "\n");
break;
case qh_PRINTmathematica: /* either 2 or 3-d by qh_printbegin */
case qh_PRINTmaple:
if (qh hull_dim == 2)
qh_printfacet2math (fp, facet, format, qh printoutvar++);
else
qh_printfacet3math (fp, facet, format, qh printoutvar++);
break;
case qh_PRINTneighbors:
fprintf (fp, "%d", qh_setsize (facet->neighbors));
FOREACHneighbor_(facet)
fprintf (fp, " %d",
neighbor->visitid ? neighbor->visitid - 1: - neighbor->id);
fprintf (fp, "\n");
break;
case qh_PRINTpointintersect:
if (!qh feasible_point) {
fprintf (fp, "qhull input error (qh_printafacet): option 'Fp' needs qh feasible_point\n");
qh_errexit( qh_ERRinput, NULL, NULL);
}
if (facet->offset > 0)
goto LABELprintinfinite;
point= coordp= (coordT*)qh_memalloc (qh normal_size);
normp= facet->normal;
feasiblep= qh feasible_point;
if (facet->offset < -qh MINdenom) {
for (k= qh hull_dim; k--; )
*(coordp++)= (*(normp++) / - facet->offset) + *(feasiblep++);
}else {
for (k= qh hull_dim; k--; ) {
*(coordp++)= qh_divzero (*(normp++), facet->offset, qh MINdenom_1,
&zerodiv) + *(feasiblep++);
if (zerodiv) {
qh_memfree (point, qh normal_size);
goto LABELprintinfinite;
}
}
}
qh_printpoint (fp, NULL, point);
qh_memfree (point, qh normal_size);
break;
LABELprintinfinite:
for (k= qh hull_dim; k--; )
fprintf (fp, qh_REAL_1, qh_INFINITE);
fprintf (fp, "\n");
break;
case qh_PRINTpointnearest:
FOREACHpoint_(facet->coplanarset) {
int id, id2;
vertex= qh_nearvertex (facet, point, &dist);
id= qh_pointid (vertex->point);
id2= qh_pointid (point);
fprintf (fp, "%d %d %d " qh_REAL_1 "\n", id, id2, facet->id, dist);
}
break;
case qh_PRINTpoints: /* VORONOI only by qh_printbegin */
if (qh CDDoutput)
fprintf (fp, "1 ");
qh_printcenter (fp, format, NULL, facet);
break;
case qh_PRINTvertices:
fprintf (fp, "%d", qh_setsize (facet->vertices));
FOREACHvertex_(facet->vertices)
fprintf (fp, " %d", qh_pointid (vertex->point));
fprintf (fp, "\n");
break;
}
} /* printafacet */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="printbegin">-</a>
qh_printbegin( )
prints header for all output formats
returns:
checks for valid format
notes:
uses qh.visit_id for 3/4off
changes qh.interior_point if printing centrums
qh_countfacets clears facet->visitid for non-good facets
see
qh_printend() and qh_printafacet()
design:
count facets and related statistics
print header for format
*/
void qh_printbegin (FILE *fp, int format, facetT *facetlist, setT *facets, boolT printall) {
int numfacets, numsimplicial, numridges, totneighbors, numcoplanars, numtricoplanars;
int i, num;
facetT *facet, **facetp;
vertexT *vertex, **vertexp;
setT *vertices;
pointT *point, **pointp, *pointtemp;
qh printoutnum= 0;
qh_countfacets (facetlist, facets, printall, &numfacets, &numsimplicial,
&totneighbors, &numridges, &numcoplanars, &numtricoplanars);
switch (format) {
case qh_PRINTnone:
break;
case qh_PRINTarea:
fprintf (fp, "%d\n", numfacets);
break;
case qh_PRINTcoplanars:
fprintf (fp, "%d\n", numfacets);
break;
case qh_PRINTcentrums:
if (qh CENTERtype == qh_ASnone)
qh_clearcenters (qh_AScentrum);
fprintf (fp, "%d\n%d\n", qh hull_dim, numfacets);
break;
case qh_PRINTfacets:
case qh_PRINTfacets_xridge:
if (facetlist)
qh_printvertexlist (fp, "Vertices and facets:\n", facetlist, facets, printall);
break;
case qh_PRINTgeom:
if (qh hull_dim > 4) /* qh_initqhull_globals also checks */
goto LABELnoformat;
if (qh VORONOI && qh hull_dim > 3) /* PRINTdim == DROPdim == hull_dim-1 */
goto LABELnoformat;
if (qh hull_dim == 2 && (qh PRINTridges || qh DOintersections))
fprintf (qh ferr, "qhull warning: output for ridges and intersections not implemented in 2-d\n");
if (qh hull_dim == 4 && (qh PRINTinner || qh PRINTouter ||
(qh PRINTdim == 4 && qh PRINTcentrums)))
fprintf (qh ferr, "qhull warning: output for outer/inner planes and centrums not implemented in 4-d\n");
if (qh PRINTdim == 4 && (qh PRINTspheres))
fprintf (qh ferr, "qhull warning: output for vertices not implemented in 4-d\n");
if (qh PRINTdim == 4 && qh DOintersections && qh PRINTnoplanes)
fprintf (qh ferr, "qhull warning: 'Gnh' generates no output in 4-d\n");
if (qh PRINTdim == 2) {
fprintf(fp, "{appearance {linewidth 3} LIST # %s | %s\n",
qh rbox_command, qh qhull_command);
}else if (qh PRINTdim == 3) {
fprintf(fp, "{appearance {+edge -evert linewidth 2} LIST # %s | %s\n",
qh rbox_command, qh qhull_command);
}else if (qh PRINTdim == 4) {
qh visit_id++;
num= 0;
FORALLfacet_(facetlist) /* get number of ridges to be printed */
qh_printend4geom (NULL, facet, &num, printall);
FOREACHfacet_(facets)
qh_printend4geom (NULL, facet, &num, printall);
qh ridgeoutnum= num;
qh printoutvar= 0; /* counts number of ridges in output */
fprintf (fp, "LIST # %s | %s\n", qh rbox_command, qh qhull_command);
}
if (qh PRINTdots) {
qh printoutnum++;
num= qh num_points + qh_setsize (qh other_points);
if (qh DELAUNAY && qh ATinfinity)
num--;
if (qh PRINTdim == 4)
fprintf (fp, "4VECT %d %d 1\n", num, num);
else
fprintf (fp, "VECT %d %d 1\n", num, num);
for (i= num; i--; ) {
if (i % 20 == 0)
fprintf (fp, "\n");
fprintf (fp, "1 ");
}
fprintf (fp, "# 1 point per line\n1 ");
for (i= num-1; i--; ) {
if (i % 20 == 0)
fprintf (fp, "\n");
fprintf (fp, "0 ");
}
fprintf (fp, "# 1 color for all\n");
FORALLpoints {
if (!qh DELAUNAY || !qh ATinfinity || qh_pointid(point) != qh num_points-1) {
if (qh PRINTdim == 4)
qh_printpoint (fp, NULL, point);
else
qh_printpoint3 (fp, point);
}
}
FOREACHpoint_(qh other_points) {
if (qh PRINTdim == 4)
qh_printpoint (fp, NULL, point);
else
qh_printpoint3 (fp, point);
}
fprintf (fp, "0 1 1 1 # color of points\n");
}
if (qh PRINTdim == 4 && !qh PRINTnoplanes)
/* 4dview loads up multiple 4OFF objects slowly */
fprintf(fp, "4OFF %d %d 1\n", 3*qh ridgeoutnum, qh ridgeoutnum);
qh PRINTcradius= 2 * qh DISTround; /* include test DISTround */
if (qh PREmerge) {
maximize_(qh PRINTcradius, qh premerge_centrum + qh DISTround);
}else if (qh POSTmerge)
maximize_(qh PRINTcradius, qh postmerge_centrum + qh DISTround);
qh PRINTradius= qh PRINTcradius;
if (qh PRINTspheres + qh PRINTcoplanar)
maximize_(qh PRINTradius, qh MAXabs_coord * qh_MINradius);
if (qh premerge_cos < REALmax/2) {
maximize_(qh PRINTradius, (1- qh premerge_cos) * qh MAXabs_coord);
}else if (!qh PREmerge && qh POSTmerge && qh postmerge_cos < REALmax/2) {
maximize_(qh PRINTradius, (1- qh postmerge_cos) * qh MAXabs_coord);
}
maximize_(qh PRINTradius, qh MINvisible);
if (qh JOGGLEmax < REALmax/2)
qh PRINTradius += qh JOGGLEmax * sqrt ((double)qh hull_dim);
if (qh PRINTdim != 4 &&
(qh PRINTcoplanar || qh PRINTspheres || qh PRINTcentrums)) {
vertices= qh_facetvertices (facetlist, facets, printall);
if (qh PRINTspheres && qh PRINTdim <= 3)
qh_printspheres (fp, vertices, qh PRINTradius);
if (qh PRINTcoplanar || qh PRINTcentrums) {
qh firstcentrum= True;
if (qh PRINTcoplanar&& !qh PRINTspheres) {
FOREACHvertex_(vertices)
qh_printpointvect2 (fp, vertex->point, NULL,
qh interior_point, qh PRINTradius);
}
FORALLfacet_(facetlist) {
if (!printall && qh_skipfacet(facet))
continue;
if (!facet->normal)
continue;
if (qh PRINTcentrums && qh PRINTdim <= 3)
qh_printcentrum (fp, facet, qh PRINTcradius);
if (!qh PRINTcoplanar)
continue;
FOREACHpoint_(facet->coplanarset)
qh_printpointvect2 (fp, point, facet->normal, NULL, qh PRINTradius);
FOREACHpoint_(facet->outsideset)
qh_printpointvect2 (fp, point, facet->normal, NULL, qh PRINTradius);
}
FOREACHfacet_(facets) {
if (!printall && qh_skipfacet(facet))
continue;
if (!facet->normal)
continue;
if (qh PRINTcentrums && qh PRINTdim <= 3)
qh_printcentrum (fp, facet, qh PRINTcradius);
if (!qh PRINTcoplanar)
continue;
FOREACHpoint_(facet->coplanarset)
qh_printpointvect2 (fp, point, facet->normal, NULL, qh PRINTradius);
FOREACHpoint_(facet->outsideset)
qh_printpointvect2 (fp, point, facet->normal, NULL, qh PRINTradius);
}
}
qh_settempfree (&vertices);
}
qh visit_id++; /* for printing hyperplane intersections */
break;
case qh_PRINTids:
fprintf (fp, "%d\n", numfacets);
break;
case qh_PRINTincidences:
if (qh VORONOI && qh PRINTprecision)
fprintf (qh ferr, "qhull warning: writing Delaunay. Use 'p' or 'o' for Voronoi centers\n");
qh printoutvar= qh vertex_id; /* centrum id for non-simplicial facets */
if (qh hull_dim <= 3)
fprintf(fp, "%d\n", numfacets);
else
fprintf(fp, "%d\n", numsimplicial+numridges);
break;
case qh_PRINTinner:
case qh_PRINTnormals:
case qh_PRINTouter:
if (qh CDDoutput)
fprintf (fp, "%s | %s\nbegin\n %d %d real\n", qh rbox_command,
qh qhull_command, numfacets, qh hull_dim+1);
else
fprintf (fp, "%d\n%d\n", qh hull_dim+1, numfacets);
break;
case qh_PRINTmathematica:
case qh_PRINTmaple:
if (qh hull_dim > 3) /* qh_initbuffers also checks */
goto LABELnoformat;
if (qh VORONOI)
fprintf (qh ferr, "qhull warning: output is the Delaunay triangulation\n");
if (format == qh_PRINTmaple) {
if (qh hull_dim == 2)
fprintf(fp, "PLOT(CURVES(\n");
else
fprintf(fp, "PLOT3D(POLYGONS(\n");
}else
fprintf(fp, "{\n");
qh printoutvar= 0; /* counts number of facets for notfirst */
break;
case qh_PRINTmerges:
fprintf (fp, "%d\n", numfacets);
break;
case qh_PRINTpointintersect:
fprintf (fp, "%d\n%d\n", qh hull_dim, numfacets);
break;
case qh_PRINTneighbors:
fprintf (fp, "%d\n", numfacets);
break;
case qh_PRINToff:
case qh_PRINTtriangles:
if (qh VORONOI)
goto LABELnoformat;
num = qh hull_dim;
if (format == qh_PRINToff || qh hull_dim == 2)
fprintf (fp, "%d\n%d %d %d\n", num,
qh num_points+qh_setsize (qh other_points), numfacets, totneighbors/2);
else { /* qh_PRINTtriangles */
qh printoutvar= qh num_points+qh_setsize (qh other_points); /* first centrum */
if (qh DELAUNAY)
num--; /* drop last dimension */
fprintf (fp, "%d\n%d %d %d\n", num, qh printoutvar
+ numfacets - numsimplicial, numsimplicial + numridges, totneighbors/2);
}
FORALLpoints
qh_printpointid (qh fout, NULL, num, point, -1);
FOREACHpoint_(qh other_points)
qh_printpointid (qh fout, NULL, num, point, -1);
if (format == qh_PRINTtriangles && qh hull_dim > 2) {
FORALLfacets {
if (!facet->simplicial && facet->visitid)
qh_printcenter (qh fout, format, NULL, facet);
}
}
break;
case qh_PRINTpointnearest:
fprintf (fp, "%d\n", numcoplanars);
break;
case qh_PRINTpoints:
if (!qh VORONOI)
goto LABELnoformat;
if (qh CDDoutput)
fprintf (fp, "%s | %s\nbegin\n%d %d real\n", qh rbox_command,
qh qhull_command, numfacets, qh hull_dim);
else
fprintf (fp, "%d\n%d\n", qh hull_dim-1, numfacets);
break;
case qh_PRINTvertices:
fprintf (fp, "%d\n", numfacets);
break;
case qh_PRINTsummary:
default:
LABELnoformat:
fprintf (qh ferr, "qhull internal error (qh_printbegin): can not use this format for dimension %d\n",
qh hull_dim);
qh_errexit (qh_ERRqhull, NULL, NULL);
}
} /* printbegin */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="printcenter">-</a>
qh_printcenter( fp, string, facet )
print facet->center as centrum or Voronoi center
string may be NULL. Don't include '%' codes.
nop if qh CENTERtype neither CENTERvoronoi nor CENTERcentrum
if upper envelope of Delaunay triangulation and point at-infinity
prints qh_INFINITE instead;
notes:
defines facet->center if needed
if format=PRINTgeom, adds a 0 if would otherwise be 2-d
*/
void qh_printcenter (FILE *fp, int format, const char *string, facetT *facet) {
int k, num;
if (qh CENTERtype != qh_ASvoronoi && qh CENTERtype != qh_AScentrum)
return;
if (string)
fprintf (fp, string, facet->id);
if (qh CENTERtype == qh_ASvoronoi) {
num= qh hull_dim-1;
if (!facet->normal || !facet->upperdelaunay || !qh ATinfinity) {
if (!facet->center)
facet->center= qh_facetcenter (facet->vertices);
for (k=0; k < num; k++)
fprintf (fp, qh_REAL_1, facet->center[k]);
}else {
for (k=0; k < num; k++)
fprintf (fp, qh_REAL_1, qh_INFINITE);
}
}else /* qh CENTERtype == qh_AScentrum */ {
num= qh hull_dim;
if (format == qh_PRINTtriangles && qh DELAUNAY)
num--;
if (!facet->center)
facet->center= qh_getcentrum (facet);
for (k=0; k < num; k++)
fprintf (fp, qh_REAL_1, facet->center[k]);
}
if (format == qh_PRINTgeom && num == 2)
fprintf (fp, " 0\n");
else
fprintf (fp, "\n");
} /* printcenter */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="printcentrum">-</a>
qh_printcentrum( fp, facet, radius )
print centrum for a facet in OOGL format
radius defines size of centrum
2-d or 3-d only
returns:
defines facet->center if needed
*/
void qh_printcentrum (FILE *fp, facetT *facet, realT radius) {
pointT *centrum, *projpt;
boolT tempcentrum= False;
realT xaxis[4], yaxis[4], normal[4], dist;
realT green[3]={0, 1, 0};
vertexT *apex;
int k;
if (qh CENTERtype == qh_AScentrum) {
if (!facet->center)
facet->center= qh_getcentrum (facet);
centrum= facet->center;
}else {
centrum= qh_getcentrum (facet);
tempcentrum= True;
}
fprintf (fp, "{appearance {-normal -edge normscale 0} ");
if (qh firstcentrum) {
qh firstcentrum= False;
fprintf (fp, "{INST geom { define centrum CQUAD # f%d\n\
-0.3 -0.3 0.0001 0 0 1 1\n\
0.3 -0.3 0.0001 0 0 1 1\n\
0.3 0.3 0.0001 0 0 1 1\n\
-0.3 0.3 0.0001 0 0 1 1 } transform { \n", facet->id);
}else
fprintf (fp, "{INST geom { : centrum } transform { # f%d\n", facet->id);
apex= SETfirstt_(facet->vertices, vertexT);
qh_distplane(apex->point, facet, &dist);
projpt= qh_projectpoint(apex->point, facet, dist);
for (k= qh hull_dim; k--; ) {
xaxis[k]= projpt[k] - centrum[k];
normal[k]= facet->normal[k];
}
if (qh hull_dim == 2) {
xaxis[2]= 0;
normal[2]= 0;
}else if (qh hull_dim == 4) {
qh_projectdim3 (xaxis, xaxis);
qh_projectdim3 (normal, normal);
qh_normalize2 (normal, qh PRINTdim, True, NULL, NULL);
}
qh_crossproduct (3, xaxis, normal, yaxis);
fprintf (fp, "%8.4g %8.4g %8.4g 0\n", xaxis[0], xaxis[1], xaxis[2]);
fprintf (fp, "%8.4g %8.4g %8.4g 0\n", yaxis[0], yaxis[1], yaxis[2]);
fprintf (fp, "%8.4g %8.4g %8.4g 0\n", normal[0], normal[1], normal[2]);
qh_printpoint3 (fp, centrum);
fprintf (fp, "1 }}}\n");
qh_memfree (projpt, qh normal_size);
qh_printpointvect (fp, centrum, facet->normal, NULL, radius, green);
if (tempcentrum)
qh_memfree (centrum, qh normal_size);
} /* printcentrum */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="printend">-</a>
qh_printend( fp, format )
prints trailer for all output formats
see:
qh_printbegin() and qh_printafacet()
*/
void qh_printend (FILE *fp, int format, facetT *facetlist, setT *facets, boolT printall) {
int num;
facetT *facet, **facetp;
if (!qh printoutnum)
fprintf (qh ferr, "qhull warning: no facets printed\n");
switch (format) {
case qh_PRINTgeom:
if (qh hull_dim == 4 && qh DROPdim < 0 && !qh PRINTnoplanes) {
qh visit_id++;
num= 0;
FORALLfacet_(facetlist)
qh_printend4geom (fp, facet,&num, printall);
FOREACHfacet_(facets)
qh_printend4geom (fp, facet, &num, printall);
if (num != qh ridgeoutnum || qh printoutvar != qh ridgeoutnum) {
fprintf (qh ferr, "qhull internal error (qh_printend): number of ridges %d != number printed %d and at end %d\n", qh ridgeoutnum, qh printoutvar, num);
qh_errexit (qh_ERRqhull, NULL, NULL);
}
}else
fprintf(fp, "}\n");
break;
case qh_PRINTinner:
case qh_PRINTnormals:
case qh_PRINTouter:
if (qh CDDoutput)
fprintf (fp, "end\n");
break;
case qh_PRINTmaple:
fprintf(fp, "));\n");
break;
case qh_PRINTmathematica:
fprintf(fp, "}\n");
break;
case qh_PRINTpoints:
if (qh CDDoutput)
fprintf (fp, "end\n");
break;
}
} /* printend */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="printend4geom">-</a>
qh_printend4geom( fp, facet, numridges, printall )
helper function for qh_printbegin/printend
returns:
number of printed ridges
notes:
just counts printed ridges if fp=NULL
uses facet->visitid
must agree with qh_printfacet4geom...
design:
computes color for facet from its normal
prints each ridge of facet
*/
void qh_printend4geom (FILE *fp, facetT *facet, int *nump, boolT printall) {
realT color[3];
int i, num= *nump;
facetT *neighbor, **neighborp;
ridgeT *ridge, **ridgep;
if (!printall && qh_skipfacet(facet))
return;
if (qh PRINTnoplanes || (facet->visible && qh NEWfacets))
return;
if (!facet->normal)
return;
if (fp) {
for (i=0; i < 3; i++) {
color[i]= (facet->normal[i]+1.0)/2.0;
maximize_(color[i], -1.0);
minimize_(color[i], +1.0);
}
}
facet->visitid= qh visit_id;
if (facet->simplicial) {
FOREACHneighbor_(facet) {
if (neighbor->visitid != qh visit_id) {
if (fp)
fprintf (fp, "3 %d %d %d %8.4g %8.4g %8.4g 1 # f%d f%d\n",
3*num, 3*num+1, 3*num+2, color[0], color[1], color[2],
facet->id, neighbor->id);
num++;
}
}
}else {
FOREACHridge_(facet->ridges) {
neighbor= otherfacet_(ridge, facet);
if (neighbor->visitid != qh visit_id) {
if (fp)
fprintf (fp, "3 %d %d %d %8.4g %8.4g %8.4g 1 #r%d f%d f%d\n",
3*num, 3*num+1, 3*num+2, color[0], color[1], color[2],
ridge->id, facet->id, neighbor->id);
num++;
}
}
}
*nump= num;
} /* printend4geom */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="printextremes">-</a>
qh_printextremes( fp, facetlist, facets, printall )
print extreme points for convex hulls or halfspace intersections
notes:
#points, followed by ids, one per line
sorted by id
same order as qh_printpoints_out if no coplanar/interior points
*/
void qh_printextremes (FILE *fp, facetT *facetlist, setT *facets, int printall) {
setT *vertices, *points;
pointT *point;
vertexT *vertex, **vertexp;
int id;
int numpoints=0, point_i, point_n;
int allpoints= qh num_points + qh_setsize (qh other_points);
points= qh_settemp (allpoints);
qh_setzero (points, 0, allpoints);
vertices= qh_facetvertices (facetlist, facets, printall);
FOREACHvertex_(vertices) {
id= qh_pointid (vertex->point);
if (id >= 0) {
SETelem_(points, id)= vertex->point;
numpoints++;
}
}
qh_settempfree (&vertices);
fprintf (fp, "%d\n", numpoints);
FOREACHpoint_i_(points) {
if (point)
fprintf (fp, "%d\n", point_i);
}
qh_settempfree (&points);
} /* printextremes */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="printextremes_2d">-</a>
qh_printextremes_2d( fp, facetlist, facets, printall )
prints point ids for facets in qh_ORIENTclock order
notes:
#points, followed by ids, one per line
if facetlist/facets are disjoint than the output includes skips
errors if facets form a loop
does not print coplanar points
*/
void qh_printextremes_2d (FILE *fp, facetT *facetlist, setT *facets, int printall) {
int numfacets, numridges, totneighbors, numcoplanars, numsimplicial, numtricoplanars;
setT *vertices;
facetT *facet, *startfacet, *nextfacet;
vertexT *vertexA, *vertexB;
qh_countfacets (facetlist, facets, printall, &numfacets, &numsimplicial,
&totneighbors, &numridges, &numcoplanars, &numtricoplanars); /* marks qh visit_id */
vertices= qh_facetvertices (facetlist, facets, printall);
fprintf(fp, "%d\n", qh_setsize (vertices));
qh_settempfree (&vertices);
if (!numfacets)
return;
facet= startfacet= facetlist ? facetlist : SETfirstt_(facets, facetT);
qh vertex_visit++;
qh visit_id++;
do {
if (facet->toporient ^ qh_ORIENTclock) {
vertexA= SETfirstt_(facet->vertices, vertexT);
vertexB= SETsecondt_(facet->vertices, vertexT);
nextfacet= SETfirstt_(facet->neighbors, facetT);
}else {
vertexA= SETsecondt_(facet->vertices, vertexT);
vertexB= SETfirstt_(facet->vertices, vertexT);
nextfacet= SETsecondt_(facet->neighbors, facetT);
}
if (facet->visitid == qh visit_id) {
fprintf(qh ferr, "qh_printextremes_2d: loop in facet list. facet %d nextfacet %d\n",
facet->id, nextfacet->id);
qh_errexit2 (qh_ERRqhull, facet, nextfacet);
}
if (facet->visitid) {
if (vertexA->visitid != qh vertex_visit) {
vertexA->visitid= qh vertex_visit;
fprintf(fp, "%d\n", qh_pointid (vertexA->point));
}
if (vertexB->visitid != qh vertex_visit) {
vertexB->visitid= qh vertex_visit;
fprintf(fp, "%d\n", qh_pointid (vertexB->point));
}
}
facet->visitid= qh visit_id;
facet= nextfacet;
}while (facet && facet != startfacet);
} /* printextremes_2d */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="printextremes_d">-</a>
qh_printextremes_d( fp, facetlist, facets, printall )
print extreme points of input sites for Delaunay triangulations
notes:
#points, followed by ids, one per line
unordered
*/
void qh_printextremes_d (FILE *fp, facetT *facetlist, setT *facets, int printall) {
setT *vertices;
vertexT *vertex, **vertexp;
boolT upperseen, lowerseen;
facetT *neighbor, **neighborp;
int numpoints=0;
vertices= qh_facetvertices (facetlist, facets, printall);
qh_vertexneighbors();
FOREACHvertex_(vertices) {
upperseen= lowerseen= False;
FOREACHneighbor_(vertex) {
if (neighbor->upperdelaunay)
upperseen= True;
else
lowerseen= True;
}
if (upperseen && lowerseen) {
vertex->seen= True;
numpoints++;
}else
vertex->seen= False;
}
fprintf (fp, "%d\n", numpoints);
FOREACHvertex_(vertices) {
if (vertex->seen)
fprintf (fp, "%d\n", qh_pointid (vertex->point));
}
qh_settempfree (&vertices);
} /* printextremes_d */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="printfacet">-</a>
qh_printfacet( fp, facet )
prints all fields of a facet to fp
notes:
ridges printed in neighbor order
*/
void qh_printfacet(FILE *fp, facetT *facet) {
qh_printfacetheader (fp, facet);
if (facet->ridges)
qh_printfacetridges (fp, facet);
} /* printfacet */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="printfacet2geom">-</a>
qh_printfacet2geom( fp, facet, color )
print facet as part of a 2-d VECT for Geomview
notes:
assume precise calculations in io.c with roundoff covered by qh_GEOMepsilon
mindist is calculated within io.c. maxoutside is calculated elsewhere
so a DISTround error may have occured.
*/
void qh_printfacet2geom(FILE *fp, facetT *facet, realT color[3]) {
pointT *point0, *point1;
realT mindist, innerplane, outerplane;
int k;
qh_facet2point (facet, &point0, &point1, &mindist);
qh_geomplanes (facet, &outerplane, &innerplane);
if (qh PRINTouter || (!qh PRINTnoplanes && !qh PRINTinner))
qh_printfacet2geom_points(fp, point0, point1, facet, outerplane, color);
if (qh PRINTinner || (!qh PRINTnoplanes && !qh PRINTouter &&
outerplane - innerplane > 2 * qh MAXabs_coord * qh_GEOMepsilon)) {
for(k= 3; k--; )
color[k]= 1.0 - color[k];
qh_printfacet2geom_points(fp, point0, point1, facet, innerplane, color);
}
qh_memfree (point1, qh normal_size);
qh_memfree (point0, qh normal_size);
} /* printfacet2geom */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="printfacet2geom_points">-</a>
qh_printfacet2geom_points( fp, point1, point2, facet, offset, color )
prints a 2-d facet as a VECT with 2 points at some offset.
The points are on the facet's plane.
*/
void qh_printfacet2geom_points(FILE *fp, pointT *point1, pointT *point2,
facetT *facet, realT offset, realT color[3]) {
pointT *p1= point1, *p2= point2;
fprintf(fp, "VECT 1 2 1 2 1 # f%d\n", facet->id);
if (offset != 0.0) {
p1= qh_projectpoint (p1, facet, -offset);
p2= qh_projectpoint (p2, facet, -offset);
}
fprintf(fp, "%8.4g %8.4g %8.4g\n%8.4g %8.4g %8.4g\n",
p1[0], p1[1], 0.0, p2[0], p2[1], 0.0);
if (offset != 0.0) {
qh_memfree (p1, qh normal_size);
qh_memfree (p2, qh normal_size);
}
fprintf(fp, "%8.4g %8.4g %8.4g 1.0\n", color[0], color[1], color[2]);
} /* printfacet2geom_points */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="printfacet2math">-</a>
qh_printfacet2math( fp, facet, format, notfirst )
print 2-d Maple or Mathematica output for a facet
may be non-simplicial
notes:
use %16.8f since Mathematica 2.2 does not handle exponential format
see qh_printfacet3math
*/
void qh_printfacet2math(FILE *fp, facetT *facet, int format, int notfirst) {
pointT *point0, *point1;
realT mindist;
const char *pointfmt;
qh_facet2point (facet, &point0, &point1, &mindist);
if (notfirst)
fprintf(fp, ",");
if (format == qh_PRINTmaple)
pointfmt= "[[%16.8f, %16.8f], [%16.8f, %16.8f]]\n";
else
pointfmt= "Line[{{%16.8f, %16.8f}, {%16.8f, %16.8f}}]\n";
fprintf(fp, pointfmt, point0[0], point0[1], point1[0], point1[1]);
qh_memfree (point1, qh normal_size);
qh_memfree (point0, qh normal_size);
} /* printfacet2math */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="printfacet3geom_nonsimplicial">-</a>
qh_printfacet3geom_nonsimplicial( fp, facet, color )
print Geomview OFF for a 3-d nonsimplicial facet.
if DOintersections, prints ridges to unvisited neighbors (qh visit_id)
notes
uses facet->visitid for intersections and ridges
*/
void qh_printfacet3geom_nonsimplicial(FILE *fp, facetT *facet, realT color[3]) {
ridgeT *ridge, **ridgep;
setT *projectedpoints, *vertices;
vertexT *vertex, **vertexp, *vertexA, *vertexB;
pointT *projpt, *point, **pointp;
facetT *neighbor;
realT dist, outerplane, innerplane;
int cntvertices, k;
realT black[3]={0, 0, 0}, green[3]={0, 1, 0};
qh_geomplanes (facet, &outerplane, &innerplane);
vertices= qh_facet3vertex (facet); /* oriented */
cntvertices= qh_setsize(vertices);
projectedpoints= qh_settemp(cntvertices);
FOREACHvertex_(vertices) {
zinc_(Zdistio);
qh_distplane(vertex->point, facet, &dist);
projpt= qh_projectpoint(vertex->point, facet, dist);
qh_setappend (&projectedpoints, projpt);
}
if (qh PRINTouter || (!qh PRINTnoplanes && !qh PRINTinner))
qh_printfacet3geom_points(fp, projectedpoints, facet, outerplane, color);
if (qh PRINTinner || (!qh PRINTnoplanes && !qh PRINTouter &&
outerplane - innerplane > 2 * qh MAXabs_coord * qh_GEOMepsilon)) {
for (k=3; k--; )
color[k]= 1.0 - color[k];
qh_printfacet3geom_points(fp, projectedpoints, facet, innerplane, color);
}
FOREACHpoint_(projectedpoints)
qh_memfree (point, qh normal_size);
qh_settempfree(&projectedpoints);
qh_settempfree(&vertices);
if ((qh DOintersections || qh PRINTridges)
&& (!facet->visible || !qh NEWfacets)) {
facet->visitid= qh visit_id;
FOREACHridge_(facet->ridges) {
neighbor= otherfacet_(ridge, facet);
if (neighbor->visitid != qh visit_id) {
if (qh DOintersections)
qh_printhyperplaneintersection(fp, facet, neighbor, ridge->vertices, black);
if (qh PRINTridges) {
vertexA= SETfirstt_(ridge->vertices, vertexT);
vertexB= SETsecondt_(ridge->vertices, vertexT);
qh_printline3geom (fp, vertexA->point, vertexB->point, green);
}
}
}
}
} /* printfacet3geom_nonsimplicial */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="printfacet3geom_points">-</a>
qh_printfacet3geom_points( fp, points, facet, offset )
prints a 3-d facet as OFF Geomview object.
offset is relative to the facet's hyperplane
Facet is determined as a list of points
*/
void qh_printfacet3geom_points(FILE *fp, setT *points, facetT *facet, realT offset, realT color[3]) {
int k, n= qh_setsize(points), i;
pointT *point, **pointp;
setT *printpoints;
fprintf(fp, "{ OFF %d 1 1 # f%d\n", n, facet->id);
if (offset != 0.0) {
printpoints= qh_settemp (n);
FOREACHpoint_(points)
qh_setappend (&printpoints, qh_projectpoint(point, facet, -offset));
}else
printpoints= points;
FOREACHpoint_(printpoints) {
for (k=0; k < qh hull_dim; k++) {
if (k == qh DROPdim)
fprintf(fp, "0 ");
else
fprintf(fp, "%8.4g ", point[k]);
}
if (printpoints != points)
qh_memfree (point, qh normal_size);
fprintf (fp, "\n");
}
if (printpoints != points)
qh_settempfree (&printpoints);
fprintf(fp, "%d ", n);
for(i= 0; i < n; i++)
fprintf(fp, "%d ", i);
fprintf(fp, "%8.4g %8.4g %8.4g 1.0 }\n", color[0], color[1], color[2]);
} /* printfacet3geom_points */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="printfacet3geom_simplicial">-</a>
qh_printfacet3geom_simplicial( )
print Geomview OFF for a 3-d simplicial facet.
notes:
may flip color
uses facet->visitid for intersections and ridges
assume precise calculations in io.c with roundoff covered by qh_GEOMepsilon
innerplane may be off by qh DISTround. Maxoutside is calculated elsewhere
so a DISTround error may have occured.
*/
void qh_printfacet3geom_simplicial(FILE *fp, facetT *facet, realT color[3]) {
setT *points, *vertices;
vertexT *vertex, **vertexp, *vertexA, *vertexB;
facetT *neighbor, **neighborp;
realT outerplane, innerplane;
realT black[3]={0, 0, 0}, green[3]={0, 1, 0};
int k;
qh_geomplanes (facet, &outerplane, &innerplane);
vertices= qh_facet3vertex (facet);
points= qh_settemp (qh TEMPsize);
FOREACHvertex_(vertices)
qh_setappend(&points, vertex->point);
if (qh PRINTouter || (!qh PRINTnoplanes && !qh PRINTinner))
qh_printfacet3geom_points(fp, points, facet, outerplane, color);
if (qh PRINTinner || (!qh PRINTnoplanes && !qh PRINTouter &&
outerplane - innerplane > 2 * qh MAXabs_coord * qh_GEOMepsilon)) {
for (k= 3; k--; )
color[k]= 1.0 - color[k];
qh_printfacet3geom_points(fp, points, facet, innerplane, color);
}
qh_settempfree(&points);
qh_settempfree(&vertices);
if ((qh DOintersections || qh PRINTridges)
&& (!facet->visible || !qh NEWfacets)) {
facet->visitid= qh visit_id;
FOREACHneighbor_(facet) {
if (neighbor->visitid != qh visit_id) {
vertices= qh_setnew_delnthsorted (facet->vertices, qh hull_dim,
SETindex_(facet->neighbors, neighbor), 0);
if (qh DOintersections)
qh_printhyperplaneintersection(fp, facet, neighbor, vertices, black);
if (qh PRINTridges) {
vertexA= SETfirstt_(vertices, vertexT);
vertexB= SETsecondt_(vertices, vertexT);
qh_printline3geom (fp, vertexA->point, vertexB->point, green);
}
qh_setfree(&vertices);
}
}
}
} /* printfacet3geom_simplicial */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="printfacet3math">-</a>
qh_printfacet3math( fp, facet, notfirst )
print 3-d Maple or Mathematica output for a facet
notes:
may be non-simplicial
use %16.8f since Mathematica 2.2 does not handle exponential format
see qh_printfacet2math
*/
void qh_printfacet3math (FILE *fp, facetT *facet, int format, int notfirst) {
vertexT *vertex, **vertexp;
setT *points, *vertices;
pointT *point, **pointp;
boolT firstpoint= True;
realT dist;
const char *pointfmt, *endfmt;
if (notfirst)
fprintf(fp, ",\n");
vertices= qh_facet3vertex (facet);
points= qh_settemp (qh_setsize (vertices));
FOREACHvertex_(vertices) {
zinc_(Zdistio);
qh_distplane(vertex->point, facet, &dist);
point= qh_projectpoint(vertex->point, facet, dist);
qh_setappend (&points, point);
}
if (format == qh_PRINTmaple) {
fprintf(fp, "[");
pointfmt= "[%16.8f, %16.8f, %16.8f]";
endfmt= "]";
}else {
fprintf(fp, "Polygon[{");
pointfmt= "{%16.8f, %16.8f, %16.8f}";
endfmt= "}]";
}
FOREACHpoint_(points) {
if (firstpoint)
firstpoint= False;
else
fprintf(fp, ",\n");
fprintf(fp, pointfmt, point[0], point[1], point[2]);
}
FOREACHpoint_(points)
qh_memfree (point, qh normal_size);
qh_settempfree(&points);
qh_settempfree(&vertices);
fprintf(fp, endfmt);
} /* printfacet3math */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="printfacet3vertex">-</a>
qh_printfacet3vertex( fp, facet, format )
print vertices in a 3-d facet as point ids
notes:
prints number of vertices first if format == qh_PRINToff
the facet may be non-simplicial
*/
void qh_printfacet3vertex(FILE *fp, facetT *facet, int format) {
vertexT *vertex, **vertexp;
setT *vertices;
vertices= qh_facet3vertex (facet);
if (format == qh_PRINToff)
fprintf (fp, "%d ", qh_setsize (vertices));
FOREACHvertex_(vertices)
fprintf (fp, "%d ", qh_pointid(vertex->point));
fprintf (fp, "\n");
qh_settempfree(&vertices);
} /* printfacet3vertex */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="printfacet4geom_nonsimplicial">-</a>
qh_printfacet4geom_nonsimplicial( )
print Geomview 4OFF file for a 4d nonsimplicial facet
prints all ridges to unvisited neighbors (qh.visit_id)
if qh.DROPdim
prints in OFF format
notes:
must agree with printend4geom()
*/
void qh_printfacet4geom_nonsimplicial(FILE *fp, facetT *facet, realT color[3]) {
facetT *neighbor;
ridgeT *ridge, **ridgep;
vertexT *vertex, **vertexp;
pointT *point;
int k;
realT dist;
facet->visitid= qh visit_id;
if (qh PRINTnoplanes || (facet->visible && qh NEWfacets))
return;
FOREACHridge_(facet->ridges) {
neighbor= otherfacet_(ridge, facet);
if (neighbor->visitid == qh visit_id)
continue;
if (qh PRINTtransparent && !neighbor->good)
continue;
if (qh DOintersections)
qh_printhyperplaneintersection(fp, facet, neighbor, ridge->vertices, color);
else {
if (qh DROPdim >= 0)
fprintf(fp, "OFF 3 1 1 # f%d\n", facet->id);
else {
qh printoutvar++;
fprintf (fp, "# r%d between f%d f%d\n", ridge->id, facet->id, neighbor->id);
}
FOREACHvertex_(ridge->vertices) {
zinc_(Zdistio);
qh_distplane(vertex->point,facet, &dist);
point=qh_projectpoint(vertex->point,facet, dist);
for(k= 0; k < qh hull_dim; k++) {
if (k != qh DROPdim)
fprintf(fp, "%8.4g ", point[k]);
}
fprintf (fp, "\n");
qh_memfree (point, qh normal_size);
}
if (qh DROPdim >= 0)
fprintf(fp, "3 0 1 2 %8.4g %8.4g %8.4g\n", color[0], color[1], color[2]);
}
}
} /* printfacet4geom_nonsimplicial */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="printfacet4geom_simplicial">-</a>
qh_printfacet4geom_simplicial( fp, facet, color )
print Geomview 4OFF file for a 4d simplicial facet
prints triangles for unvisited neighbors (qh.visit_id)
notes:
must agree with printend4geom()
*/
void qh_printfacet4geom_simplicial(FILE *fp, facetT *facet, realT color[3]) {
setT *vertices;
facetT *neighbor, **neighborp;
vertexT *vertex, **vertexp;
int k;
facet->visitid= qh visit_id;
if (qh PRINTnoplanes || (facet->visible && qh NEWfacets))
return;
FOREACHneighbor_(facet) {
if (neighbor->visitid == qh visit_id)
continue;
if (qh PRINTtransparent && !neighbor->good)
continue;
vertices= qh_setnew_delnthsorted (facet->vertices, qh hull_dim,
SETindex_(facet->neighbors, neighbor), 0);
if (qh DOintersections)
qh_printhyperplaneintersection(fp, facet, neighbor, vertices, color);
else {
if (qh DROPdim >= 0)
fprintf(fp, "OFF 3 1 1 # ridge between f%d f%d\n",
facet->id, neighbor->id);
else {
qh printoutvar++;
fprintf (fp, "# ridge between f%d f%d\n", facet->id, neighbor->id);
}
FOREACHvertex_(vertices) {
for(k= 0; k < qh hull_dim; k++) {
if (k != qh DROPdim)
fprintf(fp, "%8.4g ", vertex->point[k]);
}
fprintf (fp, "\n");
}
if (qh DROPdim >= 0)
fprintf(fp, "3 0 1 2 %8.4g %8.4g %8.4g\n", color[0], color[1], color[2]);
}
qh_setfree(&vertices);
}
} /* printfacet4geom_simplicial */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="printfacetNvertex_nonsimplicial">-</a>
qh_printfacetNvertex_nonsimplicial( fp, facet, id, format )
print vertices for an N-d non-simplicial facet
triangulates each ridge to the id
*/
void qh_printfacetNvertex_nonsimplicial(FILE *fp, facetT *facet, int id, int format) {
vertexT *vertex, **vertexp;
ridgeT *ridge, **ridgep;
if (facet->visible && qh NEWfacets)
return;
FOREACHridge_(facet->ridges) {
if (format == qh_PRINTtriangles)
fprintf(fp, "%d ", qh hull_dim);
fprintf(fp, "%d ", id);
if ((ridge->top == facet) ^ qh_ORIENTclock) {
FOREACHvertex_(ridge->vertices)
fprintf(fp, "%d ", qh_pointid(vertex->point));
}else {
FOREACHvertexreverse12_(ridge->vertices)
fprintf(fp, "%d ", qh_pointid(vertex->point));
}
fprintf(fp, "\n");
}
} /* printfacetNvertex_nonsimplicial */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="printfacetNvertex_simplicial">-</a>
qh_printfacetNvertex_simplicial( fp, facet, format )
print vertices for an N-d simplicial facet
prints vertices for non-simplicial facets
2-d facets (orientation preserved by qh_mergefacet2d)
PRINToff ('o') for 4-d and higher
*/
void qh_printfacetNvertex_simplicial(FILE *fp, facetT *facet, int format) {
vertexT *vertex, **vertexp;
if (format == qh_PRINToff || format == qh_PRINTtriangles)
fprintf (fp, "%d ", qh_setsize (facet->vertices));
if ((facet->toporient ^ qh_ORIENTclock)
|| (qh hull_dim > 2 && !facet->simplicial)) {
FOREACHvertex_(facet->vertices)
fprintf(fp, "%d ", qh_pointid(vertex->point));
}else {
FOREACHvertexreverse12_(facet->vertices)
fprintf(fp, "%d ", qh_pointid(vertex->point));
}
fprintf(fp, "\n");
} /* printfacetNvertex_simplicial */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="printfacetheader">-</a>
qh_printfacetheader( fp, facet )
prints header fields of a facet to fp
notes:
for 'f' output and debugging
*/
void qh_printfacetheader(FILE *fp, facetT *facet) {
pointT *point, **pointp, *furthest;
facetT *neighbor, **neighborp;
realT dist;
if (facet == qh_MERGEridge) {
fprintf (fp, " MERGEridge\n");
return;
}else if (facet == qh_DUPLICATEridge) {
fprintf (fp, " DUPLICATEridge\n");
return;
}else if (!facet) {
fprintf (fp, " NULLfacet\n");
return;
}
qh old_randomdist= qh RANDOMdist;
qh RANDOMdist= False;
fprintf(fp, "- f%d\n", facet->id);
fprintf(fp, " - flags:");
if (facet->toporient)
fprintf(fp, " top");
else
fprintf(fp, " bottom");
if (facet->simplicial)
fprintf(fp, " simplicial");
if (facet->tricoplanar)
fprintf(fp, " tricoplanar");
if (facet->upperdelaunay)
fprintf(fp, " upperDelaunay");
if (facet->visible)
fprintf(fp, " visible");
if (facet->newfacet)
fprintf(fp, " new");
if (facet->tested)
fprintf(fp, " tested");
if (!facet->good)
fprintf(fp, " notG");
if (facet->seen)
fprintf(fp, " seen");
if (facet->coplanar)
fprintf(fp, " coplanar");
if (facet->mergehorizon)
fprintf(fp, " mergehorizon");
if (facet->keepcentrum)
fprintf(fp, " keepcentrum");
if (facet->dupridge)
fprintf(fp, " dupridge");
if (facet->mergeridge && !facet->mergeridge2)
fprintf(fp, " mergeridge1");
if (facet->mergeridge2)
fprintf(fp, " mergeridge2");
if (facet->newmerge)
fprintf(fp, " newmerge");
if (facet->flipped)
fprintf(fp, " flipped");
if (facet->notfurthest)
fprintf(fp, " notfurthest");
if (facet->degenerate)
fprintf(fp, " degenerate");
if (facet->redundant)
fprintf(fp, " redundant");
fprintf(fp, "\n");
if (facet->isarea)
fprintf(fp, " - area: %2.2g\n", facet->f.area);
else if (qh NEWfacets && facet->visible && facet->f.replace)
fprintf(fp, " - replacement: f%d\n", facet->f.replace->id);
else if (facet->newfacet) {
if (facet->f.samecycle && facet->f.samecycle != facet)
fprintf(fp, " - shares same visible/horizon as f%d\n", facet->f.samecycle->id);
}else if (facet->tricoplanar /* !isarea */) {
if (facet->f.triowner)
fprintf(fp, " - owner of normal & centrum is facet f%d\n", facet->f.triowner->id);
}else if (facet->f.newcycle)
fprintf(fp, " - was horizon to f%d\n", facet->f.newcycle->id);
if (facet->nummerge)
fprintf(fp, " - merges: %d\n", facet->nummerge);
qh_printpointid(fp, " - normal: ", qh hull_dim, facet->normal, -1);
fprintf(fp, " - offset: %10.7g\n", facet->offset);
if (qh CENTERtype == qh_ASvoronoi || facet->center)
qh_printcenter (fp, qh_PRINTfacets, " - center: ", facet);
#if qh_MAXoutside
if (facet->maxoutside > qh DISTround)
fprintf(fp, " - maxoutside: %10.7g\n", facet->maxoutside);
#endif
if (!SETempty_(facet->outsideset)) {
furthest= (pointT*)qh_setlast(facet->outsideset);
if (qh_setsize (facet->outsideset) < 6) {
fprintf(fp, " - outside set (furthest p%d):\n", qh_pointid(furthest));
FOREACHpoint_(facet->outsideset)
qh_printpoint(fp, " ", point);
}else if (qh_setsize (facet->outsideset) < 21) {
qh_printpoints(fp, " - outside set:", facet->outsideset);
}else {
fprintf(fp, " - outside set: %d points.", qh_setsize(facet->outsideset));
qh_printpoint(fp, " Furthest", furthest);
}
#if !qh_COMPUTEfurthest
fprintf(fp, " - furthest distance= %2.2g\n", facet->furthestdist);
#endif
}
if (!SETempty_(facet->coplanarset)) {
furthest= (pointT*)qh_setlast(facet->coplanarset);
if (qh_setsize (facet->coplanarset) < 6) {
fprintf(fp, " - coplanar set (furthest p%d):\n", qh_pointid(furthest));
FOREACHpoint_(facet->coplanarset)
qh_printpoint(fp, " ", point);
}else if (qh_setsize (facet->coplanarset) < 21) {
qh_printpoints(fp, " - coplanar set:", facet->coplanarset);
}else {
fprintf(fp, " - coplanar set: %d points.", qh_setsize(facet->coplanarset));
qh_printpoint(fp, " Furthest", furthest);
}
zinc_(Zdistio);
qh_distplane (furthest, facet, &dist);
fprintf(fp, " furthest distance= %2.2g\n", dist);
}
qh_printvertices (fp, " - vertices:", facet->vertices);
fprintf(fp, " - neighboring facets: ");
FOREACHneighbor_(facet) {
if (neighbor == qh_MERGEridge)
fprintf(fp, " MERGE");
else if (neighbor == qh_DUPLICATEridge)
fprintf(fp, " DUP");
else
fprintf(fp, " f%d", neighbor->id);
}
fprintf(fp, "\n");
qh RANDOMdist= qh old_randomdist;
} /* printfacetheader */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="printfacetridges">-</a>
qh_printfacetridges( fp, facet )
prints ridges of a facet to fp
notes:
ridges printed in neighbor order
assumes the ridges exist
for 'f' output
*/
void qh_printfacetridges(FILE *fp, facetT *facet) {
facetT *neighbor, **neighborp;
ridgeT *ridge, **ridgep;
int numridges= 0;
if (facet->visible && qh NEWfacets) {
fprintf(fp, " - ridges (ids may be garbage):");
FOREACHridge_(facet->ridges)
fprintf(fp, " r%d", ridge->id);
fprintf(fp, "\n");
}else {
fprintf(fp, " - ridges:\n");
FOREACHridge_(facet->ridges)
ridge->seen= False;
if (qh hull_dim == 3) {
ridge= SETfirstt_(facet->ridges, ridgeT);
while (ridge && !ridge->seen) {
ridge->seen= True;
qh_printridge(fp, ridge);
numridges++;
ridge= qh_nextridge3d (ridge, facet, NULL);
}
}else {
FOREACHneighbor_(facet) {
FOREACHridge_(facet->ridges) {
if (otherfacet_(ridge,facet) == neighbor) {
ridge->seen= True;
qh_printridge(fp, ridge);
numridges++;
}
}
}
}
if (numridges != qh_setsize (facet->ridges)) {
fprintf (fp, " - all ridges:");
FOREACHridge_(facet->ridges)
fprintf (fp, " r%d", ridge->id);
fprintf (fp, "\n");
}
FOREACHridge_(facet->ridges) {
if (!ridge->seen)
qh_printridge(fp, ridge);
}
}
} /* printfacetridges */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="printfacets">-</a>
qh_printfacets( fp, format, facetlist, facets, printall )
prints facetlist and/or facet set in output format
notes:
also used for specialized formats ('FO' and summary)
turns off 'Rn' option since want actual numbers
*/
void qh_printfacets(FILE *fp, int format, facetT *facetlist, setT *facets, boolT printall) {
int numfacets, numsimplicial, numridges, totneighbors, numcoplanars, numtricoplanars;
facetT *facet, **facetp;
setT *vertices;
coordT *center;
realT outerplane, innerplane;
qh old_randomdist= qh RANDOMdist;
qh RANDOMdist= False;
if (qh CDDoutput && (format == qh_PRINTcentrums || format == qh_PRINTpointintersect || format == qh_PRINToff))
fprintf (qh ferr, "qhull warning: CDD format is not available for centrums, halfspace\nintersections, and OFF file format.\n");
if (format == qh_PRINTnone)
; /* print nothing */
else if (format == qh_PRINTaverage) {
vertices= qh_facetvertices (facetlist, facets, printall);
center= qh_getcenter (vertices);
fprintf (fp, "%d 1\n", qh hull_dim);
qh_printpointid (fp, NULL, qh hull_dim, center, -1);
qh_memfree (center, qh normal_size);
qh_settempfree (&vertices);
}else if (format == qh_PRINTextremes) {
if (qh DELAUNAY)
qh_printextremes_d (fp, facetlist, facets, printall);
else if (qh hull_dim == 2)
qh_printextremes_2d (fp, facetlist, facets, printall);
else
qh_printextremes (fp, facetlist, facets, printall);
}else if (format == qh_PRINToptions)
fprintf(fp, "Options selected for Qhull:\n%s\n", qh qhull_options);
//fprintf(fp, "Options selected for Qhull %s:\n%s\n", qh_version, qh qhull_options);
else if (format == qh_PRINTpoints && !qh VORONOI)
qh_printpoints_out (fp, facetlist, facets, printall);
else if (format == qh_PRINTqhull)
fprintf (fp, "%s | %s\n", qh rbox_command, qh qhull_command);
else if (format == qh_PRINTsize) {
fprintf (fp, "0\n2 ");
fprintf (fp, qh_REAL_1, qh totarea);
fprintf (fp, qh_REAL_1, qh totvol);
fprintf (fp, "\n");
}else if (format == qh_PRINTsummary) {
qh_countfacets (facetlist, facets, printall, &numfacets, &numsimplicial,
&totneighbors, &numridges, &numcoplanars, &numtricoplanars);
vertices= qh_facetvertices (facetlist, facets, printall);
fprintf (fp, "10 %d %d %d %d %d %d %d %d %d %d\n2 ", qh hull_dim,
qh num_points + qh_setsize (qh other_points),
qh num_vertices, qh num_facets - qh num_visible,
qh_setsize (vertices), numfacets, numcoplanars,
numfacets - numsimplicial, zzval_(Zdelvertextot),
numtricoplanars);
qh_settempfree (&vertices);
qh_outerinner (NULL, &outerplane, &innerplane);
fprintf (fp, qh_REAL_2n, outerplane, innerplane);
}else if (format == qh_PRINTvneighbors)
qh_printvneighbors (fp, facetlist, facets, printall);
else if (qh VORONOI && format == qh_PRINToff)
qh_printvoronoi (fp, format, facetlist, facets, printall);
else if (qh VORONOI && format == qh_PRINTgeom) {
qh_printbegin (fp, format, facetlist, facets, printall);
qh_printvoronoi (fp, format, facetlist, facets, printall);
qh_printend (fp, format, facetlist, facets, printall);
}else if (qh VORONOI
&& (format == qh_PRINTvertices || format == qh_PRINTinner || format == qh_PRINTouter))
qh_printvdiagram (fp, format, facetlist, facets, printall);
else {
qh_printbegin (fp, format, facetlist, facets, printall);
FORALLfacet_(facetlist)
qh_printafacet (fp, format, facet, printall);
FOREACHfacet_(facets)
qh_printafacet (fp, format, facet, printall);
qh_printend (fp, format, facetlist, facets, printall);
}
qh RANDOMdist= qh old_randomdist;
} /* printfacets */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="printhelp_degenerate">-</a>
qh_printhelp_degenerate( fp )
prints descriptive message for precision error
notes:
no message if qh_QUICKhelp
*/
void qh_printhelp_degenerate(FILE *fp) {
if (qh MERGEexact || qh PREmerge || qh JOGGLEmax < REALmax/2)
fprintf(fp, "\n\
A Qhull error has occurred. Qhull should have corrected the above\n\
precision error. Please send the input and all of the output to\n\
qhull_bug@qhull.org\n");
else if (!qh_QUICKhelp) {
fprintf(fp, "\n\
Precision problems were detected during construction of the convex hull.\n\
This occurs because convex hull algorithms assume that calculations are\n\
exact, but floating-point arithmetic has roundoff errors.\n\
\n\
To correct for precision problems, do not use 'Q0'. By default, Qhull\n\
selects 'C-0' or 'Qx' and merges non-convex facets. With option 'QJ',\n\
Qhull joggles the input to prevent precision problems. See \"Imprecision\n\
in Qhull\" (qh-impre.htm).\n\
\n\
If you use 'Q0', the output may include\n\
coplanar ridges, concave ridges, and flipped facets. In 4-d and higher,\n\
Qhull may produce a ridge with four neighbors or two facets with the same \n\
vertices. Qhull reports these events when they occur. It stops when a\n\
concave ridge, flipped facet, or duplicate facet occurs.\n");
#if REALfloat
fprintf (fp, "\
\n\
Qhull is currently using single precision arithmetic. The following\n\
will probably remove the precision problems:\n\
- recompile qhull for double precision (#define REALfloat 0 in user.h).\n");
#endif
if (qh DELAUNAY && !qh SCALElast && qh MAXabs_coord > 1e4)
fprintf( fp, "\
\n\
When computing the Delaunay triangulation of coordinates > 1.0,\n\
- use 'Qbb' to scale the last coordinate to [0,m] (max previous coordinate)\n");
if (qh DELAUNAY && !qh ATinfinity)
fprintf( fp, "\
When computing the Delaunay triangulation:\n\
- use 'Qz' to add a point at-infinity. This reduces precision problems.\n");
fprintf(fp, "\
\n\
If you need triangular output:\n\
- use option 'Qt' to triangulate the output\n\
- use option 'QJ' to joggle the input points and remove precision errors\n\
- use option 'Ft'. It triangulates non-simplicial facets with added points.\n\
\n\
If you must use 'Q0',\n\
try one or more of the following options. They can not guarantee an output.\n\
- use 'QbB' to scale the input to a cube.\n\
- use 'Po' to produce output and prevent partitioning for flipped facets\n\
- use 'V0' to set min. distance to visible facet as 0 instead of roundoff\n\
- use 'En' to specify a maximum roundoff error less than %2.2g.\n\
- options 'Qf', 'Qbb', and 'QR0' may also help\n",
qh DISTround);
fprintf(fp, "\
\n\
To guarantee simplicial output:\n\
- use option 'Qt' to triangulate the output\n\
- use option 'QJ' to joggle the input points and remove precision errors\n\
- use option 'Ft' to triangulate the output by adding points\n\
- use exact arithmetic (see \"Imprecision in Qhull\", qh-impre.htm)\n\
");
}
} /* printhelp_degenerate */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="printhelp_singular">-</a>
qh_printhelp_singular( fp )
prints descriptive message for singular input
*/
void qh_printhelp_singular(FILE *fp) {
facetT *facet;
vertexT *vertex, **vertexp;
realT min, max, *coord, dist;
int i,k;
fprintf(fp, "\n\
The input to qhull appears to be less than %d dimensional, or a\n\
computation has overflowed.\n\n\
Qhull could not construct a clearly convex simplex from points:\n",
qh hull_dim);
qh_printvertexlist (fp, "", qh facet_list, NULL, qh_ALL);
if (!qh_QUICKhelp)
fprintf(fp, "\n\
The center point is coplanar with a facet, or a vertex is coplanar\n\
with a neighboring facet. The maximum round off error for\n\
computing distances is %2.2g. The center point, facets and distances\n\
to the center point are as follows:\n\n", qh DISTround);
qh_printpointid (fp, "center point", qh hull_dim, qh interior_point, -1);
fprintf (fp, "\n");
FORALLfacets {
fprintf (fp, "facet");
FOREACHvertex_(facet->vertices)
fprintf (fp, " p%d", qh_pointid(vertex->point));
zinc_(Zdistio);
qh_distplane(qh interior_point, facet, &dist);
fprintf (fp, " distance= %4.2g\n", dist);
}
if (!qh_QUICKhelp) {
if (qh HALFspace)
fprintf (fp, "\n\
These points are the dual of the given halfspaces. They indicate that\n\
the intersection is degenerate.\n");
fprintf (fp,"\n\
These points either have a maximum or minimum x-coordinate, or\n\
they maximize the determinant for k coordinates. Trial points\n\
are first selected from points that maximize a coordinate.\n");
if (qh hull_dim >= qh_INITIALmax)
fprintf (fp, "\n\
Because of the high dimension, the min x-coordinate and max-coordinate\n\
points are used if the determinant is non-zero. Option 'Qs' will\n\
do a better, though much slower, job. Instead of 'Qs', you can change\n\
the points by randomly rotating the input with 'QR0'.\n");
}
fprintf (fp, "\nThe min and max coordinates for each dimension are:\n");
for (k=0; k < qh hull_dim; k++) {
min= REALmax;
max= -REALmin;
for (i=qh num_points, coord= qh first_point+k; i--; coord += qh hull_dim) {
maximize_(max, *coord);
minimize_(min, *coord);
}
fprintf (fp, " %d: %8.4g %8.4g difference= %4.4g\n", k, min, max, max-min);
}
if (!qh_QUICKhelp) {
fprintf (fp, "\n\
If the input should be full dimensional, you have several options that\n\
may determine an initial simplex:\n\
- use 'QJ' to joggle the input and make it full dimensional\n\
- use 'QbB' to scale the points to the unit cube\n\
- use 'QR0' to randomly rotate the input for different maximum points\n\
- use 'Qs' to search all points for the initial simplex\n\
- use 'En' to specify a maximum roundoff error less than %2.2g.\n\
- trace execution with 'T3' to see the determinant for each point.\n",
qh DISTround);
#if REALfloat
fprintf (fp, "\
- recompile qhull for double precision (#define REALfloat 0 in qhull.h).\n");
#endif
fprintf (fp, "\n\
If the input is lower dimensional:\n\
- use 'QJ' to joggle the input and make it full dimensional\n\
- use 'Qbk:0Bk:0' to delete coordinate k from the input. You should\n\
pick the coordinate with the least range. The hull will have the\n\
correct topology.\n\
- determine the flat containing the points, rotate the points\n\
into a coordinate plane, and delete the other coordinates.\n\
- add one or more points to make the input full dimensional.\n\
");
if (qh DELAUNAY && !qh ATinfinity)
fprintf (fp, "\n\n\
This is a Delaunay triangulation and the input is co-circular or co-spherical:\n\
- use 'Qz' to add a point \"at infinity\" (i.e., above the paraboloid)\n\
- or use 'QJ' to joggle the input and avoid co-circular data\n");
}
} /* printhelp_singular */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="printhyperplaneintersection">-</a>
qh_printhyperplaneintersection( fp, facet1, facet2, vertices, color )
print Geomview OFF or 4OFF for the intersection of two hyperplanes in 3-d or 4-d
*/
void qh_printhyperplaneintersection(FILE *fp, facetT *facet1, facetT *facet2,
setT *vertices, realT color[3]) {
realT costheta, denominator, dist1, dist2, s, t, mindenom, p[4];
vertexT *vertex, **vertexp;
int i, k;
boolT nearzero1, nearzero2;
costheta= qh_getangle(facet1->normal, facet2->normal);
denominator= 1 - costheta * costheta;
i= qh_setsize(vertices);
if (qh hull_dim == 3)
fprintf(fp, "VECT 1 %d 1 %d 1 ", i, i);
else if (qh hull_dim == 4 && qh DROPdim >= 0)
fprintf(fp, "OFF 3 1 1 ");
else
qh printoutvar++;
fprintf (fp, "# intersect f%d f%d\n", facet1->id, facet2->id);
mindenom= 1 / (10.0 * qh MAXabs_coord);
FOREACHvertex_(vertices) {
zadd_(Zdistio, 2);
qh_distplane(vertex->point, facet1, &dist1);
qh_distplane(vertex->point, facet2, &dist2);
s= qh_divzero (-dist1 + costheta * dist2, denominator,mindenom,&nearzero1);
t= qh_divzero (-dist2 + costheta * dist1, denominator,mindenom,&nearzero2);
if (nearzero1 || nearzero2)
s= t= 0.0;
for(k= qh hull_dim; k--; )
p[k]= vertex->point[k] + facet1->normal[k] * s + facet2->normal[k] * t;
if (qh PRINTdim <= 3) {
qh_projectdim3 (p, p);
fprintf(fp, "%8.4g %8.4g %8.4g # ", p[0], p[1], p[2]);
}else
fprintf(fp, "%8.4g %8.4g %8.4g %8.4g # ", p[0], p[1], p[2], p[3]);
if (nearzero1+nearzero2)
fprintf (fp, "p%d (coplanar facets)\n", qh_pointid (vertex->point));
else
fprintf (fp, "projected p%d\n", qh_pointid (vertex->point));
}
if (qh hull_dim == 3)
fprintf(fp, "%8.4g %8.4g %8.4g 1.0\n", color[0], color[1], color[2]);
else if (qh hull_dim == 4 && qh DROPdim >= 0)
fprintf(fp, "3 0 1 2 %8.4g %8.4g %8.4g 1.0\n", color[0], color[1], color[2]);
} /* printhyperplaneintersection */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="printline3geom">-</a>
qh_printline3geom( fp, pointA, pointB, color )
prints a line as a VECT
prints 0's for qh.DROPdim
notes:
if pointA == pointB,
it's a 1 point VECT
*/
void qh_printline3geom (FILE *fp, pointT *pointA, pointT *pointB, realT color[3]) {
int k;
realT pA[4], pB[4];
qh_projectdim3(pointA, pA);
qh_projectdim3(pointB, pB);
if ((fabs(pA[0] - pB[0]) > 1e-3) ||
(fabs(pA[1] - pB[1]) > 1e-3) ||
(fabs(pA[2] - pB[2]) > 1e-3)) {
fprintf (fp, "VECT 1 2 1 2 1\n");
for (k= 0; k < 3; k++)
fprintf (fp, "%8.4g ", pB[k]);
fprintf (fp, " # p%d\n", qh_pointid (pointB));
}else
fprintf (fp, "VECT 1 1 1 1 1\n");
for (k=0; k < 3; k++)
fprintf (fp, "%8.4g ", pA[k]);
fprintf (fp, " # p%d\n", qh_pointid (pointA));
fprintf (fp, "%8.4g %8.4g %8.4g 1\n", color[0], color[1], color[2]);
}
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="printneighborhood">-</a>
qh_printneighborhood( fp, format, facetA, facetB, printall )
print neighborhood of one or two facets
notes:
calls qh_findgood_all()
bumps qh.visit_id
*/
void qh_printneighborhood (FILE *fp, int format, facetT *facetA, facetT *facetB, boolT printall) {
facetT *neighbor, **neighborp, *facet;
setT *facets;
if (format == qh_PRINTnone)
return;
qh_findgood_all (qh facet_list);
if (facetA == facetB)
facetB= NULL;
facets= qh_settemp (2*(qh_setsize (facetA->neighbors)+1));
qh visit_id++;
for (facet= facetA; facet; facet= ((facet == facetA) ? facetB : NULL)) {
if (facet->visitid != qh visit_id) {
facet->visitid= qh visit_id;
qh_setappend (&facets, facet);
}
FOREACHneighbor_(facet) {
if (neighbor->visitid == qh visit_id)
continue;
neighbor->visitid= qh visit_id;
if (printall || !qh_skipfacet (neighbor))
qh_setappend (&facets, neighbor);
}
}
qh_printfacets (fp, format, NULL, facets, printall);
qh_settempfree (&facets);
} /* printneighborhood */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="printpoint">-</a>
qh_printpoint( fp, string, point )
qh_printpointid( fp, string, dim, point, id )
prints the coordinates of a point
returns:
if string is defined
prints 'string p%d' (skips p%d if id=-1)
notes:
nop if point is NULL
prints id unless it is undefined (-1)
*/
void qh_printpoint(FILE *fp, const char *string, pointT *point) {
int id= qh_pointid( point);
qh_printpointid( fp, string, qh hull_dim, point, id);
} /* printpoint */
void qh_printpointid(FILE *fp, const char *string, int dim, pointT *point, int id) {
int k;
realT r; /*bug fix*/
if (!point)
return;
if (string) {
fputs (string, fp);
if (id != -1)
fprintf(fp, " p%d: ", id);
}
for(k= dim; k--; ) {
r= *point++;
if (string)
fprintf(fp, " %8.4g", r);
else
fprintf(fp, qh_REAL_1, r);
}
fprintf(fp, "\n");
} /* printpointid */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="printpoint3">-</a>
qh_printpoint3( fp, point )
prints 2-d, 3-d, or 4-d point as Geomview 3-d coordinates
*/
void qh_printpoint3 (FILE *fp, pointT *point) {
int k;
realT p[4];
qh_projectdim3 (point, p);
for (k=0; k < 3; k++)
fprintf (fp, "%8.4g ", p[k]);
fprintf (fp, " # p%d\n", qh_pointid (point));
} /* printpoint3 */
/*----------------------------------------
-printpoints- print pointids for a set of points starting at index
see geom.c
*/
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="printpoints_out">-</a>
qh_printpoints_out( fp, facetlist, facets, printall )
prints vertices, coplanar/inside points, for facets by their point coordinates
allows qh.CDDoutput
notes:
same format as qhull input
if no coplanar/interior points,
same order as qh_printextremes
*/
void qh_printpoints_out (FILE *fp, facetT *facetlist, setT *facets, int printall) {
int allpoints= qh num_points + qh_setsize (qh other_points);
int numpoints=0, point_i, point_n;
setT *vertices, *points;
facetT *facet, **facetp;
pointT *point, **pointp;
vertexT *vertex, **vertexp;
int id;
points= qh_settemp (allpoints);
qh_setzero (points, 0, allpoints);
vertices= qh_facetvertices (facetlist, facets, printall);
FOREACHvertex_(vertices) {
id= qh_pointid (vertex->point);
if (id >= 0)
SETelem_(points, id)= vertex->point;
}
if (qh KEEPinside || qh KEEPcoplanar || qh KEEPnearinside) {
FORALLfacet_(facetlist) {
if (!printall && qh_skipfacet(facet))
continue;
FOREACHpoint_(facet->coplanarset) {
id= qh_pointid (point);
if (id >= 0)
SETelem_(points, id)= point;
}
}
FOREACHfacet_(facets) {
if (!printall && qh_skipfacet(facet))
continue;
FOREACHpoint_(facet->coplanarset) {
id= qh_pointid (point);
if (id >= 0)
SETelem_(points, id)= point;
}
}
}
qh_settempfree (&vertices);
FOREACHpoint_i_(points) {
if (point)
numpoints++;
}
if (qh CDDoutput)
fprintf (fp, "%s | %s\nbegin\n%d %d real\n", qh rbox_command,
qh qhull_command, numpoints, qh hull_dim + 1);
else
fprintf (fp, "%d\n%d\n", qh hull_dim, numpoints);
FOREACHpoint_i_(points) {
if (point) {
if (qh CDDoutput)
fprintf (fp, "1 ");
qh_printpoint (fp, NULL, point);
}
}
if (qh CDDoutput)
fprintf (fp, "end\n");
qh_settempfree (&points);
} /* printpoints_out */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="printpointvect">-</a>
qh_printpointvect( fp, point, normal, center, radius, color )
prints a 2-d, 3-d, or 4-d point as 3-d VECT's relative to normal or to center point
*/
void qh_printpointvect (FILE *fp, pointT *point, coordT *normal, pointT *center, realT radius, realT color[3]) {
realT diff[4], pointA[4];
int k;
for (k= qh hull_dim; k--; ) {
if (center)
diff[k]= point[k]-center[k];
else if (normal)
diff[k]= normal[k];
else
diff[k]= 0;
}
if (center)
qh_normalize2 (diff, qh hull_dim, True, NULL, NULL);
for (k= qh hull_dim; k--; )
pointA[k]= point[k]+diff[k] * radius;
qh_printline3geom (fp, point, pointA, color);
} /* printpointvect */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="printpointvect2">-</a>
qh_printpointvect2( fp, point, normal, center, radius )
prints a 2-d, 3-d, or 4-d point as 2 3-d VECT's for an imprecise point
*/
void qh_printpointvect2 (FILE *fp, pointT *point, coordT *normal, pointT *center, realT radius) {
realT red[3]={1, 0, 0}, yellow[3]={1, 1, 0};
qh_printpointvect (fp, point, normal, center, radius, red);
qh_printpointvect (fp, point, normal, center, -radius, yellow);
} /* printpointvect2 */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="printridge">-</a>
qh_printridge( fp, ridge )
prints the information in a ridge
notes:
for qh_printfacetridges()
*/
void qh_printridge(FILE *fp, ridgeT *ridge) {
fprintf(fp, " - r%d", ridge->id);
if (ridge->tested)
fprintf (fp, " tested");
if (ridge->nonconvex)
fprintf (fp, " nonconvex");
fprintf (fp, "\n");
qh_printvertices (fp, " vertices:", ridge->vertices);
if (ridge->top && ridge->bottom)
fprintf(fp, " between f%d and f%d\n",
ridge->top->id, ridge->bottom->id);
} /* printridge */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="printspheres">-</a>
qh_printspheres( fp, vertices, radius )
prints 3-d vertices as OFF spheres
notes:
inflated octahedron from Stuart Levy earth/mksphere2
*/
void qh_printspheres(FILE *fp, setT *vertices, realT radius) {
vertexT *vertex, **vertexp;
qh printoutnum++;
fprintf (fp, "{appearance {-edge -normal normscale 0} {\n\
INST geom {define vsphere OFF\n\
18 32 48\n\
\n\
0 0 1\n\
1 0 0\n\
0 1 0\n\
-1 0 0\n\
0 -1 0\n\
0 0 -1\n\
0.707107 0 0.707107\n\
0 -0.707107 0.707107\n\
0.707107 -0.707107 0\n\
-0.707107 0 0.707107\n\
-0.707107 -0.707107 0\n\
0 0.707107 0.707107\n\
-0.707107 0.707107 0\n\
0.707107 0.707107 0\n\
0.707107 0 -0.707107\n\
0 0.707107 -0.707107\n\
-0.707107 0 -0.707107\n\
0 -0.707107 -0.707107\n\
\n\
3 0 6 11\n\
3 0 7 6 \n\
3 0 9 7 \n\
3 0 11 9\n\
3 1 6 8 \n\
3 1 8 14\n\
3 1 13 6\n\
3 1 14 13\n\
3 2 11 13\n\
3 2 12 11\n\
3 2 13 15\n\
3 2 15 12\n\
3 3 9 12\n\
3 3 10 9\n\
3 3 12 16\n\
3 3 16 10\n\
3 4 7 10\n\
3 4 8 7\n\
3 4 10 17\n\
3 4 17 8\n\
3 5 14 17\n\
3 5 15 14\n\
3 5 16 15\n\
3 5 17 16\n\
3 6 13 11\n\
3 7 8 6\n\
3 9 10 7\n\
3 11 12 9\n\
3 14 8 17\n\
3 15 13 14\n\
3 16 12 15\n\
3 17 10 16\n} transforms { TLIST\n");
FOREACHvertex_(vertices) {
fprintf(fp, "%8.4g 0 0 0 # v%d\n 0 %8.4g 0 0\n0 0 %8.4g 0\n",
radius, vertex->id, radius, radius);
qh_printpoint3 (fp, vertex->point);
fprintf (fp, "1\n");
}
fprintf (fp, "}}}\n");
} /* printspheres */
/*----------------------------------------------
-printsummary-
see qhull.c
*/
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="printvdiagram">-</a>
qh_printvdiagram( fp, format, facetlist, facets, printall )
print voronoi diagram
# of pairs of input sites
#indices site1 site2 vertex1 ...
sites indexed by input point id
point 0 is the first input point
vertices indexed by 'o' and 'p' order
vertex 0 is the 'vertex-at-infinity'
vertex 1 is the first Voronoi vertex
see:
qh_printvoronoi()
qh_eachvoronoi_all()
notes:
if all facets are upperdelaunay,
prints upper hull (furthest-site Voronoi diagram)
*/
void qh_printvdiagram (FILE *fp, int format, facetT *facetlist, setT *facets, boolT printall) {
setT *vertices;
int totcount, numcenters;
boolT islower;
qh_RIDGE innerouter= qh_RIDGEall;
printvridgeT printvridge= NULL;
if (format == qh_PRINTvertices) {
innerouter= qh_RIDGEall;
printvridge= qh_printvridge;
}else if (format == qh_PRINTinner) {
innerouter= qh_RIDGEinner;
printvridge= qh_printvnorm;
}else if (format == qh_PRINTouter) {
innerouter= qh_RIDGEouter;
printvridge= qh_printvnorm;
}else {
fprintf(qh ferr, "qh_printvdiagram: unknown print format %d.\n", format);
qh_errexit (qh_ERRinput, NULL, NULL);
}
vertices= qh_markvoronoi (facetlist, facets, printall, &islower, &numcenters);
totcount= qh_printvdiagram2 (NULL, NULL, vertices, innerouter, False);
fprintf (fp, "%d\n", totcount);
totcount= qh_printvdiagram2 (fp, printvridge, vertices, innerouter, True /* inorder*/);
qh_settempfree (&vertices);
#if 0 /* for testing qh_eachvoronoi_all */
fprintf (fp, "\n");
totcount= qh_eachvoronoi_all(fp, printvridge, qh UPPERdelaunay, innerouter, True /* inorder*/);
fprintf (fp, "%d\n", totcount);
#endif
} /* printvdiagram */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="printvdiagram2">-</a>
qh_printvdiagram2( fp, printvridge, vertices, innerouter, inorder )
visit all pairs of input sites (vertices) for selected Voronoi vertices
vertices may include NULLs
innerouter:
qh_RIDGEall print inner ridges (bounded) and outer ridges (unbounded)
qh_RIDGEinner print only inner ridges
qh_RIDGEouter print only outer ridges
inorder:
print 3-d Voronoi vertices in order
assumes:
qh_markvoronoi marked facet->visitid for Voronoi vertices
all facet->seen= False
all facet->seen2= True
returns:
total number of Voronoi ridges
if printvridge,
calls printvridge( fp, vertex, vertexA, centers) for each ridge
[see qh_eachvoronoi()]
see:
qh_eachvoronoi_all()
*/
int qh_printvdiagram2 (FILE *fp, printvridgeT printvridge, setT *vertices, qh_RIDGE innerouter, boolT inorder) {
int totcount= 0;
int vertex_i, vertex_n;
vertexT *vertex;
FORALLvertices
vertex->seen= False;
FOREACHvertex_i_(vertices) {
if (vertex) {
if (qh GOODvertex > 0 && qh_pointid(vertex->point)+1 != qh GOODvertex)
continue;
totcount += qh_eachvoronoi (fp, printvridge, vertex, !qh_ALL, innerouter, inorder);
}
}
return totcount;
} /* printvdiagram2 */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="printvertex">-</a>
qh_printvertex( fp, vertex )
prints the information in a vertex
*/
void qh_printvertex(FILE *fp, vertexT *vertex) {
pointT *point;
int k, count= 0;
facetT *neighbor, **neighborp;
realT r; /*bug fix*/
if (!vertex) {
fprintf (fp, " NULLvertex\n");
return;
}
fprintf(fp, "- p%d (v%d):", qh_pointid(vertex->point), vertex->id);
point= vertex->point;
if (point) {
for(k= qh hull_dim; k--; ) {
r= *point++;
fprintf(fp, " %5.2g", r);
}
}
if (vertex->deleted)
fprintf(fp, " deleted");
if (vertex->delridge)
fprintf (fp, " ridgedeleted");
fprintf(fp, "\n");
if (vertex->neighbors) {
fprintf(fp, " neighbors:");
FOREACHneighbor_(vertex) {
if (++count % 100 == 0)
fprintf (fp, "\n ");
fprintf(fp, " f%d", neighbor->id);
}
fprintf(fp, "\n");
}
} /* printvertex */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="printvertexlist">-</a>
qh_printvertexlist( fp, string, facetlist, facets, printall )
prints vertices used by a facetlist or facet set
tests qh_skipfacet() if !printall
*/
void qh_printvertexlist (FILE *fp, const char* string, facetT *facetlist,
setT *facets, boolT printall) {
vertexT *vertex, **vertexp;
setT *vertices;
vertices= qh_facetvertices (facetlist, facets, printall);
fputs (string, fp);
FOREACHvertex_(vertices)
qh_printvertex(fp, vertex);
qh_settempfree (&vertices);
} /* printvertexlist */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="printvertices">-</a>
qh_printvertices( fp, string, vertices )
prints vertices in a set
*/
void qh_printvertices(FILE *fp, const char* string, setT *vertices) {
vertexT *vertex, **vertexp;
fputs (string, fp);
FOREACHvertex_(vertices)
fprintf (fp, " p%d (v%d)", qh_pointid(vertex->point), vertex->id);
fprintf(fp, "\n");
} /* printvertices */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="printvneighbors">-</a>
qh_printvneighbors( fp, facetlist, facets, printall )
print vertex neighbors of vertices in facetlist and facets ('FN')
notes:
qh_countfacets clears facet->visitid for non-printed facets
design:
collect facet count and related statistics
if necessary, build neighbor sets for each vertex
collect vertices in facetlist and facets
build a point array for point->vertex and point->coplanar facet
for each point
list vertex neighbors or coplanar facet
*/
void qh_printvneighbors (FILE *fp, facetT* facetlist, setT *facets, boolT printall) {
int numfacets, numsimplicial, numridges, totneighbors, numneighbors, numcoplanars, numtricoplanars;
setT *vertices, *vertex_points, *coplanar_points;
int numpoints= qh num_points + qh_setsize (qh other_points);
vertexT *vertex, **vertexp;
int vertex_i, vertex_n;
facetT *facet, **facetp, *neighbor, **neighborp;
pointT *point, **pointp;
qh_countfacets (facetlist, facets, printall, &numfacets, &numsimplicial,
&totneighbors, &numridges, &numcoplanars, &numtricoplanars); /* sets facet->visitid */
fprintf (fp, "%d\n", numpoints);
qh_vertexneighbors();
vertices= qh_facetvertices (facetlist, facets, printall);
vertex_points= qh_settemp (numpoints);
coplanar_points= qh_settemp (numpoints);
qh_setzero (vertex_points, 0, numpoints);
qh_setzero (coplanar_points, 0, numpoints);
FOREACHvertex_(vertices)
qh_point_add (vertex_points, vertex->point, vertex);
FORALLfacet_(facetlist) {
FOREACHpoint_(facet->coplanarset)
qh_point_add (coplanar_points, point, facet);
}
FOREACHfacet_(facets) {
FOREACHpoint_(facet->coplanarset)
qh_point_add (coplanar_points, point, facet);
}
FOREACHvertex_i_(vertex_points) {
if (vertex) {
numneighbors= qh_setsize (vertex->neighbors);
fprintf (fp, "%d", numneighbors);
if (qh hull_dim == 3)
qh_order_vertexneighbors (vertex);
else if (qh hull_dim >= 4)
qsort (SETaddr_(vertex->neighbors, facetT), numneighbors,
sizeof (facetT *), qh_compare_facetvisit);
FOREACHneighbor_(vertex)
fprintf (fp, " %d",
neighbor->visitid ? neighbor->visitid - 1 : - neighbor->id);
fprintf (fp, "\n");
}else if ((facet= SETelemt_(coplanar_points, vertex_i, facetT)))
fprintf (fp, "1 %d\n",
facet->visitid ? facet->visitid - 1 : - facet->id);
else
fprintf (fp, "0\n");
}
qh_settempfree (&coplanar_points);
qh_settempfree (&vertex_points);
qh_settempfree (&vertices);
} /* printvneighbors */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="printvoronoi">-</a>
qh_printvoronoi( fp, format, facetlist, facets, printall )
print voronoi diagram in 'o' or 'G' format
for 'o' format
prints voronoi centers for each facet and for infinity
for each vertex, lists ids of printed facets or infinity
assumes facetlist and facets are disjoint
for 'G' format
prints an OFF object
adds a 0 coordinate to center
prints infinity but does not list in vertices
see:
qh_printvdiagram()
notes:
if 'o',
prints a line for each point except "at-infinity"
if all facets are upperdelaunay,
reverses lower and upper hull
*/
void qh_printvoronoi (FILE *fp, int format, facetT *facetlist, setT *facets, boolT printall) {
int k, numcenters, numvertices= 0, numneighbors, numinf, vid=1, vertex_i, vertex_n;
facetT *facet, **facetp, *neighbor, **neighborp;
setT *vertices;
vertexT *vertex;
boolT islower;
unsigned int numfacets= (unsigned int) qh num_facets;
vertices= qh_markvoronoi (facetlist, facets, printall, &islower, &numcenters);
FOREACHvertex_i_(vertices) {
if (vertex) {
numvertices++;
numneighbors = numinf = 0;
FOREACHneighbor_(vertex) {
if (neighbor->visitid == 0)
numinf= 1;
else if (neighbor->visitid < numfacets)
numneighbors++;
}
if (numinf && !numneighbors) {
SETelem_(vertices, vertex_i)= NULL;
numvertices--;
}
}
}
if (format == qh_PRINTgeom)
fprintf (fp, "{appearance {+edge -face} OFF %d %d 1 # Voronoi centers and cells\n",
numcenters, numvertices);
else
fprintf (fp, "%d\n%d %d 1\n", qh hull_dim-1, numcenters, qh_setsize(vertices));
if (format == qh_PRINTgeom) {
for (k= qh hull_dim-1; k--; )
fprintf (fp, qh_REAL_1, 0.0);
fprintf (fp, " 0 # infinity not used\n");
}else {
for (k= qh hull_dim-1; k--; )
fprintf (fp, qh_REAL_1, qh_INFINITE);
fprintf (fp, "\n");
}
FORALLfacet_(facetlist) {
if (facet->visitid && facet->visitid < numfacets) {
if (format == qh_PRINTgeom)
fprintf (fp, "# %d f%d\n", vid++, facet->id);
qh_printcenter (fp, format, NULL, facet);
}
}
FOREACHfacet_(facets) {
if (facet->visitid && facet->visitid < numfacets) {
if (format == qh_PRINTgeom)
fprintf (fp, "# %d f%d\n", vid++, facet->id);
qh_printcenter (fp, format, NULL, facet);
}
}
FOREACHvertex_i_(vertices) {
numneighbors= 0;
numinf=0;
if (vertex) {
if (qh hull_dim == 3)
qh_order_vertexneighbors(vertex);
else if (qh hull_dim >= 4)
qsort (SETaddr_(vertex->neighbors, vertexT),
qh_setsize (vertex->neighbors),
sizeof (facetT *), qh_compare_facetvisit);
FOREACHneighbor_(vertex) {
if (neighbor->visitid == 0)
numinf= 1;
else if (neighbor->visitid < numfacets)
numneighbors++;
}
}
if (format == qh_PRINTgeom) {
if (vertex) {
fprintf (fp, "%d", numneighbors);
if (vertex) {
FOREACHneighbor_(vertex) {
if (neighbor->visitid && neighbor->visitid < numfacets)
fprintf (fp, " %d", neighbor->visitid);
}
}
fprintf (fp, " # p%d (v%d)\n", vertex_i, vertex->id);
}else
fprintf (fp, " # p%d is coplanar or isolated\n", vertex_i);
}else {
if (numinf)
numneighbors++;
fprintf (fp, "%d", numneighbors);
if (vertex) {
FOREACHneighbor_(vertex) {
if (neighbor->visitid == 0) {
if (numinf) {
numinf= 0;
fprintf (fp, " %d", neighbor->visitid);
}
}else if (neighbor->visitid < numfacets)
fprintf (fp, " %d", neighbor->visitid);
}
}
fprintf (fp, "\n");
}
}
if (format == qh_PRINTgeom)
fprintf (fp, "}\n");
qh_settempfree (&vertices);
} /* printvoronoi */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="printvnorm">-</a>
qh_printvnorm( fp, vertex, vertexA, centers, unbounded )
print one separating plane of the Voronoi diagram for a pair of input sites
unbounded==True if centers includes vertex-at-infinity
assumes:
qh_ASvoronoi and qh_vertexneighbors() already set
see:
qh_printvdiagram()
qh_eachvoronoi()
*/
void qh_printvnorm (FILE *fp, vertexT *vertex, vertexT *vertexA, setT *centers, boolT unbounded) {
pointT *normal;
realT offset;
int k;
normal= qh_detvnorm (vertex, vertexA, centers, &offset);
fprintf (fp, "%d %d %d ",
2+qh hull_dim, qh_pointid (vertex->point), qh_pointid (vertexA->point));
for (k= 0; k< qh hull_dim-1; k++)
fprintf (fp, qh_REAL_1, normal[k]);
fprintf (fp, qh_REAL_1, offset);
fprintf (fp, "\n");
} /* printvnorm */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="printvridge">-</a>
qh_printvridge( fp, vertex, vertexA, centers, unbounded )
print one ridge of the Voronoi diagram for a pair of input sites
unbounded==True if centers includes vertex-at-infinity
see:
qh_printvdiagram()
notes:
the user may use a different function
*/
void qh_printvridge (FILE *fp, vertexT *vertex, vertexT *vertexA, setT *centers, boolT unbounded) {
facetT *facet, **facetp;
fprintf (fp, "%d %d %d", qh_setsize (centers)+2,
qh_pointid (vertex->point), qh_pointid (vertexA->point));
FOREACHfacet_(centers)
fprintf (fp, " %d", facet->visitid);
fprintf (fp, "\n");
} /* printvridge */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="projectdim3">-</a>
qh_projectdim3( source, destination )
project 2-d 3-d or 4-d point to a 3-d point
uses qh.DROPdim and qh.hull_dim
source and destination may be the same
notes:
allocate 4 elements to destination just in case
*/
void qh_projectdim3 (pointT *source, pointT *destination) {
int i,k;
for (k= 0, i=0; k < qh hull_dim; k++) {
if (qh hull_dim == 4) {
if (k != qh DROPdim)
destination[i++]= source[k];
}else if (k == qh DROPdim)
destination[i++]= 0;
else
destination[i++]= source[k];
}
while (i < 3)
destination[i++]= 0.0;
} /* projectdim3 */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="readfeasible">-</a>
qh_readfeasible( dim, remainder )
read feasible point from remainder string and qh.fin
returns:
number of lines read from qh.fin
sets qh.FEASIBLEpoint with malloc'd coordinates
notes:
checks for qh.HALFspace
assumes dim > 1
see:
qh_setfeasible
*/
int qh_readfeasible (int dim, const char *remainder) {
boolT isfirst= True;
int linecount= 0, tokcount= 0;
const char *s; char *t, firstline[qh_MAXfirst + 1];
coordT *coords, value;
if (!qh HALFspace) {
fprintf (qh ferr, "qhull input error: feasible point (dim 1 coords) is only valid for halfspace intersection\n");
qh_errexit (qh_ERRinput, NULL, NULL);
}
if (qh feasible_string)
fprintf (qh ferr, "qhull input warning: feasible point (dim 1 coords) overrides 'Hn,n,n' feasible point for halfspace intersection\n");
if (!(qh feasible_point= (coordT*)malloc (dim* sizeof(coordT)))) {
fprintf(qh ferr, "qhull error: insufficient memory for feasible point\n");
qh_errexit(qh_ERRmem, NULL, NULL);
}
coords= qh feasible_point;
while ((s= (isfirst ? remainder : fgets(firstline, qh_MAXfirst, qh fin)))) {
if (isfirst)
isfirst= False;
else
linecount++;
while (*s) {
while (isspace(*s))
s++;
value= qh_strtod (s, &t);
if (s == t)
break;
s= t;
*(coords++)= value;
if (++tokcount == dim) {
while (isspace (*s))
s++;
qh_strtod (s, &t);
if (s != t) {
fprintf (qh ferr, "qhull input error: coordinates for feasible point do not finish out the line: %s\n",
s);
qh_errexit (qh_ERRinput, NULL, NULL);
}
return linecount;
}
}
}
fprintf (qh ferr, "qhull input error: only %d coordinates. Could not read %d-d feasible point.\n",
tokcount, dim);
qh_errexit (qh_ERRinput, NULL, NULL);
return 0;
} /* readfeasible */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="readpoints">-</a>
qh_readpoints( numpoints, dimension, ismalloc )
read points from qh.fin into qh.first_point, qh.num_points
qh.fin is lines of coordinates, one per vertex, first line number of points
if 'rbox D4',
gives message
if qh.ATinfinity,
adds point-at-infinity for Delaunay triangulations
returns:
number of points, array of point coordinates, dimension, ismalloc True
if qh.DELAUNAY & !qh.PROJECTinput, projects points to paraboloid
and clears qh.PROJECTdelaunay
if qh.HALFspace, reads optional feasible point, reads halfspaces,
converts to dual.
for feasible point in "cdd format" in 3-d:
3 1
coordinates
comments
begin
n 4 real/integer
...
end
notes:
dimension will change in qh_initqhull_globals if qh.PROJECTinput
uses malloc() since qh_mem not initialized
FIXUP: this routine needs rewriting
*/
coordT *qh_readpoints(int *numpoints, int *dimension, boolT *ismalloc) {
coordT *points, *coords, *infinity= NULL;
realT paraboloid, maxboloid= -REALmax, value;
realT *coordp= NULL, *offsetp= NULL, *normalp= NULL;
char *s, *t, firstline[qh_MAXfirst+1];
int diminput=0, numinput=0, dimfeasible= 0, newnum, k, tempi;
int firsttext=0, firstshort=0, firstlong=0, firstpoint=0;
int tokcount= 0, linecount=0, maxcount, coordcount=0;
boolT islong, isfirst= True, wasbegin= False;
boolT isdelaunay= qh DELAUNAY && !qh PROJECTinput;
if (qh CDDinput) {
while ((s= fgets(firstline, qh_MAXfirst, qh fin))) {
linecount++;
if (qh HALFspace && linecount == 1 && isdigit(*s)) {
dimfeasible= qh_strtol (s, &s);
while (isspace(*s))
s++;
if (qh_strtol (s, &s) == 1)
linecount += qh_readfeasible (dimfeasible, s);
else
dimfeasible= 0;
}else if (!memcmp (firstline, "begin", 5) || !memcmp (firstline, "BEGIN", 5))
break;
else if (!*qh rbox_command)
strncat(qh rbox_command, s, sizeof (qh rbox_command)-1);
}
if (!s) {
fprintf (qh ferr, "qhull input error: missing \"begin\" for cdd-formated input\n");
qh_errexit (qh_ERRinput, NULL, NULL);
}
}
while(!numinput && (s= fgets(firstline, qh_MAXfirst, qh fin))) {
linecount++;
if (!memcmp (s, "begin", 5) || !memcmp (s, "BEGIN", 5))
wasbegin= True;
while (*s) {
while (isspace(*s))
s++;
if (!*s)
break;
if (!isdigit(*s)) {
if (!*qh rbox_command) {
strncat(qh rbox_command, s, sizeof (qh rbox_command)-1);
firsttext= linecount;
}
break;
}
if (!diminput)
diminput= qh_strtol (s, &s);
else {
numinput= qh_strtol (s, &s);
if (numinput == 1 && diminput >= 2 && qh HALFspace && !qh CDDinput) {
linecount += qh_readfeasible (diminput, s); /* checks if ok */
dimfeasible= diminput;
diminput= numinput= 0;
}else
break;
}
}
}
if (!s) {
fprintf(qh ferr, "qhull input error: short input file. Did not find dimension and number of points\n");
qh_errexit(qh_ERRinput, NULL, NULL);
}
if (diminput > numinput) {
tempi= diminput; /* exchange dim and n, e.g., for cdd input format */
diminput= numinput;
numinput= tempi;
}
if (diminput < 2) {
fprintf(qh ferr,"qhull input error: dimension %d (first number) should be at least 2\n",
diminput);
qh_errexit(qh_ERRinput, NULL, NULL);
}
if (isdelaunay) {
qh PROJECTdelaunay= False;
if (qh CDDinput)
*dimension= diminput;
else
*dimension= diminput+1;
*numpoints= numinput;
if (qh ATinfinity)
(*numpoints)++;
}else if (qh HALFspace) {
*dimension= diminput - 1;
*numpoints= numinput;
if (diminput < 3) {
fprintf(qh ferr,"qhull input error: dimension %d (first number, includes offset) should be at least 3 for halfspaces\n",
diminput);
qh_errexit(qh_ERRinput, NULL, NULL);
}
if (dimfeasible) {
if (dimfeasible != *dimension) {
fprintf(qh ferr,"qhull input error: dimension %d of feasible point is not one less than dimension %d for halfspaces\n",
dimfeasible, diminput);
qh_errexit(qh_ERRinput, NULL, NULL);
}
}else
qh_setfeasible (*dimension);
}else {
if (qh CDDinput)
*dimension= diminput-1;
else
*dimension= diminput;
*numpoints= numinput;
}
qh normal_size= *dimension * sizeof(coordT); /* for tracing with qh_printpoint */
if (qh HALFspace) {
qh half_space= coordp= (coordT*) malloc (qh normal_size + sizeof(coordT));
if (qh CDDinput) {
offsetp= qh half_space;
normalp= offsetp + 1;
}else {
normalp= qh half_space;
offsetp= normalp + *dimension;
}
}
qh maxline= diminput * (qh_REALdigits + 5);
maximize_(qh maxline, 500);
qh line= (char*)malloc ((qh maxline+1) * sizeof (char));
*ismalloc= True; /* use malloc since memory not setup */
coords= points= qh temp_malloc=
(coordT*)malloc((*numpoints)*(*dimension)*sizeof(coordT));
if (!coords || !qh line || (qh HALFspace && !qh half_space)) {
fprintf(qh ferr, "qhull error: insufficient memory to read %d points\n",
numinput);
qh_errexit(qh_ERRmem, NULL, NULL);
}
if (isdelaunay && qh ATinfinity) {
infinity= points + numinput * (*dimension);
for (k= (*dimension) - 1; k--; )
infinity[k]= 0.0;
}
maxcount= numinput * diminput;
paraboloid= 0.0;
while ((s= (isfirst ? s : fgets(qh line, qh maxline, qh fin)))) {
if (!isfirst) {
linecount++;
if (*s == 'e' || *s == 'E') {
if (!memcmp (s, "end", 3) || !memcmp (s, "END", 3)) {
if (qh CDDinput )
break;
else if (wasbegin)
fprintf (qh ferr, "qhull input warning: the input appears to be in cdd format. If so, use 'Fd'\n");
}
}
}
islong= False;
while (*s) {
while (isspace(*s))
s++;
value= qh_strtod (s, &t);
if (s == t) {
if (!*qh rbox_command)
strncat(qh rbox_command, s, sizeof (qh rbox_command)-1);
if (*s && !firsttext)
firsttext= linecount;
if (!islong && !firstshort && coordcount)
firstshort= linecount;
break;
}
if (!firstpoint)
firstpoint= linecount;
s= t;
if (++tokcount > maxcount)
continue;
if (qh HALFspace) {
if (qh CDDinput)
*(coordp++)= -value; /* both coefficients and offset */
else
*(coordp++)= value;
}else {
*(coords++)= value;
if (qh CDDinput && !coordcount) {
if (value != 1.0) {
fprintf (qh ferr, "qhull input error: for cdd format, point at line %d does not start with '1'\n",
linecount);
qh_errexit (qh_ERRinput, NULL, NULL);
}
coords--;
}else if (isdelaunay) {
paraboloid += value * value;
if (qh ATinfinity) {
if (qh CDDinput)
infinity[coordcount-1] += value;
else
infinity[coordcount] += value;
}
}
}
if (++coordcount == diminput) {
coordcount= 0;
if (isdelaunay) {
*(coords++)= paraboloid;
maximize_(maxboloid, paraboloid);
paraboloid= 0.0;
}else if (qh HALFspace) {
if (!qh_sethalfspace (*dimension, coords, &coords, normalp, offsetp, qh feasible_point)) {
fprintf (qh ferr, "The halfspace was on line %d\n", linecount);
if (wasbegin)
fprintf (qh ferr, "The input appears to be in cdd format. If so, you should use option 'Fd'\n");
qh_errexit (qh_ERRinput, NULL, NULL);
}
coordp= qh half_space;
}
while (isspace(*s))
s++;
if (*s) {
islong= True;
if (!firstlong)
firstlong= linecount;
}
}
}
if (!islong && !firstshort && coordcount)
firstshort= linecount;
if (!isfirst && s - qh line >= qh maxline) {
fprintf(qh ferr, "qhull input error: line %d contained more than %d characters\n",
linecount, (int) (s - qh line));
qh_errexit(qh_ERRinput, NULL, NULL);
}
isfirst= False;
}
if (tokcount != maxcount) {
newnum= fmin_(numinput, tokcount/diminput);
fprintf(qh ferr,"\
qhull warning: instead of %d %d-dimensional points, input contains\n\
%d points and %d extra coordinates. Line %d is the first\npoint",
numinput, diminput, tokcount/diminput, tokcount % diminput, firstpoint);
if (firsttext)
fprintf(qh ferr, ", line %d is the first comment", firsttext);
if (firstshort)
fprintf(qh ferr, ", line %d is the first short\nline", firstshort);
if (firstlong)
fprintf(qh ferr, ", line %d is the first long line", firstlong);
fprintf(qh ferr, ". Continue with %d points.\n", newnum);
numinput= newnum;
if (isdelaunay && qh ATinfinity) {
for (k= tokcount % diminput; k--; )
infinity[k] -= *(--coords);
*numpoints= newnum+1;
}else {
coords -= tokcount % diminput;
*numpoints= newnum;
}
}
if (isdelaunay && qh ATinfinity) {
for (k= (*dimension) -1; k--; )
infinity[k] /= numinput;
if (coords == infinity)
coords += (*dimension) -1;
else {
for (k= 0; k < (*dimension) -1; k++)
*(coords++)= infinity[k];
}
*(coords++)= maxboloid * 1.1;
}
if (qh rbox_command[0]) {
qh rbox_command[strlen(qh rbox_command)-1]= '\0';
if (!strcmp (qh rbox_command, "./rbox D4"))
fprintf (qh ferr, "\n\
This is the qhull test case. If any errors or core dumps occur,\n\
recompile qhull with 'make new'. If errors still occur, there is\n\
an incompatibility. You should try a different compiler. You can also\n\
change the choices in user.h. If you discover the source of the problem,\n\
please send mail to qhull_bug@qhull.org.\n\
\n\
Type 'qhull' for a short list of options.\n");
}
free (qh line);
qh line= NULL;
if (qh half_space) {
free (qh half_space);
qh half_space= NULL;
}
qh temp_malloc= NULL;
trace1((qh ferr,"qh_readpoints: read in %d %d-dimensional points\n",
numinput, diminput));
return(points);
} /* readpoints */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="setfeasible">-</a>
qh_setfeasible( dim )
set qh.FEASIBLEpoint from qh.feasible_string in "n,n,n" or "n n n" format
notes:
"n,n,n" already checked by qh_initflags()
see qh_readfeasible()
*/
void qh_setfeasible (int dim) {
int tokcount= 0;
char *s;
coordT *coords, value;
if (!(s= qh feasible_string)) {
fprintf(qh ferr, "\
qhull input error: halfspace intersection needs a feasible point.\n\
Either prepend the input with 1 point or use 'Hn,n,n'. See manual.\n");
qh_errexit (qh_ERRinput, NULL, NULL);
}
if (!(qh feasible_point= (pointT*)malloc (dim* sizeof(coordT)))) {
fprintf(qh ferr, "qhull error: insufficient memory for 'Hn,n,n'\n");
qh_errexit(qh_ERRmem, NULL, NULL);
}
coords= qh feasible_point;
while (*s) {
value= qh_strtod (s, &s);
if (++tokcount > dim) {
fprintf (qh ferr, "qhull input warning: more coordinates for 'H%s' than dimension %d\n",
qh feasible_string, dim);
break;
}
*(coords++)= value;
if (*s)
s++;
}
while (++tokcount <= dim)
*(coords++)= 0.0;
} /* setfeasible */
/*-<a href="qh-io.htm#TOC"
>-------------------------------</a><a name="skipfacet">-</a>
qh_skipfacet( facet )
returns 'True' if this facet is not to be printed
notes:
based on the user provided slice thresholds and 'good' specifications
*/
boolT qh_skipfacet(facetT *facet) {
facetT *neighbor, **neighborp;
if (qh PRINTneighbors) {
if (facet->good)
return !qh PRINTgood;
FOREACHneighbor_(facet) {
if (neighbor->good)
return False;
}
return True;
}else if (qh PRINTgood)
return !facet->good;
else if (!facet->normal)
return True;
return (!qh_inthresholds (facet->normal, NULL));
} /* skipfacet */
| 32.446793 | 152 | 0.612874 | [
"geometry",
"object",
"transform"
] |
915baded945da8215880c8669123e78550cb4890 | 28,163 | cpp | C++ | src/libblockchain/documents.cpp | publiqnet/publiq.pp | 0865494edaa22ea2e3238aaf01cdb9e457535933 | [
"MIT"
] | 4 | 2019-11-20T17:27:57.000Z | 2021-01-05T09:46:20.000Z | src/libblockchain/documents.cpp | publiqnet/publiq.pp | 0865494edaa22ea2e3238aaf01cdb9e457535933 | [
"MIT"
] | null | null | null | src/libblockchain/documents.cpp | publiqnet/publiq.pp | 0865494edaa22ea2e3238aaf01cdb9e457535933 | [
"MIT"
] | 2 | 2019-01-10T14:10:26.000Z | 2020-03-01T05:55:05.000Z | #include "documents.hpp"
#include "common.hpp"
#include "exception.hpp"
#include "types.hpp"
#include "node_internals.hpp"
#include "message.tmpl.hpp"
#include <mesh.pp/fileutility.hpp>
#include <chrono>
#include <algorithm>
using namespace BlockchainMessage;
namespace filesystem = boost::filesystem;
using std::string;
using std::vector;
using std::pair;
using std::map;
using std::unordered_set;
namespace chrono = std::chrono;
using chrono::system_clock;
using time_point = system_clock::time_point;
namespace publiqpp
{
namespace detail
{
class documents_internals
{
public:
documents_internals(filesystem::path const& path_documents,
filesystem::path const& path_storages)
: m_files("file", path_documents, 10000, detail::get_putl())
, m_units("unit", path_documents, 10000, detail::get_putl())
, m_storages("storages", path_storages, 10000, get_putl_types())
, m_content_unit_sponsored_information("content_unit_info", path_documents, 10000, get_putl_types())
, m_sponsored_informations_expiring("sponsored_info_expiring", path_documents, 10000, get_putl_types())
, m_sponsored_informations_hash_to_block("sponsored_info_hash_to_block", path_documents, 10000, get_putl_types())
{}
meshpp::map_loader<File> m_files;
meshpp::map_loader<ContentUnit> m_units;
meshpp::map_loader<StorageTypes::FileUriHolders> m_storages;
meshpp::map_loader<StorageTypes::ContentUnitSponsoredInformation> m_content_unit_sponsored_information;
meshpp::map_loader<StorageTypes::SponsoredInformationHeaders> m_sponsored_informations_expiring;
meshpp::map_loader<StorageTypes::TransactionHashToBlockNumber> m_sponsored_informations_hash_to_block;
};
}
documents::documents(filesystem::path const& path_documents,
filesystem::path const& path_storages)
: m_pimpl(path_documents.empty() ? nullptr : new detail::documents_internals(path_documents, path_storages))
{}
documents::~documents() = default;
void documents::save()
{
if (nullptr == m_pimpl)
return;
m_pimpl->m_files.save();
m_pimpl->m_units.save();
m_pimpl->m_storages.save();
m_pimpl->m_content_unit_sponsored_information.save();
m_pimpl->m_sponsored_informations_expiring.save();
m_pimpl->m_sponsored_informations_hash_to_block.save();
}
void documents::commit() noexcept
{
if (nullptr == m_pimpl)
return;
m_pimpl->m_files.commit();
m_pimpl->m_units.commit();
m_pimpl->m_storages.commit();
m_pimpl->m_content_unit_sponsored_information.commit();
m_pimpl->m_sponsored_informations_expiring.commit();
m_pimpl->m_sponsored_informations_hash_to_block.commit();
}
void documents::discard() noexcept
{
if (nullptr == m_pimpl)
return;
m_pimpl->m_files.discard();
m_pimpl->m_units.discard();
m_pimpl->m_storages.discard();
m_pimpl->m_content_unit_sponsored_information.discard();
m_pimpl->m_sponsored_informations_expiring.discard();
m_pimpl->m_sponsored_informations_hash_to_block.discard();
}
void documents::clear()
{
if (nullptr == m_pimpl)
return;
m_pimpl->m_files.clear();
m_pimpl->m_units.clear();
m_pimpl->m_storages.clear();
m_pimpl->m_content_unit_sponsored_information.clear();
m_pimpl->m_sponsored_informations_expiring.clear();
m_pimpl->m_sponsored_informations_hash_to_block.clear();
}
pair<bool, string> documents::files_exist(unordered_set<string> const& uris) const
{
for (auto const& uri : uris)
{
if (false == file_exists(uri))
return std::make_pair(false, uri);
}
return std::make_pair(true, string());
}
bool documents::file_exists(string const& uri) const
{
if (uri.empty())
return false;
return m_pimpl->m_files.contains(uri);
}
bool documents::insert_file(File const& file)
{
if (m_pimpl->m_files.contains(file.uri))
return false;
m_pimpl->m_files.insert(file.uri, file);
return true;
}
void documents::remove_file(string const& uri)
{
m_pimpl->m_files.erase(uri);
}
BlockchainMessage::File const& documents::get_file(std::string const& uri) const
{
return m_pimpl->m_files.as_const().at(uri);
}
void documents::get_file_uris(vector<string>& file_uris) const
{
file_uris.clear();
for (auto it : m_pimpl->m_files.as_const().keys())
file_uris.push_back(it);
}
pair<bool, string> documents::units_exist(unordered_set<string> const& uris) const
{
for (auto const& uri : uris)
{
if (false == unit_exists(uri))
return std::make_pair(false, uri);
}
return std::make_pair(true, string());
}
bool documents::unit_exists(string const& uri) const
{
if (uri.empty())
return false;
return m_pimpl->m_units.contains(uri);
}
bool documents::insert_unit(ContentUnit const& unit)
{
if (m_pimpl->m_units.contains(unit.uri))
return false;
m_pimpl->m_units.insert(unit.uri, unit);
return true;
}
void documents::remove_unit(string const& uri)
{
m_pimpl->m_units.erase(uri);
}
BlockchainMessage::ContentUnit const& documents::get_unit(std::string const& uri) const
{
return m_pimpl->m_units.as_const().at(uri);
}
void documents::get_unit_uris(vector<string>& unit_uris) const
{
unit_uris.clear();
for (auto it : m_pimpl->m_units.as_const().keys())
unit_uris.push_back(it);
}
void documents::storage_update(std::string const& uri,
std::string const& address,
UpdateType status)
{
if (UpdateType::store == status)
{
if (false == m_pimpl->m_storages.contains(uri))
{
StorageTypes::FileUriHolders holders;
holders.addresses.insert(address);
m_pimpl->m_storages.insert(uri, holders);
}
else
{
StorageTypes::FileUriHolders& holders = m_pimpl->m_storages.at(uri);
holders.addresses.insert(address);
}
}
else
{
if (m_pimpl->m_storages.contains(uri))
{
StorageTypes::FileUriHolders& holders = m_pimpl->m_storages.at(uri);
holders.addresses.erase(address);
if (holders.addresses.empty())
m_pimpl->m_storages.erase(uri);
}
}
}
bool documents::storage_has_uri(std::string const& uri,
std::string const& address) const
{
if (false == m_pimpl->m_storages.contains(uri))
return false;
StorageTypes::FileUriHolders const& holders = m_pimpl->m_storages.as_const().at(uri);
return 0 != holders.addresses.count(address);
}
namespace
{
void refresh_index(StorageTypes::ContentUnitSponsoredInformation& cusi)
{
assert(false == cusi.time_points_used.empty());
system_clock::time_point tp = system_clock::from_time_t(cusi.time_points_used.back().tm);
vector<pair<size_t, system_clock::duration>> arr_index;
for (auto index : cusi.index_si)
{
if (cusi.sponsored_informations.size() <= index)
continue;
auto const& item = cusi.sponsored_informations[index];
auto item_start_tp = system_clock::from_time_t(item.start_time_point.tm);
auto item_end_tp = system_clock::from_time_t(item.end_time_point.tm);
assert(item.time_points_used_before <= cusi.time_points_used.size());
if (item.time_points_used_before > cusi.time_points_used.size())
throw std::logic_error("item.time_points_used_before > cusi.time_points_used.size()");
if (tp >= item_end_tp &&
cusi.time_points_used.size() > item.time_points_used_before)
continue;
system_clock::duration duration = chrono::seconds(0);
if (item_start_tp > tp)
duration = item_start_tp - tp;
arr_index.push_back(std::make_pair(index, duration));
}
std::sort(arr_index.begin(), arr_index.end(),
[](pair<size_t, system_clock::duration> const& lhs,
pair<size_t, system_clock::duration> const& rhs)
{
return lhs.second < rhs.second;
});
cusi.index_si.clear();
for (auto const& arr_index_item : arr_index)
cusi.index_si.push_back(arr_index_item.first);
}
size_t get_expiring_block_number(publiqpp::detail::node_internals const& impl,
chrono::system_clock::time_point const& item_end_tp)
{
// calculate the block index which will take care of expiration
auto genesis_tp =
system_clock::from_time_t(impl.m_blockchain.header_at(0).time_signed.tm);
size_t expiring_block_number = impl.m_blockchain.length();
if (item_end_tp > genesis_tp)
{
uint64_t seconds = chrono::duration_cast<chrono::seconds>(item_end_tp - genesis_tp).count();
size_t expected_block_number = seconds / BLOCK_MINE_DELAY;
if (0 != seconds % BLOCK_MINE_DELAY)
++expected_block_number;
if (expected_block_number > expiring_block_number)
expiring_block_number = expected_block_number;
}
return expiring_block_number;
}
}
void documents::sponsor_content_unit_apply(publiqpp::detail::node_internals& impl,
BlockchainMessage::SponsorContentUnit const& spi,
string const& transaction_hash)
{
StorageTypes::SponsoredInformation si;
si.amount = spi.amount;
auto item_start_tp = chrono::time_point_cast<chrono::seconds>
(system_clock::from_time_t(spi.start_time_point.tm));
auto item_end_tp = chrono::time_point_cast<chrono::seconds>
(item_start_tp + chrono::hours(spi.hours));
if (item_end_tp <= item_start_tp)
throw std::runtime_error("item_end_tp <= item_start_tp");
si.start_time_point.tm = system_clock::to_time_t(item_start_tp);
si.end_time_point.tm = system_clock::to_time_t(item_end_tp);
si.sponsor_address = spi.sponsor_address;
si.transaction_hash = transaction_hash;
si.cancelled = false;
if (m_pimpl->m_content_unit_sponsored_information.contains(spi.uri))
{
StorageTypes::ContentUnitSponsoredInformation& cusi =
m_pimpl->m_content_unit_sponsored_information.at(spi.uri);
assert(false == cusi.sponsored_informations.empty());
assert(false == cusi.time_points_used.empty());
if (cusi.sponsored_informations.empty())
throw std::logic_error("cusi.sponsored_informations.empty()");
if (cusi.time_points_used.empty())
throw std::logic_error("cusi.time_points_used.empty()");
si.time_points_used_before = cusi.time_points_used.size();
// the index will be sorted below inside refresh index
cusi.index_si.push_back(cusi.sponsored_informations.size());
cusi.sponsored_informations.push_back(si);
refresh_index(cusi);
}
else
{
StorageTypes::ContentUnitSponsoredInformation cusi;
cusi.uri = spi.uri;
cusi.time_points_used.push_back(si.start_time_point);
si.time_points_used_before = cusi.time_points_used.size(); // 1
// the index will be sorted below inside refresh index
cusi.index_si.push_back(cusi.sponsored_informations.size());
cusi.sponsored_informations.push_back(si);
refresh_index(cusi);
m_pimpl->m_content_unit_sponsored_information.insert(spi.uri, cusi);
}
size_t expiring_block_number = get_expiring_block_number(impl, item_end_tp);
StorageTypes::SponsoredInformationHeader expiring;
expiring.uri = spi.uri;
expiring.transaction_hash = si.transaction_hash;
expiring.block_number = expiring_block_number;
expiring.manually_cancelled = StorageTypes::Coin();
if (false == m_pimpl->m_sponsored_informations_expiring.contains(std::to_string(expiring_block_number)))
{
StorageTypes::SponsoredInformationHeaders expirings;
expirings.expirations[expiring.transaction_hash] = expiring;
m_pimpl->m_sponsored_informations_expiring.insert(std::to_string(expiring_block_number),
expirings);
}
else
{
StorageTypes::SponsoredInformationHeaders& expirings =
m_pimpl->m_sponsored_informations_expiring.at(std::to_string(expiring_block_number));
expirings.expirations[expiring.transaction_hash] = expiring;
}
StorageTypes::TransactionHashToBlockNumber hash_to_block;
hash_to_block.transaction_hash = si.transaction_hash;
hash_to_block.block_number = expiring_block_number;
m_pimpl->m_sponsored_informations_hash_to_block.insert(hash_to_block.transaction_hash,
hash_to_block);
}
void documents::sponsor_content_unit_revert(publiqpp::detail::node_internals& impl,
BlockchainMessage::SponsorContentUnit const& spi,
string const& transaction_hash)
{
StorageTypes::ContentUnitSponsoredInformation& cusi =
m_pimpl->m_content_unit_sponsored_information.at(spi.uri);
assert(false == cusi.sponsored_informations.empty());
assert(cusi.sponsored_informations.back().amount == StorageTypes::Coin(spi.amount));
assert(false == cusi.time_points_used.empty());
assert(cusi.time_points_used.size() == cusi.sponsored_informations.back().time_points_used_before);
if (cusi.sponsored_informations.empty() ||
cusi.sponsored_informations.back().amount != StorageTypes::Coin(spi.amount))
throw std::logic_error("cusi.sponsored_informations.back().amount != si");
if (cusi.time_points_used.empty())
throw std::logic_error("cusi.time_points_used.empty()");
if (cusi.time_points_used.size() != cusi.sponsored_informations.back().time_points_used_before)
throw std::logic_error("cusi.time_points_used.size() != cusi.sponsored_informations.back().time_points_used_before");
auto si = cusi.sponsored_informations.back();
assert(si.transaction_hash == transaction_hash);
if (si.transaction_hash != transaction_hash)
throw std::logic_error("si.transaction_hash != transaction_hash");
assert(si.cancelled != true);
if (si.cancelled == true)
throw std::logic_error("si.cancelled == true");
auto item_end_tp = system_clock::from_time_t(si.end_time_point.tm);
cusi.sponsored_informations.pop_back();
if (cusi.sponsored_informations.empty())
m_pimpl->m_content_unit_sponsored_information.erase(spi.uri);
else
refresh_index(cusi);
size_t expiring_block_number = get_expiring_block_number(impl, item_end_tp);
StorageTypes::SponsoredInformationHeaders& expirings =
expiration_entry_ref_by_block(expiring_block_number);
assert(expirings.expirations.count(si.transaction_hash));
if (0 == expirings.expirations.count(si.transaction_hash))
throw std::logic_error("0 == expirings.expirations.count(si.transaction_hash)");
auto const& expiration_item = expirings.expirations[si.transaction_hash];
assert(expiration_item.uri == spi.uri);
if (expiration_item.uri != spi.uri)
throw std::logic_error("expiration_item.uri != spi.uri");
assert(expiration_item.block_number == expiring_block_number);
if (expiration_item.block_number != expiring_block_number)
throw std::logic_error("expiration_item.block_number != expiring_block_number");
assert(expiration_item.transaction_hash == si.transaction_hash);
if (expiration_item.transaction_hash != si.transaction_hash)
throw std::logic_error("expiration_item.transaction_hash != si.transaction_hash");
assert(expiration_item.manually_cancelled == StorageTypes::Coin());
if (expiration_item.manually_cancelled != StorageTypes::Coin())
throw std::logic_error("expiration_item.manually_cancelled != StorageTypes::Coin()");
expirings.expirations.erase(si.transaction_hash);
if (expirings.expirations.empty())
m_pimpl->m_sponsored_informations_expiring.erase(std::to_string(expiring_block_number));
StorageTypes::TransactionHashToBlockNumber hash_to_block;
hash_to_block.transaction_hash = si.transaction_hash;
hash_to_block.block_number = expiring_block_number;
m_pimpl->m_sponsored_informations_hash_to_block.erase(hash_to_block.transaction_hash);
}
map<string, map<string, coin>> documents::sponsored_content_unit_set_used(publiqpp::detail::node_internals const& impl,
string const& content_unit_uri,
size_t block_number,
documents::e_sponsored_content_unit_set_used type,
string const& transaction_hash_to_cancel,
string const& manual_by_account,
bool pretend)
{
map<string, map<string, coin>> result;
if (transaction_hash_to_cancel.empty() ||
sponsored_content_unit_set_used_revert == type)
pretend = false;
bool manual = (false == manual_by_account.empty());
auto block_header = impl.m_blockchain.last_header();
time_point tp = system_clock::from_time_t(block_header.time_signed.tm);
if (block_number > block_header.block_number)
tp += chrono::seconds(BLOCK_MINE_DELAY * (block_number - block_header.block_number));
assert(block_number == block_header.block_number ||
block_number == block_header.block_number + 1);
if (block_number != block_header.block_number &&
block_number != block_header.block_number + 1)
throw std::logic_error("block_number range");
if (m_pimpl->m_content_unit_sponsored_information.contains(content_unit_uri))
{
StorageTypes::ContentUnitSponsoredInformation& cusi =
m_pimpl->m_content_unit_sponsored_information.at(content_unit_uri);
assert(false == cusi.sponsored_informations.empty());
assert(false == cusi.time_points_used.empty());
if (cusi.sponsored_informations.empty())
throw std::logic_error("cusi.sponsored_informations.empty()");
if (cusi.time_points_used.empty())
throw std::logic_error("cusi.time_points_used.empty()");
auto end_tp = tp;
end_tp = chrono::time_point_cast<chrono::seconds>(end_tp);
auto start_tp = system_clock::from_time_t(cusi.time_points_used.back().tm);
if ((sponsored_content_unit_set_used_apply == type && end_tp > start_tp) ||
(sponsored_content_unit_set_used_revert == type &&
(
(end_tp == start_tp && transaction_hash_to_cancel.empty()) ||
(end_tp > start_tp && false == transaction_hash_to_cancel.empty())
)
))
{
if (sponsored_content_unit_set_used_revert == type &&
transaction_hash_to_cancel.empty())
{
// pretend mode cannot enter this path
//
cusi.time_points_used.pop_back();
assert(false == cusi.time_points_used.empty());
if (cusi.time_points_used.empty())
throw std::logic_error("cusi.time_points_used.empty()");
start_tp = system_clock::from_time_t(cusi.time_points_used.back().tm);
// the index will be sorted below inside refresh index
cusi.index_si.clear();
for (size_t index = 0; index < cusi.sponsored_informations.size(); ++index)
cusi.index_si.push_back(index);
refresh_index(cusi);
}
for (auto const& index_si_item : cusi.index_si)
{
auto& item = cusi.sponsored_informations[index_si_item];
auto item_start_tp = system_clock::from_time_t(item.start_time_point.tm);
auto item_end_tp = system_clock::from_time_t(item.end_time_point.tm);
if (item_start_tp >= end_tp)
break;
if (transaction_hash_to_cancel.empty() &&
item.cancelled)
continue; // regardless if doing apply or revert
if (false == transaction_hash_to_cancel.empty() &&
item.transaction_hash != transaction_hash_to_cancel)
continue; // regardless if doing apply or revert - same
coin whole = item.amount;
auto whole_duration = item_end_tp - item_start_tp;
auto part_start_tp = std::max(start_tp, item_start_tp);
auto part_end_tp = std::min(end_tp, item_end_tp);
if (false == transaction_hash_to_cancel.empty())
part_end_tp = item_end_tp;
if (item.time_points_used_before == cusi.time_points_used.size())
part_start_tp = item_start_tp;
auto part_duration = part_end_tp - part_start_tp;
coin part = whole / uint64_t(chrono::duration_cast<chrono::seconds>(whole_duration).count())
* uint64_t(chrono::duration_cast<chrono::seconds>(part_duration).count());
if (part_end_tp == item_end_tp)
part += whole % uint64_t(chrono::duration_cast<chrono::seconds>(whole_duration).count());
if (part == coin())
continue;
auto& temp_result = result[item.sponsor_address];
auto insert_result = temp_result.insert({item.transaction_hash, part});
if (false == insert_result.second)
throw std::logic_error("temp_result.insert({item.transaction_hash, part})");
if (false == manual_by_account.empty())
{
if (item.sponsor_address != manual_by_account)
{
if (pretend)
{
result.clear();
return result;
}
throw authority_exception(manual_by_account,
item.sponsor_address);
}
}
if (false == transaction_hash_to_cancel.empty())
{
auto& expiration_entry = expiration_entry_ref_by_hash(item.transaction_hash);
if (sponsored_content_unit_set_used_apply == type)
{
if (item.cancelled)
{
if (pretend)
{
result.clear();
return result;
}
if (manual)
throw wrong_data_exception("already cancelled");
else
throw std::logic_error("already cancelled");
}
if (false == pretend)
item.cancelled = true;
assert(StorageTypes::Coin() == expiration_entry.manually_cancelled);
if (StorageTypes::Coin() != expiration_entry.manually_cancelled)
throw std::logic_error("StorageTypes::Coin() != expiration_entry.manually_cancelled");
if (manual && false == pretend)
part.to_Coin(expiration_entry.manually_cancelled);
}
if (sponsored_content_unit_set_used_revert == type)
{
// here logic errors are ok even for pretend
assert(item.cancelled);
if (false == item.cancelled)
throw std::logic_error("false == item.cancelled");
if (false == pretend)
item.cancelled = false;
assert(manual == (expiration_entry.manually_cancelled != StorageTypes::Coin()));
if (manual != (expiration_entry.manually_cancelled != StorageTypes::Coin()))
throw std::logic_error("manual != (expiration_entry.manually_cancelled != StorageTypes::Coin())");
if (manual && false == pretend)
expiration_entry.manually_cancelled = StorageTypes::Coin();
}
}
};
}
if (sponsored_content_unit_set_used_apply == type &&
transaction_hash_to_cancel.empty())
{
// pretend mode cannot enter this path
//
StorageTypes::ctime ct;
ct.tm = system_clock::to_time_t(end_tp);
cusi.time_points_used.push_back(ct);
refresh_index(cusi);
}
}
return result;
}
vector<pair<string, string>> documents::content_unit_uri_sponsor_expiring(size_t block_number) const
{
vector<pair<string, string>> result;
if (m_pimpl->m_sponsored_informations_expiring.contains(std::to_string(block_number)))
{
auto const& expirings =
m_pimpl->m_sponsored_informations_expiring.as_const().at(std::to_string(block_number));
for (auto const& expirations_item : expirings.expirations)
{
if (StorageTypes::Coin() == expirations_item.second.manually_cancelled)
{
result.push_back(std::make_pair(expirations_item.second.uri,
expirations_item.second.transaction_hash));
}
}
}
return result;
}
StorageTypes::SponsoredInformationHeaders&
documents::expiration_entry_ref_by_block(uint64_t block_number)
{
assert(m_pimpl->m_sponsored_informations_expiring.contains(std::to_string(block_number)));
if (false == m_pimpl->m_sponsored_informations_expiring.contains(std::to_string(block_number)))
throw std::logic_error("false == m_pimpl->m_sponsored_informations_expiring.contains(std::to_string(block_number))");
auto& expirings =
m_pimpl->m_sponsored_informations_expiring.at(std::to_string(block_number));
return expirings;
}
StorageTypes::SponsoredInformationHeader&
documents::expiration_entry_ref_by_block_by_hash(uint64_t block_number, std::string const& transaction_hash)
{
auto& expirings = expiration_entry_ref_by_block(block_number);
assert(expirings.expirations.count(transaction_hash));
if (0 == expirings.expirations.count(transaction_hash))
throw std::logic_error("0 == expirings.expirations.count(transaction_hash)");
auto& expiration_entry = expirings.expirations[transaction_hash];
return expiration_entry;
}
StorageTypes::SponsoredInformationHeader&
documents::expiration_entry_ref_by_hash(std::string const& transaction_hash)
{
assert(m_pimpl->m_sponsored_informations_hash_to_block.contains(transaction_hash));
if (false == m_pimpl->m_sponsored_informations_hash_to_block.contains(transaction_hash))
throw std::logic_error("false == m_pimpl->m_sponsored_informations_hash_to_block.contains(transaction_hash)");
auto const& hash_to_block = m_pimpl->m_sponsored_informations_hash_to_block.as_const().at(transaction_hash);
auto& expirings = expiration_entry_ref_by_block(hash_to_block.block_number);
assert(expirings.expirations.count(transaction_hash));
if (0 == expirings.expirations.count(transaction_hash))
throw std::logic_error("0 == expirings.expirations.count(transaction_hash)");
auto& expiration_entry = expirings.expirations[transaction_hash];
return expiration_entry;
}
}
| 37.904441 | 126 | 0.642119 | [
"mesh",
"vector"
] |
9163a205178cfe5068843ff04bd0a5996e989815 | 1,583 | cpp | C++ | test/HashSetTest.cpp | Tobias-Buerger/QLever | 6376b0e2022da702417e15bbc9701fedf35c31d0 | [
"Apache-2.0"
] | 6 | 2016-12-22T12:45:22.000Z | 2018-01-11T05:40:39.000Z | test/HashSetTest.cpp | Tobias-Buerger/QLever | 6376b0e2022da702417e15bbc9701fedf35c31d0 | [
"Apache-2.0"
] | 24 | 2017-01-03T00:01:37.000Z | 2018-03-05T09:03:11.000Z | test/HashSetTest.cpp | Tobias-Buerger/QLever | 6376b0e2022da702417e15bbc9701fedf35c31d0 | [
"Apache-2.0"
] | 5 | 2017-04-27T07:19:05.000Z | 2018-03-08T10:43:35.000Z | // Copyright 2015, University of Freiburg,
// Chair of Algorithms and Data Structures.
// Author: Niklas Schnelle (schnelle@informatik.uni-freiburg.de)
#include <gtest/gtest.h>
#include <utility>
#include <vector>
#include "../src/util/HashSet.h"
// Note: Since the HashSet class is a wrapper for a well tested hash set
// implementation the following tests only check the API for functionality and
// sanity
TEST(HashSetTest, sizeAndInsert) {
ad_utility::HashSet<int> set;
ASSERT_EQ(set.size(), 0u);
set.insert(42);
set.insert(41);
set.insert(12);
ASSERT_EQ(set.size(), 3u);
};
TEST(HashSetTest, insertRange) {
ad_utility::HashSet<int> set;
std::vector<int> values = {2, 3, 5, 7, 11};
set.insert(values.begin() + 1, values.end());
ASSERT_EQ(set.count(2), 0u);
ASSERT_EQ(set.count(4), 0u);
ASSERT_EQ(set.count(8), 0u);
ASSERT_EQ(set.count(3), 1u);
ASSERT_EQ(set.count(5), 1u);
ASSERT_EQ(set.count(7), 1u);
ASSERT_EQ(set.count(11), 1u);
};
TEST(HashSetTest, iterator) {
ad_utility::HashSet<int> set;
set.insert(41);
set.insert(12);
ASSERT_TRUE(++(++set.begin()) == set.end());
ad_utility::HashSet<int> settwo;
settwo.insert(set.begin(), set.end());
ASSERT_EQ(settwo.size(), 2u);
ASSERT_EQ(settwo.count(41), 1u);
ASSERT_EQ(settwo.count(12), 1u);
};
TEST(HashSetTest, erase) {
ad_utility::HashSet<int> set;
set.insert(41);
set.insert(12);
ASSERT_EQ(set.size(), 2u);
set.erase(41);
ASSERT_EQ(set.size(), 1u);
};
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 25.126984 | 78 | 0.675932 | [
"vector"
] |
91648ae5f207a3b8a1ea37c0d5866ce39b3ec003 | 5,039 | cpp | C++ | svc_kube_vision_opencvplus/extras/SiftThesaff/sifthesaff_extractor.cpp | lucmichalski/kube-vproxy | c7cc0edbcbcd07a48f0fc48b9457eae693b76688 | [
"Apache-2.0"
] | 3 | 2018-06-22T07:55:51.000Z | 2021-06-21T19:18:16.000Z | svc_kube_vision_opencvplus/extras/SiftThesaff/sifthesaff_extractor.cpp | lucmichalski/kube-vproxy | c7cc0edbcbcd07a48f0fc48b9457eae693b76688 | [
"Apache-2.0"
] | null | null | null | svc_kube_vision_opencvplus/extras/SiftThesaff/sifthesaff_extractor.cpp | lucmichalski/kube-vproxy | c7cc0edbcbcd07a48f0fc48b9457eae693b76688 | [
"Apache-2.0"
] | 1 | 2020-11-04T04:56:50.000Z | 2020-11-04T04:56:50.000Z | /*
* sifthesaff_extractor.cpp
*
* Created on: January 25, 2013
* Author: Siriwat Kasamwattanarote
*/
#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
#include <fstream>
#include <vector>
#include <bitset>
#include <unistd.h> // usleep
#include <sys/types.h> // for checking exist file and dir
#include <sys/stat.h>
// Siriwat's header
#include "../alphautils/alphautils.h"
#include "../alphautils/imtools.h"
#include "SIFThesaff.h"
#include "version_exe.h"
using namespace std;
using namespace alphautils;
using namespace alphautils::imtools;
int main(int argc,char *argv[])
{
cout << "SIFT extractor standalone version " << siftexe_AutoVersion::siftexe_FULLVERSION_STRING << endl;
cout << "SIFT extractor library version " << SIFThesaff::version() << endl;
cout << "Alpha Utilities library version " << alphautils::version() << endl;
if(argc < 2)
{
cout << "Params must be \"sifthesaff_extractor -i input_image [-o output_sift] [-d input_sift(display)] [-m output_mode:b|t] [-c colorspace:r(rgb)|i(irgb)|l(lab)] [-n normpoint:1|0] [-r rootsift:1|0] [-v:a|p, draw overlay in only binary mode]\"" << endl;
exit(1);
}
string input_image = "";
string output_sift = "";
string input_sift = "";
string output_overlay_image = "";
bool isBinary = false;
int colorspace = RGB_SPACE;
bool normpoint = true;
bool rootsift = true;
bool draw_mode = DRAW_AFFINE;
if(argc > 2)
{
for(int count = 1; count < argc; count+=2)
{
char opt;
if(argv[count][0] == '-')
opt = argv[count][1];
else
{
cout << "Incorrect parameter " << argv[count] << endl;
exit(1);
}
switch(opt)
{
case 'i':
input_image = string(argv[count + 1]);
break;
case 'o':
output_sift = string(argv[count + 1]);
break;
case 'd':
input_sift = string(argv[count + 1]);
break;
case 'm':
if(argv[count + 1][0] == 'b')
isBinary = true;
break;
case 'v':
if (isBinary)
{
output_overlay_image = input_image + "_overlay.png";
if (argv[count + 1][0] == 'a')
draw_mode = DRAW_AFFINE;
else if(argv[count + 1][0] == 'p')
draw_mode = DRAW_POINT;
else if (argv[count + 1][0] == 'c')
draw_mode = DRAW_CIRCLE;
}
break;
case 'c':
if (argv[count + 1][0] == 'i')
colorspace = IRGB_SPACE;
if (argv[count + 1][0] == 'l')
colorspace = LAB_SPACE;
break;
case 'n':
if(argv[count + 1][0] == '0')
normpoint = false;
break;
case 'r':
if(argv[count + 1][0] == '0')
rootsift = false;
break;
}
}
}
//input_image = "/dev/shm/test.jpg";
if (input_sift != "")
{
SIFThesaff sift_display;
sift_display.importKeypoints(input_sift, isBinary);
cout << sift_display.width << endl;
cout << sift_display.height << endl;
cout << SIFThesaff::GetSIFTD() << endl;
cout << sift_display.num_kp << endl;
for(int kp_idx = 0; kp_idx < sift_display.num_kp; kp_idx++)
{
cout << sift_display.kp[kp_idx][0] << " " << sift_display.kp[kp_idx][1] << " " << sift_display.kp[kp_idx][2] << " " << sift_display.kp[kp_idx][3] << " " << sift_display.kp[kp_idx][4] << " ";
for(size_t desc_pos = 0; desc_pos < SIFT_D; desc_pos++)
cout << sift_display.desc[kp_idx][desc_pos] << " ";
cout << endl;
}
return EXIT_SUCCESS;
}
if(input_image == "")
{
cout << "Params must be \"sifthesaff_extractor -i input_image [-o output_sift] [-m output_mode:b|t] [-c colorspace:r(rgb)|l(lab)] [-n normpoint:1|0] [-r rootsift:1|0] [-v:a|p, draw overlay in only binary mode]\"" << endl;
exit(1);
}
if(output_sift == "")
{
if (contain_path(input_image))
output_sift = input_image + ".hesaff.rootsift";
else
output_sift = "./" + input_image + ".hesaff.rootsift";
}
SIFThesaff sifthesaff(colorspace, normpoint, rootsift);
cout << "Extract sift..."; cout.flush();
timespec startTime = CurrentPreciseTime();
sifthesaff.extractPerdochSIFT(input_image);
cout << "done! (in " << setprecision(4) << fixed << TimeElapse(startTime) << " s)" << endl;
cout << "Exporting result ";
if(isBinary) cout << "[binary mode]...";
else cout << "[text mode]...";
cout.flush();
sifthesaff.exportKeypoints(output_sift, isBinary);
cout << "OK!" << endl;
if (output_overlay_image != "")
{
cout << "Drawing SIFT overlay...";
cout.flush();
sifthesaff.draw_sifts(input_image, output_overlay_image, output_sift, draw_mode);
cout << "done" << endl;
}
cout << "== SIFT feature information ==" << endl;
cout << "Total dimension: " << sifthesaff.GetSIFTD() << endl;
cout << "Total keypoint: " << sifthesaff.num_kp << endl;
return 0;
}
//;)
| 28.630682 | 256 | 0.572931 | [
"vector"
] |
916750ec9d9c83f21b4b8ff53eb51dd45f8ad6c5 | 58,637 | cpp | C++ | src/steamnetworkingsockets/clientlib/steamnetworkingsockets_udp.cpp | ArseniyShestakov/GameNetworkingSockets | e04a86de5408e0e9a3866876ddb3d3fc74bebd43 | [
"BSD-3-Clause"
] | 1 | 2022-03-16T06:34:47.000Z | 2022-03-16T06:34:47.000Z | src/steamnetworkingsockets/clientlib/steamnetworkingsockets_udp.cpp | ArseniyShestakov/GameNetworkingSockets | e04a86de5408e0e9a3866876ddb3d3fc74bebd43 | [
"BSD-3-Clause"
] | null | null | null | src/steamnetworkingsockets/clientlib/steamnetworkingsockets_udp.cpp | ArseniyShestakov/GameNetworkingSockets | e04a86de5408e0e9a3866876ddb3d3fc74bebd43 | [
"BSD-3-Clause"
] | 1 | 2021-03-04T11:36:26.000Z | 2021-03-04T11:36:26.000Z | //====== Copyright Valve Corporation, All rights reserved. ====================
#include "steamnetworkingsockets_udp.h"
#include "steamnetworkingconfig.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
const int k_cbSteamNetworkingMinPaddedPacketSize = 512;
// Put everything in a namespace, so we don't violate the one definition rule
namespace SteamNetworkingSocketsLib {
#pragma pack( push, 1 )
/// A protobuf-encoded message that is padded to ensure a minimum length
struct UDPPaddedMessageHdr
{
uint8 m_nMsgID;
uint16 m_nMsgLength;
};
struct UDPDataMsgHdr
{
enum
{
kFlag_ProtobufBlob = 0x01, // Protobuf-encoded message is inline (CMsgSteamSockets_UDP_Stats)
};
uint8 m_unMsgFlags;
uint32 m_unToConnectionID; // Recipient's portion of the connection ID
uint16 m_unSeqNum;
// [optional, if flags&kFlag_ProtobufBlob] varint-encoded protobuf blob size, followed by blob
// Data frame(s)
// End of packet
};
#pragma pack( pop )
//
// FIXME - legacy stuff. A very early version of the framing
// within the end-to-end data payload.
//
const uint8 k_nDataFrameFlags_Size_Mask = 0xc0;
const uint8 k_nDataFrameFlags_Size_RestOfPacket = 0x00;
//const uint8 k_nDataFrameFlags_Size_8bits = 0x40;
//const uint8 k_nDataFrameFlags_Size_8bitsAdd256 = 0x80;
//const uint8 k_nDataFrameFlags_Size_16bits = 0xc0;
const uint8 k_nDataFrameFlags_FrameType_Mask = 0x3c;
const uint8 k_nDataFrameFlags_FrameType_Unreliable = 0x00;
//const uint8 k_nDataFrameFlags_FrameType_Reliable = 0x10;
//const uint8 k_nDataFrameFlags_FrameType_ReliableAck = 0x20;
const uint8 k_nDataFrameFlags_Channel_Mask = 0x03;
const uint8 k_nDataFrameFlags_Channel_Same = 0x00;
const uint8 k_nDataFrameFlags_Channel_8bit = 0x02;
//const uint8 k_nDataFrameFlags_Channel_16bit = 0x03;
const int k_nMaxRecentLocalConnectionIDs = 256;
static CUtlVectorFixed<uint16,k_nMaxRecentLocalConnectionIDs> s_vecRecentLocalConnectionIDs;
/////////////////////////////////////////////////////////////////////////////
//
// Packet parsing / handling utils
//
/////////////////////////////////////////////////////////////////////////////
bool BCheckRateLimitReportBadPacket( SteamNetworkingMicroseconds usecNow )
{
static SteamNetworkingMicroseconds s_usecLastReport;
if ( s_usecLastReport + k_nMillion*2 > usecNow )
return false;
s_usecLastReport = usecNow;
return true;
}
void ReallyReportBadPacket( const netadr_t &adrFrom, const char *pszMsgType, const char *pszFmt, ... )
{
char buf[ 2048 ];
va_list ap;
va_start( ap, pszFmt );
V_vsprintf_safe( buf, pszFmt, ap );
va_end( ap );
V_StripTrailingWhitespaceASCII( buf );
if ( !pszMsgType || !pszMsgType[0] )
pszMsgType = "message";
SpewMsg( "Ignored bad %s from %s. %s\n", pszMsgType, CUtlNetAdrRender( adrFrom ).String(), buf );
}
#define ReportBadPacketFrom( adrFrom, pszMsgType, /* fmt */ ... ) \
( BCheckRateLimitReportBadPacket( usecNow ) ? ReallyReportBadPacket( adrFrom, pszMsgType, __VA_ARGS__ ) : (void)0 )
#define ReportBadPacket( pszMsgType, /* fmt */ ... ) \
ReportBadPacketFrom( adrFrom, pszMsgType, __VA_ARGS__ )
#define ParseProtobufBody( pvMsg, cbMsg, CMsgCls, msgVar ) \
CMsgCls msgVar; \
if ( !msgVar.ParseFromArray( pvMsg, cbMsg ) ) \
{ \
ReportBadPacket( # CMsgCls, "Protobuf parse failed." ); \
return; \
}
#define ParsePaddedPacket( pvPkt, cbPkt, CMsgCls, msgVar ) \
CMsgCls msgVar; \
{ \
if ( cbPkt < k_cbSteamNetworkingMinPaddedPacketSize ) \
{ \
ReportBadPacket( # CMsgCls, "Packet is %d bytes, must be padded to at least %d bytes.", cbPkt, k_cbSteamNetworkingMinPaddedPacketSize ); \
return; \
} \
const UDPPaddedMessageHdr *hdr = static_cast< const UDPPaddedMessageHdr * >( pvPkt ); \
int nMsgLength = LittleWord( hdr->m_nMsgLength ); \
if ( nMsgLength <= 0 || int(nMsgLength+sizeof(UDPPaddedMessageHdr)) > cbPkt ) \
{ \
ReportBadPacket( # CMsgCls, "Invalid encoded message length %d. Packet is %d bytes.", nMsgLength, cbPkt ); \
return; \
} \
if ( !msgVar.ParseFromArray( hdr+1, nMsgLength ) ) \
{ \
ReportBadPacket( # CMsgCls, "Protobuf parse failed." ); \
return; \
} \
}
/////////////////////////////////////////////////////////////////////////////
//
// CSteamNetworkListenSocketStandard - basic IPv4 packet handling
//
/////////////////////////////////////////////////////////////////////////////
void CSteamNetworkListenSocketStandard::ReceivedIPv4FromUnknownHost( const void *pvPkt, int cbPkt, const netadr_t &adrFrom, CSteamNetworkListenSocketStandard *pSock )
{
const uint8 *pPkt = static_cast<const uint8 *>( pvPkt );
SteamNetworkingMicroseconds usecNow = SteamNetworkingSockets_GetLocalTimestamp();
if ( cbPkt < 5 )
{
ReportBadPacket( "packet", "%d byte packet is too small", cbPkt );
return;
}
if ( *pPkt & 0x80 )
{
if ( *(uint32*)pPkt == 0xffffffff )
{
// Source engine connectionless packet (LAN discovery, etc).
// Just ignore it, and don't even spew.
}
else
{
// A stray data packet. Just ignore it.
//
// When clients are able to actually establish a connection, after that connection
// is over we will use the FinWait state to close down the connection gracefully.
// But since we don't have that connection in our table anymore, either this guy
// never had a connection, or else we believe he knows that the connection was closed,
// or the FinWait state has timed out.
ReportBadPacket( "Data", "Stray data packet from host with no connection. Ignoring." );
}
}
else if ( *pPkt == k_ESteamNetworkingUDPMsg_ChallengeRequest )
{
ParsePaddedPacket( pvPkt, cbPkt, CMsgSteamSockets_UDP_ChallengeRequest, msg )
pSock->ReceivedIPv4_ChallengeRequest( msg, adrFrom, usecNow );
}
else if ( *pPkt == k_ESteamNetworkingUDPMsg_ConnectRequest )
{
ParseProtobufBody( pPkt+1, cbPkt-1, CMsgSteamSockets_UDP_ConnectRequest, msg )
pSock->ReceivedIPv4_ConnectRequest( msg, adrFrom, cbPkt, usecNow );
}
else if ( *pPkt == k_ESteamNetworkingUDPMsg_ConnectionClosed )
{
ParsePaddedPacket( pvPkt, cbPkt, CMsgSteamSockets_UDP_ConnectionClosed, msg )
pSock->ReceivedIPv4_ConnectionClosed( msg, adrFrom, usecNow );
}
else if ( *pPkt == k_ESteamNetworkingUDPMsg_NoConnection )
{
// They don't think there's a connection on this address.
// We agree -- connection ID doesn't matter. Nothing else to do.
}
else if ( *pPkt == k_ESteamNetworkingUDPMsg_Stats )
{
ParseProtobufBody( pPkt+1, cbPkt-1, CMsgSteamSockets_UDP_Stats, msg )
pSock->ReceivedIPv4_Stats( msg, adrFrom, cbPkt, usecNow );
}
else
{
// Any other lead byte is bogus
//
// Note in particular that these packet types should be ignored:
//
// k_ESteamNetworkingUDPMsg_ChallengeReply
// k_ESteamNetworkingUDPMsg_ConnectOK
//
// We are not initiating connections, so we shouldn't ever get
// those sorts of replies.
ReportBadPacket( "packet", "Invalid lead byte 0x%02x", *pPkt );
}
}
uint64 CSteamNetworkListenSocketStandard::GenerateChallenge( uint16 nTime, uint32 nIP ) const
{
uint32 data[2] = { nTime, nIP };
uint64 nChallenge = siphash( (const uint8_t *)data, sizeof(data), m_argbChallengeSecret );
return ( nChallenge & 0xffffffffffff0000ull ) | nTime;
}
inline uint16 GetChallengeTime( SteamNetworkingMicroseconds usecNow )
{
return uint16( usecNow >> 20 );
}
void CSteamNetworkListenSocketStandard::ReceivedIPv4_ChallengeRequest( const CMsgSteamSockets_UDP_ChallengeRequest &msg, const netadr_t &adrFrom, SteamNetworkingMicroseconds usecNow )
{
if ( msg.connection_id() == 0 )
{
ReportBadPacket( "ChallengeRequest", "Missing connection_id." );
return;
}
//CSteamID steamIDClient( uint64( msg.client_steam_id() ) );
//if ( !steamIDClient.IsValid() )
//{
// ReportBadPacket( "ChallengeRequest", "Missing/invalid SteamID.", cbPkt );
// return;
//}
// Get time value of challenge
uint16 nTime = GetChallengeTime( usecNow );
// Generate a challenge
uint64 nChallenge = GenerateChallenge( nTime, adrFrom.GetIP() );
// Send them a reply
CMsgSteamSockets_UDP_ChallengeReply msgReply;
msgReply.set_connection_id( msg.connection_id() );
msgReply.set_challenge( nChallenge );
msgReply.set_your_timestamp( msg.my_timestamp() );
msgReply.set_protocol_version( k_nCurrentProtocolVersion );
SendMsgIPv4( k_ESteamNetworkingUDPMsg_ChallengeReply, msgReply, adrFrom );
}
void CSteamNetworkListenSocketStandard::ReceivedIPv4_ConnectRequest( const CMsgSteamSockets_UDP_ConnectRequest &msg, const netadr_t &adrFrom, int cbPkt, SteamNetworkingMicroseconds usecNow )
{
// Make sure challenge was generated relatively recently
uint16 nTimeThen = uint32( msg.challenge() );
uint16 nElapsed = GetChallengeTime( usecNow ) - nTimeThen;
if ( nElapsed > GetChallengeTime( 4*k_nMillion ) )
{
ReportBadPacket( "ConnectRequest", "Challenge too old." );
return;
}
// Assuming we sent them this time value, re-create the challenge we would have sent them.
if ( GenerateChallenge( nTimeThen, adrFrom.GetIP() ) != msg.challenge() )
{
ReportBadPacket( "ConnectRequest", "Incorrect challenge. Could be spoofed." );
return;
}
// Check that the Steam ID is valid. We'll authenticate this using their cert later
CSteamID steamID( uint64( msg.client_steam_id() ) );
if ( !steamID.IsValid() && steamdatagram_ip_allow_connections_without_auth == 0 )
{
ReportBadPacket( "ConnectRequest", "Invalid SteamID %llu.", steamID.ConvertToUint64() );
return;
}
uint32 unClientConnectionID = msg.client_connection_id();
if ( unClientConnectionID == 0 )
{
ReportBadPacket( "ConnectRequest", "Missing connection ID" );
return;
}
// Does this connection already exist? (At a different address?)
int h = m_mapChildConnections.Find( ChildConnectionKey_t( steamID, unClientConnectionID ) );
if ( h != m_mapChildConnections.InvalidIndex() )
{
CSteamNetworkConnectionBase *pOldConn = m_mapChildConnections[ h ];
Assert( pOldConn->m_steamIDRemote == steamID );
Assert( pOldConn->GetRemoteAddr() != adrFrom ); // or else why didn't we already map it directly to them!
// NOTE: We cannot just destroy the object. The API semantics
// are that all connections, once accepted and made visible
// to the API, must be closed by the application.
ReportBadPacket( "ConnectRequest", "Rejecting connection request from %s at %s, connection ID %u. That steamID/ConnectionID pair already has a connection from %s\n",
steamID.Render(), CUtlNetAdrRender( adrFrom ).String(), unClientConnectionID, CUtlNetAdrRender( pOldConn->GetRemoteAddr() ).String()
);
CMsgSteamSockets_UDP_ConnectionClosed msgReply;
msgReply.set_to_connection_id( unClientConnectionID );
msgReply.set_reason_code( k_ESteamNetConnectionEnd_Misc_Generic );
msgReply.set_debug( "A connection with that ID already exists." );
SendPaddedMsgIPv4( k_ESteamNetworkingUDPMsg_ConnectionClosed, msgReply, adrFrom );
}
CSteamNetworkConnectionIPv4 *pConn = new CSteamNetworkConnectionIPv4( m_pSteamNetworkingSocketsInterface );
// OK, they have completed the handshake. Accept the connection.
uint32 nPeerProtocolVersion = msg.has_protocol_version() ? msg.protocol_version() : 1;
SteamDatagramErrMsg errMsg;
if ( !pConn->BBeginAccept( this, adrFrom, m_pSockIPV4Connections, steamID, unClientConnectionID, nPeerProtocolVersion, msg.cert(), msg.crypt(), errMsg ) )
{
SpewWarning( "Failed to accept connection from %s. %s\n", CUtlNetAdrRender( adrFrom ).String(), errMsg );
pConn->Destroy();
return;
}
pConn->m_statsEndToEnd.TrackRecvPacket( cbPkt, usecNow );
// Did they send us a ping estimate?
if ( msg.has_ping_est_ms() )
pConn->m_statsEndToEnd.m_ping.ReceivedPing( msg.ping_est_ms(), usecNow );
// Save of timestamp that we will use to reply to them when the application
// decides to accept the connection
if ( msg.has_my_timestamp() )
{
pConn->m_ulHandshakeRemoteTimestamp = msg.my_timestamp();
pConn->m_usecWhenReceivedHandshakeRemoteTimestamp = usecNow;
}
}
void CSteamNetworkListenSocketStandard::ReceivedIPv4_ConnectionClosed( const CMsgSteamSockets_UDP_ConnectionClosed &msg, const netadr_t &adrFrom, SteamNetworkingMicroseconds usecNow )
{
// Send an ack. Note that we require the inbound message to be padded
// to a minimum size, and this reply is tiny, so we are not at a risk of
// being used for reflection, even though the source address could be spoofed.
CMsgSteamSockets_UDP_NoConnection msgReply;
if ( msg.from_connection_id() )
msgReply.set_to_connection_id( msg.from_connection_id() );
if ( msg.to_connection_id() )
msgReply.set_from_connection_id( msg.to_connection_id() );
SendMsgIPv4( k_ESteamNetworkingUDPMsg_NoConnection, msgReply, adrFrom );
}
void CSteamNetworkListenSocketStandard::ReceivedIPv4_Stats( const CMsgSteamSockets_UDP_Stats &msg, const netadr_t &adrFrom, int cbPkt, SteamNetworkingMicroseconds usecNow )
{
// Malformed?
if ( msg.to_connection_id() == 0 )
return;
// If their incoming message is a reasonable size, then there's no risk
// of us being used for reflection attack, because the NoConnection
// reply is tiny
if ( cbPkt < 64 && !BCheckRateLimitReportBadPacket( usecNow ) )
return; // Just drop it
// No connection!
CMsgSteamSockets_UDP_NoConnection msgReply;
if ( msg.from_connection_id() )
msgReply.set_to_connection_id( msg.from_connection_id() );
if ( msg.to_connection_id() )
msgReply.set_from_connection_id( msg.to_connection_id() );
SendMsgIPv4( k_ESteamNetworkingUDPMsg_NoConnection, msgReply, adrFrom );
}
void CSteamNetworkListenSocketStandard::SendMsgIPv4( uint8 nMsgID, const google::protobuf::MessageLite &msg, const netadr_t &adrTo )
{
if ( !m_pSockIPV4Connections )
{
Assert( false );
return;
}
uint8 pkt[ k_cbSteamNetworkingSocketsMaxUDPMsgLen ];
pkt[0] = nMsgID;
int cbPkt = msg.ByteSize()+1;
if ( cbPkt > sizeof(pkt) )
{
AssertMsg3( false, "Msg type %d is %d bytes, larger than MTU of %d bytes", int( nMsgID ), cbPkt, (int)sizeof(pkt) );
return;
}
uint8 *pEnd = msg.SerializeWithCachedSizesToArray( pkt+1 );
Assert( cbPkt == pEnd - pkt );
// Send the reply
m_pSockIPV4Connections->BSendRawPacket( pkt, cbPkt, adrTo );
}
void CSteamNetworkListenSocketStandard::SendPaddedMsgIPv4( uint8 nMsgID, const google::protobuf::MessageLite &msg, const netadr_t adrTo )
{
uint8 pkt[ k_cbSteamNetworkingSocketsMaxUDPMsgLen ];
memset( pkt, 0, sizeof(pkt) ); // don't send random bits from our process memory over the wire!
UDPPaddedMessageHdr *hdr = (UDPPaddedMessageHdr *)pkt;
int nMsgLength = msg.ByteSize();
hdr->m_nMsgID = nMsgID;
hdr->m_nMsgLength = LittleWord( uint16( nMsgLength ) );
uint8 *pEnd = msg.SerializeWithCachedSizesToArray( pkt + sizeof(*hdr) );
int cbPkt = pEnd - pkt;
Assert( cbPkt == int( sizeof(*hdr) + nMsgLength ) );
cbPkt = MAX( cbPkt, k_cbSteamNetworkingMinPaddedPacketSize );
m_pSockIPV4Connections->BSendRawPacket( pkt, cbPkt, adrTo );
}
/////////////////////////////////////////////////////////////////////////////
//
// IP connections
//
/////////////////////////////////////////////////////////////////////////////
CSteamNetworkConnectionIPv4::CSteamNetworkConnectionIPv4( CSteamNetworkingSockets *pSteamNetworkingSocketsInterface )
: CSteamNetworkConnectionBase( pSteamNetworkingSocketsInterface )
{
m_pSocket = nullptr;
}
CSteamNetworkConnectionIPv4::~CSteamNetworkConnectionIPv4()
{
AssertMsg( !m_pSocket, "Connection not destroyed properly" );
}
void CSteamNetworkConnectionIPv4::FreeResources()
{
if ( m_pSocket )
{
m_pSocket->Close();
m_pSocket = nullptr;
}
// Base class cleanup
CSteamNetworkConnectionBase::FreeResources();
}
int CSteamNetworkConnectionIPv4::SendDataChunk( const void *pChunk, int cbChunk, SteamNetworkingMicroseconds usecNow, uint16 *pOutSeqNum )
{
if ( !m_pSocket )
{
Assert( false );
return 0;
}
uint8 pkt[ k_cbSteamNetworkingSocketsMaxUDPMsgLen ];
UDPDataMsgHdr *hdr = (UDPDataMsgHdr *)pkt;
hdr->m_unMsgFlags = 0x80;
Assert( m_unConnectionIDRemote != 0 );
hdr->m_unToConnectionID = LittleDWord( m_unConnectionIDRemote );
hdr->m_unSeqNum = LittleWord( m_statsEndToEnd.GetNextSendSequenceNumber( usecNow ) );
byte *p = (byte*)( hdr + 1 );
// Check how much bigger we could grow the header
// and still fit in a packet
int cbHdrOutSpaceRemaining = pkt + sizeof(pkt) - p - cbChunk;
if ( cbHdrOutSpaceRemaining < 0 )
{
AssertMsg( false, "MTU / header size problem!" );
return 0;
}
// FIXME Check for putting acks in the header of the packet, instead of protobuf
// Do we need to send tracer ping request or connection stats?
// Make sure we aren't totally full already. (Is this even possible to fail right now?)
if ( cbHdrOutSpaceRemaining >= 4 )
{
// What sorts of ack should we request?
uint32 nFlags = 0;
if ( m_statsEndToEnd.BNeedToSendPingImmediate( usecNow ) )
{
// Connection problem. Ping aggressively until we figure it out
nFlags = CMsgSteamSockets_UDP_Stats::ACK_REQUEST_E2E | CMsgSteamSockets_UDP_Stats::ACK_REQUEST_IMMEDIATE;
}
else if ( m_statsEndToEnd.BReadyToSendTracerPing( usecNow ) || m_statsEndToEnd.BNeedToSendKeepalive( usecNow ) )
nFlags |= CMsgSteamSockets_UDP_Stats::ACK_REQUEST_E2E;
// Check if we should send connection stats inline.
bool bTrySendEndToEndStats = m_statsEndToEnd.BReadyToSendStats( usecNow );
// Do we actually want to send anything in the protobuf blob at all?
// The goal is that we should only do this every couple of seconds or so.
if ( bTrySendEndToEndStats || nFlags != 0 || m_statsEndToEnd.m_nPendingOutgoingAcks > 0 )
{
// Populate a message with everything we'd like to send
CMsgSteamSockets_UDP_Stats msgStatsOut;
if ( bTrySendEndToEndStats )
m_statsEndToEnd.PopulateMessage( *msgStatsOut.mutable_stats(), usecNow );
// Acks
// FIXME - Eventually we'd like to put a single ack in the header, since these will
// be reasonably common
PutEndToEndAcksIntoMessage( msgStatsOut, m_statsEndToEnd, usecNow );
// We'll try to fit what we can. If we try to serialize a message
// and it won't fit, we'll remove some stuff and see if that fits.
int cbStatsMsg, cbHdrSpaceNeeded;
for (;;)
{
// Slam flags based on what we are actually going to send. Don't send flags
// if they are implied by the stats we are sending.
uint32 nImpliedFlags = 0;
if ( msgStatsOut.has_stats() ) nImpliedFlags |= msgStatsOut.ACK_REQUEST_E2E;
if ( nFlags != nImpliedFlags )
msgStatsOut.set_flags( nFlags );
else
msgStatsOut.clear_flags();
// Cache size, check how big it would be
cbStatsMsg = msgStatsOut.ByteSize();
// Include varint-encoded message size.
// Note that if the size requires 3 bytes varint encoded, it won't fit in
// a packet anyway, so we don't need to handle that case. But it is totally
// possible that we might want to send more than 128 bytes of stats, and have
// an opportunity to send it all in the same packet.
cbHdrSpaceNeeded = cbStatsMsg + 1;
if ( cbStatsMsg >= 0x80 )
++cbHdrSpaceNeeded;
// Will it fit inline with this data packet?
if ( cbHdrSpaceNeeded <= cbHdrOutSpaceRemaining )
break;
// Rats. We want to send some stuff, but it won't fit.
// Strip off stuff, in no particular order.
if ( msgStatsOut.has_stats() )
{
Assert( bTrySendEndToEndStats );
if ( msgStatsOut.stats().has_instantaneous() && msgStatsOut.stats().has_lifetime() )
{
// Trying to send both - clear instantaneous
msgStatsOut.mutable_stats()->clear_instantaneous();
}
else
{
// Trying to send just one or the other. Clear the whole container.
msgStatsOut.clear_stats();
bTrySendEndToEndStats = false;
}
continue;
}
Assert( !bTrySendEndToEndStats );
// FIXME - we could try to send without acks.
// Nothing left to clear!? We shouldn't get here!
AssertMsg( false, "Serialized stats message still won't fit, ever after clearing everything?" );
cbStatsMsg = -1;
break;
}
// Did we actually end up sending anything?
if ( cbStatsMsg > 0 )
{
// Serialize the stats size, var-int encoded
byte *pStatsOut = SerializeVarInt( (byte*)p, uint32( cbStatsMsg ) );
// Serialize the actual message
pStatsOut = msgStatsOut.SerializeWithCachedSizesToArray( pStatsOut );
// Make sure we wrote the number of bytes we expected
if ( pStatsOut != p + cbHdrSpaceNeeded )
{
// ABORT!
AssertMsg( false, "Size mismatch after serializing connection quality stats" );
}
else
{
// Update bookkeeping with the stuff we are actually sending
TrackSentStats( msgStatsOut, true, usecNow );
// Mark header with the flag
hdr->m_unMsgFlags |= hdr->kFlag_ProtobufBlob;
// Advance pointer
p = pStatsOut;
}
}
}
}
// !FIXME! Time since previous, for jitter measurement?
// Use gather-based send. This saves one memcpy of every payload
iovec gather[2];
gather[0].iov_base = pkt;
gather[0].iov_len = p - pkt;
gather[1].iov_base = const_cast<void*>( pChunk );
gather[1].iov_len = cbChunk;
int cbSend = gather[0].iov_len + gather[1].iov_len;
Assert( cbSend <= sizeof(pkt) ); // Bug in the code above. We should never "overflow" the packet. (Ignoring the fact that we using a gather-based send. The data could be tiny with a large header for piggy-backed stats.)
// !FIXME! Should we track data payload separately? Maybe we ought to track
// *messages* instead of packets.
// Return sequence number to caller, if requested
if ( pOutSeqNum )
*pOutSeqNum = hdr->m_unSeqNum;
// Send it
SendPacketGather( 2, gather, cbSend );
return cbSend;
}
bool CSteamNetworkConnectionIPv4::BInitConnect( const netadr_t &netadrRemote, SteamDatagramErrMsg &errMsg )
{
AssertMsg( !m_pSocket, "Trying to connect when we already have a socket?" );
// We're initiating a connection, not being accepted on a listen socket
Assert( !m_pParentListenSocket );
// For now we're just assuming each connection will gets its own socket,
// on an ephemeral port. Later we could add a setting to enable
// sharing of the socket.
m_pSocket = OpenUDPSocketBoundToHost( 0, 0, netadrRemote, CRecvPacketCallback( PacketReceived, this ), errMsg );
if ( !m_pSocket )
return false;
// We use SteamID validity to denote when our connection has been accepted,
// so it's important that it be cleared
Assert( m_steamIDRemote.GetEAccountType() == k_EAccountTypeInvalid );
m_steamIDRemote.Clear();
// Let base class do some common initialization
uint32 nPeerProtocolVersion = 0; // don't know yet
SteamNetworkingMicroseconds usecNow = SteamNetworkingSockets_GetLocalTimestamp();
if ( !CSteamNetworkConnectionBase::BInitConnection( nPeerProtocolVersion, usecNow, errMsg ) )
{
m_pSocket->Close();
m_pSocket = nullptr;
return false;
}
// We should know our own identity, unless the app has said it's OK to go without this.
if ( !m_steamIDLocal.IsValid() && steamdatagram_ip_allow_connections_without_auth == 0 )
{
V_strcpy_safe( errMsg, "Unable to determine local SteamID. Not logged into Steam?" );
return false;
}
// Start the connection state machine, and send the first request packet.
CheckConnectionStateAndSetNextThinkTime( usecNow );
return true;
}
bool CSteamNetworkConnectionIPv4::BCanSendEndToEndConnectRequest() const
{
return m_pSocket != nullptr;
}
bool CSteamNetworkConnectionIPv4::BCanSendEndToEndData() const
{
return m_pSocket != nullptr;
}
void CSteamNetworkConnectionIPv4::SendEndToEndConnectRequest( SteamNetworkingMicroseconds usecNow )
{
Assert( !m_pParentListenSocket );
Assert( GetState() == k_ESteamNetworkingConnectionState_Connecting ); // Why else would we be doing this?
Assert( m_unConnectionIDLocal );
CMsgSteamSockets_UDP_ChallengeRequest msg;
msg.set_connection_id( m_unConnectionIDLocal );
//msg.set_client_steam_id( m_steamIDLocal.ConvertToUint64() );
msg.set_my_timestamp( usecNow );
msg.set_protocol_version( k_nCurrentProtocolVersion );
// Send it, with padding
SendPaddedMsg( k_ESteamNetworkingUDPMsg_ChallengeRequest, msg );
// They are supposed to reply with a timestamps, from which we can estimate the ping.
// So this counts as a ping request
m_statsEndToEnd.TrackSentPingRequest( usecNow, false );
}
void CSteamNetworkConnectionIPv4::SendEndToEndPing( bool bUrgent, SteamNetworkingMicroseconds usecNow )
{
SendStatsMsg( bUrgent ? k_EStatsReplyRequest_Immediate : k_EStatsReplyRequest_DelayedOK, usecNow );
}
void CSteamNetworkConnectionIPv4::ThinkConnection( SteamNetworkingMicroseconds usecNow )
{
// Check if we have stats we need to flush out
if ( BStateIsConnectedForWirePurposes() )
{
// Do we need to send something immediately, for any reason?
if (
m_statsEndToEnd.BNeedToSendStatsOrAcks( usecNow )
|| m_statsEndToEnd.BNeedToSendPingImmediate( usecNow )
) {
SendStatsMsg( k_EStatsReplyRequest_None, usecNow );
// Make sure that took care of what we needed!
Assert( !m_statsEndToEnd.BNeedToSendStatsOrAcks( usecNow ) );
Assert( !m_statsEndToEnd.BNeedToSendPingImmediate( usecNow ) );
}
}
}
bool CSteamNetworkConnectionIPv4::BBeginAccept(
CSteamNetworkListenSocketStandard *pParent,
const netadr_t &adrFrom,
CSharedSocket *pSharedSock,
CSteamID steamID,
uint32 unConnectionIDRemote,
uint32 nPeerProtocolVersion,
const CMsgSteamDatagramCertificateSigned &msgCert,
const CMsgSteamDatagramSessionCryptInfoSigned &msgCryptSessionInfo,
SteamDatagramErrMsg &errMsg
)
{
AssertMsg( !m_pSocket, "Trying to accept when we already have a socket?" );
// Get an interface just to talk just to this guy
m_pSocket = pSharedSock->AddRemoteHost( adrFrom, CRecvPacketCallback( PacketReceived, this ) );
if ( !m_pSocket )
{
V_strcpy_safe( errMsg, "Unable to create a bound socket on the shared socket." );
return false;
}
m_steamIDRemote = steamID;
m_unConnectionIDRemote = unConnectionIDRemote;
m_netAdrRemote = adrFrom;
pParent->AddChildConnection( this );
// Let base class do some common initialization
SteamNetworkingMicroseconds usecNow = SteamNetworkingSockets_GetLocalTimestamp();
if ( !CSteamNetworkConnectionBase::BInitConnection( nPeerProtocolVersion, usecNow, errMsg ) )
{
m_pSocket->Close();
m_pSocket = nullptr;
return false;
}
// Process crypto handshake now
if ( !BRecvCryptoHandshake( msgCert, msgCryptSessionInfo, true ) )
{
m_pSocket->Close();
m_pSocket = nullptr;
return false;
}
// OK
return true;
}
EResult CSteamNetworkConnectionIPv4::APIAcceptConnection()
{
SteamNetworkingMicroseconds usecNow = SteamNetworkingSockets_GetLocalTimestamp();
// Send the message
SendConnectOK( usecNow );
// We are fully connected
ConnectionState_Connected( usecNow );
// OK
return k_EResultOK;
}
void CSteamNetworkConnectionIPv4::SendMsg( uint8 nMsgID, const google::protobuf::MessageLite &msg )
{
uint8 pkt[ k_cbSteamNetworkingSocketsMaxUDPMsgLen ];
pkt[0] = nMsgID;
int cbPkt = msg.ByteSize()+1;
if ( cbPkt > sizeof(pkt) )
{
AssertMsg3( false, "Msg type %d is %d bytes, larger than MTU of %d bytes", int( nMsgID ), cbPkt, (int)sizeof(pkt) );
return;
}
uint8 *pEnd = msg.SerializeWithCachedSizesToArray( pkt+1 );
Assert( cbPkt == pEnd - pkt );
SendPacket( pkt, cbPkt );
}
void CSteamNetworkConnectionIPv4::SendPaddedMsg( uint8 nMsgID, const google::protobuf::MessageLite &msg )
{
uint8 pkt[ k_cbSteamNetworkingSocketsMaxUDPMsgLen ];
V_memset( pkt, 0, sizeof(pkt) ); // don't send random bits from our process memory over the wire!
UDPPaddedMessageHdr *hdr = (UDPPaddedMessageHdr *)pkt;
int nMsgLength = msg.ByteSize();
if ( nMsgLength + sizeof(*hdr) > k_cbSteamNetworkingSocketsMaxUDPMsgLen )
{
AssertMsg3( false, "Msg type %d is %d bytes, larger than MTU of %d bytes", int( nMsgID ), int( nMsgLength + sizeof(*hdr) ), (int)sizeof(pkt) );
return;
}
hdr->m_nMsgID = nMsgID;
hdr->m_nMsgLength = LittleWord( uint16( nMsgLength ) );
uint8 *pEnd = msg.SerializeWithCachedSizesToArray( pkt + sizeof(*hdr) );
int cbPkt = pEnd - pkt;
Assert( cbPkt == int( sizeof(*hdr) + nMsgLength ) );
cbPkt = MAX( cbPkt, k_cbSteamNetworkingMinPaddedPacketSize );
SendPacket( pkt, cbPkt );
}
void CSteamNetworkConnectionIPv4::SendPacket( const void *pkt, int cbPkt )
{
iovec temp;
temp.iov_base = const_cast<void*>( pkt );
temp.iov_len = cbPkt;
SendPacketGather( 1, &temp, cbPkt );
}
void CSteamNetworkConnectionIPv4::SendPacketGather( int nChunks, const iovec *pChunks, int cbSendTotal )
{
// Safety
if ( !m_pSocket )
{
AssertMsg( false, "Attemt to send packet, but socket has been closed!" );
return;
}
// Update stats
m_statsEndToEnd.TrackSentPacket( cbSendTotal );
// Hand over to operating system
m_pSocket->BSendRawPacketGather( nChunks, pChunks );
}
void CSteamNetworkConnectionIPv4::ConnectionStateChanged( ESteamNetworkingConnectionState eOldState )
{
CSteamNetworkConnectionBase::ConnectionStateChanged( eOldState );
switch ( GetState() )
{
case k_ESteamNetworkingConnectionState_FindingRoute: // not used for IPv4
default:
Assert( false );
case k_ESteamNetworkingConnectionState_None:
case k_ESteamNetworkingConnectionState_Dead:
return;
case k_ESteamNetworkingConnectionState_FinWait:
case k_ESteamNetworkingConnectionState_ProblemDetectedLocally:
SendConnectionClosedOrNoConnection();
break;
case k_ESteamNetworkingConnectionState_Linger:
break;
case k_ESteamNetworkingConnectionState_Connecting:
case k_ESteamNetworkingConnectionState_Connected:
case k_ESteamNetworkingConnectionState_ClosedByPeer:
break;
}
}
#define ReportBadPacketIPv4( pszMsgType, /* fmt */ ... ) \
ReportBadPacketFrom( m_pSocket->GetRemoteHostAddr(), pszMsgType, __VA_ARGS__ )
void CSteamNetworkConnectionIPv4::PacketReceived( const void *pvPkt, int cbPkt, const netadr_t &adrFrom, CSteamNetworkConnectionIPv4 *pSelf )
{
const uint8 *pPkt = static_cast<const uint8 *>( pvPkt );
SteamNetworkingMicroseconds usecNow = SteamNetworkingSockets_GetLocalTimestamp();
pSelf->m_statsEndToEnd.TrackRecvPacket( cbPkt, usecNow ); // FIXME - We really shouldn't do this until we know it is valid and hasn't been spoofed!
if ( cbPkt < 5 )
{
ReportBadPacket( "packet", "%d byte packet is too small", cbPkt );
return;
}
if ( *pPkt & 0x80 )
{
pSelf->Received_Data( pPkt, cbPkt, usecNow );
}
else if ( *pPkt == k_ESteamNetworkingUDPMsg_ChallengeReply )
{
ParseProtobufBody( pPkt+1, cbPkt-1, CMsgSteamSockets_UDP_ChallengeReply, msg )
pSelf->Received_ChallengeReply( msg, usecNow );
}
else if ( *pPkt == k_ESteamNetworkingUDPMsg_ConnectOK )
{
ParseProtobufBody( pPkt+1, cbPkt-1, CMsgSteamSockets_UDP_ConnectOK, msg );
pSelf->Received_ConnectOK( msg, usecNow );
}
else if ( *pPkt == k_ESteamNetworkingUDPMsg_ConnectionClosed )
{
ParsePaddedPacket( pvPkt, cbPkt, CMsgSteamSockets_UDP_ConnectionClosed, msg )
pSelf->Received_ConnectionClosed( msg, usecNow );
}
else if ( *pPkt == k_ESteamNetworkingUDPMsg_NoConnection )
{
ParseProtobufBody( pPkt+1, cbPkt-1, CMsgSteamSockets_UDP_NoConnection, msg )
pSelf->Received_NoConnection( msg, usecNow );
}
else if ( *pPkt == k_ESteamNetworkingUDPMsg_ChallengeRequest )
{
ParsePaddedPacket( pvPkt, cbPkt, CMsgSteamSockets_UDP_ChallengeRequest, msg )
pSelf->Received_ChallengeOrConnectRequest( "ChallengeRequest", msg.connection_id(), usecNow );
}
else if ( *pPkt == k_ESteamNetworkingUDPMsg_ConnectRequest )
{
ParseProtobufBody( pPkt+1, cbPkt-1, CMsgSteamSockets_UDP_ConnectRequest, msg )
pSelf->Received_ChallengeOrConnectRequest( "ConnectRequest", msg.client_connection_id(), usecNow );
}
else if ( *pPkt == k_ESteamNetworkingUDPMsg_Stats )
{
ParseProtobufBody( pPkt+1, cbPkt-1, CMsgSteamSockets_UDP_Stats, msg )
pSelf->Received_Stats( msg, usecNow );
}
else
{
ReportBadPacket( "packet", "Lead byte 0x%02x not a known message ID", *pPkt );
}
}
std::string DescribeStatsContents( const CMsgSteamSockets_UDP_Stats &msg )
{
std::string sWhat;
if ( msg.flags() & msg.ACK_REQUEST_E2E )
sWhat += " request_ack";
if ( msg.flags() & msg.ACK_REQUEST_IMMEDIATE )
sWhat += " request_ack_immediate";
if ( msg.stats().has_lifetime() )
sWhat += " stats.life";
if ( msg.stats().has_instantaneous() )
sWhat += " stats.rate";
if ( msg.ack_e2e_size() > 0 )
sWhat += " ack";
return sWhat;
}
void CSteamNetworkConnectionIPv4::RecvStats( const CMsgSteamSockets_UDP_Stats &msgStatsIn, bool bInline, SteamNetworkingMicroseconds usecNow )
{
// Connection quality stats?
if ( msgStatsIn.has_stats() )
m_statsEndToEnd.ProcessMessage( msgStatsIn.stats(), usecNow );
// Receive acks, if any
m_statsEndToEnd.RecvPackedAcks( msgStatsIn.ack_e2e(), usecNow );
// Spew appropriately
if ( g_eSteamDatagramDebugOutputDetailLevel >= k_ESteamNetworkingSocketsDebugOutputType_Verbose )
{
std::string sWhat = DescribeStatsContents( msgStatsIn );
SpewVerbose( "Recvd %s stats from %s @ %s:%s\n",
bInline ? "inline" : "standalone",
m_steamIDRemote.Render(),
CUtlNetAdrRender( m_pSocket->GetRemoteHostAddr() ).String(),
sWhat.c_str()
);
}
// Check if we need to reply, either now or later
if ( BStateIsConnectedForWirePurposes() )
{
// Check for queuing outgoing acks
bool bImmediate = ( msgStatsIn.flags() & msgStatsIn.ACK_REQUEST_IMMEDIATE ) != 0;
if ( ( msgStatsIn.flags() & msgStatsIn.ACK_REQUEST_E2E ) || msgStatsIn.has_stats() )
{
m_statsEndToEnd.QueueOutgoingAck( msgStatsIn.seq_num(), bImmediate, usecNow );
}
// Do we need to send an immediate reply?
if (
m_statsEndToEnd.BNeedToSendPingImmediate( usecNow )
|| m_statsEndToEnd.BNeedToSendStatsOrAcks( usecNow )
) {
// Send a stats message
SendStatsMsg( k_EStatsReplyRequest_None, usecNow );
}
}
}
void CSteamNetworkConnectionIPv4::TrackSentStats( const CMsgSteamSockets_UDP_Stats &msgStatsOut, bool bInline, SteamNetworkingMicroseconds usecNow )
{
// What effective flags will be received?
uint32 nSentFlags = msgStatsOut.flags();
if ( msgStatsOut.has_stats() )
nSentFlags |= msgStatsOut.ACK_REQUEST_E2E;
if ( nSentFlags & msgStatsOut.ACK_REQUEST_E2E )
{
bool bAllowDelayedReply = ( nSentFlags & msgStatsOut.ACK_REQUEST_IMMEDIATE ) == 0;
// Record that we sent stats and are waiting for peer to ack
if ( msgStatsOut.has_stats() )
{
m_statsEndToEnd.TrackSentStats( msgStatsOut.stats(), usecNow, bAllowDelayedReply );
}
else if ( ( nSentFlags & msgStatsOut.ACK_REQUEST_E2E ) )
{
m_statsEndToEnd.TrackSentMessageExpectingSeqNumAck( usecNow, bAllowDelayedReply );
}
}
// Did we send any acks?
m_statsEndToEnd.TrackSentPackedAcks( msgStatsOut.ack_e2e() );
// Spew appropriately
if ( g_eSteamDatagramDebugOutputDetailLevel >= k_ESteamNetworkingSocketsDebugOutputType_Verbose )
{
std::string sWhat = DescribeStatsContents( msgStatsOut );
SpewVerbose( "Sent %s stats to %s @ %s:%s\n",
bInline ? "inline" : "standalone",
m_steamIDRemote.Render(),
CUtlNetAdrRender( m_pSocket->GetRemoteHostAddr() ).String(),
sWhat.c_str()
);
}
}
void CSteamNetworkConnectionIPv4::SendStatsMsg( EStatsReplyRequest eReplyRequested, SteamNetworkingMicroseconds usecNow )
{
CMsgSteamSockets_UDP_Stats msg;
if ( m_unConnectionIDRemote )
msg.set_to_connection_id( m_unConnectionIDRemote );
msg.set_from_connection_id( m_unConnectionIDLocal );
msg.set_seq_num( m_statsEndToEnd.GetNextSendSequenceNumber( usecNow ) );
// What flags should we set?
uint32 nFlags = 0;
if ( eReplyRequested == k_EStatsReplyRequest_Immediate || m_statsEndToEnd.BNeedToSendPingImmediate( usecNow ) )
nFlags |= msg.ACK_REQUEST_E2E | msg.ACK_REQUEST_IMMEDIATE;
else if ( eReplyRequested == k_EStatsReplyRequest_DelayedOK || m_statsEndToEnd.BNeedToSendKeepalive( usecNow ) || m_statsEndToEnd.BReadyToSendTracerPing( usecNow ) )
nFlags |= msg.ACK_REQUEST_E2E;
// Need to send any connection stats stats?
if ( m_statsEndToEnd.BReadyToSendStats( usecNow ) )
m_statsEndToEnd.PopulateMessage( *msg.mutable_stats(), usecNow );
// Any pending acks?
PutEndToEndAcksIntoMessage( msg, m_statsEndToEnd, usecNow );
// Always set flags into message, even if they can be implied by the presence of stats
msg.set_flags( nFlags );
// Send it
SendMsg( k_ESteamNetworkingUDPMsg_Stats, msg );
// Track that we sent stats
TrackSentStats( msg, false, usecNow );
}
void CSteamNetworkConnectionIPv4::Received_Data( const uint8 *pPkt, int cbPkt, SteamNetworkingMicroseconds usecNow )
{
if ( cbPkt < sizeof(UDPDataMsgHdr) )
{
ReportBadPacketIPv4( "DataPacket", "Packet of size %d is too small.", cbPkt );
return;
}
// Check cookie
const UDPDataMsgHdr *hdr = (const UDPDataMsgHdr *)pPkt;
if ( LittleDWord( hdr->m_unToConnectionID ) != m_unConnectionIDLocal )
{
// Wrong session. It could be an old session, or it could be spoofed.
ReportBadPacketIPv4( "DataPacket", "Incorrect connection ID" );
if ( BCheckGlobalSpamReplyRateLimit( usecNow ) )
{
SendNoConnection( LittleDWord( hdr->m_unToConnectionID ), 0 );
}
return;
}
uint16 nWirePktNumber = LittleWord( hdr->m_unSeqNum );
m_statsEndToEnd.TrackRecvSequencedPacket( nWirePktNumber, usecNow, 0 );
// Check state
switch ( GetState() )
{
case k_ESteamNetworkingConnectionState_Dead:
case k_ESteamNetworkingConnectionState_None:
case k_ESteamNetworkingConnectionState_FindingRoute: // not used for IPv4
default:
Assert( false );
return;
case k_ESteamNetworkingConnectionState_ClosedByPeer:
case k_ESteamNetworkingConnectionState_FinWait:
case k_ESteamNetworkingConnectionState_ProblemDetectedLocally:
SendConnectionClosedOrNoConnection();
return;
case k_ESteamNetworkingConnectionState_Linger:
// FIXME: What should we do here? We are half-closed here, so this
// data is definitely going to be ignored. Do we need to communicate
// that state to the remote host somehow?
return;
case k_ESteamNetworkingConnectionState_Connecting:
// Ignore it. We don't have the SteamID of whoever is on the other end yet,
// their encryption keys, etc. The most likely cause is that a server sent
// a ConnectOK, which dropped. So they think we're connected but we don't
// have everything yet.
return;
case k_ESteamNetworkingConnectionState_Connected:
// We'll process the chunk
break;
}
const uint8 *pIn = pPkt + sizeof(*hdr);
const uint8 *pPktEnd = pPkt + cbPkt;
// Inline stats?
uint32 cbStatsMsgIn = 0;
if ( hdr->m_unMsgFlags & hdr->kFlag_ProtobufBlob )
{
//Msg_Verbose( "Received inline stats from %s", server.m_szName );
pIn = DeserializeVarInt( pIn, pPktEnd, cbStatsMsgIn );
if ( pIn == NULL )
{
ReportBadPacketIPv4( "DataPacket", "Failed to varint decode size of stats blob" );
return;
}
if ( pIn + cbStatsMsgIn > pPktEnd )
{
ReportBadPacketIPv4( "DataPacket", "stats message size doesn't make sense. Stats message size %d, packet size %d", cbStatsMsgIn, cbPkt );
return;
}
CMsgSteamSockets_UDP_Stats msgStatsIn;
if ( !msgStatsIn.ParseFromArray( pIn, cbStatsMsgIn ) )
{
ReportBadPacketIPv4( "DataPacket", "protobuf failed to parse inline stats message" );
return;
}
// Shove sequence number so we know what acks to pend, etc
msgStatsIn.set_seq_num( nWirePktNumber );
// Process the stats
RecvStats( msgStatsIn, true, usecNow );
// Advance pointer
pIn += cbStatsMsgIn;
}
RecvDataChunk( nWirePktNumber, pIn, pPktEnd - pIn, cbPkt, usecNow );
}
void CSteamNetworkConnectionIPv4::Received_ChallengeReply( const CMsgSteamSockets_UDP_ChallengeReply &msg, SteamNetworkingMicroseconds usecNow )
{
// We should only be getting this if we are the "client"
if ( m_pParentListenSocket )
{
ReportBadPacketIPv4( "ChallengeReply", "Shouldn't be receiving this unless on accepted connections, only connections initiated locally." );
return;
}
// Ignore if we're not trying to connect
if ( GetState() != k_ESteamNetworkingConnectionState_Connecting )
return;
// Check session ID to make sure they aren't spoofing.
if ( msg.connection_id() != m_unConnectionIDLocal )
{
ReportBadPacketIPv4( "ChallengeReply", "Incorrect connection ID. Message is stale or could be spoofed, ignoring." );
return;
}
if ( msg.protocol_version() < k_nMinRequiredProtocolVersion )
{
ConnectionState_ProblemDetectedLocally( k_ESteamNetConnectionEnd_Misc_Generic, "Peer is running old software and needs to be udpated" );
return;
}
// Update ping, if they replied with the timestamp
if ( msg.has_your_timestamp() )
{
SteamNetworkingMicroseconds usecElapsed = usecNow - (SteamNetworkingMicroseconds)msg.your_timestamp();
if ( usecElapsed < 0 || usecElapsed > 2*k_nMillion )
{
SpewWarning( "Ignoring weird timestamp %llu in ChallengeReply, current time is %llu.\n", (unsigned long long)msg.your_timestamp(), usecNow );
}
else
{
int nPing = (usecElapsed + 500 ) / 1000;
m_statsEndToEnd.m_ping.ReceivedPing( nPing, usecNow );
}
}
// Make sure we have the crypt info that we need
if ( !m_msgSignedCertLocal.has_cert() || !m_msgSignedCryptLocal.has_info() )
{
ConnectionState_ProblemDetectedLocally( k_ESteamNetConnectionEnd_Misc_InternalError, "Tried to connect request, but crypt not ready" );
return;
}
// Remember protocol version. They should send it again in the connect OK, but we have a valid value now,
// so we might as well save it
m_statsEndToEnd.m_nPeerProtocolVersion = msg.protocol_version();
// Reply with the challenge data and our SteamID
CMsgSteamSockets_UDP_ConnectRequest msgConnectRequest;
msgConnectRequest.set_client_connection_id( m_unConnectionIDLocal );
msgConnectRequest.set_challenge( msg.challenge() );
msgConnectRequest.set_client_steam_id( m_steamIDLocal.ConvertToUint64() );
msgConnectRequest.set_my_timestamp( usecNow );
if ( m_statsEndToEnd.m_ping.m_nSmoothedPing >= 0 )
msgConnectRequest.set_ping_est_ms( m_statsEndToEnd.m_ping.m_nSmoothedPing );
*msgConnectRequest.mutable_cert() = m_msgSignedCertLocal;
*msgConnectRequest.mutable_crypt() = m_msgSignedCryptLocal;
msgConnectRequest.set_protocol_version( k_nCurrentProtocolVersion );
SendMsg( k_ESteamNetworkingUDPMsg_ConnectRequest, msgConnectRequest );
// Reset timeout/retry for this reply. But if it fails, we'll start
// the whole handshake over again. It keeps the code simpler, and the
// challenge value has a relatively short expiry anyway.
m_usecWhenSentConnectRequest = usecNow;
EnsureMinThinkTime( usecNow + k_usecConnectRetryInterval );
// They are supposed to reply with a timestamps, from which we can estimate the ping.
// So this counts as a ping request
m_statsEndToEnd.TrackSentPingRequest( usecNow, false );
}
void CSteamNetworkConnectionIPv4::Received_ConnectOK( const CMsgSteamSockets_UDP_ConnectOK &msg, SteamNetworkingMicroseconds usecNow )
{
// We should only be getting this if we are the "client"
if ( m_pParentListenSocket )
{
ReportBadPacketIPv4( "ConnectOK", "Shouldn't be receiving this unless on accepted connections, only connections initiated locally." );
return;
}
// Check connection ID to make sure they aren't spoofing and it's the same connection we think it is
if ( msg.client_connection_id() != m_unConnectionIDLocal )
{
ReportBadPacketIPv4( "ConnectOK", "Incorrect connection ID. Message is stale or could be spoofed, ignoring." );
return;
}
// Who are they? We'll authenticate their cert below
CSteamID steamIDRemote( uint64( msg.server_steam_id() ) );
if ( !steamIDRemote.IsValid() && steamdatagram_ip_allow_connections_without_auth == 0 )
{
ReportBadPacketIPv4( "ConnectOK", "Invalid server_steam_id." );
return;
}
// Make sure they are still who we think they are
if ( m_steamIDRemote.IsValid() && m_steamIDRemote != steamIDRemote )
{
ReportBadPacketIPv4( "ConnectOK", "server_steam_id doesn't match who we expect to be connecting to!" );
return;
}
// Update ping, if they replied a timestamp
if ( msg.has_your_timestamp() )
{
SteamNetworkingMicroseconds usecElapsed = usecNow - (SteamNetworkingMicroseconds)msg.your_timestamp() - msg.delay_time_usec();
if ( usecElapsed < 0 || usecElapsed > 2*k_nMillion )
{
SpewWarning( "Ignoring weird timestamp %llu in ConnectOK, current time is %llu, remote delay was %lld.\n", (unsigned long long)msg.your_timestamp(), usecNow, (long long)msg.delay_time_usec() );
}
else
{
int nPing = (usecElapsed + 500 ) / 1000;
m_statsEndToEnd.m_ping.ReceivedPing( nPing, usecNow );
}
}
// Check state
switch ( GetState() )
{
case k_ESteamNetworkingConnectionState_Dead:
case k_ESteamNetworkingConnectionState_None:
case k_ESteamNetworkingConnectionState_FindingRoute: // not used for IPv4
default:
Assert( false );
return;
case k_ESteamNetworkingConnectionState_ClosedByPeer:
case k_ESteamNetworkingConnectionState_FinWait:
case k_ESteamNetworkingConnectionState_ProblemDetectedLocally:
SendConnectionClosedOrNoConnection();
return;
case k_ESteamNetworkingConnectionState_Linger:
case k_ESteamNetworkingConnectionState_Connected:
// We already know we were able to establish the connection.
// Just ignore this packet
return;
case k_ESteamNetworkingConnectionState_Connecting:
break;
}
if ( msg.protocol_version() < k_nMinRequiredProtocolVersion )
{
ConnectionState_ProblemDetectedLocally( k_ESteamNetConnectionEnd_Misc_Generic, "Peer is running old software and needs to be udpated" );
return;
}
m_statsEndToEnd.m_nPeerProtocolVersion = msg.protocol_version();
// New peers should send us their connection ID
m_unConnectionIDRemote = msg.server_connection_id();
if ( ( m_unConnectionIDRemote & 0xffff ) == 0 )
{
ConnectionState_ProblemDetectedLocally( k_ESteamNetConnectionEnd_Remote_BadCrypt, "Didn't send valid connection ID" );
return;
}
m_steamIDRemote = steamIDRemote;
// Check the certs, save keys, etc
if ( !BRecvCryptoHandshake( msg.cert(), msg.crypt(), false ) )
{
Assert( GetState() == k_ESteamNetworkingConnectionState_ProblemDetectedLocally );
ReportBadPacketIPv4( "ConnectOK", "Failed crypto init. %s", m_szEndDebug );
return;
}
// Generic connection code will take it from here.
ConnectionState_Connected( usecNow );
}
void CSteamNetworkConnectionIPv4::Received_ConnectionClosed( const CMsgSteamSockets_UDP_ConnectionClosed &msg, SteamNetworkingMicroseconds usecNow )
{
// Give them a reply to let them know we heard from them. If it's the right connection ID,
// then they probably aren't spoofing and it's critical that we give them an ack!
//
// If the wrong connection ID, then it could be an old connection so we'd like to send a reply
// to let them know that they can stop telling us the connection is closed.
// However, it could just be random garbage, so we need to protect ourselves from abuse,
// so limit how many of these we send.
bool bConnectionIDMatch =
msg.to_connection_id() == m_unConnectionIDLocal
|| ( msg.to_connection_id() == 0 && msg.from_connection_id() && msg.from_connection_id() == m_unConnectionIDRemote ); // they might not know our ID yet, if they are a client aborting the connection really early.
if ( bConnectionIDMatch || BCheckGlobalSpamReplyRateLimit( usecNow ) )
{
// Send a reply, echoing exactly what they sent to us
CMsgSteamSockets_UDP_NoConnection msgReply;
if ( msg.to_connection_id() )
msgReply.set_from_connection_id( msg.to_connection_id() );
if ( msg.from_connection_id() )
msgReply.set_to_connection_id( msg.from_connection_id() );
SendMsg( k_ESteamNetworkingUDPMsg_NoConnection, msgReply );
}
// If incorrect connection ID, then that's all we'll do, since this packet actually
// has nothing to do with current connection at all.
if ( !bConnectionIDMatch )
return;
// Generic connection code will take it from here.
ConnectionState_ClosedByPeer( msg.reason_code(), msg.debug().c_str() );
}
void CSteamNetworkConnectionIPv4::Received_NoConnection( const CMsgSteamSockets_UDP_NoConnection &msg, SteamNetworkingMicroseconds usecNow )
{
// Make sure it's an ack of something we would have sent
if ( msg.to_connection_id() != m_unConnectionIDLocal || msg.from_connection_id() != m_unConnectionIDRemote )
{
ReportBadPacketIPv4( "NoConnection", "Old/incorrect connection ID. Message is for a stale connection, or is spoofed. Ignoring." );
return;
}
// Generic connection code will take it from here.
ConnectionState_ClosedByPeer( 0, nullptr );
}
void CSteamNetworkConnectionIPv4::Received_Stats( const CMsgSteamSockets_UDP_Stats &msg, SteamNetworkingMicroseconds usecNow )
{
if ( msg.to_connection_id() == 0 )
{
ReportBadPacketIPv4( "Stats", "Missing connection ID." );
return;
}
// Check connection ID to make sure they aren't spoofing and it's the same connection we think it is
bool bConnectionIDMatch =
msg.to_connection_id() == m_unConnectionIDLocal
|| ( msg.to_connection_id() == 0 && msg.from_connection_id() && msg.from_connection_id() == m_unConnectionIDRemote ); // they might not know our ID yet, if they are a client aborting the connection really early.
if ( !bConnectionIDMatch )
{
if ( BCheckGlobalSpamReplyRateLimit( usecNow ) )
{
CMsgSteamSockets_UDP_NoConnection msgReply;
if ( msg.to_connection_id() )
msgReply.set_from_connection_id( msg.to_connection_id() );
if ( msg.from_connection_id() )
msgReply.set_to_connection_id( msg.from_connection_id() );
SendMsg( k_ESteamNetworkingUDPMsg_NoConnection, msgReply );
}
ReportBadPacketIPv4( "Stats", "Old/incorrect connection ID. Message is for a stale connection, or is spoofed. Ignoring." );
return;
}
// Update bookkeeping, we received a sequence number
RecvNonDataSequencedPacket( msg.seq_num(), usecNow );
// Process the incoming stats, and if it warrants an immediate reply, go ahead and send it now
RecvStats( msg, false, usecNow );
}
void CSteamNetworkConnectionIPv4::Received_ChallengeOrConnectRequest( const char *pszDebugPacketType, uint32 unPacketConnectionID, SteamNetworkingMicroseconds usecNow )
{
// If wrong connection ID, then check for sending a generic reply and bail
if ( unPacketConnectionID != m_unConnectionIDRemote )
{
ReportBadPacketIPv4( pszDebugPacketType, "Incorrect connection ID, when we do have a connection for this address. Could be spoofed, ignoring." );
// Let's not send a reply in this case
//if ( BCheckGlobalSpamReplyRateLimit( usecNow ) )
// SendNoConnection( unPacketConnectionID );
return;
}
// Check state
switch ( GetState() )
{
case k_ESteamNetworkingConnectionState_Dead:
case k_ESteamNetworkingConnectionState_None:
case k_ESteamNetworkingConnectionState_FindingRoute: // not used for IPv4
default:
Assert( false );
return;
case k_ESteamNetworkingConnectionState_ClosedByPeer:
case k_ESteamNetworkingConnectionState_FinWait:
case k_ESteamNetworkingConnectionState_ProblemDetectedLocally:
SendConnectionClosedOrNoConnection();
return;
case k_ESteamNetworkingConnectionState_Connecting:
// We're waiting on the application. So we'll just have to ignore.
break;
case k_ESteamNetworkingConnectionState_Linger:
case k_ESteamNetworkingConnectionState_Connected:
if ( !m_pParentListenSocket )
{
// WAT? We initiated this connection, so why are they requesting to connect?
ReportBadPacketIPv4( pszDebugPacketType, "We are the 'client' who initiated the connection, so 'server' shouldn't be sending us this!" );
return;
}
// This is totally legit and possible. Our earlier reply might have dropped, and they are re-sending
SendConnectOK( usecNow );
return;
}
}
void CSteamNetworkConnectionIPv4::SendConnectionClosedOrNoConnection()
{
if ( GetState() == k_ESteamNetworkingConnectionState_ClosedByPeer )
{
SendNoConnection( m_unConnectionIDLocal, m_unConnectionIDRemote );
}
else
{
CMsgSteamSockets_UDP_ConnectionClosed msg;
msg.set_from_connection_id( m_unConnectionIDLocal );
if ( m_unConnectionIDRemote )
msg.set_to_connection_id( m_unConnectionIDRemote );
msg.set_reason_code( m_eEndReason );
if ( m_szEndDebug[0] )
msg.set_debug( m_szEndDebug );
SendPaddedMsg( k_ESteamNetworkingUDPMsg_ConnectionClosed, msg );
}
}
void CSteamNetworkConnectionIPv4::SendNoConnection( uint32 unFromConnectionID, uint32 unToConnectionID )
{
CMsgSteamSockets_UDP_NoConnection msg;
if ( unFromConnectionID == 0 && unToConnectionID == 0 )
{
AssertMsg( false, "Can't send NoConnection, we need at least one of from/to connection ID!" );
return;
}
if ( unFromConnectionID )
msg.set_from_connection_id( unFromConnectionID );
if ( unToConnectionID )
msg.set_to_connection_id( unToConnectionID );
SendMsg( k_ESteamNetworkingUDPMsg_NoConnection, msg );
}
void CSteamNetworkConnectionIPv4::SendConnectOK( SteamNetworkingMicroseconds usecNow )
{
Assert( m_unConnectionIDLocal );
Assert( m_unConnectionIDRemote );
Assert( m_pParentListenSocket );
Assert( m_msgSignedCertLocal.has_cert() );
Assert( m_msgSignedCryptLocal.has_info() );
CMsgSteamSockets_UDP_ConnectOK msg;
msg.set_client_connection_id( m_unConnectionIDRemote );
msg.set_server_connection_id( m_unConnectionIDLocal );
msg.set_server_steam_id( m_steamIDLocal.ConvertToUint64() );
*msg.mutable_cert() = m_msgSignedCertLocal;
*msg.mutable_crypt() = m_msgSignedCryptLocal;
msg.set_protocol_version( k_nCurrentProtocolVersion );
// Do we have a timestamp?
if ( m_usecWhenReceivedHandshakeRemoteTimestamp )
{
SteamNetworkingMicroseconds usecElapsed = usecNow - m_usecWhenReceivedHandshakeRemoteTimestamp;
Assert( usecElapsed >= 0 );
if ( usecElapsed < 4*k_nMillion )
{
msg.set_your_timestamp( m_ulHandshakeRemoteTimestamp );
msg.set_delay_time_usec( usecElapsed );
}
else
{
SpewWarning( "Discarding handshake timestamp that's %lldms old, not sending in ConnectOK\n", usecElapsed/1000 );
m_usecWhenReceivedHandshakeRemoteTimestamp = 0;
}
}
// Send it, with padding
SendMsg( k_ESteamNetworkingUDPMsg_ConnectOK, msg );
}
/////////////////////////////////////////////////////////////////////////////
//
// Loopback connections
//
/////////////////////////////////////////////////////////////////////////////
CSteamNetworkConnectionlocalhostLoopback::CSteamNetworkConnectionlocalhostLoopback( CSteamNetworkingSockets *pSteamNetworkingSocketsInterface )
: CSteamNetworkConnectionIPv4( pSteamNetworkingSocketsInterface )
{
}
bool CSteamNetworkConnectionlocalhostLoopback::BAllowRemoteUnsignedCert() { return true; }
void CSteamNetworkConnectionlocalhostLoopback::InitConnectionCrypto( SteamNetworkingMicroseconds usecNow )
{
InitLocalCryptoWithUnsignedCert();
}
void CSteamNetworkConnectionlocalhostLoopback::PostConnectionStateChangedCallback( ESteamNetworkingConnectionState eOldAPIState, ESteamNetworkingConnectionState eNewAPIState )
{
// Don't post any callbacks for the initial transitions.
if ( eNewAPIState == k_ESteamNetworkingConnectionState_Connected || eNewAPIState == k_ESteamNetworkingConnectionState_Connected )
return;
// But post callbacks for these guys
CSteamNetworkConnectionIPv4::PostConnectionStateChangedCallback( eOldAPIState, eNewAPIState );
}
bool CSteamNetworkConnectionlocalhostLoopback::APICreateSocketPair( CSteamNetworkingSockets *pSteamNetworkingSocketsInterface, CSteamNetworkConnectionlocalhostLoopback *pConn[2] )
{
SteamDatagramErrMsg errMsg;
pConn[1] = new CSteamNetworkConnectionlocalhostLoopback( pSteamNetworkingSocketsInterface );
pConn[0] = new CSteamNetworkConnectionlocalhostLoopback( pSteamNetworkingSocketsInterface );
if ( !pConn[0] || !pConn[1] )
{
failed:
delete pConn[0]; pConn[0] = nullptr;
delete pConn[1]; pConn[1] = nullptr;
return false;
}
IBoundUDPSocket *sock[2];
if ( !CreateBoundSocketPair(
CRecvPacketCallback( CSteamNetworkConnectionIPv4::PacketReceived, (CSteamNetworkConnectionIPv4*)pConn[0] ),
CRecvPacketCallback( CSteamNetworkConnectionIPv4::PacketReceived, (CSteamNetworkConnectionIPv4*)pConn[1] ), sock, errMsg ) )
{
// Use assert here, because this really should only fail if we have some sort of bug
AssertMsg1( false, "Failed to create UDP socekt pair. %s", errMsg );
goto failed;
}
SteamNetworkingMicroseconds usecNow = SteamNetworkingSockets_GetLocalTimestamp();
// Initialize both connections
for ( int i = 0 ; i < 2 ; ++i )
{
pConn[i]->m_pSocket = sock[i];
if ( !pConn[i]->BInitConnection( k_nCurrentProtocolVersion, usecNow, errMsg ) )
goto failed;
}
// Tie the connections to each other, and mark them as connected
for ( int i = 0 ; i < 2 ; ++i )
{
CSteamNetworkConnectionlocalhostLoopback *p = pConn[i];
CSteamNetworkConnectionlocalhostLoopback *q = pConn[1-i];
p->m_steamIDRemote = q->m_steamIDLocal;
p->m_unConnectionIDRemote = q->m_unConnectionIDLocal;
p->m_statsEndToEnd.m_usecTimeLastRecv = usecNow; // Act like we just now received something
if ( !p->BRecvCryptoHandshake( q->m_msgSignedCertLocal, q->m_msgSignedCryptLocal, i==0 ) )
{
AssertMsg( false, "BRecvCryptoHandshake failed creating localhost socket pair" );
goto failed;
}
p->ConnectionState_Connected( usecNow );
}
return true;
}
void UpdateSNPDebugWindow()
{
#if defined( WIN32 )
static bool s_bDebugWindowActive = false;
static SteamNetworkingMicroseconds usec_debugWindowLastUpdate = 0;
static SteamNetworkingMicroseconds usec_debugWindowUpdateTime = k_nMillion / 10;
// do we need to enable the window
if ( !s_bDebugWindowActive && steamdatagram_snp_debug_window )
{
s_bDebugWindowActive = true;
InitSNPDebugWindow();
}
// or turn it off?
if ( s_bDebugWindowActive && !steamdatagram_snp_debug_window )
{
s_bDebugWindowActive = false;
ShutdownSNPDebugWindow();
return;
}
SteamNetworkingMicroseconds usecNow = SteamNetworkingSockets_GetLocalTimestamp();
if ( s_bDebugWindowActive && usecNow - usec_debugWindowLastUpdate >= usec_debugWindowUpdateTime )
{
usec_debugWindowLastUpdate = usecNow;
int numConnections = g_listConnections.Count();
const char **ppText = (const char **)stackalloc( sizeof( char * ) * numConnections );
int n = 0;
for ( int i = g_listConnections.CUtlLinkedListHead();
i != (int)g_listConnections.InvalidIndex();
i = g_listConnections.Next( i ) )
{
CSteamNetworkConnectionBase *pConn = g_listConnections[ i ];
char *p = new char[4096];
pConn->GetDebugText( p, 4096 );
ppText[ n++ ] = p;
}
SetSNPDebugText( numConnections, ppText );
for ( int i = 0; i < numConnections; ++i )
{
delete [] ppText[ i ];
}
RunFrameSNPDebugWindow();
}
#endif //defined( WIN32 )
}
} // namespace SteamNetworkingSocketsLib
| 35.175165 | 223 | 0.742671 | [
"render",
"object"
] |
91675218ba6057f7346d38970026c5055ca37d6f | 1,841 | cc | C++ | codechef/aug18a/kcompres.cc | Ashindustry007/competitive-programming | 2eabd3975c029d235abb7854569593d334acae2f | [
"WTFPL"
] | 506 | 2018-08-22T10:30:38.000Z | 2022-03-31T10:01:49.000Z | codechef/aug18a/kcompres.cc | Ashindustry007/competitive-programming | 2eabd3975c029d235abb7854569593d334acae2f | [
"WTFPL"
] | 13 | 2019-08-07T18:31:18.000Z | 2020-12-15T21:54:41.000Z | codechef/aug18a/kcompres.cc | Ashindustry007/competitive-programming | 2eabd3975c029d235abb7854569593d334acae2f | [
"WTFPL"
] | 234 | 2018-08-06T17:11:41.000Z | 2022-03-26T10:56:42.000Z | // https://www.codechef.com/AUG18A/problems/KCOMPRES
#include <algorithm>
#include <iostream>
#include <tuple>
#include <vector>
using namespace std;
typedef long long ll;
typedef tuple<ll, ll> ii;
typedef vector<ll> vi;
typedef vector<ii> vii;
vi tree;
ll n, nn;
void update(ll k, ll v) {
ll i = k + nn;
tree[i] = v;
for (i /= 2; i > 0 ; i /= 2) tree[i] = max(tree[2*i], tree[2*i+1]);
}
ll qmax(ll a, ll b) {
a += nn; b += nn;
ll m = 0;
while (a <= b) {
if (a % 2) m = max(m, tree[a++]);
if (!(b % 2)) m = max(m, tree[b--]);
a /= 2; b /= 2;
}
return m;
}
int main() {
int t;
cin >> t;
while (t--) {
ll s;
cin >> n >> s;
vii a(n);
for (int i = 0; i < n; i++) {
ll x;
cin >> x;
a[i] = {x, i};
}
if (s < n) {
cout << 0 << endl;
continue;
} else if (n == 1) {
cout << 2 << endl;
continue;
}
sort(a.begin(), a.end());
auto sum = [&](ll k) {
nn = 1;
while (n > nn) nn *= 2;
tree = vi(2*nn);
ll i = 0, j = -1, l = -1, v = -1;
vi ps;
while (i < n) {
ll x, y;
tie(x, y) = a[i];
if (v == -1) {
v = x;
j = max(0LL, y - k);
l = min(n - 1, y + k);
ps.push_back(y);
i++;
} else if (v == x && y <= l) {
l = min(n - 1, y + k);
ps.push_back(y);
i++;
}
else {
v = qmax(j, l) + 1;
for (auto z:ps) update(z, v);
v = -1;
ps.resize(0);
}
}
v = qmax(j, l) + 1;
for (auto z:ps) update(z, v);
ll s = 0;
for (ll i = nn; i < 2*nn; i++) s += tree[i];
return s;
};
ll k = 0;
for (ll b = n/2; b >= 1; b /= 2)
while (k+b <= n && sum(k+b) <= s) k+=b;
cout << k + 1 << endl;
}
}
| 19.795699 | 69 | 0.384574 | [
"vector"
] |
9167d5c3f98f7f870ecb0368701eb2ad5506d146 | 10,214 | cpp | C++ | isis/src/base/objs/Sinusoidal/Sinusoidal.cpp | ihumphrey-usgs/ISIS3_old | 284cc442b773f8369d44379ee29a9b46961d8108 | [
"Unlicense"
] | 1 | 2019-10-13T15:31:33.000Z | 2019-10-13T15:31:33.000Z | isis/src/base/objs/Sinusoidal/Sinusoidal.cpp | ihumphrey-usgs/ISIS3_old | 284cc442b773f8369d44379ee29a9b46961d8108 | [
"Unlicense"
] | null | null | null | isis/src/base/objs/Sinusoidal/Sinusoidal.cpp | ihumphrey-usgs/ISIS3_old | 284cc442b773f8369d44379ee29a9b46961d8108 | [
"Unlicense"
] | 1 | 2021-07-12T06:05:03.000Z | 2021-07-12T06:05:03.000Z | /**
* @file
* $Revision: 1.4 $
* $Date: 2008/05/09 18:49:25 $
*
* 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 "Sinusoidal.h"
#include <cmath>
#include <cfloat>
#include "Constants.h"
#include "IException.h"
#include "TProjection.h"
#include "Pvl.h"
#include "PvlGroup.h"
#include "PvlKeyword.h"
using namespace std;
namespace Isis {
/**
* Constructs a Sinusoidal object.
*
* @param label This argument must be a Label containing the proper mapping
* information as indicated in the Projection class. Additionally,
* the sinusoidal projection requires the center longitude to be
* defined in the keyword CenterLongitude.
*
* @param allowDefaults If set to false the constructor expects that a keyword
* of CenterLongitude will be in the label. Otherwise it
* will attempt to compute the center longitude using the
* middle of the longitude range specified in the labels.
* Defaults to false
*
* @throws IException
*/
Sinusoidal::Sinusoidal(Pvl &label, bool allowDefaults) :
TProjection::TProjection(label) {
try {
// Try to read the mapping group
PvlGroup &mapGroup = label.findGroup("Mapping", Pvl::Traverse);
// Compute and write the default center longitude if allowed and
// necessary
if ((allowDefaults) && (!mapGroup.hasKeyword("CenterLongitude"))) {
double lon = (m_minimumLongitude + m_maximumLongitude) / 2.0;
mapGroup += PvlKeyword("CenterLongitude", toString(lon));
}
// Get the center longitude
m_centerLongitude = mapGroup["CenterLongitude"];
// convert to radians, adjust for longitude direction
m_centerLongitude *= PI / 180.0;
if (m_longitudeDirection == PositiveWest) m_centerLongitude *= -1.0;
}
catch(IException &e) {
QString message = "Invalid label group [Mapping]";
throw IException(e, IException::Io, message, _FILEINFO_);
}
}
//! Destroys the Sinusoidal object
Sinusoidal::~Sinusoidal() {
}
/**
* Compares two Projection objects to see if they are equal
*
* @param proj Projection object to do comparison on
*
* @return bool Returns true if the Projection objects are equal, and false if
* they are not
*/
bool Sinusoidal::operator== (const Projection &proj) {
if (!TProjection::operator==(proj)) return false;
// dont do the below it is a recusive plunge
// if (TProjection::operator!=(proj)) return false;
Sinusoidal *sinu = (Sinusoidal *) &proj;
if (sinu->m_centerLongitude != m_centerLongitude) return false;
return true;
}
/**
* Returns the name of the map projection, "Sinusoidal"
*
* @return QString Name of projection, "Sinusoidal"
*/
QString Sinusoidal::Name() const {
return "Sinusoidal";
}
/**
* Returns the version of the map projection
*
*
* @return QString Version number
*/
QString Sinusoidal::Version() const {
return "1.0";
}
/**
* This method is used to set the latitude/longitude (assumed to be of the
* correct LatitudeType, LongitudeDirection, and LongitudeDomain. The Set
* forces an attempted calculation of the projection X/Y values. This may or
* may not be successful and a status is returned as such.
*
* @param lat Latitude value to project
*
* @param lon Longitude value to project
*
* @return bool
*/
bool Sinusoidal::SetGround(const double lat, const double lon) {
// Convert to radians
m_latitude = lat;
m_longitude = lon;
double latRadians = lat * PI / 180.0;
double lonRadians = lon * PI / 180.0;
if (m_longitudeDirection == PositiveWest) lonRadians *= -1.0;
// Compute the coordinate
double deltaLon = (lonRadians - m_centerLongitude);
double x = m_equatorialRadius * deltaLon * cos(latRadians);
double y = m_equatorialRadius * latRadians;
SetComputedXY(x, y);
m_good = true;
return m_good;
}
/**
* This method is used to set the projection x/y. The Set forces an attempted
* calculation of the corresponding latitude/longitude position. This may or
* may not be successful and a status is returned as such.
*
* @param x X coordinate of the projection in units that are the same as the
* radii in the label
*
* @param y Y coordinate of the projection in units that are the same as the
* radii in the label
*
* @return bool
*/
bool Sinusoidal::SetCoordinate(const double x, const double y) {
// Save the coordinate
SetXY(x, y);
// Compute latitude and make sure it is not above 90
m_latitude = GetY() / m_equatorialRadius;
if (fabs(m_latitude) > HALFPI) {
if (fabs(HALFPI - fabs(m_latitude)) > DBL_EPSILON) {
m_good = false;
return m_good;
}
else if (m_latitude < 0.0) {
m_latitude = -HALFPI;
}
else {
m_latitude = HALFPI;
}
}
// Compute longitude
double coslat = cos(m_latitude);
if (coslat <= DBL_EPSILON) {
m_longitude = m_centerLongitude;
}
else {
m_longitude = m_centerLongitude + GetX() / (m_equatorialRadius * coslat);
}
// Convert to degrees
m_latitude *= 180.0 / PI;
m_longitude *= 180.0 / PI;
// Cleanup the longitude
if (m_longitudeDirection == PositiveWest) m_longitude *= -1.0;
// These need to be done for circular type projections
// m_longitude = To360Domain (m_longitude);
// if (m_longitudeDomain == 180) m_longitude = To180Domain(m_longitude);
// Our double precision is not good once we pass a certain magnitude of
// longitude. Prevent failures down the road by failing now.
m_good = (fabs(m_longitude) < 1E10);
return m_good;
}
/**
* This method is used to determine the x/y range which completely covers the
* area of interest specified by the lat/lon range. The latitude/longitude
* range may be obtained from the labels. The purpose of this method is to
* return the x/y range so it can be used to compute how large a map may need
* to be. For example, how big a piece of paper is needed or how large of an
* image needs to be created. The method may fail as indicated by its return
* value.
*
* @param minX Minimum x projection coordinate which covers the latitude
* longitude range specified in the labels.
*
* @param maxX Maximum x projection coordinate which covers the latitude
* longitude range specified in the labels.
*
* @param minY Minimum y projection coordinate which covers the latitude
* longitude range specified in the labels.
*
* @param maxY Maximum y projection coordinate which covers the latitude
* longitude range specified in the labels.
*
* @return bool
*/
bool Sinusoidal::XYRange(double &minX, double &maxX,
double &minY, double &maxY) {
// Check the corners of the lat/lon range
XYRangeCheck(m_minimumLatitude, m_minimumLongitude);
XYRangeCheck(m_maximumLatitude, m_minimumLongitude);
XYRangeCheck(m_minimumLatitude, m_maximumLongitude);
XYRangeCheck(m_maximumLatitude, m_maximumLongitude);
// If the latitude crosses the equator check there
if ((m_minimumLatitude < 0.0) && (m_maximumLatitude > 0.0)) {
XYRangeCheck(0.0, m_minimumLongitude);
XYRangeCheck(0.0, m_maximumLongitude);
}
// Make sure everything is ordered
if (m_minimumX >= m_maximumX) return false;
if (m_minimumY >= m_maximumY) return false;
// Return X/Y min/maxs
minX = m_minimumX;
maxX = m_maximumX;
minY = m_minimumY;
maxY = m_maximumY;
return true;
}
/**
* This function returns the keywords that this projection uses.
*
* @return PvlGroup The keywords that this projection uses
*/
PvlGroup Sinusoidal::Mapping() {
PvlGroup mapping = TProjection::Mapping();
mapping += m_mappingGrp["CenterLongitude"];
return mapping;
}
/**
* This function returns the latitude keywords that this projection uses
*
* @return PvlGroup The latitude keywords that this projection uses
*/
PvlGroup Sinusoidal::MappingLatitudes() {
PvlGroup mapping = TProjection::MappingLatitudes();
return mapping;
}
/**
* This function returns the longitude keywords that this projection uses
*
* @return PvlGroup The longitude keywords that this projection uses
*/
PvlGroup Sinusoidal::MappingLongitudes() {
PvlGroup mapping = TProjection::MappingLongitudes();
mapping += m_mappingGrp["CenterLongitude"];
return mapping;
}
} // end namespace isis
/**
* This is the function that is called in order to instantiate a
* Sinusoidal object.
*
* @param lab Cube labels with appropriate Mapping information.
*
* @param allowDefaults Indicates whether CenterLongitude are allowed to
* be computed using the middle of the longitude
* range specified in the labels.
*
* @return @b Isis::Projection* Pointer to a Sinusoidal projection object.
*/
extern "C" Isis::TProjection *SinusoidalPlugin(Isis::Pvl &lab,
bool allowDefaults) {
return new Isis::Sinusoidal(lab, allowDefaults);
}
| 32.737179 | 81 | 0.666536 | [
"object"
] |
91692943f6c8b702c71d0973139fadab1e194dcb | 19,502 | cpp | C++ | applications/RANSApplication/tests/cpp/evm_k_epsilon/test_rans_evm_k_epsilon_conditions.cpp | HubertBalcerzak/Kratos | c15689d53f06dabb36dc44c13eeac73d3e183916 | [
"BSD-4-Clause"
] | null | null | null | applications/RANSApplication/tests/cpp/evm_k_epsilon/test_rans_evm_k_epsilon_conditions.cpp | HubertBalcerzak/Kratos | c15689d53f06dabb36dc44c13eeac73d3e183916 | [
"BSD-4-Clause"
] | null | null | null | applications/RANSApplication/tests/cpp/evm_k_epsilon/test_rans_evm_k_epsilon_conditions.cpp | HubertBalcerzak/Kratos | c15689d53f06dabb36dc44c13eeac73d3e183916 | [
"BSD-4-Clause"
] | null | null | null | // | / |
// ' / __| _` | __| _ \ __|
// . \ | ( | | ( |\__ `
// _|\_\_| \__,_|\__|\___/ ____/
// Multi-Physics
//
// License: BSD License
// Kratos default license: kratos/license.txt
//
// Main authors:
//
// System includes
#include <functional>
#include <iomanip>
#include <string>
#include <vector>
// External includes
// Project includes
#include "containers/model.h"
#include "includes/kratos_components.h"
#include "includes/variables.h"
#include "testing/testing.h"
// Application includes
#include "custom_conditions/evm_k_epsilon/rans_evm_k_epsilon_epsilon_wall.h"
#include "custom_conditions/evm_k_epsilon/rans_evm_k_epsilon_vms_monolithic_wall.h"
#include "rans_application_variables.h"
namespace Kratos
{
namespace Testing
{
namespace
{
void CreateRansEvmKEpsilonUnitTestModelPart(const std::string& rConditionName,
const std::vector<std::string>& rDofVariableNamesList,
ModelPart& rModelPart)
{
const auto& r_proto = KratosComponents<Condition>::Get(rConditionName);
auto node_ids = std::vector<ModelPart::IndexType>{};
Matrix coords;
r_proto.GetGeometry().PointsLocalCoordinates(coords);
if (coords.size2() == 1)
{
for (std::size_t i = 0; i < coords.size1(); ++i)
rModelPart.CreateNewNode(i + 1, coords(i, 0), 0.0, 0.0);
}
else
{
for (std::size_t i = 0; i < coords.size1(); ++i)
rModelPart.CreateNewNode(i + 1, coords(i, 0), coords(i, 1), 0.0);
}
for (auto& r_node : rModelPart.Nodes())
{
for (std::string dof_variable_name : rDofVariableNamesList)
{
if (KratosComponents<Variable<double>>::Has(dof_variable_name))
{
r_node
.AddDof(KratosComponents<Variable<double>>::Get(dof_variable_name))
.SetEquationId(r_node.Id());
}
else if (KratosComponents<Variable<array_1d<double, 3>>>::Has(dof_variable_name))
{
const auto& r_variable_x = KratosComponents<Variable<double>>::Get(
dof_variable_name + "_X");
const auto& r_variable_y = KratosComponents<Variable<double>>::Get(
dof_variable_name + "_Y");
r_node.AddDof(r_variable_x).SetEquationId(r_node.Id() * 5);
r_node.AddDof(r_variable_y).SetEquationId(r_node.Id() * 5);
if (coords.size2() != 2)
{
const auto& r_variable_z = KratosComponents<Variable<double>>::Get(
dof_variable_name + "_Z");
r_node.AddDof(r_variable_z).SetEquationId(r_node.Id() * 10);
}
}
else
{
KRATOS_ERROR
<< "DOF variable name = " << dof_variable_name
<< " not found in double, 3d-double variable lists.\n";
}
}
node_ids.push_back(r_node.Id());
}
auto p_prop = rModelPart.CreateNewProperties(1);
auto p_condition = rModelPart.CreateNewCondition(rConditionName, 1, node_ids, p_prop);
rModelPart.SetBufferSize(1);
p_condition->Check(rModelPart.GetProcessInfo());
}
void RansEvmKEpsilonEpsilonWall2D2N_SetUp(ModelPart& rModelPart)
{
// rModelPart.AddNodalSolutionStepVariable(DISTANCE);
rModelPart.AddNodalSolutionStepVariable(KINEMATIC_VISCOSITY);
rModelPart.AddNodalSolutionStepVariable(TURBULENT_VISCOSITY);
rModelPart.AddNodalSolutionStepVariable(TURBULENT_KINETIC_ENERGY);
rModelPart.AddNodalSolutionStepVariable(TURBULENT_ENERGY_DISSIPATION_RATE);
rModelPart.AddNodalSolutionStepVariable(RANS_Y_PLUS);
CreateRansEvmKEpsilonUnitTestModelPart(
"RansEvmKEpsilonEpsilonWall2D2N", {"TURBULENT_ENERGY_DISSIPATION_RATE"}, rModelPart);
}
void RansEvmKEpsilonVmsMonolithicWall2D2N_SetUp(ModelPart& rModelPart)
{
rModelPart.AddNodalSolutionStepVariable(DISTANCE);
rModelPart.AddNodalSolutionStepVariable(TURBULENT_KINETIC_ENERGY);
rModelPart.AddNodalSolutionStepVariable(RANS_Y_PLUS);
rModelPart.AddNodalSolutionStepVariable(DENSITY);
rModelPart.AddNodalSolutionStepVariable(VELOCITY);
rModelPart.AddNodalSolutionStepVariable(PRESSURE);
rModelPart.AddNodalSolutionStepVariable(MESH_VELOCITY);
rModelPart.AddNodalSolutionStepVariable(ACCELERATION);
rModelPart.AddNodalSolutionStepVariable(EXTERNAL_PRESSURE);
rModelPart.AddNodalSolutionStepVariable(KINEMATIC_VISCOSITY);
rModelPart.AddNodalSolutionStepVariable(TURBULENT_VISCOSITY);
rModelPart.AddNodalSolutionStepVariable(TURBULENT_ENERGY_DISSIPATION_RATE);
rModelPart.AddNodalSolutionStepVariable(VISCOSITY);
CreateRansEvmKEpsilonUnitTestModelPart(
"RansEvmKEpsilonVmsMonolithicWall2D2N", {"VELOCITY", "PRESSURE"}, rModelPart);
}
void RansEvmKEpsilonEpsilonWall2D2N_AssignTestData(ModelPart& rModelPart)
{
rModelPart.GetProcessInfo()[TURBULENCE_RANS_C_MU] = 0.09;
rModelPart.GetProcessInfo()[TURBULENT_ENERGY_DISSIPATION_RATE_SIGMA] = 0.98;
auto& node1 = rModelPart.GetNode(1);
node1.FastGetSolutionStepValue(KINEMATIC_VISCOSITY) = 0.24;
node1.FastGetSolutionStepValue(RANS_Y_PLUS) = 11.24;
node1.FastGetSolutionStepValue(TURBULENT_KINETIC_ENERGY) = 25.90;
node1.FastGetSolutionStepValue(TURBULENT_ENERGY_DISSIPATION_RATE) = 15.90;
node1.FastGetSolutionStepValue(TURBULENT_VISCOSITY) = 1.29;
auto& node2 = rModelPart.GetNode(2);
node2.FastGetSolutionStepValue(KINEMATIC_VISCOSITY) = 0.28;
node2.FastGetSolutionStepValue(TURBULENT_KINETIC_ENERGY) = 5.00;
node2.FastGetSolutionStepValue(TURBULENT_VISCOSITY) = 1.04;
node2.FastGetSolutionStepValue(RANS_Y_PLUS) = 11.24;
node2.FastGetSolutionStepValue(TURBULENT_ENERGY_DISSIPATION_RATE) = 11.90;
}
void RansEvmKEpsilonVmsMonolithicWall2D2N_AssignTestData(ModelPart& rModelPart)
{
rModelPart.GetProcessInfo()[TURBULENCE_RANS_C_MU] = 0.09;
rModelPart.GetProcessInfo()[TURBULENT_ENERGY_DISSIPATION_RATE_SIGMA] = 1.3;
auto& node1 = rModelPart.GetNode(1);
node1.FastGetSolutionStepValue(KINEMATIC_VISCOSITY) = 0.24;
node1.FastGetSolutionStepValue(TURBULENT_ENERGY_DISSIPATION_RATE) = 12.90;
node1.FastGetSolutionStepValue(TURBULENT_KINETIC_ENERGY) = 25.90;
node1.FastGetSolutionStepValue(TURBULENT_VISCOSITY) = 1.29;
node1.FastGetSolutionStepValue(RANS_Y_PLUS) = 8.34;
node1.FastGetSolutionStepValue(VELOCITY_X) = -1.85;
node1.FastGetSolutionStepValue(VELOCITY_Y) = -2.15;
node1.FastGetSolutionStepValue(PRESSURE) = -5.15;
node1.FastGetSolutionStepValue(DISTANCE) = 2.15;
node1.FastGetSolutionStepValue(VISCOSITY) = 5e-2;
node1.FastGetSolutionStepValue(DENSITY) = 2.3;
auto& node2 = rModelPart.GetNode(2);
node2.FastGetSolutionStepValue(KINEMATIC_VISCOSITY) = 0.28;
node2.FastGetSolutionStepValue(TURBULENT_ENERGY_DISSIPATION_RATE) = 5.00;
node2.FastGetSolutionStepValue(TURBULENT_KINETIC_ENERGY) = 5.00;
node2.FastGetSolutionStepValue(TURBULENT_VISCOSITY) = 1.04;
node2.FastGetSolutionStepValue(RANS_Y_PLUS) = 25.2;
node2.FastGetSolutionStepValue(VELOCITY_X) = -0.78;
node2.FastGetSolutionStepValue(VELOCITY_Y) = -0.06;
node2.FastGetSolutionStepValue(PRESSURE) = -4.15;
node2.FastGetSolutionStepValue(DISTANCE) = 8.15;
node2.FastGetSolutionStepValue(VISCOSITY) = 5e-2;
node1.FastGetSolutionStepValue(DENSITY) = 4.3;
}
void RansEvmKEpsilonVmsMonolithicWall2D2N_EvaluateTest(
std::function<void(Condition&, const ProcessInfo&, const bool, const bool)> TestEvaluationMethod)
{
// Setup:
Model model;
auto& model_part = model.CreateModelPart("test");
RansEvmKEpsilonVmsMonolithicWall2D2N_SetUp(model_part);
RansEvmKEpsilonVmsMonolithicWall2D2N_AssignTestData(model_part);
auto& r_condition = model_part.Conditions().front();
auto& r_process_info = model_part.GetProcessInfo();
auto permutated_evaluation_method =
[TestEvaluationMethod](Condition& rCondition, ProcessInfo& rProcessInfo,
const bool IsSlip, const bool IsCoSolvingProcessActive) {
rCondition.Set(SLIP, IsSlip);
rCondition.GetGeometry()[0].Set(SLIP, IsSlip);
rCondition.GetGeometry()[1].Set(SLIP, IsSlip);
rProcessInfo[IS_CO_SOLVING_PROCESS_ACTIVE] = IsCoSolvingProcessActive;
TestEvaluationMethod(rCondition, rProcessInfo, IsSlip, IsCoSolvingProcessActive);
};
permutated_evaluation_method(r_condition, r_process_info, false, false);
permutated_evaluation_method(r_condition, r_process_info, false, true);
permutated_evaluation_method(r_condition, r_process_info, true, false);
permutated_evaluation_method(r_condition, r_process_info, true, true);
}
void RansEvmKEpsilonEpsilonWall2D2N_EvaluateTest(
std::function<void(Condition&, ProcessInfo&, const bool)> TestEvaluationMethod)
{
// Setup:
Model model;
auto& model_part = model.CreateModelPart("test");
RansEvmKEpsilonEpsilonWall2D2N_SetUp(model_part);
RansEvmKEpsilonEpsilonWall2D2N_AssignTestData(model_part);
auto& r_condition = model_part.Conditions().front();
auto& r_process_info = model_part.GetProcessInfo();
auto permutated_evaluation_method =
[TestEvaluationMethod](Condition& rCondition, ProcessInfo& rProcessInfo,
const bool IsSlip) {
rCondition.Set(SLIP, IsSlip);
rCondition.GetGeometry()[0].Set(SLIP, IsSlip);
rCondition.GetGeometry()[1].Set(SLIP, IsSlip);
TestEvaluationMethod(rCondition, rProcessInfo, IsSlip);
};
permutated_evaluation_method(r_condition, r_process_info, false);
permutated_evaluation_method(r_condition, r_process_info, true);
}
} // namespace
KRATOS_TEST_CASE_IN_SUITE(RansEvmKEpsilonEpsilonWall2D2N_EquationIdVector, KratosRansFastSuite)
{
auto evaluation_method = [](Condition& rCondition,
ProcessInfo& rProcessInfo, const bool IsSlip) {
auto eqn_ids = std::vector<std::size_t>{};
rCondition.EquationIdVector(eqn_ids, rProcessInfo);
KRATOS_CHECK_EQUAL(eqn_ids.size(), rCondition.GetGeometry().PointsNumber());
for (std::size_t i = 0; i < eqn_ids.size(); ++i)
{
KRATOS_CHECK_EQUAL(eqn_ids[i], i + 1);
}
};
RansEvmKEpsilonEpsilonWall2D2N_EvaluateTest(evaluation_method);
}
KRATOS_TEST_CASE_IN_SUITE(RansEvmKEpsilonEpsilonWall2D2N_GetDofList, KratosRansFastSuite)
{
auto evaluation_method = [](Condition& rCondition,
ProcessInfo& rProcessInfo, const bool IsSlip) {
auto dofs = Element::DofsVectorType{};
rCondition.GetDofList(dofs, rProcessInfo);
KRATOS_CHECK_EQUAL(dofs.size(), rCondition.GetGeometry().PointsNumber());
for (std::size_t i = 0; i < dofs.size(); ++i)
{
KRATOS_CHECK_EQUAL(dofs[i]->GetVariable(), TURBULENT_ENERGY_DISSIPATION_RATE);
KRATOS_CHECK_EQUAL(dofs[i]->EquationId(), i + 1);
}
};
RansEvmKEpsilonEpsilonWall2D2N_EvaluateTest(evaluation_method);
}
KRATOS_TEST_CASE_IN_SUITE(RansEvmKEpsilonEpsilonWall2D2N_CalculateLocalSystem, KratosRansFastSuite)
{
auto evaluation_method = [](Condition& rCondition,
ProcessInfo& rProcessInfo, const bool IsSlip) {
Matrix LHS;
Vector RHS;
rCondition.CalculateLocalSystem(LHS, RHS, rProcessInfo);
KRATOS_CHECK_VECTOR_EQUAL(RHS, ZeroVector(2));
KRATOS_CHECK_MATRIX_EQUAL(LHS, ZeroMatrix(2, 2));
};
RansEvmKEpsilonEpsilonWall2D2N_EvaluateTest(evaluation_method);
}
KRATOS_TEST_CASE_IN_SUITE(RansEvmKEpsilonEpsilonWall2D2N_CalculateRightHandSide, KratosRansFastSuite)
{
auto evaluation_method = [](Condition& rCondition,
ProcessInfo& rProcessInfo, const bool IsSlip) {
Vector RHS;
rCondition.CalculateRightHandSide(RHS, rProcessInfo);
KRATOS_CHECK_VECTOR_EQUAL(RHS, ZeroVector(2));
};
RansEvmKEpsilonEpsilonWall2D2N_EvaluateTest(evaluation_method);
}
KRATOS_TEST_CASE_IN_SUITE(RansEvmKEpsilonEpsilonWall2D2N_CalculateLocalVelocityContribution,
KratosRansFastSuite)
{
auto evaluation_method = [](Condition& rCondition,
ProcessInfo& rProcessInfo, const bool IsSlip) {
Matrix LHS;
Vector RHS;
rCondition.CalculateLocalVelocityContribution(LHS, RHS, rProcessInfo);
if (IsSlip)
{
Matrix ref_LHS(2, 2);
ref_LHS(0, 0) = -8.8842866931915732e-01;
ref_LHS(0, 1) = -3.5618553499123140e-01;
ref_LHS(1, 0) = -3.5618553499123140e-01;
ref_LHS(1, 1) = -5.3631347064576806e-01;
Vector ref_RHS(2);
ref_RHS[0] = 1.8364623708570253e+01;
ref_RHS[1] = 1.2045480307045217e+01;
KRATOS_CHECK_VECTOR_NEAR(RHS, ref_RHS, 1e-12);
KRATOS_CHECK_MATRIX_NEAR(LHS, ref_LHS, 1e-12);
}
else
{
KRATOS_CHECK_VECTOR_EQUAL(RHS, ZeroVector(2));
KRATOS_CHECK_MATRIX_EQUAL(LHS, ZeroMatrix(2, 2));
}
};
RansEvmKEpsilonEpsilonWall2D2N_EvaluateTest(evaluation_method);
}
KRATOS_TEST_CASE_IN_SUITE(RansEvmKEpsilonEpsilonWall2D2N_CalculateMassMatrix, KratosRansFastSuite)
{
auto evaluation_method = [](Condition& rCondition,
ProcessInfo& rProcessInfo, const bool IsSlip) {
Matrix M;
rCondition.CalculateMassMatrix(M, rProcessInfo);
KRATOS_CHECK_EQUAL(M.size1(), 0);
KRATOS_CHECK_EQUAL(M.size2(), 0);
};
RansEvmKEpsilonEpsilonWall2D2N_EvaluateTest(evaluation_method);
}
KRATOS_TEST_CASE_IN_SUITE(RansEvmKEpsilonEpsilonWall2D2N_CalculateDampingMatrix, KratosRansFastSuite)
{
auto evaluation_method = [](Condition& rCondition,
ProcessInfo& rProcessInfo, const bool IsSlip) {
Matrix LHS;
rCondition.CalculateDampingMatrix(LHS, rProcessInfo);
if (IsSlip)
{
Matrix ref_LHS(2, 2);
ref_LHS(0, 0) = -8.8842866931915732e-01;
ref_LHS(0, 1) = -3.5618553499123140e-01;
ref_LHS(1, 0) = -3.5618553499123140e-01;
ref_LHS(1, 1) = -5.3631347064576806e-01;
KRATOS_CHECK_MATRIX_NEAR(LHS, ref_LHS, 1e-12);
}
else
{
KRATOS_CHECK_MATRIX_EQUAL(LHS, ZeroMatrix(2, 2));
}
};
RansEvmKEpsilonEpsilonWall2D2N_EvaluateTest(evaluation_method);
}
KRATOS_TEST_CASE_IN_SUITE(RansEvmKEpsilonVmsMonolithicWall2D2N_CalculateLocalSystem, KratosRansFastSuite)
{
auto evaluation_method = [](Condition& rCondition, const ProcessInfo& rProcessInfo,
const bool IsSlip, const bool IsCoSolvingProcessActive) {
Matrix LHS;
Vector RHS;
rCondition.CalculateLocalSystem(LHS, RHS, rProcessInfo);
KRATOS_CHECK_VECTOR_EQUAL(RHS, ZeroVector(6));
KRATOS_CHECK_MATRIX_EQUAL(LHS, ZeroMatrix(6, 6));
};
RansEvmKEpsilonVmsMonolithicWall2D2N_EvaluateTest(evaluation_method);
}
KRATOS_TEST_CASE_IN_SUITE(RansEvmKEpsilonVmsMonolithicWall2D2N_CalculateLocalVelocityContribution,
KratosRansFastSuite)
{
auto evaluation_method = [](Condition& rCondition, const ProcessInfo& rProcessInfo,
const bool IsSlip, const bool IsCoSolvingProcessActive) {
Matrix LHS;
Vector RHS;
rCondition.CalculateLocalVelocityContribution(LHS, RHS, rProcessInfo);
if (!IsSlip)
{
KRATOS_CHECK_VECTOR_EQUAL(RHS, ZeroVector(6));
KRATOS_CHECK_MATRIX_EQUAL(LHS, ZeroMatrix(6, 6));
}
else if (IsSlip && !IsCoSolvingProcessActive)
{
Matrix ref_LHS(6, 6);
ref_LHS.clear();
ref_LHS(0, 0) = 9.9785637332056212e-02;
ref_LHS(1, 1) = 9.9785637332056212e-02;
Vector ref_RHS(6);
ref_RHS.clear();
ref_RHS[0] = 1.8460342906430399e-01;
ref_RHS[1] = 2.1453912026392086e-01;
KRATOS_CHECK_VECTOR_NEAR(RHS, ref_RHS, 1e-12);
KRATOS_CHECK_MATRIX_NEAR(LHS, ref_LHS, 1e-12);
}
else if (IsSlip && IsCoSolvingProcessActive)
{
Matrix ref_LHS(6, 6);
ref_LHS.clear();
ref_LHS(0, 0) = 5.8700089206809922e+00;
ref_LHS(0, 3) = 1.9261013323368170e+00;
ref_LHS(1, 1) = 5.8700089206809922e+00;
ref_LHS(1, 4) = 1.9261013323368170e+00;
ref_LHS(3, 0) = 1.9261013323368170e+00;
ref_LHS(3, 3) = 1.8343964086662754e+00;
ref_LHS(4, 1) = 1.9261013323368170e+00;
ref_LHS(4, 4) = 1.8343964086662754e+00;
Vector ref_RHS(6);
ref_RHS.clear();
ref_RHS[0] = 1.2361875542482554e+01;
ref_RHS[1] = 1.2736085259404343e+01;
ref_RHS[3] = 4.9941166635828065e+00;
ref_RHS[4] = 4.2511816490441330e+00;
KRATOS_CHECK_VECTOR_NEAR(RHS, ref_RHS, 1e-12);
KRATOS_CHECK_MATRIX_NEAR(LHS, ref_LHS, 1e-12);
}
};
RansEvmKEpsilonVmsMonolithicWall2D2N_EvaluateTest(evaluation_method);
}
KRATOS_TEST_CASE_IN_SUITE(RansEvmKEpsilonVmsMonolithicWall2D2N_CalculateMassMatrix, KratosRansFastSuite)
{
auto evaluation_method = [](Condition& rCondition, const ProcessInfo& rProcessInfo,
const bool IsSlip, const bool IsCoSolvingProcessActive) {
Matrix M;
rCondition.CalculateMassMatrix(M, rProcessInfo);
KRATOS_CHECK_EQUAL(M.size1(), 0);
KRATOS_CHECK_EQUAL(M.size2(), 0);
};
RansEvmKEpsilonVmsMonolithicWall2D2N_EvaluateTest(evaluation_method);
}
KRATOS_TEST_CASE_IN_SUITE(RansEvmKEpsilonVmsMonolithicWall2D2N_CalculateDampingMatrix, KratosRansFastSuite)
{
auto evaluation_method = [](Condition& rCondition, const ProcessInfo& rProcessInfo,
const bool IsSlip, const bool IsCoSolvingProcessActive) {
Matrix LHS;
rCondition.CalculateDampingMatrix(LHS, rProcessInfo);
if (!IsSlip)
{
KRATOS_CHECK_MATRIX_EQUAL(LHS, ZeroMatrix(6, 6));
}
else if (IsSlip && !IsCoSolvingProcessActive)
{
Matrix ref_LHS(6, 6);
ref_LHS.clear();
ref_LHS(0, 0) = 9.9785637332056212e-02;
ref_LHS(1, 1) = 9.9785637332056212e-02;
KRATOS_CHECK_MATRIX_NEAR(LHS, ref_LHS, 1e-12);
}
else if (IsSlip && IsCoSolvingProcessActive)
{
Matrix ref_LHS(6, 6);
ref_LHS.clear();
ref_LHS(0, 0) = 5.8700089206809922e+00;
ref_LHS(0, 3) = 1.9261013323368170e+00;
ref_LHS(1, 1) = 5.8700089206809922e+00;
ref_LHS(1, 4) = 1.9261013323368170e+00;
ref_LHS(3, 0) = 1.9261013323368170e+00;
ref_LHS(3, 3) = 1.8343964086662754e+00;
ref_LHS(4, 1) = 1.9261013323368170e+00;
ref_LHS(4, 4) = 1.8343964086662754e+00;
KRATOS_CHECK_MATRIX_NEAR(LHS, ref_LHS, 1e-12);
}
};
RansEvmKEpsilonVmsMonolithicWall2D2N_EvaluateTest(evaluation_method);
}
} // namespace Testing
} // namespace Kratos.
| 40.713987 | 107 | 0.673931 | [
"vector",
"model",
"3d"
] |
916b6e16787f44c8a040c43082861da9b1f729ab | 16,905 | hpp | C++ | Cbc/Clp/src/CbcOrClpParam.hpp | fadi-alkhoury/coin-or-cbc-with-cmake | b4a216118d8e773b694b44c5f27cd75a251cc2cb | [
"MIT"
] | null | null | null | Cbc/Clp/src/CbcOrClpParam.hpp | fadi-alkhoury/coin-or-cbc-with-cmake | b4a216118d8e773b694b44c5f27cd75a251cc2cb | [
"MIT"
] | null | null | null | Cbc/Clp/src/CbcOrClpParam.hpp | fadi-alkhoury/coin-or-cbc-with-cmake | b4a216118d8e773b694b44c5f27cd75a251cc2cb | [
"MIT"
] | null | null | null |
/* $Id: CbcOrClpParam.hpp 2389 2019-02-07 19:48:00Z unxusr $ */
// Copyright (C) 2002, International Business Machines
// Corporation and others. All Rights Reserved.
// This code is licensed under the terms of the Eclipse Public License (EPL).
#ifdef USE_CBCCONFIG
#include "CbcConfig.h"
#else
#include "ClpConfig.h"
#endif
#ifndef CbcOrClpParam_H
#define CbcOrClpParam_H
/**
This has parameter handling stuff which can be shared between Cbc and Clp (and Dylp etc).
This (and .cpp) should be copied so that it is the same in Cbc/Test and Clp/Test.
I know this is not elegant but it seems simplest.
It uses COIN_HAS_CBC for parameters wanted by CBC
It uses COIN_HAS_CLP for parameters wanted by CLP (or CBC using CLP)
It could use COIN_HAS_DYLP for parameters wanted by DYLP
It could use COIN_HAS_DYLP_OR_CLP for parameters wanted by DYLP or CLP etc etc
*/
class OsiSolverInterface;
class CbcModel;
class ClpSimplex;
/*! \brief Parameter codes
Parameter type ranges are allocated as follows
<ul>
<li> 1 -- 100 double parameters
<li> 101 -- 200 integer parameters
<li> 201 -- 250 string parameters
<li> 251 -- 300 cuts etc(string but broken out for clarity)
<li> 301 -- 400 `actions'
</ul>
`Actions' do not necessarily invoke an immediate action; it's just that they
don't fit neatly into the parameters array.
This coding scheme is in flux.
*/
enum CbcOrClpParameterType
{
CBC_PARAM_GENERALQUERY = -100,
CBC_PARAM_FULLGENERALQUERY,
CLP_PARAM_DBL_PRIMALTOLERANCE = 1,
CLP_PARAM_DBL_DUALTOLERANCE,
CLP_PARAM_DBL_TIMELIMIT,
CLP_PARAM_DBL_DUALBOUND,
CLP_PARAM_DBL_PRIMALWEIGHT,
CLP_PARAM_DBL_OBJSCALE,
CLP_PARAM_DBL_RHSSCALE,
CLP_PARAM_DBL_ZEROTOLERANCE,
CLP_PARAM_DBL_PSI,
CBC_PARAM_DBL_INFEASIBILITYWEIGHT = 51,
CBC_PARAM_DBL_CUTOFF,
CBC_PARAM_DBL_INTEGERTOLERANCE,
CBC_PARAM_DBL_INCREMENT,
CBC_PARAM_DBL_ALLOWABLEGAP,
CBC_PARAM_DBL_TIMELIMIT_BAB,
CBC_PARAM_DBL_GAPRATIO,
CBC_PARAM_DBL_DJFIX = 81,
CBC_PARAM_DBL_TIGHTENFACTOR,
CLP_PARAM_DBL_PRESOLVETOLERANCE,
CLP_PARAM_DBL_OBJSCALE2,
CBC_PARAM_DBL_FAKEINCREMENT,
CBC_PARAM_DBL_FAKECUTOFF,
CBC_PARAM_DBL_ARTIFICIALCOST,
CBC_PARAM_DBL_DEXTRA3,
CBC_PARAM_DBL_SMALLBAB,
CBC_PARAM_DBL_DEXTRA4,
CBC_PARAM_DBL_DEXTRA5,
CLP_PARAM_INT_SOLVERLOGLEVEL = 101,
#ifndef COIN_HAS_CBC
CLP_PARAM_INT_LOGLEVEL = 101,
#endif
CLP_PARAM_INT_MAXFACTOR,
CLP_PARAM_INT_PERTVALUE,
CLP_PARAM_INT_MAXITERATION,
CLP_PARAM_INT_PRESOLVEPASS,
CLP_PARAM_INT_IDIOT,
CLP_PARAM_INT_SPRINT,
CLP_PARAM_INT_OUTPUTFORMAT,
CLP_PARAM_INT_SLPVALUE,
CLP_PARAM_INT_PRESOLVEOPTIONS,
CLP_PARAM_INT_PRINTOPTIONS,
CLP_PARAM_INT_SPECIALOPTIONS,
CLP_PARAM_INT_SUBSTITUTION,
CLP_PARAM_INT_DUALIZE,
CLP_PARAM_INT_VERBOSE,
CLP_PARAM_INT_CPP,
CLP_PARAM_INT_PROCESSTUNE,
CLP_PARAM_INT_USESOLUTION,
CLP_PARAM_INT_RANDOMSEED,
CLP_PARAM_INT_MORESPECIALOPTIONS,
CLP_PARAM_INT_DECOMPOSE_BLOCKS,
CLP_PARAM_INT_VECTOR_MODE,
CBC_PARAM_INT_STRONGBRANCHING = 151,
CBC_PARAM_INT_CUTDEPTH,
CBC_PARAM_INT_MAXNODES,
CBC_PARAM_INT_NUMBERBEFORE,
CBC_PARAM_INT_NUMBERANALYZE,
CBC_PARAM_INT_MIPOPTIONS,
CBC_PARAM_INT_MOREMIPOPTIONS,
CBC_PARAM_INT_MAXHOTITS,
CBC_PARAM_INT_FPUMPITS,
CBC_PARAM_INT_MAXSOLS,
CBC_PARAM_INT_FPUMPTUNE,
CBC_PARAM_INT_TESTOSI,
CBC_PARAM_INT_EXTRA1,
CBC_PARAM_INT_EXTRA2,
CBC_PARAM_INT_EXTRA3,
CBC_PARAM_INT_EXTRA4,
CBC_PARAM_INT_DEPTHMINIBAB,
CBC_PARAM_INT_CUTPASSINTREE,
CBC_PARAM_INT_THREADS,
CBC_PARAM_INT_CUTPASS,
CBC_PARAM_INT_VUBTRY,
CBC_PARAM_INT_DENSE,
CBC_PARAM_INT_EXPERIMENT,
CBC_PARAM_INT_DIVEOPT,
CBC_PARAM_INT_DIVEOPTSOLVES,
CBC_PARAM_INT_STRATEGY,
CBC_PARAM_INT_SMALLFACT,
CBC_PARAM_INT_HOPTIONS,
CBC_PARAM_INT_CUTLENGTH,
CBC_PARAM_INT_FPUMPTUNE2,
#ifdef COIN_HAS_CBC
CLP_PARAM_INT_LOGLEVEL,
#endif
CBC_PARAM_INT_MAXSAVEDSOLS,
CBC_PARAM_INT_RANDOMSEED,
CBC_PARAM_INT_MULTIPLEROOTS,
CBC_PARAM_INT_STRONG_STRATEGY,
CBC_PARAM_INT_EXTRA_VARIABLES,
CBC_PARAM_INT_MAX_SLOW_CUTS,
CBC_PARAM_INT_MOREMOREMIPOPTIONS,
CLP_PARAM_STR_DIRECTION = 201,
CLP_PARAM_STR_DUALPIVOT,
CLP_PARAM_STR_SCALING,
CLP_PARAM_STR_ERRORSALLOWED,
CLP_PARAM_STR_KEEPNAMES,
CLP_PARAM_STR_SPARSEFACTOR,
CLP_PARAM_STR_PRIMALPIVOT,
CLP_PARAM_STR_PRESOLVE,
CLP_PARAM_STR_CRASH,
CLP_PARAM_STR_BIASLU,
CLP_PARAM_STR_PERTURBATION,
CLP_PARAM_STR_MESSAGES,
CLP_PARAM_STR_AUTOSCALE,
CLP_PARAM_STR_CHOLESKY,
CLP_PARAM_STR_KKT,
CLP_PARAM_STR_BARRIERSCALE,
CLP_PARAM_STR_GAMMA,
CLP_PARAM_STR_CROSSOVER,
CLP_PARAM_STR_PFI,
CLP_PARAM_STR_INTPRINT,
CLP_PARAM_STR_VECTOR,
CLP_PARAM_STR_FACTORIZATION,
CLP_PARAM_STR_ALLCOMMANDS,
CLP_PARAM_STR_TIME_MODE,
CLP_PARAM_STR_ABCWANTED,
CLP_PARAM_STR_BUFFER_MODE,
CBC_PARAM_STR_NODESTRATEGY = 301,
CBC_PARAM_STR_BRANCHSTRATEGY,
CBC_PARAM_STR_CUTSSTRATEGY,
CBC_PARAM_STR_HEURISTICSTRATEGY,
CBC_PARAM_STR_GOMORYCUTS,
CBC_PARAM_STR_PROBINGCUTS,
CBC_PARAM_STR_KNAPSACKCUTS,
CBC_PARAM_STR_REDSPLITCUTS,
CBC_PARAM_STR_ROUNDING,
CBC_PARAM_STR_SOLVER,
CBC_PARAM_STR_CLIQUECUTS,
CBC_PARAM_STR_COSTSTRATEGY,
CBC_PARAM_STR_FLOWCUTS,
CBC_PARAM_STR_MIXEDCUTS,
CBC_PARAM_STR_TWOMIRCUTS,
CBC_PARAM_STR_PREPROCESS,
CBC_PARAM_STR_FPUMP,
CBC_PARAM_STR_GREEDY,
CBC_PARAM_STR_COMBINE,
CBC_PARAM_STR_PROXIMITY,
CBC_PARAM_STR_LOCALTREE,
CBC_PARAM_STR_SOS,
CBC_PARAM_STR_LANDPCUTS,
CBC_PARAM_STR_RINS,
CBC_PARAM_STR_RESIDCUTS,
CBC_PARAM_STR_RENS,
CBC_PARAM_STR_DIVINGS,
CBC_PARAM_STR_DIVINGC,
CBC_PARAM_STR_DIVINGF,
CBC_PARAM_STR_DIVINGG,
CBC_PARAM_STR_DIVINGL,
CBC_PARAM_STR_DIVINGP,
CBC_PARAM_STR_DIVINGV,
CBC_PARAM_STR_DINS,
CBC_PARAM_STR_PIVOTANDFIX,
CBC_PARAM_STR_RANDROUND,
CBC_PARAM_STR_NAIVE,
CBC_PARAM_STR_ZEROHALFCUTS,
CBC_PARAM_STR_CPX,
CBC_PARAM_STR_CROSSOVER2,
CBC_PARAM_STR_PIVOTANDCOMPLEMENT,
CBC_PARAM_STR_VND,
CBC_PARAM_STR_LAGOMORYCUTS,
CBC_PARAM_STR_LATWOMIRCUTS,
CBC_PARAM_STR_REDSPLIT2CUTS,
CBC_PARAM_STR_GMICUTS,
CBC_PARAM_STR_CUTOFF_CONSTRAINT,
CBC_PARAM_STR_DW,
CBC_PARAM_STR_ORBITAL,
CBC_PARAM_STR_PREPROCNAMES,
CBC_PARAM_STR_SOSPRIORITIZE,
CLP_PARAM_ACTION_DIRECTORY = 401,
CLP_PARAM_ACTION_DIRSAMPLE,
CLP_PARAM_ACTION_DIRNETLIB,
CBC_PARAM_ACTION_DIRMIPLIB,
CLP_PARAM_ACTION_IMPORT,
CLP_PARAM_ACTION_EXPORT,
CLP_PARAM_ACTION_RESTORE,
CLP_PARAM_ACTION_SAVE,
CLP_PARAM_ACTION_DUALSIMPLEX,
CLP_PARAM_ACTION_PRIMALSIMPLEX,
CLP_PARAM_ACTION_EITHERSIMPLEX,
CLP_PARAM_ACTION_MAXIMIZE,
CLP_PARAM_ACTION_MINIMIZE,
CLP_PARAM_ACTION_EXIT,
CLP_PARAM_ACTION_STDIN,
CLP_PARAM_ACTION_UNITTEST,
CLP_PARAM_ACTION_NETLIB_EITHER,
CLP_PARAM_ACTION_NETLIB_DUAL,
CLP_PARAM_ACTION_NETLIB_PRIMAL,
CLP_PARAM_ACTION_SOLUTION,
CLP_PARAM_ACTION_SAVESOL,
CLP_PARAM_ACTION_TIGHTEN,
CLP_PARAM_ACTION_FAKEBOUND,
CLP_PARAM_ACTION_HELP,
CLP_PARAM_ACTION_PLUSMINUS,
CLP_PARAM_ACTION_NETWORK,
CLP_PARAM_ACTION_ALLSLACK,
CLP_PARAM_ACTION_REVERSE,
CLP_PARAM_ACTION_BARRIER,
CLP_PARAM_ACTION_NETLIB_BARRIER,
CLP_PARAM_ACTION_NETLIB_TUNE,
CLP_PARAM_ACTION_REALLY_SCALE,
CLP_PARAM_ACTION_BASISIN,
CLP_PARAM_ACTION_BASISOUT,
CLP_PARAM_ACTION_SOLVECONTINUOUS,
CLP_PARAM_ACTION_CLEARCUTS,
CLP_PARAM_ACTION_VERSION,
CLP_PARAM_ACTION_STATISTICS,
CLP_PARAM_ACTION_DEBUG,
CLP_PARAM_ACTION_DUMMY,
CLP_PARAM_ACTION_PRINTMASK,
CLP_PARAM_ACTION_OUTDUPROWS,
CLP_PARAM_ACTION_USERCLP,
CLP_PARAM_ACTION_MODELIN,
CLP_PARAM_ACTION_CSVSTATISTICS,
CLP_PARAM_ACTION_STOREDFILE,
CLP_PARAM_ACTION_ENVIRONMENT,
CLP_PARAM_ACTION_PARAMETRICS,
CLP_PARAM_ACTION_GMPL_SOLUTION,
CLP_PARAM_ACTION_RESTORESOL,
CLP_PARAM_ACTION_GUESS,
CBC_PARAM_ACTION_BAB = 501,
CBC_PARAM_ACTION_MIPLIB,
CBC_PARAM_ACTION_STRENGTHEN,
CBC_PARAM_ACTION_PRIORITYIN,
CBC_PARAM_ACTION_MIPSTART,
CBC_PARAM_ACTION_USERCBC,
CBC_PARAM_ACTION_DOHEURISTIC,
CLP_PARAM_ACTION_NEXTBESTSOLUTION,
CBC_PARAM_NOTUSED_OSLSTUFF = 601,
CBC_PARAM_NOTUSED_CBCSTUFF,
CBC_PARAM_NOTUSED_INVALID = 1000
};
#include <vector>
#include <string>
/// Very simple class for setting parameters
class CbcOrClpParam {
public:
/**@name Constructor and destructor */
//@{
/// Constructors
CbcOrClpParam();
CbcOrClpParam(std::string name, std::string help,
double lower, double upper, CbcOrClpParameterType type, int display = 2);
CbcOrClpParam(std::string name, std::string help,
int lower, int upper, CbcOrClpParameterType type, int display = 2);
// Other strings will be added by insert
CbcOrClpParam(std::string name, std::string help, std::string firstValue,
CbcOrClpParameterType type, int whereUsed = 7, int display = 2);
// Action
CbcOrClpParam(std::string name, std::string help,
CbcOrClpParameterType type, int whereUsed = 7, int display = 2);
/// Copy constructor.
CbcOrClpParam(const CbcOrClpParam &);
/// Assignment operator. This copies the data
CbcOrClpParam &operator=(const CbcOrClpParam &rhs);
/// Destructor
~CbcOrClpParam();
//@}
/**@name stuff */
//@{
/// Insert string (only valid for keywords)
void append(std::string keyWord);
/// Adds one help line
void addHelp(std::string keyWord);
/// Returns name
inline std::string name() const
{
return name_;
}
/// Returns short help
inline std::string shortHelp() const
{
return shortHelp_;
}
/// Sets a double parameter (nonzero code if error)
int setDoubleParameter(CbcModel &model, double value);
/// Sets double parameter and returns printable string and error code
const char *setDoubleParameterWithMessage(CbcModel &model, double value, int &returnCode);
/// Gets a double parameter
double doubleParameter(CbcModel &model) const;
/// Sets a int parameter (nonzero code if error)
int setIntParameter(CbcModel &model, int value);
/// Sets int parameter and returns printable string and error code
const char *setIntParameterWithMessage(CbcModel &model, int value, int &returnCode);
/// Gets a int parameter
int intParameter(CbcModel &model) const;
/// Sets a double parameter (nonzero code if error)
int setDoubleParameter(ClpSimplex *model, double value);
/// Gets a double parameter
double doubleParameter(ClpSimplex *model) const;
/// Sets double parameter and returns printable string and error code
const char *setDoubleParameterWithMessage(ClpSimplex *model, double value, int &returnCode);
/// Sets a int parameter (nonzero code if error)
int setIntParameter(ClpSimplex *model, int value);
/// Sets int parameter and returns printable string and error code
const char *setIntParameterWithMessage(ClpSimplex *model, int value, int &returnCode);
/// Gets a int parameter
int intParameter(ClpSimplex *model) const;
/// Sets a double parameter (nonzero code if error)
int setDoubleParameter(OsiSolverInterface *model, double value);
/// Sets double parameter and returns printable string and error code
const char *setDoubleParameterWithMessage(OsiSolverInterface *model, double value, int &returnCode);
/// Gets a double parameter
double doubleParameter(OsiSolverInterface *model) const;
/// Sets a int parameter (nonzero code if error)
int setIntParameter(OsiSolverInterface *model, int value);
/// Sets int parameter and returns printable string and error code
const char *setIntParameterWithMessage(OsiSolverInterface *model, int value, int &returnCode);
/// Gets a int parameter
int intParameter(OsiSolverInterface *model) const;
/// Checks a double parameter (nonzero code if error)
int checkDoubleParameter(double value) const;
/// Returns name which could match
std::string matchName() const;
/// Returns length of name for ptinting
int lengthMatchName() const;
/// Returns parameter option which matches (-1 if none)
int parameterOption(std::string check) const;
/// Prints parameter options
void printOptions() const;
/// Returns current parameter option
inline std::string currentOption() const
{
return definedKeyWords_[currentKeyWord_];
}
/// Sets current parameter option
void setCurrentOption(int value, bool printIt = false);
/// Sets current parameter option and returns printable string
const char *setCurrentOptionWithMessage(int value);
/// Sets current parameter option using string
void setCurrentOption(const std::string value);
/// Sets current parameter option using string with message
const char *setCurrentOptionWithMessage(const std::string value);
/// Returns current parameter option position
int currentOptionAsInteger() const;
/** Returns current parameter option position
but if fake keyword returns a fake value and sets
fakeInteger to true value. If not fake then fakeInteger is -COIN_INT_MAX
*/
int currentOptionAsInteger(int &fakeInteger) const;
/// Sets int value
void setIntValue(int value);
/// Sets int value with message
const char *setIntValueWithMessage(int value);
inline int intValue() const
{
return intValue_;
}
/// Sets double value
void setDoubleValue(double value);
/// Sets double value with message
const char *setDoubleValueWithMessage(double value);
inline double doubleValue() const
{
return doubleValue_;
}
/// Sets string value
void setStringValue(std::string value);
inline std::string stringValue() const
{
return stringValue_;
}
/// Returns 1 if matches minimum, 2 if matches less, 0 if not matched
int matches(std::string input) const;
/// type
inline CbcOrClpParameterType type() const
{
return type_;
}
/// whether to display
inline int displayThis() const
{
return display_;
}
/// Set Long help
inline void setLonghelp(const std::string help)
{
longHelp_ = help;
}
/// Print Long help
void printLongHelp() const;
/// Print action and string
void printString() const;
/** 7 if used everywhere,
1 - used by clp
2 - used by cbc
4 - used by ampl
*/
inline int whereUsed() const
{
return whereUsed_;
}
/// Gets value of fake keyword
inline int fakeKeyWord() const
{
return fakeKeyWord_;
}
/// Sets value of fake keyword
inline void setFakeKeyWord(int value, int fakeValue)
{
fakeKeyWord_ = value;
fakeValue_ = fakeValue;
}
/// Sets value of fake keyword to current size of keywords
void setFakeKeyWord(int fakeValue);
private:
/// gutsOfConstructor
void gutsOfConstructor();
//@}
////////////////// data //////////////////
private:
/**@name data
We might as well throw all type data in - could derive?
*/
//@{
// Type see CbcOrClpParameterType
CbcOrClpParameterType type_;
/// If double == okay
double lowerDoubleValue_;
double upperDoubleValue_;
/// If int == okay
int lowerIntValue_;
int upperIntValue_;
// Length of name
unsigned int lengthName_;
// Minimum match
unsigned int lengthMatch_;
/// set of valid strings
std::vector< std::string > definedKeyWords_;
/// Name
std::string name_;
/// Short help
std::string shortHelp_;
/// Long help
std::string longHelp_;
/// Action
CbcOrClpParameterType action_;
/// Current keyWord (if a keyword parameter)
int currentKeyWord_;
/// Display on ?
int display_;
/// Integer parameter - current value
int intValue_;
/// Double parameter - current value
double doubleValue_;
/// String parameter - current value
std::string stringValue_;
/** 7 if used everywhere,
1 - used by clp
2 - used by cbc
4 - used by ampl
*/
int whereUsed_;
/** If >=0 then integers allowed as a fake keyword
So minusnnnn would got to -nnnn in currentKeyword_
and plusnnnn would go to fakeKeyword_+nnnn
*/
int fakeKeyWord_;
/// Return this as main value if an integer
int fakeValue_;
//@}
};
/// Simple read stuff
std::string CoinReadNextField();
std::string CoinReadGetCommand(int argc, const char *argv[]);
std::string CoinReadGetString(int argc, const char *argv[]);
// valid 0 - okay, 1 bad, 2 not there
int CoinReadGetIntField(int argc, const char *argv[], int *valid);
double CoinReadGetDoubleField(int argc, const char *argv[], int *valid);
void CoinReadPrintit(const char *input);
void setCbcOrClpPrinting(bool yesNo);
#define CBCMAXPARAMETERS 250
/*
Subroutine to establish the cbc parameter array. See the description of
class CbcOrClpParam for details. Pulled from C..Main() for clarity.
*/
void establishParams(std::vector< CbcOrClpParam > ¶ms);
// Given a parameter type - returns its number in list
int whichParam(const CbcOrClpParameterType &name,
const std::vector< CbcOrClpParam > ¶meters);
// Dump/restore a solution to file
void saveSolution(const ClpSimplex *lpSolver, std::string fileName);
void restoreSolution(ClpSimplex *lpSolver, std::string fileName, int mode);
#endif /* CbcOrClpParam_H */
/* vi: softtabstop=2 shiftwidth=2 expandtab tabstop=2
*/
| 30.459459 | 102 | 0.770305 | [
"vector",
"model"
] |
9176703788e0ecf4adcdbac6afae85a0ebccc3c4 | 3,031 | hpp | C++ | Tareas/T1_II_3/include/VecR3.hpp | Mohs9/Lab-Avanzado | af4073b0706a0279df4c31ca493162e3b5465461 | [
"MIT"
] | null | null | null | Tareas/T1_II_3/include/VecR3.hpp | Mohs9/Lab-Avanzado | af4073b0706a0279df4c31ca493162e3b5465461 | [
"MIT"
] | null | null | null | Tareas/T1_II_3/include/VecR3.hpp | Mohs9/Lab-Avanzado | af4073b0706a0279df4c31ca493162e3b5465461 | [
"MIT"
] | null | null | null | /*
* VecR3.hpp: Definicion de la clase VecR3
*
* Tarea para el curso de laboratorio Avanzado
*
* Rubí Esmeralda Ramírez Milián
*
*/
#ifndef __VECR3_HPP__
#define __VECR3_HPP__
#include <iostream>
#include <string>
/* Clase VecR3: Vectores en R3. Internamente
* se representa en forma cartesiana. */
class VecR3
{
private:
/* Coordenada x */
float Xcor;
/* Coordenada y */
float Ycor;
/* Coordenada z*/
float Zcor;
/* Atributo de clase: Indica si el despliege del
* vector seran en coordenas polares. */
static bool Esfericas;
public:
/* Constructor sin argumentos */
VecR3();
/* Constructor con argumentos */
VecR3( float valor_x, float valor_y, float valor_z );
/* Destructor */
~VecR3();
/* Metodos de asignacion (set methods) */
/* Asigna la coordenada x */
void Asignar_x( float valor_x );
/* Asigna la coordenada y */
void Asignar_y( float valor_y );
/* Asigna la coordenada y */
void Asignar_z( float valor_z );
/* Asigna las coordenadas x, y */
void Asignar_xyz( float valor_x, float valor_y, float valor_z );
/* Metodos de obtencion (get methods)
* El calificador const al final del prototipo
* indica que estos metodos no van a alterar
* los valores de la instancia que los llama. */
/* Obtener la coordenada x */
float Obtener_x( ) const;
/* Obtener la coordenada y */
float Obtener_y( ) const;
/* Obtener la coordenada x */
float Obtener_z( ) const;
/* Otros metodos */
/* Devuelve la magnitud del vector */
float Magnitud() const;
/* Sobrecarga de operadores
* El calificador const en el argumento impide
* que el argumento del operador pueda ser modificado
* dentro del metodo. */
/* Calcula la suma de dos vectores */
VecR3 operator+( const VecR3 & ) const;
/* Calcula la suma de dos vectores */
VecR3 operator-( const VecR3 & ) const;
/* Calcula el producto punto de dos vectores */
float operator*( const VecR3 & ) const;
/* Calcula la multiplicación de un vector por un escalar */
//VecR3 operator_escalar( const VecR3 & ) const;
/* Calcula el producto cruz de dos vectores */
VecR3 operator%( const VecR3 & ) ;
/* Operador de asignacion */
VecR3 operator=( const VecR3 & );
/* Operador de comparación de igualdad entre vectores*/
int operator==( const VecR3 & );
/* Metodo de clase: Fija el valor del flag para que
* el despliege del vector sea en polar (true) o
* cartesiano (false) */
static void Mostar_Esfericas( bool valor );
/* Funciones amigas */
/* Despliega un vector con cout */
friend std::ostream &operator<<( std::ostream &, const VecR3 & );
/* Multiplica un flotante por un vector */
friend VecR3 operator*( const float &, const VecR3 & );
/* Calcula la división de un vector por un escalar */
friend VecR3 operator/( const float &, const VecR3 & );
};
#endif /* __VECR3_HPP__ */ | 27.807339 | 69 | 0.642692 | [
"vector"
] |
9177cfc7fdf8e68145cbec711f6db4586340dccc | 1,982 | hpp | C++ | include/geometry/io/gplotly_actor.hpp | hyperpower/CarpioPlus | 68cc6c976d6c3ba6adec847a94c344be3f4690aa | [
"MIT"
] | null | null | null | include/geometry/io/gplotly_actor.hpp | hyperpower/CarpioPlus | 68cc6c976d6c3ba6adec847a94c344be3f4690aa | [
"MIT"
] | 1 | 2018-06-18T03:52:56.000Z | 2018-06-18T03:52:56.000Z | include/geometry/io/gplotly_actor.hpp | hyperpower/CarpioPlus | 68cc6c976d6c3ba6adec847a94c344be3f4690aa | [
"MIT"
] | null | null | null | #ifndef _GEOMETRY_PLOTLY_ACTOR_HPP_
#define _GEOMETRY_PLOTLY_ACTOR_HPP_
#include "geometry/geometry_define.hpp"
#include <array>
#include "geometry/objects/objects.hpp"
#include "io/plotly.hpp"
#include <memory>
#include <cmath>
namespace carpio {
using namespace PlotlyActor;
template<typename TYPE, St DIM>
class GPlotlyActor_ {
public:
static const St Dim = DIM;
typedef TYPE Vt;
typedef Point_<TYPE, DIM> Point;
typedef Point_<TYPE, DIM>& ref_Point;
typedef const Point_<TYPE, DIM>& const_ref_Point;
typedef Segment_<TYPE, DIM> Segment;
typedef Segment_<TYPE, DIM>& ref_Segment;
typedef const Segment_<TYPE, DIM>& const_ref_Segment;
typedef std::shared_ptr<Plotly_actor> spPA;
typedef std::shared_ptr<Plotly_actor_scatter> spPA_scatter;
typedef std::shared_ptr<Plotly_actor_scatter3d> spPA_scatter3d;
typedef std::shared_ptr<Plotly_actor_mesh3d> spPA_mesh3d;
typedef std::list<double> Listd;
template<class ContainerSegment>
static spPA_scatter LinesPoints(
const ContainerSegment& con,
const Segment& dummy) {
Listd lx;
Listd ly;
for (auto& seg : con) {
lx.push_back(seg.psx());
ly.push_back(seg.psy());
lx.push_back(seg.pex());
ly.push_back(seg.pey());
}
spPA_scatter res = spPA_scatter(new Plotly_actor_scatter(lx, ly, 2));
res->set_mode("lines+markers");
return res;
}
template<class ContainerSegment>
static spPA_scatter LinesPoints(
const ContainerSegment& con,
Segment* dummy) {
Listd lx;
Listd ly;
for (auto& seg : con) {
lx.push_back(seg->psx());
ly.push_back(seg->psy());
lx.push_back(seg->pex());
ly.push_back(seg->pey());
}
spPA_scatter res = spPA_scatter(new Plotly_actor_scatter(lx, ly, 2));
res->set_mode("lines+markers");
return res;
}
// template<class ContainerSegment>
// static spPA_scatter LinesPoints(
// const ContainerSegment& con,
// Point dummy = typename ContainerSegment::value_type()){
// std::cout << "Point";
// return nullptr;
// }
};
}
#endif
| 24.170732 | 71 | 0.726034 | [
"geometry"
] |
917b7ce7e3aad9041eab45b4d4ad40b8088dc7a9 | 3,849 | cpp | C++ | dev/test/so_5/coop/user_resource/main.cpp | ZaMaZaN4iK/sobjectizer | afe9fc4d9fac6157860ec4459ac7a129223be87c | [
"BSD-3-Clause"
] | null | null | null | dev/test/so_5/coop/user_resource/main.cpp | ZaMaZaN4iK/sobjectizer | afe9fc4d9fac6157860ec4459ac7a129223be87c | [
"BSD-3-Clause"
] | 1 | 2019-10-09T06:43:08.000Z | 2019-10-09T06:43:08.000Z | dev/test/so_5/coop/user_resource/main.cpp | ZaMaZaN4iK/sobjectizer | afe9fc4d9fac6157860ec4459ac7a129223be87c | [
"BSD-3-Clause"
] | null | null | null | /*
* A test for deallocating user resources.
*/
#include <iostream>
#include <sstream>
#include <so_5/all.hpp>
#include <test/3rd_party/various_helpers/time_limited_execution.hpp>
struct sequence_holder_t
{
typedef std::vector< int > vec_t;
vec_t m_sequence;
};
const int ID_COOP = 1;
const int ID_RESOURCE = 2;
const int ID_AGENT = 3;
struct resource_t
{
sequence_holder_t & m_holder;
resource_t( sequence_holder_t & holder )
: m_holder( holder )
{}
~resource_t()
{
m_holder.m_sequence.push_back( ID_RESOURCE );
}
};
class a_test_t : public so_5::agent_t
{
typedef so_5::agent_t base_type_t;
public :
a_test_t(
so_5::environment_t & env,
resource_t & resource )
: base_type_t( env )
, m_resource( resource )
{
}
~a_test_t()
{
m_resource.m_holder.m_sequence.push_back( ID_AGENT );
}
void
so_evt_start()
{
so_deregister_agent_coop_normally();
}
private :
resource_t & m_resource;
};
class test_agent_coop_t
: public so_5::coop_t
{
typedef so_5::coop_t base_type_t;
public :
test_agent_coop_t(
so_5::coop_id_t id,
so_5::coop_handle_t parent_coop,
so_5::disp_binder_shptr_t coop_disp_binder,
so_5::environment_t & env,
sequence_holder_t & sequence )
: base_type_t{
id,
std::move(parent_coop),
std::move(coop_disp_binder),
so_5::outliving_mutable(env) }
, m_sequence( sequence )
{}
~test_agent_coop_t()
{
m_sequence.m_sequence.push_back( ID_COOP );
}
private :
sequence_holder_t & m_sequence;
};
class a_test_starter_t : public so_5::agent_t
{
typedef so_5::agent_t base_type_t;
public :
a_test_starter_t(
so_5::environment_t & env,
sequence_holder_t & sequence )
: base_type_t( env )
, m_sequence( sequence )
, m_self_mbox( env.create_mbox() )
{}
void
so_define_agent()
{
so_subscribe( m_self_mbox ).event(
&a_test_starter_t::evt_child_destroyed );
}
void
so_evt_start()
{
so_5::coop_unique_holder_t coop(
so_5::coop_shptr_t{
new test_agent_coop_t(
1234567u,
so_coop(),
so_5::make_default_disp_binder( so_environment() ),
so_environment(),
m_sequence )
} );
coop->add_dereg_notificator(
so_5::make_coop_dereg_notificator( m_self_mbox ) );
resource_t * r = coop->take_under_control(
std::make_unique< resource_t >( m_sequence ) );
coop->make_agent< a_test_t >( *r );
so_environment().register_coop( std::move( coop ) );
}
void
evt_child_destroyed(
mhood_t< so_5::msg_coop_deregistered > )
{
so_environment().stop();
}
private :
sequence_holder_t & m_sequence;
const so_5::mbox_t m_self_mbox;
};
std::string
sequence_to_string( const std::vector< int > & s )
{
std::ostringstream out;
for( auto i = s.begin(); i != s.end(); ++i )
{
if( i != s.begin() )
out << ", ";
out << *i;
}
return out.str();
}
class test_env_t
{
public :
void
init( so_5::environment_t & env )
{
env.register_agent_as_coop(
env.make_agent< a_test_starter_t >( m_sequence ) );
}
void
check_result() const
{
sequence_holder_t::vec_t expected1{ ID_COOP, ID_AGENT, ID_RESOURCE };
sequence_holder_t::vec_t expected2{ ID_AGENT, ID_RESOURCE, ID_COOP };
if( m_sequence.m_sequence != expected1 &&
m_sequence.m_sequence != expected2 )
throw std::runtime_error( "Wrong deinit sequence:\n"
"actual: " + sequence_to_string( m_sequence.m_sequence )
+ "\n" "expected1: " + sequence_to_string( expected1 ) +
"\n" "expected2: " + sequence_to_string( expected2 ) );
}
private :
sequence_holder_t m_sequence;
};
int
main()
{
run_with_time_limit( [] {
test_env_t test_env;
so_5::launch(
[&]( so_5::environment_t & env ) {
test_env.init( env );
} );
test_env.check_result();
},
10 );
return 0;
}
| 18.77561 | 72 | 0.663549 | [
"vector"
] |
917c3fc6e5193c9866da082473502a372d64b52f | 2,289 | hpp | C++ | src/Graphics/GraphicsDevice.hpp | ariabonczek/NewLumina | f35cf7f449cfbe191e03e1d5f1c9973cc0b44a8e | [
"MIT"
] | 2 | 2017-01-08T21:30:45.000Z | 2017-01-16T10:10:12.000Z | src/Graphics/GraphicsDevice.hpp | ariabonczek/NewLumina | f35cf7f449cfbe191e03e1d5f1c9973cc0b44a8e | [
"MIT"
] | null | null | null | src/Graphics/GraphicsDevice.hpp | ariabonczek/NewLumina | f35cf7f449cfbe191e03e1d5f1c9973cc0b44a8e | [
"MIT"
] | null | null | null | //--------------------------------------
// LuminaEngine belongs to Aria Bonczek
//--------------------------------------
#ifndef GRAPHICSDEVICE_HPP
#define GRAPHICSDEVICE_HPP
#include <Core\Common.hpp>
#include <Config.hpp>
NS_BEGIN
class Window;
#if DX11
struct DisplayBuffer
{
ID3D11Texture2D* depthBuffer;
ID3D11RenderTargetView* renderTargetView;
ID3D11DepthStencilView* depthStencilView;
};
#elif DX12
#endif
/// <summary>
/// Renderer's handle to the graphics context
/// </summary>
class GraphicsDevice
{
friend class ResourceManager;
public:
GraphicsDevice();
~GraphicsDevice();
/// <summary>
/// Initializes GraphicsDevice subsystems
/// </summary>
void Initialize(Window* window);
/// <summary>
/// Shuts down GraphicsDevice subsystems
/// </summary>
void Shutdown();
/// <summary>
/// Resets command lists and clears the render target
/// </summary>
void ResetCommandList();
/// <summary>
/// Closes the current command list to prevent further adding of draw calls
/// </summary>
void CloseCommandList();
/// <summary>
/// Executes the commands in the list
/// </summary>
void ExecuteCommandList();
/// <summary>
/// Called when the window is resized to handle recreation of back buffer and viewport
/// </summary>
void OnResize();
private:
Window* window;
#if DX11
// DirectX11 Interfaces
ID3D11Device* dev;
ID3D11DeviceContext* immCon;
ID3D11DeviceContext* defCon[2];
ID3D11CommandList* commandList;
uint32 contextIndex; // Points the the context currently storing draw calls
IDXGISwapChain3* swapChain;
DisplayBuffer displayBuffers[NUM_BUFFERS];
D3D11_VIEWPORT viewport;
D3D_FEATURE_LEVEL featureLevel;
uint32 frameIndex;
#elif DX12
// DirectX12 Interfaces
ID3D12Device* dev;
IDXGISwapChain3* swapChain;
ID3D12CommandQueue* commandQueue;
ID3D12CommandAllocator* commandAllocator[2];
ID3D12DescriptorHeap* rtvHeap;
ID3D12Resource* renderTarget[NUM_BUFFERS];
ID3D12RootSignature* rootSignature;
ID3D12PipelineState* pipelineState;
ID3D12GraphicsCommandList* commandList[2];
uint32 commandIndex;
uint32 executeIndex;
D3D12_VIEWPORT viewport;
uint32 descriptorSize;
uint32 frameIndex;
// Synchronization
HANDLE fenceEvent;
ID3D12Fence* fence;
uint64 fenceValue;
#elif GL43
#endif
};
NS_END
#endif | 21 | 87 | 0.732197 | [
"render"
] |
9181c20788b02d2fbb24a298d5f2e925ed88692b | 2,219 | cpp | C++ | core/src/render/geometry.cpp | TerraGraphics/TerraEngine | 874165a22ab7dd3774a6cfdeb023485a552d9860 | [
"Apache-2.0"
] | 5 | 2019-12-24T21:43:13.000Z | 2020-06-16T03:44:16.000Z | core/src/render/geometry.cpp | TerraGraphics/TerraEngine | 874165a22ab7dd3774a6cfdeb023485a552d9860 | [
"Apache-2.0"
] | null | null | null | core/src/render/geometry.cpp | TerraGraphics/TerraEngine | 874165a22ab7dd3774a6cfdeb023485a552d9860 | [
"Apache-2.0"
] | 1 | 2020-03-30T00:17:27.000Z | 2020-03-30T00:17:27.000Z | #include "core/render/geometry.h"
#include "dg/context.h"
#include "dg/graphics_types.h"
#include "core/render/index_buffer.h"
#include "core/render/vertex_buffer.h"
Geometry::Geometry(uint16_t vDeclId)
: m_vDeclId(vDeclId) {
}
Geometry::~Geometry() {
}
GeometryUnindexed::GeometryUnindexed(const std::shared_ptr<VertexBuffer>& vb, uint32_t vbOffsetBytes, uint32_t vbCount, uint16_t vDeclId)
: Geometry(vDeclId)
, m_vertexBuffer(vb)
, m_vertexBufferOffsetBytes(vbOffsetBytes)
, m_vertexBufferCount(vbCount) {
}
GeometryUnindexed::~GeometryUnindexed() {
}
void GeometryUnindexed::Bind(ContextPtr& context) {
m_vertexBuffer->Bind(context, m_vertexBufferOffsetBytes);
}
uint32_t GeometryUnindexed::Draw(ContextPtr& context, uint32_t firstInstanceIndex) {
dg::DrawAttribs drawAttrs;
drawAttrs.NumVertices = m_vertexBufferCount;
drawAttrs.FirstInstanceLocation = firstInstanceIndex;
drawAttrs.Flags = dg::DRAW_FLAG_VERIFY_ALL;
context->Draw(drawAttrs);
// TODO: fix for not triangle
return m_vertexBufferCount / 3;
}
GeometryIndexed::GeometryIndexed(const std::shared_ptr<VertexBuffer>& vb, uint32_t vbOffsetBytes,
const std::shared_ptr<IndexBuffer>& ib, uint32_t ibOffsetBytes, uint32_t ibCount, bool ibUint32, uint16_t vDeclId)
: Geometry(vDeclId)
, m_vertexBuffer(vb)
, m_indexBuffer(ib)
, m_vertexBufferOffsetBytes(vbOffsetBytes)
, m_indexBufferOffsetBytes(ibOffsetBytes)
, m_indexBufferCount(ibCount)
, m_indexBufferUint32(ibUint32) {
}
GeometryIndexed::~GeometryIndexed() {
}
void GeometryIndexed::Bind(ContextPtr& context) {
m_vertexBuffer->Bind(context, m_vertexBufferOffsetBytes);
m_indexBuffer->Bind(context, m_indexBufferOffsetBytes);
}
uint32_t GeometryIndexed::Draw(ContextPtr& context, uint32_t firstInstanceIndex) {
dg::DrawIndexedAttribs drawAttrs;
drawAttrs.IndexType = m_indexBufferUint32 ? dg::VT_UINT32 : dg::VT_UINT16;
drawAttrs.NumIndices = m_indexBufferCount;
drawAttrs.FirstInstanceLocation = firstInstanceIndex;
drawAttrs.Flags = dg::DRAW_FLAG_VERIFY_ALL;
context->DrawIndexed(drawAttrs);
// TODO: fix for not triangle
return m_indexBufferCount / 3;
}
| 28.088608 | 137 | 0.75845 | [
"geometry",
"render"
] |
9182020c9f3cc180b9e6a9521a261e7ab50e0ad3 | 41,032 | cpp | C++ | bson.cpp | mongodb-labs/mongo-hhvm-driver | 382df3e6fb5bf3454fd8aadf24617c039afafd08 | [
"Apache-2.0"
] | 30 | 2015-10-26T07:08:21.000Z | 2022-01-21T00:02:31.000Z | bson.cpp | mongodb/mongo-hhvm-driver | 382df3e6fb5bf3454fd8aadf24617c039afafd08 | [
"Apache-2.0"
] | 111 | 2015-10-29T13:22:45.000Z | 2021-12-22T15:37:10.000Z | bson.cpp | mongodb-labs/mongo-hhvm-driver-prototype | 382df3e6fb5bf3454fd8aadf24617c039afafd08 | [
"Apache-2.0"
] | 16 | 2015-11-11T18:41:54.000Z | 2021-03-02T10:56:10.000Z | /**
* Copyright 2015 MongoDB, Inc.
*
* 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 "hphp/runtime/vm/native-data.h"
#include "hphp/runtime/base/array-init.h"
#include "hphp/runtime/base/array-iterator.h"
#include "hphp/runtime/base/builtin-functions.h"
#include "hphp/runtime/base/execution-context.h"
#include "hphp/runtime/base/type-string.h"
#include "hphp/util/logger.h"
#include "bson.h"
#include "utils.h"
#include "mongodb.h"
#include <iostream>
#include "src/MongoDB/BSON/Binary.h"
#include "src/MongoDB/BSON/Decimal128.h"
#include "src/MongoDB/BSON/Javascript.h"
#include "src/MongoDB/BSON/ObjectID.h"
#include "src/MongoDB/BSON/Regex.h"
#include "src/MongoDB/BSON/Timestamp.h"
#include "src/MongoDB/BSON/UTCDateTime.h"
#include "src/MongoDB/Driver/CursorId.h"
extern "C" {
#include "libbson/src/bson/bson.h"
#include "libmongoc/src/mongoc/mongoc.h"
}
namespace HPHP {
/* {{{ HHVM → BSON */
/* {{{ static strings used for conversions */
const StaticString
s_root("root"),
s_document("document"),
s_object("object"),
s_stdClass("stdClass"),
s_array("array"),
s_types("types");
/* }}} */
int VariantToBsonConverter::_isPackedArray(const Array &a)
{
int idx = 0, key_value = 0;
for (ArrayIter iter(a); iter; ++iter) {
Variant key(iter.first());
if (!key.isInteger()) {
return false;
}
key_value = key.toInt32();
if (idx != key_value) {
return false;
}
idx++;
}
return true;
}
VariantToBsonConverter::VariantToBsonConverter(const Variant& document, int flags)
{
m_document = document;
m_level = 0;
m_flags = flags;
m_out = Variant();
}
void VariantToBsonConverter::convert(bson_t *bson)
{
if (m_document.isObject() || m_document.isArray()) {
convertDocument(bson, NULL, m_document);
} else {
std::cout << "convert *unimplemented*: " << getDataTypeString(m_document.getType()).c_str() << "\n";
}
}
const StaticString s_MongoBSONTypeWrapper_className("MongoDB\\BSON\\TypeWrapper");
const StaticString s_MongoBSONTypeWrapper_createFromBSONType("createFromBSONType");
const StaticString s_MongoBSONTypeWrapper_toBSONType("toBSONType");
void VariantToBsonConverter::convertElement(bson_t *bson, const char *key, Variant v)
{
/* We need to check whether it is a type wrapped object (ie, the class
* implements TypeWrapper). If so, run the toBSONType() method on the
* object. The returned value then needs to be processed as normal. */
if (v.isObject() && v.toObject().instanceof(s_MongoBSONTypeWrapper_className)) {
Object obj = v.toObject();
Class *cls = obj.get()->getVMClass();
Func *m = cls->lookupMethod(s_MongoBSONTypeWrapper_toBSONType.get());
TypedValue args[0] = {};
Variant result;
#if HIPPO_HHVM_VERSION >= 31700
result = Variant::attach(
g_context->invokeFuncFew(
m, obj.get(),
nullptr, 0, args
)
);
#else
g_context->invokeFuncFew(
result.asTypedValue(),
m, obj.get(),
nullptr, 0, args
);
#endif
v = result;
}
switch (v.getType()) {
case KindOfUninit:
case KindOfNull:
convertNull(bson, key);
break;
case KindOfBoolean:
convertBoolean(bson, key, v.toBoolean());
break;
case KindOfInt64:
convertInt64(bson, key, v.toInt64());
break;
case KindOfDouble:
convertDouble(bson, key, v.toDouble());
break;
#if HIPPO_HHVM_VERSION >= 31200
case KindOfPersistentString:
#else
case KindOfStaticString:
#endif
case KindOfString:
convertString(bson, key, v.toString());
break;
case KindOfArray:
#if HIPPO_HHVM_VERSION >= 31100
case KindOfPersistentArray:
#endif
case KindOfObject:
convertDocument(bson, key, v);
break;
case KindOfRef:
convertElement(bson, key, *v.getRefData());
break;
#if HIPPO_HHVM_VERSION >= 31700
case KindOfPersistentVec:
case KindOfPersistentDict:
case KindOfPersistentKeyset:
case KindOfVec:
case KindOfDict:
case KindOfKeyset:
#endif
case KindOfResource: {
StringBuffer buf;
buf.printf(
"Got unsupported type '%s'",
HPHP::getDataTypeString(v.getType()).data()
);
Variant message = buf.detach();
throw MongoDriver::Utils::throwUnexpectedValueException((char*) message.toString().c_str());
return;
}
#if HIPPO_HHVM_VERSION < 31900
case KindOfClass:
not_reached();
#endif
}
}
void VariantToBsonConverter::convertNull(bson_t *bson, const char *key)
{
bson_append_null(bson, key, -1);
};
void VariantToBsonConverter::convertBoolean(bson_t *bson, const char *key, bool v)
{
bson_append_bool(bson, key, -1, v);
};
void VariantToBsonConverter::convertInt64(bson_t *bson, const char *key, int64_t v)
{
if (v > INT_MAX || v < INT_MIN) {
bson_append_int64(bson, key, -1, v);
} else {
bson_append_int32(bson, key, -1, (int32_t) v);
}
};
void VariantToBsonConverter::convertDouble(bson_t *bson, const char *key, double v)
{
bson_append_double(bson, key, -1, v);
};
void VariantToBsonConverter::convertString(bson_t *bson, const char *key, String v)
{
if (bson_utf8_validate(v.c_str(), v.size(), true)) {
bson_append_utf8(bson, key, -1, v.c_str(), v.size());
} else {
throw MongoDriver::Utils::throwUnexpectedValueException("Got invalid UTF-8 value serializing '" + String(v.c_str()) + "'");
}
}
char *VariantToBsonConverter::_getUnmangledPropertyName(String key)
{
const char *ckey = key.c_str();
if (ckey[0] == '\0' && key.length()) {
const char *cls = ckey + 1;
if (*cls == '*') { // protected
return strdup(ckey + 3);
} else {
int l = strlen(cls);
return strdup(cls + l + 1);
}
} else {
return strdup(ckey);
}
}
void VariantToBsonConverter::convertDocument(bson_t *bson, const char *property_name, Variant v)
{
bson_t child;
int unmangle = 0;
Array document;
/* if we are not at a top-level, we need to check (and convert) special
* BSON types too */
if (v.isObject()) {
if (convertSpecialObject(bson, property_name, v.toObject())) {
return;
}
/* The "convertSpecialObject" method didn't understand this type, so we
* will continue treating this as a normal document */
}
document = v.toObject()->o_toIterArray(null_string, ObjectData::PreserveRefs);
if (_isPackedArray(document) && !v.isObject()) {
if (property_name != NULL) {
bson_append_array_begin(bson, property_name, -1, &child);
}
} else {
unmangle = 1;
if (property_name != NULL) {
bson_append_document_begin(bson, property_name, -1, &child);
}
}
for (ArrayIter iter(document); iter; ++iter) {
Variant key(iter.first());
const Variant& data(iter.secondRef());
String s_key = key.toString();
if (m_level == 0 && (m_flags & HIPPO_BSON_ADD_ID)) {
/* If we have an ID, we don't need to add it. But we also need to
* set m_out to the value! */
if (strncmp(s_key.c_str(), "_id", s_key.length()) == 0) {
m_flags &= ~HIPPO_BSON_ADD_ID;
if (m_flags & HIPPO_BSON_RETURN_ID) {
/* FIXME: Should we add a ref here? */
m_out = data;
}
}
}
m_level++;
if (unmangle) {
const char *unmangledName;
unmangledName = _getUnmangledPropertyName(s_key);
if (strlen(s_key.c_str()) != s_key.size()) {
free((void*) unmangledName);
throw MongoDriver::Utils::throwUnexpectedValueException("BSON keys cannot contain null bytes. Unexpected null byte after \"" + String(s_key.c_str()) + "\".");
}
convertElement(property_name != NULL ? &child : bson, unmangledName, data);
free((void*) unmangledName);
} else {
if (strlen(s_key.c_str()) != s_key.size()) {
throw MongoDriver::Utils::throwUnexpectedValueException("BSON keys cannot contain null bytes. Unexpected null byte after \"" + String(s_key.c_str()) + "\".");
}
convertElement(property_name != NULL ? &child : bson, s_key.c_str(), data);
}
m_level--;
}
if (m_level == 0 && (m_flags & HIPPO_BSON_ADD_ID)) {
bson_oid_t oid;
bson_oid_init(&oid, NULL);
bson_append_oid(bson, "_id", strlen("_id"), &oid);
if (m_flags & HIPPO_BSON_RETURN_ID) {
Object obj = createMongoBsonObjectIDObject(&oid);
m_out = obj;
}
}
if (property_name != NULL) {
if (_isPackedArray(document)) {
bson_append_array_end(bson, &child);
} else {
bson_append_document_end(bson, &child);
}
}
}
/* {{{ Serialization of types */
const StaticString s_MongoDriverBsonType_className("MongoDB\\BSON\\Type");
const StaticString s_MongoDriverBsonPersistable_className("MongoDB\\BSON\\Persistable");
const StaticString s_MongoDriverBsonSerializable_className("MongoDB\\BSON\\Serializable");
const StaticString s_MongoDriverBsonUnserializable_className("MongoDB\\BSON\\Unserializable");
const StaticString s_MongoDriverBsonSerializable_functionName("bsonSerialize");
const StaticString s_MongoDriverBsonUnserializable_functionName("bsonUnserialize");
const StaticString s_MongoDriverBsonODM_fieldName("__pclass");
/* {{{ MongoDriver\BSON\Binary */
void VariantToBsonConverter::_convertBinary(bson_t *bson, const char *key, Object v)
{
String data = v.o_get(s_MongoBsonBinary_data, false, s_MongoBsonBinary_className).toString();
int64_t type = v.o_get(s_MongoBsonBinary_type, false, s_MongoBsonBinary_className).toInt64();
bson_append_binary(bson, key, -1, (bson_subtype_t) type, (const unsigned char*) data.c_str(), data.length());
}
/* }}} */
/* {{{ MongoDriver\BSON\Decimal128 */
void VariantToBsonConverter::_convertDecimal128(bson_t *bson, const char *key, Object v)
{
MongoDBBsonDecimal128Data* data = Native::data<MongoDBBsonDecimal128Data>(v.get());
bson_append_decimal128(bson, key, -1, &data->m_decimal);
}
/* }}} */
/* {{{ MongoDriver\BSON\Javascript */
void VariantToBsonConverter::_convertJavascript(bson_t *bson, const char *key, Object v)
{
bson_t *scope_bson;
String code = v.o_get(s_MongoBsonJavascript_code, false, s_MongoBsonJavascript_className).toString();
auto scope = v.o_get(s_MongoBsonJavascript_scope, false, s_MongoBsonJavascript_className);
if (scope.isObject() || scope.isArray()) {
/* Convert scope to document */
VariantToBsonConverter converter(scope, HIPPO_BSON_NO_FLAGS);
scope_bson = bson_new();
converter.convert(scope_bson);
bson_append_code_with_scope(bson, key, -1, (const char*) code.c_str(), scope_bson);
} else {
bson_append_code(bson, key, -1, (const char*) code.c_str());
}
}
/* }}} */
/* {{{ MongoDriver\BSON\MaxKey */
const StaticString s_MongoBsonMaxKey_className("MongoDB\\BSON\\MaxKey");
const StaticString s_MongoBsonMaxKey_shortName("MaxKey");
void VariantToBsonConverter::_convertMaxKey(bson_t *bson, const char *key, Object v)
{
bson_append_maxkey(bson, key, -1);
}
/* }}} */
/* {{{ MongoDriver\BSON\MinKey */
const StaticString s_MongoBsonMinKey_className("MongoDB\\BSON\\MinKey");
const StaticString s_MongoBsonMinKey_shortName("MinKey");
void VariantToBsonConverter::_convertMinKey(bson_t *bson, const char *key, Object v)
{
bson_append_minkey(bson, key, -1);
}
/* }}} */
/* {{{ MongoDriver\BSON\ObjectID */
void VariantToBsonConverter::_convertObjectID(bson_t *bson, const char *key, Object v)
{
MongoDBBsonObjectIDData* data = Native::data<MongoDBBsonObjectIDData>(v.get());
bson_append_oid(bson, key, -1, &data->m_oid);
}
/* }}} */
/* {{{ MongoDriver\BSON\Regex */
void VariantToBsonConverter::_convertRegex(bson_t *bson, const char *key, Object v)
{
String regex = v.o_get(s_MongoBsonRegex_pattern, false, s_MongoBsonRegex_className).toString();
String flags = v.o_get(s_MongoBsonRegex_flags, false, s_MongoBsonRegex_className).toString();
bson_append_regex(bson, key, -1, regex.c_str(), flags.c_str());
}
/* }}} */
/* {{{ MongoDriver\BSON\Timestamp */
void VariantToBsonConverter::_convertTimestamp(bson_t *bson, const char *key, Object v)
{
int32_t timestamp = v.o_get(s_MongoBsonTimestamp_timestamp, false, s_MongoBsonTimestamp_className).toInt32();
int32_t increment = v.o_get(s_MongoBsonTimestamp_increment, false, s_MongoBsonTimestamp_className).toInt32();
bson_append_timestamp(bson, key, -1, timestamp, increment);
}
/* {{{ MongoDriver\BSON\UTCDateTime */
void VariantToBsonConverter::_convertUTCDateTime(bson_t *bson, const char *key, Object v)
{
int64_t milliseconds = v.o_get(s_MongoBsonUTCDateTime_milliseconds, false, s_MongoBsonUTCDateTime_className).toInt64();
bson_append_date_time(bson, key, -1, milliseconds);
}
/* }}} */
/* {{{ MongoDriver\Driver\CursorId */
void VariantToBsonConverter::_convertCursorId(bson_t *bson, const char *key, Object v)
{
MongoDBDriverCursorIdData* data = Native::data<MongoDBDriverCursorIdData>(v.get());
bson_append_int64(bson, key, -1, data->id);
}
/* }}} */
/* {{{ Special objects that implement MongoDB\BSON\Serializable */
void VariantToBsonConverter::_convertSerializable(bson_t *bson, const char *key, Object v)
{
Variant result;
Array properties;
Class *cls;
Func *m;
cls = v.get()->getVMClass();
m = cls->lookupMethod(s_MongoDriverBsonSerializable_functionName.get());
#if HIPPO_HHVM_VERSION >= 31700
result = Variant::attach(
g_context->invokeFuncFew(
m,
v.get(),
nullptr
)
);
#else
g_context->invokeFuncFew(
result.asTypedValue(),
m,
v.get(),
nullptr
);
#endif
if ( ! (
result.isArray() ||
(result.isObject() && result.toObject().instanceof(s_stdClass))
)
) {
StringBuffer buf;
buf.printf(
"Expected %s::%s() to return an array or stdClass, %s given",
cls->nameStr().c_str(),
s_MongoDriverBsonSerializable_functionName.data(),
result.isObject() ? result.toObject()->getVMClass()->nameStr().c_str() : HPHP::getDataTypeString(result.getType()).data()
);
Variant full_name = buf.detach();
throw MongoDriver::Utils::throwUnexpectedValueException((char*) full_name.toString().c_str());
}
/* Convert to array so that we can handle it well */
properties = result.toArray();
if (v.instanceof(s_MongoDriverBsonPersistable_className)) {
const char *class_name = cls->nameStr().c_str();
Object obj = createMongoBsonBinaryObject(
(const uint8_t *) class_name,
strlen(class_name),
(bson_subtype_t) 0x80
);
properties.add(String(s_MongoDriverBsonODM_fieldName), obj);
}
convertDocument(bson, key, result.isObject() ? Variant(Variant(properties).toObject()) : Variant(properties));
}
/* }}} */
/* }}} */
bool VariantToBsonConverter::convertSpecialObject(bson_t *bson, const char *key, Object v)
{
if (v.instanceof(s_MongoDriverBsonType_className)) {
if (v.instanceof(s_MongoDriverBsonSerializable_className)) {
_convertSerializable(bson, key, v);
return true;
}
if (m_level == 0) {
throw MongoDriver::Utils::throwUnexpectedValueException("MongoDB\\BSON\\Type instance " + String(v->getClassName())+ " cannot be serialized as a root element");
}
if (v.instanceof(s_MongoBsonBinary_className)) {
_convertBinary(bson, key, v);
return true;
}
if (v.instanceof(s_MongoBsonDecimal128_className)) {
_convertDecimal128(bson, key, v);
return true;
}
if (v.instanceof(s_MongoBsonJavascript_className)) {
_convertJavascript(bson, key, v);
return true;
}
if (v.instanceof(s_MongoBsonMaxKey_className)) {
_convertMaxKey(bson, key, v);
return true;
}
if (v.instanceof(s_MongoBsonMinKey_className)) {
_convertMinKey(bson, key, v);
return true;
}
if (v.instanceof(s_MongoBsonObjectID_className)) {
_convertObjectID(bson, key, v);
return true;
}
if (v.instanceof(s_MongoBsonRegex_className)) {
_convertRegex(bson, key, v);
return true;
}
if (v.instanceof(s_MongoBsonTimestamp_className)) {
_convertTimestamp(bson, key, v);
return true;
}
if (v.instanceof(s_MongoBsonUTCDateTime_className)) {
_convertUTCDateTime(bson, key, v);
return true;
}
throw MongoDriver::Utils::throwUnexpectedValueException("Unexpected MongoDB\\BSON\\Type instance: " + String(v->getClassName()));
}
if (v.instanceof(s_MongoDriverCursorId_className)) {
_convertCursorId(bson, key, v);
return true;
}
return false;
}
/* }}} */
/* }}} */
/* {{{ BSON → HHVM */
BsonToVariantConverter::BsonToVariantConverter(const unsigned char *data, int data_len, hippo_bson_conversion_options_t options)
{
m_reader = bson_reader_new_from_data(data, data_len);
m_options = options;
}
/* {{{ TypeWrapping */
Variant wrapObject(String class_name, Object typeObject)
{
Variant result = invoke_static_method(class_name, s_MongoBSONTypeWrapper_createFromBSONType, Array::Create(typeObject));
return result;
}
/* }}} */
/* {{{ Visitors */
void hippo_bson_visit_corrupt(const bson_iter_t *iter __attribute__((unused)), void *data)
{
Logger::Verbose("[HIPPO] Corrupt BSON data detected!");
throw MongoDriver::Utils::throwUnexpectedValueException("Detected corrupt BSON data");
}
bool hippo_bson_visit_double(const bson_iter_t *iter __attribute__((unused)), const char *key, double v_double, void *data)
{
hippo_bson_state *state = (hippo_bson_state*) data;
state->zchild.add(String::FromCStr(key), Variant(v_double));
return false;
}
bool hippo_bson_visit_utf8(const bson_iter_t *iter __attribute__((unused)), const char *key, size_t v_utf8_len, const char *v_utf8, void *data)
{
hippo_bson_state *state = (hippo_bson_state*) data;
state->zchild.add(String::FromCStr(key), Variant(String::FromCStr(v_utf8)));
return false;
}
bool hippo_bson_visit_document(const bson_iter_t *iter __attribute__((unused)), const char *key, const bson_t *v_document, void *data)
{
hippo_bson_state *state = (hippo_bson_state*) data;
Variant document_v;
state->options.current_compound_type = HIPPO_BSONTYPE_DOCUMENT;
BsonToVariantConverter converter(bson_get_data(v_document), v_document->len, state->options);
converter.convert(&document_v);
state->zchild.add(String::FromCStr(key), document_v);
return false;
}
bool hippo_bson_visit_array(const bson_iter_t *iter __attribute__((unused)), const char *key, const bson_t *v_array, void *data)
{
hippo_bson_state *state = (hippo_bson_state*) data;
Variant array_v;
state->options.current_compound_type = HIPPO_BSONTYPE_ARRAY;
BsonToVariantConverter converter(bson_get_data(v_array), v_array->len, state->options);
converter.convert(&array_v);
state->zchild.add(String::FromCStr(key), array_v);
return false;
}
bool hippo_bson_visit_binary(const bson_iter_t *iter __attribute__((unused)), const char *key, bson_subtype_t v_subtype, size_t v_binary_len, const uint8_t *v_binary, void *data)
{
hippo_bson_state *state = (hippo_bson_state*) data;
Object obj;
obj = createMongoBsonBinaryObject(v_binary, v_binary_len, v_subtype);
if (! state->options.types.binary_class_name.empty()) {
/* We have a type wrapped class, so wrap it */
Variant result = wrapObject(state->options.types.binary_class_name, obj);
state->zchild.add(String::FromCStr(key), result);
} else {
state->zchild.add(String::FromCStr(key), Variant(obj));
}
return false;
}
bool hippo_bson_visit_oid(const bson_iter_t *iter __attribute__((unused)), const char *key, const bson_oid_t *v_oid, void *data)
{
hippo_bson_state *state = (hippo_bson_state*) data;
Object obj = createMongoBsonObjectIDObject(v_oid);
if (! state->options.types.objectid_class_name.empty()) {
/* We have a type wrapped class, so wrap it */
Variant result = wrapObject(state->options.types.objectid_class_name, obj);
state->zchild.add(String::FromCStr(key), result);
} else {
state->zchild.add(String::FromCStr(key), Variant(obj));
}
return false;
}
bool hippo_bson_visit_bool(const bson_iter_t *iter __attribute__((unused)), const char *key, bool v_bool, void *data)
{
hippo_bson_state *state = (hippo_bson_state*) data;
state->zchild.add(String::FromCStr(key), Variant(v_bool));
return false;
}
bool hippo_bson_visit_date_time(const bson_iter_t *iter __attribute__((unused)), const char *key, int64_t msec_since_epoch, void *data)
{
hippo_bson_state *state = (hippo_bson_state*) data;
static Class* c_datetime;
c_datetime = Unit::lookupClass(s_MongoBsonUTCDateTime_className.get());
assert(c_datetime);
Object obj = Object{c_datetime};
obj->o_set(s_MongoBsonUTCDateTime_milliseconds, Variant(msec_since_epoch), s_MongoBsonUTCDateTime_className);
if (! state->options.types.utcdatetime_class_name.empty()) {
/* We have a type wrapped class, so wrap it */
Variant result = wrapObject(state->options.types.utcdatetime_class_name, obj);
state->zchild.add(String::FromCStr(key), result);
} else {
state->zchild.add(String::FromCStr(key), Variant(obj));
}
return false;
}
bool hippo_bson_visit_null(const bson_iter_t *iter __attribute__((unused)), const char *key, void *data)
{
hippo_bson_state *state = (hippo_bson_state*) data;
state->zchild.add(String::FromCStr(key), Variant(Variant::NullInit()));
return false;
}
bool hippo_bson_visit_regex(const bson_iter_t *iter __attribute__((unused)), const char *key, const char *v_regex, const char *v_options, void *data)
{
hippo_bson_state *state = (hippo_bson_state*) data;
static Class* c_regex;
c_regex = Unit::lookupClass(s_MongoBsonRegex_className.get());
assert(c_regex);
Object obj = Object{c_regex};
/* Call __construct on the object */
static Class* c_class = Unit::getClass(s_MongoBsonRegex_className.get(), true);
#if HIPPO_HHVM_VERSION >= 31700
g_context->invokeFunc(
c_class->getCtor(),
HPHP::make_packed_array(v_regex, v_options),
obj.get()
);
#else
HPHP::TypedValue ret;
g_context->invokeFunc(
&ret,
c_class->getCtor(),
HPHP::make_packed_array(v_regex, v_options),
obj.get()
);
#endif
if (! state->options.types.regex_class_name.empty()) {
/* We have a type wrapped class, so wrap it */
Variant result = wrapObject(state->options.types.regex_class_name, obj);
state->zchild.add(String::FromCStr(key), result);
} else {
state->zchild.add(String::FromCStr(key), Variant(obj));
}
return false;
}
bool hippo_bson_visit_code(const bson_iter_t *iter __attribute__((unused)), const char *key, size_t v_code_len, const char *v_code, void *data)
{
hippo_bson_state *state = (hippo_bson_state*) data;
static Class* c_code;
String s;
unsigned char *data_s;
s = String(v_code_len, ReserveString);
data_s = (unsigned char*) s.bufferSlice().data();
memcpy(data_s, v_code, v_code_len);
s.setSize(v_code_len);
c_code = Unit::lookupClass(s_MongoBsonJavascript_className.get());
assert(c_code);
Object obj = Object{c_code};
obj->o_set(s_MongoBsonJavascript_code, s, s_MongoBsonJavascript_className);
if (! state->options.types.javascript_class_name.empty()) {
/* We have a type wrapped class, so wrap it */
Variant result = wrapObject(state->options.types.javascript_class_name, obj);
state->zchild.add(String::FromCStr(key), result);
} else {
state->zchild.add(String::FromCStr(key), Variant(obj));
}
return false;
}
bool hippo_bson_visit_codewscope(const bson_iter_t *iter __attribute__((unused)), const char *key, size_t v_code_len, const char *v_code, const bson_t *v_scope, void *data)
{
hippo_bson_state *state = (hippo_bson_state*) data;
static Class* c_code;
String s;
unsigned char *data_s;
Variant scope_v;
/* code */
s = String(v_code_len, ReserveString);
data_s = (unsigned char*) s.bufferSlice().data();
memcpy(data_s, v_code, v_code_len);
s.setSize(v_code_len);
/* scope */
BsonToVariantConverter converter(bson_get_data(v_scope), v_scope->len, state->options);
converter.convert(&scope_v);
/* create object */
c_code = Unit::lookupClass(s_MongoBsonJavascript_className.get());
assert(c_code);
Object obj = Object{c_code};
/* set properties */
obj->o_set(s_MongoBsonJavascript_code, s, s_MongoBsonJavascript_className);
obj->o_set(s_MongoBsonJavascript_scope, scope_v, s_MongoBsonJavascript_className);
/* add to array */
if (! state->options.types.javascript_class_name.empty()) {
/* We have a type wrapped class, so wrap it */
Variant result = wrapObject(state->options.types.javascript_class_name, obj);
state->zchild.add(String::FromCStr(key), result);
} else {
state->zchild.add(String::FromCStr(key), Variant(obj));
}
return false;
}
bool hippo_bson_visit_int32(const bson_iter_t *iter __attribute__((unused)), const char *key, int32_t v_int32, void *data)
{
hippo_bson_state *state = (hippo_bson_state*) data;
state->zchild.add(String::FromCStr(key), Variant(v_int32));
return false;
}
bool hippo_bson_visit_timestamp(const bson_iter_t *iter __attribute__((unused)), const char *key, uint32_t v_timestamp, uint32_t v_increment, void *data)
{
hippo_bson_state *state = (hippo_bson_state*) data;
static Class* c_timestamp;
c_timestamp = Unit::lookupClass(s_MongoBsonTimestamp_className.get());
assert(c_timestamp);
Object obj = Object{c_timestamp};
obj->o_set(s_MongoBsonTimestamp_timestamp, Variant((uint64_t) v_timestamp), s_MongoBsonTimestamp_className);
obj->o_set(s_MongoBsonTimestamp_increment, Variant((uint64_t) v_increment), s_MongoBsonTimestamp_className);
if (! state->options.types.timestamp_class_name.empty()) {
/* We have a type wrapped class, so wrap it */
Variant result = wrapObject(state->options.types.timestamp_class_name, obj);
state->zchild.add(String::FromCStr(key), result);
} else {
state->zchild.add(String::FromCStr(key), Variant(obj));
}
return false;
}
bool hippo_bson_visit_int64(const bson_iter_t *iter __attribute__((unused)), const char *key, int64_t v_int64, void *data)
{
hippo_bson_state *state = (hippo_bson_state*) data;
state->zchild.add(String::FromCStr(key), Variant(v_int64));
return false;
}
bool hippo_bson_visit_maxkey(const bson_iter_t *iter __attribute__((unused)), const char *key, void *data)
{
hippo_bson_state *state = (hippo_bson_state*) data;
static Class* c_objectId;
c_objectId = Unit::lookupClass(s_MongoBsonMaxKey_className.get());
assert(c_objectId);
Object obj = Object{c_objectId};
if (! state->options.types.maxkey_class_name.empty()) {
/* We have a type wrapped class, so wrap it */
Variant result = wrapObject(state->options.types.maxkey_class_name, obj);
state->zchild.add(String::FromCStr(key), result);
} else {
state->zchild.add(String::FromCStr(key), Variant(obj));
}
return false;
}
bool hippo_bson_visit_minkey(const bson_iter_t *iter __attribute__((unused)), const char *key, void *data)
{
hippo_bson_state *state = (hippo_bson_state*) data;
static Class* c_objectId;
c_objectId = Unit::lookupClass(s_MongoBsonMinKey_className.get());
assert(c_objectId);
Object obj = Object{c_objectId};
if (! state->options.types.minkey_class_name.empty()) {
/* We have a type wrapped class, so wrap it */
Variant result = wrapObject(state->options.types.minkey_class_name, obj);
state->zchild.add(String::FromCStr(key), result);
} else {
state->zchild.add(String::FromCStr(key), Variant(obj));
}
return false;
}
void hippo_bson_visit_unsupported_type(const bson_iter_t *iter __attribute__((unused)), const char *key, uint32_t v_type_code, void *data)
{
char *message;
message = (char*) malloc( 29 + 2 + 15 + strlen(key) + 35 + 1);
sprintf(message, "Detected unknown BSON type 0x%02hhx for fieldname \"%s\". Are you using the latest driver?", v_type_code, key);
throw MongoDriver::Utils::throwUnexpectedValueException(message);
}
bool hippo_bson_visit_decimal128(const bson_iter_t *iter __attribute__((unused)), const char *key, const bson_decimal128_t *v_decimal128, void *data)
{
hippo_bson_state *state = (hippo_bson_state*) data;
static Class* c_decimal128;
c_decimal128 = Unit::lookupClass(s_MongoBsonDecimal128_className.get());
assert(c_decimal128);
Object obj = Object{c_decimal128};
MongoDBBsonDecimal128Data* obj_data = Native::data<MongoDBBsonDecimal128Data>(obj);
memcpy(&obj_data->m_decimal, v_decimal128, sizeof(bson_decimal128_t));
if (! state->options.types.decimal128_class_name.empty()) {
/* We have a type wrapped class, so wrap it */
Variant result = wrapObject(state->options.types.decimal128_class_name, obj);
state->zchild.add(String::FromCStr(key), result);
} else {
state->zchild.add(String::FromCStr(key), Variant(obj));
}
return false;
}
static const bson_visitor_t hippo_bson_visitors = {
NULL /* hippo_phongo_bson_visit_before*/,
NULL /*hippo_phongo_bson_visit_after*/,
hippo_bson_visit_corrupt,
hippo_bson_visit_double,
hippo_bson_visit_utf8,
hippo_bson_visit_document,
hippo_bson_visit_array,
hippo_bson_visit_binary,
NULL /*hippo_bson_visit_undefined*/,
hippo_bson_visit_oid,
hippo_bson_visit_bool,
hippo_bson_visit_date_time,
hippo_bson_visit_null,
hippo_bson_visit_regex,
NULL /*hippo_bson_visit_dbpointer*/,
hippo_bson_visit_code,
NULL /*hippo_bson_visit_symbol*/,
hippo_bson_visit_codewscope,
hippo_bson_visit_int32,
hippo_bson_visit_timestamp,
hippo_bson_visit_int64,
hippo_bson_visit_maxkey,
hippo_bson_visit_minkey,
hippo_bson_visit_unsupported_type,
hippo_bson_visit_decimal128,
{ NULL }
};
/* }}} */
bool BsonToVariantConverter::convert(Variant *v)
{
bson_iter_t iter;
bool eof = false;
bool havePclass;
const bson_t *b;
int type_descriminator;
String named_class;
m_state.zchild = NULL;
/* Determine which descriminator to use */
switch (m_options.current_compound_type) {
case HIPPO_BSONTYPE_ARRAY:
type_descriminator = m_options.array_type;
named_class = m_options.array_class_name;
break;
case HIPPO_BSONTYPE_ROOT:
type_descriminator = m_options.root_type;
named_class = m_options.root_class_name;
break;
case HIPPO_BSONTYPE_DOCUMENT:
type_descriminator = m_options.document_type;
named_class = m_options.document_class_name;
break;
}
if (!(b = bson_reader_read(m_reader, &eof))) {
throw MongoDriver::Utils::throwUnexpectedValueException("Could not read document from BSON reader");
return false;
}
if (!bson_iter_init(&iter, b)) {
bson_reader_destroy(m_reader);
throw MongoDriver::Utils::throwUnexpectedValueException("Could not initialize BSON iterator");
return false;
}
m_state.zchild = Array::Create();
m_state.options = m_options;
if (bson_iter_visit_all(&iter, &hippo_bson_visitors, &m_state) || iter.err_off) {
bson_reader_destroy(m_reader);
throw MongoDriver::Utils::throwUnexpectedValueException("Detected corrupt BSON data");
}
/* Set "root" to false */
havePclass = false;
if (
(
type_descriminator == HIPPO_TYPEMAP_DEFAULT ||
type_descriminator == HIPPO_TYPEMAP_NAMEDCLASS
) &&
m_state.zchild.exists(s_MongoDriverBsonODM_fieldName) &&
m_state.zchild[s_MongoDriverBsonODM_fieldName].isObject() &&
m_state.zchild[s_MongoDriverBsonODM_fieldName].toObject().instanceof(s_MongoBsonBinary_className) &&
m_state.zchild[s_MongoDriverBsonODM_fieldName].toObject().o_get(s_MongoBsonBinary_type, false, s_MongoBsonBinary_className).toInt64() == 0x80
) {
havePclass = true;
}
if (type_descriminator == HIPPO_TYPEMAP_NAMEDCLASS) {
static Class* c_class;
static Class* c_unserializable_interface;
static Class* c_persistable_interface;
Object obj;
bool useTypeMap = true;
c_unserializable_interface = Unit::lookupClass(s_MongoDriverBsonUnserializable_className.get());
c_persistable_interface = Unit::lookupClass(s_MongoDriverBsonPersistable_className.get());
/* If we have a __pclass, and the class exists, and the class
* implements MongoDB\BSON\Persitable, we use that class name. */
if (havePclass) {
String class_name = m_state.zchild[s_MongoDriverBsonODM_fieldName].toObject().o_get(
s_MongoBsonBinary_data, false, s_MongoBsonBinary_className
).toString();
/* Lookup class and instantiate object, but if we can't find the class,
* make it a stdClass */
c_class = Unit::getClass(class_name.get(), true);
if (c_class && isNormalClass(c_class) && c_class->classof(c_persistable_interface)) {
/* Instantiate */
obj = Object{c_class};
useTypeMap = false;
*v = Variant(obj);
}
}
if (useTypeMap) {
c_class = Unit::getClass(named_class.get(), true);
if (c_class && isNormalClass(c_class) && c_class->classof(c_unserializable_interface)) {
/* Instantiate */
obj = Object{c_class};
useTypeMap = false;
*v = Variant(obj);
}
}
/* If the type map didn't match with a suitable class, we bail out */
if (useTypeMap) {
throw MongoDriver::Utils::throwInvalidArgumentException("The typemap does not provide a class that implements MongoDB\\BSON\\Unserializable");
}
{
/* Setup arguments for bsonUnserialize call */
TypedValue args[1] = { *(Variant(m_state.zchild)).asCell() };
/* Call bsonUnserialize on the object */
Func *m = c_class->lookupMethod(s_MongoDriverBsonUnserializable_functionName.get());
#if HIPPO_HHVM_VERSION >= 31700
g_context->invokeFuncFew(
m,
obj.get(),
nullptr,
1, args
);
#else
Variant result;
g_context->invokeFuncFew(
result.asTypedValue(),
m,
obj.get(),
nullptr,
1, args
);
#endif
*v = Variant(obj);
}
} else if (havePclass) {
static Class* c_class;
String class_name = m_state.zchild[s_MongoDriverBsonODM_fieldName].toObject().o_get(
s_MongoBsonBinary_data, false, s_MongoBsonBinary_className
).toString();
TypedValue args[1] = { *(Variant(m_state.zchild)).asCell() };
/* Lookup class and instantiate object, but if we can't find the class,
* make it a stdClass */
c_class = Unit::getClass(class_name.get(), true);
if (!c_class) {
*v = Variant(Variant(m_state.zchild).toObject());
return true;
}
/* If the class is not a "normal" class, make it a stdClass object */
if (!isNormalClass(c_class) || isAbstract(c_class)) {
*v = Variant(Variant(m_state.zchild).toObject());
return true;
}
/* Instantiate */
Object obj = Object{c_class};
/* If the class does not implement Persistable, make it a stdClass */
if (!obj->instanceof(s_MongoDriverBsonPersistable_className)) {
*v = Variant(Variant(m_state.zchild).toObject());
return true;
}
/* Call bsonUnserialize on the object */
Func *m = c_class->lookupMethod(s_MongoDriverBsonUnserializable_functionName.get());
#if HIPPO_HHVM_VERSION >= 31700
g_context->invokeFuncFew(
m,
obj.get(),
nullptr,
1, args
);
#else
Variant result;
g_context->invokeFuncFew(
result.asTypedValue(),
m,
obj.get(),
nullptr,
1, args
);
#endif
*v = Variant(obj);
} else if (type_descriminator == HIPPO_TYPEMAP_DEFAULT) {
if (m_options.current_compound_type == HIPPO_BSONTYPE_ARRAY) {
*v = Variant(Variant(m_state.zchild).toArray());
} else if (m_options.current_compound_type == HIPPO_BSONTYPE_ROOT) {
*v = Variant(Variant(m_state.zchild).toObject());
} else if (m_options.current_compound_type == HIPPO_BSONTYPE_DOCUMENT) {
*v = Variant(Variant(m_state.zchild).toObject());
}
} else if (type_descriminator == HIPPO_TYPEMAP_STDCLASS) {
*v = Variant(Variant(m_state.zchild).toObject());
} else if (type_descriminator == HIPPO_TYPEMAP_ARRAY) {
*v = Variant(m_state.zchild);
} else {
assert(NULL);
}
if (bson_reader_read(m_reader, &eof) || !eof) {
bson_reader_destroy(m_reader);
throw MongoDriver::Utils::throwUnexpectedValueException("Reading document did not exhaust input buffer");
return false;
}
bson_reader_destroy(m_reader);
return true;
}
/* }}} */
/* {{{ TypeMap helper functions */
#define CASECMP(a,b) (bstrcasecmp((a).data(), (a).size(), (b).data(), (b).size()) == 0)
static void validateClass(String class_name)
{
static Class* c_class;
static Class* c_unserializable_interface = Unit::lookupClass(s_MongoDriverBsonUnserializable_className.get());
c_class = Unit::getClass(class_name.get(), true);
if (!c_class) {
throw MongoDriver::Utils::throwInvalidArgumentException("Class " + class_name + " does not exist");
}
if (c_class && (!isNormalClass(c_class) || isAbstract(c_class))) {
throw MongoDriver::Utils::throwInvalidArgumentException("Class " + class_name + " is not instantiatable");
}
if (c_class && !c_class->classof(c_unserializable_interface)) {
throw MongoDriver::Utils::throwInvalidArgumentException("Class " + class_name + " does not implement MongoDB\\BSON\\Unserializable");
}
}
static void validateTypeWrapperClass(String class_name)
{
static Class* c_class;
static Class* c_unserializable_interface = Unit::lookupClass(s_MongoBSONTypeWrapper_className.get());
c_class = Unit::getClass(class_name.get(), true);
if (!c_class) {
throw MongoDriver::Utils::throwInvalidArgumentException("Class " + class_name + " does not exist");
}
if (c_class && (!isNormalClass(c_class) || isAbstract(c_class))) {
throw MongoDriver::Utils::throwInvalidArgumentException("Class " + class_name + " is not instantiatable");
}
if (c_class && !c_class->classof(c_unserializable_interface)) {
throw MongoDriver::Utils::throwInvalidArgumentException("Class " + class_name + " does not implement MongoDB\\BSON\\TypeWrapper");
}
}
void parseTypeMap(hippo_bson_conversion_options_t *options, const Array &typemap)
{
if (typemap.exists(s_root) && typemap[s_root].isString()) {
String root_type;
root_type = typemap[s_root].toString();
if (CASECMP(root_type, s_object) || CASECMP(root_type, s_stdClass)) {
options->root_type = HIPPO_TYPEMAP_STDCLASS;
} else if (CASECMP(root_type, s_array)) {
options->root_type = HIPPO_TYPEMAP_ARRAY;
} else {
validateClass(root_type); /* Might throw an exception */
options->root_type = HIPPO_TYPEMAP_NAMEDCLASS;
options->root_class_name = root_type;
}
}
if (typemap.exists(s_document) && typemap[s_document].isString()) {
String document_type;
document_type = typemap[s_document].toString();
if (CASECMP(document_type, s_object) || CASECMP(document_type, s_stdClass)) {
options->document_type = HIPPO_TYPEMAP_STDCLASS;
} else if (CASECMP(document_type, s_array)) {
options->document_type = HIPPO_TYPEMAP_ARRAY;
} else {
validateClass(document_type); /* Might throw an exception */
options->document_type = HIPPO_TYPEMAP_NAMEDCLASS;
options->document_class_name = document_type;
}
}
if (typemap.exists(s_array) && typemap[s_array].isString()) {
String array_type;
array_type = typemap[s_array].toString();
if (CASECMP(array_type, s_object) || CASECMP(array_type, s_stdClass)) {
options->array_type = HIPPO_TYPEMAP_STDCLASS;
} else if (CASECMP(array_type, s_array)) {
options->array_type = HIPPO_TYPEMAP_ARRAY;
} else {
validateClass(array_type); /* Might throw an exception */
options->array_type = HIPPO_TYPEMAP_NAMEDCLASS;
options->array_class_name = array_type;
}
}
if (typemap.exists(s_types)) {
if (!typemap[s_types].isArray()) {
throw MongoDriver::Utils::throwInvalidArgumentException("The 'types' key in the type map should be an array");
}
for (ArrayIter iter(typemap[s_types]); iter; ++iter) {
Variant key(iter.first());
String s_key = key.toString();
const Variant& data(iter.secondRef());
if (!data.isString()) {
throw MongoDriver::Utils::throwInvalidArgumentException("The typemap for type '" + s_key + "' should be a string");
}
String s_type_class = data.toString();
/* Depending on the key, set the right option (or throw an exception) */
if (CASECMP(s_key, s_MongoBsonBinary_shortName)) {
validateTypeWrapperClass(s_type_class);
options->types.binary_class_name = s_type_class;
} else if (CASECMP(s_key, s_MongoBsonDecimal128_shortName)) {
validateTypeWrapperClass(s_type_class);
options->types.decimal128_class_name = s_type_class;
} else if (CASECMP(s_key, s_MongoBsonJavascript_shortName)) {
validateTypeWrapperClass(s_type_class);
options->types.javascript_class_name = s_type_class;
} else if (CASECMP(s_key, s_MongoBsonMaxKey_shortName)) {
validateTypeWrapperClass(s_type_class);
options->types.maxkey_class_name = s_type_class;
} else if (CASECMP(s_key, s_MongoBsonMinKey_shortName)) {
validateTypeWrapperClass(s_type_class);
options->types.minkey_class_name = s_type_class;
} else if (CASECMP(s_key, s_MongoBsonObjectID_shortName)) {
validateTypeWrapperClass(s_type_class);
options->types.objectid_class_name = s_type_class;
} else if (CASECMP(s_key, s_MongoBsonRegex_shortName)) {
validateTypeWrapperClass(s_type_class);
options->types.regex_class_name = s_type_class;
} else if (CASECMP(s_key, s_MongoBsonTimestamp_shortName)) {
validateTypeWrapperClass(s_type_class);
options->types.timestamp_class_name = s_type_class;
} else if (CASECMP(s_key, s_MongoBsonUTCDateTime_shortName)) {
validateTypeWrapperClass(s_type_class);
options->types.utcdatetime_class_name = s_type_class;
} else {
throw MongoDriver::Utils::throwInvalidArgumentException("The type '" + s_key + "' is not supported in the type map");
}
}
}
}
/* }}} */
} /* namespace HPHP */
| 30.851128 | 178 | 0.729138 | [
"object"
] |
91828b5ed8f420b02176d05f96b08537c2e7ec75 | 938 | hpp | C++ | mason_packages/headers/vtzero/1.0.0/include/vtzero/version.hpp | shiwan66/vtvalidate-pbf | 46e192c47af5ecfce9e91e78d5eadfed408e39ee | [
"BSD-2-Clause"
] | null | null | null | mason_packages/headers/vtzero/1.0.0/include/vtzero/version.hpp | shiwan66/vtvalidate-pbf | 46e192c47af5ecfce9e91e78d5eadfed408e39ee | [
"BSD-2-Clause"
] | 1 | 2020-04-05T05:37:58.000Z | 2020-04-05T05:37:58.000Z | mason_packages/headers/vtzero/1.0.0/include/vtzero/version.hpp | shiwan66/vtvalidate-pbf | 46e192c47af5ecfce9e91e78d5eadfed408e39ee | [
"BSD-2-Clause"
] | null | null | null | #ifndef VTZERO_VERSION_HPP
#define VTZERO_VERSION_HPP
/*****************************************************************************
vtzero - Tiny and fast vector tile decoder and encoder in C++.
This file is from https://github.com/mapbox/vtzero where you can find more
documentation.
*****************************************************************************/
/**
* @file version.hpp
*
* @brief Contains the version number macros for the vtzero library.
*/
/// The major version number
#define VTZERO_VERSION_MAJOR 1
/// The minor version number
#define VTZERO_VERSION_MINOR 0
/// The patch number
#define VTZERO_VERSION_PATCH 0
/// The complete version number
#define VTZERO_VERSION_CODE \
(VTZERO_VERSION_MAJOR * 10000 + VTZERO_VERSION_MINOR * 100 + \
VTZERO_VERSION_PATCH)
/// Version number as string
#define VTZERO_VERSION_STRING "1.0.0"
#endif // VTZERO_VERSION_HPP
| 25.351351 | 78 | 0.600213 | [
"vector"
] |
91842d47559907e2dad33a745240fb96b0c3ab25 | 1,730 | cpp | C++ | softrender/engine/scene.cpp | Buzzefall/softrender | 48a3e8685e72bbf2093d8e9bae22251d6dc14662 | [
"Unlicense"
] | null | null | null | softrender/engine/scene.cpp | Buzzefall/softrender | 48a3e8685e72bbf2093d8e9bae22251d6dc14662 | [
"Unlicense"
] | null | null | null | softrender/engine/scene.cpp | Buzzefall/softrender | 48a3e8685e72bbf2093d8e9bae22251d6dc14662 | [
"Unlicense"
] | null | null | null | #include <softrender/engine/scene.h>
#include <softrender/graphics/screen.h>
#include <softrender/graphics/core.h>
#include <softrender/utils/utils.h>
Vec3 default_viewpoint = {0, 1, 2};
Vec3 default_target = {0, 0, 0};
Vec3 default_camera_orientation = {0, -1, 0};
Vec3 default_light_dir = {0, 0, 1};
Scene::Scene(const std::vector<std::string>& object_names) : light_direction(default_light_dir) {
load_objects(object_names);
}
void Scene::load_objects(const std::vector<std::string>& obj_names) {
for (auto& name : obj_names) {
objects.push_back(std::make_unique<RotatingObject>(name));
}
}
bool Scene::save(const std::string& path) {
return false; // TODO: Scene::save(path)
}
void Scene::update(high_resolution_clock::time_point time) const {
for (auto& obj : objects) {
obj->update(time);
}
}
void Scene::render(Screen& target) const {
auto Viewport = get_Viewport(target);
auto Projection = get_Projection(target);
auto View = get_View(default_viewpoint, default_target, default_camera_orientation);
target.clear_init();
for (auto& obj : objects) {
auto Model = obj->Position * obj->Rotation;
//GouraudShader shader { light_direction, obj->model, (View * Model), Projection, Viewport };
//HeatMapShader shader { View * Vec4() , light_direction, obj->model, (View * Model), Projection, Viewport };
GouraudWireShader shader { 7e-2, light_direction, obj->model, (View * Model), Projection, Viewport };
for (uint32_t iface = 0; iface < obj->model.get_faces_count(); iface++) {
Mat<3, 4> verts_screenspace;
for (int ivert : {0, 1, 2}) {
verts_screenspace[ivert] = shader.vertex(iface, ivert);
}
draw_triangle(verts_screenspace, Viewport, shader, target);
}
}
}
| 30.350877 | 111 | 0.706358 | [
"render",
"vector",
"model"
] |
91876c324744a11cbccd58aa9b4b92410a05ab8a | 4,539 | cc | C++ | hybridse/examples/toydb/src/cmd/toydb_run_engine.cc | lotabout/OpenMLDB | 432da3afbed240eb0b8d0571c05f233b1a5a1cd4 | [
"Apache-2.0"
] | 1 | 2021-11-01T10:16:37.000Z | 2021-11-01T10:16:37.000Z | hybridse/examples/toydb/src/cmd/toydb_run_engine.cc | lotabout/OpenMLDB | 432da3afbed240eb0b8d0571c05f233b1a5a1cd4 | [
"Apache-2.0"
] | 14 | 2021-04-30T06:14:30.000Z | 2022-01-07T22:45:09.000Z | hybridse/examples/toydb/src/cmd/toydb_run_engine.cc | lotabout/OpenMLDB | 432da3afbed240eb0b8d0571c05f233b1a5a1cd4 | [
"Apache-2.0"
] | 1 | 2021-04-30T06:28:46.000Z | 2021-04-30T06:28:46.000Z | /*
* Copyright 2021 4Paradigm
*
* 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 <utility>
#include "testing/toydb_engine_test_base.h"
DEFINE_string(yaml_path, "", "Yaml filepath to load cases from");
DEFINE_string(runner_mode, "batch",
"Specify runner mode, can be batch or request");
DEFINE_string(cluster_mode, "standalone",
"Specify cluster mode, can be standalone or cluster");
DEFINE_bool(
enable_batch_request_opt, true,
"Specify whether perform batch request optimization in batch request mode");
DEFINE_bool(performance_sensitive, true,
"Specify whether do performance sensitive check");
DEFINE_bool(enable_expr_opt, true,
"Specify whether do expression optimization");
DEFINE_bool(
enable_batch_window_parallelization, false,
"Specify whether enable window parallelization in spark batch mode");
DEFINE_int32(run_iters, 0, "Measure the approximate run time if specified");
DEFINE_int32(case_id, -1, "Specify the case id to run and skip others");
// jit options
DEFINE_bool(enable_mcjit, false, "Use llvm legacy mcjit engine");
DEFINE_bool(enable_vtune, false, "Enable llvm jit vtune events");
DEFINE_bool(enable_gdb, false, "Enable llvm jit gdb events");
DEFINE_bool(enable_perf, false, "Enable llvm jit perf events");
namespace hybridse {
namespace vm {
int DoRunEngine(const SqlCase& sql_case, const EngineOptions& options,
EngineMode engine_mode) {
std::shared_ptr<EngineTestRunner> runner;
if (engine_mode == kBatchMode) {
runner =
std::make_shared<ToydbBatchEngineTestRunner>(sql_case, options);
} else if (engine_mode == kRequestMode) {
runner =
std::make_shared<ToydbRequestEngineTestRunner>(sql_case, options);
} else {
runner = std::make_shared<ToydbBatchRequestEngineTestRunner>(
sql_case, options, sql_case.batch_request().common_column_indices_);
}
if (FLAGS_run_iters > 0) {
runner->RunBenchmark(FLAGS_run_iters);
} else {
runner->RunCheck();
}
return runner->return_code();
}
int RunSingle(const std::string& yaml_path) {
std::vector<SqlCase> cases;
if (!SqlCase::CreateSqlCasesFromYaml("", yaml_path, cases)) {
LOG(WARNING) << "Load cases from " << yaml_path << " failed";
return ENGINE_TEST_RET_INVALID_CASE;
}
EngineOptions options;
options.set_cluster_optimized(FLAGS_cluster_mode == "cluster");
options.set_batch_request_optimized(FLAGS_enable_batch_request_opt);
options.set_performance_sensitive(FLAGS_performance_sensitive);
options.set_enable_expr_optimize(FLAGS_enable_expr_opt);
options.set_enable_batch_window_parallelization(
FLAGS_enable_batch_window_parallelization);
JitOptions& jit_options = options.jit_options();
jit_options.set_enable_mcjit(FLAGS_enable_mcjit);
jit_options.set_enable_vtune(FLAGS_enable_vtune);
jit_options.set_enable_gdb(FLAGS_enable_gdb);
jit_options.set_enable_perf(FLAGS_enable_perf);
for (auto& sql_case : cases) {
if (FLAGS_case_id >= 0 &&
std::to_string(FLAGS_case_id) != sql_case.id()) {
continue;
}
EngineMode mode;
if (FLAGS_runner_mode == "batch") {
mode = kBatchMode;
} else if (FLAGS_runner_mode == "request") {
mode = kRequestMode;
} else {
mode = kBatchRequestMode;
}
int ret = DoRunEngine(sql_case, options, mode);
if (ret != ENGINE_TEST_RET_SUCCESS) {
return ret;
}
}
return ENGINE_TEST_RET_SUCCESS;
}
} // namespace vm
} // namespace hybridse
int main(int argc, char** argv) {
::google::ParseCommandLineFlags(&argc, &argv, false);
InitializeNativeTarget();
InitializeNativeTargetAsmPrinter();
if (FLAGS_yaml_path != "") {
return ::hybridse::vm::RunSingle(FLAGS_yaml_path);
} else {
LOG(WARNING) << "No --yaml_path specified";
return -1;
}
}
| 37.204918 | 80 | 0.695087 | [
"vector"
] |
91890f6a1267ce7a3f0ef547dffc289e198bd8e2 | 1,372 | hh | C++ | elements/ethernet/etherencap.hh | MacWR/Click-changed-for-ParaGraph | 18285e5da578fbb7285d10380836146e738dee6e | [
"Apache-2.0"
] | 32 | 2017-11-02T12:33:21.000Z | 2022-02-07T22:25:58.000Z | elements/ethernet/etherencap.hh | MacWR/Click-changed-for-ParaGraph | 18285e5da578fbb7285d10380836146e738dee6e | [
"Apache-2.0"
] | 2 | 2019-02-18T08:47:16.000Z | 2019-05-24T14:41:23.000Z | elements/ethernet/etherencap.hh | MacWR/Click-changed-for-ParaGraph | 18285e5da578fbb7285d10380836146e738dee6e | [
"Apache-2.0"
] | 10 | 2018-06-13T11:54:53.000Z | 2020-09-08T06:52:43.000Z | #ifndef CLICK_ETHERENCAP_HH
#define CLICK_ETHERENCAP_HH
#include <click/element.hh>
#include <clicknet/ether.h>
CLICK_DECLS
/*
=c
EtherEncap(ETHERTYPE, SRC, DST)
=s ethernet
encapsulates packets in Ethernet header
=d
Encapsulates each packet in the Ethernet header specified by its arguments.
ETHERTYPE should be in host order.
=e
Encapsulate packets in an Ethernet header with type
ETHERTYPE_IP (0x0800), source address 1:1:1:1:1:1, and
destination address 2:2:2:2:2:2:
EtherEncap(0x0800, 1:1:1:1:1:1, 2:2:2:2:2:2)
=n
For IP packets you probably want to use ARPQuerier instead.
=h src read/write
Return or set the SRC parameter.
=h dst read/write
Return or set the DST parameter.
=h ethertype read/write
Return or set the ETHERTYPE parameter.
=a
EtherVLANEncap, ARPQuerier, EnsureEther, StoreEtherAddress, EtherRewrite */
class EtherEncap : public Element { public:
EtherEncap() CLICK_COLD;
~EtherEncap() CLICK_COLD;
const char *class_name() const { return "EtherEncap"; }
const char *port_count() const { return PORTS_1_1; }
int configure(Vector<String> &, ErrorHandler *) CLICK_COLD;
bool can_live_reconfigure() const { return true; }
void add_handlers() CLICK_COLD;
Packet *smaction(Packet *);
void push(int, Packet *);
Packet *pull(int);
private:
click_ether _ethh;
};
CLICK_ENDDECLS
#endif
| 18.794521 | 75 | 0.73105 | [
"vector"
] |
92636f2c850bdab4dbf979c376046edffb183933 | 351 | cpp | C++ | lab4/gardurile lui gigel/main.cpp | mihaimusat/PA-labs-2019 | 113e833dc7fbe2bd5455e2552dde1d8b20931db9 | [
"MIT"
] | null | null | null | lab4/gardurile lui gigel/main.cpp | mihaimusat/PA-labs-2019 | 113e833dc7fbe2bd5455e2552dde1d8b20931db9 | [
"MIT"
] | null | null | null | lab4/gardurile lui gigel/main.cpp | mihaimusat/PA-labs-2019 | 113e833dc7fbe2bd5455e2552dde1d8b20931db9 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define mod 1009
using namespace std;
int main()
{
ifstream fin("a.in");
ofstream fout("a.out");
int n;
fin>>n;
vector<int> dp(n+1);
dp[1]=1;
dp[2]=1;
dp[3]=1;
dp[4]=2;
for(int i=5; i<=n; i++) {
dp[i]=(dp[i-1]+dp[i-4]) % mod;
}
fout<<dp[n]<<endl;
return 0;
}
| 12.535714 | 38 | 0.464387 | [
"vector"
] |
92662265d6bcb338ca9e46e1163b2abc178c0501 | 815 | cpp | C++ | Array/106. Construct Binary Tree from Inorder and Postorder Traversal.cpp | YuPeize/LeetCode- | b01d00f28e1eedcb04aee9eca984685bd9d52791 | [
"MIT"
] | 2 | 2019-10-28T06:40:09.000Z | 2022-03-09T10:50:06.000Z | Array/106. Construct Binary Tree from Inorder and Postorder Traversal.cpp | sumiya-NJU/LeetCode | 8e6065e160da3db423a51aaf3ae53b2023068d05 | [
"MIT"
] | null | null | null | Array/106. Construct Binary Tree from Inorder and Postorder Traversal.cpp | sumiya-NJU/LeetCode | 8e6065e160da3db423a51aaf3ae53b2023068d05 | [
"MIT"
] | 1 | 2018-12-09T13:46:06.000Z | 2018-12-09T13:46:06.000Z |
/*
和上题第二种方法一样,参考了别人的方法
*/
class Solution {
public:
map<int,int>m;
TreeNode*Helper(vector<int>& inorder, vector<int>& postorder,int first, int end,int pos,int cur){
TreeNode*result = new TreeNode(postorder[cur]);
int temp = m[postorder[cur]];
if(temp>first) result->left = Helper(inorder,postorder,first,temp-1,pos,pos+temp-first-1);
if(temp<end) result->right = Helper(inorder,postorder,temp+1,end,pos+temp-first,cur-1);
return result;
}
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
if(inorder.empty()) return NULL;
int length=inorder.size();
for(int i=0;i<length;i++){
m.insert(pair<int,int>(inorder[i],i));
}
return Helper(inorder,postorder,0,length-1,0,length-1);
}
};
| 30.185185 | 101 | 0.620859 | [
"vector"
] |
9268d9cba5c96ea5b6d70b06f00f2cbfbd793872 | 9,971 | cpp | C++ | hphp/runtime/vm/jit/vasm-block-counters.cpp | cobbles/hhvm | 583f879c7e1be697b1695a4506dd2f7171b921d0 | [
"PHP-3.01",
"Zend-2.0"
] | null | null | null | hphp/runtime/vm/jit/vasm-block-counters.cpp | cobbles/hhvm | 583f879c7e1be697b1695a4506dd2f7171b921d0 | [
"PHP-3.01",
"Zend-2.0"
] | null | null | null | hphp/runtime/vm/jit/vasm-block-counters.cpp | cobbles/hhvm | 583f879c7e1be697b1695a4506dd2f7171b921d0 | [
"PHP-3.01",
"Zend-2.0"
] | null | null | null | /*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/runtime/vm/jit/vasm-block-counters.h"
#include "hphp/runtime/base/runtime-option.h"
#include "hphp/runtime/vm/jit/abi.h"
#include "hphp/runtime/vm/jit/prof-data-serialize.h"
#include "hphp/runtime/vm/jit/trans-prof-counters.h"
#include "hphp/runtime/vm/jit/vasm-gen.h"
#include "hphp/runtime/vm/jit/vasm-instr.h"
#include "hphp/runtime/vm/jit/vasm-print.h"
#include "hphp/runtime/vm/jit/vasm-unit.h"
#include "hphp/runtime/vm/jit/vasm-util.h"
#include "hphp/util/trace.h"
#include <type_traits>
TRACE_SET_MOD(vasm_block_count);
namespace HPHP { namespace jit {
namespace VasmBlockCounters {
///////////////////////////////////////////////////////////////////////////////
namespace {
/*
* Profile counters for vasm blocks for each optimized JIT region and prologue.
* Along with the counters, we keep the opcode of the first Vasm instruction
* in each block as metadata (prior to inserting the profile counters), which
* is used to validate the profile.
*/
using VOpRaw = std::underlying_type<Vinstr::Opcode>::type;
TransProfCounters<int64_t, VOpRaw> s_blockCounters;
/*
* Insert profile counters for the blocks in the given unit.
*/
template <typename T>
void insert(Vunit& unit, const T& key) {
assertx(isJitSerializing());
splitCriticalEdges(unit);
auto const blocks = sortBlocks(unit);
auto const livein = computeLiveness(unit, abi(), blocks);
auto const gp_regs = abi().gpUnreserved;
auto const rgpFallback = abi().gp().choose();
auto const rsf = abi().sf.choose();
for (auto b : blocks) {
auto& block = unit.blocks[b];
auto const counterAddr = s_blockCounters.addCounter(key, block.code.front().op);
auto const& live_set = livein[b];
auto const save_sf = live_set[Vreg(rsf)] ||
RuntimeOption::EvalJitPGOVasmBlockCountersForceSaveSF;
// search for an available gp register to load the counter's address into it
auto save_gp = true;
auto rgp = rgpFallback;
gp_regs.forEach([&](PhysReg r) {
if (save_gp && !live_set[Vreg(r)]) {
save_gp = false;
rgp = r;
}
});
if (RuntimeOption::EvalJitPGOVasmBlockCountersForceSaveGP) save_gp = true;
// emit the increment of the counter, saving/restoring the used registers on
// the native stack before/after if needed.
// NB: decqmlock instructions are currently used to update the counters, so
// they actually start at zero and grow down from there. The sign is then
// flipped when serializing the data in RegionProfCounters::serialize().
jit::vector<Vinstr> new_insts;
if (save_gp) new_insts.insert(new_insts.end(), push{rgp});
if (save_sf) new_insts.insert(new_insts.end(), pushf{rsf});
new_insts.insert(new_insts.end(), ldimmq{counterAddr, rgp});
new_insts.insert(new_insts.end(), decqmlock{rgp[0], rsf});
if (save_sf) new_insts.insert(new_insts.end(), popf{rsf});
if (save_gp) new_insts.insert(new_insts.end(), pop{rgp});
// set irctx for the newly added instructions
auto const irctx = block.code.front().irctx();
for (auto& ni : new_insts) {
ni.set_irctx(irctx);
}
// insert new instructions in the beginning of the block, but after any
// existing phidef
auto insertPt = block.code.begin();
while (insertPt->op == Vinstr::phidef) insertPt++;
block.code.insert(insertPt, new_insts.begin(), new_insts.end());
}
FTRACE(1, "VasmBlockCounters::insert: modified unit\n{}", show(unit));
}
/*
* Checks whether the profile data in `counters' and `opcodes' matches the given
* `unit'. If they don't, a string with the error found is returned. Otherwise
* (on success), an empty string is returned.
*/
std::string checkProfile(const Vunit& unit,
const jit::vector<Vlabel>& sortedBlocks,
const jit::vector<int64_t>& counters,
const jit::vector<VOpRaw>& opcodes) {
if (counters.size() == 0) return "no profile for this region";
std::string errorMsg;
size_t opcodeMismatches=0;
auto reportRegion = [&] {
if (!errorMsg.empty()) return;
errorMsg = show(unit.context->region->entry()->start()) + "\n";
FTRACE(1, "VasmBlockCounters::checkProfile: SrcKey={}", errorMsg);
};
for (size_t index = 0; index < sortedBlocks.size(); index++) {
auto b = sortedBlocks[index];
auto& block = unit.blocks[b];
if (index >= counters.size()) {
reportRegion();
auto const msg = folly::sformat(
"missing block counter for B{} (index = {}, counters.size() = {})\n",
size_t{b}, index, counters.size());
FTRACE(1, "VasmBlockCounters::checkProfile: {}", msg);
errorMsg += msg;
return errorMsg;
}
auto const op_opti = block.code.front().op;
auto const op_prof = opcodes[index];
if (op_prof != op_opti) {
reportRegion();
auto const msg = folly::sformat(
"mismatch opcode for B{} (index = {}): "
"profile was {} optimized is {}\n",
size_t{b}, index, vinst_names[op_prof], vinst_names[op_opti]);
FTRACE(1, "VasmBlockCounters::checkProfile: {}", msg);
errorMsg += msg;
opcodeMismatches++;
}
}
// Consider the profile to match even if we have some opcode mismatches.
if (opcodeMismatches <=
RuntimeOption::EvalJitPGOVasmBlockCountersMaxOpMismatches) {
return "";
}
return errorMsg;
}
/*
* Set the weights of the blocks in the given unit based on profile data, if
* available.
*/
template <typename T>
void setWeights(Vunit& unit, const T& key) {
assertx(isJitDeserializing());
jit::vector<VOpRaw> opcodes;
auto counters = s_blockCounters.getCounters(key, opcodes);
splitCriticalEdges(unit);
auto sortedBlocks = sortBlocks(unit);
FTRACE(1, "VasmBlockCounters::setWeights: original unit\n{}", show(unit));
std::string errorMsg = checkProfile(unit, sortedBlocks, counters, opcodes);
auto DEBUG_ONLY prefix = "un";
bool enoughProfile = false;
if (errorMsg == "") {
// Check that enough profile was collected.
if (counters[0] >= RuntimeOption::EvalJitPGOVasmBlockCountersMinEntryValue) {
prefix = "";
enoughProfile = true;
// Update the block weights.
for (size_t index = 0; index < sortedBlocks.size(); index++) {
auto const b = sortedBlocks[index];
auto& block = unit.blocks[b];
assertx(index < counters.size());
block.weight = counters[index];
// Drop the separation between the main, cold and frozen areas, to avoid
// scaling of the block weights based on the area since we have accurate
// counters. The code-layout pass may re-split the code into
// hot/cold/frozen later.
block.area_idx = AreaIndex::Main;
}
}
}
if (RuntimeOption::EvalDumpVBC) {
unit.annotations.emplace_back("VasmBlockCounters",
errorMsg != "" ? errorMsg :
enoughProfile ? "matches" :
"matches, but not enough profile data");
}
FTRACE(1, "VasmBlockCounters::setWeights: {}modified unit\n{}",
prefix, show(unit));
}
}
///////////////////////////////////////////////////////////////////////////////
folly::Optional<uint64_t> getRegionWeight(const RegionDesc& region) {
if (!RO::EvalJitPGOVasmBlockCounters || !isJitDeserializing()) {
return folly::none;
}
auto const key = RegionEntryKey(region);
auto const weight = s_blockCounters.getFirstCounter(key);
if (!weight) return folly::none;
return safe_cast<uint64_t>(*weight);
}
template <typename T>
void update(Vunit& unit, const T& key){
if (isJitSerializing()) {
// Insert block profile counters.
insert(unit, key);
} else if (isJitDeserializing()) {
// Look up the information from the profile, and use it if found.
setWeights(unit, key);
}
}
void profileGuidedUpdate(Vunit& unit) {
if (!RuntimeOption::EvalJitPGOVasmBlockCounters) return;
if (!unit.context) return;
auto const optimizePrologue = unit.context->kind == TransKind::OptPrologue &&
RuntimeOption::EvalJitPGOVasmBlockCountersOptPrologue;
if (unit.context->kind == TransKind::Optimize) {
auto const regionPtr = unit.context->region;
if (!regionPtr) return;
const RegionEntryKey regionKey(*regionPtr);
update(unit, regionKey);
} else if (optimizePrologue) {
auto const pid = unit.context->pid;
if (pid.funcId() == FuncId::Invalid) return;
update(unit, pid);
}
}
///////////////////////////////////////////////////////////////////////////////
void serialize(ProfDataSerializer& ser) {
s_blockCounters.serialize(ser);
}
void deserialize(ProfDataDeserializer& des) {
s_blockCounters.deserialize(des);
}
void free() {
s_blockCounters.freeCounters();
}
///////////////////////////////////////////////////////////////////////////////
} } }
| 35.483986 | 84 | 0.610671 | [
"vector"
] |
926d694d2520eb8ca0e41ac3ca7c4858ef905f05 | 6,119 | cpp | C++ | test/reverse_iter.cpp | setine/stl_interfaces | c47f91507e75574278e0167accdcb28a0d1bf136 | [
"BSL-1.0"
] | null | null | null | test/reverse_iter.cpp | setine/stl_interfaces | c47f91507e75574278e0167accdcb28a0d1bf136 | [
"BSL-1.0"
] | null | null | null | test/reverse_iter.cpp | setine/stl_interfaces | c47f91507e75574278e0167accdcb28a0d1bf136 | [
"BSL-1.0"
] | null | null | null | // Copyright (C) 2019 T. Zachary Laine
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <boost/stl_interfaces/iterator_interface.hpp>
#include <boost/stl_interfaces/reverse_iterator.hpp>
#include <gtest/gtest.h>
#include <algorithm>
#include <array>
#include <list>
#include <vector>
struct zip_iter : boost::stl_interfaces::proxy_iterator_interface<
zip_iter,
std::random_access_iterator_tag,
std::tuple<int, int>,
std::tuple<int &, int &>>
{
zip_iter() : it1_(nullptr), it2_(nullptr) {}
zip_iter(int * it1, int * it2) : it1_(it1), it2_(it2) {}
std::tuple<int &, int &> operator*() const
{
return std::tuple<int &, int &>{*it1_, *it2_};
}
zip_iter & operator+=(std::ptrdiff_t i)
{
it1_ += i;
it2_ += i;
return *this;
}
friend std::ptrdiff_t operator-(zip_iter lhs, zip_iter rhs) noexcept
{
return lhs.it1_ - rhs.it1_;
}
private:
int * it1_;
int * it2_;
};
TEST(reverse_iter, std_list_iterator)
{
std::list<int> ints = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
auto first = boost::stl_interfaces::make_reverse_iterator(ints.end());
auto last = boost::stl_interfaces::make_reverse_iterator(ints.begin());
{
auto cfirst = boost::stl_interfaces::reverse_iterator<
std::list<int>::const_iterator>(first);
auto clast = boost::stl_interfaces::reverse_iterator<
std::list<int>::const_iterator>(last);
EXPECT_TRUE(std::equal(first, last, cfirst, clast));
}
{
auto ints_copy = ints;
std::reverse(ints_copy.begin(), ints_copy.end());
EXPECT_TRUE(
std::equal(first, last, ints_copy.begin(), ints_copy.end()));
}
{
std::list<int> ints_copy;
std::reverse_copy(first, last, std::back_inserter(ints_copy));
EXPECT_EQ(ints_copy, ints);
}
{
std::size_t count = 0;
for (auto it = first; it != last; ++it) {
++count;
}
EXPECT_EQ(count, ints.size());
}
{
std::size_t count = 0;
for (auto it = first; it != last; it++) {
++count;
}
EXPECT_EQ(count, ints.size());
}
{
std::size_t count = 0;
for (auto it = last; it != first; --it) {
++count;
}
EXPECT_EQ(count, ints.size());
}
{
std::size_t count = 0;
for (auto it = last; it != first; it--) {
++count;
}
EXPECT_EQ(count, ints.size());
}
}
TEST(reverse_iter, std_vector_iterator)
{
std::vector<int> ints = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
auto first = boost::stl_interfaces::make_reverse_iterator(ints.end());
auto last = boost::stl_interfaces::make_reverse_iterator(ints.begin());
{
auto cfirst = boost::stl_interfaces::reverse_iterator<
std::vector<int>::const_iterator>(first);
auto clast = boost::stl_interfaces::reverse_iterator<
std::vector<int>::const_iterator>(last);
EXPECT_TRUE(std::equal(first, last, cfirst, clast));
}
{
auto ints_copy = ints;
std::reverse(ints_copy.begin(), ints_copy.end());
EXPECT_EQ(first - last, ints_copy.begin() - ints_copy.end());
EXPECT_TRUE(
std::equal(first, last, ints_copy.begin(), ints_copy.end()));
}
{
std::vector<int> ints_copy;
std::reverse_copy(first, last, std::back_inserter(ints_copy));
EXPECT_EQ(ints_copy, ints);
}
{
std::size_t count = 0;
for (auto it = first; it != last; ++it) {
++count;
}
EXPECT_EQ(count, ints.size());
}
{
std::size_t count = 0;
for (auto it = first; it != last; it++) {
++count;
}
EXPECT_EQ(count, ints.size());
}
{
std::size_t count = 0;
for (auto it = last; it != first; --it) {
++count;
}
EXPECT_EQ(count, ints.size());
}
{
std::size_t count = 0;
for (auto it = last; it != first; it--) {
++count;
}
EXPECT_EQ(count, ints.size());
}
}
TEST(reverse_iter, zip_iterator)
{
std::array<int, 10> ints = {{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}};
std::array<int, 10> ones = {{1, 1, 1, 1, 1, 1, 1, 1, 1, 1}};
std::array<std::tuple<int, int>, 10> tuples = {{
{0, 1},
{1, 1},
{2, 1},
{3, 1},
{4, 1},
{5, 1},
{6, 1},
{7, 1},
{8, 1},
{9, 1},
}};
auto first = boost::stl_interfaces::make_reverse_iterator(
zip_iter(ints.data() + ints.size(), ones.data() + ones.size()));
auto last = boost::stl_interfaces::make_reverse_iterator(
zip_iter(ints.data(), ones.data()));
{
auto tuples_copy = tuples;
std::reverse(tuples_copy.begin(), tuples_copy.end());
EXPECT_EQ(first - last, tuples_copy.begin() - tuples_copy.end());
EXPECT_TRUE(
std::equal(first, last, tuples_copy.begin(), tuples_copy.end()));
}
{
std::array<std::tuple<int, int>, 10> tuples_copy;
std::reverse_copy(first, last, tuples_copy.begin());
EXPECT_EQ(tuples_copy, tuples);
}
{
std::size_t count = 0;
for (auto it = first; it != last; ++it) {
++count;
}
EXPECT_EQ(count, tuples.size());
}
{
std::size_t count = 0;
for (auto it = first; it != last; it++) {
++count;
}
EXPECT_EQ(count, tuples.size());
}
{
std::size_t count = 0;
for (auto it = last; it != first; --it) {
++count;
}
EXPECT_EQ(count, tuples.size());
}
{
std::size_t count = 0;
for (auto it = last; it != first; it--) {
++count;
}
EXPECT_EQ(count, tuples.size());
}
}
| 25.710084 | 77 | 0.521164 | [
"vector"
] |
927d0cf74198099352d6e939be2fcf401e2d064d | 5,744 | cc | C++ | dacbench/envs/rl-plan/fast-downward/src/search/cegar/additive_cartesian_heuristic.cc | ndangtt/LeadingOnesDAC | 953747d8702f179851d7973c65779a1f830e03a1 | [
"Apache-2.0"
] | 1 | 2022-02-23T15:26:11.000Z | 2022-02-23T15:26:11.000Z | dacbench/envs/rl-plan/fast-downward/src/search/cegar/additive_cartesian_heuristic.cc | ndangtt/LeadingOnesDAC | 953747d8702f179851d7973c65779a1f830e03a1 | [
"Apache-2.0"
] | null | null | null | dacbench/envs/rl-plan/fast-downward/src/search/cegar/additive_cartesian_heuristic.cc | ndangtt/LeadingOnesDAC | 953747d8702f179851d7973c65779a1f830e03a1 | [
"Apache-2.0"
] | null | null | null | #include "additive_cartesian_heuristic.h"
#include "cartesian_heuristic_function.h"
#include "cost_saturation.h"
#include "types.h"
#include "utils.h"
#include "../option_parser.h"
#include "../plugin.h"
#include "../utils/logging.h"
#include "../utils/markup.h"
#include "../utils/rng.h"
#include "../utils/rng_options.h"
#include <cassert>
using namespace std;
namespace cegar {
static vector<CartesianHeuristicFunction> generate_heuristic_functions(
const options::Options &opts) {
utils::g_log << "Initializing additive Cartesian heuristic..." << endl;
vector<shared_ptr<SubtaskGenerator>> subtask_generators =
opts.get_list<shared_ptr<SubtaskGenerator>>("subtasks");
shared_ptr<utils::RandomNumberGenerator> rng =
utils::parse_rng_from_options(opts);
CostSaturation cost_saturation(
subtask_generators,
opts.get<int>("max_states"),
opts.get<int>("max_transitions"),
opts.get<double>("max_time"),
opts.get<bool>("use_general_costs"),
static_cast<PickSplit>(opts.get<int>("pick")),
*rng,
opts.get<bool>("debug"));
return cost_saturation.generate_heuristic_functions(
opts.get<shared_ptr<AbstractTask>>("transform"));
}
AdditiveCartesianHeuristic::AdditiveCartesianHeuristic(
const options::Options &opts)
: Heuristic(opts),
heuristic_functions(generate_heuristic_functions(opts)) {
}
int AdditiveCartesianHeuristic::compute_heuristic(const GlobalState &global_state) {
State state = convert_global_state(global_state);
return compute_heuristic(state);
}
int AdditiveCartesianHeuristic::compute_heuristic(const State &state) {
int sum_h = 0;
for (const CartesianHeuristicFunction &function : heuristic_functions) {
int value = function.get_value(state);
assert(value >= 0);
if (value == INF)
return DEAD_END;
sum_h += value;
}
assert(sum_h >= 0);
return sum_h;
}
static shared_ptr<Heuristic> _parse(OptionParser &parser) {
parser.document_synopsis(
"Additive CEGAR heuristic",
"See the paper introducing Counterexample-guided Abstraction "
"Refinement (CEGAR) for classical planning:" +
utils::format_conference_reference(
{"Jendrik Seipp", "Malte Helmert"},
"Counterexample-guided Cartesian Abstraction Refinement",
"https://ai.dmi.unibas.ch/papers/seipp-helmert-icaps2013.pdf",
"Proceedings of the 23rd International Conference on Automated "
"Planning and Scheduling (ICAPS 2013)",
"347-351",
"AAAI Press",
"2013") +
"and the paper showing how to make the abstractions additive:" +
utils::format_conference_reference(
{"Jendrik Seipp", "Malte Helmert"},
"Diverse and Additive Cartesian Abstraction Heuristics",
"https://ai.dmi.unibas.ch/papers/seipp-helmert-icaps2014.pdf",
"Proceedings of the 24th International Conference on "
"Automated Planning and Scheduling (ICAPS 2014)",
"289-297",
"AAAI Press",
"2014") +
"For more details on Cartesian CEGAR and saturated cost partitioning, "
"see the journal paper" +
utils::format_journal_reference(
{"Jendrik Seipp", "Malte Helmert"},
"Counterexample-Guided Cartesian Abstraction Refinement for "
"Classical Planning",
"https://ai.dmi.unibas.ch/papers/seipp-helmert-jair2018.pdf",
"Journal of Artificial Intelligence Research",
"62",
"535-577",
"2018"));
parser.document_language_support("action costs", "supported");
parser.document_language_support("conditional effects", "not supported");
parser.document_language_support("axioms", "not supported");
parser.document_property("admissible", "yes");
parser.document_property("consistent", "yes");
parser.document_property("safe", "yes");
parser.document_property("preferred operators", "no");
parser.add_list_option<shared_ptr<SubtaskGenerator>>(
"subtasks",
"subtask generators",
"[landmarks(),goals()]");
parser.add_option<int>(
"max_states",
"maximum sum of abstract states over all abstractions",
"infinity",
Bounds("1", "infinity"));
parser.add_option<int>(
"max_transitions",
"maximum sum of real transitions (excluding self-loops) over "
" all abstractions",
"1000000",
Bounds("0", "infinity"));
parser.add_option<double>(
"max_time",
"maximum time in seconds for building abstractions",
"infinity",
Bounds("0.0", "infinity"));
vector<string> pick_strategies;
pick_strategies.push_back("RANDOM");
pick_strategies.push_back("MIN_UNWANTED");
pick_strategies.push_back("MAX_UNWANTED");
pick_strategies.push_back("MIN_REFINED");
pick_strategies.push_back("MAX_REFINED");
pick_strategies.push_back("MIN_HADD");
pick_strategies.push_back("MAX_HADD");
parser.add_enum_option(
"pick", pick_strategies, "split-selection strategy", "MAX_REFINED");
parser.add_option<bool>(
"use_general_costs",
"allow negative costs in cost partitioning",
"true");
parser.add_option<bool>(
"debug",
"print debugging output",
"false");
Heuristic::add_options_to_parser(parser);
utils::add_rng_options(parser);
Options opts = parser.parse();
if (parser.dry_run())
return nullptr;
return make_shared<AdditiveCartesianHeuristic>(opts);
}
static Plugin<Evaluator> _plugin("cegar", _parse);
}
| 36.35443 | 84 | 0.659645 | [
"vector",
"transform"
] |
927d205b8677f04db619b17766d88e092c245a62 | 21,568 | cc | C++ | libdrizzle/statement_param.cc | andreas-bok-sociomantic/libdrizzle-redux-5.2 | 686996f2fce5f41d669a08f9f766c65f43291530 | [
"BSD-3-Clause"
] | null | null | null | libdrizzle/statement_param.cc | andreas-bok-sociomantic/libdrizzle-redux-5.2 | 686996f2fce5f41d669a08f9f766c65f43291530 | [
"BSD-3-Clause"
] | null | null | null | libdrizzle/statement_param.cc | andreas-bok-sociomantic/libdrizzle-redux-5.2 | 686996f2fce5f41d669a08f9f766c65f43291530 | [
"BSD-3-Clause"
] | null | null | null | /* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
*
* Drizzle Client & Protocol Library
*
* Copyright (C) 2012-2013 Drizzle Developer Group
* 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.
*
* * The names of its contributors may not 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 "config.h"
#include "libdrizzle/common.h"
/* Internal function */
drizzle_return_t drizzle_stmt_set_param(drizzle_stmt_st *stmt, uint16_t param_num, drizzle_column_type_t type, void *data, uint32_t length, bool is_unsigned)
{
if ((stmt == NULL) || (param_num >= stmt->param_count) || (data == NULL))
{
return DRIZZLE_RETURN_INVALID_ARGUMENT;
}
if (stmt->state < DRIZZLE_STMT_PREPARED)
{
drizzle_set_error(stmt->con, __func__, "stmt object has bot been prepared");
return DRIZZLE_RETURN_STMT_ERROR;
}
stmt->query_params[param_num].type= type;
stmt->query_params[param_num].data= data;
stmt->query_params[param_num].length= length;
stmt->query_params[param_num].options.is_unsigned= is_unsigned;
stmt->query_params[param_num].is_bound= true;
return DRIZZLE_RETURN_OK;
}
drizzle_return_t drizzle_stmt_set_tiny(drizzle_stmt_st *stmt, uint16_t param_num, uint8_t value, bool is_unsigned)
{
uint8_t *val;
val= (uint8_t*) stmt->query_params[param_num].data_buffer;
*val= value;
return drizzle_stmt_set_param(stmt, param_num, DRIZZLE_COLUMN_TYPE_TINY, val, 1, is_unsigned);
}
drizzle_return_t drizzle_stmt_set_short(drizzle_stmt_st *stmt, uint16_t param_num, uint16_t value, bool is_unsigned)
{
uint16_t *val;
val= (uint16_t*) stmt->query_params[param_num].data_buffer;
*val= value;
return drizzle_stmt_set_param(stmt, param_num, DRIZZLE_COLUMN_TYPE_SHORT, val, 2, is_unsigned);
}
drizzle_return_t drizzle_stmt_set_int(drizzle_stmt_st *stmt, uint16_t param_num, uint32_t value, bool is_unsigned)
{
uint32_t *val;
val= (uint32_t*) stmt->query_params[param_num].data_buffer;
*val= value;
return drizzle_stmt_set_param(stmt, param_num, DRIZZLE_COLUMN_TYPE_LONG, val, 4, is_unsigned);
}
drizzle_return_t drizzle_stmt_set_bigint(drizzle_stmt_st *stmt, uint16_t param_num, uint64_t value, bool is_unsigned)
{
uint64_t *val;
val= (uint64_t*) stmt->query_params[param_num].data_buffer;
*val= value;
return drizzle_stmt_set_param(stmt, param_num, DRIZZLE_COLUMN_TYPE_LONGLONG, val, 8, is_unsigned);
}
drizzle_return_t drizzle_stmt_set_double(drizzle_stmt_st *stmt, uint16_t param_num, double value)
{
double *val;
val= (double*) stmt->query_params[param_num].data_buffer;
*val= value;
return drizzle_stmt_set_param(stmt, param_num, DRIZZLE_COLUMN_TYPE_DOUBLE, val, 8, false);
}
drizzle_return_t drizzle_stmt_set_float(drizzle_stmt_st *stmt, uint16_t param_num, float value)
{
float *val;
val= (float*) stmt->query_params[param_num].data_buffer;
*val= value;
return drizzle_stmt_set_param(stmt, param_num, DRIZZLE_COLUMN_TYPE_FLOAT, val, 4, false);
}
drizzle_return_t drizzle_stmt_set_string(drizzle_stmt_st *stmt, uint16_t param_num, char *value, size_t length)
{
return drizzle_stmt_set_param(stmt, param_num, DRIZZLE_COLUMN_TYPE_STRING, value, length, false);
}
drizzle_return_t drizzle_stmt_set_null(drizzle_stmt_st *stmt, uint16_t param_num)
{
return drizzle_stmt_set_param(stmt, param_num, DRIZZLE_COLUMN_TYPE_NULL, NULL, 0, false);
}
drizzle_return_t drizzle_stmt_set_time(drizzle_stmt_st *stmt, uint16_t param_num, uint32_t days, uint8_t hours, uint8_t minutes, uint8_t seconds, uint32_t microseconds, bool is_negative)
{
drizzle_datetime_st *time;
time= (drizzle_datetime_st*) stmt->query_params[param_num].data_buffer;
time->negative= is_negative;
time->day= days;
time->hour= hours;
time->minute= minutes;
time->second= seconds;
time->microsecond= microseconds;
/* Length not important because we will figure that out when packing */
return drizzle_stmt_set_param(stmt, param_num, DRIZZLE_COLUMN_TYPE_TIME, time, 0, false);
}
drizzle_return_t drizzle_stmt_set_timestamp(drizzle_stmt_st *stmt, uint16_t param_num, uint16_t year, uint8_t month, uint8_t day, uint8_t hours, uint8_t minutes, uint8_t seconds, uint32_t microseconds)
{
drizzle_datetime_st *timestamp;
timestamp= (drizzle_datetime_st*) stmt->query_params[param_num].data_buffer;
timestamp->negative= false;
timestamp->year= year;
timestamp->day= day;
timestamp->month= month;
timestamp->year= year;
timestamp->hour= hours;
timestamp->minute= minutes;
timestamp->second= seconds;
timestamp->microsecond= microseconds;
/* Length not important because we will figure that out when packing */
return drizzle_stmt_set_param(stmt, param_num, DRIZZLE_COLUMN_TYPE_TIME, timestamp, 0, false);
}
bool drizzle_stmt_get_is_null_from_name(drizzle_stmt_st *stmt, const char *column_name, drizzle_return_t *ret_ptr)
{
uint16_t column_number;
if ((stmt == NULL) || (stmt->result_params == NULL))
{
*ret_ptr= DRIZZLE_RETURN_INVALID_ARGUMENT;
}
column_number= drizzle_stmt_column_lookup(stmt->prepare_result, column_name, ret_ptr);
if (*ret_ptr != DRIZZLE_RETURN_OK)
{
return 0;
}
return drizzle_stmt_get_is_null(stmt, column_number, ret_ptr);
}
bool drizzle_stmt_get_is_null(drizzle_stmt_st *stmt, uint16_t column_number, drizzle_return_t *ret_ptr)
{
if ((stmt == NULL) || (stmt->result_params == NULL) || (column_number >= stmt->execute_result->column_count))
{
*ret_ptr= DRIZZLE_RETURN_INVALID_ARGUMENT;
return false;
}
*ret_ptr= DRIZZLE_RETURN_OK;
return stmt->result_params[column_number].options.is_null;
}
bool drizzle_stmt_get_is_unsigned_from_name(drizzle_stmt_st *stmt, const char *column_name, drizzle_return_t *ret_ptr)
{
uint16_t column_number;
if ((stmt == NULL) || (stmt->result_params == NULL))
{
*ret_ptr= DRIZZLE_RETURN_INVALID_ARGUMENT;
}
column_number= drizzle_stmt_column_lookup(stmt->prepare_result, column_name, ret_ptr);
if (*ret_ptr != DRIZZLE_RETURN_OK)
{
return 0;
}
return drizzle_stmt_get_is_unsigned(stmt, column_number, ret_ptr);
}
bool drizzle_stmt_get_is_unsigned(drizzle_stmt_st *stmt, uint16_t column_number, drizzle_return_t *ret_ptr)
{
if ((stmt == NULL) || (stmt->result_params == NULL) || (column_number >= stmt->execute_result->column_count))
{
*ret_ptr= DRIZZLE_RETURN_INVALID_ARGUMENT;
return false;
}
*ret_ptr= DRIZZLE_RETURN_OK;
return stmt->result_params[column_number].options.is_unsigned;
}
const char *drizzle_stmt_get_string_from_name(drizzle_stmt_st *stmt, const char *column_name, size_t *len, drizzle_return_t *ret_ptr)
{
uint16_t column_number;
if ((stmt == NULL) || (stmt->result_params == NULL))
{
*ret_ptr= DRIZZLE_RETURN_INVALID_ARGUMENT;
}
column_number= drizzle_stmt_column_lookup(stmt->prepare_result, column_name, ret_ptr);
if (*ret_ptr != DRIZZLE_RETURN_OK)
{
return 0;
}
return drizzle_stmt_get_string(stmt, column_number, len, ret_ptr);
}
const char *drizzle_stmt_get_string(drizzle_stmt_st *stmt, uint16_t column_number, size_t *len, drizzle_return_t *ret_ptr)
{
char *val;
drizzle_bind_st *param;
if ((stmt == NULL) || (stmt->result_params == NULL) || (column_number >= stmt->execute_result->column_count))
{
*len= 0;
*ret_ptr= DRIZZLE_RETURN_INVALID_ARGUMENT;
return NULL;
}
param= &stmt->result_params[column_number];
*ret_ptr= DRIZZLE_RETURN_OK;
switch(param->type)
{
case DRIZZLE_COLUMN_TYPE_NULL:
*ret_ptr= DRIZZLE_RETURN_NULL_SIZE;
val= 0;
break;
case DRIZZLE_COLUMN_TYPE_TINY:
val= long_to_string(param, (uint32_t)(*(uint8_t*)param->data));
*len= strlen(val);
break;
case DRIZZLE_COLUMN_TYPE_SHORT:
case DRIZZLE_COLUMN_TYPE_YEAR:
val= long_to_string(param, (uint32_t)(*(uint16_t*)param->data));
*len= strlen(val);
break;
case DRIZZLE_COLUMN_TYPE_INT24:
case DRIZZLE_COLUMN_TYPE_LONG:
val= long_to_string(param, *(uint32_t*)param->data);
*len= strlen(val);
break;
case DRIZZLE_COLUMN_TYPE_LONGLONG:
val= longlong_to_string(param, *(uint64_t*)param->data);
*len= strlen(val);
break;
case DRIZZLE_COLUMN_TYPE_FLOAT:
val= double_to_string(param, (double) (*(float*)param->data));
*len= strlen(val);
break;
case DRIZZLE_COLUMN_TYPE_DOUBLE:
val= double_to_string(param, *(double*)param->data);
*len= strlen(val);
break;
case DRIZZLE_COLUMN_TYPE_TIME:
val= time_to_string(param, (drizzle_datetime_st*)param->data);
*len= strlen(val);
break;
case DRIZZLE_COLUMN_TYPE_DATE:
case DRIZZLE_COLUMN_TYPE_DATETIME:
case DRIZZLE_COLUMN_TYPE_TIMESTAMP:
val= timestamp_to_string(param, (drizzle_datetime_st*)param->data);
*len= strlen(val);
break;
case DRIZZLE_COLUMN_TYPE_TINY_BLOB:
case DRIZZLE_COLUMN_TYPE_MEDIUM_BLOB:
case DRIZZLE_COLUMN_TYPE_LONG_BLOB:
case DRIZZLE_COLUMN_TYPE_BLOB:
case DRIZZLE_COLUMN_TYPE_BIT:
case DRIZZLE_COLUMN_TYPE_STRING:
case DRIZZLE_COLUMN_TYPE_VAR_STRING:
case DRIZZLE_COLUMN_TYPE_DECIMAL:
case DRIZZLE_COLUMN_TYPE_NEWDECIMAL:
val= (char*)param->data;
*len= param->length;
break;
case DRIZZLE_COLUMN_TYPE_NEWDATE:
case DRIZZLE_COLUMN_TYPE_VARCHAR:
case DRIZZLE_COLUMN_TYPE_ENUM:
case DRIZZLE_COLUMN_TYPE_SET:
case DRIZZLE_COLUMN_TYPE_GEOMETRY:
case DRIZZLE_COLUMN_TYPE_TIMESTAMP2:
case DRIZZLE_COLUMN_TYPE_DATETIME2:
case DRIZZLE_COLUMN_TYPE_TIME2:
default:
*ret_ptr= DRIZZLE_RETURN_INVALID_CONVERSION;
val= NULL;
*len= 0;
}
return val;
}
uint32_t drizzle_stmt_get_int_from_name(drizzle_stmt_st *stmt, const char *column_name, drizzle_return_t *ret_ptr)
{
uint16_t column_number;
if ((stmt == NULL) || (stmt->result_params == NULL))
{
*ret_ptr= DRIZZLE_RETURN_INVALID_ARGUMENT;
}
column_number= drizzle_stmt_column_lookup(stmt->prepare_result, column_name, ret_ptr);
if (*ret_ptr != DRIZZLE_RETURN_OK)
{
return 0;
}
return drizzle_stmt_get_int(stmt, column_number, ret_ptr);
}
uint32_t drizzle_stmt_get_int(drizzle_stmt_st *stmt, uint16_t column_number, drizzle_return_t *ret_ptr)
{
uint32_t val;
drizzle_bind_st *param;
if ((stmt == NULL) || (stmt->result_params == NULL) || (column_number >= stmt->execute_result->column_count))
{
*ret_ptr= DRIZZLE_RETURN_INVALID_ARGUMENT;
return 0;
}
param= &stmt->result_params[column_number];
*ret_ptr= DRIZZLE_RETURN_OK;
switch(param->type)
{
case DRIZZLE_COLUMN_TYPE_NULL:
*ret_ptr= DRIZZLE_RETURN_NULL_SIZE;
val= 0;
break;
case DRIZZLE_COLUMN_TYPE_TINY:
val= (uint32_t) (*(uint8_t*)param->data);
break;
case DRIZZLE_COLUMN_TYPE_SHORT:
case DRIZZLE_COLUMN_TYPE_YEAR:
val= (uint32_t) (*(uint16_t*)param->data);
break;
case DRIZZLE_COLUMN_TYPE_INT24:
case DRIZZLE_COLUMN_TYPE_LONG:
val= (uint32_t) (*(uint32_t*)param->data);
break;
case DRIZZLE_COLUMN_TYPE_LONGLONG:
val= (uint32_t) (*(uint64_t*)param->data);
if (val > UINT32_MAX)
{
*ret_ptr= DRIZZLE_RETURN_TRUNCATED;
}
break;
case DRIZZLE_COLUMN_TYPE_FLOAT:
*ret_ptr= DRIZZLE_RETURN_TRUNCATED;
val= (uint32_t) (*(float*)param->data);
break;
case DRIZZLE_COLUMN_TYPE_DOUBLE:
*ret_ptr= DRIZZLE_RETURN_TRUNCATED;
val= (uint32_t) (*(double*)param->data);
break;
case DRIZZLE_COLUMN_TYPE_TIME:
case DRIZZLE_COLUMN_TYPE_DATE:
case DRIZZLE_COLUMN_TYPE_DATETIME:
case DRIZZLE_COLUMN_TYPE_TIMESTAMP:
case DRIZZLE_COLUMN_TYPE_TINY_BLOB:
case DRIZZLE_COLUMN_TYPE_MEDIUM_BLOB:
case DRIZZLE_COLUMN_TYPE_LONG_BLOB:
case DRIZZLE_COLUMN_TYPE_BLOB:
case DRIZZLE_COLUMN_TYPE_BIT:
case DRIZZLE_COLUMN_TYPE_STRING:
case DRIZZLE_COLUMN_TYPE_VAR_STRING:
case DRIZZLE_COLUMN_TYPE_DECIMAL:
case DRIZZLE_COLUMN_TYPE_NEWDECIMAL:
case DRIZZLE_COLUMN_TYPE_NEWDATE:
case DRIZZLE_COLUMN_TYPE_VARCHAR:
case DRIZZLE_COLUMN_TYPE_ENUM:
case DRIZZLE_COLUMN_TYPE_SET:
case DRIZZLE_COLUMN_TYPE_GEOMETRY:
case DRIZZLE_COLUMN_TYPE_TIMESTAMP2:
case DRIZZLE_COLUMN_TYPE_DATETIME2:
case DRIZZLE_COLUMN_TYPE_TIME2:
default:
*ret_ptr= DRIZZLE_RETURN_INVALID_CONVERSION;
val= 0;
}
return val;
}
uint64_t drizzle_stmt_get_bigint_from_name(drizzle_stmt_st *stmt, const char *column_name, drizzle_return_t *ret_ptr)
{
uint16_t column_number;
if ((stmt == NULL) || (stmt->result_params == NULL))
{
*ret_ptr= DRIZZLE_RETURN_INVALID_ARGUMENT;
}
column_number= drizzle_stmt_column_lookup(stmt->prepare_result, column_name, ret_ptr);
if (*ret_ptr != DRIZZLE_RETURN_OK)
{
return 0;
}
return drizzle_stmt_get_bigint(stmt, column_number, ret_ptr);
}
uint64_t drizzle_stmt_get_bigint(drizzle_stmt_st *stmt, uint16_t column_number, drizzle_return_t *ret_ptr)
{
uint32_t val;
drizzle_bind_st *param;
if ((stmt == NULL) || (stmt->result_params == NULL) || (column_number >= stmt->execute_result->column_count))
{
*ret_ptr= DRIZZLE_RETURN_INVALID_ARGUMENT;
return 0;
}
param= &stmt->result_params[column_number];
*ret_ptr= DRIZZLE_RETURN_OK;
switch(param->type)
{
case DRIZZLE_COLUMN_TYPE_NULL:
*ret_ptr= DRIZZLE_RETURN_NULL_SIZE;
val= 0;
break;
case DRIZZLE_COLUMN_TYPE_TINY:
val= (uint64_t) (*(uint8_t*)param->data);
break;
case DRIZZLE_COLUMN_TYPE_SHORT:
case DRIZZLE_COLUMN_TYPE_YEAR:
val= (uint64_t) (*(uint16_t*)param->data);
break;
case DRIZZLE_COLUMN_TYPE_INT24:
case DRIZZLE_COLUMN_TYPE_LONG:
val= (uint64_t) (*(uint32_t*)param->data);
break;
case DRIZZLE_COLUMN_TYPE_LONGLONG:
val= (uint64_t) (*(uint64_t*)param->data);
break;
case DRIZZLE_COLUMN_TYPE_FLOAT:
*ret_ptr= DRIZZLE_RETURN_TRUNCATED;
val= (uint64_t) (*(float*)param->data);
break;
case DRIZZLE_COLUMN_TYPE_DOUBLE:
*ret_ptr= DRIZZLE_RETURN_TRUNCATED;
val= (uint64_t) (*(double*)param->data);
break;
case DRIZZLE_COLUMN_TYPE_TIME:
case DRIZZLE_COLUMN_TYPE_DATE:
case DRIZZLE_COLUMN_TYPE_DATETIME:
case DRIZZLE_COLUMN_TYPE_TIMESTAMP:
case DRIZZLE_COLUMN_TYPE_TINY_BLOB:
case DRIZZLE_COLUMN_TYPE_MEDIUM_BLOB:
case DRIZZLE_COLUMN_TYPE_LONG_BLOB:
case DRIZZLE_COLUMN_TYPE_BLOB:
case DRIZZLE_COLUMN_TYPE_BIT:
case DRIZZLE_COLUMN_TYPE_STRING:
case DRIZZLE_COLUMN_TYPE_VAR_STRING:
case DRIZZLE_COLUMN_TYPE_DECIMAL:
case DRIZZLE_COLUMN_TYPE_NEWDECIMAL:
case DRIZZLE_COLUMN_TYPE_NEWDATE:
case DRIZZLE_COLUMN_TYPE_VARCHAR:
case DRIZZLE_COLUMN_TYPE_ENUM:
case DRIZZLE_COLUMN_TYPE_SET:
case DRIZZLE_COLUMN_TYPE_GEOMETRY:
case DRIZZLE_COLUMN_TYPE_TIMESTAMP2:
case DRIZZLE_COLUMN_TYPE_DATETIME2:
case DRIZZLE_COLUMN_TYPE_TIME2:
default:
*ret_ptr= DRIZZLE_RETURN_INVALID_CONVERSION;
val= 0;
}
return val;
}
double drizzle_stmt_get_double_from_name(drizzle_stmt_st *stmt, const char *column_name, drizzle_return_t *ret_ptr)
{
uint16_t column_number;
if ((stmt == NULL) || (stmt->result_params == NULL))
{
*ret_ptr= DRIZZLE_RETURN_INVALID_ARGUMENT;
}
column_number= drizzle_stmt_column_lookup(stmt->prepare_result, column_name, ret_ptr);
if (*ret_ptr != DRIZZLE_RETURN_OK)
{
return 0;
}
return drizzle_stmt_get_double(stmt, column_number, ret_ptr);
}
double drizzle_stmt_get_double(drizzle_stmt_st *stmt, uint16_t column_number, drizzle_return_t *ret_ptr)
{
double val;
drizzle_bind_st *param;
if ((stmt == NULL) || (stmt->result_params == NULL) || (column_number >= stmt->execute_result->column_count))
{
*ret_ptr= DRIZZLE_RETURN_INVALID_ARGUMENT;
return 0;
}
param= &stmt->result_params[column_number];
*ret_ptr= DRIZZLE_RETURN_OK;
switch(param->type)
{
case DRIZZLE_COLUMN_TYPE_NULL:
*ret_ptr= DRIZZLE_RETURN_NULL_SIZE;
val= 0;
break;
case DRIZZLE_COLUMN_TYPE_TINY:
*ret_ptr= DRIZZLE_RETURN_TRUNCATED;
val= (double) (*(uint8_t*)param->data);
break;
case DRIZZLE_COLUMN_TYPE_SHORT:
case DRIZZLE_COLUMN_TYPE_YEAR:
*ret_ptr= DRIZZLE_RETURN_TRUNCATED;
val= (double) (*(uint16_t*)param->data);
break;
case DRIZZLE_COLUMN_TYPE_INT24:
case DRIZZLE_COLUMN_TYPE_LONG:
*ret_ptr= DRIZZLE_RETURN_TRUNCATED;
val= (double) (*(uint32_t*)param->data);
break;
case DRIZZLE_COLUMN_TYPE_LONGLONG:
*ret_ptr= DRIZZLE_RETURN_TRUNCATED;
val= (double) (*(uint64_t*)param->data);
break;
case DRIZZLE_COLUMN_TYPE_FLOAT:
val= (double) (*(float*)param->data);
break;
case DRIZZLE_COLUMN_TYPE_DOUBLE:
val= (uint32_t) (*(double*)param->data);
break;
case DRIZZLE_COLUMN_TYPE_TIME:
case DRIZZLE_COLUMN_TYPE_DATE:
case DRIZZLE_COLUMN_TYPE_DATETIME:
case DRIZZLE_COLUMN_TYPE_TIMESTAMP:
case DRIZZLE_COLUMN_TYPE_TINY_BLOB:
case DRIZZLE_COLUMN_TYPE_MEDIUM_BLOB:
case DRIZZLE_COLUMN_TYPE_LONG_BLOB:
case DRIZZLE_COLUMN_TYPE_BLOB:
case DRIZZLE_COLUMN_TYPE_BIT:
case DRIZZLE_COLUMN_TYPE_STRING:
case DRIZZLE_COLUMN_TYPE_VAR_STRING:
case DRIZZLE_COLUMN_TYPE_DECIMAL:
case DRIZZLE_COLUMN_TYPE_NEWDECIMAL:
case DRIZZLE_COLUMN_TYPE_NEWDATE:
case DRIZZLE_COLUMN_TYPE_VARCHAR:
case DRIZZLE_COLUMN_TYPE_ENUM:
case DRIZZLE_COLUMN_TYPE_SET:
case DRIZZLE_COLUMN_TYPE_GEOMETRY:
case DRIZZLE_COLUMN_TYPE_TIMESTAMP2:
case DRIZZLE_COLUMN_TYPE_DATETIME2:
case DRIZZLE_COLUMN_TYPE_TIME2:
default:
*ret_ptr= DRIZZLE_RETURN_INVALID_CONVERSION;
val= 0;
}
return val;
}
char *long_to_string(drizzle_bind_st *param, uint32_t val)
{
/* Pick an empty point in the buffer to make the str */
char* buffer= param->data_buffer + 50;
if (param->options.is_unsigned)
{
snprintf(buffer, 12, "%"PRIu32, val);
}
else
{
snprintf(buffer, 12, "%"PRId32, (int32_t)val);
}
return buffer;
}
char *longlong_to_string(drizzle_bind_st *param, uint64_t val)
{
/* Max length is -INT64_MAX + NUL = 21 */
char* buffer= param->data_buffer + 50;
if (param->options.is_unsigned)
{
snprintf(buffer, 21, "%"PRIu64, val);
}
else
{
snprintf(buffer, 21, "%"PRId64, (int64_t)val);
}
return buffer;
}
char *double_to_string(drizzle_bind_st *param, double val)
{
/* Max length is 23 */
char* buffer= param->data_buffer + 50;
snprintf(buffer, 23, "%f", val);
return buffer;
}
char *time_to_string(drizzle_bind_st *param, drizzle_datetime_st *time)
{
/* Max time is -HHH:MM:SS.ssssss + NUL = 17 */
char* buffer= param->data_buffer + 50;
if (time->microsecond == 0)
{
snprintf(buffer, 17, "%s%"PRIu16":%"PRIu8":%"PRIu8, (time->negative) ? "-" : "", time->hour, time->minute, time->second);
}
else
{
snprintf(buffer, 17, "%s%"PRIu16":%"PRIu8":%"PRIu8".%"PRIu32, (time->negative) ? "-" : "", time->hour, time->minute, time->second, time->microsecond);
}
return buffer;
}
char *timestamp_to_string(drizzle_bind_st *param, drizzle_datetime_st *timestamp)
{
/* Max timestamp is YYYY-MM-DD HH:MM:SS.ssssss + NUL = 26 */
char* buffer= param->data_buffer + 50;
if (timestamp->microsecond == 0)
{
snprintf(buffer, 26, "%"PRIu16"-%"PRIu8"-%"PRIu32" %"PRIu16":%"PRIu8":%"PRIu8, timestamp->year, timestamp->month, timestamp->day, timestamp->hour, timestamp->minute, timestamp->second);
}
else
{
snprintf(buffer, 26, "%"PRIu16"-%"PRIu8"-%"PRIu32" %"PRIu16":%"PRIu8":%"PRIu8".%"PRIu32, timestamp->year, timestamp->month, timestamp->day, timestamp->hour, timestamp->minute, timestamp->second, timestamp->microsecond);
}
return buffer;
}
uint16_t drizzle_stmt_column_lookup(drizzle_result_st *result, const char *column_name, drizzle_return_t *ret_ptr)
{
uint16_t current_column;
for (current_column= 0; current_column < result->column_count; current_column++)
{
if (strncmp(column_name, result->column_buffer[current_column].name, DRIZZLE_MAX_COLUMN_NAME_SIZE) == 0)
{
*ret_ptr= DRIZZLE_RETURN_OK;
return current_column;
}
}
*ret_ptr= DRIZZLE_RETURN_NOT_FOUND;
return 0;
}
| 32.878049 | 223 | 0.732984 | [
"object"
] |
927edc3d260bc06ae76025fa2cc2eb0eda0bee79 | 1,243 | cpp | C++ | Lumos/Source/Lumos/Core/LMLog.cpp | perefm/Lumos | 2f0ae4d0bad1447b5318043500751be1753666a2 | [
"MIT"
] | 672 | 2019-01-29T18:14:40.000Z | 2022-03-31T20:38:40.000Z | Lumos/Source/Lumos/Core/LMLog.cpp | gameconstructer/Lumos | 92f6e812fdfc9404bf557e131679ae9071f25c80 | [
"MIT"
] | 25 | 2019-10-05T17:16:13.000Z | 2021-12-29T01:40:04.000Z | Lumos/Source/Lumos/Core/LMLog.cpp | gameconstructer/Lumos | 92f6e812fdfc9404bf557e131679ae9071f25c80 | [
"MIT"
] | 83 | 2019-03-13T14:11:12.000Z | 2022-03-30T02:52:49.000Z | #include "Precompiled.h"
#include "LMLog.h"
#include <spdlog/sinks/rotating_file_sink.h>
#include <spdlog/sinks/stdout_color_sinks.h>
namespace Lumos::Debug
{
std::shared_ptr<spdlog::logger> Log::s_CoreLogger;
std::vector<spdlog::sink_ptr> sinks;
void Log::OnInit()
{
sinks.emplace_back(std::make_shared<spdlog::sinks::stdout_color_sink_mt>()); // debug
//sinks.emplace_back(std::make_shared<ImGuiConsoleSink_mt>()); // ImGuiConsole
#ifndef LUMOS_PLATFORM_IOS
//auto logFileSink = std::make_shared<spdlog::sinks::rotating_file_sink_mt>("LumosLog.txt", 1048576 * 5, 3);
//sinks.emplace_back(logFileSink); // Log file
#endif
// create the loggers
s_CoreLogger = std::make_shared<spdlog::logger>("Lumos", begin(sinks), end(sinks));
spdlog::register_logger(s_CoreLogger);
// configure the loggers
spdlog::set_pattern("%^[%T] %v%$");
s_CoreLogger->set_level(spdlog::level::trace);
}
void Log::AddSink(spdlog::sink_ptr& sink)
{
s_CoreLogger->sinks().push_back(sink);
s_CoreLogger->set_pattern("%^[%T] %v%$");
}
void Log::OnRelease()
{
s_CoreLogger.reset();
spdlog::shutdown();
}
}
| 28.906977 | 116 | 0.6428 | [
"vector"
] |
928086a430569621c22847400f4fdd41b2c473fc | 34,626 | cc | C++ | src/Buffer.cc | rohankumardubey/ramcloud | 3a30ba5edc4a81d5e12ab20fda0360cb9bacf50f | [
"0BSD"
] | 5 | 2015-11-14T16:49:06.000Z | 2019-09-03T13:21:30.000Z | src/Buffer.cc | rohankumardubey/ramcloud | 3a30ba5edc4a81d5e12ab20fda0360cb9bacf50f | [
"0BSD"
] | null | null | null | src/Buffer.cc | rohankumardubey/ramcloud | 3a30ba5edc4a81d5e12ab20fda0360cb9bacf50f | [
"0BSD"
] | 1 | 2018-02-25T11:16:27.000Z | 2018-02-25T11:16:27.000Z | /* Copyright (c) 2010 Stanford University
*
* Permission to use, copy, modify, and distribute this software for any purpose
* with or without fee is hereby granted, provided that the above copyright
* notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <string.h>
#include <algorithm>
#include "Buffer.h"
#include "Memory.h"
namespace RAMCloud {
/**
* Malloc and construct an Allocation.
* \param[in] prependSize
* See constructor.
* \param[in] totalSize
* See constructor. Will round-up to the nearest 8 bytes.
*/
Buffer::Allocation*
Buffer::Allocation::newAllocation(uint32_t prependSize, uint32_t totalSize) {
totalSize = (totalSize + 7) & ~7U;
void* a = Memory::xmalloc(HERE, sizeof(Allocation) + totalSize);
return new(a) Allocation(prependSize, totalSize);
}
/**
* Constructor for Allocation.
* The Allocation must be 8-byte aligned.
* \param[in] prependSize
* The number of bytes of the Allocation for prepend data. The rest will
* be used for append data and Chunk instances.
* \param[in] totalSize
* The number of bytes of total data the Allocation manages. The
* Allocation will assume it can use totalSize bytes directly following
* itself (i.e., the caller has allocated sizeof(Allocation) + totalSize).
* Must be 8-byte aligned.
*/
Buffer::Allocation::Allocation(uint32_t prependSize, uint32_t totalSize)
: next(NULL),
prependTop(prependSize),
appendTop(prependSize),
chunkTop(totalSize) {
assert((reinterpret_cast<uint64_t>(this) & 0x7) == 0);
assert((totalSize & 0x7) == 0);
assert(prependSize <= totalSize);
}
/**
* Destructor for Allocation.
*/
Buffer::Allocation::~Allocation() {
}
/**
* Reinitialize an Allocation, as if it had been newly constructed.
* \param[in] prependSize
* The number of bytes of the Allocation for prepend data. Same
* meaning as constructor argument.
* \param[in] totalSize
* The number of bytes of total data the Allocation manages. Same
* meaning as constructor argument.
*/
void
Buffer::Allocation::reset(uint32_t prependSize, uint32_t totalSize)
{
next = NULL;
prependTop = prependSize;
appendTop = prependSize;
chunkTop = totalSize;
assert((totalSize & 0x7) == 0);
assert(prependSize <= totalSize);
}
/**
* Try to allocate space for prepend data of a given size.
* \param[in] size The size in bytes to allocate for prepend data.
* \return A pointer to the allocated space or \c NULL if there is not enough
* space in this Allocation.
*/
void*
Buffer::Allocation::allocatePrepend(uint32_t size) {
if (prependTop < size)
return NULL;
prependTop = static_cast<DataIndex>(prependTop - size);
return &data[prependTop];
}
/**
* Try to allocate space for append data of a given size.
* \param[in] size The size in bytes to allocate for append data.
* \return A pointer to the allocated space or \c NULL if there is not enough
* space in this Allocation.
*/
void*
Buffer::Allocation::allocateAppend(uint32_t size) {
if (static_cast<DataIndex>(chunkTop - appendTop) < size)
return NULL;
char *retVal = &data[appendTop];
appendTop = static_cast<DataIndex>(appendTop + size);
return retVal;
}
/**
* Try to allocate space for a chunk of a given size.
* \param[in] size The size in bytes to allocate for a chunk.
* \return A pointer to the allocated space or \c NULL if there is not enough
* space in this Allocation.
*/
void*
Buffer::Allocation::allocateChunk(uint32_t size) {
size = (size + 7) & ~7U;
if (static_cast<DataIndex>(chunkTop - appendTop) < size)
return NULL;
chunkTop = static_cast<DataIndex>(chunkTop - size);
assert((chunkTop & 7) == 0);
return &data[chunkTop];
}
/**
* This constructor initializes an empty Buffer.
*/
Buffer::Buffer()
: totalLength(0), numberChunks(0), chunks(NULL), chunksTail(NULL),
initialAllocationContainer(),
allocations(&initialAllocationContainer.allocation),
nextAllocationSize(INITIAL_ALLOCATION_SIZE << 1) {
assert((reinterpret_cast<uint64_t>(allocations) & 7) == 0);
}
/**
* Deallocate the memory allocated by this Buffer.
*/
Buffer::~Buffer() {
reset();
}
/**
* Truncate the buffer to zero length and free all resources associated
* with it. The Buffer will end up in the same state it had immediately
* after initial construction.
*/
void
Buffer::reset() {
{ // free the list of chunks
Chunk* current = chunks;
while (current != NULL) {
Chunk* next;
next = current->next;
current->~Chunk();
current = next;
}
}
{ // free the list of allocations
Allocation* current = allocations;
// Skip the last allocation in the list (initialAllocationContainer's
// allocation) since it's not allocated with xmalloc.
if (current != NULL) {
while (current->next != NULL) {
Allocation* next;
next = current->next;
free(current);
current = next;
}
}
}
// Restore state to what it was at construction time.
totalLength = 0;
numberChunks = 0;
chunks = NULL;
chunksTail = NULL;
initialAllocationContainer.reset();
allocations = &initialAllocationContainer.allocation;
nextAllocationSize = INITIAL_ALLOCATION_SIZE << 1;
}
/**
* Prepend a new Allocation object to the #allocations list.
* This is used in #allocateChunk(), #allocatePrepend(), and #allocateAppend()
* when the existing Allocation(s) have run out of space.
* \param[in] minPrependSize
* The minimum size in bytes of the new Allocation's prepend data region.
* I got lazy, so either this or minAppendSize must be 0.
* \param[in] minAppendSize
* The minimum size in bytes of the new Allocation's append data/Chunk
* instance region. I got lazy, so either this or minPrependSize must be 0.
* \return
* The newly allocated Allocation object.
*/
Buffer::Allocation*
Buffer::newAllocation(uint32_t minPrependSize,
uint32_t minAppendSize) {
assert(minPrependSize == 0 || minAppendSize == 0);
uint32_t totalSize = nextAllocationSize;
uint32_t prependSize = totalSize >> 3;
nextAllocationSize <<= 1;
if (prependSize < minPrependSize) {
if (totalSize < minPrependSize)
totalSize = minPrependSize;
prependSize = minPrependSize;
}
if ((totalSize - prependSize) < minAppendSize) {
if (totalSize < minAppendSize)
totalSize = minAppendSize;
prependSize = totalSize - minAppendSize;
}
Allocation* newAllocation;
newAllocation = Allocation::newAllocation(prependSize, totalSize);
newAllocation->next = allocations;
allocations = newAllocation;
return newAllocation;
}
/**
* Allocate space for a Chunk instance that will be deallocated in the Buffer's
* destructor.
* \param[in] size The size in bytes to allocate for a chunk.
* \return A pointer to the allocated space (will never be \c NULL).
*/
// TODO(ongaro): Collect statistics on the distributions of sizes.
void*
Buffer::allocateChunk(uint32_t size) {
// Common case: allocate size bytes in the latest Allocation.
// It is perhaps wasteful of space to not try the other Allocations in
// the list if this fails, but the others are probably close to full
// anyway.
void* data;
if (allocations != NULL) {
data = allocations->allocateChunk(size);
if (data != NULL)
return data;
}
data = newAllocation(0, size)->allocateChunk(size);
assert(data != NULL);
return data;
}
/**
* Allocate space for prepend data that will be deallocated in the Buffer's
* destructor.
* \param[in] size The size in bytes to allocate for the prepend data.
* \return A pointer to the allocated space (will never be \c NULL).
*/
// TODO(ongaro): Collect statistics on the distributions of sizes.
void*
Buffer::allocatePrepend(uint32_t size) {
void* data;
if (allocations != NULL) {
data = allocations->allocatePrepend(size);
if (data != NULL)
return data;
}
data = newAllocation(size, 0)->allocatePrepend(size);
assert(data != NULL);
return data;
}
/**
* Allocate space for append data that will be deallocated in the Buffer's
* destructor.
* \param[in] size The size in bytes to allocate for the append data.
* \return A pointer to the allocated space (will never be \c NULL).
*/
// TODO(ongaro): Collect statistics on the distributions of sizes.
void*
Buffer::allocateAppend(uint32_t size) {
void* data;
if (allocations != NULL) {
data = allocations->allocateAppend(size);
if (data != NULL)
return data;
}
data = newAllocation(0, size)->allocateAppend(size);
assert(data != NULL);
return data;
}
/**
* Add a new memory chunk to front of the Buffer. The memory region physically
* described by the chunk will be added to the logical beginning of the Buffer.
*
* \param[in] newChunk
* The Chunk describing the memory region to be added. The caller must
* arrange for the memory storing this Chunk instance to extend through
* the life of this Buffer.
*/
void Buffer::prependChunk(Chunk* newChunk) {
++numberChunks;
totalLength += newChunk->length;
newChunk->next = chunks;
chunks = newChunk;
if (chunksTail == NULL)
chunksTail = newChunk;
}
/**
* Adds a new memory chunk to end of the Buffer. The memory region physically
* described by the chunk will be added to the logical end of the Buffer.
* See #prependChunk(), which is analogous.
*
* \param[in] newChunk
* See #prependChunk().
*/
void Buffer::appendChunk(Chunk* newChunk) {
++numberChunks;
totalLength += newChunk->length;
newChunk->next = NULL;
if (chunksTail == NULL)
chunks = newChunk;
else
chunksTail->next = newChunk;
chunksTail = newChunk;
}
/**
* Return a range of contiguous bytes at the requested location in the buffer.
* This is more efficient that #getRange() or #copy(), since a pointer is
* returned to existing memory (no copy is done).
*
* \param[in] offset The offset into the logical memory represented by
* this Buffer.
* \param[out] returnPtr A pointer to the first byte of the contiguous bytes
* available at the requested location, or NULL if the
* given offset is invalid. This is returned to the
* caller.
* \return The number of contiguous bytes available starting at \a returnPtr.
* \retval 0, if the given \a offset is invalid.
*/
uint32_t Buffer::peek(uint32_t offset, const void** returnPtr) {
for (Chunk* current = chunks; current != NULL; current = current->next) {
if (offset < current->length) {
*returnPtr = static_cast<const char*>(current->data) + offset;
return (current->length - offset);
}
offset -= current->length;
}
*returnPtr = NULL;
return 0;
}
/**
* Copies logically contiguous data starting from an offset into a given
* chunk. This is common code shared by #copy(uint32_t, uint32_t, void*) and
* #getRange().
*
* \param[in] start
* The first chunk in the Buffer having data to be copied out. This may
* not be \c NULL.
* \param[in] offset
* The physical offset relative to \a start of the first byte to be
* copied. The caller must ensure this offset is within the range of the
* \a start chunk.
* \param[in] length
* The number of bytes to copy from \a start and possibly subsequent
* chunks. The caller must ensure that this does not extend beyond the end
* of the Buffer.
* \param[in] dest
* The first byte where to copy the logical memory block. The caller must
* make sure that \a dest contains at least \a length bytes.
*/
void
Buffer::copyChunks(const Chunk* start, uint32_t offset, // NOLINT
uint32_t length, void* dest) const
{
assert(start != NULL && offset < start->length);
const Chunk* current = start;
uint32_t bytesRemaining = length;
// offset is the physical offset from 'current' at which to start copying.
// This may be non-zero for the first Chunk but will be 0 for every
// subsequent Chunk.
while (bytesRemaining > 0) {
uint32_t bytesFromCurrent = std::min(current->length - offset,
bytesRemaining);
memcpy(dest, static_cast<const char*>(current->data) + offset,
bytesFromCurrent);
dest = static_cast<char*>(dest) + bytesFromCurrent;
bytesRemaining -= bytesFromCurrent;
offset = 0;
current = current->next;
// The caller made sure length was within bounds,
// but I don't trust the caller.
assert(current != NULL || bytesRemaining == 0);
}
}
/**
* Make a range of logical memory available as contiguous bytes. If this range
* is not already contiguous, we copy it into a newly allocated region.
*
* Memory allocated by this function will not be deallocated until the Buffer is
* destructed, so too many calls to this function may eat up a lot of memory.
*
* \param[in] offset The offset into the logical Buffer.
* \param[in] length The length in bytes of the region we want to obtain.
* \return A pointer to the first byte of the requested range. This memory may
* be dynamically allocated, in which case it will exist only as long
* as the Buffer object exists.
* \retval NULL, if the <offset, length> tuple specified an invalid range of
* memory.
*/
const void* Buffer::getRange(uint32_t offset, uint32_t length) {
if (length == 0) return NULL;
if (offset + length > totalLength) return NULL;
Chunk* current = chunks;
while (offset >= current->length) {
offset -= current->length;
current = current->next;
}
if (offset + length <= current->length) { // no need to copy
const char* data = static_cast<const char*>(current->data);
return (data + offset);
} else {
char* data = new(this, MISC) char[length];
copyChunks(current, offset, length, data);
return data;
}
}
/**
* Copies the memory block identified by the <offset, length> tuple into the
* region pointed to by dest.
*
* If the <offset, length> memory block extends beyond the end of the logical
* Buffer, we copy all the bytes from offset up to the end of the Buffer.
*
* \param[in] offset The offset in the Buffer of the first byte to copy.
* \param[in] length The number of bytes to copy.
* \param[in] dest The pointer to which we should copy the logical memory
* block. The caller must make sure that 'dest' contains at
* least 'length' bytes.
* \return The actual number of bytes copied. This will be less than length if
* the requested range of bytes overshoots the end of the Buffer.
* \retval 0, if the given 'offset' is invalid.
*/
uint32_t Buffer::copy(uint32_t offset, uint32_t length,
void* dest) { // NOLINT
if (chunks == NULL || offset >= totalLength)
return 0;
if (offset + length > totalLength)
length = totalLength - offset;
Chunk* current = chunks;
while (offset >= current->length) {
offset -= current->length;
current = current->next;
}
copyChunks(current, offset, length, dest);
return length;
}
/**
* Add data specified in a string to the end of a buffer. This method
* was designed primarily for use in tests (e.g. to specify network
* packets).
*
* \param s
* Describes what to put in the buffer. Consists of one or more
* substrings separated by spaces:
* - If a substring starts with a digit or "-" it is assumed to
* be a decimal number, which is converted to a 4-byte signed
* integer in the buffer.
* - If a substring starts with "0x" it is assumed to be a
* hexadecimal number, which is converted to a 4-byte integer
* in the buffer.
* - Otherwise the characters of the substring are appended to
* the buffer, with an additional null terminating character.
*/
void
Buffer::fillFromString(const char* s) {
// Note: this method used to clear the buffer before adding the
// new data, but this breaks some uses, such as when MockTransport
// calls it (the buffer contains an RPC object in its MISC area,
// which get overwritten after a reset).
uint32_t i, length;
length = downCast<uint32_t>(strlen(s));
for (i = 0; i < length; ) {
char c = s[i];
if ((c == '0') && (s[i+1] == 'x')) {
// Hexadecimal number
int value = 0;
i += 2;
while (i < length) {
char c = s[i];
i++;
if (c == ' ') {
break;
}
if (c <= '9') {
value = 16*value + (c - '0');
} else if ((c >= 'a') && (c <= 'f')) {
value = 16*value + 10 + (c - 'a');
} else {
value = 16*value + 10 + (c - 'A');
}
}
*(new(this, APPEND) int32_t) = value;
} else if ((c == '-') || ((c >= '0') && (c <= '9'))) {
// Decimal number
int value = 0;
int sign = (c == '-') ? -1 : 1;
if (c == '-') {
sign = -1;
i++;
}
while (i < length) {
char c = s[i];
i++;
if (c == ' ') {
break;
}
value = 10*value + (c - '0');
}
*(new(this, APPEND) int32_t) = value * sign;
} else {
// String
while (i < length) {
char c = s[i];
i++;
if (c == ' ') {
break;
}
*(new(this, APPEND) char) = c;
}
*(new(this, APPEND) char) = 0;
}
}
}
/**
* Remove the first \a length bytes from the Buffer. This reduces the
* amount of information visible in the Buffer but does not free
* memory allocations such as those created with allocateChunk or
* allocateAppend.
* \param[in] length
* The number of bytes to be removed from the beginning of the Buffer.
* If this exceeds the size of the Buffer, the Buffer will become empty.
*/
void
Buffer::truncateFront(uint32_t length)
{
Chunk* current = chunks;
while (current != NULL) {
if (current->length <= length) {
totalLength -= current->length;
length -= current->length;
current->length = 0;
if (length == 0)
return;
current = current->next;
} else {
totalLength -= length;
current->data = static_cast<const char*>(current->data)
+ length;
current->length -= length;
return;
}
}
}
/**
* Remove the last \a length bytes from the Buffer. This reduces the
* amount of information visible in the Buffer but does not free
* memory allocations such as those created with allocateChunk or
* allocateAppend.
* \param[in] length
* The number of bytes to be removed from the end of the Buffer.
* If this exceeds the size of the Buffer, the Buffer will become empty.
*/
void
Buffer::truncateEnd(uint32_t length)
{
uint32_t truncateAfter = 0;
if (length < totalLength)
truncateAfter = totalLength - length;
Chunk* current = chunks;
while (current != NULL) {
if (current->length <= truncateAfter) {
truncateAfter -= current->length;
current = current->next;
if (truncateAfter == 0)
goto truncate_remaining;
} else {
totalLength += truncateAfter - current->length;
current->length = truncateAfter;
current = current->next;
goto truncate_remaining;
}
}
return;
truncate_remaining:
while (current != NULL) {
totalLength -= current->length;
current->length = 0;
current = current->next;
}
}
/**
* Create an iterator for the contents of a Buffer.
* The iterator starts on the first chunk of the Buffer, so you should use
* #isDone(), #getData(), and #getLength() before the first call to #next().
* \param buffer
* The Buffer over which to iterate.
*/
Buffer::Iterator::Iterator(const Buffer& buffer)
: current(buffer.chunks)
, currentOffset(0)
, length(buffer.totalLength)
, offset(0)
, numberChunks(buffer.numberChunks)
, numberChunksIsValid(true)
{
}
/**
* Construct an iterator that only walks chunks with data corresponding
* to a byte range in the Buffer.
*
* Any calls to getData(), getLength(), getNumberChunks(), or getTotalLength()
* are appropriately adjusted even when iteration end points don't correspond
* to chunk boundaries.
*
* \param buffer
* The Buffer over which to iterate.
* \param off
* The offset into the Buffer which should be returned by the first
* call to getData().
* \param len
* The number of bytes to iterate across before the iterator isDone().
* Notice if this exceeds the bounds of the buffer then isDone() may occur
* before len number of bytes have been iterated over.
*/
Buffer::Iterator::Iterator(const Buffer& buffer,
uint32_t off,
uint32_t len)
: current(buffer.chunks)
, currentOffset(0)
, length(len)
, offset(off)
, numberChunks(0)
, numberChunksIsValid(false)
{
// Clip offset and length if they are out of range.
offset = std::min(off, buffer.totalLength);
length = std::min(len, buffer.totalLength - offset);
// Advance Iterator up to the first chunk with data from the subrange.
while (!isDone() && currentOffset + current->length <= offset)
next();
}
/**
* Copy constructor for Buffer::Iterator.
*/
Buffer::Iterator::Iterator(const Iterator& other)
: current(other.current)
, currentOffset(other.currentOffset)
, length(other.length)
, offset(other.offset)
, numberChunks(other.numberChunks)
, numberChunksIsValid(other.numberChunksIsValid)
{
}
/**
* Destructor for Buffer::Iterator.
*/
Buffer::Iterator::~Iterator()
{
}
/**
* Assignment for Buffer::Iterator.
*/
Buffer::Iterator&
Buffer::Iterator::operator=(const Iterator& other)
{
if (&other == this)
return *this;
current = other.current;
currentOffset = other.currentOffset;
offset = other.offset;
length = other.length;
numberChunks = other.numberChunks;
return *this;
}
/**
* Return whether the current chunk is past the end of the Buffer or
* requested subrange.
* \return
* Whether the current chunk is past the end of the Buffer or
* requested subrange. If this is \c true, it is illegal to
* use #next(), #getData(), and #getLength().
*/
bool
Buffer::Iterator::isDone() const
{
// Done if the current chunk start is beyond end point
return currentOffset >= offset + length;
}
/**
* Advance to the next chunk in the Buffer.
*/
void
Buffer::Iterator::next()
{
if (isDone())
return;
currentOffset += current->length;
current = current->next;
}
/**
* Return a pointer to the first byte of data in the current chunk that is
* part of the range of iteration. If this iterator is covering only a
* subrange of the buffer, then this may not be the first byte in the chunk.
*/
const void*
Buffer::Iterator::getData() const
{
uint32_t startOffset = 0;
uint32_t endOfCurrentChunk = currentOffset + current->length;
// Does current contain offset? If so, adjust bytes on front not returned.
// In detail: If we are on the start chunk and we have a non-zero offset
// (the only case where offset > currentOffset is possible) then
// tweak the return value.
// Note: It's not possible for an offset into current to happen except
// on the starting chunk since the constructor guarantees to seek the
// Iterator up to the first Chunk that will have data accessed from it.
if (offset > currentOffset && offset < endOfCurrentChunk)
startOffset = offset - currentOffset;
return static_cast<const char *>(current->data) + startOffset;
}
/**
* Return the length of the data at the current chunk.
*/
uint32_t
Buffer::Iterator::getLength() const
{
// Just the length of the current chunk with a few possible adjustments.
uint32_t result = current->length;
uint32_t end = offset + length;
uint32_t endOfCurrentChunk = currentOffset + current->length;
// Does current contain offset? If so, adjust bytes on front not returned.
// See the comment in getData for detailed explanation, if needed.
if (offset > currentOffset && offset < endOfCurrentChunk)
result -= offset - currentOffset;
// Does current contain end? If so, adjust bytes on end not returned.
if (end > currentOffset && end < endOfCurrentChunk)
result -= endOfCurrentChunk - end;
return result;
}
/**
* Return the total number of bytes this iterator will run across.
* This number is adjusted depending on the subrange of the buffer
* requested, if any.
*/
uint32_t
Buffer::Iterator::getTotalLength() const
{
return length;
}
/**
* Return the total number of chunks this iterator will run across.
* This number is adjusted depending on the starting offset into the
* buffer requested, if any. This number may be higher than the
* number of chunks visited if a length is specified as part of the
* iterator subrange.
* If this is an Iterator on a Buffer subrange then this value is
* computed lazily on the first call to this method and cached for
* subsequent calls.
*/
uint32_t
Buffer::Iterator::getNumberChunks() const
{
if (!numberChunksIsValid) {
// Determine the number of chunks this iter will visit and
// cache for future calls
Buffer::Iterator* self = const_cast<Buffer::Iterator*>(this);
Chunk* c = current;
uint32_t o = currentOffset;
while (c && (offset + length > o)) {
o += c->length;
c = c->next;
self->numberChunks++;
}
self->numberChunksIsValid = true;
}
return numberChunks;
}
/**
* Two Buffer::Iterators are equal if the logical array of bytes they would
* iterate through is the same, regardless of their chunk layouts.
* \param leftIter
* A Buffer::Iterator that has never had #Buffer::Iterator::next() called
* on it.
* \param rightIter
* A Buffer::Iterator that has never had #Buffer::Iterator::next() called
* on it.
* \todo(ongaro): These semantics are a bit weird, but they're useful for
* comparing subranges of Buffers. What we probably want is a Buffer::Range
* struct with equality defined in terms of an iterator.
*/
bool
operator==(Buffer::Iterator leftIter, Buffer::Iterator rightIter)
{
if (leftIter.getTotalLength() != rightIter.getTotalLength())
return false;
if (leftIter.getTotalLength() == 0)
return true;
const char* leftData = static_cast<const char*>(leftIter.getData());
uint32_t leftLength = leftIter.getLength();
const char* rightData = static_cast<const char*>(rightIter.getData());
uint32_t rightLength = rightIter.getLength();
while (true) {
if (leftLength <= rightLength) {
if (memcmp(leftData, rightData, leftLength) != 0)
return false;
rightData += leftLength;
rightLength -= leftLength;
leftIter.next();
if (leftIter.isDone())
return true;
leftData = static_cast<const char*>(leftIter.getData());
leftLength = leftIter.getLength();
} else {
if (memcmp(leftData, rightData, rightLength) != 0)
return false;
leftData += rightLength;
leftLength -= rightLength;
rightIter.next();
rightData = static_cast<const char*>(rightIter.getData());
rightLength = rightIter.getLength();
}
}
}
} // namespace RAMCloud
/**
* Allocate a contiguous region of memory and add it to the front of a Buffer.
*
* \param[in] numBytes
* The number of bytes to allocate.
* \param[in] buffer
* The Buffer in which to prepend the memory.
* \param[in] prepend
* This should be #::RAMCloud::PREPEND.
* \return
* The newly allocated memory region of size \a numBytes, which will be
* automatically deallocated in this Buffer's destructor. May not be
* aligned.
*/
void*
operator new(size_t numBytes, RAMCloud::Buffer* buffer,
RAMCloud::PREPEND_T prepend)
{
using namespace RAMCloud;
uint32_t numBytes32 = downCast<uint32_t>(numBytes);
if (numBytes32 == 0) {
// We want no visible effects but should return a unique pointer.
return buffer->allocatePrepend(1);
}
char* data = static_cast<char*>(buffer->allocatePrepend(numBytes32));
Buffer::Chunk* firstChunk = buffer->chunks;
if (firstChunk != NULL && firstChunk->isRawChunk() &&
data + numBytes32 == firstChunk->data) {
// Grow the existing Chunk.
firstChunk->data = data;
firstChunk->length += numBytes32;
buffer->totalLength += numBytes32;
} else {
Buffer::Chunk::prependToBuffer(buffer, data, numBytes32);
}
return data;
}
/**
* Allocate a contiguous region of memory and add it to the end of a Buffer.
*
* \param[in] numBytes
* The number of bytes to allocate.
* \param[in] buffer
* The Buffer in which to append the memory.
* \param[in] append
* This should be #::RAMCloud::APPEND.
* \return
* The newly allocated memory region of size \a numBytes, which will be
* automatically deallocated in this Buffer's destructor. May not be
* aligned.
*/
void*
operator new(size_t numBytes, RAMCloud::Buffer* buffer,
RAMCloud::APPEND_T append)
{
using namespace RAMCloud;
uint32_t numBytes32 = downCast<uint32_t>(numBytes);
if (numBytes32 == 0) {
// We want no visible effects but should return a unique pointer.
return buffer->allocateAppend(1);
}
char* data = static_cast<char*>(buffer->allocateAppend(numBytes32));
Buffer::Chunk* const lastChunk = buffer->chunksTail;
if (lastChunk != NULL && lastChunk->isRawChunk() &&
data - lastChunk->length == lastChunk->data) {
// Grow the existing Chunk.
lastChunk->length += numBytes32;
buffer->totalLength += numBytes32;
} else {
Buffer::Chunk::appendToBuffer(buffer, data, numBytes32);
}
return data;
}
/**
* Allocate a small, contiguous region of memory in a Buffer for a Chunk
* instance.
*
* \param[in] numBytes
* The number of bytes to allocate.
* \param[in] buffer
* The Buffer in which to allocate the memory.
* \param[in] chunk
* This should be #::RAMCloud::CHUNK.
* \return
* The newly allocated memory region of size \a numBytes, which will be
* automatically deallocated in this Buffer's destructor. Will be aligned
* to 8 bytes.
*/
void*
operator new(size_t numBytes, RAMCloud::Buffer* buffer,
RAMCloud::CHUNK_T chunk)
{
using namespace RAMCloud;
assert(numBytes >= sizeof(Buffer::Chunk));
return buffer->allocateChunk(downCast<uint32_t>(numBytes));
}
/**
* Allocate a contiguous region of memory in a Buffer.
*
* \warning This memory will not necessarily be aligned.
*
* \param[in] numBytes
* The number of bytes to allocate.
* \param[in] buffer
* The Buffer in which to allocate the memory.
* \param[in] misc
* This should be #::RAMCloud::MISC.
* \return
* The newly allocated memory region of size \a numBytes, which will be
* automatically deallocated in this Buffer's destructor. May not be
* aligned.
*/
void*
operator new(size_t numBytes, RAMCloud::Buffer* buffer,
RAMCloud::MISC_T misc)
{
using namespace RAMCloud;
if (numBytes == 0) {
// We want no visible effects but should return a unique pointer.
return buffer->allocateAppend(1);
}
return buffer->allocateAppend(downCast<uint32_t>(numBytes));
}
/**
* Allocate a contiguous region of memory and add it to the front of a Buffer.
* See #::operator new(size_t, RAMCloud::Buffer*, RAMCloud::PREPEND_T).
*/
void*
operator new[](size_t numBytes, RAMCloud::Buffer* buffer,
RAMCloud::PREPEND_T prepend)
{
return operator new(numBytes, buffer, prepend);
}
/**
* Allocate a contiguous region of memory and add it to the end of a Buffer.
* See #::operator new(size_t, RAMCloud::Buffer*, RAMCloud::APPEND_T).
*/
void*
operator new[](size_t numBytes, RAMCloud::Buffer* buffer,
RAMCloud::APPEND_T append)
{
return operator new(numBytes, buffer, append);
}
/**
* Allocate a contiguous region of memory in a Buffer for a Chunk instance.
* See #::operator new(size_t, RAMCloud::Buffer*, RAMCloud::CHUNK_T).
*/
void*
operator new[](size_t numBytes, RAMCloud::Buffer* buffer,
RAMCloud::CHUNK_T chunk)
{
return operator new(numBytes, buffer, chunk);
}
/**
* Allocate a contiguous region of memory in a Buffer.
* See #::operator new(size_t, RAMCloud::Buffer*, RAMCloud::MISC_T).
*/
void*
operator new[](size_t numBytes, RAMCloud::Buffer* buffer,
RAMCloud::MISC_T misc)
{
return operator new(numBytes, buffer, misc);
}
| 32.914449 | 80 | 0.637094 | [
"object"
] |
92837aab7103abd04ee8c594f31c03330117c9ad | 1,295 | cpp | C++ | algorithms/C++/Knapsack/0-1Knapsack.cpp | herrphon/Algorithms_Example | 90091844a8320822356143c6d23de6721a8e3d61 | [
"Apache-2.0"
] | 315 | 2017-12-01T03:55:57.000Z | 2022-03-22T11:37:28.000Z | algorithms/C++/Knapsack/0-1Knapsack.cpp | herrphon/Algorithms_Example | 90091844a8320822356143c6d23de6721a8e3d61 | [
"Apache-2.0"
] | 342 | 2018-07-22T15:21:18.000Z | 2021-10-05T08:03:10.000Z | algorithms/C++/Knapsack/0-1Knapsack.cpp | herrphon/Algorithms_Example | 90091844a8320822356143c6d23de6721a8e3d61 | [
"Apache-2.0"
] | 349 | 2017-10-04T06:01:57.000Z | 2017-11-28T07:29:26.000Z | //Solved using Dynamic Programming approach
//Time Complexity - O(n*w)
//Space Complexity - 0(n*w)
#include <bits/stdc++.h>
using namespace std;
//greedy function that returns max. value that can be pushed in the knapsack
int knapSack(int W, vector<int> value, vector<int> weight, int n)
{
int dp[n + 1][W + 1];
// build table dp[][] in bottom up manner
for (int i = 0; i <= n; i++)
{
for (int w = 0; w <= W; w++)
{
if (i == 0 || w == 0)
dp[i][w] = 0;
else if (weight[i - 1] <= w)
dp[i][w] = max(value[i - 1] + dp[i - 1][w - weight[i - 1]], dp[i - 1][w]);
else
dp[i][w] = dp[i - 1][w];
}
}
return dp[n][W];
}
int main()
{
int W; //Weight of knapsack
cin>>W;
int n; //no. of available items
cin>>n;
vector<int> value(n); //stores value of each item
vector<int> weight(n); //stores weight of each item
for(int i=0; i<n; i++)
{
int v, w;
cin>>v>>w;
value.push_back(v);
weight.push_back(w);
}
cout << "Maximum value we can obtain = "<< knapSack(W, value, weight, n);
return 0;
}
| 24.903846 | 91 | 0.457143 | [
"vector"
] |
928ba151d22ab48c93fb76ffea394c9065a127df | 15,396 | cpp | C++ | src/link/DataCallback.cpp | dneuge/cvr | 516547dca0672c92aa4f4a37712e6135e7f6b011 | [
"MIT"
] | null | null | null | src/link/DataCallback.cpp | dneuge/cvr | 516547dca0672c92aa4f4a37712e6135e7f6b011 | [
"MIT"
] | 8 | 2016-07-24T19:59:06.000Z | 2016-07-24T20:13:56.000Z | src/link/DataCallback.cpp | dneuge/cvr | 516547dca0672c92aa4f4a37712e6135e7f6b011 | [
"MIT"
] | null | null | null | #include "DataCallback.h"
#include <time.h>
#include <math.h>
#include "TimedPacket.h"
// TODO: figure out if there's a better way to include that file on compilation - it's not a lib
// needs to stay prefixed with link/ or building via CMake will not find
// the file due to different include search path within build dir
#include "link/include_DeckLinkAPIDispatch.cpp"
inline unsigned char clampRGB(int x)
{
if (x < 0)
{
return 0;
}
if (x > 255)
{
return 255;
}
return x;
}
DataCallback::DataCallback(QImage** image, unsigned char *rawImage, unsigned long rawImageLength, QMutex* frameDrawMutex){
audioPacketCounter = 0;
videoFrameCounter = 0;
this->frameDrawMutex = frameDrawMutex;
this->image = image;
this->rawImage = rawImage;
this->rawImageLength = rawImageLength;
skipFrames = false;
lastFrameUsed = false;
//halfFrameRate = true; // skip every second frame?
halfFrameRate = false; // skip every second frame?
outputToQImage = false;
// pre-calculate YCrCb conversion table
if (!outputToQImage) {
std::cout << "skipping setup of color space conversion table because output to QImage is disabled\n";
} else {
std::cout << "pre-calculating color space conversion table, wait";
lookupTableYCrCbToQRgb = new QRgb**[256];
for (unsigned int y = 0; y < 256; y++) {
std::cout << ".";
std::cout.flush();
lookupTableYCrCbToQRgb[y] = new QRgb*[256];
for (unsigned int cr0 = 0; cr0 < 256; cr0++) {
lookupTableYCrCbToQRgb[y][cr0] = new QRgb[256];
for (unsigned int cb0 = 0; cb0 < 256; cb0++) {
char convCr0 = cr0 - 128;
char convCb0 = cb0 - 128;
unsigned char r = clampRGB(round((double) y + 1.402 * convCr0));
unsigned char g = clampRGB(round((double) y - 0.344 * convCb0 - 0.714 * convCr0));
unsigned char b = clampRGB(round((double) y + 1.772 * convCb0));
lookupTableYCrCbToQRgb[y][cr0][cb0] = qRgb(r, g, b);
}
}
}
std::cout << " done\n";
}
// initialize DeckLink API
BMDDisplayMode displayMode = bmdModeHD720p5994;
BMDPixelFormat pixelFormat = bmdFormat8BitYUV;
BMDVideoInputFlags inputFlags = 0;
//BMDAudioSampleRate audioSampleRate = bmdAudioSampleRate48kHz;
audioChannels = 2; // stereo
audioSampleDepth = 16; // 16 bit
audioSampleRate = 48000; // 48kHz
// get iterator
deckLinkIterator = CreateDeckLinkIteratorInstance();
if (!deckLinkIterator)
{
std::cout << "no iterator\n";
return;
}
// get first device
if (deckLinkIterator->Next(&deckLink) != S_OK)
{
std::cout << "no device found by iterator\n";
return;
}
// get input interface
if (deckLink->QueryInterface(IID_IDeckLinkInput, (void**)&deckLinkInput) != S_OK)
{
std::cout << "failed to get input interface\n";
return;
}
/*
// try to disable any previous capture
if (deckLinkInput->DisableVideoInput() != S_OK) {
std::cout << "pre: could not disable video input\n";
}
if (deckLinkInput->DisableAudioInput() != S_OK) {
std::cout << "pre: could not disable audio input\n";
}
if (deckLinkInput->FlushStreams() != S_OK) {
std::cout << "pre: could not flush streams before stop\n";
}
if (deckLinkInput->StopStreams() != S_OK) {
std::cout << "pre: could not stop streams\n";
}
if (deckLinkInput->FlushStreams() != S_OK) {
std::cout << "pre: could not flush streams after stop\n";
}
*/
// register ourselves as receiver
deckLinkInput->SetCallback(this);
// verify video mode
BMDDisplayModeSupport res;
deckLinkInput->DoesSupportVideoMode(displayMode, pixelFormat, bmdVideoInputFlagDefault, &res, NULL);
if (res == bmdDisplayModeNotSupported)
{
std::cout << "video mode is not supported\n";
return;
}
// configure video stream
if (deckLinkInput->EnableVideoInput(displayMode, pixelFormat, inputFlags) != S_OK)
{
std::cout << "could not configure video stream\n";
return;
}
// configure audio stream
if (deckLinkInput->EnableAudioInput(audioSampleRate, audioSampleDepth, audioChannels) != S_OK)
{
std::cout << "could not configure audio stream\n";
return;
}
// start streaming
if(deckLinkInput->StartStreams() != S_OK)
{
std::cout << "could not start capture streams\n";
return;
}
// register shutdown callback to release DeckLink resources
// NOTE: that doesn't work and isn't adivsable as this is an object that
// may cease to exist before the method can be called; we need some
// shutdown hook setup by main() to call destructors instead
//atexit(&DataCallback::shutdown);
std::cout << "initialized\n";
}
void DataCallback::shutdown() {
// I've seen crashes in the kernel module most likely related to unclean
// termination of the application. We try to fix that by releasing all
// interface resources.
// FIXME: currently unused
deckLinkIterator->Release();
deckLinkInput->Release();
deckLink->Release();
}
/*
HRESULT STDMETHODCALLTYPE RenderingTest::QueryInterface(REFIID iid, LPVOID *ppv)
{
return E_NOINTERFACE;
}
*/
ULONG STDMETHODCALLTYPE DataCallback::AddRef(void)
{
refCountMutex.lock();
ULONG myRefCount = refCount++;
refCountMutex.unlock();
return myRefCount;
};
ULONG STDMETHODCALLTYPE DataCallback::Release(void)
{
refCountMutex.lock();
ULONG myRefCount = refCount--;
refCountMutex.unlock();
return myRefCount;
};
HRESULT STDMETHODCALLTYPE DataCallback::VideoInputFormatChanged(BMDVideoInputFormatChangedEvents, IDeckLinkDisplayMode*, BMDDetectedVideoInputFormatFlags)
{
std::cout << "video input format changed\n";
return S_OK;
};
inline unsigned char* onePixelYCrCbToRGB(char y, char cr, char cb)
{
// http://en.wikipedia.org/wiki/YUV#Y.27UV444_to_RGB888_conversion
// integer version
unsigned char *rgb = new unsigned char[3];
rgb[0] = y + cr + (cr >> 2) + (cr >> 3) + (cr >> 5);
rgb[1] = y - ((cb >> 2) + (cb >> 4) + (cb >> 5)) - ((cr >> 1) + (cr >> 3) + (cr >> 4) + (cr >> 5));
rgb[2] = y + cb + (cb >> 1) + (cb >> 2) + (cb >> 6);
return rgb;
}
HRESULT STDMETHODCALLTYPE DataCallback::VideoInputFrameArrived(IDeckLinkVideoInputFrame *videoFrame, IDeckLinkAudioInputPacket *audioPacket)
{
// remember what time the data arrived
// CLOCK_MONOTONIC should give a clock related to system runtime, so it
// should be safe in case of clock adjustments during a recording
timespec timeOfReception;
clock_gettime(CLOCK_MONOTONIC, &timeOfReception);
// skip? (capturing disabled)
if (skipFrames) {
return S_OK;
}
// remember AV packet indices and increment
packetCounterMutex.lock();
unsigned long long currentAudioPacketIndex = audioPacketCounter;
unsigned long long currentVideoFrameIndex = videoFrameCounter;
if (audioPacket != 0) {
audioPacketCounter++;
}
if (videoFrame != 0) {
videoFrameCounter++;
}
packetCounterMutex.unlock();
// process audio packet
char *audioBuffer;
unsigned long audioLength = 0;
if (audioPacket != 0) {
if (audioPacket->GetBytes((void**) &audioBuffer) != S_OK)
{
std::cout << "error getting audio packet data\n";
}
else
{
audioLength = audioPacket->GetSampleFrameCount() * audioChannels * (audioSampleDepth / 8);
if (audioLength > 0) {
// copy buffer to variable and feed connected Qt slots
char* rawAudio = new char[audioLength];
memcpy(rawAudio, audioBuffer, audioLength);
emit audioArrived(rawAudio, audioLength);
}
}
}
// ignore every second frame if half frame rate is requested
if (halfFrameRate && lastFrameUsed) {
lastFrameUsed = false;
return S_OK;
}
lastFrameUsed = true;
// it may happen that we only got audio, only process video frame if we got data
unsigned char *imageBuffer;
unsigned long imageBufferLength = 0;
if (videoFrame != 0) {
bool videoFrameContinue = true;
long width = videoFrame->GetWidth();
long height = videoFrame->GetHeight();
long rowBytes = videoFrame->GetRowBytes();
BMDPixelFormat pixelFormat = videoFrame->GetPixelFormat();
//printf("%li x %li, row bytes %li, pixel format %i\n", width, height, rowBytes, pixelFormat); // DEBUG
QImage *newImage;
// drop frame if previous call is still being processed
if (!frameAcceptanceMutex.tryLock()) {
// DEBUG: show that we are dropping frames
std::cout << "d";
videoFrameContinue = false;
}
if (videoFrameContinue && (pixelFormat != bmdFormat8BitYUV)) {
std::cout << "unexpected pixel format, cannot decode\n";
videoFrameContinue = false;
}
if (videoFrameContinue) {
if (outputToQImage) {
newImage = new QImage(width, height, QImage::Format_RGB32);
}
imageBufferLength = rowBytes * videoFrame->GetHeight();
if (videoFrame->GetBytes((void**) &imageBuffer) != S_OK)
{
std::cout << "failed to fill buffer\n";
if (outputToQImage) {
delete newImage;
}
videoFrameContinue = false;
}
}
if (videoFrameContinue)
{
if (outputToQImage) {
// convert color space and set pixels on QImage
long bufferPos = 0;
long widthHalf = width/2;
for (long y=0; y<height; y++)
{
for (long xHalf=0; xHalf<widthHalf; xHalf++)
{
unsigned char cb0 = imageBuffer[bufferPos++];
unsigned char y0 = imageBuffer[bufferPos++];
unsigned char cr0 = imageBuffer[bufferPos++];
unsigned char y1 = imageBuffer[bufferPos++];
/*
char convCr0 = cr0 - 128;
char convCb0 = cb0 - 128;
*/
// http://en.wikipedia.org/wiki/YUV#Y.27UV444_to_RGB888_conversion
/*
// integer version
unsigned char *rgb0 = onePixelYCrCbToRGB(y0, convCr0, convCb0);
unsigned char *rgb1 = onePixelYCrCbToRGB(y1, convCr0, convCb0);
image.setPixel(xHalf * 2, y, qRgb(rgb0[0], rgb0[1], rgb0[2]));
image.setPixel(xHalf * 2 + 1, y, qRgb(rgb1[0], rgb1[1], rgb1[2]));
delete rgb0;
delete rgb1;
*/
/*
int r0 = clampRGB(round((double) y0 + 1.402 * convCr0));
int g0 = clampRGB(round((double) y0 - 0.344 * convCb0 - 0.714 * convCr0));
int b0 = clampRGB(round((double) y0 + 1.772 * convCb0));
int r1 = clampRGB(round((double) y1 + 1.402 * convCr0));
int g1 = clampRGB(round((double) y1 - 0.344 * convCb0 - 0.714 * convCr0));
int b1 = clampRGB(round((double) y1 + 1.772 * convCb0));
image.setPixel(xHalf * 2, y, qRgb(r0, g0, b0));
image.setPixel(xHalf * 2 + 1, y, qRgb(r1, g1, b1));
*/
//newImage.setPixel(xHalf * 2, y, qRgb(lookupTableYCrCbToR[y0][cr0][cb0], lookupTableYCrCbToG[y0][cr0][cb0], lookupTableYCrCbToB[y0][cr0][cb0]));
//newImage.setPixel(xHalf * 2 + 1, y, qRgb(lookupTableYCrCbToR[y1][cr0][cb0], lookupTableYCrCbToG[y1][cr0][cb0], lookupTableYCrCbToB[y1][cr0][cb0]));
newImage->setPixel(xHalf * 2, y, lookupTableYCrCbToQRgb[y0][cr0][cb0]);
newImage->setPixel(xHalf * 2 + 1, y, lookupTableYCrCbToQRgb[y1][cr0][cb0]);
}
}
}
// switch image
frameDrawMutex->lock();
if (outputToQImage) {
delete *image;
*image = newImage;
}
// copy buffer content to rawImage
if (rawImageLength < imageBufferLength) {
printf("buffer length %lu exceeds raw image length %lu, cannot copy raw image!\n", imageBufferLength, rawImageLength);
} else {
memcpy(rawImage, imageBuffer, imageBufferLength);
}
frameDrawMutex->unlock();
// ask Qt to repaint the widget optimized
emit imageUpdated();
}
// we are ready for next frame
frameAcceptanceMutex.unlock();
}
// forward data to all delayed listeners
delayedReceptionCallbacksMutex.lock();
if (!delayedReceptionCallbacks.empty()) {
unsigned long long timeOfReceptionMillis = timeOfReception.tv_sec * 1000 + lround((double) (timeOfReception.tv_nsec / 100000) / 10.0);
std::vector<DelayedReceptionCallback*>::iterator it = delayedReceptionCallbacks.begin();
while (it != delayedReceptionCallbacks.end()) {
DelayedReceptionCallback *callback = (*it);
// copy data and wrap in timestamped and indexed packets
TimedPacket *timedAudioPacket = 0;
if (audioLength != 0) {
char *tmp = new char[audioLength];
memcpy(tmp, audioBuffer, audioLength);
timedAudioPacket = new TimedPacket(currentAudioPacketIndex, timeOfReceptionMillis, tmp, audioLength);
}
TimedPacket *timedVideoFrame = 0;
if (imageBufferLength != 0) {
char *tmp = new char[imageBufferLength];
memcpy(tmp, imageBuffer, imageBufferLength);
timedVideoFrame = new TimedPacket(currentVideoFrameIndex, timeOfReceptionMillis, tmp, imageBufferLength);
}
// forward packets
callback->dataReceived(timedAudioPacket, timedVideoFrame);
it++;
}
}
delayedReceptionCallbacksMutex.unlock();
return S_OK;
};
void DataCallback::toggleCapture()
{
frameAcceptanceMutex.lock();
skipFrames = !skipFrames;
frameAcceptanceMutex.unlock();
}
void DataCallback::registerDelayedReceptionCallback(DelayedReceptionCallback *callback) {
if (callback != 0) {
delayedReceptionCallbacksMutex.lock();
delayedReceptionCallbacks.push_back(callback);
delayedReceptionCallbacksMutex.unlock();
}
}
| 34.911565 | 173 | 0.575539 | [
"object",
"vector"
] |
928f20bbf2660686a58c9879f6761fd6a4fcc1a7 | 1,306 | hpp | C++ | libs/core/include/fcppt/math/vector/std_hash.hpp | pmiddend/fcppt | 9f437acbb10258e6df6982a550213a05815eb2be | [
"BSL-1.0"
] | null | null | null | libs/core/include/fcppt/math/vector/std_hash.hpp | pmiddend/fcppt | 9f437acbb10258e6df6982a550213a05815eb2be | [
"BSL-1.0"
] | null | null | null | libs/core/include/fcppt/math/vector/std_hash.hpp | pmiddend/fcppt | 9f437acbb10258e6df6982a550213a05815eb2be | [
"BSL-1.0"
] | null | null | null | // Copyright Carl Philipp Reh 2009 - 2018.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef FCPPT_MATH_VECTOR_STD_HASH_HPP_INCLUDED
#define FCPPT_MATH_VECTOR_STD_HASH_HPP_INCLUDED
#include <fcppt/math/size_type.hpp>
#include <fcppt/math/to_array.hpp>
#include <fcppt/math/to_array_type.hpp>
#include <fcppt/math/vector/object_impl.hpp>
#include <fcppt/preprocessor/disable_clang_warning.hpp>
#include <fcppt/preprocessor/pop_warning.hpp>
#include <fcppt/preprocessor/push_warning.hpp>
#include <fcppt/range/hash_impl.hpp>
#include <fcppt/config/external_begin.hpp>
#include <cstddef>
#include <functional>
#include <fcppt/config/external_end.hpp>
namespace std
{
FCPPT_PP_PUSH_WARNING
FCPPT_PP_DISABLE_CLANG_WARNING(-Wmismatched-tags)
template<
typename T,
fcppt::math::size_type N,
typename S
>
struct hash<
fcppt::math::vector::object<
T,
N,
S
>
>
{
typedef
fcppt::math::vector::object<
T,
N,
S
> type;
std::size_t
operator()(
type const &_value
) const
{
return
fcppt::range::hash<
fcppt::math::to_array_type<
type
>
>{}(
fcppt::math::to_array(
_value
)
);
}
};
FCPPT_PP_POP_WARNING
}
#endif
| 17.890411 | 61 | 0.718224 | [
"object",
"vector"
] |
9295f9f8d198397b568b7f65657ef3c4f14f030c | 3,508 | cpp | C++ | teaching/quickselect/main.cpp | anianruoss/DNA | 0245c7d23f51e7c637aee44691828ee290fd64d6 | [
"MIT"
] | null | null | null | teaching/quickselect/main.cpp | anianruoss/DNA | 0245c7d23f51e7c637aee44691828ee290fd64d6 | [
"MIT"
] | null | null | null | teaching/quickselect/main.cpp | anianruoss/DNA | 0245c7d23f51e7c637aee44691828ee290fd64d6 | [
"MIT"
] | 1 | 2017-03-31T10:07:32.000Z | 2017-03-31T10:07:32.000Z | #include <algorithm>
#include <cassert>
#include <iomanip>
#include <iostream>
#include <random>
#include <vector>
size_t sep = 20;
class QuickSelect {
public:
using Iterator = std::vector<int>::iterator;
QuickSelect(const std::vector<int>& a) : v(a) {}
int select(size_t k, bool naive) {
step = 0;
Iterator begin = v.begin();
Iterator end = v.end();
size_t n = end - begin;
assert(k < n);
std::mt19937 gen(123);
while (n > 1) {
// choose bad pivot on purpose
Iterator pivot = begin;
Iterator pos;
if (naive) {
pos = naivePartition(begin, end, *pivot);
} else {
pos = cleverPartition(begin, end, *pivot);
}
size_t offset = pos - begin;
print(offset);
if (offset < k) {
begin = pos + 1;
k -= offset + 1;
} else if (offset > k) {
end = pos;
} else {
return *pos;
}
n = end - begin;
}
return *begin;
}
private:
std::vector<int> v;
size_t step = 0;
Iterator naivePartition(Iterator begin, Iterator end, int pivot) {
auto left = begin;
auto right = end - 1;
while (left <= right) {
while (*left < pivot) ++left;
while (pivot < *right) --right;
std::swap(*left, *right);
if (*left == *right) ++left;
}
return left - 1;
}
Iterator cleverPartition(Iterator begin, Iterator end, int pivot) {
auto left = begin;
auto right = end - 1;
bool do_left = true;
while (left <= right) {
while (*left < pivot) ++left;
while (pivot < *right) --right;
if (*left == *right) {
if (left == right || do_left)
++left;
else
--right;
do_left = !do_left;
} else {
std::swap(*left, *right);
}
}
return left - 1;
}
void print(size_t offset) {
std::cout << std::setw(sep) << "STEP " << ++step
<< std::setw(sep) << v.size() - offset - 1
<< std::setw(sep) << offset
<< std::endl;
}
};
int main() {
const size_t k = 0;
std::vector<int> vec {6, 6, 6, 6, 6, 6};
std::cout << "Finding the " << k << "-th smallest element from: ";
for (auto x : vec)
std::cout << x << " ";
std::cout << std::endl << std::endl;
QuickSelect qs(vec);
std::cout << std::left << std::setw(sep) << "NAIVE Partition"
<< std::setw(2*sep) << "Number of Elements:"
<< std::endl << std::right << std::endl
<< std::setw(sep) << ""
<< std::setw(sep) << "Left Partition"
<< std::setw(sep) << "Right Partition"
<< std::endl;
qs.select(k, true);
std::cout << std::endl << std::endl
<< std::left << std::setw(sep) << "CLEVER Partition"
<< std::setw(2*sep) << "Number of Elements:"
<< std::endl << std::internal << std::endl
<< std::setw(sep) << ""
<< std::setw(sep) << "Left Partition"
<< std::setw(sep) << "Right Partition"
<< std::endl;
qs.select(k, false);
return 0;
}
| 24.027397 | 71 | 0.440707 | [
"vector"
] |
9296a6d1410f72d00efcf8c249bdd8a037b8b4be | 42,360 | cpp | C++ | src/qt/qtbase/src/plugins/platforms/xcb/qxcbdrag.cpp | power-electro/phantomjs-Gohstdriver-DIY-openshift | a571d301a9658a4c1b524d07e15658b45f8a0579 | [
"BSD-3-Clause"
] | null | null | null | src/qt/qtbase/src/plugins/platforms/xcb/qxcbdrag.cpp | power-electro/phantomjs-Gohstdriver-DIY-openshift | a571d301a9658a4c1b524d07e15658b45f8a0579 | [
"BSD-3-Clause"
] | null | null | null | src/qt/qtbase/src/plugins/platforms/xcb/qxcbdrag.cpp | power-electro/phantomjs-Gohstdriver-DIY-openshift | a571d301a9658a4c1b524d07e15658b45f8a0579 | [
"BSD-3-Clause"
] | null | null | null | /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qxcbdrag.h"
#include <xcb/xcb.h>
#include "qxcbconnection.h"
#include "qxcbclipboard.h"
#include "qxcbmime.h"
#include "qxcbwindow.h"
#include "qxcbscreen.h"
#include "qwindow.h"
#include "qxcbcursor.h"
#include <private/qdnd_p.h>
#include <qdebug.h>
#include <qevent.h>
#include <qguiapplication.h>
#include <qrect.h>
#include <qpainter.h>
#include <qtimer.h>
#include <qpa/qwindowsysteminterface.h>
#include <private/qshapedpixmapdndwindow_p.h>
#include <private/qsimpledrag_p.h>
#include <private/qhighdpiscaling_p.h>
QT_BEGIN_NAMESPACE
#ifndef QT_NO_DRAGANDDROP
//#define DND_DEBUG
#ifdef DND_DEBUG
#define DEBUG qDebug
#else
#define DEBUG if(0) qDebug
#endif
#ifdef DND_DEBUG
#define DNDDEBUG qDebug()
#else
#define DNDDEBUG if(0) qDebug()
#endif
const int xdnd_version = 5;
static inline xcb_window_t xcb_window(QPlatformWindow *w)
{
return static_cast<QXcbWindow *>(w)->xcb_window();
}
static inline xcb_window_t xcb_window(QWindow *w)
{
return static_cast<QXcbWindow *>(w->handle())->xcb_window();
}
static xcb_window_t xdndProxy(QXcbConnection *c, xcb_window_t w)
{
xcb_window_t proxy = XCB_NONE;
xcb_get_property_cookie_t cookie = Q_XCB_CALL2(xcb_get_property(c->xcb_connection(), false, w, c->atom(QXcbAtom::XdndProxy),
XCB_ATOM_WINDOW, 0, 1), c);
xcb_get_property_reply_t *reply = xcb_get_property_reply(c->xcb_connection(), cookie, 0);
if (reply && reply->type == XCB_ATOM_WINDOW)
proxy = *((xcb_window_t *)xcb_get_property_value(reply));
free(reply);
if (proxy == XCB_NONE)
return proxy;
// exists and is real?
cookie = Q_XCB_CALL2(xcb_get_property(c->xcb_connection(), false, proxy, c->atom(QXcbAtom::XdndProxy),
XCB_ATOM_WINDOW, 0, 1), c);
reply = xcb_get_property_reply(c->xcb_connection(), cookie, 0);
if (reply && reply->type == XCB_ATOM_WINDOW) {
xcb_window_t p = *((xcb_window_t *)xcb_get_property_value(reply));
if (proxy != p)
proxy = 0;
} else {
proxy = 0;
}
free(reply);
return proxy;
}
class QXcbDropData : public QXcbMime
{
public:
QXcbDropData(QXcbDrag *d);
~QXcbDropData();
protected:
bool hasFormat_sys(const QString &mimeType) const Q_DECL_OVERRIDE;
QStringList formats_sys() const Q_DECL_OVERRIDE;
QVariant retrieveData_sys(const QString &mimeType, QVariant::Type type) const Q_DECL_OVERRIDE;
QVariant xdndObtainData(const QByteArray &format, QVariant::Type requestedType) const;
QXcbDrag *drag;
};
QXcbDrag::QXcbDrag(QXcbConnection *c) : QXcbObject(c)
{
dropData = new QXcbDropData(this);
init();
cleanup_timer = -1;
}
QXcbDrag::~QXcbDrag()
{
delete dropData;
}
void QXcbDrag::init()
{
currentWindow.clear();
accepted_drop_action = Qt::IgnoreAction;
xdnd_dragsource = XCB_NONE;
waiting_for_status = false;
current_target = XCB_NONE;
current_proxy_target = XCB_NONE;
source_time = XCB_CURRENT_TIME;
target_time = XCB_CURRENT_TIME;
QXcbCursor::queryPointer(connection(), ¤t_virtual_desktop, 0);
drag_types.clear();
}
QMimeData *QXcbDrag::platformDropData()
{
return dropData;
}
void QXcbDrag::startDrag()
{
// #fixme enableEventFilter();
init();
xcb_set_selection_owner(xcb_connection(), connection()->clipboard()->owner(),
atom(QXcbAtom::XdndSelection), connection()->time());
QStringList fmts = QXcbMime::formatsHelper(drag()->mimeData());
for (int i = 0; i < fmts.size(); ++i) {
QVector<xcb_atom_t> atoms = QXcbMime::mimeAtomsForFormat(connection(), fmts.at(i));
for (int j = 0; j < atoms.size(); ++j) {
if (!drag_types.contains(atoms.at(j)))
drag_types.append(atoms.at(j));
}
}
if (drag_types.size() > 3)
xcb_change_property(xcb_connection(), XCB_PROP_MODE_REPLACE, connection()->clipboard()->owner(),
atom(QXcbAtom::XdndTypelist),
XCB_ATOM_ATOM, 32, drag_types.size(), (const void *)drag_types.constData());
setUseCompositing(current_virtual_desktop->compositingActive());
QBasicDrag::startDrag();
if (connection()->mouseGrabber() == Q_NULLPTR)
shapedPixmapWindow()->setMouseGrabEnabled(true);
}
void QXcbDrag::endDrag()
{
QBasicDrag::endDrag();
}
static xcb_translate_coordinates_reply_t *
translateCoordinates(QXcbConnection *c, xcb_window_t from, xcb_window_t to, int x, int y)
{
xcb_translate_coordinates_cookie_t cookie =
xcb_translate_coordinates(c->xcb_connection(), from, to, x, y);
return xcb_translate_coordinates_reply(c->xcb_connection(), cookie, 0);
}
static
bool windowInteractsWithPosition(xcb_connection_t *connection, const QPoint & pos, xcb_window_t w, xcb_shape_sk_t shapeType)
{
bool interacts = false;
xcb_shape_get_rectangles_reply_t *reply = xcb_shape_get_rectangles_reply(connection, xcb_shape_get_rectangles(connection, w, shapeType), NULL);
if (reply) {
xcb_rectangle_t *rectangles = xcb_shape_get_rectangles_rectangles(reply);
if (rectangles) {
const int nRectangles = xcb_shape_get_rectangles_rectangles_length(reply);
for (int i = 0; !interacts && i < nRectangles; ++i) {
interacts = QRect(rectangles[i].x, rectangles[i].y, rectangles[i].width, rectangles[i].height).contains(pos);
}
}
free(reply);
}
return interacts;
}
xcb_window_t QXcbDrag::findRealWindow(const QPoint & pos, xcb_window_t w, int md, bool ignoreNonXdndAwareWindows)
{
if (w == shapedPixmapWindow()->handle()->winId())
return 0;
if (md) {
xcb_get_window_attributes_cookie_t cookie = xcb_get_window_attributes(xcb_connection(), w);
xcb_get_window_attributes_reply_t *reply = xcb_get_window_attributes_reply(xcb_connection(), cookie, 0);
if (!reply)
return 0;
if (reply->map_state != XCB_MAP_STATE_VIEWABLE)
return 0;
free(reply);
xcb_get_geometry_cookie_t gcookie = xcb_get_geometry(xcb_connection(), w);
xcb_get_geometry_reply_t *greply = xcb_get_geometry_reply(xcb_connection(), gcookie, 0);
if (!greply)
return 0;
QRect windowRect(greply->x, greply->y, greply->width, greply->height);
free(greply);
if (windowRect.contains(pos)) {
bool windowContainsMouse = !ignoreNonXdndAwareWindows;
{
xcb_get_property_cookie_t cookie =
Q_XCB_CALL(xcb_get_property(xcb_connection(), false, w, connection()->atom(QXcbAtom::XdndAware),
XCB_GET_PROPERTY_TYPE_ANY, 0, 0));
xcb_get_property_reply_t *reply = xcb_get_property_reply(xcb_connection(), cookie, 0);
bool isAware = reply && reply->type != XCB_NONE;
free(reply);
if (isAware) {
const QPoint relPos = pos - windowRect.topLeft();
// When ShapeInput and ShapeBounding are not set they return a single rectangle with the geometry of the window, this is why we
// need to check both here so that in the case one is set and the other is not we still get the correct result.
if (connection()->hasInputShape())
windowContainsMouse = windowInteractsWithPosition(xcb_connection(), relPos, w, XCB_SHAPE_SK_INPUT);
if (windowContainsMouse && connection()->hasXShape())
windowContainsMouse = windowInteractsWithPosition(xcb_connection(), relPos, w, XCB_SHAPE_SK_BOUNDING);
if (!connection()->hasInputShape() && !connection()->hasXShape())
windowContainsMouse = true;
if (windowContainsMouse)
return w;
}
}
xcb_query_tree_cookie_t cookie = xcb_query_tree (xcb_connection(), w);
xcb_query_tree_reply_t *reply = xcb_query_tree_reply(xcb_connection(), cookie, 0);
if (!reply)
return 0;
int nc = xcb_query_tree_children_length(reply);
xcb_window_t *c = xcb_query_tree_children(reply);
xcb_window_t r = 0;
for (uint i = nc; !r && i--;)
r = findRealWindow(pos - windowRect.topLeft(), c[i], md-1, ignoreNonXdndAwareWindows);
free(reply);
if (r)
return r;
// We didn't find a client window! Just use the
// innermost window.
// No children!
if (!windowContainsMouse)
return 0;
else
return w;
}
}
return 0;
}
void QXcbDrag::move(const QPoint &globalPos)
{
if (source_sameanswer.contains(globalPos) && source_sameanswer.isValid())
return;
QXcbVirtualDesktop *virtualDesktop = Q_NULLPTR;
QPoint cursorPos;
QXcbCursor::queryPointer(connection(), &virtualDesktop, &cursorPos);
QXcbScreen *screen = virtualDesktop->screenAt(cursorPos);
QPoint deviceIndependentPos = QHighDpiScaling::mapPositionFromNative(globalPos, screen);
if (virtualDesktop != current_virtual_desktop) {
setUseCompositing(virtualDesktop->compositingActive());
recreateShapedPixmapWindow(static_cast<QPlatformScreen*>(screen)->screen(), deviceIndependentPos);
current_virtual_desktop = virtualDesktop;
} else {
QBasicDrag::moveShapedPixmapWindow(deviceIndependentPos);
}
xcb_window_t rootwin = current_virtual_desktop->root();
xcb_translate_coordinates_reply_t *translate =
::translateCoordinates(connection(), rootwin, rootwin, globalPos.x(), globalPos.y());
if (!translate)
return;
xcb_window_t target = translate->child;
int lx = translate->dst_x;
int ly = translate->dst_y;
free (translate);
if (target && target != rootwin) {
xcb_window_t src = rootwin;
while (target != 0) {
DNDDEBUG << "checking target for XdndAware" << target << lx << ly;
// translate coordinates
translate = ::translateCoordinates(connection(), src, target, lx, ly);
if (!translate) {
target = 0;
break;
}
lx = translate->dst_x;
ly = translate->dst_y;
src = target;
xcb_window_t child = translate->child;
free(translate);
// check if it has XdndAware
xcb_get_property_cookie_t cookie = Q_XCB_CALL(xcb_get_property(xcb_connection(), false, target,
atom(QXcbAtom::XdndAware), XCB_GET_PROPERTY_TYPE_ANY, 0, 0));
xcb_get_property_reply_t *reply = xcb_get_property_reply(xcb_connection(), cookie, 0);
bool aware = reply && reply->type != XCB_NONE;
free(reply);
if (aware) {
DNDDEBUG << "Found XdndAware on " << target;
break;
}
target = child;
}
if (!target || target == shapedPixmapWindow()->handle()->winId()) {
DNDDEBUG << "need to find real window";
target = findRealWindow(globalPos, rootwin, 6, true);
if (target == 0)
target = findRealWindow(globalPos, rootwin, 6, false);
DNDDEBUG << "real window found" << target;
}
}
QXcbWindow *w = 0;
if (target) {
w = connection()->platformWindowFromId(target);
if (w && (w->window()->type() == Qt::Desktop) /*&& !w->acceptDrops()*/)
w = 0;
} else {
w = 0;
target = rootwin;
}
xcb_window_t proxy_target = xdndProxy(connection(), target);
if (!proxy_target)
proxy_target = target;
int target_version = 1;
if (proxy_target) {
xcb_get_property_cookie_t cookie = xcb_get_property(xcb_connection(), false, proxy_target,
atom(QXcbAtom::XdndAware), XCB_GET_PROPERTY_TYPE_ANY, 0, 1);
xcb_get_property_reply_t *reply = xcb_get_property_reply(xcb_connection(), cookie, 0);
if (!reply || reply->type == XCB_NONE)
target = 0;
target_version = *(uint32_t *)xcb_get_property_value(reply);
target_version = qMin(xdnd_version, target_version ? target_version : 1);
free(reply);
}
if (target != current_target) {
if (current_target)
send_leave();
current_target = target;
current_proxy_target = proxy_target;
if (target) {
int flags = target_version << 24;
if (drag_types.size() > 3)
flags |= 0x0001;
xcb_client_message_event_t enter;
enter.response_type = XCB_CLIENT_MESSAGE;
enter.window = target;
enter.format = 32;
enter.type = atom(QXcbAtom::XdndEnter);
enter.data.data32[0] = connection()->clipboard()->owner();
enter.data.data32[1] = flags;
enter.data.data32[2] = drag_types.size()>0 ? drag_types.at(0) : 0;
enter.data.data32[3] = drag_types.size()>1 ? drag_types.at(1) : 0;
enter.data.data32[4] = drag_types.size()>2 ? drag_types.at(2) : 0;
// provisionally set the rectangle to 5x5 pixels...
source_sameanswer = QRect(globalPos.x() - 2, globalPos.y() -2 , 5, 5);
DEBUG() << "sending Xdnd enter source=" << enter.data.data32[0];
if (w)
handleEnter(w, &enter, current_proxy_target);
else if (target)
xcb_send_event(xcb_connection(), false, proxy_target, XCB_EVENT_MASK_NO_EVENT, (const char *)&enter);
waiting_for_status = false;
}
}
if (waiting_for_status)
return;
if (target) {
waiting_for_status = true;
xcb_client_message_event_t move;
move.response_type = XCB_CLIENT_MESSAGE;
move.window = target;
move.format = 32;
move.type = atom(QXcbAtom::XdndPosition);
move.data.data32[0] = connection()->clipboard()->owner();
move.data.data32[1] = 0; // flags
move.data.data32[2] = (globalPos.x() << 16) + globalPos.y();
move.data.data32[3] = connection()->time();
move.data.data32[4] = toXdndAction(defaultAction(currentDrag()->supportedActions(), QGuiApplication::keyboardModifiers()));
DEBUG() << "sending Xdnd position source=" << move.data.data32[0] << "target=" << move.window;
source_time = connection()->time();
if (w)
handle_xdnd_position(w, &move);
else
xcb_send_event(xcb_connection(), false, proxy_target, XCB_EVENT_MASK_NO_EVENT, (const char *)&move);
}
}
void QXcbDrag::drop(const QPoint &globalPos)
{
QBasicDrag::drop(globalPos);
if (!current_target)
return;
xcb_client_message_event_t drop;
drop.response_type = XCB_CLIENT_MESSAGE;
drop.window = current_target;
drop.format = 32;
drop.type = atom(QXcbAtom::XdndDrop);
drop.data.data32[0] = connection()->clipboard()->owner();
drop.data.data32[1] = 0; // flags
drop.data.data32[2] = connection()->time();
drop.data.data32[3] = 0;
drop.data.data32[4] = currentDrag()->supportedActions();
QXcbWindow *w = connection()->platformWindowFromId(current_proxy_target);
if (w && (w->window()->type() == Qt::Desktop) /*&& !w->acceptDrops()*/)
w = 0;
Transaction t = {
connection()->time(),
current_target,
current_proxy_target,
w,
// current_embeddig_widget,
currentDrag(),
QTime::currentTime()
};
transactions.append(t);
// timer is needed only for drops that came from other processes.
if (!t.targetWindow && cleanup_timer == -1) {
cleanup_timer = startTimer(XdndDropTransactionTimeout);
}
if (w) {
handleDrop(w, &drop);
} else {
xcb_send_event(xcb_connection(), false, current_proxy_target, XCB_EVENT_MASK_NO_EVENT, (const char *)&drop);
}
current_target = 0;
current_proxy_target = 0;
source_time = 0;
// current_embedding_widget = 0;
}
Qt::DropAction QXcbDrag::toDropAction(xcb_atom_t a) const
{
if (a == atom(QXcbAtom::XdndActionCopy) || a == 0)
return Qt::CopyAction;
if (a == atom(QXcbAtom::XdndActionLink))
return Qt::LinkAction;
if (a == atom(QXcbAtom::XdndActionMove))
return Qt::MoveAction;
return Qt::CopyAction;
}
xcb_atom_t QXcbDrag::toXdndAction(Qt::DropAction a) const
{
switch (a) {
case Qt::CopyAction:
return atom(QXcbAtom::XdndActionCopy);
case Qt::LinkAction:
return atom(QXcbAtom::XdndActionLink);
case Qt::MoveAction:
case Qt::TargetMoveAction:
return atom(QXcbAtom::XdndActionMove);
case Qt::IgnoreAction:
return XCB_NONE;
default:
return atom(QXcbAtom::XdndActionCopy);
}
}
int QXcbDrag::findTransactionByWindow(xcb_window_t window)
{
int at = -1;
for (int i = 0; i < transactions.count(); ++i) {
const Transaction &t = transactions.at(i);
if (t.target == window || t.proxy_target == window) {
at = i;
break;
}
}
return at;
}
int QXcbDrag::findTransactionByTime(xcb_timestamp_t timestamp)
{
int at = -1;
for (int i = 0; i < transactions.count(); ++i) {
const Transaction &t = transactions.at(i);
if (t.timestamp == timestamp) {
at = i;
break;
}
}
return at;
}
#if 0
// find an ancestor with XdndAware on it
static Window findXdndAwareParent(Window window)
{
Window target = 0;
forever {
// check if window has XdndAware
Atom type = 0;
int f;
unsigned long n, a;
unsigned char *data = 0;
if (XGetWindowProperty(X11->display, window, ATOM(XdndAware), 0, 0, False,
AnyPropertyType, &type, &f,&n,&a,&data) == Success) {
if (data)
XFree(data);
if (type) {
target = window;
break;
}
}
// try window's parent
Window root;
Window parent;
Window *children;
uint unused;
if (!XQueryTree(X11->display, window, &root, &parent, &children, &unused))
break;
if (children)
XFree(children);
if (window == root)
break;
window = parent;
}
return target;
}
// for embedding only
static QWidget* current_embedding_widget = 0;
static xcb_client_message_event_t last_enter_event;
static bool checkEmbedded(QWidget* w, const XEvent* xe)
{
if (!w)
return false;
if (current_embedding_widget != 0 && current_embedding_widget != w) {
current_target = ((QExtraWidget*)current_embedding_widget)->extraData()->xDndProxy;
current_proxy_target = current_target;
qt_xdnd_send_leave();
current_target = 0;
current_proxy_target = 0;
current_embedding_widget = 0;
}
QWExtra* extra = ((QExtraWidget*)w)->extraData();
if (extra && extra->xDndProxy != 0) {
if (current_embedding_widget != w) {
last_enter_event.xany.window = extra->xDndProxy;
XSendEvent(X11->display, extra->xDndProxy, False, NoEventMask, &last_enter_event);
current_embedding_widget = w;
}
((XEvent*)xe)->xany.window = extra->xDndProxy;
XSendEvent(X11->display, extra->xDndProxy, False, NoEventMask, (XEvent*)xe);
if (currentWindow != w) {
currentWindow = w;
}
return true;
}
current_embedding_widget = 0;
return false;
}
#endif
void QXcbDrag::handleEnter(QPlatformWindow *window, const xcb_client_message_event_t *event, xcb_window_t proxy)
{
Q_UNUSED(window);
DEBUG() << "handleEnter" << window;
xdnd_types.clear();
int version = (int)(event->data.data32[1] >> 24);
if (version > xdnd_version)
return;
xdnd_dragsource = event->data.data32[0];
if (!proxy)
proxy = xdndProxy(connection(), xdnd_dragsource);
current_proxy_target = proxy ? proxy : xdnd_dragsource;
if (event->data.data32[1] & 1) {
// get the types from XdndTypeList
xcb_get_property_cookie_t cookie = xcb_get_property(xcb_connection(), false, xdnd_dragsource,
atom(QXcbAtom::XdndTypelist), XCB_ATOM_ATOM,
0, xdnd_max_type);
xcb_get_property_reply_t *reply = xcb_get_property_reply(xcb_connection(), cookie, 0);
if (reply && reply->type != XCB_NONE && reply->format == 32) {
int length = xcb_get_property_value_length(reply) / 4;
if (length > xdnd_max_type)
length = xdnd_max_type;
xcb_atom_t *atoms = (xcb_atom_t *)xcb_get_property_value(reply);
xdnd_types.reserve(length);
for (int i = 0; i < length; ++i)
xdnd_types.append(atoms[i]);
}
free(reply);
} else {
// get the types from the message
for(int i = 2; i < 5; i++) {
if (event->data.data32[i])
xdnd_types.append(event->data.data32[i]);
}
}
for(int i = 0; i < xdnd_types.length(); ++i)
DEBUG() << " " << connection()->atomName(xdnd_types.at(i));
}
void QXcbDrag::handle_xdnd_position(QPlatformWindow *w, const xcb_client_message_event_t *e)
{
QPoint p((e->data.data32[2] & 0xffff0000) >> 16, e->data.data32[2] & 0x0000ffff);
Q_ASSERT(w);
QRect geometry = w->geometry();
p -= geometry.topLeft();
if (!w || !w->window() || (w->window()->type() == Qt::Desktop))
return;
if (e->data.data32[0] != xdnd_dragsource) {
DEBUG("xdnd drag position from unexpected source (%x not %x)", e->data.data32[0], xdnd_dragsource);
return;
}
currentPosition = p;
currentWindow = w->window();
// timestamp from the source
if (e->data.data32[3] != XCB_NONE) {
target_time = e->data.data32[3];
}
QMimeData *dropData = 0;
Qt::DropActions supported_actions = Qt::IgnoreAction;
if (currentDrag()) {
dropData = currentDrag()->mimeData();
supported_actions = currentDrag()->supportedActions();
} else {
dropData = platformDropData();
supported_actions = Qt::DropActions(toDropAction(e->data.data32[4]));
}
QPlatformDragQtResponse qt_response = QWindowSystemInterface::handleDrag(w->window(),dropData,p,supported_actions);
QRect answerRect(p + geometry.topLeft(), QSize(1,1));
answerRect = qt_response.answerRect().translated(geometry.topLeft()).intersected(geometry);
xcb_client_message_event_t response;
response.response_type = XCB_CLIENT_MESSAGE;
response.window = xdnd_dragsource;
response.format = 32;
response.type = atom(QXcbAtom::XdndStatus);
response.data.data32[0] = xcb_window(w);
response.data.data32[1] = qt_response.isAccepted(); // flags
response.data.data32[2] = 0; // x, y
response.data.data32[3] = 0; // w, h
response.data.data32[4] = toXdndAction(qt_response.acceptedAction()); // action
accepted_drop_action = qt_response.acceptedAction();
if (answerRect.left() < 0)
answerRect.setLeft(0);
if (answerRect.right() > 4096)
answerRect.setRight(4096);
if (answerRect.top() < 0)
answerRect.setTop(0);
if (answerRect.bottom() > 4096)
answerRect.setBottom(4096);
if (answerRect.width() < 0)
answerRect.setWidth(0);
if (answerRect.height() < 0)
answerRect.setHeight(0);
// reset
target_time = XCB_CURRENT_TIME;
if (xdnd_dragsource == connection()->clipboard()->owner())
handle_xdnd_status(&response);
else
Q_XCB_CALL(xcb_send_event(xcb_connection(), false, current_proxy_target,
XCB_EVENT_MASK_NO_EVENT, (const char *)&response));
}
namespace
{
class ClientMessageScanner {
public:
ClientMessageScanner(xcb_atom_t a) : atom(a) {}
xcb_atom_t atom;
bool checkEvent(xcb_generic_event_t *event) const {
if (!event)
return false;
if ((event->response_type & 0x7f) != XCB_CLIENT_MESSAGE)
return false;
return ((xcb_client_message_event_t *)event)->type == atom;
}
};
}
void QXcbDrag::handlePosition(QPlatformWindow * w, const xcb_client_message_event_t *event)
{
xcb_client_message_event_t *lastEvent = const_cast<xcb_client_message_event_t *>(event);
xcb_generic_event_t *nextEvent;
ClientMessageScanner scanner(atom(QXcbAtom::XdndPosition));
while ((nextEvent = connection()->checkEvent(scanner))) {
if (lastEvent != event)
free(lastEvent);
lastEvent = (xcb_client_message_event_t *)nextEvent;
}
handle_xdnd_position(w, lastEvent);
if (lastEvent != event)
free(lastEvent);
}
void QXcbDrag::handle_xdnd_status(const xcb_client_message_event_t *event)
{
DEBUG("xdndHandleStatus");
waiting_for_status = false;
// ignore late status messages
if (event->data.data32[0] && event->data.data32[0] != current_proxy_target)
return;
const bool dropPossible = event->data.data32[1];
setCanDrop(dropPossible);
if (dropPossible) {
accepted_drop_action = toDropAction(event->data.data32[4]);
updateCursor(accepted_drop_action);
} else {
updateCursor(Qt::IgnoreAction);
}
if ((event->data.data32[1] & 2) == 0) {
QPoint p((event->data.data32[2] & 0xffff0000) >> 16, event->data.data32[2] & 0x0000ffff);
QSize s((event->data.data32[3] & 0xffff0000) >> 16, event->data.data32[3] & 0x0000ffff);
source_sameanswer = QRect(p, s);
} else {
source_sameanswer = QRect();
}
}
void QXcbDrag::handleStatus(const xcb_client_message_event_t *event)
{
if (event->window != connection()->clipboard()->owner() || !drag())
return;
xcb_client_message_event_t *lastEvent = const_cast<xcb_client_message_event_t *>(event);
xcb_generic_event_t *nextEvent;
ClientMessageScanner scanner(atom(QXcbAtom::XdndStatus));
while ((nextEvent = connection()->checkEvent(scanner))) {
if (lastEvent != event)
free(lastEvent);
lastEvent = (xcb_client_message_event_t *)nextEvent;
}
handle_xdnd_status(lastEvent);
if (lastEvent != event)
free(lastEvent);
DEBUG("xdndHandleStatus end");
}
void QXcbDrag::handleLeave(QPlatformWindow *w, const xcb_client_message_event_t *event)
{
DEBUG("xdnd leave");
if (!currentWindow || w != currentWindow.data()->handle())
return; // sanity
// ###
// if (checkEmbedded(current_embedding_widget, event)) {
// current_embedding_widget = 0;
// currentWindow.clear();
// return;
// }
if (event->data.data32[0] != xdnd_dragsource) {
// This often happens - leave other-process window quickly
DEBUG("xdnd drag leave from unexpected source (%x not %x", event->data.data32[0], xdnd_dragsource);
}
QWindowSystemInterface::handleDrag(w->window(),0,QPoint(),Qt::IgnoreAction);
xdnd_dragsource = 0;
xdnd_types.clear();
currentWindow.clear();
}
void QXcbDrag::send_leave()
{
if (!current_target)
return;
xcb_client_message_event_t leave;
leave.response_type = XCB_CLIENT_MESSAGE;
leave.window = current_target;
leave.format = 32;
leave.type = atom(QXcbAtom::XdndLeave);
leave.data.data32[0] = connection()->clipboard()->owner();
leave.data.data32[1] = 0; // flags
leave.data.data32[2] = 0; // x, y
leave.data.data32[3] = 0; // w, h
leave.data.data32[4] = 0; // just null
QXcbWindow *w = connection()->platformWindowFromId(current_proxy_target);
if (w && (w->window()->type() == Qt::Desktop) /*&& !w->acceptDrops()*/)
w = 0;
if (w)
handleLeave(w, (const xcb_client_message_event_t *)&leave);
else
xcb_send_event(xcb_connection(), false,current_proxy_target,
XCB_EVENT_MASK_NO_EVENT, (const char *)&leave);
current_target = 0;
current_proxy_target = 0;
source_time = XCB_CURRENT_TIME;
waiting_for_status = false;
}
void QXcbDrag::handleDrop(QPlatformWindow *, const xcb_client_message_event_t *event)
{
DEBUG("xdndHandleDrop");
if (!currentWindow) {
xdnd_dragsource = 0;
return; // sanity
}
const uint32_t *l = event->data.data32;
DEBUG("xdnd drop");
if (l[0] != xdnd_dragsource) {
DEBUG("xdnd drop from unexpected source (%x not %x", l[0], xdnd_dragsource);
return;
}
// update the "user time" from the timestamp in the event.
if (l[2] != 0)
target_time = /*X11->userTime =*/ l[2];
Qt::DropActions supported_drop_actions;
QMimeData *dropData = 0;
if (currentDrag()) {
dropData = currentDrag()->mimeData();
supported_drop_actions = Qt::DropActions(l[4]);
} else {
dropData = platformDropData();
supported_drop_actions = accepted_drop_action;
}
if (!dropData)
return;
// ###
// int at = findXdndDropTransactionByTime(target_time);
// if (at != -1)
// dropData = QDragManager::dragPrivate(X11->dndDropTransactions.at(at).object)->data;
// if we can't find it, then use the data in the drag manager
QPlatformDropQtResponse response = QWindowSystemInterface::handleDrop(currentWindow.data(),dropData,currentPosition,supported_drop_actions);
setExecutedDropAction(response.acceptedAction());
xcb_client_message_event_t finished;
finished.response_type = XCB_CLIENT_MESSAGE;
finished.window = xdnd_dragsource;
finished.format = 32;
finished.type = atom(QXcbAtom::XdndFinished);
finished.data.data32[0] = currentWindow ? xcb_window(currentWindow.data()) : XCB_NONE;
finished.data.data32[1] = response.isAccepted(); // flags
finished.data.data32[2] = toXdndAction(response.acceptedAction());
Q_XCB_CALL(xcb_send_event(xcb_connection(), false, current_proxy_target,
XCB_EVENT_MASK_NO_EVENT, (char *)&finished));
xdnd_dragsource = 0;
currentWindow.clear();
waiting_for_status = false;
// reset
target_time = XCB_CURRENT_TIME;
}
void QXcbDrag::handleFinished(const xcb_client_message_event_t *event)
{
DEBUG("xdndHandleFinished");
if (event->window != connection()->clipboard()->owner())
return;
const unsigned long *l = (const unsigned long *)event->data.data32;
DNDDEBUG << "xdndHandleFinished, l[0]" << l[0]
<< "current_target" << current_target
<< "qt_xdnd_current_proxy_targe" << current_proxy_target;
if (l[0]) {
int at = findTransactionByWindow(l[0]);
if (at != -1) {
Transaction t = transactions.takeAt(at);
if (t.drag)
t.drag->deleteLater();
// QDragManager *manager = QDragManager::self();
// Window target = current_target;
// Window proxy_target = current_proxy_target;
// QWidget *embedding_widget = current_embedding_widget;
// QDrag *currentObject = manager->object;
// current_target = t.target;
// current_proxy_target = t.proxy_target;
// current_embedding_widget = t.embedding_widget;
// manager->object = t.object;
// if (!passive)
// (void) checkEmbedded(currentWindow, xe);
// current_embedding_widget = 0;
// current_target = 0;
// current_proxy_target = 0;
// current_target = target;
// current_proxy_target = proxy_target;
// current_embedding_widget = embedding_widget;
// manager->object = currentObject;
} else {
qWarning("QXcbDrag::handleFinished - drop data has expired");
}
}
waiting_for_status = false;
}
void QXcbDrag::timerEvent(QTimerEvent* e)
{
if (e->timerId() == cleanup_timer) {
bool stopTimer = true;
for (int i = 0; i < transactions.count(); ++i) {
const Transaction &t = transactions.at(i);
if (t.targetWindow) {
// dnd within the same process, don't delete, these are taken care of
// in handleFinished()
continue;
}
QTime currentTime = QTime::currentTime();
int delta = t.time.msecsTo(currentTime);
if (delta > XdndDropTransactionTimeout) {
/* delete transactions which are older than XdndDropTransactionTimeout. It could mean
one of these:
- client has crashed and as a result we have never received XdndFinished
- showing dialog box on drop event where user's response takes more time than XdndDropTransactionTimeout (QTBUG-14493)
- dnd takes unusually long time to process data
*/
if (t.drag)
t.drag->deleteLater();
transactions.removeAt(i--);
} else {
stopTimer = false;
}
}
if (stopTimer && cleanup_timer != -1) {
killTimer(cleanup_timer);
cleanup_timer = -1;
}
}
}
void QXcbDrag::cancel()
{
DEBUG("QXcbDrag::cancel");
QBasicDrag::cancel();
if (current_target)
send_leave();
}
void QXcbDrag::handleSelectionRequest(const xcb_selection_request_event_t *event)
{
xcb_selection_notify_event_t notify;
notify.response_type = XCB_SELECTION_NOTIFY;
notify.requestor = event->requestor;
notify.selection = event->selection;
notify.target = XCB_NONE;
notify.property = XCB_NONE;
notify.time = event->time;
// which transaction do we use? (note: -2 means use current currentDrag())
int at = -1;
// figure out which data the requestor is really interested in
if (currentDrag() && event->time == source_time) {
// requestor wants the current drag data
at = -2;
} else {
// if someone has requested data in response to XdndDrop, find the corresponding transaction. the
// spec says to call xcb_convert_selection() using the timestamp from the XdndDrop
at = findTransactionByTime(event->time);
if (at == -1) {
// no dice, perhaps the client was nice enough to use the same window id in
// xcb_convert_selection() that we sent the XdndDrop event to.
at = findTransactionByWindow(event->requestor);
}
// if (at == -1 && event->time == XCB_CURRENT_TIME) {
// // previous Qt versions always requested the data on a child of the target window
// // using CurrentTime... but it could be asking for either drop data or the current drag's data
// Window target = findXdndAwareParent(event->requestor);
// if (target) {
// if (current_target && current_target == target)
// at = -2;
// else
// at = findXdndDropTransactionByWindow(target);
// }
// }
}
QDrag *transactionDrag = 0;
if (at >= 0) {
transactionDrag = transactions.at(at).drag;
} else if (at == -2) {
transactionDrag = currentDrag();
}
if (transactionDrag) {
xcb_atom_t atomFormat = event->target;
int dataFormat = 0;
QByteArray data;
if (QXcbMime::mimeDataForAtom(connection(), event->target, transactionDrag->mimeData(),
&data, &atomFormat, &dataFormat)) {
int dataSize = data.size() / (dataFormat / 8);
xcb_change_property(xcb_connection(), XCB_PROP_MODE_REPLACE, event->requestor, event->property,
atomFormat, dataFormat, dataSize, (const void *)data.constData());
notify.property = event->property;
notify.target = atomFormat;
}
}
xcb_window_t proxy_target = xdndProxy(connection(), event->requestor);
if (!proxy_target)
proxy_target = event->requestor;
xcb_send_event(xcb_connection(), false, proxy_target, XCB_EVENT_MASK_NO_EVENT, (const char *)¬ify);
}
bool QXcbDrag::dndEnable(QXcbWindow *w, bool on)
{
DNDDEBUG << "xdndEnable" << w << on;
if (on) {
QXcbWindow *xdnd_widget = 0;
if ((w->window()->type() == Qt::Desktop)) {
if (desktop_proxy) // *WE* already have one.
return false;
QXcbConnectionGrabber grabber(connection());
// As per Xdnd4, use XdndProxy
xcb_window_t proxy_id = xdndProxy(connection(), w->xcb_window());
if (!proxy_id) {
desktop_proxy = new QWindow;
xdnd_widget = static_cast<QXcbWindow *>(desktop_proxy->handle());
proxy_id = xdnd_widget->xcb_window();
xcb_atom_t xdnd_proxy = atom(QXcbAtom::XdndProxy);
xcb_change_property(xcb_connection(), XCB_PROP_MODE_REPLACE, w->xcb_window(), xdnd_proxy,
XCB_ATOM_WINDOW, 32, 1, &proxy_id);
xcb_change_property(xcb_connection(), XCB_PROP_MODE_REPLACE, proxy_id, xdnd_proxy,
XCB_ATOM_WINDOW, 32, 1, &proxy_id);
}
} else {
xdnd_widget = w;
}
if (xdnd_widget) {
DNDDEBUG << "setting XdndAware for" << xdnd_widget << xdnd_widget->xcb_window();
xcb_atom_t atm = xdnd_version;
xcb_change_property(xcb_connection(), XCB_PROP_MODE_REPLACE, xdnd_widget->xcb_window(),
atom(QXcbAtom::XdndAware), XCB_ATOM_ATOM, 32, 1, &atm);
return true;
} else {
return false;
}
} else {
if ((w->window()->type() == Qt::Desktop)) {
xcb_delete_property(xcb_connection(), w->xcb_window(), atom(QXcbAtom::XdndProxy));
delete desktop_proxy;
desktop_proxy = 0;
} else {
DNDDEBUG << "not deleting XDndAware";
}
return true;
}
}
bool QXcbDrag::ownsDragObject() const
{
return true;
}
QXcbDropData::QXcbDropData(QXcbDrag *d)
: QXcbMime(),
drag(d)
{
}
QXcbDropData::~QXcbDropData()
{
}
QVariant QXcbDropData::retrieveData_sys(const QString &mimetype, QVariant::Type requestedType) const
{
QByteArray mime = mimetype.toLatin1();
QVariant data = xdndObtainData(mime, requestedType);
return data;
}
QVariant QXcbDropData::xdndObtainData(const QByteArray &format, QVariant::Type requestedType) const
{
QByteArray result;
QXcbConnection *c = drag->connection();
QXcbWindow *xcb_window = c->platformWindowFromId(drag->xdnd_dragsource);
if (xcb_window && drag->currentDrag() && xcb_window->window()->type() != Qt::Desktop) {
QMimeData *data = drag->currentDrag()->mimeData();
if (data->hasFormat(QLatin1String(format)))
result = data->data(QLatin1String(format));
return result;
}
QVector<xcb_atom_t> atoms = drag->xdnd_types;
QByteArray encoding;
xcb_atom_t a = mimeAtomForFormat(c, QLatin1String(format), requestedType, atoms, &encoding);
if (a == XCB_NONE)
return result;
if (c->clipboard()->getSelectionOwner(drag->atom(QXcbAtom::XdndSelection)) == XCB_NONE)
return result; // should never happen?
xcb_atom_t xdnd_selection = c->atom(QXcbAtom::XdndSelection);
result = c->clipboard()->getSelection(xdnd_selection, a, xdnd_selection, drag->targetTime());
return mimeConvertToFormat(c, a, result, QLatin1String(format), requestedType, encoding);
}
bool QXcbDropData::hasFormat_sys(const QString &format) const
{
return formats().contains(format);
}
QStringList QXcbDropData::formats_sys() const
{
QStringList formats;
for (int i = 0; i < drag->xdnd_types.size(); ++i) {
QString f = mimeAtomToString(drag->connection(), drag->xdnd_types.at(i));
if (!formats.contains(f))
formats.append(f);
}
return formats;
}
#endif // QT_NO_DRAGANDDROP
QT_END_NAMESPACE
| 33.806864 | 147 | 0.615297 | [
"geometry",
"object"
] |
929717a6b07c341db32135c6b139334ef53f482c | 16,061 | cpp | C++ | legacyapi/Parser.cpp | marcusspangenberg/SymphonyMediaBridge | b46eb38ec5585e1280720a20170ef505fdd2a4c9 | [
"Apache-2.0"
] | 13 | 2021-11-24T09:55:32.000Z | 2022-03-25T12:29:50.000Z | legacyapi/Parser.cpp | marcusspangenberg/SymphonyMediaBridge | b46eb38ec5585e1280720a20170ef505fdd2a4c9 | [
"Apache-2.0"
] | 10 | 2021-11-23T15:21:41.000Z | 2022-03-28T08:37:59.000Z | legacyapi/Parser.cpp | marcusspangenberg/SymphonyMediaBridge | b46eb38ec5585e1280720a20170ef505fdd2a4c9 | [
"Apache-2.0"
] | 4 | 2021-11-23T14:58:44.000Z | 2022-03-13T12:11:00.000Z | #include "legacyapi/Parser.h"
#include "utils/Base64.h"
namespace
{
template <typename T>
void setIfExists(utils::Optional<T>& target, const nlohmann::json& data, const char* name)
{
if (data.find(name) != data.end())
{
target.set(data[name].get<typename utils::Optional<T>::ValueType>());
}
}
template <typename T>
void setIfExists(T& target, const nlohmann::json& data, const char* name)
{
const auto& it = data.find(name);
if (it != data.end())
{
target = it->get<T>();
}
}
template <typename T>
void setIfExistsOrDefault(T& target, const nlohmann::json& data, const char* name, T&& defaultValue)
{
const auto& it = data.find(name);
if (it != data.end())
{
target = it->get<T>();
}
else
{
target = std::forward<T>(defaultValue);
}
}
template <>
void setIfExists(utils::Optional<bool>& target, const nlohmann::json& data, const char* name)
{
if (data.find(name) != data.end())
{
const auto& jsonElement = data[name];
if (jsonElement.is_string())
{
target.set(data[name].get<std::string>().compare("true") == 0);
}
else
{
target.set(data[name].get<bool>());
}
}
}
template <>
void setIfExists(utils::Optional<std::string>& target, const nlohmann::json& data, const char* name)
{
if (data.find(name) != data.end())
{
const auto& jsonElement = data[name];
if (jsonElement.is_string())
{
target.set(data[name].get<std::string>());
}
else if (jsonElement.is_number_integer())
{
target.set(std::to_string(data[name].get<int32_t>()));
}
else if (jsonElement.is_boolean())
{
if (jsonElement.get<bool>())
{
target.set("true");
}
else
{
target.set("false");
}
}
}
}
legacyapi::Transport parseTransport(const nlohmann::json& data)
{
legacyapi::Transport transport;
setIfExists(transport._xmlns, data, "xmlns");
if (data.find("rtcp-mux") != data.end())
{
const auto& rtcpMux = data["rtcp-mux"];
if (rtcpMux.is_string())
{
transport._rtcpMux = data["rtcp-mux"].get<std::string>().compare("true") == 0;
}
else
{
transport._rtcpMux = data["rtcp-mux"].get<bool>();
}
}
else
{
transport._rtcpMux = false;
}
setIfExists(transport._ufrag, data, "ufrag");
setIfExists(transport._pwd, data, "pwd");
if (data.find("fingerprints") != data.end())
{
for (const auto& fingerprintJson : data["fingerprints"])
{
legacyapi::Fingerprint fingerprint;
fingerprint._fingerprint = fingerprintJson["fingerprint"].get<std::string>();
fingerprint._setup = fingerprintJson["setup"].get<std::string>();
fingerprint._hash = fingerprintJson["hash"].get<std::string>();
transport._fingerprints.emplace_back(std::move(fingerprint));
}
}
if (data.find("candidates") != data.end())
{
for (const auto& candidateJson : data["candidates"])
{
legacyapi::Candidate candidate;
candidate._generation = candidateJson["generation"].get<uint32_t>();
candidate._component = candidateJson["component"].get<uint32_t>();
candidate._protocol = candidateJson["protocol"].get<std::string>();
candidate._port = candidateJson["port"].get<uint32_t>();
candidate._ip = candidateJson["ip"].get<std::string>();
setIfExists(candidate._relPort, candidateJson, "rel-port");
setIfExists(candidate._relAddr, candidateJson, "rel-addr");
candidate._foundation = candidateJson["foundation"].get<std::string>();
candidate._priority = candidateJson["priority"].get<uint32_t>();
candidate._type = candidateJson["type"].get<std::string>();
candidate._network =
candidateJson.find("network") != candidateJson.end() ? candidateJson["network"].get<uint32_t>() : 0;
transport._candidates.emplace_back(std::move(candidate));
}
}
else if (data.find("connection") != data.end())
{
const auto& connectionJson = data["connection"];
legacyapi::Connection connection;
connection._port = connectionJson["port"].get<uint32_t>();
connection._ip = connectionJson["ip"].get<std::string>();
transport._connection.set(std::move(connection));
}
return transport;
}
} // namespace
namespace legacyapi
{
namespace Parser
{
Conference parse(const nlohmann::json& data)
{
Conference conference;
conference._id = data["id"].get<std::string>();
if (data.find("channel-bundles") != data.end())
{
for (const auto& channelBundleJson : data["channel-bundles"])
{
ChannelBundle channelBundle;
channelBundle._id = channelBundleJson["id"].get<std::string>();
channelBundle._transport = parseTransport(channelBundleJson["transport"]);
conference._channelBundles.emplace_back(std::move(channelBundle));
}
}
if (data.find("contents") != data.end())
{
for (const auto& contentJson : data["contents"])
{
Content content;
content._name = contentJson["name"].get<std::string>();
if (contentJson.find("channels") != contentJson.end())
{
for (const auto& channelJson : contentJson["channels"])
{
Channel channel;
setIfExists<>(channel._id, channelJson, "id");
setIfExists<>(channel._endpoint, channelJson, "endpoint");
setIfExists<>(channel._channelBundleId, channelJson, "channel-bundle-id");
setIfExists<>(channel._initiator, channelJson, "initiator");
setIfExists<>(channel._rtpLevelRelayType, channelJson, "rtp-level-relay-type");
setIfExists<>(channel._expire, channelJson, "expire");
setIfExists<>(channel._direction, channelJson, "direction");
setIfExists<>(channel._lastN, channelJson, "last-n");
if (channelJson.find("sources") != channelJson.end())
{
for (const auto& sourceJson : channelJson["sources"])
{
channel._sources.push_back(sourceJson.get<uint32_t>());
}
}
if (channelJson.find("transport") != channelJson.end())
{
channel._transport.set(parseTransport(channelJson["transport"]));
}
if (channelJson.find("payload-types") != channelJson.end())
{
for (const auto& payloadTypeJson : channelJson["payload-types"])
{
PayloadType payloadType;
payloadType._id = payloadTypeJson["id"].get<uint32_t>();
payloadType._name = payloadTypeJson["name"].get<std::string>();
{
const auto& clockRate = payloadTypeJson["clockrate"];
if (clockRate.is_string())
{
payloadType._clockRate = payloadTypeJson["clockrate"].get<std::string>();
}
else
{
payloadType._clockRate =
std::to_string(payloadTypeJson["clockrate"].get<uint32_t>());
}
}
setIfExists(payloadType._channels, payloadTypeJson, "channels");
if (payloadTypeJson.find("parameters") != payloadTypeJson.end())
{
const auto& parametersJson = payloadTypeJson["parameters"];
for (auto parameterJsonItr = parametersJson.cbegin();
parameterJsonItr != parametersJson.cend();
++parameterJsonItr)
{
payloadType._parameters.emplace_back(
std::make_pair(parameterJsonItr.key(), parameterJsonItr.value()));
}
}
if (payloadTypeJson.find("rtcp-fbs") != payloadTypeJson.end())
{
for (const auto& rtcpFbJson : payloadTypeJson["rtcp-fbs"])
{
PayloadType::RtcpFb rtcpFb;
rtcpFb._type = rtcpFbJson["type"].get<std::string>();
setIfExists(rtcpFb._subtype, rtcpFbJson, "subtype");
payloadType._rtcpFbs.emplace_back(std::move(rtcpFb));
}
}
channel._payloadTypes.emplace_back(std::move(payloadType));
}
}
if (channelJson.find("rtp-hdrexts") != channelJson.end())
{
for (const auto& rtpHdrExtJson : channelJson["rtp-hdrexts"])
{
Channel::RtpHdrExt rtpHdrExt;
rtpHdrExt._id = rtpHdrExtJson["id"].get<uint32_t>();
rtpHdrExt._uri = rtpHdrExtJson["uri"].get<std::string>();
if (rtpHdrExt._id > 0 && rtpHdrExt._id < 15)
{
channel._rtpHeaderHdrExts.emplace_back(std::move(rtpHdrExt));
}
}
}
if (channelJson.find("ssrc-groups") != channelJson.end())
{
for (const auto& ssrcGroupJson : channelJson["ssrc-groups"])
{
SsrcGroup ssrcGroup;
for (const auto& ssrcJson : ssrcGroupJson["sources"])
{
const uint32_t ssrc = ssrcJson.is_string() ? std::stoul(ssrcJson.get<std::string>())
: ssrcJson.get<uint32_t>();
ssrcGroup._sources.push_back(ssrc);
}
ssrcGroup._semantics = ssrcGroupJson["semantics"].get<std::string>();
channel._ssrcGroups.emplace_back(std::move(ssrcGroup));
}
}
if (channelJson.find("ssrc-attributes") != channelJson.end())
{
for (const auto& ssrcAttributeJson : channelJson["ssrc-attributes"])
{
SsrcAttribute ssrcAttribute;
ssrcAttribute._content = ssrcAttributeJson["content"].get<std::string>();
for (const auto& ssrcJson : ssrcAttributeJson["sources"])
{
const auto ssrc = ssrcJson.is_string() ? std::stoul(ssrcJson.get<std::string>())
: ssrcJson.get<uint32_t>();
ssrcAttribute._sources.push_back(ssrc);
}
channel._ssrcAttributes.push_back(ssrcAttribute);
}
}
if (channelJson.find("ssrc-whitelist") != channelJson.end())
{
std::vector<uint32_t> ssrcWhitelist;
for (const auto& ssrcJson : channelJson["ssrc-whitelist"])
{
const auto ssrc = ssrcJson.is_string() ? std::stoul(ssrcJson.get<std::string>())
: ssrcJson.get<uint32_t>();
ssrcWhitelist.push_back(ssrc);
}
channel._ssrcWhitelist.set(std::move(ssrcWhitelist));
}
content._channels.emplace_back(std::move(channel));
}
}
if (contentJson.find("sctpconnections") != contentJson.end())
{
for (const auto& sctpConnectionJson : contentJson["sctpconnections"])
{
SctpConnection sctpConnection;
setIfExists<>(sctpConnection._id, sctpConnectionJson, "id");
setIfExists<>(sctpConnection._endpoint, sctpConnectionJson, "endpoint");
setIfExists<>(sctpConnection._channelBundleId, sctpConnectionJson, "channel-bundle-id");
setIfExists<>(sctpConnection._initiator, sctpConnectionJson, "initiator");
setIfExists<>(sctpConnection._expire, sctpConnectionJson, "expire");
setIfExists<>(sctpConnection._port, sctpConnectionJson, "port");
if (sctpConnectionJson.find("transport") != sctpConnectionJson.end())
{
sctpConnection._transport.set(parseTransport(sctpConnectionJson["transport"]));
}
content._sctpConnections.emplace_back(std::move(sctpConnection));
}
}
conference._contents.emplace_back(std::move(content));
}
}
if (data.find("recording") != data.end())
{
api::Recording recording;
const auto& recordingJson = data["recording"];
recording._recordingId = recordingJson["recording-id"].get<std::string>();
recording._userId = recordingJson["user-id"].get<std::string>();
const auto& modalaties = recordingJson["recording-modalities"];
setIfExistsOrDefault<>(recording._isAudioEnabled, modalaties, "audio", false);
setIfExistsOrDefault<>(recording._isVideoEnabled, modalaties, "video", false);
setIfExistsOrDefault<>(recording._isScreenshareEnabled, modalaties, "screenshare", false);
if (recordingJson.find("channels") != recordingJson.end())
{
for (const auto& channelJson : recordingJson["channels"])
{
api::RecordingChannel recordingChannel;
setIfExists<>(recordingChannel._id, channelJson, "id");
setIfExists<>(recordingChannel._host, channelJson, "host");
setIfExistsOrDefault<>(recordingChannel._port, channelJson, "port", uint16_t(0));
std::string aesKeyEnc;
std::string saltEnc;
setIfExists<>(aesKeyEnc, channelJson, "aes-key");
setIfExists<>(saltEnc, channelJson, "aes-salt");
if (!aesKeyEnc.empty())
{
utils::Base64::decode(aesKeyEnc, recordingChannel._aesKey, 32);
}
if (!saltEnc.empty())
{
utils::Base64::decode(saltEnc, recordingChannel._aesSalt, 12);
}
recording._channels.emplace_back(recordingChannel);
}
}
conference._recording.set(std::move(recording));
}
return conference;
}
} // namespace Parser
} // namespace legacyapi
| 39.365196 | 116 | 0.498973 | [
"vector"
] |
92974e045f72f68df7e76339dde53072bb89b344 | 3,750 | cpp | C++ | video_file_hdl/src/video_file_hdl.cpp | majorx234/qt_videocam_hough | bb8c5ac8045a1d312e3428705967960496688846 | [
"BSD-2-Clause"
] | null | null | null | video_file_hdl/src/video_file_hdl.cpp | majorx234/qt_videocam_hough | bb8c5ac8045a1d312e3428705967960496688846 | [
"BSD-2-Clause"
] | null | null | null | video_file_hdl/src/video_file_hdl.cpp | majorx234/qt_videocam_hough | bb8c5ac8045a1d312e3428705967960496688846 | [
"BSD-2-Clause"
] | null | null | null | #include "video_file_hdl.hpp"
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
#include <fstream>
using namespace cv;
using namespace std;
VideoFile_hdl::VideoFile_hdl():imagecount(0)
{
}
VideoFile_hdl::VideoFile_hdl(Size newVideoSize) : videoSize(newVideoSize),imagecount(0)
{
}
VideoFile_hdl::~VideoFile_hdl()
{
}
int VideoFile_hdl::loadVideoRaw(std::string filename)
{
/*
clear();
std::ifstream infile(filename, std::ios::in | std::ifstream::binary);
std::istreambuf_iterator<char> iter(infile);
std::copy(iter, std::istreambuf_iterator<char>{}, std::back_inserter(video_vec)); // this leaves newVector empty
imagecount = video_vec.size();
frame_iter = video_vec.begin();
videoSize = (*frame_iter).size();
return video_vec.size();*/
return 0;
}
int VideoFile_hdl::saveVideoRaw(std::string filename)
{
/*
std::ofstream outfile(filename, std::ios::out | std::ofstream::binary);
std::ostream_iterator<cv::Mat> output_iterator(outfile);
std::copy(video_vec.begin(), video_vec.end(), output_iterator);
outfile.flush();
outfile.close();*/
return 0; //return size of file
}
int VideoFile_hdl::saveVideo(std::string filename)
{
VideoWriter outputVideo(filename, CV_FOURCC('P','I','M','1'), 20, videoSize, true);
if ( !outputVideo.isOpened() ) //if not initialize the VideoWriter successfully, exit the program
{
cout << "ERROR: Failed to write the video" << endl;
//throw "ERROR: Failed to write the video";
return -1;
}
for(auto frame : video_vec) {
outputVideo.write(frame); //
}
return 0;
}
int VideoFile_hdl::loadVideo(std::string filename)
{
clear();
VideoCapture capture(filename);
int dWidth, dHeight;
dWidth = capture.get(CV_CAP_PROP_FRAME_WIDTH); //get the width of frames of the video
dHeight = capture.get(CV_CAP_PROP_FRAME_HEIGHT); //get the height of frames of the video
Size newFrameSize(static_cast<int>(dWidth), static_cast<int>(dHeight));
videoSize = newFrameSize;
clear();
if( !capture.isOpened() ){
//throw "Error when reading steam_avi";
//printf("VideoFile_hdl::loadVideo capture not opened\n");
return -1;
}
for( ; ; )
{
Mat frame;
capture >> frame;
if(frame.empty())
break;
video_vec.push_back(frame); //maybe use add_frame here
imagecount++;
}
frame_iter = video_vec.begin();
return 0;
}
int VideoFile_hdl::loadVideo(std::string filename, int num_frames)
{
clear();
VideoCapture capture(filename);
int dWidth, dHeight;
dWidth = capture.get(CV_CAP_PROP_FRAME_WIDTH); //get the width of frames of the video
dHeight = capture.get(CV_CAP_PROP_FRAME_HEIGHT); //get the height of frames of the video
Size newFrameSize(static_cast<int>(dWidth), static_cast<int>(dHeight));
videoSize = newFrameSize;
clear();
if( !capture.isOpened() ){
//throw "Error when reading steam_avi";
//printf("VideoFile_hdl::loadVideo capture not opened\n");
return -1;
}
for(;;)
{
Mat frame;
capture >> frame;
if((frame.empty())|| (imagecount > num_frames-1))
break;
video_vec.push_back(frame); //maybe use add_frame here
imagecount++;
}
frame_iter = video_vec.begin();
return 0;
}
int VideoFile_hdl::videoStep()
{
}
int VideoFile_hdl::clear()
{
videoSize = cv::Size(0,0);
imagecount=0;
video_vec.clear();
return 0;
}
int VideoFile_hdl::addFrame(cv::Mat frame)
{
video_vec.push_back(frame);
imagecount++;
return imagecount;
}
int VideoFile_hdl::getFrame(cv::Mat &frame)
{
if (frame_iter != video_vec.end())
{
frame = *frame_iter;
frame_iter++;
return 0;
}
return -1;
}
int VideoFile_hdl::get_size()
{
return imagecount;
} | 22.865854 | 114 | 0.6776 | [
"vector"
] |
9299a75ad3742a45455b4bd1ea9629689ce81a58 | 8,213 | cpp | C++ | dbms/src/Databases/DatabaseDictionary.cpp | margaritiko/ClickHouse | 6f28e69e97c73a71091efa3dfc891c43371f2348 | [
"Apache-2.0"
] | null | null | null | dbms/src/Databases/DatabaseDictionary.cpp | margaritiko/ClickHouse | 6f28e69e97c73a71091efa3dfc891c43371f2348 | [
"Apache-2.0"
] | null | null | null | dbms/src/Databases/DatabaseDictionary.cpp | margaritiko/ClickHouse | 6f28e69e97c73a71091efa3dfc891c43371f2348 | [
"Apache-2.0"
] | null | null | null | #include <Databases/DatabaseDictionary.h>
#include <Interpreters/Context.h>
#include <Interpreters/ExternalDictionariesLoader.h>
#include <Storages/StorageDictionary.h>
#include <common/logger_useful.h>
#include <IO/WriteBufferFromString.h>
#include <IO/Operators.h>
#include <Parsers/ParserCreateQuery.h>
#include <Parsers/parseQuery.h>
#include <Parsers/IAST.h>
namespace DB
{
namespace ErrorCodes
{
extern const int TABLE_ALREADY_EXISTS;
extern const int UNKNOWN_TABLE;
extern const int LOGICAL_ERROR;
extern const int CANNOT_GET_CREATE_TABLE_QUERY;
extern const int SYNTAX_ERROR;
extern const int UNSUPPORTED_METHOD;
}
DatabaseDictionary::DatabaseDictionary(const String & name_)
: name(name_),
log(&Logger::get("DatabaseDictionary(" + name + ")"))
{
}
void DatabaseDictionary::loadStoredObjects(Context &, bool)
{
}
Tables DatabaseDictionary::listTables(const Context & context, const FilterByNameFunction & filter_by_name)
{
Tables tables;
ExternalLoader::LoadResults load_results;
if (filter_by_name)
{
/// If `filter_by_name` is set, we iterate through all dictionaries with such names. That's why we need to load all of them.
load_results = context.getExternalDictionariesLoader().tryLoad<ExternalLoader::LoadResults>(filter_by_name);
}
else
{
/// If `filter_by_name` isn't set, we iterate through only already loaded dictionaries. We don't try to load all dictionaries in this case.
load_results = context.getExternalDictionariesLoader().getCurrentLoadResults();
}
for (const auto & load_result: load_results)
{
/// Load tables only from XML dictionaries, don't touch other
if (load_result.object && load_result.repository_name.empty())
{
auto dict_ptr = std::static_pointer_cast<const IDictionaryBase>(load_result.object);
auto dict_name = dict_ptr->getName();
const DictionaryStructure & dictionary_structure = dict_ptr->getStructure();
auto columns = StorageDictionary::getNamesAndTypes(dictionary_structure);
tables[dict_name] = StorageDictionary::create(getDatabaseName(), dict_name, ColumnsDescription{columns}, context, true, dict_name);
}
}
return tables;
}
bool DatabaseDictionary::isTableExist(
const Context & context,
const String & table_name) const
{
return context.getExternalDictionariesLoader().getCurrentStatus(table_name) != ExternalLoader::Status::NOT_EXIST;
}
bool DatabaseDictionary::isDictionaryExist(
const Context & /*context*/,
const String & /*table_name*/) const
{
return false;
}
DatabaseDictionariesIteratorPtr DatabaseDictionary::getDictionariesIterator(
const Context & /*context*/,
const FilterByNameFunction & /*filter_by_dictionary_name*/)
{
return std::make_unique<DatabaseDictionariesSnapshotIterator>();
}
void DatabaseDictionary::createDictionary(
const Context & /*context*/,
const String & /*dictionary_name*/,
const ASTPtr & /*query*/)
{
throw Exception("Dictionary engine doesn't support dictionaries.", ErrorCodes::UNSUPPORTED_METHOD);
}
void DatabaseDictionary::removeDictionary(
const Context & /*context*/,
const String & /*table_name*/)
{
throw Exception("Dictionary engine doesn't support dictionaries.", ErrorCodes::UNSUPPORTED_METHOD);
}
void DatabaseDictionary::attachDictionary(
const String & /*dictionary_name*/, const Context & /*context*/)
{
throw Exception("Dictionary engine doesn't support dictionaries.", ErrorCodes::UNSUPPORTED_METHOD);
}
void DatabaseDictionary::detachDictionary(const String & /*dictionary_name*/, const Context & /*context*/)
{
throw Exception("Dictionary engine doesn't support dictionaries.", ErrorCodes::UNSUPPORTED_METHOD);
}
ASTPtr DatabaseDictionary::tryGetCreateDictionaryQuery(
const Context & /*context*/,
const String & /*table_name*/) const
{
return nullptr;
}
ASTPtr DatabaseDictionary::getCreateDictionaryQuery(
const Context & /*context*/,
const String & /*table_name*/) const
{
throw Exception("Dictionary engine doesn't support dictionaries.", ErrorCodes::UNSUPPORTED_METHOD);
}
StoragePtr DatabaseDictionary::tryGetTable(
const Context & context,
const String & table_name) const
{
auto dict_ptr = context.getExternalDictionariesLoader().tryGetDictionary(table_name);
if (dict_ptr)
{
const DictionaryStructure & dictionary_structure = dict_ptr->getStructure();
auto columns = StorageDictionary::getNamesAndTypes(dictionary_structure);
return StorageDictionary::create(getDatabaseName(), table_name, ColumnsDescription{columns}, context, true, table_name);
}
return {};
}
DatabaseTablesIteratorPtr DatabaseDictionary::getTablesIterator(const Context & context, const FilterByNameFunction & filter_by_name)
{
return std::make_unique<DatabaseTablesSnapshotIterator>(listTables(context, filter_by_name));
}
bool DatabaseDictionary::empty(const Context & context) const
{
return !context.getExternalDictionariesLoader().hasCurrentlyLoadedObjects();
}
StoragePtr DatabaseDictionary::detachTable(const String & /*table_name*/)
{
throw Exception("DatabaseDictionary: detachTable() is not supported", ErrorCodes::NOT_IMPLEMENTED);
}
void DatabaseDictionary::attachTable(const String & /*table_name*/, const StoragePtr & /*table*/)
{
throw Exception("DatabaseDictionary: attachTable() is not supported", ErrorCodes::NOT_IMPLEMENTED);
}
void DatabaseDictionary::createTable(
const Context &,
const String &,
const StoragePtr &,
const ASTPtr &)
{
throw Exception("DatabaseDictionary: createTable() is not supported", ErrorCodes::NOT_IMPLEMENTED);
}
void DatabaseDictionary::removeTable(
const Context &,
const String &)
{
throw Exception("DatabaseDictionary: removeTable() is not supported", ErrorCodes::NOT_IMPLEMENTED);
}
time_t DatabaseDictionary::getObjectMetadataModificationTime(
const Context &,
const String &)
{
return static_cast<time_t>(0);
}
ASTPtr DatabaseDictionary::getCreateTableQueryImpl(const Context & context,
const String & table_name, bool throw_on_error) const
{
String query;
{
WriteBufferFromString buffer(query);
const auto & dictionaries = context.getExternalDictionariesLoader();
auto dictionary = throw_on_error ? dictionaries.getDictionary(table_name)
: dictionaries.tryGetDictionary(table_name);
auto names_and_types = StorageDictionary::getNamesAndTypes(dictionary->getStructure());
buffer << "CREATE TABLE " << backQuoteIfNeed(name) << '.' << backQuoteIfNeed(table_name) << " (";
buffer << StorageDictionary::generateNamesAndTypesDescription(names_and_types.begin(), names_and_types.end());
buffer << ") Engine = Dictionary(" << backQuoteIfNeed(table_name) << ")";
}
ParserCreateQuery parser;
const char * pos = query.data();
std::string error_message;
auto ast = tryParseQuery(parser, pos, pos + query.size(), error_message,
/* hilite = */ false, "", /* allow_multi_statements = */ false, 0);
if (!ast && throw_on_error)
throw Exception(error_message, ErrorCodes::SYNTAX_ERROR);
return ast;
}
ASTPtr DatabaseDictionary::getCreateTableQuery(const Context & context, const String & table_name) const
{
return getCreateTableQueryImpl(context, table_name, true);
}
ASTPtr DatabaseDictionary::tryGetCreateTableQuery(const Context & context, const String & table_name) const
{
return getCreateTableQueryImpl(context, table_name, false);
}
ASTPtr DatabaseDictionary::getCreateDatabaseQuery(const Context & /*context*/) const
{
String query;
{
WriteBufferFromString buffer(query);
buffer << "CREATE DATABASE " << backQuoteIfNeed(name) << " ENGINE = Dictionary";
}
ParserCreateQuery parser;
return parseQuery(parser, query.data(), query.data() + query.size(), "", 0);
}
void DatabaseDictionary::shutdown()
{
}
String DatabaseDictionary::getDatabaseName() const
{
return name;
}
}
| 32.983936 | 147 | 0.723244 | [
"object"
] |
929ef6167a7b50940930db9bb24feebac560242a | 6,842 | cpp | C++ | RaiderEngine/GameObject2D.cpp | rystills/RaiderEngine | 5a5bce4b3eca2f2f8c166e3a6296b07309af0d8a | [
"MIT"
] | 4 | 2019-07-20T08:41:04.000Z | 2022-03-04T01:53:38.000Z | RaiderEngine/GameObject2D.cpp | rystills/RaiderEngine | 5a5bce4b3eca2f2f8c166e3a6296b07309af0d8a | [
"MIT"
] | null | null | null | RaiderEngine/GameObject2D.cpp | rystills/RaiderEngine | 5a5bce4b3eca2f2f8c166e3a6296b07309af0d8a | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "GameObject2D.hpp"
#include "model.hpp"
#include "settings.hpp"
#include "Tilemap.hpp"
GameObject2D::GameObject2D(glm::vec2 position, float rotation, glm::vec2 scale, glm::vec3 color, std::string spriteName, bool posIsCenter, float depth, Collider2D* collider) :
position(position), rotation(rotation), color(color), scaleVal(scale), depth(depth), collider(collider) {
sprite = (spriteName == "" ? Model::defaultDiffuseMap : Model::loadTextureSimple(spriteName));
recalculateHalfExtents();
if (posIsCenter) {
center = position;
position -= halfExtents;
}
else
center = position + halfExtents;
}
void GameObject2D::initStaticVertexBuffer() {
// Configure VAO and temporary VBO
GLuint VBO;
GLfloat vertices[] = {
// Pos // Tex
0.0f, 0.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f, 1.0f,
1.0f, 0.0f, 1.0f, 0.0f,
1.0f, 1.0f, 1.0f, 1.0f,
};
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glBindVertexArray(VAO);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), (GLvoid*)0);
// configure VBO for transform (model) instanced rendering (attribs 1-4 contain the model matrix in the 2D shader)
glBindBuffer(GL_ARRAY_BUFFER, 0);
glGenBuffers(1, &instancedModelVBO);
glBindBuffer(GL_ARRAY_BUFFER, instancedModelVBO);
GLsizei vec4Size = sizeof(glm::vec4);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 4 * vec4Size, (GLvoid*)0);
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, 4 * vec4Size, (GLvoid*)(vec4Size));
glEnableVertexAttribArray(3);
glVertexAttribPointer(3, 4, GL_FLOAT, GL_FALSE, 4 * vec4Size, (GLvoid*)(2 * vec4Size));
glEnableVertexAttribArray(4);
glVertexAttribPointer(4, 4, GL_FLOAT, GL_FALSE, 4 * vec4Size, (GLvoid*)(3 * vec4Size));
glVertexAttribDivisor(1, 1);
glVertexAttribDivisor(2, 1);
glVertexAttribDivisor(3, 1);
glVertexAttribDivisor(4, 1);
// configure VBO for color instanced rendering
glBindBuffer(GL_ARRAY_BUFFER, 0);
glGenBuffers(1, &instancedColorVBO);
glBindBuffer(GL_ARRAY_BUFFER, instancedColorVBO);
glEnableVertexAttribArray(5);
glVertexAttribPointer(5, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0);
glVertexAttribDivisor(5, 1);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
}
void GameObject2D::recalculateHalfExtents() {
halfExtents = { abs(scaleVal.x) * sprite.width * .5f, abs(scaleVal.y) * sprite.height * .5f };
}
void GameObject2D::setCenter(glm::vec2 newCenter) {
center = newCenter;
position = center - halfExtents;
isDirty = true;
}
void GameObject2D::setCenter(float x, float y) {
center.x = x;
center.y = y;
position = center - halfExtents;
isDirty = true;
}
void GameObject2D::setPos(glm::vec2 newPos) {
position = newPos;
center = position + halfExtents;
isDirty = true;
}
void GameObject2D::setPos(float newX, float newY) {
position.x = newX;
position.y = newY;
center = position + halfExtents;
isDirty = true;
}
void GameObject2D::translate(glm::vec2 posOff) {
position += posOff;
center += posOff;
isDirty = true;
}
void GameObject2D::translate(float xOff, float yOff) {
position.x += xOff;
position.y += yOff;
center.x += xOff;
center.y += yOff;
isDirty = true;
}
void GameObject2D::setRot(float newRot) {
rotation = newRot;
isDirty = true;
}
void GameObject2D::rotate(float rotOff) {
rotation += rotOff;
isDirty = true;
}
void GameObject2D::setScale(glm::vec2 newScale) {
scaleVal = newScale;
recalculateHalfExtents();
isDirty = true;
}
void GameObject2D::setScale(float newX, float newY) {
scaleVal.x = newX;
scaleVal.y = newY;
recalculateHalfExtents();
isDirty = true;
}
void GameObject2D::scale(glm::vec2 scaleOff) {
scaleVal += scaleOff;
recalculateHalfExtents();
isDirty = true;
}
void GameObject2D::scale(float xOff, float yOff) {
scaleVal.x += xOff;
scaleVal.y += yOff;
recalculateHalfExtents();
isDirty = true;
}
bool GameObject2D::inScreenBounds() {
glm::vec2 appliedScale(scaleVal.x * sprite.width, scaleVal.y * sprite.height);
return ((position.y + appliedScale.y < 0 || position.y >= TARGET_HEIGHT) || (position.x + appliedScale.x < 0 || position.x >= TARGET_WIDTH));
}
bool GameObject2D::collidesWith(GameObject2D* other, int colLayer) {
return collider && other->collider && other->collider->collisionLayer == colLayer && collider->collision(center, rotation, other->collider, other->center, other->rotation);
}
bool GameObject2D::collidesWith(Tilemap* t, int colLayer) {
// check collisions with all tiles that lie within the square containing our bounding radius
float normalX = center.x - t->pos.x, normalY = center.y - t->pos.y;
unsigned int gridxMin = std::max(0, static_cast<int>((normalX - collider->boundingRadius) / t->gridSize)),
gridxMax = std::max(0, static_cast<int>((normalX + collider->boundingRadius) / t->gridSize)),
gridyMin = std::max(0, static_cast<int>((normalY - collider->boundingRadius) / t->gridSize)),
gridyMax = std::max(0, static_cast<int>((normalY + collider->boundingRadius) / t->gridSize));
for (unsigned int i = gridxMin; i <= gridxMax && i < t->mapSize.x; ++i)
for (unsigned int r = gridyMin; r <= gridyMax && r < t->mapSize.y; ++r) {
Collider2D* tcol = t->tileColliders[t->map[i][r]];
if (tcol != NULL && tcol->collisionLayer == colLayer && collider->collision(center, rotation, tcol, glm::vec2(t->pos.x + i * t->gridSize + t->gridSize * .5f, t->pos.y + r * t->gridSize + t->gridSize * .5f), 0))
return true;
}
return false;
}
void GameObject2D::recalculateModel() {
// Prepare transformations
model = glm::mat4(1.0f);
// round position in an effort to achieve pixel perfect 2D rendering
// offset by sprite width/height so that scaling occurs from the center rather than from the topleft
// NOTE: rounding of x and y has been removed to allow smooth subpixel movement in low target resolution games. Consider re-introducing rounding if pixel grid movement is desired
model = glm::translate(model, glm::vec3(position.x + (.5f - .5f*scaleVal.x) * sprite.width, position.y + (.5f - .5f * scaleVal.y) * sprite.height, depth));
// multiply scaling factor by sprite dimensions so that a scale of 1,1 = original size
glm::vec2 appliedScale(scaleVal.x * sprite.width, scaleVal.y * sprite.height);
// translate by the half extents to achieve centered rotation
if (rotation != 0) {
model = glm::translate(model, glm::vec3(0.5f * appliedScale.x, 0.5f * appliedScale.y, 0.0f));
model = glm::rotate(model, rotation, glm::vec3(0.0f, 0.0f, 1.0f));
model = glm::translate(model, glm::vec3(-0.5f * appliedScale.x, -0.5f * appliedScale.y, 0.0f));
}
model = glm::scale(model, glm::vec3(appliedScale, 1.0f));
isDirty = false;
} | 34.908163 | 213 | 0.714411 | [
"model",
"transform"
] |
92a4ebfb6d986b00bef77b4fbf1a886ff10bfbc5 | 2,888 | cc | C++ | brave/renderer/extensions/content_settings_bindings.cc | destenson/brave--muon | 80442e401dd3f78d55f78daf2f5f2d8505970296 | [
"MIT"
] | null | null | null | brave/renderer/extensions/content_settings_bindings.cc | destenson/brave--muon | 80442e401dd3f78d55f78daf2f5f2d8505970296 | [
"MIT"
] | null | null | null | brave/renderer/extensions/content_settings_bindings.cc | destenson/brave--muon | 80442e401dd3f78d55f78daf2f5f2d8505970296 | [
"MIT"
] | null | null | null | // Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "brave/renderer/extensions/content_settings_bindings.h"
#include <string>
#include <vector>
#include "atom/common/native_mate_converters/string16_converter.h"
#include "atom/common/native_mate_converters/value_converter.h"
#include "atom/renderer/content_settings_manager.h"
#include "content/public/renderer/render_frame.h"
#include "content/public/renderer/render_view.h"
#include "extensions/renderer/script_context.h"
#include "third_party/WebKit/public/web/WebView.h"
#include "third_party/WebKit/public/web/WebLocalFrame.h"
#include "third_party/WebKit/public/web/WebDocument.h"
using atom::ContentSettingsManager;
namespace mate {
template<>
struct Converter<ContentSetting> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
ContentSetting val) {
std::string setting;
switch (val) {
case CONTENT_SETTING_ALLOW: setting = "allow"; break;
case CONTENT_SETTING_BLOCK: setting = "block"; break;
case CONTENT_SETTING_ASK: setting = "ask"; break;
case CONTENT_SETTING_SESSION_ONLY: setting = "session"; break;
default: setting = "default"; break;
}
return mate::ConvertToV8(isolate, setting);
}
};
} // namespace mate
namespace brave {
ContentSettingsBindings::ContentSettingsBindings(
extensions::ScriptContext* context)
: extensions::ObjectBackedNativeHandler(context) {
RouteFunction(
"getCurrent",
base::Bind(&ContentSettingsBindings::GetCurrentSetting,
base::Unretained(this)));
RouteFunction(
"getContentTypes",
base::Bind(&ContentSettingsBindings::GetContentTypes,
base::Unretained(this)));
}
ContentSettingsBindings::~ContentSettingsBindings() {
}
void ContentSettingsBindings::GetCurrentSetting(
const v8::FunctionCallbackInfo<v8::Value>& args) {
const std::string content_type =
mate::V8ToString(args[0].As<v8::String>());
bool incognito = args[1].As<v8::Boolean>()->Value();
ContentSetting setting =
atom::ContentSettingsManager::GetInstance()->GetSetting(
ContentSettingsManager::GetOriginOrURL(
context()->GetRenderFrame()->GetWebFrame()),
context()->web_frame()->GetDocument().Url(),
content_type,
incognito);
args.GetReturnValue().Set(
mate::Converter<ContentSetting>::ToV8(context()->isolate(), setting));
}
void ContentSettingsBindings::GetContentTypes(
const v8::FunctionCallbackInfo<v8::Value>& args) {
std::vector<std::string> content_types =
atom::ContentSettingsManager::GetInstance()->GetContentTypes();
args.GetReturnValue().Set(
mate::Converter<std::vector<std::string>>::ToV8(
context()->isolate(), content_types));
}
} // namespace brave
| 32.449438 | 74 | 0.709834 | [
"vector"
] |
92ae6afc4fce83178df5bb2d2decd3f75d6f304b | 2,022 | cpp | C++ | aws-cpp-sdk-lex-models/source/model/StartMigrationResult.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-02-12T08:09:30.000Z | 2022-02-12T08:09:30.000Z | aws-cpp-sdk-lex-models/source/model/StartMigrationResult.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-lex-models/source/model/StartMigrationResult.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/lex-models/model/StartMigrationResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>
#include <utility>
using namespace Aws::LexModelBuildingService::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;
StartMigrationResult::StartMigrationResult() :
m_v1BotLocale(Locale::NOT_SET),
m_migrationStrategy(MigrationStrategy::NOT_SET)
{
}
StartMigrationResult::StartMigrationResult(const Aws::AmazonWebServiceResult<JsonValue>& result) :
m_v1BotLocale(Locale::NOT_SET),
m_migrationStrategy(MigrationStrategy::NOT_SET)
{
*this = result;
}
StartMigrationResult& StartMigrationResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
JsonView jsonValue = result.GetPayload().View();
if(jsonValue.ValueExists("v1BotName"))
{
m_v1BotName = jsonValue.GetString("v1BotName");
}
if(jsonValue.ValueExists("v1BotVersion"))
{
m_v1BotVersion = jsonValue.GetString("v1BotVersion");
}
if(jsonValue.ValueExists("v1BotLocale"))
{
m_v1BotLocale = LocaleMapper::GetLocaleForName(jsonValue.GetString("v1BotLocale"));
}
if(jsonValue.ValueExists("v2BotId"))
{
m_v2BotId = jsonValue.GetString("v2BotId");
}
if(jsonValue.ValueExists("v2BotRole"))
{
m_v2BotRole = jsonValue.GetString("v2BotRole");
}
if(jsonValue.ValueExists("migrationId"))
{
m_migrationId = jsonValue.GetString("migrationId");
}
if(jsonValue.ValueExists("migrationStrategy"))
{
m_migrationStrategy = MigrationStrategyMapper::GetMigrationStrategyForName(jsonValue.GetString("migrationStrategy"));
}
if(jsonValue.ValueExists("migrationTimestamp"))
{
m_migrationTimestamp = jsonValue.GetDouble("migrationTimestamp");
}
return *this;
}
| 23.241379 | 121 | 0.743323 | [
"model"
] |
92b0b427a626a0161acad11aec10acd3753742d3 | 2,231 | hpp | C++ | include/RavEngine/VirtualFileSystem.hpp | Ravbug/RavEngine | 73249827cb2cd3c938bb59447e9edbf7b6f0defc | [
"Apache-2.0"
] | 48 | 2020-11-18T23:14:25.000Z | 2022-03-11T09:13:42.000Z | include/RavEngine/VirtualFileSystem.hpp | Ravbug/RavEngine | 73249827cb2cd3c938bb59447e9edbf7b6f0defc | [
"Apache-2.0"
] | 1 | 2020-11-17T20:53:10.000Z | 2020-12-01T20:27:36.000Z | include/RavEngine/VirtualFileSystem.hpp | Ravbug/RavEngine | 73249827cb2cd3c938bb59447e9edbf7b6f0defc | [
"Apache-2.0"
] | 3 | 2020-12-22T02:40:39.000Z | 2021-10-08T02:54:22.000Z | #pragma once
#include <string>
#include "Function.hpp"
#include "DataStructures.hpp"
#include "Utilities.hpp"
#include "Debug.hpp"
struct PHYSFS_File;
namespace RavEngine{
class VirtualFilesystem {
private:
struct ptrsize{
PHYSFS_File* ptr = nullptr;
size_t size = 0;
};
const ptrsize GetSizeAndPtr(const char* path);
void close(PHYSFS_File* file);
size_t ReadInto(PHYSFS_File*, uint8_t* data, size_t size);
public:
VirtualFilesystem(const std::string&);
/**
Get the file data as a string
@param path the resources path to the asset
@param nullTerminate whether to add a null byte to the end of the data
@return the file data
*/
template<typename vec = RavEngine::Vector<uint8_t>>
const vec FileContentsAt(const char* path, bool nullTerminate = true)
{
vec fileData;
FileContentsAt(path,fileData,nullTerminate);
return fileData;
}
/**
Get the file data in a vector
@param path the resources path to the asset
@param nullTerminate whether to add a null byte to the end of the data
@param datavec the vector to write the data into
*/
template<typename vec = RavEngine::Vector<uint8_t>>
void FileContentsAt(const char* path, vec& datavec, bool nullTerminate = true){
auto fullpath = StrFormat("{}/{}",rootname,path);
if(!Exists(path)){
Debug::Fatal("cannot open {}{}",rootname,path);
}
auto ptrsize = GetSizeAndPtr(fullpath.c_str());
auto ptr = ptrsize.ptr;
auto size = ptrsize.size + (nullTerminate ? 1 : 0);
datavec.resize(size);
size_t length_read = ReadInto(ptrsize.ptr, datavec.data(), size);
if (nullTerminate){
datavec.data()[size-1] = '\0'; //add null terminator
}
close(ptrsize.ptr);
}
/**
@return true if the VFS has the file at the path
*/
bool Exists(const char* path);
/**
Get all the files in a directory
@param path the path to the folder
@param callback function to call on each filename
*/
void IterateDirectory(const char* path, Function<void(const std::string&)> callback);
protected:
std::string rootname;
};
}
| 26.879518 | 86 | 0.647243 | [
"vector"
] |
92b1b75cb9d44a2e00f7d7c2b694c89e3f570527 | 6,427 | cpp | C++ | examples/piloting_telemetry/piloting_robot_telemetry_example.cpp | fada-catec/piloting-mavsdk | 512316f0137b737323550b2b06ae014b6e9b2ae4 | [
"BSD-3-Clause"
] | 4 | 2021-04-12T09:21:10.000Z | 2022-01-11T18:20:32.000Z | examples/piloting_telemetry/piloting_robot_telemetry_example.cpp | fada-catec/piloting-mavsdk | 512316f0137b737323550b2b06ae014b6e9b2ae4 | [
"BSD-3-Clause"
] | 1 | 2021-11-02T09:30:23.000Z | 2022-01-11T06:42:10.000Z | examples/piloting_telemetry/piloting_robot_telemetry_example.cpp | fada-catec/piloting-mavsdk | 512316f0137b737323550b2b06ae014b6e9b2ae4 | [
"BSD-3-Clause"
] | null | null | null | #include <chrono>
#include <iostream>
#include <thread>
#include <mavsdk/mavsdk.h>
#include <mavsdk/plugins/telemetry_robotic_vehicle/telemetry_robotic_vehicle.h>
using namespace mavsdk;
using namespace std::this_thread;
using namespace std::chrono;
#define ERROR_CONSOLE_TEXT "\033[31m" // Turn text on console red
#define RESULT_CONSOLE_TEXT "\033[34m" // Turn text on console blue
#define NORMAL_CONSOLE_TEXT "\033[0m" // Restore normal console colour
int main(int, char**)
{
const uint8_t local_system_id = 1;
const uint8_t local_component_id = 25;
std::vector<uint8_t> sensor_component_ids{35, 45};
const std::string local_ip = "127.0.0.1";
const std::string target_ip = "127.0.0.1";
const int local_port = 14541;
const int target_port = 14540;
const int target_system_id = 2;
Mavsdk mavsdk;
Mavsdk::Configuration config(
local_system_id,
local_component_id,
false,
Mavsdk::Configuration::UsageType::RoboticVehicle);
mavsdk.set_configuration(config);
sleep_for(seconds(1));
const auto connection_result =
mavsdk.setup_udp_connection(local_ip, local_port, target_ip, target_port);
if (connection_result != ConnectionResult::Success) {
std::cout << ERROR_CONSOLE_TEXT << "Connection failed: " << connection_result
<< NORMAL_CONSOLE_TEXT << std::endl;
return EXIT_FAILURE;
}
std::cout << "Connection established correctly!" << std::endl;
std::shared_ptr<System> target_system;
while (!(target_system = mavsdk.system(target_system_id))) {
std::cout << ERROR_CONSOLE_TEXT << "No target system (" << unsigned(target_system_id)
<< ") alive" << NORMAL_CONSOLE_TEXT << std::endl;
sleep_for(seconds(1));
}
std::cout << "Target system (" << unsigned(target_system->get_system_id()) << ") connected!"
<< std::endl;
sleep_for(seconds(3));
///////////////////
auto telemetry_rv = TelemetryRoboticVehicle{target_system};
TelemetryBase::PositionVelocityNed vehicle_position;
vehicle_position.system_id = local_system_id;
vehicle_position.component_id = local_component_id;
vehicle_position.position.north_m = 1.1f;
vehicle_position.position.east_m = 2.2f;
vehicle_position.position.down_m = 3.3f;
vehicle_position.velocity.north_m_s = 4.4f;
vehicle_position.velocity.east_m_s = 5.5f;
vehicle_position.velocity.down_m_s = 6.6f;
std::vector<TelemetryBase::PositionVelocityNed> sensor_positions;
for (unsigned i = 0; i < sensor_component_ids.size(); ++i) {
TelemetryBase::PositionVelocityNed data;
data.system_id = local_system_id;
data.component_id = sensor_component_ids[i];
data.position.north_m = 1.1f;
data.position.east_m = 2.2f;
data.position.down_m = 3.3f;
data.velocity.north_m_s = 4.4f;
data.velocity.east_m_s = 5.5f;
data.velocity.down_m_s = 6.6f;
sensor_positions.push_back(data);
}
TelemetryBase::Attitude vehicle_attitude;
vehicle_attitude.system_id = local_system_id;
vehicle_attitude.component_id = local_component_id;
vehicle_attitude.quaternion_angle.x = 7.7f;
vehicle_attitude.quaternion_angle.y = 8.8f;
vehicle_attitude.quaternion_angle.z = 9.9f;
vehicle_attitude.quaternion_angle.w = 10.10f;
vehicle_attitude.angular_velocity.roll_rad_s = 11.11f;
vehicle_attitude.angular_velocity.pitch_rad_s = 12.12f;
vehicle_attitude.angular_velocity.yaw_rad_s = 13.13f;
std::vector<TelemetryBase::Attitude> sensor_attitudes;
for (unsigned i = 0; i < sensor_component_ids.size(); ++i) {
TelemetryBase::Attitude data;
data.system_id = local_system_id;
data.component_id = sensor_component_ids[i];
data.quaternion_angle.x = 7.7f;
data.quaternion_angle.y = 8.8f;
data.quaternion_angle.z = 9.9f;
data.quaternion_angle.w = 10.10f;
data.angular_velocity.roll_rad_s = 11.11f;
data.angular_velocity.pitch_rad_s = 12.12f;
data.angular_velocity.yaw_rad_s = 13.13f;
sensor_attitudes.push_back(data);
}
TelemetryBase::TextStatus text_status;
text_status.type = TelemetryBase::TextStatusType::Info;
text_status.text = "text status example";
unsigned text_counter = 0;
for (;;) {
std::cout << "Sending vehicle position" << std::endl;
auto now = system_clock::now().time_since_epoch();
vehicle_position.stamp_ms = duration_cast<milliseconds>(now).count();
telemetry_rv.send_local_position_ned(vehicle_position);
for (unsigned i = 0; i < sensor_positions.size(); ++i) {
auto& sensor_position = sensor_positions[i];
std::cout << "Sending sensor (" << unsigned(sensor_position.component_id)
<< ") position" << std::endl;
auto now = system_clock::now().time_since_epoch();
sensor_position.stamp_ms = duration_cast<milliseconds>(now).count();
telemetry_rv.send_local_position_ned(sensor_position);
}
std::cout << "Sending vehicle attitude" << std::endl;
now = system_clock::now().time_since_epoch();
vehicle_attitude.stamp_ms = duration_cast<milliseconds>(now).count();
telemetry_rv.send_attitude(vehicle_attitude);
for (unsigned i = 0; i < sensor_attitudes.size(); ++i) {
auto& sensor_attitude = sensor_attitudes[i];
std::cout << "Sending sensor (" << unsigned(sensor_attitude.component_id)
<< ") attitude" << std::endl;
auto now = system_clock::now().time_since_epoch();
sensor_attitude.stamp_ms = duration_cast<milliseconds>(now).count();
telemetry_rv.send_attitude(sensor_attitude);
}
std::cout << "Sending text status" << std::endl;
if (text_counter == 1) {
text_status.type = TelemetryBase::TextStatusType::Warning;
} else if (text_counter == 2) {
text_status.type = TelemetryBase::TextStatusType::Error;
} else {
text_status.type = TelemetryBase::TextStatusType::Info;
}
telemetry_rv.send_text_status(text_status);
text_counter = ++text_counter % 3;
sleep_for(milliseconds(1000));
}
std::cout << "Finished..." << std::endl;
return EXIT_SUCCESS;
}
| 38.951515 | 96 | 0.665163 | [
"vector"
] |
92b2154fbfe62334fdf0660423e7f1629e11a5f8 | 5,753 | cc | C++ | services/ui/ws/window_finder.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | services/ui/ws/window_finder.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | services/ui/ws/window_finder.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2015 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 "services/ui/ws/window_finder.h"
#include "base/containers/adapters.h"
#include "services/ui/ws/server_window.h"
#include "services/ui/ws/server_window_delegate.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/point3_f.h"
#include "ui/gfx/geometry/point_f.h"
#include "ui/gfx/transform.h"
namespace ui {
namespace ws {
namespace {
bool IsLocationInNonclientArea(const ServerWindow* target,
const gfx::Point& location) {
if (!target->parent() || target->bounds().size().IsEmpty())
return false;
gfx::Rect client_area(target->bounds().size());
client_area.Inset(target->client_area());
if (client_area.Contains(location))
return false;
for (const auto& rect : target->additional_client_areas()) {
if (rect.Contains(location))
return false;
}
return true;
}
bool ShouldUseExtendedHitRegion(const ServerWindow* window) {
if (!window->parent())
return false;
const mojom::ShowState show_state = window->GetShowState();
if (show_state == mojom::ShowState::MAXIMIZED ||
show_state == mojom::ShowState::FULLSCREEN) {
return false;
}
// This matches the logic of EasyResizeWindowTargeter.
return !window->transient_parent() ||
window->transient_parent() == window->parent();
}
// Returns true if |location_in_window| is in the extended hit region and not
// in the normal bounds of |window|.
bool IsLocationInExtendedHitRegion(EventSource event_source,
const ServerWindow* window,
const gfx::Point& location_in_window) {
if (!ShouldUseExtendedHitRegion(window))
return false;
const gfx::Insets& extended_hit_insets =
event_source == EventSource::MOUSE
? window->parent()->extended_mouse_hit_test_region()
: window->parent()->extended_touch_hit_test_region();
if (extended_hit_insets.IsEmpty())
return false;
gfx::Rect child_bounds(window->bounds().size());
if (child_bounds.Contains(location_in_window))
return false;
child_bounds.Inset(extended_hit_insets);
return child_bounds.Contains(location_in_window);
}
gfx::Transform TransformFromParent(const ServerWindow* window,
const gfx::Transform& current_transform) {
gfx::Transform transform = current_transform;
if (!window->transform().IsIdentity())
transform.ConcatTransform(window->transform());
gfx::Transform translation;
translation.Translate(static_cast<float>(window->bounds().x()),
static_cast<float>(window->bounds().y()));
transform.ConcatTransform(translation);
return transform;
}
bool FindDeepestVisibleWindowForLocationImpl(
ServerWindow* window,
EventSource event_source,
const gfx::Point& location_in_root,
const gfx::Point& location_in_window,
const gfx::Transform& transform_from_parent,
DeepestWindow* deepest_window) {
// The non-client area takes precedence over descendants, as otherwise the
// user would likely not be able to hit the non-client area as it's common
// for descendants to go into the non-client area.
if (IsLocationInNonclientArea(window, location_in_window)) {
deepest_window->window = window;
deepest_window->in_non_client_area = true;
return true;
}
const mojom::EventTargetingPolicy event_targeting_policy =
window->event_targeting_policy();
if (event_targeting_policy == ui::mojom::EventTargetingPolicy::NONE)
return false;
if (event_targeting_policy ==
mojom::EventTargetingPolicy::TARGET_AND_DESCENDANTS ||
event_targeting_policy == mojom::EventTargetingPolicy::DESCENDANTS_ONLY) {
const ServerWindow::Windows& children = window->children();
for (ServerWindow* child : base::Reversed(children)) {
if (!child->visible())
continue;
const gfx::Transform child_transform =
TransformFromParent(child, transform_from_parent);
gfx::Point3F location_in_child3(gfx::PointF{location_in_root});
child_transform.TransformPointReverse(&location_in_child3);
const gfx::Point location_in_child =
gfx::ToFlooredPoint(location_in_child3.AsPointF());
if (IsLocationInExtendedHitRegion(event_source, child,
location_in_child)) {
deepest_window->window = child;
deepest_window->in_non_client_area = true;
return true;
}
gfx::Rect child_bounds(child->bounds().size());
if (!child_bounds.Contains(location_in_child) ||
(child->hit_test_mask() &&
!child->hit_test_mask()->Contains(location_in_child))) {
continue;
}
if (FindDeepestVisibleWindowForLocationImpl(
child, event_source, location_in_root, location_in_child,
child_transform, deepest_window)) {
return true;
}
}
}
if (event_targeting_policy == mojom::EventTargetingPolicy::DESCENDANTS_ONLY)
return false;
deepest_window->window = window;
deepest_window->in_non_client_area = false;
return true;
}
} // namespace
DeepestWindow FindDeepestVisibleWindowForLocation(ServerWindow* root_window,
EventSource event_source,
const gfx::Point& location) {
DeepestWindow result;
FindDeepestVisibleWindowForLocationImpl(root_window, event_source, location,
location, gfx::Transform(), &result);
return result;
}
} // namespace ws
} // namespace ui
| 35.294479 | 80 | 0.681731 | [
"geometry",
"transform"
] |
92b324197ee2dd57d15dc33c5b152d272c10f4da | 5,947 | cpp | C++ | Official Windows Platform Sample/Windows 8.1 Store app samples/[C++]-Windows 8.1 Store app samples/Application resources and localization sample/C++/Scenario12.xaml.cpp | zzgchina888/msdn-code-gallery-microsoft | 21cb9b6bc0da3b234c5854ecac449cb3bd261f29 | [
"MIT"
] | 2 | 2022-01-21T01:40:58.000Z | 2022-01-21T01:41:10.000Z | Official Windows Platform Sample/Windows 8.1 Store app samples/[C++]-Windows 8.1 Store app samples/Application resources and localization sample/C++/Scenario12.xaml.cpp | zzgchina888/msdn-code-gallery-microsoft | 21cb9b6bc0da3b234c5854ecac449cb3bd261f29 | [
"MIT"
] | 1 | 2022-03-15T04:21:41.000Z | 2022-03-15T04:21:41.000Z | Official Windows Platform Sample/Windows 8.1 Store app samples/[C++]-Windows 8.1 Store app samples/Application resources and localization sample/C++/Scenario12.xaml.cpp | zzgchina888/msdn-code-gallery-microsoft | 21cb9b6bc0da3b234c5854ecac449cb3bd261f29 | [
"MIT"
] | null | null | null | //*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
//
// Scenario12.xaml.cpp
// Implementation of the Scenario12 class
//
#include <ppltasks.h>
#include "pch.h"
#include "Scenario12.xaml.h"
using namespace SDKSample::ApplicationResources;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Navigation;
using namespace Windows::ApplicationModel::Resources::Core;
using namespace concurrency;
Scenario12::Scenario12()
{
InitializeComponent();
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page.</param>
void Scenario12::OnNavigatedTo(NavigationEventArgs^ e)
{
// A pointer back to the main page. This is needed if you want to call methods in MainPage such
// as NotifyUser()
rootPage = MainPage::Current;
}
void Scenario12::Scenario12Button_Show_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
// Two coding patterns will be used:
// 1. Get a ResourceContext on the UI thread using GetForCurrentView and pass
// to the non-UI thread
// 2. Get a ResourceContext on the non-UI thread using GetForViewIndependentUse
//
// Two analogous patterns could be used for ResourceLoader instead of ResourceContext.
// pattern 1: get a ResourceContext for the UI thread
ResourceContext^ defaultContextForUiThread = ResourceContext::GetForCurrentView();
// pattern 2: we'll create a view-independent context in the non-UI worker thread
// We need some things in order to display results in the UI (doing that
// for purposes of this sample, to show that work was actually done in the
// worker thread): a pair of vectors to capture data, and a pair of variable
// references to the controls where the results will be displayed (needed to
// pass to the .then lambda).
Platform::Collections::Vector<Platform::String^>^ uiDependentResourceItems = ref new Platform::Collections::Vector<Platform::String^>();
Platform::Collections::Vector<Platform::String^>^ uiIndependentResourceItems = ref new Platform::Collections::Vector<Platform::String^>();
ItemsControl^ viewDependentListControl = ViewDependentResourcesList;
ItemsControl^ viewIndependentListControl = ViewIndependentResourcesList;
// use a worker thread for the heavy lifting so the UI isn't blocked
concurrency::create_task(
Windows::System::Threading::ThreadPool::RunAsync(
ref new Windows::System::Threading::WorkItemHandler(
[defaultContextForUiThread, uiDependentResourceItems, uiIndependentResourceItems](Windows::Foundation::IAsyncAction^ /*action*/)
{
// This is happening asynchronously on a background worker thread,
// not on the UI thread.
ResourceMap^ stringResourceMap = ResourceManager::Current->MainResourceMap->GetSubtree("Resources");
// coding pattern 1: the defaultContextForUiThread variable was created above and has been captured to use here
// coding pattern 2: get a view-independent ResourceContext
ResourceContext^ defaultViewIndependentResourceContext = ResourceContext::GetForViewIndependentUse();
// NOTE: The ResourceContext obtained using GetForViewIndependentUse() has no scale qualifier
// value set. If this ResourceContext is used in its default state to retrieve a resource, that
// will work provided that the resource does not have any scale-qualified variants. But if the
// resource has any scale-qualified variants, then that will fail at runtime.
//
// A scale qualifier value on this ResourceContext can be set programmatically. If that is done,
// then the ResourceContext can be used to retrieve a resource that has scale-qualified variants.
// But if the scale qualifier is reset (e.g., using the ResourceContext::Reset() method), then
// it will return to the default state with no scale qualifier value set, and cannot be used
// to retrieve any resource that has scale-qualified variants.
// simulate processing a number of items
// just using a single string resource: that's sufficient to demonstrate
for (auto i = 0; i < 4; i++)
{
// pattern 1: use the ResourceContext from the UI thread
Platform::String^ item1 = stringResourceMap->GetValue("string1", defaultContextForUiThread)->ValueAsString;
uiDependentResourceItems->Append(item1);
// pattern 2: use the view-independent ResourceContext
Platform::String^ item2 = stringResourceMap->GetValue("string1", defaultViewIndependentResourceContext)->ValueAsString;
uiIndependentResourceItems->Append(item2);
}
}))
).then([uiDependentResourceItems, uiIndependentResourceItems, viewDependentListControl, viewIndependentListControl]
{
// After the async work is complete, this will happen on the UI thread.
// Display the results in one go. (A more finessed design might add results
// in the UI asynchronously, but that goes beyond what this sample is
// demonstrating.)
viewDependentListControl->ItemsSource = uiDependentResourceItems;
viewIndependentListControl->ItemsSource = uiIndependentResourceItems;
});
} | 46.826772 | 142 | 0.693795 | [
"object",
"vector"
] |
92b79249535bd0f91020d649356ffa1870ba85b0 | 6,336 | cpp | C++ | native/examples/examples.cpp | wonderit/bootcamp | 6c72a91521f35db865a6f30d1fec2be3b11be199 | [
"MIT"
] | null | null | null | native/examples/examples.cpp | wonderit/bootcamp | 6c72a91521f35db865a6f30d1fec2be3b11be199 | [
"MIT"
] | null | null | null | native/examples/examples.cpp | wonderit/bootcamp | 6c72a91521f35db865a6f30d1fec2be3b11be199 | [
"MIT"
] | null | null | null | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
#include "examples.h"
#include <vector>
#include <fstream>
#include <iostream>
#include <numeric>
using namespace std;
using namespace seal;
void bootcamp_demo()
{
// CLIENT'S VIEW
// Vector of inputs
vector<double> inputs{ 0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9 };
// Setting up encryption parameters
EncryptionParameters parms(scheme_type::CKKS);
size_t poly_modulus_degree = 8192;
parms.set_poly_modulus_degree(poly_modulus_degree);
parms.set_coeff_modulus(CoeffModulus::Create(poly_modulus_degree, { 50, 30, 50 }));
// Set up the SEALContext
auto context = SEALContext::Create(parms);
cout << "Parameters are valid: " << boolalpha
<< context->key_context_data()->qualifiers().parameters_set << endl;
cout << "Maximal allowed coeff_modulus bit-count for this poly_modulus_degree: "
<< CoeffModulus::MaxBitCount(poly_modulus_degree) << endl;
cout << "Current coeff_modulus bit-count: "
<< context->key_context_data()->total_coeff_modulus_bit_count() << endl;
// Use a scale of 2^30 to encode
double scale = pow(2.0, 30);
// Create a vector of plaintexts
CKKSEncoder encoder(context);
vector<Plaintext> pts;
for (auto val : inputs) {
Plaintext p;
// Encode val as a plaintext vector: [ val, val, val, val, ..., val ]
// (poly_modulus_degree/2 == 4096 repetitions)
encoder.encode(val, scale, p);
pts.emplace_back(move(p));
}
// Set up keys
KeyGenerator keygen(context);
auto sk = keygen.secret_key();
auto pk = keygen.public_key();
// Set up Encryptor
Encryptor encryptor(context, pk);
// Create a vector of ciphertexts
vector<Ciphertext> cts;
for (const auto &p : pts) {
Ciphertext c;
encryptor.encrypt(p, c);
cts.emplace_back(move(c));
}
// Now send this vector to the server!
// Also send the EncryptionParameters.
// SERVER'S VIEW
// Load EncryptionParameters and set up SEALContext
vector<double> weights{ 2.0, -1.0, 2.0, -1.0, 2.0, -1.0, 2.0, -1.0, 2.0, -1.0 };
vector<Plaintext> weight_pts;
for (auto wt : weights) {
Plaintext p;
// Encode wt as a plaintext vector: [ wt, wt, wt, wt, ..., wt ]
// (poly_modulus_degree/2 == 4096 repetitions)
encoder.encode(wt, scale, p);
weight_pts.emplace_back(p);
}
// Create the Evaluator
Evaluator evaluator(context);
for (auto i = 0; i < cts.size(); i++) {
evaluator.multiply_plain_inplace(cts[i], weight_pts[i]);
evaluator.rescale_to_next_inplace(cts[i]);
}
// Sum up the ciphertexts
Ciphertext ct_result;
evaluator.add_many(cts, ct_result);
// CLIENT'S VIEW ONCE AGAIN
Decryptor decryptor(context, sk);
// Decrypt the result
Plaintext pt_result;
decryptor.decrypt(ct_result, pt_result);
// Decode the result
vector<double> vec_result;
encoder.decode(pt_result, vec_result);
cout << "Result: " << vec_result[0] << endl;
cout << "True result: " << inner_product(inputs.cbegin(), inputs.cend(), weights.cbegin(), 0.0) << endl;
cout << "test" << endl;
}
int main()
{
#ifdef SEAL_VERSION
cout << "Microsoft SEAL version: " << SEAL_VERSION << endl;
#endif
bootcamp_demo();
while (false)
{
cout << "+---------------------------------------------------------+" << endl;
cout << "| The following examples should be executed while reading |" << endl;
cout << "| comments in associated files in native/examples/. |" << endl;
cout << "+---------------------------------------------------------+" << endl;
cout << "| Examples | Source Files |" << endl;
cout << "+----------------------------+----------------------------+" << endl;
cout << "| 1. BFV Basics | 1_bfv_basics.cpp |" << endl;
cout << "| 2. Encoders | 2_encoders.cpp |" << endl;
cout << "| 3. Levels | 3_levels.cpp |" << endl;
cout << "| 4. CKKS Basics | 4_ckks_basics.cpp |" << endl;
cout << "| 5. Rotation | 5_rotation.cpp |" << endl;
cout << "| 6. Performance Test | 6_performance.cpp |" << endl;
cout << "+----------------------------+----------------------------+" << endl;
/*
Print how much memory we have allocated from the current memory pool.
By default the memory pool will be a static global pool and the
MemoryManager class can be used to change it. Most users should have
little or no reason to touch the memory allocation system.
*/
size_t megabytes = MemoryManager::GetPool().alloc_byte_count() >> 20;
cout << "[" << setw(7) << right << megabytes << " MB] "
<< "Total allocation from the memory pool" << endl;
int selection = 0;
bool invalid = true;
do
{
cout << endl << "> Run example (1 ~ 6) or exit (0): ";
if (!(cin >> selection))
{
invalid = false;
}
else if (selection < 0 || selection > 6)
{
invalid = false;
}
else
{
invalid = true;
}
if (!invalid)
{
cout << " [Beep~~] Invalid option: type 0 ~ 6" << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
} while (!invalid);
switch (selection)
{
case 1:
example_bfv_basics();
break;
case 2:
example_encoders();
break;
case 3:
example_levels();
break;
case 4:
example_ckks_basics();
break;
case 5:
example_rotation();
break;
case 6:
example_performance_test();
break;
case 0:
return 0;
}
}
return 0;
} | 30.028436 | 108 | 0.522727 | [
"vector"
] |
92b7a65760d4ca46f6e486d7c256f88440fa188f | 16,762 | cc | C++ | android_webview/browser/aw_pac_processor.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | android_webview/browser/aw_pac_processor.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | android_webview/browser/aw_pac_processor.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2021-01-05T23:43:46.000Z | 2021-01-07T23:36:34.000Z | // Copyright 2019 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 "android_webview/browser/aw_pac_processor.h"
#include <android/multinetwork.h>
#include <arpa/inet.h>
#include <dlfcn.h>
#include <netdb.h>
#include <unistd.h>
#include <cstddef>
#include <memory>
#include <string>
#include "android_webview/browser_jni_headers/AwPacProcessor_jni.h"
#include "base/android/jni_android.h"
#include "base/android/jni_array.h"
#include "base/android/jni_string.h"
#include "base/bind.h"
#include "base/logging.h"
#include "base/no_destructor.h"
#include "base/task/post_task.h"
#include "base/task/thread_pool/thread_pool_instance.h"
#include "base/threading/thread_restrictions.h"
#include "net/base/address_list.h"
#include "net/base/completion_once_callback.h"
#include "net/base/net_errors.h"
#include "net/base/network_isolation_key.h"
#include "net/proxy_resolution/pac_file_data.h"
#include "net/proxy_resolution/proxy_info.h"
using base::android::AttachCurrentThread;
using base::android::ConvertJavaStringToUTF8;
using base::android::ConvertUTF8ToJavaString;
using base::android::JavaParamRef;
using base::android::JavaRef;
using base::android::ScopedJavaGlobalRef;
using base::android::ScopedJavaLocalRef;
class NetworkIsolationKey;
namespace android_webview {
namespace {
static_assert(NETWORK_UNSPECIFIED == 0,
"Java side AwPacProcessor#NETWORK_UNSPECIFIED needs update");
typedef int (*getaddrinfofornetwork_ptr_t)(net_handle_t,
const char*,
const char*,
const struct addrinfo*,
struct addrinfo**);
// The definition of android_getaddrinfofornetwork is conditional
// on __ANDROID_API__ >= 23. It's not possible to just have a runtime check for
// the SDK level to guard a call that might not exist on older platform
// versions: all native function imports are resolved at load time and loading
// the library will fail if they're unresolvable. Therefore we need to search
// for the function via dlsym.
int AndroidGetAddrInfoForNetwork(net_handle_t network,
const char* node,
const char* service,
const struct addrinfo* hints,
struct addrinfo** res) {
static getaddrinfofornetwork_ptr_t getaddrinfofornetwork = [] {
getaddrinfofornetwork_ptr_t ptr =
reinterpret_cast<getaddrinfofornetwork_ptr_t>(
dlsym(RTLD_DEFAULT, "android_getaddrinfofornetwork"));
DCHECK(ptr);
return ptr;
}();
return getaddrinfofornetwork(network, node, service, hints, res);
}
net::IPAddress StringToIPAddress(const std::string& address) {
net::IPAddress ip_address;
if (!ip_address.AssignFromIPLiteral(std::string(address))) {
LOG(ERROR) << "Not a supported IP literal: " << std::string(address);
}
return ip_address;
}
scoped_refptr<base::SingleThreadTaskRunner> GetTaskRunner() {
struct ThreadHolder {
base::Thread thread_;
scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
ThreadHolder() : thread_("AwPacProcessor") {
thread_.Start();
task_runner_ = thread_.task_runner();
}
};
static ThreadHolder thread_holder;
return thread_holder.task_runner_;
}
proxy_resolver::ProxyResolverV8TracingFactory* GetProxyResolverFactory() {
static std::unique_ptr<proxy_resolver::ProxyResolverV8TracingFactory>
factory = proxy_resolver::ProxyResolverV8TracingFactory::Create();
return factory.get();
}
} // namespace
// TODO(amalova): We could use a separate thread or thread pool for executing
// blocking DNS queries, to get better performance.
class HostResolver : public proxy_resolver::ProxyHostResolver {
public:
HostResolver(net_handle_t net_handle) : net_handle_(net_handle) {}
~HostResolver() override {}
std::unique_ptr<proxy_resolver::ProxyHostResolver::Request> CreateRequest(
const std::string& hostname,
net::ProxyResolveDnsOperation operation,
const net::NetworkIsolationKey&) override {
return std::make_unique<RequestImpl>(hostname, operation, net_handle_,
link_addresses_);
}
void SetNetworkLinkAddresses(
const std::vector<net::IPAddress>& link_addresses) {
link_addresses_ = link_addresses;
}
private:
net_handle_t net_handle_ = 0;
std::vector<net::IPAddress> link_addresses_;
class RequestImpl : public proxy_resolver::ProxyHostResolver::Request {
public:
RequestImpl(const std::string& hostname,
net::ProxyResolveDnsOperation operation,
net_handle_t net_handle,
const std::vector<net::IPAddress>& link_addresses)
: hostname_(hostname),
operation_(operation),
net_handle_(net_handle),
link_addresses_(link_addresses) {}
~RequestImpl() override = default;
int Start(net::CompletionOnceCallback callback) override {
bool success = false;
switch (operation_) {
case net::ProxyResolveDnsOperation::DNS_RESOLVE:
success = DnsResolveImpl(hostname_);
break;
case net::ProxyResolveDnsOperation::DNS_RESOLVE_EX:
success = DnsResolveExImpl(hostname_);
break;
case net::ProxyResolveDnsOperation::MY_IP_ADDRESS:
success = MyIpAddressImpl();
break;
case net::ProxyResolveDnsOperation::MY_IP_ADDRESS_EX:
success = MyIpAddressExImpl();
break;
}
return success ? net::OK : net::ERR_NAME_RESOLUTION_FAILED;
}
const std::vector<net::IPAddress>& GetResults() const override {
return results_;
}
private:
bool IsNetworkSpecified() { return net_handle_ != NETWORK_UNSPECIFIED; }
bool MyIpAddressImpl() {
// For network-aware queries the results are set from Java on
// NetworkCallback#onLinkPropertiesChanged.
// See SetNetworkLinkAddresses.
if (IsNetworkSpecified()) {
results_.push_back(link_addresses_.front());
return true;
}
std::string my_hostname = GetHostName();
if (my_hostname.empty())
return false;
return DnsResolveImpl(my_hostname);
}
bool MyIpAddressExImpl() {
if (IsNetworkSpecified()) {
results_ = link_addresses_;
return true;
}
std::string my_hostname = GetHostName();
if (my_hostname.empty())
return false;
return DnsResolveExImpl(my_hostname);
}
bool DnsResolveImpl(const std::string& host) {
struct addrinfo hints;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_INET;
struct addrinfo* res = nullptr;
int result = IsNetworkSpecified()
? AndroidGetAddrInfoForNetwork(net_handle_, host.c_str(),
nullptr, &hints, &res)
: getaddrinfo(host.c_str(), nullptr, &hints, &res);
if (result != 0) {
return false;
}
net::AddressList address_list = net::AddressList::CreateFromAddrinfo(res);
results_.push_back(address_list.front().address());
freeaddrinfo(res);
return !results_.empty();
}
bool DnsResolveExImpl(const std::string& host) {
struct addrinfo* res = nullptr;
int result = IsNetworkSpecified()
? AndroidGetAddrInfoForNetwork(net_handle_, host.c_str(),
nullptr, nullptr, &res)
: getaddrinfo(host.c_str(), nullptr, nullptr, &res);
if (result != 0) {
return false;
}
net::AddressList address_list = net::AddressList::CreateFromAddrinfo(res);
for (net::IPEndPoint endpoint : address_list.endpoints()) {
results_.push_back(endpoint.address());
}
freeaddrinfo(res);
return !results_.empty();
}
std::string GetHostName() {
char buffer[HOST_NAME_MAX + 1];
if (gethostname(buffer, HOST_NAME_MAX + 1) != 0) {
return std::string();
}
// It's unspecified whether gethostname NULL-terminates if the hostname
// must be truncated and no error is returned if that happens.
buffer[HOST_NAME_MAX] = '\0';
return std::string(buffer);
}
const std::string hostname_;
const net::ProxyResolveDnsOperation operation_;
net_handle_t net_handle_;
std::vector<net::IPAddress> results_;
std::vector<net::IPAddress> link_addresses_;
};
};
class Bindings : public proxy_resolver::ProxyResolverV8Tracing::Bindings {
public:
Bindings(HostResolver* host_resolver) : host_resolver_(host_resolver) {}
void Alert(const base::string16& message) override {}
void OnError(int line_number, const base::string16& message) override {}
proxy_resolver::ProxyHostResolver* GetHostResolver() override {
return host_resolver_;
}
net::NetLogWithSource GetNetLogWithSource() override {
return net::NetLogWithSource();
}
private:
HostResolver* host_resolver_;
};
// Public methods of AwPacProcessor may be called on multiple threads.
// ProxyResolverV8TracingFactory/ProxyResolverV8Tracing
// expects its public interface to always be called on the same thread with
// Chromium task runner so it can post it back to that thread
// with the result of the queries.
//
// Job and its subclasses wrap queries from public methods of AwPacProcessor,
// post them on a special thread and blocks on WaitableEvent
// until the query is finished. |OnSignal| is passed to
// ProxyResolverV8TracingFactory/ProxyResolverV8Tracing methods.
// This callback is called once the request is processed and,
// it signals WaitableEvent and returns result to the calling thread.
//
// ProxyResolverV8TracingFactory/ProxyResolverV8Tracing behaviour is the
// following: if the corresponding request is destroyed,
// the query is cancelled and the callback is never called.
// That means that we need to signal WaitableEvent to unblock calling thread
// when we cancel Job. We keep track of unfinished Jobs in |jobs_|. This field
// is always accessed on the same thread.
//
// All Jobs must be cancelled prior to destruction of |proxy_resolver_| since
// its destructor asserts there are no pending requests.
class Job {
public:
virtual ~Job() = default;
bool ExecSync() {
GetTaskRunner()->PostTask(
FROM_HERE, base::BindOnce(&Job::Exec, base::Unretained(this)));
event_.Wait();
return net_error_ == net::OK;
}
void Exec() {
processor_->jobs_.insert(this);
std::move(task_).Run();
}
virtual void Cancel() = 0;
void OnSignal(int net_error) {
net_error_ = net_error;
// Both SetProxyScriptJob#request_ and MakeProxyRequestJob#request_
// have to be destroyed on the same thread on which they are created.
// If we destroy them before callback is called the request_ is cancelled.
// Reset them here on the correct thread when the job is already finished
// so no cancellation occurs.
Cancel();
}
base::OnceClosure task_;
int net_error_ = net::ERR_ABORTED;
base::WaitableEvent event_;
AwPacProcessor* processor_;
};
class SetProxyScriptJob : public Job {
public:
SetProxyScriptJob(AwPacProcessor* processor, std::string script) {
processor_ = processor;
task_ = base::BindOnce(
&AwPacProcessor::SetProxyScriptNative, base::Unretained(processor_),
&request_, std::move(script),
base::BindOnce(&SetProxyScriptJob::OnSignal, base::Unretained(this)));
}
void Cancel() override {
processor_->jobs_.erase(this);
request_.reset();
event_.Signal();
}
private:
std::unique_ptr<net::ProxyResolverFactory::Request> request_;
};
class MakeProxyRequestJob : public Job {
public:
MakeProxyRequestJob(AwPacProcessor* processor, std::string url) {
processor_ = processor;
task_ = base::BindOnce(
&AwPacProcessor::MakeProxyRequestNative, base::Unretained(processor_),
&request_, std::move(url), &proxy_info_,
base::BindOnce(&MakeProxyRequestJob::OnSignal, base::Unretained(this)));
}
void Cancel() override {
processor_->jobs_.erase(this);
request_.reset();
event_.Signal();
}
net::ProxyInfo proxy_info() { return proxy_info_; }
private:
net::ProxyInfo proxy_info_;
std::unique_ptr<net::ProxyResolver::Request> request_;
};
AwPacProcessor::AwPacProcessor(net_handle_t net_handle)
: net_handle_(net_handle) {
host_resolver_ = std::make_unique<HostResolver>(net_handle_);
}
AwPacProcessor::~AwPacProcessor() {
base::WaitableEvent event;
// |proxy_resolver_| must be destroyed on the same thread it is created.
GetTaskRunner()->PostTask(
FROM_HERE,
base::BindOnce(&AwPacProcessor::Destroy, base::Unretained(this),
base::Unretained(&event)));
event.Wait();
}
void AwPacProcessor::Destroy(base::WaitableEvent* event) {
// Cancel all unfinished jobs to unblock calling thread.
for (auto* job : jobs_) {
job->Cancel();
}
proxy_resolver_.reset();
event->Signal();
}
void AwPacProcessor::DestroyNative(
JNIEnv* env,
const base::android::JavaParamRef<jobject>& obj) {
delete this;
}
void AwPacProcessor::SetProxyScriptNative(
std::unique_ptr<net::ProxyResolverFactory::Request>* request,
const std::string& script,
net::CompletionOnceCallback complete) {
DCHECK(GetTaskRunner()->BelongsToCurrentThread());
GetProxyResolverFactory()->CreateProxyResolverV8Tracing(
net::PacFileData::FromUTF8(script),
std::make_unique<Bindings>(host_resolver_.get()), &proxy_resolver_,
std::move(complete), request);
}
void AwPacProcessor::MakeProxyRequestNative(
std::unique_ptr<net::ProxyResolver::Request>* request,
const std::string& url,
net::ProxyInfo* proxy_info,
net::CompletionOnceCallback complete) {
DCHECK(GetTaskRunner()->BelongsToCurrentThread());
if (proxy_resolver_) {
proxy_resolver_->GetProxyForURL(
GURL(url), net::NetworkIsolationKey(), proxy_info, std::move(complete),
request, std::make_unique<Bindings>(host_resolver_.get()));
} else {
std::move(complete).Run(net::ERR_FAILED);
}
}
bool AwPacProcessor::SetProxyScript(std::string script) {
SetProxyScriptJob job(this, script);
bool success = job.ExecSync();
DCHECK(proxy_resolver_);
return success;
}
jboolean AwPacProcessor::SetProxyScript(JNIEnv* env,
const JavaParamRef<jobject>& obj,
const JavaParamRef<jstring>& jscript) {
std::string script = ConvertJavaStringToUTF8(env, jscript);
return SetProxyScript(script);
}
std::string AwPacProcessor::MakeProxyRequest(std::string url) {
MakeProxyRequestJob job(this, url);
bool success = job.ExecSync();
return success ? job.proxy_info().ToPacString() : nullptr;
}
ScopedJavaLocalRef<jstring> AwPacProcessor::MakeProxyRequest(
JNIEnv* env,
const JavaParamRef<jobject>& obj,
const JavaParamRef<jstring>& jurl) {
std::string url = ConvertJavaStringToUTF8(env, jurl);
return ConvertUTF8ToJavaString(env, MakeProxyRequest(url));
}
// ProxyResolverV8Tracing posts DNS resolution queries back to the thread
// it is called from. Post update of link addresses to the same thread to
// prevent concurrent access and modification of the same vector.
void AwPacProcessor::SetNetworkLinkAddresses(
JNIEnv* env,
const base::android::JavaParamRef<jobjectArray>& jlink_addresses) {
std::vector<std::string> string_link_addresses;
base::android::AppendJavaStringArrayToStringVector(env, jlink_addresses,
&string_link_addresses);
std::vector<net::IPAddress> link_addresses;
for (std::string const& address : string_link_addresses) {
link_addresses.push_back(StringToIPAddress(address));
}
GetTaskRunner()->PostTask(
FROM_HERE, base::BindOnce(&HostResolver::SetNetworkLinkAddresses,
base::Unretained(host_resolver_.get()),
std::move(link_addresses)));
}
static jlong JNI_AwPacProcessor_CreateNativePacProcessor(JNIEnv* env,
jlong net_handle) {
AwPacProcessor* processor = new AwPacProcessor(net_handle);
return reinterpret_cast<intptr_t>(processor);
}
static void JNI_AwPacProcessor_InitializeEnvironment(JNIEnv* env) {
base::ThreadPoolInstance::CreateAndStartWithDefaultParams("AwPacProcessor");
}
} // namespace android_webview
| 33.390438 | 80 | 0.68715 | [
"vector"
] |
92b8ae296eae53e894bf72f160e1a403c7aedd5d | 4,841 | hpp | C++ | include/codegen/include/GlobalNamespace/HealthWarningViewController.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 1 | 2021-11-12T09:29:31.000Z | 2021-11-12T09:29:31.000Z | include/codegen/include/GlobalNamespace/HealthWarningViewController.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | null | null | null | include/codegen/include/GlobalNamespace/HealthWarningViewController.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 2 | 2021-10-03T02:14:20.000Z | 2021-11-12T09:29:36.000Z | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: HMUI.ViewController
#include "HMUI/ViewController.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: UnityEngine::UI
namespace UnityEngine::UI {
// Forward declaring type: Button
class Button;
}
// Forward declaring namespace: UnityEngine
namespace UnityEngine {
// Forward declaring type: GameObject
class GameObject;
}
// Forward declaring namespace: GlobalNamespace
namespace GlobalNamespace {
// Forward declaring type: IAnalyticsModel
class IAnalyticsModel;
// Forward declaring type: AppStaticSettingsSO
class AppStaticSettingsSO;
}
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Action
class Action;
}
// Completed forward declares
// Type namespace:
namespace GlobalNamespace {
// Autogenerated type: HealthWarningViewController
class HealthWarningViewController : public HMUI::ViewController {
public:
// private UnityEngine.UI.Button _continueButton
// Offset: 0x68
UnityEngine::UI::Button* continueButton;
// private UnityEngine.UI.Button _privacyPolicyButton
// Offset: 0x70
UnityEngine::UI::Button* privacyPolicyButton;
// private UnityEngine.UI.Button _openDataPrivacyPageButton
// Offset: 0x78
UnityEngine::UI::Button* openDataPrivacyPageButton;
// private UnityEngine.GameObject _privacyAgreeToPrivacyPolicyLabel
// Offset: 0x80
UnityEngine::GameObject* privacyAgreeToPrivacyPolicyLabel;
// private IAnalyticsModel _analyticsModel
// Offset: 0x88
GlobalNamespace::IAnalyticsModel* analyticsModel;
// private AppStaticSettingsSO _appStaticSettings
// Offset: 0x90
GlobalNamespace::AppStaticSettingsSO* appStaticSettings;
// private System.Action privacyPolicyButtonPressedEvent
// Offset: 0x98
System::Action* privacyPolicyButtonPressedEvent;
// private System.Action openDataPrivacyPageButtonPressedEvent
// Offset: 0xA0
System::Action* openDataPrivacyPageButtonPressedEvent;
// private System.Action didFinishEvent
// Offset: 0xA8
System::Action* didFinishEvent;
// public System.Void add_privacyPolicyButtonPressedEvent(System.Action value)
// Offset: 0xB43CD4
void add_privacyPolicyButtonPressedEvent(System::Action* value);
// public System.Void remove_privacyPolicyButtonPressedEvent(System.Action value)
// Offset: 0xB44064
void remove_privacyPolicyButtonPressedEvent(System::Action* value);
// public System.Void add_openDataPrivacyPageButtonPressedEvent(System.Action value)
// Offset: 0xB43D78
void add_openDataPrivacyPageButtonPressedEvent(System::Action* value);
// public System.Void remove_openDataPrivacyPageButtonPressedEvent(System.Action value)
// Offset: 0xB44108
void remove_openDataPrivacyPageButtonPressedEvent(System::Action* value);
// public System.Void add_didFinishEvent(System.Action value)
// Offset: 0xB43C30
void add_didFinishEvent(System::Action* value);
// public System.Void remove_didFinishEvent(System.Action value)
// Offset: 0xB43FC0
void remove_didFinishEvent(System::Action* value);
// private System.Void <DidActivate>b__15_0()
// Offset: 0xB44C38
void $DidActivate$b__15_0();
// private System.Void <DidActivate>b__15_1()
// Offset: 0xB44C4C
void $DidActivate$b__15_1();
// private System.Void <DidActivate>b__15_2()
// Offset: 0xB44C60
void $DidActivate$b__15_2();
// protected override System.Void DidActivate(System.Boolean firstActivation, HMUI.ViewController/ActivationType activationType)
// Offset: 0xB44998
// Implemented from: HMUI.ViewController
// Base method: System.Void ViewController::DidActivate(System.Boolean firstActivation, HMUI.ViewController/ActivationType activationType)
void DidActivate(bool firstActivation, HMUI::ViewController::ActivationType activationType);
// public System.Void .ctor()
// Offset: 0xB44C30
// Implemented from: HMUI.ViewController
// Base method: System.Void ViewController::.ctor()
// Base method: System.Void MonoBehaviour::.ctor()
// Base method: System.Void Behaviour::.ctor()
// Base method: System.Void Component::.ctor()
// Base method: System.Void Object::.ctor()
// Base method: System.Void Object::.ctor()
static HealthWarningViewController* New_ctor();
}; // HealthWarningViewController
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::HealthWarningViewController*, "", "HealthWarningViewController");
#pragma pack(pop)
| 42.464912 | 142 | 0.746953 | [
"object"
] |
92ba5346ba2ae36e504b7826fbb8ce7bb2f50439 | 909 | cpp | C++ | Algorithms/1146.Snapshot_Array.cpp | metehkaya/LeetCode | 52f4a1497758c6f996d515ced151e8783ae4d4d2 | [
"MIT"
] | 2 | 2020-07-20T06:40:22.000Z | 2021-11-20T01:23:26.000Z | Problems/LeetCode/Problems/1146.Snapshot_Array.cpp | metehkaya/Algo-Archive | 03b5fdcf06f84a03125c57762c36a4e03ca6e756 | [
"MIT"
] | null | null | null | Problems/LeetCode/Problems/1146.Snapshot_Array.cpp | metehkaya/Algo-Archive | 03b5fdcf06f84a03125c57762c36a4e03ca6e756 | [
"MIT"
] | null | null | null | class SnapshotArray {
public:
int n;
int nSnap;
vector<vector<pair<int,int>>>v;
SnapshotArray(int length) {
nSnap=0;
v.clear();
v.resize(n=length);
for( int i = 0 ; i < n ; i++ )
v[i].push_back(make_pair(0,0));
}
void set(int index, int val) {
int sz = v[index].size();
if(v[index][sz-1].second == nSnap)
v[index][sz-1].first = val;
else
v[index].push_back(make_pair(val,nSnap));
}
int snap() {
nSnap++;
return nSnap-1;
}
int get(int index, int snap_id) {
int sz = v[index].size();
int l=0,r=sz-1,last=sz-1;
while(l <= r) {
int mid = (l+r) >> 1;
if(v[index][mid].second <= snap_id)
last=mid,l=mid+1;
else
r=mid-1;
}
return v[index][last].first;
}
}; | 25.25 | 53 | 0.453245 | [
"vector"
] |
92bb09b987d90a7ab043ec520433fd45b921c810 | 3,953 | cc | C++ | mcg/src/external/BSR/src/concurrent/threads/synchronization/synchronizables/synchronizable.cc | mouthwater/rgb | 3fafca24ecc133910923182581a2133b8568bf77 | [
"BSD-2-Clause"
] | 392 | 2015-01-14T13:19:40.000Z | 2022-02-12T08:47:33.000Z | mcg/src/external/BSR/src/concurrent/threads/synchronization/synchronizables/synchronizable.cc | mouthwater/rgb | 3fafca24ecc133910923182581a2133b8568bf77 | [
"BSD-2-Clause"
] | 45 | 2015-02-03T12:16:10.000Z | 2022-03-07T00:25:09.000Z | mcg/src/external/BSR/src/concurrent/threads/synchronization/synchronizables/synchronizable.cc | mouthwater/rgb | 3fafca24ecc133910923182581a2133b8568bf77 | [
"BSD-2-Clause"
] | 168 | 2015-01-05T02:29:53.000Z | 2022-02-22T04:32:04.000Z | /*
* Synchronizable interface.
*/
#include "concurrent/threads/synchronization/mutex.hh"
#include "concurrent/threads/synchronization/synchronizables/synchronizable.hh"
namespace concurrent {
namespace threads {
namespace synchronization {
namespace synchronizables {
/*
* Imports.
*/
using concurrent::threads::synchronization::mutex;
/*
* Issue the next available identity for a synchronizable object.
* The zero id is reserved for unsynchronized objects.
*/
unsigned long synchronizable::id_next() {
static unsigned long id = 1;
static mutex id_mutex;
id_mutex.lock();
if (id == 0) { id = 1; }
unsigned long issue_id = id;
id++;
id_mutex.unlock();
return issue_id;
}
/*
* Constructor.
* Initialize the identity of the synchronizable object.
*/
synchronizable::synchronizable()
: _id(synchronizable::id_next())
{ }
/*
* Constructor.
* Initialize the synchronizable object to have the given id.
*/
synchronizable::synchronizable(unsigned long id)
: _id(id)
{ }
/*
* Destructor.
*/
synchronizable::~synchronizable() {
/* do nothing */
}
/*
* Claim exclusive access to two synchronizable objects.
*/
void synchronizable::lock(
const synchronizable& s0,
const synchronizable& s1)
{
if (s0.syn_id() < s1.syn_id()) {
s0.abstract_lock();
s1.abstract_lock();
} else if (s0.syn_id() > s1.syn_id()) {
s1.abstract_lock();
s0.abstract_lock();
} else {
s0.abstract_lock();
}
}
/*
* Release exclusive access to two synchronizable objects.
*/
void synchronizable::unlock(
const synchronizable& s0,
const synchronizable& s1)
{
s0.abstract_unlock();
if (s0.syn_id() != s1.syn_id())
s1.abstract_unlock();
}
/*
* Claim read access to two synchronizable objects.
*/
void synchronizable::read_lock(
const synchronizable& s0,
const synchronizable& s1)
{
if (s0.syn_id() < s1.syn_id()) {
s0.abstract_read_lock();
s1.abstract_read_lock();
} else if (s0.syn_id() > s1.syn_id()) {
s1.abstract_read_lock();
s0.abstract_read_lock();
} else {
s0.abstract_read_lock();
}
}
/*
* Release read access to two synchronizable objects.
*/
void synchronizable::read_unlock(
const synchronizable& s0,
const synchronizable& s1)
{
s0.abstract_read_unlock();
if (s0.syn_id() != s1.syn_id())
s1.abstract_read_unlock();
}
/*
* Claim write access to two synchronizable objects.
*/
void synchronizable::write_lock(
const synchronizable& s0,
const synchronizable& s1)
{
if (s0.syn_id() < s1.syn_id()) {
s0.abstract_write_lock();
s1.abstract_write_lock();
} else if (s0.syn_id() > s1.syn_id()) {
s1.abstract_write_lock();
s0.abstract_write_lock();
} else {
s0.abstract_write_lock();
}
}
/*
* Release write access to two synchronizable objects.
*/
void synchronizable::write_unlock(
const synchronizable& s0,
const synchronizable& s1)
{
s0.abstract_write_unlock();
if (s0.syn_id() != s1.syn_id())
s1.abstract_write_unlock();
}
/*
* Claim read access to the first object and write access to the second.
*/
void synchronizable::read_write_lock(
const synchronizable& s0,
const synchronizable& s1)
{
if (s0.syn_id() < s1.syn_id()) {
s0.abstract_read_lock();
s1.abstract_write_lock();
} else if (s0.syn_id() > s1.syn_id()) {
s1.abstract_write_lock();
s0.abstract_read_lock();
} else {
s0.abstract_write_lock();
}
}
/*
* Release read access to the first object and write access to the second.
*/
void synchronizable::read_write_unlock(
const synchronizable& s0,
const synchronizable& s1)
{
if (s0.syn_id() != s1.syn_id()) {
s0.abstract_read_unlock();
s1.abstract_write_unlock();
} else {
s0.abstract_write_unlock();
}
}
} /* namespace synchronizables */
} /* namespace synchronization */
} /* namespace threads */
} /* namespace concurrent */
| 21.71978 | 79 | 0.664559 | [
"object"
] |
92c251f1b5d759d9b6f1b4b5540aac5a17bfa047 | 902 | cpp | C++ | stl/priority-queue.cpp | Gmaurya/data-structure-and-algorithms | 9f9790140719d24d15ee401e0d11a99dedde4235 | [
"MIT"
] | 3 | 2017-12-27T04:58:16.000Z | 2018-02-05T14:11:06.000Z | stl/priority-queue.cpp | Gmaurya/data-structure-and-algorithms | 9f9790140719d24d15ee401e0d11a99dedde4235 | [
"MIT"
] | 4 | 2018-10-04T07:45:07.000Z | 2018-11-23T17:36:20.000Z | stl/priority-queue.cpp | Gmaurya/data-structure-and-algorithms | 9f9790140719d24d15ee401e0d11a99dedde4235 | [
"MIT"
] | 8 | 2018-10-02T20:34:58.000Z | 2018-10-07T14:27:53.000Z |
#include <iostream>
#include <queue>
using namespace std;
void showpq(priority_queue <pair<int,int>,vector< pair<int,int> > , greater<pair<int,int> > > gq)
{
priority_queue <pair<int,int >,vector< pair<int,int> > , greater<pair<int,int> > > g = gq;
while (!g.empty())
{
cout << '\t' << g.top().first<<" "<<g.top().second;
g.pop();
}
cout << '\n';
}
int main ()
{
priority_queue <pair<int,int>,vector< pair<int,int> > , greater<pair<int,int> > > gquiz;
gquiz.push({10,10});
gquiz.push({10,15});
gquiz.push({20,30});
gquiz.push({5,5});
gquiz.push({1,2});
cout << "The priority queue gquiz is : ";
showpq(gquiz);
cout << "\ngquiz.size() : " << gquiz.size();
cout << "\ngquiz.top() : " << gquiz.top().first<<" "<<gquiz.top().second;
cout << "\ngquiz.pop() : ";
gquiz.pop();
showpq(gquiz);
return 0;
} | 24.378378 | 97 | 0.539911 | [
"vector"
] |
92c33a286abe009083a23f950782b9888d1c6bd5 | 14,108 | cc | C++ | chromeos/memory/pressure/pressure.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 575 | 2015-06-18T23:58:20.000Z | 2022-03-23T09:32:39.000Z | chromeos/memory/pressure/pressure.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | chromeos/memory/pressure/pressure.cc | iridium-browser/iridium-browser | 907e31cf5ce5ad14d832796e3a7c11e496828959 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 52 | 2015-07-14T10:40:50.000Z | 2022-03-15T01:11:49.000Z | // Copyright 2020 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 "chromeos/memory/pressure/pressure.h"
#include "base/files/file_util.h"
#include "base/logging.h"
#include "base/memory/singleton.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/system/sys_info.h"
namespace chromeos {
namespace memory {
namespace pressure {
namespace {
const base::Feature kCrOSLowMemoryNotificationPSI{
"CrOSLowMemoryNotificationPSI", base::FEATURE_DISABLED_BY_DEFAULT};
const base::FeatureParam<int> kCrOSLowMemoryPSIThreshold{
&kCrOSLowMemoryNotificationPSI, "CrOSLowMemoryPSIThreshold", 20};
// The reserved file cache.
constexpr char kMinFilelist[] = "/proc/sys/vm/min_filelist_kbytes";
// The estimation of how well zram based swap is compressed.
constexpr char kRamVsSwapWeight[] =
"/sys/kernel/mm/chromeos-low_mem/ram_vs_swap_weight";
// The default value if the ram_vs_swap_weight file is not available.
constexpr uint64_t kRamVsSwapWeightDefault = 4;
// The extra free to trigger kernel memory reclaim earlier.
constexpr char kExtraFree[] = "/proc/sys/vm/extra_free_kbytes";
// The margin mem file contains the two memory levels, the first is the
// critical level and the second is the moderate level. Note, this
// file may contain more values but only the first two are used for
// memory pressure notifications in chromeos.
constexpr char kMarginMemFile[] = "/sys/kernel/mm/chromeos-low_mem/margin";
// Values saved for user space available memory calculation. The value of
// |reserved_free| should not change unless min_free_kbytes or
// lowmem_reserve_ratio change. The value of |min_filelist| and
// |ram_swap_weight| should not change unless the user sets them manually.
uint64_t reserved_free = 0;
uint64_t min_filelist = 0;
uint64_t ram_swap_weight = 0;
uint64_t ReadFileToUint64(const base::FilePath& file) {
std::string file_contents;
if (!base::ReadFileToStringNonBlocking(file, &file_contents)) {
PLOG_IF(ERROR, base::SysInfo::IsRunningOnChromeOS())
<< "Unable to read uint64 from: " << file;
return 0;
}
TrimWhitespaceASCII(file_contents, base::TRIM_ALL, &file_contents);
uint64_t file_contents_uint64 = 0;
if (!base::StringToUint64(file_contents, &file_contents_uint64))
return 0;
return file_contents_uint64;
}
uint64_t GetReservedMemoryKB() {
std::string file_contents;
if (!base::ReadFileToStringNonBlocking(base::FilePath("/proc/zoneinfo"),
&file_contents)) {
PLOG(ERROR) << "Couldn't get /proc/zoneinfo";
return 0;
}
// Reserve free pages is high watermark + lowmem_reserve and extra_free_kbytes
// raises the high watermark. Nullify the effect of extra_free_kbytes by
// excluding it from the reserved pages. The default extra_free_kbytes value
// is 0 if the file couldn't be accessed.
return CalculateReservedFreeKB(file_contents) -
ReadFileToUint64(base::FilePath(kExtraFree));
}
bool SupportsPSI() {
// Checking path existence in procfs is fast.
static bool supports_psi = access("/proc/pressure/", F_OK) == 0;
return supports_psi;
}
// Returns the percentage of the recent 10 seconds that some process is blocked
// by memory.
double GetPSIMemoryPressure10Seconds() {
base::FilePath psi_memory("/proc/pressure/memory");
std::string contents;
if (!base::ReadFileToStringNonBlocking(base::FilePath(psi_memory),
&contents)) {
PLOG(ERROR) << "Unable to read file: " << psi_memory;
return 0;
}
return ParsePSIMemory(contents);
}
} // namespace
// CalculateReservedFreeKB() calculates the reserved free memory in KiB from
// /proc/zoneinfo. Reserved pages are free pages reserved for emergent kernel
// allocation and are not available to the user space. It's the sum of high
// watermarks and max protection pages of memory zones. It implements the same
// reserved pages calculation in linux kernel calculate_totalreserve_pages().
//
// /proc/zoneinfo example:
// ...
// Node 0, zone DMA32
// pages free 422432
// min 16270
// low 20337
// high 24404
// ...
// protection: (0, 0, 1953, 1953)
//
// The high field is the high watermark for this zone. The protection field is
// the protected pages for lower zones. See the lowmem_reserve_ratio section in
// https://www.kernel.org/doc/Documentation/sysctl/vm.txt.
uint64_t CalculateReservedFreeKB(const std::string& zoneinfo) {
constexpr uint64_t kPageSizeKB = 4;
uint64_t num_reserved_pages = 0;
for (const base::StringPiece& line : base::SplitStringPiece(
zoneinfo, "\n", base::KEEP_WHITESPACE, base::SPLIT_WANT_NONEMPTY)) {
std::vector<base::StringPiece> tokens = base::SplitStringPiece(
line, base::kWhitespaceASCII, base::TRIM_WHITESPACE,
base::SPLIT_WANT_NONEMPTY);
// Skip the line if there are not enough tokens.
if (tokens.size() < 2) {
continue;
}
if (tokens[0] == "high") {
// Parse the high watermark.
uint64_t high = 0;
if (base::StringToUint64(tokens[1], &high)) {
num_reserved_pages += high;
} else {
LOG(ERROR) << "Couldn't parse the high field in /proc/zoneinfo: "
<< tokens[1];
}
} else if (tokens[0] == "protection:") {
// Parse the protection pages.
uint64_t max = 0;
for (size_t i = 1; i < tokens.size(); ++i) {
uint64_t num = 0;
base::StringPiece entry;
if (i == 1) {
// Exclude the leading '(' and the trailing ','.
entry = tokens[i].substr(1, tokens[i].size() - 2);
} else {
// Exclude the trailing ',' or ')'.
entry = tokens[i].substr(0, tokens[i].size() - 1);
}
if (base::StringToUint64(entry, &num)) {
max = std::max(max, num);
} else {
LOG(ERROR)
<< "Couldn't parse the protection field in /proc/zoneinfo: "
<< entry;
}
}
num_reserved_pages += max;
}
}
return num_reserved_pages * kPageSizeKB;
}
// Returns the percentage of the recent 10 seconds that some process is blocked
// by memory.
// Example input:
// some avg10=0.00 avg60=0.00 avg300=0.00 total=0
// full avg10=0.00 avg60=0.00 avg300=0.00 total=0
double ParsePSIMemory(const std::string& contents) {
for (const base::StringPiece& line : base::SplitStringPiece(
contents, "\n", base::KEEP_WHITESPACE, base::SPLIT_WANT_NONEMPTY)) {
std::vector<base::StringPiece> tokens = base::SplitStringPiece(
line, base::kWhitespaceASCII, base::TRIM_WHITESPACE,
base::SPLIT_WANT_NONEMPTY);
if (tokens[0] == "some") {
base::StringPairs kv_pairs;
if (base::SplitStringIntoKeyValuePairs(line.substr(5), '=', ' ',
&kv_pairs)) {
double some_10seconds;
if (base::StringToDouble(kv_pairs[0].second, &some_10seconds)) {
return some_10seconds;
} else {
LOG(ERROR) << "Couldn't parse the value of the first pair";
}
} else {
LOG(ERROR)
<< "Couldn't split the key-value pairs in /proc/pressure/memory";
}
}
}
LOG(ERROR) << "Couldn't parse /proc/pressure/memory: " << contents;
DCHECK(false);
return 0;
}
// CalculateAvailableMemoryUserSpaceKB implements similar available memory
// calculation as kernel function get_available_mem_adj(). The available memory
// consists of 3 parts: the free memory, the file cache, and the swappable
// memory. The available free memory is free memory minus reserved free memory.
// The available file cache is the total file cache minus reserved file cache
// (min_filelist). Because swapping is prohibited if there is no anonymous
// memory or no swap free, the swappable memory is the minimal of anonymous
// memory and swap free. As swapping memory is more costly than dropping file
// cache, only a fraction (1 / ram_swap_weight) of the swappable memory
// contributes to the available memory.
uint64_t CalculateAvailableMemoryUserSpaceKB(
const base::SystemMemoryInfoKB& info,
uint64_t reserved_free,
uint64_t min_filelist,
uint64_t ram_swap_weight) {
const uint64_t free = info.free;
const uint64_t anon = info.active_anon + info.inactive_anon;
const uint64_t file = info.active_file + info.inactive_file;
const uint64_t dirty = info.dirty;
const uint64_t free_component =
(free > reserved_free) ? free - reserved_free : 0;
const uint64_t cache_component =
(file > dirty + min_filelist) ? file - dirty - min_filelist : 0;
const uint64_t swappable = std::min<uint64_t>(anon, info.swap_free);
const uint64_t swap_component = swappable / ram_swap_weight;
return free_component + cache_component + swap_component;
}
uint64_t GetAvailableMemoryKB() {
base::SystemMemoryInfoKB info;
uint64_t available_kb;
if (base::GetSystemMemoryInfo(&info)) {
available_kb = CalculateAvailableMemoryUserSpaceKB(
info, reserved_free, min_filelist, ram_swap_weight);
} else {
PLOG(ERROR)
<< "Assume low memory pressure if opening/parsing meminfo failed";
LOG_IF(FATAL, base::SysInfo::IsRunningOnChromeOS())
<< "procfs isn't mounted or unable to open /proc/meminfo";
available_kb = 4 * 1024;
}
static bool using_psi = SupportsPSI() && base::FeatureList::IsEnabled(
kCrOSLowMemoryNotificationPSI);
if (using_psi) {
auto margins = GetMemoryMarginsKB();
const uint64_t critical_margin = margins.first;
const uint64_t moderate_margin = margins.second;
static double psi_threshold = kCrOSLowMemoryPSIThreshold.Get();
// When PSI memory pressure is high, trigger moderate memory pressure.
if (GetPSIMemoryPressure10Seconds() > psi_threshold) {
available_kb =
std::min(available_kb, (moderate_margin + critical_margin) / 2);
}
}
return available_kb;
}
std::vector<uint64_t> GetMarginFileParts(const std::string& file) {
std::vector<uint64_t> margin_values;
std::string margin_contents;
if (base::ReadFileToStringNonBlocking(base::FilePath(file),
&margin_contents)) {
std::vector<std::string> margins =
base::SplitString(margin_contents, base::kWhitespaceASCII,
base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
for (const auto& v : margins) {
uint64_t value = 0;
if (!base::StringToUint64(v, &value)) {
// If any of the values weren't parseable as an uint64_T we return
// nothing as the file format is unexpected.
LOG(ERROR) << "Unable to parse margin file contents as integer: " << v;
return std::vector<uint64_t>();
}
margin_values.push_back(value);
}
} else {
PLOG_IF(ERROR, base::SysInfo::IsRunningOnChromeOS())
<< "Unable to read margin file";
}
return margin_values;
}
namespace {
// This function would return valid margins even when there are less than 2
// margin values in the kernel margin file.
std::pair<uint64_t, uint64_t> GetMemoryMarginsKBImpl() {
const std::vector<uint64_t> margin_file_parts(
GetMarginFileParts(kMarginMemFile));
if (margin_file_parts.size() >= 2) {
return {margin_file_parts[0] * 1024, margin_file_parts[1] * 1024};
}
// Critical margin is 5.2% of total memory, moderate margin is 40% of total
// memory. See also /usr/share/cros/init/swap.sh on DUT.
base::SystemMemoryInfoKB info;
int total_memory_kb = 2 * 1024;
if (base::GetSystemMemoryInfo(&info)) {
total_memory_kb = info.total;
} else {
PLOG(ERROR)
<< "Assume 2 GiB total memory if opening/parsing meminfo failed";
LOG_IF(FATAL, base::SysInfo::IsRunningOnChromeOS())
<< "procfs isn't mounted or unable to open /proc/meminfo";
}
return {total_memory_kb * 13 / 250, total_memory_kb * 2 / 5};
}
} // namespace
std::pair<uint64_t, uint64_t> GetMemoryMarginsKB() {
static std::pair<uint64_t, uint64_t> result(GetMemoryMarginsKBImpl());
return result;
}
void UpdateMemoryParameters() {
reserved_free = GetReservedMemoryKB();
min_filelist = ReadFileToUint64(base::FilePath(kMinFilelist));
ram_swap_weight = ReadFileToUint64(base::FilePath(kRamVsSwapWeight));
if (ram_swap_weight == 0)
ram_swap_weight = kRamVsSwapWeightDefault;
}
PressureChecker::PressureChecker() : weak_ptr_factory_(this) {}
PressureChecker::~PressureChecker() = default;
PressureChecker* PressureChecker::GetInstance() {
return base::Singleton<PressureChecker>::get();
}
void PressureChecker::SetCheckingDelay(base::TimeDelta delay) {
if (checking_timer_.GetCurrentDelay() == delay)
return;
if (delay.is_zero()) {
checking_timer_.Stop();
} else {
checking_timer_.Start(FROM_HERE, delay,
base::BindRepeating(&PressureChecker::CheckPressure,
weak_ptr_factory_.GetWeakPtr()));
}
}
void PressureChecker::AddObserver(PressureObserver* observer) {
pressure_observers_.AddObserver(observer);
}
void PressureChecker::RemoveObserver(PressureObserver* observer) {
pressure_observers_.RemoveObserver(observer);
}
void PressureChecker::CheckPressure() {
std::pair<uint64_t, uint64_t> margins_kb =
chromeos::memory::pressure::GetMemoryMarginsKB();
uint64_t critical_margin_kb = margins_kb.first;
uint64_t moderate_margin_kb = margins_kb.second;
uint64_t available_kb = GetAvailableMemoryKB();
if (available_kb < critical_margin_kb) {
for (auto& observer : pressure_observers_) {
observer.OnCriticalPressure();
}
} else if (available_kb < moderate_margin_kb) {
for (auto& observer : pressure_observers_) {
observer.OnModeratePressure();
}
}
}
} // namespace pressure
} // namespace memory
} // namespace chromeos
| 36.931937 | 80 | 0.688191 | [
"vector"
] |
92c422e0d261694bbcd38fe97b0d518472146c53 | 240 | cpp | C++ | lib/vdf/DataMgrMOM.cpp | yyr/vapor | cdebac81212ffa3f811064bbd7625ffa9089782e | [
"BSD-3-Clause"
] | null | null | null | lib/vdf/DataMgrMOM.cpp | yyr/vapor | cdebac81212ffa3f811064bbd7625ffa9089782e | [
"BSD-3-Clause"
] | null | null | null | lib/vdf/DataMgrMOM.cpp | yyr/vapor | cdebac81212ffa3f811064bbd7625ffa9089782e | [
"BSD-3-Clause"
] | null | null | null | #include <limits>
#include <cassert>
#include <vapor/DataMgrMOM.h>
using namespace VetsUtil;
using namespace VAPoR;
DataMgrMOM::DataMgrMOM(
const vector <string> &files,
size_t mem_size
) : DataMgr(mem_size), DCReaderMOM(files)
{
}
| 17.142857 | 42 | 0.741667 | [
"vector"
] |
2bb097af5c1bc3ccd3d675dc0e55da53c47df0f2 | 999 | cpp | C++ | STL/algorithm/move.cpp | liangjisheng/C-Cpp | 8b33ba1f43580a7bdded8bb4ce3d92983ccedb81 | [
"MIT"
] | 5 | 2019-09-17T09:12:15.000Z | 2021-05-29T10:54:39.000Z | STL/algorithm/move.cpp | liangjisheng/C-Cpp | 8b33ba1f43580a7bdded8bb4ce3d92983ccedb81 | [
"MIT"
] | null | null | null | STL/algorithm/move.cpp | liangjisheng/C-Cpp | 8b33ba1f43580a7bdded8bb4ce3d92983ccedb81 | [
"MIT"
] | 2 | 2021-07-26T06:36:12.000Z | 2022-01-23T15:20:30.000Z | #include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
class myClass
{
public:
myClass();
myClass(const myClass& src);
myClass(const string& src) : mStr(src) {}
// Move assignment operator
myClass& operator=(myClass&& rhs) noexcept{
if(this == &rhs)
return *this;
mStr = move(rhs.mStr);
cout << "Move operator= (mStr=" << mStr << ")" << endl;
return *this;
}
string getString() const { return mStr; }
private:
string mStr;
};
myClass::myClass() : mStr("") {}
myClass::myClass(const myClass& src) : mStr(src.mStr) {}
int main()
{
vector<myClass> vecSrc{ myClass("a"), myClass("b"), myClass("c")};
vector<myClass> vecDst(vecSrc.size());
move(vecSrc.begin(), vecSrc.end(), vecDst.begin());
// move_backward()使用了和move同样的移动机制,但是按照从
// 最后一个元素想第一个元素的顺序移动
for(const auto& c : vecDst)
cout << c.getString() << " ";
cout << endl;
return 0;
}
| 21.717391 | 70 | 0.593594 | [
"vector"
] |
2bb37f3b68790c93078576377851c730fc52c613 | 2,803 | cpp | C++ | src/process.cpp | edghyhdz/CppND-System-Monitor-Project-my_solution | 4f1f0eae3c868c469d6a2e5b5f7c77090686b466 | [
"MIT"
] | 1 | 2020-12-25T18:43:10.000Z | 2020-12-25T18:43:10.000Z | src/process.cpp | edghyhdz/CppND-System-Monitor-Project-my_solution | 4f1f0eae3c868c469d6a2e5b5f7c77090686b466 | [
"MIT"
] | null | null | null | src/process.cpp | edghyhdz/CppND-System-Monitor-Project-my_solution | 4f1f0eae3c868c469d6a2e5b5f7c77090686b466 | [
"MIT"
] | 1 | 2021-03-24T23:53:46.000Z | 2021-03-24T23:53:46.000Z | #include <unistd.h>
#include <cctype>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <cassert>
#include "linux_parser.h"
#include "process.h"
using std::string;
using std::to_string;
using std::vector;
// Class constructor
Process::Process(int pid) : pid_(pid) {}
// DONE: Return this process's ID
int Process::Pid() { return this->pid_; }
// Set function -> sets past_utilization vector for current process
void Process::setPastUtilization(vector<float> current_utilization) {
this->past_utilization_ = current_utilization;
}
// Mutator function, gets past_utilization
std::vector<float> const Process::getPastUtilization() {
return this->past_utilization_;
}
// DONE: Return this process's CPU utilization
float Process::CpuUtilization() {
vector<string> cpu_data = LinuxParser::CpuUtilization(this->Pid());
vector<float> current_cpu_utilization;
if (cpu_data.empty()){
return 0;
}
// Based on Vihelm Gray's answer from stackoverflow
// https://stackoverflow.com/a/16736599/13743493
float up_time = (float)LinuxParser::UpTime();
// Make a float vector out of the parsed linux data
for (string& k : cpu_data) {
current_cpu_utilization.push_back(stof(k));
}
// Calculate total time -> utime + stime + cutime + cstime
float total_time = current_cpu_utilization[0] + current_cpu_utilization[1];
total_time = total_time + current_cpu_utilization[2] + current_cpu_utilization[3];
// Get total elapsed time
// This is also the total time that process has been running
this->total_elapsed_time_ =
up_time - current_cpu_utilization[4] / sysconf(_SC_CLK_TCK);
// float seconds = up_time - total_elapsed_time_;
// CPU Usage
this->cpu_utilization_ = (total_time/sysconf(_SC_CLK_TCK))/this ->total_elapsed_time_;
return cpu_utilization_;
}
// DONE: Return the command that generated this process
string Process::Command() { return LinuxParser::Command(this->pid_); }
// DONE: Return this process's memory utilization
string Process::Ram() {
return to_string(stoi(LinuxParser::Ram(this->pid_)) / 1024); }
// DONE: Return the user (name) that generated this process
string Process::User() {
string user = LinuxParser::User(this->pid_);
return user;
}
// DONE: Return the age of this process (in seconds)
long int Process::UpTime() { return this->total_elapsed_time_; }
// DONE: Overload the "less than" comparison operator for Process objects
// REMOVE: [[maybe_unused]] once you define the function
bool Process::operator<(Process const& a) const {
return this->cpu_utilization_ < a.cpu_utilization_ ? true : false;
}
// Overloaded the "equal to" comparison operator for Process objects
bool Process::operator==(Process const& a) const {
return this->pid_ == a.pid_ ? true : false;
} | 30.467391 | 88 | 0.731716 | [
"vector"
] |
2bb3aba228398059085007601393c4699c19126d | 2,170 | cpp | C++ | Test/MMO/StressTestClient/ScenarioStressTestClient.cpp | RamilGauss/MMO-Framework | c7c97b019adad940db86d6533861deceafb2ba04 | [
"MIT"
] | 27 | 2015-01-08T08:26:29.000Z | 2019-02-10T03:18:05.000Z | Test/MMO/StressTestClient/ScenarioStressTestClient.cpp | RamilGauss/MMO-Framework | c7c97b019adad940db86d6533861deceafb2ba04 | [
"MIT"
] | 1 | 2017-04-05T02:02:14.000Z | 2017-04-05T02:02:14.000Z | Test/MMO/StressTestClient/ScenarioStressTestClient.cpp | RamilGauss/MMO-Framework | c7c97b019adad940db86d6533861deceafb2ba04 | [
"MIT"
] | 17 | 2015-01-18T02:50:01.000Z | 2019-02-08T21:00:53.000Z | /*
Author: Gudakov Ramil Sergeevich a.k.a. Gauss
Гудаков Рамиль Сергеевич
Contacts: [ramil2085@mail.ru, ramil2085@gmail.com]
See for more information LICENSE.md.
*/
#include <boost/asio/ip/impl/address_v4.ipp>
#include <boost/smart_ptr/scoped_array.hpp>
#include <vector>
#include <string.h>
#include "BL_Debug.h"
#include "Client.h"
#include "CommonParam.h"
#include "InputCmdTestMMO_Client.h"
#include "HiTimer.h"
#include "ResolverSelf_IP_v4.h"
#include "Logger.h"
#include "HandlerMMO_Client.h"
#include "MakerXML.h"
#include "IXML.h"
#include "ScenarioStressTestClient.h"
void TScenarioStressTestClient::Init( int argc, char** argv )
{
GetLogger()->Register( STR_NAME_MMO_ENGINE );
GetLogger()->Register( STR_NAME_NET_TRANSPORT );
GetLogger()->Init( "StressTestClient" );
GetLogger()->SetPrintf( false );
GetLogger()->SetEnable( false );
bool res = mInputCmd.SetArg( argc, argv );
BL_ASSERT( res );
mInputCmd.Get( mInputArg );
for( int i = 0; i < mInputArg.count; i++, mInputArg.begin_port++, mInputArg.begin_id++ )
{
TBehaviourClient* pClient = new TBehaviourClient;
pClient->Init( &mMakerTransport, mInputArg );
pArrClient.push_back( pClient );
}
unsigned int time_next_state = ht_GetMSCount() + eWaitForConnect;
for( auto pClient : pArrClient )
{
pClient->SetTimeNextStep( time_next_state );
time_next_state += 100;
}
}
//-----------------------------------------------------------------------
void TScenarioStressTestClient::Work()
{
while( true )
{
unsigned int startTime = ht_GetMSCount();
// Work
for( TBehaviourClient* pClient : pArrClient )
pClient->Work();
// burn rest time
unsigned int deltaTime = ht_GetMSCount() - startTime;
static int old_delta_time = -1;
if( (old_delta_time != deltaTime) &&
(deltaTime > 70) )
{
printf( "dTime=%d\n", deltaTime );
old_delta_time = deltaTime;
}
if( deltaTime < CLIENT_QUANT_TIME )
ht_msleep( CLIENT_QUANT_TIME - deltaTime );
}
}
//-----------------------------------------------------------------------
| 27.820513 | 91 | 0.62212 | [
"vector"
] |
2bb6ce35de6a4ee6bcf0165ea986702ec0cf91a1 | 27,082 | cpp | C++ | samples/src/lgogdownloader/api.cpp | Rosme/sift | f8d05d19562b4da13271d5c26658d7e8c47866ae | [
"MIT"
] | 4 | 2018-06-15T12:54:10.000Z | 2020-09-22T16:01:35.000Z | samples/src/lgogdownloader/api.cpp | Rosme/sift | f8d05d19562b4da13271d5c26658d7e8c47866ae | [
"MIT"
] | null | null | null | samples/src/lgogdownloader/api.cpp | Rosme/sift | f8d05d19562b4da13271d5c26658d7e8c47866ae | [
"MIT"
] | null | null | null | /* This program is free software. It comes without any warranty, to
* the extent permitted by applicable law. You can redistribute it
* and/or modify it under the terms of the Do What The Fuck You Want
* To Public License, Version 2, as published by Sam Hocevar. See
* http://www.wtfpl.net/ for more details. */
#include "api.h"
#include "gamefile.h"
#include <cstdio>
#include <cstdlib>
#include <sstream>
#include <json/json.h>
#include <unistd.h>
#if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) >= 40900
# define _regex_namespace_ std
# include <regex>
#else
# define _regex_namespace_ boost
# include <boost/regex.hpp>
#endif
size_t writeMemoryCallback(char *ptr, size_t size, size_t nmemb, void *userp) {
std::ostringstream *stream = (std::ostringstream*)userp;
std::streamsize count = (std::streamsize) size * nmemb;
stream->write(ptr, count);
return count;
}
API::API(const std::string& token, const std::string& secret)
{
curlhandle = curl_easy_init();
curl_easy_setopt(curlhandle, CURLOPT_FOLLOWLOCATION, 1);
curl_easy_setopt(curlhandle, CURLOPT_NOPROGRESS, 1);
curl_easy_setopt(curlhandle, CURLOPT_PROGRESSDATA, this);
curl_easy_setopt(curlhandle, CURLOPT_FAILONERROR, true);
curl_easy_setopt(curlhandle, CURLOPT_NOSIGNAL, 1);
this->error = false;
this->config.oauth_token = token;
this->config.oauth_secret = secret;
}
/* Initialize the API
returns 0 if failed
returns 1 if successful
*/
int API::init()
{
int res = 0;
this->getAPIConfig();
if (!this->getError())
res = 1;
else
this->clearError();
return res;
}
/* Login check
returns false if not logged in
returns true if logged in
*/
bool API::isLoggedIn()
{
int res = 0;
// Check if we already have token and secret
if (!this->config.oauth_token.empty() && !this->config.oauth_secret.empty())
{
// Test authorization by getting user details
res = this->getUserDetails(); // res = 1 if successful
}
return res;
}
int API::getAPIConfig()
{
std::string url = "https://api.gog.com/downloader2/status/stable/"; // Stable API
//std::string url = "https://api.gog.com/downloader2/status/beta/"; // Beta API
//std::string url = "https://api.gog.com/downloader2/status/e77989ed21758e78331b20e477fc5582/"; // Development API? Not sure because the downloader version number it reports is lower than beta.
std::string json = this->getResponse(url);
if (json.empty()) {
this->setError("Found nothing in " + url);
return 0;
}
Json::Value root;
std::istringstream json_stream(json);
try {
json_stream >> root;
} catch (const Json::Exception& exc) {
#ifdef DEBUG
std::cerr << "DEBUG INFO (API::getAPIConfig)" << std::endl << json << std::endl;
#endif
this->setError(exc.what());
return 0;
}
#ifdef DEBUG
std::cerr << "DEBUG INFO (API::getAPIConfig)" << std::endl << root << std::endl;
#endif
this->config.oauth_authorize_temp_token = root["config"]["oauth_authorize_temp_token"].asString() + "/";
this->config.oauth_get_temp_token = root["config"]["oauth_get_temp_token"].asString() + "/";
this->config.oauth_get_token = root["config"]["oauth_get_token"].asString() + "/";
this->config.get_user_games = root["config"]["get_user_games"].asString() + "/";
this->config.get_user_details = root["config"]["get_user_details"].asString() + "/";
this->config.get_installer_link = root["config"]["get_installer_link"].asString() + "/";
this->config.get_game_details = root["config"]["get_game_details"].asString() + "/";
this->config.get_extra_link = root["config"]["get_extra_link"].asString() + "/";
this->config.set_app_status = root["config"]["set_app_status"].asString() + "/";
return 1;
}
int API::login(const std::string& email, const std::string& password)
{
int res = 0;
std::string url;
std::string token, secret;
// Get temporary request token
url = oauth_sign_url2(this->config.oauth_get_temp_token.c_str(), NULL, OA_HMAC, NULL, CONSUMER_KEY.c_str(), CONSUMER_SECRET.c_str(), NULL /* token */, NULL /* secret */);
std::string request_token_resp = this->getResponse(url);
char **rv = NULL;
int rc = oauth_split_url_parameters(request_token_resp.c_str(), &rv);
qsort(rv, rc, sizeof(char *), oauth_cmpstringp);
if (rc == 3 && !strncmp(rv[1], "oauth_token=", OAUTH_TOKEN_LENGTH) && !strncmp(rv[2], "oauth_token_secret=", OAUTH_SECRET_LENGTH)) {
token = rv[1]+OAUTH_TOKEN_LENGTH+1;
secret = rv[2]+OAUTH_SECRET_LENGTH+1;
rv = NULL;
}
else
{
return res;
}
usleep(500); // Wait to avoid "429 Too Many Requests"
// Authorize temporary token and get verifier
url = this->config.oauth_authorize_temp_token + "?username=" + oauth_url_escape(email.c_str()) + "&password=" + oauth_url_escape(password.c_str());
url = oauth_sign_url2(url.c_str(), NULL, OA_HMAC, NULL, CONSUMER_KEY.c_str(), CONSUMER_SECRET.c_str(), token.c_str(), secret.c_str());
std::string authorize_resp = this->getResponse(url);
std::string verifier;
rc = oauth_split_url_parameters(authorize_resp.c_str(), &rv);
qsort(rv, rc, sizeof(char *), oauth_cmpstringp);
if (rc == 2 && !strncmp(rv[1], "oauth_verifier=", OAUTH_VERIFIER_LENGTH)) {
verifier = rv[1]+OAUTH_VERIFIER_LENGTH+1;
rv = NULL;
}
else
{
return res;
}
usleep(500); // Wait to avoid "429 Too Many Requests"
// Get final token and secret
url = this->config.oauth_get_token + "?oauth_verifier=" + verifier;
url = oauth_sign_url2(url.c_str(), NULL, OA_HMAC, NULL, CONSUMER_KEY.c_str(), CONSUMER_SECRET.c_str(), token.c_str(), secret.c_str());
std::string token_resp = this->getResponse(url);
rc = oauth_split_url_parameters(token_resp.c_str(), &rv);
qsort(rv, rc, sizeof(char *), oauth_cmpstringp);
if (rc == 2 && !strncmp(rv[0], "oauth_token=", OAUTH_TOKEN_LENGTH) && !strncmp(rv[1], "oauth_token_secret=", OAUTH_SECRET_LENGTH)) {
this->config.oauth_token = rv[0]+OAUTH_TOKEN_LENGTH+1;
this->config.oauth_secret = rv[1]+OAUTH_SECRET_LENGTH+1;
free(rv);
res = 1;
}
return res;
}
int API::getUserDetails()
{
std::string url;
url = this->config.get_user_details;
std::string json = this->getResponseOAuth(url);
if (json.empty()) {
this->setError("Found nothing in " + url);
return 0;
}
Json::Value root;
std::istringstream json_stream(json);
try {
json_stream >> root;
} catch (const Json::Exception& exc) {
#ifdef DEBUG
std::cerr << "DEBUG INFO (API::getUserDetails)" << std::endl << json << std::endl;
#endif
this->setError(exc.what());
return 0;
}
#ifdef DEBUG
std::cerr << "DEBUG INFO (API::getUserDetails)" << std::endl << root << std::endl;
#endif
this->user.id = std::stoull(root["user"]["id"].asString());
this->user.username = root["user"]["xywka"].asString();
this->user.email = root["user"]["email"].asString();
this->user.avatar_big = root["user"]["avatar"]["big"].asString();
this->user.avatar_small = root["user"]["avatar"]["small"].asString();
this->user.notifications_forum = root["user"]["notifications"]["forum"].isInt() ? root["user"]["notifications"]["forum"].asInt() : std::stoi(root["user"]["notifications"]["forum"].asString());
this->user.notifications_games = root["user"]["notifications"]["games"].isInt() ? root["user"]["notifications"]["games"].asInt() : std::stoi(root["user"]["notifications"]["games"].asString());
this->user.notifications_messages = root["user"]["notifications"]["messages"].isInt() ? root["user"]["notifications"]["messages"].asInt() : std::stoi(root["user"]["notifications"]["messages"].asString());
return 1;
}
int API::getGames()
{
// Not implemented on the server side currently
//std::string json = this->getResponseOAuth(this->config.get_user_games);
return 0;
}
std::string API::getResponse(const std::string& url)
{
#ifdef DEBUG
std::cerr << "DEBUG INFO (API::getResponse)" << std::endl << "URL: " << url << std::endl;
#endif
std::ostringstream memory;
curl_easy_setopt(curlhandle, CURLOPT_URL, url.c_str());
curl_easy_setopt(curlhandle, CURLOPT_NOPROGRESS, 1);
curl_easy_setopt(curlhandle, CURLOPT_WRITEFUNCTION, writeMemoryCallback);
curl_easy_setopt(curlhandle, CURLOPT_WRITEDATA, &memory);
CURLcode result = curl_easy_perform(curlhandle);
std::string response = memory.str();
memory.str(std::string());
if (result == CURLE_HTTP_RETURNED_ERROR)
{
long int response_code = 0;
result = curl_easy_getinfo(curlhandle, CURLINFO_RESPONSE_CODE, &response_code);
if (result == CURLE_OK)
this->setError("HTTP ERROR: " + std::to_string(response_code) + " (" + url + ")");
else
this->setError("HTTP ERROR: failed to get error code: " + static_cast<std::string>(curl_easy_strerror(result)) + " (" + url + ")");
#ifdef DEBUG
curl_easy_setopt(curlhandle, CURLOPT_FAILONERROR, false);
result = curl_easy_perform(curlhandle);
std::string debug_response = memory.str();
memory.str(std::string());
std::cerr << "Response (CURLE_HTTP_RETURNED_ERROR):";
if (debug_response.empty())
std::cerr << " Response was empty" << std::endl;
else
std::cerr << std::endl << debug_response << std::endl;
curl_easy_setopt(curlhandle, CURLOPT_FAILONERROR, true);
#endif
}
return response;
}
std::string API::getResponseOAuth(const std::string& url)
{
#ifdef DEBUG
std::cerr << "DEBUG INFO (API::getResponseOAuth)" << std::endl << "URL: " << url << std::endl;
#endif
std::string url_oauth = oauth_sign_url2(url.c_str(), NULL, OA_HMAC, NULL, CONSUMER_KEY.c_str(), CONSUMER_SECRET.c_str(), this->config.oauth_token.c_str(), this->config.oauth_secret.c_str());
std::string response = this->getResponse(url_oauth);
return response;
}
gameDetails API::getGameDetails(const std::string& game_name, const unsigned int& platform, const unsigned int& lang, const bool& useDuplicateHandler)
{
std::string url;
gameDetails game;
struct gameFileInfo
{
Json::Value jsonNode;
unsigned int platform;
unsigned int language;
};
url = this->config.get_game_details + game_name + "/" + "installer_win_en"; // can't get game details without file id, any file id seems to return all details which is good for us
std::string json = this->getResponseOAuth(url);
if (json.empty()) {
this->setError("Found nothing in " + url);
return game;
}
Json::Value root;
std::istringstream json_stream(json);
try {
json_stream >> root;
} catch (Json::Exception exc) {
#ifdef DEBUG
std::cerr << "DEBUG INFO (API::getGameDetails)" << std::endl << json << std::endl;
#endif
this->setError(exc.what());
return game;
}
#ifdef DEBUG
std::cerr << "DEBUG INFO (API::getGameDetails)" << std::endl << root << std::endl;
#endif
game.gamename = game_name;
game.title = root["game"]["title"].asString();
game.icon = root["game"]["icon"].asString();
std::vector<std::string> membernames = root["game"].getMemberNames();
// Installer details
// Create a list of installers from JSON
std::vector<gameFileInfo> installers;
for (unsigned int i = 0; i < GlobalConstants::PLATFORMS.size(); ++i)
{ // Check against the specified platforms
if (platform & GlobalConstants::PLATFORMS[i].id)
{
std::string installer = "installer_" + GlobalConstants::PLATFORMS[i].code + "_";
for (unsigned int j = 0; j < GlobalConstants::LANGUAGES.size(); ++j)
{ // Check against the specified languages
if (lang & GlobalConstants::LANGUAGES[j].id)
{ // Make sure that the installer exists in the JSON
if (root["game"].isMember(installer+GlobalConstants::LANGUAGES[j].code))
{
gameFileInfo installerInfo;
installerInfo.jsonNode = root["game"][installer+GlobalConstants::LANGUAGES[j].code];
installerInfo.platform = GlobalConstants::PLATFORMS[i].id;
installerInfo.language = GlobalConstants::LANGUAGES[j].id;
installers.push_back(installerInfo);
}
}
}
}
}
for ( unsigned int i = 0; i < installers.size(); ++i )
{
for ( unsigned int index = 0; index < installers[i].jsonNode.size(); ++index )
{
Json::Value installer = installers[i].jsonNode[index];
unsigned int language = installers[i].language;
std::string path = installer["link"].asString();
path = (std::string)curl_easy_unescape(curlhandle, path.c_str(), path.size(), NULL);
// Check for duplicate installers in different languages and add languageId of duplicate installer to the original installer
// https://secure.gog.com/forum/general/introducing_the_beta_release_of_the_new_gogcom_downloader/post1483
if (useDuplicateHandler)
{
bool bDuplicate = false;
for (unsigned int j = 0; j < game.installers.size(); ++j)
{
if (game.installers[j].path == path)
{
game.installers[j].language |= language; // Add language code to installer
bDuplicate = true;
break;
}
}
if (bDuplicate)
continue;
}
gameFile gf;
gf.type = GFTYPE_INSTALLER;
gf.gamename = game.gamename;
gf.updated = installer["notificated"].isInt() ? installer["notificated"].asInt() : std::stoi(installer["notificated"].asString());
gf.id = installer["id"].isInt() ? std::to_string(installer["id"].asInt()) : installer["id"].asString();
gf.name = installer["name"].asString();
gf.path = path;
gf.size = installer["size"].asString();
gf.language = language;
gf.platform = installers[i].platform;
gf.silent = installer["silent"].isInt() ? installer["silent"].asInt() : std::stoi(installer["silent"].asString());
game.installers.push_back(gf);
}
}
// Extra details
const Json::Value extras = root["game"]["extras"];
for ( unsigned int index = 0; index < extras.size(); ++index )
{
Json::Value extra = extras[index];
gameFile gf;
gf.type = GFTYPE_EXTRA;
gf.gamename = game.gamename;
gf.updated = false; // extras don't have "updated" flag
gf.id = extra["id"].isInt() ? std::to_string(extra["id"].asInt()) : extra["id"].asString();
gf.name = extra["name"].asString();
gf.path = extra["link"].asString();
gf.path = (std::string)curl_easy_unescape(curlhandle, gf.path.c_str(), gf.path.size(), NULL);
gf.size = extra["size_mb"].asString();
game.extras.push_back(gf);
}
// Patch details
for (unsigned int i = 0; i < GlobalConstants::LANGUAGES.size(); ++i)
{ // Check against the specified languages
if (lang & GlobalConstants::LANGUAGES[i].id)
{
// Try to find a patch
_regex_namespace_::regex re(GlobalConstants::LANGUAGES[i].code + "\\d+patch\\d+", _regex_namespace_::regex_constants::icase); // regex for patch node names
std::vector<gameFileInfo> patches;
for (unsigned int j = 0; j < membernames.size(); ++j)
{
if (_regex_namespace_::regex_match(membernames[j], re))
{ // Regex matches, we have a patch node
gameFileInfo patchInfo;
patchInfo.jsonNode = root["game"][membernames[j]];
patchInfo.language = GlobalConstants::LANGUAGES[i].id;
if (patchInfo.jsonNode["link"].asString().find("/mac/") != std::string::npos)
patchInfo.platform = GlobalConstants::PLATFORM_MAC;
else if (patchInfo.jsonNode["link"].asString().find("/linux/") != std::string::npos)
patchInfo.platform = GlobalConstants::PLATFORM_LINUX;
else
patchInfo.platform = GlobalConstants::PLATFORM_WINDOWS;
if (platform & patchInfo.platform)
patches.push_back(patchInfo);
}
}
if (!patches.empty()) // found at least one patch
{
for (unsigned int j = 0; j < patches.size(); ++j)
{
Json::Value patchnode = patches[j].jsonNode;
if (patchnode.isArray()) // Patch has multiple files
{
for ( unsigned int index = 0; index < patchnode.size(); ++index )
{
Json::Value patch = patchnode[index];
std::string path = patch["link"].asString();
path = (std::string)curl_easy_unescape(curlhandle, path.c_str(), path.size(), NULL);
// Check for duplicate patches in different languages and add languageId of duplicate patch to the original patch
if (useDuplicateHandler)
{
bool bDuplicate = false;
for (unsigned int j = 0; j < game.patches.size(); ++j)
{
if (game.patches[j].path == path)
{
game.patches[j].language |= GlobalConstants::LANGUAGES[i].id; // Add language code to patch
bDuplicate = true;
break;
}
}
if (bDuplicate)
continue;
}
gameFile gf;
gf.type = GFTYPE_PATCH;
gf.gamename = game.gamename;
gf.updated = patch["notificated"].isInt() ? patch["notificated"].asInt() : std::stoi(patch["notificated"].asString());
gf.id = patch["id"].isInt() ? std::to_string(patch["id"].asInt()) : patch["id"].asString();
gf.name = patch["name"].asString();
gf.path = path;
gf.size = patch["size"].asString();
gf.language = GlobalConstants::LANGUAGES[i].id;
gf.platform = patches[j].platform;
game.patches.push_back(gf);
}
}
else // Patch is a single file
{
std::string path = patchnode["link"].asString();
path = (std::string)curl_easy_unescape(curlhandle, path.c_str(), path.size(), NULL);
// Check for duplicate patches in different languages and add languageId of duplicate patch to the original patch
if (useDuplicateHandler)
{
bool bDuplicate = false;
for (unsigned int k = 0; k < game.patches.size(); ++k)
{
if (game.patches[k].path == path)
{
game.patches[k].language |= GlobalConstants::LANGUAGES[i].id; // Add language code to patch
bDuplicate = true;
break;
}
}
if (bDuplicate)
continue;
}
gameFile gf;
gf.type = GFTYPE_PATCH;
gf.gamename = game.gamename;
gf.updated = patchnode["notificated"].isInt() ? patchnode["notificated"].asInt() : std::stoi(patchnode["notificated"].asString());
gf.id = patchnode["id"].isInt() ? std::to_string(patchnode["id"].asInt()) : patchnode["id"].asString();
gf.name = patchnode["name"].asString();
gf.path = path;
gf.size = patchnode["size"].asString();
gf.language = GlobalConstants::LANGUAGES[i].id;
gf.platform = patches[j].platform;
game.patches.push_back(gf);
}
}
}
}
}
// Language pack details
for (unsigned int i = 0; i < GlobalConstants::LANGUAGES.size(); ++i)
{ // Check against the specified languages
if (lang & GlobalConstants::LANGUAGES[i].id)
{
// Try to find a language pack
_regex_namespace_::regex re(GlobalConstants::LANGUAGES[i].code + "\\d+langpack\\d+", _regex_namespace_::regex_constants::icase); // regex for language pack node names
std::vector<std::string> langpacknames;
for (unsigned int j = 0; j < membernames.size(); ++j)
{
if (_regex_namespace_::regex_match(membernames[j], re))
langpacknames.push_back(membernames[j]);
}
if (!langpacknames.empty()) // found at least one language pack
{
for (unsigned int j = 0; j < langpacknames.size(); ++j)
{
Json::Value langpack = root["game"][langpacknames[j]];
gameFile gf;
gf.type = GFTYPE_LANGPACK;
gf.gamename = game.gamename;
gf.updated = false; // language packs don't have "updated" flag
gf.id = langpack["id"].isInt() ? std::to_string(langpack["id"].asInt()) : langpack["id"].asString();
gf.name = langpack["name"].asString();
gf.path = langpack["link"].asString();
gf.path = (std::string)curl_easy_unescape(curlhandle, gf.path.c_str(), gf.path.size(), NULL);
gf.size = langpack["size"].asString();
gf.language = GlobalConstants::LANGUAGES[i].id;
game.languagepacks.push_back(gf);
}
}
}
}
return game;
}
std::string API::getInstallerLink(const std::string& game_name, const std::string& id)
{
std::string url, link;
url = this->config.get_installer_link + game_name + "/" + id + "/";
std::string json = this->getResponseOAuth(url);
if (json.empty()) {
this->setError("Found nothing in " + url);
return link;
}
Json::Value root;
std::istringstream json_stream(json);
try {
json_stream >> root;
} catch (const Json::Exception& exc) {
#ifdef DEBUG
std::cerr << "DEBUG INFO (API::getInstallerLink)" << std::endl << json << std::endl;
#endif
this->setError(exc.what());
return link;
}
#ifdef DEBUG
std::cerr << "DEBUG INFO (API::getInstallerLink)" << std::endl << root << std::endl;
#endif
int available = root["file"]["available"].isInt() ? root["file"]["available"].asInt() : std::stoi(root["file"]["available"].asString());
if (available)
link = root["file"]["link"].asString();
return link;
}
std::string API::getExtraLink(const std::string& game_name, const std::string& id)
{
std::string url, link;
url = this->config.get_extra_link + game_name + "/" + id + "/";
std::string json = this->getResponseOAuth(url);
if (json.empty()) {
this->setError("Found nothing in " + url);
return link;
}
Json::Value root;
std::istringstream json_stream(json);
try {
json_stream >> root;
} catch (const Json::Exception& exc) {
#ifdef DEBUG
std::cerr << "DEBUG INFO (API::getExtraLink)" << std::endl << json << std::endl;
#endif
this->setError(exc.what());
return link;
}
#ifdef DEBUG
std::cerr << "DEBUG INFO (API::getExtraLink)" << std::endl << root << std::endl;
#endif
int available = root["file"]["available"].isInt() ? root["file"]["available"].asInt() : std::stoi(root["file"]["available"].asString());
if (available)
link = root["file"]["link"].asString();
return link;
}
std::string API::getPatchLink(const std::string& game_name, const std::string& id)
{
return this->getInstallerLink(game_name, id);
}
std::string API::getLanguagePackLink(const std::string& game_name, const std::string& id)
{
return this->getInstallerLink(game_name, id);
}
std::string API::getXML(const std::string& game_name, const std::string& id)
{
std::string url, XML;
url = this->config.get_installer_link + game_name + "/" + id + "/crc/";
std::string json = this->getResponseOAuth(url);
if (json.empty()) {
this->setError("Found nothing in " + url);
return XML;
}
try {
std::istringstream iss(json);
Json::Value root;
iss >> root;
#ifdef DEBUG
std::cerr << "DEBUG INFO (API::getXML)" << std::endl << root << std::endl;
#endif
int available = root["file"]["available"].isInt() ? root["file"]["available"].asInt() : std::stoi(root["file"]["available"].asString());
if (available)
{
url = root["file"]["link"].asString();
XML = this->getResponse(url);
}
} catch (const Json::Exception& exc) {
#ifdef DEBUG
std::cerr << "DEBUG INFO (API::getXML)" << std::endl << json << std::endl;
#endif
this->setError(exc.what());
}
return XML;
}
void API::clearError()
{
this->error = false;
this->error_message = "";
}
void API::setError(const std::string& err)
{
this->error = true;
if (this->error_message.empty())
this->error_message = err;
else
this->error_message += "\n" + err;
}
API::~API()
{
curl_easy_cleanup(curlhandle);
}
| 38.855093 | 208 | 0.561665 | [
"vector"
] |
2bb816ea00b814bd6cff59df9018ce6e5b882e20 | 1,787 | cpp | C++ | Classes/ShipConfig.cpp | JoaoBaptMG/InfiniteSpaceExplorer | 841fbf57e8bcab279a7b252dad1f4ef411c5cc47 | [
"MIT"
] | 2 | 2018-11-26T03:47:18.000Z | 2019-01-12T10:07:58.000Z | Classes/ShipConfig.cpp | JoaoBaptMG/InfiniteSpaceExplorer | 841fbf57e8bcab279a7b252dad1f4ef411c5cc47 | [
"MIT"
] | null | null | null | Classes/ShipConfig.cpp | JoaoBaptMG/InfiniteSpaceExplorer | 841fbf57e8bcab279a7b252dad1f4ef411c5cc47 | [
"MIT"
] | 1 | 2019-12-25T01:28:49.000Z | 2019-12-25T01:28:49.000Z | //
// ShipConfig.cpp
// SpaceExplorer
//
// Created by João Baptista on 28/06/15.
//
//
#include "ShipConfig.h"
using namespace cocos2d;
static std::vector<ShipConfig> configs;
static bool init = false;
void parseConfigValueVector(const ValueVector &configValueVector, std::vector<ShipConfig> &configs)
{
for (const Value& value : configValueVector)
{
const ValueMap& map = value.asValueMap();
ShipConfig cfg;
cfg.pointsRequired = map.at("PointsRequired").asInt();
cfg.jetScale = map.at("JetScale").asFloat();
cfg.damageMultiplier = map.at("DamageMultiplier").asFloat();
for (const Value &posValue : map.at("JetPositions").asValueVector())
cfg.jetPositions.push_back(PointFromString(posValue.asString()));
auto polygonListIt = map.find("CollisionPolygon");
if ((cfg.collisionIsPolygon = polygonListIt != map.end()))
{
for (const Value &colValue : polygonListIt->second.asValueVector())
cfg.collisionList.push_back(PointFromString(colValue.asString()));
}
else
{
cfg.collisionRadius = map.at("CollisionRadius").asFloat();
cfg.collisionOffset = PointFromString(map.at("CollisionOffset").asString());
}
configs.push_back(std::move(cfg));
}
}
const ShipConfig &getShipConfig(unsigned long index)
{
if (!init)
{
ValueVector parseFile = FileUtils::getInstance()->getValueVectorFromFile("ShipConfig.plist");
parseConfigValueVector(parseFile, configs);
init = true;
}
return configs[index];
}
unsigned long getShipConfigSize()
{
if (!init) getShipConfig(0); // trigger config creation
return configs.size();
} | 28.822581 | 101 | 0.637941 | [
"vector"
] |
2bbb88df4c650af04a1991c3249de4cb57ebd9e9 | 3,643 | hpp | C++ | libs/dkutf/review/dkutf_cdt.hpp | Goreli/DKCPPDEV | 9436183d8b92fe62f32c3d227fa044c429724129 | [
"MIT"
] | 1 | 2019-10-27T13:26:55.000Z | 2019-10-27T13:26:55.000Z | libs/dkutf/review/dkutf_cdt.hpp | Goreli/DKCPPDEV | 9436183d8b92fe62f32c3d227fa044c429724129 | [
"MIT"
] | null | null | null | libs/dkutf/review/dkutf_cdt.hpp | Goreli/DKCPPDEV | 9436183d8b92fe62f32c3d227fa044c429724129 | [
"MIT"
] | null | null | null | /*
MIT License
Copyright(c) 2019 David Krikheli
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.
*/
/*
Modification history:
*/
#ifndef libs_dk_cdt_hpp
#define libs_dk_cdt_hpp
namespace dk {
class ConstDestTracker {
// Make an object of this class a member of a class that you want to test.
// Access type doesn't have any significance - should probably be made private.
// Call reset() before the start of each test.
//
// The following is expected at the end of the test:
// 1. getConstCount() == getDestCount()
// 2. getCtrlSum() == 0
public:
ConstDestTracker() noexcept;
// The copy constructor has only been introduced to
// preclude the default compiler generated construction.
// This is because we need to protect iObjSeqId_ from being
// corrupted.
ConstDestTracker(const ConstDestTracker&) noexcept;
// The move constructor serves a similar purpose - protect
// iObjSeqId_ from corruption in case a wrapper class applies
// brute force and tries to overwrite the content.
ConstDestTracker(ConstDestTracker&&) noexcept;
virtual ~ConstDestTracker() noexcept;
// The copy assignment operator below has only been introduced
// to preclude the default compiler generated assignment.
// This is because we need to protect iObjSeqId_ from being
// corrupted.
ConstDestTracker& operator = (const ConstDestTracker&) noexcept;
// The move assignment operator serves a similar purpose - protect
// iObjSeqId_ from corruption in case a wrapper class applies
// brute force and tries to overwrite the content.
ConstDestTracker& operator = (ConstDestTracker&&) noexcept;
static size_t getConstCount(void) noexcept;
static size_t getDestCount(void) noexcept;
static size_t getCtrlSum(void) noexcept;
static void reset() noexcept;
private:
// Total count of instrumented objects created.
static size_t iConstructorCount_;
// Total count of instrumented objects destroyed.
static size_t iDestructorCount_;
// Increases as instrumented objects are created.
// Decreases as instrumented objects are destroyed.
static size_t iControlSum_;
// Unique id of an instrumented object.
// If the object is overwritten by a brute force of a bug of some sort
// then correctness of the iControlSum_ calculation (reduction) will be
// impacted and we are likely to witness a non-zero value of the control
// sum at the end of the test. Otherwise, if there is no brute force/bug
// distorting the value then we should see the following at the end of the
// test: iControlSum_ == 0.
size_t iObjSeqId_;
void init_() noexcept;
};
} // namespace dk
#endif // libs_dk_cdt_hpp
| 37.173469 | 81 | 0.76146 | [
"object"
] |
2bc3ec3786d67d3b69e64c07542d75c00610fc4f | 5,067 | cpp | C++ | FootSoldier.cpp | VadimKachevski/cpp-wargame | 85d4c7c6170014bec08552907cdd5f3541cc4db8 | [
"MIT"
] | null | null | null | FootSoldier.cpp | VadimKachevski/cpp-wargame | 85d4c7c6170014bec08552907cdd5f3541cc4db8 | [
"MIT"
] | null | null | null | FootSoldier.cpp | VadimKachevski/cpp-wargame | 85d4c7c6170014bec08552907cdd5f3541cc4db8 | [
"MIT"
] | null | null | null | #include "FootSoldier.hpp"
#include "math.h"
// namespace WarGame
// {
void FootSoldier::action(vector<vector<Soldier *>> &board, pair<int, int> dest)
{
double closest=board.size()*board.size();
int ci,cj;
int found =0;
for(int i=0;i<board.size();i++)
{
for(int j=0;j<board.size();j++)
{
Soldier *s;
s= board[i][j];
if(s!=nullptr && (s->getPnum() != board[dest.first][dest.second]->getPnum()))
{
double dist = sqrt((i-dest.first)*(i-dest.first) + (j-dest.second)*(j-dest.second));
if(dist<closest)
{
closest =dist;
ci = i;
cj = j;
found = 1;
}
}
}
}
if(found){
Soldier *s = board[ci][cj];
int hp = s->getCurrHP() - board[dest.first][dest.second]->getact();
if(hp <= 0)
{
board[ci][cj] = nullptr;
}
else
{
s->setHP(hp);
}
// s->setHP(s->getCurrHP() - board[dest.first][dest.second]->getact());
// if (s->getCurrHP() <= 0)
// {
// board[ci][cj] = nullptr;
// }
}
// int iter = 1;
// bool found = false;
// while (!found)
// {
// for (int x = -iter; x <= iter; x++)
// {
// Soldier *s;
// // iter,x
// if (dest.first + iter >= 0 && dest.first + iter < board.size())
// {
// if (dest.second + x >= 0 && dest.second + x < board[dest.first + iter].size())
// {
// s = board[dest.first + iter][dest.second + x];
// if (s != nullptr && s->getPnum() != board[dest.first][dest.second]->getPnum())
// {
// s->setHP(s->getCurrHP() - board[dest.first][dest.second]->getact());
// if (s->getCurrHP() <= 0)
// {
// board[dest.first + iter][dest.second + x] = nullptr;
// }
// found = true;
// return;
// }
// }
// }
// // -iter,x
// if (dest.first - iter >= 0 && dest.first - iter < board.size())
// {
// if (dest.second + x >= 0 && dest.second + x < board[dest.first - iter].size())
// {
// s = board[dest.first - iter][dest.second + x];
// if (s != nullptr && s->getPnum() != board[dest.first][dest.second]->getPnum())
// {
// s->setHP(s->getCurrHP() - board[dest.first][dest.second]->getact());
// if (s->getCurrHP() <= 0)
// {
// board[dest.first - iter][dest.second + x] = nullptr;
// }
// found = true;
// return;
// }
// }
// }
// //x,-iter
// if (dest.first + x >= 0 && dest.first + x < board.size())
// {
// if (dest.second - iter >= 0 && dest.second - iter < board[dest.first + x].size())
// {
// s = board[dest.first + x][dest.second - iter];
// if (s != nullptr && s->getPnum() != board[dest.first][dest.second]->getPnum())
// {
// s->setHP(s->getCurrHP() - board[dest.first][dest.second]->getact());
// if (s->getCurrHP() <= 0)
// {
// board[dest.first + x][dest.second - iter] = nullptr;
// }
// found = true;
// return;
// }
// }
// }
// //x,iter
// if (dest.first + x >= 0 && dest.first + x < board.size())
// {
// if (dest.second + iter >= 0 && dest.second + iter < board[dest.first + x].size())
// {
// s = board[dest.first + x][dest.second + iter];
// if (s != nullptr && s->getPnum() != board[dest.first][dest.second]->getPnum())
// {
// s->setHP(s->getCurrHP() - board[dest.first][dest.second]->getact());
// if (s->getCurrHP() <= 0)
// {
// board[dest.first + x][dest.second + iter] = nullptr;
// }
// found = true;
// return;
// }
// }
// }
// }
// if (iter >= board.size())
// {
// return;
// }
// iter++;
// }
}
// } // namespace WarGame | 35.93617 | 101 | 0.342412 | [
"vector"
] |
2bc507b6359a0dbe5b89e4bd5ad7a9457f5ecb1b | 9,936 | cpp | C++ | main/PISupervisor/src/PIActionProcessDeviceLog.cpp | sim1st/endpointdlp | f5203f23e93b00c8242c45fa85c26d9b7419e50c | [
"Apache-2.0"
] | null | null | null | main/PISupervisor/src/PIActionProcessDeviceLog.cpp | sim1st/endpointdlp | f5203f23e93b00c8242c45fa85c26d9b7419e50c | [
"Apache-2.0"
] | null | null | null | main/PISupervisor/src/PIActionProcessDeviceLog.cpp | sim1st/endpointdlp | f5203f23e93b00c8242c45fa85c26d9b7419e50c | [
"Apache-2.0"
] | null | null | null | #ifndef _PIACTIONPROCESSDEVICELOG_CPP
#define _PIACTIONPROCESSDEVICELOG_CPP
#include <map>
#include "PIActionProcessDeviceLog.h"
#include "PIDocument.h"
#include <sys/time.h>
#include "sqlite3.h"
////////////////////////////////////////
// CPIActionProcessDeviceLog
CPIActionProcessDeviceLog::CPIActionProcessDeviceLog() {
clear();
}
CPIActionProcessDeviceLog::~CPIActionProcessDeviceLog() {
}
void CPIActionProcessDeviceLog::clear(void) {
CPIObject::clear();
isContinue = true;
running = false;
deviceLog.clear();
}
bool CPIActionProcessDeviceLog::initialize(void) {
DEBUG_LOG1("process device log - begin");
CPIObject::initialize();
pthread_mutex_init( &mutexDeviceLog, 0 );
pthread_cond_init( &condDeviceLog, 0 );
stateDeviceLog = CPIActionProcessDeviceLog::STATE_WAIT;
pthread_mutex_init( &mutexSavedDeviceLog, 0 );
pthread_cond_init( &condSavedDeviceLog, 0 );
stateSavedDeviceLog = CPIActionProcessDeviceLog::STATE_WAIT;
pthread_mutex_init( &mutexPISQLite, 0 );
DEBUG_LOG1("process device log - end");
return true;
}
bool CPIActionProcessDeviceLog::finalize(void) {
DEBUG_LOG1("process device log - begin");
pthread_mutex_unlock( &mutexDeviceLog);
pthread_mutex_destroy( &mutexDeviceLog);
pthread_cond_destroy( &condDeviceLog);
pthread_mutex_unlock( &mutexSavedDeviceLog);
pthread_mutex_destroy( &mutexSavedDeviceLog);
pthread_cond_destroy( &condSavedDeviceLog);
pthread_mutex_unlock( &mutexPISQLite);
pthread_mutex_destroy( &mutexPISQLite);
DEBUG_LOG1("process device log - end");
return CPIObject::finalize();
}
int CPIActionProcessDeviceLog::run(const std::string& param) {
DEBUG_LOG1("process device log - begin");
INFO_LOG1("connect to driver");
if( true == isRunning() ) {
DEBUG_LOG1("process device log - skip - already running");
return 0;
}
initialize();
if( false == startThreads() ) {
ERROR_LOG1("process device log - create_thread failed");
}
DEBUG_LOG1("process device log - end");
return 0;
}
bool CPIActionProcessDeviceLog::startThreads(void) {
DEBUG_LOG1("process device log - begin");
int result = 0;
if( false == isRunning() ) {
pthread_attr_init( &logThreadAttr);
pthread_attr_setscope( &logThreadAttr, PTHREAD_SCOPE_SYSTEM );
result = pthread_create( &logThread, &logThreadAttr, CPIActionProcessDeviceLog::fnLog, (void*)this);
if( result ) {
ERROR_LOG1( "Unable to start thread for log" );
return false;
}
pthread_attr_init( &savedLogThreadAttr);
pthread_attr_setscope( &savedLogThreadAttr, PTHREAD_SCOPE_SYSTEM );
result = pthread_create( &savedLogThread, &savedLogThreadAttr, CPIActionProcessDeviceLog::fnSavedLog, (void*)this);
if( result ) {
ERROR_LOG1( "Unable to start thread for saved log" );
return false;
}
}
else {
DEBUG_LOG1("process device log - skip - already running");
}
DEBUG_LOG1("process device log - end");
return true;
}
void CPIActionProcessDeviceLog::waitThreads(void) {
DEBUG_LOG1("process device log - begin");
if( true == isRunning() ) {
pthread_join( logThread, (void**)NULL );
pthread_join( savedLogThread, (void**)NULL );
}
DEBUG_LOG1("process device log - end");
}
int CPIActionProcessDeviceLog::stop(void) {
DEBUG_LOG1("process device log - begin");
isContinue = false;
stateDeviceLog = CPIActionProcessDeviceLog::STATE_SIG;
pthread_cond_signal(&condDeviceLog);
stateSavedDeviceLog = CPIActionProcessDeviceLog::STATE_SIG;
pthread_cond_signal(&condSavedDeviceLog);
waitThreads();
finalize();
DEBUG_LOG1("process device log - end");
return 0;
}
CPIActionProcessDeviceLog& CPIActionProcessDeviceLog::getInstance(void) {
static CPIActionProcessDeviceLog instance;
return instance;
}
void* CPIActionProcessDeviceLog::fnLog(void* pzArg)
{
DEBUG_LOG1("process device log - begin");
CPIActionProcessDeviceLog* instance = reinterpret_cast<CPIActionProcessDeviceLog*>(pzArg);
instance->running = true;
CPIDeviceLog::VECTOR deviceLog;
while(instance->isContinue && (false == Doc.getStop()))
{
pthread_mutex_lock( &instance->mutexDeviceLog);
DEBUG_LOG1("process device log - driver log wait...");
while(CPIActionProcessDeviceLog::STATE_SIG != instance->stateDeviceLog)
{
/* int err = */ pthread_cond_wait(&instance->condDeviceLog, &instance->mutexDeviceLog);
//DEBUG_LOG("process device log - pthread_cond_wait - %d", err);
}
if(false == instance->isContinue || (true == Doc.getStop()))
{
break;
}
DEBUG_LOG1("process device log - driver log received...");
if( 0 < instance->deviceLog.size() ) {
deviceLog.clear();
deviceLog.resize(instance->deviceLog.size());
std::copy(instance->deviceLog.begin(), instance->deviceLog.end(), deviceLog.begin());
instance->deviceLog.clear();
}
instance->stateDeviceLog = CPIActionProcessDeviceLog::STATE_WAIT;
pthread_mutex_unlock( &instance->mutexDeviceLog);
if( 0 == deviceLog.size() ) {
continue;
}
// ----------
bool result = true;
for(size_t index = 0; index < deviceLog.size(); ++index)
{
DEBUG_LOG1("process device log - process driver log ...");
//DEBUG_LOG("process device log - sample : %s", deviceLog[index].string().c_str());
if((deviceLog[index].policyType != MEDIA_AIRDROP) && true == DeviceMan.isDuplicatedDeviceLog(deviceLog[index]) )
{
DEBUG_LOG("process device log - skip - duplicated:%s", deviceLog[index].string().c_str());
continue;
}
result = PIAgentStub.setDeviceLog(deviceLog[index].string());
if( false == result ) {
DEBUG_LOG1("process device log - sending_device_log - failed");
ERROR_LOG1("process device log - sending_device_log - failed");
instance->saveDeviceLog(index, deviceLog);
break;
}
}
deviceLog.clear();
if( ( true == result ) && ( 0 < instance->savedDeviceLogCount ) ) {
pthread_mutex_lock(&instance->mutexSavedDeviceLog);
instance->stateSavedDeviceLog = CPIActionProcessDeviceLog::STATE_SIG;
pthread_mutex_unlock(&instance->mutexSavedDeviceLog);
pthread_cond_signal(&instance->condSavedDeviceLog);
}
// ----------
}
instance->running = false;
DEBUG_LOG1("process device log - end");
return NULL;
}
void* CPIActionProcessDeviceLog::fnSavedLog(void* pzArg) {
DEBUG_LOG1("process device log - begin");
#define WAIT_TIME_SECONDS 10
CPIActionProcessDeviceLog* instance = reinterpret_cast<CPIActionProcessDeviceLog*>(pzArg);
instance->running = true;
struct timespec ts;
struct timeval tv;
CPIDeviceLog::VECTOR deviceLog;
while(instance->isContinue && (false == Doc.getStop())) {
pthread_mutex_lock( &instance->mutexSavedDeviceLog);
//DEBUG_LOG1("process device log - driver log wait...");
gettimeofday(&tv, NULL);
ts.tv_sec = tv.tv_sec;
ts.tv_nsec = tv.tv_usec * 1000;
ts.tv_sec += WAIT_TIME_SECONDS;
while(CPIActionProcessDeviceLog::STATE_SIG != instance->stateSavedDeviceLog) {
int rc = pthread_cond_timedwait(&instance->condSavedDeviceLog, &instance->mutexSavedDeviceLog, &ts);
//DEBUG_LOG("process device log - pthread_cond_timedwait - %d", rc);
if( ETIMEDOUT == rc ) {
//DEBUG_LOG1("process device log - pthread_cond_timedwait - timeout");
break;
}
}
if(false == instance->isContinue || (true == Doc.getStop())) {
break;
}
if( true == PIAgentStub.isRegistered() ) {
pthread_mutex_lock( &instance->mutexPISQLite);
PISQLiteStub.getAll(deviceLog);
pthread_mutex_unlock( &instance->mutexPISQLite);
}
instance->stateSavedDeviceLog = CPIActionProcessDeviceLog::STATE_WAIT;
pthread_mutex_unlock( &instance->mutexSavedDeviceLog);
instance->sendSavedDeviceLog(deviceLog);
deviceLog.clear();
}
#undef WAIT_TIME_SECONDS
instance->running = false;
DEBUG_LOG1("process device log - end");
return NULL;
}
bool CPIActionProcessDeviceLog::isRunning(void) {
return running;
}
void CPIActionProcessDeviceLog::addDeviceLog(CPIDeviceLog& deviceLog) {
DEBUG_LOG1("process device log");
pthread_mutex_lock(&mutexDeviceLog);
stateDeviceLog = CPIActionProcessDeviceLog::STATE_SIG;
this->deviceLog.push_back(deviceLog);
pthread_mutex_unlock(&mutexDeviceLog);
pthread_cond_signal(&condDeviceLog);
}
bool CPIActionProcessDeviceLog::saveDeviceLog(size_t index, CPIDeviceLog::VECTOR& deviceLog) {
if( index >= deviceLog.size() ) {
return false;
}
void* conn;
PISQLiteStub.open(conn);
for(; index < deviceLog.size(); ++index) {
//todo: log save and retry again
DEBUG_LOG1("process device log - save device_log");
pthread_mutex_lock( &mutexPISQLite);
PISQLiteStub.push_back(conn, deviceLog[index]);
pthread_mutex_unlock( &mutexPISQLite);
}
PISQLiteStub.close(conn);
return true;
}
bool CPIActionProcessDeviceLog::sendSavedDeviceLog(CPIDeviceLog::VECTOR& deviceLog) {
if( 0 == deviceLog.size() ) {
return true;
}
void* conn;
PISQLiteStub.open(conn);
for(size_t index = 0; index < deviceLog.size(); ++index) {
DEBUG_LOG1("process device log - process...");
bool result = PIAgentStub.setDeviceLog(deviceLog[index].string());
if( false == result ) {
DEBUG_LOG1("process device log - sending_device_log - failed");
ERROR_LOG1("process device log - sending_device_log - failed");
break;
}
pthread_mutex_lock( &mutexPISQLite);
PISQLiteStub.erase(conn, deviceLog[index].seq, deviceLog[index].getLogTime());
pthread_mutex_unlock( &mutexPISQLite);
}
PISQLiteStub.close(conn);
deviceLog.clear();
return true;
}
#endif // #ifndef _PIACTIONPROCESSDEVICELOG_CPP
| 29.052632 | 125 | 0.688305 | [
"vector"
] |
2bcbae76ea313836091478fd6e40f3d2897bb599 | 2,142 | cpp | C++ | a3-courses/main.cpp | dontdropmybass/a3-courses | f1b3fba1b3447c08e57239619a872079f5cda71e | [
"WTFPL"
] | null | null | null | a3-courses/main.cpp | dontdropmybass/a3-courses | f1b3fba1b3447c08e57239619a872079f5cda71e | [
"WTFPL"
] | null | null | null | a3-courses/main.cpp | dontdropmybass/a3-courses | f1b3fba1b3447c08e57239619a872079f5cda71e | [
"WTFPL"
] | null | null | null | //
// main.cpp
// a3-courses
//
// Created by Alexander Cochrane 2016-10-31
//
#include "Student.hpp"
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
// overloaded << operator
//
// used to output a student object
//
// example:
//
// Student Alex:
//
// Courses:
// Course 1: C++
// Course 2: PHP
// Course 3: J2EE
ostream& operator << (ostream& output, Student& that) {
output << "Student " << that.name << ":" << endl << endl;
output << "Courses:" << endl;
for (int i = 0; i < that.numCourses; i++) {
output << "\tCourse #" << i+1 << ": " << that.courseList[i] << endl;
}
return output;
}
// main
// takes input to define Student objects
int main() {
string name;
cout << endl << "Input student name: ";
getline(cin,name);
cin.clear();
Student student = Student(name);
// Loops continuously, adding new courses to the Student object.
// Ends only when user enters an empty string
while (true) {
string temp;
cout << endl << "\tNext course: ";
temp.clear();
getline(cin,temp);
cin.clear();
if (temp=="") {
break;
}
else {
student.addCourse(temp);
}
}
// End while true
// print out student
cout << endl << student;
_getch();
// get the name of a new student
cout << endl << "Input student name: ";
name.clear();
getline(cin,name);
// copy the original student into a second student
Student student2 = Student(student);
// delete the original student
student.~Student();
// set the second students name to the name retrieved earlier
student2.setName(name);
// print out second student
cout << endl << student2;
// ask if they want to do it all again
cout << endl << "Continue? (Y,n): ";
string temp;
getline(cin,temp);
cin.clear();
// Goes back to the start unless user enters n or N
if (temp!="n"&&temp!="N") main();
return 0;
}
| 22.547368 | 76 | 0.542017 | [
"object"
] |
2bdaa109d7372bffd9a477b6b0b6a710e3f1c1e8 | 593 | cpp | C++ | app/core/post/main.cpp | C0PEP0D/sheld0n | 497d4ee8b6b1815cd5fa1b378d1b947ee259f4bc | [
"MIT"
] | null | null | null | app/core/post/main.cpp | C0PEP0D/sheld0n | 497d4ee8b6b1815cd5fa1b378d1b947ee259f4bc | [
"MIT"
] | null | null | null | app/core/post/main.cpp | C0PEP0D/sheld0n | 497d4ee8b6b1815cd5fa1b378d1b947ee259f4bc | [
"MIT"
] | null | null | null | // app includes
// // env
#include "core/env/core.h"
#include "param/env/parameters.h"
// // objects
#include "core/env/objects/core.h"
#include "param/env/objects/parameters.h"
// // post
#include "core/post/core.h"
#include "param/post/parameters.h"
// // post objects
#include "param/post/objects/parameters.h"
// // post mesh
#include "param/post/mesh/parameters.h"
// // post flow
#include "param/post/flow/parameters.h"
int main () {
c0p::Post<c0p::PostParameters, c0p::PostObjectsParameters, c0p::PostMeshParameters, c0p::PostFlowParameters, c0p::Env<c0p::EnvParameters>> post;
}
| 28.238095 | 148 | 0.711636 | [
"mesh"
] |
2bdc298889060515bda5d5528b94d3e344c7c098 | 20,074 | cpp | C++ | MogaSerial_MFC/MogaSerialDlg.cpp | kvanderlaag/MogaSerial | dce4df5e814af7637f4fd7388e26b07ba2092441 | [
"MIT"
] | null | null | null | MogaSerial_MFC/MogaSerialDlg.cpp | kvanderlaag/MogaSerial | dce4df5e814af7637f4fd7388e26b07ba2092441 | [
"MIT"
] | null | null | null | MogaSerial_MFC/MogaSerialDlg.cpp | kvanderlaag/MogaSerial | dce4df5e814af7637f4fd7388e26b07ba2092441 | [
"MIT"
] | null | null | null | /*
Moga serial to vJoy interface
Copyright (c) Jake Montgomery. All rights reserved.
THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
PURPOSE.
Module Name:
MogaSerialDlg.cpp
Abstract:
MFC GUI implementation for the Moga serial to vJoy interface program.
Revision History:
1.5.0 - Support for the SCP driver added.
1.3.0 - Settings saved to registry.
1.2.0 - Message callbacks and debug switch added. First public release.
1.1.x - Trigger mode switch added. Tooltips and status messages added.
1.0.x - Test builds and experimentation.
*/
#include "stdafx.h"
#include "MogaSerial.h"
#include "MogaSerialDlg.h"
#include "windowsx.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
const UINT WM_TASKBARCREATED = ::RegisterWindowMessage(_T("TaskbarCreated"));
//---------------------------------------------------------------------------
// CMogaSerialDlg - Constructor and data mapping
CMogaSerialDlg::CMogaSerialDlg(CWnd* pParent /*=NULL*/)
: CDialogEx(CMogaSerialDlg::IDD, pParent)
, m_iDriver(0)
, m_iTriggerMode(0)
{
m_hIcon = AfxGetApp()->LoadIcon(IDI_MOGA);
}
void CMogaSerialDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Control(pDX, IDC_BTLIST, c_BTList);
DDX_Control(pDX, IDC_BTREFRESH, c_BTRefresh);
DDX_Control(pDX, IDC_VJOYID, c_vJoyID);
DDX_Control(pDX, IDC_RADIO1, c_Drv1);
DDX_Control(pDX, IDC_RADIO2, c_Drv2);
DDX_Control(pDX, IDC_RADIOA, c_TModeA);
DDX_Control(pDX, IDC_RADIOB, c_TModeB);
DDX_Control(pDX, IDC_RADIOC, c_TModeC);
DDX_Check(pDX, IDC_CHECK1, m_dpadAsAnalog);
DDX_Check(pDX, IDC_CHECK2, m_swapL2R2andL3R3);
DDX_Radio(pDX, IDC_RADIO1, m_iDriver);
DDX_Control(pDX, IDC_OUTPUT, c_Output);
DDX_Control(pDX, IDC_STOPGO, c_StopGo);
DDX_Control(pDX, IDC_DEBUG, c_Debug);
DDX_Control(pDX, IDC_ABOUT, c_About);
}
BEGIN_MESSAGE_MAP(CMogaSerialDlg, CDialogEx)
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_MESSAGE(WM_BT_DISCOVERY_DONE, UpdateBTList_Done)
ON_MESSAGE(WM_MOGAHANDLER_DONE, MogaHandler_Done)
ON_MESSAGE(WM_MOGAHANDLER_MSG, MogaHandler_Msg)
ON_MESSAGE(MYWM_NOTIFYICON, onTrayNotify)
ON_REGISTERED_MESSAGE(WM_TASKBARCREATED, OnTaskBarCreated)
ON_BN_CLICKED(IDC_BTREFRESH, &CMogaSerialDlg::OnBnClickedBtrefresh)
ON_BN_CLICKED(IDC_STOPGO, &CMogaSerialDlg::OnBnClickedStopGo)
ON_BN_CLICKED(IDC_DEBUG, &CMogaSerialDlg::OnBnClickedDebug)
ON_BN_CLICKED(IDC_ABOUT, &CMogaSerialDlg::OnBnClickedAbout)
ON_WM_DESTROY()
ON_WM_SYSCOMMAND()
ON_BN_CLICKED(IDC_RADIO1, &CMogaSerialDlg::OnBnClickedRadio1)
ON_BN_CLICKED(IDC_RADIO2, &CMogaSerialDlg::OnBnClickedRadio2)
END_MESSAGE_MAP()
//---------------------------------------------------------------------------
// CMogaSerialDlg - Init and system control functions
BLUETOOTH_INFO CMogaSerialDlg::BTList_info[25];
BOOL CMogaSerialDlg::OnInitDialog()
{
CDialogEx::OnInitDialog();
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, true); // Set big icon
SetIcon(m_hIcon, false); // Set small icon
// Sync visual styles, mfcbuttons look old otherwise
CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerWindows));
c_Output.SetMargins(1,1);
//Create the ToolTip control
InitToolTips();
// Get quick bluetooth device list from system cache
UpdateBTList_Start(false);
// populate listbox vaules, read and validate registry defaults
int a,b,c,d,dpadAnalog,swapTriggers;
swscanf_s(DefaultRegString,_T("%d,%d,%d,%d,%d,%d"),&a,&b,&c,&d,&dpadAnalog,&swapTriggers);
if (a < 0 || a >= c_BTList.GetCount()) a = 0;
if (b < 0 || b >= c_vJoyID.GetCount()) b = 0;
if (c < 0 || c > 2) c = 0;
if (d < 0 || d > 1) d = 0;
if (dpadAnalog < 0 || dpadAnalog > 1) dpadAnalog = 0;
if (swapTriggers < 0 || swapTriggers > 1) dpadAnalog = 0;
c_BTList.SetCurSel(a);
c_vJoyID.SetCurSel(b);
m_iTriggerMode = c;
m_iDriver = d;
UpdateData(false);
m_Moga.m_ScpHandle = INVALID_HANDLE_VALUE;
m_Moga.m_KeepGoing = false;
m_Moga.m_Debug = false;
Moga_thread_running = false;
if (m_iDriver == 0)
vJoyOK = vJoyCheck();
if (m_iDriver == 1)
ScpOK = ScpCheck();
InitSysTrayIcon();
return true; // return TRUE unless you set the focus to a control
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void CMogaSerialDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialogEx::OnPaint();
}
}
// The system calls this function to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CMogaSerialDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
BOOL CMogaSerialDlg::PreTranslateMessage(MSG* pMsg)
{
m_ToolTip.RelayEvent(pMsg);
if (pMsg->wParam == VK_ESCAPE) // Intercept close-on-escape
return true;
return CDialog::PreTranslateMessage(pMsg);
}
void CMogaSerialDlg::InitToolTips()
{
if(m_ToolTip.Create(this))
{
// Add tool tips to the controls, either by hard coded string
// or using the string table resource
m_ToolTip.SetMaxTipWidth(SHRT_MAX);
m_ToolTip.AddTool( GetDlgItem(IDC_BTLIST), IDS_BT_TOOLTIP);
m_ToolTip.AddTool( GetDlgItem(IDC_BTREFRESH), IDS_BTR_TOOLTIP);
m_ToolTip.AddTool( GetDlgItem(IDC_VJOYID), IDS_VID_TOOLTIP);
m_ToolTip.AddTool( GetDlgItem(IDC_RADIO1), IDS_VJOY_TOOLTIP);
m_ToolTip.AddTool( GetDlgItem(IDC_RADIO2), IDS_SCP_TOOLTIP);
m_ToolTip.AddTool( GetDlgItem(IDC_RADIOA), IDS_TA_TOOLTIP);
m_ToolTip.AddTool( GetDlgItem(IDC_RADIOB), IDS_TB_TOOLTIP);
m_ToolTip.AddTool( GetDlgItem(IDC_RADIOC), IDS_TC_TOOLTIP);
m_ToolTip.AddTool( GetDlgItem(IDC_STOPGO), IDS_GO_TOOLTIP);
m_ToolTip.AddTool( GetDlgItem(IDC_ABOUT), IDS_ABT_TOOLTIP);
m_ToolTip.AddTool( GetDlgItem(IDC_DEBUG), IDS_DBG_TOOLTIP);
m_ToolTip.Activate(true);
}
}
void CMogaSerialDlg::InitSysTrayIcon()
{
m_trayIcon.cbSize = sizeof(NOTIFYICONDATA);
m_trayIcon.hWnd = this->GetSafeHwnd();
m_trayIcon.uID = IDI_MOGA;
m_trayIcon.uCallbackMessage = MYWM_NOTIFYICON;
m_trayIcon.uFlags = NIF_MESSAGE|NIF_ICON|NIF_TIP;
m_trayIcon.hIcon = LoadIcon(AfxGetInstanceHandle(), MAKEINTRESOURCE (IDI_MOGA));
lstrcpyn(m_trayIcon.szTip, _T("MogaSerial"), sizeof(m_trayIcon.szTip));
Shell_NotifyIcon(NIM_ADD, &m_trayIcon);
}
// Ensure the vJoy driver exists, and compare versions.
bool CMogaSerialDlg::vJoyCheck()
{
CString s;
bool retVal = true;
WORD VerDll, VerDrv;
if (!vJoyEnabled())
retVal = false;
if (!retVal)
{
s.LoadString(IDS_VJOY_FAIL);
c_Output.SetWindowText(s);
LockControls();
}
else if (!DriverMatch(&VerDll, &VerDrv))
{
s.FormatMessage(IDS_VJOY_DLL_NOTICE, VerDrv, VerDll);
c_Output.SetWindowText(s);
}
return retVal;
}
// Ensure the SCP virtual device driver exists, then get a handle to it.
// Most of this is extracted from working source code in other projects. Unfortunately with
// no documentation for SCP, I'm not sure if there's any better way of doing this.
// {F679F562-3164-42CE-A4DB-E7DDBE723909} - GUID for main SCP device interface
bool CMogaSerialDlg::ScpCheck()
{
GUID Target = { 0xF679F562, 0x3164, 0x42CE, {0xA4, 0xDB, 0xE7, 0xDD, 0xBE, 0x72, 0x39, 0x09}};
wchar_t Path[256];
char *buf;
bool retVal = true;
DWORD bufferSize;
HDEVINFO deviceInfoSet;
SP_DEVICE_INTERFACE_DATA DeviceInterfaceData;
PSP_DEVICE_INTERFACE_DETAIL_DATA pDeviceDetailData;
SP_DEVINFO_DATA DevInfoData;
wcscpy_s(Path, _T(""));
if (m_Moga.m_ScpHandle != INVALID_HANDLE_VALUE)
{
CloseHandle(m_Moga.m_ScpHandle);
m_Moga.m_ScpHandle = INVALID_HANDLE_VALUE;
}
DeviceInterfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
DevInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
deviceInfoSet = SetupDiGetClassDevs(&Target, 0, 0, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
if (SetupDiEnumDeviceInterfaces(deviceInfoSet, 0, &Target, 0, &DeviceInterfaceData))
{
SetupDiGetDeviceInterfaceDetail(deviceInfoSet, &DeviceInterfaceData, 0, 0, &bufferSize, &DevInfoData);
buf = (char *)malloc(sizeof(char) * bufferSize);
pDeviceDetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA)buf;
pDeviceDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);
if (SetupDiGetDeviceInterfaceDetail(deviceInfoSet, &DeviceInterfaceData, pDeviceDetailData, bufferSize, &bufferSize, &DevInfoData))
wcscpy_s(Path, pDeviceDetailData->DevicePath);
free(buf);
}
if (wcscmp(Path, _T("")) != 0)
m_Moga.m_ScpHandle = CreateFile(Path, (GENERIC_WRITE | GENERIC_READ), FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, 0);
if (m_Moga.m_ScpHandle == INVALID_HANDLE_VALUE)
{
CString s;
s.LoadString(IDS_SCP_FAIL);
c_Output.SetWindowText(s);
retVal = false;
}
return retVal;
}
//---------------------------------------------------------------------------
// CMogaSerialDlg - Dialog control handling functions
void CMogaSerialDlg::LockControls()
{
bool BTlist = true, BTrefresh = true,
drivers = true, options = true, stopgo = true;
if (!vJoyOK || m_iDriver == 1)
{
options = false;
}
if (BT_thread_running)
{
BTlist = false;
BTrefresh = false;
stopgo = false;
}
if (Moga_thread_running)
{
BTlist = false;
BTrefresh = false;
options = false;
drivers = false;
}
if ((c_BTList.GetCount() == 0) ||
((m_iDriver == 0 && !vJoyOK)) || ((m_iDriver == 1 && !ScpOK)) ||
((Moga_thread_running == true) && (Moga_first_connect == true)) ||
((Moga_thread_running == true) && (m_Moga.m_KeepGoing == false)))
{
stopgo = false;
}
c_BTList.EnableWindow(BTlist);
c_BTRefresh.EnableWindow(BTrefresh);
c_Drv1.EnableWindow(drivers);
c_Drv2.EnableWindow(drivers);
c_vJoyID.EnableWindow(options);
c_TModeA.EnableWindow(options);
c_TModeB.EnableWindow(options);
c_TModeC.EnableWindow(options);
c_StopGo.EnableWindow(stopgo);
}
void CMogaSerialDlg::UnlockStopGOButton()
{
Moga_first_connect = false;
c_StopGo.SetImage(IDB_MOGAL);
LockControls();
}
LRESULT CMogaSerialDlg::onTrayNotify(WPARAM wParam,LPARAM lParam)
{
switch ((UINT) lParam)
{
case WM_LBUTTONUP:
case WM_RBUTTONUP:
ShowWindow(SW_RESTORE);
break;
}
return TRUE;
}
// Show/hide the application entry on the task bar
void CMogaSerialDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
switch(nID & 0xFFF0)
{
case SC_MINIMIZE:
ShowWindow(SW_HIDE);
break;
default:
CDialogEx::OnSysCommand(nID, lParam);
}
}
// Replace the systray icon if Explorer is restarted
LRESULT CMogaSerialDlg::OnTaskBarCreated(WPARAM wp, LPARAM lp)
{
InitSysTrayIcon();
return 0;
}
void CMogaSerialDlg::OnDestroy()
{
Shell_NotifyIcon(NIM_DELETE,&m_trayIcon);
CDialogEx::OnDestroy();
}
void CMogaSerialDlg::OnBnClickedRadio1()
{
vJoyOK = vJoyCheck();
UpdateData(true);
LockControls();
}
void CMogaSerialDlg::OnBnClickedRadio2()
{
ScpOK = ScpCheck();
UpdateData(true);
LockControls();
}
// Bluetooth refresh button was clicked.
void CMogaSerialDlg::OnBnClickedBtrefresh()
{
UpdateBTList_Start(true);
}
void CMogaSerialDlg::OnBnClickedAbout()
{
CDialog aboutDlg(IDD_ABOUT);
aboutDlg.DoModal();
}
void CMogaSerialDlg::OnBnClickedDebug()
{
if (!m_Moga.m_Debug)
{
m_Moga.m_Debug = true;
c_Debug.SetImage(IDB_DEBUG2);
}
else
{
CString s;
m_Moga.m_Debug = false;
c_Debug.SetImage(IDB_DEBUG);
s.FormatMessage(IDS_MOGA_DEBUG);
c_Output.SetWindowText(s);
}
}
void CMogaSerialDlg::OnBnClickedStopGo()
{
if (Moga_thread_running == false)
MogaHandler_Start();
else
{
CString s;
s.FormatMessage(IDS_MOGA_STOPPING);
c_Output.SetWindowText(s);
m_Moga.m_KeepGoing = false;
LockControls();
}
}
//---------------------------------------------------------------------------
// Worker thread functions
// Framework functions for the primary Moga controller thread
// Lock relevant controls, populate the config values, then spawn the worker thread
void CMogaSerialDlg::MogaHandler_Start()
{
int BTList_idx;
m_Moga.m_KeepGoing = true;
Moga_thread_running = true;
Moga_first_connect = true;
LockControls();
MogaHandler_Msg(0, 0);
UpdateData(true);
BTList_idx = c_BTList.GetItemData(c_BTList.GetCurSel());
m_Moga.m_hGUI = this->m_hWnd;
m_Moga.m_vJoyInt = c_vJoyID.GetCurSel() + 1;
m_Moga.m_Addr = BTList_info[BTList_idx].addr;
if (m_iDriver == 0)
m_Moga.m_TriggerMode = m_iTriggerMode;
else
m_Moga.m_TriggerMode = 1;
// some fun compatibility hacks for swapping trigger button numbers
// and using the dpad as the left analog stick for older games.
m_dpadAsAnalog == BST_CHECKED ?
m_Moga.m_dpadAsAnalog = true
: m_Moga.m_dpadAsAnalog = false;
m_swapL2R2andL3R3 == BST_CHECKED ?
m_Moga.m_swapL2R2andL3R3 = true
: m_Moga.m_swapL2R2andL3R3 = false;
m_Moga.m_Driver = m_iDriver;
DefaultRegString.Format(_T("%d,%d,%d,%d,&d,&d"), BTList_idx, c_vJoyID.GetCurSel(),
m_iTriggerMode, m_iDriver, m_dpadAsAnalog, m_swapL2R2andL3R3);
AfxBeginThread(MogaHandler_Launch, &m_Moga);
}
UINT CMogaSerialDlg::MogaHandler_Launch(LPVOID pParam)
{
CMogaSerialMain *pMoga = (CMogaSerialMain *)pParam;
UINT retVal;
retVal = pMoga->Moga_Main();
::PostMessage(pMoga->m_hGUI, WM_MOGAHANDLER_DONE, retVal, 0);
return 0;
}
// Callback when the Moga control thread finishes.
LRESULT CMogaSerialDlg::MogaHandler_Done(WPARAM wParam, LPARAM lParam)
{
CString s;
if (m_Moga.m_KeepGoing == false)
{
s.FormatMessage(IDS_MOGA_DONE);
c_Output.SetWindowText(s);
}
Moga_thread_running = false;
c_StopGo.SetImage(IDB_MOGA);
LockControls();
return 0;
}
// Give time for the Moga control thread to finish after the main dialog is closed.
void CMogaSerialDlg::StopMogaThread()
{
// MSG uMsg;
m_Moga.m_KeepGoing = false;
// The following check wasn't working. Sleeping a few seconds works just as well.
// while (Moga_thread_running)
// {
// if (PeekMessage(&uMsg, this->m_hWnd, 0, 0, PM_REMOVE) > 0)
// DispatchMessage(&uMsg);
// }
Sleep(3000);
}
// Moga message handler callback.
LRESULT CMogaSerialDlg::MogaHandler_Msg(WPARAM wParam, LPARAM lParam)
{
static CString s(""), s2(""), s3("");
s3 = s2;
s2 = s;
switch ((int)wParam)
{
case IDS_VJOY_ERR1:
s.FormatMessage(IDS_VJOY_ERR1, m_Moga.m_vJoyInt);
break;
case IDS_VJOY_ERR2:
s.FormatMessage(IDS_VJOY_ERR2, m_Moga.m_vJoyInt);
break;
case IDS_VJOY_ERR3:
s.FormatMessage(IDS_VJOY_ERR3, m_Moga.m_vJoyInt);
break;
case IDS_VJOY_ERR4:
s.FormatMessage(IDS_VJOY_ERR4, m_Moga.m_vJoyInt);
break;
case IDS_VJOY_SUCCESS:
s.FormatMessage(IDS_VJOY_SUCCESS, (wchar_t *)GetvJoySerialNumberString(), m_Moga.m_vJoyInt);
break;
case IDS_SCP_ERR1:
s.FormatMessage(IDS_SCP_ERR1, m_Moga.m_Addr);
break;
case IDS_SCP_ERR2:
s.FormatMessage(IDS_SCP_ERR2);
break;
case IDS_SCP_XNUM:
s.FormatMessage(IDS_SCP_XNUM, m_Moga.m_CID);
break;
case IDS_MOGA_CONNECTING:
s.FormatMessage(IDS_MOGA_CONNECTING, BTList_info[c_BTList.GetItemData(c_BTList.GetCurSel())].name);
break;
case IDS_MOGA_DISCONNECT:
s.FormatMessage(IDS_MOGA_DISCONNECT);
break;
case IDS_MOGA_CONNECTED:
s.FormatMessage(IDS_MOGA_CONNECTED);
if (Moga_first_connect == true)
UnlockStopGOButton();
break;
case IDS_MOGA_RECONNECT:
s.FormatMessage(IDS_MOGA_RECONNECT);
if (Moga_first_connect == true)
UnlockStopGOButton();
break;
case IDS_MOGA_DEBUG:
s = CString((char *)lParam);
s2 = s3 = "";
break;
default:
s = s2 = s3 = "";
}
c_Output.SetWindowText(s + "\r\n" + s2 + "\r\n" + s3);
return 0;
}
// Framework functions for populating the bluetooth device list
// Lock relevant controls, then spawn the worker thread
void CMogaSerialDlg::UpdateBTList_Start(BOOL refresh)
{
CString s;
BLUETOOTH_THREAD_PARAMS *btt_p = new BLUETOOTH_THREAD_PARAMS;
btt_p->pThis = this;
btt_p->refresh = refresh;
BT_thread_running = true;
LockControls();
if (btt_p->refresh)
{
s.FormatMessage(IDS_BTSCAN_START);
c_Output.SetWindowText(s);
}
while (c_BTList.DeleteString(0) > 0); // clear the bluetooth list
AfxBeginThread(BTAddressDiscovery, btt_p);
}
// Callback when the bluetooth discovery worker thread finishes.
// Fill the fill the list box with data and unlock the controls.
// wParam - On success, number of devices found. On failure, WSAGetLastError().
LRESULT CMogaSerialDlg::UpdateBTList_Done(WPARAM wParam, LPARAM lParam)
{
int i, j;
CString BT_Line;
BLUETOOTH_THREAD_PARAMS *btt_p = (BLUETOOTH_THREAD_PARAMS *)lParam;
if (btt_p->update)
{
for (i = 0; i < (int)wParam; i++)
{
BT_Line.Format(_T("%ls - %ls"), BTList_info[i].name, BTList_info[i].name2);
j = c_BTList.AddString(BT_Line);
c_BTList.SetItemData(j, i);
}
c_BTList.SetCurSel(0);
if (btt_p->refresh)
{
BT_Line.FormatMessage(IDS_BTSCAN_DONE);
c_Output.SetWindowText(BT_Line);
}
}
else
{
BT_Line.FormatMessage(IDS_BTSCAN_ERROR, (int)wParam);
c_Output.SetWindowText(BT_Line);
}
BT_thread_running = false;
LockControls();
delete btt_p;
return 0;
}
// Worker thread function ported from the console app.
// Scan the bluetooth device list and populate the data structure.
// Use cached list on program start, flush cache and re-query on button click.
UINT CMogaSerialDlg::BTAddressDiscovery(LPVOID pParam)
{
BLUETOOTH_THREAD_PARAMS *btt_p = (BLUETOOTH_THREAD_PARAMS *)pParam;
union {
CHAR buf[5000];
SOCKADDR_BTH _Unused_; // properly align buffer to BT_ADDR requirements
};
HANDLE hLookup;
LPWSAQUERYSET pwsaQuery;
DWORD dwSize, dwFlags = LUP_CONTAINERS, dwAddrSize;
int i = 0;
if (btt_p->refresh)
dwFlags = LUP_CONTAINERS | LUP_FLUSHCACHE;
// configure the queryset structure
pwsaQuery = (LPWSAQUERYSET) buf;
dwSize = sizeof(buf);
ZeroMemory(pwsaQuery, dwSize);
pwsaQuery->dwSize = dwSize;
pwsaQuery->dwNameSpace = NS_BTH; // namespace MUST be NS_BTH for bluetooth queries
// initialize searching procedure
if (WSALookupServiceBegin(pwsaQuery, dwFlags, &hLookup) != SOCKET_ERROR)
{
// iterate through all found devices, returning name and address.
// if they have over 25 paired devices on a gaming machine, they're crazy.
while (WSALookupServiceNext(hLookup, LUP_RETURN_NAME | LUP_RETURN_ADDR, &dwSize, pwsaQuery) == 0 && i < 25)
{
wcsncpy_s(BTList_info[i].name, pwsaQuery->lpszServiceInstanceName, sizeof(BTList_info[i].name));
BTList_info[i].addr = ((SOCKADDR_BTH *)pwsaQuery->lpcsaBuffer->RemoteAddr.lpSockaddr)->btAddr;
dwAddrSize = sizeof(BTList_info[i].name2);
WSAAddressToString(pwsaQuery->lpcsaBuffer->RemoteAddr.lpSockaddr, sizeof(SOCKADDR_BTH), NULL, (LPWSTR)BTList_info[i].name2, &dwAddrSize);
i++;
}
WSALookupServiceEnd(hLookup);
btt_p->update = true;
}
else
{
i = WSAGetLastError();
btt_p->update = false;
}
::PostMessage(btt_p->pThis->m_hWnd, WM_BT_DISCOVERY_DONE, i, (LPARAM)btt_p);
return 0;
} | 28.554765 | 176 | 0.704792 | [
"model"
] |
2bdef8511c39253a291ca8c08c509536d00645d7 | 10,339 | cpp | C++ | src/Illusion/Graphics/Instance.cpp | Simmesimme/illusion-3d | 48520d87ea0677bb8852b20bb6fbfbe1a49402d2 | [
"MIT"
] | 8 | 2019-12-05T15:57:23.000Z | 2022-01-19T19:37:23.000Z | src/Illusion/Graphics/Instance.cpp | Schneegans/illusion | 48520d87ea0677bb8852b20bb6fbfbe1a49402d2 | [
"MIT"
] | null | null | null | src/Illusion/Graphics/Instance.cpp | Schneegans/illusion | 48520d87ea0677bb8852b20bb6fbfbe1a49402d2 | [
"MIT"
] | 1 | 2019-01-15T10:35:13.000Z | 2019-01-15T10:35:13.000Z | ////////////////////////////////////////////////////////////////////////////////////////////////////
// //
// _) | | _) This code may be used and modified under the terms //
// | | | | | (_-< | _ \ \ of the MIT license. See the LICENSE file for details. //
// _| _| _| \_,_| ___/ _| \___/ _| _| Copyright (c) 2018-2019 Simon Schneegans //
// //
////////////////////////////////////////////////////////////////////////////////////////////////////
#include "Instance.hpp"
#include "../Core/Logger.hpp"
#include "../Core/Utils.hpp"
#include "PhysicalDevice.hpp"
#include "VulkanPtr.hpp"
#include <GLFW/glfw3.h>
#include <iostream>
#include <set>
#include <sstream>
namespace Illusion::Graphics {
namespace {
////////////////////////////////////////////////////////////////////////////////////////////////////
const std::vector<const char*> VALIDATION_LAYERS = {"VK_LAYER_LUNARG_standard_validation"};
////////////////////////////////////////////////////////////////////////////////////////////////////
bool glfwInitialized = false;
////////////////////////////////////////////////////////////////////////////////////////////////////
VkBool32 debugCallback(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
VkDebugUtilsMessageTypeFlagsEXT /*messageType*/,
const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData, void* /*pUserData*/) {
// In the error message, Vulkan objects are referred to by a hex-string of their handle. In order
// to improve the readability, we will try to replace each mention of a Vulkan object with the
// actual name of the object.
std::string message(pCallbackData->pMessage);
for (uint32_t i(0); i < pCallbackData->objectCount; ++i) {
if (pCallbackData->pObjects[i].pObjectName != nullptr) {
std::ostringstream address;
address << reinterpret_cast<void const*>(pCallbackData->pObjects[i].objectHandle);
std::string hexHandle = address.str();
std::string objectName = "\"" + std::string(pCallbackData->pObjects[i].pObjectName) + "\"";
if (Core::Utils::replaceString(message, hexHandle, objectName) == 0 && !objectName.empty()) {
message += " [" + objectName + "]";
}
}
}
if (messageSeverity == VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT) {
Core::Logger::trace() << message << std::endl;
} else if (messageSeverity == VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT) {
Core::Logger::message() << message << std::endl;
} else if (messageSeverity == VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT) {
Core::Logger::warning() << message << std::endl;
} else if (messageSeverity == VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) {
Core::Logger::error() << message << std::endl;
}
return 0u;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
bool checkValidationLayerSupport() {
for (auto const& layer : VALIDATION_LAYERS) {
bool layerFound = false;
for (auto const& property : vk::enumerateInstanceLayerProperties()) {
if (std::strcmp(layer, property.layerName) == 0) {
layerFound = true;
break;
}
}
if (!layerFound) {
return false;
}
}
return true;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
} // namespace
////////////////////////////////////////////////////////////////////////////////////////////////////
Instance::Instance(std::string const& name, Options const& options)
: Core::NamedObject(name)
, mOptions(options)
, mInstance(createInstance("Illusion", name))
, mDebugCallback(createDebugCallback()) {
for (auto const& vkPhysicalDevice : mInstance->enumeratePhysicalDevices()) {
mPhysicalDevices.push_back(
std::make_shared<PhysicalDevice>(*mInstance.get(), vkPhysicalDevice));
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
Instance::~Instance() = default;
////////////////////////////////////////////////////////////////////////////////////////////////////
PhysicalDeviceConstPtr Instance::getPhysicalDevice(
std::vector<std::string> const& extensions) const {
// loop through physical devices and choose a suitable one
for (auto const& physicalDevice : mPhysicalDevices) {
// check whether all required extensions are supported
auto availableExtensions = physicalDevice->enumerateDeviceExtensionProperties();
std::set<std::string> requiredExtensions(extensions.begin(), extensions.end());
for (auto const& extension : availableExtensions) {
requiredExtensions.erase(extension.extensionName);
}
if (!requiredExtensions.empty()) {
continue;
}
// all required extensions are supported - take this device!
return physicalDevice;
}
throw std::runtime_error("Failed to find a suitable vulkan device!");
}
////////////////////////////////////////////////////////////////////////////////////////////////////
vk::SurfaceKHRPtr Instance::createSurface(std::string const& name, GLFWwindow* window) const {
VkSurfaceKHR tmp;
if (mOptions.contains(OptionBits::eHeadlessMode)) {
throw std::runtime_error("Cannot create window surface in headless mode!");
}
if (glfwCreateWindowSurface(*mInstance, window, nullptr, &tmp) != VK_SUCCESS) {
throw std::runtime_error("Failed to create window surface!");
}
Core::Logger::traceCreation("vk::SurfaceKHR", name);
// copying instance to keep reference counting up until the surface is destroyed
auto instance = mInstance;
return VulkanPtr::create(vk::SurfaceKHR(tmp), [instance, name](vk::SurfaceKHR* obj) {
Core::Logger::traceDeletion("vk::SurfaceKHR", name);
instance->destroySurfaceKHR(*obj);
delete obj;
});
}
////////////////////////////////////////////////////////////////////////////////////////////////////
vk::InstancePtr Instance::getHandle() const {
return mInstance;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
vk::InstancePtr Instance::createInstance(std::string const& engine, std::string const& app) const {
if (!mOptions.contains(OptionBits::eHeadlessMode) && !glfwInitialized) {
if (glfwInit() == 0) {
throw std::runtime_error("Failed to initialize GLFW.");
}
glfwSetErrorCallback([](int /*error*/, const char* description) {
throw std::runtime_error("GLFW: " + std::string(description));
});
glfwInitialized = true;
}
if (mOptions.contains(OptionBits::eDebugMode) && !checkValidationLayerSupport()) {
throw std::runtime_error("Requested validation layers are not available!");
}
// app info
vk::ApplicationInfo appInfo;
appInfo.pApplicationName = app.c_str();
appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
appInfo.pEngineName = engine.c_str();
appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
appInfo.apiVersion = VK_API_VERSION_1_0;
// find required extensions
std::vector<const char*> extensions;
if (!mOptions.contains(OptionBits::eHeadlessMode)) {
unsigned int glfwExtensionCount = 0;
const char** glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount);
for (unsigned int i = 0; i < glfwExtensionCount; ++i) {
extensions.push_back(glfwExtensions[i]);
}
}
if (mOptions.contains(OptionBits::eDebugMode)) {
extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
}
// create instance
vk::InstanceCreateInfo info;
info.pApplicationInfo = &appInfo;
info.enabledExtensionCount = static_cast<int32_t>(extensions.size());
info.ppEnabledExtensionNames = extensions.data();
if (mOptions.contains(OptionBits::eDebugMode)) {
info.enabledLayerCount = static_cast<int32_t>(VALIDATION_LAYERS.size());
info.ppEnabledLayerNames = VALIDATION_LAYERS.data();
} else {
info.enabledLayerCount = 0;
}
Core::Logger::traceCreation("vk::Instance", getName());
auto name = getName();
return VulkanPtr::create(vk::createInstance(info), [name](vk::Instance* obj) {
Core::Logger::traceDeletion("vk::Instance", name);
obj->destroy();
delete obj;
});
}
////////////////////////////////////////////////////////////////////////////////////////////////////
vk::DebugUtilsMessengerEXTPtr Instance::createDebugCallback() const {
if (!mOptions.contains(OptionBits::eDebugMode)) {
return nullptr;
}
auto createCallback{reinterpret_cast<PFN_vkCreateDebugUtilsMessengerEXT>(
mInstance->getProcAddr("vkCreateDebugUtilsMessengerEXT"))};
vk::DebugUtilsMessengerCreateInfoEXT info;
info.messageSeverity = vk::DebugUtilsMessageSeverityFlagBitsEXT::eVerbose |
vk::DebugUtilsMessageSeverityFlagBitsEXT::eInfo |
vk::DebugUtilsMessageSeverityFlagBitsEXT::eWarning |
vk::DebugUtilsMessageSeverityFlagBitsEXT::eError;
info.messageType = vk::DebugUtilsMessageTypeFlagBitsEXT::eValidation |
vk::DebugUtilsMessageTypeFlagBitsEXT::ePerformance;
info.pfnUserCallback = debugCallback;
VkDebugUtilsMessengerEXT tmp;
if (createCallback(*mInstance, reinterpret_cast<VkDebugUtilsMessengerCreateInfoEXT*>(&info),
nullptr, &tmp) != 0) {
throw std::runtime_error("Failed to set up debug callback!");
}
auto name = "DebugCallback for " + getName();
Core::Logger::traceCreation("vk::DebugUtilsMessengerEXT", name);
auto instance = mInstance;
return VulkanPtr::create(
vk::DebugUtilsMessengerEXT(tmp), [instance, name](vk::DebugUtilsMessengerEXT* obj) {
auto destroyCallback = reinterpret_cast<PFN_vkDestroyDebugUtilsMessengerEXT>(
instance->getProcAddr("vkDestroyDebugUtilsMessengerEXT"));
Core::Logger::traceDeletion("vk::DebugUtilsMessengerEXT", name);
destroyCallback(*instance, *obj, nullptr);
delete obj;
});
}
////////////////////////////////////////////////////////////////////////////////////////////////////
} // namespace Illusion::Graphics
| 37.190647 | 100 | 0.578779 | [
"object",
"vector"
] |
2be937a7dd24d07d1d79f9475362533583ce8083 | 604 | cpp | C++ | tests/perf_unique_rolls.cpp | perim/libdicey | fd618b4bbc05cbafcdb5a388894789fafc99a1e9 | [
"MIT"
] | 4 | 2021-08-14T21:32:22.000Z | 2021-09-03T17:52:39.000Z | tests/perf_unique_rolls.cpp | perim/libdicey | fd618b4bbc05cbafcdb5a388894789fafc99a1e9 | [
"MIT"
] | null | null | null | tests/perf_unique_rolls.cpp | perim/libdicey | fd618b4bbc05cbafcdb5a388894789fafc99a1e9 | [
"MIT"
] | null | null | null | #include "dice.h"
#include <assert.h>
#include <stdio.h>
// test performance of the unique_rolls() call
int main(int argc, char **argv)
{
seed s = seed_random();
uint64_t sum = 0;
const std::vector<int> t { 1, 2, 3, 4 };
const roll_table* rt = roll_table_make(t);
int results[4];
for (int i = 1; i < 50000; i++)
{
// int unique_rolls(const roll_table* table, int count, int* results, luck_type rollee = luck_type::normal, int roll_weight = 0, int start_index = 0);
s.unique_rolls(rt, 4, results, luck_type::normal, 0, 0);
sum += results[0];
}
roll_table_free(rt);
return (int)sum * 0;
}
| 27.454545 | 152 | 0.662252 | [
"vector"
] |
2bead927915b87261c7c4f953e73a887751ec81a | 12,859 | cc | C++ | chrome/renderer/media/chrome_key_systems.cc | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | chrome/renderer/media/chrome_key_systems.cc | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | chrome/renderer/media/chrome_key_systems.cc | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2013 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 "chrome/renderer/media/chrome_key_systems.h"
#include <stddef.h>
#include <string>
#include <vector>
#include "base/command_line.h"
#include "base/containers/contains.h"
#include "base/containers/flat_set.h"
#include "base/logging.h"
#include "base/strings/string_split.h"
#include "base/strings/utf_string_conversions.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "chrome/renderer/chrome_render_thread_observer.h"
#include "components/cdm/renderer/external_clear_key_key_system_properties.h"
#include "components/cdm/renderer/widevine_key_system_properties.h"
#include "content/public/renderer/render_thread.h"
#include "media/base/decrypt_config.h"
#include "media/base/eme_constants.h"
#include "media/base/key_system_properties.h"
#include "media/cdm/cdm_capability.h"
#include "media/media_buildflags.h"
#include "third_party/widevine/cdm/buildflags.h"
#if defined(OS_ANDROID)
#include "components/cdm/renderer/android_key_systems.h"
#endif
#if BUILDFLAG(ENABLE_LIBRARY_CDMS)
#include "base/feature_list.h"
#include "content/public/renderer/key_system_support.h"
#include "media/base/media_switches.h"
#include "media/base/video_codecs.h"
#if BUILDFLAG(ENABLE_WIDEVINE)
#include "third_party/widevine/cdm/widevine_cdm_common.h" // nogncheck
// TODO(crbug.com/663554): Needed for WIDEVINE_CDM_MIN_GLIBC_VERSION.
// component updated CDM on all desktop platforms and remove this.
#include "widevine_cdm_version.h" // In SHARED_INTERMEDIATE_DIR. // nogncheck
#if BUILDFLAG(ENABLE_PLATFORM_HEVC) && BUILDFLAG(IS_CHROMEOS_ASH)
#include "ash/constants/ash_features.h"
#endif // BUILDFLAG(ENABLE_PLATFORM_HEVC) && BUILDFLAG(IS_CHROMEOS_ASH)
// The following must be after widevine_cdm_version.h.
#if defined(WIDEVINE_CDM_MIN_GLIBC_VERSION)
#include <gnu/libc-version.h>
#include "base/version.h"
#endif // defined(WIDEVINE_CDM_MIN_GLIBC_VERSION)
#endif // BUILDFLAG(ENABLE_WIDEVINE)
#endif // BUILDFLAG(ENABLE_LIBRARY_CDMS)
using media::EmeFeatureSupport;
using media::EmeSessionTypeSupport;
using media::KeySystemProperties;
using media::SupportedCodecs;
namespace {
#if BUILDFLAG(ENABLE_LIBRARY_CDMS)
// External Clear Key (used for testing).
void AddExternalClearKey(
std::vector<std::unique_ptr<KeySystemProperties>>* key_systems) {
static const char kExternalClearKeyKeySystem[] =
"org.chromium.externalclearkey";
// TODO(xhwang): Actually use `capability` to determine capabilities.
media::mojom::KeySystemCapabilityPtr capability;
if (!content::IsKeySystemSupported(kExternalClearKeyKeySystem, &capability)) {
DVLOG(1) << "External Clear Key not supported";
return;
}
key_systems->push_back(std::make_unique<cdm::ExternalClearKeyProperties>());
}
#if BUILDFLAG(ENABLE_WIDEVINE)
SupportedCodecs GetVP9Codecs(
const std::vector<media::VideoCodecProfile>& profiles) {
if (profiles.empty()) {
// If no profiles are specified, then all are supported.
return media::EME_CODEC_VP9_PROFILE0 | media::EME_CODEC_VP9_PROFILE2;
}
SupportedCodecs supported_vp9_codecs = media::EME_CODEC_NONE;
for (const auto& profile : profiles) {
switch (profile) {
case media::VP9PROFILE_PROFILE0:
supported_vp9_codecs |= media::EME_CODEC_VP9_PROFILE0;
break;
case media::VP9PROFILE_PROFILE2:
supported_vp9_codecs |= media::EME_CODEC_VP9_PROFILE2;
break;
default:
DVLOG(1) << "Unexpected " << GetCodecName(media::VideoCodec::kVP9)
<< " profile: " << GetProfileName(profile);
break;
}
}
return supported_vp9_codecs;
}
#if BUILDFLAG(ENABLE_PLATFORM_HEVC)
SupportedCodecs GetHevcCodecs(
const std::vector<media::VideoCodecProfile>& profiles) {
#if BUILDFLAG(IS_CHROMEOS_LACROS)
if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kLacrosEnablePlatformHevc)) {
return media::EME_CODEC_NONE;
}
#endif // BUILDFLAG(IS_CHROMEOS_LACROS)
// If no profiles are specified, then all are supported.
if (profiles.empty()) {
return media::EME_CODEC_HEVC_PROFILE_MAIN |
media::EME_CODEC_HEVC_PROFILE_MAIN10;
}
SupportedCodecs supported_hevc_codecs = media::EME_CODEC_NONE;
for (const auto& profile : profiles) {
switch (profile) {
case media::HEVCPROFILE_MAIN:
supported_hevc_codecs |= media::EME_CODEC_HEVC_PROFILE_MAIN;
break;
case media::HEVCPROFILE_MAIN10:
supported_hevc_codecs |= media::EME_CODEC_HEVC_PROFILE_MAIN10;
break;
default:
DVLOG(1) << "Unexpected " << GetCodecName(media::VideoCodec::kHEVC)
<< " profile: " << GetProfileName(profile);
break;
}
}
return supported_hevc_codecs;
}
#endif // BUILDFLAG(ENABLE_PLATFORM_HEVC)
SupportedCodecs GetSupportedCodecs(const media::CdmCapability& capability) {
SupportedCodecs supported_codecs = media::EME_CODEC_NONE;
for (const auto& codec : capability.audio_codecs) {
switch (codec) {
case media::AudioCodec::kOpus:
supported_codecs |= media::EME_CODEC_OPUS;
break;
case media::AudioCodec::kVorbis:
supported_codecs |= media::EME_CODEC_VORBIS;
break;
case media::AudioCodec::kFLAC:
supported_codecs |= media::EME_CODEC_FLAC;
break;
#if BUILDFLAG(USE_PROPRIETARY_CODECS)
case media::AudioCodec::kAAC:
supported_codecs |= media::EME_CODEC_AAC;
break;
#endif // BUILDFLAG(USE_PROPRIETARY_CODECS)
default:
DVLOG(1) << "Unexpected supported codec: " << GetCodecName(codec);
break;
}
}
// For compatibility with older CDMs different profiles are only used
// with some video codecs.
for (const auto& codec : capability.video_codecs) {
switch (codec.first) {
case media::VideoCodec::kVP8:
supported_codecs |= media::EME_CODEC_VP8;
break;
case media::VideoCodec::kVP9:
supported_codecs |= GetVP9Codecs(codec.second);
break;
case media::VideoCodec::kAV1:
supported_codecs |= media::EME_CODEC_AV1;
break;
#if BUILDFLAG(USE_PROPRIETARY_CODECS)
case media::VideoCodec::kH264:
supported_codecs |= media::EME_CODEC_AVC1;
break;
#endif // BUILDFLAG(USE_PROPRIETARY_CODECS)
#if BUILDFLAG(ENABLE_PLATFORM_HEVC)
case media::VideoCodec::kHEVC:
supported_codecs |= GetHevcCodecs(codec.second);
break;
#endif // BUILDFLAG(ENABLE_PLATFORM_HEVC)
default:
DVLOG(1) << "Unexpected supported codec: " << GetCodecName(codec.first);
break;
}
}
return supported_codecs;
}
// Returns persistent-license session support.
EmeSessionTypeSupport GetPersistentLicenseSupport(bool supported_by_the_cdm) {
// Do not support persistent-license if the process cannot persist data.
// TODO(crbug.com/457487): Have a better plan on this. See bug for details.
if (ChromeRenderThreadObserver::is_incognito_process()) {
DVLOG(2) << __func__ << ": Not supported in incognito process.";
return EmeSessionTypeSupport::NOT_SUPPORTED;
}
if (!supported_by_the_cdm) {
DVLOG(2) << __func__ << ": Not supported by the CDM.";
return EmeSessionTypeSupport::NOT_SUPPORTED;
}
// On ChromeOS, platform verification is similar to CDM host verification.
#if BUILDFLAG(ENABLE_CDM_HOST_VERIFICATION) || defined(OS_CHROMEOS)
bool cdm_host_verification_potentially_supported = true;
#else
bool cdm_host_verification_potentially_supported = false;
#endif
// If we are sure CDM host verification is NOT supported, we should not
// support persistent-license.
if (!cdm_host_verification_potentially_supported) {
DVLOG(2) << __func__ << ": Not supported without CDM host verification.";
return EmeSessionTypeSupport::NOT_SUPPORTED;
}
#if defined(OS_CHROMEOS)
// On ChromeOS, platform verification (similar to CDM host verification)
// requires identifier to be allowed.
// TODO(jrummell): Currently the ChromeOS CDM does not require storage ID
// to support persistent license. Update this logic when the new CDM requires
// storage ID.
return EmeSessionTypeSupport::SUPPORTED_WITH_IDENTIFIER;
#elif BUILDFLAG(ENABLE_CDM_STORAGE_ID)
// On other platforms, we require storage ID to support persistent license.
return EmeSessionTypeSupport::SUPPORTED;
#else
// Storage ID not implemented, so no support for persistent license.
DVLOG(2) << __func__ << ": Not supported without CDM storage ID.";
return EmeSessionTypeSupport::NOT_SUPPORTED;
#endif // defined(OS_CHROMEOS)
}
void AddWidevine(
std::vector<std::unique_ptr<KeySystemProperties>>* key_systems) {
#if defined(WIDEVINE_CDM_MIN_GLIBC_VERSION)
base::Version glibc_version(gnu_get_libc_version());
DCHECK(glibc_version.IsValid());
if (glibc_version < base::Version(WIDEVINE_CDM_MIN_GLIBC_VERSION))
return;
#endif // defined(WIDEVINE_CDM_MIN_GLIBC_VERSION)
media::mojom::KeySystemCapabilityPtr capability;
if (!content::IsKeySystemSupported(kWidevineKeySystem, &capability)) {
DVLOG(1) << "Widevine CDM is not currently available.";
return;
}
// Codecs and encryption schemes.
SupportedCodecs codecs = media::EME_CODEC_NONE;
SupportedCodecs hw_secure_codecs = media::EME_CODEC_NONE;
base::flat_set<::media::EncryptionScheme> encryption_schemes;
base::flat_set<::media::EncryptionScheme> hw_secure_encryption_schemes;
bool cdm_supports_persistent_license = false;
if (capability->sw_secure_capability) {
codecs = GetSupportedCodecs(capability->sw_secure_capability.value());
encryption_schemes = capability->sw_secure_capability->encryption_schemes;
if (!base::Contains(capability->sw_secure_capability->session_types,
media::CdmSessionType::kTemporary)) {
DVLOG(1) << "Temporary sessions must be supported.";
return;
}
cdm_supports_persistent_license =
base::Contains(capability->sw_secure_capability->session_types,
media::CdmSessionType::kPersistentLicense);
}
if (capability->hw_secure_capability) {
hw_secure_codecs =
GetSupportedCodecs(capability->hw_secure_capability.value());
hw_secure_encryption_schemes =
capability->hw_secure_capability->encryption_schemes;
if (!base::Contains(capability->hw_secure_capability->session_types,
media::CdmSessionType::kTemporary)) {
DVLOG(1) << "Temporary sessions must be supported.";
return;
}
// TODO(b/186035558): With a single flag we can't distinguish persistent
// session support between software and hardware CDMs. This should be
// fixed so that if there is both a software and a hardware CDM, persistent
// session support can be different between the versions.
}
// Robustness.
using Robustness = cdm::WidevineKeySystemProperties::Robustness;
auto max_audio_robustness = Robustness::SW_SECURE_CRYPTO;
auto max_video_robustness = Robustness::SW_SECURE_DECODE;
#if defined(OS_CHROMEOS)
// On ChromeOS, we support HW_SECURE_ALL even without hardware secure codecs.
// See WidevineKeySystemProperties::GetRobustnessConfigRule().
max_audio_robustness = Robustness::HW_SECURE_ALL;
max_video_robustness = Robustness::HW_SECURE_ALL;
#else
if (media::IsHardwareSecureDecryptionEnabled()) {
max_audio_robustness = Robustness::HW_SECURE_CRYPTO;
max_video_robustness = Robustness::HW_SECURE_ALL;
}
#endif
auto persistent_license_support =
GetPersistentLicenseSupport(cdm_supports_persistent_license);
// Others.
auto persistent_state_support = EmeFeatureSupport::REQUESTABLE;
auto distinctive_identifier_support = EmeFeatureSupport::NOT_SUPPORTED;
#if defined(OS_CHROMEOS) || defined(OS_WIN)
distinctive_identifier_support = EmeFeatureSupport::REQUESTABLE;
#endif
key_systems->emplace_back(new cdm::WidevineKeySystemProperties(
codecs, encryption_schemes, hw_secure_codecs,
hw_secure_encryption_schemes, max_audio_robustness, max_video_robustness,
persistent_license_support, persistent_state_support,
distinctive_identifier_support));
}
#endif // BUILDFLAG(ENABLE_WIDEVINE)
#endif // BUILDFLAG(ENABLE_LIBRARY_CDMS)
} // namespace
void AddChromeKeySystems(
std::vector<std::unique_ptr<KeySystemProperties>>* key_systems) {
#if BUILDFLAG(ENABLE_LIBRARY_CDMS)
if (base::FeatureList::IsEnabled(media::kExternalClearKeyForTesting))
AddExternalClearKey(key_systems);
#if BUILDFLAG(ENABLE_WIDEVINE)
AddWidevine(key_systems);
#endif // BUILDFLAG(ENABLE_WIDEVINE)
#endif // BUILDFLAG(ENABLE_LIBRARY_CDMS)
#if defined(OS_ANDROID)
cdm::AddAndroidWidevine(key_systems);
#endif // defined(OS_ANDROID)
}
| 36.427762 | 80 | 0.743526 | [
"vector"
] |
2beddbecb023e2390e652eb30ee302d788763e35 | 4,149 | cpp | C++ | src/DEX/Method.cpp | rafael-santiago/LIEF | f230094d5877dd63d40915dc944c53c2a4be5ed9 | [
"Apache-2.0"
] | 1 | 2022-02-26T00:28:52.000Z | 2022-02-26T00:28:52.000Z | src/DEX/Method.cpp | rafael-santiago/LIEF | f230094d5877dd63d40915dc944c53c2a4be5ed9 | [
"Apache-2.0"
] | null | null | null | src/DEX/Method.cpp | rafael-santiago/LIEF | f230094d5877dd63d40915dc944c53c2a4be5ed9 | [
"Apache-2.0"
] | null | null | null | /* Copyright 2017 - 2022 R. Thomas
* Copyright 2017 - 2022 Quarkslab
*
* 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 "logging.hpp"
#include "LIEF/DEX/Method.hpp"
#include "LIEF/DEX/Prototype.hpp"
#include "LIEF/DEX/Class.hpp"
#include "LIEF/DEX/hash.hpp"
#include "LIEF/DEX/enums.hpp"
#include "LIEF/DEX/EnumToString.hpp"
#include <numeric>
#include <utility>
namespace LIEF {
namespace DEX {
Method::Method(const Method&) = default;
Method& Method::operator=(const Method&) = default;
Method::Method() = default;
Method::Method(std::string name, Class* parent) :
name_{std::move(name)},
parent_{parent}
{}
const std::string& Method::name() const {
return name_;
}
uint64_t Method::code_offset() const {
return code_offset_;
}
const Method::bytecode_t& Method::bytecode() const {
return bytecode_;
}
bool Method::has_class() const {
return parent_ != nullptr;
}
const Class* Method::cls() const {
return parent_;
}
Class* Method::cls() {
return const_cast<Class*>(static_cast<const Method*>(this)->cls());
}
size_t Method::index() const {
return original_index_;
}
void Method::insert_dex2dex_info(uint32_t pc, uint32_t index) {
dex2dex_info_.emplace(pc, index);
}
const dex2dex_method_info_t& Method::dex2dex_info() const {
return dex2dex_info_;
}
bool Method::is_virtual() const {
return is_virtual_;
}
void Method::set_virtual(bool v) {
is_virtual_ = v;
}
bool Method::has(ACCESS_FLAGS f) const {
return (access_flags_ & f) != 0u;
}
Method::access_flags_list_t Method::access_flags() const {
Method::access_flags_list_t flags;
std::copy_if(std::begin(access_flags_list),
std::end(access_flags_list),
std::back_inserter(flags),
[this] (ACCESS_FLAGS f) { return has(f); });
return flags;
}
const Prototype* Method::prototype() const {
return prototype_;
}
Prototype* Method::prototype() {
return const_cast<Prototype*>(static_cast<const Method*>(this)->prototype());
}
void Method::accept(Visitor& visitor) const {
visitor.visit(*this);
}
bool Method::operator==(const Method& rhs) const {
if (this == &rhs) {
return true;
}
size_t hash_lhs = Hash::hash(*this);
size_t hash_rhs = Hash::hash(rhs);
return hash_lhs == hash_rhs;
}
bool Method::operator!=(const Method& rhs) const {
return !(*this == rhs);
}
std::ostream& operator<<(std::ostream& os, const Method& method) {
const auto* proto = method.prototype();
if (!proto) {
os << method.name() << "()";
return os;
}
Prototype::it_const_params ps = proto->parameters_type();
std::string pretty_cls_name;
if (const auto* cls = method.cls()) {
pretty_cls_name = cls->fullname();
}
if (!pretty_cls_name.empty()) {
pretty_cls_name = pretty_cls_name.substr(1, pretty_cls_name.size() - 2);
std::replace(std::begin(pretty_cls_name), std::end(pretty_cls_name), '/', '.');
}
Method::access_flags_list_t aflags = method.access_flags();
std::string flags_str = std::accumulate(
std::begin(aflags), std::end(aflags),
std::string{},
[] (const std::string& l, ACCESS_FLAGS r) {
std::string str = to_string(r);
std::transform(std::begin(str), std::end(str), std::begin(str), ::tolower);
return l.empty() ? str : l + " " + str;
});
if (!flags_str.empty()) {
os << flags_str << " ";
}
os << proto->return_type()
<< " "
<< pretty_cls_name << "->" << method.name();
os << "(";
for (size_t i = 0; i < ps.size(); ++i) {
if (i > 0) {
os << ", ";
}
os << ps[i] << " p" << std::dec << i;
}
os << ")";
return os;
}
Method::~Method() = default;
}
}
| 23.178771 | 83 | 0.657749 | [
"transform"
] |
9200e3a2297ec268a43fb9c50a2118ec1028eb41 | 3,397 | hpp | C++ | ext/src/java/util/stream/Stream.hpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | ext/src/java/util/stream/Stream.hpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | ext/src/java/util/stream/Stream.hpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | // Generated from /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/rt.jar
#pragma once
#include <fwd-POI.hpp>
#include <java/lang/fwd-POI.hpp>
#include <java/util/fwd-POI.hpp>
#include <java/util/function/fwd-POI.hpp>
#include <java/util/stream/fwd-POI.hpp>
#include <java/util/stream/BaseStream.hpp>
struct java::util::stream::Stream
: public virtual BaseStream
{
virtual bool allMatch(::java::util::function::Predicate* predicate) = 0;
virtual bool anyMatch(::java::util::function::Predicate* predicate) = 0;
static Stream_Builder* builder();
virtual ::java::lang::Object* collect(Collector* collector) = 0;
virtual ::java::lang::Object* collect(::java::util::function::Supplier* supplier, ::java::util::function::BiConsumer* accumulator, ::java::util::function::BiConsumer* combiner) = 0;
static Stream* concat(Stream* a, Stream* b);
virtual int64_t count() = 0;
virtual Stream* distinct() = 0;
static Stream* empty();
virtual Stream* filter(::java::util::function::Predicate* predicate) = 0;
virtual ::java::util::Optional* findAny() = 0;
virtual ::java::util::Optional* findFirst() = 0;
virtual Stream* flatMap(::java::util::function::Function* mapper) = 0;
virtual DoubleStream* flatMapToDouble(::java::util::function::Function* mapper) = 0;
virtual IntStream* flatMapToInt(::java::util::function::Function* mapper) = 0;
virtual LongStream* flatMapToLong(::java::util::function::Function* mapper) = 0;
virtual void forEach(::java::util::function::Consumer* action) = 0;
virtual void forEachOrdered(::java::util::function::Consumer* action) = 0;
static Stream* generate(::java::util::function::Supplier* s);
static Stream* iterate(::java::lang::Object* seed, ::java::util::function::UnaryOperator* f);
virtual Stream* limit(int64_t maxSize) = 0;
virtual Stream* map(::java::util::function::Function* mapper) = 0;
virtual DoubleStream* mapToDouble(::java::util::function::ToDoubleFunction* mapper) = 0;
virtual IntStream* mapToInt(::java::util::function::ToIntFunction* mapper) = 0;
virtual LongStream* mapToLong(::java::util::function::ToLongFunction* mapper) = 0;
virtual ::java::util::Optional* max(::java::util::Comparator* comparator) = 0;
virtual ::java::util::Optional* min(::java::util::Comparator* comparator) = 0;
virtual bool noneMatch(::java::util::function::Predicate* predicate) = 0;
static Stream* of(::java::lang::Object* t);
static Stream* of(::java::lang::ObjectArray* values);
virtual Stream* peek(::java::util::function::Consumer* action) = 0;
virtual ::java::util::Optional* reduce(::java::util::function::BinaryOperator* accumulator) = 0;
virtual ::java::lang::Object* reduce(::java::lang::Object* identity, ::java::util::function::BinaryOperator* accumulator) = 0;
virtual ::java::lang::Object* reduce(::java::lang::Object* identity, ::java::util::function::BiFunction* accumulator, ::java::util::function::BinaryOperator* combiner) = 0;
virtual Stream* skip(int64_t n) = 0;
virtual Stream* sorted() = 0;
virtual Stream* sorted(::java::util::Comparator* comparator) = 0;
virtual ::java::lang::ObjectArray* toArray_() = 0;
virtual ::java::lang::ObjectArray* toArray_(::java::util::function::IntFunction* generator) = 0;
// Generated
static ::java::lang::Class *class_();
};
| 57.576271 | 185 | 0.691198 | [
"object"
] |
9201402f1ecac7bfc578bc22c4773a60e9a9480e | 5,473 | hpp | C++ | include/VROSC/PercussionNode.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | null | null | null | include/VROSC/PercussionNode.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | null | null | null | include/VROSC/PercussionNode.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | 1 | 2022-03-30T21:07:35.000Z | 2022-03-30T21:07:35.000Z | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: VROSC.IntNode
#include "VROSC/IntNode.hpp"
// Including type: VROSC.MidiPercussion
#include "VROSC/MidiPercussion.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Type namespace: VROSC
namespace VROSC {
// Forward declaring type: PercussionNode
class PercussionNode;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::VROSC::PercussionNode);
DEFINE_IL2CPP_ARG_TYPE(::VROSC::PercussionNode*, "VROSC", "PercussionNode");
// Type namespace: VROSC
namespace VROSC {
// Size: 0x34
#pragma pack(push, 1)
// Autogenerated type: VROSC.PercussionNode
// [TokenAttribute] Offset: FFFFFFFF
class PercussionNode : public ::VROSC::IntNode {
public:
public:
// private VROSC.MidiPercussion _percussionValue
// Size: 0x4
// Offset: 0x30
::VROSC::MidiPercussion percussionValue;
// Field size check
static_assert(sizeof(::VROSC::MidiPercussion) == 0x4);
public:
// Get instance field reference: private VROSC.MidiPercussion _percussionValue
[[deprecated("Use field access instead!")]] ::VROSC::MidiPercussion& dyn__percussionValue();
// public VROSC.MidiPercussion get_PercussionValue()
// Offset: 0xADE824
::VROSC::MidiPercussion get_PercussionValue();
// public System.Void set_PercussionValue(VROSC.MidiPercussion value)
// Offset: 0xADE82C
void set_PercussionValue(::VROSC::MidiPercussion value);
// public System.Void .ctor()
// Offset: 0xADE87C
// Implemented from: VROSC.IntNode
// Base method: System.Void IntNode::.ctor()
// Base method: System.Void Node::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static PercussionNode* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::VROSC::PercussionNode::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<PercussionNode*, creationType>()));
}
// protected override System.Void OnValidate()
// Offset: 0xADE838
// Implemented from: VROSC.IntNode
// Base method: System.Void IntNode::OnValidate()
void OnValidate();
// protected override System.Int32 SetValueInRange(System.Int32 value)
// Offset: 0xADE854
// Implemented from: VROSC.IntNode
// Base method: System.Int32 IntNode::SetValueInRange(System.Int32 value)
int SetValueInRange(int value);
}; // VROSC.PercussionNode
#pragma pack(pop)
static check_size<sizeof(PercussionNode), 48 + sizeof(::VROSC::MidiPercussion)> __VROSC_PercussionNodeSizeCheck;
static_assert(sizeof(PercussionNode) == 0x34);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: VROSC::PercussionNode::get_PercussionValue
// Il2CppName: get_PercussionValue
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::VROSC::MidiPercussion (VROSC::PercussionNode::*)()>(&VROSC::PercussionNode::get_PercussionValue)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(VROSC::PercussionNode*), "get_PercussionValue", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: VROSC::PercussionNode::set_PercussionValue
// Il2CppName: set_PercussionValue
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::PercussionNode::*)(::VROSC::MidiPercussion)>(&VROSC::PercussionNode::set_PercussionValue)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("VROSC", "MidiPercussion")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(VROSC::PercussionNode*), "set_PercussionValue", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: VROSC::PercussionNode::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: VROSC::PercussionNode::OnValidate
// Il2CppName: OnValidate
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::PercussionNode::*)()>(&VROSC::PercussionNode::OnValidate)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(VROSC::PercussionNode*), "OnValidate", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: VROSC::PercussionNode::SetValueInRange
// Il2CppName: SetValueInRange
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (VROSC::PercussionNode::*)(int)>(&VROSC::PercussionNode::SetValueInRange)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(VROSC::PercussionNode*), "SetValueInRange", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
| 48.433628 | 174 | 0.734332 | [
"vector"
] |
921049e4f09bde2f3d10f9a2c7e728468bd7d134 | 3,463 | cpp | C++ | genetics/eval/gpuimage/ImageEvaluator.cpp | crest01/ShapeGenetics | 7321f6484be668317ad763c0ca5e4d6cbfef8cd1 | [
"MIT"
] | 18 | 2017-04-26T13:53:43.000Z | 2021-05-29T03:55:27.000Z | genetics/eval/gpuimage/ImageEvaluator.cpp | crest01/ShapeGenetics | 7321f6484be668317ad763c0ca5e4d6cbfef8cd1 | [
"MIT"
] | null | null | null | genetics/eval/gpuimage/ImageEvaluator.cpp | crest01/ShapeGenetics | 7321f6484be668317ad763c0ca5e4d6cbfef8cd1 | [
"MIT"
] | 2 | 2017-10-17T10:32:01.000Z | 2019-11-11T07:23:54.000Z | /*
* VolumeEvaluator.cpp
*
* Created on: Dec 3, 2015
* Author: Karl Haubenwallner
*/
#include "ImageEvaluator.h"
#include "ToTextureRendererInstanced.h"
#include "Smoothstep.h"
#include "Grammar_IF.h"
#include "GeometryBufferInstanced.h"
namespace PGA {
namespace GPU {
ImageEvaluator::ImageEvaluator(ProceduralAlgorithm* base) :
_good_pixels(0),
_bad_pixels(0),
_algo(base),
_renderer(nullptr),
_target_initialized(false),
_calc_time(0),
_prod_time(0)
{ }
ImageEvaluator::~ImageEvaluator()
{
if (_renderer)
delete _renderer;
}
void ImageEvaluator::init(ProceduralAlgorithm* base)
{
_conf = _algo->get<ImageEvaluationConf*>("evaluation");
_base = _algo->get<AlgorithmConf*>("base");
_grammar = _algo->get<GrammarConf*>("grammar");
_genome = _algo->get<GenomeConf*>("genome");
_geometry = _algo->get<GeometryConf*>("geometry");
_population = _algo->get<PopulationConf*>("population");
_renderer = new ToTextureRendererInstanced(_conf->getTargetFilename(), _conf->getPixels().x, _conf->getPixels().y);
float fov, znear, zfar, phi, theta, radius;
math::float3 lookat;
_conf->getCameraParameters(fov, znear, zfar, phi, theta, radius, lookat);
_renderer->setupCamera(fov, znear, zfar, phi, theta, radius, lookat);
std::cout << "Image based Evaluation: " << std::endl;
std::cout << "\tgood weight: " << _conf->getGoodWeight() << std::endl;
std::cout << "\tbad weight: " << _conf->getBadWeight() << std::endl;
std::cout << "\tlength weight: " << _conf->getLengthWeight() << std::endl;
std::cout << "\ttarget pixels: " << _renderer->getTargetPixels() << std::endl;
}
float ImageEvaluator::calcRating(Genome_IF* genome)
{
//std::cout << "calc rating, current " << genome->getEvalPoints();
auto t0 = std::chrono::high_resolution_clock::now();
// if (_renderer) {
// delete _renderer;
// }
//
// _renderer = new ToTextureRenderer(_conf->getTargetFilename(), _conf->getPixels().x, _conf->getPixels().y);
float fov, znear, zfar, phi, theta, radius;
math::float3 lookat;
_conf->getCameraParameters(fov, znear, zfar, phi, theta, radius, lookat);
_renderer->setupCamera(fov, znear, zfar, phi, theta, radius, lookat);
_grammar->impl()->createGeometry(genome);
auto t1 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> time_span = std::chrono::duration_cast<std::chrono::duration<double>>(t1 - t0);
_prod_time = time_span.count();
int good_pixels = 0;
int bad_pixels = 0;
int target_pixels = _renderer->getTargetPixels();
_renderer->compare(_geometry->getInstancedObjectMeshBuffer(), good_pixels, bad_pixels, _base->getCurrentGeneration());
float good_rating = _conf->getGoodWeight() * smoothstep(0.0f, target_pixels, good_pixels);
float bad_rating = _conf->getBadWeight() * smoothstep(0.0f, target_pixels, bad_pixels);
float length_rating = _conf->getLengthWeight() * smoothstep(_genome->getMinimalLength(), _genome->getMaximalLength(), genome->length());
auto t2 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> time_span_2 = std::chrono::duration_cast<std::chrono::duration<double>>(t2 - t1);
_calc_time = time_span_2.count();
float rating = good_rating - bad_rating - length_rating;
// std::cout << "rating: " << rating << " (good: " << good_pixels << ", bad: " << bad_pixels << ", length: "<< genome->length() <<", target pixels: " << target_pixels << ")" << std::endl;
return rating;
}
} // namespace CPU
} // namespace PGA
| 29.347458 | 187 | 0.702281 | [
"geometry"
] |
92125acaf450989e631b008e9a7862417e4f6185 | 8,570 | cpp | C++ | SDK/Plugin/Transaction/Payload/OutputPayload/PayloadVote.cpp | fakecoinbase/elastosslashElastos.ELA.SPV.Cpp | b18eaeaa96e6c9049e3527c6e8b22a571aba35f6 | [
"MIT"
] | 11 | 2018-08-01T02:01:34.000Z | 2019-09-15T23:31:40.000Z | SDK/Plugin/Transaction/Payload/OutputPayload/PayloadVote.cpp | chenyukaola/Elastos.ELA.SPV.Cpp | 57b5264d4eb259439dd85aefc0455389551ee3cf | [
"MIT"
] | 51 | 2018-07-16T09:41:14.000Z | 2020-01-08T03:40:34.000Z | SDK/Plugin/Transaction/Payload/OutputPayload/PayloadVote.cpp | yiyaowen/ela-spvwallet-desktop | 475095ee3c1f49bc7e23c5c341e959568d4f72b9 | [
"MIT"
] | 26 | 2018-07-12T02:34:46.000Z | 2022-02-07T07:08:54.000Z | // Copyright (c) 2012-2018 The Elastos Open Source Project
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "PayloadVote.h"
#include <Common/Utils.h>
#include <Common/Log.h>
#include <Common/ErrorChecker.h>
namespace Elastos {
namespace ElaWallet {
CandidateVotes::CandidateVotes() : _votes(0) {
}
CandidateVotes::CandidateVotes(const bytes_t &candidate, const BigInt &votes) :
_candidate(candidate), _votes(votes) {
}
CandidateVotes::~CandidateVotes() {
}
const bytes_t &CandidateVotes::GetCandidate() const {
return _candidate;
}
const BigInt &CandidateVotes::GetVotes() const {
return _votes;
}
void CandidateVotes::SetVotes(uint64_t votes) {
_votes = votes;
}
void CandidateVotes::Serialize(ByteStream &ostream, uint8_t version) const {
ostream.WriteVarBytes(_candidate);
if (version >= VOTE_PRODUCER_CR_VERSION) {
ostream.WriteUint64(_votes.getUint64());
}
}
bool CandidateVotes::Deserialize(const ByteStream &istream, uint8_t version) {
if (!istream.ReadVarBytes(_candidate)) {
Log::error("CandidateVotes deserialize candidate fail");
return false;
}
if (version >= VOTE_PRODUCER_CR_VERSION) {
uint64_t votes = 0;
if (!istream.ReadUint64(votes)) {
Log::error("CandidateVotes deserialize votes fail");
return false;
}
_votes.setUint64(votes);
}
return true;
}
nlohmann::json CandidateVotes::ToJson(uint8_t version) const {
nlohmann::json j;
j["Candidate"] = _candidate.getHex();
if (version >= VOTE_PRODUCER_CR_VERSION) {
j["Votes"] = _votes.getDec();
}
return j;
}
void CandidateVotes::FromJson(const nlohmann::json &j, uint8_t version) {
_candidate.setHex(j["Candidate"].get<std::string>());
if (version >= VOTE_PRODUCER_CR_VERSION) {
_votes.setDec(j["Votes"].get<std::string>());
}
}
VoteContent::VoteContent() : _type(Delegate) {
}
VoteContent::VoteContent(Type t) :
_type(t) {
}
VoteContent::VoteContent(Type t, const std::vector<CandidateVotes> &c) : _type(t), _candidates(c) {
}
VoteContent::~VoteContent() {
}
void VoteContent::AddCandidate(const CandidateVotes &candidateVotes) {
_candidates.push_back(candidateVotes);
}
const VoteContent::Type &VoteContent::GetType() const {
return _type;
}
std::string VoteContent::GetTypeString() const {
if (_type == VoteContent::CRC) {
return "CRC";
} else if (_type == VoteContent::Delegate) {
return "Delegate";
} else if (_type == VoteContent::CRCProposal) {
return "CRCProposal";
} else if (_type == VoteContent::CRCImpeachment) {
return "CRCImpeachment";
}
return "Unknow";
}
void VoteContent::SetCandidateVotes(const std::vector<CandidateVotes> &candidateVotes) {
_candidates = candidateVotes;
}
const std::vector<CandidateVotes> &VoteContent::GetCandidateVotes() const {
return _candidates;
}
void VoteContent::SetAllCandidateVotes(uint64_t votes) {
for (size_t i = 0; i < _candidates.size(); ++i) {
_candidates[i].SetVotes(votes);
}
}
BigInt VoteContent::GetMaxVoteAmount() const {
BigInt max = 0;
for (std::vector<CandidateVotes>::const_iterator it = _candidates.cbegin(); it != _candidates.cend(); ++it)
if (max < (*it).GetVotes())
max = (*it).GetVotes();
return max;
}
BigInt VoteContent::GetTotalVoteAmount() const {
BigInt total = 0;
for (std::vector<CandidateVotes>::const_iterator it = _candidates.cbegin(); it != _candidates.cend(); ++it)
total += (*it).GetVotes();
return total;
}
void VoteContent::Serialize(ByteStream &ostream, uint8_t version) const {
ostream.WriteUint8(_type);
ostream.WriteVarUint(_candidates.size());
for (size_t i = 0; i < _candidates.size(); ++i) {
_candidates[i].Serialize(ostream, version);
}
}
bool VoteContent::Deserialize(const ByteStream &istream, uint8_t version) {
uint8_t type = 0;
if (!istream.ReadUint8(type)) {
Log::error("VoteContent deserialize type error");
}
_type = Type(type);
uint64_t size = 0;
if (!istream.ReadVarUint(size)) {
Log::error("VoteContent deserialize candidates count error");
return false;
}
_candidates.resize(size);
for (size_t i = 0; i < size; ++i) {
if (!_candidates[i].Deserialize(istream, version)) {
Log::error("VoteContent deserialize candidates error");
return false;
}
}
return true;
}
nlohmann::json VoteContent::ToJson(uint8_t version) const {
nlohmann::json j;
j["Type"] = _type;
std::vector<nlohmann::json> candidates;
for (size_t i = 0; i < _candidates.size(); ++i) {
candidates.push_back(_candidates[i].ToJson(version));
}
j["Candidates"] = candidates;
return j;
}
void VoteContent::FromJson(const nlohmann::json &j, uint8_t version) {
uint8_t type = j["Type"].get<uint8_t>();
_type = Type(type);
std::vector<nlohmann::json> candidates = j["Candidates"];
_candidates.resize(candidates.size());
for (size_t i = 0; i < candidates.size(); ++i) {
_candidates[i].FromJson(candidates[i], version);
}
}
PayloadVote::PayloadVote(uint8_t version) :
_version(version) {
}
PayloadVote::PayloadVote(const std::vector<VoteContent> &voteContents, uint8_t version) :
_content(voteContents),
_version(version) {
}
PayloadVote::PayloadVote(const PayloadVote &payload) {
operator=(payload);
}
PayloadVote::~PayloadVote() {
}
void PayloadVote::SetVoteContent(const std::vector<VoteContent> &voteContent) {
_content = voteContent;
}
const std::vector<VoteContent> &PayloadVote::GetVoteContent() const {
return _content;
}
uint8_t PayloadVote::Version() const {
return _version;
}
size_t PayloadVote::EstimateSize() const {
ByteStream stream;
size_t size = 0;
size += 1;
size += stream.WriteVarUint(_content.size());
for (std::vector<VoteContent>::const_iterator vc = _content.cbegin(); vc != _content.cend(); ++vc) {
size += 1;
size += stream.WriteVarUint((*vc).GetCandidateVotes().size());
const std::vector<CandidateVotes> &candidateVotes = (*vc).GetCandidateVotes();
std::vector<CandidateVotes>::const_iterator cv;
for (cv = candidateVotes.cbegin(); cv != candidateVotes.cend(); ++cv) {
size += stream.WriteVarUint((*cv).GetCandidate().size());
size += (*cv).GetCandidate().size();
if (_version >= VOTE_PRODUCER_CR_VERSION) {
size += stream.WriteVarUint((*cv).GetVotes().getUint64());
}
}
}
return size;
}
void PayloadVote::Serialize(ByteStream &ostream) const {
ostream.WriteUint8(_version);
ostream.WriteVarUint(_content.size());
for (size_t i = 0; i < _content.size(); ++i) {
_content[i].Serialize(ostream, _version);
}
}
bool PayloadVote::Deserialize(const ByteStream &istream) {
if (!istream.ReadUint8(_version)) {
Log::error("payload vote deserialize version error");
return false;
}
uint64_t contentCount = 0;
if (!istream.ReadVarUint(contentCount)) {
Log::error("payload vote deserialize content count error");
return false;
}
_content.resize(contentCount);
for (size_t i = 0; i < contentCount; ++i) {
if (!_content[i].Deserialize(istream, _version)) {
Log::error("payload vote deserialize content error");
return false;
}
}
return true;
}
nlohmann::json PayloadVote::ToJson() const {
nlohmann::json j;
j["Version"] = _version;
std::vector<nlohmann::json> voteContent;
for (size_t i = 0; i < _content.size(); ++i) {
voteContent.push_back(_content[i].ToJson(_version));
}
j["VoteContent"] = voteContent;
return j;
}
void PayloadVote::FromJson(const nlohmann::json &j) {
_version = j["Version"];
std::vector<nlohmann::json> voteContent = j["VoteContent"];
_content.resize(voteContent.size());
for (size_t i = 0; i < voteContent.size(); ++i) {
_content[i].FromJson(voteContent[i], _version);
}
}
IOutputPayload &PayloadVote::operator=(const IOutputPayload &payload) {
try {
const PayloadVote &payloadVote = dynamic_cast<const PayloadVote &>(payload);
operator=(payloadVote);
} catch (const std::bad_cast &e) {
Log::error("payload is not instance of PayloadVote");
}
return *this;
}
PayloadVote &PayloadVote::operator=(const PayloadVote &payload) {
_version = payload._version;
_content = payload._content;
return *this;
}
}
}
| 25.430267 | 110 | 0.666628 | [
"vector"
] |
921f54d466a53d610f28c9d27282dc2e3b970549 | 11,093 | cc | C++ | test/cctest/test-api-accessors.cc | dumganhar/v8_fork | 49ff8c1d2044b640c5907b91093cb0866bb23647 | [
"BSD-3-Clause"
] | null | null | null | test/cctest/test-api-accessors.cc | dumganhar/v8_fork | 49ff8c1d2044b640c5907b91093cb0866bb23647 | [
"BSD-3-Clause"
] | null | null | null | test/cctest/test-api-accessors.cc | dumganhar/v8_fork | 49ff8c1d2044b640c5907b91093cb0866bb23647 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2015 the V8 project 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 "test/cctest/cctest.h"
#include "include/v8-experimental.h"
#include "include/v8.h"
#include "src/api.h"
#include "src/objects-inl.h"
namespace i = v8::internal;
static void CppAccessor42(const v8::FunctionCallbackInfo<v8::Value>& info) {
info.GetReturnValue().Set(42);
}
static void CppAccessor41(const v8::FunctionCallbackInfo<v8::Value>& info) {
info.GetReturnValue().Set(41);
}
v8::experimental::FastAccessorBuilder* FastAccessor(v8::Isolate* isolate) {
auto builder = v8::experimental::FastAccessorBuilder::New(isolate);
builder->ReturnValue(builder->IntegerConstant(41));
return builder;
}
TEST(FastAccessors) {
v8::Isolate* isolate = CcTest::isolate();
v8::HandleScope scope(isolate);
LocalContext env;
// We emulate Embedder-created DOM Node instances. Specifically:
// - 'parent': FunctionTemplate ~= DOM Node superclass
// - 'child': FunctionTemplate ~= a specific DOM node type, like a <div />
//
// We'll install both a C++-based and a JS-based accessor on the parent,
// and expect it to be callable on the child.
// Setup the parent template ( =~ DOM Node w/ accessors).
v8::Local<v8::FunctionTemplate> parent = v8::FunctionTemplate::New(isolate);
{
auto signature = v8::Signature::New(isolate, parent);
// cpp accessor as "firstChild":
parent->PrototypeTemplate()->SetAccessorProperty(
v8_str("firstChild"),
v8::FunctionTemplate::New(isolate, CppAccessor42,
v8::Local<v8::Value>(), signature));
// JS accessor as "firstChildRaw":
parent->PrototypeTemplate()->SetAccessorProperty(
v8_str("firstChildRaw"),
v8::FunctionTemplate::NewWithFastHandler(
isolate, CppAccessor41, FastAccessor(isolate),
v8::Local<v8::Value>(), signature));
}
// Setup child object ( =~ a specific DOM Node, e.g. a <div> ).
// Also, make a creation function on the global object, so we can access it
// in a test.
v8::Local<v8::FunctionTemplate> child = v8::FunctionTemplate::New(isolate);
child->Inherit(parent);
CHECK(env->Global()
->Set(env.local(), v8_str("Node"),
child->GetFunction(env.local()).ToLocalChecked())
.IsJust());
// Setup done: Let's test it:
// The simple case: Run it once.
ExpectInt32("var n = new Node(); n.firstChild", 42);
ExpectInt32("var n = new Node(); n.firstChildRaw", 41);
// Run them in a loop. This will likely trigger the optimizing compiler:
ExpectInt32(
"var m = new Node(); "
"var sum = 0; "
"for (var i = 0; i < 10; ++i) { "
" sum += m.firstChild; "
" sum += m.firstChildRaw; "
"}; "
"sum;",
10 * (42 + 41));
// Obtain the accessor and call it via apply on the Node:
ExpectInt32(
"var n = new Node(); "
"var g = Object.getOwnPropertyDescriptor("
" n.__proto__.__proto__, 'firstChild')['get']; "
"g.apply(n);",
42);
ExpectInt32(
"var n = new Node(); "
"var g = Object.getOwnPropertyDescriptor("
" n.__proto__.__proto__, 'firstChildRaw')['get']; "
"g.apply(n);",
41);
ExpectInt32(
"var n = new Node();"
"var g = Object.getOwnPropertyDescriptor("
" n.__proto__.__proto__, 'firstChildRaw')['get'];"
"try {"
" var f = { firstChildRaw: '51' };"
" g.apply(f);"
"} catch(e) {"
" 31415;"
"}",
31415);
}
// The goal is to avoid the callback.
static void UnreachableCallback(
const v8::FunctionCallbackInfo<v8::Value>& info) {
UNREACHABLE();
}
TEST(CachedAccessor) {
// Crankshaft support for fast accessors is not implemented; crankshafted
// code uses the slow accessor which breaks this test's expectations.
v8::internal::FLAG_always_opt = false;
LocalContext env;
v8::Isolate* isolate = env->GetIsolate();
v8::HandleScope scope(isolate);
// Create 'foo' class, with a hidden property.
v8::Local<v8::ObjectTemplate> foo = v8::ObjectTemplate::New(isolate);
v8::Local<v8::Private> priv =
v8::Private::ForApi(isolate, v8_str("Foo#draft"));
foo->SetAccessorProperty(v8_str("draft"), v8::FunctionTemplate::NewWithCache(
isolate, UnreachableCallback,
priv, v8::Local<v8::Value>()));
// Create 'obj', instance of 'foo'.
v8::Local<v8::Object> obj = foo->NewInstance(env.local()).ToLocalChecked();
// Install the private property on the instance.
CHECK(obj->SetPrivate(isolate->GetCurrentContext(), priv,
v8::Undefined(isolate))
.FromJust());
CHECK(env->Global()->Set(env.local(), v8_str("obj"), obj).FromJust());
// Access cached accessor.
ExpectUndefined("obj.draft");
// Set hidden property.
CHECK(obj->SetPrivate(isolate->GetCurrentContext(), priv,
v8_str("Shhh, I'm private!"))
.FromJust());
ExpectString("obj.draft", "Shhh, I'm private!");
// Stress the accessor to use the IC.
ExpectString(
"var result = '';"
"for (var i = 0; i < 10; ++i) { "
" result = obj.draft; "
"} "
"result; ",
"Shhh, I'm private!");
}
TEST(CachedAccessorCrankshaft) {
i::FLAG_allow_natives_syntax = true;
// v8::internal::FLAG_always_opt = false;
LocalContext env;
v8::Isolate* isolate = env->GetIsolate();
v8::HandleScope scope(isolate);
// Create 'foo' class, with a hidden property.
v8::Local<v8::ObjectTemplate> foo = v8::ObjectTemplate::New(isolate);
v8::Local<v8::Private> priv =
v8::Private::ForApi(isolate, v8_str("Foo#draft"));
// Install the private property on the template.
// foo->SetPrivate(priv, v8::Undefined(isolate));
foo->SetAccessorProperty(v8_str("draft"), v8::FunctionTemplate::NewWithCache(
isolate, UnreachableCallback,
priv, v8::Local<v8::Value>()));
// Create 'obj', instance of 'foo'.
v8::Local<v8::Object> obj = foo->NewInstance(env.local()).ToLocalChecked();
// Install the private property on the instance.
CHECK(obj->SetPrivate(isolate->GetCurrentContext(), priv,
v8::Undefined(isolate))
.FromJust());
CHECK(env->Global()->Set(env.local(), v8_str("obj"), obj).FromJust());
// Access surrogate accessor.
ExpectUndefined("obj.draft");
// Set hidden property.
CHECK(obj->SetPrivate(env.local(), priv, v8::Integer::New(isolate, 123))
.FromJust());
// Test ICs.
CompileRun(
"function f() {"
" var x;"
" for (var i = 0; i < 100; i++) {"
" x = obj.draft;"
" }"
" return x;"
"}");
ExpectInt32("f()", 123);
// Reset hidden property.
CHECK(obj->SetPrivate(env.local(), priv, v8::Integer::New(isolate, 456))
.FromJust());
// Test Crankshaft.
CompileRun("%OptimizeFunctionOnNextCall(f);");
ExpectInt32("f()", 456);
CHECK(obj->SetPrivate(env.local(), priv, v8::Integer::New(isolate, 456))
.FromJust());
// Test non-global ICs.
CompileRun(
"function g() {"
" var x = obj;"
" var r = 0;"
" for (var i = 0; i < 100; i++) {"
" r = x.draft;"
" }"
" return r;"
"}");
ExpectInt32("g()", 456);
// Reset hidden property.
CHECK(obj->SetPrivate(env.local(), priv, v8::Integer::New(isolate, 789))
.FromJust());
// Test non-global access in Crankshaft.
CompileRun("%OptimizeFunctionOnNextCall(g);");
ExpectInt32("g()", 789);
}
TEST(CachedAccessorOnGlobalObject) {
i::FLAG_allow_natives_syntax = true;
LocalContext env;
v8::Isolate* isolate = env->GetIsolate();
v8::HandleScope scope(isolate);
v8::Local<v8::FunctionTemplate> templ =
v8::FunctionTemplate::New(CcTest::isolate());
v8::Local<v8::ObjectTemplate> object_template = templ->InstanceTemplate();
v8::Local<v8::Private> priv =
v8::Private::ForApi(isolate, v8_str("Foo#draft"));
object_template->SetAccessorProperty(
v8_str("draft"),
v8::FunctionTemplate::NewWithCache(isolate, UnreachableCallback, priv,
v8::Local<v8::Value>()));
v8::Local<v8::Context> ctx =
v8::Context::New(CcTest::isolate(), nullptr, object_template);
v8::Local<v8::Object> obj = ctx->Global();
// Install the private property on the instance.
CHECK(obj->SetPrivate(isolate->GetCurrentContext(), priv,
v8::Undefined(isolate))
.FromJust());
{
v8::Context::Scope context_scope(ctx);
// Access surrogate accessor.
ExpectUndefined("draft");
// Set hidden property.
CHECK(obj->SetPrivate(env.local(), priv, v8::Integer::New(isolate, 123))
.FromJust());
// Test ICs.
CompileRun(
"function f() {"
" var x;"
" for (var i = 0; i < 100; i++) {"
" x = draft;"
" }"
" return x;"
"}");
ExpectInt32("f()", 123);
// Reset hidden property.
CHECK(obj->SetPrivate(env.local(), priv, v8::Integer::New(isolate, 456))
.FromJust());
// Test Crankshaft.
CompileRun("%OptimizeFunctionOnNextCall(f);");
ExpectInt32("f()", 456);
CHECK(obj->SetPrivate(env.local(), priv, v8::Integer::New(isolate, 456))
.FromJust());
// Test non-global ICs.
CompileRun(
"var x = this;"
"function g() {"
" var r = 0;"
" for (var i = 0; i < 100; i++) {"
" r = x.draft;"
" }"
" return r;"
"}");
ExpectInt32("g()", 456);
// Reset hidden property.
CHECK(obj->SetPrivate(env.local(), priv, v8::Integer::New(isolate, 789))
.FromJust());
// Test non-global access in Crankshaft.
CompileRun("%OptimizeFunctionOnNextCall(g);");
ExpectInt32("g()", 789);
}
}
namespace {
static void Setter(v8::Local<v8::String> name, v8::Local<v8::Value> value,
const v8::PropertyCallbackInfo<void>& info) {}
}
// Re-declaration of non-configurable accessors should throw.
TEST(RedeclareAccessor) {
v8::HandleScope scope(CcTest::isolate());
LocalContext env;
v8::Local<v8::FunctionTemplate> templ =
v8::FunctionTemplate::New(CcTest::isolate());
v8::Local<v8::ObjectTemplate> object_template = templ->InstanceTemplate();
object_template->SetAccessor(
v8_str("foo"), NULL, Setter, v8::Local<v8::Value>(),
v8::AccessControl::DEFAULT, v8::PropertyAttribute::DontDelete);
v8::Local<v8::Context> ctx =
v8::Context::New(CcTest::isolate(), nullptr, object_template);
// Declare function.
v8::Local<v8::String> code = v8_str("function foo() {};");
v8::TryCatch try_catch(CcTest::isolate());
v8::Script::Compile(ctx, code).ToLocalChecked()->Run(ctx).IsEmpty();
CHECK(try_catch.HasCaught());
}
| 30.475275 | 79 | 0.6011 | [
"object"
] |
921f84fc57de68a01a07b9d616fab2b618956e09 | 15,750 | cc | C++ | caffe2/video/bef_video/video_io.cc | KevinKecc/caffe2 | a2b6c6e2f0686358a84277df65e9489fb7d9ddb2 | [
"Apache-2.0"
] | null | null | null | caffe2/video/bef_video/video_io.cc | KevinKecc/caffe2 | a2b6c6e2f0686358a84277df65e9489fb7d9ddb2 | [
"Apache-2.0"
] | null | null | null | caffe2/video/bef_video/video_io.cc | KevinKecc/caffe2 | a2b6c6e2f0686358a84277df65e9489fb7d9ddb2 | [
"Apache-2.0"
] | 23 | 2018-04-13T10:47:31.000Z | 2021-05-06T08:38:06.000Z | /**
* Copyright (c) 2016-present, Facebook, Inc.
*
* 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 "caffe2/video/video_io.h"
#include <random>
#include <string>
#include "caffe2/core/logging.h"
#include "caffe2/video/video_decoder.h"
namespace caffe2 {
void ImageChannelToBuffer(const cv::Mat* img, float* buffer, int c) {
int idx = 0;
for (int h = 0; h < img->rows; ++h) {
for (int w = 0; w < img->cols; ++w) {
buffer[idx++] = static_cast<float>(img->at<cv::Vec3b>(h, w)[c]);
}
}
}
void ImageDataToBuffer(
unsigned char* data_buffer,
int height,
int width,
float* buffer,
int c) {
int idx = 0;
for (int h = 0; h < height; ++h) {
for (int w = 0; w < width; ++w) {
buffer[idx++] =
static_cast<float>(data_buffer[h * width * 3 + w * 3 + c]);
}
}
}
void ClipTransform(
const float* clip_data,
const int channels,
const int length,
const int height,
const int width,
const int crop_size,
const bool mirror,
float mean,
float std,
float* transformed_clip,
std::mt19937* randgen,
std::bernoulli_distribution* mirror_this_clip,
const bool use_center_crop) {
int h_off = 0;
int w_off = 0;
if (use_center_crop) {
h_off = (height - crop_size) / 2;
w_off = (width - crop_size) / 2;
} else {
h_off = std::uniform_int_distribution<>(0, height - crop_size)(*randgen);
w_off = std::uniform_int_distribution<>(0, width - crop_size)(*randgen);
}
float inv_std = 1.f / std;
int top_index, data_index;
bool mirror_me = mirror && (*mirror_this_clip)(*randgen);
for (int c = 0; c < channels; ++c) {
for (int l = 0; l < length; ++l) {
for (int h = 0; h < crop_size; ++h) {
for (int w = 0; w < crop_size; ++w) {
data_index =
((c * length + l) * height + h_off + h) * width + w_off + w;
if (mirror_me) {
top_index = ((c * length + l) * crop_size + h) * crop_size +
(crop_size - 1 - w);
} else {
top_index = ((c * length + l) * crop_size + h) * crop_size + w;
}
transformed_clip[top_index] =
(clip_data[data_index] - mean) * inv_std;
}
}
}
}
}
bool ReadClipFromFrames(
std::string img_dir,
const int start_frm,
std::string im_extension,
const int length,
const int height,
const int width,
const int sampling_rate,
float*& buffer) {
char fn_im[512];
cv::Mat img, img_origin;
buffer = nullptr;
int offset = 0;
int channel_size = 0;
int image_size = 0;
int data_size = 0;
int end_frm = start_frm + length * sampling_rate;
for (int i = start_frm; i < end_frm; i += sampling_rate) {
snprintf(fn_im, 512, "%s/%06d%s", img_dir.c_str(), i, im_extension.c_str());
if (height > 0 && width > 0) {
img_origin = cv::imread(fn_im, CV_LOAD_IMAGE_COLOR);
if (!img_origin.data) {
LOG(ERROR) << "Could not open or find file " << fn_im;
if (buffer != nullptr) {
delete[] buffer;
}
return false;
}
cv::resize(img_origin, img, cv::Size(width, height));
img_origin.release();
} else {
img = cv::imread(fn_im, CV_LOAD_IMAGE_COLOR);
if (!img.data) {
LOG(ERROR) << "Could not open or find file " << fn_im;
if (buffer != nullptr) {
delete[] buffer;
}
return false;
}
}
// If this is the first frame, allocate memory for the buffer
if (i == start_frm) {
image_size = img.rows * img.cols;
channel_size = image_size * length;
data_size = channel_size * 3;
buffer = new float[data_size];
}
for (int c = 0; c < 3; c++) {
ImageChannelToBuffer(&img, buffer + c * channel_size + offset, c);
}
offset += image_size;
}
CAFFE_ENFORCE(offset == channel_size, "Wrong offset size");
return true;
}
int GetNumberOfFrames(std::string filename) {
cv::VideoCapture cap;
cap.open(filename);
if (!cap.isOpened()) {
LOG(ERROR) << "Cannot open " << filename;
return 0;
}
int num_of_frames = cap.get(CV_CAP_PROP_FRAME_COUNT);
cap.release();
return num_of_frames;
}
double GetVideoFPS(std::string filename) {
cv::VideoCapture cap;
cap.open(filename);
if (!cap.isOpened()) {
LOG(ERROR) << "Cannot open " << filename;
return 0;
}
double fps = cap.get(CV_CAP_PROP_FPS);
cap.release();
return fps;
}
void GetVideoMeta(std::string filename, int& number_of_frames, double& fps) {
cv::VideoCapture cap;
cap.open(filename);
if (cap.isOpened()) {
number_of_frames = cap.get(CV_CAP_PROP_FRAME_COUNT);
fps = cap.get(CV_CAP_PROP_FPS);
cap.release();
} else {
LOG(ERROR) << "Cannot open " << filename;
number_of_frames = -1;
fps = 0;
}
}
bool ReadClipFromVideoLazzy(
std::string filename,
const int start_frm,
const int length,
const int height,
const int width,
const int sampling_rate,
float*& buffer) {
cv::VideoCapture cap;
cv::Mat img, img_origin;
buffer = nullptr;
int offset = 0;
int channel_size = 0;
int image_size = 0;
int data_size = 0;
int end_frm = 0;
cap.open(filename);
if (!cap.isOpened()) {
LOG(ERROR) << "Cannot open " << filename;
return false;
}
int num_of_frames = cap.get(CV_CAP_PROP_FRAME_COUNT);
if (num_of_frames < length * sampling_rate) {
LOG(INFO) << filename << " does not have enough frames; having "
<< num_of_frames;
return false;
}
CAFFE_ENFORCE_GE(start_frm, 0, "start frame must be greater or equal to 0");
if (start_frm) {
cap.set(CV_CAP_PROP_POS_FRAMES, start_frm);
}
end_frm = start_frm + length * sampling_rate;
CAFFE_ENFORCE_LE(
end_frm,
num_of_frames,
"end frame must be less or equal to num of frames");
for (int i = start_frm; i < end_frm; i += sampling_rate) {
if (sampling_rate > 1) {
cap.set(CV_CAP_PROP_POS_FRAMES, i);
}
if (height > 0 && width > 0) {
cap.read(img_origin);
if (!img_origin.data) {
LOG(INFO) << filename << " has no data at frame " << i;
if (buffer != nullptr) {
delete[] buffer;
}
return false;
}
cv::resize(img_origin, img, cv::Size(width, height));
} else {
cap.read(img);
if (!img.data) {
LOG(ERROR) << "Could not open or find file " << filename;
if (buffer != nullptr) {
delete[] buffer;
}
return false;
}
}
// If this is the fisrt frame, allocate memory for the buffer
if (i == start_frm) {
image_size = img.rows * img.cols;
channel_size = image_size * length;
data_size = channel_size * 3;
buffer = new float[data_size];
}
for (int c = 0; c < 3; c++) {
ImageChannelToBuffer(&img, buffer + c * channel_size + offset, c);
}
offset += image_size;
}
CAFFE_ENFORCE(offset == channel_size, "wrong offset size");
cap.release();
return true;
}
bool ReadClipFromVideoSequential(
std::string filename,
const int start_frm,
const int length,
const int height,
const int width,
const int sampling_rate,
float*& buffer) {
cv::VideoCapture cap;
cv::Mat img, img_origin;
buffer = nullptr;
int offset = 0;
int channel_size = 0;
int image_size = 0;
int data_size = 0;
cap.open(filename);
if (!cap.isOpened()) {
LOG(ERROR) << "Cannot open " << filename;
return false;
}
int num_of_frames = cap.get(CV_CAP_PROP_FRAME_COUNT);
if (num_of_frames < length * sampling_rate) {
LOG(INFO) << filename << " does not have enough frames; having "
<< num_of_frames;
return false;
}
CAFFE_ENFORCE_GE(start_frm, 0, "start frame must be greater or equal to 0");
// Instead of random access, do sequentically access (avoid key-frame issue)
// This will keep start_frm frames
int sequential_counter = 0;
while (sequential_counter < start_frm) {
cap.read(img_origin);
sequential_counter++;
}
int end_frm = start_frm + length * sampling_rate;
CAFFE_ENFORCE_LE(
end_frm,
num_of_frames,
"end frame must be less or equal to num of frames");
for (int i = start_frm; i < end_frm; i++) {
if (sampling_rate > 1) {
// If sampling_rate > 1, purposely keep some frames
if ((i - start_frm) % sampling_rate != 0) {
cap.read(img_origin);
continue;
}
}
if (height > 0 && width > 0) {
cap.read(img_origin);
if (!img_origin.data) {
LOG(INFO) << filename << " has no data at frame " << i;
if (buffer != nullptr) {
delete[] buffer;
}
return false;
}
cv::resize(img_origin, img, cv::Size(width, height));
} else {
cap.read(img);
if (!img.data) {
LOG(ERROR) << "Could not open or find file " << filename;
if (buffer != nullptr) {
delete[] buffer;
}
return false;
}
}
// If this is the first frame, then we allocate memory for the buffer
if (i == start_frm) {
image_size = img.rows * img.cols;
channel_size = image_size * length;
data_size = channel_size * 3;
buffer = new float[data_size];
}
for (int c = 0; c < 3; c++) {
ImageChannelToBuffer(&img, buffer + c * channel_size + offset, c);
}
offset += image_size;
}
CAFFE_ENFORCE(offset == channel_size, "wrong offset size");
cap.release();
return true;
}
bool ReadClipFromVideo(
std::string filename,
const int start_frm,
const int length,
const int height,
const int width,
const int sampling_rate,
float*& buffer) {
bool read_status = ReadClipFromVideoLazzy(
filename, start_frm, length, height, width, sampling_rate, buffer);
if (!read_status) {
read_status = ReadClipFromVideoSequential(
filename, start_frm, length, height, width, sampling_rate, buffer);
}
return read_status;
}
bool DecodeClipFromVideoFile(
std::string filename,
const int start_frm,
const int length,
const int height,
const int width,
const int sampling_rate,
float*& buffer,
std::mt19937* randgen,
const int sample_times) {
Params params;
std::vector<std::unique_ptr<DecodedFrame>> sampledFrames;
VideoDecoder decoder;
params.outputHeight_ = height ? height : -1;
params.outputWidth_ = width ? width : -1;
params.maximumOutputFrames_ = MAX_DECODING_FRAMES;
// decode all frames with defaul sampling rate
decoder.decodeFile(filename, params, sampledFrames);
buffer = nullptr;
int offset = 0;
int channel_size = 0;
int image_size = 0;
int data_size = 0;
CAFFE_ENFORCE_LT(1, sampledFrames.size(), "video cannot be empty");
int use_start_frm = start_frm;
if (start_frm < 0) { // perform temporal jittering
if ((int)(sampledFrames.size() - length * sampling_rate) > 0) {
use_start_frm = std::uniform_int_distribution<>(
0, (int)(sampledFrames.size() - length * sampling_rate))(*randgen);
} else {
use_start_frm = 0;
}
}
else
{
int num_of_frames = (int)(sampledFrames.size());
float frame_gaps = (float)(num_of_frames) / (float)(sample_times);
use_start_frm = ((int)(frame_gaps * start_frm)) % num_of_frames;
}
// int end_frm = start_frm + length * sampling_rate;
// for (int i = start_frm; i < end_frm; i += sampling_rate) {
for (int idx = 0; idx < length; idx ++){
int i = use_start_frm + idx * sampling_rate;
i = i % (int)(sampledFrames.size());
if (idx == 0) {
image_size = sampledFrames[i]->height_ * sampledFrames[i]->width_;
channel_size = image_size * length;
data_size = channel_size * 3;
buffer = new float[data_size];
}
for (int c = 0; c < 3; c++) {
ImageDataToBuffer(
(unsigned char*)sampledFrames[i]->data_.get(),
sampledFrames[i]->height_,
sampledFrames[i]->width_,
buffer + c * channel_size + offset,
c);
}
offset += image_size;
}
CAFFE_ENFORCE(offset == channel_size, "Wrong offset size");
// free the sampledFrames
for (int i = 0; i < sampledFrames.size(); i++) {
DecodedFrame* p = sampledFrames[i].release();
delete p;
}
sampledFrames.clear();
return true;
}
bool DecodeClipFromMemoryBuffer(
const char* video_buffer,
const int size,
const int start_frm,
const int length,
const int height,
const int width,
const int sampling_rate,
float*& buffer,
std::mt19937* randgen) {
Params params;
std::vector<std::unique_ptr<DecodedFrame>> sampledFrames;
VideoDecoder decoder;
params.outputHeight_ = height ? height : -1;
params.outputWidth_ = width ? width : -1;
params.maximumOutputFrames_ = MAX_DECODING_FRAMES;
bool isTemporalJitter = (start_frm < 0);
decoder.decodeMemory(
video_buffer,
size,
params,
sampledFrames,
length * sampling_rate,
!isTemporalJitter);
if (sampledFrames.size() < length * sampling_rate) {
/* selective decoding failed. Decode all frames. */
decoder.decodeMemory(video_buffer, size, params, sampledFrames);
}
buffer = nullptr;
int offset = 0;
int channel_size = 0;
int image_size = 0;
int data_size = 0;
int use_start_frm = start_frm;
if (start_frm < 0) { // perform temporal jittering
if ((int)(sampledFrames.size() - length * sampling_rate) > 0) {
use_start_frm = std::uniform_int_distribution<>(
0, (int)(sampledFrames.size() - length * sampling_rate))(*randgen);
} else {
use_start_frm = 0;
}
}
CAFFE_ENFORCE_LT(1, sampledFrames.size(), "video cannot be empty");
/*
if (sampledFrames.size() < length * sampling_rate) {
LOG(ERROR)
<< "The video seems faulty and we could not decode suffient samples";
buffer = nullptr;
return true;
}
CAFFE_ENFORCE_LT(
use_start_frm,
sampledFrames.size(),
"Starting frame must less than total number of video frames");
int end_frm = use_start_frm + length * sampling_rate;
CAFFE_ENFORCE_LE(
end_frm,
sampledFrames.size(),
"Ending frame must less than or equal total number of video frames");
*/
//for (int i = use_start_frm; i < end_frm; i += sampling_rate) {
for (int idx = 0; idx < length; idx ++){
int i = use_start_frm + idx * sampling_rate;
i = i % (int)(sampledFrames.size());
if (idx == 0) {
image_size = sampledFrames[i]->height_ * sampledFrames[i]->width_;
channel_size = image_size * length;
data_size = channel_size * 3;
buffer = new float[data_size];
}
for (int c = 0; c < 3; c++) {
ImageDataToBuffer(
(unsigned char*)sampledFrames[i]->data_.get(),
sampledFrames[i]->height_,
sampledFrames[i]->width_,
buffer + c * channel_size + offset,
c);
}
offset += image_size;
}
CAFFE_ENFORCE(offset == channel_size, "Wrong offset size");
// free the sampledFrames
for (int i = 0; i < sampledFrames.size(); i++) {
DecodedFrame* p = sampledFrames[i].release();
delete p;
}
sampledFrames.clear();
return true;
}
} // caffe2 namespace
| 27.391304 | 80 | 0.615556 | [
"vector"
] |
9222b8ff5f4a76c9521c086a9b574ced11539620 | 2,941 | cpp | C++ | QtAndroidTools/QAndroidPlayStore.cpp | FalsinSoft/QtAndroidTools | d1da948d905d87f08fa49093233267a488549d83 | [
"MIT"
] | 184 | 2019-01-23T19:16:01.000Z | 2022-03-26T15:24:19.000Z | QtAndroidTools/QAndroidPlayStore.cpp | ssakone/QtAndroidTools | 783e2be3ea05b144772bce77bd987fe244253b90 | [
"MIT"
] | 34 | 2019-02-11T14:53:50.000Z | 2022-03-16T19:41:28.000Z | QtAndroidTools/QAndroidPlayStore.cpp | ssakone/QtAndroidTools | 783e2be3ea05b144772bce77bd987fe244253b90 | [
"MIT"
] | 55 | 2019-01-27T05:56:51.000Z | 2022-01-11T07:15:36.000Z | /*
* MIT License
*
* Copyright (c) 2018 Fabio Falsini <falsinsoft@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND 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 "QAndroidPlayStore.h"
QAndroidPlayStore *QAndroidPlayStore::m_pInstance = nullptr;
QAndroidPlayStore::QAndroidPlayStore() : m_javaPlayStore("com/falsinsoft/qtandroidtools/AndroidPlayStore",
"(Landroid/app/Activity;)V",
QtAndroid::androidActivity().object<jobject>())
{
m_pInstance = this;
}
QObject* QAndroidPlayStore::qmlInstance(QQmlEngine *engine, QJSEngine *scriptEngine)
{
Q_UNUSED(engine);
Q_UNUSED(scriptEngine);
return new QAndroidPlayStore();
}
QAndroidPlayStore* QAndroidPlayStore::instance()
{
return m_pInstance;
}
void QAndroidPlayStore::openAppDetails(const QString &packageName)
{
QString detailsParam("details?id=");
if(packageName.isEmpty())
{
const QAndroidJniObject activity = QtAndroid::androidActivity();
detailsParam += activity.callObjectMethod("getPackageName", "()Ljava/lang/String;").toString();
}
else
{
detailsParam += packageName;
}
if(m_javaPlayStore.isValid())
{
m_javaPlayStore.callMethod<void>("open",
"(Ljava/lang/String;)V",
QAndroidJniObject::fromString(detailsParam).object<jstring>()
);
}
}
void QAndroidPlayStore::openDeveloperAppList(const QString &developerName)
{
if(m_javaPlayStore.isValid())
{
m_javaPlayStore.callMethod<void>("open",
"(Ljava/lang/String;)V",
QAndroidJniObject::fromString("developer?id=" + developerName).object<jstring>()
);
}
}
| 36.308642 | 121 | 0.646039 | [
"object"
] |
9222f54ec286c06262a4085428cf3ad22dcd9f7f | 854 | cpp | C++ | utils/WeakSource.cpp | Skird/extractors | 3c55d2c8377f465a4960861b7f358b18214f5ac3 | [
"Apache-2.0"
] | 1 | 2019-06-11T17:19:48.000Z | 2019-06-11T17:19:48.000Z | utils/WeakSource.cpp | Skird/extractors | 3c55d2c8377f465a4960861b7f358b18214f5ac3 | [
"Apache-2.0"
] | null | null | null | utils/WeakSource.cpp | Skird/extractors | 3c55d2c8377f465a4960861b7f358b18214f5ac3 | [
"Apache-2.0"
] | null | null | null | #include <utility>
#include "WeakSource.h"
WeakSource::WeakSource(Bitstring data, double minEntropy, double error)
: data_(std::move(data)), minEntropy_(minEntropy), error_(error) {
}
const Bitstring &WeakSource::getData() const {
return data_;
}
double WeakSource::getMinEntropy() const {
return minEntropy_;
}
double WeakSource::getError() const {
return error_;
}
std::vector<WeakSource> WeakSource::splitIntoBlocks(uint32_t n) const {
assert(n > 0);
double defect = data_.size() - minEntropy_;
uint32_t sz = data_.size() / n;
std::vector<WeakSource> result;
for (uint32_t i = 0; i < n; ++i) {
uint32_t csz = sz + (i < data_.size() % sz ? 1 : 0);
Bitstring part(data_.substr(i * sz, csz));
result.emplace_back(part, sz - defect - log2(1 / error_), error_);
}
return result;
}
| 25.117647 | 74 | 0.648712 | [
"vector"
] |
9222fa864f50caa0dc32e83a46a0e40e13d2e72d | 2,204 | hpp | C++ | cpp/src/toppra/geometric_path/piecewise_poly_path.hpp | CICS-ICT/topprap | 23fc43a970387b46362fe025a200482691e0c82e | [
"MIT"
] | 1 | 2020-09-15T07:48:46.000Z | 2020-09-15T07:48:46.000Z | cpp/src/toppra/geometric_path/piecewise_poly_path.hpp | CICS-ICT/topprap | 23fc43a970387b46362fe025a200482691e0c82e | [
"MIT"
] | 12 | 2019-07-26T16:02:18.000Z | 2021-03-11T02:19:39.000Z | cpp/src/toppra/geometric_path/piecewise_poly_path.hpp | CICS-ICT/topprap | 23fc43a970387b46362fe025a200482691e0c82e | [
"MIT"
] | 1 | 2020-05-15T18:25:41.000Z | 2020-05-15T18:25:41.000Z | #ifndef TOPPRA_PIECEWISE_POLY_PATH_HPP
#define TOPPRA_PIECEWISE_POLY_PATH_HPP
#include <toppra/geometric_path.hpp>
#include <toppra/toppra.hpp>
namespace toppra {
/**
* \brief Piecewise polynomial geometric path.
*
* An implemetation of a piecewise polynoamial geometric path.
*
* The coefficent vector has shape (N, P, D), where N is the number
* segments. For each segment, the i-th row (P index) denotes the
* power, while the j-th column is the degree of freedom. In
* particular,
*
* coeff(0) * dt ^ 3 + coeff(1) * dt ^ 2 + coeff(2) * dt + coeff(3)
*
*
*/
class PiecewisePolyPath : public GeometricPath {
public:
PiecewisePolyPath() = default;
/**
* \brief Construct new piecewise polynomial.
*
* See class docstring for details.
*
* @param coefficients Polynoamial coefficients.
* @param breakpoints Vector of breakpoints.
*/
PiecewisePolyPath(const Matrices &coefficients, std::vector<value_type> breakpoints);
/**
* /brief Evaluate the path at given position.
*/
Vector eval_single(value_type, int order = 0) const override;
/**
* /brief Evaluate the path at given positions (vector).
*/
Vectors eval(const Vector &, int order = 0) const override;
/**
* Return the starting and ending path positions.
*/
Bound pathInterval() const override;
void serialize(std::ostream &O) const override;
void deserialize(std::istream &I) override;
/**
* \brief Construct a new Hermite polynomial.
*/
static PiecewisePolyPath constructHermite(const Vectors &positions,
const Vectors &velocities,
const std::vector<value_type> times);
protected:
void initAsHermite(const Vectors &positions, const Vectors &velocities,
const std::vector<value_type> times);
void reset();
size_t findSegmentIndex(value_type pos) const;
void checkInputArgs();
void computeDerivativesCoefficients();
const Matrix &getCoefficient(int seg_index, int order) const;
Matrices m_coefficients, m_coefficients_1, m_coefficients_2;
std::vector<value_type> m_breakpoints;
int m_degree;
};
} // namespace toppra
#endif
| 28.623377 | 87 | 0.685118 | [
"shape",
"vector"
] |
92299fa16b763b5e2a30e26c403c528c6cc34bf7 | 3,439 | cpp | C++ | src/TcpIpClient.cpp | huckor/openssl | 52c407eb08de63ed21c3b636360aac4bcfc59061 | [
"MIT"
] | null | null | null | src/TcpIpClient.cpp | huckor/openssl | 52c407eb08de63ed21c3b636360aac4bcfc59061 | [
"MIT"
] | null | null | null | src/TcpIpClient.cpp | huckor/openssl | 52c407eb08de63ed21c3b636360aac4bcfc59061 | [
"MIT"
] | null | null | null | #include "TcpIpClient.h"
#include <openssl/err.h>
#include <openssl/rand.h>
#include <openssl/ssl.h>
#include "Log.h"
#include "Conv.h"
#include "Global.h"
TcpIpClient::TcpIpClient()
{
_ReadTimeout = 10;
_WriteTimeout = 10;
_Conn = NULL;
_Host = "";
_Port = "";
}
TcpIpClient::~TcpIpClient()
{
if(_Conn)
Close();
}
void TcpIpClient::SetThePort(std::string Port)
{
_Port = Port;
}
void TcpIpClient::SetHost(std::string Host)
{
_Host = Host;
}
void TcpIpClient::SetReadTimeout(int Timeout)
{
_ReadTimeout = Timeout;
}
void TcpIpClient::SetWriteTimeout(int Timeout)
{
_WriteTimeout = Timeout;
}
int TcpIpClient::Open()
{
int Socket = -1;
struct timeval TimeVal;
fd_set FdSet;
//Create TCP/IP connection
_Conn = BIO_new_connect((char *)std::string(_Host + ":" + _Port).c_str());
if(!_Conn)
{
LOG("Unable to create new BIO connection to host " + _Host + " port " + _Port, OPENSSL_LOG_BIT);
return FAIL;
}
else
LOG("New BIO created to host " + _Host + " port " + _Port, OPENSSL_LOG_BIT);
//Set BIO to non blocking BIO
if(!BIO_set_nbio(_Conn, 1))
{
LOG("Unable to configure BIO to NBIO", OPENSSL_LOG_BIT);
return FAIL;
}
else
LOG("BIO is configured to NBIO", OPENSSL_LOG_BIT);
//Less or equal 0 means we need to wait on socket till openssl finish write operation
if(BIO_do_connect(_Conn) <= 0)
{
Socket = (int)BIO_get_fd(_Conn, NULL);
if(Socket == -1)
{
LOG("Unable to connect to the remote machine.", OPENSSL_LOG_BIT);
return FAIL;
}
TimeVal.tv_sec = _WriteTimeout;
TimeVal.tv_usec = 0;
FD_ZERO(&FdSet);
FD_SET(Socket, &FdSet);
if(select(Socket + 1, 0, &FdSet, 0, &TimeVal) <= 0)
{
LOG("Unable to connect to the remote machine.", OPENSSL_LOG_BIT);
return FAIL;
}
}
LOG("Sucesfully connected to the remote machine.", OPENSSL_LOG_BIT);
return OK;
}
int TcpIpClient::Write(std::vector<unsigned char> Data)
{
int Ret = 0;
if(_Conn == NULL)
{
LOG("Error - connection not opened.", OPENSSL_LOG_BIT);
return FAIL;
}
Ret = BIO_write(_Conn, &Data[0], (int)Data.size());
if(Ret >= 0)
return OK;
else
LOG("Error - write failed.", OPENSSL_LOG_BIT);
return FAIL;
}
int TcpIpClient::Read(unsigned char *Buffer, int Length)
{
int Socket = -1;
int Ret = 0;
struct timeval TimeVal;
fd_set FdSet;
if(_Conn == NULL)
{
LOG("Error - connection not opened.", OPENSSL_LOG_BIT);
return FAIL;
}
Socket = (int)BIO_get_fd(_Conn, NULL);
TimeVal.tv_sec = _ReadTimeout;
TimeVal.tv_usec = 0;
FD_ZERO(&FdSet);
FD_SET(Socket, &FdSet);
Ret = select(Socket + 1, &FdSet, 0, 0, &TimeVal);
if(Ret < 0)
{
LOG("Error on socket", OPENSSL_LOG_BIT);
return FAIL;
}
else if(Ret == 0)
{
LOG("Timeout on socket", OPENSSL_LOG_BIT);
return TIMEOUT;
}
Ret = BIO_read(_Conn, Buffer, Length);
if(Ret <= 0)
{
LOG("Error on reading from socket", OPENSSL_LOG_BIT);
return FAIL;
}
return Ret;
}
void TcpIpClient::Close()
{
if(_Conn)
{
BIO_free(_Conn);
_Conn = NULL;
}
} | 21.360248 | 104 | 0.57633 | [
"vector"
] |
922c411459300c3c5964284dff0c598399115ea1 | 33,648 | cpp | C++ | HonyarectX/HonyarectX/PMDActor.cpp | honyax/HonyarectX | 2823207792299e1904346bfa7677bafbdc494be0 | [
"MIT"
] | null | null | null | HonyarectX/HonyarectX/PMDActor.cpp | honyax/HonyarectX | 2823207792299e1904346bfa7677bafbdc494be0 | [
"MIT"
] | null | null | null | HonyarectX/HonyarectX/PMDActor.cpp | honyax/HonyarectX | 2823207792299e1904346bfa7677bafbdc494be0 | [
"MIT"
] | null | null | null | #include "PMDActor.h"
#include "PMDRenderer.h"
#include "Dx12Wrapper.h"
#include <d3dx12.h>
#include <array>
#include <algorithm>
using namespace Microsoft::WRL;
using namespace std;
using namespace DirectX;
#pragma comment(lib,"winmm.lib")
namespace
{
/// <summary>
/// テクスチャのパスをセパレータ文字で分離する
/// </summary>
/// <param name="path">対象のパス文字列</param>
/// <param name="splitter">区切り文字</param>
/// <returns>分離後の文字列ペア</returns>
pair<string, string> SplitFileName(const string& path, const char splitter = '*')
{
auto idx = path.find(splitter);
pair<string, string> ret;
ret.first = path.substr(0, idx);
ret.second = path.substr(idx + 1, path.length() - idx - 1);
return ret;
}
/// <summary>
/// ファイル名から拡張子を取得する
/// </summary>
/// <param name="path">対象のパス文字列</param>
/// <returns>拡張子</returns>
string GetExtension(const string& path)
{
auto idx = path.rfind('.');
return path.substr(idx + 1, path.length() - idx - 1);
}
/// <summary>
/// モデルのパスとテクスチャのパスから合成パスを得る
/// </summary>
/// <param name="modelPath">アプリケーションから見たpmdモデルのパス</param>
/// <param name="texPath">PMDモデルから見たテクスチャのパス</param>
/// <returns>アプリケーションから見たテクスチャのパス</returns>
string GetTexturePathFromModelAndTexPath(const string& modelPath, const char* texPath)
{
// ファイルのフォルダ区切りは\と/の二種類が使用される可能性があり
// ともかく末尾の\か/を得られればいいので、双方のrfindをとり比較する
// int型に代入しているのは見つからなかった場合はrfindがepos(-1→0xffffffff)を返すため
int pathIndex1 = static_cast<int>(modelPath.rfind('/'));
int pathIndex2 = static_cast<int>(modelPath.rfind('\\'));
auto pathIndex = max(pathIndex1, pathIndex2);
auto folderPath = modelPath.substr(0, pathIndex + 1);
return folderPath + texPath;
}
XMMATRIX LookAtMatrix(const XMVECTOR& lookat, XMFLOAT3& up, XMFLOAT3& right)
{
// 向かせたい方向(Z軸)
XMVECTOR vz = lookat;
// (向かせたい方向を向かせたときの)仮のY軸ベクトル
XMVECTOR vy = XMVector3Normalize(XMLoadFloat3(&up));
// (向かせたい方向を向かせたときの)X軸
//XMVECTOR vx = XMVector3Normalize(XMVector3Cross(vz, vx));
XMVECTOR vx = XMVector3Normalize(XMVector3Cross(vy, vz));
vy = XMVector3Normalize(XMVector3Cross(vz, vx));
// LookAtとupが同じ方向を向いてたらright基準で作り直す
if (abs(XMVector3Dot(vy, vz).m128_f32[0]) == 1.0f) {
// 仮のX方向を定義
vx = XMVector3Normalize(XMLoadFloat3(&right));
// 向かせたい方向を向かせたときのY軸を計算
vy = XMVector3Normalize(XMVector3Cross(vz, vx));
// 真のX軸を計算
vx = XMVector3Normalize(XMVector3Cross(vy, vz));
}
XMMATRIX ret = XMMatrixIdentity();
ret.r[0] = vx;
ret.r[1] = vy;
ret.r[2] = vz;
return ret;
}
XMMATRIX LookAtMatrix(const XMVECTOR& origin, const XMVECTOR& lookat, XMFLOAT3& up, XMFLOAT3& right)
{
return XMMatrixTranspose(LookAtMatrix(origin, up, right)) * LookAtMatrix(lookat, up, right);
}
enum class BoneType {
Rotation, // 回転
RotAndMove, // 回転&移動
IK, // IK
Undefined, // 未定義
IKChild, // IK影響ボーン
RotationChild, // 回転影響ボーン
IKDestination, // IK接続先
Invisible, // 見えないボーン
};
}
void PMDActor::LookAt(float x, float y, float z)
{
auto vec = XMFLOAT3(x, y, z);
auto lookat = XMLoadFloat3(&vec);
auto up = XMFLOAT3(0, 1, 0);
auto right = XMFLOAT3(1, 0, 0);
_localMat = LookAtMatrix(lookat, up, right);
}
void PMDActor::SolveLookAt(const PMDIK& ik)
{
// この関数に来た時点でノードはひとつしかなく、チェーンに入っているノード番号はIKのルートノードのものなので、
// このルートノードからターゲットに向かうベクトルを考えれば良い
auto rootNode = _boneNodeAddressArray[ik.nodeIdxes[0]];
auto targetNode = _boneNodeAddressArray[ik.targetIdx]; // !?
auto opos1 = XMLoadFloat3(&rootNode->startPos);
auto tpos1 = XMLoadFloat3(&targetNode->startPos);
auto opos2 = XMVector3Transform(opos1, _boneMatrices[ik.nodeIdxes[0]]);
auto tpos2 = XMVector3Transform(tpos1, _boneMatrices[ik.boneIdx]);
auto originVec = XMVectorSubtract(tpos1, opos1);
auto targetVec = XMVectorSubtract(tpos2, opos2);
originVec = XMVector3Normalize(originVec);
targetVec = XMVector3Normalize(targetVec);
auto up = XMFLOAT3(0, 1, 0);
auto right = XMFLOAT3(1, 0, 0);
XMMATRIX mat = XMMatrixTranslationFromVector(-opos2) * LookAtMatrix(originVec, targetVec, up, right) * XMMatrixTranslationFromVector(opos2);
_boneMatrices[ik.nodeIdxes[0]] = mat;
}
void PMDActor::SolveCosineIK(const PMDIK& ik)
{
vector<XMVECTOR> positions; // IK構成点を保存
array<float, 2> edgeLens; // IKのそれぞれのボーン間の距離を保存
// ターゲット(末端ボーンではなく、末端ボーンが近づく目標ボーンの座標を取得)
auto& targetNode = _boneNodeAddressArray[ik.boneIdx];
auto targetPos = XMVector3Transform(XMLoadFloat3(&targetNode->startPos), _boneMatrices[ik.boneIdx]);
// IKチェーンが逆順なので、逆に並ぶようにしている
// 末端ボーン
auto endNode = _boneNodeAddressArray[ik.targetIdx];
positions.emplace_back(XMLoadFloat3(&endNode->startPos));
// 中間及びルートボーン
for (auto& chainBoneIdx : ik.nodeIdxes) {
auto boneNode = _boneNodeAddressArray[chainBoneIdx];
positions.emplace_back(XMLoadFloat3(&boneNode->startPos));
}
// ちょっと分かりづらいので逆にしておく
reverse(positions.begin(), positions.end());
// 元の長さを測っておく
edgeLens[0] = XMVector3Length(XMVectorSubtract(positions[1], positions[0])).m128_f32[0];
edgeLens[1] = XMVector3Length(XMVectorSubtract(positions[2], positions[1])).m128_f32[0];
// ルートボーン座標変換(逆順になっているため使用するインデックスに注意)
positions[0] = XMVector3Transform(positions[0], _boneMatrices[ik.nodeIdxes[1]]);
// 真ん中はどうせ自動計算されるので計算しない
// 先端ボーン
positions[2] = XMVector3Transform(positions[2], _boneMatrices[ik.boneIdx]); // 本当はik.targetIdxだが・・・!?
// ルートから先端へのベクトルを作っておく
auto linearVec = XMVectorSubtract(positions[2], positions[0]);
float a = XMVector3Length(linearVec).m128_f32[0];
float b = edgeLens[0];
float c = edgeLens[1];
linearVec = XMVector3Normalize(linearVec);
// ルートから真ん中への角度計算
float theta1 = acosf((a * a + b * b - c * c) / (2 * a * b));
// 真ん中からターゲットへの角度計算
float theta2 = acosf((b * b + c * c - a * a) / (2 * b * c));
// 「軸」を求める
// もし真ん中が「ひざ」であった場合には強制的にX軸とする。
XMVECTOR axis;
if (find(_kneeIdxes.begin(), _kneeIdxes.end(), ik.nodeIdxes[0]) == _kneeIdxes.end()) {
auto vm = XMVector3Normalize(XMVectorSubtract(positions[2], positions[0]));
auto vt = XMVector3Normalize(XMVectorSubtract(targetPos, positions[0]));
axis = XMVector3Cross(vt, vm);
}
else {
auto right = XMFLOAT3(1, 0, 0);
axis = XMLoadFloat3(&right);
}
// 注意点・・・IKチェーンは根っこに向かってから数えられるため1が根っこに近い
auto mat1 = XMMatrixTranslationFromVector(-positions[0]);
mat1 *= XMMatrixRotationAxis(axis, theta1);
mat1 *= XMMatrixTranslationFromVector(positions[0]);
auto mat2 = XMMatrixTranslationFromVector(-positions[1]);
mat2 *= XMMatrixRotationAxis(axis, theta2 - XM_PI);
mat2 *= XMMatrixTranslationFromVector(positions[1]);
_boneMatrices[ik.nodeIdxes[1]] *= mat1;
_boneMatrices[ik.nodeIdxes[0]] = mat2 * _boneMatrices[ik.nodeIdxes[1]];
_boneMatrices[ik.targetIdx] = _boneMatrices[ik.nodeIdxes[0]];//直前の影響を受ける
//_boneMatrices[ik.nodeIdxes[1]] = _boneMatrices[ik.boneIdx];
//_boneMatrices[ik.nodeIdxes[0]] = _boneMatrices[ik.boneIdx];
//_boneMatrices[ik.targetIdx] *= _boneMatrices[ik.boneIdx];
}
constexpr float epsilon = 0.0005f;
void PMDActor::SolveCCDIK(const PMDIK& ik)
{
// ターゲット
auto targetBoneNode = _boneNodeAddressArray[ik.boneIdx];
auto targetOriginPos = XMLoadFloat3(&targetBoneNode->startPos);
auto parentMat = _boneMatrices[_boneNodeAddressArray[ik.boneIdx]->ikParentBone];
XMVECTOR det;
auto invParentMat = XMMatrixInverse(&det, parentMat);
auto targetNextPos = XMVector3Transform(targetOriginPos, _boneMatrices[ik.boneIdx] * invParentMat);
// まずはIKの間にあるボーンの座標を入れておく(逆順注意)
std::vector<XMVECTOR> bonePositions;
//auto endPos = XMVector3Transform(
// XMLoadFloat3(&_boneNodeAddressArray[ik.targetIdx]->startPos),
// //_boneMatrices[ik.targetIdx]);
// XMMatrixIdentity());
// 末端ノード
auto endPos = XMLoadFloat3(&_boneNodeAddressArray[ik.targetIdx]->startPos);
// 中間ノード(ルートを含む)
for (auto& cidx : ik.nodeIdxes) {
//bonePositions.emplace_back(XMVector3Transform(XMLoadFloat3(&_boneNodeAddressArray[cidx]->startPos), _boneMatrices[cidx] ));
bonePositions.push_back(XMLoadFloat3(&_boneNodeAddressArray[cidx]->startPos));
}
vector<XMMATRIX> mats(bonePositions.size());
fill(mats.begin(), mats.end(), XMMatrixIdentity());
// ちょっとよくわからないが、PMDエディタの6.8°が0.03になっており、これは180で割っただけの値である。
// つまりこれをラジアンとして使用するにはXM_PIを乗算しなければならない…と思われる。
auto ikLimit = ik.limit * XM_PI;
// ikに設定されている試行回数だけ繰り返す
for (int c = 0; c < ik.iterations; ++c) {
// ターゲットと末端がほぼ一致したら抜ける
if (XMVector3Length(XMVectorSubtract(endPos, targetNextPos)).m128_f32[0] <= epsilon) {
break;
}
// それぞれのボーンを遡りながら角度制限に引っ掛からないように曲げていく
for (int bidx = 0; bidx < bonePositions.size(); ++bidx) {
const auto& pos = bonePositions[bidx];
// まず現在のノードから末端までと、現在のノードからターゲットまでのベクトルを作る
auto vecToEnd = XMVectorSubtract(endPos, pos);
auto vecToTarget = XMVectorSubtract(targetNextPos, pos);
vecToEnd = XMVector3Normalize(vecToEnd);
vecToTarget = XMVector3Normalize(vecToTarget);
// ほぼ同じベクトルになってしまった場合は外積できないため次のボーンに引き渡す
if (XMVector3Length(XMVectorSubtract(vecToEnd, vecToTarget)).m128_f32[0] <= epsilon) {
continue;
}
// 外積計算および角度計算
auto cross = XMVector3Normalize(XMVector3Cross(vecToEnd, vecToTarget));
float angle = XMVector3AngleBetweenVectors(vecToEnd, vecToTarget).m128_f32[0];
angle = min(angle, ikLimit); // 回転限界補正
XMMATRIX rot = XMMatrixRotationAxis(cross, angle); // 回転行列
// posを中心に回転
auto mat = XMMatrixTranslationFromVector(-pos) *
rot *
XMMatrixTranslationFromVector(pos);
mats[bidx] *= mat; // 回転行列を保持しておく(乗算で回転重ね掛けを作っておく)
// 対象となる点をすべて回転させる(現在の点から見て末端側を回転)
for (auto idx = bidx - 1; idx >= 0; --idx) { // 自分を回転させる必要はない
bonePositions[idx] = XMVector3Transform(bonePositions[idx], mat);
}
endPos = XMVector3Transform(endPos, mat);
// もし正解に近くなってたらループを抜ける
if (XMVector3Length(XMVectorSubtract(endPos, targetNextPos)).m128_f32[0] <= epsilon) {
break;
}
}
}
int idx = 0;
for (auto& cidx : ik.nodeIdxes) {
_boneMatrices[cidx] = mats[idx];
++idx;
}
auto node = _boneNodeAddressArray[ik.nodeIdxes.back()];
RecursiveMatrixMultiply(node, parentMat, true);
}
float PMDActor::GetYFromXOnBezier(float x, const XMFLOAT2& a, const XMFLOAT2& b, uint8_t n)
{
if (a.x == a.y && b.x == b.y)
return x; // 計算不要
float t = x;
const float k0 = 1 + 3 * a.x - 3 * b.x; // t^3の係数
const float k1 = 3 * b.x - 6 * a.x; // t^2の係数
const float k2 = 3 * a.x; // tの係数
// 誤差の範囲内かどうかに使用する定数
constexpr float epsilon = 0.0005f;
for (int i = 0; i < n; ++i) {
// f(t)求めます
auto ft = k0 * t * t * t + k1 * t * t + k2 * t - x;
// もし結果が0に近い(誤差の範囲内)なら打ち切り
if (ft <= epsilon && ft >= -epsilon)
break;
t -= ft / 2;
}
// 既に求めたいtは求めているのでyを計算する
auto r = 1 - t;
return t * t * t + 3 * t * t * r * b.y + 3 * t * r * r * a.y;
}
void* PMDActor::Transform::operator new(size_t size)
{
return _aligned_malloc(size, 16);
}
PMDActor::PMDActor(const char* filepath, PMDRenderer& renderer) :
_renderer(renderer),
_dx12(renderer._dx12),
_angle(0.0f)
{
_transform.world = XMMatrixIdentity();
LoadPMDFile(filepath);
CreateTransformView();
CreateMaterialData();
CreateMaterialAndTextureView();
}
PMDActor::~PMDActor()
{
}
void PMDActor::LoadVMDFile(const char* filepath, const char* name)
{
FILE* fp;
fopen_s(&fp, filepath, "rb");
if (fp == nullptr) {
assert(0);
return;
}
fseek(fp, 50, SEEK_SET); // 最初の50バイトは飛ばしてOK
UINT keyframeNum = 0;
fread(&keyframeNum, sizeof(keyframeNum), 1, fp);
struct VMDKeyFrame {
char boneName[15]; // ボーン名
UINT frameNo; // フレーム番号
XMFLOAT3 location; // 位置
XMFLOAT4 quaternion; // クォータニオン(回転)
UINT8 bezier[64]; // [4][4][4] ベジェ補間パラメータ
};
vector<VMDKeyFrame> keyframes(keyframeNum);
for (auto& keyframe : keyframes) {
fread(keyframe.boneName, sizeof(keyframe.boneName), 1, fp); // ボーン名
fread(&keyframe.frameNo,
sizeof(keyframe.frameNo) // フレーム番号
+ sizeof(keyframe.location) // 位置(IKの時に使用予定)
+ sizeof(keyframe.quaternion) // クォータニオン
+ sizeof(keyframe.bezier), // 補間ベジェデータ
1, fp);
}
#pragma pack(1)
// 表情データ(頂点モーフデータ)
struct VMDMorph {
char name[15]; // 名前(パディングしてしまう)
uint32_t frameNo; // フレーム番号
float weight; // ウェイト(0.0f~1.0f)
};
#pragma pack()
uint32_t morphCount = 0;
fread(&morphCount, sizeof(morphCount), 1, fp);
vector<VMDMorph> morphs(morphCount);
fread(morphs.data(), sizeof(VMDMorph), morphCount, fp);
#pragma pack(1)
// カメラ
struct VMDCamera {
uint32_t frameNo; // フレーム番号
float distance; // 距離
XMFLOAT3 pos; // 座標
XMFLOAT3 eulerAngle; // オイラー角
uint8_t interpolation[24]; // 補完
uint32_t fov; // 視界角
uint8_t persFlg; // パースフラグON/OFF
};
#pragma pack()
uint32_t vmdCameraCount = 0;
fread(&vmdCameraCount, sizeof(vmdCameraCount), 1, fp);
vector<VMDCamera> cameraData(vmdCameraCount);
fread(cameraData.data(), sizeof(VMDCamera), vmdCameraCount, fp);
// ライト照明データ
struct VMDLight {
uint32_t frameNo; // フレーム番号
XMFLOAT3 rgb; // ライト色
XMFLOAT3 vec; // 光線ベクトル(平行光線)
};
uint32_t vmdLightCount = 0;
fread(&vmdLightCount, sizeof(vmdLightCount), 1, fp);
vector<VMDLight> lights(vmdLightCount);
fread(lights.data(), sizeof(VMDLight), vmdLightCount, fp);
#pragma pack(1)
// セルフ影データ
struct VMDSelfShadow {
uint32_t frameNo; // フレーム番号
uint8_t mode; // 影モード(0:影なし、1:モード1、2:モード2)
float distance; // 距離
};
#pragma pack()
uint32_t selfShadowCount = 0;
fread(&selfShadowCount, sizeof(selfShadowCount), 1, fp);
vector<VMDSelfShadow> selfShadowData(selfShadowCount);
fread(selfShadowData.data(), sizeof(VMDSelfShadow), selfShadowCount, fp);
// IKオンオフ切り替わり数
uint32_t ikSwitchCount = 0;
fread(&ikSwitchCount, sizeof(ikSwitchCount), 1, fp);
// IK切り替えのデータ構造は少しだけ特殊で、いくつ切り替えようがそのキーフレームは消費される。
// その中で切り替える可能性のあるIKの名前とそのフラグがすべて登録されている状態。
// ここからは気を遣って読み込む。
// キーフレームごとのデータでありIKボーン(名前で検索)ごとにオン、オフフラグを
// 持っているというデータであるとして構造体を作っていく。
_ikEnableData.resize(ikSwitchCount);
for (auto& ikEnable : _ikEnableData) {
// キーフレーム情報なのでまずはフレーム番号読み込み
fread(&ikEnable.frameNo, sizeof(ikEnable.frameNo), 1, fp);
// 次に可視フラグがあるがこれは使用しないので1バイトシークでもOK
uint8_t visibleFlg = 0;
fread(&visibleFlg, sizeof(visibleFlg), 1, fp);
// 対象ボーン数読み込み
uint32_t ikBoneCount = 0;
fread(&ikBoneCount, sizeof(ikBoneCount), 1, fp);
// ループしつつ名前とON/OFF情報を取得
for (UINT i = 0; i < ikBoneCount; ++i) {
char ikBoneName[20];
fread(ikBoneName, _countof(ikBoneName), 1, fp);
uint8_t flg = 0;
fread(&flg, sizeof(flg), 1, fp);
ikEnable.ikEnableTable[ikBoneName] = flg;
}
}
fclose(fp);
// VMDのキーフレームデータから、実際に使用するキーフレームテーブルへ変換
for (auto& f : keyframes) {
auto q = XMLoadFloat4(&f.quaternion);
XMFLOAT2 ip1((float)f.bezier[3] / 127.0f, (float)f.bezier[7] / 127.0f);
XMFLOAT2 ip2((float)f.bezier[11] / 127.0f, (float)f.bezier[15] / 127.0f);
_motiondata[f.boneName].emplace_back(KeyFrame(f.frameNo, q, f.location, ip1, ip2));
_duration = max<UINT>(_duration, f.frameNo);
}
// モーションデータをキーフレームでソート
for (auto& motion : _motiondata) {
sort(motion.second.begin(), motion.second.end(),
[](const KeyFrame& lval, const KeyFrame& rval) {
return lval.frameNo <= rval.frameNo;
});
}
for (auto& bonemotion : _motiondata) {
auto itBoneNode = _boneNodeTable.find(bonemotion.first);
if (itBoneNode == _boneNodeTable.end()) {
continue;
}
auto& node = itBoneNode->second;
auto& pos = node.startPos;
auto mat = XMMatrixTranslation(-pos.x, -pos.y, -pos.z) *
XMMatrixRotationQuaternion(bonemotion.second[0].quaternion) *
XMMatrixTranslation(pos.x, pos.y, pos.z);
_boneMatrices[node.boneIdx] = mat;
}
auto ident = XMMatrixIdentity();
RecursiveMatrixMultiply(&_boneNodeTable["センター"], ident);
copy(_boneMatrices.begin(), _boneMatrices.end(), _mappedMatrices + 1);
}
void PMDActor::PlayAnimation()
{
_startTime = timeGetTime();
}
void PMDActor::MotionUpdate()
{
auto elapsedTime = timeGetTime() - _startTime; // 経過時間を測る
UINT frameNo = static_cast<UINT>(30 * (elapsedTime / 1000.0f));
if (frameNo > _duration) {
_startTime = timeGetTime();
frameNo = 0;
}
// 行列情報クリア(していないと前フレームのポーズが重ねがけされてモデルが壊れる)
auto ident = XMMatrixIdentity();
std::fill(_boneMatrices.begin(), _boneMatrices.end(), ident);
// モーションデータ更新
for (auto& bonemotion : _motiondata) {
auto itBoneNode = _boneNodeTable.find(bonemotion.first);
if (itBoneNode == _boneNodeTable.end()) {
continue;
}
auto& node = itBoneNode->second;
// 合致するものを探す
auto keyframes = bonemotion.second;
auto rit = find_if(keyframes.rbegin(), keyframes.rend(), [frameNo](const KeyFrame& keyframe) {
return keyframe.frameNo <= frameNo;
});
if (rit == keyframes.rend()) {
// 合致するものがなければ飛ばす
continue;
}
XMMATRIX rotation = XMMatrixIdentity();
XMVECTOR offset = XMLoadFloat3(&rit->offset);
auto it = rit.base();
if (it != keyframes.end()) {
auto t = static_cast<float>(frameNo - rit->frameNo) / static_cast<float>(it->frameNo - rit->frameNo);
t = GetYFromXOnBezier(t, it->p1, it->p2, 12);
rotation = XMMatrixRotationQuaternion(XMQuaternionSlerp(rit->quaternion, it->quaternion, t));
offset = XMVectorLerp(offset, XMLoadFloat3(&it->offset), t);
}
else {
rotation = XMMatrixRotationQuaternion(rit->quaternion);
}
auto& pos = node.startPos;
auto mat = XMMatrixTranslation(-pos.x, -pos.y, -pos.z) // 原点に戻し
* rotation // 回転
* XMMatrixTranslation(pos.x, pos.y, pos.z); // 元の座標に戻す
_boneMatrices[node.boneIdx] = mat * XMMatrixTranslationFromVector(offset);
}
RecursiveMatrixMultiply(&_boneNodeTable["センター"], ident);
IKSolve(frameNo);
copy(_boneMatrices.begin(), _boneMatrices.end(), _mappedMatrices + 1);
}
void PMDActor::IKSolve(int frameNo)
{
// いつもの逆から検索
auto it = find_if(_ikEnableData.rbegin(), _ikEnableData.rend(),
[frameNo](const VMDIKEnable& ikenable) {
return ikenable.frameNo <= static_cast<UINT>(frameNo);
});
// まずはIKのターゲットボーンを動かす
for (auto& ik : _ikData) {
// IK解決のためのループ
if (it != _ikEnableData.rend()) {
auto ikEnableIt = it->ikEnableTable.find(_boneNameArray[ik.boneIdx]);
if (ikEnableIt != it->ikEnableTable.end()) {
if (!ikEnableIt->second) {
// もしOFFなら打ち切る
continue;
}
}
}
auto childrenNodesCount = ik.nodeIdxes.size();
switch (childrenNodesCount) {
case 0: // 間のボーン数が0はありえない
assert(0);
continue;
case 1: // 間のボーン数が1のときはLookAt
SolveLookAt(ik);
break;
case 2: // 間のボーン数が2のときは余弦定理IK
SolveCosineIK(ik);
break;
default: // 3以上のときはCCD-IK
SolveCCDIK(ik);
break;
}
}
}
HRESULT PMDActor::LoadPMDFile(const char* path)
{
// PMDヘッダ構造体
struct PMDHeader {
float version; // 例:00 00 80 3F == 1.00
char model_name[20]; // モデル名
char comment[256]; // モデルコメント
};
char signature[3];
PMDHeader pmdheader = {};
string strModelPath = path;
FILE* fp;
fopen_s(&fp, strModelPath.c_str(), "rb");
if (fp == nullptr) {
// エラー処理
assert(0);
return ERROR_FILE_NOT_FOUND;
}
fread(signature, sizeof(signature), 1, fp);
fread(&pmdheader, sizeof(pmdheader), 1, fp);
unsigned int vertNum; // 頂点数
fread(&vertNum, sizeof(vertNum), 1, fp);
#pragma pack(1) // ここから1バイトパッキング(アライメントは発生しない)
// PMDマテリアル構造体
struct PMDMaterial {
XMFLOAT3 diffuse; // ディフューズ色
float alpha; // ディフューズα
float specularity; // スペキュラの強さ(乗算値)
XMFLOAT3 specular; // スペキュラ色
XMFLOAT3 ambient; // アンビエント色
unsigned char toonIdx; // トゥーン番号
unsigned char edgeFlg; // マテリアル毎の輪郭線フラグ
// 1バイトパッキングにしないとここで2バイトのパディングが発生する
unsigned int indicesNum; // このマテリアルが割当たるインデックス数
char texFilePath[20]; // テクスチャファイル名
}; // 70バイトになる(パディングなしの場合)
#pragma pack() // 1バイトパッキング解除
constexpr size_t pmdvertex_size = 38; // 頂点1つあたりのサイズ
vector<unsigned char> vertices(vertNum * pmdvertex_size); // バッファの確保
fread(vertices.data(), vertices.size(), 1, fp); // 読み込み
unsigned int indicesNum; // インデックス数
fread(&indicesNum, sizeof(indicesNum), 1, fp);
auto heapProp = CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD);
auto resDesc = CD3DX12_RESOURCE_DESC::Buffer(vertices.size() * sizeof(vertices[0]));
// UPLOAD(確保は可能)
auto result = _dx12.Device()->CreateCommittedResource(
&heapProp,
D3D12_HEAP_FLAG_NONE,
&resDesc,
D3D12_RESOURCE_STATE_GENERIC_READ,
nullptr,
IID_PPV_ARGS(_vb.ReleaseAndGetAddressOf())
);
unsigned char* vertMap = nullptr;
result = _vb->Map(0, nullptr, (void**)&vertMap);
copy(vertices.begin(), vertices.end(), vertMap);
_vb->Unmap(0, nullptr);
_vbView.BufferLocation = _vb->GetGPUVirtualAddress(); // バッファの仮想アドレス
_vbView.SizeInBytes = static_cast<UINT>(vertices.size()); // 全バイト数
_vbView.StrideInBytes = pmdvertex_size; // 1頂点あたりのバイト数
vector<unsigned short> indices(indicesNum); // インデックス用バッファ
fread(indices.data(), indices.size() * sizeof(indices[0]), 1, fp);
auto resDescBuf = CD3DX12_RESOURCE_DESC::Buffer(indices.size() * sizeof(indices[0]));
// 設定は、バッファのサイズ以外頂点バッファの設定を使いまわしてOKだと思われる
result = _dx12.Device()->CreateCommittedResource(
&heapProp,
D3D12_HEAP_FLAG_NONE,
&resDescBuf,
D3D12_RESOURCE_STATE_GENERIC_READ,
nullptr,
IID_PPV_ARGS(_ib.ReleaseAndGetAddressOf())
);
// 作ったバッファにインデックスデータをコピー
unsigned short* mappedIdx = nullptr;
_ib->Map(0, nullptr, (void**)&mappedIdx);
std::copy(indices.begin(), indices.end(), mappedIdx);
_ib->Unmap(0, nullptr);
// インデックスバッファビューを作成
_ibView.BufferLocation = _ib->GetGPUVirtualAddress();
_ibView.Format = DXGI_FORMAT_R16_UINT;
_ibView.SizeInBytes = static_cast<UINT>(indices.size() * sizeof(indices[0]));
unsigned int materialNum;
fread(&materialNum, sizeof(materialNum), 1, fp);
_materials.resize(materialNum);
_textureResources.resize(materialNum);
_sphResources.resize(materialNum);
_spaResources.resize(materialNum);
_toonResources.resize(materialNum);
vector<PMDMaterial> pmdMaterials(materialNum);
fread(pmdMaterials.data(), pmdMaterials.size() * sizeof(PMDMaterial), 1, fp);
// コピー
for (UINT i = 0; i < pmdMaterials.size(); i++) {
_materials[i].indicesNum = pmdMaterials[i].indicesNum;
_materials[i].material.diffuse = pmdMaterials[i].diffuse;
_materials[i].material.alpha = pmdMaterials[i].alpha;
_materials[i].material.specular = pmdMaterials[i].specular;
_materials[i].material.specularity = pmdMaterials[i].specularity;
_materials[i].material.ambient = pmdMaterials[i].ambient;
}
for (UINT i = 0; i < pmdMaterials.size(); i++) {
// トゥーンリソースの読み込み
string toonFilePath = "toon/";
char toonFileName[16];
sprintf_s(toonFileName, 16, "toon%02d.bmp", pmdMaterials[i].toonIdx + 1);
toonFilePath += toonFileName;
_toonResources[i] = _dx12.GetTextureByPath(toonFilePath.c_str());
_textureResources[i] = nullptr;
_sphResources[i] = nullptr;
_spaResources[i] = nullptr;
if (strlen(pmdMaterials[i].texFilePath) == 0) {
continue;
}
string texFileName = pmdMaterials[i].texFilePath;
string sphFileName = "";
string spaFileName = "";
if (count(texFileName.begin(), texFileName.end(), '*') > 0) {
// スプリッタがある
auto namepair = SplitFileName(texFileName);
auto firstExt = GetExtension(namepair.first);
if (firstExt == "sph") {
texFileName = namepair.second;
sphFileName = namepair.first;
}
else if (firstExt == "spa") {
texFileName = namepair.second;
spaFileName = namepair.first;
}
else {
texFileName = namepair.first;
auto secondExt = GetExtension(namepair.second);
if (secondExt == "sph") {
sphFileName = namepair.second;
}
else if (secondExt == "spa") {
spaFileName = namepair.second;
}
}
}
else {
auto ext = GetExtension(texFileName);
if (ext == "sph") {
sphFileName = pmdMaterials[i].texFilePath;
texFileName = "";
}
else if (ext == "spa") {
spaFileName = pmdMaterials[i].texFilePath;
texFileName = "";
}
else {
texFileName = pmdMaterials[i].texFilePath;
}
}
if (texFileName != "") {
auto texFilePath = GetTexturePathFromModelAndTexPath(strModelPath, texFileName.c_str());
_textureResources[i] = _dx12.GetTextureByPath(texFilePath.c_str());
}
if (sphFileName != "") {
auto sphFilePath = GetTexturePathFromModelAndTexPath(strModelPath, sphFileName.c_str());
_sphResources[i] = _dx12.GetTextureByPath(sphFilePath.c_str());
}
if (spaFileName != "") {
auto spaFilePath = GetTexturePathFromModelAndTexPath(strModelPath, spaFileName.c_str());
_spaResources[i] = _dx12.GetTextureByPath(spaFilePath.c_str());
}
}
UINT16 boneNum = 0;
fread(&boneNum, sizeof(boneNum), 1, fp);
#pragma pack(1)
// 読み込み用ボーン構造体
struct PMDBone {
char boneName[20]; // ボーン名
UINT16 parentNo; // 親ボーン番号
UINT16 nextNo; // 先端のボーン番号
UINT8 type; // ボーン種別
UINT16 ikBoneNo; // IKボーン番号
XMFLOAT3 pos; // ボーンの基準点座標
};
#pragma pack() // 1バイトパッキング解除
vector<PMDBone> pmdBones(boneNum);
fread(pmdBones.data(), sizeof(PMDBone), boneNum, fp);
uint16_t ikNum = 0;
fread(&ikNum, sizeof(ikNum), 1, fp);
_ikData.resize(ikNum);
for (auto& ik : _ikData) {
fread(&ik.boneIdx, sizeof(ik.boneIdx), 1, fp);
fread(&ik.targetIdx, sizeof(ik.targetIdx), 1, fp);
uint8_t chainLen = 0;
fread(&chainLen, sizeof(chainLen), 1, fp);
ik.nodeIdxes.resize(chainLen);
fread(&ik.iterations, sizeof(ik.iterations), 1, fp);
fread(&ik.limit, sizeof(ik.limit), 1, fp);
if (chainLen == 0)
continue;
fread(ik.nodeIdxes.data(), sizeof(ik.nodeIdxes[0]), chainLen, fp);
}
fclose(fp);
// インデックスと名前の対応関係構築のために後で使う
vector<string> boneNames(pmdBones.size());
_boneNameArray.resize(pmdBones.size());
_boneNodeAddressArray.resize(pmdBones.size());
// ボーンノードマップを作る
for (int idx = 0; idx < pmdBones.size(); ++idx) {
auto& pb = pmdBones[idx];
boneNames[idx] = pb.boneName;
auto& node = _boneNodeTable[pb.boneName];
node.boneIdx = idx;
node.startPos = pb.pos;
node.boneType = pb.type;
node.parentBone = pb.parentNo;
node.ikParentBone = pb.ikBoneNo;
_boneNameArray[idx] = pb.boneName;
_boneNodeAddressArray[idx] = &node;
string boneName = pb.boneName;
if (boneName.find("ひざ") != std::string::npos) {
_kneeIdxes.emplace_back(idx);
}
}
// 親子関係を構築する
for (auto& pb : pmdBones) {
if (pb.parentNo >= pmdBones.size()) {
continue;
}
auto parentName = boneNames[pb.parentNo];
_boneNodeTable[parentName].children.emplace_back(&_boneNodeTable[pb.boneName]);
}
_boneMatrices.resize(pmdBones.size());
// ボーンをすべて初期化
std::fill(_boneMatrices.begin(), _boneMatrices.end(), XMMatrixIdentity());
return S_OK;
}
HRESULT PMDActor::CreateTransformView()
{
// GPUバッファ作成
auto buffSize = sizeof(XMMATRIX) * (1 + _boneMatrices.size());
buffSize = (buffSize + 0xff) & ~0xFF;
auto heapProp = CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD);
auto resDesc = CD3DX12_RESOURCE_DESC::Buffer(buffSize);
auto result = _dx12.Device()->CreateCommittedResource(
&heapProp,
D3D12_HEAP_FLAG_NONE,
&resDesc,
D3D12_RESOURCE_STATE_GENERIC_READ,
nullptr,
IID_PPV_ARGS(_transformBuff.ReleaseAndGetAddressOf())
);
if (FAILED(result)) {
assert(SUCCEEDED(result));
return result;
}
// マップとコピー
result = _transformBuff->Map(0, nullptr, (void**)&_mappedMatrices);
if (FAILED(result)) {
assert(SUCCEEDED(result));
return result;
}
_mappedMatrices[0] = _transform.world;
auto armNode = _boneNodeTable["左腕"];
auto& armPos = armNode.startPos;
auto armMat = XMMatrixTranslation(-armPos.x, -armPos.y, -armPos.z)
* XMMatrixRotationZ(XM_PIDIV2)
* XMMatrixTranslation(armPos.x, armPos.y, armPos.z);
auto elbowNode = _boneNodeTable["左ひじ"];
auto& elbowPos = elbowNode.startPos;
auto elbowMat = XMMatrixTranslation(-elbowPos.x, -elbowPos.y, -elbowPos.z)
* XMMatrixRotationZ(-XM_PIDIV2)
* XMMatrixTranslation(elbowPos.x, elbowPos.y, elbowPos.z);
_boneMatrices[armNode.boneIdx] = armMat;
_boneMatrices[elbowNode.boneIdx] = elbowMat;
auto ident = XMMatrixIdentity();
RecursiveMatrixMultiply(&_boneNodeTable["センター"], ident);
std::copy(_boneMatrices.begin(), _boneMatrices.end(), _mappedMatrices + 1);
// ビューの作成
D3D12_DESCRIPTOR_HEAP_DESC transformDescHeapDesc = {};
transformDescHeapDesc.NumDescriptors = 1; // とりあえずワールドひとつ
transformDescHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
transformDescHeapDesc.NodeMask = 0;
transformDescHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; // デスクリプタヒープ種別
// 生成
result = _dx12.Device()->CreateDescriptorHeap(&transformDescHeapDesc, IID_PPV_ARGS(_transformHeap.ReleaseAndGetAddressOf()));
if (FAILED(result)) {
assert(SUCCEEDED(result));
return result;
}
D3D12_CONSTANT_BUFFER_VIEW_DESC cbvDesc = {};
cbvDesc.BufferLocation = _transformBuff->GetGPUVirtualAddress();
cbvDesc.SizeInBytes = static_cast<UINT>(buffSize);
_dx12.Device()->CreateConstantBufferView(&cbvDesc, _transformHeap->GetCPUDescriptorHandleForHeapStart());
return S_OK;
}
void PMDActor::RecursiveMatrixMultiply(BoneNode* node, const DirectX::XMMATRIX& mat, bool flg)
{
if (node == nullptr)
return;
_boneMatrices[node->boneIdx] *= mat;
for (auto& cnode : node->children) {
RecursiveMatrixMultiply(cnode, _boneMatrices[node->boneIdx]);
}
}
HRESULT PMDActor::CreateMaterialData()
{
// マテリアルバッファを作成
auto materialBuffSize = sizeof(MaterialForHlsl);
materialBuffSize = (materialBuffSize + 0xff) & ~0xFF;
auto heapProp = CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD);
auto resDesc = CD3DX12_RESOURCE_DESC::Buffer(materialBuffSize * _materials.size());
auto result = _dx12.Device()->CreateCommittedResource(
&heapProp,
D3D12_HEAP_FLAG_NONE,
&resDesc,
D3D12_RESOURCE_STATE_GENERIC_READ,
nullptr,
IID_PPV_ARGS(_materialBuff.ReleaseAndGetAddressOf())
);
if (FAILED(result)) {
assert(SUCCEEDED(result));
return result;
}
// マップマテリアルにコピー
char* mapMaterial = nullptr;
result = _materialBuff->Map(0, nullptr, (void**)&mapMaterial);
if (FAILED(result)) {
assert(SUCCEEDED(result));
return result;
}
for (auto& m : _materials) {
*((MaterialForHlsl*)mapMaterial) = m.material; // データコピー
mapMaterial += materialBuffSize; // 次のアライメント位置まで進める
}
_materialBuff->Unmap(0, nullptr);
return S_OK;
}
HRESULT PMDActor::CreateMaterialAndTextureView()
{
D3D12_DESCRIPTOR_HEAP_DESC materialDescHeapDesc = {};
materialDescHeapDesc.NumDescriptors = static_cast<UINT>(_materials.size() * 5); // マテリアル数 x5(定数、基本テクスチャ、sph、spa、toon)
materialDescHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
materialDescHeapDesc.NodeMask = 0;
materialDescHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; // デスクリプタヒープ種別
auto result = _dx12.Device()->CreateDescriptorHeap(&materialDescHeapDesc, IID_PPV_ARGS(_materialHeap.ReleaseAndGetAddressOf()));
if (FAILED(result)) {
assert(SUCCEEDED(result));
return result;
}
// マテリアルビューの作成
auto materialBuffSize = sizeof(MaterialForHlsl);
materialBuffSize = (materialBuffSize + 0xff) & ~0xFF;
D3D12_CONSTANT_BUFFER_VIEW_DESC matCBVDesc = {};
matCBVDesc.BufferLocation = _materialBuff->GetGPUVirtualAddress(); // バッファーアドレス
matCBVDesc.SizeInBytes = static_cast<UINT>(materialBuffSize); // マテリアルの256アライメントサイズ
// 通常テクスチャビュー作成
D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {};
srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; // 後述
srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; // 2Dテクスチャ
srvDesc.Texture2D.MipLevels = 1; // ミップマップは使用しないので1
srvDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; // デフォルト
CD3DX12_CPU_DESCRIPTOR_HANDLE matDescHeapH(_materialHeap->GetCPUDescriptorHandleForHeapStart()); // 先頭を記録
auto incSize = _dx12.Device()->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
for (UINT i = 0; i < _materials.size(); i++) {
// マテリアル用定数バッファービュー
_dx12.Device()->CreateConstantBufferView(&matCBVDesc, matDescHeapH);
matDescHeapH.ptr += incSize;
matCBVDesc.BufferLocation += materialBuffSize;
// シェーダーリソースビュー
// テクスチャが空の場合は白テクスチャを使う
auto texResource = _textureResources[i] == nullptr ? _renderer._whiteTex : _textureResources[i];
srvDesc.Format = texResource->GetDesc().Format;
_dx12.Device()->CreateShaderResourceView(texResource.Get(), &srvDesc, matDescHeapH);
matDescHeapH.ptr += incSize;
// スフィア
auto sphResource = _sphResources[i] == nullptr ? _renderer._whiteTex : _sphResources[i];
srvDesc.Format = sphResource->GetDesc().Format;
_dx12.Device()->CreateShaderResourceView(sphResource.Get(), &srvDesc, matDescHeapH);
matDescHeapH.ptr += incSize;
auto spaResource = _spaResources[i] == nullptr ? _renderer._blackTex : _spaResources[i];
srvDesc.Format = spaResource->GetDesc().Format;
_dx12.Device()->CreateShaderResourceView(spaResource.Get(), &srvDesc, matDescHeapH);
matDescHeapH.ptr += incSize;
auto toonResource = _toonResources[i] == nullptr ? _renderer._gradTex : _toonResources[i];
srvDesc.Format = toonResource->GetDesc().Format;
_dx12.Device()->CreateShaderResourceView(toonResource.Get(), &srvDesc, matDescHeapH);
matDescHeapH.ptr += incSize;
}
return S_OK;
}
void PMDActor::Update()
{
_angle += 0.001f;
_mappedMatrices[0] = XMMatrixRotationY(_angle);
MotionUpdate();
}
void PMDActor::Draw()
{
_dx12.CommandList()->IASetVertexBuffers(0, 1, &_vbView);
_dx12.CommandList()->IASetIndexBuffer(&_ibView);
ID3D12DescriptorHeap* transheaps[] = { _transformHeap.Get() };
_dx12.CommandList()->SetDescriptorHeaps(1, transheaps);
_dx12.CommandList()->SetGraphicsRootDescriptorTable(1, _transformHeap->GetGPUDescriptorHandleForHeapStart());
ID3D12DescriptorHeap* mdh[] = { _materialHeap.Get() };
_dx12.CommandList()->SetDescriptorHeaps(1, mdh);
auto materialH = _materialHeap->GetGPUDescriptorHandleForHeapStart();
auto cbvSrvIncSize = _dx12.Device()->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) * 5;
UINT idxOffset = 0;
for (auto& m : _materials) {
_dx12.CommandList()->SetGraphicsRootDescriptorTable(2, materialH);
_dx12.CommandList()->DrawIndexedInstanced(m.indicesNum, 1, idxOffset, 0, 0);
materialH.ptr += cbvSrvIncSize;
idxOffset += m.indicesNum;
}
}
| 31.62406 | 141 | 0.714099 | [
"vector",
"transform"
] |
922cde2e3ec5016d7abed7e8010dbe99d53889c8 | 2,643 | cc | C++ | runtime/onert/backend/cpu/ops/SplitLayer.cc | krayzemli/ONE | b7b646825f0673415e7c14faf388c863210da052 | [
"Apache-2.0"
] | null | null | null | runtime/onert/backend/cpu/ops/SplitLayer.cc | krayzemli/ONE | b7b646825f0673415e7c14faf388c863210da052 | [
"Apache-2.0"
] | 1 | 2020-09-23T23:12:23.000Z | 2020-09-23T23:20:34.000Z | runtime/onert/backend/cpu/ops/SplitLayer.cc | krayzemli/ONE | b7b646825f0673415e7c14faf388c863210da052 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2020 Samsung Electronics Co., Ltd. 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 "SplitLayer.h"
#include "OperationUtils.h"
#include <cker/operation/Split.h>
namespace onert
{
namespace backend
{
namespace cpu
{
namespace ops
{
SplitLayer::SplitLayer() : _input(nullptr), _axis(nullptr), _num_splits(0), _outputs()
{
// DO NOTHING
}
template <typename T> void SplitLayer::split(void)
{
nnfw::cker::SplitParams op_params;
if (_axis->total_size() != sizeof(int32_t))
{
throw std::runtime_error("ArgMinMax: wrong shape of axis");
}
auto axis = *reinterpret_cast<const int32_t *>(_axis->buffer());
if (axis < 0)
{
axis += _input->num_dimensions();
}
op_params.axis = axis;
op_params.num_split = _num_splits;
std::vector<T *> outputPtrs;
for (const auto output : _outputs)
{
assert(output->total_size() == sizeOfData(output->data_type(), output->getShape().dims()));
outputPtrs.emplace_back(reinterpret_cast<T *>(output->buffer()));
}
assert(_input->total_size() == sizeOfData(_input->data_type(), _input->getShape().dims()));
nnfw::cker::Split<T>(op_params, getTensorShape(_input), reinterpret_cast<T *>(_input->buffer()),
getTensorShape(_outputs[0]), outputPtrs.data());
}
void SplitLayer::configure(const IPortableTensor *input, const IPortableTensor *axis,
uint16_t num_splits, std::vector<IPortableTensor *> &outputs)
{
assert(input != nullptr);
_num_splits = num_splits;
_input = input;
_axis = axis;
_outputs = outputs;
}
void SplitLayer::run()
{
if (_input->data_type() == OperandType::FLOAT32)
{
split<float>();
}
else if (_input->data_type() == OperandType::QUANT_UINT8_ASYMM)
{
split<uint8_t>();
}
else if (_input->data_type() == OperandType::INT32)
{
split<int32_t>();
}
else if (_input->data_type() == OperandType::INT64)
{
split<int64_t>();
}
else
{
throw std::runtime_error{"Split: unsupported input type"};
}
}
} // namespace ops
} // namespace cpu
} // namespace backend
} // namespace onert
| 25.413462 | 98 | 0.676504 | [
"shape",
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.