hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
48.5k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5489bc4061d37a20d9b00ce63970cd8ac0643d5e
| 6,638
|
cpp
|
C++
|
gui/shapes/Rect.cpp
|
TrapGameStudio/MouseTraps
|
1160f8b6ef865b180f418bd6d83f40d59d938130
|
[
"MIT"
] | null | null | null |
gui/shapes/Rect.cpp
|
TrapGameStudio/MouseTraps
|
1160f8b6ef865b180f418bd6d83f40d59d938130
|
[
"MIT"
] | null | null | null |
gui/shapes/Rect.cpp
|
TrapGameStudio/MouseTraps
|
1160f8b6ef865b180f418bd6d83f40d59d938130
|
[
"MIT"
] | 1
|
2020-04-19T23:20:25.000Z
|
2020-04-19T23:20:25.000Z
|
#include "Rect.h"
/// <summary>
/// Non top-left anchor shapes are hard to draw, so there is a absolute representation
/// which is converted from the user defined anchor and location to the equivalent
/// coordinate as if the shape is using a top-left anchor. I tried to convert negative
/// size, but that is too much to deal with so I just convert negative size values to
/// their absolute values.
/// </summary>
void Rect::updateAbsoluteRepresentation() {
absoluteSize->setTo(size);
absoluteSize->setX(absoluteSize->getX() * scalingFactor->getX());
absoluteSize->setY(absoluteSize->getY() * scalingFactor->getY());
topLeft->setTo(anchorLocation);
if (size->getX() < 0.0f) {
absoluteSize->setX(-(size->getX()));
}
if (size->getY() < 0.0f) {
absoluteSize->setY(-(size->getY()));
}
switch (anchor) {
case Top:
topLeft->addX(-0.5f * absoluteSize->getX());
break;
case TopRight:
topLeft->addX(-absoluteSize->getX());
break;
case Left:
topLeft->addY(0.5f * absoluteSize->getY());
break;
case Center:
topLeft->addX(-0.5f * absoluteSize->getX());
topLeft->addY(0.5f * absoluteSize->getY());
break;
case Right:
topLeft->addX(-absoluteSize->getX());
topLeft->addY(0.5f * absoluteSize->getY());
break;
case BottomLeft:
topLeft->addY(absoluteSize->getY());
break;
case Bottom:
topLeft->addX(-0.5f * absoluteSize->getX());
topLeft->addY(absoluteSize->getY());
break;
case BottomRight:
topLeft->addX(-absoluteSize->getX());
topLeft->addY(absoluteSize->getY());
}
}
/// <summary>
/// Constructor for builder use only.
/// </summary>
Rect::Rect() {
this->absoluteSize = this->size->deepCopy();
this->topLeft = this->anchorLocation->deepCopy();
updateAbsoluteRepresentation();
}
// TODO: make anchorLocation and color sink parameters
/// <summary>
/// Create a rectangle with specific value.
/// </summary>
/// <param name="size">size of the rectangle in window coordinate</param>
/// <param name="anchor">anchor type. <see cref="Anchor" /></param>
/// <param name="anchorLocation">
/// the location of the anchor of the rectangle in window coordinate.
/// This is a not a sink parameter.
/// </param>
/// <param name="color">
/// color of the rectangle.
/// This is not a skin parameter.
/// </param>
Rect::Rect(Vector* size, Anchor anchor, Point* anchorLocation, Color* color) {
this->anchor = anchor;
if (anchorLocation) { this->anchorLocation->setTo(anchorLocation); }
if (size) { this->size->setTo(size); }
if (color) { this->color->setTo(color); }
this->absoluteSize = this->size->deepCopy();
this->topLeft = this->anchorLocation->deepCopy();
updateAbsoluteRepresentation();
}
void Rect::draw() {
glPushMatrix();
glDepthMask(GL_FALSE);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glColor4f(
color->getR(),
color->getG(),
color->getB(),
color->getA()
);
glBegin(GL_QUADS);
glVertex2f(topLeft->getX(), topLeft->getY());
glVertex2f(topLeft->getX() + absoluteSize->getX(), topLeft->getY());
glVertex2f(topLeft->getX() + absoluteSize->getX(), topLeft->getY() - absoluteSize->getY());
glVertex2f(topLeft->getX(), topLeft->getY() - absoluteSize->getY());
glEnd();
glDisable(GL_BLEND);
glDepthMask(GL_TRUE);
glPopMatrix();
}
/// <summary>
/// Moving the shape by a specific amount.
/// </summary>
/// <param name="dx">distance to move in the x direction</param>
/// <param name="dy">distance to move in the y direction</param>
void Rect::move(float dx, float dy) {
anchorLocation->add(dx, dy);
updateAbsoluteRepresentation();
}
/// <summary>
/// Check if a point (x, y) is within this shape.
/// </summary>
/// <param name="x">x coordinate of the point to check</param>
/// <param name="y">y coordinate of the point to check</param>
/// <returns></returns>
bool Rect::contains(float x, float y) {
return (x >= topLeft->getX()
&& x <= topLeft->getX() + absoluteSize->getX()
&& y <= topLeft->getY()
&& y >= topLeft->getY() - absoluteSize->getY());
}
Rect::~Rect() {
delete size;
delete anchorLocation;
delete color;
delete absoluteSize;
delete topLeft;
}
Rect::Builder Rect::builder() {
return Rect::Builder();
}
/// <summary>
/// Magnify or shrink the size of the rectangle by specific magnitude.
/// </summary>
void Rect::zoom(float magnitude) {
scalingFactor->multiply(magnitude);
updateAbsoluteRepresentation();
}
/// <summary>
/// Change the aspect ratio of this rectangle.
/// </summary>
void Rect::scale(float x, float y) {
this->scalingFactor->setTo(x, y);
updateAbsoluteRepresentation();
}
/// <summary>
/// Set the size of the rectangle with the value specified by a Vector
/// </summary>
/// <param name="size">
/// size to set.
/// This is not a sink parameter.
/// </param>
void Rect::setSize(Vector * size) {
this->size->setTo(size);
updateAbsoluteRepresentation();
}
void Rect::setSize(float x, float y) {
size->setX(x);
size->setY(y);
updateAbsoluteRepresentation();
}
Vector * const Rect::getSize() const {
return this->size;
}
void Rect::setAnchorLocation(float x, float y) {
anchorLocation->setX(x);
anchorLocation->setY(y);
updateAbsoluteRepresentation();
}
void Rect::setAnchorLocation(Point * anchorLocation) {
this->anchorLocation->setTo(anchorLocation);
updateAbsoluteRepresentation();
}
Point* const Rect::getAnchorLocation() const {
return this->anchorLocation;
}
void Rect::setAnchor(Anchor anchor) {
this->anchor = anchor;
updateAbsoluteRepresentation();
}
Anchor Rect::getAnchor() const {
return this->anchor;
}
Point * const Rect::getTopLeft() const {
return topLeft;
}
void Rect::setColor(Color * color) {
this->color->setTo(color);
}
Color* const Rect::getColor() const {
return this->color;
}
Rect::Builder & Rect::Builder::ofSize(Vector* size) {
delete building->size;
building->size = size;
return *this;
}
Rect::Builder & Rect::Builder::ofSize(float x, float y) {
building->size->setTo(x, y);
return *this;
}
Rect::Builder & Rect::Builder::atLocation(float x, float y) {
building->anchorLocation->setTo(x, y);
return *this;
}
Rect::Builder & Rect::Builder::atLocation(Point * anchorLocation) {
delete building->anchorLocation;
building->anchorLocation = anchorLocation;
return *this;
}
Rect::Builder & Rect::Builder::onAnchor(Anchor anchor) {
building->anchor = anchor;
return *this;
}
Rect::Builder & Rect::Builder::ofColor(Color * color) {
delete building->color;
building->color = color;
return *this;
}
Rect * Rect::Builder::build() {
building->updateAbsoluteRepresentation();
return building;
}
Rect::Builder::~Builder() {}
| 25.049057
| 95
| 0.679271
|
TrapGameStudio
|
5492500a037577e2aee33d1952ea23d1b496ae76
| 887
|
cpp
|
C++
|
The Adventures of Aladdin/apple.cpp
|
AkeelMedina22/The-Adventures-of-Aladdin
|
35954db21cc5fa16617334f8cfb7c7dac0949a59
|
[
"MIT"
] | null | null | null |
The Adventures of Aladdin/apple.cpp
|
AkeelMedina22/The-Adventures-of-Aladdin
|
35954db21cc5fa16617334f8cfb7c7dac0949a59
|
[
"MIT"
] | null | null | null |
The Adventures of Aladdin/apple.cpp
|
AkeelMedina22/The-Adventures-of-Aladdin
|
35954db21cc5fa16617334f8cfb7c7dac0949a59
|
[
"MIT"
] | null | null | null |
#include "apple.hpp"
#include <iostream>
Apple::Apple(SDL_Texture *asst):assets(asst)
{
mover = {900, 540, 35, 35};
//health =1;
}
void Apple::draw(SDL_Renderer* gRenderer)
{
SDL_RenderCopy(gRenderer, assets, &src, &mover); //crashes at this line
//SDL_RenderCopyEx(gRenderer, assets, &src, &mover, 0, NULL, SDL_FLIP_NONE);
}
void Apple::move(SDL_RendererFlip flip, bool flag3)
{
if (flag3==true) //when key is indeed pressed
{
if (flip==SDL_FLIP_NONE)
{
mover.x-=20;
}
else if (flip==SDL_FLIP_HORIZONTAL)
{
mover.x+=20;
}
}
}
char Apple::name()
{
return 'P';
}
void Apple::setMove(int x)
{
mover.x = x;
}
void Apple::createOutFile(std::ostream &myfile)
{
myfile << name() << std::endl;
myfile << mover.x <<std::endl;
}
| 19.282609
| 81
| 0.554679
|
AkeelMedina22
|
54992dfbb246a4767b290e9cf0168181edfa74d2
| 1,707
|
cpp
|
C++
|
main.cpp
|
Druggist/arkanoid-3d-opengl
|
df67234723379aa20cdee9337ed7dbcc65f6e442
|
[
"MIT"
] | null | null | null |
main.cpp
|
Druggist/arkanoid-3d-opengl
|
df67234723379aa20cdee9337ed7dbcc65f6e442
|
[
"MIT"
] | null | null | null |
main.cpp
|
Druggist/arkanoid-3d-opengl
|
df67234723379aa20cdee9337ed7dbcc65f6e442
|
[
"MIT"
] | null | null | null |
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include "constants.h"
#include "game.h"
Game Arkanoid;
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode){
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) glfwSetWindowShouldClose(window, GL_TRUE);
if (key >= 0 && key < 1024) {
if (action == GLFW_PRESS) Arkanoid.Keys[key] = GL_TRUE;
else if (action == GLFW_RELEASE) Arkanoid.Keys[key] = GL_FALSE;
}
}
void error_callback(int error, const char* description) {
fputs(description, stderr);
}
int main(int argc, char const *argv[]) {
GLFWwindow* window;
glfwSetErrorCallback(error_callback);
if (!glfwInit()) {
fprintf(stderr, "Cannot initialize GLFW.\n");
exit(EXIT_FAILURE);
}
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
window = glfwCreateWindow(SCREEN_WIDTH, SCREEN_HEIGHT, "Arkanoid", NULL, NULL);
if (!window) {
fprintf(stderr, "Cannot create a window.\n");
glfwTerminate();
exit(EXIT_FAILURE);
}
glfwMakeContextCurrent(window);
glfwSwapInterval(1);
if (glewInit() != GLEW_OK) {
fprintf(stderr, "Cannot initialize GLEW.\n");
exit(EXIT_FAILURE);
}
glfwSetKeyCallback(window, key_callback);
Arkanoid.Init();
GLfloat dt = 0.0f;
GLfloat lf = 0.0f;
while(!glfwWindowShouldClose(window)) {
GLfloat cf = glfwGetTime();
dt = cf - lf;
lf = cf;
glfwPollEvents();
Arkanoid.ProcessInput(dt);
Arkanoid.Update(dt);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
Arkanoid.Render();
glfwSwapBuffers(window);
}
glfwTerminate();
return 0;
}
| 21.884615
| 95
| 0.71529
|
Druggist
|
549da7fd12822d1e9257854c8746462d34e93629
| 518
|
cpp
|
C++
|
OXGame/Game Design/StageMenu.cpp
|
kreuwont/OXGame
|
6de134161f2bb67c09c99f52b2ec966c31aed4fd
|
[
"MIT"
] | null | null | null |
OXGame/Game Design/StageMenu.cpp
|
kreuwont/OXGame
|
6de134161f2bb67c09c99f52b2ec966c31aed4fd
|
[
"MIT"
] | null | null | null |
OXGame/Game Design/StageMenu.cpp
|
kreuwont/OXGame
|
6de134161f2bb67c09c99f52b2ec966c31aed4fd
|
[
"MIT"
] | null | null | null |
#include "stdh.h"
#include "Game.h"
#include "..\Interface\UIManager.h"
#include "StageMenu.h"
#include "..\Interface\UIMenu.h"
#include "..\Interface\UIRoomSettings.h"
void StageMenu::Init()
{
UIManager* pUIManager = UIManager::getSingleton();
GameManager* pManager = GameManager::getSingleton();
pUIManager->GetMenu()->OpenUI();
if (!pManager->GameActive())
pManager->GameLoop();
}
void StageMenu::Release()
{
UIManager* pUIManager = UIManager::getSingleton();
pUIManager->GetRoomSettings()->CloseUI();
}
| 22.521739
| 53
| 0.716216
|
kreuwont
|
549dfff473b7957f7e0036345498c0eeb73e4ed5
| 7,778
|
cc
|
C++
|
Root/PruningUtil.cc
|
liboyang0112/TRExFitter
|
052e56162de0c31259e70aeff846dce634a40602
|
[
"BSD-2-Clause"
] | null | null | null |
Root/PruningUtil.cc
|
liboyang0112/TRExFitter
|
052e56162de0c31259e70aeff846dce634a40602
|
[
"BSD-2-Clause"
] | null | null | null |
Root/PruningUtil.cc
|
liboyang0112/TRExFitter
|
052e56162de0c31259e70aeff846dce634a40602
|
[
"BSD-2-Clause"
] | null | null | null |
// Class include
#include "TRExFitter/PruningUtil.h"
#include "TRExFitter/Common.h"
// C++ includes
#include <memory>
// -------------------------------------------------------------------------------------------------
// class PruningUtil
//__________________________________________________________________________________
//
PruningUtil::PruningUtil() :
fStrategy(0),
fShapeOption(PruningUtil::SHAPEOPTION::MAXBIN),
fThresholdNorm(-1),
fThresholdShape(-1),
fThresholdIsLarge(-1),
fRemoveLargeSyst(true),
fRemoveSystOnEmptySample(false)
{
}
//__________________________________________________________________________________
//
void PruningUtil::SetStrategy(const int strat) {
fStrategy = strat;
}
//__________________________________________________________________________________
//
void PruningUtil::SetShapeOption(const PruningUtil::SHAPEOPTION opt) {
fShapeOption = opt;
}
//__________________________________________________________________________________
//
void PruningUtil::SetThresholdNorm(const double thres) {
fThresholdNorm = thres;
}
//__________________________________________________________________________________
//
void PruningUtil::SetThresholdShape(const double thres) {
fThresholdShape = thres;
}
//__________________________________________________________________________________
//
void PruningUtil::SetThresholdIsLarge(const double thres) {
fThresholdIsLarge = thres;
}
//__________________________________________________________________________________
//
void PruningUtil::SetRemoveLargeSyst(const bool flag) {
fRemoveLargeSyst = flag;
}
//__________________________________________________________________________________
//
void PruningUtil::SetRemoveSystOnEmptySample(const bool flag) {
fRemoveSystOnEmptySample = flag;
}
//__________________________________________________________________________________
//
int PruningUtil::CheckSystPruning(const TH1* const hUp,
const TH1* const hDown,
const TH1* const hNom,
const TH1* hTot) {
if(fStrategy!=0 && hTot==nullptr){
std::cout << "PruningUtil::ERROR: hTot set to 0 while asking for relative pruning... Reverting to sample-by-sample pruning." << std::endl;
fStrategy = 0;
}
std::unique_ptr<TH1> hRef = nullptr;
if(fStrategy==0) hRef = std::unique_ptr<TH1>(static_cast<TH1*>(hNom->Clone()));
else hRef = std::unique_ptr<TH1>(static_cast<TH1*>(hTot->Clone()));
int res = 0;
// create shape-only syst variations
std::unique_ptr<TH1> hShapeUp = nullptr;
if(hUp) hShapeUp = std::unique_ptr<TH1>(static_cast<TH1*>(hUp ->Clone(Form("%s_shape",hUp ->GetName()))));
if(hShapeUp) hShapeUp->Scale( Common::EffIntegral(hNom)/Common::EffIntegral(hShapeUp.get()) );
std::unique_ptr<TH1> hShapeDown = nullptr;
if(hDown) hShapeDown = std::unique_ptr<TH1>(static_cast<TH1*>(hDown->Clone(Form("%s_shape",hDown->GetName()))));
if(hShapeDown) hShapeDown->Scale( Common::EffIntegral(hNom)/Common::EffIntegral(hShapeDown.get()) );
// get norm effects
const double normUp = std::fabs((Common::EffIntegral(hUp )-Common::EffIntegral(hNom))/Common::EffIntegral(hRef.get()));
const double normDown = std::fabs((Common::EffIntegral(hDown)-Common::EffIntegral(hNom))/Common::EffIntegral(hRef.get()));
const double normNom = Common::EffIntegral(hNom);
// check if systematic has no shape --> 1
bool hasShape(true);
if(fThresholdShape>=0) {
if (fShapeOption == PruningUtil::SHAPEOPTION::MAXBIN) {
hasShape = HasShapeRelative(hNom,hShapeUp.get(),hShapeDown.get(),hRef.get(),fThresholdShape);
}
if (fShapeOption == PruningUtil::SHAPEOPTION::KSTEST) {
hasShape = HasShapeKS(hNom,hShapeUp.get(),hShapeDown.get(),fThresholdShape);
}
}
// check if systematic norm effect is under threshold
bool hasNorm = true;
if(fThresholdNorm>=0) hasNorm = ((normUp >= fThresholdNorm) || (normDown >= fThresholdNorm));
// now check for crazy systematics
bool hasGoodShape = true;
bool hasGoodNorm = true;
if(fThresholdIsLarge>=0) {
if (fRemoveLargeSyst) {
if ((std::fabs(normUp) > fThresholdIsLarge) || (std::fabs(normDown) > fThresholdIsLarge)) {
hasShape = false;
hasNorm = false;
}
} else {
if (fShapeOption == PruningUtil::SHAPEOPTION::MAXBIN) {
hasGoodShape = !HasShapeRelative(hNom,hShapeUp.get(),hShapeDown.get(),hRef.get(),fThresholdIsLarge);
}
if (fShapeOption == PruningUtil::SHAPEOPTION::KSTEST) {
hasGoodShape = !HasShapeKS(hNom,hShapeUp.get(),hShapeDown.get(),fThresholdIsLarge);
}
hasGoodNorm = ((normUp <= fThresholdIsLarge) && (normDown <= fThresholdIsLarge));
}
}
if (fRemoveSystOnEmptySample) {
if (normNom < 1e-4) {
hasShape = false;
hasNorm = false;
}
}
if(!hasGoodShape && !hasGoodNorm) res = -4;
else if(!hasGoodShape) res = -3;
else if(!hasGoodNorm) res = -2;
else if(!hasShape && !hasNorm) res = 3;
else if(!hasShape) res = 1;
else if(!hasNorm) res = 2;
return res;
}
//_________________________________________________________________________
//
bool PruningUtil::HasShapeRelative(const TH1* const hNom,
const TH1* const hUp,
const TH1* const hDown,
const TH1* const combined,
const double threshold) const {
if (!hNom || !hUp || !hDown || !combined) return false;
if (hUp->GetNbinsX() == 1) return false;
const double& integralUp = hUp->Integral();
const double& integralDown = hDown->Integral();
const double& integralCombined = combined->Integral();
if ((integralUp != integralUp) || integralUp == 0) return false;
if ((integralDown != integralDown) || integralDown == 0) return false;
if ((integralCombined != integralCombined) || integralCombined == 0) return false;
bool hasShape = false;
for (int ibin = 1; ibin <= hUp->GetNbinsX(); ++ibin){
const double& nominal = hNom->GetBinContent(ibin);
if(nominal<0) continue;
const double& comb = combined->GetBinContent(ibin);
const double& up = hUp->GetBinContent(ibin);
const double& down = hDown->GetBinContent(ibin);
const double& up_err = std::fabs((up-nominal)/comb);
const double& down_err = std::fabs((down-nominal)/comb);
if(up_err>=threshold || down_err>=threshold){
hasShape = true;
break;
}
}
return hasShape;
}
//_________________________________________________________________________
//
bool PruningUtil::HasShapeKS(const TH1* const hNom,
const TH1* const hUp,
const TH1* const hDown,
const double threshold) const {
if (!hNom || !hUp || !hDown) return false;
if (hUp->GetNbinsX() == 1) return false;
if (std::abs(hUp->Integral()) < 1e-6) return true;
if (std::abs(hDown->Integral()) < 1e-6) return true;
const double probThreshold = 1 - threshold;
// first try up histogram
const double& upProb = hUp->KolmogorovTest(hNom, "X");
if (upProb <= probThreshold) {
return true;
}
// up is not significant, try down
const double& downProb = hDown->KolmogorovTest(hNom, "X");
if (downProb <= probThreshold) {
return true;
}
return false;
}
| 36.009259
| 146
| 0.64181
|
liboyang0112
|
54a50e92d2883d987d1ef80b8e0155fdf048a0f1
| 928
|
hpp
|
C++
|
src/Screen.hpp
|
Antonito/c8emu
|
2997b3dcbf25cba9364c80d3b6d5a85f43b199fe
|
[
"MIT"
] | null | null | null |
src/Screen.hpp
|
Antonito/c8emu
|
2997b3dcbf25cba9364c80d3b6d5a85f43b199fe
|
[
"MIT"
] | null | null | null |
src/Screen.hpp
|
Antonito/c8emu
|
2997b3dcbf25cba9364c80d3b6d5a85f43b199fe
|
[
"MIT"
] | null | null | null |
#pragma once
#include <SFML/Audio.hpp>
#include <SFML/Graphics.hpp>
#include <array>
namespace c8emu {
class Screen {
public:
Screen(std::uint32_t const width, std::uint32_t const height,
std::array<std::uint8_t, 0x800> const &gfx, std::array<bool, 16> &keys,
std::uint8_t const scaleFactor);
inline bool isOpen() const { return m_win.isOpen(); }
Screen(Screen const &) = delete;
Screen &operator=(Screen const &) = delete;
Screen(Screen &&) = delete;
Screen &operator=(Screen &&) = delete;
void gpuExec();
void getInputs();
void beep();
private:
std::uint32_t m_width;
std::uint32_t m_height;
sf::RenderWindow m_win;
sf::Texture m_texture;
sf::Sprite m_sprite;
std::unique_ptr<sf::Uint8[]> m_pix;
std::array<std::uint8_t, 0x800> const &m_gfx;
std::array<bool, 16> &m_keys;
sf::SoundBuffer m_soundBuff;
sf::Sound m_beep;
void loadBeep();
};
} // namespace c8emu
| 22.634146
| 80
| 0.672414
|
Antonito
|
54ab2a327565fb96afa48ba07573431d29e56942
| 2,001
|
inl
|
C++
|
Dev/Cpp/src/RendererGodot/Shaders/Model2D.inl
|
swimming92404/EffekseerForGodot3
|
abb890364b2f0f0853b7893b5ec484c525bc5513
|
[
"MIT"
] | 89
|
2021-02-17T04:06:54.000Z
|
2022-03-31T08:40:26.000Z
|
Dev/Cpp/src/RendererGodot/Shaders/Model2D.inl
|
swimming92404/EffekseerForGodot3
|
abb890364b2f0f0853b7893b5ec484c525bc5513
|
[
"MIT"
] | 9
|
2021-03-14T22:51:24.000Z
|
2022-03-29T21:24:14.000Z
|
Dev/Cpp/src/RendererGodot/Shaders/Model2D.inl
|
swimming92404/EffekseerForGodot3
|
abb890364b2f0f0853b7893b5ec484c525bc5513
|
[
"MIT"
] | 9
|
2021-03-05T06:21:34.000Z
|
2022-03-10T18:08:20.000Z
|
const char code[] =
#if !LIGHTING
R"(
render_mode unshaded;
)"
#endif
R"(
uniform mat4 ViewMatrix;
uniform mat4 ModelMatrix;
uniform vec4 ModelUV;
uniform vec4 ModelColor : hint_color;
)"
#if DISTORTION
R"(
uniform float DistortionIntensity;
uniform sampler2D DistortionTexture : hint_normal;
)"
#elif LIGHTING
R"(
uniform float EmissiveScale;
uniform sampler2D ColorTexture : hint_albedo;
uniform sampler2D NormalTexture : hint_normal;
)"
#else
R"(
uniform float EmissiveScale;
uniform sampler2D ColorTexture : hint_albedo;
)"
#endif
#include "Common2D.inl"
R"(
void vertex() {
UV = (UV.xy * ModelUV.zw) + ModelUV.xy;
COLOR = COLOR * ModelColor;
}
)"
R"(
void fragment() {
)"
#if DISTORTION
R"(
vec2 distortionUV = DistortionMap(DistortionTexture, UV, DistortionIntensity, COLOR.xy, vec2(1.0, 0.0));
COLOR = ColorMap(SCREEN_TEXTURE, SCREEN_UV + distortionUV, vec4(1.0, 1.0, 1.0, COLOR.a));
)"
#elif LIGHTING
R"(
NORMALMAP = NormalMap(NormalTexture, UV, vec2(1.0, 0.0));
COLOR = ColorMap(ColorTexture, UV, COLOR);
COLOR.rgb *= EmissiveScale;
)"
#else
R"(
COLOR = ColorMap(ColorTexture, UV, COLOR);
COLOR.rgb *= EmissiveScale;
)"
#endif
R"(
}
)";
const Shader::ParamDecl decl[] = {
//{ "ViewMatrix", Shader::ParamType::Matrix44, 0, 0 },
//{ "ModelMatrix", Shader::ParamType::Matrix44, 0, 64 },
{ "ModelUV", Shader::ParamType::Vector4, 0, 128 },
{ "ModelColor", Shader::ParamType::Vector4, 0, 144 },
#if DISTORTION
{ "DistortionIntensity", Shader::ParamType::Float, 1, 48 },
{ "DistortionTexture", Shader::ParamType::Texture, 0, 0 },
#elif LIGHTING
{ "EmissiveScale", Shader::ParamType::Float, 1, offsetof(EffekseerRenderer::PixelConstantBuffer, EmmisiveParam) },
{ "ColorTexture", Shader::ParamType::Texture, 0, 0 },
{ "NormalTexture", Shader::ParamType::Texture, 1, 0 },
#else
{ "EmissiveScale", Shader::ParamType::Float, 1, offsetof(EffekseerRenderer::PixelConstantBuffer, EmmisiveParam) },
{ "ColorTexture", Shader::ParamType::Texture, 0, 0 },
#endif
};
| 23.541176
| 115
| 0.703648
|
swimming92404
|
54b04987412002345d7c15d28c8b4b50d9d50b6b
| 13,970
|
cpp
|
C++
|
src/shape_signatures/heat_kernel_signature.cpp
|
josefgraus/self_similiarity
|
c032daa3009f60fdc8a52c437a07c6e3ba2efe4b
|
[
"MIT"
] | 1
|
2021-02-25T09:35:14.000Z
|
2021-02-25T09:35:14.000Z
|
src/shape_signatures/heat_kernel_signature.cpp
|
josefgraus/self_similarity
|
c032daa3009f60fdc8a52c437a07c6e3ba2efe4b
|
[
"MIT"
] | null | null | null |
src/shape_signatures/heat_kernel_signature.cpp
|
josefgraus/self_similarity
|
c032daa3009f60fdc8a52c437a07c6e3ba2efe4b
|
[
"MIT"
] | 2
|
2021-02-25T09:35:15.000Z
|
2021-08-12T13:26:38.000Z
|
#include "heat_kernel_signature.h"
#include <memory>
#include <exception>
#include <unsupported/Eigen/MatrixFunctions>
#include <cppoptlib/solver/lbfgsbsolver.h>
#include <geometry/patch.h>
#include <matching/threshold.h>
#include <matching/quadratic_bump.h>
#include <utilities/units.h>
#include <matching/constrained_relation_solver.h>
#include <matching/geodesic_fan.h>
struct HKSInstancer : public HeatKernelSignature {
HKSInstancer(std::shared_ptr<Mesh> mesh, int k) : HeatKernelSignature(mesh, k) {}
HKSInstancer(std::shared_ptr<Mesh> mesh, int steps, int k) : HeatKernelSignature(mesh, steps, k) {}
HKSInstancer(std::shared_ptr<Mesh> mesh, double tmin, double tmax, int k) : HeatKernelSignature(mesh, tmin, tmax, k) {}
HKSInstancer(std::shared_ptr<Mesh> mesh, double tmin, double tmax, int steps, int k) : HeatKernelSignature(mesh, tmin, tmax, steps, k) {}
};
HeatKernelSignature::HeatKernelSignature(std::shared_ptr<Mesh> mesh, int k):
SpectralSignature(std::make_shared<HKSParameterOptimization>(), mesh, k),
_t_steps(Eigen::VectorXd::Zero(0)) {
if (!mesh->loaded()) {
return;
}
double tmin = t_lower_bound();
double tmax = t_upper_bound();
int steps = eigenvalues().rows();
_t_steps = hks_steps(tmin, tmax, steps);
_sig = calculate_hks(_t_steps);
_exception_map = Eigen::MatrixXd::Zero(_sig.rows(), _sig.cols());
}
HeatKernelSignature::HeatKernelSignature(std::shared_ptr<Mesh> mesh, int steps, int k) :
SpectralSignature(std::make_shared<HKSParameterOptimization>(), mesh, k),
_t_steps(Eigen::VectorXd::Zero(0)) {
if (!mesh->loaded()) {
return;
}
double tmin = t_lower_bound();
double tmax = t_upper_bound();
_t_steps = hks_steps(tmin, tmax, steps);
_sig = calculate_hks(_t_steps);
_exception_map = Eigen::MatrixXd::Zero(_sig.rows(), _sig.cols());
}
HeatKernelSignature::HeatKernelSignature(std::shared_ptr<Mesh> mesh, double tmin, double tmax, int k):
SpectralSignature(std::make_shared<HKSParameterOptimization>(), mesh, k),
_t_steps(Eigen::VectorXd::Zero(0)) {
if (!mesh->loaded()) {
return;
}
int steps = eigenvalues().rows();
_t_steps = hks_steps(tmin, tmax, steps);
_sig = calculate_hks(_t_steps);
_exception_map = Eigen::MatrixXd::Zero(_sig.rows(), _sig.cols());
}
HeatKernelSignature::HeatKernelSignature(std::shared_ptr<Mesh> mesh, double tmin, double tmax, int steps, int k):
SpectralSignature(std::make_shared<HKSParameterOptimization>(), mesh, k),
_t_steps(Eigen::VectorXd::Zero(0)) {
if (!mesh->loaded()) {
return;
}
_t_steps = hks_steps(tmin, tmax, steps);
_sig = calculate_hks(_t_steps);
_exception_map = Eigen::MatrixXd::Zero(_sig.rows(), _sig.cols());
}
HeatKernelSignature::~HeatKernelSignature() {
}
std::shared_ptr<HeatKernelSignature> HeatKernelSignature::instantiate(std::shared_ptr<Mesh> mesh, int k) {
std::shared_ptr<HeatKernelSignature> hks = std::make_shared<HKSInstancer>(mesh, k);
hks->_param_opt->bind_signature(hks);
return hks;
}
std::shared_ptr<HeatKernelSignature> HeatKernelSignature::instantiate(std::shared_ptr<Mesh> mesh, int steps, int k) {
std::shared_ptr<HeatKernelSignature> hks = std::make_shared<HKSInstancer>(mesh, steps, k);
hks->_param_opt->bind_signature(hks);
return hks;
}
std::shared_ptr<HeatKernelSignature> HeatKernelSignature::instantiate(std::shared_ptr<Mesh> mesh, double tmin, double tmax, int k) {
std::shared_ptr<HeatKernelSignature> hks = std::make_shared<HKSInstancer>(mesh, tmin, tmax, k);
hks->_param_opt->bind_signature(hks);
return hks;
}
std::shared_ptr<HeatKernelSignature> HeatKernelSignature::instantiate(std::shared_ptr<Mesh> mesh, double tmin, double tmax, int steps, int k) {
std::shared_ptr<HeatKernelSignature> hks = std::make_shared<HKSInstancer>(mesh, tmin, tmax, steps, k);
hks->_param_opt->bind_signature(hks);
return hks;
}
void HeatKernelSignature::resample_at_t(double t, int k) {
//int steps = eigenvalues().rows();
resample_k(k);
_t_steps = hks_steps(t, t, 1);
_sig = calculate_hks(_t_steps);
_exception_map = Eigen::MatrixXd::Zero(_sig.rows(), _sig.cols());
}
void HeatKernelSignature::resample_at_param(double param) {
return resample_at_t(param, -1);
}
std::shared_ptr<HeatKernelSignature> operator-(std::shared_ptr<HeatKernelSignature> lhs, std::shared_ptr<HeatKernelSignature> rhs) {
std::shared_ptr<HeatKernelSignature> hks = nullptr;
const Eigen::MatrixXd& A = lhs->get_signature_values();
const Eigen::MatrixXd& B = rhs->get_signature_values();
if (A.rows() != B.rows() || A.cols() != B.cols()) {
// operation not defined on differently sized matrices!
return hks;
}
Eigen::MatrixXd residual = lhs->get_signature_values() - rhs->get_signature_values();
throw std::exception("Not implemented!");
}
const Eigen::VectorXd HeatKernelSignature::lerpable_coord(Eigen::DenseIndex fid, Eigen::DenseIndex vid) {
return _sig.row(vid);
}
Eigen::VectorXd HeatKernelSignature::lerpable_to_signature_value(const Eigen::VectorXd& lerped) {
return lerped;
}
unsigned long HeatKernelSignature::feature_count() {
return _sig.rows();
}
unsigned long HeatKernelSignature::feature_dimension() {
return _sig.cols();
}
const Eigen::MatrixXd& HeatKernelSignature::get_signature_values() {
return ShapeSignature::get_signature_values();
}
Eigen::VectorXd HeatKernelSignature::get_signature_values(double index) {
Eigen::DenseIndex n = -1;
double dist = std::numeric_limits<double>::max();
for (Eigen::DenseIndex i = 0; i < _t_steps.rows(); ++i) {
if (std::fabs(_t_steps(i) - index) < dist) {
n = i;
}
}
if (n > -1) {
return std::move(get_signature_values().col(n));
}
return Eigen::VectorXd();
}
int HeatKernelSignature::get_k_pairs_used() {
return get_current_k();
}
unsigned int HeatKernelSignature::get_steps() {
return _t_steps.size();
}
double HeatKernelSignature::get_tmin() {
return _t_steps(0);
}
double HeatKernelSignature::get_tmax() {
return _t_steps(_t_steps.size() - 1);
}
Eigen::VectorXd HeatKernelSignature::hks_steps(double tmin, double tmax, int steps) const {
if (tmin > tmax || steps <= 0) {
tmin = tmax;
steps = 1;
}
Eigen::VectorXd t_steps;
const Eigen::VectorXd& evals = this->eigenvalues();
if (evals.rows() < evals.cols()) {
return t_steps;
}
double stepsize;
if (steps == 1) {
stepsize = 0.0;
} else {
stepsize = (std::log(tmax) - std::log(tmin)) / (steps - 1);
}
t_steps.setLinSpaced(steps, 0.0, steps - 1);
t_steps = ((t_steps * stepsize).array() + std::log(tmin)).exp();
return t_steps;
}
Eigen::MatrixXd HeatKernelSignature::calculate_hks(const Eigen::VectorXd& t_steps) const {
if (_mesh == nullptr) {
return Eigen::MatrixXd();
}
if (!(t_steps.size() > 0)) {
return Eigen::MatrixXd();
}
// TODO: The next two statements are the most expensive part of the entire operation -- can anything be done to avoid/reduce/optimize them?
Eigen::MatrixXd evals_t = ((-1.0) * eigenvalues().cwiseAbs() * t_steps.transpose()).array().exp();
Eigen::MatrixXd hks = eigenvectors().cwiseProduct(eigenvectors()) * evals_t;
// HKS scaling (TODO: implement Scale-invariant HKS instead of just dividing by the heat trace)
Eigen::VectorXd heat_trace = evals_t.array().colwise().sum();
for (unsigned int i = 0; i < heat_trace.size(); ++i) {
hks.col(i) /= heat_trace(i);
}
return std::move(hks);
}
Eigen::MatrixXd HeatKernelSignature::sig_steps() {
return _t_steps;
}
const double HeatKernelSignature::step_width(double param) {
double lower = lower_bound();
double upper = upper_bound();
int index = -1;
double dist = std::numeric_limits<double>::max();
for (int i = 0; i < _t_steps.size(); ++i) {
double tdist = std::fabs(param - _t_steps(i));
if (tdist < dist) {
index = i;
dist = tdist;
}
}
if (index < 0 || std::fabs(_t_steps(index) - param) > std::numeric_limits<double>::epsilon()) {
throw std::logic_error("This parameter does not currently exist as a sampled column in the signature!");
}
if (index > 0) {
lower = _t_steps(index - 1);
}
if (index < _t_steps.size() - 1) {
upper = _t_steps.size() - 1;
}
return std::min(std::fabs(param - lower), std::fabs(param - upper));
}
double HeatKernelSignature::t_lower_bound() const {
// Heat Kernel Signature
// [tmin, tmax] as suggested in SOG09: http://dl.acm.org/citation.cfm?id=1735603.1735621
const Eigen::MatrixXd& evals = eigenvalues();
return 4.0 * std::log(10) / std::fabs(evals(evals.rows() - 1));
}
double HeatKernelSignature::t_upper_bound() const {
// Heat Kernel Signature
// [tmin, tmax] as suggested in SOG09: http://dl.acm.org/citation.cfm?id=1735603.1735621
const Eigen::MatrixXd& evals = eigenvalues();
return 4.0 * std::log(10) / std::fabs(evals(1));
}
double HeatKernelSignature::param_lower_bound() {
return t_lower_bound();
}
double HeatKernelSignature::param_upper_bound() {
return t_upper_bound();
}
HeatKernelSignature::HKSParameterOptimization::HKSParameterOptimization() {
}
HeatKernelSignature::HKSParameterOptimization::~HKSParameterOptimization() {
}
// An objective function of one value
// Input: Eigen::VectorXd size of 1, whose value is the t parameter of the HKS with which to compare patch geodesic fans
// Output: A double indicating the optimility of the input t parameter is maximizing distance of excluded patches and minimizing distance of included patches
double HeatKernelSignature::HKSParameterOptimization::value(const TVector &x) {
std::vector<Relation>& rels = _value_desire_set;
if (rels.size() < 2) {
// No minimization needed for a problem with one or zero patches
return 0.0;
}
std::shared_ptr<HeatKernelSignature> sig = std::dynamic_pointer_cast<HeatKernelSignature>(_optimizing_sig.lock());
double t = x(0);
double inc_obj = 0.0;
double ex_obj = 0.0;
double penalty = 0.0;
// Generate penalty for clamping
penalty += std::pow(std::max(0.0, sig->t_lower_bound() - t), 2);
penalty += std::pow(std::max(0.0, t - sig->t_upper_bound()), 2);
// clamp
t = std::max(sig->t_lower_bound(), std::min(t, sig->t_upper_bound()));
// Update signature with full signature tmin, tmax if necessary
std::shared_ptr<HeatKernelSignature> obj_interval = HeatKernelSignature::instantiate(sig->_mesh, t, t, 1);
// g(x) = f_i(x) + 1 / (1e-10 + f_e(x));
double objective = 0.0;
std::vector<std::pair<std::shared_ptr<GeodesicFan>, Relation::Designation>> fans;
for (Relation& r : rels) {
std::shared_ptr<Patch> patch = r._patch;
auto it = _metrics_map.find(patch);
Metrics patch_metrics;
if (it == _metrics_map.end()) {
// There seems to be no saved metrics, so generate them here
patch_metrics._centroid_vid = patch->get_centroid_vid_on_origin_mesh();
patch_metrics._geodesic_radius = patch->get_geodesic_extent(patch_metrics._centroid_vid);
patch_metrics._dem = patch->discrete_exponential_map(patch_metrics._centroid_vid);
_metrics_map.insert(std::pair<std::shared_ptr<Patch>, Metrics>(patch, patch_metrics));
} else {
patch_metrics = it->second;
}
// Fans are based off of value inputs, so can't be pre-computed
auto fan = std::make_shared<GeodesicFan>(patch_metrics._dem, obj_interval);
fans.push_back(std::pair<std::shared_ptr<GeodesicFan>, Relation::Designation>(fan, r._designation));
}
for (unsigned int i = 0; i < fans.size(); ++i) {
for (unsigned int j = i + 1; j < fans.size(); ++j) {
// Subsequent patch for comparison
double orientation = 0.0;
double comp = fans[i].first->compare(*fans[j].first, orientation);
if (fans[i].second == fans[j].second) {
// Include
inc_obj += comp;
} else {
// Exclude
ex_obj += comp;
}
}
}
objective = ((1 + inc_obj) / (1 + ex_obj)) + penalty;
return objective;
}
cppoptlib::Problem<double>::TVector HeatKernelSignature::HKSParameterOptimization::upperBound() const {
std::shared_ptr<HeatKernelSignature> sig = std::dynamic_pointer_cast<HeatKernelSignature>(_optimizing_sig.lock());
TVector upper_bound(1);
upper_bound << sig->t_upper_bound();
return upper_bound;
}
cppoptlib::Problem<double>::TVector HeatKernelSignature::HKSParameterOptimization::lowerBound() const {
std::shared_ptr<HeatKernelSignature> sig = std::dynamic_pointer_cast<HeatKernelSignature>(_optimizing_sig.lock());
TVector lower_bound(1); // tmin, tmax
lower_bound << sig->t_lower_bound();
return lower_bound;
}
Eigen::MatrixXd HeatKernelSignature::HKSParameterOptimization::param_steps(unsigned int steps) {
auto sig = std::dynamic_pointer_cast<HeatKernelSignature>(_optimizing_sig.lock());
assert(sig != nullptr && "Bound signature is invalid!");
return sig->hks_steps(sig->t_lower_bound(), sig->t_upper_bound(), steps);
}
bool HeatKernelSignature::HKSParameterOptimization::callback(const cppoptlib::Criteria<Scalar> &state, const TVector &x) {
// Capture state of solver per step taken
std::cout << "step: x = " << x.transpose() << std::endl;
return true;
}
std::shared_ptr<GeodesicFan> HeatKernelSignature::HKSParameterOptimization::geodesic_fan_from_relation(const Relation& r) {
// There seems to be no saved metrics, so generate them here
std::shared_ptr<HeatKernelSignature> sig = std::dynamic_pointer_cast<HeatKernelSignature>(_optimizing_sig.lock());
if (sig == nullptr) {
return nullptr;
}
auto patch = r._patch;
if (patch == nullptr) {
return nullptr;
}
auto it = _metrics_map.find(patch);
Metrics patch_metrics;
if (it == _metrics_map.end()) {
// There seems to be no saved metrics, so generate them here
patch_metrics._centroid_vid = patch->get_centroid_vid_on_origin_mesh();
patch_metrics._geodesic_radius = patch->get_geodesic_extent(patch_metrics._centroid_vid);
patch_metrics._dem = patch->discrete_exponential_map(patch_metrics._centroid_vid);
_metrics_map.insert(std::pair<std::shared_ptr<Patch>, Metrics>(patch, patch_metrics));
}
else {
patch_metrics = it->second;
}
// Fans are based off of value inputs, so can't be pre-computed
auto fan = std::make_shared<GeodesicFan>(patch_metrics._dem, sig);
return fan;
}
| 29.978541
| 157
| 0.721546
|
josefgraus
|
2a5b668d11f4ffffb6010aef49e9ba94c4f7ab79
| 1,993
|
hh
|
C++
|
src/utils/field_sources/DipoleFieldSource.hh
|
LeoRya/py-orbit
|
340b14b6fd041ed8ec2cc25b0821b85742aabe0c
|
[
"MIT"
] | 17
|
2018-02-09T23:39:06.000Z
|
2022-03-04T16:27:04.000Z
|
src/utils/field_sources/DipoleFieldSource.hh
|
LeoRya/py-orbit
|
340b14b6fd041ed8ec2cc25b0821b85742aabe0c
|
[
"MIT"
] | 22
|
2017-05-31T19:40:14.000Z
|
2021-09-24T22:07:47.000Z
|
src/utils/field_sources/DipoleFieldSource.hh
|
LeoRya/py-orbit
|
340b14b6fd041ed8ec2cc25b0821b85742aabe0c
|
[
"MIT"
] | 37
|
2016-12-08T19:39:35.000Z
|
2022-02-11T19:59:34.000Z
|
//////////////////////////////// -*- C++ -*- //////////////////////////////
//
// FILE NAME
// DipoleFieldSource.hh
//
// AUTHOR
// A. Shishlo
//
// CREATED
// 12/25/2020
//
// DESCRIPTION
// A class is an implementation of ShiftedFieldSource class.
// This class describes dipole magnetic field. It needs dipole sizes
// [m] in three directions and the field strength in [T].
// The center of the dipole is at [0,0,0].
//
///////////////////////////////////////////////////////////////////////////
#ifndef DIPOLE_FIELD_SOURCE_H
#define DIPOLE_FIELD_SOURCE_H
#include "Grid3D.hh"
#include "ShiftedFieldSource.hh"
namespace OrbitUtils{
/** A class implements of BaseFiledSource class with magnetic fields of dipiole */
class DipoleFieldSource : public ShiftedFieldSource
{
public:
/** Constructor. */
DipoleFieldSource();
/** Destructor */
~DipoleFieldSource();
/** Sets the sizes of the dipole field */
void setSizes(double sizeX, double sizeY, double sizeZ);
/** Returns the sizes of the dipole field */
void getSizes(double& sizeX, double& sizeY, double& sizeZ);
/** Sets the fields of the dipole in [T] */
void setFields(double fieldX, double fieldY, double fieldZ);
/** Returns the fields of the dipole in [T] */
void getFields(double& fieldX, double& fieldY, double& fieldZ);
/** Returns inner components of the electric and magnetic filds. */
virtual void getInnerElectricMagneticField(
double x, double y, double z, double t,
double& E_x, double& E_y, double& E_z,
double& H_x, double& H_y, double& H_z);
private:
//sizes in [m]
double sizeX;
double sizeY;
double sizeZ;
// fields in [T]
double fieldX;
double fieldY;
double fieldZ;
};
};
///////////////////////////////////////////////////////////////////////////
//
// END OF FILE
//
///////////////////////////////////////////////////////////////////////////
#endif
| 24.304878
| 83
| 0.556949
|
LeoRya
|
2a615a51da61ae8caa5e034aa95f45fd55c7c526
| 1,130
|
cc
|
C++
|
pegasus/ops/parsing_utils_test.cc
|
akhilbobby/pegasus
|
4c00483789a4c5c4db58fef95e3f135940a4b82b
|
[
"Apache-2.0"
] | 1,270
|
2020-03-25T04:20:42.000Z
|
2022-03-31T07:50:34.000Z
|
pegasus/ops/parsing_utils_test.cc
|
rohitsroch/pegasus
|
1e029a8928e8fdfba6ec7b241f6fbce92e078740
|
[
"Apache-2.0"
] | 199
|
2020-04-17T14:06:43.000Z
|
2022-03-23T09:57:19.000Z
|
pegasus/ops/parsing_utils_test.cc
|
rohitsroch/pegasus
|
1e029a8928e8fdfba6ec7b241f6fbce92e078740
|
[
"Apache-2.0"
] | 276
|
2020-04-16T10:44:55.000Z
|
2022-03-25T01:18:29.000Z
|
// Copyright 2020 The PEGASUS Authors..
//
// 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 "pegasus/ops/parsing_utils.h"
#include "testing/base/public/gmock.h"
#include "gtest/gtest.h"
namespace pegasus {
namespace {
TEST(ParsingUtilsTest, SentenceSegment) {
std::vector<std::string> segs = SentenceSegment("This is? what what.");
CHECK_EQ(segs[0], "This is? ");
CHECK_EQ(segs[1], "what what.");
}
TEST(ParsingUtilsTest, SentenceNoSegment) {
std::vector<std::string> segs = SentenceSegment("This is.what what? ");
CHECK_EQ(segs[0], "This is.what what? ");
}
} // namespace
} // namespace pegasus
| 31.388889
| 75
| 0.722124
|
akhilbobby
|
2a615af8a5939932bff1e9fd2eabb884417d67d5
| 2,703
|
cc
|
C++
|
big-lalr/test/util-test.cc
|
hooddanielc/stone
|
e3bfd674e35a6e0c11a6985fb61cf63accb73a1a
|
[
"Apache-2.0"
] | null | null | null |
big-lalr/test/util-test.cc
|
hooddanielc/stone
|
e3bfd674e35a6e0c11a6985fb61cf63accb73a1a
|
[
"Apache-2.0"
] | null | null | null |
big-lalr/test/util-test.cc
|
hooddanielc/stone
|
e3bfd674e35a6e0c11a6985fb61cf63accb73a1a
|
[
"Apache-2.0"
] | null | null | null |
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <lick/lick.h>
#include <big-lalr/util.h>
using namespace biglr;
FIXTURE(get_random_string_result) {
auto str1 = get_random_str(10);
auto str2 = get_random_str(10);
EXPECT_NE(str1, str2);
EXPECT_EQ(str1.size(), str2.size());
EXPECT_EQ(str1.size(), size_t(10));
}
FIXTURE(get_tmp_path_result) {
auto tmp1 = get_tmp_path();
auto tmp2 = get_tmp_path();
auto tmp3 = get_tmp_path("custom-prefix-");
EXPECT_EQ(tmp1.size(), size_t(24));
EXPECT_EQ(tmp2.size(), size_t(24));
EXPECT_EQ(tmp3.size(), size_t(29));
}
FIXTURE(read_a_file) {
std::string path = get_project_path("/big-lalr/test/fixtures/pets.biglr");
auto str = get_file_contents(path);
EXPECT_EQ(str.size(), size_t(145));
}
FIXTURE(write_a_file) {
auto content = "my name is tony, and i stole your sandwhich";
auto path = get_tmp_path("write-test-");
write_file_contents(path, content);
auto read = get_file_contents(path);
std::remove(path.c_str());
EXPECT_EQ(read, content);
}
FIXTURE(sanitize_cpp_ids) {
EXPECT_EQ(sanitize_cpp_identifier("alignas"), "alignas_");
EXPECT_EQ(sanitize_cpp_identifier("xor"), "xor_");
}
FIXTURE(make_child_process) {
auto proc = child_process_t::make();
EXPECT_EQ(proc->get_cmd(), std::string(""));
EXPECT_EQ(proc->get_args().size(), size_t(0));
proc->set_cmd("/usr/bin/gcc");
proc->set_args({"--help"});
EXPECT_EQ(proc->get_cmd(), std::string("/usr/bin/gcc"));
EXPECT_EQ(proc->get_args().size(), size_t(1));
EXPECT_EQ(proc->get_args()[0], std::string("--help"));
pid_t pid_returned = 0;
int total_chars_received = 0;
int exit_code = -1;
proc->on_start([&](pid_t pid) {
pid_returned = pid;
});
proc->on_stdout([&](const std::string &str) {
total_chars_received += str.size();
});
proc->on_stderr([&](const std::string &str) {
total_chars_received += str.size();
});
proc->on_exit([&](int status) {
exit_code = status;
});
proc->exec_sync();
EXPECT_NE(pid_returned, pid_t(0));
EXPECT_NE(exit_code, -1);
EXPECT_NE(total_chars_received, 0);
}
FIXTURE(child_process_output) {
auto proc = child_process_t::make();
proc->set_cmd("/bin/bash");
proc->set_args({"-c", ">&2 echo 'illusion of choice' && sleep 1 && echo 'works'"});
std::string stdout;
std::string stderr;
proc->on_stdout([&](const std::string &str) {
stdout += str;
});
proc->on_stderr([&](const std::string &str) {
stderr += str;
});
proc->on_exit([&](int status) {
EXPECT_EQ(status, 0);
EXPECT_EQ(stderr, "illusion of choice\n");
EXPECT_EQ(stdout, "works\n");
EXPECT_FALSE(stdout.back() != '\n');
});
proc->exec_sync();
}
| 25.027778
| 85
| 0.657788
|
hooddanielc
|
2a61d539199b995b2cceadbe99ece28acdb5b1a3
| 5,716
|
hpp
|
C++
|
wz4/wz4frlib/chaosfx.hpp
|
wzman/werkkzeug4CE
|
af5ff27829ed4c501515ef5131165048e991c9b4
|
[
"BSD-2-Clause"
] | 47
|
2015-03-22T05:58:47.000Z
|
2022-03-29T19:13:37.000Z
|
wz4/wz4frlib/chaosfx.hpp
|
whpskyeagle/werkkzeug4CE
|
af5ff27829ed4c501515ef5131165048e991c9b4
|
[
"BSD-2-Clause"
] | null | null | null |
wz4/wz4frlib/chaosfx.hpp
|
whpskyeagle/werkkzeug4CE
|
af5ff27829ed4c501515ef5131165048e991c9b4
|
[
"BSD-2-Clause"
] | 16
|
2015-12-31T08:13:18.000Z
|
2021-03-09T02:07:30.000Z
|
/*+**************************************************************************/
/*** ***/
/*** This file is distributed under a BSD license. ***/
/*** See LICENSE.txt for details. ***/
/*** ***/
/**************************************************************************+*/
#ifndef FILE_WZ4FRLIB_CHAOSFX_HPP
#define FILE_WZ4FRLIB_CHAOSFX_HPP
#include "base/types.hpp"
#include "wz4frlib/wz4_demo2.hpp"
#include "wz4frlib/wz4_demo2_ops.hpp"
#include "wz4frlib/wz4_mesh.hpp"
#include "wz4frlib/wz4_mtrl2.hpp"
#include "wz4frlib/chaosfx_ops.hpp"
#include "util/shaders.hpp"
/****************************************************************************/
/****************************************************************************/
class RNCubeExample : public Wz4RenderNode
{
sGeometry *Geo; // geometry holding the cube
sMatrix34 Matrix; // calculated in Prepare, used in Render
void MakeCube();
public:
RNCubeExample();
~RNCubeExample();
void Simulate(Wz4RenderContext *ctx); // execute the script.
void Prepare(Wz4RenderContext *ctx); // do simulation
void Render(Wz4RenderContext *ctx); // render a pass
Wz4RenderParaCubeExample Para,ParaBase; // animated parameters from op
Wz4RenderAnimCubeExample Anim; // information for the script engine
Wz4Mtrl *Mtrl; // material from inputs
};
/****************************************************************************/
class RNTest : public Wz4RenderNode
{
sGeometry *Geo;
sMatrix34 Matrix;
sMaterial * Mtrl;
public:
RNTest();
~RNTest();
void Simulate(Wz4RenderContext *ctx);
void Prepare(Wz4RenderContext *ctx);
void Render(Wz4RenderContext *ctx);
Wz4RenderParaTest Para,ParaBase;
Wz4RenderAnimTest Anim;
};
/****************************************************************************/
class RNPrint : public Wz4RenderNode
{
sMatrix34 Matrix;
public:
RNPrint();
~RNPrint();
void Simulate(Wz4RenderContext *ctx);
void Prepare(Wz4RenderContext *ctx);
void Render(Wz4RenderContext *ctx);
Wz4RenderParaPrint Para,ParaBase;
Wz4RenderAnimPrint Anim;
class ChaosFont *Font;
sPoolString Text;
};
/****************************************************************************/
class RNRibbons : public Wz4RenderNode
{
sGeometry *Geo;
sGeometry *GeoWire;
sSimpleMaterial *Mtrl;
public:
RNRibbons();
~RNRibbons();
Wz4RenderParaRibbons ParaBase,Para;
Wz4RenderAnimRibbons Anim;
void Simulate(Wz4RenderContext *ctx);
void Prepare(Wz4RenderContext *ctx);
void Render(Wz4RenderContext *ctx);
Wz4Mtrl *MtrlEx;
};
/****************************************************************************/
class RNRibbons2 : public Wz4RenderNode
{
sGeometry *Geo;
sGeometry *GeoWire;
sSimpleMaterial *Mtrl;
sRandomMT Random;
sVector31 Sources[4];
sF32 Power[4];
public:
RNRibbons2();
~RNRibbons2();
Wz4RenderParaRibbons2 ParaBase,Para;
Wz4RenderAnimRibbons2 Anim;
void Simulate(Wz4RenderContext *ctx);
void Prepare(Wz4RenderContext *ctx);
void Render(Wz4RenderContext *ctx);
void Eval(const sVector31 &pos,sVector30 &norm);
Wz4Mtrl *MtrlEx;
};
/****************************************************************************/
#define BNNB 9
#define BNN (1<<BNNB)
#define BNNM (BNN-1)
class RNBlowNoise : public Wz4RenderNode
{
sVertexFormatHandle *VertFormat;
sGeometry *Geo;
sGeometry *GeoWire;
//sSimpleMaterial *Mtrl;
struct NoiseData
{
sF32 Value;
sF32 DX;
sF32 DY;
};
struct Vertex
{
sVector31 Pos;
sVector31 PosOld;
sVector30 Normal;
sVector30 Tangent;
sF32 U,V;
};
Vertex *Verts;
sInt SizeX;
sInt SizeY;
NoiseData Noise[BNN][BNN];
void InitNoise();
void SampleNoise(sF32 x,sF32 y,NoiseData &nd);
ScriptSymbol *_Scale;
ScriptSymbol *_Scroll;
public:
RNBlowNoise();
~RNBlowNoise();
void Init();
sArray<struct Wz4RenderArrayBlowNoise *> Layers;
Wz4RenderParaBlowNoise Para,ParaBase;
Wz4RenderAnimBlowNoise Anim;
Wz4Mtrl *Mtrl;
void Simulate(Wz4RenderContext *ctx);
void Prepare(Wz4RenderContext *ctx);
void Render(Wz4RenderContext *ctx);
};
/****************************************************************************/
class RNDebrisClassic : public Wz4RenderNode
{
public:
RNDebrisClassic();
~RNDebrisClassic();
void Init();
Wz4RenderParaDebrisClassic Para,ParaBase;
Wz4RenderAnimDebrisClassic Anim;
Wz4Mesh *Mesh;
sImageI16 Bitmap[3];
void Simulate(Wz4RenderContext *ctx);
void Prepare(Wz4RenderContext *ctx) { if(Mesh) Mesh->BeforeFrame(Para.EnvNum); }
void Render(Wz4RenderContext *ctx);
};
/****************************************************************************/
class RNBoneVibrate : public Wz4RenderNode
{
sInt Count;
sMatrix34 *mate;
sMatrix34 *mats;
sMatrix34CM *mats0;
public:
RNBoneVibrate();
~RNBoneVibrate();
void Init();
void Simulate(Wz4RenderContext *ctx); // execute the script.
void Prepare(Wz4RenderContext *ctx); // do simulation
void Render(Wz4RenderContext *ctx); // render a pass
Wz4RenderParaBoneVibrate Para,ParaBase; // animated parameters from op
Wz4RenderAnimBoneVibrate Anim; // information for the script engine
Wz4Mesh *Mesh; // material from inputs
};
/****************************************************************************/
/****************************************************************************/
#endif // FILE_WZ4FRLIB_CHAOSFX_HPP
| 24.744589
| 82
| 0.557208
|
wzman
|
2a6592ea65d0d5efb94aee12373bf7caec7b72c3
| 2,844
|
hpp
|
C++
|
src/libField/Serialization.hpp
|
CD3/libField
|
8aa93e21d3bbc01c38ecc3a6ea31bd4ceb8bbfd6
|
[
"MIT"
] | null | null | null |
src/libField/Serialization.hpp
|
CD3/libField
|
8aa93e21d3bbc01c38ecc3a6ea31bd4ceb8bbfd6
|
[
"MIT"
] | 5
|
2017-06-18T17:05:04.000Z
|
2022-02-05T19:14:38.000Z
|
src/libField/Serialization.hpp
|
CD3/libField
|
8aa93e21d3bbc01c38ecc3a6ea31bd4ceb8bbfd6
|
[
"MIT"
] | null | null | null |
#ifndef Serialization_hpp
#define Serialization_hpp
/** @file Serialization.hpp
* @brief Provides serialization support to library.
* @author C.D. Clark III
* @date 07/18/17
*/
#if SERIALIZATION_ENABLED
#ifndef BOOST_NO_MEMBER_TEMPLATE_FRIENDS
#error \
"Boost member template friends must be disabled in order to serialize mulati_array."
#endif
#include <boost/array.hpp>
#include <boost/serialization/array.hpp>
#include <boost/serialization/shared_ptr.hpp>
#include "Field.hpp"
namespace boost
{
namespace serialization
{
template<class Archive, typename T, std::size_t N>
inline void save(Archive& ar, const boost::multi_array<T, N>& a,
const unsigned int version)
{
// write storage order info first
boost::array<multi_array_types::size_type, N> storage_order_ordering;
boost::array<bool, N> storage_order_ascending;
for (int i = 0; i < N; i++) {
storage_order_ordering[i] = a.storage_order().ordering(i);
storage_order_ascending[i] = a.storage_order().ascending(i);
}
ar << make_array(storage_order_ordering.data(), N);
ar << make_array(storage_order_ascending.data(), N);
// now write the shape
ar << make_array(a.shape(), N);
// write data
ar << make_array(a.data(), a.num_elements());
// write index offsets
ar << make_array(a.index_bases(), N);
// write strides
ar << make_array(a.strides(), N);
}
template<class Archive, typename T, std::size_t N>
inline void load(Archive& ar, boost::multi_array<T, N>& a,
const unsigned int version)
{
// read storage order
boost::array<multi_array_types::size_type, N> storage_order_ordering;
boost::array<bool, N> storage_order_ascending;
ar >> make_array(storage_order_ordering.data(), N);
ar >> make_array(storage_order_ascending.data(), N);
a.storage_ = general_storage_order<N>(storage_order_ordering.data(),
storage_order_ascending.data());
// read shape (NOTE: the storage order needs to be set *before* resizing)
boost::array<multi_array_types::size_type, N> shape;
ar >> make_array(shape.data(), N);
a.resize(shape);
// read data
ar >> make_array(a.data(), a.num_elements());
// read index offsets
boost::array<multi_array_types::index, N> offsets;
ar >> make_array(offsets.data(), N);
a.reindex(offsets);
// read strides
boost::array<multi_array_types::index, N> strides;
ar >> make_array(strides.data(), N);
for (int i = 0; i < N; i++) a.stride_list_[i] = strides[i];
}
template<typename Archive, typename T, std::size_t N>
inline void serialize(Archive& ar, boost::multi_array<T, N>& a,
const unsigned int version)
{
split_free(ar, a, version);
}
} // namespace serialization
} // namespace boost
#endif
#endif // include protector
| 29.319588
| 88
| 0.677567
|
CD3
|
2a6702b60db14ee7923639fada27f3582d2ed959
| 13,605
|
cpp
|
C++
|
dev/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/LinearManipulator.cpp
|
yuriy0/lumberyard
|
18ab07fd38492d88c34df2a3e061739d96747e13
|
[
"AML"
] | null | null | null |
dev/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/LinearManipulator.cpp
|
yuriy0/lumberyard
|
18ab07fd38492d88c34df2a3e061739d96747e13
|
[
"AML"
] | null | null | null |
dev/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/LinearManipulator.cpp
|
yuriy0/lumberyard
|
18ab07fd38492d88c34df2a3e061739d96747e13
|
[
"AML"
] | null | null | null |
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include "LinearManipulator.h"
#include <AzFramework/Entity/EntityDebugDisplayBus.h>
#include <AzToolsFramework/Manipulators/ManipulatorDebug.h>
#include <AzToolsFramework/Manipulators/ManipulatorSnapping.h>
#include <AzToolsFramework/Maths/TransformUtils.h>
#include <AzToolsFramework/Viewport/ViewportMessages.h>
#include <AzToolsFramework/ViewportSelection/EditorSelectionUtil.h>
namespace AzToolsFramework
{
LinearManipulator::StartInternal LinearManipulator::CalculateManipulationDataStart(
const Fixed& fixed, const AZ::Transform& worldFromLocal, const AZ::Transform& localTransform,
const GridSnapAction& gridSnapAction, const AZ::Vector3& rayOrigin, const AZ::Vector3& rayDirection,
const AzFramework::CameraState& cameraState)
{
const ManipulatorInteraction manipulatorInteraction =
BuildManipulatorInteraction(worldFromLocal, rayOrigin, rayDirection);
const AZ::Vector3 axis = TransformDirectionNoScaling(localTransform, fixed.m_axis);
const AZ::Vector3 rayCrossAxis = manipulatorInteraction.m_localRayDirection.Cross(axis);
StartInternal startInternal;
// initialize m_localHitPosition to handle edge case where CalculateRayPlaneIntersectingPoint
// fails because ray is parallel to the plane
startInternal.m_localHitPosition = localTransform.GetTranslation();
startInternal.m_localNormal = rayCrossAxis.Cross(axis).GetNormalizedSafeExact();
Internal::CalculateRayPlaneIntersectingPoint(
manipulatorInteraction.m_localRayOrigin, manipulatorInteraction.m_localRayDirection,
localTransform.GetTranslation(), startInternal.m_localNormal, startInternal.m_localHitPosition);
const float gridSize = gridSnapAction.m_gridSnapParams.m_gridSize;
const bool snapping = gridSnapAction.m_gridSnapParams.m_gridSnap;
const float scaleRecip = manipulatorInteraction.m_scaleReciprocal;
// calculate position amount to snap, to align with grid
const AZ::Vector3 positionSnapOffset = snapping && !gridSnapAction.m_localSnapping
? CalculateSnappedOffset(localTransform.GetTranslation(), axis, gridSize * scaleRecip)
: AZ::Vector3::CreateZero();
const AZ::Vector3 localScale = localTransform.RetrieveScale();
const AZ::Quaternion localRotation = QuaternionFromTransformNoScaling(localTransform);
// calculate scale amount to snap, to align to round scale value
const AZ::Vector3 scaleSnapOffset = snapping && !gridSnapAction.m_localSnapping
? localRotation.GetInverseFull() * CalculateSnappedOffset(
localRotation * localScale, axis, gridSize * scaleRecip)
: AZ::Vector3::CreateZero();
startInternal.m_positionSnapOffset = positionSnapOffset;
startInternal.m_scaleSnapOffset = scaleSnapOffset;
startInternal.m_localPosition = localTransform.GetTranslation() + positionSnapOffset;
startInternal.m_localScale = localScale + scaleSnapOffset;
startInternal.m_localAxis = axis;
startInternal.m_screenToWorldScale =
AZ::VectorFloat::CreateOne() /
CalculateScreenToWorldMultiplier((worldFromLocal * localTransform).GetTranslation(), cameraState);
return startInternal;
}
LinearManipulator::Action LinearManipulator::CalculateManipulationDataAction(
const Fixed& fixed, const StartInternal& startInternal, const AZ::Transform& worldFromLocal,
const AZ::Transform& localTransform, const GridSnapAction& gridSnapAction,
const AZ::Vector3& rayOrigin, const AZ::Vector3& rayDirection,
const ViewportInteraction::KeyboardModifiers keyboardModifiers)
{
const ManipulatorInteraction manipulatorInteraction =
BuildManipulatorInteraction(worldFromLocal, rayOrigin, rayDirection);
// as CalculateRayPlaneIntersectingPoint may fail, ensure localHitPosition is initialized with
// the starting hit position so the manipulator returns to the original location it was pressed
// if an invalid ray intersection is attempted
AZ::Vector3 localHitPosition = startInternal.m_localHitPosition;
Internal::CalculateRayPlaneIntersectingPoint(
manipulatorInteraction.m_localRayOrigin, manipulatorInteraction.m_localRayDirection,
startInternal.m_localPosition, startInternal.m_localNormal, localHitPosition);
const AZ::Vector3 axis = TransformDirectionNoScaling(localTransform, fixed.m_axis);
const AZ::Vector3 hitDelta = (localHitPosition - startInternal.m_localHitPosition);
const AZ::Vector3 unsnappedOffset = axis * axis.Dot(hitDelta);
const float scaleRecip = manipulatorInteraction.m_scaleReciprocal;
const float gridSize = gridSnapAction.m_gridSnapParams.m_gridSize;
const bool snapping = gridSnapAction.m_gridSnapParams.m_gridSnap;
Action action;
action.m_fixed = fixed;
action.m_start.m_localPosition = startInternal.m_localPosition;
action.m_start.m_localScale = startInternal.m_localScale;
action.m_start.m_localHitPosition = startInternal.m_localHitPosition;
action.m_start.m_localAxis = startInternal.m_localAxis;
action.m_start.m_positionSnapOffset = startInternal.m_positionSnapOffset;
action.m_start.m_scaleSnapOffset = startInternal.m_scaleSnapOffset;
action.m_current.m_localPositionOffset = snapping
? unsnappedOffset + CalculateSnappedOffset(unsnappedOffset, axis, gridSize * scaleRecip)
: unsnappedOffset;
// sign to determine which side of the linear axis we pressed
// (useful to know when the visual axis flips to face the camera)
action.m_start.m_sign =
(startInternal.m_localHitPosition - localTransform.GetTranslation()).Dot(axis).GetSign();
const AZ::Quaternion localRotation = QuaternionFromTransformNoScaling(localTransform);
const AZ::Vector3 scaledUnsnappedOffset = unsnappedOffset * startInternal.m_screenToWorldScale;
// how much to adjust the scale based on movement
const AZ::Quaternion invLocalRotation = localRotation.GetInverseFull();
action.m_current.m_localScaleOffset = snapping
? invLocalRotation * (scaledUnsnappedOffset + CalculateSnappedOffset(scaledUnsnappedOffset, axis, gridSize * scaleRecip))
: invLocalRotation * scaledUnsnappedOffset;
// record what modifier keys are held during this action
action.m_modifiers = keyboardModifiers;
return action;
}
AZStd::shared_ptr<LinearManipulator> LinearManipulator::MakeShared(const AZ::Transform& worldFromLocal)
{
return AZStd::shared_ptr<LinearManipulator>(aznew LinearManipulator(worldFromLocal));
}
LinearManipulator::LinearManipulator(const AZ::Transform& worldFromLocal)
: m_worldFromLocal(worldFromLocal)
{
AttachLeftMouseDownImpl();
}
void LinearManipulator::InstallLeftMouseDownCallback(const MouseActionCallback& onMouseDownCallback)
{
m_onLeftMouseDownCallback = onMouseDownCallback;
}
void LinearManipulator::InstallLeftMouseUpCallback(const MouseActionCallback& onMouseUpCallback)
{
m_onLeftMouseUpCallback = onMouseUpCallback;
}
void LinearManipulator::InstallMouseMoveCallback(const MouseActionCallback& onMouseMoveCallback)
{
m_onMouseMoveCallback = onMouseMoveCallback;
}
void LinearManipulator::OnLeftMouseDownImpl(
const ViewportInteraction::MouseInteraction& interaction, float /*rayIntersectionDistance*/)
{
const AZ::Transform worldFromLocalUniformScale = TransformUniformScale(m_worldFromLocal);
const GridSnapParameters gridSnapParams = GridSnapSettings(interaction.m_interactionId.m_viewportId);
AzFramework::CameraState cameraState;
ViewportInteraction::ViewportInteractionRequestBus::EventResult(
cameraState, interaction.m_interactionId.m_viewportId,
&ViewportInteraction::ViewportInteractionRequestBus::Events::GetCameraState);
// note: m_localTransform must not be made uniform as it may contain a local scale we want to snap
m_startInternal = CalculateManipulationDataStart(
m_fixed, worldFromLocalUniformScale, m_localTransform,
GridSnapAction(gridSnapParams, interaction.m_keyboardModifiers.Alt()),
interaction.m_mousePick.m_rayOrigin, interaction.m_mousePick.m_rayDirection,
cameraState);
if (m_onLeftMouseDownCallback)
{
m_onLeftMouseDownCallback(CalculateManipulationDataAction(
m_fixed, m_startInternal, worldFromLocalUniformScale, m_localTransform,
GridSnapAction(gridSnapParams, interaction.m_keyboardModifiers.Alt()),
interaction.m_mousePick.m_rayOrigin, interaction.m_mousePick.m_rayDirection,
interaction.m_keyboardModifiers));
}
}
void LinearManipulator::OnMouseMoveImpl(const ViewportInteraction::MouseInteraction& interaction)
{
if (m_onMouseMoveCallback)
{
const GridSnapParameters gridSnapParams = GridSnapSettings(interaction.m_interactionId.m_viewportId);
// note: m_localTransform must not be made uniform as it may contain a local scale we want to snap
m_onMouseMoveCallback(CalculateManipulationDataAction(
m_fixed, m_startInternal, TransformUniformScale(m_worldFromLocal), m_localTransform,
GridSnapAction(gridSnapParams, interaction.m_keyboardModifiers.Alt()),
interaction.m_mousePick.m_rayOrigin, interaction.m_mousePick.m_rayDirection,
interaction.m_keyboardModifiers));
}
}
void LinearManipulator::OnLeftMouseUpImpl(const ViewportInteraction::MouseInteraction& interaction)
{
if (m_onLeftMouseUpCallback)
{
const GridSnapParameters gridSnapParams = GridSnapSettings(interaction.m_interactionId.m_viewportId);
// note: m_localTransform must not be made uniform as it may contain a local scale we want to snap
m_onLeftMouseUpCallback(CalculateManipulationDataAction(
m_fixed, m_startInternal, TransformUniformScale(m_worldFromLocal), m_localTransform,
GridSnapAction(gridSnapParams, interaction.m_keyboardModifiers.Alt()),
interaction.m_mousePick.m_rayOrigin, interaction.m_mousePick.m_rayDirection,
interaction.m_keyboardModifiers));
}
}
void LinearManipulator::Draw(
const ManipulatorManagerState& managerState,
AzFramework::DebugDisplayRequests& debugDisplay,
const AzFramework::CameraState& cameraState,
const ViewportInteraction::MouseInteraction& mouseInteraction)
{
const AZ::Transform localTransform = m_useVisualsOverride
? AZ::Transform::CreateFromQuaternionAndTranslation(
m_visualOrientationOverride, m_localTransform.GetTranslation())
: m_localTransform;
if (cl_manipulatorDrawDebug)
{
const AZ::Transform combined = TransformUniformScale(m_worldFromLocal) * localTransform;
DrawTransformAxes(debugDisplay, combined);
DrawAxis(
debugDisplay, combined.GetTranslation(), TransformDirectionNoScaling(combined, m_fixed.m_axis));
}
for (auto& view : m_manipulatorViews)
{
view->Draw(
GetManipulatorManagerId(), managerState,
GetManipulatorId(), {
m_worldFromLocal * localTransform,
AZ::Vector3::CreateZero(), MouseOver()
},
debugDisplay, cameraState, mouseInteraction);
}
}
void LinearManipulator::SetAxis(const AZ::Vector3& axis)
{
m_fixed.m_axis = axis;
}
void LinearManipulator::SetSpace(const AZ::Transform& worldFromLocal)
{
m_worldFromLocal = worldFromLocal;
}
void LinearManipulator::SetLocalTransform(const AZ::Transform& localTransform)
{
m_localTransform = localTransform;
}
void LinearManipulator::SetLocalPosition(const AZ::Vector3& localPosition)
{
m_localTransform.SetPosition(localPosition);
}
void LinearManipulator::SetLocalOrientation(const AZ::Quaternion& localOrientation)
{
m_localTransform = AZ::Transform::CreateFromQuaternionAndTranslation(
localOrientation, m_localTransform.GetTranslation());
}
void LinearManipulator::InvalidateImpl()
{
for (auto& view : m_manipulatorViews)
{
view->Invalidate(GetManipulatorManagerId());
}
}
void LinearManipulator::SetBoundsDirtyImpl()
{
for (auto& view : m_manipulatorViews)
{
view->SetBoundDirty(GetManipulatorManagerId());
}
}
} // namespace AzToolsFramework
| 47.239583
| 133
| 0.722528
|
yuriy0
|
2a69bb77e9d7465d497e2d7f879468c60767eaec
| 2,854
|
cpp
|
C++
|
source/ui/framework/box_element.cpp
|
ThatNerdyPikachu/Tinfoil
|
abef7e3648f483368301b43611017c7ffa6f6fc2
|
[
"MIT"
] | 9
|
2020-12-24T00:12:29.000Z
|
2022-02-22T11:37:45.000Z
|
source/ui/framework/box_element.cpp
|
skvaznoi/Tinfoil
|
abef7e3648f483368301b43611017c7ffa6f6fc2
|
[
"MIT"
] | null | null | null |
source/ui/framework/box_element.cpp
|
skvaznoi/Tinfoil
|
abef7e3648f483368301b43611017c7ffa6f6fc2
|
[
"MIT"
] | 1
|
2020-07-20T01:30:03.000Z
|
2020-07-20T01:30:03.000Z
|
#include "ui/framework/box_element.hpp"
#include "util/graphics_util.hpp"
#include "error.hpp"
namespace tin::ui
{
BoxElement::BoxElement(u32 width, u32 height) :
Element(width, height)
{
}
void BoxElement::Draw(Canvas canvas, Position position)
{
// There is nothing to draw if the alpha is 0
if (m_colour.a)
{
for (u32 y = 0; y < m_dimensions.height; y++)
{
for (u32 x = 0; x < m_dimensions.width; x++)
{
u32 pixelX = x + position.x;
u32 pixelY = y + position.y;
canvas.DrawPixel(pixelX, pixelY, m_colour);
}
}
}
// No need to draw sub elements if we don't have any
if (m_subElements.empty())
return;
unsigned int startOffset = 0;
for (auto& subElement : m_subElements)
{
unsigned int startX = position.x;
unsigned int startY = position.y;
switch (m_subElementLayout.arrangementType)
{
case SubElementArrangementType::TOP_TO_BOTTOM:
startY += startOffset;
break;
case SubElementArrangementType::BOTTOM_TO_TOP:
startY = startY + m_dimensions.height - subElement->GetDimensions().height - startOffset;
break;
default:
startX += startOffset;
break;
}
Position subElementPos(startX, startY);
// We need a canvas that fits into the parent canvas, is inside this element, and accounts for the desired position/size of the sub element
Canvas subElementCanvas = canvas.Intersect(position, this->GetDimensions()).Intersect(subElementPos, subElement->GetDimensions());
subElement->Draw(subElementCanvas, subElementPos);
switch (m_subElementLayout.arrangementType)
{
case SubElementArrangementType::TOP_TO_BOTTOM:
case SubElementArrangementType::BOTTOM_TO_TOP:
startOffset += subElement->GetDimensions().height + m_subElementLayout.gapSize;
break;
default:
startOffset += subElement->GetDimensions().width + m_subElementLayout.gapSize;
break;
}
}
}
void BoxElement::SetColour(tin::ui::Colour colour)
{
m_colour = colour;
}
void BoxElement::SetSubElementLayout(SubElementLayout subElementLayout)
{
m_subElementLayout = subElementLayout;
}
void BoxElement::AddSubElement(std::unique_ptr<Element> element)
{
m_subElements.push_back(std::move(element));
}
}
| 31.362637
| 151
| 0.555011
|
ThatNerdyPikachu
|
2a6b274a5bd14e6af1a96918d94d45122af4d020
| 1,124
|
cpp
|
C++
|
Striver SDE Sheet/Day - 19 (Binary Tree)/Construct BTree from Inorder and Preorder(Hard).cpp
|
HariAcidReign/Striver-SDE-Solutions
|
80757b212abe479f3975b890398a8d877ebfd41e
|
[
"MIT"
] | 25
|
2021-08-17T04:04:41.000Z
|
2022-03-16T07:43:30.000Z
|
Striver SDE Sheet/Day - 19 (Binary Tree)/Construct BTree from Inorder and Preorder(Hard).cpp
|
hashwanthalla/Striver-Sheets-Resources
|
80757b212abe479f3975b890398a8d877ebfd41e
|
[
"MIT"
] | null | null | null |
Striver SDE Sheet/Day - 19 (Binary Tree)/Construct BTree from Inorder and Preorder(Hard).cpp
|
hashwanthalla/Striver-Sheets-Resources
|
80757b212abe479f3975b890398a8d877ebfd41e
|
[
"MIT"
] | 8
|
2021-08-18T02:02:23.000Z
|
2022-02-11T06:05:07.000Z
|
// Hari
class Solution {
public:
int idx = 0;
unordered_map<int, int> m;
TreeNode* helper(vector<int>preorder, vector<int>inorder, int start, int end){
// traverse preorder
if(start > end) return nullptr; // base case
TreeNode* curr = new TreeNode(preorder[idx++]);
if(start == end) return curr; // when leaf node added
int mid = m[curr->val]; // get parent index.
curr->left = helper(preorder, inorder, start, mid-1);
curr->right = helper(preorder, inorder, mid+1, end);
return curr;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
// preorder gives us the parent each time. Search this parent in inorder
// (using map O(1)) and left of this in left subtree, right in right subtree
idx = 0;
m.clear();
int N = inorder.size();
// filling map using inorder elements
for(int i = 0; i<N; i++) m[inorder[i]] = i; // quick element index retrieval
TreeNode* root = helper(preorder, inorder, 0, N-1);
return root;
}
};
| 35.125
| 84
| 0.580071
|
HariAcidReign
|
2a722c31cdb4c459fc0986aa3c8189d900650a90
| 86,907
|
cpp
|
C++
|
Engine/source/interior/interior.cpp
|
baktubak/Torque3D
|
c26235c5b81ed55b231af86254d740ce17540d25
|
[
"MIT"
] | 6
|
2015-06-01T15:44:43.000Z
|
2021-01-07T06:50:21.000Z
|
Engine/source/interior/interior.cpp
|
timmgt/Torque3D
|
ebc6c9cf3a2c7642b2cd30be3726810a302c3deb
|
[
"Unlicense"
] | null | null | null |
Engine/source/interior/interior.cpp
|
timmgt/Torque3D
|
ebc6c9cf3a2c7642b2cd30be3726810a302c3deb
|
[
"Unlicense"
] | 10
|
2015-01-05T15:58:31.000Z
|
2021-11-20T14:05:46.000Z
|
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#include "platform/platform.h"
#include "interior/interior.h"
#include "scene/sceneRenderState.h"
#include "scene/sceneManager.h"
#include "gfx/bitmap/gBitmap.h"
#include "math/mMatrix.h"
#include "math/mRect.h"
#include "core/bitVector.h"
#include "core/frameAllocator.h"
#include "scene/sgUtil.h"
#include "platform/profiler.h"
#include "gfx/gfxDevice.h"
#include "gfx/gfxTextureHandle.h"
#include "materials/materialList.h"
#include "materials/matInstance.h"
#include "materials/materialManager.h"
#include "renderInstance/renderPassManager.h"
#include "materials/processedMaterial.h"
#include "materials/materialFeatureTypes.h"
U32 Interior::smRenderMode = 0;
bool Interior::smFocusedDebug = false;
bool Interior::smUseVertexLighting = false;
bool Interior::smLightingCastRays = false;
bool Interior::smLightingBuildPolyList = false;
// These are setup by setupActivePolyList
U16* sgActivePolyList = NULL;
U32 sgActivePolyListSize = 0;
U16* sgEnvironPolyList = NULL;
U32 sgEnvironPolyListSize = 0;
U16* sgFogPolyList = NULL;
U32 sgFogPolyListSize = 0;
bool sgFogActive = false;
// Always the same size as the mPoints array
Point2F* sgFogTexCoords = NULL;
class PlaneRange
{
public:
U32 start;
U32 count;
};
namespace {
struct PortalRenderInfo
{
bool render;
F64 frustum[4];
RectI viewport;
};
//-------------------------------------- Rendering state variables.
Point3F sgCamPoint;
F64 sgStoredFrustum[6];
RectI sgStoredViewport;
Vector<PortalRenderInfo> sgZoneRenderInfo(__FILE__, __LINE__);
// Takes OS coords to clip space...
MatrixF sgWSToOSMatrix;
MatrixF sgProjMatrix;
PlaneF sgOSPlaneFar;
PlaneF sgOSPlaneXMin;
PlaneF sgOSPlaneXMax;
PlaneF sgOSPlaneYMin;
PlaneF sgOSPlaneYMax;
struct ZoneRect {
RectD rect;
bool active;
};
Vector<ZoneRect> sgZoneRects(__FILE__, __LINE__);
//-------------------------------------- Little utility functions
RectD outlineRects(const Vector<RectD>& rects)
{
F64 minx = 1e10;
F64 maxx = -1e10;
F64 miny = 1e10;
F64 maxy = -1e10;
for (S32 i = 0; i < rects.size(); i++)
{
if (rects[i].point.x < minx)
minx = rects[i].point.x;
if (rects[i].point.y < miny)
miny = rects[i].point.y;
if (rects[i].point.x + rects[i].extent.x > maxx)
maxx = rects[i].point.x + rects[i].extent.x;
if (rects[i].point.y + rects[i].extent.y > maxy)
maxy = rects[i].point.y + rects[i].extent.y;
}
return RectD(minx, miny, maxx - minx, maxy - miny);
}
void insertZoneRects(ZoneRect& rZoneRect, const RectD* rects, const U32 numRects)
{
F64 minx = 1e10;
F64 maxx = -1e10;
F64 miny = 1e10;
F64 maxy = -1e10;
for (U32 i = 0; i < numRects; i++) {
if (rects[i].point.x < minx)
minx = rects[i].point.x;
if (rects[i].point.y < miny)
miny = rects[i].point.y;
if (rects[i].point.x + rects[i].extent.x > maxx)
maxx = rects[i].point.x + rects[i].extent.x;
if (rects[i].point.y + rects[i].extent.y > maxy)
maxy = rects[i].point.y + rects[i].extent.y;
}
if (rZoneRect.active == false && numRects != 0) {
rZoneRect.rect = RectD(minx, miny, maxx - minx, maxy - miny);
rZoneRect.active = true;
} else {
if (rZoneRect.rect.point.x < minx)
minx = rZoneRect.rect.point.x;
if (rZoneRect.rect.point.y < miny)
miny = rZoneRect.rect.point.y;
if (rZoneRect.rect.point.x + rZoneRect.rect.extent.x > maxx)
maxx = rZoneRect.rect.point.x + rZoneRect.rect.extent.x;
if (rZoneRect.rect.point.y + rZoneRect.rect.extent.y > maxy)
maxy = rZoneRect.rect.point.y + rZoneRect.rect.extent.y;
rZoneRect.rect = RectD(minx, miny, maxx - minx, maxy - miny);
}
}
void fixupViewport(PortalRenderInfo& rInfo)
{
F64 widthV = rInfo.frustum[1] - rInfo.frustum[0];
F64 heightV = rInfo.frustum[3] - rInfo.frustum[2];
F64 fx0 = (rInfo.frustum[0] - sgStoredFrustum[0]) / (sgStoredFrustum[1] - sgStoredFrustum[0]);
F64 fx1 = (sgStoredFrustum[1] - rInfo.frustum[1]) / (sgStoredFrustum[1] - sgStoredFrustum[0]);
F64 dV0 = F64(sgStoredViewport.point.x) + fx0 * F64(sgStoredViewport.extent.x);
F64 dV1 = F64(sgStoredViewport.point.x +
sgStoredViewport.extent.x) - fx1 * F64(sgStoredViewport.extent.x);
F64 fdV0 = getMax(mFloorD(dV0), F64(sgStoredViewport.point.x));
F64 cdV1 = getMin(mCeilD(dV1), F64(sgStoredViewport.point.x + sgStoredViewport.extent.x));
// If the width is 1 pixel, we need to widen it up a bit...
if ((cdV1 - fdV0) <= 1.0)
cdV1 = fdV0 + 1;
AssertFatal((fdV0 >= sgStoredViewport.point.x &&
cdV1 <= sgStoredViewport.point.x + sgStoredViewport.extent.x),
"Out of bounds viewport bounds");
F64 new0 = rInfo.frustum[0] - ((dV0 - fdV0) * (widthV / F64(sgStoredViewport.extent.x)));
F64 new1 = rInfo.frustum[1] + ((cdV1 - dV1) * (widthV / F64(sgStoredViewport.extent.x)));
rInfo.frustum[0] = new0;
rInfo.frustum[1] = new1;
rInfo.viewport.point.x = S32(fdV0);
rInfo.viewport.extent.x = S32(cdV1) - rInfo.viewport.point.x;
F64 fy0 = (sgStoredFrustum[3] - rInfo.frustum[3]) / (sgStoredFrustum[3] - sgStoredFrustum[2]);
F64 fy1 = (rInfo.frustum[2] - sgStoredFrustum[2]) / (sgStoredFrustum[3] - sgStoredFrustum[2]);
dV0 = F64(sgStoredViewport.point.y) + fy0 * F64(sgStoredViewport.extent.y);
dV1 = F64(sgStoredViewport.point.y +
sgStoredViewport.extent.y) - fy1 * F64(sgStoredViewport.extent.y);
fdV0 = getMax(mFloorD(dV0), F64(sgStoredViewport.point.y));
cdV1 = getMin(mCeilD(dV1), F64(sgStoredViewport.point.y + sgStoredViewport.extent.y));
// If the width is 1 pixel, we need to widen it up a bit...
if ((cdV1 - fdV0) <= 1.0)
cdV1 = fdV0 + 1;
// GFX2_RENDER_MERGE
// Need to fix this properly but for now *HACK*
#ifndef TORQUE_OS_MAC
AssertFatal((fdV0 >= sgStoredViewport.point.y &&
cdV1 <= sgStoredViewport.point.y + sgStoredViewport.extent.y),
"Out of bounds viewport bounds");
#endif
new0 = rInfo.frustum[2] - ((cdV1 - dV1) * (heightV / F64(sgStoredViewport.extent.y)));
new1 = rInfo.frustum[3] + ((dV0 - fdV0) * (heightV / F64(sgStoredViewport.extent.y)));
rInfo.frustum[2] = new0;
rInfo.frustum[3] = new1;
rInfo.viewport.point.y = S32(fdV0);
rInfo.viewport.extent.y = S32(cdV1) - rInfo.viewport.point.y;
}
RectD convertToRectD(const F64 inResult[4])
{
F64 minx = ((inResult[0] + 1.0f) / 2.0f) * (sgStoredFrustum[1] - sgStoredFrustum[0]) + sgStoredFrustum[0];
F64 maxx = ((inResult[2] + 1.0f) / 2.0f) * (sgStoredFrustum[1] - sgStoredFrustum[0]) + sgStoredFrustum[0];
F64 miny = ((inResult[1] + 1.0f) / 2.0f) * (sgStoredFrustum[3] - sgStoredFrustum[2]) + sgStoredFrustum[2];
F64 maxy = ((inResult[3] + 1.0f) / 2.0f) * (sgStoredFrustum[3] - sgStoredFrustum[2]) + sgStoredFrustum[2];
return RectD(minx, miny, (maxx - minx), (maxy - miny));
}
void convertToFrustum(PortalRenderInfo& zrInfo, const RectD& finalRect)
{
zrInfo.frustum[0] = finalRect.point.x; // left
zrInfo.frustum[1] = finalRect.point.x + finalRect.extent.x; // right
zrInfo.frustum[2] = finalRect.point.y; // bottom
zrInfo.frustum[3] = finalRect.point.y + finalRect.extent.y; // top
fixupViewport(zrInfo);
}
} // namespace {}
//------------------------------------------------------------------------------
//-------------------------------------- IMPLEMENTATION
//
Interior::Interior()
{
mMaterialList = NULL;
mHasTranslucentMaterials = false;
mLMHandle = LM_HANDLE(-1);
// By default, no alarm state, no animated light states
mHasAlarmState = false;
mNumLightStateEntries = 0;
mNumTriggerableLights = 0;
mPreppedForRender = false;;
mSearchTag = 0;
mLightMapBorderSize = 0;
#ifndef TORQUE_SHIPPING
mDebugShader = NULL;
mDebugShaderModelViewSC = NULL;
mDebugShaderShadeColorSC = NULL;
#endif
// Bind our vectors
VECTOR_SET_ASSOCIATION(mPlanes);
VECTOR_SET_ASSOCIATION(mPoints);
VECTOR_SET_ASSOCIATION(mBSPNodes);
VECTOR_SET_ASSOCIATION(mBSPSolidLeaves);
VECTOR_SET_ASSOCIATION(mWindings);
VECTOR_SET_ASSOCIATION(mTexGenEQs);
VECTOR_SET_ASSOCIATION(mLMTexGenEQs);
VECTOR_SET_ASSOCIATION(mWindingIndices);
VECTOR_SET_ASSOCIATION(mSurfaces);
VECTOR_SET_ASSOCIATION(mNullSurfaces);
VECTOR_SET_ASSOCIATION(mSolidLeafSurfaces);
VECTOR_SET_ASSOCIATION(mZones);
VECTOR_SET_ASSOCIATION(mZonePlanes);
VECTOR_SET_ASSOCIATION(mZoneSurfaces);
VECTOR_SET_ASSOCIATION(mZonePortalList);
VECTOR_SET_ASSOCIATION(mPortals);
//VECTOR_SET_ASSOCIATION(mSubObjects);
VECTOR_SET_ASSOCIATION(mLightmaps);
VECTOR_SET_ASSOCIATION(mLightmapKeep);
VECTOR_SET_ASSOCIATION(mNormalLMapIndices);
VECTOR_SET_ASSOCIATION(mAlarmLMapIndices);
VECTOR_SET_ASSOCIATION(mAnimatedLights);
VECTOR_SET_ASSOCIATION(mLightStates);
VECTOR_SET_ASSOCIATION(mStateData);
VECTOR_SET_ASSOCIATION(mStateDataBuffer);
VECTOR_SET_ASSOCIATION(mNameBuffer);
VECTOR_SET_ASSOCIATION(mConvexHulls);
VECTOR_SET_ASSOCIATION(mConvexHullEmitStrings);
VECTOR_SET_ASSOCIATION(mHullIndices);
VECTOR_SET_ASSOCIATION(mHullEmitStringIndices);
VECTOR_SET_ASSOCIATION(mHullSurfaceIndices);
VECTOR_SET_ASSOCIATION(mHullPlaneIndices);
VECTOR_SET_ASSOCIATION(mPolyListPlanes);
VECTOR_SET_ASSOCIATION(mPolyListPoints);
VECTOR_SET_ASSOCIATION(mPolyListStrings);
VECTOR_SET_ASSOCIATION(mCoordBinIndices);
VECTOR_SET_ASSOCIATION(mVehicleConvexHulls);
VECTOR_SET_ASSOCIATION(mVehicleConvexHullEmitStrings);
VECTOR_SET_ASSOCIATION(mVehicleHullIndices);
VECTOR_SET_ASSOCIATION(mVehicleHullEmitStringIndices);
VECTOR_SET_ASSOCIATION(mVehicleHullSurfaceIndices);
VECTOR_SET_ASSOCIATION(mVehicleHullPlaneIndices);
VECTOR_SET_ASSOCIATION(mVehiclePolyListPlanes);
VECTOR_SET_ASSOCIATION(mVehiclePolyListPoints);
VECTOR_SET_ASSOCIATION(mVehiclePolyListStrings);
VECTOR_SET_ASSOCIATION(mVehiclePoints);
VECTOR_SET_ASSOCIATION(mVehicleNullSurfaces);
VECTOR_SET_ASSOCIATION(mVehiclePlanes);
}
Interior::~Interior()
{
U32 i;
delete mMaterialList;
mMaterialList = NULL;
if(mLMHandle != LM_HANDLE(-1))
gInteriorLMManager.removeInterior(mLMHandle);
for(i = 0; i < mLightmaps.size(); i++)
{
delete mLightmaps[i];
mLightmaps[i] = NULL;
}
for(i = 0; i < mMatInstCleanupList.size(); i++)
{
delete mMatInstCleanupList[i];
mMatInstCleanupList[i] = NULL;
}
for(S32 i=0; i<mStaticMeshes.size(); i++)
delete mStaticMeshes[i];
}
//--------------------------------------------------------------------------
bool Interior::prepForRendering(const char* path)
{
if(mPreppedForRender == true)
return true;
// Before we load the material list we temporarily remove
// some special texture names so that we don't get bogus
// texture load warnings in the console.
const Vector<String> &matNames = mMaterialList->getMaterialNameList();
Vector<String> originalNames = matNames;
for (U32 i = 0; i < matNames.size(); i++)
{
if (matNames[i].equal("NULL", String::NoCase) ||
matNames[i].equal("ORIGIN", String::NoCase) ||
matNames[i].equal("TRIGGER", String::NoCase) ||
matNames[i].equal("FORCEFIELD", String::NoCase) ||
matNames[i].equal("EMITTER", String::NoCase) )
{
mMaterialList->setMaterialName(i, String());
}
}
String relPath = Platform::makeRelativePathName(path, Platform::getCurrentDirectory());
// Load the material list
mMaterialList->setTextureLookupPath(relPath);
mMaterialList->mapMaterials();
// Grab all the static meshes and load any textures that didn't originate
// from inside the DIF.
for(S32 i=0; i<mStaticMeshes.size(); i++)
mStaticMeshes[i]->materialList->setTextureLookupPath(relPath);
// Now restore the material names since someone later may
// count on the special texture names being present.
for (U32 i = 0; i < originalNames.size(); i++)
mMaterialList->setMaterialName(i, originalNames[i]);
fillSurfaceTexMats();
createZoneVBs();
cloneMatInstances();
createReflectPlanes();
initMatInstances();
// lightmap manager steals the lightmaps here...
gInteriorLMManager.addInterior(mLMHandle, mLightmaps.size(), this);
AssertFatal(!mLightmaps.size(), "Failed to process lightmaps");
for(U32 i=0; i<mStaticMeshes.size(); i++)
mStaticMeshes[i]->prepForRendering(relPath);
GFXStateBlockDesc sh;
#ifndef TORQUE_SHIPPING
// First create a default state block with
// texturing turned off
mInteriorDebugNoneSB = GFX->createStateBlock(sh);
// Create a state block for portal rendering that
// doesn't have backface culling enabled
sh.cullDefined = true;
sh.cullMode = GFXCullNone;
mInteriorDebugPortalSB = GFX->createStateBlock(sh);
// Reset our cull mode to the default
sh.cullMode = GFXCullCCW;
#endif
// Next turn on the first texture channel
sh.samplersDefined = true;
sh.samplers[0].textureColorOp = GFXTOPModulate;
#ifndef TORQUE_SHIPPING
mInteriorDebugTextureSB = GFX->createStateBlock(sh);
sh.samplers[1].textureColorOp = GFXTOPModulate;
mInteriorDebugTwoTextureSB = GFX->createStateBlock(sh);
#endif
// Lastly create a standard rendering state block
sh.samplers[2].textureColorOp = GFXTOPModulate;
sh.samplers[0].magFilter = GFXTextureFilterLinear;
sh.samplers[0].minFilter = GFXTextureFilterLinear;
mInteriorSB = GFX->createStateBlock(sh);
mPreppedForRender = true;
return true;
}
void Interior::setupAveTexGenLength()
{
/*
F32 len = 0;
for (U32 i = 0; i < mSurfaces.size(); i++)
{
// We're going to assume that most textures don't have separate scales for
// x and y...
F32 lenx = mTexGenEQs[mSurfaces[i].texGenIndex].planeX.len();
len += F32((*mMaterialList)[mSurfaces[i].textureIndex].getWidth()) * lenx;
}
len /= F32(mSurfaces.size());
mAveTexGenLength = len;
*/
}
//--------------------------------------------------------------------------
bool Interior::traverseZones(SceneCullingState* state,
const Frustum& frustum,
S32 containingZone,
S32 baseZone,
U32 zoneOffset,
const MatrixF& OSToWS,
const Point3F& objScale,
const bool dontRestrictOutside,
const bool flipClipPlanes,
Frustum& outFrustum)
{
// Store off the viewport and frustum
sgStoredViewport = state->getCameraState().getViewport();
if( dontRestrictOutside )
{
sgStoredFrustum[0] = state->getFrustum().getNearLeft();
sgStoredFrustum[1] = state->getFrustum().getNearRight();
sgStoredFrustum[2] = state->getFrustum().getNearBottom();
sgStoredFrustum[3] = state->getFrustum().getNearTop();
sgStoredFrustum[4] = state->getFrustum().getNearDist();
sgStoredFrustum[5] = state->getFrustum().getFarDist();
}
else
{
sgStoredFrustum[0] = frustum.getNearLeft();
sgStoredFrustum[1] = frustum.getNearRight();
sgStoredFrustum[2] = frustum.getNearBottom();
sgStoredFrustum[3] = frustum.getNearTop();
sgStoredFrustum[4] = frustum.getNearDist();
sgStoredFrustum[5] = frustum.getFarDist();
}
sgProjMatrix = state->getCameraState().getProjectionMatrix();
MatrixF finalModelView = state->getCameraState().getWorldViewMatrix();
finalModelView.mul(OSToWS);
finalModelView.scale(Point3F(objScale.x, objScale.y, objScale.z));
sgProjMatrix.mul(finalModelView);
finalModelView.inverse();
finalModelView.mulP(Point3F(0, 0, 0), &sgCamPoint);
sgWSToOSMatrix = finalModelView;
// do the zone traversal
sgZoneRenderInfo.setSize(mZones.size());
zoneTraversal(baseZone, flipClipPlanes);
// Copy out the information for all zones but the outside zone.
for(U32 i = 1; i < mZones.size(); i++)
{
AssertFatal(zoneOffset != 0xFFFFFFFF, "Error, this should never happen!");
U32 globalIndex = i + zoneOffset - 1;
if( sgZoneRenderInfo[ i ].render )
{
state->addCullingVolumeToZone(
globalIndex,
SceneCullingVolume::Includer,
Frustum(
frustum.isOrtho(),
sgZoneRenderInfo[ i ].frustum[ 0 ],
sgZoneRenderInfo[ i ].frustum[ 1 ],
sgZoneRenderInfo[ i ].frustum[ 3 ],
sgZoneRenderInfo[ i ].frustum[ 2 ],
frustum.getNearDist(),
frustum.getFarDist(),
frustum.getTransform()
)
);
}
}
destroyZoneRectVectors();
// If zone 0 is rendered, then we return true...
bool continueOut = sgZoneRenderInfo[ 0 ].render;
if( continueOut )
outFrustum = Frustum(
frustum.isOrtho(),
sgZoneRenderInfo[ 0 ].frustum[ 0 ],
sgZoneRenderInfo[ 0 ].frustum[ 1 ],
sgZoneRenderInfo[ 0 ].frustum[ 3 ],
sgZoneRenderInfo[ 0 ].frustum[ 2 ],
frustum.getNearDist(),
frustum.getFarDist(),
frustum.getTransform()
);
return sgZoneRenderInfo[0].render;
}
//------------------------------------------------------------------------------
S32 Interior::getZoneForPoint(const Point3F& rPoint) const
{
const IBSPNode* pNode = &mBSPNodes[0];
while (true) {
F32 dist = getPlane(pNode->planeIndex).distToPlane(rPoint);
if (planeIsFlipped(pNode->planeIndex))
dist = -dist;
U32 traverseIndex;
if (dist >= 0)
traverseIndex = pNode->frontIndex;
else
traverseIndex = pNode->backIndex;
if (isBSPLeafIndex(traverseIndex)) {
if (isBSPSolidLeaf(traverseIndex)) {
return -1;
} else {
U16 zone = getBSPEmptyLeafZone(traverseIndex);
if (zone == 0x0FFF)
return -1;
else
return zone;
}
}
pNode = &mBSPNodes[traverseIndex];
}
}
//--------------------------------------------------------------------------
static void itrClipToPlane(Point3F* points, U32& rNumPoints, const PlaneF& rPlane)
{
S32 start = -1;
for(U32 i = 0; i < rNumPoints; i++)
{
if(rPlane.whichSide(points[i]) == PlaneF::Front)
{
start = i;
break;
}
}
// Nothing was in front of the plane...
if(start == -1)
{
rNumPoints = 0;
return;
}
static Point3F finalPoints[128];
U32 numFinalPoints = 0;
U32 baseStart = start;
U32 end = (start + 1) % rNumPoints;
while(end != baseStart)
{
const Point3F& rStartPoint = points[start];
const Point3F& rEndPoint = points[end];
PlaneF::Side fSide = rPlane.whichSide(rStartPoint);
PlaneF::Side eSide = rPlane.whichSide(rEndPoint);
S32 code = fSide * 3 + eSide;
switch(code)
{
case 4: // f f
case 3: // f o
case 1: // o f
case 0: // o o
// No Clipping required
finalPoints[numFinalPoints++] = points[start];
start = end;
end = (end + 1) % rNumPoints;
break;
case 2: // f b
{
// In this case, we emit the front point, Insert the intersection,
// and advancing to point to first point that is in front or on...
//
finalPoints[numFinalPoints++] = points[start];
Point3F vector = rEndPoint - rStartPoint;
F32 t = -(rPlane.distToPlane(rStartPoint) / mDot(rPlane, vector));
Point3F intersection = rStartPoint + (vector * t);
finalPoints[numFinalPoints++] = intersection;
U32 endSeek = (end + 1) % rNumPoints;
while(rPlane.whichSide(points[endSeek]) == PlaneF::Back)
endSeek = (endSeek + 1) % rNumPoints;
end = endSeek;
start = (end + (rNumPoints - 1)) % rNumPoints;
const Point3F& rNewStartPoint = points[start];
const Point3F& rNewEndPoint = points[end];
vector = rNewEndPoint - rNewStartPoint;
t = -(rPlane.distToPlane(rNewStartPoint) / mDot(rPlane, vector));
intersection = rNewStartPoint + (vector * t);
points[start] = intersection;
}
break;
case -1: // o b
{
// In this case, we emit the front point, and advance to point to first
// point that is in front or on...
//
finalPoints[numFinalPoints++] = points[start];
U32 endSeek = (end + 1) % rNumPoints;
while(rPlane.whichSide(points[endSeek]) == PlaneF::Back)
endSeek = (endSeek + 1) % rNumPoints;
end = endSeek;
start = (end + (rNumPoints - 1)) % rNumPoints;
const Point3F& rNewStartPoint = points[start];
const Point3F& rNewEndPoint = points[end];
Point3F vector = rNewEndPoint - rNewStartPoint;
F32 t = -(rPlane.distToPlane(rNewStartPoint) / mDot(rPlane, vector));
Point3F intersection = rNewStartPoint + (vector * t);
points[start] = intersection;
}
break;
case -2: // b f
case -3: // b o
case -4: // b b
// In the algorithm used here, this should never happen...
AssertISV(false, "CSGPlane::clipWindingToPlaneFront: error in polygon clipper");
break;
default:
AssertFatal(false, "CSGPlane::clipWindingToPlaneFront: bad outcode");
break;
}
}
// Emit the last point.
finalPoints[numFinalPoints++] = points[start];
AssertFatal(numFinalPoints >= 3, avar("Error, this shouldn't happen! Invalid winding in itrClipToPlane: %d", numFinalPoints));
// Copy the new rWinding, and we're set!
//
dMemcpy(points, finalPoints, numFinalPoints * sizeof(Point3F));
rNumPoints = numFinalPoints;
AssertISV(rNumPoints <= 128, "Increase maxWindingPoints. Talk to DMoore");
}
bool Interior::projectClipAndBoundFan(U32 fanIndex, F64* pResult)
{
const TriFan& rFan = mWindingIndices[fanIndex];
static Point3F windingPoints[128];
U32 numPoints = rFan.windingCount;
U32 i;
for(i = 0; i < numPoints; i++)
windingPoints[i] = mPoints[mWindings[rFan.windingStart + i]].point;
itrClipToPlane(windingPoints, numPoints, sgOSPlaneFar);
if(numPoints != 0)
itrClipToPlane(windingPoints, numPoints, sgOSPlaneXMin);
if(numPoints != 0)
itrClipToPlane(windingPoints, numPoints, sgOSPlaneXMax);
if(numPoints != 0)
itrClipToPlane(windingPoints, numPoints, sgOSPlaneYMin);
if(numPoints != 0)
itrClipToPlane(windingPoints, numPoints, sgOSPlaneYMax);
if(numPoints == 0)
{
pResult[0] =
pResult[1] =
pResult[2] =
pResult[3] = 0.0f;
return false;
}
F32 minX = 1e10;
F32 maxX = -1e10;
F32 minY = 1e10;
F32 maxY = -1e10;
static Point4F projPoints[128];
for(i = 0; i < numPoints; i++)
{
projPoints[i].set(windingPoints[i].x, windingPoints[i].y, windingPoints[i].z, 1.0);
sgProjMatrix.mul(projPoints[i]);
AssertFatal(projPoints[i].w != 0.0, "Error, that's bad!");
projPoints[i].x /= projPoints[i].w;
projPoints[i].y /= projPoints[i].w;
if(projPoints[i].x < minX)
minX = projPoints[i].x;
if(projPoints[i].x > maxX)
maxX = projPoints[i].x;
if(projPoints[i].y < minY)
minY = projPoints[i].y;
if(projPoints[i].y > maxY)
maxY = projPoints[i].y;
}
if(minX < -1.0f) minX = -1.0f;
if(minY < -1.0f) minY = -1.0f;
if(maxX > 1.0f) maxX = 1.0f;
if(maxY > 1.0f) maxY = 1.0f;
pResult[0] = minX;
pResult[1] = minY;
pResult[2] = maxX;
pResult[3] = maxY;
return true;
}
void Interior::createZoneRectVectors()
{
sgZoneRects.setSize(mZones.size());
for(U32 i = 0; i < mZones.size(); i++)
sgZoneRects[i].active = false;
}
void Interior::destroyZoneRectVectors()
{
}
void Interior::traverseZone(const RectD* inputRects, const U32 numInputRects, U32 currZone, Vector<U32>& zoneStack)
{
PROFILE_START(InteriorTraverseZone);
// First, we push onto our rect list all the inputRects...
insertZoneRects(sgZoneRects[currZone], inputRects, numInputRects);
// A portal is a valid traversal if the camera point is on the
// same side of it's plane as the zone. It must then pass the
// clip/project test.
U32 i;
const Zone& rZone = mZones[currZone];
for(i = rZone.portalStart; i < U32(rZone.portalStart + rZone.portalCount); i++)
{
const Portal& rPortal = mPortals[mZonePortalList[i]];
AssertFatal(U32(rPortal.zoneFront) == currZone || U32(rPortal.zoneBack) == currZone,
"Portal doesn't reference this zone?");
S32 camSide = getPlane(rPortal.planeIndex).whichSide(sgCamPoint);
if(planeIsFlipped(rPortal.planeIndex))
camSide = -camSide;
S32 zoneSide = (U32(rPortal.zoneFront) == currZone) ? 1 : -1;
U16 otherZone = (U32(rPortal.zoneFront) == currZone) ? rPortal.zoneBack : rPortal.zoneFront;
// Make sure this isn't a free floating portal...
if(otherZone == currZone)
continue;
// Make sure we haven't encountered this zone already in this traversal
bool onStack = false;
for(U32 i = 0; i < zoneStack.size(); i++)
{
if(otherZone == zoneStack[i])
{
onStack = true;
break;
}
}
if(onStack == true)
continue;
if(camSide == zoneSide)
{
// Can traverse. Note: special case PlaneF::On
// here to prevent possible w == 0 problems and infinite recursion
// Vector<RectD> newRects;
// VECTOR_SET_ASSOCIATION(newRects);
// We're abusing the heck out of the allocator here.
U32 waterMark = FrameAllocator::getWaterMark();
RectD* newRects = (RectD*)FrameAllocator::alloc(1);
U32 numNewRects = 0;
for(S32 j = 0; j < rPortal.triFanCount; j++)
{
F64 result[4];
if(projectClipAndBoundFan(rPortal.triFanStart + j, result))
{
// Have a good rect from this.
RectD possible = convertToRectD(result);
for(U32 k = 0; k < numInputRects; k++)
{
RectD copy = possible;
if(copy.intersect(inputRects[k]))
newRects[numNewRects++] = copy;
}
}
}
if(numNewRects != 0)
{
FrameAllocator::alloc((sizeof(RectD) * numNewRects) - 1);
U32 prevStackSize = zoneStack.size();
zoneStack.push_back(currZone);
traverseZone(newRects, numNewRects, otherZone, zoneStack);
zoneStack.pop_back();
AssertFatal(zoneStack.size() == prevStackSize, "Error, stack size changed!");
}
FrameAllocator::setWaterMark(waterMark);
}
else if(camSide == PlaneF::On)
{
U32 waterMark = FrameAllocator::getWaterMark();
RectD* newRects = (RectD*)FrameAllocator::alloc(numInputRects * sizeof(RectD));
dMemcpy(newRects, inputRects, sizeof(RectD) * numInputRects);
U32 prevStackSize = zoneStack.size();
zoneStack.push_back(currZone);
traverseZone(newRects, numInputRects, otherZone, zoneStack);
zoneStack.pop_back();
AssertFatal(zoneStack.size() == prevStackSize, "Error, stack size changed!");
FrameAllocator::setWaterMark(waterMark);
}
}
PROFILE_END();
}
void Interior::zoneTraversal(S32 baseZone, const bool flipClip)
{
PROFILE_START(InteriorZoneTraversal);
// If we're in solid, render everything...
if(baseZone == -1)
{
for(U32 i = 0; i < mZones.size(); i++)
{
sgZoneRenderInfo[i].render = true;
sgZoneRenderInfo[i].frustum[0] = sgStoredFrustum[0];
sgZoneRenderInfo[i].frustum[1] = sgStoredFrustum[1];
sgZoneRenderInfo[i].frustum[2] = sgStoredFrustum[2];
sgZoneRenderInfo[i].frustum[3] = sgStoredFrustum[3];
sgZoneRenderInfo[i].viewport = sgStoredViewport;
}
PROFILE_END();
return;
}
// Otherwise, we're going to have to do some work...
createZoneRectVectors();
U32 i;
for(i = 0; i < mZones.size(); i++)
sgZoneRenderInfo[i].render = false;
// Create the object space clipping planes...
sgComputeOSFrustumPlanes(sgStoredFrustum,
sgWSToOSMatrix,
sgCamPoint,
sgOSPlaneFar,
sgOSPlaneXMin,
sgOSPlaneXMax,
sgOSPlaneYMin,
sgOSPlaneYMax);
if(flipClip == true)
{
sgOSPlaneXMin.neg();
sgOSPlaneXMax.neg();
sgOSPlaneYMin.neg();
sgOSPlaneYMax.neg();
}
// First, the current zone gets the full clipRect, and marked as rendering...
static const F64 fullResult[4] = { -1, -1, 1, 1};
static Vector<U32> zoneStack;
zoneStack.clear();
VECTOR_SET_ASSOCIATION(zoneStack);
RectD baseRect = convertToRectD(fullResult);
traverseZone(&baseRect, 1, baseZone, zoneStack);
for(i = 0; i < mZones.size(); i++)
{
if(sgZoneRects[i].active == true)
{
sgZoneRenderInfo[i].render = true;
convertToFrustum(sgZoneRenderInfo[i], sgZoneRects[i].rect);
}
}
PROFILE_END();
}
void mergeSurfaceVectors(const U16* from0,
const U32 size0,
const U16* from1,
const U32 size1,
U16* output,
U32* outputSize)
{
U32 pos0 = 0;
U32 pos1 = 0;
U32 outputCount = 0;
while(pos0 < size0 && pos1 < size1)
{
if(from0[pos0] < from1[pos1])
{
output[outputCount++] = from0[pos0++];
}
else if(from0[pos0] == from1[pos1])
{
// Equal, output one, and inc both counts
output[outputCount++] = from0[pos0++];
pos1++;
}
else
{
output[outputCount++] = from1[pos1++];
}
}
AssertFatal(pos0 == size0 || pos1 == size1, "Error, one of these must have reached the end!");
// Copy the dregs...
if(pos0 != size0)
{
dMemcpy(&output[outputCount], &from0[pos0], sizeof(U16) * (size0 - pos0));
outputCount += size0 - pos0;
}
else if(pos1 != size1)
{
dMemcpy(&output[outputCount], &from1[pos1], sizeof(U16) * (size1 - pos1));
outputCount += size1 - pos1;
}
*outputSize = outputCount;
}
// Remove any collision hulls, interval trees, etc...
//
void Interior::purgeLODData()
{
mConvexHulls.clear();
mHullIndices.clear();
mHullEmitStringIndices.clear();
mHullSurfaceIndices.clear();
mCoordBinIndices.clear();
mConvexHullEmitStrings.clear();
for(U32 i = 0; i < NumCoordBins * NumCoordBins; i++)
{
mCoordBins[i].binStart = 0;
mCoordBins[i].binCount = 0;
}
}
// Build an OptimizedPolyList that represents this Interior's mesh
void Interior::buildExportPolyList(OptimizedPolyList& polys, MatrixF* mat, Point3F* scale)
{
MatrixF saveMat;
Point3F saveScale;
polys.getTransform(&saveMat, &saveScale);
if (mat)
{
if (scale)
polys.setTransform(mat, *scale);
else
polys.setTransform(mat, Point3F(1.0f, 1.0f, 1.0f));
}
// Create one TSMesh per zone
for (U32 i = 0; i < mZones.size(); i++)
{
const Interior::Zone& zone = mZones[i];
// Gather some data
for (U32 j = 0; j < zone.surfaceCount; j++)
{
U32 sdx = mZoneSurfaces[zone.surfaceStart + j];
const Interior::Surface& surface = mSurfaces[sdx];
// Snag the MaterialInstance
BaseMatInstance *matInst = mMaterialList->getMaterialInst( surface.textureIndex );
// Start a poly
polys.begin(matInst, j, OptimizedPolyList::TriangleStrip);
// Set its plane
PlaneF plane = getFlippedPlane(surface.planeIndex);
polys.plane(plane);
// Get its texGen so that we can calculate uvs
Interior::TexGenPlanes texGens = mTexGenEQs[surface.texGenIndex];
texGens.planeY.invert();
// Loop through and add the verts and uvs
for (U32 k = 0; k < surface.windingCount; k++)
{
// Get our point
U32 vdx = mWindings[surface.windingStart + k];
const Point3F& pt = mPoints[vdx].point;
// Get our uv
Point2F uv;
uv.x = texGens.planeX.distToPlane(pt);
uv.y = texGens.planeY.distToPlane(pt);
Point3F normal = getPointNormal(sdx, k);
polys.vertex(pt, normal, uv);
}
polys.end();
}
}
polys.setTransform(&saveMat, saveScale);
}
struct TempProcSurface
{
U32 numPoints;
U32 pointIndices[32];
U16 planeIndex;
U8 mask;
};
struct PlaneGrouping
{
U32 numPlanes;
U16 planeIndices[32];
U8 mask;
};
//--------------------------------------------------------------------------
void Interior::processHullPolyLists()
{
Vector<U16> planeIndices(256, __FILE__, __LINE__);
Vector<U32> pointIndices(256, __FILE__, __LINE__);
Vector<U8> pointMasks(256, __FILE__, __LINE__);
Vector<U8> planeMasks(256, __FILE__, __LINE__);
Vector<TempProcSurface> tempSurfaces(128, __FILE__, __LINE__);
Vector<PlaneGrouping> planeGroups(32, __FILE__, __LINE__);
// Reserve space in the vectors
{
mPolyListStrings.setSize(0);
mPolyListStrings.reserve(128 << 10);
mPolyListPoints.setSize(0);
mPolyListPoints.reserve(32 << 10);
mPolyListPlanes.setSize(0);
mPolyListPlanes.reserve(16 << 10);
}
for(U32 i = 0; i < mConvexHulls.size(); i++)
{
U32 j, k, l, m;
ConvexHull& rHull = mConvexHulls[i];
planeIndices.setSize(0);
pointIndices.setSize(0);
tempSurfaces.setSize(0);
// Extract all the surfaces from this hull into our temporary processing format
{
for(j = 0; j < rHull.surfaceCount; j++)
{
tempSurfaces.increment();
TempProcSurface& temp = tempSurfaces.last();
U32 surfaceIndex = mHullSurfaceIndices[j + rHull.surfaceStart];
if(isNullSurfaceIndex(surfaceIndex))
{
const NullSurface& rSurface = mNullSurfaces[getNullSurfaceIndex(surfaceIndex)];
temp.planeIndex = rSurface.planeIndex;
temp.numPoints = rSurface.windingCount;
for(k = 0; k < rSurface.windingCount; k++)
temp.pointIndices[k] = mWindings[rSurface.windingStart + k];
}
else
{
const Surface& rSurface = mSurfaces[surfaceIndex];
temp.planeIndex = rSurface.planeIndex;
collisionFanFromSurface(rSurface, temp.pointIndices, &temp.numPoints);
}
}
}
// First order of business: extract all unique planes and points from
// the list of surfaces...
{
for(j = 0; j < tempSurfaces.size(); j++)
{
const TempProcSurface& rSurface = tempSurfaces[j];
bool found = false;
for(k = 0; k < planeIndices.size() && !found; k++)
{
if(rSurface.planeIndex == planeIndices[k])
found = true;
}
if(!found)
planeIndices.push_back(rSurface.planeIndex);
for(k = 0; k < rSurface.numPoints; k++)
{
found = false;
for(l = 0; l < pointIndices.size(); l++)
{
if(pointIndices[l] == rSurface.pointIndices[k])
found = true;
}
if(!found)
pointIndices.push_back(rSurface.pointIndices[k]);
}
}
}
// Now that we have all the unique points and planes, remap the surfaces in
// terms of the offsets into the unique point list...
{
for(j = 0; j < tempSurfaces.size(); j++)
{
TempProcSurface& rSurface = tempSurfaces[j];
// Points
for(k = 0; k < rSurface.numPoints; k++)
{
bool found = false;
for(l = 0; l < pointIndices.size(); l++)
{
if(pointIndices[l] == rSurface.pointIndices[k])
{
rSurface.pointIndices[k] = l;
found = true;
break;
}
}
AssertISV(found, "Error remapping point indices in interior collision processing");
}
}
}
// Ok, at this point, we have a list of unique points, unique planes, and the
// surfaces all remapped in those terms. We need to check our error conditions
// that will make sure that we can properly encode this hull:
{
AssertISV(planeIndices.size() < 256, "Error, > 256 planes on an interior hull");
AssertISV(pointIndices.size() < 63356, "Error, > 65536 points on an interior hull");
AssertISV(tempSurfaces.size() < 256, "Error, > 256 surfaces on an interior hull");
}
// Now we group the planes together, and merge the closest groups until we're left
// with <= 8 groups
{
planeGroups.setSize(planeIndices.size());
for(j = 0; j < planeIndices.size(); j++)
{
planeGroups[j].numPlanes = 1;
planeGroups[j].planeIndices[0] = planeIndices[j];
}
while(planeGroups.size() > 8)
{
// Find the two closest groups. If mdp(i, j) is the value of the
// largest pairwise dot product that can be computed from the vectors
// of group i, and group j, then the closest group pair is the one
// with the smallest value of mdp.
F32 currmin = 2;
S32 firstGroup = -1;
S32 secondGroup = -1;
for(j = 0; j < planeGroups.size(); j++)
{
PlaneGrouping& first = planeGroups[j];
for(k = j + 1; k < planeGroups.size(); k++)
{
PlaneGrouping& second = planeGroups[k];
F32 max = -2;
for(l = 0; l < first.numPlanes; l++)
{
for(m = 0; m < second.numPlanes; m++)
{
Point3F firstNormal = getPlane(first.planeIndices[l]);
if(planeIsFlipped(first.planeIndices[l]))
firstNormal.neg();
Point3F secondNormal = getPlane(second.planeIndices[m]);
if(planeIsFlipped(second.planeIndices[m]))
secondNormal.neg();
F32 dot = mDot(firstNormal, secondNormal);
if(dot > max)
max = dot;
}
}
if(max < currmin)
{
currmin = max;
firstGroup = j;
secondGroup = k;
}
}
}
AssertFatal(firstGroup != -1 && secondGroup != -1, "Error, unable to find a suitable pairing?");
// Merge first and second
PlaneGrouping& to = planeGroups[firstGroup];
PlaneGrouping& from = planeGroups[secondGroup];
while(from.numPlanes != 0)
{
to.planeIndices[to.numPlanes++] = from.planeIndices[from.numPlanes - 1];
from.numPlanes--;
}
// And remove the merged group
planeGroups.erase(secondGroup);
}
AssertFatal(planeGroups.size() <= 8, "Error, too many plane groupings!");
// Assign a mask to each of the plane groupings
for(j = 0; j < planeGroups.size(); j++)
planeGroups[j].mask = (1 << j);
}
// Now, assign the mask to each of the temp polys
{
for(j = 0; j < tempSurfaces.size(); j++)
{
bool assigned = false;
for(k = 0; k < planeGroups.size() && !assigned; k++)
{
for(l = 0; l < planeGroups[k].numPlanes; l++)
{
if(planeGroups[k].planeIndices[l] == tempSurfaces[j].planeIndex)
{
tempSurfaces[j].mask = planeGroups[k].mask;
assigned = true;
break;
}
}
}
AssertFatal(assigned, "Error, missed a plane somewhere in the hull poly list!");
}
}
// Copy the appropriate group mask to the plane masks
{
planeMasks.setSize(planeIndices.size());
dMemset(planeMasks.address(), 0, planeMasks.size() * sizeof(U8));
for(j = 0; j < planeIndices.size(); j++)
{
bool found = false;
for(k = 0; k < planeGroups.size() && !found; k++)
{
for(l = 0; l < planeGroups[k].numPlanes; l++)
{
if(planeGroups[k].planeIndices[l] == planeIndices[j])
{
planeMasks[j] = planeGroups[k].mask;
found = true;
break;
}
}
}
AssertFatal(planeMasks[j] != 0, "Error, missing mask for plane!");
}
}
// And whip through the points, constructing the total mask for that point
{
pointMasks.setSize(pointIndices.size());
dMemset(pointMasks.address(), 0, pointMasks.size() * sizeof(U8));
for(j = 0; j < pointIndices.size(); j++)
{
for(k = 0; k < tempSurfaces.size(); k++)
{
for(l = 0; l < tempSurfaces[k].numPoints; l++)
{
if(tempSurfaces[k].pointIndices[l] == j)
{
pointMasks[j] |= tempSurfaces[k].mask;
break;
}
}
}
AssertFatal(pointMasks[j] != 0, "Error, point must exist in at least one surface!");
}
}
// Create the emit strings, and we're done!
{
// Set the range of planes
rHull.polyListPlaneStart = mPolyListPlanes.size();
mPolyListPlanes.setSize(rHull.polyListPlaneStart + planeIndices.size());
for(j = 0; j < planeIndices.size(); j++)
mPolyListPlanes[j + rHull.polyListPlaneStart] = planeIndices[j];
// Set the range of points
rHull.polyListPointStart = mPolyListPoints.size();
mPolyListPoints.setSize(rHull.polyListPointStart + pointIndices.size());
for(j = 0; j < pointIndices.size(); j++)
mPolyListPoints[j + rHull.polyListPointStart] = pointIndices[j];
// Now the emit string. The emit string goes like: (all fields are bytes)
// NumPlanes (PLMask) * NumPlanes
// NumPointsHi NumPointsLo (PtMask) * NumPoints
// NumSurfaces
// (NumPoints SurfaceMask PlOffset (PtOffsetHi PtOffsetLo) * NumPoints) * NumSurfaces
//
U32 stringLen = 1 + planeIndices.size();
stringLen += 2 + pointIndices.size();
stringLen += 1;
for(j = 0; j < tempSurfaces.size(); j++)
stringLen += 1 + 1 + 1 + (tempSurfaces[j].numPoints * 2);
rHull.polyListStringStart = mPolyListStrings.size();
mPolyListStrings.setSize(rHull.polyListStringStart + stringLen);
U8* pString = &mPolyListStrings[rHull.polyListStringStart];
U32 currPos = 0;
// Planes
pString[currPos++] = planeIndices.size();
for(j = 0; j < planeIndices.size(); j++)
pString[currPos++] = planeMasks[j];
// Points
pString[currPos++] = (pointIndices.size() >> 8) & 0xFF;
pString[currPos++] = (pointIndices.size() >> 0) & 0xFF;
for(j = 0; j < pointIndices.size(); j++)
pString[currPos++] = pointMasks[j];
// Surfaces
pString[currPos++] = tempSurfaces.size();
for(j = 0; j < tempSurfaces.size(); j++)
{
pString[currPos++] = tempSurfaces[j].numPoints;
pString[currPos++] = tempSurfaces[j].mask;
bool found = false;
for(k = 0; k < planeIndices.size(); k++)
{
if(planeIndices[k] == tempSurfaces[j].planeIndex)
{
pString[currPos++] = k;
found = true;
break;
}
}
AssertFatal(found, "Error, missing planeindex!");
for(k = 0; k < tempSurfaces[j].numPoints; k++)
{
pString[currPos++] = (tempSurfaces[j].pointIndices[k] >> 8) & 0xFF;
pString[currPos++] = (tempSurfaces[j].pointIndices[k] >> 0) & 0xFF;
}
}
AssertFatal(currPos == stringLen, "Error, mismatched string length!");
}
} // for (i = 0; i < mConvexHulls.size(); i++)
// Compact the used vectors
{
mPolyListStrings.compact();
mPolyListPoints.compact();
mPolyListPlanes.compact();
}
}
//--------------------------------------------------------------------------
void Interior::processVehicleHullPolyLists()
{
Vector<U16> planeIndices(256, __FILE__, __LINE__);
Vector<U32> pointIndices(256, __FILE__, __LINE__);
Vector<U8> pointMasks(256, __FILE__, __LINE__);
Vector<U8> planeMasks(256, __FILE__, __LINE__);
Vector<TempProcSurface> tempSurfaces(128, __FILE__, __LINE__);
Vector<PlaneGrouping> planeGroups(32, __FILE__, __LINE__);
// Reserve space in the vectors
{
mVehiclePolyListStrings.setSize(0);
mVehiclePolyListStrings.reserve(128 << 10);
mVehiclePolyListPoints.setSize(0);
mVehiclePolyListPoints.reserve(32 << 10);
mVehiclePolyListPlanes.setSize(0);
mVehiclePolyListPlanes.reserve(16 << 10);
}
for(U32 i = 0; i < mVehicleConvexHulls.size(); i++)
{
U32 j, k, l, m;
ConvexHull& rHull = mVehicleConvexHulls[i];
planeIndices.setSize(0);
pointIndices.setSize(0);
tempSurfaces.setSize(0);
// Extract all the surfaces from this hull into our temporary processing format
{
for(j = 0; j < rHull.surfaceCount; j++)
{
tempSurfaces.increment();
TempProcSurface& temp = tempSurfaces.last();
U32 surfaceIndex = mVehicleHullSurfaceIndices[j + rHull.surfaceStart];
const NullSurface& rSurface = mVehicleNullSurfaces[getVehicleNullSurfaceIndex(surfaceIndex)];
temp.planeIndex = rSurface.planeIndex;
temp.numPoints = rSurface.windingCount;
for(k = 0; k < rSurface.windingCount; k++)
temp.pointIndices[k] = mVehicleWindings[rSurface.windingStart + k];
}
}
// First order of business: extract all unique planes and points from
// the list of surfaces...
{
for(j = 0; j < tempSurfaces.size(); j++)
{
const TempProcSurface& rSurface = tempSurfaces[j];
bool found = false;
for(k = 0; k < planeIndices.size() && !found; k++)
{
if(rSurface.planeIndex == planeIndices[k])
found = true;
}
if(!found)
planeIndices.push_back(rSurface.planeIndex);
for(k = 0; k < rSurface.numPoints; k++)
{
found = false;
for(l = 0; l < pointIndices.size(); l++)
{
if(pointIndices[l] == rSurface.pointIndices[k])
found = true;
}
if(!found)
pointIndices.push_back(rSurface.pointIndices[k]);
}
}
}
// Now that we have all the unique points and planes, remap the surfaces in
// terms of the offsets into the unique point list...
{
for(j = 0; j < tempSurfaces.size(); j++)
{
TempProcSurface& rSurface = tempSurfaces[j];
// Points
for(k = 0; k < rSurface.numPoints; k++)
{
bool found = false;
for(l = 0; l < pointIndices.size(); l++)
{
if(pointIndices[l] == rSurface.pointIndices[k])
{
rSurface.pointIndices[k] = l;
found = true;
break;
}
}
AssertISV(found, "Error remapping point indices in interior collision processing");
}
}
}
// Ok, at this point, we have a list of unique points, unique planes, and the
// surfaces all remapped in those terms. We need to check our error conditions
// that will make sure that we can properly encode this hull:
{
AssertISV(planeIndices.size() < 256, "Error, > 256 planes on an interior hull");
AssertISV(pointIndices.size() < 63356, "Error, > 65536 points on an interior hull");
AssertISV(tempSurfaces.size() < 256, "Error, > 256 surfaces on an interior hull");
}
// Now we group the planes together, and merge the closest groups until we're left
// with <= 8 groups
{
planeGroups.setSize(planeIndices.size());
for(j = 0; j < planeIndices.size(); j++)
{
planeGroups[j].numPlanes = 1;
planeGroups[j].planeIndices[0] = planeIndices[j];
}
while(planeGroups.size() > 8)
{
// Find the two closest groups. If mdp(i, j) is the value of the
// largest pairwise dot product that can be computed from the vectors
// of group i, and group j, then the closest group pair is the one
// with the smallest value of mdp.
F32 currmin = 2;
S32 firstGroup = -1;
S32 secondGroup = -1;
for(j = 0; j < planeGroups.size(); j++)
{
PlaneGrouping& first = planeGroups[j];
for(k = j + 1; k < planeGroups.size(); k++)
{
PlaneGrouping& second = planeGroups[k];
F32 max = -2;
for(l = 0; l < first.numPlanes; l++)
{
for(m = 0; m < second.numPlanes; m++)
{
Point3F firstNormal = mVehiclePlanes[first.planeIndices[l]];
Point3F secondNormal = mVehiclePlanes[second.planeIndices[m]];
F32 dot = mDot(firstNormal, secondNormal);
if(dot > max)
max = dot;
}
}
if(max < currmin)
{
currmin = max;
firstGroup = j;
secondGroup = k;
}
}
}
AssertFatal(firstGroup != -1 && secondGroup != -1, "Error, unable to find a suitable pairing?");
// Merge first and second
PlaneGrouping& to = planeGroups[firstGroup];
PlaneGrouping& from = planeGroups[secondGroup];
while(from.numPlanes != 0)
{
to.planeIndices[to.numPlanes++] = from.planeIndices[from.numPlanes - 1];
from.numPlanes--;
}
// And remove the merged group
planeGroups.erase(secondGroup);
}
AssertFatal(planeGroups.size() <= 8, "Error, too many plane groupings!");
// Assign a mask to each of the plane groupings
for(j = 0; j < planeGroups.size(); j++)
planeGroups[j].mask = (1 << j);
}
// Now, assign the mask to each of the temp polys
{
for(j = 0; j < tempSurfaces.size(); j++)
{
bool assigned = false;
for(k = 0; k < planeGroups.size() && !assigned; k++)
{
for(l = 0; l < planeGroups[k].numPlanes; l++)
{
if(planeGroups[k].planeIndices[l] == tempSurfaces[j].planeIndex)
{
tempSurfaces[j].mask = planeGroups[k].mask;
assigned = true;
break;
}
}
}
AssertFatal(assigned, "Error, missed a plane somewhere in the hull poly list!");
}
}
// Copy the appropriate group mask to the plane masks
{
planeMasks.setSize(planeIndices.size());
dMemset(planeMasks.address(), 0, planeMasks.size() * sizeof(U8));
for(j = 0; j < planeIndices.size(); j++)
{
bool found = false;
for(k = 0; k < planeGroups.size() && !found; k++)
{
for(l = 0; l < planeGroups[k].numPlanes; l++)
{
if(planeGroups[k].planeIndices[l] == planeIndices[j])
{
planeMasks[j] = planeGroups[k].mask;
found = true;
break;
}
}
}
AssertFatal(planeMasks[j] != 0, "Error, missing mask for plane!");
}
}
// And whip through the points, constructing the total mask for that point
{
pointMasks.setSize(pointIndices.size());
dMemset(pointMasks.address(), 0, pointMasks.size() * sizeof(U8));
for(j = 0; j < pointIndices.size(); j++)
{
for(k = 0; k < tempSurfaces.size(); k++)
{
for(l = 0; l < tempSurfaces[k].numPoints; l++)
{
if(tempSurfaces[k].pointIndices[l] == j)
{
pointMasks[j] |= tempSurfaces[k].mask;
break;
}
}
}
AssertFatal(pointMasks[j] != 0, "Error, point must exist in at least one surface!");
}
}
// Create the emit strings, and we're done!
{
// Set the range of planes
rHull.polyListPlaneStart = mVehiclePolyListPlanes.size();
mVehiclePolyListPlanes.setSize(rHull.polyListPlaneStart + planeIndices.size());
for(j = 0; j < planeIndices.size(); j++)
mVehiclePolyListPlanes[j + rHull.polyListPlaneStart] = planeIndices[j];
// Set the range of points
rHull.polyListPointStart = mVehiclePolyListPoints.size();
mVehiclePolyListPoints.setSize(rHull.polyListPointStart + pointIndices.size());
for(j = 0; j < pointIndices.size(); j++)
mVehiclePolyListPoints[j + rHull.polyListPointStart] = pointIndices[j];
// Now the emit string. The emit string goes like: (all fields are bytes)
// NumPlanes (PLMask) * NumPlanes
// NumPointsHi NumPointsLo (PtMask) * NumPoints
// NumSurfaces
// (NumPoints SurfaceMask PlOffset (PtOffsetHi PtOffsetLo) * NumPoints) * NumSurfaces
//
U32 stringLen = 1 + planeIndices.size();
stringLen += 2 + pointIndices.size();
stringLen += 1;
for(j = 0; j < tempSurfaces.size(); j++)
stringLen += 1 + 1 + 1 + (tempSurfaces[j].numPoints * 2);
rHull.polyListStringStart = mVehiclePolyListStrings.size();
mVehiclePolyListStrings.setSize(rHull.polyListStringStart + stringLen);
U8* pString = &mVehiclePolyListStrings[rHull.polyListStringStart];
U32 currPos = 0;
// Planes
pString[currPos++] = planeIndices.size();
for(j = 0; j < planeIndices.size(); j++)
pString[currPos++] = planeMasks[j];
// Points
pString[currPos++] = (pointIndices.size() >> 8) & 0xFF;
pString[currPos++] = (pointIndices.size() >> 0) & 0xFF;
for(j = 0; j < pointIndices.size(); j++)
pString[currPos++] = pointMasks[j];
// Surfaces
pString[currPos++] = tempSurfaces.size();
for(j = 0; j < tempSurfaces.size(); j++)
{
pString[currPos++] = tempSurfaces[j].numPoints;
pString[currPos++] = tempSurfaces[j].mask;
bool found = false;
for(k = 0; k < planeIndices.size(); k++)
{
if(planeIndices[k] == tempSurfaces[j].planeIndex)
{
pString[currPos++] = k;
found = true;
break;
}
}
AssertFatal(found, "Error, missing planeindex!");
for(k = 0; k < tempSurfaces[j].numPoints; k++)
{
pString[currPos++] = (tempSurfaces[j].pointIndices[k] >> 8) & 0xFF;
pString[currPos++] = (tempSurfaces[j].pointIndices[k] >> 0) & 0xFF;
}
}
AssertFatal(currPos == stringLen, "Error, mismatched string length!");
}
} // for (i = 0; i < mConvexHulls.size(); i++)
// Compact the used vectors
{
mVehiclePolyListStrings.compact();
mVehiclePolyListPoints.compact();
mVehiclePolyListPlanes.compact();
}
}
//--------------------------------------------------------------------------
void ZoneVisDeterminer::runFromState(SceneRenderState* state, U32 offset, U32 parentZone)
{
mMode = FromState;
mState = state;
mZoneRangeOffset = offset;
mParentZone = parentZone;
}
void ZoneVisDeterminer::runFromRects(SceneRenderState* state, U32 offset, U32 parentZone)
{
mMode = FromRects;
mState = state;
mZoneRangeOffset = offset;
mParentZone = parentZone;
}
bool ZoneVisDeterminer::isZoneVisible(const U32 zone) const
{
if(zone == 0)
return mState->getCullingState().getZoneState(mParentZone).isZoneVisible();
if(mMode == FromState)
{
return mState->getCullingState().getZoneState(zone + mZoneRangeOffset - 1).isZoneVisible();
}
else
{
return sgZoneRenderInfo[zone].render;
}
}
//--------------------------------------------------------------------------
// storeSurfaceVerts -
// Need to store the verts for every surface because the uv mapping changes
// per vertex per surface.
//--------------------------------------------------------------------------
void Interior::storeSurfVerts( Vector<U16> &masterIndexList,
Vector<VertexBufferTempIndex> &tempIndexList,
Vector<GFXVertexPNTTB> &verts,
U32 numIndices,
Surface &surface,
U32 surfaceIndex )
{
U32 startIndex = tempIndexList.size() - numIndices;
U32 startVert = verts.size();
Vector<U32> vertMap;
for( U32 i=0; i<numIndices; i++ )
{
// check if vertex is already stored for this surface
bool alreadyStored = false;
for( U32 j=0; j<i; j++ )
{
if( tempIndexList[startIndex+i].index == tempIndexList[startIndex+j].index )
{
alreadyStored = true;
break;
}
}
if( alreadyStored )
{
for( U32 a=0; a<vertMap.size(); a++ )
{
// find which vertex is indexed
if( vertMap[a] == tempIndexList[startIndex+i].index )
{
// store the index
masterIndexList.push_back( startVert + a );
break;
}
}
}
else
{
// store the vertex
GFXVertexPNTTB vert;
VertexBufferTempIndex &ind = tempIndexList[startIndex+i];
vert.point = mPoints[ind.index].point;
vert.normal = ind.normal;
fillVertex( vert, surface, surfaceIndex );
verts.push_back( vert );
// store the index
masterIndexList.push_back( verts.size() - 1 );
// maintain mapping of old indices to new indices
vertMap.push_back( ind.index );
}
}
}
//--------------------------------------------------------------------------
// storeRenderNode
//--------------------------------------------------------------------------
void Interior::storeRenderNode( RenderNode &node,
ZoneRNList &RNList,
Vector<GFXPrimitive> &primInfoList,
Vector<U16> &indexList,
Vector<GFXVertexPNTTB> &verts,
U32 &startIndex,
U32 &startVert )
{
GFXPrimitive pnfo;
if( !node.matInst )
{
String name = mMaterialList->getMaterialName( node.baseTexIndex );
if (!name.equal("NULL", String::NoCase) &&
!name.equal("ORIGIN", String::NoCase) &&
!name.equal("TRIGGER", String::NoCase) &&
!name.equal("FORCEFIELD", String::NoCase) &&
!name.equal("EMITTER", String::NoCase) )
{
Con::errorf( "material unmapped: %s", name.c_str() );
}
node.matInst = MATMGR->getWarningMatInstance();
}
// find min index
pnfo.minIndex = U32(-1);
for( U32 i=startIndex; i<indexList.size(); i++ )
{
if( indexList[i] < pnfo.minIndex )
{
pnfo.minIndex = indexList[i];
}
}
pnfo.numPrimitives = (indexList.size() - startIndex) / 3;
pnfo.startIndex = startIndex;
pnfo.numVertices = verts.size() - startVert;
pnfo.type = GFXTriangleList;
startIndex = indexList.size();
startVert = verts.size();
if( pnfo.numPrimitives > 0 )
{
primInfoList.push_back( pnfo );
node.primInfoIndex = primInfoList.size() - 1;
RNList.renderNodeList.push_back( node );
}
}
//--------------------------------------------------------------------------
// fill vertex
//--------------------------------------------------------------------------
void Interior::fillVertex( GFXVertexPNTTB &vert, Surface &surface, U32 surfaceIndex )
{
TexGenPlanes texPlanes = mTexGenEQs[surface.texGenIndex];
vert.texCoord.x = texPlanes.planeX.x * vert.point.x +
texPlanes.planeX.y * vert.point.y +
texPlanes.planeX.z * vert.point.z +
texPlanes.planeX.d;
vert.texCoord.y = texPlanes.planeY.x * vert.point.x +
texPlanes.planeY.y * vert.point.y +
texPlanes.planeY.z * vert.point.z +
texPlanes.planeY.d;
texPlanes = mLMTexGenEQs[surfaceIndex];
vert.texCoord2.x = texPlanes.planeX.x * vert.point.x +
texPlanes.planeX.y * vert.point.y +
texPlanes.planeX.z * vert.point.z +
texPlanes.planeX.d;
vert.texCoord2.y = texPlanes.planeY.x * vert.point.x +
texPlanes.planeY.y * vert.point.y +
texPlanes.planeY.z * vert.point.z +
texPlanes.planeY.d;
// vert normal and N already set
vert.T = surface.T - vert.normal * mDot(vert.normal, surface.T);
vert.T.normalize();
mCross(vert.normal, vert.T, &vert.B);
vert.B *= (mDot(vert.B, surface.B) < 0.0F) ? -1.0F : 1.0F;
}
//--------------------------------------------------------------------------
// Create vertex (and index) buffers for each zone
//--------------------------------------------------------------------------
void Interior::createZoneVBs()
{
if( mVertBuff )
{
return;
}
// create one big-ass vertex buffer to contain all verts
// drawIndexedPrimitive() calls can render subsets of the big-ass buffer
Vector<GFXVertexPNTTB> verts;
Vector<U16> indices;
U32 startIndex = 0;
U32 startVert = 0;
Vector<GFXPrimitive> primInfoList;
// fill index list first, then fill verts
for( U32 i=0; i<mZones.size(); i++ )
{
ZoneRNList RNList;
RenderNode node;
U16 curTexIndex = 0;
U8 curLightMapIndex = U8(-1);
Vector<VertexBufferTempIndex> tempIndices;
tempIndices.setSize(0);
for( U32 j=0; j<mZones[i].surfaceCount; j++ )
{
U32 surfaceIndex = mZoneSurfaces[mZones[i].surfaceStart + j];
Surface& surface = mSurfaces[ surfaceIndex ];
U32 *surfIndices = &mWindings[surface.windingStart];
//surface.VBIndexStart = indices.size();
//surface.primIndex = primInfoList.size();
BaseMatInstance *matInst = mMaterialList->getMaterialInst( surface.textureIndex );
Material* pMat = dynamic_cast<Material*>(matInst->getMaterial());
if( pMat && pMat->mPlanarReflection ) continue;
node.exterior = surface.surfaceFlags & SurfaceOutsideVisible;
// fill in node info on first time through
if( j==0 )
{
node.baseTexIndex = surface.textureIndex;
node.matInst = matInst;
curTexIndex = node.baseTexIndex;
node.lightMapIndex = mNormalLMapIndices[surfaceIndex];
curLightMapIndex = node.lightMapIndex;
}
// check for material change
if( surface.textureIndex != curTexIndex ||
mNormalLMapIndices[surfaceIndex] != curLightMapIndex )
{
storeRenderNode( node, RNList, primInfoList, indices, verts, startIndex, startVert );
tempIndices.setSize( 0 );
// set new material info
U16 baseTex = surface.textureIndex;
U8 lmIndex = mNormalLMapIndices[surfaceIndex];
if( baseTex != curTexIndex )
{
node.baseTexIndex = baseTex;
node.matInst = mMaterialList->getMaterialInst( baseTex );
}
else
{
node.baseTexIndex = NULL;
}
node.lightMapIndex = lmIndex;
curTexIndex = baseTex;
curLightMapIndex = lmIndex;
}
// NOTE, can put this in storeSurfVerts()
U32 tempStartIndex = tempIndices.size();
U32 nPrim = 0;
U32 last = 2;
while(last < surface.windingCount)
{
// First
tempIndices.push_back( VertexBufferTempIndex(surfIndices[last-2], getPointNormal(surfaceIndex, last-2)) );
tempIndices.push_back( VertexBufferTempIndex(surfIndices[last-1], getPointNormal(surfaceIndex, last-1)) );
tempIndices.push_back( VertexBufferTempIndex(surfIndices[last-0], getPointNormal(surfaceIndex, last)) );
last++;
nPrim++;
if(last == surface.windingCount)
break;
// Second
tempIndices.push_back( VertexBufferTempIndex(surfIndices[last-1], getPointNormal(surfaceIndex, last-1)) );
tempIndices.push_back( VertexBufferTempIndex(surfIndices[last-2], getPointNormal(surfaceIndex, last-2)) );
tempIndices.push_back( VertexBufferTempIndex(surfIndices[last-0], getPointNormal(surfaceIndex, last)) );
last++;
nPrim++;
}
U32 dStartVert = verts.size();
GFXPrimitive* p = &surface.surfaceInfo;
p->startIndex = indices.size(); //tempStartIndex;
// Normal render info
storeSurfVerts( indices, tempIndices, verts, tempIndices.size() - tempStartIndex,
surface, surfaceIndex );
// Debug render info
p->type = GFXTriangleList;
p->numVertices = verts.size() - dStartVert;
p->numPrimitives = nPrim;
p->minIndex = indices[p->startIndex];
for (U32 i = p->startIndex; i < p->startIndex + nPrim * 3; i++) {
if (indices[i] < p->minIndex) {
p->minIndex = indices[i];
}
}
}
// store remaining index list
storeRenderNode( node, RNList, primInfoList, indices, verts, startIndex, startVert );
mZoneRNList.push_back( RNList );
}
// It is possible that we have no zones or have no surfaces in our zones (static meshes only)
if (verts.size() == 0)
return;
// create vertex buffer
mVertBuff.set(GFX, verts.size(), GFXBufferTypeStatic);
GFXVertexPNTTB *vbVerts = mVertBuff.lock();
dMemcpy( vbVerts, verts.address(), verts.size() * sizeof( GFXVertexPNTTB ) );
mVertBuff.unlock();
// create primitive buffer
U16 *ibIndices;
GFXPrimitive *piInput;
mPrimBuff.set(GFX, indices.size(), primInfoList.size(), GFXBufferTypeStatic);
mPrimBuff.lock(&ibIndices, &piInput);
dMemcpy( ibIndices, indices.address(), indices.size() * sizeof(U16) );
dMemcpy( piInput, primInfoList.address(), primInfoList.size() * sizeof(GFXPrimitive) );
mPrimBuff.unlock();
}
#define SMALL_FLOAT (1e-12)
//--------------------------------------------------------------------------
// Get the texture space matrice for a point on a surface
//--------------------------------------------------------------------------
void Interior::getTexMat(U32 surfaceIndex, U32 pointOffset, Point3F& T, Point3F& N, Point3F& B)
{
Surface& surface = mSurfaces[surfaceIndex];
if (mFileVersion >= 11)
{
// There is a one-to-one mapping of mWindings and mTexMatIndices
U32 texMatIndex = mTexMatIndices[surface.windingStart + pointOffset];
TexMatrix& texMat = mTexMatrices[texMatIndex];
T = mNormals[texMat.T];
N = mNormals[texMat.N];
B = mNormals[texMat.B];
}
else
{
T = surface.T - surface.N * mDot(surface.N, surface.T);
N = surface.N;
mCross(surface.N, T, &B);
B *= (mDot(B, surface.B) < 0.0F) ? -1.0f : 1.0f;
}
return;
}
//--------------------------------------------------------------------------
// Fill in texture space matrices for each surface
//--------------------------------------------------------------------------
void Interior::fillSurfaceTexMats()
{
for( U32 i=0; i<mSurfaces.size(); i++ )
{
Surface &surface = mSurfaces[i];
const PlaneF & plane = getPlane(surface.planeIndex);
Point3F planeNorm = plane;
if( planeIsFlipped( surface.planeIndex ) )
{
planeNorm = -planeNorm;
}
GFXVertexPNTTB pts[3];
pts[0].point = mPoints[mWindings[surface.windingStart + 1]].point;
pts[1].point = mPoints[mWindings[surface.windingStart + 0]].point;
pts[2].point = mPoints[mWindings[surface.windingStart + 2]].point;
TexGenPlanes texPlanes = mTexGenEQs[surface.texGenIndex];
for( U32 j=0; j<3; j++ )
{
pts[j].texCoord.x = texPlanes.planeX.x * pts[j].point.x +
texPlanes.planeX.y * pts[j].point.y +
texPlanes.planeX.z * pts[j].point.z +
texPlanes.planeX.d;
pts[j].texCoord.y = texPlanes.planeY.x * pts[j].point.x +
texPlanes.planeY.y * pts[j].point.y +
texPlanes.planeY.z * pts[j].point.z +
texPlanes.planeY.d;
}
Point3F edge1, edge2;
Point3F cp;
Point3F S,T,SxT;
// x, s, t
edge1.set( pts[1].point.x - pts[0].point.x, pts[1].texCoord.x - pts[0].texCoord.x, pts[1].texCoord.y - pts[0].texCoord.y );
edge2.set( pts[2].point.x - pts[0].point.x, pts[2].texCoord.x - pts[0].texCoord.x, pts[2].texCoord.y - pts[0].texCoord.y );
mCross( edge1, edge2, &cp );
if( fabs(cp.x) > SMALL_FLOAT )
{
S.x = -cp.y / cp.x;
T.x = -cp.z / cp.x;
}
edge1.set( pts[1].point.y - pts[0].point.y, pts[1].texCoord.x - pts[0].texCoord.x, pts[1].texCoord.y - pts[0].texCoord.y );
edge2.set( pts[2].point.y - pts[0].point.y, pts[2].texCoord.x - pts[0].texCoord.x, pts[2].texCoord.y - pts[0].texCoord.y );
mCross( edge1, edge2, &cp );
if( fabs(cp.x) > SMALL_FLOAT )
{
S.y = -cp.y / cp.x;
T.y = -cp.z / cp.x;
}
edge1.set( pts[1].point.z - pts[0].point.z, pts[1].texCoord.x - pts[0].texCoord.x, pts[1].texCoord.y - pts[0].texCoord.y );
edge2.set( pts[2].point.z - pts[0].point.z, pts[2].texCoord.x - pts[0].texCoord.x, pts[2].texCoord.y - pts[0].texCoord.y );
mCross( edge1, edge2, &cp );
if( fabs(cp.x) > SMALL_FLOAT )
{
S.z = -cp.y / cp.x;
T.z = -cp.z / cp.x;
}
S.normalizeSafe();
T.normalizeSafe();
mCross( S, T, &SxT );
if( mDot( SxT, planeNorm ) < 0.0 )
{
SxT = -SxT;
}
surface.T = S;
surface.B = T;
surface.N = SxT;
surface.normal = planeNorm;
}
}
//--------------------------------------------------------------------------
// Clone material instances - if a texture (material) exists on both the
// inside and outside of an interior, it needs to create two material
// instances - one for the inside, and one for the outside. The reason is
// that the light direction maps only exist on the inside of the interior.
//--------------------------------------------------------------------------
void Interior::cloneMatInstances()
{
Vector< BaseMatInstance *> outsideMats;
Vector< BaseMatInstance *> insideMats;
// store pointers to mat lists
for( U32 i=0; i<getNumZones(); i++ )
{
for( U32 j=0; j<mZoneRNList[i].renderNodeList.size(); j++ )
{
RenderNode &node = mZoneRNList[i].renderNodeList[j];
if( !node.matInst ) continue;
if( node.exterior )
{
// insert only if it's not already there
U32 k;
for( k=0; k<outsideMats.size(); k++ )
{
if( node.matInst == outsideMats[k] ) break;
}
if( k == outsideMats.size() )
{
outsideMats.push_back( node.matInst );
}
}
else
{
// insert only if it's not already there
U32 k;
for( k=0; k<insideMats.size(); k++ )
{
if( node.matInst == insideMats[k] ) break;
}
if( k == insideMats.size() )
{
insideMats.push_back( node.matInst );
}
}
}
}
// for all materials that exist both inside and outside,
// clone them so they can have separate material instances
for( U32 i=0; i<outsideMats.size(); i++ )
{
for( U32 j=0; j<insideMats.size(); j++ )
{
if( outsideMats[i] == insideMats[j] )
{
// GFX2_RENDER_MERGE
Material *mat = dynamic_cast<Material*>(outsideMats[i]->getMaterial());
if (mat)
{
BaseMatInstance *newMat = mat->createMatInstance();
mMatInstCleanupList.push_back( newMat );
// go through and find the inside version and replace it
// with the new one.
for( U32 k=0; k<getNumZones(); k++ )
{
for( U32 l=0; l<mZoneRNList[k].renderNodeList.size(); l++ )
{
RenderNode &node = mZoneRNList[k].renderNodeList[l];
if( !node.exterior )
{
if( node.matInst == outsideMats[i] )
{
node.matInst = newMat;
}
}
}
}
}
}
}
}
}
//--------------------------------------------------------------------------
// Intialize material instances
//--------------------------------------------------------------------------
void Interior::initMatInstances()
{
mHasTranslucentMaterials = false;
for( U32 i=0; i<getNumZones(); i++ )
{
for( U32 j=0; j<mZoneRNList[i].renderNodeList.size(); j++ )
{
RenderNode &node = mZoneRNList[i].renderNodeList[j];
BaseMatInstance *mat = node.matInst;
if( mat )
{
// Note: We disabled this as it was keeping the prepass lighting
// from being applied to interiors... this fixes that.
//fd.features[MFT_RTLighting] = false;
// If this node has a lightmap index,
// we need to bind the override features delegate
// in order to ensure the MFT_LightMap feature
// is added for the material.
if ( node.lightMapIndex != (U8)-1 )
mat->getFeaturesDelegate().bind( &Interior::_enableLightMapFeature );
mat->init( MATMGR->getDefaultFeatures(), getGFXVertexFormat<GFXVertexPNTTB>());
// We need to know if we have non-zwrite translucent materials
// so that we can make the extra renderimage pass for them.
Material* pMat = dynamic_cast<Material*>(mat->getMaterial());
if ( pMat )
mHasTranslucentMaterials |= pMat->mTranslucent && !pMat->mTranslucentZWrite;
}
}
for( U32 j=0; j<mZoneReflectRNList[i].reflectList.size(); j++ )
{
ReflectRenderNode &node = mZoneReflectRNList[i].reflectList[j];
BaseMatInstance *mat = node.matInst;
if( mat )
{
// Note: We disabled this as it was keeping the prepass lighting
// from being applied to interiors... this fixes that.
//fd.features[MFT_RTLighting] = false;
mat->init( MATMGR->getDefaultFeatures(), getGFXVertexFormat<GFXVertexPNTTB>());
// We need to know if we have non-zwrite translucent materials
// so that we can make the extra renderimage pass for them.
Material* pMat = dynamic_cast<Material*>(mat->getMaterial());
if ( pMat )
mHasTranslucentMaterials |= pMat->mTranslucent && !pMat->mTranslucentZWrite;
}
}
}
}
void Interior::_enableLightMapFeature( ProcessedMaterial *mat,
U32 stageNum,
MaterialFeatureData &fd,
const FeatureSet &features )
{
if ( mat->getMaterial() )
{
fd.features.addFeature( MFT_LightMap );
fd.features.removeFeature( MFT_ToneMap );
}
}
//--------------------------------------------------------------------------
// Create the reflect plane list and the nodes of geometry necessary to
// render the reflective surfaces.
//--------------------------------------------------------------------------
void Interior::createReflectPlanes()
{
Vector<GFXVertexPNTTB> verts;
Vector<GFXPrimitive> primInfoList;
Vector<U16> indices;
U32 startIndex = 0;
U32 startVert = 0;
for( U32 i=0; i<mZones.size(); i++ )
{
ZoneReflectRNList reflectRNList;
// for each zone:
// go through list of surfaces, searching for reflection
for( U32 j=0; j<mZones[i].surfaceCount; j++ )
{
U32 surfaceIndex = mZoneSurfaces[mZones[i].surfaceStart + j];
Surface& surface = mSurfaces[ surfaceIndex ];
BaseMatInstance *matInst = mMaterialList->getMaterialInst( surface.textureIndex );
Material* pMat = dynamic_cast<Material*>(matInst->getMaterial());
if( !pMat || !pMat->mPlanarReflection ) continue;
U32 *surfIndices = &mWindings[surface.windingStart];
// create / fill in GFXPrimitve, verts, indices
// going to need a new render node
ReflectRenderNode node;
node.exterior = surface.surfaceFlags & SurfaceOutsideVisible;
node.matInst = mMaterialList->getMaterialInst( surface.textureIndex );
node.lightMapIndex = mNormalLMapIndices[surfaceIndex];
PlaneF plane;
plane = getPlane( surface.planeIndex );
if( planeIsFlipped( surface.planeIndex ) )
{
plane.x = -plane.x;
plane.y = -plane.y;
plane.z = -plane.z;
plane.d = -plane.d;
}
// check if coplanar with existing reflect plane
//--------------------------------------------------
S32 rPlaneIdx = -1;
for( U32 a=0; a<mReflectPlanes.size(); a++ )
{
if( fabs( mDot( plane, mReflectPlanes[a] ) ) > 0.999 )
{
if( fabs( plane.d - mReflectPlanes[a].d ) < 0.001 )
{
rPlaneIdx = a;
break;
}
}
}
PlaneF refPlane;
refPlane = plane;
if( rPlaneIdx < 0 )
{
mReflectPlanes.push_back( refPlane );
node.reflectPlaneIndex = mReflectPlanes.size() - 1;
}
else
{
node.reflectPlaneIndex = rPlaneIdx;
}
// store the indices for the surface
//--------------------------------------------------
Vector<VertexBufferTempIndex> tempIndices;
tempIndices.setSize( 0 );
U32 tempStartIndex = tempIndices.size();
U32 last = 2;
while(last < surface.windingCount)
{
// First
tempIndices.push_back( VertexBufferTempIndex(surfIndices[last-2], getPointNormal(surfaceIndex, last-2)) );
tempIndices.push_back( VertexBufferTempIndex(surfIndices[last-1], getPointNormal(surfaceIndex, last-1)) );
tempIndices.push_back( VertexBufferTempIndex(surfIndices[last-0], getPointNormal(surfaceIndex, last)) );
last++;
if(last == surface.windingCount)
break;
// Second
tempIndices.push_back( VertexBufferTempIndex(surfIndices[last-1], getPointNormal(surfaceIndex, last-1)) );
tempIndices.push_back( VertexBufferTempIndex(surfIndices[last-2], getPointNormal(surfaceIndex, last-2)) );
tempIndices.push_back( VertexBufferTempIndex(surfIndices[last-0], getPointNormal(surfaceIndex, last)) );
last++;
}
storeSurfVerts( indices, tempIndices, verts, tempIndices.size() - tempStartIndex,
surface, surfaceIndex );
// store render node and GFXPrimitive
// each node is a different reflective surface
// ---------------------------------------------------
// find min index
GFXPrimitive pnfo;
pnfo.minIndex = U32(-1);
for( U32 k=startIndex; k<indices.size(); k++ )
{
if( indices[k] < pnfo.minIndex )
{
pnfo.minIndex = indices[k];
}
}
pnfo.numPrimitives = (indices.size() - startIndex) / 3;
pnfo.startIndex = startIndex;
pnfo.numVertices = verts.size() - startVert;
pnfo.type = GFXTriangleList;
startIndex = indices.size();
startVert = verts.size();
primInfoList.push_back( pnfo );
node.primInfoIndex = primInfoList.size() - 1;
reflectRNList.reflectList.push_back( node );
}
mZoneReflectRNList.push_back( reflectRNList );
}
if( mReflectPlanes.size() )
{
// copy verts to buffer
mReflectVertBuff.set(GFX, verts.size(), GFXBufferTypeStatic);
GFXVertexPNTTB *vbVerts = mReflectVertBuff.lock();
dMemcpy( vbVerts, verts.address(), verts.size() * sizeof( GFXVertexPNTTB ) );
mReflectVertBuff.unlock();
// create primitive buffer
U16 *ibIndices;
GFXPrimitive *piInput;
mReflectPrimBuff.set(GFX, indices.size(), primInfoList.size(), GFXBufferTypeStatic);
mReflectPrimBuff.lock(&ibIndices, &piInput);
dMemcpy( ibIndices, indices.address(), indices.size() * sizeof(U16) );
dMemcpy( piInput, primInfoList.address(), primInfoList.size() * sizeof(GFXPrimitive) );
mReflectPrimBuff.unlock();
}
}
void Interior::buildSurfaceZones()
{
surfaceZones.clear();
surfaceZones.setSize(mSurfaces.size());
for(U32 i=0; i<getSurfaceCount(); i++)
{
surfaceZones[i] = -1;
}
for(U32 z=0; z<mZones.size(); z++)
{
Interior::Zone &zone = mZones[z];
zone.zoneId = z;
for(U32 s=zone.surfaceStart; s<(zone.surfaceStart + zone.surfaceCount); s++)
{
surfaceZones[mZoneSurfaces[s]] = zone.zoneId - 1;
}
}
}
const String& Interior::getTargetName( S32 mapToNameIndex ) const
{
S32 targetCount = mMaterialList->getMaterialNameList().size();
if(mapToNameIndex < 0 || mapToNameIndex >= targetCount)
return String::EmptyString;
return mMaterialList->getMaterialNameList()[mapToNameIndex];
}
S32 Interior::getTargetCount() const
{
if(!this)
return -1;
return mMaterialList->getMaterialNameList().size();
}
| 32.844671
| 130
| 0.558735
|
baktubak
|
2a73a0677563f7662cc6c10b8cd50885ef91645b
| 51
|
hpp
|
C++
|
src/boost_type_traits_has_pre_increment.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 10
|
2018-03-17T00:58:42.000Z
|
2021-07-06T02:48:49.000Z
|
src/boost_type_traits_has_pre_increment.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 2
|
2021-03-26T15:17:35.000Z
|
2021-05-20T23:55:08.000Z
|
src/boost_type_traits_has_pre_increment.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 4
|
2019-05-28T21:06:37.000Z
|
2021-07-06T03:06:52.000Z
|
#include <boost/type_traits/has_pre_increment.hpp>
| 25.5
| 50
| 0.843137
|
miathedev
|
2a73d8f6d62a04bb23f4877e543e931268253c59
| 1,472
|
cc
|
C++
|
backend/place_test.cc
|
zyw199515/hive-cpp
|
b4b9f8d9446476f94ffb3ee0fbaec19f232c2879
|
[
"MIT"
] | null | null | null |
backend/place_test.cc
|
zyw199515/hive-cpp
|
b4b9f8d9446476f94ffb3ee0fbaec19f232c2879
|
[
"MIT"
] | null | null | null |
backend/place_test.cc
|
zyw199515/hive-cpp
|
b4b9f8d9446476f94ffb3ee0fbaec19f232c2879
|
[
"MIT"
] | null | null | null |
#include "backend/place.h"
#include "glog/logging.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
using namespace hive;
// Test samples are constructed according to official ruling book examples.
TEST(PlaceTest, GetPlacePieceTypes) {
HiveState state;
state.active_player = Side::kBlack;
state.black_piece_count = {{PieceType::kAnt, 1}, {PieceType::kBeetle, 0}, {PieceType::kQueen, 1}};
EXPECT_THAT(GetPlacePieceTypes(state),
testing::UnorderedElementsAre(PieceType::kAnt, PieceType::kQueen));
state.black_queen_turn_countdown = 0;
EXPECT_THAT(GetPlacePieceTypes(state), testing::UnorderedElementsAre(PieceType::kQueen));
}
TEST(PlaceTest, GetPlacePositions) {
// Initial state must start from (0, 0)
HiveState state;
state.active_player = Side::kBlack;
EXPECT_THAT(GetPlacePositions(state), testing::UnorderedElementsAre(Pos(0, 0)));
// The second move must be neighbour.
state.pieces[Pos(0, 0)] = Piece(PieceType::kAnt, Side::kBlack);
state.active_player = Side::kWhite;
EXPECT_THAT(GetPlacePositions(state),
testing::UnorderedElementsAre(Pos(0, 1), Pos(1, 0), Pos(-1, 1), Pos(-1, 0),
Pos(0, -1), Pos(1, -1)));
// Case from ruling
state.pieces[Pos(0, 1)] = Piece(PieceType::kAnt, Side::kWhite);
state.active_player = Side::kBlack;
EXPECT_THAT(GetPlacePositions(state),
testing::UnorderedElementsAre(Pos(-1, 0), Pos(0, -1), Pos(1, -1)));
}
| 38.736842
| 100
| 0.685462
|
zyw199515
|
2a74c014ed2e2775784522dbce71e21211697aab
| 4,787
|
cpp
|
C++
|
ShareLib/DBCmd.cpp
|
openlastchaos/lastchaos-source-server
|
935b770fa857e67b705717d154b11b717741edeb
|
[
"Apache-2.0"
] | null | null | null |
ShareLib/DBCmd.cpp
|
openlastchaos/lastchaos-source-server
|
935b770fa857e67b705717d154b11b717741edeb
|
[
"Apache-2.0"
] | null | null | null |
ShareLib/DBCmd.cpp
|
openlastchaos/lastchaos-source-server
|
935b770fa857e67b705717d154b11b717741edeb
|
[
"Apache-2.0"
] | 1
|
2022-01-17T09:34:39.000Z
|
2022-01-17T09:34:39.000Z
|
#include <boost/format.hpp>
#include "bnf.h"
#include "logsystem.h"
#include "DBCmd.h"
#include "PrintExcuteInfo.h"
CDBCmd::CDBCmd()
: m_dbconn(NULL)
, m_nrecords(0)
, m_res(NULL)
, m_row(NULL)
, m_fieldinfo(NULL)
, m_nfields(0)
{
}
CDBCmd::CDBCmd(MYSQL* mysql)
: m_dbconn(mysql)
, m_nrecords(0)
, m_res(NULL)
, m_row(NULL)
, m_fieldinfo(NULL)
, m_nfields(0)
{
}
CDBCmd::~CDBCmd()
{
if (m_res)
{
mysql_free_result(m_res);
m_res = NULL;
}
}
bool CDBCmd::Open()
{
Close();
if (mysql_real_query(m_dbconn, m_sql.c_str(), m_sql.size()) != 0)
{
LOG_ERROR("query error (mysql_real_query) : error[%s] query[%s]", mysql_error(m_dbconn), m_sql.c_str());
return false;
}
m_res = mysql_store_result(m_dbconn);
if (m_res == NULL)
{
LOG_ERROR("query error (mysql_store_result) : error[%s] query[%s]", mysql_error(m_dbconn), m_sql.c_str());
return false;
}
m_nrecords = (int)mysql_num_rows(m_res);
m_nfields = (int)mysql_num_fields(m_res);
m_fieldinfo = mysql_fetch_fields(m_res);
map_.clear();
for (int i = 0; i < m_nfields; ++i)
{
map_.insert(map_t::value_type(m_fieldinfo[i].name, i));
}
return true;
}
bool CDBCmd::MoveFirst()
{
if (m_res == NULL)
return false;
mysql_data_seek(m_res, 0);
m_row = mysql_fetch_row(m_res);
if (m_row == NULL)
return false;
return true;
}
bool CDBCmd::Seek(int nOffset)
{
if (m_res == NULL)
return false;
mysql_data_seek(m_res, nOffset);
m_row = mysql_fetch_row(m_res);
if (m_row == NULL)
return false;
return true;
}
bool CDBCmd::MoveNext()
{
if (m_res == NULL)
return false;
m_row = mysql_fetch_row(m_res);
if (m_row == NULL)
return false;
return true;
}
bool CDBCmd::Update()
{
Close();
if (mysql_real_query(m_dbconn, m_sql.c_str(), m_sql.size()) != 0)
{
m_nrecords = 0;
LOG_ERROR("query error (mysql_real_query) : error[%s] query[%s]", mysql_error(m_dbconn), m_sql.c_str());
return false;
}
m_nrecords = static_cast<int>(mysql_affected_rows(m_dbconn));
return true;
}
bool CDBCmd::GetRec(int fieldno, int& n)
{
char* ret = GetRec(fieldno);
if (ret == NULL)
return false;
n = atoi(ret);
return true;
}
bool CDBCmd::GetRec(int fieldno, unsigned int& n)
{
int t;
if (!GetRec(fieldno, t))
return false;
n = (unsigned int)t;
return true;
}
bool CDBCmd::GetRec(int fieldno, short& n)
{
int t;
if (!GetRec(fieldno, t))
return false;
n = (short)t;
return true;
}
bool CDBCmd::GetRec(int fieldno, unsigned short& n)
{
int t;
if (!GetRec(fieldno, t))
return false;
n = (unsigned short)t;
return true;
}
bool CDBCmd::GetRec(int fieldno, char& ch)
{
int t;
if (!GetRec(fieldno, t))
return false;
ch = (char)t;
return true;
}
bool CDBCmd::GetRec(int fieldno, unsigned char& ch)
{
int t;
if (!GetRec(fieldno, t))
return false;
ch = (unsigned char)t;
return true;
}
bool CDBCmd::GetRec(int fieldno, CLCString& str, bool bTrim)
{
// 데이터 읽기
char* ret = GetRec(fieldno);
// NULL이면 오류
if (ret == NULL)
return false;
char* p = ret;
// left trim 처리
if (bTrim)
{
while (*p && CLCString::IsSpace(*p))
p++;
}
// 시작 포인트 설정
char* pStart = p;
// 시작 포인트 이후 길이가 1보다 작으면
if (strlen(pStart) < 1)
{
str = "";
return true;
}
// 끝 포인트 설정(NULL 앞자리)
char* pEnd = pStart + strlen(pStart) - 1;
// right trim 처리
if (bTrim)
{
while (pEnd >= pStart)
{
if (CLCString::IsSpace(*pEnd))
pEnd--;
else
break;
}
}
// trim에 의해 길이가 0가 되면 리턴
if (pEnd < pStart)
{
str = "";
return true;
}
// 여기에 오면 pStart에서 pEnd까지 문자를 복사하면 됨
int len = pEnd - pStart + 2; // 결과 문자열 길이 (NULL 포함)
// 출력 버퍼의 크기와 비교 작은 것을 택함
if (len > str.BufferSize())
len = str.BufferSize();
char* tmp = new char[len];
memcpy(tmp, pStart, len - 1);
tmp[len - 1] = '\0';
str = tmp;
delete [] tmp;
return true;
}
bool CDBCmd::GetRec(int fieldno, float& f)
{
char* ret = GetRec(fieldno);
if (ret == NULL)
return false;
f = (float)atof(ret);
return true;
}
bool CDBCmd::GetRec(int fieldno, LONGLONG& ll)
{
char* ret = GetRec(fieldno);
if (ret == NULL)
return false;
ll = ATOLL(ret);
return true;
}
bool CDBCmd::GetRec( int fieldno, std::string& str )
{
str = GetRec(fieldno);
return true;
}
int CDBCmd::FindField( const char* fieldname )
{
map_t::iterator it = map_.find(fieldname);
if (it != map_.end())
{
return it->second;
}
std::string title = boost::str(boost::format("query[%s] / not found mysql field names ('%1%') : ") % m_sql % fieldname);
std::string str = title;
map_t::iterator eit = map_.begin();
map_t::iterator eendit = map_.end();
for (; eit != eendit; ++eit)
{
str += eit->first + " | ";
}
LOG_ERROR("\n\n\n\n\n");
LOG_ERROR(str.c_str());
LOG_ERROR("\n\n\n\n\n");
PrintExcuteInfo::Instance()->SetStopMessage(title);
bnf::instance()->Stop();
return -1;
}
| 15.956667
| 121
| 0.633382
|
openlastchaos
|
2a76b7d6750f1cdf37b9f4d40dd7ed485a45f9d7
| 3,464
|
cpp
|
C++
|
src/Profiling/denoise-profiling/src/denoise_multiple.cpp
|
sayandipde/approx_ibc
|
b8878ed24accab2a32a51cac9d0cdc6f61a49e75
|
[
"Apache-2.0"
] | 1
|
2021-01-12T07:33:15.000Z
|
2021-01-12T07:33:15.000Z
|
src/Profiling/denoise-profiling/src/denoise_multiple.cpp
|
sayandipde/approx_ibc
|
b8878ed24accab2a32a51cac9d0cdc6f61a49e75
|
[
"Apache-2.0"
] | null | null | null |
src/Profiling/denoise-profiling/src/denoise_multiple.cpp
|
sayandipde/approx_ibc
|
b8878ed24accab2a32a51cac9d0cdc6f61a49e75
|
[
"Apache-2.0"
] | 3
|
2020-09-29T22:43:07.000Z
|
2021-01-23T08:08:41.000Z
|
/*
* Copyright (c) 2020 sayandipde
* Eindhoven University of Technology
* Eindhoven, The Netherlands
*
* Name : image_signal_processing.cpp
*
* Authors : Sayandip De (sayandip.de@tue.nl)
* Sajid Mohamed (s.mohamed@tue.nl)
*
* Date : March 26, 2020
*
* Function : run denoise-cpu profiling with multiple image workloads
*
* History :
* 26-03-20 : Initial version.
*
* 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 <cstdio>
//#include <chrono>
#include <iostream>
#ifdef PROFILEWITHCHRONO
#include "../my_profiler.hpp"
#endif
#include "nl_means.h"
// #include "nl_means_auto_schedule.h"
#include "halide_benchmark.h"
#include "HalideBuffer.h"
#include "halide_image_io.h"
#include <fstream>
using namespace std;
using namespace Halide::Runtime;
using namespace Halide::Tools;
#ifdef PROFILEWITHCHRONO
template<class Container>
std::ostream& write_container(const Container& c, std::ostream& out, string pipeversion, char delimiter = ',')
{
out << pipeversion;
out << delimiter;
bool write_sep = false;
for (const auto& e: c) {
if (write_sep)
out << delimiter;
else
write_sep = true;
out << e;
}
return out;
}
#endif
int main(int argc, char **argv) {
if (argc < 5) {
printf("Usage: ./denoise_multiple.o input.png patch_size search_area sigma\n"
"e.g.: ./denoise_multiple.o input.png 7 7 0.12\n");
return 0;
}
const char * img_path = argv[1];
int patch_size = atoi(argv[2]);
int search_area = atoi(argv[3]);
float sigma = atof(argv[4]);
// int timing_iterations = atoi(argv[5]);
// int timing_iterations = 1;
Buffer<float> input;
vector<vector<double>> wc_avg_bc_tuples;
string in_string, out_string;
for (int version = 0; version <= 7; version++){
cout << "- profiling version: " << version << endl;
out_string = "chrono/runtime_denoise_multiple_v" + to_string(version) + "_.csv";
std::ofstream outfile(out_string);
for (int i = 0; i < 200; i++){
cout << i << endl;
in_string = std::string(img_path)+"v"+to_string(version)+"/demosaic/img_dem_"+to_string(i)+".png";
input = load_and_convert_image(in_string);
Buffer<float> output(input.width(), input.height(), 3);
//////////////////////////////////////////////////////////////////////////////////////////////////
// Timing code
// statistical
#ifdef PROFILEWITHCHRONO
wc_avg_bc_tuples = do_benchmarking( [&]() {
nl_means(input, patch_size, search_area, sigma, output);
} );
write_container(wc_avg_bc_tuples[0], outfile, "img_"+to_string(i));
outfile << "\n";
// Save the output
convert_and_save_image(output, (std::string(img_path)+"v"+to_string(version)+"/denoise/img_den_"+to_string(i)+".png").c_str());
#endif
}
}
return 0;
}
| 28.393443
| 130
| 0.626155
|
sayandipde
|
2a773aeadc27cee30e75bd0534fa1903ce803f61
| 1,385
|
cpp
|
C++
|
1311-F.cpp
|
ankiiitraj/questionsSolved
|
8452b120935a9c3d808b45f27dcdc05700d902fc
|
[
"MIT"
] | null | null | null |
1311-F.cpp
|
ankiiitraj/questionsSolved
|
8452b120935a9c3d808b45f27dcdc05700d902fc
|
[
"MIT"
] | 1
|
2020-02-24T19:45:57.000Z
|
2020-02-24T19:45:57.000Z
|
1311-F.cpp
|
ankiiitraj/questionsSolved
|
8452b120935a9c3d808b45f27dcdc05700d902fc
|
[
"MIT"
] | null | null | null |
// . . . . . . . . Not Completed
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
// Author : Ankit Raj
// Problem Name : Moving Points
// Problem Link : https://codeforces.com/contest/1311/problem/F
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
#include <bits/stdc++.h>
#define int long long int
#define len length
#define pb push_back
#define F first
#define S second
#define debug cout << "Debugging . . .\n";
#define faster ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL)
using namespace std;
int32_t main()
{
faster;
#ifndef ONLINE_JUDGE
freopen("ip.txt", "r", stdin);
freopen("op.txt", "w", stdout);
#endif
int t; cin >> t; while (t--)
{
int n, cntP = 1, cntN = 1, ans = 0, temp;
cin >> n;
int x[n];
map <int, pair<int, int>> vp, vn;
for (int i = 0; i < n; ++i) {
cin >> x[i];
}
for (int i = 0; i < n; ++i) {
cin >> temp;
if (temp >= 0) {
vp.insert({x[i], {temp, cntP}});
} else {
vn.insert({x[i], {temp, cntN}});
}
}
for (auto &itr : vp) {
int curX = itr.first, curV = itr.second.first;
auto it = vn.lower_bound(curX);
if (curX == it->first) {
ans += it->second.second - 1;
} else {
ans += it->second.second;
}
}
}
return 0;
}
| 23.083333
| 90
| 0.46426
|
ankiiitraj
|
2a7df292397a18f6003ec9edf48bc85571e4bb2a
| 140
|
cpp
|
C++
|
Projects/Sample/source/main.cpp
|
Nohzmi/Reflectpp
|
35a340f277ef374c9f9aeef89849918fdf7c2848
|
[
"BSD-3-Clause"
] | 3
|
2021-02-16T23:01:49.000Z
|
2021-03-10T16:13:55.000Z
|
Projects/Sample/source/main.cpp
|
Nohzmi/Reflectpp
|
35a340f277ef374c9f9aeef89849918fdf7c2848
|
[
"BSD-3-Clause"
] | null | null | null |
Projects/Sample/source/main.cpp
|
Nohzmi/Reflectpp
|
35a340f277ef374c9f9aeef89849918fdf7c2848
|
[
"BSD-3-Clause"
] | null | null | null |
// Copyright (c) 2020, Nohzmi. All rights reserved.
#include "window.h"
int main()
{
Window app;
app.Update();
return EXIT_SUCCESS;
}
| 11.666667
| 51
| 0.671429
|
Nohzmi
|
2a8a9376f3a8e3721e2078ce814b7d00aae01c8f
| 43,033
|
cpp
|
C++
|
wfs/stored_queries/StoredObsQueryHandler.cpp
|
nakkim/smartmet-plugin-wfs
|
851334dd3be1a24b9708f66696f088fdc857a999
|
[
"MIT"
] | null | null | null |
wfs/stored_queries/StoredObsQueryHandler.cpp
|
nakkim/smartmet-plugin-wfs
|
851334dd3be1a24b9708f66696f088fdc857a999
|
[
"MIT"
] | null | null | null |
wfs/stored_queries/StoredObsQueryHandler.cpp
|
nakkim/smartmet-plugin-wfs
|
851334dd3be1a24b9708f66696f088fdc857a999
|
[
"MIT"
] | null | null | null |
#include "stored_queries/StoredObsQueryHandler.h"
#include "FeatureID.h"
#include "StoredQueryHandlerFactoryDef.h"
#include "WfsConst.h"
#include "WfsConvenience.h"
#include <boost/algorithm/string.hpp>
#include <boost/format.hpp>
#include <boost/lambda/lambda.hpp>
#include <macgyver/Exception.h>
#include <macgyver/StringConversion.h>
#include <smartmet/spine/Convenience.h>
#include <smartmet/spine/ParameterTools.h>
#include <smartmet/spine/TimeSeries.h>
#include <smartmet/spine/TimeSeriesOutput.h>
#include <smartmet/spine/Value.h>
#include <algorithm>
#include <functional>
#define P_BEGIN_TIME "beginTime"
#define P_END_TIME "endTime"
#define P_METEO_PARAMETERS "meteoParameters"
#define P_STATION_TYPE "stationType"
#define P_TIME_STEP "timeStep"
#define P_LPNNS "lpnns"
#define P_NUM_OF_STATIONS "numOfStations"
#define P_HOURS "hours"
#define P_WEEK_DAYS "weekDays"
#define P_LOCALE "locale"
#define P_MISSING_TEXT "missingText"
#define P_MAX_EPOCHS "maxEpochs"
#define P_CRS "crs"
#define P_LATEST "latest"
namespace pt = boost::posix_time;
namespace lt = boost::local_time;
namespace ba = boost::algorithm;
namespace bl = boost::lambda;
using namespace SmartMet::Spine;
namespace SmartMet
{
namespace Plugin
{
namespace WFS
{
using boost::format;
using boost::str;
StoredObsQueryHandler::StoredObsQueryHandler(SmartMet::Spine::Reactor* reactor,
StoredQueryConfig::Ptr config,
PluginImpl& plugin_data,
boost::optional<std::string> template_file_name)
: StoredQueryParamRegistry(config),
SupportsExtraHandlerParams(config, false),
RequiresGeoEngine(reactor),
RequiresObsEngine(reactor),
StoredQueryHandlerBase(reactor, config, plugin_data, template_file_name),
SupportsLocationParameters(reactor, config, SUPPORT_KEYWORDS | INCLUDE_GEOIDS),
SupportsBoundingBox(config, plugin_data.get_crs_registry()),
SupportsTimeZone(reactor, config),
SupportsQualityParameters(config),
SupportsMeteoParameterOptions(config),
initial_bs_param(),
fmisid_ind(SmartMet::add_param(initial_bs_param, "fmisid", Parameter::Type::DataIndependent, kFmiFMISID)),
geoid_ind(SmartMet::add_param(initial_bs_param, "geoid", Parameter::Type::DataIndependent, kFmiGEOID)),
lon_ind(SmartMet::add_param(initial_bs_param, "stationlon", Parameter::Type::DataDerived, kFmiStationLongitude)),
lat_ind(SmartMet::add_param(initial_bs_param, "stationlat", Parameter::Type::DataDerived, kFmiStationLatitude)),
height_ind(
SmartMet::add_param(initial_bs_param, "elevation", Parameter::Type::DataIndependent, kFmiStationElevation)),
name_ind(
SmartMet::add_param(initial_bs_param, "stationname", Parameter::Type::DataIndependent, kFmiStationName)),
dist_ind(SmartMet::add_param(initial_bs_param, "distance", Parameter::Type::DataIndependent, kFmiDistance)),
direction_ind(
SmartMet::add_param(initial_bs_param, "direction", Parameter::Type::DataIndependent, kFmiDirection)),
wmo_ind(SmartMet::add_param(initial_bs_param, "wmo", Parameter::Type::DataIndependent, kFmiWmoStationNumber))
{
try
{
register_scalar_param<pt::ptime>(P_BEGIN_TIME);
register_scalar_param<pt::ptime>(P_END_TIME);
register_scalar_param<bool>(P_LATEST);
register_array_param<std::string>(P_METEO_PARAMETERS, 1);
register_scalar_param<std::string>(P_STATION_TYPE);
register_scalar_param<uint64_t>(P_TIME_STEP);
register_array_param<int64_t>(P_LPNNS);
register_scalar_param<uint64_t>(P_NUM_OF_STATIONS);
register_array_param<int64_t>(P_HOURS);
register_array_param<int64_t>(P_WEEK_DAYS);
register_scalar_param<std::string>(P_LOCALE);
register_scalar_param<std::string>(P_MISSING_TEXT);
register_scalar_param<uint64_t>(P_MAX_EPOCHS);
register_scalar_param<std::string>(P_CRS);
register_array_param<int64_t>(P_FMISIDS);
register_array_param<int64_t>(P_WMOS);
max_hours = config->get_optional_config_param<double>("maxHours", 7.0 * 24.0);
max_station_count = config->get_optional_config_param<unsigned>("maxStationCount", 0);
separate_groups = config->get_optional_config_param<bool>("separateGroups", false);
sq_restrictions = plugin_data.get_config().getSQRestrictions();
m_support_qc_parameters = config->get_optional_config_param<bool>("supportQCParameters", false);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
StoredObsQueryHandler::~StoredObsQueryHandler() {}
void StoredObsQueryHandler::query(const StoredQuery& query,
const std::string& language,
const boost::optional<std::string>& hostname,
std::ostream& output) const
{
try
{
namespace pt = boost::posix_time;
using namespace SmartMet;
using namespace SmartMet::Plugin::WFS;
const int debug_level = get_config()->get_debug_level();
if (debug_level > 0)
query.dump_query_info(std::cout);
// If 'data_source'-field exists
// extend it so that for every meteo.parameter
// a corresponding '*data_source'-field is added,
// for example, Temperature -> Temperature_data_source
auto params = query.get_param_map();
std::set<std::string> keys = params.get_keys();
for (auto k : keys)
{
if (k == "meteoParameters")
{
std::vector<SmartMet::Spine::Value> values = params.get_values(k);
std::vector<std::string> mparams;
bool dataSourceFound = false;
for (auto v : values)
{
std::string val = v.to_string();
if (val == "data_source")
{
dataSourceFound = true;
}
else
{
mparams.push_back(val);
}
}
if (dataSourceFound && mparams.size() > 0)
{
params.remove("meteoParameters");
for (auto p : mparams)
{
std::string fieldname = p + "_data_source";
params.add("meteoParameters", p);
params.add("meteoParameters", fieldname);
}
}
break;
}
}
try
{
std::vector<int64_t> tmp_vect;
SmartMet::Engine::Observation::Settings query_params;
query_params.useDataCache = true;
const char* DATA_CRS_NAME = "urn:ogc:def:crs:EPSG::4326";
query_params.latest = params.get_optional<bool>(P_LATEST, false);
query_params.starttime = params.get_single<pt::ptime>(P_BEGIN_TIME);
query_params.endtime = params.get_single<pt::ptime>(P_END_TIME);
if (sq_restrictions)
check_time_interval(query_params.starttime, query_params.endtime, max_hours);
std::vector<std::string> param_names;
bool have_meteo_param =
params.get<std::string>(P_METEO_PARAMETERS, std::back_inserter(param_names), 1);
query_params.stationtype =
Fmi::ascii_tolower_copy(params.get_single<std::string>(P_STATION_TYPE));
const bool support_quality_info = SupportsQualityParameters::supportQualityInfo(params);
std::vector<ExtParamIndexEntry> param_index;
query_params.parameters = initial_bs_param;
have_meteo_param &= add_parameters(params, param_names, query_params, param_index);
if (not have_meteo_param)
{
Fmi::Exception exception(BCP, "Operation processin failed!");
exception.addDetail("At least one meteo parameter must be specified");
exception.addParameter(WFS_EXCEPTION_CODE, WFS_OPERATION_PROCESSING_FAILED);
exception.disableStackTrace();
throw exception;
}
const std::string crs = params.get_single<std::string>(P_CRS);
auto transformation = crs_registry.create_transformation(DATA_CRS_NAME, crs);
bool show_height = false;
std::string proj_uri = "UNKNOWN";
std::string proj_epoch_uri = "UNKNOWN";
crs_registry.get_attribute(crs, "showHeight", &show_height);
crs_registry.get_attribute(crs, "projUri", &proj_uri);
crs_registry.get_attribute(crs, "projEpochUri", &proj_epoch_uri);
uint64_t timestep = params.get_single<uint64_t>(P_TIME_STEP);
// query_params.timestep = (timestep > 0 ? timestep : 1);
query_params.timestep = (timestep > 0 ? timestep : 0);
query_params.allplaces = false;
query_params.maxdistance = params.get_single<double>(P_MAX_DISTANCE);
query_params.timeformat = "iso";
query_params.timezone = "UTC";
query_params.numberofstations = params.get_single<uint64_t>(P_NUM_OF_STATIONS);
query_params.missingtext = params.get_single<std::string>(P_MISSING_TEXT);
query_params.localename = params.get_single<std::string>(P_LOCALE);
query_params.starttimeGiven = true;
params.get<int64_t>(P_HOURS, std::back_inserter(query_params.hours));
params.get<int64_t>(P_WEEK_DAYS, std::back_inserter(query_params.weekdays));
const std::string tz_name = get_tz_name(params);
std::unique_ptr<std::locale> curr_locale;
SmartMet::Engine::Observation::StationSettings stationSettings;
params.get<int64_t>(P_WMOS, std::back_inserter(stationSettings.wmos));
params.get<int64_t>(P_LPNNS, std::back_inserter(stationSettings.lpnns));
params.get<int64_t>(P_FMISIDS, std::back_inserter(stationSettings.fmisids));
std::list<std::pair<std::string, SmartMet::Spine::LocationPtr> > locations_list;
get_location_options(params, language, &locations_list);
for (const auto& item : locations_list)
{
stationSettings.nearest_station_settings.emplace_back(item.second->longitude,
item.second->latitude,
query_params.maxdistance,
query_params.numberofstations,
item.first,
item.second->fmisid);
}
params.get<int64_t>(P_GEOIDS, std::back_inserter(stationSettings.geoid_settings.geoids));
if (stationSettings.geoid_settings.geoids.size() > 0)
{
stationSettings.geoid_settings.maxdistance = query_params.maxdistance;
stationSettings.geoid_settings.numberofstations = query_params.numberofstations;
stationSettings.geoid_settings.language = language;
}
using SmartMet::Spine::BoundingBox;
BoundingBox requested_bbox;
bool have_bbox = get_bounding_box(params, crs, &requested_bbox);
std::unique_ptr<BoundingBox> query_bbox;
if (have_bbox)
{
query_bbox.reset(new BoundingBox);
*query_bbox = transform_bounding_box(requested_bbox, DATA_CRS_NAME);
stationSettings.bounding_box_settings["minx"] = query_bbox->xMin;
stationSettings.bounding_box_settings["miny"] = query_bbox->yMin;
stationSettings.bounding_box_settings["maxx"] = query_bbox->xMax;
stationSettings.bounding_box_settings["maxy"] = query_bbox->yMax;
query_params.boundingBox["minx"] = query_bbox->xMin;
query_params.boundingBox["miny"] = query_bbox->yMin;
query_params.boundingBox["maxx"] = query_bbox->xMax;
query_params.boundingBox["maxy"] = query_bbox->yMax;
if (debug_level > 0)
{
std::ostringstream msg;
msg << SmartMet::Spine::log_time_str() << ": [WFS] [DEBUG] Original bounding box: ("
<< requested_bbox.xMin << " " << requested_bbox.yMin << " " << requested_bbox.xMax
<< " " << requested_bbox.yMax << " " << requested_bbox.crs << ")\n";
msg << " "
<< " Converted bounding box: (" << query_bbox->xMin << " " << query_bbox->yMin << " "
<< query_bbox->xMax << " " << query_bbox->yMax << " " << query_bbox->crs << ")\n";
std::cout << msg.str() << std::flush;
}
}
if (query_params.starttime > query_params.endtime)
{
Fmi::Exception exception(BCP, "Invalid time interval!");
exception.addParameter(WFS_EXCEPTION_CODE, WFS_OPERATION_PARSING_FAILED);
exception.addParameter("Start time", pt::to_simple_string(query_params.starttime));
exception.addParameter("End time", pt::to_simple_string(query_params.endtime));
throw exception.disableStackTrace();
}
// Avoid an attempt to dump too much data.
unsigned maxEpochs = params.get_single<uint64_t>(P_MAX_EPOCHS);
unsigned ts1 = (timestep ? timestep : 60);
if (sq_restrictions and
query_params.starttime + pt::minutes(maxEpochs * ts1) < query_params.endtime)
{
Fmi::Exception exception(BCP, "Too many time epochs in the time interval!");
exception.addDetail("Use shorter time interval or larger time step.");
exception.addParameter(WFS_EXCEPTION_CODE, WFS_OPERATION_PROCESSING_FAILED);
exception.addParameter("Start time", pt::to_simple_string(query_params.starttime));
exception.addParameter("End time", pt::to_simple_string(query_params.endtime));
throw exception.disableStackTrace();
}
if (sq_restrictions and max_station_count > 0 and have_bbox)
{
Stations stations;
obs_engine->getStationsByBoundingBox(stations, query_params);
if (stations.size() > max_station_count)
{
Fmi::Exception exception(
BCP,
"Too many stations (" + std::to_string(stations.size()) + ") in the bounding box!");
exception.addDetail("No more than " + std::to_string(max_station_count) + " is allowed.");
exception.addParameter(WFS_EXCEPTION_CODE, WFS_OPERATION_PROCESSING_FAILED);
throw exception.disableStackTrace();
}
}
/*******************************************
* Finally perform the query *
*******************************************/
query_params.taggedFMISIDs = obs_engine->translateToFMISID(
query_params.starttime, query_params.endtime, query_params.stationtype, stationSettings);
SmartMet::Spine::TimeSeries::TimeSeriesVectorPtr obsengine_result(
obs_engine->values(query_params));
const bool emptyResult = (!obsengine_result || obsengine_result->size() == 0);
CTPP::CDT hash;
// Create index of all result rows (by observation site)
std::map<std::string, SiteRec> site_map;
std::map<int, GroupRec> group_map;
pt::ptime now = get_plugin_impl().get_time_stamp();
std::shared_ptr<Fmi::TimeFormatter> tfmt(Fmi::TimeFormatter::create("iso"));
// Formatting the SmartMet::Spine::TimeSeries::Value values.
SmartMet::Spine::ValueFormatter fmt{SmartMet::Spine::ValueFormatterParam()};
fmt.setMissingText(query_params.missingtext);
SmartMet::Spine::TimeSeries::StringVisitor sv(fmt, 3);
if (not emptyResult)
{
const SmartMet::Spine::TimeSeries::TimeSeries& ts_fmisid = obsengine_result->at(fmisid_ind);
for (std::size_t i = 0; i < ts_fmisid.size(); i++)
{
// Fmisids are doubles for some reason, fix this!!!!
sv.setPrecision(0);
const std::string fmisid = boost::apply_visitor(sv, ts_fmisid[i].value);
site_map[fmisid].row_index_vect.push_back(i);
}
}
// Get the sequence number of query in the request
int sq_id = query.get_query_id();
const int num_groups = separate_groups ? site_map.size() : ((site_map.size() != 0) ? 1 : 0);
FeatureID feature_id(get_config()->get_query_id(), params.get_map(), sq_id);
if (separate_groups)
{
// Assign group IDs to stations for separate groups requested
int group_cnt = 0;
BOOST_FOREACH (auto& item, site_map)
{
const std::string& fmisid = item.first;
const int group_id = group_cnt++;
item.second.group_id = group_id;
item.second.ind_in_group = 0;
const char* place_params[] = {
P_WMOS, P_LPNNS, P_FMISIDS, P_PLACES, P_LATLONS, P_GEOIDS, P_KEYWORD, P_BOUNDING_BOX};
for (unsigned i = 0; i < sizeof(place_params) / sizeof(*place_params); i++)
{
feature_id.erase_param(place_params[i]);
}
feature_id.add_param(P_FMISIDS, fmisid);
group_map[group_id].feature_id = feature_id.get_id();
BOOST_FOREACH (const std::string& param_name, param_names)
{
feature_id.erase_param(P_METEO_PARAMETERS);
feature_id.add_param(P_METEO_PARAMETERS, param_name);
group_map[group_id].param_ids[param_name] = feature_id.get_id();
}
}
}
else
{
const int group_id = 0;
int ind_in_group = 0;
BOOST_FOREACH (auto& item, site_map)
{
item.second.group_id = group_id;
item.second.ind_in_group = ind_in_group++;
}
group_map[group_id].feature_id = feature_id.get_id();
BOOST_FOREACH (const std::string& param_name, param_names)
{
feature_id.erase_param(P_METEO_PARAMETERS);
feature_id.add_param(P_METEO_PARAMETERS, param_name);
group_map[group_id].param_ids[param_name] = feature_id.get_id();
}
}
hash["responseTimestamp"] = Fmi::to_iso_extended_string(now) + "Z";
hash["numMatched"] = num_groups;
hash["numReturned"] = num_groups;
hash["numParam"] = param_names.size();
hash["language"] = language;
hash["projSrsDim"] = (show_height ? 3 : 2);
hash["projSrsName"] = proj_uri;
hash["projEpochSrsDim"] = (show_height ? 4 : 3);
hash["projEpochSrsName"] = proj_epoch_uri;
hash["queryNum"] = query.get_query_id();
hash["queryName"] = get_query_name();
params.dump_params(hash["query_parameters"]);
dump_named_params(params, hash["named_parameters"]);
hash["fmi_apikey"] = QueryBase::FMI_APIKEY_SUBST;
hash["fmi_apikey_prefix"] = QueryBase::FMI_APIKEY_PREFIX_SUBST;
hash["hostname"] = QueryBase::HOSTNAME_SUBST;
hash["protocol"] = QueryBase::PROTOCOL_SUBST;
if (not emptyResult)
{
const SmartMet::Spine::TimeSeries::TimeSeries& ts_lat = obsengine_result->at(lat_ind);
const SmartMet::Spine::TimeSeries::TimeSeries& ts_lon = obsengine_result->at(lon_ind);
const SmartMet::Spine::TimeSeries::TimeSeries& ts_height = obsengine_result->at(height_ind);
const SmartMet::Spine::TimeSeries::TimeSeries& ts_name = obsengine_result->at(name_ind);
const SmartMet::Spine::TimeSeries::TimeSeries& ts_dist = obsengine_result->at(dist_ind);
const SmartMet::Spine::TimeSeries::TimeSeries& ts_direction =
obsengine_result->at(direction_ind);
const SmartMet::Spine::TimeSeries::TimeSeries& ts_geoid = obsengine_result->at(geoid_ind);
const SmartMet::Spine::TimeSeries::TimeSeries& ts_wmo = obsengine_result->at(wmo_ind);
std::map<std::string, SmartMet::Spine::LocationPtr> sites;
BOOST_FOREACH (const auto& it1, site_map)
{
const std::string& fmisid = it1.first;
const int group_id = it1.second.group_id;
const int ind = it1.second.ind_in_group;
const int row_1 = it1.second.row_index_vect.at(0);
CTPP::CDT& group = hash["groups"][group_id];
group["obsStationList"][ind]["fmisid"] = fmisid;
sv.setPrecision(5);
const std::string lat = boost::apply_visitor(sv, ts_lat[row_1].value);
const std::string lon = boost::apply_visitor(sv, ts_lon[row_1].value);
sv.setPrecision(1);
const std::string height = boost::apply_visitor(sv, ts_height[row_1].value);
const std::string name = boost::apply_visitor(sv, ts_name[row_1].value);
const std::string distance = boost::apply_visitor(sv, ts_dist[row_1].value);
const std::string bearing = boost::apply_visitor(sv, ts_direction[row_1].value);
const std::string geoid = boost::apply_visitor(sv, ts_geoid[row_1].value);
const std::string wmo = boost::apply_visitor(sv, ts_wmo[row_1].value);
if (not lat.empty() and not lon.empty())
set_2D_coord(transformation, lat, lon, group["obsStationList"][ind]);
else
throw Fmi::Exception(BCP, "wfs: Internal LatLon query error.");
// Region solving
std::string region;
SmartMet::Spine::LocationPtr geoLoc;
if (not geoid.empty())
{
try
{
const long geoid_long = Fmi::stol(geoid);
std::string langCode = language;
SupportsLocationParameters::engOrFinToEnOrFi(langCode);
geoLoc = geo_engine->idSearch(geoid_long, langCode);
region = (geoLoc ? geoLoc->area : "");
}
catch (...)
{
}
sites[geoid] = geoLoc;
}
if (show_height)
group["obsStationList"][ind]["height"] =
(height.empty() ? query_params.missingtext : height);
group["obsStationList"][ind]["distance"] =
(distance.empty() ? query_params.missingtext : distance);
group["obsStationList"][ind]["bearing"] =
((distance.empty() or bearing.empty() or (distance == query_params.missingtext))
? query_params.missingtext
: bearing);
group["obsStationList"][ind]["name"] = name;
if (not region.empty())
group["obsStationList"][ind]["region"] = region;
if (not wmo.empty() && wmo != "0" && wmo != "NaN")
group["obsStationList"][ind]["wmo"] = wmo;
(geoid.empty() or geoid == "-1")
? group["obsStationList"][ind]["geoid"] = query_params.missingtext
: group["obsStationList"][ind]["geoid"] = geoid;
}
for (int group_id = 0; group_id < num_groups; group_id++)
{
int ind = 0;
CTPP::CDT& group = hash["groups"][group_id];
// Time values of a group.
group["obsPhenomenonStartTime"] =
Fmi::to_iso_extended_string(query_params.starttime) + "Z";
group["obsPhenomenonEndTime"] = Fmi::to_iso_extended_string(query_params.endtime) + "Z";
group["obsResultTime"] = Fmi::to_iso_extended_string(query_params.endtime) + "Z";
group["featureId"] = group_map.at(group_id).feature_id;
group["crs"] = crs;
if (tz_name != "UTC")
group["timezone"] = tz_name;
group["timestep"] = query_params.timestep;
if (support_quality_info)
group["qualityInfo"] = "on";
for (std::size_t k = 0; k < param_index.size(); k++)
{
const auto& entry = param_index[k];
const std::string& name = entry.p.name;
group["obsParamList"][k]["name"] = (entry.p.sensor_name ? *entry.p.sensor_name : entry.p.name);
group["obsParamList"][k]["featureId"] = group_map.at(group_id).param_ids.at(name);
// Mark QC parameters
if (SupportsQualityParameters::isQCParameter(name))
{
group["obsParamList"][k]["isQCParameter"] = "true";
}
}
// Reference id of om:phenomenonTime and om:resultTime in
// a group (a station). The first parameter in a list
// get the time values (above) and other ones get only
// references to the values.
const std::string group_id_str = str(format("%1%-%2%") % sq_id % (group_id + 1));
group["groupId"] = group_id_str;
group["groupNum"] = group_id + 1;
BOOST_FOREACH (const auto& it1, site_map)
{
const int row_1 = it1.second.row_index_vect.at(0);
if (it1.second.group_id == group_id)
{
bool first = true;
lt::time_zone_ptr tzp;
const SmartMet::Spine::TimeSeries::TimeSeries& ts_epoch =
obsengine_result->at(initial_bs_param.size());
BOOST_FOREACH (int row_num, it1.second.row_index_vect)
{
static const long ref_jd = boost::gregorian::date(1970, 1, 1).julian_day();
sv.setPrecision(5);
// Use first row instead of row_num for static parameter values
// SHOULD FIX Delfoi instead!
const std::string latitude = boost::apply_visitor(sv, ts_lat[row_1].value);
const std::string longitude = boost::apply_visitor(sv, ts_lon[row_1].value);
const std::string geoid = boost::apply_visitor(sv, ts_geoid[row_1].value);
if (first)
{
tzp = get_tz_for_site(std::stod(longitude), std::stod(latitude), tz_name);
}
CTPP::CDT obs_rec;
set_2D_coord(transformation, latitude, longitude, obs_rec);
if (show_height)
{
sv.setPrecision(1);
const std::string height = boost::apply_visitor(sv, ts_height[row_num].value);
obs_rec["height"] = (height.empty() ? query_params.missingtext : height);
}
const auto ldt = ts_epoch.at(row_num).time;
pt::ptime epoch = ldt.utc_time();
// Cannot use pt::time_difference::total_seconds() directly as it returns long and
// could overflow.
long long jd = epoch.date().julian_day();
long seconds = epoch.time_of_day().total_seconds();
INT_64 s_epoch = 86400LL * (jd - ref_jd) + seconds;
obs_rec["epochTime"] = s_epoch;
obs_rec["epochTimeStr"] = format_local_time(epoch, tzp);
for (std::size_t k = 0; k < param_index.size(); k++)
{
const auto& entry = param_index[k];
const std::string& name = entry.p.name;
const int ind = entry.p.ind;
if (ind >= 0)
{
const SmartMet::Spine::TimeSeries::TimeSeries& ts_k = obsengine_result->at(ind);
const uint precision = get_meteo_parameter_options(name)->precision;
sv.setPrecision(precision);
const std::string value = boost::apply_visitor(sv, ts_k[row_num].value);
obs_rec["data"][k]["value"] = value;
if (entry.qc)
{
const int qc_ind = entry.qc->ind;
std::stringstream qc_value;
const SmartMet::Spine::TimeSeries::TimeSeries& ts_qc_k =
obsengine_result->at(qc_ind);
sv.setPrecision(0);
const std::string value_qc = boost::apply_visitor(sv, ts_qc_k[row_num].value);
obs_rec["data"][k]["qcValue"] = value_qc;
}
}
else
{
auto geoLoc = sites.at(geoid);
if (geoLoc)
{
if (SmartMet::Spine::is_location_parameter(name))
{
const std::string val = SmartMet::Spine::location_parameter(
geoLoc,
name,
fmt,
tz_name,
get_meteo_parameter_options(name)->precision);
obs_rec["data"][k]["value"] = val;
}
else if (SmartMet::Spine::is_time_parameter(name))
{
const std::string timestring = "Not supported";
if (not curr_locale)
{
curr_locale.reset(new std::locale(query_params.localename.c_str()));
}
const auto val = SmartMet::Spine::time_parameter(name,
ldt,
now,
*geoLoc,
tz_name,
geo_engine->getTimeZones(),
*curr_locale,
*tfmt,
timestring);
std::ostringstream val_str;
val_str << val;
obs_rec["data"][k]["value"] = val_str.str();
}
else
{
assert(0 /* Not supposed to be here */);
}
}
else
{
obs_rec["data"][k]["value"] = query_params.missingtext;
}
}
}
group["obsReturnArray"][ind++] = obs_rec;
}
}
}
}
}
format_output(hash, output, query.get_use_debug_format());
}
catch (...)
{
Fmi::Exception exception(BCP, "Operation processing failed!", nullptr);
if (exception.getExceptionByParameterName(WFS_EXCEPTION_CODE) == nullptr)
exception.addParameter(WFS_EXCEPTION_CODE, WFS_OPERATION_PROCESSING_FAILED);
exception.addParameter(WFS_LANGUAGE, language);
throw exception;
}
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
void StoredObsQueryHandler::check_parameter_names(const RequestParameterMap& params,
const std::vector<std::string>& param_names) const
{
std::set<std::string> lowerCaseParamNames;
const bool support_quality_info = SupportsQualityParameters::supportQualityInfo(params);
for (const std::string& name : param_names)
{
const std::string l_name = Fmi::ascii_tolower_copy(name);
if (not lowerCaseParamNames.insert(l_name).second)
{
throw Fmi::Exception::Trace(BCP, "Duplicate parameter name '" + name + "'!")
.addParameter(WFS_EXCEPTION_CODE, WFS_INVALID_PARAMETER_VALUE);
}
// FIXME: handle possible conflict case when QC paremeter explicit specification is allowed
// and sama QC parameter may also be added automatically
if ((not m_support_qc_parameters or not support_quality_info) and
SupportsQualityParameters::isQCParameter(name))
{
throw Fmi::Exception::Trace(BCP, "Invalid parameter!")
.addDetail("Quality code parameter '" + name + "' is not allowed in this query.")
.addParameter(WFS_EXCEPTION_CODE, WFS_INVALID_PARAMETER_VALUE);
}
}
}
int StoredObsQueryHandler::lookup_initial_parameter(const std::string& name) const
{
for (std::size_t i = 0; i < initial_bs_param.size(); i++)
{
if (name == initial_bs_param[i].name())
{
return i;
}
}
return -1;
}
bool StoredObsQueryHandler::add_parameters(const RequestParameterMap& params,
const std::vector<std::string>& param_names,
SmartMet::Engine::Observation::Settings& query_params,
std::vector<ExtParamIndexEntry>& parameter_index) const
{
using SmartMet::Spine::is_location_parameter;
using SmartMet::Spine::is_special_parameter;
using SmartMet::Spine::is_time_parameter;
using SmartMet::Spine::makeParameter;
try
{
bool have_meteo_param = false;
std::set<std::string> lowerCaseParamNames;
const bool support_quality_info = SupportsQualityParameters::supportQualityInfo(params);
auto qc_param_name_ref = SupportsQualityParameters::firstQCParameter(param_names);
const bool have_explicit_qc_params = qc_param_name_ref != param_names.end();
if ((not m_support_qc_parameters or not support_quality_info) and have_explicit_qc_params)
{
throw Fmi::Exception::Trace(BCP, "Invalid parameter!")
.addDetail("Quality code parameter '" + *qc_param_name_ref +
"' is not allowed in this query.")
.addParameter(WFS_EXCEPTION_CODE, WFS_INVALID_PARAMETER_VALUE);
}
for (const auto& name : param_names)
{
const std::string l_name = Fmi::ascii_tolower_copy(name);
// Check for duplicates
if (not lowerCaseParamNames.insert(l_name).second)
{
throw Fmi::Exception::Trace(BCP, "Duplicate parameter name '" + name + "'!")
.addParameter(WFS_EXCEPTION_CODE, WFS_INVALID_PARAMETER_VALUE);
}
if (obs_engine->isParameter(name, query_params.stationtype))
{
// Normal parameter
ExtParamIndexEntry entry;
entry.p.ind = query_params.parameters.size();
entry.p.name = name;
SmartMet::Spine::Parameter param = makeParameter(name);
bool sensor_parameter_exists = false;
if (not SmartMet::Spine::special(param))
{
have_meteo_param = true;
auto parameter_option = get_meteo_parameter_options(name);
if ((parameter_option->sensor_first != 1) || (parameter_option->sensor_last != 1))
{
for (unsigned short index = parameter_option->sensor_first; index < parameter_option->sensor_last + 1; index += parameter_option->sensor_step)
{
if (index < parameter_option->sensor_last + 1)
{
param = makeParameter(name);
param.setSensorNumber(index);
entry.p.ind = query_params.parameters.size();
entry.p.sensor_name = (entry.p.name + "(:" + Fmi::to_string(index) + ")");
query_params.parameters.push_back(param);
if (not have_explicit_qc_params and support_quality_info)
{
const std::string qc_name = "qc_" + name;
ParamIndexEntry qc_entry;
qc_entry.ind = query_params.parameters.size();
qc_entry.name = qc_name;
entry.qc = qc_entry;
SmartMet::Spine::Parameter param = makeParameter(qc_name);
query_params.parameters.push_back(param);
}
sensor_parameter_exists = true;
parameter_index.push_back(entry);
}
}
}
}
// If there is no sensors defined, add default parameter
if(!sensor_parameter_exists)
{
query_params.parameters.push_back(param);
if (not have_explicit_qc_params and support_quality_info)
{
const std::string qc_name = "qc_" + name;
ParamIndexEntry qc_entry;
qc_entry.ind = query_params.parameters.size();
qc_entry.name = qc_name;
entry.qc = qc_entry;
SmartMet::Spine::Parameter param = makeParameter(qc_name);
query_params.parameters.push_back(param);
}
parameter_index.push_back(entry);
}
}
else if (is_special_parameter(name))
{
int ind = lookup_initial_parameter(l_name);
if (ind >= 0)
{
ExtParamIndexEntry entry;
entry.p.ind = ind;
entry.p.name = name;
parameter_index.push_back(entry);
}
else
{
if (is_location_parameter(name) or is_time_parameter(name))
{
ExtParamIndexEntry entry;
entry.p.ind = -1;
entry.p.name = name;
parameter_index.push_back(entry);
}
else
{
ExtParamIndexEntry entry;
entry.p.ind = query_params.parameters.size();
entry.p.name = name;
SmartMet::Spine::Parameter param = makeParameter(name);
query_params.parameters.push_back(param);
parameter_index.push_back(entry);
}
}
}
else
{
throw Fmi::Exception::Trace(BCP, "Unrecognozed parameter '" + name + "'")
.disableStackTrace();
}
}
return have_meteo_param;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation processing failed!");
}
}
} // namespace WFS
} // namespace Plugin
} // namespace SmartMet
namespace
{
using namespace SmartMet::Plugin::WFS;
boost::shared_ptr<SmartMet::Plugin::WFS::StoredQueryHandlerBase> wfs_obs_handler_create(
SmartMet::Spine::Reactor* reactor,
StoredQueryConfig::Ptr config,
PluginImpl& plugin_data,
boost::optional<std::string> template_file_name)
{
try
{
StoredObsQueryHandler* qh =
new StoredObsQueryHandler(reactor, config, plugin_data, template_file_name);
boost::shared_ptr<SmartMet::Plugin::WFS::StoredQueryHandlerBase> result(qh);
return result;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
} // namespace
SmartMet::Plugin::WFS::StoredQueryHandlerFactoryDef wfs_obs_handler_factory(
&wfs_obs_handler_create);
/**
@page WFS_SQ_GENERIC_OBS Stored query handler for querying observation data
@section WFS_SQ_GENERIC_OBS_INTRO Introduction
Stored query handler for accessing observation data provides access to weather
observations (except lightning observations)
<table border="1">
<tr>
<td>Implementation</td>
<td>SmartMet::Plugin::WFS::StoredObsQueryHandler</td>
</tr>
<tr>
<td>Constructor name (for stored query configuration)</td>
<td>@b wfs_obs_handler_factory</td>
</tr>
</table>
@section WFS_SQ_GENERIC_OBS_PARAM Stored query handler built-in parameters
The following stored query handler parameter groups are being used by this stored query handler:
- @ref WFS_SQ_LOCATION_PARAMS
- @ref WFS_SQ_PARAM_BBOX
- @ref WFS_SQ_TIME_ZONE
- @ref WFS_SQ_QUALITY_PARAMS
- @ref WFS_SQ_METEO_PARAM_OPTIONS
Additionally to parameters from these groups the following parameters are also in use
<table border="1">
<tr>
<th>Entry name</th>
<th>Type</th>
<th>Data type</th>
<th>Description</th>
</tr>
<tr>
<td>beginTime</td>
<td>@ref WFS_CFG_SCALAR_PARAM_TMPL</td>
<td>time</td>
<td>Specifies the time of the begin of time interval</td>
</tr>
<tr>
<td>endTime</td>
<td>@ref WFS_CFG_SCALAR_PARAM_TMPL</td>
<td>time</td>
<td>Specifies the time of the end of time interval</td>
</tr>
<tr>
<td>meteoParameters</td>
<td>@ref WFS_CFG_ARRAY_PARAM_TMPL</td>
<td>string</td>
<td>Specifies the meteo parameters to query. At least one parameter must be specified</td>
</tr>
<tr>
<td>stationType</td>
<td>@ref WFS_CFG_SCALAR_PARAM_TMPL</td>
<td>string</td>
<td>Specifies station type.</td>
</tr>
<tr>
<td>timeStep</td>
<td>@ref WFS_CFG_SCALAR_PARAM_TMPL</td>
<td>unsigned integer</td>
<td>Specifies time stamp for querying observations</td>
</tr>
<tr>
<td>wmos</td>
<td>@ref WFS_CFG_ARRAY_PARAM_TMPL</td>
<td>integer</td>
<td>Specifies stations WMO codes</td>
</tr>
<tr>
<td>lpnns</td>
<td>@ref WFS_CFG_ARRAY_PARAM_TMPL</td>
<td>integer</td>
<td>Specifies stations LPPN codes</td>
</tr>
<tr>
<td>fmisids</td>
<td>@ref WFS_CFG_ARRAY_PARAM_TMPL</td>
<td>integer</td>
<td>Specifies stations FMISID codes</td>
</tr>
<tr>
<td>numOfStations</td>
<td>@ref WFS_CFG_SCALAR_PARAM_TMPL</td>
<td>unsigned integer</td>
<td>Specifies how many nearest stations to select with distance less than @b maxDistance
(see @ref WFS_SQ_LOCATION_PARAMS "location parameters" for details)</td>
</tr>
<tr>
<td>hours</td>
<td>@ref WFS_CFG_ARRAY_PARAM_TMPL</td>
<td>integer</td>
<td>Specifies hours for which to return data if non empty array provided</td>
</tr>
<tr>
<td>weekDays</td>
<td>@ref WFS_CFG_ARRAY_PARAM_TMPL</td>
<td>integer</td>
<td>Week days for which to return data if non empty array is provided</td>
</tr>
<tr>
<td>locale</td>
<td>@ref WFS_CFG_SCALAR_PARAM_TMPL</td>
<td>string</td>
<td>The locale code (like 'fi_FI.utf8')</td>
</tr>
<tr>
<td>missingText</td>
<td>@ref WFS_CFG_SCALAR_PARAM_TMPL</td>
<td>string</td>
<td>Text to use to indicate missing value</td>
</tr>
<tr>
<td>maxEpochs</td>
<td>@ref WFS_CFG_SCALAR_PARAM_TMPL</td>
<td>unsigned integer</td>
<td>Maximal number of epochs that can be returned. If the estimated number
before query is larger than the specified one, query is aborted with
and processing error. This parameter is not valid, if the *optional*
storedQueryRestrictions parameter is set to false in WFS Plugin
configurations.</td>
</tr>
<tr>
<td>CRS</td>
<td>@ref WFS_CFG_SCALAR_PARAM_TMPL</td>
<td>string</td>
<td>Specifies coordinate projection to use</td>
</tr>
</table>
@section WFS_SQ_GENERIC_OBS_EXTRA_CFG_PARAM Additional parameters
This section describes this stored query handler configuration parameters which does not map to
stored query parameters
and must be specified on top level of stored query configuration file when present
<table border="1">
<tr>
<th>Entry name</th>
<th>Type</th>
<th>Use</th>
<th>Description</th>
</tr>
<tr>
<td>maxHours</td>
<td>double</td>
<td>optional</td>
<td>Specifies maximal permitted time interval in hours. The default value
is 168 hours (7 days). This parameter is not valid, if the *optional*
storedQueryRestrictions parameter is set to false in WFS Plugin
configurations.</td>
</tr>
<tr>
<td>maxStationCount</td>
<td>unsigned integer</td>
<td>optional</td>
<td>Specifies maximal permitted number of stations. This count is currently checked for bounding
boxes only.
The ProcessingError exception report is returned if the actual count exceeds the specified
one.
The default value 0 means unlimited. The default value is also used,
if the *optional* storedQueryRestrictions parameter is set to false in
WFS Plugin configurations.</td>
</tr>
<tr>
<td>separateGroups</td>
<td>boolean</td>
<td>optional (default @b false)</td>
<td>Providing value @b true tells handler to split returned observations into separate groups
by station (separate group for each station)</td>
</tr>
<tr>
<td>supportQCParameters</td>
<td>boolean</td>
<td>optional (default @b false)</td>
<td>Providing value @b true tells handler to allow meteoParameters with "qc_" prefix to
query.</td>
</tr>
</table>
*/
| 37.881162
| 147
| 0.615249
|
nakkim
|
2a8e5b39811a76bd7f064d076522da7a82c909b7
| 1,538
|
cpp
|
C++
|
GeeksForGeeks/C Plus Plus/Binary_Tree_to_BST.cpp
|
ankit-sr/Competitive-Programming
|
3397b313b80a32a47cfe224426a6e9c7cf05dec2
|
[
"MIT"
] | 4
|
2021-06-19T14:15:34.000Z
|
2021-06-21T13:53:53.000Z
|
GeeksForGeeks/C Plus Plus/Binary_Tree_to_BST.cpp
|
ankit-sr/Competitive-Programming
|
3397b313b80a32a47cfe224426a6e9c7cf05dec2
|
[
"MIT"
] | 2
|
2021-07-02T12:41:06.000Z
|
2021-07-12T09:37:50.000Z
|
GeeksForGeeks/C Plus Plus/Binary_Tree_to_BST.cpp
|
ankit-sr/Competitive-Programming
|
3397b313b80a32a47cfe224426a6e9c7cf05dec2
|
[
"MIT"
] | 3
|
2021-06-19T15:19:20.000Z
|
2021-07-02T17:24:51.000Z
|
/*
Problem Statement:
-----------------
Given a Binary Tree, convert it to Binary Search Tree in such a way that keeps the original structure of Binary Tree intact.
Example 1:
---------
Input:
1
/ \
2 3
Output: 1 2 3
Example 2:
----------
Input:
1
/ \
2 3
/
4
Output: 1 2 3 4
Explanation:
The converted BST will be
3
/ \
2 4
/
1
Your Task: You don't need to read input or print anything. Your task is to complete the function binaryTreeToBST() which takes the root of the Binary tree
as input and returns the root of the BST. The driver code will print inorder traversal of the converted BST.
Expected Time Complexity: O(NLogN).
Expected Auxiliary Space: O(N).
*/
// Link --> https://practice.geeksforgeeks.org/problems/binary-tree-to-bst/1#
// Code:
class Solution
{
public:
vector <int> in;
void preorder(Node *root)
{
if(root == NULL)
return;
in.push_back(root->data);
preorder(root->left);
preorder(root->right);
}
int index = 0;
void BST(Node *root)
{
if(root == NULL)
return;
BST(root->left);
root->data = in[index++];
BST(root->right);
}
Node* binaryTreeToBST(Node *root)
{
if(root == NULL)
return NULL;
preorder(root);
sort(in.begin() , in.end());
BST(root);
return root;
}
};
| 19.717949
| 155
| 0.529909
|
ankit-sr
|
2a8e675565d5df500801d12f84ecc49f43a47f54
| 798
|
cpp
|
C++
|
leetcode/medium/918. Maximum Sum Circular Subarray.cpp
|
Jeongseo21/Algorithm-1
|
1bce4f3d2328c3b3e24b9d7772fca43090a285e1
|
[
"MIT"
] | 7
|
2019-08-05T14:49:41.000Z
|
2022-03-13T07:10:51.000Z
|
leetcode/medium/918. Maximum Sum Circular Subarray.cpp
|
Jeongseo21/Algorithm-1
|
1bce4f3d2328c3b3e24b9d7772fca43090a285e1
|
[
"MIT"
] | null | null | null |
leetcode/medium/918. Maximum Sum Circular Subarray.cpp
|
Jeongseo21/Algorithm-1
|
1bce4f3d2328c3b3e24b9d7772fca43090a285e1
|
[
"MIT"
] | 4
|
2021-01-04T03:45:22.000Z
|
2021-10-06T06:11:00.000Z
|
/**
* problem : https://leetcode.com/problems/maximum-sum-circular-subarray/
* time comlexity : O(N)
*/
class Solution {
public:
int maxSubarraySumCircular(vector<int>& A) {
int ans = A[0];
int maxSub = A[0];
int minSub = A[0];
int sum = 0;
int sumMax = 0;
int sumMin = 0;
int maxNum = A[0];
for(int i=0; i< A.size(); i++){
sumMax = sumMax + A[i] > 0 ? sumMax + A[i] : 0;
maxSub = max(maxSub, sumMax);
sumMin = sumMin + A[i] < 0 ? sumMin + A[i] : 0;
minSub = min(minSub, sumMin);
sum += A[i];
maxNum = max(maxNum, A[i]);
}
return maxNum < 0 ? maxNum : max(maxSub, sum - minSub);
}
};
| 24.9375
| 73
| 0.448622
|
Jeongseo21
|
2a8f1c571837b15f19fc0a4b761e789d2d16f7ce
| 497
|
cpp
|
C++
|
Project/expense.cpp
|
aczapi/BudgetApp
|
63cb171d1384e7ca12542632da7ce9b3ae46d21b
|
[
"Unlicense"
] | null | null | null |
Project/expense.cpp
|
aczapi/BudgetApp
|
63cb171d1384e7ca12542632da7ce9b3ae46d21b
|
[
"Unlicense"
] | null | null | null |
Project/expense.cpp
|
aczapi/BudgetApp
|
63cb171d1384e7ca12542632da7ce9b3ae46d21b
|
[
"Unlicense"
] | null | null | null |
#include "expense.hpp"
void Expense::setUserId(int userId) {
if (userId > 0)
userId_ = userId;
}
void Expense::setExpenseId(int expenseId) {
if (expenseId > 0)
expenseId_ = expenseId;
}
void Expense::setDate(std::string date) {
date_ = date;
}
void Expense::setItem(std::string item) {
item_ = item;
}
void Expense::setAmount(float amount) {
if (amount > 0)
amount_ = amount;
}
void Expense::setDateAsInt(int dateAsInt) {
dateAsInt_ = dateAsInt;
}
| 20.708333
| 43
| 0.645875
|
aczapi
|
2a921f050f9bc5f64e3f358c2ce808b5042ec8a6
| 188
|
cxx
|
C++
|
src/lib/models/model/test/tst_model.cxx
|
johanneslochmann/cppprojecttemplate
|
28f1bd4dd1bc414ed38c8a739e33974f65891f83
|
[
"BSD-3-Clause"
] | null | null | null |
src/lib/models/model/test/tst_model.cxx
|
johanneslochmann/cppprojecttemplate
|
28f1bd4dd1bc414ed38c8a739e33974f65891f83
|
[
"BSD-3-Clause"
] | null | null | null |
src/lib/models/model/test/tst_model.cxx
|
johanneslochmann/cppprojecttemplate
|
28f1bd4dd1bc414ed38c8a739e33974f65891f83
|
[
"BSD-3-Clause"
] | null | null | null |
#include <gtest/gtest.h>
#include <models/model/model.hxx>
PRAM_NS_BEGIN
MODEL_NAMESPACE_BEGIN
TEST(tst_model, testCtor) {
Model m;
(void) m;
}
MODEL_NAMESPACE_END
PRAM_NS_END
| 12.533333
| 33
| 0.744681
|
johanneslochmann
|
2aa1957907c190a5d7921edb2a90a8e29f76fab4
| 3,121
|
hpp
|
C++
|
modules/core/include/core/shader_codex.hpp
|
Wmbat/vermillon
|
3dafc3d17a3225d32c62a3169b6b3dda32182b88
|
[
"MIT"
] | 1
|
2021-04-07T03:02:47.000Z
|
2021-04-07T03:02:47.000Z
|
modules/core/include/core/shader_codex.hpp
|
Wmbat/vermillon
|
3dafc3d17a3225d32c62a3169b6b3dda32182b88
|
[
"MIT"
] | null | null | null |
modules/core/include/core/shader_codex.hpp
|
Wmbat/vermillon
|
3dafc3d17a3225d32c62a3169b6b3dda32182b88
|
[
"MIT"
] | null | null | null |
#pragma once
#include <core/core.hpp>
#include <util/containers/dense_hash_map.hpp>
#include <vkn/shader.hpp>
#include <glslang/Public/ShaderLang.h>
namespace core
{
enum class shader_codex_error
{
failed_to_open_file,
unknow_shader_type,
failed_to_preprocess_shader,
failed_to_parse_shader,
failed_to_link_shader,
failed_to_cache_shader,
failed_to_create_shader
};
auto to_string(shader_codex_error err) -> std::string;
auto make_error(shader_codex_error err) noexcept -> error_t;
class shader_codex
{
public:
shader_codex() = default;
auto add_shader(const std::filesystem::path& path) -> std::string;
auto add_precompiled_shader(vkn::shader&& shader) -> std::string;
auto get_shader(const std::string& name) noexcept -> vkn::shader&;
[[nodiscard]] auto get_shader(const std::string& name) const noexcept -> const vkn::shader&;
private:
std::unordered_map<std::string, vkn::shader> m_shaders;
static inline constexpr int client_input_semantics_version = 100;
static inline constexpr int default_version = 100;
public:
class builder
{
public:
builder(const vkn::device& device, std::shared_ptr<util::logger> p_logger) noexcept;
auto build() -> core::result<shader_codex>;
auto set_cache_directory(const std::filesystem::path& path) -> builder&;
auto set_shader_directory(const std::filesystem::path& path) -> builder&;
auto add_shader_filepath(const std::filesystem::path& path) -> builder&;
auto allow_caching(bool is_caching_allowed = true) noexcept -> builder&;
private:
auto create_shader(const std::filesystem::path& path) -> core::result<vkn::shader>;
auto compile_shader(const std::filesystem::path& path)
-> core::result<util::dynamic_array<std::uint32_t>>;
auto load_shader(const std::filesystem::path& path)
-> core::result<util::dynamic_array<std::uint32_t>>;
[[nodiscard]] auto cache_shader(const std::filesystem::path& path,
const util::dynamic_array<std::uint32_t>& data) const
-> monad::maybe<error_t>;
[[nodiscard]] auto get_shader_stage(std::string_view stage_name) const -> EShLanguage;
[[nodiscard]] auto get_spirv_version(uint32_t version) const
-> glslang::EShTargetLanguageVersion;
[[nodiscard]] auto get_vulkan_version(uint32_t version) const
-> glslang::EshTargetClientVersion;
[[nodiscard]] auto get_shader_type(std::string_view ext_name) const -> vkn::shader_type;
private:
std::shared_ptr<util::logger> mp_logger;
const vkn::device* mp_device;
struct info
{
std::filesystem::path cache_directory_path{"cache/shaders"};
std::filesystem::path shader_directory_path{};
util::dynamic_array<std::filesystem::path> shader_paths{};
bool is_caching_allowed = true;
} m_info;
};
};
} // namespace core
| 34.296703
| 98
| 0.655239
|
Wmbat
|
2aa433a4bd1fcf9dace87958b7f15ebe6d244241
| 747
|
cpp
|
C++
|
program/OccurrencesCounter.cpp
|
wojtkolos/huffman_tree_generator
|
1679ead8c2b180024a782b1d027beffac7a95f64
|
[
"Apache-2.0"
] | null | null | null |
program/OccurrencesCounter.cpp
|
wojtkolos/huffman_tree_generator
|
1679ead8c2b180024a782b1d027beffac7a95f64
|
[
"Apache-2.0"
] | null | null | null |
program/OccurrencesCounter.cpp
|
wojtkolos/huffman_tree_generator
|
1679ead8c2b180024a782b1d027beffac7a95f64
|
[
"Apache-2.0"
] | null | null | null |
#include "OccurrencesCounter.h"
OccurrencesCounter::OccurrencesCounter(std::vector<std::string> inp) : vec(inp) {}
void OccurrencesCounter::calculate() {
for (auto i = 0; i < vec.size(); ++i) {
for (auto el : vec[i])
{
if ((el >= 65 && el >= 90) or (el >= 97 && el <= 122))
++count[el];
}
}
print();
}
void OccurrencesCounter::print() {
for (int i = 97; i < 123; i++) //wypisanie wyst¹pieñ ma³ych liter ASCII - 97-122
if (count[i] > 0)
printf("%d - %d \n", i, count[i]);
for (int i = 65; i < 91; i++) //wypisanie wyst¹pieñ du¿ych liter ASCII - 65-90
if (count[i] > 0)
printf("%d - %d \n", i, count[i]);
}
| 28.730769
| 85
| 0.487282
|
wojtkolos
|
2aa725fe58dfa44e0477431e0c02ee98c2f79c17
| 8,287
|
cpp
|
C++
|
source/binding/Research.cpp
|
Stephouuu/Epitech-Bomberman
|
8650071a6a21ba2e0606e4d8e38794de37bdf39f
|
[
"Unlicense"
] | null | null | null |
source/binding/Research.cpp
|
Stephouuu/Epitech-Bomberman
|
8650071a6a21ba2e0606e4d8e38794de37bdf39f
|
[
"Unlicense"
] | null | null | null |
source/binding/Research.cpp
|
Stephouuu/Epitech-Bomberman
|
8650071a6a21ba2e0606e4d8e38794de37bdf39f
|
[
"Unlicense"
] | null | null | null |
/*
** Research.cpp for bomberman in /home/care_j/work/bomberman/source/binding
**
** Made by care_j
** Login <care_j@epitech.net>
**
*/
#include "Research.hpp"
bbman::Research::Research(void)
{
this->_trueA.addBlockType(bbman::ItemID::II_BLOCK_INBRKABLE);
this->_trueA.addBlockType(bbman::ItemID::II_BLOCK_BRKABLE);
this->_neighA.addBlockType(bbman::ItemID::II_BLOCK_INBRKABLE);
this->_neighA.addBlockType(bbman::ItemID::II_BLOCK_BRKABLE);
this->_checkers[0] = std::bind(&bbman::Research::checkNorthEast, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4);
this->_checkers[1] = std::bind(&bbman::Research::checkNorthWest, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4);
this->_checkers[2] = std::bind(&bbman::Research::checkSouthEast, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4);
this->_checkers[3] = std::bind(&bbman::Research::checkSouthWest, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4);
}
bbman::Research::~Research(void)
{}
void bbman::Research::setL(lua_State *L)
{
this->_L = L;
}
void bbman::Research::setBoard(bbman::Board *board)
{
this->_board = board;
}
size_t bbman::Research::distCalc(irr::core::vector3d<irr::s32>const& p1,
irr::core::vector3d<irr::s32>const& p2)
{
int res1 = p1.X - p2.X;
int res2 = p1.Z - p2.Z;
if (res1 < 0) {
res1 *= -1;
}
if (res2 < 0) {
res2 *= -1;
}
return res1 + res2;
}
luabridge::LuaRef bbman::Research::vecToTable(irr::core::vector3d<irr::s32>const& vec)
{
luabridge::LuaRef pos = luabridge::newTable(this->_L);
pos["x"] = vec.X;
pos["y"] = vec.Z;
return pos;
}
irr::core::vector3d<irr::s32>const& bbman::Research::getAIPos(int numplayer)
{
IEntity *player = this->_board->getPlayerByID(numplayer);
if (player) {
return player->getPosInMap(this->_board->getScale());
}
throw(std::runtime_error("player " + std::to_string(numplayer) + " not found"));
}
irr::core::vector3d<irr::s32>const&
bbman::Research::getNearPlayer(irr::core::vector3d<irr::s32>const& ia)
{
std::vector<bbman::APlayer *>const& Players = this->_board->getPlayers();
size_t distmin = 1000;
size_t ret;
for (auto& it : Players) {
irr::core::vector3d<irr::s32> pos = it->getPosInMap(this->_board->getScale());
if ((distmin > (ret = distCalc(pos, ia))) && ((pos.X != ia.X) != (pos.Z != ia.Z))) {
distmin = ret;
this->_near = it->getPosInMap(this->_board->getScale());
}
}
return this->_near;
}
irr::core::vector3d<irr::s32>const&
bbman::Research::getNearPowerUPs(irr::core::vector3d<irr::s32>const& ia)
{
bbman::PowerUPs const& PowerUPs = this->_board->getPowerUPs();
std::list<bbman::IPowerUP *>const& powerUPsList = PowerUPs.getPowerUPs();
size_t distmin = 1000;
size_t ret;
for (auto& it : powerUPsList) {
irr::core::vector3d<irr::s32> pos = it->getPosInMap(this->_board->getScale());
if (distmin > (ret = distCalc(pos, ia))) {
distmin = ret;
this->_near = it->getPosInMap(this->_board->getScale());
}
}
return this->_near;
}
irr::core::vector3d<irr::s32>const&
bbman::Research::getNearBox(irr::core::vector3d<irr::s32>const& ia)
{
std::vector<bbman::IBlock *> Blocks = this->_board->getBlocks();
size_t distmin = 1000;
size_t ret;
for (auto& it : Blocks) {
if ((distmin > (ret = distCalc(it->getPosInMap(this->_board->getScale()), ia)))
&& !it->hasExplosed()) {
distmin = ret;
this->_near = it->getPosInMap(this->_board->getScale());
}
}
return this->_near;
}
irr::core::vector3d<irr::s32>const&
bbman::Research::getNearDBox(irr::core::vector3d<irr::s32>const& ia)
{
std::list<bbman::IBlock *> Blocks = this->_board->getDBlocks();
size_t distmin = 1000;
size_t ret;
for (auto& it : Blocks) {
if ((distmin > (ret = distCalc(it->getPosInMap(this->_board->getScale()), ia)))
&& !it->hasExplosed()) {
distmin = ret;
this->_near = it->getPosInMap(this->_board->getScale());
}
}
return this->_near;
}
bbman::APlayer * bbman::Research::getAI(int numplayer)
{
std::vector<bbman::APlayer *>const& Players = this->_board->getPlayers();
bbman::APlayer *ia;
for (auto& it : Players) {
if (it->getID() == (size_t)numplayer) {
ia = it;
}
}
if (ia && !ia->isAlive()) {
ia = NULL;
std::cerr << "ai not alive" << std::endl;
}
return ia;
}
bbman::Direction bbman::Research::checkNorthEast(irr::core::vector3d<irr::s32>const& pos, bbman::TrueAStar & trueA, int i, int j)
{
Map<bbman::Cell>const& map = this->_board->getMap();
if (((int)pos.X + j < (int)map.w) && ((int)pos.Z + i < (int)map.h) &&
(map.at(pos.X + j, pos.Z + i).id == ItemID::II_NONE)) {
if (!this->_board->isInExplosion(
irr::core::vector3d<irr::s32>(pos.X + j, 0, pos.Z + i))) {
trueA.reset();
trueA.compute(map, pos, irr::core::vector3d<irr::s32>(pos.X + j, 0, pos.Z + i));
if (trueA.getSize() != 0) {
return tools::StaticTools::getDirByCoord(pos, trueA.getNextResult());
}
}
}
return bbman::Direction::DIR_NONE;
}
bbman::Direction bbman::Research::checkSouthEast(irr::core::vector3d<irr::s32>const& pos, bbman::TrueAStar & trueA, int i, int j)
{
Map<bbman::Cell>const& map = this->_board->getMap();
if (((int)pos.X + j < (int)map.w) && ((int)pos.Z - i > 0) &&
(map.at(pos.X + j, pos.Z - i).id == ItemID::II_NONE)) {
if (!this->_board->isInExplosion(
irr::core::vector3d<irr::s32>(pos.X + j, 0, pos.Z - i))) {
trueA.reset();
trueA.compute(map, pos, irr::core::vector3d<irr::s32>(pos.X + j, 0, pos.Z - i));
if (trueA.getSize() != 0) {
return tools::StaticTools::getDirByCoord(pos, trueA.getNextResult());
}
}
}
return bbman::Direction::DIR_NONE;
}
bbman::Direction bbman::Research::checkNorthWest(irr::core::vector3d<irr::s32>const& pos, bbman::TrueAStar & trueA, int i, int j)
{
Map<bbman::Cell>const& map = this->_board->getMap();
if (((int)pos.X - j > 0) && ((int)pos.Z + i < (int)map.h) &&
(map.at(pos.X - j, pos.Z + i).id == ItemID::II_NONE)) {
if (!this->_board->isInExplosion(
irr::core::vector3d<irr::s32>(pos.X - j, 0, pos.Z + i))) {
trueA.reset();
trueA.compute(map, pos, irr::core::vector3d<irr::s32>(pos.X - j, 0, pos.Z + i));
if (trueA.getSize() != 0) {
return tools::StaticTools::getDirByCoord(pos, trueA.getNextResult());
}
}
}
return bbman::Direction::DIR_NONE;
}
bbman::Direction bbman::Research::checkSouthWest(irr::core::vector3d<irr::s32>const& pos, bbman::TrueAStar & trueA, int i, int j)
{
Map<bbman::Cell>const& map = this->_board->getMap();
if (((int)pos.X - j > 0) && ((int)pos.Z - i > 0) &&
(map.at(pos.X - j, pos.Z - i).id == ItemID::II_NONE)) {
if (!this->_board->isInExplosion(
irr::core::vector3d<irr::s32>(pos.X - j, 0, pos.Z - i))) {
trueA.reset();
trueA.compute(map, pos, irr::core::vector3d<irr::s32>(pos.X - j, 0, pos.Z - i));
if (trueA.getSize() != 0) {
return tools::StaticTools::getDirByCoord(pos, trueA.getNextResult());
}
}
}
return bbman::Direction::DIR_NONE;
}
bbman::Direction bbman::Research::findNearestSafeZone(irr::core::vector3d<irr::s32>const& pos)
{
bbman::TrueAStar trueA;
bbman::Direction ret;
int dir[4] = {0,1,2,3};
trueA.addBlockType(bbman::ItemID::II_BLOCK_INBRKABLE);
trueA.addBlockType(bbman::ItemID::II_BLOCK_BRKABLE);
std::random_shuffle(std::begin(dir), std::end(dir));
for (int k = 0; k < 10; k++) {
for (int i = 0; i < k; i++) {
for (int j = 0; j < k; j++) {
for (auto& it : dir) {
if ((ret = this->_checkers.at(it)(pos, trueA, i, j)) != bbman::Direction::DIR_NONE)
return (ret);
}
}
}
}
return bbman::Direction::DIR_NONE;
}
bbman::TrueAStar bbman::Research::getTrueA() const
{
return this->_trueA;
}
bbman::NeighborAStar bbman::Research::getNeighA() const
{
return this->_neighA;
}
| 30.579336
| 165
| 0.60975
|
Stephouuu
|
2aa980fad1466bdf6478d16d9bcfc6e13b9bd41a
| 692
|
hpp
|
C++
|
sprout/math/signbit.hpp
|
osyo-manga/Sprout
|
8885b115f739ef255530f772067475d3bc0dcef7
|
[
"BSL-1.0"
] | 1
|
2020-02-04T05:16:01.000Z
|
2020-02-04T05:16:01.000Z
|
sprout/math/signbit.hpp
|
jwakely/Sprout
|
a64938fad0a64608f22d39485bc55a1e0dc07246
|
[
"BSL-1.0"
] | null | null | null |
sprout/math/signbit.hpp
|
jwakely/Sprout
|
a64938fad0a64608f22d39485bc55a1e0dc07246
|
[
"BSL-1.0"
] | null | null | null |
#ifndef SPROUT_MATH_SIGNBIT_HPP
#define SPROUT_MATH_SIGNBIT_HPP
#include <type_traits>
#include <sprout/config.hpp>
#include <sprout/math/detail/config.hpp>
#include <sprout/type_traits/enabler_if.hpp>
namespace sprout {
namespace math {
namespace detail {
template<
typename FloatType,
typename sprout::enabler_if<std::is_floating_point<FloatType>::value>::type = sprout::enabler
>
inline SPROUT_CONSTEXPR int
signbit(FloatType x) {
return x < 0;
}
} // namespace detail
using NS_SPROUT_MATH_DETAIL::signbit;
} // namespace math
using sprout::math::signbit;
} // namespace sprout
#endif // #ifndef SPROUT_MATH_SIGNBIT_HPP
| 23.862069
| 98
| 0.710983
|
osyo-manga
|
2aaa5ac4465ddd0f6c9761459157b8d640b29a0f
| 1,581
|
cpp
|
C++
|
stack07.cpp
|
LuluFighting/DataStructAndAlgorithm
|
af8fe59a0bcf41c48034182de4e00bb91f9e411a
|
[
"MIT"
] | 1
|
2020-03-11T16:02:41.000Z
|
2020-03-11T16:02:41.000Z
|
stack07.cpp
|
LuluFighting/DataStructAndAlgorithm
|
af8fe59a0bcf41c48034182de4e00bb91f9e411a
|
[
"MIT"
] | null | null | null |
stack07.cpp
|
LuluFighting/DataStructAndAlgorithm
|
af8fe59a0bcf41c48034182de4e00bb91f9e411a
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <vector>
using std::vector;
//数组栈
class Stack{
public:
Stack(int size)
:_size(size),_index(0),_items(new int[size]())
{
std::cout << "having create a stack " << std::endl;
}
bool push(int item){
if(_index == _size){
return false;
}
_items[_index++] = item;
return true;
}
int pop(){
if(_index == 0){
return NULL;
}
return _items[--_index];
}
private:
int _size; //栈的大小
int _index; //目前的索引
int *_items;
};
struct LNode{
LNode(int val):_val(val),_next(NULL){}
int _val;
struct LNode* _next;
};
//链栈
class LinkStack{
public:
LinkStack(int size)
:_size(size),_count(0),_pHead(new LNode(0)){
std::cout << "having create linkstack" << std::endl;
}
bool push(int item){
if(_count==_size){
return false;
}
LNode* pNew = new LNode(item);
pNew->_next = _pHead->_next;
_pHead->_next = pNew;
_count++;
return true;
}
int pop(){
if(_count==0){
return NULL;
}
LNode* pLast = _pHead->_next;
_pHead->_next = pLast->_next;
int retVal = pLast->_val;
delete(pLast);
return retVal;
}
private:
int _size;
int _count;
LNode* _pHead;
};
int main() {
LinkStack a = LinkStack(10);
a.push(1);
a.push(3);
std::cout << a.pop() << std::endl;
std::cout << a.pop() << std::endl;
std::cout << a.pop() << std::endl;
return 0;
}
| 20.802632
| 60
| 0.510436
|
LuluFighting
|
2aab6c86af0b918717ca52bc87acc7d31ac73840
| 1,076
|
hpp
|
C++
|
src/rfx/compiler/Signal.hpp
|
JKot-Coder/RedRaven
|
b0f9a679c39e0d87bee60c7f4f202ca1a795eaa9
|
[
"BSD-3-Clause"
] | null | null | null |
src/rfx/compiler/Signal.hpp
|
JKot-Coder/RedRaven
|
b0f9a679c39e0d87bee60c7f4f202ca1a795eaa9
|
[
"BSD-3-Clause"
] | null | null | null |
src/rfx/compiler/Signal.hpp
|
JKot-Coder/RedRaven
|
b0f9a679c39e0d87bee60c7f4f202ca1a795eaa9
|
[
"BSD-3-Clause"
] | null | null | null |
#pragma once
namespace RR
{
namespace Rfx
{
enum class SignalType
{
Unexpected,
Unimplemented,
AssertFailure,
Unreachable,
InvalidOperation,
AbortCompilation,
};
void handleSignal(SignalType type, const U8String& message);
// clang-format off
#define RFX_UNEXPECTED(reason) \
handleSignal(SignalType::Unexpected, reason)
#define RFX_UNIMPLEMENTED_X(what) \
handleSignal(SignalType::Unimplemented, what)
#define RFX_UNREACHABLE(msg) \
handleSignal(SignalType::Unreachable, msg)
//TODO ?
#define RFX_ASSERT_FAILURE(msg) \
handleSignal(SignalType::AssertFailure, msg)
#define RFX_INVALID_OPERATION(msg) \
handleSignal(SignalType::InvalidOperation, msg)
#define RFX_ABORT_COMPILATION(msg) \
handleSignal(SignalType::AbortCompilation, msg)
// clang-format on
}
}
| 27.589744
| 68
| 0.567844
|
JKot-Coder
|
2ab2712909da74b138ba8aca26a880f009c4a7ff
| 3,344
|
cpp
|
C++
|
src/plugins/azoth/plugins/chathistory/storagethread.cpp
|
MellonQ/leechcraft
|
71cbb238d2dade56b3865278a6a8e6a58c217fc5
|
[
"BSL-1.0"
] | null | null | null |
src/plugins/azoth/plugins/chathistory/storagethread.cpp
|
MellonQ/leechcraft
|
71cbb238d2dade56b3865278a6a8e6a58c217fc5
|
[
"BSL-1.0"
] | null | null | null |
src/plugins/azoth/plugins/chathistory/storagethread.cpp
|
MellonQ/leechcraft
|
71cbb238d2dade56b3865278a6a8e6a58c217fc5
|
[
"BSL-1.0"
] | null | null | null |
/**********************************************************************
* LeechCraft - modular cross-platform feature rich internet client.
* Copyright (C) 2006-2014 Georg Rudoy
*
* Boost Software License - Version 1.0 - August 17th, 2003
*
* Permission is hereby granted, free of charge, to any person or organization
* obtaining a copy of the software and accompanying documentation covered by
* this license (the "Software") to use, reproduce, display, distribute,
* execute, and transmit the Software, and to prepare derivative works of the
* Software, and to permit third-parties to whom the Software is furnished to
* do so, all subject to the following:
*
* The copyright notices in the Software and this entire statement, including
* the above license grant, this restriction and the following disclaimer,
* must be included in all copies of the Software, in whole or in part, and
* all derivative works of the Software, unless such copies or derivative
* works are solely in the form of machine-executable object code generated by
* a source language processor.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
* SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
* FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
**********************************************************************/
#include "storagethread.h"
#include "storage.h"
#include "core.h"
#include <QTimer>
namespace LeechCraft
{
namespace Azoth
{
namespace ChatHistory
{
StorageThread::StorageThread (QObject *parent)
: QThread (parent)
{
}
Storage* StorageThread::GetStorage ()
{
return Storage_.get ();
}
void StorageThread::run ()
{
Storage_.reset (new Storage);
QTimer::singleShot (0,
this,
SLOT (connectSignals ()));
QThread::run ();
Storage_.reset ();
}
void StorageThread::connectSignals ()
{
connect (Storage_.get (),
SIGNAL (gotOurAccounts (const QStringList&)),
Core::Instance ().get (),
SIGNAL (gotOurAccounts (const QStringList&)),
Qt::QueuedConnection);
connect (Storage_.get (),
SIGNAL (gotUsersForAccount (const QStringList&, const QString&, const QStringList&)),
Core::Instance ().get (),
SIGNAL (gotUsersForAccount (const QStringList&, const QString&, const QStringList&)),
Qt::QueuedConnection);
connect (Storage_.get (),
SIGNAL (gotChatLogs (const QString&, const QString&, int, int, const QVariant&)),
Core::Instance ().get (),
SIGNAL (gotChatLogs (const QString&, const QString&, int, int, const QVariant&)),
Qt::QueuedConnection);
connect (Storage_.get (),
SIGNAL (gotSearchPosition (const QString&, const QString&, int)),
Core::Instance ().get (),
SIGNAL (gotSearchPosition (const QString&, const QString&, int)),
Qt::QueuedConnection);
connect (Storage_.get (),
SIGNAL (gotDaysForSheet (QString, QString, int, int, QList<int>)),
Core::Instance ().get (),
SIGNAL (gotDaysForSheet (QString, QString, int, int, QList<int>)),
Qt::QueuedConnection);
}
}
}
}
| 35.574468
| 89
| 0.686005
|
MellonQ
|
2ab709282cd25bc805e687ba40a60e78c8d669da
| 111
|
cpp
|
C++
|
Project2/test.cpp
|
dss875914213/dll_demo
|
31efea0135f39d9592b5769f6c09e7bb5e8a101e
|
[
"MIT"
] | null | null | null |
Project2/test.cpp
|
dss875914213/dll_demo
|
31efea0135f39d9592b5769f6c09e7bb5e8a101e
|
[
"MIT"
] | null | null | null |
Project2/test.cpp
|
dss875914213/dll_demo
|
31efea0135f39d9592b5769f6c09e7bb5e8a101e
|
[
"MIT"
] | null | null | null |
#include "test.h"
int Add(int a, int b)
{
return a + b;
}
int Min(int a, int b)
{
return a > b ? b : a;
}
| 8.538462
| 22
| 0.522523
|
dss875914213
|
2abeb5a7e5e840da07615aa4d784fdd1aa0253ea
| 6,070
|
cc
|
C++
|
inet/src/inet/applications/tcpapp/TcpBasicClientApp.cc
|
ntanetani/quisp
|
003f85746266d2eb62c66883e5b965b654672c70
|
[
"BSD-3-Clause"
] | null | null | null |
inet/src/inet/applications/tcpapp/TcpBasicClientApp.cc
|
ntanetani/quisp
|
003f85746266d2eb62c66883e5b965b654672c70
|
[
"BSD-3-Clause"
] | null | null | null |
inet/src/inet/applications/tcpapp/TcpBasicClientApp.cc
|
ntanetani/quisp
|
003f85746266d2eb62c66883e5b965b654672c70
|
[
"BSD-3-Clause"
] | 1
|
2021-07-02T13:32:40.000Z
|
2021-07-02T13:32:40.000Z
|
//
// Copyright (C) 2004 Andras Varga
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program; if not, see <http://www.gnu.org/licenses/>.
//
#include "inet/applications/tcpapp/TcpBasicClientApp.h"
#include "inet/applications/tcpapp/GenericAppMsg_m.h"
#include "inet/common/ModuleAccess.h"
#include "inet/common/lifecycle/ModuleOperations.h"
#include "inet/common/packet/Packet.h"
#include "inet/common/TimeTag_m.h"
namespace inet {
#define MSGKIND_CONNECT 0
#define MSGKIND_SEND 1
Define_Module(TcpBasicClientApp);
TcpBasicClientApp::~TcpBasicClientApp()
{
cancelAndDelete(timeoutMsg);
}
void TcpBasicClientApp::initialize(int stage)
{
TcpAppBase::initialize(stage);
if (stage == INITSTAGE_LOCAL) {
numRequestsToSend = 0;
earlySend = false; // TBD make it parameter
WATCH(numRequestsToSend);
WATCH(earlySend);
startTime = par("startTime");
stopTime = par("stopTime");
if (stopTime >= SIMTIME_ZERO && stopTime < startTime)
throw cRuntimeError("Invalid startTime/stopTime parameters");
timeoutMsg = new cMessage("timer");
}
}
void TcpBasicClientApp::handleStartOperation(LifecycleOperation *operation)
{
simtime_t now = simTime();
simtime_t start = std::max(startTime, now);
if (timeoutMsg && ((stopTime < SIMTIME_ZERO) || (start < stopTime) || (start == stopTime && startTime == stopTime))) {
timeoutMsg->setKind(MSGKIND_CONNECT);
scheduleAt(start, timeoutMsg);
}
}
void TcpBasicClientApp::handleStopOperation(LifecycleOperation *operation)
{
cancelEvent(timeoutMsg);
if (socket.getState() == TcpSocket::CONNECTED || socket.getState() == TcpSocket::CONNECTING || socket.getState() == TcpSocket::PEER_CLOSED)
close();
}
void TcpBasicClientApp::handleCrashOperation(LifecycleOperation *operation)
{
cancelEvent(timeoutMsg);
if (operation->getRootModule() != getContainingNode(this))
socket.destroy();
}
void TcpBasicClientApp::sendRequest()
{
long requestLength = par("requestLength");
long replyLength = par("replyLength");
if (requestLength < 1)
requestLength = 1;
if (replyLength < 1)
replyLength = 1;
const auto& payload = makeShared<GenericAppMsg>();
Packet *packet = new Packet("data");
payload->setChunkLength(B(requestLength));
payload->setExpectedReplyLength(B(replyLength));
payload->setServerClose(false);
payload->addTag<CreationTimeTag>()->setCreationTime(simTime());
packet->insertAtBack(payload);
EV_INFO << "sending request with " << requestLength << " bytes, expected reply length " << replyLength << " bytes,"
<< "remaining " << numRequestsToSend - 1 << " request\n";
sendPacket(packet);
}
void TcpBasicClientApp::handleTimer(cMessage *msg)
{
switch (msg->getKind()) {
case MSGKIND_CONNECT:
connect(); // active OPEN
// significance of earlySend: if true, data will be sent already
// in the ACK of SYN, otherwise only in a separate packet (but still
// immediately)
if (earlySend)
sendRequest();
break;
case MSGKIND_SEND:
sendRequest();
numRequestsToSend--;
// no scheduleAt(): next request will be sent when reply to this one
// arrives (see socketDataArrived())
break;
default:
throw cRuntimeError("Invalid timer msg: kind=%d", msg->getKind());
}
}
void TcpBasicClientApp::socketEstablished(TcpSocket *socket)
{
TcpAppBase::socketEstablished(socket);
// determine number of requests in this session
numRequestsToSend = par("numRequestsPerSession");
if (numRequestsToSend < 1)
numRequestsToSend = 1;
// perform first request if not already done (next one will be sent when reply arrives)
if (!earlySend)
sendRequest();
numRequestsToSend--;
}
void TcpBasicClientApp::rescheduleOrDeleteTimer(simtime_t d, short int msgKind)
{
cancelEvent(timeoutMsg);
if (stopTime < SIMTIME_ZERO || d < stopTime) {
timeoutMsg->setKind(msgKind);
scheduleAt(d, timeoutMsg);
}
else {
delete timeoutMsg;
timeoutMsg = nullptr;
}
}
void TcpBasicClientApp::socketDataArrived(TcpSocket *socket, Packet *msg, bool urgent)
{
TcpAppBase::socketDataArrived(socket, msg, urgent);
if (numRequestsToSend > 0) {
EV_INFO << "reply arrived\n";
if (timeoutMsg) {
simtime_t d = simTime() + par("thinkTime");
rescheduleOrDeleteTimer(d, MSGKIND_SEND);
}
}
else if (socket->getState() != TcpSocket::LOCALLY_CLOSED) {
EV_INFO << "reply to last request arrived, closing session\n";
close();
}
}
void TcpBasicClientApp::close()
{
TcpAppBase::close();
cancelEvent(timeoutMsg);
}
void TcpBasicClientApp::socketClosed(TcpSocket *socket)
{
TcpAppBase::socketClosed(socket);
// start another session after a delay
if (timeoutMsg) {
simtime_t d = simTime() + par("idleInterval");
rescheduleOrDeleteTimer(d, MSGKIND_CONNECT);
}
}
void TcpBasicClientApp::socketFailure(TcpSocket *socket, int code)
{
TcpAppBase::socketFailure(socket, code);
// reconnect after a delay
if (timeoutMsg) {
simtime_t d = simTime() + par("reconnectInterval");
rescheduleOrDeleteTimer(d, MSGKIND_CONNECT);
}
}
} // namespace inet
| 29.609756
| 143
| 0.667381
|
ntanetani
|
2ac4e38de2a487099d74701a368830a7c975d0cd
| 9,439
|
cpp
|
C++
|
ICC_interface/ICC_interface/Control.cpp
|
ArminPCM/GolfBall-Logo-Recognition
|
b03896c5b0d0f54dbdd06896b741509968ba02f3
|
[
"Unlicense"
] | null | null | null |
ICC_interface/ICC_interface/Control.cpp
|
ArminPCM/GolfBall-Logo-Recognition
|
b03896c5b0d0f54dbdd06896b741509968ba02f3
|
[
"Unlicense"
] | null | null | null |
ICC_interface/ICC_interface/Control.cpp
|
ArminPCM/GolfBall-Logo-Recognition
|
b03896c5b0d0f54dbdd06896b741509968ba02f3
|
[
"Unlicense"
] | null | null | null |
#include "stdafx.h"
#include "ControlWindow.h"
#include "OptionsWindow.h"
#include "StatisticsWindow.h"
#include "SnapshotWindow.h"
namespace ICC_interface
{
const wchar_t* settingFile = L"settings.bin";
namespace golfTransmissionConsts
{
const int maximgwidth = 2048;
const int maximgheight = 1088;
const int imgsOffset1 = sizeof(golfTransmission);
const int imgsOffset2 = imgsOffset1 + maximgwidth*maximgheight*3;
const int imgsOffset3 = imgsOffset2 + maximgwidth*maximgheight*3;
const int imgsOffset4 = imgsOffset3 + maximgwidth*maximgheight*3;
const int fileSize = imgsOffset4 + maximgwidth*maximgheight*3;
const int optionsOffset = offsetof(golfTransmission,sift_thresh);
const int optionsSize = imgsOffset1-optionsOffset;
const int controlsOffset = offsetof(golfTransmission,render_img1);
const int controlsSize = optionsOffset-controlsOffset;
const int imgsizeoffset = offsetof(golfTransmission, img_width1);
const int imgsizesize = optionsOffset-imgsizeoffset;
}
void LoadImage(unsigned char* ptr, PictureBox^ box, int offset, int width, int height)
{
Imaging::PixelFormat format = Imaging::PixelFormat::Format24bppRgb;
Rectangle rect(0,0,width,height);
Bitmap^ bitmap = gcnew Bitmap(width,height,format);
Imaging::BitmapData^ data = bitmap->LockBits(rect,Imaging::ImageLockMode::WriteOnly,bitmap->PixelFormat);
memcpy((void*)data->Scan0, ptr+offset, width*height*3);
bitmap->UnlockBits(data);
box->Image = bitmap;
}
ControlWindow::ControlWindow(void)
{
InitializeComponent();
statisticsForm = gcnew StatisticsWindow();
optionsForm = gcnew OptionsWindow();
newballForm = gcnew SnapshotWindow();
golfData = new golfTransmission;
optionsForm->golfData = golfData;
filePipeName = L"golfDataPipe";
mutexName = L"golfDataMutex";
try{
FileStream^ datafile = File::Open(gcnew String(settingFile), FileMode::OpenOrCreate);
//if(datafile->Length<golfTransmissionConsts::optionsSize)
//{
// golfData->setDefaults();
//}
//else
{
array<Byte>^ bytes = gcnew array<Byte>(golfTransmissionConsts::optionsSize);
datafile->Read(bytes, 0, golfTransmissionConsts::optionsSize);
IntPtr dst((char*)golfData+golfTransmissionConsts::optionsOffset);
System::Runtime::InteropServices::Marshal::Copy(bytes, 0, dst, golfTransmissionConsts::optionsSize);
}
datafile->Close();
}
catch(Exception^ e){MessageBox::Show(this,L"Error reading options file: " + e->Message); golfData->setDefaults();}
}
bool ControlWindow::Init()
{
try{filePipe = MemoryMappedFile::CreateNew(filePipeName, golfTransmissionConsts::fileSize, MemoryMappedFileAccess::ReadWrite);}
catch(Exception^)
{MessageBox::Show(this,L"Memory mapped file is still in use. Make sure all instances of this are closed."); return false;}
mutex = gcnew Mutex(false, mutexName);
MemoryMappedViewStream^ fileStream = filePipe->CreateViewStream();
unsigned char* dataptr;
fileStream->SafeMemoryMappedViewHandle->AcquirePointer(dataptr);
memset(dataptr, 0, golfTransmissionConsts::fileSize);
fileStream->SafeMemoryMappedViewHandle->ReleasePointer();
fileStream->Close();
return true;
}
//Process Data Thread
void ControlWindow::threadWorker()
{
try{
if(!mutex->WaitOne(100)) return;
MemoryMappedViewStream^ fileStream = filePipe->CreateViewStream();
unsigned char* dataptr;
fileStream->SafeMemoryMappedViewHandle->AcquirePointer(dataptr);
golfData->logoClk = dataptr[offsetof(golfTransmission, logoClk)];
dataptr[offsetof(golfTransmission, logoClk)] = 0;
golfData->imagesClk = dataptr[offsetof(golfTransmission, imagesClk)];
dataptr[offsetof(golfTransmission, imagesClk)] = 0;
if(golfData->optionsClk)
{
golfData->optionsClk = 0;
dataptr[offsetof(golfTransmission, optionsClk)] = 1;
memcpy(dataptr+golfTransmissionConsts::optionsOffset, (char*)golfData+golfTransmissionConsts::optionsOffset, golfTransmissionConsts::optionsSize);
}
if(golfData->controlsClk)
{
golfData->controlsClk = 0;
dataptr[offsetof(golfTransmission, controlsClk)] = 1;
memcpy(dataptr+golfTransmissionConsts::controlsOffset, (char*)golfData+golfTransmissionConsts::controlsOffset, golfTransmissionConsts::controlsSize);
}
if(golfData->logoClk)
{
if(golfData->logoClk - 1>0)
statisticsForm->addBall(golfData->logoClk - 1);
statisticsForm->save();
golfData->logoClk = 0;
}
if(golfData->imagesClk)
{
golfData->imagesClk = 0;
memcpy((char*)golfData+golfTransmissionConsts::imgsizeoffset, dataptr+golfTransmissionConsts::imgsizeoffset, golfTransmissionConsts::imgsizesize);
if(golfData->render_img1)
{
LoadImage(dataptr, pictureBox1, golfTransmissionConsts::imgsOffset1, golfData->img_width1, golfData->img_height1);
}
if(golfData->render_img2)
{
LoadImage(dataptr, pictureBox2, golfTransmissionConsts::imgsOffset2, golfData->img_width2, golfData->img_height2);
}
if(golfData->render_img3)
{
LoadImage(dataptr, pictureBox3, golfTransmissionConsts::imgsOffset3, golfData->img_width3, golfData->img_height3);
}
if(golfData->render_img4)
{
LoadImage(dataptr, newballForm->BallPicture, golfTransmissionConsts::imgsOffset4, golfData->img_width4, golfData->img_height4);
}
}
fileStream->SafeMemoryMappedViewHandle->ReleasePointer();
fileStream->Close();
mutex->ReleaseMutex();
}
catch(Exception^ e)
{
MessageBox::Show(this, e->Message);
mutex->ReleaseMutex();
return;
}
}
//Process halted
System::Void ControlWindow::sorterStopped(System::Object^ sender, System::EventArgs^ e) {
this->statusLabel->ForeColor = System::Drawing::Color::Red;
this->statusLabel->Text = L"Stopped";
this->runButton->Text = L"Run";
}
//
System::Void ControlWindow::SetHDStream(bool should)
{
golfData->controlsClk = 1;
golfData->render_img4 = should;
}
//Buttons
System::Void ControlWindow::runButtonPress(System::Object^ sender, System::EventArgs^ e) {
bool running = false;
try
{
running = !this->golfSorterProcess->HasExited;
}
catch(Exception^)
{}
if(running)
{
//Stop the process
this->golfSorterProcess->Kill();
this->runButton->Text = L"Run";
}
else
{
//Start the process
try
{
golfData->controlsClk = 1;
golfData->optionsClk = 1;
this->golfSorterProcess->StartInfo->Arguments = filePipeName + L" " + mutexName;
this->golfSorterProcess->Start();
this->statusLabel->ForeColor = System::Drawing::Color::Green;
this->statusLabel->Text = L"Running";
this->runButton->Text = L"Stop";
}
catch(Exception^ e)
{
MessageBox::Show(this, e->Message);
}
}
}
System::Void ControlWindow::optionsButtonPress(System::Object^ sender, System::EventArgs^ e) {
if(!optionsForm->Visible)
optionsForm->Show(this);
}
System::Void ControlWindow::statisticButtonPress(System::Object^ sender, System::EventArgs^ e) {
if(!statisticsForm->Visible)
{
statisticsForm->Show(this);
}
}
System::Void ControlWindow::newballPress(System::Object^ sender, System::EventArgs^ e) {
if(!newballForm->Visible)
{
SetHDStream(true);
newballForm->Show(this);
}
}
//Check Boxes here
System::Void ControlWindow::showCam1Click(System::Object^ sender, System::EventArgs^ e) {
if(this->showCam1->Checked)
{
golfData->render_img1 = 1;
}
else
{
golfData->render_img1 = 0;
pictureBox1->Image = gcnew Bitmap(1,1);
}
golfData->controlsClk = 1;
}
System::Void ControlWindow::showCam2Click(System::Object^ sender, System::EventArgs^ e) {
if(this->showCam2->Checked)
{
golfData->render_img2 = 1;
}
else
{
golfData->render_img2 = 0;
pictureBox2->Image = gcnew Bitmap(1,1);
}
golfData->controlsClk = 1;
}
System::Void ControlWindow::showCam3Click(System::Object^ sender, System::EventArgs^ e) {
if(this->showCam3->Checked)
{
golfData->render_img3 = 1;
}
else
{
golfData->render_img3 = 0;
pictureBox3->Image = gcnew Bitmap(1,1);
}
golfData->controlsClk = 1;
}
System::Void ControlWindow::showlogosPress(System::Object^ sender, System::EventArgs^ e) {
if(this->showLogos->Checked)
{
golfData->render_data = 1;
}
else
{
golfData->render_data = 0;
}
golfData->controlsClk = 1;
}
System::Void ControlWindow::ChangeMask(System::Object^ sender, System::EventArgs^ e) {
if(radioButton1->Checked)
golfData->render_mask = 0;
else if(radioButton2->Checked)
golfData->render_mask = 1;
else if(radioButton3->Checked)
golfData->render_mask = 2;
golfData->controlsClk = 1;
}
System::Void ControlWindow::sortBrands(System::Object^ sender, System::EventArgs^ e) {
if(this->sortBrandsCB->Checked)
{
golfData->sort_brands = 1;
}
else
{
golfData->sort_brands = 0;
}
golfData->controlsClk = 1;
}
System::Void ControlWindow::sortModels(System::Object^ sender, System::EventArgs^ e) {
if(this->sortModelsCB->Checked)
{
golfData->sort_models = 1;
}
else
{
golfData->sort_models = 0;
}
golfData->controlsClk = 1;
}
}
| 30.253205
| 154
| 0.687679
|
ArminPCM
|
2ac81f8158fc864fde09d0c5b551d1c5b071934b
| 2,703
|
hpp
|
C++
|
include/gSparse/ER/Policy/ExactERJacobiCG.hpp
|
As-12/gSparse
|
66c7d60544565d4bdafbffa0ba08d62db620f9d1
|
[
"MIT"
] | 6
|
2018-09-14T09:38:12.000Z
|
2021-12-11T13:03:55.000Z
|
include/gSparse/ER/Policy/ExactERJacobiCG.hpp
|
As-12/gSparse
|
66c7d60544565d4bdafbffa0ba08d62db620f9d1
|
[
"MIT"
] | null | null | null |
include/gSparse/ER/Policy/ExactERJacobiCG.hpp
|
As-12/gSparse
|
66c7d60544565d4bdafbffa0ba08d62db620f9d1
|
[
"MIT"
] | 1
|
2021-12-11T13:03:58.000Z
|
2021-12-11T13:03:58.000Z
|
// Copyright (C) 2018 Thanaphon Chavengsaksongkram <as12production@gmail.com>, He Sun <he.sun@ed.ac.uk>
// This file is subject to the license terms in the LICENSE file
// found in the top-level directory of this distribution.
#ifndef GSPARSE_ER_POLICY_EXACTERJACOBICG_HPP
#define GSPARSE_ER_POLICY_EXACTERJACOBICG_HPP
#include "../../Config.hpp"
#include <Eigen/Dense>
#include <Eigen/Sparse>
namespace gSparse
{
namespace ER
{
namespace Policy
{
/// \ingroup EffectiveResistance
///
/// This class implements Spectral Sparsifier by Effective Weight Sampling.
/// Adaptation from http://ccom.uprrp.edu/~ikoutis/SpectralAlgorithms.htm
/// The algorithm leverages Conjugated Graident with Jacobi preconditioner to solve linear system
///
class ExactERJacobiCG
{
protected:
/// This function calculates Effective Resistance and return computation status.
/// \param er A row matrix to receive the EffectiveResistance value
/// \param graph A std::shared_ptr<IGraph> object representing the graph to calculate resistance
/// \param eps Error tolerance for conjugated gradient. Default is 1.0f.
/// \param JLTol Tolerance for JL projection Matrix. Default is 0.5f. (See http://ccom.uprrp.edu/~ikoutis/SpectralAlgorithms.htm.)
/// \param maxIter Maximum iteration for conjugated gradient. Default is 300 iterations.
inline gSparse::COMPUTE_INFO _calculateER(
gSparse::PrecisionRowMatrix & er,
const gSparse::Graph & graph,
int maxIter = 300
)
{
er = gSparse::PrecisionRowMatrix::Zero(graph->GetEdgeCount(), 1);
for (int i = 0; i != graph->GetEdgeCount(); ++i)
{
Eigen::ConjugateGradient<gSparse::SparsePrecisionMatrix, Eigen::Lower | Eigen::Upper > cg;
cg.setMaxIterations(maxIter);
auto b = graph->GetIncidentMatrix().row(i);
cg.compute(graph->GetLaplacianMatrix());
Eigen::VectorXd x = cg.solve(b.transpose());
b.toDense();
er(i) = b.toDense() * x;
}
// Non finite number goes to zero
er = er.unaryExpr([](double v) { return std::isfinite(v)? v : 0.0; });
return gSparse::SUCCESSFUL;
}
};
}
}
}
#endif
| 45.05
| 146
| 0.559378
|
As-12
|
2acbc4abdd1548b347448e08f07c19af376088a6
| 2,707
|
cpp
|
C++
|
avs/vis_avs/g_avi.cpp
|
semiessessi/vis_avs
|
e99a3803e9de9032e0e6759963b2c2798f3443ef
|
[
"BSD-3-Clause"
] | 18
|
2020-07-30T11:55:23.000Z
|
2022-02-25T02:39:15.000Z
|
avs/vis_avs/g_avi.cpp
|
semiessessi/vis_avs
|
e99a3803e9de9032e0e6759963b2c2798f3443ef
|
[
"BSD-3-Clause"
] | 34
|
2021-01-13T02:02:12.000Z
|
2022-03-23T12:09:55.000Z
|
avs/vis_avs/g_avi.cpp
|
semiessessi/vis_avs
|
e99a3803e9de9032e0e6759963b2c2798f3443ef
|
[
"BSD-3-Clause"
] | 3
|
2021-03-18T12:53:58.000Z
|
2021-10-02T20:24:41.000Z
|
#include "g__lib.h"
#include "g__defs.h"
#include "c_avi.h"
#include "resource.h"
#include <windows.h>
#include <commctrl.h>
static void EnableWindows(HWND hwndDlg, C_THISCLASS* config)
{
EnableWindow(GetDlgItem(hwndDlg,IDC_PERSIST),config->adapt);
EnableWindow(GetDlgItem(hwndDlg,IDC_PERSIST_TITLE),config->adapt);
}
int win32_dlgproc_avi(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM)
{
C_THISCLASS* g_ConfigThis = (C_THISCLASS*)g_current_render;
switch (uMsg)
{
case WM_INITDIALOG:
SendDlgItemMessage(hwndDlg, IDC_PERSIST, TBM_SETRANGE, TRUE, MAKELONG(0, 32));
SendDlgItemMessage(hwndDlg, IDC_PERSIST, TBM_SETPOS, TRUE, g_ConfigThis->persist);
SendDlgItemMessage(hwndDlg, IDC_SPEED, TBM_SETTICFREQ, 50, 0);
SendDlgItemMessage(hwndDlg, IDC_SPEED, TBM_SETRANGE, TRUE, MAKELONG(0, 1000));
SendDlgItemMessage(hwndDlg, IDC_SPEED, TBM_SETPOS, TRUE, g_ConfigThis->speed);
if (g_ConfigThis->enabled) CheckDlgButton(hwndDlg,IDC_CHECK1,BST_CHECKED);
if (g_ConfigThis->blend) CheckDlgButton(hwndDlg,IDC_ADDITIVE,BST_CHECKED);
if (g_ConfigThis->blendavg) CheckDlgButton(hwndDlg,IDC_5050,BST_CHECKED);
if (g_ConfigThis->adapt) CheckDlgButton(hwndDlg,IDC_ADAPT,BST_CHECKED);
if (!g_ConfigThis->adapt && !g_ConfigThis->blend && !g_ConfigThis->blendavg) {
CheckDlgButton(hwndDlg,IDC_REPLACE,BST_CHECKED);
}
EnableWindows(hwndDlg, g_ConfigThis);
loadComboBox(GetDlgItem(hwndDlg,OBJ_COMBO),"*.AVI",g_ConfigThis->ascName);
return 1;
case WM_NOTIFY:
if (LOWORD(wParam) == IDC_PERSIST)
g_ConfigThis->persist = SendDlgItemMessage(hwndDlg, IDC_PERSIST, TBM_GETPOS, 0, 0);
if (LOWORD(wParam) == IDC_SPEED)
g_ConfigThis->speed = SendDlgItemMessage(hwndDlg, IDC_SPEED, TBM_GETPOS, 0, 0);
break;
case WM_COMMAND:
if ((LOWORD(wParam) == IDC_CHECK1) ||
(LOWORD(wParam) == IDC_ADDITIVE) ||
(LOWORD(wParam) == IDC_REPLACE) ||
(LOWORD(wParam) == IDC_ADAPT) ||
(LOWORD(wParam) == IDC_5050) )
{
g_ConfigThis->enabled=IsDlgButtonChecked(hwndDlg,IDC_CHECK1)?1:0;
g_ConfigThis->blend=IsDlgButtonChecked(hwndDlg,IDC_ADDITIVE)?1:0;
g_ConfigThis->blendavg=IsDlgButtonChecked(hwndDlg,IDC_5050)?1:0;
g_ConfigThis->adapt=IsDlgButtonChecked(hwndDlg,IDC_ADAPT)?1:0;
EnableWindows(hwndDlg, g_ConfigThis);
}
if (HIWORD(wParam) == CBN_SELCHANGE && LOWORD(wParam) == OBJ_COMBO) // handle clicks to combo box
{
int sel = SendDlgItemMessage(hwndDlg, OBJ_COMBO, CB_GETCURSEL, 0, 0);
if (sel != -1)
{
SendDlgItemMessage(hwndDlg, OBJ_COMBO, CB_GETLBTEXT, sel, (LPARAM)g_ConfigThis->ascName);
if (*(g_ConfigThis->ascName))
g_ConfigThis->loadAvi(g_ConfigThis->ascName);
}
}
return 0;
}
return 0;
}
| 38.671429
| 100
| 0.735131
|
semiessessi
|
2aceb1a1fbc5a319db71632b3e09e6478202f42c
| 406
|
cpp
|
C++
|
C++/Tutorial/30Days/14.cpp
|
gietal/HackerRank
|
66e88359022d02cf14a9cef5fc1d76946bb59c7d
|
[
"MIT"
] | null | null | null |
C++/Tutorial/30Days/14.cpp
|
gietal/HackerRank
|
66e88359022d02cf14a9cef5fc1d76946bb59c7d
|
[
"MIT"
] | null | null | null |
C++/Tutorial/30Days/14.cpp
|
gietal/HackerRank
|
66e88359022d02cf14a9cef5fc1d76946bb59c7d
|
[
"MIT"
] | null | null | null |
// Add your code here
Difference(const vector<int> e)
: elements(e) {
}
void computeDifference() {
maximumDifference = 0;
for(int i = 0; i < elements.size() - 1; ++i) {
for(int j = 0; j < elements.size(); ++j) {
maximumDifference = max(maximumDifference, abs(elements[i] - elements[j]));
}
}
}
| 29
| 92
| 0.470443
|
gietal
|
2ad0376b3ccd61f96c4d54acbefaec10122e35a2
| 3,043
|
cpp
|
C++
|
13_greedy_prob/7_weight_job_sch.cpp
|
ShyamNandanKumar/coding-ninja2
|
a43a21575342261e573f71f7d8eff0572f075a17
|
[
"MIT"
] | 11
|
2021-01-02T10:07:17.000Z
|
2022-03-16T00:18:06.000Z
|
13_greedy_prob/7_weight_job_sch.cpp
|
meyash/cp_master
|
316bf47db2a5b40891edd73cff834517993c3d2a
|
[
"MIT"
] | null | null | null |
13_greedy_prob/7_weight_job_sch.cpp
|
meyash/cp_master
|
316bf47db2a5b40891edd73cff834517993c3d2a
|
[
"MIT"
] | 5
|
2021-05-19T11:17:18.000Z
|
2021-09-16T06:23:31.000Z
|
/*
You are given N jobs where every job is represented as:
1.Start Time
2.Finish Time
3.Profit Associated
Find the maximum profit subset of jobs such that no two jobs in the subset overlap.
Input
The first line of input contains one integer denoting N.
Next N lines contains three space separated integers denoting the start time, finish time and the profit associated with the ith job.
Output
Output one integer, the maximum profit that can be achieved.
Constraints
1 ≤ N ≤ 10^6
1 ≤ ai, di, p ≤ 10^6
Sample Input
4
3 10 20
1 2 50
6 19 100
2 100 200
Sample Output
250
*/
#include<bits/stdc++.h>
using namespace std;
bool compare(int j1[],int j2[]){
return j1[1]<j2[1];
}
// binary search to find index
int find_prev(int n,int **in,int s,int e,int limit){
// base cases
if(s>e){
return -1;
}
if(s==e){
if(in[s][1]<=limit){
return s;
}else{
return -1;
}
}
int mid=(s+e)/2;
// found or less
if(in[mid][1]<=limit){
int index=find_prev(n,in,mid+1,e,limit);
if(index==-1){
return mid;
}
return index;
}
// big
return find_prev(n,in,s,mid-1,limit);
}
int max_profit(int n,int **in){
// first sort on basis of finishing time
sort(in,in+n,compare);
// for(int i=0;i<n;i++){
// cout<<in[i][0]<<" "<<in[i][1]<<" "<<in[i][2]<<endl;
// }
// create array for storing the max profit at each index
int dp[n];
// for every index find max value at that index
// use previously found values to calc current val
// for 0th index max profit will be value at 0th itself
dp[0]=in[0][2];
for(int i=1;i<n;i++){
// currrent items value may be the max
int possibleans1=dp[i-1];
// find max possible before current
// int possibleans2=0;
int possibleans2=in[i][2];
// finding latest previous posn of greater profit
// using simple method - O(n)
// for(int j=i-1;j>=0;j--){
// // if the times for jobs are not clashing, then find possible ans
// if(in[j][1]<=in[i][0]){
// // if its profit is greater than current max
// if(dp[j]>possibleans2){
// possibleans2=dp[j];
// break;
// }
// }
// }
// 0 = start, end = i-1, starting = in[i][0]
int poss_index=0;
poss_index=find_prev(n,in,0,i-1,in[i][0]);
// using binary search
// prev possible element not found
if(poss_index!=-1){
possibleans2+=dp[poss_index];
}
dp[i]=max(possibleans1,possibleans2);
// dp[i]=max(possibleans1,possibleans2+in[i][2]);
}
return dp[n-1];
}
int main()
{
int n;
cin>>n;
int **in=new int*[n];
for(int i=0;i<n;i++){
in[i]=new int[3];
}
for(int i=0;i<n;i++){
cin>>in[i][0]>>in[i][1]>>in[i][2];
}
cout<<max_profit(n,in)<<endl;
return 0;
}
| 24.739837
| 134
| 0.546172
|
ShyamNandanKumar
|
2ad17dd8d904775f1e7296b4eb519658aa26bcc4
| 5,242
|
cpp
|
C++
|
GameEngine/TestUserActor.cpp
|
csyonghe/GameEngine
|
1ac8174714a3a52e22a935f573121dd1ab0fa546
|
[
"MIT"
] | 60
|
2016-12-02T17:12:51.000Z
|
2022-01-23T09:23:19.000Z
|
GameEngine/TestUserActor.cpp
|
csyonghe/GameEngine
|
1ac8174714a3a52e22a935f573121dd1ab0fa546
|
[
"MIT"
] | 5
|
2016-11-14T21:18:57.000Z
|
2019-07-12T04:01:12.000Z
|
GameEngine/TestUserActor.cpp
|
csyonghe/GameEngine
|
1ac8174714a3a52e22a935f573121dd1ab0fa546
|
[
"MIT"
] | 11
|
2016-11-14T21:11:46.000Z
|
2020-09-10T07:29:01.000Z
|
#ifndef TEST_USER_ACTOR_H
#define TEST_USER_ACTOR_H
#include "Engine.h"
#include "Level.h"
#include "CoreLib/LibUI/LibUI.h"
#include "SystemWindow.h"
#include "RendererService.h"
using namespace GraphicsUI;
using namespace GameEngine;
using namespace VectorMath;
class TestUserActor : public Actor
{
private:
RefPtr<Drawable> boxDrawable;
RefPtr<SystemWindow> sysWindow;
Material material;
public:
virtual EngineActorType GetEngineType() override
{
return EngineActorType::Drawable;
}
virtual void RegisterUI(GraphicsUI::UIEntry * /*entry*/) override
{
sysWindow = Engine::Instance()->CreateSystemWindow(25);
sysWindow->SetClientHeight(600);
sysWindow->SetClientWidth(800);
sysWindow->SetText("Test User Control");
sysWindow->Show();
auto uiForm = sysWindow->GetUIEntry();
auto top = new Container(uiForm);
top->SetHeight(120);
top->DockStyle = GraphicsUI::Control::dsTop;
auto btnRed = new Button(top);
btnRed->SetText("Red");
btnRed->Posit(EM(1.0f), EM(1.5f), EM(3.0f), EM(1.5f));
btnRed->OnClick.Bind([this](UI_Base*)
{
material.SetVariable("solidColor", DynamicVariable(Vec3::Create(1.0f, 0.0f, 0.0f)));
});
auto btnBlue = new Button(top);
btnBlue->SetText("Blue");
btnBlue->Posit(EM(4.5f), EM(1.5f), EM(3.0f), EM(1.5f));
btnBlue->OnClick.Bind([this](UI_Base*)
{
material.SetVariable("solidColor", DynamicVariable(Vec3::Create(0.0f, 0.0f, 1.0f)));
});
auto cmb = new ComboBox(top);
cmb->Posit(EM(14.5f), EM(2.5f), EM(5.0f), EM(1.5f));
cmb->AddTextItem("item1");
cmb->AddTextItem("item2");
cmb->AddTextItem("item3");
cmb->AddTextItem("item4");
auto line = new Line(top);
line->EndCap = LineCap::Arrow;
line->BorderWidth = 5.0f;
line->BorderColor = Color(255, 202, 40, 255);
line->SetPoints((float)EM(8.0f), (float)EM(1.5f), (float)EM(14.0f), (float)EM(1.5f), 2.0f);
auto txt = GraphicsUI::CreateMultiLineTextBox(top);
txt->Posit(EM(20.0f), EM(0.5f), EM(12.0f), EM(4.0f));
auto slider = new ScrollBar(top);
slider->Posit(EM(1.0f), EM(3.5f), EM(6.5f), EM(1.0f));
slider->SetValue(0, 2000, 1000, 50);
slider->OnChanged.Bind([=](UI_Base*)
{
LocalTransform->values[12] = (slider->GetPosition() - 1000) * 0.2f;
});
auto container = new GraphicsUI::ScrollPanel(uiForm);
container->Posit(10, EM(5.0), EM(40.0f), EM(35.0f));
container->DockStyle = GraphicsUI::Control::dsFill;
auto updateContainer = [=](float zoom)
{
container->ClearChildren();
for (int i = 0; i < 100; i++)
for (int j = 0; j < 100; j++)
{
auto bezier = new BezierCurve(container);
bezier->SetPoints(Math::Max(1.0f, 5.0f * zoom), Vec2::Create(30.0f + i * 100, 200.0f + j * 60)*zoom, Vec2::Create(40.0f + i * 100, 120.0f + j * 60)*zoom, Vec2::Create(240.0f + i * 100, 280.0f + j * 60)*zoom, Vec2::Create(250.0f + i * 100, 200.0f + j * 60)*zoom);
bezier->StartCap = bezier->EndCap = LineCap::Arrow;
}
for (int i = 0; i < 100; i++)
for (int j = 0; j < 100; j++)
{
auto circle = new GraphicsUI::Ellipse(container);
circle->BorderColor = Color(255, 127, 0, 255);
circle->BorderWidth = 5.0f;
circle->FontColor = Color(255, 255, 255, 255);
circle->Posit((int)((140 + i * 140)*zoom), (int)((140 + j * 140)*zoom), (int)(60 * zoom), (int)(60 * zoom));
circle->OnMouseEnter.Bind([=](UI_Base*)
{
circle->FontColor = Color(255, 255, 0, 255);
});
circle->OnMouseLeave.Bind([=](UI_Base*) {circle->FontColor = Color(255, 255, 255, 255); });
}
container->UpdateLayout();
};
updateContainer(1.0f);
container->EnableZoom = true;
container->OnZoom.Bind([=](ZoomEventArgs & e) {updateContainer(e.VerticalScale); });
uiForm->SizeChanged();
Engine::Instance()->GetInputDispatcher()->BindActionHandler("TestUserCtrl", [=](String, ActionInput)
{
sysWindow->SetVisible(true);
sysWindow->Show();
return true;
});
}
virtual void OnLoad() override
{
Actor::OnLoad();
material = *Engine::Instance()->GetLevel()->LoadMaterial("SolidColor.material");
}
virtual void OnUnload() override
{
Actor::OnUnload();
}
virtual void GetDrawables(const GetDrawablesParameter & param) override
{
if (!boxDrawable)
{
Mesh boxMesh = Mesh::CreateBox(VectorMath::Vec3::Create(-30.0f, 0.0f, -30.0f), VectorMath::Vec3::Create(30.0, 80.0f, 30.0f));
boxDrawable = param.rendererService->CreateStaticDrawable(&boxMesh, 0, &material);
}
if (boxDrawable)
{
boxDrawable->UpdateTransformUniform(*LocalTransform);
param.sink->AddDrawable(boxDrawable.Ptr());
}
}
};
void RegisterTestUserActor()
{
Engine::Instance()->RegisterActorClass("TestUser", []() {return new TestUserActor(); });
}
#endif
| 35.90411
| 282
| 0.585464
|
csyonghe
|
2ada44ee5b1e2e14e1a78d03268b78fcd27ce895
| 3,454
|
hpp
|
C++
|
libcaf_core/caf/make_source_result.hpp
|
v2nero/actor-framework
|
c2f811809143d32c598471a20363238b0882a761
|
[
"BSL-1.0",
"BSD-3-Clause"
] | 1
|
2020-07-16T19:01:52.000Z
|
2020-07-16T19:01:52.000Z
|
libcaf_core/caf/make_source_result.hpp
|
Boubou818/actor-framework
|
da90ef78b26da5d225f039072e616da415c48494
|
[
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null |
libcaf_core/caf/make_source_result.hpp
|
Boubou818/actor-framework
|
da90ef78b26da5d225f039072e616da415c48494
|
[
"BSL-1.0",
"BSD-3-Clause"
] | 1
|
2021-02-19T11:25:15.000Z
|
2021-02-19T11:25:15.000Z
|
/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright 2011-2018 Dominik Charousset *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#pragma once
#include "caf/fwd.hpp"
#include "caf/stream_slot.hpp"
#include "caf/stream_source.hpp"
#include "caf/detail/implicit_conversions.hpp"
namespace caf {
/// Returns a stream source with the slot ID of its first outbound path.
template <class DownstreamManager, class... Ts>
struct make_source_result {
// -- member types -----------------------------------------------------------
/// Type of a single element.
using output_type = typename DownstreamManager::output_type;
/// Fully typed stream manager as returned by `make_source`.
using source_type = stream_source<DownstreamManager>;
/// Pointer to a fully typed stream manager.
using source_ptr_type = intrusive_ptr<source_type>;
/// The return type for `scheduled_actor::make_source`.
using output_stream_type = output_stream<output_type, Ts...>;
// -- constructors, destructors, and assignment operators --------------------
make_source_result() noexcept : slot_(0) {
// nop
}
make_source_result(stream_slot slot, source_ptr_type ptr) noexcept
: slot_(slot),
ptr_(std::move(ptr)) {
// nop
}
make_source_result(make_source_result&&) = default;
make_source_result(const make_source_result&) = default;
make_source_result& operator=(make_source_result&&) = default;
make_source_result& operator=(const make_source_result&) = default;
// -- conversion operators ---------------------------------------------------
inline operator output_stream_type() const noexcept {
return {};
}
// -- properties -------------------------------------------------------------
inline stream_slot outbound_slot() const noexcept {
return slot_;
}
inline source_ptr_type& ptr() noexcept {
return ptr_;
}
inline const source_ptr_type& ptr() const noexcept {
return ptr_;
}
private:
stream_slot slot_;
source_ptr_type ptr_;
};
/// @relates make_source_result
template <class DownstreamManager, class... Ts>
using make_source_result_t =
make_source_result<DownstreamManager, detail::strip_and_convert_t<Ts>...>;
} // namespace caf
| 36.357895
| 80
| 0.505501
|
v2nero
|
2adae3809de644fd7832ebcbc335df751e1be204
| 585
|
cpp
|
C++
|
voj/contest/418207/F.cpp
|
TheBadZhang/OJ
|
b5407f2483aa630068343b412ecaf3a9e3303f7e
|
[
"Apache-2.0"
] | 1
|
2020-07-22T16:54:07.000Z
|
2020-07-22T16:54:07.000Z
|
voj/contest/418207/F.cpp
|
TheBadZhang/OJ
|
b5407f2483aa630068343b412ecaf3a9e3303f7e
|
[
"Apache-2.0"
] | 1
|
2018-05-12T12:53:06.000Z
|
2018-05-12T12:53:06.000Z
|
voj/contest/418207/F.cpp
|
TheBadZhang/OJ
|
b5407f2483aa630068343b412ecaf3a9e3303f7e
|
[
"Apache-2.0"
] | null | null | null |
#include <iostream>
long long F (long long n) {
if (n == 0) {
return 0;
} else if (n % 10) {
return n%10;
} else {
return F(n/10);
}
}
long long ans;
void S(long long l, long long r) {
if (r - 1 < 9) {
for (int i = 1; i <= r; ++i) {
ans += F(i);
}
return ;
}
while (l % 10) {
ans += F(l);
++l;
}
while (r % 10) {
ans += F(r);
--r;
}
ans += 45*(r-l)/10;
S(l/10,r/10);
}
int main () {
long long p, q;
while (std::cin >> p >> q) {
if (p == -1 && q == -1) {
break;
}
ans = 0;
S(p, q);
std::cout << ans << std::endl;
}
return 0;
}
| 11.938776
| 34
| 0.432479
|
TheBadZhang
|
2adfd40c1074f0fca553eb7419662220dedd05c3
| 13,330
|
cpp
|
C++
|
src/Services/RenderService/RenderTextureService.cpp
|
irov/Mengine
|
b76e9f8037325dd826d4f2f17893ac2b236edad8
|
[
"MIT"
] | 39
|
2016-04-21T03:25:26.000Z
|
2022-01-19T14:16:38.000Z
|
src/Services/RenderService/RenderTextureService.cpp
|
irov/Mengine
|
b76e9f8037325dd826d4f2f17893ac2b236edad8
|
[
"MIT"
] | 23
|
2016-06-28T13:03:17.000Z
|
2022-02-02T10:11:54.000Z
|
src/Services/RenderService/RenderTextureService.cpp
|
irov/Mengine
|
b76e9f8037325dd826d4f2f17893ac2b236edad8
|
[
"MIT"
] | 14
|
2016-06-22T20:45:37.000Z
|
2021-07-05T12:25:19.000Z
|
#include "RenderTextureService.h"
#include "Interface/WatchdogServiceInterface.h"
#include "Interface/PrefetcherServiceInterface.h"
#include "Interface/GraveyardServiceInterface.h"
#include "Interface/ConfigServiceInterface.h"
#include "Interface/CodecServiceInterface.h"
#include "Interface/EnumeratorServiceInterface.h"
#include "Interface/NotificationServiceInterface.h"
#include "Interface/RenderSystemInterface.h"
#include "RenderTexture.h"
#include "DecoderRenderImageProvider.h"
#include "DecoderRenderImageLoader.h"
#include "Kernel/FactoryPool.h"
#include "Kernel/FactoryPoolWithListener.h"
#include "Kernel/AssertionFactory.h"
#include "Kernel/AssertionMemoryPanic.h"
#include "Kernel/ConstStringHelper.h"
#include "Kernel/FileStreamHelper.h"
#include "Kernel/PixelFormatHelper.h"
#include "Kernel/FileGroupHelper.h"
#include "Kernel/Logger.h"
#include "Kernel/DocumentHelper.h"
#include "stdex/memorycopy.h"
//////////////////////////////////////////////////////////////////////////
SERVICE_FACTORY( RenderTextureService, Mengine::RenderTextureService );
//////////////////////////////////////////////////////////////////////////
namespace Mengine
{
//////////////////////////////////////////////////////////////////////////
RenderTextureService::RenderTextureService()
{
}
//////////////////////////////////////////////////////////////////////////
RenderTextureService::~RenderTextureService()
{
}
//////////////////////////////////////////////////////////////////////////
bool RenderTextureService::_initializeService()
{
m_factoryRenderTexture = Helper::makeFactoryPoolWithListener<RenderTexture, 128>( this, &RenderTextureService::onRenderTextureDestroy_, MENGINE_DOCUMENT_FACTORABLE );
m_factoryDecoderRenderImageProvider = Helper::makeFactoryPool<DecoderRenderImageProvider, 128>( MENGINE_DOCUMENT_FACTORABLE );
m_factoryDecoderRenderImageLoader = Helper::makeFactoryPool<DecoderRenderImageLoader, 128>( MENGINE_DOCUMENT_FACTORABLE );
uint32_t TextureHashTableSize = CONFIG_VALUE( "Engine", "TextureHashTableSize", 1024 * 8 );
m_textures.reserve( TextureHashTableSize );
return true;
}
//////////////////////////////////////////////////////////////////////////
void RenderTextureService::_finalizeService()
{
for( MapRenderTextureEntry::const_iterator
it = m_textures.begin(),
it_end = m_textures.end();
it != it_end;
++it )
{
const MapRenderTextureEntry::value_type & value = *it;
RenderTextureInterface * texture = value.element;
texture->release();
}
m_textures.clear();
MENGINE_ASSERTION_FACTORY_EMPTY( m_factoryRenderTexture );
MENGINE_ASSERTION_FACTORY_EMPTY( m_factoryDecoderRenderImageProvider );
MENGINE_ASSERTION_FACTORY_EMPTY( m_factoryDecoderRenderImageLoader );
m_factoryRenderTexture = nullptr;
m_factoryDecoderRenderImageProvider = nullptr;
m_factoryDecoderRenderImageLoader = nullptr;
}
//////////////////////////////////////////////////////////////////////////
bool RenderTextureService::hasTexture( const FileGroupInterfacePtr & _fileGroup, const FilePath & _filePath, RenderTextureInterfacePtr * const _texture ) const
{
const ConstString & fileGroupName = _fileGroup->getName();
const RenderTextureInterface * texture = m_textures.find( fileGroupName, _filePath );
if( texture == nullptr )
{
if( _texture != nullptr )
{
*_texture = nullptr;
}
return false;
}
if( _texture != nullptr )
{
*_texture = texture;
}
return true;
}
//////////////////////////////////////////////////////////////////////////
RenderTextureInterfacePtr RenderTextureService::getTexture( const FileGroupInterfacePtr & _fileGroup, const FilePath & _filePath ) const
{
const ConstString & fileGroupName = _fileGroup->getName();
const RenderTextureInterface * texture = m_textures.find( fileGroupName, _filePath );
if( texture == nullptr )
{
return nullptr;
}
return RenderTextureInterfacePtr( texture );
}
//////////////////////////////////////////////////////////////////////////
RenderTextureInterfacePtr RenderTextureService::createTexture( uint32_t _mipmaps, uint32_t _width, uint32_t _height, EPixelFormat _format, const DocumentPtr & _doc )
{
RenderImageInterfacePtr image = RENDER_SYSTEM()
->createImage( _mipmaps, _width, _height, _format, _doc );
MENGINE_ASSERTION_MEMORY_PANIC( image, "invalid create image %ux%u"
, _width
, _height
);
RenderTextureInterfacePtr texture = this->createRenderTexture( image, _width, _height, _doc );
MENGINE_ASSERTION_MEMORY_PANIC( texture, "invalid create render texture %ux%u"
, _width
, _height
);
return texture;
}
//////////////////////////////////////////////////////////////////////////
bool RenderTextureService::saveImage( const RenderTextureInterfacePtr & _texture, const FileGroupInterfacePtr & _fileGroup, const ConstString & _codecType, const FilePath & _filePath )
{
OutputStreamInterfacePtr stream = Helper::openOutputStreamFile( _fileGroup, _filePath, true, MENGINE_DOCUMENT_FACTORABLE );
MENGINE_ASSERTION_MEMORY_PANIC( stream, "can't create file '%s'"
, Helper::getFileGroupFullPath( _fileGroup, _filePath )
);
ImageEncoderInterfacePtr imageEncoder = CODEC_SERVICE()
->createEncoder( _codecType, MENGINE_DOCUMENT_FACTORABLE );
MENGINE_ASSERTION_MEMORY_PANIC( imageEncoder, "can't create encoder for file '%s'"
, _filePath.c_str()
);
if( imageEncoder->initialize( stream ) == false )
{
LOGGER_ERROR( "can't initialize encoder for file '%s'"
, _filePath.c_str()
);
return false;
}
ImageCodecDataInfo dataInfo;
dataInfo.mipmaps = 1;
dataInfo.width = _texture->getWidth();
dataInfo.height = _texture->getHeight();
const RenderImageInterfacePtr & image = _texture->getImage();
dataInfo.format = image->getHWPixelFormat();
Rect rect;
rect.left = 0;
rect.top = 0;
rect.right = dataInfo.width;
rect.bottom = dataInfo.height;
RenderImageLockedInterfacePtr locked = image->lock( 0, rect, true );
size_t pitch = 0;
void * buffer = locked->getBuffer( &pitch );
MENGINE_ASSERTION_MEMORY_PANIC( buffer, "can't lock texture '%s'"
, _filePath.c_str()
);
size_t bufferSize = pitch * dataInfo.height;
ImageEncoderData data;
data.buffer = buffer;
data.size = bufferSize;
data.pitch = pitch;
size_t bytesWritten = imageEncoder->encode( &data, &dataInfo );
image->unlock( locked, 0, true );
if( bytesWritten == 0 )
{
LOGGER_ERROR( "Error while encoding image data" );
return false;
}
return true;
}
//////////////////////////////////////////////////////////////////////////
void RenderTextureService::visitTexture( const LambdaRenderTexture & _lambda ) const
{
for( MapRenderTextureEntry::const_iterator
it = m_textures.begin(),
it_end = m_textures.end();
it != it_end;
++it )
{
const MapRenderTextureEntry::value_type & value = *it;
const RenderTextureInterface * texture = value.element;
_lambda( RenderTextureInterfacePtr( texture ) );
}
}
//////////////////////////////////////////////////////////////////////////
RenderImageLoaderInterfacePtr RenderTextureService::createDecoderRenderImageLoader( const FileGroupInterfacePtr & _fileGroup, const FilePath & _filePath, const ConstString & _codecType, uint32_t _codecFlags, const DocumentPtr & _doc )
{
DecoderRenderImageLoaderPtr loader = Helper::makeFactorableUnique<DecoderRenderImageLoader>( _doc );
if( loader->initialize( _fileGroup, _filePath, _codecType, _codecFlags ) == false )
{
return nullptr;
}
return loader;
}
//////////////////////////////////////////////////////////////////////////
void RenderTextureService::cacheFileTexture( const FileGroupInterfacePtr & _fileGroup, const FilePath & _filePath, const RenderTextureInterfacePtr & _texture )
{
_texture->setFileGroup( _fileGroup );
_texture->setFilePath( _filePath );
RenderTextureInterface * texture_ptr = _texture.get();
const ConstString & fileGroupName = _fileGroup->getName();
m_textures.emplace( fileGroupName, _filePath, texture_ptr );
LOGGER_INFO( "texture", "cache texture '%s'"
, Helper::getFileGroupFullPath( _fileGroup, _filePath )
);
}
//////////////////////////////////////////////////////////////////////////
RenderTextureInterfacePtr RenderTextureService::loadTexture( const FileGroupInterfacePtr & _fileGroup, const FilePath & _filePath, const ConstString & _codecType, uint32_t _codecFlags, const DocumentPtr & _doc )
{
const ConstString & fileGroupName = _fileGroup->getName();
const RenderTextureInterface * texture = m_textures.find( fileGroupName, _filePath );
if( texture != nullptr )
{
return RenderTextureInterfacePtr::from( texture );
}
if( SERVICE_EXIST( GraveyardServiceInterface ) == true )
{
RenderTextureInterfacePtr resurrect_texture = GRAVEYARD_SERVICE()
->resurrectTexture( _fileGroup, _filePath, _doc );
if( resurrect_texture != nullptr )
{
this->cacheFileTexture( _fileGroup, _filePath, resurrect_texture );
return resurrect_texture;
}
}
LOGGER_INFO( "texture", "load texture '%s' codec '%s'"
, Helper::getFileGroupFullPath( _fileGroup, _filePath )
, _codecType.c_str()
);
DecoderRenderImageProviderPtr imageProvider = m_factoryDecoderRenderImageProvider->createObject( _doc );
MENGINE_ASSERTION_MEMORY_PANIC( imageProvider, "invalid create render image provider" );
imageProvider->initialize( _fileGroup, _filePath, _codecType, _codecFlags );
RenderImageLoaderInterfacePtr imageLoader = imageProvider->getLoader( _doc );
MENGINE_ASSERTION_MEMORY_PANIC( imageLoader, "invalid get image loader" );
RenderImageDesc imageDesc;
imageLoader->getImageDesc( &imageDesc );
RenderTextureInterfacePtr new_texture = this->createTexture( imageDesc.mipmaps, imageDesc.width, imageDesc.height, imageDesc.format, _doc );
MENGINE_ASSERTION_MEMORY_PANIC( new_texture, "create texture '%s' codec '%s'"
, Helper::getFileGroupFullPath( _fileGroup, _filePath )
, _codecType.c_str()
);
const RenderImageInterfacePtr & image = new_texture->getImage();
MENGINE_ASSERTION_MEMORY_PANIC( image, "invalid get image" );
if( imageLoader->load( image ) == false )
{
LOGGER_ERROR( "invalid decode image '%s' codec '%s'"
, _filePath.c_str()
, _codecType.c_str()
);
return nullptr;
}
image->setRenderImageProvider( imageProvider );
this->cacheFileTexture( _fileGroup, _filePath, new_texture );
return new_texture;
}
//////////////////////////////////////////////////////////////////////////
bool RenderTextureService::onRenderTextureDestroy_( RenderTextureInterface * _texture )
{
const FileGroupInterfacePtr & fileGroup = _texture->getFileGroup();
const FilePath & filePath = _texture->getFilePath();
if( filePath.empty() == false )
{
const ConstString & fileGroupName = fileGroup->getName();
RenderTextureInterface * erase_texture = m_textures.erase( fileGroupName, filePath );
MENGINE_UNUSED( erase_texture );
MENGINE_ASSERTION_MEMORY_PANIC( erase_texture );
NOTIFICATION_NOTIFY( NOTIFICATOR_ENGINE_TEXTURE_DESTROY, _texture );
}
_texture->release();
return false;
}
//////////////////////////////////////////////////////////////////////////
RenderTextureInterfacePtr RenderTextureService::createRenderTexture( const RenderImageInterfacePtr & _image, uint32_t _width, uint32_t _height, const DocumentPtr & _doc )
{
UniqueId id = ENUMERATOR_SERVICE()
->generateUniqueIdentity();
RenderTexturePtr texture = m_factoryRenderTexture->createObject( _doc );
MENGINE_ASSERTION_MEMORY_PANIC( texture );
texture->initialize( id, _image, _width, _height );
return texture;
}
//////////////////////////////////////////////////////////////////////////
}
| 37.027778
| 238
| 0.595874
|
irov
|
2aebde647e6537300825004bf2fe34d60977bb39
| 2,054
|
cpp
|
C++
|
qt/pubnub.cpp
|
sghiocel/pubnub-c
|
149e536e4e1e973a717b324034aa08df9b1bc3a8
|
[
"MIT"
] | 47
|
2015-07-09T14:14:32.000Z
|
2022-03-03T21:47:16.000Z
|
qt/pubnub.cpp
|
parasyte/c-core
|
943b39284837ea5db65eb2445fdc27a60753b183
|
[
"MIT"
] | 52
|
2015-11-03T16:59:24.000Z
|
2022-03-09T15:52:37.000Z
|
qt/pubnub.cpp
|
parasyte/c-core
|
943b39284837ea5db65eb2445fdc27a60753b183
|
[
"MIT"
] | 69
|
2015-08-19T11:32:27.000Z
|
2022-03-31T16:20:13.000Z
|
#include "pubnub.hpp"
#include <QCoreApplication>
extern "C" {
#include "pubnub_helper.h"
}
using namespace pubnub;
futres::futres(context &ctx, pubnub_res initial) :
d_ctx(ctx), d_result(initial), d_triggered(false), d_mutex(QMutex::Recursive)
{
connect(&ctx.d_pbqt, SIGNAL(outcome(pubnub_res)), this, SLOT(onOutcome(pubnub_res)));
}
#if __cplusplus >= 201103L
futres::futres(futres &&x) :
d_ctx(x.d_ctx),
d_result(x.d_result),
d_triggered(x.d_triggered),
d_mutex(QMutex::Recursive)
{
disconnect(&d_ctx.d_pbqt, SIGNAL(outcome(pubnub_res)), &x, SLOT(onOutcome(pubnub_res)));
connect(&d_ctx.d_pbqt, SIGNAL(outcome(pubnub_res)), this, SLOT(onOutcome(pubnub_res)));
}
#else
futres::futres(futres const &x) :
d_ctx(x.d_ctx),
d_result(x.d_result),
d_triggered(false),
d_mutex(QMutex(QMutex::Recursive))
{
connect(&d_ctx.d_pbqt, SIGNAL(outcome(pubnub_res)), this, SLOT(onOutcome(pubnub_res)));
}
#endif
pubnub_res futres::last_result()
{
QCoreApplication::processEvents();
QMutexLocker lk(&d_mutex);
return d_result;
}
void futres::start_await()
{
}
pubnub_res futres::end_await()
{
bool triggered;
{
QMutexLocker lk(&d_mutex);
triggered = d_triggered;
}
while (!triggered) {
QCoreApplication::processEvents();
QMutexLocker lk(&d_mutex);
triggered = d_triggered;
}
QMutexLocker lk(&d_mutex);
d_triggered = false;
return d_result;
}
pubnub_publish_res futres::parse_last_publish_result()
{
QMutexLocker lk(&d_mutex);
return d_ctx.parse_last_publish_result();
}
context::context(std::string pubkey, std::string subkey) :
d_pbqt(QString::fromStdString(pubkey), QString::fromStdString(subkey))
{
}
std::ostream& operator<<(std::ostream&out, pubnub_res e)
{
return out << (int)e << '(' << pubnub_res_2_string(e) << ')';
}
QDebug operator<<(QDebug qdbg, pubnub_res e)
{
QDebugStateSaver saver(qdbg);
qdbg.nospace() << (int)e << '(' << pubnub_res_2_string(e) << ')';
return qdbg;
}
| 21.175258
| 92
| 0.675755
|
sghiocel
|
2aef9b7bd6d40b9b372e903996061fdde1d8dae3
| 6,222
|
cpp
|
C++
|
System.Core/src/Switch/Microsoft/Win32/RegistryKeyAll.cpp
|
kkptm/CppLikeCSharp
|
b2d8d9da9973c733205aa945c9ba734de0c734bc
|
[
"MIT"
] | 4
|
2021-10-14T01:43:00.000Z
|
2022-03-13T02:16:08.000Z
|
System.Core/src/Switch/Microsoft/Win32/RegistryKeyAll.cpp
|
kkptm/CppLikeCSharp
|
b2d8d9da9973c733205aa945c9ba734de0c734bc
|
[
"MIT"
] | null | null | null |
System.Core/src/Switch/Microsoft/Win32/RegistryKeyAll.cpp
|
kkptm/CppLikeCSharp
|
b2d8d9da9973c733205aa945c9ba734de0c734bc
|
[
"MIT"
] | 2
|
2022-03-13T02:16:06.000Z
|
2022-03-14T14:32:57.000Z
|
#if defined(__linux__) || defined(__APPLE__)
#include "../../../../include/Switch/Microsoft/Win32/Registry.hpp"
#include "../../../../include/Switch/Microsoft/Win32/RegistryKey.hpp"
#include "../../../../include/Switch/System/IO/Directory.hpp"
#include "../../../../include/Switch/System/IO/DirectoryInfo.hpp"
#include "../../../../include/Switch/System/IO/File.hpp"
#include "../../../../include/Switch/System/IO/Path.hpp"
using namespace System;
using namespace System::IO;
using namespace Microsoft::Win32;
using namespace System::Collections::Generic;
namespace {
static void CreateDefaultFile(const System::String& path) {
System::IO::File::WriteAllText(path, "<Values>\n<Value Key=\"(Default)\"\nKind=\"String\"></Value>\n</Values>\n");
}
static bool ExistSubKey(const System::String& path, const System::String& subKey) {
if (path == "")
return false;
if (subKey == "")
return true;
Array<DirectoryInfo> directories = DirectoryInfo(path).GetDirectories();
System::String subKeyLowered = subKey.ToLower();
for (DirectoryInfo directory : directories) {
if (directory.Name().ToLower() == subKeyLowered)
return true;
}
return false;
}
static System::String MakePath(const System::String& path, const System::String& subKey) {
if (path == "" || subKey == "")
return path;
Array<DirectoryInfo> directories = DirectoryInfo(path).GetDirectories();
System::String subKeyLowered = subKey.ToLower();
for (DirectoryInfo directory : directories) {
if (directory.Name().ToLower() == subKeyLowered)
return Path::Combine(path, directory.Name());
}
return Path::Combine(path, subKey);
}
}
const RegistryKey RegistryKey::Null;
RegistryKey::RegistryHandle::RegistryHandle(intptr key, const System::String& name) {
}
RegistryKey::RegistryHandle::RegistryHandle(RegistryHive rhive) {
}
RegistryKey::RegistryHandle::~RegistryHandle() {
}
RegistryKey::RegistryKey(): permission(RegistryKeyPermissionCheck::ReadWriteSubTree) {
}
RegistryKey::RegistryKey(RegistryHive rhive) : name(ToName(rhive)), permission(RegistryKeyPermissionCheck::ReadWriteSubTree) {
this->path = Path::Combine(Environment::GetFolderPath(Environment::SpecialFolder::UserProfile), ".Switch", "Registry", ToName(rhive));
if (not Directory::Exists(this->path)) {
Directory::CreateDirectory(this->path);
::CreateDefaultFile(Path::Combine(this->path, "Values.xml"));
}
this->handle = ref_new<RegistryHandle>();
this->Load();
}
RegistryKey::~RegistryKey() {
}
int32 RegistryKey::SubKeyCount() const {
return DirectoryInfo(this->path).GetDirectories().Count;
}
void RegistryKey::Close() {
this->Flush();
}
RegistryKey RegistryKey::CreateSubKey(const System::String& subKey, RegistryKeyPermissionCheck permissionCheck) {
RegistryKey key = OpenSubKey(subKey, permissionCheck);
if (key != RegistryKey::Null)
return key;
if (this->permission != RegistryKeyPermissionCheck::ReadWriteSubTree)
throw UnauthorizedAccessException(caller_);
key.handle = ref_new<RegistryHandle>();
key.path = ::MakePath(this->path, subKey);
Directory::CreateDirectory(key.path);
::CreateDefaultFile(Path::Combine(key.path, "Values.xml"));
key.name = System::String::Format("{0}\\{1}", this->name, subKey);
key.permission = permissionCheck == RegistryKeyPermissionCheck::Default ? this->permission : permissionCheck;
return key;
}
void RegistryKey::DeleteSubKey(const System::String& subKey, bool throwOnMissingSubKey) {
if (subKey == "")
throw InvalidOperationException(caller_);
if (IsBaseKey(subKey))
throw ArgumentException(caller_);
System::String path = ::MakePath(this->path, subKey);
if (::ExistSubKey(this->path, subKey)) {
if (DirectoryInfo(path).GetDirectories().Count != 0)
throw InvalidOperationException(caller_);
Directory::Delete(path, true);
return;
}
if (throwOnMissingSubKey)
throw ArgumentException(caller_);
}
void RegistryKey::DeleteSubKeyTree(const System::String& subKey, bool throwOnMissingSubKey) {
if (subKey == "" or IsBaseKey(subKey))
throw ArgumentNullException(caller_);
System::String path = ::MakePath(this->path, subKey);
if (::ExistSubKey(this->path, subKey)) {
Directory::Delete(path, true);
return;
}
if (throwOnMissingSubKey)
throw ArgumentException(caller_);
}
Array<System::String> RegistryKey::GetSubKeyNames() {
Array<IO::DirectoryInfo> dirInfo = DirectoryInfo(System::String::Format("{0}", this->path)).GetDirectories();
System::Collections::Generic::List<System::String> subKeyNames;
for (IO::DirectoryInfo item : dirInfo)
subKeyNames.Add(item.Name());
subKeyNames.Sort();
return subKeyNames.ToArray();
}
void RegistryKey::Flush() {
System::String value = System::String::Format("<Values>{0}{1}{0}</Values>{0}", Environment::NewLine, System::String::Join(Environment::NewLine, this->values.Values()));
System::IO::File::WriteAllText(Path::Combine(this->path, "Values.xml"), value);
}
RegistryKey RegistryKey::OpenSubKey(const System::String& subKeyName, RegistryKeyPermissionCheck permissionCheck) {
System::String path = ::MakePath(this->path, subKeyName);
if (not ::ExistSubKey(this->path, subKeyName))
return RegistryKey::Null;
RegistryKey key;
key.path = path;
key.name = System::String::Format("{0}\\{1}", this->name, subKeyName);
key.permission = permissionCheck == RegistryKeyPermissionCheck::Default ? this->permission : permissionCheck;
key.Load();
return key;
}
void RegistryKey::Load() {
try {
this->values.Clear();
System::String s = System::IO::File::ReadAllText(Path::Combine(this->path, "Values.xml"));
System::String toParse = s.Remove(s.IndexOf("</Values>\n")).Substring(s.IndexOf("<Values>\n") + 9).Replace(System::Environment::NewLine, "");
while (!string::IsNullOrEmpty(toParse)) {
RegistryKeyValue rkv = RegistryKeyValue::Parse(toParse.Substring(0, toParse.IndexOf("</Value>") + 8));
toParse = toParse.Remove(0, toParse.IndexOf("</Value>") + 8);
this->values[rkv.Key().ToLower()] = rkv;
}
} catch (const System::Exception& e) {
throw System::FormatException(caller_);
}
}
#endif
| 34.186813
| 170
| 0.701221
|
kkptm
|
2af3e2a3cdaa268634481eb382b94b07ee1df8bc
| 12,231
|
cpp
|
C++
|
prefetcher/prefetcher.cpp
|
compor/prodigy_compiler_support_public
|
014885eb9466076770e76b8c8b1fbe31735b4104
|
[
"BSD-3-Clause"
] | 1
|
2021-12-30T10:48:08.000Z
|
2021-12-30T10:48:08.000Z
|
prefetcher/prefetcher.cpp
|
compor/prodigy_compiler_support_public
|
014885eb9466076770e76b8c8b1fbe31735b4104
|
[
"BSD-3-Clause"
] | null | null | null |
prefetcher/prefetcher.cpp
|
compor/prodigy_compiler_support_public
|
014885eb9466076770e76b8c8b1fbe31735b4104
|
[
"BSD-3-Clause"
] | 1
|
2021-12-30T10:47:58.000Z
|
2021-12-30T10:47:58.000Z
|
/*
BSD 3-Clause License
Copyright (c) 2021, Kuba Kaszyk and Chris Vasiladiotis
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// LLVM
#include "llvm/IR/Function.h"
#include "llvm/Pass.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/CallSite.h"
#include "llvm/IR/Instruction.h"
#include "llvm/Analysis/DependenceAnalysis.h"
#include "llvm/Analysis/MemoryBuiltins.h"
#include "llvm/Analysis/MemorySSA.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Type.h"
// standard
#include <vector>
#include <string>
#include <fstream>
// project
#include "prefetcher.hpp"
#include "util.hpp"
// Register Pass
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
#include "llvm/IR/LegacyPassManager.h"
// Clone Function
#include "llvm/Transforms/Utils/Cloning.h"
#include "llvm/Support/CommandLine.h"
#define DEBUG 1
#define MAX_STACK_COUNT 2
llvm::cl::opt<std::string> FunctionWhiteListFile(
"func-wl-file", llvm::cl::Hidden,
llvm::cl::desc("function whitelist file"));
namespace {
bool getAllocationSizeCalc(llvm::Value &I, std::set<llvm::Value *> &vals, int stack_count = 0) {
bool ret = false;
if (llvm::Instruction* Instr = dyn_cast<llvm::Instruction>(&I)) {
for (int i = 0; i < Instr->getNumOperands(); ++i) {
if (auto *user = llvm::dyn_cast<llvm::Instruction>(Instr->getOperand(i))) {
if (user->getOpcode() == Instruction::Call) {
if (dyn_cast<llvm::CallInst>(user)->getCalledFunction()->getName().str() == std::string("llvm.umul.with.overflow.i64")) {
ret = true;
vals.insert(user);
return true;
}
}
if (stack_count < 200) {
ret |= getAllocationSizeCalc(*user, vals, ++stack_count);
}
}
}
}
return ret;
}
void identifyNewA(llvm::Function &F,
llvm::SmallVectorImpl<myAllocCallInfo> &allocInfos) {
for (llvm::BasicBlock &BB : F) {
for (llvm::Instruction &I : BB) {
llvm::CallSite CS(&I);
if (!CS.getInstruction()) {
continue;
}
llvm::Value *called = CS.getCalledValue()->stripPointerCasts();
if (llvm::Function *f = llvm::dyn_cast<llvm::Function>(called)) {
if (f->getName().equals("_Znam")) {
std::set<llvm::Value*> vals;
getAllocationSizeCalc(*(CS.getArgOperand(0)),vals);
if (vals.size() > 0) {
for (auto v : vals) {
CallSite size(v);
myAllocCallInfo allocInfo;
allocInfo.allocInst = &I;
allocInfo.inputArguments.insert(allocInfo.inputArguments.end(),CS.getArgOperand(0));
allocInfo.inputArguments.insert(allocInfo.inputArguments.end(),size.getArgOperand(1));
allocInfos.push_back(allocInfo);
}
}
else { }
}
}
}
}
}
bool isTargetGEPusedInLoad(llvm::Instruction *I) {
for (auto &u : I->uses()) {
auto *user = llvm::dyn_cast<llvm::Instruction>(u.getUser());
if (user->getOpcode() == Instruction::Load) {
return true;
}
}
return false;
}
llvm::Instruction * findGEPToSameBasePtr(llvm::Function &F, llvm::Instruction & firstI) {
for (llvm::BasicBlock &BB : F) {
for (llvm::Instruction &I : BB) {
if (I.getOpcode() == llvm::Instruction::GetElementPtr &&
firstI.getOperand(0) == I.getOperand(0) && &firstI != &I) {
return &I;
}
}
}
return nullptr;
}
bool areUsedInComparisonOp(Instruction * I, Instruction * I2) {
llvm::SmallVector<llvm::Instruction*,8> I_loads;
llvm::SmallVector<llvm::Instruction*,8> I2_loads;
for (auto &u : I->uses()) {
auto *user = llvm::dyn_cast<llvm::Instruction>(u.getUser());
if (dyn_cast<llvm::Instruction>(user)->getOpcode() == llvm::Instruction::Load) {
I_loads.push_back(dyn_cast<llvm::Instruction>(user));
}
}
for (auto &u : I2->uses()) {
auto *user = llvm::dyn_cast<llvm::Instruction>(u.getUser());
if (dyn_cast<llvm::Instruction>(user)->getOpcode() == llvm::Instruction::Load) {
I2_loads.push_back(dyn_cast<llvm::Instruction>(user));
}
}
for (auto l1 : I_loads) {
for (auto l2 : I2_loads) {
for (auto &l1_u : l1->uses()) {
auto *user = llvm::dyn_cast<llvm::Instruction>(l1_u.getUser());
if (dyn_cast<llvm::Instruction>(user)->getOpcode() == llvm::Instruction::ICmp) {
for (auto &l2_u : l2->uses()) {
auto *user_2 = llvm::dyn_cast<llvm::Instruction>(l2_u.getUser());
if (user == user_2) {
return true;
}
}
}
}
}
}
return false;
}
void findSourceGEPCandidates(Function &F, llvm::SmallVectorImpl<llvm::Instruction*> & source_geps)
{
for (llvm::BasicBlock &BB : F) {
for (llvm::Instruction &I : BB) {
if (I.getOpcode() == Instruction::GetElementPtr) {
source_geps.push_back(&I);
}
}
}
}
void getLoadsUsingSourceGEP(llvm::Instruction * I, llvm::SmallVectorImpl<llvm::Instruction*> & loads, int iter = 0)
{
if (dyn_cast<llvm::PHINode>(I)) {
llvm::PHINode * pI = dyn_cast<llvm::PHINode>(I);
for (auto &u : I->uses()) {
auto *user = llvm::dyn_cast<llvm::Instruction>(u.getUser());
if (user->getOpcode() == Instruction::Load) {
loads.push_back(user);
return;
}
else if (iter < 20 && user->getOpcode() != Instruction::GetElementPtr && user->getOpcode() != Instruction::Store) { // Allow up to three modifications of value between gep calc and load, provided that they are not a store or another GEP
getLoadsUsingSourceGEP(user, loads, ++iter);
}
else if (iter >= 20) {
return;
}
}
}
else {
for (auto &u : I->uses()) {
auto *user = llvm::dyn_cast<llvm::Instruction>(u.getUser());
if (user->getOpcode() == Instruction::Load) {
loads.push_back(user);
return;
}
else if (iter < 20 && user->getOpcode() != Instruction::GetElementPtr && user->getOpcode() != Instruction::Store) { // Allow up to three modifications of value between gep calc and load, provided that they are not a store or another GEP
getLoadsUsingSourceGEP(user, loads, ++iter);
}
else if (iter >= 20) {
return;
}
}
}
}
void getGEPsUsingLoad(llvm::Instruction * I, llvm::SmallVectorImpl<llvm::Instruction*> & target_geps, int iter = 0)
{
for (auto &u : I->uses()) {
auto *user = llvm::dyn_cast<llvm::Instruction>(u.getUser());
if (user->getOpcode() == Instruction::Store) { }
else if (user->getOpcode() == Instruction::GetElementPtr) {
if (user->getOperand(1) == I) { // GEP is dependent only if load result is used as an index
target_geps.push_back(user);
}
}
else if (user->getOpcode() == Instruction::Load) { }
if (iter < 5) { // Allow up to three modifications of value between gep calc and load, provided that they are not a store or another GEP
getGEPsUsingLoad(user, target_geps, ++iter);
}
else {
return;
}
}
}
bool RIfindLoadUsingGEP(llvm::Instruction * src, std::vector<llvm::Instruction *> &targets, int stack_count = 0) {
bool ret = false;
for (auto &u : src->uses()) {
auto *user = llvm::dyn_cast<llvm::Instruction>(u.getUser());
if (user->getOpcode() == llvm::Instruction::Load) {
targets.push_back(user);
return true;
}
if (stack_count < MAX_STACK_COUNT) {
ret |= RIfindLoadUsingGEP(user, targets, ++stack_count);
}
}
return ret;
}
void identifyCorrectRangedIndirection(Function &F, llvm::SmallVectorImpl<GEPDepInfo> & riInfos) {
for (llvm::BasicBlock &BB : F) {
for (llvm::Instruction &I : BB) {
if (I.getOpcode() == llvm::Instruction::GetElementPtr) {
llvm::Instruction * otherGEP = findGEPToSameBasePtr(F, I);
if (otherGEP) {
GEPDepInfo gepdepinfo;
if (areUsedInComparisonOp(&I,otherGEP)) {
std::vector<llvm::Instruction*> targets;
bool found_load = RIfindLoadUsingGEP(&I, targets);
if (found_load) {
gepdepinfo.source = I.getOperand(0);
gepdepinfo.target = targets.at(0);
riInfos.push_back(gepdepinfo);
}
}
}
}
}
}
}
void identifyCorrectGEPDependence(Function &F,
llvm::SmallVectorImpl<GEPDepInfo> &gepInfos) {
llvm::SmallVector<llvm::Instruction*,8> source_geps;
findSourceGEPCandidates(F,source_geps);
for (auto I : source_geps) {
llvm::SmallVector<llvm::Instruction*,8> loads;
getLoadsUsingSourceGEP(I, loads);
for (auto ld : loads) {
llvm::SmallVector<llvm::Instruction*,8> target_geps;
getGEPsUsingLoad(ld, target_geps);
for (auto target_gep : target_geps) {
if (isTargetGEPusedInLoad(target_gep)) {
GEPDepInfo g;
g.source = I->getOperand(0);
g.source_use = ld;
g.funcSource = I->getParent()->getParent();
g.target = target_gep->getOperand(0);
g.funcTarget = target_gep->getParent()->getParent();
gepInfos.push_back(g);
// If the source GEP comes from a PHI node, we use the result of the phi node as the source edge, and insert the registration call
// immediately after the phi nodes
if (dyn_cast<llvm::Instruction>(ld->getOperand(0))->getOpcode() == llvm::Instruction::PHI) {
g.phi_node = dyn_cast<llvm::Instruction>(ld->getOperand(0));
g.phi = true;
}
#if DEBUG == 1
errs() << "Identify source: " << *g.source << "\n";
errs() << "Identify target: " << *g.target << "\n\n";
#endif
}
}
}
}
}
void removeDuplicates(std::set<GEPDepInfo> &svInfos, std::set<GEPDepInfo> &riInfos)
{
llvm::SmallVector<GEPDepInfo,8> duplicates;
for (auto g : riInfos) {
std::set<GEPDepInfo>::iterator duplicate = std::find(svInfos.begin(), svInfos.end(), g);
if (duplicate != svInfos.end()) {
svInfos.erase(duplicate);
}
}
}
} // namespace
void PrefetcherPass::getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired<TargetLibraryInfoWrapperPass>();
AU.addRequired<MemorySSAWrapperPass>();
AU.addRequired<DependenceAnalysisWrapperPass>();
AU.setPreservesAll();
}
bool in(llvm::SmallVectorImpl<std::string> &C, std::string E) {
for (std::string entry : C) {
if (E.find(entry) != std::string::npos) {
return true;
}
}
return false;
};
bool PrefetcherPass::runOnFunction(llvm::Function &F) {
llvm::SmallVector<std::string, 32> FunctionWhiteList;
if (FunctionWhiteListFile.getPosition()) {
std::ifstream wlFile{FunctionWhiteListFile};
std::string funcName;
while (wlFile >> funcName) {
FunctionWhiteList.push_back(funcName);
}
}
if (F.isDeclaration()) {
return false;
}
Result->allocs.clear();
Result->geps.clear();
Result->ri_geps.clear();
auto &TLI = getAnalysis<llvm::TargetLibraryInfoWrapperPass>().getTLI(F);
identifyNewA(F, Result->allocs);
if (FunctionWhiteListFile.getPosition() &&
!in(FunctionWhiteList, F.getName().str())) {
llvm::errs() << "skipping func: " << F.getName() << " reason: not in whitelist\n";;
return false;
}
identifyCorrectGEPDependence(F, Result->geps);
identifyCorrectRangedIndirection(F,Result->ri_geps);
return false;
}
char PrefetcherPass::ID = 0;
static llvm::RegisterPass<PrefetcherPass> X("prefetcher", "Prefetcher Pass",
false, false);
| 29.831707
| 239
| 0.678358
|
compor
|
2af4c8ead66fb0806b58c9656ba5b9bba909a8a4
| 3,875
|
cpp
|
C++
|
fon9/PkCont_UT.cpp
|
fonwin/Plan
|
3bfa9407ab04a26293ba8d23c2208bbececb430e
|
[
"Apache-2.0"
] | 21
|
2019-01-29T14:41:46.000Z
|
2022-03-11T00:22:56.000Z
|
fon9/PkCont_UT.cpp
|
fonwin/Plan
|
3bfa9407ab04a26293ba8d23c2208bbececb430e
|
[
"Apache-2.0"
] | null | null | null |
fon9/PkCont_UT.cpp
|
fonwin/Plan
|
3bfa9407ab04a26293ba8d23c2208bbececb430e
|
[
"Apache-2.0"
] | 9
|
2019-01-27T14:19:33.000Z
|
2022-03-11T06:18:24.000Z
|
// \file fon9/PkCont_UT.cpp
// \author fonwinz@gmail.com
#define _CRT_SECURE_NO_WARNINGS
#include "fon9/PkCont.hpp"
#include "fon9/TestTools.hpp"
#include "fon9/Endian.hpp"
#include "fon9/CountDownLatch.hpp"
struct Feeder : public fon9::PkContFeeder {
fon9_NON_COPY_NON_MOVE(Feeder);
using base = fon9::PkContFeeder;
Feeder() {
}
using base::NextSeq_;
using base::ReceivedCount_;
using base::DroppedCount_;
using base::WaitInterval_;
SeqT ExpectedNextSeq_{0};
SeqT ExpectedSeq_{0};
void Feed(SeqT seq) {
SeqT pk;
fon9::PutBigEndian(&pk, seq);
this->FeedPacket(&pk, sizeof(pk), seq);
}
void PkContOnReceived(const void* pk, unsigned pksz, SeqT seq) override {
if (this->ExpectedSeq_ != seq) {
std::cout << "|err=Unexpected seq=" << seq << "|expected=" << this->ExpectedSeq_
<< "\r[ERROR]" << std::endl;
abort();
}
if (pksz != sizeof(SeqT) || fon9::GetBigEndian<SeqT>(pk) != seq) {
std::cout << "|err=Invalid pk contents." "\r[ERROR]" << std::endl;
abort();
}
if (this->ExpectedNextSeq_ != this->NextSeq_) {
std::cout << "|err=Unexpected NextSeq=" << this->NextSeq_
<< "|ExpectedNextSeq=" << this->ExpectedNextSeq_
<< "\r[ERROR]" << std::endl;
abort();
}
this->ExpectedNextSeq_ = seq + 1;
++this->ExpectedSeq_;
if (this->NextSeq_ != seq)
std::cout << "|gap=[" << this->NextSeq_ << ".." << seq << ")";
}
void CheckReceivedCount(SeqT expected) {
std::cout << "|ReceivedCount=" << this->ReceivedCount_;
if (this->ReceivedCount_ != expected) {
std::cout << "|err=ReceivedCount not expected=" << expected
<< "\r[ERROR]" << std::endl;
abort();
}
std::cout << "\r[OK ]" << std::endl;
}
};
int main(int argc, char* argv[]) {
(void)argc; (void)argv;
fon9::AutoPrintTestInfo utinfo{"PkCont"};
fon9::GetDefaultTimerThread();
struct TimeWaiter : public fon9::TimerEntry {
fon9_NON_COPY_NON_MOVE(TimeWaiter);
using base = fon9::TimerEntry;
fon9::CountDownLatch Waiter_{0};
TimeWaiter() : base{fon9::GetDefaultTimerThread()} {
}
virtual void OnTimerEntryReleased() override {
// TimeWaiter 作為 local data variable, 不需要 delete, 所以 OnTimerEntryReleased(): do nothing.
}
virtual void EmitOnTimer(fon9::TimeStamp now) override {
(void)now;
this->Waiter_.ForceWakeUp();
}
void WaitFor(fon9::TimeInterval ti) {
this->Waiter_.AddCounter(1);
this->RunAfter(ti);
this->Waiter_.Wait();
}
};
TimeWaiter waiter;
waiter.WaitFor(fon9::TimeInterval{});
const Feeder::SeqT kSeqFrom = 123;
const Feeder::SeqT kSeqTo = 200;
Feeder feeder;
Feeder::SeqT seq = kSeqFrom;
Feeder::SeqT pkcount = kSeqTo - kSeqFrom + 1;
feeder.ExpectedSeq_ = seq;
// 測試1: ExpectedNextSeq==0, 序號=kSeqFrom..kSeqTo
std::cout << "[TEST ] PkCont|from=" << kSeqFrom << "|to=" << kSeqTo;
for (; seq <= kSeqTo; ++seq)
feeder.Feed(seq);
feeder.CheckReceivedCount(pkcount);
const Feeder::SeqT kGapCount = 5;
seq += kGapCount;
std::cout << "[TEST ] PkCont.gap and fill|gap=" << kGapCount
<< "|seq=" << seq << ".." << (seq - kGapCount);
for (Feeder::SeqT L = 0; L <= kGapCount; ++L)
feeder.Feed(seq - L);
feeder.CheckReceivedCount(pkcount += kGapCount + 1);
seq += kGapCount;
feeder.ExpectedSeq_ = seq;
std::cout << "[TEST ] PkCont.gap and wait|gap=" << kGapCount
<< "|seq=" << seq << ".." << (seq + kGapCount);
for (Feeder::SeqT L = 0; L <= kGapCount; ++L)
feeder.Feed(seq + L);
waiter.WaitFor(feeder.WaitInterval_ + fon9::TimeInterval_Millisecond(1));
feeder.CheckReceivedCount(pkcount += kGapCount + 1);
}
| 34.292035
| 97
| 0.592774
|
fonwin
|
2af998d639656d149eaf69afaa59f19811f3116a
| 702
|
cpp
|
C++
|
src/obsolete/udev.cpp
|
pdumais/dhas
|
424212d4766c02f5df9e363ddb8ad2c295ed49d8
|
[
"MIT"
] | 12
|
2015-09-09T07:05:27.000Z
|
2020-12-27T12:52:28.000Z
|
src/obsolete/udev.cpp
|
pdumais/dhas
|
424212d4766c02f5df9e363ddb8ad2c295ed49d8
|
[
"MIT"
] | null | null | null |
src/obsolete/udev.cpp
|
pdumais/dhas
|
424212d4766c02f5df9e363ddb8ad2c295ed49d8
|
[
"MIT"
] | 2
|
2016-10-23T05:23:20.000Z
|
2020-09-17T22:01:33.000Z
|
#include "DHASLogging.h"
#include <stdio.h>
#include <string>
#include <sstream>
#include "config.h"
#include "UDev.h"
#include <string.h>
unsigned long getMemUsage()
{
char buf[1024];
FILE* f = fopen("/proc/self/status","r");
while (fgets(buf,1024,f))
{
if (!strncmp(buf,"VmSize:",7))
{
fclose(f);
return atoi((char*)&buf[8]);
}
}
fclose(f);
return 0;
}
int main(int argc, char** argv)
{
unsigned int i;
printf("mem use before: %x\r\n",getMemUsage());
for (i = 0; i < 1000; i++)
{
std::string st = UDev::findDevice("13eb","104b");
}
printf("mem use After: %x\r\n",getMemUsage());
}
| 18.972973
| 57
| 0.534188
|
pdumais
|
2afa230a6982415423598f47a93dfd858fb2510d
| 774
|
cpp
|
C++
|
src/blinktask.cpp
|
XMrVertigoX/DualLampSwitch
|
c86a0bd38cc4e585de24cc2d8494067468fc4483
|
[
"MIT"
] | null | null | null |
src/blinktask.cpp
|
XMrVertigoX/DualLampSwitch
|
c86a0bd38cc4e585de24cc2d8494067468fc4483
|
[
"MIT"
] | null | null | null |
src/blinktask.cpp
|
XMrVertigoX/DualLampSwitch
|
c86a0bd38cc4e585de24cc2d8494067468fc4483
|
[
"MIT"
] | null | null | null |
#include <em_cmu.h>
#include <em_gpio.h>
#include <FreeRTOS.h>
#include <semphr.h>
#include <task.h>
#include "blinktask.hpp"
using namespace xXx;
BlinkTask::BlinkTask(uint16_t stack, UBaseType_t priority)
: ArduinoTask(stack, priority), _LastWakeTime(0) {}
BlinkTask::~BlinkTask() {}
void BlinkTask::setup() {
_LastWakeTime = xTaskGetTickCount();
CMU_ClockEnable(cmuClock_HFLE, true);
CMU_ClockEnable(cmuClock_GPIO, true);
GPIO_PinModeSet(gpioPortA, 0, gpioModePushPullDrive, 0);
GPIO_PinModeSet(gpioPortA, 1, gpioModePushPullDrive, 0);
GPIO_PinOutSet(gpioPortA, 0);
}
void BlinkTask::loop() {
vTaskDelayUntil(&_LastWakeTime, 1000 / portTICK_PERIOD_MS);
GPIO_PinOutToggle(gpioPortA, 0);
GPIO_PinOutToggle(gpioPortA, 1);
}
| 22.114286
| 63
| 0.728682
|
XMrVertigoX
|
2afa4086cdaae5e0aa81c05a98e43cfd82547e84
| 774
|
cpp
|
C++
|
UVA10924.cpp
|
MaSteve/UVA-problems
|
3a240fcca02e24a9c850b7e86062f8581df6f95f
|
[
"MIT"
] | 17
|
2015-12-08T18:50:03.000Z
|
2022-03-16T01:23:20.000Z
|
UVA10924.cpp
|
MaSteve/UVA-problems
|
3a240fcca02e24a9c850b7e86062f8581df6f95f
|
[
"MIT"
] | null | null | null |
UVA10924.cpp
|
MaSteve/UVA-problems
|
3a240fcca02e24a9c850b7e86062f8581df6f95f
|
[
"MIT"
] | 6
|
2017-04-04T18:16:23.000Z
|
2020-06-28T11:07:22.000Z
|
#include <iostream>
#include <unordered_set>
#include <bitset>
#include <string>
#include <cctype>
using namespace std;
typedef long long ll;
ll sieve_size;
bitset<10000010> bs;
unordered_set<int> primes;
void sieve(ll upperbound) {
sieve_size=upperbound+1; bs.set(); bs[0]=bs[1]=0;
for (ll i=2; i<=sieve_size; i++) if(bs[i]) {
for (ll j=i*i; j<=sieve_size; j+=i) bs[j] = 0;
primes.insert((int)i);
}
}
int main() {
sieve(2000);
primes.insert(1);
string s;
while (cin >> s) {
int val = 0;
for (int i = 0; i < s.length(); i++) {
if (isupper(s[i])) val += 27 + (s[i]-'A');
else if (islower(s[i])) val += 1 + (s[i]-'a');
}
if (primes.count(val)) cout << "It is a prime word." << endl;
else cout << "It is not a prime word." << endl;
}
return 0;
}
| 22.114286
| 63
| 0.595607
|
MaSteve
|
6306f6446d8b5786251e2fbf734199ab4c649530
| 2,203
|
cpp
|
C++
|
BearIO/BearFilePackageStream.cpp
|
BearIvan/bearcore
|
330a7983cb831fa4222b3ddfefc4c02df1267f0f
|
[
"MIT"
] | 1
|
2020-10-17T08:04:12.000Z
|
2020-10-17T08:04:12.000Z
|
BearIO/BearFilePackageStream.cpp
|
BearIvan/bearcore
|
330a7983cb831fa4222b3ddfefc4c02df1267f0f
|
[
"MIT"
] | null | null | null |
BearIO/BearFilePackageStream.cpp
|
BearIvan/bearcore
|
330a7983cb831fa4222b3ddfefc4c02df1267f0f
|
[
"MIT"
] | 1
|
2020-04-24T20:19:07.000Z
|
2020-04-24T20:19:07.000Z
|
#include "BearCore.hpp"
BearFilePackageStream::BearFilePackageStream():m_tell(0),m_ptr(0),m_size(0)
{
}
BearFilePackageStream::~BearFilePackageStream()
{
}
BearFilePackageStream::BearFilePackageStream(const BearFilePackageStream & right) :m_tell(0), m_ptr(0), m_size(0)
{
Copy(right);
}
BearFilePackageStream::BearFilePackageStream(BearFilePackageStream && right) : m_tell(0), m_ptr(0), m_size(0)
{
Swap(right);
}
void BearFilePackageStream::Copy(const BearFilePackageStream & right)
{
m_file_name = right.m_file_name;
m_ptr = right.m_ptr;
m_tell = right.m_tell;
m_size = right.m_size;
OpenFile();
}
void BearFilePackageStream::Swap(BearFilePackageStream & right)
{
m_file_name.swap(right.m_file_name);
m_file.Swap(right.m_file);
bear_swap(m_ptr , right.m_ptr);
bear_swap(m_tell , right.m_tell);
bear_swap(m_size, right.m_size);
}
BearFilePackageStream & BearFilePackageStream::operator=(BearFilePackageStream && right)
{
Swap(right);
return *this;
}
BearFilePackageStream & BearFilePackageStream::operator=(const BearFilePackageStream & right)
{
Copy(right);
return *this;
}
bool BearFilePackageStream::Eof() const
{
return m_size+m_ptr==m_file.Tell();
}
bsize BearFilePackageStream::Seek(bsize tell) const
{
if (tell > m_size)
m_tell = m_size;
else
m_tell = tell;
if (m_size)m_file.Seek(m_ptr + m_tell);
return m_tell;
}
bsize BearFilePackageStream::Tell() const
{
return m_tell;
}
bsize BearFilePackageStream::Size() const
{
return m_size;
}
void BearFilePackageStream::Close()
{
m_file.Close();
m_file_name.clear();
m_ptr =0;
m_tell =0;
m_size = 0;
}
BearRef<BearInputStream> BearFilePackageStream::ReadChunkAsInputStream(uint32 type) const
{
auto size = GoToChunk(type);
if (!size)return BearRef<BearInputStream>();
BearFilePackageStream *temp = bear_new<BearFilePackageStream>();
*temp = *this;
return temp;
}
bsize BearFilePackageStream::ReadBuffer(void * data, bsize size) const
{
if (m_tell + size > m_size)size = m_size - m_tell;
m_file.ReadBuffer(data, size);
m_tell += size;
return size;
}
void BearFilePackageStream::OpenFile()
{
if (m_size == 0)return;
BEAR_ASSERT(m_file.Open(*m_file_name));
m_file.Seek(m_ptr + m_tell);
}
| 19.669643
| 113
| 0.744893
|
BearIvan
|
deb9535f6d3e6ecfd7e6144eb84d3cfc2ef6ebac
| 733
|
cpp
|
C++
|
DanielaBarrios_Final.cpp
|
DanielaFBL/DanielaBarrios_Final
|
f2914a67021bd2aba09078e564970374831f90ec
|
[
"MIT"
] | null | null | null |
DanielaBarrios_Final.cpp
|
DanielaFBL/DanielaBarrios_Final
|
f2914a67021bd2aba09078e564970374831f90ec
|
[
"MIT"
] | null | null | null |
DanielaBarrios_Final.cpp
|
DanielaFBL/DanielaBarrios_Final
|
f2914a67021bd2aba09078e564970374831f90ec
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
int main(){
float m = 7294.29;
float q = 2;
float omega=1.0;
return 0;
}
void leapfrog (float t0, float tf, float dt, float m, float q, string datos){
float t0=0.0;
float x=1.0;
float y=0.0;
float tf=10.0;
float dt=0.1;
float x0= 1.0;
float y0 = 0.0;
ofstream outfile;
outfile.open(datos.dat);
if(tf<3){
cout<<"E=0";
}
if (3>tf>7){
cout<<"E=(0,3)";
}
while(t0<tf){
outfile << t0 << " " << x << " " << y << endl;
x = m + 0.5 * dt * q;
y = q + dt * (-q * dt * m);
t0 = t0 + dt;
outfile.close();
}
| 15.270833
| 77
| 0.45839
|
DanielaFBL
|
debf8fff70fdf33dae3f3a3c91062b23b981beee
| 1,988
|
cpp
|
C++
|
src/Coordination/WriteBufferFromNuraftBuffer.cpp
|
540522905/ClickHouse
|
299445ec7da10bd2ef62d8e333a95b7ab12bf5f2
|
[
"Apache-2.0"
] | 15,577
|
2019-09-23T11:57:53.000Z
|
2022-03-31T18:21:48.000Z
|
src/Coordination/WriteBufferFromNuraftBuffer.cpp
|
540522905/ClickHouse
|
299445ec7da10bd2ef62d8e333a95b7ab12bf5f2
|
[
"Apache-2.0"
] | 16,476
|
2019-09-23T11:47:00.000Z
|
2022-03-31T23:06:01.000Z
|
src/Coordination/WriteBufferFromNuraftBuffer.cpp
|
540522905/ClickHouse
|
299445ec7da10bd2ef62d8e333a95b7ab12bf5f2
|
[
"Apache-2.0"
] | 3,633
|
2019-09-23T12:18:28.000Z
|
2022-03-31T15:55:48.000Z
|
#include <Coordination/WriteBufferFromNuraftBuffer.h>
#include <base/logger_useful.h>
namespace DB
{
namespace ErrorCodes
{
extern const int CANNOT_WRITE_AFTER_END_OF_BUFFER;
}
void WriteBufferFromNuraftBuffer::nextImpl()
{
if (is_finished)
throw Exception("WriteBufferFromNuraftBuffer is finished", ErrorCodes::CANNOT_WRITE_AFTER_END_OF_BUFFER);
/// pos may not be equal to vector.data() + old_size, because WriteBuffer::next() can be used to flush data
size_t pos_offset = pos - reinterpret_cast<Position>(buffer->data_begin());
size_t old_size = buffer->size();
if (pos_offset == old_size)
{
nuraft::ptr<nuraft::buffer> new_buffer = nuraft::buffer::alloc(old_size * size_multiplier);
memcpy(new_buffer->data_begin(), buffer->data_begin(), buffer->size());
buffer = new_buffer;
}
internal_buffer = Buffer(reinterpret_cast<Position>(buffer->data_begin() + pos_offset), reinterpret_cast<Position>(buffer->data_begin() + buffer->size()));
working_buffer = internal_buffer;
}
WriteBufferFromNuraftBuffer::WriteBufferFromNuraftBuffer()
: WriteBuffer(nullptr, 0)
{
buffer = nuraft::buffer::alloc(initial_size);
set(reinterpret_cast<Position>(buffer->data_begin()), buffer->size());
}
void WriteBufferFromNuraftBuffer::finalize()
{
if (is_finished)
return;
is_finished = true;
size_t real_size = pos - reinterpret_cast<Position>(buffer->data_begin());
nuraft::ptr<nuraft::buffer> new_buffer = nuraft::buffer::alloc(real_size);
memcpy(new_buffer->data_begin(), buffer->data_begin(), real_size);
buffer = new_buffer;
/// Prevent further writes.
set(nullptr, 0);
}
nuraft::ptr<nuraft::buffer> WriteBufferFromNuraftBuffer::getBuffer()
{
finalize();
return buffer;
}
WriteBufferFromNuraftBuffer::~WriteBufferFromNuraftBuffer()
{
try
{
finalize();
}
catch (...)
{
tryLogCurrentException(__PRETTY_FUNCTION__);
}
}
}
| 27.611111
| 159
| 0.703219
|
540522905
|
dec0c16542a97df2aeea3aa4987d740f8fb06e5d
| 943
|
cpp
|
C++
|
src/objective3d.cpp
|
dream-overflow/o3d
|
087ab870cc0fd9091974bb826e25c23903a1dde0
|
[
"FSFAP"
] | 2
|
2019-06-22T23:29:44.000Z
|
2019-07-07T18:34:04.000Z
|
src/objective3d.cpp
|
dream-overflow/o3d
|
087ab870cc0fd9091974bb826e25c23903a1dde0
|
[
"FSFAP"
] | null | null | null |
src/objective3d.cpp
|
dream-overflow/o3d
|
087ab870cc0fd9091974bb826e25c23903a1dde0
|
[
"FSFAP"
] | null | null | null |
/**
* @file objective3d.cpp
* @brief Application dynamic library entry
* @author Frederic SCHERMA (frederic.scherma@dreamoverflow.org)
* @date 2001-12-25
* @copyright Copyright (C) 2001-2017 Dream Overflow. All rights reserved.
* @details
*/
#include "o3d/objective3d.h"
#include "o3d/core/architecture.h"
// it's needed for DLL exportation
#define O3D_NO_LIB_FLAG
#ifdef O3D_MACOSX
// Mac OS part
#ifndef __O3D_NOLIB__
int main(int argc, char *argv[])
{
return 0;
}
#endif // __O3D_NOLIB__
#elif defined(O3D_WINDOWS)
// Windows part
BOOL APIENTRY DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
switch (ul_reason_for_call) {
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
#endif
#undef O3D_NO_LIB_FLAG
| 23
| 86
| 0.658537
|
dream-overflow
|
ded2a7014e51e63036da42da0be6559d3da9077e
| 3,881
|
cpp
|
C++
|
src/app.cpp
|
antongus/clock-7-seg
|
090778c28d078541e376531327e23a9a669e8b29
|
[
"MIT"
] | null | null | null |
src/app.cpp
|
antongus/clock-7-seg
|
090778c28d078541e376531327e23a9a669e8b29
|
[
"MIT"
] | null | null | null |
src/app.cpp
|
antongus/clock-7-seg
|
090778c28d078541e376531327e23a9a669e8b29
|
[
"MIT"
] | null | null | null |
/**
* @file app.cpp
*
* Application class implementation.
* Copyright © 2015 Anton B. Gusev aka AHTOXA
**/
#include "app.h"
#include "textbuf.h"
/**
* Dynamic indication loop.
*/
OS_PROCESS void Application::RefreshLoop()
{
int kbdCounter = 20;
// restore brightness at startup
digits_.SetBrightness(BKP->DR2);
for (;;)
{
OS::sleep(1);
// refresh LED every millisecond
digits_.Refresh();
// read keyboard every 20 milliseconds
if (!--kbdCounter)
{
kbd_.Loop();
kbdCounter = 20;
}
}
}
/**
* Time update loop
*/
OS_PROCESS void Application::UpdateLoop()
{
for (;;)
{
OS::sleep(100);
UpdateTime();
}
}
/**
* User interface loop.
*/
OS_PROCESS void Application::UserInterfaceLoop()
{
int repeats = 0;
const int FAST_LEVEL = 10;
ButtonUp::Mode(INPUTPULLED);
ButtonUp::PullUp();
ButtonDown::Mode(INPUTPULLED);
ButtonDown::PullUp();
for (;;)
{
int keyCode = kbd_.GetChar(10000);
if (keyCode == -1)
continue;
if (keyCode == (BUTTON_UP | BUTTON_DOWN))
{
if (EditBrightness())
EditCorrection();
continue;
}
time_t t = (rtc_.ReadTime() / 60) * 60; // cut off seconds
if (keyCode & BUTTON_REPEAT)
{
if (repeats < FAST_LEVEL)
repeats++;
}
else
repeats = 0;
time_t step = repeats < FAST_LEVEL ? 60 : 5 * 60;
keyCode &= ~BUTTON_REPEAT;
if (keyCode == BUTTON_UP)
SetTime(t + step);
else if (keyCode == BUTTON_DOWN)
SetTime(t - step);
else if (keyCode == (BUTTON_UP | BUTTON_DOWN))
{
uint8_t b = digits_.GetBrightness() + 1;
if (b > 16)
b = 4;
digits_.SetBrightness(b);
}
}
}
/**
* Update time.
* Lock mutex, then draw current time.
* Mutex is used to block updates when user enters menu.
*/
void Application::UpdateTime()
{
OS::TMutexLocker lock(displayMutex_);
time_t t = rtc_.ReadTime();
struct tm stm;
localtime_r(&t, &stm);
TextBuffer<5> tmpBuf;
if (stm.tm_hour < 10)
tmpBuf << '0';
tmpBuf << stm.tm_hour;
if (stm.tm_min < 10)
tmpBuf << '0';
tmpBuf << stm.tm_min;
digits_.SetText(tmpBuf);
digits_.SetColon(t & 1);
}
/**
* Set time.
*/
void Application::SetTime(time_t t)
{
TCritSect cs;
rtc_.WriteTime(t);
}
/**
* Edit brightness.
* Lock mutex, then edit brightness with LEFT/RIGHT buttons.
* Mutex is used to block time updates.
* @return true if user pressed LEFT+RIGHT, false otherwise.
*/
bool Application::EditBrightness()
{
OS::TMutexLocker lock(displayMutex_);
for (;;)
{
// Display current brightness: "br:02"
TextBuffer<5> tmpBuf;
tmpBuf << "br";
uint8_t brightness = digits_.GetBrightness();
if (brightness < 10)
tmpBuf << '0';
tmpBuf << brightness;
digits_.SetText(tmpBuf);
digits_.SetColon(true);
// get user input
int keyCode = kbd_.GetChar(10000);
if (keyCode == -1)
return false;
if (keyCode == (BUTTON_UP | BUTTON_DOWN))
return true;
keyCode &= ~BUTTON_REPEAT;
if (keyCode == BUTTON_UP)
digits_.SetBrightness(brightness + 1);
else if (keyCode == BUTTON_DOWN)
digits_.SetBrightness(brightness - 1);
}
}
/**
* Edit time correction.
* Lock mutex, then edit correction with LEFT/RIGHT buttons.
* Mutex is used to block time updates.
* @return true if user pressed LEFT+RIGHT, false otherwise.
*/
bool Application::EditCorrection()
{
OS::TMutexLocker lock(displayMutex_);
for (;;)
{
// Display current time correction: "c002"
TextBuffer<5> tmpBuf;
tmpBuf << "c";
uint8_t corr = rtc_.GetCorrection();
if (corr < 100)
tmpBuf << '0';
if (corr < 10)
tmpBuf << '0';
tmpBuf << corr;
digits_.SetText(tmpBuf);
digits_.SetColon(false);
int keyCode = kbd_.GetChar(10000);
if (keyCode == -1)
return false;
if (keyCode == (BUTTON_UP | BUTTON_DOWN))
return true;
keyCode &= ~BUTTON_REPEAT;
if (keyCode == BUTTON_UP)
rtc_.SetCorrection(corr + 1);
else if (keyCode == BUTTON_DOWN)
rtc_.SetCorrection(corr - 1);
}
}
| 19.118227
| 60
| 0.646998
|
antongus
|
ded510b573e3c00f111631fc62198da623024f50
| 1,371
|
cpp
|
C++
|
Flatten/GA/c2ga_draw.cpp
|
mauriciocele/arap-svd
|
bbefe4b0f18d7cd5e834b4c54e518f0d70f49565
|
[
"MIT"
] | 4
|
2021-01-05T15:14:34.000Z
|
2021-09-08T14:08:49.000Z
|
Flatten/GA/c2ga_draw.cpp
|
mauriciocele/arap-svd
|
bbefe4b0f18d7cd5e834b4c54e518f0d70f49565
|
[
"MIT"
] | null | null | null |
Flatten/GA/c2ga_draw.cpp
|
mauriciocele/arap-svd
|
bbefe4b0f18d7cd5e834b4c54e518f0d70f49565
|
[
"MIT"
] | null | null | null |
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
// Copyright 2007, Daniel Fontijne, University of Amsterdam -- fontijne@science.uva.nl
#ifdef WIN32
#include <windows.h>
#endif
#if defined (__APPLE__) || defined (OSX)
#include <OpenGL/gl.h>
#else
#include <GL/gl.h>
#endif
#include "c2ga_draw.h"
#include "c3ga_draw.h"
#include "mv_analyze.h"
using namespace mv_analyze;
namespace mv_draw {
using namespace e3ga;
void drawC2GA(const mv_analyze::mvAnalysis &A, int method/*= 0*/, Palet *o/* = NULL*/) {
return drawC3GA(A, method, o);
}
void draw(const c2ga::mv &X, int method/*= 0*/, Palet *o/* = NULL*/) {
mv_analyze::mvAnalysis A(X);
drawC3GA(A, method, o);
}
} // end of namespace mv_draw
| 27.42
| 88
| 0.722101
|
mauriciocele
|
ded513904dbd40be12eaf1d591259c65228ac98f
| 6,759
|
cpp
|
C++
|
Enterprise/src/Enterprise/Time/Time.cpp
|
theOtherMichael/Enterprise
|
1f018e364c58808c36af9a428a081bb441387847
|
[
"Apache-2.0"
] | null | null | null |
Enterprise/src/Enterprise/Time/Time.cpp
|
theOtherMichael/Enterprise
|
1f018e364c58808c36af9a428a081bb441387847
|
[
"Apache-2.0"
] | null | null | null |
Enterprise/src/Enterprise/Time/Time.cpp
|
theOtherMichael/Enterprise
|
1f018e364c58808c36af9a428a081bb441387847
|
[
"Apache-2.0"
] | null | null | null |
#include "EP_PCH.h"
#include "Time.h"
#include "Enterprise/Graphics/Graphics.h"
using Enterprise::Time;
static uint64_t fixedTimestepInRealTicks;
#ifdef EP_CONFIG_DIST
static uint64_t fixedTimestepInGameTicks, maxFrameDeltaInRealTicks;
#endif
static double currentTimeScale = 1.0;
static uint64_t currentSysTimeInTicks = 0, previousSysTimeInTicks;
static uint64_t measuredRealTickDelta, measuredGameTickDelta;
static uint64_t realRunningTicks = 0, gameRunningTicks = 0;
static uint64_t unsimmedRealTicks = 0, unsimmedGameTicks = 0;
static bool inFixedTimestep_out = true;
static float realRunningTime_out, gameRunningTime_out;
static float realDelta_out, gameDelta_out;
static float unsimmedRealTime_out, unsimmedGameTime_out;
static float fixedFrameInterp_out;
static struct timeGlobalUBStruct
{
glm::vec4 ep_time_real;
glm::vec4 ep_time_game;
glm::vec4 ep_time_sinreal;
glm::vec4 ep_time_singame;
glm::vec4 ep_time_cosreal;
glm::vec4 ep_time_cosgame;
} timeGlobalUBData;
static Enterprise::Graphics::UniformBufferHandle timeGlobalUB;
bool Time::inFixedTimestep() { return inFixedTimestep_out; }
float Time::RealTime() { return realRunningTime_out; }
float Time::GameTime() { return gameRunningTime_out; }
float Time::RealDelta() { return realDelta_out; }
float Time::GameDelta() { return gameDelta_out; }
float Time::RealRemainder() { return unsimmedRealTime_out; }
float Time::GameRemainder() { return unsimmedGameTime_out; }
float Time::FixedFrameInterp() { return fixedFrameInterp_out; }
void Time::SetTimeScale(double scalar)
{
if (scalar >= 0.0f)
{
currentTimeScale = scalar;
}
else
{
EP_WARN("Time::SetTimeScale(): 'scalar' set to negative value. Set to 0.0 instead.");
currentTimeScale = 0.0f;
}
fixedTimestepInRealTicks = SecondsToTicks(Constants::Time::FixedTimestep / currentTimeScale);
}
void Time::Init()
{
PlatformInit();
#ifdef EP_CONFIG_DIST
maxFrameDeltaInRealTicks = SecondsToTicks(Constants::Time::MaxFrameDelta / currentTimeScale);
fixedTimestepInRealTicks = SecondsToTicks(Constants::Time::FixedTimestep / currentTimeScale);
fixedTimestepInGameTicks = SecondsToTicks(Constants::Time::FixedTimestep);
#endif
timeGlobalUB = Graphics::CreateUniformBuffer(HN("EP_TIME"), sizeof(timeGlobalUBStruct));
}
void Time::Cleanup()
{
Graphics::DeleteUniformBuffer(timeGlobalUB);
}
bool Time::ProcessFixedUpdate()
{
#ifdef EP_CONFIG_DIST
if (unsimmedGameTicks >= fixedTimestepInGameTicks)
{
// Going to FixedUpdate()
unsimmedRealTicks -= fixedTimestepInRealTicks;
unsimmedGameTicks -= fixedTimestepInGameTicks;
#else
if (unsimmedGameTicks >= SecondsToTicks(Constants::Time::FixedTimestep))
{
// Going to FixedUpdate()
unsimmedRealTicks -= SecondsToTicks(Constants::Time::FixedTimestep / currentTimeScale);
unsimmedGameTicks -= SecondsToTicks(Constants::Time::FixedTimestep);
#endif
realRunningTime_out = TicksToSeconds(realRunningTicks - unsimmedRealTicks);
gameRunningTime_out = TicksToSeconds(gameRunningTicks - unsimmedGameTicks);
return true;
}
else
{
// Going to Update()
inFixedTimestep_out = false;
realRunningTime_out = TicksToSeconds(realRunningTicks);
gameRunningTime_out = TicksToSeconds(gameRunningTicks);
realDelta_out = TicksToSeconds(measuredRealTickDelta);
gameDelta_out = TicksToSeconds(measuredGameTickDelta);
unsimmedRealTime_out = TicksToSeconds(unsimmedRealTicks);
unsimmedGameTime_out = TicksToSeconds(unsimmedGameTicks);
#ifdef EP_CONFIG_DIST
fixedFrameInterp_out = double(unsimmedGameTicks) / double(fixedTimestepInGameTicks);
#else
fixedFrameInterp_out = TicksToSeconds(unsimmedGameTicks) / Constants::Time::FixedTimestep;
#endif
return false;
}
}
void Time::Update()
{
previousSysTimeInTicks = currentSysTimeInTicks;
currentSysTimeInTicks = GetRawTicks();
#ifdef EP_CONFIG_DIST
measuredRealTickDelta = std::min(currentSysTimeInTicks - previousSysTimeInTicks, maxFrameDeltaInRealTicks);
#else
measuredRealTickDelta = std::min(currentSysTimeInTicks - previousSysTimeInTicks, SecondsToTicks(Constants::Time::MaxFrameDelta / currentTimeScale));
#endif
measuredGameTickDelta = measuredRealTickDelta * currentTimeScale;
realRunningTicks += measuredRealTickDelta;
gameRunningTicks += measuredGameTickDelta;
unsimmedRealTicks += measuredRealTickDelta;
unsimmedGameTicks += measuredGameTickDelta;
// Going to FixedUpdate()
inFixedTimestep_out = true;
#ifdef EP_CONFIG_DIST
realDelta_out = TicksToSeconds(fixedTimestepInRealTicks);
#else
realDelta_out = TicksToSeconds(SecondsToTicks(Constants::Time::FixedTimestep / currentTimeScale));
#endif
gameDelta_out = Constants::Time::FixedTimestep;
unsimmedRealTime_out = 0.0f;
unsimmedGameTime_out = 0.0f;
fixedFrameInterp_out = 0.0f;
// Update time variables in shader uniform buffer
timeGlobalUBData.ep_time_real.x = realRunningTime_out / 20;
timeGlobalUBData.ep_time_real.y = realRunningTime_out;
timeGlobalUBData.ep_time_real.z = realRunningTime_out * 2;
timeGlobalUBData.ep_time_real.w = realRunningTime_out * 3;
timeGlobalUBData.ep_time_game.x = gameRunningTime_out / 20;
timeGlobalUBData.ep_time_game.y = gameRunningTime_out;
timeGlobalUBData.ep_time_game.z = gameRunningTime_out * 2;
timeGlobalUBData.ep_time_game.w = gameRunningTime_out * 3;
timeGlobalUBData.ep_time_sinreal.x = glm::sin(realRunningTime_out / 8);
timeGlobalUBData.ep_time_sinreal.y = glm::sin(realRunningTime_out / 4);
timeGlobalUBData.ep_time_sinreal.z = glm::sin(realRunningTime_out / 2);
timeGlobalUBData.ep_time_sinreal.w = glm::sin(realRunningTime_out);
timeGlobalUBData.ep_time_singame.x = glm::sin(gameRunningTime_out / 8);
timeGlobalUBData.ep_time_singame.y = glm::sin(gameRunningTime_out / 4);
timeGlobalUBData.ep_time_singame.z = glm::sin(gameRunningTime_out / 2);
timeGlobalUBData.ep_time_singame.w = glm::sin(gameRunningTime_out);
timeGlobalUBData.ep_time_cosreal.x = glm::cos(realRunningTime_out / 8);
timeGlobalUBData.ep_time_cosreal.y = glm::cos(realRunningTime_out / 4);
timeGlobalUBData.ep_time_cosreal.z = glm::cos(realRunningTime_out / 2);
timeGlobalUBData.ep_time_cosreal.w = glm::cos(realRunningTime_out);
timeGlobalUBData.ep_time_cosgame.x = glm::cos(gameRunningTime_out / 8);
timeGlobalUBData.ep_time_cosgame.y = glm::cos(gameRunningTime_out / 4);
timeGlobalUBData.ep_time_cosgame.z = glm::cos(gameRunningTime_out / 2);
timeGlobalUBData.ep_time_cosgame.w = glm::cos(gameRunningTime_out);
Graphics::SetUniformBufferData(timeGlobalUB, &timeGlobalUBData);
}
bool Time::isFixedUpdatePending()
{
#ifdef EP_CONFIG_DIST
return unsimmedGameTicks / fixedTimestepInGameTicks;
#else
return unsimmedGameTicks / SecondsToTicks(Constants::Time::FixedTimestep);
#endif
}
float Time::ActualRealDelta()
{
return TicksToSeconds(measuredRealTickDelta);
}
| 33.626866
| 149
| 0.802486
|
theOtherMichael
|
ded73efd2f98c074186f084b6a378806ec7572fa
| 927
|
cpp
|
C++
|
DP/Cut_rod_example.cpp
|
obviouskkk/leetcode
|
5d25c3080fdc9f68ae79e0f4655a474a51ff01fc
|
[
"BSD-3-Clause"
] | null | null | null |
DP/Cut_rod_example.cpp
|
obviouskkk/leetcode
|
5d25c3080fdc9f68ae79e0f4655a474a51ff01fc
|
[
"BSD-3-Clause"
] | null | null | null |
DP/Cut_rod_example.cpp
|
obviouskkk/leetcode
|
5d25c3080fdc9f68ae79e0f4655a474a51ff01fc
|
[
"BSD-3-Clause"
] | null | null | null |
/* ***********************************************************************
> File Name: Cut_rod_example.cpp
> Author: zzy
> Mail: 942744575@qq.com
> Created Time: Sun 03 Mar 2019 03:17:27 PM CST
********************************************************************** */
/*
* 不同长度的钢条,具有不同的价值,而切割工序没有成本支出,公司管理层希望知道最佳切割方案.
* 假定钢条的长度均为整数:用数组v[I]表示钢条长度为I所具有的价值v[] = {0,1,5,8,9,10,17,17,20,24,30};用r[I]表示长度为I的钢条能获取的最大价值。
*/
#include<bits/stdc++.h>
int cut_rod(std::vector<int>& v) {
int length = v.size();
int r[length] = {0};
for (int i = 0; i < length; ++i) {
int profit = 0;
for (int j = 1; j <= i; ++j) {
profit = std::max(profit, v[j] + r[i - j]);
}
r[i] = profit;
printf("%d %d\n", i, r[i]);
}
return r[length-1];
}
int main()
{
std::vector<int> a{0,1,5,8,9,10,17,17,20};
//std::vector<int> a{0,1,5,8,9,10,17,17,20,24,30};
int max = cut_rod(a);
printf("max is %d\n", max);
return 0;
}
| 23.175
| 95
| 0.488673
|
obviouskkk
|
ded793c27eb89f826a9204701ae3d557dbcfd876
| 21,198
|
cpp
|
C++
|
tests/eosio.limitauth_tests.cpp
|
guilledk/mandel-contracts
|
0d452a3b45404a57f039c8a944534be1368032be
|
[
"MIT"
] | 8
|
2022-01-06T19:55:54.000Z
|
2022-03-25T07:11:36.000Z
|
tests/eosio.limitauth_tests.cpp
|
gofractally/mandel-contracts
|
0d452a3b45404a57f039c8a944534be1368032be
|
[
"MIT"
] | 6
|
2022-01-06T17:59:06.000Z
|
2022-01-31T15:25:15.000Z
|
tests/eosio.limitauth_tests.cpp
|
gofractally/mandel-contracts
|
0d452a3b45404a57f039c8a944534be1368032be
|
[
"MIT"
] | 8
|
2022-01-13T21:27:23.000Z
|
2022-03-25T07:11:42.000Z
|
#include <Runtime/Runtime.h>
#include <boost/test/unit_test.hpp>
#include <cstdlib>
#include <eosio/chain/contract_table_objects.hpp>
#include <eosio/chain/exceptions.hpp>
#include <eosio/chain/global_property_object.hpp>
#include <eosio/chain/resource_limits.hpp>
#include <eosio/chain/wast_to_wasm.hpp>
#include <fc/log/logger.hpp>
#include <iostream>
#include <sstream>
#include "eosio.system_tester.hpp"
using namespace eosio_system;
inline const auto owner = "owner"_n;
inline const auto active = "active"_n;
inline const auto admin = "admin"_n;
inline const auto admin2 = "admin2"_n;
inline const auto freebie = "freebie"_n;
inline const auto freebie2 = "freebie2"_n;
inline const auto alice = "alice1111111"_n;
inline const auto bob = "bob111111111"_n;
struct limitauth_tester: eosio_system_tester {
action_result push_action(name code, name action, permission_level auth, const variant_object& data) {
try {
TESTER::push_action(code, action, {auth}, data);
return "";
} catch (const fc::exception& ex) {
edump((ex.to_detail_string()));
return ex.top_message();
}
}
action_result limitauthchg(permission_level pl, const name& account, const std::vector<name>& allow_perms, const std::vector<name>& disallow_perms) {
return push_action(
config::system_account_name, "limitauthchg"_n, pl,
mvo()("account", account)("allow_perms", allow_perms)("disallow_perms", disallow_perms));
}
template<typename... Ts>
action_result push_action_raw(name code, name act, permission_level pl, const Ts&... data) {
try {
fc::datastream<size_t> sz;
(fc::raw::pack(sz, data), ...);
std::vector<char> vec(sz.tellp());
fc::datastream<char*> ds(vec.data(), size_t(vec.size()));
(fc::raw::pack(ds, data), ...);
signed_transaction trx;
trx.actions.push_back(action{{pl}, code, act, std::move(vec)});
set_transaction_headers(trx, DEFAULT_EXPIRATION_DELTA, 0);
trx.sign(get_private_key(pl.actor, pl.permission.to_string()), control->get_chain_id());
push_transaction(trx);
return "";
} catch (const fc::exception& ex) {
edump((ex.to_detail_string()));
return ex.top_message();
}
}
/////////////
// This set tests using the native abi (no authorized_by)
action_result updateauth(permission_level pl, name account, name permission, name parent, authority auth) {
return push_action_raw(
config::system_account_name, "updateauth"_n, pl, account, permission, parent, auth);
}
action_result deleteauth(permission_level pl, name account, name permission) {
return push_action_raw(
config::system_account_name, "deleteauth"_n, pl, account, permission);
}
action_result linkauth(permission_level pl, name account, name code, name type, name requirement) {
return push_action_raw(
config::system_account_name, "linkauth"_n, pl, account, code, type, requirement);
}
action_result unlinkauth(permission_level pl, name account, name code, name type) {
return push_action_raw(
config::system_account_name, "unlinkauth"_n, pl, account, code, type);
}
/////////////
// This set tests using the extended abi (includes authorized_by)
action_result updateauth(permission_level pl, name account, name permission, name parent, authority auth, name authorized_by) {
return push_action_raw(
config::system_account_name, "updateauth"_n, pl, account, permission, parent, auth, authorized_by);
}
action_result deleteauth(permission_level pl, name account, name permission, name authorized_by) {
return push_action_raw(
config::system_account_name, "deleteauth"_n, pl, account, permission, authorized_by);
}
action_result linkauth(permission_level pl, name account, name code, name type, name requirement, name authorized_by) {
return push_action_raw(
config::system_account_name, "linkauth"_n, pl, account, code, type, requirement, authorized_by);
}
action_result unlinkauth(permission_level pl, name account, name code, name type, name authorized_by) {
return push_action_raw(
config::system_account_name, "unlinkauth"_n, pl, account, code, type, authorized_by);
}
}; // limitauth_tester
BOOST_AUTO_TEST_SUITE(eosio_system_limitauth_tests)
// alice hasn't opted in; she can still use the native abi (no authorized_by)
BOOST_FIXTURE_TEST_CASE(native_tests, limitauth_tester) try {
BOOST_REQUIRE_EQUAL(
"",
updateauth({alice, active}, alice, freebie, active, get_public_key(alice, "freebie")));
BOOST_REQUIRE_EQUAL(
"",
linkauth({alice, active}, alice, "eosio.null"_n, "noop"_n, freebie));
// alice@freebie can create alice@freebie2
BOOST_REQUIRE_EQUAL(
"",
updateauth({alice, freebie}, alice, freebie2, freebie, get_public_key(alice, "freebie2")));
// alice@freebie can linkauth
BOOST_REQUIRE_EQUAL(
"",
linkauth({alice, freebie}, alice, "eosio.null"_n, "noop"_n, freebie2));
// alice@freebie can unlinkauth
BOOST_REQUIRE_EQUAL(
"",
unlinkauth({alice, freebie}, alice, "eosio.null"_n, "noop"_n));
// alice@freebie can delete alice@freebie2
BOOST_REQUIRE_EQUAL(
"",
deleteauth({alice, freebie}, alice, freebie2));
// bob, who has the published freebie key, attacks
BOOST_REQUIRE_EQUAL(
"",
updateauth({alice, freebie}, alice, freebie, active, get_public_key(bob, "attack")));
} // native_tests
FC_LOG_AND_RETHROW()
// alice hasn't opted in; she can use the extended abi, but set authorized_by to empty
BOOST_FIXTURE_TEST_CASE(extended_empty_tests, limitauth_tester) try {
BOOST_REQUIRE_EQUAL(
"",
updateauth({alice, active}, alice, freebie, active, get_public_key(alice, "freebie"), ""_n));
BOOST_REQUIRE_EQUAL(
"",
linkauth({alice, active}, alice, "eosio.null"_n, "noop"_n, freebie, ""_n));
// alice@freebie can create alice@freebie2
BOOST_REQUIRE_EQUAL(
"",
updateauth({alice, freebie}, alice, freebie2, freebie, get_public_key(alice, "freebie2"), ""_n));
// alice@freebie can linkauth
BOOST_REQUIRE_EQUAL(
"",
linkauth({alice, freebie}, alice, "eosio.null"_n, "noop"_n, freebie2, ""_n));
// alice@freebie can unlinkauth
BOOST_REQUIRE_EQUAL(
"",
unlinkauth({alice, freebie}, alice, "eosio.null"_n, "noop"_n, ""_n));
// alice@freebie can delete alice@freebie2
BOOST_REQUIRE_EQUAL(
"",
deleteauth({alice, freebie}, alice, freebie2, ""_n));
// bob, who has the published freebie key, attacks
BOOST_REQUIRE_EQUAL(
"",
updateauth({alice, freebie}, alice, freebie, active, get_public_key(bob, "attack"), ""_n));
} // extended_empty_tests
FC_LOG_AND_RETHROW()
// alice hasn't opted in; she can use the extended abi, but set authorized_by to matching values
BOOST_FIXTURE_TEST_CASE(extended_matching_tests, limitauth_tester) try {
BOOST_REQUIRE_EQUAL(
"missing authority of alice1111111/owner",
updateauth({alice, active}, alice, freebie, active, get_public_key(alice, "freebie"), owner));
BOOST_REQUIRE_EQUAL(
"",
updateauth({alice, active}, alice, freebie, active, get_public_key(alice, "freebie"), active));
BOOST_REQUIRE_EQUAL(
"missing authority of alice1111111/owner",
linkauth({alice, active}, alice, "eosio.null"_n, "noop"_n, freebie, owner));
BOOST_REQUIRE_EQUAL(
"",
linkauth({alice, active}, alice, "eosio.null"_n, "noop"_n, freebie, active));
// alice@freebie can create alice@freebie2
BOOST_REQUIRE_EQUAL(
"",
updateauth({alice, freebie}, alice, freebie2, freebie, get_public_key(alice, "freebie2"), freebie));
// alice@freebie can linkauth
BOOST_REQUIRE_EQUAL(
"",
linkauth({alice, freebie}, alice, "eosio.null"_n, "noop"_n, freebie2, freebie));
// alice@freebie can unlinkauth
BOOST_REQUIRE_EQUAL(
"missing authority of alice1111111/active",
unlinkauth({alice, freebie}, alice, "eosio.null"_n, "noop"_n, active));
BOOST_REQUIRE_EQUAL(
"",
unlinkauth({alice, freebie}, alice, "eosio.null"_n, "noop"_n, freebie));
// alice@freebie can delete alice@freebie2
BOOST_REQUIRE_EQUAL(
"missing authority of alice1111111/active",
deleteauth({alice, freebie}, alice, freebie2, active));
BOOST_REQUIRE_EQUAL(
"",
deleteauth({alice, freebie}, alice, freebie2, freebie));
// bob, who has the published freebie key, attacks
BOOST_REQUIRE_EQUAL(
"",
updateauth({alice, freebie}, alice, freebie, active, get_public_key(bob, "attack"), freebie));
} // extended_matching_tests
FC_LOG_AND_RETHROW()
// alice protects her account using allow_perms
BOOST_FIXTURE_TEST_CASE(allow_perms_tests, limitauth_tester) try {
BOOST_REQUIRE_EQUAL(
"missing authority of alice1111111",
limitauthchg({bob, active}, alice, {owner, active, admin}, {}));
BOOST_REQUIRE_EQUAL(
"assertion failure with message: allow_perms does not contain owner",
limitauthchg({alice, active}, alice, {active, admin}, {}));
BOOST_REQUIRE_EQUAL(
"",
limitauthchg({alice, active}, alice, {owner, active, admin}, {}));
BOOST_REQUIRE_EQUAL(
"",
updateauth({alice, active}, alice, freebie, active, get_public_key(alice, "freebie"), active));
BOOST_REQUIRE_EQUAL(
"",
updateauth({alice, active}, alice, admin, active, get_public_key(alice, "admin"), active));
BOOST_REQUIRE_EQUAL(
"",
linkauth({alice, active}, alice, "eosio.null"_n, "noop"_n, freebie, active));
BOOST_REQUIRE_EQUAL(
"",
linkauth({alice, active}, alice, "eosio.null"_n, "dosomething"_n, admin, active));
// Bob, who has the published freebie key, tries using updateauth to modify alice@freebie
BOOST_REQUIRE_EQUAL(
"assertion failure with message: authorized_by is required for this account",
updateauth({alice, freebie}, alice, freebie, active, get_public_key(bob, "attack")));
BOOST_REQUIRE_EQUAL(
"assertion failure with message: authorized_by is required for this account",
updateauth({alice, freebie}, alice, freebie, active, get_public_key(bob, "attack"), ""_n));
BOOST_REQUIRE_EQUAL(
"assertion failure with message: authorized_by does not appear in allow_perms",
updateauth({alice, freebie}, alice, freebie, active, get_public_key(bob, "attack"), freebie));
BOOST_REQUIRE_EQUAL(
"missing authority of alice1111111/active",
updateauth({alice, freebie}, alice, freebie, active, get_public_key(bob, "attack"), active));
// alice@freebie can't create alice@freebie2
BOOST_REQUIRE_EQUAL(
"assertion failure with message: authorized_by does not appear in allow_perms",
updateauth({alice, freebie}, alice, freebie2, freebie, get_public_key(alice, "freebie2"), freebie));
// alice@active can create alice@freebie2
BOOST_REQUIRE_EQUAL(
"",
updateauth({alice, active}, alice, freebie2, freebie, get_public_key(alice, "freebie2"), active));
// Bob, who has the published freebie key, tries using linkauth
BOOST_REQUIRE_EQUAL(
"assertion failure with message: authorized_by is required for this account",
linkauth({alice, freebie}, alice, "eosio.null"_n, "noop"_n, freebie2));
BOOST_REQUIRE_EQUAL(
"assertion failure with message: authorized_by is required for this account",
linkauth({alice, freebie}, alice, "eosio.null"_n, "noop"_n, freebie2, ""_n));
BOOST_REQUIRE_EQUAL(
"assertion failure with message: authorized_by does not appear in allow_perms",
linkauth({alice, freebie}, alice, "eosio.null"_n, "noop"_n, freebie2, freebie));
BOOST_REQUIRE_EQUAL(
"missing authority of alice1111111/active",
linkauth({alice, freebie}, alice, "eosio.null"_n, "noop"_n, freebie2, active));
// Bob, who has the published freebie key, tries using deleteauth
BOOST_REQUIRE_EQUAL(
"assertion failure with message: authorized_by is required for this account",
deleteauth({alice, freebie}, alice, freebie2));
BOOST_REQUIRE_EQUAL(
"assertion failure with message: authorized_by is required for this account",
deleteauth({alice, freebie}, alice, freebie2, ""_n));
BOOST_REQUIRE_EQUAL(
"assertion failure with message: authorized_by does not appear in allow_perms",
deleteauth({alice, freebie}, alice, freebie2, freebie));
BOOST_REQUIRE_EQUAL(
"missing authority of alice1111111/owner",
deleteauth({alice, freebie}, alice, freebie2, owner));
// Bob, who has the published freebie key, tries using unlinkauth
BOOST_REQUIRE_EQUAL(
"assertion failure with message: authorized_by is required for this account",
unlinkauth({alice, freebie}, alice, "eosio.null"_n, "noop"_n));
BOOST_REQUIRE_EQUAL(
"assertion failure with message: authorized_by is required for this account",
unlinkauth({alice, freebie}, alice, "eosio.null"_n, "noop"_n, ""_n));
BOOST_REQUIRE_EQUAL(
"assertion failure with message: authorized_by does not appear in allow_perms",
unlinkauth({alice, freebie}, alice, "eosio.null"_n, "noop"_n, freebie));
BOOST_REQUIRE_EQUAL(
"missing authority of alice1111111/active",
unlinkauth({alice, freebie}, alice, "eosio.null"_n, "noop"_n, active));
// alice@admin can do these
BOOST_REQUIRE_EQUAL(
"",
updateauth({alice, admin}, alice, admin2, admin, get_public_key(alice, "admin2"), admin));
BOOST_REQUIRE_EQUAL(
"",
linkauth({alice, admin}, alice, "eosio.null"_n, "dosomething"_n, admin2, admin));
BOOST_REQUIRE_EQUAL(
"",
unlinkauth({alice, admin}, alice, "eosio.null"_n, "dosomething"_n, admin));
BOOST_REQUIRE_EQUAL(
"",
deleteauth({alice, admin}, alice, admin2, admin));
// alice@active can do these
BOOST_REQUIRE_EQUAL(
"",
updateauth({alice, active}, alice, admin2, admin, get_public_key(alice, "admin2"), active));
BOOST_REQUIRE_EQUAL(
"",
linkauth({alice, active}, alice, "eosio.null"_n, "dosomething"_n, admin2, active));
BOOST_REQUIRE_EQUAL(
"",
unlinkauth({alice, active}, alice, "eosio.null"_n, "dosomething"_n, active));
BOOST_REQUIRE_EQUAL(
"",
deleteauth({alice, active}, alice, admin2, active));
// alice@owner can do these
BOOST_REQUIRE_EQUAL(
"",
updateauth({alice, owner}, alice, admin2, admin, get_public_key(alice, "admin2"), owner));
BOOST_REQUIRE_EQUAL(
"",
linkauth({alice, owner}, alice, "eosio.null"_n, "dosomething"_n, admin2, owner));
BOOST_REQUIRE_EQUAL(
"",
unlinkauth({alice, owner}, alice, "eosio.null"_n, "dosomething"_n, owner));
BOOST_REQUIRE_EQUAL(
"",
deleteauth({alice, owner}, alice, admin2, owner));
} // allow_perms_tests
FC_LOG_AND_RETHROW()
// alice protects her account using disallow_perms
BOOST_FIXTURE_TEST_CASE(disallow_perms_tests, limitauth_tester) try {
BOOST_REQUIRE_EQUAL(
"missing authority of alice1111111",
limitauthchg({bob, active}, alice, {}, {freebie, freebie2}));
BOOST_REQUIRE_EQUAL(
"assertion failure with message: disallow_perms contains owner",
limitauthchg({alice, active}, alice, {}, {freebie, owner, freebie2}));
BOOST_REQUIRE_EQUAL(
"",
limitauthchg({alice, active}, alice, {}, {freebie, freebie2}));
BOOST_REQUIRE_EQUAL(
"",
updateauth({alice, active}, alice, freebie, active, get_public_key(alice, "freebie"), active));
BOOST_REQUIRE_EQUAL(
"",
updateauth({alice, active}, alice, admin, active, get_public_key(alice, "admin"), active));
BOOST_REQUIRE_EQUAL(
"",
linkauth({alice, active}, alice, "eosio.null"_n, "noop"_n, freebie, active));
BOOST_REQUIRE_EQUAL(
"",
linkauth({alice, active}, alice, "eosio.null"_n, "dosomething"_n, admin, active));
// Bob, who has the published freebie key, tries using updateauth to modify alice@freebie
BOOST_REQUIRE_EQUAL(
"assertion failure with message: authorized_by is required for this account",
updateauth({alice, freebie}, alice, freebie, active, get_public_key(bob, "attack")));
BOOST_REQUIRE_EQUAL(
"assertion failure with message: authorized_by is required for this account",
updateauth({alice, freebie}, alice, freebie, active, get_public_key(bob, "attack"), ""_n));
BOOST_REQUIRE_EQUAL(
"assertion failure with message: authorized_by appears in disallow_perms",
updateauth({alice, freebie}, alice, freebie, active, get_public_key(bob, "attack"), freebie));
BOOST_REQUIRE_EQUAL(
"missing authority of alice1111111/active",
updateauth({alice, freebie}, alice, freebie, active, get_public_key(bob, "attack"), active));
// alice@freebie can't create alice@freebie2
BOOST_REQUIRE_EQUAL(
"assertion failure with message: authorized_by appears in disallow_perms",
updateauth({alice, freebie}, alice, freebie2, freebie, get_public_key(alice, "freebie2"), freebie));
// alice@active can create alice@freebie2
BOOST_REQUIRE_EQUAL(
"",
updateauth({alice, active}, alice, freebie2, freebie, get_public_key(alice, "freebie2"), active));
// Bob, who has the published freebie key, tries using linkauth
BOOST_REQUIRE_EQUAL(
"assertion failure with message: authorized_by is required for this account",
linkauth({alice, freebie}, alice, "eosio.null"_n, "noop"_n, freebie2));
BOOST_REQUIRE_EQUAL(
"assertion failure with message: authorized_by is required for this account",
linkauth({alice, freebie}, alice, "eosio.null"_n, "noop"_n, freebie2, ""_n));
BOOST_REQUIRE_EQUAL(
"assertion failure with message: authorized_by appears in disallow_perms",
linkauth({alice, freebie}, alice, "eosio.null"_n, "noop"_n, freebie2, freebie));
BOOST_REQUIRE_EQUAL(
"missing authority of alice1111111/active",
linkauth({alice, freebie}, alice, "eosio.null"_n, "noop"_n, freebie2, active));
// Bob, who has the published freebie key, tries using deleteauth
BOOST_REQUIRE_EQUAL(
"assertion failure with message: authorized_by is required for this account",
deleteauth({alice, freebie}, alice, freebie2));
BOOST_REQUIRE_EQUAL(
"assertion failure with message: authorized_by is required for this account",
deleteauth({alice, freebie}, alice, freebie2, ""_n));
BOOST_REQUIRE_EQUAL(
"assertion failure with message: authorized_by appears in disallow_perms",
deleteauth({alice, freebie}, alice, freebie2, freebie));
BOOST_REQUIRE_EQUAL(
"missing authority of alice1111111/owner",
deleteauth({alice, freebie}, alice, freebie2, owner));
// Bob, who has the published freebie key, tries using unlinkauth
BOOST_REQUIRE_EQUAL(
"assertion failure with message: authorized_by is required for this account",
unlinkauth({alice, freebie}, alice, "eosio.null"_n, "noop"_n));
BOOST_REQUIRE_EQUAL(
"assertion failure with message: authorized_by is required for this account",
unlinkauth({alice, freebie}, alice, "eosio.null"_n, "noop"_n, ""_n));
BOOST_REQUIRE_EQUAL(
"assertion failure with message: authorized_by appears in disallow_perms",
unlinkauth({alice, freebie}, alice, "eosio.null"_n, "noop"_n, freebie));
BOOST_REQUIRE_EQUAL(
"missing authority of alice1111111/active",
unlinkauth({alice, freebie}, alice, "eosio.null"_n, "noop"_n, active));
// alice@admin can do these
BOOST_REQUIRE_EQUAL(
"",
updateauth({alice, admin}, alice, admin2, admin, get_public_key(alice, "admin2"), admin));
BOOST_REQUIRE_EQUAL(
"",
linkauth({alice, admin}, alice, "eosio.null"_n, "dosomething"_n, admin2, admin));
BOOST_REQUIRE_EQUAL(
"",
unlinkauth({alice, admin}, alice, "eosio.null"_n, "dosomething"_n, admin));
BOOST_REQUIRE_EQUAL(
"",
deleteauth({alice, admin}, alice, admin2, admin));
// alice@active can do these
BOOST_REQUIRE_EQUAL(
"",
updateauth({alice, active}, alice, admin2, admin, get_public_key(alice, "admin2"), active));
BOOST_REQUIRE_EQUAL(
"",
linkauth({alice, active}, alice, "eosio.null"_n, "dosomething"_n, admin2, active));
BOOST_REQUIRE_EQUAL(
"",
unlinkauth({alice, active}, alice, "eosio.null"_n, "dosomething"_n, active));
BOOST_REQUIRE_EQUAL(
"",
deleteauth({alice, active}, alice, admin2, active));
// alice@owner can do these
BOOST_REQUIRE_EQUAL(
"",
updateauth({alice, owner}, alice, admin2, admin, get_public_key(alice, "admin2"), owner));
BOOST_REQUIRE_EQUAL(
"",
linkauth({alice, owner}, alice, "eosio.null"_n, "dosomething"_n, admin2, owner));
BOOST_REQUIRE_EQUAL(
"",
unlinkauth({alice, owner}, alice, "eosio.null"_n, "dosomething"_n, owner));
BOOST_REQUIRE_EQUAL(
"",
deleteauth({alice, owner}, alice, admin2, owner));
} // disallow_perms_tests
FC_LOG_AND_RETHROW()
BOOST_AUTO_TEST_SUITE_END()
| 41.810651
| 152
| 0.688603
|
guilledk
|
ded885b9243bd911d25f242d9ddf53b2bf47b6aa
| 1,197
|
hh
|
C++
|
src/Common/fasta.hh
|
sagrudd/amos
|
47643a1d238bff83421892cb74daaf6fff8d9548
|
[
"Artistic-1.0"
] | 10
|
2015-03-20T18:25:56.000Z
|
2020-06-02T22:00:08.000Z
|
src/Common/fasta.hh
|
sagrudd/amos
|
47643a1d238bff83421892cb74daaf6fff8d9548
|
[
"Artistic-1.0"
] | 5
|
2015-05-14T17:51:20.000Z
|
2020-07-19T04:17:47.000Z
|
src/Common/fasta.hh
|
sagrudd/amos
|
47643a1d238bff83421892cb74daaf6fff8d9548
|
[
"Artistic-1.0"
] | 10
|
2015-05-17T16:01:23.000Z
|
2020-05-20T08:13:43.000Z
|
// A. L. Delcher
//
// File: fasta.h
//
// Last Modified: 25 November 2002
//
// Routines to manipulate FASTA format files
#ifndef __FASTA_HH
#define __FASTA_HH
#include "delcher.hh"
#include <string>
#include <vector>
#include <cstring>
const int DEFAULT_FASTA_WIDTH = 60;
// Max number of characters to print on a FASTA data line
char Complement
(char ch);
void Fasta_Print
(FILE * fp, const char * s, const char * hdr = NULL,
int fasta_width = DEFAULT_FASTA_WIDTH);
void Fasta_Print_N
(FILE * fp, const char * s, int n, const char * hdr = NULL,
int fasta_width = DEFAULT_FASTA_WIDTH);
void Fasta_Print_Skip
(FILE * fp, const char * s, const char * skip, const char * hdr = NULL,
int fasta_width = DEFAULT_FASTA_WIDTH);
bool Fasta_Qual_Read
(FILE * fp, std::string & q, std::string & hdr);
bool Fasta_Read
(FILE * fp, std::string & s, std::string & hdr);
void Reverse_Complement
(char * s);
void Reverse_Complement
(std::string & s);
void Reverse_String
(char * s);
void Reverse_String
(std::string & s);
int Fasta_Read_String (FILE *, char * &, long int &, char [], int);
#endif // #ifndef __FASTA_HH
| 23.019231
| 75
| 0.658312
|
sagrudd
|
dee150a933928bf6bfe92c09c1a8d382c686db74
| 2,651
|
hpp
|
C++
|
libs/ecs/include/GameplayManager.hpp
|
Sharpyfile/WARdrobe
|
7842d486f65c7a045771f9ef78c0655eda2d346a
|
[
"DOC"
] | null | null | null |
libs/ecs/include/GameplayManager.hpp
|
Sharpyfile/WARdrobe
|
7842d486f65c7a045771f9ef78c0655eda2d346a
|
[
"DOC"
] | null | null | null |
libs/ecs/include/GameplayManager.hpp
|
Sharpyfile/WARdrobe
|
7842d486f65c7a045771f9ef78c0655eda2d346a
|
[
"DOC"
] | 1
|
2021-03-21T16:52:22.000Z
|
2021-03-21T16:52:22.000Z
|
#pragma once
#include <cassert>
#include <memory>
#include <unordered_map>
#include <vector>
#include "ComponentManager.hpp"
#include "ECSTypes.hpp"
#include "EntityManager.hpp"
#include "SystemManager.hpp"
class GameplayManager
{
public:
void Init()
{
// Create pointers to each manager
componentManager = std::make_shared<ComponentManager>();
entityManager = std::make_shared<EntityManager>();
systemManager = std::make_shared<SystemManager>();
}
// Entity methods
Entity CreateEntity() { return entityManager->CreateEntity(); }
void DestroyEntity(Entity entity)
{
entityManager->DestroyEntity(entity);
componentManager->EntityDestroyed(entity);
systemManager->EntityDestroyed(entity);
}
// Component methods
template<typename T>
void RegisterComponent()
{
componentManager->RegisterComponent<T>();
}
template<typename T>
void AddComponent(Entity entity, T component)
{
componentManager->AddComponent<T>(entity, component);
auto signature = entityManager->GetSignature(entity);
signature.set(componentManager->GetComponentType<T>(), true);
entityManager->SetSignature(entity, signature);
systemManager->EntitySignatureChanged(entity, signature);
}
template<typename T>
void RemoveComponent(Entity entity)
{
componentManager->RemoveComponent<T>(entity);
auto signature = entityManager->GetSignature(entity);
signature.set(componentManager->GetComponentType<T>(), false);
entityManager->SetSignature(entity, signature);
systemManager->EntitySignatureChanged(entity, signature);
}
template<typename T>
T& GetComponent(Entity entity)
{
return componentManager->GetComponent<T>(entity);
}
template<typename T>
ComponentType GetComponentType()
{
return componentManager->GetComponentType<T>();
}
// System methods
template<typename T>
std::shared_ptr<T> RegisterSystem()
{
return systemManager->RegisterSystem<T>();
}
template<typename T>
void SetSystemSignature(Signature signature)
{
systemManager->SetSignature<T>(signature);
}
template<typename T>
void SetRequiredComponent(ComponentType componentType)
{
systemManager->SetRequiredComponent<T>(componentType);
}
void Update(float dt) { systemManager->Update(dt, componentManager); }
std::shared_ptr<ComponentManager> GetComponentManager()
{
return componentManager;
}
std::shared_ptr<EntityManager> GetEntityManager() { return entityManager; }
std::shared_ptr<SystemManager> GetSystemManager() { return systemManager; }
private:
std::shared_ptr<ComponentManager> componentManager;
std::shared_ptr<EntityManager> entityManager;
std::shared_ptr<SystemManager> systemManager;
};
| 24.1
| 76
| 0.763108
|
Sharpyfile
|
dee1db6933d541784cdb98aa468e12af688755d7
| 1,810
|
hpp
|
C++
|
lihowarlib/include/lihowarlib/io/ConfigSerializer.hpp
|
ludchieng/IMAC-Lihowar
|
e5f551ab9958fa7d8fa4cbe07d0aa3555842b4fb
|
[
"BSL-1.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | null | null | null |
lihowarlib/include/lihowarlib/io/ConfigSerializer.hpp
|
ludchieng/IMAC-Lihowar
|
e5f551ab9958fa7d8fa4cbe07d0aa3555842b4fb
|
[
"BSL-1.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | null | null | null |
lihowarlib/include/lihowarlib/io/ConfigSerializer.hpp
|
ludchieng/IMAC-Lihowar
|
e5f551ab9958fa7d8fa4cbe07d0aa3555842b4fb
|
[
"BSL-1.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | null | null | null |
/*
* Copyright (c) 2020-2021 Lihowar
*
* This software is licensed under OSEF License.
*
* The "Software" is defined as the pieces of code, the documentation files, the config
* files, the textures assets, the Wavefront OBJ assets, the screenshot image, the sound
* effects and music associated with.
*
* This Software is licensed under OSEF License which means IN ACCORDANCE WITH THE LICENSE
* OF THE DEPENDENCIES OF THE SOFTWARE, you can use it as you want for any purpose, but
* it comes with no guarantee of any kind, provided that you respects the license of the
* software dependencies of the piece of code you want to reuse. The dependencies are
* listed at the end of the README given in the directory root of the Lihowar repository.
*/
#pragma once
#ifndef LIHOWAR_CONFIGSERIALIZER_HPP
#define LIHOWAR_CONFIGSERIALIZER_HPP
#include <lihowarlib/io/Serializer.hpp>
#include <lihowarlib/exceptions/LihowarIOException.hpp>
namespace lihowar {
/**
* @brief Singleton class to handle JSON config files loading
*/
class ConfigSerializer : public Serializer {
private: // singleton
// CONSTRUCTORS & DESTRUCTORS
/**
* @brief ConfigSerializer class default constructor
*/
ConfigSerializer() : Serializer() {}
public:
// INTERFACE
/**
* @brief Retrieves global configuration variables from JSON file
* @param configFilePath Path to config file
*/
static void load(const std::string &configFilePath)
{
try {
instance()._data = tao::json::parse_file(configFilePath);
} catch (tao::json_pegtl::input_error &err) {
throw LihowarIOException("Unable to read a valid json config file at: " + configFilePath, __FILE__, __LINE__);
}
}
};
}
#endif //LIHOWAR_CONFIGSERIALIZER_HPP
| 30.677966
| 122
| 0.712155
|
ludchieng
|
dee8f55e6a4095f23c71dc5914919940c8bfd820
| 8,986
|
cpp
|
C++
|
tests/FileSender.cpp
|
catid/tonk
|
e993c9b7d1bf14bd510739036e022cf24c3ecf3c
|
[
"BSD-3-Clause"
] | 91
|
2018-09-14T12:35:50.000Z
|
2021-12-24T18:09:35.000Z
|
tests/FileSender.cpp
|
catid/tonk
|
e993c9b7d1bf14bd510739036e022cf24c3ecf3c
|
[
"BSD-3-Clause"
] | 6
|
2018-09-15T00:30:37.000Z
|
2018-09-18T17:58:22.000Z
|
tests/FileSender.cpp
|
catid/tonk
|
e993c9b7d1bf14bd510739036e022cf24c3ecf3c
|
[
"BSD-3-Clause"
] | 9
|
2018-09-14T14:04:16.000Z
|
2022-03-22T14:36:45.000Z
|
/*
Copyright (c) 2018 Christopher A. Taylor. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of Tonkinese nor the names of its contributors may be
used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
/**
FileSender
This sends files to the FileReceiver. It sends the file to each client
that connects.
It is incompatible with P2PFileReceiver.
*/
#include "tonk.h"
#include "tonk_file_transfer.h"
#include "TonkCppSDK.h"
#include "Logger.h"
#include <stdio.h> // getchar
static logger::Channel Logger("FileSender", logger::Level::Debug);
// Port for FileSender server to listen on
static const uint16_t kFileSenderServerPort = 10333;
// Size of a file chunk in bytes
static const unsigned kFileChunkBytes = 32768;
class MyServer;
class MyServerConnection : public tonk::SDKConnection
{
MyServer* Server = nullptr;
TonkFile File = nullptr;
uint64_t LastReportUsec = 0;
public:
MyServerConnection(MyServer* server)
: Server(server)
{}
void OnConnect() override;
void OnData(
uint32_t channel, // Channel number attached to each message by sender
const uint8_t* data, // Pointer to a buffer containing the message data
uint32_t bytes // Number of bytes in the message
) override;
void OnTick(
uint64_t nowUsec // Current timestamp in microseconds
) override;
void OnClose(
const tonk::SDKJsonResult& reason
) override;
void StartSending();
};
class MyServer : public tonk::SDKSocket
{
public:
std::string FileSendPath, FileSendName;
bool Initialize(
const std::string& fileSendPath,
const std::string& fileSendName);
// SDKSocket:
tonk::SDKConnection* OnIncomingConnection(const TonkAddress& address) override;
void OnAdvertisement(
const std::string& ipString, ///< Source IP address of advertisement
uint16_t port, ///< Source port address of advertisement
const uint8_t* data, ///< Pointer to a buffer containing the message data
uint32_t bytes) override; ///< Number of bytes in the message
};
void MyServerConnection::StartSending()
{
File = tonk_file_from_disk(
GetRawConnection(),
TonkChannel_LowPri0,
Server->FileSendName.c_str(),
Server->FileSendPath.c_str());
if (File == nullptr) {
Logger.Error("Failed to map source file ", Server->FileSendPath);
return;
}
Logger.Debug("Successfully mapped ", Server->FileSendPath, " for file data");
tonk_file_send(File);
}
void MyServerConnection::OnConnect()
{
auto status = GetStatusEx();
Logger.Info("Connected to ", status.Remote.NetworkString, " : ", status.Remote.UDPPort);
StartSending();
}
void MyServerConnection::OnData(
uint32_t channel, // Channel number attached to each message by sender
const uint8_t* data, // Pointer to a buffer containing the message data
uint32_t bytes // Number of bytes in the message
)
{
if (channel == TonkChannel_Reliable1 && bytes == 9)
{
uint8_t pong_message[1 + 8 + 3];
pong_message[0] = 78;
for (int i = 0; i < 8; ++i) {
pong_message[i + 1] = data[i + 1];
}
uint32_t remoteTS23 = ToRemoteTime23(tonk_time());
tonk::WriteU24_LE(pong_message + 1 + 8, remoteTS23);
Send(pong_message, 1 + 8 + 3, channel);
}
}
void MyServerConnection::OnTick(
uint64_t nowUsec // Current timestamp in microseconds
)
{
if (File)
{
tonk_file_send(File);
// If transfer is done we need to call tonk_file_free().
if (File->Flags & TonkFileFlags_Done)
{
if (File->Flags & TonkFileFlags_Failed) {
Logger.Error("File transfer failed");
}
else {
Logger.Info("File transfer completed");
}
tonk_file_free(File);
File = nullptr;
// Start sending the next file
//StartSending();
}
// Periodically report progress
if (File && nowUsec - LastReportUsec > 1000000)
{
LastReportUsec = nowUsec;
Logger.Info("File(", File->Name, ") progress: ", File->ProgressBytes, " / ", File->TotalBytes,
" Bytes (", File->ProgressBytes * 100 / (float)File->TotalBytes,
"%). Received by peer at ", GetStatusEx().PeerSeenBPS / 1000.0, " KBPS");
}
}
}
void MyServerConnection::OnClose(
const tonk::SDKJsonResult& reason
)
{
auto status = GetStatusEx();
tonk_file_free(File);
Logger.Info("Disconnected from ", status.Remote.NetworkString, " : ", status.Remote.UDPPort, " - Reason = ", reason.ToString());
}
bool MyServer::Initialize(
const std::string& fileSendPath,
const std::string& fileSendName)
{
FileSendPath = fileSendPath;
FileSendName = fileSendName;
// Set configuration
Config.UDPListenPort = kFileSenderServerPort;
Config.MaximumClients = 10;
//Config.EnableFEC = 0;
//Config.InterfaceAddress = "127.0.0.1";
Config.BandwidthLimitBPS = 1000 * 1000 * 1000;
tonk::SDKJsonResult result = Create();
if (!result) {
Logger.Error("Unable to create socket: ", result.ToString());
return false;
}
return true;
}
tonk::SDKConnection* MyServer::OnIncomingConnection(
const TonkAddress& address ///< Address of the client requesting a connection
)
{
auto ptr = std::make_shared<MyServerConnection>(this);
// Keep object alive
ptr->SetSelfReference();
return ptr.get();
}
void MyServer::OnAdvertisement(
const std::string& ipString, ///< Source IP address of advertisement
uint16_t port, ///< Source port address of advertisement
const uint8_t* data, ///< Pointer to a buffer containing the message data
uint32_t bytes) ///< Number of bytes in the message
{
if (bytes != 1) {
return;
}
if (data[0] == 100)
{
Logger.Info("Advertisement PING received from ", ipString, ":", port, " - ", bytes, " bytes");
uint8_t pong[1] = {
200
};
Advertise(ipString, port, pong, 1);
return;
}
if (data[0] == 200)
{
Logger.Info("Advertisement PONG received from ", ipString, ":", port, " - ", bytes, " bytes");
return;
}
}
// Binary file to send
static const char* kFileSendPath = "sendfile.bin";
// Name at the receiver side
static const char* kFileSendName = "download.bin";
int main(int argc, char** argv)
{
std::string fileSendPath = kFileSendPath, fileSendName = kFileSendName;
if (argc >= 2) {
fileSendPath = argv[1];
Logger.Info("Using file send path: ", fileSendPath);
}
if (argc >= 3) {
fileSendName = argv[2];
Logger.Info("Using file send name: ", fileSendName);
}
{
MyServer server;
if (server.Initialize(fileSendPath, fileSendName)) {
Logger.Debug("File sending server started on port ", kFileSenderServerPort,
". Now start the file receiver client to receive a file");
}
else {
Logger.Debug("File sending server failed to start");
}
Logger.Debug("Press ENTER key to stop the server.");
::getchar();
}
Logger.Debug("Press ENTER key to terminate.");
::getchar();
Logger.Debug("...Key press detected. Terminating..");
return 0;
}
| 29.462295
| 132
| 0.637992
|
catid
|
deea02df274624662688c1f57af5633f8709c74d
| 9,853
|
cpp
|
C++
|
src/wigner_d.cpp
|
dglazier/jpacPhoto
|
a364cf40610f793bee50c4e1ce61615cd30f30a5
|
[
"MIT"
] | null | null | null |
src/wigner_d.cpp
|
dglazier/jpacPhoto
|
a364cf40610f793bee50c4e1ce61615cd30f30a5
|
[
"MIT"
] | null | null | null |
src/wigner_d.cpp
|
dglazier/jpacPhoto
|
a364cf40610f793bee50c4e1ce61615cd30f30a5
|
[
"MIT"
] | null | null | null |
// Wigner little-d functions for half-integer spin particles
//
// Author: Daniel Winney (2020)
// Affiliation: Joint Physics Analysis Center (JPAC)
// Email: dwinney@iu.edu
// ---------------------------------------------------------------------------
#include "misc_math.hpp"
// --------------------------------------------------------------------------
double jpacPhoto::wigner_leading_coeff(int j, int lam1, int lam2)
{
int M = std::max(std::abs(lam1), std::abs(lam2));
int N = std::min(std::abs(lam1), std::abs(lam2));
int lambda = std::abs(lam1 - lam2) + lam1 - lam2;
double result = (double) factorial(2*j);
result /= sqrt( (double) factorial(j-M));
result /= sqrt( (double) factorial(j+M));
result /= sqrt( (double) factorial(j-N));
result /= sqrt( (double) factorial(j+N));
result /= pow(2., double(j-M));
result *= pow(-1., double(lambda)/2.);
return result;
};
// ---------------------------------------------------------------------------
double jpacPhoto::wigner_error(int j, int lam1, int lam2, bool half)
{
// if (half == true)
// {
// std::cout << "\n";
// std::cout << "wigner_d: Argument combination with j = " << j << "/2";
// std::cout << ", lam1 = " << lam1 << "/2";
// std::cout << ", lam2 = " << lam2 << "/2";
// std::cout << " does not exist. Quitting... \n";
// }
// else
// {
// std::cout << "\n";
// std::cout << "wigner_d: Argument combination with j = " << j;
// std::cout << ", lam1 = " << lam1;
// std::cout << ", lam2 = " << lam2;
// std::cout << " does not exist. Quitting... \n";
// }
//
// exit(0);
return 0.;
}
// ---------------------------------------------------------------------------
// USING WIKIPEDIA SIGN CONVENTION
// theta is in radians
// lam1 = 2 * lambda and lam2 = 2 * lambda^prime are integers
double jpacPhoto::wigner_d_half(int j, int lam1, int lam2, double theta)
{
double phase = 1.;
// If first lam argument is smaller, switch them
if (abs(lam1) < abs(lam2))
{
int temp = lam1;
lam1 = lam2;
lam2 = temp;
phase *= pow(-1., double(lam1 - lam2) / 2.);
};
// If first lam is negative, smitch them
if (lam1 < 0)
{
lam1 *= -1;
lam2 *= -1;
phase *= pow(-1., double(lam1 - lam2) / 2.);
}
double result = 0.;
switch (j)
{
// -------------------------------------------------------------------------
// j = 1/2
// -------------------------------------------------------------------------
case 1:
{
if (lam1 == 1)
{
if (lam2 == 1)
{
result = cos(theta / 2.);
break;
}
else
{
result = -sin(theta / 2.);
break;
}
}
else
{
wigner_error(j, lam1, lam2, true);
}
break;
}
// -------------------------------------------------------------------------
// j = 3/2
// -------------------------------------------------------------------------
case 3:
{
// Lambda = 3/2
if (lam1 == 3)
{
switch (lam2)
{
case 3:
{
result = cos(theta / 2.) / 2.;
result *= (1. + cos(theta));
break;
}
case 1:
{
result = - sqrt(3.) / 2.;
result *= sin(theta / 2.);
result *= 1. + cos(theta);
break;
}
case -1:
{
result = sqrt(3.) / 2.;
result *= cos(theta / 2.);
result *= 1. - cos(theta);
break;
}
case -3:
{
result = - sin(theta / 2.) / 2.;
result *= 1. - cos(theta);
break;
}
default: wigner_error(j, lam1, lam2, true);
}
}
// Lambda = 1/2
else if (lam1 == 1)
{
switch (lam2)
{
case 1:
{
result = 1. / 2.;
result *= 3. * cos(theta) - 1.;
result *= cos(theta / 2.);
break;
}
case -1:
{
result = -1. / 2.;
result *= 3. * cos(theta) + 1.;
result *= sin(theta / 2.);
break;
}
default: wigner_error(j, lam1, lam2, true);
}
}
// Error
else
{
wigner_error(j, lam1, lam2, true);
}
break;
}
// -------------------------------------------------------------------------
// j = 5/2
// -------------------------------------------------------------------------
case 5:
{
switch (lam1)
{
// lambda = 5/2 not yet implemented
case 5:
{
wigner_error(j, lam1, lam2, true);
}
// lam1 == 3
case 3:
{
switch (lam2)
{
case 3:
{
result = -1. / 4.;
result *= cos(theta / 2.);
result *= (1. + cos(theta)) * (3. - 5. * cos(theta));
break;
}
case 1:
{
result = sqrt(2.) / 4.;
result *= sin(theta / 2.);
result *= (1. + cos(theta)) * (1. - 5. * cos(theta));
break;
}
case -1:
{
result = sqrt(2.) / 4.;
result *= cos(theta / 2.);
result *= (1. - cos(theta)) * (1. + 5. * cos(theta));
break;
}
case -3:
{
result = -1. / 4.;
result *= sin(theta / 2.);
result *= (1. - cos(theta)) * (3. + 5. * cos(theta));
break;
}
default: wigner_error(j, lam1, lam2, true);
}
break;
}
// lam1 == 1
case 1:
{
switch (lam2)
{
case 1:
{
result = -1. / 2.;
result *= cos(theta / 2.);
result *= (1. + 2. * cos(theta) - 5. * cos(theta)*cos(theta));
break;
}
case -1:
{
result = 1. / 2.;
result *= sin(theta / 2.);
result *= (1. - 2. * cos(theta) - 5. * cos(theta)*cos(theta));
break;
}
default: wigner_error(j, lam1, lam2, true);
}
break;
}
default: wigner_error(j, lam1, lam2, true);
}
break;
}
// Error
default: wigner_error(j, lam1, lam2, true);
}
return phase * result;
};
// ---------------------------------------------------------------------------
double jpacPhoto::wigner_d_int(int j, int lam1, int lam2, double theta)
{
double phase = 1.;
// If first lam argument is smaller, switch them
if (abs(lam1) < abs(lam2))
{
int temp = lam1;
lam1 = lam2;
lam2 = temp;
phase *= pow(-1., double(lam1 - lam2));
};
// If first lam is negative, smitch them
if (lam1 < 0)
{
lam1 *= -1;
lam2 *= -1;
phase *= pow(-1., double(lam1 - lam2));
}
double result = 0.;
switch (j)
{
// spin - 1
case 1:
{
if (lam1 == 1)
{
switch (lam2)
{
case 1:
{
result = (1. + cos(theta)) / 2.;
break;
}
case 0:
{
result = - sin(theta) / sqrt(2.);
break;
}
case -1:
{
result = (1. - cos(theta)) / 2.;
break;
}
default: wigner_error(j, lam1, lam2, false);
}
}
else if (lam1 == 0)
{
result = cos(theta);
}
else
{
wigner_error(j, lam1, lam2, false);
}
break;
}
// Error
default: wigner_error(j, lam1, lam2, false);
}
return phase * result;
};
// ---------------------------------------------------------------------------
std::complex<double> jpacPhoto::wigner_d_int_cos(int j, int lam1, int lam2, double cosine)
{
// Careful because this loses the +- phase of the sintheta.
std::complex<double> sine = sqrt(xr - cosine * cosine);
std::complex<double> sinhalf = sqrt((xr - cosine) / 2.);
std::complex<double> coshalf = sqrt((xr + cosine) / 2.);
double phase = 1.;
// If first lam argument is smaller, switch them
if (abs(lam1) < abs(lam2))
{
int temp = lam1;
lam1 = lam2;
lam2 = temp;
phase *= pow(-1., double(lam1 - lam2));
};
// If first lam is negative, smitch them
if (lam1 < 0)
{
lam1 *= -1;
lam2 *= -1;
phase *= pow(-1., double(lam1 - lam2));
}
std::complex<double> result = 0.;
switch (j)
{
// spin - 1
case 1:
{
if (lam1 == 1)
{
switch (lam2)
{
case 1:
{
result = (1. + cosine) / 2.;
break;
}
case 0:
{
result = - sine / sqrt(2.);
break;
}
case -1:
{
result = (1. - cosine) / 2.;
break;
}
default: wigner_error(j, lam1, lam2, false);
}
}
else if (lam1 == 0)
{
result = cosine;
}
else
{
wigner_error(j, lam1, lam2, false);
}
break;
}
// Error
default: wigner_error(j, lam1, lam2, false);
}
return phase * result;
};
| 24.388614
| 91
| 0.357962
|
dglazier
|
deed00e11b964c85558aa5e5ef32d5eb3f8ee7b1
| 419
|
cpp
|
C++
|
src/TimeStats.cpp
|
dudad/words
|
bba0d3bd1c2a5fd395fa3f0166fcf9c4c2063074
|
[
"MIT"
] | null | null | null |
src/TimeStats.cpp
|
dudad/words
|
bba0d3bd1c2a5fd395fa3f0166fcf9c4c2063074
|
[
"MIT"
] | null | null | null |
src/TimeStats.cpp
|
dudad/words
|
bba0d3bd1c2a5fd395fa3f0166fcf9c4c2063074
|
[
"MIT"
] | null | null | null |
#include "TimeStats.h"
#include <numeric>
void TimeStats::init(unsigned int bucket)
{
m_currBucketIdx = bucket;
m_ticks = SDL_GetTicks();
}
void TimeStats::set(unsigned int bucket)
{
Uint32 now = SDL_GetTicks();
m_buckets[m_currBucketIdx] += (now - m_ticks);
m_currBucketIdx = bucket;
m_ticks = now;
}
uint64_t TimeStats::totalTime()
{
return std::accumulate(m_buckets.begin(), m_buckets.end(), 0);
}
| 18.217391
| 64
| 0.706444
|
dudad
|
deedcad9d367c22ea4b40f7019b82c2d9253f67a
| 3,363
|
cpp
|
C++
|
source/gloperate/source/stages/lights/LightBufferTextureStage.cpp
|
lordgeorg/gloperate
|
13a6363fdac1f9ff06d91c9bc99649eacd87078e
|
[
"MIT"
] | 34
|
2015-10-07T12:26:27.000Z
|
2021-04-06T06:35:01.000Z
|
source/gloperate/source/stages/lights/LightBufferTextureStage.cpp
|
lordgeorg/gloperate
|
13a6363fdac1f9ff06d91c9bc99649eacd87078e
|
[
"MIT"
] | 219
|
2015-07-07T15:55:03.000Z
|
2018-09-28T08:54:36.000Z
|
source/gloperate/source/stages/lights/LightBufferTextureStage.cpp
|
lordgeorg/gloperate
|
13a6363fdac1f9ff06d91c9bc99649eacd87078e
|
[
"MIT"
] | 21
|
2015-07-07T14:33:08.000Z
|
2018-12-23T12:43:56.000Z
|
#include <gloperate/stages/lights/LightBufferTextureStage.h>
#include <glm/vec3.hpp>
#include <glbinding/gl/enum.h>
#include <globjects/Buffer.h>
#include <globjects/Texture.h>
#include <gloperate/rendering/Light.h>
namespace
{
struct ColorTypeEntry
{
glm::vec3 color;
float type;
};
}
namespace gloperate
{
CPPEXPOSE_COMPONENT(LightBufferTextureStage, gloperate::Stage)
LightBufferTextureStage::LightBufferTextureStage(Environment * environment, const std::string & name)
: Stage(environment, "LightBufferTextureStage", name)
, colorTypeData("colorTypeData", this, nullptr)
, positionData("positionData", this, nullptr)
, attenuationData("attenuationData", this, nullptr)
{
}
LightBufferTextureStage::~LightBufferTextureStage()
{
}
void LightBufferTextureStage::onContextInit(AbstractGLContext * /*context*/)
{
setupBufferTextures();
colorTypeData.invalidate();
positionData.invalidate();
attenuationData.invalidate();
}
void LightBufferTextureStage::onContextDeinit(AbstractGLContext * /*context*/)
{
m_attenuationTexture.reset();
m_positionTexture.reset();
m_colorTypeTexture.reset();
m_attenuationBuffer.reset();
m_positionBuffer.reset();
m_colorTypeBuffer.reset();
colorTypeData.setValue(nullptr);
positionData.setValue(nullptr);
attenuationData.setValue(nullptr);
}
void LightBufferTextureStage::onProcess()
{
if (!colorTypeData.isValid() || !positionData.isValid() || !attenuationData.isValid())
{
setupBufferTextures();
}
std::vector<ColorTypeEntry> colorsTypes{};
std::vector<glm::vec3> positions{};
std::vector<glm::vec3> attenuations{};
for (auto lightInput : m_lightInputs)
{
if (!lightInput->isValid())
continue;
auto lightDef = lightInput->value();
colorsTypes.push_back(ColorTypeEntry{lightDef.color, float(lightDef.type)});
positions.push_back(lightDef.position);
attenuations.push_back(lightDef.attenuationCoefficients);
}
m_colorTypeBuffer->setData(colorsTypes, gl::GL_DYNAMIC_DRAW);
m_positionBuffer->setData(positions, gl::GL_DYNAMIC_DRAW);
m_attenuationBuffer->setData(attenuations, gl::GL_DYNAMIC_DRAW);
colorTypeData.setValue(m_colorTypeTexture.get());
positionData.setValue(m_positionTexture.get());
attenuationData.setValue(m_attenuationTexture.get());
}
void LightBufferTextureStage::setupBufferTextures()
{
m_colorTypeBuffer = cppassist::make_unique<globjects::Buffer>();
m_colorTypeTexture = cppassist::make_unique<globjects::Texture>(gl::GL_TEXTURE_BUFFER);
m_positionBuffer = cppassist::make_unique<globjects::Buffer>();
m_positionTexture = cppassist::make_unique<globjects::Texture>(gl::GL_TEXTURE_BUFFER);
m_attenuationBuffer = cppassist::make_unique<globjects::Buffer>();
m_attenuationTexture = cppassist::make_unique<globjects::Texture>(gl::GL_TEXTURE_BUFFER);
m_colorTypeTexture->texBuffer(gl::GL_RGBA32F, m_colorTypeBuffer.get());
m_positionTexture->texBuffer(gl::GL_RGB32F, m_positionBuffer.get());
m_attenuationTexture->texBuffer(gl::GL_RGB32F, m_attenuationBuffer.get());
}
Input<Light> * LightBufferTextureStage::createLightInput()
{
auto lightInput = createInput<Light>("light");
m_lightInputs.push_back(lightInput);
return lightInput;
}
} // namespace gloperate
| 27.565574
| 101
| 0.742194
|
lordgeorg
|
def56e35d0f136d3049c042b236e8e909086cc68
| 1,862
|
cpp
|
C++
|
source/shared/kernels/resourcekernels/emotion.cpp
|
AmonShokhinAhmed/TattleTale
|
b3ec96ca7831d38f2cce88f1ef02f351d9f8547f
|
[
"MIT"
] | 1
|
2022-03-22T16:17:45.000Z
|
2022-03-22T16:17:45.000Z
|
source/shared/kernels/resourcekernels/emotion.cpp
|
AmonShokhinAhmed/TattleTale
|
b3ec96ca7831d38f2cce88f1ef02f351d9f8547f
|
[
"MIT"
] | 88
|
2022-01-31T09:16:19.000Z
|
2022-03-29T19:30:50.000Z
|
source/shared/kernels/resourcekernels/emotion.cpp
|
AmonShokhinAhmed/TattleTale
|
b3ec96ca7831d38f2cce88f1ef02f351d9f8547f
|
[
"MIT"
] | null | null | null |
#include "shared/kernels/resourcekernels/emotion.hpp"
#include <assert.h>
#include <iostream>
#include <fmt/core.h>
#include "shared/actor.hpp"
namespace tattletale
{
Emotion::Emotion(EmotionType type, size_t id, size_t tick, Actor *owner, std::vector<Kernel *> reasons, float value)
: Resource(
fmt::format("{}", type),
Emotion::positive_name_variants_[static_cast<int>(type)],
Emotion::negative_name_variants_[static_cast<int>(type)],
id,
tick,
owner,
reasons,
value,
KernelType::kEmotion,
Verb("felt", "feeling", "feel")),
type_(type){};
EmotionType Emotion::StringToEmotionType(std::string emotion_string)
{
if (emotion_string == "happy")
return EmotionType::kHappy;
if (emotion_string == "calm")
return EmotionType::kCalm;
if (emotion_string == "satisfied")
return EmotionType::kSatisfied;
if (emotion_string == "brave")
return EmotionType::kBrave;
if (emotion_string == "extroverted")
return EmotionType::kExtroverted;
TATTLETALE_ERROR_PRINT(true, "Invalid Emotion string was passed");
return EmotionType::kLast;
}
EmotionType Emotion::GetType()
{
return type_;
}
float Emotion::CalculateChanceInfluence(const Interaction *interaction) const
{
return (interaction->GetTendency()->emotions[static_cast<int>(type_)] * value_);
}
bool Emotion::IsSameSpecificType(Kernel *other) const
{
if (!IsSameKernelType(other))
{
return false;
}
return (dynamic_cast<Emotion *>(other)->type_ == type_);
}
} // namespace tattletale
| 34.481481
| 121
| 0.581096
|
AmonShokhinAhmed
|
def95af310a929968f78ff84aec0cdbd52e0130f
| 28
|
hpp
|
C++
|
Engine/vendor/zed/include/sl/Camera.hpp
|
jeroennelis/Engine
|
43ed6c76d1eeeeddd7fd2b3b38d17ed72d312f1f
|
[
"Apache-2.0"
] | 2
|
2019-05-17T17:08:30.000Z
|
2020-12-15T09:42:04.000Z
|
Engine/vendor/zed/include/sl/Camera.hpp
|
jeroennelis/Engine
|
43ed6c76d1eeeeddd7fd2b3b38d17ed72d312f1f
|
[
"Apache-2.0"
] | null | null | null |
Engine/vendor/zed/include/sl/Camera.hpp
|
jeroennelis/Engine
|
43ed6c76d1eeeeddd7fd2b3b38d17ed72d312f1f
|
[
"Apache-2.0"
] | null | null | null |
#include <sl_zed/Camera.hpp>
| 28
| 28
| 0.785714
|
jeroennelis
|
defbc8aa803262daf230b57e40a564e58c6dfeb3
| 2,215
|
hpp
|
C++
|
Source/server/src/DBBackEnd.hpp
|
fmiguelgarcia/crossover
|
380d12e7cb9f892894889f7a0f25ecd60c775fc7
|
[
"MIT"
] | null | null | null |
Source/server/src/DBBackEnd.hpp
|
fmiguelgarcia/crossover
|
380d12e7cb9f892894889f7a0f25ecd60c775fc7
|
[
"MIT"
] | null | null | null |
Source/server/src/DBBackEnd.hpp
|
fmiguelgarcia/crossover
|
380d12e7cb9f892894889f7a0f25ecd60c775fc7
|
[
"MIT"
] | null | null | null |
/*
* Copyright (c) 2016 Francisco Miguel Garcia
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
*/
#pragma once
#include <QObject>
namespace crossOver
{
namespace common
{
struct SystemMeasurement;
}
namespace server
{
/// @brief This abstraction resolves the access to the database.
class DBBackEnd : public QObject
{
Q_OBJECT
public:
explicit DBBackEnd (QObject *parent = nullptr);
/// @brief It gets the client Identifier from @p realm (its authentication
/// key).
/// @return It returns the clientId, or -1 if it is not found.
int findClientIdByRealm (const QString &realm) const;
/// @brief It creates and return the new client id.
int createClientId (const QString &realm, const QString &mail) const;
/// @brief It adds the statistic on a specific user.
int
addStatsToClient (const QString &realm, const QString &email,
const crossOver::common::SystemMeasurement &sm) const;
private:
/// @brief It defines the default database connection.
void setupDBDefaultConnection ();
/// @brief It creates the database Schema if it does not exit yet.
void initializeTablesIfNotExist ();
};
}
}
| 33.059701
| 77
| 0.728668
|
fmiguelgarcia
|
defcb26b2fa2f23bd59d5339838adfb13477bf8d
| 33,706
|
cpp
|
C++
|
src/prefsdlg.cpp
|
devinsmith/ngnc
|
cbcf69b435cc8c26ff6adf2f86a0eae1cfdc948e
|
[
"0BSD"
] | null | null | null |
src/prefsdlg.cpp
|
devinsmith/ngnc
|
cbcf69b435cc8c26ff6adf2f86a0eae1cfdc948e
|
[
"0BSD"
] | null | null | null |
src/prefsdlg.cpp
|
devinsmith/ngnc
|
cbcf69b435cc8c26ff6adf2f86a0eae1cfdc948e
|
[
"0BSD"
] | null | null | null |
/*
* Copyright (c) 2016-2019 Devin Smith <devin@devinsmith.net>
*
* 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 DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <fxkeys.h>
#include "defs.h"
#include "prefsdlg.h"
const ColorTheme ColorThemes[]={
//|--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------|
//| Name | Base | Border | Back | Fore | Selback | Selfore | Tipback | Tipfore | Menuback | Menufore |
//|--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------|
{"FOX" ,FXRGB(212,208,200),FXRGB( 0, 0, 0),FXRGB(255,255,255),FXRGB( 0, 0, 0),FXRGB( 10, 36,106),FXRGB(255,255,255),FXRGB(255,255,225),FXRGB( 0, 0, 0),FXRGB( 10, 36,106),FXRGB(255,255,255)},
{"Gnome" ,FXRGB(214,215,214),FXRGB( 0, 0, 0),FXRGB(255,255,255),FXRGB( 0, 0, 0),FXRGB( 0, 0,128),FXRGB(255,255,255),FXRGB(255,255,225),FXRGB( 0, 0, 0),FXRGB( 0, 0,128),FXRGB(255,255,255)},
{"Atlas Green" ,FXRGB(175,180,159),FXRGB( 0, 0, 0),FXRGB(255,255,255),FXRGB( 0, 0, 0),FXRGB(111,122, 99),FXRGB(255,255,255),FXRGB(255,255,225),FXRGB( 0, 0, 0),FXRGB(111,122, 99),FXRGB(255,255,255)},
{"BeOS" ,FXRGB(217,217,217),FXRGB( 0, 0, 0),FXRGB(255,255,255),FXRGB( 0, 0, 0),FXRGB(168,168,168),FXRGB( 0, 0, 0),FXRGB(255,255,225),FXRGB( 0, 0, 0),FXRGB(168,168,168),FXRGB( 0, 0, 0)},
{"Blue Slate" ,FXRGB(239,239,239),FXRGB( 0, 0, 0),FXRGB(255,255,255),FXRGB( 0, 0, 0),FXRGB(103,141,178),FXRGB(255,255,255),FXRGB(255,255,225),FXRGB( 0, 0, 0),FXRGB(103,141,178),FXRGB(255,255,255)},
//|--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------|
//| Name | Base | Border | Back | Fore | Selback | Selfore | Tipback | Tipfore | Menuback | Menufore |
//|--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------|
{"CDE" ,FXRGB(156,153,156),FXRGB( 0, 0, 0),FXRGB(131,129,131),FXRGB(255,255,255),FXRGB( 49, 97,131),FXRGB(255,255,255),FXRGB(255,255,225),FXRGB( 0, 0, 0),FXRGB( 49, 97,131),FXRGB(255,255,255)},
{"Digital CDE" ,FXRGB( 74,121,131),FXRGB( 0, 0, 0),FXRGB( 55, 77, 78),FXRGB(255,255,255),FXRGB( 82,102,115),FXRGB(255,255,255),FXRGB(255,255,225),FXRGB( 0, 0, 0),FXRGB( 82,102,115),FXRGB(255,255,255)},
{"Dark Blue" ,FXRGB( 66,103,148),FXRGB( 0, 0, 0),FXRGB( 0, 42, 78),FXRGB(255,255,255),FXRGB( 92,179,255),FXRGB( 0, 0, 0),FXRGB(255,255,225),FXRGB( 0, 0, 0),FXRGB( 92,179,255),FXRGB( 0, 0, 0)},
{"Desert FOX" ,FXRGB(214,205,187),FXRGB( 0, 0, 0),FXRGB(255,255,255),FXRGB( 0, 0, 0),FXRGB(128, 0, 0),FXRGB(255,255,255),FXRGB(255,255,225),FXRGB( 0, 0, 0),FXRGB(128, 0, 0),FXRGB(255,255,255)},
{"EveX" ,FXRGB(230,222,220),FXRGB( 0, 0, 0),FXRGB(255,255,255),FXRGB( 0, 0, 0),FXRGB( 10, 95,137),FXRGB(255,255,255),FXRGB(255,255,225),FXRGB( 0, 0, 0),FXRGB( 10, 95,137),FXRGB(255,255,255)},
//|--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------|
//| Name | Base | Border | Back | Fore | Selback | Selfore | Tipback | Tipfore | Menuback | Menufore |
//|--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------|
{"Galaxy" ,FXRGB(239,239,239),FXRGB( 0, 0, 0),FXRGB(255,255,255),FXRGB( 0, 0, 0),FXRGB(103,141,178),FXRGB(255,255,255),FXRGB(255,255,225),FXRGB( 0, 0, 0),FXRGB(103,141,178),FXRGB(255,255,255)},
{"iMac" ,FXRGB(205,206,205),FXRGB( 0, 0, 0),FXRGB(255,255,255),FXRGB( 0, 0, 0),FXRGB( 0, 0,128),FXRGB(255,255,255),FXRGB(255,255,225),FXRGB( 0, 0, 0),FXRGB( 0, 0,128),FXRGB(255,255,255)},
{"KDE 1" ,FXRGB(192,192,192),FXRGB( 0, 0, 0),FXRGB(255,255,255),FXRGB( 0, 0, 0),FXRGB( 0, 0,128),FXRGB(255,255,255),FXRGB(255,255,225),FXRGB( 0, 0, 0),FXRGB( 0, 0,128),FXRGB(255,255,255)},
{"KDE 2" ,FXRGB(220,220,220),FXRGB( 0, 0, 0),FXRGB(255,255,255),FXRGB( 0, 0, 0),FXRGB( 10, 95,137),FXRGB(255,255,255),FXRGB(255,255,225),FXRGB( 0, 0, 0),FXRGB( 10, 95,137),FXRGB(255,255,255)},
{"KDE 3" ,FXRGB(238,238,230),FXRGB( 0, 0, 0),FXRGB(255,255,255),FXRGB( 0, 0, 0),FXRGB(255,221,118),FXRGB(255,255,255),FXRGB(255,255,225),FXRGB( 0, 0, 0),FXRGB(255,221,118),FXRGB(255,255,255)},
//|--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------|
//| Name | Base | Border | Back | Fore | Selback | Selfore | Tipback | Tipfore | Menuback | Menufore |
//|--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------|
{"Keramik" ,FXRGB(234,233,232),FXRGB( 0, 0, 0),FXRGB(255,255,255),FXRGB( 0, 0, 0),FXRGB(169,209,255),FXRGB( 0, 0, 0),FXRGB(255,255,225),FXRGB( 0, 0, 0),FXRGB(169,209,255),FXRGB( 0, 0, 0)},
{"Keramik Emerald" ,FXRGB(238,238,230),FXRGB( 0, 0, 0),FXRGB(255,255,255),FXRGB( 0, 0, 0),FXRGB(134,204,134),FXRGB( 0, 0, 0),FXRGB(255,255,225),FXRGB( 0, 0, 0),FXRGB(134,204,134),FXRGB( 0, 0, 0)},
{"Keramik White" ,FXRGB(239,239,239),FXRGB( 0, 0, 0),FXRGB(255,255,255),FXRGB( 0, 0, 0),FXRGB(103,141,178),FXRGB(255,255,255),FXRGB(255,255,225),FXRGB( 0, 0, 0),FXRGB(103,141,178),FXRGB(255,255,255)},
{"Mandrake" ,FXRGB(230,231,230),FXRGB( 0, 0, 0),FXRGB(255,255,255),FXRGB( 0, 0, 0),FXRGB( 33, 68,156),FXRGB(255,255,255),FXRGB(255,255,225),FXRGB( 0, 0, 0),FXRGB( 33, 68,156),FXRGB(255,255,255)},
{"Media Peach" ,FXRGB(239,239,239),FXRGB( 0, 0, 0),FXRGB(255,255,255),FXRGB( 0, 0, 0),FXRGB(103,141,178),FXRGB(255,255,255),FXRGB(255,255,225),FXRGB( 0, 0, 0),FXRGB(103,141,178),FXRGB(255,255,255)},
//|--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------|
//| Name | Base | Border | Back | Fore | Selback | Selfore | Tipback | Tipfore | Menuback | Menufore |
//|--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------|
{"Next" ,FXRGB(168,168,168),FXRGB( 0, 0, 0),FXRGB(255,255,255),FXRGB( 0, 0, 0),FXRGB( 0, 0, 0),FXRGB(255,255,255),FXRGB(255,255,225),FXRGB( 0, 0, 0),FXRGB( 0, 0, 0),FXRGB(255,255,255)},
{"Pale Gray" ,FXRGB(214,214,214),FXRGB( 0, 0, 0),FXRGB(255,255,255),FXRGB( 0, 0, 0),FXRGB( 0, 0, 0),FXRGB(255,255,255),FXRGB(255,255,225),FXRGB( 0, 0, 0),FXRGB( 0, 0, 0),FXRGB(255,255,255)},
{"Plastik" ,FXRGB(239,239,239),FXRGB( 0, 0, 0),FXRGB(255,255,255),FXRGB( 0, 0, 0),FXRGB(103,141,178),FXRGB(255,255,255),FXRGB(255,255,225),FXRGB( 0, 0, 0),FXRGB(103,141,178),FXRGB(255,255,255)},
{"Pumpkin" ,FXRGB(238,216,174),FXRGB( 0, 0, 0),FXRGB(255,255,255),FXRGB( 0, 0, 0),FXRGB(205,133, 63),FXRGB(255,255,255),FXRGB(255,255,225),FXRGB( 0, 0, 0),FXRGB(205,133, 63),FXRGB(255,255,255)},
{"Redmond 95" ,FXRGB(195,195,195),FXRGB( 0, 0, 0),FXRGB(255,255,255),FXRGB( 0, 0, 0),FXRGB( 0, 0,128),FXRGB(255,255,255),FXRGB(255,255,225),FXRGB( 0, 0, 0),FXRGB( 0, 0,128),FXRGB(255,255,255)},
//|--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------|
//| Name | Base | Border | Back | Fore | Selback | Selfore | Tipback | Tipfore | Menuback | Menufore |
//|--------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------+------------------|
{"Redmond 2000" ,FXRGB(212,208,200),FXRGB( 0, 0, 0),FXRGB(255,255,255),FXRGB( 0, 0, 0),FXRGB( 0, 36,104),FXRGB(255,255,255),FXRGB(255,255,225),FXRGB( 0, 0, 0),FXRGB( 0, 36,104),FXRGB(255,255,255)},
{"Redmond XP" ,FXRGB(238,238,230),FXRGB( 0, 0, 0),FXRGB(255,255,255),FXRGB( 0, 0, 0),FXRGB( 74,121,205),FXRGB(255,255,255),FXRGB(255,255,225),FXRGB( 0, 0, 0),FXRGB( 74,121,205),FXRGB(255,255,255)},
{"Solaris" ,FXRGB(174,178,195),FXRGB( 0, 0, 0),FXRGB(147,151,165),FXRGB( 0, 0, 0),FXRGB(113,139,165),FXRGB(255,255,255),FXRGB(255,255,225),FXRGB( 0, 0, 0),FXRGB(113,139,165),FXRGB(255,255,255)},
{"Storm" ,FXRGB(192,192,192),FXRGB( 0, 0, 0),FXRGB(255,255,255),FXRGB( 0, 0, 0),FXRGB(139, 0,139),FXRGB(255,255,255),FXRGB(255,255,225),FXRGB( 0, 0, 0),FXRGB(139, 0,139),FXRGB(255,255,255)},
{"Sea Sky" ,FXRGB(165,178,198),FXRGB( 0, 0, 0),FXRGB(255,255,255),FXRGB( 0, 0, 0),FXRGB( 49,101,156),FXRGB(255,255,255),FXRGB(255,255,225),FXRGB( 0, 0, 0),FXRGB( 49,101,156),FXRGB(255,255,255)},
};
const FXint numThemes=ARRAYNUMBER(ColorThemes);
FXDEFMAP(ConfigDialog) ConfigDialogMap[] = {
FXMAPFUNC(SEL_COMMAND, ConfigDialog::ID_ACCEPT, ConfigDialog::OnAccept),
FXMAPFUNC(SEL_COMMAND, ConfigDialog::ID_CANCEL, ConfigDialog::OnCancel),
FXMAPFUNC(SEL_COMMAND, ConfigDialog::ID_CHATCOLORS, ConfigDialog::OnColor),
FXMAPFUNC(SEL_CHANGED, ConfigDialog::ID_CHATCOLORS, ConfigDialog::OnColor),
FXMAPFUNC(SEL_COMMAND, ConfigDialog::ID_COLORS, ConfigDialog::OnColorChanged),
FXMAPFUNC(SEL_CHANGED, ConfigDialog::ID_COLORS, ConfigDialog::OnColorChanged),
FXMAPFUNC(SEL_COMMAND, ConfigDialog::ID_CHOOSE_FONT, ConfigDialog::OnChooseFont),
FXMAPFUNC(SEL_COMMAND, ConfigDialog::ID_COLOR_THEME, ConfigDialog::OnColorTheme)
};
FXIMPLEMENT(ConfigDialog, FXDialogBox, ConfigDialogMap, ARRAYNUMBER(ConfigDialogMap))
ConfigDialog::ConfigDialog(FXMainWindow *owner) :
FXDialogBox(owner, "Preferences", DECOR_RESIZE | DECOR_TITLE | DECOR_BORDER,
0,0,0,0, 0,0,0,0, 0,0)
{
tooltip = new FXToolTip(getApp());
hilite = getApp()->getHiliteColor();
shadow = getApp()->getShadowColor();
ColorTheme& theme_current = Preferences::instance().theme;
target_base.connect(theme_current.base);
target_back.connect(theme_current.back);
target_border.connect(theme_current.border);
target_fore.connect(theme_current.fore);
target_hilite.connect(hilite);
target_shadow.connect(shadow);
target_selfore.connect(theme_current.selfore);
target_selback.connect(theme_current.selback);
target_tipfore.connect(theme_current.tipfore);
target_tipback.connect(theme_current.tipback);
target_menufore.connect(theme_current.menufore);
target_menuback.connect(theme_current.menuback);
target_base.setTarget(this);
target_back.setTarget(this);
target_border.setTarget(this);
target_fore.setTarget(this);
target_hilite.setTarget(this);
target_shadow.setTarget(this);
target_selfore.setTarget(this);
target_selback.setTarget(this);
target_tipfore.setTarget(this);
target_tipback.setTarget(this);
target_menufore.setTarget(this);
target_menuback.setTarget(this);
target_base.setSelector(ID_COLORS);
target_back.setSelector(ID_COLORS);
target_border.setSelector(ID_COLORS);
target_fore.setSelector(ID_COLORS);
target_hilite.setSelector(ID_COLORS);
target_shadow.setSelector(ID_COLORS);
target_selfore.setSelector(ID_COLORS);
target_selback.setSelector(ID_COLORS);
target_tipfore.setSelector(ID_COLORS);
target_tipback.setSelector(ID_COLORS);
target_menufore.setSelector(ID_COLORS);
target_menuback.setSelector(ID_COLORS);
// Setup some data targets / bindings.
ChatColor& colors = Preferences::instance().colors;
textTarget.connect(colors.text);
textTarget.setTarget(this);
textTarget.setSelector(ID_CHATCOLORS);
backTarget.connect(colors.background);
backTarget.setTarget(this);
backTarget.setSelector(ID_CHATCOLORS);
errorTarget.connect(colors.error);
errorTarget.setTarget(this);
errorTarget.setSelector(ID_CHATCOLORS);
setup();
}
void ConfigDialog::setup()
{
FXString fontDesc = Preferences::instance().chatFontspec;
if (!fontDesc.empty()) {
chatfont = new FXFont(getApp(), fontDesc);
} else {
getApp()->getNormalFont()->create();
FXFontDesc fontdescription;
getApp()->getNormalFont()->getFontDesc(fontdescription);
chatfont = new FXFont(getApp(), fontdescription);
}
chatfont->create();
FXString defaultFont = chatfont->getFont();
// Build UI.
FXHorizontalFrame *closeframe = new FXHorizontalFrame(this, LAYOUT_SIDE_BOTTOM|LAYOUT_FILL_X);
FXButton *ok = new FXButton(closeframe, "&Close", nullptr, this, ID_ACCEPT,
BUTTON_INITIAL|BUTTON_DEFAULT|LAYOUT_RIGHT|FRAME_RAISED|FRAME_THICK, 0,0,0,0, 20,20);
ok->addHotKey(KEY_Return);
new FXButton(closeframe, "Cancel", nullptr, this, ID_CANCEL, BUTTON_DEFAULT|LAYOUT_RIGHT|FRAME_RAISED|FRAME_THICK, 0,0,0,
0, 20,20);
FXHorizontalFrame *contents = new FXHorizontalFrame(this, LAYOUT_SIDE_TOP|LAYOUT_FILL_X|LAYOUT_FILL_Y);
FXVerticalFrame *buttonframe = new FXVerticalFrame(contents, LAYOUT_FILL_Y|LAYOUT_LEFT|PACK_UNIFORM_WIDTH);
FXSwitcher *switcher = new FXSwitcher(contents, LAYOUT_FILL_X|LAYOUT_FILL_Y|LAYOUT_RIGHT);
FXVerticalFrame *colorpane = new FXVerticalFrame(switcher, LAYOUT_FILL_X|LAYOUT_FILL_Y);
new FXLabel(colorpane, "Color settings", nullptr, LAYOUT_LEFT);
new FXHorizontalSeparator(colorpane, SEPARATOR_LINE|LAYOUT_FILL_X);
FXHorizontalFrame *hframe = new FXHorizontalFrame(colorpane, LAYOUT_FILL_X|LAYOUT_FILL_Y);
FXMatrix *colormatrix = new FXMatrix(hframe, 2, MATRIX_BY_COLUMNS, 0,0,0,0, DEFAULT_SPACING,DEFAULT_SPACING,DEFAULT_SPACING,DEFAULT_SPACING, 1,1);
new FXColorWell(colormatrix, FXRGB(0,0,255), &backTarget, FXDataTarget::ID_VALUE, COLORWELL_OPAQUEONLY|FRAME_SUNKEN|FRAME_THICK|LAYOUT_LEFT|LAYOUT_CENTER_Y|LAYOUT_FIX_WIDTH|LAYOUT_FIX_HEIGHT|LAYOUT_FILL_COLUMN|LAYOUT_FILL_ROW, 0,0,40,24);
new FXLabel(colormatrix, "Text backround color", nullptr, JUSTIFY_LEFT|LAYOUT_CENTER_Y|LAYOUT_FILL_X|LAYOUT_FILL_ROW);
new FXColorWell(colormatrix, FXRGB(0,0,255), &textTarget, FXDataTarget::ID_VALUE, COLORWELL_OPAQUEONLY|FRAME_SUNKEN|FRAME_THICK|LAYOUT_LEFT|LAYOUT_CENTER_Y|LAYOUT_FIX_WIDTH|LAYOUT_FIX_HEIGHT|LAYOUT_FILL_COLUMN|LAYOUT_FILL_ROW, 0,0,40,24);
new FXLabel(colormatrix, "Text color", nullptr, JUSTIFY_LEFT|LAYOUT_CENTER_Y|LAYOUT_FILL_X|LAYOUT_FILL_ROW);
new FXColorWell(colormatrix, FXRGB(0,0,255), &errorTarget, FXDataTarget::ID_VALUE, COLORWELL_OPAQUEONLY|FRAME_SUNKEN|FRAME_THICK|LAYOUT_LEFT|LAYOUT_CENTER_Y|LAYOUT_FIX_WIDTH|LAYOUT_FIX_HEIGHT|LAYOUT_FILL_COLUMN|LAYOUT_FILL_ROW, 0,0,40,24);
new FXLabel(colormatrix, "Error text color", nullptr, JUSTIFY_LEFT|LAYOUT_CENTER_Y|LAYOUT_FILL_X|LAYOUT_FILL_ROW);
FXVerticalFrame *tframe = new FXVerticalFrame(hframe, FRAME_SUNKEN|FRAME_THICK|LAYOUT_FILL_X|LAYOUT_FILL_Y);
text = new FXText(tframe, nullptr, 0, LAYOUT_FILL_X|LAYOUT_FILL_Y|TEXT_READONLY);
text->setScrollStyle(HSCROLLING_OFF);
// Other settings
// Theme settings
FXVerticalFrame *vframe = new FXVerticalFrame(switcher, LAYOUT_FILL_X|LAYOUT_FILL_Y, 0,0,0,0,0,0,0,0,0,0);
hframe = new FXHorizontalFrame(vframe, LAYOUT_FILL_X | LAYOUT_FILL_Y, 0,0,0,0,0,0,0,0,0,0);
new FXSeparator(vframe, SEPARATOR_GROOVE | LAYOUT_FILL_X);
FXVerticalFrame *frame = new FXVerticalFrame(hframe, LAYOUT_FILL_Y, 0,0,0,0, 0,0,0,0, 0, 0);
new FXSeparator(hframe,SEPARATOR_GROOVE|LAYOUT_FILL_Y);
FXVerticalFrame * themeframe = new FXVerticalFrame(frame,LAYOUT_FILL_X,0,0,0,0,DEFAULT_SPACING,DEFAULT_SPACING,DEFAULT_SPACING,DEFAULT_SPACING);
new FXLabel(themeframe,"Theme: ", nullptr,LAYOUT_CENTER_Y);
list = new FXListBox(themeframe,this,ID_COLOR_THEME,LAYOUT_FILL_X|FRAME_SUNKEN|FRAME_THICK);
list->setNumVisible(9);
new FXSeparator(frame,SEPARATOR_GROOVE|LAYOUT_FILL_X);
FXMatrix* matrix = new FXMatrix(frame,2,LAYOUT_FILL_Y|MATRIX_BY_COLUMNS,0,0,0,0,DEFAULT_SPACING,DEFAULT_SPACING,
DEFAULT_SPACING,DEFAULT_SPACING,1,1);
new FXColorWell(matrix,FXRGB(0,0,255),&target_base,FXDataTarget::ID_VALUE);
//FXLabel *label = new FXLabel(matrix,"Base Color");
new FXLabel(matrix,"Base Color");
new FXColorWell(matrix,FXRGB(0,0,255),&target_border,FXDataTarget::ID_VALUE);
//label = new FXLabel(matrix,"Border Color");
new FXLabel(matrix,"Border Color");
new FXColorWell(matrix,FXRGB(0,0,255),&target_fore,FXDataTarget::ID_VALUE);
new FXLabel(matrix,"Text Color");
new FXColorWell(matrix,FXRGB(0,0,255),&target_back,FXDataTarget::ID_VALUE);
new FXLabel(matrix,"Background Color");
new FXColorWell(matrix,FXRGB(0,0,255),&target_selfore,FXDataTarget::ID_VALUE);
new FXLabel(matrix,"Selected Text Color");
new FXColorWell(matrix,FXRGB(0,0,255),&target_selback,FXDataTarget::ID_VALUE);
new FXLabel(matrix,"Selected Background Color");
new FXColorWell(matrix,FXRGB(0,0,255),&target_menufore,FXDataTarget::ID_VALUE);
new FXLabel(matrix,"Selected Menu Text Color");
new FXColorWell(matrix,FXRGB(0,0,255),&target_menuback,FXDataTarget::ID_VALUE);
new FXLabel(matrix,"Selected Menu Background Color");
new FXColorWell(matrix,FXRGB(0,0,255),&target_tipfore,FXDataTarget::ID_VALUE);
new FXLabel(matrix,"Tip Text Color");
new FXColorWell(matrix,FXRGB(0,0,255),&target_tipback,FXDataTarget::ID_VALUE);
new FXLabel(matrix,"Tip Background Color");
frame = new FXVerticalFrame(hframe,LAYOUT_FILL_X|LAYOUT_FILL_Y,0,0,0,0,DEFAULT_SPACING,DEFAULT_SPACING,DEFAULT_SPACING,DEFAULT_SPACING,0,0);
FXTabBook* tabbook = new FXTabBook(frame, nullptr,0,LAYOUT_FILL_X|LAYOUT_FILL_Y,0,0,0,0,0,0,0,0);
tabitem = new FXTabItem(tabbook, " Item 1 ");
tabframe = new FXVerticalFrame(tabbook,LAYOUT_FILL_X|LAYOUT_FILL_Y|FRAME_THICK|FRAME_RAISED);
labeltextframe1 = new FXHorizontalFrame(tabframe,LAYOUT_FILL_X);
label1 = new FXLabel(labeltextframe1,"Label with Text", nullptr);
textfield1 = new FXTextField(labeltextframe1,30,NULL,0,LAYOUT_FILL_X|FRAME_THICK|FRAME_SUNKEN);
textfield1->setText("Select this text, to see the selected colors");
labeltextframe2 = new FXHorizontalFrame(tabframe,LAYOUT_FILL_X);
textframe1 = new FXHorizontalFrame(labeltextframe2,LAYOUT_FILL_X|FRAME_THICK|FRAME_SUNKEN,0,0,0,
0,2,2,2,2,0,0);
label3 = new FXLabel(textframe1,"Selected Text (with focus)",NULL,LAYOUT_FILL_X,0,0,0,0,1,1,1,1);
textframe2 = new FXHorizontalFrame(labeltextframe2,LAYOUT_FILL_X|FRAME_THICK|FRAME_SUNKEN,0,0,0,
0,2,2,2,2,0,0);
label4 = new FXLabel(textframe2,"Selected Text (no focus)",NULL,LAYOUT_FILL_X,0,0,0,0,1,1,1,1);
sep1 = new FXSeparator(tabframe,LAYOUT_FILL_X|SEPARATOR_LINE);
tabsubframe = new FXHorizontalFrame(tabframe,LAYOUT_FILL_X|LAYOUT_FILL_Y);
grpbox1 = new FXGroupBox(tabsubframe,"MenuPane",FRAME_GROOVE|LAYOUT_FILL_Y|LAYOUT_FILL_X);
menuframe = new FXVerticalFrame(grpbox1,FRAME_RAISED|FRAME_THICK|LAYOUT_CENTER_X|LAYOUT_CENTER_Y,0,
0,0,0,0,0,
0,0,0,0);
menulabels[0]=new FXLabel(menuframe,"&Open",NULL,LABEL_NORMAL,0,0,0,0,16,4);
menulabels[1]=new FXLabel(menuframe,"S&ave",NULL,LABEL_NORMAL,0,0,0,0,16,4);
sep2 = new FXSeparator(menuframe,LAYOUT_FILL_X|SEPARATOR_GROOVE);
menulabels[2]=new FXLabel(menuframe,"I&mport",NULL,LABEL_NORMAL,0,0,0,0,16,4);
menulabels[4]=new FXLabel(menuframe,"Selected Menu Entry",NULL,LABEL_NORMAL,0,0,0,0,16,4);
menulabels[3]=new FXLabel(menuframe,"Print",NULL,LABEL_NORMAL,0,0,0,0,16,4);
sep3 = new FXSeparator(menuframe,LAYOUT_FILL_X|SEPARATOR_GROOVE);
menulabels[5]=new FXLabel(menuframe,"&Quit",NULL,LABEL_NORMAL,0,0,0,0,16,4);
grpbox2 = new FXGroupBox(tabsubframe,"Tooltips",FRAME_GROOVE|LAYOUT_FILL_Y|LAYOUT_FILL_X);
label2 = new FXLabel(grpbox2,"Sample Tooltip",NULL,FRAME_LINE|LAYOUT_CENTER_X);
label5 = new FXLabel(grpbox2,"Multiline Sample\n Tooltip",NULL,FRAME_LINE|LAYOUT_CENTER_X);
FXHorizontalFrame *fontframe = new FXHorizontalFrame(vframe, LAYOUT_FILL_X|LAYOUT_FILL_Y, 0,0,0,0, DEFAULT_SPACING,DEFAULT_SPACING,DEFAULT_SPACING,DEFAULT_SPACING);
new FXLabel(fontframe, "Chat Font:", nullptr, LAYOUT_CENTER_Y);
fontbutton = new FXButton(fontframe, "", nullptr, this, ID_CHOOSE_FONT, LAYOUT_CENTER_Y | FRAME_RAISED | JUSTIFY_CENTER_X | JUSTIFY_CENTER_Y | LAYOUT_FILL_X);
fontbutton->setText(defaultFont);
new FXButton(buttonframe, "Co&lors", nullptr, switcher, FXSwitcher::ID_OPEN_FIRST, FRAME_RAISED);
new FXButton(buttonframe, "&Themes", nullptr, switcher, FXSwitcher::ID_OPEN_SECOND, FRAME_RAISED);
ChatColor& colors = Preferences::instance().colors;
for (int i = 0; i < 2; i++) {
textStyle[i].normalForeColor = colors.text;
textStyle[i].normalBackColor = colors.background;
textStyle[i].selectForeColor = getApp()->getSelforeColor();
textStyle[i].selectBackColor = getApp()->getSelbackColor();
textStyle[i].hiliteForeColor = getApp()->getHiliteColor();
textStyle[i].hiliteBackColor = FXRGB(255, 128, 128); // from FXText.cpp
textStyle[i].activeBackColor = colors.background;
textStyle[i].style = 0;
}
// Errors
textStyle[1].normalForeColor = colors.error;
text->setStyled(TRUE);
text->setHiliteStyles(textStyle);
text->setTextColor(colors.text);
text->setBackColor(colors.background);
text->appendText("[0]bill: Hello there!\n");
text->appendText("[1]ted: Hey Now!\n");
text->appendStyledText(FXString("No error\n"), COLOR_ERROR);
setupColors();
}
ConfigDialog::~ConfigDialog()
{
delete chatfont;
}
long ConfigDialog::OnAccept(FXObject* obj, FXSelector sel, void* ud)
{
Preferences::instance().WriteRegistry(getApp()->reg());
getApp()->stopModal(this, TRUE);
hide();
return 1;
}
long ConfigDialog::OnCancel(FXObject* obj, FXSelector sel, void* ud)
{
getApp()->stopModal(this, FALSE);
hide();
return 1;
}
long ConfigDialog::OnColor(FXObject* obj, FXSelector sel, void* ud)
{
ChatColor& colors = Preferences::instance().colors;
text->setTextColor(colors.text);
text->setBackColor(colors.background);
for (int i = 0; i < 2; i++) {
textStyle[i].normalBackColor = colors.background;
}
textStyle[1].normalForeColor = colors.error;
text->update();
return 1;
}
long ConfigDialog::OnChooseFont(FXObject* obj, FXSelector sel, void *ud)
{
FXFontDialog dialog(this, "Select Chat Font");
FXFontDesc fontdescription;
chatfont->getFontDesc(fontdescription);
strncpy(fontdescription.face, chatfont->getActualName().text(),
sizeof(fontdescription.face) - 1);
fontdescription.face[sizeof(fontdescription.face) - 1] = '\0';
dialog.setFontSelection(fontdescription);
if (dialog.execute(PLACEMENT_SCREEN)) {
FXFont *oldfont = chatfont;
dialog.getFontSelection(fontdescription);
chatfont = new FXFont(getApp(), fontdescription);
chatfont->create();
delete oldfont;
FXString newDesc = chatfont->getFont();
fontbutton->setText(newDesc);
// Save to preferences
Preferences::instance().chatFontspec = newDesc;
}
return 1;
}
void ConfigDialog::create()
{
FXDialogBox::create();
initColors();
}
void ConfigDialog::setupColors()
{
ColorTheme& theme_current = Preferences::instance().theme;
shadow = makeShadowColor(theme_current.base);
hilite = makeHiliteColor(theme_current.base);
tabitem->setBorderColor(theme_current.border);
tabitem->setBaseColor(theme_current.base);
tabitem->setBackColor(theme_current.base);
tabitem->setTextColor(theme_current.fore);
tabitem->setShadowColor(shadow);
tabitem->setHiliteColor(hilite);
tabframe->setBorderColor(theme_current.border);
tabframe->setBaseColor(theme_current.base);
tabframe->setBackColor(theme_current.base);
tabframe->setShadowColor(shadow);
tabframe->setHiliteColor(hilite);
tabsubframe->setBorderColor(theme_current.border);
tabsubframe->setBaseColor(theme_current.base);
tabsubframe->setBackColor(theme_current.base);
tabsubframe->setShadowColor(shadow);
tabsubframe->setHiliteColor(hilite);
menuframe->setBorderColor(theme_current.border);
menuframe->setBaseColor(theme_current.base);
menuframe->setBackColor(theme_current.base);
menuframe->setShadowColor(shadow);
menuframe->setHiliteColor(hilite);
grpbox1->setBorderColor(theme_current.border);
grpbox1->setBaseColor(theme_current.base);
grpbox1->setBackColor(theme_current.base);
grpbox1->setShadowColor(shadow);
grpbox1->setHiliteColor(hilite);
grpbox1->setTextColor(theme_current.fore);
grpbox2->setBorderColor(theme_current.border);
grpbox2->setBaseColor(theme_current.base);
grpbox2->setBackColor(theme_current.base);
grpbox2->setShadowColor(shadow);
grpbox2->setHiliteColor(hilite);
grpbox2->setTextColor(theme_current.fore);
sep1->setBorderColor(theme_current.border);
sep1->setBaseColor(theme_current.base);
sep1->setBackColor(theme_current.base);
sep1->setShadowColor(shadow);
sep1->setHiliteColor(hilite);
sep2->setBorderColor(theme_current.border);
sep2->setBaseColor(theme_current.base);
sep2->setBackColor(theme_current.base);
sep2->setShadowColor(shadow);
sep2->setHiliteColor(hilite);
sep3->setBorderColor(theme_current.border);
sep3->setBaseColor(theme_current.base);
sep3->setBackColor(theme_current.base);
sep3->setShadowColor(shadow);
sep3->setHiliteColor(hilite);
labeltextframe1->setBorderColor(theme_current.border);
labeltextframe1->setBaseColor(theme_current.base);
labeltextframe1->setBackColor(theme_current.base);
labeltextframe1->setShadowColor(shadow);
labeltextframe1->setHiliteColor(hilite);
labeltextframe2->setBorderColor(theme_current.border);
labeltextframe2->setBaseColor(theme_current.base);
labeltextframe2->setBackColor(theme_current.base);
labeltextframe2->setShadowColor(shadow);
labeltextframe2->setHiliteColor(hilite);
label1->setBorderColor(theme_current.border);
label1->setBaseColor(theme_current.base);
label1->setBackColor(theme_current.base);
label1->setTextColor(theme_current.fore);
label1->setShadowColor(shadow);
label1->setHiliteColor(hilite);
label2->setBorderColor(theme_current.tipfore);
label2->setBaseColor(theme_current.tipback);
label2->setBackColor(theme_current.tipback);
label2->setTextColor(theme_current.tipfore);
label2->setShadowColor(shadow);
label2->setHiliteColor(hilite);
label3->setBorderColor(theme_current.border);
label3->setBaseColor(theme_current.base);
label3->setBackColor(theme_current.selback);
label3->setTextColor(theme_current.selfore);
label3->setShadowColor(shadow);
label3->setHiliteColor(hilite);
label4->setBorderColor(theme_current.border);
label4->setBaseColor(theme_current.base);
label4->setBackColor(theme_current.base);
label4->setTextColor(theme_current.fore);
label4->setShadowColor(shadow);
label4->setHiliteColor(hilite);
label5->setBorderColor(theme_current.tipfore);
label5->setBaseColor(theme_current.tipback);
label5->setBackColor(theme_current.tipback);
label5->setTextColor(theme_current.tipfore);
label5->setShadowColor(shadow);
label5->setHiliteColor(hilite);
for (int i=0;i<6;i++){
menulabels[i]->setBorderColor(theme_current.border);
menulabels[i]->setBaseColor(theme_current.base);
menulabels[i]->setBackColor(theme_current.base);
menulabels[i]->setTextColor(theme_current.fore);
menulabels[i]->setShadowColor(shadow);
menulabels[i]->setHiliteColor(hilite);
}
menulabels[4]->setBorderColor(theme_current.border);
menulabels[4]->setBaseColor(theme_current.menuback);
menulabels[4]->setBackColor(theme_current.menuback);
menulabels[4]->setTextColor(theme_current.menufore);
menulabels[4]->setShadowColor(shadow);
menulabels[4]->setHiliteColor(hilite);
textframe1->setBorderColor(theme_current.border);
textframe1->setBaseColor(theme_current.base);
textframe1->setBackColor(theme_current.back);
textframe1->setShadowColor(shadow);
textframe1->setHiliteColor(hilite);
textframe2->setBorderColor(theme_current.border);
textframe2->setBaseColor(theme_current.base);
textframe2->setBackColor(theme_current.back);
textframe2->setShadowColor(shadow);
textframe2->setHiliteColor(hilite);
textfield1->setBorderColor(theme_current.border);
textfield1->setBackColor(theme_current.back);
textfield1->setBaseColor(theme_current.base);
textfield1->setTextColor(theme_current.fore);
textfield1->setSelTextColor(theme_current.selfore);
textfield1->setSelBackColor(theme_current.selback);
textfield1->setCursorColor(theme_current.fore);
textfield1->setShadowColor(shadow);
textfield1->setHiliteColor(hilite);
tooltip->setTextColor(theme_current.tipfore);
tooltip->setBackColor(theme_current.tipback);
}
void ConfigDialog::initColors()
{
FXint i,scheme=-1;
ColorTheme& theme_current = Preferences::instance().theme;
/// Find the correct current scheme
for(i=0;i<numThemes;i++){
if((theme_current.base==ColorThemes[i].base) &&
(theme_current.border==ColorThemes[i].border) &&
(theme_current.back==ColorThemes[i].back) &&
(theme_current.fore==ColorThemes[i].fore) &&
(theme_current.selfore==ColorThemes[i].selfore) &&
(theme_current.selback==ColorThemes[i].selback) &&
(theme_current.menufore==ColorThemes[i].menufore) &&
(theme_current.menuback==ColorThemes[i].menuback) &&
(theme_current.tipfore==ColorThemes[i].tipfore) &&
(theme_current.tipback==ColorThemes[i].tipback)){
scheme=i;
break;
}
}
if (scheme==-1) {
theme_user.base = theme_current.base;
theme_user.border = theme_current.border;
theme_user.back = theme_current.back;
theme_user.fore = theme_current.fore;
theme_user.selfore = theme_current.selfore;
theme_user.selback = theme_current.selback;
theme_user.menufore = theme_current.menufore;
theme_user.menuback = theme_current.menuback;
theme_user.tipfore = theme_current.tipfore;
theme_user.tipback = theme_current.tipback;
list->appendItem("Current",NULL,&theme_user);
}
/// Add Standard Themes to List
for(i=0; i<numThemes; i++){
list->appendItem(ColorThemes[i].name,NULL,(void*)&ColorThemes[i]);
}
list->appendItem("User Defined");
list->setCurrentItem(scheme);
}
long ConfigDialog::OnColorTheme(FXObject *, FXSelector, void *ptr)
{
FXint no=(FXint)(FXival)ptr;
ColorTheme * theme_selected = reinterpret_cast<ColorTheme*>(list->getItemData(no));
ColorTheme& theme_current = Preferences::instance().theme;
if (theme_selected) {
/// Set new colors from selected theme
theme_current.base = theme_selected->base;
theme_current.border = theme_selected->border;
theme_current.back = theme_selected->back;
theme_current.fore = theme_selected->fore;
theme_current.selfore = theme_selected->selfore;
theme_current.selback = theme_selected->selback;
theme_current.tipfore = theme_selected->tipfore;
theme_current.tipback = theme_selected->tipback;
theme_current.menufore = theme_selected->menufore;
theme_current.menuback = theme_selected->menuback;
/// Apply New Colors to Widgets
setupColors();
}
return 1;
}
long ConfigDialog::OnColorChanged(FXObject *, FXSelector, void *)
{
list->setCurrentItem(list->getNumItems()-1);
setupColors();
return 1;
}
| 53.757576
| 241
| 0.648015
|
devinsmith
|
defcc13dbe875f434dad15e1fd141052733dd4de
| 245
|
cxx
|
C++
|
source/code/icelib/private/output/elements/include.cxx
|
iceshard-engine/code-emitter
|
b86eda2bc0cbdc4302fb4b03ce012ca2a0f3aeea
|
[
"BSD-3-Clause-Clear"
] | null | null | null |
source/code/icelib/private/output/elements/include.cxx
|
iceshard-engine/code-emitter
|
b86eda2bc0cbdc4302fb4b03ce012ca2a0f3aeea
|
[
"BSD-3-Clause-Clear"
] | 2
|
2019-09-30T05:20:37.000Z
|
2019-10-10T19:18:59.000Z
|
source/code/icelib/private/output/elements/include.cxx
|
iceshard-engine/code-emitter
|
b86eda2bc0cbdc4302fb4b03ce012ca2a0f3aeea
|
[
"BSD-3-Clause-Clear"
] | null | null | null |
#include <ice/output/elements/include.hxx>
namespace ice::output
{
template<>
auto ice::output::identifier(Include const& data) noexcept -> std::string
{
return { "include:" + data.path };
}
} // namespace ice::output
| 18.846154
| 77
| 0.632653
|
iceshard-engine
|
defd03bc6160f50bfe311cc7021a0b293db8d6d0
| 303
|
cpp
|
C++
|
src/utils/log.cpp
|
vtavernier/libshadertoy
|
a0b2a133199383cc7e9bcb3c0300f39eb95177c0
|
[
"MIT"
] | 2
|
2020-02-23T09:33:07.000Z
|
2021-11-15T18:23:13.000Z
|
src/utils/log.cpp
|
vtavernier/libshadertoy
|
a0b2a133199383cc7e9bcb3c0300f39eb95177c0
|
[
"MIT"
] | 2
|
2019-08-09T15:48:07.000Z
|
2020-11-16T13:51:56.000Z
|
src/utils/log.cpp
|
vtavernier/libshadertoy
|
a0b2a133199383cc7e9bcb3c0300f39eb95177c0
|
[
"MIT"
] | 3
|
2019-12-12T09:42:34.000Z
|
2020-12-14T03:56:30.000Z
|
#include "shadertoy/utils/log.hpp"
using namespace shadertoy::utils;
namespace spd = spdlog;
bool log::initialized_ = false;
std::shared_ptr<spd::logger> log::shadertoy()
{
if (!initialized_)
{
initialized_ = true;
return spd::stderr_color_st("shadertoy");
}
return spd::get("shadertoy");
}
| 16.833333
| 45
| 0.709571
|
vtavernier
|
7206a085f7fd472287fb054f58ad85f266e4432c
| 2,715
|
cpp
|
C++
|
src/parser/src/TypeCheckingSymbolTable.cpp
|
CUDA-me-impressed/CuMat-Compiler
|
d5050f96a2712d4d135c1729484cd91db2bdd42e
|
[
"MIT"
] | 2
|
2020-10-18T10:29:34.000Z
|
2021-01-05T15:46:34.000Z
|
src/parser/src/TypeCheckingSymbolTable.cpp
|
CUDA-me-impressed/CuMat-Compiler
|
d5050f96a2712d4d135c1729484cd91db2bdd42e
|
[
"MIT"
] | 11
|
2020-10-08T18:41:20.000Z
|
2021-03-19T14:49:19.000Z
|
src/parser/src/TypeCheckingSymbolTable.cpp
|
CUDA-me-impressed/CuMat-Compiler
|
d5050f96a2712d4d135c1729484cd91db2bdd42e
|
[
"MIT"
] | null | null | null |
#include "TypeCheckingSymbolTable.hpp"
#include "TypeCheckingUtils.hpp"
std::shared_ptr<Typing::Type> TypeCheckUtils::TypeCheckingSymbolTable::getFuncType(std::string funcName, std::string nameSpace) {
if (this->funcTypes.contains(nameSpace)) {
if (this->funcTypes[nameSpace].contains(funcName)) {
return funcTypes[nameSpace][funcName];
}
}
TypeCheckUtils::notDefinedError(funcName);
return nullptr;
}
void TypeCheckUtils::TypeCheckingSymbolTable::storeFuncType(std::string funcName, std::string nameSpace, std::shared_ptr<Typing::Type> typePtr) {
if (this->inFuncTable(funcName, nameSpace)) {
TypeCheckUtils::alreadyDefinedError(funcName, false);
}
if (!this->funcTypes.contains(nameSpace)) {
this->funcTypes[nameSpace] = std::map<std::string, std::shared_ptr<Typing::Type>>();
}
this->funcTypes[nameSpace][funcName] = std::move(typePtr);
}
std::shared_ptr<Typing::Type> TypeCheckUtils::TypeCheckingSymbolTable::getVarType(std::string varName) {
if (this->varTypes.contains(varName)) {
TypeCheckUtils::VariableEntry entry = this->varTypes[varName];
if (entry.isFunction) {
return this->getFuncType(entry.funcName, entry.nameSpace);
} else {
return entry.varType;
}
}
TypeCheckUtils::notDefinedError(varName);
return nullptr;
}
void TypeCheckUtils::TypeCheckingSymbolTable::storeVarType(std::string typeName, std::shared_ptr<Typing::Type> typePtr, std::string nameSpace, std::string funcName) {
if (this->inVarTable(typeName)) {
TypeCheckUtils::alreadyDefinedError(typeName, true);
}
TypeCheckUtils::VariableEntry entry;
entry.funcName = funcName;
entry.nameSpace = nameSpace;
entry.varType = std::move(typePtr);
if (funcName != "") {
if (this->inFuncTable(funcName, nameSpace)) {
entry.isFunction = true;
} else {
TypeCheckUtils::notDefinedError(funcName);
}
} else {
entry.isFunction = false;
}
this->varTypes[typeName] = entry;
}
void TypeCheckUtils::TypeCheckingSymbolTable::removeVarEntry(std::string typeName) {
if (this->inVarTable(typeName)) {
this->varTypes.erase(typeName);
} else {
TypeCheckUtils::notDefinedError(typeName);
}
}
bool TypeCheckUtils::TypeCheckingSymbolTable::inVarTable(std::string typeName) {
return this->varTypes.contains(typeName);
}
bool TypeCheckUtils::TypeCheckingSymbolTable::inFuncTable(std::string funcName, std::string nameSpace) {
if (this->funcTypes.contains(nameSpace)) {
return this->funcTypes[nameSpace].contains(funcName);
} else {
return false;
}
}
| 36.689189
| 166
| 0.684346
|
CUDA-me-impressed
|
7207cce9bbf86f5d3492770c0ce8b2a1c2b11cd0
| 762
|
hpp
|
C++
|
core/source/core/game/components/text_component.hpp
|
Karlashenko/engine-2d
|
842c67fb6a7f19eaf16550b441ec7b79af2a0b7a
|
[
"MIT"
] | null | null | null |
core/source/core/game/components/text_component.hpp
|
Karlashenko/engine-2d
|
842c67fb6a7f19eaf16550b441ec7b79af2a0b7a
|
[
"MIT"
] | null | null | null |
core/source/core/game/components/text_component.hpp
|
Karlashenko/engine-2d
|
842c67fb6a7f19eaf16550b441ec7b79af2a0b7a
|
[
"MIT"
] | null | null | null |
#pragma once
#include <utility>
#include "../../fonts/font.hpp"
class TextComponent final
{
public:
U32 space_width;
U32 line_height;
TextComponent(const Shared<Font>& p_font, String p_text)
: m_font(p_font), m_text(std::move(p_text))
{
space_width = m_font->get_size() * 0.4F;
line_height = m_font->get_size() * 1.2F;
m_glyphs = m_font->get_glyphs(m_text);
}
[[nodiscard]] Shared<Font> get_font() const
{
return m_font;
}
[[nodiscard]] const String& get_text() const
{
return m_text;
}
[[nodiscard]] const List<Glyph>& get_glyphs() const
{
return m_glyphs;
}
private:
List<Glyph> m_glyphs;
Shared<Font> m_font;
String m_text;
};
| 18.585366
| 60
| 0.598425
|
Karlashenko
|
7208deee29978030b07f41137afca85f463d16eb
| 263
|
hpp
|
C++
|
src/snabl/timer.hpp
|
codr4life/snabl
|
b1c8a69e351243a3ae73d69754971d540c224733
|
[
"MIT"
] | 22
|
2018-08-27T15:28:10.000Z
|
2022-02-13T08:18:00.000Z
|
src/snabl/timer.hpp
|
codr4life/snabl
|
b1c8a69e351243a3ae73d69754971d540c224733
|
[
"MIT"
] | 3
|
2018-08-27T01:44:51.000Z
|
2020-06-28T20:07:42.000Z
|
src/snabl/timer.hpp
|
codr4life/snabl
|
b1c8a69e351243a3ae73d69754971d540c224733
|
[
"MIT"
] | 2
|
2018-08-26T18:55:47.000Z
|
2018-09-29T01:04:36.000Z
|
#ifndef SNABL_TIMER_HPP
#define SNABL_TIMER_HPP
#include "snabl/types.hpp"
namespace snabl {
struct Timer {
static steady_clock::time_point now();
steady_clock::time_point start;
Timer();
void reset();
I64 ns() const;
};
}
#endif
| 13.842105
| 42
| 0.661597
|
codr4life
|
720b2059c817949fe594cde895e62f1b045106fd
| 5,420
|
cpp
|
C++
|
src/drivers/win32/input_win32.cpp
|
demurzasty/rabb
|
f980fd18332f7846cd22b502f1075d224938379c
|
[
"MIT"
] | 8
|
2020-11-21T17:59:09.000Z
|
2022-02-13T05:14:40.000Z
|
src/drivers/win32/input_win32.cpp
|
demurzasty/rabb
|
f980fd18332f7846cd22b502f1075d224938379c
|
[
"MIT"
] | null | null | null |
src/drivers/win32/input_win32.cpp
|
demurzasty/rabb
|
f980fd18332f7846cd22b502f1075d224938379c
|
[
"MIT"
] | 1
|
2020-11-23T23:01:14.000Z
|
2020-11-23T23:01:14.000Z
|
#include "input_win32.hpp"
#include "window_win32.hpp"
#include <Windows.h>
#include <unordered_map>
using namespace rb;
static std::unordered_map<keycode, int> key_map = {
{ keycode::left_system, VK_LWIN },
{ keycode::right_system, VK_RWIN },
{ keycode::menu, VK_APPS },
{ keycode::semicolon, VK_OEM_1 },
{ keycode::slash, VK_OEM_2 },
{ keycode::equal, VK_OEM_PLUS },
{ keycode::minus, VK_OEM_MINUS },
{ keycode::left_bracket, VK_OEM_4 },
{ keycode::right_bracket, VK_OEM_6 },
{ keycode::comma, VK_OEM_COMMA },
{ keycode::period, VK_OEM_PERIOD },
{ keycode::quote, VK_OEM_7 },
{ keycode::backslash, VK_OEM_5 },
{ keycode::tilde, VK_OEM_3 },
{ keycode::escape, VK_ESCAPE },
{ keycode::space, VK_SPACE },
{ keycode::enter, VK_RETURN },
{ keycode::backspace, VK_BACK },
{ keycode::tab, VK_TAB },
{ keycode::page_up, VK_PRIOR },
{ keycode::page_down, VK_NEXT },
{ keycode::end, VK_END },
{ keycode::home, VK_HOME },
{ keycode::insert, VK_INSERT },
{ keycode::del, VK_DELETE },
{ keycode::add, VK_ADD },
{ keycode::subtract, VK_SUBTRACT },
{ keycode::multiply, VK_MULTIPLY },
{ keycode::divide, VK_DIVIDE },
{ keycode::pause, VK_PAUSE },
{ keycode::f1, VK_F1 },
{ keycode::f2, VK_F2 },
{ keycode::f3, VK_F3 },
{ keycode::f4, VK_F4 },
{ keycode::f5, VK_F5 },
{ keycode::f6, VK_F6 },
{ keycode::f7, VK_F7 },
{ keycode::f8, VK_F8 },
{ keycode::f9, VK_F9 },
{ keycode::f10, VK_F10 },
{ keycode::f11, VK_F11 },
{ keycode::f12, VK_F12 },
{ keycode::f13, VK_F13 },
{ keycode::f14, VK_F14 },
{ keycode::f15, VK_F15 },
{ keycode::left, VK_LEFT },
{ keycode::right, VK_RIGHT },
{ keycode::up, VK_UP },
{ keycode::down, VK_DOWN },
{ keycode::numpad0, VK_NUMPAD0 },
{ keycode::numpad1, VK_NUMPAD1 },
{ keycode::numpad2, VK_NUMPAD2 },
{ keycode::numpad3, VK_NUMPAD3 },
{ keycode::numpad4, VK_NUMPAD4 },
{ keycode::numpad5, VK_NUMPAD5 },
{ keycode::numpad6, VK_NUMPAD6 },
{ keycode::numpad7, VK_NUMPAD7 },
{ keycode::numpad8, VK_NUMPAD8 },
{ keycode::numpad9, VK_NUMPAD9 },
{ keycode::a, 'A' },
{ keycode::b, 'B' },
{ keycode::c, 'C' },
{ keycode::d, 'D' },
{ keycode::e, 'E' },
{ keycode::f, 'F' },
{ keycode::g, 'G' },
{ keycode::h, 'H' },
{ keycode::i, 'I' },
{ keycode::j, 'J' },
{ keycode::k, 'K' },
{ keycode::l, 'L' },
{ keycode::m, 'M' },
{ keycode::n, 'N' },
{ keycode::o, 'O' },
{ keycode::p, 'P' },
{ keycode::q, 'Q' },
{ keycode::r, 'R' },
{ keycode::s, 'S' },
{ keycode::t, 'T' },
{ keycode::u, 'U' },
{ keycode::v, 'V' },
{ keycode::w, 'W' },
{ keycode::x, 'X' },
{ keycode::y, 'Y' },
{ keycode::z, 'Z' },
{ keycode::num0, '0' },
{ keycode::num1, '1' },
{ keycode::num2, '2' },
{ keycode::num3, '3' },
{ keycode::num4, '4' },
{ keycode::num5, '5' },
{ keycode::num6, '6' },
{ keycode::num7, '7' },
{ keycode::num8, '8' },
{ keycode::num9, '9' },
};
void input_win32::refresh() {
std::memcpy(_last_key_state, _key_state, sizeof(_key_state));
GetKeyboardState(_key_state);
std::memcpy(_last_mouse_state, _mouse_state, sizeof(_mouse_state));
_mouse_state[static_cast<std::size_t>(mouse_button::left)] = static_cast<std::uint8_t>(GetKeyState(VK_LBUTTON));
_mouse_state[static_cast<std::size_t>(mouse_button::middle)] = static_cast<std::uint8_t>(GetKeyState(VK_MBUTTON));
_mouse_state[static_cast<std::size_t>(mouse_button::right)] = static_cast<std::uint8_t>(GetKeyState(VK_RBUTTON));
}
bool input_win32::is_key_down(keycode key) {
const auto index = key_map[key];
return _key_state[index] & 0x80;
}
bool input_win32::is_key_up(keycode key) {
const auto index = key_map[key];
return (_key_state[index] & 0x80) == 0;
}
bool input_win32::is_key_pressed(keycode key) {
const auto index = key_map[key];
return (_key_state[index] & 0x80) && ((_last_key_state[index] & 0x80) == 0);
}
bool input_win32::is_key_released(keycode key) {
const auto index = key_map[key];
return ((_key_state[index] & 0x80) == 0) && (_last_key_state[index] & 0x80);
}
vec2i input_win32::mouse_position() {
POINT position;
if (GetCursorPos(&position) && ScreenToClient(window::native_handle(), &position)) {
return { position.x, position.y };
}
return { 0, 0 };
}
float input_win32::mouse_wheel() {
return 0.0f;
}
bool input_win32::is_mouse_button_down(mouse_button button) {
return _mouse_state[static_cast<std::size_t>(button)] & 0x80;
}
bool input_win32::is_mouse_button_up(mouse_button button) {
return (_mouse_state[static_cast<std::size_t>(button)] & 0x80) == 0;
}
bool input_win32::is_mouse_button_pressed(mouse_button button) {
return (_mouse_state[static_cast<std::size_t>(button)] & 0x80) &&
((_last_mouse_state[static_cast<std::size_t>(button)] & 0x80) == 0);
}
bool input_win32::is_mouse_button_released(mouse_button button) {
return ((_mouse_state[static_cast<std::size_t>(button)] & 0x80) == 0) &&
(_last_mouse_state[static_cast<std::size_t>(button)] & 0x80);
}
| 32.071006
| 119
| 0.587269
|
demurzasty
|
720b2358fe2a4572d5b19235af339cd0493a96c3
| 1,525
|
cpp
|
C++
|
January Challenge 2021/Long Challenge/BILLRD/main.cpp
|
pratheekpai/CodeChef
|
067ae2be32cd95a4fd77f1c2100d8db819ffe2ae
|
[
"MIT"
] | null | null | null |
January Challenge 2021/Long Challenge/BILLRD/main.cpp
|
pratheekpai/CodeChef
|
067ae2be32cd95a4fd77f1c2100d8db819ffe2ae
|
[
"MIT"
] | null | null | null |
January Challenge 2021/Long Challenge/BILLRD/main.cpp
|
pratheekpai/CodeChef
|
067ae2be32cd95a4fd77f1c2100d8db819ffe2ae
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
void point_of_impact(){
long long n, k, i, x, y, p;
cin >> n >> k >> x >> y;
if(x == y){
cout << n << " " << n << endl;
}
else if(y < x){
if(x == n && y == 0){
cout << x << " " << y << endl;
}
else {
p = n - x;
switch(k%4){
case 1: cout << n << " " << y+p << endl;
break;
case 2: cout << y+p << " " << n << endl;
break;
case 3: cout << 0 << " " << n - (y+p) << endl;
break;
default: cout << n - (y+p) << " " << 0 << endl;
break;
}
}
}
else if(x < y){
if(x == 0 && y == n){
cout << 0 << " " << y << endl;
}
else {
p = n - y;
switch(k%4){
case 1: cout << x+p << " " << n << endl;
break;
case 2: cout << n << " " << x+p << endl;
break;
case 3: cout << n - (x+p) << " " << 0 << endl;
break;
default: cout << 0 << " " << n - (x+p) <<endl;
break;
}
}
}
}
int main(){
long t;
cin >> t;
while(t--){
point_of_impact();
}
return 0;
}
| 25.847458
| 67
| 0.252459
|
pratheekpai
|
720d1e4ca36f2a3d8fe4762bd77b5a8bc3b5d837
| 126
|
cpp
|
C++
|
tests/PhiCore/compile_failure/src/core/scope_ptr/not_null_reset_nullptr.fail.cpp
|
AMS21/Phi
|
d62d7235dc5307dd18607ade0f95432ae3a73dfd
|
[
"MIT"
] | 3
|
2020-12-21T13:47:35.000Z
|
2022-03-16T23:53:21.000Z
|
tests/PhiCore/compile_failure/src/core/scope_ptr/not_null_reset_nullptr.fail.cpp
|
AMS21/Phi
|
d62d7235dc5307dd18607ade0f95432ae3a73dfd
|
[
"MIT"
] | 53
|
2020-08-07T07:46:57.000Z
|
2022-02-12T11:07:08.000Z
|
tests/PhiCore/compile_failure/src/core/scope_ptr/not_null_reset_nullptr.fail.cpp
|
AMS21/Phi
|
d62d7235dc5307dd18607ade0f95432ae3a73dfd
|
[
"MIT"
] | 1
|
2020-08-19T15:50:02.000Z
|
2020-08-19T15:50:02.000Z
|
#include <phi/core/scope_ptr.hpp>
int main()
{
phi::not_null_scope_ptr<int> ptr(new int(21));
ptr.reset(nullptr);
}
| 14
| 50
| 0.65873
|
AMS21
|
720e45e5d8839ea3929e61714f0f48dd1ebc33a4
| 912
|
cpp
|
C++
|
src/output/TableOutput.cpp
|
mironec/yoshiko
|
5fe02c9f0be3462959b334e1197ca9e6ea27345d
|
[
"MIT"
] | 4
|
2017-04-13T02:11:15.000Z
|
2021-11-29T18:04:16.000Z
|
src/output/TableOutput.cpp
|
mironec/yoshiko
|
5fe02c9f0be3462959b334e1197ca9e6ea27345d
|
[
"MIT"
] | 27
|
2018-01-15T08:37:38.000Z
|
2018-04-26T13:01:58.000Z
|
src/output/TableOutput.cpp
|
mironec/yoshiko
|
5fe02c9f0be3462959b334e1197ca9e6ea27345d
|
[
"MIT"
] | 3
|
2017-07-24T13:13:28.000Z
|
2019-04-10T19:09:56.000Z
|
#include "../output/TableOutput.h"
using namespace std;
namespace ysk {
void TableOutput::writeHeader(string label, size_t solution, size_t numberOfNodes, size_t numberOfClusters) {
_os<<numberOfNodes<<endl;
_os<<numberOfClusters<<endl;
_os<<"name\tcluster"<<endl;
}
void TableOutput::writeBeginNodes(size_t numberOfNodes) {
//
}
void TableOutput::writeNode(int nodeId, string name, size_t cluster, bool isLast) {
_os <<name<<"\t"<<cluster<<endl;
}
void TableOutput::writeEndNodes() {
//
}
void TableOutput::writeBeginEdges() {
//
}
void TableOutput::writeEdge(int sourceId, int targetId, string name, double weight, bool modified) {
//
}
void TableOutput::writeEndEdges() {
//
}
void TableOutput::writeBeginCluster(size_t cluster) {
//
}
void TableOutput::writeEndCluster(bool isLast) {
//
}
void TableOutput::writeFooter() {
//
}
} // namespace ysk
| 18.24
| 109
| 0.691886
|
mironec
|
720e69e272248e9022cc0c7c0fc9133b90eefc27
| 22,449
|
cpp
|
C++
|
tests/value.cpp
|
sinisa-susnjar/mgclient
|
81a1086aa066d5fc03e770b3f1b0bdf0d5f95f00
|
[
"Apache-2.0"
] | 30
|
2020-03-01T20:00:52.000Z
|
2022-03-22T08:40:07.000Z
|
tests/value.cpp
|
sinisa-susnjar/mgclient
|
81a1086aa066d5fc03e770b3f1b0bdf0d5f95f00
|
[
"Apache-2.0"
] | 11
|
2019-08-19T13:34:21.000Z
|
2022-03-18T11:25:15.000Z
|
tests/value.cpp
|
sinisa-susnjar/mgclient
|
81a1086aa066d5fc03e770b3f1b0bdf0d5f95f00
|
[
"Apache-2.0"
] | 4
|
2019-08-21T12:07:53.000Z
|
2021-08-01T22:23:00.000Z
|
// Copyright (c) 2016-2020 Memgraph Ltd. [https://memgraph.com]
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <string>
#include <gtest/gtest.h>
extern "C" {
#include "mgallocator.h"
#include "mgclient.h"
#include "mgcommon.h"
#include "mgvalue.h"
}
using namespace std::string_literals;
struct Null {};
bool Equal(const mg_value *lhs, Null) {
return mg_value_get_type(lhs) == MG_VALUE_TYPE_NULL;
}
bool Equal(const mg_value *lhs, bool rhs) {
return mg_value_get_type(lhs) == MG_VALUE_TYPE_BOOL &&
(mg_value_bool(lhs) != 0) == rhs;
}
bool Equal(const mg_value *lhs, int64_t rhs) {
return mg_value_get_type(lhs) == MG_VALUE_TYPE_INTEGER &&
mg_value_integer(lhs) == rhs;
}
bool Equal(const mg_value *lhs, double rhs) {
return mg_value_get_type(lhs) == MG_VALUE_TYPE_FLOAT &&
mg_value_float(lhs) == rhs;
}
bool Equal(const mg_string *lhs, const std::string &rhs) {
return mg_string_size(lhs) == rhs.size() &&
memcmp(mg_string_data(lhs), rhs.data(), rhs.size()) == 0;
}
bool Equal(const mg_value *lhs, const std::string &rhs) {
return mg_value_get_type(lhs) == MG_VALUE_TYPE_STRING &&
Equal(mg_value_string(lhs), rhs);
}
TEST(Value, Null) {
mg_value *val = mg_value_make_null();
EXPECT_TRUE(Equal(val, Null{}));
mg_value *val2 = mg_value_copy(val);
mg_value_destroy(val);
EXPECT_TRUE(Equal(val2, Null{}));
mg_value_destroy(val2);
}
TEST(Value, Bool) {
{
mg_value *val = mg_value_make_bool(0);
EXPECT_TRUE(Equal(val, false));
mg_value *val2 = mg_value_copy(val);
mg_value_destroy(val);
EXPECT_TRUE(Equal(val2, false));
mg_value_destroy(val2);
}
{
mg_value *val = mg_value_make_bool(1);
EXPECT_TRUE(Equal(val, true));
mg_value *val2 = mg_value_copy(val);
mg_value_destroy(val);
EXPECT_TRUE(Equal(val2, true));
mg_value_destroy(val2);
}
}
TEST(Value, Integer) {
mg_value *val = mg_value_make_integer(3289103);
EXPECT_TRUE(Equal(val, (int64_t)3289103));
mg_value *val2 = mg_value_copy(val);
mg_value_destroy(val);
EXPECT_TRUE(Equal(val2, (int64_t)3289103));
mg_value_destroy(val2);
}
TEST(Value, Float) {
mg_value *val = mg_value_make_float(3.289103);
EXPECT_TRUE(Equal(val, 3.289103));
mg_value *val2 = mg_value_copy(val);
mg_value_destroy(val);
EXPECT_TRUE(Equal(val2, 3.289103));
mg_value_destroy(val2);
}
TEST(Value, String) {
mg_string *str = mg_string_make2(5, "abcde");
EXPECT_TRUE(Equal(str, "abcde"s));
mg_string *str2 = mg_string_make("abcdefgh");
EXPECT_TRUE(Equal(str2, "abcdefgh"s));
mg_string_destroy(str2);
mg_string *str3 = mg_string_copy(str);
mg_string_destroy(str);
EXPECT_TRUE(Equal(str3, "abcde"s));
mg_value *val = mg_value_make_string2(str3);
EXPECT_TRUE(Equal(val, "abcde"s));
mg_value *val2 = mg_value_copy(val);
mg_value_destroy(val);
EXPECT_TRUE(Equal(val2, "abcde"s));
mg_value_destroy(val2);
}
TEST(Value, List) {
auto check_list = [](const mg_list *list) {
ASSERT_EQ(mg_list_size(list), 3u);
EXPECT_TRUE(Equal(mg_list_at(list, 0), Null{}));
EXPECT_TRUE(Equal(mg_list_at(list, 1), true));
EXPECT_TRUE(Equal(mg_list_at(list, 2), "abcde"s));
EXPECT_EQ(mg_list_at(list, 3), nullptr);
EXPECT_EQ(mg_list_at(list, 328321), nullptr);
};
mg_list *list = mg_list_make_empty(3);
EXPECT_EQ(mg_list_size(list), 0u);
EXPECT_EQ(mg_list_append(list, mg_value_make_null()), 0);
EXPECT_EQ(mg_list_size(list), 1u);
EXPECT_EQ(mg_list_append(list, mg_value_make_bool(1)), 0);
EXPECT_EQ(mg_list_size(list), 2u);
EXPECT_EQ(mg_list_append(list, mg_value_make_string("abcde")), 0);
EXPECT_EQ(mg_list_size(list), 3u);
{
mg_value *value = mg_value_make_float(3.14);
EXPECT_NE(mg_list_append(list, value), 0);
EXPECT_EQ(mg_list_size(list), 3u);
mg_value_destroy(value);
}
check_list(list);
mg_list *list2 = mg_list_copy(list);
mg_list_destroy(list);
check_list(list2);
mg_value *val = mg_value_make_list(list2);
EXPECT_EQ(mg_value_get_type(val), MG_VALUE_TYPE_LIST);
mg_value *val2 = mg_value_copy(val);
mg_value_destroy(val);
EXPECT_EQ(mg_value_get_type(val2), MG_VALUE_TYPE_LIST);
check_list(mg_value_list(val2));
mg_value_destroy(val2);
}
TEST(Value, Map) {
auto check_map = [](const mg_map *map) {
ASSERT_EQ(mg_map_size(map), 4u);
EXPECT_TRUE(Equal(mg_map_at(map, "x"), (int64_t)3));
EXPECT_TRUE(Equal(mg_map_at(map, "y"), false));
EXPECT_TRUE(Equal(mg_map_at(map, "key"), "value"s));
EXPECT_TRUE(Equal(mg_map_at(map, "key2"), "value2"s));
EXPECT_TRUE(Equal(mg_map_at2(map, 1, "x"), (int64_t)3));
EXPECT_TRUE(Equal(mg_map_at2(map, 1, "y"), false));
EXPECT_TRUE(Equal(mg_map_at2(map, 3, "key"), "value"s));
EXPECT_TRUE(Equal(mg_map_at2(map, 4, "key2"), "value2"s));
EXPECT_TRUE(Equal(mg_map_key_at(map, 0), "x"s));
EXPECT_TRUE(Equal(mg_map_key_at(map, 1), "y"s));
EXPECT_TRUE(Equal(mg_map_key_at(map, 2), "key"s));
EXPECT_TRUE(Equal(mg_map_key_at(map, 3), "key2"s));
EXPECT_TRUE(Equal(mg_map_value_at(map, 0), (int64_t)3));
EXPECT_TRUE(Equal(mg_map_value_at(map, 1), false));
EXPECT_TRUE(Equal(mg_map_value_at(map, 2), "value"s));
EXPECT_TRUE(Equal(mg_map_value_at(map, 3), "value2"s));
EXPECT_EQ(mg_map_at(map, "fjdkslfjdslk"), nullptr);
EXPECT_EQ(mg_map_key_at(map, 5), nullptr);
EXPECT_EQ(mg_map_key_at(map, 321321), nullptr);
EXPECT_EQ(mg_map_value_at(map, 5), nullptr);
EXPECT_EQ(mg_map_value_at(map, 78789789), nullptr);
};
mg_map *map = mg_map_make_empty(4);
EXPECT_EQ(mg_map_size(map), 0u);
// Test `insert` and `insert2` with failures for duplicate key.
{
EXPECT_EQ(mg_map_insert(map, "x", mg_value_make_integer(3)), 0);
EXPECT_EQ(mg_map_size(map), 1u);
}
{
mg_value *value = mg_value_make_integer(5);
EXPECT_NE(mg_map_insert(map, "x", value), 0);
EXPECT_EQ(mg_map_size(map), 1u);
mg_value_destroy(value);
}
{
EXPECT_EQ(mg_map_insert2(map, mg_string_make("y"), mg_value_make_bool(0)),
0);
EXPECT_EQ(mg_map_size(map), 2u);
}
{
mg_string *key = mg_string_make("y");
mg_value *value = mg_value_make_float(3.14);
EXPECT_NE(mg_map_insert2(map, key, value), 0);
EXPECT_EQ(mg_map_size(map), 2u);
mg_string_destroy(key);
mg_value_destroy(value);
}
// Test `insert_unsafe` and `insert_unsafe2`.
{
EXPECT_EQ(mg_map_insert_unsafe(map, "key", mg_value_make_string("value")),
0);
EXPECT_EQ(mg_map_size(map), 3u);
}
{
EXPECT_EQ(mg_map_insert_unsafe2(map, mg_string_make("key2"),
mg_value_make_string("value2")),
0);
EXPECT_EQ(mg_map_size(map), 4u);
}
// All insertions should fail now because the map is full.
{
mg_value *value = mg_value_make_null();
EXPECT_NE(mg_map_insert(map, "k1", value), 0);
EXPECT_EQ(mg_map_size(map), 4u);
mg_value_destroy(value);
}
{
mg_string *key = mg_string_make("k2");
mg_value *value = mg_value_make_null();
EXPECT_NE(mg_map_insert2(map, key, value), 0);
EXPECT_EQ(mg_map_size(map), 4u);
mg_string_destroy(key);
mg_value_destroy(value);
}
{
mg_value *value = mg_value_make_null();
EXPECT_NE(mg_map_insert_unsafe(map, "k3", value), 0);
EXPECT_EQ(mg_map_size(map), 4u);
mg_value_destroy(value);
}
{
mg_string *key = mg_string_make("k4");
mg_value *value = mg_value_make_null();
EXPECT_NE(mg_map_insert_unsafe2(map, key, value), 0);
EXPECT_EQ(mg_map_size(map), 4u);
mg_string_destroy(key);
mg_value_destroy(value);
}
check_map(map);
mg_map *map2 = mg_map_copy(map);
mg_map_destroy(map);
check_map(map2);
mg_value *val = mg_value_make_map(map2);
EXPECT_EQ(mg_value_get_type(val), MG_VALUE_TYPE_MAP);
check_map(mg_value_map(val));
mg_value *val2 = mg_value_copy(val);
mg_value_destroy(val);
EXPECT_EQ(mg_value_get_type(val2), MG_VALUE_TYPE_MAP);
check_map(mg_value_map(val2));
mg_value_destroy(val2);
}
TEST(Value, Node) {
auto check_node = [](const mg_node *node) {
EXPECT_EQ(mg_node_id(node), 1234);
EXPECT_EQ(mg_node_label_count(node), 2u);
EXPECT_TRUE(Equal(mg_node_label_at(node, 0), "Label1"s));
EXPECT_TRUE(Equal(mg_node_label_at(node, 1), "Label2"s));
EXPECT_EQ(mg_node_label_at(node, 2), nullptr);
EXPECT_EQ(mg_node_label_at(node, 328192), nullptr);
const mg_map *props = mg_node_properties(node);
EXPECT_EQ(mg_map_size(props), 2u);
EXPECT_TRUE(Equal(mg_map_key_at(props, 0), "x"s));
EXPECT_TRUE(Equal(mg_map_key_at(props, 1), "y"s));
EXPECT_TRUE(Equal(mg_map_value_at(props, 0), (int64_t)1));
EXPECT_TRUE(Equal(mg_map_value_at(props, 1), (int64_t)2));
};
mg_string *labels[2] = {mg_string_make("Label1"), mg_string_make("Label2")};
mg_map *props = mg_map_make_empty(2);
mg_map_insert_unsafe(props, "x", mg_value_make_integer(1));
mg_map_insert_unsafe(props, "y", mg_value_make_integer(2));
mg_node *node = mg_node_make(1234, 2, labels, props);
check_node(node);
mg_node *node2 = mg_node_copy(node);
mg_node_destroy(node);
check_node(node2);
mg_value *val = mg_value_make_node(node2);
EXPECT_EQ(mg_value_get_type(val), MG_VALUE_TYPE_NODE);
check_node(mg_value_node(val));
mg_value *val2 = mg_value_copy(val);
mg_value_destroy(val);
EXPECT_EQ(mg_value_get_type(val2), MG_VALUE_TYPE_NODE);
check_node(mg_value_node(val2));
mg_value_destroy(val2);
}
TEST(Value, Relationship) {
auto check_relationship = [](const mg_relationship *rel) {
EXPECT_EQ(mg_relationship_id(rel), 567);
EXPECT_EQ(mg_relationship_start_id(rel), 10);
EXPECT_EQ(mg_relationship_end_id(rel), 20);
EXPECT_TRUE(Equal(mg_relationship_type(rel), "EDGE"s));
const mg_map *props = mg_relationship_properties(rel);
EXPECT_EQ(mg_map_size(props), 2u);
EXPECT_TRUE(Equal(mg_map_key_at(props, 0), "x"s));
EXPECT_TRUE(Equal(mg_map_key_at(props, 1), "y"s));
EXPECT_TRUE(Equal(mg_map_value_at(props, 0), (int64_t)1));
EXPECT_TRUE(Equal(mg_map_value_at(props, 1), (int64_t)2));
};
mg_map *props = mg_map_make_empty(2);
mg_map_insert_unsafe(props, "x", mg_value_make_integer(1));
mg_map_insert_unsafe(props, "y", mg_value_make_integer(2));
mg_relationship *rel =
mg_relationship_make(567, 10, 20, mg_string_make("EDGE"), props);
check_relationship(rel);
mg_relationship *rel2 = mg_relationship_copy(rel);
mg_relationship_destroy(rel);
check_relationship(rel2);
mg_value *val = mg_value_make_relationship(rel2);
EXPECT_EQ(mg_value_get_type(val), MG_VALUE_TYPE_RELATIONSHIP);
check_relationship(mg_value_relationship(val));
mg_value *val2 = mg_value_copy(val);
mg_value_destroy(val);
EXPECT_EQ(mg_value_get_type(val2), MG_VALUE_TYPE_RELATIONSHIP);
check_relationship(mg_value_relationship(val2));
mg_value_destroy(val2);
}
TEST(Value, UnboundRelationship) {
auto check_unbound_relationship = [](const mg_unbound_relationship *rel) {
EXPECT_EQ(mg_unbound_relationship_id(rel), 567);
EXPECT_TRUE(Equal(mg_unbound_relationship_type(rel), "EDGE"s));
const mg_map *props = mg_unbound_relationship_properties(rel);
EXPECT_EQ(mg_map_size(props), 2u);
EXPECT_TRUE(Equal(mg_map_key_at(props, 0), "x"s));
EXPECT_TRUE(Equal(mg_map_key_at(props, 1), "y"s));
EXPECT_TRUE(Equal(mg_map_value_at(props, 0), (int64_t)1));
EXPECT_TRUE(Equal(mg_map_value_at(props, 1), (int64_t)2));
};
mg_map *props = mg_map_make_empty(2);
mg_map_insert_unsafe(props, "x", mg_value_make_integer(1));
mg_map_insert_unsafe(props, "y", mg_value_make_integer(2));
mg_unbound_relationship *rel =
mg_unbound_relationship_make(567, mg_string_make("EDGE"), props);
check_unbound_relationship(rel);
mg_unbound_relationship *rel2 = mg_unbound_relationship_copy(rel);
mg_unbound_relationship_destroy(rel);
check_unbound_relationship(rel2);
mg_value *val = mg_value_make_unbound_relationship(rel2);
EXPECT_EQ(mg_value_get_type(val), MG_VALUE_TYPE_UNBOUND_RELATIONSHIP);
check_unbound_relationship(mg_value_unbound_relationship(val));
mg_value *val2 = mg_value_copy(val);
mg_value_destroy(val);
EXPECT_EQ(mg_value_get_type(val2), MG_VALUE_TYPE_UNBOUND_RELATIONSHIP);
check_unbound_relationship(mg_value_unbound_relationship(val2));
mg_value_destroy(val2);
}
TEST(Value, Path) {
const int64_t indices[] = {1, 1, -2, 2, 3, 0, 1, 1, -4, 3, 5, 3};
auto check_path = [](const mg_path *path) {
EXPECT_EQ(mg_path_length(path), 6u);
EXPECT_EQ(mg_node_id(mg_path_node_at(path, 0)), 1);
EXPECT_EQ(mg_node_id(mg_path_node_at(path, 1)), 2);
EXPECT_EQ(mg_node_id(mg_path_node_at(path, 2)), 3);
EXPECT_EQ(mg_node_id(mg_path_node_at(path, 3)), 1);
EXPECT_EQ(mg_node_id(mg_path_node_at(path, 4)), 2);
EXPECT_EQ(mg_node_id(mg_path_node_at(path, 5)), 4);
EXPECT_EQ(mg_node_id(mg_path_node_at(path, 6)), 4);
EXPECT_EQ(mg_path_node_at(path, 7), nullptr);
EXPECT_EQ(mg_path_node_at(path, 328190321), nullptr);
EXPECT_EQ(mg_unbound_relationship_id(mg_path_relationship_at(path, 0)), 12);
EXPECT_EQ(mg_unbound_relationship_id(mg_path_relationship_at(path, 1)), 32);
EXPECT_EQ(mg_unbound_relationship_id(mg_path_relationship_at(path, 2)), 31);
EXPECT_EQ(mg_unbound_relationship_id(mg_path_relationship_at(path, 3)), 12);
EXPECT_EQ(mg_unbound_relationship_id(mg_path_relationship_at(path, 4)), 42);
EXPECT_EQ(mg_unbound_relationship_id(mg_path_relationship_at(path, 5)), 44);
EXPECT_EQ(mg_path_relationship_at(path, 6), nullptr);
EXPECT_EQ(mg_path_relationship_at(path, 38290187), nullptr);
EXPECT_EQ(mg_path_relationship_reversed_at(path, 0), 0);
EXPECT_EQ(mg_path_relationship_reversed_at(path, 1), 1);
EXPECT_EQ(mg_path_relationship_reversed_at(path, 2), 0);
EXPECT_EQ(mg_path_relationship_reversed_at(path, 3), 0);
EXPECT_EQ(mg_path_relationship_reversed_at(path, 4), 1);
EXPECT_EQ(mg_path_relationship_reversed_at(path, 5), 0);
EXPECT_EQ(mg_path_relationship_reversed_at(path, 6), -1);
EXPECT_EQ(mg_path_relationship_reversed_at(path, 83291038), -1);
};
mg_node *nodes[] = {mg_node_make(1, 0, NULL, mg_map_make_empty(0)),
mg_node_make(2, 0, NULL, mg_map_make_empty(0)),
mg_node_make(3, 0, NULL, mg_map_make_empty(0)),
mg_node_make(4, 0, NULL, mg_map_make_empty(0))};
mg_unbound_relationship *relationships[] = {
mg_unbound_relationship_make(12, mg_string_make("EDGE"),
mg_map_make_empty(0)),
mg_unbound_relationship_make(32, mg_string_make("EDGE"),
mg_map_make_empty(0)),
mg_unbound_relationship_make(31, mg_string_make("EDGE"),
mg_map_make_empty(0)),
mg_unbound_relationship_make(42, mg_string_make("EDGE"),
mg_map_make_empty(0)),
mg_unbound_relationship_make(44, mg_string_make("EDGE"),
mg_map_make_empty(0))};
mg_path *path = mg_path_make(4, nodes, 5, relationships,
sizeof(indices) / sizeof(int64_t), indices);
check_path(path);
mg_path *path2 = mg_path_copy(path);
mg_path_destroy(path);
check_path(path2);
mg_value *val = mg_value_make_path(path2);
EXPECT_EQ(mg_value_get_type(val), MG_VALUE_TYPE_PATH);
check_path(mg_value_path(val));
mg_value *val2 = mg_value_copy(val);
mg_value_destroy(val);
EXPECT_EQ(mg_value_get_type(val2), MG_VALUE_TYPE_PATH);
check_path(mg_value_path(val2));
mg_value_destroy(val2);
}
TEST(Value, Date) {
{
mg_date *date = mg_date_alloc(&mg_system_allocator);
date->days = 1;
EXPECT_EQ(mg_date_days(date), static_cast<int64_t>(1));
mg_date *date2 = mg_date_copy(date);
mg_date_destroy(date);
EXPECT_EQ(mg_date_days(date2), static_cast<int64_t>(1));
mg_date_destroy(date2);
}
}
TEST(Value, Time) {
{
mg_time *time = mg_time_alloc(&mg_system_allocator);
time->nanoseconds = 1;
time->tz_offset_seconds = 1;
EXPECT_EQ(mg_time_nanoseconds(time), static_cast<int64_t>(1));
EXPECT_EQ(mg_time_tz_offset_seconds(time), static_cast<int64_t>(1));
mg_time *time2 = mg_time_copy(time);
mg_time_destroy(time);
EXPECT_EQ(mg_time_nanoseconds(time2), static_cast<int64_t>(1));
EXPECT_EQ(mg_time_tz_offset_seconds(time2), static_cast<int64_t>(1));
mg_time_destroy(time2);
}
}
TEST(Value, LocalTime) {
{
mg_local_time *local_time = mg_local_time_alloc(&mg_system_allocator);
local_time->nanoseconds = 1;
EXPECT_EQ(mg_local_time_nanoseconds(local_time), static_cast<int64_t>(1));
mg_local_time *local_time2 = mg_local_time_copy(local_time);
mg_local_time_destroy(local_time);
EXPECT_EQ(mg_local_time_nanoseconds(local_time2), static_cast<int64_t>(1));
mg_local_time_destroy(local_time2);
}
}
TEST(Value, DateTime) {
{
mg_date_time *date_time = mg_date_time_alloc(&mg_system_allocator);
date_time->seconds = 1;
date_time->nanoseconds = 1;
date_time->tz_offset_minutes = 1;
EXPECT_EQ(mg_date_time_seconds(date_time), static_cast<int64_t>(1));
EXPECT_EQ(mg_date_time_nanoseconds(date_time), static_cast<int64_t>(1));
EXPECT_EQ(mg_date_time_tz_offset_minutes(date_time),
static_cast<int64_t>(1));
mg_date_time *date_time2 = mg_date_time_copy(date_time);
mg_date_time_destroy(date_time);
EXPECT_EQ(mg_date_time_seconds(date_time2), static_cast<int64_t>(1));
EXPECT_EQ(mg_date_time_nanoseconds(date_time2), static_cast<int64_t>(1));
EXPECT_EQ(mg_date_time_tz_offset_minutes(date_time2),
static_cast<int64_t>(1));
mg_date_time_destroy(date_time2);
}
}
TEST(Value, DateTimeZoneId) {
{
mg_date_time_zone_id *date_time_zone_id =
mg_date_time_zone_id_alloc(&mg_system_allocator);
date_time_zone_id->seconds = 1;
date_time_zone_id->nanoseconds = 1;
date_time_zone_id->tz_id = 1;
EXPECT_EQ(mg_date_time_zone_id_seconds(date_time_zone_id),
static_cast<int64_t>(1));
EXPECT_EQ(mg_date_time_zone_id_nanoseconds(date_time_zone_id),
static_cast<int64_t>(1));
EXPECT_EQ(mg_date_time_zone_id_tz_id(date_time_zone_id),
static_cast<int64_t>(1));
mg_date_time_zone_id *date_time_zone_id2 =
mg_date_time_zone_id_copy(date_time_zone_id);
mg_date_time_zone_id_destroy(date_time_zone_id);
EXPECT_EQ(mg_date_time_zone_id_seconds(date_time_zone_id2),
static_cast<int64_t>(1));
EXPECT_EQ(mg_date_time_zone_id_nanoseconds(date_time_zone_id2),
static_cast<int64_t>(1));
EXPECT_EQ(mg_date_time_zone_id_tz_id(date_time_zone_id2),
static_cast<int64_t>(1));
mg_date_time_zone_id_destroy(date_time_zone_id2);
}
}
TEST(Value, LocalDateTime) {
{
mg_local_date_time *local_date_time =
mg_local_date_time_alloc(&mg_system_allocator);
local_date_time->seconds = 1;
local_date_time->nanoseconds = 1;
EXPECT_EQ(mg_local_date_time_seconds(local_date_time),
static_cast<int64_t>(1));
EXPECT_EQ(mg_local_date_time_nanoseconds(local_date_time),
static_cast<int64_t>(1));
mg_local_date_time *local_date_time2 =
mg_local_date_time_copy(local_date_time);
mg_local_date_time_destroy(local_date_time);
EXPECT_EQ(mg_local_date_time_seconds(local_date_time2),
static_cast<int64_t>(1));
EXPECT_EQ(mg_local_date_time_nanoseconds(local_date_time2),
static_cast<int64_t>(1));
mg_local_date_time_destroy(local_date_time2);
}
}
TEST(Value, Duration) {
{
mg_duration *duration = mg_duration_alloc(&mg_system_allocator);
duration->months = 1;
duration->days = 1;
duration->seconds = 1;
duration->nanoseconds = 1;
EXPECT_EQ(mg_duration_months(duration), static_cast<int64_t>(1));
EXPECT_EQ(mg_duration_days(duration), static_cast<int64_t>(1));
EXPECT_EQ(mg_duration_seconds(duration), static_cast<int64_t>(1));
EXPECT_EQ(mg_duration_nanoseconds(duration), static_cast<int64_t>(1));
mg_duration *duration2 = mg_duration_copy(duration);
mg_duration_destroy(duration);
EXPECT_EQ(mg_duration_months(duration2), static_cast<int64_t>(1));
EXPECT_EQ(mg_duration_days(duration2), static_cast<int64_t>(1));
EXPECT_EQ(mg_duration_seconds(duration2), static_cast<int64_t>(1));
EXPECT_EQ(mg_duration_nanoseconds(duration2), static_cast<int64_t>(1));
mg_duration_destroy(duration2);
}
}
TEST(Value, Point2d) {
{
mg_point_2d *point_2d = mg_point_2d_alloc(&mg_system_allocator);
point_2d->srid = 1;
point_2d->x = 1.0;
point_2d->y = 1.0;
EXPECT_EQ(mg_point_2d_srid(point_2d), static_cast<int64_t>(1));
EXPECT_EQ(mg_point_2d_x(point_2d), 1.0);
EXPECT_EQ(mg_point_2d_y(point_2d), 1.0);
mg_point_2d *point_2d2 = mg_point_2d_copy(point_2d);
mg_point_2d_destroy(point_2d);
EXPECT_EQ(mg_point_2d_srid(point_2d2), static_cast<int64_t>(1));
EXPECT_EQ(mg_point_2d_x(point_2d2), 1.0);
EXPECT_EQ(mg_point_2d_y(point_2d2), 1.0);
mg_point_2d_destroy(point_2d2);
}
}
TEST(Value, Point3d) {
{
mg_point_3d *point_3d = mg_point_3d_alloc(&mg_system_allocator);
point_3d->srid = 1;
point_3d->x = 1.0;
point_3d->y = 1.0;
point_3d->z = 1.0;
EXPECT_EQ(mg_point_3d_srid(point_3d), static_cast<int64_t>(1));
EXPECT_EQ(mg_point_3d_x(point_3d), 1.0);
EXPECT_EQ(mg_point_3d_y(point_3d), 1.0);
EXPECT_EQ(mg_point_3d_z(point_3d), 1.0);
mg_point_3d *point_3d2 = mg_point_3d_copy(point_3d);
mg_point_3d_destroy(point_3d);
EXPECT_EQ(mg_point_3d_srid(point_3d2), static_cast<int64_t>(1));
EXPECT_EQ(mg_point_3d_x(point_3d2), 1.0);
EXPECT_EQ(mg_point_3d_y(point_3d2), 1.0);
EXPECT_EQ(mg_point_3d_z(point_3d2), 1.0);
mg_point_3d_destroy(point_3d2);
}
}
| 35.9184
| 80
| 0.71139
|
sinisa-susnjar
|
72124b5d1a1bdc5b89468906144d2f8dd5aa0f4f
| 951
|
cpp
|
C++
|
src/rotate-list.cpp
|
amoudgl/leetcode-solutions
|
dc6570bb06b82c2c70d6f387b3486897035cc995
|
[
"MIT"
] | null | null | null |
src/rotate-list.cpp
|
amoudgl/leetcode-solutions
|
dc6570bb06b82c2c70d6f387b3486897035cc995
|
[
"MIT"
] | null | null | null |
src/rotate-list.cpp
|
amoudgl/leetcode-solutions
|
dc6570bb06b82c2c70d6f387b3486897035cc995
|
[
"MIT"
] | null | null | null |
// Author: Abhinav Moudgil [ https://leetcode.com/amoudgl/ ]
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
ListNode *ptr;
ListNode *HEAD;
ptr = head;
HEAD = head;
int l = 0;
while (ptr != NULL)
{
ptr = ptr->next;
l++;
}
if (l == 0) return NULL;
ptr = head;
k = k % l;
Rotate(HEAD, ptr, k);
return HEAD;
}
void Rotate(ListNode* &head, ListNode *ptr, int &k)
{
if (ptr == NULL)
return;
else if (ptr->next == NULL) ptr->next = head;
else Rotate(head, ptr->next, k);
k--;
if (k == -1)
{
head = ptr->next;
ptr->next = NULL;
}
}
};
| 22.116279
| 60
| 0.446898
|
amoudgl
|
721737962dc6ed67f62c0ca81ca7146f3c7bc9ad
| 2,990
|
cpp
|
C++
|
02_camera/source/program.cpp
|
DamianReloaded/ModernOpenGL
|
c7fe024e4d13c7bd06c0704fa66124ddf7ea75fa
|
[
"MIT"
] | null | null | null |
02_camera/source/program.cpp
|
DamianReloaded/ModernOpenGL
|
c7fe024e4d13c7bd06c0704fa66124ddf7ea75fa
|
[
"MIT"
] | null | null | null |
02_camera/source/program.cpp
|
DamianReloaded/ModernOpenGL
|
c7fe024e4d13c7bd06c0704fa66124ddf7ea75fa
|
[
"MIT"
] | null | null | null |
#include "program.h"
#include <fstream>
#include <sstream>
#include <vector>
#include <GL/glew.h>
using namespace reload;
program::program()
{
//ctor
}
program::~program()
{
//dtor
}
const uint32_t& program::id()
{
return m_id;
}
bool program::load (const std::string& _path_vertex_shader, const std::string& _path_fragment_shader)
{
uint32_t vertex_shader_id = glCreateShader(GL_VERTEX_SHADER);
uint32_t fragment_shader_id = glCreateShader(GL_FRAGMENT_SHADER);
int result = GL_FALSE;
int info = 0;
std::string vertex_shader_code;
std::ifstream vertex_shader_file(_path_vertex_shader, std::ios::in);
if (vertex_shader_file.is_open())
{
std::stringstream sstr;
sstr << vertex_shader_file.rdbuf();
vertex_shader_code = sstr.str();
vertex_shader_file.close();
char const* ptr = vertex_shader_code.c_str();
glShaderSource(vertex_shader_id, 1, &ptr, NULL);
glCompileShader(vertex_shader_id);
glGetShaderiv(vertex_shader_id, GL_COMPILE_STATUS, &result);
glGetShaderiv(vertex_shader_id, GL_INFO_LOG_LENGTH, &info);
if (info > 0)
{
std::vector<char> vertex_shader_error_message(info+1);
glGetShaderInfoLog(vertex_shader_id, info, NULL, &vertex_shader_error_message[0]);
return false;
}
}
else
{
return false;
}
std::string fragment_shader_code;
std::ifstream fragment_shader_file(_path_fragment_shader, std::ios::in);
if (fragment_shader_file.is_open())
{
std::stringstream sstr;
sstr << fragment_shader_file.rdbuf();
fragment_shader_code = sstr.str();
fragment_shader_file.close();
char const* ptr = fragment_shader_code.c_str();
glShaderSource(fragment_shader_id, 1, &ptr, NULL);
glCompileShader(fragment_shader_id);
glGetShaderiv(fragment_shader_id, GL_COMPILE_STATUS, &result);
glGetShaderiv(fragment_shader_id, GL_INFO_LOG_LENGTH, &info);
if (info > 0)
{
std::vector<char> fragment_shader_error_message(info+1);
glGetShaderInfoLog(fragment_shader_id, info, NULL, &fragment_shader_error_message[0]);
return false;
}
}
else
{
return false;
}
m_id = glCreateProgram();
glAttachShader(m_id, vertex_shader_id);
glAttachShader(m_id, fragment_shader_id);
glLinkProgram(m_id);
glGetProgramiv(m_id, GL_LINK_STATUS, &result);
glGetProgramiv(m_id, GL_INFO_LOG_LENGTH, &info);
if (info > 0)
{
std::vector<char> program_error_message(info+1);
glGetProgramInfoLog(m_id, info, NULL, &program_error_message[0]);
return false;
}
glDetachShader(m_id, vertex_shader_id);
glDetachShader(m_id, fragment_shader_id);
glDeleteShader(vertex_shader_id);
glDeleteShader(fragment_shader_id);
return true;
}
void program::use()
{
glUseProgram(m_id);
}
| 27.431193
| 101
| 0.666221
|
DamianReloaded
|
721a73cea2ba9a66abd9651520c16dcf693fd4bb
| 5,068
|
hpp
|
C++
|
include/atomic_ops/atomic_ops.hpp
|
ldalessa/atomic_ops
|
b718286789732fe36107b170e9a73b058db609ff
|
[
"BSD-3-Clause"
] | null | null | null |
include/atomic_ops/atomic_ops.hpp
|
ldalessa/atomic_ops
|
b718286789732fe36107b170e9a73b058db609ff
|
[
"BSD-3-Clause"
] | null | null | null |
include/atomic_ops/atomic_ops.hpp
|
ldalessa/atomic_ops
|
b718286789732fe36107b170e9a73b058db609ff
|
[
"BSD-3-Clause"
] | null | null | null |
// BSD 3-Clause License
//
// Copyright (c) 2020, Luke D'Alessandro
// Copyright (c) 2020, Trustees of Indiana University
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#pragma once
#include <memory>
namespace atomic_ops {
enum memory_order : int {
acquire = __ATOMIC_ACQUIRE,
relaxed = __ATOMIC_RELAXED,
release = __ATOMIC_RELEASE,
acq_rel = __ATOMIC_ACQ_REL,
seq_cst = __ATOMIC_SEQ_CST
};
template <typename T>
constexpr T load(T& t, memory_order order) {
return __atomic_load_n(std::addressof(t), order);
}
template <typename T, typename U>
constexpr void store(T& t, U u, memory_order order) {
__atomic_store_n(std::addressof(t), u, order);
}
template <typename T, typename U>
constexpr T fetch_add(T& t, U u, memory_order order) {
return __atomic_fetch_add(std::addressof(t), u, order);
}
template <typename T, typename U>
constexpr T fetch_and(T& t, U u, memory_order order) {
return __atomic_fetch_and(std::addressof(t), u, order);
}
template <typename T, typename U>
constexpr T fetch_or(T& t, U u, memory_order order) {
return __atomic_fetch_or(std::addressof(t), u, order);
}
enum MemoryModel {
SequentialConsistency,
ReleaseConsistency,
RelaxedConsistency,
Unsynchronized
};
template <MemoryModel mm>
struct mm_tag {
constexpr operator MemoryModel() const {
return mm;
}
};
inline constexpr mm_tag<SequentialConsistency> sc = {};
inline constexpr mm_tag<ReleaseConsistency> rc = {};
inline constexpr mm_tag<RelaxedConsistency> xc = {};
inline constexpr mm_tag<Unsynchronized> unsync = {};
static constexpr memory_order load_order(MemoryModel mm) {
switch (mm) {
case SequentialConsistency: return seq_cst;
case ReleaseConsistency: return acquire;
case RelaxedConsistency: return relaxed;
case Unsynchronized: return relaxed;
};
__builtin_unreachable();
}
static constexpr memory_order store_order(MemoryModel mm) {
switch (mm) {
case SequentialConsistency: return seq_cst;
case ReleaseConsistency: return release;
case RelaxedConsistency: return relaxed;
case Unsynchronized: return relaxed;
};
__builtin_unreachable();
}
static constexpr memory_order rmw_order(MemoryModel mm) {
switch (mm) {
case SequentialConsistency: return seq_cst;
case ReleaseConsistency: return acq_rel;
case RelaxedConsistency: return relaxed;
case Unsynchronized: return relaxed;
};
__builtin_unreachable();
}
template <MemoryModel mm, typename T>
constexpr T load(T& t, mm_tag<mm> = {}) {
if constexpr (mm == Unsynchronized) {
return t;
}
else {
return load(t, load_order(mm));
}
}
template <MemoryModel mm, typename T, typename U>
void store(T& t, U u, mm_tag<mm> = {}) {
if constexpr (mm == Unsynchronized) {
t = u;
}
else {
store(t, u, store_order(mm));
}
}
template <MemoryModel mm, typename T, typename U>
T fetch_add(T& t, U u, mm_tag<mm> = {}) {
if constexpr (mm == Unsynchronized) {
T temp = t;
t = temp + u;
return temp;
}
else {
return fetch_add(t, u, rmw_order(mm));
}
}
template <MemoryModel mm, typename T, typename U>
T fetch_and(T& t, U u, mm_tag<mm> = {}) {
if constexpr (mm == Unsynchronized) {
T temp = t;
t = temp & u;
return temp;
}
else {
return fetch_and(t, u, rmw_order(mm));
}
}
template <MemoryModel mm, typename T, typename U>
T fetch_or(T& t, U u, mm_tag<mm> = {}) {
if constexpr (mm == Unsynchronized) {
T temp = t;
t = temp | u;
return temp;
}
else {
return fetch_or(t, u, rmw_order(mm));
}
}
}
| 29.126437
| 81
| 0.709747
|
ldalessa
|
721dfcb5a7fa7feae736e75dd26a4e38ca9a7206
| 9,614
|
cpp
|
C++
|
crashfix_service/libdumper_tests/StackWalkerTests.cpp
|
jsonzilla/crashfix
|
278a0dfb94f815709067bef61e64f1b290f17fa0
|
[
"BSD-3-Clause"
] | 3
|
2019-01-07T20:55:30.000Z
|
2019-04-10T10:04:16.000Z
|
crashfix_service/libdumper_tests/StackWalkerTests.cpp
|
0um/crashfix
|
f283498b92efbaf150f6f09251d4bd69d8335a6b
|
[
"BSD-3-Clause"
] | 9
|
2020-04-04T13:33:00.000Z
|
2020-04-04T13:33:18.000Z
|
crashfix_service/libdumper_tests/StackWalkerTests.cpp
|
jsonzilla/crashfix
|
278a0dfb94f815709067bef61e64f1b290f17fa0
|
[
"BSD-3-Clause"
] | 1
|
2021-04-25T14:26:27.000Z
|
2021-04-25T14:26:27.000Z
|
#include "stdafx.h"
#include "Tests.h"
#include "Utils.h"
#include "MiniDumpReader.h"
#include "StackWalker.h"
#include "Thread.h"
#include "FileFinder.h"
#include "CrashReportReader.h"
#include "strconv.h"
class StackWalkerTests : public CTestCase
{
BEGIN_TEST_MAP(StackWalkerTests, "CStackWalker class tests")
REGISTER_TEST(Test_GetCallStack);
REGISTER_TEST(Test_GetCallStack_x64);
REGISTER_TEST(Test_GetCallStack_fpo);
REGISTER_TEST(Test_GetCallStack_multithreaded);
END_TEST_MAP()
public:
void SetUp();
void TearDown();
void Test_GetCallStack();
void Test_GetCallStack_multithreaded();
void Test_GetCallStack_x64();
void DoStackWalk(bool bInWorkerThread);
void Test_GetCallStack_fpo();
std::vector<std::wstring> m_asCrashReports;
CPdbCache* m_pPdbCache;
};
REGISTER_TEST_CASE( StackWalkerTests );
void StackWalkerTests::SetUp()
{
/* initialize random seed: */
srand ( (unsigned int)time(NULL) );
m_pPdbCache = NULL;
}
void StackWalkerTests::TearDown()
{
}
void StackWalkerTests::Test_GetCallStack()
{
wstring sFileName = Utils::GetTestDataFolder();
#ifdef _WIN32
sFileName += L"vs2010\\2\\crashdump.dmp";
#else
sFileName += L"vs2010/2/crashdump.dmp";
#endif
CMiniDumpReader MdmpReader;
CStackWalker StackWalker;
CPdbCache PdbCache;
BOOL bFrame = FALSE;
BOOL bInitStackWalker = FALSE;
BOOL bReadDump = FALSE;
MiniDumpExceptionInfo* pExcInfo = NULL;
DWORD dwExcThreadId = 0;
int nFrame = 0;
// Set the directory where to look for PDB files - assume success
bool bAddSearchDir = PdbCache.AddPdbSearchDir(Utils::GetTestDataFolder(), PDB_USUAL_DIR, true);
TEST_ASSERT(bAddSearchDir);
// Open minidump
bReadDump = MdmpReader.Init(sFileName);
TEST_ASSERT(bReadDump);
// Get exception thread id
pExcInfo = MdmpReader.GetExceptionInfo();
dwExcThreadId = pExcInfo->m_uThreadId;
// Init stack walker
bInitStackWalker = StackWalker.Init(&MdmpReader, &PdbCache, dwExcThreadId);
TEST_ASSERT(bInitStackWalker);
bFrame = StackWalker.FirstStackFrame();
while(bFrame)
{
CStackFrame* pStackFrame = StackWalker.GetStackFrame();
if(!pStackFrame)
break;
if(nFrame==0)
{
TEST_ASSERT(pStackFrame->m_sUndecoratedSymbolName=="crEmulateCrash()");
TEST_ASSERT(pStackFrame->m_nSrcLineNumber==828);
TEST_ASSERT(pStackFrame->m_sModuleName==L"CrashRpt1400.dll");
}
if(nFrame==25)
{
TEST_ASSERT(pStackFrame->m_sUndecoratedSymbolName=="__tmainCRTStartup()");
TEST_ASSERT(pStackFrame->m_sSrcFileName==L"f:\\dd\\vctools\\crt_bld\\self_x86\\crt\\src\\crtexe.c");
TEST_ASSERT(pStackFrame->m_nSrcLineNumber==547);
TEST_ASSERT(pStackFrame->m_sModuleName==L"WTLDemo.exe");
}
nFrame++;
bFrame = StackWalker.NextStackFrame();
}
// Ensure only one frame
TEST_ASSERT(nFrame==29);
__TEST_CLEANUP__;
}
void StackWalkerTests::Test_GetCallStack_x64()
{
wstring sFileName = Utils::GetTestDataFolder();
#ifdef _WIN32
sFileName += L"vs2010\\x64\\2\\crashdump.dmp";
#else
sFileName += L"vs2010/x64/2/crashdump.dmp";
#endif
CMiniDumpReader MdmpReader;
CStackWalker StackWalker;
CPdbCache PdbCache;
BOOL bFrame = FALSE;
BOOL bInitStackWalker = FALSE;
BOOL bReadDump = FALSE;
MiniDumpExceptionInfo* pExcInfo = NULL;
DWORD dwExcThreadId = 0;
int nFrame = 0;
// Set the directory where to look for PDB files - assume success
bool bAddSearchDir = PdbCache.AddPdbSearchDir(Utils::GetTestDataFolder(), PDB_USUAL_DIR, true);
TEST_ASSERT(bAddSearchDir);
// Open minidump
bReadDump = MdmpReader.Init(sFileName);
TEST_ASSERT(bReadDump);
// Get exception thread id
pExcInfo = MdmpReader.GetExceptionInfo();
dwExcThreadId = pExcInfo->m_uThreadId;
// Init stack walker
bInitStackWalker = StackWalker.Init(&MdmpReader, &PdbCache, dwExcThreadId);
TEST_ASSERT(bInitStackWalker);
bFrame = StackWalker.FirstStackFrame();
while(bFrame)
{
CStackFrame* pStackFrame = StackWalker.GetStackFrame();
if(!pStackFrame)
break;
if(nFrame==0)
{
TEST_ASSERT(pStackFrame->m_sSymbolName=="crEmulateCrash");
}
nFrame++;
bFrame = StackWalker.NextStackFrame();
}
// Ensure only one frame
TEST_ASSERT(nFrame==2);
__TEST_CLEANUP__;
}
class CStackWalkerTestThread : public CThread
{
public:
long ThreadProc(void* pParam)
{
StackWalkerTests* pStackWalkerTests = (StackWalkerTests*)pParam;
pStackWalkerTests->DoStackWalk(true);
return 0;
}
};
void StackWalkerTests::Test_GetCallStack_multithreaded()
{
CFileFinder FileFinder;
CFindFileInfo ffi;
wstring sFileName = Utils::GetTestDataFolder();
sFileName += L"crashReports\\WTLDemo\\1.4.0.0\\*.zip";
bool bFind = false;
CStackWalkerTestThread WorkerThread;
CPdbCache PdbCache;
std::wstring sSearchDir;
bool bAddSearchDir = false;
bool bSetMaxCount = false;
PdbCacheStat Stat;
bool bGetStat = false;
// Set cache size
const int MAX_CACHE_SIZE = 5;
bSetMaxCount = PdbCache.SetMaxEntryCount(MAX_CACHE_SIZE);
TEST_ASSERT(bSetMaxCount);
// Add valid search dir - assume success
sSearchDir = Utils::GetTestDataFolder();
sSearchDir += L"debugInfo";
bAddSearchDir = PdbCache.AddPdbSearchDir(sSearchDir, PDB_SYMBOL_STORE, true);
TEST_ASSERT(bAddSearchDir==true);
m_pPdbCache = &PdbCache;
// Get the list of crash reports in the directory
bFind = FileFinder.FindFirstFile(sFileName, &ffi);
while(bFind)
{
m_asCrashReports.push_back(ffi.m_sFileName);
bFind = FileFinder.FindNextFile(&ffi);
}
// Ensure some files found
TEST_ASSERT(m_asCrashReports.size()>=10);
// Run worker thread
WorkerThread.Run(this);
// Do our work
DoStackWalk(false);
// Wait until thread exists
WorkerThread.Wait();
// Ensure all cache entries are unreferenced
bGetStat = PdbCache.GetCacheStat(&Stat);
TEST_ASSERT(bGetStat);
TEST_ASSERT(Stat.m_nEntryCount==Stat.m_nUnrefCount);
__TEST_CLEANUP__;
}
void StackWalkerTests::DoStackWalk(bool bInWorkerThread)
{
int nAttempt;
for(nAttempt=0; nAttempt<100; nAttempt++)
{
CCrashReportReader CrashRptReader;
CMiniDumpReader* pMiniDump = NULL;
CStackWalker StackWalker;
BOOL bSymbolsFound = FALSE;
BOOL bInit = FALSE;
// Choose report randomly
int n = rand()%m_asCrashReports.size();
std::wstring sFileName = m_asCrashReports[n];
if(bInWorkerThread)
printf(",%d", n);
else
printf(".%d", n);
// Init report
bInit = CrashRptReader.Init(sFileName);
TEST_ASSERT_MSG(bInit, "Error opening crash report %s: %s",
strconv::w2a(sFileName).c_str(),
strconv::w2a(CrashRptReader.GetErrorMsg()).c_str());
pMiniDump = CrashRptReader.GetMiniDumpReader();
TEST_ASSERT(pMiniDump);
// Walk through threads
int i;
for(i=0; i<pMiniDump->GetThreadCount(); i++)
{
MiniDumpThreadInfo* pThread = pMiniDump->GetThreadInfo(i);
// Read stack trace for this thread
bool bInit = StackWalker.Init(pMiniDump, m_pPdbCache, pThread->m_uThreadId);
if(bInit)
{
BOOL bGetFrame = StackWalker.FirstStackFrame();
while(bGetFrame)
{
CStackFrame* pStackFrame = StackWalker.GetStackFrame();
if(!pStackFrame)
break;
if(pStackFrame->m_sSymbolName.length()!=0)
bSymbolsFound = TRUE;
bGetFrame = StackWalker.NextStackFrame();
}
}
}
// Ensure symbols found
TEST_ASSERT(bSymbolsFound);
// Destroy report
CrashRptReader.Destroy();
}
__TEST_CLEANUP__;
}
void StackWalkerTests::Test_GetCallStack_fpo()
{
std::wstring sDir = Utils::GetTestDataFolder();
wstring sFileName = sDir;
#ifdef _WIN32
sFileName += L"fpo_test\\57442638-726a-4b66-9327-981cb10ecd96.zip";
#else
sFileName += L"fpo_test/57442638-726a-4b66-9327-981cb10ecd96.zip";
#endif
CCrashReportReader CrashReportReader;
CStackWalker StackWalker;
CPdbCache PdbCache;
BOOL bFrame = FALSE;
BOOL bInitStackWalker = FALSE;
BOOL bRead = FALSE;
MiniDumpExceptionInfo* pExcInfo = NULL;
DWORD dwExcThreadId = 0;
int nFrame = 0;
CMiniDumpReader* pMdmpReader = NULL;
// Set the directory where to look for PDB files - assume success
bool bAddSearchDir = PdbCache.AddPdbSearchDir(sDir, PDB_USUAL_DIR, true);
TEST_ASSERT(bAddSearchDir);
// Open crash report
bRead = CrashReportReader.Init(sFileName);
TEST_ASSERT(bRead);
// Get minidump
pMdmpReader = CrashReportReader.GetMiniDumpReader();
TEST_ASSERT(pMdmpReader);
// Get exception thread id
pExcInfo = pMdmpReader->GetExceptionInfo();
TEST_ASSERT(pExcInfo);
dwExcThreadId = pExcInfo->m_uThreadId;
// Init stack walker
bInitStackWalker = StackWalker.Init(pMdmpReader, &PdbCache, dwExcThreadId);
TEST_ASSERT(bInitStackWalker);
bFrame = StackWalker.FirstStackFrame();
while(bFrame)
{
CStackFrame* pStackFrame = StackWalker.GetStackFrame();
if(!pStackFrame)
break;
if(nFrame==0)
{
TEST_ASSERT(pStackFrame->m_sUndecoratedSymbolName=="function_2()");
TEST_ASSERT(pStackFrame->m_nSrcLineNumber==12);
TEST_ASSERT(pStackFrame->m_sModuleName==L"fpo_test.exe");
}
if(nFrame==2)
{
TEST_ASSERT(pStackFrame->m_sUndecoratedSymbolName=="wmain()");
TEST_ASSERT(pStackFrame->m_sSrcFileName==L"d:\\projects\\fpo_test\\fpo_test\\fpo_test.cpp");
TEST_ASSERT(pStackFrame->m_nSrcLineNumber==58);
TEST_ASSERT(pStackFrame->m_sModuleName==L"fpo_test.exe");
}
nFrame++;
bFrame = StackWalker.NextStackFrame();
}
// Ensure frame count is correct
TEST_ASSERT(nFrame==8);
__TEST_CLEANUP__;
}
| 25.101828
| 103
| 0.717183
|
jsonzilla
|
722b15f11db4d3b6c941c8b4a6c5d395b11b035f
| 1,415
|
hpp
|
C++
|
third_party/libprocess/include/process/io.hpp
|
clearstorydata/mesos
|
4164125048c6635a4d0dbe72daf243457b0f325b
|
[
"Apache-2.0"
] | null | null | null |
third_party/libprocess/include/process/io.hpp
|
clearstorydata/mesos
|
4164125048c6635a4d0dbe72daf243457b0f325b
|
[
"Apache-2.0"
] | null | null | null |
third_party/libprocess/include/process/io.hpp
|
clearstorydata/mesos
|
4164125048c6635a4d0dbe72daf243457b0f325b
|
[
"Apache-2.0"
] | 1
|
2022-02-19T10:59:37.000Z
|
2022-02-19T10:59:37.000Z
|
#ifndef __PROCESS_IO_HPP__
#define __PROCESS_IO_HPP__
#include <string>
#include <process/future.hpp>
namespace process {
namespace io {
// Possible events for polling.
const short READ = 0x01;
const short WRITE = 0x02;
// Returns the events (a subset of the events specified) that can be
// performed on the specified file descriptor without blocking.
Future<short> poll(int fd, short events);
// TODO(benh): Add a version which takes multiple file descriptors.
// Performs a single non-blocking read by polling on the specified file
// descriptor until any data can be be read. The future will become ready when
// some data is read (may be less than that specified by size). A future failure
// will be returned if an error is detected. If end-of-file is reached, value
// zero will be returned. Note that the return type of this function differs
// from the standard 'read'. In particular, this function returns the number of
// bytes read or zero on end-of-file (an error is indicated by failing the
// future, thus only a 'size_t' is necessary rather than a 'ssize_t').
Future<size_t> read(int fd, void* data, size_t size);
// Performs a series of asynchronous reads, until EOF is reached.
// NOTE: When using this, ensure the sender will close the connection
// so that EOF can be reached.
Future<std::string> read(int fd);
} // namespace io {
} // namespace process {
#endif // __PROCESS_IO_HPP__
| 35.375
| 80
| 0.749823
|
clearstorydata
|
723025a1ef0eeda1798b6627132eb46872ce35f5
| 5,292
|
cpp
|
C++
|
src/renderer/raycaster/geometry.cpp
|
lPrimemaster/Liquid
|
72c11bf96cccb3f93725f46f0e0756a1b732163c
|
[
"MIT"
] | null | null | null |
src/renderer/raycaster/geometry.cpp
|
lPrimemaster/Liquid
|
72c11bf96cccb3f93725f46f0e0756a1b732163c
|
[
"MIT"
] | null | null | null |
src/renderer/raycaster/geometry.cpp
|
lPrimemaster/Liquid
|
72c11bf96cccb3f93725f46f0e0756a1b732163c
|
[
"MIT"
] | null | null | null |
#include "geometry.h"
#include "../../utils/fileloader.h"
#include "accelerator/bvh.h"
#include <unordered_map>
#include <chrono>
internal std::unordered_map<std::string, Geometry*> GeometryRegistry;
bool Triangle::hit(const TriangleMesh* mesh, const Ray* r, f32 tmin, f32 tmax, HitRecord* rec) const
{
Vector3 e1 = mesh->vertices[indicesVertex[0]] - mesh->vertices[indicesVertex[1]];
Vector3 e2 = mesh->vertices[indicesVertex[2]] - mesh->vertices[indicesVertex[0]];
Vector3 n = Vector3::Cross(e1, e2);
Vector3 c = mesh->vertices[indicesVertex[0]] - r->origin;
Vector3 r0 = Vector3::Cross(r->direction, c);
f32 invDet = 1.0f / Vector3::Dot(n, r->direction);
float u = Vector3::Dot(r0, e2) * invDet;
float v = Vector3::Dot(r0, e1) * invDet;
float w = 1.0f - u - v;
// This order of comparisons guarantees that none of u, v, or t, are NaNs:
// IEEE-754 mandates that they compare to false if the left hand side is a NaN.
if (u >= 0.0f && v >= 0.0f && u + v <= 1.0f) {
float t = Vector3::Dot(n, c) * invDet;
if (t >= 0.0f && t < tmax) {
rec->uv = Vector2(u, v);
rec->t = t;
Vector3 nup = mesh->normals[indicesNormal[1]] * u;
Vector3 nvp = mesh->normals[indicesNormal[2]] * v;
Vector3 nwp = mesh->normals[indicesNormal[0]] * w;
rec->n = nup + nvp + nwp;
rec->p = r->at(t);
return true;
}
}
return false;
}
internal TriangleMesh* ParseWavefrontFile(const std::string& filename)
{
TriangleMesh* mesh = new TriangleMesh();
std::vector<std::string> lines = FileLoader::readFile(filename);
u64 currVertex = 0;
mesh->vertexCount = FileLoader::countToken(lines, "v ");
mesh->vertices = new Vector3[mesh->vertexCount];
u64 currTexCoord = 0;
mesh->texCoordCount = FileLoader::countToken(lines, "vt ");
mesh->texCoords = new Vector2[mesh->texCoordCount];
u64 currNormals = 0;
mesh->normalCount = FileLoader::countToken(lines, "vn ");
mesh->normals = new Vector3[mesh->normalCount];
u64 currTriangles = 0;
mesh->triangleCount = FileLoader::countToken(lines, "f ");
mesh->triangles = new Triangle[mesh->triangleCount];
for(auto line : lines)
{
if (line[0] == '#' || line[0] == '\0')
{
continue;
}
else if (line[0] == 'o' || line[0] == 'g')
{
// TODO: Get mesh and group names
}
else if (line[0] == 'v' && line[1] == ' ')
{
mesh->vertices[currVertex++] = FileLoader::parseVector3(line);
}
else if (line[0] == 'v' && line[1] == 't')
{
mesh->texCoords[currTexCoord++] = FileLoader::parseVector2(line);
}
else if (line[0] == 'v' && line[1] == 'n')
{
mesh->normals[currNormals++] = FileLoader::parseVector3(line);
}
else if (line[0] == 's')
{
continue;
}
else if (line[0] == 'f')
{
Triangle* t = &mesh->triangles[currTriangles++];
FileLoader::parseFaces(t->indicesVertex, t->indicesTexCoord, t->indicesNormal, line);
}
else // TODO: Don't Ignore usemtl and mtllib arguments
{
// std::cout << "Ignoring line: \"" << line << "\"\n";
}
}
return mesh;
}
TriangleMesh* TriangleMesh::CreateMeshFromFile(const std::string& filename)
{
auto t0 = std::chrono::steady_clock::now();
std::cout << "Parsing wavefront file: " << filename << " ";
TriangleMesh* m = ParseWavefrontFile(filename.c_str());
std::cout << "Done [" << m->vertexCount / 1000 << "k vertices in "
<< std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::steady_clock::now() - t0
).count() << "s].\n";
t0 = std::chrono::steady_clock::now();
std::cout << "Building BVH... ";
m->bvh = BVHNodeTri::NewBVHTriTree(m);
BVHNodeTri* node = m->bvh;
u64 estimatedDepth = 0;
while(node != nullptr)
{
node = node->nleft;
estimatedDepth++;
}
std::cout << "Done [" << estimatedDepth << " estimated layers in "
<< std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::steady_clock::now() - t0
).count() << "s].\n";
return m;
}
TriangleMesh::~TriangleMesh()
{
BVHNodeTri::FreeBVHTriTree(bvh);
delete[] vertices;
delete[] texCoords;
delete[] normals;
delete[] triangles;
}
void Geometry::RegisterGeometry(std::string name, Geometry* geometry)
{
if(GeometryRegistry.find(name) != GeometryRegistry.end())
{
std::cerr << "warn: Global geometry registry already contains name " << name << " - ignoring..." << std::endl;
delete geometry;
return;
}
GeometryRegistry.emplace(name, geometry);
}
std::vector<Geometry*> Geometry::GetAllGeometry()
{
// std::vector<Geometry*> r;
// r.reserve(GeometryRegistry.size());
// for(auto g : GeometryRegistry)
// {
// r.push_back();
// }
return std::vector<Geometry*>();
}
Geometry* Geometry::GetGeometry(std::string name)
{
if(GeometryRegistry.find(name) != GeometryRegistry.end())
return GeometryRegistry.at(name);
else
return nullptr;
}
void Geometry::UnloadAll()
{
for(auto g : GeometryRegistry)
{
if(g.second != nullptr)
delete g.second;
}
}
| 29.4
| 118
| 0.590703
|
lPrimemaster
|
72372cd66527e1d39402ddf3bc250a2ef264c0ac
| 5,973
|
hpp
|
C++
|
Firmware/core/gpio/gpio.hpp
|
OstapFerensovych/BMW-K1200LT-ABS-Conversion
|
17442f79261a0d5e28f52b9f0572f02a01dd9092
|
[
"MIT"
] | 3
|
2021-02-21T14:50:38.000Z
|
2021-12-19T21:52:39.000Z
|
Firmware/core/gpio/gpio.hpp
|
OstapFerensovych/BMW-K1200LT-ABS-Conversion
|
17442f79261a0d5e28f52b9f0572f02a01dd9092
|
[
"MIT"
] | null | null | null |
Firmware/core/gpio/gpio.hpp
|
OstapFerensovych/BMW-K1200LT-ABS-Conversion
|
17442f79261a0d5e28f52b9f0572f02a01dd9092
|
[
"MIT"
] | null | null | null |
#pragma once
#include <stm32f0xx.h>
#include <cstdint>
#include <tuple>
#include "platform.hpp"
namespace gpio {
enum class port {
a = 0,
b = 1,
c = 2,
f = 3,
_max_ports,
};
enum class mode : uint8_t {
input = 0,
gp_out = 1,
af_io = 2,
analog = 3,
};
enum class drive : uint8_t {
push_pull = 0,
open_drain = 1,
input = UINT8_MAX,
};
enum class speed : uint8_t {
low = 0,
medium = 1,
high = 3,
input = UINT8_MAX,
};
enum class pull : uint8_t {
none = 0,
up = 1,
down = 2,
};
enum class alt_func : uint8_t {
af0 = 0,
af1 = 1,
af2 = 2,
af3 = 3,
af4 = 4,
af5 = 5,
af6 = 6,
af7 = 7,
none = UINT8_MAX,
};
using pin_config = struct {
enum port port;
uint8_t index;
uint8_t value;
enum mode mode;
enum drive drive;
enum speed speed;
enum pull pull;
enum alt_func alt_func;
};
#include "gpio_conf.hpp"
constexpr size_t pins_config_size = sizeof(pins_config) / sizeof(pins_config[0]);
// clang-format on
namespace priv {
flat bool check_config(const pin_config &p) {
/* Alternate function enabled and pin is not af_out or input */
if (p.alt_func != alt_func::none && (p.mode == mode::analog || p.mode == mode::gp_out)) return false;
/* PullUp of PullDown on strong driven output pin */
if (p.pull != pull::none && p.drive != drive::open_drain && (p.mode == mode::gp_out || p.mode == mode::af_io))
return false;
/* OpenDrain or PushPull on input pin */
if ((p.mode == mode::analog || p.mode == mode::input) && p.drive != drive::input) return false;
/* PullUp of PullDown on analog input pin */
if (p.mode == mode::analog && p.pull != pull::none) return false;
return true;
}
template <port p>
flat_inline GPIO_TypeDef *get_gpio_ptr() {
if constexpr (p == port::a) return GPIOA;
if constexpr (p == port::b) return GPIOB;
if constexpr (p == port::c) return GPIOC;
if constexpr (p == port::f) return GPIOF;
}
template <port p>
flat_inline uint32_t get_gpio_offset() {
if constexpr (p == port::a) return GPIOA_BASE - GPIOA_BASE;
if constexpr (p == port::b) return GPIOB_BASE - GPIOA_BASE;
if constexpr (p == port::c) return GPIOC_BASE - GPIOA_BASE;
if constexpr (p == port::f) return GPIOF_BASE - GPIOA_BASE;
}
template <port p>
flat_inline uint32_t get_rcc_mask() {
if constexpr (p == port::a) return RCC_AHBENR_GPIOAEN;
if constexpr (p == port::b) return RCC_AHBENR_GPIOBEN;
if constexpr (p == port::c) return RCC_AHBENR_GPIOCEN;
if constexpr (p == port::f) return RCC_AHBENR_GPIOFEN;
}
template <size_t count, typename Lambda>
flat_inline void static_for(Lambda const &f) {
if constexpr (count > 0) {
f(std::integral_constant<size_t, count - 1>{});
static_for<count - 1>(f);
}
}
template <line line, size_t i = pins_config_size - 1, typename Lambda>
flat_inline bool foreach_line(Lambda const &f) {
static_assert(pins_config_size > 0, "No lines defined???");
if constexpr (line != pins_config[i].first) {
static_assert(i > 0, "line not found");
if constexpr (i > 0) return foreach_line<line, i - 1, Lambda>(f);
}
constexpr auto index = pins_config[i].second.index;
auto port = get_gpio_ptr<pins_config[i].second.port>();
return f(port, index);
}
template <line... lines>
flat_inline bool check_line_group() {
constexpr line sig[] = {lines...};
port p = port::_max_ports;
for (auto &s : sig) {
port new_p = port::_max_ports;
for (auto &pc : pins_config)
if (pc.first == s) new_p = pc.second.port;
if (new_p == port::_max_ports) return false;
if (p == port::_max_ports) p = new_p;
if (p != new_p) return false;
}
return true;
}
template <bool set, line... s>
flat_inline void set_clear_group() {
uint32_t set_mask = 0;
GPIO_TypeDef *p = nullptr;
constexpr bool config_ok = check_line_group<s...>();
static_assert(config_ok, "Invalid line group");
if (!config_ok) return;
static_for<sizeof...(s)>([&](auto j) {
constexpr line lines[] = {s...};
constexpr line crnt_line = lines[j];
static_for<pins_config_size>([&](auto i) {
if constexpr (pins_config[i].first != crnt_line) return;
p = get_gpio_ptr<pins_config[i].second.port>();
set_mask |= 1u << pins_config[i].second.index;
});
});
p->BSRR = set ? set_mask : set_mask << 16u;
}
} // namespace priv
template <line... s>
flat void set_group() {
priv::set_clear_group<true, s...>();
}
template <line... s>
flat void clear_group() {
priv::set_clear_group<false, s...>();
}
template <line line>
flat_inline void set() {
priv::foreach_line<line>([&](GPIO_TypeDef *port, uint8_t index) { return port->BSRR = 1u << index; });
}
template <line line>
flat_inline void clear() {
priv::foreach_line<line>([&](GPIO_TypeDef *port, uint8_t index) { return port->BRR = 1u << index; });
}
template <line line>
flat_inline bool get() {
return priv::foreach_line<line>([&](GPIO_TypeDef *port, uint8_t index) { return port->IDR & (1u << index); });
}
using pin_group = std::pair<uint16_t, uint16_t>;
static inline void set(pin_group g) {
auto ptr = (GPIO_TypeDef *)(GPIOA_BASE + g.first);
ptr->BSRR = g.second;
}
static inline void clear(pin_group g) {
auto ptr = (GPIO_TypeDef *)(GPIOA_BASE + g.first);
ptr->BRR = g.second;
}
template <line... s>
flat pin_group mask() {
uint16_t set_mask = 0;
uint32_t addr = 0;
constexpr bool config_ok = priv::check_line_group<s...>();
static_assert(config_ok, "Invalid line group");
if (!config_ok) return {};
priv::static_for<sizeof...(s)>([&](auto j) {
constexpr line lines[] = {s...};
constexpr line crnt_line = lines[j];
priv::static_for<pins_config_size>([&](auto i) {
if constexpr (pins_config[i].first != crnt_line) return;
addr = priv::get_gpio_offset<pins_config[i].second.port>();
set_mask |= 1u << pins_config[i].second.index;
});
});
return {addr, set_mask};
}
void init();
} // namespace gpio
| 24.8875
| 112
| 0.642391
|
OstapFerensovych
|
7239546831e0ba248bcc427c224de2ef22e45b14
| 3,151
|
cpp
|
C++
|
test_package/test.cpp
|
jpilet/mediagraph
|
fa3986ef91ad0ec8d0e379f2818140df7854a139
|
[
"BSD-3-Clause"
] | null | null | null |
test_package/test.cpp
|
jpilet/mediagraph
|
fa3986ef91ad0ec8d0e379f2818140df7854a139
|
[
"BSD-3-Clause"
] | 8
|
2020-02-25T13:55:37.000Z
|
2020-10-05T13:08:48.000Z
|
test_package/test.cpp
|
jpilet/mediagraph
|
fa3986ef91ad0ec8d0e379f2818140df7854a139
|
[
"BSD-3-Clause"
] | 1
|
2020-02-26T09:59:04.000Z
|
2020-02-26T09:59:04.000Z
|
#include <mediagraph/graph.h>
#include <mediagraph/stream.h>
#include <mediagraph/stream_reader.h>
#include <iostream>
struct MyData {
std::string str;
int64_t seq;
};
namespace media_graph {
namespace {
template <> std::string typeName<MyData>() { return "MyData"; }
} // namespace
} // namespace media_graph
using namespace media_graph;
class DataStream : public Stream<MyData> {
public:
static const int maxQueueSize = 100;
DataStream(NodeBase* node)
: Stream<MyData>("DataStream", node, DROP_READ_BY_ALL_READERS, maxQueueSize) {}
virtual std::string typeName() const { return "MyData"; }
};
class DataProducerNode : public ThreadedNodeBase {
public:
DataProducerNode() : m_dataStream(this) {}
virtual int numOutputStream() const { return 1; }
virtual const NamedStream* constOutputStream(int index) const {
if (index == 0) return &m_dataStream;
return 0;
}
virtual void threadMain() {
MyData data;
data.seq = 0;
data.str = "something in the way..";
for (int i = 0; i < 100; ++i) { // send 100 values
if (m_dataStream.canUpdate()) { m_dataStream.update(Timestamp::now(), data); }
++data.seq;
}
}
private:
DataStream m_dataStream;
};
class DataConsumerNode : public ThreadedNodeBase {
public:
DataConsumerNode() : input("input_pin_name", this) {}
virtual void threadMain() {
int64_t lastSeq = -1;
while (!threadMustQuit()) {
MyData data;
Timestamp ts;
SequenceId seqId;
// read will return false when the graph is stopped
if (!input.read(&data, &ts, &seqId)) {
if (lastSeq != 99) { throw std::runtime_error("lastSeq should be 99 by now!"); }
return;
}
if (lastSeq + 1 != data.seq) {
throw std::runtime_error("Sequence out of order!"); // will crash app and fail test
}
lastSeq = data.seq;
}
}
virtual int numInputPin() const { return 1; }
virtual const NamedPin* constInputPin(int index) const {
if (index == 0) return &input;
return 0;
}
private:
StreamReader<MyData> input;
};
#define EXPECT_TRUE(x, y) \
do { \
if (!(x)) { throw std::runtime_error("Error expect true " + std::string(y)); } \
} while (0)
int main() {
Graph graph;
auto producer = graph.newNode<DataProducerNode>("producer");
auto consumer = graph.newNode<DataConsumerNode>("consumer");
EXPECT_TRUE(graph.connect("producer", "DataStream", "consumer", "input_pin_name"), "connect");
EXPECT_TRUE(graph.start(), "start");
std::cout << "Waiting for producer to finish..." << std::endl;
while (producer->isRunning()) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); }
std::cout << "Stopping graph..." << std::endl;
graph.stop();
std::cout << "Done." << std::endl;
return 0;
}
| 27.163793
| 100
| 0.576325
|
jpilet
|
5cfaf825c700e948f576f668ada65b1417eafa7c
| 4,882
|
cpp
|
C++
|
Core/Utils/Utils_win.cpp
|
zenden2k/KeeneticRainmeterPlugin
|
fb8e61e161422acfa095215ed1237727e5a9f5f9
|
[
"MIT"
] | 2
|
2021-05-01T14:08:48.000Z
|
2021-09-05T11:14:19.000Z
|
Core/Utils/Utils_win.cpp
|
zenden2k/KeeneticRainmeterPlugin
|
fb8e61e161422acfa095215ed1237727e5a9f5f9
|
[
"MIT"
] | null | null | null |
Core/Utils/Utils_win.cpp
|
zenden2k/KeeneticRainmeterPlugin
|
fb8e61e161422acfa095215ed1237727e5a9f5f9
|
[
"MIT"
] | null | null | null |
/*
Image Uploader - free application for uploading images/files to the Internet
Copyright 2007-2018 Sergey Svistunov (zenden2k@gmail.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "CoreUtils.h"
#include <Windows.h>
#include <ObjIdl.h>
namespace IuCoreUtils
{
typedef HRESULT(STDAPICALLTYPE *FindMimeFromDataFunc)(LPBC, LPCWSTR, LPVOID, DWORD, LPCWSTR, DWORD, LPWSTR*, DWORD);
std::wstring strtows(const std::string &str, UINT codePage)
{
std::wstring ws;
int n = MultiByteToWideChar(codePage, 0, str.c_str(), static_cast<int>(str.size() + 1), /*dst*/NULL, 0);
if (n) {
ws.reserve(n);
ws.resize(n - 1);
if (MultiByteToWideChar(codePage, 0, str.c_str(), static_cast<int>(str.size() + 1), /*dst*/&ws[0], n) == 0)
ws.clear();
}
return ws;
}
std::string wstostr(const std::wstring &ws, UINT codePage)
{
// prior to C++11 std::string and std::wstring were not guaranteed to have their memory be contiguous,
// although all real-world implementations make them contiguous
std::string str;
int srcLen = static_cast<int>(ws.size());
int n = WideCharToMultiByte(codePage, 0, ws.c_str(), srcLen + 1, NULL, 0, /*defchr*/0, NULL);
if (n) {
str.reserve(n);
str.resize(n - 1);
if (WideCharToMultiByte(codePage, 0, ws.c_str(), srcLen + 1, &str[0], n, /*defchr*/0, NULL) == 0)
str.clear();
}
return str;
}
const std::string AnsiToUtf8(const std::string &str, int codepage)
{
return wstostr(strtows(str, codepage), CP_UTF8);
}
const std::string WstringToUtf8(const std::wstring &str)
{
return wstostr(str, CP_UTF8);
}
const std::wstring Utf8ToWstring(const std::string &str)
{
return strtows(str, CP_UTF8);
}
const std::string Utf8ToAnsi(const std::string &str, int codepage)
{
return wstostr(strtows(str, CP_UTF8), codepage);
}
std::string Utf16ToUtf8(const std::u16string& src) {
std::string str;
int srcLen = static_cast<int>(src.size());
int n = WideCharToMultiByte(CP_UTF8, 0, reinterpret_cast<LPCWSTR>(src.c_str()), srcLen + 1, NULL, 0, /*defchr*/0, NULL);
if (n) {
str.reserve(n);
str.resize(n - 1);
if (WideCharToMultiByte(CP_UTF8, 0, reinterpret_cast<LPCWSTR>(src.c_str()), srcLen + 1, &str[0], n, /*defchr*/0, NULL) == 0)
str.clear();
}
return str;
}
bool DirectoryExists(const std::string& path)
{
DWORD dwFileAttributes = GetFileAttributes(Utf8ToWstring(path).c_str());
if (dwFileAttributes != INVALID_FILE_ATTRIBUTES && (dwFileAttributes &
FILE_ATTRIBUTE_DIRECTORY)) {
return true;
}
return false;
}
bool createDirectory(const std::string& path_, unsigned int mode)
{
std::string path = path_;
if (path.empty()) return false;
if (path[path.length() - 1] == '\\' || path[path.length() - 1] == '/') {
path.resize(path.length() - 1);
}
std::wstring wstrFolder = Utf8ToWstring(path);
DWORD dwAttrib = GetFileAttributes(wstrFolder.c_str());
// already exists ?
if (dwAttrib != 0xffffffff)
return ((dwAttrib & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY);
// recursively create from the top down
char* szPath = _strdup(path.c_str());
char * p = 0;
for (int i = path.length() - 1; i >= 0; i--) {
if (szPath[i] == '\\' || szPath[i] == '/') {
p = szPath + i;
break;
}
}
if (p) {
// The parent is a dir, not a drive
*p = '\0';
// if can't create parent
if (!createDirectory(szPath)) {
free(szPath);
return false;
}
free(szPath);
if (!::CreateDirectory(wstrFolder.c_str(), NULL)) {
//LOG(WARNING) << wstrFolder;
return false;
}
}
return TRUE;
}
bool copyFile(const std::string& src, const std::string & dest, bool overwrite)
{
return ::CopyFile(Utf8ToWstring(src).c_str(), Utf8ToWstring(dest).c_str(), !overwrite) != FALSE;
}
bool RemoveFile(const std::string& utf8Filename) {
return DeleteFile(IuCoreUtils::Utf8ToWstring(utf8Filename).c_str()) != FALSE;
}
bool MoveFileOrFolder(const std::string& from, const std::string& to) {
return MoveFile(IuCoreUtils::Utf8ToWstring(from).c_str(), IuCoreUtils::Utf8ToWstring(to).c_str()) != FALSE;
}
}
| 29.587879
| 132
| 0.633961
|
zenden2k
|
5cfe4f1990c4b5e9a6df1dfe7b308188aff29003
| 727
|
cpp
|
C++
|
Codeforces/div3#634/C.cpp
|
igortakeo/Solutions-CF
|
d945f0ae21c691120b69db78ff3d240b7dedc0a7
|
[
"MIT"
] | 1
|
2020-05-25T15:32:23.000Z
|
2020-05-25T15:32:23.000Z
|
Codeforces/div3#634/C.cpp
|
igortakeo/Solutions-CF
|
d945f0ae21c691120b69db78ff3d240b7dedc0a7
|
[
"MIT"
] | null | null | null |
Codeforces/div3#634/C.cpp
|
igortakeo/Solutions-CF
|
d945f0ae21c691120b69db78ff3d240b7dedc0a7
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
#define ll long long
#define pii pair<int,int>
#define fastcin ios_base::sync_with_stdio(false); cin.tie(NULL);
using namespace std;
int main(){
fastcin
int t;
cin >> t;
while(t--){
int n;
cin >> n;
vector<int>v(n);
int freq[n+1];
int d=0, ig=0;
memset(freq, 0, sizeof freq);
for(int i=0; i<n; i++) cin >> v[i];
for(int i=0; i<n; i++){
freq[v[i]]++;
if(freq[v[i]] == 1)d++;
}
for(int i=0; i<=n; i++) ig = max(ig, freq[i]);
if(n == 1) cout << 0 << endl;
else if(ig == 0 or d == 1) cout << 1 << endl;
else{
if(d < ig) cout << d << endl;
else if(d == ig) cout << d-1 << endl;
else cout << ig << endl;
}
}
return 0;
}
| 14.836735
| 65
| 0.499312
|
igortakeo
|
cf0015e749c1fae912992594be4f700014607427
| 353
|
hpp
|
C++
|
.hemtt/template/addon/script_component.hpp
|
YonVclaw/xmarkers
|
1e9a72a43b1ef4f920e728b2ecf9d649591645a3
|
[
"MIT"
] | null | null | null |
.hemtt/template/addon/script_component.hpp
|
YonVclaw/xmarkers
|
1e9a72a43b1ef4f920e728b2ecf9d649591645a3
|
[
"MIT"
] | null | null | null |
.hemtt/template/addon/script_component.hpp
|
YonVclaw/xmarkers
|
1e9a72a43b1ef4f920e728b2ecf9d649591645a3
|
[
"MIT"
] | null | null | null |
#define COMPONENT %%addon%%
#include "\z\XMARK\addons\xmarkers\script_mod.hpp"
// #define DEBUG_MODE_FULL
// #define DISABLE_COMPILE_CACHE
#ifdef DEBUG_ENABLED_%%ADDON%%
#define DEBUG_MODE_FULL
#endif
#ifdef DEBUG_SETTINGS_OTHER
#define DEBUG_SETTINGS DEBUG_SETTINGS_%%ADDON%%
#endif
#include "\z\XMARK\addons\xmarkers\script_macros.hpp"
| 23.533333
| 53
| 0.767705
|
YonVclaw
|
cf01e392fba3f838a707b4b15cd7c7aa7c7590b4
| 4,426
|
hpp
|
C++
|
core/mmap_allocator.hpp
|
tamim-asif/lgraph-private
|
733bbcd9e14a9850580b51c011e33785ab758b9d
|
[
"BSD-3-Clause"
] | null | null | null |
core/mmap_allocator.hpp
|
tamim-asif/lgraph-private
|
733bbcd9e14a9850580b51c011e33785ab758b9d
|
[
"BSD-3-Clause"
] | null | null | null |
core/mmap_allocator.hpp
|
tamim-asif/lgraph-private
|
733bbcd9e14a9850580b51c011e33785ab758b9d
|
[
"BSD-3-Clause"
] | null | null | null |
// This file is distributed under the BSD 3-Clause License. See LICENSE for details.
#ifndef MMAP_ALLOCATOR_H
#define MMAP_ALLOCATOR_H
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <cassert>
#include <iostream>
#define MMAPA_INIT_ENTRIES (1ULL << 15)
#define MMAPA_INCR_ENTRIES (1ULL << 20)
#define MMAPA_MAX_ENTRIES (1ULL << 34)
#define MMAPA_ALIGN_BITS (12)
#define MMAPA_ALIGN_MASK ((1 << MMAPA_ALIGN_BITS) - 1)
#define MMAPA_ALIGN_SIZE (MMAPA_ALIGN_MASK + 1)
template <typename T> class mmap_allocator {
public:
typedef T value_type;
explicit mmap_allocator(const std::string &filename)
: mmap_base(0)
, file_size(0)
, mmap_size(0)
, mmap_capacity(0)
, mmap_fd(-1)
, alloc(0)
, mmap_name(filename) {
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-parameter"
void construct(T *ptr){
#pragma clang diagnostic pop
// Do nothing, do not allocate/reallocate new elements on resize (destroys old data in mmap)
}
T *allocate(size_t n) {
alloc++; // FIXME: delete?
// std::cout << "Allocating file " << mmap_name << " with size " << n << std::endl;
if(n < 1024)
n = 1024;
if(mmap_fd < 0) {
assert(MMAPA_ALIGN_SIZE == getpagesize());
// std::cout << "Allocating swap file " << mmap_name << " with size " << n << std::endl;
mmap_fd = open(mmap_name.c_str(), O_RDWR | O_CREAT, 0644);
if(mmap_fd < 0) {
std::cerr << "ERROR: Could not mmap file " << mmap_name << std::endl;
exit(-4);
}
/* Get the size of the file. */
struct stat s;
int status = fstat(mmap_fd, &s);
if(status < 0) {
std::cerr << "ERROR: Could not check file status " << mmap_name << std::endl;
exit(-3);
}
file_size = s.st_size;
mmap_size = MMAPA_INIT_ENTRIES * sizeof(T) + MMAPA_ALIGN_SIZE;
if(file_size > mmap_size)
mmap_size = file_size;
mmap_base = reinterpret_cast<uint64_t *>(mmap(0, mmap_size, PROT_READ | PROT_WRITE, MAP_SHARED, mmap_fd, 0));
if(mmap_base == MAP_FAILED) {
std::cerr << "ERROR: mmap could not allocate\n";
mmap_base = 0;
exit(-1);
}
}
if(file_size < sizeof(T) * n + MMAPA_ALIGN_SIZE) {
file_size = sizeof(T) * n + MMAPA_ALIGN_SIZE;
if(mmap_size < file_size) {
size_t old_size = mmap_size;
while(mmap_size < file_size) {
mmap_size += MMAPA_INCR_ENTRIES;
}
assert(mmap_size <= MMAPA_MAX_ENTRIES * sizeof(T));
mmap_base = reinterpret_cast<uint64_t *>(mremap(mmap_base, old_size, mmap_size, MREMAP_MAYMOVE));
if(mmap_base == MAP_FAILED) {
std::cerr << "ERROR: mmap could not allocate\n";
mmap_base = 0;
exit(-1);
}
}
assert(file_size < MMAPA_MAX_ENTRIES * sizeof(T));
ftruncate(mmap_fd, file_size);
}
// 64KB Page aligned
uint64_t b = (uint64_t)(mmap_base + 8);
uint64_t a = b;
if((a & MMAPA_ALIGN_MASK) != 0) {
a = a >> MMAPA_ALIGN_BITS;
a++;
a = a << MMAPA_ALIGN_BITS;
}
/*int64_t sz = (file_size-8+a-b)/sizeof(T);
if (sz<0)
mmap_capacity = 0;
else
mmap_capacity = sz;*/
mmap_capacity = n;
return (T *)(a);
}
virtual void clear() {
assert(false);
}
void deallocate(T *p, size_t) {
alloc--;
// std::cout << "mmap_allocator::deallocate\n";
if(alloc != 0)
return;
p = nullptr;
if(mmap_base)
munmap(mmap_base, file_size);
if(mmap_fd >= 0)
close(mmap_fd);
mmap_fd = -1;
mmap_base = 0;
mmap_capacity = 0;
}
virtual ~mmap_allocator() {
// std::cout << "destroy mmap_allocator\n";
}
void save_size(uint64_t size) {
if(mmap_fd < 0)
return;
if(mmap_base == 0)
return;
*mmap_base = size;
file_size = sizeof(T) * size + MMAPA_ALIGN_SIZE;
// file_size = sizeof(T)*size;
// file_size = sizeof(T)*size+MMAPA_ALIGN_SIZE;
msync(mmap_base, file_size, MS_SYNC);
}
size_t capacity() const {
return mmap_capacity;
}
protected:
uint64_t * mmap_base;
size_t file_size;
size_t mmap_size;
size_t mmap_capacity; // size/sizeof - space_control
int mmap_fd;
int alloc;
std::string mmap_name;
};
#endif
| 26.189349
| 115
| 0.598961
|
tamim-asif
|
cf029815b9d064889480f84e11f40c5f113ac1e0
| 778
|
cpp
|
C++
|
src/MFLOInstruction.cpp
|
dulvinw/MIPSSimulator
|
82325e56dccbd45a2257056362b955b6ef690c34
|
[
"MIT"
] | null | null | null |
src/MFLOInstruction.cpp
|
dulvinw/MIPSSimulator
|
82325e56dccbd45a2257056362b955b6ef690c34
|
[
"MIT"
] | null | null | null |
src/MFLOInstruction.cpp
|
dulvinw/MIPSSimulator
|
82325e56dccbd45a2257056362b955b6ef690c34
|
[
"MIT"
] | null | null | null |
#include "MFLOInstruction.h"
#include <iostream>
#include <sstream>
int MFLOInstruction::execute(int* registers, DataMap& data) {
registers[_dest] = registers[LO_REGISTER_ADDRESS];
return _instructionId + NEXT_INSTRUCTION_OFFSET;
}
std::string MFLOInstruction::decode() {
std::stringstream ss;
ss << getPreamble() << getInstructionString() << std::endl;
return ss.str();
}
std::string MFLOInstruction::getInstructionString() {
std::stringstream ss;
ss << "MFLO R" << _dest;
return ss.str();
}
std::shared_ptr<MFLOInstruction> MFLOInstruction::parse(const std::string& line, const int instructionId) {
auto rt = stoi(line.substr(6, 5), 0, 2);
return std::shared_ptr<MFLOInstruction>(new MFLOInstruction(rt, line, instructionId));
}
| 26.827586
| 107
| 0.705656
|
dulvinw
|
cf05c2b2368f78a29b6858c9fbc00bc77a44fd5c
| 872
|
cpp
|
C++
|
code/cpp/MaxAndMin.cpp
|
analgorithmaday/analgorithmaday.github.io
|
d43f98803bc673f61334bff54eed381426ee902e
|
[
"MIT"
] | null | null | null |
code/cpp/MaxAndMin.cpp
|
analgorithmaday/analgorithmaday.github.io
|
d43f98803bc673f61334bff54eed381426ee902e
|
[
"MIT"
] | null | null | null |
code/cpp/MaxAndMin.cpp
|
analgorithmaday/analgorithmaday.github.io
|
d43f98803bc673f61334bff54eed381426ee902e
|
[
"MIT"
] | null | null | null |
void getRange(int *arr, int size)
{
int min;
int max;
int start=0;
if((size & 1) == 1) {
min = arr[0];
max = arr[0];
start = 1;
}
else {
if(arr[0] < arr[1]) {
min = arr[0];
max = arr[1];
}
else {
min = arr[1];
max = arr[0];
}
start = 2;
}
for(int i = start; i < size; i+=2)
{
int smaller;
int larger;
if(arr[i] < arr[i+1]) {
smaller = arr[i];
larger = arr[i+1];
}
else {
smaller = arr[i+1];
larger = arr[i];
}
if(min > smaller)
min = smaller;
if(max < larger)
max = larger;
}
cout<<min<<","<<max;
}
void main()
{
int A[] = {2,5,8,9,13,4,14,6};
getRange(A, 8);
}
| 17.44
| 38
| 0.352064
|
analgorithmaday
|
cf08b895eb4e57974481e7d8d0d60809b410881c
| 10,307
|
cc
|
C++
|
Zapocet 2/test_g.cc
|
xchovanecv1/PS2
|
913c2cd7adf65fab2e4cf420aafa766b3e2232c7
|
[
"MIT"
] | null | null | null |
Zapocet 2/test_g.cc
|
xchovanecv1/PS2
|
913c2cd7adf65fab2e4cf420aafa766b3e2232c7
|
[
"MIT"
] | null | null | null |
Zapocet 2/test_g.cc
|
xchovanecv1/PS2
|
913c2cd7adf65fab2e4cf420aafa766b3e2232c7
|
[
"MIT"
] | null | null | null |
/*
Vytvorte casovu udalost (vramci prvych 30s), ktora rozpohybuje uzly v strede. (1b)
Vytvorte funkciu ktorou zachytite zmenu CongestionWindow na triede TcpSocket (iba 1z3 app pouziva Tcp). (1b)
Ak poklesne CongestionWindow zvyste rychlosti uzlov v strede. inak spomalte ;) (1b)
Zachytte udalost (PhyRxDrop || PhyTxDrop) triedy .... funkciou, kde (1b)
vykreslite graf(<ktory uzol dropol>,t) ; t je cas simulacie (2b)
*
*
* Viktor Chovanec 80331
*/
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/mobility-module.h"
#include "ns3/config-store-module.h"
#include "ns3/wifi-module.h"
#include "ns3/internet-module.h"
#include "ns3/olsr-module.h"
#include "ns3/flow-monitor-module.h"
#include "myapp.h"
#include "ns3/gnuplot.h"
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <sstream>
using namespace ns3;
using namespace std;
Gnuplot2dDataset data;
double nodeSpeed = 3;
void WalkNodes(double speed) {
for(int i = 5; i <= 7; i++) {
std::stringstream ss;
ss << "NodeList/" << i << "/$ns3::MobilityModel/$ns3::RandomWalk2dMobilityModel/Speed";
std::string s = ss.str();
std::stringstream ssval;
ssval << "ns3::ConstantRandomVariable[Constant="<< speed << "]";
std::string sval = ssval.str();
Config::Set(s,StringValue(sval));
}
for(int i = 10; i <= 12; i++) {
std::stringstream ss;
ss << "NodeList/" << i << "/$ns3::MobilityModel/$ns3::RandomWalk2dMobilityModel/Speed";
std::string s = ss.str();
std::stringstream ssval;
ssval << "ns3::ConstantRandomVariable[Constant="<< speed << "]";
std::string sval = ssval.str();
Config::Set(s,StringValue(sval));
}
for(int i = 15; i <= 17; i++) {
std::stringstream ss;
ss << "NodeList/" << i << "/$ns3::MobilityModel/$ns3::RandomWalk2dMobilityModel/Speed";
std::string s = ss.str();
std::stringstream ssval;
ssval << "ns3::ConstantRandomVariable[Constant="<< speed << "]";
std::string sval = ssval.str();
Config::Set(s,StringValue(sval));
}
}
void static cwdn(uint32_t oldVal, uint32_t newVal) {
if(oldVal > newVal) {
nodeSpeed++;
WalkNodes(nodeSpeed);
cout << "Up " << nodeSpeed << endl;
} else {
nodeSpeed /= 2;
WalkNodes(nodeSpeed);
cout << "Down " << nodeSpeed << endl;
}
std::cout << "Traced " << oldVal << " " << newVal << std::endl;
}
void rxdrop(string context, Ptr< const Packet > pak) {
std::stringstream test(context);
std::string segment;
std::vector<std::string> seglist;
while(std::getline(test, segment, '/'))
{
seglist.push_back(segment);
}
int nodeID = stoi(seglist[2]);
data.Add(Simulator::Now().GetSeconds(), nodeID);
//cout << "RX DROP " <<context << " Node " << nodeID << endl;
}
int main (int argc, char *argv[]){
double distance = 500; // m
uint32_t numNodes = 25; // by default, 5x5
double interval = 0.001; // seconds
uint32_t packetSize = 6000; // bytes
uint32_t numPackets = 1000000000;
std::string rtslimit = "1500";
CommandLine cmd;
cmd.AddValue ("distance", "distance (m)", distance);
cmd.AddValue ("packetSize", "Packet size (B)", packetSize);
cmd.AddValue ("rtslimit", "RTS/CTS Threshold (bytes)", rtslimit);
cmd.Parse (argc, argv);
Time interPacketInterval = Seconds (interval);
// turn off RTS/CTS for frames below 2200 bytes
Config::SetDefault ("ns3::WifiRemoteStationManager::RtsCtsThreshold", StringValue (rtslimit));
Config::SetDefault ("ns3::WifiRemoteStationManager::FragmentationThreshold", StringValue ("2200"));
//Config::SetDefault ("ns3::WifiRemoteStationManager::NonUnicastMode", StringValue (phyMode));
NodeContainer c;
c.Create (numNodes);
WifiHelper wifi;
YansWifiPhyHelper wifiPhy;
wifiPhy.Set ("RxGain", DoubleValue (-10) );
wifiPhy.SetErrorRateModel("ns3::YansErrorRateModel");
YansWifiChannelHelper wifiChannel;
wifiChannel.SetPropagationDelay ("ns3::ConstantSpeedPropagationDelayModel");
wifiChannel.AddPropagationLoss ("ns3::FriisPropagationLossModel");
wifiPhy.SetChannel (wifiChannel.Create ());
WifiMacHelper wifiMac;
wifi.SetStandard (WIFI_PHY_STANDARD_80211b);
wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager",
"DataMode",StringValue ("DsssRate1Mbps"),
"ControlMode",StringValue ("DsssRate1Mbps"));
wifiMac.SetType ("ns3::AdhocWifiMac");
NetDeviceContainer devices = wifi.Install (wifiPhy, wifiMac, c);
MobilityHelper mobility;
mobility.SetPositionAllocator ("ns3::GridPositionAllocator",
"MinX", DoubleValue (0.0),
"MinY", DoubleValue (0.0),
"DeltaX", DoubleValue (distance),
"DeltaY", DoubleValue (distance),
"GridWidth", UintegerValue (5),
"LayoutType", StringValue ("RowFirst"));
mobility.SetMobilityModel ("ns3::RandomWalk2dMobilityModel"
,"Mode", StringValue("Time")
,"Speed",StringValue( "ns3::ConstantRandomVariable[Constant=0.0]" )
,"Bounds", RectangleValue(Rectangle(0,distance*(numNodes/5),0,distance*(numNodes/5)))
);
mobility.Install (c);
OlsrHelper routing;
Ipv4ListRoutingHelper list;
list.Add (routing, 10);
InternetStackHelper internet;
internet.SetRoutingHelper (list);
internet.Install (c);
Ipv4AddressHelper ipv4;
ipv4.SetBase ("10.1.1.0", "255.255.255.0");
Ipv4InterfaceContainer ifcont = ipv4.Assign (devices);
uint16_t sinkPort = 6;
Address sinkAddress1 (InetSocketAddress (ifcont.GetAddress (numNodes-1), sinkPort));
PacketSinkHelper packetSinkHelper1 ("ns3::TcpSocketFactory", InetSocketAddress (Ipv4Address::GetAny (), sinkPort));
ApplicationContainer sinkApps1 = packetSinkHelper1.Install (c.Get (numNodes-1));
sinkApps1.Start (Seconds (0.));
sinkApps1.Stop (Seconds (100.));
Ptr<Socket> ns3UdpSocket1 = Socket::CreateSocket (c.Get (0), TcpSocketFactory::GetTypeId ());
Ptr<MyApp> app1 = CreateObject<MyApp> ();
app1->Setup (ns3UdpSocket1, sinkAddress1, packetSize, numPackets, DataRate ("1Mbps"));
c.Get (0)->AddApplication (app1);
app1->SetStartTime (Seconds (31.));
app1->SetStopTime (Seconds (100.));
Address sinkAddress2 (InetSocketAddress (ifcont.GetAddress (numNodes/5*3-1), sinkPort));
PacketSinkHelper packetSinkHelper2 ("ns3::UdpSocketFactory", InetSocketAddress (Ipv4Address::GetAny (), sinkPort));
ApplicationContainer sinkApps2 = packetSinkHelper2.Install (c.Get (numNodes/5*3-1));
sinkApps2.Start (Seconds (0.));
sinkApps2.Stop (Seconds (100.));
Ptr<Socket> ns3UdpSocket2 = Socket::CreateSocket (c.Get (numNodes/5*2), UdpSocketFactory::GetTypeId ());
Ptr<MyApp> app2 = CreateObject<MyApp> ();
app2->Setup (ns3UdpSocket2, sinkAddress2, packetSize, numPackets, DataRate ("1Mbps"));
c.Get (numNodes/5*2)->AddApplication (app2);
app2->SetStartTime (Seconds (31.5));
app2->SetStopTime (Seconds (100.));
Address sinkAddress3 (InetSocketAddress (ifcont.GetAddress (numNodes/5*2-1), sinkPort));
PacketSinkHelper packetSinkHelper3 ("ns3::UdpSocketFactory", InetSocketAddress (Ipv4Address::GetAny (), sinkPort));
ApplicationContainer sinkApps3 = packetSinkHelper3.Install (c.Get (numNodes/5*2-1));
sinkApps3.Start (Seconds (0.));
sinkApps3.Stop (Seconds (100.));
Ptr<Socket> ns3UdpSocket3 = Socket::CreateSocket (c.Get (numNodes/5*4), UdpSocketFactory::GetTypeId ());
Ptr<MyApp> app3 = CreateObject<MyApp> ();
app3->Setup (ns3UdpSocket3, sinkAddress3, packetSize, numPackets, DataRate ("1Mbps"));
c.Get (numNodes/5*4)->AddApplication (app3);
app3->SetStartTime (Seconds (32.));
app3->SetStopTime (Seconds (100.));
FlowMonitorHelper flowmon;
Ptr<FlowMonitor> monitor = flowmon.InstallAll();
Simulator::Schedule (Seconds (20), &WalkNodes, nodeSpeed);
Config::ConnectWithoutContext("/NodeList/*/$ns3::TcpL4Protocol/SocketList/*/CongestionWindow",MakeCallback(&cwdn));
Config::Connect("/NodeList/*/DeviceList/*/$ns3::WifiNetDevice/Phy/PhyRxDrop",MakeCallback(&rxdrop));
Simulator::Stop (Seconds (100.0));
Simulator::Run ();
monitor->CheckForLostPackets ();
Ptr<Ipv4FlowClassifier> classifier = DynamicCast<Ipv4FlowClassifier> (flowmon.GetClassifier ());
std::map<FlowId, FlowMonitor::FlowStats> stats = monitor->GetFlowStats ();
for (std::map<FlowId, FlowMonitor::FlowStats>::const_iterator iter = stats.begin (); iter != stats.end (); ++iter)
{
Ipv4FlowClassifier::FiveTuple t = classifier->FindFlow (iter->first);
/*
numNodes/5*4 -> numNodes/5*2-1 ( 21 -> 10)
numNodes/5*2 -> numNodes/5*3-1 ( 11 -> 15)
numNodes-1 -> 0 ( 1 -> 25)
*/
if ((t.sourceAddress == Ipv4Address("10.1.1.1") && t.destinationAddress == Ipv4Address("10.1.1.25"))
|| (t.sourceAddress == Ipv4Address("10.1.1.11") && t.destinationAddress == Ipv4Address("10.1.1.15"))
|| (t.sourceAddress == Ipv4Address("10.1.1.21") && t.destinationAddress == Ipv4Address("10.1.1.10")))
{
std::cout << "Flow ID: " << iter->first << " Src Addr " << t.sourceAddress << " Dst Addr " << t.destinationAddress << "\n";
std::cout << "Tx Packets = " << iter->second.txPackets << "\n";
std::cout << "Rx Packets = " << iter->second.rxPackets << "\n";
std::cout << "Throughput: " << iter->second.rxBytes * 8.0 / (iter->second.timeLastRxPacket.GetSeconds()-iter->second.timeFirstTxPacket.GetSeconds()) / 1024 << " Kbps\n";
}
}
Simulator::Destroy ();
Gnuplot graf("graf.svg");
graf.SetTerminal("svg");
graf.SetLegend("Cas","Cislo nodu");
graf.SetTitle("RX Drop nodov v case");
data.SetStyle (Gnuplot2dDataset::POINTS);
graf.AddDataset (data);
std::ofstream plotFile ("graf.gnuplot");
graf.GenerateOutput (plotFile);
plotFile.close ();
if(system("gnuplot graf.gnuplot"));
return 0;
}
| 36.679715
| 180
| 0.644707
|
xchovanecv1
|
cf1498d674dd9b3949a47ed3b16fb53e85c84272
| 2,434
|
cpp
|
C++
|
libs/outcome/doc/src/snippets/policies.cpp
|
ztchu/boost_1_70_0
|
f86bf1a4ad9efe7b2d76e4878ea240ac35ca4250
|
[
"BSL-1.0"
] | 32
|
2018-05-14T23:26:54.000Z
|
2020-06-14T10:13:20.000Z
|
libs/outcome/doc/src/snippets/policies.cpp
|
ztchu/boost_1_70_0
|
f86bf1a4ad9efe7b2d76e4878ea240ac35ca4250
|
[
"BSL-1.0"
] | 79
|
2018-08-01T11:50:45.000Z
|
2020-11-17T13:40:06.000Z
|
libs/outcome/doc/src/snippets/policies.cpp
|
ztchu/boost_1_70_0
|
f86bf1a4ad9efe7b2d76e4878ea240ac35ca4250
|
[
"BSL-1.0"
] | 14
|
2021-01-08T05:05:19.000Z
|
2022-03-27T14:56:56.000Z
|
#include "../../../include/boost/outcome.hpp"
namespace outcome = BOOST_OUTCOME_V2_NAMESPACE;
//! [abort_policy]
struct abort_policy : outcome::policy::base
{
template <class Impl> static constexpr void wide_value_check(Impl &&self)
{
if(!base::_has_value(std::forward<Impl>(self)))
std::abort();
}
template <class Impl> static constexpr void wide_error_check(Impl &&self)
{
if(!base::_has_error(std::forward<Impl>(self)))
std::abort();
}
template <class Impl> static constexpr void wide_exception_check(Impl &&self)
{
if(!base::_has_exception(std::forward<Impl>(self)))
std::abort();
}
};
//! [abort_policy]
//! [throwing_policy]
template <typename T, typename EC, typename EP> struct throwing_policy : outcome::policy::base
{
static_assert(std::is_convertible<EC, std::error_code>::value, "only EC = error_code");
template <class Impl> static constexpr void wide_value_check(Impl &&self)
{
if(!base::_has_value(std::forward<Impl>(self)))
{
if(base::_has_error(std::forward<Impl>(self)))
throw std::system_error(base::_error(std::forward<Impl>(self)));
else
std::rethrow_exception(base::_exception<T, EC, EP, throwing_policy>(std::forward<Impl>(self)));
}
}
template <class Impl> static constexpr void wide_error_check(Impl &&self)
{
if(!base::_has_error(std::forward<Impl>(self)))
{
if(base::_has_exception(std::forward<Impl>(self)))
std::rethrow_exception(base::_exception<T, EC, EP, throwing_policy>(std::forward<Impl>(self)));
else
base::_ub(std::forward<Impl>(self));
}
}
template <class Impl> static constexpr void wide_exception_check(Impl &&self)
{
if(!base::_has_exception(std::forward<Impl>(self)))
base::_ub(std::forward<Impl>(self));
}
};
//! [throwing_policy]
//! [outcome_spec]
template <typename T>
using strictOutcome = //
outcome::basic_outcome<T, std::error_code, std::exception_ptr, abort_policy>;
//! [outcome_spec]
template <typename T, typename EC = std::error_code>
using throwingOutcome = //
outcome::basic_outcome<T, EC, std::exception_ptr, throwing_policy<T, EC, std::exception_ptr>>;
int main()
{
try
{
throwingOutcome<int> i = std::error_code{};
i.value(); // throws
assert(false);
}
catch(std::system_error const &)
{
}
strictOutcome<int> i = 1;
assert(i.value() == 1);
i.error(); // calls abort()
}
| 27.348315
| 103
| 0.664749
|
ztchu
|
cf1e74641ad881ee5fb40a7e26a4c52e9f13f9d4
| 498
|
cpp
|
C++
|
packrat/lib/x86_64-w64-mingw32/3.6.1/Rcpp/examples/ConvolveBenchmarks/overhead_1.cpp
|
Denia-Vargas-Araya/ApartamentosR
|
3e62de9946efb5b6545ce431972f5cc790dae673
|
[
"MIT"
] | 113
|
2018-07-12T07:49:33.000Z
|
2021-04-16T12:41:53.000Z
|
packrat/lib/x86_64-w64-mingw32/3.6.1/Rcpp/examples/ConvolveBenchmarks/overhead_1.cpp
|
Denia-Vargas-Araya/ApartamentosR
|
3e62de9946efb5b6545ce431972f5cc790dae673
|
[
"MIT"
] | 81
|
2018-03-01T18:05:41.000Z
|
2020-01-15T18:47:31.000Z
|
packrat/lib/x86_64-w64-mingw32/3.6.1/Rcpp/examples/ConvolveBenchmarks/overhead_1.cpp
|
Denia-Vargas-Araya/ApartamentosR
|
3e62de9946efb5b6545ce431972f5cc790dae673
|
[
"MIT"
] | 55
|
2017-05-20T12:42:19.000Z
|
2019-03-26T16:38:16.000Z
|
// -*- mode: C++; c-indent-level: 4; c-basic-offset: 4; tab-width: 8 -*-
// This is a rewrite of the 'Writing R Extensions' section 5.10.1 example
#include <Rcpp.h>
// using namespace Rcpp ;
SEXP overhead_cpp(SEXP a, SEXP b) {
return R_NilValue ;
}
extern "C" void R_init_overhead_1(DllInfo *info){
R_CallMethodDef callMethods[] = {
{"overhead_cpp", (DL_FUNC) &overhead_cpp, 2},
{NULL, NULL, 0}
};
R_registerRoutines(info, NULL, callMethods, NULL, NULL);
}
| 22.636364
| 73
| 0.638554
|
Denia-Vargas-Araya
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.