hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
48.5k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
26bfb69c0adfc8d5e94b03e09915e26d9ead7a9b
| 4,603
|
cc
|
C++
|
crc32.cc
|
bisqwit/viewnes
|
57a06b36b7a599e976a20459cb929786d506b84b
|
[
"Zlib"
] | 12
|
2017-04-27T18:50:31.000Z
|
2022-02-18T04:13:13.000Z
|
crc32.cc
|
bisqwit/viewnes
|
57a06b36b7a599e976a20459cb929786d506b84b
|
[
"Zlib"
] | null | null | null |
crc32.cc
|
bisqwit/viewnes
|
57a06b36b7a599e976a20459cb929786d506b84b
|
[
"Zlib"
] | 3
|
2017-04-28T13:23:23.000Z
|
2020-05-15T10:56:11.000Z
|
/*** CRC32 calculation (CRC::update) ***/
#include "crc32.h"
#ifdef __GNUC__
# define likely(x) __builtin_expect(!!(x), 1)
# define unlikely(x) __builtin_expect(!!(x), 0)
#else
# define likely(x) (x)
# define unlikely(x) (x)
#endif
namespace {
/* This code constructs the CRC32 table at compile-time,
* avoiding the need for a huge explicitly written table of magical numbers. */
static const uint_least32_t crc32_poly = 0xEDB88320UL;
/*
template<uint_fast32_t crc> // One bit of a CRC32:
struct b1 { enum { res = (crc >> 1) ^ (( crc&1) ? crc32_poly : 0UL) }; };
template<uint_fast32_t i> // One byte of a CRC32 (eight bits):
struct b8 { enum { res = b1<b1<b1<b1< b1<b1<b1<b1<i
>::res>::res>::res>::res>::res>::res>::res>::res }; };
*/
template<uint_fast32_t crc> // One byte of a CRC32 (eight bits):
struct b8
{
enum { b1 = (crc & 1) ? (crc32_poly ^ (crc >> 1)) : (crc >> 1),
b2 = (b1 & 1) ? (crc32_poly ^ (b1 >> 1)) : (b1 >> 1),
b3 = (b2 & 1) ? (crc32_poly ^ (b2 >> 1)) : (b2 >> 1),
b4 = (b3 & 1) ? (crc32_poly ^ (b3 >> 1)) : (b3 >> 1),
b5 = (b4 & 1) ? (crc32_poly ^ (b4 >> 1)) : (b4 >> 1),
b6 = (b5 & 1) ? (crc32_poly ^ (b5 >> 1)) : (b5 >> 1),
b7 = (b6 & 1) ? (crc32_poly ^ (b6 >> 1)) : (b6 >> 1),
res= (b7 & 1) ? (crc32_poly ^ (b7 >> 1)) : (b7 >> 1) };
/*
enum { b1 = (crc>> 1) ^ ((crc&1) ? crc32_poly : 0UL),
b2 = (b1 >> 1) ^ (( b1&1) ? crc32_poly : 0UL),
b3 = (b2 >> 1) ^ (( b2&1) ? crc32_poly : 0UL),
b4 = (b3 >> 1) ^ (( b3&1) ? crc32_poly : 0UL),
b5 = (b4 >> 1) ^ (( b4&1) ? crc32_poly : 0UL),
b6 = (b5 >> 1) ^ (( b5&1) ? crc32_poly : 0UL),
b7 = (b6 >> 1) ^ (( b6&1) ? crc32_poly : 0UL),
res= (b7 >> 1) ^ (( b7&1) ? crc32_poly : 0UL),
};*/
};/**/
// Four values of the table
#define B4(n) b8<n>::res,b8<n+1>::res,b8<n+2>::res,b8<n+3>::res
// Sixteen values of the table
#define R(n) B4(n),B4(n+4),B4(n+8),B4(n+12)
// The whole table, index by steps of 16
static const uint_least32_t crctable[256] =
{ R(0x00),R(0x10),R(0x20),R(0x30), R(0x40),R(0x50),R(0x60),R(0x70),
R(0x80),R(0x90),R(0xA0),R(0xB0), R(0xC0),R(0xD0),R(0xE0),R(0xF0) };
#undef R
#undef B4
}
uint_fast32_t crc32_update(uint_fast32_t crc, unsigned/* char */b) // __attribute__((pure))
{
return ((crc >> 8) /* & 0x00FFFFFF*/) ^ crctable[/*(unsigned char)*/(crc^b)&0xFF];
}
crc32_t crc32_calc(const unsigned char* buf, unsigned long size)
{
return crc32_calc_upd(crc32_startvalue, buf, size);
}
crc32_t crc32_calc_upd(crc32_t c, const unsigned char* buf, unsigned long size)
{
uint_fast32_t value = c;
#if 0
unsigned long pos = 0;
while(size-- > 0) value = crc32_update(value, buf[pos++]);
#endif
#if 1
for(unsigned long p=0; p<size; ++p) value = crc32_update(value, buf[p]);
#endif
#if 0
unsigned unaligned_length = (4 - (unsigned long)(buf)) & 3;
if(size < unaligned_length) unaligned_length = size;
switch(unaligned_length)
{
case 3: value = crc32_update(value, *buf++);
case 2: value = crc32_update(value, *buf++);
case 1: value = crc32_update(value, *buf++);
size -= unaligned_length;
case 0: break;
}
for(; size >= 4; size -= 4, buf += 4)
value = crc32_update(
crc32_update(
crc32_update(
crc32_update(value, buf[0]),
buf[1]),
buf[2]),
buf[3]);
switch(size)
{
case 3: value = crc32_update(value, *buf++);
case 2: value = crc32_update(value, *buf++);
case 1: value = crc32_update(value, *buf++);
case 0: break;
}
#endif
#if 0 /* duff's device -- no gains observed over the simple loop above */
if(__builtin_expect( (size!=0), 1l ))
{
{ if(__builtin_expect( !(size&1), 1l )) goto case_0;
--buf; goto case_1;
}
//switch(size % 2)
{
//default:
do { size -= 2; buf += 2;
case_0: value = crc32_update(value, buf[0]);
case_1: value = crc32_update(value, buf[1]);
} while(size > 2);
}
}
#endif
#if 0
while(size-- > 0) value = crc32_update(value, *buf++);
#endif
return value;
}
| 35.137405
| 91
| 0.499022
|
bisqwit
|
26c0ab11e8a0f7adf9ac4038fc44c7d6120e7d7f
| 232
|
hxx
|
C++
|
src/sdp_solve.hxx
|
ChrisPattison/sdpb
|
4668f72c935e7feba705dd8247d9aacb23185f1c
|
[
"MIT"
] | 45
|
2015-02-10T15:45:22.000Z
|
2022-02-24T07:45:01.000Z
|
src/sdp_solve.hxx
|
ChrisPattison/sdpb
|
4668f72c935e7feba705dd8247d9aacb23185f1c
|
[
"MIT"
] | 58
|
2015-02-27T10:03:18.000Z
|
2021-08-10T04:21:42.000Z
|
src/sdp_solve.hxx
|
ChrisPattison/sdpb
|
4668f72c935e7feba705dd8247d9aacb23185f1c
|
[
"MIT"
] | 38
|
2015-02-10T11:11:27.000Z
|
2022-02-11T20:59:42.000Z
|
#pragma once
#include "sdp_solve/Block_Info.hxx"
#include "sdp_solve/SDP_Solver.hxx"
#include "sdp_solve/Write_Solution.hxx"
#include "sdp_solve/read_text_block.hxx"
El::BigFloat dot(const Block_Vector &A, const Block_Vector &B);
| 25.777778
| 63
| 0.793103
|
ChrisPattison
|
26c11d4769736abe92dd9be916a8e4c5fe2ca2b3
| 815
|
cpp
|
C++
|
week4_divide_and_conquer/2_majority_element/majority_element.cpp
|
balajimohan80/Algorithm_Toolbox
|
e10e5ed811e2d5179d760e25ca82c29df2a879db
|
[
"MIT"
] | null | null | null |
week4_divide_and_conquer/2_majority_element/majority_element.cpp
|
balajimohan80/Algorithm_Toolbox
|
e10e5ed811e2d5179d760e25ca82c29df2a879db
|
[
"MIT"
] | null | null | null |
week4_divide_and_conquer/2_majority_element/majority_element.cpp
|
balajimohan80/Algorithm_Toolbox
|
e10e5ed811e2d5179d760e25ca82c29df2a879db
|
[
"MIT"
] | null | null | null |
#include <algorithm>
#include <iostream>
#include <vector>
using std::vector;
int get_majority_element(vector<int> &a, int left, int right) {
if (left == right) return -1;
if (left+1 == right) return -1;
//if (left + 1 == right) return a[left];
//write your code here
std::sort(a.begin(), a.end(), [](int a, int b) {return a < b; });
int Mid = a.size() >> 1;
int Count = 0;
while (Mid-1 >= 0 && a[Mid] == a[Mid-1]) {
++Count;
--Mid;
}
Mid = a.size() >> 1;
while (Mid + 1 < a.size() && a[Mid] == a[Mid + 1]) {
++Count;
++Mid;
}
return (Count >= (a.size() >> 1)) ? 1 : -1;
}
int main() {
int n;
std::cin >> n;
vector<int> a(n);
for (size_t i = 0; i < a.size(); ++i) {
std::cin >> a[i];
}
std::cout << (get_majority_element(a, 0, a.size()) != -1) << '\n';
}
| 20.897436
| 68
| 0.507975
|
balajimohan80
|
26c78b77ce1bb48d251db287731d261b49d6d024
| 1,025
|
hpp
|
C++
|
include/core/initialization.hpp
|
ida-zrt/thermalvis
|
36a6ba0d12ab91097435630586e3eb760130582c
|
[
"BSD-3-Clause"
] | 109
|
2015-02-03T23:30:59.000Z
|
2022-02-22T03:24:36.000Z
|
include/core/initialization.hpp
|
adaniy/thermalvis
|
782f71b5fbde033d226d11b8d0c994fc83d10d98
|
[
"BSD-3-Clause"
] | 9
|
2015-02-19T05:46:36.000Z
|
2021-11-02T14:00:49.000Z
|
include/core/initialization.hpp
|
adaniy/thermalvis
|
782f71b5fbde033d226d11b8d0c994fc83d10d98
|
[
"BSD-3-Clause"
] | 59
|
2015-11-05T11:51:55.000Z
|
2022-03-11T06:36:57.000Z
|
/*! \file initialization.hpp
* \brief (probably an obsolete file)
*/
#ifndef _THERMALVIS_INITIALIZATION_H_
#define _THERMALVIS_INITIALIZATION_H_
#ifdef _BUILD_FOR_ROS_
#include "core/general_resources.hpp"
#include "core/ros_resources.hpp"
#include "core/features.hpp"
#define MAXIMUM_FRAMES_TO_STORE 2000 // careful about setting this too high for memory
#define MAXIMUM_FEATURES_PER_DETECTOR 5000
#define DEFAULT_MAX_FRAMES 100
/// \brief (probably obsolete..)
struct initializationData {
string video_stream;
int max_frame_count;
bool debugMode;
string detector[MAX_DETECTORS], descriptor[MAX_DETECTORS];
double sensitivity[MAX_DETECTORS];
string method[MAX_DETECTORS];
bool method_match[MAX_DETECTORS];
unsigned int numDetectors;
string intrinsics;
bool obtainStartingData(ros::NodeHandle& nh);
void initializeDetectors(cv::Ptr<cv::FeatureDetector> *det);
void initializeDescriptors(cv::Ptr<cv::DescriptorExtractor> *desc);
};
#endif
#endif // _THERMALVIS_INITIALIZATION_H_
| 24.404762
| 88
| 0.782439
|
ida-zrt
|
26c859b46a25a7d04be90b4f4c2639c50b239922
| 721
|
hpp
|
C++
|
header/friedrichdb/fake_file_storage.hpp
|
jinncrafters/friedrichdb
|
313180fee8f230b2a406000b948210c77c4253a3
|
[
"BSD-3-Clause"
] | 1
|
2018-01-26T09:15:01.000Z
|
2018-01-26T09:15:01.000Z
|
header/friedrichdb/fake_file_storage.hpp
|
duckstax/friedrichdb
|
313180fee8f230b2a406000b948210c77c4253a3
|
[
"BSD-3-Clause"
] | 1
|
2018-06-21T07:41:38.000Z
|
2018-06-21T07:41:38.000Z
|
header/friedrichdb/fake_file_storage.hpp
|
duckstax/friedrichdb
|
313180fee8f230b2a406000b948210c77c4253a3
|
[
"BSD-3-Clause"
] | null | null | null |
#ifndef FILE_STORAGE_HPP
#define FILE_STORAGE_HPP
#include "abstract_database.hpp"
#include <vector>
#include <functional>
namespace friedrichdb {
class file_storage_fake final : public abstract_database {
public:
file_storage_fake():abstract_database(storge_t::disk){}
~file_storage_fake(){}
abstract_table *table(const std::string &name) {
return nullptr;
}
abstract_table *table(const std::string &name) const {
return nullptr;
}
bool table(const std::string &, abstract_table *) {
return true;
}
bool table(schema&&){
return true;
}
};
}
#endif //VERSIONS_FILE_STORAGE_HPP
| 24.033333
| 63
| 0.619972
|
jinncrafters
|
26c9c3a27b15384bc70a19d1089b93514861ff79
| 21,272
|
cpp
|
C++
|
ShadowMapping/CascadedShadowMappingRenderer.cpp
|
LYP951018/EasyDX
|
10b5a04c13af1fc6c3b405e309dc754a42530011
|
[
"Apache-2.0"
] | 3
|
2017-03-12T07:26:56.000Z
|
2017-11-20T13:01:46.000Z
|
ShadowMapping/CascadedShadowMappingRenderer.cpp
|
LYP951018/EasyDX
|
10b5a04c13af1fc6c3b405e309dc754a42530011
|
[
"Apache-2.0"
] | 9
|
2019-04-27T08:36:01.000Z
|
2021-11-25T16:36:02.000Z
|
ShadowMapping/CascadedShadowMappingRenderer.cpp
|
LYP951018/EasyDX
|
10b5a04c13af1fc6c3b405e309dc754a42530011
|
[
"Apache-2.0"
] | 2
|
2018-04-16T09:41:56.000Z
|
2021-11-01T06:17:58.000Z
|
#include "Pch.hpp"
#if 1
#include "CascadedShadowMappingRenderer.hpp"
#include <DirectXColors.h>
using namespace DirectX;
using namespace dx;
CascadedShadowMappingRenderer::CascadedShadowMappingRenderer(
ID3D11Device& device3D, const CascadedShadowMapConfig& shadowMapConfig)
: m_config{shadowMapConfig}, m_partitions{shadowMapConfig.Intervals}
{
CreateDepthGenerationResources(device3D);
CreateCsmGenerationResources(device3D, shadowMapConfig.ShadowMapSize);
CreateSssmRt(device3D, shadowMapConfig.ScreenSpaceTexSize);
}
XMMATRIX OrthographicFromBoundingBox(const BoundingBox& box)
{
XMFLOAT3 corners[8];
box.GetCorners(corners);
const XMFLOAT3& minPoint = corners[2];
const XMFLOAT3& maxPoint = corners[4];
return XMMatrixOrthographicOffCenterLH(minPoint.x, maxPoint.x, minPoint.y,
maxPoint.y, minPoint.z, maxPoint.z);
}
DirectX::BoundingBox BoxFromFrutum(const BoundingFrustum& frustum)
{
XMFLOAT3 corners[8];
frustum.GetCorners(corners);
DirectX::BoundingBox box;
BoundingBox::CreateFromPoints(box, 8, corners, sizeof(XMFLOAT3));
return box;
}
void CascadedShadowMappingRenderer::GenerateShadowMap(
const dx::GlobalGraphicsContext& gfxContext, const dx::Camera& camera,
gsl::span<const dx::Light> lights, gsl::span<const RenderNode> renderNodes,
const dx::GlobalShaderContext& shaderContext)
{
ID3D11DeviceContext& context3D = gfxContext.Context3D();
// first pass: collect depth in view space
// 为了从 screen space 还原到 world space。
std::array<ID3D11RenderTargetView* const, 1> nullView = {};
context3D.OMSetRenderTargets(1, nullView.data(), m_worldDepthView.Get());
// context3D.ClearRenderTargetView(rt, color.data());
context3D.ClearDepthStencilView(m_worldDepthView.Get(), D3D11_CLEAR_DEPTH, 1.0f, 0);
RunShadowCaster(renderNodes, shaderContext, context3D);
BoundingBox viewSpaceSceneAabb;
BoundingBox::CreateFromPoints(viewSpaceSceneAabb, g_XMNegInfinity,
g_XMInfinity);
for (const RenderNode& renderNode : renderNodes)
{
const BoundingBox& localBoundingBox = renderNode.mesh.GetBoundingBox();
BoundingBox worldBoundingBox;
localBoundingBox.Transform(worldBoundingBox,
renderNode.World * camera.GetView());
BoundingBox::CreateMerged(viewSpaceSceneAabb, viewSpaceSceneAabb,
worldBoundingBox);
}
// m_viewSpaceDepthMap contains what we want
// second pass: CSM
BoundingFrustum frustum = camera.Frustum();
const dx::Light& mainLight = lights[0];
BoundingFrustum lightSpaceFrustum;
XMMATRIX lightSpaceViewMatrix;
XMMATRIX lightSpaceProjMatrix;
XMMATRIX viewToLight;
switch (mainLight.index())
{
case dx::kDirectionalLight:
{
auto& directionalLight = std::get<DirectionalLight>(mainLight);
lightSpaceViewMatrix = XMMatrixLookToLH(
XMVectorZero(), Load(directionalLight.Direction),
XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f));
viewToLight =
XMMatrixInverse({}, camera.GetView()) * lightSpaceViewMatrix;
BoundingBox lightSpaceAabb;
viewSpaceSceneAabb.Transform(lightSpaceAabb, viewToLight);
lightSpaceProjMatrix = OrthographicFromBoundingBox(lightSpaceAabb);
}
}
frustum.Transform(lightSpaceFrustum, viewToLight);
// BoundingBox lightSpaceFrustumBox = BoxFromFrutum(lightSpaceFrustum);
// lightSpaceProjMatrix =
// OrthographicFromBoundingBox(lightSpaceFrustumBox);
const std::uint32_t partitionCount = kCascadedCount;
dx::GlobalShaderContext shaderContextForShadowMapping = shaderContext;
shaderContextForShadowMapping.ViewMatrix = lightSpaceViewMatrix;
const float nearZ =
std::max(frustum.Near,
viewSpaceSceneAabb.Center.z - viewSpaceSceneAabb.Extents.z);
const float farZ =
viewSpaceSceneAabb.Center.z + viewSpaceSceneAabb.Extents.z;
const float nearFarDistance = farZ - nearZ;
const XMFLOAT4 colors[] = {
XMFLOAT4{1.0f, 0.0f, 0.0f, 1.0f},
XMFLOAT4{0.0f, 1.0f, 0.0f, 1.0f},
XMFLOAT4{0.0f, 0.0f, 1.0f, 1.0f},
XMFLOAT4{1.0f, 1.0f, 0.0f, 1.0f},
};
D3D11_VIEWPORT viewport{
0.0f, 0.0f, m_config.ShadowMapSize.Width, m_config.ShadowMapSize.Height, 0, 1
};;
context3D.RSSetViewports(1, &viewport);
for (std::uint32_t i = 0; i < partitionCount; ++i)
{
const float low = nearZ + m_partitions[i] * nearFarDistance;
const float high = nearZ + m_partitions[i + 1] * nearFarDistance;
m_intervals[i] = low;
XMMATRIX projMatrix = CalcLightProjMatrix(
mainLight, frustum, low, high, lightSpaceProjMatrix,
viewSpaceSceneAabb, viewToLight);
shaderContextForShadowMapping.ProjMatrix =
lightSpaceProjMatrix * projMatrix;
if (!m_lightSpaceFrustum[i])
{
m_lightSpaceFrustum[i] = MeshFromFrustum(
gfxContext.Device3D(), lightSpaceFrustum, colors[i]);
}
shaderContextForShadowMapping.ViewProjMatrix =
shaderContextForShadowMapping.ViewMatrix *
shaderContextForShadowMapping.ProjMatrix;
m_lightViewProjs[i] = viewToLight * shaderContextForShadowMapping.ProjMatrix;
ID3D11RenderTargetView* rt = m_shadowMapRtViews[i].Get();
context3D.OMSetRenderTargets(1, &rt, m_shadowMapRtDepthStencil.View());
std::array<float, 4> color = {};
context3D.ClearRenderTargetView(rt, color.data());
m_shadowMapRtDepthStencil.ClearBoth(context3D);
ShaderInputs inputs;
for (const RenderNode& renderNode : renderNodes)
{
// FIXME:如何避免上一个对象设置的 buffer 遗留的问题?
FillUpShaders(context3D, renderNode.material.shadowCasterPass,
renderNode.World, nullptr,
shaderContextForShadowMapping);
DrawMesh(context3D, renderNode.mesh,
*renderNode.material.shadowCasterPass.pass);
}
}
/*if (!m_cubePass)
{
const auto mappedCso =
MemoryMappedCso{fs::current_path() / L"CubeVS.cso"};
m_cubePass = std::make_shared<Pass>(Pass{MakeShaderCollection(
Shader{gfxContext.Device3D(), mappedCso.Bytes()},
dx::Shader::FromCompiledCso(gfxContext.Device3D(),
fs::current_path() / L"CubePS.cso"))});
InputLayoutAllocator::Register(
gfxContext.Device3D(),
m_lightSpaceFrustum[0]->GetFullInputElementDesces(),
mappedCso.Bytes());
}
std::array<ID3D11RenderTargetView* const, 1> views = {gfxContext.MainRt()};
context3D.OMSetRenderTargets(1, views.data(),
gfxContext.GetDepthStencil().View());
for (const std::shared_ptr<dx::Mesh>& mesh : m_lightSpaceFrustum)
{
FillUpShaders(context3D, dx::PassWithShaderInputs{m_cubePass},
XMMatrixIdentity(), nullptr, shaderContext);
DrawMesh(context3D, *mesh, *m_cubePass);
}*/
ID3D11RenderTargetView* rts[] = { m_sssmRt.Get() };
context3D.OMSetRenderTargets(1, rts, nullptr);
D3D11_VIEWPORT viewport2{
0.0f, 0.0f, m_config.ScreenSpaceTexSize.Width, m_config.ScreenSpaceTexSize.Height, 0, 1
};;
context3D.RSSetViewports(1, &viewport2);
float color[4] = {};
context3D.ClearRenderTargetView(m_sssmRt.Get(), color);
ShaderInputs& inputs = m_collectPass.inputs;
const XMMATRIX invProj = XMMatrixInverse({}, camera.GetProjection());
inputs.SetField("InvProj", invProj);
inputs.SetField("lightSpaceProjs", m_lightViewProjs);
inputs.SetField("Intervals", m_intervals);
inputs.Bind("DepthMap", m_depthSrv);
inputs.Bind("ShadowMapArray", m_shadowMapTexArraySrv);
inputs.Bind("NearestPointSampler", m_nearestPointSampler);
FillUpShaders(context3D, m_collectPass,
DirectX::XMMatrixIdentity(), nullptr,
shaderContextForShadowMapping);
DrawMesh(context3D, *m_screenSpaceQuad,
m_collectPass.pass, &gfxContext.Device3D());
ID3D11ShaderResourceView* srvs[] = { nullptr, nullptr };
context3D.PSSetShaderResources(0, 2, srvs);
context3D.VSSetShaderResources(0, 2, srvs);
// m_depthTexArray has been filled.
// last pass: generate screen space shadowmap
// auto invViewProj = XMMatrixInverse({},
// XMMatrixTranspose(shaderContext.ViewProjMatrix));
// dx::ShaderInputs additionalInputs;
//// viewspace
// additionalInputs.SetField("lightSpaceProjs", m_lightViewProjs);
// additionalInputs.SetField("InvProj", m_lightViewProjs);
// additionalInputs.Bind("DepthTex", m_shadowMapTexArraySrv);
// additionalInputs.Bind("DepthTexSampler", m_nearestPointSampler);
// DrawMesh(context3D, *m_quad, m_collectPass);
}
wrl::ComPtr<ID3D11ShaderResourceView>
CascadedShadowMappingRenderer::GetCsmTexArray() const
{
return m_shadowMapTexArraySrv;
}
void CascadedShadowMappingRenderer::RunShadowCaster(
gsl::span<const dx::RenderNode>& renderNodes,
const dx::GlobalShaderContext& shaderContextForShadowMapping,
ID3D11DeviceContext& context3D)
{
for (const RenderNode& renderNode : renderNodes)
{
const Material& material = renderNode.material;
if (material.shadowCasterPass.pass)
{
FillUpShaders(context3D, material.shadowCasterPass,
renderNode.World, nullptr,
shaderContextForShadowMapping);
DrawMesh(context3D, renderNode.mesh,
*material.shadowCasterPass.pass);
}
}
}
void CascadedShadowMappingRenderer::DrawCube(
gsl::span<const DirectX::XMFLOAT3> points)
{}
std::shared_ptr<dx::Mesh> CascadedShadowMappingRenderer::MeshFromFrustum(
ID3D11Device& device3D, const DirectX::BoundingFrustum& frustum,
const XMFLOAT4& color)
{
XMFLOAT3 corners[8];
frustum.GetCorners(corners);
const ShortIndex indices[] = {3, 0, 1, 1, 2, 3, 7, 4, 5, 5, 6, 7,
7, 4, 0, 0, 3, 7, 2, 1, 5, 5, 6, 2,
4, 0, 1, 0, 1, 5, 7, 3, 2, 3, 2, 6};
const XMFLOAT4 colors[] = {color, color, color, color,
color, color, color, color};
const VSSemantics semantics[] = {VSSemantics::kPosition,
VSSemantics::kColor};
const DxgiFormat formats[] = {DxgiFormat::R32G32B32Float,
DxgiFormat::R32G32B32A32Float};
const std::uint32_t semanticsIndices[] = {0, 0};
/*
4 0
7 3
*/
std::vector<D3D11_INPUT_ELEMENT_DESC> inputDesc;
dx::FillInputElementsDesc(inputDesc, gsl::make_span(semantics),
gsl::make_span(formats),
gsl::make_span(semanticsIndices));
return Mesh::CreateImmutable(device3D, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST,
gsl::make_span(indices), semantics, 8,
std::move(inputDesc), corners, colors);
}
DirectX::XMMATRIX CascadedShadowMappingRenderer::CalcLightProjMatrix(
const dx::Light& light, DirectX::BoundingFrustum& existingFrustum,
float low, float high, const XMMATRIX& lightProjMatrix,
const DirectX::BoundingBox& viewSpaceAabb, const XMMATRIX& viewToLight)
{
switch (light.index())
{
case kDirectionalLight:
{
// BUG:
//上面的 viewSpaceSceneAabb 是物体求出的
// AABB,视锥角落的点可能不在这里面,导致变换到 homo space
//外面。
existingFrustum.Near = low;
existingFrustum.Far = high;
XMFLOAT3 frustumCorners[8];
XMFLOAT3 boxCorners[8];
XMFLOAT3 corners[8];
BoundingBox frustumBox;
existingFrustum.GetCorners(frustumCorners);
BoundingBox::CreateFromPoints(frustumBox, 8, frustumCorners,
sizeof(XMFLOAT3));
frustumBox.GetCorners(frustumCorners);
viewSpaceAabb.GetCorners(boxCorners);
/*
const auto select = [&](int index) {
const XMFLOAT3& boxCorner = boxCorners[index];
const XMFLOAT3& frustumCorner = frustumCorners[index];
const XMVECTOR minBox = XMLoadFloat3(&boxCorner);
const XMVECTOR minFrustum = XMLoadFloat3(&frustumCorner);
return XMVectorMin(g_BoxOffset[index] * minBox,
g_BoxOffset[index] * minFrustum);
};
BoundingBox newBox;
BoundingBox::CreateFromPoints(newBox, select(2), select(4));
newBox.GetCorners(corners);*/
for (int i = 0; i < 8; ++i)
{
const float* offset = g_BoxOffset[i];
const XMFLOAT3& boxCorner = boxCorners[i];
const XMFLOAT3& frustumCorner = frustumCorners[i];
const auto select = [&](int index) {
const float selector = offset[index];
return selector *
std::min(selector * (&boxCorner.x)[index],
selector * (&frustumCorner.x)[index]);
};
corners[i] = {select(0), select(1), select(2)};
}
BoundingBox newBox;
BoundingBox::CreateFromPoints(newBox, 8, corners, sizeof(XMFLOAT3));
newBox.Transform(newBox, viewToLight);
newBox.GetCorners(corners);
// for (int i = 0; i < 8; ++i)
//{
// const XMFLOAT3& frustumCorner = frustumCorners[i];
// const XMFLOAT3& boxCorner = boxCorners[i];
// const XMVECTOR minimum =
//XMVectorMin(XMLoadFloat3(&frustumCorner),
//XMLoadFloat3(&boxCorner)); XMStoreFloat3(corners + i, minimum);
//}
// Then, each corner point p of the camera’s
// frustum slice is projected into p h = PMp in the light’s
// homogeneous space.
for (XMFLOAT3& corner : corners)
{
XMFLOAT4 position = {corner.x, corner.y, corner.z, 1.0f};
XMVECTOR loaded = XMLoadFloat4(&position);
loaded = XMVector4Transform(loaded, lightProjMatrix);
loaded /= XMVectorGetW(loaded);
XMStoreFloat3(&corner, loaded);
}
BoundingBox lightHomoBox;
BoundingBox::CreateFromPoints(lightHomoBox, 8, corners,
sizeof(XMFLOAT3));
lightHomoBox.GetCorners(corners);
const XMFLOAT3& minPoint = corners[2];
const XMFLOAT3& maxPoint = corners[4];
return XMMatrixOrthographicOffCenterLH(minPoint.x, maxPoint.x,
minPoint.y, maxPoint.y,
minPoint.z, maxPoint.z);
}
default:
break;
}
}
void CascadedShadowMappingRenderer::CreateCsmGenerationResources(
ID3D11Device& device3D, dx::Size size)
{
D3D11_TEXTURE2D_DESC depthTexArrayDesc{};
depthTexArrayDesc.ArraySize = kCascadedCount;
depthTexArrayDesc.Width = size.Width;
depthTexArrayDesc.Height = size.Height;
depthTexArrayDesc.Usage = D3D11_USAGE_DEFAULT;
depthTexArrayDesc.BindFlags =
D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;
depthTexArrayDesc.Format = DXGI_FORMAT_R32_FLOAT;
depthTexArrayDesc.MipLevels = 1;
depthTexArrayDesc.SampleDesc.Count = 1;
TryHR(device3D.CreateTexture2D(&depthTexArrayDesc, nullptr,
m_depthTexArray.GetAddressOf()));
D3D11_SHADER_RESOURCE_VIEW_DESC rsvDesc{};
rsvDesc.Format = DXGI_FORMAT_R32_FLOAT;
rsvDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURE2DARRAY;
D3D11_TEX2D_ARRAY_SRV& tex2DArray = rsvDesc.Texture2DArray;
tex2DArray.ArraySize = kCascadedCount;
tex2DArray.MipLevels = 1;
tex2DArray.MostDetailedMip = 0;
tex2DArray.FirstArraySlice = 0;
TryHR(device3D.CreateShaderResourceView(
m_depthTexArray.Get(), &rsvDesc,
m_shadowMapTexArraySrv.GetAddressOf()));
D3D11_RENDER_TARGET_VIEW_DESC rtViewDesc{};
rtViewDesc.Format = DXGI_FORMAT_R32_FLOAT;
rtViewDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DARRAY;
D3D11_TEX2D_ARRAY_RTV& rtTexArray = rtViewDesc.Texture2DArray;
rtTexArray.MipSlice = 0;
rtTexArray.ArraySize = 1;
for (unsigned i = 0; i < kCascadedCount; ++i)
{
rtViewDesc.Texture2DArray.FirstArraySlice =
D3D11CalcSubresource(0, i, 1);
TryHR(device3D.CreateRenderTargetView(
m_depthTexArray.Get(), &rtViewDesc,
m_shadowMapRtViews[i].GetAddressOf()));
}
m_shadowMapRtDepthStencil = DepthStencil{device3D, size};
}
void CascadedShadowMappingRenderer::CreateSssmRt(ID3D11Device& device3D,
dx::Size size)
{
D3D11_TEXTURE2D_DESC texDesc{};
texDesc.Width = size.Width;
texDesc.Height = size.Height;
texDesc.MipLevels = 1;
texDesc.ArraySize = 1;
texDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
texDesc.Usage = D3D11_USAGE_DEFAULT;
texDesc.BindFlags = D3D11_BIND_RENDER_TARGET;
texDesc.SampleDesc.Count = 1;
TryHR(device3D.CreateTexture2D(&texDesc, nullptr,
m_screenSpaceShadowMap.GetAddressOf()));
D3D11_RENDER_TARGET_VIEW_DESC rtDesc{};
rtDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
rtDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
TryHR(device3D.CreateRenderTargetView(m_screenSpaceShadowMap.Get(), &rtDesc,
m_sssmRt.GetAddressOf()));
const ShortIndex quadIndices[] = {0, 1, 2, 2, 1, 3};
const PositionType quadPositions[] = {
MakePosition(-1.0f, 1.0f, 1.0f),
MakePosition(1.0f, 1.0f, 1.0f),
MakePosition(-1.0f, -1.0f, 1.0f),
MakePosition(1.0f, -1.0f, 1.0f),
};
const TexCoordType quadTexCoords[] = {
MakeTexCoord(0.0f, 0.0f), MakeTexCoord(1.0f, 0.0f),
MakeTexCoord(0.0f, 1.0f), MakeTexCoord(1.0f, 1.0f)};
VSSemantics semantics[] = {
VSSemantics::kPosition, VSSemantics::kTexCoord
};
DxgiFormat formats[] = {
DxgiFormat::R32G32B32A32Float,
DxgiFormat::R32G32Float
};
std::uint32_t indices[] = { 0, 0 };
std::vector<D3D11_INPUT_ELEMENT_DESC> inputElementsDesces;
FillInputElementsDesc(inputElementsDesces, semantics, formats,
indices);
m_screenSpaceQuad = Mesh::CreateImmutable(
device3D, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, gsl::span(quadIndices),
semantics, 4, std::move(inputElementsDesces),
quadPositions, quadTexCoords);
m_collectPass.pass = std::make_shared<dx::Pass>(dx::Pass
{
MakeShaderCollection(
dx::Shader::FromCompiledCso(device3D, fs::current_path() /
"ShadowCollectVS.cso"),
dx::Shader::FromCompiledCso(device3D, fs::current_path() /
L"ShadowCollectPS.cso"))
});
CD3D11_SAMPLER_DESC samplerDesc{ CD3D11_DEFAULT{} };
samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_POINT;
TryHR(device3D.CreateSamplerState(&samplerDesc, m_nearestPointSampler.GetAddressOf()));
}
void CascadedShadowMappingRenderer::CreateDepthGenerationResources(
ID3D11Device& device3D)
{
// first pass: collect depth
CD3D11_TEXTURE2D_DESC depthTexDesc{DXGI_FORMAT_R32G8X24_TYPELESS,
m_config.ScreenSpaceTexSize.Width,
m_config.ScreenSpaceTexSize.Height, 1, 1};
depthTexDesc.BindFlags |= D3D11_BIND_FLAG::D3D11_BIND_DEPTH_STENCIL;
TryHR(device3D.CreateTexture2D(&depthTexDesc, nullptr,
m_worldSpaceDepthMap.GetAddressOf()));
CD3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc{
D3D11_DSV_DIMENSION_TEXTURE2D, DXGI_FORMAT_D32_FLOAT_S8X24_UINT};
TryHR(device3D.CreateDepthStencilView(m_worldSpaceDepthMap.Get(),
&depthStencilViewDesc,
m_worldDepthView.GetAddressOf()));
CD3D11_SHADER_RESOURCE_VIEW_DESC srvDesc{
D3D11_SRV_DIMENSION_TEXTURE2D, DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS};
TryHR(device3D.CreateShaderResourceView(
m_worldSpaceDepthMap.Get(), &srvDesc, m_depthSrv.GetAddressOf()));
}
dx::Pass
CascadedShadowMappingRenderer::MakeCollectionPass(ID3D11Device& device3D)
{
throw std::runtime_error{"fuck"};
/*using namespace dx;
return Pass{ShaderCollection{
Shader::FromCompiledCso(device3D, fs::current_path() /
"SecondPassVS.hlsl"), Shader::FromCompiledCso(device3D,
fs::current_path() / "SecondPassPS.hlsl")}};*/
}
#endif
| 43.235772
| 95
| 0.639667
|
LYP951018
|
26ce3919b248d63aa4e81588360fa96dbb9b7b57
| 966
|
hpp
|
C++
|
include/bdlearn/BatchBlas.hpp
|
billythedummy/bdlearn
|
bdb7b22c326f8057ec3ec06a701d00885e801bfd
|
[
"MIT"
] | 2
|
2019-12-04T08:24:17.000Z
|
2020-01-31T23:29:52.000Z
|
include/bdlearn/BatchBlas.hpp
|
billythedummy/bdlearn
|
bdb7b22c326f8057ec3ec06a701d00885e801bfd
|
[
"MIT"
] | null | null | null |
include/bdlearn/BatchBlas.hpp
|
billythedummy/bdlearn
|
bdb7b22c326f8057ec3ec06a701d00885e801bfd
|
[
"MIT"
] | null | null | null |
#ifndef _BDLEARN_BATCHBLAS_H_
#define _BDLEARN_BATCHBLAS_H_
#include "Halide.h"
namespace bdlearn {
void BatchMatMul(Halide::Buffer<float> out, Halide::Buffer<float> A, Halide::Buffer<float> B);
void BatchMatMul_BT(Halide::Buffer<float> out, Halide::Buffer<float> A, Halide::Buffer<float> BT);
// A broadcasted, transposed
void BatchMatMul_ATBr(Halide::Buffer<float> out, Halide::Buffer<float> AT, Halide::Buffer<float> B);
// A broadcasted
//void BatchMatMul_ABr(Halide::Buffer<float> out, Halide::Buffer<float> A, Halide::Buffer<float> B);
/*
void BatchIm2Col(Halide::Buffer<float> out, Halide::Buffer<float> in,
const int p, const int s, const int k, const int out_width, const int out_height);*/
/*
void BatchCol2ImAccum(Halide::Buffer<float> out, Halide::Buffer<float> in,
const int p, const int s, const int k, const int out_width, const int out_height);*/
}
#endif
| 46
| 112
| 0.681159
|
billythedummy
|
26d9cce2051a4d4011dc367b9d511f6c5f400871
| 1,382
|
hpp
|
C++
|
MRedisConfig.hpp
|
MrMoose/mredis
|
5a60cc57c6193bd68eab9c0f6a9938c9530b8665
|
[
"BSL-1.0"
] | 4
|
2018-10-31T14:31:30.000Z
|
2019-07-31T11:45:57.000Z
|
MRedisConfig.hpp
|
MrMoose/mredis
|
5a60cc57c6193bd68eab9c0f6a9938c9530b8665
|
[
"BSL-1.0"
] | null | null | null |
MRedisConfig.hpp
|
MrMoose/mredis
|
5a60cc57c6193bd68eab9c0f6a9938c9530b8665
|
[
"BSL-1.0"
] | null | null | null |
// Copyright 2018 Stephan Menzel. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#pragma once
// see https://gcc.gnu.org/wiki/Visibility
// Generic helper definitions for shared library support
#if defined _WIN32 || defined __CYGWIN__
#define MREDIS_DLL_IMPORT __declspec(dllimport)
#define MREDIS_DLL_EXPORT __declspec(dllexport)
#define MREDIS_DLL_LOCAL
#ifndef NOMINMAX
#define NOMINMAX
#endif
#else
#if __GNUC__ >= 4
#define MREDIS_DLL_IMPORT __attribute__ ((visibility ("default")))
#define MREDIS_DLL_EXPORT __attribute__ ((visibility ("default")))
#define MREDIS_DLL_LOCAL __attribute__ ((visibility ("hidden")))
#else
#define MREDIS_DLL_IMPORT
#define MREDIS_DLL_EXPORT
#define MREDIS_DLL_LOCAL
#endif
#endif
#ifdef MREDIS_DLL // defined if is compiled as a DLL
#ifdef mredis_EXPORTS // defined if we are building the DLL (instead of using it)
#define MREDIS_API MREDIS_DLL_EXPORT
#else
#define MREDIS_API MREDIS_DLL_IMPORT
#endif // mredis_EXPORTS
#define MREDIS_LOCAL MREDIS_DLL_LOCAL
#else // MREDIS_DLL is not defined: this means it is a static lib.
#define MREDIS_API
#define MREDIS_LOCAL
#endif // MREDIS_DLL
#ifdef _MSC_VER
#pragma warning (disable : 4996) // Function call with parameters that may be unsafe.
#endif
| 29.404255
| 85
| 0.769899
|
MrMoose
|
26dc23fd0a6e7be3d02ec8fcd83019ef4b74e5ea
| 1,870
|
cpp
|
C++
|
hw/1,2/1.cpp
|
rgeorgiev583/FMI-DSP
|
7fac5ad4373bbcb8494b7675c21ad0458176a3d3
|
[
"MIT"
] | 1
|
2017-11-08T13:24:14.000Z
|
2017-11-08T13:24:14.000Z
|
hw/1,2/1.cpp
|
rgeorgiev583/FMI-DSP
|
7fac5ad4373bbcb8494b7675c21ad0458176a3d3
|
[
"MIT"
] | null | null | null |
hw/1,2/1.cpp
|
rgeorgiev583/FMI-DSP
|
7fac5ad4373bbcb8494b7675c21ad0458176a3d3
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include "stack.cpp"
#include <stack>
#include <queue>
using namespace std;
void print(queue<stack<size_t> > qs)
{
size_t i = 1;
while (!qs.empty())
{
cout << "Купчина " << i << ": ";
stack<size_t> sn = qs.front();
while (!sn.empty())
{
cout << sn.top() << " ";
sn.pop();
}
cout << endl;
i++;
qs.pop();
}
}
int main()
{
queue<size_t> q;
size_t d;
cin >> d;
while (d)
{
q.push(d);
cin >> d;
}
if (q.empty())
return 0;
queue<stack<size_t> > qs;
stack<size_t> s;
s.push(q.front());
q.pop();
while (!q.empty())
{
size_t dn = q.front();
if (s.top() > dn)
{
stack<size_t> sr;
pour(sr, s);
qs.push(sr);
destroy(s);
}
s.push(dn);
q.pop();
}
stack<size_t> sr;
pour(sr, s);
qs.push(sr);
destroy(s);
size_t fixed_stack_count = 0;
bool was_stack_moved = false;
while (fixed_stack_count < qs.size())
{
stack<size_t> sn;
copy(sn, qs.front());
if (sn.empty() && was_stack_moved)
was_stack_moved = false;
else if (s.empty())
{
pour(s, sn);
qs.push(stack<size_t>()); // sentinel stack
}
else
{
if (sn.empty())
fixed_stack_count++;
else if (sn.top() > s.top())
{
was_stack_moved = true;
fixed_stack_count = 0;
}
if (sn.empty() || sn.top() > s.top())
{
pour(sn, s);
destroy(s);
}
qs.push(sn);
}
qs.pop();
}
print(qs);
return 0;
}
| 16.548673
| 55
| 0.400535
|
rgeorgiev583
|
26ddb3d7d9833632e7517e021ef67c9f2a975b3f
| 15,200
|
cc
|
C++
|
Archive/Stroika_FINAL_for_STERL_1992/Library/Framework/Sources/FocusItem.cc
|
SophistSolutions/Stroika
|
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
|
[
"MIT"
] | 28
|
2015-09-22T21:43:32.000Z
|
2022-02-28T01:35:01.000Z
|
Archive/Stroika_FINAL_for_STERL_1992/Library/Framework/Sources/FocusItem.cc
|
SophistSolutions/Stroika
|
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
|
[
"MIT"
] | 98
|
2015-01-22T03:21:27.000Z
|
2022-03-02T01:47:00.000Z
|
Archive/Stroika_FINAL_for_STERL_1992/Library/Framework/Sources/FocusItem.cc
|
SophistSolutions/Stroika
|
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
|
[
"MIT"
] | 4
|
2019-02-21T16:45:25.000Z
|
2022-02-18T13:40:04.000Z
|
/* Copyright(c) Sophist Solutions Inc. 1990-1992. All rights reserved */
/*
* $Header: /fuji/lewis/RCS/FocusItem.cc,v 1.6 1992/09/08 15:34:00 lewis Exp $
*
* TODO:
*
* Should do FocusOwner::DTOR which asserts all items removed...
*
*
* Changes:
* $Log: FocusItem.cc,v $
* Revision 1.6 1992/09/08 15:34:00 lewis
* Renamed NULL -> Nil.
*
* Revision 1.5 1992/09/01 15:46:50 sterling
* Lots of Foundation changes.
*
* Revision 1.4 1992/07/21 21:29:31 sterling
* Use Sequence instead of obsolete SequencePtr.
*
* Revision 1.3 1992/07/03 00:25:14 lewis
* Use Panel:: to scope access to nested UpdateMode enum.
* And, general cleanups - shorten lines.
*
* Revision 1.2 1992/07/02 04:52:31 lewis
* Renamed Sequence_DoublyLLOfPointers->SequencePtr.
*
* Revision 1.1 1992/06/20 17:30:04 lewis
* Initial revision
*
* Revision 1.30 1992/05/18 17:22:20 lewis
* Dont call SetCurrentFocus (Nil) in AbstractFocusItem::DTOR since many of items
* may already be destroyed - in fact this happens often. Probably should assert
* already nil - for now, just check when debug on, and print message.
*
* Revision 1.29 92/04/15 13:42:50 13:42:50 sterling (Sterling Wight)
* changed from Option to Shift key for backwards tab
*
* Revision 1.28 92/03/26 15:15:20 15:15:20 lewis (Lewis Pringle)
* Changed EffectiveFocusedChanged () to EffectiveFocusChanged(), and got rid of
* oldFocused first argument.
*
* Revision 1.27 1992/03/13 16:36:23 lewis
* Moved FocusView to User.
*
* Revision 1.24 1992/03/10 00:30:34 lewis
* Use new HandleKeyStroke interface, and change GetTab interface to use KeyStroike
* rather than KeyBoard.
*
* Revision 1.23 1992/03/06 22:17:32 lewis
* Minor cleanups like getting rid of ifdefs out stuff, and unneeded dtors.
* Also, undid a patch sterl had done but seemed unwise - in TrackPress for FocusView...
*
* Revision 1.22 1992/02/24 06:46:26 lewis
* Added if macui around focusitem stuff as hack for sterls/simones demo til we
* clean things up a bit - sterl - lewis says: FocusItemView bad idea to begin with...
*
* Revision 1.19 1992/02/17 16:36:04 lewis
* Worked around assert for focusitem differently than before since that change broke things.
* Just comment out the assert. Must revisit the issue soon!!!
*
* Revision 1.18 1992/02/16 18:06:39 lewis
* Change definition of FocusItem::GetEffectiveFocused ().... Discuss with sterl...
*
* Revision 1.17 1992/02/15 05:32:34 sterling
* many changes, includeng adding EffectiveFocusedChanged
*
* Revision 1.16 1992/01/31 21:11:03 lewis
* In FocusItem::CanBeFocused(), we add GetFocusOwner()!=Nil to conjunction.
* And in AbstractFocusOwner we just call GetLive() in CanBeFocused () instead
* of inherited::CanBeFocusued.
*
* Revision 1.15 1992/01/31 16:43:17 sterling
* added grabfocus
*
* Revision 1.14 1992/01/22 15:18:29 sterling
* fixed tabs
*
* Revision 1.11 1992/01/08 06:25:13 lewis
* Sterl- lots of changes - mostly tabbing related.
*
*
*
*/
#include "Debug.hh"
#include "StreamUtils.hh"
#include "Shape.hh"
#include "Adornment.hh"
#include "Dialog.hh"
#include "MenuOwner.hh"
#include "View.hh"
#include "FocusItem.hh"
#if !qRealTemplatesAvailable
Implement (Iterator, FocusItemPtr);
Implement (Collection, FocusItemPtr);
Implement (AbSequence, FocusItemPtr);
Implement (Array, FocusItemPtr);
Implement (Sequence_Array, FocusItemPtr);
Implement (Sequence, FocusItemPtr);
#endif
/*
********************************************************************************
******************************* FocusException *********************************
********************************************************************************
*/
FocusException::FocusException ():
fMessage (kEmptyString)
{
}
void FocusException::Raise ()
{
if (Exception::GetCurrent () != this) { // if were not the current exception
fMessage = kEmptyString;
}
Exception::Raise ();
}
void FocusException::Raise (const String& message)
{
fMessage = message;
Exception::Raise ();
}
String FocusException::GetMessage () const
{
return (fMessage);
}
/*
********************************************************************************
********************************* FocusItem ************************************
********************************************************************************
*/
const Boolean FocusItem::kFocused = True;
const Boolean FocusItem::kValidate = True;
FocusItem::FocusItem ():
KeyHandler (),
MenuCommandHandler (),
LiveItem (),
fFocused (not kFocused),
fOwner (Nil)
{
}
void FocusItem::SetFocused (Boolean focused, Panel::UpdateMode updateMode, Boolean validate)
{
if (GetFocused () != focused) {
SetFocused_ (focused, updateMode, validate);
}
Ensure (GetFocused () == focused);
}
Boolean FocusItem::GetFocused_ () const
{
return (fFocused);
}
void FocusItem::SetFocused_ (Boolean focused, Panel::UpdateMode updateMode, Boolean validate)
{
Require (focused != fFocused);
Boolean oldFocused = GetEffectiveFocused ();
if (validate and (not focused)) {
Validate ();
}
fFocused = focused;
if (oldFocused != GetEffectiveFocused ()) {
EffectiveFocusChanged (not oldFocused, updateMode);
}
}
Boolean FocusItem::GetEffectiveFocused () const
{
AbstractFocusOwner* owner = GetFocusOwner ();
return (Boolean (GetFocused () and ((owner == Nil) or (owner->GetEffectiveFocused ()))));
}
void FocusItem::EffectiveFocusChanged (Boolean /*newFocused*/, Panel::UpdateMode /*updateMode*/)
{
MenuOwner::SetMenusOutOfDate ();
}
AbstractFocusOwner* FocusItem::GetFocusOwner () const
{
return (fOwner);
}
void FocusItem::SetFocusOwner (AbstractFocusOwner* focusOwner)
{
Require ((fOwner == Nil) or (focusOwner == Nil));
fOwner = focusOwner;
}
Boolean FocusItem::CanBeFocused ()
{
/*
* By default, focus items can be focused if they are live.
*/
return (GetEffectiveLive ());
}
void FocusItem::GrabFocus (Panel::UpdateMode updateMode, Boolean validate)
{
AbstractFocusOwner* owner = GetFocusOwner ();
if (owner == Nil) {
SetFocused (kFocused, updateMode);
}
else {
if (validate) {
// set owners focus to Nil first to ensure validates get called early on
owner->SetCurrentFocus ((FocusItem*)Nil, updateMode, validate);
}
owner->GrabFocus (updateMode, validate);
owner->SetCurrentFocus (this, updateMode, validate);
}
}
void FocusItem::TabbingFocus (SequenceDirection /*d*/,
Panel::UpdateMode updateMode)
{
GrabFocus (updateMode, kValidate);
}
Boolean FocusItem::HandleTab (SequenceDirection /*d*/,
Boolean /*wrapping*/)
{
return (False);
}
void FocusItem::Validate ()
{
}
/*
********************************************************************************
***************************** AbstractFocusOwner *******************************
********************************************************************************
*/
const Boolean AbstractFocusOwner::kWrap = True;
AbstractFocusOwner::AbstractFocusOwner ():
fFocus (Nil)
{
}
AbstractFocusOwner::~AbstractFocusOwner ()
{
// Require (GetCurrentFocus () == Nil);
#if qDebug
if (GetCurrentFocus () != Nil) {
gDebugStream << "destroying abstract focus ownerwith current focus set!!!" << newline;
}
#endif
#if 0
// LGP May 18, 1992 - if anything, assert that current focus is Nil - when we are being destroyed, our children
// may well be already!!! In fact, that should be quite common!!!
SetCurrentFocus ((FocusItem*)Nil, Panel::eNoUpdate, False);
#endif
}
void AbstractFocusOwner::EffectiveFocusChanged (Boolean newFocused, Panel::UpdateMode updateMode)
{
FocusItem::EffectiveFocusChanged (newFocused, updateMode);
if (GetCurrentFocus () != Nil) {
GetCurrentFocus ()->EffectiveFocusChanged (newFocused, updateMode);
}
}
void AbstractFocusOwner::Validate ()
{
if (GetCurrentFocus () != Nil) {
GetCurrentFocus ()->Validate ();
}
}
Boolean AbstractFocusOwner::CanBeFocused ()
{
if (GetEffectiveLive ()) {
ForEach (FocusItemPtr, it, MakeFocusIterator ()) {
AssertNotNil (it.Current ());
if (it.Current ()->CanBeFocused ()) {
return (True);
}
}
}
return (False);
}
void AbstractFocusOwner::DoSetupMenus ()
{
if (GetCurrentFocus () != Nil) {
GetCurrentFocus ()->DoSetupMenus ();
}
}
Boolean AbstractFocusOwner::DoCommand (const CommandSelection& selection)
{
if (GetCurrentFocus () != Nil) {
return (GetCurrentFocus ()->DoCommand (selection));
}
return (False);
}
void AbstractFocusOwner::TabbingFocus (SequenceDirection d,
Panel::UpdateMode updateMode)
{
SetCurrentFocus ((FocusItem*)Nil, updateMode, kValidate);
FocusItem* nextFocus = CalcNextFocus (d, True);
if (nextFocus == Nil) {
FocusItem::TabbingFocus (d, updateMode);
}
else {
nextFocus->TabbingFocus (d, updateMode);
}
}
Boolean AbstractFocusOwner::HandleTab (SequenceDirection d,
Boolean wrapping)
{
FocusItem* currentFocus = GetCurrentFocus ();
if (currentFocus != Nil) {
if (currentFocus->HandleTab (d, wrapping)) {
return (True);
}
}
FocusItem* nextFocus = CalcNextFocus (d, wrapping);
SetCurrentFocus ((FocusItem*)Nil, View::eDelayedUpdate, kValidate);
if (nextFocus != currentFocus) {
if (nextFocus != Nil) {
nextFocus->TabbingFocus (d, View::eDelayedUpdate);
}
return (True);
}
return (False);
}
Boolean AbstractFocusOwner::HandleKeyStroke (const KeyStroke& keyStroke)
{
SequenceDirection direction;
Boolean wrapping;
if (GetTab (keyStroke, direction, wrapping)) {
if (HandleTab (direction, wrapping)) {
return (True);
}
else if (not wrapping) {
return (HandleTab (direction, True));
}
}
return (False);
}
Boolean AbstractFocusOwner::DispatchKeyEvent (KeyBoard::KeyCode code, Boolean isUp,
const KeyBoard& keyBoardState,
KeyComposeState& composeState)
{
/*
* See if we handle it for tabbing purposes, otherwise pass to our focus.
*/
if (HandleKeyEvent (code, isUp, keyBoardState, composeState)) {
return (True);
}
else {
if (GetCurrentFocus () != Nil) {
return (GetCurrentFocus ()->DispatchKeyEvent (code, isUp, keyBoardState, composeState));
}
}
return (False);
}
Boolean AbstractFocusOwner::GetTab (const KeyStroke& keyStroke,
SequenceDirection& d,
Boolean& wrapping)
{
KeyStroke ks = keyStroke.GetCharacter ();
if (ks == KeyStroke::kTab) {
if (keyStroke.GetModifiers ().Contains (KeyStroke::eShiftKeyModifier)) {
d = eSequenceBackward;
}
else {
d = eSequenceForward;
}
wrapping = False;
return (True);
}
else if (ks == KeyStroke::kDownArrow) {
d = eSequenceForward;
wrapping = True;
return (True);
}
else if (ks == KeyStroke::kUpArrow) {
d = eSequenceBackward;
wrapping = True;
return (True);
}
return (False);
}
FocusItem* AbstractFocusOwner::GetCurrentFocus () const
{
return (fFocus);
}
void AbstractFocusOwner::SetCurrentFocus (FocusItem* newFocus,
Panel::UpdateMode updateMode, Boolean validate)
{
if (newFocus != GetCurrentFocus ()) {
SetCurrentFocus_ (newFocus, updateMode, validate);
}
Ensure (GetCurrentFocus () == newFocus);
}
void AbstractFocusOwner::SetCurrentFocus (SequenceDirection d,
Panel::UpdateMode updateMode, Boolean validate)
{
SetCurrentFocus (CalcNextFocus (d, True), updateMode, validate);
}
void AbstractFocusOwner::SetCurrentFocus_ (FocusItem* newFocus, Panel::UpdateMode updateMode,
Boolean validate)
{
Require (fFocus != newFocus);
if (GetCurrentFocus () != Nil) {
GetCurrentFocus ()->SetFocused (not kFocused, updateMode, validate);
}
fFocus = newFocus;
if (GetCurrentFocus () != Nil) {
GetCurrentFocus ()->SetFocused (kFocused, updateMode);
}
}
FocusItem* AbstractFocusOwner::CalcNextFocus (SequenceDirection d,
Boolean allowWrapAround)
{
Boolean matched = Boolean (fFocus == Nil);
{
ForEach (FocusItemPtr, it, MakeFocusIterator (d)) {
FocusItem* c = it.Current ();
AssertNotNil (c);
if (matched) {
Assert (c != fFocus);
if (c->CanBeFocused ()) {
return (c);
}
}
else {
matched = Boolean (c == fFocus);
}
}
}
if (matched and allowWrapAround) {
// wrap around search
ForEach (FocusItemPtr, it, MakeFocusIterator (d)) {
FocusItem* c = it.Current ();
AssertNotNil (c);
if (c == fFocus) {
// wrap around failed, could find no new candidate
break;
}
else {
if (c->CanBeFocused ()) {
return (c);
}
}
}
}
return (fFocus); // failed to find a new guy
}
void AbstractFocusOwner::SetOwnerOfFocusItem (FocusItem* focus, AbstractFocusOwner* owner)
{
Require ((owner == this) or (owner == Nil));
RequireNotNil (focus);
Require (focus->GetFocusOwner () != owner);
focus->SetFocusOwner (owner);
}
/*
********************************************************************************
********************************* FocusOwner ***********************************
********************************************************************************
*/
FocusOwner::FocusOwner ():
AbstractFocusOwner (),
fFocusList ()
{
}
void FocusOwner::AddFocus (FocusItem* focus, CollectionSize index)
{
RequireNotNil (focus);
Require (focus->GetFocusOwner () == Nil);
Require (not focus->GetFocused ());
if (index == eAppend) {
index = fFocusList.GetLength () + 1;
}
fFocusList.InsertAt (focus, index);
SetOwnerOfFocusItem (focus, this);
}
void FocusOwner::AddFocus (FocusItem* focus, FocusItem* neighborFocus, AddMode addMode)
{
RequireNotNil (neighborFocus);
CollectionSize index = fFocusList.IndexOf (neighborFocus);
Require (index != kBadSequenceIndex);
AddFocus (focus, (addMode == eAppend) ? index + 1 : index);
}
void FocusOwner::RemoveFocus (FocusItem* focus)
{
RequireNotNil (focus);
Require (focus->GetFocusOwner () == this);
if (focus == GetCurrentFocus ()) {
SetCurrentFocus ((FocusItem*)Nil, Panel::eDelayedUpdate, not kValidate);
}
fFocusList.Remove (focus);
SetOwnerOfFocusItem (focus, Nil);
}
void FocusOwner::ReorderFocus (FocusItem* focus, CollectionSize index)
{
RequireNotNil (focus);
if (index == eAppend) {
index = fFocusList.GetLength (); // not count + 1 cuz we will remove first,
// shrinking list temporarily
}
fFocusList.Remove (focus);
fFocusList.InsertAt (focus, index);
Ensure (fFocusList.IndexOf (focus) == index);
}
void FocusOwner::ReorderFocus (FocusItem* focus, FocusItem* neighborFocus, AddMode addMode)
{
RequireNotNil (neighborFocus);
Require (focus != neighborFocus);
CollectionSize index = fFocusList.IndexOf (neighborFocus);
CollectionSize oldIndex = fFocusList.IndexOf (focus);
Require (index != kBadSequenceIndex);
Require (oldIndex != kBadSequenceIndex);
if (oldIndex < index) {
index--;
}
ReorderFocus (focus, (addMode == eAppend) ? index + 1 : index);
}
SequenceIterator(FocusItemPtr)* FocusOwner::MakeFocusIterator (SequenceDirection
d)
{
return (fFocusList.MakeSequenceIterator (d));
}
Boolean FocusOwner::GetLive () const
{
return (True);
}
// For gnuemacs:
// Local Variables: ***
// mode:C++ ***
// tab-width:4 ***
// End: ***
| 24.32
| 112
| 0.649013
|
SophistSolutions
|
26e643b953a6a51f89ecdfd216e622e75d0df6ae
| 1,858
|
cpp
|
C++
|
HackerRank/Searching/A_-_Ice_Cream_Parlor.cpp
|
Sohelr360/my_codes
|
9bdd28f62d3850aad8f8af2a253ba66138a7057c
|
[
"MIT"
] | null | null | null |
HackerRank/Searching/A_-_Ice_Cream_Parlor.cpp
|
Sohelr360/my_codes
|
9bdd28f62d3850aad8f8af2a253ba66138a7057c
|
[
"MIT"
] | null | null | null |
HackerRank/Searching/A_-_Ice_Cream_Parlor.cpp
|
Sohelr360/my_codes
|
9bdd28f62d3850aad8f8af2a253ba66138a7057c
|
[
"MIT"
] | null | null | null |
/**
* Author: Sohel Rana
* Date: 2022-06-12 11:50:13
* Task: A_-_Ice_Cream_Parlor
**/
#include <bits/stdc++.h>
#define endl '\n'
#define sqr(x) (x) * (x)
#define gcd(x,y) __gcd(x, y)
#define lcm(x,y) ((x/gcd(x,y)) * y)
#define pf push_front
#define pb push_back
#define fi first
#define se second
#define mp make_pair
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define sz(x) (long long)x.size()
#define prec(x) fixed<<setprecision(x)
#define debug(x) cerr<<#x<<" = "<<(x)<< endl
#define debug2(x,y) cerr<<#x<<" = "<<(x)<<","<<#y<<" = "<<(y)<< endl
#define unsyncIO ios_base::sync_with_stdio(false); cin.tie(nullptr)
using ll = long long;
using db = double;
using ld = long double;
using ull = unsigned long long;
const ld pi = acos((ld)-1);
const int mod = 1e9+7;
const ll inf = 1e18;
const ld eps = 1e-9;
const int mx = 1e4+5;
using namespace std;
vector<int> TwoPointer(vector<pair<int,int> >& vp, int target, int n) {
int left = 0, right = n-1;
while(left < right) {
ll sum = vp[left].fi + vp[right].fi;
if(sum == target) {
return {vp[left].se, vp[right].se};
}
else if(sum < target)
left++;
else
right--;
}
return {};
}
int main()
{
//freopen("in.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
unsyncIO;
int t;
cin>>t;
while(t--) {
int target, n;
cin>>target>>n;
vector<pair<int,int> > vp;
for(int i = 1; i <= n; i++){
int x; cin>>x;
vp.pb({x,i});
}
sort(all(vp));
vector<int> ans;
ans = TwoPointer(vp, target, n);
sort(all(ans));
cout<<ans[0] <<" "<<ans[1]<<endl;
}
return 0;
}
| 24.773333
| 71
| 0.50592
|
Sohelr360
|
26ea7e087772d178fc9cd06a7e3be116ab733699
| 2,534
|
cc
|
C++
|
src/Circuit/models/ideal/IdealCapacitor.cc
|
kwisniew/devsim
|
3a7c1e9c4d28a8a6f9e7a43e5d5475ea2cdfe138
|
[
"Apache-2.0"
] | null | null | null |
src/Circuit/models/ideal/IdealCapacitor.cc
|
kwisniew/devsim
|
3a7c1e9c4d28a8a6f9e7a43e5d5475ea2cdfe138
|
[
"Apache-2.0"
] | null | null | null |
src/Circuit/models/ideal/IdealCapacitor.cc
|
kwisniew/devsim
|
3a7c1e9c4d28a8a6f9e7a43e5d5475ea2cdfe138
|
[
"Apache-2.0"
] | null | null | null |
#include "IdealCapacitor.hh"
#include <cmath>
IdealCapacitor::IdealCapacitor( NodeKeeper *nk, const char *name,
const char *n1,
const char *n2) : InstanceModel(nk, name)
{
node_ptr_vtop= this->AddCircuitNode(n1);
node_ptr_vbot= this->AddCircuitNode(n2);
//Parameter List
C = 1.000000e+00;
}
void IdealCapacitor::assembleDC(const NodeKeeper::Solution &sol, dsMath::RealRowColValueVec &mat, std::vector<std::pair<int, double> > &rhs)
{
}
void IdealCapacitor::assembleTran(const double scl, const NodeKeeper::Solution &sol, dsMath::RealRowColValueVec *mat, std::vector<std::pair<int, double> > &rhs)
{
const size_t node_num_vbot = node_ptr_vbot->getNumber();
const size_t node_num_vtop = node_ptr_vtop->getNumber();
const bool is_gnd_node_vbot = node_ptr_vbot->isGROUND();
const bool is_gnd_node_vtop = node_ptr_vtop->isGROUND();
const double vbot = (is_gnd_node_vbot) ? 0.0 : sol[node_num_vbot];
const double vtop = (is_gnd_node_vtop) ? 0.0 : sol[node_num_vtop];
const double iq = (C * (vtop - vbot));
const double evbot = scl *(-iq);
const double evtop = scl *iq;
if (!is_gnd_node_vbot)
rhs.push_back(std::make_pair(node_num_vbot, evbot));
if (!is_gnd_node_vtop)
rhs.push_back(std::make_pair(node_num_vtop, evtop));
if (mat == NULL)
return;
const double d_iq_d_vtop = C;
const double evbot_vtop = scl * (-d_iq_d_vtop);
const double d_iq_d_vbot = (-C);
const double evbot_vbot = scl * (-d_iq_d_vbot);
const double evtop_vtop = scl * d_iq_d_vtop;
const double evtop_vbot = scl * d_iq_d_vbot;
if (!is_gnd_node_vbot)
{
if (!is_gnd_node_vtop)
mat->push_back(dsMath::RealRowColVal(node_num_vbot,node_num_vtop, evbot_vtop));
mat->push_back(dsMath::RealRowColVal(node_num_vbot,node_num_vbot, evbot_vbot));
}
if (!is_gnd_node_vtop)
{
mat->push_back(dsMath::RealRowColVal(node_num_vtop,node_num_vtop, evtop_vtop));
if (!is_gnd_node_vbot)
mat->push_back(dsMath::RealRowColVal(node_num_vtop,node_num_vbot, evtop_vbot));
}
}
bool IdealCapacitor::addParam(const std::string &str, double val)
{
bool ret = false;
if (str == "C")
{
C = val;
ret = true;
}
return ret;
}
extern "C" InstanceModel *IdealCapacitor_create (NodeKeeper *nk, const std::string &name, const std::vector<std::string> &nodelist) {
return new IdealCapacitor(nk, name.c_str(), nodelist[0].c_str(), nodelist[1].c_str());
}
| 28.795455
| 160
| 0.676401
|
kwisniew
|
26f12b230f4963a779e950fe9c56e05c356300a5
| 1,538
|
cpp
|
C++
|
benchmarks/vote/novelsm/rocksdb_checkpoint.cpp
|
huangvincent170/cyclone
|
737af617ab1472dfb16e6c20a079e88dccf85850
|
[
"Apache-2.0"
] | 2
|
2019-04-16T01:33:36.000Z
|
2021-02-23T08:34:38.000Z
|
benchmarks/vote/novelsm/rocksdb_checkpoint.cpp
|
huangvincent170/cyclone
|
737af617ab1472dfb16e6c20a079e88dccf85850
|
[
"Apache-2.0"
] | null | null | null |
benchmarks/vote/novelsm/rocksdb_checkpoint.cpp
|
huangvincent170/cyclone
|
737af617ab1472dfb16e6c20a079e88dccf85850
|
[
"Apache-2.0"
] | 4
|
2020-03-27T18:06:33.000Z
|
2021-03-24T09:56:17.000Z
|
#include<assert.h>
#include<errno.h>
#include<string.h>
#include<stdlib.h>
#include<stdio.h>
#include <time.h>
#include<unistd.h>
#include <leveldb/db.h>
#include <leveldb/options.h>
#include <leveldb/write_batch.h>
#include <leveldb/utilities/checkpoint.h>
#include "rocksdb.hpp"
#include "logging.hpp"
#include "clock.hpp"
// Rate measurement stuff
leveldb::DB* db = NULL;
void opendb(){
leveldb::Options options;
options.create_if_missing = true;
//options.error_if_exists = true;
auto env = leveldb::Env::Default();
//env->set_affinity(0, 10);
env->SetBackgroundThreads(2, leveldb::Env::LOW);
env->SetBackgroundThreads(1, leveldb::Env::HIGH);
options.env = env;
options.write_buffer_size = 1024 * 1024 * 256;
options.target_file_size_base = 1024 * 1024 * 512;
options.max_background_compactions = 2;
options.max_background_flushes = 1;
options.max_write_buffer_number = 3;
leveldb::Status s = leveldb::DB::Open(options, preload_dir, &db);
if (!s.ok()){
BOOST_LOG_TRIVIAL(fatal) << s.ToString().c_str();
exit(-1);
}
// Create checkpoint
leveldb::Checkpoint * checkpoint_ptr;
s = leveldb::Checkpoint::Create(db, &checkpoint_ptr);
if (!s.ok()){
BOOST_LOG_TRIVIAL(fatal) << s.ToString().c_str();
exit(-1);
}
s = checkpoint_ptr->CreateCheckpoint(data_dir);
if (!s.ok()){
BOOST_LOG_TRIVIAL(fatal) << s.ToString().c_str();
exit(-1);
}
delete checkpoint_ptr;
}
void closedb()
{
delete db;
}
int main(int argc, char *argv[])
{
opendb();
closedb();
}
| 22.955224
| 67
| 0.680104
|
huangvincent170
|
26f2fc8f200d1d61e94ded94853dfe123552d29b
| 1,372
|
hpp
|
C++
|
Runtime/MP1/CPauseScreenBlur.hpp
|
Jcw87/urde
|
fb9ea9092ad00facfe957ece282a86c194e9cbda
|
[
"MIT"
] | 267
|
2016-03-10T21:59:16.000Z
|
2021-03-28T18:21:03.000Z
|
Runtime/MP1/CPauseScreenBlur.hpp
|
cobalt2727/metaforce
|
3bb05c0ee5dd9b1b8eaa861fc49713aef62c844a
|
[
"MIT"
] | 129
|
2016-03-12T10:17:32.000Z
|
2021-04-05T20:45:19.000Z
|
Runtime/MP1/CPauseScreenBlur.hpp
|
cobalt2727/metaforce
|
3bb05c0ee5dd9b1b8eaa861fc49713aef62c844a
|
[
"MIT"
] | 31
|
2016-03-20T00:20:11.000Z
|
2021-03-10T21:14:11.000Z
|
#pragma once
#include "Runtime/CToken.hpp"
#include "Runtime/Camera/CCameraFilter.hpp"
#include "Runtime/Graphics/CTexture.hpp"
#include "Runtime/Graphics/Shaders/CTexturedQuadFilter.hpp"
#include "Runtime/Graphics/Shaders/CScanLinesFilter.hpp"
#include "Runtime/MP1/CInGameGuiManagerCommon.hpp"
namespace metaforce {
class CStateManager;
namespace MP1 {
class CPauseScreenBlur {
enum class EState { InGame, MapScreen, SaveGame, HUDMessage, Pause };
TLockedToken<CTexture> x4_mapLightQuarter;
EState x10_prevState = EState::InGame;
EState x14_nextState = EState::InGame;
float x18_blurAmt = 0.f;
CCameraBlurPass x1c_camBlur;
bool x50_24_blurring : 1 = false;
bool x50_25_gameDraw : 1 = true;
CTexturedQuadFilter m_quarterFilter{EFilterType::Multiply, x4_mapLightQuarter};
CScanLinesFilterEven m_linesFilter{EFilterType::Multiply};
void OnBlurComplete(bool);
void SetState(EState state);
public:
CPauseScreenBlur();
void OnNewInGameGuiState(EInGameGuiState state, CStateManager& stateMgr);
bool IsGameDraw() const { return x50_25_gameDraw; }
void Update(float dt, const CStateManager& stateMgr, bool);
void Draw(const CStateManager& stateMgr);
float GetBlurAmt() const { return std::fabs(x18_blurAmt); }
bool IsNotTransitioning() const { return x10_prevState == x14_nextState; }
};
} // namespace MP1
} // namespace metaforce
| 31.181818
| 81
| 0.777697
|
Jcw87
|
26f786487133949e213c1d83b6bcdba02d155a91
| 1,583
|
cpp
|
C++
|
qt/app/applicationpath.cpp
|
qbit-t/qb
|
c1fd82df3838f8526fc5e335254529ab6f953f78
|
[
"MIT"
] | 1
|
2021-02-14T04:04:50.000Z
|
2021-02-14T04:04:50.000Z
|
qt/app/applicationpath.cpp
|
qbit-t/qb
|
c1fd82df3838f8526fc5e335254529ab6f953f78
|
[
"MIT"
] | null | null | null |
qt/app/applicationpath.cpp
|
qbit-t/qb
|
c1fd82df3838f8526fc5e335254529ab6f953f78
|
[
"MIT"
] | 1
|
2021-08-28T07:42:43.000Z
|
2021-08-28T07:42:43.000Z
|
#include <QDir>
#include <QPluginLoader>
#include <QQmlExtensionPlugin>
#include <QDebug>
#include <QException>
#include <QStandardPaths>
#include <QStringList>
#include <QJsonDocument>
#include "applicationpath.h"
#include "error.h"
using namespace buzzer;
#ifdef Q_OS_ANDROID
std::wstring gProfile(L"android");
#else
std::wstring gProfile(L"desktop");
#endif
QString ApplicationPath::applicationDirPath()
{
#ifdef Q_OS_ANDROID
return QString("assets:");
#endif
return qApp->applicationDirPath();
}
QString ApplicationPath::logsDirPath()
{
#ifdef Q_OS_ANDROID
return QStandardPaths::writableLocation(QStandardPaths::DownloadLocation);
#endif
#ifdef Q_OS_IOS
return QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
#endif
return qApp->applicationDirPath() + "/logs";
}
QString ApplicationPath::tempFilesDir()
{
#ifdef Q_OS_ANDROID
return QStandardPaths::writableLocation(QStandardPaths::TempLocation);
#endif
#ifdef Q_OS_IOS
return QStandardPaths::writableLocation(QStandardPaths::TempLocation);
#endif
QString lGlobalDataPath = qApp->applicationDirPath() + "/data";
QDir lDataDir(lGlobalDataPath);
if (!lDataDir.exists()) {
lDataDir.setPath(qApp->applicationDirPath());
lDataDir.mkdir("data");
}
QString lCacheDataPath = lGlobalDataPath + "/cache";
QDir lCacheDir(lCacheDataPath);
if (!lCacheDir.exists()) {
lCacheDir.setPath(lGlobalDataPath);
lCacheDir.mkdir("cache");
}
#ifdef Q_OS_WINDOWS
lCacheDataPath.replace(0, 1, lCacheDataPath[0].toLower());
return lCacheDataPath;
#endif
return lCacheDataPath;
}
| 21.106667
| 79
| 0.765635
|
qbit-t
|
26fad1aa447d610467e3eeacb8632ded76b35948
| 590
|
cpp
|
C++
|
Game/src/Keyboard.cpp
|
rasmusrosengren/OpenGL3DGame
|
db6101d8aae97b8798a99ae458e62d2a8b407acb
|
[
"MIT"
] | null | null | null |
Game/src/Keyboard.cpp
|
rasmusrosengren/OpenGL3DGame
|
db6101d8aae97b8798a99ae458e62d2a8b407acb
|
[
"MIT"
] | null | null | null |
Game/src/Keyboard.cpp
|
rasmusrosengren/OpenGL3DGame
|
db6101d8aae97b8798a99ae458e62d2a8b407acb
|
[
"MIT"
] | null | null | null |
#include "Keyboard.h"
std::array<bool, Keyboard::NUM_KEYS> Keyboard::m_lastKeys;
GLFWwindow* Keyboard::m_window = nullptr;
void Keyboard::init(GLFWwindow* window)
{
m_window = window;
}
void Keyboard::update() // Need to be called every frame
{
for (int i = 0; i < NUM_KEYS; i++)
{
m_lastKeys[i] = getKey(i);
}
}
bool Keyboard::getKey(int keyCode)
{
return glfwGetKey(m_window, keyCode);
}
bool Keyboard::getKeyDown(int keyCode)
{
return getKey(keyCode) && !m_lastKeys.at(keyCode);
}
bool Keyboard::getKeyUp(int keyCode)
{
return !getKey(keyCode) && m_lastKeys.at(keyCode);
}
| 18.4375
| 58
| 0.705085
|
rasmusrosengren
|
26fc029492dd6f1cc022acd3eb315badcd4bef95
| 301
|
hpp
|
C++
|
header/conditions.hpp
|
jonathanmarp/dbmem
|
fa2d143758282fc28b00d36bcc5acfb859de1f74
|
[
"MIT"
] | 2
|
2021-05-18T08:08:53.000Z
|
2021-05-18T09:41:09.000Z
|
header/conditions.hpp
|
thekotekjournal/dbmem
|
5fe1371167f5754e55dc84bd16278595dd5f9b38
|
[
"MIT"
] | 1
|
2021-05-18T10:12:15.000Z
|
2021-05-18T10:12:15.000Z
|
header/conditions.hpp
|
thekotekjournal/dbmem
|
5fe1371167f5754e55dc84bd16278595dd5f9b38
|
[
"MIT"
] | 1
|
2021-05-18T09:41:12.000Z
|
2021-05-18T09:41:12.000Z
|
#ifndef DBMEM_CONDITIONS_HPP
#define DBMEM_CONDITIONS_HPP
namespace conditions {
enum CONDITIONS_STRUCT {
FALSE = 0x001,
TRUE = 0x002
};
typedef enum CONDITIONS_STRUCT Dconditions;
Dconditions Fconditions(bool conditions_boolean);
};
#endif // DBMEM_CONDITIONS_HPP
| 20.066667
| 53
| 0.727575
|
jonathanmarp
|
26fe51326b37d5c846251f5cb710e7208fa12b56
| 1,115
|
cpp
|
C++
|
src/engine/GLUtils.cpp
|
Arkshine/PrototypeEngine
|
6833b931ca02934dd5f68377fc8c486f01103841
|
[
"Unlicense"
] | 2
|
2018-10-09T14:42:39.000Z
|
2021-02-07T21:41:00.000Z
|
src/engine/GLUtils.cpp
|
Arkshine/PrototypeEngine
|
6833b931ca02934dd5f68377fc8c486f01103841
|
[
"Unlicense"
] | null | null | null |
src/engine/GLUtils.cpp
|
Arkshine/PrototypeEngine
|
6833b931ca02934dd5f68377fc8c486f01103841
|
[
"Unlicense"
] | 1
|
2018-10-09T14:42:41.000Z
|
2018-10-09T14:42:41.000Z
|
#include <sstream>
#include <string>
#include <GL/glew.h>
#include "Logging.h"
#include "GLUtils.h"
namespace gl
{
bool GetContextVersion( uint32_t& uiOutMajor, uint32_t& uiOutMinor )
{
uiOutMajor = 1;
uiOutMinor = 0;
const char* pszVersion = reinterpret_cast<const char*>( glGetString( GL_VERSION ) );
if( !pszVersion )
{
Msg( "gl::GetContextVersion: Couldn't query OpenGL version info\n" );
return false;
}
std::string szVersion( pszVersion );
//Vendor specific information follows after a space, so trim it. - Solokiller
const auto space = szVersion.find( ' ' );
if( space != std::string::npos )
szVersion = szVersion.substr( 0, space );
std::stringstream stream( szVersion );
std::string szToken;
if( !std::getline( stream, szToken, '.' ) )
{
Msg( "gl::GetContextVersion: Invalid version string\n" );
return false;
}
const uint32_t uiMajor = std::stoul( szToken );
if( !std::getline( stream, szToken, '.' ) )
{
Msg( "gl::GetContextVersion: Invalid version string\n" );
return false;
}
uiOutMajor = uiMajor;
uiOutMinor = std::stoul( szToken );
return true;
}
}
| 19.910714
| 85
| 0.679821
|
Arkshine
|
f805448050d7b1c8e358ba00f476f98c4eb4f3aa
| 1,610
|
hpp
|
C++
|
solver/modules/slide/include/slide/KurageHashFeature.hpp
|
taiheioki/procon2014_ut
|
8199ff0a54220f1a0c51acece377f65b64db4863
|
[
"MIT"
] | 2
|
2021-04-14T06:41:18.000Z
|
2021-04-29T01:56:08.000Z
|
solver/modules/slide/include/slide/KurageHashFeature.hpp
|
taiheioki/procon2014_ut
|
8199ff0a54220f1a0c51acece377f65b64db4863
|
[
"MIT"
] | null | null | null |
solver/modules/slide/include/slide/KurageHashFeature.hpp
|
taiheioki/procon2014_ut
|
8199ff0a54220f1a0c51acece377f65b64db4863
|
[
"MIT"
] | null | null | null |
#ifndef SLIDE_KURAGE_HASH_FEATURE_HPP_
#define SLIDE_KURAGE_HASH_FEATURE_HPP_
#include <memory>
#include "PlayBoard.hpp"
#include "ZobristTable.hpp"
namespace slide
{
template<int H, int W>
class KurageHashFeature
{
private:
ull selHash;
ull hash;
public:
static std::unique_ptr<const ZobristTable<H, W>> table;
KurageHashFeature() = default;
KurageHashFeature(const PlayBoardBase<H, W>& board) {
init(board);
}
void init(const PlayBoardBase<H, W>& board)
{
hash = 0ull;
rep(i, board.height()) rep(j, board.width()) {
hash ^= table->look(board(i, j), Point(i, j));
}
if(board.isSelected()){
selHash = table->lookSelected(board(board.selected));
hash ^= selHash;
}
else{
selHash = 0ull;
}
}
ull operator()() const
{
return hash;
}
void move(const PlayBoardBase<H, W>& board, Direction dir)
{
const Point src1 = board.selected - Point::delta(dir);
const Point src2 = board.selected;
const uchar id1 = board(src2);
const uchar id2 = board(src1);
hash ^= table->look(id1, src1) ^ table->look(id1, src2) ^ table->look(id2, src1) ^ table->look(id2, src2);
}
void select(const PlayBoardBase<H, W>& board)
{
hash ^= selHash;
selHash = table->lookSelected(board(board.selected));
hash ^= selHash;
}
};
template<int H, int W>
std::unique_ptr<const ZobristTable<H, W>> KurageHashFeature<H, W>::table = nullptr;
} // end of namespace slide
#endif
| 21.756757
| 114
| 0.596273
|
taiheioki
|
f80dc8919f40eeff132b518031b932f72c2de488
| 279
|
hpp
|
C++
|
src/ast/array.hpp
|
shiroyasha/telegraph
|
1735dc392cfa6651ce69ca98b18f6b631c01f231
|
[
"MIT",
"Unlicense"
] | 1
|
2016-12-07T21:41:37.000Z
|
2016-12-07T21:41:37.000Z
|
src/ast/array.hpp
|
shiroyasha/telegraph
|
1735dc392cfa6651ce69ca98b18f6b631c01f231
|
[
"MIT",
"Unlicense"
] | null | null | null |
src/ast/array.hpp
|
shiroyasha/telegraph
|
1735dc392cfa6651ce69ca98b18f6b631c01f231
|
[
"MIT",
"Unlicense"
] | null | null | null |
#pragma once
#include "ast/node.hpp"
#include "ast/identifier.hpp"
#include "ast/type.hpp"
namespace ast {
class Array : public Type {
public:
Array(Identifier* name) : Type(name) {}
std::string toString() {
return "[" + Type::toString() + "]";
}
};
}
| 16.411765
| 43
| 0.598566
|
shiroyasha
|
f8125ad1502af2014a7b21a0def4ab8d6961d315
| 1,653
|
hpp
|
C++
|
backend/inc/sim/components/capacitor.hpp
|
capstone-2019/capstone
|
b9212ad803c962dc4b03fe8505fe56bfd820aa8a
|
[
"MIT"
] | 1
|
2019-05-04T02:21:12.000Z
|
2019-05-04T02:21:12.000Z
|
backend/inc/sim/components/capacitor.hpp
|
capstone-2019/capstone
|
b9212ad803c962dc4b03fe8505fe56bfd820aa8a
|
[
"MIT"
] | 2
|
2019-02-11T17:11:28.000Z
|
2019-02-11T17:12:26.000Z
|
backend/inc/sim/components/capacitor.hpp
|
capstone-2019/capstone
|
b9212ad803c962dc4b03fe8505fe56bfd820aa8a
|
[
"MIT"
] | null | null | null |
/**
*
* @file capacitor.hpp
*
* @data April 1, 2019
*
* @brief This file contains the interface to the capacitor, a type of
* energy storage component supported by our simulator.
*
* @author Matthew Kasper (mkasper@andrew.cmu.edu)
*
*/
#ifndef _CAPACITOR_H_
#define _CAPACITOR_H_
#include <vector>
#include <string>
#include <unordered_map>
/**
* @brief Class to represent capacitors - a passive energy storage device
* supported by our simulator.
*/
class Capacitor : public Component
{
public:
/** @brief String which denotes a new capacitor in a netlist file */
static constexpr const char *IDENTIFIER = "CAPACITOR";
/* create a capacitor */
Capacitor(const std::vector<std::string>& tokens);
/**
* @brief Destroys a capacitor.
*/
~Capacitor() { }
/* Convert a capacitor to its string representation */
std::string to_string() override;
/* get the unknown quantities for this component */
std::vector<std::string> unknowns() override;
/* map unknowns into matrix indices in a linear system */
void map_unknowns(std::unordered_map<std::string, int> mapping) override;
/* Adds resistor current contributions into system of KCL equations */
void add_contribution(LinearSystem& sys,
Eigen::VectorXd& soln,
Eigen::VectorXd& prev_soln,
double dt) override;
private:
int npos; /**< Positive terminal */
int nneg; /**< Negative terminal */
double capacitance; /**< Capacitance in farads */
int n1; /**< Matrix index for unknown npos voltage */
int n2; /**< Matrix index for unknown nneg voltage */
};
#endif /* _CAPACITOR_H_ */
| 25.430769
| 74
| 0.675136
|
capstone-2019
|
f818c9b7c0053c2db06f0a5882f94d5d234c6efb
| 402
|
cpp
|
C++
|
Simulation/src/SimulationCore/SimulationWindow.cpp
|
RubenB-1643541/MarblingSimulation
|
7534d7bcc4952a85a2512d354569256f8129c2cd
|
[
"MIT"
] | null | null | null |
Simulation/src/SimulationCore/SimulationWindow.cpp
|
RubenB-1643541/MarblingSimulation
|
7534d7bcc4952a85a2512d354569256f8129c2cd
|
[
"MIT"
] | null | null | null |
Simulation/src/SimulationCore/SimulationWindow.cpp
|
RubenB-1643541/MarblingSimulation
|
7534d7bcc4952a85a2512d354569256f8129c2cd
|
[
"MIT"
] | null | null | null |
#include "SimulationWindow.h"
#include "../SimUtils/Icon.h"
SimulationWindow::SimulationWindow() : RenderEngine::WindowBase("Marbling Simulation")
{
GLFWimage* icon = LoadGLFWimage("res/icons/Icon.png");
glfwSetWindowIcon(_window, 1, icon);
}
void SimulationWindow::OnDraw()
{
}
void SimulationWindow::OnCreate()
{
Maximize();
SetBackgroundColor(0.5f, 0.2f, 0.0f, 1.0f);
}
| 19.142857
| 87
| 0.691542
|
RubenB-1643541
|
f81d40d89f25fd1348ed725f9dc902a70b1889b6
| 2,995
|
cpp
|
C++
|
KatamariSphereController.cpp
|
catinapoke/directx-engine
|
b967eff417d170fce947066486b01a1003fa20ce
|
[
"MIT"
] | null | null | null |
KatamariSphereController.cpp
|
catinapoke/directx-engine
|
b967eff417d170fce947066486b01a1003fa20ce
|
[
"MIT"
] | null | null | null |
KatamariSphereController.cpp
|
catinapoke/directx-engine
|
b967eff417d170fce947066486b01a1003fa20ce
|
[
"MIT"
] | null | null | null |
#include "KatamariSphereController.h"
#include <iostream>
#include "TransformComponent.h"
#include "Camera.h"
typedef DirectX::SimpleMath::Matrix Matrix;
KatamariSphereController::KatamariSphereController(std::shared_ptr<InputDevice> device, CameraComponent* camera)
: transform(nullptr), camera_(camera->GetActor()->GetComponent<TransformComponent>())
{
input_device = device;
}
void KatamariSphereController::Awake()
{
ComponentBase::Awake();
transform = GetActor()->GetComponent<TransformComponent>();
assert(transform != nullptr);
}
void RotateMatrix(TransformComponent* transform, const Vector3 rotation)
{
if (rotation == Vector3{ 0,0,0 }) return;
Matrix model = Matrix::CreateScale(transform->GetLocalScale());
model *= Matrix::CreateFromQuaternion(transform->GetLocalQuaternion());
//model *= Matrix::CreateFromQuaternion(Quaternion::CreateFromYawPitchRoll(rotation.z, rotation.y, rotation.x));
model *= Matrix::CreateRotationX(rotation.x);
model *= Matrix::CreateRotationY(rotation.y);
model *= Matrix::CreateRotationZ(rotation.z);
model *= Matrix::CreateTranslation(transform->GetLocalPosition());
transform->SetLocalMatrix(model);
Vector3 r = transform->GetLocalRotation();
std::cout << "R: " << r.x << " " << r.y << " " << r.z << std::endl;
}
void KatamariSphereController::Update(float deltaTime)
{
ComponentBase::Update(deltaTime);
Vector3 position = transform->GetLocalPosition();
Vector3 rotation = transform->GetLocalRotation();
const Vector3 move_direction = GetMoveDirection();
position += move_direction * direction_weight * deltaTime;
transform->SetLocalPosition(position);
rotation = CircleRotation(rotation + GetRotationOffset(move_direction) * rotation_weight * deltaTime);
transform->SetLocalRotation(rotation);
// RotateMatrix(transform, GetRotationOffset(move_direction) * rotation_weight * deltaTime);
}
Vector3 KatamariSphereController::GetMoveDirection() const
{
Vector3 direction(0, 0, 0);
if (input_device->IsKeyDown(Keys::D)) {
direction += Vector3(1.0f, 0.0f, 0.0f);
}
if (input_device->IsKeyDown(Keys::A)) {
direction += Vector3(-1.0f, 0.0f, 0.0f);
}
if (input_device->IsKeyDown(Keys::W)) {
direction += Vector3(0.0f, 0.0f, 1.0f);
}
if (input_device->IsKeyDown(Keys::S)) {
direction += Vector3(0.0f, 0.0f, -1.0f);
}
direction.Normalize();
Vector3 forward = transform->GetWorldPosition() - camera_->GetWorldPosition();
forward = (Matrix::CreateTranslation(forward) * transform->GetParentWorldModelMatrix().Invert()).Translation();
forward.y = 0;
forward.Normalize();
const Vector3 right = forward.Cross(Vector3(0, 1, 0));
return forward * direction.z + right * direction.x;
}
Vector3 KatamariSphereController::GetRotationOffset(Vector3 move_direction)
{
move_direction.Normalize();
return { -move_direction.x, move_direction.z, 0 };
}
| 32.554348
| 116
| 0.70384
|
catinapoke
|
f81f207532f53e6de14d7ea4ae35ad527b6f1aa9
| 9,596
|
hpp
|
C++
|
lib/fiber/collection_of_basis_transformations.hpp
|
nicolas-chaulet/bempp
|
0f5cc72e0e542437e787db5704978456b0ad9e35
|
[
"BSL-1.0"
] | 2
|
2021-07-22T13:34:28.000Z
|
2021-07-22T13:35:20.000Z
|
lib/fiber/collection_of_basis_transformations.hpp
|
UCL/bempp
|
f768ec7d319c02d6e0142512fb61db0607cadf10
|
[
"BSL-1.0"
] | null | null | null |
lib/fiber/collection_of_basis_transformations.hpp
|
UCL/bempp
|
f768ec7d319c02d6e0142512fb61db0607cadf10
|
[
"BSL-1.0"
] | 1
|
2021-05-17T09:46:44.000Z
|
2021-05-17T09:46:44.000Z
|
// Copyright (C) 2011-2012 by the BEM++ Authors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#ifndef fiber_collection_of_basis_transformations_hpp
#define fiber_collection_of_basis_transformations_hpp
#include "../common/common.hpp"
#include "scalar_traits.hpp"
namespace Fiber
{
/** \cond FORWARD_DECL */
template <typename T> class CollectionOf3dArrays;
template <typename ValueType> class BasisData;
template <typename CoordinateType> class GeometricalData;
/** \endcond */
/** \ingroup weak_form_elements
* \brief Collection of basis function transformations.
*
* This class represents a collection of one or more basis function
* transformations. A basis function transformation is a function mapping a
* point \f$x\f$ located at an element of a grid to a scalar or vector
* of a fixed dimension, with real or complex elements. In addition to any
* geometrical data related to \f$x\f$, such as its global coordinates or the
* unit vectors normal to the grid at \f$x\f$, it can depend on the value
* and/or the first derivatives of a basis function defined on the reference
* element (e.g.\ the unit triangle or the unit square). Example basis
* function transformations include the mapping of basis functions to shape
* functions---expressed with the identity mapping for scalar basis functions
* or the Piola transform for vector basis function---and the mapping of basis
* functions to the surface curls of shape functions. All basis function
* transformations in a collection are evaluated together and hence may reuse
* results of any intermediate calculations.
*
* A basis function transformation is assumed to preserve the type of the
* values of basis functions, i.e. it should map real-valued basis functions
* to real-valued functions and complex-valued basis functions to
* complex-valued functions.
*
* \tparam CoordinateType_
* Type used to represent coordinates (either <tt>float</tt> or
* <tt>double</tt>). */
template <typename CoordinateType_>
class CollectionOfBasisTransformations
{
public:
typedef CoordinateType_ CoordinateType;
typedef typename ScalarTraits<CoordinateType>::ComplexType ComplexType;
/** \brief Destructor. */
virtual ~CollectionOfBasisTransformations()
{}
/** \brief Return the number of transformations belonging to the collection. */
virtual int transformationCount() const = 0;
/** \brief Return the number of components of basis functions acted upon.
*
* For instance, the implementation of this function for a collection of
* transformations operating on scalar basis functions should return 1; for
* a collection operating on vector-valued basis functions with three
* components, this function should return 3. */
virtual int argumentDimension() const = 0;
/** \brief Return the number of components of the result of i'th
* transformation.
*
* Transformation indices start from 0.
*
* For example, if the first transformation produces a scalar function,
* the implementation of this function should return 1 if \p i == 0.
*
* The behaviour of this function for \p i < 0 or \p >= transformationCount()
* is not specified. */
virtual int resultDimension(int i) const = 0;
/** \brief Retrieve the types of data on which the transformations depend.
*
* An implementation of this function should modify the \p basisDeps and
* \p geomDeps bitfields by adding to them, using the bitwise OR
* operation, an appropriate combination of the flags defined in the enums
* BasisDataType and GeometricalDataType.
*
* For example, a collection of transformations depending on the values
* and first derivatives of basis functions and the global coordinates of
* points at which the transformed functions are evaluated should modify
* the arguments as follows:
*
\code
basisDeps |= VALUES | DERIVATIVES;
geomDeps |= GLOBALS;
\endcode */
virtual void addDependencies(size_t& basisDeps, size_t& geomDeps) const = 0;
/** \brief Evaluate transformations of real-valued basis functions.
*
* \param[in] basisData
* Values and/or derivatives of \f$m \geq 0 \f$ basis functions at \f$n
* \geq 0\f$ points on an element. The number of points, \f$n\f$, can be
* obtained by calling <tt>basisData.pointCount()</tt>; the number of
* basis functions, \f$m\f$, can be obtained by calling
* <tt>basisData.functionCount()</tt>.
* \param[in] geomData
* Geometrical data related to the \f$n\f$ points at which the
* basis functions have been evaluated.
* \param[out] result
* A collection of 3-dimensional arrays intended to store the
* transformed basis function values. On output, <tt>result[i][(j, k,
* p)</tt> should contain the <em>j</em> element of the vector being the
* value of <em>i</em>th transformation of <em>k</em>th basis function
* at <em>p</em>th point.
*
* An implementation of this function may assume that \p basisData and \p
* geomData contain all the types of data specified in the implementation
* of addDependencies(). Before filling the arrays from \p result, this
* function must ensure that size of the array collection and the
* dimensions of the individual arrays are correct, calling
* <tt>CollectionOf3dArrays::set_size()</tt> and
* <tt>_3dArray::set_size()</tt> if necessary.
*/
void evaluate(
const BasisData<CoordinateType>& basisData,
const GeometricalData<CoordinateType>& geomData,
CollectionOf3dArrays<CoordinateType>& result) const {
evaluateImplReal(basisData, geomData, result);
}
/** \brief Evaluate transformations of complex-valued basis functions.
*
* See the documentation of the other overload for the description of
* function parameters.
*/
void evaluate(
const BasisData<ComplexType>& basisData,
const GeometricalData<CoordinateType>& geomData,
CollectionOf3dArrays<ComplexType>& result) const {
evaluateImplComplex(basisData, geomData, result);
}
private:
/** \brief Evaluate transformations of real-valued basis functions.
*
* \param[in] basisData
* Values and/or derivatives of \f$m \geq 0 \f$ basis functions at \f$n
* \geq 0\f$ points on an element. The number of points, \f$n\f$, can be
* obtained by calling <tt>basisData.pointCount()</tt>; the number of
* basis functions, \f$m\f$, can be obtained by calling
* <tt>basisData.functionCount()</tt>.
* \param[in] geomData
* Geometrical data related to the \f$n\f$ points at which the
* basis functions have been evaluated.
* \param[out] result
* A collection of 3-dimensional arrays intended to store the
* transformed basis function values. On output, <tt>result[i][(j, k,
* p)</tt> should contain the <em>j</em> element of the vector being the
* value of <em>i</em>th transformation of <em>k</em>th basis function
* at <em>p</em>th point.
*
* This is a pure virtual function that must be overridden in subclasses
* of CollectionOfBasisTransformations.
*
* An implementation of this function may assume that \p basisData and \p
* geomData contain all the types of data specified in the implementation
* of addDependencies(). Before filling the arrays from \p result, this
* function must ensure that size of the array collection and the
* dimensions of the individual arrays are correct, calling
* <tt>CollectionOf3dArrays::set_size()</tt> and
* <tt>_3dArray::set_size()</tt> if necessary.
*/
virtual void evaluateImplReal(
const BasisData<CoordinateType>& basisData,
const GeometricalData<CoordinateType>& geomData,
CollectionOf3dArrays<CoordinateType>& result) const = 0;
/** \brief Evaluate transformations of complex-valued basis functions.
*
* See the documentation of evaluateImplReal() for the description of
* function parameters. */
virtual void evaluateImplComplex(
const BasisData<ComplexType>& basisData,
const GeometricalData<CoordinateType>& geomData,
CollectionOf3dArrays<ComplexType>& result) const = 0;
};
} // namespace Fiber
#endif
| 45.913876
| 83
| 0.698833
|
nicolas-chaulet
|
f824c6de8a75de55487bcacabf20b24e22ab5bef
| 880
|
hpp
|
C++
|
escapee/Classes/v1/GameAct/Contours/KitExpert.hpp
|
1pkg/dump
|
0ee579cb6a97ae64d5367cc624b2407d7d4b1c7b
|
[
"MIT"
] | null | null | null |
escapee/Classes/v1/GameAct/Contours/KitExpert.hpp
|
1pkg/dump
|
0ee579cb6a97ae64d5367cc624b2407d7d4b1c7b
|
[
"MIT"
] | 3
|
2020-12-11T10:01:27.000Z
|
2022-02-13T22:12:05.000Z
|
escapee/Classes/v1/GameAct/Contours/KitExpert.hpp
|
1pkg/dump
|
0ee579cb6a97ae64d5367cc624b2407d7d4b1c7b
|
[
"MIT"
] | null | null | null |
#ifndef __GAME_ACT_CONTOURS_KIT_EXPERT_HPP__
#define __GAME_ACT_CONTOURS_KIT_EXPERT_HPP__
#include "Interfaces/INoncopyable.hpp"
#include <cocos2d.h>
namespace GameAct
{
namespace Contours
{
class Kit;
class Segment;
class Line;
class KitExpert : public Interfaces::INoncopyable
{
public:
KitExpert(Kit * path);
Segment * getSegment(cocos2d::PhysicsBody * body) const;
bool intersect(cocos2d::Rect rect) const;
bool hasSegmentUnder(cocos2d::Vec2 point) const;
bool hasSegmentBellow(cocos2d::Vec2 point) const;
bool isEndOfSegment(cocos2d::Vec2 point, float delta) const;
cocos2d::Color4F getSegmentColor(cocos2d::Vec2 point) const;
private:
std::vector<Line *> findLines(cocos2d::Vec2 point, bool orientation) const;
std::vector<Segment *> findSegments(cocos2d::Vec2 point) const;
Kit * _kit;
};
}
}
#endif
| 18.723404
| 77
| 0.727273
|
1pkg
|
f826e199873397f748c33e7cde8521e04347f672
| 5,141
|
cpp
|
C++
|
applicationsBin/sbReconf/makeConfigY.cpp
|
claytronics/visiblesim
|
2762a88a23e50516d0f166dd9629f1ac7290fded
|
[
"Apache-2.0"
] | 4
|
2016-08-18T03:19:49.000Z
|
2020-09-20T03:29:26.000Z
|
applicationsBin/sbReconf/makeConfigY.cpp
|
claytronics/visiblesim
|
2762a88a23e50516d0f166dd9629f1ac7290fded
|
[
"Apache-2.0"
] | 2
|
2016-08-18T03:25:07.000Z
|
2016-08-29T17:51:50.000Z
|
applicationsBin/sbReconf/makeConfigY.cpp
|
claytronics/visiblesim
|
2762a88a23e50516d0f166dd9629f1ac7290fded
|
[
"Apache-2.0"
] | 3
|
2015-05-14T07:29:55.000Z
|
2021-07-18T23:45:36.000Z
|
#include <iostream>
#include <fstream>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include "skeleton.h"
using namespace std;
int main(int argc,char **argv) {
int initSquareLx=41,initSquareLy=41,
conveyorBlocks=500,armLength=15;
int maxTimeSimulation=3000,iAngle=45;
double angle;
if (argc>1) {
initSquareLx = atoi(argv[1]);
cout << "initSquareLx=" << initSquareLx << endl;
}
if (argc>2) {
initSquareLy = atoi(argv[2]);
cout << "initSquareLy=" << initSquareLy << endl;
}
if (argc>3) {
conveyorBlocks = atoi(argv[3]);
cout << "conveyorBlocks=" << conveyorBlocks << endl;
}
if (argc>4) {
armLength = atoi(argv[4]);
cout << "armLength=" << armLength << endl;
}
if (argc>5) {
iAngle = atoi(argv[5]);
cout << "iangle=" << iAngle << endl;
}
angle = iAngle*M_PI/180.0;
if (argc>6) {
maxTimeSimulation = atoi(argv[6]);
cout << "maxTimeSimulation=" << maxTimeSimulation << endl;
}
int areaLx = 4+(max(initSquareLx,4*armLength)),
areaLy = 15+initSquareLy+2*armLength;
int cameraDist = 25.0*sqrt(areaLx*areaLx+areaLy*areaLy)/tan(50.0*M_PI/180.0);
int srcDist = 25.0*sqrt(areaLx*areaLx+areaLy*areaLy)/tan(45.0*M_PI/180.0);
Vecteur Origine(areaLx/2.0,areaLy-initSquareLy-3,0);
Vecteur P(Origine[0],Origine[1]-armLength/2,0);
Vecteur Q(P[0]+armLength*1.5*cos(angle),P[1]-armLength*1.5*sin(angle),0);
Vecteur R(P[0]-armLength*1.5*cos(angle),P[1]-armLength*1.5*sin(angle),0);
cout << "O=" << Origine << endl;
cout << "P=" << P << endl;
cout << "Q=" << Q << endl;
/*Skeleton *S = new SkelPoint(Origine,6,-0.1);
Skeleton *S0 = new SkelLine(Origine,P,3,-0.2);
S->add(S0);
Skeleton *S1 = new SkelPoint(P,3,-0.1);
S0->add(S1);
Skeleton *S2 = new SkelLine(P,Q,3,-0.2);
S1->add(S2);
Skeleton *S3 = new SkelPoint(Q,6,-0.1);
S2->add(S3);*/
Skeleton *S = new SkelLine(Origine,P,3,-0.2);
Skeleton *S2 = new SkelLine(P,Q,3,-0.2);
S->add(S2);
Skeleton *S3 = new SkelLine(P,R,3,-0.2);
S->add(S3);
float *grid = new float[areaLx * areaLy], *ptr=grid;
int i=areaLx*areaLy;
while (i--) {
*ptr++=0.0f;
}
int ix,iy;
for (iy=0; iy<areaLy; iy++) {
for (ix=0; ix<areaLx; ix++) {
Origine.set(ix,iy,0);
grid[iy*areaLx+ix] = S->potentiel(Origine);
}
}
float maxi=0,s;
int xmaxi,ymaxi;
for (i=0; i<conveyorBlocks; i++) {
maxi=0;
for (iy=0; iy<areaLy; iy++) {
for (ix=0; ix<areaLx; ix++) {
s=grid[iy*areaLx+ix];
if (s>=maxi) {
xmaxi = ix;
ymaxi = iy;
maxi = s;
}
}
}
grid[ymaxi*areaLx+xmaxi]=-1;
}
cout << maxi << endl;
char titre[1024];
sprintf(titre,"configMakeY%dx%d_%d_%d.xml",initSquareLx,initSquareLy,conveyorBlocks,armLength);
ofstream fout;
fout.open(titre);
fout << "<?xml version=\"1.0\" standalone=\"no\" ?>"<< endl;
fout << "<world gridSize=\""<< areaLx << "," << areaLy << "\" windowSize=\"1800,900\" maxSimulationTime=\"" << maxTimeSimulation << "mn\">" << endl;
fout << "<camera target=\""<< areaLx*25.0/2.0 << "," << areaLy*25.0/2.0 << ",0\" directionSpherical=\"0,38," << cameraDist << "\" angle=\"50\"/>" << endl;
fout << "<spotlight target=\""<< areaLx*25.0/2.0 << "," << areaLy*25.0/2.0 << ",0\" directionSpherical=\"-30,50," << srcDist << "\" angle=\"45\"/>" << endl;
fout << "<blockList color=\"0,255,0\" blocksize=\"25.0,25.0,11.0\">" << endl;
for (iy=0; iy<initSquareLy; iy++) {
fout << "<blocksLine line=\"" << initSquareLy+1-iy << "\" values=\"00";
for (ix=0; ix<areaLx/2-initSquareLx; ix++) {
fout << "0";
}
for (ix=0; ix<initSquareLx; ix++) {
fout << "1";
}
for (ix=areaLx/2; ix<areaLx; ix++) {
fout << "0";
}
fout << "\"/>" << endl;
}
fout << "</blockList>\n<targetGrid>" << endl;
/* int ix0=2+initSquareLx-overlapLx,
iy0=2+initSquareLy-overlapLy;
for (iy=0; iy<finalSquareLy; iy++) {
fout << "<targetLine line=\"" << finalSquareLy-1+iy0-iy << "\" values=\"";
for (ix=0; ix<ix0; ix++) {
fout << "0";
}
for (ix=0; ix<finalSquareLx; ix++) {
fout << "1";
}
fout << "00\"/>" << endl;
}*/
for (iy=0; iy<areaLy; iy++) {
fout << "<targetLine line=\"" << areaLy-iy-1 << "\" values=\"";
for (ix=0; ix<areaLx; ix++) {
fout << (grid[ix+iy*areaLx]==-1)?1:0 ;
//fout << grid[ix+iy*areaLx];
}
fout << "\"/>" << endl;
}
fout << "</targetGrid>" << endl;
// lecture du fichier capabilities.xml
ifstream fin("capabilities.xml");
char line[1024];
while (!fin.eof()) {
fin.getline(line,1024);
fout << line << endl;
}
fout << "</world>\n";
delete S;
fout.close();
return 0;
}
| 30.420118
| 157
| 0.51313
|
claytronics
|
f82b1039c9d734ac60363adfdb91874ca6e969c2
| 39,825
|
cpp
|
C++
|
main/dsp/DCO_Synth.cpp
|
shroomist/Glo_v1
|
19e09790fa9f26926f7565f026ebb98fec4243ee
|
[
"Apache-2.0"
] | 16
|
2019-10-09T17:20:15.000Z
|
2021-09-05T03:26:00.000Z
|
main/dsp/DCO_Synth.cpp
|
shroomist/Glo_v1
|
19e09790fa9f26926f7565f026ebb98fec4243ee
|
[
"Apache-2.0"
] | 1
|
2019-12-16T20:29:33.000Z
|
2019-12-16T20:29:33.000Z
|
main/dsp/DCO_Synth.cpp
|
shroomist/Glo_v1
|
19e09790fa9f26926f7565f026ebb98fec4243ee
|
[
"Apache-2.0"
] | 3
|
2019-11-01T01:03:00.000Z
|
2022-02-16T13:35:34.000Z
|
/*
* DCO_synth.cpp
*
* Created on: 11 May 2017
* Author: mario
*
* Based on "The Tiny-TS Touch Synthesizer" by Janost 2016, Sweden
* https://janostman.wordpress.com/the-tiny-ts-diy-touch-synthesizer/
* https://www.kickstarter.com/projects/732508269/the-tiny-ts-an-open-sourced-diy-touch-synthesizer/
*
*/
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
#include <DCO_Synth.h>
#include <Accelerometer.h>
//#include <stdbool.h>
//#include <string.h>
//#include <stddef.h>
//#include <stdlib.h>
//#include <math.h>
//#include <InitChannels.h>
#include <Interface.h>
//#include <MusicBox.h>
#include <hw/codec.h>
#include <hw/signals.h>
#include <hw/ui.h>
#include <notes.h>
#include <FreqDetect.h>
//#include <hw/init.h>
#include <hw/gpio.h>
#include <hw/sdcard.h>
#include <hw/midi.h>
#include <hw/leds.h>
//#include <hw/sha1.h>
//#include <stdio.h>
//#define DEBUG_DCO
#define MIX_INPUT
#define MIX_ECHO
//#define USE_AUTOCORRELATION
//#define LPF_ENABLED
#define ADC_LPF_ALPHA_DCO 0.2f //up to 1.0 for max feedback = no filtering
#define ADC_SAMPLE_GAIN 4 //integer value
#define DYNAMIC_LIMITER
//#define STATIC_LIMITER
extern float ADC_LPF_ALPHA;
const uint8_t DCO_Synth::sinetable256[256] = {
0,0,0,0,1,1,1,2,2,3,4,5,5,6,7,9,10,11,12,14,15,16,18,20,21,23,25,27,29,31,
33,35,37,39,42,44,46,49,51,54,56,59,62,64,67,70,73,76,78,81,84,87,90,93,96,99,102,105,108,111,115,118,121,124,
127,130,133,136,139,143,146,149,152,155,158,161,164,167,170,173,176,178,181,184,187,190,192,195,198,200,203,205,208,210,212,215,217,219,221,223,225,227,229,231,233,234,236,238,239,240,
242,243,244,245,247,248,249,249,250,251,252,252,253,253,253,254,254,254,254,254,254,254,253,253,253,252,252,251,250,249,249,248,247,245,244,243,242,240,239,238,236,234,233,231,229,227,225,223,
221,219,217,215,212,210,208,205,203,200,198,195,192,190,187,184,181,178,176,173,170,167,164,161,158,155,152,149,146,143,139,136,133,130,127,124,121,118,115,111,108,105,102,99,96,93,90,87,84,81,78,
76,73,70,67,64,62,59,56,54,51,49,46,44,42,39,37,35,33,31,29,27,25,23,21,20,18,16,15,14,12,11,10,9,7,6,5,5,4,3,2,2,1,1,1,0,0,0
};
//uint8_t DCO_Synth::*sawtable256;
//uint8_t DCO_Synth::*squaretable256;
DCO_Synth::DCO_Synth()
{
envtick = 549;
DOUBLE = 0;
RESO = 64; //resonant peak mod volume
//-------- Synth parameters --------------
//volatile uint8_t VCA=255; //VCA level 0-255
ATTACK = 1; // ENV Attack rate 0-255
RELEASE = 1; // ENV Release rate 0-255
//ENVELOPE=0; // ENV Shape
//TRIG=0; //MIDItrig 1=note ON
//-----------------------------------------
FREQ = 0; //DCO pitch
DCO_BLOCKS_ACTIVE = DCO_BLOCKS_MAX;// / 2;
DCO_mode = 0;
SET_mode = 0;
button_set_held = 0;
MIDI_note_set = 0;//, MIDI_note_on = 0;
use_table256 = (uint8_t*)sinetable256;
sawtable256 = (uint8_t*)malloc(256*sizeof(uint8_t));
squaretable256 = (uint8_t*)malloc(256*sizeof(uint8_t));
for(int i=0;i<256;i++)
{
sawtable256[i] = i;
squaretable256[i] = (i<128)?0:255;
}
}
DCO_Synth::~DCO_Synth(void)
{
printf("DCO_Synth::~DCO_Synth(void)\n");
free(sawtable256);
free(squaretable256);
#ifdef USE_AUTOCORRELATION
stop_autocorrelation();
#endif
}
//---------------------------------------------------------------------------------------------------------------------
// Old, simpler version (no controls during play, apart from IR sensors) but keeping here as it is fun to play
// Some leftovers from the original Tiny-TS code
//---------------------------------------------------------------------------------------------------------------------
//mixed sound output variable
//int16_t OutSample = 128;
//uint8_t GATEIO=0; //0=Gate is output, 1=Gate is input
//uint16_t COARSEPITCH;
//uint8_t ENVsmoothing;
//uint8_t envcnt=10;
//int16_t ENV;
//uint8_t k=0;
//uint8_t z;
//int8_t MUX=0;
void DCO_Synth::v1_init()//int mode)
{
//-----------------------------------------------------------------------------------
// Tiny-TS variables init
//-----------------------------------------------------------------------------------
sample_i16 = 128;
FREQ=DCO_FREQ_DEFAULT;//440;//MIDI2FREQ(key+12+(COARSEPITCH/21.3125));
//uint16_t CVout=COARSEPITCH+(key*21.33);
//OCR1AH = (CVout>>8);
//OCR1AL = CVout&255;
//---------------------------------------------------------------
//--------------- ADC block -------------------------------------
//if (MUX==0) COARSEPITCH=(ADCL+(ADCH<<8));
//COARSEPITCH=0;//(uint16_t)123;//45;
//if (MUX==1) DOUBLE=(ADCL+(ADCH<<8))>>2;
DOUBLE = 12;
//if (MUX==2) PHASEamt=(((ADCL+(ADCH<<8)))>>3);
PHASEamt = 9;
//if (MUX==3) ENVamt=((ADCL+(ADCH<<8))>>3);
ENVamt = 123;
//if (MUX==4) ATTACK=ATTrates[15-((ADCL+(ADCH<<8))>>6)];
ATTACK = 64;//ATTrates[12];
//if (MUX==5) RELEASE=RELrates[15-((ADCL+(ADCH<<8))>>6)];
RELEASE = 64;//RELrates[6];
ECHO_MIXING_GAIN_MUL = 3; //amount of signal to feed back to echo loop, expressed as a fragment
ECHO_MIXING_GAIN_DIV = 4; //e.g. if MUL=2 and DIV=3, it means 2/3 of signal is mixed in
ADC_LPF_ALPHA = ADC_LPF_ALPHA_DCO;
#ifdef USE_AUTOCORRELATION
start_autocorrelation(0); //start at core 0 as the DCO is running at core 1
#endif
}
void DCO_Synth::v1_play_loop()
{
int i;
int midi_override = 0;
while(!event_next_channel)
{
if(waveform)
{
//-------------------- DCO block ------------------------------------------
DCO_output[0] = 0;
DCO_output[1] = 0;
for (int b=0; b<DCO_BLOCKS_ACTIVE; b++)
{
phacc[b] += FREQ + (b * DOUBLE);
if (phacc[b] & 0x8000) {
phacc[b] &= 0x7FFF;
otone1[b] += 2;
pdacc[b] += PDmod;
}
if (!otone1[b]) pdacc[b] = 0;
otone2[b] = (pdacc[b] >> 3) & 255;
uint8_t env = (255-otone1[b]);
DCO_output[b%2] +=
//DCO_output[b/(DCO_BLOCKS_ACTIVE/2)] +=
(use_table256[otone2[b]] + use_table256[(otone2[b] + (127 - env)) & 255]);
}
//---------------------------------------------------------------------------
//------------------ VCA block ------------------------------------
/*
if ((ATTACK==255)&&(TRIG==1)) VCA=255;
if (!(envcnt--)) {
envcnt=20;
if (VCA<volume) VCA++;
if (VCA>volume) VCA--;
}
*/
/*
#define M(MX, MX1, MX2) \
asm volatile ( \
"clr r26 \n\t"\
"mulsu %B1, %A2 \n\t"\
"movw %A0, r0 \n\t"\
"mul %A1, %A2 \n\t"\
"add %A0, r1 \n\t"\
"adc %B0, r26 \n\t"\
"clr r1 \n\t"\
: \
"=&r" (MX) \
: \
"a" (MX1), \
"a" (MX2) \
:\
"r26"\
)
*/
//DCO>>=1;
//DCO>>=2;
//DCO_output>>=4;
////M(ENV, (int16_t)DCO, VCA);
//ENV = (int16_t)DCO * VCA;
//OCR2A = ENV>>1;
//OutSample = (int16_t)DCO * VCA;
//sample_i16 = (int16_t)DCO_output * VCA;
//sample_i16 = (int16_t)DCO_output;
//-----------------------------------------------------------------
if (!(envtick--)) {
envtick=582;
//--------------------- ENV block ---------------------------------
/*
if ((TRIG==1)&&(volume<255)) {
volume+=ATTACK;
if (volume>255) volume=255;
}
if ((TRIG==0)&&(volume>0)) {
volume-=RELEASE;
if (volume<0) volume=0;
}
*/
//-----------------------------------------------------------------
//--------- Resonant Peak ENV modulation ----------------------------------------
//if(!DCO_mode)
{
PDmod=((RESO*ENVamt)>>8)+PHASEamt;
if (PDmod>255) PDmod=255;
//if (PDmod>8192) PDmod=8192;
}
//-----------------------------------------------------------------
}
//-------------------------------------------------------------------------
// listen and analyse
//-------------------------------------------------------------------------
#ifdef USE_AUTOCORRELATION
if(dco_control_mode==2)
{
if(autocorrelation_rec_sample)
{
autocorrelation_buffer[--autocorrelation_rec_sample] = (int16_t)ADC_sample;
}
}
#endif
//-------------------------------------------------------------------------
// send sample to codec
//-------------------------------------------------------------------------
sample_i16 = (int16_t)DCO_output[0];
}
else
{
sample_i16 = 0;
}
#ifdef MIX_INPUT
#ifdef LPF_ENABLED
sample_lpf[0] = sample_lpf[0] + ADC_LPF_ALPHA * ((float)((int16_t)(ADC_sample>>16)) - sample_lpf[0]);
sample_i16 += (int16_t)(sample_lpf[0] * ADC_SAMPLE_GAIN); //low-pass
//sample_i16 += (int16_t)(ADC_sample>>16) - (int16_t)(sample_lpf[0] * ADC_SAMPLE_GAIN); //high-pass
#else
sample_i16 += ((int16_t)(ADC_sample>>16)) * ADC_SAMPLE_GAIN;
#endif
#endif
#ifdef MIX_ECHO
//add echo from the loop
sample_i16 += echo_buffer[echo_buffer_ptr];
#endif
#ifdef DYNAMIC_LIMITER
//apply dynamic limiter
echo_mix_f = (float)sample_i16 * limiter_coeff;
if(echo_mix_f < -DYNAMIC_LIMITER_THRESHOLD_ECHO_DCO && limiter_coeff > 0)
{
limiter_coeff *= DYNAMIC_LIMITER_COEFF_MUL_DCO;
}
sample_i16 = (int16_t)echo_mix_f;
#endif
#ifdef STATIC_LIMITER
while(sample_i16 > 16000 || sample_i16 < -16000)
{
sample_i16 /= 2;
}
#endif
sample32 = sample_i16 << 16;
if(waveform)
{
sample_i16 = (int16_t)DCO_output[1];
}
else
{
sample_i16 = 0;
}
#ifdef MIX_INPUT
#ifdef LPF_ENABLED
sample_lpf[1] = sample_lpf[1] + ADC_LPF_ALPHA * ((float)((int16_t)ADC_sample) - sample_lpf[1]);
sample_i16 += (int16_t)(sample_lpf[1] * ADC_SAMPLE_GAIN); //low-pass
//sample_i16 += (int16_t)ADC_sample - (int16_t)(sample_lpf[1] * ADC_SAMPLE_GAIN); //high-pass
#else
sample_i16 += ((int16_t)(ADC_sample)) * ADC_SAMPLE_GAIN;
#endif
#endif
#ifdef MIX_ECHO
//---------------------------------------------------------------------------------------
//wrap the echo loop
echo_buffer_ptr0++;
if(echo_buffer_ptr0 >= echo_dynamic_loop_length)
{
echo_buffer_ptr0 = 0;
}
echo_buffer_ptr = echo_buffer_ptr0 + 1;
if(echo_buffer_ptr >= echo_dynamic_loop_length)
{
echo_buffer_ptr = 0;
}
//add echo from the loop
sample_i16 += echo_buffer[echo_buffer_ptr];
#ifdef DYNAMIC_LIMITER
//apply dynamic limiter
echo_mix_f = (float)sample_i16 * limiter_coeff;
if(echo_mix_f < -DYNAMIC_LIMITER_THRESHOLD_ECHO_DCO && limiter_coeff > 0)
{
limiter_coeff *= DYNAMIC_LIMITER_COEFF_MUL_DCO;
}
sample_i16 = (int16_t)echo_mix_f;
#endif
#ifdef STATIC_LIMITER
while(sample_i16 > 16000 || sample_i16 < -16000)
{
sample_i16 /= 2;
}
#endif
#ifdef DYNAMIC_LIMITER
if(erase_echo==1 || (limiter_coeff < DYNAMIC_LIMITER_COEFF_DEFAULT))
{
ECHO_MIXING_GAIN_MUL = 1.0f;
}
else
{
ECHO_MIXING_GAIN_MUL = 3.0f;
}
#endif
if(erase_echo!=2)
{
//store result to echo, the amount defined by a fragment
echo_buffer[echo_buffer_ptr0] = (int16_t)((float)sample_i16 * ECHO_MIXING_GAIN_MUL / ECHO_MIXING_GAIN_DIV);
}
#endif
/*
if(erase_echo)
{
echo_buffer[echo_buffer_ptr0] /= 2;
}
*/
//---------------------------------------------------------------------------------------
sample32 += sample_i16;
#ifdef BOARD_WHALE
if(add_beep)
{
if(sampleCounter & (1<<add_beep))
{
sample32 += (100 + (100<<16));
}
}
#endif
for(i=0;i<dco_oversample;i++)
{
i2s_push_sample(I2S_NUM, (char *)&sample32, portMAX_DELAY);
sd_write_sample(&sample32);
}
#if defined(MIX_INPUT) || defined(USE_AUTOCORRELATION)
for(i=0;i<dco_oversample;i++)
{
/*ADC_result = */i2s_pop_sample(I2S_NUM, (char*)&ADC_sample, portMAX_DELAY);
}
#endif
//---------------------------------------------------------------------------------------
sampleCounter++;
if(TIMING_BY_SAMPLE_1_SEC)
{
sampleCounter = 0;
seconds++;
}
#ifdef BOARD_WHALE
if (TIMING_BY_SAMPLE_EVERY_100_MS==0)
{
RGB_LED_R_OFF;
RGB_LED_G_OFF;
RGB_LED_B_OFF;
}
if (TIMING_BY_SAMPLE_EVERY_100_MS==1000 && waveform)
{
RGB_LED_R_OFF;
RGB_LED_B_OFF;
if(param==0) { RGB_LED_R_ON; RGB_LED_G_ON; RGB_LED_B_ON; }
if(param==1) { RGB_LED_R_ON; RGB_LED_G_ON; }
if(param==2) { RGB_LED_R_ON; RGB_LED_B_ON; }
if(param==3) { RGB_LED_G_ON; }
if(param==4) { RGB_LED_R_ON; }
}
#endif
ui_command = 0;
if (TIMING_EVERY_20_MS==31) //50Hz
{
#define DCO_UI_CMD_NEXT_PARAM 1
#define DCO_UI_CMD_PREV_PARAM 2
#define DCO_UI_CMD_OVERSAMPLE_UP 3
#define DCO_UI_CMD_OVERSAMPLE_DOWN 4
#define DCO_UI_CMD_NEXT_WAVEFORM 5
#define DCO_UI_CMD_NEXT_DELAY 6
#define DCO_UI_CMD_RANDOMIZE_PARAMS 7
#define DCO_UI_CMD_DRIFT_PARAMS 8
//map UI commands
#ifdef BOARD_WHALE
if(short_press_volume_plus) { ui_command = DCO_UI_CMD_NEXT_PARAM; short_press_volume_plus = 0; }
if(short_press_volume_minus) { ui_command = DCO_UI_CMD_PREV_PARAM; short_press_volume_minus = 0; }
if(short_press_sequence==2) { ui_command = DCO_UI_CMD_OVERSAMPLE_UP; short_press_sequence = 0; }
if(short_press_sequence==-2) { ui_command = DCO_UI_CMD_OVERSAMPLE_DOWN; short_press_sequence = 0; }
if(short_press_sequence==3) { ui_command = DCO_UI_CMD_NEXT_WAVEFORM; short_press_sequence = 0; }
if(short_press_sequence==-3) { ui_command = DCO_UI_CMD_NEXT_DELAY; short_press_sequence = 0; }
if(short_press_sequence==SEQ_PLUS_MINUS) { ui_command = DCO_UI_CMD_RANDOMIZE_PARAMS; short_press_sequence = 0; }
if(short_press_sequence==SEQ_MINUS_PLUS) { ui_command = DCO_UI_CMD_DRIFT_PARAMS; short_press_sequence = 0; }
#endif
#ifdef BOARD_GECHO
if(btn_event_ext==BUTTON_EVENT_SHORT_PRESS+BUTTON_1) { ui_command = DCO_UI_CMD_DRIFT_PARAMS; btn_event_ext = 0; }
if(btn_event_ext==BUTTON_EVENT_SHORT_PRESS+BUTTON_2) { ui_command = DCO_UI_CMD_NEXT_WAVEFORM; btn_event_ext = 0; }
if(btn_event_ext==BUTTON_EVENT_RST_PLUS+BUTTON_2) { ui_command = DCO_UI_CMD_OVERSAMPLE_UP; btn_event_ext = 0; }
if(btn_event_ext==BUTTON_EVENT_RST_PLUS+BUTTON_1) { ui_command = DCO_UI_CMD_OVERSAMPLE_DOWN; btn_event_ext = 0; }
//if(event_channel_options) { ui_command = DCO_UI_CMD_RANDOMIZE_PARAMS; event_channel_options = 0; }
#endif
//FREQ = ADC_last_result[0] * 4;
//FREQ = (uint16_t)((acc_res[0] + 1.0f) * 440.0f * 16);
#ifdef BOARD_WHALE
if(event_channel_options)
{
event_channel_options = 0;
dco_control_mode++;
if(dco_control_mode==DCO_CONTROL_MODES)
{
dco_control_mode = 0;
}
printf("DCO Control mode = %d\n", dco_control_mode);
}
if(ui_command==DCO_UI_CMD_NEXT_PARAM)
{
if(dco_control_mode==1 || dco_control_mode==2)
{
param++;
if(param==DCO_MAX_PARAMS)
{
param = 0;
}
}
}
if(ui_command==DCO_UI_CMD_PREV_PARAM)
{
if(dco_control_mode==1 || dco_control_mode==2)
{
param--;
if(param==0)
{
param = DCO_MAX_PARAMS-1;
}
}
}
#endif
if(ui_command==DCO_UI_CMD_OVERSAMPLE_DOWN)
{
if(dco_oversample<8)
{
//dco_oversample*=2;
dco_oversample++;
}
printf("DCO Oversample = %d\n", dco_oversample);
}
if(ui_command==DCO_UI_CMD_OVERSAMPLE_UP)
{
if(dco_oversample>1)
{
//dco_oversample/=2;
dco_oversample--;
printf("DCO Oversample = %d\n", dco_oversample);
}
}
if(ui_command==DCO_UI_CMD_NEXT_WAVEFORM)
{
waveform++;
if(waveform==1)
{
use_table256 = (uint8_t*)sinetable256;
}
else if(waveform==2)
{
use_table256 = squaretable256;
}
else if(waveform==3)
{
use_table256 = sawtable256;
}
else
{
waveform = 0;
}
printf("waveform set to type #%d\n",waveform);
}
#ifdef BOARD_WHALE
if(ui_command==DCO_UI_CMD_NEXT_DELAY)
{
if(echo_dynamic_loop_current_step!=ECHO_DYNAMIC_LOOP_LENGTH_ECHO_OFF)
{
echo_dynamic_loop_current_step = ECHO_DYNAMIC_LOOP_LENGTH_ECHO_OFF;
}
else
{
echo_dynamic_loop_current_step = ECHO_DYNAMIC_LOOP_LENGTH_DEFAULT_STEP;
}
echo_dynamic_loop_length = echo_dynamic_loop_steps[echo_dynamic_loop_current_step];
printf("echo set to step #%d, length = %d\n",echo_dynamic_loop_current_step,echo_dynamic_loop_length);
}
#endif
if(ui_command==DCO_UI_CMD_RANDOMIZE_PARAMS)
{
//randomize all params
if(!midi_override)
{
new_random_value();
FREQ = random_value;
}
new_random_value();
DOUBLE = random_value;
PHASEamt = random_value<<8;
new_random_value();
ENVamt = random_value;
new_random_value();
RESO = random_value;
}
if(ui_command==DCO_UI_CMD_DRIFT_PARAMS)
{
drift_params++;
if(drift_params==DRIFT_PARAMS_MAX+1)
{
drift_params = 0;
}
drift_params_cnt = 0;
printf("drift_params = %d\n", drift_params);
}
if(!drift_params)
{
if(use_acc_or_ir_sensors==PARAMETER_CONTROL_SENSORS_ACCELEROMETER)
{
if(dco_control_mode==0)
{
if(!shift_param && (acc_res[0] > 0.3f))
{
printf("shift_param = 1, param++\n");
shift_param = 1;
param++;
if(param==DCO_MAX_PARAMS)
{
param = 0;
}
sampleCounter = 0;
}
else if(!shift_param && (acc_res[0] < -0.3f))
{
printf("shift_param = 1, param--\n");
shift_param = 1;
param--;
if(param<0)
{
param = DCO_MAX_PARAMS - 1;
}
sampleCounter = 0;
}
else if(shift_param && (fabs(acc_res[0]) < 0.2f))
{
shift_param = 0;
printf("shift_param = 0\n");
}
}
//printf("acc_res[0-2]==%f,\t%f,\t%f...\t", acc_res[0],acc_res[1],acc_res[2]);
if(param==0) //FREQ
{
FREQ = (uint16_t)(acc_res[1] * DCO_FREQ_DEFAULT * 2);
//printf("FREQ=%d\n",FREQ);
}
if(param==1) //DOUBLE
{
DOUBLE = (uint8_t)(acc_res[1] * 256);
//printf("DOUBLE=%d\n",DOUBLE);
}
if(param==2) //PHASEamt
{
PHASEamt = (uint8_t)(acc_res[1] * 256);
//printf("PHASEamt=%d\n",PHASEamt);
}
if(param==3) //ENVamt
{
ENVamt = (uint8_t)(acc_res[1] * 32);
//printf("ENVamt=%d\n",ENVamt);
}
if(param==4) //RESO
{
RESO = (uint16_t)(acc_res[1] * 4096);
//printf("RESO=%d\n",RESO);
}
/*
if(param==5) //DCO_BLOCKS_ACTIVE
{
DCO_BLOCKS_ACTIVE = (uint8_t)(((acc_res[1] + 1.0f) * (DCO_BLOCKS_MAX-1))/2);
printf("DCO_BLOCKS_ACTIVE=%d\n",DCO_BLOCKS_ACTIVE);
}
*/
/*
if(!erase_echo && acc_res[2] > 0.7f)
{
erase_echo = 2;
}
else
{
erase_echo = 0;
}
*/
if(acc_res[2] > 0.7f)
{
//ECHO_MIXING_GAIN_MUL = 1.0f;
//if(erase_echo!=1) printf("setting erase_echo => 1\n");
erase_echo = 1;
}
else if(acc_res[0] < -0.7f)
{
//ECHO_MIXING_GAIN_MUL = 1.0f;
//if(erase_echo!=2) printf("setting erase_echo => 2\n");
erase_echo = 2;
}
else
{
//ECHO_MIXING_GAIN_MUL = 3.0f;
//if(erase_echo!=0) printf("setting erase_echo => 0\n");
erase_echo = 0;
}
}
else //if sensors used
{
if(!midi_override)
{
FREQ = (uint16_t)(ir_res[0] * DCO_FREQ_DEFAULT * 2);
//printf("FREQ=%d\n",FREQ);
}
DOUBLE = (uint8_t)(ir_res[1] * 256);
//printf("DOUBLE=%d\n",DOUBLE);
PHASEamt = (uint8_t)(ir_res[2] * 256);
//printf("PHASEamt=%d\n",PHASEamt);
ENVamt = (uint8_t)(ir_res[3] * 32);
//printf("ENVamt=%d\n",ENVamt);
RESO = (uint16_t)(ir_res[3] * 4096);
}
}
#ifdef USE_AUTOCORRELATION
if(autocorrelation_result_rdy && dco_control_mode==2)
{
//printf("ac res = %d,%d,%d,%d\n", autocorrelation_result[0], autocorrelation_result[1], autocorrelation_result[2], autocorrelation_result[3]);
autocorrelation_result_rdy = 0;
//FREQ = (256-autocorrelation_result[0])<<8;//(uint16_t)((acc_res[0] + 1.0f) * 440.0f * 16);
//FREQ = (autocorrelation_result[0])<<8;//(uint16_t)((acc_res[0] + 1.0f) * 440.0f * 16);
//int x = ac_to_freq(autocorrelation_result[0]);
int x = (uint16_t)((acc_res[0] + 1.0f) * DCO_FREQ_DEFAULT/2 );
if(x>100)
{
FREQ = x;
printf("%d => %d\n", autocorrelation_result[0], FREQ);
}
}
//DOUBLE = ADC_last_result[1] / 8;
//DOUBLE = ADC_last_result[1] / 12;
//DOUBLE = 220;//(uint8_t)((acc_res[1] + 1.0f) * 120); //6; //default 12?
//PHASEamt = ADC_last_result[2] / 8;
//PHASEamt = ADC_last_result[2] / 16;
//PHASEamt = 110;//(uint8_t)((acc_res[2] + 1.0f) * 120); //4; //default 9?
//ENVamt = ADC_last_result[3] * 16; /// 4;
//ENVamt = 123;//(acc_res[2] + 1.0f) * 128;//64; //default 123
#endif
#ifdef DIRECT_PARAM_CONTROL
//direct controlls by buttons
if(event_channel_options)
{
event_channel_options = 0;
param++;
if(param==1)
{
printf("updating DOUBLE\n");
}
if(param==2)
{
printf("updating PHASEamt\n");
}
if(param==3)
{
printf("updating ENVamt\n");
}
if(param==DCO_MAX_PARAMS)
{
param = 0;
printf("updating FREQ\n");
}
printf("FREQ=%d,DOUBLE=%d,PHASEamt=%d,ENVamt=%d\n",FREQ,DOUBLE,PHASEamt,ENVamt);
}
if(short_press_sequence)
{
if(param==0) //FREQ (16-bit)
{
if(short_press_volume_minus) {FREQ--; short_press_volume_minus = 0; }
if(short_press_volume_plus) {FREQ++; short_press_volume_plus = 0; }
if(abs(short_press_sequence)==2) FREQ += short_press_sequence*10/2;
if(abs(short_press_sequence)==3) FREQ += short_press_sequence*100/3;
if(abs(short_press_sequence)==4) FREQ += short_press_sequence*1000/4;
printf("FREQ updated to %d\n", FREQ);
}
if(param==1) //DOUBLE (8-bit)
{
if(short_press_volume_minus) {DOUBLE--; short_press_volume_minus = 0; }
if(short_press_volume_plus) {DOUBLE++; short_press_volume_plus = 0; }
if(abs(short_press_sequence)==2) DOUBLE += short_press_sequence*10/2;
if(abs(short_press_sequence)==3) DOUBLE += short_press_sequence*100/3;
printf("DOUBLE updated to %d\n", DOUBLE);
}
if(param==2) //PHASE (8-bit)
{
if(short_press_volume_minus) {PHASEamt--; short_press_volume_minus = 0; }
if(short_press_volume_plus) {PHASEamt++; short_press_volume_plus = 0; }
if(abs(short_press_sequence)==2) PHASEamt += short_press_sequence*10/2;
if(abs(short_press_sequence)==3) PHASEamt += short_press_sequence*100/3;
printf("PHASEamt updated to %d\n", PHASEamt);
}
if(param==3) //ENVamt (8-bit)
{
if(short_press_volume_minus) {ENVamt--; short_press_volume_minus = 0; }
if(short_press_volume_plus) {ENVamt++; short_press_volume_plus = 0; }
if(abs(short_press_sequence)==2) ENVamt += short_press_sequence*10/2;
if(abs(short_press_sequence)==3) ENVamt += short_press_sequence*100/3;
printf("ENVamt updated to %d\n", ENVamt);
}
short_press_sequence = 0;
}
#endif
#ifdef DEBUG_DCO
printf("FREQ=%d,DOUBLE=%d,PHASEamt=%d,ENVamt=%d\n",FREQ,DOUBLE,PHASEamt,ENVamt);
#endif
}
if (TIMING_EVERY_20_MS == 47) //50Hz
{
if(!midi_override && MIDI_keys_pressed)
{
printf("MIDI active, will receive chords\n");
midi_override = 1;
}
if(midi_override && MIDI_notes_updated)
{
MIDI_notes_updated = 0;
LED_W8_all_OFF();
LED_B5_all_OFF();
MIDI_to_LED(MIDI_last_chord[0], 1);
FREQ = MIDI_note_to_freq(MIDI_last_chord[0]+36); //shift a couple octaves up as the FREQ parameter here works differently
}
}
//if (TIMING_EVERY_250_MS == 39) //4Hz
if (TIMING_EVERY_125_MS == 39) //8Hz
{
if(drift_params==4
|| (drift_params==3 && drift_params_cnt%2==0)
|| (drift_params==2 && drift_params_cnt%4==0)
|| (drift_params==1 && drift_params_cnt%8==0))
{
//adjust all params by small random value
new_random_value();
if(!midi_override)
{
FREQ += ((int8_t)random_value)/8;
}
DOUBLE += ((int8_t)(random_value>>8))/8;
PHASEamt += ((int8_t)(random_value>>16))/8;
ENVamt += ((int8_t)(random_value>>24))/8;
new_random_value();
RESO += ((int16_t)random_value/128);
}
else if(drift_params==8
|| (drift_params==7 && drift_params_cnt%2==0)
|| (drift_params==6 && drift_params_cnt%4==0)
|| (drift_params==5 && drift_params_cnt%8==0))
{
//randomize all params
if(!midi_override)
{
new_random_value();
FREQ = random_value;
}
new_random_value();
DOUBLE = random_value;
PHASEamt = random_value<<8;
new_random_value();
ENVamt = random_value;
new_random_value();
RESO = random_value;
}
#if 0
else if(drift_params==9 || (drift_params==8 && drift_params_cnt%2==0) || (drift_params==7 && drift_params_cnt%4==0))
{
//randomize all params
new_random_value();
FREQ = random_value;
new_random_value();
DOUBLE = random_value;
PHASEamt = random_value<<8;
new_random_value();
ENVamt = random_value;
new_random_value();
RESO = random_value;
}
else if(drift_params==12 || (drift_params==11 && drift_params_cnt%2==0) || (drift_params==10 && drift_params_cnt%4==0))
{
//randomize all params
new_random_value();
FREQ = random_value;
new_random_value();
DOUBLE = random_value;
PHASEamt = random_value<<8;
new_random_value();
ENVamt = random_value;
new_random_value();
RESO = random_value;
}
else if(drift_params==15 || (drift_params==14 && drift_params_cnt%2==0) || (drift_params==13 && drift_params_cnt%4==0))
{
//randomize all params
new_random_value();
FREQ = random_value;
new_random_value();
DOUBLE = random_value;
PHASEamt = random_value<<8;
new_random_value();
ENVamt = random_value;
new_random_value();
RESO = random_value;
}
else if(drift_params==18 || (drift_params==17 && drift_params_cnt%2==0) || (drift_params==16 && drift_params_cnt%4==0))
{
//randomize all params
new_random_value();
FREQ = random_value;
new_random_value();
DOUBLE = random_value;
PHASEamt = random_value<<8;
new_random_value();
ENVamt = random_value;
new_random_value();
RESO = random_value;
}
/*else if(drift_params==21 || (drift_params==20 && drift_params_cnt%2==0) || (drift_params==19 && drift_params_cnt%4==0))
{
//randomize all params
new_random_value();
FREQ = random_value;
new_random_value();
DOUBLE = random_value;
PHASEamt = random_value<<8;
new_random_value();
ENVamt = random_value;
new_random_value();
RESO = random_value;
}*/
#endif
drift_params_cnt++;
}
if (TIMING_EVERY_20_MS == 33) //50Hz
{
if(limiter_coeff < DYNAMIC_LIMITER_COEFF_DEFAULT)
{
//limiter_coeff += DYNAMIC_LIMITER_COEFF_DEFAULT / 20; //timing @20Hz, limiter will fully recover within 1 second
limiter_coeff += DYNAMIC_LIMITER_COEFF_DEFAULT / 20; //timing @ 50Hz, limiter will fully recover within 0.4 second
printf("limiter_coeff=%f\n",limiter_coeff);
}
}
}
}
#if 0
void DCO_Synth::v2_init()
{
init_codec();
//-----------------------------------------------------------------------------------
// Gecho variables and peripherals init
//-----------------------------------------------------------------------------------
GPIO_LEDs_Buttons_Reset();
//ADC_DeInit(); //reset ADC module
ADC_configure_SENSORS(ADCConvertedValues);
//ADC_configure_CV_GATE(CV_GATE_PC0_PB0); //PC0 stays the same as if configured for IRS1
//int calibration_success = Calibrate_CV(); //if successful, array with results is stored in *calibrated_cv_values
//-----------------------------------------------------------------------------------
// Tiny-TS variables init
//-----------------------------------------------------------------------------------
sample_i16 = 128;
FREQ=440;//MIDI2FREQ(key+12+(COARSEPITCH/21.3125));
DOUBLE=12;
PHASEamt=9;
ENVamt=123;
ATTACK=64;//ATTrates[12];
RELEASE=64;//RELrates[6];
DCO_BLOCKS_ACTIVE = 24;
RESO = 64;
//if(mode==1)
//{
//load the default sequence
//char *seq = "a3a2a3a2c3a2d3c3a2a2a3a2g3c3f#3e3";
//parse_notes(seq, sequence, NULL);
//SEQUENCER_THRESHOLD = 200;
//}
//echo loop
init_echo_buffer();
ECHO_MIXING_GAIN_MUL = 1; //amount of signal to feed back to echo loop, expressed as a fragment
ECHO_MIXING_GAIN_DIV = 4; //e.g. if MUL=2 and DIV=3, it means 2/3 of signal is mixed in
for(int i=0;i<128;i++)
{
MIDI_notes_to_freq[i] = NOTE_FREQ_A4 * pow(HALFTONE_STEP_COEF, i - 33);
}
}
void DCO_Synth::v2_play_loop()
{
while(1)
{
//-------------------- DCO block ------------------------------------------
DCO_output[0] = 0;
DCO_output[1] = 0;
for (int b=0; b<DCO_BLOCKS_ACTIVE; b++)
{
phacc[b] += FREQ + (b * DOUBLE);
if (phacc[b] & 0x8000) {
phacc[b] &= 0x7FFF;
otone1[b] += 2;
pdacc[b] += PDmod;
}
if (!otone1[b]) pdacc[b] = 0;
otone2[b] = (pdacc[b] >> 3) & 255;
uint8_t env = (255-otone1[b]);
DCO_output[b%2] += (use_table256[otone2[b]] + use_table256[(otone2[b] + (127 - env)) & 255]);
}
if (!(envtick--)) {
envtick=582;
//--------- Resonant Peak ENV modulation ----------------------------------------
//if(!DCO_mode)
{
PDmod=((RESO*ENVamt)>>8)+PHASEamt;
if (PDmod>255) PDmod=255;
}
}
//-------------------------------------------------------------------------
// send sample to codec
//-------------------------------------------------------------------------
sample_i16 = (int16_t)DCO_output[0];
sample_i16 += echo_buffer[echo_buffer_ptr];
while (!SPI_I2S_GetFlagStatus(CODEC_I2S, SPI_I2S_FLAG_TXE));
SPI_I2S_SendData(CODEC_I2S, sample_i16);
sample_i16 = (int16_t)DCO_output[1];
//wrap in the echo loop
echo_buffer_ptr0++;
if(echo_buffer_ptr0 >= echo_dynamic_loop_length)
{
echo_buffer_ptr0 = 0;
}
echo_buffer_ptr = echo_buffer_ptr0 + 1;
if(echo_buffer_ptr >= echo_dynamic_loop_length)
{
echo_buffer_ptr = 0;
}
//add echo from the loop
sample_i16 += echo_buffer[echo_buffer_ptr];
//store result to echo, the amount defined by a fragment
echo_buffer[echo_buffer_ptr0] = sample_i16 * ECHO_MIXING_GAIN_MUL / ECHO_MIXING_GAIN_DIV;
while (!SPI_I2S_GetFlagStatus(CODEC_I2S, SPI_I2S_FLAG_TXE));
SPI_I2S_SendData(CODEC_I2S, sample_i16);
sampleCounter++;
if (TIMING_BY_SAMPLE_ONE_SECOND_W_CORRECTION)
{
sampleCounter = 0;
seconds++;
}
if (TIMING_BY_SAMPLE_EVERY_10_MS==0) //100Hz
{
if(ADC_process_sensors()==1)
{
ADC_last_result[2] = -ADC_last_result[2];
ADC_last_result[3] = -ADC_last_result[3];
CLEAR_ADC_RESULT_RDY_FLAG;
sensors_loop++;
IR_sensors_LED_indicators(ADC_last_result);
if(SET_mode==0)
{
FREQ = ADC_last_result[0] * 4;
//DOUBLE = ADC_last_result[1] / 8;
DOUBLE = ADC_last_result[1] / 12;
//PHASEamt = ADC_last_result[2] / 8;
PHASEamt = ADC_last_result[2] / 16;
//if(!DCO_mode)
ENVamt = ADC_last_result[3] * 16; /// 4;
//}
//else
//{
// if(ADC_last_result[3] > 200)
// {
// //PDmod = ADC_last_result[3] / 2; /// 4;
// ENVamt = ADC_last_result[3] * 32; /// 4;
// }
// else
// {
// PDmod = 255;
// }
//}
}
else
{
if(BUTTON_U1_ON)
{
FREQ = ADC_last_result[0] * 8;
}
if(BUTTON_U2_ON)
{
DOUBLE = ADC_last_result[1] / 12;
}
if(BUTTON_U3_ON)
{
PHASEamt = ADC_last_result[2] / 16;
}
if(BUTTON_U4_ON)
{
ENVamt = ADC_last_result[3] * 16;
}
}
}
if(BUTTON_SET_ON)
{
if(!button_set_held)
{
if(!SET_mode)
{
LED_SIG_ON;
SET_mode = 1;
button_set_held = 1;
}
else
{
LED_SIG_OFF;
SET_mode = 0;
button_set_held = 1;
}
}
}
else
{
button_set_held = 0;
}
}
}
}
#endif
#if 0
//---------------------------------------------------------------------------------
// version with sequencer
//---------------------------------------------------------------------------------
void DCO_Synth::v3_play_loop()
{
#define SEQ_MAX_NOTES 32 //maximum length = 32 notes
#define SEQ_NOTE_DIVISION 8 //steps per note
float sequence_notes[SEQ_MAX_NOTES * SEQ_NOTE_DIVISION];
int seq_ptr = 0, seq_length;
const char *sequence = "a3a3a3a3 c4a3d4c4 a3a3a3a3 d4c4e4d4 a4g4e4a4 g4e4a4g4 f#4d4a3f#4 d4a3c4b3";
//MusicBox *chord = new MusicBox();
seq_length = MusicBox::get_song_total_melody_notes((char*)sequence);
parse_notes((char*)sequence, sequence_notes, NULL);
#define SEQ_SPREAD 1
spread_notes(sequence_notes, seq_length, SEQ_SPREAD); //spread the sequence 8 times
seq_length *= SEQ_SPREAD;
//FREQ = MIDI_notes_to_freq[data];
DOUBLE=8;
PHASEamt=217;
ENVamt=144;
SET_mode = 1;
DCO_BLOCKS_ACTIVE = 2;//16;
#define FREQ_MULTIPLIER 12
//use_table256 = (uint8_t*)sawtable256;
use_table256 = (uint8_t*)squaretable256;
while(1)
{
//-------------------- DCO block ------------------------------------------
DCO_output[0] = 0;
DCO_output[1] = 0;
for (int b=0; b<DCO_BLOCKS_ACTIVE; b++)
{
phacc[b] += FREQ + (b * DOUBLE);
if (phacc[b] & 0x8000) {
phacc[b] &= 0x7FFF;
otone1[b] += 2;
pdacc[b] += PDmod;
}
if (!otone1[b]) pdacc[b] = 0;
otone2[b] = (pdacc[b] >> 3) & 255;
uint8_t env = (255-otone1[b]);
DCO_output[b%2] += (use_table256[otone2[b]] + use_table256[(otone2[b] + (127 - env)) & 255]);
}
if (!(envtick--)) {
envtick=582;
//--------- Resonant Peak ENV modulation ----------------------------------------
//if(!DCO_mode)
{
PDmod=((RESO*ENVamt)>>8)+PHASEamt;
if (PDmod>255) PDmod=255;
}
}
//-------------------------------------------------------------------------
// send sample to codec
//-------------------------------------------------------------------------
sample_i16 = (int16_t)DCO_output[0];
sample_i16 += echo_buffer[echo_buffer_ptr];
while (!SPI_I2S_GetFlagStatus(CODEC_I2S, SPI_I2S_FLAG_TXE));
SPI_I2S_SendData(CODEC_I2S, sample_i16);
sample_i16 = (int16_t)DCO_output[1];
//wrap in the echo loop
echo_buffer_ptr0++;
if(echo_buffer_ptr0 >= echo_dynamic_loop_length)
{
echo_buffer_ptr0 = 0;
}
echo_buffer_ptr = echo_buffer_ptr0 + 1;
if(echo_buffer_ptr >= echo_dynamic_loop_length)
{
echo_buffer_ptr = 0;
}
//add echo from the loop
sample_i16 += echo_buffer[echo_buffer_ptr];
//store result to echo, the amount defined by a fragment
echo_buffer[echo_buffer_ptr0] = sample_i16 * ECHO_MIXING_GAIN_MUL / ECHO_MIXING_GAIN_DIV;
while (!SPI_I2S_GetFlagStatus(CODEC_I2S, SPI_I2S_FLAG_TXE));
SPI_I2S_SendData(CODEC_I2S, sample_i16);
sampleCounter++;
if (TIMING_BY_SAMPLE_ONE_SECOND_W_CORRECTION)
{
sampleCounter = 0;
seconds++;
}
if (TIMING_BY_SAMPLE_EVERY_10_MS==0) //100Hz
{
if(ADC_process_sensors()==1)
{
ADC_last_result[2] = -ADC_last_result[2];
ADC_last_result[3] = -ADC_last_result[3];
CLEAR_ADC_RESULT_RDY_FLAG;
sensors_loop++;
IR_sensors_LED_indicators(ADC_last_result);
if(SET_mode==0)
{
FREQ = ADC_last_result[0] * 4;
//DOUBLE = ADC_last_result[1] / 8;
DOUBLE = ADC_last_result[1] / 12;
//PHASEamt = ADC_last_result[2] / 8;
PHASEamt = ADC_last_result[2] / 16;
//if(!DCO_mode)
ENVamt = ADC_last_result[3] * 16; /// 4;
//}
//else
//{
// if(ADC_last_result[3] > 200)
// {
// //PDmod = ADC_last_result[3] / 2; /// 4;
// ENVamt = ADC_last_result[3] * 32; /// 4;
// }
// else
// {
// PDmod = 255;
// }
//}
}
else
{
if(BUTTON_U1_ON)
{
FREQ = ADC_last_result[0] * 8;
}
if(BUTTON_U2_ON)
{
DOUBLE = ADC_last_result[1] / 12;
}
if(BUTTON_U3_ON)
{
PHASEamt = ADC_last_result[2] / 16;
}
if(BUTTON_U4_ON)
{
ENVamt = ADC_last_result[3] * 16;
}
}
}
if(BUTTON_SET_ON)
{
if(!button_set_held)
{
if(!SET_mode)
{
LED_SIG_ON;
SET_mode = 1;
button_set_held = 1;
}
else
{
LED_SIG_OFF;
SET_mode = 0;
button_set_held = 1;
}
}
}
else
{
button_set_held = 0;
}
}
//if (TIMING_BY_SAMPLE_EVERY_250_MS==0) //4Hz
if (TIMING_BY_SAMPLE_EVERY_125_MS==0) //8Hz
{
//if(ADC_last_result[0] < SEQUENCER_THRESHOLD)
//{
if(sequence_notes[seq_ptr] > 0)
{
FREQ = sequence_notes[seq_ptr] * FREQ_MULTIPLIER;
}
if (++seq_ptr == seq_length)
{
seq_ptr = 0;
}
//}
}
}
}
void DCO_Synth::v4_play_loop()
//SIGNAL(PWM_INTERRUPT)
{
uint8_t value;
uint16_t output;
// incorporating DuaneB's volatile fix
uint16_t syncPhaseAcc;
volatile uint16_t syncPhaseInc;
uint16_t grainPhaseAcc;
volatile uint16_t grainPhaseInc;
uint16_t grainAmp;
volatile uint8_t grainDecay;
uint16_t grain2PhaseAcc;
volatile uint16_t grain2PhaseInc;
uint16_t grain2Amp;
volatile uint8_t grain2Decay;
int led_status = 0;
while(1)
{
syncPhaseAcc += syncPhaseInc;
if (syncPhaseAcc < syncPhaseInc) {
// Time to start the next grain
grainPhaseAcc = 0;
grainAmp = 0x7fff;
grain2PhaseAcc = 0;
grain2Amp = 0x7fff;
//LED_PORT ^= 1 << LED_BIT; // Faster than using digitalWrite
led_status?LED_SIG_ON:LED_SIG_OFF;
led_status=led_status?0:1;
}
// Increment the phase of the grain oscillators
grainPhaseAcc += grainPhaseInc;
grain2PhaseAcc += grain2PhaseInc;
// Convert phase into a triangle wave
value = (grainPhaseAcc >> 7) & 0xff;
if (grainPhaseAcc & 0x8000) value = ~value;
// Multiply by current grain amplitude to get sample
output = value * (grainAmp >> 8);
// Repeat for second grain
value = (grain2PhaseAcc >> 7) & 0xff;
if (grain2PhaseAcc & 0x8000) value = ~value;
output += value * (grain2Amp >> 8);
// Make the grain amplitudes decay by a factor every sample (exponential decay)
grainAmp -= (grainAmp >> 8) * grainDecay;
grain2Amp -= (grain2Amp >> 8) * grain2Decay;
// Scale output to the available range, clipping if necessary
output >>= 9;
if (output > 255) output = 255;
// Output to PWM (this is faster than using analogWrite)
//PWM_VALUE = output;
//-------------------------------------------------------------------------
// send sample to codec
//-------------------------------------------------------------------------
sample_i16 = (int16_t)output;//[0];
sample_i16 += echo_buffer[echo_buffer_ptr];
while (!SPI_I2S_GetFlagStatus(CODEC_I2S, SPI_I2S_FLAG_TXE));
SPI_I2S_SendData(CODEC_I2S, sample_i16);
sample_i16 = (int16_t)output;//[1];
//wrap in the echo loop
echo_buffer_ptr0++;
if(echo_buffer_ptr0 >= echo_dynamic_loop_length)
{
echo_buffer_ptr0 = 0;
}
echo_buffer_ptr = echo_buffer_ptr0 + 1;
if(echo_buffer_ptr >= echo_dynamic_loop_length)
{
echo_buffer_ptr = 0;
}
//add echo from the loop
sample_i16 += echo_buffer[echo_buffer_ptr];
//store result to echo, the amount defined by a fragment
echo_buffer[echo_buffer_ptr0] = sample_i16 * ECHO_MIXING_GAIN_MUL / ECHO_MIXING_GAIN_DIV;
while (!SPI_I2S_GetFlagStatus(CODEC_I2S, SPI_I2S_FLAG_TXE));
SPI_I2S_SendData(CODEC_I2S, sample_i16);
sampleCounter++;
if (TIMING_BY_SAMPLE_ONE_SECOND_W_CORRECTION)
{
sampleCounter = 0;
seconds++;
}
}
}
#endif
| 26.097641
| 197
| 0.590358
|
shroomist
|
f82d36f3a41917690f648621c7fbd59844900288
| 3,301
|
cpp
|
C++
|
tc 160+/InstantRunoff.cpp
|
ibudiselic/contest-problem-solutions
|
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
|
[
"BSD-2-Clause"
] | 3
|
2015-05-25T06:24:37.000Z
|
2016-09-10T07:58:00.000Z
|
tc 160+/InstantRunoff.cpp
|
ibudiselic/contest-problem-solutions
|
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
|
[
"BSD-2-Clause"
] | null | null | null |
tc 160+/InstantRunoff.cpp
|
ibudiselic/contest-problem-solutions
|
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
|
[
"BSD-2-Clause"
] | 5
|
2015-05-25T06:24:40.000Z
|
2021-08-19T19:22:29.000Z
|
#include <algorithm>
#include <cassert>
#include <cstdio>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <climits>
using namespace std;
class InstantRunoff {
public:
string outcome(string candidates, vector <string> ballots) {
while (candidates.size() > 0) {
vector<int> win(26, 0);
int best = -1;
char who = 0;
for (int i=0; i<(int)ballots.size(); ++i) {
++win[ballots[i][0] - 'A'];
if (best < win[ballots[i][0]-'A']) {
who = ballots[i][0];
best = win[ballots[i][0]-'A'];
}
}
if (best*2 > (int)ballots.size())
return string(1, who);
int worst = INT_MAX;
for (int i=0; i<26; ++i)
if (candidates.find(char('A'+i)) != string::npos)
worst = min(worst, win[i]);
for (int i=0; i<26; ++i)
if (candidates.find(char('A'+i)) != string::npos && win[i]==worst) {
for (int j=0; j<(int)ballots.size(); ++j)
ballots[j].erase(ballots[j].find(char('A'+i)), 1);
candidates.erase(candidates.find(char('A'+i)), 1);
}
}
return string();
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const string &Expected, const string &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { string Arg0 = "ABC"; string Arr1[] = {"ACB", "BCA", "ACB", "BCA", "CBA"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); string Arg2 = "B"; verify_case(0, Arg2, outcome(Arg0, Arg1)); }
void test_case_1() { string Arg0 = "DCBA"; string Arr1[] = {"ACBD", "ACBD", "ACBD", "BCAD", "BCAD", "DBCA", "CBDA"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); string Arg2 = "B"; verify_case(1, Arg2, outcome(Arg0, Arg1)); }
void test_case_2() { string Arg0 = "ACB"; string Arr1[] = {"ACB", "BCA", "ACB", "BCA", "ACB", "BCA", "CBA", "CAB"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); string Arg2 = ""; verify_case(2, Arg2, outcome(Arg0, Arg1)); }
void test_case_3() { string Arg0 = "CAB"; string Arr1[] = {"ACB", "BCA", "ACB", "BCA", "ACB", "BCA", "CAB", "CAB"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); string Arg2 = "A"; verify_case(3, Arg2, outcome(Arg0, Arg1)); }
void test_case_4() { string Arg0 = "Z"; string Arr1[] = {"Z"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); string Arg2 = "Z"; verify_case(4, Arg2, outcome(Arg0, Arg1)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main()
{
InstantRunoff ___test;
___test.run_test(-1);
}
// END CUT HERE
| 45.219178
| 315
| 0.566192
|
ibudiselic
|
f82d52b36f61ff0da4e1bb804899e48f572ec1c3
| 1,199
|
hpp
|
C++
|
win32.cpp/include/win32/high_resolution_clock.hpp
|
fallfromgrace/win32.cpp
|
cab9fbc2e595fb2c9114d0251b04d895185c5fcb
|
[
"MIT"
] | null | null | null |
win32.cpp/include/win32/high_resolution_clock.hpp
|
fallfromgrace/win32.cpp
|
cab9fbc2e595fb2c9114d0251b04d895185c5fcb
|
[
"MIT"
] | null | null | null |
win32.cpp/include/win32/high_resolution_clock.hpp
|
fallfromgrace/win32.cpp
|
cab9fbc2e595fb2c9114d0251b04d895185c5fcb
|
[
"MIT"
] | null | null | null |
#pragma once
#include <chrono>
#include <Windows.h>
#include "more\includes.hpp"
#include "win32\error.hpp"
namespace win32
{
//
class high_resolution_clock
{
public:
typedef uint64_t rep;
typedef std::nano period;
typedef std::chrono::duration<rep, period> duration;
typedef std::chrono::time_point<high_resolution_clock> time_point;
static const bool_t is_steady = true;
//
static inline time_point now()
{
LARGE_INTEGER count;
if (::QueryPerformanceCounter(&count) == FALSE)
throw win32::get_last_error();
return time_point(duration(
count.QuadPart * static_cast<rep>(period::den) / high_resolution_clock::frequency()));
}
// Gets the frequency of the high_resolution_clock
static inline uint64_t frequency()
{
static uint64_t cached_frequency = 0;
if (cached_frequency == 0)
cached_frequency = query_frequency();
return cached_frequency;
}
// Queries the frequency of the high_resolution_clock
static inline uint64_t query_frequency()
{
LARGE_INTEGER frequency;
if (::QueryPerformanceFrequency(&frequency) == FALSE)
throw win32::get_last_error();
return static_cast<uint64_t>(frequency.QuadPart);
}
};
}
| 23.509804
| 90
| 0.723103
|
fallfromgrace
|
f833abf19ec3c0320b53c6030e926fc05814edaa
| 1,041
|
cpp
|
C++
|
problems19dec/snake/3.cpp
|
Gomango999/codebreaker
|
407c4ac7a69c8db52cc7d2a57034cdda243c9134
|
[
"MIT"
] | 1
|
2021-12-11T01:43:27.000Z
|
2021-12-11T01:43:27.000Z
|
problems19dec/snake/3.cpp
|
Gomango999/codebreaker
|
407c4ac7a69c8db52cc7d2a57034cdda243c9134
|
[
"MIT"
] | null | null | null |
problems19dec/snake/3.cpp
|
Gomango999/codebreaker
|
407c4ac7a69c8db52cc7d2a57034cdda243c9134
|
[
"MIT"
] | 1
|
2021-12-15T07:04:29.000Z
|
2021-12-15T07:04:29.000Z
|
// No comment
#include <iostream>
#include <algorithm>
using namespace std;
char makeBeef(char x) {
string snake = "SNAKE";
string cow = "ANGUS";
for(int i = 0; i < 5; i++) {
if(snake[i] == x) {
return cow[i];
}
}
return 'X';
}
int N;
string S;
const int FAIL = -1234;
int _K;
int f(char thing, int start) {
if(start == FAIL || _K == 0) {
return FAIL;
}
int k = _K;
for(int i = start; i < N; i++) {
if(S[i] == thing) {
k--;
}
if(k == 0) {
return i;
}
}
return FAIL;
}
const int NO_SOLN = 0;
int main() {
cin >> N >> S;
transform(begin(S), end(S), begin(S), makeBeef);
int best = NO_SOLN;
int l = 0;
int r = N;
while(l <= r) {
_K = (l+r)/2;
if(f('S', f('U', f('G', f('N', f('A', 0))))) == FAIL) {
r = _K-1;
} else {
l = _K+1;
best = best < _K ? _K : best;
}
}
cout << best << "\n";
return 0;
}
| 17.065574
| 63
| 0.411143
|
Gomango999
|
f83ceabbb354e8ab2cd9ff9f4dbf28f93f9eadb4
| 3,071
|
cpp
|
C++
|
src/io.cpp
|
tguyard/sentry-native
|
e33c68d1d61a65a089a431185584fa304c81c58f
|
[
"MIT"
] | 1
|
2019-11-25T22:33:56.000Z
|
2019-11-25T22:33:56.000Z
|
src/io.cpp
|
detwiler/sentry-native
|
d2035afffcad282a44195cacc0d300de7fe0e36d
|
[
"MIT"
] | null | null | null |
src/io.cpp
|
detwiler/sentry-native
|
d2035afffcad282a44195cacc0d300de7fe0e36d
|
[
"MIT"
] | null | null | null |
#include <cstdlib>
#include "internal.hpp"
#include "io.hpp"
#include "path.hpp"
#ifndef _WIN32
#include <fcntl.h>
#include <unistd.h>
#endif
using namespace sentry;
IoWriter::IoWriter() {
}
IoWriter::~IoWriter() {
}
FileIoWriter::FileIoWriter() : m_buflen(0) {
// on non win32 platforms we only use open/write/close so that
// we can achieve something close to being async safe so we can
// use this class in crashing situations.
#ifdef _WIN32
m_file = nullptr;
#else
m_fd = -1;
#endif
}
FileIoWriter::~FileIoWriter() {
close();
}
bool FileIoWriter::open(const Path &path, const char *mode) {
#ifdef _WIN32
m_file = path.open(mode);
return m_file != nullptr;
#else
int flags = 0;
for (; *mode; mode++) {
switch (*mode) {
case 'r':
flags |= O_RDONLY;
break;
case 'w':
flags |= O_WRONLY | O_CREAT | O_TRUNC;
break;
case 'a':
flags |= O_WRONLY | O_CREAT | O_APPEND;
break;
case 'b':
break;
case '+':
flags |= O_RDWR;
break;
default:;
}
}
m_fd = ::open(path.as_osstr(), flags,
S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH);
return m_fd >= 0;
#endif
}
void FileIoWriter::write(const char *buf, size_t len) {
size_t to_write = len;
while (to_write) {
size_t can_write = std::min(BUF_SIZE - m_buflen, to_write);
memcpy(m_buf + m_buflen, buf, can_write);
m_buflen += can_write;
to_write -= can_write;
buf += can_write;
if (m_buflen == BUF_SIZE) {
flush();
}
}
}
void FileIoWriter::flush() {
#ifdef _WIN32
fwrite(m_buf, 1, m_buflen, m_file);
fflush(m_file);
#else
::write(m_fd, m_buf, m_buflen);
#endif
m_buflen = 0;
}
void FileIoWriter::close() {
flush();
#ifdef _WIN32
fclose(m_file);
#else
::close(m_fd);
#endif
m_buflen = 0;
}
MemoryIoWriter::MemoryIoWriter(size_t bufsize)
: m_terminated(false),
m_buflen(0),
m_bufcap(bufsize),
m_buf((char *)malloc(bufsize)) {
}
MemoryIoWriter::~MemoryIoWriter() {
free(m_buf);
}
void MemoryIoWriter::flush() {
if (!m_terminated) {
write_char(0);
m_buflen -= 1;
m_terminated = true;
}
}
void MemoryIoWriter::write(const char *buf, size_t len) {
size_t size_needed = m_buflen + len;
if (size_needed > m_bufcap) {
size_t new_bufcap = m_bufcap;
while (new_bufcap < size_needed) {
new_bufcap *= 1.3;
}
m_buf = (char *)realloc(m_buf, new_bufcap);
m_bufcap = new_bufcap;
}
memcpy(m_buf + m_buflen, buf, len);
m_buflen += len;
m_terminated = false;
}
char *MemoryIoWriter::take() {
flush();
char *rv = m_buf;
m_buf = nullptr;
return rv;
}
const char *MemoryIoWriter::buf() const {
return m_buf;
}
size_t MemoryIoWriter::len() const {
return m_buflen;
}
| 20.610738
| 67
| 0.565939
|
tguyard
|
f83eebc3951e3b7c9f6af443f0c97b8c68eafbb1
| 4,607
|
cpp
|
C++
|
2022.04.04. Test 2.d.r/2022.04.04. Test 2.d.r/Fraction.cpp
|
whitehet-sex-lman/The-first-course-2021.Cplpl
|
2bd2ad443d9c055fcd0694970d0a2f245b37f962
|
[
"Apache-2.0"
] | null | null | null |
2022.04.04. Test 2.d.r/2022.04.04. Test 2.d.r/Fraction.cpp
|
whitehet-sex-lman/The-first-course-2021.Cplpl
|
2bd2ad443d9c055fcd0694970d0a2f245b37f962
|
[
"Apache-2.0"
] | null | null | null |
2022.04.04. Test 2.d.r/2022.04.04. Test 2.d.r/Fraction.cpp
|
whitehet-sex-lman/The-first-course-2021.Cplpl
|
2bd2ad443d9c055fcd0694970d0a2f245b37f962
|
[
"Apache-2.0"
] | null | null | null |
#include "Fraction.h"
Fraction::Fraction(long long numerator, long long denominator)
{
if (numerator < 0 && denominator > 0 || numerator >= 0 && denominator > 0)
{
this->numerator = numerator;
this->denominator = denominator;
}
else if (numerator < 0 && denominator < 0 || numerator >= 0 && denominator < 0)
{
this->numerator = -numerator;
this->denominator = -denominator;
}
}
Fraction::Fraction(const Fraction& fraction) : numerator(fraction.numerator), denominator(fraction.denominator) {}
Fraction::~Fraction()
{
this->numerator = 0;
this->denominator = 0;
}
Fraction Fraction::absf()
{
if (this->numerator >= 0)
{
return Fraction(this->numerator, this->denominator);
}
else
{
return Fraction(-this->numerator, this->denominator);
}
}
Fraction Fraction::powf(int n)
{
return Fraction(pow(this->numerator, n), pow(this->denominator, n));
}
Fraction Fraction::reverse()
{
return Fraction(this->denominator, this->numerator);
}
Fraction Fraction::operator=(Fraction& fraction)
{
this->numerator = fraction.numerator;
this->denominator = fraction.denominator;
return *this;
}
long long Fraction::nod()
{
long long result = 1;
for (long long i = 1; i < min(abs(this->numerator), abs(this->denominator)); ++i)
{
if (this->numerator / i == 0 and this->denominator / i == 0)
{
result = i;
}
}
return result;
}
bool operator==(Fraction fraction1, Fraction fraction2)
{
if (fraction1.denominator == fraction2.numerator && fraction1.denominator == fraction2.denominator)
{
return true;
}
else
{
return false;
}
}
bool operator<(Fraction fraction1, Fraction fraction2)
{
if (fraction1.numerator * fraction2.denominator < fraction2.numerator * fraction1.denominator)
{
return true;
}
else
{
return false;
}
}
bool operator<=(Fraction fraction1, Fraction fraction2)
{
if (fraction1.numerator * fraction2.denominator <= fraction2.numerator * fraction1.denominator)
{
return true;
}
else
{
return false;
}
}
bool operator>(Fraction fraction1, Fraction fraction2)
{
if (fraction1.numerator * fraction2.denominator > fraction2.numerator * fraction1.denominator)
{
return true;
}
else
{
return false;
}
}
bool operator>=(Fraction fraction1, Fraction fraction2)
{
if (fraction1.numerator * fraction2.denominator >= fraction2.numerator * fraction1.denominator)
{
return true;
}
else
{
return false;
}
}
Fraction operator+(Fraction fraction1, Fraction fraction2)
{
long long nod = Fraction(fraction1.numerator * fraction2.denominator + fraction2.numerator * fraction1.denominator, fraction1.denominator * fraction2.denominator).nod();
return Fraction((fraction1.numerator * fraction2.denominator + fraction2.numerator * fraction1.denominator) / nod, fraction1.denominator * fraction2.denominator / nod);
}
Fraction operator*(Fraction fraction, double n)
{
long long nod = Fraction(fraction.numerator * n, fraction.denominator).nod();
return Fraction(fraction.numerator * n / nod, fraction.denominator / nod);
}
Fraction operator*(double n, Fraction fraction)
{
long long nod = Fraction(fraction.numerator * n, fraction.denominator).nod();
return Fraction(fraction.numerator * n / nod, fraction.denominator / nod);
}
Fraction operator*(Fraction fraction1, Fraction fraction2)
{
long long nod = Fraction(fraction1.numerator * fraction2.numerator, fraction1.denominator * fraction2.denominator).nod();
return Fraction(fraction1.numerator * fraction2.numerator / nod, fraction1.denominator * fraction2.denominator / nod);
}
Fraction operator/(Fraction fraction, double n)
{
long long nod = Fraction(fraction.numerator, fraction.denominator * n).nod();
return Fraction(fraction.numerator / nod, fraction.denominator * n / nod);
}
Fraction operator/(double n, Fraction& fraction)
{
return n * fraction.reverse();
}
Fraction operator/(Fraction fraction1, Fraction fraction2)
{
return fraction1 * fraction2.reverse();
}
Fraction operator-(Fraction fraction1, Fraction fraction2)
{
long long nod = Fraction(fraction1.numerator * fraction2.denominator - fraction2.numerator * fraction1.denominator, fraction1.denominator * fraction2.denominator).nod();
return Fraction((fraction1.numerator * fraction2.denominator - fraction2.numerator * fraction1.denominator) / nod, fraction1.denominator * fraction2.denominator / nod);
}
ostream& operator<<(ostream& stream, Fraction fraction)
{
if (fraction.numerator == 0)
{
stream << 0;
}
else if (fraction.denominator == 1)
{
stream << fraction.numerator;
}
else
{
stream << fraction.numerator << " / " << fraction.denominator;
}
return stream;
}
| 24.247368
| 170
| 0.725418
|
whitehet-sex-lman
|
f8407239587e83ddf553d64c386171ffe45ab521
| 1,650
|
hpp
|
C++
|
src/cpa/cpa.hpp
|
DfX-NYUAD/CPA
|
4b1364e7b0eb7d0580b4e90e5a05a109551ed49d
|
[
"MIT"
] | null | null | null |
src/cpa/cpa.hpp
|
DfX-NYUAD/CPA
|
4b1364e7b0eb7d0580b4e90e5a05a109551ed49d
|
[
"MIT"
] | null | null | null |
src/cpa/cpa.hpp
|
DfX-NYUAD/CPA
|
4b1364e7b0eb7d0580b4e90e5a05a109551ed49d
|
[
"MIT"
] | null | null | null |
/* Copyright (c) 2013 Tescase
*
* 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.
*/
//
// This file contains the serial and parallel
// CPA algorithms
//
#ifndef SCA_CPA_CPA_H
#define SCA_CPA_CPA_H
#include <string>
namespace cpa
{
// The serial CPU based CPA function
void cpa(std::string data_path, std::string ct_path, std::string key_path, std::string perm_path, bool candidates, int permutations, int steps, int steps_start, int steps_stop, float rate_stop, bool verbose, bool key_expansion);
// The parallel GPU based CPA function
void pcpa(std::string data_path, std::string ct_path);
} //end namespace
#endif
| 37.5
| 228
| 0.762424
|
DfX-NYUAD
|
f84549bb0abe8eca74e63b64cbcad69b6498552b
| 2,553
|
cpp
|
C++
|
assec-renderer/platform/directx12/directx12_command_list.cpp
|
TeamVistic/assec-renderer
|
5c6fc9a46fc3f6302471a22bfd2bdf2942b794db
|
[
"Apache-2.0"
] | null | null | null |
assec-renderer/platform/directx12/directx12_command_list.cpp
|
TeamVistic/assec-renderer
|
5c6fc9a46fc3f6302471a22bfd2bdf2942b794db
|
[
"Apache-2.0"
] | null | null | null |
assec-renderer/platform/directx12/directx12_command_list.cpp
|
TeamVistic/assec-renderer
|
5c6fc9a46fc3f6302471a22bfd2bdf2942b794db
|
[
"Apache-2.0"
] | null | null | null |
#include "pch.h"
#include "directx12_command_list.h"
namespace assec::renderer
{
ComPtr<ID3D12GraphicsCommandList2> create_command_list(ComPtr<ID3D12Device2> device,
ComPtr<ID3D12CommandAllocator> command_allocator, D3D12_COMMAND_LIST_TYPE type)
{
ComPtr<ID3D12GraphicsCommandList2> result;
throw_if_failed(device->CreateCommandList(0, type, command_allocator.Get(), nullptr, IID_PPV_ARGS(&result)));
return result;
}
directx12_command_list::directx12_command_list(ComPtr<ID3D12Device2> device, ComPtr<ID3D12CommandAllocator> command_allocator, D3D12_COMMAND_LIST_TYPE type)
: m_native(create_command_list(device, command_allocator, type)) {}
ComPtr<ID3D12GraphicsCommandList2> directx12_command_list::native() const { return this->m_native; }
ComPtr<ID3D12CommandAllocator> directx12_command_list::command_allocator() const
{
ID3D12CommandAllocator* command_allocator;
UINT size = sizeof(command_allocator);
throw_if_failed(this->native()->GetPrivateData(__uuidof(ID3D12CommandAllocator), &size, &command_allocator));
return command_allocator;
}
void directx12_command_list::update_subresources(directx12_resource& destination, directx12_resource& intermediate,
uint32_t offset, uint32_t first, std::vector<D3D12_SUBRESOURCE_DATA> subresources) const
{
UpdateSubresources(this->m_native.Get(),
destination.native().Get(), intermediate.native().Get(),
offset, first, subresources.size(), subresources.data());
}
void directx12_command_list::clear_render_target_view(const directx12_resource& texture, CD3DX12_CPU_DESCRIPTOR_HANDLE handle, resource_state_tracker& resource_tracker, const glm::vec4 color) const
{
if (resource_tracker.retreive_state(texture) != D3D12_RESOURCE_STATE_RENDER_TARGET)
{
auto barrier = resource_tracker.transition_barrier(texture, D3D12_RESOURCE_STATE_RENDER_TARGET);
this->native()->ResourceBarrier(1, &barrier);
}
this->native()->ClearRenderTargetView(handle, glm::value_ptr(color), 0, nullptr);
}
void directx12_command_list::clear_depth_target_view(const directx12_resource& texture, CD3DX12_CPU_DESCRIPTOR_HANDLE handle, resource_state_tracker& resource_tracker, D3D12_CLEAR_FLAGS flags, float depth, uint8_t stencil) const
{
if (resource_tracker.retreive_state(texture) != D3D12_RESOURCE_STATE_DEPTH_WRITE)
{
auto barrier = resource_tracker.transition_barrier(texture, D3D12_RESOURCE_STATE_DEPTH_WRITE);
this->native()->ResourceBarrier(1, &barrier);
}
this->native()->ClearDepthStencilView(handle, flags, depth, stencil, 0, nullptr);
}
}
| 48.169811
| 229
| 0.806894
|
TeamVistic
|
f845f3416589d1d48c63c61cae435a1759886430
| 1,983
|
cpp
|
C++
|
test/xsimd_hyperbolic_test.cpp
|
ukoethe/xsimd
|
c15e4da30d6777863d994750d4c3a61b32f2de95
|
[
"BSD-3-Clause"
] | null | null | null |
test/xsimd_hyperbolic_test.cpp
|
ukoethe/xsimd
|
c15e4da30d6777863d994750d4c3a61b32f2de95
|
[
"BSD-3-Clause"
] | null | null | null |
test/xsimd_hyperbolic_test.cpp
|
ukoethe/xsimd
|
c15e4da30d6777863d994750d4c3a61b32f2de95
|
[
"BSD-3-Clause"
] | 1
|
2020-08-19T01:15:47.000Z
|
2020-08-19T01:15:47.000Z
|
/***************************************************************************
* Copyright (c) 2016, Johan Mabille and Sylvain Corlay *
* *
* Distributed under the terms of the BSD 3-Clause License. *
* *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/
#include <fstream>
#include <iostream>
#include "gtest/gtest.h"
#include "xsimd/math/xsimd_hyperbolic.hpp"
#include "xsimd/memory/xsimd_aligned_allocator.hpp"
#include "xsimd/types/xsimd_types_include.hpp"
#include "xsimd_hyperbolic_test.hpp"
namespace xsimd
{
template <class T, size_t N, size_t A>
bool test_hyperbolic(std::ostream& out, const std::string& name)
{
simd_hyperbolic_tester<T, N, A> tester(name);
return test_simd_hyperbolic(out, tester);
}
}
#if XSIMD_X86_INSTR_SET >= XSIMD_X86_SSE2_VERSION
TEST(xsimd, sse_float_hyperbolic)
{
std::ofstream out("log/sse_float_hyperbolic.log", std::ios_base::out);
bool res = xsimd::test_hyperbolic<float, 4, 16>(out, "sse float");
EXPECT_TRUE(res);
}
TEST(xsimd, sse_double_hyperbolic)
{
std::ofstream out("log/sse_double_hyperbolic.log", std::ios_base::out);
bool res = xsimd::test_hyperbolic<double, 2, 16>(out, "sse double");
EXPECT_TRUE(res);
}
#endif
#if XSIMD_X86_INSTR_SET >= XSIMD_X86_AVX_VERSION
TEST(xsimd, avx_float_hyperbolic)
{
std::ofstream out("log/avx_float_hyperbolic.log", std::ios_base::out);
bool res = xsimd::test_hyperbolic<float, 8, 32>(out, "avx float");
EXPECT_TRUE(res);
}
TEST(xsimd, avx_double_hyperbolic)
{
std::ofstream out("log/avx_double_hyperbolic.log", std::ios_base::out);
bool res = xsimd::test_hyperbolic<double, 4, 32>(out, "avx double");
EXPECT_TRUE(res);
}
#endif
| 33.610169
| 77
| 0.595058
|
ukoethe
|
f848bacda619b0fafbb669632a9720d64f2df744
| 1,677
|
cpp
|
C++
|
modelConvert/source/main.cpp
|
sormo/simpleSDL
|
79a830a013f911c4670c86ccf68bd068a887670d
|
[
"MIT"
] | null | null | null |
modelConvert/source/main.cpp
|
sormo/simpleSDL
|
79a830a013f911c4670c86ccf68bd068a887670d
|
[
"MIT"
] | null | null | null |
modelConvert/source/main.cpp
|
sormo/simpleSDL
|
79a830a013f911c4670c86ccf68bd068a887670d
|
[
"MIT"
] | null | null | null |
#include "ModelLoader.h"
#include "ModelChecker.h"
#include <iostream>
#include <filesystem>
#include <fstream>
#include <string>
bool SaveModel(const ModelData::ModelT * model, const std::string & path)
{
flatbuffers::FlatBufferBuilder builder(1024);
auto offset = ModelData::CreateModel(builder, model);
builder.Finish(offset);
std::ofstream result(path.c_str(), std::ios_base::binary);
if (!result)
{
std::cout << "Error opening result file " << path.c_str() << "\n\n";
return false;
}
result.write((const char*)builder.GetBufferPointer(), builder.GetSize());
std::wcout << L"Success: " << path.c_str() << L"\n\n";
return true;
}
int main(int32_t argc, char * argv[])
{
for (int32_t i = 1; i < argc; ++i)
{
std::cout << "Processing: " << argv[i] << std::endl;
std::filesystem::path path(argv[i]);
if (path.extension() == ".model")
{
std::ifstream file(argv[i], std::ios::binary | std::ios::ate);
size_t fileSize = (size_t)file.tellg();
file.seekg(std::ios::beg);
std::vector<char> fileData(fileSize);
file.read(fileData.data(), fileSize);
auto data = ModelData::UnPackModel(fileData.data());
if (CheckModel(*data))
SaveModel(&(*data), path.string());
}
else
{
auto data = LoadModel(argv[i]);
if (!data)
{
std::cout << "Error loading!\n\n";
continue;
}
path.replace_extension("model");
SaveModel(&(*data), path.string());
}
}
}
| 26.619048
| 77
| 0.539058
|
sormo
|
f849d5baf154313e3e0f62b8751f8f8cb711d0b5
| 6,841
|
cpp
|
C++
|
caffe/src/caffe/test/test_clustering_loss_layer.cpp
|
blitzingeagle/DeepEmbeddedClustering
|
cbc648fc9271f74c3bb257f57f0f78e1a1a66459
|
[
"MIT"
] | 408
|
2015-11-19T21:50:16.000Z
|
2022-03-22T08:17:26.000Z
|
caffe/src/caffe/test/test_clustering_loss_layer.cpp
|
blitzingeagle/DeepEmbeddedClustering
|
cbc648fc9271f74c3bb257f57f0f78e1a1a66459
|
[
"MIT"
] | 29
|
2016-05-18T10:24:00.000Z
|
2021-09-26T21:43:46.000Z
|
caffe/src/caffe/test/test_clustering_loss_layer.cpp
|
blitzingeagle/DeepEmbeddedClustering
|
cbc648fc9271f74c3bb257f57f0f78e1a1a66459
|
[
"MIT"
] | 152
|
2015-11-24T17:30:36.000Z
|
2021-11-11T07:17:03.000Z
|
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <vector>
#include "gtest/gtest.h"
#include "caffe/blob.hpp"
#include "caffe/common.hpp"
#include "caffe/filler.hpp"
#include "caffe/vision_layers.hpp"
#include "caffe/test/test_caffe_main.hpp"
#include "caffe/test/test_gradient_check_util.hpp"
namespace caffe {
const int dim = 32;
template <typename TypeParam>
class ClusteringLossLayerTest : public MultiDeviceTest<TypeParam> {
typedef typename TypeParam::Dtype Dtype;
protected:
ClusteringLossLayerTest()
: blob_bottom_data_(new Blob<Dtype>(dim, 1, 1, dim)),
blob_bottom_label_(new Blob<Dtype>(dim, 1, 1, 1)),
blob_top_loss_(new Blob<Dtype>()),
blob_top_std_(new Blob<Dtype>()),
blob_top_ind_(new Blob<Dtype>()),
blob_top_dist_(new Blob<Dtype>()) {
// fill the values
FillerParameter filler_param;
filler_param.set_value(0.0005);
ConstantFiller<Dtype> filler(filler_param);
filler.Fill(this->blob_bottom_data_);
Dtype *data = this->blob_bottom_data_->mutable_cpu_data();
for (int i = 0; i < dim; i++) {
for (int j = 0; j < dim; j++) {
data[i*dim + j] *= j;
}
data[i*dim + i] += Dtype(1.0);
}
Dtype *cpu_data = this->blob_bottom_label_->mutable_cpu_data();
for (int i = 0; i < dim; i++) {
if (i < dim/2)
cpu_data[i] = Dtype(1);
else
cpu_data[i] = Dtype(0);
}
blob_bottom_vec_.push_back(blob_bottom_data_);
blob_bottom_vec_.push_back(blob_bottom_label_);
blob_top_vec_.push_back(blob_top_loss_);
blob_top_vec_.push_back(blob_top_std_);
blob_top_vec_.push_back(blob_top_ind_);
blob_top_vec_.push_back(blob_top_dist_);
}
virtual ~ClusteringLossLayerTest() {
delete blob_bottom_data_;
delete blob_bottom_label_;
delete blob_top_loss_;
delete blob_top_ind_;
delete blob_top_std_;
delete blob_top_dist_;
}
void TestForward() {
// Get the loss without a specified objective weight -- should be
// equivalent to explicitly specifiying a weight of 1.
LayerParameter layer_param;
layer_param.mutable_clustering_loss_param()->set_margin(10);
layer_param.mutable_clustering_loss_param()->set_num_center(dim);
ClusteringLossLayer<Dtype> layer_weight_1(layer_param);
layer_weight_1.SetUp(this->blob_bottom_vec_, &this->blob_top_vec_);
layer_weight_1.Forward(this->blob_bottom_vec_, &this->blob_top_vec_);
FillerParameter filler_param;
filler_param.set_value(-0.0005);
ConstantFiller<Dtype> filler2(filler_param);
filler2.Fill(layer_weight_1.blobs()[0].get());
Dtype *center = layer_weight_1.blobs()[0]->mutable_cpu_data();
for (int i = 0; i < dim; i++) {
for (int j = 0; j < dim; j++) {
center[j*dim + i] *= j;
}
center[i*dim + i] += Dtype(1.0);
}
const Dtype loss_weight_1 =
layer_weight_1.Forward(this->blob_bottom_vec_, &this->blob_top_vec_);
// Get the loss again with a different objective weight; check that it is
// scaled appropriately.
const Dtype kLossWeight = 3.7;
LayerParameter layer_param2;
layer_param2.mutable_clustering_loss_param()->set_margin(10);
layer_param2.mutable_clustering_loss_param()->set_num_center(dim);
layer_param2.add_loss_weight(kLossWeight);
ClusteringLossLayer<Dtype> layer_weight_2(layer_param2);
layer_weight_2.SetUp(this->blob_bottom_vec_, &this->blob_top_vec_);
layer_weight_2.Forward(this->blob_bottom_vec_, &this->blob_top_vec_);
filler2.Fill(layer_weight_2.blobs()[0].get());
center = layer_weight_2.blobs()[0]->mutable_cpu_data();
for (int i = 0; i < dim; i++) {
for (int j = 0; j < dim; j++) {
center[j*dim + i] *= j;
}
center[i*dim + i] += Dtype(1.0);
}
const Dtype loss_weight_2 =
layer_weight_2.Forward(this->blob_bottom_vec_, &this->blob_top_vec_);
const Dtype kErrorMargin = 1e-5;
EXPECT_NEAR(loss_weight_1 * kLossWeight, loss_weight_2, kErrorMargin);
// Make sure the loss is non-trivial.
const Dtype kNonTrivialAbsThresh = 1e-1;
EXPECT_GE(fabs(loss_weight_1), kNonTrivialAbsThresh);
int m = dim, n = layer_param.clustering_loss_param().num_center(), p = dim;
Blob<Dtype> *distance = layer_weight_1.distance();
const Dtype *cpu_data = blob_bottom_data_->cpu_data();
const Dtype *cpu_dist = distance->cpu_data();
const Dtype *cpu_center = layer_weight_1.blobs()[0]->cpu_data();
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
Dtype acc = Dtype(0);
for (int k = 0; k < p; ++k) {
acc += (cpu_data[i*p + k] - cpu_center[k*n + j])*(cpu_data[i*p + k] - cpu_center[k*n + j]);
}
EXPECT_NEAR(std::sqrt(acc/p), cpu_dist[i*n + j], kErrorMargin);
}
}
/*
const Dtype *cpu_ind = blob_top_ind_->cpu_data();
for (int i = 0; i < m; i++)
EXPECT_EQ(cpu_ind[i], i);
EXPECT_NEAR(blob_top_std_->cpu_data()[0], Dtype(0), kErrorMargin);*/
}
Blob<Dtype>* const blob_bottom_data_;
Blob<Dtype>* const blob_bottom_label_;
Blob<Dtype>* const blob_top_loss_;
Blob<Dtype>* const blob_top_std_;
Blob<Dtype>* const blob_top_ind_;
Blob<Dtype>* const blob_top_dist_;
vector<Blob<Dtype>*> blob_bottom_vec_;
vector<Blob<Dtype>*> blob_top_vec_;
};
TYPED_TEST_CASE(ClusteringLossLayerTest, TestDtypesAndDevices);
TYPED_TEST(ClusteringLossLayerTest, TestForward) {
this->TestForward();
}
TYPED_TEST(ClusteringLossLayerTest, TestGradient) {
typedef typename TypeParam::Dtype Dtype;
LayerParameter layer_param;
const Dtype kLossWeight = 1.0;
layer_param.add_loss_weight(kLossWeight);
layer_param.mutable_clustering_loss_param()->set_margin(10);
layer_param.mutable_clustering_loss_param()->set_num_center(dim);
layer_param.mutable_clustering_loss_param()->set_lambda(0.5);
ClusteringLossLayer<Dtype> layer(layer_param);
layer.SetUp(this->blob_bottom_vec_, &this->blob_top_vec_);
layer.Forward(this->blob_bottom_vec_, &this->blob_top_vec_);
FillerParameter filler_param;
filler_param.set_value(0.0005);
ConstantFiller<Dtype> filler(filler_param);
filler.Fill(this->blob_bottom_data_);
filler_param.set_value(-0.0005);
ConstantFiller<Dtype> filler2(filler_param);
filler2.Fill(layer.blobs()[0].get());
Dtype *center = layer.blobs()[0]->mutable_cpu_data();
Dtype *data = this->blob_bottom_data_->mutable_cpu_data();
for (int i = 0; i < dim; i++) {
for (int j = 0; j < dim; j++) {
data[i*dim + j] *= j;
center[j*dim + i] *= j;
}
center[i*dim + i] += Dtype(1.0);
data[i*dim + i] += Dtype(1.0);
}
GradientChecker<Dtype> checker(1e-1, 1e-10, 1701);
checker.CheckGradientSingle(&layer, &(this->blob_bottom_vec_),
&(this->blob_top_vec_), 0, 0, 0);
}
} // namespace caffe
| 33.866337
| 101
| 0.679871
|
blitzingeagle
|
f850ebcad2e04127a5937d7d506d9584d0348aed
| 15,526
|
hpp
|
C++
|
core/src/cogs/collections/avltree.hpp
|
cogmine/cogs
|
ef1c369a36a4f811704e0ced0493c3a6f8eca821
|
[
"MIT"
] | 5
|
2019-02-08T15:59:14.000Z
|
2022-01-22T19:12:33.000Z
|
core/src/cogs/collections/avltree.hpp
|
cogmine/cogs
|
ef1c369a36a4f811704e0ced0493c3a6f8eca821
|
[
"MIT"
] | 1
|
2019-12-03T03:11:34.000Z
|
2019-12-03T03:11:34.000Z
|
core/src/cogs/collections/avltree.hpp
|
cogmine/cogs
|
ef1c369a36a4f811704e0ced0493c3a6f8eca821
|
[
"MIT"
] | null | null | null |
//
// Copyright (C) 2000-2020 - Colen M. Garoutte-Carson <colen at cogmine.com>, Cog Mine LLC
//
// Status: Good
#ifndef COGS_HEADER_COLLECTION_AVLTREE
#define COGS_HEADER_COLLECTION_AVLTREE
#include "cogs/collections/btree.hpp"
#include "cogs/operators.hpp"
#include "cogs/mem/ptr.hpp"
namespace cogs {
/// @defgroup BinaryTrees Binary Trees
/// @{
/// @ingroup Collections
/// @brief Binary Tree classes
/// @}
/// @ingroup BinaryTrees
/// @brief Base classes for (intrusive) nodes of avltree.
/// @tparam derived_t Derived type of this class. Allows links to be returned as references to the derived type without requiring a cast.
/// If void is specified, links will point to avltree_node_t<void, ref_type, link_accessor>. Default: void
/// @tparam ref_type Reference type to use for links. Default: ptr
/// @tparam link_accessor Helper type providing functions to get and set links. Default: default_tlink_accessor<derived_t, ref_type>
template <class derived_t = void, template <typename> class ref_type = ptr, class link_accessor = default_tlink_accessor<derived_t, ref_type> >
class avltree_node_t : public tlink_t<derived_t, ref_type, link_accessor>
{
private:
typedef avltree_node_t<derived_t, ref_type, link_accessor> this_t;
typedef tlink_t<derived_t, ref_type, link_accessor> base_t;
int m_factor;
avltree_node_t(const this_t& t) = delete;
this_t& operator=(const this_t& t) = delete;
public:
avltree_node_t()
{ }
template <typename P, typename L, typename R>
avltree_node_t(int f, P&& p, L&& l, R&& r)
: base_t(std::forward<P>(p), std::forward<L>(l), std::forward<R>(r)),
m_factor(f)
{ }
avltree_node_t(this_t&& t)
: base_t(std::move(t)),
m_factor(t.m_factor)
{ }
this_t& operator=(this_t&& t)
{
base_t::operator=(std::move(t));
m_factor = t.m_factor;
return *this;
}
/// @brief Gets the AVL factor value of this node
/// @return The AVL factor value of this node
int get_factor() const { return m_factor; }
/// @brief Sets the AVL factor value of this node
/// @param f The value to set as the AVL factor of this node
void set_factor(int f) { m_factor = f; }
};
template <template <typename> class ref_type, class link_accessor>
class avltree_node_t<void, ref_type, link_accessor> : public tlink_t<avltree_node_t<void, ref_type>, ref_type, link_accessor>
{
private:
typedef avltree_node_t<void, ref_type, link_accessor> this_t;
typedef tlink_t<avltree_node_t<void, ref_type>, ref_type, link_accessor> base_t;
int m_factor;
avltree_node_t(const this_t& t) = delete;
this_t& operator=(const this_t& t) = delete;
public:
avltree_node_t()
{ }
template <typename P, typename L, typename R>
avltree_node_t(int f, P&& p, L&& l, R&& r)
: base_t(std::forward<P>(p), std::forward<L>(l), std::forward<R>(r)),
m_factor(f)
{ }
avltree_node_t(this_t&& t)
: base_t(std::move(t)),
m_factor(t.m_factor)
{ }
this_t& operator=(this_t&& t)
{
base_t::operator=(std::move(t));
m_factor = t.m_factor;
return *this;
}
int get_factor() const { return m_factor; }
void set_factor(int f) { m_factor = f; }
};
/// @brief An alias to avltree_node_t<void,ptr>
typedef avltree_node_t<void,ptr> avltree_node;
/// @ingroup BinaryTrees
/// @brief An intrusive AVL ("Adelson-Velsky-Landis") binary tree.
///
/// derived_node_t must be derived from avltree_node_t, and include the equivalent of the following member function:
/// @code{.cpp}
/// const key_t& get_key() const;
/// @endcode
/// or:
/// @code{.cpp}
/// key_t get_key() const;
/// @endcode
/// @tparam key_t The key type to contain
/// @tparam derived_node_t A class derived from the intrusive node base, avltree_node_t.
/// @tparam comparator_t A static comparator class used to compare keys. Default: default_comparator
/// @tparam ref_type Reference type to use for links. Default: ptr
template <typename key_t, class derived_node_t, class comparator_t = default_comparator, template <typename> class ref_type = ptr>
class avltree : public sorted_btree<key_t, derived_node_t, comparator_t, ref_type>
{
public:
typedef key_t key_type;
/// @brief Alias to this type.
typedef avltree<key_t, derived_node_t, comparator_t, ref_type> this_t;
/// @brief Alias to the node type.
typedef derived_node_t node_t;
/// @brief The node reference type
typedef ref_type<node_t> ref_t;
private:
typedef sorted_btree<key_t, derived_node_t, comparator_t, ref_type> base_t;
avltree(const this_t&) = delete;
this_t& operator=(const this_t&) = delete;
// rebalance balances and repaints the tree after an insert or remove.
//
// - When inserting, the inserted node is passed as n and will be at max depth (no children,
// and factor should already be set to zero). parent and isRightChild are needed for
// parity with removal (determined automatically by rebalance_after_insert()).
//
// - When removing a node, the node will always be at the bottom of the tree, and will have
// 0 or 1 children. If there was a child moved into it's place, it is passed in n, otherwise
// n is null. Since the tree was previously balanced, we know that n has no children and should
// already have a zero factor. The parent of the removed node (and now of n, if present) is passed in parent.
// isRightChild is passed in to indicate which side of the parent node the removed node had been on
// (since it may be null now, and cannot be automatically determined).
//
template <bool isInsert>
void rebalance(const ref_t& nIn, const ref_t& parentIn, bool isRightChildIn)
{
if (!parentIn)
return;
bool isRightChild = isRightChildIn;
ref_t n = nIn;
ref_t parent = parentIn;
ref_t parentParent;
ref_t child;
typename ref_t::locked_t lockedRef;
typename ref_t::locked_t lockedParent;
typename ref_t::locked_t lockedChild;
if (isInsert) // if (!!n)
lockedRef = n;
lockedParent = parent;
parentParent = lockedParent->get_parent_link();
int childFactor = 0;
int factor = 0;
for (;;)
{
const int side_convert[2] = { -1, 1 };
const int parentFactor = lockedParent->get_factor();
const int side = side_convert[isRightChild ^ !isInsert];
const int nSide = -side;
if (parentFactor == side) // If the parent has a factor that indicates it's lopsided to the other side.
{
int newFactor[2]; // index 0 is newFactor, index 1 is newParentFactor
ref_t* localRoot;
if (!isInsert) // figure out new n. When removing and rotating, we need to use the excess node on the other side as N.
{
n = lockedParent->get_child_link(!isRightChild);
lockedRef = n;
factor = lockedRef->get_factor();
}
bool direction = (isInsert == isRightChild);
if (factor == nSide) // If inverted factors, double rotate.
{
if (!isInsert) // Figure out new child, since we wont already know it when inserting.
{
child = lockedRef->get_child_link(isRightChild);
lockedChild = child;
childFactor = lockedChild->get_factor();
}
//balancing_double_rotate();
// Fix up parents
lockedChild->set_parent_link(parentParent);
lockedRef->set_parent_link(child);
lockedParent->set_parent_link(child);
ref_t childChild1 = lockedChild->get_child_link(direction);
if (!!childChild1)
{
typename ref_t::locked_t lockedChildChild1 = childChild1;
lockedChildChild1->set_parent_link(n);
}
ref_t childChild2 = lockedChild->get_child_link(!direction);
if (!!childChild2)
{
typename ref_t::locked_t lockedChildChild2 = childChild2;
lockedChildChild2->set_parent_link(parent);
}
// fix up children
lockedRef->set_child_link(!direction, childChild1);
lockedParent->set_child_link(direction, childChild2);
lockedChild->set_child_link(direction, n);
lockedChild->set_child_link(!direction, parent);
// fixup factors
newFactor[0] = newFactor[1] = 0;
if (!!childFactor)
{
lockedChild->set_factor(0);
newFactor[(childFactor == side)] = -childFactor;
}
localRoot = &child;
}
else // single rotate
{
if (!isInsert)
{
child = lockedRef->get_child_link(direction);
lockedChild = child;
}
//balancing_single_rotate();
// Fix up parents
const ref_t& otherChild = lockedRef->get_child_link(!direction);
lockedParent->set_parent_link(n);
lockedRef->set_parent_link(parentParent);
if (!!otherChild)
{
typename ref_t::locked_t lockedOtherChild = otherChild;
lockedOtherChild->set_parent_link(parent);
}
// fix up children
lockedParent->set_child_link(direction, otherChild);
lockedRef->set_child_link(!direction, parent); // set n's child last, so as not to stomp on otherChild ref
// fixup factors
newFactor[0] = factor - side;
newFactor[1] = -(newFactor[0]);
localRoot = &n;
}
lockedRef->set_factor(newFactor[0]);
lockedParent->set_factor(newFactor[1]);
// tree parent fixup
if (parent == get_root())
{
set_root(*localRoot);
break;
}
lockedParent = parentParent; // Moving lockedParentParent into lockedParent
isRightChild = (lockedParent->get_right_link() == parent);
lockedParent->set_child_link(isRightChild, *localRoot);
if (isInsert) // If inserting, a single or double rotate means we won't need to pass anything up.
break;
if (parentFactor == newFactor[1])
break;
// If removing, we only need to pass up valid values for parent (and lockedParent), and parentParent. N and child are computed
parent = parentParent;
parentParent = lockedParent->get_parent_link();
}
else
{
int newParentFactor = parentFactor + side;
lockedParent->set_factor(newParentFactor);
if (parent == get_root())
break;
if (isInsert) // If Inserting, and no need to rotate, we stop if just changed the factor TO 0.
{
if (newParentFactor == 0) //if (parentFactor == nSide)
break;
}
else // If removing, we stop if we've change a factor FROM 0.
{
if (parentFactor == 0) // if (!parentFactor)
break;
}
child = n;
lockedChild = lockedRef;
childFactor = factor;
n = parent;
lockedRef = lockedParent;
factor = newParentFactor;
parent = parentParent;
lockedParent = parent;
parentParent = lockedParent->get_parent_link();
isRightChild = (n == lockedParent->get_right_link());
}
}
}
ref_t insert(const ref_t& n, sorted_btree_insert_mode insertMode, const ref_t& hint)
{
bool wasEmpty = is_empty();
typename ref_t::locked_t lockedRef = n;
ref_t existing = base_t::insert(n, insertMode, hint);
if (!!existing)
{
if (insertMode == sorted_btree_insert_mode::replace)
{
typename ref_t::locked_t lockedExisting = existing;
lockedRef->set_factor(lockedExisting->get_factor());
}
}
else
{
lockedRef->set_factor(0);
if (!wasEmpty)
{
ref_t parent = lockedRef->get_parent_link();
typename ref_t::locked_t lockedParent = parent;
bool isRightChild = (n == lockedParent->get_right_link());
rebalance<true>(n, parent, isRightChild);
}
}
return existing;
}
const ref_t& get_root() const { return base_t::get_root(); }
void set_root(const ref_t& r) { base_t::set_root(r); }
public:
avltree()
{ }
avltree(this_t&& t)
: base_t(std::move(t))
{ }
this_t& operator=(this_t&& t)
{
base_t::operator=(std::move(t));
return *this;
}
/// @{
/// @brief Tests if the tree is empty
/// @return True if the tree is empty
bool is_empty() const { return base_t::is_empty(); }
/// @}
/// @{
/// @brief Clears the root, leftmost and rightmost values maintained by the tree. Does not delete any elements.
void clear() { base_t::clear(); }
/// @}
/// @{
/// @brief Get the first in-order node
/// @return The first in-order node
const ref_t& get_first() const { return base_t::get_first(); }
/// @}
/// @{
/// @brief Get the last in-order node
/// @return The last in-order node
const ref_t& get_last() const { return base_t::get_last(); }
/// @}
/// @{
/// @brief Insert a node, allowing duplicates
/// @param n Node to insert
/// @param hint If set, must be the result of a prior call to one of the 'last_equal' or
/// 'nearest_greater' find() functions passed the value being inserted. This is useful
/// if additional work is needed before insert, only if an existing match is or is not found.
/// @return A reference to an equal node in the case of collision, or an empty node if no collision.
ref_t insert_multi(const ref_t& n, const ref_t& hint = ref_t()) { return insert(n, sorted_btree_insert_mode::multi, hint); }
/// @}
/// @{
/// @brief Insert a node, replacing a duplicate
/// @param n Node to insert
/// @param hint If set, must be the result of a prior call to one of the 'last_equal' or
/// 'nearest_greater' find() functions passed the value being inserted. This is useful
/// if additional work is needed before insert, only if an existing match is or is not found.
/// @return A reference to the replaced node, or an empty node if no collision.
ref_t insert_replace(const ref_t& n, const ref_t& hint = ref_t()) { return insert(n, sorted_btree_insert_mode::replace, hint); }
/// @}
/// @{
/// @brief Insert a node, if an equal node is not already present
/// @param n Node to insert
/// @param hint If set, must be the result of a prior call to one of the 'last_equal' or
/// 'nearest_greater' find() functions passed the value being inserted. This is useful
/// if additional work is needed before insert, only if an existing match is or is not found.
/// @return A reference to an equal node in the case of collision, or an empty node if no collision.
ref_t insert_unique(const ref_t& n, const ref_t& hint = ref_t()) { return insert(n, sorted_btree_insert_mode::unique, hint); }
/// @}
/// @{
/// @brief Remove a node
void remove(const ref_t& n)
{
ref_t liftedChild;
ref_t swappedWith;
typename ref_t::locked_t lockedRef = n;
const int factor = lockedRef->get_factor();
bool wasRightChild = base_t::balance_remove(n, swappedWith, liftedChild, (factor == 1));
if (!!get_root())
{
for (;;)
{
ref_t parent = lockedRef->get_parent_link();
typename ref_t::locked_t lockedSwappedWith;
if (!swappedWith) // If no swap occured, we know the removed node has 0 or 1 children.
{ // Go ahead and set its parent's factor accordingly, and enter rebalance one level up.
if (!parent) // if the root is being removed, we know it's now empty, or has just 1 element.
{
if (!!liftedChild) // If just 1 element, set its factor to 0 and clear the parent
{
typename ref_t::locked_t lockedLiftedChild = liftedChild;
lockedLiftedChild->set_factor(0);
ref_t emptyRef;
lockedLiftedChild->set_parent_link(emptyRef);
}
break;
}
}
else
{
lockedSwappedWith = swappedWith;
lockedSwappedWith->set_factor(factor); // If a swap occured, trade factors with it.
}
rebalance<false>(liftedChild, parent, wasRightChild);
break;
}
}
}
/// @}
/// @{
/// @brief Swaps the contents of this tree with another.
/// @param wth The tree to swap with.
void swap(this_t& wth) { base_t::swap(wth); }
/// @}
this_t exchange(this_t&& src)
{
this_t tmp(std::move(src));
swap(tmp);
return tmp;
}
void exchange(this_t&& src, this_t& rtn)
{
rtn = std::move(src);
swap(rtn);
}
};
}
#endif
| 30.99002
| 143
| 0.682983
|
cogmine
|
f855776911f2d7b2b129b13e2bb71c99377ad8f0
| 2,251
|
cpp
|
C++
|
AI/Src/MessageDispatcher.cpp
|
ArvydasSlekaitis/ReginaGameEngine
|
4b6af9b5fbf9aad4025b0387260c31019fd8f8c8
|
[
"MIT"
] | 1
|
2020-09-02T06:00:14.000Z
|
2020-09-02T06:00:14.000Z
|
AI/Src/MessageDispatcher.cpp
|
ArvydasSlekaitis/ReginaGameEngine
|
4b6af9b5fbf9aad4025b0387260c31019fd8f8c8
|
[
"MIT"
] | null | null | null |
AI/Src/MessageDispatcher.cpp
|
ArvydasSlekaitis/ReginaGameEngine
|
4b6af9b5fbf9aad4025b0387260c31019fd8f8c8
|
[
"MIT"
] | null | null | null |
///////////////////////////////////////////////////////////
// MessageDispatcher.cpp
// Created on: 20-07-2008
// Last modified: 22-06-2009
// Original author: Arvydas Slekaitis (C)
///////////////////////////////////////////////////////////
#include <MessageDispatcher.h>
using namespace Regina;
//*****************************************************************************
CMessageDispatcher* CMessageDispatcher::Instance()
{
static CMessageDispatcher msgDisp;
return &msgDisp;
}
//*****************************************************************************
void CMessageDispatcher::DispatchMsg(CTelegram* iTelegram)
{
assert(globalTime!=NULL && L"Message dispatcher is not initialized");
if(globalTime!=NULL)
{
CBaseEntity* entity = AIManager->EntityFromID(iTelegram->Receiver());
if(entity!=NULL)
{
if(iTelegram->DispatchTime()<=0)
Discharge(iTelegram, entity);
else
{
telegramQ.insert(make_pair(iTelegram->DispatchTime()+(*globalTime), iTelegram));
}
}
}
else
preInitatedTelegrams.push_back(iTelegram);
}
//*****************************************************************************
void CMessageDispatcher::UnregisterEntity(const unsigned& iID)
{
multimap<float, CTelegram*>::iterator it = telegramQ.begin();
while(it!=telegramQ.end())
{
if(it->second->Receiver() == iID)
{
multimap<float, CTelegram*>::iterator ite = it;
it++;
telegramQ.erase(ite);
}
else
it++;
}
}
//*****************************************************************************
void CMessageDispatcher::Update()
{
assert(globalTime!=NULL && L"Message dispatcher is not initialized");
if(preInitatedTelegrams.size()>0)
{
for(unsigned i=0; i<preInitatedTelegrams.size(); i++)
DispatchMsg(preInitatedTelegrams[i]);
preInitatedTelegrams.clear();
}
multimap<float, CTelegram*>::iterator it = telegramQ.begin();
while(it!=telegramQ.end())
{
if(it->first <= *globalTime)
{
CBaseEntity* entity = AIManager->EntityFromID(it->second->Receiver());
if(entity!=NULL) Discharge(it->second, entity);
multimap<float, CTelegram*>::iterator ite = it;
it++;
telegramQ.erase(ite);
}
else
break;
}
}
//*****************************************************************************
void CMessageDispatcher::Init(float* iGlobalTime)
{
globalTime = iGlobalTime;
}
| 22.287129
| 80
| 0.564638
|
ArvydasSlekaitis
|
f859ac6a81e42cc97042b1bb9b81a3d8ba7bde8a
| 18,473
|
cpp
|
C++
|
plugins/core/qAnimation/src/qAnimationDlg.cpp
|
ohanlonl/qCMAT
|
f6ca04fa7c171629f094ee886364c46ff8b27c0b
|
[
"BSD-Source-Code"
] | null | null | null |
plugins/core/qAnimation/src/qAnimationDlg.cpp
|
ohanlonl/qCMAT
|
f6ca04fa7c171629f094ee886364c46ff8b27c0b
|
[
"BSD-Source-Code"
] | null | null | null |
plugins/core/qAnimation/src/qAnimationDlg.cpp
|
ohanlonl/qCMAT
|
f6ca04fa7c171629f094ee886364c46ff8b27c0b
|
[
"BSD-Source-Code"
] | 1
|
2019-02-03T12:19:42.000Z
|
2019-02-03T12:19:42.000Z
|
//##########################################################################
//# #
//# CLOUDCOMPARE PLUGIN: qAnimation #
//# #
//# This program is free software; you can redistribute it and/or modify #
//# it under the terms of the GNU General Public License as published by #
//# the Free Software Foundation; version 2 or later of the License. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU General Public License for more details. #
//# #
//# COPYRIGHT: Ryan Wicks, 2G Robotics Inc., 2015 #
//# #
//##########################################################################
#include "qAnimationDlg.h"
//Local
#include "ViewInterpolate.h"
//qCC_db
#include <cc2DViewportObject.h>
//qCC_gl
#include <ccGLWindow.h>
//Qt
#include <QtGui>
#include <QApplication>
#include <QFileDialog>
#include <QFileInfo>
#include <QSettings>
#include <QElapsedTimer>
#include <QProgressDialog>
#include <QMessageBox>
//standard includes
#include <vector>
#include <iomanip>
#ifdef QFFMPEG_SUPPORT
//QTFFmpeg
#include <QVideoEncoder.h>
#endif
//System
#include <algorithm>
#if defined(CC_WINDOWS)
#include "windows.h"
#else
#include <unistd.h>
#endif
static const QString s_stepDurationKey("StepDurationSec");
static const QString s_stepEnabledKey("StepEnabled");
qAnimationDlg::qAnimationDlg(ccGLWindow* view3d, QWidget* parent)
: QDialog(parent, Qt::Tool)
, Ui::AnimationDialog()
, m_view3d(view3d)
{
setupUi(this);
//restore previous settings
{
QSettings settings;
settings.beginGroup("qAnimation");
//last filename
{
QString defaultDir;
#ifdef _MSC_VER
defaultDir = QApplication::applicationDirPath();
#else
defaultDir = QDir::homePath();
#endif
const QString defaultFileName( defaultDir + "/animation.mp4" );
QString lastFilename = settings.value("filename", defaultFileName ).toString();
#ifndef QFFMPEG_SUPPORT
lastFilename = QFileInfo(lastFilename).absolutePath();
#endif
outputFileLineEdit->setText( lastFilename );
}
//other parameters
{
bool startPreviewFromSelectedStep = settings.value("previewFromSelected", previewFromSelectedCheckBox->isChecked()).toBool();
bool loop = settings.value("loop", loopCheckBox->isChecked()).toBool();
int frameRate = settings.value("frameRate", fpsSpinBox->value()).toInt();
int superRes = settings.value("superRes", superResolutionSpinBox->value()).toInt();
int renderingMode = settings.value("renderingMode", renderingModeComboBox->currentIndex()).toInt();
int bitRate = settings.value("bitRate", bitrateSpinBox->value()).toInt();
previewFromSelectedCheckBox->setChecked(startPreviewFromSelectedStep);
loopCheckBox->setChecked(loop);
fpsSpinBox->setValue(frameRate);
superResolutionSpinBox->setValue(superRes);
renderingModeComboBox->setCurrentIndex(renderingMode);
bitrateSpinBox->setValue(bitRate);
}
settings.endGroup();
}
connect ( fpsSpinBox, SIGNAL( valueChanged(int) ), this, SLOT( onFPSChanged(int) ) );
connect ( totalTimeDoubleSpinBox, SIGNAL( valueChanged(double) ), this, SLOT( onTotalTimeChanged(double) ) );
connect ( stepTimeDoubleSpinBox, SIGNAL( valueChanged(double) ), this, SLOT( onStepTimeChanged(double) ) );
connect ( loopCheckBox, SIGNAL( toggled(bool) ), this, SLOT( onLoopToggled(bool) ) );
connect ( browseButton, SIGNAL( clicked() ), this, SLOT( onBrowseButtonClicked() ) );
connect ( previewButton, SIGNAL( clicked() ), this, SLOT( preview() ) );
connect ( renderButton, SIGNAL( clicked() ), this, SLOT( renderAnimation() ) );
connect ( exportFramesPushButton, SIGNAL( clicked() ), this, SLOT( renderFrames() ) );
connect ( buttonBox, SIGNAL( accepted() ), this, SLOT( onAccept() ) );
}
bool qAnimationDlg::init(const std::vector<cc2DViewportObject*>& viewports)
{
if (viewports.size() < 2)
{
assert(false);
return false;
}
try
{
m_videoSteps.resize(viewports.size());
}
catch (const std::bad_alloc&)
{
//not enough memory
return false;
}
for (size_t i = 0; i < viewports.size(); ++i)
{
cc2DViewportObject* vp = viewports[i];
//check if the (1st) viewport has a duration in meta data (from a previous run)
double duration_sec = 2.0;
if (vp->hasMetaData(s_stepDurationKey))
{
duration_sec = vp->getMetaData(s_stepDurationKey).toDouble();
}
bool isChecked = true;
if (vp->hasMetaData(s_stepEnabledKey))
{
isChecked = vp->getMetaData(s_stepEnabledKey).toBool();
}
QString itemName = QString("step %1 (%2)").arg(QString::number(i+1), vp->getName());
QListWidgetItem* item = new QListWidgetItem(itemName, stepSelectionList);
item->setFlags(item->flags() | Qt::ItemIsUserCheckable); // set checkable flag
item->setCheckState(isChecked ? Qt::Checked : Qt::Unchecked); // initialize check state
stepSelectionList->addItem(item);
m_videoSteps[i].viewport = vp;
m_videoSteps[i].duration_sec = duration_sec;
}
connect ( stepSelectionList, SIGNAL( currentRowChanged(int) ), this, SLOT( onCurrentStepChanged(int) ) );
connect ( stepSelectionList, SIGNAL( itemChanged(QListWidgetItem*) ), this, SLOT( onItemChanged(QListWidgetItem*) ) );
stepSelectionList->setCurrentRow(0); //select the first one by default
onCurrentStepChanged(getCurrentStepIndex());
updateTotalDuration();
return true;
}
void qAnimationDlg::onAccept()
{
assert(stepSelectionList->count() >= m_videoSteps.size());
for (size_t i = 0; i < m_videoSteps.size(); ++i)
{
cc2DViewportObject* vp = m_videoSteps[i].viewport;
//save the step duration as meta data
vp->setMetaData(s_stepDurationKey, m_videoSteps[i].duration_sec);
vp->setMetaData(s_stepEnabledKey, (stepSelectionList->item(static_cast<int>(i))->checkState() == Qt::Checked));
}
//store settings
{
QSettings settings;
settings.beginGroup("qAnimation");
settings.setValue("previewFromSelected", previewFromSelectedCheckBox->isChecked());
settings.setValue("loop", loopCheckBox->isChecked());
settings.setValue("frameRate", fpsSpinBox->value());
settings.setValue("renderingMode", renderingModeComboBox->currentIndex());
settings.setValue("superRes", superResolutionSpinBox->value());
settings.setValue("bitRate", bitrateSpinBox->value());
settings.endGroup();
}
}
double qAnimationDlg::computeTotalTime()
{
double totalDuration_sec = 0;
size_t vp1 = 0, vp2 = 0;
while (getNextSegment(vp1, vp2))
{
assert(vp1 < stepSelectionList->count());
totalDuration_sec += m_videoSteps[static_cast<int>(vp1)].duration_sec;
if (vp2 == 0)
{
//loop case
break;
}
vp1 = vp2;
}
return totalDuration_sec;
}
int qAnimationDlg::getCurrentStepIndex()
{
return stepSelectionList->currentRow();
}
void qAnimationDlg::applyViewport( const cc2DViewportObject* viewport )
{
if (m_view3d)
{
m_view3d->setViewportParameters( viewport->getParameters() );
m_view3d->redraw();
}
//QApplication::processEvents();
}
void qAnimationDlg::onFPSChanged(int fps)
{
//nothing to do
}
void qAnimationDlg::onTotalTimeChanged(double newTime_sec)
{
double previousTime_sec = computeTotalTime();
if (previousTime_sec != newTime_sec)
{
assert(previousTime_sec != 0);
double scale = newTime_sec / previousTime_sec;
size_t vp1 = 0, vp2 = 0;
while (getNextSegment(vp1, vp2))
{
assert(vp1 < stepSelectionList->count());
m_videoSteps[vp1].duration_sec *= scale;
if (vp2 == 0)
{
//loop case
break;
}
vp1 = vp2;
}
//update current step
updateCurrentStepDuration();
}
}
void qAnimationDlg::onStepTimeChanged(double time_sec)
{
m_videoSteps[ getCurrentStepIndex() ].duration_sec = time_sec;
//update total duration
updateTotalDuration();
//update current step
updateCurrentStepDuration();
}
void qAnimationDlg::onBrowseButtonClicked()
{
#ifdef QFFMPEG_SUPPORT
QString filename = QFileDialog::getSaveFileName( this,
tr("Output animation file"),
outputFileLineEdit->text() );
#else
QString filename = QFileDialog::getExistingDirectory( this,
tr("Open Directory"),
outputFileLineEdit->text(),
QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks );
#endif
if (filename.isEmpty())
{
//cancelled by user
return;
}
outputFileLineEdit->setText(filename);
}
bool qAnimationDlg::getNextSegment(size_t& vp1, size_t& vp2) const
{
if( vp1 >= m_videoSteps.size())
{
assert(false);
return false;
}
size_t inputVP1 = vp1;
while (stepSelectionList->item(static_cast<int>(vp1))->checkState() == Qt::Unchecked)
{
++vp1;
if (vp1 == m_videoSteps.size())
{
if (loopCheckBox->isChecked())
{
vp1 = 0;
}
else
{
//no more valid start (vp1)
return false;
}
}
if (vp1 == inputVP1)
{
return false;
}
}
//look for the next enabled viewport
for (vp2 = vp1+1; vp2 <= m_videoSteps.size(); ++vp2)
{
if (vp1 == vp2)
{
return false;
}
if (vp2 == m_videoSteps.size())
{
if (loopCheckBox->isChecked())
{
vp2 = 0;
}
else
{
//stop
break;
}
}
if (stepSelectionList->item(static_cast<int>(vp2))->checkState() == Qt::Checked)
{
//we have found a valid couple (vp1, vp2)
return true;
}
}
//no more valid stop (vp2)
return false;
}
int qAnimationDlg::countFrames(size_t startIndex/*=0*/)
{
//reset the interpolators and count the total number of frames
int totalFrameCount = 0;
{
double fps = fpsSpinBox->value();
size_t vp1 = startIndex;
size_t vp2 = vp1+1;
while (getNextSegment(vp1, vp2))
{
const Step& currentStep = m_videoSteps[vp1];
int frameCount = static_cast<int>( fps * currentStep.duration_sec );
totalFrameCount += frameCount;
//take care of the 'loop' case
if (vp2 == 0)
{
assert(loopCheckBox->isChecked());
break;
}
vp1 = vp2;
}
}
return totalFrameCount;
}
void qAnimationDlg::preview()
{
//we'll take the rendering time into account!
QElapsedTimer timer;
timer.start();
setEnabled(false);
size_t vp1 = previewFromSelectedCheckBox->isChecked() ? static_cast<size_t>(getCurrentStepIndex()) : 0;
//count the total number of frames
int frameCount = countFrames(loopCheckBox->isChecked() ? 0 : vp1);
int fps = fpsSpinBox->value();
//show progress dialog
QProgressDialog progressDialog(QString("Frames: %1").arg(frameCount), "Cancel", 0, frameCount, this);
progressDialog.setWindowTitle("Preview");
progressDialog.show();
progressDialog.setModal(true);
progressDialog.setAutoClose(false);
QApplication::processEvents();
assert(stepSelectionList->count() >= m_videoSteps.size());
int frameIndex = 0;
size_t vp2 = 0;
while (getNextSegment(vp1, vp2))
{
Step& step1 = m_videoSteps[vp1];
Step& step2 = m_videoSteps[vp2];
//theoretical waiting time per frame
qint64 delay_ms = static_cast<int>(1000 * step1.duration_sec / fps);
int frameCount = static_cast<int>( fps * step1.duration_sec );
ViewInterpolate interpolator(step1.viewport, step2.viewport);
interpolator.setMaxStep(frameCount);
cc2DViewportObject currentParams;
while ( interpolator.nextView( currentParams ) )
{
timer.restart();
applyViewport ( ¤tParams );
qint64 dt_ms = timer.elapsed();
progressDialog.setValue(++frameIndex);
QApplication::processEvents();
if (progressDialog.wasCanceled())
{
break;
}
//remaining time
if (dt_ms < delay_ms)
{
int wait_ms = static_cast<int>(delay_ms - dt_ms);
#if defined(CC_WINDOWS)
::Sleep( wait_ms );
#else
usleep( wait_ms * 1000 );
#endif
}
}
if (progressDialog.wasCanceled())
{
break;
}
if (vp2 == 0)
{
assert(loopCheckBox->isChecked());
frameIndex = 0;
}
vp1 = vp2;
}
//reset view
onCurrentStepChanged(getCurrentStepIndex());
setEnabled(true);
}
void qAnimationDlg::render(bool asSeparateFrames)
{
if (!m_view3d)
{
assert(false);
return;
}
QString outputFilename = outputFileLineEdit->text();
//save to persistent settings
{
QSettings settings;
settings.beginGroup("qAnimation");
settings.setValue("filename", outputFilename);
settings.endGroup();
}
setEnabled(false);
//count the total number of frames
int frameCount = countFrames(0);
int fps = fpsSpinBox->value();
//super resolution
int superRes = superResolutionSpinBox->value();
const int SUPER_RESOLUTION = 0;
const int ZOOM = 1;
int renderingMode = renderingModeComboBox->currentIndex();
assert(renderingMode == SUPER_RESOLUTION || renderingMode == ZOOM);
//show progress dialog
QProgressDialog progressDialog(QString("Frames: %1").arg(frameCount), "Cancel", 0, frameCount, this);
progressDialog.setWindowTitle("Render");
progressDialog.show();
QApplication::processEvents();
#ifdef QFFMPEG_SUPPORT
QScopedPointer<QVideoEncoder> encoder(0);
QSize originalViewSize;
if (!asSeparateFrames)
{
//get original viewport size
originalViewSize = m_view3d->qtSize();
//hack: as the encoder requires that the video dimensions are multiples of 8, we resize the window a little bit...
{
//find the nearest multiples of 8
QSize customSize = originalViewSize;
if (originalViewSize.width() % 8 || originalViewSize.height() % 8)
{
if (originalViewSize.width() % 8)
customSize.setWidth((originalViewSize.width() / 8 + 1) * 8);
if (originalViewSize.height() % 8)
customSize.setHeight((originalViewSize.height() / 8 + 1) * 8);
m_view3d->resize(customSize);
QApplication::processEvents();
}
}
int bitrate = bitrateSpinBox->value() * 1024;
int gop = fps;
int animScale = 1;
if (renderingMode == ZOOM)
{
animScale = superRes;
}
encoder.reset(new QVideoEncoder(outputFilename, m_view3d->glWidth() * animScale, m_view3d->glHeight() * animScale, bitrate, gop, static_cast<unsigned>(fpsSpinBox->value())));
QString errorString;
if (!encoder->open(&errorString))
{
QMessageBox::critical(this, "Error", QString("Failed to open file for output: %1").arg(errorString));
setEnabled(true);
return;
}
}
#else
if (!asSeparateFrames)
{
QMessageBox::critical(this, "Error", QString("Animation mode is not supported (no FFMPEG support)"));
return;
}
#endif
bool lodWasEnabled = m_view3d->isLODEnabled();
m_view3d->setLODEnabled(false);
QDir outputDir( QFileInfo(outputFilename).absolutePath() );
int frameIndex = 0;
bool success = true;
size_t vp1 = 0, vp2 = 0;
while (getNextSegment(vp1, vp2))
{
Step& step1 = m_videoSteps[vp1];
Step& step2 = m_videoSteps[vp2];
ViewInterpolate interpolator(step1.viewport, step2.viewport);
int frameCount = static_cast<int>( fps * step1.duration_sec );
interpolator.setMaxStep(frameCount);
cc2DViewportObject current_params;
while ( interpolator.nextView( current_params ) )
{
applyViewport ( ¤t_params );
//render to image
QImage image = m_view3d->renderToImage(superRes, renderingMode == ZOOM, false, true );
if (image.isNull())
{
QMessageBox::critical(this, "Error", "Failed to grab the screen!");
success = false;
break;
}
if (renderingMode == SUPER_RESOLUTION && superRes > 1)
{
image = image.scaled(image.width() / superRes, image.height() / superRes, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
}
if (asSeparateFrames)
{
QString filename = QString("frame_%1.png").arg(frameIndex, 6, 10, QChar('0'));
QString fullPath = outputDir.filePath(filename);
if (!image.save(fullPath))
{
QMessageBox::critical(this, "Error", QString("Failed to save frame #%1").arg(frameIndex + 1));
success = false;
break;
}
}
else
{
#ifdef QFFMPEG_SUPPORT
QString errorString;
if (!encoder->encodeImage(image, frameIndex, &errorString))
{
QMessageBox::critical(this, "Error", QString("Failed to encode frame #%1: %2").arg(frameIndex + 1).arg(errorString));
success = false;
break;
}
#endif
}
++frameIndex;
progressDialog.setValue(frameIndex);
QApplication::processEvents();
if (progressDialog.wasCanceled())
{
QMessageBox::warning(this, "Warning", QString("Process has been cancelled"));
success = false;
break;
}
}
if (!success)
{
break;
}
if (vp2 == 0)
{
//stop loop here!
break;
}
vp1 = vp2;
}
m_view3d->setLODEnabled(lodWasEnabled);
#ifdef QFFMPEG_SUPPORT
if (encoder)
{
encoder->close();
//hack: restore original size
m_view3d->resize(originalViewSize);
QApplication::processEvents();
}
#endif
progressDialog.hide();
QApplication::processEvents();
if (success)
{
QMessageBox::information(this, "Job done", "The animation has been saved successfully");
}
setEnabled(true);
}
void qAnimationDlg::updateTotalDuration()
{
double totalDuration_sec = computeTotalTime();
totalTimeDoubleSpinBox->blockSignals(true);
totalTimeDoubleSpinBox->setValue(totalDuration_sec);
totalTimeDoubleSpinBox->blockSignals(false);
}
void qAnimationDlg::updateCurrentStepDuration()
{
int index = getCurrentStepIndex();
stepTimeDoubleSpinBox->blockSignals(true);
stepTimeDoubleSpinBox->setValue(m_videoSteps[index].duration_sec);
stepTimeDoubleSpinBox->blockSignals(false);
}
void qAnimationDlg::onItemChanged(QListWidgetItem*)
{
//update total duration
updateTotalDuration();
onCurrentStepChanged(stepSelectionList->currentRow());
}
void qAnimationDlg::onCurrentStepChanged(int index)
{
//update current step descriptor
stepIndexLabel->setText(QString::number(index+1));
updateCurrentStepDuration();
applyViewport( m_videoSteps[index].viewport );
//check that the step is enabled
bool isEnabled = (stepSelectionList->item(index)->checkState() == Qt::Checked);
bool isLoop = loopCheckBox->isChecked();
currentStepGroupBox->setEnabled(isEnabled && (index+1 < m_videoSteps.size() || isLoop));
}
void qAnimationDlg::onLoopToggled(bool)
{
updateTotalDuration();
onCurrentStepChanged(stepSelectionList->currentRow());
}
| 26.091808
| 176
| 0.678504
|
ohanlonl
|
f85c7496c6de6833a5a0ebdc236bbacc783264f7
| 12,451
|
cpp
|
C++
|
gen/blink/bindings/modules/v8/V8Database.cpp
|
gergul/MiniBlink
|
7a11c52f141d54d5f8e1a9af31867cd120a2c3c4
|
[
"Apache-2.0"
] | 8
|
2019-05-05T16:38:05.000Z
|
2021-11-09T11:45:38.000Z
|
gen/blink/bindings/modules/v8/V8Database.cpp
|
gergul/MiniBlink
|
7a11c52f141d54d5f8e1a9af31867cd120a2c3c4
|
[
"Apache-2.0"
] | null | null | null |
gen/blink/bindings/modules/v8/V8Database.cpp
|
gergul/MiniBlink
|
7a11c52f141d54d5f8e1a9af31867cd120a2c3c4
|
[
"Apache-2.0"
] | 4
|
2018-12-14T07:52:46.000Z
|
2021-06-11T18:06:09.000Z
|
// Copyright 2014 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.
// This file has been auto-generated by code_generator_v8.py. DO NOT MODIFY!
#include "config.h"
#include "V8Database.h"
#include "bindings/core/v8/ExceptionState.h"
#include "bindings/core/v8/V8DOMConfiguration.h"
#include "bindings/core/v8/V8ObjectConstructor.h"
#include "bindings/core/v8/V8VoidCallback.h"
#include "bindings/modules/v8/V8SQLTransactionCallback.h"
#include "bindings/modules/v8/V8SQLTransactionErrorCallback.h"
#include "core/dom/ContextFeatures.h"
#include "core/dom/Document.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "platform/TraceEvent.h"
#include "wtf/GetPtr.h"
#include "wtf/RefPtr.h"
namespace blink {
// Suppress warning: global constructors, because struct WrapperTypeInfo is trivial
// and does not depend on another global objects.
#if defined(COMPONENT_BUILD) && defined(WIN32) && COMPILER(CLANG)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wglobal-constructors"
#endif
const WrapperTypeInfo V8Database::wrapperTypeInfo = { gin::kEmbedderBlink, V8Database::domTemplate, V8Database::refObject, V8Database::derefObject, V8Database::trace, 0, 0, V8Database::preparePrototypeObject, V8Database::installConditionallyEnabledProperties, "Database", 0, WrapperTypeInfo::WrapperTypeObjectPrototype, WrapperTypeInfo::ObjectClassId, WrapperTypeInfo::NotInheritFromEventTarget, WrapperTypeInfo::Independent, WrapperTypeInfo::GarbageCollectedObject };
#if defined(COMPONENT_BUILD) && defined(WIN32) && COMPILER(CLANG)
#pragma clang diagnostic pop
#endif
// This static member must be declared by DEFINE_WRAPPERTYPEINFO in Database.h.
// For details, see the comment of DEFINE_WRAPPERTYPEINFO in
// bindings/core/v8/ScriptWrappable.h.
const WrapperTypeInfo& Database::s_wrapperTypeInfo = V8Database::wrapperTypeInfo;
namespace DatabaseV8Internal {
static void versionAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
Database* impl = V8Database::toImpl(holder);
v8SetReturnValueString(info, impl->version(), info.GetIsolate());
}
static void versionAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
DatabaseV8Internal::versionAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void changeVersionMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
if (UNLIKELY(info.Length() < 2)) {
V8ThrowException::throwException(createMinimumArityTypeErrorForMethod(info.GetIsolate(), "changeVersion", "Database", 2, info.Length()), info.GetIsolate());
return;
}
Database* impl = V8Database::toImpl(info.Holder());
V8StringResource<> oldVersion;
V8StringResource<> newVersion;
SQLTransactionCallback* callback;
SQLTransactionErrorCallback* errorCallback;
VoidCallback* successCallback;
{
oldVersion = info[0];
if (!oldVersion.prepare())
return;
newVersion = info[1];
if (!newVersion.prepare())
return;
if (!isUndefinedOrNull(info[2])) {
if (!info[2]->IsFunction()) {
V8ThrowException::throwTypeError(info.GetIsolate(), ExceptionMessages::failedToExecute("changeVersion", "Database", "The callback provided as parameter 3 is not a function."));
return;
}
callback = V8SQLTransactionCallback::create(v8::Local<v8::Function>::Cast(info[2]), ScriptState::current(info.GetIsolate()));
} else {
callback = nullptr;
}
if (!isUndefinedOrNull(info[3])) {
if (!info[3]->IsFunction()) {
V8ThrowException::throwTypeError(info.GetIsolate(), ExceptionMessages::failedToExecute("changeVersion", "Database", "The callback provided as parameter 4 is not a function."));
return;
}
errorCallback = V8SQLTransactionErrorCallback::create(v8::Local<v8::Function>::Cast(info[3]), ScriptState::current(info.GetIsolate()));
} else {
errorCallback = nullptr;
}
if (!isUndefinedOrNull(info[4])) {
if (!info[4]->IsFunction()) {
V8ThrowException::throwTypeError(info.GetIsolate(), ExceptionMessages::failedToExecute("changeVersion", "Database", "The callback provided as parameter 5 is not a function."));
return;
}
successCallback = V8VoidCallback::create(v8::Local<v8::Function>::Cast(info[4]), ScriptState::current(info.GetIsolate()));
} else {
successCallback = nullptr;
}
}
impl->changeVersion(oldVersion, newVersion, callback, errorCallback, successCallback);
}
static void changeVersionMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMMethod");
DatabaseV8Internal::changeVersionMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void transactionMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
if (UNLIKELY(info.Length() < 1)) {
V8ThrowException::throwException(createMinimumArityTypeErrorForMethod(info.GetIsolate(), "transaction", "Database", 1, info.Length()), info.GetIsolate());
return;
}
Database* impl = V8Database::toImpl(info.Holder());
SQLTransactionCallback* callback;
SQLTransactionErrorCallback* errorCallback;
VoidCallback* successCallback;
{
if (info.Length() <= 0 || !info[0]->IsFunction()) {
V8ThrowException::throwTypeError(info.GetIsolate(), ExceptionMessages::failedToExecute("transaction", "Database", "The callback provided as parameter 1 is not a function."));
return;
}
callback = V8SQLTransactionCallback::create(v8::Local<v8::Function>::Cast(info[0]), ScriptState::current(info.GetIsolate()));
if (!isUndefinedOrNull(info[1])) {
if (!info[1]->IsFunction()) {
V8ThrowException::throwTypeError(info.GetIsolate(), ExceptionMessages::failedToExecute("transaction", "Database", "The callback provided as parameter 2 is not a function."));
return;
}
errorCallback = V8SQLTransactionErrorCallback::create(v8::Local<v8::Function>::Cast(info[1]), ScriptState::current(info.GetIsolate()));
} else {
errorCallback = nullptr;
}
if (!isUndefinedOrNull(info[2])) {
if (!info[2]->IsFunction()) {
V8ThrowException::throwTypeError(info.GetIsolate(), ExceptionMessages::failedToExecute("transaction", "Database", "The callback provided as parameter 3 is not a function."));
return;
}
successCallback = V8VoidCallback::create(v8::Local<v8::Function>::Cast(info[2]), ScriptState::current(info.GetIsolate()));
} else {
successCallback = nullptr;
}
}
impl->transaction(callback, errorCallback, successCallback);
}
static void transactionMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMMethod");
DatabaseV8Internal::transactionMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void readTransactionMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
if (UNLIKELY(info.Length() < 1)) {
V8ThrowException::throwException(createMinimumArityTypeErrorForMethod(info.GetIsolate(), "readTransaction", "Database", 1, info.Length()), info.GetIsolate());
return;
}
Database* impl = V8Database::toImpl(info.Holder());
SQLTransactionCallback* callback;
SQLTransactionErrorCallback* errorCallback;
VoidCallback* successCallback;
{
if (info.Length() <= 0 || !info[0]->IsFunction()) {
V8ThrowException::throwTypeError(info.GetIsolate(), ExceptionMessages::failedToExecute("readTransaction", "Database", "The callback provided as parameter 1 is not a function."));
return;
}
callback = V8SQLTransactionCallback::create(v8::Local<v8::Function>::Cast(info[0]), ScriptState::current(info.GetIsolate()));
if (!isUndefinedOrNull(info[1])) {
if (!info[1]->IsFunction()) {
V8ThrowException::throwTypeError(info.GetIsolate(), ExceptionMessages::failedToExecute("readTransaction", "Database", "The callback provided as parameter 2 is not a function."));
return;
}
errorCallback = V8SQLTransactionErrorCallback::create(v8::Local<v8::Function>::Cast(info[1]), ScriptState::current(info.GetIsolate()));
} else {
errorCallback = nullptr;
}
if (!isUndefinedOrNull(info[2])) {
if (!info[2]->IsFunction()) {
V8ThrowException::throwTypeError(info.GetIsolate(), ExceptionMessages::failedToExecute("readTransaction", "Database", "The callback provided as parameter 3 is not a function."));
return;
}
successCallback = V8VoidCallback::create(v8::Local<v8::Function>::Cast(info[2]), ScriptState::current(info.GetIsolate()));
} else {
successCallback = nullptr;
}
}
impl->readTransaction(callback, errorCallback, successCallback);
}
static void readTransactionMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMMethod");
DatabaseV8Internal::readTransactionMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
} // namespace DatabaseV8Internal
static const V8DOMConfiguration::AccessorConfiguration V8DatabaseAccessors[] = {
{"version", DatabaseV8Internal::versionAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder},
};
static const V8DOMConfiguration::MethodConfiguration V8DatabaseMethods[] = {
{"changeVersion", DatabaseV8Internal::changeVersionMethodCallback, 0, 2, V8DOMConfiguration::ExposedToAllScripts},
{"transaction", DatabaseV8Internal::transactionMethodCallback, 0, 1, V8DOMConfiguration::ExposedToAllScripts},
{"readTransaction", DatabaseV8Internal::readTransactionMethodCallback, 0, 1, V8DOMConfiguration::ExposedToAllScripts},
};
static void installV8DatabaseTemplate(v8::Local<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate)
{
functionTemplate->ReadOnlyPrototype();
v8::Local<v8::Signature> defaultSignature;
defaultSignature = V8DOMConfiguration::installDOMClassTemplate(isolate, functionTemplate, "Database", v8::Local<v8::FunctionTemplate>(), V8Database::internalFieldCount,
0, 0,
V8DatabaseAccessors, WTF_ARRAY_LENGTH(V8DatabaseAccessors),
V8DatabaseMethods, WTF_ARRAY_LENGTH(V8DatabaseMethods));
v8::Local<v8::ObjectTemplate> instanceTemplate = functionTemplate->InstanceTemplate();
ALLOW_UNUSED_LOCAL(instanceTemplate);
v8::Local<v8::ObjectTemplate> prototypeTemplate = functionTemplate->PrototypeTemplate();
ALLOW_UNUSED_LOCAL(prototypeTemplate);
// Custom toString template
functionTemplate->Set(v8AtomicString(isolate, "toString"), V8PerIsolateData::from(isolate)->toStringTemplate());
}
v8::Local<v8::FunctionTemplate> V8Database::domTemplate(v8::Isolate* isolate)
{
return V8DOMConfiguration::domClassTemplate(isolate, const_cast<WrapperTypeInfo*>(&wrapperTypeInfo), installV8DatabaseTemplate);
}
bool V8Database::hasInstance(v8::Local<v8::Value> v8Value, v8::Isolate* isolate)
{
return V8PerIsolateData::from(isolate)->hasInstance(&wrapperTypeInfo, v8Value);
}
v8::Local<v8::Object> V8Database::findInstanceInPrototypeChain(v8::Local<v8::Value> v8Value, v8::Isolate* isolate)
{
return V8PerIsolateData::from(isolate)->findInstanceInPrototypeChain(&wrapperTypeInfo, v8Value);
}
Database* V8Database::toImplWithTypeCheck(v8::Isolate* isolate, v8::Local<v8::Value> value)
{
return hasInstance(value, isolate) ? toImpl(v8::Local<v8::Object>::Cast(value)) : 0;
}
void V8Database::refObject(ScriptWrappable* scriptWrappable)
{
}
void V8Database::derefObject(ScriptWrappable* scriptWrappable)
{
}
} // namespace blink
| 47.342205
| 468
| 0.709823
|
gergul
|
f86338ac040f8d2195a6caae14f599f60cb40375
| 3,486
|
hpp
|
C++
|
src/Typing.hpp
|
aukdata/TorikaiType
|
8d4079c38510ee33bc2323231065b0d72f2ea3cc
|
[
"MIT"
] | null | null | null |
src/Typing.hpp
|
aukdata/TorikaiType
|
8d4079c38510ee33bc2323231065b0d72f2ea3cc
|
[
"MIT"
] | null | null | null |
src/Typing.hpp
|
aukdata/TorikaiType
|
8d4079c38510ee33bc2323231065b0d72f2ea3cc
|
[
"MIT"
] | null | null | null |
//
// Typing.hpp
// TorikaiType
//
# ifndef Typing_hpp
# define Typing_hpp
# include <Siv3D.hpp>
# include <functional>
class Typing
{
static const Array<std::pair<String, String>> romanize_table;
static const HashTable<char32, char32> hiraganaize_table;
Array<String> m_parsed, m_hiraganized, m_romanized;
int32 m_pos = -1;
String m_buffer = U"";
bool m_acceptSecondN = false;
[[nodiscard]] bool isSmallChar(char32 c) const
{
constexpr std::array<char32, 16> smallChs =
{
U'ぁ', U'ぃ', U'ぅ', U'ぇ', U'ぉ', U'ゃ', U'ゅ', U'ょ',
U'ァ', U'ィ', U'ゥ', U'ェ', U'ォ', U'ャ', U'ュ', U'ョ'
};
return std::find(smallChs.begin(), smallChs.end(), c) != smallChs.end();
}
[[nodiscard]] constexpr bool isAlphabet(char32 c) const
{
return U'A' <= c && c <= U'z';
}
void parseText(String text) {
String buf = U"";
bool sokuon = false;
m_parsed.clear();
for (auto c : text)
{
if (c == U'っ' || c == U'ッ')
{
if (!sokuon)
{
m_parsed.push_back(std::move(buf));
buf = U"";
}
buf += c;
sokuon = true;
}
else
{
if (isSmallChar(c))
{
m_parsed.push_back(buf + c);
buf = U"";
sokuon = true;
}
else
{
if (!sokuon)
{
m_parsed.push_back(std::move(buf));
buf = U"";
}
buf += c;
sokuon = false;
}
}
}
if (buf != U"")
{
m_parsed.push_back(std::move(buf));
}
m_parsed.pop_front();
}
void setText(String text)
{
parseText(text);
m_hiraganized = m_parsed.map([&] (const auto& s) {
String hiragana = U"";
s.each([&] (const auto c) { hiragana += hiraganaize_table.count(c) > 0 ? hiraganaize_table.at(c) : c; });
return std::move(hiragana);
});
m_romanized = m_hiraganized.map([&] (const auto& kana) {
for (const auto& pair : romanize_table)
{
if (pair.second == kana)
{
return pair.first;
}
else if (U"っ" + pair.second == kana)
{
return pair.first[0] + pair.first;
}
}
return String(U" ");
});
m_pos = 0;
}
std::function<void()> m_onCorrectWordHandler;
std::function<String()> m_nextWordHandler;
public:
Typing() {};
std::pair<int32, int32> getNextCharPos() const;
void setCorrectWordHandler(std::function<void()> handler) { m_onCorrectWordHandler = handler; }
void setNextWordHandler(std::function<String()> handler) { m_nextWordHandler = handler; }
bool onCharInput(const char32 s);
[[nodiscard]] char32 getNextChar() const;
void update();
void draw(const int32 x, const int32 y, const bool showHiragana = true, const bool showRomaji = true, const bool showTypedRomaji = true) const;
};
# endif /* Typing_hpp */
| 26.815385
| 147
| 0.454676
|
aukdata
|
d379d514f9db4919fea39d1107d9432c41b660e2
| 7,292
|
cpp
|
C++
|
src/cpu/x64/zendnn_inner_product.cpp
|
amd/ZenDNN
|
2d8e025a05126b7c378d88a990a20e21a4182b20
|
[
"Apache-2.0"
] | 28
|
2021-08-12T10:38:06.000Z
|
2022-03-25T08:37:31.000Z
|
src/cpu/x64/zendnn_inner_product.cpp
|
amd/ZenDNN
|
2d8e025a05126b7c378d88a990a20e21a4182b20
|
[
"Apache-2.0"
] | 2
|
2021-08-17T03:20:10.000Z
|
2021-09-23T04:15:32.000Z
|
src/cpu/x64/zendnn_inner_product.cpp
|
amd/ZenDNN
|
2d8e025a05126b7c378d88a990a20e21a4182b20
|
[
"Apache-2.0"
] | 5
|
2021-08-20T05:05:59.000Z
|
2022-02-25T19:13:07.000Z
|
/*******************************************************************************
* Modifications Copyright (c) 2021 Advanced Micro Devices, Inc. All rights reserved.
* Notified per clause 4(b) of the license.
*******************************************************************************/
/*******************************************************************************
* Copyright 2017-2020 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
#include "c_types_map.hpp"
#include "zendnn_thread.hpp"
#include "type_helpers.hpp"
#include "cpu/binary_injector_utils.hpp"
#include "zendnn_logging.hpp"
#include "zendnn_inner_product.hpp"
#include "zendnn_private.hpp"
namespace zendnn {
namespace impl {
namespace cpu {
namespace x64 {
using namespace zendnn::impl::status;
using namespace zendnn::impl::prop_kind;
using namespace zendnn::impl::data_type;
using namespace zendnn::impl::format_tag;
using namespace zendnn::impl::primitive_kind;
template <impl::data_type_t data_type>
status_t zendnn_inner_product_fwd_t<data_type>::execute_forward(
const exec_ctx_t &ctx) const {
auto src = CTX_IN_MEM(const data_t *, ZENDNN_ARG_SRC);
auto weights = CTX_IN_MEM(const data_t *, ZENDNN_ARG_WEIGHTS);
auto bias = CTX_IN_MEM(const data_t *, ZENDNN_ARG_BIAS);
auto dst = CTX_OUT_MEM(data_t *, ZENDNN_ARG_DST);
const auto post_ops_binary_rhs_arg_vec
= binary_injector_utils::prepare_binary_args(
this->pd()->attr()->post_ops_, ctx);
const dim_t MB = pd()->MB();
const dim_t OC = pd()->OC();
const dim_t IC = pd()->IC_total_padded();
const auto &wmd = *pd()->weights_md();
// check if OC is NOT the leading dimension
bool wei_tr = wmd.format_desc.blocking.strides[0] != 1;
bool has_eltwise = pd()->attr()->post_ops_.find(primitive_kind::eltwise) >= 0;
const float *scales = pd()->attr()->output_scales_.scales_;
// The mask value of 0 implies a common output scaling factor for the
// whole output tensor.
float alpha = pd()->attr()->output_scales_.mask_ == 0 ? scales[0] : 1.0;
//TODO(aakar): Handle case where (mask == 1 << 1) or (mask != 0)
// Modify inner_product API to support Layout
bool Layout = true; //CblasRowMajor
zendnnInfo(ZENDNN_CORELOG,
"ZENDNN implementation path in zendnn_inner_product_fwd_t::execute_forward [cpu/inner_product]");
if (bias == NULL) {
zendnnInfo(ZENDNN_CORELOG,
"zendnn_inner_product_fwd_t::execute_forward zenMatMul [cpu/inner_product]");
zenMatMul(
Layout, false, wei_tr, 1, MB, IC, OC, alpha, (float *)src, IC,
(float *)weights, wei_tr ? IC : OC, beta_, (float *)dst, OC);
}
else if (!has_eltwise) {
zendnnInfo(ZENDNN_CORELOG,
"zendnn_inner_product_fwd_t::execute_forward zenMatMulWithBias [cpu/inner_product]");
zenMatMulWithBias(
Layout, false, wei_tr, 1, MB, IC, OC, alpha, (float *)src, IC,
(float *)weights, wei_tr ? IC : OC, (float *)bias, beta_,
(float *)dst, OC);
}
else {
zendnnInfo(ZENDNN_CORELOG,
"zendnn_inner_product_fwd_t::execute_forward zenMatMulWithBiasReLU [cpu/inner_product]");
zenMatMulWithBiasReLU(
Layout, false, wei_tr, 1, MB, IC, OC, alpha, (float *)src, IC,
(float *)weights, wei_tr ? IC : OC, (float *)bias, beta_,
(float *)dst, OC);
}
return status::success;
}
template <impl::data_type_t data_type>
status_t zendnn_inner_product_bwd_data_t<data_type>::execute_backward_data(
const exec_ctx_t &ctx) const {
auto diff_dst = CTX_IN_MEM(const data_t *, ZENDNN_ARG_DIFF_DST);
auto weights = CTX_IN_MEM(const data_t *, ZENDNN_ARG_WEIGHTS);
auto diff_src = CTX_OUT_MEM(data_t *, ZENDNN_ARG_DIFF_SRC);
const dim_t MB = pd()->MB();
const dim_t OC = pd()->OC();
const dim_t IC = pd()->IC_total_padded();
const auto &wmd = *pd()->weights_md();
bool wei_tr = wmd.format_desc.blocking.strides[0] == 1;
float alpha = 1.0, beta = 0.0;
status_t st = extended_sgemm(wei_tr ? "T" : "N", "N", &IC, &MB, &OC, &alpha,
weights, wei_tr ? &OC : &IC, diff_dst, &OC, &beta, diff_src, &IC);
return st;
}
template <impl::data_type_t data_type>
status_t zendnn_inner_product_bwd_weights_t<data_type>::execute_backward_weights(
const exec_ctx_t &ctx) const {
auto diff_dst = CTX_IN_MEM(const data_t *, ZENDNN_ARG_DIFF_DST);
auto src = CTX_IN_MEM(const data_t *, ZENDNN_ARG_SRC);
auto diff_weights = CTX_OUT_MEM(data_t *, ZENDNN_ARG_DIFF_WEIGHTS);
auto diff_bias = CTX_OUT_MEM(data_t *, ZENDNN_ARG_DIFF_BIAS);
const memory_desc_wrapper diff_dst_d(pd()->diff_dst_md());
const memory_desc_wrapper diff_bias_d(pd()->diff_weights_md(1));
diff_dst += diff_dst_d.offset0();
const dim_t MB = pd()->MB();
const dim_t OC = pd()->OC();
const dim_t IC = pd()->IC_total_padded();
const auto &wmd = *pd()->diff_weights_md();
bool wei_tr = wmd.format_desc.blocking.strides[0] == 1;
float alpha = 1.0, beta = 0.0;
status_t st;
if (wei_tr)
st = extended_sgemm("N", "T", &OC, &IC, &MB, &alpha, diff_dst, &OC, src,
&IC, &beta, diff_weights, &OC);
else
st = extended_sgemm("N", "T", &IC, &OC, &MB, &alpha, src, &IC, diff_dst,
&OC, &beta, diff_weights, &IC);
if (st != status::success) {
return st;
}
if (diff_bias) {
diff_bias += diff_bias_d.offset0();
constexpr dim_t blksize = 8;
const dim_t OC_blocks = utils::div_up(OC, blksize);
parallel(0, [&](const int ithr, const int nthr) {
dim_t oc_s {0}, oc_e {0};
balance211(OC_blocks, nthr, ithr, oc_s, oc_e);
oc_s = std::min(oc_s * blksize, OC);
oc_e = std::min(oc_e * blksize, OC);
ZENDNN_PRAGMA_OMP_SIMD()
for (dim_t oc = oc_s; oc < oc_e; ++oc) {
diff_bias[oc] = diff_dst[oc];
}
for (dim_t mb = 1; mb < MB; ++mb) {
ZENDNN_PRAGMA_OMP_SIMD()
for (dim_t oc = oc_s; oc < oc_e; ++oc) {
diff_bias[oc] += diff_dst[mb * OC + oc];
}
}
});
}
return status::success;
}
template struct zendnn_inner_product_fwd_t<data_type::f32>;
template struct zendnn_inner_product_bwd_data_t<data_type::f32>;
template struct zendnn_inner_product_bwd_weights_t<data_type::f32>;
} // namespace x64
} // namespace cpu
} // namespace impl
} // namespace zendnn
// vim: et ts=4 sw=4 cindent cino+=l0,\:4,N-s
| 37.782383
| 112
| 0.613961
|
amd
|
d37c8fc507a2f7e06c434ddc362d9e0c31db6323
| 3,366
|
hpp
|
C++
|
hydra/hydra.hpp
|
tim42/hydra
|
dfffd50a2863695742c0c6122a505824db8be7c3
|
[
"MIT"
] | 2
|
2016-09-15T22:29:46.000Z
|
2017-11-30T11:16:12.000Z
|
hydra/hydra.hpp
|
tim42/hydra
|
dfffd50a2863695742c0c6122a505824db8be7c3
|
[
"MIT"
] | null | null | null |
hydra/hydra.hpp
|
tim42/hydra
|
dfffd50a2863695742c0c6122a505824db8be7c3
|
[
"MIT"
] | null | null | null |
//
// file : hydra.hpp
// in : file:///home/tim/projects/hydra/hydra/hydra.hpp
//
// created by : Timothée Feuillet
// date: Sat Apr 23 2016 15:19:07 GMT+0200 (CEST)
//
//
// Copyright (c) 2016 Timothée Feuillet
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
#ifndef __N_396519513304418946_3159317424_HYDRA_HPP__
#define __N_396519513304418946_3159317424_HYDRA_HPP__
// NOTE: There's *_ext.hpp file in the current folder. Those files aren't included
// by this header as they are the main header of some extensions. If you plan using
// that extension with hydra, you may want to include
// a logger for hydra (define HYDRA_NO_MESSAGES to disable logs)
#include "hydra_logger.hpp"
// an optional reflective support for hydra (define HYDRA_NO_REFLECTIVE_SUPPORT to disable this)
// you don't need to have reflective to build and use hydra, but if the reflective header is included
// hydra will generate some meta/data for it
#include "hydra_reflective.hpp"
// some specific exception for hydra. Also, some checks.
// The macro HYDRA_DISABLE_OPTIONAL_CHECKS will disable asserts and error checking
// The macro HYDRA_ENABLE_DEBUG_CHECKS will enable some asserts and error checking that may slow down a bit the code
// on non-critical sections of the code,
// N_DISABLE_CHECKS will disable all the asserts and error checking
// N_ALLOW_DEBUG will log a lot of information about checks and asserts
// NOTE: hydra assert throws exceptions (neam::hydra::exception that inherits from std::exception)
#include "hydra_exception.hpp"
// include the bootstrap / init files
#include "init/bootstrap.hpp"
#include "init/feature_requesters/gen_feature_requester.hpp"
// Make GLM compatible with vulkan
#define GLM_FORCE_RADIANS
#define GLM_FORCE_DEPTH_ZERO_TO_ONE
#include <glm/glm.hpp> // glm is a core dependency of hydra
// include the vulkan wrapper
#include "vulkan/vulkan.hpp"
// include main components
#include "utilities/utilities.hpp"
#include "geometry/geometry.hpp"
#include "threading/threading.hpp"
#include "geometry/geometry.hpp"
// #ifndef HYDRA_NO_RENDERER
// // include the renderer (can be disabled by defining HYDRA_NO_RENDERER)
// #include "renderer/renderer.hpp"
// #endif
namespace neam
{
namespace hydra
{
} // namespace hydra
} // namespace neam
#endif // __N_396519513304418946_3159317424_HYDRA_HPP__
| 39.139535
| 116
| 0.773321
|
tim42
|
d37fe7ba141af0de221e7f50b37bef2e12f003fd
| 1,268
|
cpp
|
C++
|
samples/v8test/v8test.cpp
|
Patriccollu/smooth
|
8673d4702c55b1008bbcabddf7907da0e50505e4
|
[
"Artistic-2.0"
] | 24
|
2017-08-22T15:55:34.000Z
|
2022-03-06T11:41:31.000Z
|
samples/v8test/v8test.cpp
|
Patriccollu/smooth
|
8673d4702c55b1008bbcabddf7907da0e50505e4
|
[
"Artistic-2.0"
] | 6
|
2018-07-21T12:17:55.000Z
|
2021-08-12T11:27:27.000Z
|
samples/v8test/v8test.cpp
|
Patriccollu/smooth
|
8673d4702c55b1008bbcabddf7907da0e50505e4
|
[
"Artistic-2.0"
] | 9
|
2017-09-13T02:32:18.000Z
|
2022-03-06T11:41:32.000Z
|
#include <smooth.h>
#include <smooth/main.h>
using namespace smooth;
using namespace smooth::GUI::Dialogs;
#include <smooth-js/v8.h>
using namespace v8;
Int smooth::Main()
{
// Create a new isolate.
Isolate *isolate = v8::Isolate::New();
// Enter the created isolate.
{
Isolate::Scope isolateScope(isolate);
// Create a stack-allocated handle scope.
HandleScope handleScope(isolate);
// Create a new context.
Local<Context> context = Context::New(isolate);
// Enter the created context for compiling and
// running the hello world script.
Context::Scope contextScope(context);
// Create a string containing the JavaScript source code.
Handle<v8::String> source = v8::String::New("'Hello' + ', World!'");
Handle<v8::String> file = v8::String::New("unnamed");
// Compile the source code.
Local<Script> script = Script::Compile(source, file);
// Run the script to get the result.
Handle<Value> result = script->Run();
// Convert the result to an ASCII string and print it.
v8::String::AsciiValue ascii(result);
QuickMessage((char *) *ascii, "V8 Engine Test", GUI::Dialogs::Message::Buttons::Ok, GUI::Dialogs::Message::Icon::Information);
}
// Dispose the isolate.
isolate->Dispose();
return 0;
}
| 24.862745
| 128
| 0.683754
|
Patriccollu
|
d38223417136f27d5ab11015755a5fb407ea3359
| 876
|
hpp
|
C++
|
sources/Common/UseUnused.hpp
|
palchukovsky/TunnelEx
|
ec645271ab8b79225e378345ff108795110c57de
|
[
"Apache-2.0"
] | null | null | null |
sources/Common/UseUnused.hpp
|
palchukovsky/TunnelEx
|
ec645271ab8b79225e378345ff108795110c57de
|
[
"Apache-2.0"
] | null | null | null |
sources/Common/UseUnused.hpp
|
palchukovsky/TunnelEx
|
ec645271ab8b79225e378345ff108795110c57de
|
[
"Apache-2.0"
] | null | null | null |
/**************************************************************************
* Created: 2011/05/02 17:48
* Author: Eugene V. Palchukovsky
* E-mail: eugene@palchukovsky.com
* -------------------------------------------------------------------
* Project: TunnelEx
* URL: http://tunnelex.net
**************************************************************************/
#ifndef INCLUDED_FILE__TUNNELEX__UseUnused_hpp__1105021748
#define INCLUDED_FILE__TUNNELEX__UseUnused_hpp__1105021748
template<typename T>
inline void UseUnused(const T &) throw() {
//...//
}
template<typename T1, typename T2>
inline void UseUnused(const T1 &, const T2 &) throw() {
//...//
}
template<typename T1, typename T2, typename T3>
inline void UseUnused(const T1 &, const T2 &, const T3 &) throw() {
//...//
}
#endif // INCLUDED_FILE__TUNNELEX__UseUnused_hpp__1105021748
| 29.2
| 76
| 0.531963
|
palchukovsky
|
d38275c6387cb1d5484bba50aa63d84525071056
| 5,412
|
cpp
|
C++
|
src/main.cpp
|
wx257osn2/symboli_carotene
|
710af9e913eae012cf02d2008b21127fb422b2b5
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
wx257osn2/symboli_carotene
|
710af9e913eae012cf02d2008b21127fb422b2b5
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
wx257osn2/symboli_carotene
|
710af9e913eae012cf02d2008b21127fb422b2b5
|
[
"MIT"
] | null | null | null |
#include<symboli/prelude.hpp>
#include<optional>
#include<cstddef>
#include<memory>
#include<iostream>
#include<mutex>
#include<condition_variable>
#include<thread>
#include"symboli/carotene/core_version.hpp"
static std::optional<symboli::prelude> prelude;
extern "C"{
__declspec(dllexport) unsigned int major_version(){
return SYMBOLI_CAROTENE_CORE_EXPECTED_VERSION_MAJOR;
}
__declspec(dllexport) unsigned int minor_version(){
return SYMBOLI_CAROTENE_CORE_EXPECTED_VERSION_MINOR;
}
__declspec(dllexport) unsigned int patch_version(){
return SYMBOLI_CAROTENE_CORE_EXPECTED_VERSION_PATCH;
}
__declspec(dllexport) void* get_prelude(){
return static_cast<void*>(&*prelude);
}
}
class task_t{
struct input{
const char* ptr;
int size;
enum class message_type{
request,
response
}type;
}input_data = {nullptr, 0};
std::mutex mtx;
std::condition_variable cv_ready_to_copy;
std::condition_variable cv_finish_copy;
bool met_demise = false;
std::vector<std::function<void(const std::vector<std::byte>&)>> request_funcs;
std::vector<std::function<void(const std::vector<std::byte>&)>> response_funcs;
template<input::message_type Type>
void copy(const char* ptr, int size){
std::unique_lock lock{mtx};
if constexpr(Type == input::message_type::request){
if(request_funcs.empty())
return;
}
else if constexpr(Type == input::message_type::response){
if(response_funcs.empty())
return;
}
input_data.ptr = ptr;
input_data.size = size;
input_data.type = Type;
cv_ready_to_copy.notify_one();
cv_finish_copy.wait(lock, [&]{return input_data.ptr == nullptr || met_demise;});
}
public:
task_t() = default;
void demise(){
std::scoped_lock lock{mtx};
met_demise = true;
cv_ready_to_copy.notify_all();
cv_finish_copy.notify_all();
}
void request(const char* ptr, int size){
this->copy<input::message_type::request>(ptr, size);
}
void response(const char* ptr, int size){
this->copy<input::message_type::response>(ptr, size);
}
void add_request_func(std::function<void(const std::vector<std::byte>&)> f){
std::scoped_lock lock{mtx};
request_funcs.emplace_back(std::move(f));
}
void add_response_func(std::function<void(const std::vector<std::byte>&)> f){
std::scoped_lock lock{mtx};
response_funcs.emplace_back(std::move(f));
}
void operator()(){
while(true){
std::vector<std::byte> data;
input::message_type type;
{
std::unique_lock lock{mtx};
cv_ready_to_copy.wait(lock, [&]{return input_data.ptr != nullptr || met_demise;});
if(met_demise)
break;
data.assign(reinterpret_cast<const std::byte*>(input_data.ptr), reinterpret_cast<const std::byte*>(input_data.ptr+input_data.size));
type = input_data.type;
input_data = {};
cv_finish_copy.notify_one();
}
switch(type){
case input::message_type::request:
for(auto&& f : request_funcs)try{
f(data);
}catch(const std::exception& e){
prelude->diagnostic("Carotene Core :: request", e.what());
}
break;
case input::message_type::response:
for(auto&& f : response_funcs)try{
f(data);
}catch(const std::exception& e){
prelude->diagnostic("Carotene Core :: response", e.what());
}
}
}
}
}static task = {};
static std::thread task_thread;
struct lz4_decompress_safe_ext : symboli::hook_func<int(char*, char*, int, int), lz4_decompress_safe_ext>{
static int func(char* src, char* dst, int compressed_size, int dst_capacity){
const auto ret = orig(src, dst, compressed_size, dst_capacity);
task.response(dst, ret);
return ret;
}
};
struct lz4_compress_default_ext : symboli::hook_func<int(char*, char*, int, int), lz4_compress_default_ext>{
static int func(char* src, char* dst, int src_size, int dst_capacity){
const auto ret = orig(src, dst, src_size, dst_capacity);
task.request(src, src_size);
return ret;
}
};
__declspec(dllexport) void add_request_func(std::function<void(const std::vector<std::byte>&)> f){
task.add_request_func(std::move(f));
}
__declspec(dllexport) void add_response_func(std::function<void(const std::vector<std::byte>&)> f){
task.add_response_func(std::move(f));
}
static inline BOOL process_attach(HINSTANCE hinst){
const std::filesystem::path plugin_path{will::get_module_file_name(hinst).value()};
prelude =+ symboli::prelude::create(plugin_path.parent_path()/"symboli_prelude.dll");
prelude->enqueue_task([]{
auto libnative =+ will::get_module_handle(_T("libnative.dll"));
const auto LZ4_decompress_safe_ext =+ libnative.get_proc_address<int(char*, char*, int, int)>("LZ4_decompress_safe_ext");
prelude->hook<lz4_decompress_safe_ext>(LZ4_decompress_safe_ext);
const auto LZ4_compress_default_ext =+ libnative.get_proc_address<int(char*, char*, int, int)>("LZ4_compress_default_ext");
prelude->hook<lz4_compress_default_ext>(LZ4_compress_default_ext);
});
task_thread = std::thread{std::ref(task)};
return TRUE;
}
static inline BOOL process_detach(){
if(prelude)
prelude.reset();
task.demise();
task_thread.join();
return TRUE;
}
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID)try{
switch(fdwReason){
case DLL_PROCESS_ATTACH:
return process_attach(hinstDLL);
case DLL_PROCESS_DETACH:
return process_detach();
default:
return TRUE;
}
}catch(std::exception& e){
::MessageBoxA(nullptr, e.what(), "Carotene Core exception", MB_OK|MB_ICONERROR|MB_SETFOREGROUND);
return FALSE;
}
| 29.736264
| 136
| 0.72561
|
wx257osn2
|
d384787e3e9cc8b1f58c96a00e36e9680cb3d2df
| 150
|
cpp
|
C++
|
FastWindows.UI.Composition/CompositionShadow.cpp
|
kennykerr/Minesweeper
|
6f28abab141d80725beb746073d994833075b862
|
[
"MIT"
] | 2
|
2019-06-13T16:29:07.000Z
|
2019-12-17T18:06:59.000Z
|
FastWindows.UI.Composition/CompositionShadow.cpp
|
kennykerr/Minesweeper
|
6f28abab141d80725beb746073d994833075b862
|
[
"MIT"
] | null | null | null |
FastWindows.UI.Composition/CompositionShadow.cpp
|
kennykerr/Minesweeper
|
6f28abab141d80725beb746073d994833075b862
|
[
"MIT"
] | 2
|
2019-09-21T13:15:58.000Z
|
2020-08-30T06:48:59.000Z
|
#include "pch.h"
#include "CompositionShadow.h"
#include "CompositionShadow.g.cpp"
namespace winrt::FastWindows::UI::Composition::implementation
{
}
| 18.75
| 61
| 0.773333
|
kennykerr
|
d3882f99f5ea555e5243b55d21491000e1af6b57
| 907
|
hpp
|
C++
|
android-31/android/widget/RemoteViews_RemoteResponse.hpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 12
|
2020-03-26T02:38:56.000Z
|
2022-03-14T08:17:26.000Z
|
android-30/android/widget/RemoteViews_RemoteResponse.hpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 1
|
2021-01-27T06:07:45.000Z
|
2021-11-13T19:19:43.000Z
|
android-29/android/widget/RemoteViews_RemoteResponse.hpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 3
|
2021-02-02T12:34:55.000Z
|
2022-03-08T07:45:57.000Z
|
#pragma once
#include "../../JObject.hpp"
namespace android::app
{
class PendingIntent;
}
namespace android::content
{
class Intent;
}
class JString;
namespace android::widget
{
class RemoteViews_RemoteResponse : public JObject
{
public:
// Fields
// QJniObject forward
template<typename ...Ts> explicit RemoteViews_RemoteResponse(const char *className, const char *sig, Ts...agv) : JObject(className, sig, std::forward<Ts>(agv)...) {}
RemoteViews_RemoteResponse(QJniObject obj);
// Constructors
RemoteViews_RemoteResponse();
// Methods
static android::widget::RemoteViews_RemoteResponse fromFillInIntent(android::content::Intent arg0);
static android::widget::RemoteViews_RemoteResponse fromPendingIntent(android::app::PendingIntent arg0);
android::widget::RemoteViews_RemoteResponse addSharedElement(jint arg0, JString arg1) const;
};
} // namespace android::widget
| 25.194444
| 167
| 0.755237
|
YJBeetle
|
d389d852a82d441ad303edaa0ff6fd33cf7150fc
| 1,236
|
cpp
|
C++
|
cpp/sowcpp/src/ch14/prog14-8.cpp
|
newnix/Forge
|
6d18105460fabc20592ed3c29813173cdb57d512
|
[
"BSD-3-Clause-Clear"
] | null | null | null |
cpp/sowcpp/src/ch14/prog14-8.cpp
|
newnix/Forge
|
6d18105460fabc20592ed3c29813173cdb57d512
|
[
"BSD-3-Clause-Clear"
] | null | null | null |
cpp/sowcpp/src/ch14/prog14-8.cpp
|
newnix/Forge
|
6d18105460fabc20592ed3c29813173cdb57d512
|
[
"BSD-3-Clause-Clear"
] | null | null | null |
// Practice program 14-8
// Found on page 830
// This program demonstrates the overloaded '-' and '+' operators
#include <iostream>
#include "feetInches.h"
using namespace std;
int main()
{
int feet, inch; // Hold the input for feet and inch
// Create three feetInches objects.
// Default args for constructors will be used.
feetInches first, second, third;
// Get a distance from the user
cout << "Enter a distance in feet and inches: ";
cin >> feet >> inch;
// Store the distance in the first object
first.setFeet(feet);
first.setInch(inch);
// Get another distance
cout << "Enter another distance in feet and inches: ";
cin >> feet >> inch;
// Store the distance in second
second.setFeet(feet);
second.setInch(inch);
// Assign first + second to third
third = first + second;
// Display the results
cout << "First + Second = ";
cout << third.getF() << " feet, ";
cout << third.getI() << " inches. \n";
// Assign first - second to third
third = first - second;
// Display the results again
cout << "First - Second = ";
cout << third.getF() << " feet, ";
cout << third.getI() << " inches.\n";
return 0;
}
| 23.320755
| 65
| 0.607605
|
newnix
|
d38c08a43bd10e184ae306b6061d067837ea318c
| 1,766
|
cpp
|
C++
|
async/examples/sockio/server/main.cpp
|
Rahul18728/cerl
|
8d90c03b2ffe397021bcb8c7198c713acf840bb4
|
[
"MIT"
] | 443
|
2015-03-14T06:04:45.000Z
|
2022-01-10T01:30:56.000Z
|
async/examples/sockio/server/main.cpp
|
Rahul18728/cerl
|
8d90c03b2ffe397021bcb8c7198c713acf840bb4
|
[
"MIT"
] | null | null | null |
async/examples/sockio/server/main.cpp
|
Rahul18728/cerl
|
8d90c03b2ffe397021bcb8c7198c713acf840bb4
|
[
"MIT"
] | 125
|
2015-03-14T13:08:04.000Z
|
2021-12-08T13:03:29.000Z
|
//test socket io through epoll
//
//#define CERL_VERBOSE
//#include <async/Io.h>
//#include <netinet/in.h>
//#include <arpa/inet.h>
//#include <async/Socket.h>
#include <async/Application.h>
#include <sys/times.h>
void cerl_callback run(LPVOID param)
{
cerl::FiberParam p(param);
int socket1 = cerl::listenSocket(5039);
if(socket1 == -1)
{
p.service->quit();
return;
}
cerl::ListenSocket s;
if (s.open_handle((SOCKET)socket1) != S_OK)
{
CERL_VLOG("test", ("Listen Socket failed\n"));
p.service->quit();
close(socket1);
return;
}
SOCKET clisock = s.accept();
if(clisock == 0)
{
CERL_VLOG("test", ("Accept failed\n"));
close((int)clisock);
p.service->quit();
return;
}
cerl::SocketFileObject fileObj;
fileObj.open_handle((SOCKET)clisock);
cerl::SocketFile file(fileObj);
printf("socket file opened.\n");
//char buf[64];
int data;
tms tm;
clock_t t = times(&tm);
printf("start: %d\n", t);
for(int i =0; i<10000; i++)
{
//printf("******************\nwait for client\n");
//printf("round # %d\n", i);
ptrdiff_t n = file.read_some(&data, sizeof(data));
if(n == 0)
{
printf("connection failed.\n");
break;
}
//printf("message from client: %s\n******************\n", buf);
//if(!strcmp(buf, "quit"))
// break;
//printf("******************\nresponse to client\n");
n = file.write_some(&data, sizeof(data));
if(n == 0)
{
printf("connection failed.\n");
break;
}
//printf("response over.\n******************\n");
}
NS_STDEXT::print("10000 msg in %d ms\n", (int)((double)(times(&tm)-t)*1000)/sysconf(_SC_CLK_TCK));
fileObj.close();
p.service->quit();
}
int main()
{
cerl::Application app;
app.run(run, NULL, 16000);
printf("leaving main fun\n");
return 0;
}
| 17.485149
| 99
| 0.593431
|
Rahul18728
|
d394cb153c37f5319d6618c9646ad971c0b739f1
| 12,604
|
cpp
|
C++
|
src/server/Xml/XslDoc.cpp
|
anewholm/generalserver
|
99321562921c317f1ef14a2b84abfe91f0f871b6
|
[
"X11"
] | null | null | null |
src/server/Xml/XslDoc.cpp
|
anewholm/generalserver
|
99321562921c317f1ef14a2b84abfe91f0f871b6
|
[
"X11"
] | null | null | null |
src/server/Xml/XslDoc.cpp
|
anewholm/generalserver
|
99321562921c317f1ef14a2b84abfe91f0f871b6
|
[
"X11"
] | null | null | null |
//platform agnostic file
#include "Xml/XslDoc.h"
#include "IXml/IXmlBaseNode.h"
#include "IXml/IXmlLibrary.h"
#include "IXml/IXslNode.h"
#include "Xml/XmlAdminQueryEnvironment.h"
#include "Debug.h"
#include "Xml/XmlNodeList.h"
#include "Utilities/container.c"
using namespace std;
namespace general_server {
//---------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------
const char *XslDoc::name() const {
const XmlAdminQueryEnvironment ibqe(mmParent(), this); //XslDoc::name()
const char *sName;
const IXmlBaseDoc *pDocType = queryInterface((const IXmlBaseDoc*) 0);
const IXmlBaseNode *pRootNode = pDocType->rootNode(&ibqe);
if (pRootNode) sName = pRootNode->attributeValue(&ibqe, "name", NAMESPACE_REPOSITORY);
else sName = MM_STRDUP("stylesheet");
return sName;
}
//---------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------
XslTransformContext::XslTransformContext(const IMemoryLifetimeOwner *pMemoryLifetimeOwner, const IXmlQueryEnvironment *pOwnerQE):
MemoryLifetimeOwner(pMemoryLifetimeOwner),
m_pOwnerQE(pOwnerQE)
{
assert(m_pOwnerQE);
}
XslTransformContext::~XslTransformContext() {}
void XslTransformContext::setQueryEnvironment(const IXmlQueryEnvironment *pOwnerQE) {m_pOwnerQE = pOwnerQE;assert(m_pOwnerQE);}
const IXmlQueryEnvironment *XslTransformContext::ownerQE() const {return m_pOwnerQE;}
const char *XslTransformContext::currentSourceNodeXPath() const {
const XmlAdminQueryEnvironment ibqe_error_reporting(this, sourceDoc());
const char *sXPath = 0;
const IXmlBaseNode *pNode = 0;
try {
if (pNode = sourceNode(this)) sXPath = pNode->uniqueXPathToNode(&ibqe_error_reporting);
} catch (ExceptionBase &eb) {
sXPath = eb.toString();
}
//free up
if (pNode) delete pNode;
return (sXPath ? sXPath : "<unknown>");
}
const char *XslTransformContext::currentXSLTemplateXPath() const {
const XmlAdminQueryEnvironment ibqe_error_reporting(this, commandDoc());
const char *sXPath = 0;
const IXslCommandNode *pNode = 0;
const IXmlBaseNode *pNodeType = 0;
try {
if (pNode = templateNode(this)) {
if (pNodeType = pNode->queryInterface((const IXmlBaseNode*) 0))
sXPath = pNodeType->uniqueXPathToNode(&ibqe_error_reporting);
}
} catch (ExceptionBase &eb) {
sXPath = eb.toString();
}
//free up
if (pNode) delete pNode;
return (sXPath ? sXPath : "<unknown>");
}
const char *XslTransformContext::currentXSLCommandXPath() const {
const XmlAdminQueryEnvironment ibqe_error_reporting(this, commandDoc());
const char *sXPath = 0;
const IXmlBaseNode *pNode = 0;
try {
if (pNode = instructionNode(this)) sXPath = pNode->uniqueXPathToNode(&ibqe_error_reporting);
} catch (ExceptionBase &eb) {
sXPath = eb.toString();
}
//free up
if (pNode) delete pNode;
return (sXPath ? sXPath : "<unknown>");
}
void XslTransformContext::handleError(const char *sErrorMessage) {
//when the native XML library throws an XPATH error
// we arrive here in the agnostic layer to deal with it
// caught by our native library generic error handler
// which will bubble up to the XSLTException catch layer if we throw here
//XPathException() can also bubble up from our own custom xpath functions
// directly to the XSLTException catch layer
// without the native library generic error handler getting involved
IXslTransformContext *pTC = 0;
const IXmlBaseNode *pCommandNode = 0;
iErrorPolicy er = throw_error;
//error policies
if (pTC = m_pOwnerQE->transformContext()) {
if (pCommandNode = pTC->literalCommandNode(m_pOwnerQE)) er = pCommandNode->errorPolicy(); //pQE as MM
}
//free up
if (pCommandNode) delete pCommandNode;
//if (pTC) delete pTC; //server freed
if (er == throw_error) throw XSLTException(this, MM_STRDUP(sErrorMessage));
else Debug::warn("error suppressed by xsl:error-policy");
}
//---------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------
XslXPathFunctionContext::XslXPathFunctionContext(const IMemoryLifetimeOwner *pMemoryLifetimeOwner, const IXmlQueryEnvironment *pOwnerQE):
MemoryLifetimeOwner(pMemoryLifetimeOwner), //usually just a writeable pOwnerQE
m_pOwnerQE(pOwnerQE)
{
assert(m_pOwnerQE);
}
XslXPathFunctionContext::~XslXPathFunctionContext() {}
void XslXPathFunctionContext::setQueryEnvironment(const IXmlQueryEnvironment *pOwnerQE) {m_pOwnerQE = pOwnerQE;assert(m_pOwnerQE);}
const IXmlQueryEnvironment *XslXPathFunctionContext::ownerQE() const {return m_pOwnerQE;}
void XslXPathFunctionContext::handleError(const char *sErrorMessage) {
//when the native XML library throws an XPATH error
// we arrive here in the agnostic layer to deal with it
// caught by our native library generic error handler
// which will bubble up to the XSLTException catch layer if we throw here
//XPathException() can also bubble up from our own custom xpath functions
// directly to the XSLTException catch layer
// without the native library generic error handler getting involved
IXslTransformContext *pTC = 0;
const IXmlBaseNode *pCommandNode = 0;
iErrorPolicy er = throw_error;
//error policies
if (pTC = m_pOwnerQE->transformContext()) {
if (pCommandNode = pTC->literalCommandNode(m_pOwnerQE)) er = pCommandNode->errorPolicy(); //pQE as MM
}
//free up
if (pCommandNode) delete pCommandNode;
//if (pTC) delete pTC; //server freed
if (er == throw_error) throw XPathException(this, MM_STRDUP(sErrorMessage));
else Debug::warn("error suppressed by xsl:error-policy");
}
const char *XslXPathFunctionContext::currentXSLCommandXPath() const {
//caller frees result
const char *ret = 0;
IXslTransformContext *pTCtxt;
if (pTCtxt = m_pOwnerQE->transformContext()) ret = pTCtxt->currentXSLCommandXPath();
//free up
//if (pTCtxt) delete pTCtxt; //pointer in to pQE
return ret;
}
const char *XslXPathFunctionContext::currentXSLTemplateXPath() const {
//caller frees result
const char *ret = 0;
IXslTransformContext *pTCtxt;
if (pTCtxt = m_pOwnerQE->transformContext()) ret = pTCtxt->currentXSLTemplateXPath();
//free up
//if (pTCtxt) delete pTCtxt; //pointer in to pQE
return ret;
}
const char *XslXPathFunctionContext::toString() const {
return xpath();
}
IXmlBaseNode *XslXPathFunctionContext::popInterpretNodeFromXPathFunctionCallStack(const bool bThrowOnNot1) {
XmlNodeList<IXmlBaseNode>::iterator iNode;
IXmlBaseNode *pNode = 0;
XmlNodeList<IXmlBaseNode> *pNodes = 0;
UNWIND_EXCEPTION_BEGIN {
if (pNodes = popInterpretNodeListFromXPathFunctionCallStack()) {
if (bThrowOnNot1 && pNodes->size() != 1) throw XPathNot1Nodes(this);
else {
for (iNode = pNodes->begin(); iNode != pNodes->end(); iNode++) {
if (!pNode) pNode = *iNode;
else delete *iNode;
}
}
}
} UNWIND_EXCEPTION_END;
//free up
if (pNodes) delete pNodes;
UNWIND_EXCEPTION_THROW;
return pNode;
}
//---------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------
XslDoc::XslDoc(IXslTransformContext *pCtxt):
m_pCtxt(pCtxt),
m_pSourceNode(0)
{}
XslDoc::XslDoc():
m_pCtxt(0),
m_pSourceNode(0)
{}
const IXmlBaseNode *XslDoc::sourceNode() const {
return m_pSourceNode;
}
const IXmlBaseDoc *XslDoc::sourceDoc() const {
//m_pSourceNode will also lock the source document
return (m_pSourceNode ? m_pSourceNode->document() : NULL);
}
const IXmlBaseNode *XslDoc::sourceNode(const IXmlBaseNode *pSourceNode) {
assert(pSourceNode);
m_pSourceNode = pSourceNode;
return m_pSourceNode;
}
XmlNodeList<IXmlBaseNode> *XslDoc::includes() {
XmlAdminQueryEnvironment ibqe(this, this); //includes()
return getMultipleNodes(&ibqe, "/xsl:stylesheet/xsl:include[@href and not(@xpath)]");
}
size_t XslDoc::translateIncludes(XmlNodeList<IXmlBaseNode> *pvIncludes, IXmlQueryEnvironment *pMasterDocQE, const IXmlBaseNode *pIncludeDirectoryNode) {
//this is enacted on a COPY of the XSL node in the transform() function
//this is a live update of xsl:include @hrefs. Not a copy
//USED mostly on client-side relative @hrefs that need translating to server-side @xpath
//location of xsl:include same as:
// C++ clearMyCachedStylesheetsRecursive()
// C++ translateIncludes() @href => @xpath
// LibXml2: xsl:include processing (of @xpath) during server side compilation
// map_url_to_stylesheet_model.xsl REST based client xsl:include requests
// AJAX client_stylesheet_transform.xsl xsl:include include directly in main xsl:stylesheet request
size_t iUpdates = 0;
const IXmlBaseNode *pIncludeNode = 0,
*pIncludedNode = 0;
const IXslStylesheetNode *pIncludedStylesheetNode = 0;
typename XmlNodeList<IXmlBaseNode>::iterator iInclude;
const char *sHREF = 0,
*sXPath = 0;
//get and alter @hrefs, if @xpath not there...
//works only from the top level xsl:stylesheet node
//xsl:includes have been altered in LibXml2 to accept @xpath instead of @href which is faster
ensurePrefixedNamespaceDefinition(NAMESPACE_XSL_ALIAS, NAMESPACE_XSL);
UNWIND_EXCEPTION_BEGIN {
//NOTE: the disembodied stylesheet should have an xpath pointer to it's original parent in the world
for (iInclude = pvIncludes->begin(); iInclude != pvIncludes->end(); iInclude++) {
pIncludeNode = (*iInclude);
sXPath = pIncludeNode->attributeValue(pMasterDocQE, "xpath");
if (sXPath) {
if (pIncludedNode = pIncludeDirectoryNode->getSingleNode(pMasterDocQE, sXPath))
pIncludedStylesheetNode = pIncludedNode->queryInterface((const IXslStylesheetNode*) 0);
} else {
sHREF = pIncludeNode->attributeValue(pMasterDocQE, "href");
if (!sHREF) throw FailedToResolveXSLIncludePath(this, MM_STRDUP("no @xpath or @href"));
if (xmlLibrary()->maybeAbsoluteXPath(pMasterDocQE, sHREF)) Debug::report("xsl:include @href=[%s] not verified because cannot resolve class references against non-ids-populated disembodied new doc yet", sXPath);
pIncludedStylesheetNode = pIncludeDirectoryNode->relativeXSLIncludeFileSystemPathToXSLStylesheetNode(pMasterDocQE, sHREF);
}
//TODO: and recurse sub-includes
//GDB: p *dynamic_cast<LibXmlBaseDoc*>(this)->m_oDoc
if (!pIncludedStylesheetNode) throw FailedToResolveXSLIncludePath(this, MM_STRDUP("xpath result empty"));
else {
//register xpath parameter for later
//TODO: should we TXml this register xpath parameter for later? better that it is dynamic?
pIncludeNode->setAttribute(pMasterDocQE, "xpath", sXPath);
pIncludeNode->removeAttribute(pMasterDocQE, "href");
iUpdates++;
}
//free up
if (pIncludedStylesheetNode) {delete pIncludedStylesheetNode; pIncludedStylesheetNode = 0;}
if (sHREF) {MM_FREE(sHREF); sHREF = 0;}
if (sXPath) {MM_FREE(sXPath); sXPath = 0;}
} //for loop
} UNWIND_EXCEPTION_END;
//free up
if (pIncludedStylesheetNode) delete pIncludedStylesheetNode;
if (sHREF) MM_FREE(sHREF);
if (sXPath) MM_FREE(sXPath);
UNWIND_EXCEPTION_THROW;
return iUpdates;
}
}
| 38.901235
| 220
| 0.625754
|
anewholm
|
d39753420daa127b7f465efa38881a75a004d213
| 25,873
|
cpp
|
C++
|
src/test/test_convlayer.cpp
|
lsh123/yann
|
4a12b7c1ee2d89d34772d647586b3018df6997db
|
[
"MIT"
] | 2
|
2019-08-22T18:14:44.000Z
|
2020-01-01T10:25:07.000Z
|
src/test/test_convlayer.cpp
|
lsh123/yann
|
4a12b7c1ee2d89d34772d647586b3018df6997db
|
[
"MIT"
] | null | null | null |
src/test/test_convlayer.cpp
|
lsh123/yann
|
4a12b7c1ee2d89d34772d647586b3018df6997db
|
[
"MIT"
] | null | null | null |
//
// Add --log_level=message to see the messages!
//
#include <boost/test/unit_test.hpp>
#include <sstream>
#include "core/functions.h"
#include "core/utils.h"
#include "core/random.h"
#include "core/training.h"
#include "layers/convlayer.h"
#include "test_utils.h"
#include "timer.h"
#include "test_layers.h"
using namespace std;
using namespace boost;
using namespace boost::unit_test;
using namespace yann;
using namespace yann::test;
struct ConvolutionalLayerTestFixture
{
ConvolutionalLayerTestFixture()
{
}
~ConvolutionalLayerTestFixture()
{
}
inline MatrixSize find_max_pos(const RefConstVector & vv)
{
MatrixSize pos = 0;
vv.maxCoeff(&pos);
return pos;
}
void conv_perf_test(const MatrixSize & size, const MatrixSize & filter_size, const size_t & epochs)
{
BOOST_TEST_MESSAGE("*** ConvOp Performance test with"
<< " size=" << size
<< ", filter_size=" << filter_size
<< ", epochs=" << epochs
);
Matrix input(size, size);
Matrix filter(filter_size, filter_size);
Matrix output(size + filter_size, size + filter_size);
{
Timer timer("Random generation");
unique_ptr<RandomGenerator> gen = RandomGenerator::normal_distribution(0, 1);
gen->generate(input);
gen->generate(filter);
}
output.resize(ConvolutionalLayer::get_conv_output_rows(size, filter_size),
ConvolutionalLayer::get_conv_output_cols(size, filter_size));
{
Timer timer("Test plus_conv");
for(auto ii = epochs; ii > 0; --ii) {
ConvolutionalLayer::plus_conv(input, filter, output);
}
}
output.resize(ConvolutionalLayer::get_full_conv_output_rows(size, filter_size),
ConvolutionalLayer::get_full_conv_output_cols(size, filter_size));
{
Timer timer("Test full_conv");
for(auto ii = epochs; ii > 0; --ii) {
ConvolutionalLayer::full_conv(input, filter, output);
}
}
}
void conv_perf_batch_test(const MatrixSize & batch_size, const MatrixSize & size, const MatrixSize & filter_size, const size_t & epochs)
{
BOOST_TEST_MESSAGE("*** ConvOp Performance batch test with"
<< " batch_size=" << batch_size
<< ", size=" << size
<< ", filter_size=" << filter_size
<< ", epochs=" << epochs
);
VectorBatch input, output;
Matrix filter(filter_size, filter_size);
resize_batch(input, batch_size, size * size);
{
Timer timer("Random generation");
unique_ptr<RandomGenerator> gen = RandomGenerator::normal_distribution(0, 1);
gen->generate(input);
gen->generate(filter);
}
resize_batch(output, batch_size, ConvolutionalLayer::get_conv_output_size(size, size, filter_size));
{
Timer timer("Test plus_conv");
for(auto ii = epochs; ii > 0; --ii) {
ConvolutionalLayer::plus_conv(input, size, size, filter, output);
}
}
resize_batch(output, batch_size, ConvolutionalLayer::get_full_conv_output_size(size, size, filter_size));
{
Timer timer("Test full_conv");
for(auto ii = epochs; ii > 0; --ii) {
ConvolutionalLayer::full_conv(input, size, size, filter, output);
}
}
}
}; // struct ConvolutionalLayerTestFixture
BOOST_FIXTURE_TEST_SUITE(ConvolutionalLayerTest, ConvolutionalLayerTestFixture);
BOOST_AUTO_TEST_CASE(IO_Test)
{
BOOST_TEST_MESSAGE("*** ConvolutionalLayer IO test ...");
const MatrixSize input_cols = 5;
const MatrixSize input_rows = 3;
const MatrixSize filter_size = 2;
auto one = make_unique<ConvolutionalLayer>(input_cols, input_rows, filter_size);
one->init(Layer::InitMode_Random, boost::none);
BOOST_TEST_MESSAGE("ConvolutionalLayer before writing to file: " << "\n" << *one);
ostringstream oss;
oss << *one;
BOOST_CHECK(!oss.fail());
auto two = make_unique<ConvolutionalLayer>(input_cols, input_rows, filter_size);
std::istringstream iss(oss.str());
iss >> *two;
BOOST_CHECK(!iss.fail());
BOOST_TEST_MESSAGE("ConvolutionalLayer after loading from file: " << "\n" << *two);
BOOST_CHECK(one->is_equal(*two, TEST_TOLERANCE));
}
BOOST_AUTO_TEST_CASE(ConvOp_Test)
{
BOOST_TEST_MESSAGE("*** Convolutional operation test ...");
const size_t image_size = 4;
const size_t max_filter_size = 4;
Matrix filter(max_filter_size, max_filter_size);
Matrix input(image_size, image_size);
Matrix expected(image_size, image_size);
Matrix output(image_size, image_size);
//////////////////////////////////////////////////////////////////////
//
// Test different filter sizes
//
input <<
1, 2, 3, 4,
5, 6, 7, 8,
9, 10, 11, 12,
13, 14, 15, 16;
// 1x1
filter.resize(1, 1);
filter <<
3;
expected.resize(4, 4);
expected <<
3, 6, 9, 12,
15, 18, 21, 24,
27, 30, 33, 36,
39, 42, 45, 48;
output.resizeLike(expected);
{
// ensure we don't do allocations in eigen
BlockAllocations block;
ConvolutionalLayer::plus_conv(input, filter, output);
}
BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE));
// 2x1
filter.resize(2, 1);
filter <<
2,
3;
expected.resize(3, 4);
expected <<
17, 22, 27, 32,
37, 42, 47, 52,
57, 62, 67, 72;
output.resizeLike(expected);
{
// ensure we don't do allocations in eigen
BlockAllocations block;
ConvolutionalLayer::plus_conv(input, filter, output);
}
BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE));
// 2x2
filter.resize(2, 2);
filter <<
1, 2,
3, 4;
expected.resize(3, 3);
expected <<
44, 54, 64,
84, 94, 104,
124, 134, 144;
output.resizeLike(expected);
{
// ensure we don't do allocations in eigen
BlockAllocations block;
ConvolutionalLayer::plus_conv(input, filter, output);
}
BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE));
// 2x3
filter.resize(2, 3);
filter <<
1, 2, 3,
4, 5, 6;
expected.resize(3, 2);
expected <<
106, 127,
190, 211,
274, 295;
output.resizeLike(expected);
{
// ensure we don't do allocations in eigen
BlockAllocations block;
ConvolutionalLayer::plus_conv(input, filter, output);
}
BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE));
// 3x3
filter.resize(3, 3);
filter <<
1, 2, 3,
4, 5, 6,
7, 8, 9;
expected.resize(2, 2);
expected <<
348, 393,
528, 573;
output.resizeLike(expected);
{
// ensure we don't do allocations in eigen
BlockAllocations block;
ConvolutionalLayer::plus_conv(input, filter, output);
}
BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE));
// 4x4
filter.resize(4, 4);
filter <<
1, 2, 3, 4,
5, 6, 7, 8,
9, 10, 11, 12,
13, 14, 15, 16;
expected.resize(1, 1);
expected <<
1496;
output.resizeLike(expected);
{
// ensure we don't do allocations in eigen
BlockAllocations block;
ConvolutionalLayer::plus_conv(input, filter, output);
}
BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE));
}
BOOST_AUTO_TEST_CASE(ConvOp_Batch_Test)
{
BOOST_TEST_MESSAGE("*** Convolutional operation batch test ...");
const size_t max_filter_size = 4;
const MatrixSize image_size = 4;
const MatrixSize input_size = image_size * image_size;
const MatrixSize batch_size = 2;
Matrix filter(max_filter_size, max_filter_size);
VectorBatch input, output, expected;
//////////////////////////////////////////////////////////////////////
//
// Test different filter sizes
//
resize_batch(input, batch_size, input_size);
input << 1, 0, 1, 0,
0, 1, 0, 0,
1, 0, 1, 0,
0, 0, 0, 0,
///////////
0, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 0;
// 1x1
filter.resize(1, 1);
filter << 1;
resize_batch(expected, batch_size, 4 * 4);
expected << 1, 0, 1, 0,
0, 1, 0, 0,
1, 0, 1, 0,
0, 0, 0, 0,
///////////
0, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 0;
output.resizeLike(expected);
{
// ensure we don't do allocations in eigen
BlockAllocations block;
ConvolutionalLayer::plus_conv(input, image_size, image_size, filter, output);
}
BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE));
// 2x1
filter.resize(2, 1);
filter << 1,
1;
resize_batch(expected, batch_size, 3 * 4);
expected << 1, 1, 1, 0,
1, 1, 1, 0,
1, 0, 1, 0,
///////////
0, 1, 0, 0,
0, 1, 1, 0,
0, 0, 1, 0;
output.resizeLike(expected);
{
// ensure we don't do allocations in eigen
BlockAllocations block;
ConvolutionalLayer::plus_conv(input, image_size, image_size, filter, output);
}
BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE));
// 2x2
filter.resize(2, 2);
filter << 1, 1,
1, 0;
resize_batch(expected, batch_size, 3 * 3);
expected << 1, 2, 1,
2, 1, 1,
1, 1, 1,
////////
0, 1, 0,
1, 1, 1,
0, 1, 1;
output.resizeLike(expected);
{
// ensure we don't do allocations in eigen
BlockAllocations block;
ConvolutionalLayer::plus_conv(input, image_size, image_size, filter, output);
}
BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE));
// 3x2
filter.resize(3, 2);
filter << 1, 1,
1, 0,
1, 0;
resize_batch(expected, batch_size, 2 * 3);
expected << 2, 2, 2,
2, 1, 1,
////////
0, 1, 1,
1, 1, 1;
output.resizeLike(expected);
{
// ensure we don't do allocations in eigen
BlockAllocations block;
ConvolutionalLayer::plus_conv(input, image_size, image_size, filter, output);
}
BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE));
// 3x3
filter.resize(3, 3);
filter << 1, 1, 1,
1, 0, 0,
1, 0, 1;
resize_batch(expected, batch_size, 2 * 2);
expected << 4, 2,
2, 1,
/////
1, 1,
1, 1;
output.resizeLike(expected);
{
// ensure we don't do allocations in eigen
BlockAllocations block;
ConvolutionalLayer::plus_conv(input, image_size, image_size, filter, output);
}
BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE));
// 4x4
filter.resize(4, 4);
filter << 1, 1, 1, 1,
1, 1, 0, 0,
1, 0, 1, 0,
1, 0, 0, 1;
resize_batch(expected, batch_size, 1 * 1);
expected << 5,
//
2;
output.resizeLike(expected);
{
// ensure we don't do allocations in eigen
BlockAllocations block;
ConvolutionalLayer::plus_conv(input, image_size, image_size, filter, output);
}
BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE));
}
BOOST_AUTO_TEST_CASE(FullConvOp_Test)
{
BOOST_TEST_MESSAGE("*** Full convolutional operation test ...");
const size_t image_size = 3;
const size_t max_filter_size = 2;
Matrix filter(max_filter_size, max_filter_size);
Matrix input(image_size, image_size);
Matrix expected(image_size + max_filter_size, image_size + max_filter_size);
Matrix output(image_size + max_filter_size, image_size + max_filter_size);
//////////////////////////////////////////////////////////////////////
//
// Test different filter sizes
//
input.resize(image_size, image_size);
input <<
1, 2, 3,
4, 5, 6,
7, 8, 9;
// 1x1
filter.resize(1, 1);
filter <<
3;
expected.resize(3, 3);
expected <<
3, 6, 9,
12, 15, 18,
21, 24, 27;
output.resizeLike(expected);
{
// ensure we don't do allocations in eigen
BlockAllocations block;
ConvolutionalLayer::full_conv(input, filter, output);
}
BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE));
// 2x2
filter.resize(2, 2);
filter <<
1, 2,
3, 4;
expected.resize(4, 4);
expected <<
4, 11, 18, 9,
18, 37, 47, 21,
36, 67, 77, 33,
14, 23, 26, 9;
output.resizeLike(expected);
{
// ensure we don't do allocations in eigen
BlockAllocations block;
ConvolutionalLayer::full_conv(input, filter, output);
}
BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE));
// 2x3
filter.resize(2, 3);
filter <<
1, 2, 3,
4, 5, 6;
expected.resize(4, 5);
expected <<
6, 17, 32, 23, 12,
27, 58, 91, 58, 27,
54, 106, 154, 94, 42,
21, 38, 50, 26, 9;
output.resizeLike(expected);
{
// ensure we don't do allocations in eigen
BlockAllocations block;
ConvolutionalLayer::full_conv(input, filter, output);
}
BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE));
// 3x3
filter.resize(3, 3);
filter <<
1, 2, 3,
4, 5, 6,
7, 8, 9;
expected.resize(5, 5);
expected <<
9, 26, 50, 38, 21,
42, 94, 154, 106, 54,
90, 186, 285, 186, 90,
54, 106, 154, 94, 42,
21, 38, 50, 26, 9;
output.resizeLike(expected);
{
// ensure we don't do allocations in eigen
BlockAllocations block;
ConvolutionalLayer::full_conv(input, filter, output);
}
BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE));
}
BOOST_AUTO_TEST_CASE(FullConvOp_Batch_Test)
{
BOOST_TEST_MESSAGE("*** Full convolutional operation batch test ...");
const size_t max_filter_size = 4;
const MatrixSize image_size = 3;
const MatrixSize input_size = image_size * image_size;
const MatrixSize batch_size = 3;
Matrix filter(max_filter_size, max_filter_size);
VectorBatch input, output, expected;
//////////////////////////////////////////////////////////////////////
//
// Test different filter sizes
//
resize_batch(input, batch_size, input_size);
input << 1, 0, 1,
0, 1, 0,
1, 0, 0,
///////
0, 0, 0,
0, 0, 0,
0, 0, 0,
///////
1, 1, 1,
1, 1, 1,
1, 1, 1;
// 1x1
filter.resize(1, 1);
filter << 1;
resize_batch(expected, batch_size, 3 * 3);
expected << 1, 0, 1,
0, 1, 0,
1, 0, 0,
///////
0, 0, 0,
0, 0, 0,
0, 0, 0,
///////
1, 1, 1,
1, 1, 1,
1, 1, 1;
output.resizeLike(expected);
{
// ensure we don't do allocations in eigen
BlockAllocations block;
ConvolutionalLayer::full_conv(input, image_size, image_size, filter, output);
}
BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE));
// 2x2
filter.resize(2, 2);
filter << 1, 1,
1, 0;
resize_batch(expected, batch_size, 4 * 4);
expected << 0, 1, 0, 1,
1, 1, 2, 1,
0, 2, 1, 0,
1, 1, 0, 0,
//////////
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
//////////
0, 1, 1, 1,
1, 3, 3, 2,
1, 3, 3, 2,
1, 2, 2, 1;
output.resizeLike(expected);
{
// ensure we don't do allocations in eigen
BlockAllocations block;
ConvolutionalLayer::full_conv(input, image_size, image_size, filter, output);
}
BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE));
// 2x3
filter.resize(2, 3);
filter << 1, 1, 1,
1, 0, 0;
resize_batch(expected, batch_size, 4 * 5);
expected << 0, 0, 1, 0, 1,
1, 1, 2, 2, 1,
0, 1, 2, 1, 0,
1, 1, 1, 0, 0,
/////////////
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
/////////////
0, 0, 1, 1, 1,
1, 2, 4, 3, 2,
1, 2, 4, 3, 2,
1, 2, 3, 2, 1;
output.resizeLike(expected);
{
// ensure we don't do allocations in eigen
BlockAllocations block;
ConvolutionalLayer::full_conv(input, image_size, image_size, filter, output);
}
BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE));
// 3x3
filter.resize(3, 3);
filter << 1, 1, 1,
1, 0, 0,
1, 0, 1;
resize_batch(expected, batch_size, 5 * 5);
expected << 1, 0, 2, 0, 1,
0, 1, 1, 1, 1,
2, 1, 3, 2, 1,
0, 1, 2, 1, 0,
1, 1, 1, 0, 0,
/////////////
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
/////////////
1, 1, 2, 1, 1,
1, 1, 3, 2, 2,
2, 3, 6, 4, 3,
1, 2, 4, 3, 2,
1, 2, 3, 2, 1;
output.resizeLike(expected);
{
// ensure we don't do allocations in eigen
BlockAllocations block;
ConvolutionalLayer::full_conv(input, image_size, image_size, filter, output);
}
BOOST_CHECK(expected.isApprox(output, TEST_TOLERANCE));
}
BOOST_AUTO_TEST_CASE(Rotate180_Test)
{
BOOST_TEST_MESSAGE("*** Rotate180 test ...");
const MatrixSize input0_size = 2;
Matrix input0(input0_size, input0_size);
input0 << 1, 2,
3, 4;
Matrix expected0(input0_size, input0_size);
expected0 << 4, 3,
2, 1;
Matrix output0(input0_size, input0_size);
{
// ensure we don't do allocations in eigen
BlockAllocations block;
ConvolutionalLayer::rotate180(input0, output0);
}
BOOST_CHECK(expected0.isApprox(output0, TEST_TOLERANCE));
const MatrixSize input1_size = 3;
Matrix input1(input1_size, input1_size);
input1 << 1, 2, 3,
4, 5, 6,
7, 8, 9;
Matrix expected1(input1_size, input1_size);
expected1 << 9, 8, 7,
6, 5, 4,
3, 2, 1;
Matrix output1(input1_size, input1_size);
{
// ensure we don't do allocations in eigen
BlockAllocations block;
ConvolutionalLayer::rotate180(input1, output1);
}
BOOST_CHECK(expected1.isApprox(output1, TEST_TOLERANCE));
}
BOOST_AUTO_TEST_CASE(FeedForward_Test)
{
BOOST_TEST_MESSAGE("*** ConvolutionalLayer FeedForward test ...");
const MatrixSize image_size = 5;
const MatrixSize input_size = image_size * image_size;
const MatrixSize filter_size = 3;
const MatrixSize batch_size = 2;
const MatrixSize output_size = ConvolutionalLayer::get_conv_output_size(
image_size, image_size, filter_size);
Matrix ww(filter_size, filter_size);
VectorBatch input, expected_output;
resize_batch(input, batch_size, input_size);
resize_batch(expected_output, batch_size, output_size);
ww <<
1, 0, 1,
0, 1, 0,
1, 0, 1;
input <<
1, 0, 1, 0, 0,
0, 1, 0, 0, 0,
1, 0, 1, 0, 0,
0, 0, 0, 0, 0,
0, 0, 0, 0, 1,
/////////////
0, 0, 1, 0, 1,
0, 1, 0, 1, 0,
1, 0, 1, 0, 1,
0, 1, 0, 1, 0,
1, 0, 1, 0, 0;
expected_output <<
5.5, 0.5, 2.5,
0.5, 2.5, 0.5,
2.5, 0.5, 2.5,
/////////////
4.5, 0.5, 5.5,
0.5, 5.5, 0.5,
5.5, 0.5, 4.5;
auto layer = make_unique<ConvolutionalLayer>(image_size, image_size, filter_size);
BOOST_CHECK(layer);
layer->set_activation_function(make_unique<IdentityFunction>());
layer->set_values(ww, 0.5);
test_layer_feedforward(*layer, input, expected_output);
}
BOOST_AUTO_TEST_CASE(Backprop_Test)
{
BOOST_TEST_MESSAGE("*** ConvolutionalLayer backprop test ...");
const MatrixSize image_size = 3;
const MatrixSize input_size = image_size * image_size;
const MatrixSize filter_size = 2;
const MatrixSize output_size = ConvolutionalLayer::get_conv_output_size(
image_size, image_size, filter_size);
const double learning_rate = 0.1;
const size_t epochs = 100;
const MatrixSize batch_size = 2;
Matrix ww(filter_size, filter_size);
VectorBatch input, expected_output;
resize_batch(input, batch_size, input_size);
resize_batch(expected_output, batch_size, output_size);
ww <<
0, 0,
0, 1;
input <<
0, 0, 0,
0, 1, 1,
0, 1, 0,
////////
0, 0, 0,
1, 1, 0,
1, 0, 0;
expected_output <<
1, 0,
0, 0,
////
0, 0,
1, 0;
auto layer = make_unique<ConvolutionalLayer>(image_size, image_size, filter_size);
BOOST_CHECK(layer);
layer->set_activation_function(make_unique<IdentityFunction>());
layer->set_values(ww, 0.0);
test_layer_backprop(
*layer,
input,
boost::none,
expected_output,
make_unique<QuadraticCost>(),
learning_rate,
epochs
);
}
BOOST_AUTO_TEST_CASE(Backprop_OnVector_Test)
{
BOOST_TEST_MESSAGE("*** ConvolutionalLayer backprop on vector test ...");
const MatrixSize shift = 4;
const MatrixSize image_size = 3;
const MatrixSize input_size = image_size * image_size;
const MatrixSize filter_size = 2;
const MatrixSize output_size = ConvolutionalLayer::get_conv_output_size(
image_size, image_size, filter_size);
const double learning_rate = 0.1;
const size_t epochs = 100;
const MatrixSize batch_size = 2;
Matrix ww(filter_size, filter_size);
Vector input_buffer(shift + batch_size * input_size);
MapMatrix input(input_buffer.data() + shift, batch_size, input_size); // this assumes RowMajor layout
VectorBatch expected_output;
resize_batch(expected_output, batch_size, output_size);
ww <<
0, 0,
0, 1;
input_buffer <<
1, 2, 3, 4, // shift
0, 0, 0,
0, 1, 1,
0, 1, 0,
////////
0, 0, 0,
1, 1, 0,
1, 0, 0;
expected_output <<
1, 0,
0, 0,
////
0, 0,
1, 0;
auto layer = make_unique<ConvolutionalLayer>(image_size, image_size, filter_size);
BOOST_CHECK(layer);
layer->set_activation_function(make_unique<IdentityFunction>());
layer->set_values(ww, 0.0);
test_layer_backprop(
*layer,
input,
boost::none,
expected_output,
make_unique<QuadraticCost>(),
learning_rate,
epochs
);
}
BOOST_AUTO_TEST_CASE(Training_WithIdentity_Test)
{
BOOST_TEST_MESSAGE("*** ConvolutionalLayer with Identity activation training test ...");
const MatrixSize image_rows = 6;
const MatrixSize image_cols = 3;
const MatrixSize input_size = image_rows * image_cols;
const MatrixSize filter_size = 2;
const MatrixSize output_size = ConvolutionalLayer::get_conv_output_size(image_rows, image_cols, filter_size);
const MatrixSize batch_size = 2;
VectorBatch input, expected;
resize_batch(input, batch_size, input_size);
resize_batch(expected, batch_size, output_size);
input <<
0.01, 0.02, 0.11, 0.10, 0.13, 0.18,
0.03, 0.04, 0.12, 0.09, 0.14, 0.17,
0.05, 0.06, 0.07, 0.08, 0.15, 0.16,
///////////////////////////////////
0.02, 0.06, 0.08, 0.10, 0.13, 0.14,
0.03, 0.02, 0.07, 0.09, 0.16, 0.15,
0.04, 0.05, 0.13, 0.11, 0.16, 0.18;
expected <<
0.347, 0.478, 0.308, 0.462, 0.378,
0.492, 0.343, 0.415, 0.409, 0.480,
//////////////////////////////////
0.373, 0.446, 0.282, 0.368, 0.395,
0.442, 0.332, 0.492, 0.429, 0.530;
// create layer
auto layer = make_unique<ConvolutionalLayer>(image_rows, image_cols, filter_size);
BOOST_CHECK(layer);
layer->set_activation_function(make_unique<IdentityFunction>());
layer->init(Layer::InitMode_Zeros, boost::none);
// test
test_layer_training(
*layer,
input,
expected,
batch_size, // tests num
make_unique<QuadraticCost>(),
0.09, // learning rate
8000 // epochs
);
}
BOOST_AUTO_TEST_CASE(Training_WithSigmoid_Test)
{
BOOST_TEST_MESSAGE("*** ConvolutionalLayer with Sigmoid activation training test ...");
const MatrixSize image_rows = 6;
const MatrixSize image_cols = 3;
const MatrixSize input_size = image_rows * image_cols;
const MatrixSize filter_size = 2;
const MatrixSize output_size = ConvolutionalLayer::get_conv_output_size(image_rows, image_cols, filter_size);
const MatrixSize batch_size = 2;
VectorBatch input, expected;
resize_batch(input, batch_size, input_size);
resize_batch(expected, batch_size, output_size);
input <<
0.01, 0.02, 0.11, 0.10, 0.13, 0.18,
0.03, 0.04, 0.12, 0.09, 0.14, 0.17,
0.05, 0.06, 0.07, 0.08, 0.15, 0.16,
///////////////////////////////////
0.02, 0.06, 0.08, 0.10, 0.13, 0.14,
0.03, 0.02, 0.07, 0.09, 0.16, 0.15,
0.04, 0.05, 0.13, 0.11, 0.16, 0.18;
expected <<
0.348, 0.478, 0.309, 0.462, 0.378,
0.492, 0.341, 0.412, 0.409, 0.480,
//////////////////////////////////
0.372, 0.445, 0.287, 0.366, 0.395,
0.440, 0.331, 0.494, 0.429, 0.532;
// create layer
auto layer = make_unique<ConvolutionalLayer>(image_rows, image_cols, filter_size);
BOOST_CHECK(layer);
layer->set_activation_function(make_unique<SigmoidFunction>());
layer->init(Layer::InitMode_Zeros, boost::none);
// test
test_layer_training(
*layer,
input,
expected,
batch_size, // tests num
make_unique<CrossEntropyCost>(),
0.75, // learning rate
8000 // epochs
);
}
////////////////////////////////////////////////////////////////////////////////////////////////
//
// perf conv tests
//
BOOST_AUTO_TEST_CASE(PerfConvTest, * disabled())
{
conv_perf_test(
1000, // size
10, // filter
100 // epochs
);
}
BOOST_AUTO_TEST_CASE(PerfBatchConvTest, * disabled())
{
conv_perf_batch_test(
10, // batch
1000, // size
10, // filter
10 // epochs
);
}
BOOST_AUTO_TEST_SUITE_END()
| 26.53641
| 138
| 0.576392
|
lsh123
|
d39781614f209bd37dac8fbe3673ed1fe9741deb
| 208
|
cpp
|
C++
|
4_loops/Code_Examples/output_tracing3.cpp
|
AhsanAyub/tntech_csc_1300_fall_2021
|
a96794e9800adccb71abaf83ecf5409ad4c25b3e
|
[
"MIT"
] | 2
|
2022-02-02T05:25:46.000Z
|
2022-02-17T17:42:08.000Z
|
4_loops/Code_Examples/output_tracing3.cpp
|
AhsanAyub/tntech_csc_1300_fall_2021
|
a96794e9800adccb71abaf83ecf5409ad4c25b3e
|
[
"MIT"
] | null | null | null |
4_loops/Code_Examples/output_tracing3.cpp
|
AhsanAyub/tntech_csc_1300_fall_2021
|
a96794e9800adccb71abaf83ecf5409ad4c25b3e
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
int main()
{
for(int i = 0; i <= 10; i++)
{
if(i % 2 == 0)
{
continue;
}
cout << i << endl;
}
return 0;
}
| 13
| 32
| 0.384615
|
AhsanAyub
|
d39a7d147f697051ffcfba0a5a50f415399fbe1c
| 230
|
cpp
|
C++
|
Week-1/Day-05-firstUniqChar.cpp
|
utkarshavardhana/may-leetcoding-challenge
|
4f7600c943460029c595a3b2d85f86e68d7b7066
|
[
"MIT"
] | 1
|
2020-05-02T04:21:54.000Z
|
2020-05-02T04:21:54.000Z
|
Week-1/Day-05-firstUniqChar.cpp
|
utkarshavardhana/may-leetcoding-challenge
|
4f7600c943460029c595a3b2d85f86e68d7b7066
|
[
"MIT"
] | null | null | null |
Week-1/Day-05-firstUniqChar.cpp
|
utkarshavardhana/may-leetcoding-challenge
|
4f7600c943460029c595a3b2d85f86e68d7b7066
|
[
"MIT"
] | null | null | null |
class Solution {
public:
int firstUniqChar(string s) {
unordered_map<char, int> m;
for(char c : s) m[c]++;
for(int i=0; i<s.size(); i++) if(m[s[i]] == 1) return i;
return -1;
}
};
| 23
| 66
| 0.473913
|
utkarshavardhana
|
d39c4c39557e3acd06192a317311199dee19ac85
| 2,464
|
cpp
|
C++
|
fbzmq/async/tests/ZmqTimeoutTest.cpp
|
eensy1207/fbzmq
|
9032d469ce9565756a0a160481a002c70e66f35c
|
[
"MIT"
] | null | null | null |
fbzmq/async/tests/ZmqTimeoutTest.cpp
|
eensy1207/fbzmq
|
9032d469ce9565756a0a160481a002c70e66f35c
|
[
"MIT"
] | null | null | null |
fbzmq/async/tests/ZmqTimeoutTest.cpp
|
eensy1207/fbzmq
|
9032d469ce9565756a0a160481a002c70e66f35c
|
[
"MIT"
] | null | null | null |
/**
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <gtest/gtest.h>
#include <gflags/gflags.h>
#include <fbzmq/async/ZmqEventLoop.h>
#include <fbzmq/async/ZmqTimeout.h>
namespace fbzmq {
using namespace std::chrono_literals;
namespace {
class TestThread final : public ZmqEventLoop {
public:
TestThread() {
prepare();
}
int
getCount() {
return count_.load(std::memory_order_relaxed);
}
private:
void
prepare() {
auto start = std::chrono::steady_clock::now();
// Schedule first timeout
timeout_ = ZmqTimeout::make(this, [&, start]() noexcept {
auto diff = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - start);
LOG(INFO) << "Executing callback after " << diff.count() << "ms.";
// fetch_add returns previous value
int oldCount = count_.fetch_add(1, std::memory_order_relaxed);
EXPECT_EQ(1, getNumPendingTimeouts());
// Destruct the timeout on 4th time, this will cancel it.
if (oldCount == 3) {
timeout_.reset();
EXPECT_EQ(0, getNumPendingTimeouts());
}
});
EXPECT_EQ(0, getNumPendingTimeouts());
EXPECT_NO_THROW(timeout_->cancelTimeout());
timeout_->scheduleTimeout(100ms, true /* periodic */);
EXPECT_TRUE(timeout_->isScheduled());
// can schedule twice with no issue
timeout_->scheduleTimeout(100ms, true /* periodic */);
EXPECT_TRUE(timeout_->isScheduled());
EXPECT_TRUE(timeout_->isPeriodic());
EXPECT_EQ(1, getNumPendingTimeouts());
}
std::atomic<int> count_{0};
std::unique_ptr<ZmqTimeout> timeout_;
};
} // namespace
TEST(ZmqTimeoutTest, TimeoutTest) {
TestThread testThread;
EXPECT_EQ(0, testThread.getCount());
std::thread thread([&]() {
LOG(INFO) << "Starting zmq thread.";
testThread.run();
LOG(INFO) << "Stopping zmq thread.";
});
// Busy spin until callback has been executed 4 times
while (testThread.getCount() != 4) {
std::this_thread::yield();
}
// Cleanup
testThread.stop();
thread.join();
}
} // namespace fbzmq
int
main(int argc, char* argv[]) {
testing::InitGoogleTest(&argc, argv);
gflags::ParseCommandLineFlags(&argc, &argv, true);
google::InitGoogleLogging(argv[0]);
google::InstallFailureSignalHandler();
return RUN_ALL_TESTS();
}
| 23.92233
| 72
| 0.663555
|
eensy1207
|
d3ab8adc2a1bb7fb4e3aee0521a5fd7e9a35a42d
| 2,295
|
cpp
|
C++
|
codeforces/F - Three Paths on a Tree/Accepted.cpp
|
kzvd4729/Problem-Solving
|
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
|
[
"MIT"
] | 1
|
2022-02-11T16:55:36.000Z
|
2022-02-11T16:55:36.000Z
|
codeforces/F - Three Paths on a Tree/Accepted.cpp
|
kzvd4729/Problem-Solving
|
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
|
[
"MIT"
] | null | null | null |
codeforces/F - Three Paths on a Tree/Accepted.cpp
|
kzvd4729/Problem-Solving
|
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
|
[
"MIT"
] | null | null | null |
/****************************************************************************************
* @author: * kzvd4729 created: Jan/22/2020 21:35
* solution_verdict: Accepted language: GNU C++14
* run_time: 389 ms memory_used: 31600 KB
* problem: https://codeforces.com/contest/1294/problem/F
****************************************************************************************/
#include<bits/stdc++.h>
#define long long long
using namespace std;
const int N=1e6,inf=1e9;
int sub[N+2],fav[N+2],on,tw,th,mx;
vector<int>adj[N+2];
void dfs(int node,int par)
{
for(auto x:adj[node])
{
if(x==par)continue;dfs(x,node);
if(sub[x]+1>sub[node])
{
sub[node]=sub[x]+1;fav[node]=fav[x];
}
}
if(!fav[node])fav[node]=node;
}
void dds(int node,int par,int sb,int fv)
{
multiset<pair<int,int> >st;
st.insert({0,0});st.insert({0,0});
st.insert({sb,fv});
for(auto x:adj[node])
{
if(x==par)continue;
st.insert({sub[x]+1,fav[x]});
}
pair<int,int>a=*st.rbegin();st.erase(st.find(a));
pair<int,int>b=*st.rbegin();st.erase(st.find(b));
pair<int,int>c=*st.rbegin();st.erase(st.find(c));
if(a.first+b.first+c.first>mx)
{
mx=a.first+b.first+c.first;
on=a.second,tw=b.second,th=c.second;
//cout<<mx<<" ** "<<node<<endl;
}
st.insert(a),st.insert(b),st.insert(c);
for(auto x:adj[node])
{
if(x==par)continue;
st.erase(st.find({sub[x]+1,fav[x]}));
pair<int,int>p=*st.rbegin();
dds(x,node,p.first+1,p.second);
st.insert({sub[x]+1,fav[x]});
}
}
int main()
{
ios_base::sync_with_stdio(0);cin.tie(0);
int n;cin>>n;
for(int i=1;i<n;i++)
{
int u,v;cin>>u>>v;
adj[u].push_back(v);adj[v].push_back(u);
}
dfs(1,-1);dds(1,-1,0,1);
if(on==0)
{
if(tw!=1&&th!=1)on=1;
else if(tw!=2&&th!=2)on=2;
else if(tw!=3&&th!=3)on=3;
}
if(tw==0)
{
if(on!=1&&th!=1)tw=1;
else if(on!=2&&th!=2)tw=2;
else if(on!=3&&th!=3)tw=3;
}
if(th==0)
{
if(tw!=1&&on!=1)th=1;
else if(tw!=2&&on!=2)th=2;
else if(tw!=3&&on!=3)th=3;
}
cout<<mx<<endl<<on<<" "<<tw<<" "<<th<<endl;
return 0;
}
| 27.321429
| 111
| 0.471895
|
kzvd4729
|
d3c1b0b416e6a83a84e81982e70acab8311b8e84
| 1,798
|
cc
|
C++
|
tests/benchmark/chunk_replacement_bench.cc
|
Chippiewill/Phosphor
|
ef090fa5b331dd94301cd8562b24c78c0c2030f1
|
[
"Apache-2.0"
] | null | null | null |
tests/benchmark/chunk_replacement_bench.cc
|
Chippiewill/Phosphor
|
ef090fa5b331dd94301cd8562b24c78c0c2030f1
|
[
"Apache-2.0"
] | null | null | null |
tests/benchmark/chunk_replacement_bench.cc
|
Chippiewill/Phosphor
|
ef090fa5b331dd94301cd8562b24c78c0c2030f1
|
[
"Apache-2.0"
] | null | null | null |
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2016 Couchbase, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <benchmark/benchmark.h>
#include "bench_common.h"
#include "phosphor/trace_log.h"
#include "utils/memory.h"
using phosphor::utils::make_unique;
class MockTraceLog : public phosphor::TraceLog {
public:
using phosphor::TraceLog::TraceLog;
void replaceChunk() {
auto ctl = getChunkTenant();
if (!ctl) {
return;
}
phosphor::TraceLog::replaceChunk(*ctl.mutex());
if (!ctl.mutex()->chunk) {
ctl.unlock();
stop();
}
}
};
void RegisterTenants(benchmark::State& state) {
static MockTraceLog log{phosphor::TraceLogConfig()};
log.registerThread();
if (state.thread_index == 0) {
log.start(phosphor::TraceConfig(
phosphor::BufferMode::ring,
(sizeof(phosphor::TraceChunk) * (10 * state.threads))));
}
while (state.KeepRunning()) {
log.replaceChunk();
}
if (state.thread_index == 0) {
log.stop();
}
log.deregisterThread();
}
BENCHMARK(RegisterTenants)->ThreadRange(1, phosphor::benchNumThreads());
BENCHMARK_MAIN()
| 28.539683
| 79
| 0.6396
|
Chippiewill
|
d3c21fbb302729b47502c2d84cb61f98404cb09f
| 2,022
|
cpp
|
C++
|
Days 021 - 030/Day 24/LockableBinaryTree.cpp
|
LucidSigma/Daily-Coding-Problems
|
21dc8f7e615edd535d7beb1f5d0e41dd3b4bcc1a
|
[
"MIT"
] | null | null | null |
Days 021 - 030/Day 24/LockableBinaryTree.cpp
|
LucidSigma/Daily-Coding-Problems
|
21dc8f7e615edd535d7beb1f5d0e41dd3b4bcc1a
|
[
"MIT"
] | null | null | null |
Days 021 - 030/Day 24/LockableBinaryTree.cpp
|
LucidSigma/Daily-Coding-Problems
|
21dc8f7e615edd535d7beb1f5d0e41dd3b4bcc1a
|
[
"MIT"
] | null | null | null |
#include <iostream>
struct Node
{
public:
int value;
Node* left;
Node* right;
Node* parent;
bool isLocked;
unsigned int descendantLockCount;
Node(int value, Node* left = nullptr, Node* right = nullptr, Node* parent = nullptr) noexcept
: value(value), left(left), right(right), parent(parent), isLocked(false), descendantLockCount(0)
{
if (left != nullptr)
{
left->parent = this;
}
if (right != nullptr)
{
right->parent = this;
}
}
~Node() noexcept
{
if (left != nullptr)
{
delete left;
}
if (right != nullptr)
{
delete right;
}
}
inline bool IsLocked() const { return isLocked; }
bool Lock()
{
if (CanBeLocked())
{
isLocked = true;
Node* currentNode = parent;
while (currentNode != nullptr)
{
currentNode->descendantLockCount++;
currentNode = currentNode->parent;
}
return true;
}
return false;
}
bool Unlock()
{
if (CanBeLocked())
{
isLocked = false;
Node* currentNode = parent;
while (currentNode != nullptr)
{
currentNode->descendantLockCount--;
currentNode = currentNode->parent;
}
return true;
}
return false;
}
private:
bool CanBeLocked() const
{
if (descendantLockCount > 0)
{
return false;
}
Node* currentNode = parent;
while (currentNode != nullptr)
{
if (currentNode->isLocked)
{
return false;
}
currentNode = currentNode->parent;
}
return true;
}
};
int main(int argc, const char* argv[])
{
Node* leftleft = new Node(67);
Node* leftright = new Node(49);
Node* rightright = new Node(36);
Node* left = new Node(82, leftleft, leftright);
Node* right = new Node(49, nullptr, rightright);
Node* root = new Node(19, left, right);
std::cout << std::boolalpha;
std::cout << left->Lock() << "\n";
std::cout << leftright->Lock() << "\n";
left->Unlock();
std::cout << leftright->Lock() << "\n";
if (leftright->IsLocked())
{
std::cout << "Node leftright is locked." << "\n";
}
std::cin.get();
return 0;
}
| 14.652174
| 99
| 0.608309
|
LucidSigma
|
d3c2a72b9d24717384680c5b875076a20c977fde
| 2,322
|
cpp
|
C++
|
T__Floor.cpp
|
SJ-magic-work-GolemForBackStage/Kinobi_oF_main
|
836ef64ecf92a81230c051d308ee7e7d3a7ca1d4
|
[
"MIT"
] | null | null | null |
T__Floor.cpp
|
SJ-magic-work-GolemForBackStage/Kinobi_oF_main
|
836ef64ecf92a81230c051d308ee7e7d3a7ca1d4
|
[
"MIT"
] | null | null | null |
T__Floor.cpp
|
SJ-magic-work-GolemForBackStage/Kinobi_oF_main
|
836ef64ecf92a81230c051d308ee7e7d3a7ca1d4
|
[
"MIT"
] | null | null | null |
/************************************************************
************************************************************/
#include "T__Floor.h"
/************************************************************
************************************************************/
/******************************
******************************/
T__FLOOR::T__FLOOR()
: c_SkipProcessControl(0)
{
}
/******************************
******************************/
T__FLOOR::~T__FLOOR()
{
}
/******************************
******************************/
void T__FLOOR::exit()
{
}
/******************************
******************************/
void T__FLOOR::setup()
{
fbo.allocate(FBO_WIDTH, FBO_HEIGHT, GL_RGBA, 0);
fbo_TextureSyphonServer.setName("oF Floor");
}
/******************************
******************************/
void T__FLOOR::update()
{
}
/******************************
******************************/
void T__FLOOR::drawToFbo_SendSyphon()
{
/********************
********************/
c_SkipProcessControl++;
if( b_SkipProcessControl && (c_SkipProcessControl % 10 != 0) ){
return;
}
c_SkipProcessControl = 0;
/********************
********************/
ofDisableAlphaBlending();
ofEnableSmoothing();
fbo.begin();
ofClear(0, 0, 0, 0);
/*
// 2m
ofSetColor(255, 255, 255, 200);
ofSetLineWidth(4);
ofDrawLine(0, fbo.getHeight()/2, fbo.getWidth(), fbo.getHeight()/2);
ofDrawLine(fbo.getWidth()/2, 0, fbo.getWidth()/2, fbo.getHeight());
/*/
// 1m
ofSetColor(255, 255, 255, 170);
ofSetLineWidth(2);
/*
ofSetColor(255, 255, 255, 120);
ofSetLineWidth(600);
*/
ofDrawLine(0, fbo.getHeight()*1/4, fbo.getWidth(), fbo.getHeight()*1/4);
ofDrawLine(0, fbo.getHeight()*3/4, fbo.getWidth(), fbo.getHeight()*3/4);
ofDrawLine(fbo.getWidth()*1/4, 0, fbo.getWidth()*1/4, fbo.getHeight());
ofDrawLine(fbo.getWidth()*3/4, 0, fbo.getWidth()*3/4, fbo.getHeight());
//*/
fbo.end();
/********************
publish
********************/
ofTexture tex = fbo.getTextureReference();
fbo_TextureSyphonServer.publishTexture(&tex);
}
/******************************
******************************/
void T__FLOOR::draw_FboToMonitor()
{
ofSetColor(255, 255, 255, 255);
fbo.draw(0, 0, fbo.getWidth(), fbo.getHeight());
// fbo.draw(0, 0, ofGetWidth(), ofGetHeight());
}
| 22.990099
| 74
| 0.425065
|
SJ-magic-work-GolemForBackStage
|
d3cb37718b5d1232ca4a5ba6d54959243340e308
| 4,796
|
cpp
|
C++
|
src/PointwiseFunctions/MathFunctions/PowX.cpp
|
tomwlodarczyk/spectre
|
086aaee002f2f07eb812cf17b8e1ba54052feb71
|
[
"MIT"
] | null | null | null |
src/PointwiseFunctions/MathFunctions/PowX.cpp
|
tomwlodarczyk/spectre
|
086aaee002f2f07eb812cf17b8e1ba54052feb71
|
[
"MIT"
] | 1
|
2022-03-25T18:26:16.000Z
|
2022-03-25T19:30:39.000Z
|
src/PointwiseFunctions/MathFunctions/PowX.cpp
|
tomwlodarczyk/spectre
|
086aaee002f2f07eb812cf17b8e1ba54052feb71
|
[
"MIT"
] | 1
|
2019-01-03T21:47:04.000Z
|
2019-01-03T21:47:04.000Z
|
// Distributed under the MIT License.
// See LICENSE.txt for details.
#include "PointwiseFunctions/MathFunctions/PowX.hpp"
#include "DataStructures/DataVector.hpp"
#include "Utilities/GenerateInstantiations.hpp"
#include "Utilities/MakeWithValue.hpp"
namespace MathFunctions {
template <typename Fr>
PowX<1, Fr>::PowX(const int power) noexcept : power_(power) {}
template <typename Fr>
double PowX<1, Fr>::operator()(const double& x) const noexcept {
return apply_call_operator(x);
}
template <typename Fr>
DataVector PowX<1, Fr>::operator()(const DataVector& x) const noexcept {
return apply_call_operator(x);
}
template <typename Fr>
double PowX<1, Fr>::first_deriv(const double& x) const noexcept {
return apply_first_deriv(x);
}
template <typename Fr>
DataVector PowX<1, Fr>::first_deriv(const DataVector& x) const noexcept {
return apply_first_deriv(x);
}
template <typename Fr>
double PowX<1, Fr>::second_deriv(const double& x) const noexcept {
return apply_second_deriv(x);
}
template <typename Fr>
DataVector PowX<1, Fr>::second_deriv(const DataVector& x) const noexcept {
return apply_second_deriv(x);
}
template <typename Fr>
double PowX<1, Fr>::third_deriv(const double& x) const noexcept {
return apply_third_deriv(x);
}
template <typename Fr>
DataVector PowX<1, Fr>::third_deriv(const DataVector& x) const noexcept {
return apply_third_deriv(x);
}
template <typename Fr>
template <typename T>
T PowX<1, Fr>::apply_call_operator(const T& x) const noexcept {
return pow(x, power_);
}
template <typename Fr>
template <typename T>
T PowX<1, Fr>::apply_first_deriv(const T& x) const noexcept {
return 0 == power_ ? make_with_value<T>(x, 0.0) : power_ * pow(x, power_ - 1);
}
template <typename Fr>
template <typename T>
T PowX<1, Fr>::apply_second_deriv(const T& x) const noexcept {
return 0 == power_ or 1 == power_
? make_with_value<T>(x, 0.0)
: power_ * (power_ - 1) * pow(x, power_ - 2);
}
template <typename Fr>
template <typename T>
T PowX<1, Fr>::apply_third_deriv(const T& x) const noexcept {
return 0 == power_ or 1 == power_ or 2 == power_
? make_with_value<T>(x, 0.0)
: power_ * (power_ - 1) * (power_ - 2) * pow(x, power_ - 3);
}
template <typename Fr>
void PowX<1, Fr>::pup(PUP::er& p) {
MathFunction<1, Fr>::pup(p);
p | power_;
}
/// \cond
template MathFunctions::PowX<1, Frame::Grid>::PowX(const int power) noexcept;
template MathFunctions::PowX<1, Frame::Inertial>::PowX(
const int power) noexcept;
template void MathFunctions::PowX<1, Frame::Grid>::pup(PUP::er& p);
template void MathFunctions::PowX<1, Frame::Inertial>::pup(PUP::er& p);
#define FRAME(data) BOOST_PP_TUPLE_ELEM(0, data)
#define DTYPE(data) BOOST_PP_TUPLE_ELEM(1, data)
#define INSTANTIATE(_, data) \
template DTYPE(data) \
MathFunctions::PowX<1, FRAME(data)>::operator()(const DTYPE(data) & x) \
const noexcept; \
template DTYPE(data) \
MathFunctions::PowX<1, FRAME(data)>::first_deriv(const DTYPE(data) & x) \
const noexcept; \
template DTYPE(data) \
MathFunctions::PowX<1, FRAME(data)>::second_deriv(const DTYPE(data) & x) \
const noexcept; \
template DTYPE(data) \
MathFunctions::PowX<1, FRAME(data)>::third_deriv(const DTYPE(data) & x) \
const noexcept; \
template DTYPE(data) \
MathFunctions::PowX<1, FRAME(data)>::apply_call_operator( \
const DTYPE(data) & x) const noexcept; \
template DTYPE(data) MathFunctions::PowX<1, FRAME(data)>::apply_first_deriv( \
const DTYPE(data) & x) const noexcept; \
template DTYPE(data) \
MathFunctions::PowX<1, FRAME(data)>::apply_second_deriv( \
const DTYPE(data) & x) const noexcept; \
template DTYPE(data) MathFunctions::PowX<1, FRAME(data)>::apply_third_deriv( \
const DTYPE(data) & x) const noexcept;
GENERATE_INSTANTIATIONS(INSTANTIATE, (Frame::Grid, Frame::Inertial),
(double, DataVector))
#undef DTYPE
#undef FRAME
#undef INSTANTIATE
/// \endcond
} // namespace MathFunctions
| 36.892308
| 80
| 0.584028
|
tomwlodarczyk
|
d3cea590a7fc2df48824a7ed4cfda9c0d6d87666
| 582
|
hpp
|
C++
|
nodes/random_regex_node.hpp
|
do-m-en/random_regex_string
|
7ded2dcf7c03122a68e66b5db6f94403e8c9c690
|
[
"BSL-1.0"
] | null | null | null |
nodes/random_regex_node.hpp
|
do-m-en/random_regex_string
|
7ded2dcf7c03122a68e66b5db6f94403e8c9c690
|
[
"BSL-1.0"
] | null | null | null |
nodes/random_regex_node.hpp
|
do-m-en/random_regex_string
|
7ded2dcf7c03122a68e66b5db6f94403e8c9c690
|
[
"BSL-1.0"
] | null | null | null |
#ifndef RANDOM_REGEX_NODE_HPP_INCLUDED
#define RANDOM_REGEX_NODE_HPP_INCLUDED
#include "regex_node.hpp"
namespace rand_regex {
class random_regex_node_ : public regex_node_ // . TODO check if this could be derived from range_random_regex_node_
{
public:
void generate(std::ostream& os, random_generator_base& random_gen, std::vector<std::tuple<int, regex_node_*>>& groups) override;
void regenerate(std::ostream& os, const std::vector<std::tuple<int, regex_node_*>>& groups) const override;
private:
char generated_value_;
};
};
#endif // RANDOM_REGEX_NODE_HPP_INCLUDED
| 27.714286
| 130
| 0.785223
|
do-m-en
|
d3cfa2c85886b38d838c3caff1fb6629f0e765db
| 1,051
|
hpp
|
C++
|
Giga_v1/src/eeprom/KDEEPROMMap.hpp
|
azarashi2931/Giga-Project
|
2acbd937bec01e6042453fe777f4182b6d67d9b7
|
[
"MIT"
] | null | null | null |
Giga_v1/src/eeprom/KDEEPROMMap.hpp
|
azarashi2931/Giga-Project
|
2acbd937bec01e6042453fe777f4182b6d67d9b7
|
[
"MIT"
] | null | null | null |
Giga_v1/src/eeprom/KDEEPROMMap.hpp
|
azarashi2931/Giga-Project
|
2acbd937bec01e6042453fe777f4182b6d67d9b7
|
[
"MIT"
] | null | null | null |
#ifndef KD_EEPROM_MAP_h
#define KD_EEPROM_MAP_h
typedef struct
{
int address;
uint8_t size;
} EEPROMData;
class KDEEPROMMap
{
public:
static constexpr int NumberOfAddresses = 1;
static constexpr int LineThreshold = 0;
static constexpr EEPROMData Addresses[NumberOfAddresses] =
{
{0, 2},
};
};
constexpr int KDEEPROMMap::NumberOfAddresses;
constexpr int KDEEPROMMap::LineThreshold;
constexpr EEPROMData KDEEPROMMap::Addresses[NumberOfAddresses];
//アドレスリストの整合性を確認します. 整合性が無い場合はコンパイルエラーになります.
class KDEEPROMAddressCehecker
{
public:
constexpr static bool checkCorrection(int i)
{
return i <= 0
? true
: (KDEEPROMMap::Addresses[i - 1].address + KDEEPROMMap::Addresses[i - 1].size == KDEEPROMMap::Addresses[i].address
? checkCorrection(i - 1)
: false);
};
};
static_assert(KDEEPROMAddressCehecker::checkCorrection(KDEEPROMMap::NumberOfAddresses - 1), "EEPROM address list is invaid.");
#endif
| 25.634146
| 133
| 0.665081
|
azarashi2931
|
d3cfc6ae5338817f400e495160623ced2e329216
| 718
|
hh
|
C++
|
Watertank-System/1.0_SystemC/Solutions/Continous_Subsystem/include/watertank_lsf.hh
|
SimoGira/Embedded-Systems-Design
|
87829fb65aa64a24e062358671580716a1151572
|
[
"BSD-3-Clause"
] | null | null | null |
Watertank-System/1.0_SystemC/Solutions/Continous_Subsystem/include/watertank_lsf.hh
|
SimoGira/Embedded-Systems-Design
|
87829fb65aa64a24e062358671580716a1151572
|
[
"BSD-3-Clause"
] | null | null | null |
Watertank-System/1.0_SystemC/Solutions/Continous_Subsystem/include/watertank_lsf.hh
|
SimoGira/Embedded-Systems-Design
|
87829fb65aa64a24e062358671580716a1151572
|
[
"BSD-3-Clause"
] | null | null | null |
#ifndef WATERTANK_LSF_HH
#define WATERTANK_LSF_HH
#include <systemc-ams>
#include "global.hh"
SC_MODULE(watertank_lsf){
public:
//sc_in_clk clock;
//sca_lsf::sca_signal sig_derivative_of_valve_aperture;
sca_lsf::sca_signal sig_valve_aperture;
sca_lsf::sca_signal sig_water_level;
sca_lsf::sca_tdf::sca_source tdf2lsf; // get values from tdf
sca_lsf::sca_tdf::sca_sink lsf2tdf; // get signal lsf and output value tdf
// sca_lsf::sca_de::sca_source source;
// sca_lsf::sca_de::sca_sink sink;
sca_lsf::sca_integ int1;
sca_lsf::sca_gain gain1, gain2;
sca_lsf::sca_sub sub1;
SC_CTOR( watertank_lsf );
private:
sca_lsf::sca_signal sig1, sig2, sig3;
};
#endif
| 21.117647
| 80
| 0.720056
|
SimoGira
|
d3d0eaf1b87ea2e66037622edba63a48ba31c13e
| 1,880
|
cxx
|
C++
|
xp_comm_misc/merl/src/hist.cxx
|
avs/express-community
|
c699a68330d3b678b7e6bcea823e0891b874049c
|
[
"Apache-2.0"
] | 3
|
2020-08-03T08:52:20.000Z
|
2021-04-10T11:55:49.000Z
|
xp_comm_misc/merl/src/hist.cxx
|
avs/express-community
|
c699a68330d3b678b7e6bcea823e0891b874049c
|
[
"Apache-2.0"
] | null | null | null |
xp_comm_misc/merl/src/hist.cxx
|
avs/express-community
|
c699a68330d3b678b7e6bcea823e0891b874049c
|
[
"Apache-2.0"
] | 1
|
2021-06-08T18:16:45.000Z
|
2021-06-08T18:16:45.000Z
|
#include "express.h"
#include "hist.hxx"
int
Volume_Histogram::ComputeHistogram(OMevent_mask , int )
{
// volume (Mesh_Unif+Node_Data read notify)
// data_component (OMXint read notify)
// threshold (OMXint read notify)
// histogram (OMXint_array write)
int comp = (int)data_component;
int thresh = (int)threshold;
int dataSize;
int dataType;
void *data = volume.node_data[comp].values.ret_array_ptr(OM_GET_ARRAY_RD,
&dataSize,
&dataType);
int histSize;
int *hist = (int *)histogram.ret_array_ptr(OM_GET_ARRAY_WR, &histSize);
if (data && hist)
{
int i;
int value;
for (i = 0; i < histSize; i++)
hist[i] = 0;
if ((dataType == OM_TYPE_CHAR) || (dataType == OM_TYPE_BYTE))
{
unsigned char *bytes = (unsigned char *)data;
for (i = 0; i < dataSize; i++, bytes++)
{
value = (int)(*bytes);
if (value >= thresh)
++hist[value];
}
}
else if (dataType == OM_TYPE_SHORT) // actually 12 bits
{
unsigned short *shorts = (unsigned short *)data;
unsigned short clamped;
for (i = 0; i < dataSize; i++, shorts++)
{
clamped = *shorts;
if (clamped > 0x0FFF)
clamped = 0x0FFF;
value = (int)clamped;
if (value >= thresh)
++hist[value >> 4];
}
}
else
ERRverror("Histogram", ERR_ERROR,
"Histogram only supports char, byte, or short data\n");
}
else
ERRverror("Histogram", ERR_ERROR,
"Unable to get volume data array\n");
if (data)
ARRfree(data);
if (hist)
ARRfree(hist);
return 1;
}
| 24.102564
| 76
| 0.50266
|
avs
|
d3db75b63344d817e83451ef1cac9f8d28c654d5
| 3,690
|
cc
|
C++
|
test/hash_table_test.cc
|
yang-le/cpp-algorithms
|
0c1f422bc1e9fefa1a7d430b4a13ef7795420a2e
|
[
"MIT"
] | null | null | null |
test/hash_table_test.cc
|
yang-le/cpp-algorithms
|
0c1f422bc1e9fefa1a7d430b4a13ef7795420a2e
|
[
"MIT"
] | null | null | null |
test/hash_table_test.cc
|
yang-le/cpp-algorithms
|
0c1f422bc1e9fefa1a7d430b4a13ef7795420a2e
|
[
"MIT"
] | null | null | null |
// MIT License
// Copyright (c) 2018 Yang Le
// 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 "hash_table.hpp"
#include "gtest/gtest.h"
TEST(HashTableTest, create) {
HashTable<int> defaultHashTable;
EXPECT_EQ(defaultHashTable.buckets_.size(), 32);
HashTable<int, 64> biggerHashTable;
EXPECT_EQ(biggerHashTable.buckets_.size(), 64);
}
TEST(HashTableTest, hash) {
HashTable<int> hashTable;
EXPECT_EQ(hashTable.hash("a"), 1);
EXPECT_EQ(hashTable.hash("b"), 2);
EXPECT_EQ(hashTable.hash("abc"), 6);
}
TEST(HashTableTest, collisions) {
HashTable<std::string, 3> hashTable;
EXPECT_EQ(hashTable.hash("a"), 1);
EXPECT_EQ(hashTable.hash("b"), 2);
EXPECT_EQ(hashTable.hash("c"), 0);
EXPECT_EQ(hashTable.hash("d"), 1);
hashTable.set("a", "sky-old");
hashTable.set("a", "sky");
hashTable.set("b", "sea");
hashTable.set("c", "earth");
hashTable.set("d", "ocean");
EXPECT_FALSE(hashTable.has("x"));
EXPECT_TRUE(hashTable.has("b"));
EXPECT_TRUE(hashTable.has("c"));
auto stringifier = [](const std::pair<std::string, std::string>& pair) {
return pair.first + ":" + pair.second;
};
EXPECT_EQ(hashTable.buckets_[0].toString(stringifier), "c:earth");
EXPECT_EQ(hashTable.buckets_[1].toString(stringifier), "a:sky,d:ocean");
EXPECT_EQ(hashTable.buckets_[2].toString(stringifier), "b:sea");
EXPECT_EQ(*hashTable.get("a"), "sky");
EXPECT_EQ(*hashTable.get("d"), "ocean");
EXPECT_EQ(hashTable.get("x"), nullptr);
hashTable.remove("a");
EXPECT_EQ(hashTable.remove("not-existing"), nullptr);
EXPECT_EQ(hashTable.get("a"), nullptr);
EXPECT_EQ(*hashTable.get("d"), "ocean");
hashTable.set("d", "ocean-new");
EXPECT_EQ(*hashTable.get("d"), "ocean-new");
}
TEST(HashTableTest, add_objects) {
HashTable<std::pair<std::string, std::string>> hashTable;
hashTable.set("objectKey", std::make_pair("a", "b"));
auto object = hashTable.get("objectKey");
EXPECT_NE(object, nullptr);
EXPECT_EQ(object->first, "a");
EXPECT_EQ(object->second, "b");
}
TEST(HashTableTest, keys) {
HashTable<std::string, 3> hashTable;
hashTable.set("a", "sky-old");
hashTable.set("a", "sky");
hashTable.set("b", "sea");
hashTable.set("c", "earth");
hashTable.set("d", "ocean");
EXPECT_EQ(hashTable.getKeys(),
std::unordered_set<std::string>({"a", "b", "c", "d"}));
EXPECT_TRUE(hashTable.has("a"));
EXPECT_FALSE(hashTable.has("x"));
hashTable.remove("a");
EXPECT_FALSE(hashTable.has("a"));
EXPECT_TRUE(hashTable.has("b"));
EXPECT_FALSE(hashTable.has("x"));
}
| 32.368421
| 81
| 0.673984
|
yang-le
|
d3de4ff25af4de6bba411ea2b3b41813e7ef6d77
| 2,364
|
hpp
|
C++
|
src/perfnp/cmd_line.hpp
|
locksley-cz/perfnp
|
b55dc3401285042e1409ba930543627725a471c0
|
[
"MIT"
] | null | null | null |
src/perfnp/cmd_line.hpp
|
locksley-cz/perfnp
|
b55dc3401285042e1409ba930543627725a471c0
|
[
"MIT"
] | 10
|
2019-03-13T09:14:41.000Z
|
2020-02-19T18:01:14.000Z
|
src/perfnp/cmd_line.hpp
|
locksley-cz/perfnp
|
b55dc3401285042e1409ba930543627725a471c0
|
[
"MIT"
] | 1
|
2019-03-08T09:32:31.000Z
|
2019-03-08T09:32:31.000Z
|
// Copyright (c) 2019 Locksley.CZ s.r.o.
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
#ifndef PERFNP_CMD_LINE_H_
#define PERFNP_CMD_LINE_H_
#include <perfnp/tools.hpp>
#include <string>
#include <vector>
namespace perfnp {
/*!
* Command to be executed with arguments
*/
class CmdWithArgs {
//! Index of this run (see combin.hpp)
unsigned m_run_index;
//! Command to be executed
std::string m_command;
//! List of arguments for the command
std::vector<std::string> m_arguments;
public:
CmdWithArgs(
unsigned job_index,
std::string command,
std::vector<std::string> arguments)
: m_run_index(job_index)
, m_command(std::move(command))
, m_arguments(std::move(arguments))
{}
//! Index of this run (see combin.hpp)
unsigned job_index() const
{
return m_run_index;
}
//! Command to be executed
const std::string& command() const
{
return m_command;
}
//! List of arguments for the command
const std::vector<std::string>& arguments() const
{
return m_arguments;
}
/*!
* Returns a native-shell-friendly string in UTF-8.
*
* Method is platform-dependent. On Windows, we create
* a Command Prompt (cmd.exe) friendly string, on other
* platforms, we assume Linux and prepare a Bash-friendly
* string.
*/
std::string escape_for_native_shell() const;
//! Escape command and arguments for Linux Bash.
std::string escape_for_bash() const;
//! Escape command and arguments for Windows Command Prompt
std::wstring escape_for_cmd_exe() const;
bool operator==(const CmdWithArgs& rhs) const {
return m_run_index == rhs.m_run_index
&& m_command == rhs.m_command
&& m_arguments == rhs.m_arguments;
}
bool operator!=(const CmdWithArgs& rhs) const {
return ! ((*this) == rhs);
}
}; // CmdWithArgs
//! Serialize the command with arguments to a stream, escape for Bash
std::ostream& operator<<(std::ostream& os, const perfnp::CmdWithArgs& cwa);
//! Serialize the command with arguments to an UTF-16 stream, escape for Command Prompt (cmd.exe)
std::wostream& operator<<(std::wostream& os, const perfnp::CmdWithArgs& cwa);
} // perfnp
#endif // PERFNP_CMD_LINE_H_
| 24.884211
| 97
| 0.654399
|
locksley-cz
|
d3e4f7cbd40981044a27bdf1bec005ded1d81537
| 632
|
hpp
|
C++
|
kernel/include/x86_64/pic.hpp
|
larrabyte/thepuck
|
dc9971bc0682354e74a1869b3cc6a5c80b85e821
|
[
"MIT"
] | 5
|
2020-02-21T09:35:24.000Z
|
2021-03-28T08:26:20.000Z
|
kernel/include/x86_64/pic.hpp
|
larrabyte/thepuck
|
dc9971bc0682354e74a1869b3cc6a5c80b85e821
|
[
"MIT"
] | null | null | null |
kernel/include/x86_64/pic.hpp
|
larrabyte/thepuck
|
dc9971bc0682354e74a1869b3cc6a5c80b85e821
|
[
"MIT"
] | 1
|
2021-06-25T17:26:03.000Z
|
2021-06-25T17:26:03.000Z
|
#ifndef FREELSD_KERNEL_PIC_HEADER
#define FREELSD_KERNEL_PIC_HEADER
#include <stdint.h>
#define MASTER_PIC_COMMAND 0x20
#define MASTER_PIC_DATA 0x21
#define SLAVE_PIC_COMMAND 0xA0
#define SLAVE_PIC_DATA 0xA1
#define PIC_READ_IRR 0x0A
#define PIC_READ_ISR 0x0B
namespace pic {
// Check if the PIC is enabled or not.
extern bool enabled;
// Enable the Programmable Interrupt Controller.
void enable(void);
// Disable the Programmable Interrupt Controller.
void disable(void);
// Send an EOI command to the master and slave PICs.
void sendeoi(uint64_t vector);
}
#endif
| 22.571429
| 56
| 0.726266
|
larrabyte
|
d3e79a4e75f229efde8a3aae554600313686d193
| 1,771
|
cpp
|
C++
|
data-structure/Agenda.cpp
|
ejpcr/libs-c
|
e544e4338ea9f2fe8c57de83045944f38ae06a07
|
[
"MIT"
] | null | null | null |
data-structure/Agenda.cpp
|
ejpcr/libs-c
|
e544e4338ea9f2fe8c57de83045944f38ae06a07
|
[
"MIT"
] | null | null | null |
data-structure/Agenda.cpp
|
ejpcr/libs-c
|
e544e4338ea9f2fe8c57de83045944f38ae06a07
|
[
"MIT"
] | null | null | null |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!-- saved from url=(0224)http://65.54.187.250/cgi-bin/getmsg?curmbox=F000000001&a=2ec26e1f050efee654cc3bcc71597a74&msg=MSG1090110885.23&start=406335&len=45661&mimepart=3&disk=65.54.187.39_d298&login=nuverlomm&domain=hotmail%2ecom&_lang=ES&country=MX -->
<HTML><HEAD>
<META http-equiv=Content-Type content="text/html; charset=windows-1252">
<META content="MSHTML 6.00.2800.1106" name=GENERATOR></HEAD>
<BODY><PRE>//LISTAS DOBLE LIGADURA
#include AGENDA.h;
#include CTYPE.H;
void main()
{ clrscr();
LD agenda;
char opc='N';
int op;
char nombre[N];
char direccion[D];
char telefono[T];
do
{ cout<<"\n\t\tAGENDA VIRTUAL";
cout<<"\n\n\n\n\n\t1.INSERTAR";
cout<<"\n\t2.ELIMINAR";
cout<<"\n\t3.VISUALIZAR";
cout<<"\n\nselecciona una opcion: "; cin>>op;
switch(op)
{ case 1:
{ clrscr();
cout<<"\n\t\tAGENDA VIRTUAL";
cout<<"\n\t1.INSERTAR AMIGUIS";
cout<<"\n\tNOMBRE: "; gets(nombre);
cout<<"\n\tDIRECCION: "; gets(direccion);
cout<<"\n\tTELEFONO: "; gets(telefono);
agenda.insfinal(nombre,direccion,telefono);
break;
}
case 2:
{ clrscr();
cout<<"\n\t\tAGENDA VIRTUAL";
cout<<"\n\t1.BORRAR AMIGUIS";
cout<<"\n\tNOMBRE: "; gets(nombre);
agenda.del(nombre);
break;
}
case 3:
{ clrscr();
cout<<"\n\t\tAGENDA VIRTUAL";
cout<<"\n\t1.VER TODOS MIS AMIGUIS";
agenda.visualiza();
cout<<"\npresione enter";
getchar();
break;
}
default: break;
}
cout<<"\n\tDesea salir (S/N) :";
cin>>opc; opc=toupper(opc);
}while(opc=='N');
getchar();
}
</PRE></BODY></HTML>
| 29.032787
| 254
| 0.627329
|
ejpcr
|
d3e83e27e776d08adf5f4e9c2c82d71898aaa415
| 1,949
|
cpp
|
C++
|
Queue/queue.cpp
|
hongwei7/CPP-data_structure
|
07b1d8571a1860bfd483bd0e4104806e3481b167
|
[
"MIT"
] | 1
|
2021-12-16T13:04:31.000Z
|
2021-12-16T13:04:31.000Z
|
Queue/queue.cpp
|
hongwei7/CPP-data_structure
|
07b1d8571a1860bfd483bd0e4104806e3481b167
|
[
"MIT"
] | null | null | null |
Queue/queue.cpp
|
hongwei7/CPP-data_structure
|
07b1d8571a1860bfd483bd0e4104806e3481b167
|
[
"MIT"
] | null | null | null |
#include <iostream>
#define maxsize 20
#define max_size 50
typedef int elem;
using namespace std;
/*后来定义的一些函数需要stack*/
#include "Stack.h"
#include "queue.h"
void Init_queue(queue* &q)
{
q = new queue;
q->front = 0;
q->rear = 0;
}
void Destroy_queue(queue *&q)
{
free(q);
}
bool queue_empty(queue *q)
{
return q->front == q->rear;
}
bool enQueue(queue *&q, elem e)
{
if (q->front == ((q->rear + 1) % maxsize))return false;
q->rear = (q->rear + 1) % maxsize;
q->data[q->rear] = e;
return true;
}
bool deQueue(queue *&q, elem &e)
{
if (q->front == q->rear)return false;
q->front = (q->front + 1) % maxsize;
e = q->data[q->front];
q->data[q->front] = 0;
return true;
}
void _display(queue *q)
{
for (int i = 0; i < maxsize; i++)
{
cout << q->data[i] << " ";
} cout << endl;
}
void display(queue *q)
{
if (q->front == q->rear)return;
for (int i = q->front + 1; i != (q->rear + 1) % maxsize; i = (i + 1) % maxsize)
{
cout << q->data[i] << ' ';
} cout << endl;
}
void reverse_queue(queue *&q)
{
stack *p = new stack;
Init_stack(p);
elem t;
while (deQueue(q, t))push(p, t);
Init_queue(q);
while (!Stack_empty(p))
{
pop(p, t);
enQueue(q, t);
}
}
int main()
{
queue *q = new queue;
elem e;
Init_queue(q);
for (int i = 1; i <= 20; i++)
{
if (enQueue(q, i))cout << "in: " << i << endl;
}
for (int i = 1; i <= 12; i++)
{
if (deQueue(q, i))cout << "out: " << i << endl;
}
for (int i = 1; i <= 6; i++)
{
if (enQueue(q, i))cout << "in: " << i << endl;
}
display(q);
cout << "point:" << q->front << ' ' << q->rear << endl;
reverse_queue(q);
display(q);
cout << "point:" << q->front << ' ' << q->rear << endl;
reverse_queue(q);
display(q);
cout << "point:" << q->front << ' ' << q->rear << endl;
return 0;
}
| 20.302083
| 83
| 0.487429
|
hongwei7
|
d3e8f67b6a612ddf7e7589785f61cc3a51216bef
| 1,881
|
cpp
|
C++
|
tst/OpcUaStackServer/ServiceSet/MonitoredItem_t.cpp
|
gianricardo/OpcUaStack
|
ccdef574175ffe8b7e82b886abc5e5403968b280
|
[
"Apache-2.0"
] | 108
|
2018-10-08T17:03:32.000Z
|
2022-03-21T00:52:26.000Z
|
tst/OpcUaStackServer/ServiceSet/MonitoredItem_t.cpp
|
gianricardo/OpcUaStack
|
ccdef574175ffe8b7e82b886abc5e5403968b280
|
[
"Apache-2.0"
] | 287
|
2018-09-18T14:59:12.000Z
|
2022-01-13T12:28:23.000Z
|
tst/OpcUaStackServer/ServiceSet/MonitoredItem_t.cpp
|
gianricardo/OpcUaStack
|
ccdef574175ffe8b7e82b886abc5e5403968b280
|
[
"Apache-2.0"
] | 32
|
2018-10-19T14:35:03.000Z
|
2021-11-12T09:36:46.000Z
|
#include "unittest.h"
#include "OpcUaStackServer/ServiceSet/MonitorItem.h"
#include "OpcUaStackServer/AddressSpaceModel/VariableNodeClass.h"
#include "OpcUaStackServer/AddressSpaceModel/ObjectNodeClass.h"
using namespace OpcUaStackServer;
BOOST_AUTO_TEST_SUITE(MonitoredItem_)
BOOST_AUTO_TEST_CASE(MonitoredItem_)
{
std::cout << "MonitoredItem_t" << std::endl;
}
BOOST_AUTO_TEST_CASE(MonitoredItem_minimalSamplingInterval)
{
MonitoredItemCreateRequest::SPtr monitoredItemCreateRequest = constructSPtr<MonitoredItemCreateRequest>();
monitoredItemCreateRequest->requestedParameters().samplingInterval(100);
BaseNodeClass::SPtr valueNode = constructSPtr<VariableNodeClass>();
OpcUaDouble minValue = 200;
valueNode->setMinimumSamplingInterval(minValue);
MonitorItem item;
item.receive(valueNode, monitoredItemCreateRequest);
BOOST_REQUIRE_EQUAL(200, item.samplingInterval());
}
BOOST_AUTO_TEST_CASE(MonitoredItem_minimalSamplingIntervalNull)
{
MonitoredItemCreateRequest::SPtr monitoredItemCreateRequest = constructSPtr<MonitoredItemCreateRequest>();
monitoredItemCreateRequest->requestedParameters().samplingInterval(100);
BaseNodeClass::SPtr valueNode = constructSPtr<VariableNodeClass>();
MonitorItem item;
item.receive(valueNode, monitoredItemCreateRequest);
BOOST_REQUIRE_EQUAL(100, item.samplingInterval());
}
BOOST_AUTO_TEST_CASE(MonitoredItem_minimalSamplingIntervalNotExist)
{
MonitoredItemCreateRequest::SPtr monitoredItemCreateRequest = constructSPtr<MonitoredItemCreateRequest>();
monitoredItemCreateRequest->requestedParameters().samplingInterval(100);
BaseNodeClass::SPtr valueNode = constructSPtr<ObjectNodeClass>();
MonitorItem item;
item.receive(valueNode, monitoredItemCreateRequest);
BOOST_REQUIRE_EQUAL(100, item.samplingInterval());
}
BOOST_AUTO_TEST_SUITE_END()
| 30.836066
| 110
| 0.812334
|
gianricardo
|
d3edad04732965f9dd3176e26bf8264facbe8743
| 420
|
cpp
|
C++
|
learncppdotcom/6.3_3/main.cpp
|
coal0/Challenges
|
528c2a32680b97ca36fed55caea5d545c18ba97a
|
[
"MIT"
] | null | null | null |
learncppdotcom/6.3_3/main.cpp
|
coal0/Challenges
|
528c2a32680b97ca36fed55caea5d545c18ba97a
|
[
"MIT"
] | null | null | null |
learncppdotcom/6.3_3/main.cpp
|
coal0/Challenges
|
528c2a32680b97ca36fed55caea5d545c18ba97a
|
[
"MIT"
] | null | null | null |
#include <iostream>
int main() {
int scores[] = {84, 92, 76, 81, 56};
constexpr int numStudents = sizeof(scores) / sizeof(scores[0]);
int maxScoreIndex = 0;
for (int student = 1; student < numStudents; ++student) {
if (scores[student] > scores[maxScoreIndex]) {
maxScoreIndex = student;
}
}
std::cout << "The best score was at index " << maxScoreIndex << ".\n";
}
| 24.705882
| 74
| 0.57619
|
coal0
|
d3ef8b38e01470bea7ce78e2543629d5a36c8a58
| 81,386
|
cpp
|
C++
|
src/gpu/cgpu/d3d12/cgpu_d3d12.cpp
|
SakuraEngine/Sakura.Runtime
|
5a397fb2b1285326c4216f522fe10e347bd566f7
|
[
"MIT"
] | 29
|
2021-11-19T11:28:22.000Z
|
2022-03-29T00:26:51.000Z
|
src/gpu/cgpu/d3d12/cgpu_d3d12.cpp
|
SakuraEngine/Sakura.Runtime
|
5a397fb2b1285326c4216f522fe10e347bd566f7
|
[
"MIT"
] | null | null | null |
src/gpu/cgpu/d3d12/cgpu_d3d12.cpp
|
SakuraEngine/Sakura.Runtime
|
5a397fb2b1285326c4216f522fe10e347bd566f7
|
[
"MIT"
] | 1
|
2022-03-05T08:14:40.000Z
|
2022-03-05T08:14:40.000Z
|
#include "cgpu/backend/d3d12/cgpu_d3d12.h"
#include "d3d12_utils.h"
#include "../common/common_utils.h"
#include <dxcapi.h>
#include <EASTL/string_hash_map.h>
#if !defined(XBOX)
#pragma comment(lib, "d3d12.lib")
#pragma comment(lib, "dxgi.lib")
#pragma comment(lib, "dxguid.lib")
#pragma comment(lib, "dxcompiler.lib")
#endif
#include <comdef.h>
// Call this only once.
CGPUInstanceId cgpu_create_instance_d3d12(CGPUInstanceDescriptor const* descriptor)
{
CGPUInstance_D3D12* result = cgpu_new<CGPUInstance_D3D12>();
D3D12Util_Optionalenable_debug_layer(result, descriptor);
UINT flags = 0;
if (descriptor->enable_debug_layer) flags = DXGI_CREATE_FACTORY_DEBUG;
#if defined(XBOX)
#else
if (SUCCEEDED(CreateDXGIFactory2(flags, IID_PPV_ARGS(&result->pDXGIFactory))))
{
uint32_t gpuCount = 0;
bool foundSoftwareAdapter = false;
D3D12Util_QueryAllAdapters(result, &gpuCount, &foundSoftwareAdapter);
// If the only adapter we found is a software adapter, log error message for QA
if (!gpuCount && foundSoftwareAdapter)
{
cgpu_assert(0 && "The only available GPU has DXGI_ADAPTER_FLAG_SOFTWARE. Early exiting");
return CGPU_NULLPTR;
}
}
else
{
cgpu_assert("[D3D12 Fatal]: Create DXGIFactory2 Failed!");
}
#endif
return &result->super;
}
void cgpu_query_instance_features_d3d12(CGPUInstanceId instance, struct CGPUInstanceFeatures* features)
{
CGPUInstance_D3D12* I = (CGPUInstance_D3D12*)instance;
(void)I;
features->specialization_constant = false;
}
void cgpu_free_instance_d3d12(CGPUInstanceId instance)
{
CGPUInstance_D3D12* to_destroy = (CGPUInstance_D3D12*)instance;
if (to_destroy->mAdaptersCount > 0)
{
for (uint32_t i = 0; i < to_destroy->mAdaptersCount; i++)
{
SAFE_RELEASE(to_destroy->pAdapters[i].pDxActiveGPU);
}
}
cgpu_free(to_destroy->pAdapters);
SAFE_RELEASE(to_destroy->pDXGIFactory);
if (to_destroy->pDXDebug)
{
SAFE_RELEASE(to_destroy->pDXDebug);
}
cgpu_delete(to_destroy);
#ifdef _DEBUG
{
IDXGIDebug1* dxgiDebug;
if (SUCCEEDED(DXGIGetDebugInterface1(0, IID_PPV_ARGS(&dxgiDebug))))
{
dxgiDebug->ReportLiveObjects(
DXGI_DEBUG_ALL, DXGI_DEBUG_RLO_FLAGS(DXGI_DEBUG_RLO_SUMMARY | DXGI_DEBUG_RLO_IGNORE_INTERNAL));
}
SAFE_RELEASE(dxgiDebug);
}
#endif
}
void cgpu_enum_adapters_d3d12(CGPUInstanceId instance, CGPUAdapterId* const adapters, uint32_t* adapters_num)
{
cgpu_assert(instance != nullptr && "fatal: null instance!");
CGPUInstance_D3D12* I = (CGPUInstance_D3D12*)instance;
*adapters_num = I->mAdaptersCount;
if (!adapters)
{
return;
}
else
{
for (auto i = 0u; i < *adapters_num; i++)
adapters[i] = &(I->pAdapters[i].super);
}
}
const CGPUAdapterDetail* cgpu_query_adapter_detail_d3d12(const CGPUAdapterId adapter)
{
const CGPUAdapter_D3D12* A = (CGPUAdapter_D3D12*)adapter;
return &A->adapter_detail;
}
uint32_t cgpu_query_queue_count_d3d12(const CGPUAdapterId adapter, const ECGPUQueueType type)
{
// queues are virtual in d3d12.
/*
switch(type)
{
case CGPU_QUEUE_TYPE_GRAPHICS: return 1;
case CGPU_QUEUE_TYPE_COMPUTE: return 2;
case CGPU_QUEUE_TYPE_TRANSFER: return 2;
default: return 0;
}
*/
return UINT32_MAX;
}
CGPUDeviceId cgpu_create_device_d3d12(CGPUAdapterId adapter, const CGPUDeviceDescriptor* desc)
{
CGPUAdapter_D3D12* A = (CGPUAdapter_D3D12*)adapter;
CGPUInstance_D3D12* I = (CGPUInstance_D3D12*)A->super.instance;
CGPUDevice_D3D12* D = cgpu_new<CGPUDevice_D3D12>();
*const_cast<CGPUAdapterId*>(&D->super.adapter) = adapter;
if (!SUCCEEDED(D3D12CreateDevice(A->pDxActiveGPU, // default adapter
A->mFeatureLevel, IID_PPV_ARGS(&D->pDxDevice))))
{
cgpu_assert("[D3D12 Fatal]: Create D3D12Device Failed!");
}
// Create Requested Queues.
for (uint32_t i = 0u; i < desc->queueGroupCount; i++)
{
const auto& queueGroup = desc->queueGroups[i];
const auto type = queueGroup.queueType;
*const_cast<uint32_t*>(&D->pCommandQueueCounts[type]) = queueGroup.queueCount;
*const_cast<ID3D12CommandQueue***>(&D->ppCommandQueues[type]) =
(ID3D12CommandQueue**)cgpu_malloc(sizeof(ID3D12CommandQueue*) * queueGroup.queueCount);
for (uint32_t j = 0u; j < queueGroup.queueCount; j++)
{
DECLARE_ZERO(D3D12_COMMAND_QUEUE_DESC, queueDesc)
switch (type)
{
case CGPU_QUEUE_TYPE_GRAPHICS:
queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
break;
case CGPU_QUEUE_TYPE_COMPUTE:
queueDesc.Type = D3D12_COMMAND_LIST_TYPE_COMPUTE;
break;
case CGPU_QUEUE_TYPE_TRANSFER:
queueDesc.Type = D3D12_COMMAND_LIST_TYPE_COPY;
break;
default:
cgpu_assert(0 && "[D3D12 Fatal]: Unsupported ECGPUQueueType!");
return CGPU_NULLPTR;
}
queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
if (!SUCCEEDED(D->pDxDevice->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(&D->ppCommandQueues[type][j]))))
{
cgpu_assert("[D3D12 Fatal]: Create D3D12CommandQueue Failed!");
}
}
}
// Create D3D12MA Allocator
D3D12Util_CreateDMAAllocator(I, A, D);
cgpu_assert(D->pResourceAllocator && "DMA Allocator Must be Created!");
// Create Descriptor Heaps
D->pCPUDescriptorHeaps = (D3D12Util_DescriptorHeap**)cgpu_malloc(D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES * sizeof(D3D12Util_DescriptorHeap*));
D->pCbvSrvUavHeaps = (D3D12Util_DescriptorHeap**)cgpu_malloc(sizeof(D3D12Util_DescriptorHeap*));
D->pSamplerHeaps = (D3D12Util_DescriptorHeap**)cgpu_malloc(sizeof(D3D12Util_DescriptorHeap*));
for (uint32_t i = 0; i < D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES; ++i)
{
D3D12_DESCRIPTOR_HEAP_DESC desc = {};
desc.Flags = gCpuDescriptorHeapProperties[i].mFlags;
desc.NodeMask = 0; // CPU Descriptor Heap - Node mask is irrelevant
desc.NumDescriptors = gCpuDescriptorHeapProperties[i].mMaxDescriptors;
desc.Type = (D3D12_DESCRIPTOR_HEAP_TYPE)i;
D3D12Util_CreateDescriptorHeap(D->pDxDevice, &desc, &D->pCPUDescriptorHeaps[i]);
}
// One shader visible heap for each linked node
for (uint32_t i = 0; i < SINGLE_GPU_NODE_COUNT; ++i)
{
D3D12_DESCRIPTOR_HEAP_DESC desc = {};
desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
desc.NodeMask = SINGLE_GPU_NODE_MASK;
desc.NumDescriptors = 1 << 16;
desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
D3D12Util_CreateDescriptorHeap(D->pDxDevice, &desc, &D->pCbvSrvUavHeaps[i]);
desc.NumDescriptors = 1 << 11;
desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER;
D3D12Util_CreateDescriptorHeap(D->pDxDevice, &desc, &D->pSamplerHeaps[i]);
}
// Pipeline cache
D3D12_FEATURE_DATA_SHADER_CACHE feature = {};
HRESULT result = D->pDxDevice->CheckFeatureSupport(
D3D12_FEATURE_SHADER_CACHE, &feature, sizeof(feature));
if (SUCCEEDED(result))
{
result = E_NOTIMPL;
if (feature.SupportFlags & D3D12_SHADER_CACHE_SUPPORT_LIBRARY)
{
ID3D12Device1* device1 = NULL;
result = D->pDxDevice->QueryInterface(IID_ARGS(&device1));
if (SUCCEEDED(result))
{
result = device1->CreatePipelineLibrary(
D->pPSOCacheData, 0, IID_ARGS(&D->pPipelineLibrary));
}
SAFE_RELEASE(device1);
}
}
return &D->super;
}
void cgpu_free_device_d3d12(CGPUDeviceId device)
{
CGPUDevice_D3D12* D = (CGPUDevice_D3D12*)device;
for (uint32_t t = 0u; t < CGPU_QUEUE_TYPE_COUNT; t++)
{
for (uint32_t i = 0; i < D->pCommandQueueCounts[t]; i++)
{
SAFE_RELEASE(D->ppCommandQueues[t][i]);
}
cgpu_free((ID3D12CommandQueue**)D->ppCommandQueues[t]);
}
// Free D3D12MA Allocator
SAFE_RELEASE(D->pResourceAllocator);
// Free Descriptor Heaps
for (uint32_t i = 0; i < D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES; i++)
{
D3D12Util_FreeDescriptorHeap(D->pCPUDescriptorHeaps[i]);
}
D3D12Util_FreeDescriptorHeap(D->pCbvSrvUavHeaps[0]);
D3D12Util_FreeDescriptorHeap(D->pSamplerHeaps[0]);
cgpu_free(D->pCPUDescriptorHeaps);
cgpu_free(D->pCbvSrvUavHeaps);
cgpu_free(D->pSamplerHeaps);
// Release D3D12 Device
SAFE_RELEASE(D->pDxDevice);
SAFE_RELEASE(D->pPipelineLibrary);
if (D->pPSOCacheData) cgpu_free(D->pPSOCacheData);
cgpu_delete(D);
}
// API Objects APIs
CGPUFenceId cgpu_create_fence_d3d12(CGPUDeviceId device)
{
CGPUDevice_D3D12* D = (CGPUDevice_D3D12*)device;
// create a Fence and cgpu_assert that it is valid
CGPUFence_D3D12* F = cgpu_new<CGPUFence_D3D12>();
cgpu_assert(F);
CHECK_HRESULT(D->pDxDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_ARGS(&F->pDxFence)));
F->mFenceValue = 1;
F->pDxWaitIdleFenceEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
return &F->super;
}
void cgpu_wait_fences_d3d12(const CGPUFenceId* fences, uint32_t fence_count)
{
const CGPUFence_D3D12** Fences = (const CGPUFence_D3D12**)fences;
for (uint32_t i = 0; i < fence_count; ++i)
{
ECGPUFenceStatus fenceStatus = cgpu_query_fence_status(fences[i]);
uint64_t fenceValue = Fences[i]->mFenceValue - 1;
if (fenceStatus == CGPU_FENCE_STATUS_INCOMPLETE)
{
Fences[i]->pDxFence->SetEventOnCompletion(
fenceValue, Fences[i]->pDxWaitIdleFenceEvent);
WaitForSingleObject(Fences[i]->pDxWaitIdleFenceEvent, INFINITE);
}
}
}
ECGPUFenceStatus cgpu_query_fence_status_d3d12(CGPUFenceId fence)
{
ECGPUFenceStatus status = CGPU_FENCE_STATUS_COMPLETE;
CGPUFence_D3D12* F = (CGPUFence_D3D12*)fence;
if (F->pDxFence->GetCompletedValue() < F->mFenceValue - 1)
status = CGPU_FENCE_STATUS_INCOMPLETE;
else
status = CGPU_FENCE_STATUS_COMPLETE;
return status;
}
void cgpu_free_fence_d3d12(CGPUFenceId fence)
{
CGPUFence_D3D12* F = (CGPUFence_D3D12*)fence;
SAFE_RELEASE(F->pDxFence);
CloseHandle(F->pDxWaitIdleFenceEvent);
cgpu_delete(F);
}
CGPUSemaphoreId cgpu_create_semaphore_d3d12(CGPUDeviceId device)
{
return (CGPUSemaphoreId)cgpu_create_fence(device);
}
void cgpu_free_semaphore_d3d12(CGPUSemaphoreId semaphore)
{
return cgpu_free_fence((CGPUFenceId)semaphore);
}
CGPURootSignaturePoolId cgpu_create_root_signature_pool_d3d12(CGPUDeviceId device, const struct CGPURootSignaturePoolDescriptor* desc)
{
return CGPUUtil_CreateRootSignaturePool(desc);
}
void cgpu_free_root_signature_pool_d3d12(CGPURootSignaturePoolId pool)
{
CGPUUtil_FreeRootSignaturePool(pool);
}
// for example, shader register set: (s0t0) (s0b1) [s0b0[root]] (s1t0) (s1t1) {s2s0{static}}
// rootParams: | s0 | s1 | [s0b0] |
// rootRanges: | s0t0 | s0b1 | s1t0 | s1t1 |
// staticSamplers: | s2s0 | ... |
CGPURootSignatureId cgpu_create_root_signature_d3d12(CGPUDeviceId device, const struct CGPURootSignatureDescriptor* desc)
{
CGPUDevice_D3D12* D = (CGPUDevice_D3D12*)device;
CGPURootSignature_D3D12* RS = cgpu_new<CGPURootSignature_D3D12>();
// Pick root parameters from desc data
CGPUShaderStages shaderStages = 0;
for (uint32_t i = 0; i < desc->shader_count; i++)
{
CGPUPipelineShaderDescriptor* shader_desc = desc->shaders + i;
shaderStages |= shader_desc->stage;
}
// Pick shader reflection data
CGPUUtil_InitRSParamTables((CGPURootSignature*)RS, desc);
// [RS POOL] ALLOCATION
if (desc->pool)
{
CGPURootSignature_D3D12* poolSig =
(CGPURootSignature_D3D12*)CGPUUtil_TryAllocateSignature(desc->pool, &RS->super, desc);
if (poolSig != CGPU_NULLPTR)
{
RS->mRootConstantParam = poolSig->mRootConstantParam;
RS->pDxRootSignature = poolSig->pDxRootSignature;
RS->mRootParamIndex = poolSig->mRootParamIndex;
RS->super.pool = desc->pool;
RS->super.pool_sig = &poolSig->super;
return &RS->super;
}
}
// [RS POOL] END ALLOCATION
// Fill resource slots
// Only support descriptor tables now
// TODO: Support root CBVs
// Add backend sort for better performance
const UINT tableCount = RS->super.table_count;
UINT descRangeCount = 0;
for (uint32_t i = 0; i < tableCount; i++)
{
descRangeCount += RS->super.tables[i].resources_count;
}
D3D12_ROOT_PARAMETER1* rootParams = (D3D12_ROOT_PARAMETER1*)cgpu_calloc(
tableCount + RS->super.push_constant_count,
sizeof(D3D12_ROOT_PARAMETER1));
D3D12_DESCRIPTOR_RANGE1* cbvSrvUavRanges = (D3D12_DESCRIPTOR_RANGE1*)cgpu_calloc(descRangeCount, sizeof(D3D12_DESCRIPTOR_RANGE1));
// Create descriptor tables
UINT valid_root_tables = 0;
for (uint32_t i_set = 0, i_range = 0; i_set < RS->super.table_count; i_set++)
{
CGPUParameterTable* paramTable = &RS->super.tables[i_set];
D3D12_ROOT_PARAMETER1* rootParam = &rootParams[valid_root_tables];
rootParam->ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
CGPUShaderStages visStages = CGPU_SHADER_STAGE_NONE;
const D3D12_DESCRIPTOR_RANGE1* descRangeCursor = &cbvSrvUavRanges[i_range];
for (uint32_t i_register = 0; i_register < paramTable->resources_count; i_register++)
{
CGPUShaderResource* reflSlot = ¶mTable->resources[i_register];
visStages |= reflSlot->stages;
// Record RS::mRootConstantParam directly, it'll be copied to the end of rootParams list
{
D3D12_DESCRIPTOR_RANGE1* descRange = &cbvSrvUavRanges[i_range];
descRange->RegisterSpace = reflSlot->set;
descRange->BaseShaderRegister = reflSlot->binding;
descRange->Flags = D3D12_DESCRIPTOR_RANGE_FLAG_NONE;
descRange->NumDescriptors = (reflSlot->type != CGPU_RESOURCE_TYPE_UNIFORM_BUFFER) ? reflSlot->size : 1;
descRange->OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
descRange->RangeType = D3D12Util_ResourceTypeToDescriptorRangeType(reflSlot->type);
rootParam->DescriptorTable.NumDescriptorRanges++;
i_range++;
}
}
if (visStages != 0)
{
rootParam->ShaderVisibility = D3D12Util_TranslateShaderStages(visStages);
rootParam->DescriptorTable.pDescriptorRanges = descRangeCursor;
valid_root_tables++;
}
}
// Root Const
assert(RS->super.push_constant_count <= 1 && "Only support 1 push const now!");
if (RS->super.push_constant_count)
{
auto reflSlot = RS->super.push_constants;
RS->mRootConstantParam.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
RS->mRootConstantParam.Constants.RegisterSpace = reflSlot->set;
RS->mRootConstantParam.Constants.ShaderRegister = reflSlot->binding;
RS->mRootConstantParam.Constants.Num32BitValues = reflSlot->size / sizeof(uint32_t);
RS->mRootConstantParam.ShaderVisibility = D3D12Util_TranslateShaderStages(reflSlot->stages);
}
// Create static samplers
UINT staticSamplerCount = desc->static_sampler_count;
D3D12_STATIC_SAMPLER_DESC* staticSamplerDescs = CGPU_NULLPTR;
if (staticSamplerCount > 0)
{
staticSamplerDescs = (D3D12_STATIC_SAMPLER_DESC*)alloca(
staticSamplerCount * sizeof(D3D12_STATIC_SAMPLER_DESC));
for (uint32_t i = 0; i < RS->super.static_sampler_count; i++)
{
auto& RST_slot = RS->super.static_samplers[i];
for (uint32_t j = 0; j < desc->static_sampler_count; j++)
{
auto input_slot = (CGPUSampler_D3D12*)desc->static_samplers[j];
if (strcmp(RST_slot.name, desc->static_sampler_names[j]) == 0)
{
D3D12_SAMPLER_DESC& desc = input_slot->mDxDesc;
staticSamplerDescs[i].Filter = desc.Filter;
staticSamplerDescs[i].AddressU = desc.AddressU;
staticSamplerDescs[i].AddressV = desc.AddressV;
staticSamplerDescs[i].AddressW = desc.AddressW;
staticSamplerDescs[i].MipLODBias = desc.MipLODBias;
staticSamplerDescs[i].MaxAnisotropy = desc.MaxAnisotropy;
staticSamplerDescs[i].ComparisonFunc = desc.ComparisonFunc;
staticSamplerDescs[i].MinLOD = desc.MinLOD;
staticSamplerDescs[i].MaxLOD = desc.MaxLOD;
staticSamplerDescs[i].BorderColor = D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK;
CGPUShaderResource* samplerResource = &RST_slot;
staticSamplerDescs[i].RegisterSpace = samplerResource->set;
staticSamplerDescs[i].ShaderRegister = samplerResource->binding;
staticSamplerDescs[i].ShaderVisibility = D3D12Util_TranslateShaderStages(samplerResource->stages);
}
}
}
}
bool useInputLayout = shaderStages & CGPU_SHADER_STAGE_VERT; // VertexStage uses input layout
// Fill RS flags
D3D12_ROOT_SIGNATURE_FLAGS rootSignatureFlags = D3D12_ROOT_SIGNATURE_FLAG_NONE;
if (useInputLayout)
rootSignatureFlags |= D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT;
if (!(shaderStages & CGPU_SHADER_STAGE_VERT))
rootSignatureFlags |= D3D12_ROOT_SIGNATURE_FLAG_DENY_VERTEX_SHADER_ROOT_ACCESS;
if (!(shaderStages & CGPU_SHADER_STAGE_HULL))
rootSignatureFlags |= D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS;
if (!(shaderStages & CGPU_SHADER_STAGE_DOMAIN))
rootSignatureFlags |= D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS;
if (!(shaderStages & CGPU_SHADER_STAGE_GEOM))
rootSignatureFlags |= D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS;
if (!(shaderStages & CGPU_SHADER_STAGE_FRAG))
rootSignatureFlags |= D3D12_ROOT_SIGNATURE_FLAG_DENY_PIXEL_SHADER_ROOT_ACCESS;
// Serialize versioned RS
const UINT paramCount = valid_root_tables + RS->super.push_constant_count /*must be 0 or 1 now*/;
// Root Constant
assert(RS->super.push_constant_count <= 1 && "Only support 1 push const now!");
for (uint32_t i = 0; i < RS->super.push_constant_count; i++)
{
rootParams[valid_root_tables + i] = RS->mRootConstantParam;
RS->mRootParamIndex = valid_root_tables + i;
}
// Serialize PSO
ID3DBlob* error = NULL;
ID3DBlob* rootSignatureString = NULL;
DECLARE_ZERO(D3D12_VERSIONED_ROOT_SIGNATURE_DESC, sig_desc);
sig_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_1;
sig_desc.Desc_1_1.NumParameters = paramCount;
sig_desc.Desc_1_1.pParameters = rootParams;
sig_desc.Desc_1_1.NumStaticSamplers = staticSamplerCount;
sig_desc.Desc_1_1.pStaticSamplers = staticSamplerDescs;
sig_desc.Desc_1_1.Flags = rootSignatureFlags;
HRESULT hres = D3D12SerializeVersionedRootSignature(&sig_desc, &rootSignatureString, &error);
if (!SUCCEEDED(hres))
{
cgpu_error("Failed to serialize root signature with error (%s)", (char*)error->GetBufferPointer());
}
// If running Linked Mode (SLI) create root signature for all nodes
// #NOTE : In non SLI mode, mNodeCount will be 0 which sets nodeMask to
// default value
CHECK_HRESULT(D->pDxDevice->CreateRootSignature(
SINGLE_GPU_NODE_MASK,
rootSignatureString->GetBufferPointer(),
rootSignatureString->GetBufferSize(),
IID_ARGS(&RS->pDxRootSignature)));
cgpu_free(rootParams);
cgpu_free(cbvSrvUavRanges);
// [RS POOL] INSERTION
if (desc->pool)
{
const bool result = CGPUUtil_AddSignature(desc->pool, &RS->super, desc);
cgpu_assert(result && "Root signature pool insertion failed!");
}
// [RS POOL] END INSERTION
return &RS->super;
}
void cgpu_free_root_signature_d3d12(CGPURootSignatureId signature)
{
CGPURootSignature_D3D12* RS = (CGPURootSignature_D3D12*)signature;
// [RS POOL] FREE
if (signature->pool)
{
CGPUUtil_PoolFreeSignature(signature->pool, signature);
if (signature->pool_sig) // not root
{
// Free Reflection Data
CGPUUtil_FreeRSParamTables((CGPURootSignature*)signature);
cgpu_delete(RS);
}
return;
}
// [RS POOL] END FREE
CGPUUtil_FreeRSParamTables((CGPURootSignature*)signature);
SAFE_RELEASE(RS->pDxRootSignature);
cgpu_delete(RS);
}
CGPUDescriptorSetId cgpu_create_descriptor_set_d3d12(CGPUDeviceId device, const struct CGPUDescriptorSetDescriptor* desc)
{
CGPUDevice_D3D12* D = (CGPUDevice_D3D12*)device;
const CGPURootSignature_D3D12* RS = (const CGPURootSignature_D3D12*)desc->root_signature;
CGPUDescriptorSet_D3D12* Set = cgpu_new<CGPUDescriptorSet_D3D12>();
const uint32_t nodeIndex = SINGLE_GPU_NODE_INDEX;
struct D3D12Util_DescriptorHeap* pCbvSrvUavHeap = D->pCbvSrvUavHeaps[nodeIndex];
struct D3D12Util_DescriptorHeap* pSamplerHeap = D->pSamplerHeaps[nodeIndex];
(void)pSamplerHeap;
CGPUParameterTable* param_table = &RS->super.tables[desc->set_index];
uint32_t CbvSrvUavCount = 0;
uint32_t SamplerCount = 0;
for (uint32_t i = 0; i < param_table->resources_count; i++)
{
if (param_table->resources[i].type == CGPU_RESOURCE_TYPE_SAMPLER)
SamplerCount++;
else if (param_table->resources[i].type == CGPU_RESOURCE_TYPE_TEXTURE ||
param_table->resources[i].type == CGPU_RESOURCE_TYPE_RW_TEXTURE ||
param_table->resources[i].type == CGPU_RESOURCE_TYPE_BUFFER ||
param_table->resources[i].type == CGPU_RESOURCE_TYPE_BUFFER_RAW ||
param_table->resources[i].type == CGPU_RESOURCE_TYPE_RW_BUFFER ||
param_table->resources[i].type == CGPU_RESOURCE_TYPE_RW_BUFFER_RAW ||
param_table->resources[i].type == CGPU_RESOURCE_TYPE_TEXTURE_CUBE ||
param_table->resources[i].type == CGPU_RESOURCE_TYPE_UNIFORM_BUFFER)
{
CbvSrvUavCount++;
}
}
// CBV/SRV/UAV
Set->mCbvSrvUavHandle = D3D12_GPU_VIRTUAL_ADDRESS_UNKNOWN;
Set->mSamplerHandle = D3D12_GPU_VIRTUAL_ADDRESS_UNKNOWN;
if (CbvSrvUavCount)
{
auto StartHandle = D3D12Util_ConsumeDescriptorHandles(pCbvSrvUavHeap, param_table->resources_count);
Set->mCbvSrvUavHandle = StartHandle.mGpu.ptr - pCbvSrvUavHeap->mStartHandle.mGpu.ptr;
Set->mCbvSrvUavStride = CbvSrvUavCount * pCbvSrvUavHeap->mDescriptorSize;
}
if (SamplerCount)
{
auto StartHandle = D3D12Util_ConsumeDescriptorHandles(pSamplerHeap, param_table->resources_count);
Set->mSamplerHandle = StartHandle.mGpu.ptr - pSamplerHeap->mStartHandle.mGpu.ptr;
Set->mSamplerStride = SamplerCount * pSamplerHeap->mDescriptorSize;
}
// TODO: Bind NULL handles on creation
// TODO: Support root descriptors
return &Set->super;
}
uint32_t descriptor_count_needed(CGPUShaderResource* resource)
{
if (resource->dim == CGPU_TEX_DIMENSION_1D_ARRAY ||
resource->dim == CGPU_TEX_DIMENSION_2D_ARRAY ||
resource->dim == CGPU_TEX_DIMENSION_2DMS_ARRAY ||
resource->dim == CGPU_TEX_DIMENSION_CUBE_ARRAY)
return resource->size;
else
return 1;
}
void cgpu_update_descriptor_set_d3d12(CGPUDescriptorSetId set, const struct CGPUDescriptorData* datas, uint32_t count)
{
CGPUDescriptorSet_D3D12* Set = (CGPUDescriptorSet_D3D12*)set;
const CGPURootSignature_D3D12* RS = (const CGPURootSignature_D3D12*)set->root_signature;
CGPUDevice_D3D12* D = (CGPUDevice_D3D12*)set->root_signature->device;
CGPUParameterTable* ParamTable = &RS->super.tables[set->index];
const uint32_t nodeIndex = SINGLE_GPU_NODE_INDEX;
struct D3D12Util_DescriptorHeap* pCbvSrvUavHeap = D->pCbvSrvUavHeaps[nodeIndex];
struct D3D12Util_DescriptorHeap* pSamplerHeap = D->pSamplerHeaps[nodeIndex];
for (uint32_t i = 0; i < count; i++)
{
// Descriptor Info
const CGPUDescriptorData* pParam = datas + i;
CGPUShaderResource* ResData = CGPU_NULLPTR;
uint32_t HeapOffset = 0;
if (pParam->name != CGPU_NULLPTR)
{
size_t argNameHash = cgpu_hash(pParam->name, strlen(pParam->name), *(size_t*)&D);
for (uint32_t j = 0; j < ParamTable->resources_count; j++)
{
if (ParamTable->resources[j].name_hash == argNameHash)
{
ResData = ParamTable->resources + j;
break;
}
HeapOffset += descriptor_count_needed(&ParamTable->resources[j]);
}
}
else
{
for (uint32_t j = 0; j < ParamTable->resources_count; j++)
{
if (ParamTable->resources[j].type == pParam->binding_type &&
ParamTable->resources[j].binding == pParam->binding)
{
ResData = &ParamTable->resources[j];
break;
}
HeapOffset += descriptor_count_needed(&ParamTable->resources[j]);
}
}
// Update Info
const uint32_t arrayCount = cgpu_max(1U, pParam->count);
switch (ResData->type)
{
case CGPU_RESOURCE_TYPE_SAMPLER: {
cgpu_assert(pParam->samplers && "cgpu_assert: Binding NULL Sampler(s)!");
CGPUSampler_D3D12** Samplers = (CGPUSampler_D3D12**)pParam->samplers;
for (uint32_t arr = 0; arr < arrayCount; arr++)
{
cgpu_assert(pParam->samplers[arr] && "cgpu_assert: Binding NULL Sampler!");
D3D12Util_CopyDescriptorHandle(pSamplerHeap,
{ Samplers[arr]->mDxHandle.ptr },
Set->mSamplerHandle, arr + HeapOffset);
}
}
break;
case CGPU_RESOURCE_TYPE_TEXTURE:
case CGPU_RESOURCE_TYPE_TEXTURE_CUBE: {
cgpu_assert(pParam->textures && "cgpu_assert: Binding NULL Textures(s)!");
CGPUTextureView_D3D12** Textures = (CGPUTextureView_D3D12**)pParam->textures;
for (uint32_t arr = 0; arr < arrayCount; arr++)
{
cgpu_assert(pParam->textures[arr] && "cgpu_assert: Binding NULL Textures!");
D3D12Util_CopyDescriptorHandle(pCbvSrvUavHeap,
{ Textures[arr]->mDxDescriptorHandles.ptr + Textures[arr]->mDxSrvOffset },
Set->mCbvSrvUavHandle, arr + HeapOffset);
}
}
break;
case CGPU_RESOURCE_TYPE_BUFFER:
case CGPU_RESOURCE_TYPE_BUFFER_RAW: {
cgpu_assert(pParam->buffers && "cgpu_assert: Binding NULL Buffer(s)!");
CGPUBuffer_D3D12** Buffers = (CGPUBuffer_D3D12**)pParam->buffers;
for (uint32_t arr = 0; arr < arrayCount; arr++)
{
cgpu_assert(pParam->buffers[arr] && "cgpu_assert: Binding NULL Buffer!");
D3D12Util_CopyDescriptorHandle(pCbvSrvUavHeap,
{ Buffers[arr]->mDxDescriptorHandles.ptr + Buffers[arr]->mDxSrvOffset },
Set->mCbvSrvUavHandle, arr + HeapOffset);
}
}
break;
case CGPU_RESOURCE_TYPE_UNIFORM_BUFFER: {
cgpu_assert(pParam->buffers && "cgpu_assert: Binding NULL Buffer(s)!");
CGPUBuffer_D3D12** Buffers = (CGPUBuffer_D3D12**)pParam->buffers;
for (uint32_t arr = 0; arr < arrayCount; arr++)
{
cgpu_assert(pParam->buffers[arr] && "cgpu_assert: Binding NULL Buffer!");
D3D12Util_CopyDescriptorHandle(pCbvSrvUavHeap,
{ Buffers[arr]->mDxDescriptorHandles.ptr },
Set->mCbvSrvUavHandle, arr + HeapOffset);
}
}
break;
case CGPU_RESOURCE_TYPE_RW_TEXTURE: {
cgpu_assert(pParam->textures && "cgpu_assert: Binding NULL Texture(s)!");
CGPUTextureView_D3D12** Textures = (CGPUTextureView_D3D12**)pParam->textures;
for (uint32_t arr = 0; arr < arrayCount; arr++)
{
cgpu_assert(pParam->textures[arr] && "cgpu_assert: Binding NULL Texture!");
D3D12Util_CopyDescriptorHandle(pCbvSrvUavHeap,
{ Textures[arr]->mDxDescriptorHandles.ptr + Textures[arr]->mDxUavOffset },
Set->mCbvSrvUavHandle, arr + HeapOffset);
}
}
break;
case CGPU_RESOURCE_TYPE_RW_BUFFER:
case CGPU_RESOURCE_TYPE_RW_BUFFER_RAW: {
cgpu_assert(pParam->buffers && "cgpu_assert: Binding NULL Buffer(s)!");
CGPUBuffer_D3D12** Buffers = (CGPUBuffer_D3D12**)pParam->buffers;
for (uint32_t arr = 0; arr < arrayCount; arr++)
{
cgpu_assert(pParam->buffers[arr] && "cgpu_assert: Binding NULL Buffer!");
D3D12Util_CopyDescriptorHandle(pCbvSrvUavHeap,
{ Buffers[arr]->mDxDescriptorHandles.ptr + Buffers[arr]->mDxUavOffset },
Set->mCbvSrvUavHandle, arr + HeapOffset);
}
}
break;
default:
break;
}
}
}
void cgpu_free_descriptor_set_d3d12(CGPUDescriptorSetId set)
{
CGPUDevice_D3D12* D = (CGPUDevice_D3D12*)set->root_signature->device;
CGPUDescriptorSet_D3D12* Set = (CGPUDescriptorSet_D3D12*)set;
(void)D; // TODO: recycle of descriptor set heap handles
cgpu_delete(Set);
}
CGPUComputePipelineId cgpu_create_compute_pipeline_d3d12(CGPUDeviceId device, const struct CGPUComputePipelineDescriptor* desc)
{
CGPUDevice_D3D12* D = (CGPUDevice_D3D12*)device;
CGPUComputePipeline_D3D12* PPL = cgpu_new<CGPUComputePipeline_D3D12>();
CGPURootSignature_D3D12* RS = (CGPURootSignature_D3D12*)desc->root_signature;
CGPUShaderLibrary_D3D12* SL = (CGPUShaderLibrary_D3D12*)desc->compute_shader->library;
PPL->pRootSignature = RS->pDxRootSignature;
// Add pipeline specifying its for compute purposes
DECLARE_ZERO(D3D12_SHADER_BYTECODE, CS);
CS.BytecodeLength = SL->pShaderBlob->GetBufferSize();
CS.pShaderBytecode = SL->pShaderBlob->GetBufferPointer();
DECLARE_ZERO(D3D12_CACHED_PIPELINE_STATE, cached_pso_desc);
cached_pso_desc.pCachedBlob = NULL;
cached_pso_desc.CachedBlobSizeInBytes = 0;
DECLARE_ZERO(D3D12_COMPUTE_PIPELINE_STATE_DESC, pipeline_state_desc);
pipeline_state_desc.pRootSignature = RS->pDxRootSignature;
pipeline_state_desc.CS = CS;
pipeline_state_desc.CachedPSO = cached_pso_desc;
pipeline_state_desc.Flags = D3D12_PIPELINE_STATE_FLAG_NONE;
pipeline_state_desc.NodeMask = SINGLE_GPU_NODE_MASK;
// Pipeline cache
HRESULT result = E_FAIL;
wchar_t pipelineName[PSO_NAME_LENGTH] = {};
size_t psoShaderHash = 0;
size_t psoComputeHash = 0;
if (D->pPipelineLibrary)
{
if (CS.BytecodeLength)
psoShaderHash = cgpu_hash(CS.pShaderBytecode, CS.BytecodeLength, psoShaderHash);
psoComputeHash = cgpu_hash(&pipeline_state_desc.Flags, sizeof(D3D12_PIPELINE_STATE_FLAGS), psoComputeHash);
psoComputeHash = cgpu_hash(&pipeline_state_desc.NodeMask, sizeof(UINT), psoComputeHash);
swprintf(pipelineName, PSO_NAME_LENGTH, L"%S_S%zuR%zu", "COMPUTEPSO", psoShaderHash, psoComputeHash);
result = D->pPipelineLibrary->LoadComputePipeline(pipelineName,
&pipeline_state_desc, IID_ARGS(&PPL->pDxPipelineState));
}
if (!SUCCEEDED(result))
{
// XBOX: Support PSO extensions
CHECK_HRESULT(D->pDxDevice->CreateComputePipelineState(
&pipeline_state_desc, IID_PPV_ARGS(&PPL->pDxPipelineState)));
}
return &PPL->super;
}
void cgpu_free_compute_pipeline_d3d12(CGPUComputePipelineId pipeline)
{
CGPUComputePipeline_D3D12* PPL = (CGPUComputePipeline_D3D12*)pipeline;
SAFE_RELEASE(PPL->pDxPipelineState);
cgpu_delete(PPL);
}
D3D12_DEPTH_STENCIL_DESC gDefaultDepthDesc = {};
D3D12_BLEND_DESC gDefaultBlendDesc = {};
D3D12_RASTERIZER_DESC gDefaultRasterizerDesc = {};
CGPURenderPipelineId cgpu_create_render_pipeline_d3d12(CGPUDeviceId device, const struct CGPURenderPipelineDescriptor* desc)
{
CGPUDevice_D3D12* D = (CGPUDevice_D3D12*)device;
CGPURenderPipeline_D3D12* PPL = cgpu_new<CGPURenderPipeline_D3D12>();
CGPURootSignature_D3D12* RS = (CGPURootSignature_D3D12*)desc->root_signature;
// Vertex input state
DECLARE_ZERO(D3D12_INPUT_ELEMENT_DESC, input_elements[CGPU_MAX_VERTEX_ATTRIBS]);
uint32_t elem_count = 0;
if (desc->vertex_layout != nullptr)
{
for (uint32_t attrib_index = 0; attrib_index < desc->vertex_layout->attribute_count; ++attrib_index)
{
const CGPUVertexAttribute* attrib = &(desc->vertex_layout->attributes[attrib_index]);
for (uint32_t arr_index = 0; arr_index < attrib->array_size; arr_index++)
{
input_elements[elem_count].SemanticIndex = arr_index;
input_elements[elem_count].SemanticName = attrib->semantic_name;
input_elements[elem_count].Format = DXGIUtil_TranslatePixelFormat(attrib->format);
input_elements[elem_count].InputSlot = attrib->binding;
input_elements[elem_count].AlignedByteOffset = attrib->offset + arr_index * FormatUtil_BitSizeOfBlock(attrib->format) / 8;
if (attrib->rate == CGPU_INPUT_RATE_INSTANCE)
{
input_elements[elem_count].InputSlotClass = D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA;
input_elements[elem_count].InstanceDataStepRate = 1;
}
else
{
input_elements[elem_count].InputSlotClass = D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA;
input_elements[elem_count].InstanceDataStepRate = 0;
}
elem_count++;
}
}
}
DECLARE_ZERO(D3D12_INPUT_LAYOUT_DESC, input_layout_desc);
input_layout_desc.pInputElementDescs = elem_count ? input_elements : NULL;
input_layout_desc.NumElements = elem_count;
// Shader stages
DECLARE_ZERO(D3D12_SHADER_BYTECODE, VS);
DECLARE_ZERO(D3D12_SHADER_BYTECODE, PS);
DECLARE_ZERO(D3D12_SHADER_BYTECODE, DS);
DECLARE_ZERO(D3D12_SHADER_BYTECODE, HS);
DECLARE_ZERO(D3D12_SHADER_BYTECODE, GS);
for (uint32_t i = 0; i < 5; ++i)
{
ECGPUShaderStage stage_mask = (ECGPUShaderStage)(1 << i);
switch (stage_mask)
{
case CGPU_SHADER_STAGE_VERT: {
if (desc->vertex_shader)
{
CGPUShaderLibrary_D3D12* VertLib = (CGPUShaderLibrary_D3D12*)desc->vertex_shader->library;
VS.BytecodeLength = VertLib->pShaderBlob->GetBufferSize();
VS.pShaderBytecode = VertLib->pShaderBlob->GetBufferPointer();
}
}
break;
case CGPU_SHADER_STAGE_TESC: {
if (desc->tesc_shader)
{
CGPUShaderLibrary_D3D12* TescLib = (CGPUShaderLibrary_D3D12*)desc->tesc_shader->library;
HS.BytecodeLength = TescLib->pShaderBlob->GetBufferSize();
HS.pShaderBytecode = TescLib->pShaderBlob->GetBufferPointer();
}
}
break;
case CGPU_SHADER_STAGE_TESE: {
if (desc->tese_shader)
{
CGPUShaderLibrary_D3D12* TeseLib = (CGPUShaderLibrary_D3D12*)desc->tese_shader->library;
DS.BytecodeLength = TeseLib->pShaderBlob->GetBufferSize();
DS.pShaderBytecode = TeseLib->pShaderBlob->GetBufferPointer();
}
}
break;
case CGPU_SHADER_STAGE_GEOM: {
if (desc->geom_shader)
{
CGPUShaderLibrary_D3D12* GeomLib = (CGPUShaderLibrary_D3D12*)desc->geom_shader->library;
GS.BytecodeLength = GeomLib->pShaderBlob->GetBufferSize();
GS.pShaderBytecode = GeomLib->pShaderBlob->GetBufferPointer();
}
}
break;
case CGPU_SHADER_STAGE_FRAG: {
if (desc->fragment_shader)
{
CGPUShaderLibrary_D3D12* FragLib = (CGPUShaderLibrary_D3D12*)desc->fragment_shader->library;
PS.BytecodeLength = FragLib->pShaderBlob->GetBufferSize();
PS.pShaderBytecode = FragLib->pShaderBlob->GetBufferPointer();
}
}
break;
default:
cgpu_assert(false && "Shader Stage not supported!");
break;
}
}
// Stream out
DECLARE_ZERO(D3D12_STREAM_OUTPUT_DESC, stream_output_desc);
stream_output_desc.pSODeclaration = NULL;
stream_output_desc.NumEntries = 0;
stream_output_desc.pBufferStrides = NULL;
stream_output_desc.NumStrides = 0;
stream_output_desc.RasterizedStream = 0;
// Sample
DECLARE_ZERO(DXGI_SAMPLE_DESC, sample_desc);
sample_desc.Count = (UINT)(desc->sample_count);
sample_desc.Quality = (UINT)(desc->sample_quality);
DECLARE_ZERO(D3D12_CACHED_PIPELINE_STATE, cached_pso_desc);
cached_pso_desc.pCachedBlob = NULL;
cached_pso_desc.CachedBlobSizeInBytes = 0;
// Fill pipeline object desc
DECLARE_ZERO(D3D12_GRAPHICS_PIPELINE_STATE_DESC, pipeline_state_desc);
pipeline_state_desc.pRootSignature = RS->pDxRootSignature;
// Single GPU
pipeline_state_desc.NodeMask = SINGLE_GPU_NODE_MASK;
pipeline_state_desc.VS = VS;
pipeline_state_desc.PS = PS;
pipeline_state_desc.DS = DS;
pipeline_state_desc.HS = HS;
pipeline_state_desc.GS = GS;
pipeline_state_desc.StreamOutput = stream_output_desc;
pipeline_state_desc.BlendState = desc->blend_state ? D3D12Util_TranslateBlendState(desc->blend_state) : gDefaultBlendDesc;
pipeline_state_desc.SampleMask = UINT_MAX;
pipeline_state_desc.RasterizerState = desc->rasterizer_state ? D3D12Util_TranslateRasterizerState(desc->rasterizer_state) : gDefaultRasterizerDesc;
// Depth stencil
pipeline_state_desc.DepthStencilState = desc->depth_state ? D3D12Util_TranslateDephStencilState(desc->depth_state) : gDefaultDepthDesc;
pipeline_state_desc.InputLayout = input_layout_desc;
pipeline_state_desc.IBStripCutValue = D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED;
pipeline_state_desc.PrimitiveTopologyType = D3D12Util_TranslatePrimitiveTopology(desc->prim_topology);
pipeline_state_desc.NumRenderTargets = desc->render_target_count;
pipeline_state_desc.DSVFormat = DXGIUtil_TranslatePixelFormat(desc->depth_stencil_format);
pipeline_state_desc.SampleDesc = sample_desc;
pipeline_state_desc.CachedPSO = cached_pso_desc;
pipeline_state_desc.Flags = D3D12_PIPELINE_STATE_FLAG_NONE;
for (uint32_t i = 0; i < pipeline_state_desc.NumRenderTargets; ++i)
{
pipeline_state_desc.RTVFormats[i] = DXGIUtil_TranslatePixelFormat(desc->color_formats[i]);
}
// Create pipeline object
HRESULT result = E_FAIL;
wchar_t pipelineName[PSO_NAME_LENGTH] = {};
size_t psoShaderHash = 0;
size_t psoRenderHash = 0;
if (D->pPipelineLibrary)
{
// Calculate graphics pso shader hash
if (VS.BytecodeLength)
psoShaderHash = cgpu_hash(VS.pShaderBytecode, VS.BytecodeLength, psoShaderHash);
if (PS.BytecodeLength)
psoShaderHash = cgpu_hash(PS.pShaderBytecode, PS.BytecodeLength, psoShaderHash);
if (DS.BytecodeLength)
psoShaderHash = cgpu_hash(DS.pShaderBytecode, DS.BytecodeLength, psoShaderHash);
if (HS.BytecodeLength)
psoShaderHash = cgpu_hash(HS.pShaderBytecode, HS.BytecodeLength, psoShaderHash);
if (GS.BytecodeLength)
psoShaderHash = cgpu_hash(GS.pShaderBytecode, GS.BytecodeLength, psoShaderHash);
// Calculate graphics pso desc hash
psoRenderHash = cgpu_hash(&pipeline_state_desc.BlendState, sizeof(D3D12_BLEND_DESC), psoRenderHash);
psoRenderHash = cgpu_hash(&pipeline_state_desc.RasterizerState, sizeof(D3D12_RASTERIZER_DESC), psoRenderHash);
psoRenderHash = cgpu_hash(&pipeline_state_desc.DepthStencilState, sizeof(D3D12_DEPTH_STENCIL_DESC), psoRenderHash);
psoRenderHash = cgpu_hash(&pipeline_state_desc.IBStripCutValue, sizeof(D3D12_INDEX_BUFFER_STRIP_CUT_VALUE), psoRenderHash);
psoRenderHash = cgpu_hash(pipeline_state_desc.RTVFormats,
pipeline_state_desc.NumRenderTargets * sizeof(DXGI_FORMAT), psoRenderHash);
psoRenderHash = cgpu_hash(&pipeline_state_desc.DSVFormat, sizeof(DXGI_FORMAT), psoRenderHash);
psoRenderHash = cgpu_hash(&pipeline_state_desc.SampleDesc, sizeof(DXGI_SAMPLE_DESC), psoRenderHash);
psoRenderHash = cgpu_hash(&pipeline_state_desc.Flags, sizeof(D3D12_PIPELINE_STATE_FLAGS), psoRenderHash);
for (uint32_t i = 0; i < pipeline_state_desc.InputLayout.NumElements; i++)
{
psoRenderHash = cgpu_hash(&pipeline_state_desc.InputLayout.pInputElementDescs[i],
sizeof(D3D12_INPUT_ELEMENT_DESC), psoRenderHash);
}
swprintf(pipelineName, PSO_NAME_LENGTH, L"%S_S%zuR%zu", "GRAPHICSPSO", psoShaderHash, psoRenderHash);
result = D->pPipelineLibrary->LoadGraphicsPipeline(pipelineName,
&pipeline_state_desc, IID_ARGS(&PPL->pDxPipelineState));
}
if (!SUCCEEDED(result))
{
CHECK_HRESULT(D->pDxDevice->CreateGraphicsPipelineState(
&pipeline_state_desc, IID_PPV_ARGS(&PPL->pDxPipelineState)));
// Pipeline cache
if (D->pPipelineLibrary)
{
CHECK_HRESULT(D->pPipelineLibrary->StorePipeline(pipelineName, PPL->pDxPipelineState));
}
}
D3D_PRIMITIVE_TOPOLOGY topology = D3D_PRIMITIVE_TOPOLOGY_UNDEFINED;
switch (desc->prim_topology)
{
case CGPU_PRIM_TOPO_POINT_LIST:
topology = D3D_PRIMITIVE_TOPOLOGY_POINTLIST;
break;
case CGPU_PRIM_TOPO_LINE_LIST:
topology = D3D_PRIMITIVE_TOPOLOGY_LINELIST;
break;
case CGPU_PRIM_TOPO_LINE_STRIP:
topology = D3D_PRIMITIVE_TOPOLOGY_LINESTRIP;
break;
case CGPU_PRIM_TOPO_TRI_LIST:
topology = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
break;
case CGPU_PRIM_TOPO_TRI_STRIP:
topology = D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP;
break;
case CGPU_PRIM_TOPO_PATCH_LIST: {
// TODO: Support D3D_PRIMITIVE_TOPOLOGY_1_CONTROL_POINT_PATCHLIST with Hull Shaders
cgpu_assert(0 && "Unsupported primitive topology!");
}
default:
break;
}
PPL->mDxPrimitiveTopology = topology;
PPL->pRootSignature = RS->pDxRootSignature;
return &PPL->super;
}
void cgpu_free_render_pipeline_d3d12(CGPURenderPipelineId pipeline)
{
CGPURenderPipeline_D3D12* PPL = (CGPURenderPipeline_D3D12*)pipeline;
SAFE_RELEASE(PPL->pDxPipelineState);
cgpu_delete(PPL);
}
D3D12_QUERY_TYPE D3D12Util_ToD3D12QueryType(ECGPUQueryType type)
{
switch (type)
{
case CGPU_QUERY_TYPE_TIMESTAMP:
return D3D12_QUERY_TYPE_TIMESTAMP;
case CGPU_QUERY_TYPE_PIPELINE_STATISTICS:
return D3D12_QUERY_TYPE_PIPELINE_STATISTICS;
case CGPU_QUERY_TYPE_OCCLUSION:
return D3D12_QUERY_TYPE_OCCLUSION;
default:
cgpu_assert(false && "Invalid query heap type");
return D3D12_QUERY_TYPE_OCCLUSION;
}
}
D3D12_QUERY_HEAP_TYPE D3D12Util_ToD3D12QueryHeapType(ECGPUQueryType type)
{
switch (type)
{
case CGPU_QUERY_TYPE_TIMESTAMP:
return D3D12_QUERY_HEAP_TYPE_TIMESTAMP;
case CGPU_QUERY_TYPE_PIPELINE_STATISTICS:
return D3D12_QUERY_HEAP_TYPE_PIPELINE_STATISTICS;
case CGPU_QUERY_TYPE_OCCLUSION:
return D3D12_QUERY_HEAP_TYPE_OCCLUSION;
default:
cgpu_assert(false && "Invalid query heap type");
return D3D12_QUERY_HEAP_TYPE_OCCLUSION;
}
}
CGPUQueryPoolId cgpu_create_query_pool_d3d12(CGPUDeviceId device, const struct CGPUQueryPoolDescriptor* desc)
{
CGPUDevice_D3D12* D = (CGPUDevice_D3D12*)device;
CGPUQueryPool_D3D12* pQueryPool = cgpu_new<CGPUQueryPool_D3D12>();
pQueryPool->mType = D3D12Util_ToD3D12QueryType(desc->type);
pQueryPool->super.count = desc->query_count;
D3D12_QUERY_HEAP_DESC Desc = {};
Desc.Count = desc->query_count;
Desc.NodeMask = SINGLE_GPU_NODE_MASK;
Desc.Type = D3D12Util_ToD3D12QueryHeapType(desc->type);
D->pDxDevice->CreateQueryHeap(&Desc, IID_ARGS(&pQueryPool->pDxQueryHeap));
return &pQueryPool->super;
}
void cgpu_free_query_pool_d3d12(CGPUQueryPoolId pool)
{
CGPUQueryPool_D3D12* QP = (CGPUQueryPool_D3D12*)pool;
SAFE_RELEASE(QP->pDxQueryHeap);
cgpu_delete(QP);
}
// Queue APIs
CGPUQueueId cgpu_get_queue_d3d12(CGPUDeviceId device, ECGPUQueueType type, uint32_t index)
{
CGPUDevice_D3D12* D = (CGPUDevice_D3D12*)device;
CGPUQueue_D3D12* Q = cgpu_new<CGPUQueue_D3D12>();
Q->pCommandQueue = D->ppCommandQueues[type][index];
Q->pFence = (CGPUFence_D3D12*)cgpu_create_fence_d3d12(device);
return &Q->super;
}
void cgpu_submit_queue_d3d12(CGPUQueueId queue, const struct CGPUQueueSubmitDescriptor* desc)
{
uint32_t CmdCount = desc->cmds_count;
CGPUCommandBuffer_D3D12** Cmds = (CGPUCommandBuffer_D3D12**)desc->cmds;
CGPUQueue_D3D12* Q = (CGPUQueue_D3D12*)queue;
CGPUFence_D3D12* F = (CGPUFence_D3D12*)desc->signal_fence;
// cgpu_assert that given cmd list and given params are valid
cgpu_assert(CmdCount > 0);
cgpu_assert(Cmds);
// execute given command list
cgpu_assert(Q->pCommandQueue);
ID3D12CommandList** cmds = (ID3D12CommandList**)alloca(CmdCount * sizeof(ID3D12CommandList*));
for (uint32_t i = 0; i < CmdCount; ++i)
{
cmds[i] = Cmds[i]->pDxCmdList;
}
// Wait semaphores
CGPUFence_D3D12** WaitSemaphores = (CGPUFence_D3D12**)desc->wait_semaphores;
for (uint32_t i = 0; i < desc->wait_semaphore_count; ++i)
Q->pCommandQueue->Wait(WaitSemaphores[i]->pDxFence,
WaitSemaphores[i]->mFenceValue - 1);
// Execute
Q->pCommandQueue->ExecuteCommandLists(CmdCount, cmds);
// Signal fences
if (F)
D3D12Util_SignalFence(Q, F->pDxFence, F->mFenceValue++);
// Signal Semaphores
CGPUFence_D3D12** SignalSemaphores = (CGPUFence_D3D12**)desc->signal_semaphores;
for (uint32_t i = 0; i < desc->signal_semaphore_count; i++)
D3D12Util_SignalFence(Q, SignalSemaphores[i]->pDxFence, SignalSemaphores[i]->mFenceValue++);
}
void cgpu_wait_queue_idle_d3d12(CGPUQueueId queue)
{
CGPUQueue_D3D12* Q = (CGPUQueue_D3D12*)queue;
D3D12Util_SignalFence(Q, Q->pFence->pDxFence, Q->pFence->mFenceValue++);
uint64_t fenceValue = Q->pFence->mFenceValue - 1;
if (Q->pFence->pDxFence->GetCompletedValue() < Q->pFence->mFenceValue - 1)
{
Q->pFence->pDxFence->SetEventOnCompletion(fenceValue, Q->pFence->pDxWaitIdleFenceEvent);
WaitForSingleObject(Q->pFence->pDxWaitIdleFenceEvent, INFINITE);
}
}
void cgpu_queue_present_d3d12(CGPUQueueId queue, const struct CGPUQueuePresentDescriptor* desc)
{
CGPUSwapChain_D3D12* S = (CGPUSwapChain_D3D12*)desc->swapchain;
HRESULT hr = S->pDxSwapChain->Present(S->mDxSyncInterval, S->mFlags /*desc->index*/);
if (FAILED(hr))
{
#if defined(_WIN32)
ID3D12Device* device = NULL;
S->pDxSwapChain->GetDevice(IID_ARGS(&device));
HRESULT removeHr = device->GetDeviceRemovedReason();
if (FAILED(removeHr))
{
Sleep(5000); // Wait for a few seconds to allow the driver to come
// back online before doing a reset.
// onDeviceLost();
}
#ifdef __ID3D12DeviceRemovedExtendedData_FWD_DEFINED__
ID3D12DeviceRemovedExtendedData* pDread;
if (SUCCEEDED(device->QueryInterface(IID_ARGS(&pDread))))
{
D3D12_DRED_AUTO_BREADCRUMBS_OUTPUT breadcrumbs;
if (SUCCEEDED(pDread->GetAutoBreadcrumbsOutput(&breadcrumbs)))
{
cgpu_info("Gathered auto-breadcrumbs output.");
}
D3D12_DRED_PAGE_FAULT_OUTPUT pageFault;
if (SUCCEEDED(pDread->GetPageFaultAllocationOutput(&pageFault)))
{
cgpu_info("Gathered page fault allocation output.");
}
}
pDread->Release();
#endif
device->Release();
#endif
cgpu_error("Failed to present swapchain render target!");
}
}
float cgpu_queue_get_timestamp_period_ns_d3d12(CGPUQueueId queue)
{
CGPUQueue_D3D12* Q = (CGPUQueue_D3D12*)queue;
UINT64 freq = 0;
// ticks per second
Q->pCommandQueue->GetTimestampFrequency(&freq);
// ns per tick
const double ms_period = 1e9 / (double)freq;
return (float)ms_period;
}
void cgpu_free_queue_d3d12(CGPUQueueId queue)
{
CGPUQueue_D3D12* Q = (CGPUQueue_D3D12*)queue;
cgpu_assert(queue && "D3D12 ERROR: FREE NULL QUEUE!");
cgpu_free_fence_d3d12(&Q->pFence->super);
cgpu_delete(Q);
}
// Command Objects
// allocate_transient_command_allocator
ID3D12CommandAllocator* allocate_transient_command_allocator(CGPUCommandPool_D3D12* E, CGPUQueueId queue)
{
CGPUDevice_D3D12* D = (CGPUDevice_D3D12*)queue->device;
D3D12_COMMAND_LIST_TYPE type =
queue->type == CGPU_QUEUE_TYPE_TRANSFER ?
D3D12_COMMAND_LIST_TYPE_COPY :
queue->type == CGPU_QUEUE_TYPE_COMPUTE ?
D3D12_COMMAND_LIST_TYPE_COMPUTE :
D3D12_COMMAND_LIST_TYPE_DIRECT;
bool res = SUCCEEDED(D->pDxDevice->CreateCommandAllocator(type, IID_PPV_ARGS(&E->pDxCmdAlloc)));
if (res)
{
return E->pDxCmdAlloc;
}
return CGPU_NULLPTR;
}
void free_transient_command_allocator(ID3D12CommandAllocator* allocator) { SAFE_RELEASE(allocator); }
CGPUCommandPoolId cgpu_create_command_pool_d3d12(CGPUQueueId queue, const CGPUCommandPoolDescriptor* desc)
{
CGPUCommandPool_D3D12* P = cgpu_new<CGPUCommandPool_D3D12>();
P->pDxCmdAlloc = allocate_transient_command_allocator(P, queue);
return &P->super;
}
void cgpu_reset_command_pool_d3d12(CGPUCommandPoolId pool)
{
CGPUCommandPool_D3D12* P = (CGPUCommandPool_D3D12*)pool;
CHECK_HRESULT(P->pDxCmdAlloc->Reset());
}
CGPUCommandBufferId cgpu_create_command_buffer_d3d12(CGPUCommandPoolId pool, const struct CGPUCommandBufferDescriptor* desc)
{
// initialize to zero
CGPUCommandBuffer_D3D12* Cmd = cgpu_new<CGPUCommandBuffer_D3D12>();
CGPUCommandPool_D3D12* P = (CGPUCommandPool_D3D12*)pool;
CGPUQueue_D3D12* Q = (CGPUQueue_D3D12*)P->super.queue;
CGPUDevice_D3D12* D = (CGPUDevice_D3D12*)Q->super.device;
cgpu_assert(Cmd);
// set command pool of new command
Cmd->mNodeIndex = SINGLE_GPU_NODE_INDEX;
Cmd->mType = Q->super.type;
Cmd->pBoundHeaps[0] = D->pCbvSrvUavHeaps[Cmd->mNodeIndex];
Cmd->pBoundHeaps[1] = D->pSamplerHeaps[Cmd->mNodeIndex];
Cmd->pCmdPool = P;
uint32_t nodeMask = Cmd->mNodeIndex;
ID3D12PipelineState* initialState = NULL;
CHECK_HRESULT(D->pDxDevice->CreateCommandList(
nodeMask, gDx12CmdTypeTranslator[Cmd->mType], P->pDxCmdAlloc, initialState,
__uuidof(Cmd->pDxCmdList), (void**)&(Cmd->pDxCmdList)));
// Command lists are addd in the recording state, but there is nothing
// to record yet. The main loop expects it to be closed, so close it now.
CHECK_HRESULT(Cmd->pDxCmdList->Close());
return &Cmd->super;
}
void cgpu_free_command_buffer_d3d12(CGPUCommandBufferId cmd)
{
CGPUCommandBuffer_D3D12* Cmd = (CGPUCommandBuffer_D3D12*)cmd;
SAFE_RELEASE(Cmd->pDxCmdList);
cgpu_delete(Cmd);
}
void cgpu_free_command_pool_d3d12(CGPUCommandPoolId pool)
{
CGPUCommandPool_D3D12* P = (CGPUCommandPool_D3D12*)pool;
cgpu_assert(pool && "D3D12 ERROR: FREE NULL COMMAND POOL!");
cgpu_assert(P->pDxCmdAlloc && "D3D12 ERROR: FREE NULL pDxCmdAlloc!");
free_transient_command_allocator(P->pDxCmdAlloc);
cgpu_delete(P);
}
// CMDs
void cgpu_cmd_begin_d3d12(CGPUCommandBufferId cmd)
{
CGPUCommandBuffer_D3D12* Cmd = (CGPUCommandBuffer_D3D12*)cmd;
CGPUCommandPool_D3D12* P = (CGPUCommandPool_D3D12*)Cmd->pCmdPool;
CHECK_HRESULT(Cmd->pDxCmdList->Reset(P->pDxCmdAlloc, NULL));
if (Cmd->mType != CGPU_QUEUE_TYPE_TRANSFER)
{
ID3D12DescriptorHeap* heaps[] = {
Cmd->pBoundHeaps[0]->pCurrentHeap,
Cmd->pBoundHeaps[1]->pCurrentHeap,
};
Cmd->pDxCmdList->SetDescriptorHeaps(2, heaps);
Cmd->mBoundHeapStartHandles[0] = Cmd->pBoundHeaps[0]->pCurrentHeap->GetGPUDescriptorHandleForHeapStart();
Cmd->mBoundHeapStartHandles[1] = Cmd->pBoundHeaps[1]->pCurrentHeap->GetGPUDescriptorHandleForHeapStart();
}
// Reset CPU side data
Cmd->pBoundRootSignature = NULL;
}
// TODO: https://microsoft.github.io/DirectX-Specs/d3d/D3D12EnhancedBarriers.html#introduction
// Enhanced Barriers is not currently a hardware or driver requirement
void cgpu_cmd_resource_barrier_d3d12(CGPUCommandBufferId cmd, const struct CGPUResourceBarrierDescriptor* desc)
{
CGPUCommandBuffer_D3D12* Cmd = (CGPUCommandBuffer_D3D12*)cmd;
const uint32_t barriers_count = desc->buffer_barriers_count + desc->texture_barriers_count;
D3D12_RESOURCE_BARRIER* barriers = (D3D12_RESOURCE_BARRIER*)alloca(barriers_count * sizeof(D3D12_RESOURCE_BARRIER));
uint32_t transitionCount = 0;
for (uint32_t i = 0; i < desc->buffer_barriers_count; ++i)
{
const CGPUBufferBarrier* pTransBarrier = &desc->buffer_barriers[i];
D3D12_RESOURCE_BARRIER* pBarrier = &barriers[transitionCount];
CGPUBuffer_D3D12* pBuffer = (CGPUBuffer_D3D12*)pTransBarrier->buffer;
if (pBuffer->super.memory_usage == CGPU_MEM_USAGE_GPU_ONLY ||
pBuffer->super.memory_usage == CGPU_MEM_USAGE_GPU_TO_CPU ||
(pBuffer->super.memory_usage == CGPU_MEM_USAGE_CPU_TO_GPU && (pBuffer->super.descriptors & CGPU_RESOURCE_TYPE_RW_BUFFER)))
{
if (CGPU_RESOURCE_STATE_UNORDERED_ACCESS == pTransBarrier->src_state &&
CGPU_RESOURCE_STATE_UNORDERED_ACCESS == pTransBarrier->dst_state)
{
pBarrier->Type = D3D12_RESOURCE_BARRIER_TYPE_UAV;
pBarrier->Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
pBarrier->UAV.pResource = pBuffer->pDxResource;
++transitionCount;
}
else
{
pBarrier->Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
if (pTransBarrier->d3d12.begin_ony)
{
pBarrier->Flags = D3D12_RESOURCE_BARRIER_FLAG_BEGIN_ONLY;
}
else if (pTransBarrier->d3d12.end_only)
{
pBarrier->Flags = D3D12_RESOURCE_BARRIER_FLAG_END_ONLY;
}
pBarrier->Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
pBarrier->Transition.pResource = pBuffer->pDxResource;
pBarrier->Transition.Subresource =
D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
if (pTransBarrier->queue_acquire)
pBarrier->Transition.StateBefore = D3D12_RESOURCE_STATE_COMMON;
else
pBarrier->Transition.StateBefore = D3D12Util_TranslateResourceState(pTransBarrier->src_state);
if (pTransBarrier->queue_release)
pBarrier->Transition.StateAfter = D3D12_RESOURCE_STATE_COMMON;
else
pBarrier->Transition.StateAfter = D3D12Util_TranslateResourceState(pTransBarrier->dst_state);
++transitionCount;
}
}
}
for (uint32_t i = 0; i < desc->texture_barriers_count; ++i)
{
const CGPUTextureBarrier* pTransBarrier = &desc->texture_barriers[i];
D3D12_RESOURCE_BARRIER* pBarrier = &barriers[transitionCount];
CGPUTexture_D3D12* pTexture = (CGPUTexture_D3D12*)pTransBarrier->texture;
if (CGPU_RESOURCE_STATE_UNORDERED_ACCESS == pTransBarrier->src_state &&
CGPU_RESOURCE_STATE_UNORDERED_ACCESS == pTransBarrier->dst_state)
{
pBarrier->Type = D3D12_RESOURCE_BARRIER_TYPE_UAV;
pBarrier->Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
pBarrier->UAV.pResource = pTexture->pDxResource;
++transitionCount;
}
else
{
pBarrier->Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
pBarrier->Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
if (pTransBarrier->d3d12.begin_ony)
{
pBarrier->Flags = D3D12_RESOURCE_BARRIER_FLAG_BEGIN_ONLY;
}
else if (pTransBarrier->d3d12.end_only)
{
pBarrier->Flags = D3D12_RESOURCE_BARRIER_FLAG_END_ONLY;
}
pBarrier->Transition.pResource = pTexture->pDxResource;
pBarrier->Transition.Subresource =
pTransBarrier->subresource_barrier ? CALC_SUBRESOURCE_INDEX(
pTransBarrier->mip_level, pTransBarrier->array_layer,
0, pTexture->super.mip_levels,
pTexture->super.array_size_minus_one + 1) :
D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
if (pTransBarrier->queue_acquire)
pBarrier->Transition.StateBefore = D3D12_RESOURCE_STATE_COMMON;
else
pBarrier->Transition.StateBefore = D3D12Util_TranslateResourceState(pTransBarrier->src_state);
if (pTransBarrier->queue_release)
pBarrier->Transition.StateAfter = D3D12_RESOURCE_STATE_COMMON;
else
pBarrier->Transition.StateAfter = D3D12Util_TranslateResourceState(pTransBarrier->dst_state);
++transitionCount;
}
}
if (transitionCount)
Cmd->pDxCmdList->ResourceBarrier(transitionCount, barriers);
}
void cgpu_cmd_begin_query_d3d12(CGPUCommandBufferId cmd, CGPUQueryPoolId pool, const struct CGPUQueryDescriptor* desc)
{
auto Cmd = (CGPUCommandBuffer_D3D12*)cmd;
auto pQueryPool = (CGPUQueryPool_D3D12*)pool;
D3D12_QUERY_TYPE type = pQueryPool->mType;
switch (type)
{
case D3D12_QUERY_TYPE_OCCLUSION:
case D3D12_QUERY_TYPE_PIPELINE_STATISTICS:
case D3D12_QUERY_TYPE_BINARY_OCCLUSION:
case D3D12_QUERY_TYPE_SO_STATISTICS_STREAM0:
case D3D12_QUERY_TYPE_SO_STATISTICS_STREAM1:
case D3D12_QUERY_TYPE_SO_STATISTICS_STREAM2:
case D3D12_QUERY_TYPE_SO_STATISTICS_STREAM3:
break;
case D3D12_QUERY_TYPE_TIMESTAMP:
Cmd->pDxCmdList->EndQuery(pQueryPool->pDxQueryHeap, type, desc->index);
break;
}
}
void cgpu_cmd_end_query_d3d12(CGPUCommandBufferId cmd, CGPUQueryPoolId pool, const struct CGPUQueryDescriptor* desc)
{
cgpu_cmd_begin_query(cmd, pool, desc);
}
void cgpu_cmd_reset_query_pool_d3d12(CGPUCommandBufferId, CGPUQueryPoolId, uint32_t, uint32_t) {}
void cgpu_cmd_resolve_query_d3d12(CGPUCommandBufferId cmd, CGPUQueryPoolId pool, CGPUBufferId readback, uint32_t start_query, uint32_t query_count)
{
auto Cmd = (CGPUCommandBuffer_D3D12*)cmd;
auto pQueryPool = (CGPUQueryPool_D3D12*)pool;
auto pReadbackBuffer = (CGPUBuffer_D3D12*)readback;
Cmd->pDxCmdList->ResolveQueryData(
pQueryPool->pDxQueryHeap, pQueryPool->mType, start_query, query_count,
pReadbackBuffer->pDxResource, start_query * 8);
}
void cgpu_cmd_end_d3d12(CGPUCommandBufferId cmd)
{
CGPUCommandBuffer_D3D12* Cmd = (CGPUCommandBuffer_D3D12*)cmd;
cgpu_assert(Cmd->pDxCmdList);
CHECK_HRESULT(Cmd->pDxCmdList->Close());
}
// Compute CMDs
CGPUComputePassEncoderId cgpu_cmd_begin_compute_pass_d3d12(CGPUCommandBufferId cmd, const struct CGPUComputePassDescriptor* desc)
{
// DO NOTHING NOW
return (CGPUComputePassEncoderId)cmd;
}
void cgpu_compute_encoder_bind_descriptor_set_d3d12(CGPUComputePassEncoderId encoder, CGPUDescriptorSetId set)
{
CGPUCommandBuffer_D3D12* Cmd = (CGPUCommandBuffer_D3D12*)encoder;
const CGPUDescriptorSet_D3D12* Set = (CGPUDescriptorSet_D3D12*)set;
Cmd->pDxCmdList->SetComputeRootDescriptorTable(set->index, { Cmd->mBoundHeapStartHandles[0].ptr + Set->mCbvSrvUavHandle });
}
bool reset_root_signature(CGPUCommandBuffer_D3D12* pCmd, ECGPUPipelineType type,
ID3D12RootSignature* pRootSignature)
{
// Set root signature if the current one differs from pRootSignature
if (pCmd->pBoundRootSignature != pRootSignature)
{
pCmd->pBoundRootSignature = pRootSignature;
if (type == CGPU_PIPELINE_TYPE_GRAPHICS)
pCmd->pDxCmdList->SetGraphicsRootSignature(pRootSignature);
else
pCmd->pDxCmdList->SetComputeRootSignature(pRootSignature);
}
return true;
}
void cgpu_compute_encoder_bind_pipeline_d3d12(CGPUComputePassEncoderId encoder, CGPUComputePipelineId pipeline)
{
CGPUCommandBuffer_D3D12* Cmd = (CGPUCommandBuffer_D3D12*)encoder;
CGPUComputePipeline_D3D12* PPL = (CGPUComputePipeline_D3D12*)pipeline;
reset_root_signature(Cmd, CGPU_PIPELINE_TYPE_COMPUTE, PPL->pRootSignature);
Cmd->pDxCmdList->SetPipelineState(PPL->pDxPipelineState);
}
void cgpu_compute_encoder_push_constants_d3d12(CGPUComputePassEncoderId encoder, CGPURootSignatureId rs, const char8_t* name, const void* data)
{
CGPUCommandBuffer_D3D12* Cmd = (CGPUCommandBuffer_D3D12*)encoder;
CGPURootSignature_D3D12* RS = (CGPURootSignature_D3D12*)rs;
reset_root_signature(Cmd, CGPU_PIPELINE_TYPE_GRAPHICS, RS->pDxRootSignature);
if (RS->super.pipeline_type == CGPU_PIPELINE_TYPE_GRAPHICS)
{
Cmd->pDxCmdList->SetGraphicsRoot32BitConstants(RS->mRootParamIndex,
RS->mRootConstantParam.Constants.Num32BitValues,
data, 0);
}
else if (RS->super.pipeline_type == CGPU_PIPELINE_TYPE_COMPUTE)
{
Cmd->pDxCmdList->SetComputeRoot32BitConstants(RS->mRootParamIndex,
RS->mRootConstantParam.Constants.Num32BitValues,
data, 0);
}
}
void cgpu_render_encoder_bind_vertex_buffers_d3d12(CGPURenderPassEncoderId encoder, uint32_t buffer_count,
const CGPUBufferId* buffers, const uint32_t* strides, const uint32_t* offsets)
{
CGPUCommandBuffer_D3D12* Cmd = (CGPUCommandBuffer_D3D12*)encoder;
const CGPUBuffer_D3D12** Buffers = (const CGPUBuffer_D3D12**)buffers;
DECLARE_ZERO(D3D12_VERTEX_BUFFER_VIEW, views[CGPU_MAX_VERTEX_ATTRIBS]);
for (uint32_t i = 0; i < buffer_count; ++i)
{
cgpu_assert(D3D12_GPU_VIRTUAL_ADDRESS_NULL != Buffers[i]->mDxGpuAddress);
views[i].BufferLocation =
(Buffers[i]->mDxGpuAddress + (offsets ? offsets[i] : 0));
views[i].SizeInBytes =
(UINT)(Buffers[i]->super.size - (offsets ? offsets[i] : 0));
views[i].StrideInBytes = (UINT)strides[i];
}
Cmd->pDxCmdList->IASetVertexBuffers(0, buffer_count, views);
}
void cgpu_render_encoder_bind_index_buffer_d3d12(CGPURenderPassEncoderId encoder, CGPUBufferId buffer,
uint32_t index_stride, uint64_t offset)
{
CGPUCommandBuffer_D3D12* Cmd = (CGPUCommandBuffer_D3D12*)encoder;
const CGPUBuffer_D3D12* Buffer = (const CGPUBuffer_D3D12*)buffer;
cgpu_assert(Cmd);
cgpu_assert(buffer);
cgpu_assert(CGPU_NULLPTR != Cmd->pDxCmdList);
cgpu_assert(CGPU_NULLPTR != Buffer->pDxResource);
DECLARE_ZERO(D3D12_INDEX_BUFFER_VIEW, view);
view.BufferLocation = Buffer->mDxGpuAddress + offset;
view.Format =
(sizeof(uint16_t) == index_stride) ?
DXGI_FORMAT_R16_UINT :
((sizeof(uint8_t) == index_stride) ? DXGI_FORMAT_R8_UINT : DXGI_FORMAT_R32_UINT);
view.SizeInBytes = (UINT)(Buffer->super.size - offset);
Cmd->pDxCmdList->IASetIndexBuffer(&view);
}
void cgpu_compute_encoder_dispatch_d3d12(CGPUComputePassEncoderId encoder, uint32_t X, uint32_t Y, uint32_t Z)
{
CGPUCommandBuffer_D3D12* Cmd = (CGPUCommandBuffer_D3D12*)encoder;
Cmd->pDxCmdList->Dispatch(X, Y, Z);
}
void cgpu_cmd_end_compute_pass_d3d12(CGPUCommandBufferId cmd, CGPUComputePassEncoderId encoder)
{
// DO NOTHING NOW
}
// Render CMDs
CGPURenderPassEncoderId cgpu_cmd_begin_render_pass_d3d12(CGPUCommandBufferId cmd, const struct CGPURenderPassDescriptor* desc)
{
CGPUCommandBuffer_D3D12* Cmd = (CGPUCommandBuffer_D3D12*)cmd;
#ifdef __ID3D12GraphicsCommandList4_FWD_DEFINED__
ID3D12GraphicsCommandList4* CmdList4 = (ID3D12GraphicsCommandList4*)Cmd->pDxCmdList;
DECLARE_ZERO(D3D12_CLEAR_VALUE, clearValues[CGPU_MAX_MRT_COUNT]);
DECLARE_ZERO(D3D12_CLEAR_VALUE, clearDepth);
DECLARE_ZERO(D3D12_CLEAR_VALUE, clearStencil);
DECLARE_ZERO(D3D12_RENDER_PASS_RENDER_TARGET_DESC, renderPassRenderTargetDescs[CGPU_MAX_MRT_COUNT]);
DECLARE_ZERO(D3D12_RENDER_PASS_DEPTH_STENCIL_DESC, renderPassDepthStencilDesc);
uint32_t colorTargetCount = 0;
// color
for (uint32_t i = 0; i < desc->render_target_count; i++)
{
CGPUTextureView_D3D12* TV = (CGPUTextureView_D3D12*)desc->color_attachments[i].view;
clearValues[i].Format = DXGIUtil_TranslatePixelFormat(TV->super.info.format);
clearValues[i].Color[0] = desc->color_attachments[i].clear_color.r;
clearValues[i].Color[1] = desc->color_attachments[i].clear_color.g;
clearValues[i].Color[2] = desc->color_attachments[i].clear_color.b;
clearValues[i].Color[3] = desc->color_attachments[i].clear_color.a;
D3D12_RENDER_PASS_BEGINNING_ACCESS_TYPE beginningAccess = gDx12PassBeginOpTranslator[desc->color_attachments[i].load_action];
CGPUTextureView_D3D12* TV_Resolve = (CGPUTextureView_D3D12*)desc->color_attachments[i].resolve_view;
if (desc->sample_count != CGPU_SAMPLE_COUNT_1 && TV_Resolve)
{
CGPUTexture_D3D12* T = (CGPUTexture_D3D12*)TV->super.info.texture;
CGPUTexture_D3D12* T_Resolve = (CGPUTexture_D3D12*)TV_Resolve->super.info.texture;
D3D12_RENDER_PASS_ENDING_ACCESS_TYPE endingAccess = D3D12_RENDER_PASS_ENDING_ACCESS_TYPE_RESOLVE;
renderPassRenderTargetDescs[colorTargetCount].cpuDescriptor = TV->mDxRtvDsvDescriptorHandle;
renderPassRenderTargetDescs[colorTargetCount].BeginningAccess = { beginningAccess, { clearValues[i] } };
renderPassRenderTargetDescs[colorTargetCount].EndingAccess = { endingAccess, {} };
auto& Resolve = renderPassRenderTargetDescs[colorTargetCount].EndingAccess.Resolve;
Resolve.ResolveMode = D3D12_RESOLVE_MODE_AVERAGE; // TODO: int->MODE_MAX
Resolve.Format = clearValues[i].Format;
Resolve.pSrcResource = T->pDxResource;
Resolve.pDstResource = T_Resolve->pDxResource;
Cmd->mSubResolveResource.SrcRect = { 0, 0, 0, 0 };
Cmd->mSubResolveResource.DstX = 0;
Cmd->mSubResolveResource.DstY = 0;
Cmd->mSubResolveResource.SrcSubresource = 0;
Cmd->mSubResolveResource.DstSubresource = CALC_SUBRESOURCE_INDEX(
0, 0, 0,
T->super.mip_levels, T->super.array_size_minus_one + 1);
Resolve.PreserveResolveSource = false;
Resolve.SubresourceCount = 1;
Resolve.pSubresourceParameters = &Cmd->mSubResolveResource;
}
else
{
// Load & Store action
D3D12_RENDER_PASS_ENDING_ACCESS_TYPE endingAccess = gDx12PassEndOpTranslator[desc->color_attachments[i].store_action];
renderPassRenderTargetDescs[colorTargetCount].cpuDescriptor = TV->mDxRtvDsvDescriptorHandle;
renderPassRenderTargetDescs[colorTargetCount].BeginningAccess = { beginningAccess, { clearValues[i] } };
renderPassRenderTargetDescs[colorTargetCount].EndingAccess = { endingAccess, {} };
}
colorTargetCount++;
}
// depth stencil
D3D12_RENDER_PASS_DEPTH_STENCIL_DESC* pRenderPassDepthStencilDesc = nullptr;
if (desc->depth_stencil != nullptr && desc->depth_stencil->view != nullptr)
{
CGPUTextureView_D3D12* DTV = (CGPUTextureView_D3D12*)desc->depth_stencil->view;
D3D12_RENDER_PASS_BEGINNING_ACCESS_TYPE dBeginingAccess =
gDx12PassBeginOpTranslator[desc->depth_stencil->depth_load_action];
D3D12_RENDER_PASS_BEGINNING_ACCESS_TYPE sBeginingAccess =
gDx12PassBeginOpTranslator[desc->depth_stencil->stencil_load_action];
D3D12_RENDER_PASS_ENDING_ACCESS_TYPE dEndingAccess =
gDx12PassEndOpTranslator[desc->depth_stencil->depth_store_action];
D3D12_RENDER_PASS_ENDING_ACCESS_TYPE sEndingAccess =
gDx12PassEndOpTranslator[desc->depth_stencil->stencil_store_action];
clearDepth.Format = DXGIUtil_TranslatePixelFormat(desc->depth_stencil->view->info.format);
clearDepth.DepthStencil.Depth = desc->depth_stencil->clear_depth;
clearStencil.Format = DXGIUtil_TranslatePixelFormat(desc->depth_stencil->view->info.format);
clearStencil.DepthStencil.Stencil = desc->depth_stencil->clear_stencil;
renderPassDepthStencilDesc.cpuDescriptor = DTV->mDxRtvDsvDescriptorHandle;
renderPassDepthStencilDesc.DepthBeginningAccess = { dBeginingAccess, { clearDepth } };
renderPassDepthStencilDesc.DepthEndingAccess = { dEndingAccess };
renderPassDepthStencilDesc.StencilBeginningAccess = { sBeginingAccess, { clearStencil } };
renderPassDepthStencilDesc.StencilEndingAccess = { sEndingAccess };
pRenderPassDepthStencilDesc = &renderPassDepthStencilDesc;
}
D3D12_RENDER_PASS_RENDER_TARGET_DESC* pRenderPassRenderTargetDesc = renderPassRenderTargetDescs;
CmdList4->BeginRenderPass(colorTargetCount,
pRenderPassRenderTargetDesc, pRenderPassDepthStencilDesc,
D3D12_RENDER_PASS_FLAG_NONE);
return (CGPURenderPassEncoderId)&Cmd->super;
#endif
cgpu_info("ID3D12GraphicsCommandList4 is not defined!");
return (CGPURenderPassEncoderId)&Cmd->super;
}
void cgpu_render_encoder_bind_descriptor_set_d3d12(CGPURenderPassEncoderId encoder, CGPUDescriptorSetId set)
{
CGPUCommandBuffer_D3D12* Cmd = (CGPUCommandBuffer_D3D12*)encoder;
const CGPUDescriptorSet_D3D12* Set = (CGPUDescriptorSet_D3D12*)set;
if (Set->mCbvSrvUavHandle != D3D12_GPU_VIRTUAL_ADDRESS_UNKNOWN)
{
Cmd->pDxCmdList->SetGraphicsRootDescriptorTable(set->index,
{ Cmd->mBoundHeapStartHandles[0].ptr + Set->mCbvSrvUavHandle });
}
else if (Set->mSamplerHandle != D3D12_GPU_VIRTUAL_ADDRESS_UNKNOWN)
{
Cmd->pDxCmdList->SetGraphicsRootDescriptorTable(set->index,
{ Cmd->mBoundHeapStartHandles[1].ptr + Set->mSamplerHandle });
}
}
void cgpu_render_encoder_set_viewport_d3d12(CGPURenderPassEncoderId encoder, float x, float y, float width, float height, float min_depth, float max_depth)
{
CGPUCommandBuffer_D3D12* Cmd = (CGPUCommandBuffer_D3D12*)encoder;
D3D12_VIEWPORT viewport;
viewport.TopLeftX = x;
viewport.TopLeftY = y;
viewport.Width = width;
viewport.Height = height;
viewport.MinDepth = min_depth;
viewport.MaxDepth = max_depth;
Cmd->pDxCmdList->RSSetViewports(1, &viewport);
}
void cgpu_render_encoder_set_scissor_d3d12(CGPURenderPassEncoderId encoder, uint32_t x, uint32_t y, uint32_t width, uint32_t height)
{
CGPUCommandBuffer_D3D12* Cmd = (CGPUCommandBuffer_D3D12*)encoder;
D3D12_RECT scissor;
scissor.left = x;
scissor.top = y;
scissor.right = x + width;
scissor.bottom = y + height;
Cmd->pDxCmdList->RSSetScissorRects(1, &scissor);
}
void cgpu_render_encoder_bind_pipeline_d3d12(CGPURenderPassEncoderId encoder, CGPURenderPipelineId pipeline)
{
CGPUCommandBuffer_D3D12* Cmd = (CGPUCommandBuffer_D3D12*)encoder;
CGPURenderPipeline_D3D12* PPL = (CGPURenderPipeline_D3D12*)pipeline;
reset_root_signature(Cmd, CGPU_PIPELINE_TYPE_GRAPHICS, PPL->pRootSignature);
Cmd->pDxCmdList->IASetPrimitiveTopology(PPL->mDxPrimitiveTopology);
Cmd->pDxCmdList->SetPipelineState(PPL->pDxPipelineState);
}
void cgpu_render_encoder_push_constants_d3d12(CGPURenderPassEncoderId encoder, CGPURootSignatureId rs, const char8_t* name, const void* data)
{
CGPUCommandBuffer_D3D12* Cmd = (CGPUCommandBuffer_D3D12*)encoder;
CGPURootSignature_D3D12* RS = (CGPURootSignature_D3D12*)rs;
reset_root_signature(Cmd, CGPU_PIPELINE_TYPE_GRAPHICS, RS->pDxRootSignature);
if (RS->super.pipeline_type == CGPU_PIPELINE_TYPE_GRAPHICS)
{
Cmd->pDxCmdList->SetGraphicsRoot32BitConstants(RS->mRootParamIndex,
RS->mRootConstantParam.Constants.Num32BitValues,
data, 0);
}
else if (RS->super.pipeline_type == CGPU_PIPELINE_TYPE_COMPUTE)
{
Cmd->pDxCmdList->SetComputeRoot32BitConstants(RS->mRootParamIndex,
RS->mRootConstantParam.Constants.Num32BitValues,
data, 0);
}
}
void cgpu_render_encoder_draw_d3d12(CGPURenderPassEncoderId encoder, uint32_t vertex_count, uint32_t first_vertex)
{
CGPUCommandBuffer_D3D12* Cmd = (CGPUCommandBuffer_D3D12*)encoder;
Cmd->pDxCmdList->DrawInstanced((UINT)vertex_count, (UINT)1, (UINT)first_vertex, (UINT)0);
}
void cgpu_render_encoder_draw_instanced_d3d12(CGPURenderPassEncoderId encoder, uint32_t vertex_count, uint32_t first_vertex, uint32_t instance_count, uint32_t first_instance)
{
CGPUCommandBuffer_D3D12* Cmd = (CGPUCommandBuffer_D3D12*)encoder;
Cmd->pDxCmdList->DrawInstanced((UINT)vertex_count, (UINT)instance_count, (UINT)first_vertex, (UINT)first_instance);
}
void cgpu_render_encoder_draw_indexed_d3d12(CGPURenderPassEncoderId encoder, uint32_t index_count, uint32_t first_index, uint32_t first_vertex)
{
CGPUCommandBuffer_D3D12* Cmd = (CGPUCommandBuffer_D3D12*)encoder;
Cmd->pDxCmdList->DrawIndexedInstanced((UINT)index_count, (UINT)1, (UINT)first_index, (UINT)first_vertex, (UINT)0);
}
void cgpu_render_encoder_draw_indexed_instanced_d3d12(CGPURenderPassEncoderId encoder, uint32_t index_count, uint32_t first_index, uint32_t instance_count, uint32_t first_instance, uint32_t first_vertex)
{
CGPUCommandBuffer_D3D12* Cmd = (CGPUCommandBuffer_D3D12*)encoder;
Cmd->pDxCmdList->DrawIndexedInstanced((UINT)index_count, (UINT)instance_count, (UINT)first_index, (UINT)first_vertex, (UINT)first_instance);
}
void cgpu_cmd_end_render_pass_d3d12(CGPUCommandBufferId cmd, CGPURenderPassEncoderId encoder)
{
CGPUCommandBuffer_D3D12* Cmd = (CGPUCommandBuffer_D3D12*)cmd;
#ifdef __ID3D12GraphicsCommandList4_FWD_DEFINED__
ID3D12GraphicsCommandList4* CmdList4 = (ID3D12GraphicsCommandList4*)Cmd->pDxCmdList;
CmdList4->EndRenderPass();
return;
#endif
cgpu_info("ID3D12GraphicsCommandList4 is not defined!");
}
// SwapChain APIs
CGPUSwapChainId cgpu_create_swapchain_d3d12(CGPUDeviceId device, const CGPUSwapChainDescriptor* desc)
{
CGPUInstance_D3D12* I = (CGPUInstance_D3D12*)device->adapter->instance;
CGPUDevice_D3D12* D = (CGPUDevice_D3D12*)device;
const uint32_t buffer_count = desc->imageCount;
void* Memory = cgpu_calloc(1, sizeof(CGPUSwapChain_D3D12) +
sizeof(CGPUTexture_D3D12) * buffer_count +
sizeof(CGPUTextureId) * buffer_count);
CGPUSwapChain_D3D12* S = cgpu_new_placed<CGPUSwapChain_D3D12>(Memory);
S->mDxSyncInterval = desc->enableVsync ? 1 : 0;
DECLARE_ZERO(DXGI_SWAP_CHAIN_DESC1, chain_desc1)
chain_desc1.Width = desc->width;
chain_desc1.Height = desc->height;
chain_desc1.Format = DXGIUtil_TranslatePixelFormat(desc->format);
chain_desc1.Stereo = false;
chain_desc1.SampleDesc.Count = 1; // If multisampling is needed, we'll resolve it later
chain_desc1.SampleDesc.Quality = 0;
chain_desc1.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
chain_desc1.BufferCount = desc->imageCount;
chain_desc1.Scaling = DXGI_SCALING_STRETCH;
chain_desc1.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD; // for better performance.
chain_desc1.AlphaMode = DXGI_ALPHA_MODE_UNSPECIFIED;
chain_desc1.Flags = 0;
BOOL allowTearing = FALSE;
I->pDXGIFactory->CheckFeatureSupport(DXGI_FEATURE_PRESENT_ALLOW_TEARING, &allowTearing, sizeof(allowTearing));
chain_desc1.Flags |= allowTearing ? DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING : 0;
S->mFlags |= (!desc->enableVsync && allowTearing) ? DXGI_PRESENT_ALLOW_TEARING : 0;
IDXGISwapChain1* swapchain;
HWND hwnd = (HWND)desc->surface;
CGPUQueue_D3D12* Q = CGPU_NULLPTR;
if (desc->presentQueues == CGPU_NULLPTR)
{
Q = (CGPUQueue_D3D12*)cgpu_get_queue_d3d12(device, CGPU_QUEUE_TYPE_GRAPHICS, 0);
}
else
{
Q = (CGPUQueue_D3D12*)desc->presentQueues[0];
}
auto bCreated =
SUCCEEDED(I->pDXGIFactory->CreateSwapChainForHwnd(Q->pCommandQueue, hwnd, &chain_desc1, NULL, NULL, &swapchain));
(void)bCreated;
cgpu_assert(bCreated && "Failed to Try to Create SwapChain!");
auto bAssociation = SUCCEEDED(I->pDXGIFactory->MakeWindowAssociation(hwnd, DXGI_MWA_NO_ALT_ENTER));
(void)bAssociation;
cgpu_assert(bAssociation && "Failed to Try to Associate SwapChain With Window!");
auto bQueryChain3 = SUCCEEDED(swapchain->QueryInterface(IID_PPV_ARGS(&S->pDxSwapChain)));
(void)bQueryChain3;
cgpu_assert(bQueryChain3 && "Failed to Query IDXGISwapChain3 from Created SwapChain!");
SAFE_RELEASE(swapchain);
// Get swapchain images
ID3D12Resource** backbuffers =
(ID3D12Resource**)alloca(desc->imageCount * sizeof(ID3D12Resource*));
for (uint32_t i = 0; i < desc->imageCount; ++i)
{
CHECK_HRESULT(S->pDxSwapChain->GetBuffer(i, IID_ARGS(&backbuffers[i])));
}
CGPUTexture_D3D12* Ts = (CGPUTexture_D3D12*)(S + 1);
for (uint32_t i = 0; i < buffer_count; i++)
{
Ts[i].pDxResource = backbuffers[i];
Ts[i].pDxAllocation = nullptr;
Ts[i].super.is_cube = false;
Ts[i].super.array_size_minus_one = 0;
Ts[i].super.device = &D->super;
Ts[i].super.format = desc->format;
Ts[i].super.aspect_mask = 1;
Ts[i].super.depth = 1;
Ts[i].super.width = desc->width;
Ts[i].super.height = desc->height;
Ts[i].super.mip_levels = 1;
Ts[i].super.node_index = SINGLE_GPU_NODE_INDEX;
Ts[i].super.owns_image = false;
}
CGPUTextureId* Vs = (CGPUTextureId*)(Ts + buffer_count);
for (uint32_t i = 0; i < buffer_count; i++)
{
Vs[i] = &Ts[i].super;
}
S->super.back_buffers = Vs;
S->super.buffer_count = buffer_count;
return &S->super;
}
uint32_t cgpu_acquire_next_image_d3d12(CGPUSwapChainId swapchain, const struct CGPUAcquireNextDescriptor* desc)
{
CGPUSwapChain_D3D12* S = (CGPUSwapChain_D3D12*)swapchain;
// On PC AquireNext is always true
HRESULT hr = S_OK;
if (FAILED(hr))
{
cgpu_error("Failed to acquire next image");
return UINT32_MAX;
}
return S->pDxSwapChain->GetCurrentBackBufferIndex();
}
void cgpu_free_swapchain_d3d12(CGPUSwapChainId swapchain)
{
CGPUSwapChain_D3D12* S = (CGPUSwapChain_D3D12*)swapchain;
for (uint32_t i = 0; i < S->super.buffer_count; i++)
{
CGPUTexture_D3D12* Texture = (CGPUTexture_D3D12*)S->super.back_buffers[i];
SAFE_RELEASE(Texture->pDxResource);
}
SAFE_RELEASE(S->pDxSwapChain);
cgpu_delete_placed(S);
cgpu_free(S);
}
#include "cgpu/extensions/cgpu_d3d12_exts.h"
// extentions
CGPUDREDSettingsId cgpu_d3d12_enable_DRED()
{
CGPUDREDSettingsId settings = cgpu_new<CGPUDREDSettings>();
SUCCEEDED(D3D12GetDebugInterface(__uuidof(settings->pDredSettings), (void**)&(settings->pDredSettings)));
// Turn on auto-breadcrumbs and page fault reporting.
settings->pDredSettings->SetAutoBreadcrumbsEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON);
settings->pDredSettings->SetPageFaultEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON);
return settings;
}
void cgpu_d3d12_disable_DRED(CGPUDREDSettingsId settings)
{
settings->pDredSettings->SetAutoBreadcrumbsEnablement(D3D12_DRED_ENABLEMENT_FORCED_OFF);
settings->pDredSettings->SetPageFaultEnablement(D3D12_DRED_ENABLEMENT_FORCED_OFF);
SAFE_RELEASE(settings->pDredSettings);
cgpu_delete(settings);
}
| 43.755914
| 203
| 0.691532
|
SakuraEngine
|
1093df5a6b141d24e5ad3ad314010410788a5e04
| 395
|
hpp
|
C++
|
tools/csv_command_line/command_line.hpp
|
dagronf/csvlib
|
790f48b7bc9d361508ea4b3fc3e9a2c962da0a47
|
[
"MIT"
] | 1
|
2020-01-20T16:07:12.000Z
|
2020-01-20T16:07:12.000Z
|
tools/csv_command_line/command_line.hpp
|
dagronf/csvlib
|
790f48b7bc9d361508ea4b3fc3e9a2c962da0a47
|
[
"MIT"
] | null | null | null |
tools/csv_command_line/command_line.hpp
|
dagronf/csvlib
|
790f48b7bc9d361508ea4b3fc3e9a2c962da0a47
|
[
"MIT"
] | null | null | null |
//
// command_line.hpp
// csv_command_line
//
// Created by Darren Ford on 22/5/19.
// Copyright © 2019 Darren Ford. All rights reserved.
//
#pragma once
#include <string>
struct Arguments {
std::string type;
char separator;
bool verbose;
std::string inputFile;
std::string codepage;
size_t limit;
};
bool handle_command_args(int argc, const char * const * argv, Arguments& args);
| 17.173913
| 79
| 0.706329
|
dagronf
|
10956509edab8deef381ffa8a94e0a665183d631
| 1,452
|
hpp
|
C++
|
include/Entity.hpp
|
YuanSambo/Aircraft-Shooter
|
959114a34a25056fbffcfceb785b97a6834a9d97
|
[
"MIT"
] | null | null | null |
include/Entity.hpp
|
YuanSambo/Aircraft-Shooter
|
959114a34a25056fbffcfceb785b97a6834a9d97
|
[
"MIT"
] | null | null | null |
include/Entity.hpp
|
YuanSambo/Aircraft-Shooter
|
959114a34a25056fbffcfceb785b97a6834a9d97
|
[
"MIT"
] | null | null | null |
///////////////////////////////////////////////////////////////
// Entity.hpp
// Aircraft-Shooter
//
// Created by Yuan Sambo on 28/12/2020
// Based on SFML Game Development Book
////////////////////////////////////////////////////////////////
#ifndef AIRCRAFT_SHOOTER_ENTITY_HPP
#define AIRCRAFT_SHOOTER_ENTITY_HPP
#include "SFML/Graphics.hpp"
#include "SceneNode.hpp"
//////////////////////////////////////////////
/// \brief Denotes a game element in the world
///
//////////////////////////////////////////////
class Entity : public SceneNode{
public:
//////////////////////////////////////
/// \brief Sets the Entity's velocity
///
/// \param Vector2f velocity
///
//////////////////////////////////////
void setVelocity(sf::Vector2f velocity);
//////////////////////////////////////
/// \brief Sets the Entity's velocity
///
/// \param float velocity x
/// \param float velocity y
///
//////////////////////////////////////
void setVelocity(float vx, float vy);
//////////////////////////////////////
/// \brief Gets the Entity's velocity
///
/// \return Vector2f velocity
///
//////////////////////////////////////
sf::Vector2f getVelocity() const;
void updateCurrent(sf:: Time deltaTime) override;
private:
sf::Vector2f m_velocity;
};
#endif //AIRCRAFT_SHOOTER_ENTITY_HPP
| 26.888889
| 68
| 0.415978
|
YuanSambo
|
10959e88987120a76ebf19fef8b6f93f24c8090b
| 2,839
|
cpp
|
C++
|
plugins/csp-lod-bodies/src/TileId.cpp
|
FellegaraR/cosmoscout-vr
|
e04e1ac9c531106693a965bb03d3064f3a6179c6
|
[
"BSL-1.0",
"Apache-2.0",
"MIT"
] | 302
|
2019-03-05T08:05:03.000Z
|
2022-03-16T22:35:21.000Z
|
plugins/csp-lod-bodies/src/TileId.cpp
|
Tubbz-alt/cosmoscout-vr
|
d9fe671857b1ca906febddb59175422fc083441a
|
[
"BSL-1.0",
"Apache-2.0",
"MIT"
] | 230
|
2019-07-30T13:26:09.000Z
|
2022-03-11T11:21:06.000Z
|
plugins/csp-lod-bodies/src/TileId.cpp
|
Tubbz-alt/cosmoscout-vr
|
d9fe671857b1ca906febddb59175422fc083441a
|
[
"BSL-1.0",
"Apache-2.0",
"MIT"
] | 24
|
2019-07-22T08:00:49.000Z
|
2022-01-25T10:55:17.000Z
|
////////////////////////////////////////////////////////////////////////////////////////////////////
// This file is part of CosmoScout VR //
// and may be used under the terms of the MIT license. See the LICENSE file for details. //
// Copyright: (c) 2019 German Aerospace Center (DLR) //
////////////////////////////////////////////////////////////////////////////////////////////////////
#include "TileId.hpp"
// This is required for the << operator with const char[] with some MSVC versions.
#include <sstream>
namespace csp::lodbodies {
////////////////////////////////////////////////////////////////////////////////////////////////////
TileId::TileId() = default;
////////////////////////////////////////////////////////////////////////////////////////////////////
TileId::TileId(int level, glm::int64 patchIdx)
: mPatchIdx(patchIdx)
, mLevel(level) {
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void TileId::reset() {
mPatchIdx = -1;
mLevel = -1;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
int TileId::level() const {
return mLevel;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void TileId::level(int level) {
mLevel = level;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
glm::int64 TileId::patchIdx() const {
return mPatchIdx;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void TileId::patchIdx(glm::int64 pi) {
mPatchIdx = pi;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
bool isValid(TileId const& tileId) {
return (tileId.level() >= 0 && tileId.patchIdx() >= 0);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
bool isSameLevel(TileId const& lhs, TileId const& rhs) {
return (lhs.level() == rhs.level());
}
////////////////////////////////////////////////////////////////////////////////////////////////////
bool operator==(TileId const& lhs, TileId const& rhs) {
return (lhs.level() == rhs.level() && lhs.patchIdx() == rhs.patchIdx());
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// Print Method (not in class)
std::ostream& operator<<(std::ostream& os, TileId const& tileId) {
os << "(" << tileId.level() << " - " << tileId.patchIdx() << ")";
return os;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
} // namespace csp::lodbodies
| 33.011628
| 100
| 0.295879
|
FellegaraR
|
10975d2fcaf9023f74f363c7ff3699d11c080ef7
| 732
|
hpp
|
C++
|
pythran/pythonic/numpy/isposinf.hpp
|
artas360/pythran
|
66dad52d52be71693043e9a7d7578cfb9cb3d1da
|
[
"BSD-3-Clause"
] | null | null | null |
pythran/pythonic/numpy/isposinf.hpp
|
artas360/pythran
|
66dad52d52be71693043e9a7d7578cfb9cb3d1da
|
[
"BSD-3-Clause"
] | null | null | null |
pythran/pythonic/numpy/isposinf.hpp
|
artas360/pythran
|
66dad52d52be71693043e9a7d7578cfb9cb3d1da
|
[
"BSD-3-Clause"
] | null | null | null |
#ifndef PYTHONIC_NUMPY_ISPOSINF_HPP
#define PYTHONIC_NUMPY_ISPOSINF_HPP
#include "pythonic/include/numpy/isposinf.hpp"
#include "pythonic/utils/proxy.hpp"
#include "pythonic/types/ndarray.hpp"
#include "pythonic/types/numexpr_to_ndarray.hpp"
#include "pythonic/utils/numpy_traits.hpp"
#include <nt2/include/functions/is_inf.hpp>
#include <nt2/include/functions/is_positive.hpp>
namespace pythonic
{
namespace numpy
{
namespace wrapper
{
template <class T>
bool isposinf(T const &t)
{
return nt2::is_inf(t) and nt2::is_positive(t);
}
}
#define NUMPY_NARY_FUNC_NAME isposinf
#define NUMPY_NARY_FUNC_SYM wrapper::isposinf
#include "pythonic/types/numpy_nary_expr.hpp"
}
}
#endif
| 21.529412
| 54
| 0.743169
|
artas360
|
109b4686956a0e4baf7e56c896321f3ac93c5e8e
| 3,403
|
cpp
|
C++
|
cflib/net/net_test/http_test.cpp
|
fishbach/cflib
|
fa7a69c5962a73cf822435a67207ffc34badd0d4
|
[
"MIT"
] | null | null | null |
cflib/net/net_test/http_test.cpp
|
fishbach/cflib
|
fa7a69c5962a73cf822435a67207ffc34badd0d4
|
[
"MIT"
] | null | null | null |
cflib/net/net_test/http_test.cpp
|
fishbach/cflib
|
fa7a69c5962a73cf822435a67207ffc34badd0d4
|
[
"MIT"
] | null | null | null |
/* Copyright (C) 2013-2022 Christian Fischbach <cf@cflib.de>
*
* This file is part of cflib.
*
* Licensed under the MIT License.
*/
#include <cflib/net/httpclient.h>
#include <cflib/net/httpserver.h>
#include <cflib/net/request.h>
#include <cflib/net/requesthandler.h>
#include <cflib/net/tcpmanager.h>
#include <cflib/util/test.h>
using namespace cflib::net;
namespace {
QSemaphore msgSem;
QStringList msgs;
QMutex mutex;
void msg(const QString & msg)
{
QMutexLocker ml(&mutex);
msgs << msg;
msgSem.release();
}
class TestHdl : public RequestHandler
{
public:
TestHdl() : count_(0) {}
protected:
virtual void handleRequest(const Request & request)
{
msg("new request: " + request.getUri());
if (request.getUri() == "/abort") {
request.abort();
} else {
request.sendText(QString("reply %1").arg(++count_));
}
}
private:
uint count_;
};
class TestClient : public HttpClient
{
public:
TestClient(TCPManager & mgr, bool keepAlive) : HttpClient(mgr, keepAlive) {}
protected:
virtual void reply(const QByteArray & raw)
{
QByteArray r = raw;
r.replace("\r\n" , "|");
msg("http reply: " + r);
}
};
}
class HTTP_Test: public QObject
{
Q_OBJECT
private slots:
void test_keepAlive()
{
TestHdl hdl;
HttpServer server;
server.registerHandler(hdl);
server.start("127.0.0.1", 12301);
TCPManager mgr;
TestClient cli(mgr, true);
cli.get("127.0.0.1", 12301, "/test1");
msgSem.acquire(2);
QCOMPARE(msgs.size(), 2);
QVERIFY(msgs.contains("new request: /test1"));
QVERIFY(!msgs.filter(QRegularExpression(
"http reply: HTTP/1.1 200 OK\\|"
"Date: .*\\|"
"Server: cflib/.*\\|"
"Connection: keep-alive\\|"
"Content-Type: text/html; charset=utf-8|Content-Length: 7||reply 1"
)).isEmpty());
msgs.clear();
cli.get("127.0.0.1", 12301, "/test2");
msgSem.acquire(2);
QCOMPARE(msgs.size(), 2);
QVERIFY(msgs.contains("new request: /test2"));
QVERIFY(!msgs.filter(QRegularExpression(
"http reply: HTTP/1.1 200 OK\\|"
"Date: .*\\|"
"Server: cflib/.*\\|"
"Connection: keep-alive\\|"
"Content-Type: text/html; charset=utf-8|Content-Length: 7||reply 2"
)).isEmpty());
msgs.clear();
cli.get("127.0.0.1", 12301, "/abort");
msgSem.acquire(2);
QCOMPARE(msgs.size(), 2);
QVERIFY(msgs.contains("new request: /abort"));
QVERIFY(msgs.contains("http reply: "));
msgs.clear();
}
void test_immediateClose()
{
TestHdl hdl;
HttpServer server;
server.registerHandler(hdl);
server.start("127.0.0.1", 12301);
TCPManager mgr;
TestClient cli(mgr, false);
cli.get("127.0.0.1", 12301, "/test1");
msgSem.acquire(2);
QCOMPARE(msgs.size(), 2);
QVERIFY(msgs.contains("new request: /test1"));
QVERIFY(!msgs.filter(QRegularExpression(
"http reply: HTTP/1.1 200 OK\\|"
"Date: .*\\|"
"Server: cflib/.*\\|"
"Connection: keep-alive\\|"
"Content-Type: text/html; charset=utf-8|Content-Length: 7||reply 1"
)).isEmpty());
msgs.clear();
cli.get("127.0.0.1", 12301, "/test2");
msgSem.acquire(2);
QCOMPARE(msgs.size(), 2);
QVERIFY(msgs.contains("new request: /test2"));
QVERIFY(!msgs.filter(QRegularExpression(
"http reply: HTTP/1.1 200 OK\\|"
"Date: .*\\|"
"Server: cflib/.*\\|"
"Connection: keep-alive\\|"
"Content-Type: text/html; charset=utf-8|Content-Length: 7||reply 2"
)).isEmpty());
msgs.clear();
}
};
#include "http_test.moc"
ADD_TEST(HTTP_Test)
| 21.675159
| 78
| 0.646488
|
fishbach
|
109dba915e4b8c33ae40cebc952c33cd696ec37d
| 1,310
|
cpp
|
C++
|
src/tools/tools_func/coredump.cpp
|
JaysonSirius/learning_platform_server
|
30dc08c54af5e6b04f8392d4d5da54b5497358e9
|
[
"MIT"
] | null | null | null |
src/tools/tools_func/coredump.cpp
|
JaysonSirius/learning_platform_server
|
30dc08c54af5e6b04f8392d4d5da54b5497358e9
|
[
"MIT"
] | null | null | null |
src/tools/tools_func/coredump.cpp
|
JaysonSirius/learning_platform_server
|
30dc08c54af5e6b04f8392d4d5da54b5497358e9
|
[
"MIT"
] | null | null | null |
/**
* @file coredump.cpp
* @author 余王亮 (wotsen@outlook.com)
* @brief
* @version 0.1
* @date 2019-11-04
*
* @copyright Copyright (c) 2019
*
*/
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/resource.h>
#include "coredump.h"
static const char * const core_format = "core-%e-%p-%t";
/**
* @brief Set the up coredump object
*
* @param path_dir : coredump生成路径
* @param core_size : 文件大小
* @return true : 设置成功
* @return false : 设置失败
*/
bool setup_coredump(const char *path_dir, size_t core_size)
{
struct rlimit rlmt;
char core_path[1024];
if (NULL == path_dir) return false;
if (getrlimit(RLIMIT_CORE, &rlmt) < 0)
{
return false;
}
rlmt.rlim_cur = (rlim_t)core_size;
rlmt.rlim_max = (rlim_t)core_size;
if (setrlimit(RLIMIT_CORE, &rlmt) < 0)
{
return false;
}
if (path_dir[strlen(path_dir) - 1] != '/')
{
sprintf(core_path, "echo %s/%s > /proc/sys/kernel/core_pattern", path_dir, core_format);
}
else
{
sprintf(core_path, "echo %s%s > /proc/sys/kernel/core_pattern", path_dir, core_format);
}
sprintf(core_path, "echo %s/%s > /proc/sys/kernel/core_pattern", path_dir, core_format);
system(core_path);
system("echo 1 > /proc/sys/kernel/core_uses_pid");
return true;
}
| 20.46875
| 90
| 0.654962
|
JaysonSirius
|
10a3edcc9eac67bd11a34b3db407bee33d9c789c
| 2,776
|
cpp
|
C++
|
src/public/dt_shared.cpp
|
cstom4994/SourceEngineRebuild
|
edfd7f8ce8af13e9d23586318350319a2e193c08
|
[
"MIT"
] | 6
|
2022-01-23T09:40:33.000Z
|
2022-03-20T20:53:25.000Z
|
src/public/dt_shared.cpp
|
cstom4994/SourceEngineRebuild
|
edfd7f8ce8af13e9d23586318350319a2e193c08
|
[
"MIT"
] | null | null | null |
src/public/dt_shared.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 "dt_shared.h"
#if !defined (CLIENT_DLL)
#include "sendproxy.h"
#else
#include "recvproxy.h"
#endif
// ------------------------------------------------------------------------ //
// Just wrappers to make shared code look easier...
// ------------------------------------------------------------------------ //
// Use these functions to setup your data tables.
DataTableProp PropFloat(
char *pVarName, // Variable name.
int offset, // Offset into container structure.
int sizeofVar,
int nBits, // Number of bits to use when encoding.
int flags,
float fLowValue, // For floating point, low and high values.
float fHighValue // High value. If HIGH_DEFAULT, it's (1<<nBits).
)
{
#if !defined (CLIENT_DLL)
return SendPropFloat( pVarName, offset, sizeofVar, nBits, flags, fLowValue, fHighValue );
#else
return RecvPropFloat( pVarName, offset, sizeofVar, flags );
#endif
}
DataTableProp PropVector(
char *pVarName,
int offset,
int sizeofVar,
int nBits, // Number of bits (for each floating-point component) to use when encoding.
int flags,
float fLowValue, // For floating point, low and high values.
float fHighValue // High value. If HIGH_DEFAULT, it's (1<<nBits).
)
{
#if !defined (CLIENT_DLL)
return SendPropVector( pVarName, offset, sizeofVar, nBits, flags, fLowValue, fHighValue );
#else
return RecvPropVector( pVarName, offset, sizeofVar, flags );
#endif
}
DataTableProp PropAngle(
char *pVarName,
int offset,
int sizeofVar,
int nBits,
int flags
)
{
#if !defined (CLIENT_DLL)
return SendPropAngle( pVarName, offset, sizeofVar, nBits, flags );
#else
return RecvPropFloat( pVarName, offset, sizeofVar, flags );
#endif
}
DataTableProp PropInt(
char *pVarName,
int offset,
int sizeofVar, // Handled by SENDINFO macro.
int nBits, // Set to -1 to automatically pick (max) number of bits based on size of element.
int flags,
int rightShift
)
{
#if !defined (CLIENT_DLL)
return SendPropInt( pVarName, offset, sizeofVar, nBits, flags, rightShift );
#else
return RecvPropInt( pVarName, offset, sizeofVar, flags );
#endif
}
DataTableProp PropString(
char *pVarName,
int offset,
int bufferLen,
int flags
)
{
#if !defined (CLIENT_DLL)
return SendPropString( pVarName, offset, bufferLen, flags );
#else
return RecvPropString( pVarName, offset, bufferLen, flags );
#endif
}
DataTableProp PropEHandle(
char *pVarName,
int offset,
int sizeofVar )
{
#if !defined (CLIENT_DLL)
return SendPropEHandle( pVarName, offset, sizeofVar );
#else
return RecvPropEHandle( pVarName, offset, sizeofVar );
#endif
}
| 24.350877
| 97
| 0.65562
|
cstom4994
|
10a56f4118a157c8b6e4a2e692e1d9ca02ed8fa5
| 2,014
|
cpp
|
C++
|
vehicle/src/udp_trans/udp_client_main.cpp
|
Alvintang6/robot_formation
|
44017e939cede6bc3e964732511a53eba50544da
|
[
"MIT"
] | 11
|
2018-10-28T17:51:58.000Z
|
2022-03-02T22:46:35.000Z
|
vehicle/src/udp_trans/udp_client_main.cpp
|
Alvintang6/robot_formation
|
44017e939cede6bc3e964732511a53eba50544da
|
[
"MIT"
] | null | null | null |
vehicle/src/udp_trans/udp_client_main.cpp
|
Alvintang6/robot_formation
|
44017e939cede6bc3e964732511a53eba50544da
|
[
"MIT"
] | null | null | null |
////////////////////////////////////////////////////////
//
// This is a udp_client node for subscribe the loacl topics and than
// send it to the internet. the ip address and the port num should be
// configured.
// Author: JieTang date: 29/08/2018
//
////////////////////////////////////////////////////////
#include "udp_client.h"
int main(int argc, char **argv)
{
ros::init(argc, argv, "multi_udpclt");
ros::NodeHandle nh;
Udp_com obj;
// import the ip configure from the launch file
std::string bot1_ip,bot2_ip,bot3_ip,bot4_ip,laptop_ip;
ros::param::get("/robot1_ip",bot1_ip);
ros::param::get("/robot2_ip",bot2_ip);
ros::param::get("/robot3_ip",bot3_ip);
ros::param::get("/robot4_ip",bot4_ip);
ros::param::get("/laptop_ip",laptop_ip);
ip_list ip; // initial the ip struct for futher use
strcpy(ip.robot1,bot1_ip.c_str());
strcpy(ip.robot2,bot2_ip.c_str());
strcpy(ip.robot3,bot3_ip.c_str());
strcpy(ip.robot4,bot4_ip.c_str());
strcpy(ip.laptop,laptop_ip.c_str());
int fd=socket(AF_INET,SOCK_DGRAM,0);
if(fd==-1)
{
perror("socket create error!\n");
exit(-1);
}
printf("socket fd=%d\n",fd);
struct sockaddr_in addr_from;
addr_from.sin_family=AF_INET;
addr_from.sin_port=htons(0); // get arbitrary port
addr_from.sin_addr.s_addr=htons(INADDR_ANY); // get the host ip
//const int opt=1;
//int nb = 0;
//nb=setsockopt(fd,SOL_SOCKET,SO_BROADCAST,(char*)&opt,sizeof(opt));
//if(nb==-1)
//{
//printf("set socket error \n");
//exit(-1);
//}
int r;
r=bind(fd,(struct sockaddr*)&addr_from,sizeof(addr_from));
if(r<0)
{
perror("bind error! \n");
exit(-1);
}
struct sockaddr_in addr_to;//
addr_to.sin_family=AF_INET;
addr_to.sin_port=htons(10278);
addr_to.sin_addr.s_addr=inet_addr(ip.robot1); // unicast
//addr_to.sin_addr.s_addr=htonl(INADDR_BROADCAST); //broadcast
ros::Rate rate(20);
while(ros::ok())
{
obj.send_udp(fd,addr_to,ip);
rate.sleep();
ros::spinOnce();
}
}
//need function send_udp , callback for imu
| 19.940594
| 71
| 0.64002
|
Alvintang6
|
10b12d131d101ddc6f75f76f326892a784392a48
| 1,550
|
cpp
|
C++
|
Dimik OJ/Array Jot.cpp
|
Sohelr360/my_codes
|
9bdd28f62d3850aad8f8af2a253ba66138a7057c
|
[
"MIT"
] | null | null | null |
Dimik OJ/Array Jot.cpp
|
Sohelr360/my_codes
|
9bdd28f62d3850aad8f8af2a253ba66138a7057c
|
[
"MIT"
] | null | null | null |
Dimik OJ/Array Jot.cpp
|
Sohelr360/my_codes
|
9bdd28f62d3850aad8f8af2a253ba66138a7057c
|
[
"MIT"
] | null | null | null |
/**
* Author: Sohel Rana
* Date: 2020-10-23 09:55:34
* Link: link
**/
#include <bits/stdc++.h>
#define endl '\n'
#define db double
#define ld long double
#define ll long long
#define ull unsigned long long
#define sqr(x) (x) * (x)
#define gcd(a, b) __gcd(a, b)
#define lcm(a, b) ((a / gcd(a, b)) * b)
#define pf(x) push_front(x)
#define pb(x) push_back(x)
#define eb(x) emplace_back(x)
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define sz(x) (int)x.size()
#define debug(x) cerr << #x << " = " << (x) << endl
#define debug2(x, y) cerr << #x << " = " << (x) << "," << #y << " = " << (y) << endl
#define unsyncIO \
ios_base::sync_with_stdio(0); \
cin.tie(0); \
cout.tie(0)
const ld PI = acos((ld)-1);
const int MOD = 1e9 + 7;
const ll INF = 1e18;
using namespace std;
int main() {
//freopen("in.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
//unsyncIO;
int t;
cin >> t;
while (t--) {
vector<int> sorted;
int n1, n2;
cin >> n1;
for (int i = 0; i < n1; i++) {
int temp;
cin >> temp;
sorted.eb(temp);
}
cin >> n2;
for (int i = 0; i < n2; i++) {
int temp;
cin >> temp;
sorted.eb(temp);
}
sort(all(sorted));
cout << sorted[0];
for (int i = 1; i < sz(sorted); i++) {
cout << " " << sorted[i];
}
cout << endl;
}
return 0;
}
| 23.134328
| 84
| 0.461935
|
Sohelr360
|
10b22b40b4b806576d1ba29f4e6f47e5100d9f43
| 931
|
hpp
|
C++
|
engine/src/ui/DirectionalLayout.hpp
|
Birdy2014/Birdy3d
|
96421f262ab6ba7448cae8381063aab32ac830fe
|
[
"MIT"
] | 1
|
2021-11-01T20:22:41.000Z
|
2021-11-01T20:22:41.000Z
|
engine/src/ui/DirectionalLayout.hpp
|
Birdy2014/Birdy3d
|
96421f262ab6ba7448cae8381063aab32ac830fe
|
[
"MIT"
] | 1
|
2021-11-02T12:45:20.000Z
|
2021-11-02T12:45:20.000Z
|
engine/src/ui/DirectionalLayout.hpp
|
Birdy2014/Birdy3d
|
96421f262ab6ba7448cae8381063aab32ac830fe
|
[
"MIT"
] | 1
|
2021-11-02T12:28:58.000Z
|
2021-11-02T12:28:58.000Z
|
#pragma once
#include "ui/Layout.hpp"
namespace Birdy3d::ui {
class DirectionalLayout : public Layout {
public:
enum class Direction {
RIGHT,
LEFT,
DOWN,
UP
};
Direction dir;
float gap;
bool preserve_child_size;
DirectionalLayout() = delete;
DirectionalLayout(Direction dir, float gap = 0, bool preserve_child_size = false);
void arrange(const std::list<std::shared_ptr<Widget>>& children, glm::vec2 pos, glm::vec2 size) const override;
glm::vec2 minimal_size(const std::list<std::shared_ptr<Widget>>& children) const override;
private:
void arrange_full_size(const std::list<std::shared_ptr<Widget>>& children, glm::vec2 pos, glm::vec2 size) const;
void arrange_preserve_size(const std::list<std::shared_ptr<Widget>>& children, glm::vec2 pos, glm::vec2 size) const;
};
}
| 30.032258
| 124
| 0.632653
|
Birdy2014
|
10b49ca41a7e4de7d320afa83ee46808c8b3b6f0
| 284
|
cpp
|
C++
|
Source/BYGTextToSpeech/Private/BYGTextToSpeechSettings.cpp
|
BraceYourselfGames/UE-BYGTextToSpeech
|
a34abfb53c05c8b59706a8507bd49b6aabbd0f7c
|
[
"BSD-3-Clause"
] | 1
|
2022-03-21T15:37:29.000Z
|
2022-03-21T15:37:29.000Z
|
Source/BYGTextToSpeech/Private/BYGTextToSpeechSettings.cpp
|
BraceYourselfGames/UE-BYGTextToSpeech
|
a34abfb53c05c8b59706a8507bd49b6aabbd0f7c
|
[
"BSD-3-Clause"
] | null | null | null |
Source/BYGTextToSpeech/Private/BYGTextToSpeechSettings.cpp
|
BraceYourselfGames/UE-BYGTextToSpeech
|
a34abfb53c05c8b59706a8507bd49b6aabbd0f7c
|
[
"BSD-3-Clause"
] | null | null | null |
// Copyright 2017-2021 Brace Yourself Games. All Rights Reserved.
#include "BYGTextToSpeechSettings.h"
UBYGTextToSpeechSettings::UBYGTextToSpeechSettings( const FObjectInitializer& ObjectInitializer )
{
TextSplitDelimiters = {
TEXT( "." ),
TEXT( "\r\n" ),
TEXT( "\n" )
};
}
| 21.846154
| 97
| 0.721831
|
BraceYourselfGames
|
10c01195375074ef2a0404288f0413d48492d8b0
| 1,387
|
cpp
|
C++
|
day17.cpp
|
anshd258/100days-of-code
|
512d3c30f64aad0621bc64a337e4fcffce567265
|
[
"MIT"
] | 4
|
2020-11-13T12:27:52.000Z
|
2021-12-25T18:36:14.000Z
|
day17.cpp
|
anshd258/100days-of-code
|
512d3c30f64aad0621bc64a337e4fcffce567265
|
[
"MIT"
] | 3
|
2020-11-27T11:15:08.000Z
|
2020-12-14T03:38:58.000Z
|
day17.cpp
|
anshd258/100days-of-code
|
512d3c30f64aad0621bc64a337e4fcffce567265
|
[
"MIT"
] | null | null | null |
// day 16 solution of 100 -days - of -codding cpp
//jamal erabaki
//control git end
#include <iostream>
using namespace std;
int ap(int a,int b)
{
if(a==0)
//main recrussion function
return b;
return ap(b%a,a);
}
/*here it takes for ex 42%56,56 which will result in 42,56
then agin function is called this time a is 42 and b is56 which ressult in 0,42 so 42 will be returned*/
int main()
{
int result,n;
int *arr = new(nothrow) int[n];
//allocated array in heap
if(!arr)
{
cout<<"memory allocation failed"<<endl;
system("pause");
exit(0);
}
//exit the program if program is unable to allocate memory
else
{
cout<<"enter the nof of elements you want to enter \n";
cin>>n;
cout<<"enter the elements\n";
for(int j=0;j<n;j++)
{
cin>>arr[j];
}
//takin array elements
result=arr[0];
for (int i = 1; i < n; i++)
{
result=ap(arr[i],result);
//result called our recrussion function
}
}
cout <<"result is" <<result<< endl;
//result output
delete[] arr;
system("pause");
//deleting allocated memory
return 0;
}
| 21.671875
| 105
| 0.495314
|
anshd258
|
10ce5b4e4ea51817ffa4e14d9741233ecd67cd0d
| 8,681
|
cc
|
C++
|
cxx/hex.cc
|
ross-alexander/lizards
|
7329e754b3d8622fc202bc480fc5422dafd62a5d
|
[
"Apache-2.0"
] | null | null | null |
cxx/hex.cc
|
ross-alexander/lizards
|
7329e754b3d8622fc202bc480fc5422dafd62a5d
|
[
"Apache-2.0"
] | null | null | null |
cxx/hex.cc
|
ross-alexander/lizards
|
7329e754b3d8622fc202bc480fc5422dafd62a5d
|
[
"Apache-2.0"
] | null | null | null |
#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <libxml/tree.h>
#include <libxml/xpath.h>
#include <libxml++/libxml++.h>
#include "lizards.h"
hex_t::hex_t(void)
{
owner = 0;
terrain = WATER;
// adjlist = new adjacent_t[DIRECTIONS];
#ifndef STL
flistlen = 0;
flist = 0;
#endif
title = 0;
};
hex_t::~hex_t(void)
{
// debug.log("~hex_t(%p %s)", this, title);
clear_features();
}
void hex_t::set(int x_p, int y_p)
{
xy.x = x_p;
xy.y = y_p;
};
hex_t* hex_t::adjacent(const char *dir)
{
int d = (int)dir_t(dir);
if (d < 0)
return NULL;
else
return adjacent(d);
}
hex_t& hex_t::operator=(hex_t& h)
{
owner = h.owner;
terrain = h.terrain;
// undisturbed = h.undisturbed;
xy = h.xy;
title = strdup(h.title);
// for (int i = 0; i < DIRECTIONS; i++)
// {
// adjlist[i].xy = h.adjlist[i].xy;
// adjlist[i].hex = NULL;
// }
#ifdef STL
for (unsigned i = 0; i < h.fv.size(); i++)
fv.push_back(h.fv[i]->clone());
#else
flistlen = h.flistlen;
flist = new feature_t*[flistlen];
for (int i = 0; i < flistlen; i++)
if (h.flist[i])
flist[i] = h.flist[i]->clone();
else
flist[i] = 0;
#endif
return *this;
}
hex_t* hex_t::adjacent(dir_t d)
{
if (!d.okay())
return NULL;
assert(map);
return (*map)(map->move(xy, d));
// assert(adjlist[(int)d].hex != NULL);
// return adjlist[(int)d].hex;
}
int hex_t::terrain_adjacent(Terrain t)
{
int j = 0;
for (int i = 0; i < DIRECTIONS; i++)
j += adjacent(i)->terrain == t ? 1 : 0;
return j;
}
#ifdef KeepAdjacent
void hex_t::set_adjacent(dir_t dir, hex_t *hex)
{
adjlist[dir].hex = hex;
adjlist[dir].xy = hex->xy;
}
#endif
int hex_t::num_features(void)
{
#ifdef STL
return fv.size();
#else
int i = 0;
for (int j = 0; j < flistlen; j++)
i += flist[j] ? 1 : 0;
return i;
#endif
}
feature_t* hex_t::feature(int i)
{
if (i < 0 || i >= num_features())
return 0;
return fv[i];
}
feature_t* hex_t::has_feature(feature_t* f)
{
#ifdef STL
for (unsigned int i = 0; i < fv.size(); i++)
if (fv[i] == f)
return fv[i];
#else
for (int i = 0; i < flistlen && flist[i]; i++)
if (flist[i] == f)
return flist[i];
#endif
return 0;
}
feature_t* hex_t::has_feature(Feature f)
{
#ifdef STL
for (unsigned int i = 0; i < fv.size(); i++)
if (fv[i]->type == f)
{
misc_t::dbg.log("Hex(%s) found %s", title, fv[i]->describe());
return fv[i];
}
#else
for (int i = 0; i < flistlen && flist[i]; i++)
if (flist[i]->type == f)
return flist[i];
#endif
return 0;
}
int hex_t::count_feature(Feature f)
{
int count = 0;
#ifdef STL
for (unsigned int i = 0; i < fv.size(); i++)
if (fv[i]->type == f)
count++;
#else
for (int i = 0; i < flistlen && flist[i]; i++)
if (flist[i]->type == f)
count++;
#endif
return count;
}
int hex_t::count_feature(Feature f, int owner)
{
int count = 0;
#ifdef STL
for (unsigned int i = 0; i < fv.size(); i++)
if (fv[i]->type == f && fv[i]->owner == owner)
count++;
#else
for (int i = 0; i < flistlen && flist[i]; i++)
if (flist[i]->type == f && flist[i]->owner == owner)
count++;
#endif
return count;
}
int hex_t::feature_adjacent(Feature f)
{
int j = 0;
for (int i = NORTH; i <= NORTHWEST; i++)
if (adjacent(i)->has_feature(f))
j++;
return j;
}
feature_t* hex_t::add_feature(feature_t *f)
{
#ifdef STL
if (has_feature(f))
return f;
fv.push_back(f);
misc_t::dbg.log("Hex(%s) added %s", title, f->describe());
#else
int i;
for (i = 0; i < flistlen && flist[i]; i++)
{
if (flist[i] == f)
return f;
}
misc_t::dbg.log("add_feature(%d %s) i = %d, flistlen = %d", f->type, title, i, flistlen);
if (i == flistlen)
{
feature_t **tmp = new feature_t*[flistlen + 10];
for (int j = 0; j < flistlen; j++)
tmp[j] = flist[j];
for (int j = flistlen; j < flistlen + 10; j++)
tmp[j] = 0;
delete flist;
flist = tmp;
flistlen += 10;
}
flist[i] = f;
#endif
return f;
}
feature_t* hex_t::del_feature(feature_t *f)
{
if (f == 0) return f;
#ifdef STL
std::vector<feature_t*>::iterator i;
for (i = fv.begin(); i != fv.end(); ++i)
{
if (*i == f)
{
fv.erase(i);
break;
}
}
#else
int i, j;
for (i = 0; i < flistlen && flist[i]; i++)
if (flist[i] == f)
break;
if (flist[i] != f)
return 0;
/* Shuffle all other features down one */
for (j = i; j < flistlen && flist[j]; j++)
flist[j] = flist[j+1];
flist[j+1] = NULL;
#endif
return f;
}
feature_t* hex_t::pop_feature()
{
#ifdef STL
feature_t *f = 0;
if (fv.size())
{
f = fv.back();
fv.pop_back();
}
return f;
#else
feature_t *f;
f = (flistlen && flist[0]) ? del_feature(flist[0]) : NULL;
return f;
#endif
}
void hex_t::clear_features()
{
#ifdef STL
misc_t::dbg.log("%s cleared", title);
for (unsigned int i = 0; i < fv.size(); i++)
delete fv[i];
fv.clear();
#else
for (int i = 0; i < flistlen && flist[i]; i++)
delete flist[i];
delete [] flist;
flist = 0;
flistlen = 0;
#endif
}
int hex_t::size()
{
int size;
band_t *band;
den_t *den;
size = ((den = (den_t*)has_feature(DEN))) ? den->pop : 0;
return size + ((band = (band_t*)has_feature(BAND)) ? band->size() : 0);
}
void hex_t::save_xml(xmlpp::Element *p)
{
xmlpp::Element *xn_hex = p->add_child_element("hex");
xn_hex->set_attribute("x", Glib::ustring::compose("%1", xy.x));
xn_hex->set_attribute("y", Glib::ustring::compose("%1", xy.y));
xn_hex->set_attribute("title", Glib::ustring::compose("%1", title));
xn_hex->set_attribute("terrain", Glib::ustring::compose("%1", terrain));
xn_hex->set_attribute("owner", Glib::ustring::compose("%1", owner));
#ifdef KeepAdjacent
for (int i = 0; i < DIRECTIONS; i++)
{
if (adjacent(i))
{
xmlpp::Element *xn_adj = xn_hex->add_child_element("adj");
xn_adj->set_attribute("d", Glib::ustring::compose("%1", i));
xn_adj->set_attribute("x", Glib::ustring::compose("%1", adjlist[i].xy.x));
xn_adj->set_attribute("y", Glib::ustring::compose("%1", adjlist[i].xy.y));
}
}
#endif
for (unsigned int i = 0; i < fv.size(); i++)
#ifdef STL
fv[i]->save_xml(xn_hex);
#else
for (int i = 0; i < flistlen && flist[i]; i++)
flist[i]->save_xml(xn_hex);
#endif
}
void hex_t::debug(FILE *stream)
{
fprintf(stream, "Hex(x=%d y=%d title=%s terrain=%d owner=%d)\n",
xy.x, xy.y, title, terrain, owner);
#ifdef STL
for (unsigned int i = 0; i < fv.size(); i++)
fv[i]->debug(stream);
#else
for (int i = 0; i < flistlen && flist[i]; i++)
flist[i]->debug(stream);
#endif
}
void hex_t::reload(xmlpp::Element *e, map_t *_map)
{
assert(e->get_attribute("title"));
assert(e->get_attribute("owner"));
assert(e->get_attribute("terrain"));
owner = strtol(e->get_attribute("owner")->get_value().data(), NULL, 10);
terrain = (Terrain)strtol(e->get_attribute("terrain")->get_value().data(), NULL, 10);
title = strdup(e->get_attribute("title")->get_value().data());
map = _map;
xmlpp::Node::NodeSet ns = e->find("./*");
for (unsigned int j = 0; j < ns.size(); j++)
{
xmlpp::Element *t = dynamic_cast<xmlpp::Element*>(ns[j]);
#ifdef KeepAdjacent
if (t->get_name() == "adj")
{
assert(t->get_attribute("d") != NULL);
assert(t->get_attribute("x") != NULL);
assert(t->get_attribute("y") != NULL);
int dir = strtol(t->get_attribute("d")->get_value().data(), NULL, 10);
int x = strtol(t->get_attribute("x")->get_value().data(), NULL, 10);
int y = strtol(t->get_attribute("y")->get_value().data(), NULL, 10);
adjlist[dir].hex = (*map)(x, y);
adjlist[dir].xy = point_t(x, y);
}
#endif
Glib::ustring name = t->get_name();
if (name == "den") add_feature(new den_t(t));
if (name == "band") add_feature(new band_t(t));
if (name == "fertile") add_feature(new fertile_t(t));
if (name == "ruin") add_feature(new ruin_t(t));
if (name == "temple") add_feature(new temple_t(t));
if (name == "cursed") add_feature(new cursed_t(t));
if (name == "whirlpool") add_feature(new whirlpool_t(t));
if (name == "volcano") add_feature(new volcano_t(t));
if (name == "peak") add_feature(new peak_t(t));
if (name == "swamp") add_feature(new swamp_t(t));
if (name == "scrub") add_feature(new scrub_t(t));
}
}
hex_t::operator char*()
{
return title;
}
void hex_t::remap(map_t* _map)
{
// for (int i = 0; i < DIRECTIONS; i++)
// adjlist[i].hex = map(adjlist[i].xy);
map = _map;
}
void hex_t::setmap(map_t *m)
{
map = m;
}
| 21.648379
| 91
| 0.570326
|
ross-alexander
|
10d07a0dcbb5aec4ac727656f1c8fda1dfbf79c7
| 1,312
|
cpp
|
C++
|
Arduino-master_2/Arduino-master/libraries/CountDown/CountDown.cpp
|
GHarduino/ArduinoOnlineTrainingClass
|
b039de3c79da0b8e87272aa911f03128798b7bf8
|
[
"MIT"
] | 11
|
2017-05-02T09:50:07.000Z
|
2022-01-10T16:06:38.000Z
|
Arduino-master_2/Arduino-master/libraries/CountDown/CountDown.cpp
|
GHarduino/ArduinoOnlineTrainingClass
|
b039de3c79da0b8e87272aa911f03128798b7bf8
|
[
"MIT"
] | null | null | null |
Arduino-master_2/Arduino-master/libraries/CountDown/CountDown.cpp
|
GHarduino/ArduinoOnlineTrainingClass
|
b039de3c79da0b8e87272aa911f03128798b7bf8
|
[
"MIT"
] | 2
|
2017-05-15T05:32:07.000Z
|
2017-05-23T16:30:20.000Z
|
//
// FILE: CountDown.cpp
// AUTHOR: Rob Tillaart
// VERSION: 0.1.00
// PURPOSE: CountDown library for Arduino
//
// The library is based upon millis() and therefore
// has the same restrictions as millis() has wrt overflow.
//
// HISTORY:
// 0.1.00 - 2015-10-27 initial version
//
// Released to the public domain
//
#include "CountDown.h"
CountDown::CountDown(const enum Resolution res)
{
setResolution(res);
stop();
}
void CountDown::setResolution(const enum Resolution res)
{
_res = res;
switch(_res)
{
case MICROS:
_gettime = micros;
break;
case SECONDS:
_gettime = seconds;
break;
case MILLIS:
default:
_gettime = millis;
break;
}
}
void CountDown::start(uint32_t ticks)
{
_state = CountDown::RUNNING;
_starttime = _gettime();
_ticks = ticks;
}
unsigned long CountDown::remaining()
{
calcRemaining();
return _remaining;
}
void CountDown::stop()
{
calcRemaining();
_state = CountDown::STOPPED;
}
void CountDown::calcRemaining()
{
if (_state == CountDown::RUNNING)
{
uint32_t t = _gettime() - _starttime;
_remaining = _ticks > t? _ticks - t: 0;
if (_remaining == 0)
{
_state = CountDown::STOPPED;
}
}
}
// END OF FILE
| 17.972603
| 58
| 0.605945
|
GHarduino
|
10d3415f0bf6dfb9b91bc9f696525bab635f0bac
| 1,366
|
cpp
|
C++
|
tblock/source/GameLogic/Render.cpp
|
maximbilan/T-Block
|
b2eb3701a2567590090947a3c3dfb4afe282695a
|
[
"MIT"
] | 1
|
2016-03-09T13:03:48.000Z
|
2016-03-09T13:03:48.000Z
|
tblock/source/GameLogic/Render.cpp
|
maximbilan/T-Block
|
b2eb3701a2567590090947a3c3dfb4afe282695a
|
[
"MIT"
] | null | null | null |
tblock/source/GameLogic/Render.cpp
|
maximbilan/T-Block
|
b2eb3701a2567590090947a3c3dfb4afe282695a
|
[
"MIT"
] | null | null | null |
#include "PlatformPrecomp.h"
#include "Render.h"
#include "Board.h"
#include "GUI/GUI_MainMenu.h"
#include "Defines/GameConstants.h"
Render::Render()
{
if( !m_surface.IsLoaded() )
{
char path[256];
sprintf( path, "%s%s", GetApp()->getResourceInstance()->getItem( GetApp()->getResolutionType(), RES_TYPE_ATLAS, RES_ID_NONE ).c_str(), s_textureUImenus );
m_surface.LoadFile( path );
}
}
Render::~Render()
{
}
void Render::DrawRectangle( const float pX1, const float pY1, const E_TYPE_COLOR color, const float scaleX, const float scaleY )
{
//m_surf[ color ].Blit( pX1, pY1 );
TextureImage* img = GetBaseApp()->getAtlasManager()->findImage( RES_TYPE_COLOR_ARRAY[ color ] );
float imgX = static_cast<float>( img->getX() );
float imgY = static_cast<float>( img->getY() );
float imgWidth = static_cast<float>( img->getWidth() );
float imgHeight = static_cast<float>( img->getHeight() );
rtRectf r( pX1, pY1, pX1 + imgWidth, pY1 + imgHeight );
r.Scale( ALIGNMENT_CENTER, CL_Vec2f( scaleX, scaleY ) );
rtRectf s( imgX, imgY, imgX + imgWidth , imgY + imgHeight );
s.Scale( ALIGNMENT_CENTER, CL_Vec2f( scaleX, scaleY ) );
m_surface.BlitEx( r, s );
}
void Render::RDrawLine( const float pX1, const float pY1, const float pX2, const float pY2 )
{
DrawLine( MAKE_RGBA( 0,255,0,100 ), pX1, pY1, pX2, pY2 );
}
| 31.767442
| 157
| 0.674231
|
maximbilan
|
10d9b0b871e2fb9e55ea17a6f14df7e05784e5da
| 906
|
cpp
|
C++
|
Codechef/Div2/Long_Challenge/APRIL21B/BOLT.cpp
|
Pankajcoder1/Competitive_programming
|
72ee0d41f3f72f43a5c2a232255eb84a04b14df9
|
[
"MIT"
] | null | null | null |
Codechef/Div2/Long_Challenge/APRIL21B/BOLT.cpp
|
Pankajcoder1/Competitive_programming
|
72ee0d41f3f72f43a5c2a232255eb84a04b14df9
|
[
"MIT"
] | null | null | null |
Codechef/Div2/Long_Challenge/APRIL21B/BOLT.cpp
|
Pankajcoder1/Competitive_programming
|
72ee0d41f3f72f43a5c2a232255eb84a04b14df9
|
[
"MIT"
] | 1
|
2020-10-02T04:51:22.000Z
|
2020-10-02T04:51:22.000Z
|
/*
written by Pankaj Kumar.
country:-INDIA
Institute: National Institute of Technology, Uttarakhand
*/
#include<bits/stdc++.h>
using namespace std;
long long solve()
{
double k1,k2,k3,v;
cin>>k1>>k2>>k3>>v;
cout<<setprecision(10)<<fixed;
cout.precision(2);
v=v*k1*k2*k3;
double req_time=100.0/v;
// cout<<"req_time is "<<req_time<<endl;
if(req_time>=double(9.575))
cout<<"NO"<<endl;
else
cout<<"YES"<<endl;
return 0;
}
int main()
{
// #ifndef ONLINEJUDGE
// freopen("input.txt","r",stdin);
// freopen("output.txt","w",stdout);
// #endif
long long test=1;
cin>>test;
// scanf("%lld",&test);
while(test--)
{
solve();
}
return 0;
}
/* stuff you should look before submission
* int overflow
* special test case (n=0||n=1||n=2)
* don't get stuck on one approach if you get wrong answer
*/
| 20.590909
| 60
| 0.582781
|
Pankajcoder1
|
10de4211acb431f392544838bd777d84390f3f0b
| 878
|
cpp
|
C++
|
poo/POO21/matrix.cpp
|
pganaclara/ufmg
|
2325803427a7b4d5d150574bfd80243274cab527
|
[
"MIT"
] | null | null | null |
poo/POO21/matrix.cpp
|
pganaclara/ufmg
|
2325803427a7b4d5d150574bfd80243274cab527
|
[
"MIT"
] | null | null | null |
poo/POO21/matrix.cpp
|
pganaclara/ufmg
|
2325803427a7b4d5d150574bfd80243274cab527
|
[
"MIT"
] | null | null | null |
#include "matrix.h"
Matrix::Matrix(){
nCols = 0;
nRows = 0;
m = 0;
}
Matrix::Matrix(int rows, int cols, double elem){
nCols = cols;
nRows = rows;
m = new double *[rows];
for (int i = 0; i < nRows; i++){
m[i]= new double [nCols];
for (int j = 0; j < nCols; j++) m[i][j]=elem;
}
}
Matrix::~Matrix() {
for(int i = 0; i < nRows; ++i) {
delete [] m[i];
}
delete []m;
}
int Matrix::getRows() const {
return nRows;
}
int Matrix::getCols() const {
return nCols;
}
Matrix Matrix::transpose() {
double elem = m[0][0];
Matrix nova_matriz = Matrix(nCols, nRows, elem);
return nova_matriz;
}
void Matrix::print() const {
for (int i = 0; i < nRows; i++){
for (int j = 0; j < nCols; j++){
std::cout << m[i][j] << " ";
}
std::cout << std::endl;
}
}
| 18.291667
| 52
| 0.48861
|
pganaclara
|
10e02f0f4d2b518187620dad4681f4ebae9c6bcb
| 2,409
|
cpp
|
C++
|
src/egl-client-wayland.cpp
|
ceyusa/WPEBackend-fdo
|
e4c578f23359dba4d5abbd14b108f59e1b0701c1
|
[
"BSD-2-Clause"
] | 16
|
2018-06-26T13:37:04.000Z
|
2022-03-11T14:08:22.000Z
|
src/egl-client-wayland.cpp
|
ceyusa/WPEBackend-fdo
|
e4c578f23359dba4d5abbd14b108f59e1b0701c1
|
[
"BSD-2-Clause"
] | 118
|
2018-03-07T11:01:45.000Z
|
2022-02-01T19:44:14.000Z
|
src/egl-client-wayland.cpp
|
ceyusa/WPEBackend-fdo
|
e4c578f23359dba4d5abbd14b108f59e1b0701c1
|
[
"BSD-2-Clause"
] | 16
|
2018-02-20T19:31:13.000Z
|
2021-02-23T21:10:57.000Z
|
/*
* Copyright (C) 2020 Igalia S.L.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <wayland-egl.h>
#include "egl-client-wayland.h"
#include "ws-client.h"
namespace WS {
namespace EGLClient {
BackendWayland::BackendWayland(BaseBackend& base)
: m_base(base)
{
}
BackendWayland::~BackendWayland() = default;
EGLNativeDisplayType BackendWayland::nativeDisplay() const
{
return m_base.display();
}
uint32_t BackendWayland::platform() const
{
return 0;
}
TargetWayland::TargetWayland(BaseTarget& base, uint32_t width, uint32_t height)
: m_base(base)
{
m_egl.window = wl_egl_window_create(base.surface(), width, height);
}
TargetWayland::~TargetWayland()
{
g_clear_pointer(&m_egl.window, wl_egl_window_destroy);
}
EGLNativeWindowType TargetWayland::nativeWindow() const
{
return m_egl.window;
}
void TargetWayland::resize(uint32_t width, uint32_t height)
{
wl_egl_window_resize(m_egl.window, width, height, 0, 0);
}
void TargetWayland::frameWillRender()
{
m_base.requestFrame();
}
void TargetWayland::frameRendered()
{
}
void TargetWayland::deinitialize()
{
}
} } // namespace WS::EGLClient
| 27.375
| 79
| 0.75301
|
ceyusa
|
10e174a1891644c6e05acfb6904f4e33c0edbbb0
| 1,961
|
hpp
|
C++
|
include/rasm2/control/trajectory_structures.hpp
|
ASM-Advised-Projects/rasm-software
|
e28a17f96f70d89a4939e40a64e9e2e6a5ed7674
|
[
"MIT"
] | 3
|
2019-10-31T15:04:35.000Z
|
2021-06-24T16:35:18.000Z
|
include/rasm2/control/trajectory_structures.hpp
|
ASM-Advised-Projects/rasm-software
|
e28a17f96f70d89a4939e40a64e9e2e6a5ed7674
|
[
"MIT"
] | null | null | null |
include/rasm2/control/trajectory_structures.hpp
|
ASM-Advised-Projects/rasm-software
|
e28a17f96f70d89a4939e40a64e9e2e6a5ed7674
|
[
"MIT"
] | 2
|
2019-02-26T20:41:15.000Z
|
2019-05-14T01:40:40.000Z
|
/**
*
*/
#ifndef RASM2_CONTROL_TRAJECTORY_STRUCTURES_HPP
#define RASM2_CONTROL_TRAJECTORY_STRUCTURES_HPP
#include <vector>
#include <map>
#include <functional>
/**
*
*/
class TrajectorySegment
{
private:
std::vector<double> times;
std::vector<double> positions;
std::function<double (int)> position_function;
public:
TrajectorySegment(const std::vector<double> ×, const std::vector<double> &positions)
{
this->times = times;
this->positions = positions;
}
TrajectorySegment(int start_time, int end_time, const std::function<double (int)> &time_to_pos)
{
times = std::vector<double>(2);
positions = std::vector<double>(2);
times[0] = (double)start_time;
times[1] = (double)end_time;
positions[0] = time_to_pos(start_time);
positions[1] = time_to_pos(end_time);
position_function = time_to_pos;
}
double position(int time_millis)
{
}
void set_time_scale(double factor)
{
}
int start_time()
{
return times[0];
}
int end_time()
{
return times.back();
}
};
/**
*
*/
class Trajectory1D
{
private:
std::vector<TrajectorySegment> segments;
public:
Trajectory1D()
{
}
void add_segment(TrajectorySegment segment)
{
segments.push_back(segment);
}
double position(int time_ms)
{
}
void set_time_scale(double factor)
{
}
int start_time()
{
return segments[0].start_time();
}
int end_time()
{
return segments.back().end_time();
}
};
/**
*
*/
class Trajectory6D
{
private:
std::map<Joint, Trajectory1D> trajectories;
public:
Trajectory6D()
{
}
void set_trajectory(Joint joint, Trajectory1D trajectory)
{
trajectories[joint] = trajectory;
}
double position(Joint joint, int time_millis)
{
}
void autoscale()
{
}
int start_time()
{
return trajectories[BASE].start_time();
}
int end_time()
{
return trajectories[BASE].start_time();
}
};
#endif
| 13.431507
| 97
| 0.653238
|
ASM-Advised-Projects
|
10e5012f586e23ad32ff55566f1793980129389b
| 2,662
|
cpp
|
C++
|
tests/test_conv1d.cpp
|
stdml/stdnn-ops
|
0e6132bd65319e318f918094e482482698482e9e
|
[
"MIT"
] | 3
|
2018-10-23T18:46:39.000Z
|
2019-06-24T00:46:10.000Z
|
tests/test_conv1d.cpp
|
stdml/stdnn-ops
|
0e6132bd65319e318f918094e482482698482e9e
|
[
"MIT"
] | 27
|
2018-11-10T14:19:16.000Z
|
2020-03-08T23:33:01.000Z
|
tests/test_conv1d.cpp
|
stdml/stdnn-ops
|
0e6132bd65319e318f918094e482482698482e9e
|
[
"MIT"
] | 1
|
2018-11-05T06:17:12.000Z
|
2018-11-05T06:17:12.000Z
|
#include <ttl/nn/bits/ops/impl/col2im1d.hpp>
#include <ttl/nn/bits/ops/impl/conv1d.hpp>
#include <ttl/nn/bits/ops/impl/im2col1d.hpp>
#include <ttl/nn/testing>
#include <ttl/experimental/show>
template <typename R>
void test_col2im1d(const int n, const int ksize = 1, const int stride = 1,
const int rate = 1)
{
ttl::nn::traits::linear_padding_trait<int> padding(1);
ttl::nn::ops::im2col1d upper(ksize, stride, rate, padding);
ttl::nn::ops::col2im1d lower(ksize, stride, rate, padding);
ttl::tensor<R, 1> x(n);
ttl::tensor<R, 1> x1(n);
ttl::tensor<R, 1> c(n);
const auto [m, _k] = upper(x.shape()).dims();
static_assert(sizeof(_k) > 0, ""); // unused
ttl::tensor<R, 2> x_upper(m, ksize);
const auto x_shape = lower(x_upper.shape());
ASSERT_EQ(x_shape, x.shape());
std::iota(x.data(), x.data_end(), 1);
upper(ref(x_upper), view(x)); // x -> x_upper
lower(ref(x1), view(x_upper)); // x_upper -> x1
std::map<R, int> counts;
for (auto i : ttl::range(x_upper.shape().size())) {
++counts[x_upper.data()[i]];
}
for (auto i : ttl::range(x.shape().size())) {
const R xi = x.data()[i];
ASSERT_EQ(xi * counts[xi], x1.data()[i]);
}
// std::cout << ttl::show(view(x));
// std::cout << ttl::show(view(x1));
// std::cout << ttl::show(view(x_upper));
}
TEST(conv1d_test, test_col2im1d)
{
test_col2im1d<int>(9, 3);
// test_col2im1d<int>(9, 3);
}
template <typename R>
void test_conv1d(const int n, const int ksize, const int stride = 1,
const int rate = 1)
{
ttl::nn::traits::linear_padding_trait<int> padding(1);
ttl::nn::ops::conv1d f(stride, rate, padding);
ttl::nn::ops::im2col1d upper(ksize, stride, rate, padding);
ttl::tensor<R, 1> x(n);
ttl::tensor<R, 1> y(ksize);
ttl::tensor<R, 2> x_upper(upper(x.shape()));
ttl::tensor<R, 1> z(f(x.shape(), y.shape()));
ttl::tensor<R, 1> z1(z.shape());
std::iota(x.data(), x.data_end(), 1);
std::iota(y.data(), y.data_end(), 1);
std::iota(z.data(), z.data_end(), 1);
f(ref(z), view(x), view(y));
upper(ref(x_upper), view(x));
using la = ttl::nn::engines::linag<ttl::nn::engines::builtin>;
la::mv(view(x_upper), view(y), ref(z1));
assert_bytes_eq(view(z), view(z1));
// std::cout << ttl::show(view(x));
// std::cout << ttl::show(view(y));
// std::cout << ttl::show(view(z));
// std::cout << ttl::show(view(x_upper));
// std::cout << std::endl;
}
TEST(conv1d_test, test_conv1d)
{
test_conv1d<int>(9, 3);
test_conv1d<int>(9, 3, 1, 2);
test_conv1d<int>(9, 3, 1, 3);
}
| 29.910112
| 74
| 0.579639
|
stdml
|
10e685ac1b1e881d975152a1b52cb827140e6c96
| 795
|
cpp
|
C++
|
C++ Primer/chapter-9/9.27.cpp
|
grasslog/github-blog
|
1e09025f068774659b4bc26b7f0ad4aa1a3fbd43
|
[
"MIT"
] | 1
|
2019-05-16T07:51:12.000Z
|
2019-05-16T07:51:12.000Z
|
C++ Primer/chapter-9/9.27.cpp
|
grasslog/github-blog
|
1e09025f068774659b4bc26b7f0ad4aa1a3fbd43
|
[
"MIT"
] | null | null | null |
C++ Primer/chapter-9/9.27.cpp
|
grasslog/github-blog
|
1e09025f068774659b4bc26b7f0ad4aa1a3fbd43
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
#include <forward_list>
using namespace std;
int main(int argc, char **argv)
{
int ia[] = {0, 1, 1, 2, 3, 5, 8, 13, 21, 55, 89};
forward_list<int> forward_list1(ia, ia+9);
forward_list<int>::iterator it1 = forward_list1.begin();
forward_list<int>::iterator it2 = forward_list1.before_begin();
while(it1 != forward_list1.end())
{
if((*it1)%2 == 1)
{
it1 = forward_list1.erase_after(it2);
}
else
{
it2 = it1;
++it1;
}
}
forward_list<int>::iterator it4 = forward_list1.begin();
for(it4; it4 != forward_list1.end(); ++it4)
{
cout << *it4 << " ";
}
return 0;
}
| 20.921053
| 67
| 0.54717
|
grasslog
|
10e8650fe8ef68bfbb745245a81a0f49829b167c
| 3,001
|
cpp
|
C++
|
src/providers/CIM_DiskDrive/CIM_DiskDrive_Provider.cpp
|
LegalizeAdulthood/cimple
|
5ec70784f2ee3e455a2258f82b07c0dacccb4093
|
[
"MIT"
] | 4
|
2015-12-16T06:43:14.000Z
|
2020-01-24T06:05:47.000Z
|
src/providers/CIM_DiskDrive/CIM_DiskDrive_Provider.cpp
|
LegalizeAdulthood/cimple
|
5ec70784f2ee3e455a2258f82b07c0dacccb4093
|
[
"MIT"
] | null | null | null |
src/providers/CIM_DiskDrive/CIM_DiskDrive_Provider.cpp
|
LegalizeAdulthood/cimple
|
5ec70784f2ee3e455a2258f82b07c0dacccb4093
|
[
"MIT"
] | null | null | null |
#include "CIM_DiskDrive_Provider.h"
CIMPLE_NAMESPACE_BEGIN
CIM_DiskDrive_Provider::CIM_DiskDrive_Provider()
{
}
CIM_DiskDrive_Provider::~CIM_DiskDrive_Provider()
{
}
Load_Status CIM_DiskDrive_Provider::load()
{
return LOAD_OK;
}
Unload_Status CIM_DiskDrive_Provider::unload()
{
return UNLOAD_OK;
}
Get_Instance_Status CIM_DiskDrive_Provider::get_instance(
const CIM_DiskDrive* model,
CIM_DiskDrive*& instance)
{
return GET_INSTANCE_UNSUPPORTED;
}
Enum_Instances_Status CIM_DiskDrive_Provider::enum_instances(
const CIM_DiskDrive* model,
Enum_Instances_Handler<CIM_DiskDrive>* handler)
{
return ENUM_INSTANCES_OK;
}
Create_Instance_Status CIM_DiskDrive_Provider::create_instance(
CIM_DiskDrive* instance)
{
return CREATE_INSTANCE_UNSUPPORTED;
}
Delete_Instance_Status CIM_DiskDrive_Provider::delete_instance(
const CIM_DiskDrive* instance)
{
return DELETE_INSTANCE_UNSUPPORTED;
}
Modify_Instance_Status CIM_DiskDrive_Provider::modify_instance(
const CIM_DiskDrive* model,
const CIM_DiskDrive* instance)
{
return MODIFY_INSTANCE_UNSUPPORTED;
}
Invoke_Method_Status CIM_DiskDrive_Provider::RequestStateChange(
const CIM_DiskDrive* self,
const Property<uint16>& RequestedState,
CIM_ConcreteJob*& Job,
const Property<Datetime>& TimeoutPeriod,
Property<uint32>& return_value)
{
return INVOKE_METHOD_UNSUPPORTED;
}
Invoke_Method_Status CIM_DiskDrive_Provider::SetPowerState(
const CIM_DiskDrive* self,
const Property<uint16>& PowerState,
const Property<Datetime>& Time,
Property<uint32>& return_value)
{
return INVOKE_METHOD_UNSUPPORTED;
}
Invoke_Method_Status CIM_DiskDrive_Provider::Reset(
const CIM_DiskDrive* self,
Property<uint32>& return_value)
{
return INVOKE_METHOD_UNSUPPORTED;
}
Invoke_Method_Status CIM_DiskDrive_Provider::EnableDevice(
const CIM_DiskDrive* self,
const Property<boolean>& Enabled,
Property<uint32>& return_value)
{
return INVOKE_METHOD_UNSUPPORTED;
}
Invoke_Method_Status CIM_DiskDrive_Provider::OnlineDevice(
const CIM_DiskDrive* self,
const Property<boolean>& Online,
Property<uint32>& return_value)
{
return INVOKE_METHOD_UNSUPPORTED;
}
Invoke_Method_Status CIM_DiskDrive_Provider::QuiesceDevice(
const CIM_DiskDrive* self,
const Property<boolean>& Quiesce,
Property<uint32>& return_value)
{
return INVOKE_METHOD_UNSUPPORTED;
}
Invoke_Method_Status CIM_DiskDrive_Provider::SaveProperties(
const CIM_DiskDrive* self,
Property<uint32>& return_value)
{
return INVOKE_METHOD_UNSUPPORTED;
}
Invoke_Method_Status CIM_DiskDrive_Provider::RestoreProperties(
const CIM_DiskDrive* self,
Property<uint32>& return_value)
{
return INVOKE_METHOD_UNSUPPORTED;
}
Invoke_Method_Status CIM_DiskDrive_Provider::LockMedia(
const CIM_DiskDrive* self,
const Property<boolean>& Lock,
Property<uint32>& return_value)
{
return INVOKE_METHOD_UNSUPPORTED;
}
CIMPLE_NAMESPACE_END
| 23.084615
| 64
| 0.784738
|
LegalizeAdulthood
|
10ebaf8f0371d9ab8cf9a5fc19805763e3b53d75
| 3,097
|
cpp
|
C++
|
impl/jamtemplate/common/tilemap/tile_layer.cpp
|
runvs/Alakajam14
|
28ad5839dae9d26782f22f7d18e2dff42f4c0d1f
|
[
"CC0-1.0"
] | null | null | null |
impl/jamtemplate/common/tilemap/tile_layer.cpp
|
runvs/Alakajam14
|
28ad5839dae9d26782f22f7d18e2dff42f4c0d1f
|
[
"CC0-1.0"
] | null | null | null |
impl/jamtemplate/common/tilemap/tile_layer.cpp
|
runvs/Alakajam14
|
28ad5839dae9d26782f22f7d18e2dff42f4c0d1f
|
[
"CC0-1.0"
] | null | null | null |
#include "tile_layer.hpp"
#include "conversions.hpp"
#include "drawable_helpers.hpp"
#include "shape.hpp"
#include <memory>
namespace jt {
namespace tilemap {
TileLayer::TileLayer(
std::vector<TileInfo> const& tileInfo, std::vector<std::shared_ptr<jt::Sprite>> tileSetSprites)
: m_tileSetSprites { tileSetSprites }
, m_tiles { tileInfo }
{
}
TileLayer::TileLayer(
std::tuple<std::vector<TileInfo> const&, std::vector<std::shared_ptr<jt::Sprite>>> mapInfo)
: TileLayer { std::get<0>(mapInfo), std::get<1>(mapInfo) }
{
}
bool TileLayer::isTileVisible(TileInfo const& tile) const
{
if (m_screenSizeHint.x == 0 && m_screenSizeHint.y == 0) {
return true;
}
jt::Vector2f const camOffset = getStaticCamOffset();
if (tile.position.x + camOffset.x + tile.size.x < 0) {
return false;
}
if (tile.position.y + camOffset.y + tile.size.y < 0) {
return false;
}
if (tile.position.x + camOffset.x >= this->m_screenSizeHint.x + tile.size.x) {
return false;
}
if (tile.position.y + camOffset.y >= this->m_screenSizeHint.y + tile.size.y) {
return false;
}
return true;
}
void TileLayer::doDraw(std::shared_ptr<jt::RenderTarget> const sptr) const
{
if (!sptr) {
return;
}
auto const posOffset = m_position + getShakeOffset() + getOffset();
for (auto const& tile : m_tiles) {
// optimization: don't draw tiles which are not visible in this frame
if (!isTileVisible(tile)) {
continue;
}
auto const pixelPosForTile = tile.position + posOffset;
auto const id = tile.id;
this->m_tileSetSprites.at(id)->setPosition(jt::Vector2f {
pixelPosForTile.x * this->m_scale.x, pixelPosForTile.y * this->m_scale.y });
this->m_tileSetSprites.at(id)->setScale(this->m_scale);
this->m_tileSetSprites.at(id)->update(0.0f);
this->m_tileSetSprites.at(id)->draw(sptr);
}
}
void TileLayer::doDrawFlash(std::shared_ptr<jt::RenderTarget> const /*sptr*/) const { }
void TileLayer::doDrawShadow(std::shared_ptr<jt::RenderTarget> const /*sptr*/) const { }
void TileLayer::doUpdate(float /*elapsed*/) { }
void TileLayer::setColor(jt::Color const& col)
{
for (auto& ts : m_tileSetSprites) {
ts->setColor(col);
}
m_color = col;
}
jt::Color TileLayer::getColor() const { return m_color; }
void TileLayer::setPosition(jt::Vector2f const& pos) { m_position = pos; }
jt::Vector2f TileLayer::getPosition() const { return m_position; }
jt::Rectf TileLayer::getGlobalBounds() const { return jt::Rectf {}; }
jt::Rectf TileLayer::getLocalBounds() const { return jt::Rectf {}; }
void TileLayer::setScale(jt::Vector2f const& scale) { m_scale = scale; }
jt::Vector2f TileLayer::getScale() const { return m_scale; }
void TileLayer::setOrigin(jt::Vector2f const& origin) { m_origin = origin; }
jt::Vector2f TileLayer::getOrigin() const { return m_origin; }
void TileLayer::doRotate(float /*rot*/) { }
bool TileLayer::isVisible() const { return true; }
} // namespace tilemap
} // namespace jt
| 30.97
| 99
| 0.658379
|
runvs
|
10f62f1ab4e775ba10d4203cbd11d5697d89c72c
| 1,727
|
cpp
|
C++
|
ALGORITHM/WEEK 6 DYNAMIC PROGRAMMING 2/3/placing_parentheses.cpp
|
Mohit-007/DSA-UCDS-COURSERA
|
f5826a6f393e3b69ed8cf1c47df4d7a319b2d1fd
|
[
"MIT"
] | null | null | null |
ALGORITHM/WEEK 6 DYNAMIC PROGRAMMING 2/3/placing_parentheses.cpp
|
Mohit-007/DSA-UCDS-COURSERA
|
f5826a6f393e3b69ed8cf1c47df4d7a319b2d1fd
|
[
"MIT"
] | null | null | null |
ALGORITHM/WEEK 6 DYNAMIC PROGRAMMING 2/3/placing_parentheses.cpp
|
Mohit-007/DSA-UCDS-COURSERA
|
f5826a6f393e3b69ed8cf1c47df4d7a319b2d1fd
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <cassert>
#include <string>
#include <vector>
#include <bits/stdc++.h>
#include <cstdlib>
using std::vector;
using std::string;
using std::max;
using std::min;
using namespace std;
long long eval(long long a, long long b, char op) {
if (op == '*') {
return a * b;
} else if (op == '+') {
return a + b;
} else if (op == '-') {
return a - b;
} else {
assert(0);
}
}
long long get_maximum_value(const string &exp)
{
//write your code here
int n = exp.size();
int operands = (n + 1) / 2;
long long mini[operands][operands];
long long maxi[operands][operands];
// memset(min, 0, sizeof(min)); // initialize to 0
// memset(max, 0, sizeof(max)); // initialize to 0
for(int i=0;i<operands;i++)
{
for(int j=0;j<operands;j++)
{
mini[i][j] = 0;
maxi[i][j] = 0;
}
}
for(int i=0;i<operands;i++)
{
mini[i][i] = strtoull(exp.substr(2 * i, 1));
maxi[i][i] = stol(exp.substr(2 * i, 1));
}
for(int s=0; s<operands-1;s++)
{
for(int i=0;i<operands-s-1;i++)
{
int j = i + s + 1;
long long min_value = LLONG_MAX;
long long max_value = LLONG_MIN;
for(int k=i;k<j;k++)
{
long long a = eval(mini[i][k], mini[k + 1][j], exp[2 * k + 1]);
long long b = eval(mini[i][k], maxi[k + 1][j], exp[2 * k + 1]);
long long c = eval(maxi[i][k], mini[k + 1][j], exp[2 * k + 1]);
long long d = eval(maxi[i][k], maxi[k + 1][j], exp[2 * k + 1]);
min_value = min(min_value, min(a, min(b, min(c, d))));
max_value = max(max_value, max(a, max(b, max(c, d))));
}
mini[i][j] = min_value;
maxi[i][j] = max_value;
}
}
return 0;
}
int main() {
string s;
std::cin >> s;
std::cout << get_maximum_value(s) << '\n';
}
| 20.317647
| 66
| 0.549508
|
Mohit-007
|
10f7760fece65fb3bc48e3fdf0099b45f678e670
| 628
|
cpp
|
C++
|
BIT Manipulation/CUPC/swaping.cpp
|
mushahadur/Home-Work
|
2e885bc4bfa1a14a86ec858d4e6316fac68c1da6
|
[
"Apache-2.0"
] | null | null | null |
BIT Manipulation/CUPC/swaping.cpp
|
mushahadur/Home-Work
|
2e885bc4bfa1a14a86ec858d4e6316fac68c1da6
|
[
"Apache-2.0"
] | null | null | null |
BIT Manipulation/CUPC/swaping.cpp
|
mushahadur/Home-Work
|
2e885bc4bfa1a14a86ec858d4e6316fac68c1da6
|
[
"Apache-2.0"
] | null | null | null |
#include<bits/stdc++.h>
using namespace std;
int main()
{
cout<<"Normal Swoaping "<<endl;
int num1,num2;
cin>>num1>>num2;
cout<<"Number1 = :"<<num1<<endl<<"Number2 = :"<<num2<<endl;
num1 = num1+num2;
num2=num1-num2;
num1=num1-num2;
cout<<"After Swoap "<<endl;
cout<<"Number1 = :"<<num1<<endl<<"Number2 = :"<<num2<<endl;
cout<<"Bitwaish Swoaping "<<endl;
int a,b;
cin>>a>>b;
cout<<"Number1 = :"<<a<<endl<<"Number2 = :"<<b<<endl;
a=(a^b);
b=(a^b);
a=(a^b);
cout<<"After Swoap "<<endl;
cout<<"Number1 = :"<<a<<endl<<"Number2 = :"<<b<<endl;
return 0;
}
| 22.428571
| 63
| 0.525478
|
mushahadur
|
10f911f83e849bde222afe4788744c1d27482882
| 899
|
cpp
|
C++
|
tests/core/gui/TextTests.cpp
|
Kubaaa96/IdleRomanEmpire
|
c41365babaccd309dd78e953a333b39d8045913a
|
[
"MIT"
] | null | null | null |
tests/core/gui/TextTests.cpp
|
Kubaaa96/IdleRomanEmpire
|
c41365babaccd309dd78e953a333b39d8045913a
|
[
"MIT"
] | 29
|
2020-10-21T07:34:55.000Z
|
2021-01-12T15:15:53.000Z
|
tests/core/gui/TextTests.cpp
|
Kubaaa96/IdleRomanEmpire
|
c41365babaccd309dd78e953a333b39d8045913a
|
[
"MIT"
] | 1
|
2020-10-19T19:30:40.000Z
|
2020-10-19T19:30:40.000Z
|
#include <catch2/catch.hpp>
#include "core/gui/Text.h"
TEST_CASE("[Text]")
{
ire::core::gui::Text text;
SECTION("HorizontalAlignment")
{
REQUIRE(text.getHorizontalAlign() == ire::core::gui::Text::HorizontalAlignment::Center);
text.setHorizontalAlign(ire::core::gui::Text::HorizontalAlignment::Left);
REQUIRE(text.getHorizontalAlign() == ire::core::gui::Text::HorizontalAlignment::Left);
}
SECTION("VerticalAlignment")
{
REQUIRE(text.getVerticalAlign() == ire::core::gui::Text::VerticalAlignment::Center);
text.setVerticalAlign(ire::core::gui::Text::VerticalAlignment::Bottom);
REQUIRE(text.getVerticalAlign() == ire::core::gui::Text::VerticalAlignment::Bottom);
}
SECTION("Visibilitty")
{
REQUIRE(text.isVisible() == false);
text.setVisible(true);
REQUIRE(text.isVisible() == true);
}
}
| 35.96
| 96
| 0.649611
|
Kubaaa96
|
10fbc59ffdda178d9bf3a7efefcc24f33d6eb079
| 1,360
|
cpp
|
C++
|
Libraries/MDStudio-SDK/Source/MDStudio/PortableCore/UI/imageview.cpp
|
dcliche/studioengine
|
1a18d373b26575b040d014ae2650a1aaeb208a89
|
[
"Apache-2.0"
] | null | null | null |
Libraries/MDStudio-SDK/Source/MDStudio/PortableCore/UI/imageview.cpp
|
dcliche/studioengine
|
1a18d373b26575b040d014ae2650a1aaeb208a89
|
[
"Apache-2.0"
] | null | null | null |
Libraries/MDStudio-SDK/Source/MDStudio/PortableCore/UI/imageview.cpp
|
dcliche/studioengine
|
1a18d373b26575b040d014ae2650a1aaeb208a89
|
[
"Apache-2.0"
] | null | null | null |
//
// imageview.cpp
// MDStudio
//
// Created by Daniel Cliche on 2014-07-15.
// Copyright (c) 2014-2020 Daniel Cliche. All rights reserved.
//
#include "imageview.h"
#include <math.h>
#include "draw.h"
using namespace MDStudio;
// ---------------------------------------------------------------------------------------------------------------------
ImageView::ImageView(const std::string& name, void* owner, std::shared_ptr<Image> image, bool isStretched)
: _image(image), _isStretched(isStretched), View(name, owner) {
_color = whiteColor;
}
// ---------------------------------------------------------------------------------------------------------------------
ImageView::~ImageView() {}
// ---------------------------------------------------------------------------------------------------------------------
void ImageView::draw() {
DrawContext* dc = drawContext();
if (_image) {
Rect r = _isStretched
? bounds()
: makeCenteredRectInRect(bounds(), floorf(_image->size().width), floorf(_image->size().height));
dc->drawImage(r, _image, _color);
}
}
// ---------------------------------------------------------------------------------------------------------------------
void ImageView::setImage(std::shared_ptr<Image> image) {
_image = image;
setDirty();
}
| 31.627907
| 120
| 0.408088
|
dcliche
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.