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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
11b269e83e403f11b79659bd7b27c4a7e6fbac1e
| 835
|
cpp
|
C++
|
src/Engine/ModelEngine/ActorModel.cpp
|
Jino42/stf
|
f10ddaf4eb0a7ba94e6f9bb7d6b2191ca3a0b3db
|
[
"Unlicense"
] | null | null | null |
src/Engine/ModelEngine/ActorModel.cpp
|
Jino42/stf
|
f10ddaf4eb0a7ba94e6f9bb7d6b2191ca3a0b3db
|
[
"Unlicense"
] | null | null | null |
src/Engine/ModelEngine/ActorModel.cpp
|
Jino42/stf
|
f10ddaf4eb0a7ba94e6f9bb7d6b2191ca3a0b3db
|
[
"Unlicense"
] | null | null | null |
#include "ActorModel.hpp"
ActorModel::ActorModel() :
Transform(),
flag_(0),
model_(nullptr) {}
ActorModel::ActorModel(Model const *model) :
Transform(),
flag_(0),
model_(model) {
setCenter(model->getPositionCenterRelativeToOrigin());
setInterScaling(model->getInterScaling());
}
ActorModel::ActorModel(ActorModel const &src) :
Transform(src),
flag_(src.flag_),
model_(src.model_) {}
void ActorModel::assign(Model const *model) {
model_ = model;
setCenter(model->getPositionCenterRelativeToOrigin());
setInterScaling(model->getInterScaling());
}
void ActorModel::render(Shader &shader, GLenum typeOfDraw) {
updateTransform();
glm::mat4 modelMatrix = transform_;
shader.setMat4("model", modelMatrix);
model_->render(shader, typeOfDraw);
}
Model const *ActorModel::getModel() const {
return (model_);
}
| 22.567568
| 60
| 0.730539
|
Jino42
|
11b8bbe7b10ff2debdb60fa20930d6570b325252
| 261
|
hpp
|
C++
|
include/EventQueue.hpp
|
NotThatJonSmith/CASK
|
f7d23d174d88e03d253e9b076e3a926345411aaf
|
[
"MIT"
] | 1
|
2022-02-08T02:28:29.000Z
|
2022-02-08T02:28:29.000Z
|
include/EventQueue.hpp
|
NotThatJonSmith/CASK
|
f7d23d174d88e03d253e9b076e3a926345411aaf
|
[
"MIT"
] | null | null | null |
include/EventQueue.hpp
|
NotThatJonSmith/CASK
|
f7d23d174d88e03d253e9b076e3a926345411aaf
|
[
"MIT"
] | null | null | null |
#pragma once
#include <cstdint>
#include <queue>
namespace CASK {
class EventQueue {
private:
std::queue<__uint32_t> events;
public:
void EnqueueEvent(__uint32_t event);
__uint32_t DequeueEvent();
bool IsEmpty();
};
} // namespace CASK
| 11.347826
| 40
| 0.681992
|
NotThatJonSmith
|
11ba2099fa7a466f2889428624499854d86ca52e
| 7,163
|
cpp
|
C++
|
src/utils/SVGLoader.cpp
|
suaretjorge/laser_ofx
|
42d733489947c95cc83505f5708e89309f7d856f
|
[
"MIT"
] | 228
|
2015-08-19T06:33:13.000Z
|
2022-03-21T13:38:47.000Z
|
src/utils/SVGLoader.cpp
|
suaretjorge/laser_ofx
|
42d733489947c95cc83505f5708e89309f7d856f
|
[
"MIT"
] | 19
|
2018-06-29T17:22:39.000Z
|
2022-03-11T17:48:42.000Z
|
src/utils/SVGLoader.cpp
|
suaretjorge/laser_ofx
|
42d733489947c95cc83505f5708e89309f7d856f
|
[
"MIT"
] | 27
|
2015-11-21T02:31:51.000Z
|
2022-03-20T02:25:55.000Z
|
//
// SVGLoader.cpp
// ofxLaser
//
// Created by Seb Lee-Delisle on 22/02/2018.
//
#include "SVGLoader.h"
bool SVGLoader::isLoading = false;
deque<SVGLoader*> SVGLoader::loadQueue;
SVGLoader::~SVGLoader() {
//stopThread();
if(isThreadRunning()) waitForThread();
};
int SVGLoader:: startLoad(string path) {
dir = ofDirectory(path);
dir.listDir();
const vector<ofFile>& allFiles = dir.getFiles();
//only show svg files
dir.allowExt("svg");
//populate the directory object
dir.listDir();
files = dir.getFiles();
dir.close();
frames.resize(files.size());
loadedCount = 0;
totalFileCount = (int)files.size();
SVGLoader::addToQueue(this);
SVGLoader::startQueueLoading();
return totalFileCount;
}
void SVGLoader::threadedFunction() {
ofSort(files, sortalgo);
string dataString;
int dupeCount = 0;
loadedCount = 0;
// load the file
for(size_t i = 0; i<files.size();i++) {
ofFile & file = files.at(i);
// TODO compare resulting graphics rather than original files?
// bool dupe = false;
// string &data1 = dataStrings[i];
// for(int j = 0; j<i;j++) {
// string & data2 = dataStrings[j];
// if(data1.size()!=data2.size()) {
// continue;
// }else if(data1==data2) {
// ofLog(OF_LOG_NOTICE, "duplicate detected " + ofToString(i));
// dupe = true;
// break;
// }
//
// }
// if(dupe) {
// ofLog(OF_LOG_NOTICE, "duplicate detected " + ofToString(i));
// dupeCount++;
//
// } else {
//svgData = dataStr;
//cout << file.getExtension() << endl;
bool loadOptimised = false;
string optimisedFileName = file.getEnclosingDirectory()+"optimised/"+file.getBaseName()+".ofxlg";
ofFile ofxlgfile(optimisedFileName);
if(ofxlgfile.exists()) {
if(!useLoadOptimisation) {
ofxlgfile.remove();
} else {
time_t ofxlgfiletime = std::filesystem::last_write_time(ofxlgfile);
time_t originalfiletime = std::filesystem::last_write_time(file);
if(ofxlgfiletime>originalfiletime) {
loadOptimised = true;
}
}
}
if(!loadOptimised) {
//ofLogNotice("Loading svg : " + file.getAbsolutePath());
// ofBuffer buffer = ofBufferFromFile(file.getAbsolutePath());
//
// dataString = buffer.getText();
// buffer.clear();
//
//
// //ofLog(OF_LOG_NOTICE, "Loading frame #"+ofToString(i));
// //if(!isThreadRunning()) break;
//
//// while(!lock()){
//// sleep(1);
//// }
//// //ofLog(OF_LOG_NOTICE,file.getFileName());
//// unlock();
//
// try {
// svg.loadFromString(dataString);
// } catch (const std::exception& e) {
// ofLog(OF_LOG_ERROR, ofToString(e.what()));
// }
//
while(!lock()){
sleep(1);
}
frames[i].addSvgFromFile(file.getAbsolutePath(), true, true);
if(useLoadOptimisation) {
ofJson json;
frames[i].serialize(json);
//cout << "Saving optimised file : " << file.getEnclosingDirectory()+file.getBaseName()+".ofxlg" << endl;
ofSavePrettyJson(optimisedFileName, json);
}
unlock();
} else {
//ofLogNotice("Loading ofxlg : " + optimisedFileName);
ofJson json = ofLoadJson(optimisedFileName);
while(!lock()){
sleep(1);
}
frames[i].deserialize(json);
unlock();
}
file.close();
lock();
loadedCount=(int)i+1;
unlock();
}
dir.close();
while(!lock()){
sleep(1);
}
ofLog(OF_LOG_NOTICE, ofToString(loadedCount) + " svgs finished loading "+ ofToString(dupeCount)+ " duplicates");
//svgs.clear();
dataStrings.clear();
files.clear();
//fileNames.clear();
unlock();
stopThread();
ofLog(OF_LOG_NOTICE, "SVGLoader finished : " + dir.getOriginalDirectory());
SVGLoader::loadNext();
}
bool SVGLoader::hasFinishedLoading() {
return !isThreadRunning();
}
int SVGLoader :: getLoadedPercent(){
return ofMap(getLoadedCount(), 0, totalFileCount, 0, 100);
}
int SVGLoader :: getTotalFileCount(){
return totalFileCount;
}
int SVGLoader :: getLoadedCount(){
int count;
if(!isThreadRunning()) return loadedCount;
if(lock()) {
count = loadedCount;
unlock();
return count;
} else {
return -1;
}
}
void SVGLoader :: setLoadOptimisation(bool value) {
useLoadOptimisation = value;
}
void SVGLoader :: replaceAll(string& data, string stringToFind, string stringToReplace){
std::string::size_type n = 0;
while ( ( n = data.find( stringToFind, n ) ) != std::string::npos )
{
data.replace( n, stringToFind.size(), stringToReplace );
n += stringToReplace.size();
}
}
ofxLaser::Graphic& SVGLoader::getLaserGraphic(int index) {
if(isThreadRunning() && !lock()) {
return empty;
} else {
ofxLaser::Graphic* returngraphic = ∅
if(index>=(int)frames.size()) index = (int)frames.size()-1;
if(index<0) index = 0;
if((frames.size()!=0) && (loadedCount>index)) {
returngraphic = &(frames.at(index));
}
if(isThreadRunning()) unlock();
return *returngraphic;
}
}
// STATIC :
void SVGLoader::addToQueue(SVGLoader* svgloader) {
loadQueue.push_back(svgloader);
}
void SVGLoader::startQueueLoading() {
if(!isLoading) {
loadNext();
}
}
void SVGLoader :: loadNext() {
if(loadQueue.size()>0) {
loadQueue[0]->startThread();
ofLog(OF_LOG_NOTICE, "SVGLoader load starting : " + loadQueue[0]->dir.getOriginalDirectory());
loadQueue.pop_front();
isLoading = true;
} else {
isLoading = false;
}
}
bool SVGLoader :: sortalgo(const ofFile& a, const ofFile& b) {
string aname = a.getBaseName(), bname = b.getBaseName();
return strcasecmp_withNumbers(aname.c_str(), bname.c_str()) < 0;
}
int SVGLoader :: strcasecmp_withNumbers(const char *void_a, const char *void_b) {
const char *a = void_a;
const char *b = void_b;
if (!a || !b) { // if one doesn't exist, other wins by default
return a ? 1 : b ? -1 : 0;
}
if (isdigit(*a) && isdigit(*b)) { // if both start with numbers
char *remainderA;
char *remainderB;
long valA = strtol(a, &remainderA, 10);
long valB = strtol(b, &remainderB, 10);
if (valA != valB)
return valA - valB;
// if you wish 7 == 007, comment out the next two lines
else if (remainderB - b != remainderA - a) // equal with diff lengths
return (remainderB - b) - (remainderA - a); // set 007 before 7
else // if numerical parts equal, recurse
return strcasecmp_withNumbers(remainderA, remainderB);
}
if (isdigit(*a) || isdigit(*b)) { // if just one is a number
return isdigit(*a) ? -1 : 1; // numbers always come first
}
while (*a && *b) { // non-numeric characters
if (isdigit(*a) || isdigit(*b))
return strcasecmp_withNumbers(a, b); // recurse
if (tolower(*a) != tolower(*b))
return tolower(*a) - tolower(*b);
a++;
b++;
}
return *a ? 1 : *b ? -1 : 0;
}
| 24.281356
| 121
| 0.593327
|
suaretjorge
|
11be509889db0eb3b57357fb2205dfb7d453981a
| 3,771
|
cpp
|
C++
|
Examples/Basics/Offscreen/Offscreen/OffscreenOffscreen.cpp
|
SuperflyJon/VulkanPlayground
|
891b88227b66fc1e933ff77c1603e5d685d89047
|
[
"MIT"
] | 2
|
2021-01-25T16:59:56.000Z
|
2021-02-14T21:11:05.000Z
|
Examples/Basics/Offscreen/Offscreen/OffscreenOffscreen.cpp
|
SuperflyJon/VulkanPlayground
|
891b88227b66fc1e933ff77c1603e5d685d89047
|
[
"MIT"
] | null | null | null |
Examples/Basics/Offscreen/Offscreen/OffscreenOffscreen.cpp
|
SuperflyJon/VulkanPlayground
|
891b88227b66fc1e933ff77c1603e5d685d89047
|
[
"MIT"
] | 1
|
2021-04-23T10:20:53.000Z
|
2021-04-23T10:20:53.000Z
|
#include <VulkanPlayground\Includes.h>
class OffscreenOffscreenApp : public VulkanApplication3DLight
{
const float floorOffset = (10.0f / 2.0f) * .95f;
VkExtent2D offscreenExtent{ 512, 512 };
void ResetScene() override
{
CalcPositionMatrix({ 0.0f, 180.0f, 0.0f }, { -1.5f, 0, 0 }, 0, 0, model.GetModelSize());
SetupLighting({ -1.7f, 0.5f, 1.0f }, 0.2f, 0.4f, 0.7f, 32.0f, model.GetModelSize());
flip = true;
}
void SetupRenderPasses(RenderPasses& renderPasses, VulkanSystem& system, VkFormat imageFormat) override
{
VulkanApplication::SetupRenderPasses(renderPasses, system, imageFormat); // Create main renderpasses as normal
// Offscreen rendering
OffscreenRenderPass& offscreenRenderPass = renderPasses.CreateOffscreenRenderPass(offscreenExtent);
offscreenRenderPass.AddIntermidiateColourAttachment(VK_FORMAT_R8G8B8A8_UNORM, "Offscreen", VK_ATTACHMENT_LOAD_OP_CLEAR, VK_ATTACHMENT_STORE_OP_STORE); // Need to store the result so can be read in main renderpass
offscreenRenderPass.AddDepthAttachment(GetDepthFormat(system));
}
void SetupObjects(VulkanSystem& system, RenderPasses& renderPasses, VkExtent2D workingExtent) override
{
model.SetTranslation({ 0, floorOffset, 0 }); // Move dragon up so it's on the y axis
model.LoadToGpu(system, VulkanPlayground::GetModelFile("Basics", "chinesedragon.dae"), Attribs::PosNormCol);
descriptorOffscreen.AddUniformBuffer(system, 0, mvpUBO, "MVP");
descriptorOffscreen.AddUniformBuffer(system, 2, lightUBO, "Lighting", VK_SHADER_STAGE_FRAGMENT_BIT);
CreateDescriptor(system, descriptorOffscreen, "Offscreen");
pipelineOffscreen.SetupVertexDescription(Attribs::PosNormCol);
pipelineOffscreen.LoadShader(system, "offScene");
pipelineOffscreen.SetCullMode(VK_CULL_MODE_NONE); // So model draws correctly both ways up
CreatePipeline(system, *renderPasses.GetOffscreenRenderPass(), pipelineOffscreen, descriptorOffscreen, offscreenExtent, "Offscreen");
descriptor.AddTexture(1, renderPasses.GetOffscreenRenderPass()->GetBuffer());
CreateDescriptor(system, descriptor, "Main");
pipeline.LoadShader(system, "Test");
CreatePipeline(system, renderPasses.GetScreenRenderPass(), pipeline, descriptor, workingExtent, "Main");
};
void CreateCommandBuffers(VulkanSystem& system, RenderPasses& renderPasses) override
{
VulkanApplication::CreateCommandBuffers(system, renderPasses); // Create main command buffers as normal
renderPasses.GetOffscreenRenderPass()->GetDisplayBuffers().CreateCmdBuffers(system, *renderPasses.GetOffscreenRenderPass(),
[this, &system](VkCommandBuffer commandBuffer)
{
system.DebugStartRegion(commandBuffer, "Offscreen", { 1.0f, 0.0f, 1.0f });
pipelineOffscreen.Bind(commandBuffer, descriptorOffscreen);
model.Draw(commandBuffer);
system.DebugEndRegion(commandBuffer);
}, "OffscreenCmds");
}
void DrawScene(VkCommandBuffer commandBuffer) override
{
pipeline.Bind(commandBuffer, descriptor);
vkCmdDraw(commandBuffer, 6, 1, 0, 0);
}
void UpdateScene(VulkanSystem& /*system*/, float /*frameTime*/) override
{
if (flip)
mvpUBO().model = glm::scale(mvpUBO().model, glm::vec3(1.0f, -1.0f, 1.0f)); // Flip upside down
mvpUBO().model = glm::translate(mvpUBO().model, glm::vec3(0.0f, floorOffset, 0.0f));
}
void ProcessKeyPresses(const EventData& eventData) override
{
if (eventData.KeyPressed('T'))
{
flip = !flip;
}
if (eventData.KeyPressed('L'))
{ // Test - show low res offscreen buffer
if (offscreenExtent.height == 512)
offscreenExtent = { 128, 128 };
else
offscreenExtent = { 512, 512 };
RecreateObjects();
}
}
private:
Model model;
Descriptor descriptor, descriptorOffscreen;
Pipeline pipeline, pipelineOffscreen;
bool flip;
};
DECLARE_APP(OffscreenOffscreen)
| 38.876289
| 214
| 0.757359
|
SuperflyJon
|
11c240bd9bb43565c518054b7e99012ae5fd9c3a
| 54,686
|
cpp
|
C++
|
src/Gumps/Gump.cpp
|
Patuti/crossuo
|
489f69aba501fee0408c042ef6a45ea1b5cc6c34
|
[
"MIT"
] | null | null | null |
src/Gumps/Gump.cpp
|
Patuti/crossuo
|
489f69aba501fee0408c042ef6a45ea1b5cc6c34
|
[
"MIT"
] | null | null | null |
src/Gumps/Gump.cpp
|
Patuti/crossuo
|
489f69aba501fee0408c042ef6a45ea1b5cc6c34
|
[
"MIT"
] | null | null | null |
// MIT License
// Copyright (C) August 2016 Hotride
#include "Gump.h"
#include "../CrossUO.h"
#include "../Point.h"
#include "../PressedObject.h"
#include "../SelectedObject.h"
#include "../ClickObject.h"
#include "../GameWindow.h"
#include "../Managers/FontsManager.h"
#include "../Managers/MouseManager.h"
#include "../Managers/ConfigManager.h"
#include "../GameObjects/ObjectOnCursor.h"
#include "../ScreenStages/BaseScreen.h"
#include "../ScreenStages/GameScreen.h"
#include "../Renderer/RenderAPI.h"
#include "../Utility/PerfMarker.h"
CGump *g_ResizedGump = nullptr;
CGump *g_CurrentCheckGump = nullptr;
CGump::CGump()
: CGump(GT_NONE, 0, 0, 0)
{
}
CGump::CGump(GUMP_TYPE type, uint32_t serial, int x, int y)
: CRenderObject(serial, 0, 0, x, y)
, GumpType(type)
{
}
CGump::~CGump()
{
if (Blocked)
{
g_GrayMenuCount--;
if (g_GrayMenuCount <= 0)
{
g_GrayMenuCount = 0;
g_GameState = GS_GAME;
g_CurrentScreen = &g_GameScreen;
}
}
if (g_ClickObject.Gump == this)
{
g_ClickObject.Clear();
}
if (g_SelectedObject.Gump == this)
{
g_SelectedObject.Clear();
}
if (g_LastSelectedObject.Gump == this)
{
g_LastSelectedObject.Clear();
}
if (g_PressedObject.LeftGump == this)
{
g_PressedObject.ClearLeft();
}
if (g_PressedObject.RightGump == this)
{
g_PressedObject.ClearRight();
}
if (g_PressedObject.MidGump == this)
{
g_PressedObject.ClearMid();
}
}
void CGump::GUMP_DIRECT_HTML_LINK_EVENT_C
{
g_FontManager.GoToWebLink(link);
TRACE(Client, "OnDirectHTMLLink(%i)", link);
}
void CGump::FixCoordinates()
{
const int gumpOffsetX = 40;
const int gumpOffsetY = 40;
int maxX = g_GameWindow.GetSize().Width - gumpOffsetX;
int maxY = g_GameWindow.GetSize().Height - gumpOffsetY;
if (Minimized && GumpType != GT_MINIMAP)
{
if (MinimizedX + GumpRect.Position.X > maxX)
{
WantRedraw = true;
MinimizedX = maxX;
}
if (MinimizedX < GumpRect.Position.X &&
MinimizedX + GumpRect.Position.X + GumpRect.Size.Width - gumpOffsetX < 0)
{
WantRedraw = true;
MinimizedX = gumpOffsetX - (GumpRect.Position.X + GumpRect.Size.Width);
}
if (MinimizedY + GumpRect.Position.Y > maxY)
{
WantRedraw = true;
MinimizedY = maxY;
}
if (MinimizedY < GumpRect.Position.Y &&
MinimizedY + GumpRect.Position.Y + GumpRect.Size.Height - gumpOffsetY < 0)
{
WantRedraw = true;
MinimizedY = gumpOffsetY - (GumpRect.Position.Y + GumpRect.Size.Height);
}
}
else
{
if (m_X + GumpRect.Position.X > maxX)
{
WantRedraw = true;
m_X = maxX;
}
if (m_X < GumpRect.Position.X &&
m_X + GumpRect.Position.X + GumpRect.Size.Width - gumpOffsetX < 0)
{
WantRedraw = true;
m_X = gumpOffsetX - (GumpRect.Position.X + GumpRect.Size.Width);
}
if (m_Y + GumpRect.Position.Y > maxY)
{
WantRedraw = true;
m_Y = maxY;
}
if (m_Y < GumpRect.Position.Y &&
m_Y + GumpRect.Position.Y + GumpRect.Size.Height - gumpOffsetY < 0)
{
WantRedraw = true;
m_Y = gumpOffsetY - (GumpRect.Position.Y + GumpRect.Size.Height);
}
}
}
bool CGump::CanBeMoved()
{
bool result = true;
if (NoMove)
{
result = false;
}
else if (g_ConfigManager.LockGumpsMoving)
{
result = !LockMoving;
}
return result;
}
void CGump::DrawLocker()
{
if ((m_Locker.Serial != 0u) && g_ShowGumpLocker)
{
g_TextureGumpState[LockMoving].Draw(m_Locker.GetX(), m_Locker.GetY());
}
}
bool CGump::SelectLocker()
{
return (
(m_Locker.Serial != 0u) && g_ShowGumpLocker &&
g_Game.PolygonePixelsInXY(m_Locker.GetX(), m_Locker.GetY(), 10, 14));
}
bool CGump::TestLockerClick()
{
bool result =
((m_Locker.Serial != 0u) && g_ShowGumpLocker && g_PressedObject.LeftObject == &m_Locker);
if (result)
{
OnButton(m_Locker.Serial);
}
return result;
}
void CGump::CalculateGumpState()
{
g_GumpPressed =
(!g_ObjectInHand.Enabled &&
g_PressedObject.LeftGump == this /*&& g_SelectedObject.Gump() == this*/);
g_GumpSelectedElement = ((g_SelectedObject.Gump == this) ? g_SelectedObject.Object : nullptr);
g_GumpPressedElement = nullptr;
CRenderObject *leftObj = g_PressedObject.LeftObject;
if (g_GumpPressed && leftObj != nullptr)
{
if (leftObj == g_SelectedObject.Object)
{
g_GumpPressedElement = leftObj;
}
else if (leftObj->IsGUI() && ((CBaseGUI *)leftObj)->IsPressedOuthit())
{
g_GumpPressedElement = leftObj;
}
}
if (CanBeMoved() && g_GumpPressed && !g_ObjectInHand.Enabled &&
((g_PressedObject.LeftSerial == 0u) || g_GumpPressedElement == nullptr ||
g_PressedObject.TestMoveOnDrag()))
{
g_GumpMovingOffset = g_MouseManager.LeftDroppedOffset();
}
else
{
g_GumpMovingOffset.Reset();
}
if (Minimized)
{
g_GumpTranslate.X = (float)(MinimizedX + g_GumpMovingOffset.X);
g_GumpTranslate.Y = (float)(MinimizedY + g_GumpMovingOffset.Y);
}
else
{
g_GumpTranslate.X = (float)(m_X + g_GumpMovingOffset.X);
g_GumpTranslate.Y = (float)(m_Y + g_GumpMovingOffset.Y);
}
}
void CGump::ProcessListing()
{
if (g_PressedObject.LeftGump != nullptr && !g_PressedObject.LeftGump->NoProcess &&
g_PressedObject.LeftObject != nullptr && g_PressedObject.LeftObject->IsGUI())
{
CBaseGUI *item = (CBaseGUI *)g_PressedObject.LeftObject;
if (item->IsControlHTML())
{
if (item->Type == GOT_BUTTON)
{
((CGUIHTMLButton *)item)->Scroll(item->Color != 0, SCROLL_LISTING_DELAY / 7);
g_PressedObject.LeftGump->WantRedraw = true;
g_PressedObject.LeftGump->OnScrollButton();
}
else if (item->Type == GOT_HITBOX)
{
((CGUIHTMLHitBox *)item)->Scroll(item->Color != 0, SCROLL_LISTING_DELAY / 7);
g_PressedObject.LeftGump->WantRedraw = true;
g_PressedObject.LeftGump->OnScrollButton();
}
}
else if (item->Type == GOT_BUTTON && ((CGUIButton *)item)->ProcessPressedState)
{
g_PressedObject.LeftGump->WantRedraw = true;
g_PressedObject.LeftGump->OnButton(item->Serial);
}
else if (item->Type == GOT_MINMAXBUTTONS)
{
((CGUIMinMaxButtons *)item)->Scroll(SCROLL_LISTING_DELAY / 2);
g_PressedObject.LeftGump->OnScrollButton();
g_PressedObject.LeftGump->WantRedraw = true;
}
else if (item->Type == GOT_COMBOBOX)
{
CGUIComboBox *combo = (CGUIComboBox *)item;
if (combo->ListingTimer < g_Ticks)
{
int index = combo->StartIndex;
int direction = combo->ListingDirection;
if (direction == 1 && index > 0)
{
index--;
}
else if (direction == 2 && index + 1 < combo->GetItemsCount())
{
index++;
}
if (index != combo->StartIndex)
{
if (index < 0)
{
index = 0;
}
combo->StartIndex = index;
g_PressedObject.LeftGump->WantRedraw = true;
}
combo->ListingTimer = g_Ticks + 50;
}
}
}
}
void CGump::DrawItems(CBaseGUI *start, int currentPage, int draw2Page)
{
ScopedPerfMarker(__FUNCTION__);
CGUIComboBox *combo = nullptr;
int page = 0;
bool canDraw = ((draw2Page == 0) || (page >= currentPage && page <= currentPage + draw2Page));
QFOR(item, start, CBaseGUI *)
{
if (item->Type == GOT_PAGE)
{
page = ((CGUIPage *)item)->Index;
//if (page >= 2 && page > currentPage + draw2Page)
// break;
canDraw =
((page == -1) || ((page >= currentPage && page <= currentPage + draw2Page) ||
((page == 0) && (draw2Page == 0))));
}
else if (canDraw && item->Visible && !item->SelectOnly)
{
switch (item->Type)
{
case GOT_DATABOX:
{
CGump::DrawItems((CBaseGUI *)item->m_Items, currentPage, draw2Page);
break;
}
case GOT_HTMLGUMP:
case GOT_XFMHTMLGUMP:
case GOT_XFMHTMLTOKEN:
{
CGUIHTMLGump *htmlGump = (CGUIHTMLGump *)item;
float x = (float)htmlGump->GetX();
float y = (float)htmlGump->GetY();
#ifndef NEW_RENDERER_ENABLED
glTranslatef(x, y, 0.0f);
#else
RenderAdd_SetModelViewTranslation(
g_renderCmdList, SetModelViewTranslationCmd{ { x, y, 0.f } });
#endif
CBaseGUI *subItem = (CBaseGUI *)htmlGump->m_Items;
for (int j = 0; j < 5; j++)
{
if (subItem->Visible && !subItem->SelectOnly)
{
subItem->Draw(false);
}
subItem = (CBaseGUI *)subItem->m_Next;
}
float offsetX = (float)(htmlGump->DataOffset.X - htmlGump->CurrentOffset.X);
float offsetY = (float)(htmlGump->DataOffset.Y - htmlGump->CurrentOffset.Y);
#ifndef NEW_RENDERER_ENABLED
glTranslatef(offsetX, offsetY, 0.0f);
CGump::DrawItems(subItem, currentPage, draw2Page);
g_GL.PopScissor();
glTranslatef(-(x + offsetX), -(y + offsetY), 0.0f);
#else
RenderAdd_SetModelViewTranslation(
g_renderCmdList, SetModelViewTranslationCmd{ { offsetX, offsetY, 0.0f } });
CGump::DrawItems(subItem, currentPage, draw2Page);
Render_PopScissor();
RenderAdd_SetModelViewTranslation(
g_renderCmdList,
SetModelViewTranslationCmd{ { -(x + offsetX), -(y + offsetY), 0.0f } });
#endif
break;
}
case GOT_CHECKTRANS:
{
item->Draw();
break;
}
case GOT_COMBOBOX:
{
if (g_PressedObject.LeftObject == item)
{
combo = (CGUIComboBox *)item;
break;
}
}
default:
{
item->Draw();
break;
}
}
}
}
if (combo != nullptr)
{
combo->Draw();
}
#ifndef NEW_RENDERER_ENABLED
glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
#else
RenderAdd_SetColor(g_renderCmdList, SetColorCmd{ g_ColorWhite });
#endif
}
CRenderObject *CGump::SelectItems(CBaseGUI *start, int currentPage, int draw2Page)
{
CRenderObject *selected = nullptr;
int page = 0;
bool canDraw = ((draw2Page == 0) || (page >= currentPage && page <= currentPage + draw2Page));
std::vector<bool> scissorList;
bool currentScissorState = true;
CGUIComboBox *combo = nullptr;
CPoint2Di oldPos = g_MouseManager.Position;
QFOR(item, start, CBaseGUI *)
{
if (item->Type == GOT_PAGE)
{
page = ((CGUIPage *)item)->Index;
//if (page >= 2 && page > currentPage + draw2Page)
// break;
canDraw =
((page == -1) || ((page >= currentPage && page <= currentPage + draw2Page) ||
((page == 0) && (draw2Page == 0))));
}
else if (canDraw && item->Visible)
{
if (item->Type == GOT_SCISSOR)
{
if (item->Enabled)
{
currentScissorState = item->Select();
scissorList.push_back(currentScissorState);
}
else
{
scissorList.pop_back();
if (static_cast<unsigned int>(!scissorList.empty()) != 0u)
{
currentScissorState = scissorList.back();
}
else
{
currentScissorState = true;
}
}
continue;
}
if (!currentScissorState || !item->Enabled || (item->DrawOnly && selected != nullptr) ||
!item->Select())
{
continue;
}
switch (item->Type)
{
case GOT_HTMLGUMP:
case GOT_XFMHTMLGUMP:
case GOT_XFMHTMLTOKEN:
{
CGUIHTMLGump *htmlGump = (CGUIHTMLGump *)item;
g_MouseManager.Position =
CPoint2Di(oldPos.X - htmlGump->GetX(), oldPos.Y - htmlGump->GetY());
CBaseGUI *subItem = (CBaseGUI *)htmlGump->m_Items;
CRenderObject *selectedHTML = nullptr;
for (int j = 0; j < 4; j++)
{
if (subItem->Select())
{
selectedHTML = subItem;
}
subItem = (CBaseGUI *)subItem->m_Next;
}
//Scissor
if (subItem->Select())
{
int offsetX = htmlGump->DataOffset.X - htmlGump->CurrentOffset.X;
int offsetY = htmlGump->DataOffset.Y - htmlGump->CurrentOffset.Y;
g_MouseManager.Position = CPoint2Di(
g_MouseManager.Position.X - offsetX,
g_MouseManager.Position.Y - offsetY);
selected =
CGump::SelectItems((CBaseGUI *)subItem->m_Next, currentPage, draw2Page);
}
else
{
selected = nullptr;
}
if (selected == nullptr)
{
selected = selectedHTML;
if (selected == nullptr)
{
selected = subItem;
}
}
g_MouseManager.Position = oldPos;
break;
}
case GOT_DATABOX:
{
CRenderObject *selectedBox =
CGump::SelectItems((CBaseGUI *)item->m_Items, currentPage, draw2Page);
if (selectedBox != nullptr)
{
selected = selectedBox;
}
break;
}
case GOT_COMBOBOX:
{
//selected = ((CGUIComboBox*)item)->SelectedItem();
if (g_PressedObject.LeftObject == item)
{
combo = (CGUIComboBox *)item;
}
else
{
selected = item;
}
break;
}
case GOT_SHOPRESULT:
{
selected = ((CGUIShopResult *)item)->SelectedItem();
break;
}
case GOT_SKILLITEM:
{
selected = ((CGUISkillItem *)item)->SelectedItem();
break;
}
case GOT_SKILLGROUP:
{
selected = ((CGUISkillGroup *)item)->SelectedItem();
break;
}
default:
{
selected = item;
break;
}
}
}
}
if (combo != nullptr)
{
selected = combo->SelectedItem();
}
return selected;
}
void CGump::TestItemsLeftMouseDown(
CGump *gump, CBaseGUI *start, int currentPage, int draw2Page, int count)
{
int group = 0;
int page = 0;
bool canDraw = ((draw2Page == 0) || (page >= currentPage && page <= currentPage + draw2Page));
static bool htmlTextBackgroundCanBeColored = false;
if (!(start != nullptr && start->m_Next == nullptr && start->Type == GOT_HTMLTEXT))
{
htmlTextBackgroundCanBeColored = false;
}
QFOR(item, start, CBaseGUI *)
{
if (count == 0)
{
break;
}
count--;
if (item->Type == GOT_PAGE)
{
page = ((CGUIPage *)item)->Index;
//if (page >= 2 && page > currentPage + draw2Page)
// break;
canDraw =
((page == -1) || ((page >= currentPage && page <= currentPage + draw2Page) ||
((page == 0) && (draw2Page == 0))));
}
else if (canDraw && item->Enabled && item->Visible)
{
if (item->Type == GOT_GROUP)
{
group = ((CGUIGroup *)item)->Index;
continue;
}
if (g_SelectedObject.Object != item && !item->IsHTMLGump())
{
if (item->Type == GOT_SHOPRESULT)
{
if (g_SelectedObject.Object == ((CGUIShopResult *)item)->m_MinMaxButtons)
{
CPoint2Di oldPos = g_MouseManager.Position;
g_MouseManager.Position = CPoint2Di(
g_MouseManager.Position.X - item->GetX(),
g_MouseManager.Position.Y - item->GetY());
((CGUIShopResult *)item)->m_MinMaxButtons->OnClick();
g_MouseManager.Position = oldPos;
}
continue;
}
if (item->Type != GOT_SKILLGROUP &&
item->Type != GOT_DATABOX /*&& item->Type != GOT_TEXTENTRY*/)
{
continue;
}
}
switch (item->Type)
{
case GOT_HITBOX:
{
if (((CGUIPolygonal *)item)->CallOnMouseUp)
{
break;
}
CGUIHitBox *box = (CGUIHitBox *)item;
if (box->ToPage != -1)
{
gump->Page = box->ToPage;
//if (gump->Page < 1)
// gump->Page = 1;
}
}
case GOT_COLOREDPOLYGONE:
{
if (((CGUIPolygonal *)item)->CallOnMouseUp)
{
break;
}
}
case GOT_RESIZEPIC:
{
uint32_t serial = item->Serial;
if (serial == 0u)
{
break;
}
int tempPage = -1;
bool tempCanDraw = true;
QFOR(testItem, start, CBaseGUI *)
{
if (testItem->Type == GOT_PAGE)
{
tempPage = ((CGUIPage *)testItem)->Index;
tempCanDraw =
((tempPage == -1) ||
((tempPage >= page && tempPage <= page + draw2Page) ||
((tempPage == 0) && (draw2Page == 0))));
}
else if (
tempCanDraw && testItem->Type == GOT_TEXTENTRY &&
testItem->Serial == serial && testItem->Enabled && testItem->Visible)
{
CGUITextEntry *entry = (CGUITextEntry *)testItem;
if (!entry->ReadOnly)
{
int x = g_MouseManager.Position.X - item->GetX();
int y = g_MouseManager.Position.Y - item->GetY();
entry->OnClick(gump, x, y);
}
break;
}
}
gump->OnTextEntry(serial);
gump->WantRedraw = true;
return;
}
case GOT_SKILLGROUP:
{
CGUISkillGroup *skillGroup = (CGUISkillGroup *)item;
if (g_SelectedObject.Object == skillGroup->m_Name)
{
gump->OnTextEntry(g_SelectedObject.Object->Serial);
gump->WantRedraw = true;
return;
}
break;
}
case GOT_RESIZEBUTTON:
{
gump->OnResizeStart(item->Serial);
gump->WantRedraw = true;
break;
}
case GOT_SHOPITEM:
{
((CGUIShopItem *)item)->OnClick();
gump->WantRedraw = true;
break;
}
case GOT_HTMLTEXT:
{
CGUIHTMLText *htmlText = (CGUIHTMLText *)item;
uint16_t link =
htmlText->m_Sprite.WebLinkUnderMouse(item->GetX(), item->GetY());
if ((link != 0u) && link != 0xFFFF)
{
gump->OnDirectHTMLLink(link);
gump->WantRedraw = true;
htmlText->m_Sprite.ClearWebLink();
htmlText->Create(htmlTextBackgroundCanBeColored);
}
break;
}
case GOT_DATABOX:
{
CGump::TestItemsLeftMouseDown(
gump, (CBaseGUI *)item->m_Items, currentPage, draw2Page);
break;
}
case GOT_BUTTON:
case GOT_BUTTONTILEART:
{
gump->WantRedraw = true;
break;
}
case GOT_TEXTENTRY:
{
CGUITextEntry *entry = (CGUITextEntry *)item;
if (!entry->ReadOnly)
{
int x = g_MouseManager.Position.X - item->GetX();
int y = g_MouseManager.Position.Y - item->GetY();
entry->OnClick(gump, x, y);
}
gump->OnTextEntry(item->Serial);
gump->WantRedraw = true;
return;
}
case GOT_SLIDER:
{
int x = g_MouseManager.Position.X - item->GetX();
int y = g_MouseManager.Position.Y - item->GetY();
((CGUISlider *)item)->OnClick(x, y);
gump->OnSliderClick(item->Serial);
gump->WantRedraw = true;
return;
}
case GOT_MINMAXBUTTONS:
{
((CGUIMinMaxButtons *)item)->OnClick();
gump->WantRedraw = true;
return;
}
case GOT_COMBOBOX:
{
gump->WantRedraw = true;
return;
}
case GOT_HTMLGUMP:
case GOT_XFMHTMLGUMP:
case GOT_XFMHTMLTOKEN:
{
CGUIHTMLGump *htmlGump = (CGUIHTMLGump *)item;
htmlTextBackgroundCanBeColored = !htmlGump->HaveBackground;
CPoint2Di oldPos = g_MouseManager.Position;
g_MouseManager.Position =
CPoint2Di(oldPos.X - htmlGump->GetX(), oldPos.Y - htmlGump->GetY());
CBaseGUI *subItem = (CBaseGUI *)htmlGump->m_Items;
TestItemsLeftMouseDown(gump, subItem, currentPage, draw2Page, 5);
for (int j = 0; j < 5; j++)
{
subItem = (CBaseGUI *)subItem->m_Next;
}
int offsetX = htmlGump->DataOffset.X - htmlGump->CurrentOffset.X;
int offsetY = htmlGump->DataOffset.Y - htmlGump->CurrentOffset.Y;
g_MouseManager.Position = CPoint2Di(
g_MouseManager.Position.X - offsetX, g_MouseManager.Position.Y - offsetY);
TestItemsLeftMouseDown(gump, subItem, currentPage, draw2Page);
g_MouseManager.Position = oldPos;
break;
}
default:
break;
}
}
}
}
void CGump::TestItemsLeftMouseUp(CGump *gump, CBaseGUI *start, int currentPage, int draw2Page)
{
int group = 0;
int page = 0;
bool canDraw = ((draw2Page == 0) || (page >= currentPage && page <= currentPage + draw2Page));
QFOR(item, start, CBaseGUI *)
{
if (item->Type == GOT_PAGE)
{
page = ((CGUIPage *)item)->Index;
//if (page >= 2 && page > currentPage + draw2Page)
// break;
canDraw =
((page == -1) || ((page >= currentPage && page <= currentPage + draw2Page) ||
((page == 0) && (draw2Page == 0))));
}
else if (canDraw && item->Enabled && item->Visible)
{
if (item->Type == GOT_GROUP)
{
group = ((CGUIGroup *)item)->Index;
continue;
}
if (!item->IsHTMLGump())
{
if (item->Type != GOT_DATABOX && item->Type != GOT_COMBOBOX &&
item->Type != GOT_SKILLITEM && item->Type != GOT_SKILLGROUP)
{
if (g_PressedObject.LeftObject == item)
{
if (g_SelectedObject.Object != g_PressedObject.LeftObject &&
!item->IsPressedOuthit())
{
continue;
}
}
else
{
continue;
}
}
}
switch (item->Type)
{
case GOT_HITBOX:
{
if (!((CGUIPolygonal *)item)->CallOnMouseUp)
{
break;
}
CGUIHitBox *box = (CGUIHitBox *)item;
if (box->ToPage != -1)
{
gump->Page = box->ToPage;
//if (gump->Page < 1)
// gump->Page = 1;
}
gump->OnButton(item->Serial);
gump->WantRedraw = true;
return;
}
case GOT_COLOREDPOLYGONE:
{
if (!((CGUIPolygonal *)item)->CallOnMouseUp)
{
break;
}
gump->OnButton(item->Serial);
gump->WantRedraw = true;
return;
}
case GOT_RESIZEBUTTON:
{
gump->OnResizeEnd(item->Serial);
gump->WantRedraw = true;
break;
}
case GOT_SLIDER:
{
gump->WantRedraw = true;
break;
}
case GOT_DATABOX:
{
CGump::TestItemsLeftMouseUp(gump, (CBaseGUI *)item->m_Items, 0);
break;
}
case GOT_BUTTON:
case GOT_BUTTONTILEART:
{
if (item->IsControlHTML())
{
break;
}
CGUIButton *button = (CGUIButton *)item;
if (button->ToPage != -1)
{
gump->Page = button->ToPage;
if (gump->GumpType == GT_GENERIC)
{
gump->WantUpdateContent = true;
}
//if (gump->Page < 1)
// gump->Page = 1;
}
else
{
gump->OnButton(item->Serial);
}
gump->WantRedraw = true;
return;
}
case GOT_TILEPICHIGHTLIGHTED:
case GOT_GUMPPICHIGHTLIGHTED:
{
gump->OnButton(item->Serial);
gump->WantRedraw = true;
return;
}
case GOT_CHECKBOX:
{
CGUICheckbox *checkbox = (CGUICheckbox *)item;
checkbox->Checked = !checkbox->Checked;
gump->OnCheckbox(item->Serial, checkbox->Checked);
gump->WantRedraw = true;
return;
}
case GOT_RADIO:
{
CGUIRadio *radio = (CGUIRadio *)item;
int radioPage = 0;
int radioGroup = 0;
QFOR(testRadio, start, CBaseGUI *)
{
if (testRadio->Type == GOT_PAGE)
{
radioPage = ((CGUIPage *)testRadio)->Index;
}
else if (testRadio->Type == GOT_GROUP)
{
radioGroup = ((CGUIGroup *)testRadio)->Index;
}
else if (testRadio->Type == GOT_RADIO)
{
if (page <= 1 && radioPage <= 1)
{
if (group == radioGroup)
{
if (((CGUIRadio *)testRadio)->Checked && testRadio != radio)
{
gump->OnRadio(testRadio->Serial, false);
}
((CGUIRadio *)testRadio)->Checked = false;
}
}
else if (page == radioPage)
{
if (group == radioGroup)
{
if (((CGUIRadio *)testRadio)->Checked && testRadio != radio)
{
gump->OnRadio(testRadio->Serial, false);
}
((CGUIRadio *)testRadio)->Checked = false;
}
}
}
}
radio->Checked = true;
gump->OnRadio(item->Serial, true);
gump->WantRedraw = true;
return;
}
case GOT_COMBOBOX:
{
CGUIComboBox *combo = (CGUIComboBox *)item;
int selectedCombo = combo->IsSelectedItem();
if (selectedCombo != -1)
{
combo->SelectedIndex = selectedCombo;
gump->OnComboboxSelection(item->Serial + selectedCombo);
gump->WantRedraw = true;
}
break;
}
case GOT_SKILLITEM:
{
CGUISkillItem *skillItem = (CGUISkillItem *)item;
if ((g_PressedObject.LeftObject == skillItem->m_ButtonUse &&
skillItem->m_ButtonUse != nullptr) ||
g_PressedObject.LeftObject == skillItem->m_ButtonStatus)
{
gump->OnButton(g_PressedObject.LeftSerial);
gump->WantRedraw = true;
}
break;
}
case GOT_SKILLGROUP:
{
CGUISkillGroup *skillGroup = (CGUISkillGroup *)item;
if (g_PressedObject.LeftObject == skillGroup->m_Minimizer)
{
gump->OnButton(g_PressedObject.LeftSerial);
gump->WantRedraw = true;
}
else
{
TestItemsLeftMouseUp(
gump, (CBaseGUI *)skillGroup->m_Items, currentPage, draw2Page);
}
break;
}
case GOT_HTMLGUMP:
case GOT_XFMHTMLGUMP:
case GOT_XFMHTMLTOKEN:
{
TestItemsLeftMouseUp(gump, (CBaseGUI *)item->m_Items, currentPage, draw2Page);
break;
}
default:
break;
}
}
}
}
void CGump::TestItemsScrolling(
CGump *gump, CBaseGUI *start, bool up, int currentPage, int draw2Page)
{
const int delay = SCROLL_LISTING_DELAY / 7;
int group = 0;
int page = 0;
bool canDraw = ((draw2Page == 0) || (page >= currentPage && page <= currentPage + draw2Page));
QFOR(item, start, CBaseGUI *)
{
if (item->Type == GOT_PAGE)
{
page = ((CGUIPage *)item)->Index;
//if (page >= 2 && page > currentPage + draw2Page)
// break;
canDraw =
((page == -1) || ((page >= currentPage && page <= currentPage + draw2Page) ||
((page == 0) && (draw2Page == 0))));
}
else if (canDraw && item->Enabled && item->Visible)
{
if (item->Type == GOT_GROUP)
{
group = ((CGUIGroup *)item)->Index;
continue;
}
if (g_SelectedObject.Object != item && !item->IsHTMLGump())
{
continue;
}
switch (item->Type)
{
case GOT_RESIZEPIC:
{
if (!item->IsControlHTML())
{
break;
}
CGUIHTMLResizepic *resizepic = (CGUIHTMLResizepic *)item;
resizepic->Scroll(up, delay);
gump->OnSliderMove(item->Serial);
gump->WantRedraw = true;
break;
}
case GOT_SLIDER:
{
((CGUISlider *)item)->OnScroll(up, delay);
gump->OnSliderMove(item->Serial);
gump->WantRedraw = true;
return;
}
case GOT_DATABOX:
{
CGump::TestItemsScrolling(
gump, (CBaseGUI *)item->m_Items, up, currentPage, draw2Page);
break;
}
case GOT_HTMLGUMP:
case GOT_XFMHTMLGUMP:
case GOT_XFMHTMLTOKEN:
{
if (item->Select())
{
CGUIHTMLGump *htmlGump = (CGUIHTMLGump *)item;
CPoint2Di oldPos = g_MouseManager.Position;
g_MouseManager.Position =
CPoint2Di(oldPos.X - htmlGump->GetX(), oldPos.Y - htmlGump->GetY());
CBaseGUI *subItem = (CBaseGUI *)htmlGump->m_Items;
for (int j = 0; j < 5; j++)
{
if (subItem->Type == GOT_SLIDER)
{
((CGUISlider *)subItem)->OnScroll(up, delay);
gump->OnSliderMove(subItem->Serial);
}
subItem = (CBaseGUI *)subItem->m_Next;
}
int offsetX = htmlGump->DataOffset.X - htmlGump->CurrentOffset.X;
int offsetY = htmlGump->DataOffset.Y - htmlGump->CurrentOffset.Y;
g_MouseManager.Position = CPoint2Di(
g_MouseManager.Position.X - offsetX,
g_MouseManager.Position.Y - offsetY);
TestItemsScrolling(gump, (CBaseGUI *)subItem, up, currentPage, draw2Page);
g_MouseManager.Position = oldPos;
gump->WantRedraw = true;
}
break;
}
default:
break;
}
}
}
}
void CGump::TestItemsDragging(
CGump *gump, CBaseGUI *start, int currentPage, int draw2Page, int count)
{
int group = 0;
int page = 0;
bool canDraw =
((page == -1) || ((page == 0) && (draw2Page == 0)) ||
(page >= currentPage && page <= currentPage + draw2Page));
QFOR(item, start, CBaseGUI *)
{
if (count == 0)
{
break;
}
count--;
if (item->Type == GOT_PAGE)
{
page = ((CGUIPage *)item)->Index;
//if (page >= 2 && page > currentPage + draw2Page)
// break;
canDraw =
((page == -1) || ((page >= currentPage && page <= currentPage + draw2Page) ||
((page == 0) && (draw2Page == 0))));
}
else if (canDraw && item->Enabled && item->Visible)
{
if (item->Type == GOT_GROUP)
{
group = ((CGUIGroup *)item)->Index;
continue;
}
if (g_PressedObject.LeftObject != item && !item->IsHTMLGump())
{
continue;
}
switch (item->Type)
{
case GOT_SLIDER:
{
int x = g_MouseManager.Position.X - item->GetX();
int y = g_MouseManager.Position.Y - item->GetY();
((CGUISlider *)item)->OnClick(x, y);
gump->OnSliderMove(item->Serial);
gump->WantRedraw = true;
return;
}
case GOT_DATABOX:
{
CGump::TestItemsDragging(
gump, (CBaseGUI *)item->m_Items, currentPage, draw2Page);
break;
}
case GOT_RESIZEBUTTON:
{
gump->OnResize(item->Serial);
gump->WantRedraw = true;
break;
}
case GOT_HTMLGUMP:
case GOT_XFMHTMLGUMP:
case GOT_XFMHTMLTOKEN:
{
CGUIHTMLGump *htmlGump = (CGUIHTMLGump *)item;
CPoint2Di oldPos = g_MouseManager.Position;
g_MouseManager.Position =
CPoint2Di(oldPos.X - htmlGump->GetX(), oldPos.Y - htmlGump->GetY());
CBaseGUI *subItem = (CBaseGUI *)htmlGump->m_Items;
TestItemsDragging(gump, subItem, currentPage, draw2Page, 5);
for (int j = 0; j < 5; j++)
{
subItem = (CBaseGUI *)subItem->m_Next;
}
int offsetX = htmlGump->DataOffset.X - htmlGump->CurrentOffset.X;
int offsetY = htmlGump->DataOffset.Y - htmlGump->CurrentOffset.Y;
g_MouseManager.Position = CPoint2Di(
g_MouseManager.Position.X - offsetX, g_MouseManager.Position.Y - offsetY);
TestItemsDragging(gump, subItem, currentPage, draw2Page);
g_MouseManager.Position = oldPos;
gump->WantRedraw = true;
break;
}
default:
break;
}
}
}
}
void CGump::PrepareTextures()
{
QFOR(item, m_Items, CBaseGUI *)
item->PrepareTextures();
}
bool CGump::EntryPointerHere()
{
QFOR(item, m_Items, CBaseGUI *)
{
if (item->Visible && item->EntryPointerHere())
{
return true;
}
}
return false;
}
void CGump::GenerateFrame(bool stop)
{
#ifndef NEW_RENDERER_ENABLED
if (!g_GL.Drawing)
{
FrameCreated = false;
WantRedraw = true;
return;
}
#endif
CalculateGumpState();
PrepareTextures();
DrawItems((CBaseGUI *)m_Items, Page, Draw2Page);
WantRedraw = true;
FrameCreated = true;
}
void CGump::Draw()
{
ScopedPerfMarker(__FUNCTION__);
CalculateGumpState();
if (WantUpdateContent)
{
UpdateContent();
RecalculateSize();
WantUpdateContent = false;
FrameCreated = false;
}
if (!FrameCreated)
{
loc_create_frame:
if (!m_FrameBuffer.Ready(GumpRect.Size))
{
m_FrameBuffer.Init(GumpRect.Size);
}
if (m_FrameBuffer.Use())
{
#ifndef NEW_RENDERER_ENABLED
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glTranslatef(-(float)GumpRect.Position.X, -(float)GumpRect.Position.Y, 0.0f);
#else
RenderAdd_SetClearColor(g_renderCmdList, SetClearColorCmd{ { 0.f, 0.f, 0.f, 0.f } });
RenderAdd_ClearRT(g_renderCmdList, ClearRTCmd{ ClearRT::ClearRT_Color });
RenderAdd_SetClearColor(g_renderCmdList, SetClearColorCmd{ g_ColorBlack });
RenderAdd_SetModelViewTranslation(
g_renderCmdList,
SetModelViewTranslationCmd{
{ -(float)GumpRect.Position.X, -(float)GumpRect.Position.Y, 0.0f } });
#endif
GenerateFrame(true);
if (g_DeveloperMode == DM_DEBUGGING)
{
#ifndef NEW_RENDERER_ENABLED
if (g_SelectedObject.Gump == this)
{
glColor4f(0.0f, 1.0f, 0.0f, 0.2f);
}
else
{
glColor4f(1.0f, 1.0f, 1.0f, 0.2f);
}
g_GL.DrawLine(
GumpRect.Position.X + 1,
GumpRect.Position.Y + 1,
GumpRect.Position.X + GumpRect.Size.Width,
GumpRect.Position.Y + 1);
g_GL.DrawLine(
GumpRect.Position.X + GumpRect.Size.Width,
GumpRect.Position.Y + 1,
GumpRect.Position.X + GumpRect.Size.Width,
GumpRect.Position.Y + GumpRect.Size.Height);
g_GL.DrawLine(
GumpRect.Position.X + GumpRect.Size.Width,
GumpRect.Position.Y + GumpRect.Size.Height,
GumpRect.Position.X + 1,
GumpRect.Position.Y + GumpRect.Size.Height);
g_GL.DrawLine(
GumpRect.Position.X + 1,
GumpRect.Position.Y + GumpRect.Size.Height,
GumpRect.Position.X + 1,
GumpRect.Position.Y + 1);
glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
#else
static float4 s_colorThisGump = { 0.0f, 1.0f, 0.0f, 0.2f };
static float4 s_colorOtherGump = { 1.0f, 1.0f, 1.0f, 0.2f };
if (g_SelectedObject.Gump != this)
{
RenderAdd_SetColor(g_renderCmdList, SetColorCmd{ s_colorOtherGump });
}
else
{
RenderAdd_SetColor(g_renderCmdList, SetColorCmd{ s_colorThisGump });
}
RenderAdd_DrawLine(
g_renderCmdList,
DrawLineCmd{ GumpRect.Position.X + 1,
GumpRect.Position.Y + 1,
GumpRect.Position.X + GumpRect.Size.Width,
GumpRect.Position.Y + 1 });
RenderAdd_DrawLine(
g_renderCmdList,
DrawLineCmd{ GumpRect.Position.X + GumpRect.Size.Width,
GumpRect.Position.Y + 1,
GumpRect.Position.X + GumpRect.Size.Width,
GumpRect.Position.Y + GumpRect.Size.Height });
RenderAdd_DrawLine(
g_renderCmdList,
DrawLineCmd{ GumpRect.Position.X + GumpRect.Size.Width,
GumpRect.Position.Y + GumpRect.Size.Height,
GumpRect.Position.X + 1,
GumpRect.Position.Y + GumpRect.Size.Height });
RenderAdd_DrawLine(
g_renderCmdList,
DrawLineCmd{ GumpRect.Position.X + 1,
GumpRect.Position.Y + GumpRect.Size.Height,
GumpRect.Position.X + 1,
GumpRect.Position.Y + 1 });
RenderAdd_SetColor(g_renderCmdList, SetColorCmd{ g_ColorWhite });
#endif
}
#ifndef NEW_RENDERER_ENABLED
glTranslatef((float)GumpRect.Position.X, (float)GumpRect.Position.Y, 0.0f);
#else
RenderAdd_SetModelViewTranslation(
g_renderCmdList,
SetModelViewTranslationCmd{
{ (float)GumpRect.Position.X, (float)GumpRect.Position.Y, 0.0f } });
#endif
m_FrameBuffer.Release();
}
}
else if (WantRedraw)
{
WantRedraw = false;
goto loc_create_frame;
}
float posX = g_GumpTranslate.X;
float posY = g_GumpTranslate.Y;
posX += (float)GumpRect.Position.X;
posY += (float)GumpRect.Position.Y;
#ifndef NEW_RENDERER_ENABLED
glTranslatef(posX, posY, 0.0f);
glEnable(GL_BLEND);
//glBlendFunc(GL_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
#else
RenderAdd_SetModelViewTranslation(
g_renderCmdList, SetModelViewTranslationCmd{ { posX, posY, 0.0f } });
RenderAdd_SetBlend(
g_renderCmdList,
BlendStateCmd{ BlendFactor::BlendFactor_SrcAlpha,
BlendFactor::BlendFactor_OneMinusSrcAlpha });
RenderAdd_SetColor(g_renderCmdList, SetColorCmd{ g_ColorWhite });
#endif
m_FrameBuffer.Draw(0, 0);
#ifndef NEW_RENDERER_ENABLED
glDisable(GL_BLEND);
#else
RenderAdd_DisableBlend(g_renderCmdList);
#endif
DrawLocker();
#ifndef NEW_RENDERER_ENABLED
glTranslatef(-posX, -posY, 0.0f);
#else
RenderAdd_SetModelViewTranslation(
g_renderCmdList, SetModelViewTranslationCmd{ { -posX, -posY, 0.0f } });
#endif
}
CRenderObject *CGump::Select()
{
g_CurrentCheckGump = this;
CalculateGumpState();
if (WantUpdateContent)
{
UpdateContent();
RecalculateSize();
WantUpdateContent = false;
FrameCreated = false;
}
CPoint2Di oldPos = g_MouseManager.Position;
g_MouseManager.Position =
CPoint2Di(oldPos.X - (int)g_GumpTranslate.X, oldPos.Y - (int)g_GumpTranslate.Y);
CRenderObject *selected = nullptr;
if (SelectLocker())
{
selected = &m_Locker;
}
else if (
g_MouseManager.Position.X >= GumpRect.Position.X &&
g_MouseManager.Position.X < GumpRect.Position.X + GumpRect.Size.Width &&
g_MouseManager.Position.Y >= GumpRect.Position.Y &&
g_MouseManager.Position.Y < GumpRect.Position.Y + GumpRect.Size.Height)
{
selected = SelectItems((CBaseGUI *)m_Items, Page, Draw2Page);
}
if (selected != nullptr)
{
g_SelectedObject.Init(selected, this);
}
g_MouseManager.Position = oldPos;
g_CurrentCheckGump = nullptr;
return selected;
}
void CGump::RecalculateSize()
{
CPoint2Di minPosition(999, 999);
CPoint2Di maxPosition;
CPoint2Di offset;
GetItemsSize(this, (CBaseGUI *)m_Items, minPosition, maxPosition, offset, -1, Page, Draw2Page);
CSize size(maxPosition.X - minPosition.X, maxPosition.Y - minPosition.Y);
GumpRect = CRect(minPosition, size);
}
void CGump::GetItemsSize(
CGump *gump,
CBaseGUI *start,
CPoint2Di &minPosition,
CPoint2Di &maxPosition,
CPoint2Di &offset,
int count,
int currentPage,
int draw2Page)
{
int page = 0;
bool canDraw = ((draw2Page == 0) || (page >= currentPage && page <= currentPage + draw2Page));
QFOR(item, start, CBaseGUI *)
{
if (count == 0)
{
break;
}
count--;
if (item->Type == GOT_PAGE)
{
page = ((CGUIPage *)item)->Index;
//if (page >= 2 && page > currentPage + draw2Page)
// break;
canDraw =
((page == -1) || ((page >= currentPage && page <= currentPage + draw2Page) ||
((page == 0) && (draw2Page == 0))));
continue;
}
if (!canDraw || !item->Visible)
{
continue;
}
switch (item->Type)
{
case GOT_PAGE:
case GOT_GROUP:
case GOT_NONE:
case GOT_MASTERGUMP:
case GOT_CHECKTRANS:
case GOT_SHADER:
case GOT_BLENDING:
case GOT_GLOBAL_COLOR:
case GOT_TOOLTIP:
break;
case GOT_DATABOX:
{
CGump::GetItemsSize(
gump,
(CBaseGUI *)item->m_Items,
minPosition,
maxPosition,
offset,
count,
currentPage,
draw2Page);
break;
}
case GOT_HTMLGUMP:
case GOT_XFMHTMLGUMP:
case GOT_XFMHTMLTOKEN:
{
CPoint2Di htmlOffset(offset.X + item->GetX(), offset.X + item->GetY());
CGump::GetItemsSize(
gump,
(CBaseGUI *)item->m_Items,
minPosition,
maxPosition,
htmlOffset,
5,
currentPage,
draw2Page);
break;
}
case GOT_SCISSOR:
((CGUIScissor *)item)->GumpParent = gump;
default:
{
int x = item->GetX() + offset.X;
int y = item->GetY() + offset.Y;
if (x < minPosition.X)
{
minPosition.X = x;
}
if (y < minPosition.Y)
{
minPosition.Y = y;
}
CSize itemSize = item->GetSize();
x += itemSize.Width;
y += itemSize.Height;
if (x > maxPosition.X)
{
maxPosition.X = x;
}
if (y > maxPosition.Y)
{
maxPosition.Y = y;
}
break;
}
}
}
}
void CGump::OnLeftMouseButtonDown()
{
g_CurrentCheckGump = this;
CPoint2Di oldPos = g_MouseManager.Position;
g_MouseManager.Position = CPoint2Di(oldPos.X - m_X, oldPos.Y - m_Y);
TestItemsLeftMouseDown(this, (CBaseGUI *)m_Items, Page, Draw2Page);
g_MouseManager.Position = oldPos;
g_CurrentCheckGump = nullptr;
}
void CGump::OnLeftMouseButtonUp()
{
g_CurrentCheckGump = this;
TestItemsLeftMouseUp(this, (CBaseGUI *)m_Items, Page, Draw2Page);
TestLockerClick();
g_CurrentCheckGump = nullptr;
}
void CGump::OnMidMouseButtonScroll(bool up)
{
g_CurrentCheckGump = this;
CPoint2Di oldPos = g_MouseManager.Position;
g_MouseManager.Position = CPoint2Di(oldPos.X - m_X, oldPos.Y - m_Y);
TestItemsScrolling(this, (CBaseGUI *)m_Items, up, Page, Draw2Page);
g_MouseManager.Position = oldPos;
g_CurrentCheckGump = nullptr;
}
void CGump::OnDragging()
{
g_CurrentCheckGump = this;
CPoint2Di oldPos = g_MouseManager.Position;
g_MouseManager.Position = CPoint2Di(oldPos.X - m_X, oldPos.Y - m_Y);
TestItemsDragging(this, (CBaseGUI *)m_Items, Page, Draw2Page);
g_MouseManager.Position = oldPos;
g_CurrentCheckGump = nullptr;
}
void CGump::PasteClipboardData(wstr_t &data)
{
}
| 30.602126
| 100
| 0.444099
|
Patuti
|
11c8bd7b4f9a7daf818b6c9fe2a942b4601c26b1
| 1,185
|
cpp
|
C++
|
LTTng/QuickStart/UserSpaceTrace/hello.cpp
|
MiserableLife/Playground-Linux
|
82c0437d3367705aa7da3eb46736bb8fb460394a
|
[
"MIT"
] | null | null | null |
LTTng/QuickStart/UserSpaceTrace/hello.cpp
|
MiserableLife/Playground-Linux
|
82c0437d3367705aa7da3eb46736bb8fb460394a
|
[
"MIT"
] | null | null | null |
LTTng/QuickStart/UserSpaceTrace/hello.cpp
|
MiserableLife/Playground-Linux
|
82c0437d3367705aa7da3eb46736bb8fb460394a
|
[
"MIT"
] | null | null | null |
#include <stdio.h>
#include "hello-tp.h"
int main(int argc, char *argv[])
{
int x;
puts("Hello, World!\nPress Enter to continue...");
/*
* The following getchar() call is only placed here for the purpose
* of this demonstration, to pause the application in order for
* you to have time to list its tracepoints. It is not
* needed otherwise.
*/
getchar();
/*
* A tracepoint() call.
*
* Arguments, as defined in hello-tp.h:
*
* 1. Tracepoint provider name (required)
* 2. Tracepoint name (required)
* 3. my_integer_arg (first user-defined argument)
* 4. my_string_arg (second user-defined argument)
*
* Notice the tracepoint provider and tracepoint names are
* NOT strings: they are in fact parts of variables that the
* macros in hello-tp.h create.
*/
tracepoint(hello_world, my_first_tracepoint, 23, "hi there!");
for (x = 0; x < argc; ++x) {
tracepoint(hello_world, my_first_tracepoint, x, argv[x]);
}
puts("Quitting now!");
tracepoint(hello_world, my_first_tracepoint, x * x, "x^2");
return 0;
}
| 27.55814
| 71
| 0.604219
|
MiserableLife
|
11cb4f7a41aa95bed63d84c83981910e2382fc34
| 5,417
|
hpp
|
C++
|
include/codegen/include/Zenject/ZenjectBinding.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | 1
|
2021-11-12T09:29:31.000Z
|
2021-11-12T09:29:31.000Z
|
include/codegen/include/Zenject/ZenjectBinding.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | null | null | null |
include/codegen/include/Zenject/ZenjectBinding.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | 2
|
2021-10-03T02:14:20.000Z
|
2021-11-12T09:29:36.000Z
|
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:45 PM
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "utils/typedefs.h"
// Including type: UnityEngine.MonoBehaviour
#include "UnityEngine/MonoBehaviour.hpp"
// Including type: System.Enum
#include "System/Enum.hpp"
#include "utils/il2cpp-utils.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: Zenject
namespace Zenject {
// Skipping declaration: BindTypes because it is already included!
// Forward declaring type: Context
class Context;
}
// Forward declaring namespace: UnityEngine
namespace UnityEngine {
// Skipping declaration: Component because it is already included!
}
// Completed forward declares
// Type namespace: Zenject
namespace Zenject {
// Autogenerated type: Zenject.ZenjectBinding
class ZenjectBinding : public UnityEngine::MonoBehaviour {
public:
// Nested type: Zenject::ZenjectBinding::BindTypes
struct BindTypes;
// Autogenerated type: Zenject.ZenjectBinding/BindTypes
struct BindTypes : public System::Enum {
public:
// public System.Int32 value__
// Offset: 0x0
int value;
// static field const value: static public Zenject.ZenjectBinding/BindTypes Self
static constexpr const int Self = 0;
// Get static field: static public Zenject.ZenjectBinding/BindTypes Self
static Zenject::ZenjectBinding::BindTypes _get_Self();
// Set static field: static public Zenject.ZenjectBinding/BindTypes Self
static void _set_Self(Zenject::ZenjectBinding::BindTypes value);
// static field const value: static public Zenject.ZenjectBinding/BindTypes AllInterfaces
static constexpr const int AllInterfaces = 1;
// Get static field: static public Zenject.ZenjectBinding/BindTypes AllInterfaces
static Zenject::ZenjectBinding::BindTypes _get_AllInterfaces();
// Set static field: static public Zenject.ZenjectBinding/BindTypes AllInterfaces
static void _set_AllInterfaces(Zenject::ZenjectBinding::BindTypes value);
// static field const value: static public Zenject.ZenjectBinding/BindTypes AllInterfacesAndSelf
static constexpr const int AllInterfacesAndSelf = 2;
// Get static field: static public Zenject.ZenjectBinding/BindTypes AllInterfacesAndSelf
static Zenject::ZenjectBinding::BindTypes _get_AllInterfacesAndSelf();
// Set static field: static public Zenject.ZenjectBinding/BindTypes AllInterfacesAndSelf
static void _set_AllInterfacesAndSelf(Zenject::ZenjectBinding::BindTypes value);
// static field const value: static public Zenject.ZenjectBinding/BindTypes BaseType
static constexpr const int BaseType = 3;
// Get static field: static public Zenject.ZenjectBinding/BindTypes BaseType
static Zenject::ZenjectBinding::BindTypes _get_BaseType();
// Set static field: static public Zenject.ZenjectBinding/BindTypes BaseType
static void _set_BaseType(Zenject::ZenjectBinding::BindTypes value);
// Creating value type constructor for type: BindTypes
BindTypes(int value_ = {}) : value{value_} {}
}; // Zenject.ZenjectBinding/BindTypes
// private UnityEngine.Component[] _components
// Offset: 0x18
::Array<UnityEngine::Component*>* components;
// private System.String _identifier
// Offset: 0x20
::Il2CppString* identifier;
// private System.Boolean _useSceneContext
// Offset: 0x28
bool useSceneContext;
// private System.Boolean _ifNotBound
// Offset: 0x29
bool ifNotBound;
// private Zenject.Context _context
// Offset: 0x30
Zenject::Context* context;
// private Zenject.ZenjectBinding/BindTypes _bindType
// Offset: 0x38
Zenject::ZenjectBinding::BindTypes bindType;
// public System.Boolean get_UseSceneContext()
// Offset: 0x1928ACC
bool get_UseSceneContext();
// public System.Boolean get_IfNotBound()
// Offset: 0x1928AD4
bool get_IfNotBound();
// public Zenject.Context get_Context()
// Offset: 0x1928ADC
Zenject::Context* get_Context();
// public System.Void set_Context(Zenject.Context value)
// Offset: 0x1928AE4
void set_Context(Zenject::Context* value);
// public UnityEngine.Component[] get_Components()
// Offset: 0x1928AEC
::Array<UnityEngine::Component*>* get_Components();
// public System.String get_Identifier()
// Offset: 0x1928AF4
::Il2CppString* get_Identifier();
// public Zenject.ZenjectBinding/BindTypes get_BindType()
// Offset: 0x1928AFC
Zenject::ZenjectBinding::BindTypes get_BindType();
// public System.Void Start()
// Offset: 0x1928B04
void Start();
// public System.Void .ctor()
// Offset: 0x1928B08
// Implemented from: UnityEngine.MonoBehaviour
// Base method: System.Void MonoBehaviour::.ctor()
// Base method: System.Void Behaviour::.ctor()
// Base method: System.Void Component::.ctor()
// Base method: System.Void Object::.ctor()
// Base method: System.Void Object::.ctor()
static ZenjectBinding* New_ctor();
}; // Zenject.ZenjectBinding
}
DEFINE_IL2CPP_ARG_TYPE(Zenject::ZenjectBinding*, "Zenject", "ZenjectBinding");
DEFINE_IL2CPP_ARG_TYPE(Zenject::ZenjectBinding::BindTypes, "Zenject", "ZenjectBinding/BindTypes");
#pragma pack(pop)
| 44.401639
| 102
| 0.720879
|
Futuremappermydud
|
11cc74fc1aeda0fade02a593ae23a8ec61f8f808
| 4,591
|
hpp
|
C++
|
src/Evolution/Systems/GrMhd/ValenciaDivClean/Subcell/TciOptions.hpp
|
nilsvu/spectre
|
1455b9a8d7e92db8ad600c66f54795c29c3052ee
|
[
"MIT"
] | 117
|
2017-04-08T22:52:48.000Z
|
2022-03-25T07:23:36.000Z
|
src/Evolution/Systems/GrMhd/ValenciaDivClean/Subcell/TciOptions.hpp
|
GitHimanshuc/spectre
|
4de4033ba36547113293fe4dbdd77591485a4aee
|
[
"MIT"
] | 3,177
|
2017-04-07T21:10:18.000Z
|
2022-03-31T23:55:59.000Z
|
src/Evolution/Systems/GrMhd/ValenciaDivClean/Subcell/TciOptions.hpp
|
geoffrey4444/spectre
|
9350d61830b360e2d5b273fdd176dcc841dbefb0
|
[
"MIT"
] | 85
|
2017-04-07T19:36:13.000Z
|
2022-03-01T10:21:00.000Z
|
// Distributed under the MIT License.
// See LICENSE.txt for details.
#pragma once
#include <cstddef>
#include <limits>
#include <optional>
#include "DataStructures/DataBox/Tag.hpp"
#include "NumericalAlgorithms/DiscontinuousGalerkin/Tags/OptionsGroup.hpp"
#include "Options/Auto.hpp"
#include "Options/Options.hpp"
#include "Utilities/TMPL.hpp"
/// \cond
namespace PUP {
class er;
} // namespace PUP
/// \endcond
namespace grmhd::ValenciaDivClean::subcell {
/*!
* \brief Class holding options using by the GRMHD-specific parts of the
* troubled-cell indicator.
*/
struct TciOptions {
private:
struct DoNotCheckMagneticField {};
public:
/// \brief Minimum value of rest-mass density times Lorentz factor before we
/// switch to subcell. Used to identify places where the density has suddenly
/// become negative
struct MinimumValueOfD {
using type = double;
static type lower_bound() { return 0.0; }
static constexpr Options::String help = {
"Minimum value of rest-mass density times Lorentz factor before we "
"switch to subcell."};
};
/// \brief Minimum value of \f$\tilde{\tau}\f$ before we switch to subcell.
/// Used to identify places where the energy has suddenly become negative
struct MinimumValueOfTildeTau {
using type = double;
static type lower_bound() { return 0.0; }
static constexpr Options::String help = {
"Minimum value of tilde tau before we switch to subcell."};
};
/// \brief The density cutoff where if the maximum value of the density in the
/// DG element is below this value we skip primitive recovery and treat the
/// cell as atmosphere.
struct AtmosphereDensity {
using type = double;
static type lower_bound() { return 0.0; }
static constexpr Options::String help = {
"The density cutoff where if the maximum value of the density in the "
"DG element is below this value we skip primitive recovery and treat "
"the cell as atmosphere."};
};
/// \brief Safety factor \f$\epsilon_B\f$.
///
/// See the documentation for TciOnDgGrid for details on what this parameter
/// controls.
struct SafetyFactorForB {
using type = double;
static type lower_bound() { return 0.0; }
static constexpr Options::String help = {
"Safety factor for magnetic field bound."};
};
/// \brief The cutoff where if the maximum of the magnetic field in an element
/// is below this value we do not apply the Persson TCI to the magnetic field.
struct MagneticFieldCutoff {
using type = Options::Auto<double, DoNotCheckMagneticField>;
static constexpr Options::String help = {
"The cutoff where if the maximum of the magnetic field in an element "
"is below this value we do not apply the Persson TCI to the magnetic "
"field. This is to avoid switching to subcell in regions where there's "
"no magnetic field.\n"
"To disable the magnetic field check, set to "
"'DoNotCheckMagneticField'."};
};
using options =
tmpl::list<MinimumValueOfD, MinimumValueOfTildeTau, AtmosphereDensity,
SafetyFactorForB, MagneticFieldCutoff>;
static constexpr Options::String help = {
"Options for the troubled-cell indicator."};
// NOLINTNEXTLINE(google-runtime-references)
void pup(PUP::er& p);
double minimum_rest_mass_density_times_lorentz_factor{
std::numeric_limits<double>::signaling_NaN()};
double minimum_tilde_tau{std::numeric_limits<double>::signaling_NaN()};
double atmosphere_density{std::numeric_limits<double>::signaling_NaN()};
double safety_factor_for_magnetic_field{
std::numeric_limits<double>::signaling_NaN()};
// The signaling_NaN default is chosen so that users hit an error/FPE if the
// cutoff is not specified, rather than silently defaulting to ignoring the
// magnetic field.
std::optional<double> magnetic_field_cutoff{
std::numeric_limits<double>::signaling_NaN()};
};
namespace OptionTags {
struct TciOptions {
using type = subcell::TciOptions;
static constexpr Options::String help = "GRMHD-specific options for the TCI.";
using group = ::dg::OptionTags::DiscontinuousGalerkinGroup;
};
} // namespace OptionTags
namespace Tags {
struct TciOptions : db::SimpleTag {
using type = subcell::TciOptions;
using option_tags = tmpl::list<OptionTags::TciOptions>;
static constexpr bool pass_metavariables = false;
static type create_from_options(const type& tci_options) {
return tci_options;
}
};
} // namespace Tags
} // namespace grmhd::ValenciaDivClean::subcell
| 36.436508
| 80
| 0.713788
|
nilsvu
|
11cd28c845edbfee2d2f2d689164da6ce98fc3bb
| 1,758
|
hpp
|
C++
|
OptFrame/Experimental/NSIterators/IteratorNSSeqkRoute.hpp
|
216k155/bft-pos
|
80c1c84b8ca9a5c1c7462b21b011c89ae97666ae
|
[
"MIT"
] | 2
|
2018-05-24T11:04:12.000Z
|
2020-03-03T13:37:07.000Z
|
OptFrame/Experimental/NSIterators/IteratorNSSeqkRoute.hpp
|
216k155/bft-pos
|
80c1c84b8ca9a5c1c7462b21b011c89ae97666ae
|
[
"MIT"
] | null | null | null |
OptFrame/Experimental/NSIterators/IteratorNSSeqkRoute.hpp
|
216k155/bft-pos
|
80c1c84b8ca9a5c1c7462b21b011c89ae97666ae
|
[
"MIT"
] | 1
|
2019-06-06T16:57:49.000Z
|
2019-06-06T16:57:49.000Z
|
// OptFrame - Optimization Framework
// Copyright (C) 2009-2015
// http://optframe.sourceforge.net/
//
// This file is part of the OptFrame optimization framework. This framework
// is free software; you can redistribute it and/or modify it under the
// terms of the GNU Lesser General Public License v3 as published by the
// Free Software Foundation.
// This framework 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 v3 for more details.
// You should have received a copy of the GNU Lesser General Public License v3
// along with this library; see the file COPYING. If not, write to the Free
// Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
// USA.
#ifndef OPTFRAME_ITERATORNSSEQKROUTE_HPP_
#define OPTFRAME_ITERATORNSSEQKROUTE_HPP_
// Framework includes
#include "../../NSIterator.hpp"
#include "../Moves/MovekRoute.hpp"
using namespace std;
template<class T, class DS = OPTFRAME_DEFAULT_EMEMORY, class MOVE = MovekRoute<T, DS > >
class IteratorNSSeqkRoute: public NSIterator<vector<vector<T> > , DS >
{
typedef vector<T> Route;
typedef vector<vector<T> > MultiRoute;
private:
int k;
NSIterator<Route, DS >& iterator;
public:
IteratorNSSeqkRoute(int _k, NSIterator<Route, DS >& it) :
k(_k), iterator(it)
{
}
virtual ~IteratorNSSeqkRoute()
{
delete &iterator;
}
void first()
{
iterator.first();
}
void next()
{
iterator.next();
}
bool isDone()
{
return iterator.isDone();
}
Move<MultiRoute, DS >& current()
{
return *new MOVE(k, iterator.current());
}
};
#endif /*OPTFRAME_ITERATORNSSEQKROUTE_HPP_*/
| 23.131579
| 88
| 0.727531
|
216k155
|
11ce986f3af140d44fda7a43eed4f2e676b7e633
| 2,360
|
cpp
|
C++
|
modules/camera_calibration/event/src/EventStream.cpp
|
MobilePerceptionLab/EventCameraCalibration
|
debd774ac989674b500caf27641b7ad4e94681e9
|
[
"Apache-2.0"
] | 22
|
2021-08-06T03:21:03.000Z
|
2022-02-25T03:40:54.000Z
|
modules/camera_calibration/event/src/EventStream.cpp
|
MobilePerceptionLab/EventCameraCalibration
|
debd774ac989674b500caf27641b7ad4e94681e9
|
[
"Apache-2.0"
] | 1
|
2022-02-25T02:55:13.000Z
|
2022-02-25T15:18:45.000Z
|
modules/camera_calibration/event/src/EventStream.cpp
|
MobilePerceptionLab/EventCameraCalibration
|
debd774ac989674b500caf27641b7ad4e94681e9
|
[
"Apache-2.0"
] | 7
|
2021-08-11T12:29:35.000Z
|
2022-02-25T03:41:01.000Z
|
//
// Created by huangkun on 2020/9/15.
//
#include <exception>
#include <iostream>
#include <opengv2/event/EventStream.hpp>
opengv2::EventStream::EventStream(const std::string &binFilePath) {
is_.open(binFilePath, std::ifstream::binary | std::ifstream::in);
if (is_.is_open()) {
istreamIterator_ = std::istream_iterator<Event>(is_);
} else {
throw std::invalid_argument("No such file: " + binFilePath);
}
}
opengv2::EventStream::~EventStream() {
if (is_.is_open()) {
is_.close();
}
}
void opengv2::EventStream::txt2bin(const std::string &txtFilePath, double timeMagnitude,
long long timeBase_in, long long endTime_in) {
std::ifstream is(txtFilePath, std::ifstream::in);
if (is.is_open()) {
auto lastIndex = txtFilePath.find_last_of('.');
std::ofstream os(txtFilePath.substr(0, lastIndex) + ".bin",
std::ofstream::binary | std::ofstream::out | std::ofstream::trunc);
long long counter = 0;
long long timeStamp, timeBase = timeBase_in, endTime = endTime_in;
double x, y;
bool polarity;
while (is.good()) {
is >> timeStamp >> x >> y >> polarity;
if (counter == 0 && timeBase_in == std::numeric_limits<long long>::min())
timeBase = timeStamp;
if (endTime != std::numeric_limits<long long>::min() && timeStamp > endTime)
break;
double t = ((timeStamp - timeBase) * timeMagnitude); // convert to second
if (t < 0)
continue;
os.write((char *) &t, sizeof(t));
os.write((char *) &x, sizeof(x));
os.write((char *) &y, sizeof(y));
os.write((char *) &polarity, sizeof(polarity));
counter++;
}
std::cout << counter << " data processed." << std::endl;
std::cout.precision(30);
std::cout << "TimeBase :" << timeBase << std::endl;
std::cout.precision(15);
std::cout << "Last data is :" << timeStamp << " " << x << " " << y << " " << polarity << std::endl;
std::cout << "Duration :" << ((timeStamp - timeBase) * timeMagnitude) << std::endl;
is.close();
os.close();
} else {
throw std::invalid_argument("No such file: " + txtFilePath);
}
}
| 35.223881
| 107
| 0.547881
|
MobilePerceptionLab
|
11dcacba81e8b887d5f906a18e94d5ab8baf07ee
| 688
|
hpp
|
C++
|
src/Resource/UserResource.hpp
|
maciejjaskiewicz/FacelinkStudio
|
4bcb4ed06932546e58af4a01ee2b17e3dc45f366
|
[
"MIT"
] | 1
|
2020-08-11T02:40:32.000Z
|
2020-08-11T02:40:32.000Z
|
src/Resource/UserResource.hpp
|
maciejjaskiewicz/FacelinkStudio
|
4bcb4ed06932546e58af4a01ee2b17e3dc45f366
|
[
"MIT"
] | null | null | null |
src/Resource/UserResource.hpp
|
maciejjaskiewicz/FacelinkStudio
|
4bcb4ed06932546e58af4a01ee2b17e3dc45f366
|
[
"MIT"
] | null | null | null |
#pragma once
#include <Xenon/Graphics/API/Texture2D.hpp>
#include <opencv2/core/mat.hpp>
#include <opencv2/cudaimgproc.hpp>
namespace Fls
{
struct UserResource
{
int64 id;
std::string name;
std::string path;
cv::Mat pixels;
cv::cuda::GpuMat gpuPixels;
std::shared_ptr<Xenon::Texture2D> frame;
std::shared_ptr<Xenon::Texture2D> thumbnail;
cv::Mat detectionFrame;
bool preprocessed{ false };
UserResource()
: id(0), gpuPixels(cv::cuda::GpuMat())
{ }
static constexpr uint32_t THUMBNAIL_WIDTH = 256;
static constexpr uint32_t THUMBNAIL_HEIGHT = 256;
};
}
| 20.848485
| 57
| 0.609012
|
maciejjaskiewicz
|
11e104ce61f79910cba5b723b7c837583211656d
| 7,819
|
cpp
|
C++
|
Library_Administrator_System/bookmanagement.cpp
|
renzibei/TGLibrary
|
5c23dafa15cc8d2eec5bf06a90cd80dedf36bf4e
|
[
"Apache-2.0"
] | 1
|
2018-09-11T04:58:39.000Z
|
2018-09-11T04:58:39.000Z
|
Library_Administrator_System/bookmanagement.cpp
|
renzibei/TGLibrary
|
5c23dafa15cc8d2eec5bf06a90cd80dedf36bf4e
|
[
"Apache-2.0"
] | null | null | null |
Library_Administrator_System/bookmanagement.cpp
|
renzibei/TGLibrary
|
5c23dafa15cc8d2eec5bf06a90cd80dedf36bf4e
|
[
"Apache-2.0"
] | null | null | null |
#include "bookmanagement.h"
#include "ui_bookmanagement.h"
#include "bookoperation.h"
#include "webio.h"
#include <QMessageBox>
#include <QString>
BookManagement::BookManagement(QWidget *parent) :
QDialog(parent),
ui(new Ui::BookManagement)
{
ui->setupUi(this);
this->setAttribute(Qt::WA_DeleteOnClose);
connect(ui->BookM_Return_bt, SIGNAL(clicked()), this, SLOT(close()));
ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
booksocket = WebIO::getSocket();//new QTcpSocket;
}
BookManagement::~BookManagement()
{
booksocket->disconnectFromHost();
delete ui;
}
void BookManagement::on_AddBook_Bt_clicked()
{
this->hide();
bookoperation *bookoperation1 = new bookoperation(this);
bookoperation1->operationtype = 3;
bookoperation1->defaultchousen();
bookoperation1->show();
bookoperation1->exec();
this->show();
}
void BookManagement::on_Delete_Book_clicked()
{
if(ui->tableWidget->rowCount() == 0)
{
QMessageBox::warning(this, tr("错误"), tr("请搜索书目,之后单击书目所在行,然后删除!"));
return;
}
int rownumber = ui->tableWidget->currentRow();
QJsonObject onloadbookjson;
onloadbookjson.insert("jsontype","3");
//此处有问题
onloadbookjson.insert("docID",ui->tableWidget->item(rownumber,3)->text());
QJsonDocument jsondoc;
jsondoc.setObject(onloadbookjson);
bytearray = jsondoc.toJson(QJsonDocument::Compact);
// booksocket->write( std::to_string(bytearray.size()).c_str() );
WebIO::Singleton()->sendMessage(bytearray, this, SLOT(socket_Read_Data()));
//booksocket->write(bytearray);
}
void BookManagement::on_detailed_information_clicked()
{
if(ui->tableWidget->rowCount()==0)
{
QMessageBox::warning(this, tr("错误"), tr("请搜索到书籍后点击书籍所在行进行查询"));
return;
}
else
{
int rownumber = ui->tableWidget->currentRow();
this->hide();
bookoperation *bookoperation1 = new bookoperation(this);
bookoperation1->operationtype = 0;
bookoperation1->defaultchousen();
bookoperation1->booktransferobject = counterpartobject[rownumber];
bookoperation1->writeinformation();
bookoperation1->show();
bookoperation1->exec();
this->show();
}
}
void BookManagement::on_Modify_Book_clicked()
{
if(ui->tableWidget->rowCount()==0)
{
QMessageBox::warning(this, tr("错误"), tr("请搜索到书籍后点击书籍所在行进行查询"));
return;
}
else
{
int rownumber = ui->tableWidget->currentRow();
this->hide();
bookoperation *bookoperation1 = new bookoperation(this);
bookoperation1->operationtype = 1;
bookoperation1->booktransferobject = counterpartobject[rownumber];
bookoperation1->writeinformation();
bookoperation1->show();
bookoperation1->exec();
this->show();
this->getadvancedresult();
}
}
void BookManagement::on_advancedsearch_clicked()
{
int rownumber = ui->tableWidget->currentRow();
this->hide();
bookoperation *bookoperation1 = new bookoperation(this);
bookoperation1->operationtype = 2;
bookoperation1->defaultchousen();
bookoperation1->show();
bookoperation1->exec();
this->show();
this->getadvancedresult();
}
void BookManagement::on_SearchBook_clicked()
{
if(ui->Book_Edit->text()=="")
QMessageBox::warning(this, tr("错误"), tr("请输入"));
else
{
bookjson.insert("jsontype","5");
bookjson.insert("keywords",ui->Book_Edit->text());
QJsonDocument jsondoc;
jsondoc.setObject(bookjson);
bytearray = jsondoc.toJson(QJsonDocument::Compact);
//booksocket->write( std::to_string(bytearray.size()).c_str() );
WebIO::Singleton()->sendMessage(bytearray, this, SLOT(socket_Read_Data()));
//booksocket->write(bytearray);
}
}
void BookManagement::socket_Read_Data()
{
QByteArray getbuffer;
//getbuffer = WebIO::Singleton()->readJsonDocument();//booksocket->readAll();
QJsonDocument getdocument = WebIO::Singleton()->readJsonDocument();//QJsonDocument::fromJson(getbuffer);
QJsonObject rootobj = getdocument.object();
qDebug() << rootobj;
QJsonValue jsonvalue = rootobj.value("jsontype");
QString jsonvaluenumber = jsonvalue.toString();
QJsonValue confirmvalue = rootobj.value("confirmtype");
if(jsonvaluenumber == "5" )// || jsonvaluenumber == 6
{
QJsonValue jsontypevalue = rootobj.value("documents");
qDebug() << jsontypevalue;
QString index = confirmvalue.toString();
if(index == "2")
{
QMessageBox::warning(this, tr("错误"), tr("终端出现错误,请检查网络设置!"));
return;
}
if(jsontypevalue.toArray().size()== 0)
{
QMessageBox::information(this, tr("错误"), tr("没有查询到相关书籍!"));
return;
}
counterpartobject.clear();
ui->tableWidget->setRowCount(0);
ui->tableWidget->clearContents();
QJsonArray bookarray = jsontypevalue.toArray();
ui->tableWidget->setRowCount(bookarray.size());
for(int i = 0; i<bookarray.size(); i++)
{
//QJsonValue booknumber = bookarray.at(i);似乎完全多余并没有必要wazawaza走这一步
QJsonObject iteratorobject = bookarray.at(i).toObject();
counterpartobject.push_back(iteratorobject);
QJsonArray authorarray = iteratorobject.value("authors").toArray();
QString authorstring = "";
for(int i=0; i<authorarray.size(); i++)
authorstring = authorstring + authorarray.at(i).toString() + "; ";
QJsonValue titlevalue = iteratorobject.value("title");
QJsonValue authorvalue = iteratorobject.value("authors");
QJsonValue publishervalue = iteratorobject.value("publisher");
QJsonValue docIDvalue = iteratorobject.value("docID");
ui->tableWidget->setItem(i,0,new QTableWidgetItem(titlevalue.toString()));
ui->tableWidget->setItem(i,1,new QTableWidgetItem(authorstring.left(authorstring.size()-2 )));
ui->tableWidget->setItem(i,2,new QTableWidgetItem(publishervalue.toString()));
ui->tableWidget->setItem(i,3,new QTableWidgetItem(docIDvalue.toString()));
}
}
else if (jsonvaluenumber == "3")
{
int index = confirmvalue.toInt();
if(index == 2)
{
QMessageBox::warning(this, tr("错误"), tr("终端发生错误,请检查网络设置"));
return;
}
if(index == 0)
{
QMessageBox::information(this, tr("成功"), tr("删除成功!"));
ui->tableWidget->removeRow(ui->tableWidget->currentRow());
return;
}
}
}
void BookManagement::getadvancedresult(){
ui->tableWidget->setRowCount(0);
ui->tableWidget->clearContents();
ui->tableWidget->setRowCount(advancetransfer.size());
for(int i = 0; i<advancetransfer.size(); i++)
{
QJsonObject iteratorobject = advancetransfer.at(i).toObject();
QJsonArray authorarray = iteratorobject.value("authors").toArray();
QString authorstring = "";
for(int i=0; i<authorarray.size(); i++)
authorstring = authorstring +authorarray.at(i).toString() + "; ";
QJsonValue titlevalue = iteratorobject.value("title");
QJsonValue authorvalue = iteratorobject.value("authors");
QJsonValue publishervalue = iteratorobject.value("publisher");
QJsonValue docIDvalue = iteratorobject.value("docID");
ui->tableWidget->setItem(i,0,new QTableWidgetItem(titlevalue.toString()));
ui->tableWidget->setItem(i,1,new QTableWidgetItem(authorstring.left(authorstring.size()-2)));
ui->tableWidget->setItem(i,2,new QTableWidgetItem(publishervalue.toString()));
ui->tableWidget->setItem(i,3,new QTableWidgetItem(docIDvalue.toString()));
}
}
| 28.32971
| 108
| 0.646246
|
renzibei
|
11e3fd6a71cfc475f971fbe32f0e110923f7d719
| 1,236
|
cpp
|
C++
|
Source/CastroBld.cpp
|
AMReX-Astro/mini-Castro
|
c9ae36a944b735673ab62ff8b6ded4504e4d6278
|
[
"MIT"
] | 4
|
2019-01-15T16:05:49.000Z
|
2021-05-10T08:47:41.000Z
|
Source/CastroBld.cpp
|
AMReX-Astro/StarLord
|
c9ae36a944b735673ab62ff8b6ded4504e4d6278
|
[
"MIT"
] | 14
|
2017-07-22T19:16:29.000Z
|
2018-12-19T20:12:56.000Z
|
Source/CastroBld.cpp
|
AMReX-Astro/mini-Castro
|
c9ae36a944b735673ab62ff8b6ded4504e4d6278
|
[
"MIT"
] | 4
|
2017-06-05T14:46:01.000Z
|
2018-12-25T01:00:58.000Z
|
#include <AMReX_LevelBld.H>
#include <Castro.H>
using namespace amrex;
class CastroBld
:
public LevelBld
{
virtual void variableSetUp () override;
virtual void variableCleanUp () override;
virtual AmrLevel *operator() () override;
virtual AmrLevel *operator() (Amr& papa,
int lev,
const Geometry& level_geom,
const BoxArray& ba,
const DistributionMapping& dm,
Real time) override;
};
CastroBld Castro_bld;
LevelBld*
getLevelBld ()
{
return &Castro_bld;
}
void
CastroBld::variableSetUp ()
{
Castro::variableSetUp();
}
void
CastroBld::variableCleanUp ()
{
Castro::variableCleanUp();
}
AmrLevel*
CastroBld::operator() ()
{
return new Castro;
}
AmrLevel*
CastroBld::operator() (Amr& papa,
int lev,
const Geometry& level_geom,
const BoxArray& ba,
const DistributionMapping& dm,
Real time)
{
return new Castro(papa, lev, level_geom, ba, dm, time);
}
| 21.310345
| 65
| 0.512945
|
AMReX-Astro
|
eb237fb99a357813b1fccb8b7313253d3288b2c5
| 4,671
|
cpp
|
C++
|
DearPyGui/src/ui/AppItems/drawing/mvDrawImage.cpp
|
BadSugar/DearPyGui
|
95f3f86e2efb7fbe31d76c52a1a7965d96ee9151
|
[
"MIT"
] | 7,471
|
2020-08-12T13:36:38.000Z
|
2022-03-31T14:50:37.000Z
|
DearPyGui/src/ui/AppItems/drawing/mvDrawImage.cpp
|
BadSugar/DearPyGui
|
95f3f86e2efb7fbe31d76c52a1a7965d96ee9151
|
[
"MIT"
] | 922
|
2020-08-12T21:03:42.000Z
|
2022-03-31T01:19:10.000Z
|
DearPyGui/src/ui/AppItems/drawing/mvDrawImage.cpp
|
BadSugar/DearPyGui
|
95f3f86e2efb7fbe31d76c52a1a7965d96ee9151
|
[
"MIT"
] | 550
|
2020-08-12T21:58:55.000Z
|
2022-03-30T09:09:58.000Z
|
#include "mvDrawImage.h"
#include "mvLog.h"
#include "mvItemRegistry.h"
#include "mvContext.h"
#include "mvPythonExceptions.h"
namespace Marvel {
mvDrawImage::mvDrawImage(mvUUID uuid)
:
mvAppItem(uuid)
{
}
void mvDrawImage::applySpecificTemplate(mvAppItem* item)
{
auto titem = static_cast<mvDrawImage*>(item);
_textureUUID = titem->_textureUUID;
_pmax = titem->_pmax;
_pmin = titem->_pmin;
_uv_min = titem->_uv_min;
_uv_max = titem->_uv_max;
_color = titem->_color;
_texture = titem->_texture;
_internalTexture = titem->_internalTexture;
}
void mvDrawImage::draw(ImDrawList* drawlist, float x, float y)
{
if (_texture)
{
if (_internalTexture)
_texture->draw(drawlist, x, y);
if (!_texture->state.ok)
return;
void* texture = nullptr;
if (_texture->type == mvAppItemType::mvStaticTexture)
texture = static_cast<mvStaticTexture*>(_texture.get())->getRawTexture();
else if (_texture->type == mvAppItemType::mvRawTexture)
texture = static_cast<mvRawTexture*>(_texture.get())->getRawTexture();
else
texture = static_cast<mvDynamicTexture*>(_texture.get())->getRawTexture();
mvVec4 tpmin = drawInfo->transform * _pmin;
mvVec4 tpmax = drawInfo->transform * _pmax;
if (drawInfo->perspectiveDivide)
{
tpmin.x = tpmin.x / tpmin.w;
tpmax.x = tpmax.x / tpmax.w;
tpmin.y = tpmin.y / tpmin.w;
tpmax.y = tpmax.y / tpmax.w;
tpmin.z = tpmin.z / tpmin.w;
tpmax.z = tpmax.z / tpmax.w;
}
if (drawInfo->depthClipping)
{
if (mvClipPoint(drawInfo->clipViewport, tpmin)) return;
if (mvClipPoint(drawInfo->clipViewport, tpmax)) return;
}
if (ImPlot::GetCurrentContext()->CurrentPlot)
drawlist->AddImage(texture, ImPlot::PlotToPixels(tpmin), ImPlot::PlotToPixels(tpmax), _uv_min, _uv_max, _color);
else
{
mvVec2 start = { x, y };
drawlist->AddImage(texture, tpmin + start, tpmax + start, _uv_min, _uv_max, _color);
}
}
}
void mvDrawImage::handleSpecificRequiredArgs(PyObject* dict)
{
if (!VerifyRequiredArguments(GetParsers()[GetEntityCommand(type)], dict))
return;
for (int i = 0; i < PyTuple_Size(dict); i++)
{
PyObject* item = PyTuple_GetItem(dict, i);
switch (i)
{
case 0:
{
_textureUUID = GetIDFromPyObject(item);
_texture = GetRefItem(*GContext->itemRegistry, _textureUUID);
if (_texture)
break;
else if (_textureUUID == MV_ATLAS_UUID)
{
_texture = std::make_shared<mvStaticTexture>(_textureUUID);
_internalTexture = true;
break;
}
else
{
mvThrowPythonError(mvErrorCode::mvTextureNotFound, GetEntityCommand(type), "Texture not found.", this);
break;
}
}
case 1:
_pmin = ToVec4(item);
_pmin.w = 1.0f;
break;
case 2:
_pmax = ToVec4(item);
_pmax.w = 1.0f;
break;
default:
break;
}
}
}
void mvDrawImage::handleSpecificKeywordArgs(PyObject* dict)
{
if (dict == nullptr)
return;
if (PyObject* item = PyDict_GetItemString(dict, "pmax")) _pmax = ToVec4(item);
if (PyObject* item = PyDict_GetItemString(dict, "pmin")) _pmin = ToVec4(item);
if (PyObject* item = PyDict_GetItemString(dict, "uv_min")) _uv_min = ToVec2(item);
if (PyObject* item = PyDict_GetItemString(dict, "uv_max")) _uv_max = ToVec2(item);
if (PyObject* item = PyDict_GetItemString(dict, "color")) _color = ToColor(item);
if (PyObject* item = PyDict_GetItemString(dict, "texture_tag"))
{
_textureUUID = GetIDFromPyObject(item);
_texture = GetRefItem(*GContext->itemRegistry, _textureUUID);
if (_textureUUID == MV_ATLAS_UUID)
{
_texture = std::make_shared<mvStaticTexture>(_textureUUID);
_internalTexture = true;
}
else if(_texture)
{
_internalTexture = false;
}
else
{
mvThrowPythonError(mvErrorCode::mvTextureNotFound, GetEntityCommand(type), "Texture not found.", this);
}
}
_pmin.w = 1.0f;
_pmax.w = 1.0f;
}
void mvDrawImage::getSpecificConfiguration(PyObject* dict)
{
if (dict == nullptr)
return;
PyDict_SetItemString(dict, "pmax", mvPyObject(ToPyPair(_pmax.x, _pmax.y)));
PyDict_SetItemString(dict, "pmin", mvPyObject(ToPyPair(_pmin.x, _pmin.y)));
PyDict_SetItemString(dict, "uv_min", mvPyObject(ToPyPair(_uv_min.x, _uv_min.y)));
PyDict_SetItemString(dict, "uv_max", mvPyObject(ToPyPair(_uv_max.x, _uv_max.y)));
PyDict_SetItemString(dict, "color", mvPyObject(ToPyColor(_color)));
PyDict_SetItemString(dict, "texture_tag", mvPyObject(ToPyUUID(_textureUUID)));
}
}
| 27.476471
| 119
| 0.655748
|
BadSugar
|
eb23afb8e7a58380a5e421d7a89795e3fb7713e7
| 2,221
|
hpp
|
C++
|
streamableobject.hpp
|
VladX/StreamlabsAssignment
|
5135270ee5ce77be869a9606ae07b0db771853f1
|
[
"MIT"
] | null | null | null |
streamableobject.hpp
|
VladX/StreamlabsAssignment
|
5135270ee5ce77be869a9606ae07b0db771853f1
|
[
"MIT"
] | null | null | null |
streamableobject.hpp
|
VladX/StreamlabsAssignment
|
5135270ee5ce77be869a9606ae07b0db771853f1
|
[
"MIT"
] | null | null | null |
#pragma once
#include "streamable.hpp"
#include <memory>
#include <string>
#include <map>
#include <vector>
namespace Streamlabs {
enum StreamableObjectType {
INTEGER = 0,
FLOAT,
STRING,
VECTOR,
};
extern const std::vector<std::string> kObjectNames; // Object type names as strings
class StreamableObjectSchema {
private:
#ifdef _MSC_VER
typedef void(__thiscall *MethodPointer)(void*);
#else
typedef void(*MethodPointer)(void*);
#endif
std::vector<std::string> method_names_;
std::map<std::string, MethodPointer> methods;
void RegisterMethod(const std::string &name, MethodPointer method) {
method_names_.push_back(name);
methods[name] = method;
}
void CallMethod(const std::string &name, void* object) const {
methods.at(name)(object);
}
public:
const std::vector<std::string>& GetMethodNames() const { return method_names_; }
friend class StreamableObject;
};
class StreamableObject : public IStreamable {
protected:
StreamableObjectType type_;
StreamableObjectSchema schema_;
// Register a method with the specified name in the schema which could be called later
template<typename T>
void RegisterMethod(const std::string &name, void (T::* method)()) {
const void* ptr = *reinterpret_cast<const void**>(&method);
schema_.RegisterMethod(name, reinterpret_cast<StreamableObjectSchema::MethodPointer>(ptr));
}
public:
StreamableObject(StreamableObjectType type) : type_(type) {}
// Get the type of the underlying object
StreamableObjectType GetType() const { return type_; }
// Get the schema of the underlying object (methods, attributes, etc...)
const StreamableObjectSchema& GetSchema() const { return schema_; }
// Call a method with the specified name
void CallMethod(const std::string &name) {
schema_.CallMethod(name, this);
}
// Factory method to create an empty object with the given type
static std::unique_ptr<StreamableObject> Create(StreamableObjectType type);
// Factory method to create an empty object with the given type name
static std::unique_ptr<StreamableObject> Create(const std::string &type_name);
};
}
| 28.113924
| 99
| 0.707339
|
VladX
|
eb2676654c8e4dd7040c5721f7da4725f0fae85f
| 1,879
|
cpp
|
C++
|
ch-02-Container/ch-02-11.cpp
|
Writtic/gameProgramming
|
a909670f83ddb12bcff17881f080628d223bea54
|
[
"MIT"
] | 2
|
2016-09-20T08:33:24.000Z
|
2020-03-04T09:34:31.000Z
|
ch-02-Container/ch-02-11.cpp
|
Writtic/gameProgramming
|
a909670f83ddb12bcff17881f080628d223bea54
|
[
"MIT"
] | null | null | null |
ch-02-Container/ch-02-11.cpp
|
Writtic/gameProgramming
|
a909670f83ddb12bcff17881f080628d223bea54
|
[
"MIT"
] | 1
|
2020-03-04T15:09:11.000Z
|
2020-03-04T15:09:11.000Z
|
#include <iostream>
#include <vector>
using namespace std;
// 벡터에 숫자가 들어있을 경우
// 중간에 숫자를 추가하거나
// 벡터를 추가하거나
// 벡터를 통째로 드러내거나
int main( )
{
vector<int> v;
v.push_back(10);
v.push_back(20);
v.push_back(30);
v.push_back(40);
v.push_back(50);
vector<int>::iterator iter;
vector<int>::iterator iter2;
vector<int> v2;
v2.assign( v.begin(), v.end() ); // v2에 순차열 [v.begin(), v.end())을 할당.
for( iter = v2.begin(); iter != v2.end() ; ++iter)
cout << *iter << " "; // v2 출력
cout << endl;
iter = v.begin()+2; // 30을 가리킴
// iter가 가리키는 위치에 정수 100을 삽입.
// iter2는 삽입한 정수를 가리키는 반복자.
// 현 위치의 숫자포함 뒷 숫자들은 뒤로 밀려나고 100이 삽입됨.
iter2 = v.insert(iter, 100);
for( iter = v.begin(); iter != v.end() ; ++iter)
cout << *iter << " ";
cout << endl;
cout << "iter2: " << *iter2 << endl;
iter = v2.begin()+1; // {10, 20, 30, 40, 50}
// iter가 가리키는 위치에 [v.begin(), v.end()) 구간의 원소를 삽입.
v2.insert(iter, v.begin(), v.end()); // {10, [v.begin(), v,end()) 20, 30, 40, 50}
for( iter = v2.begin(); iter != v2.end() ; ++iter)
cout << *iter << " ";
cout << endl;
iter = v2.begin()+2; // { 10, 10, 20, 100, …}
// iter가 가리키는 위치의 원소를 제거합니다.
iter2 = v2.erase(iter);
for( iter = v2.begin(); iter != v2.end() ; ++iter)
cout << *iter << " ";
cout << endl;
// [v2.begin()+5, v2.end()) 구간의 원소를 제거합니다.
iter2 = v2.erase(v2.begin()+2, v2.end()-2); // iter2는 다음 원소 v.end()
for( iter = v2.begin(); iter != v2.end() ; ++iter)
cout << *iter << " ";
cout << endl;
if( v == v2 )
cout << "v1 == v2" << endl;
if( v != v2 )
cout << "v1 != v2" << endl;
if( v < v2 )
cout << "v1 < v2" << endl;
if( v > v2 )
cout << "v1 > v2" << endl;
}
| 26.842857
| 86
| 0.465141
|
Writtic
|
eb28f158b6ce96a1e19b48c3a5306e5dee4e1d88
| 55,866
|
cpp
|
C++
|
fallen/Source/hm.cpp
|
inco1/MuckyFoot-UrbanChaos
|
81aa5cfe18ef7fe2d1b1f9911bd33a47c22d5390
|
[
"MIT"
] | 188
|
2017-05-20T03:26:33.000Z
|
2022-03-10T16:58:39.000Z
|
fallen/Source/hm.cpp
|
dizzy2003/MuckyFoot-UrbanChaos
|
81aa5cfe18ef7fe2d1b1f9911bd33a47c22d5390
|
[
"MIT"
] | 7
|
2017-05-28T14:28:13.000Z
|
2022-01-09T01:47:38.000Z
|
fallen/Source/hm.cpp
|
inco1/MuckyFoot-UrbanChaos
|
81aa5cfe18ef7fe2d1b1f9911bd33a47c22d5390
|
[
"MIT"
] | 43
|
2017-05-20T07:31:32.000Z
|
2022-03-09T18:39:35.000Z
|
//
// Hypermatter!
//
#ifndef TARGET_DC
#include "game.h"
#include <MFStdLib.h>
#include <stdlib.h>
#include <hm.h>
#include <math.h>
#include "c:\fallen\ddengine\headers\message.h"
#include "c:\fallen\ddengine\headers\matrix.h"
#include "maths.h"
#include "pap.h"
#include "memory.h"
//
// How to draw a line in the world.
//
void e_draw_3d_line (SLONG x1,SLONG y1,SLONG z1,SLONG x2,SLONG y2,SLONG z2);
void e_draw_3d_line_col_sorted(SLONG x1,SLONG y1,SLONG z1,SLONG x2,SLONG y2,SLONG z2, SLONG r, SLONG g, SLONG b);
//
// Fast approximation to vector length in 3d.
//
static inline float qdist(float x, float y, float z)
{
float ans;
ASSERT(x >= 0.0F);
ASSERT(y >= 0.0F);
ASSERT(z >= 0.0F);
if (x > y)
{
if (x > z)
{
//
// x is the biggeset.
//
ans = x + (y + z) * 0.2941F;
return ans;
}
}
else
{
if (y > z)
{
//
// y is the biggeset.
//
ans = y + (x + z) * 0.2941F;
return ans;
}
}
//
// z is the biggeset.
//
ans = z + (x + y) * 0.2941F;
return ans;
}
//
// Each hypermatter point.
//
typedef struct
{
float x;
float y;
float z;
float dx;
float dy;
float dz;
float mass; // How much gravity we apply to this point.
} HM_Point;
//
// An edge connecting two points for fast force calculations
// between pairs of points.
//
typedef struct
{
UWORD p1;
UWORD p2;
UBYTE len; // Index into the length squared array...
UBYTE shit;
} HM_Edge;
typedef UWORD HM_Index; // Index into the point[] array or NULL if there is no point here.
//
// Each point of the original prim is given in terms of the
// position of three prim points relative to an origin.
//
typedef struct
{
UWORD origin;
UWORD p[3];
float along[3];
} HM_Mesh;
//
// When a point enters a cube of hypermatter belonging to a different object,
// one of these structures is created and tagged onto the linked list for
// each point.
//
typedef struct hm_bump
{
//
// The point that has entered the other object.
//
UWORD point;
UWORD shit;
//
// The other object the point is inside, and the cube
// of that object the point entered.
//
HM_Index hm_index;
UBYTE cube_x;
UBYTE cube_y;
UBYTE cube_z;
//
// The point where the point entered the object, relative to
// the cube.
//
float rel_x;
float rel_y;
float rel_z;
//
// When this point recieves a force that tries to make it leave the
// cube, an equal and opposite force must be applied to the cube.
// The force is applied to these eight points. The proportions should
// all add up to one.
//
#define HM_NUM_OPP_POINTS 8
UWORD opp_point[HM_NUM_OPP_POINTS];
float opp_prop [HM_NUM_OPP_POINTS];
//
// The next structure in the linked list
//
struct hm_bump *next;
} HM_Bump;
//
// An edge that a hypermatter object collides with.
//
typedef struct
{
ULONG consider; // 1 bit for each point, on if that point is worth considering...
float x1, z1;
float x2, z2;
float len;
} HM_Col;
//
// Each hypermatter object.
//
#define HM_MAX_SIZES 256
#define HM_COLS_PER_OBJECT 64
typedef struct
{
UBYTE used;
UBYTE shit;
UWORD prim;
SLONG x_res;
SLONG y_res;
SLONG z_res;
SLONG x_res_times_y_res;
SLONG num_indices;
SLONG num_points;
SLONG num_edges;
SLONG num_sizes;
SLONG num_meshes;
SLONG num_cols;
HM_Index *index;
HM_Point *point;
HM_Edge *edge;
HM_Mesh *mesh;
HM_Col col[HM_COLS_PER_OBJECT];
HM_Bump *bump;
//
// To recreate the (x,y,z) and matrix where we could
// draw the prim. to fit as best as it can inside the hypermatter.
//
SLONG x_index; // Indices into the point array.
SLONG y_index;
SLONG z_index;
SLONG o_index;
float o_prim_x;
float o_prim_y;
float o_prim_z;
float cog_x; // The point about which the prim object rotates.
float cog_y;
float cog_z;
float size [HM_MAX_SIZES];
float oversize[HM_MAX_SIZES]; // The reciprocal of the size array.
float elasticity;
float bounciness;
float friction;
float damping;
} HM_Object;
#define HM_MAX_OBJECTS 8
HM_Object HM_object[HM_MAX_OBJECTS];
SLONG HM_object_upto;
//
// Returns the index of the given point.
//
inline SLONG HM_index(HM_Object *ho, SLONG x, SLONG y, SLONG z)
{
SLONG ans;
ASSERT(WITHIN(x, 0, ho->x_res - 1));
ASSERT(WITHIN(y, 0, ho->y_res - 1));
ASSERT(WITHIN(z, 0, ho->z_res - 1));
ans = x;
ans += y * ho->x_res;
ans += z * ho->x_res_times_y_res;
return ans;
}
void HM_init()
{
SLONG i;
for (i = 0; i < HM_MAX_OBJECTS; i++)
{
HM_object[i].used = FALSE;
}
}
#define HM_MAX_PRIMGRIDS 64
HM_Primgrid HM_primgrid[HM_MAX_PRIMGRIDS];
SLONG HM_primgrid_upto;
void HM_load(CBYTE *fname)
{
SLONG i;
SLONG j;
HM_Header hm_h;
FILE *handle;
handle = MF_Fopen(fname, "rb");
if (handle == NULL)
{
TRACE("Could not open file %s\n", fname);
return;
}
//
// Load in the header.
//
if (fread(&hm_h, sizeof(HM_Header), 1, handle) != 1) goto file_error;
if (hm_h.version != 1)
{
//
// Wrong version.
//
MSG_add("File %s is an obsolete version\n", fname);
return;
}
//
// Load in each HM_Primgrid in turn.
//
HM_primgrid_upto = 0;
for (i = 0; i < hm_h.num_primgrids; i++)
{
ASSERT(WITHIN(HM_primgrid_upto, 0, HM_MAX_PRIMGRIDS - 1));
if (fread(&HM_primgrid[HM_primgrid_upto++], sizeof(HM_Primgrid), 1, handle) != 1) goto file_error;
}
MF_Fclose(handle);
return;
file_error:;
MF_Fclose(handle);
TRACE("Error loading file %s\n", fname);
return;
}
HM_Primgrid HM_default_primgrid =
{
0,
2,
2,
2,
{0, 0x10000},
{0, 0x10000},
{0, 0x10000},
0.00F,
0.00F,
-0.25F
};
HM_Primgrid *HM_get_primgrid(SLONG prim)
{
SLONG i;
for (i = 0; i < HM_primgrid_upto; i++)
{
if (HM_primgrid[i].prim == prim)
{
return &HM_primgrid[i];
}
}
return &HM_default_primgrid;
}
HM_Mesh HM_find_point_inside_cube(
HM_Object *ho,
SLONG x,
SLONG y,
SLONG z,
float ppx,
float ppy,
float ppz)
{
SLONG index_o;
SLONG index_x;
SLONG index_y;
SLONG index_z;
HM_Point *p_o;
HM_Point *p_x;
HM_Point *p_y;
HM_Point *p_z;
float along_x;
float along_y;
float along_z;
HM_Mesh ans;
//
// Find the origin of the cube.
//
index_o = ho->index[HM_index(ho, x + 0, y + 0, z + 0)];
index_x = ho->index[HM_index(ho, x + 1, y + 0, z + 0)];
index_y = ho->index[HM_index(ho, x + 0, y + 1, z + 0)];
index_z = ho->index[HM_index(ho, x + 0, y + 0, z + 1)];
ASSERT(WITHIN(index_o, 1, ho->num_points));
ASSERT(WITHIN(index_x, 1, ho->num_points));
ASSERT(WITHIN(index_y, 1, ho->num_points));
ASSERT(WITHIN(index_z, 1, ho->num_points));
p_o = &ho->point[index_o];
p_x = &ho->point[index_x];
p_y = &ho->point[index_y];
p_z = &ho->point[index_z];
//
// Find the amount you are along each edge.
//
along_x = (ppx - p_o->x) / (p_x->x - p_o->x);
along_y = (ppy - p_o->y) / (p_y->y - p_o->y);
along_z = (ppz - p_o->z) / (p_z->z - p_o->z);
ASSERT(WITHIN(along_x, 0.0F, 1.0F));
ASSERT(WITHIN(along_y, 0.0F, 1.0F));
ASSERT(WITHIN(along_z, 0.0F, 1.0F));
if (along_x + along_y + along_z > 1.5F)
{
//
// We use the other corner of cube because it iss nearer.
//
index_o = ho->index[HM_index(ho, x + 1, y + 1, z + 1)];
index_x = ho->index[HM_index(ho, x + 0, y + 1, z + 1)];
index_y = ho->index[HM_index(ho, x + 1, y + 0, z + 1)];
index_z = ho->index[HM_index(ho, x + 1, y + 1, z + 0)];
ASSERT(WITHIN(index_o, 1, ho->num_points));
ASSERT(WITHIN(index_x, 1, ho->num_points));
ASSERT(WITHIN(index_y, 1, ho->num_points));
ASSERT(WITHIN(index_z, 1, ho->num_points));
along_x = 1.0F - along_x;
along_y = 1.0F - along_y;
along_z = 1.0F - along_z;
}
ans.origin = index_o;
ans.p[0] = index_x;
ans.p[1] = index_y;
ans.p[2] = index_z;
ans.along[0] = along_x;
ans.along[1] = along_y;
ans.along[2] = along_z;
return ans;
}
UBYTE HM_create(
SLONG prim,
SLONG pos_x,
SLONG pos_y,
SLONG pos_z,
SLONG yaw,
SLONG pitch,
SLONG roll,
SLONG vel_x,
SLONG vel_y,
SLONG vel_z,
SLONG x_res, // The number of points along the x-axis
SLONG y_res, // The number of points along the y-axis
SLONG z_res, // The number of points along the z-axis
SLONG x_point[], // The position of each point along the x-axis, 0 => The bounding box min, 0x10000 => the bb max.
SLONG y_point[],
SLONG z_point[],
float x_dgrav,
float y_dgrav,
float z_dgrav,
//
// These go from 0 to 1.
//
float elasticity,
float bounciness,
float friction,
float damping)
{
SLONG i;
SLONG x;
SLONG y;
SLONG z;
SLONG dx;
SLONG dy;
SLONG dz;
SLONG index;
SLONG index1;
SLONG index2;
SLONG num_points;
SLONG num_edges;
SLONG edge_upto;
SLONG point_upto;
SLONG ans;
float dpx;
float dpy;
float dpz;
float size;
HM_Object *ho;
HM_Point *hp;
HM_Point *hp1;
HM_Point *hp2;
HM_Edge *he;
//
// Look for an unused HM_Object...
//
for (i = 0; i < HM_MAX_OBJECTS; i++)
{
ho = &HM_object[i];
if (!ho->used)
{
//
// Found one!
//
ans = i;
goto found_unused_hm_object;
}
}
//
// Oh dear!
//
return HM_NO_MORE_OBJECTS;
found_unused_hm_object:;
ho->used = TRUE;
ho->prim = prim;
ho->x_res = x_res;
ho->y_res = y_res;
ho->z_res = z_res;
ho->x_res_times_y_res = ho->x_res * ho->y_res;
ho->elasticity = elasticity;
ho->bounciness = bounciness;
ho->friction = friction;
ho->damping = damping;
ho->bump = NULL;
//
// The bounding box of the prim.
//
ASSERT(WITHIN(prim, 1, next_prim_object - 1));
PrimObject *po = &prim_objects[prim];
PrimInfo *pi = get_prim_info(prim);
PrimPoint *pp;
PrimFace3 *f3;
PrimFace4 *f4;
ASSERT(WITHIN(x_res, 2, HM_MAX_RES));
ASSERT(WITHIN(y_res, 2, HM_MAX_RES));
ASSERT(WITHIN(z_res, 2, HM_MAX_RES));
UBYTE empty[HM_MAX_RES][HM_MAX_RES][HM_MAX_RES];
SLONG cubex[HM_MAX_RES];
SLONG cubey[HM_MAX_RES];
SLONG cubez[HM_MAX_RES];
//
// Work out the positions of all the unrotated points of
// the new hypermatter object.
//
for (i = 0; i < x_res; i++) {cubex[i] = pi->minx + MUL64(x_point[i], pi->maxx - pi->minx);}
for (i = 0; i < y_res; i++) {cubey[i] = pi->miny + MUL64(y_point[i], pi->maxy - pi->miny);}
for (i = 0; i < z_res; i++) {cubez[i] = pi->minz + MUL64(z_point[i], pi->maxz - pi->minz);}
//
// Mark all the cubes as empty.
//
for (x = 0; x < x_res - 1; x++)
for (y = 0; y < y_res - 1; y++)
for (z = 0; z < z_res - 1; z++)
{
empty[x][y][z] = TRUE;
}
//
// Go through all the points. Mark the cube a point is in as
// not empty.
//
for (i = po->StartPoint; i < po->EndPoint; i++)
{
pp = &prim_points[i];
for (x = 0; x < x_res - 1; x++)
{
if (!WITHIN(pp->X, cubex[x], cubex[x + 1]))
{
continue;
}
for (y = 0; y < y_res - 1; y++)
{
if (!WITHIN(pp->Y, cubey[y], cubey[y + 1]))
{
continue;
}
for (z = 0; z < z_res - 1; z++)
{
if (WITHIN(pp->Z, cubez[z], cubez[z + 1]))
{
empty[x][y][z] = FALSE;
goto do_next_point;
}
}
}
}
do_next_point:;
}
//
// Allocate the indices.
//
ho->num_indices = ho->x_res * ho->y_res * ho->z_res;
ho->index = (HM_Index *) MemAlloc(ho->num_indices * sizeof(HM_Index));
ASSERT(ho->index != NULL);
//
// Clear out the indices.
//
memset((UBYTE*)ho->index, 0, ho->num_indices * sizeof(HM_Index));
//
// Go through all the active cubes and mark the points they used as alive.
//
for (x = 0; x < x_res - 1; x++)
for (y = 0; y < y_res - 1; y++)
for (z = 0; z < z_res - 1; z++)
{
if (!empty[x][y][z])
{
ho->index[HM_index(ho, x + 0, y + 0, z + 0)] = 0xffff;
ho->index[HM_index(ho, x + 1, y + 0, z + 0)] = 0xffff;
ho->index[HM_index(ho, x + 0, y + 1, z + 0)] = 0xffff;
ho->index[HM_index(ho, x + 1, y + 1, z + 0)] = 0xffff;
ho->index[HM_index(ho, x + 0, y + 0, z + 1)] = 0xffff;
ho->index[HM_index(ho, x + 1, y + 0, z + 1)] = 0xffff;
ho->index[HM_index(ho, x + 0, y + 1, z + 1)] = 0xffff;
ho->index[HM_index(ho, x + 1, y + 1, z + 1)] = 0xffff;
}
}
//
// How many points do we need?
//
num_points = 1; // point 0 is the NULL point, so we always need one point.
for (x = 0; x < x_res; x++)
for (y = 0; y < y_res; y++)
for (z = 0; z < z_res; z++)
{
if (ho->index[HM_index(ho, x, y, z)] != NULL)
{
num_points += 1;
}
}
//
// Create the points array.
//
ho->point = (HM_Point *) MemAlloc(num_points * sizeof(HM_Point));
ASSERT(ho->point != NULL);
//
// Put in the correct indices into the point array.
//
float grav_mid_x = float(x_res) * 0.5F;
float grav_mid_y = float(y_res) * 0.5F;
float grav_mid_z = float(z_res) * 0.5F;
point_upto = 1;
for (x = 0; x < x_res; x++)
for (y = 0; y < y_res; y++)
for (z = 0; z < z_res; z++)
{
if (ho->index[HM_index(ho, x, y, z)] != NULL)
{
ASSERT(WITHIN(point_upto, 1, num_points - 1));
ho->index[HM_index(ho, x, y, z)] = point_upto;
ho->point[point_upto].x = float(cubex[x]);
ho->point[point_upto].y = float(cubey[y]);
ho->point[point_upto].z = float(cubez[z]);
ho->point[point_upto].dx = float(vel_x);
ho->point[point_upto].dy = float(vel_y);
ho->point[point_upto].dz = float(vel_z);
ho->point[point_upto].mass = 1.0F;
ho->point[point_upto].mass += (float(x) - grav_mid_x) * x_dgrav;
ho->point[point_upto].mass += (float(y) - grav_mid_y) * y_dgrav;
ho->point[point_upto].mass += (float(z) - grav_mid_z) * z_dgrav;
point_upto += 1;
}
}
ASSERT(point_upto == num_points);
ho->num_points = num_points;
//
// Adjust the gravity of the points so that all objects have the
// same force of gravity acting on them!
//
float grav_av = 0.0F;
float grav_adjust;
for (i = 1; i < ho->num_points; i++)
{
grav_av += ho->point[i].mass;
}
grav_av /= float(ho->num_points - 1);
if (grav_av < 0.01F)
{
//
// Give up!
//
}
else
{
grav_adjust = 1.0F / grav_av;
for (i = 1; i < ho->num_points; i++)
{
ho->point[i].mass *= grav_adjust;
}
}
//
// Count how many edges we need.
//
num_edges = 0;
for (z = 0; z < ho->z_res; z++)
for (y = 0; y < ho->y_res; y++)
for (x = 0; x < ho->x_res; x++)
{
index1 = HM_index(ho, x, y, z);
if (ho->index[index1] == NULL)
{
continue;
}
for (dz = 0; dz <= 1; dz++)
for (dy = -1; dy <= 1; dy++)
for (dx = -1; dx <= 1; dx++)
{
if ((dz == 1) ||
(dx == -1 && dy == 1) ||
(dx == 0 && dy == 1) ||
(dx == 1 && dy == 1) ||
(dx == 1 && dy == 0))
{
if (WITHIN(x + dx, 0, ho->x_res - 1) &&
WITHIN(y + dy, 0, ho->y_res - 1) &&
WITHIN(z + dz, 0, ho->z_res - 1))
{
index2 = HM_index(ho, x + dx, y + dy, z + dz);
if (ho->index[index2] != NULL)
{
num_edges += 1;
}
else
{
num_edges += 0;
}
}
}
}
}
ho->num_edges = num_edges;
//
// Reserve enough memory for them.
//
ho->edge = (HM_Edge *) MemAlloc(num_edges * sizeof(HM_Edge));
//
// Build the edges.
//
edge_upto = 0;
ho->num_sizes = 0;
for (z = 0; z < ho->z_res; z++)
for (y = 0; y < ho->y_res; y++)
for (x = 0; x < ho->x_res; x++)
{
index1 = HM_index(ho, x, y, z);
if (ho->index[index1] == NULL)
{
continue;
}
for (dz = 0; dz <= 1; dz++)
for (dy = -1; dy <= 1; dy++)
for (dx = -1; dx <= 1; dx++)
{
if ((dz == 1) ||
(dx == -1 && dy == 1) ||
(dx == 0 && dy == 1) ||
(dx == 1 && dy == 1) ||
(dx == 1 && dy == 0))
{
if (WITHIN(x + dx, 0, ho->x_res - 1) &&
WITHIN(y + dy, 0, ho->y_res - 1) &&
WITHIN(z + dz, 0, ho->z_res - 1))
{
index2 = HM_index(ho, x + dx, y + dy, z + dz);
if (ho->index[index2] != NULL)
{
ASSERT(WITHIN(edge_upto, 0, ho->num_edges - 1));
ho->edge[edge_upto].p1 = ho->index[index1];
ho->edge[edge_upto].p2 = ho->index[index2];
hp1 = &ho->point[ho->index[index1]];
hp2 = &ho->point[ho->index[index2]];
dpx = hp2->x - hp1->x;
dpy = hp2->y - hp1->y;
dpz = hp2->z - hp1->z;
size = dpx*dpx + dpy*dpy + dpz*dpz;
for (i = 0; i < ho->num_sizes; i++)
{
if (ho->size[i] == size)
{
ho->edge[edge_upto].len = i;
goto found_size;
}
}
ASSERT(WITHIN(ho->num_sizes, 0, HM_MAX_SIZES - 1));
//
// Create a new element in the size array.
//
ho->size [ho->num_sizes] = size;
ho->oversize[ho->num_sizes] = 1.0F / size;
ho->edge[edge_upto].len = ho->num_sizes;
ho->num_sizes += 1;
found_size:;
edge_upto += 1;
}
}
}
}
}
ASSERT(edge_upto == num_edges);
//
// Create the HM_mesh...
//
ho->num_meshes = po->EndPoint - po->StartPoint;
ho->mesh = (HM_Mesh *) MemAlloc(ho->num_meshes * sizeof(HM_Mesh));
ASSERT(ho->mesh != NULL);
for (i = 0; i < ho->num_meshes; i++)
{
//
// Which cube is this point in?
//
pp = &prim_points[po->StartPoint + i];
for (x = 0; x < x_res - 1; x++)
{
if (!WITHIN(pp->X, cubex[x], cubex[x + 1]))
{
continue;
}
for (y = 0; y < y_res - 1; y++)
{
if (!WITHIN(pp->Y, cubey[y], cubey[y + 1]))
{
continue;
}
for (z = 0; z < z_res - 1; z++)
{
if (WITHIN(pp->Z, cubez[z], cubez[z + 1]))
{
//
// This point is in cube (x,y,z)
//
ho->mesh[i] = HM_find_point_inside_cube(
ho,
x, y, z,
float(pp->X),
float(pp->Y),
float(pp->Z));
goto done_this_point;
}
}
}
}
ASSERT(0);
done_this_point:;
}
//
// Find the best three vectors to use for calculating the
// position and orientation of the original prim.
//
float best_score = float(INFINITY);
SLONG best_origin = -1;
SLONG best_x = -1;
SLONG best_y = -1;
SLONG best_z = -1;
SLONG index_o;
SLONG index_x;
SLONG index_y;
SLONG index_z;
float score;
for (x = 0; x < ho->x_res - 1; x++)
for (y = 0; y < ho->y_res - 1; y++)
for (z = 0; z < ho->z_res - 1; z++)
{
index_o = ho->index[HM_index(ho, x, y, z )];
index_x = ho->index[HM_index(ho, x + 1, y, z )];
index_y = ho->index[HM_index(ho, x, y + 1, z )];
index_z = ho->index[HM_index(ho, x, y, z + 1)];
if (index_o != NULL &&
index_x != NULL &&
index_y != NULL &&
index_z != NULL)
{
//
// Points closer to the centre of gravity and origin of
// the prim are better.
//
score = 0;
score += fabs(ho->point[index_o].x - float(pi->cogx));
score += fabs(ho->point[index_o].y - float(pi->cogy));
score += fabs(ho->point[index_o].z - float(pi->cogz));
score += fabs(ho->point[index_o].x);
score += fabs(ho->point[index_o].y);
score += fabs(ho->point[index_o].z);
if (score < best_score)
{
best_score = score;
best_origin = index_o;
best_x = index_x;
best_y = index_y;
best_z = index_z;
}
}
}
if (best_score >= INFINITY)
{
//
// Oh hell! We couldn't find and decent vectors.
//
MemFree(ho->index);
MemFree(ho->point);
MemFree(ho->edge);
MemFree(ho->mesh);
return HM_NO_MORE_OBJECTS;
}
else
{
ho->x_index = best_x;
ho->y_index = best_y;
ho->z_index = best_z;
ho->o_index = best_origin;
ho->o_prim_x = ho->point[best_origin].x;
ho->o_prim_y = ho->point[best_origin].y;
ho->o_prim_z = ho->point[best_origin].z;
ho->cog_x = float(pi->cogx);
ho->cog_y = float(pi->cogy);
ho->cog_z = float(pi->cogz);
}
//
// The rotation matrix of the prim.
//
float f_yaw = float(yaw) * 2.0F * PI / 2048.0F;
float f_pitch = float(pitch) * 2.0F * PI / 2048.0F;
float f_roll = float(roll) * 2.0F * PI / 2048.0F;
float matrix[9];
MATRIX_calc(matrix, f_yaw, f_pitch, f_roll);
//
// Rotate the points about the centre of gravity.
//
float cogx = float(pi->cogx);
float cogy = float(pi->cogy);
float cogz = float(pi->cogz);
for (i = 1; i < ho->num_points; i++)
{
ho->point[i].x -= cogx;
ho->point[i].y -= cogy;
ho->point[i].z -= cogz;
MATRIX_MUL_BY_TRANSPOSE(
matrix,
ho->point[i].x,
ho->point[i].y,
ho->point[i].z);
ho->point[i].x += cogx;
ho->point[i].y += cogy;
ho->point[i].z += cogz;
}
//
// Put the points at the correct place
//
float fposx = float(pos_x);
float fposy = float(pos_y);
float fposz = float(pos_z);
for (i = 1; i < ho->num_points; i++)
{
ho->point[i].x += fposx;
ho->point[i].y += fposy;
ho->point[i].z += fposz;
}
return ans;
}
void HM_destroy(UBYTE hm_index)
{
ASSERT(WITHIN(hm_index, 0, HM_MAX_OBJECTS - 1));
HM_Object *ho = &HM_object[hm_index];
if (ho->used)
{
ho->used = FALSE;
//
// Free up MemAlloc'ed memory.
//
MemFree(ho->index);
MemFree(ho->point);
MemFree(ho->edge);
MemFree(ho->mesh);
}
else
{
//
// Lets just pretend it was okay...
//
}
}
void HM_find_cog(
UBYTE hm_index,
float *x,
float *y,
float *z)
{
SLONG i;
float ans_x = 0.0F;
float ans_y = 0.0F;
float ans_z = 0.0F;
float tot_mass = 0.0F;
ASSERT(WITHIN(hm_index, 0, HM_MAX_OBJECTS - 1));
HM_Object *ho = &HM_object[hm_index];
HM_Point *hp;
ASSERT(ho->used);
for (i = 1; i < ho->num_points; i++)
{
hp = &ho->point[i];
ans_x += hp->x * hp->mass;
ans_y += hp->y * hp->mass;
ans_z += hp->z * hp->mass;
tot_mass += hp->mass;
}
ans_x /= tot_mass;
ans_y /= tot_mass;
ans_z /= tot_mass;
*x = ans_x;
*y = ans_y;
*z = ans_z;
}
void HM_colvect_clear(UBYTE hm)
{
ASSERT(WITHIN(hm, 0, HM_MAX_OBJECTS - 1));
HM_object[hm].num_cols = 0;
}
void HM_colvect_add(
UBYTE hm,
SLONG x1, SLONG z1,
SLONG x2, SLONG z2)
{
SLONG i;
float dx;
float dz;
ASSERT(WITHIN(hm, 0, HM_MAX_OBJECTS - 1));
HM_Object *ho = &HM_object[hm];
HM_Col *hc;
ASSERT(ho->used);
ASSERT(WITHIN(ho->num_cols, 0, HM_COLS_PER_OBJECT - 1));
//
// Do we already have a colvect like this?
//
for (i = 0; i < ho->num_cols; i++)
{
hc = &ho->col[i];
if (hc->x1 == float(x1) &&
hc->z1 == float(z1) &&
hc->x2 == float(x2) &&
hc->z2 == float(z2))
{
return;
}
}
//
// Create a new colvect for this object to collide with.
//
hc = &ho->col[ho->num_cols++];
hc->x1 = float(x1);
hc->z1 = float(z1);
hc->x2 = float(x2);
hc->z2 = float(z2);
dx = hc->x2 - hc->x1;
dz = hc->z2 - hc->z1;
hc->len = sqrt(dx*dx + dz*dz);
//
// Which points of this object are worth considering?
// All of them for now!
//
hc->consider = 0xffffffff;
}
//
// Hmm...
//
//
// This function returns the height of the floor at (x,z).
// It is defined in collide.cpp. We don't #include collide.h
// because then we would have to include thing.h and eventaully
// we'd have to include everything!
//
SLONG calc_height_at(SLONG x, SLONG z);
float HM_height_at(float x, float z)
{
SLONG ans = PAP_calc_height_at(
SLONG(x),
SLONG(z));
return float(ans);
}
//
// Returns the position of the given mesh-point of the HM_object.
//
void HM_find_mesh_point(
UBYTE hm_index,
SLONG point,
float *x,
float *y,
float *z)
{
float ansx;
float ansy;
float ansz;
HM_Point *p_o;
HM_Point *p_x;
HM_Point *p_y;
HM_Point *p_z;
ASSERT(WITHIN(hm_index, 0, HM_MAX_OBJECTS - 1));
HM_Object *ho = &HM_object[hm_index];
HM_Mesh *hm;
ASSERT(WITHIN(point, 0, ho->num_meshes - 1));
hm = &ho->mesh[point];
ASSERT(WITHIN(hm->origin, 1, ho->num_points - 1));
ASSERT(WITHIN(hm->p[0], 1, ho->num_points - 1));
ASSERT(WITHIN(hm->p[1], 1, ho->num_points - 1));
ASSERT(WITHIN(hm->p[2], 1, ho->num_points - 1));
p_o = &ho->point[hm->origin];
p_x = &ho->point[hm->p[0]];
p_y = &ho->point[hm->p[1]];
p_z = &ho->point[hm->p[2]];
ansx = p_o->x;
ansy = p_o->y;
ansz = p_o->z;
ansx += hm->along[0] * (p_x->x - p_o->x);
ansy += hm->along[0] * (p_x->y - p_o->y);
ansz += hm->along[0] * (p_x->z - p_o->z);
ansx += hm->along[1] * (p_y->x - p_o->x);
ansy += hm->along[1] * (p_y->y - p_o->y);
ansz += hm->along[1] * (p_y->z - p_o->z);
ansx += hm->along[2] * (p_z->x - p_o->x);
ansy += hm->along[2] * (p_z->y - p_o->y);
ansz += hm->along[2] * (p_z->z - p_o->z);
*x = ansx;
*y = ansy;
*z = ansz;
}
//
// Returnstrue if the cube of the hypermatter object exists. If you pass
// an out-of-bounds cube, then it just returns FALSE.
//
SLONG HM_cube_exists(
HM_Object *ho,
SLONG x_cube,
SLONG y_cube,
SLONG z_cube)
{
SLONG i;
SLONG dx;
SLONG dy;
SLONG dz;
SLONG px;
SLONG py;
SLONG pz;
SLONG index;
if (!WITHIN(x_cube, 0, ho->x_res - 2) ||
!WITHIN(y_cube, 0, ho->y_res - 2) ||
!WITHIN(z_cube, 0, ho->z_res - 2))
{
return FALSE;
}
for (i = 0; i < 8; i++)
{
dx = (i >> 0) & 1;
dy = (i >> 1) & 1;
dz = (i >> 2) & 1;
px = x_cube + dx;
py = y_cube + dy;
pz = z_cube + dz;
if (!WITHIN(px, 0, ho->x_res - 1) ||
!WITHIN(py, 0, ho->y_res - 1) ||
!WITHIN(pz, 0, ho->z_res - 1))
{
return FALSE;
}
index = HM_index(ho, px, py, pz);
if (ho->index[index] == NULL)
{
//
// No point here.
//
return FALSE;
}
}
return TRUE;
}
//
// Returns true if 'p' is inside the given cube of the hypermatter object.
// If it is it gives a point on an outside surface of the cube that 'p' entered by.
// The point is given in terms of the three vectors that go out of the origin of the
// cube.
//
SLONG HM_is_point_in_cube(
HM_Object *ho, // The object the cube is a part of...
HM_Point *p,
SLONG x_cube,
SLONG y_cube,
SLONG z_cube,
float *rel_x,
float *rel_y,
float *rel_z)
{
HM_Point *hp_o;
HM_Point *hp_x;
HM_Point *hp_y;
HM_Point *hp_z;
float rx;
float ry;
float rz;
float len;
float matrix[9];
SLONG index_o;
SLONG index_x;
SLONG index_y;
SLONG index_z;
ASSERT(WITHIN(x_cube, 0, ho->x_res - 2));
ASSERT(WITHIN(y_cube, 0, ho->y_res - 2));
ASSERT(WITHIN(z_cube, 0, ho->z_res - 2));
//
// Make sure this cube exists...
//
if (!HM_cube_exists(ho, x_cube, y_cube, z_cube))
{
return FALSE;
}
//
// ASSUME THAT THE CUBE IS IN A RIGID SHAPE.
//
index_o = HM_index(ho, x_cube + 0, y_cube + 0, z_cube + 0);
index_x = HM_index(ho, x_cube + 1, y_cube + 0, z_cube + 0);
index_y = HM_index(ho, x_cube + 0, y_cube + 1, z_cube + 0);
index_z = HM_index(ho, x_cube + 0, y_cube + 0, z_cube + 1);
ASSERT(WITHIN(ho->index[index_o], 1, ho->num_points - 1));
ASSERT(WITHIN(ho->index[index_x], 1, ho->num_points - 1));
ASSERT(WITHIN(ho->index[index_y], 1, ho->num_points - 1));
ASSERT(WITHIN(ho->index[index_z], 1, ho->num_points - 1));
hp_o = &ho->point[ho->index[index_o]];
hp_x = &ho->point[ho->index[index_x]];
hp_y = &ho->point[ho->index[index_y]];
hp_z = &ho->point[ho->index[index_z]];
//
// Create a rotation matrix that rotates point 'p' into the space of the cube.
//
matrix[0] = hp_x->x - hp_o->x;
matrix[1] = hp_x->y - hp_o->y;
matrix[2] = hp_x->z - hp_o->z;
matrix[3] = hp_y->x - hp_o->x;
matrix[4] = hp_y->y - hp_o->y;
matrix[5] = hp_y->z - hp_o->z;
matrix[6] = hp_z->x - hp_o->x;
matrix[7] = hp_z->y - hp_o->y;
matrix[8] = hp_z->z - hp_o->z;
//
// ASSUME THAT THE MATRIX IS ORTHOGONAL! Normalise each vector of the matrix
// 'doubley' so that the space of the box goes from 0 to 1 in each axis..
//
len = matrix[0]*matrix[0] + matrix[1]*matrix[1] + matrix[2]*matrix[2];
len = 1.0F / len;
matrix[0] *= len;
matrix[1] *= len;
matrix[2] *= len;
len = matrix[3]*matrix[3] + matrix[4]*matrix[4] + matrix[5]*matrix[5];
len = 1.0F / len;
matrix[3] *= len;
matrix[4] *= len;
matrix[5] *= len;
len = matrix[6]*matrix[6] + matrix[7]*matrix[7] + matrix[8]*matrix[8];
len = 1.0F / len;
matrix[6] *= len;
matrix[7] *= len;
matrix[8] *= len;
//
// Find the coordinates of point 'p' in the space of this cube.
//
rx = p->x - hp_o->x;
ry = p->y - hp_o->y;
rz = p->z - hp_o->z;
MATRIX_MUL(matrix, rx, ry, rz);
//
// Is the point inside the cube?
//
if (WITHIN(rx, 0.0F, 1.0F) &&
WITHIN(ry, 0.0F, 1.0F) &&
WITHIN(rz, 0.0F, 1.0F))
{
//
// This point is inside the cube.
//
*rel_x = rx;
*rel_y = ry;
*rel_z = rz;
return TRUE;
}
return FALSE;
}
//
// Find the last position of the point relative to the last position of the cube.
//
void HM_last_point_in_last_cube(
HM_Object *ho, // The object the cube is a part of...
HM_Point *p,
SLONG x_cube,
SLONG y_cube,
SLONG z_cube,
float *last_rel_x,
float *last_rel_y,
float *last_rel_z)
{
HM_Point *hp_o;
HM_Point *hp_x;
HM_Point *hp_y;
HM_Point *hp_z;
float rx;
float ry;
float rz;
float len;
float matrix[9];
SLONG index_o;
SLONG index_x;
SLONG index_y;
SLONG index_z;
ASSERT(WITHIN(x_cube, 0, ho->x_res - 2));
ASSERT(WITHIN(y_cube, 0, ho->y_res - 2));
ASSERT(WITHIN(z_cube, 0, ho->z_res - 2));
//
// This cube must exist.
//
ASSERT(HM_cube_exists(ho, x_cube, y_cube, z_cube));
//
// ASSUME THAT THE CUBE IS IN A RIGID SHAPE.
//
index_o = HM_index(ho, x_cube + 0, y_cube + 0, z_cube + 0);
index_x = HM_index(ho, x_cube + 1, y_cube + 0, z_cube + 0);
index_y = HM_index(ho, x_cube + 0, y_cube + 1, z_cube + 0);
index_z = HM_index(ho, x_cube + 0, y_cube + 0, z_cube + 1);
ASSERT(WITHIN(ho->index[index_o], 1, ho->num_points - 1));
ASSERT(WITHIN(ho->index[index_x], 1, ho->num_points - 1));
ASSERT(WITHIN(ho->index[index_y], 1, ho->num_points - 1));
ASSERT(WITHIN(ho->index[index_z], 1, ho->num_points - 1));
hp_o = &ho->point[ho->index[index_o]];
hp_x = &ho->point[ho->index[index_x]];
hp_y = &ho->point[ho->index[index_y]];
hp_z = &ho->point[ho->index[index_z]];
//
// Create a rotation matrix that rotates point 'p' into the space of the cube.
//
matrix[0] = (hp_x->x - hp_x->dx) - (hp_o->x - hp_o->dx);
matrix[1] = (hp_x->y - hp_x->dy) - (hp_o->y - hp_o->dy);
matrix[2] = (hp_x->z - hp_x->dz) - (hp_o->z - hp_o->dz);
matrix[3] = (hp_y->x - hp_y->dx) - (hp_o->x - hp_o->dx);
matrix[4] = (hp_y->y - hp_y->dy) - (hp_o->y - hp_o->dy);
matrix[5] = (hp_y->z - hp_y->dz) - (hp_o->z - hp_o->dz);
matrix[6] = (hp_z->x - hp_z->dx) - (hp_o->x - hp_o->dx);
matrix[7] = (hp_z->y - hp_z->dy) - (hp_o->y - hp_o->dy);
matrix[8] = (hp_z->z - hp_z->dz) - (hp_o->z - hp_o->dz);
//
// ASSUME THAT THE MATRIX IS ORTHOGONAL! Normalise each vector of the matrix
// 'doubley' so that the space of the box goes from 0 to 1 in each axis..
//
len = matrix[0]*matrix[0] + matrix[1]*matrix[1] + matrix[2]*matrix[2];
len = 1.0F / len;
matrix[0] *= len;
matrix[1] *= len;
matrix[2] *= len;
len = matrix[3]*matrix[3] + matrix[4]*matrix[4] + matrix[5]*matrix[5];
len = 1.0F / len;
matrix[3] *= len;
matrix[4] *= len;
matrix[5] *= len;
len = matrix[6]*matrix[6] + matrix[7]*matrix[7] + matrix[8]*matrix[8];
len = 1.0F / len;
matrix[6] *= len;
matrix[7] *= len;
matrix[8] *= len;
//
// Find the coordinates of point 'p' in the space of this cube.
//
rx = (p->x - p->dx) - (hp_o->x - hp_o->dx);
ry = (p->y - p->dy) - (hp_o->y - hp_o->dy);
rz = (p->z - p->dz) - (hp_o->z - hp_o->dz);
MATRIX_MUL(matrix, rx, ry, rz);
*last_rel_x = rx;
*last_rel_y = ry;
*last_rel_z = rz;
}
void HM_collide_all()
{
SLONG i;
SLONG j;
for (i = 0; i < HM_MAX_OBJECTS; i++)
{
if (!HM_object[i].used)
{
continue;
}
for (j = i + 1; j < HM_MAX_OBJECTS; j++)
{
if (!HM_object[i].used)
{
continue;
}
HM_collide(i,j);
HM_collide(j,i);
}
}
}
//
// Given a point relative to a cube, this function returns the 3d
// coordinates of that point.
//
void HM_rel_cube_to_world(
HM_Object *ho, // The object the cube is a part of...
SLONG x_cube,
SLONG y_cube,
SLONG z_cube,
float rel_x,
float rel_y,
float rel_z,
float *world_x,
float *world_y,
float *world_z)
{
float wx;
float wy;
float wz;
float len;
float matrix[9];
HM_Point *hp_o;
HM_Point *hp_x;
HM_Point *hp_y;
HM_Point *hp_z;
SLONG index_o;
SLONG index_x;
SLONG index_y;
SLONG index_z;
ASSERT(WITHIN(x_cube, 0, ho->x_res - 2));
ASSERT(WITHIN(y_cube, 0, ho->y_res - 2));
ASSERT(WITHIN(z_cube, 0, ho->z_res - 2));
//
// This cube must exist.
//
ASSERT(HM_cube_exists(ho, x_cube, y_cube, z_cube));
index_o = HM_index(ho, x_cube + 0, y_cube + 0, z_cube + 0);
index_x = HM_index(ho, x_cube + 1, y_cube + 0, z_cube + 0);
index_y = HM_index(ho, x_cube + 0, y_cube + 1, z_cube + 0);
index_z = HM_index(ho, x_cube + 0, y_cube + 0, z_cube + 1);
ASSERT(WITHIN(ho->index[index_o], 1, ho->num_points - 1));
ASSERT(WITHIN(ho->index[index_x], 1, ho->num_points - 1));
ASSERT(WITHIN(ho->index[index_y], 1, ho->num_points - 1));
ASSERT(WITHIN(ho->index[index_z], 1, ho->num_points - 1));
hp_o = &ho->point[ho->index[index_o]];
hp_x = &ho->point[ho->index[index_x]];
hp_y = &ho->point[ho->index[index_y]];
hp_z = &ho->point[ho->index[index_z]];
//
// Create a rotation matrix that rotates point 'p' into the space of the cube.
//
matrix[0] = hp_x->x - hp_o->x;
matrix[1] = hp_x->y - hp_o->y;
matrix[2] = hp_x->z - hp_o->z;
matrix[3] = hp_y->x - hp_o->x;
matrix[4] = hp_y->y - hp_o->y;
matrix[5] = hp_y->z - hp_o->z;
matrix[6] = hp_z->x - hp_o->x;
matrix[7] = hp_z->y - hp_o->y;
matrix[8] = hp_z->z - hp_o->z;
#if WE_WANT_TO_NORMALISE_THE_MATRIX
//
// ASSUME THAT THE MATRIX IS ORTHOGONAL! Normalise each vector of the matrix
// 'doubley' so that the space of the box goes from 0 to 1 in each axis..
//
len = matrix[0]*matrix[0] + matrix[1]*matrix[1] + matrix[2]*matrix[2];
len = 1.0F / len;
matrix[0] *= len;
matrix[1] *= len;
matrix[2] *= len;
len = matrix[3]*matrix[3] + matrix[4]*matrix[4] + matrix[5]*matrix[5];
len = 1.0F / len;
matrix[3] *= len;
matrix[4] *= len;
matrix[5] *= len;
len = matrix[6]*matrix[6] + matrix[7]*matrix[7] + matrix[8]*matrix[8];
len = 1.0F / len;
matrix[6] *= len;
matrix[7] *= len;
matrix[8] *= len;
#endif
//
// Convert from cube-space to world space.
//
wx = rel_x;
wy = rel_y;
wz = rel_z;
MATRIX_MUL_BY_TRANSPOSE(
matrix,
wx,
wy,
wz);
wx += hp_o->x;
wy += hp_o->y;
wz += hp_o->z;
*world_x = wx;
*world_y = wy;
*world_z = wz;
}
//
// Does the processing for the enter structure that it part of
// the given HM_Object.
//
void HM_process_bump(HM_Object *ho, HM_Bump *hb)
{
SLONG i;
float out_x;
float out_y;
float out_z;
float squash;
float dx;
float dy;
float dz;
float fx;
float fy;
float fz;
float dist;
ASSERT(WITHIN(hb->point, 1, ho->num_points - 1));
ASSERT(WITHIN(hb->hm_index, 0, HM_MAX_OBJECTS - 1));
HM_Point *hp = &ho->point[hb->point];
HM_Object *ho2 = &HM_object[hb->hm_index];
HM_Point *hp2;
MSG_add("Bumping!");
//
// Where did this point enter the object?
//
HM_rel_cube_to_world(
ho2,
hb->cube_x,
hb->cube_y,
hb->cube_z,
hb->rel_x,
hb->rel_y,
hb->rel_z,
&out_x,
&out_y,
&out_z);
#ifndef TARGET_DC
e_draw_3d_line(
hp->x,
hp->y,
hp->z,
out_x,
out_y,
out_z);
#endif
//
// Work out the force on the point.
//
dx = out_x - hp->x;
dy = out_y - hp->y;
dz = out_z - hp->z;
dist = dx*dx + dy*dy + dz*dz;
squash = ho2->elasticity * dist * 0.0003F;
fx = squash * dx;
fy = squash * dy;
fz = squash * dz;
//
// Apply the force to the point.
//
hp->dx += fx;
hp->dy += fy;
hp->dz += fz;
#ifdef WE_WANT_TO_APPLY_THE_EQUAL_FORCE_TO_THE_CUBE
//
// Apply an equal but opposite force to the cube.
//
for (i = 0; i < HM_NUM_OPP_POINTS; i++)
{
ASSERT(WITHIN(hb->opp_point[i], 1, ho2->num_points - 1));
hp2 = &ho2->point[hb->opp_point[i]];
hp2->dx -= fx * hb->opp_prop[i];
hp2->dy -= fy * hb->opp_prop[i];
hp2->dz -= fz * hb->opp_prop[i];
}
#endif
}
//
// Returns TRUE if the given bump structure is no longer relavent- i.e.
// the bumping point is no longer bumping.
//
SLONG HM_bump_dead(HM_Object *ho, HM_Bump *hb)
{
SLONG sx;
SLONG sy;
SLONG sz;
float rel_x;
float rel_y;
float rel_z;
ASSERT(WITHIN(hb->point, 1, ho->num_points - 1));
ASSERT(WITHIN(hb->hm_index, 0, HM_MAX_OBJECTS - 1));
HM_Point *hp = &ho->point[hb->point];
HM_Object *ho2 = &HM_object[hb->hm_index];
//
// Check the cube the point entered originally first, as
// an optimisation.
//
if (HM_is_point_in_cube(
ho2,
hp,
hb->cube_x,
hb->cube_y,
hb->cube_z,
&rel_x,
&rel_y,
&rel_z))
{
return FALSE;
}
for (sx = 0; sx < ho2->x_res - 1; sx++)
for (sy = 0; sy < ho2->y_res - 1; sy++)
for (sz = 0; sz < ho2->z_res - 1; sz++)
{
if (sx == hb->cube_x &&
sy == hb->cube_y &&
sz == hb->cube_z)
{
//
// Already checked this cube.
//
}
else
{
if (HM_is_point_in_cube(
ho2,
hp,
sx,
sy,
sz,
&rel_x,
&rel_y,
&rel_z))
{
return FALSE;
}
}
}
//
// The point is not inside the object... don't collide any more.
//
return TRUE;
}
void HM_collide(UBYTE hm_index1, UBYTE hm_index2)
{
SLONG i;
SLONG j;
SLONG k;
SLONG dx;
SLONG dy;
SLONG dz;
SLONG px;
SLONG py;
SLONG pz;
SLONG index;
SLONG sx;
SLONG sy;
SLONG sz;
float dpx;
float dpy;
float dpz;
float fx;
float fy;
float fz;
float rel_x;
float rel_y;
float rel_z;
float last_rel_x;
float last_rel_y;
float last_rel_z;
float along_x;
float along_y;
float along_z;
float along_enter;
float enter_rel_x;
float enter_rel_y;
float enter_rel_z;
float out_x;
float out_y;
float out_z;
float total_dist;
float dist;
float ddist;
float pdist;
float squash;
float wantdist;
float squaredist;
SLONG byte;
SLONG bit;
HM_Object *ho1;
HM_Object *ho2;
HM_Point *hp;
HM_Point *hp2;
HM_Bump *hb;
#define HM_ALREADY_BYTES 16
UBYTE already_bumped[HM_ALREADY_BYTES];
ASSERT(WITHIN(hm_index1, 0, HM_MAX_OBJECTS - 1));
ASSERT(WITHIN(hm_index2, 0, HM_MAX_OBJECTS - 1));
ho1 = &HM_object[hm_index1];
ho2 = &HM_object[hm_index2];
//
// Find any points of hypermatter object 1 that are already inside one of
// the cubes of hypermatter object 2.
//
memset((UBYTE*)already_bumped, 0, sizeof(already_bumped));
for (hb = ho1->bump; hb; hb = hb->next)
{
if (hb->hm_index == hm_index2)
{
byte = hb->point >> 3;
bit = hb->point & 7;
ASSERT(WITHIN(byte, 0, HM_ALREADY_BYTES - 1));
already_bumped[byte] |= 1 << bit;
}
}
//
// Are any of the points of hypermatter object1 inside one of
// the cubes of hypermatter object 2?
//
for (i = 1; i < ho1->num_points; i++)
{
hp = &ho1->point[i];
if (already_bumped[i >> 3] & (1 << (i & 7)))
{
//
// This point already has a bumped structure for it.
//
continue;
}
//
// Go through each square in object 2.
//
for (sx = 0; sx < ho2->x_res - 1; sx++)
for (sy = 0; sy < ho2->y_res - 1; sy++)
for (sz = 0; sz < ho2->z_res - 1; sz++)
{
if (HM_is_point_in_cube(
ho2,
hp,
sx,
sy,
sz,
&rel_x,
&rel_y,
&rel_z))
{
//
// Find the last relative position of the point.
//
HM_last_point_in_last_cube(
ho2,
hp,
sx,
sy,
sz,
&last_rel_x,
&last_rel_y,
&last_rel_z);
//
// So where did the point enter the cube?
//
along_x = float(INFINITY);
along_y = float(INFINITY);
along_z = float(INFINITY);
//
// Along one of the x-edges?
//
if (last_rel_x > 1.0F && rel_x <= 1.0F && !HM_cube_exists(ho2, sx + 1, sy, sz))
{
along_x = (1.0F - last_rel_x) / (rel_x - last_rel_x);
}
else
if (last_rel_x < 0.0F && rel_x >= 0.0F && !HM_cube_exists(ho2, sx - 1, sy, sz))
{
along_x = (0.0F - last_rel_x) / (rel_x - last_rel_x);
}
//
// Along one of the y-edges?
//
if (last_rel_y > 1.0F && rel_y <= 1.0F && !HM_cube_exists(ho2, sx, sy + 1, sz))
{
along_y = (1.0F - last_rel_y) / (rel_y - last_rel_y);
}
else
if (last_rel_y < 0.0F && rel_y >= 0.0F && !HM_cube_exists(ho2, sx, sy - 1, sz))
{
along_y = (0.0F - last_rel_y) / (rel_y - last_rel_y);
}
//
// Along one of the z-edges?
//
if (last_rel_z > 1.0F && rel_z <= 1.0F && !HM_cube_exists(ho2, sx, sy, sz + 1))
{
along_z = (1.0F - last_rel_z) / (rel_z - last_rel_z);
}
else
if (last_rel_z < 0.0F && rel_z >= 0.0F && !HM_cube_exists(ho2, sx, sy, sz - 1))
{
along_z = (0.0F - last_rel_z) / (rel_z - last_rel_z);
}
along_enter = float(INFINITY);
if (along_x < along_enter) {along_enter = along_x;}
if (along_y < along_enter) {along_enter = along_y;}
if (along_z < along_enter) {along_enter = along_z;}
//
// 'along_enter' is how far along the line from (last_rel to rel) the point
// entered the cube.
//
enter_rel_x = last_rel_x + along_enter * (rel_x - last_rel_x);
enter_rel_y = last_rel_y + along_enter * (rel_y - last_rel_y);
enter_rel_z = last_rel_z + along_enter * (rel_z - last_rel_z);
//
// The point outside the cube.
//
HM_rel_cube_to_world(
ho2,
sx,
sy,
sz,
enter_rel_x,
enter_rel_y,
enter_rel_z,
&out_x,
&out_y,
&out_z);
//
// Find the HM_NUM_OPP_POINTS points of 'ho2' that are nearest (out_x,out_y,out_z).
//
SLONG opp_num;
SLONG opp_point[HM_NUM_OPP_POINTS];
float opp_dist [HM_NUM_OPP_POINTS];
dpx = ho2->point[1].x - out_x;
dpy = ho2->point[1].y - out_y;
dpz = ho2->point[1].z - out_z;
dist = dpx*dpx + dpy*dpy + dpz*dpz;
opp_point[0] = 1;
opp_dist [0] = dist;
opp_num = 1;
for (j = 2; j < ho2->num_points; j++)
{
dpx = ho2->point[j].x - out_x;
dpy = ho2->point[j].y - out_y;
dpz = ho2->point[j].z - out_z;
dist = dpx*dpx + dpy*dpy + dpz*dpz;
for (k = opp_num - 1; k >= 0; k--)
{
if (opp_dist[k] > dist)
{
if (k + 1 < HM_NUM_OPP_POINTS)
{
opp_point[k + 1] = opp_point[k];
opp_dist [k + 1] = opp_dist [k];
}
}
else
{
if (k + 1 < HM_NUM_OPP_POINTS)
{
opp_point[k + 1] = j;
opp_dist [k + 1] = dist;
break;
}
}
}
opp_num += 1;
if (opp_num > HM_NUM_OPP_POINTS)
{
opp_num = HM_NUM_OPP_POINTS;
}
}
//
// Create a new HM_Bump structure for this point.
//
hb = (HM_Bump *) MemAlloc(sizeof(HM_Bump));
hb->point = i;
hb->hm_index = hm_index2;
hb->cube_x = sx;
hb->cube_y = sy;
hb->cube_z = sz;
hb->rel_x = enter_rel_x;
hb->rel_y = enter_rel_y;
hb->rel_z = enter_rel_z;
total_dist = 0;
for (j = 0; j < HM_NUM_OPP_POINTS; j++)
{
hb->opp_point[j] = opp_point[j];
hb->opp_prop [j] = 1.0F / opp_dist [j];
total_dist += hb->opp_prop[j];
}
for (j = 0; j < HM_NUM_OPP_POINTS; j++)
{
hb->opp_prop[j] *= (1.0F / total_dist);
}
{
HM_Bump *bb;
for (bb = ho1->bump; bb; bb = bb->next)
{
if (bb->hm_index == hm_index2)
{
if (bb->point == i)
{
MSG_add("Two that are the same.");
}
}
}
}
//
// Add the structure to the linked list for this object.
//
hb->next = ho1->bump;
ho1->bump = hb;
}
else
{
}
}
}
}
//
// The gravty...
//
#define HM_GRAVITY (-0.015F)
void HM_process()
{
SLONG i;
SLONG j;
SLONG k;
float ddx;
float ddy;
float ddz;
float squaredist;
float dpx;
float dpy;
float dpz;
float pdist;
float wantdist;
float wantdistx;
float wantdisty;
float wantdistz;
float ddist;
float ddistx;
float ddisty;
float ddistz;
float squash;
float fx;
float fy;
float fz;
float gy;
float av_div;
HM_Object *ho;
HM_Point *hp;
HM_Point *hp1;
HM_Point *hp2;
HM_Edge *he;
HM_Col *hc;
HM_Bump *hb;
HM_Bump **prev;
HM_Bump *dead;
for (i = 0; i < HM_MAX_OBJECTS; i++)
{
ho = &HM_object[i];
if (!ho->used)
{
continue;
}
/*
//
// Keyboard control...
//
if (Keys[KB_P3] ||
Keys[KB_P2])
{
if (Keys[KB_P3]) {Keys[KB_P3] = 0; ho->elasticity *= 1.05F;}
if (Keys[KB_P2]) {Keys[KB_P2] = 0; ho->elasticity *= 0.95F;}
MSG_add("Elasticity = %f", ho->elasticity);
}
if (Keys[KB_P6] ||
Keys[KB_P5])
{
if (Keys[KB_P6]) {Keys[KB_P6] = 0; ho->damping += 0.0001F;}
if (Keys[KB_P5]) {Keys[KB_P5] = 0; ho->damping -= 0.0001F;}
MSG_add("Damping = %f", ho->damping);
}
if (Keys[KB_P1])
{
Keys[KB_P1] = 0;
}
if (Keys[KB_ASTERISK])
{
Keys[KB_ASTERISK] = 0;
if (ho->friction < 0.5F)
{
ho->friction = 0.9F;
}
else
{
ho->friction = 0.1F;
}
MSG_add("Friction = %f", ho->friction);
}
if (Keys[KB_PSLASH])
{
Keys[KB_PSLASH] = 0;
if (ho->bounciness > 0.75F)
{
ho->bounciness = 0.0F;
}
else
if (ho->bounciness > 0.25F)
{
ho->bounciness = 1.0F;
}
else
{
ho->bounciness = 0.5F;
}
MSG_add("Bounciness = %f", ho->bounciness);
}
if (Keys[KB_P7])
{
ho->point[1].dy = 40.0F * -HM_GRAVITY * ho->x_res;
}
if (Keys[KB_P4])
{
ho->point[2].dx += 25.0F * -HM_GRAVITY * ho->x_res;
}
*/
//
// Fast processing via the edge list.
//
for (j = 0; j < ho->num_edges; j++)
{
he = &ho->edge[j];
ASSERT(WITHIN(he->p1, 0, ho->num_points - 1));
ASSERT(WITHIN(he->p2, 0, ho->num_points - 1));
hp1 = &ho->point[he->p1];
hp2 = &ho->point[he->p2];
dpx = hp2->x - hp1->x;
dpy = hp2->y - hp1->y;
dpz = hp2->z - hp1->z;
squaredist = dpx*dpx;
squaredist += dpy*dpy;
squaredist += dpz*dpz;
if (squaredist > 0.001F)
{
ASSERT(WITHIN(he->len, 0, ho->num_sizes - 1));
pdist = squaredist;
wantdist = ho->size[he->len];
ddist = pdist - wantdist;
squash = ddist * ho->elasticity * ho->oversize[he->len];
//
// Equal and opposite force between the two points.. what if they
// have different mass, though?
//
fx = dpx * squash;
fy = dpy * squash;
fz = dpz * squash;
hp1->dx += fx;
hp1->dy += fy;
hp1->dz += fz;
hp2->dx -= fx;
hp2->dy -= fy;
hp2->dz -= fz;
}
else
{
MSG_add("Points too close together.");
}
}
//
// Collision processing of the bump list.
//
for (hb = ho->bump; hb; hb = hb->next)
{
HM_process_bump(ho, hb);
}
//
// Do the movement of all the points
//
for (j = 1; j < ho->num_points; j++)
{
hp = &ho->point[j];
//
// Damping.
//
hp->dx *= ho->damping;
hp->dy *= ho->damping;
hp->dz *= ho->damping;
//
// Gravity should constant on all points... surely!
//
hp->dy += HM_GRAVITY * hp->mass; // WE CAN PRECALCULATE THIS MULTIPLY!!!
//
// If the point is underground, then bring it to the surface.
//
{
gy = 0;
if (hp->y < gy)
{
//
// Bounciness and friction.
//
hp->dy = -hp->dy * ho->bounciness;
hp->dx *= ho->friction;
hp->dz *= ho->friction;
hp->y = gy - hp->y;
}
}
//
// Does this point collide?
//
for (k = 0; k < ho->num_cols; k++)
{
hc = &ho->col[k];
if (MATHS_seg_intersect(
SLONG(hc->x1), SLONG(hc->z1),
SLONG(hc->x2), SLONG(hc->z2),
SLONG(hp->x),
SLONG(hp->z),
SLONG(hp->x + hp->dx + hp->dx),
SLONG(hp->z + hp->dz + hp->dz)))
{
if (hc->x1 == hc->x2)
{
hp->dx = -hp->dx;
}
else
if (hc->z1 == hc->z2)
{
hp->dz = -hp->dz;
}
else
{
hp->dx = -hp->dx;
hp->dz = -hp->dz;
}
MSG_add("Point collided.");
goto dont_move_this_point;
}
}
hp->x += hp->dx;
hp->y += hp->dy;
hp->z += hp->dz;
dont_move_this_point:;
}
//
// Can we get rid of any of the bumps?
//
prev = &ho->bump;
hb = ho->bump;
while(hb)
{
if (HM_bump_dead(ho, hb))
{
dead = hb;
//
// Take this bump out of the linked list.
//
*prev = hb->next;
hb = hb->next;
MemFree(dead);
}
else
{
//
// Go onto the next one.
//
prev = &hb->next;
hb = hb->next;
}
}
}
}
void HM_draw(void)
{
SLONG i;
SLONG j;
SLONG k;
SLONG x;
SLONG y;
SLONG z;
SLONG x1;
SLONG y1;
SLONG z1;
SLONG x2;
SLONG y2;
SLONG z2;
SLONG index;
SLONG nindex;
SLONG r;
SLONG g;
SLONG b;
float px[4];
float py[4];
float pz[4];
HM_Object *ho;
HM_Point *hp;
HM_Point *np;
PrimObject *po;
PrimFace4 *f4;
for (i = 0; i < HM_MAX_OBJECTS; i++)
{
ho = &HM_object[i];
if (!ho->used)
{
continue;
}
if (Keys[KB_5])
{
//
// Draw the actual mesh.
//
ASSERT(WITHIN(ho->prim, 1, next_prim_object - 1));
po = &prim_objects[ho->prim];
for (j = po->StartFace4; j < po->EndFace4; j++)
{
f4 = &prim_faces4[j];
for (k = 0; k < 4; k++)
{
HM_find_mesh_point(i, f4->Points[k] - po->StartPoint, &px[k], &py[k], &pz[k]);
}
e_draw_3d_line_col_sorted((SLONG) px[0], (SLONG) py[0], (SLONG) pz[0], (SLONG) px[1], (SLONG) py[1], (SLONG) pz[1], 255, 255, 255);
e_draw_3d_line_col_sorted((SLONG) px[1], (SLONG) py[1], (SLONG) pz[1], (SLONG) px[3], (SLONG) py[3], (SLONG) pz[3], 255, 255, 255);
e_draw_3d_line_col_sorted((SLONG) px[3], (SLONG) py[3], (SLONG) pz[3], (SLONG) px[2], (SLONG) py[2], (SLONG) pz[2], 255, 255, 255);
e_draw_3d_line_col_sorted((SLONG) px[2], (SLONG) py[2], (SLONG) pz[2], (SLONG) px[0], (SLONG) py[0], (SLONG) pz[0], 255, 255, 255);
}
}
index = 0;
for (z = 0; z < ho->z_res; z++)
{
for (y = 0; y < ho->y_res; y++)
{
for (x = 0; x < ho->x_res; x++)
{
if (ho->index[index])
{
ASSERT(WITHIN(ho->index[index], 1, ho->num_points - 1));
hp = &ho->point[ho->index[index]];
x1 = SLONG(hp->x - hp->dx * 0.5F);
y1 = SLONG(hp->y - hp->dy * 0.5F);
z1 = SLONG(hp->z - hp->dz * 0.5F);
if (z && (x == 0 || x == ho->x_res - 1 || y == 0 || y == ho->y_res - 1))
{
r = 32;
g = 32;
b = 32;
if (x == 0 || x == ho->x_res - 1) {r = 244 - x * 24;}
else
if (y == 0 || y == ho->y_res - 1) {g = 244 - y * 24;}
nindex = index - ho->x_res_times_y_res;
ASSERT(WITHIN(nindex, 0, ho->num_indices - 1));
if (ho->index[nindex])
{
ASSERT(WITHIN(ho->index[nindex], 1, ho->num_points - 1));
np = &ho->point[ho->index[nindex]];
x2 = SLONG(np->x - np->dx * 0.5F);
y2 = SLONG(np->y - np->dy * 0.5F);
z2 = SLONG(np->z - np->dz * 0.5F);
e_draw_3d_line_col_sorted(
x1, y1, z1,
x2, y2, z2,
r, g, b);
}
}
if (y && (x == 0 || x == ho->x_res - 1 || z == 0 || z == ho->y_res - 1))
{
r = 32;
g = 32;
b = 32;
if (x == 0 || x == ho->x_res - 1) {r = 244 - x * 24;}
else
if (z == 0 || z == ho->z_res - 1) {b = 244 - z * 24;}
nindex = index - ho->x_res;
ASSERT(WITHIN(nindex, 0, ho->num_indices - 1));
if (ho->index[nindex])
{
ASSERT(WITHIN(ho->index[nindex], 1, ho->num_points - 1));
np = &ho->point[ho->index[nindex]];
x2 = SLONG(np->x - np->dx * 0.5F);
y2 = SLONG(np->y - np->dy * 0.5F);
z2 = SLONG(np->z - np->dz * 0.5F);
e_draw_3d_line_col_sorted(
x1, y1, z1,
x2, y2, z2,
r, g, b);
}
}
if (x && (y == 0 || y == ho->x_res - 1 || z == 0 || z == ho->y_res - 1))
{
r = 32;
g = 32;
b = 32;
if (y == 0 || y == ho->y_res - 1) {g = 244 - y * 24;}
else
if (z == 0 || z == ho->z_res - 1) {b = 244 - z * 24;}
nindex = index - 1;
ASSERT(WITHIN(nindex, 0, ho->num_indices - 1));
if (ho->index[nindex])
{
ASSERT(WITHIN(ho->index[nindex], 1, ho->num_points - 1));
np = &ho->point[ho->index[nindex]];
x2 = SLONG(np->x - np->dx * 0.5F);
y2 = SLONG(np->y - np->dy * 0.5F);
z2 = SLONG(np->z - np->dz * 0.5F);
e_draw_3d_line_col_sorted(
x1, y1, z1,
x2, y2, z2,
r, g, b);
}
}
}
index++;
}
}
}
}
}
void HM_find_mesh_pos(
UBYTE hm_index,
SLONG *x,
SLONG *y,
SLONG *z,
SLONG *yaw,
SLONG *pitch,
SLONG *roll)
{
float len;
float overlen;
float matrix[9];
float ans_x;
float ans_y;
float ans_z;
ASSERT(WITHIN(hm_index, 0, HM_MAX_OBJECTS - 1));
HM_Object *ho = &HM_object[hm_index];
HM_Point *hp_o;
HM_Point *hp_x;
HM_Point *hp_y;
HM_Point *hp_z;
//
// The points we use...
//
ASSERT(WITHIN(ho->o_index, 1, ho->num_points - 1));
ASSERT(WITHIN(ho->x_index, 1, ho->num_points - 1));
ASSERT(WITHIN(ho->y_index, 1, ho->num_points - 1));
ASSERT(WITHIN(ho->z_index, 1, ho->num_points - 1));
hp_o = &ho->point[ho->o_index];
hp_x = &ho->point[ho->x_index];
hp_y = &ho->point[ho->y_index];
hp_z = &ho->point[ho->z_index];
//
// The rows of the matrix.
//
matrix[0] = hp_x->x - hp_o->x;
matrix[1] = hp_x->y - hp_o->y;
matrix[2] = hp_x->z - hp_o->z;
matrix[3] = hp_y->x - hp_o->x;
matrix[4] = hp_y->y - hp_o->y;
matrix[5] = hp_y->z - hp_o->z;
matrix[6] = hp_z->x - hp_o->x;
matrix[7] = hp_z->y - hp_o->y;
matrix[8] = hp_z->z - hp_o->z;
//
// Assume they are orthogonal for now!
//
len = matrix[0]*matrix[0] + matrix[1]*matrix[1] + matrix[2]*matrix[2];
len = sqrt(len);
overlen = 1.0F / len;
matrix[0] *= overlen;
matrix[1] *= overlen;
matrix[2] *= overlen;
len = matrix[3]*matrix[3] + matrix[4]*matrix[4] + matrix[5]*matrix[5];
len = sqrt(len);
overlen = 1.0F / len;
matrix[3] *= overlen;
matrix[4] *= overlen;
matrix[5] *= overlen;
len = matrix[6]*matrix[6] + matrix[7]*matrix[7] + matrix[8]*matrix[8];
len = sqrt(len);
overlen = 1.0F / len;
matrix[6] *= overlen;
matrix[7] *= overlen;
matrix[8] *= overlen;
//
// This matrix in terms of three angles.
//
Direction rot = MATRIX_find_angles(matrix);
rot.yaw *= 2048.0F / (2.0F * PI);
rot.pitch *= 2048.0F / (2.0F * PI);
rot.roll *= 2048.0F / (2.0F * PI);
*yaw = SLONG(rot.yaw);
*pitch = SLONG(rot.pitch);
*roll = SLONG(rot.roll);
//
// Unrotate the origin into prim space.
//
ans_x = ho->o_prim_x;
ans_y = ho->o_prim_y;
ans_z = ho->o_prim_z;
ans_x -= ho->cog_x;
ans_y -= ho->cog_y;
ans_z -= ho->cog_z;
MATRIX_MUL_BY_TRANSPOSE(
matrix,
ans_x,
ans_y,
ans_z);
ans_x += ho->cog_x;
ans_y += ho->cog_y;
ans_z += ho->cog_z;
*x = SLONG(hp_o->x - ans_x);
*y = SLONG(hp_o->y - ans_y);
*z = SLONG(hp_o->z - ans_z);
}
SLONG HM_stationary(UBYTE hm_index)
{
SLONG i;
float dx = 0;
float dy = 0;
float dz = 0;
ASSERT(WITHIN(hm_index, 0, HM_MAX_OBJECTS - 1));
HM_Object *ho = &HM_object[hm_index];
for (i = 1; i < ho->num_points; i++)
{
dx += fabs(ho->point[i].dx);
dy += fabs(ho->point[i].dy);
dz += fabs(ho->point[i].dz);
}
dx /= ho->num_points;
dy /= ho->num_points;
dz /= ho->num_points;
if (dx + dy + dz < 0.25F)
{
return TRUE;
}
else
{
return FALSE;
}
}
void HM_shockwave(
UBYTE hm_index,
float x,
float y,
float z,
float range,
float force)
{
ASSERT(WITHIN(hm_index, 0, HM_MAX_OBJECTS - 1));
HM_Object *ho = &HM_object[hm_index];
SLONG i;
float dx;
float dy;
float dz;
float dist;
float push;
for (i = 1; i < ho->num_points; i++)
{
dx = ho->point[i].x - x;
dy = ho->point[i].y - y;
dz = ho->point[i].z - z;
dist = sqrt(dx*dx + dy*dy + dz*dz);
if (dist < range)
{
push = ((range - dist) / range) * force / dist;
ho->point[i].dx += dx * push;
ho->point[i].dy += dy * push * 2.0F;
ho->point[i].dz += dz * push;
}
}
}
#endif //#ifndef TARGET_DC
| 18.161899
| 135
| 0.559858
|
inco1
|
eb2aba4d10ebc7da175320b8465097189bd773b9
| 3,122
|
cc
|
C++
|
src/whetstone/MFD3D_Electromagnetics_Surface.cc
|
fmyuan/amanzi
|
edb7b815ae6c22956c8519acb9d87b92a9915ed4
|
[
"RSA-MD"
] | 37
|
2017-04-26T16:27:07.000Z
|
2022-03-01T07:38:57.000Z
|
src/whetstone/MFD3D_Electromagnetics_Surface.cc
|
fmyuan/amanzi
|
edb7b815ae6c22956c8519acb9d87b92a9915ed4
|
[
"RSA-MD"
] | 494
|
2016-09-14T02:31:13.000Z
|
2022-03-13T18:57:05.000Z
|
src/whetstone/MFD3D_Electromagnetics_Surface.cc
|
fmyuan/amanzi
|
edb7b815ae6c22956c8519acb9d87b92a9915ed4
|
[
"RSA-MD"
] | 43
|
2016-09-26T17:58:40.000Z
|
2022-03-25T02:29:59.000Z
|
/*
WhetStone, Version 2.2
Release name: naka-to.
Copyright 2010-201x held jointly by LANS/LANL, LBNL, and PNNL.
Amanzi is released under the three-clause BSD License.
The terms of use and "as is" disclaimer for this license are
provided in the top-level COPYRIGHT file.
Author: Konstantin Lipnikov (lipnikov@lanl.gov)
The mimetic finite difference method.
*/
#include <cmath>
#include <vector>
#include "MeshLight.hh"
#include "Point.hh"
#include "errors.hh"
#include "DenseMatrix.hh"
#include "Tensor.hh"
#include "MFD3D_Electromagnetics.hh"
#include "MFD3D_Diffusion.hh"
namespace Amanzi {
namespace WhetStone {
/* ******************************************************************
* Consistency condition for the mass matrix in electromagnetics for
* face f of a 3D cell.
****************************************************************** */
int MFD3D_Electromagnetics::L2consistencyBoundary(
int f, const Tensor& T, DenseMatrix& N, DenseMatrix& Mc)
{
Entity_ID_List edges;
std::vector<int> dirs;
mesh_->face_get_edges_and_dirs(f, &edges, &dirs);
int nedges = edges.size();
N.Reshape(nedges, d_ - 1);
Mc.Reshape(nedges, nedges);
AmanziGeometry::Point v1(d_), v2(d_), v3(d_);
const AmanziGeometry::Point& normal = mesh_->face_normal(f);
const AmanziGeometry::Point& xf = mesh_->face_centroid(f);
double area = mesh_->face_area(f);
// calculate rotation matrix
Tensor P(d_, 2);
v3 = normal / area;
for (int i = 0; i < d_; i++) {
for (int j = 0; j < d_; j++) {
P(i, j) = v3[i] * v3[j];
}
}
P(0, 1) -= v3[2];
P(0, 2) += v3[1];
P(1, 0) += v3[2];
P(1, 2) -= v3[0];
P(2, 0) -= v3[1];
P(2, 1) += v3[0];
// define rotated tensor
Tensor PTP(d_, 2), Pt(P), Tinv(T);
Tinv.Inverse();
Pt.Transpose();
PTP = Pt * Tinv * P;
for (int i = 0; i < nedges; i++) {
int e = edges[i];
const AmanziGeometry::Point& xe = mesh_->edge_centroid(e);
double a1 = mesh_->edge_length(e);
v2 = PTP * (xe - xf);
for (int j = i; j < nedges; j++) {
e = edges[j];
const AmanziGeometry::Point& ye = mesh_->edge_centroid(e);
double a2 = mesh_->edge_length(e);
v1 = ye - xf;
Mc(i, j) = (v1 * v2) * (a1 * a2) / area;
}
}
// Rows of matrix N are normal vectors in the plane of face f.
v1 = mesh_->edge_vector(edges[0]) / mesh_->edge_length(edges[0]);
v2 = v3^v1;
for (int i = 0; i < nedges; i++) {
int e = edges[i];
const AmanziGeometry::Point& tau = mesh_->edge_vector(e);
double len = mesh_->edge_length(e);
N(i, 0) = -(tau * v2) * dirs[i] / len;
N(i, 1) = (tau * v1) * dirs[i] / len;
}
return 0;
}
/* ******************************************************************
* Matrix matrix for edge-based discretization.
****************************************************************** */
int MFD3D_Electromagnetics::MassMatrixBoundary(int f, const Tensor& T, DenseMatrix& M)
{
DenseMatrix N;
int ok = L2consistencyBoundary(f, T, N, M);
if (ok) return ok;
StabilityScalar_(N, M);
return 0;
}
} // namespace WhetStone
} // namespace Amanzi
| 24.976
| 86
| 0.566944
|
fmyuan
|
eb2d8fb96904ac2eff415b41e70bc36982e21c5b
| 2,589
|
cpp
|
C++
|
src/main.cpp
|
stop-pattern/cab-v202
|
4ed4334128dfbd9c0529691a968bc776a9b4d494
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
stop-pattern/cab-v202
|
4ed4334128dfbd9c0529691a968bc776a9b4d494
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
stop-pattern/cab-v202
|
4ed4334128dfbd9c0529691a968bc776a9b4d494
|
[
"MIT"
] | null | null | null |
#include <Arduino.h>
#include <vector>
#include "TR.BIDS.libs.h"
#include "data.h"
#include "define.h"
uint bidsVer = VERSION;
bool outputStatus = false;
std::vector<byte> latest = {};
BIDS bids = BIDS(&Serial);
cData storedData = cData();
void setup() {
Serial.begin(19200);
while (!Serial) delay(1);
#ifdef _DEBUG_
Serial.println("init..."); // debug
#endif // _DEBUG_
pinMode(IO0, INPUT);
pinMode(SW, INPUT);
pinMode(LED, OUTPUT);
pinMode(PWM1, OUTPUT);
ledcSetup(0, LEDC_BASE_FREQ, LEDC_TIMER_BIT);
ledcAttachPin(PWM1, 0);
pinMode(PWM2, OUTPUT);
ledcSetup(1, LEDC_BASE_FREQ, LEDC_TIMER_BIT);
ledcAttachPin(PWM2, 1);
pinMode(SER, OUTPUT);
pinMode(RCK, OUTPUT);
pinMode(SCK, OUTPUT);
pinMode(OE, OUTPUT);
pinMode(SCL, OUTPUT);
digitalWrite(OE, LOW);
digitalWrite(SCL, HIGH);
digitalWrite(LED, HIGH);
#ifdef _DEBUG_
Serial.println("set auto send"); // debug
#endif // _DEBUG_
bids.AddAutoSend('P', 100, signalChanged);
bids.AddAutoSend('P', 255, indicatorChanged);
bids.AddAutoSend('S', 2, bellChanged);
bids.AddAutoSend('D', 0, doorChanged);
#ifdef _DEBUG_
Serial.println("init finished"); // debug
#endif // _DEBUG_
}
void loop() {
bidsVer = bids.CmdSenderI("TRV202");
if (bidsVer >= 202) {
digitalWrite(LED, HIGH);
while (true) {
loop_v202();
}
} else {
digitalWrite(LED, LOW);
uint8_t cnt = 0;
while (true) {
loop_v100(cnt);
cnt++;
}
}
}
void loop_v100(uint8_t cnt) {
double Speed = bids.CmdSenderF("TRIE1");
pwmWRite(0, Speed);
double ORP = bids.CmdSenderF("TRIP135") / 10;
pwmWRite(0, ORP);
if (cnt >= 5) {
signalChanged(bids.CmdSenderF("TRIP00"), 0);
indicatorChanged(bids.CmdSenderF("TRIP255"), 0);
bellChanged(bids.CmdSenderF("TRIS2"), 0);
doorChanged(bids.CmdSenderF("TRID0"), 0);
cnt = 0;
}
if (outputStatus) {
std::vector<byte> indicator = {};
storedData.getArray(indicator);
if (indicator == latest) {
ShiftOut(indicator);
latest = indicator;
}
outputStatus = false;
}
}
void loop_v202() {
double Speed = bids.CmdSenderF("TRIE1");
pwmWRite(0, Speed);
double ORP = bids.CmdSenderF("TRIP135") / 10;
pwmWRite(0, ORP);
if (checkAS()) {
while (true)
; // assert
}
if (outputStatus) {
std::vector<byte> indicator = {};
storedData.getArray(indicator);
if (indicator == latest) {
ShiftOut(indicator);
latest = indicator;
}
outputStatus = false;
}
}
| 21.756303
| 52
| 0.614137
|
stop-pattern
|
eb32428b01e1bfaad8a254c0e6227adf2fd426b9
| 3,650
|
cpp
|
C++
|
cnf_dump/main.cpp
|
appu226/FactorGraph
|
26e4de8518874abf2696a167eaf3dbaede5930f8
|
[
"MIT"
] | null | null | null |
cnf_dump/main.cpp
|
appu226/FactorGraph
|
26e4de8518874abf2696a167eaf3dbaede5930f8
|
[
"MIT"
] | null | null | null |
cnf_dump/main.cpp
|
appu226/FactorGraph
|
26e4de8518874abf2696a167eaf3dbaede5930f8
|
[
"MIT"
] | null | null | null |
/*
Copyright 2019 Parakram Majumdar
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.
*/
// std includes
#include <iostream>
#include <string>
#include <memory>
// blif_solve_lib includes
#include <blif_solve_lib/log.h>
#include <blif_solve_lib/blif_factors.h>
#include <blif_solve_lib/cnf_dump.h>
// cnf_dump includes
#include "cnf_dump_clo.h"
namespace {
bdd_ptr_set bdd_cube_to_set(DdManager * manager, bdd_ptr cube)
{
bdd_ptr_set result;
auto one = bdd_one(manager);
cube = bdd_dup(cube);
while (cube != one)
{
bdd_ptr next = bdd_new_var_with_index(manager, bdd_get_lowest_index(manager, cube));
result.insert(next);
auto smaller_cube = bdd_cube_diff(manager, cube, next);
bdd_free(manager, cube);
cube = smaller_cube;
}
bdd_free(manager, one);
bdd_free(manager, cube);
return result;
}
} // end anonymous namespace
int main(int argc, char const * const * const argv)
{
try
{
auto clo = cnf_dump::CnfDumpClo::create(argc, argv);
blif_solve::setVerbosity(clo->verbosity);
// if --help flag is given, print help and exit
if (clo->help)
{
cnf_dump::CnfDumpClo::printHelpMessage();
return 0;
}
// parse blif bdds
blif_solve_log(INFO, "Parsing blif bdds");
DdManager *ddm = Cudd_Init(0, 0, 256, 262144, 0);
if (ddm == NULL)
throw std::runtime_error("Could not initialize DdManager.");
auto blif_factors = std::make_shared<blif_solve::BlifFactors> (clo->blif_file, clo->num_lo_vars_to_quantify, ddm);
blif_factors->createBdds();
// dump cnf
blif_solve_log(INFO, "Creating cnf files");
auto npv_vec = blif_factors->getNonPiVars();
auto factor_vec = blif_factors->getFactors();
bdd_ptr_set non_pi_vars(npv_vec->cbegin(), npv_vec->cend());
bdd_ptr_set factors(factor_vec->cbegin(), factor_vec->cend());
bdd_ptr_set pi_vars = bdd_cube_to_set(ddm, blif_factors->getPiVars());
blif_solve_log(INFO, "Dumping "
<< factors.size() << " factors on "
<< non_pi_vars.size() << " vars while quantifying "
<< pi_vars.size() << " vars");
blif_solve::dumpCnfForModelCounting(blif_factors->getDdManager(),
non_pi_vars,
factors,
bdd_ptr_set(),
clo->output_cnf_file);
for (auto pi_var: pi_vars)
bdd_free(ddm, pi_var);
blif_solve_log(INFO, "Done");
}
catch (const std::exception & e)
{
std::cerr << "ERROR: "
<< e.what()
<< std::endl;;
return 1;
}
return 0;
}
| 28.968254
| 116
| 0.669863
|
appu226
|
eb3b128ff15e84412969a96453b947e3bd7849a4
| 2,661
|
cpp
|
C++
|
hyperUI/source/3D/Object3DManager.cpp
|
sadcatsoft/hyperui
|
f26242a9034ad1e0abf54bd7691fe48809262f5b
|
[
"MIT"
] | 2
|
2019-05-17T16:16:21.000Z
|
2019-08-21T20:18:22.000Z
|
hyperUI/source/3D/Object3DManager.cpp
|
sadcatsoft/hyperui
|
f26242a9034ad1e0abf54bd7691fe48809262f5b
|
[
"MIT"
] | 1
|
2018-10-18T22:05:12.000Z
|
2018-10-18T22:05:12.000Z
|
hyperUI/source/3D/Object3DManager.cpp
|
sadcatsoft/hyperui
|
f26242a9034ad1e0abf54bd7691fe48809262f5b
|
[
"MIT"
] | null | null | null |
#include "stdafx.h"
namespace HyperUI
{
/********************************************************************************************/
Object3DManager::Object3DManager()
{
}
/********************************************************************************************/
Object3DManager::~Object3DManager()
{
clear();
}
/********************************************************************************************/
void Object3DManager::initFromCollection(ResourceCollection* pColl, Window* pEngine)
{
#ifndef ALLOW_3D
return;
#endif
if(!pColl)
return;
CachedObject3D* pObject;
string strFileName;
const char* pcsTypeName;
//bool bFlipU, bFlipV;
ResourceItem* pItem = NULL;
ResourceCollection::Iterator ci;
//ResourceItem* pItem = pColl->traverseBegin();
SVector3D svDefScale;
//while(pItem)
for(ci = pColl->itemsBegin(); !ci.isEnd(); ci++)
{
pItem = ci.getItem();
pObject = new CachedObject3D;
pcsTypeName = pItem->getStringProp(PropertyId);
/*
strFileName = pItem->getStringProp(PropertyAnimFilename);
bFlipU = pItem->getBoolProp(PropertyObj3dFlipU);
bFlipV = pItem->getBoolProp(PropertyObj3dFlipV);
if(pItem->doesPropertyExist(PropertyObj3dDefaultScale))
pItem->getAsVector3(PropertyObj3dDefaultScale, svDefScale);
else
svDefScale.set(1,1,1);
if(pObject->loadFromObjFile(strFileName.c_str(), pEngine, false, bFlipU, bFlipV, svDefScale) == false)
*/
if(pObject->loadFromItem(pItem, pEngine) == false)
{
// Kill it and forget about it.
_ASSERT(0);
delete pObject;
}
else
{
myObjects[pcsTypeName] = pObject;
}
//pItem = pColl->traverseNext();
}
}
/********************************************************************************************/
void Object3DManager::clear(void)
{
TStringObject3DMap::iterator mi;
for(mi = myObjects.begin(); mi != myObjects.end(); mi++)
{
delete mi->second;
}
myObjects.clear();
}
/********************************************************************************************/
CachedObject3D* Object3DManager::findObject(const char* pcsType)
{
TStringObject3DMap::iterator mi;
mi = myObjects.find(pcsType);
if(mi == myObjects.end())
return NULL;
else
return mi->second;
}
/********************************************************************************************/
void Object3DManager::onTimerTick(void)
{
TStringObject3DMap::iterator mi;
for(mi = myObjects.begin(); mi != myObjects.end(); mi++)
{
mi->second->onTimerTick();
}
}
/********************************************************************************************/
};
| 26.61
| 105
| 0.505825
|
sadcatsoft
|
eb3cf456ff9e3ad2fcf4a6d7562a04584d7b6901
| 6,512
|
cpp
|
C++
|
SOURCES/ui95/cfonts.cpp
|
IsraelyFlightSimulator/Negev-Storm
|
86de63e195577339f6e4a94198bedd31833a8be8
|
[
"Unlicense"
] | 1
|
2021-02-19T06:06:31.000Z
|
2021-02-19T06:06:31.000Z
|
src/ui95/cfonts.cpp
|
markbb1957/FFalconSource
|
07b12e2c41a93fa3a95b912a2433a8056de5bc4d
|
[
"BSD-2-Clause"
] | null | null | null |
src/ui95/cfonts.cpp
|
markbb1957/FFalconSource
|
07b12e2c41a93fa3a95b912a2433a8056de5bc4d
|
[
"BSD-2-Clause"
] | 2
|
2019-08-20T13:35:13.000Z
|
2021-04-24T07:32:04.000Z
|
#include <windows.h>
#include "chandler.h"
#ifdef _UI95_PARSER_ // List of Keywords & functions to handle them
enum
{
CFNT_NOTHING=0,
CFNT_ID,
CFNT_lfHeight,
CFNT_lfWidth,
CFNT_lfEscapement,
CFNT_lfOrientation,
CFNT_lfWeight,
CFNT_lfItalic,
CFNT_lfUnderline,
CFNT_lfStrikeOut,
CFNT_lfCharSet,
CFNT_lfOutPrecision,
CFNT_lfClipPrecision,
CFNT_lfQuality,
CFNT_lfPitchAndFamily,
CFNT_lfFaceName,
CFNT_SPACING,
CFNT_ADDFONT,
CFNT_FONT,
CFNT_LOAD
};
char *C_Fnt_Tokens[]=
{
"[NOTHING]",
"[ID]",
"[lfHeight]",
"[lfWidth]",
"[lfEscapement]",
"[lfOrientation]",
"[lfWeight]",
"[lfItalic]",
"[lfUnderline]",
"[lfStrikeOut]",
"[lfCharSet]",
"[lfOutPrecision]",
"[lfClipPrecision]",
"[lfQuality]",
"[lfPitchAndFamily]",
"[lfFaceName]",
"[SPACING]",
"[ADDFONT]",
"[FONT]", // nothing done here
"[LOADFONT]",
0,
};
#endif
C_Font *gFontList=NULL;
static LOGFONT DefaultFont=
{
16,
0,
0,
0,
FW_NORMAL,
FALSE,
FALSE,
FALSE,
ANSI_CHARSET,
OUT_DEFAULT_PRECIS,
CLIP_DEFAULT_PRECIS,
PROOF_QUALITY,
VARIABLE_PITCH | FF_SWISS,
"",
};
static void HashDelCB(void *me)
{
C_Fontmgr *fnt;
fnt=(C_Fontmgr*)me;
if(fnt)
{
fnt->Cleanup();
delete fnt;
}
}
C_Font::C_Font()
{
Root_=NULL;
Spacing_=0;
Fonts_=NULL;
}
C_Font::~C_Font()
{
if(Root_ || Fonts_)
Cleanup();
}
void C_Font::Setup(C_Handler *handler)
{
Handler_=handler;
Fonts_=new C_Hash;
Fonts_->Setup(5);
Fonts_->SetFlags(C_BIT_REMOVE);
Fonts_->SetCallback(HashDelCB);
}
void C_Font::Cleanup()
{
FONTLIST *cur,*last;
cur=Root_;
while(cur)
{
last=cur;
cur=cur->Next;
DeleteObject(last->Font_);
delete last->Widths_;
delete last;
}
Root_=NULL;
if(Fonts_)
{
Fonts_->Cleanup();
delete Fonts_;
Fonts_=NULL;
}
}
BOOL C_Font::AddFont(long ,LOGFONT *)
{
#if 0
FONTLIST *newfont,*cur;
HDC hdc;
newfont=new FONTLIST;
newfont->Spacing_=Spacing_;
newfont->Font_=CreateFontIndirect(reqs);
if(newfont->Font_ == NULL)
{
delete newfont;
return(FALSE);
}
memcpy(&newfont->logfont,reqs,sizeof(LOGFONT));
newfont->ID_=ID;
Handler_->GetDC(&hdc);
SelectObject(hdc,newfont->Font_);
GetTextMetrics(hdc,&newfont->Metrics_);
newfont->Widths_=new INT[newfont->Metrics_.tmLastChar+1];
if(!GetCharWidth(hdc,0,newfont->Metrics_.tmLastChar,&newfont->Widths_[0]))
{
VOID *lpMsgBuf;
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL,GetLastError(),MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),(LPTSTR) &lpMsgBuf,0,NULL );
// Display the string.
MessageBox( NULL, (char *)lpMsgBuf, "GetLastError", MB_OK|MB_ICONINFORMATION );
// Free the buffer.
LocalFree( lpMsgBuf );
}
Handler_->ReleaseDC(hdc);
newfont->Next=NULL;
if(Root_ == NULL)
{
Root_=newfont;
}
else
{
cur=Root_;
while(cur->Next)
cur=cur->Next;
cur->Next=newfont;
}
return(TRUE);
#endif
return(FALSE);
}
FONTLIST *C_Font::FindID(long ID)
{
FONTLIST *cur;
cur=Root_;
while(cur)
{
if(cur->ID_ == ID)
return(cur);
cur=cur->Next;
}
return(Root_);
}
HFONT C_Font::GetFont(long ID)
{
FONTLIST *cur;
cur=FindID(ID);
if(cur)
return(cur->Font_);
return(NULL);
}
int C_Font::GetHeight(long ID)
{
#if 0 // Replacing OLD code
FONTLIST *cur;
cur=FindID(ID);
if(cur)
return(cur->Metrics_.tmHeight);
#else // New method
C_Fontmgr *found;
found=Find(ID);
if(found)
return(found->Height());
found=Find(1);
if(found)
return(found->Height());
#endif
return(0);
}
C_Fontmgr *C_Font::Find(long ID)
{
C_Fontmgr *cur;
if(Fonts_)
{
cur=(C_Fontmgr*)Fonts_->Find(ID);
if(!cur)
cur=(C_Fontmgr*)Fonts_->Find(1);
return(cur);
}
return(NULL);
}
void C_Font::LoadFont(long ID,char *filename)
{
C_Fontmgr *newfont;
if(Fonts_->Find(ID)) // Check to see if ID used
return;
newfont=new C_Fontmgr;
newfont->Setup(ID,filename);
if(!newfont->Height())
{
delete newfont;
return;
}
Fonts_->Add(ID,newfont);
}
int C_Font::StrWidth(long fontID,_TCHAR *Str)
{
#if 0 // Removing OLD method
FONTLIST *cur;
int w=0,i;
_TCHAR c;
cur=FindID(fontID);
if(cur)
{
i=0;
while(Str[i])
{
c=Str[i];
if(c > cur->Metrics_.tmLastChar) c=0;
w+=cur->Widths_[c] + cur->Spacing_;
i++;
}
return(w+1);
}
return(0);
#else
C_Fontmgr *found;
found=Find(fontID);
if(found)
return(found->Width(Str));
return(0);
#endif
}
int C_Font::StrWidth(long fontID,_TCHAR *Str,int len)
{
#if 0 // Replacing OLD method
FONTLIST *cur;
int w=0,i;
_TCHAR c;
cur=FindID(fontID);
if(cur)
{
i=0;
while(Str[i] && i < len)
{
c=Str[i];
if(c > cur->Metrics_.tmLastChar) c=0;
w+=cur->Widths_[c]+cur->Spacing_;
i++;
}
return(w+1);
}
return(0);
#else // New method
C_Fontmgr *found;
found=Find(fontID);
if(found)
return(found->Width(Str,len));
return(0);
#endif
}
#ifdef _UI95_PARSER_
short C_Font::FontFind(char *token)
{
short i=0;
while(C_Fnt_Tokens[i])
{
if(strnicmp(token,C_Fnt_Tokens[i],strlen(C_Fnt_Tokens[i])) == 0)
return(i);
i++;
}
return(0);
}
void C_Font::FontFunction(short ID,long P[],_TCHAR *str,LOGFONT *lgfnt,long *NewID)
{
switch(ID)
{
case CFNT_ID:
*NewID=P[0];
break;
case CFNT_lfHeight:
if(lgfnt)
lgfnt->lfHeight|=P[0];
break;
case CFNT_lfWidth:
if(lgfnt)
lgfnt->lfWidth|=P[0];
break;
case CFNT_lfEscapement:
if(lgfnt)
lgfnt->lfEscapement|=P[0];
break;
case CFNT_lfOrientation:
if(lgfnt)
lgfnt->lfOrientation|=P[0];
break;
case CFNT_lfWeight:
if(lgfnt)
lgfnt->lfWeight|=P[0];
break;
case CFNT_lfItalic:
if(lgfnt)
lgfnt->lfItalic|=(BYTE)P[0];
break;
case CFNT_lfUnderline:
if(lgfnt)
lgfnt->lfUnderline|=(BYTE)P[0];
break;
case CFNT_lfStrikeOut:
if(lgfnt)
lgfnt->lfStrikeOut|=(BYTE)P[0];
break;
case CFNT_lfCharSet:
if(lgfnt)
lgfnt->lfCharSet|=(BYTE)P[0];
break;
case CFNT_lfOutPrecision:
if(lgfnt)
lgfnt->lfOutPrecision|=(BYTE)P[0];
break;
case CFNT_lfClipPrecision:
if(lgfnt)
lgfnt->lfClipPrecision|=(BYTE)P[0];
break;
case CFNT_lfQuality:
if(lgfnt)
lgfnt->lfQuality|=(BYTE)P[0];
break;
case CFNT_lfPitchAndFamily:
if(lgfnt)
lgfnt->lfPitchAndFamily|=(BYTE)P[0];
break;
case CFNT_lfFaceName:
if(lgfnt)
_tcsncpy(lgfnt->lfFaceName,str,LF_FACESIZE);
break;
case CFNT_SPACING:
Spacing_=P[0];
break;
case CFNT_ADDFONT:
AddFont(*NewID,lgfnt);
Spacing_=0;
memset(lgfnt,0,sizeof(LOGFONT));
break;
case CFNT_LOAD:
LoadFont(P[0],str);
break;
}
}
#endif
| 15.394799
| 97
| 0.658784
|
IsraelyFlightSimulator
|
eb3ea0b38355eaf36bb24a52ce48d1ed47b3ce4b
| 2,333
|
cpp
|
C++
|
core/src/storage/disk/DiskOperation.cpp
|
godchen0212/milvus
|
31306f660ec2eb4f459eadee856f2c1020240a53
|
[
"Apache-2.0"
] | 1
|
2020-08-10T18:28:59.000Z
|
2020-08-10T18:28:59.000Z
|
core/src/storage/disk/DiskOperation.cpp
|
godchen0212/milvus
|
31306f660ec2eb4f459eadee856f2c1020240a53
|
[
"Apache-2.0"
] | null | null | null |
core/src/storage/disk/DiskOperation.cpp
|
godchen0212/milvus
|
31306f660ec2eb4f459eadee856f2c1020240a53
|
[
"Apache-2.0"
] | null | null | null |
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include <boost/filesystem.hpp>
#include <fiu-local.h>
#include "storage/disk/DiskOperation.h"
#include "utils/Exception.h"
#include "utils/Log.h"
namespace milvus {
namespace storage {
DiskOperation::DiskOperation(const std::string& dir_path) : dir_path_(dir_path) {
}
void
DiskOperation::CreateDirectory() {
bool is_dir = boost::filesystem::is_directory(dir_path_);
fiu_do_on("DiskOperation.CreateDirectory.is_directory", is_dir = false);
if (!is_dir) {
/* create directories recursively */
auto ret = boost::filesystem::create_directories(dir_path_);
fiu_do_on("DiskOperation.CreateDirectory.create_directory", ret = false);
if (!ret) {
std::string err_msg = "Failed to create directory: " + dir_path_;
LOG_ENGINE_ERROR_ << err_msg;
throw Exception(SERVER_CANNOT_CREATE_FOLDER, err_msg);
}
}
}
const std::string&
DiskOperation::GetDirectory() const {
return dir_path_;
}
void
DiskOperation::ListDirectory(std::vector<std::string>& file_paths) {
boost::filesystem::path target_path(dir_path_);
typedef boost::filesystem::directory_iterator d_it;
d_it it_end;
d_it it(target_path);
if (boost::filesystem::is_directory(dir_path_)) {
for (; it != it_end; ++it) {
file_paths.emplace_back(it->path().c_str());
}
}
}
bool
DiskOperation::DeleteFile(const std::string& file_path) {
return boost::filesystem::remove(file_path);
}
} // namespace storage
} // namespace milvus
| 31.958904
| 81
| 0.707673
|
godchen0212
|
eb5118e3a93cae0fddab9094be206b7b97246662
| 11,005
|
cpp
|
C++
|
android-29/android/media/MediaCodec.cpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 12
|
2020-03-26T02:38:56.000Z
|
2022-03-14T08:17:26.000Z
|
android-29/android/media/MediaCodec.cpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 1
|
2021-01-27T06:07:45.000Z
|
2021-11-13T19:19:43.000Z
|
android-29/android/media/MediaCodec.cpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 3
|
2021-02-02T12:34:55.000Z
|
2022-03-08T07:45:57.000Z
|
#include "../../JArray.hpp"
#include "./AudioPresentation.hpp"
#include "./Image.hpp"
#include "./MediaCodec_BufferInfo.hpp"
#include "./MediaCodec_Callback.hpp"
#include "./MediaCodec_CryptoInfo.hpp"
#include "./MediaCodecInfo.hpp"
#include "./MediaCrypto.hpp"
#include "./MediaDescrambler.hpp"
#include "./MediaFormat.hpp"
#include "../os/Bundle.hpp"
#include "../os/Handler.hpp"
#include "../os/PersistableBundle.hpp"
#include "../view/Surface.hpp"
#include "../../JString.hpp"
#include "../../java/nio/ByteBuffer.hpp"
#include "./MediaCodec.hpp"
namespace android::media
{
// Fields
jint MediaCodec::BUFFER_FLAG_CODEC_CONFIG()
{
return getStaticField<jint>(
"android.media.MediaCodec",
"BUFFER_FLAG_CODEC_CONFIG"
);
}
jint MediaCodec::BUFFER_FLAG_END_OF_STREAM()
{
return getStaticField<jint>(
"android.media.MediaCodec",
"BUFFER_FLAG_END_OF_STREAM"
);
}
jint MediaCodec::BUFFER_FLAG_KEY_FRAME()
{
return getStaticField<jint>(
"android.media.MediaCodec",
"BUFFER_FLAG_KEY_FRAME"
);
}
jint MediaCodec::BUFFER_FLAG_PARTIAL_FRAME()
{
return getStaticField<jint>(
"android.media.MediaCodec",
"BUFFER_FLAG_PARTIAL_FRAME"
);
}
jint MediaCodec::BUFFER_FLAG_SYNC_FRAME()
{
return getStaticField<jint>(
"android.media.MediaCodec",
"BUFFER_FLAG_SYNC_FRAME"
);
}
jint MediaCodec::CONFIGURE_FLAG_ENCODE()
{
return getStaticField<jint>(
"android.media.MediaCodec",
"CONFIGURE_FLAG_ENCODE"
);
}
jint MediaCodec::CRYPTO_MODE_AES_CBC()
{
return getStaticField<jint>(
"android.media.MediaCodec",
"CRYPTO_MODE_AES_CBC"
);
}
jint MediaCodec::CRYPTO_MODE_AES_CTR()
{
return getStaticField<jint>(
"android.media.MediaCodec",
"CRYPTO_MODE_AES_CTR"
);
}
jint MediaCodec::CRYPTO_MODE_UNENCRYPTED()
{
return getStaticField<jint>(
"android.media.MediaCodec",
"CRYPTO_MODE_UNENCRYPTED"
);
}
jint MediaCodec::INFO_OUTPUT_BUFFERS_CHANGED()
{
return getStaticField<jint>(
"android.media.MediaCodec",
"INFO_OUTPUT_BUFFERS_CHANGED"
);
}
jint MediaCodec::INFO_OUTPUT_FORMAT_CHANGED()
{
return getStaticField<jint>(
"android.media.MediaCodec",
"INFO_OUTPUT_FORMAT_CHANGED"
);
}
jint MediaCodec::INFO_TRY_AGAIN_LATER()
{
return getStaticField<jint>(
"android.media.MediaCodec",
"INFO_TRY_AGAIN_LATER"
);
}
JString MediaCodec::PARAMETER_KEY_HDR10_PLUS_INFO()
{
return getStaticObjectField(
"android.media.MediaCodec",
"PARAMETER_KEY_HDR10_PLUS_INFO",
"Ljava/lang/String;"
);
}
JString MediaCodec::PARAMETER_KEY_OFFSET_TIME()
{
return getStaticObjectField(
"android.media.MediaCodec",
"PARAMETER_KEY_OFFSET_TIME",
"Ljava/lang/String;"
);
}
JString MediaCodec::PARAMETER_KEY_REQUEST_SYNC_FRAME()
{
return getStaticObjectField(
"android.media.MediaCodec",
"PARAMETER_KEY_REQUEST_SYNC_FRAME",
"Ljava/lang/String;"
);
}
JString MediaCodec::PARAMETER_KEY_SUSPEND()
{
return getStaticObjectField(
"android.media.MediaCodec",
"PARAMETER_KEY_SUSPEND",
"Ljava/lang/String;"
);
}
JString MediaCodec::PARAMETER_KEY_SUSPEND_TIME()
{
return getStaticObjectField(
"android.media.MediaCodec",
"PARAMETER_KEY_SUSPEND_TIME",
"Ljava/lang/String;"
);
}
JString MediaCodec::PARAMETER_KEY_VIDEO_BITRATE()
{
return getStaticObjectField(
"android.media.MediaCodec",
"PARAMETER_KEY_VIDEO_BITRATE",
"Ljava/lang/String;"
);
}
jint MediaCodec::VIDEO_SCALING_MODE_SCALE_TO_FIT()
{
return getStaticField<jint>(
"android.media.MediaCodec",
"VIDEO_SCALING_MODE_SCALE_TO_FIT"
);
}
jint MediaCodec::VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING()
{
return getStaticField<jint>(
"android.media.MediaCodec",
"VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING"
);
}
// QJniObject forward
MediaCodec::MediaCodec(QJniObject obj) : JObject(obj) {}
// Constructors
// Methods
android::media::MediaCodec MediaCodec::createByCodecName(JString arg0)
{
return callStaticObjectMethod(
"android.media.MediaCodec",
"createByCodecName",
"(Ljava/lang/String;)Landroid/media/MediaCodec;",
arg0.object<jstring>()
);
}
android::media::MediaCodec MediaCodec::createDecoderByType(JString arg0)
{
return callStaticObjectMethod(
"android.media.MediaCodec",
"createDecoderByType",
"(Ljava/lang/String;)Landroid/media/MediaCodec;",
arg0.object<jstring>()
);
}
android::media::MediaCodec MediaCodec::createEncoderByType(JString arg0)
{
return callStaticObjectMethod(
"android.media.MediaCodec",
"createEncoderByType",
"(Ljava/lang/String;)Landroid/media/MediaCodec;",
arg0.object<jstring>()
);
}
android::view::Surface MediaCodec::createPersistentInputSurface()
{
return callStaticObjectMethod(
"android.media.MediaCodec",
"createPersistentInputSurface",
"()Landroid/view/Surface;"
);
}
void MediaCodec::configure(android::media::MediaFormat arg0, android::view::Surface arg1, android::media::MediaCrypto arg2, jint arg3) const
{
callMethod<void>(
"configure",
"(Landroid/media/MediaFormat;Landroid/view/Surface;Landroid/media/MediaCrypto;I)V",
arg0.object(),
arg1.object(),
arg2.object(),
arg3
);
}
void MediaCodec::configure(android::media::MediaFormat arg0, android::view::Surface arg1, jint arg2, android::media::MediaDescrambler arg3) const
{
callMethod<void>(
"configure",
"(Landroid/media/MediaFormat;Landroid/view/Surface;ILandroid/media/MediaDescrambler;)V",
arg0.object(),
arg1.object(),
arg2,
arg3.object()
);
}
android::view::Surface MediaCodec::createInputSurface() const
{
return callObjectMethod(
"createInputSurface",
"()Landroid/view/Surface;"
);
}
jint MediaCodec::dequeueInputBuffer(jlong arg0) const
{
return callMethod<jint>(
"dequeueInputBuffer",
"(J)I",
arg0
);
}
jint MediaCodec::dequeueOutputBuffer(android::media::MediaCodec_BufferInfo arg0, jlong arg1) const
{
return callMethod<jint>(
"dequeueOutputBuffer",
"(Landroid/media/MediaCodec$BufferInfo;J)I",
arg0.object(),
arg1
);
}
void MediaCodec::flush() const
{
callMethod<void>(
"flush",
"()V"
);
}
JString MediaCodec::getCanonicalName() const
{
return callObjectMethod(
"getCanonicalName",
"()Ljava/lang/String;"
);
}
android::media::MediaCodecInfo MediaCodec::getCodecInfo() const
{
return callObjectMethod(
"getCodecInfo",
"()Landroid/media/MediaCodecInfo;"
);
}
java::nio::ByteBuffer MediaCodec::getInputBuffer(jint arg0) const
{
return callObjectMethod(
"getInputBuffer",
"(I)Ljava/nio/ByteBuffer;",
arg0
);
}
JArray MediaCodec::getInputBuffers() const
{
return callObjectMethod(
"getInputBuffers",
"()[Ljava/nio/ByteBuffer;"
);
}
android::media::MediaFormat MediaCodec::getInputFormat() const
{
return callObjectMethod(
"getInputFormat",
"()Landroid/media/MediaFormat;"
);
}
android::media::Image MediaCodec::getInputImage(jint arg0) const
{
return callObjectMethod(
"getInputImage",
"(I)Landroid/media/Image;",
arg0
);
}
android::os::PersistableBundle MediaCodec::getMetrics() const
{
return callObjectMethod(
"getMetrics",
"()Landroid/os/PersistableBundle;"
);
}
JString MediaCodec::getName() const
{
return callObjectMethod(
"getName",
"()Ljava/lang/String;"
);
}
java::nio::ByteBuffer MediaCodec::getOutputBuffer(jint arg0) const
{
return callObjectMethod(
"getOutputBuffer",
"(I)Ljava/nio/ByteBuffer;",
arg0
);
}
JArray MediaCodec::getOutputBuffers() const
{
return callObjectMethod(
"getOutputBuffers",
"()[Ljava/nio/ByteBuffer;"
);
}
android::media::MediaFormat MediaCodec::getOutputFormat() const
{
return callObjectMethod(
"getOutputFormat",
"()Landroid/media/MediaFormat;"
);
}
android::media::MediaFormat MediaCodec::getOutputFormat(jint arg0) const
{
return callObjectMethod(
"getOutputFormat",
"(I)Landroid/media/MediaFormat;",
arg0
);
}
android::media::Image MediaCodec::getOutputImage(jint arg0) const
{
return callObjectMethod(
"getOutputImage",
"(I)Landroid/media/Image;",
arg0
);
}
void MediaCodec::queueInputBuffer(jint arg0, jint arg1, jint arg2, jlong arg3, jint arg4) const
{
callMethod<void>(
"queueInputBuffer",
"(IIIJI)V",
arg0,
arg1,
arg2,
arg3,
arg4
);
}
void MediaCodec::queueSecureInputBuffer(jint arg0, jint arg1, android::media::MediaCodec_CryptoInfo arg2, jlong arg3, jint arg4) const
{
callMethod<void>(
"queueSecureInputBuffer",
"(IILandroid/media/MediaCodec$CryptoInfo;JI)V",
arg0,
arg1,
arg2.object(),
arg3,
arg4
);
}
void MediaCodec::release() const
{
callMethod<void>(
"release",
"()V"
);
}
void MediaCodec::releaseOutputBuffer(jint arg0, jboolean arg1) const
{
callMethod<void>(
"releaseOutputBuffer",
"(IZ)V",
arg0,
arg1
);
}
void MediaCodec::releaseOutputBuffer(jint arg0, jlong arg1) const
{
callMethod<void>(
"releaseOutputBuffer",
"(IJ)V",
arg0,
arg1
);
}
void MediaCodec::reset() const
{
callMethod<void>(
"reset",
"()V"
);
}
void MediaCodec::setAudioPresentation(android::media::AudioPresentation arg0) const
{
callMethod<void>(
"setAudioPresentation",
"(Landroid/media/AudioPresentation;)V",
arg0.object()
);
}
void MediaCodec::setCallback(android::media::MediaCodec_Callback arg0) const
{
callMethod<void>(
"setCallback",
"(Landroid/media/MediaCodec$Callback;)V",
arg0.object()
);
}
void MediaCodec::setCallback(android::media::MediaCodec_Callback arg0, android::os::Handler arg1) const
{
callMethod<void>(
"setCallback",
"(Landroid/media/MediaCodec$Callback;Landroid/os/Handler;)V",
arg0.object(),
arg1.object()
);
}
void MediaCodec::setInputSurface(android::view::Surface arg0) const
{
callMethod<void>(
"setInputSurface",
"(Landroid/view/Surface;)V",
arg0.object()
);
}
void MediaCodec::setOnFrameRenderedListener(JObject arg0, android::os::Handler arg1) const
{
callMethod<void>(
"setOnFrameRenderedListener",
"(Landroid/media/MediaCodec$OnFrameRenderedListener;Landroid/os/Handler;)V",
arg0.object(),
arg1.object()
);
}
void MediaCodec::setOutputSurface(android::view::Surface arg0) const
{
callMethod<void>(
"setOutputSurface",
"(Landroid/view/Surface;)V",
arg0.object()
);
}
void MediaCodec::setParameters(android::os::Bundle arg0) const
{
callMethod<void>(
"setParameters",
"(Landroid/os/Bundle;)V",
arg0.object()
);
}
void MediaCodec::setVideoScalingMode(jint arg0) const
{
callMethod<void>(
"setVideoScalingMode",
"(I)V",
arg0
);
}
void MediaCodec::signalEndOfInputStream() const
{
callMethod<void>(
"signalEndOfInputStream",
"()V"
);
}
void MediaCodec::start() const
{
callMethod<void>(
"start",
"()V"
);
}
void MediaCodec::stop() const
{
callMethod<void>(
"stop",
"()V"
);
}
} // namespace android::media
| 21.835317
| 146
| 0.70159
|
YJBeetle
|
eb551b93cb9bc7f79861a5da0272e6991347cc91
| 697
|
cc
|
C++
|
src/analyzer/protocol/ftp/Plugin.cc
|
yaplej/bro
|
1e60264548fd3bde5222c027de21c482b009ccb1
|
[
"Apache-2.0"
] | 2,181
|
2015-01-01T15:31:58.000Z
|
2022-03-08T22:15:19.000Z
|
src/analyzer/protocol/ftp/Plugin.cc
|
yaplej/bro
|
1e60264548fd3bde5222c027de21c482b009ccb1
|
[
"Apache-2.0"
] | 1,277
|
2018-12-07T17:12:15.000Z
|
2022-03-31T22:56:35.000Z
|
src/analyzer/protocol/ftp/Plugin.cc
|
yaplej/bro
|
1e60264548fd3bde5222c027de21c482b009ccb1
|
[
"Apache-2.0"
] | 696
|
2015-01-01T20:29:40.000Z
|
2022-02-06T17:39:01.000Z
|
// See the file in the main distribution directory for copyright.
#include "zeek/plugin/Plugin.h"
#include "zeek/analyzer/Component.h"
#include "zeek/analyzer/protocol/ftp/FTP.h"
namespace zeek::plugin::detail::Zeek_FTP
{
class Plugin : public zeek::plugin::Plugin
{
public:
zeek::plugin::Configuration Configure() override
{
AddComponent(
new zeek::analyzer::Component("FTP", zeek::analyzer::ftp::FTP_Analyzer::Instantiate));
AddComponent(new zeek::analyzer::Component("FTP_ADAT", nullptr));
zeek::plugin::Configuration config;
config.name = "Zeek::FTP";
config.description = "FTP analyzer";
return config;
}
} plugin;
} // namespace zeek::plugin::detail::Zeek_FTP
| 24.892857
| 89
| 0.723099
|
yaplej
|
eb56f2ebf8ab8c43007882bfe5e9f59b43c3b38d
| 11,005
|
cpp
|
C++
|
cpp/src/VideoOverlayDemo.cpp
|
npahucki/RealTimePoseEsitmationDancingGame
|
45fa716d9c156187ceedff458efa2fa4c3e3c9de
|
[
"MIT"
] | 4
|
2019-05-08T03:53:14.000Z
|
2021-10-10T13:15:44.000Z
|
cpp/src/VideoOverlayDemo.cpp
|
chunyang-zhang/RealTimePoseEsitmationDancingGame
|
45fa716d9c156187ceedff458efa2fa4c3e3c9de
|
[
"MIT"
] | 1
|
2019-05-10T13:41:23.000Z
|
2019-05-15T10:19:14.000Z
|
cpp/src/VideoOverlayDemo.cpp
|
chunyang-zhang/RealTimePoseEsitmationDancingGame
|
45fa716d9c156187ceedff458efa2fa4c3e3c9de
|
[
"MIT"
] | 1
|
2019-05-08T03:32:54.000Z
|
2019-05-08T03:32:54.000Z
|
//
// Created by Nathan Pahucki on 10/11/18.
//
#include <iostream>
#include "VideoOverlayDemo.h"
#include "UpperBodyRaisedHandPredictor.h"
#include "extract_utils.h"
#include <openpose/tracking/headers.hpp>
#include <VideoOverlayDemo.h>
VideoOverlayDemo::VideoOverlayDemo(const string &windowName_) : VideoPoseCapture(windowName_) {}
VideoOverlayDemo::~VideoOverlayDemo() {
delete personIdentifier_;
delete scoreTracker_;
delete storage_;
delete frameKeypoints_;
delete themeManager_;
}
cv::Mat VideoOverlayDemo::getRenderBaseImage(const cv::Mat &inputImage) {
return themeManager_->getBackgroundImage(currentBackgroundIdx_);
}
void VideoOverlayDemo::handleKeyPress(int key) {
if (key == 's') {
if (smoothingWeight_ != 0) enableSmoothing_ = !enableSmoothing_;
std::cout << "Smoothing enabled: " << (enableSmoothing_ ? "YES" : "NO") << std::endl;
}
}
bool VideoOverlayDemo::processKeypoints(const op::Array<float> &originalKeypoints, const cv::Mat &inputImage,
cv::Mat &outputImage) {
// Make sure to write to the DB periodically to ensure that in the event of a crash we don't lose the data.
if (getFramesProcessed() % (30/* assumed fps*/ * 60/*secs*/ * 1/*mins*/) == 0) {
currentBackgroundIdx_ = themeManager_->getNextBackgroundNumber();
storage_->flush();
}
if (getFramesProcessed() % (30/* assumed fps*/ * 10/*secs*/) == 0) {
updateLeaderBoard();
}
// Include the FPS on the image
std::stringstream fpsText;
fpsText << std::setprecision(4) << getFps() << " fps";
cv::putText(outputImage, fpsText.str(), cv::Point(10, 30), cv::FONT_HERSHEY_PLAIN, 1.5F, cv::Scalar(255, 255, 255));
const int numPersons = frameKeypoints_->getNumPersonsInCurrentFrame();
const auto personIds = this->personIdentifier_->identifyPersons(*frameKeypoints_, inputImage);
for (int personIdx = 0; personIdx < numPersons; personIdx++) {
try {
const auto personId = personIds[personIdx];
const auto personInfo = storage_->lookupPerson(personId);
const auto nose = frameKeypoints_->getBodyPartPoint(personIdx, 0);
const auto neck = frameKeypoints_->getBodyPartPoint(personIdx, 1);
const auto leftEye = frameKeypoints_->getBodyPartPoint(personIdx, 16);
const auto rightEye = frameKeypoints_->getBodyPartPoint(personIdx, 15);
if (nose.x == 0 || neck.x == 0) continue;
cv::Mat &headImage = themeManager_->getHeadImage(personInfo.head);
cv::Mat imageToOverlay;
// First scale it correctly
// This is a fairly reliable metric that we can use for scaling
const auto neckToNoseDist = frameKeypoints_->getDistanceBetweenParts(personIdx, 0, 1);
// TODO: This depend on how much padding there is around the image
// TODO: WE should define some standard for the padding on the head images.
const double scale = (neckToNoseDist / headImage.cols) * 2.0;
cv::resize(headImage, imageToOverlay, cv::Size(), scale, scale);
if (rightEye.x > 0 && leftEye.x > 0) {
const double angle = atan2(leftEye.y - rightEye.y, leftEye.x - rightEye.x);
const auto degrees = static_cast<float>(angle * -180 / M_PI);
const auto center = cv::Point{imageToOverlay.cols / 2, imageToOverlay.rows / 2};
auto m = cv::getRotationMatrix2D(center, degrees, 1.0);
auto longestEdge = max(imageToOverlay.cols,
imageToOverlay.rows); // TODO: figure out how to not cut off edges when rotated
// NOTE: Trying to do a rotate and scale at the same time with warpAffine does not seem to work,
// the image_ is drawn with the 0,0 coordinates off the canvas
cv::warpAffine(imageToOverlay, imageToOverlay, m, cv::Size{longestEdge, longestEdge});
}
const auto imageToOverlayCenter = cv::Point{imageToOverlay.cols / 2, imageToOverlay.rows / 2};
overlayImage(outputImage, imageToOverlay, outputImage, nose - imageToOverlayCenter);
//////////////////// Score and name stuff /////////////////////
std::string displayText = "-----";
if (!personId.empty()) {
// Render score
const int score = scoreTracker_->computeNewScoreForPerson(*frameKeypoints_, personIdx, personId);
displayText = "00000";
std::ostringstream ss;
ss << personInfo.name << " - " << std::setw(5) << std::setfill('0') << score << " pts";
displayText = ss.str();
// Update leader board in realtime
for(auto &line: leaderStats_) {
if(line.first == personInfo.name) {
line.second = std::to_string(score);
break;
}
}
}
const int fontFace = cv::FONT_HERSHEY_PLAIN;
const double fontScale = 1.25;
const int thickness = 2;
int baseline = 0;
const auto textSize = cv::getTextSize(displayText, fontFace, fontScale, thickness, &baseline);
baseline += thickness;
const cv::Point textOrg(nose.x - textSize.width / 2, std::max(0, nose.y - imageToOverlay.rows / 2));
cv::putText(outputImage, displayText, textOrg, fontFace, fontScale, cv::Scalar(0, 255, 0), thickness);
} catch (const std::exception &e) {
std::cerr << "Exception processing person " << personIdx << ". Error:" << e.what();
continue;
}
}
// //////////////// Leader board ///////////////////
int totalWidth = 0, totalHeight = 0;
const int fontFace = cv::FONT_HERSHEY_PLAIN;
const double fontScale = 1.0;
const int thickness = 1;
const int padding = 3;
for(auto line: leaderStats_) {
int baseline = 0;
const auto nameSize = cv::getTextSize(line.first, fontFace, fontScale, thickness, &baseline);
const auto scoreSize = cv::getTextSize(line.second, fontFace, fontScale, thickness, &baseline);
totalWidth = std::max(totalWidth, nameSize.width + scoreSize.width + 4*padding);
totalHeight += std::max(nameSize.height, scoreSize.height) + 2*padding;
}
// Now that we kow the full width and height, we can actually draw
if(totalWidth < 200) totalWidth = 300;
if(totalHeight < 200) totalHeight = 200;
const auto boardRect = cv::Rect(outputImage.cols - (totalWidth + 10), 10, totalWidth, totalHeight + padding*4);
cv::GaussianBlur(outputImage(boardRect), outputImage(boardRect), cv::Size(0, 0), 4);
cv::rectangle(outputImage,boardRect,cv::Scalar(0, 255, 0),1);
// Write the names
int textYPosition = boardRect.y + padding;
for(auto line: leaderStats_) {
int baseline = 0;
const auto nameSize = cv::getTextSize(line.first, fontFace, fontScale, thickness, &baseline);
const auto scoreSize = cv::getTextSize(line.second, fontFace, fontScale, thickness, &baseline);
textYPosition += std::max(nameSize.height, scoreSize.height) + padding*2;
const cv::Point nameOrg(boardRect.x + padding , textYPosition);
const cv::Point scoreOrg(boardRect.x + boardRect.width - (scoreSize.width + padding), textYPosition);
cv::putText(outputImage, line.first, nameOrg, fontFace, fontScale, cv::Scalar(0, 255, 0), thickness);
cv::putText(outputImage, line.second, scoreOrg, fontFace, fontScale, cv::Scalar(0, 255, 0), thickness);
}
return true;
}
void VideoOverlayDemo::updateLeaderBoard() {
typedef PersonStorage::PersonData pd;
std::vector<pd> players;
leaderStats_.clear();
for (auto tuple : *(storage_->getMap())) {
players.push_back(tuple.second);
}
std::sort(std::begin(players), std::end(players), [](pd &a, pd &b) { return a.score > b.score; });
const size_t max = 10;
auto end = std::next(players.begin(), std::min(max, players.size()));
for(auto it = players.begin(); it != end; it++) {
leaderStats_.emplace_back((*it).name,std::to_string((*it).score));
}
}
void VideoOverlayDemo::renderPose(op::PoseRenderer *renderer, const op::Array<float> &poseKeypoints,
double scaleInputToOutput, op::Array<float> &outputArray) {
frameKeypoints_->update(poseKeypoints, enableSmoothing_ ? smoothingWeight_ : 0);
renderer->renderPose(outputArray, filterKeypointsToRender(frameKeypoints_->getCurrentFrameKeypoints()),
scaleInputToOutput);
// This creates a 'thicker' effect
if (renderLastNFrames_) {
int idx = (int) frameKeypoints_->getLastNFrames().size();
for (const auto &pastPoseKeypoints: frameKeypoints_->getLastNFrames()) {
if (isUseGpuRendering()) {
((op::PoseGpuRenderer *) renderer)->setAlphaKeypoint(1.0F / (1.5F * idx--));
}
renderer->renderPose(outputArray, filterKeypointsToRender(pastPoseKeypoints), scaleInputToOutput);
}
}
}
op::Array<float> VideoOverlayDemo::filterKeypointsToRender(const op::Array<float> &keypoints) {
const auto numPersons = keypoints.getSize(0);
auto filtered = keypoints.clone();
for (int i = 0; i < numPersons; i++) {
filtered[{i, 15, 2}] = 0;
filtered[{i, 16, 2}] = 0;
filtered[{i, 17, 2}] = 0;
filtered[{i, 18, 2}] = 0;
//filtered[{i,0,2}] = 0;
}
return filtered;
}
void VideoOverlayDemo::start() {
// Should not have been initialized already
assert(this->themeManager_ == nullptr);
UpperBodyRaisedHandPredictor predictor{getModelFolder()};
// This is all cleaned up in destructor
themeManager_ = new ThemeManager(themeName_, cv::Size{getOutputSize().x, getOutputSize().y});
frameKeypoints_ = new FrameKeypoints(max(1, renderLastNFrames_));
storage_ = new PersonStorage(dbFolderPath_ + themeName_ + "_persons.bdb");
scoreTracker_ = new ScoreTracker(&predictor, storage_);
personIdentifier_ = new PersonIdentifier(getModelFolder(), storage_, themeManager_, faceIdFrameInterval_);
enableSmoothing_ = smoothingWeight_ > 0;
VideoPoseCapture::start();
}
void VideoOverlayDemo::setFaceIdFrameInterval(int faceIdFrameInterval) {
faceIdFrameInterval_ = faceIdFrameInterval;
}
void VideoOverlayDemo::setThemeName(std::string themeName) {
themeName_ = themeName;
}
void VideoOverlayDemo::setSmoothingWeight(float smoothingWeight) {
smoothingWeight_ = smoothingWeight;
}
void VideoOverlayDemo::setRenderLastNFrames(int renderLastNFrames) {
VideoOverlayDemo::renderLastNFrames_ = renderLastNFrames;
}
void VideoOverlayDemo::setDbFilePath(const string &dbFilePath) {
dbFolderPath_ = dbFilePath;
}
| 42.821012
| 120
| 0.636165
|
npahucki
|
eb5705a8161d1088d6901950521f685c6dd2823b
| 336
|
cpp
|
C++
|
1d/sim_error_floord/openacc/main.reference.cpp
|
realincubus/clang_plugin_tests
|
018e22f37baaa7c072de8d455ad16057c953fd96
|
[
"MIT"
] | null | null | null |
1d/sim_error_floord/openacc/main.reference.cpp
|
realincubus/clang_plugin_tests
|
018e22f37baaa7c072de8d455ad16057c953fd96
|
[
"MIT"
] | null | null | null |
1d/sim_error_floord/openacc/main.reference.cpp
|
realincubus/clang_plugin_tests
|
018e22f37baaa7c072de8d455ad16057c953fd96
|
[
"MIT"
] | null | null | null |
#include <cmath>
int main(int argc, char** argv){
int dp = 10;
int other = 10;
int x[10];
if (dp >= 2){
for (auto t1=0;t1<=std::floor( (double)(dp-2) /2);++t1) {
int sum = 0;
#pragma acc kernels
for (auto t3=0;t3<=other-1;++t3) {
sum += t3*3;
}
x[t1] = sum;
}
}
return 0;
}
| 16
| 59
| 0.464286
|
realincubus
|
eb612af1ea7fe2800994258a408496099c81b5a7
| 23,862
|
cc
|
C++
|
src/upr-consumer.cc
|
mikewied/ep-engine
|
c8302b874a6d5b705ff2888e9f84dd922dc0dd8a
|
[
"Apache-2.0"
] | null | null | null |
src/upr-consumer.cc
|
mikewied/ep-engine
|
c8302b874a6d5b705ff2888e9f84dd922dc0dd8a
|
[
"Apache-2.0"
] | null | null | null |
src/upr-consumer.cc
|
mikewied/ep-engine
|
c8302b874a6d5b705ff2888e9f84dd922dc0dd8a
|
[
"Apache-2.0"
] | null | null | null |
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2013 Couchbase, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "config.h"
#include "ep_engine.h"
#include "failover-table.h"
#include "tapconnmap.h"
#include "tapthrottle.h"
#include "upr-consumer.h"
#include "upr-response.h"
#include "upr-stream.h"
class Processer : public GlobalTask {
public:
Processer(EventuallyPersistentEngine* e, connection_t c,
const Priority &p, double sleeptime = 1, bool shutdown = false)
: GlobalTask(e, p, sleeptime, shutdown), conn(c) {}
bool run();
std::string getDescription();
private:
connection_t conn;
};
bool Processer::run() {
UprConsumer* consumer = static_cast<UprConsumer*>(conn.get());
if (consumer->doDisconnect()) {
return false;
}
switch (consumer->processBufferedItems()) {
case all_processed:
snooze(1);
break;
case more_to_process:
snooze(0);
break;
case cannot_process:
snooze(5);
break;
default:
abort();
}
return true;
}
std::string Processer::getDescription() {
std::stringstream ss;
ss << "Processing buffered items for " << conn->getName();
return ss.str();
}
UprConsumer::UprConsumer(EventuallyPersistentEngine &engine, const void *cookie,
const std::string &name)
: Consumer(engine, cookie, name), opaqueCounter(0), processTaskId(0),
itemsToProcess(false) {
Configuration& config = engine.getConfiguration();
streams = new passive_stream_t[config.getMaxVbuckets()];
setSupportAck(false);
setLogHeader("UPR (Consumer) " + getName() + " -");
setReserved(true);
flowControl.enabled = config.isUprEnableFlowControl();
flowControl.bufferSize = config.getUprConnBufferSize();
flowControl.maxUnackedBytes = config.getUprMaxUnackedBytes();
ExTask task = new Processer(&engine, this, Priority::PendingOpsPriority, 1);
processTaskId = ExecutorPool::get()->schedule(task, NONIO_TASK_IDX);
}
UprConsumer::~UprConsumer() {
delete[] streams;
}
ENGINE_ERROR_CODE UprConsumer::addStream(uint32_t opaque, uint16_t vbucket,
uint32_t flags) {
LockHolder lh(streamMutex);
if (doDisconnect()) {
return ENGINE_DISCONNECT;
}
RCPtr<VBucket> vb = engine_.getVBucket(vbucket);
if (!vb) {
LOG(EXTENSION_LOG_WARNING, "%s (vb %d) Add stream failed because this "
"vbucket doesn't exist", logHeader(), vbucket);
return ENGINE_NOT_MY_VBUCKET;
}
failover_entry_t entry = vb->failovers->getLatestEntry();
uint64_t start_seqno = vb->getHighSeqno();
uint64_t end_seqno = std::numeric_limits<uint64_t>::max();
uint64_t vbucket_uuid = entry.vb_uuid;
uint64_t snap_start_seqno = start_seqno;
uint64_t snap_end_seqno = start_seqno;
uint32_t new_opaque = ++opaqueCounter;
passive_stream_t &stream = streams[vbucket];
if (stream && stream->isActive()) {
LOG(EXTENSION_LOG_WARNING, "%s (vb %d) Cannot add stream because one "
"already exists", logHeader(), vbucket);
return ENGINE_KEY_EEXISTS;
}
streams[vbucket] = new PassiveStream(&engine_, this, getName(), flags,
new_opaque, vbucket, start_seqno,
end_seqno, vbucket_uuid,
snap_start_seqno, snap_end_seqno);
ready.push_back(vbucket);
opaqueMap_[new_opaque] = std::make_pair(opaque, vbucket);
return ENGINE_SUCCESS;
}
ENGINE_ERROR_CODE UprConsumer::closeStream(uint32_t opaque, uint16_t vbucket) {
LockHolder lh(streamMutex);
if (doDisconnect()) {
return ENGINE_DISCONNECT;
}
opaque_map::iterator oitr = opaqueMap_.find(opaque);
if (oitr != opaqueMap_.end()) {
opaqueMap_.erase(oitr);
}
passive_stream_t &stream = streams[vbucket];
if (!stream) {
LOG(EXTENSION_LOG_WARNING, "%s (vb %d) Cannot close stream because no "
"stream exists for this vbucket", logHeader(), vbucket);
return ENGINE_KEY_ENOENT;
}
uint32_t bytesCleared = stream->setDead(END_STREAM_CLOSED);
flowControl.freedBytes.fetch_add(bytesCleared);
return ENGINE_SUCCESS;
}
ENGINE_ERROR_CODE UprConsumer::streamEnd(uint32_t opaque, uint16_t vbucket,
uint32_t flags) {
if (doDisconnect()) {
return ENGINE_DISCONNECT;
}
ENGINE_ERROR_CODE err = ENGINE_KEY_ENOENT;
passive_stream_t stream = streams[vbucket];
if (stream && stream->getOpaque() == opaque && stream->isActive()) {
LOG(EXTENSION_LOG_INFO, "%s (vb %d) End stream received with reason %d",
logHeader(), vbucket, flags);
StreamEndResponse* response = new StreamEndResponse(opaque, flags,
vbucket);
err = stream->messageReceived(response);
bool disable = false;
if (err == ENGINE_SUCCESS &&
itemsToProcess.compare_exchange_strong(disable, true)) {
ExecutorPool::get()->wake(processTaskId);
}
}
if (err != ENGINE_SUCCESS) {
LOG(EXTENSION_LOG_WARNING, "%s (vb %d) End stream received with opaque "
"%d but does not exist", logHeader(), vbucket, opaque);
flowControl.freedBytes.fetch_add(StreamEndResponse::baseMsgBytes);
}
return err;
}
ENGINE_ERROR_CODE UprConsumer::mutation(uint32_t opaque, const void* key,
uint16_t nkey, const void* value,
uint32_t nvalue, uint64_t cas,
uint16_t vbucket, uint32_t flags,
uint8_t datatype, uint32_t locktime,
uint64_t bySeqno, uint64_t revSeqno,
uint32_t exptime, uint8_t nru,
const void* meta, uint16_t nmeta) {
if (doDisconnect()) {
return ENGINE_DISCONNECT;
}
ENGINE_ERROR_CODE err = ENGINE_KEY_ENOENT;
passive_stream_t stream = streams[vbucket];
if (stream && stream->getOpaque() == opaque && stream->isActive()) {
std::string key_str(static_cast<const char*>(key), nkey);
value_t vblob(Blob::New(static_cast<const char*>(value), nvalue,
&(datatype), (uint8_t) EXT_META_LEN));
Item *item = new Item(key_str, flags, exptime, vblob, cas, bySeqno,
vbucket, revSeqno);
MutationResponse* response = new MutationResponse(item, opaque);
err = stream->messageReceived(response);
bool disable = false;
if (err == ENGINE_SUCCESS &&
itemsToProcess.compare_exchange_strong(disable, true)) {
ExecutorPool::get()->wake(processTaskId);
}
}
if (err != ENGINE_SUCCESS) {
uint32_t bytes =
MutationResponse::mutationBaseMsgBytes + nkey + nmeta + nvalue;
flowControl.freedBytes.fetch_add(bytes);
}
return err;
}
ENGINE_ERROR_CODE UprConsumer::deletion(uint32_t opaque, const void* key,
uint16_t nkey, uint64_t cas,
uint16_t vbucket, uint64_t bySeqno,
uint64_t revSeqno, const void* meta,
uint16_t nmeta) {
if (doDisconnect()) {
return ENGINE_DISCONNECT;
}
ENGINE_ERROR_CODE err = ENGINE_KEY_ENOENT;
passive_stream_t stream = streams[vbucket];
if (stream && stream->getOpaque() == opaque && stream->isActive()) {
Item* item = new Item(key, nkey, 0, 0, NULL, 0, NULL, 0, cas, bySeqno,
vbucket, revSeqno);
item->setDeleted();
MutationResponse* response = new MutationResponse(item, opaque);
err = stream->messageReceived(response);
bool disable = false;
if (err == ENGINE_SUCCESS &&
itemsToProcess.compare_exchange_strong(disable, true)) {
ExecutorPool::get()->wake(processTaskId);
}
}
if (err != ENGINE_SUCCESS) {
uint32_t bytes = MutationResponse::deletionBaseMsgBytes + nkey + nmeta;
flowControl.freedBytes.fetch_add(bytes);
}
return err;
}
ENGINE_ERROR_CODE UprConsumer::expiration(uint32_t opaque, const void* key,
uint16_t nkey, uint64_t cas,
uint16_t vbucket, uint64_t bySeqno,
uint64_t revSeqno, const void* meta,
uint16_t nmeta) {
if (doDisconnect()) {
return ENGINE_DISCONNECT;
}
return ENGINE_ENOTSUP;
}
ENGINE_ERROR_CODE UprConsumer::snapshotMarker(uint32_t opaque,
uint16_t vbucket,
uint64_t start_seqno,
uint64_t end_seqno,
uint32_t flags) {
if (doDisconnect()) {
return ENGINE_DISCONNECT;
}
ENGINE_ERROR_CODE err = ENGINE_KEY_ENOENT;
passive_stream_t stream = streams[vbucket];
if (stream && stream->getOpaque() == opaque && stream->isActive()) {
SnapshotMarker* response = new SnapshotMarker(opaque, vbucket,
start_seqno, end_seqno,
flags);
err = stream->messageReceived(response);
bool disable = false;
if (err == ENGINE_SUCCESS &&
itemsToProcess.compare_exchange_strong(disable, true)) {
ExecutorPool::get()->wake(processTaskId);
}
}
if (err != ENGINE_SUCCESS) {
flowControl.freedBytes.fetch_add(SnapshotMarker::baseMsgBytes);
}
return err;
}
ENGINE_ERROR_CODE UprConsumer::flush(uint32_t opaque, uint16_t vbucket) {
if (doDisconnect()) {
return ENGINE_DISCONNECT;
}
return ENGINE_ENOTSUP;
}
ENGINE_ERROR_CODE UprConsumer::setVBucketState(uint32_t opaque,
uint16_t vbucket,
vbucket_state_t state) {
if (doDisconnect()) {
return ENGINE_DISCONNECT;
}
ENGINE_ERROR_CODE err = ENGINE_KEY_ENOENT;
passive_stream_t stream = streams[vbucket];
if (stream && stream->getOpaque() == opaque && stream->isActive()) {
SetVBucketState* response = new SetVBucketState(opaque, vbucket, state);
err = stream->messageReceived(response);
bool disable = false;
if (err == ENGINE_SUCCESS &&
itemsToProcess.compare_exchange_strong(disable, true)) {
ExecutorPool::get()->wake(processTaskId);
}
}
if (err != ENGINE_SUCCESS) {
flowControl.freedBytes.fetch_add(SetVBucketState::baseMsgBytes);
}
return err;
}
ENGINE_ERROR_CODE UprConsumer::step(struct upr_message_producers* producers) {
setLastWalkTime();
if (doDisconnect()) {
return ENGINE_DISCONNECT;
}
ENGINE_ERROR_CODE ret = ENGINE_SUCCESS;
if (flowControl.enabled) {
uint32_t ackable_bytes = flowControl.freedBytes;
if (flowControl.pendingControl) {
uint32_t opaque = ++opaqueCounter;
char buf_size[10];
snprintf(buf_size, 10, "%u", flowControl.bufferSize);
ret = producers->control(getCookie(), opaque,
"connection_buffer_size", 22, buf_size,
strlen(buf_size));
flowControl.pendingControl = false;
return (ret == ENGINE_SUCCESS) ? ENGINE_WANT_MORE : ret;
} else if (ackable_bytes > (flowControl.bufferSize * .2)) {
// Send a buffer ack when at least 20% of the buffer is drained
uint32_t opaque = ++opaqueCounter;
ret = producers->buffer_acknowledgement(getCookie(), opaque, 0,
ackable_bytes);
flowControl.lastBufferAck = ep_current_time();
flowControl.ackedBytes.fetch_add(ackable_bytes);
flowControl.freedBytes.fetch_sub(ackable_bytes);
return (ret == ENGINE_SUCCESS) ? ENGINE_WANT_MORE : ret;
} else if (ackable_bytes > 0 &&
(ep_current_time() - flowControl.lastBufferAck) > 5) {
// Ack at least every 5 seconds
uint32_t opaque = ++opaqueCounter;
ret = producers->buffer_acknowledgement(getCookie(), opaque, 0,
ackable_bytes);
flowControl.lastBufferAck = ep_current_time();
flowControl.ackedBytes.fetch_add(ackable_bytes);
flowControl.freedBytes.fetch_sub(ackable_bytes);
return (ret == ENGINE_SUCCESS) ? ENGINE_WANT_MORE : ret;
}
}
UprResponse *resp = getNextItem();
if (resp == NULL) {
return ENGINE_SUCCESS;
}
switch (resp->getEvent()) {
case UPR_ADD_STREAM:
{
AddStreamResponse *as = static_cast<AddStreamResponse*>(resp);
ret = producers->add_stream_rsp(getCookie(), as->getOpaque(),
as->getStreamOpaque(),
as->getStatus());
break;
}
case UPR_STREAM_REQ:
{
StreamRequest *sr = static_cast<StreamRequest*> (resp);
ret = producers->stream_req(getCookie(), sr->getOpaque(),
sr->getVBucket(), sr->getFlags(),
sr->getStartSeqno(), sr->getEndSeqno(),
sr->getVBucketUUID(),
sr->getSnapStartSeqno(),
sr->getSnapEndSeqno());
break;
}
case UPR_SET_VBUCKET:
{
SetVBucketStateResponse* vs;
vs = static_cast<SetVBucketStateResponse*>(resp);
ret = producers->set_vbucket_state_rsp(getCookie(), vs->getOpaque(),
vs->getStatus());
break;
}
default:
LOG(EXTENSION_LOG_WARNING, "%s Unknown consumer event (%d), "
"disconnecting", logHeader(), resp->getEvent());
ret = ENGINE_DISCONNECT;
}
delete resp;
if (ret == ENGINE_SUCCESS) {
return ENGINE_WANT_MORE;
}
return ret;
}
bool RollbackTask::run() {
cons->doRollback(engine->getEpStore(), opaque, vbid, rollbackSeqno);
++(engine->getEpStats().rollbackCount);
return false;
}
ENGINE_ERROR_CODE UprConsumer::handleResponse(
protocol_binary_response_header *resp) {
if (doDisconnect()) {
return ENGINE_DISCONNECT;
}
uint8_t opcode = resp->response.opcode;
uint32_t opaque = resp->response.opaque;
opaque_map::iterator oitr = opaqueMap_.find(opaque);
bool validOpaque = false;
if (oitr != opaqueMap_.end()) {
validOpaque = isValidOpaque(opaque, oitr->second.second);
}
if (!validOpaque) {
LOG(EXTENSION_LOG_WARNING, "%s Received response with opaque %ld and "
"that stream no longer exists", logHeader());
return ENGINE_KEY_ENOENT;
}
if (opcode == PROTOCOL_BINARY_CMD_UPR_STREAM_REQ) {
protocol_binary_response_upr_stream_req* pkt =
reinterpret_cast<protocol_binary_response_upr_stream_req*>(resp);
uint16_t vbid = oitr->second.second;
uint16_t status = ntohs(pkt->message.header.response.status);
uint64_t bodylen = ntohl(pkt->message.header.response.bodylen);
uint8_t* body = pkt->bytes + sizeof(protocol_binary_response_header);
if (status == PROTOCOL_BINARY_RESPONSE_ROLLBACK) {
cb_assert(bodylen == sizeof(uint64_t));
uint64_t rollbackSeqno = 0;
memcpy(&rollbackSeqno, body, sizeof(uint64_t));
rollbackSeqno = ntohll(rollbackSeqno);
ExTask task = new RollbackTask(&engine_, opaque, vbid,
rollbackSeqno, this,
Priority::TapBgFetcherPriority);
ExecutorPool::get()->schedule(task, READER_TASK_IDX);
return ENGINE_SUCCESS;
}
if (((bodylen % 16) != 0 || bodylen == 0) && status == ENGINE_SUCCESS) {
LOG(EXTENSION_LOG_WARNING, "%s (vb %d)Got a stream response with a "
"bad failover log (length %llu), disconnecting", logHeader(),
vbid, bodylen);
return ENGINE_DISCONNECT;
}
streamAccepted(opaque, status, body, bodylen);
return ENGINE_SUCCESS;
} else if (opcode == PROTOCOL_BINARY_CMD_UPR_BUFFER_ACKNOWLEDGEMENT ||
opcode == PROTOCOL_BINARY_CMD_UPR_CONTROL) {
return ENGINE_SUCCESS;
}
LOG(EXTENSION_LOG_WARNING, "%s Trying to handle an unknown response %d, "
"disconnecting", logHeader(), opcode);
return ENGINE_DISCONNECT;
}
void UprConsumer::doRollback(EventuallyPersistentStore *st,
uint32_t opaque,
uint16_t vbid,
uint64_t rollbackSeqno) {
shared_ptr<RollbackCB> cb(new RollbackCB(engine_));
ENGINE_ERROR_CODE errCode = ENGINE_SUCCESS;
errCode = engine_.getEpStore()->rollback(vbid, rollbackSeqno, cb);
if (errCode == ENGINE_ROLLBACK) {
if (engine_.getEpStore()->resetVBucket(vbid)) {
errCode = ENGINE_SUCCESS;
} else {
LOG(EXTENSION_LOG_WARNING, "%s (vb %d) Rollback failed because the "
"vbucket was not found", logHeader(), vbid);
errCode = ENGINE_FAILED;
}
}
if (errCode == ENGINE_SUCCESS) {
RCPtr<VBucket> vb = st->getVBucket(vbid);
streams[vbid]->reconnectStream(vb, opaque, rollbackSeqno);
} else {
//TODO: If rollback failed due to internal errors, we need to
//send an error message back to producer, so that it can terminate
//the connection.
LOG(EXTENSION_LOG_WARNING, "%s (vb %d) Rollback failed due to an "
"internal error %d", logHeader(), vbid, errCode);
opaqueMap_.erase(opaque);
}
}
void UprConsumer::addStats(ADD_STAT add_stat, const void *c) {
ConnHandler::addStats(add_stat, c);
int max_vbuckets = engine_.getConfiguration().getMaxVbuckets();
for (int vbucket = 0; vbucket < max_vbuckets; vbucket++) {
passive_stream_t stream = streams[vbucket];
if (stream) {
stream->addStats(add_stat, c);
}
}
if (flowControl.enabled) {
addStat("total_acked_bytes", flowControl.ackedBytes, add_stat, c);
}
}
process_items_error_t UprConsumer::processBufferedItems() {
itemsToProcess.store(false);
int max_vbuckets = engine_.getConfiguration().getMaxVbuckets();
for (int vbucket = 0; vbucket < max_vbuckets; vbucket++) {
passive_stream_t stream = streams[vbucket];
if (!stream) {
continue;
}
uint32_t bytes_processed;
do {
if (!engine_.getTapThrottle().shouldProcess()) {
return cannot_process;
}
bytes_processed = stream->processBufferedMessages();
flowControl.freedBytes.fetch_add(bytes_processed);
} while (bytes_processed > 0);
}
if (itemsToProcess.load()) {
return more_to_process;
}
return all_processed;
}
UprResponse* UprConsumer::getNextItem() {
LockHolder lh(streamMutex);
setPaused(false);
while (!ready.empty()) {
uint16_t vbucket = ready.front();
ready.pop_front();
if (!streams[vbucket]) {
continue;
}
UprResponse* op = streams[vbucket]->next();
if (!op) {
continue;
}
switch (op->getEvent()) {
case UPR_STREAM_REQ:
case UPR_ADD_STREAM:
case UPR_SET_VBUCKET:
break;
default:
LOG(EXTENSION_LOG_WARNING, "%s Consumer is attempting to write"
" an unexpected event %d", logHeader(), op->getEvent());
abort();
}
ready.push_back(vbucket);
return op;
}
setPaused(true);
return NULL;
}
void UprConsumer::notifyStreamReady(uint16_t vbucket) {
std::list<uint16_t>::iterator iter =
std::find(ready.begin(), ready.end(), vbucket);
if (iter != ready.end()) {
return;
}
ready.push_back(vbucket);
engine_.getUprConnMap().notifyPausedConnection(this, true);
}
void UprConsumer::streamAccepted(uint32_t opaque, uint16_t status, uint8_t* body,
uint32_t bodylen) {
LockHolder lh(streamMutex);
opaque_map::iterator oitr = opaqueMap_.find(opaque);
if (oitr != opaqueMap_.end()) {
uint32_t add_opaque = oitr->second.first;
uint16_t vbucket = oitr->second.second;
passive_stream_t &stream = streams[vbucket];
if (stream && stream->getOpaque() == opaque &&
stream->getState() == STREAM_PENDING) {
if (status == ENGINE_SUCCESS) {
RCPtr<VBucket> vb = engine_.getVBucket(vbucket);
vb->failovers->replaceFailoverLog(body, bodylen);
EventuallyPersistentStore* st = engine_.getEpStore();
st->scheduleVBSnapshot(Priority::VBucketPersistHighPriority,
st->getVBuckets().getShard(vbucket)->getId());
}
LOG(EXTENSION_LOG_INFO, "%s (vb %d) Add stream for opaque %ld"
" %s with error code %d", logHeader(), vbucket, opaque,
status == ENGINE_SUCCESS ? "succeeded" : "failed", status);
stream->acceptStream(status, add_opaque);
} else {
LOG(EXTENSION_LOG_WARNING, "%s (vb %d) Trying to add stream, but "
"none exists (opaque: %d, add_opaque: %d)", logHeader(),
vbucket, opaque, add_opaque);
}
opaqueMap_.erase(opaque);
} else {
LOG(EXTENSION_LOG_WARNING, "%s No opaque found for add stream response "
"with opaque %ld", logHeader(), opaque);
}
}
bool UprConsumer::isValidOpaque(uint32_t opaque, uint16_t vbucket) {
LockHolder lh(streamMutex);
passive_stream_t &stream = streams[vbucket];
return stream && stream->getOpaque() == opaque;
}
void UprConsumer::closeAllStreams() {
int max_vbuckets = engine_.getConfiguration().getMaxVbuckets();
for (int vbucket = 0; vbucket < max_vbuckets; vbucket++) {
passive_stream_t stream = streams[vbucket];
if (stream) {
stream->setDead(END_STREAM_DISCONNECTED);
}
}
}
| 35.882707
| 81
| 0.584192
|
mikewied
|
eb63e91dac3558b570ba51a381dd792c4a00b1c1
| 59,799
|
cpp
|
C++
|
plugins/network/NetClass.cpp
|
sergey-rybalkin/FarManager
|
26f8df87ee2461ed3c1da4c12b4761d958766608
|
[
"BSD-3-Clause"
] | null | null | null |
plugins/network/NetClass.cpp
|
sergey-rybalkin/FarManager
|
26f8df87ee2461ed3c1da4c12b4761d958766608
|
[
"BSD-3-Clause"
] | null | null | null |
plugins/network/NetClass.cpp
|
sergey-rybalkin/FarManager
|
26f8df87ee2461ed3c1da4c12b4761d958766608
|
[
"BSD-3-Clause"
] | null | null | null |
#include "NetCommon.hpp"
#include "NetCfg.hpp"
#include "NetFavorites.hpp"
#include "NetClass.hpp"
#include "guid.hpp"
#include <PluginSettings.hpp>
#include <DlgBuilder.hpp>
#include <SimpleString.hpp>
NetResourceList *CommonRootResources;
BOOL SavedCommonRootResources = FALSE;
static __int64 GetSetting(FARSETTINGS_SUBFOLDERS Root,const wchar_t* Name)
{
__int64 result=0;
FarSettingsCreate settings={sizeof(FarSettingsCreate),FarGuid,INVALID_HANDLE_VALUE};
HANDLE Settings=PsInfo.SettingsControl(INVALID_HANDLE_VALUE,SCTL_CREATE,0,&settings)?settings.Handle:nullptr;
if(Settings)
{
FarSettingsItem item={sizeof(FarSettingsItem),static_cast<size_t>(Root),Name,FST_UNKNOWN,{}};
if(PsInfo.SettingsControl(Settings,SCTL_GET,0,&item)&&FST_QWORD==item.Type)
{
result=item.Number;
}
PsInfo.SettingsControl(Settings,SCTL_FREE,0,{});
}
return result;
}
// -- NetResourceList --------------------------------------------------------
#ifdef NETWORK_LOGGING
FILE* NetBrowser::LogFile{};
int NetBrowser::LogFileRef = 0;
void NetBrowser::OpenLogFile(const wchar_t *lpFileName)
{
if (!LogFileRef)
LogFile = _wfopen(lpFileName, L"a+t");
if (LogFile)
fwprintf(LogFile, L"Opening plugin\n");
LogFileRef++;
}
void NetBrowser::CloseLogfile()
{
LogFileRef--;
if (!LogFileRef && LogFile)fclose(LogFile),LogFile = {};
}
void NetBrowser::LogData(const wchar_t * Data)
{
if (LogFile)
{
fwprintf(LogFile,L"%s\n", Data);
wchar_t buffer[MAX_PATH];
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, {}, GetLastError(), 0, buffer, ARRAYSIZE(buffer), {});
fwprintf(LogFile,L"GetLastError returns: %s\n", buffer);
}
}
#endif
NetResourceList::NetResourceList()
: ResList(), ResCount(0)
{
}
NetResourceList::~NetResourceList()
{
Clear();
}
NetResourceList &NetResourceList::operator= (NetResourceList &other)
{
Clear();
for (unsigned I=0; I<other.Count(); I++)
Push(other [I]);
return *this;
}
void NetResourceList::Clear()
{
for (unsigned i=0; i < ResCount; i++)
DeleteNetResource(ResList [i]);
free(ResList);
ResList={};
ResCount=0;
}
void NetResourceList::DeleteNetResource(NETRESOURCE &Res)
{
free(Res.lpRemoteName);
free(Res.lpLocalName);
free(Res.lpComment);
free(Res.lpProvider);
}
wchar_t *NetResourceList::CopyText(const wchar_t *Text)
{
return Text ? wcsdup(Text) : nullptr;
}
void NetResourceList::InitNetResource(NETRESOURCE &Res)
{
Res.lpRemoteName = {};
Res.lpLocalName = {};
Res.lpComment = {};
Res.lpProvider = {};
}
void NetResourceList::CopyNetResource(NETRESOURCE &Dest, const NETRESOURCE &Src)
{
free(Dest.lpRemoteName);
free(Dest.lpLocalName);
free(Dest.lpComment);
free(Dest.lpProvider);
memcpy(&Dest, &Src, sizeof(NETRESOURCE));
Dest.lpRemoteName = CopyText(Src.lpRemoteName);
Dest.lpLocalName = CopyText(Src.lpLocalName);
Dest.lpComment = CopyText(Src.lpComment);
Dest.lpProvider = CopyText(Src.lpProvider);
}
void NetResourceList::Push(NETRESOURCE &Res)
{
ResList=(NETRESOURCE *)realloc(ResList,(ResCount+1)*sizeof(*ResList));
ZeroMemory(&ResList [ResCount], sizeof(*ResList));
CopyNetResource(ResList [ResCount], Res);
ResCount++;
}
NETRESOURCE *NetResourceList::Top()
{
if (ResCount == 0)
return {};
return &ResList [ResCount-1];
}
void NetResourceList::Pop()
{
if (ResCount > 0)
{
DeleteNetResource(ResList [ResCount-1]);
ResList=(NETRESOURCE *)realloc(ResList,(ResCount-1)*sizeof(*ResList));
ResCount--;
}
}
BOOL NetResourceList::Enumerate(DWORD dwScope, DWORD dwType, DWORD dwUsage,
LPNETRESOURCE lpNetResource)
{
Clear();
if (GetFavorites(lpNetResource, this))
return TRUE;
HANDLE hEnum;
if (WNetOpenEnum(dwScope, dwType, dwUsage, lpNetResource, &hEnum)!=NO_ERROR)
return FALSE;
BOOL EnumFailed = FALSE;
for (;;)
{
NETRESOURCE nr[1024];
DWORD NetSize=sizeof(nr),NetCount=ARRAYSIZE(nr);
DWORD EnumCode=WNetEnumResource(hEnum,&NetCount,nr,&NetSize);
if (EnumCode!=NO_ERROR)
{
if (EnumCode!=ERROR_NO_MORE_ITEMS)
{
Clear();
EnumFailed = TRUE;
}
break;
}
if (NetCount>0)
{
ResList=(NETRESOURCE *)realloc(ResList,(ResCount+NetCount)*sizeof(*ResList));
ZeroMemory(&ResList [ResCount], sizeof(*ResList)*NetCount);
for (unsigned I=0; I<NetCount; I++)
CopyNetResource(ResList [ResCount+I], nr [I]);
ResCount+=NetCount;
}
}
WNetCloseEnum(hEnum);
return !EnumFailed;
}
// -- NetBrowser -------------------------------------------------------------
NetBrowser::NetBrowser()
{
{
PluginSettings settings(MainGuid, PsInfo.SettingsControl);
settings.Get(0,StrPanelMode,m_PanelMode,ARRAYSIZE(m_PanelMode),L"3");
}
NetResourceList::InitNetResource(CurResource);
ReenterGetFindData = 0;
ChangeDirSuccess = TRUE;
OpenFromFilePanel = FALSE;
if (SavedCommonRootResources)
{
RootResources = *CommonRootResources;
PCurResource = RootResources.Top();
}
else
{
NetResourceList::CopyNetResource(CurResource, CommonCurResource);
if (PCommonCurResource)
PCurResource = &CurResource;
else
PCurResource = {};
}
NetListRemoteName [0] = L'\0';
CmdLinePath [0] = L'\0';
#ifdef NETWORK_LOGGING
OpenLogFile(L"c:\\network.log");
#endif
}
NetBrowser::~NetBrowser()
{
#ifdef NETWORK_LOGGING
CloseLogfile();
#endif
}
#ifdef NETWORK_LOGGING
void NetBrowser::LogNetResource(NETRESOURCE &Res)
{
if (LogFile)
{
fwprintf(LogFile, L"dwScope = %u\ndwType = %u\ndwDisplayType = %u\ndwUsage = %u\n", Res.dwScope, Res.dwType, Res.dwDisplayType, Res.dwUsage);
fwprintf(LogFile, L"lpLocalName = %s\nlpRemoteName = %s\nlpComment = %s\nlpProvider = %s\n\n", Res.lpLocalName, Res.lpRemoteName, Res.lpComment, Res.lpProvider);
}
}
#endif
BOOL NetBrowser::EnumerateNetList()
{
if (PCurResource && PCurResource->lpRemoteName)
lstrcpy(NetListRemoteName, PCurResource->lpRemoteName);
else
NetListRemoteName [0] = L'\0';
if (!NetList.Enumerate(RESOURCE_GLOBALNET,RESOURCETYPE_ANY,0,PCurResource))
{
if (!PCurResource)
{
const wchar_t *MsgItems[]={GetMsg(MError),GetMsg(MNetCannotBrowse),GetMsg(MOk)};
PsInfo.Message(&MainGuid, nullptr,FMSG_WARNING|FMSG_ERRORTYPE,{},MsgItems,ARRAYSIZE(MsgItems),1);
return(FALSE);
}
else
{
// try again with connection
AddConnection(PCurResource);
if (!NetList.Enumerate(RESOURCE_GLOBALNET,RESOURCETYPE_ANY,0,PCurResource))
NetList.Clear();
}
}
if (!CheckFavoriteItem(PCurResource) && Opt.HiddenShares)
{
PanelInfo PInfo = {sizeof(PanelInfo)};
PsInfo.PanelControl(this, FCTL_GETPANELINFO,0,&PInfo);
if (!Opt.HiddenSharesAsHidden || (PInfo.Flags & PFLAGS_SHOWHIDDEN))
{
// Check whether we need to get the hidden shares.
if (NetList.Count() > 0)
{
if (PCurResource)
{
// If the parent of the current folder is not a server
if (PCurResource->dwDisplayType != RESOURCEDISPLAYTYPE_SERVER)
{
return TRUE;
}
}
// If there are elements, check the first element
if ((NetList[NetList.Count()-1].dwDisplayType) != RESOURCEDISPLAYTYPE_SHARE)
{
return TRUE;
}
}
GetHiddenShares();
}
}
/*
if (NetCount==0 && CurResource && AddConnection(CurResource))
if (WNetOpenEnum(RESOURCE_GLOBALNET,RESOURCETYPE_ANY,0,CurResource,&hEnum)==NO_ERROR)
{
GetNetList(hEnum,NetRes,NetCount);
WNetCloseEnum(hEnum);
}
*/
return TRUE;
}
BOOL NetBrowser::GotoFavorite(wchar_t *lpPath)
{
#ifdef NEWTWORK_LOGGING
LogData(L"Entered NetBrowser::GotoFavorite")
#endif
NETRESOURCE nr = {0};
if (GetFavoriteResource(lpPath, &nr))
{
#ifdef NETWORK_LOGGING
LogData(L"GetFavoriteResource SUCCEEDED");
LogNetResource(nr);
#endif
NetResourceList::CopyNetResource(CurResource, nr);
NetResourceList::DeleteNetResource(nr);
PCurResource = &CurResource;
PsInfo.PanelControl(this, FCTL_UPDATEPANEL,0,{});
PsInfo.PanelControl(this, FCTL_REDRAWPANEL,0,{});
return TRUE;
}
return FALSE;
}
int NetBrowser::GetFindData(PluginPanelItem **pPanelItem,size_t *pItemsNumber,OPERATION_MODES OpMode)
{
#ifdef NETWORK_LOGGING
LogData(L"Entering NetBrowser::GetFindData");
#endif
if (OpMode & OPM_FIND)
return FALSE;
if (ReenterGetFindData)
return TRUE;
ReenterGetFindData++;
if (ChangeDirSuccess)
{
if (CmdLinePath [0])
{
// prevent recursion
wchar_t TmpCmdLinePath [MAX_PATH];
lstrcpy(TmpCmdLinePath, CmdLinePath);
CmdLinePath [0] = 0;
ReenterGetFindData--;
if (!GotoFavorite(TmpCmdLinePath))
GotoComputer(TmpCmdLinePath);
ReenterGetFindData++;
}
*pPanelItem={};
*pItemsNumber=0;
TSaveScreen SS;
// get the list of connections, so that we can show mapped drive letters
if (!ConnectedList.Enumerate(RESOURCE_CONNECTED,RESOURCETYPE_DISK,0,{}))
{
const wchar_t *MsgItems[]={GetMsg(MError),GetMsg(MNetCannotBrowse),GetMsg(MOk)};
PsInfo.Message(&MainGuid, nullptr,FMSG_WARNING|FMSG_ERRORTYPE,{},MsgItems,ARRAYSIZE(MsgItems),1);
ReenterGetFindData--;
return FALSE;
}
if (!EnumerateNetList())
{
ReenterGetFindData--;
return FALSE;
}
}
ChangeDirSuccess = TRUE;
PluginPanelItem *NewPanelItem=(PluginPanelItem *)malloc(sizeof(PluginPanelItem)*NetList.Count());
*pPanelItem=NewPanelItem;
if (!NewPanelItem)
{
ReenterGetFindData--;
return(FALSE);
}
int CurItemPos=0;
for (unsigned I=0; I<NetList.Count(); I++)
{
if (NetList[I].dwType==RESOURCETYPE_PRINT && !Opt.ShowPrinters)
continue;
wchar_t RemoteName[MAX_PATH],LocalName[MAX_PATH],Comment[300];
GetRemoteName(&NetList [I],RemoteName);
if (!NetList[I].lpComment)
*Comment=0;
else
lstrcpy(Comment,NetList[I].lpComment);
memset(&NewPanelItem[CurItemPos],0,sizeof(PluginPanelItem));
GetLocalName(NetList[I].lpRemoteName,LocalName);
LPTSTR* CustomColumnData=(LPTSTR*)malloc(sizeof(LPTSTR)*2);
CustomColumnData[0] = wcsdup(LocalName);
CustomColumnData[1] = wcsdup(Comment);
NewPanelItem[CurItemPos].CustomColumnData=CustomColumnData;
NewPanelItem[CurItemPos].CustomColumnNumber=2;
NewPanelItem[CurItemPos].FileName = wcsdup(RemoteName);
NewPanelItem[CurItemPos].Description = wcsdup(Comment);
DWORD attr = FILE_ATTRIBUTE_DIRECTORY;
if (NetList[I].dwType==RESOURCETYPE_PRINT)
attr = FILE_ATTRIBUTE_VIRTUAL;
if (Opt.HiddenSharesAsHidden && RemoteName [lstrlen(RemoteName)-1] == L'$')
attr |= FILE_ATTRIBUTE_HIDDEN;
NewPanelItem[CurItemPos].FileAttributes=attr;
CurItemPos++;
}
*pItemsNumber=CurItemPos;
ReenterGetFindData--;
return(TRUE);
}
void NetBrowser::FreeFindData(PluginPanelItem *PanelItem,int ItemsNumber)
{
for (int I=0; I<ItemsNumber; I++)
{
free(const_cast<wchar_t*>(PanelItem[I].CustomColumnData[0]));
free(const_cast<wchar_t*>(PanelItem[I].CustomColumnData[1]));
free(const_cast<wchar_t**>(PanelItem[I].CustomColumnData));
free(const_cast<wchar_t*>(PanelItem[I].FileName));
free(const_cast<wchar_t*>(PanelItem[I].Description));
}
free(PanelItem);
}
int NetBrowser::ProcessEvent(intptr_t Event, void* /*Param*/)
{
if (Event == FE_CLOSE)
{
{
PanelInfo PInfo = {sizeof(PanelInfo)};
PsInfo.PanelControl(this, FCTL_GETPANELINFO,0,&PInfo);
wchar_t Mode[2] = { static_cast<wchar_t>(PInfo.ViewMode + 0x30), 0 };
PluginSettings settings(MainGuid, PsInfo.SettingsControl);
settings.Set(0,StrPanelMode,Mode);
}
if (!PCurResource || IsMSNetResource(*PCurResource))
{
NetResourceList::CopyNetResource(CommonCurResource, CurResource);
PCommonCurResource = PCurResource ? &CommonCurResource : nullptr;
SavedCommonRootResources = false;
}
else
{
*CommonRootResources = RootResources;
SavedCommonRootResources = true;
}
}
return FALSE;
}
int NetBrowser::DeleteFiles(PluginPanelItem *PanelItem,int ItemsNumber, OPERATION_MODES /*OpMode*/)
{
if (CheckFavoriteItem(PCurResource))
{
//Deleting from favorites
RemoveItems();
}
else
{
for (int I=0; I<ItemsNumber; I++)
if (PanelItem[I].CustomColumnNumber==2 && PanelItem[I].CustomColumnData)
{
if (*PanelItem[I].CustomColumnData[0])
if (!CancelConnection(PanelItem [I].FileName)) break;
}
}
return(TRUE);
}
BOOL NetBrowser::CancelConnection(const wchar_t *RemoteName)
{
wchar_t LocalName [MAX_PATH];
wchar_t szFullName[MAX_PATH];
szFullName[0] = 0;
if (Opt.FullPathShares)
lstrcpy(szFullName, RemoteName);
else if (PCurResource && PCurResource->lpRemoteName)
FSF.sprintf(szFullName, L"%s\\%s", PCurResource->lpRemoteName, RemoteName);
else
return FALSE;
if (!GetDriveToDisconnect(szFullName, LocalName))
return FALSE;
int UpdateProfile = 0;
if (!ConfirmCancelConnection(LocalName, szFullName, UpdateProfile))
return FALSE;
DWORD status = WNetCancelConnection2(LocalName,UpdateProfile,FALSE);
// if we're on the drive we're disconnecting, set the directory to
// a different drive and try again
if (status != NO_ERROR && HandsOffDisconnectDrive(LocalName))
status = WNetCancelConnection2(LocalName,UpdateProfile,FALSE);
if (status!=NO_ERROR)
{
int Failed=FALSE;
wchar_t MsgText[200];
FSF.sprintf(MsgText,GetMsg(MNetCannotDisconnect),LocalName);
int LastError=GetLastError();
if (LastError==ERROR_OPEN_FILES || LastError==ERROR_DEVICE_IN_USE)
{
const wchar_t *MsgItems[]={GetMsg(MError),MsgText,L"\x1",GetMsg(MOpenFiles),GetMsg(MAskDisconnect),GetMsg(MOk),GetMsg(MCancel)};
if (PsInfo.Message(&MainGuid, nullptr,FMSG_WARNING|FMSG_ERRORTYPE,{},MsgItems,ARRAYSIZE(MsgItems),2)==0)
// всегда рвать соединение
if (WNetCancelConnection2(LocalName,UpdateProfile,TRUE)!=NO_ERROR)
Failed=TRUE;
}
else
Failed=TRUE;
if (Failed)
{
const wchar_t *MsgItems[]={GetMsg(MError),MsgText,GetMsg(MOk)};
PsInfo.Message(&MainGuid, nullptr,FMSG_WARNING|FMSG_ERRORTYPE,{},MsgItems,ARRAYSIZE(MsgItems),1);
return FALSE;
}
}
return TRUE;
}
BOOL NetBrowser::GetDriveToDisconnect(const wchar_t *RemoteName, wchar_t *LocalName)
{
wchar_t LocalNames [MAX_PATH][10];
DWORD LocalNameCount = 0;
DWORD i;
for (i = 0; i < ConnectedList.Count(); i++)
{
NETRESOURCE &connRes = ConnectedList [i];
if (connRes.lpRemoteName && connRes.lpLocalName &&
*connRes.lpLocalName && lstrcmpi(connRes.lpRemoteName, RemoteName) == 0)
{
if (connRes.dwScope == RESOURCE_CONNECTED ||
connRes.dwScope == RESOURCE_REMEMBERED)
{
lstrcpy(LocalNames [LocalNameCount++], connRes.lpLocalName);
if (LocalNameCount == 10) break;
}
}
}
if (!LocalNameCount) return FALSE; // hmmm... strange
if (LocalNameCount == 1)
lstrcpy(LocalName, LocalNames [0]);
else
{
wchar_t MsgText [512];
FSF.sprintf(MsgText, GetMsg(MMultipleDisconnect), RemoteName);
for (i=0; i<LocalNameCount; i++)
{
lstrcat(MsgText, LocalNames [i]);
lstrcat(MsgText, L"\n");
}
int index = (int)PsInfo.Message(&MainGuid, nullptr, FMSG_ALLINONE, {},
(const wchar_t **) MsgText, 3+LocalNameCount, LocalNameCount);
if (index < 0)
return FALSE;
lstrcpy(LocalName, LocalNames [index]);
}
return TRUE;
}
BOOL NetBrowser::ConfirmCancelConnection(wchar_t *LocalName, wchar_t *RemoteName, int &UpdateProfile)
{
wchar_t MsgText[MAX_PATH];
BOOL IsPersistent = TRUE;
// Check if this was a permanent connection or not.
{
HKEY hKey{};
FSF.sprintf(MsgText,L"Network\\%c",FSF.LUpper(LocalName[0]));
if (RegOpenKeyEx(HKEY_CURRENT_USER,MsgText,0,KEY_QUERY_VALUE,&hKey)!=ERROR_SUCCESS)
{
IsPersistent=FALSE;
}
if (hKey)
RegCloseKey(hKey);
}
FSF.sprintf(MsgText,GetMsg(MConfirmDisconnectQuestion),LocalName);
/*
wchar_t tmp[MAX_PATH];
DialogItems[3].Data = tmp;
{
size_t rc = lstrlen(DialogItems[0].Data);
if(Len1 < rc) Len1 = rc;
rc = lstrlen(DialogItems[5].Data);
if(Len1 < rc) Len1 = rc;
}
lstrcpy((wchar_t*)DialogItems[3].Data, FSF.TruncPathStr(RemoteName, (int)Len1));
*/
PluginDialogBuilder Builder(PsInfo, MainGuid, DisconnectDialogGuid, MConfirmDisconnectTitle, L"DisconnectDrive");
Builder.AddText(MsgText);
Builder.AddText(RemoteName);
Builder.AddSeparator();
Builder.AddCheckbox(MConfirmDisconnectReconnect, &Opt.DisconnectMode)->Flags |= IsPersistent ? 0 : DIF_DISABLE;
Builder.AddOKCancel(MYes, MCancel);
if (!NeedConfirmCancelConnection() || Builder.ShowDialog())
{
UpdateProfile=Opt.DisconnectMode?0:CONNECT_UPDATE_PROFILE;
if (IsPersistent)
{
PluginSettings settings(MainGuid, PsInfo.SettingsControl);
settings.Set(0,StrDisconnectMode,Opt.DisconnectMode);
}
return TRUE;
}
return FALSE;
}
BOOL NetBrowser::NeedConfirmCancelConnection()
{
return GetSetting(FSSF_CONFIRMATIONS,L"RemoveConnection")?true:false;
}
BOOL NetBrowser::HandsOffDisconnectDrive(const wchar_t *LocalName)
{
wchar_t DirBuf [MAX_PATH];
GetCurrentDirectory(ARRAYSIZE(DirBuf)-1, DirBuf);
if (FSF.LUpper(DirBuf [0]) != FSF.LUpper(LocalName [0]))
return FALSE;
// change to the root of the drive where network.dll resides
if (!GetModuleFileName({}, DirBuf, ARRAYSIZE(DirBuf)-1))
return FALSE;
DirBuf [3] = L'\0'; // truncate to "X:\\"
return SetCurrentDirectory(DirBuf);
}
void NetBrowser::GetOpenPanelInfo(OpenPanelInfo *Info)
{
#ifdef NETWORK_LOGGING__
if (PCurResource)
LogData(L"Entering NetBrowser::GetOpenPluginInfo. Info->Flags will contain OPIF_ADDDOTS");
else
LogData(L"Entering NetBrowser::GetOpenPluginInfo. Info->Flags will NOT contain OPIF_ADDDOTS");
#endif
Info->StructSize=sizeof(*Info);
Info->Flags=OPIF_ADDDOTS|OPIF_RAWSELECTION|OPIF_SHOWPRESERVECASE|OPIF_SHORTCUT;
Info->HostFile={};
if (!PCurResource)
{
Info->CurDir=L"";
if (!Opt.RootDoublePoint)
Info->Flags &= ~OPIF_ADDDOTS;
}
else
{
static wchar_t CurDir[MAX_PATH];
if (!PCurResource->lpRemoteName)
{
if (CheckFavoriteItem(PCurResource))
lstrcpy(CurDir, GetMsg(MFavorites));
else
lstrcpy(CurDir, PCurResource->lpProvider);
}
else
{
lstrcpy(CurDir, PCurResource->lpRemoteName);
}
Info->CurDir=CurDir;
}
Info->Format=const_cast<wchar_t*>(GetMsg(MNetwork));
static wchar_t Title[MAX_PATH];
FSF.sprintf(Title,L" %s: %s ",GetMsg(MNetwork), Info->CurDir);
Info->PanelTitle=Title;
Info->InfoLines={};
Info->InfoLinesNumber=0;
Info->DescrFiles={};
Info->DescrFilesNumber=0;
static PanelMode PanelModesArray[10];
static const wchar_t *ColumnTitles[3];
ColumnTitles[0]=GetMsg(MColumnName);
ColumnTitles[1]=GetMsg(MColumnDisk);
ColumnTitles[2]=GetMsg(MColumnComment);
PanelModesArray[3].ColumnTypes=L"N,C0,C1";
PanelModesArray[3].ColumnWidths=L"0,2,0";
PanelModesArray[3].ColumnTitles=ColumnTitles;
PanelModesArray[4].ColumnTypes=L"N,C0";
PanelModesArray[4].ColumnWidths=L"0,2";
PanelModesArray[4].ColumnTitles=ColumnTitles;
PanelModesArray[5].ColumnTypes=L"N,C0,C1";
PanelModesArray[5].ColumnWidths=L"0,2,0";
PanelModesArray[5].ColumnTitles=ColumnTitles;
Info->PanelModesArray=PanelModesArray;
Info->PanelModesNumber=ARRAYSIZE(PanelModesArray);
Info->StartPanelMode=m_PanelMode[0];
if (PCurResource && PCurResource->dwDisplayType == RESOURCEDISPLAYTYPE_SERVER)
{
Info->Flags|=OPIF_REALNAMES;
static WORD FKeys[]=
{
VK_F3,0,0,
VK_F4,0,MF4,
VK_F5,0,MF5,
VK_F6,0,MF6,
VK_F7,0,0,
VK_F8,0,MF8,
VK_F5,LEFT_CTRL_PRESSED,0,
VK_F6,LEFT_CTRL_PRESSED,0,
VK_F3,LEFT_ALT_PRESSED,0,
VK_F4,LEFT_ALT_PRESSED,0,
VK_F5,LEFT_ALT_PRESSED,0,
VK_F1,SHIFT_PRESSED,0,
VK_F2,SHIFT_PRESSED,0,
VK_F3,SHIFT_PRESSED,0,
VK_F4,SHIFT_PRESSED,0,
VK_F5,SHIFT_PRESSED,MSHIFTF5,
VK_F6,SHIFT_PRESSED,MSHIFTF6,
VK_F7,SHIFT_PRESSED,0,
VK_F8,SHIFT_PRESSED,0,
};
static KeyBarLabel kbl[ARRAYSIZE(FKeys)/3];
static KeyBarTitles kbt = {ARRAYSIZE(kbl), kbl};
for (size_t j=0,i=0; i < ARRAYSIZE(FKeys); i+=3, ++j)
{
kbl[j].Key.VirtualKeyCode = FKeys[i];
kbl[j].Key.ControlKeyState = FKeys[i+1];
if (FKeys[i+2])
{
kbl[j].Text = kbl[j].LongText = GetMsg(FKeys[i+2]);
}
else
{
kbl[j].Text = kbl[j].LongText = L"";
}
}
Info->KeyBar=&kbt;
}
else
{
static WORD FKeys[]=
{
VK_F3,0,0,
VK_F4,0,(WORD)-1,
VK_F5,0,0,
VK_F6,0,0,
VK_F7,0,0,
VK_F8,0,(WORD)-1,
VK_F5,LEFT_CTRL_PRESSED,0,
VK_F6,LEFT_CTRL_PRESSED,0,
VK_F3,LEFT_ALT_PRESSED,0,
VK_F4,LEFT_ALT_PRESSED,0,
VK_F5,LEFT_ALT_PRESSED,0,
VK_F6,LEFT_ALT_PRESSED,0,
VK_F1,SHIFT_PRESSED,0,
VK_F2,SHIFT_PRESSED,0,
VK_F3,SHIFT_PRESSED,0,
VK_F4,SHIFT_PRESSED,0,
VK_F5,SHIFT_PRESSED,0,
VK_F6,SHIFT_PRESSED,0,
VK_F7,SHIFT_PRESSED,0,
VK_F8,SHIFT_PRESSED,0,
};
static KeyBarLabel kbl[ARRAYSIZE(FKeys)/3];
static KeyBarTitles kbt = {ARRAYSIZE(kbl), kbl};
for (size_t j=0,i=0; i < ARRAYSIZE(FKeys); i+=3, ++j)
{
kbl[j].Key.VirtualKeyCode = FKeys[i];
kbl[j].Key.ControlKeyState = FKeys[i+1];
switch (FKeys[i + 2])
{
case 0:
kbl[j].Text = kbl[j].LongText = L"";
break;
case static_cast<WORD>(-1):
switch (FKeys[i])
{
case VK_F4:
kbl[j].Text = kbl[j].LongText = (PCurResource && PCurResource->dwDisplayType == RESOURCEDISPLAYTYPE_DOMAIN) ? GetMsg(MF4) : L"";
break;
case VK_F8:
kbl[j].Text = kbl[j].LongText = CheckFavoriteItem(PCurResource) ? GetMsg(MF8Fav) : L"";
break;
default:
break;
}
break;
default:
kbl[j].Text = kbl[j].LongText = GetMsg(FKeys[i+2]);
break;
}
}
Info->KeyBar=&kbt;
}
}
int NetBrowser::SetDirectory(const wchar_t *Dir,OPERATION_MODES OpMode)
{
if (OpMode & OPM_FIND)
return TRUE;
ChangeDirSuccess = TRUE;
if (OpenFromFilePanel)
PCurResource = {};
BOOL TmpOpenFromFilePanel = OpenFromFilePanel;
OpenFromFilePanel = FALSE;
if (!Dir || lstrcmp(Dir,L"\\")==0)
{
PCurResource = {};
RootResources.Clear();
return(TRUE);
}
if (lstrcmp(Dir,L"..")==0)
{
if (!PCurResource)
return FALSE;
if (IsMSNetResource(*PCurResource))
{
NETRESOURCE nrParent;
NetResourceList::InitNetResource(nrParent);
if (!GetResourceParent(*PCurResource, &nrParent))
PCurResource = {};
else
{
CurResource = nrParent;
PCurResource = &CurResource;
}
}
else
{
RootResources.Pop();
PCurResource = RootResources.Top();
}
return TRUE;
}
else
{
ChangeDirSuccess = TRUE;
if (ChangeToDirectory(Dir, OpMode, false))
return ChangeDirSuccess;
if (GetLastError()==ERROR_CANCELLED)
return FALSE;
wchar_t AnsiDir[MAX_PATH];
lstrcpy(AnsiDir, Dir);
if (AnsiDir [0] == L'/')
AnsiDir [0] = L'\\';
if (AnsiDir [1] == L'/')
AnsiDir [1] = L'\\';
// if still haven't found and the name starts with \\, try to jump to a
// computer in a different domain
if (wcsncmp(AnsiDir, L"\\\\", 2) == 0)
{
if (!TmpOpenFromFilePanel && wcschr(AnsiDir+2, L'\\'))
{
if (!IsReadable(AnsiDir))
{
#ifdef NETWORK_LOGGING
wchar_t szErrBuff[MAX_PATH*2];
_snwprintf(szErrBuff, ARRAYSIZE(szErrBuff), L"GetLastError = %d at line %d, file %S", GetLastError(), __LINE__, __FILE__);
LogData(szErrBuff);
#endif
PsInfo.Message(&MainGuid, nullptr, FMSG_WARNING | FMSG_ERRORTYPE | FMSG_MB_OK | FMSG_ALLINONE,
{}, reinterpret_cast<const wchar_t* const*>(GetMsg(MError)), 0, 0);
return FALSE;
}
PsInfo.PanelControl(this, FCTL_CLOSEPANEL,0, const_cast<wchar_t*>(Dir));
return TRUE;
}
ChangeDirSuccess = GotoComputer(AnsiDir);
return ChangeDirSuccess;
}
}
return(FALSE);
}
BOOL NetBrowser::ChangeToDirectory(const wchar_t *Dir, OPERATION_MODES opmodes, bool IsExplicit)
{
bool IsFind = (opmodes & OPM_FIND) != 0;
bool IsPgDn = (opmodes & OPM_PGDN) != 0;
// if we already have the resource list for the current directory,
// do not scan it again
if (!PCurResource || !PCurResource->lpRemoteName ||
lstrcmp(PCurResource->lpRemoteName, NetListRemoteName) != 0)
EnumerateNetList();
wchar_t AnsiDir[MAX_PATH];
lstrcpy(AnsiDir, Dir);
if (AnsiDir [0] == L'/')
AnsiDir [0] = L'\\';
if (AnsiDir [1] == L'/')
AnsiDir [1] = L'\\';
for (unsigned I=0; I<NetList.Count(); I++)
{
wchar_t RemoteName[MAX_PATH];
GetRemoteName(&NetList[I],RemoteName);
if (FSF.LStricmp(AnsiDir,RemoteName)==0)
{
if (CheckFavoriteItem(&NetList[I]))
{
NetResourceList::CopyNetResource(CurResource, NetList [I]);
PCurResource = &CurResource;
//RootResources.Push (CurResource);
return TRUE;
}
if ((NetList[I].dwUsage & RESOURCEUSAGE_CONTAINER)==0 &&
(NetList[I].dwType & RESOURCETYPE_DISK) &&
NetList[I].lpRemoteName)
{
if (IsFind)
return(FALSE);
wchar_t NewDir[MAX_PATH],LocalName[MAX_PATH];
GetLocalName(NetList[I].lpRemoteName,LocalName);
if (IsPgDn && *LocalName)
if (IsReadable(LocalName))
lstrcpy(NewDir,LocalName);
else
{
PsInfo.Message(&MainGuid, nullptr, FMSG_WARNING | FMSG_ERRORTYPE | FMSG_MB_OK | FMSG_ALLINONE,
{}, reinterpret_cast<const wchar_t* const*>(GetMsg(MError)), 0, 0);
return TRUE;
}
else
{
BOOL ConnectError = FALSE;
lstrcpy(NewDir,NetList[I].lpRemoteName);
if (IsExplicit)
{
if (!AddConnectionExplicit(&NetList [I]) || !IsReadable(NewDir))
ConnectError = TRUE;
}
else
{
if (!IsReadable(NewDir))
if (!AddConnection(&NetList[I]) || !IsReadable(NewDir))
ConnectError = TRUE;
}
if (ConnectError)
{
DWORD res = GetLastError();
if (!IsExplicit)
if (res == ERROR_INVALID_PASSWORD || res == ERROR_LOGON_FAILURE || res == ERROR_ACCESS_DENIED || res == ERROR_INVALID_HANDLE)
ConnectError = !((AddConnectionFromFavorites(&NetList[I]) ||
AddConnectionExplicit(&NetList[I])) && IsReadable(NewDir));
if (ConnectError)
{
ChangeDirSuccess = FALSE;
if (GetLastError() != ERROR_CANCELLED)
PsInfo.Message(&MainGuid, nullptr, FMSG_WARNING | FMSG_ERRORTYPE | FMSG_MB_OK | FMSG_ALLINONE,
{}, reinterpret_cast<const wchar_t*const*>(GetMsg(MError)), 0, 0);
return TRUE;
}
}
}
PsInfo.PanelControl(this,FCTL_CLOSEPANEL,0,NewDir);
return(TRUE);
}
if (IsExplicit?!AddConnectionExplicit(&NetList[I]):!IsResourceReadable(NetList [I]))
{
int res = GetLastError();
if (res == ERROR_INVALID_PASSWORD || res == ERROR_LOGON_FAILURE || res == ERROR_ACCESS_DENIED || res == ERROR_LOGON_TYPE_NOT_GRANTED)
ChangeDirSuccess = IsExplicit?FALSE:(AddConnectionFromFavorites(&NetList[I]) || AddConnectionExplicit(&NetList[I]));
else
ChangeDirSuccess = FALSE;
if (!ChangeDirSuccess)
{
if (GetLastError() != ERROR_CANCELLED)
PsInfo.Message(&MainGuid, nullptr, FMSG_WARNING | FMSG_ERRORTYPE | FMSG_MB_OK | FMSG_ALLINONE,
{}, reinterpret_cast<const wchar_t*const*>(GetMsg(MError)), 0, 0);
return FALSE;
}
}
NetResourceList::CopyNetResource(CurResource, NetList [I]);
PCurResource = &CurResource;
if (!IsMSNetResource(CurResource))
{
#ifdef NETWORK_LOGGING
LogData(L"Resource is not MSN");
LogNetResource(CurResource);
#endif
RootResources.Push(CurResource);
}
#ifdef NETWORK_LOGGING
else
{
LogData(L"Resource is MSN");
LogNetResource(CurResource);
}
#endif
return(TRUE);
}
}
return FALSE;
}
BOOL NetBrowser::IsMSNetResource(const NETRESOURCE &Res)
{
if (!Res.lpProvider)
return TRUE;
return wcsstr(Res.lpProvider, L"Microsoft") ||
CheckFavoriteItem(const_cast<LPNETRESOURCE>(&Res));
}
BOOL NetBrowser::IsResourceReadable(NETRESOURCE &Res)
{
if (CheckFavoriteItem(&Res))
return TRUE;
HANDLE hEnum = INVALID_HANDLE_VALUE;
DWORD result = WNetOpenEnum(RESOURCE_GLOBALNET, RESOURCETYPE_ANY, 0, &Res, &hEnum);
if (result != NO_ERROR)
{
if (!AddConnection(&Res))
return FALSE;
result = WNetOpenEnum(RESOURCE_GLOBALNET, RESOURCETYPE_ANY, 0, &Res, &hEnum);
if (result != NO_ERROR)
return FALSE;
}
if (hEnum != INVALID_HANDLE_VALUE)
WNetCloseEnum(hEnum);
return TRUE;
}
/*DELETING
BOOL NetBrowser::GetDfsParent(const NETRESOURCE &SrcRes, NETRESOURCE &Parent)
{
if(!FNetDfsGetInfo)
return FALSE;
//we should allocate memory for Wide chars
int nSize = MultiByteToWideChar(CP_ACP, 0, SrcRes.lpRemoteName, -1, {}, 0);
if(!nSize)
return FALSE;
WCHAR *szRes = new WCHAR[nSize++];
if(!szRes)
return FALSE;
int Res = FALSE;
if(MultiByteToWideChar(CP_ACP, 0, SrcRes.lpRemoteName, -1, szRes, nSize*sizeof(WCHAR)))
{
LPDFS_INFO_3 lpData;
if(ERROR_SUCCESS == FNetDfsGetInfo(szRes, {}, {}, 3, (LPBYTE *) &lpData))
{
DWORD dwBuffSize = 32*sizeof(NETRESOURCE);
NETRESOURCE *resResult = (NETRESOURCE *)malloc(dwBuffSize);
CHAR *pszSys{};
for(DWORD i = 0; i < lpData->NumberOfStorages; i++)
{
nSize = WideCharToMultiByte(CP_ACP, 0, lpData->Storage[i].ServerName,
-1, {}, 0, {}, {});
if(!nSize)
break;
nSize += 3;
CHAR *szServ =new CHAR[nSize];
szServ[0] = L'\\';
szServ[1] = L'\\';
WideCharToMultiByte(CP_ACP, 0, lpData->Storage[i].ServerName,
-1, &szServ[2], nSize - 2, {}, {});
NETRESOURCE inRes = {0};
inRes.dwScope = RESOURCE_CONNECTED;
inRes.dwType = RESOURCETYPE_ANY;
inRes.lpRemoteName = szServ;
DWORD dwRes;
while((dwRes = WNetGetResourceInformation(&inRes, resResult,
&dwBuffSize, &pszSys)) == ERROR_MORE_DATA)
{
resResult = (NETRESOURCE *)realloc(resResult, dwBuffSize);
}
if(dwRes == ERROR_SUCCESS)
{
if(IsResourceReadable(*resResult))
{
NetResourceList::CopyNetResource(Parent, *resResult);
Res = TRUE;
}
}
delete(szServ);
if(Res)
break;
}
free(resResult);
}
}
delete (szRes);
return Res;
}
*/
BOOL NetBrowser::GetResourceInfo(wchar_t *SrcName,LPNETRESOURCE DstNetResource)
{
NETRESOURCE nr = {0};
#ifdef NETWORK_LOGGING
if (LogFile)
fwprintf(LogFile, L"GetResourceInfo %s\n", SrcName);
#endif
NETRESOURCE nrOut [32]; // provide buffer space
NETRESOURCE *lpnrOut = &nrOut [0];
DWORD cbBuffer = sizeof(nrOut);
LPTSTR pszSystem{}; // pointer to variable-length strings
nr.dwDisplayType = RESOURCEDISPLAYTYPE_GENERIC;
nr.dwScope = RESOURCE_GLOBALNET;
nr.dwType = RESOURCETYPE_ANY;
nr.dwUsage = RESOURCEUSAGE_ALL;
nr.lpRemoteName = SrcName;
DWORD dwError=WNetGetResourceInformation(&nr,lpnrOut,&cbBuffer,&pszSystem);
// If the call fails because the buffer is too small,
// call the LocalAlloc function to allocate a larger buffer.
if (dwError == ERROR_MORE_DATA)
{
if ((lpnrOut = (LPNETRESOURCE)LocalAlloc(LMEM_FIXED, cbBuffer)))
dwError = WNetGetResourceInformation(&nr, lpnrOut, &cbBuffer, &pszSystem);
}
if (dwError == NO_ERROR)
{
if (DstNetResource)
NetResourceList::CopyNetResource(*DstNetResource, *lpnrOut);
#ifdef NETWORK_LOGGING
if (LogFile)
fwprintf(LogFile, L"Result:\n");
LogNetResource(*DstNetResource);
#endif
if (lpnrOut != &nrOut [0])
LocalFree(lpnrOut);
return TRUE;
}
#ifdef NETWORK_LOGGING
else
{
if (LogFile)
fwprintf(LogFile, L"error %u\n", GetLastError());
}
#endif
return FALSE;
}
BOOL NetBrowser::GetResourceParent(NETRESOURCE &SrcRes, LPNETRESOURCE DstNetResource)
{
if (CheckFavoriteItem(&SrcRes) ||
Opt.FavoritesFlags & FAVORITES_UPBROWSE_TO_FAVORITES)
{
if (GetFavoritesParent(SrcRes, DstNetResource))
return TRUE;
}
#ifdef NETWORK_LOGGING
if (LogFile)
fwprintf(LogFile, L"GetResourceParent( for:\n");
LogNetResource(SrcRes);
#endif
TSaveScreen ss;
BOOL Ret=FALSE;
NETRESOURCE nrOut [32]; // provide buffer space
NETRESOURCE *lpnrOut = &nrOut [0];
DWORD cbBuffer = sizeof(nrOut);
LPTSTR pszSystem{}; // pointer to variable-length strings
NETRESOURCE nrSrc = SrcRes;
nrSrc.dwDisplayType = RESOURCEDISPLAYTYPE_GENERIC;
nrSrc.dwScope = RESOURCE_GLOBALNET;
nrSrc.dwUsage = 0;
nrSrc.dwType = RESOURCETYPE_ANY;
DWORD dwError=WNetGetResourceInformation(&nrSrc,lpnrOut,&cbBuffer,&pszSystem);
// If the call fails because the buffer is too small,
// call the LocalAlloc function to allocate a larger buffer.
if (dwError == ERROR_MORE_DATA)
{
if ((lpnrOut = (LPNETRESOURCE)LocalAlloc(LMEM_FIXED, cbBuffer)))
dwError = WNetGetResourceInformation(&nrSrc, lpnrOut, &cbBuffer, &pszSystem);
}
if (dwError == NO_ERROR)
{
#ifdef NETWORK_LOGGING
if (LogFile)
fwprintf(LogFile, L"WNetGetResourceInformation() returned:\n");
LogNetResource(*lpnrOut);
#endif
nrSrc.lpProvider=lpnrOut->lpProvider;
if (WNetGetResourceParent(&nrSrc,lpnrOut,&cbBuffer) == NO_ERROR)
{
if (DstNetResource)
NetResourceList::CopyNetResource(*DstNetResource, *lpnrOut);
#ifdef NETWORK_LOGGING
if (LogFile)
fwprintf(LogFile, L"Result:\n");
LogNetResource(*DstNetResource);
#endif
Ret=TRUE;
}
if (lpnrOut != &nrOut [0])
LocalFree(lpnrOut);
}
return Ret;
}
BOOL NetBrowser::EditFavorites()
{
if (!PCurResource)
return TRUE;
// First we should determine the type of Favorite Item under cursor
string Path;
PanelInfo PInfo = {sizeof(PanelInfo)};
PsInfo.PanelControl(this,FCTL_GETPANELINFO,0,&PInfo);
size_t Size = PsInfo.PanelControl(this, FCTL_GETPANELDIRECTORY, 0, nullptr);
FarPanelDirectory* dir = static_cast<FarPanelDirectory*>(malloc(Size));
dir->StructSize = sizeof(FarPanelDirectory);
PsInfo.PanelControl(this, FCTL_GETPANELDIRECTORY, Size, dir);
Path = dir->Name;
free(dir);
if(Path.At(Path.Len()-1) != L'\\')
{
Path+=L"\\";
}
Size = PsInfo.PanelControl(this,FCTL_GETPANELITEM,PInfo.CurrentItem,{});
PluginPanelItem* PPI=(PluginPanelItem*)malloc(Size);
if (PPI)
{
FarGetPluginPanelItem gpi={sizeof(FarGetPluginPanelItem), Size, PPI};
PsInfo.PanelControl(this,FCTL_GETPANELITEM,PInfo.CurrentItem,&gpi);
Path += PPI->FileName;
free(PPI);
}
NETRESOURCE nr = {0};
if (GetFavoriteResource(Path, &nr))
{
Path = nr.lpRemoteName;
switch (nr.dwDisplayType)
{
case RESOURCEDISPLAYTYPE_DOMAIN:
PsInfo.Message(
&MainGuid,
nullptr,
FMSG_ALLINONE,
L"Data",
reinterpret_cast<const wchar_t* const *>(L"This is a domain"),
0,1);
break;
case RESOURCEDISPLAYTYPE_SERVER:
PsInfo.Message(
&MainGuid,
nullptr,
FMSG_ALLINONE,
L"Data",
reinterpret_cast<const wchar_t* const *>(L"This is a SERVER"),
0,1);
break;
default:
PsInfo.Message(
&MainGuid,
nullptr,
FMSG_ALLINONE,
L"Data",
reinterpret_cast<const wchar_t* const *>(Path.CPtr()),
0,1);
}
NetResourceList::DeleteNetResource(nr);
return TRUE;
}
return FALSE;
}
int NetBrowser::ProcessKey(const INPUT_RECORD *Rec)
{
if ((Rec->EventType&(~0x8000))!=KEY_EVENT || !Rec->Event.KeyEvent.bKeyDown)
return FALSE;
int Key=Rec->Event.KeyEvent.wVirtualKeyCode;
int Shift=Rec->Event.KeyEvent.dwControlKeyState&SHIFT_PRESSED;
int Ctrl=Rec->Event.KeyEvent.dwControlKeyState&(LEFT_CTRL_PRESSED|RIGHT_CTRL_PRESSED);
int Alt=Rec->Event.KeyEvent.dwControlKeyState&(LEFT_ALT_PRESSED|RIGHT_ALT_PRESSED);
if (!Ctrl && !Alt && (Key==VK_F5 || Key==VK_F6))
{
if (PCurResource && PCurResource->dwDisplayType == RESOURCEDISPLAYTYPE_SERVER)
{
PanelInfo PInfo = {sizeof(PanelInfo)};
PsInfo.PanelControl(this,FCTL_GETPANELINFO,0,&PInfo);
for (int I=0; I<(int)PInfo.SelectedItemsNumber; I++)
{
const wchar_t *pRemoteName{};
size_t Size = PsInfo.PanelControl(this,FCTL_GETSELECTEDPANELITEM,I,{});
PluginPanelItem* PPI=(PluginPanelItem*)malloc(Size);
if (PPI)
{
FarGetPluginPanelItem gpi={sizeof(FarGetPluginPanelItem), Size, PPI};
PsInfo.PanelControl(this,FCTL_GETSELECTEDPANELITEM,I,&gpi);
pRemoteName = PPI->FileName;
if (!Opt.FullPathShares)
{
for (unsigned J = 0; J < NetList.Count(); ++J)
{
wchar_t RemoteName[MAX_PATH];
GetRemoteName(&NetList[J],RemoteName);
if (FSF.LStricmp(PPI->FileName,RemoteName)==0)
{
pRemoteName = NetList[J].lpRemoteName;
break;
}
}
}
}
if (!PPI||!MapNetworkDrive(pRemoteName, (Key == VK_F6), (Shift==0)))
{
free(PPI);
break;
}
free(PPI);
}
PsInfo.PanelControl(this,FCTL_UPDATEPANEL,0,{});
PsInfo.PanelControl(this,FCTL_REDRAWPANEL,0,{});
}
return(TRUE);
}
else if (Key == L'F' && Ctrl)
{
FileNames2Clipboard(TRUE);
return TRUE;
}
else if (Key == VK_INSERT && Alt && Shift)
{
FileNames2Clipboard(FALSE);
return TRUE;
}
else if (Key == VK_INSERT && Alt && Ctrl)
{
FileNames2Clipboard(FALSE);
return TRUE;
}
else if (Key == VK_F4 && !Alt && !Ctrl && !Shift)
{
PanelInfo PInfo = {sizeof(PanelInfo)};
PsInfo.PanelControl(this,FCTL_GETPANELINFO,0,&PInfo);
size_t Size = PsInfo.PanelControl(this,FCTL_GETSELECTEDPANELITEM,0,{});
PluginPanelItem* PPI=(PluginPanelItem*)malloc(Size);
if (PPI)
{
FarGetPluginPanelItem gpi={sizeof(FarGetPluginPanelItem), Size, PPI};
PsInfo.PanelControl(this,FCTL_GETSELECTEDPANELITEM,0,&gpi);
}
if (PPI&&lstrcmp(PPI->FileName,L".."))
if (ChangeToDirectory(PPI->FileName, OPM_NONE, true))
if (FSF.PointToName(PPI->FileName) -
PPI->FileName <= 2)
{
PsInfo.PanelControl(this,FCTL_UPDATEPANEL,1,{});
PanelRedrawInfo ri = {sizeof(PanelRedrawInfo)};
ri.CurrentItem = ri.TopPanelItem = 0;
PsInfo.PanelControl(this,FCTL_REDRAWPANEL,0,&ri);
}
free(PPI);
return TRUE;
}
else if (Key == VK_F4 && Shift)
{
EditFavorites();
return TRUE;
}
else if (Key == VK_F7 && !Alt && !Ctrl && !Shift)
{
CreateFavSubFolder();
return TRUE;
}
// disable processing of F3 - avoid unnecessary slowdown
else if ((Key == VK_F3 || Key == VK_CLEAR) && !Ctrl && !Shift)
{
return TRUE;
}
else if ((Key == VK_PRIOR || Key == 0xDC) && Ctrl && !PCurResource && !Opt.RootDoublePoint)
{
return TRUE;
}
return FALSE;
}
BOOL NetBrowser::MapNetworkDrive(const wchar_t *RemoteName, BOOL AskDrive, BOOL Permanent)
{
wchar_t AnsiRemoteName[MAX_PATH];
lstrcpy(AnsiRemoteName, RemoteName);
DWORD DriveMask=GetLogicalDrives();
wchar_t NewLocalName[10];
*NewLocalName=0;
if (!AskDrive)
GetFreeLetter(DriveMask,NewLocalName);
else
{
if (!AskMapDrive(NewLocalName, Permanent))
return FALSE;
}
if (*NewLocalName)
{
NETRESOURCE newnr;
// wchar_t LocalName[10];
newnr.dwType=RESOURCETYPE_DISK;
newnr.lpLocalName=NewLocalName;
newnr.lpRemoteName=AnsiRemoteName;
newnr.lpProvider={};
for (;;)
{
if (IsReadable(AnsiRemoteName))
{
if (AddConnection(&newnr,Permanent))
break;
}
else if ((AddConnectionFromFavorites(&newnr, Permanent) || AddConnectionExplicit(&newnr, Permanent)) && IsReadable(newnr.lpLocalName))
break;
else if (ERROR_CANCELLED == GetLastError())
break;
if (GetLastError()==ERROR_DEVICE_ALREADY_REMEMBERED)
{
if (!AskDrive)
{
GetFreeLetter(DriveMask,NewLocalName);
if (*NewLocalName==0)
{
const wchar_t *MsgItems[]={GetMsg(MError),GetMsg(MNoFreeLetters),GetMsg(MOk)};
PsInfo.Message(&MainGuid, nullptr,FMSG_WARNING|FMSG_ERRORTYPE,{},MsgItems,ARRAYSIZE(MsgItems),1);
return FALSE;
}
}
else
{
const wchar_t *MsgItems[]={GetMsg(MError),GetMsg(MAlreadyRemembered),GetMsg(MOk)};
PsInfo.Message(&MainGuid, nullptr,FMSG_WARNING|FMSG_ERRORTYPE,{},MsgItems,ARRAYSIZE(MsgItems),1);
return FALSE;
}
}
else
{
wchar_t MsgText[300];
FSF.sprintf(MsgText,GetMsg(MNetCannotConnect),RemoteName,NewLocalName);
const wchar_t *MsgItems[]={GetMsg(MError),MsgText,GetMsg(MOk)};
PsInfo.Message(&MainGuid, nullptr,FMSG_WARNING|FMSG_ERRORTYPE,{},MsgItems,ARRAYSIZE(MsgItems),1);
return FALSE;
}
}
}
else
{
const wchar_t *MsgItems[]={GetMsg(MError),GetMsg(MNoFreeLetters),GetMsg(MOk)};
PsInfo.Message(&MainGuid, nullptr,FMSG_WARNING|FMSG_ERRORTYPE,{},MsgItems,ARRAYSIZE(MsgItems),1);
return FALSE;
}
return TRUE;
}
BOOL NetBrowser::AskMapDrive(wchar_t *NewLocalName, BOOL &Permanent)
{
int ExitCode = 0;
for (;;)
{
FarMenuItem MenuItems['Z'-'A'+1];
int MenuItemsNumber=0;
memset(MenuItems,0,sizeof(MenuItems));
wchar_t umname[ARRAYSIZE(MenuItems)][4];
memset(umname, 0, sizeof(umname));
for (size_t n = 0; n < ARRAYSIZE(MenuItems); n++)
MenuItems[n].Text = umname[n];
DWORD DriveMask=GetLogicalDrives();
for (int I=0; I<='Z'-'A'; I++)
if ((DriveMask & (1<<I))==0)
FSF.sprintf(const_cast<wchar_t*>(MenuItems[MenuItemsNumber++].Text),L"&%c:",L'A'+I);
MenuItems[ExitCode].Flags = MIF_SELECTED;
if (!MenuItemsNumber)
return FALSE;
const wchar_t *MenuTitle, *MenuBottom;
if (Permanent)
{
MenuTitle = GetMsg(MPermanentTo);
MenuBottom = GetMsg(MToggleTemporary);
}
else
{
MenuTitle = GetMsg(MTemporaryTo);
MenuBottom = GetMsg(MTogglePermanent);
}
FarKey BreakKeys[]={{VK_F6,0}, {0,0}};
intptr_t BreakCode;
ExitCode=(int)PsInfo.Menu(&MainGuid, nullptr,-1,-1,0,0,
MenuTitle,MenuBottom,StrHelpNetBrowse,
BreakKeys,&BreakCode,MenuItems,MenuItemsNumber);
if (ExitCode<0)
return FALSE;
if (BreakCode == -1)
{
lstrcpy(NewLocalName,MenuItems[ExitCode].Text+1);
break;
}
Permanent = !Permanent;
}
return TRUE;
}
void NetBrowser::GetFreeLetter(DWORD &DriveMask,wchar_t *DiskName)
{
*DiskName=0;
for (wchar_t I=2; I<='Z'-'A'; I++)
if ((DriveMask & (1<<I))==0)
{
DriveMask |= 1<<I;
DiskName[0]=L'A'+I;
DiskName[1]=L':';
DiskName[2]=0;
break;
}
}
int NetBrowser::AddConnection(NETRESOURCE *nr,int Remember)
{
NETRESOURCE connectnr=*nr;
DWORD lastErrDebug = WNetAddConnection2(&connectnr,{},{},(Remember?CONNECT_UPDATE_PROFILE:0));
if (lastErrDebug==NO_ERROR)
{
lastErrDebug = GetLastError();
return(TRUE);
}
return(FALSE);
}
int NetBrowser::AddConnectionExplicit(NETRESOURCE *nr, int Remember)
{
wchar_t Name[256],Password[256];
NETRESOURCE connectnr=*nr;
/*static*/ BOOL bSelected = FALSE;
NameAndPassInfo passInfo={connectnr.lpRemoteName,Name,Password,&bSelected};
if (!GetNameAndPassword(&passInfo))
{
SetLastError(ERROR_CANCELLED);
return(FALSE);
}
if (AddConnectionWithLogon(&connectnr, Name, Password, Remember))
{
if (bSelected)
{
FAVORITEITEM Item;
Item.lpRemoteName = connectnr.lpRemoteName;
Item.lpUserName = Name;
Item.lpPassword = Password;
WriteFavoriteItem(&Item, passInfo.szFavoritePath);
}
return TRUE;
}
return FALSE;
}
int NetBrowser::AddConnectionWithLogon(NETRESOURCE *nr, wchar_t *Name, wchar_t *Password, int Remember)
{
for (;;)
{
if (NO_ERROR == WNetAddConnection2(nr,Password,*Name ? Name:nullptr,(Remember?CONNECT_UPDATE_PROFILE:0)))
{
return TRUE;
}
else
{
if (ERROR_SESSION_CREDENTIAL_CONFLICT == GetLastError())
{
//Trying to cancel existing connections
DisconnectFromServer(nr);
if (NO_ERROR == WNetAddConnection2(nr,Password,*Name ? Name:nullptr,(Remember?CONNECT_UPDATE_PROFILE:0)))
{
return TRUE;
}
}
}
if (ERROR_SUCCESS != GetLastError() && Name?(!wcsstr(Name, L"\\")&&!wcsstr(Name, L"@")):FALSE)
{
//If the specified user name does not look like "ComputerName\UserName" nor "User@Domain"
//and the plug-in failed to log on to the remote machine, the specified user name can be
//interpreted as user name of the remote computer, so let's transform it to look like
//"Computer\User"
wchar_t szServer[MAX_PATH];
wchar_t szNameCopy[MAX_PATH];
//make copy of Name
lstrcpy(szNameCopy, Name);
wchar_t *p = nr->lpRemoteName;
int n = (int)(FSF.PointToName(p) - p);
if (n <= 2)
lstrcpyn(szServer, p + n, ARRAYSIZE(szServer));
else
{
while (*++p == L'\\') n--;
if (n > MAX_PATH) n = MAX_PATH;
lstrcpyn(szServer, p, n-1);
}
FSF.sprintf(Name, L"%s\\%s", szServer, szNameCopy);
//Try again to log on with the transformed user name.
continue;
}
return FALSE;
}
}
int NetBrowser::AddConnectionFromFavorites(NETRESOURCE *nr,int Remember)
{
//Try to search login info in registry
if (nr)
{
wchar_t Name[MAX_PATH];
wchar_t Pass[MAX_PATH];
Name[0] = Pass[0] = 0;
FAVORITEITEM Item =
{
nr->lpRemoteName,
lstrlen(nr->lpRemoteName),
Name,
ARRAYSIZE(Name),
Pass,
ARRAYSIZE(Pass)
};
if (ReadFavoriteItem(&Item))
{
return AddConnectionWithLogon(nr, Name, Pass, Remember);
}
}
return FALSE;
}
void NetBrowser::DisconnectFromServer(NETRESOURCE *nr)
{
//First we should know a name of the server
int n = (int)(FSF.PointToName(nr->lpRemoteName) - nr->lpRemoteName);
if (n <= 2)
n = lstrlen(nr->lpRemoteName) + 1;
wchar_t *szServer = (wchar_t*)malloc((n + 1)*sizeof(wchar_t));
if (szServer)
{
wchar_t *szBuff = (wchar_t*)malloc((n + 1)*sizeof(wchar_t));
if (szBuff)
{
lstrcpyn(szServer, nr->lpRemoteName, n);
NETRESOURCE *lpBuff{};
HANDLE hEnum;
if (NO_ERROR == WNetOpenEnum(RESOURCE_CONNECTED, RESOURCETYPE_ANY, 0, {}, &hEnum))
{
DWORD cCount = (DWORD)-1;
DWORD nBuffSize = 0;
//Let's determine buffer's size we need to store all the connections
if (ERROR_MORE_DATA == WNetEnumResource(hEnum, &cCount, {}, &nBuffSize))
{
lpBuff = (NETRESOURCE*)malloc(nBuffSize);
if (lpBuff)
{
cCount = (DWORD)-1;
if (NO_ERROR != WNetEnumResource(hEnum, &cCount, lpBuff, &nBuffSize))
{
free(lpBuff);
lpBuff = {};
}
}
}
WNetCloseEnum(hEnum);
if (lpBuff)
{
for (DWORD i = 0; i < cCount; i++)
{
lstrcpyn(szBuff, lpBuff[i].lpRemoteName, n);
if (0 == lstrcmpi(szServer, szBuff))
WNetCancelConnection2(lpBuff[i].lpRemoteName, 0, TRUE);
}
free(lpBuff);
}
}
free(szBuff);
}
//Trying harder to disconnect from the server
WNetCancelConnection2(szServer, 0, TRUE);
free(szServer);
}
//Let's check the current dir and if it's remote try to change it to %TMP%
wchar_t lpszPath[MAX_PATH];
if (GetCurrentDirectory(MAX_PATH, lpszPath))
{
if (lpszPath[0] == L'\\')
{
ExpandEnvironmentStrings(L"%TMP%", lpszPath, MAX_PATH);
SetCurrentDirectory(lpszPath);
}
}
}
void NetBrowser::GetLocalName(wchar_t *RemoteName,wchar_t *LocalName)
{
*LocalName=0;
if (RemoteName && *RemoteName)
for (int I=ConnectedList.Count()-1; I>=0; I--)
if (ConnectedList [I].lpRemoteName && ConnectedList [I].lpLocalName &&
*ConnectedList [I].lpLocalName &&
lstrcmpi(ConnectedList [I].lpRemoteName,RemoteName)==0)
{
if (ConnectedList [I].dwScope==RESOURCE_CONNECTED ||
ConnectedList [I].dwScope==RESOURCE_REMEMBERED)
lstrcpy(LocalName, ConnectedList[I].lpLocalName);
break;
}
}
int NetBrowser::GetNameAndPassword(NameAndPassInfo* passInfo)
{
static wchar_t LastName[256],LastPassword[256];
PluginDialogBuilder Builder(PsInfo, MainGuid, UserPassDialogGuid, passInfo->Title ? passInfo->Title : L"", StrHelpNetBrowse);
Builder.AddText(MNetUserName);
Builder.AddEditField(LastName, ARRAYSIZE(LastName), 60, L"NetworkUser", true);
Builder.AddText(MNetUserPassword);
Builder.AddPasswordField(LastPassword, ARRAYSIZE(LastPassword), 60);
Builder.AddSeparator();
int disabled = 0;
if (passInfo->pRemember)
Builder.AddCheckbox(MRememberPass, passInfo->pRemember);
else
Builder.AddCheckbox(MRememberPass, &disabled)->Flags |= DIF_DISABLE;
Builder.AddOKCancel(MOk, MCancel);
if (Builder.ShowDialog())
{
lstrcpy(passInfo->Name, LastName);
lstrcpy(passInfo->Password, LastPassword);
return TRUE;
}
return FALSE;
}
void NetBrowser::FileNames2Clipboard(BOOL ToCommandLine)
{
PanelInfo PInfo = {sizeof(PanelInfo)};
PsInfo.PanelControl(this, FCTL_GETPANELINFO,0,&PInfo);
wchar_t *CopyData=nullptr;
long DataSize=0;
if (ToCommandLine)
{
if (PInfo.ItemsNumber > 0)
{
wchar_t CurFile [MAX_PATH];
size_t Size = PsInfo.PanelControl(this,FCTL_GETPANELITEM,PInfo.CurrentItem,{});
PluginPanelItem* PPI=(PluginPanelItem*)malloc(Size);
if (PPI)
{
FarGetPluginPanelItem gpi={sizeof(FarGetPluginPanelItem), Size, PPI};
PsInfo.PanelControl(this,FCTL_GETPANELITEM,PInfo.CurrentItem,&gpi);
lstrcpy(CurFile,PPI->FileName);
free(PPI);
}
if (!lstrcmp(CurFile, L".."))
{
if (!PCurResource)
lstrcpy(CurFile, L".\\");
else
lstrcpy(CurFile, PCurResource->lpRemoteName);
}
FSF.QuoteSpaceOnly(CurFile);
lstrcat(CurFile, L" ");
PsInfo.PanelControl(this, FCTL_INSERTCMDLINE,0,CurFile);
}
return;
}
for (size_t I=0; I < PInfo.SelectedItemsNumber; ++I)
{
if (DataSize > 0)
{
lstrcat(CopyData+DataSize,L"\r\n");
DataSize+=2;
}
size_t Size = PsInfo.PanelControl(this,FCTL_GETSELECTEDPANELITEM,I,{});
PluginPanelItem* PPI=(PluginPanelItem*)malloc(Size);
if (PPI)
{
FarGetPluginPanelItem gpi={sizeof(FarGetPluginPanelItem), Size, PPI};
PsInfo.PanelControl(this,FCTL_GETSELECTEDPANELITEM,I,&gpi);
wchar_t CurFile[MAX_PATH];
lstrcpy(CurFile,PPI->FileName);
if (!lstrcmp(CurFile, L".."))
{
if (!PCurResource)
lstrcpy(CurFile, L".\\");
else
lstrcpy(CurFile, PCurResource->lpRemoteName);
}
FSF.QuoteSpaceOnly(CurFile);
int Length=lstrlen(CurFile);
wchar_t *NewPtr=(wchar_t *)realloc(CopyData, (DataSize+Length+3)*sizeof(wchar_t));
if (!NewPtr)
{
if (CopyData)
{
free(CopyData);
CopyData=nullptr;
}
}
else
{
CopyData=NewPtr;
CopyData[DataSize]=0;
lstrcpy(CopyData+DataSize, CurFile);
DataSize+=Length;
}
free(PPI);
if (!CopyData)
break;
}
}
if (CopyData)
{
FSF.CopyToClipboard(FCT_STREAM,CopyData);
free(CopyData);
}
}
void NetBrowser::ManualConnect()
{
PanelInfo PInfo = {sizeof(PanelInfo)};
PsInfo.PanelControl(this, FCTL_GETPANELINFO,0,&PInfo);
if (PInfo.ItemsNumber)
{
size_t Size = PsInfo.PanelControl(this,FCTL_GETPANELITEM,PInfo.CurrentItem,{});
PluginPanelItem* PPI=(PluginPanelItem*)malloc(Size);
if (PPI)
{
FarGetPluginPanelItem gpi={sizeof(FarGetPluginPanelItem), Size, PPI};
PsInfo.PanelControl(this,FCTL_GETPANELITEM,PInfo.CurrentItem,&gpi);
ChangeToDirectory(PPI->FileName, OPM_NONE, true);
free(PPI);
}
}
}
void NetBrowser::GetRemoteName(NETRESOURCE *NetRes,wchar_t *RemoteName)
{
if (CheckFavoriteItem(NetRes))
{
if (!NetRes->lpRemoteName)
{
lstrcpy(RemoteName, GetMsg(MFavorites));
}
else
{
free(NetRes->lpComment);
NetRes->lpComment = NetResourceList::CopyText(GetMsg(MFavoritesFolder));
lstrcpy(RemoteName, FSF.PointToName(NetRes->lpRemoteName));
}
}
else if (NetRes->lpProvider && (!NetRes->lpRemoteName ||
NetRes->dwDisplayType==RESOURCEDISPLAYTYPE_NETWORK))
lstrcpy(RemoteName,NetRes->lpProvider);
else if (!NetRes->lpRemoteName)
*RemoteName=0;
else if (Opt.FullPathShares)
lstrcpy(RemoteName,NetRes->lpRemoteName);
else
lstrcpy(RemoteName,FSF.PointToName(NetRes->lpRemoteName));
}
BOOL NetBrowser::IsReadable(const wchar_t *Remote)
{
wchar_t Mask[MAX_PATH];
if (*Remote == L'\\' && *(Remote+1) == L'\\')
FSF.sprintf(Mask,L"\\\\?\\UNC%s\\*",Remote+1);
else
FSF.sprintf(Mask,L"%s\\*",Remote);
HANDLE FindHandle;
WIN32_FIND_DATA FindData;
FindHandle=FindFirstFile(Mask,&FindData);
DWORD err = GetLastError();
FindClose(FindHandle);
SetLastError(err);
if (err == ERROR_FILE_NOT_FOUND)
{
SetLastError(0);
return TRUE;
}
return(FindHandle!=INVALID_HANDLE_VALUE);
}
void NetBrowser::SetOpenFromCommandLine(wchar_t *ShareName)
{
//lstrcpy (CmdLinePath, ShareName);
#ifdef NETWORK_LOGGING
LogData(L"SetOpenFromCommandLine ShareName is");
LogData(ShareName);
#endif
lstrcpy(CmdLinePath, ShareName);
/*if(!GotoFavorite(ShareName))
GotoComputer(ShareName);*/
}
BOOL NetBrowser::SetOpenFromFilePanel(wchar_t *ShareName)
{
NETRESOURCE nr;
NetResourceList::InitNetResource(nr);
if (!GetResourceInfo(ShareName, &nr))
return FALSE;
if (!IsMSNetResource(nr))
return FALSE;
OpenFromFilePanel = TRUE;
return TRUE;
}
int NetBrowser::GotoComputer(const wchar_t *Dir)
{
#ifdef NETWORK_LOGGING
LogData(L"Entering GotoComputer");
#endif
// if there are backslashes in the name, truncate them
wchar_t ComputerName [MAX_PATH];
lstrcpy(ComputerName, Dir);
BOOL IsShare = FALSE;
wchar_t *p = wcschr(ComputerName + 2, L'\\'); // skip past leading backslashes
if (p)
{
IsShare = TRUE;
*p = L'\0';
}
else
{
p = wcschr(ComputerName + 2, L'/');
if (p)
{
IsShare = TRUE;
*p = L'\0';
}
}
CharUpper(ComputerName);
NETRESOURCE res;
NetResourceList::InitNetResource(res);
if (!GetResourceInfo(ComputerName, &res))
return FALSE;
/*
if (!IsMSNetResource (res))
return FALSE;
*/
if (!IsResourceReadable(res))
{
int err = GetLastError();
if (err == ERROR_INVALID_PASSWORD || err == ERROR_LOGON_FAILURE || err == ERROR_ACCESS_DENIED || err == ERROR_INVALID_HANDLE || err == ERROR_LOGON_TYPE_NOT_GRANTED)
if (!((AddConnectionFromFavorites(&res)||AddConnectionExplicit(&res))&&IsResourceReadable(res)))
{
if (GetLastError() != ERROR_CANCELLED)
PsInfo.Message(&MainGuid, nullptr, FMSG_WARNING|FMSG_ERRORTYPE|FMSG_MB_OK|FMSG_ALLINONE,
{}, reinterpret_cast<const wchar_t*const*>(GetMsg(MError)), 0, 0);
return FALSE;
}
}
CurResource = res;
PCurResource = &CurResource;
/*int result = */PsInfo.PanelControl(this, FCTL_UPDATEPANEL,0,{});
if (IsShare)
{
wchar_t ShareName [MAX_PATH];
lstrcpy(ShareName, Dir);
// replace forward slashes with backslashes
for (p = ShareName; *p; p++)
if (*p == L'/')
*p = L'\\';
SetCursorToShare(ShareName);
}
else
PsInfo.PanelControl(this, FCTL_REDRAWPANEL,0,{});
return TRUE;
}
void NetBrowser::GotoLocalNetwork()
{
TSaveScreen ss;
wchar_t ComputerName [MAX_PATH];
lstrcpy(ComputerName, L"\\\\");
DWORD ComputerNameLength = MAX_PATH-3;
if (!GetComputerName(ComputerName+2, &ComputerNameLength))
return;
NETRESOURCE res;
NetResourceList::InitNetResource(res);
if (!GetResourceInfo(ComputerName, &res) || !IsMSNetResource(res))
return;
NETRESOURCE parent;
NetResourceList::InitNetResource(parent);
if (!GetResourceParent(res, &parent))
return;
NetResourceList::CopyNetResource(CurResource, parent);
PCurResource = &CurResource;
PsInfo.PanelControl(this, FCTL_UPDATEPANEL,0,{});
PsInfo.PanelControl(this, FCTL_REDRAWPANEL,0,{});
}
void NetBrowser::SetCursorToShare(wchar_t *Share)
{
PanelInfo PInfo = {sizeof(PanelInfo)};
// this returns the items in sorted order, so we can position correctly
PsInfo.PanelControl(this, FCTL_GETPANELINFO,0,&PInfo);
if (PInfo.ItemsNumber)
{
// prevent recursion
for (int i=0; i<(int)PInfo.ItemsNumber; i++)
{
wchar_t szAnsiName[MAX_PATH];
size_t Size = PsInfo.PanelControl(this,FCTL_GETPANELITEM,i,{});
PluginPanelItem* PPI=(PluginPanelItem*)malloc(Size);
if (PPI)
{
FarGetPluginPanelItem gpi={sizeof(FarGetPluginPanelItem), Size, PPI};
PsInfo.PanelControl(this,FCTL_GETPANELITEM,i,&gpi);
lstrcpy(szAnsiName,PPI->FileName);
free(PPI);
}
if (!FSF.LStricmp(szAnsiName, Opt.FullPathShares?Share:FSF.PointToName(Share)))
{
PanelRedrawInfo info={sizeof(PanelRedrawInfo)};
info.CurrentItem = i;
info.TopPanelItem = 0;
PsInfo.PanelControl(this, FCTL_REDRAWPANEL,0,&info);
break;
}
}
}
}
void WINAPI ExitFARW(const ExitInfo *Info)
{
delete CommonRootResources;
NetResourceList::DeleteNetResource(CommonCurResource);
}
void NetBrowser::RemoveItems()
{
if (!CheckFavoriteItem(PCurResource))
return;
// We are in Favorites folder, so we can remove items from this folder
PanelInfo PInfo = {sizeof(PanelInfo)};
PsInfo.PanelControl(this,FCTL_GETPANELINFO,0,&PInfo);
if (PInfo.SelectedItemsNumber <= 0) // Something strange is happen
{
return;
}
wchar_t szConfirmation[MAX_PATH*2];
if (PInfo.SelectedItemsNumber == 1)
{
size_t Size = PsInfo.PanelControl(this,FCTL_GETSELECTEDPANELITEM,0,{});
PluginPanelItem* PPI=(PluginPanelItem*)malloc(Size);
if (PPI)
{
FarGetPluginPanelItem gpi={sizeof(FarGetPluginPanelItem), Size, PPI};
PsInfo.PanelControl(this,FCTL_GETSELECTEDPANELITEM,0,&gpi);
FSF.sprintf(szConfirmation, GetMsg(MRemoveFavItem), PPI->FileName);
free(PPI);
}
}
else // PInfo.SelectedItemsNumber > 1
FSF.sprintf(szConfirmation, GetMsg(MRemoveFavItems), PInfo.SelectedItemsNumber);
const wchar_t* Msg[4];
Msg[0] = GetMsg(MRemoveFavCaption);
Msg[1] = szConfirmation;
Msg[2] = GetMsg(MOk);
Msg[3] = GetMsg(MCancel);
if (0 != PsInfo.Message(&MainGuid, nullptr, FMSG_WARNING, L"RemoveItemFav", Msg,
ARRAYSIZE(Msg), 2))
{
return; // User canceled deletion
}
wchar_t szName[MAX_PATH*2] = {0};
lstrcpy(szName, PCurResource->lpRemoteName);
wchar_t* p = szName + lstrlen(szName);
if ((p>szName)&&(p[-1] != L'\\'))
*p++ = L'\\';
for (int i = 0; i < (int)PInfo.SelectedItemsNumber; i++)
{
size_t Size = PsInfo.PanelControl(this,FCTL_GETSELECTEDPANELITEM,i,{});
PluginPanelItem* PPI=(PluginPanelItem*)malloc(Size);
if (PPI)
{
FarGetPluginPanelItem gpi={sizeof(FarGetPluginPanelItem), Size, PPI};
PsInfo.PanelControl(this,FCTL_GETSELECTEDPANELITEM,i,&gpi);
lstrcpy(p,PPI->FileName);
free(PPI);
}
RemoveFromFavorites(szName, {}, {});
}
PsInfo.PanelControl(this, FCTL_UPDATEPANEL,0,{});
PsInfo.PanelControl(this, FCTL_REDRAWPANEL,0,{});
}
void NetBrowser::CreateFavSubFolder()
{
if (!CheckFavoriteItem(PCurResource))
return;
wchar_t buff[MAX_PATH];
if (DlgCreateFolder(buff, ARRAYSIZE(buff)))
{
if (!CreateSubFolder(PCurResource->lpRemoteName, buff))
{
ShowMessage(L"Failed to create folder");
return;
}
PsInfo.PanelControl(this,FCTL_UPDATEPANEL,0,{});
PsInfo.PanelControl(this,FCTL_REDRAWPANEL,0,{});
}
}
void NetBrowser::GetHiddenShares()
{
wchar_t lpwsNetPath[MAX_PATH];
PSHARE_INFO_1 BufPtr, p;
NET_API_STATUS res;
if (!PCurResource) return;
LPTSTR lpszServer = PCurResource->lpRemoteName;
wchar_t szResPath [MAX_PATH];
LPTSTR pszSystem;
NETRESOURCE pri;
NETRESOURCE nr [256];
DWORD er=0,tr=0,resume=0,rrsiz;
lstrcpyn(lpwsNetPath,lpszServer,ARRAYSIZE(lpwsNetPath));
do
{
res = NetShareEnum((LPWSTR)lpwsNetPath, 1, (LPBYTE *) &BufPtr, MAX_PREFERRED_LENGTH, &er, &tr, &resume);
if (res == ERROR_SUCCESS || res == ERROR_MORE_DATA)
{
p=BufPtr;
for (DWORD J=0; J < er; J++)
{
memset((void *)&pri,0,sizeof(pri));
pri.dwScope = RESOURCE_GLOBALNET;
pri.dwType = RESOURCETYPE_DISK;
pri.lpLocalName = {};
lstrcpy(szResPath,lpszServer);
lstrcat(szResPath,L"\\");
{
size_t pos = lstrlen(szResPath);
lstrcpyn(&szResPath[pos], p->shi1_netname, (int)(ARRAYSIZE(szResPath)-pos));
}
if (szResPath[lstrlen(szResPath)-1] == L'$' &&
lstrcmp(&szResPath[lstrlen(szResPath)-4],L"IPC$"))
{
pri.lpRemoteName = szResPath;
pri.dwUsage = RESOURCEUSAGE_CONTAINER;
pri.lpProvider = {};
rrsiz = sizeof(nr);
// we need to provide buffer space for WNetGetResourceInformation
int rc = WNetGetResourceInformation(&pri,(void *)&nr [0],&rrsiz,&pszSystem);
if (rc!=NO_ERROR)
{
p++;
continue;
//break; //?????
}
switch(p->shi1_type)
{
case STYPE_DISKTREE:
case STYPE_SPECIAL:
nr [0].dwType=RESOURCETYPE_DISK;
break;
case STYPE_PRINTQ:
nr [0].dwType=RESOURCETYPE_PRINT;
break;
}
NetList.Push(nr [0]);
}
p++;
}
NetApiBufferFree(BufPtr);
}
if (res == ERROR_SUCCESS)
break;
}
while (res==ERROR_MORE_DATA);
}
| 24.161212
| 166
| 0.68446
|
sergey-rybalkin
|
eb685b31fd956d02cfffb90953d0aed7332dca02
| 7,299
|
cpp
|
C++
|
apps/yscnproc.cpp
|
cyanpencil/yocto-gl
|
ee0ff506e762bed1ae580e6413c2ea395ef40ac1
|
[
"MIT"
] | 1
|
2018-03-14T22:43:25.000Z
|
2018-03-14T22:43:25.000Z
|
apps/yscnproc.cpp
|
cyanpencil/yocto-gl
|
ee0ff506e762bed1ae580e6413c2ea395ef40ac1
|
[
"MIT"
] | null | null | null |
apps/yscnproc.cpp
|
cyanpencil/yocto-gl
|
ee0ff506e762bed1ae580e6413c2ea395ef40ac1
|
[
"MIT"
] | null | null | null |
//
// LICENSE:
//
// Copyright (c) 2016 -- 2017 Fabio Pellacini
//
// 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.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
#include "../yocto/yocto_gl.h"
using namespace ygl;
#include <algorithm>
#include <array>
#include <memory>
void mkdir(const string& dir) {
if (dir == "" || dir == "." || dir == ".." || dir == "./" || dir == "../")
return;
#ifndef _MSC_VER
system(("mkdir -p " + dir).c_str());
#else
system(("mkdir " + dir).c_str());
#endif
}
void validate_texture_paths(scene* obj, const string& filename) {
auto dirname = path_dirname(filename);
for (auto txt : obj->textures) {
auto f = fopen((dirname + txt->path).c_str(), "rb");
if (!f)
printf("Missing texture: %s\n", txt->path.c_str());
else
fclose(f);
}
}
int main(int argc, char** argv) {
// command line params
using namespace string_literals;
auto parser = make_parser(argc, argv, "yobj2gltf", "converts obj to gltf");
auto textures = parse_flag(parser, "--textures", "-t", "process textures");
auto no_flipy_texcoord = parse_flag(
parser, "--no-flipy-texcoord", "", "texcoord vertical flipping");
auto no_flip_opacity =
parse_flag(parser, "--no-flip-opacity", "", "flip opacity");
auto facet_non_smooth = parse_flag(
parser, "--facet-non-smooth", "", "facet non smooth surfaces");
auto scale = parse_opt(parser, "--scale", "", "scale the model", 1.0f);
auto flipyz = parse_flag(parser, "--flipyz", "", "flip y and z coords");
auto add_scene = parse_flag(parser, "--scene", "", "add scene");
auto add_normals = parse_flag(parser, "--normals", "", "add normals");
auto tesselation =
parse_opt(parser, "--tesselation", "-T", "tesselation level", 0);
auto subdiv =
parse_opt(parser, "--subdiv", "", "Catmull-Clark subdivision", 0);
// auto add_specgloss =
// parse_flag( "--specgloss", "", "add spec gloss");
auto save_separate_buffers =
parse_flag(parser, "--separate-buffers", "", "save separate buffers");
auto info = parse_flag(parser, "--print-info", "", "print information");
auto validate_textures =
parse_flag(parser, "--validate-textures", "", "validate texture paths");
auto validate =
parse_flag(parser, "--validate", "", "validate after saving");
auto output = parse_opt(
parser, "--output", "-o", "output scene filename", "out.obj"s);
auto filenames =
parse_args(parser, "scenes", "input scene filenames", vector<string>{});
if (should_exit(parser)) {
printf("%s\n", get_usage(parser).c_str());
exit(1);
}
// load obj
auto scn = unique_ptr<scene>(new scene());
for (auto filename : filenames) {
auto to_merge = unique_ptr<scene>(nullptr);
try {
auto opts = load_options();
opts.load_textures = textures;
opts.obj_flip_texcoord = !no_flipy_texcoord;
opts.obj_flip_tr = !no_flip_opacity;
opts.obj_facet_non_smooth = facet_non_smooth;
opts.preserve_quads = true;
to_merge = unique_ptr<scene>(load_scene(filename, opts));
} catch (const exception& e) {
log_fatal("unable to load file %s with error {}\n",
filename.c_str(), e.what());
}
// check missing texture
if (validate_textures) validate_texture_paths(to_merge.get(), filename);
// print information
if (info) {
printf("information ------------------------\n");
printf("filename: %s\n", filename.c_str());
print_info(to_merge.get());
}
// merge the scene into the other
if (filenames.size() > 1) {
merge_into(scn.get(), to_merge.get());
} else {
swap(scn, to_merge);
}
}
// print information
if (info && filenames.size() > 1) {
printf("information ------------------------\n");
printf("merged\n");
print_info(scn.get());
}
// add missing elements
{
auto opts = add_elements_options::none();
opts.default_names = true;
opts.smooth_normals = add_normals;
opts.shape_instances = add_scene;
opts.default_paths = true;
add_elements(scn.get(), opts);
}
// process geometry
if (scale != 1.0f) {
for (auto shp : scn->shapes) {
for (auto& p : shp->pos) p *= scale;
}
}
if (flipyz) {
for (auto shp : scn->shapes) {
for (auto& p : shp->pos) swap(p.y, p.z);
for (auto& n : shp->norm) swap(n.y, n.z);
}
}
if (tesselation) {
for (auto shp : scn->shapes) {
for (auto l = 0; l < tesselation; l++) { subdivide_shape(shp); }
}
}
if (subdiv) {
for (auto shp : scn->shapes) {
for (auto l = 0; l < subdiv; l++) { subdivide_shape(shp, true); }
}
}
// print infomation again if needed
if (info and scale != 1.0f) {
printf("post-correction information -------\n");
printf("output: %s\n", output.c_str());
print_info(scn.get());
}
// make a directory if needed
try {
mkdir(path_dirname(output));
} catch (const exception& e) {
log_fatal("unable to make directory %s with error {}\n",
path_dirname(output), e.what());
}
// save scene
try {
auto opts = save_options();
opts.save_textures = textures;
opts.gltf_separate_buffers = save_separate_buffers;
save_scene(output, scn.get(), opts);
} catch (const exception& e) {
log_fatal("unable to save scene %s with error {}\n", output.c_str(),
e.what());
}
// validate
if (validate) {
auto vscn = unique_ptr<scene>(load_scene(output));
if (info) {
printf("validate information -----------------\n");
print_info(vscn.get());
}
}
// done
return 0;
}
| 34.757143
| 80
| 0.591999
|
cyanpencil
|
eb68870ac37f9ac64b30535c9e56b7b474d0be97
| 2,710
|
cpp
|
C++
|
turtleProgram.cpp
|
TabithaRoemish/CSS343_Assignment1
|
238741f2b676b657cb71ec8545b1b6b0f7932cdf
|
[
"Unlicense"
] | null | null | null |
turtleProgram.cpp
|
TabithaRoemish/CSS343_Assignment1
|
238741f2b676b657cb71ec8545b1b6b0f7932cdf
|
[
"Unlicense"
] | null | null | null |
turtleProgram.cpp
|
TabithaRoemish/CSS343_Assignment1
|
238741f2b676b657cb71ec8545b1b6b0f7932cdf
|
[
"Unlicense"
] | null | null | null |
// File Name: TurtleProgram.cpp
// Programmer: Tabitha Roemish
// File contains: TurtleProgram class definitions
#include "TurtleProgram.h"
#include <iostream>
using namespace std;
//constructor
TurtleProgram::TurtleProgram(string direction, string angleOrLength)
{
turtleArray = new string[2]; //beginning length of array - commands come in pairs
turtleArray[0] = direction;
turtleArray[1] = angleOrLength;
length = 2; // beginning length of array - commands come in pairs
}
//copy constructor
TurtleProgram::TurtleProgram(const TurtleProgram& turtle)
{
this->setLength(turtle.length);
turtleArray = new string[length];
for (int i = 0; i < length; i++)
turtleArray[i] = turtle.turtleArray[i];
}
//ostream overload (not a friend, defined out of class)
ostream& operator<< (ostream& out, const TurtleProgram& turtle)
{
for (int i = 0; i < turtle.getLength(); i++)
{
out << turtle.getIndex(i);
out << " ";
}
return out;
}
//boolean comparisons
bool TurtleProgram::operator==(const TurtleProgram& turtle) const
{
string baseTurtle = "";
string compareTurtle = "";
for (int i = 0; i < turtle.getLength(); i++)
baseTurtle += turtle.turtleArray[i];
for (int l = 0; l < this->getLength(); l++)
compareTurtle += this->turtleArray[l];
return (baseTurtle == compareTurtle);
}
bool TurtleProgram::operator!=(const TurtleProgram& turtle) const
{
bool answer = false;
if (turtle == *this)
answer = true;
return answer;
}
//assignment operator
TurtleProgram& TurtleProgram::operator=(const TurtleProgram& turtle)
{
if (this == &turtle)
return *this;
else
{
this->setLength(turtle.length);
delete[] turtleArray;
turtleArray = new string[length];
for (int i = 0; i < length; i++)
turtleArray[i] = turtle.turtleArray[i];
}
return *this;
}
//arithmetic overloads
const TurtleProgram TurtleProgram::operator+(const TurtleProgram& turtle) const
{
TurtleProgram answer;
int size = turtle.getLength() + this->getLength();
answer.setLength(size);
answer.turtleArray = new string[size];
for (int i = 0; i < this->getLength(); i++)
answer.turtleArray[i] = this->turtleArray[i];
for (int m = 0; m < turtle.getLength(); m++)
answer.turtleArray[m + this->getLength()] = turtle.turtleArray[m];
return answer;
}
TurtleProgram& TurtleProgram::operator+=(const TurtleProgram& turtle)
{
return *this = *this + turtle;
}
const TurtleProgram TurtleProgram::operator*(int multiplier) const
{
TurtleProgram answer;
for (int x = 0; x < multiplier; x++)
{
answer += *this;
}
return answer;
}
TurtleProgram& TurtleProgram::operator*=(int multiplier)
{
TurtleProgram answer;
answer = *this * multiplier;
*this = answer;
return *this;
}
| 21.507937
| 83
| 0.694465
|
TabithaRoemish
|
eb6c8507eddcb466173b93bc844e3e01a176d735
| 9,114
|
cpp
|
C++
|
riscv/llvm/3.5/cfe-3.5.0.src/test/SemaCXX/decl-microsoft-call-conv.cpp
|
tangyibin/goblin-core
|
1940db6e95908c81687b2b22ddd9afbc8db9cdfe
|
[
"BSD-3-Clause"
] | null | null | null |
riscv/llvm/3.5/cfe-3.5.0.src/test/SemaCXX/decl-microsoft-call-conv.cpp
|
tangyibin/goblin-core
|
1940db6e95908c81687b2b22ddd9afbc8db9cdfe
|
[
"BSD-3-Clause"
] | null | null | null |
riscv/llvm/3.5/cfe-3.5.0.src/test/SemaCXX/decl-microsoft-call-conv.cpp
|
tangyibin/goblin-core
|
1940db6e95908c81687b2b22ddd9afbc8db9cdfe
|
[
"BSD-3-Clause"
] | 1
|
2021-03-24T06:40:32.000Z
|
2021-03-24T06:40:32.000Z
|
// RUN: %clang_cc1 -triple i686-pc-win32 -fms-extensions -verify %s
// RUN: %clang_cc1 -triple i686-pc-mingw32 -verify %s
// RUN: %clang_cc1 -triple i686-pc-mingw32 -fms-extensions -verify %s
typedef void void_fun_t();
typedef void __cdecl cdecl_fun_t();
// Pointers to free functions
void free_func_default(); // expected-note 2 {{previous declaration is here}}
void __cdecl free_func_cdecl(); // expected-note 2 {{previous declaration is here}}
void __stdcall free_func_stdcall(); // expected-note 2 {{previous declaration is here}}
void __fastcall free_func_fastcall(); // expected-note 2 {{previous declaration is here}}
void __cdecl free_func_default();
void __stdcall free_func_default(); // expected-error {{function declared 'stdcall' here was previously declared without calling convention}}
void __fastcall free_func_default(); // expected-error {{function declared 'fastcall' here was previously declared without calling convention}}
void free_func_cdecl();
void __stdcall free_func_cdecl(); // expected-error {{function declared 'stdcall' here was previously declared 'cdecl'}}
void __fastcall free_func_cdecl(); // expected-error {{function declared 'fastcall' here was previously declared 'cdecl'}}
void free_func_stdcall();
void __cdecl free_func_stdcall(); // expected-error {{function declared 'cdecl' here was previously declared 'stdcall'}}
void __fastcall free_func_stdcall(); // expected-error {{function declared 'fastcall' here was previously declared 'stdcall'}}
void __cdecl free_func_fastcall(); // expected-error {{function declared 'cdecl' here was previously declared 'fastcall'}}
void __stdcall free_func_fastcall(); // expected-error {{function declared 'stdcall' here was previously declared 'fastcall'}}
void free_func_fastcall();
// Overloaded functions may have different calling conventions
void __fastcall free_func_default(int);
void __cdecl free_func_default(int *);
void __thiscall free_func_cdecl(char *);
void __cdecl free_func_cdecl(double);
typedef void void_fun_t();
typedef void __cdecl cdecl_fun_t();
// Pointers to member functions
struct S {
void member_default1(); // expected-note {{previous declaration is here}}
void member_default2();
void __cdecl member_cdecl1();
void __cdecl member_cdecl2(); // expected-note {{previous declaration is here}}
void __thiscall member_thiscall1();
void __thiscall member_thiscall2(); // expected-note {{previous declaration is here}}
// Typedefs carrying the __cdecl convention are adjusted to __thiscall.
void_fun_t member_typedef_default; // expected-note {{previous declaration is here}}
cdecl_fun_t member_typedef_cdecl1; // expected-note {{previous declaration is here}}
cdecl_fun_t __cdecl member_typedef_cdecl2;
void_fun_t __stdcall member_typedef_stdcall;
// Static member functions can't be __thiscall
static void static_member_default1();
static void static_member_default2();
static void static_member_default3(); // expected-note {{previous declaration is here}}
static void __cdecl static_member_cdecl1();
static void __cdecl static_member_cdecl2(); // expected-note {{previous declaration is here}}
static void __stdcall static_member_stdcall1();
static void __stdcall static_member_stdcall2();
// Variadic functions can't be other than default or __cdecl
void member_variadic_default(int x, ...);
void __cdecl member_variadic_cdecl(int x, ...);
static void static_member_variadic_default(int x, ...);
static void __cdecl static_member_variadic_cdecl(int x, ...);
};
void __cdecl S::member_default1() {} // expected-error {{function declared 'cdecl' here was previously declared without calling convention}}
void __thiscall S::member_default2() {}
void __cdecl S::member_typedef_default() {} // expected-error {{function declared 'cdecl' here was previously declared without calling convention}}
void __cdecl S::member_typedef_cdecl1() {} // expected-error {{function declared 'cdecl' here was previously declared without calling convention}}
void __cdecl S::member_typedef_cdecl2() {}
void __stdcall S::member_typedef_stdcall() {}
void S::member_cdecl1() {}
void __thiscall S::member_cdecl2() {} // expected-error {{function declared 'thiscall' here was previously declared 'cdecl'}}
void S::member_thiscall1() {}
void __cdecl S::member_thiscall2() {} // expected-error {{function declared 'cdecl' here was previously declared 'thiscall'}}
void S::static_member_default1() {}
void __cdecl S::static_member_default2() {}
void __stdcall S::static_member_default3() {} // expected-error {{function declared 'stdcall' here was previously declared without calling convention}}
void S::static_member_cdecl1() {}
void __stdcall S::static_member_cdecl2() {} // expected-error {{function declared 'stdcall' here was previously declared 'cdecl'}}
void __cdecl S::member_variadic_default(int x, ...) { (void)x; }
void S::member_variadic_cdecl(int x, ...) { (void)x; }
void __cdecl S::static_member_variadic_default(int x, ...) { (void)x; }
void S::static_member_variadic_cdecl(int x, ...) { (void)x; }
// Declare a template using a calling convention.
template <class CharT> inline int __cdecl mystrlen(const CharT *str) {
int i;
for (i = 0; str[i]; i++) { }
return i;
}
extern int sse_strlen(const char *str);
template <> inline int __cdecl mystrlen(const char *str) {
return sse_strlen(str);
}
void use_tmpl(const char *str, const int *ints) {
mystrlen(str);
mystrlen(ints);
}
struct MixedCCStaticOverload {
static void overloaded(int a);
static void __stdcall overloaded(short a);
};
void MixedCCStaticOverload::overloaded(int a) {}
void MixedCCStaticOverload::overloaded(short a) {}
// Friend function decls are cdecl by default, not thiscall. Friend method
// decls should always be redeclarations, because the class cannot be
// incomplete.
struct FriendClass {
void friend_method() {}
};
void __stdcall friend_stdcall1() {}
class MakeFriendDecls {
int x;
friend void FriendClass::friend_method();
friend void friend_default();
friend void friend_stdcall1();
friend void __stdcall friend_stdcall2();
friend void friend_stdcall3(); // expected-note {{previous declaration is here}}
};
void friend_default() {}
void __stdcall friend_stdcall3() {} // expected-error {{function declared 'stdcall' here was previously declared without calling convention}}
void __stdcall friend_stdcall2() {}
// Test functions with multiple attributes.
void __attribute__((noreturn)) __stdcall __attribute__((regparm(1))) multi_attribute(int x);
void multi_attribute(int x) { __builtin_unreachable(); }
// expected-error@+2 {{stdcall and cdecl attributes are not compatible}}
// expected-error@+1 {{fastcall and cdecl attributes are not compatible}}
void __cdecl __cdecl __stdcall __cdecl __fastcall multi_cc(int x);
template <typename T> void __stdcall StdcallTemplate(T) {}
template <> void StdcallTemplate<int>(int) {}
template <> void __stdcall StdcallTemplate<short>(short) {}
// FIXME: Note the template, not the implicit instantiation.
// expected-error@+2 {{function declared 'cdecl' here was previously declared 'stdcall}}
// expected-note@+1 {{previous declaration is here}}
template <> void __cdecl StdcallTemplate<long>(long) {}
struct ExactlyInt {
template <typename T> static int cast_to_int(T) {
return T::this_is_not_an_int();
}
};
template <> inline int ExactlyInt::cast_to_int<int>(int x) { return x; }
namespace test2 {
class foo {
template <typename T> void bar(T v);
};
extern template void foo::bar(const void *);
}
namespace test3 {
struct foo {
typedef void bar();
};
bool zed(foo::bar *);
void bah() {}
void baz() { zed(bah); }
}
namespace test4 {
class foo {
template <typename T> static void bar(T v);
};
extern template void foo::bar(const void *);
}
namespace test5 {
template <class T>
class valarray {
void bar();
};
extern template void valarray<int>::bar();
}
namespace test6 {
struct foo {
int bar();
};
typedef int bar_t();
void zed(bar_t foo::*) {
}
void baz() {
zed(&foo::bar);
}
}
namespace test7 {
template <typename T>
struct S {
void f(T t) {
t = 42;
}
};
template<> void S<void*>::f(void*);
void g(S<void*> s, void* p) {
s.f(p);
}
}
namespace test8 {
template <typename T>
struct S {
void f(T t) { // expected-note {{previous declaration is here}}
t = 42; // expected-error {{assigning to 'void *' from incompatible type 'int'}}
}
};
template<> void __cdecl S<void*>::f(void*); // expected-error {{function declared 'cdecl' here was previously declared without calling convention}}
void g(S<void*> s, void* p) {
s.f(p); // expected-note {{in instantiation of member function 'test8::S<void *>::f' requested here}}
}
}
| 38.948718
| 152
| 0.709129
|
tangyibin
|
eb6ef146561771bc2168224e093c45b1914351a4
| 862
|
hpp
|
C++
|
include/msqlite/detail/onerror.hpp
|
ricardocosme/msqlite
|
95af5b04831c7af449f87346301b6e26bf749e9f
|
[
"MIT"
] | 19
|
2020-08-18T21:25:05.000Z
|
2022-01-14T03:45:41.000Z
|
include/msqlite/detail/onerror.hpp
|
ricardocosme/msqlite
|
95af5b04831c7af449f87346301b6e26bf749e9f
|
[
"MIT"
] | null | null | null |
include/msqlite/detail/onerror.hpp
|
ricardocosme/msqlite
|
95af5b04831c7af449f87346301b6e26bf749e9f
|
[
"MIT"
] | null | null | null |
#pragma once
#include "msqlite/error.hpp"
#include <type_traits>
namespace msqlite::detail {
template<typename Expected,
typename F,
typename Ret =
std::invoke_result_t<F, typename std::remove_reference_t<Expected>::error_type>
>
void onerror(Expected&& exp,
F&& f,
std::enable_if_t<
std::is_same_v<Ret, void>>* = nullptr)
{
if(!exp) f(exp.error());
}
template<typename Expected,
typename F,
typename Ret =
std::invoke_result_t<F, typename std::remove_reference_t<Expected>::error_type>
>
typename std::remove_reference_t<Expected>::value_type
onerror(Expected&& exp,
F&& f,
std::enable_if_t<
!std::is_same_v<Ret, void>>* = nullptr)
{
if(!exp) return f(exp.error());
return *std::forward<Expected>(exp);
}
}
| 23.297297
| 88
| 0.607889
|
ricardocosme
|
eb706a9a5e5f79a208868260e7c9b0d6d633540d
| 1,331
|
hpp
|
C++
|
components/document/support/platform_compat.hpp
|
jinntechio/RocketJoe
|
9b08a21fda1609c57b40ef8b9750897797ac815b
|
[
"BSD-3-Clause"
] | 7
|
2019-06-02T12:04:22.000Z
|
2019-10-15T18:01:21.000Z
|
components/document/support/platform_compat.hpp
|
jinntechio/RocketJoe
|
9b08a21fda1609c57b40ef8b9750897797ac815b
|
[
"BSD-3-Clause"
] | 26
|
2019-10-27T12:58:42.000Z
|
2020-05-30T16:43:48.000Z
|
components/document/support/platform_compat.hpp
|
jinntechio/RocketJoe
|
9b08a21fda1609c57b40ef8b9750897797ac815b
|
[
"BSD-3-Clause"
] | 1
|
2020-05-25T09:28:46.000Z
|
2020-05-25T09:28:46.000Z
|
#pragma once
#include <components/document/core/base.hpp>
#ifdef _MSC_VER
#define NOINLINE __declspec(noinline)
#define ALWAYS_INLINE inline
#define ASSUME(cond) __assume(cond)
#define LITECORE_UNUSED
#define __typeof decltype
#define __func__ __FUNCTION__
#include <BaseTsd.h>
typedef SSIZE_T ssize_t;
#define MAXFLOAT FLT_MAX
#define __printflike(A, B)
#define cbl_strdup _strdup
#define cbl_getcwd _getcwd
#include <winapifamily.h>
#else
#define LITECORE_UNUSED __attribute__((unused))
#define NOINLINE __attribute((noinline))
#if __has_attribute(always_inline)
#define ALWAYS_INLINE __attribute__((always_inline)) inline
#else
#define ALWAYS_INLINE inline
#endif
#if __has_builtin(__builtin_assume)
#define ASSUME(cond) __builtin_assume(cond)
#else
#define ASSUME(cond) (void(0))
#endif
#ifndef __printflike
#define __printflike(fmtarg, firstvararg) __attribute__((__format__ (__printf__, fmtarg, firstvararg)))
#endif
#define cbl_strdup strdup
#define cbl_getcwd getcwd
#endif
| 27.163265
| 107
| 0.602554
|
jinntechio
|
eb71610feddf6fa21386c0d51d519425a099abdc
| 29
|
cpp
|
C++
|
projects/Vk_11/src/renderer.cpp
|
AnselmoGPP/Vulkan_samples
|
9aaefcff024962b41539be70a9179e78856ff6a7
|
[
"MIT"
] | null | null | null |
projects/Vk_11/src/renderer.cpp
|
AnselmoGPP/Vulkan_samples
|
9aaefcff024962b41539be70a9179e78856ff6a7
|
[
"MIT"
] | null | null | null |
projects/Vk_11/src/renderer.cpp
|
AnselmoGPP/Vulkan_samples
|
9aaefcff024962b41539be70a9179e78856ff6a7
|
[
"MIT"
] | null | null | null |
#include "renderer.hpp"
| 7.25
| 24
| 0.62069
|
AnselmoGPP
|
eb72277e8f1d53772dec414047f2080ff97ec505
| 262
|
cpp
|
C++
|
digitCount.cpp
|
terminatorx0x0/C-LanguageCode
|
0a03106eb26f16ef82c4ca29791f244561ffb336
|
[
"Apache-2.0"
] | null | null | null |
digitCount.cpp
|
terminatorx0x0/C-LanguageCode
|
0a03106eb26f16ef82c4ca29791f244561ffb336
|
[
"Apache-2.0"
] | null | null | null |
digitCount.cpp
|
terminatorx0x0/C-LanguageCode
|
0a03106eb26f16ef82c4ca29791f244561ffb336
|
[
"Apache-2.0"
] | null | null | null |
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
char c[100];
int x,i,count=0;
cout<<"Enter the number";
cin>>c;
x=strlen(c);
for ( i = 0; i < x; i++)
{
count++;
}
cout<<count;
}
| 15.411765
| 30
| 0.473282
|
terminatorx0x0
|
eb86da84cfdc1aa0fd2d0c33335fdac3badc9924
| 1,187
|
cpp
|
C++
|
kdrive/src/knx/telegrams/cemi/RfAdditionalInfo.cpp
|
weinzierl-engineering/baos
|
306acc8e86da774fdeecec042dcf99734677fdc0
|
[
"MIT"
] | 34
|
2015-09-16T10:10:14.000Z
|
2022-02-19T16:11:04.000Z
|
kdrive/src/knx/telegrams/cemi/RfAdditionalInfo.cpp
|
weinzierl-engineering/baos
|
306acc8e86da774fdeecec042dcf99734677fdc0
|
[
"MIT"
] | 17
|
2017-01-02T15:26:19.000Z
|
2022-01-20T01:27:24.000Z
|
kdrive/src/knx/telegrams/cemi/RfAdditionalInfo.cpp
|
weinzierl-engineering/baos
|
306acc8e86da774fdeecec042dcf99734677fdc0
|
[
"MIT"
] | 20
|
2016-12-12T22:18:08.000Z
|
2022-03-15T16:20:20.000Z
|
#include "pch/kdrive_pch.h"
#include "kdrive/knx/telegrams/cemi/RfAdditionalInfo.h"
using namespace kdrive::knx;using namespace kdrive::knx::cemi;z7a67187a0a::
z7a67187a0a(){addFormatter(&zff3b419262);addFormatter(&z4bd60052e2);addFormatter
(&z24086b7caf);addFormatter(&z8a729e8447);addFormatter(&z1261f544f8);}
z7a67187a0a::~z7a67187a0a(){}bool z7a67187a0a::isValid()const{return(zbfd7d2bb9b
()==TypeId)&&(getLength()==Length);}void z7a67187a0a::setDefaults(){Formatter::
setDefaults();zff3b419262.set(TypeId);z4bd60052e2.set(Length);}unsigned char
z7a67187a0a::zbfd7d2bb9b()const{return zff3b419262.get();}unsigned char
z7a67187a0a::getLength()const{return z4bd60052e2.get();}void z7a67187a0a::
ze08fc529a9(unsigned char zee6bb9ea1d){z24086b7caf.set(zee6bb9ea1d);}unsigned
char z7a67187a0a::z0d337d47d5()const{return z24086b7caf.get();}void z7a67187a0a
::setAddress(const std::vector<unsigned char>&address){z8a729e8447.set(address);
}std::vector<unsigned char>z7a67187a0a::getAddress()const{return z8a729e8447.get
();}void z7a67187a0a::zf7a93e33ac(unsigned char zf5c66aa14d){z1261f544f8.set(
zf5c66aa14d);}unsigned char z7a67187a0a::z0821ada427()const{return z1261f544f8.
get();}
| 62.473684
| 80
| 0.804549
|
weinzierl-engineering
|
eb88cbe7a2b979ced34789b3d7f886041af0d7cd
| 80
|
hpp
|
C++
|
test/hncrypt_test_providers.hpp
|
vladp72/hcrypt
|
6f265e38d27a5c92e882a06c629aa8a2b6ad6c45
|
[
"MIT"
] | 3
|
2019-09-09T04:58:51.000Z
|
2022-02-02T02:24:31.000Z
|
test/hncrypt_test_providers.hpp
|
vladp72/hcrypt
|
6f265e38d27a5c92e882a06c629aa8a2b6ad6c45
|
[
"MIT"
] | null | null | null |
test/hncrypt_test_providers.hpp
|
vladp72/hcrypt
|
6f265e38d27a5c92e882a06c629aa8a2b6ad6c45
|
[
"MIT"
] | 2
|
2021-10-19T10:28:08.000Z
|
2022-02-02T05:22:44.000Z
|
#pragma once
#include "hcrypt_test_helpers.hpp"
void test_ncrypt_providers();
| 13.333333
| 34
| 0.8
|
vladp72
|
eb8f621378f1fa43c75512d7ca17c4268992996c
| 1,359
|
cpp
|
C++
|
2dSpriteGame/Monkey/classes/mage.cpp
|
ScottRMcleod/CPLUSPLUS
|
94352ddf374b048fab960c1e7d5b2000d08ab399
|
[
"Unlicense"
] | null | null | null |
2dSpriteGame/Monkey/classes/mage.cpp
|
ScottRMcleod/CPLUSPLUS
|
94352ddf374b048fab960c1e7d5b2000d08ab399
|
[
"Unlicense"
] | null | null | null |
2dSpriteGame/Monkey/classes/mage.cpp
|
ScottRMcleod/CPLUSPLUS
|
94352ddf374b048fab960c1e7d5b2000d08ab399
|
[
"Unlicense"
] | null | null | null |
#include "stdwx.h"
#include "mage.h"
#include "fireball.h"
#include "iceBall.h"
#include "level.h"
Mage::Mage(Level *l,DrawEngine *de, int s_index, float x, float y,
int lives, int mana, char spell_key, char up_key, char down_key,
char left_key, char right_key)
: Character(l,de,s_index,x,y,lives,up_key,down_key,left_key,right_key)
{
spellKey = spell_key;
classID = MAGE_CLASSID;
manaLevel = mana;
}
bool Mage::keyPress(char c)
{
bool val = Character::keyPress(c);
if(val == false)
{
if(c==spellKey)
{
castSpell();
return true;
}
}
return val;
}
void Mage::castSpell(void)
{
if(facingDirection.x == 0 && facingDirection.y == 0)
return;
if(facingDirection.y < -1 && facingDirection.y < -1)
return;
if(manaLevel > 0)
{
manaLevel -= 2;
Fireball *temp = new Fireball(level, drawArea,SPRITE_FIREBALL,
(int)pos.x+facingDirection.x, (int)pos.y+facingDirection.y,
facingDirection.x, facingDirection.y);
if(temp->move(facingDirection.x, facingDirection.y))
{
temp->idleUpdate();
level->addNPC((Sprite *)temp);
}
else
delete temp;
}
update();
}
int Mage::getMana(void)
{
return manaLevel;
}
void Mage::setMana(int amount)
{
manaLevel += amount;
}
void Mage::addLives(int num)
{
Character::addLives(num);
manaLevel = 50;
}
| 20.283582
| 74
| 0.640912
|
ScottRMcleod
|
eb923b30465e5a9b4b5d1cf19500b6b35f300399
| 262
|
hpp
|
C++
|
headers/Fields.hpp
|
BasiqueEvangelist/Purpuri
|
ad028d9527b7485afe0510f90b32c2dcc2689b1a
|
[
"MIT"
] | 7
|
2021-04-25T22:26:00.000Z
|
2021-12-30T21:37:31.000Z
|
headers/Fields.hpp
|
BasiqueEvangelist/Purpuri
|
ad028d9527b7485afe0510f90b32c2dcc2689b1a
|
[
"MIT"
] | 1
|
2021-06-11T22:48:45.000Z
|
2021-06-11T22:48:45.000Z
|
headers/Fields.hpp
|
BasiqueEvangelist/Purpuri
|
ad028d9527b7485afe0510f90b32c2dcc2689b1a
|
[
"MIT"
] | 4
|
2021-02-25T23:52:13.000Z
|
2021-11-21T02:36:36.000Z
|
/**************
* GEMWIRE *
* PURPURI *
**************/
#include <stdint.h>
#include "Common.hpp"
struct FieldData {
uint16_t Access;
uint16_t Name;
uint16_t Descriptor;
uint16_t AttributeCount;
struct AttributeData* Attributes;
};
| 17.466667
| 37
| 0.587786
|
BasiqueEvangelist
|
eb93e0b875b1fb73293ac1a60315ddc5eacf9b99
| 929
|
cpp
|
C++
|
0024-swap-nodes-in-pairs.cpp
|
Jamesweng/leetcode
|
1711a2a0e31d831e40137203c9abcba0bf56fcad
|
[
"Apache-2.0"
] | 106
|
2019-06-08T15:23:45.000Z
|
2020-04-04T17:56:54.000Z
|
0024-swap-nodes-in-pairs.cpp
|
Jamesweng/leetcode
|
1711a2a0e31d831e40137203c9abcba0bf56fcad
|
[
"Apache-2.0"
] | null | null | null |
0024-swap-nodes-in-pairs.cpp
|
Jamesweng/leetcode
|
1711a2a0e31d831e40137203c9abcba0bf56fcad
|
[
"Apache-2.0"
] | 3
|
2019-07-13T05:51:29.000Z
|
2020-04-04T17:56:57.000Z
|
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* p1 = head;
if (head == NULL) return NULL;
if (head->next == NULL) return head;
ListNode* p2 = head->next;
ListNode* newhead = p2;
while (p2 != NULL) {
if (p2->next == NULL) {
p2->next = p1;
p1->next = NULL;
break;
}
ListNode* p3 = p2->next;
ListNode* p4 = p3->next;
p2->next = p1;
if (p4 != NULL) {
p1->next = p4;
} else {
p1->next = p3;
}
p1 = p3;
p2 = p4;
}
return newhead;
}
};
| 22.658537
| 46
| 0.38859
|
Jamesweng
|
eb96e89b5f25fd84b6d01aac27938486a3ca354e
| 6,060
|
cpp
|
C++
|
src/common/InQueue.cpp
|
Maximus5/git-bug-1
|
a52853b683dde57cbd29e943299ab46451c542f4
|
[
"BSD-3-Clause"
] | 1
|
2015-05-08T22:47:13.000Z
|
2015-05-08T22:47:13.000Z
|
src/common/InQueue.cpp
|
Maximus5/git-bug-1
|
a52853b683dde57cbd29e943299ab46451c542f4
|
[
"BSD-3-Clause"
] | null | null | null |
src/common/InQueue.cpp
|
Maximus5/git-bug-1
|
a52853b683dde57cbd29e943299ab46451c542f4
|
[
"BSD-3-Clause"
] | null | null | null |
/*
Copyright (c) 2009-2012 Maximus5
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. The name of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <Windows.h>
#include <WinCon.h>
#ifdef _DEBUG
#include <stdio.h>
#endif
#include "../common/common.hpp"
#include "../common/ConEmuCheck.h"
#include "../common/WObjects.h"
#include "InQueue.h"
#define DEBUGSTRINPUTEVENT(s) //DEBUGSTR(s) // SetEvent(this->hInputEvent)
BOOL InQueue::Initialize(int MaxInputQueue, HANDLE ahInputEvent/*by value*/)
{
this->nUsedLen = 0;
this->nMaxInputQueue = MaxInputQueue;
this->hInputEvent = ahInputEvent;
this->pInputQueue = (INPUT_RECORD*)calloc(this->nMaxInputQueue, sizeof(INPUT_RECORD));
if (!this->pInputQueue)
return FALSE;
this->pInputQueueEnd = this->pInputQueue+this->nMaxInputQueue;
this->pInputQueueWrite = this->pInputQueue;
this->pInputQueueRead = this->pInputQueueEnd;
return TRUE;
}
void InQueue::Release()
{
SafeFree(this->pInputQueue);
}
// this->nMaxInputQueue = CE_MAX_INPUT_QUEUE_BUFFER;
BOOL InQueue::WriteInputQueue(const INPUT_RECORD *pr, BOOL bSetEvent /*= TRUE*/, DWORD nLength /*= 1*/)
{
// Передернуть буфер (записать в консоль то, что накопилось)
if (pr == NULL)
{
if (bSetEvent)
{
DEBUGSTRINPUTEVENT(L"SetEvent(this->hInputEvent)\n");
if (this->hInputEvent)
SetEvent(this->hInputEvent);
}
return TRUE;
}
const INPUT_RECORD *pSrc = pr;
while (nLength--)
{
INPUT_RECORD* pNext = this->pInputQueueWrite;
// Проверяем, есть ли свободное место в буфере
if (this->pInputQueueRead != this->pInputQueueEnd)
{
if (this->pInputQueueRead < this->pInputQueueEnd
&& ((this->pInputQueueWrite+1) == this->pInputQueueRead))
{
return FALSE;
}
}
// OK
*pNext = *(pSrc++);
this->pInputQueueWrite++;
InterlockedIncrement(&nUsedLen);
if (this->pInputQueueWrite >= this->pInputQueueEnd)
this->pInputQueueWrite = this->pInputQueue;
// Могут писать "пачку", тогда подождать ее окончания
if (bSetEvent && !nLength)
{
DEBUGSTRINPUTEVENT(L"SetEvent(this->hInputEvent)\n");
if (this->hInputEvent)
SetEvent(this->hInputEvent);
}
// Подвинуть указатель чтения, если до этого буфер был пуст
if (this->pInputQueueRead == this->pInputQueueEnd)
this->pInputQueueRead = pNext;
}
return TRUE;
}
BOOL InQueue::IsInputQueueEmpty()
{
if (this->pInputQueueRead != this->pInputQueueEnd
&& this->pInputQueueRead != this->pInputQueueWrite)
{
return FALSE;
}
return TRUE;
}
BOOL InQueue::ReadInputQueue(INPUT_RECORD *prs, DWORD *pCount, BOOL bNoRemove /*= FALSE*/)
{
DWORD nCount = 0;
if (!IsInputQueueEmpty())
{
DWORD n = *pCount;
INPUT_RECORD *pSrc = this->pInputQueueRead;
INPUT_RECORD *pEnd = (this->pInputQueueRead < this->pInputQueueWrite) ? this->pInputQueueWrite : this->pInputQueueEnd;
INPUT_RECORD *pDst = prs;
while (n && pSrc < pEnd)
{
*pDst = *pSrc; nCount++; pSrc++;
InterlockedDecrement(&nUsedLen);
//// Для приведения поведения к стандартному RealConsole&Far
//if (pDst->EventType == KEY_EVENT
// // Для нажатия НЕ символьных клавиш
// && pDst->Event.KeyEvent.bKeyDown && pDst->Event.KeyEvent.uChar.UnicodeChar < 32
// && pSrc < (pEnd = (this->pInputQueueRead < this->pInputQueueWrite) ? this->pInputQueueWrite : this->pInputQueueEnd)) // и пока в буфере еще что-то есть
//{
// while (pSrc < (pEnd = (this->pInputQueueRead < this->pInputQueueWrite) ? this->pInputQueueWrite : this->pInputQueueEnd)
// && pSrc->EventType == KEY_EVENT
// && pSrc->Event.KeyEvent.bKeyDown
// && pSrc->Event.KeyEvent.wVirtualKeyCode == pDst->Event.KeyEvent.wVirtualKeyCode
// && pSrc->Event.KeyEvent.wVirtualScanCode == pDst->Event.KeyEvent.wVirtualScanCode
// && pSrc->Event.KeyEvent.uChar.UnicodeChar == pDst->Event.KeyEvent.uChar.UnicodeChar
// && pSrc->Event.KeyEvent.dwControlKeyState == pDst->Event.KeyEvent.dwControlKeyState)
// {
// pDst->Event.KeyEvent.wRepeatCount++; pSrc++;
// }
//}
n--; pDst++;
}
if (pSrc == this->pInputQueueEnd)
pSrc = this->pInputQueue;
TODO("Доделать чтение начала буфера, если считали его конец");
//
if (!bNoRemove)
{
this->pInputQueueRead = pSrc;
}
}
*pCount = nCount;
return (nCount>0);
}
BOOL InQueue::GetNumberOfBufferEvents()
{
DWORD nCount = 0;
if (!IsInputQueueEmpty())
{
INPUT_RECORD *pSrc = this->pInputQueueRead;
INPUT_RECORD *pEnd = (this->pInputQueueRead < this->pInputQueueWrite) ? this->pInputQueueWrite : this->pInputQueueEnd;
while (pSrc < pEnd)
{
nCount++; pSrc++;
}
if (pSrc == this->pInputQueueEnd)
{
pSrc = this->pInputQueue;
pEnd = (this->pInputQueueRead < this->pInputQueueWrite) ? this->pInputQueueWrite : this->pInputQueueEnd;
while(pSrc < pEnd)
{
nCount++; pSrc++;
}
}
}
return nCount;
}
| 29.560976
| 157
| 0.712706
|
Maximus5
|
eb972e40904f382ce16f02cd927648a972ed8d9c
| 2,997
|
cc
|
C++
|
src/vcash/GwMakerVcash.cc
|
duguyifang/btcpool
|
0127a750b3b26a515e66261cbd9ad7f95c54de01
|
[
"MIT"
] | 585
|
2016-08-20T22:25:49.000Z
|
2021-03-11T15:13:54.000Z
|
src/vcash/GwMakerVcash.cc
|
immense055/btcpool
|
0127a750b3b26a515e66261cbd9ad7f95c54de01
|
[
"MIT"
] | 335
|
2016-09-22T02:58:02.000Z
|
2021-03-08T07:19:13.000Z
|
src/vcash/GwMakerVcash.cc
|
immense055/btcpool
|
0127a750b3b26a515e66261cbd9ad7f95c54de01
|
[
"MIT"
] | 443
|
2016-08-20T17:56:54.000Z
|
2021-03-11T04:10:42.000Z
|
/*
The MIT License (MIT)
Copyright (C) 2017 vcash Labs Ltd.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "GwMakerVcash.h"
#include "Utils.h"
#include <glog/logging.h>
#include <limits.h>
///////////////////////////////GwMakerHandlerVcash////////////////////////////////////
bool GwMakerHandlerVcash::checkFields(JsonNode &r) {
if (r["prev_hash"].type() != Utilities::JS::type::Str ||
r["cur_hash"].type() != Utilities::JS::type::Str ||
r["bits"].type() != Utilities::JS::type::Int ||
r["base_rewards"].type() != Utilities::JS::type::Int ||
r["transactions_fee"].type() !=
Utilities::JS::type::Int || // maybe double
r["height"].type() != Utilities::JS::type::Int) {
return false;
}
return true;
}
string GwMakerHandlerVcash::constructRawMsg(JsonNode &r) {
LOG(INFO) << "chain: " << def_.chainType_ << ", topic: " << def_.rawGwTopic_
<< ", prev hash: " << r["prev_hash"].str()
<< ", block hash for merge mining: " << r["cur_hash"].str()
<< ", bits: " << r["bits"].uint32()
<< ", height: " << r["height"].uint64()
<< ", fees paid to miner: " << r["base_rewards"].uint64()
<< ", transactions_fee: " << r["transactions_fee"].uint64();
return Strings::Format(
"{\"created_at_ts\":%u,"
"\"chainType\":\"%s\","
"\"vcashdRpcAddress\":\"%s\","
"\"vcashdRpcUserPwd\":\"%s\","
"\"bits\":%" PRIu32
","
"\"parentBlockHash\":\"%s\","
"\"blockHashForMergedMining\":\"%s\","
"\"baserewards\":%" PRIu64
","
"\"transactionsfee\":%" PRIu64
","
"\"height\": %" PRIu64 "}",
(uint32_t)time(nullptr),
def_.chainType_.c_str(),
def_.rpcAddr_.c_str(),
def_.rpcUserPwd_.c_str(),
r["bits"].uint32(),
r["prev_hash"].str().c_str(),
r["cur_hash"].str().c_str(),
r["base_rewards"].uint64(),
r["transactions_fee"].uint64(),
r["height"].uint64());
}
| 37
| 86
| 0.612279
|
duguyifang
|
eba0669d8be57cba5d4aa999689636595c656465
| 5,722
|
cpp
|
C++
|
tsMuxer/dvbSubStreamReader.cpp
|
alexls74/tsMuxer
|
451ec61a50a4f6e1859e7ae3dd4b3b99729af1a6
|
[
"Apache-2.0"
] | null | null | null |
tsMuxer/dvbSubStreamReader.cpp
|
alexls74/tsMuxer
|
451ec61a50a4f6e1859e7ae3dd4b3b99729af1a6
|
[
"Apache-2.0"
] | null | null | null |
tsMuxer/dvbSubStreamReader.cpp
|
alexls74/tsMuxer
|
451ec61a50a4f6e1859e7ae3dd4b3b99729af1a6
|
[
"Apache-2.0"
] | 1
|
2021-02-13T00:23:15.000Z
|
2021-02-13T00:23:15.000Z
|
#include "dvbSubStreamReader.h"
#if 1
const static uint64_t TS_FREQ_TO_INT_FREQ_COEFF = INTERNAL_PTS_FREQ / PCR_FREQUENCY;
static const int BAD_FRAME = -1;
int DVBSubStreamReader::getTSDescriptor(uint8_t* dstBuff) { return 0; }
uint8_t* DVBSubStreamReader::findFrame(uint8_t* buff, uint8_t* end)
{
if (m_firstFrame)
return buff;
else
return buff + 1;
}
#define READ_OFFSET(a) (m_big_offsets ? AV_RB32(a) : AV_RB16(a))
int DVBSubStreamReader::decodeFrame(uint8_t* buff, uint8_t* end, int& skipBytes, int& skipBeforeBytes)
{
skipBytes = 0;
skipBeforeBytes = 0;
int rez;
rez = intDecodeFrame(buff, end);
if (rez <= 0)
return rez;
int64_t currentTime = m_start_display_time;
int nextRez;
nextRez = intDecodeFrame(buff + rez, end);
if (nextRez <= 0)
return rez;
m_frameDuration = m_start_display_time - currentTime;
return rez;
}
int DVBSubStreamReader::intDecodeFrame(uint8_t* buff, uint8_t* end)
{
return 0; // not working yet
unsigned pos, cmd, x1, y1, x2, y2, offset1, offset2, next_cmd_pos;
unsigned cmd_pos, is_8bit = 0;
const uint8_t* yuv_palette = 0;
uint8_t colormap[4], alpha[256];
int date;
int i;
int is_menu = 0;
int buf_size = end - buff;
if (buf_size < 10)
return NOT_ENOUGH_BUFFER;
m_start_display_time = 0;
m_end_display_time = 0;
if (m_firstFrame)
{
if (AV_RB16(buff) == 0)
{ // HD subpicture with 4-byte offsets
m_big_offsets = 1;
m_offset_size = 4;
}
else
{
m_big_offsets = 0;
m_offset_size = 2;
}
m_firstFrame = false;
}
else
{
if (m_big_offsets && AV_RB16(buff) != 0)
return BAD_FRAME;
if (!m_big_offsets && AV_RB16(buff) == 0)
return BAD_FRAME;
}
cmd_pos = 2 + m_big_offsets * 4;
// int frameSize = READ_OFFSET(buff);
cmd_pos = READ_OFFSET(buff + cmd_pos);
while ((cmd_pos + 2 + m_offset_size) < buf_size)
{
date = AV_RB16(buff + cmd_pos);
next_cmd_pos = READ_OFFSET(buff + cmd_pos + 2);
pos = cmd_pos + 2 + m_offset_size;
offset1 = -1;
offset2 = -1;
x1 = y1 = x2 = y2 = 0;
bool breakFlag = false;
while (pos < buf_size && !breakFlag)
{
cmd = buff[pos++];
switch (cmd)
{
case 0x00:
// menu subpicture
is_menu = 1;
break;
case 0x01:
// set start date
m_start_display_time = (date << 10) * TS_FREQ_TO_INT_FREQ_COEFF;
break;
case 0x02:
// set end date
m_end_display_time = (date << 10) * TS_FREQ_TO_INT_FREQ_COEFF;
break;
case 0x03:
// set colormap
if ((buf_size - pos) < 2)
return NOT_ENOUGH_BUFFER;
colormap[3] = buff[pos] >> 4;
colormap[2] = buff[pos] & 0x0f;
colormap[1] = buff[pos + 1] >> 4;
colormap[0] = buff[pos + 1] & 0x0f;
pos += 2;
break;
case 0x04:
// set alpha
if ((buf_size - pos) < 2)
return NOT_ENOUGH_BUFFER;
alpha[3] = buff[pos] >> 4;
alpha[2] = buff[pos] & 0x0f;
alpha[1] = buff[pos + 1] >> 4;
alpha[0] = buff[pos + 1] & 0x0f;
pos += 2;
break;
case 0x05:
case 0x85:
if ((buf_size - pos) < 6)
return NOT_ENOUGH_BUFFER;
x1 = (buff[pos] << 4) | (buff[pos + 1] >> 4);
x2 = ((buff[pos + 1] & 0x0f) << 8) | buff[pos + 2];
y1 = (buff[pos + 3] << 4) | (buff[pos + 4] >> 4);
y2 = ((buff[pos + 4] & 0x0f) << 8) | buff[pos + 5];
if (cmd & 0x80)
is_8bit = 1;
pos += 6;
break;
case 0x06:
if ((buf_size - pos) < 4)
return NOT_ENOUGH_BUFFER;
offset1 = AV_RB16(buff + pos);
offset2 = AV_RB16(buff + pos + 2);
pos += 4;
break;
case 0x86:
if ((buf_size - pos) < 8)
return NOT_ENOUGH_BUFFER;
offset1 = AV_RB32(buff + pos);
offset2 = AV_RB32(buff + pos + 4);
pos += 8;
break;
case 0x83:
// HD set palette
if ((buf_size - pos) < 768)
return NOT_ENOUGH_BUFFER;
yuv_palette = buff + pos;
pos += 768;
break;
case 0x84:
// HD set contrast (alpha)
if ((buf_size - pos) < 256)
return NOT_ENOUGH_BUFFER;
for (i = 0; i < 256; i++) alpha[i] = 0xFF - buff[pos + i];
pos += 256;
break;
case 0xff:
default:
if (next_cmd_pos == cmd_pos)
return (pos + 1) & 0xfffffffe;
cmd_pos = next_cmd_pos;
breakFlag = true;
break;
}
}
}
return NOT_ENOUGH_BUFFER;
}
double DVBSubStreamReader::getFrameDurationNano() { return m_frameDuration; }
const std::string DVBSubStreamReader::getStreamInfo()
{
if (m_big_offsets)
return "HD-DVD subpicture";
else
return "Subpicture";
}
#endif
| 29.647668
| 102
| 0.477106
|
alexls74
|
eba120fac8036230a9f0c0175c2129f33014e4c8
| 922
|
cpp
|
C++
|
cmdstan/stan/lib/stan_math/test/unit/math/prim/arr/fun/array_builder_test.cpp
|
yizhang-cae/torsten
|
dc82080ca032325040844cbabe81c9a2b5e046f9
|
[
"BSD-3-Clause"
] | null | null | null |
cmdstan/stan/lib/stan_math/test/unit/math/prim/arr/fun/array_builder_test.cpp
|
yizhang-cae/torsten
|
dc82080ca032325040844cbabe81c9a2b5e046f9
|
[
"BSD-3-Clause"
] | null | null | null |
cmdstan/stan/lib/stan_math/test/unit/math/prim/arr/fun/array_builder_test.cpp
|
yizhang-cae/torsten
|
dc82080ca032325040844cbabe81c9a2b5e046f9
|
[
"BSD-3-Clause"
] | null | null | null |
#include <stan/math/prim/arr.hpp>
#include <gtest/gtest.h>
using std::vector;
using stan::math::array_builder;
TEST(MathArray,arrayBuilder) {
EXPECT_EQ(0U, array_builder<double>().array().size());
vector<double> v3
= array_builder<double>()
.add(1)
.add(3)
.add(2)
.array();
EXPECT_EQ(3U,v3.size());
EXPECT_FLOAT_EQ(1.0, v3[0]);
EXPECT_FLOAT_EQ(3.0, v3[1]);
EXPECT_FLOAT_EQ(2.0, v3[2]);
vector<vector<int> > v3v2
= array_builder<vector<int> >()
.add(array_builder<int>().add(1).add(2).array())
.add(array_builder<int>().add(3).add(4).array())
.add(array_builder<int>().add(5).add(6).array())
.array();
EXPECT_EQ(3U,v3v2.size());
for (size_t i = 0; i < 3; ++i)
EXPECT_EQ(2U,v3v2[i].size());
EXPECT_EQ(1,v3v2[0][0]);
EXPECT_EQ(2,v3v2[0][1]);
EXPECT_EQ(3,v3v2[1][0]);
EXPECT_EQ(4,v3v2[1][1]);
EXPECT_EQ(5,v3v2[2][0]);
EXPECT_EQ(6,v3v2[2][1]);
}
| 23.641026
| 56
| 0.612798
|
yizhang-cae
|
eba17cf674189dd15f02d921f6cafbd92f39ee0c
| 8,752
|
cpp
|
C++
|
plugins/cinema4dsdk/source/other/command_test.cpp
|
urender-vt/cinema4d_cpp_sdk_extended
|
77235d2e382d1536e0e694609929dbb74883072a
|
[
"Apache-2.0"
] | 23
|
2018-09-05T21:11:07.000Z
|
2022-01-12T10:43:17.000Z
|
plugins/cinema4dsdk/source/other/command_test.cpp
|
urender-vt/cinema4d_cpp_sdk_extended
|
77235d2e382d1536e0e694609929dbb74883072a
|
[
"Apache-2.0"
] | null | null | null |
plugins/cinema4dsdk/source/other/command_test.cpp
|
urender-vt/cinema4d_cpp_sdk_extended
|
77235d2e382d1536e0e694609929dbb74883072a
|
[
"Apache-2.0"
] | 4
|
2019-07-12T16:57:20.000Z
|
2021-06-23T15:33:09.000Z
|
#include "c4d_basetag.h"
#include "c4d_baseobject.h"
#include "c4d_objectdata.h"
#include "c4d_basedocument.h"
#include "c4d_basedraw.h"
#include "c4d.h"
#include "main.h"
#include "command_test.h"
namespace maxon
{
class PaintObject : public ObjectData
{
INSTANCEOF(PaintObject, ObjectData)
public:
PaintObject() = default;
~PaintObject() { }
static NodeData *Alloc() { return NewObjClear(PaintObject); }
virtual void Free(GeListNode *node)
{
_positions.Reset();
}
virtual Bool Init(GeListNode *node)
{
return true;
}
virtual Bool Message(GeListNode* node, Int32 type, void* data)
{
return SUPER::Message(node, type, data);
}
virtual DRAWRESULT Draw(BaseObject* op, DRAWPASS drawpass, BaseDraw* bd, BaseDrawHelp* bh)
{
BaseDocument* doc = bd->GetDocument();
if (!doc)
return DRAWRESULT::SKIP;
if (bd != doc->GetRenderBaseDraw())
return DRAWRESULT::SKIP;
bd->SetMatrix_Screen();
bd->LineStripBegin();
Int count = _positions.GetCount();
for (Int i = 0; i < _positions.GetCount(); ++i)
{
bd->LineStrip(_positions[i], GetViewColor(VIEWCOLOR_YAXIS), 0);
}
if (count > 2)
{
bd->LineStrip(_positions[0], GetViewColor(VIEWCOLOR_YAXIS), 0);
}
bd->LineStripEnd();
return DRAWRESULT::OK;
}
BaseArray<Vector>& GetPositions()
{
return _positions;
}
private:
BaseArray<Vector> _positions;
};
static const Int32 ID_PAINT_OBJECT = 990020202;
class PaintCommandImpl : public Component<PaintCommandImpl, CommandClassInterface, CommandInteractionClassInterface>
{
MAXON_COMPONENT(NORMAL);
public:
MAXON_METHOD Result<COMMANDSTATE> GetState(CommandDataRef& data) const
{
return COMMANDSTATE::ENABLED;
}
MAXON_METHOD Result<COMMANDRESULT> Execute(CommandDataRef& data) const
{
iferr_scope;
BaseArray<Vector> positions;
POLYLINE_DRAW shape = data.Get(COMMAND::POLYLINE::DRAW) iferr_return;
Vector start = data.GetOrDefault(COMMAND::POLYLINE::START);
Vector end = data.GetOrDefault(COMMAND::POLYLINE::END);
switch (shape)
{
case POLYLINE_DRAW::LINE:
positions.Resize(2) iferr_return;
positions[0] = start;
positions[1] = end;
break;
case POLYLINE_DRAW::BOX:
positions.Resize(4) iferr_return;
positions[0] = start;
positions[1] = Vector(start.x, end.y, 0.0);
positions[2] = end;
positions[3] = Vector(end.x, start.y, 0.0);
break;
default:
break;
}
data.Set(COMMAND::POLYLINE::POSITIONS, std::move(positions)) iferr_return;
return COMMANDRESULT::OK;
}
MAXON_METHOD Result<COMMANDRESULT> Interact(CommandDataRef& data, INTERACTIONTYPE interactionType) const
{
iferr_scope;
if (interactionType != INTERACTIONTYPE::ITERATE)
return COMMANDRESULT::OK;
POLYLINE_DRAW shape = data.Get(COMMAND::POLYLINE::DRAW) iferr_return;
BaseArray<Vector> positions = data.Get(COMMAND::POLYLINE::POSITIONS) iferr_return;
Vector end = data.Get(COMMAND::POLYLINE::END) iferr_return;
switch (shape)
{
case POLYLINE_DRAW::LINE:
positions[1] = end;
break;
case POLYLINE_DRAW::BOX:
positions[1].y = end.y;
positions[2] = end;
positions[3].x = end.x;
break;
default:
break;
}
data.Set(COMMAND::POLYLINE::POSITIONS, std::move(positions)) iferr_return;
return COMMANDRESULT::OK;
}
};
MAXON_COMPONENT_OBJECT_REGISTER(PaintCommandImpl, CommandClasses, "net.maxonexample.command.paint");
} // namespace maxon
static const Int32 ID_PAINT_TOOL = 990020203;
class PaintTool : public DescriptionToolData
{
public:
virtual Int32 GetToolPluginId() { return ID_PAINT_TOOL; }
virtual const String GetResourceSymbol() { return String(); }
void InitDefaultSettings(BaseDocument* doc, BaseContainer& data)
{
DescriptionToolData::InitDefaultSettings(doc, data);
}
virtual Int32 GetState(BaseDocument* doc)
{
return CMD_ENABLED;
}
virtual Bool MouseInput(BaseDocument* doc, BaseContainer& data, BaseDraw* bd, EditorWindow* win, const BaseContainer& msg)
{
BaseObject* op = nullptr;
BaseContainer bc;
BaseContainer device;
Int32 button = NOTOK;
Float dx = 0.0;
Float dy = 0.0;
Float mouseX = msg.GetFloat(BFM_INPUT_X);
Float mouseY = msg.GetFloat(BFM_INPUT_Y);
Bool ctrl = msg.GetInt32(BFM_INPUT_QUALIFIER) & QCTRL;
Bool shift = msg.GetInt32(BFM_INPUT_QUALIFIER) & QSHIFT;
switch (msg.GetInt32(BFM_INPUT_CHANNEL))
{
case BFM_INPUT_MOUSELEFT : button = KEY_MLEFT; break;
case BFM_INPUT_MOUSERIGHT: button = KEY_MRIGHT; break;
default: return true;
}
AutoAlloc<AtomArray>opList;
if (!opList)
return false;
doc->GetActiveObjects(*opList, GETACTIVEOBJECTFLAGS::CHILDREN);
if (opList->GetCount() <= 0)
return true;
op = static_cast<BaseObject*>(opList->GetIndex(0));
if (!op)
return true;
if (!op->IsInstanceOf(maxon::ID_PAINT_OBJECT))
return true;
maxon::PaintObject* paintObject = op->GetNodeData<maxon::PaintObject>();
if (!paintObject)
return false;
iferr_scope_handler
{
err.DbgStop();
return false;
};
if (ctrl) // case A: create a fixed size line if the user does a single click with CTRL
{
maxon::CommandDataRef commandData = maxon::CommandDataClasses::BASE().Create() iferr_return;
commandData.Set(maxon::COMMAND::POLYLINE::DRAW, maxon::POLYLINE_DRAW::LINE) iferr_return;
maxon::COMMANDRESULT res = commandData.Invoke(maxon::CommandClasses::PAINT(), false) iferr_return;
if (res == maxon::COMMANDRESULT::OK)
{
const maxon::BaseArray<Vector>& positions = commandData.Get(maxon::COMMAND::POLYLINE::POSITIONS) iferr_return;
maxon::BaseArray<Vector>& destPositions = paintObject->GetPositions();
destPositions.CopyFrom(positions) iferr_return;
DrawViews(DRAWFLAGS::ONLY_ACTIVE_VIEW|DRAWFLAGS::NO_THREAD|DRAWFLAGS::NO_ANIMATION);
}
return true;
}
else if (shift) // case B: create a fixed size box if the user does a single click with SHIFT
{
maxon::CommandDataRef commandData = maxon::CommandDataClasses::BASE().Create() iferr_return;
maxon::COMMANDRESULT res = commandData.Invoke(maxon::CommandClasses::PAINT(), false,
PARAM(maxon::COMMAND::POLYLINE::DRAW, maxon::POLYLINE_DRAW::BOX),
PARAM(maxon::COMMAND::POLYLINE::START, Vector(100.0, 100.0, 0.0)),
PARAM(maxon::COMMAND::POLYLINE::END, Vector(200.0, 200.0, 0.0))) iferr_return;
if (res == maxon::COMMANDRESULT::OK)
{
const maxon::BaseArray<Vector>& positions = commandData.Get(maxon::COMMAND::POLYLINE::POSITIONS) iferr_return;
maxon::BaseArray<Vector>& destPositions = paintObject->GetPositions();
destPositions.CopyFrom(positions) iferr_return;
DrawViews(DRAWFLAGS::ONLY_ACTIVE_VIEW|DRAWFLAGS::NO_THREAD|DRAWFLAGS::NO_ANIMATION);
}
return true;
}
// case C: interactive mode where the user can click and drag in the view and create a custom size box
maxon::CommandDataRef commandData = maxon::CommandDataClasses::BASE().Create() iferr_return;
maxon::COMMANDRESULT result = commandData.Invoke(maxon::CommandClasses::PAINT(), true,
PARAM(maxon::COMMAND::POLYLINE::DRAW, maxon::POLYLINE_DRAW::BOX),
PARAM(maxon::COMMAND::POLYLINE::START, Vector(mouseX, mouseY, 0.0)),
PARAM(maxon::COMMAND::POLYLINE::END, Vector(mouseX, mouseY, 0.0))) iferr_return;
win->MouseDragStart(button, mouseX, mouseY, MOUSEDRAGFLAGS::DONTHIDEMOUSE | MOUSEDRAGFLAGS::NOMOVE);
result = commandData.Interact(maxon::INTERACTIONTYPE::START) iferr_return;
while (win->MouseDrag(&dx, &dy, &device) == MOUSEDRAGRESULT::CONTINUE)
{
if (dx == 0.0 && dy == 0.0)
continue;
mouseX += dx;
mouseY += dy;
commandData.Set(maxon::COMMAND::POLYLINE::END, Vector(mouseX, mouseY, 0.0)) iferr_return;
result = commandData.Interact(maxon::INTERACTIONTYPE::ITERATE) iferr_return;
if (result == maxon::COMMANDRESULT::OK)
{
const maxon::BaseArray<Vector>& positions = commandData.Get(maxon::COMMAND::POLYLINE::POSITIONS) iferr_return;
maxon::BaseArray<Vector>& destPositions = paintObject->GetPositions();
destPositions.CopyFrom(positions) iferr_return;
}
DrawViews(DRAWFLAGS::ONLY_ACTIVE_VIEW|DRAWFLAGS::NO_THREAD|DRAWFLAGS::NO_ANIMATION);
}
result = commandData.Interact(maxon::INTERACTIONTYPE::END) iferr_return;
DrawViews(DRAWFLAGS::ONLY_ACTIVE_VIEW|DRAWFLAGS::NO_THREAD|DRAWFLAGS::NO_ANIMATION);
if (win->MouseDragEnd() == MOUSEDRAGRESULT::ESCAPE)
doc->DoUndo();
return true;
}
};
Bool RegisterPaintObject()
{
String name = "Paint Object"_s;
return RegisterObjectPlugin(maxon::ID_PAINT_OBJECT, name, 0 , maxon::PaintObject::Alloc, ""_s, nullptr, 0);
}
Bool RegisterPaintTool()
{
String name = "Paint Tool"_s;
return RegisterToolPlugin(ID_PAINT_TOOL, name, 0, nullptr, ""_s, NewObjClear(PaintTool));
}
| 28.051282
| 123
| 0.715722
|
urender-vt
|
eba4f7072010baee076959d464199718a5dc80fd
| 1,149
|
cpp
|
C++
|
SharpMedia.Graphics.Driver.Direct3D10/ServiceProcess.cpp
|
zigaosolin/SharpMedia
|
b7b594a4c9c64a03d94862877ba642b0460d1067
|
[
"Apache-2.0"
] | null | null | null |
SharpMedia.Graphics.Driver.Direct3D10/ServiceProcess.cpp
|
zigaosolin/SharpMedia
|
b7b594a4c9c64a03d94862877ba642b0460d1067
|
[
"Apache-2.0"
] | null | null | null |
SharpMedia.Graphics.Driver.Direct3D10/ServiceProcess.cpp
|
zigaosolin/SharpMedia
|
b7b594a4c9c64a03d94862877ba642b0460d1067
|
[
"Apache-2.0"
] | null | null | null |
#include "GraphicsService.h"
#include "GraphicsServiceView.h"
#include "ServiceProcess.h"
namespace SharpMedia {
namespace Graphics {
namespace Driver {
namespace Direct3D10 {
D3D10ServiceProcess::D3D10ServiceProcess()
{
serviceRegistry = nullptr;
}
Services::IServiceRegistry^ D3D10ServiceProcess::ServiceRegistry::get()
{
return serviceRegistry;
}
void D3D10ServiceProcess::ServiceRegistry::set(Services::IServiceRegistry^ value)
{
serviceRegistry = value;
}
int D3D10ServiceProcess::Start(array<String^>^ args)
{
// We first create service singleton
Components::Configuration::ComponentProviders::Instance^ singleton =
gcnew Components::Configuration::ComponentProviders::Instance(gcnew D3D10GraphicsService());
// The provider.
Components::Configuration::ComponentProviders::InstanceViewSupport^ provider =
gcnew Components::Configuration::ComponentProviders::InstanceViewSupport(singleton, D3D10GraphicsServiceView::typeid, IGraphicsService::typeid);
serviceRegistry->RegisterServiceComponent(provider);
// Sleep forever.
System::Threading::Thread::Sleep(int::MaxValue);
return 0;
}
}
}
}
}
| 23.9375
| 147
| 0.774587
|
zigaosolin
|
ebaa9e021ae8464c6184a0297f29199f16483ec1
| 17,977
|
cpp
|
C++
|
src/Crash/CrashHandler.cpp
|
Moroque/Buffout4
|
5e15a71d1879ad481076b234621609d63ea1dae4
|
[
"MIT"
] | 31
|
2020-09-12T13:17:22.000Z
|
2022-03-04T20:26:13.000Z
|
src/Crash/CrashHandler.cpp
|
Nukem9/Buffout4
|
b7961236e332e7991edb8b85596a64166b1bf926
|
[
"MIT"
] | 3
|
2020-09-30T08:15:18.000Z
|
2021-06-22T18:41:59.000Z
|
src/Crash/CrashHandler.cpp
|
Nukem9/Buffout4
|
b7961236e332e7991edb8b85596a64166b1bf926
|
[
"MIT"
] | 9
|
2020-09-26T01:49:00.000Z
|
2022-02-10T02:59:46.000Z
|
#include "CrashHandler.h"
#include "Crash/Introspection/Introspection.h"
#include "Crash/Modules/ModuleHandler.h"
#define WIN32_LEAN_AND_MEAN
#define NOGDICAPMASKS
#define NOVIRTUALKEYCODES
#define NOWINMESSAGES
#define NOWINSTYLES
#define NOSYSMETRICS
#define NOMENUS
#define NOICONS
#define NOKEYSTATES
#define NOSYSCOMMANDS
#define NORASTEROPS
#define NOSHOWWINDOW
#define OEMRESOURCE
#define NOATOM
#define NOCLIPBOARD
#define NOCOLOR
#define NOCTLMGR
#define NODRAWTEXT
#define NOGDI
#define NOKERNEL
#define NOUSER
#define NONLS
#define NOMB
#define NOMEMMGR
#define NOMETAFILE
#define NOMINMAX
#define NOMSG
#define NOOPENFILE
#define NOSCROLL
#define NOSERVICE
#define NOSOUND
#define NOTEXTMETRIC
#define NOWH
#define NOWINOFFSETS
#define NOCOMM
#define NOKANJI
#define NOHELP
#define NOPROFILER
#define NODEFERWINDOWPOS
#define NOMCX
#include <Windows.h>
#include <winternl.h>
namespace Crash
{
Callstack::Callstack(const ::EXCEPTION_RECORD& a_except)
{
const auto exceptionAddress = reinterpret_cast<std::uintptr_t>(a_except.ExceptionAddress);
auto it = std::find_if(
_stacktrace.cbegin(),
_stacktrace.cend(),
[&](auto&& a_elem) noexcept {
return reinterpret_cast<std::uintptr_t>(a_elem.address()) == exceptionAddress;
});
if (it == _stacktrace.cend()) {
it = _stacktrace.cbegin();
}
_frames = std::span(it, _stacktrace.cend());
}
void Callstack::print(
spdlog::logger& a_log,
std::span<const module_pointer> a_modules) const
{
print_probable_callstack(a_log, a_modules);
}
std::string Callstack::get_size_string(std::size_t a_size)
{
return fmt::to_string(
fmt::to_string(a_size - 1)
.length());
}
std::string Callstack::get_format(std::size_t a_nameWidth) const
{
return "\t[{:>"s +
get_size_string(_frames.size()) +
"}] 0x{:012X} {:>"s +
fmt::to_string(a_nameWidth) +
"}{}"s;
}
void Callstack::print_probable_callstack(
spdlog::logger& a_log,
std::span<const module_pointer> a_modules) const
{
a_log.critical("PROBABLE CALL STACK:"sv);
std::vector<const Modules::Module*> moduleStack;
moduleStack.reserve(_frames.size());
for (const auto& frame : _frames) {
const auto mod = Introspection::get_module_for_pointer(
frame.address(),
a_modules);
if (mod && mod->in_range(frame.address())) {
moduleStack.push_back(mod);
} else {
moduleStack.push_back(nullptr);
}
}
const auto format = get_format([&]() {
std::size_t max = 0;
std::for_each(
moduleStack.begin(),
moduleStack.end(),
[&](auto&& a_elem) {
max = a_elem ? std::max(max, a_elem->name().length()) : max;
});
return max;
}());
for (std::size_t i = 0; i < _frames.size(); ++i) {
const auto mod = moduleStack[i];
const auto& frame = _frames[i];
a_log.critical(
format,
i,
reinterpret_cast<std::uintptr_t>(frame.address()),
(mod ? mod->name() : ""sv),
(mod ? mod->frame_info(frame) : ""s));
}
}
void Callstack::print_raw_callstack(spdlog::logger& a_log) const
{
a_log.critical("RAW CALL STACK:");
const auto format =
"\t[{:>"s +
get_size_string(_stacktrace.size()) +
"}] 0x{:X}"s;
for (std::size_t i = 0; i < _stacktrace.size(); ++i) {
a_log.critical(
format,
i,
reinterpret_cast<std::uintptr_t>(_stacktrace[i].address()));
}
}
namespace
{
[[nodiscard]] std::shared_ptr<spdlog::logger> get_log()
{
auto path = logger::log_directory();
if (!path) {
stl::report_and_fail("failed to find standard log directory"sv);
}
const auto time = std::time(nullptr);
std::tm localTime{};
if (gmtime_s(std::addressof(localTime), std::addressof(time)) != 0) {
stl::report_and_fail("failed to get current time"sv);
}
std::stringstream buf;
buf << "crash-"sv << std::put_time(std::addressof(localTime), "%Y-%m-%d-%H-%M-%S") << ".log"sv;
*path /= buf.str();
auto sink = std::make_shared<spdlog::sinks::basic_file_sink_st>(path->string(), true);
auto log = std::make_shared<spdlog::logger>("crash log"s, std::move(sink));
log->set_pattern("%v"s);
log->set_level(spdlog::level::trace);
log->flush_on(spdlog::level::off);
return log;
}
void print_exception(
spdlog::logger& a_log,
const ::EXCEPTION_RECORD& a_exception,
std::span<const module_pointer> a_modules)
{
#define EXCEPTION_CASE(a_code) \
case a_code: \
return " \"" #a_code "\""sv
const auto eptr = a_exception.ExceptionAddress;
const auto eaddr = reinterpret_cast<std::uintptr_t>(a_exception.ExceptionAddress);
const auto post = [&]() {
const auto mod = Introspection::get_module_for_pointer(
eptr,
a_modules);
if (mod) {
return fmt::format(
FMT_STRING(" {}+{:07X}"),
mod->name(),
eaddr - mod->address());
} else {
return ""s;
}
}();
const auto exception = [&]() {
switch (a_exception.ExceptionCode) {
EXCEPTION_CASE(EXCEPTION_ACCESS_VIOLATION);
EXCEPTION_CASE(EXCEPTION_ARRAY_BOUNDS_EXCEEDED);
EXCEPTION_CASE(EXCEPTION_BREAKPOINT);
EXCEPTION_CASE(EXCEPTION_DATATYPE_MISALIGNMENT);
EXCEPTION_CASE(EXCEPTION_FLT_DENORMAL_OPERAND);
EXCEPTION_CASE(EXCEPTION_FLT_DIVIDE_BY_ZERO);
EXCEPTION_CASE(EXCEPTION_FLT_INEXACT_RESULT);
EXCEPTION_CASE(EXCEPTION_FLT_INVALID_OPERATION);
EXCEPTION_CASE(EXCEPTION_FLT_OVERFLOW);
EXCEPTION_CASE(EXCEPTION_FLT_STACK_CHECK);
EXCEPTION_CASE(EXCEPTION_FLT_UNDERFLOW);
EXCEPTION_CASE(EXCEPTION_ILLEGAL_INSTRUCTION);
EXCEPTION_CASE(EXCEPTION_IN_PAGE_ERROR);
EXCEPTION_CASE(EXCEPTION_INT_DIVIDE_BY_ZERO);
EXCEPTION_CASE(EXCEPTION_INT_OVERFLOW);
EXCEPTION_CASE(EXCEPTION_INVALID_DISPOSITION);
EXCEPTION_CASE(EXCEPTION_NONCONTINUABLE_EXCEPTION);
EXCEPTION_CASE(EXCEPTION_PRIV_INSTRUCTION);
EXCEPTION_CASE(EXCEPTION_SINGLE_STEP);
EXCEPTION_CASE(EXCEPTION_STACK_OVERFLOW);
default:
return ""sv;
}
}();
a_log.critical(
FMT_STRING("Unhandled exception{} at 0x{:012X}{}"),
exception,
eaddr,
post);
#undef EXCEPTION_CASE
}
void print_f4se_plugins(
spdlog::logger& a_log,
std::span<const module_pointer> a_modules)
{
a_log.critical("F4SE PLUGINS:"sv);
const auto ci = [](std::string_view a_lhs, std::string_view a_rhs) {
const auto cmp =
_strnicmp(
a_lhs.data(),
a_rhs.data(),
std::min(a_lhs.size(), a_rhs.size()));
return cmp == 0 && a_lhs.length() != a_rhs.length() ?
a_lhs.length() < a_rhs.length() :
cmp < 0;
};
const auto modules = [&]() {
boost::container::flat_set<std::string_view, decltype(ci)> result;
for (const auto& mod : a_modules) {
result.insert(mod->name());
}
return result;
}();
using value_type = std::pair<std::string, std::optional<REL::Version>>;
std::vector<value_type> plugins;
std::filesystem::path pluginDir{ "Data/F4SE/Plugins"sv };
for (const auto& elem : std::filesystem::directory_iterator(pluginDir)) {
if (const auto filename =
elem.path().has_filename() ?
std::make_optional(elem.path().filename().string()) :
std::nullopt;
filename && modules.contains(*filename)) {
plugins.emplace_back(
*std::move(filename),
REL::get_file_version(elem.path().wstring()));
}
}
std::sort(
plugins.begin(),
plugins.end(),
[=](const value_type& a_lhs, const value_type& a_rhs) {
return ci(a_lhs.first, a_rhs.first);
});
for (const auto& [plugin, version] : plugins) {
const auto ver = [&]() {
if (version) {
std::span view{ version->begin(), version->end() };
const auto it = std::find_if(
view.rbegin(),
view.rend(),
[](std::uint16_t a_val) noexcept { return a_val != 0; });
if (it != view.rend()) {
std::string result = " v";
std::string_view pre;
for (std::size_t i = 0; i < static_cast<std::size_t>(view.rend() - it); ++i) {
result += pre;
result += fmt::to_string(view[i]);
pre = "."sv;
}
return result;
}
}
return ""s;
}();
a_log.critical(FMT_STRING("\t{}{}"), plugin, ver);
}
}
void print_modules(
spdlog::logger& a_log,
std::span<const module_pointer> a_modules)
{
a_log.critical("MODULES:"sv);
const auto format = [&]() {
const auto width = [&]() {
std::size_t max = 0;
std::for_each(
a_modules.begin(),
a_modules.end(),
[&](auto&& a_elem) {
max = std::max(max, a_elem->name().length());
});
return max;
}();
return "\t{:<"s +
fmt::to_string(width) +
"} 0x{:012X}"s;
}();
for (const auto& mod : a_modules) {
a_log.critical(
format,
mod->name(),
mod->address());
}
}
void print_plugins(spdlog::logger& a_log)
{
a_log.critical("PLUGINS:"sv);
const auto datahandler = RE::TESDataHandler::GetSingleton();
if (datahandler) {
const auto& [files, smallfiles] = datahandler->compiledFileCollection;
const auto fileFormat = [&]() {
return "\t[{:>02X}]{:"s +
(!smallfiles.empty() ? "5"s : "1"s) +
"}{}"s;
}();
for (const auto file : files) {
a_log.critical(
fileFormat,
file->GetCompileIndex(),
"",
file->GetFilename());
}
for (const auto file : smallfiles) {
a_log.critical(
FMT_STRING("\t[FE:{:>03X}] {}"),
file->GetSmallFileCompileIndex(),
file->GetFilename());
}
}
}
void print_registers(
spdlog::logger& a_log,
const ::CONTEXT& a_context,
std::span<const module_pointer> a_modules)
{
a_log.critical("REGISTERS:"sv);
const std::array regs{
std::make_pair("RAX"sv, a_context.Rax),
std::make_pair("RCX"sv, a_context.Rcx),
std::make_pair("RDX"sv, a_context.Rdx),
std::make_pair("RBX"sv, a_context.Rbx),
std::make_pair("RSP"sv, a_context.Rsp),
std::make_pair("RBP"sv, a_context.Rbp),
std::make_pair("RSI"sv, a_context.Rsi),
std::make_pair("RDI"sv, a_context.Rdi),
std::make_pair("R8"sv, a_context.R8),
std::make_pair("R9"sv, a_context.R9),
std::make_pair("R10"sv, a_context.R10),
std::make_pair("R11"sv, a_context.R11),
std::make_pair("R12"sv, a_context.R12),
std::make_pair("R13"sv, a_context.R13),
std::make_pair("R14"sv, a_context.R14),
std::make_pair("R15"sv, a_context.R15),
};
std::array<std::size_t, regs.size()> todo{};
for (std::size_t i = 0; i < regs.size(); ++i) {
todo[i] = regs[i].second;
}
const auto analysis = Introspection::analyze_data(todo, a_modules);
for (std::size_t i = 0; i < regs.size(); ++i) {
const auto& [name, reg] = regs[i];
a_log.critical(
FMT_STRING("\t{:<3} 0x{:<16X} {}"),
name,
reg,
analysis[i]);
}
}
void print_settings(
spdlog::logger& a_log)
{
#define SETTING_CASE(a_enum, a_type) \
case toml::node_type::a_enum: \
{ \
assert(dynamic_cast<const AutoTOML::a_type*>(setting)); \
/* NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast) */ \
const auto ptr = static_cast<const AutoTOML::a_type*>(setting); \
value = fmt::to_string(ptr->get()); \
} \
break
a_log.critical("SETTINGS:"sv);
const auto groups = []() {
const auto& src = AutoTOML::ISetting::get_settings();
boost::container::flat_map<
std::string_view,
std::vector<AutoTOML::ISetting*>>
groups;
std::for_each(
src.begin(),
src.end(),
[&](auto&& a_elem) {
assert(a_elem != nullptr);
const auto it = groups.emplace(a_elem->group(), 0).first;
assert(it != groups.end());
it->second.push_back(a_elem);
});
std::for_each(
groups.begin(),
groups.end(),
[](auto& a_elem) {
std::sort(
a_elem.second.begin(),
a_elem.second.end(),
[](auto&& a_lhs, auto&& a_rhs) {
assert(a_lhs != nullptr && a_rhs != nullptr);
return a_lhs->key() < a_rhs->key();
});
});
return groups;
}();
std::string value;
for (const auto& [group, settings] : groups) {
assert(!settings.empty());
a_log.critical(
FMT_STRING("\t[{}]"),
group);
for (const auto setting : settings) {
assert(setting != nullptr);
value = "UNKNOWN"sv;
switch (setting->type()) {
SETTING_CASE(boolean, bSetting);
SETTING_CASE(floating_point, fSetting);
SETTING_CASE(integer, iSetting);
SETTING_CASE(string, sSetting);
default:
break;
}
a_log.critical(
FMT_STRING("\t\t{}: {}"),
setting->key(),
value);
}
}
}
void print_stack(
spdlog::logger& a_log,
const ::CONTEXT& a_context,
std::span<const module_pointer> a_modules)
{
a_log.critical("STACK:"sv);
const auto tib = reinterpret_cast<const ::NT_TIB*>(::NtCurrentTeb());
const auto base = tib ? static_cast<const std::size_t*>(tib->StackBase) : nullptr;
if (!base) {
a_log.critical("\tFAILED TO READ TIB"sv);
} else {
const auto rsp = reinterpret_cast<const std::size_t*>(a_context.Rsp);
std::span stack{ rsp, base };
const auto format = [&]() {
return "\t[RSP+{:<"s +
fmt::to_string(
fmt::format(FMT_STRING("{:X}"), (stack.size() - 1) * sizeof(std::size_t))
.length()) +
"X}] 0x{:<16X} {}"s;
}();
constexpr std::size_t blockSize = 1000;
std::size_t idx = 0;
for (std::size_t off = 0; off < stack.size(); off += blockSize) {
const auto analysis =
Introspection::analyze_data(
stack.subspan(off, std::min<std::size_t>(stack.size() - off, blockSize)),
a_modules);
for (const auto& data : analysis) {
a_log.critical(
format,
idx * sizeof(std::size_t),
stack[idx],
data);
++idx;
}
}
}
}
void print_sysinfo(
spdlog::logger& a_log)
{
a_log.critical("SYSTEM SPECS:"sv);
const auto os = iware::system::OS_info();
a_log.critical(
FMT_STRING("\tOS: {} v{}.{}.{}"),
os.full_name,
os.major,
os.minor,
os.patch);
a_log.critical(
FMT_STRING("\tCPU: {} {}"),
iware::cpu::vendor(),
iware::cpu::model_name());
const auto vendor = [](iware::gpu::vendor_t a_vendor) {
using vendor_t = iware::gpu::vendor_t;
switch (a_vendor) {
case vendor_t::intel:
return "Intel"sv;
case vendor_t::amd:
return "AMD"sv;
case vendor_t::nvidia:
return "Nvidia"sv;
case vendor_t::microsoft:
return "Microsoft"sv;
case vendor_t::qualcomm:
return "Qualcomm"sv;
case vendor_t::unknown:
default:
return "Unknown"sv;
}
};
const auto gpus = iware::gpu::device_properties();
for (std::size_t i = 0; i < gpus.size(); ++i) {
const auto& gpu = gpus[i];
a_log.critical(
FMT_STRING("\tGPU #{}: {} {}"),
i + 1,
vendor(gpu.vendor),
gpu.name);
}
const auto gibibyte = [](std::uint64_t a_bytes) {
constexpr double factor = 1024 * 1024 * 1024;
return static_cast<double>(a_bytes) / factor;
};
const auto mem = iware::system::memory();
a_log.critical(
FMT_STRING("\tPHYSICAL MEMORY: {:.02f} GB/{:.02f} GB"),
gibibyte(mem.physical_total - mem.physical_available),
gibibyte(mem.physical_total));
}
#undef SETTING_CASE
std::int32_t __stdcall UnhandledExceptions(::EXCEPTION_POINTERS* a_exception) noexcept
{
#ifndef NDEBUG
while (!WinAPI::IsDebuggerPresent()) {}
#endif
try {
static std::mutex sync;
const std::lock_guard l{ sync };
const auto modules = Modules::get_loaded_modules();
const std::span cmodules{ modules.begin(), modules.end() };
const auto log = get_log();
const auto print = [&](auto&& a_functor) {
log->critical(""sv);
try {
a_functor();
} catch (const std::exception& e) {
log->critical(
FMT_STRING("\t{}"),
e.what());
} catch (...) {
log->critical("\tERROR"sv);
}
log->flush();
};
const auto runtimeVer = REL::Module::get().version();
log->critical(FMT_STRING("Fallout 4 v{}.{}.{}"), runtimeVer[0], runtimeVer[1], runtimeVer[2]);
log->critical(FMT_STRING("Buffout 4 v{}"), Version::NAME);
log->flush();
print([&]() { print_exception(*log, *a_exception->ExceptionRecord, cmodules); });
print([&]() { print_settings(*log); });
print([&]() { print_sysinfo(*log); });
print([&]() {
const Callstack callstack{ *a_exception->ExceptionRecord };
callstack.print(*log, cmodules);
});
print([&]() { print_registers(*log, *a_exception->ContextRecord, cmodules); });
print([&]() { print_stack(*log, *a_exception->ContextRecord, cmodules); });
print([&]() { print_modules(*log, cmodules); });
print([&]() { print_f4se_plugins(*log, cmodules); });
print([&]() { print_plugins(*log); });
} catch (...) {}
WinAPI::TerminateProcess(
WinAPI::GetCurrentProcess(),
EXIT_FAILURE);
}
std::int32_t _stdcall VectoredExceptions(::EXCEPTION_POINTERS*) noexcept
{
::SetUnhandledExceptionFilter(
reinterpret_cast<::LPTOP_LEVEL_EXCEPTION_FILTER>(&UnhandledExceptions));
return EXCEPTION_CONTINUE_SEARCH;
}
}
void Install()
{
const auto success =
::AddVectoredExceptionHandler(
1,
reinterpret_cast<::PVECTORED_EXCEPTION_HANDLER>(&VectoredExceptions));
if (success == nullptr) {
stl::report_and_fail("failed to install vectored exception handler"sv);
}
logger::debug("installed crash handlers"sv);
}
}
| 26.87145
| 98
| 0.607387
|
Moroque
|
ebae31c1919b5f51254ca92da5ee65c22baaeeea
| 776
|
cpp
|
C++
|
src/nfa.cpp
|
SuprDewd/states
|
68f89c8e60767819b0b9d0218bb14f6e8b4fac89
|
[
"MIT"
] | 4
|
2015-01-09T16:54:26.000Z
|
2018-10-29T13:07:59.000Z
|
src/nfa.cpp
|
SuprDewd/states
|
68f89c8e60767819b0b9d0218bb14f6e8b4fac89
|
[
"MIT"
] | null | null | null |
src/nfa.cpp
|
SuprDewd/states
|
68f89c8e60767819b0b9d0218bb14f6e8b4fac89
|
[
"MIT"
] | 2
|
2016-07-27T02:54:49.000Z
|
2018-04-11T17:04:07.000Z
|
#include "nfa.h"
nfa* nfa_from_ast(ast_nfa *m) {
nfa *res = new nfa();
res->set_start(m->start);
for (ast_statelist::const_iterator it = m->states.begin(); it != m->states.end(); ++it) {
ast_state *state = *it;
if (state->accept) {
res->add_final(state->name);
}
for (ast_onlist::const_iterator jt = state->next.begin(); jt != state->next.end(); ++jt) {
ast_on *on = *jt;
char t;
if (on->token.size() == 1) {
t = on->token[0];
} else if (on->token == "epsilon") {
t = 0;
} else {
assert(false);
}
res->add_next(state->name, t, on->target_state);
}
}
return res;
}
| 23.515152
| 98
| 0.451031
|
SuprDewd
|
ebaf5be445f916eb9125873f62d21533087da357
| 4,505
|
cpp
|
C++
|
Lucy/LucyText/Town.cpp
|
Tuz1e/Lucy
|
284f3308e494a4544750c82f21b4a976a9938257
|
[
"Apache-2.0"
] | null | null | null |
Lucy/LucyText/Town.cpp
|
Tuz1e/Lucy
|
284f3308e494a4544750c82f21b4a976a9938257
|
[
"Apache-2.0"
] | null | null | null |
Lucy/LucyText/Town.cpp
|
Tuz1e/Lucy
|
284f3308e494a4544750c82f21b4a976a9938257
|
[
"Apache-2.0"
] | null | null | null |
#include "Town.h"
#include "ItemManager.h"
Town::Town()
{
myFirstT = true;
mySpecialDimensionCost = 25;
}
Town::~Town()
{
}
void Town::Run(const Player aPlayer)
{
myPlayer = aPlayer;
while (1)
{
Empty();
if (myFirstT)
{
Introduction();
}
else
{
myPlayer.Update();
Print("Location: " TOWNNAME ", Town Square", Colour::LIGHTCYAN);
Print("What would you like to do?");
Print("[1] <Shop>\n[2] <Enchantment Station>\n[3] <Open a Dimension> \n[4] <Player Information> ");
std::getline(std::cin, myChoToConvert);
myCho = ConvertToInt(myChoToConvert);
switch (myCho)
{
case 1:
Shop();
break;
case 2:
myPlayer.Enchantment();
break;
case 3:
OpenDimension();
break;
case 4:
myPlayer.Choices();
break;
case 47190:
myPlayer.ModifyGold(1000000); //Cheat code for easier debugging.
break;
}
}
}
}
void Town::Introduction()
{
Print(
"Welcome to the town of " TOWNNAME "!" "\n"
"Here you will be able to shop for gear, weapons and scrolls." "\n"
"You could also open a breach into another dimension and fight "
"some monsters. You know, just casual things. " "\n" "Have Fun!"
, 3);
Print("\nPress 'any key' to continue...");
getchar();
myFirstT = false;
}
void Town::NotAvailable()
{
Print("That is currently unavailable.", 12);
Sleep(1000);
}
void Town::OpenDimension()
{
int tempDimensionCho;
bool tempCho;
Empty();
myPlayer.Update();
Print("Which kind of dimension would you like to open?", Colour::LIGHTCYAN);
Print("[1] <Normal> \n[2] <Special>");
std::getline(std::cin, myChoToConvert);
tempDimensionCho = ConvertToInt(myChoToConvert);
if (tempDimensionCho == 1)
{
tempCho = CheckCertain();
if (tempCho)
{
Dimension(false).Run(myPlayer);
}
}
else if (tempDimensionCho == 2)
{
Empty();
myPlayer.Update();
Print("\nOpening a special dimension costs " + std::to_string(mySpecialDimensionCost) + " Fragments", Colour::LIGHTRED);
tempCho = CheckCertain();
if (tempCho)
{
if (myPlayer.GetFragments() >= mySpecialDimensionCost)
{
Dimension(true).Run(myPlayer);
}
else
{
NotEnoughMoney();
}
}
}
}
void Town::Shop()
{
myItems = myItemManager.GetItems();
while (1)
{
Empty();
myPlayer.Update();
Print("SHOP:", 11);
for (size_t i = 0; i < myItems.size(); i++)
{
PrintCon(myItems[i].GetName());
Print(" > " + std::to_string(myItems[i].GetCost()) + " Gold", Colour::YELLOW);
}
Print("\n");
Print("\n[1] <Buy an Item> \n[2] <Inspect Item> \n[3] <Player Information> \n[4] <Back>");
std::getline(std::cin, myChoToConvert);
myCho = ConvertToInt(myChoToConvert);
if (myCho == 1)
{
myCho = -1;
while (1)
{
Empty();
myPlayer.Update();
Print("SHOP:", 11);
for (size_t i = 0; i < myItems.size(); i++)
{
PrintCon("[" + std::to_string(i) + "] " + myItems[i].GetName());
Print(" > " + std::to_string(myItems[i].GetCost()) + " Gold", Colour::YELLOW);
}
Print("\n[" + std::to_string(myItems.size()) + "] Back");
Print("Which item would you like to buy?");
std::getline(std::cin, myChoToConvert);
myCho = ConvertToInt(myChoToConvert);
if (myCho >= 0 && myCho <= myItems.size() - 1)
{
if (myPlayer.GetGold() >= myItems[myCho].GetCost())
{
myPlayer.ModifyGold(-myItems[myCho].GetCost());
Print("You successfully bought a " + myItems[myCho].GetName());
myPlayer.GiveItem(myItems[myCho]);
Sleep(1000);
}
else
{
NotEnoughMoney();
}
}
else if (myCho == (myItems.size()))
{
break;
}
}
}
else if (myCho == 2)
{
Empty();
Print("SHOP:", 11);
for (size_t i = 0; i < myItems.size(); i++)
{
Print("[" + std::to_string(i) + "] " + myItems[i].GetName());
}
Print("\n");
Print("Which item would you like to inspect?");
std::getline(std::cin, myChoToConvert);
myCho = ConvertToInt(myChoToConvert);
if (myCho >= 0 && myCho <= myItems.size())
{
Inspect(myItems[myCho]);
}
}
else if (myCho == 3)
{
myPlayer.Choices();
}
else if (myCho == 4)
{
break;
}
}
myItems.clear();
}
void Town::NotEnoughMoney()
{
Print("Not enough money/fragments.", 12);
Sleep(1000);
}
bool Town::CheckCertain()
{
Print("\nAre you certain?", Colour::YELLOW);
Print("[1] <Yes>\n[2] <No>");
std::getline(std::cin, myChoToConvert);
myCho = ConvertToInt(myChoToConvert);
return (myCho == 1) ? true : false;
}
| 20.201794
| 122
| 0.595339
|
Tuz1e
|
ebb2c9ab0d1d6feed09fa74e682880d6b650427a
| 269
|
cpp
|
C++
|
system/CoreMemento.cpp
|
arulagrawal/cos214_project
|
1ea65ac7e46b97107c0ec2a75359514bc6c98c15
|
[
"BSD-2-Clause"
] | null | null | null |
system/CoreMemento.cpp
|
arulagrawal/cos214_project
|
1ea65ac7e46b97107c0ec2a75359514bc6c98c15
|
[
"BSD-2-Clause"
] | null | null | null |
system/CoreMemento.cpp
|
arulagrawal/cos214_project
|
1ea65ac7e46b97107c0ec2a75359514bc6c98c15
|
[
"BSD-2-Clause"
] | null | null | null |
#include "CoreMemento.h"
CoreMemento::CoreMemento(int fuelWeight, bool isOn)
{
this->coreState = new CoreState(fuelWeight, isOn);
//cout << "FUEL WEIGHT: " << fuelWeight << endl;
}
CoreMemento::~CoreMemento()
{
delete this->coreState;
coreState = 0;
}
| 20.692308
| 54
| 0.669145
|
arulagrawal
|
ebb30094a14919cdd4cf98563a194e47a2da0b11
| 1,455
|
cpp
|
C++
|
renderString.cpp
|
moelatt/3D_TransFormation_OpenGL
|
facee07358afadd338e7c99a3bb54f32eb80e91e
|
[
"MIT"
] | null | null | null |
renderString.cpp
|
moelatt/3D_TransFormation_OpenGL
|
facee07358afadd338e7c99a3bb54f32eb80e91e
|
[
"MIT"
] | null | null | null |
renderString.cpp
|
moelatt/3D_TransFormation_OpenGL
|
facee07358afadd338e7c99a3bb54f32eb80e91e
|
[
"MIT"
] | null | null | null |
#include "main.h"
// Display Text
void renderString(const char* text, int length, int x, int y, int id){
glMatrixMode(GL_PROJECTION);
double *array = new double[16];
glGetDoublev(GL_PROJECTION_MATRIX,array);
glLoadIdentity();
glOrtho(0,293, 0, 294, -1,3);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glPushMatrix();
glLoadIdentity();
glRasterPos2i(x,y);
for(int i = 0; i < length; i++){
switch (id){
case 0:
glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, (int)text[i]); break;
case 1:
glutBitmapCharacter(GLUT_BITMAP_9_BY_15, (int)text[i]); break;
default:
break;
}
}
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glLoadMatrixd(array);
glMatrixMode(GL_MODELVIEW);
}
void extraWinFunc(){
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
string str = "Welcome";
string str2 = "From";
string str1 = "Grapic World!";
string str3 = "Right Click Here";
string str4 = "To See Menu";
glColor3f(0.4,1.0,0.9);
renderString(str.data(), str.size(), 195, 125, 0);
glColor3f(1,0.5,0.2);
renderString(str2.data(), str2.size(), 205, 110, 0);
glColor3f(1,0.5,1.0);
renderString(str1.data(), str1.size(), 185, 95, 0);
glColor3f(1,0.2,0.3);
renderString(str3.data(), str3.size(), 180, 65, 0);
glColor3f(1,0.9,1.0);
renderString(str4.data(), str4.size(), 187, 50, 0);
}
| 30.3125
| 81
| 0.613058
|
moelatt
|
ebb31597082a1fe9dc20e2e477ec72e89daba4bf
| 5,291
|
cpp
|
C++
|
src/subcommand/kmers_main.cpp
|
ruolin/vg
|
fddf5a0e3172cfc50eb6f8a561dfbe3dbbbaec04
|
[
"MIT"
] | 740
|
2016-02-23T02:31:10.000Z
|
2022-03-31T20:51:36.000Z
|
src/subcommand/kmers_main.cpp
|
ruolin/vg
|
fddf5a0e3172cfc50eb6f8a561dfbe3dbbbaec04
|
[
"MIT"
] | 2,455
|
2016-02-24T08:17:45.000Z
|
2022-03-31T20:19:41.000Z
|
src/subcommand/kmers_main.cpp
|
ruolin/vg
|
fddf5a0e3172cfc50eb6f8a561dfbe3dbbbaec04
|
[
"MIT"
] | 169
|
2016-03-03T15:41:33.000Z
|
2022-03-31T04:01:53.000Z
|
/** \file kmers_main.cpp
*
* Defines the "vg kmers" subcommand, which generates the kmers in a graph.
*/
#include <omp.h>
#include <unistd.h>
#include <getopt.h>
#include <iostream>
#include <set>
#include "subcommand.hpp"
#include "../vg.hpp"
#include "../vg_set.hpp"
#include "../kmer.hpp"
using namespace std;
using namespace vg;
using namespace vg::subcommand;
void help_kmers(char** argv) {
cerr << "usage: " << argv[0] << " kmers [options] <graph1.vg> [graph2.vg ...] >kmers.tsv" << endl
<< "Generates kmers from both strands of the graph(s). Output is: kmer id pos" << endl
<< endl
<< "general options:" << endl
<< " -k, --kmer-size N print kmers of size N in the graph" << endl
<< " -t, --threads N number of threads to use" << endl
<< " -p, --progress show progress" << endl
<< "gcsa options:" << endl
<< " -g, --gcsa-out output a table suitable for input to GCSA2:" << endl
<< " kmer, starting position, previous characters," << endl
<< " successive characters, successive positions." << endl
<< " -B, --gcsa-binary write the GCSA graph in binary format (implies -g)" << endl
<< " -H, --head-id N use the specified ID for the GCSA2 head sentinel node" << endl
<< " -T, --tail-id N use the specified ID for the GCSA2 tail sentinel node" << endl
<< "" << endl;
}
int main_kmers(int argc, char** argv) {
if (argc == 2) {
help_kmers(argv);
return 1;
}
// General options.
size_t kmer_size = 0;
bool show_progress = false;
// GCSA options. Head and tail for distributed kmer generation.
bool gcsa_out = false;
bool gcsa_binary = false;
int64_t head_id = 0;
int64_t tail_id = 0;
int c;
optind = 2; // force optind past command positional argument
while (true) {
static struct option long_options[] =
{
// General options.
{"kmer-size", required_argument, 0, 'k'},
{"threads", required_argument, 0, 't'},
{"progress", no_argument, 0, 'p'},
// GCSA options.
{"gcsa-out", no_argument, 0, 'g'},
{"gcsa-binary", no_argument, 0, 'B'},
{"head-id", required_argument, 0, 'H'},
{"tail-id", required_argument, 0, 'T'},
// Obsolete options.
{"edge-max", required_argument, 0, 'e'},
{"forward-only", no_argument, 0, 'F'},
{"help", no_argument, 0, 'h'},
{0, 0, 0, 0}
};
int option_index = 0;
c = getopt_long (argc, argv, "k:t:pgBH:T:e:Fh",
long_options, &option_index);
// Detect the end of the options.
if (c == -1)
break;
switch (c)
{
// General options.
case 'k':
kmer_size = parse<size_t>(optarg);
break;
case 't':
omp_set_num_threads(parse<int>(optarg));
break;
case 'p':
show_progress = true;
break;
// GCSA options.
case 'g':
gcsa_out = true;
break;
case 'B':
gcsa_out = true;
gcsa_binary = true;
break;
case 'H':
head_id = parse<int>(optarg);
break;
case 'T':
tail_id = parse<int>(optarg);
break;
// Obsolete options.
case 'e':
cerr << "error: [vg kmers] Option --edge-max is obsolete. Use vg prune to prune the graph instead." << endl;
std::exit(EXIT_FAILURE);
break;
case 'F':
cerr << "error: [vg kmers] Option --forward-only is obsolete" << endl;
std::exit(EXIT_FAILURE);
break;
case 'h':
case '?':
help_kmers(argv);
exit(1);
break;
default:
abort ();
}
}
if (kmer_size == 0) {
cerr << "error: [vg kmers] --kmer-size was not specified" << endl;
std::exit(EXIT_FAILURE);
}
vector<string> graph_file_names;
while (optind < argc) {
string file_name = get_input_file_name(optind, argc, argv);
graph_file_names.push_back(file_name);
}
VGset graphs(graph_file_names);
graphs.show_progress = show_progress;
if (gcsa_out) {
if (!gcsa_binary) {
graphs.write_gcsa_kmers_ascii(cout, kmer_size, head_id, tail_id);
} else {
size_t limit = ~(size_t)0;
graphs.write_gcsa_kmers_binary(cout, kmer_size, limit, head_id, tail_id);
}
} else {
auto lambda = [](const kmer_t& kmer) {
#pragma omp critical (cout)
cout << kmer << endl;
};
graphs.for_each_kmer_parallel(kmer_size, lambda);
}
cout.flush();
return 0;
}
// Register subcommand
static Subcommand vg_kmers("kmers", "enumerate kmers of the graph", DEPRECATED, main_kmers);
| 29.724719
| 124
| 0.502741
|
ruolin
|
ebb9f9250152e37412bfc37c4d8d4dbed1399365
| 197
|
cpp
|
C++
|
src/L/L12D1.cpp
|
wlhcode/lscct
|
7fd112a9d1851ddcf41886d3084381a52e84a3ce
|
[
"MIT"
] | null | null | null |
src/L/L12D1.cpp
|
wlhcode/lscct
|
7fd112a9d1851ddcf41886d3084381a52e84a3ce
|
[
"MIT"
] | null | null | null |
src/L/L12D1.cpp
|
wlhcode/lscct
|
7fd112a9d1851ddcf41886d3084381a52e84a3ce
|
[
"MIT"
] | null | null | null |
#include<bits/stdc++.h>
using namespace std;
double arr[10];
int main(){
for(int i=0;i<6;i++) cin>>arr[i];
sort(arr,arr+6);
cout<<(arr[1]+arr[2]+arr[3]+arr[4])/4<<endl;
return 0;
}
| 19.7
| 48
| 0.568528
|
wlhcode
|
ebbcd7f9dc0e4be56099e08eb99ea1a3cb051e7c
| 19,907
|
cpp
|
C++
|
src/libclipper/test/input_test.cpp
|
yujialuo/Clipper
|
7269521f003b542b60d13f3a69276b62f610ef33
|
[
"Apache-2.0"
] | null | null | null |
src/libclipper/test/input_test.cpp
|
yujialuo/Clipper
|
7269521f003b542b60d13f3a69276b62f610ef33
|
[
"Apache-2.0"
] | null | null | null |
src/libclipper/test/input_test.cpp
|
yujialuo/Clipper
|
7269521f003b542b60d13f3a69276b62f610ef33
|
[
"Apache-2.0"
] | null | null | null |
#include <stdexcept>
#include <type_traits>
#include <gtest/gtest.h>
#include <clipper/datatypes.hpp>
using namespace clipper;
using std::vector;
namespace {
const unsigned long SERIALIZED_REQUEST_SIZE = 3;
const int NUM_PRIMITIVE_INPUTS = 500;
const int NUM_STRING_INPUTS = 300;
const uint8_t PRIMITIVE_INPUT_SIZE_ELEMS = 200;
template<typename T>
std::vector<std::vector<T>> get_primitive_data_vectors() {
std::vector<std::vector<T>> data_vectors;
for (int i = 0; i < NUM_PRIMITIVE_INPUTS; i++) {
std::vector<T> data_vector;
for (uint8_t j = 0; j < PRIMITIVE_INPUT_SIZE_ELEMS; j++) {
// Differentiate vectors by populating them with the index j under differing moduli
int k = static_cast<int>(j) % (i + 1);
data_vector.push_back(static_cast<T>(k));
}
data_vectors.push_back(data_vector);
}
return data_vectors;
}
void get_string_data(std::vector<std::string> &string_vector) {
for(int i = 0; i < NUM_STRING_INPUTS; i++) {
std::string str;
switch(i % 3) {
case 0:
str = std::string("CAT");
break;
case 1:
str = std::string("DOG");
break;
case 2:
str = std::string("COW");
break;
default:
str = std::string("INVALID");
break;
}
string_vector.push_back(str);
}
}
TEST(InputSerializationTests, EmptySerialization) {
clipper::rpc::PredictionRequest request(InputType::Bytes);
try {
request.serialize();
} catch (std::length_error) {
SUCCEED();
return;
}
FAIL();
}
TEST(InputSerializationTests, ByteSerialization) {
clipper::rpc::PredictionRequest request(InputType::Bytes);
std::vector<std::vector<uint8_t>> data_vectors = get_primitive_data_vectors<uint8_t>();
for(int i = 0; i < (int) data_vectors.size(); i++) {
std::shared_ptr<ByteVector> byte_vec = std::make_shared<ByteVector>(data_vectors[i]);
request.add_input(byte_vec);
}
std::vector<clipper::ByteBuffer> serialized_request = request.serialize();
ASSERT_EQ(serialized_request.size(), SERIALIZED_REQUEST_SIZE);
clipper::ByteBuffer request_header = serialized_request[0];
clipper::ByteBuffer input_header = serialized_request[1];
clipper::ByteBuffer raw_content = serialized_request[2];
uint32_t* raw_request_type = reinterpret_cast<uint32_t*>(request_header.data());
ASSERT_EQ(*raw_request_type, static_cast<uint32_t>(clipper::RequestType::PredictRequest));
uint32_t* typed_input_header = reinterpret_cast<uint32_t*>(input_header.data());
ASSERT_EQ(*typed_input_header, static_cast<uint32_t>(clipper::InputType::Bytes));
typed_input_header++;
uint32_t num_inputs = *typed_input_header;
ASSERT_EQ(num_inputs, static_cast<uint32_t>(data_vectors.size()));
typed_input_header++;
uint8_t* content_ptr = raw_content.data();
uint32_t prev_index = 0;
for(int i = 0; i < (int) num_inputs - 1; i++) {
uint32_t split_index = typed_input_header[i];
std::vector<uint8_t> vec(content_ptr + prev_index, content_ptr + split_index);
ASSERT_EQ(vec, data_vectors[i]);
prev_index = split_index;
}
// Our splits define internal indices at which to delimit input vectors, so they exclude 0
// and the content length. We therefore have to check the consistency of the final vector.
// This vector is composed of the elements from the last split index through the total content length.
std::vector<uint8_t> tail_vec(content_ptr + prev_index, content_ptr + (raw_content.size() / sizeof(uint8_t)));
ASSERT_EQ(tail_vec, data_vectors[data_vectors.size() - 1]);
}
TEST(InputSerializationTests, IntSerialization) {
clipper::rpc::PredictionRequest request(InputType::Ints);
std::vector<std::vector<int>> data_vectors = get_primitive_data_vectors<int>();
for(int i = 0; i < (int) data_vectors.size(); i++) {
std::shared_ptr<IntVector> int_vec = std::make_shared<IntVector>(data_vectors[i]);
request.add_input(int_vec);
}
std::vector<clipper::ByteBuffer> serialized_request = request.serialize();
ASSERT_EQ(serialized_request.size(), SERIALIZED_REQUEST_SIZE);
clipper::ByteBuffer request_header = serialized_request[0];
clipper::ByteBuffer input_header = serialized_request[1];
clipper::ByteBuffer raw_content = serialized_request[2];
uint32_t* raw_request_type = reinterpret_cast<uint32_t*>(request_header.data());
ASSERT_EQ(*raw_request_type, static_cast<uint32_t>(clipper::RequestType::PredictRequest));
uint32_t* typed_input_header = reinterpret_cast<uint32_t*>(input_header.data());
ASSERT_EQ(*typed_input_header, static_cast<uint32_t>(clipper::InputType::Ints));
typed_input_header++;
uint32_t num_inputs = *typed_input_header;
ASSERT_EQ(num_inputs, static_cast<uint32_t>(data_vectors.size()));
typed_input_header++;
int* content_ptr = reinterpret_cast<int*>(raw_content.data());
uint32_t prev_index = 0;
for(int i = 0; i < (int) num_inputs - 1; i++) {
uint32_t split_index = typed_input_header[i];
std::vector<int> vec(content_ptr + prev_index, content_ptr + split_index);
ASSERT_EQ(vec, data_vectors[i]);
prev_index = split_index;
}
// Our splits define internal indices at which to delimit input vectors, so they exclude 0
// and the content length. We therefore have to check the consistency of the final vector.
// This vector is composed of the elements from the last split index through the total content length.
std::vector<int> tail_vec(content_ptr + prev_index, content_ptr + (raw_content.size() / sizeof(int)));
ASSERT_EQ(tail_vec, data_vectors[data_vectors.size() - 1]);
}
TEST(InputSerializationTests, FloatSerialization) {
clipper::rpc::PredictionRequest request(InputType::Floats);
std::vector<std::vector<float>> data_vectors = get_primitive_data_vectors<float>();
for(int i = 0; i < (int) data_vectors.size(); i++) {
std::shared_ptr<FloatVector> float_vec = std::make_shared<FloatVector>(data_vectors[i]);
request.add_input(float_vec);
}
std::vector<clipper::ByteBuffer> serialized_request = request.serialize();
ASSERT_EQ(serialized_request.size(), SERIALIZED_REQUEST_SIZE);
clipper::ByteBuffer request_header = serialized_request[0];
clipper::ByteBuffer input_header = serialized_request[1];
clipper::ByteBuffer raw_content = serialized_request[2];
uint32_t* raw_request_type = reinterpret_cast<uint32_t*>(request_header.data());
ASSERT_EQ(*raw_request_type, static_cast<uint32_t>(clipper::RequestType::PredictRequest));
uint32_t* typed_input_header = reinterpret_cast<uint32_t*>(input_header.data());
ASSERT_EQ(*typed_input_header, static_cast<uint32_t>(clipper::InputType::Floats));
typed_input_header++;
uint32_t num_inputs = *typed_input_header;
ASSERT_EQ(num_inputs, static_cast<uint32_t>(data_vectors.size()));
typed_input_header++;
float* content_ptr = reinterpret_cast<float*>(raw_content.data());
uint32_t prev_index = 0;
for(int i = 0; i < (int) num_inputs - 1; i++) {
uint32_t split_index = typed_input_header[i];
std::vector<float> vec(content_ptr + prev_index, content_ptr + split_index);
ASSERT_EQ(vec, data_vectors[i]);
prev_index = split_index;
}
// Our splits define internal indices at which to delimit input vectors, so they exclude 0
// and the content length. We therefore have to check the consistency of the final vector.
// This vector is composed of the elements from the last split index through the total content length.
std::vector<float> tail_vec(content_ptr + prev_index, content_ptr + (raw_content.size() / sizeof(float)));
ASSERT_EQ(tail_vec, data_vectors[data_vectors.size() - 1]);
}
TEST(InputSerializationTests, DoubleSerialization) {
clipper::rpc::PredictionRequest request(InputType::Doubles);
std::vector<std::vector<double>> data_vectors = get_primitive_data_vectors<double>();
for(int i = 0; i < (int) data_vectors.size(); i++) {
std::shared_ptr<DoubleVector> double_vec = std::make_shared<DoubleVector>(data_vectors[i]);
request.add_input(double_vec);
}
std::vector<clipper::ByteBuffer> serialized_request = request.serialize();
ASSERT_EQ(serialized_request.size(), SERIALIZED_REQUEST_SIZE);
clipper::ByteBuffer request_header = serialized_request[0];
clipper::ByteBuffer input_header = serialized_request[1];
clipper::ByteBuffer raw_content = serialized_request[2];
uint32_t* raw_request_type = reinterpret_cast<uint32_t*>(request_header.data());
ASSERT_EQ(*raw_request_type, static_cast<uint32_t>(clipper::RequestType::PredictRequest));
uint32_t* typed_input_header = reinterpret_cast<uint32_t*>(input_header.data());
ASSERT_EQ(*typed_input_header, static_cast<uint32_t>(clipper::InputType::Doubles));
typed_input_header++;
uint32_t num_inputs = *typed_input_header;
ASSERT_EQ(num_inputs, static_cast<uint32_t>(data_vectors.size()));
typed_input_header++;
double* content_ptr = reinterpret_cast<double*>(raw_content.data());
uint32_t prev_index = 0;
for(int i = 0; i < (int) num_inputs - 1; i++) {
uint32_t split_index = typed_input_header[i];
std::vector<double> vec(content_ptr + prev_index, content_ptr + split_index);
ASSERT_EQ(vec, data_vectors[i]);
prev_index = split_index;
}
// Our splits define internal indices at which to delimit input vectors, so they exclude 0
// and the content length. We therefore have to check the consistency of the final vector.
// This vector is composed of the elements from the last split index through the total content length.
std::vector<double> tail_vec(content_ptr + prev_index, content_ptr + (raw_content.size() / sizeof(double)));
ASSERT_EQ(tail_vec, data_vectors[data_vectors.size() - 1]);
}
TEST(InputSerializationTests, StringSerialization) {
clipper::rpc::PredictionRequest request(InputType::Strings);
std::vector<std::string> string_vector;
get_string_data(string_vector);
for(int i = 0; i < (int) string_vector.size(); i++) {
std::shared_ptr<SerializableString> serializable_str = std::make_shared<SerializableString>(string_vector[i]);
request.add_input(serializable_str);
}
std::vector<clipper::ByteBuffer> serialized_request = request.serialize();
ASSERT_EQ(serialized_request.size(), SERIALIZED_REQUEST_SIZE);
clipper::ByteBuffer request_header = serialized_request[0];
clipper::ByteBuffer input_header = serialized_request[1];
clipper::ByteBuffer raw_content = serialized_request[2];
uint32_t* raw_request_type = reinterpret_cast<uint32_t*>(request_header.data());
ASSERT_EQ(*raw_request_type, static_cast<uint32_t>(clipper::RequestType::PredictRequest));
uint32_t* typed_input_header = reinterpret_cast<uint32_t*>(input_header.data());
ASSERT_EQ(*typed_input_header, static_cast<uint32_t>(clipper::InputType::Strings));
typed_input_header++;
uint32_t num_inputs = *typed_input_header;
ASSERT_EQ(num_inputs, static_cast<uint32_t>(string_vector.size()));
typed_input_header++;
char* content_ptr = reinterpret_cast<char*>(raw_content.data());
for(int i = 0; i < (int) num_inputs; i++) {
std::string str(content_ptr);
ASSERT_EQ(str, string_vector[i]);
content_ptr += (str.length() + 1);
}
}
TEST(InputSerializationTests, RpcPredictionRequestsOnlyAcceptValidInputs) {
int int_data[] = {5, 6, 7, 8, 9};
std::vector<int> raw_data_vec;
for(int elem : int_data) {
raw_data_vec.push_back(elem);
}
std::shared_ptr<IntVector> int_vec = std::make_shared<IntVector>(raw_data_vec);
std::vector<std::shared_ptr<Input>> inputs;
inputs.push_back(int_vec);
// Without error, we should be able to directly construct an integer-typed
// PredictionRequest by supplying a vector of IntVector inputs
ASSERT_NO_THROW(rpc::PredictionRequest(inputs, InputType::Ints));
// Without error, we should be able to add an IntVector input to
// an integer-typed PredictionRequest
rpc::PredictionRequest ints_prediction_request(InputType::Ints);
ASSERT_NO_THROW(ints_prediction_request.add_input(int_vec));
// We expect an invalid argument exception when we attempt to construct a
// double-typed PredictionRequest by supplying a vector of IntVector inputs
ASSERT_THROW(rpc::PredictionRequest(inputs, InputType::Doubles), std::invalid_argument);
// We expect an invalid argument exception when we attempt to add
// an IntVector input to a double-typed PredictionRequest
rpc::PredictionRequest doubles_prediction_request(InputType::Doubles);
ASSERT_THROW(doubles_prediction_request.add_input(int_vec), std::invalid_argument);
}
template <typename T>
std::vector<std::vector<T>> get_primitive_hash_vectors() {
std::vector<std::vector<T>> hash_vectors;
std::vector<T> hash_vec_1;
for(uint8_t i = 0; i < 100; i++) {
T elem = static_cast<T>(i);
hash_vec_1.push_back(elem);
}
std::vector<T> hash_vec_2 = hash_vec_1;
std::vector<T> hash_vec_3 = hash_vec_1;
std::reverse(hash_vec_3.begin(), hash_vec_3.end());
hash_vectors.push_back(hash_vec_1);
hash_vectors.push_back(hash_vec_2);
hash_vectors.push_back(hash_vec_3);
return hash_vectors;
}
TEST(InputHashTests, IntVectorsHashCorrectly) {
// Obtains 3 vectors containing integer interpretations of unsigned bytes 0-99.
// The first two are identical, and the third is reversed
std::vector<std::vector<int>> int_hash_vecs = get_primitive_hash_vectors<int>();
ASSERT_EQ(IntVector(int_hash_vecs[0]).hash(), IntVector(int_hash_vecs[1]).hash());
ASSERT_NE(IntVector(int_hash_vecs[0]).hash(), IntVector(int_hash_vecs[2]).hash());
int_hash_vecs[1].pop_back();
// Removing the last element of the second vector renders the first two vectors
// distinct, so they should have different hashes
ASSERT_NE(IntVector(int_hash_vecs[0]).hash(), IntVector(int_hash_vecs[1]).hash());
int_hash_vecs[1].push_back(500);
// Adding the element 500, which is not present in the first vector, to the second vector
// leaves the first two vectors distinct, so they should have different hashes
ASSERT_NE(IntVector(int_hash_vecs[0]).hash(), IntVector(int_hash_vecs[1]).hash());
std::reverse(int_hash_vecs[2].begin(), int_hash_vecs[2].end());
// Reversing the third vector, which was initially the reverse of the first vector,
// renders the first and third vectors identical, so they should have the same hash
ASSERT_EQ(IntVector(int_hash_vecs[0]).hash(), IntVector(int_hash_vecs[2]).hash());
}
TEST(InputHashTests, FloatVectorsHashCorrectly) {
// Obtains 3 vectors containing float intepretations of unsigned bytes 0-99.
// The first two are identical, and the third is reversed
std::vector<std::vector<float>> float_hash_vecs = get_primitive_hash_vectors<float>();
ASSERT_EQ(FloatVector(float_hash_vecs[0]).hash(), FloatVector(float_hash_vecs[1]).hash());
ASSERT_NE(FloatVector(float_hash_vecs[0]).hash(), FloatVector(float_hash_vecs[2]).hash());
float_hash_vecs[1].pop_back();
// Removing the last element of the second vector renders the first two vectors
// distinct, so they should have different hashes
ASSERT_NE(FloatVector(float_hash_vecs[0]).hash(), FloatVector(float_hash_vecs[1]).hash());
float_hash_vecs[1].push_back(500);
// Adding the element 500.0, which is not present in the first vector, to the second vector
// leaves the first two vectors distinct, so they should have different hashes
ASSERT_NE(FloatVector(float_hash_vecs[0]).hash(), FloatVector(float_hash_vecs[1]).hash());
std::reverse(float_hash_vecs[2].begin(), float_hash_vecs[2].end());
// Reversing the third vector, which was initially the reverse of the first vector,
// renders the first and third vectors identical, so they should have the same hash
ASSERT_EQ(FloatVector(float_hash_vecs[0]).hash(), FloatVector(float_hash_vecs[2]).hash());
}
TEST(InputHashTests, DoubleVectorsHashCorrectly) {
// Obtains 3 vectors containing double intepretations of unsigned bytes 0-99.
// The first two are identical, and the third is reversed
std::vector<std::vector<double>> double_hash_vecs = get_primitive_hash_vectors<double>();
ASSERT_EQ(DoubleVector(double_hash_vecs[0]).hash(), DoubleVector(double_hash_vecs[1]).hash());
ASSERT_NE(DoubleVector(double_hash_vecs[0]).hash(), DoubleVector(double_hash_vecs[2]).hash());
double_hash_vecs[1].pop_back();
// Removing the last element of the second vector renders the first two vectors
// distinct, so they should have different hashes
ASSERT_NE(DoubleVector(double_hash_vecs[0]).hash(), DoubleVector(double_hash_vecs[1]).hash());
double_hash_vecs[1].push_back(500);
// Adding the element 500.0, which is not present in the first vector, to the second vector
// leaves the first two vectors distinct, so they should have different hashes
ASSERT_NE(DoubleVector(double_hash_vecs[0]).hash(), DoubleVector(double_hash_vecs[1]).hash());
std::reverse(double_hash_vecs[2].begin(), double_hash_vecs[2].end());
// Reversing the third vector, which was initially the reverse of the first vector,
// renders the first and third vectors identical, so they should have the same hash
ASSERT_EQ(DoubleVector(double_hash_vecs[0]).hash(), DoubleVector(double_hash_vecs[2]).hash());
}
TEST(InputHashTests, ByteVectorsHashCorrectly) {
// Obtains 3 vectors containing unsigned bytes 0-99.
// The first two are identical, and the third is reversed
std::vector<std::vector<uint8_t>> byte_hash_vecs = get_primitive_hash_vectors<uint8_t>();
ASSERT_EQ(ByteVector(byte_hash_vecs[0]).hash(), ByteVector(byte_hash_vecs[1]).hash());
ASSERT_NE(ByteVector(byte_hash_vecs[0]).hash(), ByteVector(byte_hash_vecs[2]).hash());
byte_hash_vecs[1].pop_back();
// Removing the last element of the second vector renders the first two vectors
// distinct, so they should have different hashes
ASSERT_NE(ByteVector(byte_hash_vecs[0]).hash(), ByteVector(byte_hash_vecs[1]).hash());
byte_hash_vecs[1].push_back(200);
// Adding an unsigned byte with value 200, which is not present in the first vector,
// to the second vector leaves the first two vectors distinct, so they should have different hashes
ASSERT_NE(ByteVector(byte_hash_vecs[0]).hash(), ByteVector(byte_hash_vecs[1]).hash());
std::reverse(byte_hash_vecs[2].begin(), byte_hash_vecs[2].end());
// Reversing the third vector, which was initially the reverse of the first vector,
// renders the first and third vectors identical, so they should have the same hash
ASSERT_EQ(ByteVector(byte_hash_vecs[0]).hash(), ByteVector(byte_hash_vecs[2]).hash());
}
TEST(InputHashTests, SerializableStringsHashCorrectly) {
std::string cat_string = "CAT";
std::string cat_string_copy = cat_string;
std::string tac_string = "TAC";
ASSERT_EQ(SerializableString(cat_string).hash(), SerializableString(cat_string_copy).hash());
ASSERT_NE(SerializableString(cat_string).hash(), SerializableString(tac_string).hash());
// The strings "CATS" and "CAT" are not equal, so they should have different hashes
ASSERT_NE(SerializableString(cat_string + "S").hash(), SerializableString(cat_string).hash());
std::reverse(tac_string.rbegin(), tac_string.rend());
// The reverse of the string "TAC" is "CAT", so cat_string and the reverse of tac_string
// should have identical hashes
ASSERT_EQ(SerializableString(cat_string).hash(), SerializableString(tac_string).hash());
}
} //namespace
| 52.525066
| 116
| 0.723665
|
yujialuo
|
ebbec5cf685a26b7183ce5989defac7d3d1abe40
| 12,530
|
cpp
|
C++
|
.build/egal-d-win32/src/OIS/src/win32/Win32JoyStick.old.cpp
|
Pength-TH/egal-D-engine
|
f16a8def566f678cb324bd901768d32f4412396f
|
[
"Apache-2.0"
] | null | null | null |
.build/egal-d-win32/src/OIS/src/win32/Win32JoyStick.old.cpp
|
Pength-TH/egal-D-engine
|
f16a8def566f678cb324bd901768d32f4412396f
|
[
"Apache-2.0"
] | null | null | null |
.build/egal-d-win32/src/OIS/src/win32/Win32JoyStick.old.cpp
|
Pength-TH/egal-D-engine
|
f16a8def566f678cb324bd901768d32f4412396f
|
[
"Apache-2.0"
] | null | null | null |
/*
The zlib/libpng License
Copyright (c) 2005-2007 Phillip Castaneda (pjcast -- www.wreckedgames.com)
This software is provided 'as-is', without any express or implied warranty. In no event will
the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose, including commercial
applications, and to alter it and redistribute it freely, subject to the following
restrictions:
1. The origin of this software must not be misrepresented; you must not claim that
you wrote the original software. If you use this software in a product,
an acknowledgment in the product documentation would be appreciated but is
not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "win32/Win32JoyStick.h"
#include "win32/Win32InputManager.h"
#include "win32/Win32ForceFeedback.h"
#include "OISEvents.h"
#include "OISException.h"
#include <cassert>
//DX Only defines macros for the JOYSTICK not JOYSTICK2, so fix it
#undef DIJOFS_BUTTON
#undef DIJOFS_POV
#define DIJOFS_BUTTON(n) (FIELD_OFFSET(DIJOYSTATE2, rgbButtons) + (n))
#define DIJOFS_POV(n) (FIELD_OFFSET(DIJOYSTATE2, rgdwPOV)+(n)*sizeof(DWORD))
#define DIJOFS_SLIDER0(n) (FIELD_OFFSET(DIJOYSTATE2, rglSlider)+(n) * sizeof(LONG))
#define DIJOFS_SLIDER1(n) (FIELD_OFFSET(DIJOYSTATE2, rglVSlider)+(n) * sizeof(LONG))
#define DIJOFS_SLIDER2(n) (FIELD_OFFSET(DIJOYSTATE2, rglASlider)+(n) * sizeof(LONG))
#define DIJOFS_SLIDER3(n) (FIELD_OFFSET(DIJOYSTATE2, rglFSlider)+(n) * sizeof(LONG))
using namespace OIS;
//--------------------------------------------------------------------------------------------------//
Win32JoyStick::Win32JoyStick( InputManager* creator, IDirectInput8* pDI,
bool buffered, DWORD coopSettings, const JoyStickInfo &info )
: JoyStick(info.vendor, buffered, info.devId, creator)
{
mDirectInput = pDI;
coopSetting = coopSettings;
mJoyStick = 0;
mJoyInfo = info; //mJoyInfo.deviceID = info.deviceID;
mFfDevice = 0;
}
//--------------------------------------------------------------------------------------------------//
Win32JoyStick::~Win32JoyStick()
{
delete mFfDevice;
if(mJoyStick)
{
mJoyStick->Unacquire();
mJoyStick->Release();
mJoyStick = 0;
}
//Return joystick to pool
static_cast<Win32InputManager*>(mCreator)->_returnJoyStick(mJoyInfo);
}
//--------------------------------------------------------------------------------------------------//
void Win32JoyStick::_initialize()
{
//Clear old state
mState.mAxes.clear();
delete mFfDevice;
mFfDevice = 0;
DIPROPDWORD dipdw;
dipdw.diph.dwSize = sizeof(DIPROPDWORD);
dipdw.diph.dwHeaderSize = sizeof(DIPROPHEADER);
dipdw.diph.dwObj = 0;
dipdw.diph.dwHow = DIPH_DEVICE;
dipdw.dwData = JOYSTICK_DX_BUFFERSIZE;
if(FAILED(mDirectInput->CreateDevice(mJoyInfo.deviceID, &mJoyStick, NULL)))
OIS_EXCEPT( E_General, "Win32JoyStick::_initialize() >> Could not initialize joy device!");
if(FAILED(mJoyStick->SetDataFormat(&c_dfDIJoystick2)))
OIS_EXCEPT( E_General, "Win32JoyStick::_initialize() >> data format error!");
HWND hwin = ((Win32InputManager*)mCreator)->getWindowHandle();
if(FAILED(mJoyStick->SetCooperativeLevel( hwin, coopSetting)))
OIS_EXCEPT( E_General, "Win32JoyStick::_initialize() >> failed to set cooperation level!");
if( FAILED(mJoyStick->SetProperty(DIPROP_BUFFERSIZE, &dipdw.diph)) )
OIS_EXCEPT( E_General, "Win32Mouse::Win32Mouse >> Failed to set buffer size property" );
//Enumerate all axes/buttons/sliders/etc before aquiring
_enumerate();
mState.clear();
capture();
}
//--------------------------------------------------------------------------------------------------//
void Win32JoyStick::_enumerate()
{
//We can check force feedback here too
mDIJoyCaps.dwSize = sizeof(DIDEVCAPS);
mJoyStick->GetCapabilities(&mDIJoyCaps);
mPOVs = (short)mDIJoyCaps.dwPOVs;
mState.mButtons.resize(mDIJoyCaps.dwButtons);
mState.mAxes.resize(mDIJoyCaps.dwAxes);
//Reset the axis mapping enumeration value
_AxisNumber = 0;
//Enumerate Force Feedback (if any)
mJoyStick->EnumEffects(DIEnumEffectsCallback, this, DIEFT_ALL);
//Enumerate and set axis constraints (and check FF Axes)
mJoyStick->EnumObjects(DIEnumDeviceObjectsCallback, this, DIDFT_AXIS);
}
//--------------------------------------------------------------------------------------------------//
BOOL CALLBACK Win32JoyStick::DIEnumDeviceObjectsCallback(LPCDIDEVICEOBJECTINSTANCE lpddoi, LPVOID pvRef)
{
Win32JoyStick* _this = (Win32JoyStick*)pvRef;
//Setup mappings
DIPROPPOINTER diptr;
diptr.diph.dwSize = sizeof(DIPROPPOINTER);
diptr.diph.dwHeaderSize = sizeof(DIPROPHEADER);
diptr.diph.dwHow = DIPH_BYID;
diptr.diph.dwObj = lpddoi->dwType;
//Add the high bit in so that an axis value of zero does not mean a null userdata
diptr.uData = 0x80000000 | _this->_AxisNumber;
//Check if axis is slider, if so, do not treat as regular axis
if(GUID_Slider == lpddoi->guidType)
{
++_this->mSliders;
//Decrease Axes, since this slider shows up in a different place
_this->mState.mAxes.pop_back();
}
else if (FAILED(_this->mJoyStick->SetProperty(DIPROP_APPDATA, &diptr.diph)))
{ //If for some reason we could not set needed user data, just ignore this axis
return DIENUM_CONTINUE;
}
//Increase for next time through
_this->_AxisNumber += 1;
//Set range
DIPROPRANGE diprg;
diprg.diph.dwSize = sizeof(DIPROPRANGE);
diprg.diph.dwHeaderSize = sizeof(DIPROPHEADER);
diprg.diph.dwHow = DIPH_BYID;
diprg.diph.dwObj = lpddoi->dwType;
diprg.lMin = MIN_AXIS;
diprg.lMax = MAX_AXIS;
if (FAILED(_this->mJoyStick->SetProperty(DIPROP_RANGE, &diprg.diph)))
OIS_EXCEPT( E_General, "Win32JoyStick::_DIEnumDeviceObjectsCallback >> Failed to set min/max range property" );
//Check if FF Axes
if((lpddoi->dwFlags & DIDOI_FFACTUATOR) != 0 )
{
if( _this->mFfDevice )
{
//todo - increment force feedback axis count
}
}
return DIENUM_CONTINUE;
}
//--------------------------------------------------------------------------------------------------//
BOOL CALLBACK Win32JoyStick::DIEnumEffectsCallback(LPCDIEFFECTINFO pdei, LPVOID pvRef)
{
Win32JoyStick* _this = (Win32JoyStick*)pvRef;
//Create the FF class after we know there is at least one effect type
if( _this->mFfDevice == 0 )
_this->mFfDevice = new Win32ForceFeedback(_this->mJoyStick, &_this->mDIJoyCaps);
_this->mFfDevice->_addEffectSupport( pdei );
return DIENUM_CONTINUE;
}
//--------------------------------------------------------------------------------------------------//
void Win32JoyStick::capture()
{
DIDEVICEOBJECTDATA diBuff[JOYSTICK_DX_BUFFERSIZE];
DWORD entries = JOYSTICK_DX_BUFFERSIZE;
// Poll the device to read the current state
HRESULT hr = mJoyStick->Poll();
if( hr == DI_OK )
hr = mJoyStick->GetDeviceData( sizeof(DIDEVICEOBJECTDATA), diBuff, &entries, 0 );
if( hr != DI_OK )
{
hr = mJoyStick->Acquire();
while( hr == DIERR_INPUTLOST )
hr = mJoyStick->Acquire();
// Poll the device to read the current state
mJoyStick->Poll();
hr = mJoyStick->GetDeviceData( sizeof(DIDEVICEOBJECTDATA), diBuff, &entries, 0 );
//Perhaps the user just tabbed away
if( FAILED(hr) )
return;
}
bool axisMoved[24] = {false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,
false,false,false,false,false,false,false,false};
bool sliderMoved[4] = {false,false,false,false};
//Loop through all the events
for(unsigned int i = 0; i < entries; ++i)
{
//First check to see if event entry is a Axis we enumerated earlier
if( diBuff[i].uAppData != 0xFFFFFFFF && diBuff[i].uAppData > 0 )
{
int axis = (int)(0x7FFFFFFF & diBuff[i].uAppData); //Mask out the high bit
assert( axis >= 0 && axis < (int)mState.mAxes.size() && "Axis out of range!");
mState.mAxes[axis].abs = diBuff[i].dwData;
axisMoved[axis] = true;
}
else
{
//This may seem outof order, but is in order of the way these variables
//are declared in the JoyStick State 2 structure.
switch(diBuff[i].dwOfs)
{
//------ slider -//
case DIJOFS_SLIDER0(0):
sliderMoved[0] = true;
mState.mSliders[0].abX = diBuff[i].dwData;
break;
case DIJOFS_SLIDER0(1):
sliderMoved[0] = true;
mState.mSliders[0].abY = diBuff[i].dwData;
break;
//----- Max 4 POVs Next ---------------//
case DIJOFS_POV(0):
if(!_changePOV(0,diBuff[i]))
return;
break;
case DIJOFS_POV(1):
if(!_changePOV(1,diBuff[i]))
return;
break;
case DIJOFS_POV(2):
if(!_changePOV(2,diBuff[i]))
return;
break;
case DIJOFS_POV(3):
if(!_changePOV(3,diBuff[i]))
return;
break;
case DIJOFS_SLIDER1(0):
sliderMoved[1] = true;
mState.mSliders[1].abX = diBuff[i].dwData;
break;
case DIJOFS_SLIDER1(1):
sliderMoved[1] = true;
mState.mSliders[1].abY = diBuff[i].dwData;
break;
case DIJOFS_SLIDER2(0):
sliderMoved[2] = true;
mState.mSliders[2].abX = diBuff[i].dwData;
break;
case DIJOFS_SLIDER2(1):
sliderMoved[2] = true;
mState.mSliders[2].abY = diBuff[i].dwData;
break;
case DIJOFS_SLIDER3(0):
sliderMoved[3] = true;
mState.mSliders[3].abX = diBuff[i].dwData;
break;
case DIJOFS_SLIDER3(1):
sliderMoved[3] = true;
mState.mSliders[3].abY = diBuff[i].dwData;
break;
//-----------------------------------------//
default:
//Handle Button Events Easily using the DX Offset Macros
if( diBuff[i].dwOfs >= DIJOFS_BUTTON(0) && diBuff[i].dwOfs < DIJOFS_BUTTON(128) )
{
if(!_doButtonClick((diBuff[i].dwOfs - DIJOFS_BUTTON(0)), diBuff[i]))
return;
}
break;
} //end case
} //End else
} //end for
//Check to see if any of the axes values have changed.. if so send events
if( mBuffered && mListener && entries > 0 )
{
JoyStickEvent temp(this, mState);
//Update axes
for( int i = 0; i < 24; ++i )
if( axisMoved[i] )
if( mListener->axisMoved( temp, i ) == false )
return;
//Now update sliders
for( int i = 0; i < 4; ++i )
if( sliderMoved[i] )
if( mListener->sliderMoved( temp, i ) == false )
return;
}
}
//--------------------------------------------------------------------------------------------------//
bool Win32JoyStick::_doButtonClick( int button, DIDEVICEOBJECTDATA& di )
{
if( di.dwData & 0x80 )
{
mState.mButtons[button] = true;
if( mBuffered && mListener )
return mListener->buttonPressed( JoyStickEvent( this, mState ), button );
}
else
{
mState.mButtons[button] = false;
if( mBuffered && mListener )
return mListener->buttonReleased( JoyStickEvent( this, mState ), button );
}
return true;
}
//--------------------------------------------------------------------------------------------------//
bool Win32JoyStick::_changePOV( int pov, DIDEVICEOBJECTDATA& di )
{
//Some drivers report a value of 65,535, instead of ?,
//for the center position
if(LOWORD(di.dwData) == 0xFFFF)
{
mState.mPOV[pov].direction = Pov::Centered;
}
else
{
switch(di.dwData)
{
case 0: mState.mPOV[pov].direction = Pov::North; break;
case 4500: mState.mPOV[pov].direction = Pov::NorthEast; break;
case 9000: mState.mPOV[pov].direction = Pov::East; break;
case 13500: mState.mPOV[pov].direction = Pov::SouthEast; break;
case 18000: mState.mPOV[pov].direction = Pov::South; break;
case 22500: mState.mPOV[pov].direction = Pov::SouthWest; break;
case 27000: mState.mPOV[pov].direction = Pov::West; break;
case 31500: mState.mPOV[pov].direction = Pov::NorthWest; break;
}
}
if( mBuffered && mListener )
return mListener->povMoved( JoyStickEvent( this, mState ), pov );
return true;
}
//--------------------------------------------------------------------------------------------------//
void Win32JoyStick::setBuffered(bool buffered)
{
mBuffered = buffered;
}
//--------------------------------------------------------------------------------------------------//
Interface* Win32JoyStick::queryInterface(Interface::IType type)
{
//Thought about using covariant return type here.. however,
//some devices may allow LED light changing, or other interface stuff
if( mFfDevice && type == Interface::ForceFeedback )
return mFfDevice;
else
return 0;
}
| 31.561713
| 119
| 0.636153
|
Pength-TH
|
ebc4a938378d298d83d334badc82e81252ff0f63
| 2,614
|
cpp
|
C++
|
VSProject/LeetCodeSol/UnitTest/RangeSumQueryTestSuite.cpp
|
wangxiaotao1980/leetCodeCPP
|
1806c00cd89eacddbdd20a7c33875f54400a20a8
|
[
"MIT"
] | null | null | null |
VSProject/LeetCodeSol/UnitTest/RangeSumQueryTestSuite.cpp
|
wangxiaotao1980/leetCodeCPP
|
1806c00cd89eacddbdd20a7c33875f54400a20a8
|
[
"MIT"
] | null | null | null |
VSProject/LeetCodeSol/UnitTest/RangeSumQueryTestSuite.cpp
|
wangxiaotao1980/leetCodeCPP
|
1806c00cd89eacddbdd20a7c33875f54400a20a8
|
[
"MIT"
] | null | null | null |
/*******************************************************************************************
* @file RangeSumQueryTestSuite.cpp 2015\12\10 19:10:01 $
* @author Wang Xiaotao<wangxiaotao1980@gmail.com> (中文编码测试)
* @note LeetCode No.307 Range Sum Query
*******************************************************************************************/
#include "gtest/gtest.h"
#include "../Src/NumArraySolution.hpp"
#include "disabled.hpp"
// ------------------------------------------------------------------------------------------
//
TEST(RangeSumQueryTestSuite, RangeSumQueryTestSuiteTestCase0)
{
std::vector<int> a{ 1 , 2 };
NumArray regionTree(a);
ASSERT_EQ(1, regionTree.sumRange(0, 0));
ASSERT_EQ(2, regionTree.sumRange(1, 1));
ASSERT_EQ(3, regionTree.sumRange(0, 1));
regionTree.update(0, 2);
ASSERT_EQ(2, a[0]);
ASSERT_EQ(2, regionTree.sumRange(0, 0));
ASSERT_EQ(2, regionTree.sumRange(1, 1));
ASSERT_EQ(4, regionTree.sumRange(0, 1));
regionTree.update(1, 1);
ASSERT_EQ(1, a[1]);
ASSERT_EQ(2, regionTree.sumRange(0, 0));
ASSERT_EQ(1, regionTree.sumRange(1, 1));
ASSERT_EQ(3, regionTree.sumRange(0, 1));
}
TEST(RangeSumQueryTestSuite, DISABLED_RangeSumQueryTestSuiteTestCase1)
{
std::vector<int> a{ 1, 2, 3 };
NumArray regionTree(a);
ASSERT_EQ(1, regionTree.sumRange(0, 0));
ASSERT_EQ(2, regionTree.sumRange(1, 1));
ASSERT_EQ(3, regionTree.sumRange(2, 2));
ASSERT_EQ(3, regionTree.sumRange(0, 1));
ASSERT_EQ(5, regionTree.sumRange(1, 2));
ASSERT_EQ(6, regionTree.sumRange(0, 2));
}
TEST(RangeSumQueryTestSuite, DISABLED_RangeSumQueryTestSuiteTestCase2)
{
std::vector<int> a{ 1, 2, 3 };
NumArray regionTree(a);
ASSERT_EQ(1, regionTree.sumRange(0, 0));
ASSERT_EQ(2, regionTree.sumRange(1, 1));
ASSERT_EQ(3, regionTree.sumRange(2, 2));
ASSERT_EQ(3, regionTree.sumRange(0, 1));
ASSERT_EQ(5, regionTree.sumRange(1, 2));
ASSERT_EQ(6, regionTree.sumRange(0, 2));
}
TEST(RangeSumQueryTestSuite, RangeSumQueryTestSuiteTestCase3)
{
std::vector<int> a{ 1, 3, 5 };
NumArray regionTree(a);
ASSERT_EQ(9, regionTree.sumRange(0, 2));
regionTree.update(1, 2);
ASSERT_EQ(2, a[1]);
ASSERT_EQ(1, regionTree.sumRange(0, 0));
ASSERT_EQ(2, regionTree.sumRange(1, 1));
ASSERT_EQ(5, regionTree.sumRange(2, 2));
ASSERT_EQ(3, regionTree.sumRange(0, 1));
ASSERT_EQ(7, regionTree.sumRange(1, 2));
ASSERT_EQ(8, regionTree.sumRange(0, 2));
}
//
// -------------------------------------------------------------------------------------------
| 31.493976
| 94
| 0.573451
|
wangxiaotao1980
|
ebc4c8e1a5f7e0f84bc4da374081d185dbb157ef
| 1,882
|
cpp
|
C++
|
1030/main.cpp
|
Heliovic/PAT_Solutions
|
7c5dd554654045308f2341713c3e52cc790beb59
|
[
"MIT"
] | 2
|
2019-03-18T12:55:38.000Z
|
2019-09-07T10:11:26.000Z
|
1030/main.cpp
|
Heliovic/My_PAT_Answer
|
7c5dd554654045308f2341713c3e52cc790beb59
|
[
"MIT"
] | null | null | null |
1030/main.cpp
|
Heliovic/My_PAT_Answer
|
7c5dd554654045308f2341713c3e52cc790beb59
|
[
"MIT"
] | null | null | null |
#include <cstdio>
#include <climits>
#include <algorithm>
#include <stack>
#define MAX_N 512
using namespace std;
int dis[MAX_N], cost[MAX_N], path[MAX_N], visit[MAX_N];
int N, M, S, D;
int graph[MAX_N][MAX_N][2];
void dijkstra(int v)
{
cost[v] = 0;
dis[v] = 0;
for (int i = 0; i < N - 1; i++)
{
visit[v] = 1;
for (int j = 0; j < N; j++)
{
if (visit[j] == 0 && graph[v][j][0] > 0 && dis[j] > dis[v] + graph[v][j][0])
{
dis[j] = dis[v] + graph[v][j][0];
cost[j] = cost[v] + graph[v][j][1];
path[j] = v;
} else if (visit[j] == 0 && graph[v][j][0] > 0 && dis[j] == dis[v] + graph[v][j][0] && cost[j] > cost[v] + graph[v][j][1])
{
cost[j] = cost[v] + graph[v][j][1];
path[j] = v;
}
}
int min_dis = INT_MAX;
for (int j = 0; j < N; j++)
{
if (visit[j] == 0 && dis[j] < min_dis)
{
min_dis = dis[j];
v = j;
}
}
}
}
void PrintPath(int k)
{
stack<int> p;
while (path[k] != -1)
{
p.push(k);
k = path[k];
}
printf("%d ", S);
while (!p.empty())
{
printf("%d ", p.top());
p.pop();
}
}
int main()
{
fill_n(dis, MAX_N, INT_MAX);
fill_n(cost, MAX_N, INT_MAX);
fill_n(path, MAX_N, -1);
fill_n(visit, MAX_N, 0);
fill_n(&graph[0][0][0], MAX_N * MAX_N * 2, -1);
scanf("%d %d %d %d", &N, &M, &S, &D);
for (int i = 0; i < M; i++)
{
int s, t, d, c;
scanf("%d %d %d %d", &s, &t, &d, &c);
graph[s][t][0] = d;
graph[s][t][1] = c;
graph[t][s][0] = d;
graph[t][s][1] = c;
}
dijkstra(S);
PrintPath(D);
printf("%d %d", dis[D], cost[D]);
return 0;
}
| 21.883721
| 134
| 0.392136
|
Heliovic
|
1b0eb356a537279bd2bb8cc73891c4d3afa32b77
| 2,536
|
cpp
|
C++
|
apps/POLite/pagerank-sync/Run.cpp
|
POETSII/jordmorr-tinsel
|
39249538d532e4945d9916748346c261dc5ea75d
|
[
"BSD-2-Clause"
] | 31
|
2019-09-18T10:55:47.000Z
|
2021-12-01T20:39:46.000Z
|
apps/POLite/pagerank-sync/Run.cpp
|
POETSII/jordmorr-tinsel
|
39249538d532e4945d9916748346c261dc5ea75d
|
[
"BSD-2-Clause"
] | 26
|
2019-10-13T13:33:04.000Z
|
2021-11-10T11:09:48.000Z
|
apps/POLite/pagerank-sync/Run.cpp
|
POETSII/jordmorr-tinsel
|
39249538d532e4945d9916748346c261dc5ea75d
|
[
"BSD-2-Clause"
] | 1
|
2020-09-11T17:32:43.000Z
|
2020-09-11T17:32:43.000Z
|
// SPDX-License-Identifier: BSD-2-Clause
#include "PageRank.h"
#include <HostLink.h>
#include <POLite.h>
#include <EdgeList.h>
#include <assert.h>
#include <iostream>
#include <sys/time.h>
int main(int argc, char **argv)
{
// Read in the example edge list and create data structure
if (argc != 2) {
printf("Specify edge file\n");
exit(EXIT_FAILURE);
}
// Connection to tinsel machine
HostLink hostLink;
// Create POETS graph
PGraph<PageRankDevice, PageRankState, None, PageRankMessage> graph;
// Load in the edge list file
printf("Loading in the graph..."); fflush(stdout);
EdgeList net;
net.read(argv[1]);
printf(" done\n");
// Print fan-out
printf("Min fan-out = %d\n", net.minFanOut());
printf("Max fan-out = %d\n", net.maxFanOut());
// Create nodes in POETS graph
for (uint32_t i = 0; i < net.numNodes; i++) {
PDeviceId id = graph.newDevice();
assert(i == id);
}
// Create connections in POETS graph
for (uint32_t i = 0; i < net.numNodes; i++) {
uint32_t numNeighbours = net.neighbours[i][0];
for (uint32_t j = 0; j < numNeighbours; j++)
graph.addEdge(i, 0, net.neighbours[i][j+1]);
}
// Prepare mapping from graph to hardware
printf("Mapping the graph..."); fflush(stdout);
graph.map();
printf(" done\n");
printf("Setting up devices..."); fflush(stdout);
// Specify number of time steps to run on each device
for (PDeviceId i = 0; i < graph.numDevices; i++) {
graph.devices[i]->state.fanOut = graph.fanOut(i);
}
printf(" done\n");
// Write graph down to tinsel machine via HostLink
printf("Loading the graph..."); fflush(stdout);
graph.write(&hostLink);
printf(" done\n");
// Load code and trigger execution
hostLink.boot("code.v", "data.v");
// Global accumulated score
float gscore = 0.0;
// Get start time
printf("Starting\n");
struct timeval start, finish, diff;
gettimeofday(&start, NULL);
hostLink.go();
// Consume performance stats
politeSaveStats(&hostLink, "stats.txt");
// Wait for response
PMessage<PageRankMessage> msg;
for (uint32_t i = 0; i < graph.numDevices; i++) {
hostLink.recvMsg(&msg, sizeof(msg));
gscore += msg.payload.val;
if (i == 0) {
// Get finish time
gettimeofday(&finish, NULL);
}
}
printf("Done\n");
printf("score=%.8f\n", gscore);
// Display time
timersub(&finish, &start, &diff);
double duration = (double) diff.tv_sec + (double) diff.tv_usec / 1000000.0;
printf("Time = %lf\n", duration);
return 0;
}
| 25.108911
| 77
| 0.639984
|
POETSII
|
1b17cd25e789caad4f5ab9957aed15e8217bbb8f
| 182
|
hpp
|
C++
|
src/game/physics.hpp
|
carstene1ns/pekka-kana-2
|
89e9eccf267ad40773af3717b8d93b3acf783a97
|
[
"MIT"
] | 55
|
2017-05-28T11:40:57.000Z
|
2022-02-22T17:15:46.000Z
|
src/game/physics.hpp
|
carstene1ns/pekka-kana-2
|
89e9eccf267ad40773af3717b8d93b3acf783a97
|
[
"MIT"
] | 11
|
2017-09-25T22:46:42.000Z
|
2022-01-21T12:43:27.000Z
|
src/game/physics.hpp
|
carstene1ns/pekka-kana-2
|
89e9eccf267ad40773af3717b8d93b3acf783a97
|
[
"MIT"
] | 21
|
2017-06-14T02:22:27.000Z
|
2022-03-23T08:44:13.000Z
|
//#########################
//Pekka Kana 2
//Copyright (c) 2003 Janne Kivilahti
//#########################
#pragma once
int Sprite_Movement(int i);
int BonusSprite_Movement(int i);
| 22.75
| 36
| 0.532967
|
carstene1ns
|
1b1825436230e1869a2fa2067ddf33b3c4404784
| 2,052
|
cpp
|
C++
|
timemachine/cpp/src/rmsd_align.cpp
|
proteneer/timemachine
|
feee9f24adcb533ab9e1c15a3f4fa4dcc9d9a701
|
[
"Apache-2.0"
] | 91
|
2019-01-05T17:03:04.000Z
|
2022-03-11T09:08:46.000Z
|
timemachine/cpp/src/rmsd_align.cpp
|
proteneer/timemachine
|
feee9f24adcb533ab9e1c15a3f4fa4dcc9d9a701
|
[
"Apache-2.0"
] | 474
|
2019-01-07T14:33:15.000Z
|
2022-03-31T19:15:12.000Z
|
timemachine/cpp/src/rmsd_align.cpp
|
proteneer/timemachine
|
feee9f24adcb533ab9e1c15a3f4fa4dcc9d9a701
|
[
"Apache-2.0"
] | 12
|
2019-01-13T00:40:36.000Z
|
2022-01-14T10:23:54.000Z
|
#include "rmsd_align.hpp"
#include <Eigen/Dense>
#include <iostream> // delete me
namespace timemachine {
/*
Optimally align x2 onto x1. In particular, x2 is shifted so that its centroid is placed
at the same position as the of x1's centroid. x2 is also rotated so that the RMSD
is minimized.
*/
void rmsd_align_cpu(const int N, const double *x1_raw, const double *x2_raw, double *x2_aligned_raw) {
Eigen::MatrixXd x1(N, 3);
Eigen::MatrixXd x2(N, 3);
for (int i = 0; i < N; i++) {
x1(i, 0) = x1_raw[i * 3 + 0];
x1(i, 1) = x1_raw[i * 3 + 1];
x1(i, 2) = x1_raw[i * 3 + 2];
x2(i, 0) = x2_raw[i * 3 + 0];
x2(i, 1) = x2_raw[i * 3 + 1];
x2(i, 2) = x2_raw[i * 3 + 2];
}
Eigen::Vector3d x1_centroid = x1.colwise().mean();
Eigen::Vector3d x2_centroid = x2.colwise().mean();
Eigen::Vector3d translation = x2_centroid - x1_centroid;
// shift to the center
Eigen::MatrixXd x1_centered = x1.rowwise() - x1_centroid.transpose();
Eigen::MatrixXd x2_centered = x2.rowwise() - x2_centroid.transpose();
// compute correlations
Eigen::MatrixXd c = x2_centered.transpose() * x1_centered;
Eigen::JacobiSVD<Eigen::MatrixXd> svd(c, Eigen::ComputeFullU | Eigen::ComputeFullV);
auto s = svd.singularValues();
Eigen::MatrixXd u = svd.matrixU();
Eigen::MatrixXd v = svd.matrixV();
Eigen::MatrixXd v_t = v.transpose();
bool is_reflection = u.determinant() * v_t.determinant() < 0.0;
if (is_reflection) {
for (int i = 0; i < 3; i++) {
u(i, 2) = -u(i, 2);
}
}
Eigen::MatrixXd rotation = u * v_t;
// x2 is centered
Eigen::MatrixXd x2_rot = x2_centered * rotation;
Eigen::MatrixXd x2_aligned = x2_rot.rowwise() - (translation.transpose() - x2_centroid.transpose());
for (int i = 0; i < N; i++) {
x2_aligned_raw[i * 3 + 0] = x2_aligned(i, 0);
x2_aligned_raw[i * 3 + 1] = x2_aligned(i, 1);
x2_aligned_raw[i * 3 + 2] = x2_aligned(i, 2);
}
}
} // namespace timemachine
| 31.090909
| 104
| 0.604776
|
proteneer
|
1b1bf794c85195093606d2ea98fae3a97727015a
| 543
|
cpp
|
C++
|
reflection.cpp
|
vsoftco/snippets
|
467520e285f9c83024416f050a5357bf659f4860
|
[
"MIT"
] | 13
|
2015-04-21T09:09:59.000Z
|
2021-11-27T11:00:40.000Z
|
reflection.cpp
|
vsoftco/snippets
|
467520e285f9c83024416f050a5357bf659f4860
|
[
"MIT"
] | null | null | null |
reflection.cpp
|
vsoftco/snippets
|
467520e285f9c83024416f050a5357bf659f4860
|
[
"MIT"
] | 3
|
2019-08-09T09:29:59.000Z
|
2021-01-09T08:52:11.000Z
|
// Basic compile-time reflection in C++11
#include <cstddef>
#include <iostream>
#include <typeinfo>
template <typename T>
struct Inspect;
template <typename R, typename... Args>
struct Inspect<R(Args... args)> {
using ReturnT = R; // return type
const static std::size_t ParamN = sizeof...(Args); // number of parameters
};
double f(int, float);
int main() {
std::cout << typeid(Inspect<decltype(f)>::ReturnT).name() << std::endl;
std::cout << Inspect<decltype(f)>::ParamN << std::endl;
}
| 24.681818
| 78
| 0.622468
|
vsoftco
|
1b1c39aa93694500238e15cec1f80a04d93635d1
| 10,679
|
cpp
|
C++
|
code/engine/xrGame/alife_monster_detail_path_manager.cpp
|
InNoHurryToCode/xray-162
|
fff9feb9ffb681b3c6ba1dc7c4534fe80006f87e
|
[
"Apache-2.0"
] | 58
|
2016-11-20T19:14:35.000Z
|
2021-12-27T21:03:35.000Z
|
code/engine/xrGame/alife_monster_detail_path_manager.cpp
|
InNoHurryToCode/xray-162
|
fff9feb9ffb681b3c6ba1dc7c4534fe80006f87e
|
[
"Apache-2.0"
] | 59
|
2016-09-10T10:44:20.000Z
|
2018-09-03T19:07:30.000Z
|
code/engine/xrGame/alife_monster_detail_path_manager.cpp
|
InNoHurryToCode/xray-162
|
fff9feb9ffb681b3c6ba1dc7c4534fe80006f87e
|
[
"Apache-2.0"
] | 39
|
2017-02-05T13:35:37.000Z
|
2022-03-14T11:00:12.000Z
|
////////////////////////////////////////////////////////////////////////////
// Module : alife_monster_detail_path_manager.cpp
// Created : 01.11.2005
// Modified : 22.11.2005
// Author : Dmitriy Iassenev
// Description : ALife monster detail path manager class
////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "alife_monster_detail_path_manager.h"
#include "ai_space.h"
#include "alife_simulator.h"
#include "alife_time_manager.h"
#include "xrServer_Objects_ALife_Monsters.h"
#include "game_graph.h"
#include "level_graph.h"
#include "game_level_cross_table.h"
#include "alife_smart_terrain_task.h"
#include "alife_graph_registry.h"
#include "graph_engine.h"
//#include "alife_monster_brain.h"
CALifeMonsterDetailPathManager::CALifeMonsterDetailPathManager(object_type* object) {
VERIFY(object);
m_object = object;
m_last_update_time = 0;
m_destination.m_game_vertex_id = this->object().get_object().m_tGraphID;
m_destination.m_level_vertex_id = this->object().get_object().m_tNodeID;
m_destination.m_position = this->object().get_object().o_Position;
m_walked_distance = 0.f;
}
void CALifeMonsterDetailPathManager::target(const GameGraph::_GRAPH_ID& game_vertex_id,
const u32& level_vertex_id, const Fvector& position) {
VERIFY(ai().game_graph().valid_vertex_id(game_vertex_id));
VERIFY((ai().game_graph().vertex(game_vertex_id)->level_id() !=
ai().alife().graph().level().level_id()) ||
ai().level_graph().valid_vertex_id(level_vertex_id));
VERIFY((ai().game_graph().vertex(game_vertex_id)->level_id() !=
ai().alife().graph().level().level_id()) ||
(ai().cross_table().vertex(level_vertex_id).game_vertex_id() == game_vertex_id));
VERIFY((ai().game_graph().vertex(game_vertex_id)->level_id() !=
ai().alife().graph().level().level_id()) ||
ai().level_graph().inside(level_vertex_id, position));
m_destination.m_game_vertex_id = game_vertex_id;
m_destination.m_level_vertex_id = level_vertex_id;
m_destination.m_position = position;
// Msg
//("[%6d][%s][%f][%f][%f]",Device.dwTimeGlobal,object().name_replace(),VPUSH(m_destination.m_position));
}
void CALifeMonsterDetailPathManager::target(const GameGraph::_GRAPH_ID& game_vertex_id) {
VERIFY(ai().game_graph().valid_vertex_id(game_vertex_id));
target(game_vertex_id, ai().game_graph().vertex(game_vertex_id)->level_vertex_id(),
ai().game_graph().vertex(game_vertex_id)->level_point());
}
void CALifeMonsterDetailPathManager::target(const CALifeSmartTerrainTask& task) {
target(task.game_vertex_id(), task.level_vertex_id(), task.position());
}
void CALifeMonsterDetailPathManager::target(const CALifeSmartTerrainTask* task) {
// Msg
//("[%6d][%s][%s]",Device.dwTimeGlobal,object().name_replace(),*task->patrol_path_name());
target(*task);
}
bool CALifeMonsterDetailPathManager::completed() const {
if (m_destination.m_game_vertex_id != object().get_object().m_tGraphID)
return (false);
if (m_destination.m_level_vertex_id != object().get_object().m_tNodeID)
return (false);
return (true);
}
bool CALifeMonsterDetailPathManager::actual() const {
if (failed())
return (false);
if (m_destination.m_game_vertex_id != m_path.front())
return (false);
return (true);
}
bool CALifeMonsterDetailPathManager::failed() const { return (m_path.empty()); }
void CALifeMonsterDetailPathManager::update() {
ALife::_TIME_ID current_time = ai().alife().time_manager().game_time();
if (current_time <= m_last_update_time)
return;
// if (ai().game_graph().vertex(object().m_tGraphID)->level_id() ==
//ai().level_graph().level_id()) Msg
//("[detail::update][%6d][%s]",Device.dwTimeGlobal,object().name_replace());
ALife::_TIME_ID time_delta = current_time - m_last_update_time;
update(time_delta);
// we advisedly "lost" time we need to process a query to avoid some undesirable effects
m_last_update_time = ai().alife().time_manager().game_time();
}
void CALifeMonsterDetailPathManager::make_inactual() { m_path.clear(); }
void CALifeMonsterDetailPathManager::actualize() {
m_path.clear();
typedef GraphEngineSpace::CGameVertexParams CGameVertexParams;
CGameVertexParams temp = CGameVertexParams(object().m_tpaTerrain);
bool failed = !ai().graph_engine().search(ai().game_graph(), object().get_object().m_tGraphID,
m_destination.m_game_vertex_id, &m_path, temp);
#ifdef DEBUG
if (failed) {
Msg("! %s couldn't build game path from", object().get_object().name_replace());
{
const CGameGraph::CVertex* vertex =
ai().game_graph().vertex(object().get_object().m_tGraphID);
LogMsg("! [{0}][{1}][{2}][{3}][{4}]", object().get_object().m_tGraphID,
ai().game_graph().header().level(vertex->level_id()).name(),
VPUSH(vertex->level_point()));
Msg("! game_graph_mask -> [ %d, %d, %d, %d]", vertex->vertex_type()[0],
vertex->vertex_type()[1], vertex->vertex_type()[2], vertex->vertex_type()[3]);
}
{
const CGameGraph::CVertex* vertex =
ai().game_graph().vertex(m_destination.m_game_vertex_id);
LogMsg("! [{0}][{1}][{2}][{3}][{4}]", m_destination.m_game_vertex_id,
ai().game_graph().header().level(vertex->level_id()).name(),
VPUSH(vertex->level_point()));
Msg("! game_graph_mask -> [ %d, %d, %d, %d]", vertex->vertex_type()[0],
vertex->vertex_type()[1], vertex->vertex_type()[2], vertex->vertex_type()[3]);
}
Msg("! List of available game_graph masks:");
xr_vector<GameGraph::STerrainPlace>::iterator I = object().m_tpaTerrain.begin();
xr_vector<GameGraph::STerrainPlace>::iterator E = object().m_tpaTerrain.end();
for (; I != E; ++I) {
Msg("! [%d , %d , %d , %d]", (*I).tMask[0], (*I).tMask[1], (*I).tMask[2],
(*I).tMask[3]);
};
}
#endif
if (failed)
return;
VERIFY(!m_path.empty());
if (m_path.size() == 1) {
VERIFY(m_path.back() == object().get_object().m_tGraphID);
return;
}
m_walked_distance = 0.f;
std::reverse(m_path.begin(), m_path.end());
VERIFY(m_path.back() == object().get_object().m_tGraphID);
}
void CALifeMonsterDetailPathManager::update(const ALife::_TIME_ID& time_delta) {
// first update has enormous time delta, therefore just skip it
if (!m_last_update_time)
return;
if (completed())
return;
if (!actual()) {
actualize();
if (failed())
return;
}
follow_path(time_delta);
}
void CALifeMonsterDetailPathManager::setup_current_speed() {
if (ai().game_graph().vertex(object().get_object().m_tGraphID)->level_id() ==
ai().level_graph().level_id())
speed(object().m_fCurrentLevelGoingSpeed);
else
speed(object().m_fGoingSpeed);
}
void CALifeMonsterDetailPathManager::follow_path(const ALife::_TIME_ID& time_delta) {
VERIFY(!completed());
VERIFY(!failed());
VERIFY(actual());
VERIFY(!m_path.empty());
if (m_path.back() != object().get_object().m_tGraphID) {
make_inactual();
}
if (m_path.size() == 1) {
VERIFY(object().get_object().m_tGraphID == m_destination.m_game_vertex_id);
m_walked_distance = 0.f;
object().get_object().m_tNodeID = m_destination.m_level_vertex_id;
object().get_object().o_Position = m_destination.m_position;
#ifdef DEBUG
object().m_fDistanceFromPoint = 0.f;
object().m_fDistanceToPoint = 0.f;
object().m_tNextGraphID = object().get_object().m_tGraphID;
#endif
return;
}
float last_time_delta = float(time_delta) / 1000.f;
for (; m_path.size() > 1;) {
setup_current_speed();
float update_distance =
(last_time_delta / ai().alife().time_manager().normal_time_factor()) * speed();
float distance_between = ai().game_graph().distance(
object().get_object().m_tGraphID, (GameGraph::_GRAPH_ID)m_path[m_path.size() - 2]);
if (distance_between > (update_distance + m_walked_distance)) {
m_walked_distance += update_distance;
#ifdef DEBUG
object().m_fDistanceFromPoint = m_walked_distance;
object().m_fDistanceToPoint = distance_between;
object().m_tNextGraphID = (GameGraph::_GRAPH_ID)m_path[m_path.size() - 2];
#endif
return;
}
update_distance += m_walked_distance;
update_distance -= distance_between;
last_time_delta =
update_distance * ai().alife().time_manager().normal_time_factor() / speed();
m_walked_distance = 0.f;
m_path.pop_back();
// Msg ("%6d %s changes
//graph point from %d to
//%d",Device.dwTimeGlobal,object().name_replace(),object().m_tGraphID,(GameGraph::_GRAPH_ID)m_path.back());
object().get_object().alife().graph().change(&object().get_object(),
object().get_object().m_tGraphID,
(GameGraph::_GRAPH_ID)m_path.back());
VERIFY(m_path.back() == object().get_object().m_tGraphID);
object().on_location_change();
VERIFY(m_path.back() == object().get_object().m_tGraphID);
}
}
void CALifeMonsterDetailPathManager::on_switch_online() { m_path.clear(); }
void CALifeMonsterDetailPathManager::on_switch_offline() { m_path.clear(); }
Fvector CALifeMonsterDetailPathManager::draw_level_position() const {
if (path().empty())
return (object().get_object().Position());
u32 path_size = path().size();
if (path_size == 1)
return (object().get_object().Position());
VERIFY(m_path.back() == object().get_object().m_tGraphID);
const GameGraph::CVertex* current = ai().game_graph().vertex(object().get_object().m_tGraphID);
const GameGraph::CVertex* next = ai().game_graph().vertex(m_path[path_size - 2]);
if (current->level_id() != next->level_id())
return (object().get_object().Position());
Fvector current_vertex = current->level_point();
Fvector next_vertex = next->level_point();
Fvector direction = Fvector().sub(next_vertex, current_vertex);
direction.normalize();
return (current_vertex.mad(direction, walked_distance()));
}
| 38.832727
| 115
| 0.631707
|
InNoHurryToCode
|
1b1de2d4614a40c2fef4b9cf34877ee86b1ce964
| 7,010
|
cpp
|
C++
|
Stardust/src/input/Input.cpp
|
LucidSigma/stardust
|
7012b46b0e75fa272e0bd39f3a1cc483c29fc10c
|
[
"MIT"
] | 7
|
2020-10-08T11:40:53.000Z
|
2022-03-30T10:40:06.000Z
|
Stardust/src/input/Input.cpp
|
LucidSigma/stardust
|
7012b46b0e75fa272e0bd39f3a1cc483c29fc10c
|
[
"MIT"
] | 1
|
2020-10-08T11:44:27.000Z
|
2020-12-01T08:43:19.000Z
|
Stardust/src/input/Input.cpp
|
LucidSigma/stardust
|
7012b46b0e75fa272e0bd39f3a1cc483c29fc10c
|
[
"MIT"
] | null | null | null |
#include "stardust/input/Input.h"
#include <algorithm>
#include <utility>
#include "stardust/debug/logging/Log.h"
#include "stardust/debug/message_box/MessageBox.h"
#include "stardust/math/Math.h"
#include "stardust/filesystem/vfs/VFS.h"
namespace stardust
{
[[nodiscard]] Status Input::InitialiseGameControllerDatabase(const StringView& controllerDatabaseFilepath)
{
const Vector<ubyte> controllerDatabaseFileData = vfs::ReadFileData(controllerDatabaseFilepath);
if (controllerDatabaseFileData.empty())
{
return Status::Fail;
}
SDL_RWops* controllerDatabaseRWOps = SDL_RWFromConstMem(controllerDatabaseFileData.data(), static_cast<i32>(controllerDatabaseFileData.size()));
if (controllerDatabaseRWOps == nullptr)
{
return Status::Fail;
}
if (SDL_GameControllerAddMappingsFromRW(controllerDatabaseRWOps, SDL_TRUE) == -1)
{
return Status::Fail;
}
return Status::Success;
}
[[nodiscard]] bool Input::IsMouseCaptured()
{
return s_isMouseCaptured;
}
void Input::CaptureMouse(const bool captureMouse)
{
s_isMouseInRelativeMode = SDL_CaptureMouse(static_cast<SDL_bool>(captureMouse)) == 0;
}
[[nodiscard]] bool Input::IsMouseInRelativeMode()
{
return s_isMouseInRelativeMode;
}
void Input::SetRelativeMouseMode(const bool isMouseRelative)
{
s_isMouseInRelativeMode = SDL_SetRelativeMouseMode(static_cast<SDL_bool>(isMouseRelative)) == 0;
if (s_isMouseInRelativeMode)
{
ClearRelativeMouseState();
}
}
void Input::ClearRelativeMouseState()
{
SDL_GetRelativeMouseState(nullptr, nullptr);
}
[[nodiscard]] bool Input::IsCursorShown()
{
return SDL_ShowCursor(SDL_QUERY) == SDL_ENABLE;
}
void Input::ShowCursor(const bool showCursor)
{
SDL_ShowCursor(showCursor ? SDL_ENABLE : SDL_DISABLE);
}
void Input::WarpMouse(const Window& window, const i32 x, const i32 y)
{
SDL_WarpMouseInWindow(window.GetRawHandle(), x, y);
}
[[nodiscard]] u32 Input::GetMaxGameControllers() noexcept
{
return s_maxGameControllers;
}
void Input::SetMaxGameControllers(const u32 maxGameControllers) noexcept
{
s_maxGameControllers = std::max(1u, maxGameControllers);
}
[[nodiscard]] u32 Input::GetGameControllerDeadzone() noexcept
{
return s_gameControllerDeadzone;
}
void Input::SetGameControllerDeadzone(const u32 gameControllerDeadzone) noexcept
{
s_gameControllerDeadzone = gameControllerDeadzone;
}
ObserverPtr<GameController> Input::AddGameController(const i32 id, const Locale& locale)
{
if (GetGameControllerCount() == s_maxGameControllers)
{
return nullptr;
}
GameController gameController(id);
const GameControllerID instanceID = SDL_JoystickInstanceID(gameController.GetRawJoystickHandle());
s_gameControllers.emplace(instanceID, std::move(gameController));
if (s_gameControllers.at(instanceID).GetRawHandle() == nullptr)
{
message_box::Show(
locale["engine"]["warnings"]["titles"]["controller"],
locale["engine"]["warnings"]["bodies"]["controller"],
message_box::Type::Warning
);
Log::EngineWarn("Could not add new game controller: {}.", SDL_GetError());
s_gameControllers.erase(instanceID);
return nullptr;
}
else
{
Log::EngineTrace("Controller {} added (Instance ID {}).", id, instanceID);
return &s_gameControllers.at(instanceID);
}
}
void Input::RemoveGameController(const GameControllerID instanceID)
{
if (s_gameControllers.contains(instanceID))
{
s_gameControllers.erase(instanceID);
Log::EngineTrace("Controller removed: {}", instanceID);
}
}
void Input::RemoveAllGameControllers() noexcept
{
s_gameControllers.clear();
}
[[nodiscard]] usize Input::GetGameControllerCount() noexcept
{
return s_gameControllers.size();
}
void Input::UpdateKeyboardState()
{
s_previousKeys = std::move(s_currentKeys);
s_currentKeys = std::move(Vector<u8>(SDL_GetKeyboardState(nullptr), SDL_GetKeyboardState(nullptr) + SDL_NUM_SCANCODES));
s_keyboardState = Keyboard(s_currentKeys.data(), s_previousKeys.data());
}
void Input::UpdateMouseState()
{
i32 x = 0;
i32 y = 0;
s_previousMouseButtonStates = s_currentMouseButtonStates;
s_currentMouseButtonStates = SDL_GetMouseState(&x, &y);
i32 relativeX = 0;
i32 relativeY = 0;
if (s_isMouseInRelativeMode)
{
SDL_GetRelativeMouseState(&relativeX, &relativeY);
}
s_mouseState.m_currentButtonStates = s_currentMouseButtonStates;
s_mouseState.m_previousButtonStates = s_previousMouseButtonStates;
s_mouseState.m_x = static_cast<f32>(x);
s_mouseState.m_y = static_cast<f32>(y);
s_mouseState.m_relativeX = static_cast<f32>(relativeX);
s_mouseState.m_relativeY = static_cast<f32>(relativeY);
}
void Input::ResetScrollState() noexcept
{
s_mouseState.m_yScrollAmount = 0;
}
void Input::UpdateScrollState(const i32 scrollAmount) noexcept
{
s_mouseState.m_yScrollAmount = scrollAmount;
}
void Input::UpdateGameControllers()
{
for (auto& [id, gameController] : s_gameControllers)
{
gameController.UpdateButtons();
gameController.UpdateAxes();
gameController.UpdateTouchpadFingers();
gameController.UpdateSensors();
}
}
[[nodiscard]] const Keyboard& Input::GetKeyboardState()
{
return s_keyboardState;
}
[[nodiscard]] const Mouse& Input::GetMouseState()
{
return s_mouseState;
}
[[nodiscard]] bool Input::DoesGameControllerExist(const GameControllerID instanceID)
{
return s_gameControllers.contains(instanceID);
}
[[nodiscard]] ObserverPtr<GameController> Input::GetGameController(const GameControllerID instanceID)
{
return DoesGameControllerExist(instanceID) ? &s_gameControllers.at(instanceID) : nullptr;
}
[[nodiscard]] ObserverPtr<GameController> Input::GetGameControllerByPlayerIndex(const u32 playerIndex)
{
for (auto& [id, gameController] : s_gameControllers)
{
if (gameController.m_playerIndex == playerIndex)
{
return &gameController;
}
}
return nullptr;
}
[[nodiscard]] const HashMap<Input::GameControllerID, GameController>& Input::GetGameControllers()
{
return s_gameControllers;
}
}
| 28.847737
| 152
| 0.646505
|
LucidSigma
|
1b2523928b7900f0ebd8ee852e33f3ebea9a6eb4
| 641
|
cpp
|
C++
|
Castenstein/Sky.cpp
|
bytecode77/castenstein
|
e2ebfe7f6dfec68bb09b751bf95a04d9ea2ca4a7
|
[
"BSD-2-Clause"
] | 16
|
2018-07-31T19:53:37.000Z
|
2022-01-23T15:44:58.000Z
|
Castenstein/Sky.cpp
|
bytecode77/castenstein
|
e2ebfe7f6dfec68bb09b751bf95a04d9ea2ca4a7
|
[
"BSD-2-Clause"
] | null | null | null |
Castenstein/Sky.cpp
|
bytecode77/castenstein
|
e2ebfe7f6dfec68bb09b751bf95a04d9ea2ca4a7
|
[
"BSD-2-Clause"
] | 4
|
2020-01-24T18:35:04.000Z
|
2021-09-05T16:18:02.000Z
|
#include "Castenstein.h"
Sky::Sky()
{
}
Sky::Sky(string path)
{
SDL_Surface *surface = Engine::LoadSDLSurface(path);
if ((surface->w & (surface->w - 1)) || (surface->h & (surface->h - 1))) throw;
Width = surface->w;
Height = surface->h;
WidthExponent = int(log2(Width));
Buffer = new int[Width * Height];
memcpy(Buffer, surface->pixels, Width * Height * 4);
SDL_FreeSurface(surface);
}
Sky::~Sky()
{
delete[] Buffer;
}
Sky* Sky::CreateDummySky()
{
Sky *sky = new Sky();
sky->Width = 1;
sky->Height = 1;
sky->WidthExponent = 0;
sky->Buffer = new int[0];
sky->Buffer[0] = 0xffffff;
return sky;
}
| 20.677419
| 80
| 0.603744
|
bytecode77
|
1b258dddc033ccc90851fdf2a03fe8bee54ee952
| 3,324
|
hpp
|
C++
|
Engine/Networking/NetworkSystem.hpp
|
achen889/Warlockery_Engine
|
160a14e85009057f4505ff5380a8c17258698f3e
|
[
"MIT"
] | null | null | null |
Engine/Networking/NetworkSystem.hpp
|
achen889/Warlockery_Engine
|
160a14e85009057f4505ff5380a8c17258698f3e
|
[
"MIT"
] | null | null | null |
Engine/Networking/NetworkSystem.hpp
|
achen889/Warlockery_Engine
|
160a14e85009057f4505ff5380a8c17258698f3e
|
[
"MIT"
] | null | null | null |
//==============================================================================================================
//NetworkSystem.hpp
//by Albert Chen Jan-14-2016.
//==============================================================================================================
#pragma once
#ifndef _included_NetworkSystem__
#define _included_NetworkSystem__
//===========================================================================================================
#include "Engine/Core/Utilities.hpp"
#include "Engine/Networking/NetworkSession.hpp"
//===========================================================================================================
//===========================================================================================================
class NetworkSystem;
extern NetworkSystem* theNetworkSystem;
class NetworkSystem {
public:
NetworkSystem();
~NetworkSystem() {
}
bool StartUp();
void ShutDown();
void Update();
NetworkSession* CreateSession();
void DestroySession(NetworkSession* session);
static bool StartSession(NetworkSession*& hostSession, short port);
UDPSocket* CreateUDPSocket(NetPacketQueue* queue, short port);
void FreeSocket(UDPSocket* socket);
static NetworkSession* s_gameSession;
static Byte GetMyConnIndex(NetConnection* conn);
};
///----------------------------------------------------------------------------------------------------------
///inline methods
inline UDPSocket* NetworkSystem::CreateUDPSocket(NetPacketQueue* queue, short port){
UDPSocket* sock = new UDPSocket(queue, port); //mem leak here
return sock;
}
//be sure to call join on the socket before freeing the memory, otherwise thread issues
inline void NetworkSystem::FreeSocket(UDPSocket* socket){
if (socket){
socket->m_isRunning = false;
socket->Join();
}
socket->Stop();
//then delete socket
delete socket;
socket = NULL;
}
//-----------------------------------------------------------------------------------------------------------
inline NetworkSession* NetworkSystem::CreateSession() {
NetworkSession* session = new NetworkSession(); //mem leak here
return session;
}
//-----------------------------------------------------------------------------------------------------------
inline void NetworkSystem::DestroySession(NetworkSession* session) {
if (session) {
delete session;
session = NULL;
}
}
//-----------------------------------------------------------------------------------------------------------
inline Byte NetworkSystem::GetMyConnIndex(NetConnection* conn) {
if (conn) {
return conn->GetConnIndex();
}
if (NetworkSystem::s_gameSession && NetworkSystem::s_gameSession->m_connSelf) {
return NetworkSystem::s_gameSession->m_connSelf->GetConnIndex();
}
return 0xff; //assume Invalid otherwise
}
//===========================================================================================================
///----------------------------------------------------------------------------------------------------------
///global helpers
std::string WindowsErrorAsString(DWORD error_id);
void* GetInAddress(sockaddr *sa);
std::string AllocLocalHostName();
//===========================================================================================================
#endif //__includedNetworkSystem__
| 27.02439
| 112
| 0.452768
|
achen889
|
1b27a771ce978644a8cf231d595181418cce6e1e
| 3,036
|
hpp
|
C++
|
sprout/math/exp.hpp
|
kevcadieux/Sprout
|
6b5addba9face0a6403e66e7db2aa94d87387f61
|
[
"BSL-1.0"
] | 691
|
2015-01-15T18:52:23.000Z
|
2022-03-15T23:39:39.000Z
|
sprout/math/exp.hpp
|
kevcadieux/Sprout
|
6b5addba9face0a6403e66e7db2aa94d87387f61
|
[
"BSL-1.0"
] | 22
|
2015-03-11T01:22:56.000Z
|
2021-03-29T01:51:45.000Z
|
sprout/math/exp.hpp
|
kevcadieux/Sprout
|
6b5addba9face0a6403e66e7db2aa94d87387f61
|
[
"BSL-1.0"
] | 57
|
2015-03-11T07:52:29.000Z
|
2021-12-16T09:15:33.000Z
|
/*=============================================================================
Copyright (c) 2011-2019 Bolero MURAKAMI
https://github.com/bolero-MURAKAMI/Sprout
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#ifndef SPROUT_MATH_EXP_HPP
#define SPROUT_MATH_EXP_HPP
#include <type_traits>
#include <sprout/config.hpp>
#include <sprout/workaround/std/cstddef.hpp>
#include <sprout/limits.hpp>
#include <sprout/detail/pow.hpp>
#include <sprout/math/detail/config.hpp>
#include <sprout/math/detail/float_compute.hpp>
#include <sprout/math/isnan.hpp>
#include <sprout/math/factorial.hpp>
#include <sprout/type_traits/enabler_if.hpp>
namespace sprout {
namespace math {
namespace detail {
#if SPROUT_USE_BUILTIN_CMATH_FUNCTION
inline SPROUT_CONSTEXPR float
builtin_exp(float x) {
return __builtin_expf(x);
}
inline SPROUT_CONSTEXPR double
builtin_exp(double x) {
return __builtin_exp(x);
}
inline SPROUT_CONSTEXPR long double
builtin_exp(long double x) {
return __builtin_expl(x);
}
#endif
template<typename T>
inline SPROUT_CONSTEXPR T
exp_impl_1(T x, std::size_t n, std::size_t last) {
return last - n == 1
? sprout::detail::pow_n(x, n) / sprout::math::unchecked_factorial<T>(n)
: sprout::math::detail::exp_impl_1(x, n, n + (last - n) / 2)
+ sprout::math::detail::exp_impl_1(x, n + (last - n) / 2, last)
;
}
template<typename T>
inline SPROUT_CONSTEXPR T
exp_impl(T x) {
return !(x > -1) ? T(1) / (T(1) + sprout::math::detail::exp_impl_1(-x, 1, sprout::math::factorial_limit<T>() / 2 + 1))
: T(1) + sprout::math::detail::exp_impl_1(x, 1, sprout::math::factorial_limit<T>() / 2 + 1)
;
}
} // namespace detail
//
// exp
//
template<
typename FloatType,
typename sprout::enabler_if<std::is_floating_point<FloatType>::value>::type = sprout::enabler
>
inline SPROUT_CONSTEXPR FloatType
exp(FloatType x) {
return sprout::math::isnan(x) ? x
: x == -sprout::numeric_limits<FloatType>::infinity() ? FloatType(0)
: x == sprout::numeric_limits<FloatType>::infinity() ? sprout::numeric_limits<FloatType>::infinity()
#if SPROUT_USE_BUILTIN_CMATH_FUNCTION
: sprout::math::detail::builtin_exp(x)
#else
: x == 0 ? FloatType(1)
: static_cast<FloatType>(sprout::math::detail::exp_impl(static_cast<typename sprout::math::detail::float_compute<FloatType>::type>(x)))
#endif
;
}
template<
typename IntType,
typename sprout::enabler_if<std::is_integral<IntType>::value>::type = sprout::enabler
>
inline SPROUT_CONSTEXPR double
exp(IntType x) {
return sprout::math::exp(static_cast<double>(x));
}
} // namespace math
using sprout::math::exp;
} // namespace sprout
#endif // #ifndef SPROUT_MATH_EXP_HPP
| 33.362637
| 140
| 0.637022
|
kevcadieux
|
1b28a239c889c3ee0ad32481e5ee61c766ec193d
| 6,674
|
cpp
|
C++
|
GEO/ProjectData.cpp
|
ThieJan/ogs5
|
a05837cac4de890db18845b5bc0cb002d1ca5829
|
[
"BSD-4-Clause"
] | null | null | null |
GEO/ProjectData.cpp
|
ThieJan/ogs5
|
a05837cac4de890db18845b5bc0cb002d1ca5829
|
[
"BSD-4-Clause"
] | null | null | null |
GEO/ProjectData.cpp
|
ThieJan/ogs5
|
a05837cac4de890db18845b5bc0cb002d1ca5829
|
[
"BSD-4-Clause"
] | null | null | null |
/**
* \file ProjectData.cpp
* 25/08/2010 KR Initial implementation
* \copyright
* Copyright (c) 2018, OpenGeoSys Community (http://www.opengeosys.org)
* Distributed under a Modified BSD License.
* See accompanying file LICENSE.txt or
* http://www.opengeosys.org/project/license
*/
#include "ProjectData.h"
#include "StringTools.h"
ProjectData::ProjectData() : _geoObjects(NULL)
{
}
ProjectData::~ProjectData()
{
delete _geoObjects;
for (std::map<std::string, MeshLib::CFEMesh*>::iterator it = _msh_vec.begin(); it != _msh_vec.end(); ++it)
delete it->second;
size_t nCond(_cond_vec.size());
for (size_t i = 0; i < nCond; i++)
delete _cond_vec[i];
}
void ProjectData::addMesh(MeshLib::CFEMesh* mesh, std::string& name)
{
isUniqueMeshName(name);
_msh_vec[name] = mesh;
}
const MeshLib::CFEMesh* ProjectData::getMesh(const std::string& name) const
{
return _msh_vec.find(name)->second;
}
bool ProjectData::removeMesh(const std::string& name)
{
delete _msh_vec[name];
size_t result = _msh_vec.erase(name);
return result > 0;
}
bool ProjectData::meshExists(const std::string& name)
{
if (_msh_vec.count(name) > 0)
return true;
return false;
}
void ProjectData::addProcess(ProcessInfo* pcs)
{
for (std::vector<ProcessInfo*>::const_iterator it = _pcs_vec.begin(); it != _pcs_vec.end(); ++it)
if ((*it)->getProcessType() == pcs->getProcessType())
{
std::cout << "Error in ProjectData::addProcess() - "
<< FiniteElement::convertProcessTypeToString(pcs->getProcessType()) << " process already exists."
<< "\n";
}
_pcs_vec.push_back(pcs);
}
const ProcessInfo* ProjectData::getProcess(FiniteElement::ProcessType type) const
{
for (std::vector<ProcessInfo*>::const_iterator it = _pcs_vec.begin(); it != _pcs_vec.end(); ++it)
if ((*it)->getProcessType() == type)
return *it;
std::cout << "Error in ProjectData::getProcess() - No " << FiniteElement::convertProcessTypeToString(type)
<< " process found..."
<< "\n";
return NULL;
}
bool ProjectData::removeProcess(FiniteElement::ProcessType type)
{
for (std::vector<ProcessInfo*>::iterator it = _pcs_vec.begin(); it != _pcs_vec.end(); ++it)
if ((*it)->getProcessType() == type)
{
delete *it;
_pcs_vec.erase(it);
return true;
}
std::cout << "Error in ProjectData::removeProcess() - No " << FiniteElement::convertProcessTypeToString(type)
<< " process found..."
<< "\n";
return false;
}
void ProjectData::addCondition(FEMCondition* cond)
{
_cond_vec.push_back(cond);
}
void ProjectData::addConditions(std::vector<FEMCondition*> conds)
{
for (size_t i = 0; i < conds.size(); i++)
_cond_vec.push_back(conds[i]);
}
const FEMCondition* ProjectData::getCondition(const std::string& geo_name,
GEOLIB::GEOTYPE type,
const std::string& cond_name) const
{
for (std::vector<FEMCondition*>::const_iterator it = _cond_vec.begin(); it != _cond_vec.end(); ++it)
if ((*it)->getAssociatedGeometryName().compare(geo_name) == 0)
if (((*it)->getGeoName().compare(cond_name) == 0) && ((*it)->getGeoType() == type))
return *it;
std::cout << "Error in ProjectData::getCondition() - No condition found with name \"" << cond_name << "\"..."
<< "\n";
return NULL;
}
const std::vector<FEMCondition*> ProjectData::getConditions(FiniteElement::ProcessType pcs_type,
std::string geo_name,
FEMCondition::CondType cond_type) const
{
// if all
if (pcs_type == FiniteElement::INVALID_PROCESS && geo_name.empty() && cond_type == FEMCondition::UNSPECIFIED)
return _cond_vec;
// else: filter according to parameters
std::vector<FEMCondition*> conds;
for (std::vector<FEMCondition*>::const_iterator it = _cond_vec.begin(); it != _cond_vec.end(); ++it)
{
if (((pcs_type == FiniteElement::INVALID_PROCESS) || (pcs_type == ((*it)->getProcessType())))
&& ((geo_name.empty() || ((*it)->getAssociatedGeometryName().compare(geo_name) == 0)))
&& ((cond_type == FEMCondition::UNSPECIFIED) || ((*it)->getCondType() == cond_type)))
conds.push_back(*it);
}
return conds;
}
void ProjectData::removeConditions(FiniteElement::ProcessType pcs_type,
std::string geo_name,
FEMCondition::CondType cond_type)
{
// if all
if (pcs_type == FiniteElement::INVALID_PROCESS && geo_name.empty() && cond_type == FEMCondition::UNSPECIFIED)
{
for (size_t i = 0; i < _cond_vec.size(); i++)
delete _cond_vec[i];
_cond_vec.clear();
return;
}
// else: filter according to parameters
for (std::vector<FEMCondition*>::iterator it = _cond_vec.begin(); it != _cond_vec.end();)
{
if (((pcs_type == FiniteElement::INVALID_PROCESS) || (pcs_type == ((*it)->getProcessType())))
&& ((geo_name.empty() || ((*it)->getAssociatedGeometryName().compare(geo_name) == 0)))
&& ((cond_type == FEMCondition::UNSPECIFIED) || ((*it)->getCondType() == cond_type)))
{
delete *it;
it = _cond_vec.erase(it);
}
else
++it;
}
}
bool ProjectData::removeCondition(const std::string& geo_name, GEOLIB::GEOTYPE type, const std::string& cond_name)
{
for (std::vector<FEMCondition*>::iterator it = _cond_vec.begin(); it != _cond_vec.end(); ++it)
{
if ((*it)->getAssociatedGeometryName().compare(geo_name) == 0)
if (((*it)->getGeoName().compare(cond_name) == 0) && ((*it)->getGeoType() == type))
{
delete *it;
_cond_vec.erase(it);
return true;
}
}
std::cout << "Error in ProjectData::removeCondition() - No condition found with name \"" << cond_name << "\"..."
<< "\n";
return false;
}
bool ProjectData::isUniqueMeshName(std::string& name)
{
int count(0);
bool isUnique(false);
std::string cpName;
while (!isUnique)
{
isUnique = true;
cpName = name;
count++;
// If the original name already exists we start to add numbers to name for
// as long as it takes to make the name unique.
if (count > 1)
cpName = cpName + "-" + number2str(count);
for (std::map<std::string, MeshLib::CFEMesh*>::iterator it = _msh_vec.begin(); it != _msh_vec.end(); ++it)
if (cpName.compare(it->first) == 0)
isUnique = false;
}
// At this point cpName is a unique name and isUnique is true.
// If cpName is not the original name, "name" is changed and isUnique is set to false,
// indicating that a vector with the original name already exists.
if (count > 1)
{
isUnique = false;
name = cpName;
}
return isUnique;
}
| 30.75576
| 114
| 0.633503
|
ThieJan
|
1b2b351ddd0e756bd1fe644d906cfbcda41fa396
| 14,177
|
cpp
|
C++
|
AIFS_ROS/hiperlab_rostools/src/QuadMocapRatesControl/ExampleVehicleStateMachine.cpp
|
muellerlab/agri-fly
|
6851f2f207e73300b4ed9be7ec1c72c2f23eeef5
|
[
"BSD-2-Clause"
] | 1
|
2022-03-09T21:31:49.000Z
|
2022-03-09T21:31:49.000Z
|
AIFS_ROS/hiperlab_rostools/src/QuadMocapRatesControl/ExampleVehicleStateMachine.cpp
|
muellerlab/agri-fly
|
6851f2f207e73300b4ed9be7ec1c72c2f23eeef5
|
[
"BSD-2-Clause"
] | 4
|
2022-02-11T18:24:49.000Z
|
2022-03-28T01:16:51.000Z
|
AIFS_ROS/hiperlab_rostools/src/QuadMocapRatesControl/ExampleVehicleStateMachine.cpp
|
muellerlab/agri-fly
|
6851f2f207e73300b4ed9be7ec1c72c2f23eeef5
|
[
"BSD-2-Clause"
] | null | null | null |
#include "ExampleVehicleStateMachine.hpp"
using namespace std;
using namespace Offboard;
ExampleVehicleStateMachine::ExampleVehicleStateMachine() {
_name = "INVALID";
_id = 0;
_flightStage = StageWaitForStart;
_lastFlightStage = StageComplete;
_systemLatencyTime = 0;
_vehicleIsReadyForProgramToExit = false;
_initPosition = Vec3d(0, 0, 0);
_desiredPosition = Vec3d(0, 0, 0);
_desiredYawAngle = 0;
_cmdYawAngle = 0;
_lastTelWarnings = 0;
_lastPos = Vec3d(0, 0, 0);
_lastVel = Vec3d(0, 0, 0);
_lastAcc = Vec3d(0, 0, 0);
_lastYaw = 0;
}
void ExampleVehicleStateMachine::CallbackEstimator(
const hiperlab_rostools::mocap_output& msg) {
if (_est->GetID() == msg.vehicleID) {
_est->UpdateWithMeasurement(
Vec3d(msg.posx, msg.posy, msg.posz),
Rotationd(msg.attq0, msg.attq1, msg.attq2, msg.attq3));
}
}
void ExampleVehicleStateMachine::CallbackTelemetry(
const hiperlab_rostools::telemetry& msg) {
_lastTelWarnings = msg.warnings;
}
void ExampleVehicleStateMachine::Initialize(int id, std::string name,
ros::NodeHandle &n,
BaseTimer* timer,
double systemLatencyTime) {
_id = id;
stringstream ss;
ss << "[" << name << " (" << _id << ")]: ";
_name = ss.str();
//set up networking stuff:
_subMocap.reset(
new ros::Subscriber(
n.subscribe("mocap_output" + std::to_string(_id), 1,
&ExampleVehicleStateMachine::CallbackEstimator, this)));
_subTelemetry.reset(
new ros::Subscriber(
n.subscribe("telemetry" + std::to_string(_id), 1,
&ExampleVehicleStateMachine::CallbackTelemetry, this)));
_pubEstimate.reset(
new ros::Publisher(
n.advertise<hiperlab_rostools::estimator_output>(
"estimator" + std::to_string(_id), 1)));
_pubCmd.reset(
new ros::Publisher(
n.advertise<hiperlab_rostools::radio_command>(
"radio_command" + std::to_string(_id), 1)));
//set up components:
_est.reset(new MocapStateEstimator(timer, _id, systemLatencyTime));
_systemLatencyTime = systemLatencyTime;
_ctrl.reset(new QuadcopterController());
_safetyNet.reset(new SafetyNet());
_flightStage = StageWaitForStart;
_lastFlightStage = StageComplete;
_stageTimer.reset(new Timer(timer));
// Initialize control parameters
Onboard::QuadcopterConstants::QuadcopterType quadcopterType =
Onboard::QuadcopterConstants::GetVehicleTypeFromID(_id);
Onboard::QuadcopterConstants vehConsts(quadcopterType);
_ctrl->SetParameters(vehConsts.posControl_natFreq,
vehConsts.posControl_damping,
vehConsts.attControl_timeConst_xy,
vehConsts.attControl_timeConst_z);
cout << _name << "Created.\n";
}
void ExampleVehicleStateMachine::Run(bool shouldStart, bool shouldStop) {
// Check for flight stage change
bool stageChange = _flightStage != _lastFlightStage;
_lastFlightStage = _flightStage;
if (stageChange) {
_stageTimer->Reset();
}
// Get the current state estimate and publish to ROS
MocapStateEstimator::MocapEstimatedState estState = _est->GetPrediction(
_systemLatencyTime);
_safetyNet->UpdateWithEstimator(estState,
_est->GetTimeSinceLastGoodMeasurement());
PublishEstimate(estState);
// Create radio message depending on the current flight stage
hiperlab_rostools::radio_command cmdMsg;
uint8_t rawMsg[RadioTypes::RadioMessageDecoded::RAW_PACKET_SIZE];
switch (_flightStage) {
case StageWaitForStart:
if (stageChange) {
cout << _name << "Waiting for start signal.\n";
}
if (shouldStart) {
_flightStage = StageSpoolUp;
}
break;
case StageSpoolUp:
if (stageChange) {
cout << _name << "Spooling up motors.\n";
}
if (!_safetyNet->GetIsSafe()) {
_flightStage = StageEmergency;
}
{
double const motorSpoolUpTime = 0.5; //[s]
double const spoolUpThrustByWeight = 0.25; //[]
_est->SetPredictedValues(Vec3d(0, 0, 0), Vec3d(0, 0, 0));
double cmdThrust = 9.81 * spoolUpThrustByWeight;
Vec3d cmdAngVel(0, 0, 0);
RadioTypes::RadioMessageDecoded::CreateRatesCommand(0, float(cmdThrust),
Vec3f(cmdAngVel),
rawMsg);
cmdMsg.debugtype = RadioTypes::externalRatesCmd;
cmdMsg.debugvals[0] = float(cmdThrust);
cmdMsg.debugvals[1] = float(cmdAngVel.x);
cmdMsg.debugvals[2] = float(cmdAngVel.y);
cmdMsg.debugvals[3] = float(cmdAngVel.z);
for (int i = 0; i < RadioTypes::RadioMessageDecoded::RAW_PACKET_SIZE;
i++) {
cmdMsg.raw[i] = rawMsg[i];
}
if (_stageTimer->GetSeconds<double>() > motorSpoolUpTime) {
_flightStage = StageTakeoff;
}
}
if (HaveLowBattery()) {
printf("LOW BATTERY!\n");
_flightStage = StageLanding;
}
break;
case StageTakeoff:
if (stageChange) {
cout << _name << "Taking off.\n";
_initPosition = estState.pos;
}
if (!_safetyNet->GetIsSafe()) {
_flightStage = StageEmergency;
}
{
double const takeOffTime = 2.0; //[s]
double frac = _stageTimer->GetSeconds<double>() / takeOffTime;
if (frac >= 1.0) {
_flightStage = StageFlight;
frac = 1.0;
}
Vec3d cmdPos = (1 - frac) * _initPosition + frac * _desiredPosition;
cmdMsg = RunControllerAndUpdateEstimator(estState, cmdPos,
Vec3d(0, 0, 0),
Vec3d(0, 0, 0));
}
if (HaveLowBattery()) {
printf("LOW BATTERY!\n");
_flightStage = StageLanding;
}
break;
case StageFlight:
if (stageChange) {
cout << _name << "Entering flight stage.\n";
}
if (!_safetyNet->GetIsSafe()) {
_flightStage = StageEmergency;
}
if (HaveLowBattery()) {
printf("LOW BATTERY!\n");
_flightStage = StageLanding;
}
{
// Command a specific trajectory
int trajID = 3; // 0 - fixed pt, 1 - circle, 2 - SHM
Vec3d cmdPos(0, 0, 0), cmdVel(0, 0, 0), cmdAcc(0, 0, 0);
double t = _stageTimer->GetSeconds<double>(); // I know 't' is a really bad name, sorry
double const getIntoActionTime = 2.0; //[s]
double frac = min(t / getIntoActionTime, 1.0);
switch (trajID) {
case 0: // Fixed set point
{
cmdPos = _desiredPosition;
cmdVel = Vec3d(0, 0, 0);
cmdAcc = Vec3d(0, 0, 0);
_cmdYawAngle = 0;
}
break;
case 1: // Circular trajectory
{
Vec3d circleCenter(0.0, -2.0, _desiredPosition.z);
double radius = 1.0; // [m]
double angSpeed = 0.5; // [rad/s]
cmdPos = circleCenter
+ radius * Vec3d(cos(angSpeed * t), sin(angSpeed * t), 0);
cmdVel = radius * angSpeed
* Vec3d(-sin(angSpeed * t), cos(angSpeed * t), 0);
cmdAcc = radius * pow(angSpeed, 2)
* Vec3d(-cos(angSpeed * t), -sin(angSpeed * t), 0);
_cmdYawAngle = _desiredYawAngle + angSpeed * t;
}
break;
case 2: // SHM trajectory
{
double amplitude = 1.0; // [m]
double angFreq = 2.0; // [rad/s]
cmdPos = _desiredPosition
+ amplitude * Vec3d(0, sin(angFreq * t), 0);
cmdVel = amplitude * angFreq * Vec3d(0, cos(angFreq * t), 0);
cmdAcc = amplitude * pow(angFreq, 2)
* Vec3d(0, -sin(angFreq * t), 0);
_cmdYawAngle = _desiredYawAngle;
}
break;
case 3: // Circle at Fixed Height Line Test
{
Vec3d circleCenter(0.0, 0.0, _desiredPosition.z);
double radius = 0.5; // [m]
double angSpeed = 1; // [rad/s]
cmdPos = circleCenter
+ radius * Vec3d(cos(angSpeed * t), sin(angSpeed * t), 0);
cmdVel = radius * angSpeed
* Vec3d(-sin(angSpeed * t), cos(angSpeed * t), 0);
cmdAcc = radius * pow(angSpeed, 2)
* Vec3d(-cos(angSpeed * t), -sin(angSpeed * t), 0);
_cmdYawAngle = 0;
}
break;
case 4: // Circle at Sinusoidal Height and Yaw
{
Vec3d circleCenter(0.0, 0.0, _desiredPosition.z);
double radius = 0.5; // [m]
double angSpeed = 0.5; // [rad/s]
cmdPos = circleCenter
+ radius * Vec3d(cos(angSpeed * t), sin(angSpeed * t), cos(angSpeed * t * 4));
cmdVel = radius * angSpeed
* Vec3d(-sin(angSpeed * t), cos(angSpeed * t), -sin(angSpeed * t * 4));
cmdAcc = radius * pow(angSpeed, 2)
* Vec3d(-cos(angSpeed * t), -sin(angSpeed * t), -cos(angSpeed * t * 4));
_cmdYawAngle = angSpeed*t;
}
break;
case 5: // Rotate Yaw at fixed position
{
cmdPos = _desiredPosition;
_cmdYawAngle = 0.2*t;
}
break;
}
_lastPos = (1 - frac) * _desiredPosition + frac * cmdPos;
_lastVel = frac * cmdVel;
_lastAcc = frac * cmdAcc;
cmdMsg = RunControllerAndUpdateEstimator(estState, _lastPos, _lastVel,
_lastAcc);
}
if (shouldStop) {
_flightStage = StageLanding;
}
break;
case StageLanding:
if (stageChange) {
cout << _name << "Starting landing.\n";
}
if (!_safetyNet->GetIsSafe()) {
_flightStage = StageEmergency;
}
{
double const LANDING_SPEED = 0.5; //m/s
double const getIntoActionTime = 2.0; //[s]
double frac = min(_stageTimer->GetSeconds<double>() / getIntoActionTime,
1.0);
Vec3d cmdPos = _lastPos
+ _stageTimer->GetSeconds<double>() * Vec3d(0, 0, -LANDING_SPEED);
if (cmdPos.z < 0) {
_flightStage = StageComplete;
}
cmdMsg = RunControllerAndUpdateEstimator(
estState, (1 - frac) * _lastPos + frac * cmdPos,
(1 - frac) * _lastVel + frac * Vec3d(0, 0, -LANDING_SPEED),
(1 - frac) * _lastAcc + frac * Vec3d(0, 0, 0));
}
break;
case StageComplete:
if (stageChange) {
cout << _name << "Landing complete. Idling.\n";
}
{
_est->SetPredictedValues(Vec3d(0, 0, 0), Vec3d(0, 0, 0));
//Publish the commands:
RadioTypes::RadioMessageDecoded::CreateIdleCommand(0, rawMsg);
for (int i = 0; i < RadioTypes::RadioMessageDecoded::RAW_PACKET_SIZE;
i++) {
cmdMsg.raw[i] = rawMsg[i];
}
cmdMsg.debugtype = RadioTypes::idleCommand;
}
if (_stageTimer->GetSeconds<double>() > 1.0) {
cout << _name << "Exiting.\n";
_vehicleIsReadyForProgramToExit = true;
}
break;
default:
case StageEmergency:
if (stageChange) {
cout << _name << "Emergency stage! Safety net = <"
<< _safetyNet->GetStatusString() << ">.\n";
}
RadioTypes::RadioMessageDecoded::CreateKillCommand(0, rawMsg);
for (int i = 0; i < RadioTypes::RadioMessageDecoded::RAW_PACKET_SIZE;
i++) {
cmdMsg.raw[i] = rawMsg[i];
}
cmdMsg.debugtype = RadioTypes::emergencyKill;
break;
}
cmdMsg.header.stamp = ros::Time::now();
_pubCmd->publish(cmdMsg);
}
void ExampleVehicleStateMachine::PublishEstimate(
MocapStateEstimator::MocapEstimatedState estState) {
// Publish the current state estimate
hiperlab_rostools::estimator_output estOutMsg;
estOutMsg.header.stamp = ros::Time::now();
estOutMsg.vehicleID = _est->GetID();
estOutMsg.posx = estState.pos.x;
estOutMsg.posy = estState.pos.y;
estOutMsg.posz = estState.pos.z;
estOutMsg.velx = estState.vel.x;
estOutMsg.vely = estState.vel.y;
estOutMsg.velz = estState.vel.z;
estOutMsg.attq0 = estState.att[0];
estOutMsg.attq1 = estState.att[1];
estOutMsg.attq2 = estState.att[2];
estOutMsg.attq3 = estState.att[3];
estOutMsg.attyaw = estState.att.ToEulerYPR().x;
estOutMsg.attpitch = estState.att.ToEulerYPR().y;
estOutMsg.attroll = estState.att.ToEulerYPR().z;
estOutMsg.angvelx = estState.angVel.x;
estOutMsg.angvely = estState.angVel.y;
estOutMsg.angvelz = estState.angVel.z;
_pubEstimate->publish(estOutMsg);
}
hiperlab_rostools::radio_command ExampleVehicleStateMachine::RunControllerAndUpdateEstimator(
MocapStateEstimator::MocapEstimatedState estState, Vec3d desPos,
Vec3d desVel, Vec3d desAcc) {
// Run the rates controller
Vec3d cmdAngVel;
double cmdThrust;
_ctrl->Run(estState.pos, estState.vel, estState.att, desPos, desVel, desAcc,
_cmdYawAngle, cmdAngVel, cmdThrust);
//Tell the estimator:
_est->SetPredictedValues(
cmdAngVel,
(estState.att * Vec3d(0, 0, 1) * cmdThrust - Vec3d(0, 0, 9.81)));
//Create and return the radio command
uint8_t rawMsg[RadioTypes::RadioMessageDecoded::RAW_PACKET_SIZE];
RadioTypes::RadioMessageDecoded::CreateRatesCommand(0, float(cmdThrust),
Vec3f(cmdAngVel), rawMsg);
hiperlab_rostools::radio_command cmdMsg;
for (int i = 0; i < RadioTypes::RadioMessageDecoded::RAW_PACKET_SIZE; i++) {
cmdMsg.raw[i] = rawMsg[i];
}
cmdMsg.debugvals[0] = float(cmdThrust);
cmdMsg.debugvals[1] = float(cmdAngVel.x);
cmdMsg.debugvals[2] = float(cmdAngVel.y);
cmdMsg.debugvals[3] = float(cmdAngVel.z);
cmdMsg.debugtype = RadioTypes::externalRatesCmd;
return cmdMsg;
}
| 32.741339
| 96
| 0.579178
|
muellerlab
|
1b2bb45071d6890b39189d0301ce6deb8fdf96c1
| 287
|
cpp
|
C++
|
naive_simulation_works/systemc_for_dummies/half_adder/MyTestBenchMonitor.cpp
|
VSPhaneendraPaluri/pvsdrudgeworks
|
5827f45567eecbcf0bb606de6adb1fb94fe2d8c6
|
[
"MIT"
] | null | null | null |
naive_simulation_works/systemc_for_dummies/half_adder/MyTestBenchMonitor.cpp
|
VSPhaneendraPaluri/pvsdrudgeworks
|
5827f45567eecbcf0bb606de6adb1fb94fe2d8c6
|
[
"MIT"
] | null | null | null |
naive_simulation_works/systemc_for_dummies/half_adder/MyTestBenchMonitor.cpp
|
VSPhaneendraPaluri/pvsdrudgeworks
|
5827f45567eecbcf0bb606de6adb1fb94fe2d8c6
|
[
"MIT"
] | null | null | null |
#include <systemc.h>
#include "MyTestBenchMonitor.h"
void MyTestBenchMonitor::Display_Patterns()
{
cout << "At time : " << sc_time_stamp();
cout << "\ta = " << TBMonitor_a << "\tb = " << TBMonitor_b;
cout << "\tCarry = " << TBMonitor_carry << "\tSum = " << TBMonitor_sum << endl;
}
| 26.090909
| 80
| 0.620209
|
VSPhaneendraPaluri
|
1b2ec6d330971fcc560985d7bbd22e36761359c8
| 15,773
|
cpp
|
C++
|
usb-device.cpp
|
KeyboxWallet/keyboxd
|
67c9103aaf48d5e83c922311acf5a4deab8c0755
|
[
"MIT"
] | 2
|
2018-11-26T10:40:46.000Z
|
2019-05-30T05:30:01.000Z
|
usb-device.cpp
|
KeyboxWallet/keyboxd
|
67c9103aaf48d5e83c922311acf5a4deab8c0755
|
[
"MIT"
] | null | null | null |
usb-device.cpp
|
KeyboxWallet/keyboxd
|
67c9103aaf48d5e83c922311acf5a4deab8c0755
|
[
"MIT"
] | 1
|
2018-10-16T10:17:23.000Z
|
2018-10-16T10:17:23.000Z
|
#include "usb-device.hpp"
#include "keybox-proto-types.h"
#include "keybox-errcodes.h"
#include "messages.pb.h"
#include "base64.h"
#include "buffer-utils.hpp"
#include <sstream>
#include "device-manager.hpp"
#include <streambuf>
struct membuf : std::streambuf
{
membuf(char *begin, char *end)
{
this->setg(begin, begin, end);
}
};
UsbDevice::UsbDevice(libusb_device *device, boost::asio::io_context *ioc)
{
//mServerPath = serverPath;
mDevice = libusb_ref_device(device);
// devId += "1";
// struct libusb_device_descriptor descriptor;
int err = libusb_get_device_descriptor(device, &mDescriptor);
if (err)
{
//todo: fatal
// libusb_unref_device(device);
mDisconnectedFlag = true;
return;
}
mBus = libusb_get_bus_number(device);
mPort = libusb_get_port_number(device);
mAddress = libusb_get_device_address(device);
std::stringstream devId; //= "USB";
devId << "USB:" << mBus << "_" << mPort << "_" << mAddress
<< "_" << mDescriptor.idVendor
<< "_" << mDescriptor.idProduct
<< "_" << mDescriptor.bcdDevice;
mDeviceId = devId.str();
mContext = ioc;
mRpcStatus = IDLE;
mDevHandle = NULL;
mWriteTransfer = libusb_alloc_transfer(0);
mReadTransfer = libusb_alloc_transfer(0);
mDisconnectedFlag = false;
mResetFlag = false;
}
bool UsbDevice::maybeDisconnected()
{
return mDisconnectedFlag;
}
UsbDevice::~UsbDevice()
{
std::cerr << "~UsbDevice\n" ;
if (mDevHandle)
{
libusb_close(mDevHandle);
mDevHandle = NULL;
}
libusb_unref_device(mDevice);
libusb_free_transfer(mWriteTransfer);
libusb_free_transfer(mReadTransfer);
}
bool UsbDevice::isSameDevice(libusb_device *device)
{
// todo: implem
struct libusb_device_descriptor descriptor;
int err = libusb_get_device_descriptor(device, &descriptor);
if (err)
{
return false;
}
if (mBus != libusb_get_bus_number(device))
{
return false;
}
if (mPort != libusb_get_port_number(device))
{
return false;
}
if (mAddress != libusb_get_device_address(device))
{
return false;
}
#define SAME_FIELD(fname) \
if (mDescriptor.fname != descriptor.fname) \
return false;
SAME_FIELD(bcdUSB)
SAME_FIELD(bDeviceClass)
SAME_FIELD(bDeviceSubClass)
SAME_FIELD(bDeviceProtocol)
SAME_FIELD(idVendor)
SAME_FIELD(idProduct)
SAME_FIELD(bcdDevice)
SAME_FIELD(bNumConfigurations)
return true;
}
bool UsbDevice::connect()
{
if (mDevHandle)
{
return true;
}
int r;
r = libusb_open(mDevice, &mDevHandle);
if (r)
{
std::cerr << "error open " << libusb_error_name(r) << "\n";
return false;
}
r = libusb_kernel_driver_active(mDevHandle, 0);
if (r && r != LIBUSB_ERROR_NOT_SUPPORTED)
{
r = libusb_detach_kernel_driver(mDevHandle, 0);
}
if (r && r != LIBUSB_ERROR_NOT_SUPPORTED)
{
std::cerr << "kernel active or detach " << libusb_error_name(r) << "\n";
libusb_close(mDevHandle);
mDevHandle = NULL;
return false;
}
r = libusb_claim_interface(mDevHandle, 0);
if (r)
{
std::cerr << "error claim " << libusb_error_name(r) << "\n";
libusb_close(mDevHandle);
mDevHandle = NULL;
return false;
}
return true;
}
void UsbDevice::disconnect()
{
if (!mDevHandle)
{
return;
}
if( mRpcStatus != IDLE) {
libusb_cancel_transfer(mWriteTransfer);
libusb_cancel_transfer(mReadTransfer);
mRpcStatus = IDLE;
}
libusb_close(mDevHandle);
mDevHandle = NULL;
}
bool UsbDevice::isConnected()
{
return mDevHandle;
}
const std::string UsbDevice::deviceId()
{
return mDeviceId;
}
extern "C"
{
#ifndef NDEBUG
void myToHex(uint8_t *srcbuf, int srcLen, char *dstBuff)
{
static char hexString[] = "0123456789ABCDEF";
int i;
for (i=0; i<srcLen; i++){
dstBuff[2*i] = hexString[(srcbuf[i] & 0xF0) >> 4];
dstBuff[2*i + 1] = hexString[srcbuf[i] & 0xF];
}
dstBuff[2*i] = 0;
}
#endif
void LIBUSB_CALL writeComplete(struct libusb_transfer *transfer)
{
UsbDevice *dev = (UsbDevice *)transfer->user_data;
boost::asio::post(std::bind(&UsbDevice::writehandle, dev, transfer->status, 1024));
#ifndef NDEBUG
char buff[32*2 + 1];
myToHex(transfer->buffer, 32, buff);
std::cerr << "write handle "
<< transfer->status
<< " first 32 bytes: \n"
<< (char*)buff << "\n";
#endif
}
void LIBUSB_CALL readComplete(struct libusb_transfer *transfer)
{
UsbDevice *dev = (UsbDevice *)transfer->user_data;
boost::asio::post(std::bind(&UsbDevice::readhandle, dev, transfer->status, 1024));
#ifndef NDEBUG
char buff[32*2 + 1];
myToHex(transfer->buffer, 32, buff);
std::cerr << "read handle "
<< transfer->status
<< " first 32 bytes: \n"
<< (char*)buff << "\n";
#endif
}
}
void UsbDevice::call_async(const std::string &method, const json ¶ms, DevCallbackFn cb)
{
json r;
boost::system::error_code error;
if (!mDevHandle)
{
return cb(KEYBOX_ERROR_CLIENT_ISSUE, "you should connect the device first", r);
}
if (mRpcStatus != IDLE)
{
return cb(KEYBOX_ERROR_CLIENT_ISSUE, "another call in progress.", r);
}
if( mResetFlag ){
//return cb()
return;
}
// write to socket
std::ostream o_2(&mBufferContent);
mCurrentMethod = method;
uint32_t type;
uint32_t len = 0;
type = MsgTypeLowLimit;
int32_t errCode;
std::string errMessage;
json_rpc_to_protobuf(method, params, errCode, errMessage, type, &o_2);
if (errCode == 0)
{
type = htonl(type);
len = htonl(mBufferContent.size());
mRpcStatus = WRITING;
//boost::asio::async_write(*mSocket, buffers,
// std::bind(&UsbDevice::writehandle, this, cb, std::placeholders::_1, std::placeholders::_2));
//
bool multipkg = false;
if (mBufferContent.size() < 1015)
{ // one packet message
usb_write_pkg[0] = 1; //
}
else
{ // multi-package message
usb_write_pkg[0] = 2;
multipkg = true;
}
memcpy(usb_write_pkg + 1, (char *)&type, 4);
memcpy(usb_write_pkg + 5, (char *)&len, 4);
auto bufs = mBufferContent.data();
int len = copy2RawBuffer(bufs, usb_write_pkg + 9, 1015);
mBufferContent.consume(len);
nextWriteOffset = len;
mCb = cb;
libusb_fill_bulk_transfer(mWriteTransfer, mDevHandle, 2, usb_write_pkg, 1024, writeComplete, this, 2000);
errCode = libusb_submit_transfer(mWriteTransfer);
if (errCode)
{
mRpcStatus = IDLE;
return cb(errCode, "io error", r);
}
}
else
{
cb(errCode, errMessage, r);
}
}
void UsbDevice::writehandle(enum libusb_transfer_status ec, size_t length)
{
json r;
if( mResetFlag ){
if (ec != LIBUSB_TRANSFER_COMPLETED){
std::cerr << "write error " << libusb_error_name(ec) << "\n";
mResetFlag = false;
return;
}
}
if (ec != LIBUSB_TRANSFER_COMPLETED)
{
mRpcStatus = IDLE;
std::cerr << "write error " << libusb_error_name(ec) << "\n";
mCb(KEYBOX_ERROR_SERVER_ISSUE, "io: write error", r);
mDisconnectedFlag = true;
resetDevice();
/*
if (ec == LIBUSB_TRANSFER_NO_DEVICE)
{
DeviceManager::getDeviceManager(NULL)->rmDevice(this);
}*/
return;
}
int readTimeout;
if( !mResetFlag && mCurrentMethod == "signReq"){ // methods needs to be confirmed by user.
readTimeout = 50000; // 50s
}
else {
readTimeout = 5000; // 5s
}
if (mBufferContent.size())
{ // more pkg to send
readTimeout = 2000;
}
libusb_fill_bulk_transfer(mReadTransfer, mDevHandle, 129, usb_read_pkg, 1024, readComplete, this, readTimeout);
int errorCode;
errorCode = libusb_submit_transfer(mReadTransfer);
if (errorCode)
{
if( mResetFlag){
mResetFlag = false;
}
else{
mRpcStatus = IDLE;
return mCb(KEYBOX_ERROR_SERVER_ISSUE, "io error,submit write", r);
}
}
}
void UsbDevice::writeAckPackge()
{
json r;
// write ack
usb_write_pkg[0] = 4;
libusb_fill_bulk_transfer(mWriteTransfer, mDevHandle, 2, usb_write_pkg, 1024, writeComplete, this, 2000);
int errCode = libusb_submit_transfer(mWriteTransfer);
if (errCode)
{
mRpcStatus = IDLE;
return mCb(KEYBOX_ERROR_SERVER_ISSUE, "io error, submit writing", r);
}
}
void UsbDevice::readhandle(enum libusb_transfer_status ec, size_t length)
{
json r;
if( mResetFlag ){
mResetFlag = false;
return;
}
if (mBufferContent.size())
{ // more pkg to send, write.
if (usb_read_pkg[0] != 4)
{
mRpcStatus = IDLE;
mCb(KEYBOX_ERROR_SERVER_ISSUE, "internal io error, multi-pkg write, reading ack", r);
return;
}
//
usb_write_pkg[0] = 3;
int off = htonl(nextWriteOffset);
memcpy(usb_write_pkg + 1, &off, 4);
auto bufs = mBufferContent.data();
int len = copy2RawBuffer(bufs, usb_write_pkg + 5, 1019);
nextWriteOffset += len;
mBufferContent.consume(len);
libusb_fill_bulk_transfer(mWriteTransfer, mDevHandle, 2, usb_write_pkg, 1024, writeComplete, this, 2000);
int errCode;
errCode = libusb_submit_transfer(mWriteTransfer);
if (errCode)
{
mRpcStatus = IDLE;
std::cerr << "write submit transfer error " << libusb_error_name(r) << "\n";
mCb(KEYBOX_ERROR_SERVER_ISSUE, "io error", r);
return;
}
}
else if (ec == LIBUSB_TRANSFER_COMPLETED)
{
// read pkg ok
if (mRpcStatus == WRITING)
{
mRpcStatus = READING_HEADER;
/*parse first packet */
if (length != 1024 || (usb_read_pkg[0] != 1 && usb_read_pkg[0] != 2))
{
mRpcStatus = IDLE;
mCb(KEYBOX_ERROR_SERVER_ISSUE, "internal read issue", r);
return;
}
int msgType, msgLen;
memcpy(&msgType, usb_read_pkg + 1, 4);
memcpy(&msgLen, usb_read_pkg + 5, 4);
msgType = ntohl(msgType);
msgLen = ntohl(msgLen);
if( (usb_read_pkg[0] == 1 && msgLen > 1015) ||
(usb_read_pkg[0] == 2 && msgLen < 1015)
) {
mRpcStatus = IDLE;
mCb(KEYBOX_ERROR_SERVER_ISSUE, "protocol issue: pkg error from wallet", r);
return;
}
if (msgLen <= 1015)
{
membuf m((char *)usb_read_pkg + 9, (char *)usb_read_pkg + 9 + msgLen);
std::istream istream(&m);
int32_t errCode;
std::string errMessage;
if (msgType == MsgTypeRequestRejected)
{
RequestRejected rej;
if (rej.ParseFromIstream(&istream))
{
mRpcStatus = IDLE;
mCb(rej.errcode(), rej.errmessage(), r);
return;
}
}
protobuf_to_json_rpc(msgType, &istream, mCurrentMethod, errCode, errMessage, r);
mRpcStatus = IDLE;
mCb(errCode, errMessage, r);
}
else
{
large_msg_type = msgType;
large_msg = new uint8_t[msgLen];
memcpy(large_msg, usb_read_pkg + 9, 1015);
large_msg_offset = 1015;
mRpcStatus = READING_CONTENT;
writeAckPackge();
}
}
else if (mRpcStatus == READING_CONTENT)
{
// expected new
if (length != 1024 || usb_read_pkg[0] != 3)
{
mRpcStatus = IDLE;
mCb(KEYBOX_ERROR_SERVER_ISSUE, "internal read issue", r);
return;
}
int msgOffset;
memcpy(&msgOffset, usb_read_pkg + 1, 4);
msgOffset = ntohl(msgOffset);
if (msgOffset != large_msg_offset)
{
mRpcStatus = IDLE;
mCb(KEYBOX_ERROR_SERVER_ISSUE, "internal read error: offset mismatch", r);
return;
}
int remLen = large_msg_len - msgOffset;
if (remLen <= 1019)
{ // final pkg
memcpy(large_msg + msgOffset, usb_read_pkg + 5, remLen);
membuf m((char *)large_msg, (char *)large_msg + large_msg_len);
std::istream istream(&m);
int32_t errCode;
std::string errMessage;
if (large_msg_type == MsgTypeRequestRejected)
{
RequestRejected rej;
if (rej.ParseFromIstream(&istream))
{
mRpcStatus = IDLE;
mCb(rej.errcode(), rej.errmessage(), r);
return;
}
// return;
}
protobuf_to_json_rpc(large_msg_type, &istream, mCurrentMethod, errCode, errMessage, r);
mRpcStatus = IDLE;
mCb(errCode, errMessage, r);
}
else
{
memcpy(large_msg + msgOffset, usb_read_pkg + 5, 1019);
large_msg_offset += 1019;
writeAckPackge();
}
}
else
{
mRpcStatus = IDLE;
mCb(KEYBOX_ERROR_SERVER_ISSUE, "internal status issue", r);
return;
}
}
else if (ec == LIBUSB_TRANSFER_TIMED_OUT)
{ // read again
std::cerr << "read timeout " << ec << "\n";
if( mCurrentMethod == "signReq"){
int readTimeout = 50000;
libusb_fill_bulk_transfer(mReadTransfer, mDevHandle, 129, usb_read_pkg, 1024, readComplete, this, readTimeout);
int errCode;
errCode = libusb_submit_transfer(mReadTransfer);
if (errCode)
{
mRpcStatus = IDLE;
return mCb(KEYBOX_ERROR_SERVER_ISSUE, "io error, submit to read", r);
}
}
else{
mRpcStatus = IDLE;
mDisconnectedFlag = true;
mCb(KEYBOX_ERROR_SERVER_ISSUE, "io error: read timeout", r);
resetDevice();
}
}
else
{
mRpcStatus = IDLE;
mDisconnectedFlag = true;
mCb(KEYBOX_ERROR_SERVER_ISSUE, "io error: read", r);
resetDevice();
}
}
void UsbDevice::resetDevice()
{
memset(usb_write_pkg, 0, 1024);
usb_write_pkg[0] = 5;
mResetFlag = true;
std::cerr << "resetting device " << "\n";
libusb_fill_bulk_transfer(mWriteTransfer, mDevHandle, 2, usb_write_pkg, 1024, writeComplete, this, 2000);
int errCode;
errCode = libusb_submit_transfer(mWriteTransfer);
if( errCode ){
std::cerr << "error write " << errCode << "\n";
mResetFlag = false;
return;
}
}
| 28.471119
| 126
| 0.548596
|
KeyboxWallet
|
1b395593b2764ebfed69f0214e767ed26b8d2cf2
| 1,285
|
cpp
|
C++
|
src/Modeling/BaseMesh.cpp
|
fcaillaud/SARAH
|
ca79c7d9449cf07eec9d5cc13293ec0c128defc1
|
[
"MIT"
] | null | null | null |
src/Modeling/BaseMesh.cpp
|
fcaillaud/SARAH
|
ca79c7d9449cf07eec9d5cc13293ec0c128defc1
|
[
"MIT"
] | null | null | null |
src/Modeling/BaseMesh.cpp
|
fcaillaud/SARAH
|
ca79c7d9449cf07eec9d5cc13293ec0c128defc1
|
[
"MIT"
] | null | null | null |
#include "BaseMesh.hpp"
namespace Sarah
{
namespace Modeling
{
BaseMesh::BaseMesh(std::string p_meshName):
m_name(p_meshName),
m_vertices(),
m_faces(),
m_colors(),
m_glMesh()
{
m_vertices.push_back(geo::Vertex(-50, -50, -50));
m_colors.push_back(geo::Vertex(1, 0, 0));
m_vertices.push_back(geo::Vertex(-50, 50, -50));
m_colors.push_back(geo::Vertex(0, 1, 0));
m_vertices.push_back(geo::Vertex(-50, -50, 50));
m_colors.push_back(geo::Vertex(0, 0, 1));
Face face; face.push_back(0); face.push_back(1); face.push_back(2);
m_faces.push_back(face);
m_glMesh = new GLfloat[(m_vertices.size() + m_colors.size()) * 3];
}
BaseMesh::~BaseMesh()
{
delete m_glMesh;
}
GLfloat * BaseMesh::Draw()
{
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
for(unsigned int i = 0; i < m_vertices.size(); ++i)
{
m_glMesh[(i*6)] = m_vertices[i].GetX();
m_glMesh[(i*6) + 1] = m_vertices[i].GetY();
m_glMesh[(i*6) + 2] = m_vertices[i].GetZ();
m_glMesh[(i*6) + 3] = m_colors[i].GetX();
m_glMesh[(i*6) + 4] = m_colors[i].GetY();
m_glMesh[(i*6) + 5] = m_colors[i].GetZ();
}
return m_glMesh;
}
}
}
| 21.416667
| 69
| 0.642023
|
fcaillaud
|
1b3b67e9dc8ef2a1bbd0bc4953a39acc6c7be881
| 1,637
|
cpp
|
C++
|
seed/DSP/decimator/decimator.cpp
|
KrisTiasMusic/DaisyExamples
|
340cca01798ada16287c2328d5a46259f40141bf
|
[
"MIT"
] | 1
|
2022-03-18T01:24:33.000Z
|
2022-03-18T01:24:33.000Z
|
seed/DSP/decimator/decimator.cpp
|
KrisTiasMusic/DaisyExamples
|
340cca01798ada16287c2328d5a46259f40141bf
|
[
"MIT"
] | null | null | null |
seed/DSP/decimator/decimator.cpp
|
KrisTiasMusic/DaisyExamples
|
340cca01798ada16287c2328d5a46259f40141bf
|
[
"MIT"
] | null | null | null |
#include "daisysp.h"
#include "daisy_seed.h"
// Shortening long macro for sample rate
#ifndef sample_rate
#endif
// Interleaved audio definitions
#define LEFT (i)
#define RIGHT (i + 1)
using namespace daisysp;
using namespace daisy;
static DaisySeed seed;
static Oscillator osc;
static Decimator decim;
static Phasor phs;
static void AudioCallback(AudioHandle::InterleavingInputBuffer in,
AudioHandle::InterleavingOutputBuffer out,
size_t size)
{
float osc_out, decimated_out;
float downsample_amt;
for(size_t i = 0; i < size; i += 2)
{
// Generate a pure sine wave
osc_out = osc.Process();
// Modulate downsample amount via Phasor
downsample_amt = phs.Process();
decim.SetDownsampleFactor(downsample_amt);
// downsample and bitcrush
decimated_out = decim.Process(osc_out);
// outputs
out[LEFT] = decimated_out;
out[RIGHT] = decimated_out;
}
}
int main(void)
{
// initialize seed hardware and daisysp modules
float sample_rate;
seed.Configure();
seed.Init();
seed.SetAudioBlockSize(4);
sample_rate = seed.AudioSampleRate();
osc.Init(sample_rate);
phs.Init(sample_rate, 0.5f);
decim.Init();
// Set parameters for oscillator
osc.SetWaveform(osc.WAVE_SIN);
osc.SetFreq(220);
osc.SetAmp(0.25);
// Set downsampling, and bit crushing values.
decim.SetDownsampleFactor(0.4f);
decim.SetBitsToCrush(8);
// start callback
seed.StartAudio(AudioCallback);
while(1) {}
}
| 23.724638
| 69
| 0.638363
|
KrisTiasMusic
|
1b3c1b899506d8e7c41f3a8a87a1bd81ca4f16ec
| 21,836
|
cpp
|
C++
|
thirdparty/packaged/vmem/VirtualMem.cpp
|
BoneCrasher/ShirabeEngine
|
39b3aa2c5173084d59b96b7f60c15207bff0ad04
|
[
"MIT"
] | 5
|
2019-12-02T12:28:57.000Z
|
2021-04-07T21:21:13.000Z
|
thirdparty/packaged/vmem/VirtualMem.cpp
|
BoneCrasher/ShirabeEngine
|
39b3aa2c5173084d59b96b7f60c15207bff0ad04
|
[
"MIT"
] | null | null | null |
thirdparty/packaged/vmem/VirtualMem.cpp
|
BoneCrasher/ShirabeEngine
|
39b3aa2c5173084d59b96b7f60c15207bff0ad04
|
[
"MIT"
] | 1
|
2020-01-09T14:25:42.000Z
|
2020-01-09T14:25:42.000Z
|
/*
Copyright 2010 - 2017 PureDev Software Ltd. All Rights Reserved.
This file is part of VMem.
VMem is dual licensed. For use in open source software VMem can
be used under the GNU license. For use in commercial applications a
license can be purchased from PureDev Software.
If used under the GNU license VMem 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 3 of the License,
or (at your option) any later version.
Under the GNU Public License VMem 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 VMem. If not, see <http://www.gnu.org/licenses/>.
VMem can only be used in commercial products if a commercial license has been purchased
from PureDev Software. Please see http://www.puredevsoftware.com/vmem/License.htm
*/
//------------------------------------------------------------------------
#include "VMem_PCH.hpp"
#include "VirtualMem.hpp"
#include "VMemCore.hpp"
#include "VMemThread.hpp"
#include "VMemCriticalSection.hpp"
#include "VMemHashMap.hpp"
#include "BasicFSA.hpp"
#include "RangeMap.hpp"
#include "List.hpp"
//------------------------------------------------------------------------
#ifdef VMEM_ENABLE
//------------------------------------------------------------------------
namespace VMem
{
//------------------------------------------------------------------------
VirtualMem::VirtualMem(int page_size)
: m_PageSize(page_size),
m_Reservations(page_size)
#ifdef VMEM_ENABLE_STATS
,m_ReservedOverhead(0)
#endif
#ifdef VMEM_DECOMMIT_CACHE
,m_PendingDecommitBytes(0)
,m_PendingReleaseBytes(0)
,m_ReleaseNodePool(page_size)
,m_DecommitNodePool(page_size)
,m_RangeMapAllocator(page_size)
,m_DecommitNodeMap(&m_RangeMapAllocator, page_size)
,m_CurrentFrame(0)
#endif
{
}
//------------------------------------------------------------------------
VirtualMem::~VirtualMem()
{
#ifdef VMEM_DECOMMIT_CACHE
CriticalSectionScope lock(m_CriticalSection);
FlushMemory(true);
#endif
}
//------------------------------------------------------------------------
#ifdef VMEM_DECOMMIT_CACHE
int VirtualMem::GetReleaseNodeBucketIndex(size_t size)
{
return VMin((int)(size / (1024*1024)), m_ReleaseNodeBucketCount-1);
}
#endif
//------------------------------------------------------------------------
void* VirtualMem::Reserve(size_t size, int align, int reserve_flags)
{
VMEM_ASSERT(size > 0 && (size & (m_PageSize-1)) == 0, "Invalid size passed to VirtualReserve");
void* p = NULL;
size_t aligned_size = size;
bool needs_aligning = align != m_PageSize;
#ifdef VMEM_DECOMMIT_CACHE
int bucket_index = GetReleaseNodeBucketIndex(size);
#endif
CriticalSectionScope lock(m_CriticalSection);
#ifdef VMEM_DECOMMIT_CACHE
// try ad find an existing released node in the release node buckets
List<ReleaseNode>& node_list = m_ReleaseNodeBuckets[bucket_index];
ReleaseNode* p_node_end = node_list.GetIterEnd();
for(ReleaseNode* p_node=node_list.GetHead(); p_node!=p_node_end; p_node=p_node->mp_Next)
{
if(p_node->m_Size == size && p_node->m_Align == align && p_node->m_ReserveFlags == reserve_flags)
{
p = p_node->mp_Mem;
node_list.Remove(p_node);
aligned_size = p_node->m_AlignedSize;
m_ReleaseNodePool.Free(p_node);
m_PendingReleaseBytes -= size;
break;
}
}
#endif
// if we didn't find a pre-existing released node reserve from the OS
if(!p)
{
if(needs_aligning)
{
VMEM_ASSERT((align & (m_PageSize-1)) == 0, "bad alignment");
aligned_size = AlignSizeUpPow2(aligned_size + align-1, m_PageSize);
}
p = VMem::VirtualReserve(aligned_size, m_PageSize, reserve_flags);
if(!p)
{
#ifdef VMEM_DECOMMIT_CACHE
FlushMemory(true);
p = VMem::VirtualReserve(aligned_size, m_PageSize, reserve_flags);
if(!p)
#endif
return NULL;
}
VMEM_STATS(m_ReservedOverhead += aligned_size - size);
}
// record the virtual alloc and hash it based on the ALIGNED address
Reservation reservation;
reservation.mp_BaseAddr = p;
reservation.m_Align = align;
reservation.m_ReserveFlags = reserve_flags;
reservation.m_Size = size;
reservation.m_AlignedSize = aligned_size;
if(needs_aligning)
p = AlignUp((byte*)p, align);
if(!m_Reservations.Add(p, reservation))
{
VMem::VirtualRelease(reservation.mp_BaseAddr, reservation.m_AlignedSize);
VMEM_STATS(m_ReservedOverhead -= reservation.m_AlignedSize - reservation.m_Size);
return NULL; // out of memory
}
return p;
}
//------------------------------------------------------------------------
void VirtualMem::Release(void* p)
{
CriticalSectionScope lock(m_CriticalSection);
VMEM_ASSERT(p != NULL && ((size_t)p & (m_PageSize-1)) == 0, "Invalid address passed to VirtualRelease");
Reservation reservation = m_Reservations.Remove(p);
#ifdef VMEM_DECOMMIT_CACHE
p = reservation.mp_BaseAddr;
size_t size = reservation.m_AlignedSize;
VMEM_ASSERT(size > 0 && (size & (m_PageSize-1)) == 0, "Invalid size passed to VirtualRelease");
int bucket_index = GetReleaseNodeBucketIndex(size);
ReleaseNode* p_node = m_ReleaseNodePool.Alloc();
if(!p_node)
{
// out of memory so release immediately
DecommitNodesInRange(reservation.mp_BaseAddr, reservation.m_AlignedSize);
VMem::VirtualRelease(reservation.mp_BaseAddr, reservation.m_AlignedSize);
VMEM_STATS(m_ReservedOverhead -= reservation.m_AlignedSize - reservation.m_Size);
return;
}
p_node->mp_Mem = p;
p_node->m_Size = reservation.m_Size;
p_node->m_AlignedSize = reservation.m_AlignedSize;
p_node->m_Align = reservation.m_Align;
p_node->m_ReserveFlags = reservation.m_ReserveFlags;
p_node->mp_Next = NULL;
p_node->mp_Prev = NULL;
p_node->m_FlushFrame = m_CurrentFrame + VMEM_DECOMMIT_CACHE_RELEASE_FRAME_DELAY;
m_ReleaseNodeBuckets[bucket_index].AddHead(p_node);
m_PendingReleaseBytes += reservation.m_Size;
#else
VMem::VirtualRelease(reservation.mp_BaseAddr, reservation.m_AlignedSize);
VMEM_STATS(m_ReservedOverhead -= reservation.m_AlignedSize - reservation.m_Size);
#endif
}
//------------------------------------------------------------------------
bool VirtualMem::Commit(void* p, size_t size, int commit_flags)
{
#ifdef VMEM_DECOMMIT_CACHE
CriticalSectionScope lock(m_CriticalSection);
VMEM_ASSERT(p != NULL && ((size_t)p & (m_PageSize-1)) == 0, "Invalid address passed to VirtualCommit");
VMEM_ASSERT(size >= 0 && (size & (m_PageSize-1)) == 0, "Invalid size passed to VirtualCommit");
bool succeeded = TryCommit(p, size, commit_flags);
if(!succeeded)
{
FlushMemory(true);
succeeded = TryCommit(p, size, commit_flags);
}
if(succeeded)
{
VMEM_MEMSET(p, VMEM_COMMITTED_MEM, size);
VMEM_ASSERT(VMem::Committed(p, size), "Commit succeeded but memory is not committed!");
}
return succeeded;
#else
return VMem::VirtualCommit(p, size, m_PageSize, commit_flags);
#endif
}
//------------------------------------------------------------------------
#ifdef VMEM_DECOMMIT_CACHE
void VirtualMem::DecommitNodesInRange(void* p, size_t size)
{
DecommitNode* p_node = m_DecommitNodeList.GetHead();
DecommitNode* p_node_end = m_DecommitNodeList.GetIterEnd();
while(p_node != p_node_end)
{
DecommitNode* p_next = p_node->mp_Next;
// if there is any overlap decommit it
if((byte*)p_node->mp_Mem + p_node->m_Size > p && p_node->mp_Mem < (byte*)p + size)
{
DecommitDecommitNode(p_node);
}
p_node = p_next;
}
}
#endif
//------------------------------------------------------------------------
#ifdef VMEM_DECOMMIT_CACHE
bool VirtualMem::TryCommit(void* p_commit, size_t commit_size, int commit_flags)
{
DecommitNode* p_decommit_node = NULL;
// try and find a node that overlaps the commit range
if (!m_DecommitNodeMap.TryRemoveRange(p_commit, commit_size, p_decommit_node))
{
// if we didn't find a node simply allocate from the OS and we are done
return VMem::VirtualCommit(p_commit, commit_size, m_PageSize, commit_flags);
}
VMEM_ASSERT(p_decommit_node->m_CommitFlags == commit_flags, "can't re-commit with different physical flags");
// handle the common case of re-committing exactly the same range
if(p_decommit_node->mp_Mem == p_commit && p_decommit_node->m_Size == commit_size)
{
#ifdef VMEM_ENABLE_MEMSET
CheckMemory(p_commit, commit_size, VMEM_DECOMMITTED_MEM);
#endif
m_DecommitNodeList.Remove(p_decommit_node);
m_DecommitNodePool.Free(p_decommit_node);
m_PendingDecommitBytes -= commit_size;
return true;
}
else
{
// the decommit node is not exactly the same but overlaps, so we must take just the ranges that we need
size_t committed_bytes = 0;
void* p = p_commit;
size_t total_bytes_to_commit = commit_size;
// handle the case where p_commit is part way into the node
if(p_decommit_node->mp_Mem < p)
{
#ifdef VMEM_ENABLE_MEMSET
CheckMemory(p_decommit_node->mp_Mem, p_decommit_node->m_Size, VMEM_DECOMMITTED_MEM);
#endif
// only commit as much of the node as we need
void* p_node_end = (byte*)p_decommit_node->mp_Mem + p_decommit_node->m_Size;
size_t size_to_commit = VMem::VMin((size_t)((byte*)p_node_end - (byte*)p), total_bytes_to_commit);
// reduce the size of the commit node
p_decommit_node->m_Size = (byte*)p - (byte*)p_decommit_node->mp_Mem;
p_decommit_node->m_CommitFlags = commit_flags;
// re-add range to map
DecommitNodeMap::Range range(p_decommit_node->mp_Mem, p, p_decommit_node);
bool add_result = m_DecommitNodeMap.Add(range);
VMEM_ASSERT(add_result, "add shouldn't fail because we've just removed an item");
VMEM_UNREFERENCED_PARAM(add_result);
VMEM_ASSERT(p_decommit_node->m_CommitFlags == commit_flags, "can't re-commit with different physical flags");
p = (byte*)p + size_to_commit;
total_bytes_to_commit -= size_to_commit;
committed_bytes += size_to_commit;
m_PendingDecommitBytes -= size_to_commit;
// if we have some left over, create a new node
if(p < p_node_end)
{
// allocate new node
DecommitNode* p_new_node = m_DecommitNodePool.Alloc();
size_t new_node_size = (byte*)p_node_end - (byte*)p;
if(p_new_node)
{
// setup new node
p_new_node->mp_Mem = p;
p_new_node->m_Size = new_node_size;
p_new_node->m_CommitFlags = commit_flags;
p_new_node->m_FlushFrame = p_decommit_node->m_FlushFrame;
VMEM_ASSERT_CODE(p_new_node->mp_Prev = p_new_node->mp_Next = NULL);
// insert new node into list
m_DecommitNodeList.Insert(p_decommit_node, p_new_node);
// add new range to map
DecommitNodeMap::Range offcut_range(p, (byte*)p + new_node_size, p_new_node);
if(!m_DecommitNodeMap.Add(offcut_range))
{
m_DecommitNodeList.Remove(p_new_node);
m_DecommitNodePool.Free(p_new_node);
if(committed_bytes)
VirtualMem::Decommit(p_commit, committed_bytes, commit_flags);
return false;
}
VMEM_MEMSET(p_new_node->mp_Mem, VMEM_DECOMMITTED_MEM, p_new_node->m_Size);
}
else
{
// OOM so decommit the offcut range instead of adding it to the map
VMem::VirtualDecommit(p, new_node_size, m_PageSize, commit_flags);
}
return true;
}
if(!total_bytes_to_commit)
return true;
// try and get the next range
p_decommit_node = NULL;
m_DecommitNodeMap.TryRemoveRange(p, total_bytes_to_commit, p_decommit_node);
}
// keep committing nodes and the gaps until we have committed enough
while(total_bytes_to_commit && p_decommit_node)
{
#ifdef VMEM_ENABLE_MEMSET
CheckMemory(p_decommit_node->mp_Mem, p_decommit_node->m_Size, VMEM_DECOMMITTED_MEM);
#endif
// if the node starts part way through the block commit the range before the node
void* p_node_start = p_decommit_node->mp_Mem;
if(p < p_node_start)
{
size_t size_to_commit = (byte*)p_node_start - (byte*)p;
VMEM_ASSERT(size_to_commit < total_bytes_to_commit, "m_DecommitNodeMap has been corrupted");
if(!VMem::VirtualCommit(p, size_to_commit, m_PageSize, commit_flags))
{
if(committed_bytes)
VMem::VirtualDecommit(p_commit, committed_bytes, m_PageSize, commit_flags);
bool add_result = m_DecommitNodeMap.Add(DecommitNodeMap::Range(p_decommit_node->mp_Mem, (byte*)p_decommit_node->mp_Mem + p_decommit_node->m_Size, p_decommit_node));
VMEM_ASSERT(add_result, "add should never fail due to oom because we just removed an item");
VMEM_UNREFERENCED_PARAM(add_result);
return false;
}
p = (byte*)p + size_to_commit;
total_bytes_to_commit -= size_to_commit;
committed_bytes += size_to_commit;
}
VMEM_ASSERT(total_bytes_to_commit, "node doesn't overlap?");
VMEM_ASSERT(p_decommit_node->mp_Mem == p, "Decommit node has been corrupted.");
// commit as much of the node as we need
size_t size_to_commit = VMem::VMin(p_decommit_node->m_Size, total_bytes_to_commit);
p_decommit_node->mp_Mem = (byte*)p_decommit_node->mp_Mem + size_to_commit;
p_decommit_node->m_Size = p_decommit_node->m_Size - size_to_commit;
p_decommit_node->m_CommitFlags = commit_flags;
VMEM_ASSERT(p_decommit_node->m_CommitFlags == commit_flags, "can't re-commit with different physical flags");
p = (byte*)p + size_to_commit;
total_bytes_to_commit -= size_to_commit;
committed_bytes += size_to_commit;
m_PendingDecommitBytes -= size_to_commit;
if(p_decommit_node->m_Size)
{
DecommitNodeMap::Range range(p_decommit_node->mp_Mem, (byte*)p_decommit_node->mp_Mem + p_decommit_node->m_Size, p_decommit_node);
bool add_result = m_DecommitNodeMap.Add(range);
VMEM_ASSERT(add_result, "add should never fail due to oom because we just removed an item");
VMEM_UNREFERENCED_PARAM(add_result);
}
else
{
m_DecommitNodeList.Remove(p_decommit_node);
m_DecommitNodePool.Free(p_decommit_node);
}
if(!total_bytes_to_commit)
return true;
// try and get the next range
p_decommit_node = NULL;
m_DecommitNodeMap.TryRemoveRange(p, total_bytes_to_commit, p_decommit_node);
}
if(total_bytes_to_commit)
{
if(!VMem::VirtualCommit(p, total_bytes_to_commit, m_PageSize, commit_flags))
{
VirtualMem::Decommit(p_commit, committed_bytes, commit_flags);
return false;
}
}
return true;
}
}
#endif
//------------------------------------------------------------------------
void VirtualMem::Decommit(void* p, size_t size, int commit_flags)
{
#ifdef VMEM_DECOMMIT_CACHE
if(size > VMEM_DECOMMIT_CACHE_MAX_SIZE)
{
VMem::VirtualDecommit(p, size, m_PageSize, commit_flags);
}
else
{
CriticalSectionScope lock(m_CriticalSection);
VMEM_ASSERT(p != NULL && ((size_t)p & (m_PageSize-1)) == 0, "Invalid address passed to VirtualDecommit");
VMEM_ASSERT(size >= 0 && (size & (m_PageSize-1)) == 0, "Invalid size passed to VirtualDecommit");
VMEM_ASSERT(VMem::Committed(p, size), "Can't decommit range because it is not committed");
VMEM_MEMSET(p, VMEM_DECOMMITTED_MEM, size);
DecommitNode* p_new_node = m_DecommitNodePool.Alloc();
if(!p_new_node)
{
VMem::VirtualDecommit(p, size, m_PageSize, commit_flags); // out of memory so decommit immediately
return;
}
m_PendingDecommitBytes += size;
p_new_node->mp_Mem = p;
p_new_node->m_Size = size;
p_new_node->m_CommitFlags = commit_flags;
p_new_node->mp_Prev = NULL;
p_new_node->mp_Next = NULL;
p_new_node->m_FlushFrame = m_CurrentFrame + VMEM_DECOMMIT_CACHE_RELEASE_FRAME_DELAY;
m_DecommitNodeList.AddHead(p_new_node);
DecommitNodeMap::Range range(p, (byte*)p + size, p_new_node);
if(!m_DecommitNodeMap.Add(range))
{
m_PendingDecommitBytes -= size;
m_DecommitNodeList.Remove(p_new_node);
m_DecommitNodePool.Free(p_new_node);
VMem::VirtualDecommit(p, size, m_PageSize, commit_flags); // out of memory so decommit immediately
return;
}
VMEM_MEMSET(p_new_node->mp_Mem, VMEM_DECOMMITTED_MEM, p_new_node->m_Size);
if(m_PendingDecommitBytes > VMEM_DECOMMIT_CACHE_SIZE)
FlushDecommitCache();
}
#else
VMem::VirtualDecommit(p, size, m_PageSize, commit_flags);
#endif
}
//------------------------------------------------------------------------
void VirtualMem::Flush()
{
CriticalSectionScope lock(m_CriticalSection);
#ifdef VMEM_DECOMMIT_CACHE
FlushMemory(true);
#endif
}
//------------------------------------------------------------------------
void VirtualMem::Update()
{
#ifdef VMEM_DECOMMIT_CACHE
CriticalSectionScope lock(m_CriticalSection);
FlushMemory(false);
++m_CurrentFrame;
#endif
}
//------------------------------------------------------------------------
#ifdef VMEM_DECOMMIT_CACHE
void VirtualMem::FlushDecommitCache(bool force)
{
DecommitNode* p_node = m_DecommitNodeList.GetTail();
DecommitNode* p_node_end = m_DecommitNodeList.GetIterEnd();
while(p_node != p_node_end && (m_PendingDecommitBytes > VMEM_DECOMMIT_CACHE_SIZE || m_CurrentFrame >= p_node->m_FlushFrame || force))
{
DecommitNode* p_prev = p_node->mp_Prev;
DecommitDecommitNode(p_node);
p_node = p_prev;
}
}
#endif
//------------------------------------------------------------------------
#ifdef VMEM_DECOMMIT_CACHE
void VirtualMem::DecommitDecommitNode(DecommitNode* p_node)
{
size_t size = p_node->m_Size;
VMem::VirtualDecommit(p_node->mp_Mem, size, m_PageSize, p_node->m_CommitFlags);
m_PendingDecommitBytes -= size;
DecommitNodeMap::Range range(p_node->mp_Mem, (byte*)p_node->mp_Mem + size, p_node);
m_DecommitNodeMap.Remove(range);
m_DecommitNodeList.Remove(p_node);
m_DecommitNodePool.Free(p_node);
}
#endif
//------------------------------------------------------------------------
#ifdef VMEM_DECOMMIT_CACHE
void VirtualMem::FlushMemory(bool force)
{
// if m_FlushFrame wraps around then all flush frames will be invalid, so simply flush everything
if(!m_CurrentFrame)
force = true;
// must flush the decommit cache first so that we don't release while still committed
FlushDecommitCache(force);
FlushReleaseCache(force);
}
#endif
//------------------------------------------------------------------------
#ifdef VMEM_DECOMMIT_CACHE
void VirtualMem::FlushReleaseCache(bool force)
{
for(int i=0; i<m_ReleaseNodeBucketCount; ++i)
{
List<ReleaseNode>& node_list = m_ReleaseNodeBuckets[i];
ReleaseNode* p_node = node_list.GetTail();
ReleaseNode* p_node_end = node_list.GetIterEnd();
while(p_node != p_node_end && (m_CurrentFrame >= p_node->m_FlushFrame || force))
{
ReleaseNode* p_prev = p_node->mp_Prev;
size_t size = p_node->m_Size;
size_t aligned_size = p_node->m_AlignedSize;
VMem::VirtualRelease(p_node->mp_Mem, aligned_size);
m_PendingReleaseBytes -= size;
VMEM_STATS(m_ReservedOverhead -= aligned_size - size);
node_list.Remove(p_node);
m_ReleaseNodePool.Free(p_node);
p_node = p_prev;
}
}
}
#endif
//------------------------------------------------------------------------
#ifdef VMEM_ENABLE_STATS
Stats VirtualMem::GetStats()
{
CriticalSectionScope lock(m_CriticalSection);
return GetStatsNoLock();
}
#endif
//------------------------------------------------------------------------
#ifdef VMEM_ENABLE_STATS
Stats VirtualMem::GetStatsNoLock() const
{
size_t allocs_overhead = m_Reservations.GetAllocedMemory();
Stats stats;
stats.m_Reserved = m_ReservedOverhead + allocs_overhead;
stats.m_Overhead = allocs_overhead;
#ifdef VMEM_DECOMMIT_CACHE
stats.m_Unused = m_PendingDecommitBytes;
stats.m_Reserved += m_PendingReleaseBytes;
stats += m_DecommitNodeMap.GetStats();
stats += m_ReleaseNodePool.GetStats();
stats += m_DecommitNodePool.GetStats();
#endif
return stats;
}
#endif
//------------------------------------------------------------------------
void VirtualMem::Lock() const
{
m_CriticalSection.Enter();
}
//------------------------------------------------------------------------
void VirtualMem::Release() const
{
m_CriticalSection.Leave();
}
//------------------------------------------------------------------------
void VirtualMem::CheckIntegrity()
{
{
CriticalSectionScope lock(m_CriticalSection);
#if defined(VMEM_ASSERTS) && defined(VMEM_DECOMMIT_CACHE) && defined(VMEM_ENABLE_MEMSET)
DecommitNode* p_node = m_DecommitNodeList.GetHead();
DecommitNode* p_end_node = m_DecommitNodeList.GetIterEnd();
while (p_node != p_end_node)
{
CheckMemory(p_node->mp_Mem, p_node->m_Size, VMEM_DECOMMITTED_MEM);
p_node = p_node->mp_Next;
}
#endif
}
VMemSysCheckIntegrity();
}
}
//------------------------------------------------------------------------
#endif // #ifdef VMEM_ENABLE
| 32.445765
| 171
| 0.647005
|
BoneCrasher
|
1b4128c4a3b7ce9d758c5f003dbbf83aa7226269
| 6,890
|
cpp
|
C++
|
tests/bitmex_gateway.cpp
|
yyun/gamma-ray
|
f06971caac75c1669981b3ebb7166413ab0921fc
|
[
"ISC"
] | 150
|
2020-12-28T23:56:42.000Z
|
2022-03-21T13:22:40.000Z
|
tests/bitmex_gateway.cpp
|
yyun/gamma-ray
|
f06971caac75c1669981b3ebb7166413ab0921fc
|
[
"ISC"
] | 6
|
2020-12-29T13:08:10.000Z
|
2022-02-06T20:25:25.000Z
|
tests/bitmex_gateway.cpp
|
yyun/gamma-ray
|
f06971caac75c1669981b3ebb7166413ab0921fc
|
[
"ISC"
] | 49
|
2020-12-29T11:49:34.000Z
|
2022-03-22T08:35:54.000Z
|
#include <iostream>
#include <unistd.h>
#include <future>
#include "doctest.h"
#include "json.hpp"
#include "bitmexws.h"
#include "bitmex_gateway.h"
#include "bitmexhttp.h"
#include "models.h"
#include "delta_parser.h"
#include "Poco/Delegate.h"
#include "Poco/DateTime.h"
#define LOG(x) (std::cout << x << std::endl)
using namespace std;
using json = nlohmann::json;
class MarketDataListener
{
private:
BitmexMarketDataGateway &md;
BitmexWebsocket &ws;
BitmexSymbolProvider &symbol;
void on_market_quote(const void *, Models::MarketQuote "e)
{
// LOG(quote.symbol);
CHECK(quote.symbol == symbol.symbol);
ws.close();
}
public:
MarketDataListener(BitmexMarketDataGateway &md, BitmexWebsocket &ws, BitmexSymbolProvider &symbol)
: md(md), ws(ws), symbol(symbol)
{
md.market_quote += Poco::delegate(this, &MarketDataListener::on_market_quote);
}
~MarketDataListener()
{
md.market_quote -= Poco::delegate(this, &MarketDataListener::on_market_quote);
}
};
class OrderEntryListener
{
private:
BitmexOrderEntryGateway &oe;
BitmexWebsocket &ws;
void on_trade(const void *, Models::Trade &trade)
{
CHECK(trade.size == 25);
this->ws.close();
}
public:
OrderEntryListener(BitmexOrderEntryGateway &oe, BitmexWebsocket &ws)
: oe(oe), ws(ws)
{
oe.trade += Poco::delegate(this, &OrderEntryListener::on_trade);
}
~OrderEntryListener()
{
oe.trade -= Poco::delegate(this, &OrderEntryListener::on_trade);
}
};
TEST_CASE("Bitmex market data gateway")
{
string uri = "wss://testnet.bitmex.com/realtime";
string api_key = "iCDc_MrgK2bfZOaRKhz5K99A";
string api_secret = "VJN9dBwrBInY2dY-SMVzDkb1suv9DQRwxmYKiEh7TcJVTg0w";
BitmexWebsocket ws_client(uri, api_key, api_secret);
BitmexSymbolProvider symbol;
BitmexMarketDataGateway md(ws_client, symbol);
MarketDataListener MDL(md, ws_client, symbol);
ws_client.connect();
}
TEST_CASE("Bitmex order entry gateway")
{
string ws_uri = "wss://testnet.bitmex.com/realtime";
string http_uri = "https://testnet.bitmex.com";
string api_key = "iCDc_MrgK2bfZOaRKhz5K99A";
string api_secret = "VJN9dBwrBInY2dY-SMVzDkb1suv9DQRwxmYKiEh7TcJVTg0w";
BitmexWebsocket ws_cli(ws_uri, api_key, api_secret);
BitmexHttp http_cli(http_uri, api_key, api_secret);
BitmexSymbolProvider symbol;
BitmexStore store;
BitmexDeltaParser parser;
BitmexOrderEntryGateway oe(http_cli, ws_cli, parser, store, symbol);
OrderEntryListener OEL(oe, ws_cli);
auto handle = std::async(std::launch::async, [&ws_cli]() {
ws_cli.connect();
});
// get middle price
std::string path = "/api/v1/orderBook/L2?symbol=XBT";
std::string verb = "GET";
double mid = 0;
http_cli.call(path, verb)
.then([&mid](json res) {
mid = (res[24]["price"].get<double>() + res[25]["price"].get<double>()) / 2;
})
.wait();
// cancel all open orders
unsigned int opens = oe.cancel_all();
std::cout << "Bitmex order entry gateway canceled " << opens << " existing orders " << std::endl;
std::string clOrdID1 = "order1";
std::string clOrdID2 = "order2";
Models::NewOrder order1(symbol.symbol, clOrdID1, mid + 100.25, 25.0, Models::Side::Ask, Models::OrderType::Limit, Models::TimeInForce::GTC, Poco::DateTime(), true);
Models::NewOrder order2(symbol.symbol, clOrdID2, mid - 100.25, 25.0, Models::Side::Bid, Models::OrderType::Limit, Models::TimeInForce::GTC, Poco::DateTime(), true);
std::vector<Models::NewOrder> orders = {order1, order2};
Models::ReplaceOrder replace1(clOrdID1, mid + 50.25, 26.0, Poco::DateTime());
Models::ReplaceOrder replace2(clOrdID2, mid - 50.25, 27.0, Poco::DateTime());
std::vector<Models::ReplaceOrder> replaces = {replace1, replace2};
Models::CancelOrder cancel1(clOrdID1, Poco::DateTime());
Models::CancelOrder cancel2(clOrdID2, Poco::DateTime());
std::vector<Models::CancelOrder> cancels = {cancel1, cancel2};
// test send orders
oe.batch_send_order(orders);
sleep(3);
CHECK(store.data["order"]["XBTUSD"].size() == 2);
// test replace orders
oe.batch_replace_order(replaces);
sleep(3);
CHECK(store.data["order"]["XBTUSD"][0]["price"].get<double>() == mid + 50.25);
CHECK(store.data["order"]["XBTUSD"][0]["orderQty"].get<double>() == 26);
CHECK(store.data["order"]["XBTUSD"][1]["price"].get<double>() == mid - 50.25);
CHECK(store.data["order"]["XBTUSD"][1]["orderQty"].get<double>() == 27);
// test cancel orders
oe.batch_cancel_order(cancels);
sleep(3);
CHECK(store.data["order"]["XBTUSD"].size() == 2);
// test trade
std::string clOrdID3 = "order3";
// Models::NewOrder order3(symbol.symbol, clOrdID3, mid - 200.25, 25.0, Models::Side::Ask, Models::OrderType::Limit, Models::TimeInForce::GTC, Poco::DateTime(), false);
Models::NewOrder order3(symbol.symbol, clOrdID3, mid + 200.25, 25.0, Models::Side::Bid, Models::OrderType::Limit, Models::TimeInForce::GTC, Poco::DateTime(), false);
std::vector<Models::NewOrder> orders2 = {order3};
oe.batch_send_order(orders2);
handle.get();
}
TEST_CASE("Bitmex position gateway")
{
string ws_uri = "wss://testnet.bitmex.com/realtime";
string http_uri = "https://testnet.bitmex.com";
string api_key = "iCDc_MrgK2bfZOaRKhz5K99A";
string api_secret = "VJN9dBwrBInY2dY-SMVzDkb1suv9DQRwxmYKiEh7TcJVTg0w";
BitmexWebsocket ws_cli(ws_uri, api_key, api_secret);
BitmexHttp http_cli(http_uri, api_key, api_secret);
BitmexSymbolProvider symbol;
BitmexStore store;
BitmexDeltaParser parser;
BitmexOrderEntryGateway oe(http_cli, ws_cli, parser, store, symbol);
BitmexPositionGateway pg(ws_cli, parser, store, symbol);
auto handle = std::async(std::launch::async, [&ws_cli]() {
ws_cli.connect();
});
bool haveValues = false;
while (!haveValues)
{
auto pos = pg.get_latest_position();
auto margin = pg.get_latest_margin();
if (pos && margin)
haveValues = true;
else
sleep(1);
}
auto pos = pg.get_latest_position();
auto margin = pg.get_latest_margin();
CHECK(pos.value().contains("currentQty"));
CHECK(margin.value().contains("amount"));
ws_cli.close();
}
TEST_CASE("bitmex rate limit monitor")
{
string http_uri = "https://testnet.bitmex.com";
string api_key = "iCDc_MrgK2bfZOaRKhz5K99A";
string api_secret = "VJN9dBwrBInY2dY-SMVzDkb1suv9DQRwxmYKiEh7TcJVTg0w";
BitmexRateLimit monitor;
BitmexHttp http_cli(http_uri, api_key, api_secret, monitor);
const std::string path = "/api/v1/stats";
const std::string verb = "GET";
int remain;
http_cli.call(path, verb)
.then([](json) {
})
.wait();
remain = monitor.remain;
http_cli.call(path, verb)
.then([](json) {
})
.wait();
CHECK((remain - monitor.remain) == 1);
CHECK(monitor.is_rate_limited() == false);
monitor.update_rate_limit(60, 11, Poco::DateTime());
CHECK(monitor.is_rate_limited() == true);
}
| 30.087336
| 170
| 0.691872
|
yyun
|
1b41c304cb57fb3bfd5c7d9eed84dad47a720908
| 6,630
|
cpp
|
C++
|
ql/pricingengines/vanilla/fdcirvanillaengine.cpp
|
jiangjiali/QuantLib
|
37c98eccfa18a95acb1e98b276831641be92b38e
|
[
"BSD-3-Clause"
] | 3,358
|
2015-12-18T02:56:17.000Z
|
2022-03-31T02:42:47.000Z
|
ql/pricingengines/vanilla/fdcirvanillaengine.cpp
|
jiangjiali/QuantLib
|
37c98eccfa18a95acb1e98b276831641be92b38e
|
[
"BSD-3-Clause"
] | 965
|
2015-12-21T10:35:28.000Z
|
2022-03-30T02:47:00.000Z
|
ql/pricingengines/vanilla/fdcirvanillaengine.cpp
|
jiangjiali/QuantLib
|
37c98eccfa18a95acb1e98b276831641be92b38e
|
[
"BSD-3-Clause"
] | 1,663
|
2015-12-17T17:45:38.000Z
|
2022-03-31T07:58:29.000Z
|
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2020 Lew Wei Hao
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy of the license along with this program; if not, please email
<quantlib-dev@lists.sf.net>. The license is also available online at
<http://quantlib.org/license.shtml>.
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 license for more details.
*/
#include <ql/methods/finitedifferences/meshers/fdmblackscholesmesher.hpp>
#include <ql/methods/finitedifferences/meshers/fdmmeshercomposite.hpp>
#include <ql/methods/finitedifferences/meshers/fdmsimpleprocess1dmesher.hpp>
#include <ql/methods/finitedifferences/operators/fdmlinearoplayout.hpp>
#include <ql/methods/finitedifferences/solvers/fdmcirsolver.hpp>
#include <ql/methods/finitedifferences/stepconditions/fdmstepconditioncomposite.hpp>
#include <ql/methods/finitedifferences/utilities/fdminnervaluecalculator.hpp>
#include <ql/pricingengines/vanilla/fdcirvanillaengine.hpp>
#include <ql/processes/blackscholesprocess.hpp>
#include <ql/processes/coxingersollrossprocess.hpp>
#include <utility>
namespace QuantLib {
FdCIRVanillaEngine::FdCIRVanillaEngine(
ext::shared_ptr<CoxIngersollRossProcess> cirProcess,
ext::shared_ptr<GeneralizedBlackScholesProcess> bsProcess,
Size tGrid,
Size xGrid,
Size rGrid,
Size dampingSteps,
const Real rho,
const FdmSchemeDesc& schemeDesc,
ext::shared_ptr<FdmQuantoHelper> quantoHelper)
: tGrid_(tGrid), xGrid_(xGrid), rGrid_(rGrid), dampingSteps_(dampingSteps), rho_(rho),
schemeDesc_(schemeDesc), bsProcess_(std::move(bsProcess)), cirProcess_(std::move(cirProcess)),
quantoHelper_(std::move(quantoHelper)) {}
FdmSolverDesc FdCIRVanillaEngine::getSolverDesc(Real) const {
const ext::shared_ptr<StrikedTypePayoff> payoff =
ext::dynamic_pointer_cast<StrikedTypePayoff>(arguments_.payoff);
const Time maturity = bsProcess_->time(arguments_.exercise->lastDate());
// The short rate mesher
const ext::shared_ptr<Fdm1dMesher> shortRateMesher(
new FdmSimpleProcess1dMesher(rGrid_, cirProcess_, maturity, tGrid_));
// The equity mesher
const ext::shared_ptr<Fdm1dMesher> equityMesher(
new FdmBlackScholesMesher(
xGrid_, bsProcess_, maturity, payoff->strike(),
Null<Real>(), Null<Real>(), 0.0001, 1.5,
std::pair<Real, Real>(payoff->strike(), 0.1),
arguments_.cashFlow, quantoHelper_,
0.0));
const ext::shared_ptr<FdmMesher> mesher(
new FdmMesherComposite(equityMesher, shortRateMesher));
// Calculator
const ext::shared_ptr<FdmInnerValueCalculator> calculator(
new FdmLogInnerValue(arguments_.payoff, mesher, 0));
// Step conditions
const ext::shared_ptr<FdmStepConditionComposite> conditions =
FdmStepConditionComposite::vanillaComposite(
arguments_.cashFlow, arguments_.exercise,
mesher, calculator,
bsProcess_->riskFreeRate()->referenceDate(),
bsProcess_->riskFreeRate()->dayCounter());
// Boundary conditions
const FdmBoundaryConditionSet boundaries;
// Solver
FdmSolverDesc solverDesc = { mesher, boundaries, conditions,
calculator, maturity,
tGrid_, dampingSteps_ };
return solverDesc;
}
void FdCIRVanillaEngine::calculate() const {
const ext::shared_ptr<StrikedTypePayoff> payoff =
ext::dynamic_pointer_cast<StrikedTypePayoff>(arguments_.payoff);
ext::shared_ptr<FdmCIRSolver> solver(new FdmCIRSolver(
Handle<CoxIngersollRossProcess>(cirProcess_),
Handle<GeneralizedBlackScholesProcess>(bsProcess_),
getSolverDesc(1.5), schemeDesc_,
rho_, payoff->strike()));
const Real r0 = cirProcess_->x0();
const Real spot = bsProcess_->x0();
results_.value = solver->valueAt(spot, r0);
results_.delta = solver->deltaAt(spot, r0);
results_.gamma = solver->gammaAt(spot, r0);
results_.theta = solver->thetaAt(spot, r0);
}
MakeFdCIRVanillaEngine::MakeFdCIRVanillaEngine(
ext::shared_ptr<CoxIngersollRossProcess> cirProcess,
ext::shared_ptr<GeneralizedBlackScholesProcess> bsProcess,
const Real rho)
: cirProcess_(std::move(cirProcess)), bsProcess_(std::move(bsProcess)), rho_(rho), tGrid_(10),
xGrid_(100), rGrid_(100), dampingSteps_(0),
schemeDesc_(ext::make_shared<FdmSchemeDesc>(FdmSchemeDesc::ModifiedHundsdorfer())),
quantoHelper_(ext::shared_ptr<FdmQuantoHelper>()) {}
MakeFdCIRVanillaEngine& MakeFdCIRVanillaEngine::withQuantoHelper(
const ext::shared_ptr<FdmQuantoHelper>& quantoHelper) {
quantoHelper_ = quantoHelper;
return *this;
}
MakeFdCIRVanillaEngine&
MakeFdCIRVanillaEngine::withTGrid(Size tGrid) {
tGrid_ = tGrid;
return *this;
}
MakeFdCIRVanillaEngine&
MakeFdCIRVanillaEngine::withXGrid(Size xGrid) {
xGrid_ = xGrid;
return *this;
}
MakeFdCIRVanillaEngine&
MakeFdCIRVanillaEngine::withRGrid(Size rGrid) {
rGrid_ = rGrid;
return *this;
}
MakeFdCIRVanillaEngine&
MakeFdCIRVanillaEngine::withDampingSteps(Size dampingSteps) {
dampingSteps_ = dampingSteps;
return *this;
}
MakeFdCIRVanillaEngine&
MakeFdCIRVanillaEngine::withFdmSchemeDesc(
const FdmSchemeDesc& schemeDesc) {
schemeDesc_ = ext::make_shared<FdmSchemeDesc>(schemeDesc);
return *this;
}
MakeFdCIRVanillaEngine::operator
ext::shared_ptr<PricingEngine>() const {
return ext::make_shared<FdCIRVanillaEngine>(
cirProcess_,
bsProcess_,
tGrid_, xGrid_, rGrid_, dampingSteps_,
rho_,
*schemeDesc_,
quantoHelper_);
}
}
| 39.230769
| 100
| 0.667421
|
jiangjiali
|
1b48dde8d82f4b5b3cbfbb8c6499b8da7a5b5d11
| 7,545
|
cc
|
C++
|
src/fileio.cc
|
etola/kortex
|
172877fde712dce2e5ecf9bc9b5ec3b86d8e085f
|
[
"MIT"
] | null | null | null |
src/fileio.cc
|
etola/kortex
|
172877fde712dce2e5ecf9bc9b5ec3b86d8e085f
|
[
"MIT"
] | null | null | null |
src/fileio.cc
|
etola/kortex
|
172877fde712dce2e5ecf9bc9b5ec3b86d8e085f
|
[
"MIT"
] | 4
|
2016-11-29T12:50:25.000Z
|
2017-09-13T21:29:01.000Z
|
// ---------------------------------------------------------------------------
//
// This file is part of the <kortex> library suite
//
// Copyright (C) 2013 Engin Tola
//
// See LICENSE file for license information.
//
// author: Engin Tola
// e-mail: engintola@gmail.com
// web : http://www.engintola.com
//
// ---------------------------------------------------------------------------
#include <kortex/fileio.h>
#include <kortex/string.h>
#include <kortex/check.h>
#include <kortex/mem_unit.h>
#include <kortex/types.h>
#include <kortex/defs.h>
#include <sys/types.h>
#include <sys/stat.h>
#ifdef _MSC_VER
#include <Windows.h> // mkdir
#endif
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <string.h>
#ifdef __GNUC__
#include <experimental/filesystem>
#endif
#include <experimental/filesystem>
namespace fs = std::experimental::filesystem;
using namespace std;
namespace kortex {
void get_files(const string& input_folder, vector<string>& ifiles, const char* file_extension ) {
for( const auto & entry : fs::directory_iterator(input_folder) ) {
string fpath = entry.path();
if( file_extension != nullptr ) {
string fext = get_file_extension(fpath);
if( compare_string_nc(fext.c_str(), file_extension ) )
continue;
}
ifiles.push_back(fpath);
}
}
inline bool string_comparison_s(const string& l, const string& r ) {
return bool(strcmp(l.c_str(),r.c_str()) < 0);
}
void sort_strings_by_name(std::vector<string>& strs) {
if( strs.size() <= 1 ) return;
std::sort(strs.begin(), strs.end(), string_comparison_s);
}
FileFormat get_file_format( const string& str ) {
string fext = get_file_extension( str );
std::transform( fext.begin(), fext.end(), fext.begin(), ::tolower );
if ( !fext.compare("pgm" ) ) return FF_PGM;
else if( !fext.compare("ppm" ) ) return FF_PPM;
else if( !fext.compare("jpg" ) ) return FF_JPG;
else if( !fext.compare("png" ) ) return FF_PNG;
else if( !fext.compare("ibin" ) ) return FF_IBIN;
else if( !fext.compare("txt" ) ) return FF_TXT;
else if( !fext.compare("calibration" ) ) return FF_CALIBRATION;
else return FF_NONE;
}
int create_folder( const string& path ) {
#ifdef __GNUC__
mode_t perm=0777;
return mkdir( path.c_str(), perm );
#elif defined _MSC_VER
return CreateDirectory( path.c_str(), NULL );
#else
logman_fatal_g( "folder creation not supported in this OS [%s]", path.c_str() );
#endif
}
bool remove_folder( const string& dir_path ) {
#ifdef __GNUC__
std::experimental::filesystem::remove_all(dir_path);
return true;
#else
return false;
#endif
}
bool is_directory( const string& path_string ) {
return fs::is_directory( path_string );
}
void check_file_stream_error( const ifstream& fin, const char* msg ) {
if( !fin.fail() ) return;
if( msg == NULL ) logman_fatal ("error while reading file stream");
else logman_fatal_g("error while reading file stream [%s]", msg );
}
void check_file_stream_error(const ofstream& fout, const char* msg) {
if( !fout.fail() ) return;
if( msg == NULL ) logman_fatal ("error while writing file stream");
else logman_fatal_g("error while writing file stream [%s]", msg);
}
void reset_file_contents(const char* file_name) {
passert_pointer( file_name );
FILE* fp = fopen(file_name,"w");
if( fp ) fclose(fp);
}
bool delete_file(const string& path) {
// logman_log_g("deleting file [%s]", path.c_str());
if( remove( path.c_str() ) == 0 ) return true;
else return false;
}
void open_or_fail( const string& file, ifstream &fin, bool binary ) {
if( binary ) fin.open( file.c_str(), ios::binary );
else fin.open( file.c_str() );
check_file_stream_error(fin, ("cannot open file: "+file).c_str());
}
void open_or_fail( const string& file, ofstream &fout, bool binary ) {
if( binary ) fout.open( file.c_str(), ios::binary );
else fout.open( file.c_str() );
check_file_stream_error(fout, ("cannot open file: "+file).c_str());
}
void file_exists_or_fail(const string& file) {
if( !file_exists( file ) )
logman_fatal_g("file does not exist [%s]", file.c_str());
}
bool file_exists(const string& file) {
return file_exists(file.c_str());
}
bool file_exists(const char* file) {
FILE *fp = fopen(file,"r");
if( fp == NULL ) {
return false;
} else {
fclose(fp);
return true;
}
}
bool file_create( const string& file ) {
FILE *fp = fopen(file.c_str(),"w");
if( fp == NULL ) {
logman_fatal_g("could not create file [%s]", file.c_str());
} else {
fclose(fp);
return true;
}
}
bool folder_exists(const char* folder) {
struct stat info;
if( stat(folder, &info) != 0 )
return false;
else if( info.st_mode & S_IFDIR ) // S_ISDIR() doesn't exist on my windows
return true;
return false;
}
void read_string(ifstream& fin, string& param, const char* check_against) {
char buffer[1024];
fin.getline( buffer, 1024 );
param = buffer;
check_file_stream_error(fin);
if( check_against == NULL ) return;
if( !is_exact_match( param.c_str(), check_against ) )
logman_fatal_g("read param error. read[%s], expecting[%s]", param.c_str(), check_against);
}
//
// binary
//
void check_binary_stream_begin_tag(ifstream& fin) {
int safety_num;
fin.read( (char*)&safety_num, sizeof(safety_num) );
if( safety_num != AC_SAFETY_BEGIN_NUM || fin.fail() )
logman_fatal("stream corrupted");
check_file_stream_error(fin);
}
void check_binary_stream_end_tag(ifstream& fin) {
int safety_num;
fin.read( (char*)&safety_num, sizeof(safety_num) );
if( safety_num != AC_SAFETY_END_NUM || fin.fail() )
logman_fatal("stream corrupted");
check_file_stream_error(fin);
}
void insert_binary_stream_begin_tag(ofstream& fout) {
int safety_num = AC_SAFETY_BEGIN_NUM;
fout.write( (const char*)&safety_num, sizeof(safety_num) );
check_file_stream_error(fout);
}
void insert_binary_stream_end_tag(ofstream& fout) {
int safety_num = AC_SAFETY_END_NUM;
fout.write( (char*)&safety_num, sizeof(safety_num) );
check_file_stream_error(fout);
}
//
//
void save_ascii(const string& file, const vector<bool>& array) {
ofstream fout;
open_or_fail(file, fout, false);
write_array( fout, NULL, array );
fout.close();
}
void load_ascii(const string& file, vector<bool>& array) {
array.clear();
ifstream fin;
open_or_fail(file, fin, false);
int narr;
read_param( fin, NULL, narr );
array.resize(narr);
for( int i=0; i<narr; i++ ) {
bool b;
fin >> b;
array[i] = b;
}
fin.close();
}
}
| 30.795918
| 102
| 0.57389
|
etola
|
1b4d16251d7ea36601b902479d56e44a7edabc23
| 714
|
hh
|
C++
|
include/rootStorageManagerMessenger.hh
|
jvavrek/NIMB2018
|
0aaf4143db2194b9f95002c681e4f860c8c76f7a
|
[
"MIT"
] | 4
|
2020-06-28T02:18:53.000Z
|
2022-01-17T07:54:31.000Z
|
include/rootStorageManagerMessenger.hh
|
jvavrek/NIMB2018
|
0aaf4143db2194b9f95002c681e4f860c8c76f7a
|
[
"MIT"
] | 3
|
2018-08-16T18:49:53.000Z
|
2020-10-19T18:04:25.000Z
|
include/rootStorageManagerMessenger.hh
|
jvavrek/NIMB2018
|
0aaf4143db2194b9f95002c681e4f860c8c76f7a
|
[
"MIT"
] | null | null | null |
#ifndef rootStorageMessenger_hh
#define rootStorageMessenger_hh 1
#include "G4UImessenger.hh"
class rootStorageManager;
class G4UIdirectory;
class G4UIcmdWithAString;
class G4UIcmdWithoutParameter;
class G4UIcmdWithADoubleAndUnit;
class G4UIcmdWithAnInteger;
class G4UIcmdWithABool;
class rootStorageManagerMessenger : public G4UImessenger {
public:
rootStorageManagerMessenger(rootStorageManager *);
~rootStorageManagerMessenger();
void SetNewValue(G4UIcommand *, G4String);
private:
rootStorageManager *theRSManager;
G4UIdirectory *ZKDirectory, *rootDirectory;
G4UIcmdWithAString *rootFileNameCmd;
G4UIcmdWithoutParameter *rootInitCmd;
G4UIcmdWithoutParameter *rootWriteCmd;
};
#endif
| 21.636364
| 58
| 0.830532
|
jvavrek
|
1b4dad6417fbbcde9c859d79e779a4f3daffd404
| 8,771
|
cpp
|
C++
|
test/Matuna.OCLConvNetBackMaxPoolingTest/OCLConvNetBackMaxPoolingTest.cpp
|
mihed/ATML
|
242fb951eea7a55846b8a18dd6abcabb26e2a1cc
|
[
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null |
test/Matuna.OCLConvNetBackMaxPoolingTest/OCLConvNetBackMaxPoolingTest.cpp
|
mihed/ATML
|
242fb951eea7a55846b8a18dd6abcabb26e2a1cc
|
[
"BSL-1.0",
"BSD-3-Clause"
] | 3
|
2015-06-08T19:51:53.000Z
|
2015-07-01T10:15:06.000Z
|
test/Matuna.OCLConvNetBackMaxPoolingTest/OCLConvNetBackMaxPoolingTest.cpp
|
mihed/ATML
|
242fb951eea7a55846b8a18dd6abcabb26e2a1cc
|
[
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null |
/*
* OCLConvNetBackMaxPoolingTest.cpp
*
* Created on: Jun 23, 2015
* Author: Mikael
*/
#define CATCH_CONFIG_MAIN
#include "catch/catch.hpp"
#include "Matuna.OCLHelper/OCLHelper.h"
#include "Matuna.OCLConvNet/OCLConvNet.h"
#include "Matuna.OCLConvNet/ConvolutionLayer.h"
#include "Matuna.ConvNet/ConvolutionLayerConfig.h"
#include "Matuna.ConvNet/StandardOutputLayerConfig.h"
#include "Matuna.ConvNet/MaxPoolingLayerConfig.h"
#include "Matuna.OCLConvNet/MaxPoolingLayer.h"
#include "Matuna.Math/Matrix.h"
#include <memory>
#include <cmath>
#include <random>
#include <tuple>
#include <type_traits>
using namespace Matuna::MachineLearning;
using namespace Matuna::Helper;
using namespace Matuna::Math;
unique_ptr<ConvNetConfig> CreateRandomConvNetMaxPoolingConfig(mt19937& mt,
uniform_int_distribution<int>& layerGenerator,
uniform_int_distribution<int>& dimensionGenerator,
uniform_int_distribution<int>& unitGenerator,
uniform_int_distribution<int>& samplingSizeGenerator,
bool useDivisableLayers)
{
cout << "\n\n-------------------Network-------------------" << endl;
int layerCount = layerGenerator(mt);
INFO("Creating the layers config");
int requiredWidthMultiple = 1;
int requiredHeightMultiple = 1;
vector<MaxPoolingLayerConfig*> maxConfigs;
for (int i = 0; i < layerCount; i++)
{
cout << "----------Layer " << i << "----------------" << endl;
int widthSamplingSize = samplingSizeGenerator(mt);
requiredWidthMultiple *= widthSamplingSize;
int heightSamplingSize = samplingSizeGenerator(mt);
requiredHeightMultiple *= heightSamplingSize;
maxConfigs.push_back(new MaxPoolingLayerConfig(widthSamplingSize, heightSamplingSize));
cout << "Width Sampling: " << widthSamplingSize << " Height Sampling: " << heightSamplingSize << endl;
}
//Let us now find the dimension that is closest to the multiples
int width = dimensionGenerator(mt);
int height = dimensionGenerator(mt);
int units = unitGenerator(mt);
if (useDivisableLayers)
{
width = static_cast<int>(ceil(double(width) / requiredWidthMultiple) * requiredWidthMultiple);
height = static_cast<int>(ceil(double(height) / requiredHeightMultiple) * requiredHeightMultiple);
CHECK((width % requiredWidthMultiple) == 0);
CHECK((height % requiredHeightMultiple) == 0);
}
vector<LayerDataDescription> dataDescriptions;
LayerDataDescription dataDescription;
dataDescription.Width = width;
dataDescription.Height = height;
dataDescription.Units = units;
cout << endl << "Width: " << width << " Height: " << height << " Units: " << units << endl << endl;
dataDescriptions.push_back(dataDescription);
unique_ptr<ConvNetConfig> config(new ConvNetConfig(dataDescriptions));
for(auto maxConfig : maxConfigs)
config->AddToBack(unique_ptr<ForwardBackPropLayerConfig>(maxConfig));
unique_ptr<StandardOutputLayerConfig> outputConfig(new StandardOutputLayerConfig());
config->SetOutputConfig(move(outputConfig));
return move(config);
}
SCENARIO("Creating a max sampling network")
{
auto platformInfos = OCLHelper::GetPlatformInfos();
random_device device;
mt19937 mt(device());
uniform_int_distribution<int> dimensionGenerator(1, 1000);
uniform_int_distribution<int> samplingSizeGenerator(1, 5);
uniform_int_distribution<int> unitGenerator(1, 15);
uniform_int_distribution<int> layerGenerator(1, 5);
for (int dummy = 0; dummy < 50; dummy++)
{
vector<vector<OCLDeviceInfo>> deviceInfos;
for (auto platformInfo : platformInfos)
deviceInfos.push_back(OCLHelper::GetDeviceInfos(platformInfo));
for (auto& deviceInfo : deviceInfos)
{
unique_ptr<ConvNetConfig> config;
if (dummy > 24)
config = CreateRandomConvNetMaxPoolingConfig(mt, layerGenerator, dimensionGenerator, unitGenerator, samplingSizeGenerator, true);
else
config = CreateRandomConvNetMaxPoolingConfig(mt, layerGenerator, dimensionGenerator, unitGenerator, samplingSizeGenerator, false);
OCLConvNet<float> network(deviceInfo, move(config));
auto layers = network.GetLayers();
size_t layersCount= layers.size();
vector<tuple<int, int>> samplingSizes;
for (auto layer : layers)
{
auto config = dynamic_cast<MaxPoolingLayer<float>*>(layer)->GetConfig();
samplingSizes.push_back(make_tuple(config.SamplingSizeWidth(), config.SamplingSizeHeight()));
}
LayerDataDescription inForwardDesc = network.InputForwardDataDescriptions()[0];
LayerDataDescription outForwardDesc = network.OutputForwardDataDescriptions()[0];
printf("Out width: %i, Out height: %i, Out units: %i \n", outForwardDesc.Width, outForwardDesc.Height, outForwardDesc.Units);
vector<Matrixf> inputMatrices;
for (int i = 0; i < inForwardDesc.Units; i++)
inputMatrices.push_back(Matrixf::RandomNormal(inForwardDesc.Height, inForwardDesc.Width));
unique_ptr<float[]> contiguousMemory(new float[inForwardDesc.TotalUnits()]);
for (int i = 0; i < inForwardDesc.Units; i++)
memcpy(contiguousMemory.get() + i * inForwardDesc.Width * inForwardDesc.Height, inputMatrices[i].Data, inForwardDesc.Width * inForwardDesc.Height * sizeof(float));
INFO("Feed forwarding the max network");
auto networkResult = network.FeedForwardUnaligned(contiguousMemory.get(), 0);
INFO("Calculating the manual network");
vector<tuple<int, int>> heightWidths;
vector<vector<vector<tuple<int, int>>>> downSampleIndices;
for (size_t i = 0; i < layersCount; i++)
{
auto& samplingSize = samplingSizes[i];
vector<Matrixf> resultMatrices;
vector<vector<tuple<int, int>>> downSampleIndicesForLayer;
for (size_t j = 0; j < inputMatrices.size(); j++)
{
vector<tuple<int, int>> indicesForUnit;
resultMatrices.push_back(inputMatrices[j].MaxDownSample(get<0>(samplingSize), get<1>(samplingSize), indicesForUnit));
//if (i == 1)
// for (auto tempTest : indicesForUnit)
// printf("(%i, %i) \n", get<0>(tempTest), get<1>(tempTest));
downSampleIndicesForLayer.push_back(indicesForUnit);
}
downSampleIndices.push_back(downSampleIndicesForLayer);
auto tempMatrix = resultMatrices[0];
heightWidths.push_back(make_tuple(tempMatrix.RowCount(), tempMatrix.ColumnCount()));
inputMatrices = resultMatrices;
}
for(size_t i = 0; i < inputMatrices.size(); i++)
{
auto inputMatrix = inputMatrices[i];
Matrixf networkMatrix(inputMatrix.RowCount(), inputMatrix.ColumnCount(), networkResult.get() + i * inputMatrix.RowCount() * inputMatrix.ColumnCount());
auto difference = (inputMatrix - networkMatrix).Norm2Square();
cout << "difference: " << difference << endl;
CHECK(difference < 1E-13f);
}
INFO("Creating some random targets");
vector<Matrixf> targets;
for (int i = 0; i < outForwardDesc.Units; i++)
targets.push_back(Matrixf::RandomNormal(outForwardDesc.Height, outForwardDesc.Width));
unique_ptr<float[]> contiguousOutMemory(new float[outForwardDesc.TotalUnits()]);
for (int i = 0; i < outForwardDesc.Units; i++)
memcpy(contiguousOutMemory.get() + i * outForwardDesc.Width * outForwardDesc.Height, targets[i].Data, outForwardDesc.Width * outForwardDesc.Height * sizeof(float));
INFO("Back propagating the max pool network");
auto backNetworkResult = network.BackPropUnaligned(contiguousMemory.get(), 0, contiguousOutMemory.get());
CHECK(inputMatrices.size() == targets.size());
vector<Matrixf> backMatrices;
INFO("Calculating the output layer here, it must be linear activation since we use max sampling");
for (size_t i = 0; i < inputMatrices.size(); i++)
backMatrices.push_back(inputMatrices[i] - targets[i]);
for (int i = static_cast<int>(layersCount) - 1; i > 0; i--)
{
auto& heigthWidth = heightWidths[i - 1];
vector<Matrixf> resultMatrices;
for (size_t j = 0; j < backMatrices.size(); j++)
resultMatrices.push_back(backMatrices[j].MaxUpSample(get<0>(heigthWidth), get<1>(heigthWidth), downSampleIndices[i][j]));
//cout << resultMatrices[0].GetString() << endl;
backMatrices = resultMatrices;
}
for(size_t i = 0; i < backMatrices.size(); i++)
{
auto backMatrix = backMatrices[i];
Matrixf networkMatrix(backMatrix.RowCount(), backMatrix.ColumnCount(), backNetworkResult.get() + i * backMatrix.RowCount() * backMatrix.ColumnCount());
//cout << "Network matrix: " << endl << networkMatrix.GetString() << endl;
//cout << "Back matrix: " << endl << backMatrix.GetString() << endl;
auto difference = (backMatrix- networkMatrix).Norm2Square() / backMatrix.ElementCount();
cout << "Back Difference: " << difference << endl;
//cout << "Difference matrix: " << (backMatrix- networkMatrix).GetString() << endl;
CHECK(difference < 1E-13f);
}
}
}
}
| 38.134783
| 168
| 0.718162
|
mihed
|
1b4f9ba62223ab6e1e075be1419ee5f4cfb4ef9a
| 821
|
cpp
|
C++
|
Src/Middle/69_Sqrt.cpp
|
HATTER-LONG/https---github.com-HATTER-LONG-AlgorithmTraining
|
bd2773c066352bab46ac019cef9fbbff8761c147
|
[
"Apache-2.0"
] | 2
|
2021-02-07T07:03:43.000Z
|
2021-02-08T16:04:42.000Z
|
Src/Middle/69_Sqrt.cpp
|
HATTER-LONG/https---github.com-HATTER-LONG-AlgorithmTraining
|
bd2773c066352bab46ac019cef9fbbff8761c147
|
[
"Apache-2.0"
] | null | null | null |
Src/Middle/69_Sqrt.cpp
|
HATTER-LONG/https---github.com-HATTER-LONG-AlgorithmTraining
|
bd2773c066352bab46ac019cef9fbbff8761c147
|
[
"Apache-2.0"
] | 1
|
2021-02-24T09:48:26.000Z
|
2021-02-24T09:48:26.000Z
|
#include "Tools/Tools.hpp"
#include <tuple>
/*
* 题目描述
* 给定一个非负整数,求它的开方,向下取整。
*
* 输入输出样例
* 输入一个整数,输出一个整数。
*
* Input: 8
* Output: 2
* 8 的开方结果是 2.82842...,向下取整即是 2。
*/
int mySqrt2(int a)
{
long x = a;
while (x * x > a)
{
x = (x + a / x) / 2;
}
return x;
}
int mySqrt(int a)
{
if (a == 0)
return 0;
int l = 1, r = a, mid, sqrtl = 0;
while (l <= r)
{
mid = l + (r - l) / 2;
sqrtl = a / mid;
if (sqrtl == mid)
return mid;
if (mid > sqrtl)
r = mid - 1;
else
l = mid + 1;
}
return r;
}
TEST_CASE()
{
int input;
int result;
tie(input, result) = GENERATE(table<int, int>({ make_tuple(8, 2) }));
CAPTURE(input, result);
REQUIRE(mySqrt(input) == result);
}
| 14.927273
| 73
| 0.45067
|
HATTER-LONG
|
1b508e4311b6c313811ba29a514db800ebb7c6c4
| 8,061
|
cpp
|
C++
|
libs/process/test/environment.cpp
|
lijgame/boost
|
ec2214a19cdddd1048058321a8105dd0231dac47
|
[
"BSL-1.0"
] | null | null | null |
libs/process/test/environment.cpp
|
lijgame/boost
|
ec2214a19cdddd1048058321a8105dd0231dac47
|
[
"BSL-1.0"
] | 2
|
2021-03-20T05:38:48.000Z
|
2021-03-31T20:14:11.000Z
|
libs/process/test/environment.cpp
|
lijgame/boost
|
ec2214a19cdddd1048058321a8105dd0231dac47
|
[
"BSL-1.0"
] | null | null | null |
// Copyright (c) 2006, 2007 Julio M. Merino Vidal
// Copyright (c) 2008 Ilya Sokolov, Boris Schaeling
// Copyright (c) 2009 Boris Schaeling
// Copyright (c) 2010 Felipe Tanus, Boris Schaeling
// Copyright (c) 2011, 2012 Jeff Flinn, Boris Schaeling
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#define BOOST_TEST_MAIN
#define BOOST_TEST_IGNORE_SIGCHLD
#include <boost/test/included/unit_test.hpp>
#include <boost/process/environment.hpp>
namespace bp = boost::process;
namespace std
{
std::ostream & operator<<(std::ostream & str, const std::wstring & ws)
{
str << bp::detail::convert(ws);
return str;
}
}
BOOST_AUTO_TEST_CASE(empty, *boost::unit_test::timeout(5))
{
bp::environment ev ;
BOOST_CHECK(ev.empty());
BOOST_CHECK_EQUAL(ev.size(), 0u);
BOOST_CHECK_EQUAL(ev.end() - ev.begin(), 0);
ev["Thingy"] = "My value";
BOOST_CHECK(!ev.empty());
BOOST_CHECK_EQUAL(ev.size(), 1u);
BOOST_CHECK_EQUAL(ev.end() - ev.begin(), 1);
for (auto x : ev)
{
BOOST_CHECK_EQUAL(x.to_string(), "My value");
BOOST_CHECK_EQUAL(x.get_name(), "Thingy");
}
ev["Thingy"].clear();
BOOST_CHECK(ev.empty());
BOOST_CHECK_EQUAL(ev.size(), 0u);
BOOST_CHECK_EQUAL(ev.end() - ev.begin(), 0);
ev.clear();
}
BOOST_AUTO_TEST_CASE(wempty, *boost::unit_test::timeout(5))
{
bp::wenvironment ev ;
BOOST_CHECK(ev.empty());
BOOST_CHECK_EQUAL(ev.size(), 0u);
BOOST_CHECK_EQUAL(ev.end() - ev.begin(), 0);
ev[L"Thingy"] = L"My value";
BOOST_CHECK(!ev.empty());
BOOST_CHECK_EQUAL(ev.size(), 1u);
BOOST_CHECK_EQUAL(ev.end() - ev.begin(), 1);
for (auto x : ev)
{
BOOST_CHECK(x.to_string() == L"My value");
BOOST_CHECK(x.get_name() == L"Thingy");
}
ev[L"Thingy"].clear();
BOOST_CHECK(ev.empty());
BOOST_CHECK_EQUAL(ev.size(), 0u);
BOOST_CHECK_EQUAL(ev.end() - ev.begin(), 0);
ev.clear();
}
BOOST_AUTO_TEST_CASE(compare, *boost::unit_test::timeout(5))
{
auto nat = boost::this_process::environment();
bp::environment env = nat;
{
BOOST_CHECK_EQUAL(nat.size(), env.size());
auto ni = nat.begin();
auto ei = env.begin();
while ((ni != nat.end()) &&(ei != env.end()))
{
BOOST_CHECK_EQUAL(ni->get_name(), ei->get_name());
BOOST_CHECK_EQUAL(ni->to_string(), ei->to_string());
ni++; ei++;
}
}
//ok check if I can convert it.
bp::wenvironment wenv{env};
auto wnat = boost::this_process::wenvironment();
BOOST_CHECK_EQUAL(wenv.size(), env.size());
BOOST_CHECK_EQUAL(wnat.size(), nat.size());
{
BOOST_CHECK_EQUAL(wnat.size(), wenv.size());
auto ni = wnat.begin();
auto ei = wenv.begin();
while ((ni != wnat.end()) && (ei != wenv.end()))
{
BOOST_CHECK_EQUAL(ni->get_name() , ei->get_name());
BOOST_CHECK_EQUAL(ni->to_string(), ei->to_string());
ni++; ei++;
}
BOOST_CHECK(ni == wnat.end());
}
BOOST_TEST_PASSPOINT();
env.clear();
BOOST_TEST_PASSPOINT();
wenv.clear();
BOOST_TEST_PASSPOINT();
}
BOOST_AUTO_TEST_CASE(insert_remove, *boost::unit_test::timeout(5))
{
bp::environment env(boost::this_process::environment());
auto sz = env.size();
BOOST_REQUIRE_GE(sz, 1u);
BOOST_REQUIRE_EQUAL(env.count("BOOST_TEST_VAR"), 0u);
env["BOOST_TEST_VAR"] = {"some string", "badabumm"};
#if defined(BOOST_WINDOWS_API)
BOOST_CHECK_EQUAL(env["BOOST_TEST_VAR"].to_string(), "some string;badabumm");
#else
BOOST_CHECK_EQUAL(env["BOOST_TEST_VAR"].to_string(), "some string:badabumm");
#endif
BOOST_CHECK_EQUAL(sz +1, env.size());
env["BOOST_TEST_VAR"].clear();
BOOST_CHECK_EQUAL(env.size(), sz);
env.clear();
}
BOOST_AUTO_TEST_CASE(clear_empty_my, *boost::unit_test::timeout(5))
{
bp::native_environment env;
bp::environment e = env;
const std::size_t sz = env.size();
BOOST_TEST_MESSAGE("Current native size: " << sz);
BOOST_REQUIRE_EQUAL(env.count("BOOST_PROCESS_TEST_VAR_a"), 0u);
BOOST_REQUIRE_EQUAL(env.count("BOOST_PROCESS_TEST_VAR_b"), 0u);
BOOST_REQUIRE_EQUAL(env.count("BOOST_PROCESS_TEST_VAR_c"), 0u);
env["BOOST_PROCESS_TEST_VAR_a"] = "1";
env["BOOST_PROCESS_TEST_VAR_b"] = "2";
BOOST_CHECK(env.emplace("BOOST_PROCESS_TEST_VAR_c", "3").second);
BOOST_CHECK_EQUAL(env.count("BOOST_PROCESS_TEST_VAR_a"), 1u);
BOOST_CHECK_EQUAL(env.count("BOOST_PROCESS_TEST_VAR_b"), 1u);
BOOST_CHECK_EQUAL(env.count("BOOST_PROCESS_TEST_VAR_c"), 1u);
BOOST_CHECK_EQUAL(env.at("BOOST_PROCESS_TEST_VAR_a").to_string(), "1");
BOOST_CHECK_EQUAL(env.at("BOOST_PROCESS_TEST_VAR_b").to_string(), "2");
BOOST_CHECK_EQUAL(env.at("BOOST_PROCESS_TEST_VAR_c").to_string(), "3");
BOOST_CHECK_EQUAL(env.size(), sz + 3u);
BOOST_CHECK_EQUAL(std::distance(env.begin(), env.end()), sz + 3);
BOOST_CHECK_EQUAL(std::distance(env.cbegin(), env.cend()), sz + 3);
env.erase("BOOST_PROCESS_TEST_VAR_a");
BOOST_CHECK_EQUAL(env.size(), sz + 2u);
BOOST_CHECK_EQUAL(env.count("BOOST_PROCESS_TEST_VAR_a"), 0u);
BOOST_CHECK_EQUAL(env.at ("BOOST_PROCESS_TEST_VAR_b").to_string(), "2");
BOOST_CHECK_EQUAL(env.at ("BOOST_PROCESS_TEST_VAR_c").to_string(), "3");
BOOST_CHECK_EQUAL(std::distance(env.begin(), env.end()), sz + 2);
BOOST_CHECK_EQUAL(std::distance(env.cbegin(), env.cend()), sz + 2);
env.erase("BOOST_PROCESS_TEST_VAR_b");
BOOST_CHECK_EQUAL(env.size(), sz + 1u);
BOOST_CHECK_EQUAL(env.count("BOOST_PROCESS_TEST_VAR_a"), 0u);
BOOST_CHECK_EQUAL(env.count("BOOST_PROCESS_TEST_VAR_b"), 0u);
BOOST_CHECK_EQUAL(env.at ("BOOST_PROCESS_TEST_VAR_c").to_string(), "3");
BOOST_CHECK_EQUAL(std::distance(env.begin(), env.end()), sz + 1);
BOOST_CHECK_EQUAL(std::distance(env.cbegin(), env.cend()), sz + 1);
env.clear();
//note: windows puts an entry without a name into the list, so it might not be empty after clear.
BOOST_CHECK_LE(env.size(), sz);
BOOST_CHECK_LE(std::distance(env.begin(), env.end()), sz);
BOOST_CHECK_LE(std::distance(env.cbegin(), env.cend()), sz);
for (auto && ee : e)
env.emplace(ee.get_name(), ee.to_string());
}
BOOST_AUTO_TEST_CASE(clear_empty, *boost::unit_test::timeout(5))
{
bp::environment env;
BOOST_CHECK(env.empty());
BOOST_CHECK_EQUAL(env.size(), 0u);
env["a"] = "1";
env["b"] = "2";
env["c"] = "3";
BOOST_CHECK_EQUAL(env.at("a").to_string(), "1");
BOOST_CHECK_EQUAL(env.at("b").to_string(), "2");
BOOST_CHECK_EQUAL(env.at("c").to_string(), "3");
BOOST_CHECK_EQUAL(env.size(), 3u);
BOOST_CHECK_EQUAL(std::distance(env.begin(), env.end()), 3u);
BOOST_CHECK_EQUAL(std::distance(env.cbegin(), env.cend()), 3u);
env.erase("a");
BOOST_CHECK_EQUAL(env.size(), 2u);
BOOST_CHECK_EQUAL(env.count("a"), 0u);
BOOST_CHECK_EQUAL(env.at("b").to_string(), "2");
BOOST_CHECK_EQUAL(env.at("c").to_string(), "3");
BOOST_CHECK_EQUAL(std::distance(env.begin(), env.end()), 2u);
BOOST_CHECK_EQUAL(std::distance(env.cbegin(), env.cend()), 2u);
env.erase("b");
BOOST_CHECK_EQUAL(env.size(), 1u);
BOOST_CHECK_EQUAL(env.count("a"), 0u);
BOOST_CHECK_EQUAL(env.count("b"), 0u);
BOOST_CHECK_EQUAL(env.at("c").to_string(), "3");
BOOST_CHECK_EQUAL(std::distance(env.begin(), env.end()), 1u);
BOOST_CHECK_EQUAL(std::distance(env.cbegin(), env.cend()), 1u);
env.clear();
BOOST_CHECK(env.empty());
BOOST_CHECK_EQUAL(env.size(), 0u);
BOOST_CHECK_EQUAL(std::distance(env.begin(), env.end()), 0u);
BOOST_CHECK_EQUAL(std::distance(env.cbegin(), env.cend()), 0u);
}
| 32.768293
| 102
| 0.629078
|
lijgame
|
1b52594ff3fa86fa05c5b98986fa9770c21e3304
| 1,419
|
hpp
|
C++
|
PPmatrix/transform_view.hpp
|
Petkr/PPmatrix
|
af0d6bece21a39f837e14d9dbee3e72bbfda14b4
|
[
"MIT"
] | null | null | null |
PPmatrix/transform_view.hpp
|
Petkr/PPmatrix
|
af0d6bece21a39f837e14d9dbee3e72bbfda14b4
|
[
"MIT"
] | null | null | null |
PPmatrix/transform_view.hpp
|
Petkr/PPmatrix
|
af0d6bece21a39f837e14d9dbee3e72bbfda14b4
|
[
"MIT"
] | null | null | null |
#pragma once
#include "simple_view.hpp"
namespace PPmatrix
{
template <iterator BaseIterator, typename Transform>
class transform_iterator
{
compressed_pair<BaseIterator, Transform> pair;
public:
constexpr transform_iterator(BaseIterator base_iterator, Transform t)
: pair{ base_iterator, t }
{}
constexpr decltype(auto) operator*() const
{
return pair.second(*pair.first);
}
constexpr auto& operator+=(size_t offset)
{
pair.first += offset;
return *this;
}
constexpr auto& operator-=(size_t offset)
{
pair.first -= offset;
return *this;
}
constexpr auto operator==(iterator auto other) const
{
return pair.first == other;
}
constexpr auto& base()
{
return pair.first;
}
constexpr auto base() const
{
return pair.first;
}
};
template <typename Functor>
struct transform
{
Functor functor;
constexpr transform(Functor functor)
: functor(functor)
{}
};
constexpr view auto transform_view(view auto&& v, auto f)
{
return transform_iterator(begin(v), f) ^ transform_iterator(end(v), f);
}
constexpr iterator auto operator&(iterator auto i, transform<auto> t)
{
return transform_iterator(i, t.functor);
}
constexpr view auto operator||(view auto&& v, transform<auto> t)
{
return begin(v) & t ^ end(v);
}
constexpr view auto operator|(view auto&& v, transform<auto> t)
{
return transform_view(v, t.functor);
}
}
| 19.985915
| 73
| 0.688513
|
Petkr
|
1b56f7613400d53a28d750559476530c1f30af0c
| 4,279
|
cpp
|
C++
|
dev/ext/noice.io/dev/src/TextReader.cpp
|
gnilk/yapt
|
1f1d7bad26fb477b545927774f323c367c0e1dad
|
[
"BSD-3-Clause"
] | null | null | null |
dev/ext/noice.io/dev/src/TextReader.cpp
|
gnilk/yapt
|
1f1d7bad26fb477b545927774f323c367c0e1dad
|
[
"BSD-3-Clause"
] | null | null | null |
dev/ext/noice.io/dev/src/TextReader.cpp
|
gnilk/yapt
|
1f1d7bad26fb477b545927774f323c367c0e1dad
|
[
"BSD-3-Clause"
] | null | null | null |
/*-------------------------------------------------------------------------
File : $Archive: TextReader.cpp $
Author : $Author: Fkling $
Version : $Revision: 1 $
Orginal : 2009-11-02, 15:50
Descr : Implements a class that reads text lines from a stream
Modified: $Date: $ by $Author: Fkling $
---------------------------------------------------------------------------
TODO: [ -:Not done, +:In progress, !:Completed]
<pre>
! Support simple reading of bytes as well as lines
</pre>
\History
- 02.11.09, FKling, Implementation
- 10.11.09, FKling, Support for simple reads (no CRLN conversion)
- 09.12.09, FKling, Free buffer in destructor
---------------------------------------------------------------------------*/
#include <stdlib.h>
#include <stdio.h>
#ifdef WIN32
#include <malloc.h>
#define WIN32_LEAN_AND_MEAN
#define snprintf _snprintf
#include <windows.h>
#else
#endif
//#include "noice/io/ySystem.h"
//#include "noice/io/TextReader.h"
//using namespace yapt;
#include "noice/io/io.h"
#include "noice/io/ioutils.h"
#include "noice/io/TextReader.h" // TODO: Reconsider this
using namespace noice::io;
const int TextReader::kTextReader_ChunkSize = 1024;
TextReader::TextReader(IStream *pStream)
{
buffer = NULL;
this->pStream = pStream;
if (pStream->Open(kStreamOp_ReadOnly))
{
pos = 0;
buffer = (char *)malloc(kTextReader_ChunkSize);
bHaveData = true;
} else
{
this->pStream= NULL;
}
pos = endpos = 0;
}
TextReader::~TextReader()
{
// someone deleted us without calling close
if(pStream != NULL)
{
pStream->Close();
}
if (buffer != NULL)
{
free(buffer);
}
}
bool TextReader::Close()
{
if (pStream != NULL)
{
pStream->Close();
pStream = NULL;
}
return true;
}
char *TextReader::FindLine()
{
// no more data, last returned line was the last available
if (pos > endpos) return NULL;
bool bNeedMoreChars = false;
// strip of all empty lines - work on pos, update original buffer pointer
while(((buffer[pos]==0x0a) || (buffer[pos]==0x0d)) && (buffer[pos]!='\0'))
{
pos++;
if (pos>=endpos)
{
bNeedMoreChars = true;
break;
}
}
// reached the end, only empty lines??
int idx = pos;
if (!bNeedMoreChars)
{
// dig out one line..
while((buffer[idx]!=0x0a) && (buffer[idx]!=0x0d) && (buffer[idx]!='\0'))
{
idx++;
if (idx>=endpos)
{
bNeedMoreChars = true;
break;
}
}
}
// need more and we have more..
if ((bNeedMoreChars) && (bHaveData)) return NULL;
// allocate and copy line
char *result = (char *)malloc(idx - pos + 1);
memcpy(result, &buffer[pos], idx - pos);
result[idx-pos]='\0';
pos = idx+1;
return result;
}
void TextReader::MoreData()
{
if (pos > 0)
{
memset(buffer,'X',pos);
memcpy(buffer, &buffer[pos],endpos-pos);
}
int offset = endpos - pos;
// can't read directly to "buffer"
long szRead = kTextReader_ChunkSize - offset;
endpos = pStream->Read(&buffer[offset], szRead);
if (endpos < szRead)
{
// got less?? -> no more data available
bHaveData = false;
}
endpos += offset;
pos = 0;
}
char *TextReader::ReadLine()
{
char *res = NULL;
// todo: read a line from the buffer
if (pStream != NULL)
{
if (pos > 0) res = FindLine();
if ((res == NULL) && (bHaveData))
{
MoreData();
res = FindLine();
}
}
return res;
}
char *TextReader::ReadLine(char *pDest, int nMax)
{
char *tmp = ReadLine();
if (tmp != NULL)
{
snprintf(pDest, nMax, "%s", tmp);
free(tmp);
} else
{
pDest = NULL;
}
return pDest;
}
// simply reads data without doing any line magic
int TextReader::Read(char *pDest, int nBytes)
{
// TODO: Finalize this function
int res = 0;
if ((endpos - pos) > nBytes)
{
memcpy(pDest, &buffer[pos],nBytes);
pos += nBytes;
res = nBytes;
} else
{
int nCopied = 0;
int nBlock = 0;
// no data at all, try suck in some..
if ((endpos-pos) == 0) MoreData();
// continue as long as we have bytes to consume and there are bytes to consume
while((nBytes > 0) && ((endpos - pos) != 0))
{
nBlock = (endpos - pos);
if (nBlock > nBytes)
{
nBlock = nBytes;
}
memcpy(&pDest[nCopied], &buffer[pos],nBlock);
nCopied += nBlock;
pos += nBlock;
nBytes -= nBlock;
// end of available information, suck in some more
MoreData();
}
res = nCopied;
}
return res;
}
| 20.572115
| 80
| 0.600608
|
gnilk
|
1b574ddcd935d9595e0fa4567a2109992f4d822a
| 6,894
|
cc
|
C++
|
gui/sound_frame.cc
|
BradenButler/simutrans
|
86f29844625119182896e0e08d7b775bc847758d
|
[
"Artistic-1.0"
] | null | null | null |
gui/sound_frame.cc
|
BradenButler/simutrans
|
86f29844625119182896e0e08d7b775bc847758d
|
[
"Artistic-1.0"
] | null | null | null |
gui/sound_frame.cc
|
BradenButler/simutrans
|
86f29844625119182896e0e08d7b775bc847758d
|
[
"Artistic-1.0"
] | null | null | null |
/*
* This file is part of the Simutrans project under the Artistic License.
* (see LICENSE.txt)
*/
/*
* Dialog for sound settings
*/
#include "sound_frame.h"
#include "../simsound.h"
#include "../dataobj/translator.h"
#include "../dataobj/environment.h"
#include "components/gui_divider.h"
#ifdef USE_FLUIDSYNTH_MIDI
#include "loadsoundfont_frame.h"
#endif
#define L_KNOB_SIZE (32)
void sound_frame_t::update_song_name()
{
const int current_midi = get_current_midi();
if( current_midi < 0 ) {
song_name_label.buf().printf( translator::translate("Music playing disabled/not available") );
}
#ifdef USE_FLUIDSYNTH_MIDI
else if( strcmp( env_t::soundfont_filename.c_str(), "Error") == 0 ){
song_name_label.buf().printf( translator::translate("Soundfont not found. Please select a soundfont below.") );
}
#endif
else {
song_name_label.buf().printf("%d - %s", current_midi + 1, sound_get_midi_title( current_midi ) );
}
song_name_label.update();
song_name_label.set_size( song_name_label.get_min_size() );
// Loadsoundfont dialog may unmute us, update mute status
music_mute_button.pressed = midi_get_mute();
previous_song_button.enable( !music_mute_button.pressed );
next_song_button.enable( !music_mute_button.pressed );
}
const char *specific_volume_names[ MAX_SOUND_TYPES ] = {
"TOOL_SOUND",
"TRAFFIC_SOUND",
"AMBIENT_SOUND",
"FACTORY_SOUND",
"CROSSING_SOUND",
"CASH_SOUND"
};
sound_frame_t::sound_frame_t() :
gui_frame_t( translator::translate("Sound settings") ),
sound_volume_scrollbar(scrollbar_t::horizontal),
music_volume_scrollbar(scrollbar_t::horizontal)
{
set_table_layout(1,0);
sound_mute_button.init( button_t::square_state, "mute sound");
sound_mute_button.pressed = sound_get_mute();
add_component(&sound_mute_button);
sound_mute_button.add_listener( this );
add_table(2,0);
{
// Sound volume label
new_component<gui_label_t>( "Sound volume:" );
sound_volume_scrollbar.set_knob( L_KNOB_SIZE, 255 + L_KNOB_SIZE );
sound_volume_scrollbar.set_knob_offset( sound_get_global_volume() );
sound_volume_scrollbar.set_scroll_discrete( false );
sound_volume_scrollbar.add_listener( this );
add_component( &sound_volume_scrollbar );
new_component<gui_label_t>( "Sound range:" );
sound_range.set_value( env_t::sound_distance_scaling);
sound_range.set_limits( 1, 32 );
sound_range.add_listener(this);
// sound_range.set_tooltip( "Lower values mean more local sounds" )
add_component(&sound_range);
for( int i = 0; i < MAX_SOUND_TYPES; i++ ) {
new_component<gui_label_t>( specific_volume_names[i] );
specific_volume_scrollbar[ i ] = new scrollbar_t( scrollbar_t::horizontal );
specific_volume_scrollbar[i]->set_knob( L_KNOB_SIZE, 255 + L_KNOB_SIZE );
specific_volume_scrollbar[i]->set_knob_offset( sound_get_specific_volume((sound_type_t)i) );
specific_volume_scrollbar[i]->set_scroll_discrete( false );
specific_volume_scrollbar[i]->add_listener( this );
add_component( specific_volume_scrollbar[i] );
}
}
end_table();
new_component<gui_divider_t>();
// Music
music_mute_button.init( button_t::square_state, "disable midi");
music_mute_button.pressed = midi_get_mute();
music_mute_button.add_listener( this );
#ifdef USE_FLUIDSYNTH_MIDI
if( strcmp( env_t::soundfont_filename.c_str(), "Error" ) == 0 ){
music_mute_button.enable( !music_mute_button.pressed );
}
#endif
add_component(&music_mute_button);
add_table(2,0);
{
new_component<gui_label_t>( "Music volume:" );
music_volume_scrollbar.set_knob( L_KNOB_SIZE, 255 + L_KNOB_SIZE );
music_volume_scrollbar.set_knob_offset( sound_get_midi_volume() );
music_volume_scrollbar.set_scroll_discrete( false );
music_volume_scrollbar.add_listener( this );
add_component( &music_volume_scrollbar );
}
end_table();
// song selection
new_component<gui_label_t>( "Currently playing:" );
add_table( 3, 1 );
{
previous_song_button.set_typ( button_t::arrowleft );
previous_song_button.add_listener( this );
previous_song_button.enable( !music_mute_button.pressed );
add_component( &previous_song_button );
next_song_button.set_typ( button_t::arrowright );
next_song_button.add_listener( this );
next_song_button.enable( !music_mute_button.pressed );
add_component( &next_song_button );
add_component( &song_name_label );
update_song_name();
}
end_table();
shuffle_song_button.init( button_t::square_state, "shuffle midis" );
shuffle_song_button.pressed = sound_get_shuffle_midi();
shuffle_song_button.add_listener(this);
add_component(&shuffle_song_button);
#ifdef USE_FLUIDSYNTH_MIDI
// Soundfont selection
soundfont_button.init( button_t::roundbox_state | button_t::flexible, "Select soundfont" );
soundfont_button.add_listener(this);
add_component( &soundfont_button );
#endif
set_resizemode(diagonal_resize);
reset_min_windowsize();
}
bool sound_frame_t::action_triggered( gui_action_creator_t *comp, value_t p)
{
if (comp == &next_song_button) {
midi_stop();
midi_next_track();
check_midi();
update_song_name();
}
else if (comp == &previous_song_button) {
midi_stop();
midi_last_track();
check_midi();
update_song_name();
}
else if (comp == &shuffle_song_button) {
sound_set_shuffle_midi( !sound_get_shuffle_midi() );
shuffle_song_button.pressed = sound_get_shuffle_midi();
}
else if (comp == &sound_mute_button) {
sound_set_mute( !sound_mute_button.pressed );
sound_mute_button.pressed = sound_get_mute();
}
else if (comp == &music_mute_button) {
midi_set_mute( !music_mute_button.pressed );
music_mute_button.pressed = midi_get_mute();
previous_song_button.enable( !music_mute_button.pressed );
next_song_button.enable( !music_mute_button.pressed );
}
else if (comp == &sound_volume_scrollbar) {
sound_set_global_volume(p.i);
}
else if (comp == &music_volume_scrollbar) {
sound_set_midi_volume(p.i);
}
else if (comp == &sound_range) {
env_t::sound_distance_scaling = p.i;
}
#ifdef USE_FLUIDSYNTH_MIDI
else if( comp == &soundfont_button ) {
create_win( new loadsoundfont_frame_t(), w_info, magic_soundfont );
}
#endif
else {
for( int i = 0; i < MAX_SOUND_TYPES; i++ ) {
if( comp == specific_volume_scrollbar[ i ] ) {
sound_set_specific_volume( p.i, (sound_type_t)i );
}
}
}
return true;
}
/**
* Draw new component. The values to be passed refer to the window
* i.e. It's the screen coordinates of the window where the
* component is displayed.
*/
void sound_frame_t::draw(scr_coord pos, scr_size size)
{
// update song name label
update_song_name();
#ifdef USE_FLUIDSYNTH_MIDI
if( !strcmp(env_t::soundfont_filename.c_str(), "Error") == 0 ){
music_mute_button.enable( true );
}
#endif
gui_frame_t::draw(pos, size);
}
// need to delete scroll bars
sound_frame_t::~sound_frame_t()
{
for( int i = 0; i < MAX_SOUND_TYPES; i++ ) {
delete specific_volume_scrollbar[ i ];
}
}
| 28.966387
| 113
| 0.745866
|
BradenButler
|
1b57b5eb551716c0dbd189da443526c1cebfce8e
| 8,748
|
cpp
|
C++
|
tools/src/Productizer.cpp
|
jmakovicka/OsmAnd-core
|
d18f57bb123b6c6ad0adbed0c2f4419d0e6a6610
|
[
"MIT"
] | null | null | null |
tools/src/Productizer.cpp
|
jmakovicka/OsmAnd-core
|
d18f57bb123b6c6ad0adbed0c2f4419d0e6a6610
|
[
"MIT"
] | null | null | null |
tools/src/Productizer.cpp
|
jmakovicka/OsmAnd-core
|
d18f57bb123b6c6ad0adbed0c2f4419d0e6a6610
|
[
"MIT"
] | null | null | null |
#include "Productizer.h"
#include <OsmAndCore/stdlib_common.h>
#include <OsmAndCore/ignore_warnings_on_external_includes.h>
#include <iomanip>
#include <OsmAndCore/restore_internal_warnings.h>
#include <OsmAndCore/QtExtensions.h>
#include <OsmAndCore/ignore_warnings_on_external_includes.h>
#include <QSet>
#include <QFile>
#include <QXmlStreamWriter>
#include <OsmAndCore/restore_internal_warnings.h>
#include <OsmAndCore/QtCommon.h>
#include <OsmAndCore.h>
#include <OsmAndCore/Common.h>
#include <OsmAndCore/QKeyValueIterator.h>
#include <OsmAndCoreTools.h>
#include <OsmAndCoreTools/Utilities.h>
OsmAndTools::Productizer::Productizer(const Configuration& configuration_)
: configuration(configuration_)
{
}
OsmAndTools::Productizer::~Productizer()
{
}
#if defined(_UNICODE) || defined(UNICODE)
bool OsmAndTools::Productizer::productize(std::wostream& output)
#else
bool OsmAndTools::Productizer::productize(std::ostream& output)
#endif
{
if (configuration.verbose)
output << xT("Going to create IAP product definitions for ") << configuration.regions.size() << xT(" region(s)...") << std::endl;
// Find subregions for each region (unflatten regions hierarchy)
QHash< QString, QSet< QString > > subregionsByParent;
for (const auto& region : configuration.regions)
{
// Root elements should be skipped
if (region->parentId.isNull())
continue;
subregionsByParent[region->parentId].insert(region->id);
}
// Compute price tier for each region:
QHash< QString, int> priceTierByRegion;
// Price tiers:
// 0 - free/not-a-product
// 1 - country
// 2 - large country
// 3 - "part of the world"
// 4 - "world"
// Special price tiers:
priceTierByRegion[QString::null] = 4;
priceTierByRegion[OsmAnd::WorldRegions::AfricaRegionId] = 3;
priceTierByRegion[OsmAnd::WorldRegions::AsiaRegionId] = 3;
priceTierByRegion[OsmAnd::WorldRegions::AustraliaAndOceaniaRegionId] = 3;
priceTierByRegion[OsmAnd::WorldRegions::CentralAmericaRegionId] = 3;
priceTierByRegion[OsmAnd::WorldRegions::EuropeRegionId] = 3;
priceTierByRegion[OsmAnd::WorldRegions::NorthAmericaRegionId] = 3;
priceTierByRegion[OsmAnd::WorldRegions::SouthAmericaRegionId] = 3;
priceTierByRegion[QLatin1String("us_northamerica")] = 2;
priceTierByRegion[QLatin1String("canada_northamerica")] = 2;
priceTierByRegion[OsmAnd::WorldRegions::RussiaRegionId] = 2;
priceTierByRegion[QLatin1String("germany_europe")] = 1;
priceTierByRegion[QLatin1String("italy_europe")] = 1;
priceTierByRegion[QLatin1String("france_europe")] = 1;
priceTierByRegion[QLatin1String("gb_england_europe")] = 1;
// Everything else has price trier of a country (with exceptions)
for (const auto& region : configuration.regions)
{
// Skip if a special price is defined
if (priceTierByRegion.contains(region->id))
continue;
// Subregions of following countries are treated as bundle-only regions:
// - Germany
// - Italy
// - France
// - USA
// - Canada
// - England
// - Russia
bool isBundleOnly = false;
isBundleOnly = isBundleOnly || (region->parentId == QLatin1String("germany_europe"));
isBundleOnly = isBundleOnly || (region->parentId == QLatin1String("italy_europe"));
isBundleOnly = isBundleOnly || (region->parentId == QLatin1String("france_europe"));
isBundleOnly = isBundleOnly || (region->parentId == QLatin1String("us_northamerica"));
isBundleOnly = isBundleOnly || (region->parentId == QLatin1String("canada_northamerica"));
isBundleOnly = isBundleOnly || (region->parentId == QLatin1String("gb_england_europe"));
isBundleOnly = isBundleOnly || (region->parentId == QLatin1String("russia"));
if (isBundleOnly)
{
if (configuration.verbose)
output << xT("Region '") << QStringToStlString(region->id) << xT("' is treated as bundle-only region") << std::endl;
priceTierByRegion[region->id] = 0;
continue;
}
priceTierByRegion[region->id] = 1;
}
QFile file(configuration.outputProductsFilename);
if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text))
{
output << xT("Failed to open '") << QStringToStlString(configuration.outputProductsFilename) << xT("' for writing") << std::endl;
return false;
}
QXmlStreamWriter writer(&file);
writer.setAutoFormatting(true);
writer.writeStartDocument(QLatin1String("1.0"), true);
// <products>
writer.writeStartElement(QLatin1String("products"));
bool success = true;
for (;;)
{
// Write all products that are based on regions
for (const auto& itPriceEntry : OsmAnd::rangeOf(priceTierByRegion))
{
const auto& regionId = itPriceEntry.key();
const auto& priceTier = itPriceEntry.value();
if (configuration.verbose)
output << xT("Product from region '") << QStringToStlString(regionId) << xT("' has ") << priceTier << xT(" price tier") << std::endl;
// <regionAsProduct>
writer.writeStartElement(QLatin1String("regionAsProduct"));
writer.writeAttribute(QLatin1String("regionId"), regionId);
writer.writeAttribute(QLatin1String("priceTier"), QString::number(priceTier));
// Write names (if available)
const auto citRegion = configuration.regions.constFind(regionId);
if (citRegion != configuration.regions.cend())
{
const auto& region = *citRegion;
writer.writeAttribute(QLatin1String("name"), region->name);
for (const auto& itLocalizedNameEntry : OsmAnd::rangeOf(region->localizedNames))
{
const auto& lang = itLocalizedNameEntry.key();
const auto& name = itLocalizedNameEntry.value();
// <localizedName/>
writer.writeStartElement(QLatin1String("localizedName"));
writer.writeAttribute(QLatin1String("lang"), lang);
writer.writeAttribute(QLatin1String("name"), name);
writer.writeEndElement();
}
}
// </regionAsProduct>
writer.writeEndElement();
}
break;
}
// </products>
writer.writeEndElement();
writer.writeEndDocument();
file.close();
return success;
}
bool OsmAndTools::Productizer::productize(QString *pLog /*= nullptr*/)
{
if (pLog != nullptr)
{
#if defined(_UNICODE) || defined(UNICODE)
std::wostringstream output;
const bool success = productize(output);
*pLog = QString::fromStdWString(output.str());
return success;
#else
std::ostringstream output;
const bool success = productize(output);
*pLog = QString::fromStdString(output.str());
return success;
#endif
}
else
{
#if defined(_UNICODE) || defined(UNICODE)
return productize(std::wcout);
#else
return productize(std::cout);
#endif
}
}
OsmAndTools::Productizer::Configuration::Configuration()
: verbose(false)
{
}
bool OsmAndTools::Productizer::Configuration::parseFromCommandLineArguments(
const QStringList& commandLineArgs,
Configuration& outConfiguration,
QString& outError)
{
outConfiguration = Configuration();
for (const auto& arg : commandLineArgs)
{
if (arg.startsWith(QLatin1String("-regions=")))
{
const auto value = Utilities::resolvePath(arg.mid(strlen("-regions=")));
if (!QFile(value).exists())
{
outError = QString("'%1' file does not exist").arg(value);
return false;
}
const auto ok = OsmAnd::WorldRegions(value).loadWorldRegions(outConfiguration.regions, nullptr);
if (!ok)
{
outError = QString("'%1' file can not be parsed as OCBF file").arg(value);
return false;
}
}
else if (arg.startsWith(QLatin1String("-outputProductsFilename=")))
{
outConfiguration.outputProductsFilename = Utilities::resolvePath(arg.mid(strlen("-outputProductsFilename=")));
}
else if (arg == QLatin1String("-verbose"))
{
outConfiguration.verbose = true;
}
else
{
outError = QString("Unrecognized argument: '%1'").arg(arg);
return false;
}
}
return true;
}
| 34.440945
| 149
| 0.633059
|
jmakovicka
|
1b5d35a67cfbdcaa1ea9824b36ee9d542e33591a
| 1,563
|
hpp
|
C++
|
include/p12218319/ann/NeuronI.hpp
|
p12218319/-DEPRECIATED-neural_network
|
95a4909efa6e2bbc5d6ae8f1fac5f3285a9a6cee
|
[
"Apache-2.0"
] | null | null | null |
include/p12218319/ann/NeuronI.hpp
|
p12218319/-DEPRECIATED-neural_network
|
95a4909efa6e2bbc5d6ae8f1fac5f3285a9a6cee
|
[
"Apache-2.0"
] | null | null | null |
include/p12218319/ann/NeuronI.hpp
|
p12218319/-DEPRECIATED-neural_network
|
95a4909efa6e2bbc5d6ae8f1fac5f3285a9a6cee
|
[
"Apache-2.0"
] | null | null | null |
/*
Copyright 2016 Adam Smith
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.
email : p12218319@myemail.dmu.ac.uk
*/
#ifndef P12218319_ANN_NEURONI_HPP
#define P12218319_ANN_NEURONI_HPP
#include "P12218319\core\Core.hpp"
namespace P12218319 { namespace ann {
class P12218319_EXPORT_API NeuronI {
protected:
virtual float* P12218319_CALL GetWeights() throw() = 0;
public:
virtual P12218319_CALL ~NeuronI(){}
virtual uint32_t P12218319_CALL GetInputs() const throw() = 0;
virtual float P12218319_CALL operator()(const float* const) const throw() = 0;
virtual void P12218319_CALL SetBias(const float) throw() = 0;
inline float& P12218319_CALL operator[](const uint32_t aWeight) throw() {return GetWeights()[aWeight];}
inline float P12218319_CALL operator[](const uint32_t aWeight) const throw() {return const_cast<NeuronI*>(this)->GetWeights()[aWeight];}
inline void P12218319_CALL SetBias(const float aBias) throw() {const uint32_t count = Size(); for(uint32_t i = 0; i < count; ++i) GetNeuron(i).SetBias(aBias);}
};
}}
#endif
| 39.075
| 161
| 0.746641
|
p12218319
|
1b6076eb4d935831523ba35736be2961bf7a0fb3
| 1,820
|
cpp
|
C++
|
src/net/ip.cpp
|
Vieraw/auth
|
5ed546a9b65289abc91c42813f66e59e363dd2d3
|
[
"MIT"
] | 2
|
2021-12-04T11:19:45.000Z
|
2021-12-30T11:56:14.000Z
|
src/net/ip.cpp
|
Vieraw/auth
|
5ed546a9b65289abc91c42813f66e59e363dd2d3
|
[
"MIT"
] | null | null | null |
src/net/ip.cpp
|
Vieraw/auth
|
5ed546a9b65289abc91c42813f66e59e363dd2d3
|
[
"MIT"
] | 1
|
2021-12-04T11:19:53.000Z
|
2021-12-04T11:19:53.000Z
|
//
// Created by php on 28-Aug-19.
//
#include <sstream>
#include <vector>
#include "ip.h"
namespace net {
std::vector<std::string> split(const std::string &data, char separator) {
std::vector<std::string> temp{};
std::stringstream ss(data);
std::string str;
while (std::getline(ss, str, separator)) {
temp.push_back(str);
}
return temp;
}
ip::ip(const std::string &ip) {
std::vector<std::string> parts = split(ip, '.');
if (parts.size() != 4) {
throw ip_error("Invalid format");
}
_ip = (std::stoull(parts[0]) << 24u) |
(std::stoull(parts[1]) << 16u) |
(std::stoull(parts[2]) << 8u) |
(std::stoull(parts[3]));
}
ip::ip(const uint32_t &ip) {
_ip = ip;
}
ip &ip::operator++() {
++_ip;
return *this;
}
ip ip::operator++(int) {
const ip result(*this);
++_ip;
return result;
}
ip &ip::operator--() {
--_ip;
return *this;
}
ip ip::operator--(int) {
const ip result(*this);
--_ip;
return result;
}
ip::operator unsigned int() const {
return _ip;
}
std::string ip::to_string() const {
std::stringstream ss;
ss << (_ip >> 24u & 0xFFu) << '.' << (_ip >> 16u & 0xFFu) << '.' << (_ip >> 8u & 0xFFu) << '.' << (_ip & 0xFFu);
return ss.str();
}
bool operator<(const ip &first, const ip &second) {
return first._ip < second._ip;
}
bool operator==(const ip &first, const ip &second) {
return first._ip == second._ip;
}
std::ostream &operator<<(std::ostream &os, const ip &address) {
os << address.to_string();
return os;
}
}
| 21.927711
| 120
| 0.484066
|
Vieraw
|
1b60b039f117037614fe68c4f1170cd0a08b6ade
| 8,093
|
cpp
|
C++
|
source/ParticleShader.cpp
|
Tomash667/carpglib
|
c8701b170e4e2cbdb4d52fe3b7c8529afb3e97ed
|
[
"MIT"
] | 4
|
2019-08-18T19:33:04.000Z
|
2021-08-07T02:12:54.000Z
|
source/ParticleShader.cpp
|
Tomash667/carpglib
|
c8701b170e4e2cbdb4d52fe3b7c8529afb3e97ed
|
[
"MIT"
] | 5
|
2019-08-14T05:45:56.000Z
|
2021-03-15T07:47:24.000Z
|
source/ParticleShader.cpp
|
Tomash667/carpglib
|
c8701b170e4e2cbdb4d52fe3b7c8529afb3e97ed
|
[
"MIT"
] | 2
|
2019-10-05T02:36:35.000Z
|
2021-02-15T20:20:09.000Z
|
#include "Pch.h"
#include "ParticleShader.h"
#include "Camera.h"
#include "DirectX.h"
#include "ParticleSystem.h"
#include "Render.h"
#include "Texture.h"
struct VsGlobals
{
Matrix matCombined;
};
//=================================================================================================
ParticleShader::ParticleShader() : deviceContext(app::render->GetDeviceContext()), vertexShader(nullptr), pixelShader(nullptr), layout(nullptr),
vsGlobals(nullptr), vb(nullptr), texEmpty(nullptr), particleCount(0)
{
}
//=================================================================================================
void ParticleShader::OnInit()
{
Render::ShaderParams params;
params.name = "particle";
params.decl = VDI_PARTICLE;
params.vertexShader = &vertexShader;
params.pixelShader = &pixelShader;
params.layout = &layout;
app::render->CreateShader(params);
vsGlobals = app::render->CreateConstantBuffer(sizeof(VsGlobals));
texEmpty = app::render->CreateImmutableTexture(Int2(1, 1), &Color::White);
vBillboard[0].pos = Vec3(-1, -1, 0);
vBillboard[0].tex = Vec2(0, 0);
vBillboard[0].color = Vec4(1.f, 1.f, 1.f, 1.f);
vBillboard[1].pos = Vec3(-1, 1, 0);
vBillboard[1].tex = Vec2(0, 1);
vBillboard[1].color = Vec4(1.f, 1.f, 1.f, 1.f);
vBillboard[2].pos = Vec3(1, -1, 0);
vBillboard[2].tex = Vec2(1, 0);
vBillboard[2].color = Vec4(1.f, 1.f, 1.f, 1.f);
vBillboard[3] = vBillboard[2];
vBillboard[4] = vBillboard[1];
vBillboard[5].pos = Vec3(1, 1, 0);
vBillboard[5].tex = Vec2(1, 1);
vBillboard[5].color = Vec4(1.f, 1.f, 1.f, 1.f);
billboardExt[0] = Vec3(-1, -1, 0);
billboardExt[1] = Vec3(-1, 1, 0);
billboardExt[2] = Vec3(1, -1, 0);
billboardExt[3] = Vec3(1, -1, 0);
billboardExt[4] = Vec3(-1, 1, 0);
billboardExt[5] = Vec3(1, 1, 0);
}
//=================================================================================================
void ParticleShader::OnRelease()
{
SafeRelease(vertexShader);
SafeRelease(pixelShader);
SafeRelease(layout);
SafeRelease(vsGlobals);
SafeRelease(vb);
SafeRelease(texEmpty);
particleCount = 0;
}
//=================================================================================================
void ParticleShader::Prepare(Camera& camera)
{
matViewInv = camera.mat_view_inv;
camPos = camera.from;
app::render->SetDepthState(Render::DEPTH_READ);
app::render->SetRasterState(Render::RASTER_NO_CULLING);
// setup shader
deviceContext->VSSetShader(vertexShader, nullptr, 0);
deviceContext->VSSetConstantBuffers(0, 1, &vsGlobals);
deviceContext->PSSetShader(pixelShader, nullptr, 0);
ID3D11SamplerState* sampler = app::render->GetSampler();
deviceContext->PSSetSamplers(0, 1, &sampler);
uint stride = sizeof(VParticle), offset = 0;
deviceContext->IASetVertexBuffers(0, 1, &vb, &stride, &offset);
deviceContext->IASetInputLayout(layout);
ReserveVertexBuffer(1);
// vertex shader constants
ResourceLock lock(vsGlobals);
lock.Get<VsGlobals>()->matCombined = camera.mat_view_proj.Transpose();
lastTex = (Texture*)0xFEFEFEFE;
}
//=================================================================================================
void ParticleShader::DrawBillboards(const vector<Billboard>& billboards)
{
app::render->SetBlendState(Render::BLEND_ADD);
for(vector<Billboard>::const_iterator it = billboards.begin(), end = billboards.end(); it != end; ++it)
{
matViewInv._41 = it->pos.x;
matViewInv._42 = it->pos.y;
matViewInv._43 = it->pos.z;
Matrix m1 = Matrix::Scale(it->size) * matViewInv;
for(int i = 0; i < 6; ++i)
vBillboard[i].pos = Vec3::Transform(billboardExt[i], m1);
// fill vertex buffer
{
ResourceLock lock(vb);
memcpy(lock.Get(), vBillboard, sizeof(VParticle) * 6);
}
if(lastTex != it->tex)
{
lastTex = it->tex;
deviceContext->PSSetShaderResources(0, 1, &it->tex->tex);
}
deviceContext->Draw(6, 0);
}
}
//=================================================================================================
void ParticleShader::DrawParticles(const vector<ParticleEmitter*>& pes)
{
for(vector<ParticleEmitter*>::const_iterator it = pes.begin(), end = pes.end(); it != end; ++it)
{
const ParticleEmitter& pe = **it;
ReserveVertexBuffer(pe.alive);
// fill vertex buffer
{
ResourceLock lock(vb);
VParticle* v = lock.Get<VParticle>();
int idx = 0;
for(const ParticleEmitter::Particle& p : pe.particles)
{
if(!p.exists)
continue;
matViewInv._41 = p.pos.x;
matViewInv._42 = p.pos.y;
matViewInv._43 = p.pos.z;
Matrix m1 = Matrix::Scale(pe.GetScale(p)) * matViewInv;
const Vec4 color(1.f, 1.f, 1.f, pe.GetAlpha(p));
v[idx].pos = Vec3::Transform(Vec3(-1, -1, 0), m1);
v[idx].tex = Vec2(0, 0);
v[idx].color = color;
v[idx + 1].pos = Vec3::Transform(Vec3(-1, 1, 0), m1);
v[idx + 1].tex = Vec2(0, 1);
v[idx + 1].color = color;
v[idx + 2].pos = Vec3::Transform(Vec3(1, -1, 0), m1);
v[idx + 2].tex = Vec2(1, 0);
v[idx + 2].color = color;
v[idx + 3] = v[idx + 1];
v[idx + 4].pos = Vec3::Transform(Vec3(1, 1, 0), m1);
v[idx + 4].tex = Vec2(1, 1);
v[idx + 4].color = color;
v[idx + 5] = v[idx + 2];
idx += 6;
}
}
// set blending
app::render->SetBlendState((Render::BlendState)(pe.mode + 1));
// set texture
if(lastTex != pe.tex)
{
lastTex = pe.tex;
deviceContext->PSSetShaderResources(0, 1, &pe.tex->tex);
}
// draw
deviceContext->Draw(pe.alive * 6, 0);
}
}
//=================================================================================================
void ParticleShader::DrawTrailParticles(const vector<TrailParticleEmitter*>& tpes)
{
app::render->SetBlendState(Render::BLEND_ADD_ONE);
for(vector<TrailParticleEmitter*>::const_iterator it = tpes.begin(), end = tpes.end(); it != end; ++it)
{
const TrailParticleEmitter& tp = **it;
if(tp.alive < 2)
continue;
uint count = tp.alive - 1;
ReserveVertexBuffer(count);
// fill vertex buffer
{
int id = tp.first;
const TrailParticleEmitter::Particle* prev = &tp.parts[id];
const float width = tp.width / 2;
id = prev->next;
ResourceLock lock(vb);
VParticle* v = lock.Get<VParticle>();
int idx = 0;
while(id != -1)
{
const TrailParticleEmitter::Particle& p = tp.parts[id];
Vec3 line_dir = p.pt - prev->pt;
Vec3 quad_normal = camPos - (p.pt + prev->pt) / 2;
Vec3 extrude_dir = line_dir.Cross(quad_normal).Normalize();
v[idx].pos = prev->pt + extrude_dir * width;
v[idx + 1].pos = prev->pt - extrude_dir * width;
v[idx + 2].pos = p.pt + extrude_dir * width;
v[idx + 3].pos = p.pt - extrude_dir * width;
v[idx].color = Vec4::Lerp(tp.color1, tp.color2, 1.f - prev->t / tp.fade);
v[idx + 1].color = v[idx].color;
v[idx + 2].color = Vec4::Lerp(tp.color1, tp.color2, 1.f - p.t / tp.fade);
v[idx + 3].color = v[idx + 2].color;
v[idx].tex = Vec2(0, 0);
v[idx + 1].tex = Vec2(0, 1);
v[idx + 2].tex = Vec2(1, 0);
v[idx + 3].tex = Vec2(1, 1);
v[idx + 4] = v[idx + 1];
v[idx + 5] = v[idx + 2];
prev = &p;
id = prev->next;
idx += 6;
}
}
// set texture
if(tp.tex != lastTex)
{
lastTex = tp.tex;
deviceContext->PSSetShaderResources(0, 1, &(lastTex ? lastTex->tex : texEmpty));
}
// draw
deviceContext->Draw(count * 6, 0);
}
}
//=================================================================================================
void ParticleShader::ReserveVertexBuffer(uint count)
{
if(!vb || particleCount < count)
{
if(vb)
vb->Release();
// create vertex buffer
D3D11_BUFFER_DESC bufDesc;
bufDesc.Usage = D3D11_USAGE_DYNAMIC;
bufDesc.ByteWidth = sizeof(VParticle) * 6 * count;
bufDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
bufDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
bufDesc.MiscFlags = 0;
bufDesc.StructureByteStride = 0;
V(app::render->GetDevice()->CreateBuffer(&bufDesc, nullptr, &vb));
SetDebugName(vb, "ParticleVb");
uint stride = sizeof(VParticle),
offset = 0;
deviceContext->IASetVertexBuffers(0, 1, &vb, &stride, &offset);
particleCount = count;
}
}
| 28.100694
| 144
| 0.581367
|
Tomash667
|
1b61edf279ba4a00f86e14591ab629c554c40e1a
| 3,040
|
hpp
|
C++
|
Inception/ChaosCV/include/core/io.hpp
|
zjysnow/ChaosLab
|
2d3a0ee36ab1ac7bd90cd3fc95e9f2e4bc5a622c
|
[
"BSD-3-Clause"
] | 20
|
2018-02-20T03:42:16.000Z
|
2021-05-25T01:03:23.000Z
|
Inception/ChaosCV/include/core/io.hpp
|
zjysnow/ChaosLab
|
2d3a0ee36ab1ac7bd90cd3fc95e9f2e4bc5a622c
|
[
"BSD-3-Clause"
] | 2
|
2020-11-09T14:12:44.000Z
|
2021-10-31T15:11:12.000Z
|
Inception/ChaosCV/include/core/io.hpp
|
zjysnow/ChaosLab
|
2d3a0ee36ab1ac7bd90cd3fc95e9f2e4bc5a622c
|
[
"BSD-3-Clause"
] | 6
|
2019-04-03T03:05:26.000Z
|
2020-11-09T06:08:41.000Z
|
#pragma once
#include "core/types.hpp"
#include "core/array.hpp"
#include "core/tensor.hpp"
#ifdef _WIN32
#include <iostream>
#include <format>
namespace chaos
{
template<class Type = float>
void PrintTensor(std::ostream& stream, const Tensor& tensor)
{
const Shape& shape = tensor.shape;
const Steps& steps = tensor.steps;
const Depth& depth = tensor.depth;
const Packing& packing = tensor.packing;
Type* data = static_cast<Type*>(tensor.data);
stream << "[";
switch (shape.size())
{
case 1:
for (int i = 0; i < steps[0] * shape[0] * packing; i += static_cast<int>(steps[0] * packing))
{
switch (packing)
{
case Packing::CHW:
stream << std::format(", {0}" + 2LL * !i, data[i]);
break;
case Packing::C2HW2:
stream << std::format(", {0} {1}" + 2LL * !i, data[i], data[i + 1]);
break;
case Packing::C3HW3:
stream << std::format(", {0} {1} {2}" + 2LL * !i,
data[i], data[i + 1], data[i + 2]);
break;
case Packing::C4HW4:
stream << std::format(", {0} {1} {2} {3}" + 2LL * !i,
data[i], data[i + 1], data[i + 2], data[i + 3]);
break;
case Packing::C8HW8:
stream << std::format(", {0} {1} {2} {3} {4} {5} {6} {7}" + 2LL * !i,
data[i], data[i + 1], data[i + 2], data[i + 3], data[i + 4], data[i + 5], data[i + 6], data[i + 7]);
break;
default:
LOG(FATAL) << "invalid packing data";
}
}
break;
case 2:
for (int i = 0; i < shape[0]; i++)
{
PrintTensor<Type>(stream, Tensor(shape[-1], depth, packing, data + i * steps[0] * packing, steps[-1]));
if (i < shape[0] - 1) stream << std::endl;
}
break;
case 0:
break;
default:
size_t dims = shape.size();
int h = shape[-2];
int w = shape[-1];
size_t csize = static_cast<size_t>(h) * w;
int estep = steps[-1];
int rstep = steps[-2];
int total = shape.total();
for (size_t i = 0; i < total; i += csize)
{
size_t offset = 0;
size_t idx = i;
for (int d = 1; d <= dims; d++)
{
size_t k = idx % shape[-d];
offset += k * steps[-d];
idx /= shape[-d];
}
PrintTensor<Type>(stream, Tensor(shape.ranges(-2,-1), depth, packing, data + offset * packing, steps.ranges(-2,-1)));
if (i < total - csize) stream << ";" << std::endl;
}
break;
}
stream << "]";
}
//CHAOS_API std::ostream& operator<<(std::ostream& stream, const GPUInfo& info);
//CHAOS_API std::ostream& operator<<(std::ostream& stream, const Depth& depth);
//CHAOS_API std::ostream& operator<<(std::ostream& stream, const Packing& packing);
// just for float or uchar
static std::ostream& operator<<(std::ostream& stream, const Tensor& tensor)
{
switch (tensor.depth)
{
case Depth::D1: // as uchar
PrintTensor<uchar>(stream, tensor);
break;
case Depth::D4:
PrintTensor<float>(stream, tensor);
break;
default:
LOG(FATAL) << "just for float or uchar type";
break;
}
return stream << std::endl << "<Tensor " << tensor.shape << ">";
}
}
#else
namespace chaos
{
}
#endif
| 26.902655
| 121
| 0.566447
|
zjysnow
|
1b6317ca486e9f7eb5d14999052e0256f216d4a7
| 5,559
|
cpp
|
C++
|
src/tree/lpm_cpu_tree.cpp
|
pbosler/lpmKokkos
|
c8b4a8478c08957ce70a6fbd7da00481c53414b9
|
[
"BSD-3-Clause"
] | null | null | null |
src/tree/lpm_cpu_tree.cpp
|
pbosler/lpmKokkos
|
c8b4a8478c08957ce70a6fbd7da00481c53414b9
|
[
"BSD-3-Clause"
] | 18
|
2021-06-27T17:59:03.000Z
|
2022-02-22T03:41:27.000Z
|
src/tree/lpm_cpu_tree.cpp
|
pbosler/lpmKokkos
|
c8b4a8478c08957ce70a6fbd7da00481c53414b9
|
[
"BSD-3-Clause"
] | null | null | null |
#include "tree/lpm_cpu_tree.hpp"
#include "lpm_assert.hpp"
#ifdef LPM_USE_VTK
#include "vtkPolyData.h"
#include "vtkVoxel.h"
#include "vtkCellData.h"
#include "vtkXMLPolyDataWriter.h"
#endif
#include <numeric>
#include <limits>
namespace Lpm {
namespace tree {
template <typename Geo>
CpuTree<Geo>::CpuTree(const std::shared_ptr<Coords<Geo>> crds) :
_crds(crds),
depth(0),
n_nodes(1) {
const auto xminmax = crds->min_max_extent(0);
const auto yminmax = crds->min_max_extent(1);
const auto zminmax = crds->min_max_extent(2);
Box3d root_box(xminmax.min_val, xminmax.max_val,
yminmax.min_val, yminmax.max_val,
zminmax.min_val, zminmax.max_val);
std::vector<Index> root_inds(crds->nh());
std::iota(root_inds.begin(), root_inds.end(), 0);
root = std::unique_ptr<Node>(new Node(root_box, NULL, root_inds));
LPM_ASSERT(root->is_leaf());
LPM_ASSERT(!root->has_kids());
LPM_ASSERT(root->n() == crds.size());
}
template <typename Geo>
void CpuTree<Geo>::shrink_box(Node* node) {
Real xmin = std::numeric_limits<Real>::max();
Real xmax = std::numeric_limits<Real>::lowest();
Real ymin = xmin;
Real ymax = xmax;
Real zmin = xmin;
Real zmax = xmax;
const auto crd_view = _crds->get_host_crd_view();
for (Index i=0; i<node->n(); ++i) {
const auto cxyz = Kokkos::subview(crd_view, i, Kokkos::ALL);
if (cxyz[0] < xmin) xmin = cxyz[0];
if (cxyz[1] < ymin) ymin = cxyz[1];
if (cxyz[2] < zmin) zmin = cxyz[2];
if (cxyz[0] > xmax) xmax = cxyz[0];
if (cxyz[1] > ymax) ymax = cxyz[1];
if (cxyz[2] > zmax) zmax = cxyz[2];
}
node->box.xmin = xmin;
node->box.xmax = xmax;
node->box.ymin = ymin;
node->box.ymax = ymax;
node->box.zmin = zmin;
node->box.zmax = zmax;
}
template <typename Geo>
void CpuTree<Geo>::divide_node(Node* node, const bool do_shrink) {
LPM_ASSERT(!node->empty());
const auto kid_boxes = node->box.bisect_all();
auto counted = std::vector<bool>(node->n(), false);
const auto crd_view = _crds->get_host_crd_view();
int empty_count = 0;
int full_count = 0;
for (int k=0; k<8; ++k) {
std::vector<Index> kid_inds;
for (int i=0; i<node->n(); ++i) {
const auto cxyz = Kokkos::subview(crd_view, i, Kokkos::ALL);
if (kid_boxes[k].contains_pt(cxyz)) {
if (!counted[i]) {
kid_inds.push_back(i);
counted[i] = true;
}
}
}
if (kid_inds.empty()) {
++empty_count;
}
else {
++full_count;
kid_inds.shrink_to_fit();
}
node->kids.push_back(std::unique_ptr<Node>(
new Node(kid_boxes[k], node, kid_inds)));
}
LPM_ASSERT(node->has_kids());
LPM_ASSERT(full_count + empty_count == 8);
LPM_ASSERT(full_count > 0);
n_nodes += full_count;
if (do_shrink) {
for (int k=0; k<8; ++k) {
if (!node->kids[k]->empty()) {
shrink_box(node->kids[k].get());
}
}
}
}
template <typename Geo>
void CpuTree<Geo>::generate_tree_max_coords_per_node(Node* node,
const Index max_coords_per_node, const bool do_shrink) {
if (node->n() <= max_coords_per_node or node->empty()) {
return;
}
else {
divide_node(node, do_shrink);
for (int k=0; k<8; ++k) {
generate_tree_max_coords_per_node(node->kids[k].get(),
max_coords_per_node, do_shrink);
}
}
}
template <typename Geo>
void CpuTree<Geo>::generate_tree_max_depth(Node* node, const int max_depth,
const bool do_shrink) {
if (node->level == max_depth or node->empty()) {
return;
}
else {
divide_node(node, do_shrink);
for (int k=0; k<8; ++k) {
generate_tree_max_depth(node->kids[k].get(), max_depth, do_shrink);
}
}
}
#ifdef LPM_USE_VTK
template <typename Geo>
void CpuTree<Geo>::insert_vtk_cell_points(
vtkSmartPointer<vtkPoints> pts, const Index pt_offset,
vtkSmartPointer<vtkCellArray> cells, const Index cell_offset,
vtkSmartPointer<vtkIntArray> levels, const Node* node) {
const auto box = node->box;
pts->InsertNextPoint(box.xmin,box.ymin, box.zmin);
pts->InsertNextPoint(box.xmax,box.ymin, box.zmin);
pts->InsertNextPoint(box.xmin,box.ymax, box.zmin);
pts->InsertNextPoint(box.xmax,box.ymax, box.zmin);
pts->InsertNextPoint(box.xmin,box.ymin, box.zmax);
pts->InsertNextPoint(box.xmax,box.ymin, box.zmax);
pts->InsertNextPoint(box.xmin,box.ymax, box.zmax);
pts->InsertNextPoint(box.xmax,box.ymax, box.zmax);
cells->InsertNextCell(8);
for (int k=0; k<8; ++k) {
cells->InsertCellPoint(pt_offset + k);
}
levels->InsertTuple1(cell_offset+1, node->level);
if (node->has_kids()) {
for (int k=0; k<8; ++k) {
if (!node->kids[k]->empty()) {
insert_vtk_cell_points(pts, pt_offset+8*(k+1), cells, cell_offset+k+1, levels,
node->kids[k].get());
}
}
}
}
template <typename Geo>
void CpuTree<Geo>::write_vtk(const std::string& ofname) const {
auto pts = vtkSmartPointer<vtkPoints>::New();
auto cells = vtkSmartPointer<vtkCellArray>::New();
auto levels = vtkSmartPointer<vtkIntArray>::New();
levels->SetName("tree_level");
levels->SetNumberOfComponents(1);
levels->SetNumberOfTuples(n_nodes);
insert_vtk_cell_points(pts, 0, cells, 0, levels, root);
auto polydata = vtkSmartPointer<vtkPolyData>::New();
polydata->SetPoints(pts);
polydata->SetPolys(cells);
polydata->GetCellData()->AddArray(levels);
auto writer = vtkSmartPointer<vtkXMLPolyDataWriter>::New();
writer->SetInputData(polydata);
writer->SetFileName(ofname.c_str());
writer->Write();
}
#endif
} // namespace tree
} // namespace Lpm
| 28.953125
| 86
| 0.653355
|
pbosler
|
1b66705dbae3fe08c47f698a767b62cb6863442f
| 349
|
cpp
|
C++
|
LeetCode/Array/remove-element.cpp
|
vasanth9/coding-universe
|
69ffcb58af0c163689ab9893e6d1e0581e0247e0
|
[
"MIT"
] | null | null | null |
LeetCode/Array/remove-element.cpp
|
vasanth9/coding-universe
|
69ffcb58af0c163689ab9893e6d1e0581e0247e0
|
[
"MIT"
] | null | null | null |
LeetCode/Array/remove-element.cpp
|
vasanth9/coding-universe
|
69ffcb58af0c163689ab9893e6d1e0581e0247e0
|
[
"MIT"
] | null | null | null |
//leetcode.com/problems/remove-element
#include<bits/stdc++.h>
using namespace std;
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int k=0,n=nums.size();
for(int i=0;i<n;i++){
if(nums[i]!=val){
nums[k]=nums[i];
k++;
}
}
return k;
}
};
| 20.529412
| 51
| 0.492837
|
vasanth9
|
1b6683bd18dd2d67f5014993369d098972711774
| 18,237
|
hpp
|
C++
|
include/RootMotion/FinalIK/AimController.hpp
|
Fernthedev/BeatSaber-Quest-Codegen
|
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
|
[
"Unlicense"
] | null | null | null |
include/RootMotion/FinalIK/AimController.hpp
|
Fernthedev/BeatSaber-Quest-Codegen
|
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
|
[
"Unlicense"
] | null | null | null |
include/RootMotion/FinalIK/AimController.hpp
|
Fernthedev/BeatSaber-Quest-Codegen
|
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
|
[
"Unlicense"
] | null | null | null |
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
#include "extern/beatsaber-hook/shared/utils/byref.hpp"
// Including type: UnityEngine.MonoBehaviour
#include "UnityEngine/MonoBehaviour.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: RootMotion::FinalIK
namespace RootMotion::FinalIK {
// Forward declaring type: AimIK
class AimIK;
}
// Forward declaring namespace: UnityEngine
namespace UnityEngine {
// Forward declaring type: Transform
class Transform;
}
// Forward declaring namespace: System::Collections
namespace System::Collections {
// Forward declaring type: IEnumerator
class IEnumerator;
}
// Completed forward declares
// Type namespace: RootMotion.FinalIK
namespace RootMotion::FinalIK {
// Size: 0xB8
#pragma pack(push, 1)
// Autogenerated type: RootMotion.FinalIK.AimController
// [TokenAttribute] Offset: FFFFFFFF
class AimController : public UnityEngine::MonoBehaviour {
public:
// Nested type: RootMotion::FinalIK::AimController::$TurnToTarget$d__33
class $TurnToTarget$d__33;
// [TooltipAttribute] Offset: 0xE2D830
// public RootMotion.FinalIK.AimIK ik
// Size: 0x8
// Offset: 0x18
RootMotion::FinalIK::AimIK* ik;
// Field size check
static_assert(sizeof(RootMotion::FinalIK::AimIK*) == 0x8);
// [TooltipAttribute] Offset: 0xE2D868
// [RangeAttribute] Offset: 0xE2D868
// public System.Single weight
// Size: 0x4
// Offset: 0x20
float weight;
// Field size check
static_assert(sizeof(float) == 0x4);
// Padding between fields: weight and: target
char __padding1[0x4] = {};
// [HeaderAttribute] Offset: 0xE2D8BC
// [TooltipAttribute] Offset: 0xE2D8BC
// public UnityEngine.Transform target
// Size: 0x8
// Offset: 0x28
UnityEngine::Transform* target;
// Field size check
static_assert(sizeof(UnityEngine::Transform*) == 0x8);
// [TooltipAttribute] Offset: 0xE2D91C
// public System.Single targetSwitchSmoothTime
// Size: 0x4
// Offset: 0x30
float targetSwitchSmoothTime;
// Field size check
static_assert(sizeof(float) == 0x4);
// [TooltipAttribute] Offset: 0xE2D954
// public System.Single weightSmoothTime
// Size: 0x4
// Offset: 0x34
float weightSmoothTime;
// Field size check
static_assert(sizeof(float) == 0x4);
// [HeaderAttribute] Offset: 0xE2D98C
// [TooltipAttribute] Offset: 0xE2D98C
// public System.Boolean smoothTurnTowardsTarget
// Size: 0x1
// Offset: 0x38
bool smoothTurnTowardsTarget;
// Field size check
static_assert(sizeof(bool) == 0x1);
// Padding between fields: smoothTurnTowardsTarget and: maxRadiansDelta
char __padding5[0x3] = {};
// [TooltipAttribute] Offset: 0xE2D9EC
// public System.Single maxRadiansDelta
// Size: 0x4
// Offset: 0x3C
float maxRadiansDelta;
// Field size check
static_assert(sizeof(float) == 0x4);
// [TooltipAttribute] Offset: 0xE2DA24
// public System.Single maxMagnitudeDelta
// Size: 0x4
// Offset: 0x40
float maxMagnitudeDelta;
// Field size check
static_assert(sizeof(float) == 0x4);
// [TooltipAttribute] Offset: 0xE2DA5C
// public System.Single slerpSpeed
// Size: 0x4
// Offset: 0x44
float slerpSpeed;
// Field size check
static_assert(sizeof(float) == 0x4);
// [TooltipAttribute] Offset: 0xE2DA94
// public UnityEngine.Vector3 pivotOffsetFromRoot
// Size: 0xC
// Offset: 0x48
UnityEngine::Vector3 pivotOffsetFromRoot;
// Field size check
static_assert(sizeof(UnityEngine::Vector3) == 0xC);
// [TooltipAttribute] Offset: 0xE2DACC
// public System.Single minDistance
// Size: 0x4
// Offset: 0x54
float minDistance;
// Field size check
static_assert(sizeof(float) == 0x4);
// [TooltipAttribute] Offset: 0xE2DB04
// public UnityEngine.Vector3 offset
// Size: 0xC
// Offset: 0x58
UnityEngine::Vector3 offset;
// Field size check
static_assert(sizeof(UnityEngine::Vector3) == 0xC);
// [HeaderAttribute] Offset: 0xE2DB3C
// [TooltipAttribute] Offset: 0xE2DB3C
// [RangeAttribute] Offset: 0xE2DB3C
// public System.Single maxRootAngle
// Size: 0x4
// Offset: 0x64
float maxRootAngle;
// Field size check
static_assert(sizeof(float) == 0x4);
// [TooltipAttribute] Offset: 0xE2DBB8
// public System.Boolean turnToTarget
// Size: 0x1
// Offset: 0x68
bool turnToTarget;
// Field size check
static_assert(sizeof(bool) == 0x1);
// Padding between fields: turnToTarget and: turnToTargetTime
char __padding13[0x3] = {};
// [TooltipAttribute] Offset: 0xE2DBF0
// public System.Single turnToTargetTime
// Size: 0x4
// Offset: 0x6C
float turnToTargetTime;
// Field size check
static_assert(sizeof(float) == 0x4);
// [HeaderAttribute] Offset: 0xE2DC28
// [TooltipAttribute] Offset: 0xE2DC28
// public System.Boolean useAnimatedAimDirection
// Size: 0x1
// Offset: 0x70
bool useAnimatedAimDirection;
// Field size check
static_assert(sizeof(bool) == 0x1);
// Padding between fields: useAnimatedAimDirection and: animatedAimDirection
char __padding15[0x3] = {};
// [TooltipAttribute] Offset: 0xE2DC88
// public UnityEngine.Vector3 animatedAimDirection
// Size: 0xC
// Offset: 0x74
UnityEngine::Vector3 animatedAimDirection;
// Field size check
static_assert(sizeof(UnityEngine::Vector3) == 0xC);
// private UnityEngine.Transform lastTarget
// Size: 0x8
// Offset: 0x80
UnityEngine::Transform* lastTarget;
// Field size check
static_assert(sizeof(UnityEngine::Transform*) == 0x8);
// private System.Single switchWeight
// Size: 0x4
// Offset: 0x88
float switchWeight;
// Field size check
static_assert(sizeof(float) == 0x4);
// private System.Single switchWeightV
// Size: 0x4
// Offset: 0x8C
float switchWeightV;
// Field size check
static_assert(sizeof(float) == 0x4);
// private System.Single weightV
// Size: 0x4
// Offset: 0x90
float weightV;
// Field size check
static_assert(sizeof(float) == 0x4);
// private UnityEngine.Vector3 lastPosition
// Size: 0xC
// Offset: 0x94
UnityEngine::Vector3 lastPosition;
// Field size check
static_assert(sizeof(UnityEngine::Vector3) == 0xC);
// private UnityEngine.Vector3 dir
// Size: 0xC
// Offset: 0xA0
UnityEngine::Vector3 dir;
// Field size check
static_assert(sizeof(UnityEngine::Vector3) == 0xC);
// private System.Boolean lastSmoothTowardsTarget
// Size: 0x1
// Offset: 0xAC
bool lastSmoothTowardsTarget;
// Field size check
static_assert(sizeof(bool) == 0x1);
// private System.Boolean turningToTarget
// Size: 0x1
// Offset: 0xAD
bool turningToTarget;
// Field size check
static_assert(sizeof(bool) == 0x1);
// Padding between fields: turningToTarget and: turnToTargetMlp
char __padding24[0x2] = {};
// private System.Single turnToTargetMlp
// Size: 0x4
// Offset: 0xB0
float turnToTargetMlp;
// Field size check
static_assert(sizeof(float) == 0x4);
// private System.Single turnToTargetMlpV
// Size: 0x4
// Offset: 0xB4
float turnToTargetMlpV;
// Field size check
static_assert(sizeof(float) == 0x4);
// Creating value type constructor for type: AimController
AimController(RootMotion::FinalIK::AimIK* ik_ = {}, float weight_ = {}, UnityEngine::Transform* target_ = {}, float targetSwitchSmoothTime_ = {}, float weightSmoothTime_ = {}, bool smoothTurnTowardsTarget_ = {}, float maxRadiansDelta_ = {}, float maxMagnitudeDelta_ = {}, float slerpSpeed_ = {}, UnityEngine::Vector3 pivotOffsetFromRoot_ = {}, float minDistance_ = {}, UnityEngine::Vector3 offset_ = {}, float maxRootAngle_ = {}, bool turnToTarget_ = {}, float turnToTargetTime_ = {}, bool useAnimatedAimDirection_ = {}, UnityEngine::Vector3 animatedAimDirection_ = {}, UnityEngine::Transform* lastTarget_ = {}, float switchWeight_ = {}, float switchWeightV_ = {}, float weightV_ = {}, UnityEngine::Vector3 lastPosition_ = {}, UnityEngine::Vector3 dir_ = {}, bool lastSmoothTowardsTarget_ = {}, bool turningToTarget_ = {}, float turnToTargetMlp_ = {}, float turnToTargetMlpV_ = {}) noexcept : ik{ik_}, weight{weight_}, target{target_}, targetSwitchSmoothTime{targetSwitchSmoothTime_}, weightSmoothTime{weightSmoothTime_}, smoothTurnTowardsTarget{smoothTurnTowardsTarget_}, maxRadiansDelta{maxRadiansDelta_}, maxMagnitudeDelta{maxMagnitudeDelta_}, slerpSpeed{slerpSpeed_}, pivotOffsetFromRoot{pivotOffsetFromRoot_}, minDistance{minDistance_}, offset{offset_}, maxRootAngle{maxRootAngle_}, turnToTarget{turnToTarget_}, turnToTargetTime{turnToTargetTime_}, useAnimatedAimDirection{useAnimatedAimDirection_}, animatedAimDirection{animatedAimDirection_}, lastTarget{lastTarget_}, switchWeight{switchWeight_}, switchWeightV{switchWeightV_}, weightV{weightV_}, lastPosition{lastPosition_}, dir{dir_}, lastSmoothTowardsTarget{lastSmoothTowardsTarget_}, turningToTarget{turningToTarget_}, turnToTargetMlp{turnToTargetMlp_}, turnToTargetMlpV{turnToTargetMlpV_} {}
// Deleting conversion operator: operator System::IntPtr
constexpr operator System::IntPtr() const noexcept = delete;
// Get instance field reference: public RootMotion.FinalIK.AimIK ik
RootMotion::FinalIK::AimIK*& dyn_ik();
// Get instance field reference: public System.Single weight
float& dyn_weight();
// Get instance field reference: public UnityEngine.Transform target
UnityEngine::Transform*& dyn_target();
// Get instance field reference: public System.Single targetSwitchSmoothTime
float& dyn_targetSwitchSmoothTime();
// Get instance field reference: public System.Single weightSmoothTime
float& dyn_weightSmoothTime();
// Get instance field reference: public System.Boolean smoothTurnTowardsTarget
bool& dyn_smoothTurnTowardsTarget();
// Get instance field reference: public System.Single maxRadiansDelta
float& dyn_maxRadiansDelta();
// Get instance field reference: public System.Single maxMagnitudeDelta
float& dyn_maxMagnitudeDelta();
// Get instance field reference: public System.Single slerpSpeed
float& dyn_slerpSpeed();
// Get instance field reference: public UnityEngine.Vector3 pivotOffsetFromRoot
UnityEngine::Vector3& dyn_pivotOffsetFromRoot();
// Get instance field reference: public System.Single minDistance
float& dyn_minDistance();
// Get instance field reference: public UnityEngine.Vector3 offset
UnityEngine::Vector3& dyn_offset();
// Get instance field reference: public System.Single maxRootAngle
float& dyn_maxRootAngle();
// Get instance field reference: public System.Boolean turnToTarget
bool& dyn_turnToTarget();
// Get instance field reference: public System.Single turnToTargetTime
float& dyn_turnToTargetTime();
// Get instance field reference: public System.Boolean useAnimatedAimDirection
bool& dyn_useAnimatedAimDirection();
// Get instance field reference: public UnityEngine.Vector3 animatedAimDirection
UnityEngine::Vector3& dyn_animatedAimDirection();
// Get instance field reference: private UnityEngine.Transform lastTarget
UnityEngine::Transform*& dyn_lastTarget();
// Get instance field reference: private System.Single switchWeight
float& dyn_switchWeight();
// Get instance field reference: private System.Single switchWeightV
float& dyn_switchWeightV();
// Get instance field reference: private System.Single weightV
float& dyn_weightV();
// Get instance field reference: private UnityEngine.Vector3 lastPosition
UnityEngine::Vector3& dyn_lastPosition();
// Get instance field reference: private UnityEngine.Vector3 dir
UnityEngine::Vector3& dyn_dir();
// Get instance field reference: private System.Boolean lastSmoothTowardsTarget
bool& dyn_lastSmoothTowardsTarget();
// Get instance field reference: private System.Boolean turningToTarget
bool& dyn_turningToTarget();
// Get instance field reference: private System.Single turnToTargetMlp
float& dyn_turnToTargetMlp();
// Get instance field reference: private System.Single turnToTargetMlpV
float& dyn_turnToTargetMlpV();
// private UnityEngine.Vector3 get_pivot()
// Offset: 0x1D30A80
UnityEngine::Vector3 get_pivot();
// private System.Void Start()
// Offset: 0x1D30984
void Start();
// private System.Void LateUpdate()
// Offset: 0x1D30BCC
void LateUpdate();
// private System.Void ApplyMinDistance()
// Offset: 0x1D31304
void ApplyMinDistance();
// private System.Void RootRotation()
// Offset: 0x1D314A0
void RootRotation();
// private System.Collections.IEnumerator TurnToTarget()
// Offset: 0x1D31810
System::Collections::IEnumerator* TurnToTarget();
// public System.Void .ctor()
// Offset: 0x1D318AC
// Implemented from: UnityEngine.MonoBehaviour
// Base method: System.Void MonoBehaviour::.ctor()
// Base method: System.Void Behaviour::.ctor()
// Base method: System.Void Component::.ctor()
// Base method: System.Void Object::.ctor()
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static AimController* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("RootMotion::FinalIK::AimController::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<AimController*, creationType>()));
}
}; // RootMotion.FinalIK.AimController
#pragma pack(pop)
static check_size<sizeof(AimController), 180 + sizeof(float)> __RootMotion_FinalIK_AimControllerSizeCheck;
static_assert(sizeof(AimController) == 0xB8);
}
DEFINE_IL2CPP_ARG_TYPE(RootMotion::FinalIK::AimController*, "RootMotion.FinalIK", "AimController");
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: RootMotion::FinalIK::AimController::get_pivot
// Il2CppName: get_pivot
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<UnityEngine::Vector3 (RootMotion::FinalIK::AimController::*)()>(&RootMotion::FinalIK::AimController::get_pivot)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(RootMotion::FinalIK::AimController*), "get_pivot", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: RootMotion::FinalIK::AimController::Start
// Il2CppName: Start
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (RootMotion::FinalIK::AimController::*)()>(&RootMotion::FinalIK::AimController::Start)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(RootMotion::FinalIK::AimController*), "Start", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: RootMotion::FinalIK::AimController::LateUpdate
// Il2CppName: LateUpdate
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (RootMotion::FinalIK::AimController::*)()>(&RootMotion::FinalIK::AimController::LateUpdate)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(RootMotion::FinalIK::AimController*), "LateUpdate", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: RootMotion::FinalIK::AimController::ApplyMinDistance
// Il2CppName: ApplyMinDistance
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (RootMotion::FinalIK::AimController::*)()>(&RootMotion::FinalIK::AimController::ApplyMinDistance)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(RootMotion::FinalIK::AimController*), "ApplyMinDistance", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: RootMotion::FinalIK::AimController::RootRotation
// Il2CppName: RootRotation
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (RootMotion::FinalIK::AimController::*)()>(&RootMotion::FinalIK::AimController::RootRotation)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(RootMotion::FinalIK::AimController*), "RootRotation", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: RootMotion::FinalIK::AimController::TurnToTarget
// Il2CppName: TurnToTarget
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::Collections::IEnumerator* (RootMotion::FinalIK::AimController::*)()>(&RootMotion::FinalIK::AimController::TurnToTarget)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(RootMotion::FinalIK::AimController*), "TurnToTarget", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: RootMotion::FinalIK::AimController::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
| 47.368831
| 1,758
| 0.706531
|
Fernthedev
|
1b672c46a17422d9df3d1eb4f0879f8ca381ce36
| 9,111
|
cpp
|
C++
|
src/AudioEffectDelay_f32.cpp
|
UTSAAH/Dhwani-HA_Library
|
f182d8b6571d48b1e506637684844eb12e0a791c
|
[
"MIT"
] | null | null | null |
src/AudioEffectDelay_f32.cpp
|
UTSAAH/Dhwani-HA_Library
|
f182d8b6571d48b1e506637684844eb12e0a791c
|
[
"MIT"
] | null | null | null |
src/AudioEffectDelay_f32.cpp
|
UTSAAH/Dhwani-HA_Library
|
f182d8b6571d48b1e506637684844eb12e0a791c
|
[
"MIT"
] | null | null | null |
/* Audio Library for Teensy 3.X
* Copyright (c) 2014, Paul Stoffregen, paul@pjrc.com
* Extended by Chip Audette, Open Audio, April 2018
*
* Development of this audio library was funded by PJRC.COM, LLC by sales of
* Teensy and Audio Adaptor boards. Please support PJRC's efforts to develop
* open source software by purchasing Teensy or other PJRC products.
*
* 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, development funding 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 <Arduino.h>
#include "AudioEffectDelay_f32.h"
void AudioEffectDelay_F32::update(void)
{
//Serial.println("AudioEffectDelay_F32: update()...");
receiveIncomingData(); //put the in-coming audio data into the queue
discardUnneededBlocksFromQueue(); //clear out queued data this is no longer needed
transmitOutgoingData(); //put the queued data into the output
return;
}
void AudioEffectDelay_F32::receiveIncomingData(void) {
//Serial.println("AudioEffectDelay_F32::receiveIncomingData: starting...");
//prepare the receiving queue
uint16_t head = headindex; //what block to write to
uint16_t tail = tailindex; //what block to read from
if (queue[head] == NULL) {
//if (!Serial) Serial.println("AudioEffectDelay_F32::receiveIncomingData: Allocating queue[head].");
queue[head] = allocate_f32();
if (queue[head] == NULL) {
//if (!Serial) Serial.println("AudioEffectDelay_F32::receiveIncomingData: Null memory 1. Returning.");
return;
}
}
//prepare target memory nto which we'll copy the incoming data into the queue
int dest_ind = writeposition; //inclusive
if (dest_ind >= (queue[head]->full_length)) {
head++; dest_ind = 0;
if (head >= DELAY_QUEUE_SIZE) head = 0;
if (queue[head] != NULL) {
if (head==tail) {tail++; if (tail >= DELAY_QUEUE_SIZE) tail = 0; }
AudioStream_F32::release(queue[head]);
queue[head]=NULL;
}
}
if (queue[head]==NULL) {
queue[head] = allocate_f32();
if (queue[head] == NULL) {
if (!Serial) Serial.println("AudioEffectDelay_F32::receiveIncomingData: Null memory 2. Returning.");
return;
}
}
//receive the in-coming audio data block
audio_block_f32_t *input = receiveReadOnly_f32();
if (input == NULL) {
//if (!Serial) Serial.println("AudioEffectDelay_F32::receiveIncomingData: Input data is NULL. Returning.");
return;
}
int n_copy = input->length;
last_received_block_id = input->id;
// Now we'll loop over the individual samples of the in-coming data
float32_t *dest = queue[head]->data;
float32_t *source = input->data;
int end_write = dest_ind + n_copy; //this may go past the end of the destination array
int end_loop = min(end_write,(int)(queue[head]->full_length)); //limit to the end of the array
int src_count=0, dest_count=dest_ind;
for (int i=dest_ind; i<end_loop; i++) dest[dest_count++] = source[src_count++];
//finish writing taking data from the next queue buffer
if (src_count < n_copy) { // there's still more input data to copy...but we need to roll-over to a new input queue
head++; dest_ind = 0;
if (head >= DELAY_QUEUE_SIZE) head = 0;
if (queue[head] != NULL) {
if (head==tail) {tail++; if (tail >= DELAY_QUEUE_SIZE) tail = 0; }
AudioStream_F32::release(queue[head]);
queue[head]=NULL;
}
if (queue[head]==NULL) {
queue[head] = allocate_f32();
if (queue[head] == NULL) {
Serial.println("AudioEffectDelay_F32::receiveIncomingData: Null memory 3. Returning.");
AudioStream_F32::release(input);
return;
}
}
float32_t *dest = queue[head]->data;
end_loop = end_write - (queue[head]->full_length);
dest_count = dest_ind;
for (int i=dest_ind; i < end_loop; i++) dest[dest_count++]=source[src_count++];
}
AudioStream_F32::release(input);
writeposition = dest_count;
headindex = head;
tailindex = tail;
return;
}
void AudioEffectDelay_F32::discardUnneededBlocksFromQueue(void) {
uint16_t head = headindex; //what block to write to
uint16_t tail = tailindex; //last useful block of data
uint32_t count;
// discard unneeded blocks from the queue
if (head >= tail) {
count = head - tail;
} else {
count = DELAY_QUEUE_SIZE + head - tail;
}
/* if (head>0) {
Serial.print("AudioEffectDelay_F32::discardUnneededBlocksFromQueue: head, tail, count, maxblocks, DELAY_QUEUE_SIZE: ");
Serial.print(head); Serial.print(", ");
Serial.print(tail); Serial.print(", ");
Serial.print(count); Serial.print(", ");
Serial.print(maxblocks); Serial.print(", ");
Serial.print(DELAY_QUEUE_SIZE); Serial.print(", ");
Serial.println();
} */
if (count > maxblocks) {
count -= maxblocks;
do {
if (queue[tail] != NULL) {
AudioStream_F32::release(queue[tail]);
queue[tail] = NULL;
}
if (++tail >= DELAY_QUEUE_SIZE) tail = 0;
} while (--count > 0);
}
tailindex = tail;
}
void AudioEffectDelay_F32::transmitOutgoingData(void) {
uint16_t head = headindex; //what block to write to
//uint16_t tail = tailindex; //last useful block of data
audio_block_f32_t *output;
int channel; //, index, prev, offset;
//const float32_t *src, *end;
//float32_t *dst;
// transmit the delayed outputs using queue data
for (channel = 0; channel < 8; channel++) {
if (!(activemask & (1<<channel))) continue;
output = allocate_f32();
if (!output) continue;
//figure out where to start pulling the data samples from
uint32_t ref_samp_long = (head*AUDIO_BLOCK_SIZE_F32) + writeposition; //note that writepoisition has already been
//incremented by the block length by the
//receiveIncomingData method. We'll adjust it next
uint32_t offset_samp = delay_samps[channel]+output->length;
if (ref_samp_long < offset_samp) { //when (ref_samp_long - offset_samp) goes negative, the uint32_t will fail, so we do this logic check
ref_samp_long = ref_samp_long + (((uint32_t)(DELAY_QUEUE_SIZE))*((uint32_t)AUDIO_BLOCK_SIZE_F32));
}
ref_samp_long = ref_samp_long - offset_samp;
uint16_t source_queue_ind = (uint16_t)(ref_samp_long / ((uint32_t)AUDIO_BLOCK_SIZE_F32));
int source_samp = (int)(ref_samp_long - (((uint32_t)source_queue_ind)*((uint32_t)AUDIO_BLOCK_SIZE_F32)));
//pull the data from the first source data block
int dest_counter=0;
int n_output = output->length;
float32_t *dest = output->data;
audio_block_f32_t *source_block = queue[source_queue_ind];
if (source_block == NULL) {
//fill destination with zeros for this source block
int Iend = min(source_samp+n_output,AUDIO_BLOCK_SIZE_F32);
for (int Isource = source_samp; Isource < Iend; Isource++) {
dest[dest_counter++]=0.0;
}
} else {
//fill destination with this source block's values
float32_t *source = source_block->data;
int Iend = min(source_samp+n_output,AUDIO_BLOCK_SIZE_F32);
for (int Isource = source_samp; Isource < Iend; Isource++) {
dest[dest_counter++]=source[Isource];
}
}
//pull the data from the second source data block, if needed
if (dest_counter < n_output) {
//yes, we need to keep filling the output
int Iend = n_output - dest_counter; //how many more data points do we need
source_queue_ind++; source_samp = 0; //which source block will we draw from (and reset the source sample counter)
if (source_queue_ind >= DELAY_QUEUE_SIZE) source_queue_ind = 0; //wrap around on our source black.
source_block = queue[source_queue_ind]; //get the source block
if (source_block == NULL) { //does it have data?
//no, it doesn't have data. fill destination with zeros
for (int Isource = source_samp; Isource < Iend; Isource++) {
dest[dest_counter++] = 0.0;
}
} else {
//source block does have data. use this block's values
float32_t *source = source_block->data;
for (int Isource = source_samp; Isource < Iend; Isource++) {
dest[dest_counter++]=source[Isource];
}
}
}
//add the id of the last received audio block
output->id = last_received_block_id;
//transmit and release
AudioStream_F32::transmit(output, channel);
AudioStream_F32::release(output);
}
}
| 37.804979
| 138
| 0.699155
|
UTSAAH
|
1b68bd9ab2aa2e53724f1c88e9600b48360b1d62
| 2,581
|
cpp
|
C++
|
InjectorTemplate/Main.cpp
|
JuniorDjjr/InjectorTemplate
|
3f9f50a297750a299c4ef374c07cf0fa13d6b60f
|
[
"MIT"
] | 3
|
2020-01-25T18:53:15.000Z
|
2022-03-23T09:24:43.000Z
|
InjectorTemplate/Main.cpp
|
JuniorDjjr/InjectorTemplate
|
3f9f50a297750a299c4ef374c07cf0fa13d6b60f
|
[
"MIT"
] | null | null | null |
InjectorTemplate/Main.cpp
|
JuniorDjjr/InjectorTemplate
|
3f9f50a297750a299c4ef374c07cf0fa13d6b60f
|
[
"MIT"
] | 1
|
2021-11-18T16:48:26.000Z
|
2021-11-18T16:48:26.000Z
|
/*
The base of this code is from InjectorTemplate by Junior_Djjr - MixMods.com.br
*/
#include "stdafx.h"
#include "IniReader/IniReader.h"
#include "ReadIniCustom.h"
#include "injector/injector.hpp"
#include "injector/assembly.hpp"
#include "PatchStuff.h"
#include "GameStuff.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace injector;
using namespace std;
string const projectName = TARGET_NAME; // Set the name on your project properties
int const BUILD_NUMBER = 1;
enum gameVersion
{
VERSION_UNKNOWN,
VERSION_A
};
gameVersion version;
gameVersion GetGameVersion()
{
switch (injector::ReadMemory<uint32_t>(0xDEADC0DE, true))
{
case 0x12345678:
//MessageBoxA(0, "VERSION_A", "Game version", 0);
return VERSION_A;
default:
//MessageBoxA(0, "VERSION_UNKNOWN", "Game version", 0);
return VERSION_UNKNOWN;
}
}
BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
version = GetGameVersion();
if (version != VERSION_UNKNOWN) Init();
else MessageBoxA(0, "Incompatible game version.", "Error", 0);
break;
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
fstream lg;
///////////////////////////////////////////////////////////////////////////////////////////////////
uintptr_t gameProcessingOriginalCall;
void GameProcessing()
{
lg << "Game processing." << endl;
lg.flush();
SimpleCall(gameProcessingOriginalCall);
}
///////////////////////////////////////////////////////////////////////////////////////////////////
void ReadIni()
{
int i;
float f;
CIniReader ini(projectName + ".ini");
if (ini.data.size() <= 0) { lg << projectName << ".ini NOT FOUND\n"; lg.flush(); return; }
if (ReadIniInt(ini, &lg, "Settings", "ExampleInt", &i)) {
WriteMemory<uint32_t>(0xDEADC0DE, i, true);
}
lg.flush();
}
///////////////////////////////////////////////////////////////////////////////////////////////////
void Init()
{
lg.open(projectName + ".log", std::fstream::out | std::fstream::trunc);
lg << "Build " << BUILD_NUMBER << endl;
lg.flush();
uintptr_t address;
switch (version)
{
case VERSION_A:
address = 0xDEADC0DE;
break;
default:
return;
}
SimpleHookCallStoreOriginal(address, GameProcessing, &gameProcessingOriginalCall);
ReadIni();
}
///////////////////////////////////////////////////////////////////////////////////////////////////
| 23.044643
| 100
| 0.573034
|
JuniorDjjr
|
1b6993a4c77f7287c7bb89337fbb3c8b497de676
| 1,453
|
hpp
|
C++
|
Include/Firefly/ImportSourceFiles.hpp
|
Intro-Ventors/Firefly
|
fa817785758c72f135492e9cc36daf1250169490
|
[
"MIT"
] | null | null | null |
Include/Firefly/ImportSourceFiles.hpp
|
Intro-Ventors/Firefly
|
fa817785758c72f135492e9cc36daf1250169490
|
[
"MIT"
] | null | null | null |
Include/Firefly/ImportSourceFiles.hpp
|
Intro-Ventors/Firefly
|
fa817785758c72f135492e9cc36daf1250169490
|
[
"MIT"
] | null | null | null |
#pragma once
/**
* This file imports all the source files from this library.
* Make sure that this file is included in ONE SOURCE FILE to compile the whole library. No additional dependencies needed.
*/
#include "Source/AssetLoaders/ImageLoader.cpp"
#include "Source/AssetLoaders/ObjLoader.cpp"
#include "Source/AssetLoaders/Types.cpp"
#include "Source/Decoder/Decoder.cpp"
#include "Source/Encoder/Encoder.cpp"
#include "Source/Graphics/GraphicsEngine.cpp"
#include "Source/Graphics/GraphicsPipeline.cpp"
#include "Source/Graphics/Package.cpp"
#include "Source/Graphics/RenderTarget.cpp"
#ifndef __ANDROID__
# include "Source/Graphics/Surface.cpp"
#endif
#include "Source/Maths/Camera.cpp"
#include "Source/Maths/CameraMatrix.cpp"
#include "Source/Maths/MonoCamera.cpp"
#include "Source/Maths/StereoCamera.cpp"
#include "Source/Tools/Renderdoc.cpp"
#include "Source/Buffer.cpp"
#include "Source/CommandBuffer.cpp"
#include "Source/Engine.cpp"
#include "Source/EngineBoundObject.cpp"
#include "Source/Image.cpp"
#include "Source/Instance.cpp"
#include "Source/Queue.cpp"
#include "Source/Shader.cpp"
#include "Source/Utility.cpp"
#define VOLK_IMPLEMENTATION
#include <volk/volk.h>
#define VMA_IMPLEMENTATION
#include <VulkanMemoryAllocator/vk_mem_alloc.h>
#define STB_IMAGE_IMPLEMENTATION
#include <stb/stb_image.h>
#define TINYOBJLOADER_IMPLEMENTATION
#include <tinyobjloader/tiny_obj_loader.h>
#include <SPIRV-Reflect/spirv_reflect.c>
| 26.907407
| 123
| 0.793531
|
Intro-Ventors
|
1b6a7c519c8226cef9857b33fbce1e98983d7edb
| 1,196
|
cpp
|
C++
|
cpp/cpp/697. Degree of an Array.cpp
|
longwangjhu/LeetCode
|
a5c33e8d67e67aedcd439953d96ac7f443e2817b
|
[
"MIT"
] | 3
|
2021-08-07T07:01:34.000Z
|
2021-08-07T07:03:02.000Z
|
cpp/cpp/697. Degree of an Array.cpp
|
longwangjhu/LeetCode
|
a5c33e8d67e67aedcd439953d96ac7f443e2817b
|
[
"MIT"
] | null | null | null |
cpp/cpp/697. Degree of an Array.cpp
|
longwangjhu/LeetCode
|
a5c33e8d67e67aedcd439953d96ac7f443e2817b
|
[
"MIT"
] | null | null | null |
// https://leetcode.com/problems/degree-of-an-array/
// Given a non-empty array of non-negative integers nums, the degree of this array
// is defined as the maximum frequency of any one of its elements.
// Your task is to find the smallest possible length of a (contiguous) subarray of
// nums, that has the same degree as nums.
////////////////////////////////////////////////////////////////////////////////
// use hashMap
class Solution {
public:
int findShortestSubArray(vector<int>& nums) {
// hashMap[num] = {freq, left, right}
unordered_map<int, vector<int>> hashMap;
int n = nums.size(), maxFreq = 0;
for (int i = 0; i < n; ++i) {
if (hashMap.find(nums[i]) == hashMap.end()) {
hashMap[nums[i]] = vector<int>{1, i, i};
} else {
++hashMap[nums[i]][0]; // update freq
hashMap[nums[i]][2] = i; // update right
}
maxFreq = max(maxFreq, hashMap[nums[i]][0]);
}
int ans = INT_MAX;
for (auto [num, vec] : hashMap) {
if (vec[0] == maxFreq) ans = min(ans, vec[2] - vec[1] + 1);
}
return ans;
}
};
| 34.171429
| 82
| 0.506689
|
longwangjhu
|
1b6aa0efc77f93e38214b0a1ff25ddbdf7d7ce70
| 16,272
|
hpp
|
C++
|
rajson/conversions.hpp
|
dmitigr/cefeika
|
6189843d4244f7334558708e57e952584561b1e0
|
[
"Zlib"
] | 19
|
2019-07-21T15:38:12.000Z
|
2022-01-06T05:24:48.000Z
|
rajson/conversions.hpp
|
dmitigr/cefeika
|
6189843d4244f7334558708e57e952584561b1e0
|
[
"Zlib"
] | 6
|
2019-12-07T22:12:37.000Z
|
2022-01-10T22:31:48.000Z
|
rajson/conversions.hpp
|
dmitigr/cefeika
|
6189843d4244f7334558708e57e952584561b1e0
|
[
"Zlib"
] | 1
|
2019-08-15T14:49:00.000Z
|
2019-08-15T14:49:00.000Z
|
// -*- C++ -*-
// Copyright (C) 2021 Dmitry Igrishin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
// Dmitry Igrishin
// dmitigr@gmail.com
#ifndef DMITIGR_RAJSON_CONVERSIONS_HPP
#define DMITIGR_RAJSON_CONVERSIONS_HPP
#include "fwd.hpp"
#include "exceptions.hpp"
#include "../3rdparty/rapidjson/document.h"
#include "../3rdparty/rapidjson/schema.h"
#include "../3rdparty/rapidjson/stringbuffer.h"
#include "../3rdparty/rapidjson/writer.h"
#include <cstdint>
#include <limits>
#include <optional>
#include <stdexcept>
#include <string>
#include <string_view>
#include <type_traits>
#include <utility>
#include <vector>
namespace dmitigr::rajson {
/// The centralized "namespace" for conversion algorithms implementations.
template<typename, typename = void> struct Conversions;
/**
* @returns The result of conversion of `value` to a JSON text. (Aka serialization.)
*
* @throws Generic_exception on error.
*/
template<class Encoding, class Allocator>
std::string to_text(const rapidjson::GenericValue<Encoding, Allocator>& value)
{
rapidjson::StringBuffer buf;
rapidjson::Writer<decltype(buf)> writer{buf}; // decltype() required for GCC 7
if (!value.Accept(writer))
throw Generic_exception{"cannot convert JSON value to text representation"};
return std::string{buf.GetString(), buf.GetSize()};
}
/**
* @returns The result of parsing a JSON text. (Aka deserialization.)
*
* @throw Parse_exception on parse error.
*/
inline rapidjson::Document to_document(const std::string_view input)
{
rapidjson::Document result;
const rapidjson::ParseResult pr{result.Parse(input.data(), input.size())};
if (!pr)
throw Parse_exception{pr};
return result;
}
/// @returns The RapidJSON's string reference.
inline auto to_string_ref(const std::string_view value)
{
return rapidjson::StringRef(value.data(), value.size());
}
/**
* @returns The result of conversion of `value` to the value of type `Destination`
* by using specializations of the template structure Conversions.
*/
template<typename Destination, class Encoding, class Allocator, typename ... Types>
Destination to(const rapidjson::GenericValue<Encoding, Allocator>& value, Types&& ... args)
{
using Dst = std::decay_t<Destination>;
return Conversions<Dst>::to_type(value, std::forward<Types>(args)...);
}
/// @returns The result of conversion of `value` to the RapidJSON generic value.
template<class Encoding, class Allocator, typename Source, typename ... Types>
rapidjson::GenericValue<Encoding, Allocator> to_value(Source&& value, Types&& ... args)
{
using Src = std::decay_t<Source>;
return Conversions<Src>::template to_value<Encoding,
Allocator>(std::forward<Source>(value), std::forward<Types>(args)...);
}
/// @overload
template<typename Source, typename ... Types>
rapidjson::Value to_value(Source&& value, Types&& ... args)
{
using E = rapidjson::Value::EncodingType;
using A = rapidjson::Value::AllocatorType;
return to_value<E, A>(std::forward<Source>(value), std::forward<Types>(args)...);
}
// -----------------------------------------------------------------------------
// Conversions specializations
// -----------------------------------------------------------------------------
/// Generic implementation of conversion routines for arithmetic types.
struct Arithmetic_generic_conversions {
template<class Encoding, class Allocator, typename T>
static auto to_value(const T value, Allocator&)
{
static_assert(std::is_arithmetic_v<std::decay_t<T>>);
return rapidjson::GenericValue<Encoding, Allocator>{value};
}
};
/// Full specialization for `bool`.
template<>
struct Conversions<bool> final : Arithmetic_generic_conversions {
template<class Encoding, class Allocator>
static auto to_type(const rapidjson::GenericValue<Encoding, Allocator>& value)
{
if (value.IsBool())
return value.GetBool();
throw Generic_exception{"cannot convert JSON value to bool"};
}
};
/// Full specialization for `std::uint8_t`.
template<>
struct Conversions<std::uint8_t> final : Arithmetic_generic_conversions {
template<class Encoding, class Allocator>
static auto to_type(const rapidjson::GenericValue<Encoding, Allocator>& value)
{
if (value.IsUint()) {
const auto result = value.GetUint();
if (result <= std::numeric_limits<std::uint8_t>::max())
return static_cast<std::uint8_t>(result);
}
throw Generic_exception{"cannot convert JSON value to std::uint8_t"};
}
};
/// Full specialization for `std::uint16_t`.
template<>
struct Conversions<std::uint16_t> final : Arithmetic_generic_conversions {
template<class Encoding, class Allocator>
static auto to_type(const rapidjson::GenericValue<Encoding, Allocator>& value)
{
if (value.IsUint()) {
const auto result = value.GetUint();
if (result <= std::numeric_limits<std::uint16_t>::max())
return static_cast<std::uint16_t>(result);
}
throw Generic_exception{"cannot convert JSON value to std::uint16_t"};
}
};
/// Full specialization for `std::uint32_t`.
template<>
struct Conversions<std::uint32_t> final : Arithmetic_generic_conversions {
template<class Encoding, class Allocator>
static auto to_type(const rapidjson::GenericValue<Encoding, Allocator>& value)
{
if (value.IsUint()) {
const auto result = value.GetUint();
if (result <= std::numeric_limits<std::uint32_t>::max())
return static_cast<std::uint32_t>(result);
}
throw Generic_exception{"cannot convert JSON value to std::uint32_t"};
}
};
/// Full specialization for `std::uint64_t`.
template<>
struct Conversions<std::uint64_t> final : Arithmetic_generic_conversions {
template<class Encoding, class Allocator>
static auto to_type(const rapidjson::GenericValue<Encoding, Allocator>& value)
{
if (value.IsUint64())
return static_cast<std::uint64_t>(value.GetUint64());
throw Generic_exception{"cannot convert JSON value to std::uint64_t"};
}
};
/// Full specialization for `std::int8_t`.
template<>
struct Conversions<std::int8_t> final : Arithmetic_generic_conversions {
template<class Encoding, class Allocator>
static auto to_type(const rapidjson::GenericValue<Encoding, Allocator>& value)
{
if (value.IsInt()) {
const auto result = value.GetInt();
if (std::numeric_limits<std::int8_t>::min() <= result &&
result <= std::numeric_limits<std::int8_t>::max())
return static_cast<std::int8_t>(result);
}
throw Generic_exception{"cannot convert JSON value to std::int8_t"};
}
};
/// Full specialization for `std::int16_t`.
template<>
struct Conversions<std::int16_t> final : Arithmetic_generic_conversions {
template<class Encoding, class Allocator>
static auto to_type(const rapidjson::GenericValue<Encoding, Allocator>& value)
{
if (value.IsInt()) {
const auto result = value.GetInt();
if (std::numeric_limits<std::int16_t>::min() <= result &&
result <= std::numeric_limits<std::int16_t>::max())
return static_cast<std::int16_t>(result);
}
throw Generic_exception{"cannot convert JSON value to std::int16_t"};
}
};
/// Full specialization for `std::int32_t`.
template<>
struct Conversions<std::int32_t> final : Arithmetic_generic_conversions {
template<class Encoding, class Allocator>
static auto to_type(const rapidjson::GenericValue<Encoding, Allocator>& value)
{
if (value.IsInt()) {
const auto result = value.GetInt();
if (std::numeric_limits<std::int32_t>::min() <= result &&
result <= std::numeric_limits<std::int32_t>::max())
return static_cast<std::int32_t>(result);
}
throw Generic_exception{"cannot convert JSON value to std::int32_t"};
}
};
/// Full specialization for `std::int64_t`.
template<>
struct Conversions<std::int64_t> final : Arithmetic_generic_conversions {
template<class Encoding, class Allocator>
static auto to_type(const rapidjson::GenericValue<Encoding, Allocator>& value)
{
if (value.IsInt64())
return static_cast<std::int64_t>(value.GetInt64());
throw Generic_exception{"cannot convert JSON value to std::int64_t"};
}
};
/// Full specialization for `float`.
template<>
struct Conversions<float> final : Arithmetic_generic_conversions {
template<class Encoding, class Allocator>
static auto to_type(const rapidjson::GenericValue<Encoding, Allocator>& value)
{
if (value.IsFloat() || value.IsLosslessFloat())
return value.GetFloat();
throw Generic_exception{"cannot convert JSON value to float"};
}
};
/// Full specialization for `double`.
template<>
struct Conversions<double> final : Arithmetic_generic_conversions {
template<class Encoding, class Allocator>
static auto to_type(const rapidjson::GenericValue<Encoding, Allocator>& value)
{
if (value.IsDouble() || value.IsLosslessDouble())
return value.GetDouble();
throw Generic_exception{"cannot convert JSON value to double"};
}
};
/// Full specialization for `std::string`.
template<>
struct Conversions<std::string> final {
template<class Encoding, class Allocator>
static auto to_type(const rapidjson::GenericValue<Encoding, Allocator>& value)
{
if (value.IsString())
return std::string{value.GetString(), value.GetStringLength()};
throw Generic_exception{"cannot convert JSON value to std::string"};
}
template<class Encoding, class Allocator>
static auto to_value(const std::string& value, Allocator& alloc)
{
// Copy `value` to result.
return rapidjson::GenericValue<Encoding, Allocator>{value, alloc};
}
};
/// Full specialization for `std::string_view`.
template<>
struct Conversions<std::string_view> final {
template<class Encoding, class Allocator>
static auto to_type(const rapidjson::GenericValue<Encoding, Allocator>& value)
{
if (value.IsString())
return std::string_view{value.GetString(), value.GetStringLength()};
throw Generic_exception{"cannot convert JSON value to std::string_view"};
}
template<class Encoding, class Allocator>
static auto to_value(const std::string_view value, Allocator&)
{
// Don't copy `value` to result.
return rapidjson::GenericValue<Encoding, Allocator>{value.data(), value.size()};
}
};
/// Full specialization for `const char*`.
template<>
struct Conversions<const char*> final {
template<class Encoding, class Allocator>
static auto to_value(const char* const value, Allocator& alloc)
{
// Don't copy `value` to result.
return rapidjson::GenericValue<Encoding, Allocator>{value, alloc};
}
};
/// Partial specialization for enumeration types.
template<typename T>
struct Conversions<T, std::enable_if_t<std::is_enum_v<T>>> {
template<class Encoding, class Allocator>
static auto to_type(const rapidjson::GenericValue<Encoding, Allocator>& value)
{
return static_cast<T>(to<std::underlying_type_t<T>>(value));
}
template<class Encoding, class Allocator>
static auto to_value(const T value, Allocator&)
{
return rapidjson::GenericValue<Encoding, Allocator>(static_cast<std::underlying_type_t<T>>(value));
}
};
/// Partial specialization for `std::vector<T>`.
template<typename T>
struct Conversions<std::vector<T>> final {
template<class Encoding, class Allocator>
static auto to_type(const rapidjson::GenericValue<Encoding, Allocator>& value)
{
if (value.IsArray()) {
const auto arr = value.GetArray();
std::vector<T> result;
result.reserve(arr.Size());
for (const auto& val : arr) {
if (val.IsNull())
throw Generic_exception{"cannot emplace NULL value to std::vector<T>"};
result.emplace_back(to<T>(val));
}
return result;
}
throw Generic_exception{"cannot convert JSON value to std::vector<T>"};
}
template<class Encoding, class Allocator>
static auto to_value(const std::vector<T>& value, Allocator& alloc)
{
rapidjson::GenericValue<Encoding, Allocator> result{rapidjson::kArrayType};
result.Reserve(value.size(), alloc);
for (const auto& val : value)
result.PushBack(rajson::to_value<Encoding, Allocator>(val, alloc), alloc);
return result;
}
};
/// Partial specialization for `std::vector<std::optional<T>>`.
template<typename T>
struct Conversions<std::vector<std::optional<T>>> final {
template<class Encoding, class Allocator>
static auto to_type(const rapidjson::GenericValue<Encoding, Allocator>& value)
{
if (value.IsArray()) {
const auto arr = value.GetArray();
std::vector<std::optional<T>> result;
result.reserve(arr.Size());
for (const auto& val : arr)
result.emplace_back(!val.IsNull() ? to<T>(val) : std::optional<T>{});
return result;
}
throw Generic_exception{"cannot convert JSON value to std::vector<std::optional<T>>"};
}
template<class Encoding, class Allocator>
static auto to_value(const std::vector<std::optional<T>>& value, Allocator& alloc)
{
using Value = rapidjson::GenericValue<Encoding, Allocator>;
Value result{rapidjson::kArrayType};
result.Reserve(value.size(), alloc);
for (const auto& val : value)
result.PushBack(val ? rajson::to_value<Encoding, Allocator>(*val, alloc) : Value{}, alloc);
return result;
}
};
/// Partial specialization for `rapidjson::GenericValue`.
template<class Encoding, class Allocator>
struct Conversions<rapidjson::GenericValue<Encoding, Allocator>> final {
using Type = rapidjson::GenericValue<Encoding, Allocator>;
template<class E, class A>
static auto to_type(Type&& value)
{
static_assert(std::is_same_v<E, Encoding> && std::is_same_v<A, Allocator>);
return std::move(value);
}
template<class E, class A>
static auto to_type(const Type& value)
{
static_assert(std::is_same_v<E, Encoding> && std::is_same_v<A, Allocator>);
Type result;
result.CopyFrom(value, result.GetAllocator(), true);
return result;
}
template<class E, class A>
static auto to_value(Type&& value, Allocator&)
{
static_assert(std::is_same_v<E, Encoding> && std::is_same_v<A, Allocator>);
return std::move(value);
}
template<class E, class A>
static auto to_value(const Type& value, Allocator&)
{
static_assert(std::is_same_v<E, Encoding> && std::is_same_v<A, Allocator>);
return to_type(value);
}
};
/// Partial specialization for `rapidjson::GenericDocument`.
template<class Encoding, class Allocator, class StackAllocator>
struct Conversions<rapidjson::GenericDocument<Encoding, Allocator, StackAllocator>> final {
using Type = rapidjson::GenericDocument<Encoding, Allocator, StackAllocator>;
using Value_type = rapidjson::GenericValue<Encoding, Allocator>;
template<class E, class A>
static auto to_type(Type&& value)
{
static_assert(std::is_same_v<E, Encoding> && std::is_same_v<A, Allocator>);
return std::move(value);
}
template<class E, class A>
static auto to_type(const Type& value)
{
static_assert(std::is_same_v<E, Encoding> && std::is_same_v<A, Allocator>);
Type result;
result.CopyFrom(value, result.GetAllocator(), true);
return result;
}
template<class E, class A>
static auto to_value(const Type& value, Allocator& alloc)
{
static_assert(std::is_same_v<E, Encoding> && std::is_same_v<A, Allocator>);
Value_type result;
result.CopyFrom(value, alloc, true);
return result;
}
};
} // namespace dmitigr::rajson
#endif // DMITIGR_RAJSON_CONVERSIONS_HPP
| 33.619835
| 103
| 0.705875
|
dmitigr
|
1b6bfd7e63c49464684dfde6cb5fba27ba3c4a94
| 1,718
|
cpp
|
C++
|
vnoj/277.5C-div2.cpp
|
tiozo/Training
|
02cc8c4fcf68e07c16520fd05fcbfa524c171b6b
|
[
"MIT"
] | 1
|
2021-08-28T04:16:34.000Z
|
2021-08-28T04:16:34.000Z
|
vnoj/277.5C-div2.cpp
|
tiozo/Training
|
02cc8c4fcf68e07c16520fd05fcbfa524c171b6b
|
[
"MIT"
] | null | null | null |
vnoj/277.5C-div2.cpp
|
tiozo/Training
|
02cc8c4fcf68e07c16520fd05fcbfa524c171b6b
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <stdio.h>
#include <fstream>
#include <string.h>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <list>
#include <set>
#include <deque>
#include <utility>
#include <sstream>
#include <queue>
#include <stack>
#include <bitset>
#include <math.h>
#include <iomanip>
#include <algorithm>
#include <limits.h>
#define MP make_pair
#define PB push_back
#define MAX 1001
#define EPS 0.000001
using namespace std;
int m, s;
bool dp[MAX][200], dp2[MAX][200];
string solve(string curAns, int curSum, int curPos) {
//cout << "->" << curAns << endl;
if(curSum > s) return "-1";
if(dp[curSum][curPos]) return "-1";
dp[curSum][curPos] = true;
if(curPos == m) {
if(curSum == s) return curAns;
return "-1";
}
for(int i = 9; i >= 0; i--) {
if(curPos == 0 && m > 1 && i == 0) continue;
char num = i + '0';
string ret = solve(curAns + num, curSum + i, curPos + 1);
if(ret != "-1") return ret;
}
return "-1";
}
string solve2(string curAns, int curSum, int curPos) {
//cout << "->" << curAns << endl;
if(curSum > s) return "-1";
if(dp2[curSum][curPos]) return "-1";
dp2[curSum][curPos] = true;
if(curPos == m) {
if(curSum == s) return curAns;
return "-1";
}
for(int i = 0; i <= 9; i++) {
if(i == 0 && curPos == 0 && m > 1) continue;
char num = i + '0';
string ret = solve2(curAns + num, curSum + i, curPos + 1);
if(ret != "-1") return ret;
}
return "-1";
}
int main() {
//freopen("F.in", "r", stdin);
cin >> m >> s;
cout << solve2("", 0, 0) << " " << solve("", 0, 0) << endl;
return 0;
}
| 21.475
| 66
| 0.536671
|
tiozo
|
1b6ca293c3326f9298b57f053cce14e711878bd5
| 143
|
cpp
|
C++
|
devel/main.cpp
|
tonypilz/CompileTimeCStringConcatenation
|
beda905ae0169adc66d03716f22e37de4035e2a9
|
[
"BSD-3-Clause"
] | 1
|
2019-06-02T20:08:42.000Z
|
2019-06-02T20:08:42.000Z
|
devel/main.cpp
|
tonypilz/CompileTimeCStringConcatenation
|
beda905ae0169adc66d03716f22e37de4035e2a9
|
[
"BSD-3-Clause"
] | 1
|
2019-02-03T11:36:18.000Z
|
2019-02-03T11:36:18.000Z
|
devel/main.cpp
|
tonypilz/ConstexprString
|
beda905ae0169adc66d03716f22e37de4035e2a9
|
[
"BSD-3-Clause"
] | null | null | null |
#include <iostream>
#include "ConstexprString.h"
#include "main_example.cpp"
#include "tests.h"
int main()
{
main_();
return 0;
}
| 9.533333
| 28
| 0.643357
|
tonypilz
|
1b79589bfa8caed14c57f9c155b1b7d5c82e7a06
| 3,768
|
cpp
|
C++
|
source/tools/Tests/prefix.cpp
|
ganboing/pintool
|
ece4788ffded47124b1c9b203707cc255dbaf20f
|
[
"Intel"
] | 1
|
2017-06-06T16:02:31.000Z
|
2017-06-06T16:02:31.000Z
|
source/tools/Tests/prefix.cpp
|
ganboing/pintool
|
ece4788ffded47124b1c9b203707cc255dbaf20f
|
[
"Intel"
] | null | null | null |
source/tools/Tests/prefix.cpp
|
ganboing/pintool
|
ece4788ffded47124b1c9b203707cc255dbaf20f
|
[
"Intel"
] | null | null | null |
/*BEGIN_LEGAL
Intel Open Source License
Copyright (c) 2002-2016 Intel Corporation. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer. Redistributions
in binary form must reproduce the above copyright notice, this list of
conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution. Neither the name of
the Intel Corporation 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 INTEL OR
ITS 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.
END_LEGAL */
/*
@ORIGINAL_AUTHOR: Daniel Lemel
*/
/*! @file
* Chek the prefixes APIs.
*/
#include "pin_tests_util.H"
#include <fstream>
UINT32 addressSizePrefixCount = 0;
UINT32 branchNotTakenPrefixCount = 0;
UINT32 branchTakenPrefixCount = 0;
UINT32 lockPrefixCount = 0;
UINT32 operandSizePrefixCount = 0;
UINT32 repPrefixCount = 0;
UINT32 repnePrefixCount = 0;
UINT32 segmentPrefixCount = 0;
VOID CountsUpdate(INS ins)
{
if (INS_AddressSizePrefix(ins)) addressSizePrefixCount++;
if (INS_BranchNotTakenPrefix(ins)) branchNotTakenPrefixCount++;
if (INS_BranchTakenPrefix(ins)) branchTakenPrefixCount++;
if (INS_LockPrefix(ins)) lockPrefixCount++;
if (INS_OperandSizePrefix(ins)) operandSizePrefixCount++;
if (INS_RepPrefix(ins)) repPrefixCount++;
if (INS_RepnePrefix(ins)) repnePrefixCount++;
if (INS_SegmentPrefix(ins)) segmentPrefixCount++;
}
VOID Rtn(RTN rtn, VOID * v)
{
string name = RTN_Name(rtn);
if ((name == "test1") || (name == "test2")) {
RTN_Open(rtn);
for (INS ins = RTN_InsHead(rtn); INS_Valid(ins); ins = INS_Next(ins)) {
CountsUpdate(ins);
}
RTN_Close(rtn);
}
}
VOID Fini(INT32 code, VOID *v)
{
TEST(addressSizePrefixCount == 1, "INS_AddressSizePrefix failed");
TEST(branchNotTakenPrefixCount == 0, "INS_BranchNotTakenPrefix failed");
TEST(branchTakenPrefixCount == 0, "INS_BranchTakenPrefix failed");
TEST(lockPrefixCount == 1, "INS_LockPrefix failed");
TEST(operandSizePrefixCount == 1, "INS_OperandSizePrefix failed");
TEST(repPrefixCount == 1, "INS_RepPrefix failed");
TEST(repnePrefixCount == 1, "INS_RepnePrefix failed");
TEST(segmentPrefixCount == 1, "INS_SegmentPrefix failed");
}
int main(INT32 argc, CHAR **argv)
{
PIN_InitSymbols();
PIN_Init(argc, argv);
RTN_AddInstrumentFunction(Rtn, 0);
PIN_AddFiniFunction(Fini, 0);
// Never returns
PIN_StartProgram();
return 0;
}
| 37.68
| 81
| 0.692675
|
ganboing
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.