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 108 | 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 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c58206d9926748e1736b9d349a8bbfbc97ea87e7 | 597 | hpp | C++ | Code/include/OE/Platform/Direct3D/D3DMesh.hpp | mlomb/OrbitEngine | 41f053626f05782e81c2e48f5c87b04972f9be2c | [
"Apache-2.0"
] | 21 | 2018-06-26T16:37:36.000Z | 2022-01-11T01:19:42.000Z | Code/include/OE/Platform/Direct3D/D3DMesh.hpp | mlomb/OrbitEngine | 41f053626f05782e81c2e48f5c87b04972f9be2c | [
"Apache-2.0"
] | null | null | null | Code/include/OE/Platform/Direct3D/D3DMesh.hpp | mlomb/OrbitEngine | 41f053626f05782e81c2e48f5c87b04972f9be2c | [
"Apache-2.0"
] | 3 | 2019-10-01T14:10:50.000Z | 2021-11-19T20:30:18.000Z | #ifndef GRAPHICS_D3DMESH_HPP
#define GRAPHICS_D3DMESH_HPP
#include "OE/Graphics/API/Mesh.hpp"
#include "OE/Platform/Direct3D/Direct3D.hpp"
namespace OrbitEngine { namespace Graphics {
class D3DMesh : public Mesh {
public:
D3DMesh(void* vertices, unsigned int vertexSize, VertexLayout* layout, const std::vector<unsigned short>& indices);
void drawIndexed(unsigned int count, unsigned int offset = 0) override;
void draw(unsigned int count, unsigned int offset = 0) override;
private:
static D3D_PRIMITIVE_TOPOLOGY TopologyToD3D(Topology topology);
void preDraw();
};
} }
#endif | 27.136364 | 117 | 0.768844 | mlomb |
c583f6f94f0adfcb7081ef318f16ef789d5ea72c | 2,052 | cpp | C++ | src/unit_tests/engine/ut_aabb.cpp | OndraVoves/LumixEngine | b7040d7a5b9dc1c6bc78e5e6d9b33b7f585c435f | [
"MIT"
] | 1 | 2020-10-28T10:29:21.000Z | 2020-10-28T10:29:21.000Z | src/unit_tests/engine/ut_aabb.cpp | OndraVoves/LumixEngine | b7040d7a5b9dc1c6bc78e5e6d9b33b7f585c435f | [
"MIT"
] | null | null | null | src/unit_tests/engine/ut_aabb.cpp | OndraVoves/LumixEngine | b7040d7a5b9dc1c6bc78e5e6d9b33b7f585c435f | [
"MIT"
] | null | null | null | #include "engine/geometry.h"
#include "engine/matrix.h"
#include "unit_tests/suite/lumix_unit_tests.h"
using namespace Lumix;
void UT_aabb(const char* params)
{
AABB aabb1;
AABB aabb2(Vec3(0, 0, 0), Vec3(1, 1, 1));
LUMIX_EXPECT(aabb2.min.x == 0);
LUMIX_EXPECT(aabb2.min.y == 0);
LUMIX_EXPECT(aabb2.min.z == 0);
LUMIX_EXPECT(aabb2.max.x == 1);
LUMIX_EXPECT(aabb2.max.y == 1);
LUMIX_EXPECT(aabb2.max.z == 1);
aabb1 = aabb2;
LUMIX_EXPECT(aabb1.min.x == aabb2.min.x);
LUMIX_EXPECT(aabb1.min.y == aabb2.min.y);
LUMIX_EXPECT(aabb1.min.z == aabb2.min.z);
LUMIX_EXPECT(aabb1.max.x == aabb2.max.x);
LUMIX_EXPECT(aabb1.max.y == aabb2.max.y);
LUMIX_EXPECT(aabb1.max.z == aabb2.max.z);
Vec3 points[8];
aabb2.getCorners(Matrix::IDENTITY, points);
LUMIX_EXPECT(points[0].x == 0);
LUMIX_EXPECT(points[0].y == 0);
LUMIX_EXPECT(points[0].z == 0);
LUMIX_EXPECT(points[1].x == 0);
LUMIX_EXPECT(points[1].y == 0);
LUMIX_EXPECT(points[1].z == 1);
LUMIX_EXPECT(points[2].x == 0);
LUMIX_EXPECT(points[2].y == 1);
LUMIX_EXPECT(points[2].z == 0);
LUMIX_EXPECT(points[3].x == 0);
LUMIX_EXPECT(points[3].y == 1);
LUMIX_EXPECT(points[3].z == 1);
LUMIX_EXPECT(points[4].x == 1);
LUMIX_EXPECT(points[4].y == 0);
LUMIX_EXPECT(points[4].z == 0);
LUMIX_EXPECT(points[5].x == 1);
LUMIX_EXPECT(points[5].y == 0);
LUMIX_EXPECT(points[5].z == 1);
LUMIX_EXPECT(points[6].x == 1);
LUMIX_EXPECT(points[6].y == 1);
LUMIX_EXPECT(points[6].z == 0);
LUMIX_EXPECT(points[7].x == 1);
LUMIX_EXPECT(points[7].y == 1);
LUMIX_EXPECT(points[7].z == 1);
AABB aabb3(Vec3(0, 0, 0), Vec3(1, 1, 1));
AABB aabb4(Vec3(1, 2, 3), Vec3(2, 3, 4));
Matrix mtx = Matrix::IDENTITY;
mtx.setTranslation(Vec3(1, 2, 3));
aabb3.transform(mtx);
LUMIX_EXPECT(aabb3.min.x == aabb4.min.x);
LUMIX_EXPECT(aabb3.min.y == aabb4.min.y);
LUMIX_EXPECT(aabb3.min.z == aabb4.min.z);
LUMIX_EXPECT(aabb3.max.x == aabb4.max.x);
LUMIX_EXPECT(aabb3.max.y == aabb4.max.y);
LUMIX_EXPECT(aabb3.max.z == aabb4.max.z);
}
REGISTER_TEST("unit_tests/engine/aabb", UT_aabb, "") | 25.65 | 52 | 0.662768 | OndraVoves |
c5869e7586189e620e6a78d1bdae1cae6677a9ea | 2,298 | cpp | C++ | src/util.cpp | tony/tot-cpp-shmup | 40084b5e19eeabb0e65fa3f7aac7ea92cbf77fee | [
"MIT"
] | 6 | 2016-12-31T11:42:17.000Z | 2019-10-25T07:11:26.000Z | src/util.cpp | tony/tot-cpp-shmup | 40084b5e19eeabb0e65fa3f7aac7ea92cbf77fee | [
"MIT"
] | null | null | null | src/util.cpp | tony/tot-cpp-shmup | 40084b5e19eeabb0e65fa3f7aac7ea92cbf77fee | [
"MIT"
] | null | null | null | /* Copyright 2016 Tony Narlock. All rights reserved. */
#include "util.h"
#include <memory>
#include "config.h"
#include "json.hpp"
using json = nlohmann::json;
std::shared_ptr<SDL2pp::Texture> DrawText(
const std::string& text,
const SDL2pp::Point& position,
const std::shared_ptr<SDL2pp::Font>& font,
const std::unique_ptr<SDL2pp::Renderer>& renderer,
bool underline = true) {
SDL_Color text_fg_color{255, 255, 255, 255};
SDL_Color text_shadow_color{0, 0, 0, 255};
auto target1 = std::make_shared<SDL2pp::Texture>(
*renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_TARGET,
SCREEN_RECT.w, SCREEN_RECT.h);
target1->SetBlendMode(SDL_BLENDMODE_BLEND);
renderer->SetTarget(*target1);
renderer->Clear();
renderer->SetDrawBlendMode(SDL_BLENDMODE_BLEND);
if (underline) {
auto message_shadow(font->RenderText_Blended(text, text_shadow_color));
auto message_texture_shadow(SDL2pp::Texture(*renderer, message_shadow));
SDL2pp::Rect message_shadow_rect = {position.x + 1, position.y + 1,
message_shadow.GetWidth(),
message_shadow.GetHeight()};
renderer->Copy(message_texture_shadow, SDL2pp::NullOpt,
message_shadow_rect);
}
auto message(font->RenderText_Blended(text, text_fg_color));
auto message_texture(SDL2pp::Texture(*renderer, message));
SDL2pp::Rect message_rect = {position.x, position.y, message.GetWidth(),
message.GetHeight()};
renderer->Copy(message_texture, SDL2pp::NullOpt, message_rect);
renderer->SetTarget();
return target1;
}
int RandInt(int lo, int hi) {
std::random_device rd;
std::mt19937 mt(rd());
std::uniform_int_distribution<int> dist(lo, hi);
return dist(mt);
}
SDL2pp::Rect TintToSDL_Rect(json::iterator o) {
std::array<uint8_t, 4> a;
int idx = 0;
for (json::iterator i = o->begin(); i != o->end(); ++i) {
a[idx] = i->get<uint8_t>();
idx++;
}
return SDL2pp::Rect{a[0], a[1], a[2], a[3]};
}
SDL_Color TintToSDL_Color(json::iterator o) {
std::array<uint8_t, 4> a;
int idx = 0;
for (json::iterator i = o->begin(); i != o->end(); ++i) {
a[idx] = i->get<uint8_t>();
idx++;
}
return SDL_Color{a[0], a[1], a[2], a[3]};
}
| 31.916667 | 76 | 0.64752 | tony |
c58833ce649533cf2706a330c27a8f2a95d859e5 | 3,929 | cpp | C++ | VSDataReduction/VSSimplePedData.cpp | sfegan/ChiLA | 916bdd95348c2df2ecc736511d5f5b2bfb4a831e | [
"BSD-3-Clause"
] | 1 | 2018-04-17T14:03:36.000Z | 2018-04-17T14:03:36.000Z | VSDataReduction/VSSimplePedData.cpp | sfegan/ChiLA | 916bdd95348c2df2ecc736511d5f5b2bfb4a831e | [
"BSD-3-Clause"
] | null | null | null | VSDataReduction/VSSimplePedData.cpp | sfegan/ChiLA | 916bdd95348c2df2ecc736511d5f5b2bfb4a831e | [
"BSD-3-Clause"
] | null | null | null | //-*-mode:c++; mode:font-lock;-*-
/*! \file VSSimplePedData.hpp
Simple pedestal data
\author Stephen Fegan \n
UCLA \n
sfegan@astro.ucla.edu \n
\version 1.0
\date 05/18/2005
$Id: VSSimplePedData.cpp,v 3.1 2007/12/04 18:05:03 sfegan Exp $
*/
#include<fstream>
#include<memory>
#include<vsassert>
#include <VSLineTokenizer.hpp>
#include "VSSimpleStat.hpp"
#include "VSSimplePedData.hpp"
using namespace VERITAS;
bool VSSimplePedData::load(const std::string& filename)
{
std::ifstream datastream(filename.c_str());
if(!datastream)return false;
m_data.clear();
std::string line;
VSLineTokenizer tokenizer;
VSTokenList tokens;
unsigned iline=0;
while(getline(datastream,line))
{
iline++;
std::string line_copy = line;
tokenizer.tokenize(line_copy, tokens);
if(tokens.size() == 0)continue;
if(tokens.size() < 4)
{
std::cerr << filename << ": line " << iline
<< ": " << tokens.size()
<< " columns found (>=4 expected)" << std::endl
<< "Line: " << line << std::endl;
continue;
}
unsigned iscope = 0;
unsigned ichan = 0;
double ped = 0;
tokens[0].to(iscope);
tokens[1].to(ichan);
tokens[2].to(ped);
if(iscope >= m_data.size())m_data.resize(iscope+1);
if(ichan >= m_data[iscope].size())m_data[iscope].resize(ichan+1);
m_data[iscope][ichan].ped = ped;
unsigned nsample = tokens.size()-3;
m_data[iscope][ichan].dev.resize(nsample);
for(unsigned isample=0;isample<nsample;isample++)
tokens[3+isample].to(m_data[iscope][ichan].dev[isample]);
m_data[iscope][ichan].suppressed = false;
}
return true;
}
bool VSSimplePedData::save(const std::string& filename)
{
std::ostream* filestream = 0;
std::ostream* datastream = &std::cout;
if(!filename.empty())
{
filestream = new std::ofstream(filename.c_str());
if(!filestream->good())return false;
datastream = filestream;
}
unsigned nscope = m_data.size();
for(unsigned iscope=0;iscope<nscope;iscope++)
{
unsigned nchan = m_data[iscope].size();
for(unsigned ichan=0;ichan<nchan;ichan++)
{
unsigned nsample = m_data[iscope][ichan].dev.size();
(*datastream) << iscope << ' ' << ichan << ' '
<< m_data[iscope][ichan].ped;
for(unsigned isample=0;isample<nsample;isample++)
(*datastream) << ' ' << m_data[iscope][ichan].dev[isample];
(*datastream) << std::endl;
}
}
delete filestream;
return true;
}
void VSSimplePedData::suppress(const double lo, const double hi,
const unsigned window)
{
unsigned nscope = m_data.size();
unsigned isample = window;
// This loop to find window size to use for suppression (if necessary!)
if(isample==0)
{
for(unsigned iscope=0;isample==0&&iscope<nscope;iscope++)
{
unsigned nchan = m_data[iscope].size();
for(unsigned ichan=0;isample==0&&ichan<nchan;ichan++)
{
unsigned nsample = m_data[iscope][ichan].dev.size();
if(nsample)isample=nsample;
}
}
vsassert(isample!=0);
}
isample--;
// This loop to suppress
for(unsigned iscope=0;iscope<nscope;iscope++)
{
unsigned nchan = m_data[iscope].size();
if(nchan==0)continue;
std::vector<std::pair<bool,double> > dev_list(nchan);
for(unsigned ichan=0;ichan<nchan;ichan++)
dev_list[ichan].first=!m_data[iscope][ichan].suppressed,
dev_list[ichan].second=m_data[iscope][ichan].dev[isample];
double meddev = median(dev_list);
double locut = meddev*lo;
double hicut = meddev*hi;
for(unsigned ichan=0;ichan<nchan;ichan++)
if((m_data[iscope][ichan].dev[isample]<locut)
||(m_data[iscope][ichan].dev[isample]>hicut))
m_data[iscope][ichan].suppressed=true;
}
}
| 26.910959 | 73 | 0.611861 | sfegan |
c58ab15f5f674fb2e4a27e1651627c519ccf7b9e | 18,416 | cpp | C++ | com/netfx/src/clr/profile/mscorcap/callback.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | com/netfx/src/clr/profile/mscorcap/callback.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | com/netfx/src/clr/profile/mscorcap/callback.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | // ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
//*****************************************************************************
// Callback.cpp
//
// Implements the profiling callbacks and does the right thing for icecap.
//
//*****************************************************************************
#include "StdAfx.h"
#include "mscorcap.h"
#include "PrettyPrintSig.h"
#include "icecap.h"
#define SZ_DEFAULT_LOG_FILE L"icecap.csv"
#define SZ_CRLF "\r\n"
#define SZ_COLUMNHDR "FunctionId,Name\r\n"
#define SZ_SIGNATURES L"signatures"
#define LEN_SZ_SIGNATURES ((sizeof(SZ_SIGNATURES) - 1) / sizeof(WCHAR))
#define BUFFER_SIZE (8 * 1096)
extern "C"
{
typedef BOOL (__stdcall *PFN_SUSPENDPROFILNG)(int nLevel, DWORD dwid);
typedef BOOL (__stdcall *PFN_RESUMEPROFILNG)(int nLevel, DWORD dwid);
}
#ifndef PROFILE_THREADLEVEL
#define PROFILE_GLOBALLEVEL 1
#define PROFILE_PROCESSLEVEL 2
#define PROFILE_THREADLEVEL 3
#define PROFILE_CURRENTID ((unsigned long)0xFFFFFFFF)
#endif
const char* PrettyPrintSig(
PCCOR_SIGNATURE typePtr, // type to convert,
unsigned typeLen, // length of type
const char* name, // can be "", the name of the method for this sig
CQuickBytes *out, // where to put the pretty printed string
IMetaDataImport *pIMDI); // Import api to use.
// Global for use by DllMain
ProfCallback *g_pCallback = NULL;
ProfCallback::ProfCallback() :
m_pInfo(NULL),
m_wszFilename(NULL),
m_eSig(SIG_NONE)
{
}
ProfCallback::~ProfCallback()
{
if (m_pInfo)
RELEASE(m_pInfo);
// Prevent anyone else from doing a delete on an already deleted object
g_pCallback = NULL;
delete [] m_wszFilename;
_ASSERTE(!(m_wszFilename = NULL));
}
COM_METHOD ProfCallback::Initialize(
/* [in] */ IUnknown *pEventInfoUnk)
{
HRESULT hr = S_OK;
ICorProfilerInfo *pEventInfo;
// Comes back addref'd
hr = pEventInfoUnk->QueryInterface(IID_ICorProfilerInfo, (void **)&pEventInfo);
if (FAILED(hr))
return (hr);
// By default, always get jit completion events.
DWORD dwRequestedEvents = COR_PRF_MONITOR_JIT_COMPILATION | COR_PRF_MONITOR_CACHE_SEARCHES;
// Called to initialize the WinWrap stuff so that WszXXX functions work
OnUnicodeSystem();
// Read the configuration from the PROF_CONFIG environment variable
{
WCHAR wszBuffer[BUF_SIZE];
WCHAR *wszEnv = wszBuffer;
DWORD cEnv = BUF_SIZE;
DWORD cRes = WszGetEnvironmentVariable(CONFIG_ENV_VAR, wszEnv, cEnv);
if (cRes != 0)
{
// Need to allocate a bigger string and try again
if (cRes > cEnv)
{
wszEnv = (WCHAR *)_alloca(cRes * sizeof(WCHAR));
cRes = WszGetEnvironmentVariable(CONFIG_ENV_VAR, wszEnv,
cRes);
_ASSERTE(cRes != 0);
}
hr = ParseConfig(wszEnv, &dwRequestedEvents);
}
// Else set default values
else
hr = ParseConfig(NULL, &dwRequestedEvents);
}
if (SUCCEEDED(hr))
{
hr = pEventInfo->SetEventMask(dwRequestedEvents);
_ASSERTE((dwRequestedEvents | (COR_PRF_MONITOR_JIT_COMPILATION | COR_PRF_MONITOR_CACHE_SEARCHES)) && SUCCEEDED(hr));
}
if (SUCCEEDED(hr))
{
hr = IcecapProbes::LoadIcecap(pEventInfo);
}
if (SUCCEEDED(hr))
{
// Save the info interface
m_pInfo = pEventInfo;
}
else
pEventInfo->Release();
return (hr);
}
//*****************************************************************************
// Record each unique function id that get's jit compiled. This list will be
// used at shut down to correlate probe values (which use Function ID) to
// their corresponding name values.
//*****************************************************************************
COM_METHOD ProfCallback::JITCompilationFinished(
FunctionID functionId,
HRESULT hrStatus)
{
if (FAILED(hrStatus))
return (S_OK);
FunctionID *p = m_FuncIdList.Append();
if (!p)
return (E_OUTOFMEMORY);
*p = functionId;
return (S_OK);
}
COM_METHOD ProfCallback::JITCachedFunctionSearchFinished(
FunctionID functionId,
COR_PRF_JIT_CACHE result)
{
if (result == COR_PRF_CACHED_FUNCTION_FOUND)
{
FunctionID *p = m_FuncIdList.Append();
if (!p)
return (E_OUTOFMEMORY);
*p = functionId;
return (S_OK);
}
return (S_OK);
}
COM_METHOD ProfCallback::Shutdown()
{
HINSTANCE hInst = 0;
HRESULT hr = S_OK;
// This is freaky: the module may be memory unmapped but still in NT's
// internal linked list of loaded modules, so we assume that icecap.dll has
// already been unloaded and don't try to do anything else with it.
// Walk the list of JIT'd functions and dump their names into the
// log file.
// Open the output file
HANDLE hOutFile = WszCreateFile(m_wszFilename, GENERIC_WRITE, 0, NULL,
CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hOutFile != INVALID_HANDLE_VALUE)
{
hr = _DumpFunctionNamesToFile(hOutFile);
CloseHandle(hOutFile);
}
// File was not opened for some reason
else
hr = HRESULT_FROM_WIN32(GetLastError());
// Free up the library.
IcecapProbes::UnloadIcecap();
return (hr);
}
#define DELIMS L" \t"
HRESULT ProfCallback::ParseConfig(WCHAR *wszConfig, DWORD *pdwRequestedEvents)
{
HRESULT hr = S_OK;
if (wszConfig != NULL)
{
for (WCHAR *wszToken = wcstok(wszConfig, DELIMS);
SUCCEEDED(hr) && wszToken != NULL;
wszToken = wcstok(NULL, DELIMS))
{
if (wszToken[0] != L'/' || wszToken[1] == L'\0')
hr = E_INVALIDARG;
// Other options.
else
{
switch (wszToken[1])
{
// Signatures
case L's':
case L'S':
{
if (_wcsnicmp(&wszToken[1], SZ_SIGNATURES, LEN_SZ_SIGNATURES) == 0)
{
WCHAR *wszOpt = &wszToken[LEN_SZ_SIGNATURES + 2];
if (_wcsicmp(wszOpt, L"none") == 0)
m_eSig = SIG_NONE;
else if (_wcsicmp(wszOpt, L"always") == 0)
m_eSig = SIG_ALWAYS;
else
goto BadArg;
}
else
goto BadArg;
}
break;
// Profiling type.
case L'f':
case L'F':
{
/*
if (_wcsicmp(&wszToken[1], L"fastcap") == 0)
*pdwRequestedEvents |= COR_PRF_MONITOR_STARTEND;
*/
// Not allowed.
WszMessageBoxInternal(NULL, L"Invalid option: fastcap. Currently unsupported in Icecap 4.1."
L" Fix being investigated, no ETA.", L"Unsupported option",
MB_OK | MB_ICONEXCLAMATION);
return (E_INVALIDARG);
}
break;
case L'c':
case L'C':
if (_wcsicmp(&wszToken[1], L"callcap") == 0)
*pdwRequestedEvents |= COR_PRF_MONITOR_ENTERLEAVE;
break;
// Bad arg.
default:
BadArg:
wprintf(L"Unknown option: '%s'\n", wszToken);
return (E_INVALIDARG);
}
}
}
}
// Check for type flags, if none given default.
if ((*pdwRequestedEvents & (/*COR_PRF_MONITOR_STARTEND |*/ COR_PRF_MONITOR_ENTERLEAVE)) == 0)
*pdwRequestedEvents |= /*COR_PRF_MONITOR_STARTEND |*/ COR_PRF_MONITOR_ENTERLEAVE;
// Provide default file name. This is done using the pattern ("%s_%08x.csv", szApp, pid).
// This gives the report tool a deterministic way to find the correct dump file for
// a given run. If you recycle a PID for the same file name with this tecnique,
// you're on your own:-)
if (SUCCEEDED(hr))
{
WCHAR rcExeName[_MAX_PATH];
GetIcecapProfileOutFile(rcExeName);
m_wszFilename = new WCHAR[wcslen(rcExeName) + 1];
wcscpy(m_wszFilename, rcExeName);
}
return (hr);
}
//*****************************************************************************
// Walk the list of loaded functions, get their names, and then dump the list
// to the output symbol file.
//*****************************************************************************
HRESULT ProfCallback::_DumpFunctionNamesToFile( // Return code.
HANDLE hOutFile) // Output file.
{
UINT i, iLen; // Loop control.
WCHAR *szName = 0; // Name buffer for fetch.
ULONG cchName, cch; // How many chars max in name.
char *rgBuff = 0; // Write buffer.
FunctionID funcId; // Orig func id
FunctionID handle; // Profiling handle.
ULONG cbOffset; // Current offset in buffer.
ULONG cbMax; // Max size of the buffer.
ULONG cb; // Working size buffer.
HRESULT hr;
// Allocate a buffer to use for name lookup.
cbMax = BUFFER_SIZE;
rgBuff = (char *) malloc(cbMax);
cchName = MAX_CLASSNAME_LENGTH;
szName = (WCHAR *) malloc(cchName * 2);
if (!rgBuff || !szName)
{
hr = OutOfMemory();
goto ErrExit;
}
// Init the copy buffer with the column header.
strcpy(rgBuff, SZ_COLUMNHDR);
cbOffset = sizeof(SZ_COLUMNHDR) - 1;
LOG((LF_CORPROF, LL_INFO10, "**PROFTABLE: MethodDesc, Handle, Name\n"));
// Walk every JIT'd method and get it's name.
for (i=0; i < IcecapProbes::GetFunctionCount(); i++)
{
// Dump the current text of the file.
if (cbMax - cbOffset < 32)
{
if (!WriteFile(hOutFile, rgBuff, cbOffset, &cb, NULL))
{
hr = HRESULT_FROM_WIN32(GetLastError());
goto ErrExit;
}
cbOffset = 0;
}
// Add the function id to the dump.
funcId = IcecapProbes::GetFunctionID(i);
handle = IcecapProbes::GetMappedID(i);
cbOffset += sprintf(&rgBuff[cbOffset], "%08x,", handle);
LOG((LF_CORPROF, LL_INFO10, "**PROFTABLE: %08x, %08x, ", funcId, handle));
RetryName:
hr = GetStringForFunction(IcecapProbes::GetFunctionID(i), szName, cchName, &cch);
if (FAILED(hr))
goto ErrExit;
// If the name was truncated, then make the name buffer bigger.
if (cch > cchName)
{
WCHAR *sz = (WCHAR *) realloc(szName, (cchName + cch + 128) * 2);
if (!sz)
{
hr = OutOfMemory();
goto ErrExit;
}
szName = sz;
cchName += cch + 128;
goto RetryName;
}
LOG((LF_CORPROF, LL_INFO10, "%S\n", szName));
// If the name cannot fit successfully into the disk buffer (assuming
// worst case scenario of 2 bytes per unicode char), then the buffer
// is too small and needs to get flushed to disk.
if (cbMax - cbOffset < (cch * 2) + sizeof(SZ_CRLF))
{
// If this fires, it means that the copy buffer was too small.
_ASSERTE(cch > 0);
// Dump everything we do have before the truncation.
if (!WriteFile(hOutFile, rgBuff, cbOffset, &cb, NULL))
{
hr = HRESULT_FROM_WIN32(GetLastError());
goto ErrExit;
}
// Reset the buffer to use the whole thing.
cbOffset = 0;
}
// Convert the name buffer into the disk buffer.
iLen = WideCharToMultiByte(CP_ACP, 0,
szName, -1,
&rgBuff[cbOffset], cbMax - cbOffset,
NULL, NULL);
if (!iLen)
{
hr = HRESULT_FROM_WIN32(GetLastError());
goto ErrExit;
}
--iLen;
strcpy(&rgBuff[cbOffset + iLen], SZ_CRLF);
cbOffset = cbOffset + iLen + sizeof(SZ_CRLF) - 1;
}
// If there is data left in the write buffer, flush it.
if (cbOffset)
{
if (!WriteFile(hOutFile, rgBuff, cbOffset, &cb, NULL))
{
hr = HRESULT_FROM_WIN32(GetLastError());
goto ErrExit;
}
}
ErrExit:
if (rgBuff)
free(rgBuff);
if (szName)
free(szName);
return (hr);
}
//*****************************************************************************
// Given a function id, turn it into the corresponding name which will be used
// for symbol resolution.
//*****************************************************************************
HRESULT ProfCallback::GetStringForFunction( // Return code.
FunctionID functionId, // ID of the function to get name for.
WCHAR *wszName, // Output buffer for name.
ULONG cchName, // Max chars for output buffer.
ULONG *pcName) // Return name (truncation check).
{
IMetaDataImport *pImport = 0; // Metadata for reading.
mdMethodDef funcToken; // Token for metadata.
HRESULT hr = S_OK;
*wszName = 0;
// Get the scope and token for the current function
hr = m_pInfo->GetTokenAndMetaDataFromFunction(functionId, IID_IMetaDataImport,
(IUnknown **) &pImport, &funcToken);
if (SUCCEEDED(hr))
{
// Initially, get the size of the function name string
ULONG cFuncName;
mdTypeDef classToken;
WCHAR wszFuncBuffer[BUF_SIZE];
WCHAR *wszFuncName = wszFuncBuffer;
PCCOR_SIGNATURE pvSigBlob;
ULONG cbSig;
RetryName:
hr = pImport->GetMethodProps(funcToken, &classToken,
wszFuncBuffer, BUF_SIZE, &cFuncName,
NULL,
&pvSigBlob, &cbSig,
NULL, NULL);
// If the function name is longer than the buffer, try again
if (hr == CLDB_S_TRUNCATION)
{
wszFuncName = (WCHAR *)_alloca(cFuncName * sizeof(WCHAR));
goto RetryName;
}
// Now get the name of the class
if (SUCCEEDED(hr))
{
// Class name
WCHAR wszClassBuffer[BUF_SIZE];
WCHAR *wszClassName = wszClassBuffer;
ULONG cClassName = BUF_SIZE;
// Not a global function
if (classToken != mdTypeDefNil)
{
RetryClassName:
hr = pImport->GetTypeDefProps(classToken, wszClassName,
cClassName, &cClassName, NULL,
NULL);
if (hr == CLDB_S_TRUNCATION)
{
wszClassName = (WCHAR *)_alloca(cClassName * sizeof(WCHAR));
goto RetryClassName;
}
}
// It's a global function
else
wszClassName = L"<Global>";
if (SUCCEEDED(hr))
{
*pcName = wcslen(wszClassName) + sizeof(NAMESPACE_SEPARATOR_WSTR) +
wcslen(wszFuncName) + 1;
// Check if the provided buffer is big enough
if (cchName < *pcName)
{
hr = S_FALSE;
}
// Otherwise, the buffer is big enough
else
{
wcscat(wszName, wszClassName);
wcscat(wszName, NAMESPACE_SEPARATOR_WSTR);
wcscat(wszName, wszFuncName);
// Add the formatted signature only if need be.
if (m_eSig == SIG_ALWAYS)
{
CQuickBytes qb;
PrettyPrintSig(pvSigBlob, cbSig, wszName,
&qb, pImport);
// Copy big name for output, make sure it is null.
ULONG iCopy = qb.Size() / sizeof(WCHAR);
if (iCopy > cchName)
iCopy = cchName;
wcsncpy(wszName, (LPCWSTR) qb.Ptr(), cchName);
wszName[cchName - 1] = 0;
}
// Change spaces and commas into underscores so
// that icecap doesn't have problems with them.
WCHAR *sz;
for (sz = (WCHAR *) wszName; *sz; sz++)
{
switch (*sz)
{
case L' ':
case L',':
case L'?':
case L'@':
*sz = L'_';
break;
}
}
hr = S_OK;
}
}
}
}
if (pImport) pImport->Release();
return (hr);
}
| 32.652482 | 125 | 0.485393 | npocmaka |
c58e60d33e3f09717504d19cc55fa2fc2271b104 | 487 | cpp | C++ | abc068/abc068_b.cpp | crazystylus/AtCoderPractice | 8e0f56a9b3905e11f83f351af66af5bfed8606b2 | [
"MIT"
] | null | null | null | abc068/abc068_b.cpp | crazystylus/AtCoderPractice | 8e0f56a9b3905e11f83f351af66af5bfed8606b2 | [
"MIT"
] | null | null | null | abc068/abc068_b.cpp | crazystylus/AtCoderPractice | 8e0f56a9b3905e11f83f351af66af5bfed8606b2 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ull unsigned long long
#define rep(i, n) for (int i = 0; i < n; i++)
const int mod = 1e9 + 7; // 10^9 + 7;
const int N = 1e5 + 1;
///////////////////
// multiply 1 with 2 till it is <= n
int n, op;
void solve() {
op = 1;
cin >> n;
// if (n == 1)
// return (void)(cout << "0\n");
while (op <= n)
op = op << 1;
cout << op / 2 << '\n';
}
int main() {
solve();
return 0;
} | 21.173913 | 45 | 0.478439 | crazystylus |
c5953e50037c06f0fd50b203f3a246e6bf433296 | 1,625 | hpp | C++ | src/utility/debug_log.hpp | mnewhouse/tselements | bd1c6724018e862156948a680bb1bc70dd28bef6 | [
"MIT"
] | null | null | null | src/utility/debug_log.hpp | mnewhouse/tselements | bd1c6724018e862156948a680bb1bc70dd28bef6 | [
"MIT"
] | null | null | null | src/utility/debug_log.hpp | mnewhouse/tselements | bd1c6724018e862156948a680bb1bc70dd28bef6 | [
"MIT"
] | null | null | null | /*
* TS Elements
* Copyright 2015-2018 M. Newhouse
* Released under the MIT license.
*/
#pragma once
#include "logger.hpp"
#include <cstdint>
namespace ts
{
namespace debug
{
struct DebugTag {};
using logger::flush;
using logger::endl;
namespace level
{
static const std::uint32_t essential = 0;
static const std::uint32_t relevant = 1;
static const std::uint32_t auxiliary = 2;
}
#define DEBUG_ESSENTIAL debug::Log(debug::level::essential)
#define DEBUG_RELEVANT debug::Log(debug::level::relevant)
#define DEBUG_AUXILIARY debug::Log(debug::level::auxiliary)
struct DebugConfig
{
std::uint32_t debug_level = level::essential;
};
}
namespace logger
{
template <>
struct LoggerTraits<debug::DebugTag>
{
using config_type = debug::DebugConfig;
using dispatcher_type = LogFileDispatcher;
};
}
namespace debug
{
struct Log
{
public:
Log(std::uint32_t debug_level);
template <typename T>
Log& operator<<(const T& value);
private:
logger::LoggerFront<DebugTag> logger_;
std::uint32_t debug_level_;
std::uint32_t debug_config_level_;
};
using ScopedLogger = logger::ScopedLogger<DebugTag>;
inline Log::Log(std::uint32_t debug_level)
: logger_(),
debug_level_(debug_level),
debug_config_level_(logger_.config().debug_level)
{
}
template <typename T>
Log& Log::operator<<(const T& value)
{
if (debug_config_level_ >= debug_level_)
{
logger_ << value;
}
return *this;
}
}
}
| 18.895349 | 59 | 0.634462 | mnewhouse |
c599c13d52611de45949f9f2d2297c4b3e93e13a | 452 | cpp | C++ | src/luogu/P1439/33162768_ua_50_442ms_128000k_noO2.cpp | lnkkerst/oj-codes | d778489182d644370b2a690aa92c3df6542cc306 | [
"MIT"
] | null | null | null | src/luogu/P1439/33162768_ua_50_442ms_128000k_noO2.cpp | lnkkerst/oj-codes | d778489182d644370b2a690aa92c3df6542cc306 | [
"MIT"
] | null | null | null | src/luogu/P1439/33162768_ua_50_442ms_128000k_noO2.cpp | lnkkerst/oj-codes | d778489182d644370b2a690aa92c3df6542cc306 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#define int long long
using namespace std;
signed main() {
int n;
cin >> n;
vector<int> a(n + 1), b(n + 1);
vector<vector<int> > dp(n + 1, vector<int>(n + 1, 0));
for(int i = 1; i <= n; ++i) cin >> a[i];
for(int i = 1; i <= n; ++i) cin >> b[i];
for(int i = 1; i <= n; ++i)
for(int j = 1; j <= n; ++j)
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) + (a[i] == b[j]);
cout << dp.back().back();
return 0;
} | 25.111111 | 63 | 0.49115 | lnkkerst |
c599d2d698815e65a40fbcc4222a32e62849ea04 | 1,656 | cxx | C++ | StRoot/StFgtPool/StFgtClusterTools/StFgtCosmicAlignment.cxx | xiaohaijin/RHIC-STAR | a305cb0a6ac15c8165bd8f0d074d7075d5e58752 | [
"MIT"
] | 2 | 2018-12-24T19:37:00.000Z | 2022-02-28T06:57:20.000Z | StRoot/StFgtPool/StFgtClusterTools/StFgtCosmicAlignment.cxx | xiaohaijin/RHIC-STAR | a305cb0a6ac15c8165bd8f0d074d7075d5e58752 | [
"MIT"
] | null | null | null | StRoot/StFgtPool/StFgtClusterTools/StFgtCosmicAlignment.cxx | xiaohaijin/RHIC-STAR | a305cb0a6ac15c8165bd8f0d074d7075d5e58752 | [
"MIT"
] | null | null | null | #include "StFgtCosmicAlignment.h"
#include <math.h>
const int MaxDisc=3;
//initial z offsets for disks
float z0[MaxDisc]={0.0, 16.51, 2.0*16.51};
//center of rotaion
float x00=2.0, y00=-26.0, z00=0.0;
//Alignment xyz offsets and Euler angles for each disc
float par[MaxDisc][6]= { {0.0, 0.0, 0.0, 0.0, 0.0, 0.0},
{-0.0314,-0.1427, 0.1298, -0.0746, 0.0247, -0.0311},
{0.0228, 0.3543, 0.0815, -0.1006, -0.0110, -0.0372}};
void rot(float x, float y, float z,
float x0,float y0,float z0,
float o, float p, float q,
float &xx,float &yy,float &zz){
//printf("inp = %8.3f %8.3f %8.3f\n",x,y,z);
//printf("off = %8.3f %8.3f %8.3f\n",x0,y0,z0);
float co=cos(o), so=sin(o);
float cp=cos(p), sp=sin(p);
float cq=cos(q), sq=sin(q);
float x1=x+x0-x00;
float y1=y+y0-y00;
float z1=z+z0-z00;
//printf("opq = %8.3f %8.3f %8.3f\n",o,p,q);
//printf("out1 = %8.3f %8.3f %8.3f\n",xx,yy,zz);
//printf("cos = %8.3f %8.3f %8.3f\n",co,cp,cq);
//printf("sin = %8.3f %8.3f %8.3f\n",so,sp,sq);
xx=x1*co*cp + y1*(-cq*sp+sq*so*cp) + z1*( sq*sp+cq*so*cp) + x00;
yy=x1*co*sp + y1*( cq*cp+sq*so*sp) + z1*(-sq*cp+cq*so*sp) + y00;
zz=x1*(-so) + y1*( sq*co ) + z1*( cq*co ) + z00;
//printf("out2 = %8.3f %8.3f %8.3f\n",xx,yy,zz);
};
void getAlign(int idisc, float pl, float rl, float &x, float &y, float &z, float &p, float &r){
float xx=rl * cos(pl);
float yy=rl * sin(pl);
rot(xx,yy,0.0,par[idisc][0],par[idisc][1],par[idisc][2],par[idisc][3],par[idisc][4],par[idisc][5],x,y,z);
z+=z0[idisc];
r=sqrt(x*x + y*y);
p=atan2(y,x);
};
| 38.511628 | 107 | 0.539251 | xiaohaijin |
c59c605d4a34c43141f0afdca8e824d12872150a | 2,342 | hpp | C++ | database/L1/demos/q5_simplified_100g/kernel/q5simplified.hpp | vmayoral/Vitis_Libraries | 2323dc5036041e18242718287aee4ce66ba071ef | [
"Apache-2.0"
] | 1 | 2021-06-14T17:02:06.000Z | 2021-06-14T17:02:06.000Z | database/L1/demos/q5_simplified_100g/kernel/q5simplified.hpp | vmayoral/Vitis_Libraries | 2323dc5036041e18242718287aee4ce66ba071ef | [
"Apache-2.0"
] | null | null | null | database/L1/demos/q5_simplified_100g/kernel/q5simplified.hpp | vmayoral/Vitis_Libraries | 2323dc5036041e18242718287aee4ce66ba071ef | [
"Apache-2.0"
] | 1 | 2021-04-28T05:58:38.000Z | 2021-04-28T05:58:38.000Z | /*
* Copyright 2019 Xilinx, 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 "table_dt.hpp"
#define AP_INT_MAX_W 4096
#include <ap_int.h>
#define L_DEPTH (L_MAX_ROW / VEC_LEN)
#define O_DEPTH (O_MAX_ROW / VEC_LEN)
#define Q5E2_HJ_HW_J 18
#define Q5E2_HJ_AW 19
#define Q5E2_HJ_BVW 20 // only used when enable bloomfilter
#define Q5E2_HJ_HW_P 3
#define Q5E2_HJ_PU_NM (1 << Q5E2_HJ_HW_P) // number of process unit
#define Q5E2_HJ_MODE (1) // 0 -radix 1 - Jenkins
#define Q5E2_HJ_CH_NM 4 // channel number
// platform information
#define BUFF_DEPTH (O_MAX_ROW / 8 * 2)
extern "C" void q5simplified(ap_uint<8 * KEY_SZ * VEC_LEN> buf_l_orderkey[L_DEPTH],
ap_uint<8 * MONEY_SZ * VEC_LEN> buf_l_extendedprice[L_DEPTH],
ap_uint<8 * MONEY_SZ * VEC_LEN> buf_l_discount[L_DEPTH],
const int l_nrow,
ap_uint<8 * KEY_SZ * VEC_LEN> buf_o_orderkey[O_DEPTH],
ap_uint<8 * DATE_SZ * VEC_LEN> buf_o_orderdate[O_DEPTH],
const int o_nrow,
// temp
ap_uint<8 * KEY_SZ> buf0[BUFF_DEPTH],
ap_uint<8 * KEY_SZ> buf1[BUFF_DEPTH],
ap_uint<8 * KEY_SZ> buf2[BUFF_DEPTH],
ap_uint<8 * KEY_SZ> buf3[BUFF_DEPTH],
ap_uint<8 * KEY_SZ> buf4[BUFF_DEPTH],
ap_uint<8 * KEY_SZ> buf5[BUFF_DEPTH],
ap_uint<8 * KEY_SZ> buf6[BUFF_DEPTH],
ap_uint<8 * KEY_SZ> buf7[BUFF_DEPTH],
// output
ap_uint<8 * MONEY_SZ * 2> buf_result[1]);
| 43.37037 | 90 | 0.577284 | vmayoral |
c59e1d492e86efd34c133c287d1548ea3bf637db | 1,119 | cpp | C++ | pomodoro/logic-config.cpp | ximenpo/easy-pomodoro | c0eed81e824dc7348816f059f68a51ba0ddb0810 | [
"MIT"
] | null | null | null | pomodoro/logic-config.cpp | ximenpo/easy-pomodoro | c0eed81e824dc7348816f059f68a51ba0ddb0810 | [
"MIT"
] | null | null | null | pomodoro/logic-config.cpp | ximenpo/easy-pomodoro | c0eed81e824dc7348816f059f68a51ba0ddb0810 | [
"MIT"
] | null | null | null | #include <stddef.h>
#include <stdint.h>
#include <string.h>
#include "logic-config.h"
size_t storage_load(uint8_t* begin, uint8_t* end);
void storage_save(uint8_t* begin, uint8_t* end);
void logic_config::init() {
const char DEFAULT_SSID[] = "pomodoro";
const char DEFAULT_PASSWORDD[] = "88888888";
memcpy(this->ap_ssid, DEFAULT_SSID, sizeof(DEFAULT_SSID));
memcpy(this->ap_password, DEFAULT_PASSWORDD, sizeof(DEFAULT_PASSWORDD));
memset(this->wifi_ssid, 0, sizeof(this->wifi_ssid));
memset(this->wifi_password, 0, sizeof(this->wifi_password));
memset(this->app_id, 0, sizeof(this->app_id));
memset(this->app_key, 0, sizeof(this->app_key));
this->work_minites = 25;
this->break_minites = 5;
this->long_break_minites = 15;
this->long_break_work_times = 4;
this->confirm_seconds = 5;
this->slient_mode = 0;
}
void logic_config::load() {
if (!storage_load(&this->__storage_begin__, &this->__storage_end__)) {
this->init();
}
}
void logic_config::save() {
storage_save(&this->__storage_begin__, &this->__storage_end__);
}
| 27.292683 | 74 | 0.679178 | ximenpo |
c5a0f36daed9457c007f555f9a83f6f2d18384ba | 1,257 | cpp | C++ | kvm_gadget/src/kvm_mouse.cpp | pspglb/kvm | 2dc3c4cc331dedaf5245e5c8a24bcba02b6ded32 | [
"BSD-3-Clause"
] | 26 | 2020-12-03T11:13:42.000Z | 2022-03-25T05:36:33.000Z | kvm_gadget/src/kvm_mouse.cpp | mtlynch/kvm | f0128edd493a758197a683cbb40dd409d16235e5 | [
"BSD-3-Clause"
] | 4 | 2021-01-28T19:32:17.000Z | 2021-06-01T15:01:42.000Z | kvm_gadget/src/kvm_mouse.cpp | mtlynch/kvm | f0128edd493a758197a683cbb40dd409d16235e5 | [
"BSD-3-Clause"
] | 8 | 2020-12-04T01:30:21.000Z | 2021-12-01T11:19:11.000Z | // Copyright 2020 Christopher A. Taylor
#include "kvm_mouse.hpp"
#include "kvm_serializer.hpp"
#include "kvm_logger.hpp"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
namespace kvm {
static logger::Channel Logger("Gadget");
//------------------------------------------------------------------------------
// MouseEmulator
bool MouseEmulator::Initialize()
{
fd = open("/dev/hidg1", O_RDWR);
if (fd < 0) {
Logger.Error("Failed to open mouse emulator device");
return false;
}
Logger.Info("Mouse emulator ready");
return true;
}
void MouseEmulator::Shutdown()
{
if (fd >= 0) {
close(fd);
fd = -1;
}
}
bool MouseEmulator::SendReport(uint8_t button_status, uint16_t x, uint16_t y)
{
std::lock_guard<std::mutex> locker(Lock);
char buffer[5] = {0};
buffer[0] = button_status;
WriteU16_LE(buffer + 1, x);
WriteU16_LE(buffer + 3, y);
//Logger.Info("Writing report: ", HexDump((const uint8_t*)buffer, 5));
ssize_t written = write(fd, buffer, 5);
if (written != 5) {
Logger.Error("Failed to write mouse device: errno=", errno);
return false;
}
return true;
}
} // namespace kvm
| 19.640625 | 80 | 0.584726 | pspglb |
c5a6671cf32c952770c4dccef896eacc5755a6c4 | 7,831 | cc | C++ | framework/window/linux/x_window.cc | ans-hub/gdm_framework | 4218bb658d542df2c0568c4d3aac813cd1f18e1b | [
"MIT"
] | 1 | 2020-12-30T23:50:01.000Z | 2020-12-30T23:50:01.000Z | framework/window/linux/x_window.cc | ans-hub/gdm_framework | 4218bb658d542df2c0568c4d3aac813cd1f18e1b | [
"MIT"
] | null | null | null | framework/window/linux/x_window.cc | ans-hub/gdm_framework | 4218bb658d542df2c0568c4d3aac813cd1f18e1b | [
"MIT"
] | null | null | null | // *************************************************************
// File: x_window.cc
// Author: Novoselov Anton @ 2018
// URL: https://github.com/ans-hub/gdm_framework
// *************************************************************
#include "x_window.h"
// --public
gdm::XWindow::XWindow()
: disp_{ XOpenDisplay(NULL) }
, root_{}
, self_{}
, event_{}
, fullscreen_{false}
, vmode_{-1}
, width_{0}
, height_{0}
{
if (!disp_)
throw WinException("XOpenDisplay failed", errno);
root_ = XDefaultRootWindow(disp_);
auto ask_wm_notify_closing = [&]()
{
wm_protocols_ = XInternAtom(disp_, "WM_PROTOCOLS", false);
wm_delete_window_ = XInternAtom(disp_, "WM_DELETE_WINDOW", false);
}();
}
gdm::XWindow::XWindow(XWindow&& rhs)
: disp_{ rhs.disp_ }
, root_{ rhs.root_ }
, self_{ rhs.self_ }
, event_{ rhs.event_ }
, fullscreen_{ rhs.fullscreen_ }
, vmode_{ rhs.vmode_ }
, width_{ rhs.width_ }
, height_{ rhs.height_ }
, wm_protocols_ { rhs.wm_protocols_ }
, wm_delete_window_ { rhs.wm_delete_window_ }
{
rhs.disp_ = nullptr;
rhs.root_ = 0;
rhs.self_ = 0;
rhs.fullscreen_ = false;
rhs.vmode_ = 0;
rhs.width_ = 0;
rhs.height_ = 0;
rhs.wm_protocols_ = 0;
rhs.wm_delete_window_ = 0;
}
gdm::XWindow::~XWindow()
{
if (vmode_ != -1)
helpers::ChangeVideoMode(disp_, root_, vmode_);
if (self_) {
XDestroyWindow(disp_, self_);
XFlush(disp_);
}
if (disp_)
XCloseDisplay(disp_);
}
void gdm::XWindow::Show()
{
XMapWindow(disp_, self_);
XFlush(disp_);
}
void gdm::XWindow::Hide()
{
XUnmapWindow(disp_, self_);
XFlush(disp_);
}
void gdm::XWindow::Move(int x, int y)
{
XMoveWindow(disp_, self_, x, y);
}
void gdm::XWindow::Close()
{
helpers::SendCloseWindowNotify(disp_, root_, self_);
}
void gdm::XWindow::HideCursor()
{
helpers::HideCursor(disp_, self_);
}
void gdm::XWindow::UnhideCursor()
{
helpers::UnhideCursor(disp_, self_);
}
void gdm::XWindow::SetFocus()
{
XRaiseWindow(disp_, self_);
XSetInputFocus(disp_, self_, RevertToNone, CurrentTime);
}
bool gdm::XWindow::ToggleFullscreen()
{
int curr = helpers::GetCurrentVideoMode(disp_, root_);
return this->ToggleFullscreen(curr);
}
bool gdm::XWindow::ToggleFullscreen(int mode)
{
if (mode < 0)
return false;
this->Move(0,0);
vmode_ = helpers::ChangeVideoMode(disp_, root_, mode);
helpers::GetWindowDimension(disp_, root_, &width_, &height_);
int wait = 1000; // todo: make more smart way to wait while resolution will be changed
do {
timespec ts;
ts.tv_sec = wait / 1000;
ts.tv_nsec = wait * 1000000;
while ((nanosleep(&ts, &ts) == -1) && (errno == EINTR)) { }
} while (GrabSuccess != XGrabPointer(
disp_, self_, True, None, GrabModeAsync, GrabModeAsync,
self_, None, CurrentTime));
SetFocus();
XWarpPointer(disp_, None, root_, 0, 0, 0, 0, 0, 0); // todo: place in the middle of the scr
bool result = helpers::SendToggleFullscreenNotify(disp_, root_, self_);
fullscreen_ ^= result;
if (!fullscreen_)
XUngrabPointer(disp_, CurrentTime);
return true;
}
void gdm::XWindow::ToggleOnTop()
{
helpers::SendToggleOnTopNotify(disp_, root_, self_);
}
bool gdm::XWindow::IsClosed()
{
if (XCheckTypedWindowEvent(disp_, self_, ClientMessage, &event_)) {
if (event_.xclient.message_type == wm_protocols_ &&
event_.xclient.data.l[0] == (int)wm_delete_window_) {
return true;
}
}
return false;
}
// Exposed() - only if window was moved, overlapperd, etc
// Up window (need to hide wm ontop elements after change resolution)
// Redraw() - every time
void gdm::XWindow::Render()
{
if (XCheckWindowEvent(disp_, self_, ExposureMask, &event_)) {
Exposed();
helpers::GetWindowDimension(disp_, self_, &width_, &height_);
}
if (fullscreen_ && XCheckTypedWindowEvent(disp_, self_, VisibilityNotify, &event_)) {
XRaiseWindow(disp_, self_);
helpers::GetWindowDimension(disp_, self_, &width_, &height_);
}
Redraw();
}
auto gdm::XWindow::GetNextEvent()
{
XNextEvent(disp_, &event_);
switch (event_.type) {
case Expose : return WinEvent::EXPOSE;
case KeyPress : return WinEvent::KEYPRESS;
case KeyRelease : return WinEvent::KEYRELEASE;
case ButtonPress : return WinEvent::MOUSEPRESS;
case ButtonRelease : return WinEvent::MOUSERELEASE;
case MotionNotify : return WinEvent::MOUSEMOVE;
default : return WinEvent::NONSENCE;
}
}
Btn gdm::XWindow::ReadKeyboardBtn(BtnType t) const
{
XEvent event;
auto buf = Btn::NONE;
long type = 1L << static_cast<int>(t);
if (XCheckWindowEvent(disp_, self_, type, &event))
{
auto key = XkbKeycodeToKeysym(disp_, event.xkey.keycode, 0, 0);
char buff[32];
XLookupString(&event.xkey, buff, 32, &key, NULL); // see note below
buf = static_cast<Btn>(key);
}
return buf;
// Note : This string is necessary if somewho press key in layout
// differ than ISO Latin-1
}
Btn gdm::XWindow::ReadMouseBtn(BtnType t) const
{
XEvent event;
auto buf = Btn::NONE;
long type = 1L << static_cast<int>(t);
if (XCheckWindowEvent(disp_, self_, type, &event))
{
buf = static_cast<Btn>(event.xbutton.button + kMouseBtnOffset);
}
return buf;
}
// Returns mouse pos every time its requered. When required non-glob
// there are may be situation when first result returns position without
// window decoration, and other results are with it. Thus more preffered
// use glob == true
Pos gdm::XWindow::ReadMousePos(bool glob) const
{
Window root_ret;
Window child_ret;
int x_rel {0};
int y_rel {0};
int x_win {0};
int y_win {0};
unsigned int mask;
XQueryPointer(
disp_, self_, &root_ret, &child_ret, &x_rel, &y_rel, &x_win, &y_win, &mask);
if (glob)
return Pos{x_rel, y_rel};
else
return Pos{x_win, y_win};
}
// Returns correct mouse pos only if moved, else default value for Pos
Pos gdm::XWindow::ListenMousePos() const
{
// Other versions - http://www.rahul.net/kenton/perf.html
Pos buf {};
if (XCheckWindowEvent(disp_, self_, PointerMotionMask, &event_))
{
XSync(disp_, true);
buf.x = event_.xmotion.x;
buf.y = event_.xmotion.y;
}
return buf;
}
// Sets mouse pos relative to root
// todo: incorrect working
void gdm::XWindow::MoveMousePos(int x, int y)
{
SetFocus();
XWarpPointer(disp_, self_, self_, 0, 0, 0, 0, x, y);
}
// From here: https://goo.gl/W3zqgh
bool gdm::XWindow::IsKeyboardBtnPressed(KbdBtn btn) const
{
if (btn == KbdBtn::NONE)
return false;
KeyCode keycode = XKeysymToKeycode(disp_, static_cast<KeySym>(btn));
if (keycode) {
char keys[32];
XQueryKeymap(disp_, keys);
return (keys[keycode / 8] & (1 << (keycode % 8))) != 0;
}
else
return false;
}
// From here: https://goo.gl/W3zqgh
bool gdm::XWindow::IsMouseBtnPressed(MouseBtn btn) const
{
Window root_ret;
Window child_ret;
int x_rel {0};
int y_rel {0};
int x_win {0};
int y_win {0};
unsigned int btns;
XQueryPointer(
disp_, self_, &root_ret, &child_ret, &x_rel, &y_rel, &x_win, &y_win, &btns);
switch (btn)
{
case MouseBtn::LMB: return btns & Button1Mask;
case MouseBtn::RMB: return btns & Button3Mask;
case MouseBtn::MMB: return btns & Button2Mask;
case MouseBtn::WH_UP: return false;
case MouseBtn::WH_DWN: return false;
default: return false;
}
return false;
}
// Ask WM to notify when it should close the window
void gdm::XWindow::NotifyWhenClose()
{
XSetWMProtocols(disp_, self_, &wm_delete_window_, 1);
}
// Note : XCheckWindowEvent doesn't wait for next event (like XNextEvent)
// but check if event is present. Function used that function only works
// with masked events. For not masked events - XCheckTypedWindowEvent() | 24.395639 | 93 | 0.653556 | ans-hub |
c5a94600268ac8606b8249272b99cd6cb5567a26 | 16,792 | cpp | C++ | src/evaluation.cpp | x0x/hive | 5cd9cc82f469b184dcf0a8161ba432d6abf79823 | [
"MIT"
] | null | null | null | src/evaluation.cpp | x0x/hive | 5cd9cc82f469b184dcf0a8161ba432d6abf79823 | [
"MIT"
] | null | null | null | src/evaluation.cpp | x0x/hive | 5cd9cc82f469b184dcf0a8161ba432d6abf79823 | [
"MIT"
] | null | null | null | #include "../include/types.hpp"
#include "../include/bitboard.hpp"
#include "../include/position.hpp"
#include "../include/evaluation.hpp"
#include "../include/piece_square_tables.hpp"
#include <cassert>
#include <stdlib.h>
namespace Evaluation
{
EvalData::EvalData(const Board& board)
{
Square kings[] = { board.get_pieces<WHITE, KING>().bitscan_forward(),
board.get_pieces<BLACK, KING>().bitscan_forward() };
for (auto turn : { WHITE, BLACK })
king_zone[turn] = Bitboards::get_attacks<KING>(kings[turn], Bitboard());
}
MixedScore material(Board board, EvalData& eval)
{
eval.fields[WHITE].material = MixedScore(0, 0);
eval.fields[BLACK].material = MixedScore(0, 0);
for (auto piece : { PAWN, KNIGHT, BISHOP, ROOK, QUEEN })
{
eval.fields[WHITE].material += piece_value[piece] * board.get_pieces(WHITE, piece).count();
eval.fields[BLACK].material += piece_value[piece] * board.get_pieces(BLACK, piece).count();
}
return eval.fields[WHITE].material - eval.fields[BLACK].material;
}
MixedScore piece_square_value(Board board, EvalData& eval)
{
eval.fields[WHITE].placement = MixedScore(0, 0);
eval.fields[BLACK].placement = MixedScore(0, 0);
Bitboard bb;
for (auto piece : { PAWN, KNIGHT, BISHOP, ROOK, QUEEN, KING })
{
for (auto turn : { WHITE, BLACK })
{
bb = board.get_pieces(turn, piece);
while (bb)
eval.fields[turn].placement += piece_square(piece, bb.bitscan_forward_reset(), turn);
}
}
return eval.fields[WHITE].placement - eval.fields[BLACK].placement;
}
MixedScore pawns(const Board& board, EvalData& data)
{
// Bonuses and penalties
constexpr MixedScore DoubledPenalty(-13, -51);
constexpr MixedScore IsolatedPenalty(-3, -15);
constexpr MixedScore BackwardPenalty(-9, -22);
constexpr MixedScore IslandPenalty(-3, -12);
constexpr MixedScore NonPushedCentralPenalty(-35, -50);
constexpr MixedScore PassedBonus[] = { MixedScore( 0, 0), MixedScore( 0, 0),
MixedScore( 7, 27), MixedScore( 16, 32),
MixedScore( 17, 40), MixedScore( 64, 71),
MixedScore(170, 174), MixedScore(278, 262) };
// Some helpers
constexpr Direction Up = 8;
PawnStructure& wps = data.pawns[WHITE];
PawnStructure& bps = data.pawns[BLACK];
const Bitboard pawns[] = { board.get_pieces<WHITE, PAWN>(), board.get_pieces<BLACK, PAWN>() };
// Build fields required in other evaluation terms
wps.attacks = Bitboards::get_attacks_pawns<WHITE>(pawns[WHITE]);
bps.attacks = Bitboards::get_attacks_pawns<BLACK>(pawns[BLACK]);
wps.span = wps.attacks.fill< Up>();
bps.span = bps.attacks.fill<-Up>();
wps.outposts = pawns[WHITE].shift< Up>() & ~wps.span;
bps.outposts = pawns[BLACK].shift<-Up>() & ~bps.span;
wps.open_files = ~(pawns[WHITE].fill< Up>().fill<-Up>());
bps.open_files = ~(pawns[BLACK].fill<-Up>().fill< Up>());
wps.passed = pawns[WHITE] & ~(bps.span | pawns[BLACK].fill<-Up>());
bps.passed = pawns[BLACK] & ~(wps.span | pawns[WHITE].fill< Up>());
// Isolated pawns
Bitboard isolated[] = { pawns[WHITE] & Bitboards::isolated_mask(wps.open_files),
pawns[BLACK] & Bitboards::isolated_mask(bps.open_files) };
// Doubled pawns (excluding the frontmost doubled pawn)
Bitboard doubled[] = { pawns[WHITE] & pawns[WHITE].fill_excluded<-Up>(),
pawns[BLACK] & pawns[BLACK].fill_excluded< Up>() };
// Backward pawns (not defended and cannot safely push)
Bitboard backward[] = { pawns[WHITE] & (~wps.span.shift<-Up>() & bps.attacks).shift<-Up>(),
pawns[BLACK] & (~bps.span.shift< Up>() & wps.attacks).shift< Up>() };
// Build pawn structure scores
for (auto turn : { WHITE, BLACK })
{
// Basic penalties
data.fields[turn].pieces[PAWN] = DoubledPenalty * doubled[turn].count()
+ IsolatedPenalty * isolated[turn].count()
+ BackwardPenalty * backward[turn].count()
+ IslandPenalty * Bitboards::file_count(data.pawns[turn].open_files);
// Passed pawn scores
Bitboard b = data.pawns[turn].passed;
while (b)
data.fields[turn].pieces[PAWN] += PassedBonus[rank(b.bitscan_forward_reset(), turn)];
// Update attack tables
data.attacks[turn].push<PAWN>(data.pawns[turn].attacks);
}
return data.fields[WHITE].pieces[PAWN] - data.fields[BLACK].pieces[PAWN];
}
template <PieceType PIECE, Turn TURN>
MixedScore piece(const Board& board, Bitboard occupancy, EvalData& data)
{
// Various bonuses and penalties
constexpr MixedScore RooksConnected(15, 5);
constexpr MixedScore RookOn7th(10, 15);
constexpr MixedScore RookOnOpen(20, 7);
constexpr MixedScore BehindEnemyLines(5, 4);
constexpr MixedScore SafeBehindEnemyLines(25, 10);
constexpr MixedScore BishopPair(10, 20);
constexpr MixedScore DefendedByPawn(5, 1);
// Mobility scores
constexpr MixedScore BonusPerMove(10, 10);
constexpr MixedScore NominalMoves = PIECE == KNIGHT ? MixedScore(4, 4)
: PIECE == BISHOP ? MixedScore(5, 5)
: PIECE == ROOK ? MixedScore(4, 6)
: MixedScore(7, 9); // QUEEN
MixedScore score(0, 0);
Bitboard b = board.get_pieces<TURN, PIECE>();
while (b)
{
Square square = b.bitscan_forward_reset();
Bitboard attacks = Bitboards::get_attacks<PIECE>(square, occupancy);
data.attacks[TURN].push<PIECE>(attacks);
if (attacks & data.king_zone[~TURN])
data.king_attackers[~TURN].set(square);
int safe_squares = (attacks & ~data.attacks[~TURN].get_less_valuable<PIECE>()).count();
score += (MixedScore(safe_squares, safe_squares) - NominalMoves) * BonusPerMove;
// TODO: other terms
if (PIECE == KNIGHT)
{
}
else if (PIECE == BISHOP)
{
}
else if (PIECE == ROOK)
{
// Connects to another rook?
score += RooksConnected * (b & attacks).count();
}
else if (PIECE == QUEEN)
{
}
}
// General placement terms
b = board.get_pieces<TURN, PIECE>();
// Behind enemy lines?
score += BehindEnemyLines * NominalMoves * (b & ~data.pawns[~TURN].span).count();
// Set-wise terms
if (PIECE == KNIGHT)
{
// Defended by pawns?
score += DefendedByPawn * (b & data.pawns[TURN].attacks).count();
// Additional bonus if behind enemy lines and defended by pawns
score += SafeBehindEnemyLines * (b & ~data.pawns[~TURN].span & data.pawns[TURN].attacks).count();
}
else if (PIECE == BISHOP)
{
// Defended by pawns?
score += DefendedByPawn * (b & data.pawns[TURN].attacks).count();
// Additional bonus if behind enemy lines and defended by pawns
score += SafeBehindEnemyLines * (b & ~data.pawns[~TURN].span & data.pawns[TURN].attacks).count();
// Bishop pair?
if ((b & Bitboards::square_color[WHITE]) && (b & Bitboards::square_color[BLACK]))
score += BishopPair;
}
else if (PIECE == ROOK)
{
// Rooks on 7th rank?
constexpr Bitboard rank7 = TURN == WHITE ? Bitboards::rank_7 : Bitboards::rank_2;
score += RookOn7th * (b & rank7).count();
// Files for each rook: check if open or semi-open
score += RookOnOpen * (b & data.pawns[TURN].open_files).count();
}
else if (PIECE == QUEEN)
{
}
data.fields[TURN].pieces[PIECE] = score;
return score;
}
MixedScore pieces(const Board& board, EvalData& data)
{
MixedScore result(0, 0);
Bitboard occupancy = board.get_pieces<WHITE>() | board.get_pieces<BLACK>();
result += piece<KNIGHT, WHITE>(board, occupancy, data)
- piece<KNIGHT, BLACK>(board, occupancy, data);
result += piece<BISHOP, WHITE>(board, occupancy, data)
- piece<BISHOP, BLACK>(board, occupancy, data);
result += piece< ROOK, WHITE>(board, occupancy, data)
- piece< ROOK, BLACK>(board, occupancy, data);
result += piece< QUEEN, WHITE>(board, occupancy, data)
- piece< QUEEN, BLACK>(board, occupancy, data);
return result;
}
template<Turn TURN>
MixedScore king_safety(const Board& board, EvalData& data)
{
constexpr Direction Up = (TURN == WHITE) ? 8 : -8;
constexpr Direction Left = -1;
constexpr Direction Right = 1;
constexpr Bitboard Rank1 = (TURN == WHITE) ? Bitboards::rank_1 : Bitboards::rank_8;
constexpr MixedScore BackRankBonus(50, -50);
constexpr MixedScore OpenRay(-15, 8);
constexpr MixedScore KingOnOpenFile(-75, 0);
constexpr MixedScore KingNearOpenFile(-35, 0);
constexpr MixedScore PawnShelter[] = { MixedScore(-100, 0), MixedScore(-25, 0), MixedScore( 0, 0),
MixedScore( 25, 0), MixedScore( 35, -5), MixedScore(40, -5),
MixedScore( 40, -10), MixedScore( 41, -15), MixedScore(42, -20) };
constexpr MixedScore SquaresAttacked[] = { MixedScore( 0, 0), MixedScore( -10, 0),
MixedScore( -50, 0), MixedScore( -75, 0),
MixedScore(-100, 0), MixedScore(-150, 0),
MixedScore(-200, 0), MixedScore(-225, 0),
MixedScore(-250, 0), MixedScore(-250, 0) };
constexpr MixedScore SliderAttackers[] = { MixedScore(-150, -100), MixedScore(-50, -20),
MixedScore( -15, -2), MixedScore( 0, 0),
MixedScore( 0, 0), MixedScore( 0, 0),
MixedScore( 0, 0) };
Bitboard occupancy = board.get_pieces();
const Bitboard king_bb = board.get_pieces<TURN, KING>();
const Bitboard pawns_bb = board.get_pieces<TURN, PAWN>();
const Square king_sq = king_bb.bitscan_forward();
const Bitboard mask = Bitboards::get_attacks<KING>(king_sq, occupancy) | king_bb;
MixedScore score(0, 0);
// Pawn shelter
Bitboard shelter_zone = mask | mask.shift<2*Up>();
score += PawnShelter[(pawns_bb & shelter_zone).count()];
// Back-rank bonus
score += BackRankBonus * Rank1.test(king_sq);
// X-rays with enemy sliders
Bitboard their_rooks = board.get_pieces<~TURN, ROOK>() | board.get_pieces<~TURN, QUEEN>();
Bitboard their_bishops = board.get_pieces<~TURN, BISHOP>() | board.get_pieces<~TURN, QUEEN>();
Bitboard slider_attackers = (Bitboards::ranks_files[king_sq] & their_rooks)
| (Bitboards::diagonals[king_sq] & their_bishops);
while (slider_attackers)
score += SliderAttackers[Bitboards::between(king_sq, slider_attackers.bitscan_forward_reset()).count()];
// Attackers to the squares near the king
int attacked_squares = 0;
Bitboard b = mask;
while(b)
attacked_squares += board.attackers_battery<~TURN>(b.bitscan_forward_reset(), occupancy).count();
score += SquaresAttacked[std::min(9, attacked_squares)];
// King out in the open
Bitboard rays = Bitboards::get_attacks<BISHOP>(king_sq, occupancy)
| Bitboards::get_attacks< ROOK>(king_sq, occupancy);
int safe_dirs = (rays & board.get_pieces<TURN>()).count();
score += OpenRay * std::max(0, mask.count() - safe_dirs - 3);
// Open or semi-open files near the king
Bitboard king_file = king_bb.fill<Up>();
Bitboard left_king_file = (king_file & ~Bitboards::a_file).shift< Left>();
Bitboard right_king_file = (king_file & ~Bitboards::h_file).shift<Right>();
score += KingOnOpenFile * !( king_file & pawns_bb)
+ KingNearOpenFile * !( left_king_file & pawns_bb)
+ KingNearOpenFile * !(right_king_file & pawns_bb);
data.fields[TURN].pieces[KING] = score;
return score;
}
template<Turn TURN>
MixedScore space(const Board& board, EvalData& data)
{
constexpr MixedScore CenterSquareControl(15, 1);
// Center control
Bitboard center = Bitboards::zone1 | Bitboards::zone2;
Bitboard control_bb = data.attacks[TURN].get() & ~data.attacks[~TURN].get();
data.fields[TURN].space = CenterSquareControl * (control_bb & center).count();
return data.fields[TURN].space;
}
Score evaluation(const Board& board, EvalData& data)
{
MixedScore mixed_result(0, 0);
// Material and PSQT: incrementally updated in the position (with eg scaling)
mixed_result += board.material_eval() / MixedScore(10, 5);
// Pawn structure
mixed_result += pawns(board, data);
// Piece scores
mixed_result += pieces(board, data);
// King safety
mixed_result += king_safety<WHITE>(board, data) - king_safety<BLACK>(board, data);
// Space
mixed_result += space<WHITE>(board, data) - space<BLACK>(board, data);
// Tapered eval
Score result = mixed_result.tapered(board.phase());
// We don't return exact draw scores -> add one centipawn to the moving side
if (result == SCORE_DRAW)
result += turn_to_color(board.turn());
return result;
}
void eval_table(const Board& board, EvalData& data, Score score)
{
// No eval printing when in check
if (board.checkers())
{
std::cout << "No eval: in check" << std::endl;
return;
}
// Update material and placement terms
material(board, data);
piece_square_value(board, data);
// Print the eval table
std::cout << "---------------------------------------------------------------" << std::endl;
std::cout << " | White | Black | Total " << std::endl;
std::cout << " Term | MG EG | MG EG | MG EG " << std::endl;
std::cout << "---------------------------------------------------------------" << std::endl;
std::cout << " Material | " << Term< true>(data.fields[WHITE].material / 10, data.fields[BLACK].material / 10) << std::endl;
std::cout << " Placement | " << Term< true>(data.fields[WHITE].placement / 10, data.fields[BLACK].placement / 10) << std::endl;
std::cout << " Pawns | " << Term<false>(data.fields[WHITE].pieces[PAWN], data.fields[BLACK].pieces[PAWN]) << std::endl;
std::cout << " Knights | " << Term<false>(data.fields[WHITE].pieces[KNIGHT], data.fields[BLACK].pieces[KNIGHT]) << std::endl;
std::cout << " Bishops | " << Term<false>(data.fields[WHITE].pieces[BISHOP], data.fields[BLACK].pieces[BISHOP]) << std::endl;
std::cout << " Rooks | " << Term<false>(data.fields[WHITE].pieces[ROOK], data.fields[BLACK].pieces[ROOK]) << std::endl;
std::cout << " Queens | " << Term<false>(data.fields[WHITE].pieces[QUEEN], data.fields[BLACK].pieces[QUEEN]) << std::endl;
std::cout << " King safety | " << Term<false>(data.fields[WHITE].pieces[KING], data.fields[BLACK].pieces[KING]) << std::endl;
std::cout << " Space | " << Term<false>(data.fields[WHITE].space, data.fields[BLACK].space) << std::endl;
std::cout << "---------------------------------------------------------------" << std::endl;
std::cout << " Phase | " << std::setw(4) << (int)board.phase() << std::endl;
std::cout << " Final | " << std::setw(5) << score / 100.0 << " (White)" << std::endl;
std::cout << "---------------------------------------------------------------" << std::endl;
std::cout << std::endl;
}
}
| 43.278351 | 136 | 0.558182 | x0x |
c5af54ec396d6934559543d71b7fd82e62efb4c3 | 1,454 | cc | C++ | Chapter23_01.cc | ucarlos/Programming-Principles-Chapter23 | 30234d31720e9194880cc84d04d3d6247ce1c1a0 | [
"MIT"
] | null | null | null | Chapter23_01.cc | ucarlos/Programming-Principles-Chapter23 | 30234d31720e9194880cc84d04d3d6247ce1c1a0 | [
"MIT"
] | null | null | null | Chapter23_01.cc | ucarlos/Programming-Principles-Chapter23 | 30234d31720e9194880cc84d04d3d6247ce1c1a0 | [
"MIT"
] | null | null | null | /*
* -----------------------------------------------------------------------------
* Created by Ulysses Carlos on 01/05/2021 at 02:22 PM
*
* Chapter23_01.cc
* Get the email file example to run; test it using a larger file of your own
* creation. Be sure to include messages that are likely to trigger errors, such
* as messages with two address lines, several messages with the same ad-
* dress and/or same subject, and empty messages. Also test the program
* with something that simply isn’t a message according to that program’s
* specification, such as a large file containing no –––– lines.
* -----------------------------------------------------------------------------
*/
#include "MailFile.h"
using namespace std;
int main() {
Mail_File mail_file {"../Chapter23_01_Mail.txt"};
// Now gather the messages into a multimap:
std::multimap<string, const Message *> sender;
for (const auto &m : mail_file) {
string s;
if (find_from_addr(&m, s))
sender.insert(make_pair(s, &m));
}
// Now iterate through the multimap and extract the subjects of John Doe's
// and extract the subjects of John Doe's messages:
string name = "John Doe <jdoe@machine.example>";
auto pp = sender.equal_range(name);
if (pp.first == pp.second) {
cerr << "Error: No messages can be found with \""
<< name << "\"\n";
exit(EXIT_FAILURE);
}
for (auto p = pp.first; p != pp.second; p++)
cout << find_subject(p->second) << "\n";
}
| 33.045455 | 80 | 0.610041 | ucarlos |
c5b039ee0234f54312d283c1d27949f21872e054 | 3,607 | cpp | C++ | src/core_math.cpp | thechrisyoon08/NeuralNetworks | b47eb6425341c0d0e8278431aaf8b64143ce921f | [
"MIT"
] | 1 | 2018-12-30T05:11:59.000Z | 2018-12-30T05:11:59.000Z | src/core_math.cpp | thechrisyoon08/sANNity | b47eb6425341c0d0e8278431aaf8b64143ce921f | [
"MIT"
] | null | null | null | src/core_math.cpp | thechrisyoon08/sANNity | b47eb6425341c0d0e8278431aaf8b64143ce921f | [
"MIT"
] | null | null | null | #include "../include/core_math.h"
#include <cstdlib>
#include <iostream>
#include <vector>
#include <random>
#include <math.h>
#include <assert.h>
namespace tensor{
void Tensor::fill_weights(const std::string initializer){
this->tensor.resize(this->m * this->n);
if(initializer== "zero"){
for(size_t entry = 0; entry < this->m * this->n; ++entry){
this->tensor[entry] = 0.0;
}
}
if(initializer == "glorot"){
double variance = 2.0 / (this->m + this->n);
std::random_device rd;
std::mt19937 e2(rd());
std::uniform_real_distribution<> dist(-std::sqrt(3.0 * variance), std::sqrt(3.0 * variance));
for(size_t entry = 0; entry < this->m * this->n; ++entry){
this->tensor[entry] = dist(e2);
}
}
}
void Tensor::fill_weights(const double low, const double high){
this->tensor.resize(this->m * this->n);
std::random_device rd;
std::mt19937 e2(rd());
std::uniform_real_distribution<> dist(low, high);
for(size_t entry = 0; entry < this->m * this->n; ++entry){
this->tensor[entry] = dist(e2);
}
}
void Tensor::T(){
std::vector<double> original = this->tensor;
this->tensor.resize(this->n * this->m);
for(size_t e = 0; e < this->n * this->m; ++e){
size_t i = e/this->m;
size_t j = e%this->m;
this->tensor[e] = original[this->n * j + i];
}
std::swap(this->m, this->n);
this->transposed = !this->transposed;
}
void copy_tensor(Tensor& A, Tensor& B){
A = B;
}
void initialize(Tensor& empty_tensor, size_t row, size_t col, std::string initializer){
empty_tensor.m = row;
empty_tensor.n = col;
empty_tensor.fill_weights(initializer);
}
void initialize(Tensor& empty_tensor, size_t row, size_t col, double low, double high){
empty_tensor.m = row;
empty_tensor.n = col;
empty_tensor.fill_weights(low, high);
}
const Tensor operator+(const Tensor& lhs, const Tensor& rhs){
Tensor ret(lhs.m, lhs.n);
for(size_t entry = 0; entry < lhs.m * lhs.n; ++entry){
ret.tensor[entry] = lhs.tensor[entry] + rhs.tensor[entry];
}
return ret;
}
const Tensor operator-(const Tensor& lhs, const Tensor& rhs){
Tensor ret(lhs.m, lhs.n);
for(size_t entry = 0; entry < lhs.m * lhs.n; ++entry){
ret.tensor[entry] = lhs.tensor[entry] - rhs.tensor[entry];
}
return ret;
}
const Tensor operator*(const double k, const Tensor& rhs){
Tensor ret(rhs.m, rhs.n);
for(size_t entry = 0; entry < rhs.m * rhs.n; ++entry){
ret.tensor[entry] = k * rhs.tensor[entry];
}
return ret;
}
const Tensor operator*(const Tensor& lhs, const Tensor& rhs){
assert(lhs.n == rhs.m);
Tensor ret(lhs.m, rhs.n);
for(size_t i = 0; i < lhs.m; ++i){
for(size_t j = 0; j < rhs.n; ++j){
for(size_t k = 0; k < lhs.n; ++k){
ret.tensor[j + i * rhs.n] += lhs.tensor[k + i * lhs.n] * rhs.tensor[j + k * rhs.n];
}
}
}
return ret;
}
/*const Tensor operator=(const Tensor& t){
return t;
}*/
std::ostream& operator<<(std::ostream& os, const Tensor& M){
os << "[";
for(size_t i = 0; i < M.m; ++i){
if(i != 0){
os << " ";
}
os << "[";
for(size_t j = 0; j < M.n; ++j){
os << M.tensor[j + M.n * i];
if(j == M.n - 1){
os << "]";
}else{
os << ", ";
}
}
if(i == M.m - 1){
os << "]\n ";
}else{
os << "\n";
}
}
}
}
| 26.137681 | 101 | 0.535071 | thechrisyoon08 |
c5b3694027671c2a0d6653bc51150967a242c5f9 | 1,034 | cpp | C++ | src/arguments/src/ArgumentsException.cpp | xgallom/eset_file_system | 3816a8e3ae3c36d5771b900251345d08c76f8a0e | [
"MIT"
] | null | null | null | src/arguments/src/ArgumentsException.cpp | xgallom/eset_file_system | 3816a8e3ae3c36d5771b900251345d08c76f8a0e | [
"MIT"
] | null | null | null | src/arguments/src/ArgumentsException.cpp | xgallom/eset_file_system | 3816a8e3ae3c36d5771b900251345d08c76f8a0e | [
"MIT"
] | null | null | null | //
// Created by xgallom on 4/4/19.
//
#include "ArgumentsException.h"
#include "ArgumentsConfig.h"
#include <sstream>
namespace Arguments
{
Exception::Exception(const std::string &a_what) :
std::runtime_error(a_what)
{}
Exception Exception::InvalidArgCount(int argCount)
{
std::stringstream stream;
// count - 1 because argument[0] is the program name
stream << "Program expects between " << (MinArgCount - 1) << " and " << (MaxArgCount - 1) << " arguments, "
<< (argCount - 1) << " provided";
return Exception(stream.str());
}
Exception Exception::InvalidKeyLength(const std::string &key)
{
std::stringstream stream;
stream << "Key \"" << key << "\" with length " << key.length() << " is either empty, or too long.\n"
<< "Maximum allowed key length is " << MaximumKeyLength;
return Exception(stream.str());
}
Exception Exception::InvalidOption(const std::string &option)
{
std::stringstream stream;
stream << "Invalid option " << option;
return Exception(stream.str());
}
}
| 22.478261 | 109 | 0.659574 | xgallom |
c5b60c75a1c28b40bf241789e5011fe70eb4d74e | 4,492 | cpp | C++ | test/test-uvcpp/my-uv-tcp/MTcpServer.cpp | miaopei/B4860 | 6f084bd485b787bb36de26d40f83ff4833098c3d | [
"MIT"
] | 5 | 2019-10-27T19:06:06.000Z | 2022-01-01T02:27:21.000Z | test/test-uvcpp/my-uv-tcp/MTcpServer.cpp | miaopei/B4860 | 6f084bd485b787bb36de26d40f83ff4833098c3d | [
"MIT"
] | null | null | null | test/test-uvcpp/my-uv-tcp/MTcpServer.cpp | miaopei/B4860 | 6f084bd485b787bb36de26d40f83ff4833098c3d | [
"MIT"
] | 2 | 2020-02-15T13:27:47.000Z | 2021-12-24T17:32:56.000Z | #include "MTcpServer.hpp"
#include "MClientSession.hpp"
MTcpServer::MTcpServer() :on_new_session(nullptr), on_new_packet(nullptr),
on_session_close(nullptr), on_server_close(nullptr), is_short_connection(false){}
MTcpServer::~MTcpServer(){}
int MTcpServer::Setup(const char* ip, int port, bool is_ip_v6) {
lastError = uv_loop_init(&loop);
if (lastError) {
PrintError("Loop initialization error : %s.\n", lastError);
return lastError;
}
loop.data = &memory_pool;
lastError = uv_tcp_init(&loop, &server);
if (lastError) {
PrintError("Server initialization error : %s.\n", lastError);
return lastError;
}
if (!is_ip_v6)
{
struct sockaddr_in addr;
lastError = uv_ip4_addr(ip, port, &addr);
if (lastError) {
PrintError("Server addr error : %s.\n", lastError);
return lastError;
}
//bind server
lastError = uv_tcp_bind(&server, (const struct sockaddr*)&addr, 0);
if (lastError) {
PrintError("Server binding error : %s.\n", lastError);
return lastError;
}
}
else
{
struct sockaddr_in6 addr;
lastError = uv_ip6_addr(ip, port, &addr);
if (lastError) {
PrintError("Server addr error : %s.\n", lastError);
return lastError;
}
//bind server
lastError = uv_tcp_bind(&server, (const struct sockaddr*)&addr, 0);
if (lastError) {
PrintError("Server binding error : %s.\n", lastError);
return lastError;
}
}
//pass this pointer for callback
server.data = this;
//listen for new connection
lastError = uv_listen((uv_stream_t *)&server, DEFAULT_BACKLOG, [](uv_stream_t * server, int status) {
((MTcpServer *)server->data)->OnNewConnection(server, status);
});
if (lastError) {
return lastError;
}
return 0;
}
int MTcpServer::SetSimultaneousAccepts(bool enable)
{
lastError = uv_tcp_simultaneous_accepts(&server, enable ? 1 : 0);
return lastError;
}
int MTcpServer::SetKeepAlive(bool enable, int delay)
{
lastError = uv_tcp_keepalive(&server, enable ? 1 : 0, delay);
return lastError;
}
void MTcpServer::SetShortConnection(bool enable)
{
is_short_connection = enable;
}
int MTcpServer::Start()
{
if (lastError = uv_run(&loop, UV_RUN_DEFAULT)) {
PrintError("Run loop error : %s.\n", lastError);
return lastError;
}
return lastError;
}
void MTcpServer::Close()
{
for (auto & session : sessions)
{
CloseClient(session.first);
}
uv_close((uv_handle_t *)&server, [](uv_handle_t* handle) {
int error = uv_loop_close(handle->loop);
if (error)
{
PrintError("Close server loop error : %s.\n", error);
}
MTcpServer* _tcpServer = (MTcpServer *)(handle->data);
if (_tcpServer->on_server_close)
{
_tcpServer->on_server_close(*_tcpServer);
}
});
}
void MTcpServer::CloseClient(uint64_t id)
{
MClientSession* _session = sessions[id];
if (on_session_close)
{
on_session_close(*_session);
}
uv_close((uv_handle_t *)_session->GetClient(), [](uv_handle_t* handle) {
delete (MClientSession*)handle->data;
});
//only erase from map, not clear memory
sessions.erase(id);
}
void MTcpServer::SendTo(uint64_t client_id, const char * data, uint64_t len)
{
sessions[client_id]->Send(data, len);
}
void MTcpServer::Broadcast(const char * data, uint64_t len)
{
//loop map
for (auto &session: sessions)
{
session.second->Send(data, len);
}
}
const char* MTcpServer::GetLastError()
{
return uv_strerror(lastError);
}
const char * MTcpServer::GetError(int error)
{
return uv_strerror(error);
}
void MTcpServer::PrintError(const char* format, int error)
{
fprintf(stderr, format,
uv_strerror(error));
}
uv_loop_t * MTcpServer::GetLoop()
{
return &loop;
}
uv_tcp_t * MTcpServer::GetServer()
{
return &server;
}
MMemoryPool * MTcpServer::GetMemoryPool()
{
return &memory_pool;
}
void MTcpServer::OnNewConnection(uv_stream_t * server, int status) {
if (status < 0) {
lastError = status;
PrintError("Connection status error: %s.\n", lastError);
return;
}
//get a unique id for session
uint64_t session_id = MClientSession::CreateID();
MClientSession *_session = (sessions[session_id] = new MClientSession(session_id, this));
_session->SetShortConnection(is_short_connection);
lastError = _session->StartAccept();
if (lastError)//accept error, close connection, do not call session close callback
{
PrintError("Accept connection error: %s.\n", lastError);
uv_close((uv_handle_t *)_session->GetClient(), [](uv_handle_t* handle) {
delete (MClientSession*)handle->data;
});
//only erase from map, not clear memory
sessions.erase(session_id);
}
}
| 23.642105 | 102 | 0.705699 | miaopei |
c5b86897c012d61d17e8cbd2402c3f462896dd9d | 1,276 | cpp | C++ | code/src/core/errlib/log.cpp | jgresula/jagpdf | 6c36958b109e6522e6b57d04144dd83c024778eb | [
"MIT"
] | 54 | 2015-02-16T14:25:16.000Z | 2022-03-16T07:54:25.000Z | code/src/core/errlib/log.cpp | jgresula/jagpdf | 6c36958b109e6522e6b57d04144dd83c024778eb | [
"MIT"
] | null | null | null | code/src/core/errlib/log.cpp | jgresula/jagpdf | 6c36958b109e6522e6b57d04144dd83c024778eb | [
"MIT"
] | 30 | 2015-03-05T08:52:25.000Z | 2022-02-17T13:49:15.000Z | // Copyright (c) 2005-2009 Jaroslav Gresula
//
// Distributed under the MIT license (See accompanying file
// LICENSE.txt or copy at http://jagpdf.org/LICENSE.txt)
//
#include "precompiled.h"
#include <core/errlib/log.h>
#include <interfaces/message_sink.h>
#include <cstdio>
namespace {
//////////////////////////////////////////////////////////////////////////
class StdErrSink
: public jag::IMessageSink
{
StdErrSink() {}
public: //IMessageSink
void message(jag::UInt /*code*/, jag::MessageSeverity /*sev*/, jag::Char const* /*msg*/) {
// fprintf(stderr, "%s\n", msg);
}
public:
static IMessageSink& instance();
};
//////////////////////////////////////////////////////////////////////////
jag::IMessageSink& StdErrSink::instance()
{
static StdErrSink sink;
return sink;
}
jag::IMessageSink* g_message_sink = 0;
} // anonymous namespace
namespace jag
{
//////////////////////////////////////////////////////////////////////////
IMessageSink& message_sink()
{
return g_message_sink
? *g_message_sink
: StdErrSink::instance()
;
}
//////////////////////////////////////////////////////////////////////////
void set_message_sink(IMessageSink* sink)
{
g_message_sink = sink;
}
} //namespace jag
| 20.918033 | 97 | 0.510188 | jgresula |
c5b8b2e00fb51bbfd63c63fbf4c6369b0eda6d02 | 764 | cpp | C++ | editor/ui/windows/sceneview/light.cpp | chokomancarr/chokoengine2 | 2825f2b95d24689f4731b096c8be39cc9a0f759a | [
"Apache-2.0"
] | null | null | null | editor/ui/windows/sceneview/light.cpp | chokomancarr/chokoengine2 | 2825f2b95d24689f4731b096c8be39cc9a0f759a | [
"Apache-2.0"
] | null | null | null | editor/ui/windows/sceneview/light.cpp | chokomancarr/chokoengine2 | 2825f2b95d24689f4731b096c8be39cc9a0f759a | [
"Apache-2.0"
] | null | null | null | #include "chokoeditor.hpp"
CE_BEGIN_ED_NAMESPACE
void EW_S_Light::Init() {
EW_S_DrawCompList::funcs[(int)ComponentType::Light] = &Draw;
EW_S_DrawCompList::activeFuncs[(int)ComponentType::Light] = &DrawActive;
}
void EW_S_Light::Draw(const Component& c, const Mat4x4& p) {
}
void EW_S_Light::DrawActive(const Component& c, const Mat4x4& p) {
const auto& lht = static_cast<Light>(c);
const auto& tr = lht->object()->transform();
switch (lht->type()) {
case LightType::Point: {
break;
}
case LightType::Spot: {
const auto& p1 = tr->worldPosition();
const auto& fw = tr->forward();
UI::W::Line(p1 + fw * lht->radius(), p1 + fw * lht->distance(), Color::white());
break;
}
case LightType::Directional: {
break;
}
}
}
CE_END_ED_NAMESPACE | 21.222222 | 82 | 0.676702 | chokomancarr |
c5bb650b6b79f65a7f578b14a57e6aa4af27d794 | 2,350 | cpp | C++ | CppMisc/SrcOld/002-fibonacci.cpp | Ginkgo-Biloba/Cpp-Repo1-VS | 231c68a055e6bf69a3f7c224e7c0182b67ce5b67 | [
"Apache-2.0"
] | null | null | null | CppMisc/SrcOld/002-fibonacci.cpp | Ginkgo-Biloba/Cpp-Repo1-VS | 231c68a055e6bf69a3f7c224e7c0182b67ce5b67 | [
"Apache-2.0"
] | null | null | null | CppMisc/SrcOld/002-fibonacci.cpp | Ginkgo-Biloba/Cpp-Repo1-VS | 231c68a055e6bf69a3f7c224e7c0182b67ce5b67 | [
"Apache-2.0"
] | null | null | null | #include <ctime>
#include <cstdio>
typedef unsigned long long ullong;
void timeit(ullong(*func)(ullong), char const* info)
{
clock_t start = clock();
ullong r, s = 0ull;
// n 纯粹为了计时故意调大,反正溢出了结果也肯定一样
ullong n = 0xffffull;
unsigned it = 0xffffu;
// += 是防止直接赋值循环被优化掉;后面的输出是为了防止优化掉 s
for (unsigned u = 0u; u < it; ++u)
s += func(n);
r = func(n);
clock_t stop = clock();
printf("%10s(%llu) = %llu (s = %llu) | clock = %d\n", \
info, n, r, s, (int)(stop - start));
}
/* O(N) 64 位无符号也只能算到 93 项 12200160415121876738 */
ullong fibonacci(ullong n)
{
ullong fkm1 = 1ull, fk = 0ull; // F(-1) = 1, F(0) = 0
for (; n; --n)
{
ullong fkp1 = fkm1 + fk;
fkm1 = fk; fk = fkp1;
}
return fk;
}
/** O(log2(N)) 因为掺杂了矩阵乘法,所以常数系数大
* 就代码里来说,16 次乘法和 8 次加法避免不了
* [1 1]^n = [f(n + 1) f(n) ]
* [1 0] [f(n) f(n - 1)] */
ullong fibMatrix(ullong n)
{
ullong A[4] = { 1ull, 1ull, 1ull, 0ull }; // n = 1,底数
ullong B[4] = { 1ull, 0ull, 0ull, 1ull }; // n = 0
for (; n; n >>= 1)
{
ullong C[4];
if (n & 1ull) // r *= x;
{
C[0] = B[0] * A[0] + B[1] * A[2];
C[1] = B[0] * A[1] + B[1] * A[3];
C[2] = B[2] * A[0] + B[3] * A[2];
C[3] = B[2] * A[1] + B[3] * A[3];
B[0] = C[0]; B[1] = C[1]; B[2] = C[2]; B[3] = C[3];
}
// x *= x,其实最后一个循环可以算这个的
C[0] = A[0] * A[0] + A[1] * A[2];
C[1] = A[0] * A[1] + A[1] * A[3];
C[2] = A[2] * A[0] + A[3] * A[2];
C[3] = A[2] * A[1] + A[3] * A[3];
A[0] = C[0]; A[1] = C[1]; A[2] = C[2]; A[3] = C[3];
}
return B[1];
}
/** O(log2(N))倍数公式,跟矩阵方法差不多,常数小
* F(2n - 1) = F(n)^2 + F(n - 1)^2
* F(2n) = (F(n - 1) + F(n + 1)) * F(n) = (2F(n - 1) + F(n)) * F(n) */
ullong fibShift(ullong n)
{
// 找到最左边那个 1
ullong mask = 1ull << (sizeof(ullong) * 8 - 1);
while (!(mask & n) && mask) mask >>= 1;
// f(k), f(k - 1). k = 0, F(-1) = 1
ullong fkm1 = 1ull, fk = 0ull;
for (; mask; mask >>= 1)
{
ullong f2km1 = fk * fk + fkm1 * fkm1;
ullong f2k = (fkm1 + fkm1 + fk) * fk;
if (mask & n)
{
fk = f2k + f2km1; // 2k + 1
fkm1 = f2k;
}
else
{
fk = f2k; // 2k
fkm1 = f2km1;
}
}
return fk;
}
int main()
{
/* 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765... */
timeit(fibonacci, "fibonacci");
timeit(fibMatrix, "fibMatrix");
timeit(fibShift, "fibShift");
for (ullong n = 1ull; n--;)
printf("fib(%2llu) = %llu\n", n, fibShift(n));
}
| 22.169811 | 78 | 0.488511 | Ginkgo-Biloba |
c5bf3d264367627720709b6232fc1980890a8aa5 | 1,045 | cpp | C++ | Data Structures/TRIE.cpp | FreeJ99/Algorithms | d8364e1107e702aec0b4055b0d52130e64ddc386 | [
"MIT"
] | null | null | null | Data Structures/TRIE.cpp | FreeJ99/Algorithms | d8364e1107e702aec0b4055b0d52130e64ddc386 | [
"MIT"
] | null | null | null | Data Structures/TRIE.cpp | FreeJ99/Algorithms | d8364e1107e702aec0b4055b0d52130e64ddc386 | [
"MIT"
] | null | null | null | #include<iostream>
#include<string>
#include<unordered_map>
using namespace std;
struct Node{
bool leaf;
unordered_map<char, Node*> chd;
Node(): leaf(false){}
};
void insert(Node* root, string s, int idx){
if(idx == s.size()){
root->leaf = true;
}
else{
if(root->chd[s[idx]] == NULL)
root->chd[s[idx]] = new Node();
insert(root->chd[s[idx]], s, idx+1);
}
}
bool find(Node* root, string s, int idx){
if(idx == s.size()){
return root->leaf;
}
if(root->chd[s[idx]] == NULL)
return false;
return find(root->chd[s[idx]], s, idx+1);
}
int main(){
Node* trie = new Node();
insert(trie, "abc", 0);
insert(trie, "abd", 0);
insert(trie, "def", 0);
insert(trie, "dag", 0);
cout<< find(trie, "abc", 0) << endl;
cout<< find(trie, "abd", 0) << endl;
cout<< find(trie, "def", 0) << endl;
cout<< find(trie, "dag", 0) << endl;
cout<< find(trie, "abv", 0) << endl;
cout<< find(trie, "art", 0) << endl;
return 0;
} | 22.234043 | 45 | 0.522488 | FreeJ99 |
c5c035dee395ffffc3b65c7d297f7df0d532c2fd | 12,042 | hpp | C++ | src/mechanics_model.hpp | StopkaKris/ExaConstit | fecf8b5d0d97946e29244360c3bc538c3efb433a | [
"BSD-3-Clause"
] | 16 | 2019-10-11T17:03:20.000Z | 2021-11-17T14:09:47.000Z | src/mechanics_model.hpp | Leonidas-Z/ExaConstit | 0ab293cb6543b97eabde99e3ab43c1e921258ae4 | [
"BSD-3-Clause"
] | 41 | 2020-01-29T04:40:16.000Z | 2022-03-11T16:59:31.000Z | src/mechanics_model.hpp | Leonidas-Z/ExaConstit | 0ab293cb6543b97eabde99e3ab43c1e921258ae4 | [
"BSD-3-Clause"
] | 7 | 2019-10-12T02:00:58.000Z | 2022-03-10T04:09:35.000Z | #ifndef MECHANICS_MODEL
#define MECHANICS_MODEL
#include "mfem.hpp"
#include <utility>
#include <unordered_map>
#include <string>
/// free function to compute the beginning step deformation gradient to store
/// on a quadrature function
void computeDefGrad(mfem::QuadratureFunction *qf, mfem::ParFiniteElementSpace *fes,
mfem::Vector &x0);
class ExaModel
{
public:
int numProps;
int numStateVars;
bool init_step = false;
protected:
double dt, t;
// --------------------------------------------------------------------------
// The velocity method requires us to retain both the beggining and end time step
// coordinates of the mesh. We need these to be able to compute the correct
// incremental deformation gradient (using the beg. time step coords) and the
// velocity gradient (uses the end time step coords).
mfem::ParGridFunction* beg_coords;
mfem::ParGridFunction* end_coords;
// ---------------------------------------------------------------------------
// STATE VARIABLES and PROPS common to all user defined models
// The beginning step stress and the end step (or incrementally upated) stress
mfem::QuadratureFunction *stress0;
mfem::QuadratureFunction *stress1;
// The updated material tangent stiffness matrix, which will need to be
// stored after an EvalP call and used in a later AssembleH call
mfem::QuadratureFunction *matGrad;
// quadrature vector function coefficients for any history variables at the
// beginning of the step and end (or incrementally updated) step.
mfem::QuadratureFunction *matVars0;
mfem::QuadratureFunction *matVars1;
// Stores the von Mises / hydrostatic scalar stress measure
// we use this array to compute both the hydro and von Mises stress quantities
mfem::QuadratureFunction *vonMises;
// add vector for material properties, which will be populated based on the
// requirements of the user defined model. The properties are expected to be
// the same at all quadrature points. That is, the material properties are
// constant and not dependent on space
mfem::Vector *matProps;
bool PA;
// Temporary fix just to make sure things work
mfem::Vector matGradPA;
std::unordered_map<std::string, std::pair<int, int> > qf_mapping;
// ---------------------------------------------------------------------------
public:
ExaModel(mfem::QuadratureFunction *q_stress0, mfem::QuadratureFunction *q_stress1,
mfem::QuadratureFunction *q_matGrad, mfem::QuadratureFunction *q_matVars0,
mfem::QuadratureFunction *q_matVars1,
mfem::ParGridFunction* _beg_coords, mfem::ParGridFunction* _end_coords,
mfem::Vector *props, int nProps, int nStateVars, bool _PA) :
numProps(nProps), numStateVars(nStateVars),
beg_coords(_beg_coords),
end_coords(_end_coords),
stress0(q_stress0),
stress1(q_stress1),
matGrad(q_matGrad),
matVars0(q_matVars0),
matVars1(q_matVars1),
matProps(props),
PA(_PA)
{
if (_PA) {
int npts = q_matGrad->Size() / q_matGrad->GetVDim();
matGradPA.SetSize(81 * npts, mfem::Device::GetMemoryType());
matGradPA.UseDevice(true);
}
}
virtual ~ExaModel() { }
/// This function is used in generating the B matrix commonly seen in the formation of
/// the material tangent stiffness matrix in mechanics [B^t][Cstiff][B]
virtual void GenerateGradMatrix(const mfem::DenseMatrix& DS, mfem::DenseMatrix& B);
/// This function is used in generating the Bbar matrix seen in the formation of
/// the material tangent stiffness matrix in mechanics [B^t][Cstiff][B] for
/// incompressible materials
virtual void GenerateGradBarMatrix(const mfem::DenseMatrix& DS, const mfem::DenseMatrix& eDS, mfem::DenseMatrix& B);
/// This function is used in generating the B matrix that's used in the formation
/// of the geometric stiffness contribution of the stiffness matrix seen in mechanics
/// as [B^t][sigma][B]
virtual void GenerateGradGeomMatrix(const mfem::DenseMatrix& DS, mfem::DenseMatrix& Bgeom);
/** @brief This function is responsible for running the entire model and will be the
* external function that other classes/people can call.
*
* It will consist of 3 stages/kernels:
* 1.) A set-up kernel/stage that computes all of the needed values for the material model
* 2.) A kernel that runs the material model (an t = 0 version of this will exist as well)
* 3.) A post-processing kernel/stage that does everything after the kernel
* e.g. All of the data is put back into the correct format here and re-arranged as needed
* By having this function, we only need to ever right one integrator for everything.
* It also allows us to run these models on the GPU even if the rest of the assembly operation
* can't be there yet. If UMATs are used then these operations won't occur on the GPU.
*
* We'll need to supply the number of quadrature pts, number of elements, the dimension
* of the space we're working with, the number of nodes for an element, the jacobian associated
* with the transformation from the reference element to the local element, the quadrature integration wts,
* and the velocity field at the elemental level (space_dim * nnodes * nelems).
*/
virtual void ModelSetup(const int nqpts, const int nelems, const int space_dim,
const int nnodes, const mfem::Vector &jacobian,
const mfem::Vector &loc_grad, const mfem::Vector &vel) = 0;
/// routine to update the beginning step deformation gradient. This must
/// be written by a model class extension to update whatever else
/// may be required for that particular model
virtual void UpdateModelVars() = 0;
/// set time on the base model class
void SetModelTime(const double time) { t = time; }
/// set delta timestep on the base model class
void SetModelDt(const double dtime) { dt = dtime; }
/// Get delta timestep on the base model class
double GetModelDt() { return dt; }
/// return a pointer to beginning step stress. This is used for output visualization
mfem::QuadratureFunction *GetStress0() { return stress0; }
/// return a pointer to beginning step stress. This is used for output visualization
mfem::QuadratureFunction *GetStress1() { return stress1; }
/// function to set the internal von Mises QuadratureFuntion pointer to some
/// outside source
void setVonMisesPtr(mfem::QuadratureFunction* vm_ptr) { vonMises = vm_ptr; }
/// return a pointer to von Mises stress quadrature function for visualization
mfem::QuadratureFunction *GetVonMises() { return vonMises; }
/// return a pointer to the matVars0 quadrature function
mfem::QuadratureFunction *GetMatVars0() { return matVars0; }
/// return a pointer to the matGrad quadrature function
mfem::QuadratureFunction *GetMatGrad() { return matGrad; }
/// return a pointer to the matProps vector
mfem::Vector *GetMatProps() { return matProps; }
/// routine to get element stress at ip point. These are the six components of
/// the symmetric Cauchy stress where standard Voigt notation is being used
void GetElementStress(const int elID, const int ipNum, bool beginStep,
double* stress, int numComps);
/// set the components of the member function end stress quadrature function with
/// the updated stress
void SetElementStress(const int elID, const int ipNum, bool beginStep,
double* stress, int numComps);
/// routine to get the element statevars at ip point.
void GetElementStateVars(const int elID, const int ipNum, bool beginStep,
double* stateVars, int numComps);
/// routine to set the element statevars at ip point
void SetElementStateVars(const int elID, const int ipNum, bool beginStep,
double* stateVars, int numComps);
/// routine to get the material properties data from the decorated mfem vector
void GetMatProps(double* props);
/// setter for the material properties data on the user defined model object
void SetMatProps(double* props, int size);
/// routine to set the material Jacobian for this element and integration point.
void SetElementMatGrad(const int elID, const int ipNum, double* grad, int numComps);
/// routine to get the material Jacobian for this element and integration point
void GetElementMatGrad(const int elId, const int ipNum, double* grad, int numComps);
/// routine to update beginning step stress with end step values
void UpdateStress();
/// routine to update beginning step state variables with end step values
void UpdateStateVars();
/// Update the End Coordinates using a simple Forward Euler Integration scheme
/// The beggining time step coordinates should be updated outside of the model routines
void UpdateEndCoords(const mfem::Vector& vel);
/// This method performs a fast approximate polar decomposition for 3x3 matrices
/// The deformation gradient or 3x3 matrix of interest to be decomposed is passed
/// in as the initial R matrix. The error on the solution can be set by the user.
void CalcPolarDecompDefGrad(mfem::DenseMatrix& R, mfem::DenseMatrix& U,
mfem::DenseMatrix& V, double err = 1e-12);
/// Lagrangian is simply E = 1/2(F^tF - I)
void CalcLagrangianStrain(mfem::DenseMatrix& E, const mfem::DenseMatrix &F);
/// Eulerian is simply e = 1/2(I - F^(-t)F^(-1))
void CalcEulerianStrain(mfem::DenseMatrix& E, const mfem::DenseMatrix &F);
/// Biot strain is simply B = U - I
void CalcBiotStrain(mfem::DenseMatrix& E, const mfem::DenseMatrix &F);
/// Log strain is equal to e = 1/2 * ln(C) or for UMATs its e = 1/2 * ln(B)
void CalcLogStrain(mfem::DenseMatrix& E, const mfem::DenseMatrix &F);
/// Converts a unit quaternion over to rotation matrix
void Quat2RMat(const mfem::Vector& quat, mfem::DenseMatrix& rmat);
/// Converts a rotation matrix over to a unit quaternion
void RMat2Quat(const mfem::DenseMatrix& rmat, mfem::Vector& quat);
/// Returns a pointer to our 4D material tangent stiffness tensor
const double *GetMTanData(){ return matGradPA.Read(); }
/// Converts a normal 2D stiffness tensor into it's equivalent 4D stiffness
/// tensor
void TransformMatGradTo4D();
/// This method sets the end time step stress to the beginning step
/// and then returns the internal data pointer of the end time step
/// array.
double* StressSetup();
/// This methods set the end time step state variable array to the
/// beginning time step values and then returns the internal data pointer
/// of the end time step array.
double* StateVarsSetup();
/// This function calculates the plastic strain rate tensor (D^p) with
/// a DpMat that's a full 3x3 matrix rather than a 6-dim vector just so
/// we can re-use storage from the deformation gradient tensor.
virtual void calcDpMat(mfem::QuadratureFunction &DpMat) const = 0;
/// Returns an unordered map that maps a given variable name to its
/// its location and length within the state variable variable.
const std::unordered_map<std::string, std::pair<int, int> > *GetQFMapping()
{
return &qf_mapping;
}
};
#endif | 46.674419 | 122 | 0.66102 | StopkaKris |
c5c31a6215118d04f3e7655eadd9e8229e66be39 | 2,424 | cpp | C++ | Practice/2018/2018.11.2/Luogu3962.cpp | SYCstudio/OI | 6e9bfc17dbd4b43467af9b19aa2aed41e28972fa | [
"MIT"
] | 4 | 2017-10-31T14:25:18.000Z | 2018-06-10T16:10:17.000Z | Practice/2018/2018.11.2/Luogu3962.cpp | SYCstudio/OI | 6e9bfc17dbd4b43467af9b19aa2aed41e28972fa | [
"MIT"
] | null | null | null | Practice/2018/2018.11.2/Luogu3962.cpp | SYCstudio/OI | 6e9bfc17dbd4b43467af9b19aa2aed41e28972fa | [
"MIT"
] | null | null | null | #include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;
#define ll long long
#define mem(Arr,x) memset(Arr,x,sizeof(Arr))
#define lson (now<<1)
#define rson (lson|1)
const int maxN=101000;
const int SS=(1<<10)-1;
const int inf=2147483647;
class SegmentData
{
public:
int lkey,rkey,key;
int sum;
};
int n;
int Seq[maxN];
SegmentData S[maxN<<2];
SegmentData operator + (const SegmentData A,const SegmentData B);
void Build(int now,int l,int r);
SegmentData Query(int now,int l,int r,int ql,int qr);
int main(){
scanf("%d",&n);
for (int i=1;i<=n;i++) scanf("%d",&Seq[i]),Seq[i]=(Seq[i]-1)%9+1;
//for (int i=1;i<=n;i++) cout<<Seq[i]<<" ";cout<<endl;
Build(1,1,n);
int Q;scanf("%d",&Q);
while (Q--){
int l,r;scanf("%d%d",&l,&r);
//cout<<"Q:"<<l<<" "<<r<<endl;
SegmentData R=Query(1,1,n,l,r);
int cnt=0;
for (int i=9;(i>=0)&&(cnt<5);i--)
if (R.key&(1<<i)){
printf("%d ",i);++cnt;
}
while (cnt<5) printf("-1 "),++cnt;
printf("\n");
}
return 0;
}
SegmentData operator + (const SegmentData A,const SegmentData B){
SegmentData r;r.lkey=A.lkey;r.rkey=B.rkey;r.key=A.key|B.key;r.sum=(A.sum+B.sum-1)%9+1;
//cout<<r.key<<endl;
for (int i=0;i<=9;i++)
if (A.rkey&(1<<i)){
r.key|=((B.lkey<<i)&SS);
if (i) r.key|=((((B.lkey>>(9-i))&SS)>>1)<<1);
}
//cout<<r.lkey<<" "<<A.lkey<<" "<<((A.lkey<<B.sum)&SS)<<" "<<((A.lkey>>(9-B.sum))&SS)<<endl;
r.lkey|=((B.lkey<<A.sum)&SS);
r.lkey|=((((B.lkey>>(9-A.sum))&SS)>>1)<<1);
//cout<<r.lkey<<endl;
r.rkey|=((A.rkey<<B.sum)&SS);
r.rkey|=((((A.rkey>>(9-B.sum))&SS)>>1)<<1);
//cout<<r.key<<endl;
r.key|=r.lkey|r.rkey;
//cout<<"Merge:["<<A.lkey<<" "<<A.rkey<<" "<<A.key<<" "<<A.sum<<"] ["<<B.lkey<<" "<<B.rkey<<" "<<B.key<<" "<<B.sum<<"] ["<<r.lkey<<" "<<r.rkey<<" "<<r.key<<" "<<r.sum<<"]"<<endl;
return r;
}
void Build(int now,int l,int r){
if (l==r){
S[now].lkey=S[now].rkey=S[now].key=(1<<Seq[l]);
S[now].sum=Seq[l];return;
}
int mid=(l+r)>>1;
Build(lson,l,mid);Build(rson,mid+1,r);
S[now]=S[lson]+S[rson];return;
}
SegmentData Query(int now,int l,int r,int ql,int qr){
//cout<<"["<<l<<","<<r<<"]"<<endl;
if ((l==ql)&&(r==qr)) return S[now];
int mid=(l+r)>>1;
if (qr<=mid) return Query(lson,l,mid,ql,qr);
else if (ql>=mid+1) return Query(rson,mid+1,r,ql,qr);
else return Query(lson,l,mid,ql,mid)+Query(rson,mid+1,r,mid+1,qr);
}
/*
10
4 1 9 9 5 5 4 4 7 7
1
4 7
//*/
| 24.989691 | 179 | 0.560644 | SYCstudio |
c5c5ed2eebcc56d6b9c04051215eb73a824b79ae | 762 | cpp | C++ | dumb_kernel.cpp | rioyokotalab/scala20-artifact | 2a438f1fec4f9963d44181578f87c703a5bd4016 | [
"BSD-3-Clause"
] | 1 | 2021-06-10T01:11:55.000Z | 2021-06-10T01:11:55.000Z | dumb_kernel.cpp | rioyokotalab/scala20-artifact | 2a438f1fec4f9963d44181578f87c703a5bd4016 | [
"BSD-3-Clause"
] | null | null | null | dumb_kernel.cpp | rioyokotalab/scala20-artifact | 2a438f1fec4f9963d44181578f87c703a5bd4016 | [
"BSD-3-Clause"
] | null | null | null | #include "utils.hpp"
void dumb_kernel(double *GXYb, int mc, int nc, int xc, int yc, int mb, int nb, double * packA_V,
double * packB_S, double *packB_U, double *packA_S) {
double cmn, exn;
for (int mi = 0; mi < B_SIZE; ++mi) {
for (int ni = 0; ni < B_SIZE; ++ni) {
for (int ki = 0; ki < K_SIZE; ++ki) {
for (int xi = 0; xi < B_SIZE; ++xi) {
for (int yi = 0; yi < B_SIZE; ++yi) {
cmn = packA_V[(mc * block_size + mi) + ki * VEC_SIZE] *
packB_U[ki * VEC_SIZE + nb + nc + ni];
exn = packA_S[(mi + mc + mb) * VEC_SIZE + (xc + xi) ] * cmn;
GXYb[(xc + xi) * LDA_S + yc + yi] += exn * packB_S[nc + ni * VEC_SIZE + (yc + yi)];
}
}
}
}
}
}
| 34.636364 | 96 | 0.472441 | rioyokotalab |
c5c7b40f5fc1e12a15e2b359e6552cfa5cae6088 | 10,416 | cpp | C++ | xlib/Drawing.cpp | X547/xlibe | fbab795ad8a86503174ecfcb8603ec868537d069 | [
"MIT"
] | 1 | 2022-01-02T16:10:26.000Z | 2022-01-02T16:10:26.000Z | xlib/Drawing.cpp | X547/xlibe | fbab795ad8a86503174ecfcb8603ec868537d069 | [
"MIT"
] | null | null | null | xlib/Drawing.cpp | X547/xlibe | fbab795ad8a86503174ecfcb8603ec868537d069 | [
"MIT"
] | null | null | null | /*
* Copyright 2003, Shibukawa Yoshiki. All rights reserved.
* Copyright 2003, kazuyakt. All rights reserved.
* Copyright 2021, Haiku, Inc. All rights reserved.
* Distributed under the terms of the MIT license.
*/
#include "Drawing.h"
#include <interface/Bitmap.h>
#include <interface/Polygon.h>
#include "Drawables.h"
#include "Font.h"
#include "GC.h"
extern "C" {
#include <X11/Xlib.h>
#include <X11/Xlibint.h>
}
#include "Debug.h"
static pattern
pattern_for(GC gc)
{
pattern ptn;
switch (gc->values.fill_style) {
default:
case FillSolid:
ptn = B_SOLID_HIGH;
break;
case FillTiled:
case FillStippled:
// TODO: proper implementation?
case FillOpaqueStippled:
ptn = B_MIXED_COLORS;
break;
}
return ptn;
}
extern "C" int
XDrawLine(Display *display, Drawable w, GC gc,
int x1, int y1, int x2, int y2)
{
XSegment seg;
seg.x1 = x1;
seg.y1 = y1;
seg.x2 = x2;
seg.y2 = y2;
return XDrawSegments(display, w, gc, &seg, 1);
}
extern "C" int
XDrawSegments(Display *display, Drawable w, GC gc,
XSegment *segments, int ns)
{
XDrawable* window = Drawables::get(w);
BView* view = window->view();
view->LockLooper();
bex_check_gc(window, gc);
for(int i = 0; i < ns; i++) {
BPoint point1(segments[i].x1, segments[i].y1);
BPoint point2(segments[i].x2, segments[i].y2);
view->StrokeLine(point1, point2, pattern_for(gc));
}
view->UnlockLooper();
return 0;
}
extern "C" int
XDrawLines(Display *display, Drawable w, GC gc,
XPoint *points, int np, int mode)
{
int i;
short wx, wy;
wx = 0;
wy = 0;
XDrawable* window = Drawables::get(w);
BView* view = window->view();
view->LockLooper();
bex_check_gc(window, gc);
switch( mode ) {
case CoordModeOrigin :
for( i=0; i<(np-1); i++ ) {
BPoint point1(points[i].x, points[i].y);
BPoint point2(points[i+1].x, points[i+1].y);
view->StrokeLine(point1, point2, pattern_for(gc));
}
break;
case CoordModePrevious:
for( i=0; i<np; i++ ) {
if ( i==0 ) {
wx = wx + points[i].x;
wy = wy + points[i].y;
BPoint point1( wx, wy );
BPoint point2( wx, wy );
view->StrokeLine(point1, point2, pattern_for(gc));
}
else {
BPoint point3( wx, wy );
wx = wx + points[i].x;
wy = wy + points[i].y;
BPoint point4( wx, wy );
view->StrokeLine(point3, point4, pattern_for(gc));
}
}
break;
}
view->UnlockLooper();
return 0;
}
extern "C" int
XDrawRectangle(Display *display, Drawable w, GC gc,
int x,int y, unsigned int width, unsigned int height)
{
XRectangle rect;
rect.x = x;
rect.y = y;
rect.width = width;
rect.height = height;
return XDrawRectangles(display, w, gc, &rect, 1);
}
extern "C" int
XDrawRectangles(Display *display, Drawable w, GC gc,
XRectangle *rect, int n)
{
XDrawable* window = Drawables::get(w);
BView* view = window->view();
view->LockLooper();
bex_check_gc(window, gc);
for (int i = 0; i < n; i++) {
view->StrokeRect(brect_from_xrect(rect[i]), pattern_for(gc));
}
view->UnlockLooper();
return 0;
}
extern "C" int
XFillRectangle(Display *display, Drawable win, GC gc,
int x, int y, unsigned int w, unsigned int h)
{
XRectangle rect;
rect.x = x;
rect.y = y;
rect.width = w;
rect.height = h;
return XFillRectangles(display, win, gc, &rect, 1);
}
extern "C" int
XFillRectangles(Display *display, Drawable w, GC gc,
XRectangle *rect, int n)
{
XDrawable* window = Drawables::get(w);
BView* view = window->view();
view->LockLooper();
bex_check_gc(window, gc);
for (int i = 0; i < n; i++) {
view->FillRect(brect_from_xrect(rect[i]), pattern_for(gc));
}
view->UnlockLooper();
return 0;
}
extern "C" int
XDrawArc(Display *display, Drawable w, GC gc,
int x, int y, unsigned int width,unsigned height, int a1, int a2)
{
XArc arc;
arc.x = x;
arc.y = y;
arc.width = width;
arc.height = height;
arc.angle1 = a1;
arc.angle2 = a2;
return XDrawArcs(display, w, gc, &arc, 1);
}
extern "C" int
XDrawArcs(Display *display, Drawable w, GC gc, XArc *arc, int n)
{
// FIXME: Take arc_mode into account!
XDrawable* window = Drawables::get(w);
BView* view = window->view();
view->LockLooper();
bex_check_gc(window, gc);
for (int i = 0; i < n; i++) {
view->StrokeArc(brect_from_xrect(make_xrect(arc[i].x, arc[i].y, arc[i].width, arc[i].height)),
((float)arc[i].angle1) / 64, ((float)arc[i].angle2) / 64,
pattern_for(gc));
}
view->UnlockLooper();
return 0;
}
extern "C" int
XFillArc(Display *display, Drawable w, GC gc,
int x, int y, unsigned int width, unsigned height, int a1, int a2)
{
XArc arc;
arc.x = x;
arc.y = y;
arc.width = width;
arc.height = height;
arc.angle1 = a1;
arc.angle2 = a2;
return XFillArcs(display, w, gc, &arc, 1);
}
extern "C" int
XFillArcs(Display *display, Drawable w, GC gc,
XArc *arc, int n)
{
// FIXME: Take arc_mode into account!
XDrawable* window = Drawables::get(w);
BView* view = window->view();
view->LockLooper();
bex_check_gc(window, gc);
for (int i = 0; i < n; i++) {
view->FillArc(brect_from_xrect(make_xrect(arc[i].x, arc[i].y, arc[i].width, arc[i].height)),
((float)arc[i].angle1) / 64.0f, ((float)arc[i].angle2) / 64.0f,
pattern_for(gc));
}
view->UnlockLooper();
return 0;
}
extern "C" int
XFillPolygon(Display *display, Drawable w, GC gc,
XPoint *points, int npoints, int shape, int mode)
{
BPolygon polygon;
switch (mode) {
case CoordModeOrigin :
for(int i = 0; i < npoints; i++) {
BPoint point(points[i].x, points[i].y);
polygon.AddPoints(&point, 1);
}
break;
case CoordModePrevious: {
int wx = 0, wy = 0;
for(int i = 0; i < npoints; i++) {
wx = wx + points[i].x;
wy = wy + points[i].y;
BPoint point(wx, wy);
polygon.AddPoints(&point, 1);
}
break;
}
}
XDrawable* window = Drawables::get(w);
BView* view = window->view();
view->LockLooper();
bex_check_gc(window, gc);
view->FillPolygon(&polygon, pattern_for(gc));
view->UnlockLooper();
return 0;
}
extern "C" int
XDrawPoint(Display *display, Drawable w, GC gc, int x, int y)
{
XPoint point;
point.x = x;
point.y = y;
return XDrawPoints(display, w, gc, &point, 1, CoordModeOrigin);
}
extern "C" int
XDrawPoints(Display *display, Drawable w, GC gc,
XPoint* points, int n, int mode)
{
XDrawable* window = Drawables::get(w);
BView* view = window->view();
view->LockLooper();
bex_check_gc(window, gc);
view->PushState();
view->SetPenSize(1);
switch (mode) {
case CoordModeOrigin :
for (int i = 0; i < n; i++) {
BPoint point(points[i].x, points[i].y);
view->StrokeLine(point, point, pattern_for(gc));
}
break;
case CoordModePrevious: {
short wx = 0, wy = 0;
for (int i = 0; i < n; i++) {
wx = wx + points[i].x;
wy = wy + points[i].y;
BPoint point( wx, wy );
view->StrokeLine(point, point, pattern_for(gc));
}
break;
}
}
view->PopState();
view->UnlockLooper();
return 0;
}
extern "C" int
XCopyArea(Display* display, Drawable src, Drawable dest, GC gc,
int src_x, int src_y, unsigned int width, unsigned int height, int dest_x, int dest_y)
{
XDrawable* src_d = Drawables::get(src);
XDrawable* dest_d = Drawables::get(dest);
if (!src_d || !dest_d)
return BadDrawable;
const BRect src_rect = brect_from_xrect(make_xrect(src_x, src_y, width, height));
const BRect dest_rect = brect_from_xrect(make_xrect(dest_x, dest_y, width, height));
if (src_d == dest_d) {
src_d->view()->LockLooper();
bex_check_gc(src_d, gc);
src_d->view()->CopyBits(src_rect, dest_rect);
src_d->view()->UnlockLooper();
return Success;
}
XPixmap* src_pxm = dynamic_cast<XPixmap*>(src_d);
if (src_pxm) {
src_pxm->sync();
dest_d->view()->LockLooper();
bex_check_gc(dest_d, gc);
dest_d->view()->DrawBitmap(src_pxm->offscreen(), src_rect, dest_rect);
dest_d->view()->UnlockLooper();
return Success;
}
// TODO?
UNIMPLEMENTED();
return BadValue;
}
extern "C" int
XCopyPlane(Display *display, Drawable src, Drawable dest, GC gc,
int src_x, int src_y, unsigned int width, unsigned int height,
int dest_x, int dest_y, unsigned long plane)
{
// TODO: Actually use "plane"!
return XCopyArea(display, src, dest, gc, src_x, src_y, width, height, dest_x, dest_y);
}
extern "C" int
XPutImage(Display *display, Drawable d, GC gc, XImage* image,
int src_x, int src_y, int dest_x, int dest_y,
unsigned int width, unsigned int height)
{
XDrawable* drawable = Drawables::get(d);
if (!drawable)
return BadDrawable;
BBitmap* bbitmap = (BBitmap*)image->obdata;
if (image->data != bbitmap->Bits()) {
// We must import the bits before drawing.
// TODO: Optimization: Import only the bits we are about to draw!
bbitmap->ImportBits(image->data, image->height * image->bytes_per_line,
image->bytes_per_line, image->xoffset, bbitmap->ColorSpace());
}
BView* view = drawable->view();
view->LockLooper();
bex_check_gc(drawable, gc);
view->DrawBitmap(bbitmap, brect_from_xrect(make_xrect(src_x, src_y, width, height)),
brect_from_xrect(make_xrect(dest_x, dest_y, width, height)));
view->UnlockLooper();
return Success;
}
extern "C" void
Xutf8DrawString(Display *display, Drawable w, XFontSet set, GC gc, int x, int y, const char* str, int len)
{
// FIXME: Use provided fonts!
XDrawable* window = Drawables::get(w);
BView* view = window->view();
view->LockLooper();
bex_check_gc(window, gc);
view->DrawString(str, len, BPoint(x, y));
view->UnlockLooper();
}
extern "C" int
XDrawString(Display* display, Drawable w, GC gc, int x, int y, const char* str, int len)
{
Xutf8DrawString(display, w, NULL, gc, x, y, str, len);
return 0;
}
extern "C" void
Xutf8DrawImageString(Display *display, Drawable w, XFontSet set, GC gc,
int x, int y, const char* str, int len)
{
Xutf8DrawString(display, w, set, gc, x, y, str, len);
}
extern "C" int
XDrawImageString(Display *display, Drawable w, GC gc, int x, int y, const char* str, int len)
{
return XDrawString(display, w, gc, x, y, str, len);
}
extern "C" int
XDrawText(Display *display, Drawable w, GC gc, int x, int y, XTextItem* items, int count)
{
XDrawable* window = Drawables::get(w);
BView* view = window->view();
view->LockLooper();
bex_check_gc(window, gc);
view->PushState();
for (int i = 0; i < count; i++) {
if (items[i].font != None) {
BFont font = bfont_from_font(items[i].font);
view->SetFont(&font);
}
view->DrawString(items[i].chars, items[i].nchars, BPoint(x, y));
x += view->StringWidth(items[i].chars, items[i].nchars);
x += items[i].delta;
}
view->PopState();
view->UnlockLooper();
return 0;
}
| 24.223256 | 106 | 0.66225 | X547 |
c5c83e5489bc07df68ab6b618831b6c3ad512abc | 188 | cpp | C++ | src/backends/windows/has_last_error.cpp | freundlich/libawl | 0d51f388a6b662373058cb51a24ef25ed826fa0f | [
"BSL-1.0"
] | null | null | null | src/backends/windows/has_last_error.cpp | freundlich/libawl | 0d51f388a6b662373058cb51a24ef25ed826fa0f | [
"BSL-1.0"
] | null | null | null | src/backends/windows/has_last_error.cpp | freundlich/libawl | 0d51f388a6b662373058cb51a24ef25ed826fa0f | [
"BSL-1.0"
] | null | null | null | #include <awl/backends/windows/has_last_error.hpp>
#include <awl/backends/windows/windows.hpp>
bool awl::backends::windows::has_last_error() { return ::GetLastError() != ERROR_SUCCESS; }
| 37.6 | 91 | 0.765957 | freundlich |
c5ca729a61faf3428f30752fc18548673c8ddfdd | 18,824 | cc | C++ | src/buffers.cc | klantz81/feature-detection | 1ed289711128a30648e198b085534fe9a9610984 | [
"MIT"
] | null | null | null | src/buffers.cc | klantz81/feature-detection | 1ed289711128a30648e198b085534fe9a9610984 | [
"MIT"
] | null | null | null | src/buffers.cc | klantz81/feature-detection | 1ed289711128a30648e198b085534fe9a9610984 | [
"MIT"
] | null | null | null | #include "buffers.h"
// cFloatBuffer /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
cFloatBuffer::cFloatBuffer() : width(0), height(0), buffer(0) { }
cFloatBuffer::cFloatBuffer(int width, int height) : width(width), height(height) { this->buffer = new float[this->width*this->height]; for (int i = 0; i < this->width * this->height; i++) this->buffer[i] = 0.0f; }
cFloatBuffer::~cFloatBuffer() { if (this->buffer) delete [] buffer; }
cFloatBuffer& cFloatBuffer::operator=(const cFloatBuffer& buffer) {
if (this->width != buffer.width || this->height != buffer.height) {
this->width = buffer.width;
this->height = buffer.height;
if (this->buffer) delete [] this->buffer;
this->buffer = new float[this->width*this->height];
}
for (int i = 0; i < this->width * this->height; i++)
this->buffer[i] = buffer.buffer[i];
return *this;
}
// cDoubleBuffer /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int cDoubleBuffer::save_index = 0;
cDoubleBuffer::cDoubleBuffer() : width(0), height(0), buffer(0) { }
cDoubleBuffer::cDoubleBuffer(int width, int height) : width(width), height(height) { this->buffer = new double[this->width*this->height]; for (int i = 0; i < this->width * this->height; i++) this->buffer[i] = 0.0; }
cDoubleBuffer::cDoubleBuffer(const cDoubleBuffer& buffer) : width(buffer.width), height(buffer.height), buffer(0) {
this->buffer = new double[this->width*this->height];
for (int i = 0; i < this->width*this->height; i++) this->buffer[i] = buffer.buffer[i];
}
cDoubleBuffer::~cDoubleBuffer() { if (this->buffer) delete [] buffer; }
cDoubleBuffer& cDoubleBuffer::operator=(const cDoubleBuffer& buffer) {
if (this->width != buffer.width || this->height != buffer.height) {
this->width = buffer.width;
this->height = buffer.height;
if (this->buffer) delete [] this->buffer;
this->buffer = new double[this->width*this->height];
}
for (int i = 0; i < this->width * this->height; i++)
this->buffer[i] = buffer.buffer[i];
return *this;
}
cFloatBuffer cDoubleBuffer::toFloat(float scale_factor) {
cFloatBuffer buf(this->width, this->height);
for (int i = 0; i < this->width * this->height; i++)
buf.buffer[i] = (float)this->buffer[i] * scale_factor;
return buf;
}
void cDoubleBuffer::save() {
cDoubleBuffer::save_index++;
std::stringstream s;
s << "media_save/buffer" << (save_index < 10 ? "000" : (save_index < 100 ? "00" : (save_index < 1000 ? "0" : ""))) << save_index << ".pgm";
std::fstream of(s.str().c_str(), std::ios_base::out | std::ios_base::trunc);
of << "P2" << std::endl;
of << this->width << " " << this->height << std::endl;
of << "255" << std::endl;
for (int j = 0; j < this->height; j++) {
for (int i = 0; i < this->width; i++) {
int p = (int)(this->buffer[j * this->width + i] * 255.0);
p = CLAMP(p, 0, 255);
of << p << " ";
}
of << std::endl;
}
}
void cDoubleBuffer::save(const char* file) {
std::fstream of(file, std::ios_base::out | std::ios_base::trunc);
of << "P2" << std::endl;
of << this->width << " " << this->height << std::endl;
of << "255" << std::endl;
for (int j = 0; j < this->height; j++) {
for (int i = 0; i < this->width; i++) {
int p = (int)(this->buffer[j * this->width + i] * 255.0);
p = CLAMP(p, 0, 255);
of << p << " ";
}
of << std::endl;
}
}
double cDoubleBuffer::operator[](int index) const {
return (index >= 0 && index < this->width * this->height) ? this->buffer[index] : 0.0;
}
double cDoubleBuffer::at(int index) const {
return (index >= 0 && index < this->width * this->height) ? this->buffer[index] : 0.0;
}
double cDoubleBuffer::at(int x, int y) const {
int index = y * this->width + x;
return (index >= 0 && index < this->width * this->height) ? this->buffer[index] : 0.0;
}
double cDoubleBuffer::interpolate(double x, double y) const {
x = CLAMP(x, 0.000001, this->width - 1.000001);
y = CLAMP(y, 0.000001, this->height - 1.000001);
int x0 = (int)x,
y0 = (int)y;
double s0 = x - x0,
s1 = y - y0;
double t = this->buffer[(y0 + 0) * this->width + x0 + 0]*(1 - s0)*(1 - s1) +
this->buffer[(y0 + 0) * this->width + x0 + 1]*( s0)*(1 - s1) +
this->buffer[(y0 + 1) * this->width + x0 + 0]*(1 - s0)*( s1) +
this->buffer[(y0 + 1) * this->width + x0 + 1]*( s0)*( s1);
return t;
}
double cDoubleBuffer::sum(int x, int y, const cKernel& kernel) {
double sum = 0.0;
for (int j = -kernel.kernel_radius; j <= kernel.kernel_radius; j++)
for (int i = -kernel.kernel_radius; i <= kernel.kernel_radius; i++)
sum += this->at(x + i, y + j);
return sum;
}
cDoubleBuffer cDoubleBuffer::operator*(const cDoubleBuffer& buffer) {
cDoubleBuffer buf(this->width, this->height);
for (int i = 0; i < this->width * this->height; i++)
buf.buffer[i] = this->buffer[i] * buffer.buffer[i];
return buf;
}
cDoubleBuffer cDoubleBuffer::magnitude(const cDoubleBuffer& buffer) {
cDoubleBuffer buf(this->width, this->height);
for (int i = 0; i < this->width * this->height; i++)
buf.buffer[i] = sqrt(pow(this->buffer[i], 2.0) + pow(buffer.buffer[i], 2.0));
return buf;
}
cDoubleBuffer cDoubleBuffer::sub(int x, int y, const cKernel& kernel) const {
cDoubleBuffer buf(kernel.kernel_radius * 2 + 1, kernel.kernel_radius * 2 + 1);
int index = 0;
for (int j = -kernel.kernel_radius; j <= kernel.kernel_radius; j++)
for (int i = -kernel.kernel_radius; i <= kernel.kernel_radius; i++)
buf.buffer[index++] = this->at(x + i, y + j);
return buf;
}
cDoubleBuffer cDoubleBuffer::subInterpolate(double x, double y, const cKernel& kernel) const {
cDoubleBuffer buf(kernel.kernel_radius * 2 + 1, kernel.kernel_radius * 2 + 1);
int index = 0;
for (int j = -kernel.kernel_radius; j <= kernel.kernel_radius; j++)
for (int i = -kernel.kernel_radius; i <= kernel.kernel_radius; i++)
buf.buffer[index++] = this->interpolate(x + i, y + j);
return buf;
}
cDoubleBuffer cDoubleBuffer::subInterpolate(matrix22 A, vector2 b, const cKernel& kernel) const {
cDoubleBuffer buf(kernel.kernel_radius * 2 + 1, kernel.kernel_radius * 2 + 1);
int index = 0;
for (int j = -kernel.kernel_radius; j <= kernel.kernel_radius; j++)
for (int i = -kernel.kernel_radius; i <= kernel.kernel_radius; i++) {
vector2 x = A * vector2(i, j) + b;
buf.buffer[index++] = this->interpolate(x.x, x.y);
}
return buf;
}
cDoubleBuffer cDoubleBuffer::downsample() {
cDoubleBuffer buf(this->width/2, this->height/2);
for (int j = 0; j < this->height / 2; j++)
for (int i = 0; i < this->width / 2; i++)
buf.buffer[j * this->width / 2 + i] = 0.25 * this->buffer[j * 2 * this->width + i * 2] +
0.125 * (
(j > 0 ? this->buffer[(j - 1) * 2 * this->width + i * 2] : 0.0) +
(j < this->height / 2 - 1 ? this->buffer[(j + 1) * 2 * this->width + i * 2] : 0.0) +
(i > 0 ? this->buffer[j * 2 * this->width + (i - 1) * 2] : 0.0) +
(i < this->width / 2 - 1 ? this->buffer[j * 2 * this->width + (i + 1) * 2] : 0.0)
) +
0.0625 * (
(j > 0 && i > 0 ? this->buffer[(j - 1) * 2 * this->width + (i - 1) * 2] : 0.0) +
(j > 0 && i < this->width / 2 - 1 ? this->buffer[(j - 1) * 2 * this->width + (i + 1) * 2] : 0.0) +
(j < this->height / 2 - 1 && i > 0 ? this->buffer[(j + 1) * 2 * this->width + (i - 1) * 2] : 0.0) +
(j < this->height / 2 - 1 && i < this->width / 2 - 1 ? this->buffer[(j + 1) * 2 * this->width + (i + 1) * 2] : 0.0)
);
return buf;
}
cDoubleBuffer cDoubleBuffer::scharrOperatorX() {
cDoubleBuffer Ix(this->width, this->height);
for (int j = 0; j < this->height; j++)
for (int i = 0; i < this->width; i++)
Ix.buffer[j * this->width + i] = (i > 0 ?
(
(j > 0 ? this->buffer[(j - 1) * this->width + (i - 1)] * -3.0 : 0.0) +
this->buffer[ j * this->width + (i - 1)] * -10.0 +
(j < this->height - 1 ? this->buffer[(j + 1) * this->width + (i - 1)] * -3.0 : 0.0)
) : 0.0) +
(i < this->width - 1 ?
(
(j > 0 ? this->buffer[(j - 1) * this->width + (i + 1)] * 3.0 : 0.0) +
this->buffer[ j * this->width + (i + 1)] * 10.0 +
(j < this->height - 1 ? this->buffer[(j + 1) * this->width + (i + 1)] * 3.0 : 0.0)
) : 0.0);
return Ix;
}
cDoubleBuffer cDoubleBuffer::scharrOperatorY() {
cDoubleBuffer Iy(this->width, this->height);
for (int j = 0; j < this->height; j++)
for (int i = 0; i < this->width; i++)
Iy.buffer[j * this->width + i] = (j > 0 ?
(
(i > 0 ? this->buffer[(j - 1) * this->width + (i - 1)] * -3.0 : 0.0) +
this->buffer[(j - 1) * this->width + i ] * -10.0 +
(i < this->width - 1 ? this->buffer[(j - 1) * this->width + (i + 1)] * -3.0 : 0.0)
) : 0.0) +
(j < this->height - 1 ?
(
(i > 0 ? this->buffer[(j + 1) * this->width + (i - 1)] * 3.0 : 0.0) +
this->buffer[(j + 1) * this->width + i ] * 10.0 +
(i < this->width - 1 ? this->buffer[(j + 1) * this->width + (i + 1)] * 3.0 : 0.0)
) : 0.0);
return Iy;
}
cDoubleBuffer cDoubleBuffer::scharrOperator() {
cDoubleBuffer Ix = this->scharrOperatorX();
cDoubleBuffer Iy = this->scharrOperatorY();
cDoubleBuffer I(this->width, this->height);
for (int i = 0; i < this->width * this->height; i++)
I.buffer[i] = sqrt(Ix.buffer[i]*Ix.buffer[i] + Iy.buffer[i]*Iy.buffer[i]);
return I;
}
cDoubleBuffer cDoubleBuffer::gaussianConvolutionX(const cKernel& kernel) {
cDoubleBuffer buf(this->width, this->height);
for (int j = 0; j < this->height; j++)
for (int i = 0; i < this->width; i++)
for (int k = -kernel.kernel_radius; k <= kernel.kernel_radius; k++)
if (i + k >= 0 && i + k < this->width)
buf.buffer[j * this->width + i] += this->buffer[j * this->width + i + k] * kernel.kernel[k + kernel.kernel_radius];
return buf;
}
cDoubleBuffer cDoubleBuffer::gaussianConvolutionY(const cKernel& kernel) {
cDoubleBuffer buf(this->width, this->height);
for (int j = 0; j < this->height; j++)
for (int i = 0; i < this->width; i++)
for (int k = -kernel.kernel_radius; k <= kernel.kernel_radius; k++)
if (j + k >= 0 && j + k < this->height)
buf.buffer[j * this->width + i] += this->buffer[(j + k) * this->width + i] * kernel.kernel[k + kernel.kernel_radius];
return buf;
}
cDoubleBuffer cDoubleBuffer::gaussianConvolution(const cKernel& kernel) {
return (this->gaussianConvolutionX(kernel)).gaussianConvolutionY(kernel);
}
cDoubleBuffer cDoubleBuffer::gaussianConvolutionDX(const cKernel& kernel) {
cDoubleBuffer buf(this->width, this->height);
for (int j = 0; j < this->height; j++)
for (int i = 0; i < this->width; i++)
for (int k = -kernel.kernel_radius; k <= kernel.kernel_radius; k++)
if (i + k >= 0 && i + k < this->width)
buf.buffer[j * this->width + i] += this->buffer[j * this->width + i + k] * kernel.kernel_derivative[k + kernel.kernel_radius];
return buf;
}
cDoubleBuffer cDoubleBuffer::gaussianConvolutionDY(const cKernel& kernel) {
cDoubleBuffer buf(this->width, this->height);
for (int j = 0; j < this->height; j++)
for (int i = 0; i < this->width; i++)
for (int k = -kernel.kernel_radius; k <= kernel.kernel_radius; k++)
if (j + k >= 0 && j + k < this->height)
buf.buffer[j * this->width + i] += this->buffer[(j + k) * this->width + i] * kernel.kernel_derivative[k + kernel.kernel_radius];
return buf;
}
cDoubleBuffer cDoubleBuffer::gaussianDerivativeX(const cKernel& kernel) {
return (this->gaussianConvolutionDX(kernel)).gaussianConvolutionY(kernel);
}
cDoubleBuffer cDoubleBuffer::gaussianDerivativeY(const cKernel& kernel) {
return (this->gaussianConvolutionX(kernel)).gaussianConvolutionDY(kernel);
}
// cColorBuffer /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int cColorBuffer::save_index = 0;
cColorBuffer::cColorBuffer() : width(0), height(0), bpp(0), buffer(0) { }
cColorBuffer::cColorBuffer(int width, int height, int bpp) : width(width), height(height), bpp(bpp) { this->buffer = new unsigned char[this->width*this->height*this->bpp]; for (int i = 0; i < this->width * this->height * this->bpp; i++) this->buffer[i] = 0; }
cColorBuffer::cColorBuffer(const char* image) {
SDL_Surface *s = IMG_Load(image);
this->width = s->w;
this->height = s->h;
this->bpp = s->format->BitsPerPixel;
this->buffer = new unsigned char[width * height * bpp / 8];
memcpy(buffer, s->pixels, width * height * bpp / 8);
SDL_FreeSurface(s);
}
void cColorBuffer::save() {
cColorBuffer::save_index++;
std::stringstream s;
s << "media_save/cbuffer" << (save_index < 10 ? "000" : (save_index < 100 ? "00" : (save_index < 1000 ? "0" : ""))) << save_index << ".ppm";
std::fstream of(s.str().c_str(), std::ios_base::out | std::ios_base::trunc);
of << "P3" << std::endl;
of << this->width << " " << this->height << std::endl;
of << "255" << std::endl;
for (int j = 0; j < this->height; j++) {
for (int i = 0; i < this->width; i++) {
int r = this->buffer[j * this->width * this->bpp/8 + i * this->bpp/8 + 0]; r = CLAMP(r, 0, 255);
int g = this->buffer[j * this->width * this->bpp/8 + i * this->bpp/8 + 1]; g = CLAMP(g, 0, 255);
int b = this->buffer[j * this->width * this->bpp/8 + i * this->bpp/8 + 2]; b = CLAMP(b, 0, 255);
of << r << " " << g << " " << b << " ";
}
of << std::endl;
}
}
void cColorBuffer::save(const char* file) {
std::fstream of(file, std::ios_base::out | std::ios_base::trunc);
of << "P3" << std::endl;
of << this->width << " " << this->height << std::endl;
of << "255" << std::endl;
for (int j = 0; j < this->height; j++) {
for (int i = 0; i < this->width; i++) {
int r = this->buffer[j * this->width * this->bpp/8 + i * this->bpp/8 + 0]; r = CLAMP(r, 0, 255);
int g = this->buffer[j * this->width * this->bpp/8 + i * this->bpp/8 + 1]; g = CLAMP(g, 0, 255);
int b = this->buffer[j * this->width * this->bpp/8 + i * this->bpp/8 + 2]; b = CLAMP(b, 0, 255);
of << r << " " << g << " " << b << " ";
}
of << std::endl;
}
}
_rgb cColorBuffer::at(int x, int y) const {
int index = y * this->width * this->bpp/8 + x * this->bpp/8;
_rgb rgb = {0,0,0};
if (index >= 0 && index < this->width * this->bpp / 8 * this->height - 2) {
rgb.r = this->buffer[index + 0];
rgb.g = this->buffer[index + 1];
rgb.b = this->buffer[index + 2];
}
return rgb;
}
_rgb cColorBuffer::interpolate(double x, double y) const {
x = CLAMP(x, 0.000001, this->width - 1.000001);
y = CLAMP(y, 0.000001, this->height - 1.000001);
int x0 = (int)x,
y0 = (int)y;
double s0 = x - x0,
s1 = y - y0;
_rgb rgb = {0,0,0};
rgb.r = this->buffer[(y0 + 0) * this->width * this->bpp/8 + (x0 + 0) * this->bpp/8 + 0]*(1 - s0)*(1 - s1) +
this->buffer[(y0 + 0) * this->width * this->bpp/8 + (x0 + 1) * this->bpp/8 + 0]*( s0)*(1 - s1) +
this->buffer[(y0 + 1) * this->width * this->bpp/8 + (x0 + 0) * this->bpp/8 + 0]*(1 - s0)*( s1) +
this->buffer[(y0 + 1) * this->width * this->bpp/8 + (x0 + 1) * this->bpp/8 + 0]*( s0)*( s1);
rgb.g = this->buffer[(y0 + 0) * this->width * this->bpp/8 + (x0 + 0) * this->bpp/8 + 1]*(1 - s0)*(1 - s1) +
this->buffer[(y0 + 0) * this->width * this->bpp/8 + (x0 + 1) * this->bpp/8 + 1]*( s0)*(1 - s1) +
this->buffer[(y0 + 1) * this->width * this->bpp/8 + (x0 + 0) * this->bpp/8 + 1]*(1 - s0)*( s1) +
this->buffer[(y0 + 1) * this->width * this->bpp/8 + (x0 + 1) * this->bpp/8 + 1]*( s0)*( s1);
rgb.b = this->buffer[(y0 + 0) * this->width * this->bpp/8 + (x0 + 0) * this->bpp/8 + 2]*(1 - s0)*(1 - s1) +
this->buffer[(y0 + 0) * this->width * this->bpp/8 + (x0 + 1) * this->bpp/8 + 2]*( s0)*(1 - s1) +
this->buffer[(y0 + 1) * this->width * this->bpp/8 + (x0 + 0) * this->bpp/8 + 2]*(1 - s0)*( s1) +
this->buffer[(y0 + 1) * this->width * this->bpp/8 + (x0 + 1) * this->bpp/8 + 2]*( s0)*( s1);
return rgb;
}
cColorBuffer cColorBuffer::sub(int x, int y, const cKernel& kernel) const {
cColorBuffer buf(kernel.kernel_radius * 2 + 1, kernel.kernel_radius * 2 + 1, this->bpp);
int index = 0;
for (int j = -kernel.kernel_radius; j <= kernel.kernel_radius; j++)
for (int i = -kernel.kernel_radius; i <= kernel.kernel_radius; i++) {
_rgb rgb = this->at(x + i, y + j);
buf.buffer[index + 0] = rgb.r;
buf.buffer[index + 1] = rgb.g;
buf.buffer[index + 2] = rgb.b;
index += buf.bpp / 8;
}
return buf;
}
cColorBuffer cColorBuffer::subInterpolate(double x, double y, const cKernel& kernel) const {
cColorBuffer buf(kernel.kernel_radius * 2 + 1, kernel.kernel_radius * 2 + 1, this->bpp);
int index = 0;
for (int j = -kernel.kernel_radius; j <= kernel.kernel_radius; j++)
for (int i = -kernel.kernel_radius; i <= kernel.kernel_radius; i++) {
_rgb rgb = this->interpolate(x + i, y + j);
buf.buffer[index + 0] = rgb.r;
buf.buffer[index + 1] = rgb.g;
buf.buffer[index + 2] = rgb.b;
index += buf.bpp / 8;
}
return buf;
}
cColorBuffer cColorBuffer::subInterpolate(matrix22 A, vector2 b, const cKernel& kernel) const {
cColorBuffer buf(kernel.kernel_radius * 2 + 1, kernel.kernel_radius * 2 + 1, this->bpp);
int index = 0;
for (int j = -kernel.kernel_radius; j <= kernel.kernel_radius; j++)
for (int i = -kernel.kernel_radius; i <= kernel.kernel_radius; i++) {
vector2 x = A * vector2(i, j) + b;
_rgb rgb = this->interpolate(x.x, x.y);
buf.buffer[index + 0] = rgb.r;
buf.buffer[index + 1] = rgb.g;
buf.buffer[index + 2] = rgb.b;
index += buf.bpp / 8;
}
return buf;
}
cColorBuffer::~cColorBuffer() { if (this->buffer) delete [] buffer; }
void cColorBuffer::load(const char* image) {
SDL_Surface *s = IMG_Load(image);
if (this->width != s->w || this->height != s->h || this->bpp != s->format->BitsPerPixel) {
this->width = s->w;
this->height = s->h;
this->bpp = s->format->BitsPerPixel;
if (this->buffer) delete [] this->buffer;
this->buffer = new unsigned char[this->width*this->height*this->bpp];
}
memcpy(this->buffer, s->pixels, this->width * this->height * this->bpp / 8);
SDL_FreeSurface(s);
}
cDoubleBuffer cColorBuffer::grayscale() {
cDoubleBuffer buf(this->width, this->height);
for (int i = 0; i < this->width * this->height; i++)
buf.buffer[i] = (this->buffer[i * this->bpp / 8 + 0] / 255.0 * 0.30 +
this->buffer[i * this->bpp / 8 + 1] / 255.0 * 0.59 +
this->buffer[i * this->bpp / 8 + 2] / 255.0 * 0.11);
return buf;
}
| 41.462555 | 259 | 0.562208 | klantz81 |
c5cadfbc305bb5d1e535e8f8fcaa60d267412bdb | 2,763 | cpp | C++ | overhead-detect/src/modules/view/ImageGridWindow.cpp | cn0512/PokeDetective | b2785350010a00391c1349046a78f7e27c3af564 | [
"Apache-2.0"
] | null | null | null | overhead-detect/src/modules/view/ImageGridWindow.cpp | cn0512/PokeDetective | b2785350010a00391c1349046a78f7e27c3af564 | [
"Apache-2.0"
] | null | null | null | overhead-detect/src/modules/view/ImageGridWindow.cpp | cn0512/PokeDetective | b2785350010a00391c1349046a78f7e27c3af564 | [
"Apache-2.0"
] | null | null | null | #ifndef IMAGE_GRID_WINDOW_CPP
#define IMAGE_GRID_WINDOW_CPP
#include <assert.h>
#include <string>
#include <opencv2/opencv.hpp>
#include "ImageGridCell.cpp"
using namespace cv;
class ImageGridWindow {
private:
String title;
Size size;
bool isVisible;
int rows;
int cols;
vector<ImageGridCell> cells;
ImageGridCell& cell(int i, int j) {
return cells[i + j * rows];
}
public:
ImageGridWindow(String title, int rows = 1, int cols = 1) {
this->title = title;
this->isVisible = false;
this->rows = rows;
this->cols = cols;
this->cells = vector<ImageGridCell>(rows * cols);
}
ImageGridWindow* setGridCellTitle(int i, int j, String title) {
cell(i, j).setTitle(title);
return this;
}
ImageGridWindow* setGridCellImage(int i, int j, Mat image) {
cell(i, j).setImage(image);
return this;
}
ImageGridWindow* setSize(int width, int height) {
assert(!isVisible);
size = Size(width, height);
return this;
}
ImageGridWindow* addTrackbar(string name, int* value, int maxValue) {
assert(isVisible);
createTrackbar(name, title, value, maxValue);
return this;
}
ImageGridWindow* show() {
assert(!isVisible);
namedWindow(title, WINDOW_NORMAL);
resizeWindow(title, size.width, size.height);
isVisible = true;
return this;
}
void draw() {
assert(isVisible);
Mat image(size.height, size.width, CV_8UC3);
Size cellImageSize = Size(size.width / cols, size.height / rows);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
Rect cellROIRect = Rect(j * cellImageSize.width, i * cellImageSize.height, cellImageSize.width, cellImageSize.height);
if (cell(i, j).hasImage()) {
Mat cellImage;
resize(cell(i, j).getImage(), cellImage, cellImageSize);
if (cellImage.type() == CV_8UC1) {
cvtColor(cellImage, cellImage, CV_GRAY2RGB);
}
cellImage.copyTo(image(cellROIRect));
}
String cellTitle = cell(i, j).getTitle();
Size cellTitleTextSize = getTextSize(cellTitle, FONT_HERSHEY_COMPLEX_SMALL, 1.0, 1, NULL);
putText(image, cellTitle, Point(cellROIRect.x + (cellROIRect.width / 2 - cellTitleTextSize.width / 2), cellTitleTextSize.height + 8), FONT_HERSHEY_COMPLEX_SMALL, 0.75, Scalar(0, 0, 255));
}
}
imshow(title, image);
waitKey(1);
}
};
#endif | 26.314286 | 203 | 0.564604 | cn0512 |
c5cbfaea8c07ab64173da8ec2ebef8d5001cb145 | 573 | cpp | C++ | modules/dh2320lab1/dh2320lab1module.cpp | victorca25/inviwo | 34b6675f6b791a08e358d24aea4f75d5baadc6da | [
"BSD-2-Clause"
] | null | null | null | modules/dh2320lab1/dh2320lab1module.cpp | victorca25/inviwo | 34b6675f6b791a08e358d24aea4f75d5baadc6da | [
"BSD-2-Clause"
] | null | null | null | modules/dh2320lab1/dh2320lab1module.cpp | victorca25/inviwo | 34b6675f6b791a08e358d24aea4f75d5baadc6da | [
"BSD-2-Clause"
] | null | null | null | /*********************************************************************
* Author : Himangshu Saikia
* Init : Thursday, October 12, 2017 - 11:10:04
*
* Project : KTH Inviwo Modules
*
* License : Follows the Inviwo BSD license model
*********************************************************************
*/
#include <dh2320lab1/dh2320lab1module.h>
#include <dh2320lab1/cubeanimator.h>
namespace inviwo
{
DH2320Lab1Module::DH2320Lab1Module(InviwoApplication* app) : InviwoModule(app, "DH2320Lab1")
{
registerProcessor<CubeAnimator>();
}
} // namespace
| 23.875 | 92 | 0.535777 | victorca25 |
c5cf4a2e6f99f5132de6b89e9d404cfcd2f4f7bf | 25,849 | cc | C++ | chrome/browser/ui/webui/management_ui_handler_unittest.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/ui/webui/management_ui_handler_unittest.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/ui/webui/management_ui_handler_unittest.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <memory>
#include <set>
#include <string>
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/ui/webui/management_ui_handler.h"
#include "chrome/test/base/testing_profile.h"
#include "components/policy/core/common/mock_policy_service.h"
#include "components/policy/core/common/policy_map.h"
#include "components/policy/core/common/policy_namespace.h"
#include "components/policy/core/common/policy_service.h"
#include "components/policy/policy_constants.h"
#include "components/strings/grit/components_strings.h"
#include "content/public/test/browser_task_environment.h"
#include "extensions/common/extension.h"
#include "extensions/common/extension_builder.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/l10n/l10n_util.h"
#if defined(OS_CHROMEOS)
#include "ui/chromeos/devicetype_utils.h"
#endif // defined(OS_CHROMEOS)
using testing::_;
using testing::Return;
using testing::ReturnRef;
struct ContextualManagementSourceUpdate {
base::string16 extension_reporting_title;
base::string16 subtitle;
#if defined(OS_CHROMEOS)
base::string16 management_overview;
#else
base::string16 browser_management_notice;
#endif // defined(OS_CHROMEOS)
bool managed;
};
class TestManagementUIHandler : public ManagementUIHandler {
public:
TestManagementUIHandler() = default;
explicit TestManagementUIHandler(policy::PolicyService* policy_service)
: policy_service_(policy_service) {}
~TestManagementUIHandler() override = default;
void EnableCloudReportingExtension(bool enable) {
cloud_reporting_extension_exists_ = enable;
}
base::Value GetContextualManagedDataForTesting(Profile* profile) {
return GetContextualManagedData(profile);
}
base::Value GetExtensionReportingInfo() {
base::Value report_sources(base::Value::Type::LIST);
AddReportingInfo(&report_sources);
return report_sources;
}
base::Value GetThreatProtectionInfo(Profile* profile) {
return ManagementUIHandler::GetThreatProtectionInfo(profile);
}
policy::PolicyService* GetPolicyService() const override {
return policy_service_;
}
const extensions::Extension* GetEnabledExtension(
const std::string& extensionId) const override {
if (cloud_reporting_extension_exists_)
return extensions::ExtensionBuilder("dummy").SetID("id").Build().get();
return nullptr;
}
#if defined(OS_CHROMEOS)
const std::string GetDeviceDomain() const override { return device_domain; }
void SetDeviceDomain(const std::string& domain) { device_domain = domain; }
#endif // defined(OS_CHROMEOS)
private:
bool cloud_reporting_extension_exists_ = false;
policy::PolicyService* policy_service_ = nullptr;
std::string device_domain = "devicedomain.com";
};
class ManagementUIHandlerTests : public testing::Test {
public:
ManagementUIHandlerTests()
: handler_(&policy_service_),
device_domain_(base::UTF8ToUTF16("devicedomain.com")) {
ON_CALL(policy_service_, GetPolicies(_))
.WillByDefault(ReturnRef(empty_policy_map_));
}
base::string16 device_domain() { return device_domain_; }
void EnablePolicy(const char* policy_key, policy::PolicyMap& policies) {
policies.Set(policy_key, policy::POLICY_LEVEL_MANDATORY,
policy::POLICY_SCOPE_MACHINE, policy::POLICY_SOURCE_CLOUD,
std::make_unique<base::Value>(true), nullptr);
}
void SetPolicyValue(const char* policy_key,
policy::PolicyMap& policies,
int value) {
policies.Set(policy_key, policy::POLICY_LEVEL_MANDATORY,
policy::POLICY_SCOPE_MACHINE, policy::POLICY_SOURCE_CLOUD,
std::make_unique<base::Value>(value), nullptr);
}
void SetPolicyValue(const char* policy_key,
policy::PolicyMap& policies,
bool value) {
policies.Set(policy_key, policy::POLICY_LEVEL_MANDATORY,
policy::POLICY_SCOPE_MACHINE, policy::POLICY_SOURCE_CLOUD,
std::make_unique<base::Value>(value), nullptr);
}
base::string16 ExtractPathFromDict(const base::Value& data,
const std::string path) {
const std::string* buf = data.FindStringPath(path);
if (!buf)
return base::string16();
return base::UTF8ToUTF16(*buf);
}
void ExtractContextualSourceUpdate(const base::Value& data) {
extracted_.extension_reporting_title =
ExtractPathFromDict(data, "extensionReportingTitle");
extracted_.subtitle = ExtractPathFromDict(data, "pageSubtitle");
#if defined(OS_CHROMEOS)
extracted_.management_overview = ExtractPathFromDict(data, "overview");
#else
extracted_.browser_management_notice =
ExtractPathFromDict(data, "browserManagementNotice");
#endif // defined(OS_CHROMEOS)
base::Optional<bool> managed = data.FindBoolPath("managed");
extracted_.managed = managed.has_value() && managed.value();
}
void PrepareProfileAndHandler() {
PrepareProfileAndHandler(std::string(), false, true, false,
"devicedomain.com");
}
void PrepareProfileAndHandler(const std::string& profile_name,
bool override_policy_connector_is_managed,
bool use_account,
bool use_device) {
PrepareProfileAndHandler(profile_name, override_policy_connector_is_managed,
use_account, use_device, "devicedomain.com");
}
void PrepareProfileAndHandler(const std::string& profile_name,
bool override_policy_connector_is_managed,
bool use_account,
bool use_device,
const std::string& device_domain) {
TestingProfile::Builder builder;
builder.SetProfileName(profile_name);
if (override_policy_connector_is_managed) {
builder.OverridePolicyConnectorIsManagedForTesting(true);
}
profile_ = builder.Build();
handler_.SetAccountManagedForTesting(use_account);
handler_.SetDeviceManagedForTesting(use_device);
#if defined(OS_CHROMEOS)
handler_.SetDeviceDomain(device_domain);
#endif
base::Value data =
handler_.GetContextualManagedDataForTesting(profile_.get());
ExtractContextualSourceUpdate(data);
}
bool GetManaged() const { return extracted_.managed; }
#if defined(OS_CHROMEOS)
base::string16 GetManagementOverview() const {
return extracted_.management_overview;
}
#else
base::string16 GetBrowserManagementNotice() const {
return extracted_.browser_management_notice;
}
#endif
base::string16 GetExtensionReportingTitle() const {
return extracted_.extension_reporting_title;
}
base::string16 GetPageSubtitle() const { return extracted_.subtitle; }
protected:
TestManagementUIHandler handler_;
content::BrowserTaskEnvironment task_environment_;
policy::MockPolicyService policy_service_;
policy::PolicyMap empty_policy_map_;
base::string16 device_domain_;
ContextualManagementSourceUpdate extracted_;
std::unique_ptr<TestingProfile> profile_;
};
void ExpectMessagesToBeEQ(base::Value::ConstListView infolist,
const std::set<std::string>& expected_messages) {
ASSERT_EQ(infolist.size(), expected_messages.size());
std::set<std::string> tmp_expected(expected_messages);
for (const base::Value& info : infolist) {
const std::string* message_id = info.FindStringKey("messageId");
if (message_id) {
EXPECT_EQ(1u, tmp_expected.erase(*message_id));
}
}
EXPECT_TRUE(tmp_expected.empty());
}
#if !defined(OS_CHROMEOS)
TEST_F(ManagementUIHandlerTests,
ManagementContextualSourceUpdateUnmanagedNoDomain) {
PrepareProfileAndHandler(
/* profile_name= */ "",
/* override_policy_connector_is_managed= */ false,
/* use_account= */ false,
/* use_device= */ false);
EXPECT_EQ(GetExtensionReportingTitle(),
l10n_util::GetStringUTF16(IDS_MANAGEMENT_EXTENSIONS_INSTALLED));
EXPECT_EQ(GetBrowserManagementNotice(),
l10n_util::GetStringFUTF16(
IDS_MANAGEMENT_NOT_MANAGED_NOTICE,
base::UTF8ToUTF16(chrome::kManagedUiLearnMoreUrl)));
EXPECT_EQ(GetPageSubtitle(),
l10n_util::GetStringUTF16(IDS_MANAGEMENT_NOT_MANAGED_SUBTITLE));
}
TEST_F(ManagementUIHandlerTests,
ManagementContextualSourceUpdateManagedNoDomain) {
PrepareProfileAndHandler();
EXPECT_EQ(GetExtensionReportingTitle(),
l10n_util::GetStringUTF16(IDS_MANAGEMENT_EXTENSIONS_INSTALLED));
EXPECT_EQ(GetBrowserManagementNotice(),
l10n_util::GetStringFUTF16(
IDS_MANAGEMENT_BROWSER_NOTICE,
base::UTF8ToUTF16(chrome::kManagedUiLearnMoreUrl)));
EXPECT_EQ(GetPageSubtitle(),
l10n_util::GetStringUTF16(IDS_MANAGEMENT_SUBTITLE));
EXPECT_TRUE(GetManaged());
}
TEST_F(ManagementUIHandlerTests,
ManagementContextualSourceUpdateManagedConsumerDomain) {
PrepareProfileAndHandler(
/* profile_name= */ "managed@gmail.com",
/* override_policy_connector_is_managed= */ true,
/* use_account= */ true, /* use_device= */ false);
EXPECT_EQ(GetExtensionReportingTitle(),
l10n_util::GetStringUTF16(IDS_MANAGEMENT_EXTENSIONS_INSTALLED));
EXPECT_EQ(GetBrowserManagementNotice(),
l10n_util::GetStringFUTF16(
IDS_MANAGEMENT_BROWSER_NOTICE,
base::UTF8ToUTF16(chrome::kManagedUiLearnMoreUrl)));
EXPECT_EQ(GetPageSubtitle(),
l10n_util::GetStringUTF16(IDS_MANAGEMENT_SUBTITLE));
EXPECT_TRUE(GetManaged());
}
TEST_F(ManagementUIHandlerTests,
ManagementContextualSourceUpdateUnmanagedKnownDomain) {
const std::string domain = "manager.com";
PrepareProfileAndHandler(
/* profile_name= */ "managed@" + domain,
/* override_policy_connector_is_managed= */ true,
/* use_account= */ false, /* use_device= */ false);
EXPECT_EQ(GetExtensionReportingTitle(),
l10n_util::GetStringFUTF16(IDS_MANAGEMENT_EXTENSIONS_INSTALLED_BY,
base::UTF8ToUTF16(domain)));
EXPECT_EQ(GetBrowserManagementNotice(),
l10n_util::GetStringFUTF16(
IDS_MANAGEMENT_NOT_MANAGED_NOTICE,
base::UTF8ToUTF16(chrome::kManagedUiLearnMoreUrl)));
EXPECT_EQ(GetPageSubtitle(),
l10n_util::GetStringUTF16(IDS_MANAGEMENT_NOT_MANAGED_SUBTITLE));
EXPECT_FALSE(GetManaged());
}
TEST_F(ManagementUIHandlerTests,
ManagementContextualSourceUpdateUnmanagedCustomerDomain) {
PrepareProfileAndHandler(
/* profile_name= */ "managed@googlemail.com",
/* override_policy_connector_is_managed= */ false,
/* use_account= */ false, /* use_device= */ false);
EXPECT_EQ(GetExtensionReportingTitle(),
l10n_util::GetStringUTF16(IDS_MANAGEMENT_EXTENSIONS_INSTALLED));
EXPECT_EQ(GetBrowserManagementNotice(),
l10n_util::GetStringFUTF16(
IDS_MANAGEMENT_NOT_MANAGED_NOTICE,
base::UTF8ToUTF16(chrome::kManagedUiLearnMoreUrl)));
EXPECT_EQ(GetPageSubtitle(),
l10n_util::GetStringUTF16(IDS_MANAGEMENT_NOT_MANAGED_SUBTITLE));
EXPECT_FALSE(GetManaged());
}
TEST_F(ManagementUIHandlerTests,
ManagementContextualSourceUpdateManagedKnownDomain) {
const std::string domain = "gmail.com.manager.com.gmail.com";
PrepareProfileAndHandler(
/* profile_name= */ "managed@" + domain,
/* override_policy_connector_is_managed= */ true,
/* use_account_for_testing= */ true, /* use_device= */ false);
EXPECT_EQ(GetExtensionReportingTitle(),
l10n_util::GetStringFUTF16(IDS_MANAGEMENT_EXTENSIONS_INSTALLED_BY,
base::UTF8ToUTF16(domain)));
EXPECT_EQ(GetBrowserManagementNotice(),
l10n_util::GetStringFUTF16(
IDS_MANAGEMENT_BROWSER_NOTICE,
base::UTF8ToUTF16(chrome::kManagedUiLearnMoreUrl)));
EXPECT_EQ(GetPageSubtitle(),
l10n_util::GetStringFUTF16(IDS_MANAGEMENT_SUBTITLE_MANAGED_BY,
base::UTF8ToUTF16(domain)));
EXPECT_TRUE(GetManaged());
}
#endif // !defined(OS_CHROMEOS)
#if defined(OS_CHROMEOS)
TEST_F(ManagementUIHandlerTests,
ManagementContextualSourceUpdateManagedAccountKnownDomain) {
const std::string domain = "manager.com";
PrepareProfileAndHandler(
/* profile_name= */ "managed@" + domain,
/* override_policy_connector_is_managed= */ true,
/* use_account= */ true, /* use_device= */ false,
/* device_name= */ "");
const auto device_type = ui::GetChromeOSDeviceTypeResourceId();
EXPECT_EQ(GetExtensionReportingTitle(),
l10n_util::GetStringFUTF16(IDS_MANAGEMENT_EXTENSIONS_INSTALLED_BY,
base::UTF8ToUTF16(domain)));
EXPECT_EQ(GetPageSubtitle(),
l10n_util::GetStringFUTF16(IDS_MANAGEMENT_SUBTITLE_MANAGED_BY,
l10n_util::GetStringUTF16(device_type),
base::UTF8ToUTF16(domain)));
EXPECT_EQ(GetManagementOverview(),
l10n_util::GetStringFUTF16(IDS_MANAGEMENT_ACCOUNT_MANAGED_BY,
base::UTF8ToUTF16(domain)));
EXPECT_TRUE(GetManaged());
}
TEST_F(ManagementUIHandlerTests,
ManagementContextualSourceUpdateManagedAccountUnknownDomain) {
PrepareProfileAndHandler(
/* profile_name= */ "",
/* override_policy_connector_is_managed= */ false,
/* use_account= */ true, /* use_device= */ false,
/* device_name= */ "");
const auto device_type = ui::GetChromeOSDeviceTypeResourceId();
EXPECT_EQ(GetExtensionReportingTitle(),
l10n_util::GetStringUTF16(IDS_MANAGEMENT_EXTENSIONS_INSTALLED));
EXPECT_EQ(GetPageSubtitle(),
l10n_util::GetStringFUTF16(IDS_MANAGEMENT_SUBTITLE_MANAGED,
l10n_util::GetStringUTF16(device_type)));
EXPECT_EQ(GetManagementOverview(), base::string16());
EXPECT_TRUE(GetManaged());
}
TEST_F(ManagementUIHandlerTests,
ManagementContextualSourceUpdateManagedDevice) {
PrepareProfileAndHandler(
/* profile_name= */ "managed@manager.com",
/* override_policy_connector_is_managed= */ false,
/* use_account= */ false, /* use_device= */ true);
const auto device_type = ui::GetChromeOSDeviceTypeResourceId();
EXPECT_EQ(GetPageSubtitle(),
l10n_util::GetStringFUTF16(IDS_MANAGEMENT_SUBTITLE_MANAGED_BY,
l10n_util::GetStringUTF16(device_type),
device_domain()));
EXPECT_EQ(GetExtensionReportingTitle(),
l10n_util::GetStringFUTF16(IDS_MANAGEMENT_EXTENSIONS_INSTALLED_BY,
device_domain()));
EXPECT_EQ(GetManagementOverview(), base::string16());
EXPECT_TRUE(GetManaged());
}
TEST_F(ManagementUIHandlerTests,
ManagementContextualSourceUpdateManagedDeviceAndAccount) {
PrepareProfileAndHandler(
/* profile_name= */ "managed@devicedomain.com",
/* override_policy_connector_is_managed= */ false,
/* use_account= */ true, /* use_device= */ true);
const auto device_type = ui::GetChromeOSDeviceTypeResourceId();
EXPECT_EQ(GetPageSubtitle(),
l10n_util::GetStringFUTF16(IDS_MANAGEMENT_SUBTITLE_MANAGED_BY,
l10n_util::GetStringUTF16(device_type),
device_domain()));
EXPECT_EQ(GetExtensionReportingTitle(),
l10n_util::GetStringFUTF16(IDS_MANAGEMENT_EXTENSIONS_INSTALLED_BY,
device_domain()));
EXPECT_EQ(GetManagementOverview(),
l10n_util::GetStringFUTF16(
IDS_MANAGEMENT_DEVICE_AND_ACCOUNT_MANAGED_BY, device_domain()));
EXPECT_TRUE(GetManaged());
}
TEST_F(ManagementUIHandlerTests,
ManagementContextualSourceUpdateManagedDeviceAndAccountMultipleDomains) {
const std::string domain = "manager.com";
PrepareProfileAndHandler(
/* profile_name= */ "managed@" + domain,
/* override_policy_connector_is_managed= */ true,
/* use_account= */ true, /* use_device= */ true);
const auto device_type = ui::GetChromeOSDeviceTypeResourceId();
EXPECT_EQ(GetPageSubtitle(),
l10n_util::GetStringFUTF16(IDS_MANAGEMENT_SUBTITLE_MANAGED_BY,
l10n_util::GetStringUTF16(device_type),
device_domain()));
EXPECT_EQ(GetExtensionReportingTitle(),
l10n_util::GetStringFUTF16(IDS_MANAGEMENT_EXTENSIONS_INSTALLED_BY,
device_domain()));
EXPECT_EQ(GetManagementOverview(),
l10n_util::GetStringFUTF16(
IDS_MANAGEMENT_DEVICE_MANAGED_BY_ACCOUNT_MANAGED_BY,
device_domain(), base::UTF8ToUTF16(domain)));
EXPECT_TRUE(GetManaged());
}
TEST_F(ManagementUIHandlerTests, ManagementContextualSourceUpdateUnmanaged) {
PrepareProfileAndHandler(
/* profile_name= */ "",
/* override_policy_connector_is_managed= */ false,
/* use_account= */ false, /* use_device= */ false,
/* device_domain= */ "");
const auto device_type = ui::GetChromeOSDeviceTypeResourceId();
EXPECT_EQ(GetPageSubtitle(),
l10n_util::GetStringFUTF16(IDS_MANAGEMENT_NOT_MANAGED_SUBTITLE,
l10n_util::GetStringUTF16(device_type)));
EXPECT_EQ(GetExtensionReportingTitle(),
l10n_util::GetStringUTF16(IDS_MANAGEMENT_EXTENSIONS_INSTALLED));
EXPECT_EQ(GetManagementOverview(),
l10n_util::GetStringUTF16(IDS_MANAGEMENT_DEVICE_NOT_MANAGED));
EXPECT_FALSE(GetManaged());
}
#endif
TEST_F(ManagementUIHandlerTests, ExtensionReportingInfoNoPolicySetNoMessage) {
handler_.EnableCloudReportingExtension(false);
auto reporting_info = handler_.GetExtensionReportingInfo();
EXPECT_EQ(reporting_info.GetList().size(), 0u);
}
TEST_F(ManagementUIHandlerTests,
ExtensionReportingInfoCloudExtensionAddsDefaultPolicies) {
handler_.EnableCloudReportingExtension(true);
const std::set<std::string> expected_messages = {
kManagementExtensionReportMachineName, kManagementExtensionReportUsername,
kManagementExtensionReportVersion,
kManagementExtensionReportExtensionsPlugin,
kManagementExtensionReportSafeBrowsingWarnings};
ExpectMessagesToBeEQ(handler_.GetExtensionReportingInfo().GetList(),
expected_messages);
}
TEST_F(ManagementUIHandlerTests, CloudReportingPolicy) {
handler_.EnableCloudReportingExtension(false);
policy::PolicyMap chrome_policies;
const policy::PolicyNamespace chrome_policies_namespace =
policy::PolicyNamespace(policy::POLICY_DOMAIN_CHROME, std::string());
EXPECT_CALL(policy_service_, GetPolicies(_))
.WillRepeatedly(ReturnRef(chrome_policies));
SetPolicyValue(policy::key::kCloudReportingEnabled, chrome_policies, true);
std::set<std::string> expected_messages = {
kManagementExtensionReportMachineName, kManagementExtensionReportUsername,
kManagementExtensionReportVersion,
kManagementExtensionReportExtensionsPlugin};
ExpectMessagesToBeEQ(handler_.GetExtensionReportingInfo().GetList(),
expected_messages);
}
TEST_F(ManagementUIHandlerTests, ExtensionReportingInfoPoliciesMerge) {
policy::PolicyMap on_prem_reporting_extension_beta_policies;
policy::PolicyMap on_prem_reporting_extension_stable_policies;
EnablePolicy(kPolicyKeyReportUserIdData,
on_prem_reporting_extension_beta_policies);
EnablePolicy(kManagementExtensionReportVersion,
on_prem_reporting_extension_beta_policies);
EnablePolicy(kPolicyKeyReportUserIdData,
on_prem_reporting_extension_beta_policies);
EnablePolicy(kPolicyKeyReportPolicyData,
on_prem_reporting_extension_stable_policies);
EnablePolicy(kPolicyKeyReportMachineIdData,
on_prem_reporting_extension_stable_policies);
EnablePolicy(kPolicyKeyReportSafeBrowsingData,
on_prem_reporting_extension_stable_policies);
EnablePolicy(kPolicyKeyReportSystemTelemetryData,
on_prem_reporting_extension_stable_policies);
EnablePolicy(kPolicyKeyReportUserBrowsingData,
on_prem_reporting_extension_stable_policies);
const policy::PolicyNamespace
on_prem_reporting_extension_stable_policy_namespace =
policy::PolicyNamespace(policy::POLICY_DOMAIN_EXTENSIONS,
kOnPremReportingExtensionStableId);
const policy::PolicyNamespace
on_prem_reporting_extension_beta_policy_namespace =
policy::PolicyNamespace(policy::POLICY_DOMAIN_EXTENSIONS,
kOnPremReportingExtensionBetaId);
EXPECT_CALL(policy_service_,
GetPolicies(on_prem_reporting_extension_stable_policy_namespace))
.WillOnce(ReturnRef(on_prem_reporting_extension_stable_policies));
EXPECT_CALL(policy_service_,
GetPolicies(on_prem_reporting_extension_beta_policy_namespace))
.WillOnce(ReturnRef(on_prem_reporting_extension_beta_policies));
policy::PolicyMap empty_policy_map;
EXPECT_CALL(policy_service_,
GetPolicies(policy::PolicyNamespace(policy::POLICY_DOMAIN_CHROME,
std::string())))
.WillOnce(ReturnRef(empty_policy_map));
handler_.EnableCloudReportingExtension(true);
std::set<std::string> expected_messages = {
kManagementExtensionReportMachineNameAddress,
kManagementExtensionReportUsername,
kManagementExtensionReportVersion,
kManagementExtensionReportExtensionsPlugin,
kManagementExtensionReportSafeBrowsingWarnings,
kManagementExtensionReportUserBrowsingData,
kManagementExtensionReportPerfCrash};
ExpectMessagesToBeEQ(handler_.GetExtensionReportingInfo().GetList(),
expected_messages);
}
TEST_F(ManagementUIHandlerTests, ThreatReportingInfo) {
policy::PolicyMap chrome_policies;
const policy::PolicyNamespace chrome_policies_namespace =
policy::PolicyNamespace(policy::POLICY_DOMAIN_CHROME, std::string());
TestingProfile::Builder builder_no_domain;
auto profile_no_domain = builder_no_domain.Build();
TestingProfile::Builder builder_known_domain;
builder_known_domain.SetProfileName("managed@manager.com");
auto profile_known_domain = builder_known_domain.Build();
#if defined(OS_CHROMEOS)
handler_.SetDeviceDomain("");
#endif // !defined(OS_CHROMEOS)
EXPECT_CALL(policy_service_, GetPolicies(chrome_policies_namespace))
.WillRepeatedly(ReturnRef(chrome_policies));
base::DictionaryValue* threat_protection_info = nullptr;
// When no policies are set, nothing to report.
auto info = handler_.GetThreatProtectionInfo(profile_no_domain.get());
info.GetAsDictionary(&threat_protection_info);
EXPECT_TRUE(threat_protection_info->FindListKey("info")->GetList().empty());
EXPECT_EQ(
l10n_util::GetStringUTF16(IDS_MANAGEMENT_THREAT_PROTECTION_DESCRIPTION),
base::UTF8ToUTF16(*threat_protection_info->FindStringKey("description")));
// When policies are set to uninteresting values, nothing to report.
SetPolicyValue(policy::key::kCheckContentCompliance, chrome_policies, 0);
SetPolicyValue(policy::key::kSendFilesForMalwareCheck, chrome_policies, 0);
SetPolicyValue(policy::key::kUnsafeEventsReportingEnabled, chrome_policies,
false);
info = handler_.GetThreatProtectionInfo(profile_known_domain.get());
info.GetAsDictionary(&threat_protection_info);
EXPECT_TRUE(threat_protection_info->FindListKey("info")->GetList().empty());
EXPECT_EQ(
l10n_util::GetStringUTF16(IDS_MANAGEMENT_THREAT_PROTECTION_DESCRIPTION),
base::UTF8ToUTF16(*threat_protection_info->FindStringKey("description")));
// When policies are set to values that enable the feature, report it.
SetPolicyValue(policy::key::kCheckContentCompliance, chrome_policies, 1);
SetPolicyValue(policy::key::kSendFilesForMalwareCheck, chrome_policies, 2);
SetPolicyValue(policy::key::kUnsafeEventsReportingEnabled, chrome_policies,
true);
info = handler_.GetThreatProtectionInfo(profile_no_domain.get());
info.GetAsDictionary(&threat_protection_info);
EXPECT_EQ(3u, threat_protection_info->FindListKey("info")->GetList().size());
EXPECT_EQ(
l10n_util::GetStringUTF16(IDS_MANAGEMENT_THREAT_PROTECTION_DESCRIPTION),
base::UTF8ToUTF16(*threat_protection_info->FindStringKey("description")));
base::Value expected_info(base::Value::Type::LIST);
{
base::Value value(base::Value::Type::DICTIONARY);
value.SetStringKey("title", kManagementDataLossPreventionName);
value.SetStringKey("permission", kManagementDataLossPreventionPermissions);
expected_info.Append(std::move(value));
}
{
base::Value value(base::Value::Type::DICTIONARY);
value.SetStringKey("title", kManagementMalwareScanningName);
value.SetStringKey("permission", kManagementMalwareScanningPermissions);
expected_info.Append(std::move(value));
}
{
base::Value value(base::Value::Type::DICTIONARY);
value.SetStringKey("title", kManagementEnterpriseReportingName);
value.SetStringKey("permission", kManagementEnterpriseReportingPermissions);
expected_info.Append(std::move(value));
}
EXPECT_EQ(expected_info, *threat_protection_info->FindListKey("info"));
}
| 41.030159 | 80 | 0.718674 | sarang-apps |
c5d75f83f8654919a33244141985beffda4e6a19 | 2,835 | cpp | C++ | src/ui/3d/entities/HemiFunctionEntity.cpp | PearCoding/PearRay | 8654a7dcd55cc67859c7c057c7af64901bf97c35 | [
"MIT"
] | 19 | 2016-11-07T00:01:19.000Z | 2021-12-29T05:35:14.000Z | src/ui/3d/entities/HemiFunctionEntity.cpp | PearCoding/PearRay | 8654a7dcd55cc67859c7c057c7af64901bf97c35 | [
"MIT"
] | 33 | 2016-07-06T21:58:05.000Z | 2020-08-01T18:18:24.000Z | src/ui/3d/entities/HemiFunctionEntity.cpp | PearCoding/PearRay | 8654a7dcd55cc67859c7c057c7af64901bf97c35 | [
"MIT"
] | null | null | null | #include "3d/OpenGLHeaders.h"
#include "3d/shader/ColorShader.h"
#include "HemiFunctionEntity.h"
#include "math/Spherical.h"
#include <tbb/blocked_range.h>
#include <tbb/parallel_for.h>
namespace PR {
namespace UI {
HemiFunctionEntity::HemiFunctionEntity(const Function& function, int ntheta, int nphi)
: GraphicEntity()
, mFunction(function)
, mNTheta(ntheta)
, mNPhi(nphi)
{
setupBuffer();
setTwoSided(true);
setShader(std::make_shared<ColorShader>());
setDrawMode(GL_TRIANGLES);
}
HemiFunctionEntity::~HemiFunctionEntity()
{
}
template <typename T>
static inline T lerp(const T& a, const T& b, float t)
{
return a * (1 - t) + b * t;
}
// t in [0,1]
static inline Vector3f colormap(float t)
{
if (t > 0.5f)
return lerp(Vector3f(0, 1, 0), Vector3f(1, 0, 0), (t - 0.5f) * 2);
else
return lerp(Vector3f(0, 0, 1), Vector3f(0, 1, 0), t * 2);
}
void HemiFunctionEntity::setupBuffer()
{
//////////////// Vertices
std::vector<float> vertices;
vertices.resize((mNTheta + 1) * mNPhi * 3);
tbb::parallel_for(
tbb::blocked_range<int>(0, mNTheta + 1),
[&](const tbb::blocked_range<int>& r) {
const int sy = r.begin();
const int ey = r.end();
for (int j = sy; j < ey; ++j) {
for (int i = 0; i < mNPhi; ++i) {
float theta = 0.5f * PR_PI * j / (float)mNTheta;
float phi = 2 * PR_PI * (i / (float)mNPhi);
const Vector3f D = Spherical::cartesian(theta, phi);
float val = mFunction(theta, phi);
if (!std::isfinite(val))
val = 0;
int ind = j * mNPhi + i;
vertices[ind * 3 + 0] = val * D(0);
vertices[ind * 3 + 1] = val * D(1);
vertices[ind * 3 + 2] = val * D(2);
}
}
});
//////////////// Color
std::vector<float> colors;
const auto appendC = [&](const Vector3f& p0) {
colors.push_back(p0[0]);
colors.push_back(p0[1]);
colors.push_back(p0[2]);
};
colors.reserve(vertices.size());
for (int j = 0; j <= mNTheta; ++j) {
for (int i = 0; i < mNPhi; ++i) {
int ind = j * mNPhi + i;
Vector3f v = Vector3f(vertices[ind * 3], vertices[ind * 3 + 1], vertices[ind * 3 + 2]);
float val = v.norm();
if (val <= 1)
val *= 0.5f;
else
val = val * 0.5f + 0.5f;
appendC(colormap(val));
}
}
///////////////////// Indices
std::vector<uint32> indices;
for (int j = 0; j < mNTheta; ++j) {
for (int i = 0; i < mNPhi; ++i) {
uint32 row1 = j * mNPhi;
uint32 row2 = (j + 1) * mNPhi;
uint32 ni = (i + 1) % mNPhi;
// Triangle 1
indices.push_back(row1 + i);
indices.push_back(row1 + ni);
indices.push_back(row2 + ni);
// Triangle 2
indices.push_back(row1 + i);
indices.push_back(row2 + ni);
indices.push_back(row2 + i);
}
}
//////////////////// Commit
setVertices(vertices);
setColors(colors);
setIndices(indices);
requestRebuild();
}
} // namespace UI
} // namespace PR | 22.5 | 90 | 0.586596 | PearCoding |
c5d89e7e6033d1ed5f43d64760d76a23841efbdd | 6,160 | cc | C++ | dlb_pmd/test/TestSadm.cc | DolbyLaboratories/pmd_tool | 4c6d27df5f531d488a627f96f489cf213cbf121a | [
"BSD-3-Clause"
] | 11 | 2020-04-05T19:58:40.000Z | 2022-02-04T19:18:12.000Z | dlb_pmd/test/TestSadm.cc | DolbyLaboratories/pmd_tool | 4c6d27df5f531d488a627f96f489cf213cbf121a | [
"BSD-3-Clause"
] | 1 | 2020-02-25T22:08:30.000Z | 2020-02-25T22:08:30.000Z | dlb_pmd/test/TestSadm.cc | DolbyLaboratories/pmd_tool | 4c6d27df5f531d488a627f96f489cf213cbf121a | [
"BSD-3-Clause"
] | null | null | null | /************************************************************************
* dlb_pmd
* Copyright (c) 2021, Dolby Laboratories Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
**********************************************************************/
/**
* @file TestSadm.cc
* @brief encapsulate serial ADM XML read/write testing
*/
extern "C"
{
#include "dlb_pmd_sadm_string.h"
#include "src/modules/sadm/pmd_sadm_limits.h"
}
#include "TestSadm.hh"
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
namespace
{
static const int MAX_SADM_SIZE = 100 * 1024 * 1024;
/* minimize the number of error files written; we don't want to risk flooding
* the disk when there are many failures */
static const unsigned int MAX_FILES_WRITTEN = 16;
static unsigned int files_written = 0;
}
void TestSadm::run(TestModel& m1, const char *testname, int param, bool match)
{
const char *errmsg = NULL;
TestModel m2;
TestModel m3;
TestSadm sadm(m1);
if (sadm.write(m1))
{
errmsg = "could not write SADM";
}
else if (sadm.read(m2))
{
errmsg = sadm.error_message_;
}
else if ((dlb_pmd_success)match == dlb_pmd_equal(m1, m2, 0, 0))
{
errmsg = match
? "Model mismatch after SADM write and read"
: "Models shouldn't match after SADM write and read, but do";
}
else if (sadm.write(m2))
{
errmsg = "could not write SADM 2";
}
else if (sadm.read(m3))
{
errmsg = sadm.error_message_;
}
else if ((dlb_pmd_success)match == dlb_pmd_equal(m1, m3, 0, 0))
{
errmsg = match
? "Model mismatch after SADM2 write and read"
: "Models shouldn't match after SADM2 write and read, but do";
}
if (errmsg)
{
std::string error = errmsg;
if (files_written < MAX_FILES_WRITTEN)
{
char outfile[128];
snprintf(outfile, sizeof(outfile), "test_%s_%d_sadm.xml", testname, param);
sadm.dump(outfile);
error += ": ";
error += outfile;
++files_written;
}
throw TestModel::failure(error);
}
}
TestSadm::TestSadm(TestModel& m)
: sadm_(0)
, smem_(0)
, bmem_(0)
, size_(0)
, error_line_(0)
{
dlb_pmd_model_constraints limits;
dlb_sadm_counts sc;
size_t sz;
dlb_pmd_get_constraints(m, &limits);
compute_sadm_limits(&limits, &sc);
sz = dlb_sadm_query_memory(&sc);
size_= MAX_SADM_SIZE;
bmem_ = new uint8_t[size_];
smem_ = new uint8_t[sz];
if (dlb_sadm_init(&sc, smem_, &sadm_))
{
std::string error = "could not init sADM model";
throw TestModel::failure(error);
}
}
TestSadm::~TestSadm()
{
dlb_sadm_finish(sadm_);
sadm_ = 0;
delete[] bmem_;
delete[] smem_;
}
int TestSadm::get_write_buf_(char *pos, char **buf, size_t *capacity)
{
if (!buf)
{
/* writer is closing, so determine actual size used */
size_ = pos - (char*)bmem_;
}
else if (!pos)
{
*buf = (char*)bmem_;
*capacity = size_;
return 1;
}
return 0;
}
void TestSadm::error_callback_(const char *msg)
{
snprintf(error_message_, sizeof(error_message_),
"Could not read SADM: %s at line %u", msg, error_line_);
}
dlb_pmd_success TestSadm::write(TestModel& m)
{
dlb_pmd_model_constraints limits;
dlb_pmd_sadm_writer *w;
uint8_t *mem;
size_t wsz;
dlb_pmd_get_constraints(m, &limits);
wsz = dlb_pmd_sadm_writer_query_mem(&limits);
mem = new uint8_t[wsz];
size_ = MAX_SADM_SIZE;
dlb_pmd_success res
= dlb_pmd_sadm_writer_init(&w, &limits, mem)
|| dlb_pmd_sadm_string_write(w, m, (char*)bmem_, &size_);
dlb_pmd_sadm_writer_finish(w);
delete[] mem;
return res;
}
dlb_pmd_success TestSadm::read(TestModel& m)
{
dlb_pmd_model_constraints limits;
dlb_pmd_sadm_reader *r;
dlb_pmd_success res;
uint8_t *mem;
size_t rsz;
dlb_pmd_get_constraints(m, &limits);
rsz = dlb_pmd_sadm_reader_query_mem(&limits);
mem = new uint8_t[rsz];
res = dlb_pmd_sadm_reader_init(&r, &limits, mem)
|| dlb_pmd_sadm_string_read(r, "TestSadm", (char*)bmem_, size_, m, error_callback, this, &error_line_)
;
dlb_pmd_sadm_reader_finish(r);
delete[] mem;
return res;
}
void TestSadm::dump(const char *filename)
{
FILE *f = fopen(filename, "wb");
if (NULL != f)
{
fwrite(bmem_, 1, size_, f);
fclose(f);
}
}
| 26.899563 | 110 | 0.626786 | DolbyLaboratories |
c5daa273dd4ab20759832968146f7077fee9c58b | 439 | cc | C++ | MWP2_1E.cc | hkktr/POLSKI-SPOJ | 59f7e0be99fca6532681c2ca01c8a7d97c6b5eed | [
"Unlicense"
] | 1 | 2021-02-01T11:21:56.000Z | 2021-02-01T11:21:56.000Z | MWP2_1E.cc | hkktr/POLSKI-SPOJ | 59f7e0be99fca6532681c2ca01c8a7d97c6b5eed | [
"Unlicense"
] | null | null | null | MWP2_1E.cc | hkktr/POLSKI-SPOJ | 59f7e0be99fca6532681c2ca01c8a7d97c6b5eed | [
"Unlicense"
] | 1 | 2022-01-28T15:25:45.000Z | 2022-01-28T15:25:45.000Z | // C++14 (gcc 8.3)
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
int main() {
std::ios_base::sync_with_stdio(false);
std::cin.tie(nullptr);
std::vector<std::string> words;
std::string word;
while (std::cin >> word) {
words.push_back(word);
}
std::sort(words.begin(), words.end());
for (auto it{words.begin()}; it != words.end(); ++it) {
std::cout << *it << "\n";
}
return 0;
} | 19.086957 | 57 | 0.594533 | hkktr |
c5db24648dcb994cc0671d991851bedc79c33fac | 232 | hpp | C++ | src/actor/ActorId.hpp | patrikpihlstrom/nn-c- | 8b5df5f2c62a3dbefc9ded4908daffdf989c771b | [
"MIT"
] | null | null | null | src/actor/ActorId.hpp | patrikpihlstrom/nn-c- | 8b5df5f2c62a3dbefc9ded4908daffdf989c771b | [
"MIT"
] | null | null | null | src/actor/ActorId.hpp | patrikpihlstrom/nn-c- | 8b5df5f2c62a3dbefc9ded4908daffdf989c771b | [
"MIT"
] | null | null | null | #pragma once
#include <cstdint>
struct ActorId
{
uint64_t id;
bool operator== (const ActorId& compare) const
{
return id == compare.id;
}
bool operator< (const ActorId& compare) const
{
return id < compare.id;
}
};
| 11.047619 | 47 | 0.659483 | patrikpihlstrom |
c5dba36aad008efc0858fcd21d747c9d17b5b30e | 4,458 | hpp | C++ | src/klass/layer.hpp | burncode/py-skp | 2e022fc7ef54bc77454bd368f3b512ad3cb5b0f2 | [
"MIT"
] | 1 | 2021-02-28T16:33:38.000Z | 2021-02-28T16:33:38.000Z | src/klass/layer.hpp | burncode/py-skp | 2e022fc7ef54bc77454bd368f3b512ad3cb5b0f2 | [
"MIT"
] | null | null | null | src/klass/layer.hpp | burncode/py-skp | 2e022fc7ef54bc77454bd368f3b512ad3cb5b0f2 | [
"MIT"
] | null | null | null | #ifndef SKP_LAYER_HPP
#define SKP_LAYER_HPP
#include "common.hpp"
#include <SketchUpAPI/model/layer.h>
#include "entity.hpp"
typedef struct {
SkpEntity skp_entilty;
SULayerRef _su_layer;
} SkpLayer;
static void SkpLayer_dealloc(SkpLayer* self) {
Py_TYPE(self)->tp_free((PyObject*)self);
}
static SUEntityRef SkpLayer__get_su_entity(void *self) {
SkpEntity *ent_self = (SkpEntity*)self;
if (!SUIsValid(ent_self->_su_entity)) {
ent_self->_su_entity = SULayerToEntity(((SkpLayer*)self)->_su_layer);
}
return ent_self->_su_entity;
}
static PyObject * SkpLayer_new(PyTypeObject *type, PyObject *args, PyObject *kwds) {
PyObject *py_obj = (PyObject*)SkpEntityType.tp_new(type, args, kwds);
SkpLayer *self = (SkpLayer*)py_obj;
if (self != NULL) {
((SkpEntity*)self)->get_su_entity = &SkpLayer__get_su_entity;
self->_su_layer = SU_INVALID;
}
return py_obj;
}
static int SkpLayer_init(SkpLayer *self, PyObject *args, PyObject *kwds) {
return 0;
}
static PyMemberDef SkpLayer_members[] = {
{NULL} /* Sentinel */
};
static PyObject* SkpLayer_getname(SkpLayer *self, void *closure) {
SKP_GET_STRING_BODY(SULayerGetName, _su_layer, "cannot get name")
}
static int SkpLayer_setname(SkpLayer *self, PyObject *value, void *closure) {
//TODO: Cannot overwrite Layer0
SKP_SET_STRING_BODY(SULayerSetName, _su_layer, "cannot set name")
}
static PyGetSetDef SkpLayer_getseters[] = {
{ "name", (getter)SkpLayer_getname, (setter)SkpLayer_setname,
"name", NULL},
{NULL} /* Sentinel */
};
static PyMethodDef SkpLayer_methods[] = {
{NULL} /* Sentinel */
};
static PyTypeObject SkpLayerType = {
PyVarObject_HEAD_INIT(NULL, 0)
"skp.Layer", /* tp_name */
sizeof(SkpLayer), /* tp_basicsize */
0, /* tp_itemsize */
(destructor)SkpLayer_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
"SketchUp Layer", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
SkpLayer_methods, /* tp_methods */
SkpLayer_members, /* tp_members */
SkpLayer_getseters, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)SkpLayer_init, /* tp_init */
0, /* tp_alloc */
SkpLayer_new, /* tp_new */
};
#endif
| 40.162162 | 84 | 0.401301 | burncode |
c5e35d17fb6c91295662f366518c972975b69bed | 2,389 | cpp | C++ | google/gcj/2019/1b/a.cpp | yu3mars/proconVSCodeGcc | fcf36165bb14fb6f555664355e05dd08d12e426b | [
"MIT"
] | null | null | null | google/gcj/2019/1b/a.cpp | yu3mars/proconVSCodeGcc | fcf36165bb14fb6f555664355e05dd08d12e426b | [
"MIT"
] | null | null | null | google/gcj/2019/1b/a.cpp | yu3mars/proconVSCodeGcc | fcf36165bb14fb6f555664355e05dd08d12e426b | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using pii = pair<int, int>;
#define REP(i, n) for (int i = 0, i##_len = (n); i < i##_len; ++i)
#define all(x) (x).begin(), (x).end()
#define m0(x) memset(x, 0, sizeof(x))
int dx4[4] = {1, 0, -1, 0}, dy4[4] = {0, 1, 0, -1};
class GoogleCodeJam
{
public:
string case_prefix;
void exec()
{
int p,q;
cin>>p>>q;
vector<int> x(p),y(p);
vector<char> c(p);
vector<int> lsN(q+1),lsS(q+1),lsE(q+1),lsW(q+1);
for(int i = 0; i < p; i++)
{
cin>>x[i]>>y[i]>>c[i];
if(c[i]=='N')
{
lsN[y[i]+1]++;
}
else if(c[i]=='S')
{
lsS[y[i]-1]++;
}
else if(c[i]=='E')
{
lsE[x[i]+1]++;
}
else if(c[i]=='W')
{
lsW[x[i]-1]++;
}
}
for(int i = 0; i < q; i++)
{
lsN[i+1]+=lsN[i];
lsE[i+1]+=lsE[i];
}
for(int i = q - 1; i >= 0; i--)
{
lsS[i]+=lsS[i+1];
lsW[i]+=lsW[i+1];
}
int ansx=0, ansy=0;
for(int i = 0; i <= q; i++)
{
if(lsN[i]+lsS[i]>lsN[ansy]+lsS[ansy])
{
ansy=i;
}
if(lsE[i]+lsW[i]>lsE[ansx]+lsW[ansx])
{
ansx=i;
}
}
/*
cout<< "lsN";
for(int i = 0; i <= q; i++)
{
cout<<" "<<lsN[i];
}
cout<<endl;
cout<< "lsS";
for(int i = 0; i <= q; i++)
{
cout<<" "<<lsS[i];
}
cout<<endl;
cout<< "lsE";
for(int i = 0; i <= q; i++)
{
cout<<" "<<lsE[i];
}
cout<<endl;
cout<< "lsW";
for(int i = 0; i <= q; i++)
{
cout<<" "<<lsW[i];
}
cout<<endl;
*/
cout<<ansx<<" "<<ansy<<endl;
}
GoogleCodeJam()
{
int T;
std::cin >> T;
for (int i = 1; i <= T; i++)
{
case_prefix = "Case #" + std::to_string(i) + ": ";
cout << case_prefix;
exec();
}
}
};
int main()
{
GoogleCodeJam();
return 0;
} | 20.594828 | 66 | 0.321892 | yu3mars |
c5e3b634fe1e1449283eaaf536e62babbcf04933 | 3,184 | cc | C++ | lib/io/disk_manager.cc | DibiBase/dibibase | 46020a1052f16d8225a06a5a5b5dd43dd62e5c26 | [
"Apache-2.0"
] | 1 | 2021-12-14T12:22:32.000Z | 2021-12-14T12:22:32.000Z | lib/io/disk_manager.cc | DibiBase/dibibase | 46020a1052f16d8225a06a5a5b5dd43dd62e5c26 | [
"Apache-2.0"
] | 5 | 2021-11-16T15:21:11.000Z | 2022-03-30T13:01:44.000Z | lib/io/disk_manager.cc | DibiBase/dibibase | 46020a1052f16d8225a06a5a5b5dd43dd62e5c26 | [
"Apache-2.0"
] | null | null | null | #include "io/disk_manager.hh"
#include <cerrno>
#include <fcntl.h>
#include <memory>
#include <string>
#include <unistd.h>
#include "catalog/record.hh"
#include "catalog/schema.hh"
#include "db/index_page.hh"
#include "mem/summary.hh"
#include "util/buffer.hh"
#include "util/logger.hh"
using namespace dibibase;
std::unique_ptr<mem::Summary>
io::DiskManager::load_summary(std::string &database_path,
std::string &table_name, size_t sstable_id) {
int fd = open((database_path + "/" + table_name + "/summary_" +
std::to_string(sstable_id) + ".db")
.c_str(),
O_RDONLY);
std::unique_ptr<unsigned char[]> buf =
std::unique_ptr<unsigned char[]>(new unsigned char[4096]);
int rc = read(fd, buf.get(), 4096);
if (rc < 0)
util::Logger::make().err("Error reading Summary file: %d", errno);
else if (rc != 4096)
util::Logger::make().err("Malformed Summary file: File length isn't 4096");
util::Buffer *summary_buffer = new util::MemoryBuffer(std::move(buf), 4096);
auto summary = mem::Summary::from(summary_buffer);
delete summary_buffer;
return summary;
}
std::unique_ptr<db::IndexPage>
io::DiskManager::load_index_page(std::string &database_path,
std::string &table_name, size_t sstable_id,
uint8_t page_num) {
int fd = open((database_path + "/" + table_name + "/index_" +
std::to_string(sstable_id) + ".db")
.c_str(),
O_RDONLY);
lseek(fd, page_num * 4096, SEEK_SET);
std::unique_ptr<unsigned char[]> buf =
std::unique_ptr<unsigned char[]>(new unsigned char[4096]);
int rc = read(fd, buf.get(), 4096);
if (rc < 0)
util::Logger::make().err("Error reading Index file: %d", errno);
else if (rc != 4096)
util::Logger::make().err(
"Malformed Index file: File length isn't a mulitple of 4096");
util::Buffer *index_buffer = new util::MemoryBuffer(std::move(buf), 4096);
auto index_page = db::IndexPage::from(index_buffer);
delete index_buffer;
return index_page;
}
catalog::Record io::DiskManager::get_record_from_data(
std::string &database_path, std::string &table_name, size_t sstable_id,
catalog::Schema &schema, off_t offset) {
int fd = open((database_path + "/" + table_name + "/data_" +
std::to_string(sstable_id) + ".db")
.c_str(),
O_RDONLY);
lseek(fd, offset, SEEK_SET);
std::unique_ptr<unsigned char[]> buf =
std::unique_ptr<unsigned char[]>(new unsigned char[schema.record_size()]);
int rc = read(fd, buf.get(), schema.record_size());
if (rc < 0)
util::Logger::make().err("Error reading Data file: %d", errno);
else if (rc != static_cast<int>(schema.record_size()))
util::Logger::make().err("Malformed Data file: File is truncated");
util::Buffer *record_buffer =
new util::MemoryBuffer(std::move(buf), schema.record_size());
auto read_record = catalog::Record::from(record_buffer, schema);
auto record = catalog::Record(read_record->values());
delete record_buffer;
return record;
}
| 31.524752 | 80 | 0.629083 | DibiBase |
c5e4b411660dcf15e43f5cf4e4e2ee1251f141d1 | 1,262 | hpp | C++ | api.hpp | CESNET/TorquePlanSched | 1db26ccb25822132af61a6edd722a67ac21754a7 | [
"MIT"
] | null | null | null | api.hpp | CESNET/TorquePlanSched | 1db26ccb25822132af61a6edd722a67ac21754a7 | [
"MIT"
] | null | null | null | api.hpp | CESNET/TorquePlanSched | 1db26ccb25822132af61a6edd722a67ac21754a7 | [
"MIT"
] | null | null | null | #ifndef API_HPP_
#define API_HPP_
/* api.h modified for usage in C++ code */
extern "C" {
#include "pbs_cache_api.h"
}
inline char *xpbs_cache_get_local(const char *hostname, const char *name)
{ return pbs_cache_get_local(const_cast<char*>(hostname), const_cast<char*>(name)); }
inline int xcache_hash_fill_local(const char *metric, void *hash)
{ return cache_hash_fill_local(const_cast<char*>(metric), hash); }
inline int xcache_hash_fill_remote(char *fqdn, const char *metric, void *hash) {
FILE *stream = cache_connect_net(fqdn, PBS_CACHE_PORT);
int res = cache_hash_fill(stream, (char*)metric, hash);
cache_close(stream);
return res;
}
inline char *xcache_hash_find(void *hash,const char *key)
{ return cache_hash_find(hash,const_cast<char*>(key)); }
inline int xcache_store_local(const char *hostname, const char *name, const char *value)
{ return cache_store_local(const_cast<char*>(hostname), const_cast<char*>(name), const_cast<char*>(value)); }
inline int xcache_store_remote(char *fqdn, const char *hostname, const char *name, const char *value) {
FILE *stream = cache_connect_net(fqdn, PBS_CACHE_PORT);
int res = cache_store(stream, (char*)hostname,(char*)name, (char*)value);
cache_close(stream);
return res;
}
#endif /* API_HPP_ */
| 34.108108 | 109 | 0.748811 | CESNET |
c5e58142ee2b983da881c2859c0fd5449fda7f9b | 1,516 | cpp | C++ | a4atlas/src/grl.cpp | a4/a4 | e1de89260cb3894908f1d01dfacea125abc79da9 | [
"BSL-1.0"
] | 4 | 2015-04-07T20:25:16.000Z | 2019-04-27T15:04:02.000Z | a4atlas/src/grl.cpp | a4/a4 | e1de89260cb3894908f1d01dfacea125abc79da9 | [
"BSL-1.0"
] | null | null | null | a4atlas/src/grl.cpp | a4/a4 | e1de89260cb3894908f1d01dfacea125abc79da9 | [
"BSL-1.0"
] | 1 | 2021-06-02T17:22:35.000Z | 2021-06-02T17:22:35.000Z | #include <iostream>
#include <fstream>
#include <stdexcept>
#include <a4/grl.h>
#include <a4/types.h>
using namespace std;
namespace a4{ namespace atlas{
FileGRL::FileGRL(const string& fn) {
ifstream in(fn.c_str(), ios::in);
if (!in) {
TERMINATE("Can not open '", fn, "'!");
}
uint32_t run, start, end;
while(in >> run >> start >> end) {
_data[run].insert(LBRange(end, start));
}
if (in.bad()) {
TERMINATE("Reading from '", fn, "' failed! Is it really in (run, lb) format?");
}
if (_data.size() == 0) {
TERMINATE("Cowardly refusing to use empty GRL from '", fn,
"'. Is it really in (run, lb) format?");
}
};
bool FileGRL::pass(const uint32_t& run, const uint32_t& lb) const {
// First, check if the run is actually in the GRL:
std::map<uint32_t, std::set<LBRange> >::const_iterator i_run = _data.find(run);
if (i_run == _data.end())
return false;
const std::set<LBRange>& ranges = i_run->second;
// Now, check if the lb is in one of the ranges
// first get the range where the "end lb" is at least as large as the current lb
set<LBRange>::const_iterator block = ranges.lower_bound(LBRange(lb, 0));
if (block == ranges.end())
return false; // the last end block happened before "lb"
// block.first is already larger/equal to lb, now check if block.second is smaller/equal:
if (block->second <= lb)
return true;
return false;
}
};}; // namespace atlas::a4;
| 30.938776 | 93 | 0.610158 | a4 |
c5e5d6998482ee9db4ff33ed16f7b4ba8e38dce2 | 999 | cpp | C++ | src/main/cpp/states/turret/HoldTurretPosition.cpp | Team302/2020InfiiniteRechargeImportedInto2021 | cfdbcc78e3a83e57cb8a0acc894609a94ab57193 | [
"BSD-3-Clause"
] | 5 | 2020-01-11T14:49:32.000Z | 2020-01-30T01:10:00.000Z | src/main/cpp/states/turret/HoldTurretPosition.cpp | Team302/2020InfiiniteRechargeImportedInto2021 | cfdbcc78e3a83e57cb8a0acc894609a94ab57193 | [
"BSD-3-Clause"
] | 117 | 2020-01-11T14:48:09.000Z | 2020-03-04T01:38:43.000Z | src/main/cpp/states/turret/HoldTurretPosition.cpp | Team302/2020InfiniteRecharge | c6355fdc7fcfd1f62b4f0ed5d077f026d3ace8f4 | [
"MIT"
] | null | null | null | /*----------------------------------------------------------------------------*/
/* Copyright (c) 2018 FIRST. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
#include "states/turret/HoldTurretPosition.h"
#include "subsys/MechanismFactory.h"
#include "subsys/IMechanism.h"
#include "subsys/Turret.h"
#include "controllers/ControlData.h"
#include "states/MechanismState.h"
#include "controllers/MechanismTargetData.h"
HoldTurretPosition::HoldTurretPosition(ControlData* controlData, double target, MechanismTargetData::SOLENOID solenoid) :
MechanismState(MechanismFactory::GetMechanismFactory()->GetIMechanism(MechanismTypes::TURRET),controlData, 0.0, solenoid)
{
}
| 49.95 | 125 | 0.580581 | Team302 |
c5e6003b9f5e7d70abdf6fe2e66e6568cfc80184 | 650 | cpp | C++ | Semester_2/Lab_14/main.cpp | DenCoder618/SUAI-Labs | 4785f5888257a7da79bc7ab681cde670ab3cf586 | [
"MIT"
] | 1 | 2021-09-20T23:58:34.000Z | 2021-09-20T23:58:34.000Z | Semester_2/Lab_14/main.cpp | DenCoder618/SUAI-Labs | 4785f5888257a7da79bc7ab681cde670ab3cf586 | [
"MIT"
] | 9 | 2021-09-22T22:47:47.000Z | 2021-10-23T00:34:36.000Z | Semester_2/Lab_14/main.cpp | DenCoder618/SUAI-Labs | 4785f5888257a7da79bc7ab681cde670ab3cf586 | [
"MIT"
] | null | null | null | // Программа должна хранить схему в виде заданной в задании
// структуры данных, где хранятся геометрические фигуры.
// Каждая фигура характеризуется уникальным идентификатором
// (int) id, координатами на экране (x, y), а также своими параметрами
// Программа должна уметь работать с фигурами, указанными в задании.
// Каждая фигуру должна уметь выводить на экран свои параметры
// в текстовом режиме с помощью метода print().
// Возможно, в будущем будут добавлены новые фигуры
// Класс FigureList должен быть основан на связном списке.
// Связаный список должен быть реализован с помощью двух классов
// Node (элемент списка) и List (сам список) | 50 | 70 | 0.783077 | DenCoder618 |
c5e717454e58e19ba151abb9eef773b7e7a5bef3 | 1,222 | cpp | C++ | src/DocumentManager.cpp | kungyao/Group5 | 6c0c8ebffe22882e02c2dd88c45e51124a6c3268 | [
"BSD-3-Clause"
] | null | null | null | src/DocumentManager.cpp | kungyao/Group5 | 6c0c8ebffe22882e02c2dd88c45e51124a6c3268 | [
"BSD-3-Clause"
] | 10 | 2021-04-20T09:08:48.000Z | 2021-06-12T10:28:33.000Z | src/DocumentManager.cpp | kungyao/Group5 | 6c0c8ebffe22882e02c2dd88c45e51124a6c3268 | [
"BSD-3-Clause"
] | 3 | 2021-04-13T14:35:57.000Z | 2021-04-20T05:22:41.000Z | // Copyright (c) 2021, Kung-Yao Hsieh, Shang-Chen LIN, Yi-Hang Xie. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "DocumentManager.h"
std::string Revision::toString()
{
std::string output_;
output_ += user_id;
output_ += ",";
output_ += std::to_string(start_position);
output_ += ",";
output_ += std::to_string(end_position);
output_ += ",";
output_ += is_insert == false ? "0" : "1";
output_ += ",";
output_ += insert_data;
output_ += ",";
output_ += std::to_string(delete_length);
output_ += ",";
return output_;
}
void DocumentManager::updateDocumentByID(const int id, Revision revision)
{
if (doc_map.find(id) != doc_map.end())
{
doc_map.find(id)->second.history.push_back(revision);
}
else
{
Document doc(id, std::vector<Revision>());
doc_map.insert(std::pair<int, Document>(id, doc));
}
}
std::vector<Revision> *DocumentManager::getHistoryFromDocument(const int id)
{
if (doc_map.find(id) != doc_map.end())
{
return &doc_map.find(id)->second.history;
}
else
{
return nullptr;
}
}
| 24.938776 | 88 | 0.613748 | kungyao |
c5e7778713b803c63fc46728bf635fff4d5826f4 | 10,667 | cpp | C++ | Test/test_buffer.cpp | Grandbrain/StdEx | e79c37ea77f67ae44e4cc4db4a9e90965c2fbf97 | [
"MIT"
] | null | null | null | Test/test_buffer.cpp | Grandbrain/StdEx | e79c37ea77f67ae44e4cc4db4a9e90965c2fbf97 | [
"MIT"
] | null | null | null | Test/test_buffer.cpp | Grandbrain/StdEx | e79c37ea77f67ae44e4cc4db4a9e90965c2fbf97 | [
"MIT"
] | null | null | null | #include <catch.hpp>
#include <buffer.hpp>
// Testing of buffer.
TEST_CASE("Testing of buffer") {
// Testing of buffer constructors.
SECTION("Constructors") {
SECTION("Constructor without parameters") {
stdex::buffer<int> a;
REQUIRE(a.data() == nullptr);
REQUIRE(a.empty());
REQUIRE(a.capacity() == 0);
}
SECTION("Constructor with initializer list") {
stdex::buffer<int> a { 1, 2, 3, 4, 5 };
REQUIRE(a.data() != nullptr);
REQUIRE(a.size() == 5);
REQUIRE(a.capacity() == 5);
REQUIRE(a.at(4) == 5);
}
SECTION("Constructor with capacity") {
stdex::buffer<int> a(10);
REQUIRE(a.data() != nullptr);
REQUIRE(a.empty());
REQUIRE(a.capacity() == 10);
}
SECTION("Constructor with data array") {
int array[] = { 1, 2, 3, 4, 5 };
stdex::buffer<int> a(array, sizeof(array) / sizeof(int));
REQUIRE(a.data() != nullptr);
REQUIRE(a.size() == 5);
REQUIRE(a.capacity() == 5);
REQUIRE(a.at(0) == 1);
}
SECTION("Constructor with data array and capacity") {
int array[] = { 1, 2, 3, 4, 5 };
stdex::buffer<int> a(array, sizeof(array) / sizeof(int), 10);
REQUIRE(a.data() != nullptr);
REQUIRE(a.size() == 5);
REQUIRE(a.capacity() == 10);
REQUIRE(a.at(0) == 1);
}
SECTION("Copy constructor") {
stdex::buffer<int> a { 1, 2, 3, 4, 5 };
stdex::buffer<int> b = a;
REQUIRE(b.data() != nullptr);
REQUIRE(b.size() == 5);
REQUIRE(b.capacity() == 5);
REQUIRE(b.at(1) == 2);
}
SECTION("Move constructor") {
stdex::buffer<int> a { 1, 2, 3, 4, 5 };
stdex::buffer<int> b = std::move(a);
REQUIRE(b.data() != nullptr);
REQUIRE(b.size() == 5);
REQUIRE(b.capacity() == 5);
REQUIRE(b.at(0) == 1);
REQUIRE(b.at(1) == 2);
REQUIRE(b.at(2) == 3);
REQUIRE(b.at(3) == 4);
REQUIRE(b.at(4) == 5);
}
}
// Testing of assignment operators.
SECTION("Assignment operators") {
SECTION("Copy assignment operator") {
stdex::buffer<int> a { 1, 2, 3, 4, 5 };
stdex::buffer<int> b { 6, 7, 8, 9, 10 };
b = a;
REQUIRE(b.size() == 5);
REQUIRE(b.capacity() == 5);
REQUIRE(b.at(0) == 1);
REQUIRE(b.at(4) == 5);
}
SECTION("Move assignment operator") {
stdex::buffer<int> a { 1, 2, 3, 4, 5 };
stdex::buffer<int> b { 6, 7, 8, 9, 10 };
b = std::move(a);
REQUIRE(b.size() == 5);
REQUIRE(b.capacity() == 5);
REQUIRE(b.at(0) == 1);
REQUIRE(b.at(1) == 2);
REQUIRE(b.at(2) == 3);
REQUIRE(b.at(3) == 4);
REQUIRE(b.at(4) == 5);
}
SECTION("Assignment operator with initializer list") {
stdex::buffer<int> a;
a = { 1, 2, 3, 4, 5 };
REQUIRE(a.size() == 5);
REQUIRE(a.capacity() == 5);
REQUIRE(a.at(0) == 1);
REQUIRE(a.at(4) == 5);
}
}
// Testing of equality operators.
SECTION("Equality checking") {
SECTION("Equality operator") {
stdex::buffer<int> a { 1, 2, 3, 4, 5 };
stdex::buffer<int> b { 1, 2, 3, 4, 5 };
REQUIRE(a == b);
}
SECTION("Inequality operator") {
stdex::buffer<int> a { 1, 2, 3, 4, 5 };
stdex::buffer<int> b { 6, 7, 8, 9, 10 };
REQUIRE(a != b);
}
}
// Testing of data assignment.
SECTION("Data assignment") {
SECTION("Assign an initializer list") {
stdex::buffer<int> a;
a.assign({ 1, 2, 3, 4, 5 });
REQUIRE(a.data() != nullptr);
REQUIRE(a.size() == 5);
REQUIRE(a.capacity() == 5);
REQUIRE(a.at(4) == 5);
}
SECTION("Assign a capacity") {
stdex::buffer<int> a;
a.assign(10);
REQUIRE(a.data() != nullptr);
REQUIRE(a.empty());
REQUIRE(a.capacity() == 10);
}
SECTION("Assign a data array") {
int array[] = { 1, 2, 3, 4, 5 };
stdex::buffer<int> a;
a.assign(array, sizeof(array) / sizeof(int));
REQUIRE(a.data() != nullptr);
REQUIRE(a.size() == 5);
REQUIRE(a.capacity() == 5);
REQUIRE(a.at(0) == 1);
}
SECTION("Assign a data array and capacity") {
int array[] = { 1, 2, 3, 4, 5 };
stdex::buffer<int> a;
a.assign(array, sizeof(array) / sizeof(int), 10);
REQUIRE(a.data() != nullptr);
REQUIRE(a.size() == 5);
REQUIRE(a.capacity() == 10);
REQUIRE(a.at(0) == 1);
}
SECTION("Assign an existing object") {
stdex::buffer<int> a { 1, 2, 3, 4, 5 };
stdex::buffer<int> b;
b.assign(a);
REQUIRE(b.data() != nullptr);
REQUIRE(b.size() == 5);
REQUIRE(b.capacity() == 5);
REQUIRE(b.at(1) == 2);
}
SECTION("Assign a temporary object") {
stdex::buffer<int> a { 1, 2, 3, 4, 5 };
stdex::buffer<int> b;
b.assign(std::move(a));
REQUIRE(b.data() != nullptr);
REQUIRE(b.size() == 5);
REQUIRE(b.capacity() == 5);
REQUIRE(b.at(0) == 1);
REQUIRE(b.at(1) == 2);
REQUIRE(b.at(2) == 3);
REQUIRE(b.at(3) == 4);
REQUIRE(b.at(4) == 5);
}
SECTION("Erase old data") {
stdex::buffer<int> a { 1, 2, 3, 4, 5 };
stdex::buffer<int> b { 6, 7, 8, 9, 10 };
b.assign(a);
REQUIRE(b.data() != nullptr);
REQUIRE(b.size() == 5);
REQUIRE(b.capacity() == 5);
REQUIRE(b.at(0) == 1);
REQUIRE(b[4] == 5);
}
}
// Testing of data appending.
SECTION("Data appending") {
SECTION("Append an existing object") {
stdex::buffer<int> a { 1, 2, 3, 4, 5 };
stdex::buffer<int> b { 6, 7, 8, 9, 10 };
a.append(b);
REQUIRE(a.data() != nullptr);
REQUIRE(a.size() == 10);
REQUIRE(a.capacity() == 10);
REQUIRE(a.at(0) == 1);
REQUIRE(a[9] == 10);
}
SECTION("Append an initializer list") {
stdex::buffer<int> a { 1, 2, 3, 4, 5 };
a.append({ 6, 7, 8, 9, 10 });
REQUIRE(a.data() != nullptr);
REQUIRE(a.size() == 10);
REQUIRE(a.capacity() == 10);
REQUIRE(a.at(9) == 10);
}
SECTION("Append a single value") {
stdex::buffer<int> a { 1, 2, 3, 4, 5 };
a.append(6);
REQUIRE(a.data() != nullptr);
REQUIRE(a.size() == 6);
REQUIRE(a.capacity() == 6);
REQUIRE(a.at(5) == 6);
}
SECTION("Append a data array") {
int array[] = { 6, 7, 8, 9, 10 };
stdex::buffer<int> a { 1, 2, 3, 4, 5 };
a.append(array, sizeof(array) / sizeof(int));
REQUIRE(a.data() != nullptr);
REQUIRE(a.size() == 10);
REQUIRE(a.capacity() == 10);
REQUIRE(a.at(9) == 10);
}
SECTION("Append a data with reserved capacity") {
stdex::buffer<int> a { 1, 2, 3, 4, 5 };
a.assign(10);
a.append({ 6, 7, 8 });
REQUIRE(a.data() != nullptr);
REQUIRE(a.size() == 8);
REQUIRE(a.capacity() == 10);
REQUIRE(a.at(7) == 8);
REQUIRE(a[9] == 0);
}
}
// Testing of data insertion.
SECTION("Data insertion") {
SECTION("Insert a data array") {
int array[] = { 6, 7, 8, 9, 10 };
stdex::buffer<int> a { 1, 2, 3, 4, 5 };
a.insert(array, sizeof(array) / sizeof(int), 2);
REQUIRE(a.data() != nullptr);
REQUIRE(a.size() == 10);
REQUIRE(a.capacity() == 10);
REQUIRE(a.at(0) == 1);
REQUIRE(a.at(2) == 6);
REQUIRE(a.at(4) == 8);
REQUIRE(a.at(6) == 10);
REQUIRE(a.at(9) == 5);
}
}
// Testing of range access.
SECTION("Range access") {
SECTION("Getting the first element") {
stdex::buffer<int> a { 1, 2, 3, 4, 5 };
REQUIRE(a.first() == 1);
REQUIRE((a.first() = 10) == 10);
}
SECTION("Getting the last element") {
stdex::buffer<int> a { 1, 2, 3, 4, 5 };
REQUIRE(a.last() == 5);
REQUIRE((a.last() = 10) == 10);
}
SECTION("Iterator loop") {
stdex::buffer<int> a { 1, 2, 3, 4, 5 };
stdex::buffer<int> b;
for (int element : a) b.append(element);
REQUIRE(a == b);
}
}
// Testing of data clearing.
SECTION("Data clearing") {
stdex::buffer<int> a { 1, 2, 3, 4, 5 };
a.clear();
REQUIRE(a.data() == nullptr);
REQUIRE(a.empty());
REQUIRE(a.capacity() == 0);
}
// Testing of object swapping.
SECTION("Object swapping") {
stdex::buffer<int> a { 1, 2, 3, 4, 5 };
stdex::buffer<int32_t> b { 6, 7, 8, 9, 10 };
stdex::swap(a, b);
REQUIRE(a.at(0) == 6);
REQUIRE(a.at(4) == 10);
REQUIRE(a.size() == 5);
REQUIRE(a.capacity() == 5);
REQUIRE(b.at(0) == 1);
REQUIRE(b.at(4) == 5);
REQUIRE(b.size() == 5);
REQUIRE(b.capacity() == 5);
}
// Testing of shrinking to fit.
SECTION("Shrinking to fit") {
stdex::buffer<int> a { 1, 2, 3, 4, 5 };
a.assign(10);
REQUIRE(a.data() != nullptr);
REQUIRE(a.size() == 5);
REQUIRE(a.capacity() == 10);
REQUIRE(a.at(4) == 5);
a.shrink_to_fit();
REQUIRE(a.capacity() == 5);
}
// Testing of data releasing.
SECTION("Data releasing") {
stdex::buffer<int> a { 1, 2, 3, 4, 5 };
int* data = a.release();
delete[] data;
REQUIRE(a.data() == nullptr);
REQUIRE(a.empty());
REQUIRE(a.capacity() == 0);
}
}
| 31.190058 | 73 | 0.431612 | Grandbrain |
c5ec745eb47bce7dd5d8dec897432173e866d91b | 30 | cc | C++ | deps/gettext/gettext-tools/woe32dll/c++msgfilter.cc | kimpel70/poedit | 9114258b6421c530f6516258635e730d8d3f6b26 | [
"MIT"
] | 3 | 2021-05-04T17:09:06.000Z | 2021-10-04T07:19:26.000Z | deps/gettext/gettext-tools/woe32dll/c++msgfilter.cc | kimpel70/poedit | 9114258b6421c530f6516258635e730d8d3f6b26 | [
"MIT"
] | null | null | null | deps/gettext/gettext-tools/woe32dll/c++msgfilter.cc | kimpel70/poedit | 9114258b6421c530f6516258635e730d8d3f6b26 | [
"MIT"
] | null | null | null | #include "../src/msgfilter.c"
| 15 | 29 | 0.666667 | kimpel70 |
c5eef785114172af92a644f2c971a510e55dac8d | 131,233 | cpp | C++ | disabled_modules/visual_script/visual_script_nodes.cpp | ZopharShinta/SegsEngine | 86d52c5b805e05e107594efd3358cabd694365f0 | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | null | null | null | disabled_modules/visual_script/visual_script_nodes.cpp | ZopharShinta/SegsEngine | 86d52c5b805e05e107594efd3358cabd694365f0 | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | null | null | null | disabled_modules/visual_script/visual_script_nodes.cpp | ZopharShinta/SegsEngine | 86d52c5b805e05e107594efd3358cabd694365f0 | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | null | null | null | /*************************************************************************/
/* visual_script_nodes.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* 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 "visual_script_nodes.h"
#include "core/engine.h"
#include "core/global_constants.h"
#include "core/method_bind.h"
#include "core/method_info.h"
#include "core/method_ptrcall.h"
#include "core/object_tooling.h"
#include "core/os/input.h"
#include "core/os/os.h"
#include "core/project_settings.h"
#include "core/string.h"
#include "core/string_formatter.h"
#include "core/translation_helpers.h"
#include "scene/main/node.h"
#include "scene/main/scene_tree.h"
#include "EASTL/sort.h"
IMPL_GDCLASS(VisualScriptFunction)
IMPL_GDCLASS(VisualScriptOperator)
IMPL_GDCLASS(VisualScriptSelect)
IMPL_GDCLASS(VisualScriptVariableGet)
IMPL_GDCLASS(VisualScriptVariableSet)
IMPL_GDCLASS(VisualScriptConstant)
IMPL_GDCLASS(VisualScriptPreload)
IMPL_GDCLASS(VisualScriptIndexGet)
IMPL_GDCLASS(VisualScriptLists)
IMPL_GDCLASS(VisualScriptComposeArray)
IMPL_GDCLASS(VisualScriptIndexSet)
IMPL_GDCLASS(VisualScriptGlobalConstant)
IMPL_GDCLASS(VisualScriptClassConstant)
IMPL_GDCLASS(VisualScriptBasicTypeConstant)
IMPL_GDCLASS(VisualScriptMathConstant)
IMPL_GDCLASS(VisualScriptEngineSingleton)
IMPL_GDCLASS(VisualScriptSceneNode)
IMPL_GDCLASS(VisualScriptSceneTree)
IMPL_GDCLASS(VisualScriptResourcePath)
IMPL_GDCLASS(VisualScriptSelf)
IMPL_GDCLASS(VisualScriptCustomNode)
IMPL_GDCLASS(VisualScriptSubCall)
IMPL_GDCLASS(VisualScriptComment)
IMPL_GDCLASS(VisualScriptConstructor)
IMPL_GDCLASS(VisualScriptLocalVar)
IMPL_GDCLASS(VisualScriptLocalVarSet)
IMPL_GDCLASS(VisualScriptInputAction)
IMPL_GDCLASS(VisualScriptDeconstruct)
VARIANT_ENUM_CAST(VisualScriptMathConstant::MathConstant)
VARIANT_ENUM_CAST(VisualScriptCustomNode::StartMode);
VARIANT_ENUM_CAST(VisualScriptInputAction::Mode)
//////////////////////////////////////////
////////////////FUNCTION//////////////////
//////////////////////////////////////////
bool VisualScriptFunction::_set(const StringName &p_name, const Variant &p_value) {
if (p_name == "argument_count") {
int new_argc = p_value.as<int>();
int argc = arguments.size();
if (argc == new_argc)
return true;
arguments.resize(new_argc);
for (int i = argc; i < new_argc; i++) {
arguments[i].name = StringName("arg" + itos(i + 1));
arguments[i].type = VariantType::NIL;
}
ports_changed_notify();
Object_change_notify(this);
return true;
}
if (StringUtils::begins_with(p_name,"argument/")) {
FixedVector<StringView, 3> parts;
String::split_ref(parts, p_name, '/');
int idx = StringUtils::to_int(parts[1]) - 1;
ERR_FAIL_INDEX_V(idx, arguments.size(), false);
StringView what = parts[2];
if (what == StringView("type")) {
VariantType new_type = p_value.as<VariantType>();
arguments[idx].type = new_type;
ports_changed_notify();
return true;
}
if (what == StringView("name")) {
arguments[idx].name = p_value.as<StringName>();
ports_changed_notify();
return true;
}
}
if (p_name == "stack/stackless") {
set_stack_less(p_value.as<bool>());
return true;
}
if (p_name == "stack/size") {
stack_size = p_value.as<int>();
return true;
}
if (p_name == "rpc/mode") {
rpc_mode = p_value.as<MultiplayerAPI_RPCMode>();
return true;
}
if (p_name == "sequenced/sequenced") {
sequenced = p_value.as<bool>();
ports_changed_notify();
return true;
}
return false;
}
bool VisualScriptFunction::_get(const StringName &p_name, Variant &r_ret) const {
if (p_name == "argument_count") {
r_ret = arguments.size();
return true;
}
if (StringUtils::begins_with(p_name,"argument/")) {
FixedVector<StringView, 3> parts;
String::split_ref(parts, p_name, '/');
int idx = StringUtils::to_int(parts[1]) - 1;
ERR_FAIL_INDEX_V(idx, arguments.size(), false);
StringView what = parts[2];
if (what == StringView("type")) {
r_ret = arguments[idx].type;
return true;
}
if (what == StringView("name")) {
r_ret = arguments[idx].name;
return true;
}
}
if (p_name == "stack/stackless") {
r_ret = stack_less;
return true;
}
if (p_name == "stack/size") {
r_ret = stack_size;
return true;
}
if (p_name == "rpc/mode") {
r_ret = (int8_t)rpc_mode;
return true;
}
if (p_name == "sequenced/sequenced") {
r_ret = sequenced;
return true;
}
return false;
}
void VisualScriptFunction::_get_property_list(Vector<PropertyInfo> *p_list) const {
p_list->push_back(PropertyInfo(VariantType::INT, "argument_count", PropertyHint::Range, "0,256"));
char argt[7+(longest_variant_type_name+1)*(int)VariantType::VARIANT_MAX];
fill_with_all_variant_types("Any",argt);
for (int i = 0; i < arguments.size(); i++) {
p_list->push_back(PropertyInfo(VariantType::INT, StringName("argument/" + itos(i + 1) + "/type"), PropertyHint::Enum, argt));
p_list->push_back(PropertyInfo(VariantType::STRING, StringName("argument/" + itos(i + 1) + "/name")));
}
p_list->push_back(PropertyInfo(VariantType::BOOL, "sequenced/sequenced"));
if (!stack_less) {
p_list->push_back(PropertyInfo(VariantType::INT, "stack/size", PropertyHint::Range, "1,100000"));
}
p_list->push_back(PropertyInfo(VariantType::BOOL, "stack/stackless"));
p_list->push_back(PropertyInfo(VariantType::INT, "rpc/mode", PropertyHint::Enum, "Disabled,Remote,Master,Puppet,Remote Sync,Master Sync,Puppet Sync"));
}
int VisualScriptFunction::get_output_sequence_port_count() const {
return 1;
}
bool VisualScriptFunction::has_input_sequence_port() const {
return false;
}
int VisualScriptFunction::get_input_value_port_count() const {
return 0;
}
int VisualScriptFunction::get_output_value_port_count() const {
return arguments.size();
}
StringView VisualScriptFunction::get_output_sequence_port_text(int p_port) const {
return nullptr;
}
PropertyInfo VisualScriptFunction::get_input_value_port_info(int p_idx) const {
ERR_FAIL_V(PropertyInfo());
}
PropertyInfo VisualScriptFunction::get_output_value_port_info(int p_idx) const {
ERR_FAIL_INDEX_V(p_idx, arguments.size(), PropertyInfo());
PropertyInfo out;
out.type = arguments[p_idx].type;
out.name = arguments[p_idx].name;
out.hint = arguments[p_idx].hint;
out.hint_string = arguments[p_idx].hint_string;
return out;
}
StringView VisualScriptFunction::get_caption() const {
return "Function";
}
String VisualScriptFunction::get_text() const {
return get_name(); //use name as function name I guess
}
void VisualScriptFunction::add_argument(VariantType p_type, const StringName &p_name, int p_index, const PropertyHint p_hint, StringView p_hint_string) {
Argument arg;
arg.name = p_name;
arg.type = p_type;
arg.hint = p_hint;
arg.hint_string = p_hint_string;
if (p_index >= 0)
arguments.insert_at(p_index, arg);
else
arguments.push_back(arg);
ports_changed_notify();
}
void VisualScriptFunction::set_argument_type(int p_argidx, VariantType p_type) {
ERR_FAIL_INDEX(p_argidx, arguments.size());
arguments[p_argidx].type = p_type;
ports_changed_notify();
}
VariantType VisualScriptFunction::get_argument_type(int p_argidx) const {
ERR_FAIL_INDEX_V(p_argidx, arguments.size(), VariantType::NIL);
return arguments[p_argidx].type;
}
void VisualScriptFunction::set_argument_name(int p_argidx, const StringName &p_name) {
ERR_FAIL_INDEX(p_argidx, arguments.size());
arguments[p_argidx].name = p_name;
ports_changed_notify();
}
StringName VisualScriptFunction::get_argument_name(int p_argidx) const {
ERR_FAIL_INDEX_V(p_argidx, arguments.size(), StringName());
return arguments[p_argidx].name;
}
void VisualScriptFunction::remove_argument(int p_argidx) {
ERR_FAIL_INDEX(p_argidx, arguments.size());
arguments.erase_at(p_argidx);
ports_changed_notify();
}
int VisualScriptFunction::get_argument_count() const {
return arguments.size();
}
void VisualScriptFunction::set_rpc_mode(MultiplayerAPI_RPCMode p_mode) {
rpc_mode = p_mode;
}
MultiplayerAPI_RPCMode VisualScriptFunction::get_rpc_mode() const {
return rpc_mode;
}
class VisualScriptNodeInstanceFunction : public VisualScriptNodeInstance {
public:
VisualScriptFunction *node;
VisualScriptInstance *instance;
//virtual int get_working_memory_size() const { return 0; }
int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override {
int ac = node->get_argument_count();
for (int i = 0; i < ac; i++) {
#ifdef DEBUG_ENABLED
VariantType expected = node->get_argument_type(i);
if (expected != VariantType::NIL) {
if (!Variant::can_convert_strict(p_inputs[i]->get_type(), expected)) {
r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
r_error.expected = expected;
r_error.argument = i;
return 0;
}
}
#endif
*p_outputs[i] = *p_inputs[i];
}
return 0;
}
};
VisualScriptNodeInstance *VisualScriptFunction::instance(VisualScriptInstance *p_instance) {
VisualScriptNodeInstanceFunction *instance = memnew(VisualScriptNodeInstanceFunction);
instance->node = this;
instance->instance = p_instance;
return instance;
}
VisualScriptFunction::VisualScriptFunction() {
stack_size = 256;
stack_less = false;
sequenced = true;
rpc_mode = MultiplayerAPI_RPCMode(0);
}
void VisualScriptFunction::set_stack_less(bool p_enable) {
stack_less = p_enable;
Object_change_notify(this);
}
bool VisualScriptFunction::is_stack_less() const {
return stack_less;
}
void VisualScriptFunction::set_sequenced(bool p_enable) {
sequenced = p_enable;
}
bool VisualScriptFunction::is_sequenced() const {
return sequenced;
}
void VisualScriptFunction::set_stack_size(int p_size) {
ERR_FAIL_COND(p_size < 1 || p_size > 100000);
stack_size = p_size;
}
int VisualScriptFunction::get_stack_size() const {
return stack_size;
}
//////////////////////////////////////////
/////////////////LISTS////////////////////
//////////////////////////////////////////
int VisualScriptLists::get_output_sequence_port_count() const {
if (sequenced)
return 1;
return 0;
}
bool VisualScriptLists::has_input_sequence_port() const {
return sequenced;
}
StringView VisualScriptLists::get_output_sequence_port_text(int p_port) const {
return nullptr;
}
int VisualScriptLists::get_input_value_port_count() const {
return inputports.size();
}
int VisualScriptLists::get_output_value_port_count() const {
return outputports.size();
}
PropertyInfo VisualScriptLists::get_input_value_port_info(int p_idx) const {
ERR_FAIL_INDEX_V(p_idx, inputports.size(), PropertyInfo());
PropertyInfo pi;
pi.name = inputports[p_idx].name;
pi.type = inputports[p_idx].type;
return pi;
}
PropertyInfo VisualScriptLists::get_output_value_port_info(int p_idx) const {
ERR_FAIL_INDEX_V(p_idx, outputports.size(), PropertyInfo());
PropertyInfo pi;
pi.name = outputports[p_idx].name;
pi.type = outputports[p_idx].type;
return pi;
}
bool VisualScriptLists::is_input_port_editable() const {
return ((flags & INPUT_EDITABLE) == INPUT_EDITABLE);
}
bool VisualScriptLists::is_input_port_name_editable() const {
return ((flags & INPUT_NAME_EDITABLE) == INPUT_NAME_EDITABLE);
}
bool VisualScriptLists::is_input_port_type_editable() const {
return ((flags & INPUT_TYPE_EDITABLE) == INPUT_TYPE_EDITABLE);
}
bool VisualScriptLists::is_output_port_editable() const {
return ((flags & OUTPUT_EDITABLE) == OUTPUT_EDITABLE);
}
bool VisualScriptLists::is_output_port_name_editable() const {
return ((flags & INPUT_NAME_EDITABLE) == INPUT_NAME_EDITABLE);
}
bool VisualScriptLists::is_output_port_type_editable() const {
return ((flags & INPUT_TYPE_EDITABLE) == INPUT_TYPE_EDITABLE);
}
// for the inspector
bool VisualScriptLists::_set(const StringName &p_name, const Variant &p_value) {
using namespace StringUtils;
if (p_name == "input_count" && is_input_port_editable()) {
int new_argc = p_value.as<int>();
int argc = inputports.size();
if (argc == new_argc)
return true;
inputports.resize(new_argc);
for (int i = argc; i < new_argc; i++) {
inputports[i].name = StringName("arg" + itos(i + 1));
inputports[i].type = VariantType::NIL;
}
ports_changed_notify();
Object_change_notify(this);
return true;
}
if (StringUtils::begins_with(p_name,"input/") && is_input_port_editable()) {
FixedVector<StringView, 3> parts;
String::split_ref(parts, p_name, '/');
int idx = to_int(parts[1]) - 1;
ERR_FAIL_INDEX_V(idx, inputports.size(), false);
StringView what = parts[2];
if (what == StringView("type")) {
VariantType new_type = p_value.as<VariantType>();
inputports[idx].type = new_type;
ports_changed_notify();
return true;
}
if (what == StringView("name")) {
inputports[idx].name = p_value.as<StringName>();
ports_changed_notify();
return true;
}
}
if (p_name == "output_count" && is_output_port_editable()) {
int new_argc = p_value.as<int>();
int argc = outputports.size();
if (argc == new_argc)
return true;
outputports.resize(new_argc);
for (int i = argc; i < new_argc; i++) {
outputports[i].name = StringName("arg" + itos(i + 1));
outputports[i].type = VariantType::NIL;
}
ports_changed_notify();
Object_change_notify(this);
return true;
}
if (begins_with(p_name,"output/") && is_output_port_editable()) {
FixedVector<StringView, 3> parts;
String::split_ref(parts, p_name, '/');
int idx = to_int(parts[1]) - 1;
ERR_FAIL_INDEX_V(idx, outputports.size(), false);
StringView what = parts[2];
if (what == StringView("type")) {
VariantType new_type = p_value.as<VariantType>();
outputports[idx].type = new_type;
ports_changed_notify();
return true;
}
if (what == StringView("name")) {
outputports[idx].name = p_value.as<StringName>();
ports_changed_notify();
return true;
}
}
if (p_name == "sequenced/sequenced") {
sequenced = p_value.as<bool>();
ports_changed_notify();
return true;
}
return false;
}
bool VisualScriptLists::_get(const StringName &p_name, Variant &r_ret) const {
using namespace StringUtils;
if (p_name == "input_count" && is_input_port_editable()) {
r_ret = inputports.size();
return true;
}
if (begins_with(p_name,"input/") && is_input_port_editable()) {
FixedVector<StringView, 3> parts;
String::split_ref(parts, p_name, '/');
int idx = to_int(parts[1]) - 1;
ERR_FAIL_INDEX_V(idx, inputports.size(), false);
StringView what = parts[2];
if (what == StringView("type")) {
r_ret = inputports[idx].type;
return true;
}
if (what == StringView("name")) {
r_ret = inputports[idx].name;
return true;
}
}
if (p_name == "output_count" && is_output_port_editable()) {
r_ret = outputports.size();
return true;
}
if (begins_with(p_name,"output/") && is_output_port_editable()) {
FixedVector<StringView, 3> parts;
String::split_ref(parts, p_name, '/');
int idx = to_int(parts[1]) - 1;
ERR_FAIL_INDEX_V(idx, outputports.size(), false);
StringView what = parts[2];
if (what == StringView("type")) {
r_ret = outputports[idx].type;
return true;
}
if (what == StringView("name")) {
r_ret = outputports[idx].name;
return true;
}
}
if (p_name == "sequenced/sequenced") {
r_ret = sequenced;
return true;
}
return false;
}
void VisualScriptLists::_get_property_list(Vector<PropertyInfo> *p_list) const {
if (is_input_port_editable()) {
p_list->push_back(PropertyInfo(VariantType::INT, "input_count", PropertyHint::Range, "0,256"));
String argt("Any");
for (int i = 1; i < (int8_t)VariantType::VARIANT_MAX; i++) {
argt += String(",") + Variant::get_type_name(VariantType(i));
}
for (int i = 0; i < inputports.size(); i++) {
p_list->push_back(PropertyInfo(VariantType::INT, StringName("input/" + itos(i + 1) + "/type"), PropertyHint::Enum, StringName(argt)));
p_list->push_back(PropertyInfo(VariantType::STRING, StringName("input/" + itos(i + 1) + "/name")));
}
}
if (is_output_port_editable()) {
p_list->push_back(PropertyInfo(VariantType::INT, "output_count", PropertyHint::Range, "0,256"));
String argt("Any");
for (int i = 1; i < (int8_t)VariantType::VARIANT_MAX; i++) {
argt += String(",") + Variant::get_type_name(VariantType(i));
}
for (int i = 0; i < outputports.size(); i++) {
p_list->push_back(PropertyInfo(VariantType::INT, StringName("output/" + itos(i + 1) + "/type"), PropertyHint::Enum, StringName(argt)));
p_list->push_back(PropertyInfo(VariantType::STRING, StringName("output/" + itos(i + 1) + "/name")));
}
}
p_list->push_back(PropertyInfo(VariantType::BOOL, "sequenced/sequenced"));
}
// input data port interaction
void VisualScriptLists::add_input_data_port(VariantType p_type, const StringName &p_name, int p_index) {
if (!is_input_port_editable())
return;
Port inp;
inp.name = p_name;
inp.type = p_type;
if (p_index >= 0)
inputports.insert_at(p_index, inp);
else
inputports.push_back(inp);
ports_changed_notify();
Object_change_notify(this);
}
void VisualScriptLists::set_input_data_port_type(int p_idx, VariantType p_type) {
if (!is_input_port_type_editable())
return;
ERR_FAIL_INDEX(p_idx, inputports.size());
inputports[p_idx].type = p_type;
ports_changed_notify();
Object_change_notify(this);
}
void VisualScriptLists::set_input_data_port_name(int p_idx, const StringName &p_name) {
if (!is_input_port_name_editable())
return;
ERR_FAIL_INDEX(p_idx, inputports.size());
inputports[p_idx].name = p_name;
ports_changed_notify();
Object_change_notify(this);
}
void VisualScriptLists::remove_input_data_port(int p_argidx) {
if (!is_input_port_editable())
return;
ERR_FAIL_INDEX(p_argidx, inputports.size());
inputports.erase_at(p_argidx);
ports_changed_notify();
Object_change_notify(this);
}
// output data port interaction
void VisualScriptLists::add_output_data_port(VariantType p_type, const StringName &p_name, int p_index) {
if (!is_output_port_editable())
return;
Port out;
out.name = p_name;
out.type = p_type;
if (p_index >= 0)
outputports.insert_at(p_index, out);
else
outputports.push_back(out);
ports_changed_notify();
Object_change_notify(this);
}
void VisualScriptLists::set_output_data_port_type(int p_idx, VariantType p_type) {
if (!is_output_port_type_editable())
return;
ERR_FAIL_INDEX(p_idx, outputports.size());
outputports[p_idx].type = p_type;
ports_changed_notify();
Object_change_notify(this);
}
void VisualScriptLists::set_output_data_port_name(int p_idx, const StringName &p_name) {
if (!is_output_port_name_editable())
return;
ERR_FAIL_INDEX(p_idx, outputports.size());
outputports[p_idx].name = p_name;
ports_changed_notify();
Object_change_notify(this);
}
void VisualScriptLists::remove_output_data_port(int p_argidx) {
if (!is_output_port_editable())
return;
ERR_FAIL_INDEX(p_argidx, outputports.size());
outputports.erase_at(p_argidx);
ports_changed_notify();
Object_change_notify(this);
}
// sequences
void VisualScriptLists::set_sequenced(bool p_enable) {
if (sequenced == p_enable)
return;
sequenced = p_enable;
ports_changed_notify();
}
bool VisualScriptLists::is_sequenced() const {
return sequenced;
}
VisualScriptLists::VisualScriptLists() {
// initialize
sequenced = false;
flags = 0;
}
void VisualScriptLists::_bind_methods() {
MethodBinder::bind_method(D_METHOD("add_input_data_port", {"type", "name", "index"}), &VisualScriptLists::add_input_data_port);
MethodBinder::bind_method(D_METHOD("set_input_data_port_name", {"index", "name"}), &VisualScriptLists::set_input_data_port_name);
MethodBinder::bind_method(D_METHOD("set_input_data_port_type", {"index", "type"}), &VisualScriptLists::set_input_data_port_type);
MethodBinder::bind_method(D_METHOD("remove_input_data_port", {"index"}), &VisualScriptLists::remove_input_data_port);
MethodBinder::bind_method(D_METHOD("add_output_data_port", {"type", "name", "index"}), &VisualScriptLists::add_output_data_port);
MethodBinder::bind_method(D_METHOD("set_output_data_port_name", {"index", "name"}), &VisualScriptLists::set_output_data_port_name);
MethodBinder::bind_method(D_METHOD("set_output_data_port_type", {"index", "type"}), &VisualScriptLists::set_output_data_port_type);
MethodBinder::bind_method(D_METHOD("remove_output_data_port", {"index"}), &VisualScriptLists::remove_output_data_port);
}
//////////////////////////////////////////
//////////////COMPOSEARRAY////////////////
//////////////////////////////////////////
int VisualScriptComposeArray::get_output_sequence_port_count() const {
if (sequenced)
return 1;
return 0;
}
bool VisualScriptComposeArray::has_input_sequence_port() const {
return sequenced;
}
StringView VisualScriptComposeArray::get_output_sequence_port_text(int p_port) const {
return nullptr;
}
int VisualScriptComposeArray::get_input_value_port_count() const {
return inputports.size();
}
int VisualScriptComposeArray::get_output_value_port_count() const {
return 1;
}
PropertyInfo VisualScriptComposeArray::get_input_value_port_info(int p_idx) const {
ERR_FAIL_INDEX_V(p_idx, inputports.size(), PropertyInfo());
PropertyInfo pi;
pi.name = inputports[p_idx].name;
pi.type = inputports[p_idx].type;
return pi;
}
PropertyInfo VisualScriptComposeArray::get_output_value_port_info(int p_idx) const {
PropertyInfo pi;
pi.name = "out";
pi.type = VariantType::ARRAY;
return pi;
}
StringView VisualScriptComposeArray::get_caption() const {
return "Compose Array";
}
String VisualScriptComposeArray::get_text() const {
return {};
}
class VisualScriptComposeArrayNode : public VisualScriptNodeInstance {
public:
int input_count = 0;
int get_working_memory_size() const override { return 0; }
virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override {
if (input_count > 0) {
Array arr;
for (int i = 0; i < input_count; i++)
arr.push_back((*p_inputs[i]));
Variant va = Variant(arr);
*p_outputs[0] = va;
}
return 0;
}
};
VisualScriptNodeInstance *VisualScriptComposeArray::instance(VisualScriptInstance *p_instance) {
VisualScriptComposeArrayNode *instance = memnew(VisualScriptComposeArrayNode);
instance->input_count = inputports.size();
return instance;
}
VisualScriptComposeArray::VisualScriptComposeArray() {
// initialize stuff here
sequenced = false;
flags = INPUT_EDITABLE;
}
//////////////////////////////////////////
////////////////OPERATOR//////////////////
//////////////////////////////////////////
int VisualScriptOperator::get_output_sequence_port_count() const {
return 0;
}
bool VisualScriptOperator::has_input_sequence_port() const {
return false;
}
int VisualScriptOperator::get_input_value_port_count() const {
return (op == Variant::OP_BIT_NEGATE || op == Variant::OP_NOT || op == Variant::OP_NEGATE || op == Variant::OP_POSITIVE) ? 1 : 2;
}
int VisualScriptOperator::get_output_value_port_count() const {
return 1;
}
StringView VisualScriptOperator::get_output_sequence_port_text(int p_port) const {
return StringView();
}
PropertyInfo VisualScriptOperator::get_input_value_port_info(int p_idx) const {
static const VariantType port_types[Variant::OP_MAX][2] = {
{ VariantType::NIL, VariantType::NIL }, //OP_EQUAL,
{ VariantType::NIL, VariantType::NIL }, //OP_NOT_EQUAL,
{ VariantType::NIL, VariantType::NIL }, //OP_LESS,
{ VariantType::NIL, VariantType::NIL }, //OP_LESS_EQUAL,
{ VariantType::NIL, VariantType::NIL }, //OP_GREATER,
{ VariantType::NIL, VariantType::NIL }, //OP_GREATER_EQUAL,
//mathematic
{ VariantType::NIL, VariantType::NIL }, //OP_ADD,
{ VariantType::NIL, VariantType::NIL }, //OP_SUBTRACT,
{ VariantType::NIL, VariantType::NIL }, //OP_MULTIPLY,
{ VariantType::NIL, VariantType::NIL }, //OP_DIVIDE,
{ VariantType::NIL, VariantType::NIL }, //OP_NEGATE,
{ VariantType::NIL, VariantType::NIL }, //OP_POSITIVE,
{ VariantType::INT, VariantType::INT }, //OP_MODULE,
{ VariantType::STRING, VariantType::STRING }, //OP_STRING_CONCAT,
//bitwise
{ VariantType::INT, VariantType::INT }, //OP_SHIFT_LEFT,
{ VariantType::INT, VariantType::INT }, //OP_SHIFT_RIGHT,
{ VariantType::INT, VariantType::INT }, //OP_BIT_AND,
{ VariantType::INT, VariantType::INT }, //OP_BIT_OR,
{ VariantType::INT, VariantType::INT }, //OP_BIT_XOR,
{ VariantType::INT, VariantType::INT }, //OP_BIT_NEGATE,
//logic
{ VariantType::BOOL, VariantType::BOOL }, //OP_AND,
{ VariantType::BOOL, VariantType::BOOL }, //OP_OR,
{ VariantType::BOOL, VariantType::BOOL }, //OP_XOR,
{ VariantType::BOOL, VariantType::BOOL }, //OP_NOT,
//containment
{ VariantType::NIL, VariantType::NIL } //OP_IN,
};
ERR_FAIL_INDEX_V(p_idx, 2, PropertyInfo());
PropertyInfo pinfo;
pinfo.name = StringName(p_idx == 0 ? "A" : "B");
pinfo.type = port_types[op][p_idx];
if (pinfo.type == VariantType::NIL)
pinfo.type = typed;
return pinfo;
}
PropertyInfo VisualScriptOperator::get_output_value_port_info(int p_idx) const {
static const VariantType port_types[Variant::OP_MAX] = {
//comparison
VariantType::BOOL, //OP_EQUAL,
VariantType::BOOL, //OP_NOT_EQUAL,
VariantType::BOOL, //OP_LESS,
VariantType::BOOL, //OP_LESS_EQUAL,
VariantType::BOOL, //OP_GREATER,
VariantType::BOOL, //OP_GREATER_EQUAL,
//mathematic
VariantType::NIL, //OP_ADD,
VariantType::NIL, //OP_SUBTRACT,
VariantType::NIL, //OP_MULTIPLY,
VariantType::NIL, //OP_DIVIDE,
VariantType::NIL, //OP_NEGATE,
VariantType::NIL, //OP_POSITIVE,
VariantType::INT, //OP_MODULE,
VariantType::STRING, //OP_STRING_CONCAT,
//bitwise
VariantType::INT, //OP_SHIFT_LEFT,
VariantType::INT, //OP_SHIFT_RIGHT,
VariantType::INT, //OP_BIT_AND,
VariantType::INT, //OP_BIT_OR,
VariantType::INT, //OP_BIT_XOR,
VariantType::INT, //OP_BIT_NEGATE,
//logic
VariantType::BOOL, //OP_AND,
VariantType::BOOL, //OP_OR,
VariantType::BOOL, //OP_XOR,
VariantType::BOOL, //OP_NOT,
//containment
VariantType::BOOL //OP_IN,
};
PropertyInfo pinfo;
pinfo.name = "";
pinfo.type = port_types[op];
if (pinfo.type == VariantType::NIL)
pinfo.type = typed;
return pinfo;
}
static const char *op_names[] = {
//comparison
"Are Equal", //OP_EQUAL,
"Are Not Equal", //OP_NOT_EQUAL,
"Less Than", //OP_LESS,
"Less Than or Equal", //OP_LESS_EQUAL,
"Greater Than", //OP_GREATER,
"Greater Than or Equal", //OP_GREATER_EQUAL,
//mathematic
"Add", //OP_ADD,
"Subtract", //OP_SUBTRACT,
"Multiply", //OP_MULTIPLY,
"Divide", //OP_DIVIDE,
"Negate", //OP_NEGATE,
"Positive", //OP_POSITIVE,
"Remainder", //OP_MODULE,
"Concatenate", //OP_STRING_CONCAT,
//bitwise
"Bit Shift Left", //OP_SHIFT_LEFT,
"Bit Shift Right", //OP_SHIFT_RIGHT,
"Bit And", //OP_BIT_AND,
"Bit Or", //OP_BIT_OR,
"Bit Xor", //OP_BIT_XOR,
"Bit Negate", //OP_BIT_NEGATE,
//logic
"And", //OP_AND,
"Or", //OP_OR,
"Xor", //OP_XOR,
"Not", //OP_NOT,
//containment
"In", //OP_IN,
};
StringView VisualScriptOperator::get_caption() const {
static const StringView op_names[] = {
//comparison
"A = B", //OP_EQUAL,
"A ≠B", //OP_NOT_EQUAL,
"A < B", //OP_LESS,
"A ≤ B", //OP_LESS_EQUAL,
"A > B", //OP_GREATER,
"A ≥ B", //OP_GREATER_EQUAL,
//mathematic
"A + B", //OP_ADD,
"A - B", //OP_SUBTRACT,
"A × B", //OP_MULTIPLY,
"A ÷ B", //OP_DIVIDE,
"¬ A", //OP_NEGATE,
"+ A", //OP_POSITIVE,
"A mod B", //OP_MODULE,
"A .. B", //OP_STRING_CONCAT,
//bitwise
"A << B", //OP_SHIFT_LEFT,
"A >> B", //OP_SHIFT_RIGHT,
"A & B", //OP_BIT_AND,
"A | B", //OP_BIT_OR,
"A ^ B", //OP_BIT_XOR,
"~A", //OP_BIT_NEGATE,
//logic
"A and B", //OP_AND,
"A or B", //OP_OR,
"A xor B", //OP_XOR,
"not A", //OP_NOT,
"A in B", //OP_IN,
};
return op_names[op];
}
void VisualScriptOperator::set_operator(Variant::Operator p_op) {
if (op == p_op)
return;
op = p_op;
ports_changed_notify();
}
Variant::Operator VisualScriptOperator::get_operator() const {
return op;
}
void VisualScriptOperator::set_typed(VariantType p_op) {
if (typed == p_op)
return;
typed = p_op;
ports_changed_notify();
}
VariantType VisualScriptOperator::get_typed() const {
return typed;
}
void VisualScriptOperator::_bind_methods() {
MethodBinder::bind_method(D_METHOD("set_operator", {"op"}), &VisualScriptOperator::set_operator);
MethodBinder::bind_method(D_METHOD("get_operator"), &VisualScriptOperator::get_operator);
MethodBinder::bind_method(D_METHOD("set_typed", {"type"}), &VisualScriptOperator::set_typed);
MethodBinder::bind_method(D_METHOD("get_typed"), &VisualScriptOperator::get_typed);
String types;
for (int i = 0; i < Variant::OP_MAX; i++) {
if (i > 0)
types += (",");
types += (op_names[i]);
}
char argt[7+(longest_variant_type_name+1)*(int)VariantType::VARIANT_MAX];
fill_with_all_variant_types("Any",argt);
ADD_PROPERTY(PropertyInfo(VariantType::INT, "operator", PropertyHint::Enum, StringName(types)), "set_operator", "get_operator");
ADD_PROPERTY(PropertyInfo(VariantType::INT, "type", PropertyHint::Enum, argt), "set_typed", "get_typed");
}
class VisualScriptNodeInstanceOperator : public VisualScriptNodeInstance {
public:
bool unary;
Variant::Operator op;
//virtual int get_working_memory_size() const { return 0; }
int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override {
bool valid;
if (unary) {
Variant::evaluate(op, *p_inputs[0], Variant(), *p_outputs[0], valid);
} else {
Variant::evaluate(op, *p_inputs[0], *p_inputs[1], *p_outputs[0], valid);
}
if (!valid) {
r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
if (p_outputs[0]->get_type() == VariantType::STRING) {
r_error_str = p_outputs[0]->as<String>();
} else {
if (unary)
r_error_str = String(op_names[op]) + RTR_utf8(": Invalid argument of type: ") + Variant::get_type_name(p_inputs[0]->get_type());
else
r_error_str = String(op_names[op]) + RTR_utf8(": Invalid arguments: ") + "A: " + Variant::get_type_name(p_inputs[0]->get_type()) + " B: " + Variant::get_type_name(p_inputs[1]->get_type());
}
}
return 0;
}
};
VisualScriptNodeInstance *VisualScriptOperator::instance(VisualScriptInstance *p_instance) {
VisualScriptNodeInstanceOperator *instance = memnew(VisualScriptNodeInstanceOperator);
instance->unary = get_input_value_port_count() == 1;
instance->op = op;
return instance;
}
VisualScriptOperator::VisualScriptOperator() {
op = Variant::OP_ADD;
typed = VariantType::NIL;
}
template <Variant::Operator OP>
static Ref<VisualScriptNode> create_op_node(StringView p_name) {
Ref<VisualScriptOperator> node(make_ref_counted<VisualScriptOperator>());
node->set_operator(OP);
return node;
}
//////////////////////////////////////////
////////////////OPERATOR//////////////////
//////////////////////////////////////////
int VisualScriptSelect::get_output_sequence_port_count() const {
return 0;
}
bool VisualScriptSelect::has_input_sequence_port() const {
return false;
}
int VisualScriptSelect::get_input_value_port_count() const {
return 3;
}
int VisualScriptSelect::get_output_value_port_count() const {
return 1;
}
StringView VisualScriptSelect::get_output_sequence_port_text(int p_port) const {
return StringView();
}
PropertyInfo VisualScriptSelect::get_input_value_port_info(int p_idx) const {
if (p_idx == 0) {
return PropertyInfo(VariantType::BOOL, "cond");
} else if (p_idx == 1) {
return PropertyInfo(typed, "a");
} else {
return PropertyInfo(typed, "b");
}
}
PropertyInfo VisualScriptSelect::get_output_value_port_info(int p_idx) const {
return PropertyInfo(typed, "out");
}
StringView VisualScriptSelect::get_caption() const {
return "Select";
}
String VisualScriptSelect::get_text() const {
return "a if cond, else b";
}
void VisualScriptSelect::set_typed(VariantType p_op) {
if (typed == p_op)
return;
typed = p_op;
ports_changed_notify();
}
VariantType VisualScriptSelect::get_typed() const {
return typed;
}
void VisualScriptSelect::_bind_methods() {
MethodBinder::bind_method(D_METHOD("set_typed", {"type"}), &VisualScriptSelect::set_typed);
MethodBinder::bind_method(D_METHOD("get_typed"), &VisualScriptSelect::get_typed);
char argt[7+(longest_variant_type_name+1)*(int)VariantType::VARIANT_MAX];
fill_with_all_variant_types("Any",argt);
ADD_PROPERTY(PropertyInfo(VariantType::INT, "type", PropertyHint::Enum, argt), "set_typed", "get_typed");
}
class VisualScriptNodeInstanceSelect : public VisualScriptNodeInstance {
public:
//virtual int get_working_memory_size() const { return 0; }
int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override {
bool cond = p_inputs[0]->as<bool>();
if (cond)
*p_outputs[0] = *p_inputs[1];
else
*p_outputs[0] = *p_inputs[2];
return 0;
}
};
VisualScriptNodeInstance *VisualScriptSelect::instance(VisualScriptInstance *p_instance) {
VisualScriptNodeInstanceSelect *instance = memnew(VisualScriptNodeInstanceSelect);
return instance;
}
VisualScriptSelect::VisualScriptSelect() {
typed = VariantType::NIL;
}
//////////////////////////////////////////
////////////////VARIABLE GET//////////////////
//////////////////////////////////////////
int VisualScriptVariableGet::get_output_sequence_port_count() const {
return 0;
}
bool VisualScriptVariableGet::has_input_sequence_port() const {
return false;
}
int VisualScriptVariableGet::get_input_value_port_count() const {
return 0;
}
int VisualScriptVariableGet::get_output_value_port_count() const {
return 1;
}
StringView VisualScriptVariableGet::get_output_sequence_port_text(int p_port) const {
return StringView();
}
PropertyInfo VisualScriptVariableGet::get_input_value_port_info(int p_idx) const {
return PropertyInfo();
}
PropertyInfo VisualScriptVariableGet::get_output_value_port_info(int p_idx) const {
PropertyInfo pinfo;
pinfo.name = "value";
if (get_visual_script() && get_visual_script()->has_variable(variable)) {
PropertyInfo vinfo = get_visual_script()->get_variable_info(variable);
pinfo.type = vinfo.type;
pinfo.hint = vinfo.hint;
pinfo.hint_string = vinfo.hint_string;
}
return pinfo;
}
StringView VisualScriptVariableGet::get_caption() const {
thread_local char buf[512];
buf[0]=0;
strncat(buf,"Get ",511);
strncat(buf,variable.asCString(),511);
return buf;
}
void VisualScriptVariableGet::set_variable(StringName p_variable) {
if (variable == p_variable)
return;
variable = p_variable;
ports_changed_notify();
}
StringName VisualScriptVariableGet::get_variable() const {
return variable;
}
void VisualScriptVariableGet::_validate_property(PropertyInfo &property) const {
if (property.name == "var_name" && get_visual_script()) {
Ref<VisualScript> vs = get_visual_script();
Vector<StringName> vars;
vs->get_variable_list(&vars);
String vhint;
for (int i=0,fin=vars.size(); i<fin; ++i) {
if (!vhint.empty())
vhint += (",");
vhint += vars[i].asCString();
}
property.hint = PropertyHint::Enum;
property.hint_string = vhint;
}
}
void VisualScriptVariableGet::_bind_methods() {
MethodBinder::bind_method(D_METHOD("set_variable", {"name"}), &VisualScriptVariableGet::set_variable);
MethodBinder::bind_method(D_METHOD("get_variable"), &VisualScriptVariableGet::get_variable);
ADD_PROPERTY(PropertyInfo(VariantType::STRING, "var_name"), "set_variable", "get_variable");
}
class VisualScriptNodeInstanceVariableGet : public VisualScriptNodeInstance {
public:
VisualScriptVariableGet *node;
VisualScriptInstance *instance;
StringName variable;
int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override {
if (!instance->get_variable(variable, p_outputs[0])) {
r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
r_error_str = RTR_utf8("VariableGet not found in script: ") + "'" + String(variable) + "'";
return 0;
}
return 0;
}
};
VisualScriptNodeInstance *VisualScriptVariableGet::instance(VisualScriptInstance *p_instance) {
VisualScriptNodeInstanceVariableGet *instance = memnew(VisualScriptNodeInstanceVariableGet);
instance->node = this;
instance->instance = p_instance;
instance->variable = variable;
return instance;
}
VisualScriptVariableGet::VisualScriptVariableGet() {
}
//////////////////////////////////////////
////////////////VARIABLE SET//////////////////
//////////////////////////////////////////
int VisualScriptVariableSet::get_output_sequence_port_count() const {
return 1;
}
bool VisualScriptVariableSet::has_input_sequence_port() const {
return true;
}
int VisualScriptVariableSet::get_input_value_port_count() const {
return 1;
}
int VisualScriptVariableSet::get_output_value_port_count() const {
return 0;
}
StringView VisualScriptVariableSet::get_output_sequence_port_text(int p_port) const {
return StringView();
}
PropertyInfo VisualScriptVariableSet::get_input_value_port_info(int p_idx) const {
PropertyInfo pinfo;
pinfo.name = "set";
if (get_visual_script() && get_visual_script()->has_variable(variable)) {
PropertyInfo vinfo = get_visual_script()->get_variable_info(variable);
pinfo.type = vinfo.type;
pinfo.hint = vinfo.hint;
pinfo.hint_string = vinfo.hint_string;
}
return pinfo;
}
PropertyInfo VisualScriptVariableSet::get_output_value_port_info(int p_idx) const {
return PropertyInfo();
}
StringView VisualScriptVariableSet::get_caption() const {
thread_local char buf[512];
buf[0]=0;
strncat(buf,"Set ",511);
strncat(buf,variable.asCString(),511);
return buf;
}
void VisualScriptVariableSet::set_variable(StringName p_variable) {
if (variable == p_variable)
return;
variable = p_variable;
ports_changed_notify();
}
StringName VisualScriptVariableSet::get_variable() const {
return variable;
}
void VisualScriptVariableSet::_validate_property(PropertyInfo &property) const {
if (property.name == "var_name" && get_visual_script()) {
Ref<VisualScript> vs = get_visual_script();
Vector<StringName> vars;
vs->get_variable_list(&vars);
String vhint;
for (int i=0,fin=vars.size(); i<fin; ++i) {
if (!vhint.empty())
vhint += (",");
vhint += vars[i].asCString();
}
property.hint = PropertyHint::Enum;
property.hint_string = vhint;
}
}
void VisualScriptVariableSet::_bind_methods() {
MethodBinder::bind_method(D_METHOD("set_variable", {"name"}), &VisualScriptVariableSet::set_variable);
MethodBinder::bind_method(D_METHOD("get_variable"), &VisualScriptVariableSet::get_variable);
ADD_PROPERTY(PropertyInfo(VariantType::STRING, "var_name"), "set_variable", "get_variable");
}
class VisualScriptNodeInstanceVariableSet : public VisualScriptNodeInstance {
public:
VisualScriptVariableSet *node;
VisualScriptInstance *instance;
StringName variable;
//virtual int get_working_memory_size() const { return 0; }
int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override {
if (!instance->set_variable(variable, *p_inputs[0])) {
r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
r_error_str = RTR_utf8("VariableSet not found in script: ") + "'" + variable + "'";
}
return 0;
}
};
VisualScriptNodeInstance *VisualScriptVariableSet::instance(VisualScriptInstance *p_instance) {
VisualScriptNodeInstanceVariableSet *instance = memnew(VisualScriptNodeInstanceVariableSet);
instance->node = this;
instance->instance = p_instance;
instance->variable = variable;
return instance;
}
VisualScriptVariableSet::VisualScriptVariableSet() {
}
//////////////////////////////////////////
////////////////CONSTANT//////////////////
//////////////////////////////////////////
int VisualScriptConstant::get_output_sequence_port_count() const {
return 0;
}
bool VisualScriptConstant::has_input_sequence_port() const {
return false;
}
int VisualScriptConstant::get_input_value_port_count() const {
return 0;
}
int VisualScriptConstant::get_output_value_port_count() const {
return 1;
}
StringView VisualScriptConstant::get_output_sequence_port_text(int p_port) const {
return StringView();
}
PropertyInfo VisualScriptConstant::get_input_value_port_info(int p_idx) const {
return PropertyInfo();
}
PropertyInfo VisualScriptConstant::get_output_value_port_info(int p_idx) const {
PropertyInfo pinfo;
pinfo.name = value.as<StringName>();
pinfo.type = type;
return pinfo;
}
StringView VisualScriptConstant::get_caption() const {
return ("Constant");
}
void VisualScriptConstant::set_constant_type(VariantType p_type) {
if (type == p_type)
return;
type = p_type;
Callable::CallError ce;
value = Variant::construct(type, nullptr, 0, ce);
ports_changed_notify();
Object_change_notify(this);
}
VariantType VisualScriptConstant::get_constant_type() const {
return type;
}
void VisualScriptConstant::set_constant_value(Variant p_value) {
if (value == p_value)
return;
value = p_value;
ports_changed_notify();
}
Variant VisualScriptConstant::get_constant_value() const {
return value;
}
void VisualScriptConstant::_validate_property(PropertyInfo &property) const {
if (property.name == "value") {
property.type = type;
if (type == VariantType::NIL)
property.usage = 0; //do not save if nil
}
}
void VisualScriptConstant::_bind_methods() {
MethodBinder::bind_method(D_METHOD("set_constant_type", {"type"}), &VisualScriptConstant::set_constant_type);
MethodBinder::bind_method(D_METHOD("get_constant_type"), &VisualScriptConstant::get_constant_type);
MethodBinder::bind_method(D_METHOD("set_constant_value", {"value"}), &VisualScriptConstant::set_constant_value);
MethodBinder::bind_method(D_METHOD("get_constant_value"), &VisualScriptConstant::get_constant_value);
char argt[7+(longest_variant_type_name+1)*(int)VariantType::VARIANT_MAX];
fill_with_all_variant_types("Null",argt);
ADD_PROPERTY(PropertyInfo(VariantType::INT, "type", PropertyHint::Enum, argt), "set_constant_type", "get_constant_type");
ADD_PROPERTY(PropertyInfo(VariantType::NIL, "value", PropertyHint::None, "", PROPERTY_USAGE_NIL_IS_VARIANT | PROPERTY_USAGE_DEFAULT), "set_constant_value", "get_constant_value");
}
class VisualScriptNodeInstanceConstant : public VisualScriptNodeInstance {
public:
Variant constant;
//virtual int get_working_memory_size() const { return 0; }
int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override {
*p_outputs[0] = constant;
return 0;
}
};
VisualScriptNodeInstance *VisualScriptConstant::instance(VisualScriptInstance *p_instance) {
VisualScriptNodeInstanceConstant *instance = memnew(VisualScriptNodeInstanceConstant);
instance->constant = value;
return instance;
}
VisualScriptConstant::VisualScriptConstant() {
type = VariantType::NIL;
}
//////////////////////////////////////////
////////////////PRELOAD//////////////////
//////////////////////////////////////////
int VisualScriptPreload::get_output_sequence_port_count() const {
return 0;
}
bool VisualScriptPreload::has_input_sequence_port() const {
return false;
}
int VisualScriptPreload::get_input_value_port_count() const {
return 0;
}
int VisualScriptPreload::get_output_value_port_count() const {
return 1;
}
StringView VisualScriptPreload::get_output_sequence_port_text(int p_port) const {
return StringView();
}
PropertyInfo VisualScriptPreload::get_input_value_port_info(int p_idx) const {
return PropertyInfo();
}
PropertyInfo VisualScriptPreload::get_output_value_port_info(int p_idx) const {
PropertyInfo pinfo;
pinfo.type = VariantType::OBJECT;
if (preload) {
pinfo.hint = PropertyHint::ResourceType;
pinfo.hint_string = preload->get_class();
if (PathUtils::is_resource_file(preload->get_path())) {
pinfo.name = StringName(preload->get_path());
} else if (!preload->get_name().empty()) {
pinfo.name = StringName(preload->get_name());
} else {
pinfo.name = StringName(preload->get_class());
}
} else {
pinfo.name = "<empty>";
}
return pinfo;
}
StringView VisualScriptPreload::get_caption() const {
return ("Preload");
}
void VisualScriptPreload::set_preload(const Ref<Resource> &p_preload) {
if (preload == p_preload)
return;
preload = p_preload;
ports_changed_notify();
}
Ref<Resource> VisualScriptPreload::get_preload() const {
return preload;
}
void VisualScriptPreload::_bind_methods() {
MethodBinder::bind_method(D_METHOD("set_preload", {"resource"}), &VisualScriptPreload::set_preload);
MethodBinder::bind_method(D_METHOD("get_preload"), &VisualScriptPreload::get_preload);
ADD_PROPERTY(PropertyInfo(VariantType::OBJECT, "resource", PropertyHint::ResourceType, "Resource"), "set_preload", "get_preload");
}
class VisualScriptNodeInstancePreload : public VisualScriptNodeInstance {
public:
Ref<Resource> preload;
//virtual int get_working_memory_size() const { return 0; }
int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override {
*p_outputs[0] = preload;
return 0;
}
};
VisualScriptNodeInstance *VisualScriptPreload::instance(VisualScriptInstance *p_instance) {
VisualScriptNodeInstancePreload *instance = memnew(VisualScriptNodeInstancePreload);
instance->preload = preload;
return instance;
}
VisualScriptPreload::VisualScriptPreload() {
}
//////////////////////////////////////////
////////////////INDEX////////////////////
//////////////////////////////////////////
int VisualScriptIndexGet::get_output_sequence_port_count() const {
return 0;
}
bool VisualScriptIndexGet::has_input_sequence_port() const {
return false;
}
int VisualScriptIndexGet::get_input_value_port_count() const {
return 2;
}
int VisualScriptIndexGet::get_output_value_port_count() const {
return 1;
}
StringView VisualScriptIndexGet::get_output_sequence_port_text(int p_port) const {
return StringView();
}
PropertyInfo VisualScriptIndexGet::get_input_value_port_info(int p_idx) const {
if (p_idx == 0) {
return PropertyInfo(VariantType::NIL, "base");
} else {
return PropertyInfo(VariantType::NIL, "index");
}
}
PropertyInfo VisualScriptIndexGet::get_output_value_port_info(int p_idx) const {
return PropertyInfo();
}
StringView VisualScriptIndexGet::get_caption() const {
return ("Get Index");
}
class VisualScriptNodeInstanceIndexGet : public VisualScriptNodeInstance {
public:
//virtual int get_working_memory_size() const { return 0; }
int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override {
bool valid;
*p_outputs[0] = p_inputs[0]->get(*p_inputs[1], &valid);
if (!valid) {
r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
r_error_str = "Invalid get: " + p_inputs[0]->get_construct_string();
}
return 0;
}
};
VisualScriptNodeInstance *VisualScriptIndexGet::instance(VisualScriptInstance *p_instance) {
VisualScriptNodeInstanceIndexGet *instance = memnew(VisualScriptNodeInstanceIndexGet);
return instance;
}
VisualScriptIndexGet::VisualScriptIndexGet() {
}
//////////////////////////////////////////
////////////////INDEXSET//////////////////
//////////////////////////////////////////
int VisualScriptIndexSet::get_output_sequence_port_count() const {
return 1;
}
bool VisualScriptIndexSet::has_input_sequence_port() const {
return true;
}
int VisualScriptIndexSet::get_input_value_port_count() const {
return 3;
}
int VisualScriptIndexSet::get_output_value_port_count() const {
return 0;
}
StringView VisualScriptIndexSet::get_output_sequence_port_text(int p_port) const {
return StringView();
}
PropertyInfo VisualScriptIndexSet::get_input_value_port_info(int p_idx) const {
if (p_idx == 0) {
return PropertyInfo(VariantType::NIL, "base");
} else if (p_idx == 1) {
return PropertyInfo(VariantType::NIL, "index");
} else {
return PropertyInfo(VariantType::NIL, "value");
}
}
PropertyInfo VisualScriptIndexSet::get_output_value_port_info(int p_idx) const {
return PropertyInfo();
}
StringView VisualScriptIndexSet::get_caption() const {
return ("Set Index");
}
class VisualScriptNodeInstanceIndexSet : public VisualScriptNodeInstance {
public:
//virtual int get_working_memory_size() const { return 0; }
int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override {
bool valid;
*p_outputs[0] = *p_inputs[0];
p_outputs[0]->set(*p_inputs[1], *p_inputs[2], &valid);
if (!valid) {
r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
r_error_str = "Invalid set: " + p_inputs[1]->get_construct_string();
}
return 0;
}
};
VisualScriptNodeInstance *VisualScriptIndexSet::instance(VisualScriptInstance *p_instance) {
VisualScriptNodeInstanceIndexSet *instance = memnew(VisualScriptNodeInstanceIndexSet);
return instance;
}
VisualScriptIndexSet::VisualScriptIndexSet() {
}
//////////////////////////////////////////
////////////////GLOBALCONSTANT///////////
//////////////////////////////////////////
int VisualScriptGlobalConstant::get_output_sequence_port_count() const {
return 0;
}
bool VisualScriptGlobalConstant::has_input_sequence_port() const {
return false;
}
int VisualScriptGlobalConstant::get_input_value_port_count() const {
return 0;
}
int VisualScriptGlobalConstant::get_output_value_port_count() const {
return 1;
}
StringView VisualScriptGlobalConstant::get_output_sequence_port_text(int p_port) const {
return StringView();
}
PropertyInfo VisualScriptGlobalConstant::get_input_value_port_info(int p_idx) const {
return PropertyInfo();
}
PropertyInfo VisualScriptGlobalConstant::get_output_value_port_info(int p_idx) const {
return PropertyInfo(VariantType::INT, StringName(GlobalConstants::get_global_constant_name(index)));
}
StringView VisualScriptGlobalConstant::get_caption() const {
return ("Global Constant");
}
void VisualScriptGlobalConstant::set_global_constant(int p_which) {
index = p_which;
Object_change_notify(this);
ports_changed_notify();
}
int VisualScriptGlobalConstant::get_global_constant() {
return index;
}
class VisualScriptNodeInstanceGlobalConstant : public VisualScriptNodeInstance {
public:
int index;
//virtual int get_working_memory_size() const { return 0; }
int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override {
*p_outputs[0] = GlobalConstants::get_global_constant_value(index);
return 0;
}
};
VisualScriptNodeInstance *VisualScriptGlobalConstant::instance(VisualScriptInstance *p_instance) {
VisualScriptNodeInstanceGlobalConstant *instance = memnew(VisualScriptNodeInstanceGlobalConstant);
instance->index = index;
return instance;
}
void VisualScriptGlobalConstant::_bind_methods() {
MethodBinder::bind_method(D_METHOD("set_global_constant", {"index"}), &VisualScriptGlobalConstant::set_global_constant);
MethodBinder::bind_method(D_METHOD("get_global_constant"), &VisualScriptGlobalConstant::get_global_constant);
String cc;
for (int i = 0; i < GlobalConstants::get_global_constant_count(); i++) {
if (i > 0)
cc += ",";
cc += String(GlobalConstants::get_global_constant_name(i));
}
ADD_PROPERTY(PropertyInfo(VariantType::INT, "constant", PropertyHint::Enum, StringName(cc)), "set_global_constant", "get_global_constant");
}
VisualScriptGlobalConstant::VisualScriptGlobalConstant() {
index = 0;
}
//////////////////////////////////////////
////////////////CLASSCONSTANT///////////
//////////////////////////////////////////
int VisualScriptClassConstant::get_output_sequence_port_count() const {
return 0;
}
bool VisualScriptClassConstant::has_input_sequence_port() const {
return false;
}
int VisualScriptClassConstant::get_input_value_port_count() const {
return 0;
}
int VisualScriptClassConstant::get_output_value_port_count() const {
return 1;
}
StringView VisualScriptClassConstant::get_output_sequence_port_text(int p_port) const {
return StringView();
}
PropertyInfo VisualScriptClassConstant::get_input_value_port_info(int p_idx) const {
return PropertyInfo();
}
PropertyInfo VisualScriptClassConstant::get_output_value_port_info(int p_idx) const {
return PropertyInfo(VariantType::INT, StringName(String(base_type) + "." + name));
}
StringView VisualScriptClassConstant::get_caption() const {
return ("Class Constant");
}
void VisualScriptClassConstant::set_class_constant(const StringName &p_which) {
name = p_which;
Object_change_notify(this);
ports_changed_notify();
}
StringName VisualScriptClassConstant::get_class_constant() {
return name;
}
void VisualScriptClassConstant::set_base_type(const StringName &p_which) {
base_type = p_which;
List<String> constants;
ClassDB::get_integer_constant_list(base_type, &constants, true);
if (constants.size() > 0) {
bool found_name = false;
for (const String &E : constants) {
if (E == name) {
found_name = true;
break;
}
}
if (!found_name) {
name = StringName(constants.front());
}
} else {
name = "";
}
Object_change_notify(this);
ports_changed_notify();
}
StringName VisualScriptClassConstant::get_base_type() {
return base_type;
}
class VisualScriptNodeInstanceClassConstant : public VisualScriptNodeInstance {
public:
int value;
bool valid;
//virtual int get_working_memory_size() const { return 0; }
int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override {
if (!valid) {
r_error_str = "Invalid constant name, pick a valid class constant.";
r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
}
*p_outputs[0] = value;
return 0;
}
};
VisualScriptNodeInstance *VisualScriptClassConstant::instance(VisualScriptInstance *p_instance) {
VisualScriptNodeInstanceClassConstant *instance = memnew(VisualScriptNodeInstanceClassConstant);
instance->value = ClassDB::get_integer_constant(base_type, name, &instance->valid);
return instance;
}
void VisualScriptClassConstant::_validate_property(PropertyInfo &property) const {
if (property.name == "constant") {
List<String> constants;
ClassDB::get_integer_constant_list(base_type, &constants, true);
property.hint_string = "";
for(const String & E : constants) {
if (!property.hint_string.empty()) {
property.hint_string += ",";
}
property.hint_string += E;
}
}
}
void VisualScriptClassConstant::_bind_methods() {
MethodBinder::bind_method(D_METHOD("set_class_constant", {"name"}), &VisualScriptClassConstant::set_class_constant);
MethodBinder::bind_method(D_METHOD("get_class_constant"), &VisualScriptClassConstant::get_class_constant);
MethodBinder::bind_method(D_METHOD("set_base_type", {"name"}), &VisualScriptClassConstant::set_base_type);
MethodBinder::bind_method(D_METHOD("get_base_type"), &VisualScriptClassConstant::get_base_type);
ADD_PROPERTY(PropertyInfo(VariantType::STRING, "base_type", PropertyHint::TypeString, "Object"), "set_base_type", "get_base_type");
ADD_PROPERTY(PropertyInfo(VariantType::STRING, "constant", PropertyHint::Enum, ""), "set_class_constant", "get_class_constant");
}
VisualScriptClassConstant::VisualScriptClassConstant() {
base_type = "Object";
}
//////////////////////////////////////////
////////////////BASICTYPECONSTANT///////////
//////////////////////////////////////////
int VisualScriptBasicTypeConstant::get_output_sequence_port_count() const {
return 0;
}
bool VisualScriptBasicTypeConstant::has_input_sequence_port() const {
return false;
}
int VisualScriptBasicTypeConstant::get_input_value_port_count() const {
return 0;
}
int VisualScriptBasicTypeConstant::get_output_value_port_count() const {
return 1;
}
StringView VisualScriptBasicTypeConstant::get_output_sequence_port_text(int p_port) const {
return StringView();
}
PropertyInfo VisualScriptBasicTypeConstant::get_input_value_port_info(int p_idx) const {
return PropertyInfo();
}
PropertyInfo VisualScriptBasicTypeConstant::get_output_value_port_info(int p_idx) const {
return PropertyInfo(type, "value");
}
StringView VisualScriptBasicTypeConstant::get_caption() const {
return "Basic Constant";
}
String VisualScriptBasicTypeConstant::get_text() const {
if (name.empty()) {
return Variant::get_type_name(type);
} else {
return String(Variant::get_type_name(type)) + "." + name;
}
}
void VisualScriptBasicTypeConstant::set_basic_type_constant(const StringName &p_which) {
name = p_which;
Object_change_notify(this);
ports_changed_notify();
}
StringName VisualScriptBasicTypeConstant::get_basic_type_constant() const {
return name;
}
void VisualScriptBasicTypeConstant::set_basic_type(VariantType p_which) {
type = p_which;
Vector<StringName> constants;
Variant::get_constants_for_type(type, &constants);
if (constants.size() > 0) {
bool found_name = false;
for (const StringName &E : constants) {
if (name == StringView(E)) {
found_name = true;
break;
}
}
if (!found_name) {
name = constants[0];
}
} else {
name = "";
}
Object_change_notify(this);
ports_changed_notify();
}
VariantType VisualScriptBasicTypeConstant::get_basic_type() const {
return type;
}
class VisualScriptNodeInstanceBasicTypeConstant : public VisualScriptNodeInstance {
public:
Variant value;
bool valid;
//virtual int get_working_memory_size() const { return 0; }
int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override {
if (!valid) {
r_error_str = "Invalid constant name, pick a valid basic type constant.";
r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
}
*p_outputs[0] = value;
return 0;
}
};
VisualScriptNodeInstance *VisualScriptBasicTypeConstant::instance(VisualScriptInstance *p_instance) {
VisualScriptNodeInstanceBasicTypeConstant *instance = memnew(VisualScriptNodeInstanceBasicTypeConstant);
instance->value = Variant::get_constant_value(type, name, &instance->valid);
return instance;
}
void VisualScriptBasicTypeConstant::_validate_property(PropertyInfo &property) const {
if (property.name == "constant") {
Vector<StringName> constants;
Variant::get_constants_for_type(type, &constants);
if (constants.empty()) {
property.usage = 0;
return;
}
property.hint_string = "";
for (const StringName &E : constants) {
if (!property.hint_string.empty()) {
property.hint_string += (",");
}
property.hint_string += E;
}
}
}
void VisualScriptBasicTypeConstant::_bind_methods() {
MethodBinder::bind_method(D_METHOD("set_basic_type", {"name"}), &VisualScriptBasicTypeConstant::set_basic_type);
MethodBinder::bind_method(D_METHOD("get_basic_type"), &VisualScriptBasicTypeConstant::get_basic_type);
MethodBinder::bind_method(D_METHOD("set_basic_type_constant", {"name"}), &VisualScriptBasicTypeConstant::set_basic_type_constant);
MethodBinder::bind_method(D_METHOD("get_basic_type_constant"), &VisualScriptBasicTypeConstant::get_basic_type_constant);
char argt[7+(longest_variant_type_name+1)*(int)VariantType::VARIANT_MAX];
fill_with_all_variant_types("Null",argt);
ADD_PROPERTY(PropertyInfo(VariantType::INT, "basic_type", PropertyHint::Enum, argt), "set_basic_type", "get_basic_type");
ADD_PROPERTY(PropertyInfo(VariantType::STRING, "constant", PropertyHint::Enum, ""), "set_basic_type_constant", "get_basic_type_constant");
}
VisualScriptBasicTypeConstant::VisualScriptBasicTypeConstant() {
type = VariantType::NIL;
}
//////////////////////////////////////////
////////////////MATHCONSTANT///////////
//////////////////////////////////////////
const char *VisualScriptMathConstant::const_name[MATH_CONSTANT_MAX] = {
"One",
"PI",
"PI/2",
"TAU",
"E",
"Sqrt2",
"INF",
"NAN"
};
double VisualScriptMathConstant::const_value[MATH_CONSTANT_MAX] = {
1.0,
Math_PI,
Math_PI * 0.5,
Math_TAU,
2.71828182845904523536,
Math::sqrt(2.0),
Math_INF,
Math_NAN
};
int VisualScriptMathConstant::get_output_sequence_port_count() const {
return 0;
}
bool VisualScriptMathConstant::has_input_sequence_port() const {
return false;
}
int VisualScriptMathConstant::get_input_value_port_count() const {
return 0;
}
int VisualScriptMathConstant::get_output_value_port_count() const {
return 1;
}
StringView VisualScriptMathConstant::get_output_sequence_port_text(int p_port) const {
return StringView();
}
PropertyInfo VisualScriptMathConstant::get_input_value_port_info(int p_idx) const {
return PropertyInfo();
}
PropertyInfo VisualScriptMathConstant::get_output_value_port_info(int p_idx) const {
return PropertyInfo(VariantType::FLOAT, StaticCString(const_name[constant],true));
}
StringView VisualScriptMathConstant::get_caption() const {
return ("Math Constant");
}
void VisualScriptMathConstant::set_math_constant(MathConstant p_which) {
constant = p_which;
Object_change_notify(this);
ports_changed_notify();
}
VisualScriptMathConstant::MathConstant VisualScriptMathConstant::get_math_constant() {
return constant;
}
class VisualScriptNodeInstanceMathConstant : public VisualScriptNodeInstance {
public:
float value;
//virtual int get_working_memory_size() const { return 0; }
int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override {
*p_outputs[0] = value;
return 0;
}
};
VisualScriptNodeInstance *VisualScriptMathConstant::instance(VisualScriptInstance *p_instance) {
VisualScriptNodeInstanceMathConstant *instance = memnew(VisualScriptNodeInstanceMathConstant);
instance->value = const_value[constant];
return instance;
}
void VisualScriptMathConstant::_bind_methods() {
MethodBinder::bind_method(D_METHOD("set_math_constant", {"which"}), &VisualScriptMathConstant::set_math_constant);
MethodBinder::bind_method(D_METHOD("get_math_constant"), &VisualScriptMathConstant::get_math_constant);
String cc;
for (int i = 0; i < MATH_CONSTANT_MAX; i++) {
if (i > 0)
cc += (",");
cc += (const_name[i]);
}
ADD_PROPERTY(PropertyInfo(VariantType::INT, "constant", PropertyHint::Enum, StringName(cc)), "set_math_constant", "get_math_constant");
BIND_ENUM_CONSTANT(MATH_CONSTANT_ONE)
BIND_ENUM_CONSTANT(MATH_CONSTANT_PI)
BIND_ENUM_CONSTANT(MATH_CONSTANT_HALF_PI)
BIND_ENUM_CONSTANT(MATH_CONSTANT_TAU)
BIND_ENUM_CONSTANT(MATH_CONSTANT_E)
BIND_ENUM_CONSTANT(MATH_CONSTANT_SQRT2)
BIND_ENUM_CONSTANT(MATH_CONSTANT_INF)
BIND_ENUM_CONSTANT(MATH_CONSTANT_NAN)
BIND_ENUM_CONSTANT(MATH_CONSTANT_MAX)
}
VisualScriptMathConstant::VisualScriptMathConstant() {
constant = MATH_CONSTANT_ONE;
}
//////////////////////////////////////////
////////////////ENGINESINGLETON///////////
//////////////////////////////////////////
int VisualScriptEngineSingleton::get_output_sequence_port_count() const {
return 0;
}
bool VisualScriptEngineSingleton::has_input_sequence_port() const {
return false;
}
int VisualScriptEngineSingleton::get_input_value_port_count() const {
return 0;
}
int VisualScriptEngineSingleton::get_output_value_port_count() const {
return 1;
}
StringView VisualScriptEngineSingleton::get_output_sequence_port_text(int p_port) const {
return StringView();
}
PropertyInfo VisualScriptEngineSingleton::get_input_value_port_info(int p_idx) const {
return PropertyInfo();
}
PropertyInfo VisualScriptEngineSingleton::get_output_value_port_info(int p_idx) const {
return PropertyInfo(VariantType::OBJECT, singleton);
}
StringView VisualScriptEngineSingleton::get_caption() const {
return ("Get Engine Singleton");
}
void VisualScriptEngineSingleton::set_singleton(const StringName &p_string) {
singleton = p_string;
Object_change_notify(this);
ports_changed_notify();
}
StringName VisualScriptEngineSingleton::get_singleton() {
return singleton;
}
class VisualScriptNodeInstanceEngineSingleton : public VisualScriptNodeInstance {
public:
Object *singleton;
//virtual int get_working_memory_size() const { return 0; }
int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override {
*p_outputs[0] = Variant(singleton);
return 0;
}
};
VisualScriptNodeInstance *VisualScriptEngineSingleton::instance(VisualScriptInstance *p_instance) {
VisualScriptNodeInstanceEngineSingleton *instance = memnew(VisualScriptNodeInstanceEngineSingleton);
instance->singleton = Engine::get_singleton()->get_named_singleton(singleton);
return instance;
}
VisualScriptEngineSingleton::TypeGuess VisualScriptEngineSingleton::guess_output_type(TypeGuess *p_inputs, int p_output) const {
Object *obj = Engine::get_singleton()->get_named_singleton(singleton);
TypeGuess tg;
tg.type = VariantType::OBJECT;
if (obj) {
tg.gdclass = obj->get_class_name();
tg.script = refFromRefPtr<Script>(obj->get_script());
}
return tg;
}
void VisualScriptEngineSingleton::_validate_property(PropertyInfo &property) const {
String cc;
const Vector<Engine::Singleton> &singletons = Engine::get_singleton()->get_singletons();
for (const Engine::Singleton &E : singletons) {
if (E.name == "VS" || E.name == "PS" || E.name == "PS2D" || E.name == "AS" || E.name == "TS" || E.name == "SS" || E.name == "SS2D")
continue; //skip these, too simple named
if (!cc.empty())
cc += ",";
cc += E.name;
}
property.hint = PropertyHint::Enum;
property.hint_string = cc;
}
void VisualScriptEngineSingleton::_bind_methods() {
MethodBinder::bind_method(D_METHOD("set_singleton", {"name"}), &VisualScriptEngineSingleton::set_singleton);
MethodBinder::bind_method(D_METHOD("get_singleton"), &VisualScriptEngineSingleton::get_singleton);
ADD_PROPERTY(PropertyInfo(VariantType::STRING, "constant"), "set_singleton", "get_singleton");
}
VisualScriptEngineSingleton::VisualScriptEngineSingleton() {
singleton = StringName();
}
//////////////////////////////////////////
////////////////GETNODE///////////
//////////////////////////////////////////
int VisualScriptSceneNode::get_output_sequence_port_count() const {
return 0;
}
bool VisualScriptSceneNode::has_input_sequence_port() const {
return false;
}
int VisualScriptSceneNode::get_input_value_port_count() const {
return 0;
}
int VisualScriptSceneNode::get_output_value_port_count() const {
return 1;
}
StringView VisualScriptSceneNode::get_output_sequence_port_text(int p_port) const {
return StringView();
}
PropertyInfo VisualScriptSceneNode::get_input_value_port_info(int p_idx) const {
return PropertyInfo();
}
PropertyInfo VisualScriptSceneNode::get_output_value_port_info(int p_idx) const {
return PropertyInfo(VariantType::OBJECT, StringName((String)path.simplified()));
}
StringView VisualScriptSceneNode::get_caption() const {
return ("Get Scene Node");
}
void VisualScriptSceneNode::set_node_path(const NodePath &p_path) {
path = p_path;
Object_change_notify(this);
ports_changed_notify();
}
NodePath VisualScriptSceneNode::get_node_path() {
return path;
}
class VisualScriptNodeInstanceSceneNode : public VisualScriptNodeInstance {
public:
VisualScriptSceneNode *node;
VisualScriptInstance *instance;
NodePath path;
//virtual int get_working_memory_size() const { return 0; }
int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override {
Node *node = object_cast<Node>(instance->get_owner_ptr());
if (!node) {
r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
r_error_str = "Base object is not a Node!";
return 0;
}
Node *another = node->get_node(path);
if (!another) {
r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
r_error_str = "Path does not lead Node!";
return 0;
}
*p_outputs[0] = Variant(another);
return 0;
}
};
VisualScriptNodeInstance *VisualScriptSceneNode::instance(VisualScriptInstance *p_instance) {
VisualScriptNodeInstanceSceneNode *instance = memnew(VisualScriptNodeInstanceSceneNode);
instance->node = this;
instance->instance = p_instance;
instance->path = path;
return instance;
}
VisualScriptSceneNode::TypeGuess VisualScriptSceneNode::guess_output_type(TypeGuess *p_inputs, int p_output) const {
VisualScriptSceneNode::TypeGuess tg;
tg.type = VariantType::OBJECT;
tg.gdclass = "Node";
#ifdef TOOLS_ENABLED
Ref<Script> script = get_visual_script();
if (not script)
return tg;
MainLoop *main_loop = OS::get_singleton()->get_main_loop();
SceneTree *scene_tree = object_cast<SceneTree>(main_loop);
if (!scene_tree)
return tg;
Node *edited_scene = scene_tree->get_edited_scene_root();
if (!edited_scene)
return tg;
Node *script_node = _find_script_node(edited_scene, edited_scene, script);
if (!script_node)
return tg;
Node *another = script_node->get_node(path);
if (another) {
tg.gdclass = another->get_class_name();
tg.script = refFromRefPtr<Script>(another->get_script());
}
#endif
return tg;
}
void VisualScriptSceneNode::_validate_property(PropertyInfo &property) const {
#ifdef TOOLS_ENABLED
if (property.name == "node_path") {
Ref<Script> script = get_visual_script();
if (not script)
return;
MainLoop *main_loop = OS::get_singleton()->get_main_loop();
SceneTree *scene_tree = object_cast<SceneTree>(main_loop);
if (!scene_tree)
return;
Node *edited_scene = scene_tree->get_edited_scene_root();
if (!edited_scene)
return;
Node *script_node = _find_script_node(edited_scene, edited_scene, script);
if (!script_node)
return;
property.hint_string = (String)script_node->get_path();
}
#endif
}
void VisualScriptSceneNode::_bind_methods() {
MethodBinder::bind_method(D_METHOD("set_node_path", {"path"}), &VisualScriptSceneNode::set_node_path);
MethodBinder::bind_method(D_METHOD("get_node_path"), &VisualScriptSceneNode::get_node_path);
ADD_PROPERTY(PropertyInfo(VariantType::NODE_PATH, "node_path", PropertyHint::NodePathToEditedNode), "set_node_path", "get_node_path");
}
VisualScriptSceneNode::VisualScriptSceneNode() {
path = NodePath(".");
}
//////////////////////////////////////////
////////////////SceneTree///////////
//////////////////////////////////////////
int VisualScriptSceneTree::get_output_sequence_port_count() const {
return 0;
}
bool VisualScriptSceneTree::has_input_sequence_port() const {
return false;
}
int VisualScriptSceneTree::get_input_value_port_count() const {
return 0;
}
int VisualScriptSceneTree::get_output_value_port_count() const {
return 1;
}
StringView VisualScriptSceneTree::get_output_sequence_port_text(int p_port) const {
return StringView();
}
PropertyInfo VisualScriptSceneTree::get_input_value_port_info(int p_idx) const {
return PropertyInfo();
}
PropertyInfo VisualScriptSceneTree::get_output_value_port_info(int p_idx) const {
return PropertyInfo(VariantType::OBJECT, "Scene Tree", PropertyHint::TypeString, "SceneTree");
}
StringView VisualScriptSceneTree::get_caption() const {
return "Get Scene Tree";
}
class VisualScriptNodeInstanceSceneTree : public VisualScriptNodeInstance {
public:
VisualScriptSceneTree *node;
VisualScriptInstance *instance;
//virtual int get_working_memory_size() const { return 0; }
int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override {
Node *node = object_cast<Node>(instance->get_owner_ptr());
if (!node) {
r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
r_error_str = "Base object is not a Node!";
return 0;
}
SceneTree *tree = node->get_tree();
if (!tree) {
r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
r_error_str = "Attempt to get SceneTree while node is not in the active tree.";
return 0;
}
*p_outputs[0] = Variant(tree);
return 0;
}
};
VisualScriptNodeInstance *VisualScriptSceneTree::instance(VisualScriptInstance *p_instance) {
VisualScriptNodeInstanceSceneTree *instance = memnew(VisualScriptNodeInstanceSceneTree);
instance->node = this;
instance->instance = p_instance;
return instance;
}
VisualScriptSceneTree::TypeGuess VisualScriptSceneTree::guess_output_type(TypeGuess *p_inputs, int p_output) const {
TypeGuess tg;
tg.type = VariantType::OBJECT;
tg.gdclass = "SceneTree";
return tg;
}
void VisualScriptSceneTree::_validate_property(PropertyInfo &property) const {
}
void VisualScriptSceneTree::_bind_methods() {
}
VisualScriptSceneTree::VisualScriptSceneTree() {
}
//////////////////////////////////////////
////////////////RESPATH///////////
//////////////////////////////////////////
int VisualScriptResourcePath::get_output_sequence_port_count() const {
return 0;
}
bool VisualScriptResourcePath::has_input_sequence_port() const {
return false;
}
int VisualScriptResourcePath::get_input_value_port_count() const {
return 0;
}
int VisualScriptResourcePath::get_output_value_port_count() const {
return 1;
}
StringView VisualScriptResourcePath::get_output_sequence_port_text(int p_port) const {
return StringView();
}
PropertyInfo VisualScriptResourcePath::get_input_value_port_info(int p_idx) const {
return PropertyInfo();
}
PropertyInfo VisualScriptResourcePath::get_output_value_port_info(int p_idx) const {
return PropertyInfo(VariantType::STRING, StringName(path));
}
StringView VisualScriptResourcePath::get_caption() const {
return ("Resource Path");
}
void VisualScriptResourcePath::set_resource_path(StringView p_path) {
path = p_path;
Object_change_notify(this);
ports_changed_notify();
}
const String & VisualScriptResourcePath::get_resource_path() {
return path;
}
class VisualScriptNodeInstanceResourcePath : public VisualScriptNodeInstance {
public:
String path;
//virtual int get_working_memory_size() const { return 0; }
int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override {
*p_outputs[0] = path;
return 0;
}
};
VisualScriptNodeInstance *VisualScriptResourcePath::instance(VisualScriptInstance *p_instance) {
VisualScriptNodeInstanceResourcePath *instance = memnew(VisualScriptNodeInstanceResourcePath);
instance->path = path;
return instance;
}
void VisualScriptResourcePath::_bind_methods() {
MethodBinder::bind_method(D_METHOD("set_resource_path", {"path"}), &VisualScriptResourcePath::set_resource_path);
MethodBinder::bind_method(D_METHOD("get_resource_path"), &VisualScriptResourcePath::get_resource_path);
ADD_PROPERTY(PropertyInfo(VariantType::STRING, "path", PropertyHint::File), "set_resource_path", "get_resource_path");
}
VisualScriptResourcePath::VisualScriptResourcePath() {
path = "";
}
//////////////////////////////////////////
////////////////SELF///////////
//////////////////////////////////////////
int VisualScriptSelf::get_output_sequence_port_count() const {
return 0;
}
bool VisualScriptSelf::has_input_sequence_port() const {
return false;
}
int VisualScriptSelf::get_input_value_port_count() const {
return 0;
}
int VisualScriptSelf::get_output_value_port_count() const {
return 1;
}
StringView VisualScriptSelf::get_output_sequence_port_text(int p_port) const {
return StringView();
}
PropertyInfo VisualScriptSelf::get_input_value_port_info(int p_idx) const {
return PropertyInfo();
}
PropertyInfo VisualScriptSelf::get_output_value_port_info(int p_idx) const {
StringName type_name;
if (get_visual_script())
type_name = get_visual_script()->get_instance_base_type();
else
type_name = "instance";
return PropertyInfo(VariantType::OBJECT, type_name);
}
StringView VisualScriptSelf::get_caption() const {
return ("Get Self");
}
class VisualScriptNodeInstanceSelf : public VisualScriptNodeInstance {
public:
VisualScriptInstance *instance;
//virtual int get_working_memory_size() const { return 0; }
int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override {
*p_outputs[0] = Variant(instance->get_owner_ptr());
return 0;
}
};
VisualScriptNodeInstance *VisualScriptSelf::instance(VisualScriptInstance *p_instance) {
VisualScriptNodeInstanceSelf *instance = memnew(VisualScriptNodeInstanceSelf);
instance->instance = p_instance;
return instance;
}
VisualScriptSelf::TypeGuess VisualScriptSelf::guess_output_type(TypeGuess *p_inputs, int p_output) const {
VisualScriptSceneNode::TypeGuess tg;
tg.type = VariantType::OBJECT;
tg.gdclass = "Object";
Ref<Script> script = get_visual_script();
if (not script)
return tg;
tg.gdclass = script->get_instance_base_type();
tg.script = script;
return tg;
}
void VisualScriptSelf::_bind_methods() {
}
VisualScriptSelf::VisualScriptSelf() {
}
//////////////////////////////////////////
////////////////CUSTOM (SCRIPTED)///////////
//////////////////////////////////////////
int VisualScriptCustomNode::get_output_sequence_port_count() const {
if (get_script_instance() && get_script_instance()->has_method("_get_output_sequence_port_count")) {
return get_script_instance()->call("_get_output_sequence_port_count").as<int>();
}
return 0;
}
bool VisualScriptCustomNode::has_input_sequence_port() const {
if (get_script_instance() && get_script_instance()->has_method("_has_input_sequence_port")) {
return get_script_instance()->call("_has_input_sequence_port").as<bool>();
}
return false;
}
int VisualScriptCustomNode::get_input_value_port_count() const {
if (get_script_instance() && get_script_instance()->has_method("_get_input_value_port_count")) {
return get_script_instance()->call("_get_input_value_port_count").as<int>();
}
return 0;
}
int VisualScriptCustomNode::get_output_value_port_count() const {
if (get_script_instance() && get_script_instance()->has_method("_get_output_value_port_count")) {
return get_script_instance()->call("_get_output_value_port_count").as<int>();
}
return 0;
}
StringView VisualScriptCustomNode::get_output_sequence_port_text(int p_port) const {
if (get_script_instance() && get_script_instance()->has_method("_get_output_sequence_port_text")) {
static String val;
val = get_script_instance()->call("_get_output_sequence_port_text", p_port).as<String>();
return val;
}
return StringView();
}
PropertyInfo VisualScriptCustomNode::get_input_value_port_info(int p_idx) const {
PropertyInfo info;
if (get_script_instance() && get_script_instance()->has_method("_get_input_value_port_type")) {
info.type = get_script_instance()->call("_get_input_value_port_type", p_idx).as<VariantType>();
}
if (get_script_instance() && get_script_instance()->has_method("_get_input_value_port_name")) {
info.name = get_script_instance()->call("_get_input_value_port_name", p_idx).as<StringName>();
}
return info;
}
PropertyInfo VisualScriptCustomNode::get_output_value_port_info(int p_idx) const {
PropertyInfo info;
if (get_script_instance() && get_script_instance()->has_method("_get_output_value_port_type")) {
info.type = get_script_instance()->call("_get_output_value_port_type", p_idx).as<VariantType>();
}
if (get_script_instance() && get_script_instance()->has_method("_get_output_value_port_name")) {
info.name = get_script_instance()->call("_get_output_value_port_name", p_idx).as<StringName>();
}
return info;
}
StringView VisualScriptCustomNode::get_caption() const {
thread_local char buf[512];
if (get_script_instance() && get_script_instance()->has_method("_get_caption")) {
buf[0]=0;
strncat(buf,get_script_instance()->call("_get_caption").as<String>().c_str(),511);
return buf;
}
return "CustomNode";
}
String VisualScriptCustomNode::get_text() const {
if (get_script_instance() && get_script_instance()->has_method("_get_text")) {
return get_script_instance()->call("_get_text").as<String>();
}
return String();
}
const char *VisualScriptCustomNode::get_category() const {
if (get_script_instance() && get_script_instance()->has_method("_get_category")) {
static char buf[256];
strncpy(buf,get_script_instance()->call("_get_category").as<String>().c_str(),255);
return buf;
}
return "Custom";
}
class VisualScriptNodeInstanceCustomNode : public VisualScriptNodeInstance {
public:
VisualScriptInstance *instance;
VisualScriptCustomNode *node;
int in_count;
int out_count;
int work_mem_size;
int get_working_memory_size() const override { return work_mem_size; }
int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override {
if (node->get_script_instance()) {
#ifdef DEBUG_ENABLED
if (!node->get_script_instance()->has_method(VisualScriptLanguage::singleton->_step)) {
r_error_str = RTR_utf8("Custom node has no _step() method, can't process graph.");
r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
return 0;
}
#endif
Array in_values;
Array out_values;
Array work_mem;
in_values.resize(in_count);
for (int i = 0; i < in_count; i++) {
in_values[i] = *p_inputs[i];
}
out_values.resize(out_count);
work_mem.resize(work_mem_size);
for (int i = 0; i < work_mem_size; i++) {
work_mem[i] = p_working_mem[i];
}
int ret_out;
Variant ret = node->get_script_instance()->call(VisualScriptLanguage::singleton->_step, in_values, out_values, p_start_mode, work_mem);
if (ret.get_type() == VariantType::STRING) {
r_error_str = ret.as<String>();
r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
return 0;
} else if (ret.is_num()) {
ret_out = ret.as<int>();
} else {
r_error_str = RTR_utf8("Invalid return value from _step(), must be integer (seq out), or string (error).");
r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
return 0;
}
for (int i = 0; i < out_count; i++) {
if (i < out_values.size()) {
*p_outputs[i] = out_values[i];
}
}
for (int i = 0; i < work_mem_size; i++) {
if (i < work_mem.size()) {
p_working_mem[i] = work_mem[i];
}
}
return ret_out;
}
return 0;
}
};
VisualScriptNodeInstance *VisualScriptCustomNode::instance(VisualScriptInstance *p_instance) {
VisualScriptNodeInstanceCustomNode *instance = memnew(VisualScriptNodeInstanceCustomNode);
instance->instance = p_instance;
instance->node = this;
instance->in_count = get_input_value_port_count();
instance->out_count = get_output_value_port_count();
if (get_script_instance() && get_script_instance()->has_method("_get_working_memory_size")) {
instance->work_mem_size = get_script_instance()->call("_get_working_memory_size").as<int>();
} else {
instance->work_mem_size = 0;
}
return instance;
}
void VisualScriptCustomNode::_script_changed() {
call_deferred("ports_changed_notify");
}
void VisualScriptCustomNode::_bind_methods() {
BIND_VMETHOD(MethodInfo(VariantType::INT, "_get_output_sequence_port_count"));
BIND_VMETHOD(MethodInfo(VariantType::BOOL, "_has_input_sequence_port"));
BIND_VMETHOD(MethodInfo(VariantType::STRING, "_get_output_sequence_port_text", PropertyInfo(VariantType::INT, "idx")));
BIND_VMETHOD(MethodInfo(VariantType::INT, "_get_input_value_port_count"));
BIND_VMETHOD(MethodInfo(VariantType::INT, "_get_output_value_port_count"));
BIND_VMETHOD(MethodInfo(VariantType::INT, "_get_input_value_port_type", PropertyInfo(VariantType::INT, "idx")));
BIND_VMETHOD(MethodInfo(VariantType::STRING, "_get_input_value_port_name", PropertyInfo(VariantType::INT, "idx")));
BIND_VMETHOD(MethodInfo(VariantType::INT, "_get_output_value_port_type", PropertyInfo(VariantType::INT, "idx")));
BIND_VMETHOD(MethodInfo(VariantType::STRING, "_get_output_value_port_name", PropertyInfo(VariantType::INT, "idx")));
BIND_VMETHOD(MethodInfo(VariantType::STRING, "_get_caption"));
BIND_VMETHOD(MethodInfo(VariantType::STRING, "_get_text"));
BIND_VMETHOD(MethodInfo(VariantType::STRING, "_get_category"));
BIND_VMETHOD(MethodInfo(VariantType::INT, "_get_working_memory_size"));
MethodInfo stepmi(VariantType::NIL, "_step", PropertyInfo(VariantType::ARRAY, "inputs"),
PropertyInfo(VariantType::ARRAY, "outputs"), PropertyInfo(VariantType::INT, "start_mode"),
PropertyInfo(VariantType::ARRAY, "working_mem"));
stepmi.return_val.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
BIND_VMETHOD(stepmi);
MethodBinder::bind_method(D_METHOD("_script_changed"), &VisualScriptCustomNode::_script_changed);
BIND_ENUM_CONSTANT(START_MODE_BEGIN_SEQUENCE)
BIND_ENUM_CONSTANT(START_MODE_CONTINUE_SEQUENCE)
BIND_ENUM_CONSTANT(START_MODE_RESUME_YIELD)
BIND_CONSTANT(STEP_PUSH_STACK_BIT)
BIND_CONSTANT(STEP_GO_BACK_BIT)
BIND_CONSTANT(STEP_NO_ADVANCE_BIT)
BIND_CONSTANT(STEP_EXIT_FUNCTION_BIT)
BIND_CONSTANT(STEP_YIELD_BIT)
}
VisualScriptCustomNode::VisualScriptCustomNode() {
connect("script_changed", this, "_script_changed");
}
//////////////////////////////////////////
////////////////SUBCALL///////////
//////////////////////////////////////////
int VisualScriptSubCall::get_output_sequence_port_count() const {
return 1;
}
bool VisualScriptSubCall::has_input_sequence_port() const {
return true;
}
int VisualScriptSubCall::get_input_value_port_count() const {
Ref<Script> script = refFromRefPtr<Script>(get_script());
if (script && script->has_method(VisualScriptLanguage::singleton->_subcall)) {
MethodInfo mi = script->get_method_info(VisualScriptLanguage::singleton->_subcall);
return mi.arguments.size();
}
return 0;
}
int VisualScriptSubCall::get_output_value_port_count() const {
return 1;
}
StringView VisualScriptSubCall::get_output_sequence_port_text(int p_port) const {
return StringView();
}
PropertyInfo VisualScriptSubCall::get_input_value_port_info(int p_idx) const {
Ref<Script> script = refFromRefPtr<Script>(get_script());
if (script && script->has_method(VisualScriptLanguage::singleton->_subcall)) {
MethodInfo mi = script->get_method_info(VisualScriptLanguage::singleton->_subcall);
return mi.arguments[p_idx];
}
return PropertyInfo();
}
PropertyInfo VisualScriptSubCall::get_output_value_port_info(int p_idx) const {
Ref<Script> script = refFromRefPtr<Script>(get_script());
if (script && script->has_method(VisualScriptLanguage::singleton->_subcall)) {
MethodInfo mi = script->get_method_info(VisualScriptLanguage::singleton->_subcall);
return mi.return_val;
}
return PropertyInfo();
}
StringView VisualScriptSubCall::get_caption() const {
return "SubCall";
}
String VisualScriptSubCall::get_text() const {
Ref<Script> script = refFromRefPtr<Script>(get_script());
if (script) {
if (!script->get_name().empty())
return script->get_name();
if (PathUtils::is_resource_file(script->get_path()))
return String(PathUtils::get_file(script->get_path()));
return String(script->get_class());
}
return String();
}
const char *VisualScriptSubCall::get_category() const {
return "custom";
}
class VisualScriptNodeInstanceSubCall : public VisualScriptNodeInstance {
public:
VisualScriptInstance *instance;
VisualScriptSubCall *subcall;
int input_args;
bool valid;
//virtual int get_working_memory_size() const { return 0; }
int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override {
if (!valid) {
r_error_str = "Node requires a script with a _subcall(<args>) method to work.";
r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
return 0;
}
*p_outputs[0] = subcall->call(VisualScriptLanguage::singleton->_subcall, p_inputs, input_args, r_error);
return 0;
}
};
VisualScriptNodeInstance *VisualScriptSubCall::instance(VisualScriptInstance *p_instance) {
VisualScriptNodeInstanceSubCall *instance = memnew(VisualScriptNodeInstanceSubCall);
instance->instance = p_instance;
Ref<Script> script = refFromRefPtr<Script>(get_script());
if (script && script->has_method(VisualScriptLanguage::singleton->_subcall)) {
instance->valid = true;
instance->input_args = get_input_value_port_count();
} else {
instance->valid = false;
}
return instance;
}
void VisualScriptSubCall::_bind_methods() {
MethodInfo scmi(VariantType::NIL, "_subcall", PropertyInfo(VariantType::NIL, "arguments"));
scmi.return_val.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
BIND_VMETHOD(scmi);
}
VisualScriptSubCall::VisualScriptSubCall() {
}
//////////////////////////////////////////
////////////////Comment///////////
//////////////////////////////////////////
int VisualScriptComment::get_output_sequence_port_count() const {
return 0;
}
bool VisualScriptComment::has_input_sequence_port() const {
return false;
}
int VisualScriptComment::get_input_value_port_count() const {
return 0;
}
int VisualScriptComment::get_output_value_port_count() const {
return 0;
}
StringView VisualScriptComment::get_output_sequence_port_text(int p_port) const {
return StringView();
}
PropertyInfo VisualScriptComment::get_input_value_port_info(int p_idx) const {
return PropertyInfo();
}
PropertyInfo VisualScriptComment::get_output_value_port_info(int p_idx) const {
return PropertyInfo();
}
StringView VisualScriptComment::get_caption() const {
return title;
}
String VisualScriptComment::get_text() const {
return description;
}
void VisualScriptComment::set_title(const String &p_title) {
if (title == p_title)
return;
title = p_title;
ports_changed_notify();
}
const String & VisualScriptComment::get_title() const {
return title;
}
void VisualScriptComment::set_description(const String &p_description) {
if (description == p_description)
return;
description = p_description;
ports_changed_notify();
}
const String& VisualScriptComment::get_description() const {
return description;
}
void VisualScriptComment::set_size(const Size2 &p_size) {
if (size == p_size)
return;
size = p_size;
ports_changed_notify();
}
Size2 VisualScriptComment::get_size() const {
return size;
}
const char *VisualScriptComment::get_category() const {
return "data";
}
class VisualScriptNodeInstanceComment : public VisualScriptNodeInstance {
public:
VisualScriptInstance *instance;
//virtual int get_working_memory_size() const { return 0; }
int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override {
return 0;
}
};
VisualScriptNodeInstance *VisualScriptComment::instance(VisualScriptInstance *p_instance) {
VisualScriptNodeInstanceComment *instance = memnew(VisualScriptNodeInstanceComment);
instance->instance = p_instance;
return instance;
}
void VisualScriptComment::_bind_methods() {
MethodBinder::bind_method(D_METHOD("set_title", {"title"}), &VisualScriptComment::set_title);
MethodBinder::bind_method(D_METHOD("get_title"), &VisualScriptComment::get_title);
MethodBinder::bind_method(D_METHOD("set_description", {"description"}), &VisualScriptComment::set_description);
MethodBinder::bind_method(D_METHOD("get_description"), &VisualScriptComment::get_description);
MethodBinder::bind_method(D_METHOD("set_size", {"size"}), &VisualScriptComment::set_size);
MethodBinder::bind_method(D_METHOD("get_size"), &VisualScriptComment::get_size);
ADD_PROPERTY(PropertyInfo(VariantType::STRING, "title"), "set_title", "get_title");
ADD_PROPERTY(PropertyInfo(VariantType::STRING, "description", PropertyHint::MultilineText), "set_description", "get_description");
ADD_PROPERTY(PropertyInfo(VariantType::VECTOR2, "size"), "set_size", "get_size");
}
VisualScriptComment::VisualScriptComment() {
title = "Comment";
size = Size2(150, 150);
}
//////////////////////////////////////////
////////////////Constructor///////////
//////////////////////////////////////////
int VisualScriptConstructor::get_output_sequence_port_count() const {
return 0;
}
bool VisualScriptConstructor::has_input_sequence_port() const {
return false;
}
int VisualScriptConstructor::get_input_value_port_count() const {
return constructor.arguments.size();
}
int VisualScriptConstructor::get_output_value_port_count() const {
return 1;
}
StringView VisualScriptConstructor::get_output_sequence_port_text(int p_port) const {
return StringView();
}
PropertyInfo VisualScriptConstructor::get_input_value_port_info(int p_idx) const {
return constructor.arguments[p_idx];
}
PropertyInfo VisualScriptConstructor::get_output_value_port_info(int p_idx) const {
return PropertyInfo(type, "value");
}
StringView VisualScriptConstructor::get_caption() const {
thread_local char buf[512];
buf[0]=0;
strncat(buf,"Construct ",511);
strncat(buf,Variant::get_type_name(type),511);
return buf;
}
const char *VisualScriptConstructor::get_category() const {
return "functions";
}
void VisualScriptConstructor::set_constructor_type(VariantType p_type) {
if (type == p_type)
return;
type = p_type;
ports_changed_notify();
}
VariantType VisualScriptConstructor::get_constructor_type() const {
return type;
}
void VisualScriptConstructor::set_constructor(const Dictionary &p_info) {
constructor = MethodInfo::from_dict(p_info);
ports_changed_notify();
}
Dictionary VisualScriptConstructor::get_constructor() const {
return constructor;
}
class VisualScriptNodeInstanceConstructor : public VisualScriptNodeInstance {
public:
VisualScriptInstance *instance;
VariantType type;
int argcount;
//virtual int get_working_memory_size() const { return 0; }
int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override {
Callable::CallError ce;
*p_outputs[0] = Variant::construct(type, p_inputs, argcount, ce);
if (ce.error != Callable::CallError::CALL_OK) {
r_error_str = "Invalid arguments for constructor";
}
return 0;
}
};
VisualScriptNodeInstance *VisualScriptConstructor::instance(VisualScriptInstance *p_instance) {
VisualScriptNodeInstanceConstructor *instance = memnew(VisualScriptNodeInstanceConstructor);
instance->instance = p_instance;
instance->type = type;
instance->argcount = constructor.arguments.size();
return instance;
}
void VisualScriptConstructor::_bind_methods() {
MethodBinder::bind_method(D_METHOD("set_constructor_type", {"type"}), &VisualScriptConstructor::set_constructor_type);
MethodBinder::bind_method(D_METHOD("get_constructor_type"), &VisualScriptConstructor::get_constructor_type);
MethodBinder::bind_method(D_METHOD("set_constructor", {"constructor"}), &VisualScriptConstructor::set_constructor);
MethodBinder::bind_method(D_METHOD("get_constructor"), &VisualScriptConstructor::get_constructor);
ADD_PROPERTY(PropertyInfo(VariantType::INT, "type", PropertyHint::None, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL), "set_constructor_type", "get_constructor_type");
ADD_PROPERTY(PropertyInfo(VariantType::DICTIONARY, "constructor", PropertyHint::None, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL), "set_constructor", "get_constructor");
}
VisualScriptConstructor::VisualScriptConstructor() {
type = VariantType::NIL;
}
static Map<String, Pair<VariantType, MethodInfo> > constructor_map;
static Ref<VisualScriptNode> create_constructor_node(StringView p_name) {
auto constructor_iter = constructor_map.find_as(p_name);
ERR_FAIL_COND_V(constructor_iter==constructor_map.end(), Ref<VisualScriptNode>());
Ref<VisualScriptConstructor> vsc(make_ref_counted<VisualScriptConstructor>());
vsc->set_constructor_type(constructor_iter->second.first);
vsc->set_constructor(constructor_iter->second.second);
return vsc;
}
//////////////////////////////////////////
////////////////LocalVar///////////
//////////////////////////////////////////
int VisualScriptLocalVar::get_output_sequence_port_count() const {
return 0;
}
bool VisualScriptLocalVar::has_input_sequence_port() const {
return false;
}
int VisualScriptLocalVar::get_input_value_port_count() const {
return 0;
}
int VisualScriptLocalVar::get_output_value_port_count() const {
return 1;
}
StringView VisualScriptLocalVar::get_output_sequence_port_text(int p_port) const {
return StringView();
}
PropertyInfo VisualScriptLocalVar::get_input_value_port_info(int p_idx) const {
return PropertyInfo();
}
PropertyInfo VisualScriptLocalVar::get_output_value_port_info(int p_idx) const {
return PropertyInfo(type, name);
}
StringView VisualScriptLocalVar::get_caption() const {
return "Get Local Var";
}
const char *VisualScriptLocalVar::get_category() const {
return "data";
}
void VisualScriptLocalVar::set_var_name(const StringName &p_name) {
if (name == p_name)
return;
name = p_name;
ports_changed_notify();
}
StringName VisualScriptLocalVar::get_var_name() const {
return name;
}
void VisualScriptLocalVar::set_var_type(VariantType p_type) {
type = p_type;
ports_changed_notify();
}
VariantType VisualScriptLocalVar::get_var_type() const {
return type;
}
class VisualScriptNodeInstanceLocalVar : public VisualScriptNodeInstance {
public:
VisualScriptInstance *instance;
StringName name;
int get_working_memory_size() const override { return 1; }
int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override {
*p_outputs[0] = *p_working_mem;
return 0;
}
};
VisualScriptNodeInstance *VisualScriptLocalVar::instance(VisualScriptInstance *p_instance) {
VisualScriptNodeInstanceLocalVar *instance = memnew(VisualScriptNodeInstanceLocalVar);
instance->instance = p_instance;
instance->name = name;
return instance;
}
void VisualScriptLocalVar::_bind_methods() {
MethodBinder::bind_method(D_METHOD("set_var_name", {"name"}), &VisualScriptLocalVar::set_var_name);
MethodBinder::bind_method(D_METHOD("get_var_name"), &VisualScriptLocalVar::get_var_name);
MethodBinder::bind_method(D_METHOD("set_var_type", {"type"}), &VisualScriptLocalVar::set_var_type);
MethodBinder::bind_method(D_METHOD("get_var_type"), &VisualScriptLocalVar::get_var_type);
char argt[7+(longest_variant_type_name+1)*(int)VariantType::VARIANT_MAX];
fill_with_all_variant_types("Any",argt);
ADD_PROPERTY(PropertyInfo(VariantType::STRING, "var_name"), "set_var_name", "get_var_name");
ADD_PROPERTY(PropertyInfo(VariantType::INT, "type", PropertyHint::Enum, argt), "set_var_type", "get_var_type");
}
VisualScriptLocalVar::VisualScriptLocalVar() {
name = "new_local";
type = VariantType::NIL;
}
//////////////////////////////////////////
////////////////LocalVar///////////
//////////////////////////////////////////
int VisualScriptLocalVarSet::get_output_sequence_port_count() const {
return 1;
}
bool VisualScriptLocalVarSet::has_input_sequence_port() const {
return true;
}
int VisualScriptLocalVarSet::get_input_value_port_count() const {
return 1;
}
int VisualScriptLocalVarSet::get_output_value_port_count() const {
return 1;
}
StringView VisualScriptLocalVarSet::get_output_sequence_port_text(int p_port) const {
return StringView();
}
PropertyInfo VisualScriptLocalVarSet::get_input_value_port_info(int p_idx) const {
return PropertyInfo(type, "set");
}
PropertyInfo VisualScriptLocalVarSet::get_output_value_port_info(int p_idx) const {
return PropertyInfo(type, "get");
}
StringView VisualScriptLocalVarSet::get_caption() const {
return "Set Local Var";
}
String VisualScriptLocalVarSet::get_text() const {
return name.asCString();
}
const char *VisualScriptLocalVarSet::get_category() const {
return "data";
}
void VisualScriptLocalVarSet::set_var_name(const StringName &p_name) {
if (name == p_name)
return;
name = p_name;
ports_changed_notify();
}
StringName VisualScriptLocalVarSet::get_var_name() const {
return name;
}
void VisualScriptLocalVarSet::set_var_type(VariantType p_type) {
type = p_type;
ports_changed_notify();
}
VariantType VisualScriptLocalVarSet::get_var_type() const {
return type;
}
class VisualScriptNodeInstanceLocalVarSet : public VisualScriptNodeInstance {
public:
VisualScriptInstance *instance;
StringName name;
int get_working_memory_size() const override { return 1; }
int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override {
*p_working_mem = *p_inputs[0];
*p_outputs[0] = *p_working_mem;
return 0;
}
};
VisualScriptNodeInstance *VisualScriptLocalVarSet::instance(VisualScriptInstance *p_instance) {
VisualScriptNodeInstanceLocalVarSet *instance = memnew(VisualScriptNodeInstanceLocalVarSet);
instance->instance = p_instance;
instance->name = name;
return instance;
}
void VisualScriptLocalVarSet::_bind_methods() {
MethodBinder::bind_method(D_METHOD("set_var_name", {"name"}), &VisualScriptLocalVarSet::set_var_name);
MethodBinder::bind_method(D_METHOD("get_var_name"), &VisualScriptLocalVarSet::get_var_name);
MethodBinder::bind_method(D_METHOD("set_var_type", {"type"}), &VisualScriptLocalVarSet::set_var_type);
MethodBinder::bind_method(D_METHOD("get_var_type"), &VisualScriptLocalVarSet::get_var_type);
char argt[7+(longest_variant_type_name+1)*(int)VariantType::VARIANT_MAX];
fill_with_all_variant_types("Any",argt);
ADD_PROPERTY(PropertyInfo(VariantType::STRING, "var_name"), "set_var_name", "get_var_name");
ADD_PROPERTY(PropertyInfo(VariantType::INT, "type", PropertyHint::Enum, argt), "set_var_type", "get_var_type");
}
VisualScriptLocalVarSet::VisualScriptLocalVarSet() {
name = "new_local";
type = VariantType::NIL;
}
//////////////////////////////////////////
////////////////LocalVar///////////
//////////////////////////////////////////
int VisualScriptInputAction::get_output_sequence_port_count() const {
return 0;
}
bool VisualScriptInputAction::has_input_sequence_port() const {
return false;
}
int VisualScriptInputAction::get_input_value_port_count() const {
return 0;
}
int VisualScriptInputAction::get_output_value_port_count() const {
return 1;
}
StringView VisualScriptInputAction::get_output_sequence_port_text(int p_port) const {
return StringView();
}
PropertyInfo VisualScriptInputAction::get_input_value_port_info(int p_idx) const {
return PropertyInfo();
}
PropertyInfo VisualScriptInputAction::get_output_value_port_info(int p_idx) const {
const char *mstr=nullptr;
switch (mode) {
case MODE_PRESSED: {
mstr = "pressed";
} break;
case MODE_RELEASED: {
mstr = "not pressed";
} break;
case MODE_JUST_PRESSED: {
mstr = "just pressed";
} break;
case MODE_JUST_RELEASED: {
mstr = "just released";
} break;
}
return PropertyInfo(VariantType::BOOL, StaticCString(mstr,true));
}
StringView VisualScriptInputAction::get_caption() const {
thread_local char buf[512];
buf[0]=0;
strncat(buf,"Action ",511);
strncat(buf,name.asCString(),511);
return buf;
}
const char *VisualScriptInputAction::get_category() const {
return "data";
}
void VisualScriptInputAction::set_action_name(const StringName &p_name) {
if (name == p_name)
return;
name = p_name;
ports_changed_notify();
}
StringName VisualScriptInputAction::get_action_name() const {
return name;
}
void VisualScriptInputAction::set_action_mode(Mode p_mode) {
if (mode == p_mode)
return;
mode = p_mode;
ports_changed_notify();
}
VisualScriptInputAction::Mode VisualScriptInputAction::get_action_mode() const {
return mode;
}
class VisualScriptNodeInstanceInputAction : public VisualScriptNodeInstance {
public:
VisualScriptInstance *instance;
StringName action;
VisualScriptInputAction::Mode mode;
int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override {
switch (mode) {
case VisualScriptInputAction::MODE_PRESSED: {
*p_outputs[0] = Input::get_singleton()->is_action_pressed(action);
} break;
case VisualScriptInputAction::MODE_RELEASED: {
*p_outputs[0] = !Input::get_singleton()->is_action_pressed(action);
} break;
case VisualScriptInputAction::MODE_JUST_PRESSED: {
*p_outputs[0] = Input::get_singleton()->is_action_just_pressed(action);
} break;
case VisualScriptInputAction::MODE_JUST_RELEASED: {
*p_outputs[0] = Input::get_singleton()->is_action_just_released(action);
} break;
}
return 0;
}
};
VisualScriptNodeInstance *VisualScriptInputAction::instance(VisualScriptInstance *p_instance) {
VisualScriptNodeInstanceInputAction *instance = memnew(VisualScriptNodeInstanceInputAction);
instance->instance = p_instance;
instance->action = name;
instance->mode = mode;
return instance;
}
void VisualScriptInputAction::_validate_property(PropertyInfo &property) const {
if (property.name != StringView("action"))
return;
property.hint = PropertyHint::Enum;
Vector<PropertyInfo> pinfo;
ProjectSettings::get_singleton()->get_property_list(&pinfo);
FixedVector<String,32,true> al;
for(const PropertyInfo &pi : pinfo) {
if (!StringUtils::begins_with(pi.name,"input/"))
continue;
String name(StringUtils::substr(pi.name,StringUtils::find(pi.name,"/") + 1));
al.push_back(name);
}
eastl::sort(al.begin(),al.end());
property.hint_string = String::joined(al,",");
}
void VisualScriptInputAction::_bind_methods() {
MethodBinder::bind_method(D_METHOD("set_action_name", {"name"}), &VisualScriptInputAction::set_action_name);
MethodBinder::bind_method(D_METHOD("get_action_name"), &VisualScriptInputAction::get_action_name);
MethodBinder::bind_method(D_METHOD("set_action_mode", {"mode"}), &VisualScriptInputAction::set_action_mode);
MethodBinder::bind_method(D_METHOD("get_action_mode"), &VisualScriptInputAction::get_action_mode);
ADD_PROPERTY(PropertyInfo(VariantType::STRING, "action"), "set_action_name", "get_action_name");
ADD_PROPERTY(PropertyInfo(VariantType::INT, "mode", PropertyHint::Enum, "Pressed,Released,JustPressed,JustReleased"), "set_action_mode", "get_action_mode");
BIND_ENUM_CONSTANT(MODE_PRESSED)
BIND_ENUM_CONSTANT(MODE_RELEASED)
BIND_ENUM_CONSTANT(MODE_JUST_PRESSED)
BIND_ENUM_CONSTANT(MODE_JUST_RELEASED)
}
VisualScriptInputAction::VisualScriptInputAction() {
name = "";
mode = MODE_PRESSED;
}
//////////////////////////////////////////
////////////////Constructor///////////
//////////////////////////////////////////
int VisualScriptDeconstruct::get_output_sequence_port_count() const {
return 0;
}
bool VisualScriptDeconstruct::has_input_sequence_port() const {
return false;
}
int VisualScriptDeconstruct::get_input_value_port_count() const {
return 1;
}
int VisualScriptDeconstruct::get_output_value_port_count() const {
return elements.size();
}
StringView VisualScriptDeconstruct::get_output_sequence_port_text(int p_port) const {
return StringView();
}
PropertyInfo VisualScriptDeconstruct::get_input_value_port_info(int p_idx) const {
return PropertyInfo(type, "value");
}
PropertyInfo VisualScriptDeconstruct::get_output_value_port_info(int p_idx) const {
return PropertyInfo(elements[p_idx].type, elements[p_idx].name);
}
StringView VisualScriptDeconstruct::get_caption() const {
thread_local char buf[512]="Deconstruct ";
strncat(buf,Variant::get_type_name(type),256);
return buf;
}
const char *VisualScriptDeconstruct::get_category() const {
return "functions";
}
void VisualScriptDeconstruct::_update_elements() {
elements.clear();
Variant v;
Callable::CallError ce;
v = Variant::construct(type, nullptr, 0, ce);
Vector<PropertyInfo> pinfo;
v.get_property_list(&pinfo);
for(const PropertyInfo & E : pinfo) {
Element e;
e.name = E.name;
e.type = E.type;
elements.push_back(e);
}
}
void VisualScriptDeconstruct::set_deconstruct_type(VariantType p_type) {
if (type == p_type)
return;
type = p_type;
_update_elements();
ports_changed_notify();
Object_change_notify(this); //to make input appear/disappear
}
VariantType VisualScriptDeconstruct::get_deconstruct_type() const {
return type;
}
void VisualScriptDeconstruct::_set_elem_cache(const Array &p_elements) {
ERR_FAIL_COND(p_elements.size() % 2 == 1);
elements.resize(p_elements.size() / 2);
for (int i = 0; i < elements.size(); i++) {
elements[i].name = p_elements[i * 2 + 0].as<StringName>();
elements[i].type = p_elements[i * 2 + 1].as<VariantType>();
}
}
Array VisualScriptDeconstruct::_get_elem_cache() const {
Array ret;
for (int i = 0; i < elements.size(); i++) {
ret.push_back(elements[i].name);
ret.push_back(elements[i].type);
}
return ret;
}
class VisualScriptNodeInstanceDeconstruct : public VisualScriptNodeInstance {
public:
VisualScriptInstance *instance;
Vector<StringName> outputs;
//virtual int get_working_memory_size() const { return 0; }
int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override {
Variant in = *p_inputs[0];
for (int i = 0; i < outputs.size(); i++) {
bool valid;
*p_outputs[i] = in.get(outputs[i], &valid);
if (!valid) {
r_error_str = "Can't obtain element '" + String(outputs[i]) + "' from " + Variant::get_type_name(in.get_type());
r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
return 0;
}
}
return 0;
}
};
VisualScriptNodeInstance *VisualScriptDeconstruct::instance(VisualScriptInstance *p_instance) {
VisualScriptNodeInstanceDeconstruct *instance = memnew(VisualScriptNodeInstanceDeconstruct);
instance->instance = p_instance;
instance->outputs.resize(elements.size());
for (int i = 0; i < elements.size(); i++) {
instance->outputs[i] = elements[i].name;
}
return instance;
}
void VisualScriptDeconstruct::_validate_property(PropertyInfo & /*property*/) const {
}
void VisualScriptDeconstruct::_bind_methods() {
MethodBinder::bind_method(D_METHOD("set_deconstruct_type", {"type"}), &VisualScriptDeconstruct::set_deconstruct_type);
MethodBinder::bind_method(D_METHOD("get_deconstruct_type"), &VisualScriptDeconstruct::get_deconstruct_type);
MethodBinder::bind_method(D_METHOD("_set_elem_cache", {"_cache"}), &VisualScriptDeconstruct::_set_elem_cache);
MethodBinder::bind_method(D_METHOD("_get_elem_cache"), &VisualScriptDeconstruct::_get_elem_cache);
char argt[7+(longest_variant_type_name+1)*(int)VariantType::VARIANT_MAX];
fill_with_all_variant_types("Any",argt);
ADD_PROPERTY(PropertyInfo(VariantType::INT, "type", PropertyHint::Enum, argt), "set_deconstruct_type", "get_deconstruct_type");
ADD_PROPERTY(PropertyInfo(VariantType::ARRAY, "elem_cache", PropertyHint::None, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL), "_set_elem_cache", "_get_elem_cache");
}
VisualScriptDeconstruct::VisualScriptDeconstruct() {
type = VariantType::NIL;
}
template <VariantType T>
static Ref<VisualScriptNode> create_node_deconst_typed(StringView /*p_name*/) {
Ref<VisualScriptDeconstruct> node(make_ref_counted<VisualScriptDeconstruct>());
node->set_deconstruct_type(T);
return node;
}
void register_visual_script_nodes() {
VisualScriptLanguage::singleton->add_register_func("data/set_variable", create_node_generic<VisualScriptVariableSet>);
VisualScriptLanguage::singleton->add_register_func("data/get_variable", create_node_generic<VisualScriptVariableGet>);
VisualScriptLanguage::singleton->add_register_func("data/engine_singleton", create_node_generic<VisualScriptEngineSingleton>);
VisualScriptLanguage::singleton->add_register_func("data/scene_node", create_node_generic<VisualScriptSceneNode>);
VisualScriptLanguage::singleton->add_register_func("data/scene_tree", create_node_generic<VisualScriptSceneTree>);
VisualScriptLanguage::singleton->add_register_func("data/resource_path", create_node_generic<VisualScriptResourcePath>);
VisualScriptLanguage::singleton->add_register_func("data/self", create_node_generic<VisualScriptSelf>);
VisualScriptLanguage::singleton->add_register_func("data/comment", create_node_generic<VisualScriptComment>);
VisualScriptLanguage::singleton->add_register_func("data/get_local_variable", create_node_generic<VisualScriptLocalVar>);
VisualScriptLanguage::singleton->add_register_func("data/set_local_variable", create_node_generic<VisualScriptLocalVarSet>);
VisualScriptLanguage::singleton->add_register_func("data/preload", create_node_generic<VisualScriptPreload>);
VisualScriptLanguage::singleton->add_register_func("data/action", create_node_generic<VisualScriptInputAction>);
VisualScriptLanguage::singleton->add_register_func("constants/constant", create_node_generic<VisualScriptConstant>);
VisualScriptLanguage::singleton->add_register_func("constants/math_constant", create_node_generic<VisualScriptMathConstant>);
VisualScriptLanguage::singleton->add_register_func("constants/class_constant", create_node_generic<VisualScriptClassConstant>);
VisualScriptLanguage::singleton->add_register_func("constants/global_constant", create_node_generic<VisualScriptGlobalConstant>);
VisualScriptLanguage::singleton->add_register_func("constants/basic_type_constant", create_node_generic<VisualScriptBasicTypeConstant>);
VisualScriptLanguage::singleton->add_register_func("custom/custom_node", create_node_generic<VisualScriptCustomNode>);
VisualScriptLanguage::singleton->add_register_func("custom/sub_call", create_node_generic<VisualScriptSubCall>);
VisualScriptLanguage::singleton->add_register_func("index/get_index", create_node_generic<VisualScriptIndexGet>);
VisualScriptLanguage::singleton->add_register_func("index/set_index", create_node_generic<VisualScriptIndexSet>);
VisualScriptLanguage::singleton->add_register_func("operators/compare/equal", create_op_node<Variant::OP_EQUAL>);
VisualScriptLanguage::singleton->add_register_func("operators/compare/not_equal", create_op_node<Variant::OP_NOT_EQUAL>);
VisualScriptLanguage::singleton->add_register_func("operators/compare/less", create_op_node<Variant::OP_LESS>);
VisualScriptLanguage::singleton->add_register_func("operators/compare/less_equal", create_op_node<Variant::OP_LESS_EQUAL>);
VisualScriptLanguage::singleton->add_register_func("operators/compare/greater", create_op_node<Variant::OP_GREATER>);
VisualScriptLanguage::singleton->add_register_func("operators/compare/greater_equal", create_op_node<Variant::OP_GREATER_EQUAL>);
//mathematic
VisualScriptLanguage::singleton->add_register_func("operators/math/add", create_op_node<Variant::OP_ADD>);
VisualScriptLanguage::singleton->add_register_func("operators/math/subtract", create_op_node<Variant::OP_SUBTRACT>);
VisualScriptLanguage::singleton->add_register_func("operators/math/multiply", create_op_node<Variant::OP_MULTIPLY>);
VisualScriptLanguage::singleton->add_register_func("operators/math/divide", create_op_node<Variant::OP_DIVIDE>);
VisualScriptLanguage::singleton->add_register_func("operators/math/negate", create_op_node<Variant::OP_NEGATE>);
VisualScriptLanguage::singleton->add_register_func("operators/math/positive", create_op_node<Variant::OP_POSITIVE>);
VisualScriptLanguage::singleton->add_register_func("operators/math/remainder", create_op_node<Variant::OP_MODULE>);
VisualScriptLanguage::singleton->add_register_func("operators/math/string_concat", create_op_node<Variant::OP_STRING_CONCAT>);
//bitwise
VisualScriptLanguage::singleton->add_register_func("operators/bitwise/shift_left", create_op_node<Variant::OP_SHIFT_LEFT>);
VisualScriptLanguage::singleton->add_register_func("operators/bitwise/shift_right", create_op_node<Variant::OP_SHIFT_RIGHT>);
VisualScriptLanguage::singleton->add_register_func("operators/bitwise/bit_and", create_op_node<Variant::OP_BIT_AND>);
VisualScriptLanguage::singleton->add_register_func("operators/bitwise/bit_or", create_op_node<Variant::OP_BIT_OR>);
VisualScriptLanguage::singleton->add_register_func("operators/bitwise/bit_xor", create_op_node<Variant::OP_BIT_XOR>);
VisualScriptLanguage::singleton->add_register_func("operators/bitwise/bit_negate", create_op_node<Variant::OP_BIT_NEGATE>);
//logic
VisualScriptLanguage::singleton->add_register_func("operators/logic/and", create_op_node<Variant::OP_AND>);
VisualScriptLanguage::singleton->add_register_func("operators/logic/or", create_op_node<Variant::OP_OR>);
VisualScriptLanguage::singleton->add_register_func("operators/logic/xor", create_op_node<Variant::OP_XOR>);
VisualScriptLanguage::singleton->add_register_func("operators/logic/not", create_op_node<Variant::OP_NOT>);
VisualScriptLanguage::singleton->add_register_func("operators/logic/in", create_op_node<Variant::OP_IN>);
VisualScriptLanguage::singleton->add_register_func("operators/logic/select", create_node_generic<VisualScriptSelect>);
String deconstruct_prefix("functions/deconstruct/");
VisualScriptLanguage::singleton->add_register_func(deconstruct_prefix + Variant::get_type_name(VariantType::VECTOR2), create_node_deconst_typed<VariantType::VECTOR2>);
VisualScriptLanguage::singleton->add_register_func(deconstruct_prefix + Variant::get_type_name(VariantType::VECTOR3), create_node_deconst_typed<VariantType::VECTOR3>);
VisualScriptLanguage::singleton->add_register_func(deconstruct_prefix + Variant::get_type_name(VariantType::COLOR), create_node_deconst_typed<VariantType::COLOR>);
VisualScriptLanguage::singleton->add_register_func(deconstruct_prefix + Variant::get_type_name(VariantType::RECT2), create_node_deconst_typed<VariantType::RECT2>);
VisualScriptLanguage::singleton->add_register_func(deconstruct_prefix + Variant::get_type_name(VariantType::TRANSFORM2D), create_node_deconst_typed<VariantType::TRANSFORM2D>);
VisualScriptLanguage::singleton->add_register_func(deconstruct_prefix + Variant::get_type_name(VariantType::PLANE), create_node_deconst_typed<VariantType::PLANE>);
VisualScriptLanguage::singleton->add_register_func(deconstruct_prefix + Variant::get_type_name(VariantType::QUAT), create_node_deconst_typed<VariantType::QUAT>);
VisualScriptLanguage::singleton->add_register_func(deconstruct_prefix + Variant::get_type_name(VariantType::AABB), create_node_deconst_typed<VariantType::AABB>);
VisualScriptLanguage::singleton->add_register_func(deconstruct_prefix + Variant::get_type_name(VariantType::BASIS), create_node_deconst_typed<VariantType::BASIS>);
VisualScriptLanguage::singleton->add_register_func(deconstruct_prefix + Variant::get_type_name(VariantType::TRANSFORM), create_node_deconst_typed<VariantType::TRANSFORM>);
VisualScriptLanguage::singleton->add_register_func("functions/compose_array", create_node_generic<VisualScriptComposeArray>);
for (int i = 1; i < (int)VariantType::VARIANT_MAX; i++) {
Vector<MethodInfo> constructors;
Variant::get_constructor_list(VariantType(i), &constructors);
for (const MethodInfo &E : constructors) {
if (!E.arguments.empty()) {
String name = FormatVE("functions/constructors/%s(",Variant::get_type_name(VariantType(i)));
for (size_t j = 0; j < E.arguments.size(); j++) {
if (j > 0) {
name += ", ";
}
if (E.arguments.size() == 1) {
name += Variant::get_type_name(E.arguments[j].type);
} else {
name += E.arguments[j].name.asCString();
}
}
name += ")";
VisualScriptLanguage::singleton->add_register_func(name, create_constructor_node);
Pair<VariantType, MethodInfo> pair;
pair.first = VariantType(i);
pair.second = E;
constructor_map[name] = pair;
}
}
}
}
void unregister_visual_script_nodes() {
constructor_map.clear();
}
| 30.791412 | 209 | 0.686116 | ZopharShinta |
c5f20d70f2335d0ddb3a93c5de9954735850173d | 817 | cpp | C++ | abc/249d.cpp | wky32768/Atcoder | b816b8de922b5bcd59881d808ea0f98148c07311 | [
"MIT"
] | null | null | null | abc/249d.cpp | wky32768/Atcoder | b816b8de922b5bcd59881d808ea0f98148c07311 | [
"MIT"
] | null | null | null | abc/249d.cpp | wky32768/Atcoder | b816b8de922b5bcd59881d808ea0f98148c07311 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <map>
#define int long long
#define For(i,a,b) for(int i=a;i<=b;i++)
using namespace std;
const int N=200005;
int n, ans, mx, a[N];
map <int, int> mp;
signed main() {
cin>>n;
For(i,1,n) {
cin>>a[i];
mp[a[i]]++;
mx=max(mx, a[i]);
}
For(i,1,mx) if(mp[i]) {
For(j,1,sqrt(i)) if(i%j==0) if(mp[j] && mp[i/j]) {
// ans+=mp[i]*mp[j]*mp[i/j]*2;
if(i==j && j==1/j) ans+=mp[i]*mp[j]*mp[i/j];
else if(j==1) ans+=mp[j]*mp[i]*mp[i]*2;
else if(j==i/j) ans+=mp[i]*mp[j]*mp[j];
else ans+=mp[i]*mp[j]*mp[i/j]*2;
// cout<<i<<" "<<j<<" "<<i/j<<" "<<ans<<'\n';
}
}
cout<<ans<<'\n';
return 0;
} | 25.53125 | 58 | 0.451652 | wky32768 |
c5f4f2b247ca2257eb82f43f8abda37882412ddd | 720 | cpp | C++ | src/121.BestTimetoBuyandSellStock/121.cpp | Taowyoo/LeetCodeLog | cb05798538dd10675bf81011a419d0e33d85e4e0 | [
"MIT"
] | null | null | null | src/121.BestTimetoBuyandSellStock/121.cpp | Taowyoo/LeetCodeLog | cb05798538dd10675bf81011a419d0e33d85e4e0 | [
"MIT"
] | null | null | null | src/121.BestTimetoBuyandSellStock/121.cpp | Taowyoo/LeetCodeLog | cb05798538dd10675bf81011a419d0e33d85e4e0 | [
"MIT"
] | null | null | null | /*
* @Author: Nick Cao
* @Date: 2021-06-06 11:02:12
* @LastEditTime: 2021-06-06 12:00:48
* @LastEditors: Nick Cao
* @Description:
* @FilePath: \LeetCodeLog\src\121. Best Time to Buy and Sell Stock\121.cpp
*/
class Solution {
public:
int maxProfit(vector<int>& prices) {
int buy_idx = 0;
int profit = 0;
for(int i = 1; i < prices.size(); ++i){
// check lower timing to buy
if(prices[i] < prices[buy_idx]){
buy_idx = i;
} else if(prices[i] - prices[buy_idx] > profit){ // Update profit when meet higher price
profit = prices[i] - prices[buy_idx];
}
}
return profit;
}
}; | 27.692308 | 102 | 0.529167 | Taowyoo |
c5f571fc1d2c45774dbe0bf7ed14da3749be378d | 1,258 | cpp | C++ | lldb/test/Shell/Register/Inputs/x86-multithread-read.cpp | mkinsner/llvm | 589d48844edb12cd357b3024248b93d64b6760bf | [
"Apache-2.0"
] | 2,338 | 2018-06-19T17:34:51.000Z | 2022-03-31T11:00:37.000Z | lldb/test/Shell/Register/Inputs/x86-multithread-read.cpp | mkinsner/llvm | 589d48844edb12cd357b3024248b93d64b6760bf | [
"Apache-2.0"
] | 3,740 | 2019-01-23T15:36:48.000Z | 2022-03-31T22:01:13.000Z | lldb/test/Shell/Register/Inputs/x86-multithread-read.cpp | mkinsner/llvm | 589d48844edb12cd357b3024248b93d64b6760bf | [
"Apache-2.0"
] | 500 | 2019-01-23T07:49:22.000Z | 2022-03-30T02:59:37.000Z | #include <cstdint>
#include <mutex>
#include <thread>
std::mutex t1_mutex, t2_mutex;
struct test_data {
uint32_t eax;
uint32_t ebx;
struct alignas(16) {
uint64_t mantissa;
uint16_t sign_exp;
} st0;
};
void t_func(std::mutex &t_mutex, const test_data &t_data) {
std::lock_guard<std::mutex> t_lock(t_mutex);
asm volatile(
"finit\t\n"
"fldt %2\t\n"
"int3\n\t"
:
: "a"(t_data.eax), "b"(t_data.ebx), "m"(t_data.st0)
: "st"
);
}
int main() {
test_data t1_data = {
.eax = 0x05060708,
.ebx = 0x15161718,
.st0 = {0x8070605040302010, 0x4000},
};
test_data t2_data = {
.eax = 0x25262728,
.ebx = 0x35363738,
.st0 = {0x8171615141312111, 0xc000},
};
// block both threads from proceeding
std::unique_lock<std::mutex> m1_lock(t1_mutex);
std::unique_lock<std::mutex> m2_lock(t2_mutex);
// start both threads
std::thread t1(t_func, std::ref(t1_mutex), std::ref(t1_data));
std::thread t2(t_func, std::ref(t2_mutex), std::ref(t2_data));
// release lock on thread 1 to make it interrupt the program
m1_lock.unlock();
// wait for thread 1 to finish
t1.join();
// release lock on thread 2
m2_lock.unlock();
// wait for thread 2 to finish
t2.join();
return 0;
}
| 20.290323 | 64 | 0.636725 | mkinsner |
c5f575f144f8d8537c2a7e8c8b6b235525c2f225 | 4,450 | cpp | C++ | src/mongo/db/catalog/commit_quorum_options.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/mongo/db/catalog/commit_quorum_options.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/mongo/db/catalog/commit_quorum_options.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (C) 2019-present MongoDB, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* 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
* Server Side Public License for more details.
*
* You should have received a copy of the Server Side Public License
* along with this program. If not, see
* <http://www.mongodb.com/licensing/server-side-public-license>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the Server Side Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#include "mongo/platform/basic.h"
#include "mongo/db/catalog/commit_quorum_options.h"
#include "mongo/base/status.h"
#include "mongo/base/string_data.h"
#include "mongo/bson/util/bson_extract.h"
#include "mongo/db/field_parser.h"
#include "mongo/db/repl/repl_set_config.h"
#include "mongo/util/str.h"
namespace mongo {
const StringData CommitQuorumOptions::kCommitQuorumField = "commitQuorum"_sd;
const char CommitQuorumOptions::kMajority[] = "majority";
const char CommitQuorumOptions::kVotingMembers[] = "votingMembers";
const BSONObj CommitQuorumOptions::Majority(BSON(kCommitQuorumField
<< CommitQuorumOptions::kMajority));
const BSONObj CommitQuorumOptions::VotingMembers(BSON(kCommitQuorumField
<< CommitQuorumOptions::kVotingMembers));
CommitQuorumOptions::CommitQuorumOptions(int numNodesOpts) {
reset();
numNodes = numNodesOpts;
invariant(numNodes >= 0 &&
numNodes <= static_cast<decltype(numNodes)>(repl::ReplSetConfig::kMaxMembers));
}
CommitQuorumOptions::CommitQuorumOptions(const std::string& modeOpts) {
reset();
mode = modeOpts;
invariant(!mode.empty());
}
Status CommitQuorumOptions::parse(const BSONElement& commitQuorumElement) {
reset();
if (commitQuorumElement.isNumber()) {
auto cNumNodes = commitQuorumElement.safeNumberLong();
if (cNumNodes < 0 ||
cNumNodes > static_cast<decltype(cNumNodes)>(repl::ReplSetConfig::kMaxMembers)) {
return Status(
ErrorCodes::FailedToParse,
str::stream()
<< "commitQuorum has to be a non-negative number and not greater than "
<< repl::ReplSetConfig::kMaxMembers);
}
numNodes = static_cast<decltype(numNodes)>(cNumNodes);
} else if (commitQuorumElement.type() == String) {
mode = commitQuorumElement.str();
if (mode.empty()) {
return Status(ErrorCodes::FailedToParse,
str::stream() << "commitQuorum can't be an empty string");
}
} else {
return Status(ErrorCodes::FailedToParse, "commitQuorum has to be a number or a string");
}
return Status::OK();
}
CommitQuorumOptions CommitQuorumOptions::deserializerForIDL(
const BSONElement& commitQuorumElement) {
CommitQuorumOptions commitQuorumOptions;
uassertStatusOK(commitQuorumOptions.parse(commitQuorumElement));
return commitQuorumOptions;
}
BSONObj CommitQuorumOptions::toBSON() const {
BSONObjBuilder builder;
appendToBuilder(kCommitQuorumField, &builder);
return builder.obj();
}
void CommitQuorumOptions::appendToBuilder(StringData fieldName, BSONObjBuilder* builder) const {
if (mode.empty()) {
builder->append(fieldName, numNodes);
} else {
builder->append(fieldName, mode);
}
}
} // namespace mongo
| 39.035088 | 96 | 0.689213 | benety |
c5f9411338a09e257face1d14db19a463987269b | 3,679 | cpp | C++ | errors/errorhandler.cpp | buelowp/aquarium | 6d379469fbfe2a8c12631bc5571c76d3c0d9d84a | [
"MIT"
] | 3 | 2017-05-04T08:14:46.000Z | 2020-04-21T12:17:08.000Z | errors/errorhandler.cpp | buelowp/aquarium | 6d379469fbfe2a8c12631bc5571c76d3c0d9d84a | [
"MIT"
] | 12 | 2019-08-17T20:49:35.000Z | 2020-04-22T00:46:17.000Z | errors/errorhandler.cpp | buelowp/aquarium | 6d379469fbfe2a8c12631bc5571c76d3c0d9d84a | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2020 <copyright holder> <email>
*
* 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 "errorhandler.h"
/**
* \fn ErrorHandler::ErrorHandler()
*
* Set m_handle to 100 because we want to reserve some values
* for static assignment, these would be known errors
*/
ErrorHandler::ErrorHandler()
{
m_storedErrors = 0;
m_handle = 100;
}
ErrorHandler::~ErrorHandler()
{
}
unsigned int ErrorHandler::critical(std::string msg, mqtt::async_client *client, int timeout, int handle)
{
if (handle > 0)
m_handle = handle;
else
m_handle++;
Critical err(m_handle, msg, client, timeout);
err.activate();
digitalWrite(Configuration::instance()->m_greenLed, 0);
m_criticals[m_handle] = err;
m_storedErrors++;
return m_handle;
}
unsigned int ErrorHandler::fatal(std::string msg, mqtt::async_client *client, int handle)
{
if (handle > 0)
m_handle = handle;
else
m_handle++;
Fatal err(m_handle, msg, client);
err.activate();
digitalWrite(Configuration::instance()->m_greenLed, 0);
m_fatals[m_handle] = err;
m_storedErrors++;
return m_handle;
}
unsigned int ErrorHandler::warning(std::string msg, mqtt::async_client *client, int timeout, int handle)
{
if (handle > 0)
m_handle = handle;
else
m_handle++;
Warning err(m_handle, msg, client, timeout);
err.activate();
digitalWrite(Configuration::instance()->m_greenLed, 0);
m_warnings[m_handle] = err;
m_storedErrors++;
return m_handle;
}
void ErrorHandler::clearCritical(unsigned int handle)
{
auto search = m_criticals.find(handle);
if (search != m_criticals.end()) {
Critical err = search->second;
err.cancel();
m_criticals.erase(search);
m_storedErrors--;
}
if (m_criticals.size() == 0) {
if (m_warnings.size()) {
auto it = m_warnings.begin();
Warning err = it->second;
err.activate();
}
}
else {
auto it = m_criticals.begin();
Critical err = it->second;
err.activate();
}
if (m_storedErrors == 0) {
digitalWrite(Configuration::instance()->m_greenLed, 1);
}
}
void ErrorHandler::clearWarning(unsigned int handle)
{
auto search = m_warnings.find(handle);
if (search != m_warnings.end()) {
Warning err = search->second;
err.cancel();
m_warnings.erase(search);
m_storedErrors--;
}
if (m_storedErrors == 0) {
digitalWrite(Configuration::instance()->m_greenLed, 1);
}
}
| 27.251852 | 105 | 0.654797 | buelowp |
c5f99647d63a209ee39e8ffd30f8ef6eaf2acb46 | 1,177 | cpp | C++ | learncpp_com/6-arr_string_pointer_references/142-array_loops/main.cpp | mitsiu-carreno/cpp_tutorial | 71f9083884ae6aa23774c044c3d08be273b6bb8e | [
"MIT"
] | null | null | null | learncpp_com/6-arr_string_pointer_references/142-array_loops/main.cpp | mitsiu-carreno/cpp_tutorial | 71f9083884ae6aa23774c044c3d08be273b6bb8e | [
"MIT"
] | null | null | null | learncpp_com/6-arr_string_pointer_references/142-array_loops/main.cpp | mitsiu-carreno/cpp_tutorial | 71f9083884ae6aa23774c044c3d08be273b6bb8e | [
"MIT"
] | null | null | null | #include <iostream>
int main()
{
int testScore[] ={88, 75, 98, 80, 93};
// Get the average score without loops
double noLoopTotalScore = testScore[0] + testScore[1] + testScore[2] + testScore[3] + testScore[4];
double noLoopAverageScore = noLoopTotalScore / (sizeof(testScore) / sizeof(testScore[0]));
std::cout << "The average score is: " << noLoopAverageScore << "\n";
// Get the average score WITH loops
int totalElements = sizeof(testScore) / sizeof(testScore[0]);
double sumScores = 0;
int bestScore = 0;
for(int count = 0; count < totalElements; ++count)
{
sumScores += testScore[count];
if(testScore[count] > bestScore)
{
bestScore = testScore[count];
}
}
std::cout << "The average score (with loops) is: " << sumScores / totalElements << "\n";
std::cout << "And the best score was: " << bestScore << "\n\n";
std::cout << "Loops are typically used with arrays to do one of three things:\n";
std::cout << "1) Calculate a value (e.g. average, total)\n";
std::cout << "2) Search of a value (e.g. highest, lowest)\n";
std::cout << "3) Reorganize the array (e.g. ascending, descending)\n";
return 0;
} | 31.810811 | 101 | 0.638063 | mitsiu-carreno |
c5fc885fb12759a1fcd7354a5edc3448e4c3a067 | 9,042 | cpp | C++ | GeneralFunctions/MUSEN/GeometryMotion.cpp | ElsevierSoftwareX/SOFTX-D-20-00025 | 24f10384f50d7e5fcebcc90fb27fb836c2fa6c73 | [
"BSD-3-Clause"
] | 2 | 2021-03-18T16:22:10.000Z | 2021-09-18T13:56:04.000Z | MUSEN/Modules/Geometries/GeometryMotion.cpp | LasCondes/musen | 18961807928285ff802e050050f4c627dd7bec1e | [
"BSD-3-Clause"
] | null | null | null | MUSEN/Modules/Geometries/GeometryMotion.cpp | LasCondes/musen | 18961807928285ff802e050050f4c627dd7bec1e | [
"BSD-3-Clause"
] | 3 | 2020-11-22T19:17:06.000Z | 2021-12-03T14:21:18.000Z | /* Copyright (c) 2013-2020, MUSEN Development Team. All rights reserved.
This file is part of MUSEN framework http://msolids.net/musen.
See LICENSE file for license and warranty information. */
#include "GeometryMotion.h"
#include "MixedFunctions.h"
#include "ProtoFunctions.h"
// TODO: sort time-dependent motion intervals
CGeometryMotion::EMotionType CGeometryMotion::MotionType() const
{
return m_motionType;
}
void CGeometryMotion::SetMotionType(EMotionType _type)
{
m_motionType = _type;
}
void CGeometryMotion::AddInterval()
{
switch (m_motionType)
{
case EMotionType::NONE: break;
case EMotionType::TIME_DEPENDENT: AddTimeInterval(); break;
case EMotionType::FORCE_DEPENDENT: AddForceInterval(); break;
}
}
void CGeometryMotion::AddTimeInterval()
{
if (m_intervalsTime.empty())
AddTimeInterval({ 0.0, 1.0, SMotionInfo{} });
else
AddTimeInterval({ m_intervalsTime.back().timeEnd, m_intervalsTime.back().timeEnd + 1.0, SMotionInfo{} });
}
void CGeometryMotion::AddTimeInterval(const STimeMotionInterval& _interval)
{
m_intervalsTime.push_back(_interval);
}
void CGeometryMotion::ChangeTimeInterval(size_t _index, const STimeMotionInterval& _interval)
{
if (_index < m_intervalsTime.size())
m_intervalsTime[_index] = _interval;
}
CGeometryMotion::STimeMotionInterval CGeometryMotion::GetTimeInterval(size_t _index) const
{
if (_index < m_intervalsTime.size())
return m_intervalsTime[_index];
return {};
}
std::vector<CGeometryMotion::STimeMotionInterval> CGeometryMotion::GetTimeIntervals() const
{
return m_intervalsTime;
}
void CGeometryMotion::AddForceInterval()
{
if (m_intervalsForce.empty())
AddForceInterval({ 1.0, SForceMotionInterval::ELimitType::MAX, SMotionInfo{} });
else
AddForceInterval({ m_intervalsForce.back().forceLimit, m_intervalsForce.back().limitType, SMotionInfo{} });
}
void CGeometryMotion::AddForceInterval(const SForceMotionInterval& _interval)
{
m_intervalsForce.push_back(_interval);
}
void CGeometryMotion::ChangeForceInterval(size_t _index, const SForceMotionInterval& _interval)
{
if (_index < m_intervalsForce.size())
m_intervalsForce[_index] = _interval;
}
CGeometryMotion::SForceMotionInterval CGeometryMotion::GetForceInterval(size_t _index) const
{
if (_index < m_intervalsForce.size())
return m_intervalsForce[_index];
return {};
}
std::vector<CGeometryMotion::SForceMotionInterval> CGeometryMotion::GetForceIntervals() const
{
return m_intervalsForce;
}
void CGeometryMotion::DeleteInterval(size_t _index)
{
switch (m_motionType)
{
case EMotionType::TIME_DEPENDENT:
if (_index < m_intervalsTime.size())
m_intervalsTime.erase(m_intervalsTime.begin() + _index);
break;
case EMotionType::FORCE_DEPENDENT:
if (_index < m_intervalsForce.size())
m_intervalsForce.erase(m_intervalsForce.begin() + _index);
break;
case EMotionType::NONE: break;
}
}
void CGeometryMotion::MoveIntervalUp(size_t _index)
{
switch (m_motionType)
{
case EMotionType::TIME_DEPENDENT:
if (_index < m_intervalsTime.size() && _index != 0)
std::iter_swap(m_intervalsTime.begin() + _index, m_intervalsTime.begin() + _index - 1);
break;
case EMotionType::FORCE_DEPENDENT:
if (_index < m_intervalsForce.size() && _index != 0)
std::iter_swap(m_intervalsForce.begin() + _index, m_intervalsForce.begin() + _index - 1);
break;
case EMotionType::NONE: break;
}
}
void CGeometryMotion::MoveIntervalDown(size_t _index)
{
switch (m_motionType)
{
case EMotionType::TIME_DEPENDENT:
if (_index < m_intervalsTime.size() && _index != m_intervalsTime.size() - 1)
std::iter_swap(m_intervalsTime.begin() + _index, m_intervalsTime.begin() + _index + 1);
break;
case EMotionType::FORCE_DEPENDENT:
if (_index < m_intervalsForce.size() && _index != m_intervalsForce.size() - 1)
std::iter_swap(m_intervalsForce.begin() + _index, m_intervalsForce.begin() + _index + 1);
break;
case EMotionType::NONE: break;
}
}
bool CGeometryMotion::HasMotion() const
{
return !m_intervalsTime.empty() || !m_intervalsForce.empty();
}
void CGeometryMotion::Clear()
{
m_intervalsTime.clear();
m_intervalsForce.clear();
}
bool CGeometryMotion::IsValid() const
{
switch (m_motionType)
{
case EMotionType::TIME_DEPENDENT:
if (m_intervalsTime.empty())
{
m_errorMessage = "Time-dependent movement is selected, but time intervals are not specified.";
return false;
}
break;
case EMotionType::FORCE_DEPENDENT:
if (m_intervalsForce.empty())
{
m_errorMessage = "Force-dependent movement is selected, but force intervals are not specified.";
return false;
}
break;
case EMotionType::NONE: break;
}
m_errorMessage.clear();
return true;
}
std::string CGeometryMotion::ErrorMessage() const
{
return m_errorMessage;
}
void CGeometryMotion::UpdateMotionInfo(double _dependentValue)
{
switch (m_motionType)
{
case EMotionType::TIME_DEPENDENT:
{
bool found = false; // is needed to accelerate updating
const size_t iStart = m_iMotion == static_cast<size_t>(-1) ? 0 : m_iMotion;
for (size_t i = iStart; i < m_intervalsTime.size() && !found; ++i) // search starting from the current
if (m_intervalsTime[i].timeBeg <= _dependentValue && _dependentValue <= m_intervalsTime[i].timeEnd) // the value is in interval
{
found = true;
if (m_iMotion != i) // it is a new interval - update current values
{
m_iMotion = i;
m_currentMotion = m_intervalsTime[i].motion;
}
}
if (!found) // such interval does not exist
m_currentMotion.Clear(); // set current velocities to zero
break;
}
case EMotionType::FORCE_DEPENDENT:
{
if (m_iMotion == static_cast<size_t>(-1)) // initialize
{
m_iMotion = 0;
m_currentMotion = m_intervalsForce[m_iMotion].motion;
}
if (m_iMotion >= m_intervalsForce.size()) // no intervals defined
{
m_currentMotion.Clear(); // set current velocities to zero
break;
}
bool updated = false; // is needed to accelerate updating
switch (m_intervalsForce[m_iMotion].limitType)
{
case SForceMotionInterval::ELimitType::MIN: if (_dependentValue < m_intervalsForce[m_iMotion].forceLimit) { ++m_iMotion; updated = true; } break;
case SForceMotionInterval::ELimitType::MAX: if (_dependentValue > m_intervalsForce[m_iMotion].forceLimit) { ++m_iMotion; updated = true; } break;
}
if (updated) // it is a new interval - update current values
m_currentMotion = m_intervalsForce[m_iMotion].motion;
break;
}
case EMotionType::NONE: break;
}
}
void CGeometryMotion::ResetMotionInfo()
{
m_iMotion = -1;
m_currentMotion.Clear();
}
CGeometryMotion::SMotionInfo CGeometryMotion::GetCurrentMotion() const
{
return m_currentMotion;
}
CVector3 CGeometryMotion::TimeDependentShift(double _time) const
{
if (m_motionType != EMotionType::TIME_DEPENDENT) return CVector3{ 0.0 };
CVector3 shift{ 0 };
for (const auto& interval : m_intervalsTime)
if (_time > interval.timeBeg)
shift += (std::min(interval.timeEnd, _time) - interval.timeBeg) * interval.motion.velocity;
return shift;
}
void CGeometryMotion::LoadFromProto(const ProtoGeometryMotion& _proto)
{
m_motionType = static_cast<EMotionType>(_proto.type());
switch (m_motionType)
{
case EMotionType::TIME_DEPENDENT:
for (const auto& interval : _proto.intervals())
AddTimeInterval({ interval.limit1(), interval.limit2(),
SMotionInfo{Proto2Val(interval.velocity()), Proto2Val(interval.rot_velocity()), Proto2Val(interval.rot_center())} });
break;
case EMotionType::FORCE_DEPENDENT:
for (const auto& interval : _proto.intervals())
AddForceInterval({ interval.limit1(), static_cast<SForceMotionInterval::ELimitType>(interval.limit_type()),
SMotionInfo{Proto2Val(interval.velocity()), Proto2Val(interval.rot_velocity()), Proto2Val(interval.rot_center())} });
break;
case EMotionType::NONE: break;
}
}
void CGeometryMotion::SaveToProto(ProtoGeometryMotion& _proto) const
{
_proto.set_version(0);
_proto.set_type(E2I(m_motionType));
_proto.clear_intervals();
switch (m_motionType)
{
case EMotionType::TIME_DEPENDENT:
for (const auto& interval : m_intervalsTime)
{
auto* protoInterval = _proto.add_intervals();
protoInterval->set_limit1(interval.timeBeg);
protoInterval->set_limit2(interval.timeEnd);
Val2Proto(protoInterval->mutable_velocity(), interval.motion.velocity);
Val2Proto(protoInterval->mutable_rot_velocity(), interval.motion.rotationVelocity);
Val2Proto(protoInterval->mutable_rot_center(), interval.motion.rotationCenter);
}
break;
case EMotionType::FORCE_DEPENDENT:
for (const auto& interval : m_intervalsForce)
{
auto* protoInterval = _proto.add_intervals();
protoInterval->set_limit1(interval.forceLimit);
protoInterval->set_limit_type(E2I(interval.limitType));
Val2Proto(protoInterval->mutable_velocity(), interval.motion.velocity);
Val2Proto(protoInterval->mutable_rot_velocity(), interval.motion.rotationVelocity);
Val2Proto(protoInterval->mutable_rot_center(), interval.motion.rotationCenter);
}
break;
case EMotionType::NONE: break;
}
}
| 29.54902 | 147 | 0.745521 | ElsevierSoftwareX |
c5ff0185e80f8e4451d6a8a1f35b9b8e8eef643c | 40 | cpp | C++ | lab4/Streamline/Streamline/Grid.cpp | trainsn/CSE_5194.02 | 645c132dfe9169e5bd140ce0410225780723d93b | [
"MIT"
] | null | null | null | lab4/Streamline/Streamline/Grid.cpp | trainsn/CSE_5194.02 | 645c132dfe9169e5bd140ce0410225780723d93b | [
"MIT"
] | null | null | null | lab4/Streamline/Streamline/Grid.cpp | trainsn/CSE_5194.02 | 645c132dfe9169e5bd140ce0410225780723d93b | [
"MIT"
] | null | null | null | #include "Grid.h"
Grid::~Grid()
{ }
| 5.714286 | 17 | 0.5 | trainsn |
68019d9f9622a364965e0e7bf99327e5a7522a96 | 21,223 | cpp | C++ | src/game/client/tf2/c_env_meteor.cpp | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | 6 | 2022-01-23T09:40:33.000Z | 2022-03-20T20:53:25.000Z | src/game/client/tf2/c_env_meteor.cpp | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | null | null | null | src/game/client/tf2/c_env_meteor.cpp | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | 1 | 2022-02-06T21:05:23.000Z | 2022-02-06T21:05:23.000Z | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include "cbase.h"
#include "C_Env_Meteor.h"
#include "fx_explosion.h"
#include "tempentity.h"
#include "c_tracer.h"
//=============================================================================
//
// Meteor Factory Functions
//
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void C_MeteorFactory::CreateMeteor( int nID, int iType,
const Vector &vecPosition, const Vector &vecDirection,
float flSpeed, float flStartTime, float flDamageRadius,
const Vector &vecTriggerMins, const Vector &vecTriggerMaxs )
{
C_EnvMeteor::Create( nID, iType, vecPosition, vecDirection, flSpeed, flStartTime, flDamageRadius,
vecTriggerMins, vecTriggerMaxs );
}
//=============================================================================
//
// Meteor Spawner Functions
//
void RecvProxy_MeteorTargetPositions( const CRecvProxyData *pData, void *pStruct, void *pOut )
{
CEnvMeteorSpawnerShared *pSpawner = ( CEnvMeteorSpawnerShared* )pStruct;
pSpawner->m_aTargets[pData->m_iElement].m_vecPosition.x = pData->m_Value.m_Vector[0];
pSpawner->m_aTargets[pData->m_iElement].m_vecPosition.y = pData->m_Value.m_Vector[1];
pSpawner->m_aTargets[pData->m_iElement].m_vecPosition.z = pData->m_Value.m_Vector[2];
}
void RecvProxy_MeteorTargetRadii( const CRecvProxyData *pData, void *pStruct, void *pOut )
{
CEnvMeteorSpawnerShared *pSpawner = ( CEnvMeteorSpawnerShared* )pStruct;
pSpawner->m_aTargets[pData->m_iElement].m_flRadius = pData->m_Value.m_Float;
}
void RecvProxyArrayLength_MeteorTargets( void *pStruct, int objectID, int currentArrayLength )
{
CEnvMeteorSpawnerShared *pSpawner = ( CEnvMeteorSpawnerShared* )pStruct;
if ( pSpawner->m_aTargets.Count() < currentArrayLength )
{
pSpawner->m_aTargets.SetSize( currentArrayLength );
}
}
BEGIN_RECV_TABLE_NOBASE( CEnvMeteorSpawnerShared, DT_EnvMeteorSpawnerShared )
// Setup (read from) Worldcraft.
RecvPropInt ( RECVINFO( m_iMeteorType ) ),
RecvPropInt ( RECVINFO( m_bSkybox ) ),
RecvPropFloat ( RECVINFO( m_flMinSpawnTime ) ),
RecvPropFloat ( RECVINFO( m_flMaxSpawnTime ) ),
RecvPropInt ( RECVINFO( m_nMinSpawnCount ) ),
RecvPropInt ( RECVINFO( m_nMaxSpawnCount ) ),
RecvPropFloat ( RECVINFO( m_flMinSpeed ) ),
RecvPropFloat ( RECVINFO( m_flMaxSpeed ) ),
// Setup through Init.
RecvPropFloat ( RECVINFO( m_flStartTime ) ),
RecvPropInt ( RECVINFO( m_nRandomSeed ) ),
RecvPropVector ( RECVINFO( m_vecMinBounds ) ),
RecvPropVector ( RECVINFO( m_vecMaxBounds ) ),
RecvPropVector ( RECVINFO( m_vecTriggerMins ) ),
RecvPropVector ( RECVINFO( m_vecTriggerMaxs ) ),
// Target List
RecvPropArray2( RecvProxyArrayLength_MeteorTargets,
RecvPropVector( "meteortargetposition_array_element", 0, 0, 0, RecvProxy_MeteorTargetPositions ),
16, 0, "meteortargetposition_array" ),
RecvPropArray2( RecvProxyArrayLength_MeteorTargets,
RecvPropFloat( "meteortargetradius_array_element", 0, 0, 0, RecvProxy_MeteorTargetRadii ),
16, 0, "meteortargetradius_array" )
END_RECV_TABLE()
// This table encodes the CBaseEntity data.
IMPLEMENT_CLIENTCLASS_DT( C_EnvMeteorSpawner, DT_EnvMeteorSpawner, CEnvMeteorSpawner )
RecvPropDataTable ( RECVINFO_DT( m_SpawnerShared ), 0, &REFERENCE_RECV_TABLE( DT_EnvMeteorSpawnerShared ) ),
RecvPropInt ( RECVINFO( m_fDisabled ) ),
END_RECV_TABLE()
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
C_EnvMeteorSpawner::C_EnvMeteorSpawner()
{
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void C_EnvMeteorSpawner::OnDataChanged( DataUpdateType_t updateType )
{
// Initialize the client side spawner.
m_SpawnerShared.Init( &m_Factory, m_SpawnerShared.m_nRandomSeed, m_SpawnerShared.m_flStartTime,
m_SpawnerShared.m_vecMinBounds, m_SpawnerShared.m_vecMaxBounds,
m_SpawnerShared.m_vecTriggerMins, m_SpawnerShared.m_vecTriggerMaxs );
// Set the next think to be the next spawn interval.
if ( !m_fDisabled )
{
SetNextClientThink( m_SpawnerShared.m_flNextSpawnTime );
}
}
#if 0
// Will probably be used later!!
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void C_EnvMeteorSpawner::ReceiveMessage( int classID, bf_read &msg )
{
if ( classID != GetClientClass()->m_ClassID )
{
// message is for subclass
BaseClass::ReceiveMessage( classID, msg );
return;
}
m_SpawnerShared.m_flStartTime = msg.ReadLong();
m_SpawnerShared.m_flNextSpawnTime = msg.ReadLong();
SetNextClientThink( m_SpawnerShared.m_flNextSpawnTime );
}
#endif
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void C_EnvMeteorSpawner::ClientThink( void )
{
SetNextClientThink( m_SpawnerShared.MeteorThink( gpGlobals->curtime ) );
}
//=============================================================================
//
// Meteor Tail Functions
//
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
C_EnvMeteorHead::C_EnvMeteorHead()
{
m_vecPos.Init();
m_vecPrevPos.Init();
m_flParticleScale = 1.0f;
m_pSmokeEmitter = NULL;
m_flSmokeSpawnInterval = 0.0f;
m_hSmokeMaterial = INVALID_MATERIAL_HANDLE;
m_flSmokeLifetime = 2.5f;
m_bEmitSmoke = true;
m_hFlareMaterial = INVALID_MATERIAL_HANDLE;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
C_EnvMeteorHead::~C_EnvMeteorHead()
{
Destroy();
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void C_EnvMeteorHead::Start( const Vector &vecOrigin, const Vector &vecDirection )
{
// Emitters.
m_pSmokeEmitter = CSimpleEmitter::Create( "MeteorTrail" );
// m_pFireEmitter = CSimpleEmitter::Create( "MeteorFire" );
if ( !m_pSmokeEmitter /*|| !m_pFireEmitter*/ )
return;
// Smoke
m_pSmokeEmitter->SetSortOrigin( vecOrigin );
m_hSmokeMaterial = m_pSmokeEmitter->GetPMaterial( "particle/SmokeStack" );
Assert( m_hSmokeMaterial != INVALID_MATERIAL_HANDLE );
// Fire
// m_pFireEmitter->SetSortOrigin( vecOrigin );
// m_hFireMaterial = m_pFireEmitter->GetPMaterial( "particle/particle_fire" );
// Assert( m_hFireMaterial != INVALID_MATERIAL_HANDLE );
// Flare
// m_hFlareMaterial = m_ParticleEffect.FindOrAddMaterial( "effects/redflare" );
VectorCopy( vecDirection, m_vecDirection );
VectorCopy( vecOrigin, m_vecPos );
m_bInitThink = true;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void C_EnvMeteorHead::Destroy( void )
{
m_pSmokeEmitter = NULL;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void C_EnvMeteorHead::MeteorHeadThink( const Vector &vecOrigin, float flTime )
{
if ( m_bInitThink )
{
VectorCopy( vecOrigin, m_vecPrevPos );
m_bInitThink = false;
}
// Update the position of the emitters.
VectorCopy( vecOrigin, m_vecPos );
// Update Smoke
if ( m_pSmokeEmitter.IsValid() && m_bEmitSmoke )
{
m_pSmokeEmitter->SetSortOrigin( m_vecPos );
// Get distance covered
Vector vecDelta;
VectorSubtract( m_vecPos, m_vecPrevPos, vecDelta );
float flLength = vecDelta.Length();
int nParticleCount = flLength / 35.0f;
if ( nParticleCount < 1 )
{
nParticleCount = 1;
}
flLength /= nParticleCount;
Vector vecPos;
for( int iParticle = 0; iParticle < nParticleCount; ++iParticle )
{
vecPos = m_vecPrevPos + ( m_vecDirection * ( flLength * iParticle ) );
// Add some noise to the position.
Vector vecPosOffset;
vecPosOffset.Random( -m_flSmokeSpawnRadius, m_flSmokeSpawnRadius );
VectorAdd( vecPosOffset, vecPos, vecPosOffset );
SimpleParticle *pParticle = ( SimpleParticle* )m_pSmokeEmitter->AddParticle( sizeof( SimpleParticle ),
m_hSmokeMaterial,
vecPosOffset );
if ( pParticle )
{
pParticle->m_flLifetime = 0.0f;
pParticle->m_flDieTime = m_flSmokeLifetime;
// Add just a little movement.
pParticle->m_vecVelocity.Random( -5.0f, 5.0f );
pParticle->m_uchColor[0] = 255.0f;
pParticle->m_uchColor[1] = 255.0f;
pParticle->m_uchColor[2] = 255.0f;
pParticle->m_uchStartSize = 70 * m_flParticleScale;
pParticle->m_uchEndSize = 25 * m_flParticleScale;
float flAlpha = random->RandomFloat( 0.5f, 1.0f );
pParticle->m_uchStartAlpha = flAlpha * 255;
pParticle->m_uchEndAlpha = 0;
pParticle->m_flRoll = random->RandomInt( 0, 360 );
pParticle->m_flRollDelta = random->RandomFloat( -1.0f, 1.0f );
}
}
}
// Update Fire
// if ( m_pFireEmitter && m_bEmitFire )
// {
// }
// Flare
// Save off position.
VectorCopy( m_vecPos, m_vecPrevPos );
}
//=============================================================================
//
// Meteor Tail Functions
//
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
C_EnvMeteorTail::C_EnvMeteorTail()
{
m_TailMaterialHandle = INVALID_MATERIAL_HANDLE;
m_pParticleMgr = NULL;
m_pParticle = NULL;
m_flFadeTime = 0.5f;
m_flWidth = 3.0f;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
C_EnvMeteorTail::~C_EnvMeteorTail()
{
Destroy();
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void C_EnvMeteorTail::Start( const Vector &vecOrigin, const Vector &vecDirection,
float flSpeed )
{
// Set the particle manager.
m_pParticleMgr = ParticleMgr();
m_pParticleMgr->AddEffect( &m_ParticleEffect, this );
m_TailMaterialHandle = m_ParticleEffect.FindOrAddMaterial( "particle/guidedplasmaprojectile" );
m_pParticle = m_ParticleEffect.AddParticle( sizeof( StandardParticle_t ), m_TailMaterialHandle );
if ( m_pParticle )
{
m_pParticle->m_Pos = vecOrigin;
}
VectorCopy( vecDirection, m_vecDirection );
m_flSpeed = flSpeed;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void C_EnvMeteorTail::Destroy( void )
{
if ( m_pParticleMgr )
{
m_pParticleMgr->RemoveEffect( &m_ParticleEffect );
m_pParticleMgr = NULL;
}
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void C_EnvMeteorTail::DrawFragment( ParticleDraw* pDraw,
const Vector &vecStart, const Vector &vecDelta,
const Vector4D &vecStartColor, const Vector4D &vecEndColor,
float flStartV, float flEndV )
{
if( !pDraw->GetMeshBuilder() )
return;
// Clip the fragment.
Vector vecVerts[4];
if ( !Tracer_ComputeVerts( vecStart, vecDelta, m_flWidth, vecVerts ) )
return;
// NOTE: Gotta get the winding right so it's not backface culled
// (we need to turn of backface culling for these bad boys)
CMeshBuilder* pMeshBuilder = pDraw->GetMeshBuilder();
pMeshBuilder->Position3f( vecVerts[0].x, vecVerts[0].y, vecVerts[0].z );
pMeshBuilder->TexCoord2f( 0, 0.0f, flStartV );
pMeshBuilder->Color4fv( vecStartColor.Base() );
pMeshBuilder->AdvanceVertex();
pMeshBuilder->Position3f( vecVerts[1].x, vecVerts[1].y, vecVerts[1].z );
pMeshBuilder->TexCoord2f( 0, 1.0f, flStartV );
pMeshBuilder->Color4fv( vecStartColor.Base() );
pMeshBuilder->AdvanceVertex();
pMeshBuilder->Position3f( vecVerts[3].x, vecVerts[3].y, vecVerts[3].z );
pMeshBuilder->TexCoord2f( 0, 1.0f, flEndV );
pMeshBuilder->Color4fv( vecEndColor.Base() );
pMeshBuilder->AdvanceVertex();
pMeshBuilder->Position3f( vecVerts[2].x, vecVerts[2].y, vecVerts[2].z );
pMeshBuilder->TexCoord2f( 0, 0.0f, flEndV );
pMeshBuilder->Color4fv( vecEndColor.Base() );
pMeshBuilder->AdvanceVertex();
}
void C_EnvMeteorTail::SimulateParticles( CParticleSimulateIterator *pIterator )
{
Particle *pParticle = (Particle*)pIterator->GetFirst();
while ( pParticle )
{
// Update the particle position.
pParticle->m_Pos = GetLocalOrigin();
pParticle = (Particle*)pIterator->GetNext();
}
}
void C_EnvMeteorTail::RenderParticles( CParticleRenderIterator *pIterator )
{
const Particle *pParticle = (const Particle *)pIterator->GetFirst();
while ( pParticle )
{
// Now draw the tail fragments...
Vector4D vecStartColor( 1.0f, 1.0f, 1.0f, 1.0f );
Vector4D vecEndColor( 1.0f, 1.0f, 1.0f, 0.0f );
Vector vecDelta, vecStartPos, vecEndPos;
// Calculate the tail.
Vector vecTailEnd;
vecTailEnd = GetLocalOrigin() + ( m_vecDirection * -m_flSpeed );
// Transform particles into camera space.
TransformParticle( m_pParticleMgr->GetModelView(), GetLocalOrigin(), vecStartPos );
TransformParticle( m_pParticleMgr->GetModelView(), vecTailEnd, vecEndPos );
float sortKey = vecStartPos.z;
// Draw the tail fragment.
VectorSubtract( vecStartPos, vecEndPos, vecDelta );
DrawFragment( pIterator->GetParticleDraw(), vecEndPos, vecDelta, vecEndColor, vecStartColor,
1.0f - vecEndColor[3], 1.0f - vecStartColor[3] );
pParticle = (const Particle *)pIterator->GetNext( sortKey );
}
}
//=============================================================================
//
// Meteor Functions
//
static g_MeteorCounter = 0;
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
C_EnvMeteor::C_EnvMeteor()
{
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
C_EnvMeteor::~C_EnvMeteor()
{
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void C_EnvMeteor::ClientThink( void )
{
// Get the current time.
float flTime = gpGlobals->curtime;
// Update the meteor.
if ( m_Meteor.IsInSkybox( flTime ) )
{
if ( m_Meteor.m_nLocation == METEOR_LOCATION_WORLD )
{
WorldToSkyboxThink( flTime );
}
else
{
SkyboxThink( flTime );
}
}
else
{
if ( m_Meteor.m_nLocation == METEOR_LOCATION_SKYBOX )
{
SkyboxToWorldThink( flTime );
}
else
{
WorldThink( flTime );
}
}
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void C_EnvMeteor::SkyboxThink( float flTime )
{
float flDeltaTime = flTime - m_Meteor.m_flStartTime;
if ( flDeltaTime > METEOR_MAX_LIFETIME )
{
Destroy( this );
return;
}
// Check to see if the object is passive or not - act accordingly!
if ( !m_Meteor.IsPassive( flTime ) )
{
// Update meteor position.
Vector origin;
m_Meteor.GetPositionAtTime( flTime, origin );
SetLocalOrigin( origin );
// Update the position of the tail effect.
m_TailEffect.SetLocalOrigin( GetLocalOrigin() );
m_HeadEffect.MeteorHeadThink( GetLocalOrigin(), flTime );
}
// Add the entity to the active list - update!
AddEntity();
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void C_EnvMeteor::WorldToSkyboxThink( float flTime )
{
// Move the meteor from the world into the skybox.
m_Meteor.ConvertFromWorldToSkybox();
// Destroy the head effect. Recreate it.
m_HeadEffect.Destroy();
m_HeadEffect.Start( m_Meteor.m_vecStartPosition, m_vecTravelDir );
m_HeadEffect.SetSmokeEmission( true );
m_HeadEffect.SetParticleScale( 1.0f / 16.0f );
m_HeadEffect.m_bInitThink = true;
// Update to world model.
SetModel( "models/props/common/meteorites/meteor05.mdl" );
// Update the meteor position (move into the skybox!)
SetLocalOrigin( m_Meteor.m_vecStartPosition );
// Update (think).
SkyboxThink( flTime );
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void C_EnvMeteor::SkyboxToWorldThink( float flTime )
{
// Move the meteor from the skybox into the world.
m_Meteor.ConvertFromSkyboxToWorld();
// Destroy the head effect. Recreate it.
m_HeadEffect.Destroy();
m_HeadEffect.Start( m_Meteor.m_vecStartPosition, m_vecTravelDir );
m_HeadEffect.SetSmokeEmission( true );
m_HeadEffect.SetParticleScale( 1.0f );
m_HeadEffect.m_bInitThink = true;
// Update to world model.
SetModel( "models/props/common/meteorites/meteor04.mdl" );
SetLocalOrigin( m_Meteor.m_vecStartPosition );
// Update (think).
WorldThink( flTime );
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void C_EnvMeteor::WorldThink( float flTime )
{
// Update meteor position.
Vector vecEndPosition;
m_Meteor.GetPositionAtTime( flTime, vecEndPosition );
// m_Meteor must return the end position in world space for the trace to work.
Assert( GetMoveParent() == NULL );
// Msg( "Client: Time = %lf, Position: %4.2f %4.2f %4.2f\n", flTime, vecEndPosition.x, vecEndPosition.y, vecEndPosition.z );
// Check to see if we struck the world. If so, cause an explosion.
trace_t trace;
Vector vecMin, vecMax;
GetRenderBounds( vecMin, vecMax );
// NOTE: This code works only if we aren't in hierarchy!!!
Assert( !GetMoveParent() );
CTraceFilterWorldOnly traceFilter;
UTIL_TraceHull( GetAbsOrigin(), vecEndPosition, vecMin, vecMax,
MASK_SOLID_BRUSHONLY, &traceFilter, &trace );
// Collision.
if ( ( trace.fraction < 1.0f ) && !( trace.surface.flags & SURF_SKY ) )
{
// Move up to the end.
Vector vecEnd = GetAbsOrigin() + ( ( vecEndPosition - GetAbsOrigin() ) * trace.fraction );
// Create an explosion effect!
BaseExplosionEffect().Create( vecEnd, 10, 32, TE_EXPLFLAG_NONE );
// Debugging Info!!!!
// debugoverlay->AddBoxOverlay( vecEnd, Vector( -10, -10, -10 ), Vector( 10, 10, 10 ), QAngle( 0.0f, 0.0f, 0.0f ), 255, 0, 0, 0, 100 );
Destroy( this );
return;
}
else
{
// Move to the end.
SetLocalOrigin( vecEndPosition );
}
m_TailEffect.SetLocalOrigin( GetLocalOrigin() );
m_HeadEffect.MeteorHeadThink( GetLocalOrigin(), flTime );
// Add the entity to the active list - update!
AddEntity();
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
C_EnvMeteor *C_EnvMeteor::Create( int nID, int iMeteorType, const Vector &vecOrigin,
const Vector &vecDirection, float flSpeed, float flStartTime,
float flDamageRadius,
const Vector &vecTriggerMins, const Vector &vecTriggerMaxs )
{
C_EnvMeteor *pMeteor = new C_EnvMeteor;
if ( pMeteor )
{
pMeteor->m_Meteor.Init( nID, flStartTime, METEOR_PASSIVE_TIME, vecOrigin, vecDirection, flSpeed, flDamageRadius,
vecTriggerMins, vecTriggerMaxs );
// Initialize the meteor.
pMeteor->InitializeAsClientEntity( "models/props/common/meteorites/meteor05.mdl", RENDER_GROUP_OPAQUE_ENTITY );
// Handle forward simulation.
if ( ( pMeteor->m_Meteor.m_flStartTime + METEOR_MAX_LIFETIME ) < gpGlobals->curtime )
{
Destroy( pMeteor );
}
// Meteor Head and Tail
pMeteor->SetTravelDirection( vecDirection );
pMeteor->m_HeadEffect.SetSmokeEmission( true );
pMeteor->m_HeadEffect.Start( vecOrigin, vecDirection );
pMeteor->m_HeadEffect.SetParticleScale( 1.0f / 16.0f );
pMeteor->m_TailEffect.Start( vecOrigin, vecDirection, flSpeed );
pMeteor->SetNextClientThink( CLIENT_THINK_ALWAYS );
}
return pMeteor;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void C_EnvMeteor::Destroy( C_EnvMeteor *pMeteor )
{
Assert( pMeteor->GetClientHandle() != INVALID_CLIENTENTITY_HANDLE );
ClientThinkList()->AddToDeleteList( pMeteor->GetClientHandle() );
}
| 32.550613 | 136 | 0.569429 | cstom4994 |
68042b93b117990dfebcf29a5579fbdd97c0e06b | 224 | hpp | C++ | graphics/shaders/Type.hpp | quyse/inanity | a39225c5a41f879abe5aa492bb22b500dbe77433 | [
"MIT"
] | 26 | 2015-04-22T05:25:25.000Z | 2020-11-15T11:07:56.000Z | graphics/shaders/Type.hpp | quyse/inanity | a39225c5a41f879abe5aa492bb22b500dbe77433 | [
"MIT"
] | 2 | 2015-01-05T10:41:27.000Z | 2015-01-06T20:46:11.000Z | graphics/shaders/Type.hpp | quyse/inanity | a39225c5a41f879abe5aa492bb22b500dbe77433 | [
"MIT"
] | 5 | 2016-08-02T11:13:57.000Z | 2018-10-26T11:19:27.000Z | #ifndef ___INANITY_SHADERS_TYPE_HPP___
#define ___INANITY_SHADERS_TYPE_HPP___
#include "shaders.hpp"
BEGIN_INANITY_SHADERS
/// Базовый класс типов данных для шейдеров.
class Type
{
public:
};
END_INANITY_SHADERS
#endif
| 13.176471 | 44 | 0.816964 | quyse |
680662dc4b4e7bab5d390e481ae866021c4f9eae | 2,465 | cpp | C++ | src/OpenGL/entrypoints/GL3.0/gl_get_booleani_v.cpp | kbiElude/VKGL | fffabf412723a3612ba1c5bfeafe1da38062bd18 | [
"MIT"
] | 114 | 2018-08-05T16:26:53.000Z | 2021-12-30T07:28:35.000Z | src/OpenGL/entrypoints/GL3.0/gl_get_booleani_v.cpp | kbiElude/VKGL | fffabf412723a3612ba1c5bfeafe1da38062bd18 | [
"MIT"
] | 5 | 2018-08-18T21:16:58.000Z | 2018-11-22T21:50:48.000Z | src/OpenGL/entrypoints/GL3.0/gl_get_booleani_v.cpp | kbiElude/VKGL | fffabf412723a3612ba1c5bfeafe1da38062bd18 | [
"MIT"
] | 6 | 2018-08-05T22:32:28.000Z | 2021-10-04T15:39:53.000Z | /* VKGL (c) 2018 Dominik Witczak
*
* This code is licensed under MIT license (see LICENSE.txt for details)
*/
#include "OpenGL/entrypoints/GL3.0/gl_get_booleani_v.h"
#include "OpenGL/context.h"
#include "OpenGL/globals.h"
#include "OpenGL/utils_enum.h"
static bool validate(OpenGL::Context* in_context_ptr,
const GLenum& in_target,
const GLuint& in_index,
GLboolean* out_data_ptr)
{
bool result = false;
// ..
result = true;
return result;
}
void VKGL_APIENTRY OpenGL::vkglGetBooleani_v(GLenum target,
GLuint index,
GLboolean* data)
{
const auto dispatch_table_ptr = OpenGL::g_dispatch_table_ptr;
VKGL_TRACE("glGetBooleani_v(target=[%s] index=[%u] data=[%p])",
OpenGL::Utils::get_raw_string_for_gl_enum(target),
index,
data);
dispatch_table_ptr->pGLGetBooleani_v(dispatch_table_ptr->bound_context_ptr,
target,
index,
data);
}
static void vkglGetBooleani_v_execute(OpenGL::Context* in_context_ptr,
const GLenum& in_target,
const GLuint& in_index,
GLboolean* out_data_ptr)
{
const OpenGL::ContextProperty target_vkgl = OpenGL::Utils::get_context_property_for_gl_enum(in_target);
in_context_ptr->get_parameter_indexed(target_vkgl,
OpenGL::GetSetArgumentType::Boolean,
in_index,
out_data_ptr);
}
void OpenGL::vkglGetBooleani_v_with_validation(OpenGL::Context* in_context_ptr,
const GLenum& in_target,
const GLuint& in_index,
GLboolean* out_data_ptr)
{
if (validate(in_context_ptr,
in_target,
in_index,
out_data_ptr) )
{
vkglGetBooleani_v_execute(in_context_ptr,
in_target,
in_index,
out_data_ptr);
}
}
| 35.724638 | 107 | 0.486815 | kbiElude |
6809a142f548c14845ebb3e92c8c8ad2e4767598 | 1,762 | cpp | C++ | src/commonUtils.cpp | flavio-fernandes/oclock | a5c7c4e4a36e16cf1c68f597e68ec70fc4f3b984 | [
"MIT"
] | null | null | null | src/commonUtils.cpp | flavio-fernandes/oclock | a5c7c4e4a36e16cf1c68f597e68ec70fc4f3b984 | [
"MIT"
] | null | null | null | src/commonUtils.cpp | flavio-fernandes/oclock | a5c7c4e4a36e16cf1c68f597e68ec70fc4f3b984 | [
"MIT"
] | null | null | null | #include <random>
#include <algorithm>
#include <stdlib.h>
#include <strings.h>
#include "commonUtils.h"
// http://en.cppreference.com/w/cpp/numeric/random
// Choose a random mean between 1 and 0xffffff
static std::random_device randomDevice;
static std::default_random_engine randomEngine(randomDevice());
static std::uniform_int_distribution<Int32U> uniform_dist(0);
Int32U getRandomNumber(Int32U upperBound) {
return uniform_dist(randomEngine) % upperBound;
}
bool parseBooleanValue(const char* valueStr) {
if (valueStr == nullptr) return false;
if (strncasecmp(valueStr, "n", 1) == 0) return false;
if (strncasecmp(valueStr, "y", 1) == 0) return true;
if (strcasecmp(valueStr, "false") == 0) return false;
if (strcasecmp(valueStr, "true") == 0) return true;
return strtoul(valueStr, NULL /*endptr*/, 0 /*base*/) != 0;
}
bool isParamSet(const StringMap& params, const char* const paramName, const char* const paramValue) {
StringMap::const_iterator iter = params.find(paramName);
if (iter == params.end()) return false;
if (paramValue != nullptr && iter->second != paramValue) return false;
return true;
}
bool getParamValue(const StringMap& params, const char* const paramName, std::string& paramValueFound) {
StringMap::const_iterator iter = params.find(paramName);
if (iter != params.end()) {
paramValueFound = iter->second;
return true;
}
return false;
}
static bool isUnwantedChar(char c) {
return c < ' ' or c > '~';
}
std::string currTimestamp() {
time_t rawTime;
struct tm timeInfo;
char buff[64];
time(&rawTime);
localtime_r(&rawTime, &timeInfo);
std::string str(asctime_r(&timeInfo, buff));
str.erase(std::remove_if(str.begin(), str.end(), &isUnwantedChar), str.end());
return str;
}
| 30.37931 | 104 | 0.708854 | flavio-fernandes |
6809ab5cf6abd4173e98010d97a194f80c2f44f9 | 3,622 | cc | C++ | emu-ex-plus-alpha/imagine/src/input/ps3/ps3.cc | damoonvisuals/GBA4iOS | 95bfce0aca270b68484535ecaf0d3b2366739c77 | [
"MIT"
] | 1 | 2018-11-14T23:40:35.000Z | 2018-11-14T23:40:35.000Z | emu-ex-plus-alpha/imagine/src/input/ps3/ps3.cc | damoonvisuals/GBA4iOS | 95bfce0aca270b68484535ecaf0d3b2366739c77 | [
"MIT"
] | null | null | null | emu-ex-plus-alpha/imagine/src/input/ps3/ps3.cc | damoonvisuals/GBA4iOS | 95bfce0aca270b68484535ecaf0d3b2366739c77 | [
"MIT"
] | null | null | null | /* This file is part of Imagine.
Imagine 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.
Imagine 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 Imagine. If not, see <http://www.gnu.org/licenses/> */
#define thisModuleName "input:ps3"
#include <input/common/common.h>
#include <base/Base.hh>
#include <cell/pad.h>
#include <cell/sysmodule.h>
namespace Input
{
static const PackedInputAccess padDataAccess[] =
{
{ CELL_PAD_BTN_OFFSET_DIGITAL1, CELL_PAD_CTRL_SELECT, PS3::SELECT },
{ CELL_PAD_BTN_OFFSET_DIGITAL1, CELL_PAD_CTRL_L3, PS3::L3 },
{ CELL_PAD_BTN_OFFSET_DIGITAL1, CELL_PAD_CTRL_R3, PS3::R3 },
{ CELL_PAD_BTN_OFFSET_DIGITAL1, CELL_PAD_CTRL_START, PS3::START },
{ CELL_PAD_BTN_OFFSET_DIGITAL1, CELL_PAD_CTRL_UP, PS3::UP },
{ CELL_PAD_BTN_OFFSET_DIGITAL1, CELL_PAD_CTRL_RIGHT, PS3::RIGHT },
{ CELL_PAD_BTN_OFFSET_DIGITAL1, CELL_PAD_CTRL_DOWN, PS3::DOWN },
{ CELL_PAD_BTN_OFFSET_DIGITAL1, CELL_PAD_CTRL_LEFT, PS3::LEFT },
{ CELL_PAD_BTN_OFFSET_DIGITAL2, CELL_PAD_CTRL_L2, PS3::L2 },
{ CELL_PAD_BTN_OFFSET_DIGITAL2, CELL_PAD_CTRL_R2, PS3::R2 },
{ CELL_PAD_BTN_OFFSET_DIGITAL2, CELL_PAD_CTRL_L1, PS3::L1 },
{ CELL_PAD_BTN_OFFSET_DIGITAL2, CELL_PAD_CTRL_R1, PS3::R1 },
{ CELL_PAD_BTN_OFFSET_DIGITAL2, CELL_PAD_CTRL_TRIANGLE, PS3::TRIANGLE },
{ CELL_PAD_BTN_OFFSET_DIGITAL2, CELL_PAD_CTRL_CIRCLE, PS3::CIRCLE },
{ CELL_PAD_BTN_OFFSET_DIGITAL2, CELL_PAD_CTRL_CROSS, PS3::CROSS },
{ CELL_PAD_BTN_OFFSET_DIGITAL2, CELL_PAD_CTRL_SQUARE, PS3::SQUARE },
};
static const uint numPads = 5;
static uint padStatus[numPads] = { 0 };
static CellPadData padData[numPads] = { { 0, { 0 } } };
void update()
{
CellPadInfo2 padInfo;
cellPadGetInfo2(&padInfo);
iterateTimes(sizeofArray(padStatus), i)
{
if(padInfo.port_status[i] != 0 && padStatus[i] == 0)
{
//logMsg("pad connection %d vendor:%d product:%d", i, padInfo.vendor_id[i], padInfo.product_id[i]);
logMsg("pad connection %d type:%d capability:%d", i, padInfo.device_type[i], padInfo.device_capability[i]);
mem_zero(padData[i]);
addDevice(Device{i, Event::MAP_PS3PAD, Device::TYPE_BIT_GAMEPAD, "PS3 Controller"});
}
padStatus[i] = padInfo.port_status[i];
CellPadData data = { 0, { 0 } };
cellPadGetData(i, &data);
if(data.len != 0)
{
//logMsg("%d bytes from port", data.len, i);
forEachInArray(padDataAccess, e)
{
bool oldState = padData[i].button[e->byteOffset] & e->mask,
newState = data.button[e->byteOffset] & e->mask;
if(oldState != newState)
{
//logMsg("%d %s %s", i, buttonName(InputEvent::DEV_PS3PAD, e->keyEvent), newState ? "pushed" : "released");
Input::onInputEvent(Event(i, Event::MAP_PS3PAD, e->keyEvent, newState ? PUSHED : RELEASED, 0, devList.first()));
}
}
memcpy(&padData[i], &data, sizeof(CellPadData));
}
}
}
bool Device::anyTypeBitsPresent(uint typeBits)
{
if(typeBits & TYPE_BIT_GAMEPAD)
{
return true;
}
return false;
}
void setKeyRepeat(bool on)
{
// TODO
}
CallResult init()
{
cellSysmoduleLoadModule(CELL_SYSMODULE_IO);
int ret = cellPadInit(numPads);
if(ret != CELL_OK && ret != CELL_PAD_ERROR_ALREADY_INITIALIZED)
{
logErr("error in cellPadInit");
Base::exit();
}
return OK;
}
}
| 31.495652 | 117 | 0.726394 | damoonvisuals |
680aff3b1abb8e6c9b0a90d3175a5b36e3dd2430 | 856 | hpp | C++ | src/Onyx32.Gui.Legacy/Onyx32.Gui/src/Controls/DateTime/DateTime.hpp | yottaawesome/onyx32-gui | 6d1ead1a6e36f3f56e26fa445ea314e96d1234e9 | [
"MIT"
] | 1 | 2019-02-02T03:30:53.000Z | 2019-02-02T03:30:53.000Z | src/Onyx32.Gui.Legacy/Onyx32.Gui/src/Controls/DateTime/DateTime.hpp | yottaawesome/Onyx32 | 6d1ead1a6e36f3f56e26fa445ea314e96d1234e9 | [
"MIT"
] | 1 | 2020-01-22T00:35:34.000Z | 2020-01-22T15:30:47.000Z | src/Onyx32.Gui.Legacy/Onyx32.Gui/src/Controls/DateTime/DateTime.hpp | yottaawesome/Onyx32 | 6d1ead1a6e36f3f56e26fa445ea314e96d1234e9 | [
"MIT"
] | null | null | null | #pragma once
#include "../BaseControl.hpp"
namespace Onyx32::Gui::Controls
{
class DateTime : public BaseControl<IDateTime>
{
public:
DateTime(
const unsigned int width,
const unsigned int height,
const unsigned int xPos,
const unsigned int yPos,
const uint64_t controlId);
virtual ~DateTime();
virtual void Initialize() override;
virtual void GetDateTime(SYSTEMTIME& dateTime) override;
virtual void SetOnChange(OnDateTimeChange& onChange) override;
LRESULT Process(unsigned int message, WPARAM wParam, LPARAM lParam) override;
static IDateTime* Create(IWindow* parent, uint64_t controlId, unsigned int width, unsigned int height, unsigned int xPos, unsigned int yPos);
protected:
OnDateTimeChange& _onChange;
static OnDateTimeChange DefaultDateTimeChangeHandler;
};
} | 30.571429 | 145 | 0.727804 | yottaawesome |
6810d2e317cbd7d391bd49bdb16675f913db7b8b | 1,833 | hpp | C++ | Engine/src/Render/Primitive.hpp | MilkyStorm3/SplashyEngine | 2c321395da04b524938390c74a45340d7c3c1e2a | [
"MIT"
] | null | null | null | Engine/src/Render/Primitive.hpp | MilkyStorm3/SplashyEngine | 2c321395da04b524938390c74a45340d7c3c1e2a | [
"MIT"
] | null | null | null | Engine/src/Render/Primitive.hpp | MilkyStorm3/SplashyEngine | 2c321395da04b524938390c74a45340d7c3c1e2a | [
"MIT"
] | null | null | null | #pragma once
#include "Graphics/Buffer.hpp"
#include "Render/Transform.hpp"
#include "Graphics/Texture.hpp"
namespace ant
{
struct Vertex
{
glm::vec4 position;
glm::vec4 color;
glm::vec2 textureCoordinate;
float textureId = 0;
static VertexBufferLayout layout;
operator float *();
#define INT_VERTEX_LAYOUT_DECL VertexBufferLayout Vertex::layout = {AttributeType::vec4f, AttributeType::vec4f, AttributeType::vec2f, AttributeType::vec1f};
};
class OldQuad
: public TransformComponent
{
public:
OldQuad();
~OldQuad() {}
friend class Renderer2D;
friend class Renderer2DQueue;
void SetColor(const glm::vec4 &color);
void SetTexture(Ref<Texture> texture);
Ref<Texture> GetTexture() const { return m_texture; }
inline const glm::vec4 &GetColor() const { return m_color; }
inline void SetSubTexture(Ref<SubTexture> tex) { SetSubTexture(*tex); }
void SetSubTexture(const SubTexture &tex);
private:
void SetTexId(uint32_t id);
glm::vec4 m_color = {1.f, 1.f, 1.f, 1.f};
Ref<Texture> m_texture;
std::array<Vertex, 4> m_vertices;
std::array<uint32_t, 6> m_indices;
};
class Quad
{
public:
friend class Renderer2D;
friend class Renderer2DQueue;
Quad(const glm::vec4 &color = {1.f, 1.f, 1.f, 1.f});
~Quad() {}
inline const glm::vec4 &GetColor() const { return m_color; }
inline glm::vec4 &GetColorRef() { return m_color; }
void SetColor(const glm::vec4 &color);
void UpdateColor();
private:
glm::vec4 m_color;
std::array<Vertex, 4> m_vertices;
static const std::array<uint32_t, 6> s_indices;
};
} | 26.955882 | 164 | 0.604474 | MilkyStorm3 |
681626199cecf9f91bc68e243da86c518fc934f5 | 315 | cpp | C++ | lib/geometry/distance_between_two_points.cpp | mdstoy/atcoder-cpp | 5dfe4db5558dfa1faaf10f19c1a99fee1b4104e7 | [
"Unlicense"
] | null | null | null | lib/geometry/distance_between_two_points.cpp | mdstoy/atcoder-cpp | 5dfe4db5558dfa1faaf10f19c1a99fee1b4104e7 | [
"Unlicense"
] | null | null | null | lib/geometry/distance_between_two_points.cpp | mdstoy/atcoder-cpp | 5dfe4db5558dfa1faaf10f19c1a99fee1b4104e7 | [
"Unlicense"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
// verifing: https://atcoder.jp/contests/math-and-algorithm/submissions/30698630
// *** CAUTION *** : Return value is square.
double distance_between_two_points(double x1, double y1, double x2, double y2) {
return (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2);
}
| 31.5 | 80 | 0.669841 | mdstoy |
681846559edf0e4b5d0f15a30d826a03e68a29a6 | 313 | cpp | C++ | Contest 1005/D.cpp | PC-DOS/SEUCPP-OJ-KEYS | 073f97fb29a659abd25554330382f0a7149c2511 | [
"MIT"
] | null | null | null | Contest 1005/D.cpp | PC-DOS/SEUCPP-OJ-KEYS | 073f97fb29a659abd25554330382f0a7149c2511 | [
"MIT"
] | null | null | null | Contest 1005/D.cpp | PC-DOS/SEUCPP-OJ-KEYS | 073f97fb29a659abd25554330382f0a7149c2511 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cmath>
using namespace std;
int main(){
int a,b,c,n;
n = 0;
for (c = 1; c <= 100; ++c){
for (a = 1; a <= c; ++a){
b = sqrt(c*c - a*a);
if (a <= b && ((a*a + b*b) == (c*c))) ++n;
}
}
cout << n;
//system("pause > nul");
} | 20.866667 | 54 | 0.373802 | PC-DOS |
681af677f93b2046ecf12a3ced4e35528cef662f | 17,280 | cpp | C++ | src/bpftrace.cpp | ajor/bpftrace | 691e1264b526b9179a610c3ae706e439efd132d3 | [
"Apache-2.0"
] | 278 | 2016-12-28T00:51:17.000Z | 2022-02-09T10:32:31.000Z | src/bpftrace.cpp | brendangregg/bpftrace | 4cc2e864a9bbbcb97a508bfc5a3db1cd0b5d7f95 | [
"Apache-2.0"
] | 48 | 2017-07-10T20:17:55.000Z | 2020-01-20T23:41:51.000Z | src/bpftrace.cpp | ajor/bpftrace | 691e1264b526b9179a610c3ae706e439efd132d3 | [
"Apache-2.0"
] | 19 | 2017-07-28T05:49:00.000Z | 2022-02-22T22:05:37.000Z | #include <assert.h>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <regex>
#include <sstream>
#include <sys/epoll.h>
#include "bcc_syms.h"
#include "perf_reader.h"
#include "bpforc.h"
#include "bpftrace.h"
#include "attached_probe.h"
#include "triggers.h"
namespace bpftrace {
int BPFtrace::add_probe(ast::Probe &p)
{
for (auto attach_point : *p.attach_points)
{
if (attach_point->provider == "BEGIN")
{
Probe probe;
probe.path = "/proc/self/exe";
probe.attach_point = "BEGIN_trigger";
probe.type = probetype(attach_point->provider);
probe.prog_name = p.name();
probe.name = p.name();
special_probes_.push_back(probe);
continue;
}
else if (attach_point->provider == "END")
{
Probe probe;
probe.path = "/proc/self/exe";
probe.attach_point = "END_trigger";
probe.type = probetype(attach_point->provider);
probe.prog_name = p.name();
probe.name = p.name();
special_probes_.push_back(probe);
continue;
}
std::vector<std::string> attach_funcs;
if (attach_point->func.find("*") != std::string::npos ||
attach_point->func.find("[") != std::string::npos &&
attach_point->func.find("]") != std::string::npos)
{
std::string file_name;
switch (probetype(attach_point->provider))
{
case ProbeType::kprobe:
case ProbeType::kretprobe:
file_name = "/sys/kernel/debug/tracing/available_filter_functions";
break;
case ProbeType::tracepoint:
file_name = "/sys/kernel/debug/tracing/available_events";
break;
default:
std::cerr << "Wildcard matches aren't available on probe type '"
<< attach_point->provider << "'" << std::endl;
return 1;
}
auto matches = find_wildcard_matches(attach_point->target,
attach_point->func,
file_name);
attach_funcs.insert(attach_funcs.end(), matches.begin(), matches.end());
}
else
{
attach_funcs.push_back(attach_point->func);
}
for (auto func : attach_funcs)
{
Probe probe;
probe.path = attach_point->target;
probe.attach_point = func;
probe.type = probetype(attach_point->provider);
probe.prog_name = p.name();
probe.name = attach_point->name(func);
probe.freq = attach_point->freq;
probes_.push_back(probe);
}
}
return 0;
}
std::set<std::string> BPFtrace::find_wildcard_matches(const std::string &prefix, const std::string &func, const std::string &file_name)
{
// Turn glob into a regex
auto regex_str = "(" + std::regex_replace(func, std::regex("\\*"), "[^\\s]*") + ")";
if (prefix != "")
regex_str = prefix + ":" + regex_str;
regex_str = "^" + regex_str;
std::regex func_regex(regex_str);
std::smatch match;
std::ifstream file(file_name);
if (file.fail())
{
std::cerr << strerror(errno) << ": " << file_name << std::endl;
return std::set<std::string>();
}
std::string line;
std::set<std::string> matches;
while (std::getline(file, line))
{
if (std::regex_search(line, match, func_regex))
{
assert(match.size() == 2);
matches.insert(match[1]);
}
}
return matches;
}
int BPFtrace::num_probes() const
{
return special_probes_.size() + probes_.size();
}
void perf_event_printer(void *cb_cookie, void *data, int size)
{
auto bpftrace = static_cast<BPFtrace*>(cb_cookie);
auto printf_id = *static_cast<uint64_t*>(data);
auto arg_data = static_cast<uint8_t*>(data) + sizeof(uint64_t);
auto fmt = std::get<0>(bpftrace->printf_args_[printf_id]).c_str();
auto args = std::get<1>(bpftrace->printf_args_[printf_id]);
std::vector<uint64_t> arg_values;
std::vector<std::unique_ptr<char>> resolved_symbols;
for (auto arg : args)
{
switch (arg.type)
{
case Type::integer:
arg_values.push_back(*(uint64_t*)arg_data);
break;
case Type::string:
arg_values.push_back((uint64_t)arg_data);
break;
case Type::sym:
resolved_symbols.emplace_back(strdup(
bpftrace->resolve_sym(*(uint64_t*)arg_data).c_str()));
arg_values.push_back((uint64_t)resolved_symbols.back().get());
break;
case Type::usym:
resolved_symbols.emplace_back(strdup(
bpftrace->resolve_usym(*(uint64_t*)arg_data).c_str()));
arg_values.push_back((uint64_t)resolved_symbols.back().get());
break;
default:
abort();
}
arg_data += arg.size;
}
switch (args.size())
{
case 0:
printf(fmt);
break;
case 1:
printf(fmt, arg_values.at(0));
break;
case 2:
printf(fmt, arg_values.at(0), arg_values.at(1));
break;
case 3:
printf(fmt, arg_values.at(0), arg_values.at(1), arg_values.at(2));
break;
case 4:
printf(fmt, arg_values.at(0), arg_values.at(1), arg_values.at(2),
arg_values.at(3));
break;
case 5:
printf(fmt, arg_values.at(0), arg_values.at(1), arg_values.at(2),
arg_values.at(3), arg_values.at(4));
break;
case 6:
printf(fmt, arg_values.at(0), arg_values.at(1), arg_values.at(2),
arg_values.at(3), arg_values.at(4), arg_values.at(5));
break;
default:
abort();
}
}
void perf_event_lost(void *cb_cookie, uint64_t lost)
{
printf("Lost %lu events\n", lost);
}
std::unique_ptr<AttachedProbe> BPFtrace::attach_probe(Probe &probe, const BpfOrc &bpforc)
{
auto func = bpforc.sections_.find("s_" + probe.prog_name);
if (func == bpforc.sections_.end())
{
std::cerr << "Code not generated for probe: " << probe.name << std::endl;
return nullptr;
}
try
{
return std::make_unique<AttachedProbe>(probe, func->second);
}
catch (std::runtime_error e)
{
std::cerr << e.what() << std::endl;
}
return nullptr;
}
int BPFtrace::run(std::unique_ptr<BpfOrc> bpforc)
{
for (Probe &probe : special_probes_)
{
auto attached_probe = attach_probe(probe, *bpforc.get());
if (attached_probe == nullptr)
return -1;
special_attached_probes_.push_back(std::move(attached_probe));
}
int epollfd = setup_perf_events();
if (epollfd < 0)
return epollfd;
BEGIN_trigger();
for (Probe &probe : probes_)
{
auto attached_probe = attach_probe(probe, *bpforc.get());
if (attached_probe == nullptr)
return -1;
attached_probes_.push_back(std::move(attached_probe));
}
poll_perf_events(epollfd);
attached_probes_.clear();
END_trigger();
poll_perf_events(epollfd, 100);
special_attached_probes_.clear();
return 0;
}
int BPFtrace::setup_perf_events()
{
int epollfd = epoll_create1(EPOLL_CLOEXEC);
if (epollfd == -1)
{
std::cerr << "Failed to create epollfd" << std::endl;
return -1;
}
std::vector<int> cpus = ebpf::get_online_cpus();
online_cpus_ = cpus.size();
for (int cpu : cpus)
{
int page_cnt = 8;
void *reader = bpf_open_perf_buffer(&perf_event_printer, &perf_event_lost, this, -1, cpu, page_cnt);
if (reader == nullptr)
{
std::cerr << "Failed to open perf buffer" << std::endl;
return -1;
}
struct epoll_event ev = {};
ev.events = EPOLLIN;
ev.data.ptr = reader;
int reader_fd = perf_reader_fd((perf_reader*)reader);
bpf_update_elem(perf_event_map_->mapfd_, &cpu, &reader_fd, 0);
if (epoll_ctl(epollfd, EPOLL_CTL_ADD, reader_fd, &ev) == -1)
{
std::cerr << "Failed to add perf reader to epoll" << std::endl;
return -1;
}
}
return epollfd;
}
void BPFtrace::poll_perf_events(int epollfd, int timeout)
{
auto events = std::vector<struct epoll_event>(online_cpus_);
while (true)
{
int ready = epoll_wait(epollfd, events.data(), online_cpus_, timeout);
if (ready <= 0)
{
return;
}
for (int i=0; i<ready; i++)
{
perf_reader_event_read((perf_reader*)events[i].data.ptr);
}
}
return;
}
int BPFtrace::print_maps()
{
for(auto &mapmap : maps_)
{
IMap &map = *mapmap.second.get();
int err;
if (map.type_.type == Type::quantize)
err = print_map_quantize(map);
else
err = print_map(map);
if (err)
return err;
}
return 0;
}
int BPFtrace::print_map(IMap &map)
{
std::vector<uint8_t> old_key;
try
{
old_key = find_empty_key(map, map.key_.size());
}
catch (std::runtime_error &e)
{
std::cerr << "Error getting key for map '" << map.name_ << "': "
<< e.what() << std::endl;
return -2;
}
auto key(old_key);
std::vector<std::pair<std::vector<uint8_t>, std::vector<uint8_t>>> values_by_key;
while (bpf_get_next_key(map.mapfd_, old_key.data(), key.data()) == 0)
{
int value_size = map.type_.size;
if (map.type_.type == Type::count)
value_size *= ncpus_;
auto value = std::vector<uint8_t>(value_size);
int err = bpf_lookup_elem(map.mapfd_, key.data(), value.data());
if (err)
{
std::cerr << "Error looking up elem: " << err << std::endl;
return -1;
}
values_by_key.push_back({key, value});
old_key = key;
}
if (map.type_.type == Type::count)
{
std::sort(values_by_key.begin(), values_by_key.end(), [&](auto &a, auto &b)
{
return reduce_value(a.second, ncpus_) < reduce_value(b.second, ncpus_);
});
}
else
{
sort_by_key(map.key_.args_, values_by_key);
};
for (auto &pair : values_by_key)
{
auto key = pair.first;
auto value = pair.second;
std::cout << map.name_ << map.key_.argument_value_list(*this, key) << ": ";
if (map.type_.type == Type::stack)
std::cout << get_stack(*(uint32_t*)value.data(), false, 8);
else if (map.type_.type == Type::ustack)
std::cout << get_stack(*(uint32_t*)value.data(), true, 8);
else if (map.type_.type == Type::sym)
std::cout << resolve_sym(*(uintptr_t*)value.data());
else if (map.type_.type == Type::usym)
std::cout << resolve_usym(*(uintptr_t*)value.data());
else if (map.type_.type == Type::string)
std::cout << value.data() << std::endl;
else if (map.type_.type == Type::count)
std::cout << reduce_value(value, ncpus_) << std::endl;
else
std::cout << *(int64_t*)value.data() << std::endl;
}
std::cout << std::endl;
return 0;
}
int BPFtrace::print_map_quantize(IMap &map)
{
// A quantize-map adds an extra 8 bytes onto the end of its key for storing
// the bucket number.
// e.g. A map defined as: @x[1, 2] = @quantize(3);
// would actually be stored with the key: [1, 2, 3]
std::vector<uint8_t> old_key;
try
{
old_key = find_empty_key(map, map.key_.size() + 8);
}
catch (std::runtime_error &e)
{
std::cerr << "Error getting key for map '" << map.name_ << "': "
<< e.what() << std::endl;
return -2;
}
auto key(old_key);
std::map<std::vector<uint8_t>, std::vector<uint64_t>> values_by_key;
while (bpf_get_next_key(map.mapfd_, old_key.data(), key.data()) == 0)
{
auto key_prefix = std::vector<uint8_t>(map.key_.size());
int bucket = key.at(map.key_.size());
for (size_t i=0; i<map.key_.size(); i++)
key_prefix.at(i) = key.at(i);
int value_size = map.type_.size * ncpus_;
auto value = std::vector<uint8_t>(value_size);
int err = bpf_lookup_elem(map.mapfd_, key.data(), value.data());
if (err)
{
std::cerr << "Error looking up elem: " << err << std::endl;
return -1;
}
if (values_by_key.find(key_prefix) == values_by_key.end())
{
// New key - create a list of buckets for it
values_by_key[key_prefix] = std::vector<uint64_t>(65);
}
values_by_key[key_prefix].at(bucket) = reduce_value(value, ncpus_);
old_key = key;
}
// Sort based on sum of counts in all buckets
std::vector<std::pair<std::vector<uint8_t>, uint64_t>> total_counts_by_key;
for (auto &map_elem : values_by_key)
{
int sum = 0;
for (size_t i=0; i<map_elem.second.size(); i++)
{
sum += map_elem.second.at(i);
}
total_counts_by_key.push_back({map_elem.first, sum});
}
std::sort(total_counts_by_key.begin(), total_counts_by_key.end(), [&](auto &a, auto &b)
{
return a.second < b.second;
});
for (auto &key_count : total_counts_by_key)
{
auto &key = key_count.first;
auto &value = values_by_key[key];
std::cout << map.name_ << map.key_.argument_value_list(*this, key) << ": " << std::endl;
print_quantize(value);
std::cout << std::endl;
}
return 0;
}
int BPFtrace::print_quantize(const std::vector<uint64_t> &values) const
{
int max_index = -1;
int max_value = 0;
for (size_t i = 0; i < values.size(); i++)
{
int v = values.at(i);
if (v != 0)
max_index = i;
if (v > max_value)
max_value = v;
}
if (max_index == -1)
return 0;
for (int i = 0; i <= max_index; i++)
{
std::ostringstream header;
if (i == 0)
{
header << "[0, 1]";
}
else
{
header << "[" << quantize_index_label(i);
header << ", " << quantize_index_label(i+1) << ")";
}
int max_width = 52;
int bar_width = values.at(i)/(float)max_value*max_width;
std::string bar(bar_width, '@');
std::cout << std::setw(16) << std::left << header.str()
<< std::setw(8) << std::right << values.at(i)
<< " |" << std::setw(max_width) << std::left << bar << "|"
<< std::endl;
}
return 0;
}
std::string BPFtrace::quantize_index_label(int power)
{
char suffix = '\0';
if (power >= 40)
{
suffix = 'T';
power -= 40;
}
else if (power >= 30)
{
suffix = 'G';
power -= 30;
}
else if (power >= 20)
{
suffix = 'M';
power -= 20;
}
else if (power >= 10)
{
suffix = 'k';
power -= 10;
}
std::ostringstream label;
label << (1<<power);
if (suffix)
label << suffix;
return label.str();
}
uint64_t BPFtrace::reduce_value(const std::vector<uint8_t> &value, int ncpus)
{
uint64_t sum = 0;
for (int i=0; i<ncpus; i++)
{
sum += *(uint64_t*)(value.data() + i*sizeof(uint64_t*));
}
return sum;
}
std::vector<uint8_t> BPFtrace::find_empty_key(IMap &map, size_t size) const
{
if (size == 0) size = 8;
auto key = std::vector<uint8_t>(size);
int value_size = map.type_.size;
if (map.type_.type == Type::count || map.type_.type == Type::quantize)
value_size *= ncpus_;
auto value = std::vector<uint8_t>(value_size);
if (bpf_lookup_elem(map.mapfd_, key.data(), value.data()))
return key;
for (auto &elem : key) elem = 0xff;
if (bpf_lookup_elem(map.mapfd_, key.data(), value.data()))
return key;
for (auto &elem : key) elem = 0x55;
if (bpf_lookup_elem(map.mapfd_, key.data(), value.data()))
return key;
throw std::runtime_error("Could not find empty key");
}
std::string BPFtrace::get_stack(uint32_t stackid, bool ustack, int indent)
{
auto stack_trace = std::vector<uint64_t>(MAX_STACK_SIZE);
int err = bpf_lookup_elem(stackid_map_->mapfd_, &stackid, stack_trace.data());
if (err)
{
std::cerr << "Error looking up stack id " << stackid << ": " << err << std::endl;
return "";
}
std::ostringstream stack;
std::string padding(indent, ' ');
stack << "\n";
for (auto &addr : stack_trace)
{
if (addr == 0)
break;
if (!ustack)
stack << padding << resolve_sym(addr, true) << std::endl;
else
stack << padding << resolve_usym(addr) << std::endl;
}
return stack.str();
}
std::string BPFtrace::resolve_sym(uintptr_t addr, bool show_offset)
{
struct bcc_symbol sym;
std::ostringstream symbol;
if (ksyms_.resolve_addr(addr, &sym))
{
symbol << sym.name;
if (show_offset)
symbol << "+" << sym.offset;
}
else
{
symbol << (void*)addr;
}
return symbol.str();
}
std::string BPFtrace::resolve_usym(uintptr_t addr) const
{
// TODO
std::ostringstream symbol;
symbol << (void*)addr;
return symbol.str();
}
void BPFtrace::sort_by_key(std::vector<SizedType> key_args,
std::vector<std::pair<std::vector<uint8_t>, std::vector<uint8_t>>> &values_by_key)
{
int arg_offset = 0;
for (auto arg : key_args)
{
arg_offset += arg.size;
}
// Sort the key arguments in reverse order so the results are sorted by
// the first argument first, then the second, etc.
for (size_t i=key_args.size(); i-- > 0; )
{
auto arg = key_args.at(i);
arg_offset -= arg.size;
if (arg.type == Type::integer)
{
if (arg.size == 8)
{
std::stable_sort(values_by_key.begin(), values_by_key.end(), [&](auto &a, auto &b)
{
return *(uint64_t*)(a.first.data() + arg_offset) < *(uint64_t*)(b.first.data() + arg_offset);
});
}
else
abort();
}
else if (arg.type == Type::string)
{
std::stable_sort(values_by_key.begin(), values_by_key.end(), [&](auto &a, auto &b)
{
return strncmp((char*)(a.first.data() + arg_offset),
(char*)(b.first.data() + arg_offset),
STRING_SIZE) < 0;
});
}
// Other types don't get sorted
}
}
} // namespace bpftrace
| 25.300146 | 135 | 0.599653 | ajor |
681b706f6831743ded94d704c5f06f2b86e47399 | 7,681 | cpp | C++ | Engine/Source/Runtime/Online/BuildPatchServices/Private/BuildPatchMergeManifests.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | 1 | 2022-01-29T18:36:12.000Z | 2022-01-29T18:36:12.000Z | Engine/Source/Runtime/Online/BuildPatchServices/Private/BuildPatchMergeManifests.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | Engine/Source/Runtime/Online/BuildPatchServices/Private/BuildPatchMergeManifests.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "BuildPatchMergeManifests.h"
#include "Misc/FileHelper.h"
#include "Misc/Paths.h"
#include "HAL/ThreadSafeBool.h"
#include "Misc/Guid.h"
#include "BuildPatchManifest.h"
#include "Async/Future.h"
#include "Async/Async.h"
DECLARE_LOG_CATEGORY_EXTERN(LogMergeManifests, Log, All);
DEFINE_LOG_CATEGORY(LogMergeManifests);
namespace MergeHelpers
{
FBuildPatchAppManifestPtr LoadManifestFile(const FString& ManifestFilePath, FCriticalSection* UObjectAllocationLock)
{
check(UObjectAllocationLock != nullptr);
UObjectAllocationLock->Lock();
FBuildPatchAppManifestPtr Manifest = MakeShareable(new FBuildPatchAppManifest());
UObjectAllocationLock->Unlock();
if (Manifest->LoadFromFile(ManifestFilePath))
{
return Manifest;
}
return FBuildPatchAppManifestPtr();
}
bool CopyFileDataFromManifestToArray(const TSet<FString>& Filenames, const FBuildPatchAppManifestPtr& Source, TArray<FFileManifestData>& DestArray)
{
bool bSuccess = true;
for (const FString& Filename : Filenames)
{
check(Source.IsValid());
const FFileManifestData* FileManifest = Source->GetFileManifest(Filename);
if (FileManifest == nullptr)
{
UE_LOG(LogMergeManifests, Error, TEXT("Could not find file in %s %s: %s"), *Source->GetAppName(), *Source->GetVersionString(), *Filename);
bSuccess = false;
}
else
{
DestArray.Add(*FileManifest);
}
}
return bSuccess;
}
}
bool FBuildMergeManifests::MergeManifests(const FString& ManifestFilePathA, const FString& ManifestFilePathB, const FString& ManifestFilePathC, const FString& NewVersionString, const FString& SelectionDetailFilePath)
{
bool bSuccess = true;
FCriticalSection UObjectAllocationLock;
TFunction<FBuildPatchAppManifestPtr()> TaskManifestA = [&UObjectAllocationLock, &ManifestFilePathA]()
{
return MergeHelpers::LoadManifestFile(ManifestFilePathA, &UObjectAllocationLock);
};
TFunction<FBuildPatchAppManifestPtr()> TaskManifestB = [&UObjectAllocationLock, &ManifestFilePathB]()
{
return MergeHelpers::LoadManifestFile(ManifestFilePathB, &UObjectAllocationLock);
};
typedef TPair<TSet<FString>,TSet<FString>> FStringSetPair;
FThreadSafeBool bSelectionDetailSuccess = false;
TFunction<FStringSetPair()> TaskSelectionInfo = [&SelectionDetailFilePath, &bSelectionDetailSuccess]()
{
bSelectionDetailSuccess = true;
FStringSetPair StringSetPair;
if(SelectionDetailFilePath.IsEmpty() == false)
{
FString SelectionDetailFileData;
bSelectionDetailSuccess = FFileHelper::LoadFileToString(SelectionDetailFileData, *SelectionDetailFilePath);
if (bSelectionDetailSuccess)
{
TArray<FString> SelectionDetailLines;
SelectionDetailFileData.ParseIntoArrayLines(SelectionDetailLines);
for (int32 LineIdx = 0; LineIdx < SelectionDetailLines.Num(); ++LineIdx)
{
FString Filename, Source;
SelectionDetailLines[LineIdx].Split(TEXT("\t"), &Filename, &Source, ESearchCase::CaseSensitive);
Filename = Filename.TrimStartAndEnd().TrimQuotes();
FPaths::NormalizeDirectoryName(Filename);
Source = Source.TrimStartAndEnd().TrimQuotes();
if (Source == TEXT("A"))
{
StringSetPair.Key.Add(Filename);
}
else if (Source == TEXT("B"))
{
StringSetPair.Value.Add(Filename);
}
else
{
UE_LOG(LogMergeManifests, Error, TEXT("Could not parse line %d from %s"), LineIdx + 1, *SelectionDetailFilePath);
bSelectionDetailSuccess = false;
}
}
}
else
{
UE_LOG(LogMergeManifests, Error, TEXT("Could not load selection detail file %s"), *SelectionDetailFilePath);
}
}
return MoveTemp(StringSetPair);
};
TFuture<FBuildPatchAppManifestPtr> FutureManifestA = Async(EAsyncExecution::ThreadPool, MoveTemp(TaskManifestA));
TFuture<FBuildPatchAppManifestPtr> FutureManifestB = Async(EAsyncExecution::ThreadPool, MoveTemp(TaskManifestB));
TFuture<FStringSetPair> FutureSelectionDetail = Async(EAsyncExecution::ThreadPool, MoveTemp(TaskSelectionInfo));
FBuildPatchAppManifestPtr ManifestA = FutureManifestA.Get();
FBuildPatchAppManifestPtr ManifestB = FutureManifestB.Get();
FStringSetPair SelectionDetail = FutureSelectionDetail.Get();
// Flush any logs collected by tasks
GLog->FlushThreadedLogs();
// We must have loaded our manifests
if (ManifestA.IsValid() == false)
{
UE_LOG(LogMergeManifests, Error, TEXT("Could not load manifest %s"), *ManifestFilePathA);
return false;
}
if (ManifestB.IsValid() == false)
{
UE_LOG(LogMergeManifests, Error, TEXT("Could not load manifest %s"), *ManifestFilePathB);
return false;
}
// Check if the selection detail had an error
if (bSelectionDetailSuccess == false)
{
return false;
}
// If we have no selection detail, then we take the union of all files, preferring the version from B
if (SelectionDetail.Key.Num() == 0 && SelectionDetail.Value.Num() == 0)
{
TSet<FString> ManifestFilesA(ManifestA->GetBuildFileList());
SelectionDetail.Value.Append(ManifestB->GetBuildFileList());
SelectionDetail.Key = ManifestFilesA.Difference(SelectionDetail.Value);
}
// Create the new manifest
FBuildPatchAppManifest MergedManifest;
// Copy basic info from B
MergedManifest.ManifestFileVersion = ManifestB->ManifestFileVersion;
MergedManifest.bIsFileData = ManifestB->bIsFileData;
MergedManifest.AppID = ManifestB->AppID;
MergedManifest.AppName = ManifestB->AppName;
MergedManifest.LaunchExe = ManifestB->LaunchExe;
MergedManifest.LaunchCommand = ManifestB->LaunchCommand;
MergedManifest.PrereqIds = ManifestB->PrereqIds;
MergedManifest.PrereqName = ManifestB->PrereqName;
MergedManifest.PrereqPath = ManifestB->PrereqPath;
MergedManifest.PrereqArgs = ManifestB->PrereqArgs;
MergedManifest.CustomFields = ManifestB->CustomFields;
// Set the new version string
MergedManifest.BuildVersion = NewVersionString;
// Copy the file manifests required from A
bSuccess = MergeHelpers::CopyFileDataFromManifestToArray(SelectionDetail.Key, ManifestA, MergedManifest.FileManifestList) && bSuccess;
// Copy the file manifests required from B
bSuccess = MergeHelpers::CopyFileDataFromManifestToArray(SelectionDetail.Value, ManifestB, MergedManifest.FileManifestList) && bSuccess;
// Sort the file manifests before entering chunk info
MergedManifest.FileManifestList.Sort();
// Fill out the chunk list in order of reference
TSet<FGuid> ReferencedChunks;
for (const FFileManifestData& FileManifest: MergedManifest.FileManifestList)
{
for (const FChunkPartData& FileChunkPart : FileManifest.FileChunkParts)
{
if (ReferencedChunks.Contains(FileChunkPart.Guid) == false)
{
ReferencedChunks.Add(FileChunkPart.Guid);
// Find the chunk info
FChunkInfoData** ChunkInfo = ManifestB->ChunkInfoLookup.Find(FileChunkPart.Guid);
if (ChunkInfo == nullptr)
{
ChunkInfo = ManifestA->ChunkInfoLookup.Find(FileChunkPart.Guid);
}
if (ChunkInfo == nullptr)
{
UE_LOG(LogMergeManifests, Error, TEXT("Failed to copy chunk meta for %s used by %s. Possible damaged manifest file as input."), *FileChunkPart.Guid.ToString(), *FileManifest.Filename);
bSuccess = false;
}
else
{
MergedManifest.ChunkList.Add(**ChunkInfo);
}
}
}
}
// Save the new manifest out if we didn't register a failure
if (bSuccess)
{
MergedManifest.InitLookups();
if (!MergedManifest.SaveToFile(ManifestFilePathC, false))
{
UE_LOG(LogMergeManifests, Error, TEXT("Failed to save new manifest %s"), *ManifestFilePathC);
bSuccess = false;
}
}
else
{
UE_LOG(LogMergeManifests, Error, TEXT("Not saving new manifest due to previous errors."));
}
return bSuccess;
}
| 35.073059 | 216 | 0.755631 | windystrife |
681d496db1850440188eb5a96e41a2c1b2dc09a8 | 1,436 | cpp | C++ | 12.Classes&DynamicMemoryAllocation/Exercises/3.stock.cpp | HuangStomach/Cpp-primer-plus | c8b2b90f10057e72da3ab570da7cc39220c88f70 | [
"MIT"
] | 1 | 2019-09-18T01:48:06.000Z | 2019-09-18T01:48:06.000Z | 12.Classes&DynamicMemoryAllocation/Exercises/3.stock.cpp | HuangStomach/Cpp-primer-plus | c8b2b90f10057e72da3ab570da7cc39220c88f70 | [
"MIT"
] | 1 | 2019-09-18T11:31:31.000Z | 2019-09-22T04:47:31.000Z | 12.Classes&DynamicMemoryAllocation/Exercises/3.stock.cpp | HuangStomach/Cpp-primer-plus | c8b2b90f10057e72da3ab570da7cc39220c88f70 | [
"MIT"
] | null | null | null | #include <iostream>
#include "3.stock.h"
Stock::Stock() {
std::cout << "Default\n";
company = new char[strlen("no name") + 1];
strcpy(company, "no name");
shares = 0;
share_val = 0.0;
total_val = 0.0;
}
Stock::Stock(const char * co, long n, double pr) {
std::cout << "Constructor using " << co << "\n";
int len = strlen(co);
company = new char[len + 1];
strcpy(company, co);
shares = n >= 0 ? n : 0;
share_val = pr;
set_tot();
}
Stock::~Stock() {
delete[] company;
std::cout << "Bye." << "!\n";
}
void Stock::buy(long num, double price) {
if (num < 0) {
std::cout << "negative" << std::endl;
}
else {
shares += num;
share_val = price;
set_tot();
}
}
void Stock::sell(long num, double price) {
using std::cout;
using std::endl;
if (num < 0 || num > shares) {
cout << "negative" << endl;
return;
}
shares -= num;
share_val = price;
set_tot();
}
void Stock::update(double price) {
share_val = price;
set_tot();
}
const Stock & Stock::topval(const Stock & s) const {
return s.total_val > total_val ? s : *this;
}
std::ostream & operator<<(std::ostream & os, const Stock & s) {
os << "Company: " << s.company
<< " Shares: " << s.shares << "\n"
<< "Share Price: $" << s.share_val
<< " Total Worth: $" << s.total_val << "\n";
return os;
}
| 21.432836 | 63 | 0.520195 | HuangStomach |
681da69852f2e04e8ec972ea255dc83edc65a06a | 1,632 | cc | C++ | ETI06F3.cc | hkktr/POLSKI-SPOJ | 59f7e0be99fca6532681c2ca01c8a7d97c6b5eed | [
"Unlicense"
] | 1 | 2021-02-01T11:21:56.000Z | 2021-02-01T11:21:56.000Z | ETI06F3.cc | hkktr/POLSKI-SPOJ | 59f7e0be99fca6532681c2ca01c8a7d97c6b5eed | [
"Unlicense"
] | null | null | null | ETI06F3.cc | hkktr/POLSKI-SPOJ | 59f7e0be99fca6532681c2ca01c8a7d97c6b5eed | [
"Unlicense"
] | 1 | 2022-01-28T15:25:45.000Z | 2022-01-28T15:25:45.000Z | // C++14 (gcc 8.3)
#include <algorithm>
#include <iostream>
#include <vector>
class Graph {
public:
Graph(int vertices) : vertices_{vertices} {
adjacency_list_.resize(vertices_);
}
void AddEdge(int a, int b) { adjacency_list_[a].push_back(b); }
std::vector<int> ConnectedComponents() {
std::vector<char> visited(vertices_, false);
std::vector<int> connected_components;
for (int v{0}; v < vertices_; ++v) {
if (!visited[v]) {
int count{0};
ConnectedComponentsUtility(v, visited, count);
if (count > 0) connected_components.push_back(count);
}
}
return connected_components;
}
private:
int vertices_;
std::vector<std::vector<int>> adjacency_list_;
void ConnectedComponentsUtility(int v, std::vector<char>& visited,
int& count) {
visited[v] = true;
++count;
for (int u : adjacency_list_[v]) {
if (!visited[u]) {
ConnectedComponentsUtility(u, visited, count);
}
}
}
};
int main() {
int n;
std::cin >> n;
Graph graph(n);
for (int i{0}; i < n; ++i) {
for (int j{0}; j < n; ++j) {
bool acquaintance;
std::cin >> acquaintance;
if (acquaintance) graph.AddEdge(i, j);
}
}
std::vector<int> connected_components{graph.ConnectedComponents()};
if (connected_components.size() != 3) {
std::cout << "NIE\n";
} else {
std::sort(connected_components.begin(), connected_components.end());
std::cout << "TAK";
for (int count : connected_components) {
std::cout << " " << count;
}
std::cout << "\n";
}
return 0;
} | 22.356164 | 72 | 0.58701 | hkktr |
68217ed14129fd41ec911faa7874ca14d18ae343 | 995 | hpp | C++ | src/Luddite/Utilities/YamlParsers.hpp | Aquaticholic/Luddite-Engine | 66584fa31ee75b0cdebabe88cdfa2431d0e0ac2f | [
"Apache-2.0"
] | 1 | 2021-06-03T05:46:46.000Z | 2021-06-03T05:46:46.000Z | src/Luddite/Utilities/YamlParsers.hpp | Aquaticholic/Luddite-Engine | 66584fa31ee75b0cdebabe88cdfa2431d0e0ac2f | [
"Apache-2.0"
] | null | null | null | src/Luddite/Utilities/YamlParsers.hpp | Aquaticholic/Luddite-Engine | 66584fa31ee75b0cdebabe88cdfa2431d0e0ac2f | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "Luddite/Core/pch.hpp"
#include "Luddite/Graphics/Color.hpp"
void operator >>(const YAML::Node& node, float& f);
void operator >>(const YAML::Node& node, int32_t& i);
void operator >>(const YAML::Node& node, uint32_t& u);
void operator >>(const YAML::Node& node, glm::vec2& v);
void operator >>(const YAML::Node& node, glm::vec3& v);
void operator >>(const YAML::Node& node, glm::vec4& v);
void operator >>(const YAML::Node& node, glm::ivec2& v);
void operator >>(const YAML::Node& node, glm::ivec3& v);
void operator >>(const YAML::Node& node, glm::ivec4& v);
void operator >>(const YAML::Node& node, glm::uvec2& v);
void operator >>(const YAML::Node& node, glm::uvec3& v);
void operator >>(const YAML::Node& node, glm::uvec4& v);
void operator >>(const YAML::Node& node, glm::mat3& m);
void operator >>(const YAML::Node& node, glm::mat4& m);
void operator >>(const YAML::Node& node, Luddite::ColorRGB& c);
void operator >>(const YAML::Node& node, Luddite::ColorRGBA& c);
| 49.75 | 64 | 0.681407 | Aquaticholic |
6822d1a77aa7f6e4f374c36b11d3bd13fa35b860 | 4,484 | cpp | C++ | src/QtFuzzy/nFuzzyVariable.cpp | Vladimir-Lin/QtFuzzy | 185869384f3ce9d3a801080b675bae8ed6c5fb12 | [
"MIT"
] | null | null | null | src/QtFuzzy/nFuzzyVariable.cpp | Vladimir-Lin/QtFuzzy | 185869384f3ce9d3a801080b675bae8ed6c5fb12 | [
"MIT"
] | null | null | null | src/QtFuzzy/nFuzzyVariable.cpp | Vladimir-Lin/QtFuzzy | 185869384f3ce9d3a801080b675bae8ed6c5fb12 | [
"MIT"
] | null | null | null | #include <qtfuzzy.h>
N::Fuzzy::Variable:: Variable (
const QString & name ,
double minimum ,
double maximum )
: Object ( 0 , None )
, _name ( name )
, _minimum ( minimum )
, _maximum ( maximum )
, Name ( "" )
{
}
N::Fuzzy::Variable::Variable(const Variable & copy)
{
uuid = copy.uuid ;
type = copy.type ;
Name = copy.Name ;
nFullLoop ( i , copy.numberOfTerms() ) {
addTerm ( copy.getTerm(i)->copy() ) ;
} ;
}
N::Fuzzy::Variable::~Variable(void)
{
nFullLoop ( i , _terms . size () ) {
delete _terms.at(i) ;
} ;
}
void N::Fuzzy::Variable::setName(const QString & n)
{
_name = n ;
}
QString N::Fuzzy::Variable::getName(void) const
{
return _name ;
}
void N::Fuzzy::Variable::setRange(double minimum,double maximum)
{
_minimum = minimum ;
_maximum = maximum ;
}
void N::Fuzzy::Variable::setMinimum(double minimum)
{
_minimum = minimum ;
}
double N::Fuzzy::Variable::getMinimum(void) const
{
return _minimum ;
}
void N::Fuzzy::Variable::setMaximum(double maximum)
{
_maximum = maximum ;
}
double N::Fuzzy::Variable::getMaximum(void) const
{
return _maximum ;
}
QString N::Fuzzy::Variable::fuzzify(double x) const
{
QString R ;
QString M ;
QStringList L ;
nFullLoop ( i , _terms.size() ) {
M = Operation :: str ( _terms . at(i)->membership(x) ) ;
R = QString("%1 / %2").arg(M).arg(_terms.at(i)->Name ) ;
L << R ;
} ;
R = "" ;
if (L.count()>0) R = L . join (" + ") ;
return R ;
}
N::Fuzzy::Term * N::Fuzzy::Variable::highestMembership(double x,double * yhighest) const
{
Term * result = NULL ;
double ymax = 0 ;
nFullLoop ( i , _terms.size() ) {
double y = _terms.at(i)->membership(x) ;
if ( Operation :: isGt ( y , ymax ) ) {
ymax = y ;
result = _terms.at(i) ;
} ;
} ;
if (yhighest) (*yhighest) = ymax ;
return result ;
}
QString N::Fuzzy::Variable::toString(void) const
{
QString R ;
QStringList L ;
nFullLoop ( i , _terms.size() ) {
L << _terms.at(i)->toString() ;
} ;
R = QString( "%1 [ %2 ]" )
.arg ( getName() )
.arg ( L.join(", ") ) ;
return R ;
}
void N::Fuzzy::Variable::sort(void)
{
SortByCoG criterion ;
criterion.minimum = _minimum ;
criterion.maximum = _maximum ;
std::sort(_terms.begin(),_terms.end(),criterion) ;
}
void N::Fuzzy::Variable::addTerm(Term * term)
{
_terms . push_back ( term ) ;
}
void N::Fuzzy::Variable::insertTerm(Term * term,int index)
{
_terms . insert ( index , term ) ;
}
N::Fuzzy::Term * N::Fuzzy::Variable::getTerm(int index) const
{
return _terms . at ( index ) ;
}
N::Fuzzy::Term * N::Fuzzy::Variable::getTerm(const QString & name) const
{
nFullLoop ( i , _terms.size() ) {
if (_terms.at(i)->is(name)) {
return _terms.at(i) ;
} ;
} ;
return NULL ;
}
bool N::Fuzzy::Variable::hasTerm(const QString & name) const
{
return NotNull( getTerm(name) ) ;
}
N::Fuzzy::Term * N::Fuzzy::Variable::removeTerm(int index)
{
Term * result ;
result = _terms.at(index) ;
_terms . remove (index) ;
return result ;
}
int N::Fuzzy::Variable::numberOfTerms(void) const
{
return _terms.size() ;
}
const QVector<N::Fuzzy::Term *> & N::Fuzzy::Variable::terms(void) const
{
return _terms ;
}
| 27.012048 | 88 | 0.432649 | Vladimir-Lin |
68277db57fbd8b0ebd116e7a5821b5825d87b3da | 5,244 | cpp | C++ | Source/Readers/HTKDeserializers/MLFBinaryIndexBuilder.cpp | shyamalschandra/CNTK | 0e7a6cd4cc174eab28eaf2ffc660c6380b9e4e2d | [
"MIT"
] | 17,702 | 2016-01-25T14:03:01.000Z | 2019-05-06T09:23:41.000Z | Source/Readers/HTKDeserializers/MLFBinaryIndexBuilder.cpp | shyamalschandra/CNTK | 0e7a6cd4cc174eab28eaf2ffc660c6380b9e4e2d | [
"MIT"
] | 3,489 | 2016-01-25T13:32:09.000Z | 2019-05-03T11:29:15.000Z | Source/Readers/HTKDeserializers/MLFBinaryIndexBuilder.cpp | shyamalschandra/CNTK | 0e7a6cd4cc174eab28eaf2ffc660c6380b9e4e2d | [
"MIT"
] | 5,180 | 2016-01-25T14:02:12.000Z | 2019-05-06T04:24:28.000Z | //
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
//
#include "stdafx.h"
#define _CRT_SECURE_NO_WARNINGS
#define _SCL_SECURE_NO_WARNINGS
#include "MLFBinaryIndexBuilder.h"
#include "MLFUtils.h"
#include "ReaderUtil.h"
namespace CNTK {
using namespace std;
MLFBinaryIndexBuilder::MLFBinaryIndexBuilder(const FileWrapper& input, CorpusDescriptorPtr corpus)
: IndexBuilder(input)
{
IndexBuilder::SetCorpus(corpus);
IndexBuilder::SetChunkSize(g_64MB);
if (m_corpus == nullptr)
InvalidArgument("MLFBinaryIndexBuilder: corpus descriptor was not specified.");
// MLF index builder does not need to map sequence keys to locations,
// deserializer will do that instead, set primary to true to skip that step.
m_primary = true;
}
/*virtual*/ wstring MLFBinaryIndexBuilder::GetCacheFilename() /*override*/
{
if (m_isCacheEnabled && !m_corpus->IsNumericSequenceKeys() && !m_corpus->IsHashingEnabled())
InvalidArgument("Index caching is not supported for non-numeric sequence keys "
"using in a corpus with disabled hashing.");
wstringstream wss;
wss << m_input.Filename() << "."
<< (m_corpus->IsNumericSequenceKeys() ? "1" : "0") << "."
<< (m_corpus->IsHashingEnabled() ? std::to_wstring(CorpusDescriptor::s_hashVersion) : L"0") << "."
<< L"v" << IndexBuilder::s_version << "."
<< L"cache";
return wss.str();
}
bool readUtteranceLabel(short modelVersion, BufferedFileReader& reader, vector<char>& buffer, std::string& out)
{
bool result = false;
if (modelVersion == 1)
{
result = reader.TryReadBinarySegment(sizeof(uint), buffer.data());
uint uttrKey = *(uint*)buffer.data();
out = std::to_string(uttrKey);
}
else if (modelVersion == 2)
{
result = reader.TryReadBinarySegment(sizeof(ushort), buffer.data());
if (!result)
return false;
ushort uttLabelLength = *(ushort*)buffer.data();
result = result && reader.TryReadBinarySegment(sizeof(char) * uttLabelLength, buffer.data());
if (!result)
return false;
out = std::string(buffer.data()).substr(0, uttLabelLength);
if (uttLabelLength > MAX_UTTERANCE_LABEL_LENGTH)
RuntimeError("Utterance label length is greater than limit %hu: %s", uttLabelLength, out.c_str());
}
else
{
RuntimeError("Not supported MLF model version.");
}
return result;
}
// Building an index of the MLF file:
// MLF file -> MLF Header [MLF Utterance]+
// MLF Utterance -> Key EOL [Frame Range EOL]+ "." EOL
// MLF file should start with the MLF header (State::Header -> State:UtteranceKey).
// Each utterance starts with an utterance key (State::UtteranceKey -> State::UtteranceFrames).
// End of utterance is indicated by a single dot on a line (State::UtteranceFrames -> State::UtteranceKey)
/*virtual*/ void MLFBinaryIndexBuilder::Populate(shared_ptr<Index>& index) /*override*/
{
m_input.CheckIsOpenOrDie();
index->Reserve(filesize(m_input.File()));
BufferedFileReader reader(m_bufferSize, m_input);
if (reader.Empty())
RuntimeError("Input file is empty");
if (!m_corpus)
RuntimeError("MLFBinaryIndexBuilder: corpus descriptor was not specified.");
vector<char> buffer(MAX_UTTERANCE_LABEL_LENGTH);
// Validate file label
reader.TryReadBinarySegment(3, buffer.data());
std::string mlfLabel(buffer.data(),3);
if (mlfLabel != MLF_BIN_LABEL)
RuntimeError("MLFBinaryIndexBuilder: MLF binary file is malformed.");
//Validate MLF format version
reader.TryReadBinarySegment(sizeof(short), buffer.data());
short modelVersion = *(short*)buffer.data();
// Iterate over the bin MLF
string uttrKey;
while (readUtteranceLabel(modelVersion, reader, buffer, uttrKey))
{
auto uttrId = m_corpus->KeyToId(uttrKey);
reader.TryReadBinarySegment(sizeof(uint), buffer.data());
uint uttrFrameCount = *(uint*)buffer.data();
auto sequenceStartOffset = reader.GetFileOffset();
// Read size of this uttrs
reader.TryReadBinarySegment(sizeof(ushort), buffer.data());
ushort uttrSamplesCount = *(ushort*)buffer.data();
// sample count, senone/count pairs
size_t uttrSize =sizeof(ushort) + uttrSamplesCount * 2 * sizeof(ushort);
IndexedSequence sequence;
sequence.SetKey(uttrId)
.SetNumberOfSamples(uttrFrameCount)
.SetOffset(sequenceStartOffset)
.SetSize(uttrSize);
index->AddSequence(sequence);
reader.SetFileOffset(reader.GetFileOffset() + uttrSamplesCount * 2 * sizeof(ushort));
}
}
}
| 37.726619 | 115 | 0.61804 | shyamalschandra |
68280ca358bc4ed9c6da4e3744c99967dd88af84 | 3,065 | cpp | C++ | test/CpuOperations/BCHGTest.cpp | PaulTrampert/GenieSys | 637e7f764bc7faac8d0b5afcf22646e200562f6a | [
"MIT"
] | null | null | null | test/CpuOperations/BCHGTest.cpp | PaulTrampert/GenieSys | 637e7f764bc7faac8d0b5afcf22646e200562f6a | [
"MIT"
] | 82 | 2020-12-17T04:03:10.000Z | 2022-03-24T17:54:28.000Z | test/CpuOperations/BCHGTest.cpp | PaulTrampert/GenieSys | 637e7f764bc7faac8d0b5afcf22646e200562f6a | [
"MIT"
] | null | null | null | //
// Created by paul.trampert on 4/4/2021.
//
#include <gtest/gtest.h>
#include <GenieSys/CpuOperations/BCHG.h>
#include <GenieSys/Bus.h>
struct BCHGTest : testing::Test {
GenieSys::M68kCpu* cpu;
GenieSys::Bus bus;
GenieSys::BCHG* subject;
BCHGTest() {
cpu = bus.getCpu();
subject = new GenieSys::BCHG(cpu, &bus);
}
~BCHGTest() override {
delete subject;
}
};
TEST_F(BCHGTest, SpecificityIsTen) {
ASSERT_EQ(10, subject->getSpecificity());
}
TEST_F(BCHGTest, DisassembleImmediate) {
cpu->setPc(20);
bus.writeWord(20, 0x0003);
ASSERT_EQ("BCHG $03,D7", subject->disassemble(0b0000100000000111));
}
TEST_F(BCHGTest, DisassembleDataRegister) {
ASSERT_EQ("BCHG D2,D7", subject->disassemble(0b0000010100000111));
}
TEST_F(BCHGTest, ImmModeSetsZeroFlag_WhenSpecifiedBitIsZero) {
cpu->setDataRegister(0, (uint32_t)0x00000000);
cpu->setCcrFlags(GenieSys::CCR_CARRY | GenieSys::CCR_EXTEND | GenieSys::CCR_NEGATIVE | GenieSys::CCR_OVERFLOW);
cpu->setPc(20);
bus.writeWord(20, 0x0003);
uint8_t cycles = subject->execute(0b0000100000000000);
ASSERT_EQ(12, cycles);
ASSERT_EQ((GenieSys::CCR_CARRY | GenieSys::CCR_EXTEND | GenieSys::CCR_NEGATIVE | GenieSys::CCR_OVERFLOW | GenieSys::CCR_ZERO), cpu->getCcrFlags());
ASSERT_EQ(8, cpu->getDataRegister(0));
}
TEST_F(BCHGTest, ImmModeDoesNotSetZeroFlag_WhenSpecifiedBitIsNotZero) {
cpu->setDataRegister(0, (uint32_t)0b00000000000000000000000000001000);
cpu->setCcrFlags(GenieSys::CCR_CARRY | GenieSys::CCR_EXTEND | GenieSys::CCR_NEGATIVE | GenieSys::CCR_OVERFLOW);
cpu->setPc(20);
bus.writeWord(20, 0x0003);
uint8_t cycles = subject->execute(0b0000100000000000);
ASSERT_EQ(12, cycles);
ASSERT_EQ((GenieSys::CCR_CARRY | GenieSys::CCR_EXTEND | GenieSys::CCR_NEGATIVE | GenieSys::CCR_OVERFLOW), cpu->getCcrFlags());
ASSERT_EQ(0, cpu->getDataRegister(0));
}
TEST_F(BCHGTest, RegModeSetsZeroFlag_WhenSpecifiedBitIsZero) {
cpu->setDataRegister(0, (uint32_t)0x00000000);
cpu->setCcrFlags(GenieSys::CCR_CARRY | GenieSys::CCR_EXTEND | GenieSys::CCR_NEGATIVE | GenieSys::CCR_OVERFLOW);
cpu->setDataRegister(2, (uint32_t)35);
uint8_t cycles = subject->execute(0b0000010100000000);
ASSERT_EQ(8, cycles);
ASSERT_EQ((GenieSys::CCR_CARRY | GenieSys::CCR_EXTEND | GenieSys::CCR_NEGATIVE | GenieSys::CCR_OVERFLOW | GenieSys::CCR_ZERO), cpu->getCcrFlags());
ASSERT_EQ(8, cpu->getDataRegister(0));
}
TEST_F(BCHGTest, RegModeDoesNotSetZeroFlag_WhenSpecifiedBitIsNotZero) {
cpu->setDataRegister(0, (uint32_t)0b00000000000000000000000000001000);
cpu->setCcrFlags(GenieSys::CCR_CARRY | GenieSys::CCR_EXTEND | GenieSys::CCR_NEGATIVE | GenieSys::CCR_OVERFLOW);
cpu->setDataRegister(2, (uint32_t)35);
uint8_t cycles = subject->execute(0b0000010100000000);
ASSERT_EQ(8, cycles);
ASSERT_EQ((GenieSys::CCR_CARRY | GenieSys::CCR_EXTEND | GenieSys::CCR_NEGATIVE | GenieSys::CCR_OVERFLOW), cpu->getCcrFlags());
ASSERT_EQ(0, cpu->getDataRegister(0));
} | 34.055556 | 151 | 0.72398 | PaulTrampert |
68292e8a8ea099595f63a41b270e1210d757bda9 | 2,210 | cpp | C++ | omp1.cpp | jrengdahl/bmomp | 3c00f0e599c127504e47a0b35fdb8dbd85f9ebc4 | [
"BSD-3-Clause"
] | null | null | null | omp1.cpp | jrengdahl/bmomp | 3c00f0e599c127504e47a0b35fdb8dbd85f9ebc4 | [
"BSD-3-Clause"
] | null | null | null | omp1.cpp | jrengdahl/bmomp | 3c00f0e599c127504e47a0b35fdb8dbd85f9ebc4 | [
"BSD-3-Clause"
] | null | null | null | // A test program for experiments with OpenMP.
// omp1.cpp tests
// "#pragma omp parallel for"
#include <stdint.h>
#include <stdio.h>
#include "exports.hpp"
#include "thread.hpp"
#include "threadFIFO.hpp"
#include "libgomp.hpp"
#include "omp.h"
// The DeferFIFO used by yield, for rudimentary time-slicing.
// Note that the only form of "time-slicing" occurs when a thread
// voluntarily calls "yield" to temporarily give up the CPU
// to other threads.
threadFIFO<DEFER_FIFO_DEPTH> DeferFIFO;
// forward declaration of the test thread
// We want the test thread to be later in the proram so that "start" is at the beginning of the binary,
// so we can say "go 24000000" and not have to look up the entry point in the map.
void test();
// the stack for the test thread
char stack[2048];
// this is the entry point
// we want it to be located at the beginning of the binary
extern "C"
int start(int argc, char *const argv[])
{
app_startup(argv); // init the u-boot API
Thread::init(); // init the bare metal threading system
libgomp_init(); // init OpenMP
Thread::spawn(test, stack); // spawn the test thread
// The background loop.
// Loop until the test thread terminates.
// Note that this code will only spin if
// -- all threads have yielded or suspended, or
// -- the test thread has terminated.
while(!Thread::done(stack)) // while the test thread is stil running
{
undefer(); // keep trying to wake threads
}
printf("test complete\n");
return (0);
}
#define LIMIT 32
void test()
{
unsigned array[LIMIT];
printf("hello, world!\n");
#pragma omp parallel for num_threads(LIMIT)
for(int i=0; i<LIMIT; i++)
{
array[i] = omp_get_thread_num(); // fill an array with the number of the thread that procsed each element of the array
}
for(int i=0; i<LIMIT; i++)
{
printf("%u ", array[i]); // print the array
}
printf("\n");
}
| 27.625 | 141 | 0.589593 | jrengdahl |
6829bd8c63bcfd90ba5752091106328991fa11b0 | 404 | hpp | C++ | hw3/tmpl/src-cpp/include/AST/UnaryOperator.hpp | idoleat/P-Language-Compiler-CourseProject | 57db735b349a0a3a30d78b927953e2d44b7c7d53 | [
"MIT"
] | 7 | 2020-09-10T16:54:49.000Z | 2022-03-15T12:39:23.000Z | hw3/tmpl/src-cpp/include/AST/UnaryOperator.hpp | idoleat/simple-P-compiler | 57db735b349a0a3a30d78b927953e2d44b7c7d53 | [
"MIT"
] | null | null | null | hw3/tmpl/src-cpp/include/AST/UnaryOperator.hpp | idoleat/simple-P-compiler | 57db735b349a0a3a30d78b927953e2d44b7c7d53 | [
"MIT"
] | null | null | null | #ifndef __AST_UNARY_OPERATOR_NODE_H
#define __AST_UNARY_OPERATOR_NODE_H
#include "AST/expression.hpp"
class UnaryOperatorNode : public ExpressionNode {
public:
UnaryOperatorNode(const uint32_t line, const uint32_t col
/* TODO: operator, expression */);
~UnaryOperatorNode() = default;
void print() override;
private:
// TODO: operator, expression
};
#endif
| 21.263158 | 61 | 0.70297 | idoleat |
682aeb16d6533e5bff7e1bbd3aa5831f4aa8dd4d | 1,290 | cpp | C++ | math/kth_root_mod/gen/safe_prime.cpp | tko919/library-checker-problems | 007a3ef79d1a1824e68545ab326d1523d9c05262 | [
"Apache-2.0"
] | 290 | 2019-06-06T22:20:36.000Z | 2022-03-27T12:45:04.000Z | math/kth_root_mod/gen/safe_prime.cpp | tko919/library-checker-problems | 007a3ef79d1a1824e68545ab326d1523d9c05262 | [
"Apache-2.0"
] | 536 | 2019-06-06T18:25:36.000Z | 2022-03-29T11:46:36.000Z | math/kth_root_mod/gen/safe_prime.cpp | tko919/library-checker-problems | 007a3ef79d1a1824e68545ab326d1523d9c05262 | [
"Apache-2.0"
] | 82 | 2019-06-06T18:17:55.000Z | 2022-03-21T07:40:31.000Z | #include "random.h"
#include <iostream>
#include <vector>
#include <cassert>
#include "../params.h"
using namespace std;
using ll = long long;
vector<ll> enum_prime(ll l, ll r) {
vector<int> is_prime(r - l + 1, true);
for (ll i = 2; i * i <= r; i++) {
for (ll j = max(2 * i, (l + i - 1) / i * i); j <= r; j += i) {
assert(l <= j && j <= r);
is_prime[j - l] = false;
}
}
vector<ll> res;
for (ll i = l; i <= r; i++) {
if (2 <= i && is_prime[i - l]) res.push_back(i);
}
return res;
}
bool is_prime(ll a) {
for (ll div = 2; div*div <= a; ++div) {
if (a % div == 0) return false;
}
return true;
}
// Suppose a is prime.
bool is_safeprime(ll a) {
return a>=3 && is_prime((a-1)/2);
}
int main(int, char* argv[]) {
long long seed = atoll(argv[1]);
auto gen = Random(seed);
ll up = gen.uniform((ll)9e8, P_MAX);
vector<ll> primes = enum_prime(up - (ll)5e6, up);
int t = T_MAX;
printf("%d\n", t);
for (int i = 0; i < t; i++) {
ll p = 0;
while (!is_safeprime(p)) p = primes[gen.uniform<ll>(0LL, primes.size() - 1)];
ll y = gen.uniform(0LL, p - 1);
ll k = gen.uniform(0LL, p - 1);
printf("%lld %lld %lld\n", k, y, p);
}
return 0;
}
| 23.454545 | 85 | 0.494574 | tko919 |
682eba30c768c3fd3dcaaef271ea4e7c5c664ea1 | 871 | hpp | C++ | include/daqi/utilities/file_utilities.hpp | hl4/da4qi4 | 9dfb8902427d40b392977b4fd706048ce3ee8828 | [
"Apache-2.0"
] | 166 | 2019-04-15T03:19:31.000Z | 2022-03-26T05:41:12.000Z | include/daqi/utilities/file_utilities.hpp | YangKefan/da4qi4 | 9dfb8902427d40b392977b4fd706048ce3ee8828 | [
"Apache-2.0"
] | 9 | 2019-07-18T06:09:59.000Z | 2021-01-27T04:19:04.000Z | include/daqi/utilities/file_utilities.hpp | YangKefan/da4qi4 | 9dfb8902427d40b392977b4fd706048ce3ee8828 | [
"Apache-2.0"
] | 43 | 2019-07-03T05:41:57.000Z | 2022-02-24T14:16:09.000Z | #ifndef DAQI_FILE_UTILITIES_HPP
#define DAQI_FILE_UTILITIES_HPP
#include <string>
#include "daqi/def/boost_def.hpp"
namespace da4qi4
{
namespace Utilities
{
bool SaveDataToFile(std::string const& data, std::string const& filename_with_path, std::string& err);
bool SaveDataToFile(std::string const& data, fs::path const& filename_with_path, std::string& err);
bool IsFileExists(fs::path const& fullpath);
bool IsFileExists(std::string const& fullpath);
enum class FileOverwriteOptions
{
ignore_success,
ignore_fail,
overwrite
};
std::pair<bool, std::string /*msg*/>
CopyFile(fs::path const& src, fs::path const& dst, FileOverwriteOptions overwrite);
std::pair<bool, std::string /*msg*/>
MoveFile(fs::path const& src, fs::path const& dst, FileOverwriteOptions overwrite);
} //namesapce Utilities
} //namespace da4qi4
#endif // DAQI_FILE_UTILITIES_HPP
| 24.885714 | 102 | 0.75775 | hl4 |
682fc5812863d852f26231283fd91b4c75e0515f | 613 | cpp | C++ | leetcode/Algorithms/reverse-vowels-of-a-string.cpp | Doarakko/competitive-programming | 5ae78c501664af08a3f16c81dbd54c68310adec8 | [
"MIT"
] | 1 | 2017-07-11T16:47:29.000Z | 2017-07-11T16:47:29.000Z | leetcode/Algorithms/reverse-vowels-of-a-string.cpp | Doarakko/Competitive-Programming | 10642a4bd7266c828dd2fc6e311284e86bdf2968 | [
"MIT"
] | 1 | 2021-02-07T09:10:26.000Z | 2021-02-07T09:10:26.000Z | leetcode/Algorithms/reverse-vowels-of-a-string.cpp | Doarakko/Competitive-Programming | 10642a4bd7266c828dd2fc6e311284e86bdf2968 | [
"MIT"
] | null | null | null | class Solution
{
public:
string reverseVowels(string s)
{
vector<int> v;
for (int i = 0; i < s.length(); i++)
{
switch (s[i])
{
case 'a':
case 'i':
case 'u':
case 'e':
case 'o':
case 'A':
case 'I':
case 'U':
case 'E':
case 'O':
v.push_back(i);
}
}
for (int i = 0; i < (int)(v.size() / 2); i++)
{
swap(s[v[i]], s[v[v.size() - 1 - i]]);
}
return s;
}
};
| 19.15625 | 53 | 0.298532 | Doarakko |
682fce5ba95dadeb2a1ba215388d6142c832646d | 583 | hpp | C++ | Include/SA/Input/Base/Axis/Bindings/InputAxisRange.hpp | SapphireSuite/Engine | f29821853aec6118508f31d3e063e83e603f52dd | [
"MIT"
] | 1 | 2022-01-20T23:17:18.000Z | 2022-01-20T23:17:18.000Z | Include/SA/Input/Base/Axis/Bindings/InputAxisRange.hpp | SapphireSuite/Engine | f29821853aec6118508f31d3e063e83e603f52dd | [
"MIT"
] | null | null | null | Include/SA/Input/Base/Axis/Bindings/InputAxisRange.hpp | SapphireSuite/Engine | f29821853aec6118508f31d3e063e83e603f52dd | [
"MIT"
] | null | null | null | // Copyright (c) 2021 Sapphire's Suite. All Rights Reserved.
#pragma once
#ifndef SAPPHIRE_INPUT_INPUT_AXIS_RANGE_GUARD
#define SAPPHIRE_INPUT_INPUT_AXIS_RANGE_GUARD
#include <SA/Input/Base/Bindings/InputRangeBase.hpp>
#include <SA/Input/Base/Axis/Bindings/InputAxisBinding.hpp>
namespace Sa
{
class InputAxisRange : public InputRangeBase<InputAxisBinding>
{
public:
float minThreshold = 0.0f;
float maxThreshold = 1.0f;
float scale = 1.0f;
using InputRangeBase<InputAxisBinding>::InputRangeBase;
bool Execute(float _value) override final;
};
}
#endif // GUARD
| 20.821429 | 63 | 0.7753 | SapphireSuite |
6830046466209c71aafc249d502ff69efbc46f64 | 373 | cpp | C++ | Math/168. Excel Sheet Column Title.cpp | YuPeize/LeetCode- | b01d00f28e1eedcb04aee9eca984685bd9d52791 | [
"MIT"
] | 2 | 2019-10-28T06:40:09.000Z | 2022-03-09T10:50:06.000Z | Math/168. Excel Sheet Column Title.cpp | sumiya-NJU/LeetCode | 8e6065e160da3db423a51aaf3ae53b2023068d05 | [
"MIT"
] | null | null | null | Math/168. Excel Sheet Column Title.cpp | sumiya-NJU/LeetCode | 8e6065e160da3db423a51aaf3ae53b2023068d05 | [
"MIT"
] | 1 | 2018-12-09T13:46:06.000Z | 2018-12-09T13:46:06.000Z | /*
author: ypz
*/
class Solution {
public:
string convertToTitle(int n) {
string ans;
while(n != 0) {
char temp;
if(n%26 == 0) {
temp = 'Z';
n -= 1;
}
else temp = 'A' + n%26 - 1;
ans = temp + ans;
n = n / 26;
}
return ans;
}
};
| 16.954545 | 39 | 0.335121 | YuPeize |
6834eaa61ab72647f1f8a23f2265d6a14a8ae59a | 2,459 | cpp | C++ | luogu/p1042.cpp | ajidow/Answers_of_OJ | 70e0c02d9367c3a154b83a277edbf158f32484a3 | [
"MIT"
] | null | null | null | luogu/p1042.cpp | ajidow/Answers_of_OJ | 70e0c02d9367c3a154b83a277edbf158f32484a3 | [
"MIT"
] | null | null | null | luogu/p1042.cpp | ajidow/Answers_of_OJ | 70e0c02d9367c3a154b83a277edbf158f32484a3 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstdio>
using namespace std;
char c;
// int hua,sb;
// int huawin,sbwin;
int tmphua,tmpsb;
int cnt = 0;
int get[100000];
int main(int argc, char const *argv[])
{
// cout << "11:0" << endl;
while(1)
{
c = getchar();
if (c == 'E')
{
cout << tmphua << ":" << tmpsb << endl;
break;
}else if (c == 'W'){
// hua++;
tmphua++;
cnt++;
get[cnt] = 1;
}else{
// sb++;
tmpsb++;
cnt++;
get[cnt] = -1;
}
if (tmphua >= 11 && tmphua - tmpsb >= 2)
{
cout << tmphua << ":" << tmpsb << endl;
tmphua = 0;
tmpsb = 0;
}else if (tmpsb >= 11 && tmpsb - tmphua >= 2)
{
cout << tmphua << ":" << tmpsb << endl;
tmphua = 0;
tmpsb = 0;
}
}
cout << endl;
tmphua = 0;
tmpsb = 0;
// cout << "21:0" << endl;
for (int i = 1;i <= cnt; ++i)
{
if (get[i] == 1){
tmphua++;
}else{
tmpsb++;
}
if (tmphua >= 21 && tmphua - tmpsb >= 2)
{
cout << tmphua << ":" << tmpsb << endl;
tmpsb = 0;
tmphua = 0;
}else if (tmpsb >= 21 && tmpsb - tmphua >= 2)
{
cout << tmphua << ":" << tmpsb << endl;
tmpsb = 0;
tmphua = 0;
}
}
cout << tmphua << ":" << tmpsb;
return 0;
}
// #include<iostream>
// using namespace std;
// char ch;
// bool g[1000000];//记录比分,true表示华华胜,false表示输;
// int a,tmpsb,cnt;//a,tmpsb存储比分;
// int main()
// {
// while(1)
// {
// ch=getchar();//一个字符一个字符读入;
// if(ch=='E')
// {
// cout<<a<<":"<<tmpsb<<endl;//输出当前比分;
// break;
// }
// if(ch=='W')
// {
// a++;cnt++;g[cnt]=true;//存到数组中,以便算21分制时再模拟一次;
// }
// if(ch=='L')
// {
// tmpsb++;cnt++;
// }
// if(a>=11&&a-tmpsb>=2)
// {
// cout<<a<<":"<<tmpsb<<endl;
// a=0;tmpsb=0;
// }
// if(tmpsb>=11&&tmpsb-a>=2)
// {
// cout<<a<<":"<<tmpsb<<endl;
// a=0;tmpsb=0;
// }
// }
// a=0;tmpsb=0;cout<<endl;//归零;
// for(int i=1;i<=cnt;i++)//过程与之前类似;
// {
// if(g[i]) a++;
// else tmpsb++;
// if(a>=21&&a-tmpsb>=2)
// {
// cout<<a<<":"<<tmpsb<<endl;
// a=0;tmpsb=0;
// }
// if(tmpsb>=21&&tmpsb-a>=2)
// {
// cout<<a<<":"<<tmpsb<<endl;
// a=0;tmpsb=0;
// }
// }
// cout<<a<<":"<<tmpsb<<endl;//输出最后一局比分;
// return 0;
// } | 19.362205 | 60 | 0.395283 | ajidow |
6835e1f3603467bf8ff17f87fc84f97f267c2969 | 1,997 | cpp | C++ | SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_SingleSwitchProgramWidget.cpp | Gin890/Arduino-Source | 9047ff584010d8ddc3558068874f16fb3c7bb46d | [
"MIT"
] | 1 | 2022-03-29T18:51:49.000Z | 2022-03-29T18:51:49.000Z | SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_SingleSwitchProgramWidget.cpp | Gin890/Arduino-Source | 9047ff584010d8ddc3558068874f16fb3c7bb46d | [
"MIT"
] | null | null | null | SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_SingleSwitchProgramWidget.cpp | Gin890/Arduino-Source | 9047ff584010d8ddc3558068874f16fb3c7bb46d | [
"MIT"
] | null | null | null | /* Single Switch Program Template
*
* From: https://github.com/PokemonAutomation/Arduino-Source
*
*/
#include "CommonFramework/Tools/BlackBorderCheck.h"
#include "NintendoSwitch_SingleSwitchProgramWidget.h"
#include <iostream>
using std::cout;
using std::endl;
namespace PokemonAutomation{
namespace NintendoSwitch{
SingleSwitchProgramWidget::~SingleSwitchProgramWidget(){
RunnableSwitchProgramWidget::request_program_stop();
join_program_thread();
}
SingleSwitchProgramWidget* SingleSwitchProgramWidget::make(
QWidget& parent,
SingleSwitchProgramInstance& instance,
PanelHolder& holder
){
SingleSwitchProgramWidget* widget = new SingleSwitchProgramWidget(parent, instance, holder);
widget->construct();
return widget;
}
void SingleSwitchProgramWidget::run_switch_program(const ProgramInfo& info){
SingleSwitchProgramInstance& instance = static_cast<SingleSwitchProgramInstance&>(m_instance);
CancellableHolder<CancellableScope> scope;
SingleSwitchProgramEnvironment env(
info,
scope,
m_logger,
m_current_stats.get(), m_historical_stats.get(),
system().logger(),
sanitize_botbase(system().botbase()),
system().camera(),
system().overlay(),
system().audio()
);
connect(
&env, &ProgramEnvironment::set_status,
this, &SingleSwitchProgramWidget::status_update
);
{
std::lock_guard<std::mutex> lg(m_lock);
m_scope = &scope;
}
try{
start_program_video_check(env.console, instance.descriptor().feedback());
BotBaseContext context(scope, env.console.botbase());
instance.program(env, context);
std::lock_guard<std::mutex> lg(m_lock);
m_scope = nullptr;
}catch (...){
env.update_stats();
std::lock_guard<std::mutex> lg(m_lock);
m_scope = nullptr;
throw;
}
}
}
}
| 26.626667 | 99 | 0.657987 | Gin890 |
68383cad3387296c9c36cca5935b428b4f51c87f | 9,038 | cpp | C++ | Grbl_Esp32/src/Spindles/YL620Spindle.cpp | ghjklzx/ESP32-E-support | 03e081d3f6df613ff1f215ba311bec3fb7baa8ed | [
"MIT"
] | 49 | 2021-12-15T12:57:20.000Z | 2022-02-07T12:22:10.000Z | Firmware/Grbl_Esp32-main/Grbl_Esp32/src/Spindles/YL620Spindle.cpp | pspadale/Onyx-Stepper-Motherboard | e94e6cc2e40869f6ee395a3f6e52c81307373971 | [
"MIT"
] | null | null | null | Firmware/Grbl_Esp32-main/Grbl_Esp32/src/Spindles/YL620Spindle.cpp | pspadale/Onyx-Stepper-Motherboard | e94e6cc2e40869f6ee395a3f6e52c81307373971 | [
"MIT"
] | 10 | 2021-12-15T12:57:24.000Z | 2022-01-17T22:47:33.000Z | #include "YL620Spindle.h"
/*
YL620Spindle.cpp
This is for a Yalang YL620/YL620-A VFD based spindle to be controlled via RS485 Modbus RTU.
Part of Grbl_ESP32
2021 - Marco Wagner
Grbl 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.
Grbl 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 Grbl. If not, see <http://www.gnu.org/licenses/>.
WARNING!!!!
VFDs are very dangerous. They have high voltages and are very powerful
Remove power before changing bits.
=============================================================================================================
Configuration required for the YL620
Parameter number Description Value
-------------------------------------------------------------------------------
P00.00 Main frequency 400.00Hz (match to your spindle)
P00.01 Command source 3
P03.00 RS485 Baud rate 3 (9600)
P03.01 RS485 address 1
P03.02 RS485 protocol 2
P03.08 Frequency given lower limit 100.0Hz (match to your spindle cooling-type)
===============================================================================================================
RS485 communication is standard Modbus RTU
Therefore, the following operation codes are relevant:
0x03: read single holding register
0x06: write single holding register
Holding register address Description
---------------------------------------------------------------------------
0x0000 main frequency
0x0308 frequency given lower limit
0x2000 command register (further information below)
0x2001 Modbus485 frequency command (x0.1Hz => 2500 = 250.0Hz)
0x200A Target frequency
0x200B Output frequency
0x200C Output current
Command register at holding address 0x2000
--------------------------------------------------------------------------
bit 1:0 b00: No function
b01: shutdown command
b10: start command
b11: Jog command
bit 3:2 reserved
bit 5:4 b00: No function
b01: Forward command
b10: Reverse command
b11: change direction
bit 7:6 b00: No function
b01: reset an error flag
b10: reset all error flags
b11: reserved
*/
namespace Spindles {
YL620::YL620() : VFD() {}
void YL620::direction_command(SpindleState mode, ModbusCommand& data) {
// NOTE: data length is excluding the CRC16 checksum.
data.tx_length = 6;
data.rx_length = 6;
// data.msg[0] is omitted (modbus address is filled in later)
data.msg[1] = 0x06; // 06: write output register
data.msg[2] = 0x20; // 0x2000: command register address
data.msg[3] = 0x00;
data.msg[4] = 0x00; // High-Byte of command always 0x00
switch (mode) {
case SpindleState::Cw:
data.msg[5] = 0x12; // Start in forward direction
break;
case SpindleState::Ccw:
data.msg[5] = 0x22; // Start in reverse direction
break;
default: // SpindleState::Disable
data.msg[5] = 0x01; // Disable spindle
break;
}
}
void YL620::set_speed_command(uint32_t rpm, ModbusCommand& data) {
// NOTE: data length is excluding the CRC16 checksum.
data.tx_length = 6;
data.rx_length = 6;
// We have to know the max RPM before we can set the current RPM:
auto max_rpm = this->_max_rpm;
auto max_frequency = this->_maxFrequency;
uint16_t freqFromRPM = (uint16_t(rpm) * uint16_t(max_frequency)) / uint16_t(max_rpm);
#ifdef VFD_DEBUG_MODE
grbl_msg_sendf(CLIENT_SERIAL, MsgLevel::Info, "For %d RPM the output frequency is set to %d Hz*10", int(rpm), int(freqFromRPM));
#endif
data.msg[1] = 0x06;
data.msg[2] = 0x20;
data.msg[3] = 0x01;
data.msg[4] = uint8_t(freqFromRPM >> 8);
data.msg[5] = uint8_t(freqFromRPM & 0xFF);
}
VFD::response_parser YL620::initialization_sequence(int index, ModbusCommand& data) {
if (index == -1) {
// NOTE: data length is excluding the CRC16 checksum.
data.tx_length = 6;
data.rx_length = 5;
data.msg[1] = 0x03;
data.msg[2] = 0x03;
data.msg[3] = 0x08;
data.msg[4] = 0x00;
data.msg[5] = 0x01;
// Recv: 01 03 02 03 E8 xx xx
// -- -- = 1000
return [](const uint8_t* response, Spindles::VFD* vfd) -> bool {
auto yl620 = static_cast<YL620*>(vfd);
yl620->_minFrequency = (uint16_t(response[3]) << 8) | uint16_t(response[4]);
#ifdef VFD_DEBUG_MODE
grbl_msg_sendf(CLIENT_SERIAL, MsgLevel::Info, "YL620 allows minimum frequency of %d Hz", int(yl620->_minFrequency));
#endif
return true;
};
} else if (index == -2) {
// NOTE: data length is excluding the CRC16 checksum.
data.tx_length = 6;
data.rx_length = 5;
data.msg[1] = 0x03;
data.msg[2] = 0x00;
data.msg[3] = 0x00;
data.msg[4] = 0x00;
data.msg[5] = 0x01;
// Recv: 01 03 02 0F A0 xx xx
// -- -- = 4000
return [](const uint8_t* response, Spindles::VFD* vfd) -> bool {
auto yl620 = static_cast<YL620*>(vfd);
yl620->_maxFrequency = (uint16_t(response[3]) << 8) | uint16_t(response[4]);
vfd->_min_rpm = uint32_t(yl620->_minFrequency) * uint32_t(vfd->_max_rpm) /
uint32_t(yl620->_maxFrequency); // 1000 * 24000 / 4000 = 6000 RPM.
#ifdef VFD_DEBUG_MODE
grbl_msg_sendf(CLIENT_SERIAL, MsgLevel::Info, "YL620 allows maximum frequency of %d Hz", int(yl620->_maxFrequency));
grbl_msg_sendf(CLIENT_SERIAL,
MsgLevel::Info,
"Configured maxRPM of %d RPM results in minRPM of %d RPM",
int(vfd->_max_rpm),
int(vfd->_min_rpm));
#endif
return true;
};
} else {
return nullptr;
}
}
VFD::response_parser YL620::get_current_rpm(ModbusCommand& data) {
// NOTE: data length is excluding the CRC16 checksum.
data.tx_length = 6;
data.rx_length = 5;
// Send: 01 03 200B 0001
data.msg[1] = 0x03;
data.msg[2] = 0x20;
data.msg[3] = 0x0B;
data.msg[4] = 0x00;
data.msg[5] = 0x01;
// Recv: 01 03 02 05 DC xx xx
// ---- = 1500
return [](const uint8_t* response, Spindles::VFD* vfd) -> bool {
uint16_t freq = (uint16_t(response[3]) << 8) | uint16_t(response[4]);
auto yl620 = static_cast<YL620*>(vfd);
uint16_t rpm = freq * uint16_t(vfd->_max_rpm) / uint16_t(yl620->_maxFrequency);
// Set current RPM value? Somewhere?
vfd->_sync_rpm = rpm;
return true;
};
}
VFD::response_parser YL620::get_current_direction(ModbusCommand& data) {
// NOTE: data length is excluding the CRC16 checksum.
data.tx_length = 6;
data.rx_length = 5;
// Send: 01 03 20 00 00 01
data.msg[1] = 0x03;
data.msg[2] = 0x20;
data.msg[3] = 0x00;
data.msg[4] = 0x00;
data.msg[5] = 0x01;
// Receive: 01 03 02 00 0A xx xx
// ----- status is in 00 0A bit 5:4
// TODO: What are we going to do with this? Update sys.spindle_speed? Update vfd state?
return [](const uint8_t* response, Spindles::VFD* vfd) -> bool { return true; };
}
}
| 38.7897 | 136 | 0.501881 | ghjklzx |
683ba4119670f9dbd36d441fbe7e90e150be3690 | 5,495 | cpp | C++ | crystal/foundation/http/Crypto.cpp | crystal-dataop/crystal | 128e1dcde1ef68cabadab9b16d45f5199f0afe5c | [
"Apache-2.0"
] | 2 | 2020-10-02T03:31:50.000Z | 2020-12-31T09:41:48.000Z | crystal/foundation/http/Crypto.cpp | crystal-dataop/crystal | 128e1dcde1ef68cabadab9b16d45f5199f0afe5c | [
"Apache-2.0"
] | null | null | null | crystal/foundation/http/Crypto.cpp | crystal-dataop/crystal | 128e1dcde1ef68cabadab9b16d45f5199f0afe5c | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2020 Yeolar
*/
#include "crystal/foundation/http/Crypto.h"
#include <iomanip>
#include <vector>
#include <openssl/evp.h>
#include <openssl/md5.h>
#include <openssl/sha.h>
namespace crystal {
std::string Crypto::to_hex_string(const std::string& input) {
std::stringstream hex_stream;
hex_stream << std::hex << std::internal << std::setfill('0');
for (auto& byte : input) {
hex_stream << std::setw(2)
<< static_cast<int>(static_cast<unsigned char>(byte));
}
return hex_stream.str();
}
std::string Crypto::md5(const std::string& input, size_t iterations) {
std::string hash;
hash.resize(128 / 8);
MD5(reinterpret_cast<const unsigned char*>(&input[0]), input.size(),
reinterpret_cast<unsigned char*>(&hash[0]));
for (size_t c = 1; c < iterations; ++c) {
MD5(reinterpret_cast<const unsigned char*>(&hash[0]), hash.size(),
reinterpret_cast<unsigned char*>(&hash[0]));
}
return hash;
}
std::string Crypto::md5(std::istream& stream, size_t iterations) {
MD5_CTX context;
MD5_Init(&context);
std::streamsize read_length;
std::vector<char> buffer(buffer_size);
while ((read_length = stream.read(&buffer[0], buffer_size).gcount()) > 0) {
MD5_Update(&context, buffer.data(), static_cast<size_t>(read_length));
}
std::string hash;
hash.resize(128 / 8);
MD5_Final(reinterpret_cast<unsigned char*>(&hash[0]), &context);
for (size_t c = 1; c < iterations; ++c) {
MD5(reinterpret_cast<const unsigned char*>(&hash[0]), hash.size(),
reinterpret_cast<unsigned char*>(&hash[0]));
}
return hash;
}
std::string Crypto::sha1(const std::string& input, size_t iterations) {
std::string hash;
hash.resize(160 / 8);
SHA1(reinterpret_cast<const unsigned char*>(&input[0]), input.size(),
reinterpret_cast<unsigned char*>(&hash[0]));
for (size_t c = 1; c < iterations; ++c) {
SHA1(reinterpret_cast<const unsigned char*>(&hash[0]), hash.size(),
reinterpret_cast<unsigned char*>(&hash[0]));
}
return hash;
}
std::string Crypto::sha1(std::istream& stream, size_t iterations) {
SHA_CTX context;
SHA1_Init(&context);
std::streamsize read_length;
std::vector<char> buffer(buffer_size);
while ((read_length = stream.read(&buffer[0], buffer_size).gcount()) > 0) {
SHA1_Update(&context, buffer.data(), static_cast<size_t>(read_length));
}
std::string hash;
hash.resize(160 / 8);
SHA1_Final(reinterpret_cast<unsigned char*>(&hash[0]), &context);
for (size_t c = 1; c < iterations; ++c) {
SHA1(reinterpret_cast<const unsigned char*>(&hash[0]), hash.size(),
reinterpret_cast<unsigned char*>(&hash[0]));
}
return hash;
}
std::string Crypto::sha256(const std::string& input, size_t iterations) {
std::string hash;
hash.resize(256 / 8);
SHA256(reinterpret_cast<const unsigned char*>(&input[0]), input.size(),
reinterpret_cast<unsigned char*>(&hash[0]));
for (size_t c = 1; c < iterations; ++c) {
SHA256(reinterpret_cast<const unsigned char*>(&hash[0]), hash.size(),
reinterpret_cast<unsigned char*>(&hash[0]));
}
return hash;
}
std::string Crypto::sha256(std::istream& stream, size_t iterations) {
SHA256_CTX context;
SHA256_Init(&context);
std::streamsize read_length;
std::vector<char> buffer(buffer_size);
while ((read_length = stream.read(&buffer[0], buffer_size).gcount()) > 0) {
SHA256_Update(&context, buffer.data(), static_cast<size_t>(read_length));
}
std::string hash;
hash.resize(256 / 8);
SHA256_Final(reinterpret_cast<unsigned char*>(&hash[0]), &context);
for (size_t c = 1; c < iterations; ++c) {
SHA256(reinterpret_cast<const unsigned char*>(&hash[0]), hash.size(),
reinterpret_cast<unsigned char*>(&hash[0]));
}
return hash;
}
std::string Crypto::sha512(const std::string& input, size_t iterations) {
std::string hash;
hash.resize(512 / 8);
SHA512(reinterpret_cast<const unsigned char*>(&input[0]), input.size(),
reinterpret_cast<unsigned char*>(&hash[0]));
for (size_t c = 1; c < iterations; ++c) {
SHA512(reinterpret_cast<const unsigned char*>(&hash[0]), hash.size(),
reinterpret_cast<unsigned char*>(&hash[0]));
}
return hash;
}
std::string Crypto::sha512(std::istream& stream, size_t iterations) {
SHA512_CTX context;
SHA512_Init(&context);
std::streamsize read_length;
std::vector<char> buffer(buffer_size);
while ((read_length = stream.read(&buffer[0], buffer_size).gcount()) > 0) {
SHA512_Update(&context, buffer.data(), static_cast<size_t>(read_length));
}
std::string hash;
hash.resize(512 / 8);
SHA512_Final(reinterpret_cast<unsigned char*>(&hash[0]), &context);
for (size_t c = 1; c < iterations; ++c) {
SHA512(reinterpret_cast<const unsigned char*>(&hash[0]), hash.size(),
reinterpret_cast<unsigned char*>(&hash[0]));
}
return hash;
}
std::string Crypto::pbkdf2(const std::string& password,
const std::string& salt,
int iterations,
int key_size) {
std::string key;
key.resize(static_cast<size_t>(key_size));
PKCS5_PBKDF2_HMAC_SHA1(password.c_str(), password.size(),
reinterpret_cast<const unsigned char*>(salt.c_str()),
salt.size(),
iterations,
key_size,
reinterpret_cast<unsigned char*>(&key[0]));
return key;
}
} // namespace crystal
| 33.919753 | 78 | 0.647134 | crystal-dataop |
683f82e4ea5d0c5966b1ad32dd95cfea784541a8 | 25,099 | cpp | C++ | octomap/src/testing/test_set_tree_values.cpp | BadgerTechnologies/octomap | cf470ad72aaf7783b6eeef82331f52146557fc09 | [
"BSD-3-Clause"
] | null | null | null | octomap/src/testing/test_set_tree_values.cpp | BadgerTechnologies/octomap | cf470ad72aaf7783b6eeef82331f52146557fc09 | [
"BSD-3-Clause"
] | null | null | null | octomap/src/testing/test_set_tree_values.cpp | BadgerTechnologies/octomap | cf470ad72aaf7783b6eeef82331f52146557fc09 | [
"BSD-3-Clause"
] | null | null | null | #include <memory>
#include <octomap/octomap.h>
#include "testing.h"
using namespace std;
using namespace octomap;
using namespace octomath;
int main(int /*argc*/, char** /*argv*/) {
double res = 0.01;
OcTree value_tree(res);
OcTree value_tree2(res);
OcTree bounds_tree(res);
OcTree tree(res);
OcTree expected_tree(res);
OcTree* null_tree = nullptr;
shared_ptr<OcTree> treep;
OcTreeNode* node;
const key_type center_key = tree.coordToKey(0.0);
std::cout << "\nSetting Tree Values from Other Trees\n===============================\n";
// First, test using empty trees
tree.setTreeValues(null_tree, false, false);
EXPECT_EQ(tree.size(), 0);
EXPECT_EQ(tree.size(), tree.calcNumNodes());
tree.setTreeValues(null_tree, true, false);
EXPECT_EQ(tree.size(), 0);
EXPECT_EQ(tree.size(), tree.calcNumNodes());
tree.setTreeValues(null_tree, true, true);
EXPECT_EQ(tree.size(), 0);
EXPECT_EQ(tree.size(), tree.calcNumNodes());
tree.setTreeValues(&value_tree);
EXPECT_EQ(tree.size(), 0);
EXPECT_EQ(tree.size(), tree.calcNumNodes());
tree.setTreeValues(&value_tree, true);
EXPECT_EQ(tree.size(), 0);
EXPECT_EQ(tree.size(), tree.calcNumNodes());
tree.setTreeValues(&value_tree, true, true);
EXPECT_EQ(tree.size(), 0);
EXPECT_EQ(tree.size(), tree.calcNumNodes());
tree.setTreeValues(&value_tree, &bounds_tree);
EXPECT_EQ(tree.size(), 0);
EXPECT_EQ(tree.size(), tree.calcNumNodes());
tree.setTreeValues(&value_tree, &bounds_tree, true);
EXPECT_EQ(tree.size(), 0);
EXPECT_EQ(tree.size(), tree.calcNumNodes());
tree.setTreeValues(&value_tree, &bounds_tree, true, true);
EXPECT_EQ(tree.size(), 0);
EXPECT_EQ(tree.size(), tree.calcNumNodes());
// Add a node to the value tree but use an empty bounds tree
value_tree.setNodeValue(OcTreeKey(), 1.0);
tree.setTreeValues(&value_tree, &bounds_tree);
EXPECT_EQ(tree.size(), 0);
EXPECT_EQ(tree.size(), tree.calcNumNodes());
tree.setTreeValues(&value_tree, &bounds_tree, true);
EXPECT_EQ(tree.size(), 0);
EXPECT_EQ(tree.size(), tree.calcNumNodes());
tree.setTreeValues(&value_tree, &bounds_tree, true, true);
EXPECT_EQ(tree.size(), 0);
EXPECT_EQ(tree.size(), tree.calcNumNodes());
// Test the case of an empty tree being set to the universe (pruned node at top).
tree.clear();
value_tree.clear();
value_tree.setNodeValueAtDepth(OcTreeKey(), 0, value_tree.getClampingThresMaxLog());
EXPECT_EQ(tree.size(), 0);
tree.setTreeValues(&value_tree);
EXPECT_EQ(tree.size(), 1);
tree.clear();
value_tree.clear();
// Now, test with one leaf in our tree
point3d singlePt(-0.05, -0.02, 1.0);
OcTreeKey singleKey, nextKey;
tree.coordToKeyChecked(singlePt, singleKey);
tree.updateNode(singleKey, true);
tree.setTreeValues(&value_tree);
EXPECT_EQ(tree.size(), tree.getTreeDepth() + 1);
EXPECT_EQ(tree.size(), tree.calcNumNodes());
tree.setTreeValues(&value_tree, true);
EXPECT_EQ(tree.size(), tree.getTreeDepth() + 1);
EXPECT_EQ(tree.size(), tree.calcNumNodes());
tree.setTreeValues(&value_tree, false, true);
EXPECT_EQ(tree.size(), 0);
EXPECT_EQ(tree.size(), tree.calcNumNodes());
tree.updateNode(singleKey, true);
// Since the bounds tree is empty, no change should happen
tree.setTreeValues(&value_tree, &bounds_tree, true, true);
EXPECT_EQ(tree.size(), tree.getTreeDepth() + 1);
EXPECT_EQ(tree.size(), tree.calcNumNodes());
bounds_tree.updateNode(singleKey, true);
tree.setTreeValues(&value_tree, &bounds_tree, false, false);
EXPECT_EQ(tree.size(), tree.getTreeDepth() + 1);
EXPECT_EQ(tree.size(), tree.calcNumNodes());
tree.setTreeValues(&value_tree, &bounds_tree, true, false);
EXPECT_EQ(tree.size(), tree.getTreeDepth() + 1);
EXPECT_EQ(tree.size(), tree.calcNumNodes());
tree.setTreeValues(&value_tree, &bounds_tree, false, true);
// Bounds tree has our key, our tree should be empty now
EXPECT_EQ(tree.size(), 0);
EXPECT_EQ(tree.size(), tree.calcNumNodes());
// Set the bounds tree to everything.
bounds_tree.setNodeValueAtDepth(OcTreeKey(), 0, bounds_tree.getClampingThresMax());
EXPECT_EQ(bounds_tree.size(), 1);
tree.clear();
tree.updateNode(singleKey, true);
tree.setTreeValues(&value_tree, &bounds_tree, false, false);
EXPECT_EQ(tree.size(), tree.getTreeDepth() + 1);
EXPECT_EQ(tree.size(), tree.calcNumNodes());
tree.setTreeValues(&value_tree, &bounds_tree, true, false);
EXPECT_EQ(tree.size(), tree.getTreeDepth() + 1);
EXPECT_EQ(tree.size(), tree.calcNumNodes());
tree.setTreeValues(&value_tree, &bounds_tree, false, true);
// Bounds tree has our key, our tree should be empty now
EXPECT_EQ(tree.size(), 0);
EXPECT_EQ(tree.size(), tree.calcNumNodes());
// Now put a single node in the value tree
value_tree.setNodeValue(singleKey, -1.0);
tree.setNodeValue(singleKey, 1.0);
node = tree.search(singleKey);
EXPECT_TRUE(node);
EXPECT_EQ(1.0, node->getLogOdds());
tree.setTreeValues(&value_tree, true, false);
EXPECT_EQ(tree.size(), tree.getTreeDepth() + 1);
EXPECT_EQ(tree.size(), tree.calcNumNodes());
node = tree.search(singleKey);
EXPECT_TRUE(node);
EXPECT_EQ(1.0, node->getLogOdds());
tree.setTreeValues(&value_tree, false, false);
EXPECT_EQ(tree.size(), tree.getTreeDepth() + 1);
EXPECT_EQ(tree.size(), tree.calcNumNodes());
node = tree.search(singleKey);
EXPECT_TRUE(node);
EXPECT_EQ(-1.0, node->getLogOdds());
tree.setNodeValue(singleKey, 1.0);
tree.setTreeValues(&value_tree, false, true);
EXPECT_EQ(tree.size(), tree.getTreeDepth() + 1);
EXPECT_EQ(tree.size(), tree.calcNumNodes());
node = tree.search(singleKey);
EXPECT_TRUE(node);
EXPECT_EQ(-1.0, node->getLogOdds());
// Now try the same node in the bounds tree.
bounds_tree.clear();
bounds_tree.setNodeValue(singleKey, 1.0);
tree.setNodeValue(singleKey, 1.0);
node = tree.search(singleKey);
EXPECT_TRUE(node);
EXPECT_EQ(1.0, node->getLogOdds());
tree.setTreeValues(&value_tree, &bounds_tree, true, false);
EXPECT_EQ(tree.size(), tree.getTreeDepth() + 1);
EXPECT_EQ(tree.size(), tree.calcNumNodes());
node = tree.search(singleKey);
EXPECT_TRUE(node);
EXPECT_EQ(1.0, node->getLogOdds());
tree.setTreeValues(&value_tree, &bounds_tree, false, false);
EXPECT_EQ(tree.size(), tree.getTreeDepth() + 1);
EXPECT_EQ(tree.size(), tree.calcNumNodes());
node = tree.search(singleKey);
EXPECT_TRUE(node);
EXPECT_EQ(-1.0, node->getLogOdds());
tree.setNodeValue(singleKey, 1.0);
tree.setTreeValues(&value_tree, &bounds_tree, false, true);
EXPECT_EQ(tree.size(), tree.getTreeDepth() + 1);
EXPECT_EQ(tree.size(), tree.calcNumNodes());
node = tree.search(singleKey);
EXPECT_TRUE(node);
EXPECT_EQ(-1.0, node->getLogOdds());
// Set the bounds tree to everything.
bounds_tree.setNodeValueAtDepth(OcTreeKey(), 0, bounds_tree.getClampingThresMax());
EXPECT_EQ(bounds_tree.size(), 1);
tree.setNodeValue(singleKey, 1.0);
node = tree.search(singleKey);
EXPECT_TRUE(node);
EXPECT_EQ(1.0, node->getLogOdds());
tree.setTreeValues(&value_tree, &bounds_tree, true, false);
EXPECT_EQ(tree.size(), tree.getTreeDepth() + 1);
EXPECT_EQ(tree.size(), tree.calcNumNodes());
node = tree.search(singleKey);
EXPECT_TRUE(node);
EXPECT_EQ(1.0, node->getLogOdds());
tree.setTreeValues(&value_tree, &bounds_tree, false, false);
EXPECT_EQ(tree.size(), tree.getTreeDepth() + 1);
EXPECT_EQ(tree.size(), tree.calcNumNodes());
node = tree.search(singleKey);
EXPECT_TRUE(node);
EXPECT_EQ(-1.0, node->getLogOdds());
tree.setNodeValue(singleKey, 1.0);
tree.setTreeValues(&value_tree, &bounds_tree, false, true);
EXPECT_EQ(tree.size(), tree.getTreeDepth() + 1);
EXPECT_EQ(tree.size(), tree.calcNumNodes());
node = tree.search(singleKey);
EXPECT_TRUE(node);
EXPECT_EQ(-1.0, node->getLogOdds());
// Test having a pruned inner node for a value tree when using maximum.
tree.setNodeValue(singleKey, 1.0);
value_tree.setNodeValueAtDepth(singleKey, value_tree.getTreeDepth() - 1, -1.0);
EXPECT_EQ(value_tree.size(), value_tree.getTreeDepth());
EXPECT_EQ(tree.size(), tree.getTreeDepth() + 1);
tree.setTreeValues(&value_tree, &bounds_tree, true, false);
EXPECT_EQ(tree.size(), tree.getTreeDepth() + 8);
node = tree.search(singleKey);
EXPECT_TRUE(node);
EXPECT_EQ(1.0, node->getLogOdds());
nextKey = singleKey;
nextKey[1] += 1;
node = tree.search(nextKey);
EXPECT_TRUE(node);
EXPECT_EQ(-1.0, node->getLogOdds());
// Test having a pruned inner node in our tree, a sub-node in the value
// tree while using delete first.
tree.clear();
value_tree.clear();
bounds_tree.clear();
tree.setNodeValueAtDepth(singleKey, tree.getTreeDepth() - 1, 1.0);
value_tree.setNodeValueAtDepth(singleKey, value_tree.getTreeDepth(), 1.0);
bounds_tree.setNodeValueAtDepth(singleKey, bounds_tree.getTreeDepth() - 1, 1.0);
EXPECT_EQ(tree.size(), tree.getTreeDepth());
EXPECT_EQ(value_tree.size(), value_tree.getTreeDepth() + 1);
EXPECT_EQ(bounds_tree.size(), bounds_tree.getTreeDepth());
tree.setTreeValues(&value_tree, &bounds_tree, false, true);
EXPECT_EQ(tree.size(), tree.getTreeDepth() + 1);
// Test no value tree with a non-overlapping bounds tree with delete first set.
tree.clear();
bounds_tree.clear();
nextKey[1] += 2;
tree.setNodeValue(singleKey, 1.0);
bounds_tree.setNodeValue(nextKey, 1.0);
EXPECT_EQ(tree.getTreeDepth() + 1, tree.size());
EXPECT_EQ(bounds_tree.getTreeDepth() + 1, bounds_tree.size());
treep.reset(new OcTree(tree));
treep->setTreeValues(null_tree, &bounds_tree, false, true);
EXPECT_EQ(tree.getTreeDepth() + 1, tree.size());
EXPECT_TRUE(tree == *treep);
// Test delete first with an empty value tree, a complex bounds tree and
// value tree with the value tree completely inside (result should be
// empty).
tree.clear();
bounds_tree.clear();
for(int i=-10; i<=10; ++i) {
for(int j=-10; j<=10; ++j) {
for(int k=-10; k<=10; ++k) {
OcTreeKey key(center_key+i, center_key+j, center_key+k);
bounds_tree.setNodeValue(key, 1.0);
}
}
}
for(int i=-7; i<=9; ++i) {
for(int j=-5; j<=3; ++j) {
for(int k=-2; k<=8; ++k) {
OcTreeKey key(center_key+i, center_key+j, center_key+k);
tree.setNodeValue(key, 1.0);
}
}
}
tree.setTreeValues(null_tree, &bounds_tree, false, true);
EXPECT_EQ(0, tree.size());
// Now, make more complex merging scenarios.
tree.clear();
value_tree.clear();
bounds_tree.setNodeValueAtDepth(OcTreeKey(), 0, bounds_tree.getClampingThresMax());
for(int i=0; i<4; ++i) {
for(int j=0; j<4; ++j) {
for(int k=0; k<4; ++k) {
float value1 = -1.0;
float value2 = 1.0;
if (i >= 1 && i <= 2 && j >= 1 && j <= 2 && k >= 1 && k <= 2) {
value1 = 1.0;
value2 = -1.0;
}
OcTreeKey key(center_key+i, center_key+j, center_key+k);
tree.setNodeValue(key, value1);
value_tree.setNodeValue(key, value2);
}
}
}
OcTreeKey search_key(center_key+2, center_key+2, center_key+2);
EXPECT_EQ(4*4*4 + 4*4*4/8 + tree.getTreeDepth() - 1, tree.size());
EXPECT_EQ(4*4*4 + 4*4*4/8 + value_tree.getTreeDepth() - 1, value_tree.size());
treep.reset(new OcTree(tree));
treep->setTreeValues(&value_tree, &bounds_tree, true, false);
EXPECT_EQ(tree.getTreeDepth() - 1, treep->size());
EXPECT_EQ(treep->size(), treep->calcNumNodes());
node = treep->search(search_key);
EXPECT_EQ(1.0, node->getLogOdds());
expected_tree.clear();
expected_tree.setNodeValueAtDepth(OcTreeKey(center_key+2, center_key+2, center_key+2), tree.getTreeDepth() - 2, 1.0);
EXPECT_TRUE(expected_tree == *treep);
treep.reset(new OcTree(tree));
treep->setTreeValues(&value_tree, &bounds_tree, false, false);
EXPECT_EQ(treep->size(), treep->calcNumNodes());
EXPECT_TRUE(value_tree == *treep);
treep.reset(new OcTree(tree));
treep->setTreeValues(&value_tree, &bounds_tree, false, true);
EXPECT_EQ(treep->size(), treep->calcNumNodes());
EXPECT_TRUE(value_tree == *treep);
// Now try with bounds limited.
expected_tree.clear();
treep.reset(new OcTree(tree));
expected_tree.swapContent(*treep);
expected_tree.setNodeValueAtDepth(OcTreeKey(center_key+1, center_key+1, center_key+1), tree.getTreeDepth() - 1, 1.0);
bounds_tree.clear();
bounds_tree.setNodeValueAtDepth(OcTreeKey(center_key+1, center_key+1, center_key+1), tree.getTreeDepth() - 1, 1.0);
treep.reset(new OcTree(tree));
treep->setTreeValues(&value_tree, &bounds_tree, true, false);
EXPECT_EQ(4*4*4 - 8 + 4*4*4/8 + tree.getTreeDepth() - 1, treep->size());
EXPECT_EQ(treep->size(), treep->calcNumNodes());
EXPECT_TRUE(expected_tree == *treep);
expected_tree.setNodeValue(OcTreeKey(center_key+1, center_key+1, center_key+1), -1.0);
treep.reset(new OcTree(tree));
treep->setTreeValues(&value_tree, &bounds_tree, false, false);
EXPECT_EQ(treep->size(), treep->calcNumNodes());
EXPECT_TRUE(expected_tree == *treep);
treep.reset(new OcTree(tree));
treep->setTreeValues(&value_tree, &bounds_tree, false, true);
EXPECT_EQ(treep->size(), treep->calcNumNodes());
EXPECT_TRUE(expected_tree == *treep);
tree.clear();
value_tree.clear();
value_tree2.clear();
bounds_tree.clear();
for(int i=-4; i<4; ++i) {
for(int j=-4; j<4; ++j) {
for(int k=-4; k<4; ++k) {
float value1 = -200.0;
float value2 = -200.0;
float value3 = -200.0;
if (i >= -4 && i <= -3 && j >= -4 && j <= -3 && k >= -4 && k <= -3)
{
value1 = -1.0;
}
else if( i >= -4 && i < 0 && j >= -4 && j < 0 && k >= -4 && k < 0)
{
value1 = 1.0;
}
else if(i == 0 && j == 0 && k == 0)
{
value1 = 1.0;
}
else if(i == 2 && j == 2 && k == 2)
{
value1 = 1.0;
}
else if (i >= 2 && i <= 3 && j >= 2 && j <= 3 && k >= 2 && k <= 3)
{
value1 = -1.0;
}
if( i >= -4 && i < 0 && j >= -4 && j < 0 && k >= -4 && k < 0)
{
value2 = 1.0;
}
else if( i >= 1 && i < 4 && j >= 1 && j < 4 && k >= 1 && k < 4)
{
value2 = -1.0;
}
if(i == -2 && j == -2 && k == -2)
{
value3 = -1.0;
}
else if(i == 0 && j == 0 && k == 0)
{
value3 = -1.0;
}
else if(i == 1 && j == 1 && k == 1)
{
value3 = 1.0;
}
else if (i >= 2 && i <= 3 && j >= 2 && j <= 3 && k >= 2 && k <= 3)
{
value3 = 1.0;
}
OcTreeKey key(center_key+i, center_key+j, center_key+k);
if (value1 > -100.0)
{
tree.setNodeValue(key, value1);
}
if (value2 > -100.0)
{
value_tree.setNodeValue(key, value2);
}
if (value3 > -100.0)
{
value_tree2.setNodeValue(key, value3);
}
}
}
}
bounds_tree.setNodeValueAtDepth(OcTreeKey(center_key-2, center_key-2, center_key-2), bounds_tree.getTreeDepth() - 2, 1.0);
bounds_tree.setNodeValueAtDepth(OcTreeKey(center_key+3, center_key+3, center_key+3), bounds_tree.getTreeDepth() - 1, 1.0);
treep.reset(new OcTree(tree));
EXPECT_EQ((1 + 8) + 7 + 2 * tree.getTreeDepth(), treep->size());
EXPECT_EQ(4*3+2*3+1 + 5 + 2 * tree.getTreeDepth(), value_tree.size());
EXPECT_EQ(2 + 1 + 2 * tree.getTreeDepth(), value_tree2.size());
treep->setTreeValues(&value_tree, &bounds_tree, true, false);
EXPECT_EQ(treep->size(), treep->calcNumNodes());
treep->setTreeValues(&value_tree2, &bounds_tree, true, false);
EXPECT_EQ(treep->size(), treep->calcNumNodes());
EXPECT_EQ(2 * tree.getTreeDepth(), treep->size());
expected_tree.clear();
expected_tree.setNodeValueAtDepth(OcTreeKey(center_key-2, center_key-2, center_key-2), expected_tree.getTreeDepth() - 2, 1.0);
expected_tree.setNodeValue(OcTreeKey(center_key, center_key, center_key), 1.0);
expected_tree.setNodeValueAtDepth(OcTreeKey(center_key+3, center_key+3, center_key+3), expected_tree.getTreeDepth() - 1, 1.0);
EXPECT_TRUE(expected_tree == *treep);
treep.reset(new OcTree(tree));
treep->setTreeValues(&value_tree, true, false);
EXPECT_EQ(treep->size(), treep->calcNumNodes());
treep->setTreeValues(&value_tree2, true, false);
EXPECT_EQ(treep->size(), treep->calcNumNodes());
for(int i=1; i<4; ++i) {
for(int j=1; j<4; ++j) {
for(int k=1; k<4; ++k) {
float v=-200.0;
if (i==1 && j==1 && k==1) {
v=1.0;
} else if (i==1 || j==1 || k==1) {
v=-1.0;
}
if (v > -100.0) {
expected_tree.setNodeValue(OcTreeKey(center_key+i, center_key+j, center_key+k), v);
}
}
}
}
EXPECT_TRUE(expected_tree == *treep);
treep.reset(new OcTree(tree));
treep->setTreeValues(&value_tree, true);
EXPECT_EQ(treep->size(), treep->calcNumNodes());
treep->setTreeValues(&value_tree2, true);
EXPECT_EQ(treep->size(), treep->calcNumNodes());
expected_tree.swapContent(*treep);
treep.reset(new OcTree(tree));
treep->setTreeValues(&value_tree2, true);
EXPECT_EQ(treep->size(), treep->calcNumNodes());
treep->setTreeValues(&value_tree, true);
EXPECT_EQ(treep->size(), treep->calcNumNodes());
EXPECT_TRUE(expected_tree == *treep);
treep.reset(new OcTree(tree));
treep->setTreeValues(&value_tree);
EXPECT_EQ(treep->size(), treep->calcNumNodes());
treep->setTreeValues(&value_tree2);
EXPECT_EQ(treep->size(), treep->calcNumNodes());
expected_tree.swapContent(*treep);
treep.reset(new OcTree(tree));
treep->setTreeValues(&value_tree2);
EXPECT_EQ(treep->size(), treep->calcNumNodes());
treep->setTreeValues(&value_tree);
EXPECT_EQ(treep->size(), treep->calcNumNodes());
treep->setTreeValues(&value_tree2);
EXPECT_EQ(treep->size(), treep->calcNumNodes());
EXPECT_TRUE(expected_tree == *treep);
treep.reset(new OcTree(tree));
treep->setTreeValues(&value_tree, &bounds_tree);
EXPECT_EQ(treep->size(), treep->calcNumNodes());
treep->setTreeValues(&value_tree2, &bounds_tree);
EXPECT_EQ(treep->size(), treep->calcNumNodes());
expected_tree.swapContent(*treep);
treep.reset(new OcTree(tree));
treep->setTreeValues(&value_tree2, &bounds_tree);
EXPECT_EQ(treep->size(), treep->calcNumNodes());
treep->setTreeValues(&value_tree, &bounds_tree);
EXPECT_EQ(treep->size(), treep->calcNumNodes());
treep->setTreeValues(&value_tree2, &bounds_tree);
EXPECT_EQ(treep->size(), treep->calcNumNodes());
EXPECT_TRUE(expected_tree == *treep);
treep.reset(new OcTree(tree));
treep->setTreeValues(&value_tree, &value_tree);
EXPECT_EQ(treep->size(), treep->calcNumNodes());
treep->setTreeValues(&value_tree2, &value_tree2);
EXPECT_EQ(treep->size(), treep->calcNumNodes());
expected_tree.swapContent(*treep);
treep.reset(new OcTree(tree));
treep->setTreeValues(&value_tree2, &value_tree2);
EXPECT_EQ(treep->size(), treep->calcNumNodes());
treep->setTreeValues(&value_tree, &value_tree);
EXPECT_EQ(treep->size(), treep->calcNumNodes());
treep->setTreeValues(&value_tree2, &value_tree2);
EXPECT_EQ(treep->size(), treep->calcNumNodes());
EXPECT_TRUE(expected_tree == *treep);
treep.reset(new OcTree(tree));
treep->setTreeValues(&value_tree, &value_tree);
EXPECT_EQ(treep->size(), treep->calcNumNodes());
treep->setTreeValues(&value_tree2, &value_tree2);
EXPECT_EQ(treep->size(), treep->calcNumNodes());
expected_tree.swapContent(*treep);
treep.reset(new OcTree(tree));
treep->setTreeValues(&value_tree2, &value_tree);
EXPECT_EQ(treep->size(), treep->calcNumNodes());
treep->setTreeValues(&value_tree, &value_tree2);
EXPECT_EQ(treep->size(), treep->calcNumNodes());
treep->setTreeValues(&value_tree2, &value_tree);
EXPECT_EQ(treep->size(), treep->calcNumNodes());
EXPECT_FALSE(expected_tree == *treep);
treep.reset(new OcTree(tree));
treep->setTreeValues(&value_tree, false, true);
EXPECT_EQ(treep->size(), treep->calcNumNodes());
EXPECT_TRUE(value_tree == *treep);
treep->setTreeValues(&value_tree2, false, true);
EXPECT_EQ(treep->size(), treep->calcNumNodes());
EXPECT_TRUE(value_tree2 == *treep);
treep.reset(new OcTree(tree));
treep->setTreeValues(&value_tree, &bounds_tree, false, true);
EXPECT_EQ(treep->size(), treep->calcNumNodes());
EXPECT_FALSE(value_tree == *treep);
treep.reset(new OcTree(tree));
treep->setTreeValues(&value_tree2, &bounds_tree, false, true);
EXPECT_EQ(treep->size(), treep->calcNumNodes());
EXPECT_FALSE(value_tree2 == *treep);
treep.reset(new OcTree(tree));
treep->setTreeValues(null_tree, &tree, false, true);
EXPECT_EQ(treep->size(), 0);
EXPECT_EQ(treep->size(), treep->calcNumNodes());
treep.reset(new OcTree(tree));
treep->setTreeValues(&tree, false, false,
[](const OcTree::NodeType*, OcTree::NodeType* node, bool, const OcTreeKey&, unsigned int)
{node->setLogOdds(1.0);});
EXPECT_EQ(treep->size(), 2 * treep->getTreeDepth());
EXPECT_EQ(treep->size(), treep->calcNumNodes());
treep->clear();
float max_log = tree.getClampingThresMaxLog();
// Ugly, but in C++11 you can't capture in a lambda and use it as a function pointer.
// Instead, use bind to send the value to set to the lambda
treep->setTreeValues(&tree, false, false,
std::bind([](OcTree::NodeType* node, float value){node->setLogOdds(value);},
std::placeholders::_2, max_log));
EXPECT_EQ(treep->size(), 2 * treep->getTreeDepth());
EXPECT_EQ(treep->size(), treep->calcNumNodes());
treep->clear();
treep->setTreeValues(&tree, false, false,
[](const OcTree::NodeType*, OcTree::NodeType* node, bool, const OcTreeKey&, unsigned int)
{node->setLogOdds(1.0);});
treep->setTreeValues(&value_tree, false, false,
[](const OcTree::NodeType*, OcTree::NodeType* node, bool, const OcTreeKey&, unsigned int)
{node->setLogOdds(1.0);});
treep->setTreeValues(&value_tree2, false, false,
[](const OcTree::NodeType*, OcTree::NodeType* node, bool, const OcTreeKey&, unsigned int)
{node->setLogOdds(1.0);});
EXPECT_EQ(treep->size(), 25 + 2 * treep->getTreeDepth());
EXPECT_EQ(treep->size(), treep->calcNumNodes());
tree.clear();
value_tree.clear();
value_tree2.clear();
for(int i=0; i<16; ++i) {
for(int j=0; j<16; ++j) {
for(int k=0; k<16; ++k) {
float value1 = -200.0;
float value2 = -200.0;
float value3 = -200.0;
if(i<2 || k>13 ) {
value1 = -1.0;
}
else if(i<5 || j>3) {
value2 = .5;
}
else {
value3 = 1.0;
}
OcTreeKey key(center_key+i, center_key+j, center_key+k);
if (value1 > -100.0)
{
tree.setNodeValue(key, value1);
}
if (value2 > -100.0)
{
value_tree.setNodeValue(key, value2);
}
if (value3 > -100.0)
{
value_tree2.setNodeValue(key, value3);
}
}
}
}
treep->clear();
treep->setTreeValues(&tree, false, false,
[](const OcTree::NodeType*, OcTree::NodeType* node, bool, const OcTreeKey&, unsigned int)
{node->setLogOdds(1.0);});
treep->setTreeValues(&value_tree, false, false,
[](const OcTree::NodeType*, OcTree::NodeType* node, bool, const OcTreeKey&, unsigned int)
{node->setLogOdds(1.0);});
treep->setTreeValues(&value_tree2, false, false,
[](const OcTree::NodeType*, OcTree::NodeType* node, bool, const OcTreeKey&, unsigned int)
{node->setLogOdds(1.0);});
EXPECT_EQ(treep->size(), treep->getTreeDepth() - 3);
EXPECT_EQ(treep->size(), treep->calcNumNodes());
std::cerr << "Test successful.\n";
return 0;
}
| 40.287319 | 130 | 0.61616 | BadgerTechnologies |
683f877debdbab79a8362817d237a71245f32022 | 546 | cpp | C++ | c++/10611.cpp | AkashChandrakar/UVA | b90535c998ecdffe0f30e56fec89411f456b16a5 | [
"Apache-2.0"
] | 2 | 2016-10-23T14:35:13.000Z | 2018-09-16T05:38:47.000Z | c++/10611.cpp | AkashChandrakar/UVA | b90535c998ecdffe0f30e56fec89411f456b16a5 | [
"Apache-2.0"
] | null | null | null | c++/10611.cpp | AkashChandrakar/UVA | b90535c998ecdffe0f30e56fec89411f456b16a5 | [
"Apache-2.0"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
int arr[50001];
int main()
{
int n, q, x, y, h;
scanf("%d", &n);
for (int i = 0; i < n; i++)
scanf("%d", &arr[i]);
scanf("%d", &q);
for (int i = 0; i < q; i++)
{
scanf("%d", &h);
x = lower_bound(arr, arr + n, h) - arr;
if (arr[x] >= h && x > 0)
{
printf("%d ", arr[x - 1]);
}
else if(arr[n-1] < h)
printf("%d ", arr[n - 1]);
else
printf("X ");
y = upper_bound(arr, arr + n, h) - arr;
if (y != n)
printf("%d\n", arr[y]);
else
printf("X\n");
}
return 0;
} | 17.612903 | 41 | 0.456044 | AkashChandrakar |
684136a1306bd5df1908ea77a56e1c371dd228b1 | 3,071 | cxx | C++ | Testing/Code/BasicFilters/itkPathToChainCodePathFilterTest.cxx | kiranhs/ITKv4FEM-Kiran | 0e4ab3b61b5fc4c736f04a73dd19e41390f20152 | [
"BSD-3-Clause"
] | 1 | 2018-04-15T13:32:43.000Z | 2018-04-15T13:32:43.000Z | Testing/Code/BasicFilters/itkPathToChainCodePathFilterTest.cxx | kiranhs/ITKv4FEM-Kiran | 0e4ab3b61b5fc4c736f04a73dd19e41390f20152 | [
"BSD-3-Clause"
] | null | null | null | Testing/Code/BasicFilters/itkPathToChainCodePathFilterTest.cxx | kiranhs/ITKv4FEM-Kiran | 0e4ab3b61b5fc4c736f04a73dd19e41390f20152 | [
"BSD-3-Clause"
] | null | null | null | /*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkPathToChainCodePathFilterTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include <iostream>
#include "itkPolyLineParametricPath.h"
#include "itkChainCodePath2D.h"
#include "itkPathToChainCodePathFilter.h"
#include "itkPathIterator.h"
int itkPathToChainCodePathFilterTest(int, char*[])
{
typedef itk::PolyLineParametricPath<2> InPathType;
typedef itk::ChainCodePath2D ChainPathType;
typedef InPathType::VertexType VertexType;
typedef InPathType::OffsetType OffsetType;
typedef InPathType::InputType InPathInputType;
typedef itk::PathToChainCodePathFilter<InPathType,ChainPathType> FilterType;
bool passed = true;
// Setup the path
std::cout << "Making a triangle Path with v0 at (30,30) -> (30,33) -> (33,33)" << std::endl;
VertexType v;
InPathType::Pointer inPath = InPathType::New();
ChainPathType::Pointer chainPath;
v.Fill(30);
inPath->AddVertex(v);
v[0]=30;
v[1]=33;
inPath->AddVertex(v);
v.Fill(33);
inPath->AddVertex(v);
// Setup the filter
FilterType::Pointer filter = FilterType::New();
filter->SetInput(inPath);
chainPath=filter->GetOutput();
chainPath->Update();
std::cout << "PathToChainCodePathFilter: open test path is "
<< chainPath->NumberOfSteps() << " steps:\n \""
<< chainPath->GetChainCodeAsString() << "\"." << std::endl;
if( chainPath->NumberOfSteps() != 6 )
{
passed = false;
}
// close the triangle
v.Fill(30);
inPath->AddVertex(v);
chainPath->Update();
std::cout << "PathToChainCodePathFilter: closed test path is "
<< chainPath->NumberOfSteps() << " steps:\n \""
<< chainPath->GetChainCodeAsString() << "\"." << std::endl;
if( chainPath->NumberOfSteps() != 9 )
{
passed = false;
}
filter->MaximallyConnectedOn();
filter->Update();
std::cout << "PathToChainCodePathFilter: maximally connected test path is "
<< chainPath->NumberOfSteps() << " steps:\n \""
<< chainPath->GetChainCodeAsString() << "\"." << std::endl;
if( chainPath->NumberOfSteps() != 12 )
{
passed = false;
}
if (passed)
{
std::cout << "PathToChainCodePathFilter tests passed" << std::endl;
return EXIT_SUCCESS;
}
else
{
std::cout << "PathToChainCodePathFilter tests failed" << std::endl;
return EXIT_FAILURE;
}
}
| 29.528846 | 94 | 0.62097 | kiranhs |
684167ef25f5b08999dc11929875145ad578c9ce | 10,381 | cpp | C++ | code/marvinolomu-snake.cpp | nyamako/hacktoberfest-2018 | bf7939d4b0cfb57a854a1644dbbae7ddf8af3c4f | [
"MIT"
] | 67 | 2018-09-25T21:37:23.000Z | 2020-11-03T02:03:22.000Z | code/marvinolomu-snake.cpp | nyamako/hacktoberfest-2018 | bf7939d4b0cfb57a854a1644dbbae7ddf8af3c4f | [
"MIT"
] | 245 | 2018-09-18T10:07:28.000Z | 2020-09-30T19:00:11.000Z | code/marvinolomu-snake.cpp | nyamako/hacktoberfest-2018 | bf7939d4b0cfb57a854a1644dbbae7ddf8af3c4f | [
"MIT"
] | 1,192 | 2018-09-18T11:27:55.000Z | 2021-10-17T10:24:37.000Z | #include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#include <math.h>
#include <time.h>
// a simple snake game
// 4 is a body
// 3 is the head
// 2 is an apple
// 1 is a block
// 0 is nothing
// works under Windows
// compiled with MSC compiler
int level_matrix[20][20];
int lastposx[20];
int lastposy[20];
int delta_time = 0;
int game_tick = 0;
int delta_time_tick = delta_time + 10; // magic number
bool block_input = 0;
bool apple_spawned = 0;
int playerx = 10;
int playery = 5; // first array is y second is x
int body = 0;
char input = 'n';
bool apple_on_player = true;
void gotoxy(short x, short y)
{
HANDLE hCon = GetStdHandle(STD_OUTPUT_HANDLE);
COORD pos;
pos.X = x - 1;
pos.Y = y - 1;
SetConsoleCursorPosition(hCon, pos);
}
void hidecursor()
{
HANDLE consoleHandle = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_CURSOR_INFO info;
info.dwSize = 100;
info.bVisible = FALSE;
SetConsoleCursorInfo(consoleHandle, &info);
}
void render_level()
{
char wall = '#';
char point = 'o';
char player = 'X';
char bodypart = 'y';
gotoxy(1, 7);
for (int i = 0; i < 20; i++) // height
{
for (int j = 0; j < 20; j++) //width
{
//printf("%d", level_matrix[i][j]);
if (level_matrix[i][j] == 1)
{
printf("%c", wall);
}
if (level_matrix[i][j] == 0)
{
printf(" ");
}
if (level_matrix[i][j] == 3)
{
printf("%c",player);
}
if (level_matrix[i][j] == 4)
{
printf("%c", bodypart);
}
if (level_matrix[i][j] == 2)
{
printf("%c", point);
}
}
printf("\n");
}
}
void input_handler()
{
if (_kbhit())
{
input = (char)_getch();
}
switch (input)
{
case 'w': case 'W':
{
gotoxy(1, 5);
printf("key:up ");
break;
}
case 's': case 'S':
{
gotoxy(1, 5);
printf("key:down ");
break;
}
case 'a': case 'A':
{
gotoxy(1, 5);
printf("key:left ");
break;
}
case 'd': case 'D':
{
gotoxy(1, 5);
printf("key:right ");
break;
}
}
}
void spawn_player()
{
level_matrix[playery][playerx] = 3;
}
void nullify_mid()
{
for (int i = 1; i < 19; i++) //rewrite this part just use 2 loops
{
level_matrix[1][i] = 0;
level_matrix[i][1] = 0;
level_matrix[2][i] = 0;
level_matrix[i][2] = 0;
level_matrix[3][i] = 0;
level_matrix[i][3] = 0;
level_matrix[4][i] = 0;
level_matrix[i][4] = 0;
level_matrix[5][i] = 0;
level_matrix[i][5] = 0;
level_matrix[6][i] = 0;
level_matrix[i][6] = 0;
level_matrix[7][i] = 0;
level_matrix[i][7] = 0;
level_matrix[8][i] = 0;
level_matrix[i][8] = 0;
level_matrix[9][i] = 0;
level_matrix[i][9] = 0;
level_matrix[10][i] = 0;
level_matrix[i][10] = 0;
level_matrix[11][i] = 0;
level_matrix[i][11] = 0;
level_matrix[12][i] = 0;
level_matrix[i][12] = 0;
level_matrix[13][i] = 0;
level_matrix[i][13] = 0;
level_matrix[14][i] = 0;
level_matrix[i][14] = 0;
level_matrix[15][i] = 0;
level_matrix[i][15] = 0;
level_matrix[16][i] = 0;
level_matrix[i][16] = 0;
level_matrix[17][i] = 0;
level_matrix[i][17] = 0;
level_matrix[18][i] = 0;
level_matrix[i][18] = 0;
}
}
void create_walls()
{
for (int i = 0; i < 20; i++)
{
level_matrix[0][i] = 1;
level_matrix[i][0] = 1;
level_matrix[19][i] = 1;
level_matrix[i][19] = 1;
}
}
void add_body()
{
body++;
lastposx[body] = lastposx[0];
lastposy[body] = lastposy[0];
level_matrix[lastposy[body]][lastposx[body]] = 4;
}
void check_lose()
{
}
void spawn_apple()
{
int x, y;
while (apple_on_player != false)
{
srand((unsigned)time(NULL));
x = (rand() % 18 + 1);
y = (rand() % 18 + 1);
if (level_matrix[y][x] == 0)
{
apple_on_player = false;
apple_spawned = true;
level_matrix[y][x] = 2;
}
}
}
int main()
{
bool game_window = 1;
hidecursor();
nullify_mid();
create_walls();
spawn_player();
while(game_window == 1)
{
if (delta_time == delta_time_tick)
{
block_input = 1;
game_tick++;
delta_time = 0;
switch (input)
{
case 'w': case 'W':
{
if (level_matrix[playery][playerx - 1] == 4 || level_matrix[playery][playerx + 1] == 4 || level_matrix[playery + 1][playerx] == 4 || level_matrix[playery - 1][playerx] == 4)
{
}
else if (level_matrix[playery][playerx - 1] == 1 || level_matrix[playery][playerx + 1] == 1 || level_matrix[playery + 1][playerx] == 1 || level_matrix[playery - 1][playerx] == 1)
{
return 0;
}
else if (level_matrix[playery][playerx - 1] == 2)
{
level_matrix[playery][playerx - 1] = 0;
add_body();
spawn_apple();
if (apple_spawned != 0)
{
apple_spawned = 0;
}
}
else if (level_matrix[playery - 1][playerx] == 2)
{
level_matrix[playery--][playerx] = 0;
add_body();
spawn_apple();
if (apple_spawned != 0)
{
apple_spawned = 0;
}
}
else if (level_matrix[playery + 1][playerx] == 2)
{
level_matrix[playery + 1][playerx] = 0;
add_body();
spawn_apple();
if (apple_spawned != 0)
{
apple_spawned = 0;
}
}
else if (level_matrix[playery][playerx + 1] == 2)
{
level_matrix[playery][playerx + 1] = 0;
add_body();
spawn_apple();
if (apple_spawned != 0)
{
apple_spawned = 0;
}
}
else
{
level_matrix[playery][playerx] = 0;
}
lastposx[0] = playerx;
lastposy[0] = playery;
if (playery >= 0)
{
playery--;
level_matrix[playery][playerx] = 3;
}
//gotoxy(1, 5);
//printf("key:up ");
break;
}
case 's': case 'S':
{
if (level_matrix[playery][playerx-1] == 4 || level_matrix[playery][playerx+1] == 4 || level_matrix[playery+1][playerx] == 4 || level_matrix[playery-1][playerx] == 4)
{
}
else if (level_matrix[playery][playerx-1] == 1 || level_matrix[playery][playerx+1] == 1 || level_matrix[playery+1][playerx] == 1 || level_matrix[playery-1][playerx] == 1)
{
return 0;
}
else if (level_matrix[playery][playerx-1] == 2)
{
level_matrix[playery][playerx-1] = 0;
add_body();
spawn_apple();
if (apple_spawned != 0)
{
apple_spawned = 0;
}
}
else if (level_matrix[playery-1][playerx] == 2)
{
level_matrix[playery-1][playerx] = 0;
add_body();
spawn_apple();
if (apple_spawned != 0)
{
apple_spawned = 0;
}
}
else if (level_matrix[playery+1][playerx] == 2)
{
level_matrix[playery+1][playerx] = 0;
add_body();
if (apple_spawned != 0)
{
apple_spawned = 0;
}
}
else if (level_matrix[playery][playerx+1] == 2)
{
level_matrix[playery][playerx+1] = 0;
add_body();
spawn_apple();
if (apple_spawned != 0)
{
apple_spawned = 0;
}
}
else
{
level_matrix[playery][playerx] = 0;
}
lastposx[0] = playerx;
lastposy[0] = playery;
playery++;
level_matrix[playery][playerx] = 3;
//gotoxy(1, 5);
//printf("key:down ");
break;
}
case 'a': case 'A':
{
if (level_matrix[playery][playerx - 1] == 4 || level_matrix[playery][playerx + 1] == 4 || level_matrix[playery + 1][playerx] == 4 || level_matrix[playery - 1][playerx] == 4)
{
}
else if (level_matrix[playery][playerx - 1] == 1 || level_matrix[playery][playerx + 1] == 1 || level_matrix[playery + 1][playerx] == 1 || level_matrix[playery - 1][playerx] == 1)
{
return 0;
}
else if (level_matrix[playery][playerx - 1] == 2)
{
level_matrix[playery][playerx - 1] = 0;
add_body();
spawn_apple();
if (apple_spawned != 0)
{
apple_spawned = 0;
}
}
else if (level_matrix[playery - 1][playerx] == 2)
{
level_matrix[playery-1][playerx] = 0;
add_body();
spawn_apple();
if (apple_spawned != 0)
{
apple_spawned = 0;
}
}
else if (level_matrix[playery + 1][playerx] == 2)
{
level_matrix[playery + 1][playerx] = 0;
add_body();
spawn_apple();
if (apple_spawned != 0)
{
apple_spawned = 0;
}
}
else if (level_matrix[playery][playerx + 1] == 2)
{
level_matrix[playery][playerx + 1] = 0;
add_body();
spawn_apple();
if (apple_spawned != 0)
{
apple_spawned = 0;
}
}
else
{
level_matrix[playery][playerx] = 0;
}
lastposx[0] = playerx;
lastposy[0] = playery;
playerx--;
level_matrix[playery][playerx] = 3;
//gotoxy(1, 5);
//printf("key:left ");
break;
}
case 'd': case 'D':
{
if (level_matrix[playery][playerx - 1] == 4 || level_matrix[playery][playerx + 1] == 4 || level_matrix[playery + 1][playerx] == 4 || level_matrix[playery - 1][playerx] == 4)
{
}
else if (level_matrix[playery][playerx - 1] == 1 || level_matrix[playery][playerx + 1] == 1 || level_matrix[playery + 1][playerx] == 1 || level_matrix[playery - 1][playerx] == 1)
{
return 0;
}
else if (level_matrix[playery][playerx - 1] == 2)
{
level_matrix[playery][playerx - 1] = 3;
add_body();
spawn_apple();
if (apple_spawned != 0)
{
apple_spawned = 0;
}
}
else if (level_matrix[playery - 1][playerx] == 2)
{
level_matrix[playery-1][playerx] = 3;
add_body();
spawn_apple();
if (apple_spawned != 0)
{
apple_spawned = 0;
}
}
else if (level_matrix[playery + 1][playerx] == 2)
{
level_matrix[playery + 1][playerx] = 3;
add_body();
spawn_apple();
if (apple_spawned != 0)
{
apple_spawned = 0;
}
}
else if (level_matrix[playery][playerx + 1] == 2)
{
level_matrix[playery][playerx + 1] = 3;
add_body();
spawn_apple();
if (apple_spawned != 0)
{
apple_spawned = 0;
}
}
else
{
level_matrix[playery][playerx] = 0;
}
lastposx[0] = playerx;
lastposy[0] = playery;
playerx++;
level_matrix[playery][playerx] = 3;
//gotoxy(1, 5);
//printf("key:right ");
break;
}
}
}
if (block_input == 0)
{
input_handler();
}
gotoxy(1, 1);
printf("Snake -(Hello world 'C' project) game time: %d", game_tick); // it's not finished :(
gotoxy(1, 2);
printf("press w, s, a, d to move.\n \n");
delta_time++;
render_level();
if (apple_spawned == 0)
{
spawn_apple();
}
block_input = 0;
}
} | 20.556436 | 182 | 0.554282 | nyamako |
684168141721cff59b7e4d9dbd510002eabfc488 | 955 | cpp | C++ | src/random/UniformReal.cpp | shiruizhao/swift | 2026acce35f0717c7a3e9dc522ff1c69f8dc3227 | [
"BSD-4-Clause-UC",
"BSD-4-Clause"
] | 22 | 2016-07-11T15:34:14.000Z | 2021-04-19T04:11:13.000Z | src/random/UniformReal.cpp | shiruizhao/swift | 2026acce35f0717c7a3e9dc522ff1c69f8dc3227 | [
"BSD-4-Clause-UC",
"BSD-4-Clause"
] | 14 | 2016-07-11T14:28:42.000Z | 2017-01-27T02:59:24.000Z | src/random/UniformReal.cpp | shiruizhao/swift | 2026acce35f0717c7a3e9dc522ff1c69f8dc3227 | [
"BSD-4-Clause-UC",
"BSD-4-Clause"
] | 7 | 2016-10-03T10:05:06.000Z | 2021-05-31T00:58:35.000Z | /*
* UniformReal.cpp
*
* Created on: Mar 16, 2014
* Author: yiwu
*/
#include <cmath>
#include <algorithm>
#include "UniformReal.h"
namespace swift {
namespace random {
UniformReal::UniformReal() :
dist(0.0,1.0), a(0), b(1), scale(1), logscale(0) {
is_logscale_ok = true;
}
UniformReal::~UniformReal() {
}
void UniformReal::init(double a, double b) {
if (a > b) std::swap(a, b);
this->a = a;
this->b = b;
if (b - a != scale) {
scale = b - a;
is_logscale_ok = false;
}
}
double UniformReal::gen() {
return dist(engine) * scale + a;
}
double UniformReal::likeli(const double& x) {
return ((x >= a) && (x <= b)) ? 1.0 / scale : 0;
}
double UniformReal::loglikeli(const double& x) {
if ((x >= a) && (x <= b)) {
if (!is_logscale_ok) {
logscale = -std::log(scale);
is_logscale_ok = true;
}
return logscale;
} else
return -INFINITY;
}
} /* namespace random */
} /* namespace swift */
| 18.018868 | 54 | 0.579058 | shiruizhao |
68438640222cc0b050f6467019e921a04bd91a6a | 1,705 | hpp | C++ | Support/Modules/GSModelDevLib/ModelColor.hpp | graphisoft-python/TextEngine | 20c2ff53877b20fdfe2cd51ce7abdab1ff676a70 | [
"Apache-2.0"
] | 3 | 2019-07-15T10:54:54.000Z | 2020-01-25T08:24:51.000Z | Support/Modules/GSModelDevLib/ModelColor.hpp | graphisoft-python/GSRoot | 008fac2c6bf601ca96e7096705e25b10ba4d3e75 | [
"Apache-2.0"
] | null | null | null | Support/Modules/GSModelDevLib/ModelColor.hpp | graphisoft-python/GSRoot | 008fac2c6bf601ca96e7096705e25b10ba4d3e75 | [
"Apache-2.0"
] | 1 | 2020-09-26T03:17:22.000Z | 2020-09-26T03:17:22.000Z | // *****************************************************************************
// Color
// GSModeler, Platform independent
//
// Namespaces: Contact person:
// PCS
//
// SG compatible
// *****************************************************************************
#if !defined (MODELCOLOR_HPP)
#define MODELCOLOR_HPP
// ----------------------- Class declaration -----------------------------------
namespace ModelerAPI {
class Color {
public:
double red;
double green;
double blue;
Color () : red (0.0), green (0.0), blue (0.0) {}
Color (double r, double g, double b) : red (r), green (g), blue (b) {}
inline bool operator== (const Color& other) const;
inline bool operator!= (const Color& other) const;
inline bool operator< (const Color& other) const;
};
// ----------------------- Class implementation --------------------------------
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
bool Color::operator== (const Color& other) const
{
return red == other.red && green == other.green && blue == other.blue;
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
bool Color::operator!= (const Color& other) const
{
return !(*this == other);
}
bool Color::operator< (const Color& other) const
{
if (red != other.red)
return red < other.red;
if (green != other.green)
return green < other.green;
if (blue != other.blue)
return blue < other.blue;
return false;
}
} // namespace ModelerAPI
#endif
| 23.040541 | 80 | 0.410557 | graphisoft-python |
6844aeda302cab7ce5e12d5ebb4fc310de0fc6ac | 9,896 | cpp | C++ | Homework3 Matrix calculations/Homework3 Matrix calculations/vectorMatrix.cpp | ShounakNR/Programming-for-Finance-16-332-503 | 56048c67179d98ab519fcb4e9df4d8dfc323266a | [
"Apache-2.0"
] | null | null | null | Homework3 Matrix calculations/Homework3 Matrix calculations/vectorMatrix.cpp | ShounakNR/Programming-for-Finance-16-332-503 | 56048c67179d98ab519fcb4e9df4d8dfc323266a | [
"Apache-2.0"
] | null | null | null | Homework3 Matrix calculations/Homework3 Matrix calculations/vectorMatrix.cpp | ShounakNR/Programming-for-Finance-16-332-503 | 56048c67179d98ab519fcb4e9df4d8dfc323266a | [
"Apache-2.0"
] | null | null | null | //
// vectorMatrix.cpp
// Homework3 Matrix calculations (with vectors)
// Programming for finance 16:332:503.
// Created by Shounak Rangwala on 9/22/19.
// Copyright © 2019 Shounak Rangwala. All rights reserved.
//
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
vector<int> inputDimensions (){
vector<int> matrixDimensions;
int rows,columns;
cout<<"enter the number of rows: "<<endl;
cin>>rows;
while(rows<=0 || rows>10){
cout<<"out of bounds, enter dimension less than 10"<<endl;
cin>>rows;
}
matrixDimensions.push_back(rows);
cout<<"enter the number of columns: "<<endl;
cin>>columns;
while(columns<=0 || columns>10){
cout<<"out of bounds, enter dimension less than 10"<<endl;
cin>>columns;
}
matrixDimensions.push_back(columns);
return matrixDimensions;
}
void inputValues(vector<int>&dimensions,vector<vector<double>> &Matrix){
int rows = dimensions.front();
int columns = dimensions.back();
Matrix.resize(rows);
for(int i=0;i<Matrix.size();i++){
Matrix[i].resize(columns);
}
cout<< "enter the elements of your matrix"<<endl;
for(int i=0;i<Matrix.size();i++){
for(int j=0;j<Matrix[i].size();j++){
cin>>Matrix[i][j];
}
}
// for(int i=0;i<Matrix.size();i++){
// for(int j=0;j<Matrix[i].size();j++){
//// cin>>input;
// cout<<Matrix[i][j];
// }
// cout<<endl;
// }
}
void DisplayMatrix(vector<vector<double>> &Matrix){
for(int i=0;i<Matrix.size();i++){
for(int j=0;j<Matrix[i].size();j++){
cout<<setw(10)<<Matrix[i][j];
}
cout<<endl;
}
}
void Addition (){
cout<<"enter dimensions of First matrix"<<endl;
vector<int> Mat1Dims = inputDimensions();
cout<<"enter dimensions of second matrix"<<endl;
vector<int> Mat2Dims = inputDimensions();
if(Mat1Dims.front()!= Mat2Dims.front() || Mat1Dims.back()!= Mat2Dims.back()){
cout<< "operation not supported"<<endl;
return;
}
vector<vector<double>> Matrix1, Matrix2, result;
inputValues(Mat1Dims, Matrix1);
inputValues(Mat2Dims, Matrix2);
result.resize(Mat1Dims.front());
for(int i=0;i<result.size();i++){
result[i].resize(Mat1Dims.back());
}
for(int i=0;i<Matrix1.size();i++){
for(int j=0;j<Matrix1[i].size();j++){
result[i][j] = Matrix2[i][j]+Matrix1[i][j];
}
}
DisplayMatrix(result);
}
void Subtraction(){
cout<<"enter dimensions of First matrix"<<endl;
vector<int> Mat1Dims = inputDimensions();
cout<<"enter dimensions of second matrix"<<endl;
vector<int> Mat2Dims = inputDimensions();
if(Mat1Dims.front()!= Mat2Dims.front() || Mat1Dims.back()!= Mat2Dims.back()){
cout<< "operation not supported"<<endl;
return;
}
vector<vector<double>> Matrix1, Matrix2, result;
inputValues(Mat1Dims, Matrix1);
inputValues(Mat2Dims, Matrix2);
result.resize(Mat1Dims.front());
for(int i=0;i<result.size();i++){
result[i].resize(Mat1Dims.back());
}
for(int i=0;i<Matrix1.size();i++){
for(int j=0;j<Matrix1[i].size();j++){
result[i][j] = Matrix2[i][j]-Matrix1[i][j];
}
}
DisplayMatrix(result);
}
void Multiplication(){
cout<<"enter dimensions of First matrix"<<endl;
vector<int> Mat1Dims = inputDimensions();
cout<<"enter dimensions of second matrix"<<endl;
vector<int> Mat2Dims = inputDimensions();
if(Mat2Dims.front()!= Mat1Dims.back()){
cout<< "operation not supported"<<endl;
return;
}
vector<vector<double>> Matrix1, Matrix2, result;
cout<<"enter values in 1st matrix"<<endl;
inputValues(Mat1Dims, Matrix1);
cout<<"enter values in 2nd matrix"<<endl;
inputValues(Mat2Dims, Matrix2);
result.resize(Mat1Dims.front());
for(int i=0;i<result.size();i++){
result[i].resize(Mat2Dims.back(),0);
}
for(int i=0;i<Mat1Dims.front();i++){
for(int j=0;j<Mat2Dims.back();j++){
for(int k=0; k<Mat1Dims.back();k++)
result[i][j] += Matrix1[i][k]*Matrix2[k][j];
}
}
DisplayMatrix(result);
}
void Transpose(){
cout<<"enter dimensions of the matrix"<<endl;
vector<int> Mat1Dims = inputDimensions();
vector<vector<double>> Matrix1, result;
cout<<"enter values in the matrix"<<endl;
inputValues(Mat1Dims, Matrix1);
result.resize(Mat1Dims.back());
for(int i=0;i<result.size();i++){
result[i].resize(Mat1Dims.front(),0);
}
for(int i=0;i<Mat1Dims.front();i++){
for(int j=0;j<Mat1Dims.back();j++){
result[j][i] = Matrix1[i][j];
}
}
DisplayMatrix(result);
}
void Determinant(){
cout<<"enter dimensions of the matrix"<<endl;
vector<int> Mat1Dims = inputDimensions();
if(Mat1Dims.front()!= 3 || Mat1Dims.back()!=3){
cout<< "operation not supported"<<endl;
return;
}
vector<vector<double>> Matrix1;
double result;
cout<<"enter values in the matrix"<<endl;
inputValues(Mat1Dims, Matrix1);
result=Matrix1[0][0]*(Matrix1[1][1] * Matrix1[2][2]-Matrix1[2][1]*Matrix1[1][2]) - Matrix1[0][1]*(Matrix1[1][0]*Matrix1[2][2] - Matrix1[2][0]*Matrix1[1][2]) + Matrix1[0][2]*(Matrix1[1][0]*Matrix1[2][1]-Matrix1[2][0]*Matrix1[1][1]);
cout<<"the determinant is "<<result<<endl;
}
void Inverse(){
cout<<"enter dimensions of the matrix"<<endl;
vector<int> Mat1Dims = inputDimensions();
if(Mat1Dims.front()!= 3 || Mat1Dims.back()!=3){
cout<< "operation not supported"<<endl;
return;
}
vector<vector<double>> Matrix1,transposeMatrix;
double result;
cout<<"enter values in the matrix"<<endl;
inputValues(Mat1Dims, Matrix1);
result=Matrix1[0][0]*(Matrix1[1][1] * Matrix1[2][2]-Matrix1[2][1]*Matrix1[1][2]) - Matrix1[0][1]*(Matrix1[1][0]*Matrix1[2][2] - Matrix1[2][0]*Matrix1[1][2]) + Matrix1[0][2]*(Matrix1[1][0]*Matrix1[2][1]-Matrix1[2][0]*Matrix1[1][1]);
if(result ==0){
cout<<" operation not possible"<<endl;
return;
}
transposeMatrix.resize(Mat1Dims.back());
for(int i=0;i<transposeMatrix.size();i++){
transposeMatrix[i].resize(Mat1Dims.front(),0);
}
for(int i=0;i<Mat1Dims.front();i++){
for(int j=0;j<Mat1Dims.back();j++){
transposeMatrix[j][i] = Matrix1[i][j];
}
}
//Calculate 2-complement of matrix.
vector<vector<double>> complementMatrix;
complementMatrix.resize(Mat1Dims.back());
for(int i=0;i<complementMatrix.size();i++){
complementMatrix[i].resize(Mat1Dims.front(),0);
}
complementMatrix[0][0] = transposeMatrix[1][1] * transposeMatrix[2][2] - transposeMatrix[1][2] * transposeMatrix[2][1];
complementMatrix[0][1] = - (transposeMatrix[1][0] * transposeMatrix[2][2] - transposeMatrix[1][2] * transposeMatrix[2][0]);
complementMatrix[0][2] = transposeMatrix[1][0] * transposeMatrix[2][1] - transposeMatrix[1][1] * transposeMatrix[2][0];
complementMatrix[1][0] = - (transposeMatrix[0][1] * transposeMatrix[2][2] - transposeMatrix[0][2] * transposeMatrix[2][1]);
complementMatrix[1][1] = transposeMatrix[0][0] * transposeMatrix[2][2] - transposeMatrix[0][2] * transposeMatrix[2][0];
complementMatrix[1][2] = - (transposeMatrix[0][0] * transposeMatrix[2][1] - transposeMatrix[0][1] * transposeMatrix[2][0]);
complementMatrix[2][0] = transposeMatrix[0][1] * transposeMatrix[1][2] - transposeMatrix[0][2] * transposeMatrix[1][1];
complementMatrix[2][1] = - (transposeMatrix[0][0] * transposeMatrix[1][2] - transposeMatrix[0][2] * transposeMatrix[1][0]);
complementMatrix[2][2] = transposeMatrix[0][0] * transposeMatrix[1][1] - transposeMatrix[0][1] * transposeMatrix[1][0];
//The pre-result is 2-complement times 1/det(matrix).
vector<vector<double>> preInverseMatrix;
preInverseMatrix.resize(Mat1Dims.back());
for(int i=0;i<preInverseMatrix.size();i++){
preInverseMatrix[i].resize(Mat1Dims.front(),0);
}
for (int i = 0; i < Mat1Dims.front(); i++) {
for (int j = 0; j < Mat1Dims.back(); j++) {
preInverseMatrix[i][j] = complementMatrix[i][j] / result;
}
}
//The result is transpose of pre-result.
vector<vector<double>> InverseMatrix;
InverseMatrix.resize(Mat1Dims.back());
for(int i=0;i<InverseMatrix.size();i++){
InverseMatrix[i].resize(Mat1Dims.front(),0);
}
for (int i = 0; i < Mat1Dims.front(); i++) {
for (int j = 0; j < Mat1Dims.back(); j++) {
InverseMatrix[j][i] = preInverseMatrix[i][j];
}
}
cout<<" The ans is: "<<endl;
DisplayMatrix(InverseMatrix);
return;
}
int main(){
// vector<int> dims =inputDimensions();
// vector<vector<int>>matrix1;
// inputValues(dims,matrix1);
while(true){
int choice;
cout<< "Menu"<< endl;
cout<<"Choice 1: Addition"<<endl;
cout<<"Choice 2: Subtraction"<<endl;
cout<<"Choice 3: Multiplication"<<endl;
cout<<"Choice 4: Transpose"<< endl;
cout<<"Choice 5: Determinant"<< endl;
cout<<"Choice 6: Inverse"<< endl;
cout<<"Choice 7: Quit" << endl;
cout<<"enter your choice"<<endl;
cin>> choice;
switch(choice){
case 1: Addition();
break;
case 2: Subtraction();
break;
case 3: Multiplication();
break;
case 4: Transpose();
break;
case 5: Determinant();
break;
case 6: Inverse();
break;
case 7: return 0;
}
}
}
| 32.660066 | 235 | 0.584883 | ShounakNR |
96970a72455650957c85d7ac776a10299f1ec863 | 6,135 | cpp | C++ | heart/src/donotuse/hDeviceFileSystem.cpp | JoJo2nd/Heart | 4b50dfa6cbf87d32768f6c01b578bc1b23c18591 | [
"BSD-3-Clause"
] | 1 | 2016-05-14T09:22:26.000Z | 2016-05-14T09:22:26.000Z | heart/src/donotuse/hDeviceFileSystem.cpp | JoJo2nd/Heart | 4b50dfa6cbf87d32768f6c01b578bc1b23c18591 | [
"BSD-3-Clause"
] | null | null | null | heart/src/donotuse/hDeviceFileSystem.cpp | JoJo2nd/Heart | 4b50dfa6cbf87d32768f6c01b578bc1b23c18591 | [
"BSD-3-Clause"
] | null | null | null | /********************************************************************
Written by James Moran
Please see the file HEART_LICENSE.txt in the source's root directory.
*********************************************************************/
#include "base/hDeviceFileSystem.h"
#include "pal/hMutex.h"
#include "base/hStringUtil.h"
namespace Heart {
class hdFileSystemMountInfo
{
public:
hdFileSystemMountInfo()
: mountCount_(0)
{}
~hdFileSystemMountInfo() {
while (mountCount_) {
unmount(mounts_[0].mountName_);
}
}
static const hUint s_maxMountLen=8;
static const hUint s_maxMounts=64;
void lock() { mountAccessMutex_.Lock(); }
void unlock() { mountAccessMutex_.Unlock(); }
void mount(const hChar* mount, const hChar* path) {
mountAccessMutex_.Lock();
hcAssert(findMountIndex(mount)==s_maxMounts);
hStrNCopy(mounts_[mountCount_].mountName_, s_maxMountLen, mount);
mounts_[mountCount_].pathLen_=hMax(hStrLen(path),1);
mounts_[mountCount_].mountPath_=new hChar[mounts_[mountCount_].pathLen_+1];
hStrCopy(mounts_[mountCount_].mountPath_, mounts_[mountCount_].pathLen_+1, path);
if (mounts_[mountCount_].mountPath_[mounts_[mountCount_].pathLen_-1]=='/' || mounts_[mountCount_].mountPath_[mounts_[mountCount_].pathLen_-1]=='\\') {
mounts_[mountCount_].mountPath_[mounts_[mountCount_].pathLen_-1]=0;
--mounts_[mountCount_].pathLen_;
}
hcPrintf("Mounting [%s] to /%s", mounts_[mountCount_].mountPath_, mounts_[mountCount_].mountName_);
++mountCount_;
mountAccessMutex_.Unlock();
}
void unmount(const hChar* mount) {
mountAccessMutex_.Lock();
if (mountCount_ > 0) {
hUint midx=findMountIndex(mount);
hcPrintf("Unmounting [%s] from /%s", mounts_[midx].mountPath_, mounts_[midx].mountName_);
delete mounts_[midx].mountPath_; mounts_[midx].mountPath_ = nullptr;
--mountCount_;
mounts_[midx]=mounts_[mountCount_];
}
mountAccessMutex_.Unlock();
}
hUint getMountPathlength(const hChar* mount) {
mountAccessMutex_.Lock();
hUint len=0;
hUint midx=findMountIndex(mount);
if (midx < s_maxMounts) {
len = mounts_[midx].pathLen_;
}
mountAccessMutex_.Unlock();
return len;
}
hUint getMount(const hChar* mount, hChar* outpath, hUint size) {
hcAssert(outpath && mount);
hUint ret=0;
mountAccessMutex_.Lock();
outpath[0]=0;
hUint midx=findMountIndex(mount);
if (midx < s_maxMounts) {
ret=mounts_[midx].pathLen_;
hStrCopy(outpath, size, mounts_[midx].mountPath_);
}
mountAccessMutex_.Unlock();
return ret;
}
private:
struct hdMount {
hChar mountName_[s_maxMountLen];
hUint pathLen_;
hChar* mountPath_;
};
hUint findMountIndex(const hChar* mount) const {
for (hUint i=0; i<mountCount_; ++i) {
if (hStrCmp(mount, mounts_[i].mountName_) == 0) {
return i;
}
}
return s_maxMounts;
}
hMutex mountAccessMutex_;
hUint mountCount_;
hdMount mounts_[s_maxMounts];
};
hdFileSystemMountInfo g_fileSystemInfo;
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
void HEART_API hdMountPoint(const hChar* path, const hChar* mount) {
hcAssert(hdIsAbsolutePath(path));
g_fileSystemInfo.mount(mount, path);
}
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
void HEART_API hdUnmountPoint(const hChar* mount) {
g_fileSystemInfo.unmount(mount);
}
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
void HEART_API hdGetSystemPath(const hChar* path, hChar* outdir, hUint size) {
hcAssert(path && *path == '/'); // paths must be absolute
hcAssert(hStrChr(path, ':')==nullptr); // we don't use the mount:/ style anymore
++path;
g_fileSystemInfo.lock();
hChar mnt[hdFileSystemMountInfo::s_maxMountLen+1];
const hChar* term=hStrChr(path, '/');
if (term && (hUint)((hPtrdiff_t)term-(hPtrdiff_t)path) < hdFileSystemMountInfo::s_maxMountLen) {
hUint os=(hUint)((hPtrdiff_t)term-(hPtrdiff_t)path);
hStrNCopy(mnt, os+1, path);
hUint mountlen=g_fileSystemInfo.getMount(mnt, outdir, size);
if (mountlen==0) {
hStrCopy(outdir, size, path-1);
} else {
hStrCopy(outdir+mountlen, size-mountlen, path+os);
}
} else {
hStrCopy(outdir, size, path);
}
g_fileSystemInfo.unlock();
}
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
hUint HEART_API hdGetSystemPathSize(const hChar* path) {
hcAssert(path && *path == '/'); // paths must be absolute
hcAssert(hStrChr(path, ':')==nullptr); // we don't use the mount:/ style anymore
++path;
g_fileSystemInfo.lock();
hChar mnt[hdFileSystemMountInfo::s_maxMountLen+1];
hUint ret=hStrLen(path);
// look for /$mount_name$/
const hChar* term=hStrChr(path, '/');
if (term && (hUint)((hPtrdiff_t)term-(hPtrdiff_t)path) < hdFileSystemMountInfo::s_maxMountLen) {
hStrNCopy(mnt, (hUint)((hPtrdiff_t)term-(hPtrdiff_t)path)+1, path);
ret+=g_fileSystemInfo.getMountPathlength(mnt);
}
g_fileSystemInfo.unlock();
return ret;
}
} | 36.736527 | 158 | 0.52339 | JoJo2nd |
9697f68859d4396524f960cc99eaf724a97aa2d6 | 1,588 | cc | C++ | src/pineapple/app.cc | tomocy/pineapple | bc9c901a521616c4f47d079c6945359eac947ca2 | [
"MIT"
] | null | null | null | src/pineapple/app.cc | tomocy/pineapple | bc9c901a521616c4f47d079c6945359eac947ca2 | [
"MIT"
] | null | null | null | src/pineapple/app.cc | tomocy/pineapple | bc9c901a521616c4f47d079c6945359eac947ca2 | [
"MIT"
] | null | null | null | #include "src/pineapple/app.h"
#include <iostream>
#include <map>
#include <string>
#include <vector>
#include "external/flags/src/flags/flags.h"
#include "src/pineapple/command.h"
#include "src/pineapple/context.h"
#include "src/pineapple/exceptions.h"
namespace pineapple {
App::App(const std::string& name) : Command(name) {}
App::App(const std::string& name, const std::string& description)
: Command(name, description, nullptr) {}
App::App(const std::string& name, const action_t& action)
: Command(name, action) {}
App::App(const std::string& name, const std::string& description,
const Command::action_t& action)
: Command(name, description, action) {}
void App::Run(int n, const char** args) {
Run(std::vector<std::string>(args, args + n));
}
void App::Run(const std::vector<std::string>& args) {
if (args.size() < 1) {
throw Exception(
"insufficient arguments: one argument is required at least");
}
auto trimmed = std::vector<std::string>(std::begin(args) + 1, std::end(args));
try {
flags.Parse(trimmed);
} catch (const flags::Exception& e) {
throw Exception(e.What());
}
auto ctx = Context(flags);
if (ctx.Args().size() >= 1 && DoHaveCommand(ctx.Args().at(0))) {
RunCommand(std::move(ctx));
return;
}
if (ctx.Args().empty() || action != nullptr) {
DoAction(ctx);
return;
}
throw Exception("argument\"" + ctx.Args().at(0) +
"\" is not handled at all: action or command named \"" +
ctx.Args().at(0) + "\" is needed");
}
} // namespace pineapple | 26.466667 | 80 | 0.630353 | tomocy |
9698ff51d7f20ca0b8a25b150ddb419aaa7e01c8 | 2,860 | cpp | C++ | crogine/src/network/NetPeer.cpp | fallahn/crogine | f6cf3ade1f4e5de610d52e562bf43e852344bca0 | [
"FTL",
"Zlib"
] | 41 | 2017-08-29T12:14:36.000Z | 2022-02-04T23:49:48.000Z | crogine/src/network/NetPeer.cpp | fallahn/crogine | f6cf3ade1f4e5de610d52e562bf43e852344bca0 | [
"FTL",
"Zlib"
] | 11 | 2017-09-02T15:32:45.000Z | 2021-12-27T13:34:56.000Z | crogine/src/network/NetPeer.cpp | fallahn/crogine | f6cf3ade1f4e5de610d52e562bf43e852344bca0 | [
"FTL",
"Zlib"
] | 5 | 2020-01-25T17:51:45.000Z | 2022-03-01T05:20:30.000Z | /*-----------------------------------------------------------------------
Matt Marchant 2017 - 2020
http://trederia.blogspot.com
crogine - Zlib license.
This software is provided 'as-is', without any express or
implied warranty.In no event will the authors be held
liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute
it freely, subject to the following restrictions :
1. The origin of this software must not be misrepresented;
you must not claim that you wrote the original software.
If you use this software in a product, an acknowledgment
in the product documentation would be appreciated but
is not required.
2. Altered source versions must be plainly marked as such,
and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any
source distribution.
-----------------------------------------------------------------------*/
#include "../detail/enet/enet/enet.h"
#include <crogine/network/NetData.hpp>
using namespace cro;
std::string NetPeer::getAddress() const
{
CRO_ASSERT(m_peer, "Not a valid peer");
auto bytes = m_peer->address.host;
std::string ret = std::to_string(bytes & 0x000000FF);
ret += "." + std::to_string((bytes & 0x0000FF00) >> 8);
ret += "." + std::to_string((bytes & 0x00FF0000) >> 16);
ret += "." + std::to_string((bytes & 0xFF000000) >> 24);
return ret;
}
std::uint16_t NetPeer::getPort() const
{
CRO_ASSERT(m_peer, "Not a valid peer");
return m_peer->address.port;
}
std::uint32_t NetPeer::getID() const
{
CRO_ASSERT(m_peer, "Not a valid peer");
return m_peer->connectID;
}
std::uint32_t NetPeer::getRoundTripTime()const
{
CRO_ASSERT(m_peer, "Not a valid peer");
return m_peer->roundTripTime;
}
NetPeer::State NetPeer::getState() const
{
if (!m_peer)
{
return State::Disconnected;
}
switch (m_peer->state)
{
case ENET_PEER_STATE_ACKNOWLEDGING_CONNECT:
return State::AcknowledingConnect;
case ENET_PEER_STATE_ACKNOWLEDGING_DISCONNECT:
return State::AcknowledingDisconnect;
case ENET_PEER_STATE_CONNECTED:
return State::Connected;
case ENET_PEER_STATE_CONNECTING:
return State::Connecting;
case ENET_PEER_STATE_CONNECTION_PENDING:
return State::PendingConnect;
case ENET_PEER_STATE_CONNECTION_SUCCEEDED:
return State::Succeeded;
case ENET_PEER_STATE_DISCONNECTED:
return State::Disconnected;
case ENET_PEER_STATE_DISCONNECTING:
return State::Disconnecting;
case ENET_PEER_STATE_DISCONNECT_LATER:
return State::DisconnectLater;
case ENET_PEER_STATE_ZOMBIE:
return State::Zombie;
}
return State::Zombie;
} | 28.316832 | 73 | 0.683217 | fallahn |
969e5fbeb80508aa303a4023e918e6af5a213024 | 955 | cpp | C++ | Cpp/CpTemplate.cpp | aminPial/Competitive-Programming-Library | c77373bf9f0dd212369a383ec3165d345f2a0cc7 | [
"MIT"
] | 4 | 2020-03-21T04:32:09.000Z | 2021-07-14T13:49:00.000Z | Cpp/CpTemplate.cpp | aminPial/Competitive-Programming-Library | c77373bf9f0dd212369a383ec3165d345f2a0cc7 | [
"MIT"
] | null | null | null | Cpp/CpTemplate.cpp | aminPial/Competitive-Programming-Library | c77373bf9f0dd212369a383ec3165d345f2a0cc7 | [
"MIT"
] | 1 | 2020-12-11T06:06:06.000Z | 2020-12-11T06:06:06.000Z |
#pragma GCC optimize("O3","unroll-loops","omit-frame-pointer","inline","fast-math","no-stack-protector") //Optimization flags
#pragma GCC target("sse,sse2,sse3,ssse3,popcnt,abm,mmx,tune=native")
// #include <x86intrin.h> //AVX/SSE Extensions
/* 만든 사람 <xrssa> */
/* 불타오르네, 불타오르네, 불타오르네 */
#include <bits/stdc++.h>
using namespace std;
#define f(i,n) for(int i=0;i<n;i++)
#define fab(i,a,b) for(int i=a;i<b;i++)
#define fa(elem, arr) for(auto &elem:arr)
#define gcd(x,y) __gcd(x,y)
#define lcm(x,y) (x/gcd(x,y))*y
#define mod 1000000007
#define all(a) a.begin(),a.end()
#define INF 1e9+5 // # define INF 0x3f3f3f3f
#define EPS 1e-6
void solve(){
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
solve();
// 여러 테스트 사례 사용
// int t;scanf("%d",&t);while(t--) solve();
// int t;scanf("%d",&t);fab(i,1,t+1) printf("Case #%d: %d",i,solve()) ;
return 0;
}
| 27.285714 | 125 | 0.584293 | aminPial |
969fbf7d50bcec325b35d3515b12ca53f22524d3 | 17,013 | cpp | C++ | plugins/dali-script-v8/src/controls/scroll-view-api.cpp | tizenorg/platform.core.uifw.dali-toolkit | 146486a8c7410a2f2a20a6d670145fe855672b96 | [
"Apache-2.0"
] | null | null | null | plugins/dali-script-v8/src/controls/scroll-view-api.cpp | tizenorg/platform.core.uifw.dali-toolkit | 146486a8c7410a2f2a20a6d670145fe855672b96 | [
"Apache-2.0"
] | null | null | null | plugins/dali-script-v8/src/controls/scroll-view-api.cpp | tizenorg/platform.core.uifw.dali-toolkit | 146486a8c7410a2f2a20a6d670145fe855672b96 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2015 Samsung Electronics Co., Ltd.
*
* 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.
*
*/
// CLASS HEADER
#include "scroll-view-api.h"
// EXTERNAL INCLUDES
// INTERNAL INCLUDES
#include <v8-utils.h>
#include <actors/actor-wrapper.h>
#include <controls/control-wrapper.h>
namespace Dali
{
namespace V8Plugin
{
namespace // unanmed namespace
{
Toolkit::ScrollView GetScrollView( v8::Isolate* isolate, const v8::FunctionCallbackInfo<v8::Value>& args )
{
HandleWrapper* handleWrapper = HandleWrapper::Unwrap( isolate, args.This() );
return Toolkit::ScrollView::DownCast( handleWrapper->mHandle );
}
} //unanmed namespace
/***************************************
* SCROLLVIEW API FUNCTIONS
***************************************/
/**
* Constructor
*
* @for ScrollView
* @constructor
* @method ScrollView
* @return {Object} scrollView
*/
Toolkit::Control ScrollViewApi::New( const v8::FunctionCallbackInfo< v8::Value >& args )
{
v8::Isolate* isolate = args.GetIsolate();
v8::HandleScope handleScope( isolate );
Toolkit::ScrollView scrollView = Toolkit::ScrollView::New();
return scrollView;
}
/**
* Set the scroll mode of ScrollView.
*
* This defines whether scrolling is enabled horizontally or vertically, how
* scrolling is snapped, and the boundary in which the scroll view can pan.
*
* When no specific scroll mode is set, scroll view can scroll to any position
* both horizontally and vertically and no snapping is enabled.
*
* Example of setting the scroll boundary of scroll view in the X axis to
* three pages (page size equals to the width of scroll view) and allowing
* snapping between pages, and disabling scrolling in the Y axis.
*
* ```
* var scrollMode = {
* xAxisScrollEnabled : true,
* xAxisSnapToInterval : scrollView.sizeWidth,
* xAxisScrollBoundary : scrollView.sizeWidth * 3,
* yAxisScrollEnabled : false
* }
*
* scrollView.setScrollMode(scrollMode);
* ```
*
* @for ScrollView
* @method setScrollMode
* @param {Object} scrollMode
* @param {Boolean} scrollMode.xAxisScrollEnabled True if the content can be scrolled in X axis or false if not.
* @param {Float} [scrollMode.xAxisSnapToInterval] When set, causes scroll view to snap to multiples of the value of the interval in the X axis while flicking. (by default no snapping)
* @param {Float} [scrollMode.xAxisScrollBoundary] When set, causes scroll view unable to scroll beyond the value of the boundary in the X axis (by default no boundary)
* @param {Boolean} scrollMode.yAxisScrollEnabled True if the content can be scrolled in Y axis or false if not.
* @param {Float} [scrollMode.yAxisSnapToInterval] When set, causes scroll view to snap to multiples of the value of the interval in the Y axis while flicking. (by default no snapping)
* @param {Float} [scrollMode.yAxisScrollBoundary] When set, causes scroll view unable to scroll beyond the value of the boundary in the Y axis (by default no boundary)
*/
void ScrollViewApi::SetScrollMode( const v8::FunctionCallbackInfo< v8::Value >& args)
{
v8::Isolate* isolate = args.GetIsolate();
v8::HandleScope handleScope( isolate );
Toolkit::ScrollView scrollView = GetScrollView( isolate, args );
v8::Local<v8::Value> scrollMode( args[0] );
if( !scrollMode->IsObject() )
{
DALI_SCRIPT_EXCEPTION( isolate, "invalid scroll mode parameter" );
return;
}
v8::Local<v8::Object> scrollModeObj = scrollMode->ToObject();
Toolkit::RulerPtr rulerX, rulerY;
// Check the scroll mode in the X axis
bool xAxisScrollEnabled = true;
v8::Local<v8::Value> xAxisScrollEnabledValue= scrollModeObj->Get( v8::String::NewFromUtf8( isolate, "xAxisScrollEnabled" ) );
if( xAxisScrollEnabledValue->IsBoolean() )
{
xAxisScrollEnabled = xAxisScrollEnabledValue->ToBoolean()->Value();
}
else
{
DALI_SCRIPT_EXCEPTION( isolate, "Missing xAxisScrollEnabled");
return;
}
if(!xAxisScrollEnabled)
{
// Default ruler and disabled
rulerX = new Toolkit::DefaultRuler();
rulerX->Disable();
}
else
{
v8::Local<v8::Value> xAxisSnapToIntervalValue= scrollModeObj->Get( v8::String::NewFromUtf8( isolate, "xAxisSnapToInterval" ) );
if( xAxisSnapToIntervalValue->IsNumber() )
{
// Fixed ruler and enabled
float xAxisSnapToInterval = xAxisSnapToIntervalValue->ToNumber()->Value();
rulerX = new Toolkit::FixedRuler(xAxisSnapToInterval);
}
else
{
// Default ruler and enabled
rulerX = new Toolkit::DefaultRuler();
}
v8::Local<v8::Value> xAxisScrollBoundaryValue= scrollModeObj->Get( v8::String::NewFromUtf8( isolate, "xAxisScrollBoundary" ) );
if( xAxisScrollBoundaryValue->IsNumber() )
{
// By default ruler domain is disabled unless set
float xAxisScrollBoundary = xAxisScrollBoundaryValue->ToNumber()->Value();
rulerX->SetDomain( Toolkit::RulerDomain( 0, xAxisScrollBoundary, true ) );
}
}
// Check the scroll mode in the Y axis
bool yAxisScrollEnabled = true;
v8::Local<v8::Value> yAxisScrollEnabledValue= scrollModeObj->Get( v8::String::NewFromUtf8( isolate, "yAxisScrollEnabled" ) );
if( yAxisScrollEnabledValue->IsBoolean() )
{
yAxisScrollEnabled = yAxisScrollEnabledValue->ToBoolean()->Value();
}
else
{
DALI_SCRIPT_EXCEPTION( isolate, "Missing yAxisScrollEnabled");
return;
}
if(!yAxisScrollEnabled)
{
// Default ruler and disabled
rulerY = new Toolkit::DefaultRuler();
rulerY->Disable();
}
else
{
v8::Local<v8::Value> yAxisSnapToIntervalValue= scrollModeObj->Get( v8::String::NewFromUtf8( isolate, "yAxisSnapToInterval" ) );
if( yAxisSnapToIntervalValue->IsNumber() )
{
// Fixed ruler and enabled
float yAxisSnapToInterval = yAxisSnapToIntervalValue->ToNumber()->Value();
rulerY = new Toolkit::FixedRuler(yAxisSnapToInterval);
}
else
{
// Default ruler and enabled
rulerY = new Toolkit::DefaultRuler();
}
v8::Local<v8::Value> yAxisScrollBoundaryValue= scrollModeObj->Get( v8::String::NewFromUtf8( isolate, "yAxisScrollBoundary" ) );
if( yAxisScrollBoundaryValue->IsNumber() )
{
// By default ruler domain is disabled unless set
float yAxisScrollBoundary = yAxisScrollBoundaryValue->ToNumber()->Value();
rulerY->SetDomain( Toolkit::RulerDomain( 0, yAxisScrollBoundary, true ) );
}
}
scrollView.SetRulerX(rulerX);
scrollView.SetRulerY(rulerY);
}
/**
* Retrieves current scroll page based on the defined snap interval being the
* size of one page, and all pages laid out in a grid fashion, increasing from
* left to right until the end of the scroll boundary. Pages start from 0 as the
* first page.
*
* If no snap interval is defined, this API will return undefined value.
*
* @for ScrollView
* @method getCurrentPage
* @return {Integer} The index of current page in scroll view
*/
void ScrollViewApi::GetCurrentPage( const v8::FunctionCallbackInfo< v8::Value >& args)
{
v8::Isolate* isolate = args.GetIsolate();
v8::HandleScope handleScope( isolate );
Toolkit::ScrollView scrollView = GetScrollView( isolate, args );
args.GetReturnValue().Set( v8::Integer::New( isolate, scrollView.GetCurrentPage() ) );
}
/**
* Scrolls the contents to the given position.
*
* Position 0,0 is the origin. Increasing X scrolls contents left, while
* increasing Y scrolls contents up. If Rulers have been applied to the axes,
* then the contents will scroll until reaching the scroll boundary.
* Contents will not snap.
*
* The biasing parameters are provided such that in scenarios with 2 or 2x2 pages
* in wrap mode, the application developer can decide whether to scroll left or
* right to get to the target page.
*
* @for ScrollView
* @method scrollToPosition
* @param {Array} position The position to scroll to.
* @param {Float} [durationSeconds] The duration of the scroll animation in seconds (default value is scrollView.scrollSnapDuration)
* @param {Integer} [alphaFunction] The alpha function to use.
* @param {Integer} [horizontalBias] Whether to bias scrolling to left or right (by default no bias).
* @param {Integer} [verticalBias] Whether to bias scrolling to top or bottom (by default no bias).
* @example
* // scroll direction bias is one of the following
* dali.DIRECTION_BIAS_NONE // Don't bias scroll snap
* dali.DIRECTION_BIAS_LEFT // Bias scroll snap to Left
* dali.DIRECTION_BIAS_RIGHT // Bias scroll snap to Right
*
* scrollView.scrollToPosition( [150.0, 100.0], 0.5, dali.ALPHA_FUNCTION_EASE_IN_OUT, dali.DIRECTION_BIAS_LEFT, dali.DIRECTION_BIAS_NONE );
*/
void ScrollViewApi::ScrollToPosition( const v8::FunctionCallbackInfo< v8::Value >& args)
{
v8::Isolate* isolate = args.GetIsolate();
v8::HandleScope handleScope( isolate );
Toolkit::ScrollView scrollView = GetScrollView( isolate, args );
bool found( false );
Vector2 position = V8Utils::GetVector2Parameter( PARAMETER_0, found, isolate, args );
if( !found )
{
DALI_SCRIPT_EXCEPTION( isolate, "bad position parameter" );
return;
}
float durationSeconds = V8Utils::GetFloatParameter( PARAMETER_1, found, isolate, args, scrollView.GetScrollSnapDuration() );
AlphaFunction alphaFunction = scrollView.GetScrollSnapAlphaFunction();
found = false;
int alpha = V8Utils::GetIntegerParameter( PARAMETER_2, found, isolate, args, 0 );
if(found)
{
alphaFunction = static_cast<AlphaFunction::BuiltinFunction>(alpha);
}
Toolkit::DirectionBias horizontalBias = static_cast<Toolkit::DirectionBias>( V8Utils::GetIntegerParameter( PARAMETER_3, found, isolate, args, Toolkit::DirectionBiasNone ) );
Toolkit::DirectionBias verticalBias = static_cast<Toolkit::DirectionBias>( V8Utils::GetIntegerParameter( PARAMETER_4, found, isolate, args, Toolkit::DirectionBiasNone ) );
scrollView.ScrollTo( position, durationSeconds, alphaFunction, horizontalBias, verticalBias );
}
/**
* Scrolls the contents to the page with the given index.
*
* This is based on assumption that the page index starts from 0 and the
* position of each page is: [pageIndex * snapToInterval, 0].
*
* If no snap interval is defined, calling this API will cause unexpected
* behaviour.
*
* The biasing parameter is provided such that in scenarios with 2 pages
* in wrap mode, the application developer can decide whether to scroll
* left or right to get to the target page.
*
* @for ScrollView
* @method scrollToPage
* @param {Integer} pageIndex The index of the page to scroll to.
* @param {Float} [durationSeconds] The duration of the scroll animation in seconds (default value is scrollView.scrollSnapDuration)
* @param {Integer} [bias] Whether to bias scrolling to left or right (by default no bias).
* @example
* // scroll direction bias is one of the following
* dali.DIRECTION_BIAS_NONE // Don't bias scroll snap
* dali.DIRECTION_BIAS_LEFT // Bias scroll snap to Left
* dali.DIRECTION_BIAS_RIGHT // Bias scroll snap to Right
*
* scrollView.scrollToPage( 1, 0.5, dali.DIRECTION_BIAS_RIGHT );
*/
void ScrollViewApi::ScrollToPage( const v8::FunctionCallbackInfo< v8::Value >& args)
{
v8::Isolate* isolate = args.GetIsolate();
v8::HandleScope handleScope( isolate );
Toolkit::ScrollView scrollView = GetScrollView( isolate, args );
bool found( false );
int pageIndex = V8Utils::GetIntegerParameter( PARAMETER_0, found, isolate, args, 0 );
if( !found )
{
DALI_SCRIPT_EXCEPTION( isolate, "bad page index parameter" );
return;
}
float durationSeconds = V8Utils::GetFloatParameter( PARAMETER_1, found, isolate, args, scrollView.GetScrollSnapDuration() );
Toolkit::DirectionBias bias = static_cast<Toolkit::DirectionBias>( V8Utils::GetIntegerParameter( PARAMETER_2, found, isolate, args, Toolkit::DirectionBiasNone ) );
scrollView.ScrollTo( pageIndex, durationSeconds, bias );
}
/**
* Scrolls the contents such that the given actor appears in the center of
* the scroll view.
*
* The actor must be a direct child of scroll view.
*
* @for ScrollView
* @method scrollToActor
* @param {Object} actor The actor to scroll to.
* @param {Float} [durationSeconds] The duration of the scroll animation in seconds (default value is scrollView.scrollSnapDuration)
* @example
* scrollView.scrollToActor( childActor, 0.5 );
*/
void ScrollViewApi::ScrollToActor( const v8::FunctionCallbackInfo< v8::Value >& args)
{
v8::Isolate* isolate = args.GetIsolate();
v8::HandleScope handleScope( isolate );
Toolkit::ScrollView scrollView = GetScrollView( isolate, args );
bool found( false );
Actor actor = V8Utils::GetActorParameter( 0, found, isolate, args );
if( !found )
{
DALI_SCRIPT_EXCEPTION( isolate, "invalid actor parameter" );
return;
}
float durationSeconds = V8Utils::GetFloatParameter( PARAMETER_1, found, isolate, args, scrollView.GetScrollSnapDuration() );
scrollView.ScrollTo( actor, durationSeconds );
}
/**
* Scrolls the content to the nearest snap point as specified by the snap interval.
* If already at snap points, it will not scroll.
*
* @for ScrollView
* @method scrollToSnapInterval
* @return {Boolean} True if snapping is needed or false if already at snap points
* @example
* var success = scrollView.scrollToSnapInterval();
*/
void ScrollViewApi::ScrollToSnapInterval( const v8::FunctionCallbackInfo< v8::Value >& args)
{
v8::Isolate* isolate = args.GetIsolate();
v8::HandleScope handleScope( isolate );
Toolkit::ScrollView scrollView = GetScrollView( isolate, args );
args.GetReturnValue().Set( v8::Boolean::New( isolate, scrollView.ScrollToSnapPoint() ) );
}
/**
* Set the alpha function of flick animation.
*
* @for ScrollView
* @method setScrollFlickAlphaFunction
* @param {Integer} alphaFunction The alpha function to use.
* @example
* scrollView.setScrollFlickAlphaFunction( dali.ALPHA_FUNCTION_EASE_IN_OUT );
*/
void ScrollViewApi::SetScrollFlickAlphaFunction( const v8::FunctionCallbackInfo< v8::Value >& args)
{
v8::Isolate* isolate = args.GetIsolate();
v8::HandleScope handleScope( isolate );
Toolkit::ScrollView scrollView = GetScrollView( isolate, args );
bool found( false );
int alphaFunction = V8Utils::GetIntegerParameter( PARAMETER_0, found, isolate, args, 0 );
if( !found )
{
DALI_SCRIPT_EXCEPTION( isolate, "invalid alpha function parameter" );
return;
}
else
{
scrollView.SetScrollFlickAlphaFunction( static_cast<AlphaFunction::BuiltinFunction>(alphaFunction) );
}
}
/**
* Set the alpha function of snap animation.
*
* @for ScrollView
* @method setScrollSnapAlphaFunction
* @param {String} alphaFunction The alpha function to use.
* @example
* scrollView.setScrollSnapAlphaFunction( dali.ALPHA_FUNCTION_EASE_IN_OUT );
*/
void ScrollViewApi::SetScrollSnapAlphaFunction( const v8::FunctionCallbackInfo< v8::Value >& args)
{
v8::Isolate* isolate = args.GetIsolate();
v8::HandleScope handleScope( isolate );
Toolkit::ScrollView scrollView = GetScrollView( isolate, args );
bool found( false );
int alphaFunction = V8Utils::GetIntegerParameter( PARAMETER_0, found, isolate, args, 0 );
if( !found )
{
DALI_SCRIPT_EXCEPTION( isolate, "invalid alpha function parameter" );
return;
}
else
{
scrollView.SetScrollSnapAlphaFunction( static_cast<AlphaFunction::BuiltinFunction>(alphaFunction) );
}
}
/**
* Set the alpha function of overshoot snap animation.
*
* @for ScrollView
* @method setSnapOvershootAlphaFunction
* @param {String} alphaFunction The alpha function to use.
* @example
* scrollView.setSnapOvershootAlphaFunction( dali.ALPHA_FUNCTION_EASE_IN_OUT );
*/
void ScrollViewApi::SetSnapOvershootAlphaFunction( const v8::FunctionCallbackInfo< v8::Value >& args)
{
v8::Isolate* isolate = args.GetIsolate();
v8::HandleScope handleScope( isolate );
Toolkit::ScrollView scrollView = GetScrollView( isolate, args );
bool found( false );
int alphaFunction = V8Utils::GetIntegerParameter( PARAMETER_0, found, isolate, args, 0 );
if( !found )
{
DALI_SCRIPT_EXCEPTION( isolate, "invalid alpha function parameter" );
return;
}
else
{
scrollView.SetSnapOvershootAlphaFunction( static_cast<AlphaFunction::BuiltinFunction>(alphaFunction) );
}
}
} // namespace V8Plugin
} // namespace Dali
| 35.59205 | 184 | 0.716687 | tizenorg |
96a0e1fecb2c7f6e7286af9704399ff11e621035 | 6,614 | hpp | C++ | Simple++/Graphic/Texture.hpp | Oriode/Simpleplusplus | 2ba44eeab5078d6dab66bdefdf73617696b8cb2e | [
"Apache-2.0"
] | null | null | null | Simple++/Graphic/Texture.hpp | Oriode/Simpleplusplus | 2ba44eeab5078d6dab66bdefdf73617696b8cb2e | [
"Apache-2.0"
] | null | null | null | Simple++/Graphic/Texture.hpp | Oriode/Simpleplusplus | 2ba44eeab5078d6dab66bdefdf73617696b8cb2e | [
"Apache-2.0"
] | null | null | null |
namespace Graphic {
template<typename T>
Texture<T>::Texture( typename Format format )
{
this -> datas.push( new ImageT<T>( format ) );
}
template<typename T>
Graphic::Texture<T>::Texture( const Math::Vec2<Size> & size, typename Format format ) {
this -> datas.push( new ImageT<T>( size, format ) );
}
template<typename T>
Texture<T>::Texture( const Texture<T> & image ) {
for ( auto it = image.datas.getBegin(); it != image.datas.getEnd(); it++ )
this -> datas.push( new ImageT<T>( **it ) );
}
template<typename T>
Texture<T>::Texture( const T * dataBuffer, const Math::Vec2<Size> & size, typename LoadingFormat loadingFormat, bool invertY ) {
this -> datas.push( new ImageT<T>( dataBuffer, size, loadingFormat, invertY ) );
}
template<typename T>
Graphic::Texture<T>::Texture( const ImageT<T> & image ) {
this -> datas.push( new ImageT<T>( image ) );
}
template<typename T>
Texture<T>::Texture( ctor ) {
}
template<typename T>
Texture<T>::Texture( Texture<T> && image ) :
datas( Utility::toRValue( image.datas ) ) {
image.datas.clear(); //clear the others datas to ensure no double delete
}
template<typename T>
Texture<T>::~Texture() {
_unload();
}
template<typename T>
void Graphic::Texture<T>::setPixel( typename Vector<ImageT<T>>::Size i, unsigned int x, unsigned int y, const T * p ) {
this -> datas[i] -> getDatas()[this -> size.x * y + x] = p;
}
template<typename T>
const T * Texture<T>::getPixel( typename Vector<ImageT<T>>::Size i, unsigned int x, unsigned int y ) const {
return this -> datas[i] -> getDatas()[this -> size.x * y + x];
}
template<typename T>
void Texture<T>::generateMipmaps() {
if ( this -> datas.getSize() > 1 ) {
for ( auto it = this -> datas.getBegin() + 1; it != this -> datas.getEnd(); it++ ) {
delete * it;
}
this -> datas.resize( 1 );
}
Vector<ImageT<T>>::Size i = 0;
auto newMipmap = this -> datas[i] -> createMipmap();
while ( newMipmap ) {
this -> datas.push( newMipmap );
i++;
newMipmap = this -> datas[i] -> createMipmap();
}
}
template<typename T>
bool Texture<T>::write( std::fstream * fileStream ) const {
Vector<ImageT<T> *>::Size nbMipmaps = this -> datas.getSize();
if ( !IO::write( fileStream, &nbMipmaps ) )
return false;
for ( auto it = this -> datas.getBegin(); it != this -> datas.getEnd(); it++ ) {
if ( !IO::write( fileStream, *it ) )
return false;
}
return true;
}
template<typename T>
bool Texture<T>::read( std::fstream * fileStream ) {
_unload();
return _read( fileStream );
}
template<typename T>
void Texture<T>::_unload() {
while ( this -> datas.getSize() )
delete this -> datas.pop();
}
template<typename T>
bool Texture<T>::_read( std::fstream * fileStream ) {
Vector<ImageT<T> *>::Size nbDatas;
if ( !IO::read( fileStream, &nbDatas ) )
return false;
// Clamp the number of datas with a big number just in case of file corruption.
nbDatas = Math::min<Vector<ImageT<T> *>::Size>( nbDatas, 100 );
for ( Vector<ImageT<T> * >::Size i = 0; i < nbDatas; i++ ) {
ImageT<T> * newImage = new ImageT<T>();
if ( newImage -> read( fileStream ) ) {
this -> datas.push( newImage );
} else {
delete newImage;
_unload();
return false;
}
}
return true;
}
template<typename T>
void Texture<T>::setDatas( const T * data, const Math::Vec2<Size> & size, typename LoadingFormat loadingFormat /*= LoadingFormat::RGB*/, bool invertY /*= false*/ ) {
_unload();
this -> datas.push( new ImageT<T>( data, size, loadingFormat, invertY ) );
}
template<typename T>
void Graphic::Texture<T>::setDatas( const ImageT<T> & image ) {
_unload();
this -> datas.push( new ImageT<T>( image ) );
}
template<typename T>
Texture<T> & Texture<T>::operator=( Texture<T> && image ) {
for ( auto it = this -> datas.getBegin(); it != this -> datas.getEnd(); it++ )
delete ( *it );
this -> datas = Utility::toRValue( image.datas );
image.datas.clear(); //clear the others datas to ensure no double delete
return *this;
}
template<typename T>
Texture<T> & Texture<T>::operator=( const Texture<T> & image ) {
for ( auto it = this -> datas.getBegin(); it != this -> datas.getEnd(); it++ )
delete ( *it );
this -> datas.clear();
for ( auto it = image.datas.getBegin(); it != image.datas.getEnd(); it++ )
this -> datas.push( new Image( **it ) );
return *this;
}
template<typename T>
T * Texture<T>::getDatas( typename Vector<ImageT<T>>::Size i ) {
return this -> datas[i] -> getDatas();
}
template<typename T>
const T * Texture<T>::getDatas( typename Vector<ImageT<T>>::Size i ) const {
return this -> datas[i] -> getDatas();
}
template<typename T>
unsigned int Texture<T>::getHeight( typename Vector<ImageT<T>>::Size i ) const {
return this -> datas[i] -> getSize().y;
}
template<typename T>
unsigned int Texture<T>::getWidth( typename Vector<ImageT<T>>::Size i ) const {
return this -> datas[i] -> getSize().x;
}
template<typename T>
const Math::Vec2<Size> & Texture<T>::getSize( typename Vector<ImageT<T>>::Size i ) const {
return this -> datas[i] -> getSize();
}
template<typename T>
void Texture<T>::clear( const Math::Vec2<Size> & size ) {
Format format = getFormat();
_unload();
this -> datas.push( new Image( size, format ) );
}
template<typename T>
void Texture<T>::clear( const Math::Vec2<Size> & size, typename Format format ) {
_unload();
this -> datas.push( new Image( size, format ) );
}
template<typename T>
typename Format Texture<T>::getFormat() const {
return this -> datas[0] -> getFormat();
}
template<typename T>
ImageT<T> & Texture<T>::getMipmap( typename Vector<ImageT<T>>::Size i ) {
return *this -> datas[i];
}
template<typename T>
const ImageT<T> & Texture<T>::getMipmap( typename Vector<ImageT<T>>::Size i ) const {
return *this -> datas[i];
}
template<typename T>
ImageT<T> & Graphic::Texture<T>::operator[]( typename Vector<ImageT<T>>::Size i ) {
return *this -> datas[i];
}
template<typename T>
const ImageT<T> & Graphic::Texture<T>::operator[]( typename Vector<ImageT<T>>::Size i ) const {
return *this -> datas[i];
}
template<typename T>
typename Vector<ImageT<T> * >::Size Texture<T>::getNbMipmaps() const {
return this -> datas.getSize();
}
template<typename T>
typename Vector<ImageT<T> * > & Graphic::Texture<T>::getMipmapVector() {
return this -> datas;
}
template<typename T>
const typename Vector<ImageT<T> * > & Graphic::Texture<T>::getMipmapVector() const {
return this -> datas;
}
}
| 25.05303 | 166 | 0.63033 | Oriode |
96a5bc246fdf8fb6249efb449594d710a9d59ccf | 3,438 | cc | C++ | riscos/libs/tbx/tbx/doc/docsaveas.cc | riscoscloverleaf/chatcube | a7184ef76108f90a74a88d3183a3d21c1249a0f5 | [
"MIT"
] | null | null | null | riscos/libs/tbx/tbx/doc/docsaveas.cc | riscoscloverleaf/chatcube | a7184ef76108f90a74a88d3183a3d21c1249a0f5 | [
"MIT"
] | null | null | null | riscos/libs/tbx/tbx/doc/docsaveas.cc | riscoscloverleaf/chatcube | a7184ef76108f90a74a88d3183a3d21c1249a0f5 | [
"MIT"
] | null | null | null | /*
* tbx RISC OS toolbox library
*
* Copyright (C) 2010 Alan Buckley All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/*
* DocSaveAs.cpp
*
* Created on: 8 Oct 2010
* Author: alanb
*/
#include "../application.h"
#include "../res/ressaveas.h"
#include "docsaveas.h"
#include "docwindow.h"
namespace tbx
{
namespace doc
{
/**
* Constructor. Sets up listener for when toolbox save as object is created
*
*/
DocSaveAs::DocSaveAs()
{
tbx::res::ResSaveAs res_save_as = tbx::app()->resource("SaveAs");
_has_selection = !res_save_as.no_selection();
tbx::app()->set_autocreate_listener("SaveAs", this);
}
DocSaveAs::~DocSaveAs()
{
}
/**
* SaveAs has been created so attach listeners for saving documents.
*
* As the save as object is shared, this routine can be called multiple times.
* However the old object would have been deleted before this happened which
* automatically removes the old listeners.
*/
void DocSaveAs::auto_created(std::string template_name, tbx::Object object)
{
tbx::SaveAs save_as(object);
save_as.add_about_to_be_shown_listener(this);
save_as.set_save_to_file_handler(this);
save_as.add_save_completed_listener(this);
}
/**
* Interrogate document for parameters for save and fill in save as dialog
*/
void DocSaveAs::about_to_be_shown(tbx::AboutToBeShownEvent &event)
{
tbx::SaveAs saveas(event.id_block().self_object());
Document *doc = DocWindow::document(event.id_block().ancestor_object());
saveas.file_name(doc->file_name());
saveas.file_type(doc->file_type());
saveas.file_size(doc->document_size());
if (_has_selection) saveas.selection_available(doc->has_selection());
}
/**
* Save the document or selection to a file
*/
void DocSaveAs::saveas_save_to_file(tbx::SaveAs saveas, bool selection, std::string filename)
{
Document *doc = DocWindow::document(saveas.ancestor_object());
bool saved_ok = false;
if (selection) saved_ok = doc->save_selection(filename);
else saved_ok = doc->save(filename);
saveas.file_save_completed(saved_ok, filename);
}
/**
* Called when document has been successfully saved
*/
void DocSaveAs::saveas_save_completed(tbx::SaveAsSaveCompletedEvent &event)
{
Document *doc = DocWindow::document(event.id_block().ancestor_object());
if (event.selection_saved()) doc->save_selection_completed(event.file_name());
else doc->save_completed(event.file_name(), event.safe());
}
}
}
| 30.972973 | 93 | 0.747237 | riscoscloverleaf |
96aa0c6d5cbc789bf926bffea3256127799d74b4 | 2,237 | cpp | C++ | DOS_Boat_Source/EnemySpace.cpp | michaelslewis/DOS_Boat | 1c25f352d75555fa81bbd0f99c89aaed43739646 | [
"MIT"
] | null | null | null | DOS_Boat_Source/EnemySpace.cpp | michaelslewis/DOS_Boat | 1c25f352d75555fa81bbd0f99c89aaed43739646 | [
"MIT"
] | null | null | null | DOS_Boat_Source/EnemySpace.cpp | michaelslewis/DOS_Boat | 1c25f352d75555fa81bbd0f99c89aaed43739646 | [
"MIT"
] | null | null | null | /****************************************************************************
* Author: Michael S. Lewis *
* Date: 6/3/2016 *
* Description: EnemySpace.cpp is the EnemySpace class function *
* implementation file (for Final Project "DOS Boat"). *
* An EnemySpace inflicts damage to the SS Damage, and deducts *
* a specific number of Strength Points, varying by space. *
*****************************************************************************/
#include "EnemySpace.hpp"
#include "Babbage.hpp"
#include <iostream>
#include <cstdlib>
#include <string>
/****************************************************************************
* EnemySpace::EnemySpace() *
* Default constructor for the EnemySpace derived class. *
*****************************************************************************/
EnemySpace::EnemySpace() : Ocean()
{
// Empty function.
}
/****************************************************************************
* EnemySpace::EnemySpace(string, string, int) *
* Overloaded constructor for the EnemySpace derived class. *
*****************************************************************************/
EnemySpace::EnemySpace(std::string nameSpace, std::string spaceHeading,
std::string spaceType, int damageSpace) : Ocean(nameSpace, spaceHeading,
spaceType)
{
this->damage = damageSpace;
}
/****************************************************************************
* EnemySpace::playSpace(Babbage*, bool) *
* Displays current space, description, inflicts damage, offers a hint, *
* displays commands for headings, and prompts for next move. *
*****************************************************************************/
void EnemySpace::playSpace(Babbage* babbage, bool displayHint)
{
std::cout << "You are " << this->name << "." << std::endl;
std::cout << this->description << std::endl;
babbage->damage(this->damage);
if (!babbage->aliveStatus())
{
return;
}
if (displayHint)
{
babbage->getSpace()->displayHint();
}
std::cout << "You can go " << this->headings << "." << std::endl;
this->nextSpace(babbage);
}
| 38.568966 | 78 | 0.453286 | michaelslewis |
96ad39b2a5385f3be8906cdd2fd7048b6aeda733 | 3,703 | cpp | C++ | lib/regi/sim_metrics_2d/xregImgSimMetric2DGradNCCOCL.cpp | rg2/xreg | c06440d7995f8a441420e311bb7b6524452843d3 | [
"MIT"
] | 30 | 2020-09-29T18:36:13.000Z | 2022-03-28T09:25:13.000Z | lib/regi/sim_metrics_2d/xregImgSimMetric2DGradNCCOCL.cpp | gaocong13/Orthopedic-Robot-Navigation | bf36f7de116c1c99b86c9ba50f111c3796336af0 | [
"MIT"
] | 3 | 2020-10-09T01:21:27.000Z | 2020-12-10T15:39:44.000Z | lib/regi/sim_metrics_2d/xregImgSimMetric2DGradNCCOCL.cpp | rg2/xreg | c06440d7995f8a441420e311bb7b6524452843d3 | [
"MIT"
] | 8 | 2021-05-25T05:14:48.000Z | 2022-02-26T12:29:50.000Z | /*
* MIT License
*
* Copyright (c) 2020 Robert Grupp
*
* 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 "xregImgSimMetric2DGradNCCOCL.h"
xreg::ImgSimMetric2DGradNCCOCL::ImgSimMetric2DGradNCCOCL()
: grad_x_sim_(this->ctx_, this->queue_),
grad_y_sim_(this->ctx_, this->queue_)
{ }
xreg::ImgSimMetric2DGradNCCOCL::ImgSimMetric2DGradNCCOCL(
const boost::compute::device& dev)
: ImgSimMetric2DGradImgOCL(dev),
grad_x_sim_(this->ctx_, this->queue_),
grad_y_sim_(this->ctx_, this->queue_)
{ }
xreg::ImgSimMetric2DGradNCCOCL::ImgSimMetric2DGradNCCOCL(
const boost::compute::context& ctx,
const boost::compute::command_queue& queue)
: ImgSimMetric2DGradImgOCL(ctx, queue),
grad_x_sim_(this->ctx_, this->queue_),
grad_y_sim_(this->ctx_, this->queue_)
{ }
void xreg::ImgSimMetric2DGradNCCOCL::allocate_resources()
{
ImgSimMetric2DGradImgOCL::allocate_resources();
// masks are set to grad_x_sim_ and grad_y_sim_ via the parent call to allocate resources, which
// will make the initial call to process_updated_mask() and in turn call process_mask()
grad_x_sim_.set_num_moving_images(this->num_mov_imgs_);
grad_x_sim_.set_fixed_image(this->fixed_img_); // still needs to be set for metadata
grad_x_sim_.set_fixed_image_dev(fixed_grad_x_dev_buf_);
grad_x_sim_.set_mov_imgs_ocl_buf(mov_grad_x_dev_buf_.get());
grad_x_sim_.set_setup_vienna_cl_ctx(false);
grad_x_sim_.set_vienna_cl_ctx_idx(this->vienna_cl_ctx_idx());
grad_x_sim_.allocate_resources();
grad_y_sim_.set_num_moving_images(this->num_mov_imgs_);
grad_y_sim_.set_fixed_image(this->fixed_img_); // still needs to be set for metadata
grad_y_sim_.set_fixed_image_dev(fixed_grad_y_dev_buf_);
grad_y_sim_.set_mov_imgs_ocl_buf(mov_grad_y_dev_buf_.get());
grad_y_sim_.set_setup_vienna_cl_ctx(false);
grad_y_sim_.set_vienna_cl_ctx_idx(this->vienna_cl_ctx_idx());
grad_y_sim_.allocate_resources();
this->sim_vals_.assign(this->num_mov_imgs_, 0);
}
void xreg::ImgSimMetric2DGradNCCOCL::process_mask()
{
ImgSimMetric2DGradImgOCL::process_mask();
grad_x_sim_.set_mask(this->mask_);
grad_y_sim_.set_mask(this->mask_);
}
void xreg::ImgSimMetric2DGradNCCOCL::compute()
{
this->pre_compute();
compute_sobel_grads();
// perform the NCC calculations on each direction
grad_x_sim_.set_num_moving_images(this->num_mov_imgs_);
grad_y_sim_.set_num_moving_images(this->num_mov_imgs_);
grad_x_sim_.compute();
grad_y_sim_.compute();
for (size_type mov_idx = 0; mov_idx < this->num_mov_imgs_; ++mov_idx)
{
this->sim_vals_[mov_idx] = 0.5 * (grad_x_sim_.sim_val(mov_idx) + grad_y_sim_.sim_val(mov_idx));
}
}
| 37.40404 | 99 | 0.766946 | rg2 |
96b1f1cf82f32d190a55de09c85fbcb1e0a3b7f2 | 6,201 | cxx | C++ | main/shell/source/win32/workbench/TestSmplMail.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/shell/source/win32/workbench/TestSmplMail.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/shell/source/win32/workbench/TestSmplMail.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* 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.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_shell.hxx"
//-----------------------------------------------------------
// interface includes
//-----------------------------------------------------------
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/registry/XSimpleRegistry.hpp>
#include <com/sun/star/system/XSystemMailProvider.hpp>
#include <cppuhelper/servicefactory.hxx>
#include <cppuhelper/servicefactory.hxx>
#include <rtl/ustring.hxx>
#include <sal/types.h>
#include <osl/diagnose.h>
#include <stdio.h>
#if defined _MSC_VER
#pragma warning(push, 1)
#endif
#include <windows.h>
#if defined _MSC_VER
#pragma warning(pop)
#endif
#include <osl/file.hxx>
//--------------------------------------------------------------
// namesapces
//--------------------------------------------------------------
using namespace ::rtl ;
using namespace ::cppu ;
using namespace ::com::sun::star::uno ;
using namespace ::com::sun::star::lang ;
using namespace std ;
using namespace com::sun::star::system;
//--------------------------------------------------------------
// defines
//--------------------------------------------------------------
#define RDB_SYSPATH "D:\\Projects\\gsl\\shell\\wntmsci7\\bin\\applicat.rdb"
//--------------------------------------------------------------
// global variables
//--------------------------------------------------------------
Reference< XMultiServiceFactory > g_xFactory;
//--------------------------------------------------------------
// main
//--------------------------------------------------------------
// int SAL_CALL main(int nArgc, char* Argv[], char* pEnv[] )
// make Warning free, leave out typename
int SAL_CALL main(int , char*, char* )
{
//-------------------------------------------------
// get the global service-manager
//-------------------------------------------------
// Get global factory for uno services.
OUString rdbName = OUString( RTL_CONSTASCII_USTRINGPARAM( RDB_SYSPATH ) );
Reference< XMultiServiceFactory > g_xFactory( createRegistryServiceFactory( rdbName ) );
// Print a message if an error occurred.
if ( g_xFactory.is() == sal_False )
{
OSL_ENSURE(sal_False, "Can't create RegistryServiceFactory");
return(-1);
}
printf("Creating RegistryServiceFactory successful\n");
//-------------------------------------------------
// try to get an Interface to a XFilePicker Service
//-------------------------------------------------
try
{
Reference< XSystemMailProvider > xSmplMailClientSuppl(
g_xFactory->createInstance( OUString::createFromAscii( "com.sun.star.system.SimpleSystemMail" ) ), UNO_QUERY );
if ( !xSmplMailClientSuppl.is() )
{
OSL_ENSURE( sal_False, "Error creating SimpleSystemMail Service" );
return(-1);
}
Reference< XMailClient > xSmplMailClient(
xSmplMailClientSuppl->queryMailClient( ) );
if ( xSmplMailClient.is( ) )
{
Reference< XMailMessage > xSmplMailMsg(
xSmplMailClient->createMailMessage( ) );
if ( xSmplMailMsg.is( ) )
{
xSmplMailMsg->setRecipient( OUString::createFromAscii("tino.rachui@germany.sun.com") );
xSmplMailMsg->setOriginator( OUString::createFromAscii( "tino.rachui@germany.sun.com" ) );
Sequence< OUString > ccRecips( 1 );
ccRecips[0] = OUString::createFromAscii( "tino.rachui@germany.sun.com" );
xSmplMailMsg->setCcRecipient( ccRecips );
Sequence< OUString > bccRecips( 1 );
bccRecips[0] = OUString::createFromAscii( "tino.rachui@germany.sun.com" );
xSmplMailMsg->setBccRecipient( bccRecips );
xSmplMailMsg->setSubject( OUString::createFromAscii( "Mapi Test" ) );
Sequence< OUString > attachements( 2 );
OUString aFile = OUString::createFromAscii( "D:\\Projects\\gsl\\shell\\wntmsci7\\bin\\testprx.exe" );
OUString aFileURL;
osl::FileBase::getFileURLFromSystemPath( aFile, aFileURL );
attachements[0] = aFileURL;
aFile = OUString::createFromAscii( "D:\\Projects\\gsl\\shell\\wntmsci7\\bin\\testsyssh.exe" );
osl::FileBase::getFileURLFromSystemPath( aFile, aFileURL );
attachements[1] = aFile;
xSmplMailMsg->setAttachement( attachements );
xSmplMailClient->sendMailMessage( xSmplMailMsg, 0 );
}
}
}
catch( Exception& )
{
}
//--------------------------------------------------
// shutdown
//--------------------------------------------------
// Cast factory to XComponent
Reference< XComponent > xComponent( g_xFactory, UNO_QUERY );
// Print a message if an error occurred.
if ( xComponent.is() == sal_False )
{
OSL_ENSURE(sal_False, "Error shutting down");
}
// Dispose and clear factory
xComponent->dispose();
g_xFactory.clear();
g_xFactory = Reference< XMultiServiceFactory >();
printf("Test successful\n");
return 0;
}
| 33.518919 | 126 | 0.541042 | Grosskopf |
96bba7b9ab561f38e4598dc669f60b9304497550 | 1,609 | cpp | C++ | Libraries/RobsJuceModules/jura_framework/gui/misc/jura_DescribedComponent.cpp | elanhickler/RS-MET | c04cbe660ea426ddf659dfda3eb9cba890de5468 | [
"FTL"
] | null | null | null | Libraries/RobsJuceModules/jura_framework/gui/misc/jura_DescribedComponent.cpp | elanhickler/RS-MET | c04cbe660ea426ddf659dfda3eb9cba890de5468 | [
"FTL"
] | null | null | null | Libraries/RobsJuceModules/jura_framework/gui/misc/jura_DescribedComponent.cpp | elanhickler/RS-MET | c04cbe660ea426ddf659dfda3eb9cba890de5468 | [
"FTL"
] | 1 | 2017-10-15T07:25:41.000Z | 2017-10-15T07:25:41.000Z | // construction/destruction:
DescribedItem::DescribedItem(const String& newDescription)
{
description = newDescription;
descriptionField = NULL;
}
DescribedItem::~DescribedItem()
{
}
// setup:
void DescribedItem::setDescription(const String &newDescription)
{
description = newDescription;
if( descriptionField != NULL )
descriptionField->setText(description);
}
void DescribedItem::setDescriptionField(RTextField *newDescriptionField)
{
if( descriptionField != NULL )
descriptionField->setText(String()); // clear the old field
descriptionField = newDescriptionField;
}
// inquiry:
String DescribedItem::getDescription() const
{
return description;
}
RTextField* DescribedItem::getDescriptionField() const
{
return descriptionField;
}
//=================================================================================================
void DescribedComponent::mouseEnter(const juce::MouseEvent &e)
{
if( descriptionField != NULL )
descriptionField->setText(description);
}
void DescribedComponent::mouseExit(const MouseEvent &e)
{
if( descriptionField != NULL )
descriptionField->setText(String());
}
void DescribedComponent::repaintOnMessageThread()
{
if(MessageManager::getInstance()->isThisTheMessageThread())
repaint();
else
{
/*
* Passing a safe ptr to avoid accidentally calling this while the editor is being
* destroyed during an automation move.
*/
Component::SafePointer<DescribedComponent> ptr = { this };
MessageManager::callAsync([=] {if (ptr) ptr.getComponent()->repaint(); });
}
} | 22.985714 | 99 | 0.675575 | elanhickler |